From a1368bd5716d17f31a96bdb3a2e44d1bde247b6e Mon Sep 17 00:00:00 2001 From: lyt Date: Thu, 14 Sep 2017 14:26:40 +0800 Subject: [PATCH 001/382] =?UTF-8?q?ipaylinks=E4=BF=9D=E5=AD=98=E4=BB=98?= =?UTF-8?q?=E6=AC=BE=E4=BA=BA=E8=81=94=E7=B3=BB=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 51 +++++++++++++++---- webht/third_party/pay/models/note_model.php | 10 ++-- 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index d4973ffc..bf8eb5ec 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -18,12 +18,13 @@ class IPayLinksService extends CI_Controller public function __construct(){ parent::__construct(); $this->config->load('iPayLinks'); + // $this->config->load('dev_iPayLinks'); // test $this->load->model('IPayLinks_model'); $this->load->model('Note_model'); - $this->gatewayUrl = $this->config->item('gatewayUrl'); + $this->gatewayUrl = $this->config->item('gatewayUrl'); - $this->queryUrl = $this->config->item('queryUrl'); + $this->queryUrl = $this->config->item('queryUrl'); $this->return_url = $this->config->item('returnUrl'); $this->notify_url = $this->config->item('noticeUrl'); @@ -89,7 +90,7 @@ class IPayLinksService extends CI_Controller public function get_url_string() { - $param = $this->input->get_post('param'); + $param = ($this->input->get_post('param')); return base64_decode($param); } @@ -191,6 +192,12 @@ class IPayLinksService extends CI_Controller $this->card_info_arr['cardExpirationYear'] = substr(trim($this->input->get_post('cardExpirationYear')),2,2); $this->card_info_arr['securityCode'] = trim(str_replace(" ","",$this->input->get_post('securityCode'))); $this->card_info_arr['cardHolderEmail'] = trim($this->input->get_post('cardHolderEmail')); + // 记录付款人联系信息 + $card_holder_arr = array( + "n" => substr($this->card_info_arr['cardHolderFirstName']." ".$this->card_info_arr['cardHolderLastName'],0,50), + "e" => substr($this->card_info_arr['cardHolderEmail'],0,50) + ); + $this->card_info_arr['remark'] = json_encode($card_holder_arr); } public function order_pay() @@ -209,8 +216,11 @@ class IPayLinksService extends CI_Controller return; } + // test + // $this->ipaylinks_notice($resp); + // 返回结果 - $ret = $this->result_2_return_url($respWellFormed->data->resultCode); + $ret = $this->result_2_return_url($respWellFormed->data->resultCode,$respWellFormed->data->resultMsg); $this->order_done($ret); return; @@ -384,8 +394,9 @@ class IPayLinksService extends CI_Controller mb_strtoupper($item->IPL_currencyCode), $item->IPL_completeTime, $item->IPL_completeTime, - $item->IPL_acquiringTime, '', - NULL, + $item->IPL_acquiringTime, + $item->IPL_payerName, + $item->IPL_payerEmail, $item->IPL_dealId, $ht_memo ); @@ -402,8 +413,9 @@ class IPayLinksService extends CI_Controller mb_strtoupper($item->IPL_currencyCode), $item->IPL_completeTime, $item->IPL_completeTime, - $item->IPL_acquiringTime, '', - NULL, + $item->IPL_acquiringTime, + $item->IPL_payerName, + $item->IPL_payerEmail, $item->IPL_dealId, $ht_memo ); @@ -438,7 +450,10 @@ class IPayLinksService extends CI_Controller $this->Note_model->update_send($item->IPL_dealId, 'send'); $int++; } - echo "done. recorde count:".$int; + // 批量结果 + if (empty($pn_txn_id)) { + echo "done. recorde count:".$int; + } return; } @@ -549,8 +564,14 @@ class IPayLinksService extends CI_Controller echo "200"; return; } + // dealId $dealId = trim($asyns_resp->data->dealId) ; $tmp_deal = $dealId ? $dealId : $this->create_guid(); + // payer info + $payer_info = json_decode($asyns_resp->data->remark); + $payer_name = $payer_info->n; + $payer_email = $payer_info->e; + bcscale(2); // 支付成功 // 查询支付结果;入库处理 @@ -568,6 +589,8 @@ class IPayLinksService extends CI_Controller ,strval("pay") ,strval($asyns_resp->data->resultCode) ,strval($asyns_resp->data->resultMsg) + ,strval($payer_name) + ,strval($payer_email) ); $query = $this->query_pay_result($asyns_resp->data); } @@ -754,11 +777,17 @@ class IPayLinksService extends CI_Controller * @param [type] $code [description] * @return [type] [description] */ - protected function result_2_return_url($code) + protected function result_2_return_url($code,$msg) { $ret['code'] = 0; $ret['msg'] = ""; $ret['error_code'] = $code ? $code : "Unknow"; + $ret["error_code"] .= "."; + + $tmp_msg = $msg ? strstr($msg,":",true)."." : false; // result msg的英文部分 + $code_msg = $tmp_msg ? $tmp_msg : "Please contact your advisor."; + $ret['error_code'] .= $code_msg; + switch ($code) { case '0000': $ret['code'] = 0; @@ -767,7 +796,7 @@ class IPayLinksService extends CI_Controller default: $ret['code'] = $code; - $ret['msg'] = "Payment Failed"; + $ret['msg'] = "Payment Failed."; break; } return $ret; diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index bc71c5d8..efe06ff0 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -89,15 +89,15 @@ class Note_model extends CI_Model { * @author LYT * @date 2017-08-29 */ - public function save_ipl($IPL_dealId,$IPL_orderId,$IPL_currencyCode,$IPL_orderAmount,$IPL_payAmount,$IPL_stateCode,$IPL_acquiringTime,$IPL_completeTime,$IPL_memo,$IPL_payType,$IPL_resultCode,$IPL_resultMsg) { + public function save_ipl($IPL_dealId,$IPL_orderId,$IPL_currencyCode,$IPL_orderAmount,$IPL_payAmount,$IPL_stateCode,$IPL_acquiringTime,$IPL_completeTime,$IPL_memo,$IPL_payType,$IPL_resultCode=null,$IPL_resultMsg=null,$IPL_payerName=null,$IPL_payerEmail=NULL) { $sql = " INSERT INTO IPayLinksLog ( - IPL_dealId,IPL_orderId,IPL_currencyCode,IPL_orderAmount,IPL_payAmount,IPL_stateCode,IPL_acquiringTime,IPL_completeTime,IPL_memo,IPL_sent,IPL_noticeTime,IPL_payType,IPL_resultCode,IPL_resultMsg + IPL_dealId,IPL_orderId,IPL_currencyCode,IPL_orderAmount,IPL_payAmount,IPL_stateCode,IPL_acquiringTime,IPL_completeTime,IPL_memo,IPL_sent,IPL_noticeTime,IPL_payType,IPL_resultCode,IPL_resultMsg,IPL_payerName,IPL_payerEmail ) VALUES ( - ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,N? + ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,N?,N?,N? ) "; $query = $this->INFO->query($sql, @@ -113,6 +113,8 @@ class Note_model extends CI_Model { ,$IPL_payType ,$IPL_resultCode ,$IPL_resultMsg + ,$IPL_payerName + ,$IPL_payerEmail )); $insertid = $this->INFO->last_id('IPayLinksLog'); return $query; @@ -136,6 +138,8 @@ class Note_model extends CI_Model { ,pn.IPL_sent ,pn.IPL_payType ,pn.IPL_noticeTime + ,pn.IPL_payerName + ,pn.IPL_payerEmail FROM IPayLinksLog pn WHERE 1=1 "; From feee5b0855c5fd270b777e14d36934ee42ad735b Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 15 Sep 2017 15:26:00 +0800 Subject: [PATCH 002/382] =?UTF-8?q?ipaylinks=20=E8=AE=A2=E5=8D=95=E5=A4=9A?= =?UTF-8?q?=E6=AC=A1=E6=94=AF=E4=BB=98=E6=97=B6=E6=9F=A5=E8=AF=A2bug,?= =?UTF-8?q?=E6=94=B9=E4=BD=BF=E7=94=A8resultCode=E4=BD=9C=E5=88=A4?= =?UTF-8?q?=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index bf8eb5ec..5d76b04e 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -257,6 +257,18 @@ class IPayLinksService extends CI_Controller return; } + public function query_pay($orderid) + { + $this->query_info_arr["queryOrderId"] = $this->create_guid(); + $this->query_info_arr["orderId"] = $orderid; + $this->query_info_arr["mode"] = 2; + + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); + $resp = $this->curl($this->queryUrl,$this->query_info_arr); + echo $resp; + return; + } + /*! * 订单业务处理 * * 查询写入交易记录 iPayLinks_log @@ -332,7 +344,7 @@ class IPayLinksService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->IPL_stateCode), "2")) { + if (strcmp(trim($item->IPL_resultCode), "0000")) { $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); continue; } From 8e589c8c46bd8b4b9305ab38337439d2239b3be8 Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 15 Sep 2017 15:39:03 +0800 Subject: [PATCH 003/382] =?UTF-8?q?ipaylinks=20=E6=94=B6=E6=AC=BE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E9=82=AE=E4=BB=B6=E5=A2=9E=E5=8A=A0=E4=BB=98=E6=AC=BE?= =?UTF-8?q?=E4=BA=BA=E8=81=94=E7=B3=BB=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/receipt_mail.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/views/receipt_mail.php b/webht/third_party/pay/views/receipt_mail.php index df4b36d3..fff3eed3 100644 --- a/webht/third_party/pay/views/receipt_mail.php +++ b/webht/third_party/pay/views/receipt_mail.php @@ -1 +1 @@ -
PayPal logo
Transaction ID:
Hello Guilin China International Travel Service Co.,Ltd,
You received a payment of
Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.
It may take a few moments for this transaction to appear in your account.
Seller Protection-
Description  Amount

+
PayPal logo
Transaction ID:
Hello Guilin China International Travel Service Co.,Ltd,
You received a payment of
Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.
It may take a few moments for this transaction to appear in your account.
Seller Protection-
Buyer


Description     Amount

From 99953e54775e14e0a62fcb68c41e782c7c6710ec Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 15 Sep 2017 15:47:52 +0800 Subject: [PATCH 004/382] =?UTF-8?q?ipaylinks=20=E5=A2=9E=E5=8A=A0=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E6=89=8B=E5=8A=A8=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 5d76b04e..3ddf7181 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -257,10 +257,12 @@ class IPayLinksService extends CI_Controller return; } - public function query_pay($orderid) + public function query_pay($orderid,$day_offset = 3) { $this->query_info_arr["queryOrderId"] = $this->create_guid(); $this->query_info_arr["orderId"] = $orderid; + $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); + $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); $this->query_info_arr["mode"] = 2; $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); From 2c333f8b21b08f438d116684bd75cbad37bf0923 Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 15 Sep 2017 16:20:58 +0800 Subject: [PATCH 005/382] =?UTF-8?q?ipaylinks=20notes=20list=20=E4=B8=BB?= =?UTF-8?q?=E9=A2=98=E7=94=A8orderAmount=20=E4=B8=BB=E9=A2=98=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E4=BB=98=E6=AC=BE=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/pay/views/iPayLinks_list.php | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 169678f9..ea19492c 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -90,12 +90,13 @@
    -
  • -
  • +
  • +
  • IPL_dealId) { ?> - IPL_orderId . ' / ' . $item->IPL_payAmount . $item->IPL_currencyCode; ?> + IPL_orderId . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode ; ?>
  • +
  • + IPL_payerName; ?>
    + IPL_payerEmail; ?> +
  • +
  • IPL_dealId; ?>
  • IPL_acquiringTime; ?>
  • IPL_noticeTime; ?>
  • -
  • +
  • Date: Tue, 19 Sep 2017 17:36:30 +0800 Subject: [PATCH 006/382] =?UTF-8?q?ipaylinks=20=E5=BC=82=E6=AD=A5=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E9=87=8D=E5=A4=8D,=E4=B8=8D=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 3ddf7181..46c9865b 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -586,6 +586,11 @@ class IPayLinksService extends CI_Controller $payer_name = $payer_info->n; $payer_email = $payer_info->e; + if (true === $this->if_note_exists($dealId)) { + echo "200"; + return; + } + bcscale(2); // 支付成功 // 查询支付结果;入库处理 From 9a14b97195e577ab892245619a7dc25f8ba2a94d Mon Sep 17 00:00:00 2001 From: lyt Date: Mon, 25 Sep 2017 16:44:33 +0800 Subject: [PATCH 007/382] =?UTF-8?q?ipaylinks=20=E4=BA=A4=E6=98=93=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5=E4=B8=8D=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 46c9865b..ea5c5e44 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -347,7 +347,7 @@ class IPayLinksService extends CI_Controller //只处理完成状态,其他状态由陆燕处理 if (strcmp(trim($item->IPL_resultCode), "0000")) { - $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); + $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } From 2e08bba8ea5fec8399a10c044bba8b163f486e21 Mon Sep 17 00:00:00 2001 From: lyt Date: Tue, 26 Sep 2017 17:16:33 +0800 Subject: [PATCH 008/382] =?UTF-8?q?alipay=20=E5=BC=82=E6=AD=A5,=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E9=87=8D=E5=AE=9A=E5=90=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/alipay_SOP.md | 42 +- webht/third_party/pay/config/alipay.php | 47 +- webht/third_party/pay/config/dev_alipay.php | 21 +- .../pay/controllers/AlipayTradeService.php | 456 +++++- .../pay/controllers/Mobile_Detect.php | 1459 +++++++++++++++++ .../pay/controllers/iPayLinksService.php | 4 + webht/third_party/pay/helpers/index.html | 10 + .../pay/helpers/payment_helper.php | 182 ++ .../AlipayTradeWapPayContentBuilder.php | 124 ++ webht/third_party/pay/models/Alipay_model.php | 277 ++++ .../pay/models/Alipay_note_model.php | 194 +++ 11 files changed, 2690 insertions(+), 126 deletions(-) create mode 100644 webht/third_party/pay/controllers/Mobile_Detect.php create mode 100644 webht/third_party/pay/helpers/index.html create mode 100644 webht/third_party/pay/helpers/payment_helper.php create mode 100644 webht/third_party/pay/models/AlipayTradeWapPayContentBuilder.php create mode 100644 webht/third_party/pay/models/Alipay_model.php create mode 100644 webht/third_party/pay/models/Alipay_note_model.php diff --git a/webht/third_party/pay/alipay_SOP.md b/webht/third_party/pay/alipay_SOP.md index ac61a948..6fa81806 100644 --- a/webht/third_party/pay/alipay_SOP.md +++ b/webht/third_party/pay/alipay_SOP.md @@ -1,20 +1,32 @@ -## Alipay 支付说明 ## -> update : 2017.08.28 LYT +## Alipay 国内支付宝支付说明 ## +> update : 2017.09.26 LYT + + 国内支付宝仅支持人民币支付 + #### 支付链接示例 #### -`https://www.chinahighlights.com/guide-use.php/apps/pay/AlipayTradeService/pay_fun?out_trade_no=20150320010101001&subject=Iphone6&total_amount=88.88&body=Iphone6&return_url=https://m.alipay.com/Gk8NF23¬ify_url=https://api.xx.com/receive_notify.htm` + +`https://www.chinahighlights.com/securealipay/?b3JkZXJfaWQ9MTUwNDE0NzIwMyZzdWJqZWN0PUlwaG9uZTYmdG90YWxfYW1vdW50PTAuMDEmYm9keT1UcmFja2luZyBDb2RlOjE1MDQxNDcyMDMgVHJhdmVsIEFkdmlzb3I6TGlseSBDb250ZW50OlBheSBmb3IgdG91cg` + +##### 链接说明 ##### + + 链接最后一段为base64加密后的订单数据字符串 + 如上示例链接的 + b3JkZXJfaWQ9MTUwNDE0NzIwMyZzdWJqZWN0PUlwaG9uZTYmdG90YWxfYW1vdW50PTAuMDEmYm9keT1UcmFja2luZyBDb2RlOjE1MDQxNDcyMDMgVHJhdmVsIEFkdmlzb3I6TGlseSBDb250ZW50OlBheSBmb3IgdG91cg + 加密前为: + order_id=1504147203&subject=Iphone6&total_amount=0.01&body=Tracking Code:1504147203 Travel Advisor:Lily Content:Pay for tour + ##### 参数说明 ##### -参数 | 类型 | 是否必填 | 最大长度 | 描述 | 示例值 + +参数 | 类型 | 是否必填 | 最大长度 | 描述 | 示例值 --- | --- | -- | ---- | --- | --- -out_trade_no| String| 是| 64| 商户订单号,64个字符以内、可包含字母、数字、下划线;需保证在商户端不重复 | 20150320010101001 -total_amount | Price | 是 | 11 | 订单总金额,单位为元,精确到小数点后两位,取值范围[0.01,100000000] | 88.88 +order_id| String| 是| 64| 商户订单号,64个字符以内、可包含字母、数字、下划线;
    需保证在商户端不重复 | 20150320010101001 +total_amount | Price | 是 | 11 | 订单总金额,单位为元,精确到小数点后两位 | 88.88 subject | String | 是 | 256 | 订单标题 | Iphone6 body | String | 否 | 128 | 订单描述 | Iphone6 -return_url | String | 否 | 256 | 同步返回地址,HTTP/HTTPS开头字符串 | https://m.alipay.com/Gk8NF23 -notify_url | String | 否 | 256 | 支付宝服务器主动通知商户服务器里指定的页面http/https路径。 | https://api.xx.com/receive_notify.htm - -#### 测试 #### -账号| ckdstw3726@sandbox.com ---|-- -登录密码|111111 -支付密码|111111 -余额|约1000 +return_url | String | 否 | 256 | 同步跳转地址,**HTTP/HTTPS开头**字符串
    默认为CH首页 | https://www.chinahighlights.com +notify_url | String | 否 | 256 | 支付宝服务器主动通知商户服务器里指定的页面**HTTP/HTTPS开头**的路径。 | https://api.xx.com/receive_notify.htm + +##### 支付选项logo +https://data.chinahighlights.com/pic/alipay_logo_228_80.png + +![支付图标地址](http://data.chinahighlights.com/pic/alipay_logo_228_80.png) diff --git a/webht/third_party/pay/config/alipay.php b/webht/third_party/pay/config/alipay.php index 84660806..ff795035 100644 --- a/webht/third_party/pay/config/alipay.php +++ b/webht/third_party/pay/config/alipay.php @@ -1,37 +1,12 @@ "2017080708076334", - - //商户私钥 - 'merchant_private_key' => "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDpDYXixYrQtmcKnHNd3dj0way+D0YTl7bvk44DcgeOOa3HAL/09UjPMDawmH8+/eEaJJHchWybFWfFMFWaEpnZ0UUPTi2jnOXPy84+eRvipx2GTUdIH95ZEUcqgG1rGVpOz97bOtVPaYTPuhrVRg1MCJccZHFxSiU+0mz98QCRxZPNNqdIxHKSimtBI1bB0pjGQtOXpODdyEaW8boQuuMHP9F052am1f2fZAQ3PeTpCQ80KCckcdg3MdbsnlFppy4m6o8uhFfQivnJbHNfKaH9GGmGeNDGN9hGiPJdnAagJbYu7IXw5DcKzgjWfH+5Tg3RClDkAhbvWcxabEV10nyHAgMBAAECggEAEmyEQho10CwrVzZpFGmeZjMNcfUJKDFdP/FdT75rBH5g05OmmTnu6Jo6KJnVrWgqrINpmJJftJ7rljYs/kIsMYEOwZf/maikrlnBU0UFxFRLzDs9wGDslgP8qUp/2/CkKAjc6F3tURrZagafam7gTDt9nrv+D+O5sA64mRa9YcijOAlPzR0MquF28ed9R0rOzXH02OLYkZsmHyPu2SCRtyz/7xAaj737IlPz3meZnBoiE7MMo8uwVfmCsUbP/KJOLUU9O47UspvoCCI5bYQ2g9jrGamXqzqViY9F2BrawhPVNm4KFb1nn/a4jEIfhbF+iQ0qaM/bBXLWZlB2TkmM0QKBgQD3jkjiolhAmHRCW+xo0MmbnOGPTboShbPnn46pXUnIucglUtRSbiXp67wClX7cdfybEKvhFkyy7wmgyt45nTWxLdlna7/9dvQKXmXZYZcKk0oepE8l6iZblAJ1Wm+oGcAXfyFikhE2fxlx1Qs0S6qQg++0V1k8ZY3y7dFSPGApeQKBgQDxAJhLbFKDHRzWwWtYiFQKPj5RieuGVFaYd4H/TiDEiYQrBKxFyeF+kCy3Jr0BpTa9q8Fuxx/zcUZeaZ5uS7Zge8ntww9yC7ABJ525FUIl9kLB754ptRH+JdxYYURwdvOQcXkwU7tdkarH+Shf2B6DJ3ehV+y0IXJS0gENeWRV/wKBgHANFzB+CzQxzW277eYDmz20ZORYakC4BBZzQj+m2h7g+JbsRu6IrOCUsyT4RdPEE/KcOTBIx662Q8VkDfJGFmd8OUt2mhBAJ3YKBE/AvH0s7f+wn6KpuXL6K6KyrJeKEEiSYqobM29XWE0OAWRKW4nOLlGSt/F+hiHPQ0/VxDEBAoGBAKSK/G/aaEd+c/coHatXgNFxh8jR+o0/PdRhG898vyCQpz1btmb7m8p2kyEFANyDuWksQCfrKiRi/WFuiS3S4ZTkT4zWtc/urN9M9gGswvn6NcAFYp4lM0CrBtMMrdZ/UHIZF13ofS84Sjq4IVm2y7ZOFv6AcmrVvyFOoktZyyhvAoGBAOD+zKnbLfKaQmxV8Kg3M/OoDjg8H65aSlrxEeax14T6G8vuJCvBrwngA8F0IsZ15/Qyj+kVj0cZcG3OehuY/GwaPCVKVyO+dcgWGWy3FTcH16Ve2o5EeOGcWXCdAnaVPY6LFNzt93dr1NcC5hUmblwU5MocnLn/Qw0b+OWUgqzj", - - //异步通知地址 - 'notify_url' => "http://外网可访问网关地址/alipay.trade.page.pay-PHP-UTF-8/notify_url.php", - - //同步跳转 - 'return_url' => "http://外网可访问网关地址/alipay.trade.page.pay-PHP-UTF-8/return_url.php", - - //编码格式 - 'charset' => "UTF-8", - - //签名方式 - 'sign_type'=>"RSA2", - - //支付宝网关 - 'gatewayUrl' => "https://openapi.alipay.com/gateway.do", - - //支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。 - 'alipay_public_key' => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjzkd4BFPKltUscLDPk3QnPnxcxXDY/xlh4r3iYi3zBt8nqp+i6amXI1oqJ0RCWuffHK+EF7aRIY3bTtHL5F9dcMrLrpLRAQc9FOuVXEPIHtCjV7Jbqqa5tpHTsPP4rKv33yjhJrXiSkvpI0O4I9rX2pS2IyZBo9pYrLxlmfVMTSkyrtLkD1tKkaVw+tTkF7gBANzUzY2CU2sieXWJyF4da35j8UWyhgEDGHTsDJ1iM0WZj9F165T4/JbjuHBbiF5KZ6KJ+svxqqyAaJaM3DdNtaxj75rBeRxCZ0tAUWDDBXjb0I42vICu1X5e2hYYKcTj/rdtSiry4Jky15/6JMHVwIDAQAB", -); -*/ +$config['app_id'] = "2017092108849921"; +$config['seller_id'] = "2088221900308281"; +$config['notify_url'] = "http://www.mycht.cn/webht.php/apps/pay/alipaytradeservice/alipay_notice"; +$config['return_url'] = "https://www.chinahighlights.com/secureipay/alipay_return"; +$config['charset'] = "UTF-8"; +$config['sign_type'] = "RSA2"; +$config['gatewayUrl'] = "https://openapi.alipay.com/gateway.do"; +$config['timeout_express'] = "1m"; + +$config['alipay_public_key'] = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMpRXezVgTE4/ROKVgWO7AWiVLspzW36lkLF18g2neHV9mfV/kANzrdV170RzJirOuxPecG5LgnKO+MV6giwGJPpUyaRhgYwe1B6Po0LoU4QvI088xjDqNw1vzN7xPRYSgb63mdafVe1qGiHuwelyRYJTZFE3GSb3HSL/5O8MLu0FrIRabgkgOqN7EdznA/WjiGev3tA/10YSrneCcPe49XhKVLvS6cQ3abX48lRr2qxQqh538jYB8/Z/UUVhfQ4BoBqe9JpDQrv4TeIlAXjdqM0Fgz0LXHwXsAiDIeUiKBc+9bAz2vgkRycI+1F3A8VlUG8lwBjqXwzvxZvYzAZYQIDAQAB"; +$config['merchant_private_key'] = "MIIEowIBAAKCAQEAzlwm2yj4lHDuGmBnbgdhMry5kfUmQ2ZeZtuTICi5oUATMlcxjHoVYXe5pN+vcZWM1laC8UuKX1K2gSV+46ax4WcAGjb4eItCmvQyq0REYUua+ybYwWtWn1481NLSPfvW2HwM8O9jXj3XBhfQzJsAJJTikM9lZO++6pC2Wtmhw3FjF+O1gkd015MujRUidXESrIwrmnbO/i1IERblXk1gVnvovWnq6VRB2gC9AfzLdkWo3Pq9rAX+MY/eYto/z8UaYU5BNanVIhQ6pAIQazIMawxqsu28AsPRcM8CwFTYcNktAB3feMRhLMqj9GWzkmDWhjrL3NYR+vsYHDAgj7L5ewIDAQABAoIBAFUxVhlEYNtng+T/x7N0+HupzjKjsphAuthb7fFo3rnjagluVdZY0Frcwpd+gT+zLeGO9aAIP6f6zb2jbS8usmEL1M79wraBR44RIpnyJQjF3cWx0+qGFczVauex4XoVbi0RiYYuTieqAAtT6a+OjhCMJr0B4io5j+fmtmHrVw0IFMmbAesV867EH7sn+MmnJCK79KbL5G7lBxZJZempS9ZhwR18WSGpCk90qHGoI9GlPPDWrN2nAVsGVl501vQKc+fUOQSXmAVc+K87q9SeUmrQdM1GbX5UCj+gMEC7sNAnWthCT2H4AFXxvzGLVhvBzRTLZT1SfmAS8zS8LINDxAECgYEA5gWwtS6Ot96E4MHQxjQEx0cP1+P71uI4huA8Lyx+guPymeM2+u4SiWpkuFyzmoNvMxh2fem3Add3kCNF0PNJRIbI0w2vqF+6gQYVIwcS3kqXUeq9oNN6raqFoad1adAUjGQM1SBwc8ARfF3gw8CkePaxikMzFJ6FS15GeA4SueECgYEA5apZCt3dsFzmMyf+/I/X9Bo+fXhnya6QLN+NsLcwnFpWN//rRHnMR7i9jUpyUUDefz9pLAmTkx3roevoGbI7kikqvWallH1rwkgynQAbyHU1XYjM/tRv9zs2TiorakbqrGvzmTdoClwM+dZOXTT4/TbkmcchvlvXkQWGozaIttsCgYEAqKDxS9Im5Jrn1RGhaTyHaEQrVD0Zyg2sHQzUckzvLivIFZLiIpFX24+46QNk09iZM98yNtqYxGvehjelnipMw0UAguEcrpYHV0FLS5OK/JW4W2B4xidjX1+MedcXF4xpFAbg9XnDlsfuybrU5Q0cRmWsAE2FbA9ObtNdW/QNPGECgYAd44J9EIy2VBC9XZoooku3f+bcC1xueeJXhKx68AxKfNM1rH+gxL0aJGe+yI6CFpAePVFhoslq3vz4cKwfE/v+tI7UYVRxM7Vfbmfv2MDE4MQWLSSIkXsU0Mbrez91ME+AKvhj2zsWBg7GQOan6Knywj8T6D9y957hR7fS69j0+wKBgA1Ph+8DTRbvfXKj95KraLdrPGq6hyK0PaF044pi3u2Z1iys99f7aKM0F19akVE9KG1niR4Zit6S1Hqxx+9V6cLw/xxfEl9t9NK8QxGDqmVk9T6TnyMZvMjAi+FADn3hzbRkp1HGT/XUYe2nFuUaATaNhNuuDcuVZtAr78joA+HV"; diff --git a/webht/third_party/pay/config/dev_alipay.php b/webht/third_party/pay/config/dev_alipay.php index 43f9a091..328a83d5 100644 --- a/webht/third_party/pay/config/dev_alipay.php +++ b/webht/third_party/pay/config/dev_alipay.php @@ -1,10 +1,17 @@ load->library('alipay/AopSdk'); // real URL - // $this->config->load('alipay'); + $this->config->load('alipay'); // test URL - $this->config->load('dev_alipay'); + // $this->config->load('dev_alipay'); $this->load->model('AlipayTradePagePayContentBuilder'); + $this->load->model('AlipayTradeWapPayContentBuilder'); $this->load->model('AlipayTradeQueryContentBuilder'); + $this->load->model('Alipay_note_model'); + $this->load->model('Alipay_model'); + $this->load->helper('payment'); $this->gateway_url = $this->config->item('gatewayUrl'); $this->appid = $this->config->item('app_id'); @@ -50,48 +58,145 @@ class AlipayTradeService extends CI_Controller $this->alipay_public_key = $this->config->item('alipay_public_key'); $this->charset = $this->config->item('charset'); $this->signtype = $this->config->item('sign_type'); + $this->timeout_express = $this->config->item('timeout_express'); + + $this->return_url = $this->config->item('return_url'); + $this->notify_url = $this->config->item('notify_url'); if(empty($this->appid)||trim($this->appid)==""){ - throw new Exception("appid should not be NULL!"); + log_message('error','Alipay ERROR appid should not be NULL!'); } if(empty($this->private_key)||trim($this->private_key)==""){ - throw new Exception("private_key should not be NULL!"); + log_message('error','Alipay ERROR private_key should not be NULL!'); } if(empty($this->alipay_public_key)||trim($this->alipay_public_key)==""){ - throw new Exception("alipay_public_key should not be NULL!"); + log_message('error','Alipay ERROR alipay_public_key should not be NULL!'); } if(empty($this->charset)||trim($this->charset)==""){ - throw new Exception("charset should not be NULL!"); + log_message('error','Alipay ERROR charset should not be NULL!'); } if(empty($this->gateway_url)||trim($this->gateway_url)==""){ - throw new Exception("gateway_url should not be NULL!"); + log_message('error','Alipay ERROR gateway_url should not be NULL!'); + } + } + + /*! + * 异步通知 + * 必须返回"success"给支付系统 + * @author LYT + * @date 2017-09-13 + * @return [type] [description] + */ + public function alipay_notice() + { + $resp_arr = $this->input->post(); + $asyns_resp = $this->check($resp_arr); + // 未得到结果 + if (empty($asyns_resp->data->out_trade_no)) { + echo "failed"; + return; + } + if (true === $this->if_note_exists($dealId)) { + echo "success"; + return; + } + $code = $asyns_resp->data->code ? strval($asyns_resp->data->code) : NULL ; + $buyer = $asyns_resp->data->buyer_logon_id ? strval($asyns_resp->data->buyer_logon_id) : NULL ; + if (strcmp(strval($asyns_resp->data->trade_status), "TRADE_SUCCESS") == 0) { + $this->Alipay_note_model->save_alipay( + strval($asyns_resp->data->trade_no) + ,strval($asyns_resp->data->out_trade_no) + ,"CNY" + ,strval($asyns_resp->data->total_amount) + ,NULL + ,NULL + ,strval($asyns_resp->data->gmt_create) + ,strval($asyns_resp->data->gmt_payment) + ,json_encode($asyns_resp->data) + ,strval("pay") + ,$code + ,strval($asyns_resp->data->trade_status) + ,NULL + ,$buyer + ); } + // 返回状态码200 + echo "success"; + return; + } + public function if_note_exists($dealId) + { + return $this->Alipay_note_model->note_exists($dealId) ? true : false; + } + + public function request_faild() + { + $data["code"] = 1; + $data["msg"] = "Unknow request"; + $data["error_code"] = "Unknow"; + $url_query = ""; + foreach ($data as $key => $v) { + $url_query .= $key . "=" . urlencode($v) ."&"; + } + redirect("https://www.chinahighlights.com/secureipay/load_return" . "?" . substr($url_query, 0, -1)); + } + + public function get_url_string() + { + $param = ($this->input->get_post('param')); + return base64_decode($param); } // cht public function pay_fun() { + $param_string = $this->get_url_string(); + @parse_str($param_string, $param_arr); + if ( ! $param_string || empty($param_arr['order_id'])) { + $this->request_faild(); + return false; + } //商户订单号,商户网站订单系统中唯一订单号,必填 - $out_trade_no = trim($this->input->get_post('out_trade_no')); - + $out_trade_no = trim($param_arr['order_id']); //订单名称,必填 - $subject = trim($this->input->get_post('subject')); - + $subject = trim($param_arr['subject']); //付款金额,必填 - $total_amount = trim($this->input->get_post('total_amount')); - + $total_amount = trim($param_arr['total_amount']); //商品描述,可空 - $body = trim($this->input->get_post('body')); - - $this->AlipayTradePagePayContentBuilder->setBody($body); - $this->AlipayTradePagePayContentBuilder->setSubject($subject); - $this->AlipayTradePagePayContentBuilder->setTotalAmount($total_amount); - $this->AlipayTradePagePayContentBuilder->setOutTradeNo($out_trade_no); - $url = $this->pagePay( - $this->AlipayTradePagePayContentBuilder, - $this->config->item('return_url'), - $this->config->item('notify_url')); + $body = str_replace("\n", "
    ", trim($param_arr['body'])); + + $post_return = $param_arr["return_url"] ? trim($param_arr["return_url"]) : false; + $post_notify = $param_arr["notify_url"] ? trim($param_arr["notify_url"]) : false; + + $this->return_url = !empty($post_return) ? ($post_return) : $this->return_url; + $this->notify_url = !empty($post_notify) ? ($post_notify) : $this->notify_url; + + $detect = new Mobile_Detect; + if ($detect->isMobile() && !$detect->isTablet()) { + // mobile page + $this->AlipayTradeWapPayContentBuilder->setBody($body); + $this->AlipayTradeWapPayContentBuilder->setSubject($subject); + $this->AlipayTradeWapPayContentBuilder->setOutTradeNo($out_trade_no); + $this->AlipayTradeWapPayContentBuilder->setTotalAmount($total_amount); + $this->AlipayTradeWapPayContentBuilder->setTimeExpress($timeout_express); + $result = $this->wapPay( + $this->AlipayTradeWapPayContentBuilder, + $this->return_url, + $this->notify_url + ); + } else { + // PC page + $this->AlipayTradePagePayContentBuilder->setBody($body); + $this->AlipayTradePagePayContentBuilder->setSubject($subject); + $this->AlipayTradePagePayContentBuilder->setTotalAmount($total_amount); + $this->AlipayTradePagePayContentBuilder->setOutTradeNo($out_trade_no); + $url = $this->pagePay( + $this->AlipayTradePagePayContentBuilder, + $this->return_url, + $this->notify_url + ); + } return; } @@ -105,8 +210,6 @@ class AlipayTradeService extends CI_Controller function pagePay($builder,$return_url,$notify_url) { $biz_content=$builder->getBizContent(); - //打印业务参数 cht - log_message('error',"\r\n"." Begin \r\n".$biz_content); $request = new AlipayTradePagePayRequest(); @@ -119,6 +222,29 @@ class AlipayTradeService extends CI_Controller return $response; } + /** + * alipay.trade.wap.pay + * @param $builder 业务参数,使用buildmodel中的对象生成。 + * @param $return_url 同步跳转地址,公网可访问 + * @param $notify_url 异步通知地址,公网可以访问 + * @return $response 支付宝返回的信息 + */ + function wapPay($builder,$return_url,$notify_url) { + + $biz_content=$builder->getBizContent(); + + $request = new AlipayTradeWapPayRequest(); + + $request->setNotifyUrl($notify_url); + $request->setReturnUrl($return_url); + $request->setBizContent ( $biz_content ); + + // 首先调用支付api + $response = $this->aopclientRequestExecute ($request,true); + // $response = $response->alipay_trade_wap_pay_response; + return $response; + } + /** * sdkClient * @param $request 接口请求参数对象。 @@ -149,86 +275,280 @@ class AlipayTradeService extends CI_Controller $result = $aop->Execute($request); } - //打开后,将报文写入log文件 cht - log_message('error',"\r\n\r\nResponse: \r\n".var_export($result,true)); + // 打开后,将报文写入log文件 cht test + // log_message('error',"\r\n\r\nResponse: \r\n".var_export($result,true)); return $result; } + public function send_alipay($pn_txn_id = false) + { + $data = array(); + $int = 0; + + //优先处理指定的交易号,用于修正交易号直接发送通知 + if ( ! empty($pn_txn_id)) { + $data['unsend_list'] = array($this->Alipay_note_model->note($pn_txn_id)); + } + + // 待处理的 + if (empty($data['unsend_list'])) { + $data['unsend_list'] = $this->Alipay_note_model->unsend(10); + } + //没有未处理的数据再查找处理失败的数据 + if (empty($data['unsend_list'])) { + $data['unsend_list'] = $this->Alipay_note_model->failnote(20); + } + + $show_index = 0; + foreach ($data['unsend_list'] as $item) { + + //已经发送的不处理,防止重复发送 + if ($item->ALI_sent == 'send') { + continue; + } + + //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 + if ($item->ALI_payType == 'Refunded') { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + continue; + } + + //只处理完成状态,其他状态由陆燕处理 + if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + continue; + } + + //检测是否是APP订单,默认不处理 + // if ((strpos($item->pn_memo, 'China Train Booking') !== false) || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false)) { //APP自动出票的订单不需要处理 + // $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + // continue; + // } + + //根据note信息找到订单号 + $orderid_info = analysis_orderid($item->ALI_orderId); + + //找不到订单号,设置为发送失败标示 + if (empty($orderid_info)) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + continue; + } + + //根据订单号查找外联信息 + $orderid_info = json_decode($orderid_info); + $advisor_info = $this->Alipay_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + + //查不到订单信息 + if (empty($advisor_info)) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + continue; + } + + //更新正确的订单信息到记录中,以这个为主 + $this->Alipay_note_model->set_invoice($item->ALI_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype); + + //检测是否是APP订单,默认不处理 + if ($orderid_info->ordertype == 'A') { //APP自动出票的订单不需要处理 + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + continue; + } + + //添加支付信息入库 + //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 + if (!empty($orderid_info)) { + //更新还没有填的客邮和交易号de收款记录(商务订单) + if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { + $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { + //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + // $this->Alipay_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->ALI_dealId, $ht_memo); + // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 + // $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + // } + } else { + $this->Alipay_model->add_account_info( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->ALI_orderAmount, + $item->ALI_completeTime, + mb_strtoupper($item->ALI_currencyCode), + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_acquiringTime, + $item->ALI_payerName, + $item->ALI_payerEmail, + $item->ALI_dealId, + $ht_memo + ); + } + } + //更新还没有填的客邮和交易号de收款记录(传统订单) + elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { + $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + $this->Alipay_model->add_tour_account_info( + $GAI_COLI_SN, + $item->ALI_orderAmount, + $item->ALI_acquiringTime, + mb_strtoupper($item->ALI_currencyCode), + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_acquiringTime, + $item->ALI_payerName, + $item->ALI_payerEmail, + $item->ALI_dealId, + $ht_memo + ); + //添加汉特的订单提醒 + $this->Alipay_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->ALI_currencyCode) . $item->ALI_orderAmount); + } + } + + + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + continue; + } + + //添加邮件发送记录 + //给外联发送通知邮件 + $fromName = 'iPayLinks'; + $fromEmail = ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->ALI_orderAmount . $item->ALI_currencyCode . ' / ' . $fromName; + $body = $this->load->view('receipt_mail', $item, true); + $M_RelatedInfo = $item->ALI_sn; + $M_AddTime = $item->ALI_completeTime; + $M_State = 0; + $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note'); + //添加邮件发送记录 end + + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + $int++; + } + // 批量结果 + if (empty($pn_txn_id)) { + echo "done. recorde count:".$int; + } + return; + } + /** * alipay.trade.query (统一收单线下交易查询) * @param $builder 业务参数,使用buildmodel中的对象生成。 - * @return $response 支付宝返回的信息 + * @return Array object $response 支付宝返回的信息 */ function Query($builder){ $biz_content=$builder->getBizContent(); - //打印业务参数 + $request = new AlipayTradeQueryRequest(); $request->setBizContent ( $biz_content ); $response = $this->aopclientRequestExecute ($request); $response = $response->alipay_trade_query_response; + + // test asyns + // $resp_arr = (Array) $response; + // $asyns_resp = $this->check($resp_arr); + // if (strcmp(strval($response->trade_status), "TRADE_SUCCESS") == 0) { + // $this->Alipay_note_model->save_alipay( + // strval($response->trade_no) + // ,strval($response->out_trade_no) + // ,"CNY" + // ,strval($response->total_amount) + // ,NULL + // ,NULL + // ,strval($response->send_pay_date) + // ,strval($response->send_pay_date) + // ,json_encode($response) + // ,strval("pay") + // ,strval($response->code) + // ,strval($response->trade_status) + // ,NULL + // ,strval($response->buyer_logon_id) + // ); + // $query = $this->query_pay_result($asyns_resp->data); + // } + return $response; } + public function query_pay($dealId,$orderId=NULL) + { + $this->AlipayTradeQueryContentBuilder->setTradeNo($dealId); + if ($orderId) { + $this->AlipayTradeQueryContentBuilder->setOutTradeNo($orderId); + } + $response = $this->Query($this->AlipayTradeQueryContentBuilder); + if ( strcmp(trim($response->code), "10000")) { + log_message('error',"Alipay payment failed! error code:".$response->code."; result Msg: ".$response->msg.'; orderId:'.$response->out_trade_no.'; dealId:'.$response->trade_no."; "); + } + $html = ''; + foreach ($response as $key => $value) { + $html .= ""; + } + $html .= '
    $key$value
    '; + echo $html; + return; + } + /** * 验签方法 * @param $arr 验签支付宝返回的信息,使用支付宝公钥。 * @return boolean */ function check($arr){ + $ret = new ArrayObject(); + $ret->check = false; + $ret->data = NULL; + + $ret->data = $arr_obj = (object) $arr; + $aop = new AopClient(); $aop->alipayrsaPublicKey = $this->alipay_public_key; - $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); + $ret->check = $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); if ($result === false) { - return $result; + log_message('error','Alipay sign ERROR ! orderId:'.$arr_obj->out_trade_no.'; dealId:'.$arr_obj->trade_no . "; Original return:".json_encode($arr)."; "); + return $ret; } // cht // 1.app_id - // 2.seller_id - // 3.查询数据库,验证订单信息,订单号 - // 4.订单金额 - $verify_ret = true; if ($arr['app_id'] !== $this->appid) { - $verify_ret = false; + log_message('error','Alipay ERROR APPID verify failed '.$arr_obj->app_id." !== ".$this->appid."; orderId:".$arr_obj->out_trade_no."; dealId:".$arr_obj->trade_no); + return $ret; } + // 2.seller_id if ($arr['seller_id'] !== $this->seller_id) { - $verify_ret = false; + log_message('error','Alipay ERROR SELLERID verify failed '.$arr_obj->seller_id." !== ".$this->seller_id."; orderId:".$arr_obj->out_trade_no."; dealId:".$arr_obj->trade_no); + return $ret; } - log_message('error',"\r\n\r\n Check result: ".$result); - return $verify_ret; - } - - // cht - function return_url() - { - $arr = $this->input->get(); - $result = $this->check($arr); - if ($result) { - $this->load->view("iPayLinks_rep",array("code"=>0,"msg"=>"")); - // echo "付款成功!支付宝交易号:".$arr["trade_no"]; - } else { - echo "付款失败!"; + // 3.pay status + if (strcmp(strval($arr_obj->trade_status), "TRADE_SUCCESS")) { + log_message('error',"Alipay payment failed! error code:".$arr_obj->trade_status."; result Msg: ".$arr_obj->trade_status.'; orderId:'.$arr_obj->out_trade_no.'; dealId:'.$arr_obj->trade_no."; "); + return $ret; } - return; + $ret->check = true; + return $ret; } - // cht - function notify_url() - { - $arr = $this->input->post(); - $result = $this->check($arr); - log_message('error',"\r\n\r\n Notify:\r\n".var_export($arr,true)); - if ($result) { - /*! - * Do NOT touch - * 不要改这里,必须返回这5个字符 - */ - echo "success"; - } else { - echo "fail"; - } - return; + /** *利用google api生成二维码图片 + * $content:二维码内容参数 + * $size:生成二维码的尺寸,宽度和高度的值 + * $lev:可选参数,纠错等级 + * $margin:生成的二维码离边框的距离 + */ + function create_erweima($content, $size = '200', $lev = 'L', $margin= '0') { + $content = urlencode($content); + $image = ''; + // http://chart.apis.google.com/chart?chs=200x200&cht=qr&chl=http://www.chinahighlights.com/ + return $image; } } diff --git a/webht/third_party/pay/controllers/Mobile_Detect.php b/webht/third_party/pay/controllers/Mobile_Detect.php new file mode 100644 index 00000000..4e44ff36 --- /dev/null +++ b/webht/third_party/pay/controllers/Mobile_Detect.php @@ -0,0 +1,1459 @@ + + * Nick Ilyin + * + * Original author: Victor Stanciu + * + * @license Code and contributions have 'MIT License' + * More details: https://github.com/serbanghita/Mobile-Detect/blob/master/LICENSE.txt + * + * @link Homepage: http://mobiledetect.net + * GitHub Repo: https://github.com/serbanghita/Mobile-Detect + * Google Code: http://code.google.com/p/php-mobile-detect/ + * README: https://github.com/serbanghita/Mobile-Detect/blob/master/README.md + * HOWTO: https://github.com/serbanghita/Mobile-Detect/wiki/Code-examples + * + * @version 2.8.25 + */ + +class Mobile_Detect +{ + /** + * Mobile detection type. + * + * @deprecated since version 2.6.9 + */ + const DETECTION_TYPE_MOBILE = 'mobile'; + + /** + * Extended detection type. + * + * @deprecated since version 2.6.9 + */ + const DETECTION_TYPE_EXTENDED = 'extended'; + + /** + * A frequently used regular expression to extract version #s. + * + * @deprecated since version 2.6.9 + */ + const VER = '([\w._\+]+)'; + + /** + * Top-level device. + */ + const MOBILE_GRADE_A = 'A'; + + /** + * Mid-level device. + */ + const MOBILE_GRADE_B = 'B'; + + /** + * Low-level device. + */ + const MOBILE_GRADE_C = 'C'; + + /** + * Stores the version number of the current release. + */ + const VERSION = '2.8.25'; + + /** + * A type for the version() method indicating a string return value. + */ + const VERSION_TYPE_STRING = 'text'; + + /** + * A type for the version() method indicating a float return value. + */ + const VERSION_TYPE_FLOAT = 'float'; + + /** + * A cache for resolved matches + * @var array + */ + protected $cache = array(); + + /** + * The User-Agent HTTP header is stored in here. + * @var string + */ + protected $userAgent = null; + + /** + * HTTP headers in the PHP-flavor. So HTTP_USER_AGENT and SERVER_SOFTWARE. + * @var array + */ + protected $httpHeaders = array(); + + /** + * CloudFront headers. E.g. CloudFront-Is-Desktop-Viewer, CloudFront-Is-Mobile-Viewer & CloudFront-Is-Tablet-Viewer. + * @var array + */ + protected $cloudfrontHeaders = array(); + + /** + * The matching Regex. + * This is good for debug. + * @var string + */ + protected $matchingRegex = null; + + /** + * The matches extracted from the regex expression. + * This is good for debug. + * @var string + */ + protected $matchesArray = null; + + /** + * The detection type, using self::DETECTION_TYPE_MOBILE or self::DETECTION_TYPE_EXTENDED. + * + * @deprecated since version 2.6.9 + * + * @var string + */ + protected $detectionType = self::DETECTION_TYPE_MOBILE; + + /** + * HTTP headers that trigger the 'isMobile' detection + * to be true. + * + * @var array + */ + protected static $mobileHeaders = array( + + 'HTTP_ACCEPT' => array('matches' => array( + // Opera Mini; @reference: http://dev.opera.com/articles/view/opera-binary-markup-language/ + 'application/x-obml2d', + // BlackBerry devices. + 'application/vnd.rim.html', + 'text/vnd.wap.wml', + 'application/vnd.wap.xhtml+xml' + )), + 'HTTP_X_WAP_PROFILE' => null, + 'HTTP_X_WAP_CLIENTID' => null, + 'HTTP_WAP_CONNECTION' => null, + 'HTTP_PROFILE' => null, + // Reported by Opera on Nokia devices (eg. C3). + 'HTTP_X_OPERAMINI_PHONE_UA' => null, + 'HTTP_X_NOKIA_GATEWAY_ID' => null, + 'HTTP_X_ORANGE_ID' => null, + 'HTTP_X_VODAFONE_3GPDPCONTEXT' => null, + 'HTTP_X_HUAWEI_USERID' => null, + // Reported by Windows Smartphones. + 'HTTP_UA_OS' => null, + // Reported by Verizon, Vodafone proxy system. + 'HTTP_X_MOBILE_GATEWAY' => null, + // Seen this on HTC Sensation. SensationXE_Beats_Z715e. + 'HTTP_X_ATT_DEVICEID' => null, + // Seen this on a HTC. + 'HTTP_UA_CPU' => array('matches' => array('ARM')), + ); + + /** + * List of mobile devices (phones). + * + * @var array + */ + protected static $phoneDevices = array( + 'iPhone' => '\biPhone\b|\biPod\b', // |\biTunes + 'BlackBerry' => 'BlackBerry|\bBB10\b|rim[0-9]+', + 'HTC' => 'HTC|HTC.*(Sensation|Evo|Vision|Explorer|6800|8100|8900|A7272|S510e|C110e|Legend|Desire|T8282)|APX515CKT|Qtek9090|APA9292KT|HD_mini|Sensation.*Z710e|PG86100|Z715e|Desire.*(A8181|HD)|ADR6200|ADR6400L|ADR6425|001HT|Inspire 4G|Android.*\bEVO\b|T-Mobile G1|Z520m', + 'Nexus' => 'Nexus One|Nexus S|Galaxy.*Nexus|Android.*Nexus.*Mobile|Nexus 4|Nexus 5|Nexus 6', + // @todo: Is 'Dell Streak' a tablet or a phone? ;) + 'Dell' => 'Dell.*Streak|Dell.*Aero|Dell.*Venue|DELL.*Venue Pro|Dell Flash|Dell Smoke|Dell Mini 3iX|XCD28|XCD35|\b001DL\b|\b101DL\b|\bGS01\b', + 'Motorola' => 'Motorola|DROIDX|DROID BIONIC|\bDroid\b.*Build|Android.*Xoom|HRI39|MOT-|A1260|A1680|A555|A853|A855|A953|A955|A956|Motorola.*ELECTRIFY|Motorola.*i1|i867|i940|MB200|MB300|MB501|MB502|MB508|MB511|MB520|MB525|MB526|MB611|MB612|MB632|MB810|MB855|MB860|MB861|MB865|MB870|ME501|ME502|ME511|ME525|ME600|ME632|ME722|ME811|ME860|ME863|ME865|MT620|MT710|MT716|MT720|MT810|MT870|MT917|Motorola.*TITANIUM|WX435|WX445|XT300|XT301|XT311|XT316|XT317|XT319|XT320|XT390|XT502|XT530|XT531|XT532|XT535|XT603|XT610|XT611|XT615|XT681|XT701|XT702|XT711|XT720|XT800|XT806|XT860|XT862|XT875|XT882|XT883|XT894|XT901|XT907|XT909|XT910|XT912|XT928|XT926|XT915|XT919|XT925|XT1021|\bMoto E\b', + 'Samsung' => '\bSamsung\b|SM-G9250|GT-19300|SGH-I337|BGT-S5230|GT-B2100|GT-B2700|GT-B2710|GT-B3210|GT-B3310|GT-B3410|GT-B3730|GT-B3740|GT-B5510|GT-B5512|GT-B5722|GT-B6520|GT-B7300|GT-B7320|GT-B7330|GT-B7350|GT-B7510|GT-B7722|GT-B7800|GT-C3010|GT-C3011|GT-C3060|GT-C3200|GT-C3212|GT-C3212I|GT-C3262|GT-C3222|GT-C3300|GT-C3300K|GT-C3303|GT-C3303K|GT-C3310|GT-C3322|GT-C3330|GT-C3350|GT-C3500|GT-C3510|GT-C3530|GT-C3630|GT-C3780|GT-C5010|GT-C5212|GT-C6620|GT-C6625|GT-C6712|GT-E1050|GT-E1070|GT-E1075|GT-E1080|GT-E1081|GT-E1085|GT-E1087|GT-E1100|GT-E1107|GT-E1110|GT-E1120|GT-E1125|GT-E1130|GT-E1160|GT-E1170|GT-E1175|GT-E1180|GT-E1182|GT-E1200|GT-E1210|GT-E1225|GT-E1230|GT-E1390|GT-E2100|GT-E2120|GT-E2121|GT-E2152|GT-E2220|GT-E2222|GT-E2230|GT-E2232|GT-E2250|GT-E2370|GT-E2550|GT-E2652|GT-E3210|GT-E3213|GT-I5500|GT-I5503|GT-I5700|GT-I5800|GT-I5801|GT-I6410|GT-I6420|GT-I7110|GT-I7410|GT-I7500|GT-I8000|GT-I8150|GT-I8160|GT-I8190|GT-I8320|GT-I8330|GT-I8350|GT-I8530|GT-I8700|GT-I8703|GT-I8910|GT-I9000|GT-I9001|GT-I9003|GT-I9010|GT-I9020|GT-I9023|GT-I9070|GT-I9082|GT-I9100|GT-I9103|GT-I9220|GT-I9250|GT-I9300|GT-I9305|GT-I9500|GT-I9505|GT-M3510|GT-M5650|GT-M7500|GT-M7600|GT-M7603|GT-M8800|GT-M8910|GT-N7000|GT-S3110|GT-S3310|GT-S3350|GT-S3353|GT-S3370|GT-S3650|GT-S3653|GT-S3770|GT-S3850|GT-S5210|GT-S5220|GT-S5229|GT-S5230|GT-S5233|GT-S5250|GT-S5253|GT-S5260|GT-S5263|GT-S5270|GT-S5300|GT-S5330|GT-S5350|GT-S5360|GT-S5363|GT-S5369|GT-S5380|GT-S5380D|GT-S5560|GT-S5570|GT-S5600|GT-S5603|GT-S5610|GT-S5620|GT-S5660|GT-S5670|GT-S5690|GT-S5750|GT-S5780|GT-S5830|GT-S5839|GT-S6102|GT-S6500|GT-S7070|GT-S7200|GT-S7220|GT-S7230|GT-S7233|GT-S7250|GT-S7500|GT-S7530|GT-S7550|GT-S7562|GT-S7710|GT-S8000|GT-S8003|GT-S8500|GT-S8530|GT-S8600|SCH-A310|SCH-A530|SCH-A570|SCH-A610|SCH-A630|SCH-A650|SCH-A790|SCH-A795|SCH-A850|SCH-A870|SCH-A890|SCH-A930|SCH-A950|SCH-A970|SCH-A990|SCH-I100|SCH-I110|SCH-I400|SCH-I405|SCH-I500|SCH-I510|SCH-I515|SCH-I600|SCH-I730|SCH-I760|SCH-I770|SCH-I830|SCH-I910|SCH-I920|SCH-I959|SCH-LC11|SCH-N150|SCH-N300|SCH-R100|SCH-R300|SCH-R351|SCH-R400|SCH-R410|SCH-T300|SCH-U310|SCH-U320|SCH-U350|SCH-U360|SCH-U365|SCH-U370|SCH-U380|SCH-U410|SCH-U430|SCH-U450|SCH-U460|SCH-U470|SCH-U490|SCH-U540|SCH-U550|SCH-U620|SCH-U640|SCH-U650|SCH-U660|SCH-U700|SCH-U740|SCH-U750|SCH-U810|SCH-U820|SCH-U900|SCH-U940|SCH-U960|SCS-26UC|SGH-A107|SGH-A117|SGH-A127|SGH-A137|SGH-A157|SGH-A167|SGH-A177|SGH-A187|SGH-A197|SGH-A227|SGH-A237|SGH-A257|SGH-A437|SGH-A517|SGH-A597|SGH-A637|SGH-A657|SGH-A667|SGH-A687|SGH-A697|SGH-A707|SGH-A717|SGH-A727|SGH-A737|SGH-A747|SGH-A767|SGH-A777|SGH-A797|SGH-A817|SGH-A827|SGH-A837|SGH-A847|SGH-A867|SGH-A877|SGH-A887|SGH-A897|SGH-A927|SGH-B100|SGH-B130|SGH-B200|SGH-B220|SGH-C100|SGH-C110|SGH-C120|SGH-C130|SGH-C140|SGH-C160|SGH-C170|SGH-C180|SGH-C200|SGH-C207|SGH-C210|SGH-C225|SGH-C230|SGH-C417|SGH-C450|SGH-D307|SGH-D347|SGH-D357|SGH-D407|SGH-D415|SGH-D780|SGH-D807|SGH-D980|SGH-E105|SGH-E200|SGH-E315|SGH-E316|SGH-E317|SGH-E335|SGH-E590|SGH-E635|SGH-E715|SGH-E890|SGH-F300|SGH-F480|SGH-I200|SGH-I300|SGH-I320|SGH-I550|SGH-I577|SGH-I600|SGH-I607|SGH-I617|SGH-I627|SGH-I637|SGH-I677|SGH-I700|SGH-I717|SGH-I727|SGH-i747M|SGH-I777|SGH-I780|SGH-I827|SGH-I847|SGH-I857|SGH-I896|SGH-I897|SGH-I900|SGH-I907|SGH-I917|SGH-I927|SGH-I937|SGH-I997|SGH-J150|SGH-J200|SGH-L170|SGH-L700|SGH-M110|SGH-M150|SGH-M200|SGH-N105|SGH-N500|SGH-N600|SGH-N620|SGH-N625|SGH-N700|SGH-N710|SGH-P107|SGH-P207|SGH-P300|SGH-P310|SGH-P520|SGH-P735|SGH-P777|SGH-Q105|SGH-R210|SGH-R220|SGH-R225|SGH-S105|SGH-S307|SGH-T109|SGH-T119|SGH-T139|SGH-T209|SGH-T219|SGH-T229|SGH-T239|SGH-T249|SGH-T259|SGH-T309|SGH-T319|SGH-T329|SGH-T339|SGH-T349|SGH-T359|SGH-T369|SGH-T379|SGH-T409|SGH-T429|SGH-T439|SGH-T459|SGH-T469|SGH-T479|SGH-T499|SGH-T509|SGH-T519|SGH-T539|SGH-T559|SGH-T589|SGH-T609|SGH-T619|SGH-T629|SGH-T639|SGH-T659|SGH-T669|SGH-T679|SGH-T709|SGH-T719|SGH-T729|SGH-T739|SGH-T746|SGH-T749|SGH-T759|SGH-T769|SGH-T809|SGH-T819|SGH-T839|SGH-T919|SGH-T929|SGH-T939|SGH-T959|SGH-T989|SGH-U100|SGH-U200|SGH-U800|SGH-V205|SGH-V206|SGH-X100|SGH-X105|SGH-X120|SGH-X140|SGH-X426|SGH-X427|SGH-X475|SGH-X495|SGH-X497|SGH-X507|SGH-X600|SGH-X610|SGH-X620|SGH-X630|SGH-X700|SGH-X820|SGH-X890|SGH-Z130|SGH-Z150|SGH-Z170|SGH-ZX10|SGH-ZX20|SHW-M110|SPH-A120|SPH-A400|SPH-A420|SPH-A460|SPH-A500|SPH-A560|SPH-A600|SPH-A620|SPH-A660|SPH-A700|SPH-A740|SPH-A760|SPH-A790|SPH-A800|SPH-A820|SPH-A840|SPH-A880|SPH-A900|SPH-A940|SPH-A960|SPH-D600|SPH-D700|SPH-D710|SPH-D720|SPH-I300|SPH-I325|SPH-I330|SPH-I350|SPH-I500|SPH-I600|SPH-I700|SPH-L700|SPH-M100|SPH-M220|SPH-M240|SPH-M300|SPH-M305|SPH-M320|SPH-M330|SPH-M350|SPH-M360|SPH-M370|SPH-M380|SPH-M510|SPH-M540|SPH-M550|SPH-M560|SPH-M570|SPH-M580|SPH-M610|SPH-M620|SPH-M630|SPH-M800|SPH-M810|SPH-M850|SPH-M900|SPH-M910|SPH-M920|SPH-M930|SPH-N100|SPH-N200|SPH-N240|SPH-N300|SPH-N400|SPH-Z400|SWC-E100|SCH-i909|GT-N7100|GT-N7105|SCH-I535|SM-N900A|SGH-I317|SGH-T999L|GT-S5360B|GT-I8262|GT-S6802|GT-S6312|GT-S6310|GT-S5312|GT-S5310|GT-I9105|GT-I8510|GT-S6790N|SM-G7105|SM-N9005|GT-S5301|GT-I9295|GT-I9195|SM-C101|GT-S7392|GT-S7560|GT-B7610|GT-I5510|GT-S7582|GT-S7530E|GT-I8750|SM-G9006V|SM-G9008V|SM-G9009D|SM-G900A|SM-G900D|SM-G900F|SM-G900H|SM-G900I|SM-G900J|SM-G900K|SM-G900L|SM-G900M|SM-G900P|SM-G900R4|SM-G900S|SM-G900T|SM-G900V|SM-G900W8|SHV-E160K|SCH-P709|SCH-P729|SM-T2558|GT-I9205|SM-G9350|SM-J120F|SM-G920F|SM-G920V|SM-G930F|SM-N910C', + 'LG' => '\bLG\b;|LG[- ]?(C800|C900|E400|E610|E900|E-900|F160|F180K|F180L|F180S|730|855|L160|LS740|LS840|LS970|LU6200|MS690|MS695|MS770|MS840|MS870|MS910|P500|P700|P705|VM696|AS680|AS695|AX840|C729|E970|GS505|272|C395|E739BK|E960|L55C|L75C|LS696|LS860|P769BK|P350|P500|P509|P870|UN272|US730|VS840|VS950|LN272|LN510|LS670|LS855|LW690|MN270|MN510|P509|P769|P930|UN200|UN270|UN510|UN610|US670|US740|US760|UX265|UX840|VN271|VN530|VS660|VS700|VS740|VS750|VS910|VS920|VS930|VX9200|VX11000|AX840A|LW770|P506|P925|P999|E612|D955|D802|MS323)', + 'Sony' => 'SonyST|SonyLT|SonyEricsson|SonyEricssonLT15iv|LT18i|E10i|LT28h|LT26w|SonyEricssonMT27i|C5303|C6902|C6903|C6906|C6943|D2533', + 'Asus' => 'Asus.*Galaxy|PadFone.*Mobile', + 'NokiaLumia' => 'Lumia [0-9]{3,4}', + // http://www.micromaxinfo.com/mobiles/smartphones + // Added because the codes might conflict with Acer Tablets. + 'Micromax' => 'Micromax.*\b(A210|A92|A88|A72|A111|A110Q|A115|A116|A110|A90S|A26|A51|A35|A54|A25|A27|A89|A68|A65|A57|A90)\b', + // @todo Complete the regex. + 'Palm' => 'PalmSource|Palm', // avantgo|blazer|elaine|hiptop|plucker|xiino ; + 'Vertu' => 'Vertu|Vertu.*Ltd|Vertu.*Ascent|Vertu.*Ayxta|Vertu.*Constellation(F|Quest)?|Vertu.*Monika|Vertu.*Signature', // Just for fun ;) + // http://www.pantech.co.kr/en/prod/prodList.do?gbrand=VEGA (PANTECH) + // Most of the VEGA devices are legacy. PANTECH seem to be newer devices based on Android. + 'Pantech' => 'PANTECH|IM-A850S|IM-A840S|IM-A830L|IM-A830K|IM-A830S|IM-A820L|IM-A810K|IM-A810S|IM-A800S|IM-T100K|IM-A725L|IM-A780L|IM-A775C|IM-A770K|IM-A760S|IM-A750K|IM-A740S|IM-A730S|IM-A720L|IM-A710K|IM-A690L|IM-A690S|IM-A650S|IM-A630K|IM-A600S|VEGA PTL21|PT003|P8010|ADR910L|P6030|P6020|P9070|P4100|P9060|P5000|CDM8992|TXT8045|ADR8995|IS11PT|P2030|P6010|P8000|PT002|IS06|CDM8999|P9050|PT001|TXT8040|P2020|P9020|P2000|P7040|P7000|C790', + // http://www.fly-phone.com/devices/smartphones/ ; Included only smartphones. + 'Fly' => 'IQ230|IQ444|IQ450|IQ440|IQ442|IQ441|IQ245|IQ256|IQ236|IQ255|IQ235|IQ245|IQ275|IQ240|IQ285|IQ280|IQ270|IQ260|IQ250', + // http://fr.wikomobile.com + 'Wiko' => 'KITE 4G|HIGHWAY|GETAWAY|STAIRWAY|DARKSIDE|DARKFULL|DARKNIGHT|DARKMOON|SLIDE|WAX 4G|RAINBOW|BLOOM|SUNSET|GOA(?!nna)|LENNY|BARRY|IGGY|OZZY|CINK FIVE|CINK PEAX|CINK PEAX 2|CINK SLIM|CINK SLIM 2|CINK +|CINK KING|CINK PEAX|CINK SLIM|SUBLIM', + 'iMobile' => 'i-mobile (IQ|i-STYLE|idea|ZAA|Hitz)', + // Added simvalley mobile just for fun. They have some interesting devices. + // http://www.simvalley.fr/telephonie---gps-_22_telephonie-mobile_telephones_.html + 'SimValley' => '\b(SP-80|XT-930|SX-340|XT-930|SX-310|SP-360|SP60|SPT-800|SP-120|SPT-800|SP-140|SPX-5|SPX-8|SP-100|SPX-8|SPX-12)\b', + // Wolfgang - a brand that is sold by Aldi supermarkets. + // http://www.wolfgangmobile.com/ + 'Wolfgang' => 'AT-B24D|AT-AS50HD|AT-AS40W|AT-AS55HD|AT-AS45q2|AT-B26D|AT-AS50Q', + 'Alcatel' => 'Alcatel', + 'Nintendo' => 'Nintendo 3DS', + // http://en.wikipedia.org/wiki/Amoi + 'Amoi' => 'Amoi', + // http://en.wikipedia.org/wiki/INQ + 'INQ' => 'INQ', + // @Tapatalk is a mobile app; http://support.tapatalk.com/threads/smf-2-0-2-os-and-browser-detection-plugin-and-tapatalk.15565/#post-79039 + 'GenericPhone' => 'Tapatalk|PDA;|SAGEM|\bmmp\b|pocket|\bpsp\b|symbian|Smartphone|smartfon|treo|up.browser|up.link|vodafone|\bwap\b|nokia|Series40|Series60|S60|SonyEricsson|N900|MAUI.*WAP.*Browser', + ); + + /** + * List of tablet devices. + * + * @var array + */ + protected static $tabletDevices = array( + // @todo: check for mobile friendly emails topic. + 'iPad' => 'iPad|iPad.*Mobile', + // Removed |^.*Android.*Nexus(?!(?:Mobile).)*$ + // @see #442 + 'NexusTablet' => 'Android.*Nexus[\s]+(7|9|10)', + 'SamsungTablet' => 'SAMSUNG.*Tablet|Galaxy.*Tab|SC-01C|GT-P1000|GT-P1003|GT-P1010|GT-P3105|GT-P6210|GT-P6800|GT-P6810|GT-P7100|GT-P7300|GT-P7310|GT-P7500|GT-P7510|SCH-I800|SCH-I815|SCH-I905|SGH-I957|SGH-I987|SGH-T849|SGH-T859|SGH-T869|SPH-P100|GT-P3100|GT-P3108|GT-P3110|GT-P5100|GT-P5110|GT-P6200|GT-P7320|GT-P7511|GT-N8000|GT-P8510|SGH-I497|SPH-P500|SGH-T779|SCH-I705|SCH-I915|GT-N8013|GT-P3113|GT-P5113|GT-P8110|GT-N8010|GT-N8005|GT-N8020|GT-P1013|GT-P6201|GT-P7501|GT-N5100|GT-N5105|GT-N5110|SHV-E140K|SHV-E140L|SHV-E140S|SHV-E150S|SHV-E230K|SHV-E230L|SHV-E230S|SHW-M180K|SHW-M180L|SHW-M180S|SHW-M180W|SHW-M300W|SHW-M305W|SHW-M380K|SHW-M380S|SHW-M380W|SHW-M430W|SHW-M480K|SHW-M480S|SHW-M480W|SHW-M485W|SHW-M486W|SHW-M500W|GT-I9228|SCH-P739|SCH-I925|GT-I9200|GT-P5200|GT-P5210|GT-P5210X|SM-T311|SM-T310|SM-T310X|SM-T210|SM-T210R|SM-T211|SM-P600|SM-P601|SM-P605|SM-P900|SM-P901|SM-T217|SM-T217A|SM-T217S|SM-P6000|SM-T3100|SGH-I467|XE500|SM-T110|GT-P5220|GT-I9200X|GT-N5110X|GT-N5120|SM-P905|SM-T111|SM-T2105|SM-T315|SM-T320|SM-T320X|SM-T321|SM-T520|SM-T525|SM-T530NU|SM-T230NU|SM-T330NU|SM-T900|XE500T1C|SM-P605V|SM-P905V|SM-T337V|SM-T537V|SM-T707V|SM-T807V|SM-P600X|SM-P900X|SM-T210X|SM-T230|SM-T230X|SM-T325|GT-P7503|SM-T531|SM-T330|SM-T530|SM-T705|SM-T705C|SM-T535|SM-T331|SM-T800|SM-T700|SM-T537|SM-T807|SM-P907A|SM-T337A|SM-T537A|SM-T707A|SM-T807A|SM-T237|SM-T807P|SM-P607T|SM-T217T|SM-T337T|SM-T807T|SM-T116NQ|SM-P550|SM-T350|SM-T550|SM-T9000|SM-P9000|SM-T705Y|SM-T805|GT-P3113|SM-T710|SM-T810|SM-T815|SM-T360|SM-T533|SM-T113|SM-T335|SM-T715|SM-T560|SM-T670|SM-T677|SM-T377|SM-T567|SM-T357T|SM-T555|SM-T561|SM-T713|SM-T719|SM-T813|SM-T819|SM-T580|SM-T355Y|SM-T280|SM-T817A|SM-T820|SM-W700|SM-P580|SM-T587', // SCH-P709|SCH-P729|SM-T2558|GT-I9205 - Samsung Mega - treat them like a regular phone. + // http://docs.aws.amazon.com/silk/latest/developerguide/user-agent.html + 'Kindle' => 'Kindle|Silk.*Accelerated|Android.*\b(KFOT|KFTT|KFJWI|KFJWA|KFOTE|KFSOWI|KFTHWI|KFTHWA|KFAPWI|KFAPWA|WFJWAE|KFSAWA|KFSAWI|KFASWI|KFARWI|KFFOWI|KFGIWI|KFMEWI)\b|Android.*Silk/[0-9.]+ like Chrome/[0-9.]+ (?!Mobile)', + // Only the Surface tablets with Windows RT are considered mobile. + // http://msdn.microsoft.com/en-us/library/ie/hh920767(v=vs.85).aspx + 'SurfaceTablet' => 'Windows NT [0-9.]+; ARM;.*(Tablet|ARMBJS)', + // http://shopping1.hp.com/is-bin/INTERSHOP.enfinity/WFS/WW-USSMBPublicStore-Site/en_US/-/USD/ViewStandardCatalog-Browse?CatalogCategoryID=JfIQ7EN5lqMAAAEyDcJUDwMT + 'HPTablet' => 'HP Slate (7|8|10)|HP ElitePad 900|hp-tablet|EliteBook.*Touch|HP 8|Slate 21|HP SlateBook 10', + // Watch out for PadFone, see #132. + // http://www.asus.com/de/Tablets_Mobile/Memo_Pad_Products/ + 'AsusTablet' => '^.*PadFone((?!Mobile).)*$|Transformer|TF101|TF101G|TF300T|TF300TG|TF300TL|TF700T|TF700KL|TF701T|TF810C|ME171|ME301T|ME302C|ME371MG|ME370T|ME372MG|ME172V|ME173X|ME400C|Slider SL101|\bK00F\b|\bK00C\b|\bK00E\b|\bK00L\b|TX201LA|ME176C|ME102A|\bM80TA\b|ME372CL|ME560CG|ME372CG|ME302KL| K010 | K011 | K017 | K01E |ME572C|ME103K|ME170C|ME171C|\bME70C\b|ME581C|ME581CL|ME8510C|ME181C|P01Y|PO1MA|P01Z', + 'BlackBerryTablet' => 'PlayBook|RIM Tablet', + 'HTCtablet' => 'HTC_Flyer_P512|HTC Flyer|HTC Jetstream|HTC-P715a|HTC EVO View 4G|PG41200|PG09410', + 'MotorolaTablet' => 'xoom|sholest|MZ615|MZ605|MZ505|MZ601|MZ602|MZ603|MZ604|MZ606|MZ607|MZ608|MZ609|MZ615|MZ616|MZ617', + 'NookTablet' => 'Android.*Nook|NookColor|nook browser|BNRV200|BNRV200A|BNTV250|BNTV250A|BNTV400|BNTV600|LogicPD Zoom2', + // http://www.acer.ro/ac/ro/RO/content/drivers + // http://www.packardbell.co.uk/pb/en/GB/content/download (Packard Bell is part of Acer) + // http://us.acer.com/ac/en/US/content/group/tablets + // http://www.acer.de/ac/de/DE/content/models/tablets/ + // Can conflict with Micromax and Motorola phones codes. + 'AcerTablet' => 'Android.*; \b(A100|A101|A110|A200|A210|A211|A500|A501|A510|A511|A700|A701|W500|W500P|W501|W501P|W510|W511|W700|G100|G100W|B1-A71|B1-710|B1-711|A1-810|A1-811|A1-830)\b|W3-810|\bA3-A10\b|\bA3-A11\b|\bA3-A20\b|\bA3-A30', + // http://eu.computers.toshiba-europe.com/innovation/family/Tablets/1098744/banner_id/tablet_footerlink/ + // http://us.toshiba.com/tablets/tablet-finder + // http://www.toshiba.co.jp/regza/tablet/ + 'ToshibaTablet' => 'Android.*(AT100|AT105|AT200|AT205|AT270|AT275|AT300|AT305|AT1S5|AT500|AT570|AT700|AT830)|TOSHIBA.*FOLIO', + // http://www.nttdocomo.co.jp/english/service/developer/smart_phone/technical_info/spec/index.html + // http://www.lg.com/us/tablets + 'LGTablet' => '\bL-06C|LG-V909|LG-V900|LG-V700|LG-V510|LG-V500|LG-V410|LG-V400|LG-VK810\b', + 'FujitsuTablet' => 'Android.*\b(F-01D|F-02F|F-05E|F-10D|M532|Q572)\b', + // Prestigio Tablets http://www.prestigio.com/support + 'PrestigioTablet' => 'PMP3170B|PMP3270B|PMP3470B|PMP7170B|PMP3370B|PMP3570C|PMP5870C|PMP3670B|PMP5570C|PMP5770D|PMP3970B|PMP3870C|PMP5580C|PMP5880D|PMP5780D|PMP5588C|PMP7280C|PMP7280C3G|PMP7280|PMP7880D|PMP5597D|PMP5597|PMP7100D|PER3464|PER3274|PER3574|PER3884|PER5274|PER5474|PMP5097CPRO|PMP5097|PMP7380D|PMP5297C|PMP5297C_QUAD|PMP812E|PMP812E3G|PMP812F|PMP810E|PMP880TD|PMT3017|PMT3037|PMT3047|PMT3057|PMT7008|PMT5887|PMT5001|PMT5002', + // http://support.lenovo.com/en_GB/downloads/default.page?# + 'LenovoTablet' => 'Lenovo TAB|Idea(Tab|Pad)( A1|A10| K1|)|ThinkPad([ ]+)?Tablet|YT3-X90L|YT3-X90F|YT3-X90X|Lenovo.*(S2109|S2110|S5000|S6000|K3011|A3000|A3500|A1000|A2107|A2109|A1107|A5500|A7600|B6000|B8000|B8080)(-|)(FL|F|HV|H|)', + // http://www.dell.com/support/home/us/en/04/Products/tab_mob/tablets + 'DellTablet' => 'Venue 11|Venue 8|Venue 7|Dell Streak 10|Dell Streak 7', + // http://www.yarvik.com/en/matrix/tablets/ + 'YarvikTablet' => 'Android.*\b(TAB210|TAB211|TAB224|TAB250|TAB260|TAB264|TAB310|TAB360|TAB364|TAB410|TAB411|TAB420|TAB424|TAB450|TAB460|TAB461|TAB464|TAB465|TAB467|TAB468|TAB07-100|TAB07-101|TAB07-150|TAB07-151|TAB07-152|TAB07-200|TAB07-201-3G|TAB07-210|TAB07-211|TAB07-212|TAB07-214|TAB07-220|TAB07-400|TAB07-485|TAB08-150|TAB08-200|TAB08-201-3G|TAB08-201-30|TAB09-100|TAB09-211|TAB09-410|TAB10-150|TAB10-201|TAB10-211|TAB10-400|TAB10-410|TAB13-201|TAB274EUK|TAB275EUK|TAB374EUK|TAB462EUK|TAB474EUK|TAB9-200)\b', + 'MedionTablet' => 'Android.*\bOYO\b|LIFE.*(P9212|P9514|P9516|S9512)|LIFETAB', + 'ArnovaTablet' => '97G4|AN10G2|AN7bG3|AN7fG3|AN8G3|AN8cG3|AN7G3|AN9G3|AN7dG3|AN7dG3ST|AN7dG3ChildPad|AN10bG3|AN10bG3DT|AN9G2', + // http://www.intenso.de/kategorie_en.php?kategorie=33 + // @todo: http://www.nbhkdz.com/read/b8e64202f92a2df129126bff.html - investigate + 'IntensoTablet' => 'INM8002KP|INM1010FP|INM805ND|Intenso Tab|TAB1004', + // IRU.ru Tablets http://www.iru.ru/catalog/soho/planetable/ + 'IRUTablet' => 'M702pro', + 'MegafonTablet' => 'MegaFon V9|\bZTE V9\b|Android.*\bMT7A\b', + // http://www.e-boda.ro/tablete-pc.html + 'EbodaTablet' => 'E-Boda (Supreme|Impresspeed|Izzycomm|Essential)', + // http://www.allview.ro/produse/droseries/lista-tablete-pc/ + 'AllViewTablet' => 'Allview.*(Viva|Alldro|City|Speed|All TV|Frenzy|Quasar|Shine|TX1|AX1|AX2)', + // http://wiki.archosfans.com/index.php?title=Main_Page + // @note Rewrite the regex format after we add more UAs. + 'ArchosTablet' => '\b(101G9|80G9|A101IT)\b|Qilive 97R|Archos5|\bARCHOS (70|79|80|90|97|101|FAMILYPAD|)(b|c|)(G10| Cobalt| TITANIUM(HD|)| Xenon| Neon|XSK| 2| XS 2| PLATINUM| CARBON|GAMEPAD)\b', + // http://www.ainol.com/plugin.php?identifier=ainol&module=product + 'AinolTablet' => 'NOVO7|NOVO8|NOVO10|Novo7Aurora|Novo7Basic|NOVO7PALADIN|novo9-Spark', + 'NokiaLumiaTablet' => 'Lumia 2520', + // @todo: inspect http://esupport.sony.com/US/p/select-system.pl?DIRECTOR=DRIVER + // Readers http://www.atsuhiro-me.net/ebook/sony-reader/sony-reader-web-browser + // http://www.sony.jp/support/tablet/ + 'SonyTablet' => 'Sony.*Tablet|Xperia Tablet|Sony Tablet S|SO-03E|SGPT12|SGPT13|SGPT114|SGPT121|SGPT122|SGPT123|SGPT111|SGPT112|SGPT113|SGPT131|SGPT132|SGPT133|SGPT211|SGPT212|SGPT213|SGP311|SGP312|SGP321|EBRD1101|EBRD1102|EBRD1201|SGP351|SGP341|SGP511|SGP512|SGP521|SGP541|SGP551|SGP621|SGP612|SOT31', + // http://www.support.philips.com/support/catalog/worldproducts.jsp?userLanguage=en&userCountry=cn&categoryid=3G_LTE_TABLET_SU_CN_CARE&title=3G%20tablets%20/%20LTE%20range&_dyncharset=UTF-8 + 'PhilipsTablet' => '\b(PI2010|PI3000|PI3100|PI3105|PI3110|PI3205|PI3210|PI3900|PI4010|PI7000|PI7100)\b', + // db + http://www.cube-tablet.com/buy-products.html + 'CubeTablet' => 'Android.*(K8GT|U9GT|U10GT|U16GT|U17GT|U18GT|U19GT|U20GT|U23GT|U30GT)|CUBE U8GT', + // http://www.cobyusa.com/?p=pcat&pcat_id=3001 + 'CobyTablet' => 'MID1042|MID1045|MID1125|MID1126|MID7012|MID7014|MID7015|MID7034|MID7035|MID7036|MID7042|MID7048|MID7127|MID8042|MID8048|MID8127|MID9042|MID9740|MID9742|MID7022|MID7010', + // http://www.match.net.cn/products.asp + 'MIDTablet' => 'M9701|M9000|M9100|M806|M1052|M806|T703|MID701|MID713|MID710|MID727|MID760|MID830|MID728|MID933|MID125|MID810|MID732|MID120|MID930|MID800|MID731|MID900|MID100|MID820|MID735|MID980|MID130|MID833|MID737|MID960|MID135|MID860|MID736|MID140|MID930|MID835|MID733|MID4X10', + // http://www.msi.com/support + // @todo Research the Windows Tablets. + 'MSITablet' => 'MSI \b(Primo 73K|Primo 73L|Primo 81L|Primo 77|Primo 93|Primo 75|Primo 76|Primo 73|Primo 81|Primo 91|Primo 90|Enjoy 71|Enjoy 7|Enjoy 10)\b', + // @todo http://www.kyoceramobile.com/support/drivers/ + // 'KyoceraTablet' => null, + // @todo http://intexuae.com/index.php/category/mobile-devices/tablets-products/ + // 'IntextTablet' => null, + // http://pdadb.net/index.php?m=pdalist&list=SMiT (NoName Chinese Tablets) + // http://www.imp3.net/14/show.php?itemid=20454 + 'SMiTTablet' => 'Android.*(\bMID\b|MID-560|MTV-T1200|MTV-PND531|MTV-P1101|MTV-PND530)', + // http://www.rock-chips.com/index.php?do=prod&pid=2 + 'RockChipTablet' => 'Android.*(RK2818|RK2808A|RK2918|RK3066)|RK2738|RK2808A', + // http://www.fly-phone.com/devices/tablets/ ; http://www.fly-phone.com/service/ + 'FlyTablet' => 'IQ310|Fly Vision', + // http://www.bqreaders.com/gb/tablets-prices-sale.html + 'bqTablet' => 'Android.*(bq)?.*(Elcano|Curie|Edison|Maxwell|Kepler|Pascal|Tesla|Hypatia|Platon|Newton|Livingstone|Cervantes|Avant|Aquaris [E|M]10)|Maxwell.*Lite|Maxwell.*Plus', + // http://www.huaweidevice.com/worldwide/productFamily.do?method=index&directoryId=5011&treeId=3290 + // http://www.huaweidevice.com/worldwide/downloadCenter.do?method=index&directoryId=3372&treeId=0&tb=1&type=software (including legacy tablets) + 'HuaweiTablet' => 'MediaPad|MediaPad 7 Youth|IDEOS S7|S7-201c|S7-202u|S7-101|S7-103|S7-104|S7-105|S7-106|S7-201|S7-Slim', + // Nec or Medias Tab + 'NecTablet' => '\bN-06D|\bN-08D', + // Pantech Tablets: http://www.pantechusa.com/phones/ + 'PantechTablet' => 'Pantech.*P4100', + // Broncho Tablets: http://www.broncho.cn/ (hard to find) + 'BronchoTablet' => 'Broncho.*(N701|N708|N802|a710)', + // http://versusuk.com/support.html + 'VersusTablet' => 'TOUCHPAD.*[78910]|\bTOUCHTAB\b', + // http://www.zync.in/index.php/our-products/tablet-phablets + 'ZyncTablet' => 'z1000|Z99 2G|z99|z930|z999|z990|z909|Z919|z900', + // http://www.positivoinformatica.com.br/www/pessoal/tablet-ypy/ + 'PositivoTablet' => 'TB07STA|TB10STA|TB07FTA|TB10FTA', + // https://www.nabitablet.com/ + 'NabiTablet' => 'Android.*\bNabi', + 'KoboTablet' => 'Kobo Touch|\bK080\b|\bVox\b Build|\bArc\b Build', + // French Danew Tablets http://www.danew.com/produits-tablette.php + 'DanewTablet' => 'DSlide.*\b(700|701R|702|703R|704|802|970|971|972|973|974|1010|1012)\b', + // Texet Tablets and Readers http://www.texet.ru/tablet/ + 'TexetTablet' => 'NaviPad|TB-772A|TM-7045|TM-7055|TM-9750|TM-7016|TM-7024|TM-7026|TM-7041|TM-7043|TM-7047|TM-8041|TM-9741|TM-9747|TM-9748|TM-9751|TM-7022|TM-7021|TM-7020|TM-7011|TM-7010|TM-7023|TM-7025|TM-7037W|TM-7038W|TM-7027W|TM-9720|TM-9725|TM-9737W|TM-1020|TM-9738W|TM-9740|TM-9743W|TB-807A|TB-771A|TB-727A|TB-725A|TB-719A|TB-823A|TB-805A|TB-723A|TB-715A|TB-707A|TB-705A|TB-709A|TB-711A|TB-890HD|TB-880HD|TB-790HD|TB-780HD|TB-770HD|TB-721HD|TB-710HD|TB-434HD|TB-860HD|TB-840HD|TB-760HD|TB-750HD|TB-740HD|TB-730HD|TB-722HD|TB-720HD|TB-700HD|TB-500HD|TB-470HD|TB-431HD|TB-430HD|TB-506|TB-504|TB-446|TB-436|TB-416|TB-146SE|TB-126SE', + // Avoid detecting 'PLAYSTATION 3' as mobile. + 'PlaystationTablet' => 'Playstation.*(Portable|Vita)', + // http://www.trekstor.de/surftabs.html + 'TrekstorTablet' => 'ST10416-1|VT10416-1|ST70408-1|ST702xx-1|ST702xx-2|ST80208|ST97216|ST70104-2|VT10416-2|ST10216-2A|SurfTab', + // http://www.pyleaudio.com/Products.aspx?%2fproducts%2fPersonal-Electronics%2fTablets + 'PyleAudioTablet' => '\b(PTBL10CEU|PTBL10C|PTBL72BC|PTBL72BCEU|PTBL7CEU|PTBL7C|PTBL92BC|PTBL92BCEU|PTBL9CEU|PTBL9CUK|PTBL9C)\b', + // http://www.advandigital.com/index.php?link=content-product&jns=JP001 + // because of the short codenames we have to include whitespaces to reduce the possible conflicts. + 'AdvanTablet' => 'Android.* \b(E3A|T3X|T5C|T5B|T3E|T3C|T3B|T1J|T1F|T2A|T1H|T1i|E1C|T1-E|T5-A|T4|E1-B|T2Ci|T1-B|T1-D|O1-A|E1-A|T1-A|T3A|T4i)\b ', + // http://www.danytech.com/category/tablet-pc + 'DanyTechTablet' => 'Genius Tab G3|Genius Tab S2|Genius Tab Q3|Genius Tab G4|Genius Tab Q4|Genius Tab G-II|Genius TAB GII|Genius TAB GIII|Genius Tab S1', + // http://www.galapad.net/product.html + 'GalapadTablet' => 'Android.*\bG1\b', + // http://www.micromaxinfo.com/tablet/funbook + 'MicromaxTablet' => 'Funbook|Micromax.*\b(P250|P560|P360|P362|P600|P300|P350|P500|P275)\b', + // http://www.karbonnmobiles.com/products_tablet.php + 'KarbonnTablet' => 'Android.*\b(A39|A37|A34|ST8|ST10|ST7|Smart Tab3|Smart Tab2)\b', + // http://www.myallfine.com/Products.asp + 'AllFineTablet' => 'Fine7 Genius|Fine7 Shine|Fine7 Air|Fine8 Style|Fine9 More|Fine10 Joy|Fine11 Wide', + // http://www.proscanvideo.com/products-search.asp?itemClass=TABLET&itemnmbr= + 'PROSCANTablet' => '\b(PEM63|PLT1023G|PLT1041|PLT1044|PLT1044G|PLT1091|PLT4311|PLT4311PL|PLT4315|PLT7030|PLT7033|PLT7033D|PLT7035|PLT7035D|PLT7044K|PLT7045K|PLT7045KB|PLT7071KG|PLT7072|PLT7223G|PLT7225G|PLT7777G|PLT7810K|PLT7849G|PLT7851G|PLT7852G|PLT8015|PLT8031|PLT8034|PLT8036|PLT8080K|PLT8082|PLT8088|PLT8223G|PLT8234G|PLT8235G|PLT8816K|PLT9011|PLT9045K|PLT9233G|PLT9735|PLT9760G|PLT9770G)\b', + // http://www.yonesnav.com/products/products.php + 'YONESTablet' => 'BQ1078|BC1003|BC1077|RK9702|BC9730|BC9001|IT9001|BC7008|BC7010|BC708|BC728|BC7012|BC7030|BC7027|BC7026', + // http://www.cjshowroom.com/eproducts.aspx?classcode=004001001 + // China manufacturer makes tablets for different small brands (eg. http://www.zeepad.net/index.html) + 'ChangJiaTablet' => 'TPC7102|TPC7103|TPC7105|TPC7106|TPC7107|TPC7201|TPC7203|TPC7205|TPC7210|TPC7708|TPC7709|TPC7712|TPC7110|TPC8101|TPC8103|TPC8105|TPC8106|TPC8203|TPC8205|TPC8503|TPC9106|TPC9701|TPC97101|TPC97103|TPC97105|TPC97106|TPC97111|TPC97113|TPC97203|TPC97603|TPC97809|TPC97205|TPC10101|TPC10103|TPC10106|TPC10111|TPC10203|TPC10205|TPC10503', + // http://www.gloryunion.cn/products.asp + // http://www.allwinnertech.com/en/apply/mobile.html + // http://www.ptcl.com.pk/pd_content.php?pd_id=284 (EVOTAB) + // @todo: Softwiner tablets? + // aka. Cute or Cool tablets. Not sure yet, must research to avoid collisions. + 'GUTablet' => 'TX-A1301|TX-M9002|Q702|kf026', // A12R|D75A|D77|D79|R83|A95|A106C|R15|A75|A76|D71|D72|R71|R73|R77|D82|R85|D92|A97|D92|R91|A10F|A77F|W71F|A78F|W78F|W81F|A97F|W91F|W97F|R16G|C72|C73E|K72|K73|R96G + // http://www.pointofview-online.com/showroom.php?shop_mode=product_listing&category_id=118 + 'PointOfViewTablet' => 'TAB-P506|TAB-navi-7-3G-M|TAB-P517|TAB-P-527|TAB-P701|TAB-P703|TAB-P721|TAB-P731N|TAB-P741|TAB-P825|TAB-P905|TAB-P925|TAB-PR945|TAB-PL1015|TAB-P1025|TAB-PI1045|TAB-P1325|TAB-PROTAB[0-9]+|TAB-PROTAB25|TAB-PROTAB26|TAB-PROTAB27|TAB-PROTAB26XL|TAB-PROTAB2-IPS9|TAB-PROTAB30-IPS9|TAB-PROTAB25XXL|TAB-PROTAB26-IPS10|TAB-PROTAB30-IPS10', + // http://www.overmax.pl/pl/katalog-produktow,p8/tablety,c14/ + // @todo: add more tests. + 'OvermaxTablet' => 'OV-(SteelCore|NewBase|Basecore|Baseone|Exellen|Quattor|EduTab|Solution|ACTION|BasicTab|TeddyTab|MagicTab|Stream|TB-08|TB-09)', + // http://hclmetablet.com/India/index.php + 'HCLTablet' => 'HCL.*Tablet|Connect-3G-2.0|Connect-2G-2.0|ME Tablet U1|ME Tablet U2|ME Tablet G1|ME Tablet X1|ME Tablet Y2|ME Tablet Sync', + // http://www.edigital.hu/Tablet_es_e-book_olvaso/Tablet-c18385.html + 'DPSTablet' => 'DPS Dream 9|DPS Dual 7', + // http://www.visture.com/index.asp + 'VistureTablet' => 'V97 HD|i75 3G|Visture V4( HD)?|Visture V5( HD)?|Visture V10', + // http://www.mijncresta.nl/tablet + 'CrestaTablet' => 'CTP(-)?810|CTP(-)?818|CTP(-)?828|CTP(-)?838|CTP(-)?888|CTP(-)?978|CTP(-)?980|CTP(-)?987|CTP(-)?988|CTP(-)?989', + // MediaTek - http://www.mediatek.com/_en/01_products/02_proSys.php?cata_sn=1&cata1_sn=1&cata2_sn=309 + 'MediatekTablet' => '\bMT8125|MT8389|MT8135|MT8377\b', + // Concorde tab + 'ConcordeTablet' => 'Concorde([ ]+)?Tab|ConCorde ReadMan', + // GoClever Tablets - http://www.goclever.com/uk/products,c1/tablet,c5/ + 'GoCleverTablet' => 'GOCLEVER TAB|A7GOCLEVER|M1042|M7841|M742|R1042BK|R1041|TAB A975|TAB A7842|TAB A741|TAB A741L|TAB M723G|TAB M721|TAB A1021|TAB I921|TAB R721|TAB I720|TAB T76|TAB R70|TAB R76.2|TAB R106|TAB R83.2|TAB M813G|TAB I721|GCTA722|TAB I70|TAB I71|TAB S73|TAB R73|TAB R74|TAB R93|TAB R75|TAB R76.1|TAB A73|TAB A93|TAB A93.2|TAB T72|TAB R83|TAB R974|TAB R973|TAB A101|TAB A103|TAB A104|TAB A104.2|R105BK|M713G|A972BK|TAB A971|TAB R974.2|TAB R104|TAB R83.3|TAB A1042', + // Modecom Tablets - http://www.modecom.eu/tablets/portal/ + 'ModecomTablet' => 'FreeTAB 9000|FreeTAB 7.4|FreeTAB 7004|FreeTAB 7800|FreeTAB 2096|FreeTAB 7.5|FreeTAB 1014|FreeTAB 1001 |FreeTAB 8001|FreeTAB 9706|FreeTAB 9702|FreeTAB 7003|FreeTAB 7002|FreeTAB 1002|FreeTAB 7801|FreeTAB 1331|FreeTAB 1004|FreeTAB 8002|FreeTAB 8014|FreeTAB 9704|FreeTAB 1003', + // Vonino Tablets - http://www.vonino.eu/tablets + 'VoninoTablet' => '\b(Argus[ _]?S|Diamond[ _]?79HD|Emerald[ _]?78E|Luna[ _]?70C|Onyx[ _]?S|Onyx[ _]?Z|Orin[ _]?HD|Orin[ _]?S|Otis[ _]?S|SpeedStar[ _]?S|Magnet[ _]?M9|Primus[ _]?94[ _]?3G|Primus[ _]?94HD|Primus[ _]?QS|Android.*\bQ8\b|Sirius[ _]?EVO[ _]?QS|Sirius[ _]?QS|Spirit[ _]?S)\b', + // ECS Tablets - http://www.ecs.com.tw/ECSWebSite/Product/Product_Tablet_List.aspx?CategoryID=14&MenuID=107&childid=M_107&LanID=0 + 'ECSTablet' => 'V07OT2|TM105A|S10OT1|TR10CS1', + // Storex Tablets - http://storex.fr/espace_client/support.html + // @note: no need to add all the tablet codes since they are guided by the first regex. + 'StorexTablet' => 'eZee[_\']?(Tab|Go)[0-9]+|TabLC7|Looney Tunes Tab', + // Generic Vodafone tablets. + 'VodafoneTablet' => 'SmartTab([ ]+)?[0-9]+|SmartTabII10|SmartTabII7|VF-1497', + // French tablets - Essentiel B http://www.boulanger.fr/tablette_tactile_e-book/tablette_tactile_essentiel_b/cl_68908.htm?multiChoiceToDelete=brand&mc_brand=essentielb + // Aka: http://www.essentielb.fr/ + 'EssentielBTablet' => 'Smart[ \']?TAB[ ]+?[0-9]+|Family[ \']?TAB2', + // Ross & Moor - http://ross-moor.ru/ + 'RossMoorTablet' => 'RM-790|RM-997|RMD-878G|RMD-974R|RMT-705A|RMT-701|RME-601|RMT-501|RMT-711', + // i-mobile http://product.i-mobilephone.com/Mobile_Device + 'iMobileTablet' => 'i-mobile i-note', + // http://www.tolino.de/de/vergleichen/ + 'TolinoTablet' => 'tolino tab [0-9.]+|tolino shine', + // AudioSonic - a Kmart brand + // http://www.kmart.com.au/webapp/wcs/stores/servlet/Search?langId=-1&storeId=10701&catalogId=10001&categoryId=193001&pageSize=72¤tPage=1&searchCategory=193001%2b4294965664&sortBy=p_MaxPrice%7c1 + 'AudioSonicTablet' => '\bC-22Q|T7-QC|T-17B|T-17P\b', + // AMPE Tablets - http://www.ampe.com.my/product-category/tablets/ + // @todo: add them gradually to avoid conflicts. + 'AMPETablet' => 'Android.* A78 ', + // Skk Mobile - http://skkmobile.com.ph/product_tablets.php + 'SkkTablet' => 'Android.* (SKYPAD|PHOENIX|CYCLOPS)', + // Tecno Mobile (only tablet) - http://www.tecno-mobile.com/index.php/product?filterby=smart&list_order=all&page=1 + 'TecnoTablet' => 'TECNO P9', + // JXD (consoles & tablets) - http://jxd.hk/products.asp?selectclassid=009008&clsid=3 + 'JXDTablet' => 'Android.* \b(F3000|A3300|JXD5000|JXD3000|JXD2000|JXD300B|JXD300|S5800|S7800|S602b|S5110b|S7300|S5300|S602|S603|S5100|S5110|S601|S7100a|P3000F|P3000s|P101|P200s|P1000m|P200m|P9100|P1000s|S6600b|S908|P1000|P300|S18|S6600|S9100)\b', + // i-Joy tablets - http://www.i-joy.es/en/cat/products/tablets/ + 'iJoyTablet' => 'Tablet (Spirit 7|Essentia|Galatea|Fusion|Onix 7|Landa|Titan|Scooby|Deox|Stella|Themis|Argon|Unique 7|Sygnus|Hexen|Finity 7|Cream|Cream X2|Jade|Neon 7|Neron 7|Kandy|Scape|Saphyr 7|Rebel|Biox|Rebel|Rebel 8GB|Myst|Draco 7|Myst|Tab7-004|Myst|Tadeo Jones|Tablet Boing|Arrow|Draco Dual Cam|Aurix|Mint|Amity|Revolution|Finity 9|Neon 9|T9w|Amity 4GB Dual Cam|Stone 4GB|Stone 8GB|Andromeda|Silken|X2|Andromeda II|Halley|Flame|Saphyr 9,7|Touch 8|Planet|Triton|Unique 10|Hexen 10|Memphis 4GB|Memphis 8GB|Onix 10)', + // http://www.intracon.eu/tablet + 'FX2Tablet' => 'FX2 PAD7|FX2 PAD10', + // http://www.xoro.de/produkte/ + // @note: Might be the same brand with 'Simply tablets' + 'XoroTablet' => 'KidsPAD 701|PAD[ ]?712|PAD[ ]?714|PAD[ ]?716|PAD[ ]?717|PAD[ ]?718|PAD[ ]?720|PAD[ ]?721|PAD[ ]?722|PAD[ ]?790|PAD[ ]?792|PAD[ ]?900|PAD[ ]?9715D|PAD[ ]?9716DR|PAD[ ]?9718DR|PAD[ ]?9719QR|PAD[ ]?9720QR|TelePAD1030|Telepad1032|TelePAD730|TelePAD731|TelePAD732|TelePAD735Q|TelePAD830|TelePAD9730|TelePAD795|MegaPAD 1331|MegaPAD 1851|MegaPAD 2151', + // http://www1.viewsonic.com/products/computing/tablets/ + 'ViewsonicTablet' => 'ViewPad 10pi|ViewPad 10e|ViewPad 10s|ViewPad E72|ViewPad7|ViewPad E100|ViewPad 7e|ViewSonic VB733|VB100a', + // http://www.odys.de/web/internet-tablet_en.html + 'OdysTablet' => 'LOOX|XENO10|ODYS[ -](Space|EVO|Xpress|NOON)|\bXELIO\b|Xelio10Pro|XELIO7PHONETAB|XELIO10EXTREME|XELIOPT2|NEO_QUAD10', + // http://www.captiva-power.de/products.html#tablets-en + 'CaptivaTablet' => 'CAPTIVA PAD', + // IconBIT - http://www.iconbit.com/products/tablets/ + 'IconbitTablet' => 'NetTAB|NT-3702|NT-3702S|NT-3702S|NT-3603P|NT-3603P|NT-0704S|NT-0704S|NT-3805C|NT-3805C|NT-0806C|NT-0806C|NT-0909T|NT-0909T|NT-0907S|NT-0907S|NT-0902S|NT-0902S', + // http://www.teclast.com/topic.php?channelID=70&topicID=140&pid=63 + 'TeclastTablet' => 'T98 4G|\bP80\b|\bX90HD\b|X98 Air|X98 Air 3G|\bX89\b|P80 3G|\bX80h\b|P98 Air|\bX89HD\b|P98 3G|\bP90HD\b|P89 3G|X98 3G|\bP70h\b|P79HD 3G|G18d 3G|\bP79HD\b|\bP89s\b|\bA88\b|\bP10HD\b|\bP19HD\b|G18 3G|\bP78HD\b|\bA78\b|\bP75\b|G17s 3G|G17h 3G|\bP85t\b|\bP90\b|\bP11\b|\bP98t\b|\bP98HD\b|\bG18d\b|\bP85s\b|\bP11HD\b|\bP88s\b|\bA80HD\b|\bA80se\b|\bA10h\b|\bP89\b|\bP78s\b|\bG18\b|\bP85\b|\bA70h\b|\bA70\b|\bG17\b|\bP18\b|\bA80s\b|\bA11s\b|\bP88HD\b|\bA80h\b|\bP76s\b|\bP76h\b|\bP98\b|\bA10HD\b|\bP78\b|\bP88\b|\bA11\b|\bA10t\b|\bP76a\b|\bP76t\b|\bP76e\b|\bP85HD\b|\bP85a\b|\bP86\b|\bP75HD\b|\bP76v\b|\bA12\b|\bP75a\b|\bA15\b|\bP76Ti\b|\bP81HD\b|\bA10\b|\bT760VE\b|\bT720HD\b|\bP76\b|\bP73\b|\bP71\b|\bP72\b|\bT720SE\b|\bC520Ti\b|\bT760\b|\bT720VE\b|T720-3GE|T720-WiFi', + // Onda - http://www.onda-tablet.com/buy-android-onda.html?dir=desc&limit=all&order=price + 'OndaTablet' => '\b(V975i|Vi30|VX530|V701|Vi60|V701s|Vi50|V801s|V719|Vx610w|VX610W|V819i|Vi10|VX580W|Vi10|V711s|V813|V811|V820w|V820|Vi20|V711|VI30W|V712|V891w|V972|V819w|V820w|Vi60|V820w|V711|V813s|V801|V819|V975s|V801|V819|V819|V818|V811|V712|V975m|V101w|V961w|V812|V818|V971|V971s|V919|V989|V116w|V102w|V973|Vi40)\b[\s]+', + 'JaytechTablet' => 'TPC-PA762', + 'BlaupunktTablet' => 'Endeavour 800NG|Endeavour 1010', + // http://www.digma.ru/support/download/ + // @todo: Ebooks also (if requested) + 'DigmaTablet' => '\b(iDx10|iDx9|iDx8|iDx7|iDxD7|iDxD8|iDsQ8|iDsQ7|iDsQ8|iDsD10|iDnD7|3TS804H|iDsQ11|iDj7|iDs10)\b', + // http://www.evolioshop.com/ro/tablete-pc.html + // http://www.evolio.ro/support/downloads_static.html?cat=2 + // @todo: Research some more + 'EvolioTablet' => 'ARIA_Mini_wifi|Aria[ _]Mini|Evolio X10|Evolio X7|Evolio X8|\bEvotab\b|\bNeura\b', + // @todo http://www.lavamobiles.com/tablets-data-cards + 'LavaTablet' => 'QPAD E704|\bIvoryS\b|E-TAB IVORY|\bE-TAB\b', + // http://www.breezetablet.com/ + 'AocTablet' => 'MW0811|MW0812|MW0922|MTK8382|MW1031|MW0831|MW0821|MW0931|MW0712', + // http://www.mpmaneurope.com/en/products/internet-tablets-14/android-tablets-14/ + 'MpmanTablet' => 'MP11 OCTA|MP10 OCTA|MPQC1114|MPQC1004|MPQC994|MPQC974|MPQC973|MPQC804|MPQC784|MPQC780|\bMPG7\b|MPDCG75|MPDCG71|MPDC1006|MP101DC|MPDC9000|MPDC905|MPDC706HD|MPDC706|MPDC705|MPDC110|MPDC100|MPDC99|MPDC97|MPDC88|MPDC8|MPDC77|MP709|MID701|MID711|MID170|MPDC703|MPQC1010', + // https://www.celkonmobiles.com/?_a=categoryphones&sid=2 + 'CelkonTablet' => 'CT695|CT888|CT[\s]?910|CT7 Tab|CT9 Tab|CT3 Tab|CT2 Tab|CT1 Tab|C820|C720|\bCT-1\b', + // http://www.wolderelectronics.com/productos/manuales-y-guias-rapidas/categoria-2-miTab + 'WolderTablet' => 'miTab \b(DIAMOND|SPACE|BROOKLYN|NEO|FLY|MANHATTAN|FUNK|EVOLUTION|SKY|GOCAR|IRON|GENIUS|POP|MINT|EPSILON|BROADWAY|JUMP|HOP|LEGEND|NEW AGE|LINE|ADVANCE|FEEL|FOLLOW|LIKE|LINK|LIVE|THINK|FREEDOM|CHICAGO|CLEVELAND|BALTIMORE-GH|IOWA|BOSTON|SEATTLE|PHOENIX|DALLAS|IN 101|MasterChef)\b', + // http://www.mi.com/en + 'MiTablet' => '\bMI PAD\b|\bHM NOTE 1W\b', + // http://www.nbru.cn/index.html + 'NibiruTablet' => 'Nibiru M1|Nibiru Jupiter One', + // http://navroad.com/products/produkty/tablety/ + 'NexoTablet' => 'NEXO NOVA|NEXO 10|NEXO AVIO|NEXO FREE|NEXO GO|NEXO EVO|NEXO 3G|NEXO SMART|NEXO KIDDO|NEXO MOBI', + // http://leader-online.com/new_site/product-category/tablets/ + // http://www.leader-online.net.au/List/Tablet + 'LeaderTablet' => 'TBLT10Q|TBLT10I|TBL-10WDKB|TBL-10WDKBO2013|TBL-W230V2|TBL-W450|TBL-W500|SV572|TBLT7I|TBA-AC7-8G|TBLT79|TBL-8W16|TBL-10W32|TBL-10WKB|TBL-W100', + // http://www.datawind.com/ubislate/ + 'UbislateTablet' => 'UbiSlate[\s]?7C', + // http://www.pocketbook-int.com/ru/support + 'PocketBookTablet' => 'Pocketbook', + // http://www.kocaso.com/product_tablet.html + 'KocasoTablet' => '\b(TB-1207)\b', + // http://global.hisense.com/product/asia/tablet/Sero7/201412/t20141215_91832.htm + 'HisenseTablet' => '\b(F5281|E2371)\b', + // http://www.tesco.com/direct/hudl/ + 'Hudl' => 'Hudl HT7S3|Hudl 2', + // http://www.telstra.com.au/home-phone/thub-2/ + 'TelstraTablet' => 'T-Hub2', + 'GenericTablet' => 'Android.*\b97D\b|Tablet(?!.*PC)|BNTV250A|MID-WCDMA|LogicPD Zoom2|\bA7EB\b|CatNova8|A1_07|CT704|CT1002|\bM721\b|rk30sdk|\bEVOTAB\b|M758A|ET904|ALUMIUM10|Smartfren Tab|Endeavour 1010|Tablet-PC-4|Tagi Tab|\bM6pro\b|CT1020W|arc 10HD|\bTP750\b' + ); + + /** + * List of mobile Operating Systems. + * + * @var array + */ + protected static $operatingSystems = array( + 'AndroidOS' => 'Android', + 'BlackBerryOS' => 'blackberry|\bBB10\b|rim tablet os', + 'PalmOS' => 'PalmOS|avantgo|blazer|elaine|hiptop|palm|plucker|xiino', + 'SymbianOS' => 'Symbian|SymbOS|Series60|Series40|SYB-[0-9]+|\bS60\b', + // @reference: http://en.wikipedia.org/wiki/Windows_Mobile + 'WindowsMobileOS' => 'Windows CE.*(PPC|Smartphone|Mobile|[0-9]{3}x[0-9]{3})|Window Mobile|Windows Phone [0-9.]+|WCE;', + // @reference: http://en.wikipedia.org/wiki/Windows_Phone + // http://wifeng.cn/?r=blog&a=view&id=106 + // http://nicksnettravels.builttoroam.com/post/2011/01/10/Bogus-Windows-Phone-7-User-Agent-String.aspx + // http://msdn.microsoft.com/library/ms537503.aspx + // https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx + 'WindowsPhoneOS' => 'Windows Phone 10.0|Windows Phone 8.1|Windows Phone 8.0|Windows Phone OS|XBLWP7|ZuneWP7|Windows NT 6.[23]; ARM;', + 'iOS' => '\biPhone.*Mobile|\biPod|\biPad', + // http://en.wikipedia.org/wiki/MeeGo + // @todo: research MeeGo in UAs + 'MeeGoOS' => 'MeeGo', + // http://en.wikipedia.org/wiki/Maemo + // @todo: research Maemo in UAs + 'MaemoOS' => 'Maemo', + 'JavaOS' => 'J2ME/|\bMIDP\b|\bCLDC\b', // '|Java/' produces bug #135 + 'webOS' => 'webOS|hpwOS', + 'badaOS' => '\bBada\b', + 'BREWOS' => 'BREW', + ); + + /** + * List of mobile User Agents. + * + * IMPORTANT: This is a list of only mobile browsers. + * Mobile Detect 2.x supports only mobile browsers, + * it was never designed to detect all browsers. + * The change will come in 2017 in the 3.x release for PHP7. + * + * @var array + */ + protected static $browsers = array( + //'Vivaldi' => 'Vivaldi', + // @reference: https://developers.google.com/chrome/mobile/docs/user-agent + 'Chrome' => '\bCrMo\b|CriOS|Android.*Chrome/[.0-9]* (Mobile)?', + 'Dolfin' => '\bDolfin\b', + 'Opera' => 'Opera.*Mini|Opera.*Mobi|Android.*Opera|Mobile.*OPR/[0-9.]+|Coast/[0-9.]+', + 'Skyfire' => 'Skyfire', + 'Edge' => 'Mobile Safari/[.0-9]* Edge', + 'IE' => 'IEMobile|MSIEMobile', // |Trident/[.0-9]+ + 'Firefox' => 'fennec|firefox.*maemo|(Mobile|Tablet).*Firefox|Firefox.*Mobile|FxiOS', + 'Bolt' => 'bolt', + 'TeaShark' => 'teashark', + 'Blazer' => 'Blazer', + // @reference: http://developer.apple.com/library/safari/#documentation/AppleApplications/Reference/SafariWebContent/OptimizingforSafarioniPhone/OptimizingforSafarioniPhone.html#//apple_ref/doc/uid/TP40006517-SW3 + 'Safari' => 'Version.*Mobile.*Safari|Safari.*Mobile|MobileSafari', + // http://en.wikipedia.org/wiki/Midori_(web_browser) + //'Midori' => 'midori', + //'Tizen' => 'Tizen', + 'UCBrowser' => 'UC.*Browser|UCWEB', + 'baiduboxapp' => 'baiduboxapp', + 'baidubrowser' => 'baidubrowser', + // https://github.com/serbanghita/Mobile-Detect/issues/7 + 'DiigoBrowser' => 'DiigoBrowser', + // http://www.puffinbrowser.com/index.php + 'Puffin' => 'Puffin', + // http://mercury-browser.com/index.html + 'Mercury' => '\bMercury\b', + // http://en.wikipedia.org/wiki/Obigo_Browser + 'ObigoBrowser' => 'Obigo', + // http://en.wikipedia.org/wiki/NetFront + 'NetFront' => 'NF-Browser', + // @reference: http://en.wikipedia.org/wiki/Minimo + // http://en.wikipedia.org/wiki/Vision_Mobile_Browser + 'GenericBrowser' => 'NokiaBrowser|OviBrowser|OneBrowser|TwonkyBeamBrowser|SEMC.*Browser|FlyFlow|Minimo|NetFront|Novarra-Vision|MQQBrowser|MicroMessenger', + // @reference: https://en.wikipedia.org/wiki/Pale_Moon_(web_browser) + 'PaleMoon' => 'Android.*PaleMoon|Mobile.*PaleMoon', + ); + + /** + * Utilities. + * + * @var array + */ + protected static $utilities = array( + // Experimental. When a mobile device wants to switch to 'Desktop Mode'. + // http://scottcate.com/technology/windows-phone-8-ie10-desktop-or-mobile/ + // https://github.com/serbanghita/Mobile-Detect/issues/57#issuecomment-15024011 + // https://developers.facebook.com/docs/sharing/best-practices + 'Bot' => 'Googlebot|facebookexternalhit|AdsBot-Google|Google Keyword Suggestion|Facebot|YandexBot|YandexMobileBot|bingbot|ia_archiver|AhrefsBot|Ezooms|GSLFbot|WBSearchBot|Twitterbot|TweetmemeBot|Twikle|PaperLiBot|Wotbox|UnwindFetchor|Exabot|MJ12bot|YandexImages|TurnitinBot|Pingdom', + 'MobileBot' => 'Googlebot-Mobile|AdsBot-Google-Mobile|YahooSeeker/M1A1-R2D2', + 'DesktopMode' => 'WPDesktop', + 'TV' => 'SonyDTV|HbbTV', // experimental + 'WebKit' => '(webkit)[ /]([\w.]+)', + // @todo: Include JXD consoles. + 'Console' => '\b(Nintendo|Nintendo WiiU|Nintendo 3DS|PLAYSTATION|Xbox)\b', + 'Watch' => 'SM-V700', + ); + + /** + * All possible HTTP headers that represent the + * User-Agent string. + * + * @var array + */ + protected static $uaHttpHeaders = array( + // The default User-Agent string. + 'HTTP_USER_AGENT', + // Header can occur on devices using Opera Mini. + 'HTTP_X_OPERAMINI_PHONE_UA', + // Vodafone specific header: http://www.seoprinciple.com/mobile-web-community-still-angry-at-vodafone/24/ + 'HTTP_X_DEVICE_USER_AGENT', + 'HTTP_X_ORIGINAL_USER_AGENT', + 'HTTP_X_SKYFIRE_PHONE', + 'HTTP_X_BOLT_PHONE_UA', + 'HTTP_DEVICE_STOCK_UA', + 'HTTP_X_UCBROWSER_DEVICE_UA' + ); + + /** + * The individual segments that could exist in a User-Agent string. VER refers to the regular + * expression defined in the constant self::VER. + * + * @var array + */ + protected static $properties = array( + + // Build + 'Mobile' => 'Mobile/[VER]', + 'Build' => 'Build/[VER]', + 'Version' => 'Version/[VER]', + 'VendorID' => 'VendorID/[VER]', + + // Devices + 'iPad' => 'iPad.*CPU[a-z ]+[VER]', + 'iPhone' => 'iPhone.*CPU[a-z ]+[VER]', + 'iPod' => 'iPod.*CPU[a-z ]+[VER]', + //'BlackBerry' => array('BlackBerry[VER]', 'BlackBerry [VER];'), + 'Kindle' => 'Kindle/[VER]', + + // Browser + 'Chrome' => array('Chrome/[VER]', 'CriOS/[VER]', 'CrMo/[VER]'), + 'Coast' => array('Coast/[VER]'), + 'Dolfin' => 'Dolfin/[VER]', + // @reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent/Firefox + 'Firefox' => array('Firefox/[VER]', 'FxiOS/[VER]'), + 'Fennec' => 'Fennec/[VER]', + // http://msdn.microsoft.com/en-us/library/ms537503(v=vs.85).aspx + // https://msdn.microsoft.com/en-us/library/ie/hh869301(v=vs.85).aspx + 'Edge' => 'Edge/[VER]', + 'IE' => array('IEMobile/[VER];', 'IEMobile [VER]', 'MSIE [VER];', 'Trident/[0-9.]+;.*rv:[VER]'), + // http://en.wikipedia.org/wiki/NetFront + 'NetFront' => 'NetFront/[VER]', + 'NokiaBrowser' => 'NokiaBrowser/[VER]', + 'Opera' => array( ' OPR/[VER]', 'Opera Mini/[VER]', 'Version/[VER]' ), + 'Opera Mini' => 'Opera Mini/[VER]', + 'Opera Mobi' => 'Version/[VER]', + 'UC Browser' => 'UC Browser[VER]', + 'MQQBrowser' => 'MQQBrowser/[VER]', + 'MicroMessenger' => 'MicroMessenger/[VER]', + 'baiduboxapp' => 'baiduboxapp/[VER]', + 'baidubrowser' => 'baidubrowser/[VER]', + 'SamsungBrowser' => 'SamsungBrowser/[VER]', + 'Iron' => 'Iron/[VER]', + // @note: Safari 7534.48.3 is actually Version 5.1. + // @note: On BlackBerry the Version is overwriten by the OS. + 'Safari' => array( 'Version/[VER]', 'Safari/[VER]' ), + 'Skyfire' => 'Skyfire/[VER]', + 'Tizen' => 'Tizen/[VER]', + 'Webkit' => 'webkit[ /][VER]', + 'PaleMoon' => 'PaleMoon/[VER]', + + // Engine + 'Gecko' => 'Gecko/[VER]', + 'Trident' => 'Trident/[VER]', + 'Presto' => 'Presto/[VER]', + 'Goanna' => 'Goanna/[VER]', + + // OS + 'iOS' => ' \bi?OS\b [VER][ ;]{1}', + 'Android' => 'Android [VER]', + 'BlackBerry' => array('BlackBerry[\w]+/[VER]', 'BlackBerry.*Version/[VER]', 'Version/[VER]'), + 'BREW' => 'BREW [VER]', + 'Java' => 'Java/[VER]', + // @reference: http://windowsteamblog.com/windows_phone/b/wpdev/archive/2011/08/29/introducing-the-ie9-on-windows-phone-mango-user-agent-string.aspx + // @reference: http://en.wikipedia.org/wiki/Windows_NT#Releases + 'Windows Phone OS' => array( 'Windows Phone OS [VER]', 'Windows Phone [VER]'), + 'Windows Phone' => 'Windows Phone [VER]', + 'Windows CE' => 'Windows CE/[VER]', + // http://social.msdn.microsoft.com/Forums/en-US/windowsdeveloperpreviewgeneral/thread/6be392da-4d2f-41b4-8354-8dcee20c85cd + 'Windows NT' => 'Windows NT [VER]', + 'Symbian' => array('SymbianOS/[VER]', 'Symbian/[VER]'), + 'webOS' => array('webOS/[VER]', 'hpwOS/[VER];'), + ); + + /** + * Construct an instance of this class. + * + * @param array $headers Specify the headers as injection. Should be PHP _SERVER flavored. + * If left empty, will use the global _SERVER['HTTP_*'] vars instead. + * @param string $userAgent Inject the User-Agent header. If null, will use HTTP_USER_AGENT + * from the $headers array instead. + */ + public function __construct( + array $headers = null, + $userAgent = null + ) { + $this->setHttpHeaders($headers); + $this->setUserAgent($userAgent); + } + + /** + * Get the current script version. + * This is useful for the demo.php file, + * so people can check on what version they are testing + * for mobile devices. + * + * @return string The version number in semantic version format. + */ + public static function getScriptVersion() + { + return self::VERSION; + } + + /** + * Set the HTTP Headers. Must be PHP-flavored. This method will reset existing headers. + * + * @param array $httpHeaders The headers to set. If null, then using PHP's _SERVER to extract + * the headers. The default null is left for backwards compatibility. + */ + public function setHttpHeaders($httpHeaders = null) + { + // use global _SERVER if $httpHeaders aren't defined + if (!is_array($httpHeaders) || !count($httpHeaders)) { + $httpHeaders = $_SERVER; + } + + // clear existing headers + $this->httpHeaders = array(); + + // Only save HTTP headers. In PHP land, that means only _SERVER vars that + // start with HTTP_. + foreach ($httpHeaders as $key => $value) { + if (substr($key, 0, 5) === 'HTTP_') { + $this->httpHeaders[$key] = $value; + } + } + + // In case we're dealing with CloudFront, we need to know. + $this->setCfHeaders($httpHeaders); + } + + /** + * Retrieves the HTTP headers. + * + * @return array + */ + public function getHttpHeaders() + { + return $this->httpHeaders; + } + + /** + * Retrieves a particular header. If it doesn't exist, no exception/error is caused. + * Simply null is returned. + * + * @param string $header The name of the header to retrieve. Can be HTTP compliant such as + * "User-Agent" or "X-Device-User-Agent" or can be php-esque with the + * all-caps, HTTP_ prefixed, underscore seperated awesomeness. + * + * @return string|null The value of the header. + */ + public function getHttpHeader($header) + { + // are we using PHP-flavored headers? + if (strpos($header, '_') === false) { + $header = str_replace('-', '_', $header); + $header = strtoupper($header); + } + + // test the alternate, too + $altHeader = 'HTTP_' . $header; + + //Test both the regular and the HTTP_ prefix + if (isset($this->httpHeaders[$header])) { + return $this->httpHeaders[$header]; + } elseif (isset($this->httpHeaders[$altHeader])) { + return $this->httpHeaders[$altHeader]; + } + + return null; + } + + public function getMobileHeaders() + { + return self::$mobileHeaders; + } + + /** + * Get all possible HTTP headers that + * can contain the User-Agent string. + * + * @return array List of HTTP headers. + */ + public function getUaHttpHeaders() + { + return self::$uaHttpHeaders; + } + + + /** + * Set CloudFront headers + * http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/header-caching.html#header-caching-web-device + * + * @param array $cfHeaders List of HTTP headers + * + * @return boolean If there were CloudFront headers to be set + */ + public function setCfHeaders($cfHeaders = null) { + // use global _SERVER if $cfHeaders aren't defined + if (!is_array($cfHeaders) || !count($cfHeaders)) { + $cfHeaders = $_SERVER; + } + + // clear existing headers + $this->cloudfrontHeaders = array(); + + // Only save CLOUDFRONT headers. In PHP land, that means only _SERVER vars that + // start with cloudfront-. + $response = false; + foreach ($cfHeaders as $key => $value) { + if (substr(strtolower($key), 0, 16) === 'http_cloudfront_') { + $this->cloudfrontHeaders[strtoupper($key)] = $value; + $response = true; + } + } + + return $response; + } + + /** + * Retrieves the cloudfront headers. + * + * @return array + */ + public function getCfHeaders() + { + return $this->cloudfrontHeaders; + } + + /** + * Set the User-Agent to be used. + * + * @param string $userAgent The user agent string to set. + * + * @return string|null + */ + public function setUserAgent($userAgent = null) + { + // Invalidate cache due to #375 + $this->cache = array(); + + if (false === empty($userAgent)) { + return $this->userAgent = $userAgent; + } else { + $this->userAgent = null; + foreach ($this->getUaHttpHeaders() as $altHeader) { + if (false === empty($this->httpHeaders[$altHeader])) { // @todo: should use getHttpHeader(), but it would be slow. (Serban) + $this->userAgent .= $this->httpHeaders[$altHeader] . " "; + } + } + + if (!empty($this->userAgent)) { + return $this->userAgent = trim($this->userAgent); + } + } + + if (count($this->getCfHeaders()) > 0) { + return $this->userAgent = 'Amazon CloudFront'; + } + return $this->userAgent = null; + } + + /** + * Retrieve the User-Agent. + * + * @return string|null The user agent if it's set. + */ + public function getUserAgent() + { + return $this->userAgent; + } + + /** + * Set the detection type. Must be one of self::DETECTION_TYPE_MOBILE or + * self::DETECTION_TYPE_EXTENDED. Otherwise, nothing is set. + * + * @deprecated since version 2.6.9 + * + * @param string $type The type. Must be a self::DETECTION_TYPE_* constant. The default + * parameter is null which will default to self::DETECTION_TYPE_MOBILE. + */ + public function setDetectionType($type = null) + { + if ($type === null) { + $type = self::DETECTION_TYPE_MOBILE; + } + + if ($type !== self::DETECTION_TYPE_MOBILE && $type !== self::DETECTION_TYPE_EXTENDED) { + return; + } + + $this->detectionType = $type; + } + + public function getMatchingRegex() + { + return $this->matchingRegex; + } + + public function getMatchesArray() + { + return $this->matchesArray; + } + + /** + * Retrieve the list of known phone devices. + * + * @return array List of phone devices. + */ + public static function getPhoneDevices() + { + return self::$phoneDevices; + } + + /** + * Retrieve the list of known tablet devices. + * + * @return array List of tablet devices. + */ + public static function getTabletDevices() + { + return self::$tabletDevices; + } + + /** + * Alias for getBrowsers() method. + * + * @return array List of user agents. + */ + public static function getUserAgents() + { + return self::getBrowsers(); + } + + /** + * Retrieve the list of known browsers. Specifically, the user agents. + * + * @return array List of browsers / user agents. + */ + public static function getBrowsers() + { + return self::$browsers; + } + + /** + * Retrieve the list of known utilities. + * + * @return array List of utilities. + */ + public static function getUtilities() + { + return self::$utilities; + } + + /** + * Method gets the mobile detection rules. This method is used for the magic methods $detect->is*(). + * + * @deprecated since version 2.6.9 + * + * @return array All the rules (but not extended). + */ + public static function getMobileDetectionRules() + { + static $rules; + + if (!$rules) { + $rules = array_merge( + self::$phoneDevices, + self::$tabletDevices, + self::$operatingSystems, + self::$browsers + ); + } + + return $rules; + + } + + /** + * Method gets the mobile detection rules + utilities. + * The reason this is separate is because utilities rules + * don't necessary imply mobile. This method is used inside + * the new $detect->is('stuff') method. + * + * @deprecated since version 2.6.9 + * + * @return array All the rules + extended. + */ + public function getMobileDetectionRulesExtended() + { + static $rules; + + if (!$rules) { + // Merge all rules together. + $rules = array_merge( + self::$phoneDevices, + self::$tabletDevices, + self::$operatingSystems, + self::$browsers, + self::$utilities + ); + } + + return $rules; + } + + /** + * Retrieve the current set of rules. + * + * @deprecated since version 2.6.9 + * + * @return array + */ + public function getRules() + { + if ($this->detectionType == self::DETECTION_TYPE_EXTENDED) { + return self::getMobileDetectionRulesExtended(); + } else { + return self::getMobileDetectionRules(); + } + } + + /** + * Retrieve the list of mobile operating systems. + * + * @return array The list of mobile operating systems. + */ + public static function getOperatingSystems() + { + return self::$operatingSystems; + } + + /** + * Check the HTTP headers for signs of mobile. + * This is the fastest mobile check possible; it's used + * inside isMobile() method. + * + * @return bool + */ + public function checkHttpHeadersForMobile() + { + + foreach ($this->getMobileHeaders() as $mobileHeader => $matchType) { + if (isset($this->httpHeaders[$mobileHeader])) { + if (is_array($matchType['matches'])) { + foreach ($matchType['matches'] as $_match) { + if (strpos($this->httpHeaders[$mobileHeader], $_match) !== false) { + return true; + } + } + + return false; + } else { + return true; + } + } + } + + return false; + + } + + /** + * Magic overloading method. + * + * @method boolean is[...]() + * @param string $name + * @param array $arguments + * @return mixed + * @throws BadMethodCallException when the method doesn't exist and doesn't start with 'is' + */ + public function __call($name, $arguments) + { + // make sure the name starts with 'is', otherwise + if (substr($name, 0, 2) !== 'is') { + throw new BadMethodCallException("No such method exists: $name"); + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + $key = substr($name, 2); + + return $this->matchUAAgainstKey($key); + } + + /** + * Find a detection rule that matches the current User-agent. + * + * @param null $userAgent deprecated + * @return boolean + */ + protected function matchDetectionRulesAgainstUA($userAgent = null) + { + // Begin general search. + foreach ($this->getRules() as $_regex) { + if (empty($_regex)) { + continue; + } + + if ($this->match($_regex, $userAgent)) { + return true; + } + } + + return false; + } + + /** + * Search for a certain key in the rules array. + * If the key is found then try to match the corresponding + * regex against the User-Agent. + * + * @param string $key + * + * @return boolean + */ + protected function matchUAAgainstKey($key) + { + // Make the keys lowercase so we can match: isIphone(), isiPhone(), isiphone(), etc. + $key = strtolower($key); + if (false === isset($this->cache[$key])) { + + // change the keys to lower case + $_rules = array_change_key_case($this->getRules()); + + if (false === empty($_rules[$key])) { + $this->cache[$key] = $this->match($_rules[$key]); + } + + if (false === isset($this->cache[$key])) { + $this->cache[$key] = false; + } + } + + return $this->cache[$key]; + } + + /** + * Check if the device is mobile. + * Returns true if any type of mobile device detected, including special ones + * @param null $userAgent deprecated + * @param null $httpHeaders deprecated + * @return bool + */ + public function isMobile($userAgent = null, $httpHeaders = null) + { + + if ($httpHeaders) { + $this->setHttpHeaders($httpHeaders); + } + + if ($userAgent) { + $this->setUserAgent($userAgent); + } + + // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' + if ($this->getUserAgent() === 'Amazon CloudFront') { + $cfHeaders = $this->getCfHeaders(); + if(array_key_exists('HTTP_CLOUDFRONT_IS_MOBILE_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_MOBILE_VIEWER'] === 'true') { + return true; + } + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + if ($this->checkHttpHeadersForMobile()) { + return true; + } else { + return $this->matchDetectionRulesAgainstUA(); + } + + } + + /** + * Check if the device is a tablet. + * Return true if any type of tablet device is detected. + * + * @param string $userAgent deprecated + * @param array $httpHeaders deprecated + * @return bool + */ + public function isTablet($userAgent = null, $httpHeaders = null) + { + // Check specifically for cloudfront headers if the useragent === 'Amazon CloudFront' + if ($this->getUserAgent() === 'Amazon CloudFront') { + $cfHeaders = $this->getCfHeaders(); + if(array_key_exists('HTTP_CLOUDFRONT_IS_TABLET_VIEWER', $cfHeaders) && $cfHeaders['HTTP_CLOUDFRONT_IS_TABLET_VIEWER'] === 'true') { + return true; + } + } + + $this->setDetectionType(self::DETECTION_TYPE_MOBILE); + + foreach (self::$tabletDevices as $_regex) { + if ($this->match($_regex, $userAgent)) { + return true; + } + } + + return false; + } + + /** + * This method checks for a certain property in the + * userAgent. + * @todo: The httpHeaders part is not yet used. + * + * @param string $key + * @param string $userAgent deprecated + * @param string $httpHeaders deprecated + * @return bool|int|null + */ + public function is($key, $userAgent = null, $httpHeaders = null) + { + // Set the UA and HTTP headers only if needed (eg. batch mode). + if ($httpHeaders) { + $this->setHttpHeaders($httpHeaders); + } + + if ($userAgent) { + $this->setUserAgent($userAgent); + } + + $this->setDetectionType(self::DETECTION_TYPE_EXTENDED); + + return $this->matchUAAgainstKey($key); + } + + /** + * Some detection rules are relative (not standard), + * because of the diversity of devices, vendors and + * their conventions in representing the User-Agent or + * the HTTP headers. + * + * This method will be used to check custom regexes against + * the User-Agent string. + * + * @param $regex + * @param string $userAgent + * @return bool + * + * @todo: search in the HTTP headers too. + */ + public function match($regex, $userAgent = null) + { + $match = (bool) preg_match(sprintf('#%s#is', $regex), (false === empty($userAgent) ? $userAgent : $this->userAgent), $matches); + // If positive match is found, store the results for debug. + if ($match) { + $this->matchingRegex = $regex; + $this->matchesArray = $matches; + } + + return $match; + } + + /** + * Get the properties array. + * + * @return array + */ + public static function getProperties() + { + return self::$properties; + } + + /** + * Prepare the version number. + * + * @todo Remove the error supression from str_replace() call. + * + * @param string $ver The string version, like "2.6.21.2152"; + * + * @return float + */ + public function prepareVersionNo($ver) + { + $ver = str_replace(array('_', ' ', '/'), '.', $ver); + $arrVer = explode('.', $ver, 2); + + if (isset($arrVer[1])) { + $arrVer[1] = @str_replace('.', '', $arrVer[1]); // @todo: treat strings versions. + } + + return (float) implode('.', $arrVer); + } + + /** + * Check the version of the given property in the User-Agent. + * Will return a float number. (eg. 2_0 will return 2.0, 4.3.1 will return 4.31) + * + * @param string $propertyName The name of the property. See self::getProperties() array + * keys for all possible properties. + * @param string $type Either self::VERSION_TYPE_STRING to get a string value or + * self::VERSION_TYPE_FLOAT indicating a float value. This parameter + * is optional and defaults to self::VERSION_TYPE_STRING. Passing an + * invalid parameter will default to the this type as well. + * + * @return string|float The version of the property we are trying to extract. + */ + public function version($propertyName, $type = self::VERSION_TYPE_STRING) + { + if (empty($propertyName)) { + return false; + } + + // set the $type to the default if we don't recognize the type + if ($type !== self::VERSION_TYPE_STRING && $type !== self::VERSION_TYPE_FLOAT) { + $type = self::VERSION_TYPE_STRING; + } + + $properties = self::getProperties(); + + // Check if the property exists in the properties array. + if (true === isset($properties[$propertyName])) { + + // Prepare the pattern to be matched. + // Make sure we always deal with an array (string is converted). + $properties[$propertyName] = (array) $properties[$propertyName]; + + foreach ($properties[$propertyName] as $propertyMatchString) { + + $propertyPattern = str_replace('[VER]', self::VER, $propertyMatchString); + + // Identify and extract the version. + preg_match(sprintf('#%s#is', $propertyPattern), $this->userAgent, $match); + + if (false === empty($match[1])) { + $version = ($type == self::VERSION_TYPE_FLOAT ? $this->prepareVersionNo($match[1]) : $match[1]); + + return $version; + } + + } + + } + + return false; + } + + /** + * Retrieve the mobile grading, using self::MOBILE_GRADE_* constants. + * + * @return string One of the self::MOBILE_GRADE_* constants. + */ + public function mobileGrade() + { + $isMobile = $this->isMobile(); + + if ( + // Apple iOS 4-7.0 – Tested on the original iPad (4.3 / 5.0), iPad 2 (4.3 / 5.1 / 6.1), iPad 3 (5.1 / 6.0), iPad Mini (6.1), iPad Retina (7.0), iPhone 3GS (4.3), iPhone 4 (4.3 / 5.1), iPhone 4S (5.1 / 6.0), iPhone 5 (6.0), and iPhone 5S (7.0) + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) >= 4.3 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) >= 4.3 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) >= 4.3 || + + // Android 2.1-2.3 - Tested on the HTC Incredible (2.2), original Droid (2.2), HTC Aria (2.1), Google Nexus S (2.3). Functional on 1.5 & 1.6 but performance may be sluggish, tested on Google G1 (1.5) + // Android 3.1 (Honeycomb) - Tested on the Samsung Galaxy Tab 10.1 and Motorola XOOM + // Android 4.0 (ICS) - Tested on a Galaxy Nexus. Note: transition performance can be poor on upgraded devices + // Android 4.1 (Jelly Bean) - Tested on a Galaxy Nexus and Galaxy 7 + ( $this->version('Android', self::VERSION_TYPE_FLOAT)>2.1 && $this->is('Webkit') ) || + + // Windows Phone 7.5-8 - Tested on the HTC Surround (7.5), HTC Trophy (7.5), LG-E900 (7.5), Nokia 800 (7.8), HTC Mazaa (7.8), Nokia Lumia 520 (8), Nokia Lumia 920 (8), HTC 8x (8) + $this->version('Windows Phone OS', self::VERSION_TYPE_FLOAT) >= 7.5 || + + // Tested on the Torch 9800 (6) and Style 9670 (6), BlackBerry® Torch 9810 (7), BlackBerry Z10 (10) + $this->is('BlackBerry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 6.0 || + // Blackberry Playbook (1.0-2.0) - Tested on PlayBook + $this->match('Playbook.*Tablet') || + + // Palm WebOS (1.4-3.0) - Tested on the Palm Pixi (1.4), Pre (1.4), Pre 2 (2.0), HP TouchPad (3.0) + ( $this->version('webOS', self::VERSION_TYPE_FLOAT) >= 1.4 && $this->match('Palm|Pre|Pixi') ) || + // Palm WebOS 3.0 - Tested on HP TouchPad + $this->match('hp.*TouchPad') || + + // Firefox Mobile 18 - Tested on Android 2.3 and 4.1 devices + ( $this->is('Firefox') && $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 18 ) || + + // Chrome for Android - Tested on Android 4.0, 4.1 device + ( $this->is('Chrome') && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 4.0 ) || + + // Skyfire 4.1 - Tested on Android 2.3 device + ( $this->is('Skyfire') && $this->version('Skyfire', self::VERSION_TYPE_FLOAT) >= 4.1 && $this->is('AndroidOS') && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) || + + // Opera Mobile 11.5-12: Tested on Android 2.3 + ( $this->is('Opera') && $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11.5 && $this->is('AndroidOS') ) || + + // Meego 1.2 - Tested on Nokia 950 and N9 + $this->is('MeeGoOS') || + + // Tizen (pre-release) - Tested on early hardware + $this->is('Tizen') || + + // Samsung Bada 2.0 - Tested on a Samsung Wave 3, Dolphin browser + // @todo: more tests here! + $this->is('Dolfin') && $this->version('Bada', self::VERSION_TYPE_FLOAT) >= 2.0 || + + // UC Browser - Tested on Android 2.3 device + ( ($this->is('UC Browser') || $this->is('Dolfin')) && $this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 ) || + + // Kindle 3 and Fire - Tested on the built-in WebKit browser for each + ( $this->match('Kindle Fire') || + $this->is('Kindle') && $this->version('Kindle', self::VERSION_TYPE_FLOAT) >= 3.0 ) || + + // Nook Color 1.4.1 - Tested on original Nook Color, not Nook Tablet + $this->is('AndroidOS') && $this->is('NookTablet') || + + // Chrome Desktop 16-24 - Tested on OS X 10.7 and Windows 7 + $this->version('Chrome', self::VERSION_TYPE_FLOAT) >= 16 && !$isMobile || + + // Safari Desktop 5-6 - Tested on OS X 10.7 and Windows 7 + $this->version('Safari', self::VERSION_TYPE_FLOAT) >= 5.0 && !$isMobile || + + // Firefox Desktop 10-18 - Tested on OS X 10.7 and Windows 7 + $this->version('Firefox', self::VERSION_TYPE_FLOAT) >= 10.0 && !$isMobile || + + // Internet Explorer 7-9 - Tested on Windows XP, Vista and 7 + $this->version('IE', self::VERSION_TYPE_FLOAT) >= 7.0 && !$isMobile || + + // Opera Desktop 10-12 - Tested on OS X 10.7 and Windows 7 + $this->version('Opera', self::VERSION_TYPE_FLOAT) >= 10 && !$isMobile + ){ + return self::MOBILE_GRADE_A; + } + + if ( + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT)<4.3 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT)<4.3 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT)<4.3 || + + // Blackberry 5.0: Tested on the Storm 2 9550, Bold 9770 + $this->is('Blackberry') && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) >= 5 && $this->version('BlackBerry', self::VERSION_TYPE_FLOAT)<6 || + + //Opera Mini (5.0-6.5) - Tested on iOS 3.2/4.3 and Android 2.3 + ($this->version('Opera Mini', self::VERSION_TYPE_FLOAT) >= 5.0 && $this->version('Opera Mini', self::VERSION_TYPE_FLOAT) <= 7.0 && + ($this->version('Android', self::VERSION_TYPE_FLOAT) >= 2.3 || $this->is('iOS')) ) || + + // Nokia Symbian^3 - Tested on Nokia N8 (Symbian^3), C7 (Symbian^3), also works on N97 (Symbian^1) + $this->match('NokiaN8|NokiaC7|N97.*Series60|Symbian/3') || + + // @todo: report this (tested on Nokia N71) + $this->version('Opera Mobi', self::VERSION_TYPE_FLOAT) >= 11 && $this->is('SymbianOS') + ){ + return self::MOBILE_GRADE_B; + } + + if ( + // Blackberry 4.x - Tested on the Curve 8330 + $this->version('BlackBerry', self::VERSION_TYPE_FLOAT) <= 5.0 || + // Windows Mobile - Tested on the HTC Leo (WinMo 5.2) + $this->match('MSIEMobile|Windows CE.*Mobile') || $this->version('Windows Mobile', self::VERSION_TYPE_FLOAT) <= 5.2 || + + // Tested on original iPhone (3.1), iPhone 3 (3.2) + $this->is('iOS') && $this->version('iPad', self::VERSION_TYPE_FLOAT) <= 3.2 || + $this->is('iOS') && $this->version('iPhone', self::VERSION_TYPE_FLOAT) <= 3.2 || + $this->is('iOS') && $this->version('iPod', self::VERSION_TYPE_FLOAT) <= 3.2 || + + // Internet Explorer 7 and older - Tested on Windows XP + $this->version('IE', self::VERSION_TYPE_FLOAT) <= 7.0 && !$isMobile + ){ + return self::MOBILE_GRADE_C; + } + + // All older smartphone platforms and featurephones - Any device that doesn't support media queries + // will receive the basic, C grade experience. + return self::MOBILE_GRADE_C; + } +} diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index ea5c5e44..559ded7d 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -930,4 +930,8 @@ class IPayLinksService extends CI_Controller $this->load->view('receipt_mail', $data); } + public function alipay_return() + { + redirect('https://www.chinahighlights.com'); + } } diff --git a/webht/third_party/pay/helpers/index.html b/webht/third_party/pay/helpers/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/pay/helpers/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + \ No newline at end of file diff --git a/webht/third_party/pay/helpers/payment_helper.php b/webht/third_party/pay/helpers/payment_helper.php new file mode 100644 index 00000000..3ec1e8cc --- /dev/null +++ b/webht/third_party/pay/helpers/payment_helper.php @@ -0,0 +1,182 @@ + $v) + { + $temp[$k] = explode(",",$v); //再将拆开的数组重新组装 + } + return $temp; +} + +function my_array_unique($array, $keep_key_assoc = false) +{ + $duplicate_keys = array(); + $tmp = array(); + + foreach ($array as $key=>$val) + { + // convert objects to arrays, in_array() does not support objects + if (is_object($val)) + $val = (array)$val; + + if (!in_array($val, $tmp)) + $tmp[] = $val; + else + $duplicate_keys[] = $key; + } + + foreach ($duplicate_keys as $key) + unset($array[$key]); + + return $keep_key_assoc ? $array : array_values($array); +} + +//根据URL获取月份 +function getaqiMonth($url){ + $monArr = array('January','February','March','April','May','June','July','August','September','October','November','December'); + $monObj = array( + 'January' => '01', + 'February' => '02', + 'March' => '03', + 'April' => '04', + 'May' => '05' , + 'June' => '06', + 'July' => '07', + 'August' => '08', + 'September' => '09', + 'October' => '10', + 'November' => '11', + 'December' => '12'); + $urlarr = explode("/",$url); + $tmp = $urlarr[(count($urlarr)-1)]; + $tmp = ucfirst(str_ireplace('.htm','',$tmp)); + //$d=strtotime("00:01am ".$tmp." 15 2015"); + if(in_array($tmp,$monArr)){ + return $monObj[$tmp]; + }else{ + return false; + } +} +/* + * 把数组元素组合为字符串 + * $container:用来包含元素的符号 + * $se:分隔符 + * $arr:需要重新组合的数组 + * 例如:$arr=['aaaa','bbbb'];myimplode("'",",",$arr);得到 + * 'aaaa','bbbb' + */ +function my_implode($container,$se,$arr) +{ + $str = ""; + if ($arr != '') { + $str = ""; + $tcount = count($arr); + $tcountInt = 0; + foreach ($arr as $i) { + $tcountInt++; + if ($tcount == $tcountInt) { + $str .= $container . $i . $container; + } else { + $str .= $container . $i . $container . $se; + } + } + } + return $str; +} +/*! + * 解析订单号 + * @author LYT + * @date 2017-09-18 + * @param [type] $note_invoice_string [description] + */ +function analysis_orderid($note_invoice_string) { + $data = array(); + + //空字符串或者小于8位都属于不正确的订单号 + if (empty($note_invoice_string) || strlen($note_invoice_string) < 8) { + return false; + } + + //APP订单处理,如标题China Train Booking-160617462 + if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) { + $note_invoice_string = explode('-', $note_invoice_string); + if (isset($note_invoice_string[1])) { + $note_invoice_string = trim($note_invoice_string[1]); + } + return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单,不需要处理交易记录和通知 + } + + //订单号例子 160420021_B--9608 + //Tracking code:2016-05-06-JJ160319027 /Travel advisor:Fiona Jiang /Content:Shanghai, Beijing, Pingyao, Xian, Guilin, Yangshuo, S + + if (strpos($note_invoice_string, 'Tracking Code:') !== false) { + $note_invoice_string = explode('Tracking Code:', $note_invoice_string); + $note_invoice_string = explode('Travel Advisor', $note_invoice_string[1]); + $note_invoice_string = trim($note_invoice_string[0]); + } + + //订单号过滤 + $note_invoice_string = explode('--', $note_invoice_string); + $note_invoice_string = $note_invoice_string[0]; + $note_invoice_string = explode('_', $note_invoice_string); + + //订单类型识别 + $ordertype = 'N'; + if (isset($note_invoice_string[1])) { + $ordertype_temp = trim($note_invoice_string[1]); + if (substr($ordertype_temp, 0, 1) == 'T') { + $ordertype = 'T'; + } elseif (substr($ordertype_temp, 0, 1) == 'B') { + $ordertype = 'B'; + } + } + + //手机订单、机票订单都没有加标示,在这里帮加上,暂时的,今后还是要在网前设置好 + if ($ordertype == 'N' && isset($note_invoice_string[0])) { + $orderid_temp = $note_invoice_string[0]; + if (strlen($orderid_temp) == 9 && substr($orderid_temp, 0, 2) == '16') { + $ordertype = 'B'; + } + } + + //前台预付款订单,以45开头,如45117640类型的订单号,这个类型的订单会分配到某个新订单去,需要查找COLI_AddCode来找新订单号,然后再发送通知 + + if ($ordertype == 'N' && isset($note_invoice_string[0])) { + $orderid_temp = $note_invoice_string[0]; + if (strlen($orderid_temp) == 8 && substr($orderid_temp, 0, 2) == '45') { + $ordertype = 'M'; + } + } + //新的订单号14733661876255 + if ($ordertype == 'N' && isset($note_invoice_string[0])) { + $orderid_temp = $note_invoice_string[0]; + if (strlen($orderid_temp) == 14 && substr($orderid_temp, 0, 2) == '14') { + $ordertype = 'M'; + } + } + + if ($ordertype == 'N') { + return false; //没有编号的订单直接显示错误,由人工分配 + } + + $note_invoice_string = $note_invoice_string[0]; + $note_invoice_string = explode(',', $note_invoice_string); + $orderid = trim($note_invoice_string[0]); + $temp_orderid = explode('-', $orderid); + if (isset($temp_orderid[1])) { + $orderid = trim($temp_orderid[1]); + } + $tempid = explode(' ', $orderid); + $pm_orderid = $tempid[0]; //订单号 + + if (empty($pm_orderid) || strlen($pm_orderid) < 8) { + return false; + } + return json_encode(array('orderid' => $pm_orderid, 'ordertype' => $ordertype)); +} diff --git a/webht/third_party/pay/models/AlipayTradeWapPayContentBuilder.php b/webht/third_party/pay/models/AlipayTradeWapPayContentBuilder.php new file mode 100644 index 00000000..2fca3d26 --- /dev/null +++ b/webht/third_party/pay/models/AlipayTradeWapPayContentBuilder.php @@ -0,0 +1,124 @@ +bizContentarr)){ + $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + } + return $this->bizContent; + } + + public function __construct() + { + $this->bizContentarr['productCode'] = "QUICK_WAP_PAY"; + } + + public function AlipayTradeWapPayContentBuilder() + { + $this->__construct(); + } + + public function getBody() + { + return $this->body; + } + + public function setBody($body) + { + $this->body = $body; + $this->bizContentarr['body'] = $body; + } + + public function setSubject($subject) + { + $this->subject = $subject; + $this->bizContentarr['subject'] = $subject; + } + + public function getSubject() + { + return $this->subject; + } + + public function getOutTradeNo() + { + return $this->outTradeNo; + } + + public function setOutTradeNo($outTradeNo) + { + $this->outTradeNo = $outTradeNo; + $this->bizContentarr['out_trade_no'] = $outTradeNo; + } + + public function setTimeExpress($timeExpress) + { + $this->timeExpress = $timeExpress; + $this->bizContentarr['timeout_express'] = $timeExpress; + } + + public function getTimeExpress() + { + return $this->timeExpress; + } + + public function setTotalAmount($totalAmount) + { + $this->totalAmount = $totalAmount; + $this->bizContentarr['total_amount'] = $totalAmount; + } + + public function getTotalAmount() + { + return $this->totalAmount; + } + + public function setSellerId($sellerId) + { + $this->sellerId = $sellerId; + $this->bizContentarr['seller_id'] = $sellerId; + } + + public function getSellerId() + { + return $this->sellerId; + } +} + +?> diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php new file mode 100644 index 00000000..48821bc3 --- /dev/null +++ b/webht/third_party/pay/models/Alipay_model.php @@ -0,0 +1,277 @@ +HT = $this->load->database('HT', TRUE); + } + + //根据订单号获取外联邮箱 + public function get_order($COLI_ID, $orderinfo = false, $ordertype = 'N') { + $result = ''; + $fieldsql = $orderinfo == false ? '' : " ,* "; + //先查商务订单B,APP订单A、再查传统订单T + if ($ordertype == 'B' || $ordertype == 'A') { + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_ID =?"; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 + if (empty($result) && ($ordertype == 'T')) { + $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_ID like '%$COLI_ID'"; + $query = $this->HT->query($sql); + $result = $query->result(); + } + + //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 + + if (empty($result) && ($ordertype == 'M')) { + $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_AddCode =? "; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + + if (empty($result) && ($ordertype == 'M')) { + $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where + EXISTS ( + SELECT TOP 1 1 + FROM ConfirmLineInfoTmp clit + WHERE clit.COLI_ID = ? + AND cli.COLI_AddCode = CAST(clit.COLI_SN AS VARCHAR(10)) + ) + "; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + + //订单号查询不到尝试使用团号查询 + if (empty($result) && $ordertype == 'B') { + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_GroupCode like '%-$COLI_ID%'"; + $query = $this->HT->query($sql); + $result = $query->result(); + } + //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序,取最新的数据) + + if (!empty($result)) { + //print_r($result[0]); + //die(); + $result = $result[0]; + } + + return $result; + } + + //获取收款记录(商务订单) + public function get_money_list($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) { + $sql = "SELECT GAI_SN,GAI_CusEmail,GAI_Memo + FROM BIZ_GroupAccountInfo bgai + WHERE bgai.GAI_COLI_ID = ? and GAI_SQJE=? and GAI_SQJECurrency=? + ORDER BY bgai.GAI_SN ASC"; + $query = $this->HT->query($sql, array($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency)); + $result = $query->result(); + return $result; + } + + //获取收款记录(传统订单) + public function get_money_list2($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) { + $sql = "SELECT COLI_ID,GroupAccountInfo.* + from GroupAccountInfo + left join ConfirmLineInfo on GAI_COLI_SN=COLI_SN + where COLI_ID=? and GAI_SQJE=? and GAI_SQJECurrency=? + ORDER BY GAI_SN ASC"; + $query = $this->HT->query($sql, array($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency)); + $result = $query->result(); + return $result; + } + + //更新收款记录(商务订单) + public function update_account_info($GAI_CusEmail, $GAI_Memo, $GAI_SN, $GAI_AccreditNo) { + $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_CusEmail=?, GAI_Memo=?,GAI_AccreditNo=? WHERE GAI_SN=?"; + $query = $this->HT->query($sql, array($GAI_CusEmail, $GAI_Memo, $GAI_AccreditNo, $GAI_SN)); + return $query; + } + + //更新收款记录(传统订单) + public function update_account_info2($GAI_CusEmail, $GAI_Memo, $GAI_SN) { + $sql = "UPDATE GroupAccountInfo SET GAI_CusEmail=?, GAI_Memo=? WHERE GAI_SN=?"; + $query = $this->HT->query($sql, array($GAI_CusEmail, $GAI_Memo, $GAI_SN)); + return $query; + } + + //修改订单状态 + public function update_biz_coli_state($coli_sn, $coli_state) { + $sql = " + UPDATE BIZ_ConfirmLineInfo + SET COLI_State = ? + WHERE COLI_SN = ? + "; + $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + return $query; + } + + //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 + public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupAccountInfo + WHERE GAI_COLI_SN = ? AND GAI_SQJE=? + ) + INSERT INTO BIZ_GroupAccountInfo ( + GAI_COLI_SN + ,GAI_COLI_ID + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); + return $query; + } + + //添加收款记录(商务订单) + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + + IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupAccountInfo + WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + ) + INSERT INTO BIZ_GroupAccountInfo ( + GAI_COLI_SN + ,GAI_COLI_ID + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); + return $query; + } + + //添加收款记录(传统订单) + public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + + IF NOT EXISTS( + SELECT TOP 1 1 + FROM GroupAccountInfo + WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + ) + INSERT INTO GroupAccountInfo ( + GAI_COLI_SN + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('GroupAccountInfo'); + return $query; + } + + //更新线路提醒 + public function update_coli_introduction($coli_sn, $msg) { + $sql = " + update ConfirmLineInfo + set COLI_Introduction=ISNULL(COLI_Introduction,'')+' '+? + where 1=1 + AND ISNULL(COLI_Introduction,'')='' + AND COLI_SN=? + "; + // isnull(COLI_Sended,0) in (0,1) 之前判断是新订单或者未分配状态才添加提示的,有些团是后面付款的,所以把限制取消掉 + $query = $this->HT->query($sql, array($msg, $coli_sn)); + return $query; + } + + //存储paypal的实时通知 + public function save_paypal_note($pn_txn_id, $pn_invoice, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer_email, $pn_payment_date, $pn_memo) { + $sql = " + INSERT INTO paypal_note + ( + pn_txn_id,pn_invoice, pn_mc_gross, pn_item_name, pn_item_number,pn_mc_currency, pn_payment_status,pn_payer_email,pn_payment_date, pn_memo,pn_datetime + ) + VALUES + ( + ?,?,?,N?,N?,?,?,N?,?, N?, GETDATE() + ) + "; + $query = $this->HT->query($sql, array($pn_txn_id, $pn_invoice, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer_email, $pn_payment_date, $pn_memo)); + $insertid = $this->HT->last_id('paypal_note'); + return $query; + } + + public function update_mail($mail_sn, $mail_to, $mail_to_name, $mail_sendstate = 0) { + $sql = "UPDATE Email_AutomaticSend SET M_ToEmail=N?,M_ToName=N?,M_State=? WHERE M_SN =? "; + $query = $this->HT->query($sql, array($mail_to, $mail_to_name, $mail_sendstate, $mail_sn)); + return $query; + } + + public function save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $frominfo = 'paypal msg', $M_Web = 'paypal msg') { + $sql = "INSERT INTO + Email_AutomaticSend ( + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, + M_FromName, + M_ServiceSN, + M_State, + M_AddTime + ) VALUES (N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; + $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); + return $query; + } +} diff --git a/webht/third_party/pay/models/Alipay_note_model.php b/webht/third_party/pay/models/Alipay_note_model.php new file mode 100644 index 00000000..af2acc00 --- /dev/null +++ b/webht/third_party/pay/models/Alipay_note_model.php @@ -0,0 +1,194 @@ +INFO = $this->load->database('INFO', TRUE); + } + + public function init() { + $this->topnum = false; + $this->send = false; + $this->search = false; + $this->payment_status = false; + $this->dealId = false; + $this->orderby = ' ORDER BY pn.ALI_sn DESC '; + } + + public function unsend($topnum = 2) { + $this->init(); + $this->topnum = $topnum; + $this->send = " AND (ALI_sent='unsend' OR ALI_sent='' OR ALI_sent IS NULL) "; + return $this->get_list(); + } + + public function failnote($topnum = 2) { + $this->init(); + $this->topnum = $topnum; + $this->send = " AND ALI_sent='sendfail' "; + return $this->get_list(); + } + + public function search_date($date) { + $this->init(); + $search_sql = " AND pn.ALI_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' "; + $this->search = $search_sql; + $this->orderby=" ORDER BY CASE pn.ALI_sent WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.ALI_sn DESC "; + return $this->get_list(); + } + + public function note($txn_id){ + $this->init(); + $this->topnum=1; + $this->dealId=" AND pn.ALI_dealId=".$this->INFO->escape($txn_id); + return $this->get_list(); + } + + public function note_order($orderid,$notice_time) + { + $this->init(); + $this->topnum=1; + $this->dealId=" AND pn.ALI_orderId=".$this->INFO->escape($orderid)." AND pn.ALI_noticeTime=".$this->INFO->escape($notice_time); + return $this->get_list(); + } + + public function search_key($search_key) { + $this->init(); + $this->topnum = 300; //限制最大数量,防止查询单词过短 + $search_sql = ''; + $search_key = trim($search_key); + if (!empty($search_key)) { + $search_sql.=" AND ( pn.ALI_dealId = '$search_key' + OR pn.ALI_orderId like '%$search_key%' )"; + } + $this->search = $search_sql; + return $this->get_list(); + } + + public function note_exists($dealId) + { + $this->init(); + $this->topnum = 1; + $this->search = " AND pn.ALI_dealId = '".$dealId."' "; + return $this->get_list(); + } + + /*! + * 存储IPayLinks的实时通知 + * @author LYT + * @date 2017-08-29 + */ + public function save_alipay($ALI_dealId,$ALI_orderId,$ALI_currencyCode,$ALI_orderAmount,$ALI_payAmount,$ALI_stateCode,$ALI_acquiringTime,$ALI_completeTime,$ALI_memo,$ALI_payType,$ALI_resultCode=null,$ALI_resultMsg=null,$ALI_payerName=null,$ALI_payerEmail=NULL) { + $sql = " + INSERT INTO AlipayLog + ( + ALI_dealId,ALI_orderId,ALI_currencyCode,ALI_orderAmount,ALI_payAmount,ALI_stateCode,ALI_acquiringTime,ALI_completeTime,ALI_memo,ALI_sent,ALI_noticeTime,ALI_payType,ALI_resultCode,ALI_resultMsg,ALI_payerName,ALI_payerEmail + ) + VALUES + ( + ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,N?,?,N? + ) + "; + // echo "

    ".$this->INFO->compile_binds($sql, + $query = $this->INFO->query($sql, + array($ALI_dealId + ,$ALI_orderId + ,strtoupper($ALI_currencyCode) + ,$ALI_orderAmount + ,$ALI_payAmount + ,$ALI_stateCode + ,$ALI_acquiringTime + ,$ALI_completeTime + ,$ALI_memo + ,$ALI_payType + ,$ALI_resultCode + ,$ALI_resultMsg + ,$ALI_payerName + ,$ALI_payerEmail + )); + $insertid = $this->INFO->last_id('AlipayLog'); + return $query; + } + + public function get_list() { + $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT "; + $sql .= " + pn.ALI_sn + ,pn.ALI_dealId + ,pn.ALI_orderId + ,pn.ALI_currencyCode + ,pn.ALI_orderAmount + ,pn.ALI_payAmount + ,pn.ALI_stateCode + ,pn.ALI_resultCode + ,pn.ALI_resultMsg + ,pn.ALI_acquiringTime + ,pn.ALI_completeTime + ,pn.ALI_memo + ,pn.ALI_sent + ,pn.ALI_payType + ,pn.ALI_noticeTime + ,pn.ALI_payerName + ,pn.ALI_payerEmail + FROM AlipayLog pn + WHERE 1=1 + "; + $this->send ? $sql.=$this->send : false; + $this->search ? $sql.=$this->search : false; + $this->dealId ? $sql.=$this->dealId : false; + $this->orderby ? $sql.=$this->orderby : false; + $query = $this->INFO->query($sql); + if ($this->topnum === 1) { + if ($query->num_rows() > 0) { + $row = $query->row(); + return $row; + } else { + return FALSE; + } + } else { + return $query->result(); + } + } + + public function update_send($pn_txn_id, $pn_send) { + $sql = " + UPDATE AlipayLog + SET ALI_sent = ? + WHERE ALI_dealId = ? + "; + return $this->INFO->query($sql, array($pn_send, $pn_txn_id)); + } + + //设置订单号 + public function set_invoice($pn_txn_id, $pn_invoice) { + $sql = " + UPDATE AlipayLog + SET ALI_orderId = ? + WHERE ALI_dealId = ? + "; + return $this->INFO->query($sql, array($pn_invoice, $pn_txn_id)); + } + + public function update_query($dealId,$stateCode,$payAmount) + { + $sql = " + UPDATE AlipayLog + SET ALI_stateCode = ?, + ALI_payAmount = ? + where ALI_dealId = ? + "; + return $this->INFO->query($sql, array($stateCode,$payAmount,$dealId)); + } + +} From 9f49113d7c95a381279440e40f3dade041954c67 Mon Sep 17 00:00:00 2001 From: lyt Date: Wed, 27 Sep 2017 09:51:29 +0800 Subject: [PATCH 009/382] =?UTF-8?q?alipay=20=E4=BF=9D=E5=AD=98payer?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 11 +++++++++++ webht/third_party/pay/models/Alipay_note_model.php | 9 ++++----- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index c1d0de4d..e11cd9f4 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -119,6 +119,17 @@ class AlipayTradeService extends CI_Controller ,NULL ,$buyer ); + // 查询payer + $this->AlipayTradeQueryContentBuilder->setTradeNo($asyns_resp->data->trade_no); + if ($asyns_resp->data->out_trade_no) { + $this->AlipayTradeQueryContentBuilder->setOutTradeNo($asyns_resp->data->out_trade_no); + } + $response = $this->Query($this->AlipayTradeQueryContentBuilder); + $resp_arr = (Array) $response; + $query_resp = $this->check($resp_arr); + if (strcmp(strval($response->trade_status), "TRADE_SUCCESS") == 0) { + $this->Alipay_note_model->update_query($response->trade_no,$response->buyer_logon_id); + } } // 返回状态码200 echo "success"; diff --git a/webht/third_party/pay/models/Alipay_note_model.php b/webht/third_party/pay/models/Alipay_note_model.php index af2acc00..b9d8ea73 100644 --- a/webht/third_party/pay/models/Alipay_note_model.php +++ b/webht/third_party/pay/models/Alipay_note_model.php @@ -85,7 +85,7 @@ class Alipay_note_model extends CI_Model { } /*! - * 存储IPayLinks的实时通知 + * 存储实时通知 * @author LYT * @date 2017-08-29 */ @@ -180,15 +180,14 @@ class Alipay_note_model extends CI_Model { return $this->INFO->query($sql, array($pn_invoice, $pn_txn_id)); } - public function update_query($dealId,$stateCode,$payAmount) + public function update_query($dealId,$payer) { $sql = " UPDATE AlipayLog - SET ALI_stateCode = ?, - ALI_payAmount = ? + SET ALI_payerEmail = ? where ALI_dealId = ? "; - return $this->INFO->query($sql, array($stateCode,$payAmount,$dealId)); + return $this->INFO->query($sql, array($payer,$dealId)); } } From f5c9f9713b463a833675e9c98fb4db056cd7b3cb Mon Sep 17 00:00:00 2001 From: lyt Date: Wed, 27 Sep 2017 10:25:05 +0800 Subject: [PATCH 010/382] =?UTF-8?q?alipay=20=E4=BA=A4=E6=98=93=E8=AE=B0?= =?UTF-8?q?=E5=BD=95,=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 135 ++++++++- webht/third_party/pay/views/alipay_list.php | 256 ++++++++++++++++++ .../pay/views/alipay_note_setting.php | 53 ++++ .../pay/views/alipay_receipt_mail.php | 1 + 4 files changed, 444 insertions(+), 1 deletion(-) create mode 100644 webht/third_party/pay/views/alipay_list.php create mode 100644 webht/third_party/pay/views/alipay_note_setting.php create mode 100644 webht/third_party/pay/views/alipay_receipt_mail.php diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index e11cd9f4..0d4a916f 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -79,7 +79,10 @@ class AlipayTradeService extends CI_Controller log_message('error','Alipay ERROR gateway_url should not be NULL!'); } } - + public function index() + { + $this->note_list(); + } /*! * 异步通知 * 必须返回"success"给支付系统 @@ -562,4 +565,134 @@ class AlipayTradeService extends CI_Controller return $image; } + public function note_list() + { + $data = array(); + $data["paytext"] = $this->payment_status(); + $data["keywords"] = $this->input->get_post("keywords"); + $data["date"] = $this->input->get_post("date"); + empty($data['date']) ? $data['date'] = date('Y-m-d') : false; + if (!empty($data['keywords'])) { + $data['notelist'] = $this->Alipay_note_model->search_key($data['keywords']); + } else { + $data['notelist'] = $this->Alipay_note_model->search_date($data['date']); + } + $this->load->view("alipay_list",$data); + return; + } + //失败记录列表 + public function note_faillist() { + $data = array(); + $data["paytext"] = $this->payment_status(); + //有关键词则不限制日期 + $data['search_key'] = $this->input->post('keywords'); + $data['date'] = $this->input->get_post('date'); + empty($data['date']) ? $data['date'] = date('Y-m-d') : false; + $data['notelist'] = $this->Alipay_note_model->failnote(100); + $this->load->view("alipay_list",$data); + } + //用于HT--交易详情 + public function receipt($pm_transaction_id) { + if ( ! $pm_transaction_id) { + return false; + } + $data = array(); + $data = $this->Alipay_note_model->note($pm_transaction_id); + $this->load->view('alipay_receipt_mail', $data); + } + + //获取note详情,以便后续修改各项数据 + public function note_modal($pn_txn_id = false, $pn_invoice = false ,$notice_time = false) { + $data = array(); + $data['IPL_orderId'] = $pn_invoice; + if (!empty($pn_txn_id)) { + $data['note'] = $this->Alipay_note_model->note($pn_txn_id); + if (!empty($data['note'])) { + if (!empty($pn_invoice)) { + $orderid_info = analysis_orderid($pn_invoice); + } else { + $orderid_info = analysis_orderid($data['note']->IPL_orderId); + } + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $data['order_info'] = $this->Alipay_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype); + } + $data["paytext"] = $this->payment_status(); + echo json_encode($this->load->view('alipay_note_setting', $data, true)); + return true; + } + } + echo json_encode('没找到数据!'); + return; + } + public function note_order_modal($old_order,$pn_invoice = false ,$notice_time = false) { + $data = array(); + $data['IPL_orderId'] = $pn_invoice; + if (!empty($pn_invoice)) { + $data['note'] = $this->Alipay_note_model->note_order($old_order,$notice_time); + if (!empty($data['note'])) { + if (!empty($pn_invoice)) { + $orderid_info = analysis_orderid($pn_invoice); + } else { + $orderid_info = analysis_orderid($data['note']->IPL_orderId); + } + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $data['order_info'] = $this->Alipay_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype); + } + $data["paytext"] = $this->payment_status(); + echo json_encode($this->load->view('alipay_note_setting', $data, true)); + return true; + } + } + echo json_encode('没找到数据!'); + return; + } + + //关闭note通知,用于手动处理通知后 + public function close_note($pn_txn_id) { + $data = array(); + $data['note'] = $this->Alipay_note_model->note($pn_txn_id); + if (!empty($data['note'])) { + $this->Alipay_note_model->update_send($pn_txn_id, 'send'); + echo json_encode('通知已经关闭!'); + return true; + } + echo json_encode('没找到数据!'); + return; + } + + //修改订单名 + public function note_modal_save() { + $data = array(); + + $pn_txn_id = $this->input->post('pn_txn_id'); + $pn_invoice = $this->input->post('pn_invoice'); + + if (!empty($pn_txn_id) && !empty($pn_invoice)) { + $orderid_info = analysis_orderid($pn_invoice); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $advisor_info = $this->Alipay_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + if (!empty($advisor_info)) { + $this->Alipay_note_model->set_invoice($pn_txn_id, $pn_invoice); + $this->send_alipay($pn_txn_id); + echo json_encode('修改成功!'); + return true; + } + } + } + echo json_encode('没找到数据!'); + return; + } + + public function payment_status() + { + return array( + "WAIT_BUYER_PAY" => "Pending", + "TRADE_SUCCESS" => "Payment success", + "TRADE_FINISHED" => "Payment success" + ); + } + } diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php new file mode 100644 index 00000000..7bb47876 --- /dev/null +++ b/webht/third_party/pay/views/alipay_list.php @@ -0,0 +1,256 @@ + +* @date 2017-09-06 +*/ +?> + + + + + + Alipay Notes - China Highlights + + + + + + + + + +
    + +
    +
    +
    +
    + +
    +
    +
    +
    + + +
    +
    +
    +
    +

    + +
    +

    通知状态:

    +

    1.send 表示通知正确发送给外联

    +

    2.unsend 表示通知在等待处理,5~10分钟系统处理一遍

    +

    3.sendfail 状态的需要手工设置正确的订单号

    +

    4.Pending 还未到账,需要人工检查,确认支付或者取消,需要手工关闭此通知

    +

    5.Denied 银行拒付,需要手工关闭此通知

    +
    +
    + +
    + + $item) { + ?> +
      + +
    • +
    • + ALI_dealId) { ?> + + + + + ALI_orderId . ' / ' . $item->ALI_orderAmount . $item->ALI_currencyCode ; ?> +
    • + +
    • + ALI_payerName; ?> + ALI_payerEmail; ?> +
    • + +
    • ALI_dealId; ?>
    • + +
    • ALI_acquiringTime; ?>
    • +
    • ALI_noticeTime; ?>
    • +
    • + ALI_sent == 'send') { + $show_send = $item->ALI_sent; + } else if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")) { + $class_css = 'btn-danger'; + $show_send = $paytext[intval(trim($item->ALI_resultMsg))]; + } else { + $class_css = 'btn-danger'; + $show_send = $item->ALI_sent; + } + ?> +
    • +
    + + +
    + + +
    +
    +
    +
    +
    + + + + + + + + + + diff --git a/webht/third_party/pay/views/alipay_note_setting.php b/webht/third_party/pay/views/alipay_note_setting.php new file mode 100644 index 00000000..90332bba --- /dev/null +++ b/webht/third_party/pay/views/alipay_note_setting.php @@ -0,0 +1,53 @@ +
    + +
    +
    交易号
    +
    ALI_dealId ?> ( ALI_resultMsg))].".".$note->ALI_resultMsg; ?> )
    +
    +
    +
    付款金额
    +
    ALI_currencyCode . ' ' . $note->ALI_orderAmount ?>
    +
    +
    +
    付款时间
    +
    ALI_acquiringTime; ?>
    +
    + + +
    +
    订单号
    +
    +
    + + +
    + +
    +
    + +
    +
    订单详细内容
    +
    + + $order_info->COLI_SN
    "; + echo "COLI_ID => $order_info->COLI_ID
    "; + echo "OPI_Email => $order_info->OPI_Email
    "; + echo "OPI_Name => $order_info->OPI_Name
    "; + echo!empty($order_info->COLI_GroupCode) ? "COLI_GroupCode => $order_info->COLI_GroupCode
    " : false; + echo!empty($order_info->COLI_OrderDetailText) ? "COLI_OrderDetailText => $order_info->COLI_OrderDetailText\n" : false; + } else { + echo '找不到订单内容'; + } + ?> + +
    +
    +
    +
    原始数据
    +
    +
    + + +
    diff --git a/webht/third_party/pay/views/alipay_receipt_mail.php b/webht/third_party/pay/views/alipay_receipt_mail.php new file mode 100644 index 00000000..3233bb72 --- /dev/null +++ b/webht/third_party/pay/views/alipay_receipt_mail.php @@ -0,0 +1 @@ +
    PayPal logo
    Transaction ID:
    Hello Guilin China International Travel Service Co.,Ltd,
    You received a payment of
    Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.
    It may take a few moments for this transaction to appear in your account.
    Seller Protection-
    Buyer


    Description     Amount

    From b0297af32f008676165db867aeccf8bcf666dc87 Mon Sep 17 00:00:00 2001 From: lyt Date: Wed, 27 Sep 2017 10:31:24 +0800 Subject: [PATCH 011/382] ipaylinks warning refer --- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 559ded7d..9a36a765 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -687,7 +687,7 @@ class IPayLinksService extends CI_Controller $ret->data = $respObject = (Object) $resp; $ref = ""; } else { - $ref = $_SERVER['HTTP_REFERER']; + $ref = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : NULL; $r = iconv("UTF-8", "UTF-8//IGNORE", $resp); $ret->data = $respObject = @ simplexml_load_string($resp); // test From 167e006b997dddba7acd21da7431d0b4d97eb6a3 Mon Sep 17 00:00:00 2001 From: lyt Date: Wed, 27 Sep 2017 11:05:22 +0800 Subject: [PATCH 012/382] ipaylinks stateCode=null --- webht/third_party/pay/views/iPayLinks_list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index ea19492c..dd33dfaf 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -129,7 +129,7 @@ $class_css = ''; if ($item->IPL_sent == 'send') { $show_send = $item->IPL_sent; - } else if (strcmp(trim($item->IPL_stateCode), "2")) { + } else if (strcmp(trim($item->IPL_stateCode), "2") && $item->IPL_stateCode != NULL) { $class_css = 'btn-danger'; $show_send = $paytext[intval(trim($item->IPL_stateCode))]; } else { From 653ff6de874e84a1b0f2fcf3bcadec081b1bd60f Mon Sep 17 00:00:00 2001 From: lyt Date: Thu, 28 Sep 2017 10:31:17 +0800 Subject: [PATCH 013/382] =?UTF-8?q?Ipaylinks=E6=B7=BB=E5=8A=A0=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E4=BB=98=E6=AC=BE=E5=90=8E=EF=BC=8C=20=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E8=87=AA=E5=8A=A8=E5=8F=91=E9=80=81=E4=BB=98=E6=AC=BE?= =?UTF-8?q?=E6=88=90=E5=8A=9F=E7=9A=84=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E7=BB=99=E5=AE=A2=E4=BA=BA=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 15 ++- webht/third_party/pay/views/receipt_buyer.php | 91 +++++++++++++++++++ 2 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 webht/third_party/pay/views/receipt_buyer.php diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 9a36a765..861be2e4 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -448,9 +448,9 @@ class IPayLinksService extends CI_Controller } //添加邮件发送记录 - //给外联发送通知邮件 $fromName = 'iPayLinks'; $fromEmail = ''; + // 1.给外联发送通知邮件 $toName = !empty($opi_firstname) ? $opi_firstname : ''; $toEmail = !empty($opi_email) ? $opi_email : ''; $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / ' . $fromName; @@ -459,7 +459,17 @@ class IPayLinksService extends CI_Controller $M_AddTime = $item->IPL_completeTime; $M_State = 0; $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note'); - //添加邮件发送记录 end + // 2.给客人发邮件,通知账单 + $toName2 = !empty($item->IPL_payerName) ? $item->IPL_payerName : ''; + $toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : ''; + // Zac170919039_T(订单号) / 996.00USD / iPayLinks + $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / ' . $fromName; + $body2 = $this->load->view('receipt_buyer', $item, true); + $M_RelatedInfo2 = $item->IPL_sn; + $M_AddTime2 = $item->IPL_completeTime; + $M_State2 = 0; + $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'iPayLinks note'); + // ---- 添加邮件发送记录 end $this->Note_model->update_send($item->IPL_dealId, 'send'); $int++; @@ -934,4 +944,5 @@ class IPayLinksService extends CI_Controller { redirect('https://www.chinahighlights.com'); } + } diff --git a/webht/third_party/pay/views/receipt_buyer.php b/webht/third_party/pay/views/receipt_buyer.php new file mode 100644 index 00000000..305fc5ad --- /dev/null +++ b/webht/third_party/pay/views/receipt_buyer.php @@ -0,0 +1,91 @@ + + + +
    + + + + + +
    + + + + + + + +
    + PayPal logo + + +
    Transaction ID: + + +
    +
    + Hello , +
    + You made a payment of + + +
    + + + + + + + +
    Thanks for using Ipaylinks. Your payment to China Highlights International Travel Service Co., Ltd is sucessully.
    +It may take a few moments for this transaction to appear in our account.
    + + +
    +
    +
    +
    + + + + + + + +
    + Buyer +
    + +
    + +
    +
    +
    + + + + + + + + + + + + + + + +
    Description  Amount
    + +
    +
    + + + + +
    +
    +
    + + From f215ce52dbbf1ea1fe6a3911a72c2926710587e4 Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 29 Sep 2017 09:43:39 +0800 Subject: [PATCH 014/382] ipaylinks HTTP_REFERER notice --- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 861be2e4..12ff910d 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -697,7 +697,7 @@ class IPayLinksService extends CI_Controller $ret->data = $respObject = (Object) $resp; $ref = ""; } else { - $ref = $_SERVER['HTTP_REFERER'] ? $_SERVER['HTTP_REFERER'] : NULL; + $ref = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL; $r = iconv("UTF-8", "UTF-8//IGNORE", $resp); $ret->data = $respObject = @ simplexml_load_string($resp); // test From f5411c2138b35769ab9a76fcb1441515a75daaa0 Mon Sep 17 00:00:00 2001 From: lyt Date: Sat, 30 Sep 2017 11:55:59 +0800 Subject: [PATCH 015/382] =?UTF-8?q?Alipay=20=E5=BC=82=E6=AD=A5=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E6=97=A5=E5=BF=97;=E5=88=A0=E9=99=A4JSON=5FUNESCAPED?= =?UTF-8?q?=5FUNICODE=E5=B8=B8=E9=87=8F,PHP5.4=E4=BB=A5=E4=B8=8B=E4=B8=8D?= =?UTF-8?q?=E6=94=AF=E6=8C=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 1 + webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 0d4a916f..f4ffba33 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -93,6 +93,7 @@ class AlipayTradeService extends CI_Controller public function alipay_notice() { $resp_arr = $this->input->post(); + log_message('error','Alipay Original Notice :'.json_encode($resp_arr)); $asyns_resp = $this->check($resp_arr); // 未得到结果 if (empty($asyns_resp->data->out_trade_no)) { diff --git a/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php b/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php index 6929da92..ed892a77 100644 --- a/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php +++ b/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php @@ -24,7 +24,7 @@ class AlipayTradeQueryContentBuilder extends CI_Model public function getBizContent() { if(!empty($this->bizContentarr)){ - $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + $this->bizContent = json_encode($this->bizContentarr); // 5.4增加的常量 JSON_UNESCAPED_UNICODE } return $this->bizContent; } From 69a7185ec30596bb93b1458e5c3c9ae1a3625a2f Mon Sep 17 00:00:00 2001 From: lyt Date: Sat, 30 Sep 2017 17:38:37 +0800 Subject: [PATCH 016/382] =?UTF-8?q?alipay=20RSA=20ipaylinks=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=AE=A2=E4=BA=BA=E9=82=AE=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/alipay.php | 6 +- .../pay/controllers/AlipayTradeService.php | 9 +- .../pay/controllers/iPayLinksService.php | 4 +- .../pay/libraries/alipay/aop/AopClient.php | 2 +- .../pay/models/Alipay_note_model.php | 2 +- webht/third_party/pay/views/receipt_buyer.php | 92 +------------------ 6 files changed, 13 insertions(+), 102 deletions(-) diff --git a/webht/third_party/pay/config/alipay.php b/webht/third_party/pay/config/alipay.php index ff795035..c33c06b2 100644 --- a/webht/third_party/pay/config/alipay.php +++ b/webht/third_party/pay/config/alipay.php @@ -4,9 +4,9 @@ $config['seller_id'] = "2088221900308281"; $config['notify_url'] = "http://www.mycht.cn/webht.php/apps/pay/alipaytradeservice/alipay_notice"; $config['return_url'] = "https://www.chinahighlights.com/secureipay/alipay_return"; $config['charset'] = "UTF-8"; -$config['sign_type'] = "RSA2"; +$config['sign_type'] = "RSA"; $config['gatewayUrl'] = "https://openapi.alipay.com/gateway.do"; $config['timeout_express'] = "1m"; -$config['alipay_public_key'] = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMpRXezVgTE4/ROKVgWO7AWiVLspzW36lkLF18g2neHV9mfV/kANzrdV170RzJirOuxPecG5LgnKO+MV6giwGJPpUyaRhgYwe1B6Po0LoU4QvI088xjDqNw1vzN7xPRYSgb63mdafVe1qGiHuwelyRYJTZFE3GSb3HSL/5O8MLu0FrIRabgkgOqN7EdznA/WjiGev3tA/10YSrneCcPe49XhKVLvS6cQ3abX48lRr2qxQqh538jYB8/Z/UUVhfQ4BoBqe9JpDQrv4TeIlAXjdqM0Fgz0LXHwXsAiDIeUiKBc+9bAz2vgkRycI+1F3A8VlUG8lwBjqXwzvxZvYzAZYQIDAQAB"; -$config['merchant_private_key'] = "MIIEowIBAAKCAQEAzlwm2yj4lHDuGmBnbgdhMry5kfUmQ2ZeZtuTICi5oUATMlcxjHoVYXe5pN+vcZWM1laC8UuKX1K2gSV+46ax4WcAGjb4eItCmvQyq0REYUua+ybYwWtWn1481NLSPfvW2HwM8O9jXj3XBhfQzJsAJJTikM9lZO++6pC2Wtmhw3FjF+O1gkd015MujRUidXESrIwrmnbO/i1IERblXk1gVnvovWnq6VRB2gC9AfzLdkWo3Pq9rAX+MY/eYto/z8UaYU5BNanVIhQ6pAIQazIMawxqsu28AsPRcM8CwFTYcNktAB3feMRhLMqj9GWzkmDWhjrL3NYR+vsYHDAgj7L5ewIDAQABAoIBAFUxVhlEYNtng+T/x7N0+HupzjKjsphAuthb7fFo3rnjagluVdZY0Frcwpd+gT+zLeGO9aAIP6f6zb2jbS8usmEL1M79wraBR44RIpnyJQjF3cWx0+qGFczVauex4XoVbi0RiYYuTieqAAtT6a+OjhCMJr0B4io5j+fmtmHrVw0IFMmbAesV867EH7sn+MmnJCK79KbL5G7lBxZJZempS9ZhwR18WSGpCk90qHGoI9GlPPDWrN2nAVsGVl501vQKc+fUOQSXmAVc+K87q9SeUmrQdM1GbX5UCj+gMEC7sNAnWthCT2H4AFXxvzGLVhvBzRTLZT1SfmAS8zS8LINDxAECgYEA5gWwtS6Ot96E4MHQxjQEx0cP1+P71uI4huA8Lyx+guPymeM2+u4SiWpkuFyzmoNvMxh2fem3Add3kCNF0PNJRIbI0w2vqF+6gQYVIwcS3kqXUeq9oNN6raqFoad1adAUjGQM1SBwc8ARfF3gw8CkePaxikMzFJ6FS15GeA4SueECgYEA5apZCt3dsFzmMyf+/I/X9Bo+fXhnya6QLN+NsLcwnFpWN//rRHnMR7i9jUpyUUDefz9pLAmTkx3roevoGbI7kikqvWallH1rwkgynQAbyHU1XYjM/tRv9zs2TiorakbqrGvzmTdoClwM+dZOXTT4/TbkmcchvlvXkQWGozaIttsCgYEAqKDxS9Im5Jrn1RGhaTyHaEQrVD0Zyg2sHQzUckzvLivIFZLiIpFX24+46QNk09iZM98yNtqYxGvehjelnipMw0UAguEcrpYHV0FLS5OK/JW4W2B4xidjX1+MedcXF4xpFAbg9XnDlsfuybrU5Q0cRmWsAE2FbA9ObtNdW/QNPGECgYAd44J9EIy2VBC9XZoooku3f+bcC1xueeJXhKx68AxKfNM1rH+gxL0aJGe+yI6CFpAePVFhoslq3vz4cKwfE/v+tI7UYVRxM7Vfbmfv2MDE4MQWLSSIkXsU0Mbrez91ME+AKvhj2zsWBg7GQOan6Knywj8T6D9y957hR7fS69j0+wKBgA1Ph+8DTRbvfXKj95KraLdrPGq6hyK0PaF044pi3u2Z1iys99f7aKM0F19akVE9KG1niR4Zit6S1Hqxx+9V6cLw/xxfEl9t9NK8QxGDqmVk9T6TnyMZvMjAi+FADn3hzbRkp1HGT/XUYe2nFuUaATaNhNuuDcuVZtAr78joA+HV"; +$config['alipay_public_key'] = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB"; +$config['merchant_private_key'] = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJvR9Ot5j/xv4F7nJaC7kH515Q1VgsLs5WInByvKd/Sffh0Qyu7fK7sXktFZZrRKdA2fH5v4DBDwqgF0PgKzcaa0nmLrGQTmeLo7MEmydAb5G+PDCqKbqyRWu7nZxPBQ+1NoalYDIVYFXFfIP3EJr3Jh+nadgPdx783mSDNKG6GT8D2ViqmTOQ94NNwGGgnCqjIxF5wdO1uDzN+4nnIOTH0SL6JJ/5Bgm/Q/Ks0qU4gcPYgO+jrJsxvhRBRkd9HXEqxbrGOkXu9causnQXiztzoeCLuC55dOv8m6P64KELY7Gh3csS5SZieAGMuyYZy19YB0S903G0sYJQOebE17LJAgMBAAECggEAPF+PN3u2LnbUpVjs+pck1VgOuTOqYENr4clarJAQgvSzGGH/QzW9LZQO3zoVIpOHFB/ztlrAXt7u81j/QWTv1D6ut5xD7FLRhB2OvDgdrlq48T+EvTFpSfav0B63gtNfHTj3L8nIaiI9tkBrv4Ghyy8EtObp821tQb1hJTmOofkDNOR3d6kyzkatj+FKFO0kjT1WBC15/l26kRJ8RIQwJnj1z2J+HndYn6z2CVwGQsXHtcAtpfnFx2K9J5Ja3yzpnjwvfMx5uC8VQ+DEc2YrzPVVos6ZRdbtc0CSq9apTsPApfUkDDPB+Q2YPiFROCUQB0ahhpJ/9rfQYKpn7jA9OQKBgQDj627IwRMlf+CUivrYGCYGsTyNTWml+oqx0Up+uzON7xLvpvMnaFoyXyJ6yLLREO9kLGSyyPouppOIAoLU+v1qDBHLIHdj9ZWWVXH2wuW83e+lanonhvxIn74/O+i4yXjhARbU0P9B0KvypVgRY5aB1pNzgUG0tNAAntAzrqxa/wKBgQCatWQyKLhZUpP3awlSFP1NHS1WA7YSWwWuXBd/2oXU8UtA9PmiVcTkPCqdSDiSPGOr8Y1MScLFOTDjYcFpVVYdg5F3weMe9eSa6EAKgnuv/9xzIVjeZQWFoaVSPc6QbZNXkqmtged6QzLxMcTLqF92SU1h73trG3AoIBKOBq3aNwKBgG3IBhmenilO2g7SjpatswtALYlmQ0AWWN3jkH1QkDmKcVWL1c0if2eJ2WLI7xCyloxqsapIEfGMfL1jcD9EEfIVlDCCF9/G9+FskLMqF1yMjhTgH6yQYU5d21Y79hGjwZynWKbzcC/0Yg5DRBNEI8ewYl+dX9e5zAKwfFqYhR5jAoGALGpNJLVaD5LMliitmVobSotI27vfBrAJFoCr4nHbIEJR54ktLfTPvPKlDViRnTInL1L+zNsURsjfhzgmbdYpDfoaxjXsvZO8mNh6oknJtsKPCKKXP+nixvWcX9sMtZwvw+GAQybbTNeEBYjTReDF31C2HZrCZQKQlYR3rzytpssCgYEArfJz2GdJUB59ly8ciW6GegwOUvtYLAuFGbbAudMQRVl8D4bHjCp1t55WAbGWM3pgUWVLxMQS2cyir77YOkhZ32GrKe7irEuzQGlY7omQcPIY1aqCySbKVELkOcK12PzbttYnhOuEVSTsWE3DCf+0m1TslUnpv1NFH/rwOeP0VAI="; diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index f4ffba33..3a421776 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -100,12 +100,12 @@ class AlipayTradeService extends CI_Controller echo "failed"; return; } - if (true === $this->if_note_exists($dealId)) { + if (true === $this->if_note_exists($asyns_resp->data->trade_no)) { echo "success"; return; } - $code = $asyns_resp->data->code ? strval($asyns_resp->data->code) : NULL ; - $buyer = $asyns_resp->data->buyer_logon_id ? strval($asyns_resp->data->buyer_logon_id) : NULL ; + $code = isset($asyns_resp->data->code) ? strval($asyns_resp->data->code) : NULL ; + $buyer = isset($asyns_resp->data->buyer_logon_id) ? strval($asyns_resp->data->buyer_logon_id) : NULL ; if (strcmp(strval($asyns_resp->data->trade_status), "TRADE_SUCCESS") == 0) { $this->Alipay_note_model->save_alipay( strval($asyns_resp->data->trade_no) @@ -527,7 +527,8 @@ class AlipayTradeService extends CI_Controller $aop = new AopClient(); $aop->alipayrsaPublicKey = $this->alipay_public_key; - $ret->check = $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); + // $ret->check = $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); + $ret->check = $result = true; if ($result === false) { log_message('error','Alipay sign ERROR ! orderId:'.$arr_obj->out_trade_no.'; dealId:'.$arr_obj->trade_no . "; Original return:".json_encode($arr)."; "); return $ret; diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 12ff910d..f1fa0335 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -463,12 +463,12 @@ class IPayLinksService extends CI_Controller $toName2 = !empty($item->IPL_payerName) ? $item->IPL_payerName : ''; $toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : ''; // Zac170919039_T(订单号) / 996.00USD / iPayLinks - $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / ' . $fromName; + $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights'; $body2 = $this->load->view('receipt_buyer', $item, true); $M_RelatedInfo2 = $item->IPL_sn; $M_AddTime2 = $item->IPL_completeTime; $M_State2 = 0; - $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'iPayLinks note'); + $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'China Highlights Has Received Your Payment'); // ---- 添加邮件发送记录 end $this->Note_model->update_send($item->IPL_dealId, 'send'); diff --git a/webht/third_party/pay/libraries/alipay/aop/AopClient.php b/webht/third_party/pay/libraries/alipay/aop/AopClient.php index 773150ab..4f3c88e6 100644 --- a/webht/third_party/pay/libraries/alipay/aop/AopClient.php +++ b/webht/third_party/pay/libraries/alipay/aop/AopClient.php @@ -676,7 +676,7 @@ class AopClient { //调用openssl内置方法验签,返回bool值 if ("RSA2" == $signType) { - $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256); + $result = (bool)openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256); // sha256 OPENSSL_ALGO_SHA256 } else { $result = (bool)openssl_verify($data, base64_decode($sign), $res); } diff --git a/webht/third_party/pay/models/Alipay_note_model.php b/webht/third_party/pay/models/Alipay_note_model.php index b9d8ea73..15294ba7 100644 --- a/webht/third_party/pay/models/Alipay_note_model.php +++ b/webht/third_party/pay/models/Alipay_note_model.php @@ -97,7 +97,7 @@ class Alipay_note_model extends CI_Model { ) VALUES ( - ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,N?,?,N? + ?,?,?,?,?,?,?,?,?,'unsend', GETDATE(),?,?,?,?,? ) "; // echo "

    ".$this->INFO->compile_binds($sql, diff --git a/webht/third_party/pay/views/receipt_buyer.php b/webht/third_party/pay/views/receipt_buyer.php index 305fc5ad..2f94719b 100644 --- a/webht/third_party/pay/views/receipt_buyer.php +++ b/webht/third_party/pay/views/receipt_buyer.php @@ -1,91 +1 @@ - - - -
    - - - - - -
    - - - - - - - -
    - PayPal logo - - -
    Transaction ID: - - -
    -
    - Hello , -
    - You made a payment of - - -
    - - - - - - - -
    Thanks for using Ipaylinks. Your payment to China Highlights International Travel Service Co., Ltd is sucessully.
    -It may take a few moments for this transaction to appear in our account.
    - - -
    -
    -
    -
    - - - - - - - -
    - Buyer -
    - -
    - -
    -
    -
    - - - - - - - - - - - - - - - -
    Description  Amount
    - -
    -
    - - - - -
    -
    -
    - - +
    PayPal logo
    Transaction ID:
    Hello ,
    You made a payment of
    Thanks for your payment. Your payment to China Highlights International Travel Service Co., Ltd is sucessully.
    It may take a few moments for this transaction to appear in our account.
    Buyer


    Description     Amount

    From 18753829536526c6b48b94a16574a9d98482bea0 Mon Sep 17 00:00:00 2001 From: lyt Date: Mon, 9 Oct 2017 13:43:32 +0800 Subject: [PATCH 017/382] =?UTF-8?q?Alipay=20=E6=9A=82=E6=97=B6=E6=B3=A8?= =?UTF-8?q?=E9=87=8A=E6=9F=A5=E8=AF=A2=E4=B9=B0=E5=AE=B6=E4=BF=A1=E6=81=AF?= =?UTF-8?q?,=E5=9B=A0=E6=97=A0=E6=B3=95=E7=94=9F=E6=88=90=E7=AD=BE?= =?UTF-8?q?=E5=90=8D;=E5=A2=9E=E5=8A=A0=E8=8E=B7=E5=8F=96=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E5=8D=95=E6=96=B9=E6=B3=95,=E6=9C=AA=E5=AE=8C?= =?UTF-8?q?=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/alipay.php | 6 +- .../pay/controllers/AlipayTradeService.php | 96 +++++++++---------- 2 files changed, 51 insertions(+), 51 deletions(-) diff --git a/webht/third_party/pay/config/alipay.php b/webht/third_party/pay/config/alipay.php index c33c06b2..ff795035 100644 --- a/webht/third_party/pay/config/alipay.php +++ b/webht/third_party/pay/config/alipay.php @@ -4,9 +4,9 @@ $config['seller_id'] = "2088221900308281"; $config['notify_url'] = "http://www.mycht.cn/webht.php/apps/pay/alipaytradeservice/alipay_notice"; $config['return_url'] = "https://www.chinahighlights.com/secureipay/alipay_return"; $config['charset'] = "UTF-8"; -$config['sign_type'] = "RSA"; +$config['sign_type'] = "RSA2"; $config['gatewayUrl'] = "https://openapi.alipay.com/gateway.do"; $config['timeout_express'] = "1m"; -$config['alipay_public_key'] = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDI6d306Q8fIfCOaTXyiUeJHkrIvYISRcc73s3vF1ZT7XN8RNPwJxo8pWaJMmvyTn9N4HQ632qJBVHf8sxHi/fEsraprwCtzvzQETrNRwVxLO5jVmRGi60j8Ue1efIlzPXV9je9mkjzOmdssymZkh2QhUrCmZYI/FCEa3/cNMW0QIDAQAB"; -$config['merchant_private_key'] = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCJvR9Ot5j/xv4F7nJaC7kH515Q1VgsLs5WInByvKd/Sffh0Qyu7fK7sXktFZZrRKdA2fH5v4DBDwqgF0PgKzcaa0nmLrGQTmeLo7MEmydAb5G+PDCqKbqyRWu7nZxPBQ+1NoalYDIVYFXFfIP3EJr3Jh+nadgPdx783mSDNKG6GT8D2ViqmTOQ94NNwGGgnCqjIxF5wdO1uDzN+4nnIOTH0SL6JJ/5Bgm/Q/Ks0qU4gcPYgO+jrJsxvhRBRkd9HXEqxbrGOkXu9causnQXiztzoeCLuC55dOv8m6P64KELY7Gh3csS5SZieAGMuyYZy19YB0S903G0sYJQOebE17LJAgMBAAECggEAPF+PN3u2LnbUpVjs+pck1VgOuTOqYENr4clarJAQgvSzGGH/QzW9LZQO3zoVIpOHFB/ztlrAXt7u81j/QWTv1D6ut5xD7FLRhB2OvDgdrlq48T+EvTFpSfav0B63gtNfHTj3L8nIaiI9tkBrv4Ghyy8EtObp821tQb1hJTmOofkDNOR3d6kyzkatj+FKFO0kjT1WBC15/l26kRJ8RIQwJnj1z2J+HndYn6z2CVwGQsXHtcAtpfnFx2K9J5Ja3yzpnjwvfMx5uC8VQ+DEc2YrzPVVos6ZRdbtc0CSq9apTsPApfUkDDPB+Q2YPiFROCUQB0ahhpJ/9rfQYKpn7jA9OQKBgQDj627IwRMlf+CUivrYGCYGsTyNTWml+oqx0Up+uzON7xLvpvMnaFoyXyJ6yLLREO9kLGSyyPouppOIAoLU+v1qDBHLIHdj9ZWWVXH2wuW83e+lanonhvxIn74/O+i4yXjhARbU0P9B0KvypVgRY5aB1pNzgUG0tNAAntAzrqxa/wKBgQCatWQyKLhZUpP3awlSFP1NHS1WA7YSWwWuXBd/2oXU8UtA9PmiVcTkPCqdSDiSPGOr8Y1MScLFOTDjYcFpVVYdg5F3weMe9eSa6EAKgnuv/9xzIVjeZQWFoaVSPc6QbZNXkqmtged6QzLxMcTLqF92SU1h73trG3AoIBKOBq3aNwKBgG3IBhmenilO2g7SjpatswtALYlmQ0AWWN3jkH1QkDmKcVWL1c0if2eJ2WLI7xCyloxqsapIEfGMfL1jcD9EEfIVlDCCF9/G9+FskLMqF1yMjhTgH6yQYU5d21Y79hGjwZynWKbzcC/0Yg5DRBNEI8ewYl+dX9e5zAKwfFqYhR5jAoGALGpNJLVaD5LMliitmVobSotI27vfBrAJFoCr4nHbIEJR54ktLfTPvPKlDViRnTInL1L+zNsURsjfhzgmbdYpDfoaxjXsvZO8mNh6oknJtsKPCKKXP+nixvWcX9sMtZwvw+GAQybbTNeEBYjTReDF31C2HZrCZQKQlYR3rzytpssCgYEArfJz2GdJUB59ly8ciW6GegwOUvtYLAuFGbbAudMQRVl8D4bHjCp1t55WAbGWM3pgUWVLxMQS2cyir77YOkhZ32GrKe7irEuzQGlY7omQcPIY1aqCySbKVELkOcK12PzbttYnhOuEVSTsWE3DCf+0m1TslUnpv1NFH/rwOeP0VAI="; +$config['alipay_public_key'] = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsMpRXezVgTE4/ROKVgWO7AWiVLspzW36lkLF18g2neHV9mfV/kANzrdV170RzJirOuxPecG5LgnKO+MV6giwGJPpUyaRhgYwe1B6Po0LoU4QvI088xjDqNw1vzN7xPRYSgb63mdafVe1qGiHuwelyRYJTZFE3GSb3HSL/5O8MLu0FrIRabgkgOqN7EdznA/WjiGev3tA/10YSrneCcPe49XhKVLvS6cQ3abX48lRr2qxQqh538jYB8/Z/UUVhfQ4BoBqe9JpDQrv4TeIlAXjdqM0Fgz0LXHwXsAiDIeUiKBc+9bAz2vgkRycI+1F3A8VlUG8lwBjqXwzvxZvYzAZYQIDAQAB"; +$config['merchant_private_key'] = "MIIEowIBAAKCAQEAzlwm2yj4lHDuGmBnbgdhMry5kfUmQ2ZeZtuTICi5oUATMlcxjHoVYXe5pN+vcZWM1laC8UuKX1K2gSV+46ax4WcAGjb4eItCmvQyq0REYUua+ybYwWtWn1481NLSPfvW2HwM8O9jXj3XBhfQzJsAJJTikM9lZO++6pC2Wtmhw3FjF+O1gkd015MujRUidXESrIwrmnbO/i1IERblXk1gVnvovWnq6VRB2gC9AfzLdkWo3Pq9rAX+MY/eYto/z8UaYU5BNanVIhQ6pAIQazIMawxqsu28AsPRcM8CwFTYcNktAB3feMRhLMqj9GWzkmDWhjrL3NYR+vsYHDAgj7L5ewIDAQABAoIBAFUxVhlEYNtng+T/x7N0+HupzjKjsphAuthb7fFo3rnjagluVdZY0Frcwpd+gT+zLeGO9aAIP6f6zb2jbS8usmEL1M79wraBR44RIpnyJQjF3cWx0+qGFczVauex4XoVbi0RiYYuTieqAAtT6a+OjhCMJr0B4io5j+fmtmHrVw0IFMmbAesV867EH7sn+MmnJCK79KbL5G7lBxZJZempS9ZhwR18WSGpCk90qHGoI9GlPPDWrN2nAVsGVl501vQKc+fUOQSXmAVc+K87q9SeUmrQdM1GbX5UCj+gMEC7sNAnWthCT2H4AFXxvzGLVhvBzRTLZT1SfmAS8zS8LINDxAECgYEA5gWwtS6Ot96E4MHQxjQEx0cP1+P71uI4huA8Lyx+guPymeM2+u4SiWpkuFyzmoNvMxh2fem3Add3kCNF0PNJRIbI0w2vqF+6gQYVIwcS3kqXUeq9oNN6raqFoad1adAUjGQM1SBwc8ARfF3gw8CkePaxikMzFJ6FS15GeA4SueECgYEA5apZCt3dsFzmMyf+/I/X9Bo+fXhnya6QLN+NsLcwnFpWN//rRHnMR7i9jUpyUUDefz9pLAmTkx3roevoGbI7kikqvWallH1rwkgynQAbyHU1XYjM/tRv9zs2TiorakbqrGvzmTdoClwM+dZOXTT4/TbkmcchvlvXkQWGozaIttsCgYEAqKDxS9Im5Jrn1RGhaTyHaEQrVD0Zyg2sHQzUckzvLivIFZLiIpFX24+46QNk09iZM98yNtqYxGvehjelnipMw0UAguEcrpYHV0FLS5OK/JW4W2B4xidjX1+MedcXF4xpFAbg9XnDlsfuybrU5Q0cRmWsAE2FbA9ObtNdW/QNPGECgYAd44J9EIy2VBC9XZoooku3f+bcC1xueeJXhKx68AxKfNM1rH+gxL0aJGe+yI6CFpAePVFhoslq3vz4cKwfE/v+tI7UYVRxM7Vfbmfv2MDE4MQWLSSIkXsU0Mbrez91ME+AKvhj2zsWBg7GQOan6Knywj8T6D9y957hR7fS69j0+wKBgA1Ph+8DTRbvfXKj95KraLdrPGq6hyK0PaF044pi3u2Z1iys99f7aKM0F19akVE9KG1niR4Zit6S1Hqxx+9V6cLw/xxfEl9t9NK8QxGDqmVk9T6TnyMZvMjAi+FADn3hzbRkp1HGT/XUYe2nFuUaATaNhNuuDcuVZtAr78joA+HV"; diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 3a421776..808b7f31 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -93,7 +93,6 @@ class AlipayTradeService extends CI_Controller public function alipay_notice() { $resp_arr = $this->input->post(); - log_message('error','Alipay Original Notice :'.json_encode($resp_arr)); $asyns_resp = $this->check($resp_arr); // 未得到结果 if (empty($asyns_resp->data->out_trade_no)) { @@ -124,16 +123,16 @@ class AlipayTradeService extends CI_Controller ,$buyer ); // 查询payer - $this->AlipayTradeQueryContentBuilder->setTradeNo($asyns_resp->data->trade_no); - if ($asyns_resp->data->out_trade_no) { - $this->AlipayTradeQueryContentBuilder->setOutTradeNo($asyns_resp->data->out_trade_no); - } - $response = $this->Query($this->AlipayTradeQueryContentBuilder); - $resp_arr = (Array) $response; - $query_resp = $this->check($resp_arr); - if (strcmp(strval($response->trade_status), "TRADE_SUCCESS") == 0) { - $this->Alipay_note_model->update_query($response->trade_no,$response->buyer_logon_id); - } + // $this->AlipayTradeQueryContentBuilder->setTradeNo($asyns_resp->data->trade_no); + // if ($asyns_resp->data->out_trade_no) { + // $this->AlipayTradeQueryContentBuilder->setOutTradeNo($asyns_resp->data->out_trade_no); + // } + // $response = $this->Query($this->AlipayTradeQueryContentBuilder); + // $resp_arr = (Array) $response; + // $query_resp = $this->check($resp_arr); + // if (strcmp(strval($response->trade_status), "TRADE_SUCCESS") == 0) { + // $this->Alipay_note_model->update_query($response->trade_no,$response->buyer_logon_id); + // } } // 返回状态码200 echo "success"; @@ -269,17 +268,17 @@ class AlipayTradeService extends CI_Controller function aopclientRequestExecute($request,$ispage=false) { $aop = new AopClient (); - $aop->gatewayUrl = $this->gateway_url; - $aop->appId = $this->appid; - $aop->rsaPrivateKey = $this->private_key; + $aop->gatewayUrl = $this->gateway_url; + $aop->appId = $this->appid; + $aop->rsaPrivateKey = $this->private_key; $aop->alipayrsaPublicKey = $this->alipay_public_key; - $aop->apiVersion ="1.0"; - $aop->postCharset = $this->charset; - $aop->format= $this->format; - $aop->signType=$this->signtype; + $aop->apiVersion = "1.0"; + $aop->postCharset = $this->charset; + $aop->format = $this->format; + $aop->signType = $this->signtype; // 开启页面信息输出 - $aop->debugInfo=true; - $result = null; + $aop->debugInfo = true; + $result = null; if($ispage) { $result = $aop->pageExecute($request,"post"); @@ -290,8 +289,6 @@ class AlipayTradeService extends CI_Controller $result = $aop->Execute($request); } - // 打开后,将报文写入log文件 cht test - // log_message('error',"\r\n\r\nResponse: \r\n".var_export($result,true)); return $result; } @@ -465,32 +462,9 @@ class AlipayTradeService extends CI_Controller $request = new AlipayTradeQueryRequest(); $request->setBizContent ( $biz_content ); - $response = $this->aopclientRequestExecute ($request); + $response = $this->aopclientRequestExecute ($request,true); $response = $response->alipay_trade_query_response; - // test asyns - // $resp_arr = (Array) $response; - // $asyns_resp = $this->check($resp_arr); - // if (strcmp(strval($response->trade_status), "TRADE_SUCCESS") == 0) { - // $this->Alipay_note_model->save_alipay( - // strval($response->trade_no) - // ,strval($response->out_trade_no) - // ,"CNY" - // ,strval($response->total_amount) - // ,NULL - // ,NULL - // ,strval($response->send_pay_date) - // ,strval($response->send_pay_date) - // ,json_encode($response) - // ,strval("pay") - // ,strval($response->code) - // ,strval($response->trade_status) - // ,NULL - // ,strval($response->buyer_logon_id) - // ); - // $query = $this->query_pay_result($asyns_resp->data); - // } - return $response; } @@ -513,6 +487,33 @@ class AlipayTradeService extends CI_Controller return; } + /*! + * 对账单 + * 流程: + * * 获取对账单下载地址 + * * 下载对账单 + * * 解压,获取明细表 + * * 分析明细表,入库 + * @author LYT + * @date 2017-10-10 + * @param [type] $date 按天yyyy-MM-dd;按月yyyy-MM + */ + public function get_billfile($date=NULL) + { + $request = new AlipayDataDataserviceBillDownloadurlQueryRequest(); + $request->setBizContent("{" . + "\"bill_type\":\"trade\"," . + "\"bill_date\":\"2017-09\"" . + "}"); + $response = $this->aopclientRequestExecute ($request); +// var_dump($response); + $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response"; +var_dump($response->$responseNode); + // $resultCode = $result->$responseNode->code; + // if(!empty($resultCode)&&$resultCode == 10000){ + // } + } + /** * 验签方法 * @param $arr 验签支付宝返回的信息,使用支付宝公钥。 @@ -527,8 +528,7 @@ class AlipayTradeService extends CI_Controller $aop = new AopClient(); $aop->alipayrsaPublicKey = $this->alipay_public_key; - // $ret->check = $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); - $ret->check = $result = true; + $ret->check = $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype); if ($result === false) { log_message('error','Alipay sign ERROR ! orderId:'.$arr_obj->out_trade_no.'; dealId:'.$arr_obj->trade_no . "; Original return:".json_encode($arr)."; "); return $ret; From f70e7de9d4e7cb0f479a75787036f67e500b03aa Mon Sep 17 00:00:00 2001 From: lyt Date: Thu, 12 Oct 2017 13:21:41 +0800 Subject: [PATCH 018/382] =?UTF-8?q?Alipay=20=E4=BF=AE=E6=94=B9=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E9=A1=B5=E9=9D=A2logo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 6 +++--- webht/third_party/pay/views/alipay_receipt_mail.php | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 808b7f31..0724ef10 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -429,16 +429,16 @@ class AlipayTradeService extends CI_Controller //添加邮件发送记录 //给外联发送通知邮件 - $fromName = 'iPayLinks'; + $fromName = 'Alipay'; $fromEmail = ''; $toName = !empty($opi_firstname) ? $opi_firstname : ''; $toEmail = !empty($opi_email) ? $opi_email : ''; $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->ALI_orderAmount . $item->ALI_currencyCode . ' / ' . $fromName; - $body = $this->load->view('receipt_mail', $item, true); + $body = $this->load->view('alipay_receipt_mail', $item, true); $M_RelatedInfo = $item->ALI_sn; $M_AddTime = $item->ALI_completeTime; $M_State = 0; - $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note'); + $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'Alipay note'); //添加邮件发送记录 end $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); diff --git a/webht/third_party/pay/views/alipay_receipt_mail.php b/webht/third_party/pay/views/alipay_receipt_mail.php index 3233bb72..a2590081 100644 --- a/webht/third_party/pay/views/alipay_receipt_mail.php +++ b/webht/third_party/pay/views/alipay_receipt_mail.php @@ -1 +1 @@ -
    PayPal logo
    Transaction ID:
    Hello Guilin China International Travel Service Co.,Ltd,
    You received a payment of
    Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.
    It may take a few moments for this transaction to appear in your account.
    Seller Protection-
    Buyer


    Description     Amount

    +
    PayPal logo
    Transaction ID:
    Hello Guilin China International Travel Service Co.,Ltd,
    You received a payment of
    Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.
    It may take a few moments for this transaction to appear in your account.
    Seller Protection-
    Buyer


    Description     Amount

    From 4c0650e4ec785a21f8a29db287a5cc6523ef244d Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 3 Nov 2017 15:24:41 +0800 Subject: [PATCH 019/382] =?UTF-8?q?=E6=94=B6=E6=AC=BE=E5=90=8E=E5=86=99?= =?UTF-8?q?=E5=85=A5=E5=AE=9E=E6=94=B6=E4=BA=BA=E6=B0=91=E5=B8=81=E9=87=91?= =?UTF-8?q?=E9=A2=9D;=20PayPal,=20ipaylinks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 9 ++ .../pay/models/IPayLinks_model.php | 32 ++++- .../third_party/paypal/controllers/index.php | 21 +-- .../paypal/models/paypal_model.php | 132 ++++++++++-------- 4 files changed, 123 insertions(+), 71 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index f1fa0335..9e6b2a84 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -388,6 +388,7 @@ class IPayLinksService extends CI_Controller //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { + $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, mb_strtoupper($item->IPL_currencyCode)); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; @@ -406,6 +407,7 @@ class IPayLinksService extends CI_Controller $item->IPL_orderAmount, $item->IPL_completeTime, mb_strtoupper($item->IPL_currencyCode), + $ssje, $item->IPL_completeTime, $item->IPL_completeTime, $item->IPL_acquiringTime, @@ -425,6 +427,7 @@ class IPayLinksService extends CI_Controller $item->IPL_orderAmount, $item->IPL_acquiringTime, mb_strtoupper($item->IPL_currencyCode), + $ssje, $item->IPL_completeTime, $item->IPL_completeTime, $item->IPL_acquiringTime, @@ -945,4 +948,10 @@ class IPayLinksService extends CI_Controller redirect('https://www.chinahighlights.com'); } + public function cal_ssje($amount, $currency='USD') + { + $ssje = $this->IPayLinks_model->get_ssje($amount, $currency); + var_dump($ssje); + } + } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 351be45e..969c79c7 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -157,7 +157,7 @@ class IPayLinks_model extends CI_Model { } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -173,6 +173,7 @@ class IPayLinks_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -182,14 +183,14 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } //添加收款记录(传统订单) - public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -204,6 +205,7 @@ class IPayLinks_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -213,8 +215,8 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,15018,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $query; } @@ -274,4 +276,22 @@ class IPayLinks_model extends CI_Model { $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); return $query; } + + /*! + * 调用数据库函数,生成实收金额 + * @author LYT + * @date 2017-11-03 + * @param decimal(18,3) $amount + * @param varchar(6) $currency + */ + public function get_ssje($amount, $currency='USD') + { + $sql = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje"; + $query = $this->HT->query($sql,array('15018', $currency, $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 69c5c6de..70ac529b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -61,7 +61,7 @@ class Index extends CI_Controller { //$url=site_url('apps/paypal/index/error_paypal'); //echo '无详细信息,三秒后跳转......'; //echo ''; - //die(); + //die(); } $mailinfo = $mailinfo[0]; @@ -430,7 +430,7 @@ class Index extends CI_Controller { echo 'ok
    '; } - //设置授权 + //设置授权 public function base($sandbox) { if ($sandbox == '1') { @@ -472,8 +472,8 @@ class Index extends CI_Controller { $post .= '&PWD=' . $base['password']; $post .= '&USER=' . $base['username']; $post .= '&SIGNATURE=' . $base['signature']; - //print_r($post); - // print_r($base); + //print_r($post); + // print_r($base); //die(); //启动服务器代理 $ch = curl_init($base['url']); //初始化URL @@ -729,7 +729,7 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); continue; } - + //检测是否是APP订单,默认不处理 if ((strpos($item->pn_memo, 'China Train Booking') !== false) || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false)) { //APP自动出票的订单不需要处理 $this->Note_model->update_send($item->pn_txn_id, 'send'); @@ -747,7 +747,7 @@ class Index extends CI_Controller { if (empty($orderid_info)) { $orderid_info = $this->analysis_orderid($item->pn_item_number); } - + //找不到订单号,设置为发送失败标示 if (empty($orderid_info)) { @@ -783,19 +783,22 @@ class Index extends CI_Controller { $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); + $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 } } else { - $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); + $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); } } //更新还没有填的客邮和交易号de收款记录(传统订单) elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; - $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); + $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index f17c0359..3105d078 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,16 +19,16 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo - LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); $result = $query->result(); } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo - LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); $result = $query->result(); @@ -47,7 +47,7 @@ class Paypal_model extends CI_Model { if (empty($result) && ($ordertype == 'M')) { $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN - where + where EXISTS ( SELECT TOP 1 1 FROM ConfirmLineInfoTmp clit @@ -58,11 +58,11 @@ class Paypal_model extends CI_Model { $query = $this->HT->query($sql, array($COLI_ID)); $result = $query->result(); } - + //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo - LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); $result = $query->result(); @@ -91,10 +91,10 @@ class Paypal_model extends CI_Model { //获取收款记录(传统订单) public function get_money_list2($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) { - $sql = "SELECT COLI_ID,GroupAccountInfo.* - from GroupAccountInfo - left join ConfirmLineInfo on GAI_COLI_SN=COLI_SN - where COLI_ID=? and GAI_SQJE=? and GAI_SQJECurrency=? + $sql = "SELECT COLI_ID,GroupAccountInfo.* + from GroupAccountInfo + left join ConfirmLineInfo on GAI_COLI_SN=COLI_SN + where COLI_ID=? and GAI_SQJE=? and GAI_SQJECurrency=? ORDER BY GAI_SN ASC"; $query = $this->HT->query($sql, array($COLI_ID, $GAI_SQJE, $GAI_SQJECurrency)); $result = $query->result(); @@ -120,14 +120,14 @@ class Paypal_model extends CI_Model { $sql = " UPDATE BIZ_ConfirmLineInfo SET COLI_State = ? - WHERE COLI_SN = ? + WHERE COLI_SN = ? "; $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; } //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 - public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " IF NOT EXISTS( @@ -142,6 +142,7 @@ class Paypal_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -151,21 +152,21 @@ class Paypal_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " - + IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN @@ -174,6 +175,7 @@ class Paypal_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -183,21 +185,21 @@ class Paypal_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } //添加收款记录(传统订单) - public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " - + IF NOT EXISTS( SELECT TOP 1 1 FROM GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' ) INSERT INTO GroupAccountInfo ( GAI_COLI_SN @@ -205,6 +207,7 @@ class Paypal_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -214,8 +217,8 @@ class Paypal_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,15002,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,15002,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $query; } @@ -223,7 +226,7 @@ class Paypal_model extends CI_Model { //更新线路提醒 public function update_coli_introduction($coli_sn, $msg) { $sql = " - update ConfirmLineInfo + update ConfirmLineInfo set COLI_Introduction=ISNULL(COLI_Introduction,'')+' '+? where 1=1 AND ISNULL(COLI_Introduction,'')='' @@ -252,7 +255,7 @@ class Paypal_model extends CI_Model { } public function note_list() { - + } public function save_paypal_msg($pm_transaction_id, $pm_orderid, $pm_item_name, $pm_money, $pm_currency, $pm_payer, $pm_payer_email, $pm_payer_status, $pm_memo, $pm_payment_date, $pm_pay_type) { @@ -276,8 +279,8 @@ class Paypal_model extends CI_Model { } public function update_paypal_msg($pm_sn, $pm_orderid, $pm_item_name, $pm_payer_email, $pm_payer_status, $pm_memo) { - $sql = "UPDATE paypal_msg - SET + $sql = "UPDATE paypal_msg + SET pm_orderid=N?, pm_item_name=N?, pm_payer_email=N?, @@ -308,10 +311,10 @@ class Paypal_model extends CI_Model { if ($mail_sn_string == '') { $sql = "SELECT top 360 M_SN FROM Email_AutomaticSend WHERE M_Web='paypal msg' $mapsql ORDER BY M_AddTime desc,M_SN desc"; } else { - $sql = "SELECT * - FROM Email_AutomaticSend + $sql = "SELECT * + FROM Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn - WHERE M_Web='paypal msg' AND M_SN in($mail_sn_string) + WHERE M_Web='paypal msg' AND M_SN in($mail_sn_string) ORDER BY M_AddTime desc,M_SN desc"; } $query = $this->HT->query($sql); @@ -320,10 +323,10 @@ class Paypal_model extends CI_Model { //根据订单号查询邮件 public function get_search_mails($mail_o_orderno) { - $sql = "SELECT TOP 50 * - FROM Email_AutomaticSend + $sql = "SELECT TOP 50 * + FROM Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn - WHERE M_Web='paypal msg' AND pm_orderid like '%$mail_o_orderno%' or M_ReplyToEmail like '%$mail_o_orderno%' or pm_transaction_id like '%$mail_o_orderno%' + WHERE M_Web='paypal msg' AND pm_orderid like '%$mail_o_orderno%' or M_ReplyToEmail like '%$mail_o_orderno%' or pm_transaction_id like '%$mail_o_orderno%' ORDER BY M_AddTime desc,M_SN desc"; $query = $this->HT->query($sql); $result = $query->result(); @@ -332,7 +335,7 @@ class Paypal_model extends CI_Model { //我的收款记录 public function get_my_order($mail_to, $mail_to_name, $cn_name) { - $sql = "SELECT top 100 * + $sql = "SELECT top 100 * from Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn where M_Web='paypal msg' and M_ToEmail =? AND (M_ToName=? or M_ToName=?)"; $query = $this->HT->query($sql, array($mail_to, $mail_to_name, $cn_name)); @@ -355,19 +358,19 @@ class Paypal_model extends CI_Model { } public function save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $frominfo = 'paypal msg', $M_Web = 'paypal msg') { - $sql = "INSERT INTO + $sql = "INSERT INTO Email_AutomaticSend ( - M_ReplyToName, - M_ReplyToEmail, - M_ToName, - M_ToEmail, - M_Title, - M_Body, - M_Web, + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, M_FromName, - M_ServiceSN, + M_ServiceSN, M_State, - M_AddTime + M_AddTime ) VALUES (N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); return $query; @@ -377,33 +380,33 @@ class Paypal_model extends CI_Model { public function get_all_error_order($i = "", $lastdate) { switch ($i) { case 1: - $sql = "SELECT + $sql = "SELECT M_SN, M_ReplyToEmail, pm_currency, pm_payer, pm_money, pm_orderid, - M_ToEmail - FROM Email_AutomaticSend + M_ToEmail + FROM Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn WHERE pm_orderid='' AND M_Web='paypal msg' ORDER BY M_SN DESC"; break; case 2: - $sql = "SELECT + $sql = "SELECT M_SN, M_ReplyToEmail, pm_currency, pm_payer, pm_money, pm_orderid, - M_ToEmail - FROM Email_AutomaticSend + M_ToEmail + FROM Email_AutomaticSend LEFT JOIN paypal_msg ON M_ServiceSN=pm_sn WHERE M_ToEmail='' AND M_Web='paypal msg' ORDER BY M_SN DESC"; break; default: - $sql = "SELECT + $sql = "SELECT M_SN, M_ReplyToEmail, pm_currency, @@ -428,7 +431,7 @@ class Paypal_model extends CI_Model { public function get_unmatch_list($type, $lastdate) { if ($type == 'BIZ') { - $sql = "SELECT * + $sql = "SELECT * FROM ( SELECT COLI_ID, OPI_Email @@ -458,7 +461,7 @@ class Paypal_model extends CI_Model { $sql = "SELECT * FROM ( - + SELECT COLI_ID ,OPI_Email from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID =OPI_SN WHERE EXISTS( @@ -490,4 +493,21 @@ class Paypal_model extends CI_Model { return $result1; } + /*! + * 调用数据库函数,生成实收金额 + * @author LYT + * @date 2017-11-03 + * @param decimal(18,3) $amount + * @param varchar(6) $currency + */ + public function get_ssje($amount, $pay_type='15002', $currency='USD') + { + $sql = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje"; + $query = $this->HT->query($sql,array($pay_type, $currency, $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } } From 6bfd429f275361ad3298bd8b7d4bb27a9f642abd Mon Sep 17 00:00:00 2001 From: lyt Date: Mon, 6 Nov 2017 15:44:30 +0800 Subject: [PATCH 020/382] =?UTF-8?q?ipaylinks=20=E4=BF=AE=E6=94=B9=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E5=9C=B0=E5=9D=80,=E4=BD=BF=E7=94=A8=E5=9B=BD?= =?UTF-8?q?=E5=86=85=E7=9A=84=E5=9C=B0=E5=9D=80;=20=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E9=80=80=E6=AC=BE=E4=BF=A1=E6=81=AF;=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E9=80=80=E6=AC=BE=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/iPayLinks.php | 3 +- .../pay/controllers/iPayLinksService.php | 122 +++++++++++++++--- webht/third_party/pay/models/note_model.php | 45 ++++++- .../third_party/pay/views/iPayLinks_list.php | 7 +- 4 files changed, 156 insertions(+), 21 deletions(-) diff --git a/webht/third_party/pay/config/iPayLinks.php b/webht/third_party/pay/config/iPayLinks.php index 594624ef..7de2b398 100644 --- a/webht/third_party/pay/config/iPayLinks.php +++ b/webht/third_party/pay/config/iPayLinks.php @@ -17,6 +17,7 @@ $config['currencyCode'] = "USD"; $config['travDetailsSize'] = "0"; $config['pkey'] = "30819f300d06092a864886f70d010101050003818d00308189028181008c903972be5509375edec0d6793d8d3eb533334d146069b5dfcdafd24e5c7d0a05d1774488ea257d504a18c9098d798c0f523f3ad722e3e9c32ae7fecd7e734b340b9c8ff805aa32d0a49cb6df9eca3bb6954d966f6148533a8d667aabb55b2762dcd06308c94d24d257dfdb2ad86b46702774c51e7627e5b707d52224ef794b0203010001"; // 商户证书的公钥 -$config['queryUrl'] = "https://query.ipaylinks.com/webgate/orderQuery.htm"; +// $config['queryUrl'] = "https://query.ipaylinks.com/webgate/orderQuery.htm"; +$config['queryUrl'] = "https://query-aw.ipaylinks.com/webgate/orderQuery.htm"; // 国内 $config['query_mode'] = "1"; $config['query_type'] = "1"; diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 9e6b2a84..ec19d471 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -340,7 +340,7 @@ class IPayLinksService extends CI_Controller } //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 - if ($item->IPL_payType == 'Refunded') { + if ($item->IPL_payType == 'refund') { $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } @@ -689,7 +689,7 @@ class IPayLinksService extends CI_Controller * @date 2017-08-17 * @param mix $resp API返回的原始xml或异步返回的post数组 */ - protected function verify_sign($resp=NULL) + protected function verify_sign($resp=NULL, $sign=true) { $ret = new ArrayObject(); $ret->check = false; @@ -710,20 +710,21 @@ class IPayLinksService extends CI_Controller return $ret; } } - $rep_sign = $this->generate_sign((array)$respObject); - if (strcmp($rep_sign,$respObject->signMsg)) { - log_message('error','iPayLinks sign ERROR ! orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId . "; Original return:".$resp."; From: ".$ref); - return $ret; - } - // partnerId - if (strcmp($respObject->partnerId, $this->pay_info_arr['partnerId'])) { - log_message("error", " iPayLinks ERROR partnerId verify failed ".$respObject->partnerId." !== ".$this->pay_info_arr['partnerId'].'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref); - return $ret; - } - // resultCode payment failed - - if (strcmp(strval($respObject->resultCode), "0000")) { - log_message('error',"iPayLinks payment failed! error code:".$respObject->resultCode."; result Msg: ".$respObject->resultMsg.'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref); + if ($sign === true) { + $rep_sign = $this->generate_sign((array)$respObject); + if (strcmp($rep_sign,$respObject->signMsg)) { + log_message('error','iPayLinks sign ERROR ! orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId . "; Original return:".$resp."; From: ".$ref); + return $ret; + } + // partnerId + if (strcmp($respObject->partnerId, $this->pay_info_arr['partnerId'])) { + log_message("error", " iPayLinks ERROR partnerId verify failed ".$respObject->partnerId." !== ".$this->pay_info_arr['partnerId'].'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref); + return $ret; + } + // resultCode payment failed + if (strcmp(strval($respObject->resultCode), "0000")) { + log_message('error',"iPayLinks payment failed! error code:".$respObject->resultCode."; result Msg: ".$respObject->resultMsg.'; orderId:'.$respObject->orderId.'; dealId:'.$respObject->dealId."; From: ".$ref); + } } $ret->check = true; return $ret; @@ -776,7 +777,7 @@ class IPayLinksService extends CI_Controller } else { $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); if (200 !== $httpStatusCode) { - log_message('error', " iPayLinks Request html Status Code: ".$error_message."; curl postBodyString: ".substr($postBodyString, 0, -1)); + log_message('error', " iPayLinks Request html Status Code: ".$httpStatusCode."; curl postBodyString: ".substr($postBodyString, 0, -1)); } } curl_close($ch); @@ -954,4 +955,91 @@ class IPayLinksService extends CI_Controller var_dump($ssje); } + /*! + * 每天请求一次,批量取回退款记录保存 + * @author LYT + * @date 2017-11-06 + */ + public function get_refund_list($daylength=3) + { + bcscale(2); + $ret = array(); + $list = $this->refund_list_info($daylength); + foreach ($list as $key => $refund) { + if ($refund->stateCode == 1) continue; + $ret[] = $this->Note_model->save_refund( + strval($refund->dealId) + , strval($refund->orderId) + , strval("-" . bcdiv(floatval($refund->refundAmount), 100)) + , strval(date('Y-m-d H:i:s',strtotime($refund->refundTime))) + , strval(date('Y-m-d H:i:s',strtotime($refund->completeTime))) + , $refund->stateCode + , "0000" + , json_encode($refund) + , "refund" + ); + } + echo "Got record count: " . count($ret); + return; + } + + /*! + * 批量取回退款记录 + * @author LYT + * @date 2017-11-03 + */ + public function refund_list_info($daylength) + { + $this->query_info_arr["queryOrderId"] = $this->create_guid(); + $this->query_info_arr['mode'] = '2'; + $this->query_info_arr['type'] = '2'; + $this->query_info_arr["beginTime"] = date('Ymd000000', strtotime("-$daylength days")); + $this->query_info_arr["endTime"] = date('Ymd235959'); + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); + + $resp = $this->curl($this->queryUrl,$this->query_info_arr); + + $query_resp = $this->verify_sign($resp, false); + + // 未得到结果 + if (false === $query_resp->data) { + // echo "No record."; + return false; + } + $refund_list = $query_resp->data->refundDetails->detail; + foreach ($refund_list as $key => $refund) { + // 由于ipaylinks批量查询的bug,这里要用单笔查询校对 + $this_info = $this->get_refund($refund->refundOrderId); + if ($this_info !== false) { + $refund->stateCode = $this_info->stateCode; + $refund->refundTime = $this_info->refundTime; + $refund->completeTime = $this_info->completeTime; + } + } + return $refund_list; + } + + /*! + * 单笔查询退款信息 + * ipaylinks的批量查询有问题,所以这个需要用单笔查询确认信息 + * @author LYT + * @date 2017-11-06 + * @param string $refund_order_id 退款信息中的refundOrderId + */ + public function get_refund($refund_order_id) + { + $this->query_info_arr["queryOrderId"] = $this->create_guid(); + $this->query_info_arr["orderId"] = $refund_order_id; + $this->query_info_arr['mode'] = '1'; + $this->query_info_arr['type'] = '2'; + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); + $resp = $this->curl($this->queryUrl,$this->query_info_arr); + $query_resp = $this->verify_sign($resp, false); + // 未得到结果 + if (false === $query_resp->data) { + return false; + } + return $query_resp->data->refundDetails->detail; + } + } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index efe06ff0..a9745543 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -70,7 +70,8 @@ class Note_model extends CI_Model { $search_key = trim($search_key); if (!empty($search_key)) { $search_sql.=" AND ( pn.IPL_dealId = '$search_key' - OR pn.IPL_orderId like '%$search_key%' )"; + OR pn.IPL_orderId like '%$search_key%' + OR pn.IPL_memo like '%$search_key%' )"; } $this->search = $search_sql; return $this->get_list(); @@ -190,4 +191,46 @@ class Note_model extends CI_Model { return $this->INFO->query($sql, array($stateCode,$payAmount,$dealId)); } + public function save_refund($dealId, $orderId, $refundAmount, $refundTime, $completeTime, $stateCode, $resultcode, $memo, $paytype) + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM IPayLinksLog + WHERE IPL_dealId = ? + ) + INSERT INTO IPayLinksLog + ( + IPL_dealId + ,IPL_orderId + ,IPL_orderAmount + ,IPL_stateCode + ,IPL_acquiringTime + ,IPL_completeTime + ,IPL_memo + ,IPL_sent + ,IPL_noticeTime + ,IPL_payType + ,IPL_resultCode + ) + VALUES + ( + ?,?,?,?,?,?,?,'send',?,?,? + ) + "; + $query = $this->INFO->query($sql, + array($dealId + ,$dealId + ,$orderId + ,$refundAmount + ,$stateCode + ,$refundTime + ,$completeTime + ,$memo + ,$completeTime + ,$paytype + ,$resultcode + )); + return $query; + } + } diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index dd33dfaf..35e291f7 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -115,8 +115,11 @@
  • - IPL_payerName; ?>
    - IPL_payerEmail; ?> + IPL_payType == 'refund') { + echo "退款"; + } else { + echo $item->IPL_payerName . "
    " . $item->IPL_payerEmail; + } ?>
  • IPL_dealId; ?>
  • From 52e14744e89faa0f13273ce101ec5c6e6e1ef440 Mon Sep 17 00:00:00 2001 From: lyt Date: Mon, 20 Nov 2017 10:17:58 +0800 Subject: [PATCH 021/382] =?UTF-8?q?ipaylinks=20=E5=95=86=E5=8A=A1=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E7=9A=84=E4=BB=98=E6=AC=BE=E5=A2=9E=E5=8A=A0=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=B8=BB=E8=A1=A8=E7=9A=84=E4=BB=98=E6=AC=BE=E6=96=B9?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/pay/controllers/iPayLinksService.php | 2 ++ webht/third_party/pay/models/IPayLinks_model.php | 12 ++++++++++++ 2 files changed, 14 insertions(+) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index ec19d471..b2f4f989 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -416,6 +416,8 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 969c79c7..b616707f 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -294,4 +294,16 @@ class IPayLinks_model extends CI_Model { } return 0; } + + /*! + * 更新订单主表付款方式,防止没访问thankyou-train.asp + * @author LYT + * @date 2017-11-20 + */ + public function update_paymanner($COLI_SN) + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = '15018' WHERE COLI_SN=? "; + $query = $this->HT->query($sql, array($COLI_SN)); + return $query; + } } From cff5d5a6d5bebafb8aa278aeb0b7ed699e202d39 Mon Sep 17 00:00:00 2001 From: lyt Date: Tue, 28 Nov 2017 09:18:30 +0800 Subject: [PATCH 022/382] =?UTF-8?q?paypal=20=E5=95=86=E5=8A=A1=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E7=9A=84=E4=BB=98=E6=AC=BE=E5=A2=9E=E5=8A=A0=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=B8=BB=E8=A1=A8=E7=9A=84=E4=BB=98=E6=AC=BE=E6=96=B9?= =?UTF-8?q?=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 ++ webht/third_party/paypal/models/paypal_model.php | 11 +++++++++++ 2 files changed, 13 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 70ac529b..9ca58990 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -791,6 +791,8 @@ class Index extends CI_Controller { } else { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 3105d078..af3f95b5 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -510,4 +510,15 @@ class Paypal_model extends CI_Model { } return 0; } + /*! + * 更新订单主表付款方式,防止没访问thankyou-train.asp + * @author LYT + * @date 2017-11-27 + */ + public function update_paymanner($COLI_SN, $paymanner = '15010') + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = ? WHERE COLI_SN=? "; + $query = $this->HT->query($sql, array($paymanner, $COLI_SN)); + return $query; + } } From 92b7d1b92c0efb4910707da0a9fb3442dcce2b4d Mon Sep 17 00:00:00 2001 From: lyt Date: Mon, 11 Dec 2017 17:31:56 +0800 Subject: [PATCH 023/382] =?UTF-8?q?ipaylinks=20=E5=A4=9A=E8=AF=AD=E7=A7=8D?= =?UTF-8?q?=20=E6=9B=B4=E6=96=B0=E5=AE=A2=E4=BA=BA=E9=82=AE=E4=BB=B6?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 9 ++++++- webht/third_party/pay/language/en/index.html | 10 ++++++++ .../pay/language/en/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/en/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/en/ipl_common_lang.php | 9 +++++++ .../language/en/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/en/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/en/ipl_rep_lang.php | 10 ++++++++ webht/third_party/pay/language/es/index.html | 10 ++++++++ .../pay/language/es/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/es/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/es/ipl_common_lang.php | 9 +++++++ .../language/es/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/es/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/es/ipl_rep_lang.php | 10 ++++++++ webht/third_party/pay/language/fr/index.html | 10 ++++++++ .../pay/language/fr/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/fr/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/fr/ipl_common_lang.php | 9 +++++++ .../language/fr/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/fr/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/fr/ipl_rep_lang.php | 10 ++++++++ webht/third_party/pay/language/index.html | 10 ++++++++ webht/third_party/pay/language/ru/index.html | 10 ++++++++ .../pay/language/ru/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/ru/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/ru/ipl_common_lang.php | 9 +++++++ .../language/ru/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/ru/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/ru/ipl_rep_lang.php | 10 ++++++++ webht/third_party/pay/views/receipt_buyer.php | 2 +- 31 files changed, 395 insertions(+), 2 deletions(-) create mode 100644 webht/third_party/pay/language/en/index.html create mode 100644 webht/third_party/pay/language/en/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/en/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/en/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/en/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/en/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/en/ipl_rep_lang.php create mode 100644 webht/third_party/pay/language/es/index.html create mode 100644 webht/third_party/pay/language/es/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/es/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/es/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/es/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/es/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/es/ipl_rep_lang.php create mode 100644 webht/third_party/pay/language/fr/index.html create mode 100644 webht/third_party/pay/language/fr/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/fr/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/fr/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/fr/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/fr/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/fr/ipl_rep_lang.php create mode 100644 webht/third_party/pay/language/index.html create mode 100644 webht/third_party/pay/language/ru/index.html create mode 100644 webht/third_party/pay/language/ru/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/ru/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/ru/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/ru/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/ru/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/ru/ipl_rep_lang.php diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index b2f4f989..2920fe3f 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -321,7 +321,6 @@ class IPayLinksService extends CI_Controller if ( ! empty($pn_txn_id)) { $data['unsend_list'] = array($this->Note_model->note($pn_txn_id)); } - // 待处理的 if (empty($data['unsend_list'])) { $data['unsend_list'] = $this->Note_model->unsend(10); @@ -469,6 +468,14 @@ class IPayLinksService extends CI_Controller $toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : ''; // Zac170919039_T(订单号) / 996.00USD / iPayLinks $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights'; + // lang + $remark_info = json_decode($item->IPL_memo); + $remark_info = json_decode($remark_info->remark); + $ln = $remark_info->ln; + $this->lang->load('ipl_common',$ln); + $this->lang->load('ipl_buyer_email',$ln); + $item->text = $this->lang->language; + // # lang end $body2 = $this->load->view('receipt_buyer', $item, true); $M_RelatedInfo2 = $item->IPL_sn; $M_AddTime2 = $item->IPL_completeTime; diff --git a/webht/third_party/pay/language/en/index.html b/webht/third_party/pay/language/en/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/pay/language/en/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

    Directory access is forbidden.

    + + + \ No newline at end of file diff --git a/webht/third_party/pay/language/en/ipl_buyer_email_lang.php b/webht/third_party/pay/language/en/ipl_buyer_email_lang.php new file mode 100644 index 00000000..3801f3b2 --- /dev/null +++ b/webht/third_party/pay/language/en/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ + It may take a few moments for this transaction to appear in our account.
    '; diff --git a/webht/third_party/pay/language/en/ipl_code_lang.php b/webht/third_party/pay/language/en/ipl_code_lang.php new file mode 100644 index 00000000..fd85754f --- /dev/null +++ b/webht/third_party/pay/language/en/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

    © 1998 China Highlights. + Privacy Statement +

    +
'; diff --git a/webht/third_party/pay/language/en/ipl_form_validate_lang.php b/webht/third_party/pay/language/en/ipl_form_validate_lang.php new file mode 100644 index 00000000..aaf2ca81 --- /dev/null +++ b/webht/third_party/pay/language/en/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/es/ipl_buyer_email_lang.php b/webht/third_party/pay/language/es/ipl_buyer_email_lang.php new file mode 100644 index 00000000..1bdfe705 --- /dev/null +++ b/webht/third_party/pay/language/es/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ +La transacción puede tardar unos minutos en mostrar en su cuenta.
"; diff --git a/webht/third_party/pay/language/es/ipl_code_lang.php b/webht/third_party/pay/language/es/ipl_code_lang.php new file mode 100644 index 00000000..abf3bdb2 --- /dev/null +++ b/webht/third_party/pay/language/es/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Privacy Statement +

+ '; diff --git a/webht/third_party/pay/language/es/ipl_form_validate_lang.php b/webht/third_party/pay/language/es/ipl_form_validate_lang.php new file mode 100644 index 00000000..aaf2ca81 --- /dev/null +++ b/webht/third_party/pay/language/es/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/fr/ipl_buyer_email_lang.php b/webht/third_party/pay/language/fr/ipl_buyer_email_lang.php new file mode 100644 index 00000000..0b7503dd --- /dev/null +++ b/webht/third_party/pay/language/fr/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ +Il est probable que le montant ne soit crédité sur notre compte que dans quelques jours.
"; diff --git a/webht/third_party/pay/language/fr/ipl_code_lang.php b/webht/third_party/pay/language/fr/ipl_code_lang.php new file mode 100644 index 00000000..04ad03a1 --- /dev/null +++ b/webht/third_party/pay/language/fr/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Privacy Statement +

+ '; diff --git a/webht/third_party/pay/language/fr/ipl_form_validate_lang.php b/webht/third_party/pay/language/fr/ipl_form_validate_lang.php new file mode 100644 index 00000000..aaf2ca81 --- /dev/null +++ b/webht/third_party/pay/language/fr/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/ru/index.html b/webht/third_party/pay/language/ru/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/pay/language/ru/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/ru/ipl_buyer_email_lang.php b/webht/third_party/pay/language/ru/ipl_buyer_email_lang.php new file mode 100644 index 00000000..3a5392e7 --- /dev/null +++ b/webht/third_party/pay/language/ru/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ +Это может занять несколько минут, чтобы эта транзакция пришла в наш аккаунт.
"; diff --git a/webht/third_party/pay/language/ru/ipl_code_lang.php b/webht/third_party/pay/language/ru/ipl_code_lang.php new file mode 100644 index 00000000..28d618b3 --- /dev/null +++ b/webht/third_party/pay/language/ru/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Privacy Statement +

+ '; diff --git a/webht/third_party/pay/language/ru/ipl_form_validate_lang.php b/webht/third_party/pay/language/ru/ipl_form_validate_lang.php new file mode 100644 index 00000000..aaf2ca81 --- /dev/null +++ b/webht/third_party/pay/language/ru/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ +
PayPal logo
Transaction ID:
Hello ,
You made a payment of
Thanks for your payment. Your payment to China Highlights International Travel Service Co., Ltd is sucessully.
It may take a few moments for this transaction to appear in our account.
Buyer


Description     Amount

+
border=0 alt="PayPal logo">
,




   

From 0c73968fff204e4995aff9a6268ddabe2603d577 Mon Sep 17 00:00:00 2001 From: lyt Date: Thu, 14 Dec 2017 16:47:50 +0800 Subject: [PATCH 024/382] =?UTF-8?q?ipaylinks=20=E5=A4=9A=E8=AF=AD=E7=A7=8D?= =?UTF-8?q?;=20=E9=BB=98=E8=AE=A4=E8=8B=B1=E8=AF=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 2920fe3f..b72051c2 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -472,6 +472,7 @@ class IPayLinksService extends CI_Controller $remark_info = json_decode($item->IPL_memo); $remark_info = json_decode($remark_info->remark); $ln = $remark_info->ln; + $ln = $ln ? $ln : "en"; $this->lang->load('ipl_common',$ln); $this->lang->load('ipl_buyer_email',$ln); $item->text = $this->lang->language; From 09b62f9150b83a45148d6660a0b0f3f24d7019f0 Mon Sep 17 00:00:00 2001 From: lyt Date: Thu, 21 Dec 2017 16:48:46 +0800 Subject: [PATCH 025/382] =?UTF-8?q?ipaylinks=20fixed=20=E9=80=80=E6=AC=BE?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=20=E7=BB=93=E6=9E=9C=E5=A4=84=E7=90=86xml=20?= =?UTF-8?q?bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index b72051c2..5fa2e1da 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1016,7 +1016,8 @@ class IPayLinksService extends CI_Controller // echo "No record."; return false; } - $refund_list = $query_resp->data->refundDetails->detail; + $refund_list_obj = @ json_decode(@ json_encode($query_resp->data->refundDetails)); + $refund_list = $refund_list_obj->detail; foreach ($refund_list as $key => $refund) { // 由于ipaylinks批量查询的bug,这里要用单笔查询校对 $this_info = $this->get_refund($refund->refundOrderId); From 6faebf3e28090a836adfc181a80407480552aef9 Mon Sep 17 00:00:00 2001 From: lyt Date: Tue, 26 Dec 2017 14:47:03 +0800 Subject: [PATCH 026/382] =?UTF-8?q?ipaylinks=20=E5=BE=B7=E8=AF=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/language/de/index.html | 10 ++++++++ .../pay/language/de/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/de/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/de/ipl_common_lang.php | 9 +++++++ .../language/de/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/de/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/de/ipl_rep_lang.php | 10 ++++++++ 7 files changed, 94 insertions(+) create mode 100644 webht/third_party/pay/language/de/index.html create mode 100644 webht/third_party/pay/language/de/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/de/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/de/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/de/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/de/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/de/ipl_rep_lang.php diff --git a/webht/third_party/pay/language/de/index.html b/webht/third_party/pay/language/de/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/pay/language/de/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/de/ipl_buyer_email_lang.php b/webht/third_party/pay/language/de/ipl_buyer_email_lang.php new file mode 100644 index 00000000..b606d231 --- /dev/null +++ b/webht/third_party/pay/language/de/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ +'; diff --git a/webht/third_party/pay/language/de/ipl_code_lang.php b/webht/third_party/pay/language/de/ipl_code_lang.php new file mode 100644 index 00000000..27e282f7 --- /dev/null +++ b/webht/third_party/pay/language/de/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Privacy Statement +

+ '; diff --git a/webht/third_party/pay/language/de/ipl_form_validate_lang.php b/webht/third_party/pay/language/de/ipl_form_validate_lang.php new file mode 100644 index 00000000..0153b6d4 --- /dev/null +++ b/webht/third_party/pay/language/de/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + Date: Thu, 4 Jan 2018 09:53:36 +0800 Subject: [PATCH 027/382] =?UTF-8?q?ipaylinks=20=E6=84=8F=E5=A4=A7=E5=88=A9?= =?UTF-8?q?=E8=AF=AD=20=E6=97=A5=E8=AF=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/language/it/index.html | 10 ++++++++ .../pay/language/it/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/it/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/it/ipl_common_lang.php | 9 +++++++ .../language/it/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/it/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/it/ipl_rep_lang.php | 10 ++++++++ webht/third_party/pay/language/jp/index.html | 10 ++++++++ .../pay/language/jp/ipl_buyer_email_lang.php | 9 +++++++ .../pay/language/jp/ipl_code_lang.php | 24 +++++++++++++++++++ .../pay/language/jp/ipl_common_lang.php | 9 +++++++ .../language/jp/ipl_form_validate_lang.php | 9 +++++++ .../pay/language/jp/ipl_index_lang.php | 23 ++++++++++++++++++ .../pay/language/jp/ipl_rep_lang.php | 10 ++++++++ 14 files changed, 188 insertions(+) create mode 100644 webht/third_party/pay/language/it/index.html create mode 100644 webht/third_party/pay/language/it/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/it/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/it/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/it/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/it/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/it/ipl_rep_lang.php create mode 100644 webht/third_party/pay/language/jp/index.html create mode 100644 webht/third_party/pay/language/jp/ipl_buyer_email_lang.php create mode 100644 webht/third_party/pay/language/jp/ipl_code_lang.php create mode 100644 webht/third_party/pay/language/jp/ipl_common_lang.php create mode 100644 webht/third_party/pay/language/jp/ipl_form_validate_lang.php create mode 100644 webht/third_party/pay/language/jp/ipl_index_lang.php create mode 100644 webht/third_party/pay/language/jp/ipl_rep_lang.php diff --git a/webht/third_party/pay/language/it/index.html b/webht/third_party/pay/language/it/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/pay/language/it/index.html @@ -0,0 +1,10 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/it/ipl_buyer_email_lang.php b/webht/third_party/pay/language/it/ipl_buyer_email_lang.php new file mode 100644 index 00000000..a86fc4f3 --- /dev/null +++ b/webht/third_party/pay/language/it/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ + Potrebbero essere necessari alcuni momenti prima che questa transazione venga visualizzata nel nostro account.
'; diff --git a/webht/third_party/pay/language/it/ipl_code_lang.php b/webht/third_party/pay/language/it/ipl_code_lang.php new file mode 100644 index 00000000..1d871445 --- /dev/null +++ b/webht/third_party/pay/language/it/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Informativa sulla Privacy +

+ '; diff --git a/webht/third_party/pay/language/it/ipl_form_validate_lang.php b/webht/third_party/pay/language/it/ipl_form_validate_lang.php new file mode 100644 index 00000000..f0db5f4c --- /dev/null +++ b/webht/third_party/pay/language/it/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + + + 403 Forbidden + + + +

Directory access is forbidden.

+ + + \ No newline at end of file diff --git a/webht/third_party/pay/language/jp/ipl_buyer_email_lang.php b/webht/third_party/pay/language/jp/ipl_buyer_email_lang.php new file mode 100644 index 00000000..5c562a0d --- /dev/null +++ b/webht/third_party/pay/language/jp/ipl_buyer_email_lang.php @@ -0,0 +1,9 @@ + ご入金手続き完了後、弊社口座に反映されるまでにお時間がかかりますので、ご了承ください。
'; diff --git a/webht/third_party/pay/language/jp/ipl_code_lang.php b/webht/third_party/pay/language/jp/ipl_code_lang.php new file mode 100644 index 00000000..f39d4d8b --- /dev/null +++ b/webht/third_party/pay/language/jp/ipl_code_lang.php @@ -0,0 +1,24 @@ + +

© 1998 China Highlights. + Privacy Statement +

+ '; diff --git a/webht/third_party/pay/language/jp/ipl_form_validate_lang.php b/webht/third_party/pay/language/jp/ipl_form_validate_lang.php new file mode 100644 index 00000000..6180ccd1 --- /dev/null +++ b/webht/third_party/pay/language/jp/ipl_form_validate_lang.php @@ -0,0 +1,9 @@ + Date: Fri, 26 Jan 2018 09:50:34 +0800 Subject: [PATCH 028/382] =?UTF-8?q?ipaylinks=20=E4=BA=A4=E6=98=93=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E7=9A=84=E5=B8=81=E7=A7=8D=E5=86=99=E5=85=A5bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 5fa2e1da..3c3ab578 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -387,6 +387,7 @@ class IPayLinksService extends CI_Controller //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { + $item->IPL_currencyCode = trim($item->IPL_currencyCode); $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, mb_strtoupper($item->IPL_currencyCode)); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { From 780ed7741e2aa88cb31bc2aa21b47d1c9a785403 Mon Sep 17 00:00:00 2001 From: lyt Date: Fri, 2 Feb 2018 11:39:07 +0800 Subject: [PATCH 029/382] =?UTF-8?q?ipaylinks=20=E4=B8=8B=E8=BD=BD=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E5=8D=95,=20=E5=88=86=E6=9E=90,=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BB=98=E6=AC=BE=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 +- ipaylinks_statement/Crypt/AES.php | 197 + ipaylinks_statement/Crypt/Base.php | 2616 ++++++ ipaylinks_statement/Crypt/Blowfish.php | 674 ++ ipaylinks_statement/Crypt/DES.php | 1516 ++++ ipaylinks_statement/Crypt/Hash.php | 861 ++ ipaylinks_statement/Crypt/RC2.php | 761 ++ ipaylinks_statement/Crypt/RC4.php | 366 + ipaylinks_statement/Crypt/RSA.php | 3142 ++++++++ ipaylinks_statement/Crypt/Random.php | 334 + ipaylinks_statement/Crypt/Rijndael.php | 1050 +++ ipaylinks_statement/Crypt/TripleDES.php | 517 ++ ipaylinks_statement/Crypt/Twofish.php | 881 ++ ipaylinks_statement/File/ANSI.php | 604 ++ ipaylinks_statement/File/ASN1.php | 1473 ++++ ipaylinks_statement/File/X509.php | 4937 ++++++++++++ ipaylinks_statement/Math/BigInteger.php | 3812 +++++++++ ipaylinks_statement/Net/SCP.php | 373 + ipaylinks_statement/Net/SFTP.php | 3161 ++++++++ ipaylinks_statement/Net/SFTP/Stream.php | 815 ++ ipaylinks_statement/Net/SSH1.php | 1691 ++++ ipaylinks_statement/Net/SSH2.php | 4723 +++++++++++ ipaylinks_statement/System/SSH/Agent.php | 486 ++ ipaylinks_statement/System/SSH_Agent.php | 39 + ipaylinks_statement/bootstrap.php | 16 + ipaylinks_statement/download_files.php | 28 + ipaylinks_statement/openssl.cnf | 6 + .../statement_files/2018/01/20180127.xlsx | Bin 0 -> 12239 bytes .../statement_files/2018/01/20180128.xlsx | Bin 0 -> 10029 bytes .../statement_files/2018/01/20180129.xlsx | Bin 0 -> 13902 bytes .../statement_files/2018/01/20180130.xlsx | Bin 0 -> 13749 bytes .../statement_files/2018/01/20180131.xlsx | Bin 0 -> 13756 bytes webht/config/config.php | 4 +- .../pay/controllers/iPayLinksService.php | 149 +- .../pay/libraries/PHPExcel/PHPExcel.php | 1139 +++ .../PHPExcel/PHPExcel/Autoloader.php | 85 + .../PHPExcel/CachedObjectStorage/APC.php | 295 + .../CachedObjectStorage/CacheBase.php | 347 + .../PHPExcel/CachedObjectStorage/DiscISAM.php | 219 + .../PHPExcel/CachedObjectStorage/ICache.php | 112 + .../PHPExcel/CachedObjectStorage/Igbinary.php | 152 + .../PHPExcel/CachedObjectStorage/Memcache.php | 312 + .../PHPExcel/CachedObjectStorage/Memory.php | 125 + .../CachedObjectStorage/MemoryGZip.php | 137 + .../CachedObjectStorage/MemorySerialized.php | 137 + .../PHPExcel/CachedObjectStorage/PHPTemp.php | 206 + .../PHPExcel/CachedObjectStorage/SQLite.php | 306 + .../PHPExcel/CachedObjectStorage/SQLite3.php | 345 + .../PHPExcel/CachedObjectStorage/Wincache.php | 294 + .../PHPExcel/CachedObjectStorageFactory.php | 251 + .../CalcEngine/CyclicReferenceStack.php | 98 + .../PHPExcel/PHPExcel/CalcEngine/Logger.php | 153 + .../PHPExcel/PHPExcel/Calculation.php | 3933 +++++++++ .../PHPExcel/Calculation/Database.php | 725 ++ .../PHPExcel/Calculation/DateTime.php | 1475 ++++ .../PHPExcel/Calculation/Engineering.php | 2505 ++++++ .../PHPExcel/Calculation/Exception.php | 52 + .../PHPExcel/Calculation/ExceptionHandler.php | 49 + .../PHPExcel/Calculation/Financial.php | 2292 ++++++ .../PHPExcel/Calculation/FormulaParser.php | 614 ++ .../PHPExcel/Calculation/FormulaToken.php | 176 + .../PHPExcel/Calculation/Function.php | 149 + .../PHPExcel/Calculation/Functions.php | 726 ++ .../PHPExcel/PHPExcel/Calculation/Logical.php | 288 + .../PHPExcel/Calculation/LookupRef.php | 881 ++ .../PHPExcel/Calculation/MathTrig.php | 1373 ++++ .../PHPExcel/Calculation/Statistical.php | 3651 +++++++++ .../PHPExcel/Calculation/TextData.php | 590 ++ .../PHPExcel/Calculation/Token/Stack.php | 115 + .../PHPExcel/Calculation/functionlist.txt | 351 + .../pay/libraries/PHPExcel/PHPExcel/Cell.php | 990 +++ .../PHPExcel/Cell/AdvancedValueBinder.php | 192 + .../PHPExcel/PHPExcel/Cell/DataType.php | 122 + .../PHPExcel/PHPExcel/Cell/DataValidation.php | 472 ++ .../PHPExcel/Cell/DefaultValueBinder.php | 106 + .../PHPExcel/PHPExcel/Cell/Hyperlink.php | 126 + .../PHPExcel/PHPExcel/Cell/IValueBinder.php | 46 + .../pay/libraries/PHPExcel/PHPExcel/Chart.php | 551 ++ .../PHPExcel/PHPExcel/Chart/DataSeries.php | 365 + .../PHPExcel/Chart/DataSeriesValues.php | 327 + .../PHPExcel/PHPExcel/Chart/Exception.php | 52 + .../PHPExcel/PHPExcel/Chart/Layout.php | 445 ++ .../PHPExcel/PHPExcel/Chart/Legend.php | 171 + .../PHPExcel/PHPExcel/Chart/PlotArea.php | 128 + .../Chart/Renderer/PHP Charting Libraries.txt | 17 + .../PHPExcel/Chart/Renderer/jpgraph.php | 855 ++ .../PHPExcel/PHPExcel/Chart/Title.php | 92 + .../libraries/PHPExcel/PHPExcel/Comment.php | 327 + .../PHPExcel/PHPExcel/DocumentProperties.php | 587 ++ .../PHPExcel/PHPExcel/DocumentSecurity.php | 218 + .../libraries/PHPExcel/PHPExcel/Exception.php | 52 + .../libraries/PHPExcel/PHPExcel/HashTable.php | 202 + .../PHPExcel/PHPExcel/IComparable.php | 43 + .../libraries/PHPExcel/PHPExcel/IOFactory.php | 288 + .../PHPExcel/PHPExcel/NamedRange.php | 246 + .../PHPExcel/PHPExcel/Reader/Abstract.php | 227 + .../PHPExcel/PHPExcel/Reader/CSV.php | 415 + .../PHPExcel/Reader/DefaultReadFilter.php | 58 + .../PHPExcel/PHPExcel/Reader/Excel2003XML.php | 802 ++ .../PHPExcel/PHPExcel/Reader/Excel2007.php | 2069 +++++ .../PHPExcel/Reader/Excel2007/Chart.php | 517 ++ .../PHPExcel/Reader/Excel2007/Theme.php | 124 + .../PHPExcel/PHPExcel/Reader/Excel5.php | 7084 +++++++++++++++++ .../PHPExcel/Reader/Excel5/Escher.php | 640 ++ .../PHPExcel/PHPExcel/Reader/Excel5/MD5.php | 221 + .../PHPExcel/PHPExcel/Reader/Excel5/RC4.php | 88 + .../PHPExcel/PHPExcel/Reader/Exception.php | 52 + .../PHPExcel/PHPExcel/Reader/Gnumeric.php | 873 ++ .../PHPExcel/PHPExcel/Reader/HTML.php | 468 ++ .../PHPExcel/PHPExcel/Reader/IReadFilter.php | 47 + .../PHPExcel/PHPExcel/Reader/IReader.php | 53 + .../PHPExcel/PHPExcel/Reader/OOCalc.php | 707 ++ .../PHPExcel/PHPExcel/Reader/SYLK.php | 450 ++ .../PHPExcel/PHPExcel/ReferenceHelper.php | 922 +++ .../libraries/PHPExcel/PHPExcel/RichText.php | 199 + .../PHPExcel/RichText/ITextElement.php | 64 + .../PHPExcel/PHPExcel/RichText/Run.php | 102 + .../PHPExcel/RichText/TextElement.php | 108 + .../libraries/PHPExcel/PHPExcel/Settings.php | 387 + .../PHPExcel/PHPExcel/Shared/CodePage.php | 102 + .../PHPExcel/PHPExcel/Shared/Date.php | 393 + .../PHPExcel/PHPExcel/Shared/Drawing.php | 272 + .../PHPExcel/PHPExcel/Shared/Escher.php | 91 + .../PHPExcel/Shared/Escher/DgContainer.php | 83 + .../Escher/DgContainer/SpgrContainer.php | 109 + .../DgContainer/SpgrContainer/SpContainer.php | 395 + .../PHPExcel/Shared/Escher/DggContainer.php | 203 + .../Escher/DggContainer/BstoreContainer.php | 65 + .../DggContainer/BstoreContainer/BSE.php | 120 + .../DggContainer/BstoreContainer/BSE/Blip.php | 91 + .../PHPExcel/PHPExcel/Shared/Excel5.php | 317 + .../PHPExcel/PHPExcel/Shared/File.php | 178 + .../PHPExcel/PHPExcel/Shared/Font.php | 775 ++ .../PHPExcel/Shared/JAMA/CHANGELOG.TXT | 16 + .../Shared/JAMA/CholeskyDecomposition.php | 149 + .../Shared/JAMA/EigenvalueDecomposition.php | 862 ++ .../PHPExcel/Shared/JAMA/LUDecomposition.php | 258 + .../PHPExcel/PHPExcel/Shared/JAMA/Matrix.php | 1059 +++ .../PHPExcel/Shared/JAMA/QRDecomposition.php | 234 + .../JAMA/SingularValueDecomposition.php | 526 ++ .../PHPExcel/Shared/JAMA/utils/Error.php | 82 + .../PHPExcel/Shared/JAMA/utils/Maths.php | 43 + .../PHPExcel/PHPExcel/Shared/OLE.php | 531 ++ .../Shared/OLE/ChainedBlockStream.php | 230 + .../PHPExcel/PHPExcel/Shared/OLE/PPS.php | 230 + .../PHPExcel/PHPExcel/Shared/OLE/PPS/File.php | 84 + .../PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php | 467 ++ .../PHPExcel/PHPExcel/Shared/OLERead.php | 317 + .../PHPExcel/Shared/PCLZip/gnu-lgpl.txt | 504 ++ .../PHPExcel/Shared/PCLZip/pclzip.lib.php | 5694 +++++++++++++ .../PHPExcel/Shared/PCLZip/readme.txt | 421 + .../PHPExcel/Shared/PasswordHasher.php | 66 + .../PHPExcel/PHPExcel/Shared/String.php | 776 ++ .../PHPExcel/PHPExcel/Shared/TimeZone.php | 140 + .../PHPExcel/PHPExcel/Shared/XMLWriter.php | 127 + .../PHPExcel/PHPExcel/Shared/ZipArchive.php | 175 + .../PHPExcel/Shared/ZipStreamWrapper.php | 201 + .../PHPExcel/Shared/trend/bestFitClass.php | 432 + .../Shared/trend/exponentialBestFitClass.php | 148 + .../Shared/trend/linearBestFitClass.php | 111 + .../Shared/trend/logarithmicBestFitClass.php | 120 + .../Shared/trend/polynomialBestFitClass.php | 224 + .../Shared/trend/powerBestFitClass.php | 142 + .../PHPExcel/Shared/trend/trendClass.php | 156 + .../pay/libraries/PHPExcel/PHPExcel/Style.php | 668 ++ .../PHPExcel/PHPExcel/Style/Alignment.php | 412 + .../PHPExcel/PHPExcel/Style/Border.php | 294 + .../PHPExcel/PHPExcel/Style/Borders.php | 424 + .../PHPExcel/PHPExcel/Style/Color.php | 429 + .../PHPExcel/PHPExcel/Style/Conditional.php | 277 + .../PHPExcel/PHPExcel/Style/Fill.php | 321 + .../PHPExcel/PHPExcel/Style/Font.php | 532 ++ .../PHPExcel/PHPExcel/Style/NumberFormat.php | 711 ++ .../PHPExcel/PHPExcel/Style/Protection.php | 207 + .../PHPExcel/PHPExcel/Style/Supervisor.php | 132 + .../libraries/PHPExcel/PHPExcel/Worksheet.php | 2909 +++++++ .../PHPExcel/Worksheet/AutoFilter.php | 858 ++ .../PHPExcel/Worksheet/AutoFilter/Column.php | 394 + .../Worksheet/AutoFilter/Column/Rule.php | 464 ++ .../PHPExcel/Worksheet/BaseDrawing.php | 485 ++ .../PHPExcel/Worksheet/CellIterator.php | 161 + .../PHPExcel/Worksheet/ColumnDimension.php | 266 + .../PHPExcel/PHPExcel/Worksheet/Drawing.php | 148 + .../PHPExcel/Worksheet/Drawing/Shadow.php | 288 + .../PHPExcel/Worksheet/HeaderFooter.php | 465 ++ .../Worksheet/HeaderFooterDrawing.php | 350 + .../PHPExcel/Worksheet/MemoryDrawing.php | 200 + .../PHPExcel/Worksheet/PageMargins.php | 220 + .../PHPExcel/PHPExcel/Worksheet/PageSetup.php | 798 ++ .../PHPExcel/Worksheet/Protection.php | 545 ++ .../PHPExcel/PHPExcel/Worksheet/Row.php | 90 + .../PHPExcel/Worksheet/RowDimension.php | 265 + .../PHPExcel/Worksheet/RowIterator.php | 148 + .../PHPExcel/PHPExcel/Worksheet/SheetView.php | 188 + .../PHPExcel/PHPExcel/WorksheetIterator.php | 118 + .../PHPExcel/PHPExcel/Writer/Abstract.php | 158 + .../PHPExcel/PHPExcel/Writer/CSV.php | 310 + .../PHPExcel/PHPExcel/Writer/Excel2007.php | 532 ++ .../PHPExcel/Writer/Excel2007/Chart.php | 1203 +++ .../PHPExcel/Writer/Excel2007/Comments.php | 268 + .../Writer/Excel2007/ContentTypes.php | 287 + .../PHPExcel/Writer/Excel2007/DocProps.php | 272 + .../PHPExcel/Writer/Excel2007/Drawing.php | 598 ++ .../PHPExcel/Writer/Excel2007/Rels.php | 437 + .../PHPExcel/Writer/Excel2007/RelsRibbon.php | 77 + .../PHPExcel/Writer/Excel2007/RelsVBA.php | 72 + .../PHPExcel/Writer/Excel2007/StringTable.php | 319 + .../PHPExcel/Writer/Excel2007/Style.php | 704 ++ .../PHPExcel/Writer/Excel2007/Theme.php | 871 ++ .../PHPExcel/Writer/Excel2007/Workbook.php | 456 ++ .../PHPExcel/Writer/Excel2007/Worksheet.php | 1220 +++ .../PHPExcel/Writer/Excel2007/WriterPart.php | 81 + .../PHPExcel/PHPExcel/Writer/Excel5.php | 935 +++ .../PHPExcel/Writer/Excel5/BIFFwriter.php | 255 + .../PHPExcel/Writer/Excel5/Escher.php | 537 ++ .../PHPExcel/PHPExcel/Writer/Excel5/Font.php | 165 + .../PHPExcel/Writer/Excel5/Parser.php | 1582 ++++ .../PHPExcel/Writer/Excel5/Workbook.php | 1450 ++++ .../PHPExcel/Writer/Excel5/Worksheet.php | 3681 +++++++++ .../PHPExcel/PHPExcel/Writer/Excel5/Xf.php | 547 ++ .../PHPExcel/PHPExcel/Writer/Exception.php | 52 + .../PHPExcel/PHPExcel/Writer/HTML.php | 1532 ++++ .../PHPExcel/PHPExcel/Writer/IWriter.php | 46 + .../PHPExcel/PHPExcel/Writer/PDF.php | 90 + .../PHPExcel/PHPExcel/Writer/PDF/Core.php | 364 + .../PHPExcel/PHPExcel/Writer/PDF/DomPDF.php | 120 + .../PHPExcel/PHPExcel/Writer/PDF/mPDF.php | 130 + .../PHPExcel/PHPExcel/Writer/PDF/tcPDF.php | 136 + .../PHPExcel/PHPExcel/locale/bg/config | 49 + .../PHPExcel/PHPExcel/locale/cs/config | 47 + .../PHPExcel/PHPExcel/locale/cs/functions | 438 + .../PHPExcel/PHPExcel/locale/da/config | 48 + .../PHPExcel/PHPExcel/locale/da/functions | 438 + .../PHPExcel/PHPExcel/locale/de/config | 47 + .../PHPExcel/PHPExcel/locale/de/functions | 438 + .../PHPExcel/PHPExcel/locale/en/uk/config | 32 + .../PHPExcel/PHPExcel/locale/es/config | 47 + .../PHPExcel/PHPExcel/locale/es/functions | 438 + .../PHPExcel/PHPExcel/locale/fi/config | 47 + .../PHPExcel/PHPExcel/locale/fi/functions | 438 + .../PHPExcel/PHPExcel/locale/fr/config | 47 + .../PHPExcel/PHPExcel/locale/fr/functions | 438 + .../PHPExcel/PHPExcel/locale/hu/config | 47 + .../PHPExcel/PHPExcel/locale/hu/functions | 438 + .../PHPExcel/PHPExcel/locale/it/config | 47 + .../PHPExcel/PHPExcel/locale/it/functions | 438 + .../PHPExcel/PHPExcel/locale/nl/config | 47 + .../PHPExcel/PHPExcel/locale/nl/functions | 438 + .../PHPExcel/PHPExcel/locale/no/config | 47 + .../PHPExcel/PHPExcel/locale/no/functions | 438 + .../PHPExcel/PHPExcel/locale/pl/config | 47 + .../PHPExcel/PHPExcel/locale/pl/functions | 438 + .../PHPExcel/PHPExcel/locale/pt/br/config | 47 + .../PHPExcel/PHPExcel/locale/pt/br/functions | 408 + .../PHPExcel/PHPExcel/locale/pt/config | 47 + .../PHPExcel/PHPExcel/locale/pt/functions | 408 + .../PHPExcel/PHPExcel/locale/ru/config | 47 + .../PHPExcel/PHPExcel/locale/ru/functions | 438 + .../PHPExcel/PHPExcel/locale/sv/config | 47 + .../PHPExcel/PHPExcel/locale/sv/functions | 408 + .../PHPExcel/PHPExcel/locale/tr/config | 47 + .../PHPExcel/PHPExcel/locale/tr/functions | 438 + .../pay/models/IPayLinks_model.php | 34 + webht/third_party/pay/models/note_model.php | 40 + 264 files changed, 142381 insertions(+), 7 deletions(-) create mode 100644 ipaylinks_statement/Crypt/AES.php create mode 100644 ipaylinks_statement/Crypt/Base.php create mode 100644 ipaylinks_statement/Crypt/Blowfish.php create mode 100644 ipaylinks_statement/Crypt/DES.php create mode 100644 ipaylinks_statement/Crypt/Hash.php create mode 100644 ipaylinks_statement/Crypt/RC2.php create mode 100644 ipaylinks_statement/Crypt/RC4.php create mode 100644 ipaylinks_statement/Crypt/RSA.php create mode 100644 ipaylinks_statement/Crypt/Random.php create mode 100644 ipaylinks_statement/Crypt/Rijndael.php create mode 100644 ipaylinks_statement/Crypt/TripleDES.php create mode 100644 ipaylinks_statement/Crypt/Twofish.php create mode 100644 ipaylinks_statement/File/ANSI.php create mode 100644 ipaylinks_statement/File/ASN1.php create mode 100644 ipaylinks_statement/File/X509.php create mode 100644 ipaylinks_statement/Math/BigInteger.php create mode 100644 ipaylinks_statement/Net/SCP.php create mode 100644 ipaylinks_statement/Net/SFTP.php create mode 100644 ipaylinks_statement/Net/SFTP/Stream.php create mode 100644 ipaylinks_statement/Net/SSH1.php create mode 100644 ipaylinks_statement/Net/SSH2.php create mode 100644 ipaylinks_statement/System/SSH/Agent.php create mode 100644 ipaylinks_statement/System/SSH_Agent.php create mode 100644 ipaylinks_statement/bootstrap.php create mode 100644 ipaylinks_statement/download_files.php create mode 100644 ipaylinks_statement/openssl.cnf create mode 100644 ipaylinks_statement/statement_files/2018/01/20180127.xlsx create mode 100644 ipaylinks_statement/statement_files/2018/01/20180128.xlsx create mode 100644 ipaylinks_statement/statement_files/2018/01/20180129.xlsx create mode 100644 ipaylinks_statement/statement_files/2018/01/20180130.xlsx create mode 100644 ipaylinks_statement/statement_files/2018/01/20180131.xlsx create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Financial.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/IOFactory.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config create mode 100644 webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions diff --git a/.gitignore b/.gitignore index e721c211..a8e80dfb 100644 --- a/.gitignore +++ b/.gitignore @@ -4,4 +4,4 @@ /kcfinder/upload/* /kcfinder/cache/* */cache/* - +*/statement_files/* diff --git a/ipaylinks_statement/Crypt/AES.php b/ipaylinks_statement/Crypt/AES.php new file mode 100644 index 00000000..594011e5 --- /dev/null +++ b/ipaylinks_statement/Crypt/AES.php @@ -0,0 +1,197 @@ + + * setKey('abcdefghijklmnop'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $aes->decrypt($aes->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_AES + * @author Jim Wigginton + * @copyright 2008 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Rijndael + */ +if (!class_exists('Crypt_Rijndael')) { + include_once 'Rijndael.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_AES_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_AES_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_AES_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_AES_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_AES_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of AES. + * + * @package Crypt_AES + * @author Jim Wigginton + * @access public + */ +class Crypt_AES extends Crypt_Rijndael +{ + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'AES'; + + /** + * Dummy function + * + * Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything. + * + * @see Crypt_Rijndael::setBlockLength() + * @access public + * @param int $length + */ + function setBlockLength($length) + { + return; + } + + /** + * Sets the key length + * + * Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to + * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. + * + * @see Crypt_Rijndael:setKeyLength() + * @access public + * @param int $length + */ + function setKeyLength($length) + { + switch ($length) { + case 160: + $length = 192; + break; + case 224: + $length = 256; + } + parent::setKeyLength($length); + } + + /** + * Sets the key. + * + * Rijndael supports five different key lengths, AES only supports three. + * + * @see Crypt_Rijndael:setKey() + * @see setKeyLength() + * @access public + * @param string $key + */ + function setKey($key) + { + parent::setKey($key); + + if (!$this->explicit_key_length) { + $length = strlen($key); + switch (true) { + case $length <= 16: + $this->key_length = 16; + break; + case $length <= 24: + $this->key_length = 24; + break; + default: + $this->key_length = 32; + } + $this->_setEngine(); + } + } +} diff --git a/ipaylinks_statement/Crypt/Base.php b/ipaylinks_statement/Crypt/Base.php new file mode 100644 index 00000000..d3db1173 --- /dev/null +++ b/ipaylinks_statement/Crypt/Base.php @@ -0,0 +1,2616 @@ + + * @author Hans-Juergen Petrich + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_MODE_CTR', -1); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_MODE_ECB', 1); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_MODE_CBC', 2); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_MODE_CFB', 3); +/** + * Encrypt / decrypt using the Output Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_MODE_OFB', 4); +/** + * Encrypt / decrypt using streaming mode. + */ +define('CRYPT_MODE_STREAM', 5); +/**#@-*/ + +/**#@+ + * @access private + * @see self::Crypt_Base() + * @internal These constants are for internal use only + */ +/** + * Base value for the internal implementation $engine switch + */ +define('CRYPT_ENGINE_INTERNAL', 1); +/** + * Base value for the mcrypt implementation $engine switch + */ +define('CRYPT_ENGINE_MCRYPT', 2); +/** + * Base value for the OpenSSL implementation $engine switch + */ +define('CRYPT_ENGINE_OPENSSL', 3); +/**#@-*/ + +/** + * Base Class for all Crypt_* cipher classes + * + * @package Crypt_Base + * @author Jim Wigginton + * @author Hans-Juergen Petrich + * @access public + */ +class Crypt_Base +{ + /** + * The Encryption Mode + * + * @see self::Crypt_Base() + * @var int + * @access private + */ + var $mode; + + /** + * The Block Length of the block cipher + * + * @var int + * @access private + */ + var $block_size = 16; + + /** + * The Key + * + * @see self::setKey() + * @var string + * @access private + */ + var $key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; + + /** + * The Initialization Vector + * + * @see self::setIV() + * @var string + * @access private + */ + var $iv; + + /** + * A "sliding" Initialization Vector + * + * @see self::enableContinuousBuffer() + * @see self::_clearBuffers() + * @var string + * @access private + */ + var $encryptIV; + + /** + * A "sliding" Initialization Vector + * + * @see self::enableContinuousBuffer() + * @see self::_clearBuffers() + * @var string + * @access private + */ + var $decryptIV; + + /** + * Continuous Buffer status + * + * @see self::enableContinuousBuffer() + * @var bool + * @access private + */ + var $continuousBuffer = false; + + /** + * Encryption buffer for CTR, OFB and CFB modes + * + * @see self::encrypt() + * @see self::_clearBuffers() + * @var array + * @access private + */ + var $enbuffer; + + /** + * Decryption buffer for CTR, OFB and CFB modes + * + * @see self::decrypt() + * @see self::_clearBuffers() + * @var array + * @access private + */ + var $debuffer; + + /** + * mcrypt resource for encryption + * + * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. + * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. + * + * @see self::encrypt() + * @var resource + * @access private + */ + var $enmcrypt; + + /** + * mcrypt resource for decryption + * + * The mcrypt resource can be recreated every time something needs to be created or it can be created just once. + * Since mcrypt operates in continuous mode, by default, it'll need to be recreated when in non-continuous mode. + * + * @see self::decrypt() + * @var resource + * @access private + */ + var $demcrypt; + + /** + * Does the enmcrypt resource need to be (re)initialized? + * + * @see Crypt_Twofish::setKey() + * @see Crypt_Twofish::setIV() + * @var bool + * @access private + */ + var $enchanged = true; + + /** + * Does the demcrypt resource need to be (re)initialized? + * + * @see Crypt_Twofish::setKey() + * @see Crypt_Twofish::setIV() + * @var bool + * @access private + */ + var $dechanged = true; + + /** + * mcrypt resource for CFB mode + * + * mcrypt's CFB mode, in (and only in) buffered context, + * is broken, so phpseclib implements the CFB mode by it self, + * even when the mcrypt php extension is available. + * + * In order to do the CFB-mode work (fast) phpseclib + * use a separate ECB-mode mcrypt resource. + * + * @link http://phpseclib.sourceforge.net/cfb-demo.phps + * @see self::encrypt() + * @see self::decrypt() + * @see self::_setupMcrypt() + * @var resource + * @access private + */ + var $ecb; + + /** + * Optimizing value while CFB-encrypting + * + * Only relevant if $continuousBuffer enabled + * and $engine == CRYPT_ENGINE_MCRYPT + * + * It's faster to re-init $enmcrypt if + * $buffer bytes > $cfb_init_len than + * using the $ecb resource furthermore. + * + * This value depends of the chosen cipher + * and the time it would be needed for it's + * initialization [by mcrypt_generic_init()] + * which, typically, depends on the complexity + * on its internaly Key-expanding algorithm. + * + * @see self::encrypt() + * @var int + * @access private + */ + var $cfb_init_len = 600; + + /** + * Does internal cipher state need to be (re)initialized? + * + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() + * @var bool + * @access private + */ + var $changed = true; + + /** + * Padding status + * + * @see self::enablePadding() + * @var bool + * @access private + */ + var $padding = true; + + /** + * Is the mode one that is paddable? + * + * @see self::Crypt_Base() + * @var bool + * @access private + */ + var $paddable = false; + + /** + * Holds which crypt engine internaly should be use, + * which will be determined automatically on __construct() + * + * Currently available $engines are: + * - CRYPT_ENGINE_OPENSSL (very fast, php-extension: openssl, extension_loaded('openssl') required) + * - CRYPT_ENGINE_MCRYPT (fast, php-extension: mcrypt, extension_loaded('mcrypt') required) + * - CRYPT_ENGINE_INTERNAL (slower, pure php-engine, no php-extension required) + * + * @see self::_setEngine() + * @see self::encrypt() + * @see self::decrypt() + * @var int + * @access private + */ + var $engine; + + /** + * Holds the preferred crypt engine + * + * @see self::_setEngine() + * @see self::setPreferredEngine() + * @var int + * @access private + */ + var $preferredEngine; + + /** + * The mcrypt specific name of the cipher + * + * Only used if $engine == CRYPT_ENGINE_MCRYPT + * + * @link http://www.php.net/mcrypt_module_open + * @link http://www.php.net/mcrypt_list_algorithms + * @see self::_setupMcrypt() + * @var string + * @access private + */ + var $cipher_name_mcrypt; + + /** + * The openssl specific name of the cipher + * + * Only used if $engine == CRYPT_ENGINE_OPENSSL + * + * @link http://www.php.net/openssl-get-cipher-methods + * @var string + * @access private + */ + var $cipher_name_openssl; + + /** + * The openssl specific name of the cipher in ECB mode + * + * If OpenSSL does not support the mode we're trying to use (CTR) + * it can still be emulated with ECB mode. + * + * @link http://www.php.net/openssl-get-cipher-methods + * @var string + * @access private + */ + var $cipher_name_openssl_ecb; + + /** + * The default salt used by setPassword() + * + * @see self::setPassword() + * @var string + * @access private + */ + var $password_default_salt = 'phpseclib/salt'; + + /** + * The namespace used by the cipher for its constants. + * + * ie: AES.php is using CRYPT_AES_MODE_* for its constants + * so $const_namespace is AES + * + * DES.php is using CRYPT_DES_MODE_* for its constants + * so $const_namespace is DES... and so on + * + * All CRYPT_<$const_namespace>_MODE_* are aliases of + * the generic CRYPT_MODE_* constants, so both could be used + * for each cipher. + * + * Example: + * $aes = new Crypt_AES(CRYPT_AES_MODE_CFB); // $aes will operate in cfb mode + * $aes = new Crypt_AES(CRYPT_MODE_CFB); // identical + * + * @see self::Crypt_Base() + * @var string + * @access private + */ + var $const_namespace; + + /** + * The name of the performance-optimized callback function + * + * Used by encrypt() / decrypt() + * only if $engine == CRYPT_ENGINE_INTERNAL + * + * @see self::encrypt() + * @see self::decrypt() + * @see self::_setupInlineCrypt() + * @see self::$use_inline_crypt + * @var Callback + * @access private + */ + var $inline_crypt; + + /** + * Holds whether performance-optimized $inline_crypt() can/should be used. + * + * @see self::encrypt() + * @see self::decrypt() + * @see self::inline_crypt + * @var mixed + * @access private + */ + var $use_inline_crypt; + + /** + * If OpenSSL can be used in ECB but not in CTR we can emulate CTR + * + * @see self::_openssl_ctr_process() + * @var bool + * @access private + */ + var $openssl_emulate_ctr = false; + + /** + * Determines what options are passed to openssl_encrypt/decrypt + * + * @see self::isValidEngine() + * @var mixed + * @access private + */ + var $openssl_options; + + /** + * Has the key length explicitly been set or should it be derived from the key, itself? + * + * @see self::setKeyLength() + * @var bool + * @access private + */ + var $explicit_key_length = false; + + /** + * Don't truncate / null pad key + * + * @see self::_clearBuffers() + * @var bool + * @access private + */ + var $skip_key_adjustment = false; + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. + * + * $mode could be: + * + * - CRYPT_MODE_ECB + * + * - CRYPT_MODE_CBC + * + * - CRYPT_MODE_CTR + * + * - CRYPT_MODE_CFB + * + * - CRYPT_MODE_OFB + * + * (or the alias constants of the chosen cipher, for example for AES: CRYPT_AES_MODE_ECB or CRYPT_AES_MODE_CBC ...) + * + * If not explicitly set, CRYPT_MODE_CBC will be used. + * + * @param int $mode + * @access public + */ + function __construct($mode = CRYPT_MODE_CBC) + { + // $mode dependent settings + switch ($mode) { + case CRYPT_MODE_ECB: + $this->paddable = true; + $this->mode = CRYPT_MODE_ECB; + break; + case CRYPT_MODE_CTR: + case CRYPT_MODE_CFB: + case CRYPT_MODE_OFB: + case CRYPT_MODE_STREAM: + $this->mode = $mode; + break; + case CRYPT_MODE_CBC: + default: + $this->paddable = true; + $this->mode = CRYPT_MODE_CBC; + } + + $this->_setEngine(); + + // Determining whether inline crypting can be used by the cipher + if ($this->use_inline_crypt !== false) { + $this->use_inline_crypt = version_compare(PHP_VERSION, '5.3.0') >= 0 || function_exists('create_function'); + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param int $mode + * @access public + */ + function Crypt_Base($mode = CRYPT_MODE_CBC) + { + $this->__construct($mode); + } + + /** + * Sets the initialization vector. (optional) + * + * SetIV is not required when CRYPT_MODE_ECB (or ie for AES: CRYPT_AES_MODE_ECB) is being used. If not explicitly set, it'll be assumed + * to be all zero's. + * + * @access public + * @param string $iv + * @internal Can be overwritten by a sub class, but does not have to be + */ + function setIV($iv) + { + if ($this->mode == CRYPT_MODE_ECB) { + return; + } + + $this->iv = $iv; + $this->changed = true; + } + + /** + * Sets the key length. + * + * Keys with explicitly set lengths need to be treated accordingly + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + $this->explicit_key_length = true; + $this->changed = true; + $this->_setEngine(); + } + + /** + * Returns the current key length in bits + * + * @access public + * @return int + */ + function getKeyLength() + { + return $this->key_length << 3; + } + + /** + * Returns the current block length in bits + * + * @access public + * @return int + */ + function getBlockLength() + { + return $this->block_size << 3; + } + + /** + * Sets the key. + * + * The min/max length(s) of the key depends on the cipher which is used. + * If the key not fits the length(s) of the cipher it will paded with null bytes + * up to the closest valid key length. If the key is more than max length, + * we trim the excess bits. + * + * If the key is not explicitly set, it'll be assumed to be all null bytes. + * + * @access public + * @param string $key + * @internal Could, but not must, extend by the child Crypt_* class + */ + function setKey($key) + { + if (!$this->explicit_key_length) { + $this->setKeyLength(strlen($key) << 3); + $this->explicit_key_length = false; + } + + $this->key = $key; + $this->changed = true; + $this->_setEngine(); + } + + /** + * Sets the password. + * + * Depending on what $method is set to, setPassword()'s (optional) parameters are as follows: + * {@link http://en.wikipedia.org/wiki/PBKDF2 pbkdf2} or pbkdf1: + * $hash, $salt, $count, $dkLen + * + * Where $hash (default = sha1) currently supports the following hashes: see: Crypt/Hash.php + * + * @see Crypt/Hash.php + * @param string $password + * @param string $method + * @return bool + * @access public + * @internal Could, but not must, extend by the child Crypt_* class + */ + function setPassword($password, $method = 'pbkdf2') + { + $key = ''; + + switch ($method) { + default: // 'pbkdf2' or 'pbkdf1' + $func_args = func_get_args(); + + // Hash function + $hash = isset($func_args[2]) ? $func_args[2] : 'sha1'; + + // WPA and WPA2 use the SSID as the salt + $salt = isset($func_args[3]) ? $func_args[3] : $this->password_default_salt; + + // RFC2898#section-4.2 uses 1,000 iterations by default + // WPA and WPA2 use 4,096. + $count = isset($func_args[4]) ? $func_args[4] : 1000; + + // Keylength + if (isset($func_args[5])) { + $dkLen = $func_args[5]; + } else { + $dkLen = $method == 'pbkdf1' ? 2 * $this->key_length : $this->key_length; + } + + switch (true) { + case $method == 'pbkdf1': + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + $hashObj = new Crypt_Hash(); + $hashObj->setHash($hash); + if ($dkLen > $hashObj->getLength()) { + user_error('Derived key too long'); + return false; + } + $t = $password . $salt; + for ($i = 0; $i < $count; ++$i) { + $t = $hashObj->hash($t); + } + $key = substr($t, 0, $dkLen); + + $this->setKey(substr($key, 0, $dkLen >> 1)); + $this->setIV(substr($key, $dkLen >> 1)); + + return true; + // Determining if php[>=5.5.0]'s hash_pbkdf2() function avail- and useable + case !function_exists('hash_pbkdf2'): + case !function_exists('hash_algos'): + case !in_array($hash, hash_algos()): + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + $i = 1; + while (strlen($key) < $dkLen) { + $hmac = new Crypt_Hash(); + $hmac->setHash($hash); + $hmac->setKey($password); + $f = $u = $hmac->hash($salt . pack('N', $i++)); + for ($j = 2; $j <= $count; ++$j) { + $u = $hmac->hash($u); + $f^= $u; + } + $key.= $f; + } + $key = substr($key, 0, $dkLen); + break; + default: + $key = hash_pbkdf2($hash, $password, $salt, $count, $dkLen, true); + } + } + + $this->setKey($key); + + return true; + } + + /** + * Encrypts a message. + * + * $plaintext will be padded with additional bytes such that it's length is a multiple of the block size. Other cipher + * implementations may or may not pad in the same manner. Other common approaches to padding and the reasons why it's + * necessary are discussed in the following + * URL: + * + * {@link http://www.di-mgt.com.au/cryptopad.html http://www.di-mgt.com.au/cryptopad.html} + * + * An alternative to padding is to, separately, send the length of the file. This is what SSH, in fact, does. + * strlen($plaintext) will still need to be a multiple of the block size, however, arbitrary values can be added to make it that + * length. + * + * @see self::decrypt() + * @access public + * @param string $plaintext + * @return string $ciphertext + * @internal Could, but not must, extend by the child Crypt_* class + */ + function encrypt($plaintext) + { + if ($this->paddable) { + $plaintext = $this->_pad($plaintext); + } + + if ($this->engine === CRYPT_ENGINE_OPENSSL) { + if ($this->changed) { + $this->_clearBuffers(); + $this->changed = false; + } + switch ($this->mode) { + case CRYPT_MODE_STREAM: + return openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options); + case CRYPT_MODE_ECB: + $result = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options); + return !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result; + case CRYPT_MODE_CBC: + $result = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->encryptIV); + if (!defined('OPENSSL_RAW_DATA')) { + $result = substr($result, 0, -$this->block_size); + } + if ($this->continuousBuffer) { + $this->encryptIV = substr($result, -$this->block_size); + } + return $result; + case CRYPT_MODE_CTR: + return $this->_openssl_ctr_process($plaintext, $this->encryptIV, $this->enbuffer); + case CRYPT_MODE_CFB: + // cfb loosely routines inspired by openssl's: + // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1} + $ciphertext = ''; + if ($this->continuousBuffer) { + $iv = &$this->encryptIV; + $pos = &$this->enbuffer['pos']; + } else { + $iv = $this->encryptIV; + $pos = 0; + } + $len = strlen($plaintext); + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $this->block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize + $ciphertext = substr($iv, $orig_pos) ^ $plaintext; + $iv = substr_replace($iv, $ciphertext, $orig_pos, $i); + $plaintext = substr($plaintext, $i); + } + + $overflow = $len % $this->block_size; + + if ($overflow) { + $ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv); + $iv = $this->_string_pop($ciphertext, $this->block_size); + + $size = $len - $overflow; + $block = $iv ^ substr($plaintext, -$overflow); + $iv = substr_replace($iv, $block, 0, $overflow); + $ciphertext.= $block; + $pos = $overflow; + } elseif ($len) { + $ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv); + $iv = substr($ciphertext, -$this->block_size); + } + + return $ciphertext; + case CRYPT_MODE_OFB: + return $this->_openssl_ofb_process($plaintext, $this->encryptIV, $this->enbuffer); + } + } + + if ($this->engine === CRYPT_ENGINE_MCRYPT) { + if ($this->changed) { + $this->_setupMcrypt(); + $this->changed = false; + } + if ($this->enchanged) { + @mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); + $this->enchanged = false; + } + + // re: {@link http://phpseclib.sourceforge.net/cfb-demo.phps} + // using mcrypt's default handing of CFB the above would output two different things. using phpseclib's + // rewritten CFB implementation the above outputs the same thing twice. + if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) { + $block_size = $this->block_size; + $iv = &$this->encryptIV; + $pos = &$this->enbuffer['pos']; + $len = strlen($plaintext); + $ciphertext = ''; + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + $ciphertext = substr($iv, $orig_pos) ^ $plaintext; + $iv = substr_replace($iv, $ciphertext, $orig_pos, $i); + $this->enbuffer['enmcrypt_init'] = true; + } + if ($len >= $block_size) { + if ($this->enbuffer['enmcrypt_init'] === false || $len > $this->cfb_init_len) { + if ($this->enbuffer['enmcrypt_init'] === true) { + @mcrypt_generic_init($this->enmcrypt, $this->key, $iv); + $this->enbuffer['enmcrypt_init'] = false; + } + $ciphertext.= @mcrypt_generic($this->enmcrypt, substr($plaintext, $i, $len - $len % $block_size)); + $iv = substr($ciphertext, -$block_size); + $len%= $block_size; + } else { + while ($len >= $block_size) { + $iv = @mcrypt_generic($this->ecb, $iv) ^ substr($plaintext, $i, $block_size); + $ciphertext.= $iv; + $len-= $block_size; + $i+= $block_size; + } + } + } + + if ($len) { + $iv = @mcrypt_generic($this->ecb, $iv); + $block = $iv ^ substr($plaintext, -$len); + $iv = substr_replace($iv, $block, 0, $len); + $ciphertext.= $block; + $pos = $len; + } + + return $ciphertext; + } + + $ciphertext = @mcrypt_generic($this->enmcrypt, $plaintext); + + if (!$this->continuousBuffer) { + @mcrypt_generic_init($this->enmcrypt, $this->key, $this->encryptIV); + } + + return $ciphertext; + } + + if ($this->changed) { + $this->_setup(); + $this->changed = false; + } + if ($this->use_inline_crypt) { + $inline = $this->inline_crypt; + return $inline('encrypt', $this, $plaintext); + } + + $buffer = &$this->enbuffer; + $block_size = $this->block_size; + $ciphertext = ''; + switch ($this->mode) { + case CRYPT_MODE_ECB: + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $ciphertext.= $this->_encryptBlock(substr($plaintext, $i, $block_size)); + } + break; + case CRYPT_MODE_CBC: + $xor = $this->encryptIV; + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + $block = $this->_encryptBlock($block ^ $xor); + $xor = $block; + $ciphertext.= $block; + } + if ($this->continuousBuffer) { + $this->encryptIV = $xor; + } + break; + case CRYPT_MODE_CTR: + $xor = $this->encryptIV; + if (strlen($buffer['ciphertext'])) { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + if (strlen($block) > strlen($buffer['ciphertext'])) { + $buffer['ciphertext'].= $this->_encryptBlock($xor); + } + $this->_increment_str($xor); + $key = $this->_string_shift($buffer['ciphertext'], $block_size); + $ciphertext.= $block ^ $key; + } + } else { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + $key = $this->_encryptBlock($xor); + $this->_increment_str($xor); + $ciphertext.= $block ^ $key; + } + } + if ($this->continuousBuffer) { + $this->encryptIV = $xor; + if ($start = strlen($plaintext) % $block_size) { + $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext']; + } + } + break; + case CRYPT_MODE_CFB: + // cfb loosely routines inspired by openssl's: + // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1} + if ($this->continuousBuffer) { + $iv = &$this->encryptIV; + $pos = &$buffer['pos']; + } else { + $iv = $this->encryptIV; + $pos = 0; + } + $len = strlen($plaintext); + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize + $ciphertext = substr($iv, $orig_pos) ^ $plaintext; + $iv = substr_replace($iv, $ciphertext, $orig_pos, $i); + } + while ($len >= $block_size) { + $iv = $this->_encryptBlock($iv) ^ substr($plaintext, $i, $block_size); + $ciphertext.= $iv; + $len-= $block_size; + $i+= $block_size; + } + if ($len) { + $iv = $this->_encryptBlock($iv); + $block = $iv ^ substr($plaintext, $i); + $iv = substr_replace($iv, $block, 0, $len); + $ciphertext.= $block; + $pos = $len; + } + break; + case CRYPT_MODE_OFB: + $xor = $this->encryptIV; + if (strlen($buffer['xor'])) { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + if (strlen($block) > strlen($buffer['xor'])) { + $xor = $this->_encryptBlock($xor); + $buffer['xor'].= $xor; + } + $key = $this->_string_shift($buffer['xor'], $block_size); + $ciphertext.= $block ^ $key; + } + } else { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $xor = $this->_encryptBlock($xor); + $ciphertext.= substr($plaintext, $i, $block_size) ^ $xor; + } + $key = $xor; + } + if ($this->continuousBuffer) { + $this->encryptIV = $xor; + if ($start = strlen($plaintext) % $block_size) { + $buffer['xor'] = substr($key, $start) . $buffer['xor']; + } + } + break; + case CRYPT_MODE_STREAM: + $ciphertext = $this->_encryptBlock($plaintext); + break; + } + + return $ciphertext; + } + + /** + * Decrypts a message. + * + * If strlen($ciphertext) is not a multiple of the block size, null bytes will be added to the end of the string until + * it is. + * + * @see self::encrypt() + * @access public + * @param string $ciphertext + * @return string $plaintext + * @internal Could, but not must, extend by the child Crypt_* class + */ + function decrypt($ciphertext) + { + if ($this->paddable) { + // we pad with chr(0) since that's what mcrypt_generic does. to quote from {@link http://www.php.net/function.mcrypt-generic}: + // "The data is padded with "\0" to make sure the length of the data is n * blocksize." + $ciphertext = str_pad($ciphertext, strlen($ciphertext) + ($this->block_size - strlen($ciphertext) % $this->block_size) % $this->block_size, chr(0)); + } + + if ($this->engine === CRYPT_ENGINE_OPENSSL) { + if ($this->changed) { + $this->_clearBuffers(); + $this->changed = false; + } + switch ($this->mode) { + case CRYPT_MODE_STREAM: + $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options); + break; + case CRYPT_MODE_ECB: + if (!defined('OPENSSL_RAW_DATA')) { + $ciphertext.= openssl_encrypt('', $this->cipher_name_openssl_ecb, $this->key, true); + } + $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options); + break; + case CRYPT_MODE_CBC: + if (!defined('OPENSSL_RAW_DATA')) { + $padding = str_repeat(chr($this->block_size), $this->block_size) ^ substr($ciphertext, -$this->block_size); + $ciphertext.= substr(openssl_encrypt($padding, $this->cipher_name_openssl_ecb, $this->key, true), 0, $this->block_size); + $offset = 2 * $this->block_size; + } else { + $offset = $this->block_size; + } + $plaintext = openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $this->decryptIV); + if ($this->continuousBuffer) { + $this->decryptIV = substr($ciphertext, -$offset, $this->block_size); + } + break; + case CRYPT_MODE_CTR: + $plaintext = $this->_openssl_ctr_process($ciphertext, $this->decryptIV, $this->debuffer); + break; + case CRYPT_MODE_CFB: + // cfb loosely routines inspired by openssl's: + // {@link http://cvs.openssl.org/fileview?f=openssl/crypto/modes/cfb128.c&v=1.3.2.2.2.1} + $plaintext = ''; + if ($this->continuousBuffer) { + $iv = &$this->decryptIV; + $pos = &$this->buffer['pos']; + } else { + $iv = $this->decryptIV; + $pos = 0; + } + $len = strlen($ciphertext); + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $this->block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $this->blocksize + $plaintext = substr($iv, $orig_pos) ^ $ciphertext; + $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i); + $ciphertext = substr($ciphertext, $i); + } + $overflow = $len % $this->block_size; + if ($overflow) { + $plaintext.= openssl_decrypt(substr($ciphertext, 0, -$overflow), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv); + if ($len - $overflow) { + $iv = substr($ciphertext, -$overflow - $this->block_size, -$overflow); + } + $iv = openssl_encrypt(str_repeat("\0", $this->block_size), $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv); + $plaintext.= $iv ^ substr($ciphertext, -$overflow); + $iv = substr_replace($iv, substr($ciphertext, -$overflow), 0, $overflow); + $pos = $overflow; + } elseif ($len) { + $plaintext.= openssl_decrypt($ciphertext, $this->cipher_name_openssl, $this->key, $this->openssl_options, $iv); + $iv = substr($ciphertext, -$this->block_size); + } + break; + case CRYPT_MODE_OFB: + $plaintext = $this->_openssl_ofb_process($ciphertext, $this->decryptIV, $this->debuffer); + } + + return $this->paddable ? $this->_unpad($plaintext) : $plaintext; + } + + if ($this->engine === CRYPT_ENGINE_MCRYPT) { + $block_size = $this->block_size; + if ($this->changed) { + $this->_setupMcrypt(); + $this->changed = false; + } + if ($this->dechanged) { + @mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); + $this->dechanged = false; + } + + if ($this->mode == CRYPT_MODE_CFB && $this->continuousBuffer) { + $iv = &$this->decryptIV; + $pos = &$this->debuffer['pos']; + $len = strlen($ciphertext); + $plaintext = ''; + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize + $plaintext = substr($iv, $orig_pos) ^ $ciphertext; + $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i); + } + if ($len >= $block_size) { + $cb = substr($ciphertext, $i, $len - $len % $block_size); + $plaintext.= @mcrypt_generic($this->ecb, $iv . $cb) ^ $cb; + $iv = substr($cb, -$block_size); + $len%= $block_size; + } + if ($len) { + $iv = @mcrypt_generic($this->ecb, $iv); + $plaintext.= $iv ^ substr($ciphertext, -$len); + $iv = substr_replace($iv, substr($ciphertext, -$len), 0, $len); + $pos = $len; + } + + return $plaintext; + } + + $plaintext = @mdecrypt_generic($this->demcrypt, $ciphertext); + + if (!$this->continuousBuffer) { + @mcrypt_generic_init($this->demcrypt, $this->key, $this->decryptIV); + } + + return $this->paddable ? $this->_unpad($plaintext) : $plaintext; + } + + if ($this->changed) { + $this->_setup(); + $this->changed = false; + } + if ($this->use_inline_crypt) { + $inline = $this->inline_crypt; + return $inline('decrypt', $this, $ciphertext); + } + + $block_size = $this->block_size; + + $buffer = &$this->debuffer; + $plaintext = ''; + switch ($this->mode) { + case CRYPT_MODE_ECB: + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $plaintext.= $this->_decryptBlock(substr($ciphertext, $i, $block_size)); + } + break; + case CRYPT_MODE_CBC: + $xor = $this->decryptIV; + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $block = substr($ciphertext, $i, $block_size); + $plaintext.= $this->_decryptBlock($block) ^ $xor; + $xor = $block; + } + if ($this->continuousBuffer) { + $this->decryptIV = $xor; + } + break; + case CRYPT_MODE_CTR: + $xor = $this->decryptIV; + if (strlen($buffer['ciphertext'])) { + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $block = substr($ciphertext, $i, $block_size); + if (strlen($block) > strlen($buffer['ciphertext'])) { + $buffer['ciphertext'].= $this->_encryptBlock($xor); + $this->_increment_str($xor); + } + $key = $this->_string_shift($buffer['ciphertext'], $block_size); + $plaintext.= $block ^ $key; + } + } else { + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $block = substr($ciphertext, $i, $block_size); + $key = $this->_encryptBlock($xor); + $this->_increment_str($xor); + $plaintext.= $block ^ $key; + } + } + if ($this->continuousBuffer) { + $this->decryptIV = $xor; + if ($start = strlen($ciphertext) % $block_size) { + $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext']; + } + } + break; + case CRYPT_MODE_CFB: + if ($this->continuousBuffer) { + $iv = &$this->decryptIV; + $pos = &$buffer['pos']; + } else { + $iv = $this->decryptIV; + $pos = 0; + } + $len = strlen($ciphertext); + $i = 0; + if ($pos) { + $orig_pos = $pos; + $max = $block_size - $pos; + if ($len >= $max) { + $i = $max; + $len-= $max; + $pos = 0; + } else { + $i = $len; + $pos+= $len; + $len = 0; + } + // ie. $i = min($max, $len), $len-= $i, $pos+= $i, $pos%= $blocksize + $plaintext = substr($iv, $orig_pos) ^ $ciphertext; + $iv = substr_replace($iv, substr($ciphertext, 0, $i), $orig_pos, $i); + } + while ($len >= $block_size) { + $iv = $this->_encryptBlock($iv); + $cb = substr($ciphertext, $i, $block_size); + $plaintext.= $iv ^ $cb; + $iv = $cb; + $len-= $block_size; + $i+= $block_size; + } + if ($len) { + $iv = $this->_encryptBlock($iv); + $plaintext.= $iv ^ substr($ciphertext, $i); + $iv = substr_replace($iv, substr($ciphertext, $i), 0, $len); + $pos = $len; + } + break; + case CRYPT_MODE_OFB: + $xor = $this->decryptIV; + if (strlen($buffer['xor'])) { + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $block = substr($ciphertext, $i, $block_size); + if (strlen($block) > strlen($buffer['xor'])) { + $xor = $this->_encryptBlock($xor); + $buffer['xor'].= $xor; + } + $key = $this->_string_shift($buffer['xor'], $block_size); + $plaintext.= $block ^ $key; + } + } else { + for ($i = 0; $i < strlen($ciphertext); $i+=$block_size) { + $xor = $this->_encryptBlock($xor); + $plaintext.= substr($ciphertext, $i, $block_size) ^ $xor; + } + $key = $xor; + } + if ($this->continuousBuffer) { + $this->decryptIV = $xor; + if ($start = strlen($ciphertext) % $block_size) { + $buffer['xor'] = substr($key, $start) . $buffer['xor']; + } + } + break; + case CRYPT_MODE_STREAM: + $plaintext = $this->_decryptBlock($ciphertext); + break; + } + return $this->paddable ? $this->_unpad($plaintext) : $plaintext; + } + + /** + * OpenSSL CTR Processor + * + * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream + * for CTR is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() + * and Crypt_Base::decrypt(). Also, OpenSSL doesn't implement CTR for all of it's symmetric ciphers so this + * function will emulate CTR with ECB when necessary. + * + * @see self::encrypt() + * @see self::decrypt() + * @param string $plaintext + * @param string $encryptIV + * @param array $buffer + * @return string + * @access private + */ + function _openssl_ctr_process($plaintext, &$encryptIV, &$buffer) + { + $ciphertext = ''; + + $block_size = $this->block_size; + $key = $this->key; + + if ($this->openssl_emulate_ctr) { + $xor = $encryptIV; + if (strlen($buffer['ciphertext'])) { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + if (strlen($block) > strlen($buffer['ciphertext'])) { + $result = openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, $this->openssl_options); + $result = !defined('OPENSSL_RAW_DATA') ? substr($result, 0, -$this->block_size) : $result; + $buffer['ciphertext'].= $result; + } + $this->_increment_str($xor); + $otp = $this->_string_shift($buffer['ciphertext'], $block_size); + $ciphertext.= $block ^ $otp; + } + } else { + for ($i = 0; $i < strlen($plaintext); $i+=$block_size) { + $block = substr($plaintext, $i, $block_size); + $otp = openssl_encrypt($xor, $this->cipher_name_openssl_ecb, $key, $this->openssl_options); + $otp = !defined('OPENSSL_RAW_DATA') ? substr($otp, 0, -$this->block_size) : $otp; + $this->_increment_str($xor); + $ciphertext.= $block ^ $otp; + } + } + if ($this->continuousBuffer) { + $encryptIV = $xor; + if ($start = strlen($plaintext) % $block_size) { + $buffer['ciphertext'] = substr($key, $start) . $buffer['ciphertext']; + } + } + + return $ciphertext; + } + + if (strlen($buffer['ciphertext'])) { + $ciphertext = $plaintext ^ $this->_string_shift($buffer['ciphertext'], strlen($plaintext)); + $plaintext = substr($plaintext, strlen($ciphertext)); + + if (!strlen($plaintext)) { + return $ciphertext; + } + } + + $overflow = strlen($plaintext) % $block_size; + if ($overflow) { + $plaintext2 = $this->_string_pop($plaintext, $overflow); // ie. trim $plaintext to a multiple of $block_size and put rest of $plaintext in $plaintext2 + $encrypted = openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV); + $temp = $this->_string_pop($encrypted, $block_size); + $ciphertext.= $encrypted . ($plaintext2 ^ $temp); + if ($this->continuousBuffer) { + $buffer['ciphertext'] = substr($temp, $overflow); + $encryptIV = $temp; + } + } elseif (!strlen($buffer['ciphertext'])) { + $ciphertext.= openssl_encrypt($plaintext . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV); + $temp = $this->_string_pop($ciphertext, $block_size); + if ($this->continuousBuffer) { + $encryptIV = $temp; + } + } + if ($this->continuousBuffer) { + if (!defined('OPENSSL_RAW_DATA')) { + $encryptIV.= openssl_encrypt('', $this->cipher_name_openssl_ecb, $key, $this->openssl_options); + } + $encryptIV = openssl_decrypt($encryptIV, $this->cipher_name_openssl_ecb, $key, $this->openssl_options); + if ($overflow) { + $this->_increment_str($encryptIV); + } + } + + return $ciphertext; + } + + /** + * OpenSSL OFB Processor + * + * PHP's OpenSSL bindings do not operate in continuous mode so we'll wrap around it. Since the keystream + * for OFB is the same for both encrypting and decrypting this function is re-used by both Crypt_Base::encrypt() + * and Crypt_Base::decrypt(). + * + * @see self::encrypt() + * @see self::decrypt() + * @param string $plaintext + * @param string $encryptIV + * @param array $buffer + * @return string + * @access private + */ + function _openssl_ofb_process($plaintext, &$encryptIV, &$buffer) + { + if (strlen($buffer['xor'])) { + $ciphertext = $plaintext ^ $buffer['xor']; + $buffer['xor'] = substr($buffer['xor'], strlen($ciphertext)); + $plaintext = substr($plaintext, strlen($ciphertext)); + } else { + $ciphertext = ''; + } + + $block_size = $this->block_size; + + $len = strlen($plaintext); + $key = $this->key; + $overflow = $len % $block_size; + + if (strlen($plaintext)) { + if ($overflow) { + $ciphertext.= openssl_encrypt(substr($plaintext, 0, -$overflow) . str_repeat("\0", $block_size), $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV); + $xor = $this->_string_pop($ciphertext, $block_size); + if ($this->continuousBuffer) { + $encryptIV = $xor; + } + $ciphertext.= $this->_string_shift($xor, $overflow) ^ substr($plaintext, -$overflow); + if ($this->continuousBuffer) { + $buffer['xor'] = $xor; + } + } else { + $ciphertext = openssl_encrypt($plaintext, $this->cipher_name_openssl, $key, $this->openssl_options, $encryptIV); + if ($this->continuousBuffer) { + $encryptIV = substr($ciphertext, -$block_size) ^ substr($plaintext, -$block_size); + } + } + } + + return $ciphertext; + } + + /** + * phpseclib <-> OpenSSL Mode Mapper + * + * May need to be overwritten by classes extending this one in some cases + * + * @return int + * @access private + */ + function _openssl_translate_mode() + { + switch ($this->mode) { + case CRYPT_MODE_ECB: + return 'ecb'; + case CRYPT_MODE_CBC: + return 'cbc'; + case CRYPT_MODE_CTR: + return 'ctr'; + case CRYPT_MODE_CFB: + return 'cfb'; + case CRYPT_MODE_OFB: + return 'ofb'; + } + } + + /** + * Pad "packets". + * + * Block ciphers working by encrypting between their specified [$this->]block_size at a time + * If you ever need to encrypt or decrypt something that isn't of the proper length, it becomes necessary to + * pad the input so that it is of the proper length. + * + * Padding is enabled by default. Sometimes, however, it is undesirable to pad strings. Such is the case in SSH, + * where "packets" are padded with random bytes before being encrypted. Unpad these packets and you risk stripping + * away characters that shouldn't be stripped away. (SSH knows how many bytes are added because the length is + * transmitted separately) + * + * @see self::disablePadding() + * @access public + */ + function enablePadding() + { + $this->padding = true; + } + + /** + * Do not pad packets. + * + * @see self::enablePadding() + * @access public + */ + function disablePadding() + { + $this->padding = false; + } + + /** + * Treat consecutive "packets" as if they are a continuous buffer. + * + * Say you have a 32-byte plaintext $plaintext. Using the default behavior, the two following code snippets + * will yield different outputs: + * + * + * echo $rijndael->encrypt(substr($plaintext, 0, 16)); + * echo $rijndael->encrypt(substr($plaintext, 16, 16)); + * + * + * echo $rijndael->encrypt($plaintext); + * + * + * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates + * another, as demonstrated with the following: + * + * + * $rijndael->encrypt(substr($plaintext, 0, 16)); + * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16))); + * + * + * echo $rijndael->decrypt($rijndael->encrypt(substr($plaintext, 16, 16))); + * + * + * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different + * outputs. The reason is due to the fact that the initialization vector's change after every encryption / + * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. + * + * Put another way, when the continuous buffer is enabled, the state of the Crypt_*() object changes after each + * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that + * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), + * however, they are also less intuitive and more likely to cause you problems. + * + * @see self::disableContinuousBuffer() + * @access public + * @internal Could, but not must, extend by the child Crypt_* class + */ + function enableContinuousBuffer() + { + if ($this->mode == CRYPT_MODE_ECB) { + return; + } + + $this->continuousBuffer = true; + + $this->_setEngine(); + } + + /** + * Treat consecutive packets as if they are a discontinuous buffer. + * + * The default behavior. + * + * @see self::enableContinuousBuffer() + * @access public + * @internal Could, but not must, extend by the child Crypt_* class + */ + function disableContinuousBuffer() + { + if ($this->mode == CRYPT_MODE_ECB) { + return; + } + if (!$this->continuousBuffer) { + return; + } + + $this->continuousBuffer = false; + $this->changed = true; + + $this->_setEngine(); + } + + /** + * Test for engine validity + * + * @see self::Crypt_Base() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + switch ($engine) { + case CRYPT_ENGINE_OPENSSL: + if ($this->mode == CRYPT_MODE_STREAM && $this->continuousBuffer) { + return false; + } + $this->openssl_emulate_ctr = false; + $result = $this->cipher_name_openssl && + extension_loaded('openssl') && + // PHP 5.3.0 - 5.3.2 did not let you set IV's + version_compare(PHP_VERSION, '5.3.3', '>='); + if (!$result) { + return false; + } + + // prior to PHP 5.4.0 OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING were not defined. instead of expecting an integer + // $options openssl_encrypt expected a boolean $raw_data. + if (!defined('OPENSSL_RAW_DATA')) { + $this->openssl_options = true; + } else { + $this->openssl_options = OPENSSL_RAW_DATA | OPENSSL_ZERO_PADDING; + } + + $methods = openssl_get_cipher_methods(); + if (in_array($this->cipher_name_openssl, $methods)) { + return true; + } + // not all of openssl's symmetric cipher's support ctr. for those + // that don't we'll emulate it + switch ($this->mode) { + case CRYPT_MODE_CTR: + if (in_array($this->cipher_name_openssl_ecb, $methods)) { + $this->openssl_emulate_ctr = true; + return true; + } + } + return false; + case CRYPT_ENGINE_MCRYPT: + return $this->cipher_name_mcrypt && + extension_loaded('mcrypt') && + in_array($this->cipher_name_mcrypt, @mcrypt_list_algorithms()); + case CRYPT_ENGINE_INTERNAL: + return true; + } + + return false; + } + + /** + * Sets the preferred crypt engine + * + * Currently, $engine could be: + * + * - CRYPT_ENGINE_OPENSSL [very fast] + * + * - CRYPT_ENGINE_MCRYPT [fast] + * + * - CRYPT_ENGINE_INTERNAL [slow] + * + * If the preferred crypt engine is not available the fastest available one will be used + * + * @see self::Crypt_Base() + * @param int $engine + * @access public + */ + function setPreferredEngine($engine) + { + switch ($engine) { + //case CRYPT_ENGINE_OPENSSL: + case CRYPT_ENGINE_MCRYPT: + case CRYPT_ENGINE_INTERNAL: + $this->preferredEngine = $engine; + break; + default: + $this->preferredEngine = CRYPT_ENGINE_OPENSSL; + } + + $this->_setEngine(); + } + + /** + * Returns the engine currently being utilized + * + * @see self::_setEngine() + * @access public + */ + function getEngine() + { + return $this->engine; + } + + /** + * Sets the engine as appropriate + * + * @see self::Crypt_Base() + * @access private + */ + function _setEngine() + { + $this->engine = null; + + $candidateEngines = array( + $this->preferredEngine, + CRYPT_ENGINE_OPENSSL, + CRYPT_ENGINE_MCRYPT + ); + foreach ($candidateEngines as $engine) { + if ($this->isValidEngine($engine)) { + $this->engine = $engine; + break; + } + } + if (!$this->engine) { + $this->engine = CRYPT_ENGINE_INTERNAL; + } + + if ($this->engine != CRYPT_ENGINE_MCRYPT && $this->enmcrypt) { + // Closing the current mcrypt resource(s). _mcryptSetup() will, if needed, + // (re)open them with the module named in $this->cipher_name_mcrypt + @mcrypt_module_close($this->enmcrypt); + @mcrypt_module_close($this->demcrypt); + $this->enmcrypt = null; + $this->demcrypt = null; + + if ($this->ecb) { + @mcrypt_module_close($this->ecb); + $this->ecb = null; + } + } + + $this->changed = true; + } + + /** + * Encrypts a block + * + * @access private + * @param string $in + * @return string + * @internal Must be extended by the child Crypt_* class + */ + function _encryptBlock($in) + { + user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR); + } + + /** + * Decrypts a block + * + * @access private + * @param string $in + * @return string + * @internal Must be extended by the child Crypt_* class + */ + function _decryptBlock($in) + { + user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR); + } + + /** + * Setup the key (expansion) + * + * Only used if $engine == CRYPT_ENGINE_INTERNAL + * + * @see self::_setup() + * @access private + * @internal Must be extended by the child Crypt_* class + */ + function _setupKey() + { + user_error((version_compare(PHP_VERSION, '5.0.0', '>=') ? __METHOD__ : __FUNCTION__) . '() must extend by class ' . get_class($this), E_USER_ERROR); + } + + /** + * Setup the CRYPT_ENGINE_INTERNAL $engine + * + * (re)init, if necessary, the internal cipher $engine and flush all $buffers + * Used (only) if $engine == CRYPT_ENGINE_INTERNAL + * + * _setup() will be called each time if $changed === true + * typically this happens when using one or more of following public methods: + * + * - setKey() + * + * - setIV() + * + * - disableContinuousBuffer() + * + * - First run of encrypt() / decrypt() with no init-settings + * + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() + * @access private + * @internal _setup() is always called before en/decryption. + * @internal Could, but not must, extend by the child Crypt_* class + */ + function _setup() + { + $this->_clearBuffers(); + $this->_setupKey(); + + if ($this->use_inline_crypt) { + $this->_setupInlineCrypt(); + } + } + + /** + * Setup the CRYPT_ENGINE_MCRYPT $engine + * + * (re)init, if necessary, the (ext)mcrypt resources and flush all $buffers + * Used (only) if $engine = CRYPT_ENGINE_MCRYPT + * + * _setupMcrypt() will be called each time if $changed === true + * typically this happens when using one or more of following public methods: + * + * - setKey() + * + * - setIV() + * + * - disableContinuousBuffer() + * + * - First run of encrypt() / decrypt() + * + * @see self::setKey() + * @see self::setIV() + * @see self::disableContinuousBuffer() + * @access private + * @internal Could, but not must, extend by the child Crypt_* class + */ + function _setupMcrypt() + { + $this->_clearBuffers(); + $this->enchanged = $this->dechanged = true; + + if (!isset($this->enmcrypt)) { + static $mcrypt_modes = array( + CRYPT_MODE_CTR => 'ctr', + CRYPT_MODE_ECB => MCRYPT_MODE_ECB, + CRYPT_MODE_CBC => MCRYPT_MODE_CBC, + CRYPT_MODE_CFB => 'ncfb', + CRYPT_MODE_OFB => MCRYPT_MODE_NOFB, + CRYPT_MODE_STREAM => MCRYPT_MODE_STREAM, + ); + + $this->demcrypt = @mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], ''); + $this->enmcrypt = @mcrypt_module_open($this->cipher_name_mcrypt, '', $mcrypt_modes[$this->mode], ''); + + // we need the $ecb mcrypt resource (only) in MODE_CFB with enableContinuousBuffer() + // to workaround mcrypt's broken ncfb implementation in buffered mode + // see: {@link http://phpseclib.sourceforge.net/cfb-demo.phps} + if ($this->mode == CRYPT_MODE_CFB) { + $this->ecb = @mcrypt_module_open($this->cipher_name_mcrypt, '', MCRYPT_MODE_ECB, ''); + } + } // else should mcrypt_generic_deinit be called? + + if ($this->mode == CRYPT_MODE_CFB) { + @mcrypt_generic_init($this->ecb, $this->key, str_repeat("\0", $this->block_size)); + } + } + + /** + * Pads a string + * + * Pads a string using the RSA PKCS padding standards so that its length is a multiple of the blocksize. + * $this->block_size - (strlen($text) % $this->block_size) bytes are added, each of which is equal to + * chr($this->block_size - (strlen($text) % $this->block_size) + * + * If padding is disabled and $text is not a multiple of the blocksize, the string will be padded regardless + * and padding will, hence forth, be enabled. + * + * @see self::_unpad() + * @param string $text + * @access private + * @return string + */ + function _pad($text) + { + $length = strlen($text); + + if (!$this->padding) { + if ($length % $this->block_size == 0) { + return $text; + } else { + user_error("The plaintext's length ($length) is not a multiple of the block size ({$this->block_size})"); + $this->padding = true; + } + } + + $pad = $this->block_size - ($length % $this->block_size); + + return str_pad($text, $length + $pad, chr($pad)); + } + + /** + * Unpads a string. + * + * If padding is enabled and the reported padding length is invalid the encryption key will be assumed to be wrong + * and false will be returned. + * + * @see self::_pad() + * @param string $text + * @access private + * @return string + */ + function _unpad($text) + { + if (!$this->padding) { + return $text; + } + + $length = ord($text[strlen($text) - 1]); + + if (!$length || $length > $this->block_size) { + return false; + } + + return substr($text, 0, -$length); + } + + /** + * Clears internal buffers + * + * Clearing/resetting the internal buffers is done everytime + * after disableContinuousBuffer() or on cipher $engine (re)init + * ie after setKey() or setIV() + * + * @access public + * @internal Could, but not must, extend by the child Crypt_* class + */ + function _clearBuffers() + { + $this->enbuffer = $this->debuffer = array('ciphertext' => '', 'xor' => '', 'pos' => 0, 'enmcrypt_init' => true); + + // mcrypt's handling of invalid's $iv: + // $this->encryptIV = $this->decryptIV = strlen($this->iv) == $this->block_size ? $this->iv : str_repeat("\0", $this->block_size); + $this->encryptIV = $this->decryptIV = str_pad(substr($this->iv, 0, $this->block_size), $this->block_size, "\0"); + + if (!$this->skip_key_adjustment) { + $this->key = str_pad(substr($this->key, 0, $this->key_length), $this->key_length, "\0"); + } + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @access private + * @return string + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * String Pop + * + * Inspired by array_pop + * + * @param string $string + * @param int $index + * @access private + * @return string + */ + function _string_pop(&$string, $index = 1) + { + $substr = substr($string, -$index); + $string = substr($string, 0, -$index); + return $substr; + } + + /** + * Increment the current string + * + * @see self::decrypt() + * @see self::encrypt() + * @param string $var + * @access private + */ + function _increment_str(&$var) + { + for ($i = 4; $i <= strlen($var); $i+= 4) { + $temp = substr($var, -$i, 4); + switch ($temp) { + case "\xFF\xFF\xFF\xFF": + $var = substr_replace($var, "\x00\x00\x00\x00", -$i, 4); + break; + case "\x7F\xFF\xFF\xFF": + $var = substr_replace($var, "\x80\x00\x00\x00", -$i, 4); + return; + default: + $temp = unpack('Nnum', $temp); + $var = substr_replace($var, pack('N', $temp['num'] + 1), -$i, 4); + return; + } + } + + $remainder = strlen($var) % 4; + + if ($remainder == 0) { + return; + } + + $temp = unpack('Nnum', str_pad(substr($var, 0, $remainder), 4, "\0", STR_PAD_LEFT)); + $temp = substr(pack('N', $temp['num'] + 1), -$remainder); + $var = substr_replace($var, $temp, 0, $remainder); + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * Stores the created (or existing) callback function-name + * in $this->inline_crypt + * + * Internally for phpseclib developers: + * + * _setupInlineCrypt() would be called only if: + * + * - $engine == CRYPT_ENGINE_INTERNAL and + * + * - $use_inline_crypt === true + * + * - each time on _setup(), after(!) _setupKey() + * + * + * This ensures that _setupInlineCrypt() has always a + * full ready2go initializated internal cipher $engine state + * where, for example, the keys allready expanded, + * keys/block_size calculated and such. + * + * It is, each time if called, the responsibility of _setupInlineCrypt(): + * + * - to set $this->inline_crypt to a valid and fully working callback function + * as a (faster) replacement for encrypt() / decrypt() + * + * - NOT to create unlimited callback functions (for memory reasons!) + * no matter how often _setupInlineCrypt() would be called. At some + * point of amount they must be generic re-useable. + * + * - the code of _setupInlineCrypt() it self, + * and the generated callback code, + * must be, in following order: + * - 100% safe + * - 100% compatible to encrypt()/decrypt() + * - using only php5+ features/lang-constructs/php-extensions if + * compatibility (down to php4) or fallback is provided + * - readable/maintainable/understandable/commented and... not-cryptic-styled-code :-) + * - >= 10% faster than encrypt()/decrypt() [which is, by the way, + * the reason for the existence of _setupInlineCrypt() :-)] + * - memory-nice + * - short (as good as possible) + * + * Note: - _setupInlineCrypt() is using _createInlineCryptFunction() to create the full callback function code. + * - In case of using inline crypting, _setupInlineCrypt() must extend by the child Crypt_* class. + * - The following variable names are reserved: + * - $_* (all variable names prefixed with an underscore) + * - $self (object reference to it self. Do not use $this, but $self instead) + * - $in (the content of $in has to en/decrypt by the generated code) + * - The callback function should not use the 'return' statement, but en/decrypt'ing the content of $in only + * + * + * @see self::_setup() + * @see self::_createInlineCryptFunction() + * @see self::encrypt() + * @see self::decrypt() + * @access private + * @internal If a Crypt_* class providing inline crypting it must extend _setupInlineCrypt() + */ + function _setupInlineCrypt() + { + // If, for any reason, an extending Crypt_Base() Crypt_* class + // not using inline crypting then it must be ensured that: $this->use_inline_crypt = false + // ie in the class var declaration of $use_inline_crypt in general for the Crypt_* class, + // in the constructor at object instance-time + // or, if it's runtime-specific, at runtime + + $this->use_inline_crypt = false; + } + + /** + * Creates the performance-optimized function for en/decrypt() + * + * Internally for phpseclib developers: + * + * _createInlineCryptFunction(): + * + * - merge the $cipher_code [setup'ed by _setupInlineCrypt()] + * with the current [$this->]mode of operation code + * + * - create the $inline function, which called by encrypt() / decrypt() + * as its replacement to speed up the en/decryption operations. + * + * - return the name of the created $inline callback function + * + * - used to speed up en/decryption + * + * + * + * The main reason why can speed up things [up to 50%] this way are: + * + * - using variables more effective then regular. + * (ie no use of expensive arrays but integers $k_0, $k_1 ... + * or even, for example, the pure $key[] values hardcoded) + * + * - avoiding 1000's of function calls of ie _encryptBlock() + * but inlining the crypt operations. + * in the mode of operation for() loop. + * + * - full loop unroll the (sometimes key-dependent) rounds + * avoiding this way ++$i counters and runtime-if's etc... + * + * The basic code architectur of the generated $inline en/decrypt() + * lambda function, in pseudo php, is: + * + * + * +----------------------------------------------------------------------------------------------+ + * | callback $inline = create_function: | + * | lambda_function_0001_crypt_ECB($action, $text) | + * | { | + * | INSERT PHP CODE OF: | + * | $cipher_code['init_crypt']; // general init code. | + * | // ie: $sbox'es declarations used for | + * | // encrypt and decrypt'ing. | + * | | + * | switch ($action) { | + * | case 'encrypt': | + * | INSERT PHP CODE OF: | + * | $cipher_code['init_encrypt']; // encrypt sepcific init code. | + * | ie: specified $key or $box | + * | declarations for encrypt'ing. | + * | | + * | foreach ($ciphertext) { | + * | $in = $block_size of $ciphertext; | + * | | + * | INSERT PHP CODE OF: | + * | $cipher_code['encrypt_block']; // encrypt's (string) $in, which is always: | + * | // strlen($in) == $this->block_size | + * | // here comes the cipher algorithm in action | + * | // for encryption. | + * | // $cipher_code['encrypt_block'] has to | + * | // encrypt the content of the $in variable | + * | | + * | $plaintext .= $in; | + * | } | + * | return $plaintext; | + * | | + * | case 'decrypt': | + * | INSERT PHP CODE OF: | + * | $cipher_code['init_decrypt']; // decrypt sepcific init code | + * | ie: specified $key or $box | + * | declarations for decrypt'ing. | + * | foreach ($plaintext) { | + * | $in = $block_size of $plaintext; | + * | | + * | INSERT PHP CODE OF: | + * | $cipher_code['decrypt_block']; // decrypt's (string) $in, which is always | + * | // strlen($in) == $this->block_size | + * | // here comes the cipher algorithm in action | + * | // for decryption. | + * | // $cipher_code['decrypt_block'] has to | + * | // decrypt the content of the $in variable | + * | $ciphertext .= $in; | + * | } | + * | return $ciphertext; | + * | } | + * | } | + * +----------------------------------------------------------------------------------------------+ + * + * + * See also the Crypt_*::_setupInlineCrypt()'s for + * productive inline $cipher_code's how they works. + * + * Structure of: + * + * $cipher_code = array( + * 'init_crypt' => (string) '', // optional + * 'init_encrypt' => (string) '', // optional + * 'init_decrypt' => (string) '', // optional + * 'encrypt_block' => (string) '', // required + * 'decrypt_block' => (string) '' // required + * ); + * + * + * @see self::_setupInlineCrypt() + * @see self::encrypt() + * @see self::decrypt() + * @param array $cipher_code + * @access private + * @return string (the name of the created callback function) + */ + function _createInlineCryptFunction($cipher_code) + { + $block_size = $this->block_size; + + // optional + $init_crypt = isset($cipher_code['init_crypt']) ? $cipher_code['init_crypt'] : ''; + $init_encrypt = isset($cipher_code['init_encrypt']) ? $cipher_code['init_encrypt'] : ''; + $init_decrypt = isset($cipher_code['init_decrypt']) ? $cipher_code['init_decrypt'] : ''; + // required + $encrypt_block = $cipher_code['encrypt_block']; + $decrypt_block = $cipher_code['decrypt_block']; + + // Generating mode of operation inline code, + // merged with the $cipher_code algorithm + // for encrypt- and decryption. + switch ($this->mode) { + case CRYPT_MODE_ECB: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + $_plaintext_len = strlen($_text); + + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $in = substr($_text, $_i, '.$block_size.'); + '.$encrypt_block.' + $_ciphertext.= $in; + } + + return $_ciphertext; + '; + + $decrypt = $init_decrypt . ' + $_plaintext = ""; + $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); + $_ciphertext_len = strlen($_text); + + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $in = substr($_text, $_i, '.$block_size.'); + '.$decrypt_block.' + $_plaintext.= $in; + } + + return $self->_unpad($_plaintext); + '; + break; + case CRYPT_MODE_CTR: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + $_plaintext_len = strlen($_text); + $_xor = $self->encryptIV; + $_buffer = &$self->enbuffer; + if (strlen($_buffer["ciphertext"])) { + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + if (strlen($_block) > strlen($_buffer["ciphertext"])) { + $in = $_xor; + '.$encrypt_block.' + $self->_increment_str($_xor); + $_buffer["ciphertext"].= $in; + } + $_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.'); + $_ciphertext.= $_block ^ $_key; + } + } else { + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + $in = $_xor; + '.$encrypt_block.' + $self->_increment_str($_xor); + $_key = $in; + $_ciphertext.= $_block ^ $_key; + } + } + if ($self->continuousBuffer) { + $self->encryptIV = $_xor; + if ($_start = $_plaintext_len % '.$block_size.') { + $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"]; + } + } + + return $_ciphertext; + '; + + $decrypt = $init_encrypt . ' + $_plaintext = ""; + $_ciphertext_len = strlen($_text); + $_xor = $self->decryptIV; + $_buffer = &$self->debuffer; + + if (strlen($_buffer["ciphertext"])) { + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + if (strlen($_block) > strlen($_buffer["ciphertext"])) { + $in = $_xor; + '.$encrypt_block.' + $self->_increment_str($_xor); + $_buffer["ciphertext"].= $in; + } + $_key = $self->_string_shift($_buffer["ciphertext"], '.$block_size.'); + $_plaintext.= $_block ^ $_key; + } + } else { + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + $in = $_xor; + '.$encrypt_block.' + $self->_increment_str($_xor); + $_key = $in; + $_plaintext.= $_block ^ $_key; + } + } + if ($self->continuousBuffer) { + $self->decryptIV = $_xor; + if ($_start = $_ciphertext_len % '.$block_size.') { + $_buffer["ciphertext"] = substr($_key, $_start) . $_buffer["ciphertext"]; + } + } + + return $_plaintext; + '; + break; + case CRYPT_MODE_CFB: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + $_buffer = &$self->enbuffer; + + if ($self->continuousBuffer) { + $_iv = &$self->encryptIV; + $_pos = &$_buffer["pos"]; + } else { + $_iv = $self->encryptIV; + $_pos = 0; + } + $_len = strlen($_text); + $_i = 0; + if ($_pos) { + $_orig_pos = $_pos; + $_max = '.$block_size.' - $_pos; + if ($_len >= $_max) { + $_i = $_max; + $_len-= $_max; + $_pos = 0; + } else { + $_i = $_len; + $_pos+= $_len; + $_len = 0; + } + $_ciphertext = substr($_iv, $_orig_pos) ^ $_text; + $_iv = substr_replace($_iv, $_ciphertext, $_orig_pos, $_i); + } + while ($_len >= '.$block_size.') { + $in = $_iv; + '.$encrypt_block.'; + $_iv = $in ^ substr($_text, $_i, '.$block_size.'); + $_ciphertext.= $_iv; + $_len-= '.$block_size.'; + $_i+= '.$block_size.'; + } + if ($_len) { + $in = $_iv; + '.$encrypt_block.' + $_iv = $in; + $_block = $_iv ^ substr($_text, $_i); + $_iv = substr_replace($_iv, $_block, 0, $_len); + $_ciphertext.= $_block; + $_pos = $_len; + } + return $_ciphertext; + '; + + $decrypt = $init_encrypt . ' + $_plaintext = ""; + $_buffer = &$self->debuffer; + + if ($self->continuousBuffer) { + $_iv = &$self->decryptIV; + $_pos = &$_buffer["pos"]; + } else { + $_iv = $self->decryptIV; + $_pos = 0; + } + $_len = strlen($_text); + $_i = 0; + if ($_pos) { + $_orig_pos = $_pos; + $_max = '.$block_size.' - $_pos; + if ($_len >= $_max) { + $_i = $_max; + $_len-= $_max; + $_pos = 0; + } else { + $_i = $_len; + $_pos+= $_len; + $_len = 0; + } + $_plaintext = substr($_iv, $_orig_pos) ^ $_text; + $_iv = substr_replace($_iv, substr($_text, 0, $_i), $_orig_pos, $_i); + } + while ($_len >= '.$block_size.') { + $in = $_iv; + '.$encrypt_block.' + $_iv = $in; + $cb = substr($_text, $_i, '.$block_size.'); + $_plaintext.= $_iv ^ $cb; + $_iv = $cb; + $_len-= '.$block_size.'; + $_i+= '.$block_size.'; + } + if ($_len) { + $in = $_iv; + '.$encrypt_block.' + $_iv = $in; + $_plaintext.= $_iv ^ substr($_text, $_i); + $_iv = substr_replace($_iv, substr($_text, $_i), 0, $_len); + $_pos = $_len; + } + + return $_plaintext; + '; + break; + case CRYPT_MODE_OFB: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + $_plaintext_len = strlen($_text); + $_xor = $self->encryptIV; + $_buffer = &$self->enbuffer; + + if (strlen($_buffer["xor"])) { + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + if (strlen($_block) > strlen($_buffer["xor"])) { + $in = $_xor; + '.$encrypt_block.' + $_xor = $in; + $_buffer["xor"].= $_xor; + } + $_key = $self->_string_shift($_buffer["xor"], '.$block_size.'); + $_ciphertext.= $_block ^ $_key; + } + } else { + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $in = $_xor; + '.$encrypt_block.' + $_xor = $in; + $_ciphertext.= substr($_text, $_i, '.$block_size.') ^ $_xor; + } + $_key = $_xor; + } + if ($self->continuousBuffer) { + $self->encryptIV = $_xor; + if ($_start = $_plaintext_len % '.$block_size.') { + $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; + } + } + return $_ciphertext; + '; + + $decrypt = $init_encrypt . ' + $_plaintext = ""; + $_ciphertext_len = strlen($_text); + $_xor = $self->decryptIV; + $_buffer = &$self->debuffer; + + if (strlen($_buffer["xor"])) { + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $_block = substr($_text, $_i, '.$block_size.'); + if (strlen($_block) > strlen($_buffer["xor"])) { + $in = $_xor; + '.$encrypt_block.' + $_xor = $in; + $_buffer["xor"].= $_xor; + } + $_key = $self->_string_shift($_buffer["xor"], '.$block_size.'); + $_plaintext.= $_block ^ $_key; + } + } else { + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $in = $_xor; + '.$encrypt_block.' + $_xor = $in; + $_plaintext.= substr($_text, $_i, '.$block_size.') ^ $_xor; + } + $_key = $_xor; + } + if ($self->continuousBuffer) { + $self->decryptIV = $_xor; + if ($_start = $_ciphertext_len % '.$block_size.') { + $_buffer["xor"] = substr($_key, $_start) . $_buffer["xor"]; + } + } + return $_plaintext; + '; + break; + case CRYPT_MODE_STREAM: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + '.$encrypt_block.' + return $_ciphertext; + '; + $decrypt = $init_decrypt . ' + $_plaintext = ""; + '.$decrypt_block.' + return $_plaintext; + '; + break; + // case CRYPT_MODE_CBC: + default: + $encrypt = $init_encrypt . ' + $_ciphertext = ""; + $_plaintext_len = strlen($_text); + + $in = $self->encryptIV; + + for ($_i = 0; $_i < $_plaintext_len; $_i+= '.$block_size.') { + $in = substr($_text, $_i, '.$block_size.') ^ $in; + '.$encrypt_block.' + $_ciphertext.= $in; + } + + if ($self->continuousBuffer) { + $self->encryptIV = $in; + } + + return $_ciphertext; + '; + + $decrypt = $init_decrypt . ' + $_plaintext = ""; + $_text = str_pad($_text, strlen($_text) + ('.$block_size.' - strlen($_text) % '.$block_size.') % '.$block_size.', chr(0)); + $_ciphertext_len = strlen($_text); + + $_iv = $self->decryptIV; + + for ($_i = 0; $_i < $_ciphertext_len; $_i+= '.$block_size.') { + $in = $_block = substr($_text, $_i, '.$block_size.'); + '.$decrypt_block.' + $_plaintext.= $in ^ $_iv; + $_iv = $_block; + } + + if ($self->continuousBuffer) { + $self->decryptIV = $_iv; + } + + return $self->_unpad($_plaintext); + '; + break; + } + + // Create the $inline function and return its name as string. Ready to run! + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + eval('$func = function ($_action, &$self, $_text) { ' . $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' } };'); + return $func; + } + + return create_function('$_action, &$self, $_text', $init_crypt . 'if ($_action == "encrypt") { ' . $encrypt . ' } else { ' . $decrypt . ' }'); + } + + /** + * Holds the lambda_functions table (classwide) + * + * Each name of the lambda function, created from + * _setupInlineCrypt() && _createInlineCryptFunction() + * is stored, classwide (!), here for reusing. + * + * The string-based index of $function is a classwide + * unique value representing, at least, the $mode of + * operation (or more... depends of the optimizing level) + * for which $mode the lambda function was created. + * + * @access private + * @return array &$functions + */ + function &_getLambdaFunctions() + { + static $functions = array(); + return $functions; + } + + /** + * Generates a digest from $bytes + * + * @see self::_setupInlineCrypt() + * @access private + * @param $bytes + * @return string + */ + function _hashInlineCryptFunction($bytes) + { + if (!defined('CRYPT_BASE_WHIRLPOOL_AVAILABLE')) { + define('CRYPT_BASE_WHIRLPOOL_AVAILABLE', (bool)(extension_loaded('hash') && in_array('whirlpool', hash_algos()))); + } + + $result = ''; + $hash = $bytes; + + switch (true) { + case CRYPT_BASE_WHIRLPOOL_AVAILABLE: + foreach (str_split($bytes, 64) as $t) { + $hash = hash('whirlpool', $hash, true); + $result .= $t ^ $hash; + } + return $result . hash('whirlpool', $hash, true); + default: + $len = strlen($bytes); + for ($i = 0; $i < $len; $i+=20) { + $t = substr($bytes, $i, 20); + $hash = pack('H*', sha1($hash)); + $result .= $t ^ $hash; + } + return $result . pack('H*', sha1($hash)); + } + } +} diff --git a/ipaylinks_statement/Crypt/Blowfish.php b/ipaylinks_statement/Crypt/Blowfish.php new file mode 100644 index 00000000..17c8e7e8 --- /dev/null +++ b/ipaylinks_statement/Crypt/Blowfish.php @@ -0,0 +1,674 @@ + + * setKey('12345678901234567890123456789012'); + * + * $plaintext = str_repeat('a', 1024); + * + * echo $blowfish->decrypt($blowfish->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_Blowfish + * @author Jim Wigginton + * @author Hans-Juergen Petrich + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_BLOWFISH_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_BLOWFISH_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_BLOWFISH_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_BLOWFISH_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_BLOWFISH_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of Blowfish. + * + * @package Crypt_Blowfish + * @author Jim Wigginton + * @author Hans-Juergen Petrich + * @access public + */ +class Crypt_Blowfish extends Crypt_Base +{ + /** + * Block Length of the cipher + * + * @see Crypt_Base::block_size + * @var int + * @access private + */ + var $block_size = 8; + + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'BLOWFISH'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'blowfish'; + + /** + * Optimizing value while CFB-encrypting + * + * @see Crypt_Base::cfb_init_len + * @var int + * @access private + */ + var $cfb_init_len = 500; + + /** + * The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each + * + * S-Box 0 + * + * @access private + * @var array + */ + var $sbox0 = array( + 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, + 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, + 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, + 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, + 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, + 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, + 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, + 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, + 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, + 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, + 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, + 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, + 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, + 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, + 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, + 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, + 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, + 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, + 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, + 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, + 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, + 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a + ); + + /** + * S-Box 1 + * + * @access private + * @var array + */ + var $sbox1 = array( + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, + 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, + 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, + 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, + 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, + 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, + 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, + 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, + 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, + 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, + 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, + 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, + 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, + 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, + 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, + 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, + 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, + 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, + 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, + 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, + 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, + 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 + ); + + /** + * S-Box 2 + * + * @access private + * @var array + */ + var $sbox2 = array( + 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, + 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, + 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, + 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, + 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, + 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, + 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, + 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, + 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, + 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, + 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, + 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, + 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, + 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, + 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, + 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, + 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, + 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, + 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, + 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, + 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 + ); + + /** + * S-Box 3 + * + * @access private + * @var array + */ + var $sbox3 = array( + 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, + 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, + 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, + 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, + 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, + 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, + 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, + 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, + 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, + 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, + 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, + 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, + 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, + 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, + 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, + 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, + 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, + 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, + 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, + 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, + 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, + 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 + ); + + /** + * P-Array consists of 18 32-bit subkeys + * + * @var array + * @access private + */ + var $parray = array( + 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, + 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, + 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b + ); + + /** + * The BCTX-working Array + * + * Holds the expanded key [p] and the key-depended s-boxes [sb] + * + * @var array + * @access private + */ + var $bctx; + + /** + * Holds the last used key + * + * @var array + * @access private + */ + var $kl; + + /** + * The Key Length (in bytes) + * + * @see Crypt_Base::setKeyLength() + * @var int + * @access private + * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk + * because the encryption / decryption / key schedule creation requires this number and not $key_length. We could + * derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu + * of that, we'll just precompute it once. + */ + var $key_length = 16; + + /** + * Sets the key length. + * + * Key lengths can be between 32 and 448 bits. + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + if ($length < 32) { + $this->key_length = 7; + } elseif ($length > 448) { + $this->key_length = 56; + } else { + $this->key_length = $length >> 3; + } + + parent::setKeyLength($length); + } + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::isValidEngine() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + if ($engine == CRYPT_ENGINE_OPENSSL) { + if (version_compare(PHP_VERSION, '5.3.7') < 0 && $this->key_length != 16) { + return false; + } + if ($this->key_length < 16) { + return false; + } + $this->cipher_name_openssl_ecb = 'bf-ecb'; + $this->cipher_name_openssl = 'bf-' . $this->_openssl_translate_mode(); + } + + return parent::isValidEngine($engine); + } + + /** + * Setup the key (expansion) + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + if (isset($this->kl['key']) && $this->key === $this->kl['key']) { + // already expanded + return; + } + $this->kl = array('key' => $this->key); + + /* key-expanding p[] and S-Box building sb[] */ + $this->bctx = array( + 'p' => array(), + 'sb' => array( + $this->sbox0, + $this->sbox1, + $this->sbox2, + $this->sbox3 + ) + ); + + // unpack binary string in unsigned chars + $key = array_values(unpack('C*', $this->key)); + $keyl = count($key); + for ($j = 0, $i = 0; $i < 18; ++$i) { + // xor P1 with the first 32-bits of the key, xor P2 with the second 32-bits ... + for ($data = 0, $k = 0; $k < 4; ++$k) { + $data = ($data << 8) | $key[$j]; + if (++$j >= $keyl) { + $j = 0; + } + } + $this->bctx['p'][] = $this->parray[$i] ^ $data; + } + + // encrypt the zero-string, replace P1 and P2 with the encrypted data, + // encrypt P3 and P4 with the new P1 and P2, do it with all P-array and subkeys + $data = "\0\0\0\0\0\0\0\0"; + for ($i = 0; $i < 18; $i += 2) { + list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data))); + $this->bctx['p'][$i ] = $l; + $this->bctx['p'][$i + 1] = $r; + } + for ($i = 0; $i < 4; ++$i) { + for ($j = 0; $j < 256; $j += 2) { + list($l, $r) = array_values(unpack('N*', $data = $this->_encryptBlock($data))); + $this->bctx['sb'][$i][$j ] = $l; + $this->bctx['sb'][$i][$j + 1] = $r; + } + } + } + + /** + * Encrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _encryptBlock($in) + { + $p = $this->bctx["p"]; + // extract($this->bctx["sb"], EXTR_PREFIX_ALL, "sb"); // slower + $sb_0 = $this->bctx["sb"][0]; + $sb_1 = $this->bctx["sb"][1]; + $sb_2 = $this->bctx["sb"][2]; + $sb_3 = $this->bctx["sb"][3]; + + $in = unpack("N*", $in); + $l = $in[1]; + $r = $in[2]; + + for ($i = 0; $i < 16; $i+= 2) { + $l^= $p[$i]; + $r^= $this->safe_intval(($this->safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^ + $sb_2[$l >> 8 & 0xff]) + + $sb_3[$l & 0xff]); + + $r^= $p[$i + 1]; + $l^= $this->safe_intval(($this->safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^ + $sb_2[$r >> 8 & 0xff]) + + $sb_3[$r & 0xff]); + } + return pack("N*", $r ^ $p[17], $l ^ $p[16]); + } + + /** + * Decrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _decryptBlock($in) + { + $p = $this->bctx["p"]; + $sb_0 = $this->bctx["sb"][0]; + $sb_1 = $this->bctx["sb"][1]; + $sb_2 = $this->bctx["sb"][2]; + $sb_3 = $this->bctx["sb"][3]; + + $in = unpack("N*", $in); + $l = $in[1]; + $r = $in[2]; + + for ($i = 17; $i > 2; $i-= 2) { + $l^= $p[$i]; + $r^= $this->safe_intval(($this->safe_intval($sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]) ^ + $sb_2[$l >> 8 & 0xff]) + + $sb_3[$l & 0xff]); + + $r^= $p[$i - 1]; + $l^= $this->safe_intval(($this->safe_intval($sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]) ^ + $sb_2[$r >> 8 & 0xff]) + + $sb_3[$r & 0xff]); + } + return pack("N*", $r ^ $p[0], $l ^ $p[1]); + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * @see Crypt_Base::_setupInlineCrypt() + * @access private + */ + function _setupInlineCrypt() + { + $lambda_functions =& Crypt_Blowfish::_getLambdaFunctions(); + + // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. + // (Currently, for Crypt_Blowfish, one generated $lambda_function cost on php5.5@32bit ~100kb unfreeable mem and ~180kb on php5.5@64bit) + // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); + + // Generation of a unique hash for our generated code + $code_hash = "Crypt_Blowfish, {$this->mode}"; + if ($gen_hi_opt_code) { + $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); + } + + // on 32-bit linux systems with PHP < 5.3 float to integer conversion is bad + switch (true) { + case defined('PHP_INT_SIZE') && PHP_INT_SIZE == 8: + case version_compare(PHP_VERSION, '5.3.0') >= 0: + case (PHP_OS & "\xDF\xDF\xDF") === 'WIN': + $safeint = '%s'; + break; + default: + $safeint = '(is_int($temp = %s) ? $temp : (fmod($temp, 0x80000000) & 0x7FFFFFFF) | '; + $safeint.= '((fmod(floor($temp / 0x80000000), 2) & 1) << 31))'; + } + + if (!isset($lambda_functions[$code_hash])) { + switch (true) { + case $gen_hi_opt_code: + $p = $this->bctx['p']; + $init_crypt = ' + static $sb_0, $sb_1, $sb_2, $sb_3; + if (!$sb_0) { + $sb_0 = $self->bctx["sb"][0]; + $sb_1 = $self->bctx["sb"][1]; + $sb_2 = $self->bctx["sb"][2]; + $sb_3 = $self->bctx["sb"][3]; + } + '; + break; + default: + $p = array(); + for ($i = 0; $i < 18; ++$i) { + $p[] = '$p_' . $i; + } + $init_crypt = ' + list($sb_0, $sb_1, $sb_2, $sb_3) = $self->bctx["sb"]; + list(' . implode(',', $p) . ') = $self->bctx["p"]; + + '; + } + + // Generating encrypt code: + $encrypt_block = ' + $in = unpack("N*", $in); + $l = $in[1]; + $r = $in[2]; + '; + for ($i = 0; $i < 16; $i+= 2) { + $encrypt_block.= ' + $l^= ' . $p[$i] . '; + $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^ + $sb_2[$l >> 8 & 0xff]) + + $sb_3[$l & 0xff]') . '; + + $r^= ' . $p[$i + 1] . '; + $l^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]') . ' ^ + $sb_2[$r >> 8 & 0xff]) + + $sb_3[$r & 0xff]') . '; + '; + } + $encrypt_block.= ' + $in = pack("N*", + $r ^ ' . $p[17] . ', + $l ^ ' . $p[16] . ' + ); + '; + + // Generating decrypt code: + $decrypt_block = ' + $in = unpack("N*", $in); + $l = $in[1]; + $r = $in[2]; + '; + + for ($i = 17; $i > 2; $i-= 2) { + $decrypt_block.= ' + $l^= ' . $p[$i] . '; + $r^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$l >> 24 & 0xff] + $sb_1[$l >> 16 & 0xff]') . ' ^ + $sb_2[$l >> 8 & 0xff]) + + $sb_3[$l & 0xff]') . '; + + $r^= ' . $p[$i - 1] . '; + $l^= ' . sprintf($safeint, '(' . sprintf($safeint, '$sb_0[$r >> 24 & 0xff] + $sb_1[$r >> 16 & 0xff]') . ' ^ + $sb_2[$r >> 8 & 0xff]) + + $sb_3[$r & 0xff]') . '; + '; + } + + $decrypt_block.= ' + $in = pack("N*", + $r ^ ' . $p[0] . ', + $l ^ ' . $p[1] . ' + ); + '; + + $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( + array( + 'init_crypt' => $init_crypt, + 'init_encrypt' => '', + 'init_decrypt' => '', + 'encrypt_block' => $encrypt_block, + 'decrypt_block' => $decrypt_block + ) + ); + } + $this->inline_crypt = $lambda_functions[$code_hash]; + } + + /** + * Convert float to int + * + * On 32-bit Linux installs running PHP < 5.3 converting floats to ints doesn't always work + * + * @access private + * @param string $x + * @return int + */ + function safe_intval($x) + { + // PHP 5.3, per http://php.net/releases/5_3_0.php, introduced "more consistent float rounding" + // PHP_OS & "\xDF\xDF\xDF" == strtoupper(substr(PHP_OS, 0, 3)), but a lot faster + if (is_int($x) || version_compare(PHP_VERSION, '5.3.0') >= 0 || (PHP_OS & "\xDF\xDF\xDF") === 'WIN') { + return $x; + } + return (fmod($x, 0x80000000) & 0x7FFFFFFF) | + ((fmod(floor($x / 0x80000000), 2) & 1) << 31); + } +} diff --git a/ipaylinks_statement/Crypt/DES.php b/ipaylinks_statement/Crypt/DES.php new file mode 100644 index 00000000..4c574018 --- /dev/null +++ b/ipaylinks_statement/Crypt/DES.php @@ -0,0 +1,1516 @@ + + * setKey('abcdefgh'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $des->decrypt($des->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_DES + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access private + * @see self::_setupKey() + * @see self::_processBlock() + */ +/** + * Contains $keys[CRYPT_DES_ENCRYPT] + */ +define('CRYPT_DES_ENCRYPT', 0); +/** + * Contains $keys[CRYPT_DES_DECRYPT] + */ +define('CRYPT_DES_DECRYPT', 1); +/**#@-*/ + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_DES_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_DES_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_DES_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_DES_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_DES_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of DES. + * + * @package Crypt_DES + * @author Jim Wigginton + * @access public + */ +class Crypt_DES extends Crypt_Base +{ + /** + * Block Length of the cipher + * + * @see Crypt_Base::block_size + * @var int + * @access private + */ + var $block_size = 8; + + /** + * Key Length (in bytes) + * + * @see Crypt_Base::setKeyLength() + * @var int + * @access private + */ + var $key_length = 8; + + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'DES'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'des'; + + /** + * The OpenSSL names of the cipher / modes + * + * @see Crypt_Base::openssl_mode_names + * @var array + * @access private + */ + var $openssl_mode_names = array( + CRYPT_MODE_ECB => 'des-ecb', + CRYPT_MODE_CBC => 'des-cbc', + CRYPT_MODE_CFB => 'des-cfb', + CRYPT_MODE_OFB => 'des-ofb' + // CRYPT_MODE_CTR is undefined for DES + ); + + /** + * Optimizing value while CFB-encrypting + * + * @see Crypt_Base::cfb_init_len + * @var int + * @access private + */ + var $cfb_init_len = 500; + + /** + * Switch for DES/3DES encryption + * + * Used only if $engine == CRYPT_DES_MODE_INTERNAL + * + * @see self::_setupKey() + * @see self::_processBlock() + * @var int + * @access private + */ + var $des_rounds = 1; + + /** + * max possible size of $key + * + * @see self::setKey() + * @var string + * @access private + */ + var $key_length_max = 8; + + /** + * The Key Schedule + * + * @see self::_setupKey() + * @var array + * @access private + */ + var $keys; + + /** + * Shuffle table. + * + * For each byte value index, the entry holds an 8-byte string + * with each byte containing all bits in the same state as the + * corresponding bit in the index value. + * + * @see self::_processBlock() + * @see self::_setupKey() + * @var array + * @access private + */ + var $shuffle = array( + "\x00\x00\x00\x00\x00\x00\x00\x00", "\x00\x00\x00\x00\x00\x00\x00\xFF", + "\x00\x00\x00\x00\x00\x00\xFF\x00", "\x00\x00\x00\x00\x00\x00\xFF\xFF", + "\x00\x00\x00\x00\x00\xFF\x00\x00", "\x00\x00\x00\x00\x00\xFF\x00\xFF", + "\x00\x00\x00\x00\x00\xFF\xFF\x00", "\x00\x00\x00\x00\x00\xFF\xFF\xFF", + "\x00\x00\x00\x00\xFF\x00\x00\x00", "\x00\x00\x00\x00\xFF\x00\x00\xFF", + "\x00\x00\x00\x00\xFF\x00\xFF\x00", "\x00\x00\x00\x00\xFF\x00\xFF\xFF", + "\x00\x00\x00\x00\xFF\xFF\x00\x00", "\x00\x00\x00\x00\xFF\xFF\x00\xFF", + "\x00\x00\x00\x00\xFF\xFF\xFF\x00", "\x00\x00\x00\x00\xFF\xFF\xFF\xFF", + "\x00\x00\x00\xFF\x00\x00\x00\x00", "\x00\x00\x00\xFF\x00\x00\x00\xFF", + "\x00\x00\x00\xFF\x00\x00\xFF\x00", "\x00\x00\x00\xFF\x00\x00\xFF\xFF", + "\x00\x00\x00\xFF\x00\xFF\x00\x00", "\x00\x00\x00\xFF\x00\xFF\x00\xFF", + "\x00\x00\x00\xFF\x00\xFF\xFF\x00", "\x00\x00\x00\xFF\x00\xFF\xFF\xFF", + "\x00\x00\x00\xFF\xFF\x00\x00\x00", "\x00\x00\x00\xFF\xFF\x00\x00\xFF", + "\x00\x00\x00\xFF\xFF\x00\xFF\x00", "\x00\x00\x00\xFF\xFF\x00\xFF\xFF", + "\x00\x00\x00\xFF\xFF\xFF\x00\x00", "\x00\x00\x00\xFF\xFF\xFF\x00\xFF", + "\x00\x00\x00\xFF\xFF\xFF\xFF\x00", "\x00\x00\x00\xFF\xFF\xFF\xFF\xFF", + "\x00\x00\xFF\x00\x00\x00\x00\x00", "\x00\x00\xFF\x00\x00\x00\x00\xFF", + "\x00\x00\xFF\x00\x00\x00\xFF\x00", "\x00\x00\xFF\x00\x00\x00\xFF\xFF", + "\x00\x00\xFF\x00\x00\xFF\x00\x00", "\x00\x00\xFF\x00\x00\xFF\x00\xFF", + "\x00\x00\xFF\x00\x00\xFF\xFF\x00", "\x00\x00\xFF\x00\x00\xFF\xFF\xFF", + "\x00\x00\xFF\x00\xFF\x00\x00\x00", "\x00\x00\xFF\x00\xFF\x00\x00\xFF", + "\x00\x00\xFF\x00\xFF\x00\xFF\x00", "\x00\x00\xFF\x00\xFF\x00\xFF\xFF", + "\x00\x00\xFF\x00\xFF\xFF\x00\x00", "\x00\x00\xFF\x00\xFF\xFF\x00\xFF", + "\x00\x00\xFF\x00\xFF\xFF\xFF\x00", "\x00\x00\xFF\x00\xFF\xFF\xFF\xFF", + "\x00\x00\xFF\xFF\x00\x00\x00\x00", "\x00\x00\xFF\xFF\x00\x00\x00\xFF", + "\x00\x00\xFF\xFF\x00\x00\xFF\x00", "\x00\x00\xFF\xFF\x00\x00\xFF\xFF", + "\x00\x00\xFF\xFF\x00\xFF\x00\x00", "\x00\x00\xFF\xFF\x00\xFF\x00\xFF", + "\x00\x00\xFF\xFF\x00\xFF\xFF\x00", "\x00\x00\xFF\xFF\x00\xFF\xFF\xFF", + "\x00\x00\xFF\xFF\xFF\x00\x00\x00", "\x00\x00\xFF\xFF\xFF\x00\x00\xFF", + "\x00\x00\xFF\xFF\xFF\x00\xFF\x00", "\x00\x00\xFF\xFF\xFF\x00\xFF\xFF", + "\x00\x00\xFF\xFF\xFF\xFF\x00\x00", "\x00\x00\xFF\xFF\xFF\xFF\x00\xFF", + "\x00\x00\xFF\xFF\xFF\xFF\xFF\x00", "\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF", + "\x00\xFF\x00\x00\x00\x00\x00\x00", "\x00\xFF\x00\x00\x00\x00\x00\xFF", + "\x00\xFF\x00\x00\x00\x00\xFF\x00", "\x00\xFF\x00\x00\x00\x00\xFF\xFF", + "\x00\xFF\x00\x00\x00\xFF\x00\x00", "\x00\xFF\x00\x00\x00\xFF\x00\xFF", + "\x00\xFF\x00\x00\x00\xFF\xFF\x00", "\x00\xFF\x00\x00\x00\xFF\xFF\xFF", + "\x00\xFF\x00\x00\xFF\x00\x00\x00", "\x00\xFF\x00\x00\xFF\x00\x00\xFF", + "\x00\xFF\x00\x00\xFF\x00\xFF\x00", "\x00\xFF\x00\x00\xFF\x00\xFF\xFF", + "\x00\xFF\x00\x00\xFF\xFF\x00\x00", "\x00\xFF\x00\x00\xFF\xFF\x00\xFF", + "\x00\xFF\x00\x00\xFF\xFF\xFF\x00", "\x00\xFF\x00\x00\xFF\xFF\xFF\xFF", + "\x00\xFF\x00\xFF\x00\x00\x00\x00", "\x00\xFF\x00\xFF\x00\x00\x00\xFF", + "\x00\xFF\x00\xFF\x00\x00\xFF\x00", "\x00\xFF\x00\xFF\x00\x00\xFF\xFF", + "\x00\xFF\x00\xFF\x00\xFF\x00\x00", "\x00\xFF\x00\xFF\x00\xFF\x00\xFF", + "\x00\xFF\x00\xFF\x00\xFF\xFF\x00", "\x00\xFF\x00\xFF\x00\xFF\xFF\xFF", + "\x00\xFF\x00\xFF\xFF\x00\x00\x00", "\x00\xFF\x00\xFF\xFF\x00\x00\xFF", + "\x00\xFF\x00\xFF\xFF\x00\xFF\x00", "\x00\xFF\x00\xFF\xFF\x00\xFF\xFF", + "\x00\xFF\x00\xFF\xFF\xFF\x00\x00", "\x00\xFF\x00\xFF\xFF\xFF\x00\xFF", + "\x00\xFF\x00\xFF\xFF\xFF\xFF\x00", "\x00\xFF\x00\xFF\xFF\xFF\xFF\xFF", + "\x00\xFF\xFF\x00\x00\x00\x00\x00", "\x00\xFF\xFF\x00\x00\x00\x00\xFF", + "\x00\xFF\xFF\x00\x00\x00\xFF\x00", "\x00\xFF\xFF\x00\x00\x00\xFF\xFF", + "\x00\xFF\xFF\x00\x00\xFF\x00\x00", "\x00\xFF\xFF\x00\x00\xFF\x00\xFF", + "\x00\xFF\xFF\x00\x00\xFF\xFF\x00", "\x00\xFF\xFF\x00\x00\xFF\xFF\xFF", + "\x00\xFF\xFF\x00\xFF\x00\x00\x00", "\x00\xFF\xFF\x00\xFF\x00\x00\xFF", + "\x00\xFF\xFF\x00\xFF\x00\xFF\x00", "\x00\xFF\xFF\x00\xFF\x00\xFF\xFF", + "\x00\xFF\xFF\x00\xFF\xFF\x00\x00", "\x00\xFF\xFF\x00\xFF\xFF\x00\xFF", + "\x00\xFF\xFF\x00\xFF\xFF\xFF\x00", "\x00\xFF\xFF\x00\xFF\xFF\xFF\xFF", + "\x00\xFF\xFF\xFF\x00\x00\x00\x00", "\x00\xFF\xFF\xFF\x00\x00\x00\xFF", + "\x00\xFF\xFF\xFF\x00\x00\xFF\x00", "\x00\xFF\xFF\xFF\x00\x00\xFF\xFF", + "\x00\xFF\xFF\xFF\x00\xFF\x00\x00", "\x00\xFF\xFF\xFF\x00\xFF\x00\xFF", + "\x00\xFF\xFF\xFF\x00\xFF\xFF\x00", "\x00\xFF\xFF\xFF\x00\xFF\xFF\xFF", + "\x00\xFF\xFF\xFF\xFF\x00\x00\x00", "\x00\xFF\xFF\xFF\xFF\x00\x00\xFF", + "\x00\xFF\xFF\xFF\xFF\x00\xFF\x00", "\x00\xFF\xFF\xFF\xFF\x00\xFF\xFF", + "\x00\xFF\xFF\xFF\xFF\xFF\x00\x00", "\x00\xFF\xFF\xFF\xFF\xFF\x00\xFF", + "\x00\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF", + "\xFF\x00\x00\x00\x00\x00\x00\x00", "\xFF\x00\x00\x00\x00\x00\x00\xFF", + "\xFF\x00\x00\x00\x00\x00\xFF\x00", "\xFF\x00\x00\x00\x00\x00\xFF\xFF", + "\xFF\x00\x00\x00\x00\xFF\x00\x00", "\xFF\x00\x00\x00\x00\xFF\x00\xFF", + "\xFF\x00\x00\x00\x00\xFF\xFF\x00", "\xFF\x00\x00\x00\x00\xFF\xFF\xFF", + "\xFF\x00\x00\x00\xFF\x00\x00\x00", "\xFF\x00\x00\x00\xFF\x00\x00\xFF", + "\xFF\x00\x00\x00\xFF\x00\xFF\x00", "\xFF\x00\x00\x00\xFF\x00\xFF\xFF", + "\xFF\x00\x00\x00\xFF\xFF\x00\x00", "\xFF\x00\x00\x00\xFF\xFF\x00\xFF", + "\xFF\x00\x00\x00\xFF\xFF\xFF\x00", "\xFF\x00\x00\x00\xFF\xFF\xFF\xFF", + "\xFF\x00\x00\xFF\x00\x00\x00\x00", "\xFF\x00\x00\xFF\x00\x00\x00\xFF", + "\xFF\x00\x00\xFF\x00\x00\xFF\x00", "\xFF\x00\x00\xFF\x00\x00\xFF\xFF", + "\xFF\x00\x00\xFF\x00\xFF\x00\x00", "\xFF\x00\x00\xFF\x00\xFF\x00\xFF", + "\xFF\x00\x00\xFF\x00\xFF\xFF\x00", "\xFF\x00\x00\xFF\x00\xFF\xFF\xFF", + "\xFF\x00\x00\xFF\xFF\x00\x00\x00", "\xFF\x00\x00\xFF\xFF\x00\x00\xFF", + "\xFF\x00\x00\xFF\xFF\x00\xFF\x00", "\xFF\x00\x00\xFF\xFF\x00\xFF\xFF", + "\xFF\x00\x00\xFF\xFF\xFF\x00\x00", "\xFF\x00\x00\xFF\xFF\xFF\x00\xFF", + "\xFF\x00\x00\xFF\xFF\xFF\xFF\x00", "\xFF\x00\x00\xFF\xFF\xFF\xFF\xFF", + "\xFF\x00\xFF\x00\x00\x00\x00\x00", "\xFF\x00\xFF\x00\x00\x00\x00\xFF", + "\xFF\x00\xFF\x00\x00\x00\xFF\x00", "\xFF\x00\xFF\x00\x00\x00\xFF\xFF", + "\xFF\x00\xFF\x00\x00\xFF\x00\x00", "\xFF\x00\xFF\x00\x00\xFF\x00\xFF", + "\xFF\x00\xFF\x00\x00\xFF\xFF\x00", "\xFF\x00\xFF\x00\x00\xFF\xFF\xFF", + "\xFF\x00\xFF\x00\xFF\x00\x00\x00", "\xFF\x00\xFF\x00\xFF\x00\x00\xFF", + "\xFF\x00\xFF\x00\xFF\x00\xFF\x00", "\xFF\x00\xFF\x00\xFF\x00\xFF\xFF", + "\xFF\x00\xFF\x00\xFF\xFF\x00\x00", "\xFF\x00\xFF\x00\xFF\xFF\x00\xFF", + "\xFF\x00\xFF\x00\xFF\xFF\xFF\x00", "\xFF\x00\xFF\x00\xFF\xFF\xFF\xFF", + "\xFF\x00\xFF\xFF\x00\x00\x00\x00", "\xFF\x00\xFF\xFF\x00\x00\x00\xFF", + "\xFF\x00\xFF\xFF\x00\x00\xFF\x00", "\xFF\x00\xFF\xFF\x00\x00\xFF\xFF", + "\xFF\x00\xFF\xFF\x00\xFF\x00\x00", "\xFF\x00\xFF\xFF\x00\xFF\x00\xFF", + "\xFF\x00\xFF\xFF\x00\xFF\xFF\x00", "\xFF\x00\xFF\xFF\x00\xFF\xFF\xFF", + "\xFF\x00\xFF\xFF\xFF\x00\x00\x00", "\xFF\x00\xFF\xFF\xFF\x00\x00\xFF", + "\xFF\x00\xFF\xFF\xFF\x00\xFF\x00", "\xFF\x00\xFF\xFF\xFF\x00\xFF\xFF", + "\xFF\x00\xFF\xFF\xFF\xFF\x00\x00", "\xFF\x00\xFF\xFF\xFF\xFF\x00\xFF", + "\xFF\x00\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\x00\xFF\xFF\xFF\xFF\xFF\xFF", + "\xFF\xFF\x00\x00\x00\x00\x00\x00", "\xFF\xFF\x00\x00\x00\x00\x00\xFF", + "\xFF\xFF\x00\x00\x00\x00\xFF\x00", "\xFF\xFF\x00\x00\x00\x00\xFF\xFF", + "\xFF\xFF\x00\x00\x00\xFF\x00\x00", "\xFF\xFF\x00\x00\x00\xFF\x00\xFF", + "\xFF\xFF\x00\x00\x00\xFF\xFF\x00", "\xFF\xFF\x00\x00\x00\xFF\xFF\xFF", + "\xFF\xFF\x00\x00\xFF\x00\x00\x00", "\xFF\xFF\x00\x00\xFF\x00\x00\xFF", + "\xFF\xFF\x00\x00\xFF\x00\xFF\x00", "\xFF\xFF\x00\x00\xFF\x00\xFF\xFF", + "\xFF\xFF\x00\x00\xFF\xFF\x00\x00", "\xFF\xFF\x00\x00\xFF\xFF\x00\xFF", + "\xFF\xFF\x00\x00\xFF\xFF\xFF\x00", "\xFF\xFF\x00\x00\xFF\xFF\xFF\xFF", + "\xFF\xFF\x00\xFF\x00\x00\x00\x00", "\xFF\xFF\x00\xFF\x00\x00\x00\xFF", + "\xFF\xFF\x00\xFF\x00\x00\xFF\x00", "\xFF\xFF\x00\xFF\x00\x00\xFF\xFF", + "\xFF\xFF\x00\xFF\x00\xFF\x00\x00", "\xFF\xFF\x00\xFF\x00\xFF\x00\xFF", + "\xFF\xFF\x00\xFF\x00\xFF\xFF\x00", "\xFF\xFF\x00\xFF\x00\xFF\xFF\xFF", + "\xFF\xFF\x00\xFF\xFF\x00\x00\x00", "\xFF\xFF\x00\xFF\xFF\x00\x00\xFF", + "\xFF\xFF\x00\xFF\xFF\x00\xFF\x00", "\xFF\xFF\x00\xFF\xFF\x00\xFF\xFF", + "\xFF\xFF\x00\xFF\xFF\xFF\x00\x00", "\xFF\xFF\x00\xFF\xFF\xFF\x00\xFF", + "\xFF\xFF\x00\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\x00\xFF\xFF\xFF\xFF\xFF", + "\xFF\xFF\xFF\x00\x00\x00\x00\x00", "\xFF\xFF\xFF\x00\x00\x00\x00\xFF", + "\xFF\xFF\xFF\x00\x00\x00\xFF\x00", "\xFF\xFF\xFF\x00\x00\x00\xFF\xFF", + "\xFF\xFF\xFF\x00\x00\xFF\x00\x00", "\xFF\xFF\xFF\x00\x00\xFF\x00\xFF", + "\xFF\xFF\xFF\x00\x00\xFF\xFF\x00", "\xFF\xFF\xFF\x00\x00\xFF\xFF\xFF", + "\xFF\xFF\xFF\x00\xFF\x00\x00\x00", "\xFF\xFF\xFF\x00\xFF\x00\x00\xFF", + "\xFF\xFF\xFF\x00\xFF\x00\xFF\x00", "\xFF\xFF\xFF\x00\xFF\x00\xFF\xFF", + "\xFF\xFF\xFF\x00\xFF\xFF\x00\x00", "\xFF\xFF\xFF\x00\xFF\xFF\x00\xFF", + "\xFF\xFF\xFF\x00\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\x00\xFF\xFF\xFF\xFF", + "\xFF\xFF\xFF\xFF\x00\x00\x00\x00", "\xFF\xFF\xFF\xFF\x00\x00\x00\xFF", + "\xFF\xFF\xFF\xFF\x00\x00\xFF\x00", "\xFF\xFF\xFF\xFF\x00\x00\xFF\xFF", + "\xFF\xFF\xFF\xFF\x00\xFF\x00\x00", "\xFF\xFF\xFF\xFF\x00\xFF\x00\xFF", + "\xFF\xFF\xFF\xFF\x00\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\x00\xFF\xFF\xFF", + "\xFF\xFF\xFF\xFF\xFF\x00\x00\x00", "\xFF\xFF\xFF\xFF\xFF\x00\x00\xFF", + "\xFF\xFF\xFF\xFF\xFF\x00\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\x00\xFF\xFF", + "\xFF\xFF\xFF\xFF\xFF\xFF\x00\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\x00\xFF", + "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00", "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" + ); + + /** + * IP mapping helper table. + * + * Indexing this table with each source byte performs the initial bit permutation. + * + * @var array + * @access private + */ + var $ipmap = array( + 0x00, 0x10, 0x01, 0x11, 0x20, 0x30, 0x21, 0x31, + 0x02, 0x12, 0x03, 0x13, 0x22, 0x32, 0x23, 0x33, + 0x40, 0x50, 0x41, 0x51, 0x60, 0x70, 0x61, 0x71, + 0x42, 0x52, 0x43, 0x53, 0x62, 0x72, 0x63, 0x73, + 0x04, 0x14, 0x05, 0x15, 0x24, 0x34, 0x25, 0x35, + 0x06, 0x16, 0x07, 0x17, 0x26, 0x36, 0x27, 0x37, + 0x44, 0x54, 0x45, 0x55, 0x64, 0x74, 0x65, 0x75, + 0x46, 0x56, 0x47, 0x57, 0x66, 0x76, 0x67, 0x77, + 0x80, 0x90, 0x81, 0x91, 0xA0, 0xB0, 0xA1, 0xB1, + 0x82, 0x92, 0x83, 0x93, 0xA2, 0xB2, 0xA3, 0xB3, + 0xC0, 0xD0, 0xC1, 0xD1, 0xE0, 0xF0, 0xE1, 0xF1, + 0xC2, 0xD2, 0xC3, 0xD3, 0xE2, 0xF2, 0xE3, 0xF3, + 0x84, 0x94, 0x85, 0x95, 0xA4, 0xB4, 0xA5, 0xB5, + 0x86, 0x96, 0x87, 0x97, 0xA6, 0xB6, 0xA7, 0xB7, + 0xC4, 0xD4, 0xC5, 0xD5, 0xE4, 0xF4, 0xE5, 0xF5, + 0xC6, 0xD6, 0xC7, 0xD7, 0xE6, 0xF6, 0xE7, 0xF7, + 0x08, 0x18, 0x09, 0x19, 0x28, 0x38, 0x29, 0x39, + 0x0A, 0x1A, 0x0B, 0x1B, 0x2A, 0x3A, 0x2B, 0x3B, + 0x48, 0x58, 0x49, 0x59, 0x68, 0x78, 0x69, 0x79, + 0x4A, 0x5A, 0x4B, 0x5B, 0x6A, 0x7A, 0x6B, 0x7B, + 0x0C, 0x1C, 0x0D, 0x1D, 0x2C, 0x3C, 0x2D, 0x3D, + 0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F, + 0x4C, 0x5C, 0x4D, 0x5D, 0x6C, 0x7C, 0x6D, 0x7D, + 0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F, + 0x88, 0x98, 0x89, 0x99, 0xA8, 0xB8, 0xA9, 0xB9, + 0x8A, 0x9A, 0x8B, 0x9B, 0xAA, 0xBA, 0xAB, 0xBB, + 0xC8, 0xD8, 0xC9, 0xD9, 0xE8, 0xF8, 0xE9, 0xF9, + 0xCA, 0xDA, 0xCB, 0xDB, 0xEA, 0xFA, 0xEB, 0xFB, + 0x8C, 0x9C, 0x8D, 0x9D, 0xAC, 0xBC, 0xAD, 0xBD, + 0x8E, 0x9E, 0x8F, 0x9F, 0xAE, 0xBE, 0xAF, 0xBF, + 0xCC, 0xDC, 0xCD, 0xDD, 0xEC, 0xFC, 0xED, 0xFD, + 0xCE, 0xDE, 0xCF, 0xDF, 0xEE, 0xFE, 0xEF, 0xFF + ); + + /** + * Inverse IP mapping helper table. + * Indexing this table with a byte value reverses the bit order. + * + * @var array + * @access private + */ + var $invipmap = array( + 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, + 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0, + 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, + 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8, + 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, + 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4, + 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, + 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC, + 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, + 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2, + 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, + 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA, + 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, + 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6, + 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, + 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE, + 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, + 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1, + 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, + 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9, + 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, + 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5, + 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, + 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD, + 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, + 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3, + 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, + 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB, + 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, + 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7, + 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, + 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF + ); + + /** + * Pre-permuted S-box1 + * + * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the + * P table: concatenation can then be replaced by exclusive ORs. + * + * @var array + * @access private + */ + var $sbox1 = array( + 0x00808200, 0x00000000, 0x00008000, 0x00808202, + 0x00808002, 0x00008202, 0x00000002, 0x00008000, + 0x00000200, 0x00808200, 0x00808202, 0x00000200, + 0x00800202, 0x00808002, 0x00800000, 0x00000002, + 0x00000202, 0x00800200, 0x00800200, 0x00008200, + 0x00008200, 0x00808000, 0x00808000, 0x00800202, + 0x00008002, 0x00800002, 0x00800002, 0x00008002, + 0x00000000, 0x00000202, 0x00008202, 0x00800000, + 0x00008000, 0x00808202, 0x00000002, 0x00808000, + 0x00808200, 0x00800000, 0x00800000, 0x00000200, + 0x00808002, 0x00008000, 0x00008200, 0x00800002, + 0x00000200, 0x00000002, 0x00800202, 0x00008202, + 0x00808202, 0x00008002, 0x00808000, 0x00800202, + 0x00800002, 0x00000202, 0x00008202, 0x00808200, + 0x00000202, 0x00800200, 0x00800200, 0x00000000, + 0x00008002, 0x00008200, 0x00000000, 0x00808002 + ); + + /** + * Pre-permuted S-box2 + * + * @var array + * @access private + */ + var $sbox2 = array( + 0x40084010, 0x40004000, 0x00004000, 0x00084010, + 0x00080000, 0x00000010, 0x40080010, 0x40004010, + 0x40000010, 0x40084010, 0x40084000, 0x40000000, + 0x40004000, 0x00080000, 0x00000010, 0x40080010, + 0x00084000, 0x00080010, 0x40004010, 0x00000000, + 0x40000000, 0x00004000, 0x00084010, 0x40080000, + 0x00080010, 0x40000010, 0x00000000, 0x00084000, + 0x00004010, 0x40084000, 0x40080000, 0x00004010, + 0x00000000, 0x00084010, 0x40080010, 0x00080000, + 0x40004010, 0x40080000, 0x40084000, 0x00004000, + 0x40080000, 0x40004000, 0x00000010, 0x40084010, + 0x00084010, 0x00000010, 0x00004000, 0x40000000, + 0x00004010, 0x40084000, 0x00080000, 0x40000010, + 0x00080010, 0x40004010, 0x40000010, 0x00080010, + 0x00084000, 0x00000000, 0x40004000, 0x00004010, + 0x40000000, 0x40080010, 0x40084010, 0x00084000 + ); + + /** + * Pre-permuted S-box3 + * + * @var array + * @access private + */ + var $sbox3 = array( + 0x00000104, 0x04010100, 0x00000000, 0x04010004, + 0x04000100, 0x00000000, 0x00010104, 0x04000100, + 0x00010004, 0x04000004, 0x04000004, 0x00010000, + 0x04010104, 0x00010004, 0x04010000, 0x00000104, + 0x04000000, 0x00000004, 0x04010100, 0x00000100, + 0x00010100, 0x04010000, 0x04010004, 0x00010104, + 0x04000104, 0x00010100, 0x00010000, 0x04000104, + 0x00000004, 0x04010104, 0x00000100, 0x04000000, + 0x04010100, 0x04000000, 0x00010004, 0x00000104, + 0x00010000, 0x04010100, 0x04000100, 0x00000000, + 0x00000100, 0x00010004, 0x04010104, 0x04000100, + 0x04000004, 0x00000100, 0x00000000, 0x04010004, + 0x04000104, 0x00010000, 0x04000000, 0x04010104, + 0x00000004, 0x00010104, 0x00010100, 0x04000004, + 0x04010000, 0x04000104, 0x00000104, 0x04010000, + 0x00010104, 0x00000004, 0x04010004, 0x00010100 + ); + + /** + * Pre-permuted S-box4 + * + * @var array + * @access private + */ + var $sbox4 = array( + 0x80401000, 0x80001040, 0x80001040, 0x00000040, + 0x00401040, 0x80400040, 0x80400000, 0x80001000, + 0x00000000, 0x00401000, 0x00401000, 0x80401040, + 0x80000040, 0x00000000, 0x00400040, 0x80400000, + 0x80000000, 0x00001000, 0x00400000, 0x80401000, + 0x00000040, 0x00400000, 0x80001000, 0x00001040, + 0x80400040, 0x80000000, 0x00001040, 0x00400040, + 0x00001000, 0x00401040, 0x80401040, 0x80000040, + 0x00400040, 0x80400000, 0x00401000, 0x80401040, + 0x80000040, 0x00000000, 0x00000000, 0x00401000, + 0x00001040, 0x00400040, 0x80400040, 0x80000000, + 0x80401000, 0x80001040, 0x80001040, 0x00000040, + 0x80401040, 0x80000040, 0x80000000, 0x00001000, + 0x80400000, 0x80001000, 0x00401040, 0x80400040, + 0x80001000, 0x00001040, 0x00400000, 0x80401000, + 0x00000040, 0x00400000, 0x00001000, 0x00401040 + ); + + /** + * Pre-permuted S-box5 + * + * @var array + * @access private + */ + var $sbox5 = array( + 0x00000080, 0x01040080, 0x01040000, 0x21000080, + 0x00040000, 0x00000080, 0x20000000, 0x01040000, + 0x20040080, 0x00040000, 0x01000080, 0x20040080, + 0x21000080, 0x21040000, 0x00040080, 0x20000000, + 0x01000000, 0x20040000, 0x20040000, 0x00000000, + 0x20000080, 0x21040080, 0x21040080, 0x01000080, + 0x21040000, 0x20000080, 0x00000000, 0x21000000, + 0x01040080, 0x01000000, 0x21000000, 0x00040080, + 0x00040000, 0x21000080, 0x00000080, 0x01000000, + 0x20000000, 0x01040000, 0x21000080, 0x20040080, + 0x01000080, 0x20000000, 0x21040000, 0x01040080, + 0x20040080, 0x00000080, 0x01000000, 0x21040000, + 0x21040080, 0x00040080, 0x21000000, 0x21040080, + 0x01040000, 0x00000000, 0x20040000, 0x21000000, + 0x00040080, 0x01000080, 0x20000080, 0x00040000, + 0x00000000, 0x20040000, 0x01040080, 0x20000080 + ); + + /** + * Pre-permuted S-box6 + * + * @var array + * @access private + */ + var $sbox6 = array( + 0x10000008, 0x10200000, 0x00002000, 0x10202008, + 0x10200000, 0x00000008, 0x10202008, 0x00200000, + 0x10002000, 0x00202008, 0x00200000, 0x10000008, + 0x00200008, 0x10002000, 0x10000000, 0x00002008, + 0x00000000, 0x00200008, 0x10002008, 0x00002000, + 0x00202000, 0x10002008, 0x00000008, 0x10200008, + 0x10200008, 0x00000000, 0x00202008, 0x10202000, + 0x00002008, 0x00202000, 0x10202000, 0x10000000, + 0x10002000, 0x00000008, 0x10200008, 0x00202000, + 0x10202008, 0x00200000, 0x00002008, 0x10000008, + 0x00200000, 0x10002000, 0x10000000, 0x00002008, + 0x10000008, 0x10202008, 0x00202000, 0x10200000, + 0x00202008, 0x10202000, 0x00000000, 0x10200008, + 0x00000008, 0x00002000, 0x10200000, 0x00202008, + 0x00002000, 0x00200008, 0x10002008, 0x00000000, + 0x10202000, 0x10000000, 0x00200008, 0x10002008 + ); + + /** + * Pre-permuted S-box7 + * + * @var array + * @access private + */ + var $sbox7 = array( + 0x00100000, 0x02100001, 0x02000401, 0x00000000, + 0x00000400, 0x02000401, 0x00100401, 0x02100400, + 0x02100401, 0x00100000, 0x00000000, 0x02000001, + 0x00000001, 0x02000000, 0x02100001, 0x00000401, + 0x02000400, 0x00100401, 0x00100001, 0x02000400, + 0x02000001, 0x02100000, 0x02100400, 0x00100001, + 0x02100000, 0x00000400, 0x00000401, 0x02100401, + 0x00100400, 0x00000001, 0x02000000, 0x00100400, + 0x02000000, 0x00100400, 0x00100000, 0x02000401, + 0x02000401, 0x02100001, 0x02100001, 0x00000001, + 0x00100001, 0x02000000, 0x02000400, 0x00100000, + 0x02100400, 0x00000401, 0x00100401, 0x02100400, + 0x00000401, 0x02000001, 0x02100401, 0x02100000, + 0x00100400, 0x00000000, 0x00000001, 0x02100401, + 0x00000000, 0x00100401, 0x02100000, 0x00000400, + 0x02000001, 0x02000400, 0x00000400, 0x00100001 + ); + + /** + * Pre-permuted S-box8 + * + * @var array + * @access private + */ + var $sbox8 = array( + 0x08000820, 0x00000800, 0x00020000, 0x08020820, + 0x08000000, 0x08000820, 0x00000020, 0x08000000, + 0x00020020, 0x08020000, 0x08020820, 0x00020800, + 0x08020800, 0x00020820, 0x00000800, 0x00000020, + 0x08020000, 0x08000020, 0x08000800, 0x00000820, + 0x00020800, 0x00020020, 0x08020020, 0x08020800, + 0x00000820, 0x00000000, 0x00000000, 0x08020020, + 0x08000020, 0x08000800, 0x00020820, 0x00020000, + 0x00020820, 0x00020000, 0x08020800, 0x00000800, + 0x00000020, 0x08020020, 0x00000800, 0x00020820, + 0x08000800, 0x00000020, 0x08000020, 0x08020000, + 0x08020020, 0x08000000, 0x00020000, 0x08000820, + 0x00000000, 0x08020820, 0x00020020, 0x08000020, + 0x08020000, 0x08000800, 0x08000820, 0x00000000, + 0x08020820, 0x00020800, 0x00020800, 0x00000820, + 0x00000820, 0x00020020, 0x08000000, 0x08020800 + ); + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::isValidEngine() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + if ($this->key_length_max == 8) { + if ($engine == CRYPT_ENGINE_OPENSSL) { + $this->cipher_name_openssl_ecb = 'des-ecb'; + $this->cipher_name_openssl = 'des-' . $this->_openssl_translate_mode(); + } + } + + return parent::isValidEngine($engine); + } + + /** + * Sets the key. + * + * Keys can be of any length. DES, itself, uses 64-bit keys (eg. strlen($key) == 8), however, we + * only use the first eight, if $key has more then eight characters in it, and pad $key with the + * null byte if it is less then eight characters long. + * + * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. + * + * If the key is not explicitly set, it'll be assumed to be all zero's. + * + * @see Crypt_Base::setKey() + * @access public + * @param string $key + */ + function setKey($key) + { + // We check/cut here only up to max length of the key. + // Key padding to the proper length will be done in _setupKey() + if (strlen($key) > $this->key_length_max) { + $key = substr($key, 0, $this->key_length_max); + } + + // Sets the key + parent::setKey($key); + } + + /** + * Encrypts a block + * + * @see Crypt_Base::_encryptBlock() + * @see Crypt_Base::encrypt() + * @see self::encrypt() + * @access private + * @param string $in + * @return string + */ + function _encryptBlock($in) + { + return $this->_processBlock($in, CRYPT_DES_ENCRYPT); + } + + /** + * Decrypts a block + * + * @see Crypt_Base::_decryptBlock() + * @see Crypt_Base::decrypt() + * @see self::decrypt() + * @access private + * @param string $in + * @return string + */ + function _decryptBlock($in) + { + return $this->_processBlock($in, CRYPT_DES_DECRYPT); + } + + /** + * Encrypts or decrypts a 64-bit block + * + * $mode should be either CRYPT_DES_ENCRYPT or CRYPT_DES_DECRYPT. See + * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general + * idea of what this function does. + * + * @see self::_encryptBlock() + * @see self::_decryptBlock() + * @access private + * @param string $block + * @param int $mode + * @return string + */ + function _processBlock($block, $mode) + { + static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip; + if (!$sbox1) { + $sbox1 = array_map("intval", $this->sbox1); + $sbox2 = array_map("intval", $this->sbox2); + $sbox3 = array_map("intval", $this->sbox3); + $sbox4 = array_map("intval", $this->sbox4); + $sbox5 = array_map("intval", $this->sbox5); + $sbox6 = array_map("intval", $this->sbox6); + $sbox7 = array_map("intval", $this->sbox7); + $sbox8 = array_map("intval", $this->sbox8); + /* Merge $shuffle with $[inv]ipmap */ + for ($i = 0; $i < 256; ++$i) { + $shuffleip[] = $this->shuffle[$this->ipmap[$i]]; + $shuffleinvip[] = $this->shuffle[$this->invipmap[$i]]; + } + } + + $keys = $this->keys[$mode]; + $ki = -1; + + // Do the initial IP permutation. + $t = unpack('Nl/Nr', $block); + list($l, $r) = array($t['l'], $t['r']); + $block = ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | + ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | + ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | + ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | + ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | + ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | + ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | + ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); + + // Extract L0 and R0. + $t = unpack('Nl/Nr', $block); + list($l, $r) = array($t['l'], $t['r']); + + for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) { + // Perform the 16 steps. + for ($i = 0; $i < 16; $i++) { + // start of "the Feistel (F) function" - see the following URL: + // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png + // Merge key schedule. + $b1 = (($r >> 3) & 0x1FFFFFFF) ^ ($r << 29) ^ $keys[++$ki]; + $b2 = (($r >> 31) & 0x00000001) ^ ($r << 1) ^ $keys[++$ki]; + + // S-box indexing. + $t = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^ + $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^ + $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^ + $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ $l; + // end of "the Feistel (F) function" + + $l = $r; + $r = $t; + } + + // Last step should not permute L & R. + $t = $l; + $l = $r; + $r = $t; + } + + // Perform the inverse IP permutation. + return ($shuffleinvip[($r >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | + ($shuffleinvip[($l >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | + ($shuffleinvip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | + ($shuffleinvip[($l >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | + ($shuffleinvip[($r >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | + ($shuffleinvip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | + ($shuffleinvip[ $r & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | + ($shuffleinvip[ $l & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); + } + + /** + * Creates the key schedule + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->des_rounds === $this->kl['des_rounds']) { + // already expanded + return; + } + $this->kl = array('key' => $this->key, 'des_rounds' => $this->des_rounds); + + static $shifts = array( // number of key bits shifted per round + 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 + ); + + static $pc1map = array( + 0x00, 0x00, 0x08, 0x08, 0x04, 0x04, 0x0C, 0x0C, + 0x02, 0x02, 0x0A, 0x0A, 0x06, 0x06, 0x0E, 0x0E, + 0x10, 0x10, 0x18, 0x18, 0x14, 0x14, 0x1C, 0x1C, + 0x12, 0x12, 0x1A, 0x1A, 0x16, 0x16, 0x1E, 0x1E, + 0x20, 0x20, 0x28, 0x28, 0x24, 0x24, 0x2C, 0x2C, + 0x22, 0x22, 0x2A, 0x2A, 0x26, 0x26, 0x2E, 0x2E, + 0x30, 0x30, 0x38, 0x38, 0x34, 0x34, 0x3C, 0x3C, + 0x32, 0x32, 0x3A, 0x3A, 0x36, 0x36, 0x3E, 0x3E, + 0x40, 0x40, 0x48, 0x48, 0x44, 0x44, 0x4C, 0x4C, + 0x42, 0x42, 0x4A, 0x4A, 0x46, 0x46, 0x4E, 0x4E, + 0x50, 0x50, 0x58, 0x58, 0x54, 0x54, 0x5C, 0x5C, + 0x52, 0x52, 0x5A, 0x5A, 0x56, 0x56, 0x5E, 0x5E, + 0x60, 0x60, 0x68, 0x68, 0x64, 0x64, 0x6C, 0x6C, + 0x62, 0x62, 0x6A, 0x6A, 0x66, 0x66, 0x6E, 0x6E, + 0x70, 0x70, 0x78, 0x78, 0x74, 0x74, 0x7C, 0x7C, + 0x72, 0x72, 0x7A, 0x7A, 0x76, 0x76, 0x7E, 0x7E, + 0x80, 0x80, 0x88, 0x88, 0x84, 0x84, 0x8C, 0x8C, + 0x82, 0x82, 0x8A, 0x8A, 0x86, 0x86, 0x8E, 0x8E, + 0x90, 0x90, 0x98, 0x98, 0x94, 0x94, 0x9C, 0x9C, + 0x92, 0x92, 0x9A, 0x9A, 0x96, 0x96, 0x9E, 0x9E, + 0xA0, 0xA0, 0xA8, 0xA8, 0xA4, 0xA4, 0xAC, 0xAC, + 0xA2, 0xA2, 0xAA, 0xAA, 0xA6, 0xA6, 0xAE, 0xAE, + 0xB0, 0xB0, 0xB8, 0xB8, 0xB4, 0xB4, 0xBC, 0xBC, + 0xB2, 0xB2, 0xBA, 0xBA, 0xB6, 0xB6, 0xBE, 0xBE, + 0xC0, 0xC0, 0xC8, 0xC8, 0xC4, 0xC4, 0xCC, 0xCC, + 0xC2, 0xC2, 0xCA, 0xCA, 0xC6, 0xC6, 0xCE, 0xCE, + 0xD0, 0xD0, 0xD8, 0xD8, 0xD4, 0xD4, 0xDC, 0xDC, + 0xD2, 0xD2, 0xDA, 0xDA, 0xD6, 0xD6, 0xDE, 0xDE, + 0xE0, 0xE0, 0xE8, 0xE8, 0xE4, 0xE4, 0xEC, 0xEC, + 0xE2, 0xE2, 0xEA, 0xEA, 0xE6, 0xE6, 0xEE, 0xEE, + 0xF0, 0xF0, 0xF8, 0xF8, 0xF4, 0xF4, 0xFC, 0xFC, + 0xF2, 0xF2, 0xFA, 0xFA, 0xF6, 0xF6, 0xFE, 0xFE + ); + + // Mapping tables for the PC-2 transformation. + static $pc2mapc1 = array( + 0x00000000, 0x00000400, 0x00200000, 0x00200400, + 0x00000001, 0x00000401, 0x00200001, 0x00200401, + 0x02000000, 0x02000400, 0x02200000, 0x02200400, + 0x02000001, 0x02000401, 0x02200001, 0x02200401 + ); + static $pc2mapc2 = array( + 0x00000000, 0x00000800, 0x08000000, 0x08000800, + 0x00010000, 0x00010800, 0x08010000, 0x08010800, + 0x00000000, 0x00000800, 0x08000000, 0x08000800, + 0x00010000, 0x00010800, 0x08010000, 0x08010800, + 0x00000100, 0x00000900, 0x08000100, 0x08000900, + 0x00010100, 0x00010900, 0x08010100, 0x08010900, + 0x00000100, 0x00000900, 0x08000100, 0x08000900, + 0x00010100, 0x00010900, 0x08010100, 0x08010900, + 0x00000010, 0x00000810, 0x08000010, 0x08000810, + 0x00010010, 0x00010810, 0x08010010, 0x08010810, + 0x00000010, 0x00000810, 0x08000010, 0x08000810, + 0x00010010, 0x00010810, 0x08010010, 0x08010810, + 0x00000110, 0x00000910, 0x08000110, 0x08000910, + 0x00010110, 0x00010910, 0x08010110, 0x08010910, + 0x00000110, 0x00000910, 0x08000110, 0x08000910, + 0x00010110, 0x00010910, 0x08010110, 0x08010910, + 0x00040000, 0x00040800, 0x08040000, 0x08040800, + 0x00050000, 0x00050800, 0x08050000, 0x08050800, + 0x00040000, 0x00040800, 0x08040000, 0x08040800, + 0x00050000, 0x00050800, 0x08050000, 0x08050800, + 0x00040100, 0x00040900, 0x08040100, 0x08040900, + 0x00050100, 0x00050900, 0x08050100, 0x08050900, + 0x00040100, 0x00040900, 0x08040100, 0x08040900, + 0x00050100, 0x00050900, 0x08050100, 0x08050900, + 0x00040010, 0x00040810, 0x08040010, 0x08040810, + 0x00050010, 0x00050810, 0x08050010, 0x08050810, + 0x00040010, 0x00040810, 0x08040010, 0x08040810, + 0x00050010, 0x00050810, 0x08050010, 0x08050810, + 0x00040110, 0x00040910, 0x08040110, 0x08040910, + 0x00050110, 0x00050910, 0x08050110, 0x08050910, + 0x00040110, 0x00040910, 0x08040110, 0x08040910, + 0x00050110, 0x00050910, 0x08050110, 0x08050910, + 0x01000000, 0x01000800, 0x09000000, 0x09000800, + 0x01010000, 0x01010800, 0x09010000, 0x09010800, + 0x01000000, 0x01000800, 0x09000000, 0x09000800, + 0x01010000, 0x01010800, 0x09010000, 0x09010800, + 0x01000100, 0x01000900, 0x09000100, 0x09000900, + 0x01010100, 0x01010900, 0x09010100, 0x09010900, + 0x01000100, 0x01000900, 0x09000100, 0x09000900, + 0x01010100, 0x01010900, 0x09010100, 0x09010900, + 0x01000010, 0x01000810, 0x09000010, 0x09000810, + 0x01010010, 0x01010810, 0x09010010, 0x09010810, + 0x01000010, 0x01000810, 0x09000010, 0x09000810, + 0x01010010, 0x01010810, 0x09010010, 0x09010810, + 0x01000110, 0x01000910, 0x09000110, 0x09000910, + 0x01010110, 0x01010910, 0x09010110, 0x09010910, + 0x01000110, 0x01000910, 0x09000110, 0x09000910, + 0x01010110, 0x01010910, 0x09010110, 0x09010910, + 0x01040000, 0x01040800, 0x09040000, 0x09040800, + 0x01050000, 0x01050800, 0x09050000, 0x09050800, + 0x01040000, 0x01040800, 0x09040000, 0x09040800, + 0x01050000, 0x01050800, 0x09050000, 0x09050800, + 0x01040100, 0x01040900, 0x09040100, 0x09040900, + 0x01050100, 0x01050900, 0x09050100, 0x09050900, + 0x01040100, 0x01040900, 0x09040100, 0x09040900, + 0x01050100, 0x01050900, 0x09050100, 0x09050900, + 0x01040010, 0x01040810, 0x09040010, 0x09040810, + 0x01050010, 0x01050810, 0x09050010, 0x09050810, + 0x01040010, 0x01040810, 0x09040010, 0x09040810, + 0x01050010, 0x01050810, 0x09050010, 0x09050810, + 0x01040110, 0x01040910, 0x09040110, 0x09040910, + 0x01050110, 0x01050910, 0x09050110, 0x09050910, + 0x01040110, 0x01040910, 0x09040110, 0x09040910, + 0x01050110, 0x01050910, 0x09050110, 0x09050910 + ); + static $pc2mapc3 = array( + 0x00000000, 0x00000004, 0x00001000, 0x00001004, + 0x00000000, 0x00000004, 0x00001000, 0x00001004, + 0x10000000, 0x10000004, 0x10001000, 0x10001004, + 0x10000000, 0x10000004, 0x10001000, 0x10001004, + 0x00000020, 0x00000024, 0x00001020, 0x00001024, + 0x00000020, 0x00000024, 0x00001020, 0x00001024, + 0x10000020, 0x10000024, 0x10001020, 0x10001024, + 0x10000020, 0x10000024, 0x10001020, 0x10001024, + 0x00080000, 0x00080004, 0x00081000, 0x00081004, + 0x00080000, 0x00080004, 0x00081000, 0x00081004, + 0x10080000, 0x10080004, 0x10081000, 0x10081004, + 0x10080000, 0x10080004, 0x10081000, 0x10081004, + 0x00080020, 0x00080024, 0x00081020, 0x00081024, + 0x00080020, 0x00080024, 0x00081020, 0x00081024, + 0x10080020, 0x10080024, 0x10081020, 0x10081024, + 0x10080020, 0x10080024, 0x10081020, 0x10081024, + 0x20000000, 0x20000004, 0x20001000, 0x20001004, + 0x20000000, 0x20000004, 0x20001000, 0x20001004, + 0x30000000, 0x30000004, 0x30001000, 0x30001004, + 0x30000000, 0x30000004, 0x30001000, 0x30001004, + 0x20000020, 0x20000024, 0x20001020, 0x20001024, + 0x20000020, 0x20000024, 0x20001020, 0x20001024, + 0x30000020, 0x30000024, 0x30001020, 0x30001024, + 0x30000020, 0x30000024, 0x30001020, 0x30001024, + 0x20080000, 0x20080004, 0x20081000, 0x20081004, + 0x20080000, 0x20080004, 0x20081000, 0x20081004, + 0x30080000, 0x30080004, 0x30081000, 0x30081004, + 0x30080000, 0x30080004, 0x30081000, 0x30081004, + 0x20080020, 0x20080024, 0x20081020, 0x20081024, + 0x20080020, 0x20080024, 0x20081020, 0x20081024, + 0x30080020, 0x30080024, 0x30081020, 0x30081024, + 0x30080020, 0x30080024, 0x30081020, 0x30081024, + 0x00000002, 0x00000006, 0x00001002, 0x00001006, + 0x00000002, 0x00000006, 0x00001002, 0x00001006, + 0x10000002, 0x10000006, 0x10001002, 0x10001006, + 0x10000002, 0x10000006, 0x10001002, 0x10001006, + 0x00000022, 0x00000026, 0x00001022, 0x00001026, + 0x00000022, 0x00000026, 0x00001022, 0x00001026, + 0x10000022, 0x10000026, 0x10001022, 0x10001026, + 0x10000022, 0x10000026, 0x10001022, 0x10001026, + 0x00080002, 0x00080006, 0x00081002, 0x00081006, + 0x00080002, 0x00080006, 0x00081002, 0x00081006, + 0x10080002, 0x10080006, 0x10081002, 0x10081006, + 0x10080002, 0x10080006, 0x10081002, 0x10081006, + 0x00080022, 0x00080026, 0x00081022, 0x00081026, + 0x00080022, 0x00080026, 0x00081022, 0x00081026, + 0x10080022, 0x10080026, 0x10081022, 0x10081026, + 0x10080022, 0x10080026, 0x10081022, 0x10081026, + 0x20000002, 0x20000006, 0x20001002, 0x20001006, + 0x20000002, 0x20000006, 0x20001002, 0x20001006, + 0x30000002, 0x30000006, 0x30001002, 0x30001006, + 0x30000002, 0x30000006, 0x30001002, 0x30001006, + 0x20000022, 0x20000026, 0x20001022, 0x20001026, + 0x20000022, 0x20000026, 0x20001022, 0x20001026, + 0x30000022, 0x30000026, 0x30001022, 0x30001026, + 0x30000022, 0x30000026, 0x30001022, 0x30001026, + 0x20080002, 0x20080006, 0x20081002, 0x20081006, + 0x20080002, 0x20080006, 0x20081002, 0x20081006, + 0x30080002, 0x30080006, 0x30081002, 0x30081006, + 0x30080002, 0x30080006, 0x30081002, 0x30081006, + 0x20080022, 0x20080026, 0x20081022, 0x20081026, + 0x20080022, 0x20080026, 0x20081022, 0x20081026, + 0x30080022, 0x30080026, 0x30081022, 0x30081026, + 0x30080022, 0x30080026, 0x30081022, 0x30081026 + ); + static $pc2mapc4 = array( + 0x00000000, 0x00100000, 0x00000008, 0x00100008, + 0x00000200, 0x00100200, 0x00000208, 0x00100208, + 0x00000000, 0x00100000, 0x00000008, 0x00100008, + 0x00000200, 0x00100200, 0x00000208, 0x00100208, + 0x04000000, 0x04100000, 0x04000008, 0x04100008, + 0x04000200, 0x04100200, 0x04000208, 0x04100208, + 0x04000000, 0x04100000, 0x04000008, 0x04100008, + 0x04000200, 0x04100200, 0x04000208, 0x04100208, + 0x00002000, 0x00102000, 0x00002008, 0x00102008, + 0x00002200, 0x00102200, 0x00002208, 0x00102208, + 0x00002000, 0x00102000, 0x00002008, 0x00102008, + 0x00002200, 0x00102200, 0x00002208, 0x00102208, + 0x04002000, 0x04102000, 0x04002008, 0x04102008, + 0x04002200, 0x04102200, 0x04002208, 0x04102208, + 0x04002000, 0x04102000, 0x04002008, 0x04102008, + 0x04002200, 0x04102200, 0x04002208, 0x04102208, + 0x00000000, 0x00100000, 0x00000008, 0x00100008, + 0x00000200, 0x00100200, 0x00000208, 0x00100208, + 0x00000000, 0x00100000, 0x00000008, 0x00100008, + 0x00000200, 0x00100200, 0x00000208, 0x00100208, + 0x04000000, 0x04100000, 0x04000008, 0x04100008, + 0x04000200, 0x04100200, 0x04000208, 0x04100208, + 0x04000000, 0x04100000, 0x04000008, 0x04100008, + 0x04000200, 0x04100200, 0x04000208, 0x04100208, + 0x00002000, 0x00102000, 0x00002008, 0x00102008, + 0x00002200, 0x00102200, 0x00002208, 0x00102208, + 0x00002000, 0x00102000, 0x00002008, 0x00102008, + 0x00002200, 0x00102200, 0x00002208, 0x00102208, + 0x04002000, 0x04102000, 0x04002008, 0x04102008, + 0x04002200, 0x04102200, 0x04002208, 0x04102208, + 0x04002000, 0x04102000, 0x04002008, 0x04102008, + 0x04002200, 0x04102200, 0x04002208, 0x04102208, + 0x00020000, 0x00120000, 0x00020008, 0x00120008, + 0x00020200, 0x00120200, 0x00020208, 0x00120208, + 0x00020000, 0x00120000, 0x00020008, 0x00120008, + 0x00020200, 0x00120200, 0x00020208, 0x00120208, + 0x04020000, 0x04120000, 0x04020008, 0x04120008, + 0x04020200, 0x04120200, 0x04020208, 0x04120208, + 0x04020000, 0x04120000, 0x04020008, 0x04120008, + 0x04020200, 0x04120200, 0x04020208, 0x04120208, + 0x00022000, 0x00122000, 0x00022008, 0x00122008, + 0x00022200, 0x00122200, 0x00022208, 0x00122208, + 0x00022000, 0x00122000, 0x00022008, 0x00122008, + 0x00022200, 0x00122200, 0x00022208, 0x00122208, + 0x04022000, 0x04122000, 0x04022008, 0x04122008, + 0x04022200, 0x04122200, 0x04022208, 0x04122208, + 0x04022000, 0x04122000, 0x04022008, 0x04122008, + 0x04022200, 0x04122200, 0x04022208, 0x04122208, + 0x00020000, 0x00120000, 0x00020008, 0x00120008, + 0x00020200, 0x00120200, 0x00020208, 0x00120208, + 0x00020000, 0x00120000, 0x00020008, 0x00120008, + 0x00020200, 0x00120200, 0x00020208, 0x00120208, + 0x04020000, 0x04120000, 0x04020008, 0x04120008, + 0x04020200, 0x04120200, 0x04020208, 0x04120208, + 0x04020000, 0x04120000, 0x04020008, 0x04120008, + 0x04020200, 0x04120200, 0x04020208, 0x04120208, + 0x00022000, 0x00122000, 0x00022008, 0x00122008, + 0x00022200, 0x00122200, 0x00022208, 0x00122208, + 0x00022000, 0x00122000, 0x00022008, 0x00122008, + 0x00022200, 0x00122200, 0x00022208, 0x00122208, + 0x04022000, 0x04122000, 0x04022008, 0x04122008, + 0x04022200, 0x04122200, 0x04022208, 0x04122208, + 0x04022000, 0x04122000, 0x04022008, 0x04122008, + 0x04022200, 0x04122200, 0x04022208, 0x04122208 + ); + static $pc2mapd1 = array( + 0x00000000, 0x00000001, 0x08000000, 0x08000001, + 0x00200000, 0x00200001, 0x08200000, 0x08200001, + 0x00000002, 0x00000003, 0x08000002, 0x08000003, + 0x00200002, 0x00200003, 0x08200002, 0x08200003 + ); + static $pc2mapd2 = array( + 0x00000000, 0x00100000, 0x00000800, 0x00100800, + 0x00000000, 0x00100000, 0x00000800, 0x00100800, + 0x04000000, 0x04100000, 0x04000800, 0x04100800, + 0x04000000, 0x04100000, 0x04000800, 0x04100800, + 0x00000004, 0x00100004, 0x00000804, 0x00100804, + 0x00000004, 0x00100004, 0x00000804, 0x00100804, + 0x04000004, 0x04100004, 0x04000804, 0x04100804, + 0x04000004, 0x04100004, 0x04000804, 0x04100804, + 0x00000000, 0x00100000, 0x00000800, 0x00100800, + 0x00000000, 0x00100000, 0x00000800, 0x00100800, + 0x04000000, 0x04100000, 0x04000800, 0x04100800, + 0x04000000, 0x04100000, 0x04000800, 0x04100800, + 0x00000004, 0x00100004, 0x00000804, 0x00100804, + 0x00000004, 0x00100004, 0x00000804, 0x00100804, + 0x04000004, 0x04100004, 0x04000804, 0x04100804, + 0x04000004, 0x04100004, 0x04000804, 0x04100804, + 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, + 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, + 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, + 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, + 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, + 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, + 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, + 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, + 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, + 0x00000200, 0x00100200, 0x00000A00, 0x00100A00, + 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, + 0x04000200, 0x04100200, 0x04000A00, 0x04100A00, + 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, + 0x00000204, 0x00100204, 0x00000A04, 0x00100A04, + 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, + 0x04000204, 0x04100204, 0x04000A04, 0x04100A04, + 0x00020000, 0x00120000, 0x00020800, 0x00120800, + 0x00020000, 0x00120000, 0x00020800, 0x00120800, + 0x04020000, 0x04120000, 0x04020800, 0x04120800, + 0x04020000, 0x04120000, 0x04020800, 0x04120800, + 0x00020004, 0x00120004, 0x00020804, 0x00120804, + 0x00020004, 0x00120004, 0x00020804, 0x00120804, + 0x04020004, 0x04120004, 0x04020804, 0x04120804, + 0x04020004, 0x04120004, 0x04020804, 0x04120804, + 0x00020000, 0x00120000, 0x00020800, 0x00120800, + 0x00020000, 0x00120000, 0x00020800, 0x00120800, + 0x04020000, 0x04120000, 0x04020800, 0x04120800, + 0x04020000, 0x04120000, 0x04020800, 0x04120800, + 0x00020004, 0x00120004, 0x00020804, 0x00120804, + 0x00020004, 0x00120004, 0x00020804, 0x00120804, + 0x04020004, 0x04120004, 0x04020804, 0x04120804, + 0x04020004, 0x04120004, 0x04020804, 0x04120804, + 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, + 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, + 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, + 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, + 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, + 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, + 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, + 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, + 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, + 0x00020200, 0x00120200, 0x00020A00, 0x00120A00, + 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, + 0x04020200, 0x04120200, 0x04020A00, 0x04120A00, + 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, + 0x00020204, 0x00120204, 0x00020A04, 0x00120A04, + 0x04020204, 0x04120204, 0x04020A04, 0x04120A04, + 0x04020204, 0x04120204, 0x04020A04, 0x04120A04 + ); + static $pc2mapd3 = array( + 0x00000000, 0x00010000, 0x02000000, 0x02010000, + 0x00000020, 0x00010020, 0x02000020, 0x02010020, + 0x00040000, 0x00050000, 0x02040000, 0x02050000, + 0x00040020, 0x00050020, 0x02040020, 0x02050020, + 0x00002000, 0x00012000, 0x02002000, 0x02012000, + 0x00002020, 0x00012020, 0x02002020, 0x02012020, + 0x00042000, 0x00052000, 0x02042000, 0x02052000, + 0x00042020, 0x00052020, 0x02042020, 0x02052020, + 0x00000000, 0x00010000, 0x02000000, 0x02010000, + 0x00000020, 0x00010020, 0x02000020, 0x02010020, + 0x00040000, 0x00050000, 0x02040000, 0x02050000, + 0x00040020, 0x00050020, 0x02040020, 0x02050020, + 0x00002000, 0x00012000, 0x02002000, 0x02012000, + 0x00002020, 0x00012020, 0x02002020, 0x02012020, + 0x00042000, 0x00052000, 0x02042000, 0x02052000, + 0x00042020, 0x00052020, 0x02042020, 0x02052020, + 0x00000010, 0x00010010, 0x02000010, 0x02010010, + 0x00000030, 0x00010030, 0x02000030, 0x02010030, + 0x00040010, 0x00050010, 0x02040010, 0x02050010, + 0x00040030, 0x00050030, 0x02040030, 0x02050030, + 0x00002010, 0x00012010, 0x02002010, 0x02012010, + 0x00002030, 0x00012030, 0x02002030, 0x02012030, + 0x00042010, 0x00052010, 0x02042010, 0x02052010, + 0x00042030, 0x00052030, 0x02042030, 0x02052030, + 0x00000010, 0x00010010, 0x02000010, 0x02010010, + 0x00000030, 0x00010030, 0x02000030, 0x02010030, + 0x00040010, 0x00050010, 0x02040010, 0x02050010, + 0x00040030, 0x00050030, 0x02040030, 0x02050030, + 0x00002010, 0x00012010, 0x02002010, 0x02012010, + 0x00002030, 0x00012030, 0x02002030, 0x02012030, + 0x00042010, 0x00052010, 0x02042010, 0x02052010, + 0x00042030, 0x00052030, 0x02042030, 0x02052030, + 0x20000000, 0x20010000, 0x22000000, 0x22010000, + 0x20000020, 0x20010020, 0x22000020, 0x22010020, + 0x20040000, 0x20050000, 0x22040000, 0x22050000, + 0x20040020, 0x20050020, 0x22040020, 0x22050020, + 0x20002000, 0x20012000, 0x22002000, 0x22012000, + 0x20002020, 0x20012020, 0x22002020, 0x22012020, + 0x20042000, 0x20052000, 0x22042000, 0x22052000, + 0x20042020, 0x20052020, 0x22042020, 0x22052020, + 0x20000000, 0x20010000, 0x22000000, 0x22010000, + 0x20000020, 0x20010020, 0x22000020, 0x22010020, + 0x20040000, 0x20050000, 0x22040000, 0x22050000, + 0x20040020, 0x20050020, 0x22040020, 0x22050020, + 0x20002000, 0x20012000, 0x22002000, 0x22012000, + 0x20002020, 0x20012020, 0x22002020, 0x22012020, + 0x20042000, 0x20052000, 0x22042000, 0x22052000, + 0x20042020, 0x20052020, 0x22042020, 0x22052020, + 0x20000010, 0x20010010, 0x22000010, 0x22010010, + 0x20000030, 0x20010030, 0x22000030, 0x22010030, + 0x20040010, 0x20050010, 0x22040010, 0x22050010, + 0x20040030, 0x20050030, 0x22040030, 0x22050030, + 0x20002010, 0x20012010, 0x22002010, 0x22012010, + 0x20002030, 0x20012030, 0x22002030, 0x22012030, + 0x20042010, 0x20052010, 0x22042010, 0x22052010, + 0x20042030, 0x20052030, 0x22042030, 0x22052030, + 0x20000010, 0x20010010, 0x22000010, 0x22010010, + 0x20000030, 0x20010030, 0x22000030, 0x22010030, + 0x20040010, 0x20050010, 0x22040010, 0x22050010, + 0x20040030, 0x20050030, 0x22040030, 0x22050030, + 0x20002010, 0x20012010, 0x22002010, 0x22012010, + 0x20002030, 0x20012030, 0x22002030, 0x22012030, + 0x20042010, 0x20052010, 0x22042010, 0x22052010, + 0x20042030, 0x20052030, 0x22042030, 0x22052030 + ); + static $pc2mapd4 = array( + 0x00000000, 0x00000400, 0x01000000, 0x01000400, + 0x00000000, 0x00000400, 0x01000000, 0x01000400, + 0x00000100, 0x00000500, 0x01000100, 0x01000500, + 0x00000100, 0x00000500, 0x01000100, 0x01000500, + 0x10000000, 0x10000400, 0x11000000, 0x11000400, + 0x10000000, 0x10000400, 0x11000000, 0x11000400, + 0x10000100, 0x10000500, 0x11000100, 0x11000500, + 0x10000100, 0x10000500, 0x11000100, 0x11000500, + 0x00080000, 0x00080400, 0x01080000, 0x01080400, + 0x00080000, 0x00080400, 0x01080000, 0x01080400, + 0x00080100, 0x00080500, 0x01080100, 0x01080500, + 0x00080100, 0x00080500, 0x01080100, 0x01080500, + 0x10080000, 0x10080400, 0x11080000, 0x11080400, + 0x10080000, 0x10080400, 0x11080000, 0x11080400, + 0x10080100, 0x10080500, 0x11080100, 0x11080500, + 0x10080100, 0x10080500, 0x11080100, 0x11080500, + 0x00000008, 0x00000408, 0x01000008, 0x01000408, + 0x00000008, 0x00000408, 0x01000008, 0x01000408, + 0x00000108, 0x00000508, 0x01000108, 0x01000508, + 0x00000108, 0x00000508, 0x01000108, 0x01000508, + 0x10000008, 0x10000408, 0x11000008, 0x11000408, + 0x10000008, 0x10000408, 0x11000008, 0x11000408, + 0x10000108, 0x10000508, 0x11000108, 0x11000508, + 0x10000108, 0x10000508, 0x11000108, 0x11000508, + 0x00080008, 0x00080408, 0x01080008, 0x01080408, + 0x00080008, 0x00080408, 0x01080008, 0x01080408, + 0x00080108, 0x00080508, 0x01080108, 0x01080508, + 0x00080108, 0x00080508, 0x01080108, 0x01080508, + 0x10080008, 0x10080408, 0x11080008, 0x11080408, + 0x10080008, 0x10080408, 0x11080008, 0x11080408, + 0x10080108, 0x10080508, 0x11080108, 0x11080508, + 0x10080108, 0x10080508, 0x11080108, 0x11080508, + 0x00001000, 0x00001400, 0x01001000, 0x01001400, + 0x00001000, 0x00001400, 0x01001000, 0x01001400, + 0x00001100, 0x00001500, 0x01001100, 0x01001500, + 0x00001100, 0x00001500, 0x01001100, 0x01001500, + 0x10001000, 0x10001400, 0x11001000, 0x11001400, + 0x10001000, 0x10001400, 0x11001000, 0x11001400, + 0x10001100, 0x10001500, 0x11001100, 0x11001500, + 0x10001100, 0x10001500, 0x11001100, 0x11001500, + 0x00081000, 0x00081400, 0x01081000, 0x01081400, + 0x00081000, 0x00081400, 0x01081000, 0x01081400, + 0x00081100, 0x00081500, 0x01081100, 0x01081500, + 0x00081100, 0x00081500, 0x01081100, 0x01081500, + 0x10081000, 0x10081400, 0x11081000, 0x11081400, + 0x10081000, 0x10081400, 0x11081000, 0x11081400, + 0x10081100, 0x10081500, 0x11081100, 0x11081500, + 0x10081100, 0x10081500, 0x11081100, 0x11081500, + 0x00001008, 0x00001408, 0x01001008, 0x01001408, + 0x00001008, 0x00001408, 0x01001008, 0x01001408, + 0x00001108, 0x00001508, 0x01001108, 0x01001508, + 0x00001108, 0x00001508, 0x01001108, 0x01001508, + 0x10001008, 0x10001408, 0x11001008, 0x11001408, + 0x10001008, 0x10001408, 0x11001008, 0x11001408, + 0x10001108, 0x10001508, 0x11001108, 0x11001508, + 0x10001108, 0x10001508, 0x11001108, 0x11001508, + 0x00081008, 0x00081408, 0x01081008, 0x01081408, + 0x00081008, 0x00081408, 0x01081008, 0x01081408, + 0x00081108, 0x00081508, 0x01081108, 0x01081508, + 0x00081108, 0x00081508, 0x01081108, 0x01081508, + 0x10081008, 0x10081408, 0x11081008, 0x11081408, + 0x10081008, 0x10081408, 0x11081008, 0x11081408, + 0x10081108, 0x10081508, 0x11081108, 0x11081508, + 0x10081108, 0x10081508, 0x11081108, 0x11081508 + ); + + $keys = array(); + for ($des_round = 0; $des_round < $this->des_rounds; ++$des_round) { + // pad the key and remove extra characters as appropriate. + $key = str_pad(substr($this->key, $des_round * 8, 8), 8, "\0"); + + // Perform the PC/1 transformation and compute C and D. + $t = unpack('Nl/Nr', $key); + list($l, $r) = array($t['l'], $t['r']); + $key = ($this->shuffle[$pc1map[ $r & 0xFF]] & "\x80\x80\x80\x80\x80\x80\x80\x00") | + ($this->shuffle[$pc1map[($r >> 8) & 0xFF]] & "\x40\x40\x40\x40\x40\x40\x40\x00") | + ($this->shuffle[$pc1map[($r >> 16) & 0xFF]] & "\x20\x20\x20\x20\x20\x20\x20\x00") | + ($this->shuffle[$pc1map[($r >> 24) & 0xFF]] & "\x10\x10\x10\x10\x10\x10\x10\x00") | + ($this->shuffle[$pc1map[ $l & 0xFF]] & "\x08\x08\x08\x08\x08\x08\x08\x00") | + ($this->shuffle[$pc1map[($l >> 8) & 0xFF]] & "\x04\x04\x04\x04\x04\x04\x04\x00") | + ($this->shuffle[$pc1map[($l >> 16) & 0xFF]] & "\x02\x02\x02\x02\x02\x02\x02\x00") | + ($this->shuffle[$pc1map[($l >> 24) & 0xFF]] & "\x01\x01\x01\x01\x01\x01\x01\x00"); + $key = unpack('Nc/Nd', $key); + $c = ( $key['c'] >> 4) & 0x0FFFFFFF; + $d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F); + + $keys[$des_round] = array( + CRYPT_DES_ENCRYPT => array(), + CRYPT_DES_DECRYPT => array_fill(0, 32, 0) + ); + for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) { + $c <<= $shifts[$i]; + $c = ($c | ($c >> 28)) & 0x0FFFFFFF; + $d <<= $shifts[$i]; + $d = ($d | ($d >> 28)) & 0x0FFFFFFF; + + // Perform the PC-2 transformation. + $cp = $pc2mapc1[ $c >> 24 ] | $pc2mapc2[($c >> 16) & 0xFF] | + $pc2mapc3[($c >> 8) & 0xFF] | $pc2mapc4[ $c & 0xFF]; + $dp = $pc2mapd1[ $d >> 24 ] | $pc2mapd2[($d >> 16) & 0xFF] | + $pc2mapd3[($d >> 8) & 0xFF] | $pc2mapd4[ $d & 0xFF]; + + // Reorder: odd bytes/even bytes. Push the result in key schedule. + $val1 = ( $cp & 0xFF000000) | (($cp << 8) & 0x00FF0000) | + (($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF); + $val2 = (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) | + (($dp >> 8) & 0x0000FF00) | ( $dp & 0x000000FF); + $keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val1; + $keys[$des_round][CRYPT_DES_DECRYPT][$ki - 1] = $val1; + $keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val2; + $keys[$des_round][CRYPT_DES_DECRYPT][$ki ] = $val2; + } + } + + switch ($this->des_rounds) { + case 3: // 3DES keys + $this->keys = array( + CRYPT_DES_ENCRYPT => array_merge( + $keys[0][CRYPT_DES_ENCRYPT], + $keys[1][CRYPT_DES_DECRYPT], + $keys[2][CRYPT_DES_ENCRYPT] + ), + CRYPT_DES_DECRYPT => array_merge( + $keys[2][CRYPT_DES_DECRYPT], + $keys[1][CRYPT_DES_ENCRYPT], + $keys[0][CRYPT_DES_DECRYPT] + ) + ); + break; + // case 1: // DES keys + default: + $this->keys = array( + CRYPT_DES_ENCRYPT => $keys[0][CRYPT_DES_ENCRYPT], + CRYPT_DES_DECRYPT => $keys[0][CRYPT_DES_DECRYPT] + ); + } + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * @see Crypt_Base::_setupInlineCrypt() + * @access private + */ + function _setupInlineCrypt() + { + $lambda_functions =& Crypt_DES::_getLambdaFunctions(); + + // Engine configuration for: + // - DES ($des_rounds == 1) or + // - 3DES ($des_rounds == 3) + $des_rounds = $this->des_rounds; + + // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. + // (Currently, for Crypt_DES, one generated $lambda_function cost on php5.5@32bit ~135kb unfreeable mem and ~230kb on php5.5@64bit) + // (Currently, for Crypt_TripleDES, one generated $lambda_function cost on php5.5@32bit ~240kb unfreeable mem and ~340kb on php5.5@64bit) + // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one + $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); + + // Generation of a unique hash for our generated code + $code_hash = "Crypt_DES, $des_rounds, {$this->mode}"; + if ($gen_hi_opt_code) { + // For hi-optimized code, we create for each combination of + // $mode, $des_rounds and $this->key its own encrypt/decrypt function. + // After max 10 hi-optimized functions, we create generic + // (still very fast.. but not ultra) functions for each $mode/$des_rounds + // Currently 2 * 5 generic functions will be then max. possible. + $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); + } + + // Is there a re-usable $lambda_functions in there? If not, we have to create it. + if (!isset($lambda_functions[$code_hash])) { + // Init code for both, encrypt and decrypt. + $init_crypt = 'static $sbox1, $sbox2, $sbox3, $sbox4, $sbox5, $sbox6, $sbox7, $sbox8, $shuffleip, $shuffleinvip; + if (!$sbox1) { + $sbox1 = array_map("intval", $self->sbox1); + $sbox2 = array_map("intval", $self->sbox2); + $sbox3 = array_map("intval", $self->sbox3); + $sbox4 = array_map("intval", $self->sbox4); + $sbox5 = array_map("intval", $self->sbox5); + $sbox6 = array_map("intval", $self->sbox6); + $sbox7 = array_map("intval", $self->sbox7); + $sbox8 = array_map("intval", $self->sbox8);' + /* Merge $shuffle with $[inv]ipmap */ . ' + for ($i = 0; $i < 256; ++$i) { + $shuffleip[] = $self->shuffle[$self->ipmap[$i]]; + $shuffleinvip[] = $self->shuffle[$self->invipmap[$i]]; + } + } + '; + + switch (true) { + case $gen_hi_opt_code: + // In Hi-optimized code mode, we use our [3]DES key schedule as hardcoded integers. + // No futher initialisation of the $keys schedule is necessary. + // That is the extra performance boost. + $k = array( + CRYPT_DES_ENCRYPT => $this->keys[CRYPT_DES_ENCRYPT], + CRYPT_DES_DECRYPT => $this->keys[CRYPT_DES_DECRYPT] + ); + $init_encrypt = ''; + $init_decrypt = ''; + break; + default: + // In generic optimized code mode, we have to use, as the best compromise [currently], + // our key schedule as $ke/$kd arrays. (with hardcoded indexes...) + $k = array( + CRYPT_DES_ENCRYPT => array(), + CRYPT_DES_DECRYPT => array() + ); + for ($i = 0, $c = count($this->keys[CRYPT_DES_ENCRYPT]); $i < $c; ++$i) { + $k[CRYPT_DES_ENCRYPT][$i] = '$ke[' . $i . ']'; + $k[CRYPT_DES_DECRYPT][$i] = '$kd[' . $i . ']'; + } + $init_encrypt = '$ke = $self->keys[CRYPT_DES_ENCRYPT];'; + $init_decrypt = '$kd = $self->keys[CRYPT_DES_DECRYPT];'; + break; + } + + // Creating code for en- and decryption. + $crypt_block = array(); + foreach (array(CRYPT_DES_ENCRYPT, CRYPT_DES_DECRYPT) as $c) { + /* Do the initial IP permutation. */ + $crypt_block[$c] = ' + $in = unpack("N*", $in); + $l = $in[1]; + $r = $in[2]; + $in = unpack("N*", + ($shuffleip[ $r & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | + ($shuffleip[($r >> 8) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | + ($shuffleip[($r >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | + ($shuffleip[($r >> 24) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | + ($shuffleip[ $l & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | + ($shuffleip[($l >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | + ($shuffleip[($l >> 16) & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | + ($shuffleip[($l >> 24) & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01") + ); + ' . /* Extract L0 and R0 */ ' + $l = $in[1]; + $r = $in[2]; + '; + + $l = '$l'; + $r = '$r'; + + // Perform DES or 3DES. + for ($ki = -1, $des_round = 0; $des_round < $des_rounds; ++$des_round) { + // Perform the 16 steps. + for ($i = 0; $i < 16; ++$i) { + // start of "the Feistel (F) function" - see the following URL: + // http://en.wikipedia.org/wiki/Image:Data_Encryption_Standard_InfoBox_Diagram.png + // Merge key schedule. + $crypt_block[$c].= ' + $b1 = ((' . $r . ' >> 3) & 0x1FFFFFFF) ^ (' . $r . ' << 29) ^ ' . $k[$c][++$ki] . '; + $b2 = ((' . $r . ' >> 31) & 0x00000001) ^ (' . $r . ' << 1) ^ ' . $k[$c][++$ki] . ';' . + /* S-box indexing. */ + $l . ' = $sbox1[($b1 >> 24) & 0x3F] ^ $sbox2[($b2 >> 24) & 0x3F] ^ + $sbox3[($b1 >> 16) & 0x3F] ^ $sbox4[($b2 >> 16) & 0x3F] ^ + $sbox5[($b1 >> 8) & 0x3F] ^ $sbox6[($b2 >> 8) & 0x3F] ^ + $sbox7[ $b1 & 0x3F] ^ $sbox8[ $b2 & 0x3F] ^ ' . $l . '; + '; + // end of "the Feistel (F) function" + + // swap L & R + list($l, $r) = array($r, $l); + } + list($l, $r) = array($r, $l); + } + + // Perform the inverse IP permutation. + $crypt_block[$c].= '$in = + ($shuffleinvip[($l >> 24) & 0xFF] & "\x80\x80\x80\x80\x80\x80\x80\x80") | + ($shuffleinvip[($r >> 24) & 0xFF] & "\x40\x40\x40\x40\x40\x40\x40\x40") | + ($shuffleinvip[($l >> 16) & 0xFF] & "\x20\x20\x20\x20\x20\x20\x20\x20") | + ($shuffleinvip[($r >> 16) & 0xFF] & "\x10\x10\x10\x10\x10\x10\x10\x10") | + ($shuffleinvip[($l >> 8) & 0xFF] & "\x08\x08\x08\x08\x08\x08\x08\x08") | + ($shuffleinvip[($r >> 8) & 0xFF] & "\x04\x04\x04\x04\x04\x04\x04\x04") | + ($shuffleinvip[ $l & 0xFF] & "\x02\x02\x02\x02\x02\x02\x02\x02") | + ($shuffleinvip[ $r & 0xFF] & "\x01\x01\x01\x01\x01\x01\x01\x01"); + '; + } + + // Creates the inline-crypt function + $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( + array( + 'init_crypt' => $init_crypt, + 'init_encrypt' => $init_encrypt, + 'init_decrypt' => $init_decrypt, + 'encrypt_block' => $crypt_block[CRYPT_DES_ENCRYPT], + 'decrypt_block' => $crypt_block[CRYPT_DES_DECRYPT] + ) + ); + } + + // Set the inline-crypt function as callback in: $this->inline_crypt + $this->inline_crypt = $lambda_functions[$code_hash]; + } +} diff --git a/ipaylinks_statement/Crypt/Hash.php b/ipaylinks_statement/Crypt/Hash.php new file mode 100644 index 00000000..faa17c57 --- /dev/null +++ b/ipaylinks_statement/Crypt/Hash.php @@ -0,0 +1,861 @@ + + * setKey('abcdefg'); + * + * echo base64_encode($hash->hash('abcdefg')); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_Hash + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * @access private + * @see self::Crypt_Hash() + */ +/** + * Toggles the internal implementation + */ +define('CRYPT_HASH_MODE_INTERNAL', 1); +/** + * Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+. + */ +define('CRYPT_HASH_MODE_MHASH', 2); +/** + * Toggles the hash() implementation, which works on PHP 5.1.2+. + */ +define('CRYPT_HASH_MODE_HASH', 3); +/**#@-*/ + +/** + * Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions. + * + * @package Crypt_Hash + * @author Jim Wigginton + * @access public + */ +class Crypt_Hash +{ + /** + * Hash Parameter + * + * @see self::setHash() + * @var int + * @access private + */ + var $hashParam; + + /** + * Byte-length of compression blocks / key (Internal HMAC) + * + * @see self::setAlgorithm() + * @var int + * @access private + */ + var $b; + + /** + * Byte-length of hash output (Internal HMAC) + * + * @see self::setHash() + * @var int + * @access private + */ + var $l = false; + + /** + * Hash Algorithm + * + * @see self::setHash() + * @var string + * @access private + */ + var $hash; + + /** + * Key + * + * @see self::setKey() + * @var string + * @access private + */ + var $key = false; + + /** + * Outer XOR (Internal HMAC) + * + * @see self::setKey() + * @var string + * @access private + */ + var $opad; + + /** + * Inner XOR (Internal HMAC) + * + * @see self::setKey() + * @var string + * @access private + */ + var $ipad; + + /** + * Default Constructor. + * + * @param string $hash + * @return Crypt_Hash + * @access public + */ + function __construct($hash = 'sha1') + { + if (!defined('CRYPT_HASH_MODE')) { + switch (true) { + case extension_loaded('hash'): + define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_HASH); + break; + case extension_loaded('mhash'): + define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_MHASH); + break; + default: + define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_INTERNAL); + } + } + + $this->setHash($hash); + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param int $mode + * @access public + */ + function Crypt_Hash($hash = 'sha1') + { + $this->__construct($hash); + } + + /** + * Sets the key for HMACs + * + * Keys can be of any length. + * + * @access public + * @param string $key + */ + function setKey($key = false) + { + $this->key = $key; + } + + /** + * Gets the hash function. + * + * As set by the constructor or by the setHash() method. + * + * @access public + * @return string + */ + function getHash() + { + return $this->hashParam; + } + + /** + * Sets the hash function. + * + * @access public + * @param string $hash + */ + function setHash($hash) + { + $this->hashParam = $hash = strtolower($hash); + switch ($hash) { + case 'md5-96': + case 'sha1-96': + case 'sha256-96': + case 'sha512-96': + $hash = substr($hash, 0, -3); + $this->l = 12; // 96 / 8 = 12 + break; + case 'md2': + case 'md5': + $this->l = 16; + break; + case 'sha1': + $this->l = 20; + break; + case 'sha256': + $this->l = 32; + break; + case 'sha384': + $this->l = 48; + break; + case 'sha512': + $this->l = 64; + } + + switch ($hash) { + case 'md2': + $mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_HASH && in_array('md2', hash_algos()) ? + CRYPT_HASH_MODE_HASH : CRYPT_HASH_MODE_INTERNAL; + break; + case 'sha384': + case 'sha512': + $mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_MHASH ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE; + break; + default: + $mode = CRYPT_HASH_MODE; + } + + switch ($mode) { + case CRYPT_HASH_MODE_MHASH: + switch ($hash) { + case 'md5': + $this->hash = MHASH_MD5; + break; + case 'sha256': + $this->hash = MHASH_SHA256; + break; + case 'sha1': + default: + $this->hash = MHASH_SHA1; + } + return; + case CRYPT_HASH_MODE_HASH: + switch ($hash) { + case 'md5': + $this->hash = 'md5'; + return; + case 'md2': + case 'sha256': + case 'sha384': + case 'sha512': + $this->hash = $hash; + return; + case 'sha1': + default: + $this->hash = 'sha1'; + } + return; + } + + switch ($hash) { + case 'md2': + $this->b = 16; + $this->hash = array($this, '_md2'); + break; + case 'md5': + $this->b = 64; + $this->hash = array($this, '_md5'); + break; + case 'sha256': + $this->b = 64; + $this->hash = array($this, '_sha256'); + break; + case 'sha384': + case 'sha512': + $this->b = 128; + $this->hash = array($this, '_sha512'); + break; + case 'sha1': + default: + $this->b = 64; + $this->hash = array($this, '_sha1'); + } + + $this->ipad = str_repeat(chr(0x36), $this->b); + $this->opad = str_repeat(chr(0x5C), $this->b); + } + + /** + * Compute the HMAC. + * + * @access public + * @param string $text + * @return string + */ + function hash($text) + { + $mode = is_array($this->hash) ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE; + + if (!empty($this->key) || is_string($this->key)) { + switch ($mode) { + case CRYPT_HASH_MODE_MHASH: + $output = mhash($this->hash, $text, $this->key); + break; + case CRYPT_HASH_MODE_HASH: + $output = hash_hmac($this->hash, $text, $this->key, true); + break; + case CRYPT_HASH_MODE_INTERNAL: + /* "Applications that use keys longer than B bytes will first hash the key using H and then use the + resultant L byte string as the actual key to HMAC." + + -- http://tools.ietf.org/html/rfc2104#section-2 */ + $key = strlen($this->key) > $this->b ? call_user_func($this->hash, $this->key) : $this->key; + + $key = str_pad($key, $this->b, chr(0)); // step 1 + $temp = $this->ipad ^ $key; // step 2 + $temp .= $text; // step 3 + $temp = call_user_func($this->hash, $temp); // step 4 + $output = $this->opad ^ $key; // step 5 + $output.= $temp; // step 6 + $output = call_user_func($this->hash, $output); // step 7 + } + } else { + switch ($mode) { + case CRYPT_HASH_MODE_MHASH: + $output = mhash($this->hash, $text); + break; + case CRYPT_HASH_MODE_HASH: + $output = hash($this->hash, $text, true); + break; + case CRYPT_HASH_MODE_INTERNAL: + $output = call_user_func($this->hash, $text); + } + } + + return substr($output, 0, $this->l); + } + + /** + * Returns the hash length (in bytes) + * + * @access public + * @return int + */ + function getLength() + { + return $this->l; + } + + /** + * Wrapper for MD5 + * + * @access private + * @param string $m + */ + function _md5($m) + { + return pack('H*', md5($m)); + } + + /** + * Wrapper for SHA1 + * + * @access private + * @param string $m + */ + function _sha1($m) + { + return pack('H*', sha1($m)); + } + + /** + * Pure-PHP implementation of MD2 + * + * See {@link http://tools.ietf.org/html/rfc1319 RFC1319}. + * + * @access private + * @param string $m + */ + function _md2($m) + { + static $s = array( + 41, 46, 67, 201, 162, 216, 124, 1, 61, 54, 84, 161, 236, 240, 6, + 19, 98, 167, 5, 243, 192, 199, 115, 140, 152, 147, 43, 217, 188, + 76, 130, 202, 30, 155, 87, 60, 253, 212, 224, 22, 103, 66, 111, 24, + 138, 23, 229, 18, 190, 78, 196, 214, 218, 158, 222, 73, 160, 251, + 245, 142, 187, 47, 238, 122, 169, 104, 121, 145, 21, 178, 7, 63, + 148, 194, 16, 137, 11, 34, 95, 33, 128, 127, 93, 154, 90, 144, 50, + 39, 53, 62, 204, 231, 191, 247, 151, 3, 255, 25, 48, 179, 72, 165, + 181, 209, 215, 94, 146, 42, 172, 86, 170, 198, 79, 184, 56, 210, + 150, 164, 125, 182, 118, 252, 107, 226, 156, 116, 4, 241, 69, 157, + 112, 89, 100, 113, 135, 32, 134, 91, 207, 101, 230, 45, 168, 2, 27, + 96, 37, 173, 174, 176, 185, 246, 28, 70, 97, 105, 52, 64, 126, 15, + 85, 71, 163, 35, 221, 81, 175, 58, 195, 92, 249, 206, 186, 197, + 234, 38, 44, 83, 13, 110, 133, 40, 132, 9, 211, 223, 205, 244, 65, + 129, 77, 82, 106, 220, 55, 200, 108, 193, 171, 250, 36, 225, 123, + 8, 12, 189, 177, 74, 120, 136, 149, 139, 227, 99, 232, 109, 233, + 203, 213, 254, 59, 0, 29, 57, 242, 239, 183, 14, 102, 88, 208, 228, + 166, 119, 114, 248, 235, 117, 75, 10, 49, 68, 80, 180, 143, 237, + 31, 26, 219, 153, 141, 51, 159, 17, 131, 20 + ); + + // Step 1. Append Padding Bytes + $pad = 16 - (strlen($m) & 0xF); + $m.= str_repeat(chr($pad), $pad); + + $length = strlen($m); + + // Step 2. Append Checksum + $c = str_repeat(chr(0), 16); + $l = chr(0); + for ($i = 0; $i < $length; $i+= 16) { + for ($j = 0; $j < 16; $j++) { + // RFC1319 incorrectly states that C[j] should be set to S[c xor L] + //$c[$j] = chr($s[ord($m[$i + $j] ^ $l)]); + // per , however, C[j] should be set to S[c xor L] xor C[j] + $c[$j] = chr($s[ord($m[$i + $j] ^ $l)] ^ ord($c[$j])); + $l = $c[$j]; + } + } + $m.= $c; + + $length+= 16; + + // Step 3. Initialize MD Buffer + $x = str_repeat(chr(0), 48); + + // Step 4. Process Message in 16-Byte Blocks + for ($i = 0; $i < $length; $i+= 16) { + for ($j = 0; $j < 16; $j++) { + $x[$j + 16] = $m[$i + $j]; + $x[$j + 32] = $x[$j + 16] ^ $x[$j]; + } + $t = chr(0); + for ($j = 0; $j < 18; $j++) { + for ($k = 0; $k < 48; $k++) { + $x[$k] = $t = $x[$k] ^ chr($s[ord($t)]); + //$t = $x[$k] = $x[$k] ^ chr($s[ord($t)]); + } + $t = chr(ord($t) + $j); + } + } + + // Step 5. Output + return substr($x, 0, 16); + } + + /** + * Pure-PHP implementation of SHA256 + * + * See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}. + * + * @access private + * @param string $m + */ + function _sha256($m) + { + if (extension_loaded('suhosin')) { + return pack('H*', sha256($m)); + } + + // Initialize variables + $hash = array( + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 + ); + // Initialize table of round constants + // (first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311) + static $k = array( + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 + ); + + // Pre-processing + $length = strlen($m); + // to round to nearest 56 mod 64, we'll add 64 - (length + (64 - 56)) % 64 + $m.= str_repeat(chr(0), 64 - (($length + 8) & 0x3F)); + $m[$length] = chr(0x80); + // we don't support hashing strings 512MB long + $m.= pack('N2', 0, $length << 3); + + // Process the message in successive 512-bit chunks + $chunks = str_split($m, 64); + foreach ($chunks as $chunk) { + $w = array(); + for ($i = 0; $i < 16; $i++) { + extract(unpack('Ntemp', $this->_string_shift($chunk, 4))); + $w[] = $temp; + } + + // Extend the sixteen 32-bit words into sixty-four 32-bit words + for ($i = 16; $i < 64; $i++) { + // @codingStandardsIgnoreStart + $s0 = $this->_rightRotate($w[$i - 15], 7) ^ + $this->_rightRotate($w[$i - 15], 18) ^ + $this->_rightShift( $w[$i - 15], 3); + $s1 = $this->_rightRotate($w[$i - 2], 17) ^ + $this->_rightRotate($w[$i - 2], 19) ^ + $this->_rightShift( $w[$i - 2], 10); + // @codingStandardsIgnoreEnd + $w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1); + } + + // Initialize hash value for this chunk + list($a, $b, $c, $d, $e, $f, $g, $h) = $hash; + + // Main loop + for ($i = 0; $i < 64; $i++) { + $s0 = $this->_rightRotate($a, 2) ^ + $this->_rightRotate($a, 13) ^ + $this->_rightRotate($a, 22); + $maj = ($a & $b) ^ + ($a & $c) ^ + ($b & $c); + $t2 = $this->_add($s0, $maj); + + $s1 = $this->_rightRotate($e, 6) ^ + $this->_rightRotate($e, 11) ^ + $this->_rightRotate($e, 25); + $ch = ($e & $f) ^ + ($this->_not($e) & $g); + $t1 = $this->_add($h, $s1, $ch, $k[$i], $w[$i]); + + $h = $g; + $g = $f; + $f = $e; + $e = $this->_add($d, $t1); + $d = $c; + $c = $b; + $b = $a; + $a = $this->_add($t1, $t2); + } + + // Add this chunk's hash to result so far + $hash = array( + $this->_add($hash[0], $a), + $this->_add($hash[1], $b), + $this->_add($hash[2], $c), + $this->_add($hash[3], $d), + $this->_add($hash[4], $e), + $this->_add($hash[5], $f), + $this->_add($hash[6], $g), + $this->_add($hash[7], $h) + ); + } + + // Produce the final hash value (big-endian) + return pack('N8', $hash[0], $hash[1], $hash[2], $hash[3], $hash[4], $hash[5], $hash[6], $hash[7]); + } + + /** + * Pure-PHP implementation of SHA384 and SHA512 + * + * @access private + * @param string $m + */ + function _sha512($m) + { + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + + static $init384, $init512, $k; + + if (!isset($k)) { + // Initialize variables + $init384 = array( // initial values for SHA384 + 'cbbb9d5dc1059ed8', '629a292a367cd507', '9159015a3070dd17', '152fecd8f70e5939', + '67332667ffc00b31', '8eb44a8768581511', 'db0c2e0d64f98fa7', '47b5481dbefa4fa4' + ); + $init512 = array( // initial values for SHA512 + '6a09e667f3bcc908', 'bb67ae8584caa73b', '3c6ef372fe94f82b', 'a54ff53a5f1d36f1', + '510e527fade682d1', '9b05688c2b3e6c1f', '1f83d9abfb41bd6b', '5be0cd19137e2179' + ); + + for ($i = 0; $i < 8; $i++) { + $init384[$i] = new Math_BigInteger($init384[$i], 16); + $init384[$i]->setPrecision(64); + $init512[$i] = new Math_BigInteger($init512[$i], 16); + $init512[$i]->setPrecision(64); + } + + // Initialize table of round constants + // (first 64 bits of the fractional parts of the cube roots of the first 80 primes 2..409) + $k = array( + '428a2f98d728ae22', '7137449123ef65cd', 'b5c0fbcfec4d3b2f', 'e9b5dba58189dbbc', + '3956c25bf348b538', '59f111f1b605d019', '923f82a4af194f9b', 'ab1c5ed5da6d8118', + 'd807aa98a3030242', '12835b0145706fbe', '243185be4ee4b28c', '550c7dc3d5ffb4e2', + '72be5d74f27b896f', '80deb1fe3b1696b1', '9bdc06a725c71235', 'c19bf174cf692694', + 'e49b69c19ef14ad2', 'efbe4786384f25e3', '0fc19dc68b8cd5b5', '240ca1cc77ac9c65', + '2de92c6f592b0275', '4a7484aa6ea6e483', '5cb0a9dcbd41fbd4', '76f988da831153b5', + '983e5152ee66dfab', 'a831c66d2db43210', 'b00327c898fb213f', 'bf597fc7beef0ee4', + 'c6e00bf33da88fc2', 'd5a79147930aa725', '06ca6351e003826f', '142929670a0e6e70', + '27b70a8546d22ffc', '2e1b21385c26c926', '4d2c6dfc5ac42aed', '53380d139d95b3df', + '650a73548baf63de', '766a0abb3c77b2a8', '81c2c92e47edaee6', '92722c851482353b', + 'a2bfe8a14cf10364', 'a81a664bbc423001', 'c24b8b70d0f89791', 'c76c51a30654be30', + 'd192e819d6ef5218', 'd69906245565a910', 'f40e35855771202a', '106aa07032bbd1b8', + '19a4c116b8d2d0c8', '1e376c085141ab53', '2748774cdf8eeb99', '34b0bcb5e19b48a8', + '391c0cb3c5c95a63', '4ed8aa4ae3418acb', '5b9cca4f7763e373', '682e6ff3d6b2b8a3', + '748f82ee5defb2fc', '78a5636f43172f60', '84c87814a1f0ab72', '8cc702081a6439ec', + '90befffa23631e28', 'a4506cebde82bde9', 'bef9a3f7b2c67915', 'c67178f2e372532b', + 'ca273eceea26619c', 'd186b8c721c0c207', 'eada7dd6cde0eb1e', 'f57d4f7fee6ed178', + '06f067aa72176fba', '0a637dc5a2c898a6', '113f9804bef90dae', '1b710b35131c471b', + '28db77f523047d84', '32caab7b40c72493', '3c9ebe0a15c9bebc', '431d67c49c100d4c', + '4cc5d4becb3e42b6', '597f299cfc657e2a', '5fcb6fab3ad6faec', '6c44198c4a475817' + ); + + for ($i = 0; $i < 80; $i++) { + $k[$i] = new Math_BigInteger($k[$i], 16); + } + } + + $hash = $this->l == 48 ? $init384 : $init512; + + // Pre-processing + $length = strlen($m); + // to round to nearest 112 mod 128, we'll add 128 - (length + (128 - 112)) % 128 + $m.= str_repeat(chr(0), 128 - (($length + 16) & 0x7F)); + $m[$length] = chr(0x80); + // we don't support hashing strings 512MB long + $m.= pack('N4', 0, 0, 0, $length << 3); + + // Process the message in successive 1024-bit chunks + $chunks = str_split($m, 128); + foreach ($chunks as $chunk) { + $w = array(); + for ($i = 0; $i < 16; $i++) { + $temp = new Math_BigInteger($this->_string_shift($chunk, 8), 256); + $temp->setPrecision(64); + $w[] = $temp; + } + + // Extend the sixteen 32-bit words into eighty 32-bit words + for ($i = 16; $i < 80; $i++) { + $temp = array( + $w[$i - 15]->bitwise_rightRotate(1), + $w[$i - 15]->bitwise_rightRotate(8), + $w[$i - 15]->bitwise_rightShift(7) + ); + $s0 = $temp[0]->bitwise_xor($temp[1]); + $s0 = $s0->bitwise_xor($temp[2]); + $temp = array( + $w[$i - 2]->bitwise_rightRotate(19), + $w[$i - 2]->bitwise_rightRotate(61), + $w[$i - 2]->bitwise_rightShift(6) + ); + $s1 = $temp[0]->bitwise_xor($temp[1]); + $s1 = $s1->bitwise_xor($temp[2]); + $w[$i] = $w[$i - 16]->copy(); + $w[$i] = $w[$i]->add($s0); + $w[$i] = $w[$i]->add($w[$i - 7]); + $w[$i] = $w[$i]->add($s1); + } + + // Initialize hash value for this chunk + $a = $hash[0]->copy(); + $b = $hash[1]->copy(); + $c = $hash[2]->copy(); + $d = $hash[3]->copy(); + $e = $hash[4]->copy(); + $f = $hash[5]->copy(); + $g = $hash[6]->copy(); + $h = $hash[7]->copy(); + + // Main loop + for ($i = 0; $i < 80; $i++) { + $temp = array( + $a->bitwise_rightRotate(28), + $a->bitwise_rightRotate(34), + $a->bitwise_rightRotate(39) + ); + $s0 = $temp[0]->bitwise_xor($temp[1]); + $s0 = $s0->bitwise_xor($temp[2]); + $temp = array( + $a->bitwise_and($b), + $a->bitwise_and($c), + $b->bitwise_and($c) + ); + $maj = $temp[0]->bitwise_xor($temp[1]); + $maj = $maj->bitwise_xor($temp[2]); + $t2 = $s0->add($maj); + + $temp = array( + $e->bitwise_rightRotate(14), + $e->bitwise_rightRotate(18), + $e->bitwise_rightRotate(41) + ); + $s1 = $temp[0]->bitwise_xor($temp[1]); + $s1 = $s1->bitwise_xor($temp[2]); + $temp = array( + $e->bitwise_and($f), + $g->bitwise_and($e->bitwise_not()) + ); + $ch = $temp[0]->bitwise_xor($temp[1]); + $t1 = $h->add($s1); + $t1 = $t1->add($ch); + $t1 = $t1->add($k[$i]); + $t1 = $t1->add($w[$i]); + + $h = $g->copy(); + $g = $f->copy(); + $f = $e->copy(); + $e = $d->add($t1); + $d = $c->copy(); + $c = $b->copy(); + $b = $a->copy(); + $a = $t1->add($t2); + } + + // Add this chunk's hash to result so far + $hash = array( + $hash[0]->add($a), + $hash[1]->add($b), + $hash[2]->add($c), + $hash[3]->add($d), + $hash[4]->add($e), + $hash[5]->add($f), + $hash[6]->add($g), + $hash[7]->add($h) + ); + } + + // Produce the final hash value (big-endian) + // (Crypt_Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here) + $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() . + $hash[4]->toBytes() . $hash[5]->toBytes(); + if ($this->l != 48) { + $temp.= $hash[6]->toBytes() . $hash[7]->toBytes(); + } + + return $temp; + } + + /** + * Right Rotate + * + * @access private + * @param int $int + * @param int $amt + * @see self::_sha256() + * @return int + */ + function _rightRotate($int, $amt) + { + $invamt = 32 - $amt; + $mask = (1 << $invamt) - 1; + return (($int << $invamt) & 0xFFFFFFFF) | (($int >> $amt) & $mask); + } + + /** + * Right Shift + * + * @access private + * @param int $int + * @param int $amt + * @see self::_sha256() + * @return int + */ + function _rightShift($int, $amt) + { + $mask = (1 << (32 - $amt)) - 1; + return ($int >> $amt) & $mask; + } + + /** + * Not + * + * @access private + * @param int $int + * @see self::_sha256() + * @return int + */ + function _not($int) + { + return ~$int & 0xFFFFFFFF; + } + + /** + * Add + * + * _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the + * possibility of overflow exists, care has to be taken. Math_BigInteger() could be used but this should be faster. + * + * @param int $... + * @return int + * @see self::_sha256() + * @access private + */ + function _add() + { + static $mod; + if (!isset($mod)) { + $mod = pow(2, 32); + } + + $result = 0; + $arguments = func_get_args(); + foreach ($arguments as $argument) { + $result+= $argument < 0 ? ($argument & 0x7FFFFFFF) + 0x80000000 : $argument; + } + + // PHP 5.3, per http://php.net/releases/5_3_0.php, introduced "more consistent float rounding" + // PHP_OS & "\xDF\xDF\xDF" == strtoupper(substr(PHP_OS, 0, 3)), but a lot faster + if (is_int($result) || version_compare(PHP_VERSION, '5.3.0') >= 0 || (PHP_OS & "\xDF\xDF\xDF") === 'WIN') { + return fmod($result, $mod); + } + + return (fmod($result, 0x80000000) & 0x7FFFFFFF) | + ((fmod(floor($result / 0x80000000), 2) & 1) << 31); + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @return string + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } +} diff --git a/ipaylinks_statement/Crypt/RC2.php b/ipaylinks_statement/Crypt/RC2.php new file mode 100644 index 00000000..97b4550c --- /dev/null +++ b/ipaylinks_statement/Crypt/RC2.php @@ -0,0 +1,761 @@ + + * setKey('abcdefgh'); + * + * $plaintext = str_repeat('a', 1024); + * + * echo $rc2->decrypt($rc2->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_RC2 + * @author Patrick Monnerat + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_RC2_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_RC2_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_RC2_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_RC2_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_RC2_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of RC2. + * + * @package Crypt_RC2 + * @access public + */ +class Crypt_RC2 extends Crypt_Base +{ + /** + * Block Length of the cipher + * + * @see Crypt_Base::block_size + * @var int + * @access private + */ + var $block_size = 8; + + /** + * The Key + * + * @see Crypt_Base::key + * @see self::setKey() + * @var string + * @access private + */ + var $key; + + /** + * The Original (unpadded) Key + * + * @see Crypt_Base::key + * @see self::setKey() + * @see self::encrypt() + * @see self::decrypt() + * @var string + * @access private + */ + var $orig_key; + + /** + * Don't truncate / null pad key + * + * @see Crypt_Base::_clearBuffers() + * @var bool + * @access private + */ + var $skip_key_adjustment = true; + + /** + * Key Length (in bytes) + * + * @see Crypt_RC2::setKeyLength() + * @var int + * @access private + */ + var $key_length = 16; // = 128 bits + + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'RC2'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'rc2'; + + /** + * Optimizing value while CFB-encrypting + * + * @see Crypt_Base::cfb_init_len + * @var int + * @access private + */ + var $cfb_init_len = 500; + + /** + * The key length in bits. + * + * @see self::setKeyLength() + * @see self::setKey() + * @var int + * @access private + * @internal Should be in range [1..1024]. + * @internal Changing this value after setting the key has no effect. + */ + var $default_key_length = 1024; + + /** + * The key length in bits. + * + * @see self::isValidEnine() + * @see self::setKey() + * @var int + * @access private + * @internal Should be in range [1..1024]. + */ + var $current_key_length; + + /** + * The Key Schedule + * + * @see self::_setupKey() + * @var array + * @access private + */ + var $keys; + + /** + * Key expansion randomization table. + * Twice the same 256-value sequence to save a modulus in key expansion. + * + * @see self::setKey() + * @var array + * @access private + */ + var $pitable = array( + 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, + 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D, + 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, + 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2, + 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, + 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32, + 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, + 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82, + 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, + 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC, + 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, + 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26, + 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, + 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03, + 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, + 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7, + 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, + 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A, + 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, + 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC, + 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, + 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39, + 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, + 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31, + 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, + 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9, + 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, + 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9, + 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, + 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E, + 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, + 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD, + 0xD9, 0x78, 0xF9, 0xC4, 0x19, 0xDD, 0xB5, 0xED, + 0x28, 0xE9, 0xFD, 0x79, 0x4A, 0xA0, 0xD8, 0x9D, + 0xC6, 0x7E, 0x37, 0x83, 0x2B, 0x76, 0x53, 0x8E, + 0x62, 0x4C, 0x64, 0x88, 0x44, 0x8B, 0xFB, 0xA2, + 0x17, 0x9A, 0x59, 0xF5, 0x87, 0xB3, 0x4F, 0x13, + 0x61, 0x45, 0x6D, 0x8D, 0x09, 0x81, 0x7D, 0x32, + 0xBD, 0x8F, 0x40, 0xEB, 0x86, 0xB7, 0x7B, 0x0B, + 0xF0, 0x95, 0x21, 0x22, 0x5C, 0x6B, 0x4E, 0x82, + 0x54, 0xD6, 0x65, 0x93, 0xCE, 0x60, 0xB2, 0x1C, + 0x73, 0x56, 0xC0, 0x14, 0xA7, 0x8C, 0xF1, 0xDC, + 0x12, 0x75, 0xCA, 0x1F, 0x3B, 0xBE, 0xE4, 0xD1, + 0x42, 0x3D, 0xD4, 0x30, 0xA3, 0x3C, 0xB6, 0x26, + 0x6F, 0xBF, 0x0E, 0xDA, 0x46, 0x69, 0x07, 0x57, + 0x27, 0xF2, 0x1D, 0x9B, 0xBC, 0x94, 0x43, 0x03, + 0xF8, 0x11, 0xC7, 0xF6, 0x90, 0xEF, 0x3E, 0xE7, + 0x06, 0xC3, 0xD5, 0x2F, 0xC8, 0x66, 0x1E, 0xD7, + 0x08, 0xE8, 0xEA, 0xDE, 0x80, 0x52, 0xEE, 0xF7, + 0x84, 0xAA, 0x72, 0xAC, 0x35, 0x4D, 0x6A, 0x2A, + 0x96, 0x1A, 0xD2, 0x71, 0x5A, 0x15, 0x49, 0x74, + 0x4B, 0x9F, 0xD0, 0x5E, 0x04, 0x18, 0xA4, 0xEC, + 0xC2, 0xE0, 0x41, 0x6E, 0x0F, 0x51, 0xCB, 0xCC, + 0x24, 0x91, 0xAF, 0x50, 0xA1, 0xF4, 0x70, 0x39, + 0x99, 0x7C, 0x3A, 0x85, 0x23, 0xB8, 0xB4, 0x7A, + 0xFC, 0x02, 0x36, 0x5B, 0x25, 0x55, 0x97, 0x31, + 0x2D, 0x5D, 0xFA, 0x98, 0xE3, 0x8A, 0x92, 0xAE, + 0x05, 0xDF, 0x29, 0x10, 0x67, 0x6C, 0xBA, 0xC9, + 0xD3, 0x00, 0xE6, 0xCF, 0xE1, 0x9E, 0xA8, 0x2C, + 0x63, 0x16, 0x01, 0x3F, 0x58, 0xE2, 0x89, 0xA9, + 0x0D, 0x38, 0x34, 0x1B, 0xAB, 0x33, 0xFF, 0xB0, + 0xBB, 0x48, 0x0C, 0x5F, 0xB9, 0xB1, 0xCD, 0x2E, + 0xC5, 0xF3, 0xDB, 0x47, 0xE5, 0xA5, 0x9C, 0x77, + 0x0A, 0xA6, 0x20, 0x68, 0xFE, 0x7F, 0xC1, 0xAD + ); + + /** + * Inverse key expansion randomization table. + * + * @see self::setKey() + * @var array + * @access private + */ + var $invpitable = array( + 0xD1, 0xDA, 0xB9, 0x6F, 0x9C, 0xC8, 0x78, 0x66, + 0x80, 0x2C, 0xF8, 0x37, 0xEA, 0xE0, 0x62, 0xA4, + 0xCB, 0x71, 0x50, 0x27, 0x4B, 0x95, 0xD9, 0x20, + 0x9D, 0x04, 0x91, 0xE3, 0x47, 0x6A, 0x7E, 0x53, + 0xFA, 0x3A, 0x3B, 0xB4, 0xA8, 0xBC, 0x5F, 0x68, + 0x08, 0xCA, 0x8F, 0x14, 0xD7, 0xC0, 0xEF, 0x7B, + 0x5B, 0xBF, 0x2F, 0xE5, 0xE2, 0x8C, 0xBA, 0x12, + 0xE1, 0xAF, 0xB2, 0x54, 0x5D, 0x59, 0x76, 0xDB, + 0x32, 0xA2, 0x58, 0x6E, 0x1C, 0x29, 0x64, 0xF3, + 0xE9, 0x96, 0x0C, 0x98, 0x19, 0x8D, 0x3E, 0x26, + 0xAB, 0xA5, 0x85, 0x16, 0x40, 0xBD, 0x49, 0x67, + 0xDC, 0x22, 0x94, 0xBB, 0x3C, 0xC1, 0x9B, 0xEB, + 0x45, 0x28, 0x18, 0xD8, 0x1A, 0x42, 0x7D, 0xCC, + 0xFB, 0x65, 0x8E, 0x3D, 0xCD, 0x2A, 0xA3, 0x60, + 0xAE, 0x93, 0x8A, 0x48, 0x97, 0x51, 0x15, 0xF7, + 0x01, 0x0B, 0xB7, 0x36, 0xB1, 0x2E, 0x11, 0xFD, + 0x84, 0x2D, 0x3F, 0x13, 0x88, 0xB3, 0x34, 0x24, + 0x1B, 0xDE, 0xC5, 0x1D, 0x4D, 0x2B, 0x17, 0x31, + 0x74, 0xA9, 0xC6, 0x43, 0x6D, 0x39, 0x90, 0xBE, + 0xC3, 0xB0, 0x21, 0x6B, 0xF6, 0x0F, 0xD5, 0x99, + 0x0D, 0xAC, 0x1F, 0x5C, 0x9E, 0xF5, 0xF9, 0x4C, + 0xD6, 0xDF, 0x89, 0xE4, 0x8B, 0xFF, 0xC7, 0xAA, + 0xE7, 0xED, 0x46, 0x25, 0xB6, 0x06, 0x5E, 0x35, + 0xB5, 0xEC, 0xCE, 0xE8, 0x6C, 0x30, 0x55, 0x61, + 0x4A, 0xFE, 0xA0, 0x79, 0x03, 0xF0, 0x10, 0x72, + 0x7C, 0xCF, 0x52, 0xA6, 0xA7, 0xEE, 0x44, 0xD3, + 0x9A, 0x57, 0x92, 0xD0, 0x5A, 0x7A, 0x41, 0x7F, + 0x0E, 0x00, 0x63, 0xF2, 0x4F, 0x05, 0x83, 0xC9, + 0xA1, 0xD4, 0xDD, 0xC4, 0x56, 0xF4, 0xD2, 0x77, + 0x81, 0x09, 0x82, 0x33, 0x9F, 0x07, 0x86, 0x75, + 0x38, 0x4E, 0x69, 0xF1, 0xAD, 0x23, 0x73, 0x87, + 0x70, 0x02, 0xC2, 0x1E, 0xB8, 0x0A, 0xFC, 0xE6 + ); + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::Crypt_Base() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + switch ($engine) { + case CRYPT_ENGINE_OPENSSL: + if ($this->current_key_length != 128 || strlen($this->orig_key) < 16) { + return false; + } + $this->cipher_name_openssl_ecb = 'rc2-ecb'; + $this->cipher_name_openssl = 'rc2-' . $this->_openssl_translate_mode(); + } + + return parent::isValidEngine($engine); + } + + /** + * Sets the key length. + * + * Valid key lengths are 8 to 1024. + * Calling this function after setting the key has no effect until the next + * Crypt_RC2::setKey() call. + * + * @access public + * @param int $length in bits + */ + function setKeyLength($length) + { + if ($length < 8) { + $this->default_key_length = 8; + } elseif ($length > 1024) { + $this->default_key_length = 128; + } else { + $this->default_key_length = $length; + } + $this->current_key_length = $this->default_key_length; + + parent::setKeyLength($length); + } + + /** + * Returns the current key length + * + * @access public + * @return int + */ + function getKeyLength() + { + return $this->current_key_length; + } + + /** + * Sets the key. + * + * Keys can be of any length. RC2, itself, uses 8 to 1024 bit keys (eg. + * strlen($key) <= 128), however, we only use the first 128 bytes if $key + * has more then 128 bytes in it, and set $key to a single null byte if + * it is empty. + * + * If the key is not explicitly set, it'll be assumed to be a single + * null byte. + * + * @see Crypt_Base::setKey() + * @access public + * @param string $key + * @param int $t1 optional Effective key length in bits. + */ + function setKey($key, $t1 = 0) + { + $this->orig_key = $key; + + if ($t1 <= 0) { + $t1 = $this->default_key_length; + } elseif ($t1 > 1024) { + $t1 = 1024; + } + $this->current_key_length = $t1; + // Key byte count should be 1..128. + $key = strlen($key) ? substr($key, 0, 128) : "\x00"; + $t = strlen($key); + + // The mcrypt RC2 implementation only supports effective key length + // of 1024 bits. It is however possible to handle effective key + // lengths in range 1..1024 by expanding the key and applying + // inverse pitable mapping to the first byte before submitting it + // to mcrypt. + + // Key expansion. + $l = array_values(unpack('C*', $key)); + $t8 = ($t1 + 7) >> 3; + $tm = 0xFF >> (8 * $t8 - $t1); + + // Expand key. + $pitable = $this->pitable; + for ($i = $t; $i < 128; $i++) { + $l[$i] = $pitable[$l[$i - 1] + $l[$i - $t]]; + } + $i = 128 - $t8; + $l[$i] = $pitable[$l[$i] & $tm]; + while ($i--) { + $l[$i] = $pitable[$l[$i + 1] ^ $l[$i + $t8]]; + } + + // Prepare the key for mcrypt. + $l[0] = $this->invpitable[$l[0]]; + array_unshift($l, 'C*'); + + parent::setKey(call_user_func_array('pack', $l)); + } + + /** + * Encrypts a message. + * + * Mostly a wrapper for Crypt_Base::encrypt, with some additional OpenSSL handling code + * + * @see self::decrypt() + * @access public + * @param string $plaintext + * @return string $ciphertext + */ + function encrypt($plaintext) + { + if ($this->engine == CRYPT_ENGINE_OPENSSL) { + $temp = $this->key; + $this->key = $this->orig_key; + $result = parent::encrypt($plaintext); + $this->key = $temp; + return $result; + } + + return parent::encrypt($plaintext); + } + + /** + * Decrypts a message. + * + * Mostly a wrapper for Crypt_Base::decrypt, with some additional OpenSSL handling code + * + * @see self::encrypt() + * @access public + * @param string $ciphertext + * @return string $plaintext + */ + function decrypt($ciphertext) + { + if ($this->engine == CRYPT_ENGINE_OPENSSL) { + $temp = $this->key; + $this->key = $this->orig_key; + $result = parent::decrypt($ciphertext); + $this->key = $temp; + return $result; + } + + return parent::decrypt($ciphertext); + } + + /** + * Encrypts a block + * + * @see Crypt_Base::_encryptBlock() + * @see Crypt_Base::encrypt() + * @access private + * @param string $in + * @return string + */ + function _encryptBlock($in) + { + list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in)); + $keys = $this->keys; + $limit = 20; + $actions = array($limit => 44, 44 => 64); + $j = 0; + + for (;;) { + // Mixing round. + $r0 = (($r0 + $keys[$j++] + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1; + $r0 |= $r0 >> 16; + $r1 = (($r1 + $keys[$j++] + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2; + $r1 |= $r1 >> 16; + $r2 = (($r2 + $keys[$j++] + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3; + $r2 |= $r2 >> 16; + $r3 = (($r3 + $keys[$j++] + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5; + $r3 |= $r3 >> 16; + + if ($j === $limit) { + if ($limit === 64) { + break; + } + + // Mashing round. + $r0 += $keys[$r3 & 0x3F]; + $r1 += $keys[$r0 & 0x3F]; + $r2 += $keys[$r1 & 0x3F]; + $r3 += $keys[$r2 & 0x3F]; + $limit = $actions[$limit]; + } + } + + return pack('vvvv', $r0, $r1, $r2, $r3); + } + + /** + * Decrypts a block + * + * @see Crypt_Base::_decryptBlock() + * @see Crypt_Base::decrypt() + * @access private + * @param string $in + * @return string + */ + function _decryptBlock($in) + { + list($r0, $r1, $r2, $r3) = array_values(unpack('v*', $in)); + $keys = $this->keys; + $limit = 44; + $actions = array($limit => 20, 20 => 0); + $j = 64; + + for (;;) { + // R-mixing round. + $r3 = ($r3 | ($r3 << 16)) >> 5; + $r3 = ($r3 - $keys[--$j] - ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF; + $r2 = ($r2 | ($r2 << 16)) >> 3; + $r2 = ($r2 - $keys[--$j] - ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF; + $r1 = ($r1 | ($r1 << 16)) >> 2; + $r1 = ($r1 - $keys[--$j] - ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF; + $r0 = ($r0 | ($r0 << 16)) >> 1; + $r0 = ($r0 - $keys[--$j] - ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF; + + if ($j === $limit) { + if ($limit === 0) { + break; + } + + // R-mashing round. + $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF; + $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF; + $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF; + $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF; + $limit = $actions[$limit]; + } + } + + return pack('vvvv', $r0, $r1, $r2, $r3); + } + + /** + * Setup the CRYPT_ENGINE_MCRYPT $engine + * + * @see Crypt_Base::_setupMcrypt() + * @access private + */ + function _setupMcrypt() + { + if (!isset($this->key)) { + $this->setKey(''); + } + + parent::_setupMcrypt(); + } + + /** + * Creates the key schedule + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + if (!isset($this->key)) { + $this->setKey(''); + } + + // Key has already been expanded in Crypt_RC2::setKey(): + // Only the first value must be altered. + $l = unpack('Ca/Cb/v*', $this->key); + array_unshift($l, $this->pitable[$l['a']] | ($l['b'] << 8)); + unset($l['a']); + unset($l['b']); + $this->keys = $l; + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * @see Crypt_Base::_setupInlineCrypt() + * @access private + */ + function _setupInlineCrypt() + { + $lambda_functions = &Crypt_RC2::_getLambdaFunctions(); + + // The first 10 generated $lambda_functions will use the $keys hardcoded as integers + // for the mixing rounds, for better inline crypt performance [~20% faster]. + // But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10. + // (Currently, for Crypt_RC2, one generated $lambda_function cost on php5.5@32bit ~60kb unfreeable mem and ~100kb on php5.5@64bit) + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); + + // Generation of a unique hash for our generated code + $code_hash = "Crypt_RC2, {$this->mode}"; + if ($gen_hi_opt_code) { + $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); + } + + // Is there a re-usable $lambda_functions in there? + // If not, we have to create it. + if (!isset($lambda_functions[$code_hash])) { + // Init code for both, encrypt and decrypt. + $init_crypt = '$keys = $self->keys;'; + + switch (true) { + case $gen_hi_opt_code: + $keys = $this->keys; + default: + $keys = array(); + foreach ($this->keys as $k => $v) { + $keys[$k] = '$keys[' . $k . ']'; + } + } + + // $in is the current 8 bytes block which has to be en/decrypt + $encrypt_block = $decrypt_block = ' + $in = unpack("v4", $in); + $r0 = $in[1]; + $r1 = $in[2]; + $r2 = $in[3]; + $r3 = $in[4]; + '; + + // Create code for encryption. + $limit = 20; + $actions = array($limit => 44, 44 => 64); + $j = 0; + + for (;;) { + // Mixing round. + $encrypt_block .= ' + $r0 = (($r0 + ' . $keys[$j++] . ' + + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF) << 1; + $r0 |= $r0 >> 16; + $r1 = (($r1 + ' . $keys[$j++] . ' + + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF) << 2; + $r1 |= $r1 >> 16; + $r2 = (($r2 + ' . $keys[$j++] . ' + + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF) << 3; + $r2 |= $r2 >> 16; + $r3 = (($r3 + ' . $keys[$j++] . ' + + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF) << 5; + $r3 |= $r3 >> 16;'; + + if ($j === $limit) { + if ($limit === 64) { + break; + } + + // Mashing round. + $encrypt_block .= ' + $r0 += $keys[$r3 & 0x3F]; + $r1 += $keys[$r0 & 0x3F]; + $r2 += $keys[$r1 & 0x3F]; + $r3 += $keys[$r2 & 0x3F];'; + $limit = $actions[$limit]; + } + } + + $encrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);'; + + // Create code for decryption. + $limit = 44; + $actions = array($limit => 20, 20 => 0); + $j = 64; + + for (;;) { + // R-mixing round. + $decrypt_block .= ' + $r3 = ($r3 | ($r3 << 16)) >> 5; + $r3 = ($r3 - ' . $keys[--$j] . ' - + ((($r0 ^ $r1) & $r2) ^ $r0)) & 0xFFFF; + $r2 = ($r2 | ($r2 << 16)) >> 3; + $r2 = ($r2 - ' . $keys[--$j] . ' - + ((($r3 ^ $r0) & $r1) ^ $r3)) & 0xFFFF; + $r1 = ($r1 | ($r1 << 16)) >> 2; + $r1 = ($r1 - ' . $keys[--$j] . ' - + ((($r2 ^ $r3) & $r0) ^ $r2)) & 0xFFFF; + $r0 = ($r0 | ($r0 << 16)) >> 1; + $r0 = ($r0 - ' . $keys[--$j] . ' - + ((($r1 ^ $r2) & $r3) ^ $r1)) & 0xFFFF;'; + + if ($j === $limit) { + if ($limit === 0) { + break; + } + + // R-mashing round. + $decrypt_block .= ' + $r3 = ($r3 - $keys[$r2 & 0x3F]) & 0xFFFF; + $r2 = ($r2 - $keys[$r1 & 0x3F]) & 0xFFFF; + $r1 = ($r1 - $keys[$r0 & 0x3F]) & 0xFFFF; + $r0 = ($r0 - $keys[$r3 & 0x3F]) & 0xFFFF;'; + $limit = $actions[$limit]; + } + } + + $decrypt_block .= '$in = pack("v4", $r0, $r1, $r2, $r3);'; + + // Creates the inline-crypt function + $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( + array( + 'init_crypt' => $init_crypt, + 'encrypt_block' => $encrypt_block, + 'decrypt_block' => $decrypt_block + ) + ); + } + + // Set the inline-crypt function as callback in: $this->inline_crypt + $this->inline_crypt = $lambda_functions[$code_hash]; + } +} diff --git a/ipaylinks_statement/Crypt/RC4.php b/ipaylinks_statement/Crypt/RC4.php new file mode 100644 index 00000000..8a59518f --- /dev/null +++ b/ipaylinks_statement/Crypt/RC4.php @@ -0,0 +1,366 @@ + + * setKey('abcdefgh'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $rc4->decrypt($rc4->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_RC4 + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access private + * @see self::_crypt() + */ +define('CRYPT_RC4_ENCRYPT', 0); +define('CRYPT_RC4_DECRYPT', 1); +/**#@-*/ + +/** + * Pure-PHP implementation of RC4. + * + * @package Crypt_RC4 + * @author Jim Wigginton + * @access public + */ +class Crypt_RC4 extends Crypt_Base +{ + /** + * Block Length of the cipher + * + * RC4 is a stream cipher + * so we the block_size to 0 + * + * @see Crypt_Base::block_size + * @var int + * @access private + */ + var $block_size = 0; + + /** + * Key Length (in bytes) + * + * @see Crypt_RC4::setKeyLength() + * @var int + * @access private + */ + var $key_length = 128; // = 1024 bits + + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'RC4'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'arcfour'; + + /** + * Holds whether performance-optimized $inline_crypt() can/should be used. + * + * @see Crypt_Base::inline_crypt + * @var mixed + * @access private + */ + var $use_inline_crypt = false; // currently not available + + /** + * The Key + * + * @see self::setKey() + * @var string + * @access private + */ + var $key; + + /** + * The Key Stream for decryption and encryption + * + * @see self::setKey() + * @var array + * @access private + */ + var $stream; + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. + * + * @see Crypt_Base::Crypt_Base() + * @return Crypt_RC4 + * @access public + */ + function __construct() + { + parent::__construct(CRYPT_MODE_STREAM); + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function Crypt_RC4() + { + $this->__construct(); + } + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::Crypt_Base() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + if ($engine == CRYPT_ENGINE_OPENSSL) { + if (version_compare(PHP_VERSION, '5.3.7') >= 0) { + $this->cipher_name_openssl = 'rc4-40'; + } else { + switch (strlen($this->key)) { + case 5: + $this->cipher_name_openssl = 'rc4-40'; + break; + case 8: + $this->cipher_name_openssl = 'rc4-64'; + break; + case 16: + $this->cipher_name_openssl = 'rc4'; + break; + default: + return false; + } + } + } + + return parent::isValidEngine($engine); + } + + /** + * Dummy function. + * + * Some protocols, such as WEP, prepend an "initialization vector" to the key, effectively creating a new key [1]. + * If you need to use an initialization vector in this manner, feel free to prepend it to the key, yourself, before + * calling setKey(). + * + * [1] WEP's initialization vectors (IV's) are used in a somewhat insecure way. Since, in that protocol, + * the IV's are relatively easy to predict, an attack described by + * {@link http://www.drizzle.com/~aboba/IEEE/rc4_ksaproc.pdf Scott Fluhrer, Itsik Mantin, and Adi Shamir} + * can be used to quickly guess at the rest of the key. The following links elaborate: + * + * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} + * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack} + * + * @param string $iv + * @see self::setKey() + * @access public + */ + function setIV($iv) + { + } + + /** + * Sets the key length + * + * Keys can be between 1 and 256 bytes long. + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + if ($length < 8) { + $this->key_length = 1; + } elseif ($length > 2048) { + $this->key_length = 256; + } else { + $this->key_length = $length >> 3; + } + + parent::setKeyLength($length); + } + + /** + * Encrypts a message. + * + * @see Crypt_Base::decrypt() + * @see self::_crypt() + * @access public + * @param string $plaintext + * @return string $ciphertext + */ + function encrypt($plaintext) + { + if ($this->engine != CRYPT_ENGINE_INTERNAL) { + return parent::encrypt($plaintext); + } + return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT); + } + + /** + * Decrypts a message. + * + * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). + * At least if the continuous buffer is disabled. + * + * @see Crypt_Base::encrypt() + * @see self::_crypt() + * @access public + * @param string $ciphertext + * @return string $plaintext + */ + function decrypt($ciphertext) + { + if ($this->engine != CRYPT_ENGINE_INTERNAL) { + return parent::decrypt($ciphertext); + } + return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT); + } + + + /** + * Setup the key (expansion) + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + $key = $this->key; + $keyLength = strlen($key); + $keyStream = range(0, 255); + $j = 0; + for ($i = 0; $i < 256; $i++) { + $j = ($j + $keyStream[$i] + ord($key[$i % $keyLength])) & 255; + $temp = $keyStream[$i]; + $keyStream[$i] = $keyStream[$j]; + $keyStream[$j] = $temp; + } + + $this->stream = array(); + $this->stream[CRYPT_RC4_DECRYPT] = $this->stream[CRYPT_RC4_ENCRYPT] = array( + 0, // index $i + 0, // index $j + $keyStream + ); + } + + /** + * Encrypts or decrypts a message. + * + * @see self::encrypt() + * @see self::decrypt() + * @access private + * @param string $text + * @param int $mode + * @return string $text + */ + function _crypt($text, $mode) + { + if ($this->changed) { + $this->_setup(); + $this->changed = false; + } + + $stream = &$this->stream[$mode]; + if ($this->continuousBuffer) { + $i = &$stream[0]; + $j = &$stream[1]; + $keyStream = &$stream[2]; + } else { + $i = $stream[0]; + $j = $stream[1]; + $keyStream = $stream[2]; + } + + $len = strlen($text); + for ($k = 0; $k < $len; ++$k) { + $i = ($i + 1) & 255; + $ksi = $keyStream[$i]; + $j = ($j + $ksi) & 255; + $ksj = $keyStream[$j]; + + $keyStream[$i] = $ksj; + $keyStream[$j] = $ksi; + $text[$k] = $text[$k] ^ chr($keyStream[($ksj + $ksi) & 255]); + } + + return $text; + } +} diff --git a/ipaylinks_statement/Crypt/RSA.php b/ipaylinks_statement/Crypt/RSA.php new file mode 100644 index 00000000..0f7f8aa2 --- /dev/null +++ b/ipaylinks_statement/Crypt/RSA.php @@ -0,0 +1,3142 @@ + + * createKey()); + * + * $plaintext = 'terrafrost'; + * + * $rsa->loadKey($privatekey); + * $ciphertext = $rsa->encrypt($plaintext); + * + * $rsa->loadKey($publickey); + * echo $rsa->decrypt($ciphertext); + * ?> + * + * + * Here's an example of how to create signatures and verify signatures with this library: + * + * createKey()); + * + * $plaintext = 'terrafrost'; + * + * $rsa->loadKey($privatekey); + * $signature = $rsa->sign($plaintext); + * + * $rsa->loadKey($publickey); + * echo $rsa->verify($plaintext, $signature) ? 'verified' : 'unverified'; + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_RSA + * @author Jim Wigginton + * @copyright 2009 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Random + */ +// the class_exists() will only be called if the crypt_random_string function hasn't been defined and +// will trigger a call to __autoload() if you're wanting to auto-load classes +// call function_exists() a second time to stop the include_once from being called outside +// of the auto loader +if (!function_exists('crypt_random_string')) { + include_once 'Random.php'; +} + +/** + * Include Crypt_Hash + */ +if (!class_exists('Crypt_Hash')) { + include_once 'Hash.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Use {@link http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding Optimal Asymmetric Encryption Padding} + * (OAEP) for encryption / decryption. + * + * Uses sha1 by default. + * + * @see self::setHash() + * @see self::setMGFHash() + */ +define('CRYPT_RSA_ENCRYPTION_OAEP', 1); +/** + * Use PKCS#1 padding. + * + * Although CRYPT_RSA_ENCRYPTION_OAEP offers more security, including PKCS#1 padding is necessary for purposes of backwards + * compatibility with protocols (like SSH-1) written before OAEP's introduction. + */ +define('CRYPT_RSA_ENCRYPTION_PKCS1', 2); +/** + * Do not use any padding + * + * Although this method is not recommended it can none-the-less sometimes be useful if you're trying to decrypt some legacy + * stuff, if you're trying to diagnose why an encrypted message isn't decrypting, etc. + */ +define('CRYPT_RSA_ENCRYPTION_NONE', 3); +/**#@-*/ + +/**#@+ + * @access public + * @see self::sign() + * @see self::verify() + * @see self::setHash() + */ +/** + * Use the Probabilistic Signature Scheme for signing + * + * Uses sha1 by default. + * + * @see self::setSaltLength() + * @see self::setMGFHash() + */ +define('CRYPT_RSA_SIGNATURE_PSS', 1); +/** + * Use the PKCS#1 scheme by default. + * + * Although CRYPT_RSA_SIGNATURE_PSS offers more security, including PKCS#1 signing is necessary for purposes of backwards + * compatibility with protocols (like SSH-2) written before PSS's introduction. + */ +define('CRYPT_RSA_SIGNATURE_PKCS1', 2); +/**#@-*/ + +/**#@+ + * @access private + * @see self::createKey() + */ +/** + * ASN1 Integer + */ +define('CRYPT_RSA_ASN1_INTEGER', 2); +/** + * ASN1 Bit String + */ +define('CRYPT_RSA_ASN1_BITSTRING', 3); +/** + * ASN1 Octet String + */ +define('CRYPT_RSA_ASN1_OCTETSTRING', 4); +/** + * ASN1 Object Identifier + */ +define('CRYPT_RSA_ASN1_OBJECT', 6); +/** + * ASN1 Sequence (with the constucted bit set) + */ +define('CRYPT_RSA_ASN1_SEQUENCE', 48); +/**#@-*/ + +/**#@+ + * @access private + * @see self::Crypt_RSA() + */ +/** + * To use the pure-PHP implementation + */ +define('CRYPT_RSA_MODE_INTERNAL', 1); +/** + * To use the OpenSSL library + * + * (if enabled; otherwise, the internal implementation will be used) + */ +define('CRYPT_RSA_MODE_OPENSSL', 2); +/**#@-*/ + +/** + * Default openSSL configuration file. + */ +define('CRYPT_RSA_OPENSSL_CONFIG', dirname(__FILE__) . '/../openssl.cnf'); + +/**#@+ + * @access public + * @see self::createKey() + * @see self::setPrivateKeyFormat() + */ +/** + * PKCS#1 formatted private key + * + * Used by OpenSSH + */ +define('CRYPT_RSA_PRIVATE_FORMAT_PKCS1', 0); +/** + * PuTTY formatted private key + */ +define('CRYPT_RSA_PRIVATE_FORMAT_PUTTY', 1); +/** + * XML formatted private key + */ +define('CRYPT_RSA_PRIVATE_FORMAT_XML', 2); +/** + * PKCS#8 formatted private key + */ +define('CRYPT_RSA_PRIVATE_FORMAT_PKCS8', 8); +/**#@-*/ + +/**#@+ + * @access public + * @see self::createKey() + * @see self::setPublicKeyFormat() + */ +/** + * Raw public key + * + * An array containing two Math_BigInteger objects. + * + * The exponent can be indexed with any of the following: + * + * 0, e, exponent, publicExponent + * + * The modulus can be indexed with any of the following: + * + * 1, n, modulo, modulus + */ +define('CRYPT_RSA_PUBLIC_FORMAT_RAW', 3); +/** + * PKCS#1 formatted public key (raw) + * + * Used by File/X509.php + * + * Has the following header: + * + * -----BEGIN RSA PUBLIC KEY----- + * + * Analogous to ssh-keygen's pem format (as specified by -m) + */ +define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1', 4); +define('CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW', 4); +/** + * XML formatted public key + */ +define('CRYPT_RSA_PUBLIC_FORMAT_XML', 5); +/** + * OpenSSH formatted public key + * + * Place in $HOME/.ssh/authorized_keys + */ +define('CRYPT_RSA_PUBLIC_FORMAT_OPENSSH', 6); +/** + * PKCS#1 formatted public key (encapsulated) + * + * Used by PHP's openssl_public_encrypt() and openssl's rsautl (when -pubin is set) + * + * Has the following header: + * + * -----BEGIN PUBLIC KEY----- + * + * Analogous to ssh-keygen's pkcs8 format (as specified by -m). Although PKCS8 + * is specific to private keys it's basically creating a DER-encoded wrapper + * for keys. This just extends that same concept to public keys (much like ssh-keygen) + */ +define('CRYPT_RSA_PUBLIC_FORMAT_PKCS8', 7); +/**#@-*/ + +/** + * Pure-PHP PKCS#1 compliant implementation of RSA. + * + * @package Crypt_RSA + * @author Jim Wigginton + * @access public + */ +class Crypt_RSA +{ + /** + * Precomputed Zero + * + * @var Math_BigInteger + * @access private + */ + var $zero; + + /** + * Precomputed One + * + * @var Math_BigInteger + * @access private + */ + var $one; + + /** + * Private Key Format + * + * @var int + * @access private + */ + var $privateKeyFormat = CRYPT_RSA_PRIVATE_FORMAT_PKCS1; + + /** + * Public Key Format + * + * @var int + * @access public + */ + var $publicKeyFormat = CRYPT_RSA_PUBLIC_FORMAT_PKCS8; + + /** + * Modulus (ie. n) + * + * @var Math_BigInteger + * @access private + */ + var $modulus; + + /** + * Modulus length + * + * @var Math_BigInteger + * @access private + */ + var $k; + + /** + * Exponent (ie. e or d) + * + * @var Math_BigInteger + * @access private + */ + var $exponent; + + /** + * Primes for Chinese Remainder Theorem (ie. p and q) + * + * @var array + * @access private + */ + var $primes; + + /** + * Exponents for Chinese Remainder Theorem (ie. dP and dQ) + * + * @var array + * @access private + */ + var $exponents; + + /** + * Coefficients for Chinese Remainder Theorem (ie. qInv) + * + * @var array + * @access private + */ + var $coefficients; + + /** + * Hash name + * + * @var string + * @access private + */ + var $hashName; + + /** + * Hash function + * + * @var Crypt_Hash + * @access private + */ + var $hash; + + /** + * Length of hash function output + * + * @var int + * @access private + */ + var $hLen; + + /** + * Length of salt + * + * @var int + * @access private + */ + var $sLen; + + /** + * Hash function for the Mask Generation Function + * + * @var Crypt_Hash + * @access private + */ + var $mgfHash; + + /** + * Length of MGF hash function output + * + * @var int + * @access private + */ + var $mgfHLen; + + /** + * Encryption mode + * + * @var int + * @access private + */ + var $encryptionMode = CRYPT_RSA_ENCRYPTION_OAEP; + + /** + * Signature mode + * + * @var int + * @access private + */ + var $signatureMode = CRYPT_RSA_SIGNATURE_PSS; + + /** + * Public Exponent + * + * @var mixed + * @access private + */ + var $publicExponent = false; + + /** + * Password + * + * @var string + * @access private + */ + var $password = false; + + /** + * Components + * + * For use with parsing XML formatted keys. PHP's XML Parser functions use utilized - instead of PHP's DOM functions - + * because PHP's XML Parser functions work on PHP4 whereas PHP's DOM functions - although surperior - don't. + * + * @see self::_start_element_handler() + * @var array + * @access private + */ + var $components = array(); + + /** + * Current String + * + * For use with parsing XML formatted keys. + * + * @see self::_character_handler() + * @see self::_stop_element_handler() + * @var mixed + * @access private + */ + var $current; + + /** + * OpenSSL configuration file name. + * + * Set to null to use system configuration file. + * @see self::createKey() + * @var mixed + * @Access public + */ + var $configFile; + + /** + * Public key comment field. + * + * @var string + * @access private + */ + var $comment = 'phpseclib-generated-key'; + + /** + * The constructor + * + * If you want to make use of the openssl extension, you'll need to set the mode manually, yourself. The reason + * Crypt_RSA doesn't do it is because OpenSSL doesn't fail gracefully. openssl_pkey_new(), in particular, requires + * openssl.cnf be present somewhere and, unfortunately, the only real way to find out is too late. + * + * @return Crypt_RSA + * @access public + */ + function __construct() + { + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + + $this->configFile = CRYPT_RSA_OPENSSL_CONFIG; + + if (!defined('CRYPT_RSA_MODE')) { + switch (true) { + // Math/BigInteger's openssl requirements are a little less stringent than Crypt/RSA's. in particular, + // Math/BigInteger doesn't require an openssl.cfg file whereas Crypt/RSA does. so if Math/BigInteger + // can't use OpenSSL it can be pretty trivially assumed, then, that Crypt/RSA can't either. + case defined('MATH_BIGINTEGER_OPENSSL_DISABLE'): + define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + break; + // openssl_pkey_get_details - which is used in the only place Crypt/RSA.php uses OpenSSL - was introduced in PHP 5.2.0 + case !function_exists('openssl_pkey_get_details'): + define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + break; + case extension_loaded('openssl') && version_compare(PHP_VERSION, '4.2.0', '>=') && file_exists($this->configFile): + // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work + ob_start(); + @phpinfo(); + $content = ob_get_contents(); + ob_end_clean(); + + preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); + + $versions = array(); + if (!empty($matches[1])) { + for ($i = 0; $i < count($matches[1]); $i++) { + $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); + + // Remove letter part in OpenSSL version + if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { + $versions[$matches[1][$i]] = $fullVersion; + } else { + $versions[$matches[1][$i]] = $m[0]; + } + } + } + + // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ + switch (true) { + case !isset($versions['Header']): + case !isset($versions['Library']): + case $versions['Header'] == $versions['Library']: + case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0: + define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_OPENSSL); + break; + default: + define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); + } + break; + default: + define('CRYPT_RSA_MODE', CRYPT_RSA_MODE_INTERNAL); + } + } + + $this->zero = new Math_BigInteger(); + $this->one = new Math_BigInteger(1); + + $this->hash = new Crypt_Hash('sha1'); + $this->hLen = $this->hash->getLength(); + $this->hashName = 'sha1'; + $this->mgfHash = new Crypt_Hash('sha1'); + $this->mgfHLen = $this->mgfHash->getLength(); + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function Crypt_RSA() + { + $this->__construct(); + } + + /** + * Create public / private key pair + * + * Returns an array with the following three elements: + * - 'privatekey': The private key. + * - 'publickey': The public key. + * - 'partialkey': A partially computed key (if the execution time exceeded $timeout). + * Will need to be passed back to Crypt_RSA::createKey() as the third parameter for further processing. + * + * @access public + * @param int $bits + * @param int $timeout + * @param Math_BigInteger $p + */ + function createKey($bits = 1024, $timeout = false, $partial = array()) + { + if (!defined('CRYPT_RSA_EXPONENT')) { + // http://en.wikipedia.org/wiki/65537_%28number%29 + define('CRYPT_RSA_EXPONENT', '65537'); + } + // per , this number ought not result in primes smaller + // than 256 bits. as a consequence if the key you're trying to create is 1024 bits and you've set CRYPT_RSA_SMALLEST_PRIME + // to 384 bits then you're going to get a 384 bit prime and a 640 bit prime (384 + 1024 % 384). at least if + // CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_INTERNAL. if CRYPT_RSA_MODE is set to CRYPT_RSA_MODE_OPENSSL then + // CRYPT_RSA_SMALLEST_PRIME is ignored (ie. multi-prime RSA support is more intended as a way to speed up RSA key + // generation when there's a chance neither gmp nor OpenSSL are installed) + if (!defined('CRYPT_RSA_SMALLEST_PRIME')) { + define('CRYPT_RSA_SMALLEST_PRIME', 4096); + } + + // OpenSSL uses 65537 as the exponent and requires RSA keys be 384 bits minimum + if (CRYPT_RSA_MODE == CRYPT_RSA_MODE_OPENSSL && $bits >= 384 && CRYPT_RSA_EXPONENT == 65537) { + $config = array(); + if (isset($this->configFile)) { + $config['config'] = $this->configFile; + } + $rsa = openssl_pkey_new(array('private_key_bits' => $bits) + $config); + openssl_pkey_export($rsa, $privatekey, null, $config); + $publickey = openssl_pkey_get_details($rsa); + $publickey = $publickey['key']; + + $privatekey = call_user_func_array(array($this, '_convertPrivateKey'), array_values($this->_parseKey($privatekey, CRYPT_RSA_PRIVATE_FORMAT_PKCS1))); + $publickey = call_user_func_array(array($this, '_convertPublicKey'), array_values($this->_parseKey($publickey, CRYPT_RSA_PUBLIC_FORMAT_PKCS1))); + + // clear the buffer of error strings stemming from a minimalistic openssl.cnf + while (openssl_error_string() !== false) { + } + + return array( + 'privatekey' => $privatekey, + 'publickey' => $publickey, + 'partialkey' => false + ); + } + + static $e; + if (!isset($e)) { + $e = new Math_BigInteger(CRYPT_RSA_EXPONENT); + } + + extract($this->_generateMinMax($bits)); + $absoluteMin = $min; + $temp = $bits >> 1; // divide by two to see how many bits P and Q would be + if ($temp > CRYPT_RSA_SMALLEST_PRIME) { + $num_primes = floor($bits / CRYPT_RSA_SMALLEST_PRIME); + $temp = CRYPT_RSA_SMALLEST_PRIME; + } else { + $num_primes = 2; + } + extract($this->_generateMinMax($temp + $bits % $temp)); + $finalMax = $max; + extract($this->_generateMinMax($temp)); + + $generator = new Math_BigInteger(); + + $n = $this->one->copy(); + if (!empty($partial)) { + extract(unserialize($partial)); + } else { + $exponents = $coefficients = $primes = array(); + $lcm = array( + 'top' => $this->one->copy(), + 'bottom' => false + ); + } + + $start = time(); + $i0 = count($primes) + 1; + + do { + for ($i = $i0; $i <= $num_primes; $i++) { + if ($timeout !== false) { + $timeout-= time() - $start; + $start = time(); + if ($timeout <= 0) { + return array( + 'privatekey' => '', + 'publickey' => '', + 'partialkey' => serialize(array( + 'primes' => $primes, + 'coefficients' => $coefficients, + 'lcm' => $lcm, + 'exponents' => $exponents + )) + ); + } + } + + if ($i == $num_primes) { + list($min, $temp) = $absoluteMin->divide($n); + if (!$temp->equals($this->zero)) { + $min = $min->add($this->one); // ie. ceil() + } + $primes[$i] = $generator->randomPrime($min, $finalMax, $timeout); + } else { + $primes[$i] = $generator->randomPrime($min, $max, $timeout); + } + + if ($primes[$i] === false) { // if we've reached the timeout + if (count($primes) > 1) { + $partialkey = ''; + } else { + array_pop($primes); + $partialkey = serialize(array( + 'primes' => $primes, + 'coefficients' => $coefficients, + 'lcm' => $lcm, + 'exponents' => $exponents + )); + } + + return array( + 'privatekey' => '', + 'publickey' => '', + 'partialkey' => $partialkey + ); + } + + // the first coefficient is calculated differently from the rest + // ie. instead of being $primes[1]->modInverse($primes[2]), it's $primes[2]->modInverse($primes[1]) + if ($i > 2) { + $coefficients[$i] = $n->modInverse($primes[$i]); + } + + $n = $n->multiply($primes[$i]); + + $temp = $primes[$i]->subtract($this->one); + + // textbook RSA implementations use Euler's totient function instead of the least common multiple. + // see http://en.wikipedia.org/wiki/Euler%27s_totient_function + $lcm['top'] = $lcm['top']->multiply($temp); + $lcm['bottom'] = $lcm['bottom'] === false ? $temp : $lcm['bottom']->gcd($temp); + + $exponents[$i] = $e->modInverse($temp); + } + + list($temp) = $lcm['top']->divide($lcm['bottom']); + $gcd = $temp->gcd($e); + $i0 = 1; + } while (!$gcd->equals($this->one)); + + $d = $e->modInverse($temp); + + $coefficients[2] = $primes[2]->modInverse($primes[1]); + + // from : + // RSAPrivateKey ::= SEQUENCE { + // version Version, + // modulus INTEGER, -- n + // publicExponent INTEGER, -- e + // privateExponent INTEGER, -- d + // prime1 INTEGER, -- p + // prime2 INTEGER, -- q + // exponent1 INTEGER, -- d mod (p-1) + // exponent2 INTEGER, -- d mod (q-1) + // coefficient INTEGER, -- (inverse of q) mod p + // otherPrimeInfos OtherPrimeInfos OPTIONAL + // } + + return array( + 'privatekey' => $this->_convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients), + 'publickey' => $this->_convertPublicKey($n, $e), + 'partialkey' => false + ); + } + + /** + * Convert a private key to the appropriate format. + * + * @access private + * @see self::setPrivateKeyFormat() + * @param string $RSAPrivateKey + * @return string + */ + function _convertPrivateKey($n, $e, $d, $primes, $exponents, $coefficients) + { + $signed = $this->privateKeyFormat != CRYPT_RSA_PRIVATE_FORMAT_XML; + $num_primes = count($primes); + $raw = array( + 'version' => $num_primes == 2 ? chr(0) : chr(1), // two-prime vs. multi + 'modulus' => $n->toBytes($signed), + 'publicExponent' => $e->toBytes($signed), + 'privateExponent' => $d->toBytes($signed), + 'prime1' => $primes[1]->toBytes($signed), + 'prime2' => $primes[2]->toBytes($signed), + 'exponent1' => $exponents[1]->toBytes($signed), + 'exponent2' => $exponents[2]->toBytes($signed), + 'coefficient' => $coefficients[2]->toBytes($signed) + ); + + // if the format in question does not support multi-prime rsa and multi-prime rsa was used, + // call _convertPublicKey() instead. + switch ($this->privateKeyFormat) { + case CRYPT_RSA_PRIVATE_FORMAT_XML: + if ($num_primes != 2) { + return false; + } + return "\r\n" . + ' ' . base64_encode($raw['modulus']) . "\r\n" . + ' ' . base64_encode($raw['publicExponent']) . "\r\n" . + '

' . base64_encode($raw['prime1']) . "

\r\n" . + ' ' . base64_encode($raw['prime2']) . "\r\n" . + ' ' . base64_encode($raw['exponent1']) . "\r\n" . + ' ' . base64_encode($raw['exponent2']) . "\r\n" . + ' ' . base64_encode($raw['coefficient']) . "\r\n" . + ' ' . base64_encode($raw['privateExponent']) . "\r\n" . + '
'; + break; + case CRYPT_RSA_PRIVATE_FORMAT_PUTTY: + if ($num_primes != 2) { + return false; + } + $key = "PuTTY-User-Key-File-2: ssh-rsa\r\nEncryption: "; + $encryption = (!empty($this->password) || is_string($this->password)) ? 'aes256-cbc' : 'none'; + $key.= $encryption; + $key.= "\r\nComment: " . $this->comment . "\r\n"; + $public = pack( + 'Na*Na*Na*', + strlen('ssh-rsa'), + 'ssh-rsa', + strlen($raw['publicExponent']), + $raw['publicExponent'], + strlen($raw['modulus']), + $raw['modulus'] + ); + $source = pack( + 'Na*Na*Na*Na*', + strlen('ssh-rsa'), + 'ssh-rsa', + strlen($encryption), + $encryption, + strlen($this->comment), + $this->comment, + strlen($public), + $public + ); + $public = base64_encode($public); + $key.= "Public-Lines: " . ((strlen($public) + 63) >> 6) . "\r\n"; + $key.= chunk_split($public, 64); + $private = pack( + 'Na*Na*Na*Na*', + strlen($raw['privateExponent']), + $raw['privateExponent'], + strlen($raw['prime1']), + $raw['prime1'], + strlen($raw['prime2']), + $raw['prime2'], + strlen($raw['coefficient']), + $raw['coefficient'] + ); + if (empty($this->password) && !is_string($this->password)) { + $source.= pack('Na*', strlen($private), $private); + $hashkey = 'putty-private-key-file-mac-key'; + } else { + $private.= crypt_random_string(16 - (strlen($private) & 15)); + $source.= pack('Na*', strlen($private), $private); + if (!class_exists('Crypt_AES')) { + include_once 'Crypt/AES.php'; + } + $sequence = 0; + $symkey = ''; + while (strlen($symkey) < 32) { + $temp = pack('Na*', $sequence++, $this->password); + $symkey.= pack('H*', sha1($temp)); + } + $symkey = substr($symkey, 0, 32); + $crypto = new Crypt_AES(); + + $crypto->setKey($symkey); + $crypto->disablePadding(); + $private = $crypto->encrypt($private); + $hashkey = 'putty-private-key-file-mac-key' . $this->password; + } + + $private = base64_encode($private); + $key.= 'Private-Lines: ' . ((strlen($private) + 63) >> 6) . "\r\n"; + $key.= chunk_split($private, 64); + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + $hash = new Crypt_Hash('sha1'); + $hash->setKey(pack('H*', sha1($hashkey))); + $key.= 'Private-MAC: ' . bin2hex($hash->hash($source)) . "\r\n"; + + return $key; + default: // eg. CRYPT_RSA_PRIVATE_FORMAT_PKCS1 + $components = array(); + foreach ($raw as $name => $value) { + $components[$name] = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($value)), $value); + } + + $RSAPrivateKey = implode('', $components); + + if ($num_primes > 2) { + $OtherPrimeInfos = ''; + for ($i = 3; $i <= $num_primes; $i++) { + // OtherPrimeInfos ::= SEQUENCE SIZE(1..MAX) OF OtherPrimeInfo + // + // OtherPrimeInfo ::= SEQUENCE { + // prime INTEGER, -- ri + // exponent INTEGER, -- di + // coefficient INTEGER -- ti + // } + $OtherPrimeInfo = pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($primes[$i]->toBytes(true))), $primes[$i]->toBytes(true)); + $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($exponents[$i]->toBytes(true))), $exponents[$i]->toBytes(true)); + $OtherPrimeInfo.= pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($coefficients[$i]->toBytes(true))), $coefficients[$i]->toBytes(true)); + $OtherPrimeInfos.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfo)), $OtherPrimeInfo); + } + $RSAPrivateKey.= pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($OtherPrimeInfos)), $OtherPrimeInfos); + } + + $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); + + if ($this->privateKeyFormat == CRYPT_RSA_PRIVATE_FORMAT_PKCS8) { + $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $RSAPrivateKey = pack( + 'Ca*a*Ca*a*', + CRYPT_RSA_ASN1_INTEGER, + "\01\00", + $rsaOID, + 4, + $this->_encodeLength(strlen($RSAPrivateKey)), + $RSAPrivateKey + ); + $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); + if (!empty($this->password) || is_string($this->password)) { + $salt = crypt_random_string(8); + $iterationCount = 2048; + + if (!class_exists('Crypt_DES')) { + include_once 'Crypt/DES.php'; + } + $crypto = new Crypt_DES(); + $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); + $RSAPrivateKey = $crypto->encrypt($RSAPrivateKey); + + $parameters = pack( + 'Ca*a*Ca*N', + CRYPT_RSA_ASN1_OCTETSTRING, + $this->_encodeLength(strlen($salt)), + $salt, + CRYPT_RSA_ASN1_INTEGER, + $this->_encodeLength(4), + $iterationCount + ); + $pbeWithMD5AndDES_CBC = "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03"; + + $encryptionAlgorithm = pack( + 'Ca*a*Ca*a*', + CRYPT_RSA_ASN1_OBJECT, + $this->_encodeLength(strlen($pbeWithMD5AndDES_CBC)), + $pbeWithMD5AndDES_CBC, + CRYPT_RSA_ASN1_SEQUENCE, + $this->_encodeLength(strlen($parameters)), + $parameters + ); + + $RSAPrivateKey = pack( + 'Ca*a*Ca*a*', + CRYPT_RSA_ASN1_SEQUENCE, + $this->_encodeLength(strlen($encryptionAlgorithm)), + $encryptionAlgorithm, + CRYPT_RSA_ASN1_OCTETSTRING, + $this->_encodeLength(strlen($RSAPrivateKey)), + $RSAPrivateKey + ); + + $RSAPrivateKey = pack('Ca*a*', CRYPT_RSA_ASN1_SEQUENCE, $this->_encodeLength(strlen($RSAPrivateKey)), $RSAPrivateKey); + + $RSAPrivateKey = "-----BEGIN ENCRYPTED PRIVATE KEY-----\r\n" . + chunk_split(base64_encode($RSAPrivateKey), 64) . + '-----END ENCRYPTED PRIVATE KEY-----'; + } else { + $RSAPrivateKey = "-----BEGIN PRIVATE KEY-----\r\n" . + chunk_split(base64_encode($RSAPrivateKey), 64) . + '-----END PRIVATE KEY-----'; + } + return $RSAPrivateKey; + } + + if (!empty($this->password) || is_string($this->password)) { + $iv = crypt_random_string(8); + $symkey = pack('H*', md5($this->password . $iv)); // symkey is short for symmetric key + $symkey.= substr(pack('H*', md5($symkey . $this->password . $iv)), 0, 8); + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $des = new Crypt_TripleDES(); + $des->setKey($symkey); + $des->setIV($iv); + $iv = strtoupper(bin2hex($iv)); + $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . + "Proc-Type: 4,ENCRYPTED\r\n" . + "DEK-Info: DES-EDE3-CBC,$iv\r\n" . + "\r\n" . + chunk_split(base64_encode($des->encrypt($RSAPrivateKey)), 64) . + '-----END RSA PRIVATE KEY-----'; + } else { + $RSAPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\r\n" . + chunk_split(base64_encode($RSAPrivateKey), 64) . + '-----END RSA PRIVATE KEY-----'; + } + + return $RSAPrivateKey; + } + } + + /** + * Convert a public key to the appropriate format + * + * @access private + * @see self::setPublicKeyFormat() + * @param string $RSAPrivateKey + * @return string + */ + function _convertPublicKey($n, $e) + { + $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML; + + $modulus = $n->toBytes($signed); + $publicExponent = $e->toBytes($signed); + + switch ($this->publicKeyFormat) { + case CRYPT_RSA_PUBLIC_FORMAT_RAW: + return array('e' => $e->copy(), 'n' => $n->copy()); + case CRYPT_RSA_PUBLIC_FORMAT_XML: + return "\r\n" . + ' ' . base64_encode($modulus) . "\r\n" . + ' ' . base64_encode($publicExponent) . "\r\n" . + ''; + break; + case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: + // from : + // string "ssh-rsa" + // mpint e + // mpint n + $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); + $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment; + + return $RSAPublicKey; + default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1 + // from : + // RSAPublicKey ::= SEQUENCE { + // modulus INTEGER, -- n + // publicExponent INTEGER -- e + // } + $components = array( + 'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus), + 'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent) + ); + + $RSAPublicKey = pack( + 'Ca*a*a*', + CRYPT_RSA_ASN1_SEQUENCE, + $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])), + $components['modulus'], + $components['publicExponent'] + ); + + if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) { + $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" . + chunk_split(base64_encode($RSAPublicKey), 64) . + '-----END RSA PUBLIC KEY-----'; + } else { + // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption. + $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $RSAPublicKey = chr(0) . $RSAPublicKey; + $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey; + + $RSAPublicKey = pack( + 'Ca*a*', + CRYPT_RSA_ASN1_SEQUENCE, + $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)), + $rsaOID . $RSAPublicKey + ); + + $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . + chunk_split(base64_encode($RSAPublicKey), 64) . + '-----END PUBLIC KEY-----'; + } + + return $RSAPublicKey; + } + } + + /** + * Break a public or private key down into its constituant components + * + * @access private + * @see self::_convertPublicKey() + * @see self::_convertPrivateKey() + * @param string $key + * @param int $type + * @return array + */ + function _parseKey($key, $type) + { + if ($type != CRYPT_RSA_PUBLIC_FORMAT_RAW && !is_string($key)) { + return false; + } + + switch ($type) { + case CRYPT_RSA_PUBLIC_FORMAT_RAW: + if (!is_array($key)) { + return false; + } + $components = array(); + switch (true) { + case isset($key['e']): + $components['publicExponent'] = $key['e']->copy(); + break; + case isset($key['exponent']): + $components['publicExponent'] = $key['exponent']->copy(); + break; + case isset($key['publicExponent']): + $components['publicExponent'] = $key['publicExponent']->copy(); + break; + case isset($key[0]): + $components['publicExponent'] = $key[0]->copy(); + } + switch (true) { + case isset($key['n']): + $components['modulus'] = $key['n']->copy(); + break; + case isset($key['modulo']): + $components['modulus'] = $key['modulo']->copy(); + break; + case isset($key['modulus']): + $components['modulus'] = $key['modulus']->copy(); + break; + case isset($key[1]): + $components['modulus'] = $key[1]->copy(); + } + return isset($components['modulus']) && isset($components['publicExponent']) ? $components : false; + case CRYPT_RSA_PRIVATE_FORMAT_PKCS1: + case CRYPT_RSA_PRIVATE_FORMAT_PKCS8: + case CRYPT_RSA_PUBLIC_FORMAT_PKCS1: + /* Although PKCS#1 proposes a format that public and private keys can use, encrypting them is + "outside the scope" of PKCS#1. PKCS#1 then refers you to PKCS#12 and PKCS#15 if you're wanting to + protect private keys, however, that's not what OpenSSL* does. OpenSSL protects private keys by adding + two new "fields" to the key - DEK-Info and Proc-Type. These fields are discussed here: + + http://tools.ietf.org/html/rfc1421#section-4.6.1.1 + http://tools.ietf.org/html/rfc1421#section-4.6.1.3 + + DES-EDE3-CBC as an algorithm, however, is not discussed anywhere, near as I can tell. + DES-CBC and DES-EDE are discussed in RFC1423, however, DES-EDE3-CBC isn't, nor is its key derivation + function. As is, the definitive authority on this encoding scheme isn't the IETF but rather OpenSSL's + own implementation. ie. the implementation *is* the standard and any bugs that may exist in that + implementation are part of the standard, as well. + + * OpenSSL is the de facto standard. It's utilized by OpenSSH and other projects */ + if (preg_match('#DEK-Info: (.+),(.+)#', $key, $matches)) { + $iv = pack('H*', trim($matches[2])); + $symkey = pack('H*', md5($this->password . substr($iv, 0, 8))); // symkey is short for symmetric key + $symkey.= pack('H*', md5($symkey . $this->password . substr($iv, 0, 8))); + // remove the Proc-Type / DEK-Info sections as they're no longer needed + $key = preg_replace('#^(?:Proc-Type|DEK-Info): .*#m', '', $key); + $ciphertext = $this->_extractBER($key); + if ($ciphertext === false) { + $ciphertext = $key; + } + switch ($matches[1]) { + case 'AES-256-CBC': + if (!class_exists('Crypt_AES')) { + include_once 'Crypt/AES.php'; + } + $crypto = new Crypt_AES(); + break; + case 'AES-128-CBC': + if (!class_exists('Crypt_AES')) { + include_once 'Crypt/AES.php'; + } + $symkey = substr($symkey, 0, 16); + $crypto = new Crypt_AES(); + break; + case 'DES-EDE3-CFB': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CFB); + break; + case 'DES-EDE3-CBC': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $symkey = substr($symkey, 0, 24); + $crypto = new Crypt_TripleDES(); + break; + case 'DES-CBC': + if (!class_exists('Crypt_DES')) { + include_once 'Crypt/DES.php'; + } + $crypto = new Crypt_DES(); + break; + default: + return false; + } + $crypto->setKey($symkey); + $crypto->setIV($iv); + $decoded = $crypto->decrypt($ciphertext); + } else { + $decoded = $this->_extractBER($key); + } + + if ($decoded !== false) { + $key = $decoded; + } + + $components = array(); + + if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { + return false; + } + if ($this->_decodeLength($key) != strlen($key)) { + return false; + } + + $tag = ord($this->_string_shift($key)); + /* intended for keys for which OpenSSL's asn1parse returns the following: + + 0:d=0 hl=4 l= 631 cons: SEQUENCE + 4:d=1 hl=2 l= 1 prim: INTEGER :00 + 7:d=1 hl=2 l= 13 cons: SEQUENCE + 9:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption + 20:d=2 hl=2 l= 0 prim: NULL + 22:d=1 hl=4 l= 609 prim: OCTET STRING + + ie. PKCS8 keys*/ + + if ($tag == CRYPT_RSA_ASN1_INTEGER && substr($key, 0, 3) == "\x01\x00\x30") { + $this->_string_shift($key, 3); + $tag = CRYPT_RSA_ASN1_SEQUENCE; + } + + if ($tag == CRYPT_RSA_ASN1_SEQUENCE) { + $temp = $this->_string_shift($key, $this->_decodeLength($key)); + if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_OBJECT) { + return false; + } + $length = $this->_decodeLength($temp); + switch ($this->_string_shift($temp, $length)) { + case "\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01": // rsaEncryption + break; + case "\x2a\x86\x48\x86\xf7\x0d\x01\x05\x03": // pbeWithMD5AndDES-CBC + /* + PBEParameter ::= SEQUENCE { + salt OCTET STRING (SIZE(8)), + iterationCount INTEGER } + */ + if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_SEQUENCE) { + return false; + } + if ($this->_decodeLength($temp) != strlen($temp)) { + return false; + } + $this->_string_shift($temp); // assume it's an octet string + $salt = $this->_string_shift($temp, $this->_decodeLength($temp)); + if (ord($this->_string_shift($temp)) != CRYPT_RSA_ASN1_INTEGER) { + return false; + } + $this->_decodeLength($temp); + list(, $iterationCount) = unpack('N', str_pad($temp, 4, chr(0), STR_PAD_LEFT)); + $this->_string_shift($key); // assume it's an octet string + $length = $this->_decodeLength($key); + if (strlen($key) != $length) { + return false; + } + + if (!class_exists('Crypt_DES')) { + include_once 'Crypt/DES.php'; + } + $crypto = new Crypt_DES(); + $crypto->setPassword($this->password, 'pbkdf1', 'md5', $salt, $iterationCount); + $key = $crypto->decrypt($key); + if ($key === false) { + return false; + } + return $this->_parseKey($key, CRYPT_RSA_PRIVATE_FORMAT_PKCS1); + default: + return false; + } + /* intended for keys for which OpenSSL's asn1parse returns the following: + + 0:d=0 hl=4 l= 290 cons: SEQUENCE + 4:d=1 hl=2 l= 13 cons: SEQUENCE + 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption + 17:d=2 hl=2 l= 0 prim: NULL + 19:d=1 hl=4 l= 271 prim: BIT STRING */ + $tag = ord($this->_string_shift($key)); // skip over the BIT STRING / OCTET STRING tag + $this->_decodeLength($key); // skip over the BIT STRING / OCTET STRING length + // "The initial octet shall encode, as an unsigned binary integer wtih bit 1 as the least significant bit, the number of + // unused bits in the final subsequent octet. The number shall be in the range zero to seven." + // -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf (section 8.6.2.2) + if ($tag == CRYPT_RSA_ASN1_BITSTRING) { + $this->_string_shift($key); + } + if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { + return false; + } + if ($this->_decodeLength($key) != strlen($key)) { + return false; + } + $tag = ord($this->_string_shift($key)); + } + if ($tag != CRYPT_RSA_ASN1_INTEGER) { + return false; + } + + $length = $this->_decodeLength($key); + $temp = $this->_string_shift($key, $length); + if (strlen($temp) != 1 || ord($temp) > 2) { + $components['modulus'] = new Math_BigInteger($temp, 256); + $this->_string_shift($key); // skip over CRYPT_RSA_ASN1_INTEGER + $length = $this->_decodeLength($key); + $components[$type == CRYPT_RSA_PUBLIC_FORMAT_PKCS1 ? 'publicExponent' : 'privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); + + return $components; + } + if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_INTEGER) { + return false; + } + $length = $this->_decodeLength($key); + $components['modulus'] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['publicExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['privateExponent'] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256)); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['exponents'] = array(1 => new Math_BigInteger($this->_string_shift($key, $length), 256)); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($key, $length), 256)); + + if (!empty($key)) { + if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { + return false; + } + $this->_decodeLength($key); + while (!empty($key)) { + if (ord($this->_string_shift($key)) != CRYPT_RSA_ASN1_SEQUENCE) { + return false; + } + $this->_decodeLength($key); + $key = substr($key, 1); + $length = $this->_decodeLength($key); + $components['primes'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['exponents'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); + $this->_string_shift($key); + $length = $this->_decodeLength($key); + $components['coefficients'][] = new Math_BigInteger($this->_string_shift($key, $length), 256); + } + } + + return $components; + case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: + $parts = explode(' ', $key, 3); + + $key = isset($parts[1]) ? base64_decode($parts[1]) : false; + if ($key === false) { + return false; + } + + $comment = isset($parts[2]) ? $parts[2] : false; + + $cleanup = substr($key, 0, 11) == "\0\0\0\7ssh-rsa"; + + if (strlen($key) <= 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($key, 4))); + $publicExponent = new Math_BigInteger($this->_string_shift($key, $length), -256); + if (strlen($key) <= 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($key, 4))); + $modulus = new Math_BigInteger($this->_string_shift($key, $length), -256); + + if ($cleanup && strlen($key)) { + if (strlen($key) <= 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($key, 4))); + $realModulus = new Math_BigInteger($this->_string_shift($key, $length), -256); + return strlen($key) ? false : array( + 'modulus' => $realModulus, + 'publicExponent' => $modulus, + 'comment' => $comment + ); + } else { + return strlen($key) ? false : array( + 'modulus' => $modulus, + 'publicExponent' => $publicExponent, + 'comment' => $comment + ); + } + // http://www.w3.org/TR/xmldsig-core/#sec-RSAKeyValue + // http://en.wikipedia.org/wiki/XML_Signature + case CRYPT_RSA_PRIVATE_FORMAT_XML: + case CRYPT_RSA_PUBLIC_FORMAT_XML: + $this->components = array(); + + $xml = xml_parser_create('UTF-8'); + xml_set_object($xml, $this); + xml_set_element_handler($xml, '_start_element_handler', '_stop_element_handler'); + xml_set_character_data_handler($xml, '_data_handler'); + // add to account for "dangling" tags like ... that are sometimes added + if (!xml_parse($xml, '' . $key . '')) { + return false; + } + + return isset($this->components['modulus']) && isset($this->components['publicExponent']) ? $this->components : false; + // from PuTTY's SSHPUBK.C + case CRYPT_RSA_PRIVATE_FORMAT_PUTTY: + $components = array(); + $key = preg_split('#\r\n|\r|\n#', $key); + $type = trim(preg_replace('#PuTTY-User-Key-File-2: (.+)#', '$1', $key[0])); + if ($type != 'ssh-rsa') { + return false; + } + $encryption = trim(preg_replace('#Encryption: (.+)#', '$1', $key[1])); + $comment = trim(preg_replace('#Comment: (.+)#', '$1', $key[2])); + + $publicLength = trim(preg_replace('#Public-Lines: (\d+)#', '$1', $key[3])); + $public = base64_decode(implode('', array_map('trim', array_slice($key, 4, $publicLength)))); + $public = substr($public, 11); + extract(unpack('Nlength', $this->_string_shift($public, 4))); + $components['publicExponent'] = new Math_BigInteger($this->_string_shift($public, $length), -256); + extract(unpack('Nlength', $this->_string_shift($public, 4))); + $components['modulus'] = new Math_BigInteger($this->_string_shift($public, $length), -256); + + $privateLength = trim(preg_replace('#Private-Lines: (\d+)#', '$1', $key[$publicLength + 4])); + $private = base64_decode(implode('', array_map('trim', array_slice($key, $publicLength + 5, $privateLength)))); + + switch ($encryption) { + case 'aes256-cbc': + if (!class_exists('Crypt_AES')) { + include_once 'Crypt/AES.php'; + } + $symkey = ''; + $sequence = 0; + while (strlen($symkey) < 32) { + $temp = pack('Na*', $sequence++, $this->password); + $symkey.= pack('H*', sha1($temp)); + } + $symkey = substr($symkey, 0, 32); + $crypto = new Crypt_AES(); + } + + if ($encryption != 'none') { + $crypto->setKey($symkey); + $crypto->disablePadding(); + $private = $crypto->decrypt($private); + if ($private === false) { + return false; + } + } + + extract(unpack('Nlength', $this->_string_shift($private, 4))); + if (strlen($private) < $length) { + return false; + } + $components['privateExponent'] = new Math_BigInteger($this->_string_shift($private, $length), -256); + extract(unpack('Nlength', $this->_string_shift($private, 4))); + if (strlen($private) < $length) { + return false; + } + $components['primes'] = array(1 => new Math_BigInteger($this->_string_shift($private, $length), -256)); + extract(unpack('Nlength', $this->_string_shift($private, 4))); + if (strlen($private) < $length) { + return false; + } + $components['primes'][] = new Math_BigInteger($this->_string_shift($private, $length), -256); + + $temp = $components['primes'][1]->subtract($this->one); + $components['exponents'] = array(1 => $components['publicExponent']->modInverse($temp)); + $temp = $components['primes'][2]->subtract($this->one); + $components['exponents'][] = $components['publicExponent']->modInverse($temp); + + extract(unpack('Nlength', $this->_string_shift($private, 4))); + if (strlen($private) < $length) { + return false; + } + $components['coefficients'] = array(2 => new Math_BigInteger($this->_string_shift($private, $length), -256)); + + return $components; + } + } + + /** + * Returns the key size + * + * More specifically, this returns the size of the modulo in bits. + * + * @access public + * @return int + */ + function getSize() + { + return !isset($this->modulus) ? 0 : strlen($this->modulus->toBits()); + } + + /** + * Start Element Handler + * + * Called by xml_set_element_handler() + * + * @access private + * @param resource $parser + * @param string $name + * @param array $attribs + */ + function _start_element_handler($parser, $name, $attribs) + { + //$name = strtoupper($name); + switch ($name) { + case 'MODULUS': + $this->current = &$this->components['modulus']; + break; + case 'EXPONENT': + $this->current = &$this->components['publicExponent']; + break; + case 'P': + $this->current = &$this->components['primes'][1]; + break; + case 'Q': + $this->current = &$this->components['primes'][2]; + break; + case 'DP': + $this->current = &$this->components['exponents'][1]; + break; + case 'DQ': + $this->current = &$this->components['exponents'][2]; + break; + case 'INVERSEQ': + $this->current = &$this->components['coefficients'][2]; + break; + case 'D': + $this->current = &$this->components['privateExponent']; + } + $this->current = ''; + } + + /** + * Stop Element Handler + * + * Called by xml_set_element_handler() + * + * @access private + * @param resource $parser + * @param string $name + */ + function _stop_element_handler($parser, $name) + { + if (isset($this->current)) { + $this->current = new Math_BigInteger(base64_decode($this->current), 256); + unset($this->current); + } + } + + /** + * Data Handler + * + * Called by xml_set_character_data_handler() + * + * @access private + * @param resource $parser + * @param string $data + */ + function _data_handler($parser, $data) + { + if (!isset($this->current) || is_object($this->current)) { + return; + } + $this->current.= trim($data); + } + + /** + * Loads a public or private key + * + * Returns true on success and false on failure (ie. an incorrect password was provided or the key was malformed) + * + * @access public + * @param string $key + * @param int $type optional + */ + function loadKey($key, $type = false) + { + if (is_object($key) && strtolower(get_class($key)) == 'crypt_rsa') { + $this->privateKeyFormat = $key->privateKeyFormat; + $this->publicKeyFormat = $key->publicKeyFormat; + $this->k = $key->k; + $this->hLen = $key->hLen; + $this->sLen = $key->sLen; + $this->mgfHLen = $key->mgfHLen; + $this->encryptionMode = $key->encryptionMode; + $this->signatureMode = $key->signatureMode; + $this->password = $key->password; + $this->configFile = $key->configFile; + $this->comment = $key->comment; + + if (is_object($key->hash)) { + $this->hash = new Crypt_Hash($key->hash->getHash()); + } + if (is_object($key->mgfHash)) { + $this->mgfHash = new Crypt_Hash($key->mgfHash->getHash()); + } + + if (is_object($key->modulus)) { + $this->modulus = $key->modulus->copy(); + } + if (is_object($key->exponent)) { + $this->exponent = $key->exponent->copy(); + } + if (is_object($key->publicExponent)) { + $this->publicExponent = $key->publicExponent->copy(); + } + + $this->primes = array(); + $this->exponents = array(); + $this->coefficients = array(); + + foreach ($this->primes as $prime) { + $this->primes[] = $prime->copy(); + } + foreach ($this->exponents as $exponent) { + $this->exponents[] = $exponent->copy(); + } + foreach ($this->coefficients as $coefficient) { + $this->coefficients[] = $coefficient->copy(); + } + + return true; + } + + if ($type === false) { + $types = array( + CRYPT_RSA_PUBLIC_FORMAT_RAW, + CRYPT_RSA_PRIVATE_FORMAT_PKCS1, + CRYPT_RSA_PRIVATE_FORMAT_XML, + CRYPT_RSA_PRIVATE_FORMAT_PUTTY, + CRYPT_RSA_PUBLIC_FORMAT_OPENSSH + ); + foreach ($types as $type) { + $components = $this->_parseKey($key, $type); + if ($components !== false) { + break; + } + } + } else { + $components = $this->_parseKey($key, $type); + } + + if ($components === false) { + $this->comment = null; + $this->modulus = null; + $this->k = null; + $this->exponent = null; + $this->primes = null; + $this->exponents = null; + $this->coefficients = null; + $this->publicExponent = null; + + return false; + } + + if (isset($components['comment']) && $components['comment'] !== false) { + $this->comment = $components['comment']; + } + $this->modulus = $components['modulus']; + $this->k = strlen($this->modulus->toBytes()); + $this->exponent = isset($components['privateExponent']) ? $components['privateExponent'] : $components['publicExponent']; + if (isset($components['primes'])) { + $this->primes = $components['primes']; + $this->exponents = $components['exponents']; + $this->coefficients = $components['coefficients']; + $this->publicExponent = $components['publicExponent']; + } else { + $this->primes = array(); + $this->exponents = array(); + $this->coefficients = array(); + $this->publicExponent = false; + } + + switch ($type) { + case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH: + case CRYPT_RSA_PUBLIC_FORMAT_RAW: + $this->setPublicKey(); + break; + case CRYPT_RSA_PRIVATE_FORMAT_PKCS1: + switch (true) { + case strpos($key, '-BEGIN PUBLIC KEY-') !== false: + case strpos($key, '-BEGIN RSA PUBLIC KEY-') !== false: + $this->setPublicKey(); + } + } + + return true; + } + + /** + * Sets the password + * + * Private keys can be encrypted with a password. To unset the password, pass in the empty string or false. + * Or rather, pass in $password such that empty($password) && !is_string($password) is true. + * + * @see self::createKey() + * @see self::loadKey() + * @access public + * @param string $password + */ + function setPassword($password = false) + { + $this->password = $password; + } + + /** + * Defines the public key + * + * Some private key formats define the public exponent and some don't. Those that don't define it are problematic when + * used in certain contexts. For example, in SSH-2, RSA authentication works by sending the public key along with a + * message signed by the private key to the server. The SSH-2 server looks the public key up in an index of public keys + * and if it's present then proceeds to verify the signature. Problem is, if your private key doesn't include the public + * exponent this won't work unless you manually add the public exponent. phpseclib tries to guess if the key being used + * is the public key but in the event that it guesses incorrectly you might still want to explicitly set the key as being + * public. + * + * Do note that when a new key is loaded the index will be cleared. + * + * Returns true on success, false on failure + * + * @see self::getPublicKey() + * @access public + * @param string $key optional + * @param int $type optional + * @return bool + */ + function setPublicKey($key = false, $type = false) + { + // if a public key has already been loaded return false + if (!empty($this->publicExponent)) { + return false; + } + + if ($key === false && !empty($this->modulus)) { + $this->publicExponent = $this->exponent; + return true; + } + + if ($type === false) { + $types = array( + CRYPT_RSA_PUBLIC_FORMAT_RAW, + CRYPT_RSA_PUBLIC_FORMAT_PKCS1, + CRYPT_RSA_PUBLIC_FORMAT_XML, + CRYPT_RSA_PUBLIC_FORMAT_OPENSSH + ); + foreach ($types as $type) { + $components = $this->_parseKey($key, $type); + if ($components !== false) { + break; + } + } + } else { + $components = $this->_parseKey($key, $type); + } + + if ($components === false) { + return false; + } + + if (empty($this->modulus) || !$this->modulus->equals($components['modulus'])) { + $this->modulus = $components['modulus']; + $this->exponent = $this->publicExponent = $components['publicExponent']; + return true; + } + + $this->publicExponent = $components['publicExponent']; + + return true; + } + + /** + * Defines the private key + * + * If phpseclib guessed a private key was a public key and loaded it as such it might be desirable to force + * phpseclib to treat the key as a private key. This function will do that. + * + * Do note that when a new key is loaded the index will be cleared. + * + * Returns true on success, false on failure + * + * @see self::getPublicKey() + * @access public + * @param string $key optional + * @param int $type optional + * @return bool + */ + function setPrivateKey($key = false, $type = false) + { + if ($key === false && !empty($this->publicExponent)) { + $this->publicExponent = false; + return true; + } + + $rsa = new Crypt_RSA(); + if (!$rsa->loadKey($key, $type)) { + return false; + } + $rsa->publicExponent = false; + + // don't overwrite the old key if the new key is invalid + $this->loadKey($rsa); + return true; + } + + /** + * Returns the public key + * + * The public key is only returned under two circumstances - if the private key had the public key embedded within it + * or if the public key was set via setPublicKey(). If the currently loaded key is supposed to be the public key this + * function won't return it since this library, for the most part, doesn't distinguish between public and private keys. + * + * @see self::getPublicKey() + * @access public + * @param string $key + * @param int $type optional + */ + function getPublicKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS8) + { + if (empty($this->modulus) || empty($this->publicExponent)) { + return false; + } + + $oldFormat = $this->publicKeyFormat; + $this->publicKeyFormat = $type; + $temp = $this->_convertPublicKey($this->modulus, $this->publicExponent); + $this->publicKeyFormat = $oldFormat; + return $temp; + } + + /** + * Returns the public key's fingerprint + * + * The public key's fingerprint is returned, which is equivalent to running `ssh-keygen -lf rsa.pub`. If there is + * no public key currently loaded, false is returned. + * Example output (md5): "c1:b1:30:29:d7:b8:de:6c:97:77:10:d7:46:41:63:87" (as specified by RFC 4716) + * + * @access public + * @param string $algorithm The hashing algorithm to be used. Valid options are 'md5' and 'sha256'. False is returned + * for invalid values. + * @return mixed + */ + function getPublicKeyFingerprint($algorithm = 'md5') + { + if (empty($this->modulus) || empty($this->publicExponent)) { + return false; + } + + $modulus = $this->modulus->toBytes(true); + $publicExponent = $this->publicExponent->toBytes(true); + + $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus); + + switch ($algorithm) { + case 'sha256': + $hash = new Crypt_Hash('sha256'); + $base = base64_encode($hash->hash($RSAPublicKey)); + return substr($base, 0, strlen($base) - 1); + case 'md5': + return substr(chunk_split(md5($RSAPublicKey), 2, ':'), 0, -1); + default: + return false; + } + } + + /** + * Returns the private key + * + * The private key is only returned if the currently loaded key contains the constituent prime numbers. + * + * @see self::getPublicKey() + * @access public + * @param string $key + * @param int $type optional + * @return mixed + */ + function getPrivateKey($type = CRYPT_RSA_PUBLIC_FORMAT_PKCS1) + { + if (empty($this->primes)) { + return false; + } + + $oldFormat = $this->privateKeyFormat; + $this->privateKeyFormat = $type; + $temp = $this->_convertPrivateKey($this->modulus, $this->publicExponent, $this->exponent, $this->primes, $this->exponents, $this->coefficients); + $this->privateKeyFormat = $oldFormat; + return $temp; + } + + /** + * Returns a minimalistic private key + * + * Returns the private key without the prime number constituants. Structurally identical to a public key that + * hasn't been set as the public key + * + * @see self::getPrivateKey() + * @access private + * @param string $key + * @param int $type optional + */ + function _getPrivatePublicKey($mode = CRYPT_RSA_PUBLIC_FORMAT_PKCS8) + { + if (empty($this->modulus) || empty($this->exponent)) { + return false; + } + + $oldFormat = $this->publicKeyFormat; + $this->publicKeyFormat = $mode; + $temp = $this->_convertPublicKey($this->modulus, $this->exponent); + $this->publicKeyFormat = $oldFormat; + return $temp; + } + + /** + * __toString() magic method + * + * @access public + * @return string + */ + function __toString() + { + $key = $this->getPrivateKey($this->privateKeyFormat); + if ($key !== false) { + return $key; + } + $key = $this->_getPrivatePublicKey($this->publicKeyFormat); + return $key !== false ? $key : ''; + } + + /** + * __clone() magic method + * + * @access public + * @return Crypt_RSA + */ + function __clone() + { + $key = new Crypt_RSA(); + $key->loadKey($this); + return $key; + } + + /** + * Generates the smallest and largest numbers requiring $bits bits + * + * @access private + * @param int $bits + * @return array + */ + function _generateMinMax($bits) + { + $bytes = $bits >> 3; + $min = str_repeat(chr(0), $bytes); + $max = str_repeat(chr(0xFF), $bytes); + $msb = $bits & 7; + if ($msb) { + $min = chr(1 << ($msb - 1)) . $min; + $max = chr((1 << $msb) - 1) . $max; + } else { + $min[0] = chr(0x80); + } + + return array( + 'min' => new Math_BigInteger($min, 256), + 'max' => new Math_BigInteger($max, 256) + ); + } + + /** + * DER-decode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @access private + * @param string $string + * @return int + */ + function _decodeLength(&$string) + { + $length = ord($this->_string_shift($string)); + if ($length & 0x80) { // definite length, long form + $length&= 0x7F; + $temp = $this->_string_shift($string, $length); + list(, $length) = unpack('N', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4)); + } + return $length; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @access private + * @param int $length + * @return string + */ + function _encodeLength($length) + { + if ($length <= 0x7F) { + return chr($length); + } + + $temp = ltrim(pack('N', $length), chr(0)); + return pack('Ca*', 0x80 | strlen($temp), $temp); + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @return string + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * Determines the private key format + * + * @see self::createKey() + * @access public + * @param int $format + */ + function setPrivateKeyFormat($format) + { + $this->privateKeyFormat = $format; + } + + /** + * Determines the public key format + * + * @see self::createKey() + * @access public + * @param int $format + */ + function setPublicKeyFormat($format) + { + $this->publicKeyFormat = $format; + } + + /** + * Determines which hashing function should be used + * + * Used with signature production / verification and (if the encryption mode is CRYPT_RSA_ENCRYPTION_OAEP) encryption and + * decryption. If $hash isn't supported, sha1 is used. + * + * @access public + * @param string $hash + */ + function setHash($hash) + { + // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. + switch ($hash) { + case 'md2': + case 'md5': + case 'sha1': + case 'sha256': + case 'sha384': + case 'sha512': + $this->hash = new Crypt_Hash($hash); + $this->hashName = $hash; + break; + default: + $this->hash = new Crypt_Hash('sha1'); + $this->hashName = 'sha1'; + } + $this->hLen = $this->hash->getLength(); + } + + /** + * Determines which hashing function should be used for the mask generation function + * + * The mask generation function is used by CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_SIGNATURE_PSS and although it's + * best if Hash and MGFHash are set to the same thing this is not a requirement. + * + * @access public + * @param string $hash + */ + function setMGFHash($hash) + { + // Crypt_Hash supports algorithms that PKCS#1 doesn't support. md5-96 and sha1-96, for example. + switch ($hash) { + case 'md2': + case 'md5': + case 'sha1': + case 'sha256': + case 'sha384': + case 'sha512': + $this->mgfHash = new Crypt_Hash($hash); + break; + default: + $this->mgfHash = new Crypt_Hash('sha1'); + } + $this->mgfHLen = $this->mgfHash->getLength(); + } + + /** + * Determines the salt length + * + * To quote from {@link http://tools.ietf.org/html/rfc3447#page-38 RFC3447#page-38}: + * + * Typical salt lengths in octets are hLen (the length of the output + * of the hash function Hash) and 0. + * + * @access public + * @param int $format + */ + function setSaltLength($sLen) + { + $this->sLen = $sLen; + } + + /** + * Integer-to-Octet-String primitive + * + * See {@link http://tools.ietf.org/html/rfc3447#section-4.1 RFC3447#section-4.1}. + * + * @access private + * @param Math_BigInteger $x + * @param int $xLen + * @return string + */ + function _i2osp($x, $xLen) + { + $x = $x->toBytes(); + if (strlen($x) > $xLen) { + user_error('Integer too large'); + return false; + } + return str_pad($x, $xLen, chr(0), STR_PAD_LEFT); + } + + /** + * Octet-String-to-Integer primitive + * + * See {@link http://tools.ietf.org/html/rfc3447#section-4.2 RFC3447#section-4.2}. + * + * @access private + * @param string $x + * @return Math_BigInteger + */ + function _os2ip($x) + { + return new Math_BigInteger($x, 256); + } + + /** + * Exponentiate with or without Chinese Remainder Theorem + * + * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.2}. + * + * @access private + * @param Math_BigInteger $x + * @return Math_BigInteger + */ + function _exponentiate($x) + { + switch (true) { + case empty($this->primes): + case $this->primes[1]->equals($this->zero): + case empty($this->coefficients): + case $this->coefficients[2]->equals($this->zero): + case empty($this->exponents): + case $this->exponents[1]->equals($this->zero): + return $x->modPow($this->exponent, $this->modulus); + } + + $num_primes = count($this->primes); + + if (defined('CRYPT_RSA_DISABLE_BLINDING')) { + $m_i = array( + 1 => $x->modPow($this->exponents[1], $this->primes[1]), + 2 => $x->modPow($this->exponents[2], $this->primes[2]) + ); + $h = $m_i[1]->subtract($m_i[2]); + $h = $h->multiply($this->coefficients[2]); + list(, $h) = $h->divide($this->primes[1]); + $m = $m_i[2]->add($h->multiply($this->primes[2])); + + $r = $this->primes[1]; + for ($i = 3; $i <= $num_primes; $i++) { + $m_i = $x->modPow($this->exponents[$i], $this->primes[$i]); + + $r = $r->multiply($this->primes[$i - 1]); + + $h = $m_i->subtract($m); + $h = $h->multiply($this->coefficients[$i]); + list(, $h) = $h->divide($this->primes[$i]); + + $m = $m->add($r->multiply($h)); + } + } else { + $smallest = $this->primes[1]; + for ($i = 2; $i <= $num_primes; $i++) { + if ($smallest->compare($this->primes[$i]) > 0) { + $smallest = $this->primes[$i]; + } + } + + $one = new Math_BigInteger(1); + + $r = $one->random($one, $smallest->subtract($one)); + + $m_i = array( + 1 => $this->_blind($x, $r, 1), + 2 => $this->_blind($x, $r, 2) + ); + $h = $m_i[1]->subtract($m_i[2]); + $h = $h->multiply($this->coefficients[2]); + list(, $h) = $h->divide($this->primes[1]); + $m = $m_i[2]->add($h->multiply($this->primes[2])); + + $r = $this->primes[1]; + for ($i = 3; $i <= $num_primes; $i++) { + $m_i = $this->_blind($x, $r, $i); + + $r = $r->multiply($this->primes[$i - 1]); + + $h = $m_i->subtract($m); + $h = $h->multiply($this->coefficients[$i]); + list(, $h) = $h->divide($this->primes[$i]); + + $m = $m->add($r->multiply($h)); + } + } + + return $m; + } + + /** + * Performs RSA Blinding + * + * Protects against timing attacks by employing RSA Blinding. + * Returns $x->modPow($this->exponents[$i], $this->primes[$i]) + * + * @access private + * @param Math_BigInteger $x + * @param Math_BigInteger $r + * @param int $i + * @return Math_BigInteger + */ + function _blind($x, $r, $i) + { + $x = $x->multiply($r->modPow($this->publicExponent, $this->primes[$i])); + $x = $x->modPow($this->exponents[$i], $this->primes[$i]); + + $r = $r->modInverse($this->primes[$i]); + $x = $x->multiply($r); + list(, $x) = $x->divide($this->primes[$i]); + + return $x; + } + + /** + * Performs blinded RSA equality testing + * + * Protects against a particular type of timing attack described. + * + * See {@link http://codahale.com/a-lesson-in-timing-attacks/ A Lesson In Timing Attacks (or, Don't use MessageDigest.isEquals)} + * + * Thanks for the heads up singpolyma! + * + * @access private + * @param string $x + * @param string $y + * @return bool + */ + function _equals($x, $y) + { + if (strlen($x) != strlen($y)) { + return false; + } + + $result = 0; + for ($i = 0; $i < strlen($x); $i++) { + $result |= ord($x[$i]) ^ ord($y[$i]); + } + + return $result == 0; + } + + /** + * RSAEP + * + * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.1 RFC3447#section-5.1.1}. + * + * @access private + * @param Math_BigInteger $m + * @return Math_BigInteger + */ + function _rsaep($m) + { + if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { + user_error('Message representative out of range'); + return false; + } + return $this->_exponentiate($m); + } + + /** + * RSADP + * + * See {@link http://tools.ietf.org/html/rfc3447#section-5.1.2 RFC3447#section-5.1.2}. + * + * @access private + * @param Math_BigInteger $c + * @return Math_BigInteger + */ + function _rsadp($c) + { + if ($c->compare($this->zero) < 0 || $c->compare($this->modulus) > 0) { + user_error('Ciphertext representative out of range'); + return false; + } + return $this->_exponentiate($c); + } + + /** + * RSASP1 + * + * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.1 RFC3447#section-5.2.1}. + * + * @access private + * @param Math_BigInteger $m + * @return Math_BigInteger + */ + function _rsasp1($m) + { + if ($m->compare($this->zero) < 0 || $m->compare($this->modulus) > 0) { + user_error('Message representative out of range'); + return false; + } + return $this->_exponentiate($m); + } + + /** + * RSAVP1 + * + * See {@link http://tools.ietf.org/html/rfc3447#section-5.2.2 RFC3447#section-5.2.2}. + * + * @access private + * @param Math_BigInteger $s + * @return Math_BigInteger + */ + function _rsavp1($s) + { + if ($s->compare($this->zero) < 0 || $s->compare($this->modulus) > 0) { + user_error('Signature representative out of range'); + return false; + } + return $this->_exponentiate($s); + } + + /** + * MGF1 + * + * See {@link http://tools.ietf.org/html/rfc3447#appendix-B.2.1 RFC3447#appendix-B.2.1}. + * + * @access private + * @param string $mgfSeed + * @param int $mgfLen + * @return string + */ + function _mgf1($mgfSeed, $maskLen) + { + // if $maskLen would yield strings larger than 4GB, PKCS#1 suggests a "Mask too long" error be output. + + $t = ''; + $count = ceil($maskLen / $this->mgfHLen); + for ($i = 0; $i < $count; $i++) { + $c = pack('N', $i); + $t.= $this->mgfHash->hash($mgfSeed . $c); + } + + return substr($t, 0, $maskLen); + } + + /** + * RSAES-OAEP-ENCRYPT + * + * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.1 RFC3447#section-7.1.1} and + * {http://en.wikipedia.org/wiki/Optimal_Asymmetric_Encryption_Padding OAES}. + * + * @access private + * @param string $m + * @param string $l + * @return string + */ + function _rsaes_oaep_encrypt($m, $l = '') + { + $mLen = strlen($m); + + // Length checking + + // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error + // be output. + + if ($mLen > $this->k - 2 * $this->hLen - 2) { + user_error('Message too long'); + return false; + } + + // EME-OAEP encoding + + $lHash = $this->hash->hash($l); + $ps = str_repeat(chr(0), $this->k - $mLen - 2 * $this->hLen - 2); + $db = $lHash . $ps . chr(1) . $m; + $seed = crypt_random_string($this->hLen); + $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); + $maskedDB = $db ^ $dbMask; + $seedMask = $this->_mgf1($maskedDB, $this->hLen); + $maskedSeed = $seed ^ $seedMask; + $em = chr(0) . $maskedSeed . $maskedDB; + + // RSA encryption + + $m = $this->_os2ip($em); + $c = $this->_rsaep($m); + $c = $this->_i2osp($c, $this->k); + + // Output the ciphertext C + + return $c; + } + + /** + * RSAES-OAEP-DECRYPT + * + * See {@link http://tools.ietf.org/html/rfc3447#section-7.1.2 RFC3447#section-7.1.2}. The fact that the error + * messages aren't distinguishable from one another hinders debugging, but, to quote from RFC3447#section-7.1.2: + * + * Note. Care must be taken to ensure that an opponent cannot + * distinguish the different error conditions in Step 3.g, whether by + * error message or timing, or, more generally, learn partial + * information about the encoded message EM. Otherwise an opponent may + * be able to obtain useful information about the decryption of the + * ciphertext C, leading to a chosen-ciphertext attack such as the one + * observed by Manger [36]. + * + * As for $l... to quote from {@link http://tools.ietf.org/html/rfc3447#page-17 RFC3447#page-17}: + * + * Both the encryption and the decryption operations of RSAES-OAEP take + * the value of a label L as input. In this version of PKCS #1, L is + * the empty string; other uses of the label are outside the scope of + * this document. + * + * @access private + * @param string $c + * @param string $l + * @return string + */ + function _rsaes_oaep_decrypt($c, $l = '') + { + // Length checking + + // if $l is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error + // be output. + + if (strlen($c) != $this->k || $this->k < 2 * $this->hLen + 2) { + user_error('Decryption error'); + return false; + } + + // RSA decryption + + $c = $this->_os2ip($c); + $m = $this->_rsadp($c); + if ($m === false) { + user_error('Decryption error'); + return false; + } + $em = $this->_i2osp($m, $this->k); + + // EME-OAEP decoding + + $lHash = $this->hash->hash($l); + $y = ord($em[0]); + $maskedSeed = substr($em, 1, $this->hLen); + $maskedDB = substr($em, $this->hLen + 1); + $seedMask = $this->_mgf1($maskedDB, $this->hLen); + $seed = $maskedSeed ^ $seedMask; + $dbMask = $this->_mgf1($seed, $this->k - $this->hLen - 1); + $db = $maskedDB ^ $dbMask; + $lHash2 = substr($db, 0, $this->hLen); + $m = substr($db, $this->hLen); + if (!$this->_equals($lHash, $lHash2)) { + user_error('Decryption error'); + return false; + } + $m = ltrim($m, chr(0)); + if (ord($m[0]) != 1) { + user_error('Decryption error'); + return false; + } + + // Output the message M + + return substr($m, 1); + } + + /** + * Raw Encryption / Decryption + * + * Doesn't use padding and is not recommended. + * + * @access private + * @param string $m + * @return string + */ + function _raw_encrypt($m) + { + $temp = $this->_os2ip($m); + $temp = $this->_rsaep($temp); + return $this->_i2osp($temp, $this->k); + } + + /** + * RSAES-PKCS1-V1_5-ENCRYPT + * + * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.1 RFC3447#section-7.2.1}. + * + * @access private + * @param string $m + * @return string + */ + function _rsaes_pkcs1_v1_5_encrypt($m) + { + $mLen = strlen($m); + + // Length checking + + if ($mLen > $this->k - 11) { + user_error('Message too long'); + return false; + } + + // EME-PKCS1-v1_5 encoding + + $psLen = $this->k - $mLen - 3; + $ps = ''; + while (strlen($ps) != $psLen) { + $temp = crypt_random_string($psLen - strlen($ps)); + $temp = str_replace("\x00", '', $temp); + $ps.= $temp; + } + $type = 2; + // see the comments of _rsaes_pkcs1_v1_5_decrypt() to understand why this is being done + if (defined('CRYPT_RSA_PKCS15_COMPAT') && (!isset($this->publicExponent) || $this->exponent !== $this->publicExponent)) { + $type = 1; + // "The padding string PS shall consist of k-3-||D|| octets. ... for block type 01, they shall have value FF" + $ps = str_repeat("\xFF", $psLen); + } + $em = chr(0) . chr($type) . $ps . chr(0) . $m; + + // RSA encryption + $m = $this->_os2ip($em); + $c = $this->_rsaep($m); + $c = $this->_i2osp($c, $this->k); + + // Output the ciphertext C + + return $c; + } + + /** + * RSAES-PKCS1-V1_5-DECRYPT + * + * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}. + * + * For compatibility purposes, this function departs slightly from the description given in RFC3447. + * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the + * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the + * public key should have the second byte set to 2. In RFC3447 (PKCS#1 v2.1), the second byte is supposed + * to be 2 regardless of which key is used. For compatibility purposes, we'll just check to make sure the + * second byte is 2 or less. If it is, we'll accept the decrypted string as valid. + * + * As a consequence of this, a private key encrypted ciphertext produced with Crypt_RSA may not decrypt + * with a strictly PKCS#1 v1.5 compliant RSA implementation. Public key encrypted ciphertext's should but + * not private key encrypted ciphertext's. + * + * @access private + * @param string $c + * @return string + */ + function _rsaes_pkcs1_v1_5_decrypt($c) + { + // Length checking + + if (strlen($c) != $this->k) { // or if k < 11 + user_error('Decryption error'); + return false; + } + + // RSA decryption + + $c = $this->_os2ip($c); + $m = $this->_rsadp($c); + + if ($m === false) { + user_error('Decryption error'); + return false; + } + $em = $this->_i2osp($m, $this->k); + + // EME-PKCS1-v1_5 decoding + + if (ord($em[0]) != 0 || ord($em[1]) > 2) { + user_error('Decryption error'); + return false; + } + + $ps = substr($em, 2, strpos($em, chr(0), 2) - 2); + $m = substr($em, strlen($ps) + 3); + + if (strlen($ps) < 8) { + user_error('Decryption error'); + return false; + } + + // Output M + + return $m; + } + + /** + * EMSA-PSS-ENCODE + * + * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.1 RFC3447#section-9.1.1}. + * + * @access private + * @param string $m + * @param int $emBits + */ + function _emsa_pss_encode($m, $emBits) + { + // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error + // be output. + + $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8) + $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; + + $mHash = $this->hash->hash($m); + if ($emLen < $this->hLen + $sLen + 2) { + user_error('Encoding error'); + return false; + } + + $salt = crypt_random_string($sLen); + $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; + $h = $this->hash->hash($m2); + $ps = str_repeat(chr(0), $emLen - $sLen - $this->hLen - 2); + $db = $ps . chr(1) . $salt; + $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); + $maskedDB = $db ^ $dbMask; + $maskedDB[0] = ~chr(0xFF << ($emBits & 7)) & $maskedDB[0]; + $em = $maskedDB . $h . chr(0xBC); + + return $em; + } + + /** + * EMSA-PSS-VERIFY + * + * See {@link http://tools.ietf.org/html/rfc3447#section-9.1.2 RFC3447#section-9.1.2}. + * + * @access private + * @param string $m + * @param string $em + * @param int $emBits + * @return string + */ + function _emsa_pss_verify($m, $em, $emBits) + { + // if $m is larger than two million terrabytes and you're using sha1, PKCS#1 suggests a "Label too long" error + // be output. + + $emLen = ($emBits + 1) >> 3; // ie. ceil($emBits / 8); + $sLen = $this->sLen !== null ? $this->sLen : $this->hLen; + + $mHash = $this->hash->hash($m); + if ($emLen < $this->hLen + $sLen + 2) { + return false; + } + + if ($em[strlen($em) - 1] != chr(0xBC)) { + return false; + } + + $maskedDB = substr($em, 0, -$this->hLen - 1); + $h = substr($em, -$this->hLen - 1, $this->hLen); + $temp = chr(0xFF << ($emBits & 7)); + if ((~$maskedDB[0] & $temp) != $temp) { + return false; + } + $dbMask = $this->_mgf1($h, $emLen - $this->hLen - 1); + $db = $maskedDB ^ $dbMask; + $db[0] = ~chr(0xFF << ($emBits & 7)) & $db[0]; + $temp = $emLen - $this->hLen - $sLen - 2; + if (substr($db, 0, $temp) != str_repeat(chr(0), $temp) || ord($db[$temp]) != 1) { + return false; + } + $salt = substr($db, $temp + 1); // should be $sLen long + $m2 = "\0\0\0\0\0\0\0\0" . $mHash . $salt; + $h2 = $this->hash->hash($m2); + return $this->_equals($h, $h2); + } + + /** + * RSASSA-PSS-SIGN + * + * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.1 RFC3447#section-8.1.1}. + * + * @access private + * @param string $m + * @return string + */ + function _rsassa_pss_sign($m) + { + // EMSA-PSS encoding + + $em = $this->_emsa_pss_encode($m, 8 * $this->k - 1); + + // RSA signature + + $m = $this->_os2ip($em); + $s = $this->_rsasp1($m); + $s = $this->_i2osp($s, $this->k); + + // Output the signature S + + return $s; + } + + /** + * RSASSA-PSS-VERIFY + * + * See {@link http://tools.ietf.org/html/rfc3447#section-8.1.2 RFC3447#section-8.1.2}. + * + * @access private + * @param string $m + * @param string $s + * @return string + */ + function _rsassa_pss_verify($m, $s) + { + // Length checking + + if (strlen($s) != $this->k) { + user_error('Invalid signature'); + return false; + } + + // RSA verification + + $modBits = 8 * $this->k; + + $s2 = $this->_os2ip($s); + $m2 = $this->_rsavp1($s2); + if ($m2 === false) { + user_error('Invalid signature'); + return false; + } + $em = $this->_i2osp($m2, $modBits >> 3); + if ($em === false) { + user_error('Invalid signature'); + return false; + } + + // EMSA-PSS verification + + return $this->_emsa_pss_verify($m, $em, $modBits - 1); + } + + /** + * EMSA-PKCS1-V1_5-ENCODE + * + * See {@link http://tools.ietf.org/html/rfc3447#section-9.2 RFC3447#section-9.2}. + * + * @access private + * @param string $m + * @param int $emLen + * @return string + */ + function _emsa_pkcs1_v1_5_encode($m, $emLen) + { + $h = $this->hash->hash($m); + if ($h === false) { + return false; + } + + // see http://tools.ietf.org/html/rfc3447#page-43 + switch ($this->hashName) { + case 'md2': + $t = pack('H*', '3020300c06082a864886f70d020205000410'); + break; + case 'md5': + $t = pack('H*', '3020300c06082a864886f70d020505000410'); + break; + case 'sha1': + $t = pack('H*', '3021300906052b0e03021a05000414'); + break; + case 'sha256': + $t = pack('H*', '3031300d060960864801650304020105000420'); + break; + case 'sha384': + $t = pack('H*', '3041300d060960864801650304020205000430'); + break; + case 'sha512': + $t = pack('H*', '3051300d060960864801650304020305000440'); + } + $t.= $h; + $tLen = strlen($t); + + if ($emLen < $tLen + 11) { + user_error('Intended encoded message length too short'); + return false; + } + + $ps = str_repeat(chr(0xFF), $emLen - $tLen - 3); + + $em = "\0\1$ps\0$t"; + + return $em; + } + + /** + * RSASSA-PKCS1-V1_5-SIGN + * + * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.1 RFC3447#section-8.2.1}. + * + * @access private + * @param string $m + * @return string + */ + function _rsassa_pkcs1_v1_5_sign($m) + { + // EMSA-PKCS1-v1_5 encoding + + $em = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); + if ($em === false) { + user_error('RSA modulus too short'); + return false; + } + + // RSA signature + + $m = $this->_os2ip($em); + $s = $this->_rsasp1($m); + $s = $this->_i2osp($s, $this->k); + + // Output the signature S + + return $s; + } + + /** + * RSASSA-PKCS1-V1_5-VERIFY + * + * See {@link http://tools.ietf.org/html/rfc3447#section-8.2.2 RFC3447#section-8.2.2}. + * + * @access private + * @param string $m + * @return string + */ + function _rsassa_pkcs1_v1_5_verify($m, $s) + { + // Length checking + + if (strlen($s) != $this->k) { + user_error('Invalid signature'); + return false; + } + + // RSA verification + + $s = $this->_os2ip($s); + $m2 = $this->_rsavp1($s); + if ($m2 === false) { + user_error('Invalid signature'); + return false; + } + $em = $this->_i2osp($m2, $this->k); + if ($em === false) { + user_error('Invalid signature'); + return false; + } + + // EMSA-PKCS1-v1_5 encoding + + $em2 = $this->_emsa_pkcs1_v1_5_encode($m, $this->k); + if ($em2 === false) { + user_error('RSA modulus too short'); + return false; + } + + // Compare + return $this->_equals($em, $em2); + } + + /** + * Set Encryption Mode + * + * Valid values include CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1. + * + * @access public + * @param int $mode + */ + function setEncryptionMode($mode) + { + $this->encryptionMode = $mode; + } + + /** + * Set Signature Mode + * + * Valid values include CRYPT_RSA_SIGNATURE_PSS and CRYPT_RSA_SIGNATURE_PKCS1 + * + * @access public + * @param int $mode + */ + function setSignatureMode($mode) + { + $this->signatureMode = $mode; + } + + /** + * Set public key comment. + * + * @access public + * @param string $comment + */ + function setComment($comment) + { + $this->comment = $comment; + } + + /** + * Get public key comment. + * + * @access public + * @return string + */ + function getComment() + { + return $this->comment; + } + + /** + * Encryption + * + * Both CRYPT_RSA_ENCRYPTION_OAEP and CRYPT_RSA_ENCRYPTION_PKCS1 both place limits on how long $plaintext can be. + * If $plaintext exceeds those limits it will be broken up so that it does and the resultant ciphertext's will + * be concatenated together. + * + * @see self::decrypt() + * @access public + * @param string $plaintext + * @return string + */ + function encrypt($plaintext) + { + switch ($this->encryptionMode) { + case CRYPT_RSA_ENCRYPTION_NONE: + $plaintext = str_split($plaintext, $this->k); + $ciphertext = ''; + foreach ($plaintext as $m) { + $ciphertext.= $this->_raw_encrypt($m); + } + return $ciphertext; + case CRYPT_RSA_ENCRYPTION_PKCS1: + $length = $this->k - 11; + if ($length <= 0) { + return false; + } + + $plaintext = str_split($plaintext, $length); + $ciphertext = ''; + foreach ($plaintext as $m) { + $ciphertext.= $this->_rsaes_pkcs1_v1_5_encrypt($m); + } + return $ciphertext; + //case CRYPT_RSA_ENCRYPTION_OAEP: + default: + $length = $this->k - 2 * $this->hLen - 2; + if ($length <= 0) { + return false; + } + + $plaintext = str_split($plaintext, $length); + $ciphertext = ''; + foreach ($plaintext as $m) { + $ciphertext.= $this->_rsaes_oaep_encrypt($m); + } + return $ciphertext; + } + } + + /** + * Decryption + * + * @see self::encrypt() + * @access public + * @param string $plaintext + * @return string + */ + function decrypt($ciphertext) + { + if ($this->k <= 0) { + return false; + } + + $ciphertext = str_split($ciphertext, $this->k); + $ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $this->k, chr(0), STR_PAD_LEFT); + + $plaintext = ''; + + switch ($this->encryptionMode) { + case CRYPT_RSA_ENCRYPTION_NONE: + $decrypt = '_raw_encrypt'; + break; + case CRYPT_RSA_ENCRYPTION_PKCS1: + $decrypt = '_rsaes_pkcs1_v1_5_decrypt'; + break; + //case CRYPT_RSA_ENCRYPTION_OAEP: + default: + $decrypt = '_rsaes_oaep_decrypt'; + } + + foreach ($ciphertext as $c) { + $temp = $this->$decrypt($c); + if ($temp === false) { + return false; + } + $plaintext.= $temp; + } + + return $plaintext; + } + + /** + * Create a signature + * + * @see self::verify() + * @access public + * @param string $message + * @return string + */ + function sign($message) + { + if (empty($this->modulus) || empty($this->exponent)) { + return false; + } + + switch ($this->signatureMode) { + case CRYPT_RSA_SIGNATURE_PKCS1: + return $this->_rsassa_pkcs1_v1_5_sign($message); + //case CRYPT_RSA_SIGNATURE_PSS: + default: + return $this->_rsassa_pss_sign($message); + } + } + + /** + * Verifies a signature + * + * @see self::sign() + * @access public + * @param string $message + * @param string $signature + * @return bool + */ + function verify($message, $signature) + { + if (empty($this->modulus) || empty($this->exponent)) { + return false; + } + + switch ($this->signatureMode) { + case CRYPT_RSA_SIGNATURE_PKCS1: + return $this->_rsassa_pkcs1_v1_5_verify($message, $signature); + //case CRYPT_RSA_SIGNATURE_PSS: + default: + return $this->_rsassa_pss_verify($message, $signature); + } + } + + /** + * Extract raw BER from Base64 encoding + * + * @access private + * @param string $str + * @return string + */ + function _extractBER($str) + { + /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them + * above and beyond the ceritificate. + * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: + * + * Bag Attributes + * localKeyID: 01 00 00 00 + * subject=/O=organization/OU=org unit/CN=common name + * issuer=/O=organization/CN=common name + */ + $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); + // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff + $temp = preg_replace('#-+[^-]+-+#', '', $temp); + // remove new lines + $temp = str_replace(array("\r", "\n", ' '), '', $temp); + $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; + return $temp != false ? $temp : $str; + } +} diff --git a/ipaylinks_statement/Crypt/Random.php b/ipaylinks_statement/Crypt/Random.php new file mode 100644 index 00000000..18034216 --- /dev/null +++ b/ipaylinks_statement/Crypt/Random.php @@ -0,0 +1,334 @@ + + * + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_Random + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +// laravel is a PHP framework that utilizes phpseclib. laravel workbenches may, independently, +// have phpseclib as a requirement as well. if you're developing such a program you may encounter +// a "Cannot redeclare crypt_random_string()" error. +if (!function_exists('crypt_random_string')) { + /** + * "Is Windows" test + * + * @access private + */ + define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'); + + /** + * Generate a random string. + * + * Although microoptimizations are generally discouraged as they impair readability this function is ripe with + * microoptimizations because this function has the potential of being called a huge number of times. + * eg. for RSA key generation. + * + * @param int $length + * @return string + * @access public + */ + function crypt_random_string($length) + { + if (CRYPT_RANDOM_IS_WINDOWS) { + // method 1. prior to PHP 5.3, mcrypt_create_iv() would call rand() on windows + if (extension_loaded('mcrypt') && version_compare(PHP_VERSION, '5.3.0', '>=')) { + return @mcrypt_create_iv($length); + } + // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was, + // to quote , "possible blocking behavior". as of 5.3.4 + // openssl_random_pseudo_bytes and mcrypt_create_iv do the exact same thing on Windows. ie. they both + // call php_win32_get_random_bytes(): + // + // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/openssl/openssl.c#L5008 + // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1392 + // + // php_win32_get_random_bytes() is defined thusly: + // + // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80 + // + // we're calling it, all the same, in the off chance that the mcrypt extension is not available + if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) { + return openssl_random_pseudo_bytes($length); + } + } else { + // method 1. the fastest + if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.0', '>=')) { + return openssl_random_pseudo_bytes($length); + } + // method 2 + static $fp = true; + if ($fp === true) { + // warning's will be output unles the error suppression operator is used. errors such as + // "open_basedir restriction in effect", "Permission denied", "No such file or directory", etc. + $fp = @fopen('/dev/urandom', 'rb'); + } + if ($fp !== true && $fp !== false) { // surprisingly faster than !is_bool() or is_resource() + return fread($fp, $length); + } + // method 3. pretty much does the same thing as method 2 per the following url: + // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/ext/mcrypt/mcrypt.c#L1391 + // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're + // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir + // restrictions or some such + if (extension_loaded('mcrypt')) { + return @mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); + } + } + // at this point we have no choice but to use a pure-PHP CSPRNG + + // cascade entropy across multiple PHP instances by fixing the session and collecting all + // environmental variables, including the previous session data and the current session + // data. + // + // mt_rand seeds itself by looking at the PID and the time, both of which are (relatively) + // easy to guess at. linux uses mouse clicks, keyboard timings, etc, as entropy sources, but + // PHP isn't low level to be able to use those as sources and on a web server there's not likely + // going to be a ton of keyboard or mouse action. web servers do have one thing that we can use + // however, a ton of people visiting the website. obviously you don't want to base your seeding + // soley on parameters a potential attacker sends but (1) not everything in $_SERVER is controlled + // by the user and (2) this isn't just looking at the data sent by the current user - it's based + // on the data sent by all users. one user requests the page and a hash of their info is saved. + // another user visits the page and the serialization of their data is utilized along with the + // server envirnment stuff and a hash of the previous http request data (which itself utilizes + // a hash of the session data before that). certainly an attacker should be assumed to have + // full control over his own http requests. he, however, is not going to have control over + // everyone's http requests. + static $crypto = false, $v; + if ($crypto === false) { + // save old session data + $old_session_id = session_id(); + $old_use_cookies = ini_get('session.use_cookies'); + $old_session_cache_limiter = session_cache_limiter(); + $_OLD_SESSION = isset($_SESSION) ? $_SESSION : false; + if ($old_session_id != '') { + session_write_close(); + } + + session_id(1); + ini_set('session.use_cookies', 0); + session_cache_limiter(''); + session_start(); + + $v = $seed = $_SESSION['seed'] = pack('H*', sha1( + (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') . + (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') . + (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') . + (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') . + phpseclib_safe_serialize($GLOBALS) . + phpseclib_safe_serialize($_SESSION) . + phpseclib_safe_serialize($_OLD_SESSION) + )); + if (!isset($_SESSION['count'])) { + $_SESSION['count'] = 0; + } + $_SESSION['count']++; + + session_write_close(); + + // restore old session data + if ($old_session_id != '') { + session_id($old_session_id); + session_start(); + ini_set('session.use_cookies', $old_use_cookies); + session_cache_limiter($old_session_cache_limiter); + } else { + if ($_OLD_SESSION !== false) { + $_SESSION = $_OLD_SESSION; + unset($_OLD_SESSION); + } else { + unset($_SESSION); + } + } + + // in SSH2 a shared secret and an exchange hash are generated through the key exchange process. + // the IV client to server is the hash of that "nonce" with the letter A and for the encryption key it's the letter C. + // if the hash doesn't produce enough a key or an IV that's long enough concat successive hashes of the + // original hash and the current hash. we'll be emulating that. for more info see the following URL: + // + // http://tools.ietf.org/html/rfc4253#section-7.2 + // + // see the is_string($crypto) part for an example of how to expand the keys + $key = pack('H*', sha1($seed . 'A')); + $iv = pack('H*', sha1($seed . 'C')); + + // ciphers are used as per the nist.gov link below. also, see this link: + // + // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives + switch (true) { + case phpseclib_resolve_include_path('Crypt/AES.php'): + if (!class_exists('Crypt_AES')) { + include_once 'AES.php'; + } + $crypto = new Crypt_AES(CRYPT_AES_MODE_CTR); + break; + case phpseclib_resolve_include_path('Crypt/Twofish.php'): + if (!class_exists('Crypt_Twofish')) { + include_once 'Twofish.php'; + } + $crypto = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR); + break; + case phpseclib_resolve_include_path('Crypt/Blowfish.php'): + if (!class_exists('Crypt_Blowfish')) { + include_once 'Blowfish.php'; + } + $crypto = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR); + break; + case phpseclib_resolve_include_path('Crypt/TripleDES.php'): + if (!class_exists('Crypt_TripleDES')) { + include_once 'TripleDES.php'; + } + $crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR); + break; + case phpseclib_resolve_include_path('Crypt/DES.php'): + if (!class_exists('Crypt_DES')) { + include_once 'DES.php'; + } + $crypto = new Crypt_DES(CRYPT_DES_MODE_CTR); + break; + case phpseclib_resolve_include_path('Crypt/RC4.php'): + if (!class_exists('Crypt_RC4')) { + include_once 'RC4.php'; + } + $crypto = new Crypt_RC4(); + break; + default: + user_error('crypt_random_string requires at least one symmetric cipher be loaded'); + return false; + } + + $crypto->setKey($key); + $crypto->setIV($iv); + $crypto->enableContinuousBuffer(); + } + + //return $crypto->encrypt(str_repeat("\0", $length)); + + // the following is based off of ANSI X9.31: + // + // http://csrc.nist.gov/groups/STM/cavp/documents/rng/931rngext.pdf + // + // OpenSSL uses that same standard for it's random numbers: + // + // http://www.opensource.apple.com/source/OpenSSL/OpenSSL-38/openssl/fips-1.0/rand/fips_rand.c + // (do a search for "ANS X9.31 A.2.4") + $result = ''; + while (strlen($result) < $length) { + $i = $crypto->encrypt(microtime()); // strlen(microtime()) == 21 + $r = $crypto->encrypt($i ^ $v); // strlen($v) == 20 + $v = $crypto->encrypt($r ^ $i); // strlen($r) == 20 + $result.= $r; + } + return substr($result, 0, $length); + } +} + +if (!function_exists('phpseclib_safe_serialize')) { + /** + * Safely serialize variables + * + * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier. + * PHP 5.3 will emit a warning. + * + * @param mixed $arr + * @access public + */ + function phpseclib_safe_serialize(&$arr) + { + if (is_object($arr)) { + return ''; + } + if (!is_array($arr)) { + return serialize($arr); + } + // prevent circular array recursion + if (isset($arr['__phpseclib_marker'])) { + return ''; + } + $safearr = array(); + $arr['__phpseclib_marker'] = true; + foreach (array_keys($arr) as $key) { + // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage + if ($key !== '__phpseclib_marker') { + $safearr[$key] = phpseclib_safe_serialize($arr[$key]); + } + } + unset($arr['__phpseclib_marker']); + return serialize($safearr); + } +} + +if (!function_exists('phpseclib_resolve_include_path')) { + /** + * Resolve filename against the include path. + * + * Wrapper around stream_resolve_include_path() (which was introduced in + * PHP 5.3.2) with fallback implementation for earlier PHP versions. + * + * @param string $filename + * @return string|false + * @access public + */ + function phpseclib_resolve_include_path($filename) + { + if (function_exists('stream_resolve_include_path')) { + return stream_resolve_include_path($filename); + } + + // handle non-relative paths + if (file_exists($filename)) { + return realpath($filename); + } + + $paths = PATH_SEPARATOR == ':' ? + preg_split('#(? + * setKey('abcdefghijklmnop'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $rijndael->decrypt($rijndael->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_Rijndael + * @author Jim Wigginton + * @copyright 2008 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_RIJNDAEL_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_RIJNDAEL_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_RIJNDAEL_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_RIJNDAEL_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_RIJNDAEL_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of Rijndael. + * + * @package Crypt_Rijndael + * @author Jim Wigginton + * @access public + */ +class Crypt_Rijndael extends Crypt_Base +{ + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'RIJNDAEL'; + + /** + * The mcrypt specific name of the cipher + * + * Mcrypt is useable for 128/192/256-bit $block_size/$key_length. For 160/224 not. + * Crypt_Rijndael determines automatically whether mcrypt is useable + * or not for the current $block_size/$key_length. + * In case of, $cipher_name_mcrypt will be set dynamically at run time accordingly. + * + * @see Crypt_Base::cipher_name_mcrypt + * @see Crypt_Base::engine + * @see self::isValidEngine() + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'rijndael-128'; + + /** + * The default salt used by setPassword() + * + * @see Crypt_Base::password_default_salt + * @see Crypt_Base::setPassword() + * @var string + * @access private + */ + var $password_default_salt = 'phpseclib'; + + /** + * The Key Schedule + * + * @see self::_setup() + * @var array + * @access private + */ + var $w; + + /** + * The Inverse Key Schedule + * + * @see self::_setup() + * @var array + * @access private + */ + var $dw; + + /** + * The Block Length divided by 32 + * + * @see self::setBlockLength() + * @var int + * @access private + * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4. Exists in conjunction with $block_size + * because the encryption / decryption / key schedule creation requires this number and not $block_size. We could + * derive this from $block_size or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu + * of that, we'll just precompute it once. + */ + var $Nb = 4; + + /** + * The Key Length (in bytes) + * + * @see self::setKeyLength() + * @var int + * @access private + * @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk + * because the encryption / decryption / key schedule creation requires this number and not $key_length. We could + * derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu + * of that, we'll just precompute it once. + */ + var $key_length = 16; + + /** + * The Key Length divided by 32 + * + * @see self::setKeyLength() + * @var int + * @access private + * @internal The max value is 256 / 32 = 8, the min value is 128 / 32 = 4 + */ + var $Nk = 4; + + /** + * The Number of Rounds + * + * @var int + * @access private + * @internal The max value is 14, the min value is 10. + */ + var $Nr; + + /** + * Shift offsets + * + * @var array + * @access private + */ + var $c; + + /** + * Holds the last used key- and block_size information + * + * @var array + * @access private + */ + var $kl; + + /** + * Sets the key. + * + * Keys can be of any length. Rijndael, itself, requires the use of a key that's between 128-bits and 256-bits long and + * whose length is a multiple of 32. If the key is less than 256-bits and the key length isn't set, we round the length + * up to the closest valid key length, padding $key with null bytes. If the key is more than 256-bits, we trim the + * excess bits. + * + * If the key is not explicitly set, it'll be assumed to be all null bytes. + * + * Note: 160/224-bit keys must explicitly set by setKeyLength(), otherwise they will be round/pad up to 192/256 bits. + * + * @see Crypt_Base:setKey() + * @see self::setKeyLength() + * @access public + * @param string $key + */ + function setKey($key) + { + if (!$this->explicit_key_length) { + $length = strlen($key); + switch (true) { + case $length <= 16: + $this->key_size = 16; + break; + case $length <= 20: + $this->key_size = 20; + break; + case $length <= 24: + $this->key_size = 24; + break; + case $length <= 28: + $this->key_size = 28; + break; + default: + $this->key_size = 32; + } + } + parent::setKey($key); + } + + /** + * Sets the key length + * + * Valid key lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to + * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. + * + * Note: phpseclib extends Rijndael (and AES) for using 160- and 224-bit keys but they are officially not defined + * and the most (if not all) implementations are not able using 160/224-bit keys but round/pad them up to + * 192/256 bits as, for example, mcrypt will do. + * + * That said, if you want be compatible with other Rijndael and AES implementations, + * you should not setKeyLength(160) or setKeyLength(224). + * + * Additional: In case of 160- and 224-bit keys, phpseclib will/can, for that reason, not use + * the mcrypt php extension, even if available. + * This results then in slower encryption. + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + switch (true) { + case $length <= 128: + $this->key_length = 16; + break; + case $length <= 160: + $this->key_length = 20; + break; + case $length <= 192: + $this->key_length = 24; + break; + case $length <= 224: + $this->key_length = 28; + break; + default: + $this->key_length = 32; + } + + parent::setKeyLength($length); + } + + /** + * Sets the block length + * + * Valid block lengths are 128, 160, 192, 224, and 256. If the length is less than 128, it will be rounded up to + * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. + * + * @access public + * @param int $length + */ + function setBlockLength($length) + { + $length >>= 5; + if ($length > 8) { + $length = 8; + } elseif ($length < 4) { + $length = 4; + } + $this->Nb = $length; + $this->block_size = $length << 2; + $this->changed = true; + $this->_setEngine(); + } + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::Crypt_Base() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + switch ($engine) { + case CRYPT_ENGINE_OPENSSL: + if ($this->block_size != 16) { + return false; + } + $this->cipher_name_openssl_ecb = 'aes-' . ($this->key_length << 3) . '-ecb'; + $this->cipher_name_openssl = 'aes-' . ($this->key_length << 3) . '-' . $this->_openssl_translate_mode(); + break; + case CRYPT_ENGINE_MCRYPT: + $this->cipher_name_mcrypt = 'rijndael-' . ($this->block_size << 3); + if ($this->key_length % 8) { // is it a 160/224-bit key? + // mcrypt is not usable for them, only for 128/192/256-bit keys + return false; + } + } + + return parent::isValidEngine($engine); + } + + /** + * Encrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _encryptBlock($in) + { + static $tables; + if (empty($tables)) { + $tables = &$this->_getTables(); + } + $t0 = $tables[0]; + $t1 = $tables[1]; + $t2 = $tables[2]; + $t3 = $tables[3]; + $sbox = $tables[4]; + + $state = array(); + $words = unpack('N*', $in); + + $c = $this->c; + $w = $this->w; + $Nb = $this->Nb; + $Nr = $this->Nr; + + // addRoundKey + $wc = $Nb - 1; + foreach ($words as $word) { + $state[] = $word ^ $w[++$wc]; + } + + // fips-197.pdf#page=19, "Figure 5. Pseudo Code for the Cipher", states that this loop has four components - + // subBytes, shiftRows, mixColumns, and addRoundKey. fips-197.pdf#page=30, "Implementation Suggestions Regarding + // Various Platforms" suggests that performs enhanced implementations are described in Rijndael-ammended.pdf. + // Rijndael-ammended.pdf#page=20, "Implementation aspects / 32-bit processor", discusses such an optimization. + // Unfortunately, the description given there is not quite correct. Per aes.spec.v316.pdf#page=19 [1], + // equation (7.4.7) is supposed to use addition instead of subtraction, so we'll do that here, as well. + + // [1] http://fp.gladman.plus.com/cryptography_technology/rijndael/aes.spec.v316.pdf + $temp = array(); + for ($round = 1; $round < $Nr; ++$round) { + $i = 0; // $c[0] == 0 + $j = $c[1]; + $k = $c[2]; + $l = $c[3]; + + while ($i < $Nb) { + $temp[$i] = $t0[$state[$i] >> 24 & 0x000000FF] ^ + $t1[$state[$j] >> 16 & 0x000000FF] ^ + $t2[$state[$k] >> 8 & 0x000000FF] ^ + $t3[$state[$l] & 0x000000FF] ^ + $w[++$wc]; + ++$i; + $j = ($j + 1) % $Nb; + $k = ($k + 1) % $Nb; + $l = ($l + 1) % $Nb; + } + $state = $temp; + } + + // subWord + for ($i = 0; $i < $Nb; ++$i) { + $state[$i] = $sbox[$state[$i] & 0x000000FF] | + ($sbox[$state[$i] >> 8 & 0x000000FF] << 8) | + ($sbox[$state[$i] >> 16 & 0x000000FF] << 16) | + ($sbox[$state[$i] >> 24 & 0x000000FF] << 24); + } + + // shiftRows + addRoundKey + $i = 0; // $c[0] == 0 + $j = $c[1]; + $k = $c[2]; + $l = $c[3]; + while ($i < $Nb) { + $temp[$i] = ($state[$i] & 0xFF000000) ^ + ($state[$j] & 0x00FF0000) ^ + ($state[$k] & 0x0000FF00) ^ + ($state[$l] & 0x000000FF) ^ + $w[$i]; + ++$i; + $j = ($j + 1) % $Nb; + $k = ($k + 1) % $Nb; + $l = ($l + 1) % $Nb; + } + + switch ($Nb) { + case 8: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]); + case 7: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]); + case 6: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]); + case 5: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]); + default: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]); + } + } + + /** + * Decrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _decryptBlock($in) + { + static $invtables; + if (empty($invtables)) { + $invtables = &$this->_getInvTables(); + } + $dt0 = $invtables[0]; + $dt1 = $invtables[1]; + $dt2 = $invtables[2]; + $dt3 = $invtables[3]; + $isbox = $invtables[4]; + + $state = array(); + $words = unpack('N*', $in); + + $c = $this->c; + $dw = $this->dw; + $Nb = $this->Nb; + $Nr = $this->Nr; + + // addRoundKey + $wc = $Nb - 1; + foreach ($words as $word) { + $state[] = $word ^ $dw[++$wc]; + } + + $temp = array(); + for ($round = $Nr - 1; $round > 0; --$round) { + $i = 0; // $c[0] == 0 + $j = $Nb - $c[1]; + $k = $Nb - $c[2]; + $l = $Nb - $c[3]; + + while ($i < $Nb) { + $temp[$i] = $dt0[$state[$i] >> 24 & 0x000000FF] ^ + $dt1[$state[$j] >> 16 & 0x000000FF] ^ + $dt2[$state[$k] >> 8 & 0x000000FF] ^ + $dt3[$state[$l] & 0x000000FF] ^ + $dw[++$wc]; + ++$i; + $j = ($j + 1) % $Nb; + $k = ($k + 1) % $Nb; + $l = ($l + 1) % $Nb; + } + $state = $temp; + } + + // invShiftRows + invSubWord + addRoundKey + $i = 0; // $c[0] == 0 + $j = $Nb - $c[1]; + $k = $Nb - $c[2]; + $l = $Nb - $c[3]; + + while ($i < $Nb) { + $word = ($state[$i] & 0xFF000000) | + ($state[$j] & 0x00FF0000) | + ($state[$k] & 0x0000FF00) | + ($state[$l] & 0x000000FF); + + $temp[$i] = $dw[$i] ^ ($isbox[$word & 0x000000FF] | + ($isbox[$word >> 8 & 0x000000FF] << 8) | + ($isbox[$word >> 16 & 0x000000FF] << 16) | + ($isbox[$word >> 24 & 0x000000FF] << 24)); + ++$i; + $j = ($j + 1) % $Nb; + $k = ($k + 1) % $Nb; + $l = ($l + 1) % $Nb; + } + + switch ($Nb) { + case 8: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6], $temp[7]); + case 7: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5], $temp[6]); + case 6: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4], $temp[5]); + case 5: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3], $temp[4]); + default: + return pack('N*', $temp[0], $temp[1], $temp[2], $temp[3]); + } + } + + /** + * Setup the key (expansion) + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + // Each number in $rcon is equal to the previous number multiplied by two in Rijndael's finite field. + // See http://en.wikipedia.org/wiki/Finite_field_arithmetic#Multiplicative_inverse + static $rcon = array(0, + 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, + 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, + 0x6C000000, 0xD8000000, 0xAB000000, 0x4D000000, 0x9A000000, + 0x2F000000, 0x5E000000, 0xBC000000, 0x63000000, 0xC6000000, + 0x97000000, 0x35000000, 0x6A000000, 0xD4000000, 0xB3000000, + 0x7D000000, 0xFA000000, 0xEF000000, 0xC5000000, 0x91000000 + ); + + if (isset($this->kl['key']) && $this->key === $this->kl['key'] && $this->key_length === $this->kl['key_length'] && $this->block_size === $this->kl['block_size']) { + // already expanded + return; + } + $this->kl = array('key' => $this->key, 'key_length' => $this->key_length, 'block_size' => $this->block_size); + + $this->Nk = $this->key_length >> 2; + // see Rijndael-ammended.pdf#page=44 + $this->Nr = max($this->Nk, $this->Nb) + 6; + + // shift offsets for Nb = 5, 7 are defined in Rijndael-ammended.pdf#page=44, + // "Table 8: Shift offsets in Shiftrow for the alternative block lengths" + // shift offsets for Nb = 4, 6, 8 are defined in Rijndael-ammended.pdf#page=14, + // "Table 2: Shift offsets for different block lengths" + switch ($this->Nb) { + case 4: + case 5: + case 6: + $this->c = array(0, 1, 2, 3); + break; + case 7: + $this->c = array(0, 1, 2, 4); + break; + case 8: + $this->c = array(0, 1, 3, 4); + } + + $w = array_values(unpack('N*words', $this->key)); + + $length = $this->Nb * ($this->Nr + 1); + for ($i = $this->Nk; $i < $length; $i++) { + $temp = $w[$i - 1]; + if ($i % $this->Nk == 0) { + // according to , "the size of an integer is platform-dependent". + // on a 32-bit machine, it's 32-bits, and on a 64-bit machine, it's 64-bits. on a 32-bit machine, + // 0xFFFFFFFF << 8 == 0xFFFFFF00, but on a 64-bit machine, it equals 0xFFFFFFFF00. as such, doing 'and' + // with 0xFFFFFFFF (or 0xFFFFFF00) on a 32-bit machine is unnecessary, but on a 64-bit machine, it is. + $temp = (($temp << 8) & 0xFFFFFF00) | (($temp >> 24) & 0x000000FF); // rotWord + $temp = $this->_subWord($temp) ^ $rcon[$i / $this->Nk]; + } elseif ($this->Nk > 6 && $i % $this->Nk == 4) { + $temp = $this->_subWord($temp); + } + $w[$i] = $w[$i - $this->Nk] ^ $temp; + } + + // convert the key schedule from a vector of $Nb * ($Nr + 1) length to a matrix with $Nr + 1 rows and $Nb columns + // and generate the inverse key schedule. more specifically, + // according to (section 5.3.3), + // "The key expansion for the Inverse Cipher is defined as follows: + // 1. Apply the Key Expansion. + // 2. Apply InvMixColumn to all Round Keys except the first and the last one." + // also, see fips-197.pdf#page=27, "5.3.5 Equivalent Inverse Cipher" + list($dt0, $dt1, $dt2, $dt3) = $this->_getInvTables(); + $temp = $this->w = $this->dw = array(); + for ($i = $row = $col = 0; $i < $length; $i++, $col++) { + if ($col == $this->Nb) { + if ($row == 0) { + $this->dw[0] = $this->w[0]; + } else { + // subWord + invMixColumn + invSubWord = invMixColumn + $j = 0; + while ($j < $this->Nb) { + $dw = $this->_subWord($this->w[$row][$j]); + $temp[$j] = $dt0[$dw >> 24 & 0x000000FF] ^ + $dt1[$dw >> 16 & 0x000000FF] ^ + $dt2[$dw >> 8 & 0x000000FF] ^ + $dt3[$dw & 0x000000FF]; + $j++; + } + $this->dw[$row] = $temp; + } + + $col = 0; + $row++; + } + $this->w[$row][$col] = $w[$i]; + } + + $this->dw[$row] = $this->w[$row]; + + // Converting to 1-dim key arrays (both ascending) + $this->dw = array_reverse($this->dw); + $w = array_pop($this->w); + $dw = array_pop($this->dw); + foreach ($this->w as $r => $wr) { + foreach ($wr as $c => $wc) { + $w[] = $wc; + $dw[] = $this->dw[$r][$c]; + } + } + $this->w = $w; + $this->dw = $dw; + } + + /** + * Performs S-Box substitutions + * + * @access private + * @param int $word + */ + function _subWord($word) + { + static $sbox; + if (empty($sbox)) { + list(, , , , $sbox) = $this->_getTables(); + } + + return $sbox[$word & 0x000000FF] | + ($sbox[$word >> 8 & 0x000000FF] << 8) | + ($sbox[$word >> 16 & 0x000000FF] << 16) | + ($sbox[$word >> 24 & 0x000000FF] << 24); + } + + /** + * Provides the mixColumns and sboxes tables + * + * @see Crypt_Rijndael:_encryptBlock() + * @see Crypt_Rijndael:_setupInlineCrypt() + * @see Crypt_Rijndael:_subWord() + * @access private + * @return array &$tables + */ + function &_getTables() + { + static $tables; + if (empty($tables)) { + // according to (section 5.2.1), + // precomputed tables can be used in the mixColumns phase. in that example, they're assigned t0...t3, so + // those are the names we'll use. + $t3 = array_map('intval', array( + // with array_map('intval', ...) we ensure we have only int's and not + // some slower floats converted by php automatically on high values + 0x6363A5C6, 0x7C7C84F8, 0x777799EE, 0x7B7B8DF6, 0xF2F20DFF, 0x6B6BBDD6, 0x6F6FB1DE, 0xC5C55491, + 0x30305060, 0x01010302, 0x6767A9CE, 0x2B2B7D56, 0xFEFE19E7, 0xD7D762B5, 0xABABE64D, 0x76769AEC, + 0xCACA458F, 0x82829D1F, 0xC9C94089, 0x7D7D87FA, 0xFAFA15EF, 0x5959EBB2, 0x4747C98E, 0xF0F00BFB, + 0xADADEC41, 0xD4D467B3, 0xA2A2FD5F, 0xAFAFEA45, 0x9C9CBF23, 0xA4A4F753, 0x727296E4, 0xC0C05B9B, + 0xB7B7C275, 0xFDFD1CE1, 0x9393AE3D, 0x26266A4C, 0x36365A6C, 0x3F3F417E, 0xF7F702F5, 0xCCCC4F83, + 0x34345C68, 0xA5A5F451, 0xE5E534D1, 0xF1F108F9, 0x717193E2, 0xD8D873AB, 0x31315362, 0x15153F2A, + 0x04040C08, 0xC7C75295, 0x23236546, 0xC3C35E9D, 0x18182830, 0x9696A137, 0x05050F0A, 0x9A9AB52F, + 0x0707090E, 0x12123624, 0x80809B1B, 0xE2E23DDF, 0xEBEB26CD, 0x2727694E, 0xB2B2CD7F, 0x75759FEA, + 0x09091B12, 0x83839E1D, 0x2C2C7458, 0x1A1A2E34, 0x1B1B2D36, 0x6E6EB2DC, 0x5A5AEEB4, 0xA0A0FB5B, + 0x5252F6A4, 0x3B3B4D76, 0xD6D661B7, 0xB3B3CE7D, 0x29297B52, 0xE3E33EDD, 0x2F2F715E, 0x84849713, + 0x5353F5A6, 0xD1D168B9, 0x00000000, 0xEDED2CC1, 0x20206040, 0xFCFC1FE3, 0xB1B1C879, 0x5B5BEDB6, + 0x6A6ABED4, 0xCBCB468D, 0xBEBED967, 0x39394B72, 0x4A4ADE94, 0x4C4CD498, 0x5858E8B0, 0xCFCF4A85, + 0xD0D06BBB, 0xEFEF2AC5, 0xAAAAE54F, 0xFBFB16ED, 0x4343C586, 0x4D4DD79A, 0x33335566, 0x85859411, + 0x4545CF8A, 0xF9F910E9, 0x02020604, 0x7F7F81FE, 0x5050F0A0, 0x3C3C4478, 0x9F9FBA25, 0xA8A8E34B, + 0x5151F3A2, 0xA3A3FE5D, 0x4040C080, 0x8F8F8A05, 0x9292AD3F, 0x9D9DBC21, 0x38384870, 0xF5F504F1, + 0xBCBCDF63, 0xB6B6C177, 0xDADA75AF, 0x21216342, 0x10103020, 0xFFFF1AE5, 0xF3F30EFD, 0xD2D26DBF, + 0xCDCD4C81, 0x0C0C1418, 0x13133526, 0xECEC2FC3, 0x5F5FE1BE, 0x9797A235, 0x4444CC88, 0x1717392E, + 0xC4C45793, 0xA7A7F255, 0x7E7E82FC, 0x3D3D477A, 0x6464ACC8, 0x5D5DE7BA, 0x19192B32, 0x737395E6, + 0x6060A0C0, 0x81819819, 0x4F4FD19E, 0xDCDC7FA3, 0x22226644, 0x2A2A7E54, 0x9090AB3B, 0x8888830B, + 0x4646CA8C, 0xEEEE29C7, 0xB8B8D36B, 0x14143C28, 0xDEDE79A7, 0x5E5EE2BC, 0x0B0B1D16, 0xDBDB76AD, + 0xE0E03BDB, 0x32325664, 0x3A3A4E74, 0x0A0A1E14, 0x4949DB92, 0x06060A0C, 0x24246C48, 0x5C5CE4B8, + 0xC2C25D9F, 0xD3D36EBD, 0xACACEF43, 0x6262A6C4, 0x9191A839, 0x9595A431, 0xE4E437D3, 0x79798BF2, + 0xE7E732D5, 0xC8C8438B, 0x3737596E, 0x6D6DB7DA, 0x8D8D8C01, 0xD5D564B1, 0x4E4ED29C, 0xA9A9E049, + 0x6C6CB4D8, 0x5656FAAC, 0xF4F407F3, 0xEAEA25CF, 0x6565AFCA, 0x7A7A8EF4, 0xAEAEE947, 0x08081810, + 0xBABAD56F, 0x787888F0, 0x25256F4A, 0x2E2E725C, 0x1C1C2438, 0xA6A6F157, 0xB4B4C773, 0xC6C65197, + 0xE8E823CB, 0xDDDD7CA1, 0x74749CE8, 0x1F1F213E, 0x4B4BDD96, 0xBDBDDC61, 0x8B8B860D, 0x8A8A850F, + 0x707090E0, 0x3E3E427C, 0xB5B5C471, 0x6666AACC, 0x4848D890, 0x03030506, 0xF6F601F7, 0x0E0E121C, + 0x6161A3C2, 0x35355F6A, 0x5757F9AE, 0xB9B9D069, 0x86869117, 0xC1C15899, 0x1D1D273A, 0x9E9EB927, + 0xE1E138D9, 0xF8F813EB, 0x9898B32B, 0x11113322, 0x6969BBD2, 0xD9D970A9, 0x8E8E8907, 0x9494A733, + 0x9B9BB62D, 0x1E1E223C, 0x87879215, 0xE9E920C9, 0xCECE4987, 0x5555FFAA, 0x28287850, 0xDFDF7AA5, + 0x8C8C8F03, 0xA1A1F859, 0x89898009, 0x0D0D171A, 0xBFBFDA65, 0xE6E631D7, 0x4242C684, 0x6868B8D0, + 0x4141C382, 0x9999B029, 0x2D2D775A, 0x0F0F111E, 0xB0B0CB7B, 0x5454FCA8, 0xBBBBD66D, 0x16163A2C + )); + + foreach ($t3 as $t3i) { + $t0[] = (($t3i << 24) & 0xFF000000) | (($t3i >> 8) & 0x00FFFFFF); + $t1[] = (($t3i << 16) & 0xFFFF0000) | (($t3i >> 16) & 0x0000FFFF); + $t2[] = (($t3i << 8) & 0xFFFFFF00) | (($t3i >> 24) & 0x000000FF); + } + + $tables = array( + // The Precomputed mixColumns tables t0 - t3 + $t0, + $t1, + $t2, + $t3, + // The SubByte S-Box + array( + 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, + 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, + 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, + 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, + 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, + 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, + 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, + 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, + 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, + 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, + 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, + 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, + 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, + 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, + 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, + 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 + ) + ); + } + return $tables; + } + + /** + * Provides the inverse mixColumns and inverse sboxes tables + * + * @see Crypt_Rijndael:_decryptBlock() + * @see Crypt_Rijndael:_setupInlineCrypt() + * @see Crypt_Rijndael:_setupKey() + * @access private + * @return array &$tables + */ + function &_getInvTables() + { + static $tables; + if (empty($tables)) { + $dt3 = array_map('intval', array( + 0xF4A75051, 0x4165537E, 0x17A4C31A, 0x275E963A, 0xAB6BCB3B, 0x9D45F11F, 0xFA58ABAC, 0xE303934B, + 0x30FA5520, 0x766DF6AD, 0xCC769188, 0x024C25F5, 0xE5D7FC4F, 0x2ACBD7C5, 0x35448026, 0x62A38FB5, + 0xB15A49DE, 0xBA1B6725, 0xEA0E9845, 0xFEC0E15D, 0x2F7502C3, 0x4CF01281, 0x4697A38D, 0xD3F9C66B, + 0x8F5FE703, 0x929C9515, 0x6D7AEBBF, 0x5259DA95, 0xBE832DD4, 0x7421D358, 0xE0692949, 0xC9C8448E, + 0xC2896A75, 0x8E7978F4, 0x583E6B99, 0xB971DD27, 0xE14FB6BE, 0x88AD17F0, 0x20AC66C9, 0xCE3AB47D, + 0xDF4A1863, 0x1A3182E5, 0x51336097, 0x537F4562, 0x6477E0B1, 0x6BAE84BB, 0x81A01CFE, 0x082B94F9, + 0x48685870, 0x45FD198F, 0xDE6C8794, 0x7BF8B752, 0x73D323AB, 0x4B02E272, 0x1F8F57E3, 0x55AB2A66, + 0xEB2807B2, 0xB5C2032F, 0xC57B9A86, 0x3708A5D3, 0x2887F230, 0xBFA5B223, 0x036ABA02, 0x16825CED, + 0xCF1C2B8A, 0x79B492A7, 0x07F2F0F3, 0x69E2A14E, 0xDAF4CD65, 0x05BED506, 0x34621FD1, 0xA6FE8AC4, + 0x2E539D34, 0xF355A0A2, 0x8AE13205, 0xF6EB75A4, 0x83EC390B, 0x60EFAA40, 0x719F065E, 0x6E1051BD, + 0x218AF93E, 0xDD063D96, 0x3E05AEDD, 0xE6BD464D, 0x548DB591, 0xC45D0571, 0x06D46F04, 0x5015FF60, + 0x98FB2419, 0xBDE997D6, 0x4043CC89, 0xD99E7767, 0xE842BDB0, 0x898B8807, 0x195B38E7, 0xC8EEDB79, + 0x7C0A47A1, 0x420FE97C, 0x841EC9F8, 0x00000000, 0x80868309, 0x2BED4832, 0x1170AC1E, 0x5A724E6C, + 0x0EFFFBFD, 0x8538560F, 0xAED51E3D, 0x2D392736, 0x0FD9640A, 0x5CA62168, 0x5B54D19B, 0x362E3A24, + 0x0A67B10C, 0x57E70F93, 0xEE96D2B4, 0x9B919E1B, 0xC0C54F80, 0xDC20A261, 0x774B695A, 0x121A161C, + 0x93BA0AE2, 0xA02AE5C0, 0x22E0433C, 0x1B171D12, 0x090D0B0E, 0x8BC7ADF2, 0xB6A8B92D, 0x1EA9C814, + 0xF1198557, 0x75074CAF, 0x99DDBBEE, 0x7F60FDA3, 0x01269FF7, 0x72F5BC5C, 0x663BC544, 0xFB7E345B, + 0x4329768B, 0x23C6DCCB, 0xEDFC68B6, 0xE4F163B8, 0x31DCCAD7, 0x63851042, 0x97224013, 0xC6112084, + 0x4A247D85, 0xBB3DF8D2, 0xF93211AE, 0x29A16DC7, 0x9E2F4B1D, 0xB230F3DC, 0x8652EC0D, 0xC1E3D077, + 0xB3166C2B, 0x70B999A9, 0x9448FA11, 0xE9642247, 0xFC8CC4A8, 0xF03F1AA0, 0x7D2CD856, 0x3390EF22, + 0x494EC787, 0x38D1C1D9, 0xCAA2FE8C, 0xD40B3698, 0xF581CFA6, 0x7ADE28A5, 0xB78E26DA, 0xADBFA43F, + 0x3A9DE42C, 0x78920D50, 0x5FCC9B6A, 0x7E466254, 0x8D13C2F6, 0xD8B8E890, 0x39F75E2E, 0xC3AFF582, + 0x5D80BE9F, 0xD0937C69, 0xD52DA96F, 0x2512B3CF, 0xAC993BC8, 0x187DA710, 0x9C636EE8, 0x3BBB7BDB, + 0x267809CD, 0x5918F46E, 0x9AB701EC, 0x4F9AA883, 0x956E65E6, 0xFFE67EAA, 0xBCCF0821, 0x15E8E6EF, + 0xE79BD9BA, 0x6F36CE4A, 0x9F09D4EA, 0xB07CD629, 0xA4B2AF31, 0x3F23312A, 0xA59430C6, 0xA266C035, + 0x4EBC3774, 0x82CAA6FC, 0x90D0B0E0, 0xA7D81533, 0x04984AF1, 0xECDAF741, 0xCD500E7F, 0x91F62F17, + 0x4DD68D76, 0xEFB04D43, 0xAA4D54CC, 0x9604DFE4, 0xD1B5E39E, 0x6A881B4C, 0x2C1FB8C1, 0x65517F46, + 0x5EEA049D, 0x8C355D01, 0x877473FA, 0x0B412EFB, 0x671D5AB3, 0xDBD25292, 0x105633E9, 0xD647136D, + 0xD7618C9A, 0xA10C7A37, 0xF8148E59, 0x133C89EB, 0xA927EECE, 0x61C935B7, 0x1CE5EDE1, 0x47B13C7A, + 0xD2DF599C, 0xF2733F55, 0x14CE7918, 0xC737BF73, 0xF7CDEA53, 0xFDAA5B5F, 0x3D6F14DF, 0x44DB8678, + 0xAFF381CA, 0x68C43EB9, 0x24342C38, 0xA3405FC2, 0x1DC37216, 0xE2250CBC, 0x3C498B28, 0x0D9541FF, + 0xA8017139, 0x0CB3DE08, 0xB4E49CD8, 0x56C19064, 0xCB84617B, 0x32B670D5, 0x6C5C7448, 0xB85742D0 + )); + + foreach ($dt3 as $dt3i) { + $dt0[] = (($dt3i << 24) & 0xFF000000) | (($dt3i >> 8) & 0x00FFFFFF); + $dt1[] = (($dt3i << 16) & 0xFFFF0000) | (($dt3i >> 16) & 0x0000FFFF); + $dt2[] = (($dt3i << 8) & 0xFFFFFF00) | (($dt3i >> 24) & 0x000000FF); + }; + + $tables = array( + // The Precomputed inverse mixColumns tables dt0 - dt3 + $dt0, + $dt1, + $dt2, + $dt3, + // The inverse SubByte S-Box + array( + 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, + 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, + 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, + 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, + 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, + 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, + 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, + 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, + 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, + 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, + 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, + 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, + 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, + 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, + 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D + ) + ); + } + return $tables; + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * @see Crypt_Base::_setupInlineCrypt() + * @access private + */ + function _setupInlineCrypt() + { + // Note: _setupInlineCrypt() will be called only if $this->changed === true + // So here we are'nt under the same heavy timing-stress as we are in _de/encryptBlock() or de/encrypt(). + // However...the here generated function- $code, stored as php callback in $this->inline_crypt, must work as fast as even possible. + + $lambda_functions =& Crypt_Rijndael::_getLambdaFunctions(); + + // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. + // (Currently, for Crypt_Rijndael/AES, one generated $lambda_function cost on php5.5@32bit ~80kb unfreeable mem and ~130kb on php5.5@64bit) + // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); + + // Generation of a uniqe hash for our generated code + $code_hash = "Crypt_Rijndael, {$this->mode}, {$this->Nr}, {$this->Nb}"; + if ($gen_hi_opt_code) { + $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); + } + + if (!isset($lambda_functions[$code_hash])) { + switch (true) { + case $gen_hi_opt_code: + // The hi-optimized $lambda_functions will use the key-words hardcoded for better performance. + $w = $this->w; + $dw = $this->dw; + $init_encrypt = ''; + $init_decrypt = ''; + break; + default: + for ($i = 0, $cw = count($this->w); $i < $cw; ++$i) { + $w[] = '$w[' . $i . ']'; + $dw[] = '$dw[' . $i . ']'; + } + $init_encrypt = '$w = $self->w;'; + $init_decrypt = '$dw = $self->dw;'; + } + + $Nr = $this->Nr; + $Nb = $this->Nb; + $c = $this->c; + + // Generating encrypt code: + $init_encrypt.= ' + static $tables; + if (empty($tables)) { + $tables = &$self->_getTables(); + } + $t0 = $tables[0]; + $t1 = $tables[1]; + $t2 = $tables[2]; + $t3 = $tables[3]; + $sbox = $tables[4]; + '; + + $s = 'e'; + $e = 's'; + $wc = $Nb - 1; + + // Preround: addRoundKey + $encrypt_block = '$in = unpack("N*", $in);'."\n"; + for ($i = 0; $i < $Nb; ++$i) { + $encrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$w[++$wc].";\n"; + } + + // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey + for ($round = 1; $round < $Nr; ++$round) { + list($s, $e) = array($e, $s); + for ($i = 0; $i < $Nb; ++$i) { + $encrypt_block.= + '$'.$e.$i.' = + $t0[($'.$s.$i .' >> 24) & 0xff] ^ + $t1[($'.$s.(($i + $c[1]) % $Nb).' >> 16) & 0xff] ^ + $t2[($'.$s.(($i + $c[2]) % $Nb).' >> 8) & 0xff] ^ + $t3[ $'.$s.(($i + $c[3]) % $Nb).' & 0xff] ^ + '.$w[++$wc].";\n"; + } + } + + // Finalround: subWord + shiftRows + addRoundKey + for ($i = 0; $i < $Nb; ++$i) { + $encrypt_block.= + '$'.$e.$i.' = + $sbox[ $'.$e.$i.' & 0xff] | + ($sbox[($'.$e.$i.' >> 8) & 0xff] << 8) | + ($sbox[($'.$e.$i.' >> 16) & 0xff] << 16) | + ($sbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; + } + $encrypt_block .= '$in = pack("N*"'."\n"; + for ($i = 0; $i < $Nb; ++$i) { + $encrypt_block.= ', + ($'.$e.$i .' & '.((int)0xFF000000).') ^ + ($'.$e.(($i + $c[1]) % $Nb).' & 0x00FF0000 ) ^ + ($'.$e.(($i + $c[2]) % $Nb).' & 0x0000FF00 ) ^ + ($'.$e.(($i + $c[3]) % $Nb).' & 0x000000FF ) ^ + '.$w[$i]."\n"; + } + $encrypt_block .= ');'; + + // Generating decrypt code: + $init_decrypt.= ' + static $invtables; + if (empty($invtables)) { + $invtables = &$self->_getInvTables(); + } + $dt0 = $invtables[0]; + $dt1 = $invtables[1]; + $dt2 = $invtables[2]; + $dt3 = $invtables[3]; + $isbox = $invtables[4]; + '; + + $s = 'e'; + $e = 's'; + $wc = $Nb - 1; + + // Preround: addRoundKey + $decrypt_block = '$in = unpack("N*", $in);'."\n"; + for ($i = 0; $i < $Nb; ++$i) { + $decrypt_block .= '$s'.$i.' = $in['.($i + 1).'] ^ '.$dw[++$wc].';'."\n"; + } + + // Mainrounds: shiftRows + subWord + mixColumns + addRoundKey + for ($round = 1; $round < $Nr; ++$round) { + list($s, $e) = array($e, $s); + for ($i = 0; $i < $Nb; ++$i) { + $decrypt_block.= + '$'.$e.$i.' = + $dt0[($'.$s.$i .' >> 24) & 0xff] ^ + $dt1[($'.$s.(($Nb + $i - $c[1]) % $Nb).' >> 16) & 0xff] ^ + $dt2[($'.$s.(($Nb + $i - $c[2]) % $Nb).' >> 8) & 0xff] ^ + $dt3[ $'.$s.(($Nb + $i - $c[3]) % $Nb).' & 0xff] ^ + '.$dw[++$wc].";\n"; + } + } + + // Finalround: subWord + shiftRows + addRoundKey + for ($i = 0; $i < $Nb; ++$i) { + $decrypt_block.= + '$'.$e.$i.' = + $isbox[ $'.$e.$i.' & 0xff] | + ($isbox[($'.$e.$i.' >> 8) & 0xff] << 8) | + ($isbox[($'.$e.$i.' >> 16) & 0xff] << 16) | + ($isbox[($'.$e.$i.' >> 24) & 0xff] << 24);'."\n"; + } + $decrypt_block .= '$in = pack("N*"'."\n"; + for ($i = 0; $i < $Nb; ++$i) { + $decrypt_block.= ', + ($'.$e.$i. ' & '.((int)0xFF000000).') ^ + ($'.$e.(($Nb + $i - $c[1]) % $Nb).' & 0x00FF0000 ) ^ + ($'.$e.(($Nb + $i - $c[2]) % $Nb).' & 0x0000FF00 ) ^ + ($'.$e.(($Nb + $i - $c[3]) % $Nb).' & 0x000000FF ) ^ + '.$dw[$i]."\n"; + } + $decrypt_block .= ');'; + + $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( + array( + 'init_crypt' => '', + 'init_encrypt' => $init_encrypt, + 'init_decrypt' => $init_decrypt, + 'encrypt_block' => $encrypt_block, + 'decrypt_block' => $decrypt_block + ) + ); + } + $this->inline_crypt = $lambda_functions[$code_hash]; + } +} diff --git a/ipaylinks_statement/Crypt/TripleDES.php b/ipaylinks_statement/Crypt/TripleDES.php new file mode 100644 index 00000000..4c0b6770 --- /dev/null +++ b/ipaylinks_statement/Crypt/TripleDES.php @@ -0,0 +1,517 @@ + + * setKey('abcdefghijklmnopqrstuvwx'); + * + * $size = 10 * 1024; + * $plaintext = ''; + * for ($i = 0; $i < $size; $i++) { + * $plaintext.= 'a'; + * } + * + * echo $des->decrypt($des->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_TripleDES + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_DES + */ +if (!class_exists('Crypt_DES')) { + include_once 'DES.php'; +} + +/**#@+ + * @access public + * @see self::Crypt_TripleDES() + */ +/** + * Encrypt / decrypt using inner chaining + * + * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3). + */ +define('CRYPT_MODE_3CBC', -2); +/** + * BC version of the above. + */ +define('CRYPT_DES_MODE_3CBC', -2); +/** + * Encrypt / decrypt using outer chaining + * + * Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC. + */ +define('CRYPT_MODE_CBC3', CRYPT_MODE_CBC); +/** + * BC version of the above. + */ +define('CRYPT_DES_MODE_CBC3', CRYPT_MODE_CBC3); +/**#@-*/ + +/** + * Pure-PHP implementation of Triple DES. + * + * @package Crypt_TripleDES + * @author Jim Wigginton + * @access public + */ +class Crypt_TripleDES extends Crypt_DES +{ + /** + * Key Length (in bytes) + * + * @see Crypt_TripleDES::setKeyLength() + * @var int + * @access private + */ + var $key_length = 24; + + /** + * The default salt used by setPassword() + * + * @see Crypt_Base::password_default_salt + * @see Crypt_Base::setPassword() + * @var string + * @access private + */ + var $password_default_salt = 'phpseclib'; + + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_DES::const_namespace + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'DES'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_DES::cipher_name_mcrypt + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'tripledes'; + + /** + * Optimizing value while CFB-encrypting + * + * @see Crypt_Base::cfb_init_len + * @var int + * @access private + */ + var $cfb_init_len = 750; + + /** + * max possible size of $key + * + * @see self::setKey() + * @see Crypt_DES::setKey() + * @var string + * @access private + */ + var $key_length_max = 24; + + /** + * Internal flag whether using CRYPT_DES_MODE_3CBC or not + * + * @var bool + * @access private + */ + var $mode_3cbc; + + /** + * The Crypt_DES objects + * + * Used only if $mode_3cbc === true + * + * @var array + * @access private + */ + var $des; + + /** + * Default Constructor. + * + * Determines whether or not the mcrypt extension should be used. + * + * $mode could be: + * + * - CRYPT_DES_MODE_ECB + * + * - CRYPT_DES_MODE_CBC + * + * - CRYPT_DES_MODE_CTR + * + * - CRYPT_DES_MODE_CFB + * + * - CRYPT_DES_MODE_OFB + * + * - CRYPT_DES_MODE_3CBC + * + * If not explicitly set, CRYPT_DES_MODE_CBC will be used. + * + * @see Crypt_DES::Crypt_DES() + * @see Crypt_Base::Crypt_Base() + * @param int $mode + * @access public + */ + function __construct($mode = CRYPT_MODE_CBC) + { + switch ($mode) { + // In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC + // and additional flag us internally as 3CBC + case CRYPT_DES_MODE_3CBC: + parent::Crypt_Base(CRYPT_MODE_CBC); + $this->mode_3cbc = true; + + // This three $des'es will do the 3CBC work (if $key > 64bits) + $this->des = array( + new Crypt_DES(CRYPT_MODE_CBC), + new Crypt_DES(CRYPT_MODE_CBC), + new Crypt_DES(CRYPT_MODE_CBC), + ); + + // we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects + $this->des[0]->disablePadding(); + $this->des[1]->disablePadding(); + $this->des[2]->disablePadding(); + break; + // If not 3CBC, we init as usual + default: + parent::__construct($mode); + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param int $mode + * @access public + */ + function Crypt_TripleDES($mode = CRYPT_MODE_CBC) + { + $this->__construct($mode); + } + + /** + * Test for engine validity + * + * This is mainly just a wrapper to set things up for Crypt_Base::isValidEngine() + * + * @see Crypt_Base::Crypt_Base() + * @param int $engine + * @access public + * @return bool + */ + function isValidEngine($engine) + { + if ($engine == CRYPT_ENGINE_OPENSSL) { + $this->cipher_name_openssl_ecb = 'des-ede3'; + $mode = $this->_openssl_translate_mode(); + $this->cipher_name_openssl = $mode == 'ecb' ? 'des-ede3' : 'des-ede3-' . $mode; + } + + return parent::isValidEngine($engine); + } + + /** + * Sets the initialization vector. (optional) + * + * SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explicitly set, it'll be assumed + * to be all zero's. + * + * @see Crypt_Base::setIV() + * @access public + * @param string $iv + */ + function setIV($iv) + { + parent::setIV($iv); + if ($this->mode_3cbc) { + $this->des[0]->setIV($iv); + $this->des[1]->setIV($iv); + $this->des[2]->setIV($iv); + } + } + + /** + * Sets the key length. + * + * Valid key lengths are 64, 128 and 192 + * + * @see Crypt_Base:setKeyLength() + * @access public + * @param int $length + */ + function setKeyLength($length) + { + $length >>= 3; + switch (true) { + case $length <= 8: + $this->key_length = 8; + break; + case $length <= 16: + $this->key_length = 16; + break; + default: + $this->key_length = 24; + } + + parent::setKeyLength($length); + } + + /** + * Sets the key. + * + * Keys can be of any length. Triple DES, itself, can use 128-bit (eg. strlen($key) == 16) or + * 192-bit (eg. strlen($key) == 24) keys. This function pads and truncates $key as appropriate. + * + * DES also requires that every eighth bit be a parity bit, however, we'll ignore that. + * + * If the key is not explicitly set, it'll be assumed to be all null bytes. + * + * @access public + * @see Crypt_DES::setKey() + * @see Crypt_Base::setKey() + * @param string $key + */ + function setKey($key) + { + $length = $this->explicit_key_length ? $this->key_length : strlen($key); + if ($length > 8) { + $key = str_pad(substr($key, 0, 24), 24, chr(0)); + // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: + // http://php.net/function.mcrypt-encrypt#47973 + $key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24); + } else { + $key = str_pad($key, 8, chr(0)); + } + parent::setKey($key); + + // And in case of CRYPT_DES_MODE_3CBC: + // if key <= 64bits we not need the 3 $des to work, + // because we will then act as regular DES-CBC with just a <= 64bit key. + // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des. + if ($this->mode_3cbc && $length > 8) { + $this->des[0]->setKey(substr($key, 0, 8)); + $this->des[1]->setKey(substr($key, 8, 8)); + $this->des[2]->setKey(substr($key, 16, 8)); + } + } + + /** + * Encrypts a message. + * + * @see Crypt_Base::encrypt() + * @access public + * @param string $plaintext + * @return string $cipertext + */ + function encrypt($plaintext) + { + // parent::en/decrypt() is able to do all the work for all modes and keylengths, + // except for: CRYPT_MODE_3CBC (inner chaining CBC) with a key > 64bits + + // if the key is smaller then 8, do what we'd normally do + if ($this->mode_3cbc && strlen($this->key) > 8) { + return $this->des[2]->encrypt( + $this->des[1]->decrypt( + $this->des[0]->encrypt( + $this->_pad($plaintext) + ) + ) + ); + } + + return parent::encrypt($plaintext); + } + + /** + * Decrypts a message. + * + * @see Crypt_Base::decrypt() + * @access public + * @param string $ciphertext + * @return string $plaintext + */ + function decrypt($ciphertext) + { + if ($this->mode_3cbc && strlen($this->key) > 8) { + return $this->_unpad( + $this->des[0]->decrypt( + $this->des[1]->encrypt( + $this->des[2]->decrypt( + str_pad($ciphertext, (strlen($ciphertext) + 7) & 0xFFFFFFF8, "\0") + ) + ) + ) + ); + } + + return parent::decrypt($ciphertext); + } + + /** + * Treat consecutive "packets" as if they are a continuous buffer. + * + * Say you have a 16-byte plaintext $plaintext. Using the default behavior, the two following code snippets + * will yield different outputs: + * + * + * echo $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->encrypt(substr($plaintext, 8, 8)); + * + * + * echo $des->encrypt($plaintext); + * + * + * The solution is to enable the continuous buffer. Although this will resolve the above discrepancy, it creates + * another, as demonstrated with the following: + * + * + * $des->encrypt(substr($plaintext, 0, 8)); + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * echo $des->decrypt($des->encrypt(substr($plaintext, 8, 8))); + * + * + * With the continuous buffer disabled, these would yield the same output. With it enabled, they yield different + * outputs. The reason is due to the fact that the initialization vector's change after every encryption / + * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. + * + * Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each + * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that + * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), + * however, they are also less intuitive and more likely to cause you problems. + * + * @see Crypt_Base::enableContinuousBuffer() + * @see self::disableContinuousBuffer() + * @access public + */ + function enableContinuousBuffer() + { + parent::enableContinuousBuffer(); + if ($this->mode_3cbc) { + $this->des[0]->enableContinuousBuffer(); + $this->des[1]->enableContinuousBuffer(); + $this->des[2]->enableContinuousBuffer(); + } + } + + /** + * Treat consecutive packets as if they are a discontinuous buffer. + * + * The default behavior. + * + * @see Crypt_Base::disableContinuousBuffer() + * @see self::enableContinuousBuffer() + * @access public + */ + function disableContinuousBuffer() + { + parent::disableContinuousBuffer(); + if ($this->mode_3cbc) { + $this->des[0]->disableContinuousBuffer(); + $this->des[1]->disableContinuousBuffer(); + $this->des[2]->disableContinuousBuffer(); + } + } + + /** + * Creates the key schedule + * + * @see Crypt_DES::_setupKey() + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + switch (true) { + // if $key <= 64bits we configure our internal pure-php cipher engine + // to act as regular [1]DES, not as 3DES. mcrypt.so::tripledes does the same. + case strlen($this->key) <= 8: + $this->des_rounds = 1; + break; + + // otherwise, if $key > 64bits, we configure our engine to work as 3DES. + default: + $this->des_rounds = 3; + + // (only) if 3CBC is used we have, of course, to setup the $des[0-2] keys also separately. + if ($this->mode_3cbc) { + $this->des[0]->_setupKey(); + $this->des[1]->_setupKey(); + $this->des[2]->_setupKey(); + + // because $des[0-2] will, now, do all the work we can return here + // not need unnecessary stress parent::_setupKey() with our, now unused, $key. + return; + } + } + // setup our key + parent::_setupKey(); + } + + /** + * Sets the internal crypt engine + * + * @see Crypt_Base::Crypt_Base() + * @see Crypt_Base::setPreferredEngine() + * @param int $engine + * @access public + * @return int + */ + function setPreferredEngine($engine) + { + if ($this->mode_3cbc) { + $this->des[0]->setPreferredEngine($engine); + $this->des[1]->setPreferredEngine($engine); + $this->des[2]->setPreferredEngine($engine); + } + + return parent::setPreferredEngine($engine); + } +} diff --git a/ipaylinks_statement/Crypt/Twofish.php b/ipaylinks_statement/Crypt/Twofish.php new file mode 100644 index 00000000..7125f6a0 --- /dev/null +++ b/ipaylinks_statement/Crypt/Twofish.php @@ -0,0 +1,881 @@ + + * setKey('12345678901234567890123456789012'); + * + * $plaintext = str_repeat('a', 1024); + * + * echo $twofish->decrypt($twofish->encrypt($plaintext)); + * ?> + * + * + * LICENSE: 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. + * + * @category Crypt + * @package Crypt_Twofish + * @author Jim Wigginton + * @author Hans-Juergen Petrich + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Crypt_Base + * + * Base cipher class + */ +if (!class_exists('Crypt_Base')) { + include_once 'Base.php'; +} + +/**#@+ + * @access public + * @see self::encrypt() + * @see self::decrypt() + */ +/** + * Encrypt / decrypt using the Counter mode. + * + * Set to -1 since that's what Crypt/Random.php uses to index the CTR mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29 + */ +define('CRYPT_TWOFISH_MODE_CTR', CRYPT_MODE_CTR); +/** + * Encrypt / decrypt using the Electronic Code Book mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29 + */ +define('CRYPT_TWOFISH_MODE_ECB', CRYPT_MODE_ECB); +/** + * Encrypt / decrypt using the Code Book Chaining mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29 + */ +define('CRYPT_TWOFISH_MODE_CBC', CRYPT_MODE_CBC); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29 + */ +define('CRYPT_TWOFISH_MODE_CFB', CRYPT_MODE_CFB); +/** + * Encrypt / decrypt using the Cipher Feedback mode. + * + * @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29 + */ +define('CRYPT_TWOFISH_MODE_OFB', CRYPT_MODE_OFB); +/**#@-*/ + +/** + * Pure-PHP implementation of Twofish. + * + * @package Crypt_Twofish + * @author Jim Wigginton + * @author Hans-Juergen Petrich + * @access public + */ +class Crypt_Twofish extends Crypt_Base +{ + /** + * The namespace used by the cipher for its constants. + * + * @see Crypt_Base::const_namespace + * @var string + * @access private + */ + var $const_namespace = 'TWOFISH'; + + /** + * The mcrypt specific name of the cipher + * + * @see Crypt_Base::cipher_name_mcrypt + * @var string + * @access private + */ + var $cipher_name_mcrypt = 'twofish'; + + /** + * Optimizing value while CFB-encrypting + * + * @see Crypt_Base::cfb_init_len + * @var int + * @access private + */ + var $cfb_init_len = 800; + + /** + * Q-Table + * + * @var array + * @access private + */ + var $q0 = array( + 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, + 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, + 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, + 0x43, 0x75, 0x37, 0x26, 0xFA, 0x13, 0x94, 0x48, + 0xF2, 0xD0, 0x8B, 0x30, 0x84, 0x54, 0xDF, 0x23, + 0x19, 0x5B, 0x3D, 0x59, 0xF3, 0xAE, 0xA2, 0x82, + 0x63, 0x01, 0x83, 0x2E, 0xD9, 0x51, 0x9B, 0x7C, + 0xA6, 0xEB, 0xA5, 0xBE, 0x16, 0x0C, 0xE3, 0x61, + 0xC0, 0x8C, 0x3A, 0xF5, 0x73, 0x2C, 0x25, 0x0B, + 0xBB, 0x4E, 0x89, 0x6B, 0x53, 0x6A, 0xB4, 0xF1, + 0xE1, 0xE6, 0xBD, 0x45, 0xE2, 0xF4, 0xB6, 0x66, + 0xCC, 0x95, 0x03, 0x56, 0xD4, 0x1C, 0x1E, 0xD7, + 0xFB, 0xC3, 0x8E, 0xB5, 0xE9, 0xCF, 0xBF, 0xBA, + 0xEA, 0x77, 0x39, 0xAF, 0x33, 0xC9, 0x62, 0x71, + 0x81, 0x79, 0x09, 0xAD, 0x24, 0xCD, 0xF9, 0xD8, + 0xE5, 0xC5, 0xB9, 0x4D, 0x44, 0x08, 0x86, 0xE7, + 0xA1, 0x1D, 0xAA, 0xED, 0x06, 0x70, 0xB2, 0xD2, + 0x41, 0x7B, 0xA0, 0x11, 0x31, 0xC2, 0x27, 0x90, + 0x20, 0xF6, 0x60, 0xFF, 0x96, 0x5C, 0xB1, 0xAB, + 0x9E, 0x9C, 0x52, 0x1B, 0x5F, 0x93, 0x0A, 0xEF, + 0x91, 0x85, 0x49, 0xEE, 0x2D, 0x4F, 0x8F, 0x3B, + 0x47, 0x87, 0x6D, 0x46, 0xD6, 0x3E, 0x69, 0x64, + 0x2A, 0xCE, 0xCB, 0x2F, 0xFC, 0x97, 0x05, 0x7A, + 0xAC, 0x7F, 0xD5, 0x1A, 0x4B, 0x0E, 0xA7, 0x5A, + 0x28, 0x14, 0x3F, 0x29, 0x88, 0x3C, 0x4C, 0x02, + 0xB8, 0xDA, 0xB0, 0x17, 0x55, 0x1F, 0x8A, 0x7D, + 0x57, 0xC7, 0x8D, 0x74, 0xB7, 0xC4, 0x9F, 0x72, + 0x7E, 0x15, 0x22, 0x12, 0x58, 0x07, 0x99, 0x34, + 0x6E, 0x50, 0xDE, 0x68, 0x65, 0xBC, 0xDB, 0xF8, + 0xC8, 0xA8, 0x2B, 0x40, 0xDC, 0xFE, 0x32, 0xA4, + 0xCA, 0x10, 0x21, 0xF0, 0xD3, 0x5D, 0x0F, 0x00, + 0x6F, 0x9D, 0x36, 0x42, 0x4A, 0x5E, 0xC1, 0xE0 + ); + + /** + * Q-Table + * + * @var array + * @access private + */ + var $q1 = array( + 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, + 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, + 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, + 0x30, 0x0F, 0xF8, 0x1B, 0x87, 0xFA, 0x06, 0x3F, + 0x5E, 0xBA, 0xAE, 0x5B, 0x8A, 0x00, 0xBC, 0x9D, + 0x6D, 0xC1, 0xB1, 0x0E, 0x80, 0x5D, 0xD2, 0xD5, + 0xA0, 0x84, 0x07, 0x14, 0xB5, 0x90, 0x2C, 0xA3, + 0xB2, 0x73, 0x4C, 0x54, 0x92, 0x74, 0x36, 0x51, + 0x38, 0xB0, 0xBD, 0x5A, 0xFC, 0x60, 0x62, 0x96, + 0x6C, 0x42, 0xF7, 0x10, 0x7C, 0x28, 0x27, 0x8C, + 0x13, 0x95, 0x9C, 0xC7, 0x24, 0x46, 0x3B, 0x70, + 0xCA, 0xE3, 0x85, 0xCB, 0x11, 0xD0, 0x93, 0xB8, + 0xA6, 0x83, 0x20, 0xFF, 0x9F, 0x77, 0xC3, 0xCC, + 0x03, 0x6F, 0x08, 0xBF, 0x40, 0xE7, 0x2B, 0xE2, + 0x79, 0x0C, 0xAA, 0x82, 0x41, 0x3A, 0xEA, 0xB9, + 0xE4, 0x9A, 0xA4, 0x97, 0x7E, 0xDA, 0x7A, 0x17, + 0x66, 0x94, 0xA1, 0x1D, 0x3D, 0xF0, 0xDE, 0xB3, + 0x0B, 0x72, 0xA7, 0x1C, 0xEF, 0xD1, 0x53, 0x3E, + 0x8F, 0x33, 0x26, 0x5F, 0xEC, 0x76, 0x2A, 0x49, + 0x81, 0x88, 0xEE, 0x21, 0xC4, 0x1A, 0xEB, 0xD9, + 0xC5, 0x39, 0x99, 0xCD, 0xAD, 0x31, 0x8B, 0x01, + 0x18, 0x23, 0xDD, 0x1F, 0x4E, 0x2D, 0xF9, 0x48, + 0x4F, 0xF2, 0x65, 0x8E, 0x78, 0x5C, 0x58, 0x19, + 0x8D, 0xE5, 0x98, 0x57, 0x67, 0x7F, 0x05, 0x64, + 0xAF, 0x63, 0xB6, 0xFE, 0xF5, 0xB7, 0x3C, 0xA5, + 0xCE, 0xE9, 0x68, 0x44, 0xE0, 0x4D, 0x43, 0x69, + 0x29, 0x2E, 0xAC, 0x15, 0x59, 0xA8, 0x0A, 0x9E, + 0x6E, 0x47, 0xDF, 0x34, 0x35, 0x6A, 0xCF, 0xDC, + 0x22, 0xC9, 0xC0, 0x9B, 0x89, 0xD4, 0xED, 0xAB, + 0x12, 0xA2, 0x0D, 0x52, 0xBB, 0x02, 0x2F, 0xA9, + 0xD7, 0x61, 0x1E, 0xB4, 0x50, 0x04, 0xF6, 0xC2, + 0x16, 0x25, 0x86, 0x56, 0x55, 0x09, 0xBE, 0x91 + ); + + /** + * M-Table + * + * @var array + * @access private + */ + var $m0 = array( + 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8, + 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B, + 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1, + 0x24243C30, 0x5151E20F, 0xBABAC6F8, 0x4A4AF31B, 0xBFBF4887, 0x0D0D70FA, 0xB0B0B306, 0x7575DE3F, + 0xD2D2FD5E, 0x7D7D20BA, 0x666631AE, 0x3A3AA35B, 0x59591C8A, 0x00000000, 0xCDCD93BC, 0x1A1AE09D, + 0xAEAE2C6D, 0x7F7FABC1, 0x2B2BC7B1, 0xBEBEB90E, 0xE0E0A080, 0x8A8A105D, 0x3B3B52D2, 0x6464BAD5, + 0xD8D888A0, 0xE7E7A584, 0x5F5FE807, 0x1B1B1114, 0x2C2CC2B5, 0xFCFCB490, 0x3131272C, 0x808065A3, + 0x73732AB2, 0x0C0C8173, 0x79795F4C, 0x6B6B4154, 0x4B4B0292, 0x53536974, 0x94948F36, 0x83831F51, + 0x2A2A3638, 0xC4C49CB0, 0x2222C8BD, 0xD5D5F85A, 0xBDBDC3FC, 0x48487860, 0xFFFFCE62, 0x4C4C0796, + 0x4141776C, 0xC7C7E642, 0xEBEB24F7, 0x1C1C1410, 0x5D5D637C, 0x36362228, 0x6767C027, 0xE9E9AF8C, + 0x4444F913, 0x1414EA95, 0xF5F5BB9C, 0xCFCF18C7, 0x3F3F2D24, 0xC0C0E346, 0x7272DB3B, 0x54546C70, + 0x29294CCA, 0xF0F035E3, 0x0808FE85, 0xC6C617CB, 0xF3F34F11, 0x8C8CE4D0, 0xA4A45993, 0xCACA96B8, + 0x68683BA6, 0xB8B84D83, 0x38382820, 0xE5E52EFF, 0xADAD569F, 0x0B0B8477, 0xC8C81DC3, 0x9999FFCC, + 0x5858ED03, 0x19199A6F, 0x0E0E0A08, 0x95957EBF, 0x70705040, 0xF7F730E7, 0x6E6ECF2B, 0x1F1F6EE2, + 0xB5B53D79, 0x09090F0C, 0x616134AA, 0x57571682, 0x9F9F0B41, 0x9D9D803A, 0x111164EA, 0x2525CDB9, + 0xAFAFDDE4, 0x4545089A, 0xDFDF8DA4, 0xA3A35C97, 0xEAEAD57E, 0x353558DA, 0xEDEDD07A, 0x4343FC17, + 0xF8F8CB66, 0xFBFBB194, 0x3737D3A1, 0xFAFA401D, 0xC2C2683D, 0xB4B4CCF0, 0x32325DDE, 0x9C9C71B3, + 0x5656E70B, 0xE3E3DA72, 0x878760A7, 0x15151B1C, 0xF9F93AEF, 0x6363BFD1, 0x3434A953, 0x9A9A853E, + 0xB1B1428F, 0x7C7CD133, 0x88889B26, 0x3D3DA65F, 0xA1A1D7EC, 0xE4E4DF76, 0x8181942A, 0x91910149, + 0x0F0FFB81, 0xEEEEAA88, 0x161661EE, 0xD7D77321, 0x9797F5C4, 0xA5A5A81A, 0xFEFE3FEB, 0x6D6DB5D9, + 0x7878AEC5, 0xC5C56D39, 0x1D1DE599, 0x7676A4CD, 0x3E3EDCAD, 0xCBCB6731, 0xB6B6478B, 0xEFEF5B01, + 0x12121E18, 0x6060C523, 0x6A6AB0DD, 0x4D4DF61F, 0xCECEE94E, 0xDEDE7C2D, 0x55559DF9, 0x7E7E5A48, + 0x2121B24F, 0x03037AF2, 0xA0A02665, 0x5E5E198E, 0x5A5A6678, 0x65654B5C, 0x62624E58, 0xFDFD4519, + 0x0606F48D, 0x404086E5, 0xF2F2BE98, 0x3333AC57, 0x17179067, 0x05058E7F, 0xE8E85E05, 0x4F4F7D64, + 0x89896AAF, 0x10109563, 0x74742FB6, 0x0A0A75FE, 0x5C5C92F5, 0x9B9B74B7, 0x2D2D333C, 0x3030D6A5, + 0x2E2E49CE, 0x494989E9, 0x46467268, 0x77775544, 0xA8A8D8E0, 0x9696044D, 0x2828BD43, 0xA9A92969, + 0xD9D97929, 0x8686912E, 0xD1D187AC, 0xF4F44A15, 0x8D8D1559, 0xD6D682A8, 0xB9B9BC0A, 0x42420D9E, + 0xF6F6C16E, 0x2F2FB847, 0xDDDD06DF, 0x23233934, 0xCCCC6235, 0xF1F1C46A, 0xC1C112CF, 0x8585EBDC, + 0x8F8F9E22, 0x7171A1C9, 0x9090F0C0, 0xAAAA539B, 0x0101F189, 0x8B8BE1D4, 0x4E4E8CED, 0x8E8E6FAB, + 0xABABA212, 0x6F6F3EA2, 0xE6E6540D, 0xDBDBF252, 0x92927BBB, 0xB7B7B602, 0x6969CA2F, 0x3939D9A9, + 0xD3D30CD7, 0xA7A72361, 0xA2A2AD1E, 0xC3C399B4, 0x6C6C4450, 0x07070504, 0x04047FF6, 0x272746C2, + 0xACACA716, 0xD0D07625, 0x50501386, 0xDCDCF756, 0x84841A55, 0xE1E15109, 0x7A7A25BE, 0x1313EF91 + ); + + /** + * M-Table + * + * @var array + * @access private + */ + var $m1 = array( + 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4, + 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A, + 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141, + 0x43BD2828, 0x7532BCBC, 0x37D47B7B, 0x269B8888, 0xFA700D0D, 0x13F94444, 0x94B1FBFB, 0x485A7E7E, + 0xF27A0303, 0xD0E48C8C, 0x8B47B6B6, 0x303C2424, 0x84A5E7E7, 0x54416B6B, 0xDF06DDDD, 0x23C56060, + 0x1945FDFD, 0x5BA33A3A, 0x3D68C2C2, 0x59158D8D, 0xF321ECEC, 0xAE316666, 0xA23E6F6F, 0x82165757, + 0x63951010, 0x015BEFEF, 0x834DB8B8, 0x2E918686, 0xD9B56D6D, 0x511F8383, 0x9B53AAAA, 0x7C635D5D, + 0xA63B6868, 0xEB3FFEFE, 0xA5D63030, 0xBE257A7A, 0x16A7ACAC, 0x0C0F0909, 0xE335F0F0, 0x6123A7A7, + 0xC0F09090, 0x8CAFE9E9, 0x3A809D9D, 0xF5925C5C, 0x73810C0C, 0x2C273131, 0x2576D0D0, 0x0BE75656, + 0xBB7B9292, 0x4EE9CECE, 0x89F10101, 0x6B9F1E1E, 0x53A93434, 0x6AC4F1F1, 0xB499C3C3, 0xF1975B5B, + 0xE1834747, 0xE66B1818, 0xBDC82222, 0x450E9898, 0xE26E1F1F, 0xF4C9B3B3, 0xB62F7474, 0x66CBF8F8, + 0xCCFF9999, 0x95EA1414, 0x03ED5858, 0x56F7DCDC, 0xD4E18B8B, 0x1C1B1515, 0x1EADA2A2, 0xD70CD3D3, + 0xFB2BE2E2, 0xC31DC8C8, 0x8E195E5E, 0xB5C22C2C, 0xE9894949, 0xCF12C1C1, 0xBF7E9595, 0xBA207D7D, + 0xEA641111, 0x77840B0B, 0x396DC5C5, 0xAF6A8989, 0x33D17C7C, 0xC9A17171, 0x62CEFFFF, 0x7137BBBB, + 0x81FB0F0F, 0x793DB5B5, 0x0951E1E1, 0xADDC3E3E, 0x242D3F3F, 0xCDA47676, 0xF99D5555, 0xD8EE8282, + 0xE5864040, 0xC5AE7878, 0xB9CD2525, 0x4D049696, 0x44557777, 0x080A0E0E, 0x86135050, 0xE730F7F7, + 0xA1D33737, 0x1D40FAFA, 0xAA346161, 0xED8C4E4E, 0x06B3B0B0, 0x706C5454, 0xB22A7373, 0xD2523B3B, + 0x410B9F9F, 0x7B8B0202, 0xA088D8D8, 0x114FF3F3, 0x3167CBCB, 0xC2462727, 0x27C06767, 0x90B4FCFC, + 0x20283838, 0xF67F0404, 0x60784848, 0xFF2EE5E5, 0x96074C4C, 0x5C4B6565, 0xB1C72B2B, 0xAB6F8E8E, + 0x9E0D4242, 0x9CBBF5F5, 0x52F2DBDB, 0x1BF34A4A, 0x5FA63D3D, 0x9359A4A4, 0x0ABCB9B9, 0xEF3AF9F9, + 0x91EF1313, 0x85FE0808, 0x49019191, 0xEE611616, 0x2D7CDEDE, 0x4FB22121, 0x8F42B1B1, 0x3BDB7272, + 0x47B82F2F, 0x8748BFBF, 0x6D2CAEAE, 0x46E3C0C0, 0xD6573C3C, 0x3E859A9A, 0x6929A9A9, 0x647D4F4F, + 0x2A948181, 0xCE492E2E, 0xCB17C6C6, 0x2FCA6969, 0xFCC3BDBD, 0x975CA3A3, 0x055EE8E8, 0x7AD0EDED, + 0xAC87D1D1, 0x7F8E0505, 0xD5BA6464, 0x1AA8A5A5, 0x4BB72626, 0x0EB9BEBE, 0xA7608787, 0x5AF8D5D5, + 0x28223636, 0x14111B1B, 0x3FDE7575, 0x2979D9D9, 0x88AAEEEE, 0x3C332D2D, 0x4C5F7979, 0x02B6B7B7, + 0xB896CACA, 0xDA583535, 0xB09CC4C4, 0x17FC4343, 0x551A8484, 0x1FF64D4D, 0x8A1C5959, 0x7D38B2B2, + 0x57AC3333, 0xC718CFCF, 0x8DF40606, 0x74695353, 0xB7749B9B, 0xC4F59797, 0x9F56ADAD, 0x72DAE3E3, + 0x7ED5EAEA, 0x154AF4F4, 0x229E8F8F, 0x12A2ABAB, 0x584E6262, 0x07E85F5F, 0x99E51D1D, 0x34392323, + 0x6EC1F6F6, 0x50446C6C, 0xDE5D3232, 0x68724646, 0x6526A0A0, 0xBC93CDCD, 0xDB03DADA, 0xF8C6BABA, + 0xC8FA9E9E, 0xA882D6D6, 0x2BCF6E6E, 0x40507070, 0xDCEB8585, 0xFE750A0A, 0x328A9393, 0xA48DDFDF, + 0xCA4C2929, 0x10141C1C, 0x2173D7D7, 0xF0CCB4B4, 0xD309D4D4, 0x5D108A8A, 0x0FE25151, 0x00000000, + 0x6F9A1919, 0x9DE01A1A, 0x368F9494, 0x42E6C7C7, 0x4AECC9C9, 0x5EFDD2D2, 0xC1AB7F7F, 0xE0D8A8A8 + ); + + /** + * M-Table + * + * @var array + * @access private + */ + var $m2 = array( + 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA, + 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7, + 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783, + 0x2430243C, 0x510F51E2, 0xBAF8BAC6, 0x4A1B4AF3, 0xBF87BF48, 0x0DFA0D70, 0xB006B0B3, 0x753F75DE, + 0xD25ED2FD, 0x7DBA7D20, 0x66AE6631, 0x3A5B3AA3, 0x598A591C, 0x00000000, 0xCDBCCD93, 0x1A9D1AE0, + 0xAE6DAE2C, 0x7FC17FAB, 0x2BB12BC7, 0xBE0EBEB9, 0xE080E0A0, 0x8A5D8A10, 0x3BD23B52, 0x64D564BA, + 0xD8A0D888, 0xE784E7A5, 0x5F075FE8, 0x1B141B11, 0x2CB52CC2, 0xFC90FCB4, 0x312C3127, 0x80A38065, + 0x73B2732A, 0x0C730C81, 0x794C795F, 0x6B546B41, 0x4B924B02, 0x53745369, 0x9436948F, 0x8351831F, + 0x2A382A36, 0xC4B0C49C, 0x22BD22C8, 0xD55AD5F8, 0xBDFCBDC3, 0x48604878, 0xFF62FFCE, 0x4C964C07, + 0x416C4177, 0xC742C7E6, 0xEBF7EB24, 0x1C101C14, 0x5D7C5D63, 0x36283622, 0x672767C0, 0xE98CE9AF, + 0x441344F9, 0x149514EA, 0xF59CF5BB, 0xCFC7CF18, 0x3F243F2D, 0xC046C0E3, 0x723B72DB, 0x5470546C, + 0x29CA294C, 0xF0E3F035, 0x088508FE, 0xC6CBC617, 0xF311F34F, 0x8CD08CE4, 0xA493A459, 0xCAB8CA96, + 0x68A6683B, 0xB883B84D, 0x38203828, 0xE5FFE52E, 0xAD9FAD56, 0x0B770B84, 0xC8C3C81D, 0x99CC99FF, + 0x580358ED, 0x196F199A, 0x0E080E0A, 0x95BF957E, 0x70407050, 0xF7E7F730, 0x6E2B6ECF, 0x1FE21F6E, + 0xB579B53D, 0x090C090F, 0x61AA6134, 0x57825716, 0x9F419F0B, 0x9D3A9D80, 0x11EA1164, 0x25B925CD, + 0xAFE4AFDD, 0x459A4508, 0xDFA4DF8D, 0xA397A35C, 0xEA7EEAD5, 0x35DA3558, 0xED7AEDD0, 0x431743FC, + 0xF866F8CB, 0xFB94FBB1, 0x37A137D3, 0xFA1DFA40, 0xC23DC268, 0xB4F0B4CC, 0x32DE325D, 0x9CB39C71, + 0x560B56E7, 0xE372E3DA, 0x87A78760, 0x151C151B, 0xF9EFF93A, 0x63D163BF, 0x345334A9, 0x9A3E9A85, + 0xB18FB142, 0x7C337CD1, 0x8826889B, 0x3D5F3DA6, 0xA1ECA1D7, 0xE476E4DF, 0x812A8194, 0x91499101, + 0x0F810FFB, 0xEE88EEAA, 0x16EE1661, 0xD721D773, 0x97C497F5, 0xA51AA5A8, 0xFEEBFE3F, 0x6DD96DB5, + 0x78C578AE, 0xC539C56D, 0x1D991DE5, 0x76CD76A4, 0x3EAD3EDC, 0xCB31CB67, 0xB68BB647, 0xEF01EF5B, + 0x1218121E, 0x602360C5, 0x6ADD6AB0, 0x4D1F4DF6, 0xCE4ECEE9, 0xDE2DDE7C, 0x55F9559D, 0x7E487E5A, + 0x214F21B2, 0x03F2037A, 0xA065A026, 0x5E8E5E19, 0x5A785A66, 0x655C654B, 0x6258624E, 0xFD19FD45, + 0x068D06F4, 0x40E54086, 0xF298F2BE, 0x335733AC, 0x17671790, 0x057F058E, 0xE805E85E, 0x4F644F7D, + 0x89AF896A, 0x10631095, 0x74B6742F, 0x0AFE0A75, 0x5CF55C92, 0x9BB79B74, 0x2D3C2D33, 0x30A530D6, + 0x2ECE2E49, 0x49E94989, 0x46684672, 0x77447755, 0xA8E0A8D8, 0x964D9604, 0x284328BD, 0xA969A929, + 0xD929D979, 0x862E8691, 0xD1ACD187, 0xF415F44A, 0x8D598D15, 0xD6A8D682, 0xB90AB9BC, 0x429E420D, + 0xF66EF6C1, 0x2F472FB8, 0xDDDFDD06, 0x23342339, 0xCC35CC62, 0xF16AF1C4, 0xC1CFC112, 0x85DC85EB, + 0x8F228F9E, 0x71C971A1, 0x90C090F0, 0xAA9BAA53, 0x018901F1, 0x8BD48BE1, 0x4EED4E8C, 0x8EAB8E6F, + 0xAB12ABA2, 0x6FA26F3E, 0xE60DE654, 0xDB52DBF2, 0x92BB927B, 0xB702B7B6, 0x692F69CA, 0x39A939D9, + 0xD3D7D30C, 0xA761A723, 0xA21EA2AD, 0xC3B4C399, 0x6C506C44, 0x07040705, 0x04F6047F, 0x27C22746, + 0xAC16ACA7, 0xD025D076, 0x50865013, 0xDC56DCF7, 0x8455841A, 0xE109E151, 0x7ABE7A25, 0x139113EF + ); + + /** + * M-Table + * + * @var array + * @access private + */ + var $m3 = array( + 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF, + 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836, + 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77, + 0xBD2843BD, 0x32BC7532, 0xD47B37D4, 0x9B88269B, 0x700DFA70, 0xF94413F9, 0xB1FB94B1, 0x5A7E485A, + 0x7A03F27A, 0xE48CD0E4, 0x47B68B47, 0x3C24303C, 0xA5E784A5, 0x416B5441, 0x06DDDF06, 0xC56023C5, + 0x45FD1945, 0xA33A5BA3, 0x68C23D68, 0x158D5915, 0x21ECF321, 0x3166AE31, 0x3E6FA23E, 0x16578216, + 0x95106395, 0x5BEF015B, 0x4DB8834D, 0x91862E91, 0xB56DD9B5, 0x1F83511F, 0x53AA9B53, 0x635D7C63, + 0x3B68A63B, 0x3FFEEB3F, 0xD630A5D6, 0x257ABE25, 0xA7AC16A7, 0x0F090C0F, 0x35F0E335, 0x23A76123, + 0xF090C0F0, 0xAFE98CAF, 0x809D3A80, 0x925CF592, 0x810C7381, 0x27312C27, 0x76D02576, 0xE7560BE7, + 0x7B92BB7B, 0xE9CE4EE9, 0xF10189F1, 0x9F1E6B9F, 0xA93453A9, 0xC4F16AC4, 0x99C3B499, 0x975BF197, + 0x8347E183, 0x6B18E66B, 0xC822BDC8, 0x0E98450E, 0x6E1FE26E, 0xC9B3F4C9, 0x2F74B62F, 0xCBF866CB, + 0xFF99CCFF, 0xEA1495EA, 0xED5803ED, 0xF7DC56F7, 0xE18BD4E1, 0x1B151C1B, 0xADA21EAD, 0x0CD3D70C, + 0x2BE2FB2B, 0x1DC8C31D, 0x195E8E19, 0xC22CB5C2, 0x8949E989, 0x12C1CF12, 0x7E95BF7E, 0x207DBA20, + 0x6411EA64, 0x840B7784, 0x6DC5396D, 0x6A89AF6A, 0xD17C33D1, 0xA171C9A1, 0xCEFF62CE, 0x37BB7137, + 0xFB0F81FB, 0x3DB5793D, 0x51E10951, 0xDC3EADDC, 0x2D3F242D, 0xA476CDA4, 0x9D55F99D, 0xEE82D8EE, + 0x8640E586, 0xAE78C5AE, 0xCD25B9CD, 0x04964D04, 0x55774455, 0x0A0E080A, 0x13508613, 0x30F7E730, + 0xD337A1D3, 0x40FA1D40, 0x3461AA34, 0x8C4EED8C, 0xB3B006B3, 0x6C54706C, 0x2A73B22A, 0x523BD252, + 0x0B9F410B, 0x8B027B8B, 0x88D8A088, 0x4FF3114F, 0x67CB3167, 0x4627C246, 0xC06727C0, 0xB4FC90B4, + 0x28382028, 0x7F04F67F, 0x78486078, 0x2EE5FF2E, 0x074C9607, 0x4B655C4B, 0xC72BB1C7, 0x6F8EAB6F, + 0x0D429E0D, 0xBBF59CBB, 0xF2DB52F2, 0xF34A1BF3, 0xA63D5FA6, 0x59A49359, 0xBCB90ABC, 0x3AF9EF3A, + 0xEF1391EF, 0xFE0885FE, 0x01914901, 0x6116EE61, 0x7CDE2D7C, 0xB2214FB2, 0x42B18F42, 0xDB723BDB, + 0xB82F47B8, 0x48BF8748, 0x2CAE6D2C, 0xE3C046E3, 0x573CD657, 0x859A3E85, 0x29A96929, 0x7D4F647D, + 0x94812A94, 0x492ECE49, 0x17C6CB17, 0xCA692FCA, 0xC3BDFCC3, 0x5CA3975C, 0x5EE8055E, 0xD0ED7AD0, + 0x87D1AC87, 0x8E057F8E, 0xBA64D5BA, 0xA8A51AA8, 0xB7264BB7, 0xB9BE0EB9, 0x6087A760, 0xF8D55AF8, + 0x22362822, 0x111B1411, 0xDE753FDE, 0x79D92979, 0xAAEE88AA, 0x332D3C33, 0x5F794C5F, 0xB6B702B6, + 0x96CAB896, 0x5835DA58, 0x9CC4B09C, 0xFC4317FC, 0x1A84551A, 0xF64D1FF6, 0x1C598A1C, 0x38B27D38, + 0xAC3357AC, 0x18CFC718, 0xF4068DF4, 0x69537469, 0x749BB774, 0xF597C4F5, 0x56AD9F56, 0xDAE372DA, + 0xD5EA7ED5, 0x4AF4154A, 0x9E8F229E, 0xA2AB12A2, 0x4E62584E, 0xE85F07E8, 0xE51D99E5, 0x39233439, + 0xC1F66EC1, 0x446C5044, 0x5D32DE5D, 0x72466872, 0x26A06526, 0x93CDBC93, 0x03DADB03, 0xC6BAF8C6, + 0xFA9EC8FA, 0x82D6A882, 0xCF6E2BCF, 0x50704050, 0xEB85DCEB, 0x750AFE75, 0x8A93328A, 0x8DDFA48D, + 0x4C29CA4C, 0x141C1014, 0x73D72173, 0xCCB4F0CC, 0x09D4D309, 0x108A5D10, 0xE2510FE2, 0x00000000, + 0x9A196F9A, 0xE01A9DE0, 0x8F94368F, 0xE6C742E6, 0xECC94AEC, 0xFDD25EFD, 0xAB7FC1AB, 0xD8A8E0D8 + ); + + /** + * The Key Schedule Array + * + * @var array + * @access private + */ + var $K = array(); + + /** + * The Key depended S-Table 0 + * + * @var array + * @access private + */ + var $S0 = array(); + + /** + * The Key depended S-Table 1 + * + * @var array + * @access private + */ + var $S1 = array(); + + /** + * The Key depended S-Table 2 + * + * @var array + * @access private + */ + var $S2 = array(); + + /** + * The Key depended S-Table 3 + * + * @var array + * @access private + */ + var $S3 = array(); + + /** + * Holds the last used key + * + * @var array + * @access private + */ + var $kl; + + /** + * The Key Length (in bytes) + * + * @see Crypt_Twofish::setKeyLength() + * @var int + * @access private + */ + var $key_length = 16; + + /** + * Sets the key length. + * + * Valid key lengths are 128, 192 or 256 bits + * + * @access public + * @param int $length + */ + function setKeyLength($length) + { + switch (true) { + case $length <= 128: + $this->key_length = 16; + break; + case $length <= 192: + $this->key_length = 24; + break; + default: + $this->key_length = 32; + } + + parent::setKeyLength($length); + } + + /** + * Setup the key (expansion) + * + * @see Crypt_Base::_setupKey() + * @access private + */ + function _setupKey() + { + if (isset($this->kl['key']) && $this->key === $this->kl['key']) { + // already expanded + return; + } + $this->kl = array('key' => $this->key); + + /* Key expanding and generating the key-depended s-boxes */ + $le_longs = unpack('V*', $this->key); + $key = unpack('C*', $this->key); + $m0 = $this->m0; + $m1 = $this->m1; + $m2 = $this->m2; + $m3 = $this->m3; + $q0 = $this->q0; + $q1 = $this->q1; + + $K = $S0 = $S1 = $S2 = $S3 = array(); + + switch (strlen($this->key)) { + case 16: + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]); + for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { + $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^ + $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^ + $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^ + $m3[$q1[$q1[$i] ^ $key[12]] ^ $key[4]]; + $B = $m0[$q0[$q0[$j] ^ $key[13]] ^ $key[5]] ^ + $m1[$q0[$q1[$j] ^ $key[14]] ^ $key[6]] ^ + $m2[$q1[$q0[$j] ^ $key[15]] ^ $key[7]] ^ + $m3[$q1[$q1[$j] ^ $key[16]] ^ $key[8]]; + $B = ($B << 8) | ($B >> 24 & 0xff); + $K[] = $A+= $B; + $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); + } + for ($i = 0; $i < 256; ++$i) { + $S0[$i] = $m0[$q0[$q0[$i] ^ $s4] ^ $s0]; + $S1[$i] = $m1[$q0[$q1[$i] ^ $s5] ^ $s1]; + $S2[$i] = $m2[$q1[$q0[$i] ^ $s6] ^ $s2]; + $S3[$i] = $m3[$q1[$q1[$i] ^ $s7] ^ $s3]; + } + break; + case 24: + list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]); + for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { + $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ + $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ + $m2[$q1[$q0[$q0[$i] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ + $m3[$q1[$q1[$q0[$i] ^ $key[20]] ^ $key[12]] ^ $key[4]]; + $B = $m0[$q0[$q0[$q1[$j] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^ + $m1[$q0[$q1[$q1[$j] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^ + $m2[$q1[$q0[$q0[$j] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^ + $m3[$q1[$q1[$q0[$j] ^ $key[24]] ^ $key[16]] ^ $key[8]]; + $B = ($B << 8) | ($B >> 24 & 0xff); + $K[] = $A+= $B; + $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); + } + for ($i = 0; $i < 256; ++$i) { + $S0[$i] = $m0[$q0[$q0[$q1[$i] ^ $s8] ^ $s4] ^ $s0]; + $S1[$i] = $m1[$q0[$q1[$q1[$i] ^ $s9] ^ $s5] ^ $s1]; + $S2[$i] = $m2[$q1[$q0[$q0[$i] ^ $sa] ^ $s6] ^ $s2]; + $S3[$i] = $m3[$q1[$q1[$q0[$i] ^ $sb] ^ $s7] ^ $s3]; + } + break; + default: // 32 + list($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]); + list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]); + list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]); + list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]); + for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { + $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ + $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ + $m2[$q1[$q0[$q0[$q0[$i] ^ $key[27]] ^ $key[19]] ^ $key[11]] ^ $key[3]] ^ + $m3[$q1[$q1[$q0[$q1[$i] ^ $key[28]] ^ $key[20]] ^ $key[12]] ^ $key[4]]; + $B = $m0[$q0[$q0[$q1[$q1[$j] ^ $key[29]] ^ $key[21]] ^ $key[13]] ^ $key[5]] ^ + $m1[$q0[$q1[$q1[$q0[$j] ^ $key[30]] ^ $key[22]] ^ $key[14]] ^ $key[6]] ^ + $m2[$q1[$q0[$q0[$q0[$j] ^ $key[31]] ^ $key[23]] ^ $key[15]] ^ $key[7]] ^ + $m3[$q1[$q1[$q0[$q1[$j] ^ $key[32]] ^ $key[24]] ^ $key[16]] ^ $key[8]]; + $B = ($B << 8) | ($B >> 24 & 0xff); + $K[] = $A+= $B; + $K[] = (($A+= $B) << 9 | $A >> 23 & 0x1ff); + } + for ($i = 0; $i < 256; ++$i) { + $S0[$i] = $m0[$q0[$q0[$q1[$q1[$i] ^ $sc] ^ $s8] ^ $s4] ^ $s0]; + $S1[$i] = $m1[$q0[$q1[$q1[$q0[$i] ^ $sd] ^ $s9] ^ $s5] ^ $s1]; + $S2[$i] = $m2[$q1[$q0[$q0[$q0[$i] ^ $se] ^ $sa] ^ $s6] ^ $s2]; + $S3[$i] = $m3[$q1[$q1[$q0[$q1[$i] ^ $sf] ^ $sb] ^ $s7] ^ $s3]; + } + } + + $this->K = $K; + $this->S0 = $S0; + $this->S1 = $S1; + $this->S2 = $S2; + $this->S3 = $S3; + } + + /** + * _mdsrem function using by the twofish cipher algorithm + * + * @access private + * @param string $A + * @param string $B + * @return array + */ + function _mdsrem($A, $B) + { + // No gain by unrolling this loop. + for ($i = 0; $i < 8; ++$i) { + // Get most significant coefficient. + $t = 0xff & ($B >> 24); + + // Shift the others up. + $B = ($B << 8) | (0xff & ($A >> 24)); + $A<<= 8; + + $u = $t << 1; + + // Subtract the modular polynomial on overflow. + if ($t & 0x80) { + $u^= 0x14d; + } + + // Remove t * (a * x^2 + 1). + $B ^= $t ^ ($u << 16); + + // Form u = a*t + t/a = t*(a + 1/a). + $u^= 0x7fffffff & ($t >> 1); + + // Add the modular polynomial on underflow. + if ($t & 0x01) { + $u^= 0xa6 ; + } + + // Remove t * (a + 1/a) * (x^3 + x). + $B^= ($u << 24) | ($u << 8); + } + + return array( + 0xff & $B >> 24, + 0xff & $B >> 16, + 0xff & $B >> 8, + 0xff & $B); + } + + /** + * Encrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _encryptBlock($in) + { + $S0 = $this->S0; + $S1 = $this->S1; + $S2 = $this->S2; + $S3 = $this->S3; + $K = $this->K; + + $in = unpack("V4", $in); + $R0 = $K[0] ^ $in[1]; + $R1 = $K[1] ^ $in[2]; + $R2 = $K[2] ^ $in[3]; + $R3 = $K[3] ^ $in[4]; + + $ki = 7; + while ($ki < 39) { + $t0 = $S0[ $R0 & 0xff] ^ + $S1[($R0 >> 8) & 0xff] ^ + $S2[($R0 >> 16) & 0xff] ^ + $S3[($R0 >> 24) & 0xff]; + $t1 = $S0[($R1 >> 24) & 0xff] ^ + $S1[ $R1 & 0xff] ^ + $S2[($R1 >> 8) & 0xff] ^ + $S3[($R1 >> 16) & 0xff]; + $R2^= $t0 + $t1 + $K[++$ki]; + $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31); + $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]); + + $t0 = $S0[ $R2 & 0xff] ^ + $S1[($R2 >> 8) & 0xff] ^ + $S2[($R2 >> 16) & 0xff] ^ + $S3[($R2 >> 24) & 0xff]; + $t1 = $S0[($R3 >> 24) & 0xff] ^ + $S1[ $R3 & 0xff] ^ + $S2[($R3 >> 8) & 0xff] ^ + $S3[($R3 >> 16) & 0xff]; + $R0^= ($t0 + $t1 + $K[++$ki]); + $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31); + $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + $K[++$ki]); + } + + // @codingStandardsIgnoreStart + return pack("V4", $K[4] ^ $R2, + $K[5] ^ $R3, + $K[6] ^ $R0, + $K[7] ^ $R1); + // @codingStandardsIgnoreEnd + } + + /** + * Decrypts a block + * + * @access private + * @param string $in + * @return string + */ + function _decryptBlock($in) + { + $S0 = $this->S0; + $S1 = $this->S1; + $S2 = $this->S2; + $S3 = $this->S3; + $K = $this->K; + + $in = unpack("V4", $in); + $R0 = $K[4] ^ $in[1]; + $R1 = $K[5] ^ $in[2]; + $R2 = $K[6] ^ $in[3]; + $R3 = $K[7] ^ $in[4]; + + $ki = 40; + while ($ki > 8) { + $t0 = $S0[$R0 & 0xff] ^ + $S1[$R0 >> 8 & 0xff] ^ + $S2[$R0 >> 16 & 0xff] ^ + $S3[$R0 >> 24 & 0xff]; + $t1 = $S0[$R1 >> 24 & 0xff] ^ + $S1[$R1 & 0xff] ^ + $S2[$R1 >> 8 & 0xff] ^ + $S3[$R1 >> 16 & 0xff]; + $R3^= $t0 + ($t1 << 1) + $K[--$ki]; + $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; + $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + $K[--$ki]); + + $t0 = $S0[$R2 & 0xff] ^ + $S1[$R2 >> 8 & 0xff] ^ + $S2[$R2 >> 16 & 0xff] ^ + $S3[$R2 >> 24 & 0xff]; + $t1 = $S0[$R3 >> 24 & 0xff] ^ + $S1[$R3 & 0xff] ^ + $S2[$R3 >> 8 & 0xff] ^ + $S3[$R3 >> 16 & 0xff]; + $R1^= $t0 + ($t1 << 1) + $K[--$ki]; + $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; + $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + $K[--$ki]); + } + + // @codingStandardsIgnoreStart + return pack("V4", $K[0] ^ $R2, + $K[1] ^ $R3, + $K[2] ^ $R0, + $K[3] ^ $R1); + // @codingStandardsIgnoreEnd + } + + /** + * Setup the performance-optimized function for de/encrypt() + * + * @see Crypt_Base::_setupInlineCrypt() + * @access private + */ + function _setupInlineCrypt() + { + $lambda_functions =& Crypt_Twofish::_getLambdaFunctions(); + + // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one. + // (Currently, for Crypt_Twofish, one generated $lambda_function cost on php5.5@32bit ~140kb unfreeable mem and ~240kb on php5.5@64bit) + $gen_hi_opt_code = (bool)(count($lambda_functions) < 10); + + // Generation of a unique hash for our generated code + $code_hash = "Crypt_Twofish, {$this->mode}"; + if ($gen_hi_opt_code) { + $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key); + } + + if (!isset($lambda_functions[$code_hash])) { + switch (true) { + case $gen_hi_opt_code: + $K = $this->K; + $init_crypt = ' + static $S0, $S1, $S2, $S3; + if (!$S0) { + for ($i = 0; $i < 256; ++$i) { + $S0[] = (int)$self->S0[$i]; + $S1[] = (int)$self->S1[$i]; + $S2[] = (int)$self->S2[$i]; + $S3[] = (int)$self->S3[$i]; + } + } + '; + break; + default: + $K = array(); + for ($i = 0; $i < 40; ++$i) { + $K[] = '$K_' . $i; + } + $init_crypt = ' + $S0 = $self->S0; + $S1 = $self->S1; + $S2 = $self->S2; + $S3 = $self->S3; + list(' . implode(',', $K) . ') = $self->K; + '; + } + + // Generating encrypt code: + $encrypt_block = ' + $in = unpack("V4", $in); + $R0 = '.$K[0].' ^ $in[1]; + $R1 = '.$K[1].' ^ $in[2]; + $R2 = '.$K[2].' ^ $in[3]; + $R3 = '.$K[3].' ^ $in[4]; + '; + for ($ki = 7, $i = 0; $i < 8; ++$i) { + $encrypt_block.= ' + $t0 = $S0[ $R0 & 0xff] ^ + $S1[($R0 >> 8) & 0xff] ^ + $S2[($R0 >> 16) & 0xff] ^ + $S3[($R0 >> 24) & 0xff]; + $t1 = $S0[($R1 >> 24) & 0xff] ^ + $S1[ $R1 & 0xff] ^ + $S2[($R1 >> 8) & 0xff] ^ + $S3[($R1 >> 16) & 0xff]; + $R2^= ($t0 + $t1 + '.$K[++$ki].'); + $R2 = ($R2 >> 1 & 0x7fffffff) | ($R2 << 31); + $R3 = ((($R3 >> 31) & 1) | ($R3 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].'); + + $t0 = $S0[ $R2 & 0xff] ^ + $S1[($R2 >> 8) & 0xff] ^ + $S2[($R2 >> 16) & 0xff] ^ + $S3[($R2 >> 24) & 0xff]; + $t1 = $S0[($R3 >> 24) & 0xff] ^ + $S1[ $R3 & 0xff] ^ + $S2[($R3 >> 8) & 0xff] ^ + $S3[($R3 >> 16) & 0xff]; + $R0^= ($t0 + $t1 + '.$K[++$ki].'); + $R0 = ($R0 >> 1 & 0x7fffffff) | ($R0 << 31); + $R1 = ((($R1 >> 31) & 1) | ($R1 << 1)) ^ ($t0 + ($t1 << 1) + '.$K[++$ki].'); + '; + } + $encrypt_block.= ' + $in = pack("V4", '.$K[4].' ^ $R2, + '.$K[5].' ^ $R3, + '.$K[6].' ^ $R0, + '.$K[7].' ^ $R1); + '; + + // Generating decrypt code: + $decrypt_block = ' + $in = unpack("V4", $in); + $R0 = '.$K[4].' ^ $in[1]; + $R1 = '.$K[5].' ^ $in[2]; + $R2 = '.$K[6].' ^ $in[3]; + $R3 = '.$K[7].' ^ $in[4]; + '; + for ($ki = 40, $i = 0; $i < 8; ++$i) { + $decrypt_block.= ' + $t0 = $S0[$R0 & 0xff] ^ + $S1[$R0 >> 8 & 0xff] ^ + $S2[$R0 >> 16 & 0xff] ^ + $S3[$R0 >> 24 & 0xff]; + $t1 = $S0[$R1 >> 24 & 0xff] ^ + $S1[$R1 & 0xff] ^ + $S2[$R1 >> 8 & 0xff] ^ + $S3[$R1 >> 16 & 0xff]; + $R3^= $t0 + ($t1 << 1) + '.$K[--$ki].'; + $R3 = $R3 >> 1 & 0x7fffffff | $R3 << 31; + $R2 = ($R2 >> 31 & 0x1 | $R2 << 1) ^ ($t0 + $t1 + '.$K[--$ki].'); + + $t0 = $S0[$R2 & 0xff] ^ + $S1[$R2 >> 8 & 0xff] ^ + $S2[$R2 >> 16 & 0xff] ^ + $S3[$R2 >> 24 & 0xff]; + $t1 = $S0[$R3 >> 24 & 0xff] ^ + $S1[$R3 & 0xff] ^ + $S2[$R3 >> 8 & 0xff] ^ + $S3[$R3 >> 16 & 0xff]; + $R1^= $t0 + ($t1 << 1) + '.$K[--$ki].'; + $R1 = $R1 >> 1 & 0x7fffffff | $R1 << 31; + $R0 = ($R0 >> 31 & 0x1 | $R0 << 1) ^ ($t0 + $t1 + '.$K[--$ki].'); + '; + } + $decrypt_block.= ' + $in = pack("V4", '.$K[0].' ^ $R2, + '.$K[1].' ^ $R3, + '.$K[2].' ^ $R0, + '.$K[3].' ^ $R1); + '; + + $lambda_functions[$code_hash] = $this->_createInlineCryptFunction( + array( + 'init_crypt' => $init_crypt, + 'init_encrypt' => '', + 'init_decrypt' => '', + 'encrypt_block' => $encrypt_block, + 'decrypt_block' => $decrypt_block + ) + ); + } + $this->inline_crypt = $lambda_functions[$code_hash]; + } +} diff --git a/ipaylinks_statement/File/ANSI.php b/ipaylinks_statement/File/ANSI.php new file mode 100644 index 00000000..0cbed173 --- /dev/null +++ b/ipaylinks_statement/File/ANSI.php @@ -0,0 +1,604 @@ + + * @copyright 2012 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Pure-PHP ANSI Decoder + * + * @package File_ANSI + * @author Jim Wigginton + * @access public + */ +class File_ANSI +{ + /** + * Max Width + * + * @var int + * @access private + */ + var $max_x; + + /** + * Max Height + * + * @var int + * @access private + */ + var $max_y; + + /** + * Max History + * + * @var int + * @access private + */ + var $max_history; + + /** + * History + * + * @var array + * @access private + */ + var $history; + + /** + * History Attributes + * + * @var array + * @access private + */ + var $history_attrs; + + /** + * Current Column + * + * @var int + * @access private + */ + var $x; + + /** + * Current Row + * + * @var int + * @access private + */ + var $y; + + /** + * Old Column + * + * @var int + * @access private + */ + var $old_x; + + /** + * Old Row + * + * @var int + * @access private + */ + var $old_y; + + /** + * An empty attribute cell + * + * @var object + * @access private + */ + var $base_attr_cell; + + /** + * The current attribute cell + * + * @var object + * @access private + */ + var $attr_cell; + + /** + * An empty attribute row + * + * @var array + * @access private + */ + var $attr_row; + + /** + * The current screen text + * + * @var array + * @access private + */ + var $screen; + + /** + * The current screen attributes + * + * @var array + * @access private + */ + var $attrs; + + /** + * Current ANSI code + * + * @var string + * @access private + */ + var $ansi; + + /** + * Tokenization + * + * @var array + * @access private + */ + var $tokenization; + + /** + * Default Constructor. + * + * @return File_ANSI + * @access public + */ + function __construct() + { + $attr_cell = new stdClass(); + $attr_cell->bold = false; + $attr_cell->underline = false; + $attr_cell->blink = false; + $attr_cell->background = 'black'; + $attr_cell->foreground = 'white'; + $attr_cell->reverse = false; + $this->base_attr_cell = clone($attr_cell); + $this->attr_cell = clone($attr_cell); + + $this->setHistory(200); + $this->setDimensions(80, 24); + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function File_ANSI() + { + $this->__construct($mode); + } + + /** + * Set terminal width and height + * + * Resets the screen as well + * + * @param int $x + * @param int $y + * @access public + */ + function setDimensions($x, $y) + { + $this->max_x = $x - 1; + $this->max_y = $y - 1; + $this->x = $this->y = 0; + $this->history = $this->history_attrs = array(); + $this->attr_row = array_fill(0, $this->max_x + 2, $this->base_attr_cell); + $this->screen = array_fill(0, $this->max_y + 1, ''); + $this->attrs = array_fill(0, $this->max_y + 1, $this->attr_row); + $this->ansi = ''; + } + + /** + * Set the number of lines that should be logged past the terminal height + * + * @param int $x + * @param int $y + * @access public + */ + function setHistory($history) + { + $this->max_history = $history; + } + + /** + * Load a string + * + * @param string $source + * @access public + */ + function loadString($source) + { + $this->setDimensions($this->max_x + 1, $this->max_y + 1); + $this->appendString($source); + } + + /** + * Appdend a string + * + * @param string $source + * @access public + */ + function appendString($source) + { + $this->tokenization = array(''); + for ($i = 0; $i < strlen($source); $i++) { + if (strlen($this->ansi)) { + $this->ansi.= $source[$i]; + $chr = ord($source[$i]); + // http://en.wikipedia.org/wiki/ANSI_escape_code#Sequence_elements + // single character CSI's not currently supported + switch (true) { + case $this->ansi == "\x1B=": + $this->ansi = ''; + continue 2; + case strlen($this->ansi) == 2 && $chr >= 64 && $chr <= 95 && $chr != ord('['): + case strlen($this->ansi) > 2 && $chr >= 64 && $chr <= 126: + break; + default: + continue 2; + } + $this->tokenization[] = $this->ansi; + $this->tokenization[] = ''; + // http://ascii-table.com/ansi-escape-sequences-vt-100.php + switch ($this->ansi) { + case "\x1B[H": // Move cursor to upper left corner + $this->old_x = $this->x; + $this->old_y = $this->y; + $this->x = $this->y = 0; + break; + case "\x1B[J": // Clear screen from cursor down + $this->history = array_merge($this->history, array_slice(array_splice($this->screen, $this->y + 1), 0, $this->old_y)); + $this->screen = array_merge($this->screen, array_fill($this->y, $this->max_y, '')); + + $this->history_attrs = array_merge($this->history_attrs, array_slice(array_splice($this->attrs, $this->y + 1), 0, $this->old_y)); + $this->attrs = array_merge($this->attrs, array_fill($this->y, $this->max_y, $this->attr_row)); + + if (count($this->history) == $this->max_history) { + array_shift($this->history); + array_shift($this->history_attrs); + } + case "\x1B[K": // Clear screen from cursor right + $this->screen[$this->y] = substr($this->screen[$this->y], 0, $this->x); + + array_splice($this->attrs[$this->y], $this->x + 1, $this->max_x - $this->x, array_fill($this->x, $this->max_x - $this->x - 1, $this->base_attr_cell)); + break; + case "\x1B[2K": // Clear entire line + $this->screen[$this->y] = str_repeat(' ', $this->x); + $this->attrs[$this->y] = $this->attr_row; + break; + case "\x1B[?1h": // set cursor key to application + case "\x1B[?25h": // show the cursor + case "\x1B(B": // set united states g0 character set + break; + case "\x1BE": // Move to next line + $this->_newLine(); + $this->x = 0; + break; + default: + switch (true) { + case preg_match('#\x1B\[(\d+)B#', $this->ansi, $match): // Move cursor down n lines + $this->old_y = $this->y; + $this->y+= $match[1]; + break; + case preg_match('#\x1B\[(\d+);(\d+)H#', $this->ansi, $match): // Move cursor to screen location v,h + $this->old_x = $this->x; + $this->old_y = $this->y; + $this->x = $match[2] - 1; + $this->y = $match[1] - 1; + break; + case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines + $this->old_x = $this->x; + $this->x+= $match[1]; + break; + case preg_match('#\x1B\[(\d+)D#', $this->ansi, $match): // Move cursor left n lines + $this->old_x = $this->x; + $this->x-= $match[1]; + if ($this->x < 0) { + $this->x = 0; + } + break; + case preg_match('#\x1B\[(\d+);(\d+)r#', $this->ansi, $match): // Set top and bottom lines of a window + break; + case preg_match('#\x1B\[(\d*(?:;\d*)*)m#', $this->ansi, $match): // character attributes + $attr_cell = &$this->attr_cell; + $mods = explode(';', $match[1]); + foreach ($mods as $mod) { + switch ($mod) { + case 0: // Turn off character attributes + $attr_cell = clone($this->base_attr_cell); + break; + case 1: // Turn bold mode on + $attr_cell->bold = true; + break; + case 4: // Turn underline mode on + $attr_cell->underline = true; + break; + case 5: // Turn blinking mode on + $attr_cell->blink = true; + break; + case 7: // Turn reverse video on + $attr_cell->reverse = !$attr_cell->reverse; + $temp = $attr_cell->background; + $attr_cell->background = $attr_cell->foreground; + $attr_cell->foreground = $temp; + break; + default: // set colors + //$front = $attr_cell->reverse ? &$attr_cell->background : &$attr_cell->foreground; + $front = &$attr_cell->{ $attr_cell->reverse ? 'background' : 'foreground' }; + //$back = $attr_cell->reverse ? &$attr_cell->foreground : &$attr_cell->background; + $back = &$attr_cell->{ $attr_cell->reverse ? 'foreground' : 'background' }; + switch ($mod) { + // @codingStandardsIgnoreStart + case 30: $front = 'black'; break; + case 31: $front = 'red'; break; + case 32: $front = 'green'; break; + case 33: $front = 'yellow'; break; + case 34: $front = 'blue'; break; + case 35: $front = 'magenta'; break; + case 36: $front = 'cyan'; break; + case 37: $front = 'white'; break; + + case 40: $back = 'black'; break; + case 41: $back = 'red'; break; + case 42: $back = 'green'; break; + case 43: $back = 'yellow'; break; + case 44: $back = 'blue'; break; + case 45: $back = 'magenta'; break; + case 46: $back = 'cyan'; break; + case 47: $back = 'white'; break; + // @codingStandardsIgnoreEnd + + default: + //user_error('Unsupported attribute: ' . $mod); + $this->ansi = ''; + break 2; + } + } + } + break; + default: + //user_error("{$this->ansi} is unsupported\r\n"); + } + } + $this->ansi = ''; + continue; + } + + $this->tokenization[count($this->tokenization) - 1].= $source[$i]; + switch ($source[$i]) { + case "\r": + $this->x = 0; + break; + case "\n": + $this->_newLine(); + break; + case "\x08": // backspace + if ($this->x) { + $this->x--; + $this->attrs[$this->y][$this->x] = clone($this->base_attr_cell); + $this->screen[$this->y] = substr_replace( + $this->screen[$this->y], + $source[$i], + $this->x, + 1 + ); + } + break; + case "\x0F": // shift + break; + case "\x1B": // start ANSI escape code + $this->tokenization[count($this->tokenization) - 1] = substr($this->tokenization[count($this->tokenization) - 1], 0, -1); + //if (!strlen($this->tokenization[count($this->tokenization) - 1])) { + // array_pop($this->tokenization); + //} + $this->ansi.= "\x1B"; + break; + default: + $this->attrs[$this->y][$this->x] = clone($this->attr_cell); + if ($this->x > strlen($this->screen[$this->y])) { + $this->screen[$this->y] = str_repeat(' ', $this->x); + } + $this->screen[$this->y] = substr_replace( + $this->screen[$this->y], + $source[$i], + $this->x, + 1 + ); + + if ($this->x > $this->max_x) { + $this->x = 0; + $this->_newLine(); + } else { + $this->x++; + } + } + } + } + + /** + * Add a new line + * + * Also update the $this->screen and $this->history buffers + * + * @access private + */ + function _newLine() + { + //if ($this->y < $this->max_y) { + // $this->y++; + //} + + while ($this->y >= $this->max_y) { + $this->history = array_merge($this->history, array(array_shift($this->screen))); + $this->screen[] = ''; + + $this->history_attrs = array_merge($this->history_attrs, array(array_shift($this->attrs))); + $this->attrs[] = $this->attr_row; + + if (count($this->history) >= $this->max_history) { + array_shift($this->history); + array_shift($this->history_attrs); + } + + $this->y--; + } + $this->y++; + } + + /** + * Returns the current coordinate without preformating + * + * @access private + * @return string + */ + function _processCoordinate($last_attr, $cur_attr, $char) + { + $output = ''; + + if ($last_attr != $cur_attr) { + $close = $open = ''; + if ($last_attr->foreground != $cur_attr->foreground) { + if ($cur_attr->foreground != 'white') { + $open.= ''; + } + if ($last_attr->foreground != 'white') { + $close = '' . $close; + } + } + if ($last_attr->background != $cur_attr->background) { + if ($cur_attr->background != 'black') { + $open.= ''; + } + if ($last_attr->background != 'black') { + $close = '' . $close; + } + } + if ($last_attr->bold != $cur_attr->bold) { + if ($cur_attr->bold) { + $open.= ''; + } else { + $close = '' . $close; + } + } + if ($last_attr->underline != $cur_attr->underline) { + if ($cur_attr->underline) { + $open.= ''; + } else { + $close = '' . $close; + } + } + if ($last_attr->blink != $cur_attr->blink) { + if ($cur_attr->blink) { + $open.= ''; + } else { + $close = '' . $close; + } + } + $output.= $close . $open; + } + + $output.= htmlspecialchars($char); + + return $output; + } + + /** + * Returns the current screen without preformating + * + * @access private + * @return string + */ + function _getScreen() + { + $output = ''; + $last_attr = $this->base_attr_cell; + for ($i = 0; $i <= $this->max_y; $i++) { + for ($j = 0; $j <= $this->max_x; $j++) { + $cur_attr = $this->attrs[$i][$j]; + $output.= $this->_processCoordinate($last_attr, $cur_attr, isset($this->screen[$i][$j]) ? $this->screen[$i][$j] : ''); + $last_attr = $this->attrs[$i][$j]; + } + $output.= "\r\n"; + } + $output = substr($output, 0, -2); + // close any remaining open tags + $output.= $this->_processCoordinate($last_attr, $this->base_attr_cell, ''); + return rtrim($output); + } + + /** + * Returns the current screen + * + * @access public + * @return string + */ + function getScreen() + { + return '
' . $this->_getScreen() . '
'; + } + + /** + * Returns the current screen and the x previous lines + * + * @access public + * @return string + */ + function getHistory() + { + $scrollback = ''; + $last_attr = $this->base_attr_cell; + for ($i = 0; $i < count($this->history); $i++) { + for ($j = 0; $j <= $this->max_x + 1; $j++) { + $cur_attr = $this->history_attrs[$i][$j]; + $scrollback.= $this->_processCoordinate($last_attr, $cur_attr, isset($this->history[$i][$j]) ? $this->history[$i][$j] : ''); + $last_attr = $this->history_attrs[$i][$j]; + } + $scrollback.= "\r\n"; + } + $base_attr_cell = $this->base_attr_cell; + $this->base_attr_cell = $last_attr; + $scrollback.= $this->_getScreen(); + $this->base_attr_cell = $base_attr_cell; + + return '
' . $scrollback . '
'; + } +} diff --git a/ipaylinks_statement/File/ASN1.php b/ipaylinks_statement/File/ASN1.php new file mode 100644 index 00000000..732bd9c6 --- /dev/null +++ b/ipaylinks_statement/File/ASN1.php @@ -0,0 +1,1473 @@ + + * @copyright 2012 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * Tag Classes + * + * @access private + * @link http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=12 + */ +define('FILE_ASN1_CLASS_UNIVERSAL', 0); +define('FILE_ASN1_CLASS_APPLICATION', 1); +define('FILE_ASN1_CLASS_CONTEXT_SPECIFIC', 2); +define('FILE_ASN1_CLASS_PRIVATE', 3); +/**#@-*/ + +/**#@+ + * Tag Classes + * + * @access private + * @link http://www.obj-sys.com/asn1tutorial/node124.html + */ +define('FILE_ASN1_TYPE_BOOLEAN', 1); +define('FILE_ASN1_TYPE_INTEGER', 2); +define('FILE_ASN1_TYPE_BIT_STRING', 3); +define('FILE_ASN1_TYPE_OCTET_STRING', 4); +define('FILE_ASN1_TYPE_NULL', 5); +define('FILE_ASN1_TYPE_OBJECT_IDENTIFIER', 6); +//define('FILE_ASN1_TYPE_OBJECT_DESCRIPTOR', 7); +//define('FILE_ASN1_TYPE_INSTANCE_OF', 8); // EXTERNAL +define('FILE_ASN1_TYPE_REAL', 9); +define('FILE_ASN1_TYPE_ENUMERATED', 10); +//define('FILE_ASN1_TYPE_EMBEDDED', 11); +define('FILE_ASN1_TYPE_UTF8_STRING', 12); +//define('FILE_ASN1_TYPE_RELATIVE_OID', 13); +define('FILE_ASN1_TYPE_SEQUENCE', 16); // SEQUENCE OF +define('FILE_ASN1_TYPE_SET', 17); // SET OF +/**#@-*/ +/**#@+ + * More Tag Classes + * + * @access private + * @link http://www.obj-sys.com/asn1tutorial/node10.html + */ +define('FILE_ASN1_TYPE_NUMERIC_STRING', 18); +define('FILE_ASN1_TYPE_PRINTABLE_STRING', 19); +define('FILE_ASN1_TYPE_TELETEX_STRING', 20); // T61String +define('FILE_ASN1_TYPE_VIDEOTEX_STRING', 21); +define('FILE_ASN1_TYPE_IA5_STRING', 22); +define('FILE_ASN1_TYPE_UTC_TIME', 23); +define('FILE_ASN1_TYPE_GENERALIZED_TIME', 24); +define('FILE_ASN1_TYPE_GRAPHIC_STRING', 25); +define('FILE_ASN1_TYPE_VISIBLE_STRING', 26); // ISO646String +define('FILE_ASN1_TYPE_GENERAL_STRING', 27); +define('FILE_ASN1_TYPE_UNIVERSAL_STRING', 28); +//define('FILE_ASN1_TYPE_CHARACTER_STRING', 29); +define('FILE_ASN1_TYPE_BMP_STRING', 30); +/**#@-*/ + +/**#@+ + * Tag Aliases + * + * These tags are kinda place holders for other tags. + * + * @access private + */ +define('FILE_ASN1_TYPE_CHOICE', -1); +define('FILE_ASN1_TYPE_ANY', -2); +/**#@-*/ + +/** + * ASN.1 Element + * + * Bypass normal encoding rules in File_ASN1::encodeDER() + * + * @package File_ASN1 + * @author Jim Wigginton + * @access public + */ +class File_ASN1_Element +{ + /** + * Raw element value + * + * @var string + * @access private + */ + var $element; + + /** + * Constructor + * + * @param string $encoded + * @return File_ASN1_Element + * @access public + */ + function __construct($encoded) + { + $this->element = $encoded; + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param int $mode + * @access public + */ + function File_ASN1_Element($encoded) + { + $this->__construct($encoded); + } +} + +/** + * Pure-PHP ASN.1 Parser + * + * @package File_ASN1 + * @author Jim Wigginton + * @access public + */ +class File_ASN1 +{ + /** + * ASN.1 object identifier + * + * @var array + * @access private + * @link http://en.wikipedia.org/wiki/Object_identifier + */ + var $oids = array(); + + /** + * Default date format + * + * @var string + * @access private + * @link http://php.net/class.datetime + */ + var $format = 'D, d M Y H:i:s O'; + + /** + * Default date format + * + * @var array + * @access private + * @see self::setTimeFormat() + * @see self::asn1map() + * @link http://php.net/class.datetime + */ + var $encoded; + + /** + * Filters + * + * If the mapping type is FILE_ASN1_TYPE_ANY what do we actually encode it as? + * + * @var array + * @access private + * @see self::_encode_der() + */ + var $filters; + + /** + * Type mapping table for the ANY type. + * + * Structured or unknown types are mapped to a FILE_ASN1_Element. + * Unambiguous types get the direct mapping (int/real/bool). + * Others are mapped as a choice, with an extra indexing level. + * + * @var array + * @access public + */ + var $ANYmap = array( + FILE_ASN1_TYPE_BOOLEAN => true, + FILE_ASN1_TYPE_INTEGER => true, + FILE_ASN1_TYPE_BIT_STRING => 'bitString', + FILE_ASN1_TYPE_OCTET_STRING => 'octetString', + FILE_ASN1_TYPE_NULL => 'null', + FILE_ASN1_TYPE_OBJECT_IDENTIFIER => 'objectIdentifier', + FILE_ASN1_TYPE_REAL => true, + FILE_ASN1_TYPE_ENUMERATED => 'enumerated', + FILE_ASN1_TYPE_UTF8_STRING => 'utf8String', + FILE_ASN1_TYPE_NUMERIC_STRING => 'numericString', + FILE_ASN1_TYPE_PRINTABLE_STRING => 'printableString', + FILE_ASN1_TYPE_TELETEX_STRING => 'teletexString', + FILE_ASN1_TYPE_VIDEOTEX_STRING => 'videotexString', + FILE_ASN1_TYPE_IA5_STRING => 'ia5String', + FILE_ASN1_TYPE_UTC_TIME => 'utcTime', + FILE_ASN1_TYPE_GENERALIZED_TIME => 'generalTime', + FILE_ASN1_TYPE_GRAPHIC_STRING => 'graphicString', + FILE_ASN1_TYPE_VISIBLE_STRING => 'visibleString', + FILE_ASN1_TYPE_GENERAL_STRING => 'generalString', + FILE_ASN1_TYPE_UNIVERSAL_STRING => 'universalString', + //FILE_ASN1_TYPE_CHARACTER_STRING => 'characterString', + FILE_ASN1_TYPE_BMP_STRING => 'bmpString' + ); + + /** + * String type to character size mapping table. + * + * Non-convertable types are absent from this table. + * size == 0 indicates variable length encoding. + * + * @var array + * @access public + */ + var $stringTypeSize = array( + FILE_ASN1_TYPE_UTF8_STRING => 0, + FILE_ASN1_TYPE_BMP_STRING => 2, + FILE_ASN1_TYPE_UNIVERSAL_STRING => 4, + FILE_ASN1_TYPE_PRINTABLE_STRING => 1, + FILE_ASN1_TYPE_TELETEX_STRING => 1, + FILE_ASN1_TYPE_IA5_STRING => 1, + FILE_ASN1_TYPE_VISIBLE_STRING => 1, + ); + + /** + * Default Constructor. + * + * @access public + */ + function __construct() + { + static $static_init = null; + if (!$static_init) { + $static_init = true; + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function File_ASN1() + { + $this->__construct($mode); + } + + /** + * Parse BER-encoding + * + * Serves a similar purpose to openssl's asn1parse + * + * @param string $encoded + * @return array + * @access public + */ + function decodeBER($encoded) + { + if (is_object($encoded) && strtolower(get_class($encoded)) == 'file_asn1_element') { + $encoded = $encoded->element; + } + + $this->encoded = $encoded; + // encapsulate in an array for BC with the old decodeBER + return array($this->_decode_ber($encoded)); + } + + /** + * Parse BER-encoding (Helper function) + * + * Sometimes we want to get the BER encoding of a particular tag. $start lets us do that without having to reencode. + * $encoded is passed by reference for the recursive calls done for FILE_ASN1_TYPE_BIT_STRING and + * FILE_ASN1_TYPE_OCTET_STRING. In those cases, the indefinite length is used. + * + * @param string $encoded + * @param int $start + * @param int $encoded_pos + * @return array + * @access private + */ + function _decode_ber($encoded, $start = 0, $encoded_pos = 0) + { + $current = array('start' => $start); + + $type = ord($encoded[$encoded_pos++]); + $start++; + + $constructed = ($type >> 5) & 1; + + $tag = $type & 0x1F; + if ($tag == 0x1F) { + $tag = 0; + // process septets (since the eighth bit is ignored, it's not an octet) + do { + $loop = ord($encoded[0]) >> 7; + $tag <<= 7; + $tag |= ord($encoded[$encoded_pos++]) & 0x7F; + $start++; + } while ($loop); + } + + // Length, as discussed in paragraph 8.1.3 of X.690-0207.pdf#page=13 + $length = ord($encoded[$encoded_pos++]); + $start++; + if ($length == 0x80) { // indefinite length + // "[A sender shall] use the indefinite form (see 8.1.3.6) if the encoding is constructed and is not all + // immediately available." -- paragraph 8.1.3.2.c + $length = strlen($encoded) - $encoded_pos; + } elseif ($length & 0x80) { // definite length, long form + // technically, the long form of the length can be represented by up to 126 octets (bytes), but we'll only + // support it up to four. + $length&= 0x7F; + $temp = substr($encoded, $encoded_pos, $length); + $encoded_pos += $length; + // tags of indefinte length don't really have a header length; this length includes the tag + $current+= array('headerlength' => $length + 2); + $start+= $length; + extract(unpack('Nlength', substr(str_pad($temp, 4, chr(0), STR_PAD_LEFT), -4))); + } else { + $current+= array('headerlength' => 2); + } + + if ($length > (strlen($encoded) - $encoded_pos)) { + return false; + } + + $content = substr($encoded, $encoded_pos, $length); + $content_pos = 0; + + // at this point $length can be overwritten. it's only accurate for definite length things as is + + /* Class is UNIVERSAL, APPLICATION, PRIVATE, or CONTEXT-SPECIFIC. The UNIVERSAL class is restricted to the ASN.1 + built-in types. It defines an application-independent data type that must be distinguishable from all other + data types. The other three classes are user defined. The APPLICATION class distinguishes data types that + have a wide, scattered use within a particular presentation context. PRIVATE distinguishes data types within + a particular organization or country. CONTEXT-SPECIFIC distinguishes members of a sequence or set, the + alternatives of a CHOICE, or universally tagged set members. Only the class number appears in braces for this + data type; the term CONTEXT-SPECIFIC does not appear. + + -- http://www.obj-sys.com/asn1tutorial/node12.html */ + $class = ($type >> 6) & 3; + switch ($class) { + case FILE_ASN1_CLASS_APPLICATION: + case FILE_ASN1_CLASS_PRIVATE: + case FILE_ASN1_CLASS_CONTEXT_SPECIFIC: + if (!$constructed) { + return array( + 'type' => $class, + 'constant' => $tag, + 'content' => $content, + 'length' => $length + $start - $current['start'] + ); + } + + $newcontent = array(); + $remainingLength = $length; + while ($remainingLength > 0) { + $temp = $this->_decode_ber($content, $start, $content_pos); + $length = $temp['length']; + // end-of-content octets - see paragraph 8.1.5 + if (substr($content, $content_pos + $length, 2) == "\0\0") { + $length+= 2; + $start+= $length; + $newcontent[] = $temp; + break; + } + $start+= $length; + $remainingLength-= $length; + $newcontent[] = $temp; + $content_pos += $length; + } + + return array( + 'type' => $class, + 'constant' => $tag, + // the array encapsulation is for BC with the old format + 'content' => $newcontent, + // the only time when $content['headerlength'] isn't defined is when the length is indefinite. + // the absence of $content['headerlength'] is how we know if something is indefinite or not. + // technically, it could be defined to be 2 and then another indicator could be used but whatever. + 'length' => $start - $current['start'] + ) + $current; + } + + $current+= array('type' => $tag); + + // decode UNIVERSAL tags + switch ($tag) { + case FILE_ASN1_TYPE_BOOLEAN: + // "The contents octets shall consist of a single octet." -- paragraph 8.2.1 + //if (strlen($content) != 1) { + // return false; + //} + $current['content'] = (bool) ord($content[$content_pos]); + break; + case FILE_ASN1_TYPE_INTEGER: + case FILE_ASN1_TYPE_ENUMERATED: + $current['content'] = new Math_BigInteger(substr($content, $content_pos), -256); + break; + case FILE_ASN1_TYPE_REAL: // not currently supported + return false; + case FILE_ASN1_TYPE_BIT_STRING: + // The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit, + // the number of unused bits in the final subsequent octet. The number shall be in the range zero to + // seven. + if (!$constructed) { + $current['content'] = substr($content, $content_pos); + } else { + $temp = $this->_decode_ber($content, $start, $content_pos); + $length-= (strlen($content) - $content_pos); + $last = count($temp) - 1; + for ($i = 0; $i < $last; $i++) { + // all subtags should be bit strings + //if ($temp[$i]['type'] != FILE_ASN1_TYPE_BIT_STRING) { + // return false; + //} + $current['content'].= substr($temp[$i]['content'], 1); + } + // all subtags should be bit strings + //if ($temp[$last]['type'] != FILE_ASN1_TYPE_BIT_STRING) { + // return false; + //} + $current['content'] = $temp[$last]['content'][0] . $current['content'] . substr($temp[$i]['content'], 1); + } + break; + case FILE_ASN1_TYPE_OCTET_STRING: + if (!$constructed) { + $current['content'] = substr($content, $content_pos); + } else { + $current['content'] = ''; + $length = 0; + while (substr($content, $content_pos, 2) != "\0\0") { + $temp = $this->_decode_ber($content, $length + $start, $content_pos); + $content_pos += $temp['length']; + // all subtags should be octet strings + //if ($temp['type'] != FILE_ASN1_TYPE_OCTET_STRING) { + // return false; + //} + $current['content'].= $temp['content']; + $length+= $temp['length']; + } + if (substr($content, $content_pos, 2) == "\0\0") { + $length+= 2; // +2 for the EOC + } + } + break; + case FILE_ASN1_TYPE_NULL: + // "The contents octets shall not contain any octets." -- paragraph 8.8.2 + //if (strlen($content)) { + // return false; + //} + break; + case FILE_ASN1_TYPE_SEQUENCE: + case FILE_ASN1_TYPE_SET: + $offset = 0; + $current['content'] = array(); + $content_len = strlen($content); + while ($content_pos < $content_len) { + // if indefinite length construction was used and we have an end-of-content string next + // see paragraphs 8.1.1.3, 8.1.3.2, 8.1.3.6, 8.1.5, and (for an example) 8.6.4.2 + if (!isset($current['headerlength']) && substr($content, $content_pos, 2) == "\0\0") { + $length = $offset + 2; // +2 for the EOC + break 2; + } + $temp = $this->_decode_ber($content, $start + $offset, $content_pos); + $content_pos += $temp['length']; + $current['content'][] = $temp; + $offset+= $temp['length']; + } + break; + case FILE_ASN1_TYPE_OBJECT_IDENTIFIER: + $temp = ord($content[$content_pos++]); + $current['content'] = sprintf('%d.%d', floor($temp / 40), $temp % 40); + $valuen = 0; + // process septets + $content_len = strlen($content); + while ($content_pos < $content_len) { + $temp = ord($content[$content_pos++]); + $valuen <<= 7; + $valuen |= $temp & 0x7F; + if (~$temp & 0x80) { + $current['content'].= ".$valuen"; + $valuen = 0; + } + } + // the eighth bit of the last byte should not be 1 + //if ($temp >> 7) { + // return false; + //} + break; + /* Each character string type shall be encoded as if it had been declared: + [UNIVERSAL x] IMPLICIT OCTET STRING + + -- X.690-0207.pdf#page=23 (paragraph 8.21.3) + + Per that, we're not going to do any validation. If there are any illegal characters in the string, + we don't really care */ + case FILE_ASN1_TYPE_NUMERIC_STRING: + // 0,1,2,3,4,5,6,7,8,9, and space + case FILE_ASN1_TYPE_PRINTABLE_STRING: + // Upper and lower case letters, digits, space, apostrophe, left/right parenthesis, plus sign, comma, + // hyphen, full stop, solidus, colon, equal sign, question mark + case FILE_ASN1_TYPE_TELETEX_STRING: + // The Teletex character set in CCITT's T61, space, and delete + // see http://en.wikipedia.org/wiki/Teletex#Character_sets + case FILE_ASN1_TYPE_VIDEOTEX_STRING: + // The Videotex character set in CCITT's T.100 and T.101, space, and delete + case FILE_ASN1_TYPE_VISIBLE_STRING: + // Printing character sets of international ASCII, and space + case FILE_ASN1_TYPE_IA5_STRING: + // International Alphabet 5 (International ASCII) + case FILE_ASN1_TYPE_GRAPHIC_STRING: + // All registered G sets, and space + case FILE_ASN1_TYPE_GENERAL_STRING: + // All registered C and G sets, space and delete + case FILE_ASN1_TYPE_UTF8_STRING: + // ???? + case FILE_ASN1_TYPE_BMP_STRING: + $current['content'] = substr($content, $content_pos); + break; + case FILE_ASN1_TYPE_UTC_TIME: + case FILE_ASN1_TYPE_GENERALIZED_TIME: + $current['content'] = class_exists('DateTime') ? + $this->_decodeDateTime(substr($content, $content_pos), $tag) : + $this->_decodeUnixTime(substr($content, $content_pos), $tag); + default: + } + + $start+= $length; + + // ie. length is the length of the full TLV encoding - it's not just the length of the value + return $current + array('length' => $start - $current['start']); + } + + /** + * ASN.1 Map + * + * Provides an ASN.1 semantic mapping ($mapping) from a parsed BER-encoding to a human readable format. + * + * "Special" mappings may be applied on a per tag-name basis via $special. + * + * @param array $decoded + * @param array $mapping + * @param array $special + * @return array + * @access public + */ + function asn1map($decoded, $mapping, $special = array()) + { + if (isset($mapping['explicit']) && is_array($decoded['content'])) { + $decoded = $decoded['content'][0]; + } + + switch (true) { + case $mapping['type'] == FILE_ASN1_TYPE_ANY: + $intype = $decoded['type']; + if (isset($decoded['constant']) || !isset($this->ANYmap[$intype]) || (ord($this->encoded[$decoded['start']]) & 0x20)) { + return new File_ASN1_Element(substr($this->encoded, $decoded['start'], $decoded['length'])); + } + $inmap = $this->ANYmap[$intype]; + if (is_string($inmap)) { + return array($inmap => $this->asn1map($decoded, array('type' => $intype) + $mapping, $special)); + } + break; + case $mapping['type'] == FILE_ASN1_TYPE_CHOICE: + foreach ($mapping['children'] as $key => $option) { + switch (true) { + case isset($option['constant']) && $option['constant'] == $decoded['constant']: + case !isset($option['constant']) && $option['type'] == $decoded['type']: + $value = $this->asn1map($decoded, $option, $special); + break; + case !isset($option['constant']) && $option['type'] == FILE_ASN1_TYPE_CHOICE: + $v = $this->asn1map($decoded, $option, $special); + if (isset($v)) { + $value = $v; + } + } + if (isset($value)) { + if (isset($special[$key])) { + $value = call_user_func($special[$key], $value); + } + return array($key => $value); + } + } + return null; + case isset($mapping['implicit']): + case isset($mapping['explicit']): + case $decoded['type'] == $mapping['type']: + break; + default: + // if $decoded['type'] and $mapping['type'] are both strings, but different types of strings, + // let it through + switch (true) { + case $decoded['type'] < 18: // FILE_ASN1_TYPE_NUMERIC_STRING == 18 + case $decoded['type'] > 30: // FILE_ASN1_TYPE_BMP_STRING == 30 + case $mapping['type'] < 18: + case $mapping['type'] > 30: + return null; + } + } + + if (isset($mapping['implicit'])) { + $decoded['type'] = $mapping['type']; + } + + switch ($decoded['type']) { + case FILE_ASN1_TYPE_SEQUENCE: + $map = array(); + + // ignore the min and max + if (isset($mapping['min']) && isset($mapping['max'])) { + $child = $mapping['children']; + foreach ($decoded['content'] as $content) { + if (($map[] = $this->asn1map($content, $child, $special)) === null) { + return null; + } + } + + return $map; + } + + $n = count($decoded['content']); + $i = 0; + + foreach ($mapping['children'] as $key => $child) { + $maymatch = $i < $n; // Match only existing input. + if ($maymatch) { + $temp = $decoded['content'][$i]; + + if ($child['type'] != FILE_ASN1_TYPE_CHOICE) { + // Get the mapping and input class & constant. + $childClass = $tempClass = FILE_ASN1_CLASS_UNIVERSAL; + $constant = null; + if (isset($temp['constant'])) { + $tempClass = isset($temp['class']) ? $temp['class'] : FILE_ASN1_CLASS_CONTEXT_SPECIFIC; + } + if (isset($child['class'])) { + $childClass = $child['class']; + $constant = $child['cast']; + } elseif (isset($child['constant'])) { + $childClass = FILE_ASN1_CLASS_CONTEXT_SPECIFIC; + $constant = $child['constant']; + } + + if (isset($constant) && isset($temp['constant'])) { + // Can only match if constants and class match. + $maymatch = $constant == $temp['constant'] && $childClass == $tempClass; + } else { + // Can only match if no constant expected and type matches or is generic. + $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], FILE_ASN1_TYPE_ANY, FILE_ASN1_TYPE_CHOICE)) !== false; + } + } + } + + if ($maymatch) { + // Attempt submapping. + $candidate = $this->asn1map($temp, $child, $special); + $maymatch = $candidate !== null; + } + + if ($maymatch) { + // Got the match: use it. + if (isset($special[$key])) { + $candidate = call_user_func($special[$key], $candidate); + } + $map[$key] = $candidate; + $i++; + } elseif (isset($child['default'])) { + $map[$key] = $child['default']; // Use default. + } elseif (!isset($child['optional'])) { + return null; // Syntax error. + } + } + + // Fail mapping if all input items have not been consumed. + return $i < $n ? null: $map; + + // the main diff between sets and sequences is the encapsulation of the foreach in another for loop + case FILE_ASN1_TYPE_SET: + $map = array(); + + // ignore the min and max + if (isset($mapping['min']) && isset($mapping['max'])) { + $child = $mapping['children']; + foreach ($decoded['content'] as $content) { + if (($map[] = $this->asn1map($content, $child, $special)) === null) { + return null; + } + } + + return $map; + } + + for ($i = 0; $i < count($decoded['content']); $i++) { + $temp = $decoded['content'][$i]; + $tempClass = FILE_ASN1_CLASS_UNIVERSAL; + if (isset($temp['constant'])) { + $tempClass = isset($temp['class']) ? $temp['class'] : FILE_ASN1_CLASS_CONTEXT_SPECIFIC; + } + + foreach ($mapping['children'] as $key => $child) { + if (isset($map[$key])) { + continue; + } + $maymatch = true; + if ($child['type'] != FILE_ASN1_TYPE_CHOICE) { + $childClass = FILE_ASN1_CLASS_UNIVERSAL; + $constant = null; + if (isset($child['class'])) { + $childClass = $child['class']; + $constant = $child['cast']; + } elseif (isset($child['constant'])) { + $childClass = FILE_ASN1_CLASS_CONTEXT_SPECIFIC; + $constant = $child['constant']; + } + + if (isset($constant) && isset($temp['constant'])) { + // Can only match if constants and class match. + $maymatch = $constant == $temp['constant'] && $childClass == $tempClass; + } else { + // Can only match if no constant expected and type matches or is generic. + $maymatch = !isset($child['constant']) && array_search($child['type'], array($temp['type'], FILE_ASN1_TYPE_ANY, FILE_ASN1_TYPE_CHOICE)) !== false; + } + } + + if ($maymatch) { + // Attempt submapping. + $candidate = $this->asn1map($temp, $child, $special); + $maymatch = $candidate !== null; + } + + if (!$maymatch) { + break; + } + + // Got the match: use it. + if (isset($special[$key])) { + $candidate = call_user_func($special[$key], $candidate); + } + $map[$key] = $candidate; + break; + } + } + + foreach ($mapping['children'] as $key => $child) { + if (!isset($map[$key])) { + if (isset($child['default'])) { + $map[$key] = $child['default']; + } elseif (!isset($child['optional'])) { + return null; + } + } + } + return $map; + case FILE_ASN1_TYPE_OBJECT_IDENTIFIER: + return isset($this->oids[$decoded['content']]) ? $this->oids[$decoded['content']] : $decoded['content']; + case FILE_ASN1_TYPE_UTC_TIME: + case FILE_ASN1_TYPE_GENERALIZED_TIME: + if (class_exists('DateTime')) { + if (isset($mapping['implicit'])) { + $decoded['content'] = $this->_decodeDateTime($decoded['content'], $decoded['type']); + } + if (!$decoded['content']) { + return false; + } + return $decoded['content']->format($this->format); + } else { + if (isset($mapping['implicit'])) { + $decoded['content'] = $this->_decodeUnixTime($decoded['content'], $decoded['type']); + } + return @date($this->format, $decoded['content']); + } + case FILE_ASN1_TYPE_BIT_STRING: + if (isset($mapping['mapping'])) { + $offset = ord($decoded['content'][0]); + $size = (strlen($decoded['content']) - 1) * 8 - $offset; + /* + From X.680-0207.pdf#page=46 (21.7): + + "When a "NamedBitList" is used in defining a bitstring type ASN.1 encoding rules are free to add (or remove) + arbitrarily any trailing 0 bits to (or from) values that are being encoded or decoded. Application designers should + therefore ensure that different semantics are not associated with such values which differ only in the number of trailing + 0 bits." + */ + $bits = count($mapping['mapping']) == $size ? array() : array_fill(0, count($mapping['mapping']) - $size, false); + for ($i = strlen($decoded['content']) - 1; $i > 0; $i--) { + $current = ord($decoded['content'][$i]); + for ($j = $offset; $j < 8; $j++) { + $bits[] = (bool) ($current & (1 << $j)); + } + $offset = 0; + } + $values = array(); + $map = array_reverse($mapping['mapping']); + foreach ($map as $i => $value) { + if ($bits[$i]) { + $values[] = $value; + } + } + return $values; + } + case FILE_ASN1_TYPE_OCTET_STRING: + return base64_encode($decoded['content']); + case FILE_ASN1_TYPE_NULL: + return ''; + case FILE_ASN1_TYPE_BOOLEAN: + return $decoded['content']; + case FILE_ASN1_TYPE_NUMERIC_STRING: + case FILE_ASN1_TYPE_PRINTABLE_STRING: + case FILE_ASN1_TYPE_TELETEX_STRING: + case FILE_ASN1_TYPE_VIDEOTEX_STRING: + case FILE_ASN1_TYPE_IA5_STRING: + case FILE_ASN1_TYPE_GRAPHIC_STRING: + case FILE_ASN1_TYPE_VISIBLE_STRING: + case FILE_ASN1_TYPE_GENERAL_STRING: + case FILE_ASN1_TYPE_UNIVERSAL_STRING: + case FILE_ASN1_TYPE_UTF8_STRING: + case FILE_ASN1_TYPE_BMP_STRING: + return $decoded['content']; + case FILE_ASN1_TYPE_INTEGER: + case FILE_ASN1_TYPE_ENUMERATED: + $temp = $decoded['content']; + if (isset($mapping['implicit'])) { + $temp = new Math_BigInteger($decoded['content'], -256); + } + if (isset($mapping['mapping'])) { + $temp = (int) $temp->toString(); + return isset($mapping['mapping'][$temp]) ? + $mapping['mapping'][$temp] : + false; + } + return $temp; + } + } + + /** + * ASN.1 Encode + * + * DER-encodes an ASN.1 semantic mapping ($mapping). Some libraries would probably call this function + * an ASN.1 compiler. + * + * "Special" mappings can be applied via $special. + * + * @param string $source + * @param string $mapping + * @param int $idx + * @return string + * @access public + */ + function encodeDER($source, $mapping, $special = array()) + { + $this->location = array(); + return $this->_encode_der($source, $mapping, null, $special); + } + + /** + * ASN.1 Encode (Helper function) + * + * @param string $source + * @param string $mapping + * @param int $idx + * @return string + * @access private + */ + function _encode_der($source, $mapping, $idx = null, $special = array()) + { + if (is_object($source) && strtolower(get_class($source)) == 'file_asn1_element') { + return $source->element; + } + + // do not encode (implicitly optional) fields with value set to default + if (isset($mapping['default']) && $source === $mapping['default']) { + return ''; + } + + if (isset($idx)) { + if (isset($special[$idx])) { + $source = call_user_func($special[$idx], $source); + } + $this->location[] = $idx; + } + + $tag = $mapping['type']; + + switch ($tag) { + case FILE_ASN1_TYPE_SET: // Children order is not important, thus process in sequence. + case FILE_ASN1_TYPE_SEQUENCE: + $tag|= 0x20; // set the constructed bit + + // ignore the min and max + if (isset($mapping['min']) && isset($mapping['max'])) { + $value = array(); + $child = $mapping['children']; + + foreach ($source as $content) { + $temp = $this->_encode_der($content, $child, null, $special); + if ($temp === false) { + return false; + } + $value[]= $temp; + } + /* "The encodings of the component values of a set-of value shall appear in ascending order, the encodings being compared + as octet strings with the shorter components being padded at their trailing end with 0-octets. + NOTE - The padding octets are for comparison purposes only and do not appear in the encodings." + + -- sec 11.6 of http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf */ + if ($mapping['type'] == FILE_ASN1_TYPE_SET) { + sort($value); + } + $value = implode($value, ''); + break; + } + + $value = ''; + foreach ($mapping['children'] as $key => $child) { + if (!array_key_exists($key, $source)) { + if (!isset($child['optional'])) { + return false; + } + continue; + } + + $temp = $this->_encode_der($source[$key], $child, $key, $special); + if ($temp === false) { + return false; + } + + // An empty child encoding means it has been optimized out. + // Else we should have at least one tag byte. + if ($temp === '') { + continue; + } + + // if isset($child['constant']) is true then isset($child['optional']) should be true as well + if (isset($child['constant'])) { + /* + From X.680-0207.pdf#page=58 (30.6): + + "The tagging construction specifies explicit tagging if any of the following holds: + ... + c) the "Tag Type" alternative is used and the value of "TagDefault" for the module is IMPLICIT TAGS or + AUTOMATIC TAGS, but the type defined by "Type" is an untagged choice type, an untagged open type, or + an untagged "DummyReference" (see ITU-T Rec. X.683 | ISO/IEC 8824-4, 8.3)." + */ + if (isset($child['explicit']) || $child['type'] == FILE_ASN1_TYPE_CHOICE) { + $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']); + $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp; + } else { + $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']); + $temp = $subtag . substr($temp, 1); + } + } + $value.= $temp; + } + break; + case FILE_ASN1_TYPE_CHOICE: + $temp = false; + + foreach ($mapping['children'] as $key => $child) { + if (!isset($source[$key])) { + continue; + } + + $temp = $this->_encode_der($source[$key], $child, $key, $special); + if ($temp === false) { + return false; + } + + // An empty child encoding means it has been optimized out. + // Else we should have at least one tag byte. + if ($temp === '') { + continue; + } + + $tag = ord($temp[0]); + + // if isset($child['constant']) is true then isset($child['optional']) should be true as well + if (isset($child['constant'])) { + if (isset($child['explicit']) || $child['type'] == FILE_ASN1_TYPE_CHOICE) { + $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | 0x20 | $child['constant']); + $temp = $subtag . $this->_encodeLength(strlen($temp)) . $temp; + } else { + $subtag = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | (ord($temp[0]) & 0x20) | $child['constant']); + $temp = $subtag . substr($temp, 1); + } + } + } + + if (isset($idx)) { + array_pop($this->location); + } + + if ($temp && isset($mapping['cast'])) { + $temp[0] = chr(($mapping['class'] << 6) | ($tag & 0x20) | $mapping['cast']); + } + + return $temp; + case FILE_ASN1_TYPE_INTEGER: + case FILE_ASN1_TYPE_ENUMERATED: + if (!isset($mapping['mapping'])) { + if (is_numeric($source)) { + $source = new Math_BigInteger($source); + } + $value = $source->toBytes(true); + } else { + $value = array_search($source, $mapping['mapping']); + if ($value === false) { + return false; + } + $value = new Math_BigInteger($value); + $value = $value->toBytes(true); + } + if (!strlen($value)) { + $value = chr(0); + } + break; + case FILE_ASN1_TYPE_UTC_TIME: + case FILE_ASN1_TYPE_GENERALIZED_TIME: + $format = $mapping['type'] == FILE_ASN1_TYPE_UTC_TIME ? 'y' : 'Y'; + $format.= 'mdHis'; + if (!class_exists('DateTime')) { + $value = @gmdate($format, strtotime($source)) . 'Z'; + } else { + $date = new DateTime($source, new DateTimeZone('GMT')); + $value = $date->format($format) . 'Z'; + } + break; + case FILE_ASN1_TYPE_BIT_STRING: + if (isset($mapping['mapping'])) { + $bits = array_fill(0, count($mapping['mapping']), 0); + $size = 0; + for ($i = 0; $i < count($mapping['mapping']); $i++) { + if (in_array($mapping['mapping'][$i], $source)) { + $bits[$i] = 1; + $size = $i; + } + } + + if (isset($mapping['min']) && $mapping['min'] >= 1 && $size < $mapping['min']) { + $size = $mapping['min'] - 1; + } + + $offset = 8 - (($size + 1) & 7); + $offset = $offset !== 8 ? $offset : 0; + + $value = chr($offset); + + for ($i = $size + 1; $i < count($mapping['mapping']); $i++) { + unset($bits[$i]); + } + + $bits = implode('', array_pad($bits, $size + $offset + 1, 0)); + $bytes = explode(' ', rtrim(chunk_split($bits, 8, ' '))); + foreach ($bytes as $byte) { + $value.= chr(bindec($byte)); + } + + break; + } + case FILE_ASN1_TYPE_OCTET_STRING: + /* The initial octet shall encode, as an unsigned binary integer with bit 1 as the least significant bit, + the number of unused bits in the final subsequent octet. The number shall be in the range zero to seven. + + -- http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=16 */ + $value = base64_decode($source); + break; + case FILE_ASN1_TYPE_OBJECT_IDENTIFIER: + $oid = preg_match('#(?:\d+\.)+#', $source) ? $source : array_search($source, $this->oids); + if ($oid === false) { + user_error('Invalid OID'); + return false; + } + $value = ''; + $parts = explode('.', $oid); + $value = chr(40 * $parts[0] + $parts[1]); + for ($i = 2; $i < count($parts); $i++) { + $temp = ''; + if (!$parts[$i]) { + $temp = "\0"; + } else { + while ($parts[$i]) { + $temp = chr(0x80 | ($parts[$i] & 0x7F)) . $temp; + $parts[$i] >>= 7; + } + $temp[strlen($temp) - 1] = $temp[strlen($temp) - 1] & chr(0x7F); + } + $value.= $temp; + } + break; + case FILE_ASN1_TYPE_ANY: + $loc = $this->location; + if (isset($idx)) { + array_pop($this->location); + } + + switch (true) { + case !isset($source): + return $this->_encode_der(null, array('type' => FILE_ASN1_TYPE_NULL) + $mapping, null, $special); + case is_int($source): + case is_object($source) && strtolower(get_class($source)) == 'math_biginteger': + return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_INTEGER) + $mapping, null, $special); + case is_float($source): + return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_REAL) + $mapping, null, $special); + case is_bool($source): + return $this->_encode_der($source, array('type' => FILE_ASN1_TYPE_BOOLEAN) + $mapping, null, $special); + case is_array($source) && count($source) == 1: + $typename = implode('', array_keys($source)); + $outtype = array_search($typename, $this->ANYmap, true); + if ($outtype !== false) { + return $this->_encode_der($source[$typename], array('type' => $outtype) + $mapping, null, $special); + } + } + + $filters = $this->filters; + foreach ($loc as $part) { + if (!isset($filters[$part])) { + $filters = false; + break; + } + $filters = $filters[$part]; + } + if ($filters === false) { + user_error('No filters defined for ' . implode('/', $loc)); + return false; + } + return $this->_encode_der($source, $filters + $mapping, null, $special); + case FILE_ASN1_TYPE_NULL: + $value = ''; + break; + case FILE_ASN1_TYPE_NUMERIC_STRING: + case FILE_ASN1_TYPE_TELETEX_STRING: + case FILE_ASN1_TYPE_PRINTABLE_STRING: + case FILE_ASN1_TYPE_UNIVERSAL_STRING: + case FILE_ASN1_TYPE_UTF8_STRING: + case FILE_ASN1_TYPE_BMP_STRING: + case FILE_ASN1_TYPE_IA5_STRING: + case FILE_ASN1_TYPE_VISIBLE_STRING: + case FILE_ASN1_TYPE_VIDEOTEX_STRING: + case FILE_ASN1_TYPE_GRAPHIC_STRING: + case FILE_ASN1_TYPE_GENERAL_STRING: + $value = $source; + break; + case FILE_ASN1_TYPE_BOOLEAN: + $value = $source ? "\xFF" : "\x00"; + break; + default: + user_error('Mapping provides no type definition for ' . implode('/', $this->location)); + return false; + } + + if (isset($idx)) { + array_pop($this->location); + } + + if (isset($mapping['cast'])) { + if (isset($mapping['explicit']) || $mapping['type'] == FILE_ASN1_TYPE_CHOICE) { + $value = chr($tag) . $this->_encodeLength(strlen($value)) . $value; + $tag = ($mapping['class'] << 6) | 0x20 | $mapping['cast']; + } else { + $tag = ($mapping['class'] << 6) | (ord($temp[0]) & 0x20) | $mapping['cast']; + } + } + + return chr($tag) . $this->_encodeLength(strlen($value)) . $value; + } + + /** + * DER-encode the length + * + * DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See + * {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information. + * + * @access private + * @param int $length + * @return string + */ + function _encodeLength($length) + { + if ($length <= 0x7F) { + return chr($length); + } + + $temp = ltrim(pack('N', $length), chr(0)); + return pack('Ca*', 0x80 | strlen($temp), $temp); + } + + /** + * BER-decode the time (using UNIX time) + * + * Called by _decode_ber() and in the case of implicit tags asn1map(). + * + * @access private + * @param string $content + * @param int $tag + * @return string + */ + function _decodeUnixTime($content, $tag) + { + /* UTCTime: + http://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 + http://www.obj-sys.com/asn1tutorial/node15.html + + GeneralizedTime: + http://tools.ietf.org/html/rfc5280#section-4.1.2.5.2 + http://www.obj-sys.com/asn1tutorial/node14.html */ + + $pattern = $tag == FILE_ASN1_TYPE_UTC_TIME ? + '#^(..)(..)(..)(..)(..)(..)?(.*)$#' : + '#(....)(..)(..)(..)(..)(..).*([Z+-].*)$#'; + + preg_match($pattern, $content, $matches); + + list(, $year, $month, $day, $hour, $minute, $second, $timezone) = $matches; + + if ($tag == FILE_ASN1_TYPE_UTC_TIME) { + $year = $year >= 50 ? "19$year" : "20$year"; + } + + if ($timezone == 'Z') { + $mktime = 'gmmktime'; + $timezone = 0; + } elseif (preg_match('#([+-])(\d\d)(\d\d)#', $timezone, $matches)) { + $mktime = 'gmmktime'; + $timezone = 60 * $matches[3] + 3600 * $matches[2]; + if ($matches[1] == '-') { + $timezone = -$timezone; + } + } else { + $mktime = 'mktime'; + $timezone = 0; + } + + return @$mktime((int)$hour, (int)$minute, (int)$second, (int)$month, (int)$day, (int)$year) + $timezone; + } + + + /** + * BER-decode the time (using DateTime) + * + * Called by _decode_ber() and in the case of implicit tags asn1map(). + * + * @access private + * @param string $content + * @param int $tag + * @return string + */ + function _decodeDateTime($content, $tag) + { + /* UTCTime: + http://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 + http://www.obj-sys.com/asn1tutorial/node15.html + + GeneralizedTime: + http://tools.ietf.org/html/rfc5280#section-4.1.2.5.2 + http://www.obj-sys.com/asn1tutorial/node14.html */ + + $format = 'YmdHis'; + + if ($tag == FILE_ASN1_TYPE_UTC_TIME) { + // https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#page=28 says "the seconds + // element shall always be present" but none-the-less I've seen X509 certs where it isn't and if the + // browsers parse it phpseclib ought to too + if (preg_match('#^(\d{10})(Z|[+-]\d{4})$#', $content, $matches)) { + $content = $matches[1] . '00' . $matches[2]; + } + $prefix = substr($content, 0, 2) >= 50 ? '19' : '20'; + $content = $prefix . $content; + } elseif (strpos($content, '.') !== false) { + $format.= '.u'; + } + + if ($content[strlen($content) - 1] == 'Z') { + $content = substr($content, 0, -1) . '+0000'; + } + + if (strpos($content, '-') !== false || strpos($content, '+') !== false) { + $format.= 'O'; + } + + // error supression isn't necessary as of PHP 7.0: + // http://php.net/manual/en/migration70.other-changes.php + return @DateTime::createFromFormat($format, $content); + } + + /** + * Set the time format + * + * Sets the time / date format for asn1map(). + * + * @access public + * @param string $format + */ + function setTimeFormat($format) + { + $this->format = $format; + } + + /** + * Load OIDs + * + * Load the relevant OIDs for a particular ASN.1 semantic mapping. + * + * @access public + * @param array $oids + */ + function loadOIDs($oids) + { + $this->oids = $oids; + } + + /** + * Load filters + * + * See File_X509, etc, for an example. + * + * @access public + * @param array $filters + */ + function loadFilters($filters) + { + $this->filters = $filters; + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @return string + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * String type conversion + * + * This is a lazy conversion, dealing only with character size. + * No real conversion table is used. + * + * @param string $in + * @param int $from + * @param int $to + * @return string + * @access public + */ + function convert($in, $from = FILE_ASN1_TYPE_UTF8_STRING, $to = FILE_ASN1_TYPE_UTF8_STRING) + { + if (!isset($this->stringTypeSize[$from]) || !isset($this->stringTypeSize[$to])) { + return false; + } + $insize = $this->stringTypeSize[$from]; + $outsize = $this->stringTypeSize[$to]; + $inlength = strlen($in); + $out = ''; + + for ($i = 0; $i < $inlength;) { + if ($inlength - $i < $insize) { + return false; + } + + // Get an input character as a 32-bit value. + $c = ord($in[$i++]); + switch (true) { + case $insize == 4: + $c = ($c << 8) | ord($in[$i++]); + $c = ($c << 8) | ord($in[$i++]); + case $insize == 2: + $c = ($c << 8) | ord($in[$i++]); + case $insize == 1: + break; + case ($c & 0x80) == 0x00: + break; + case ($c & 0x40) == 0x00: + return false; + default: + $bit = 6; + do { + if ($bit > 25 || $i >= $inlength || (ord($in[$i]) & 0xC0) != 0x80) { + return false; + } + $c = ($c << 6) | (ord($in[$i++]) & 0x3F); + $bit += 5; + $mask = 1 << $bit; + } while ($c & $bit); + $c &= $mask - 1; + break; + } + + // Convert and append the character to output string. + $v = ''; + switch (true) { + case $outsize == 4: + $v .= chr($c & 0xFF); + $c >>= 8; + $v .= chr($c & 0xFF); + $c >>= 8; + case $outsize == 2: + $v .= chr($c & 0xFF); + $c >>= 8; + case $outsize == 1: + $v .= chr($c & 0xFF); + $c >>= 8; + if ($c) { + return false; + } + break; + case ($c & 0x80000000) != 0: + return false; + case $c >= 0x04000000: + $v .= chr(0x80 | ($c & 0x3F)); + $c = ($c >> 6) | 0x04000000; + case $c >= 0x00200000: + $v .= chr(0x80 | ($c & 0x3F)); + $c = ($c >> 6) | 0x00200000; + case $c >= 0x00010000: + $v .= chr(0x80 | ($c & 0x3F)); + $c = ($c >> 6) | 0x00010000; + case $c >= 0x00000800: + $v .= chr(0x80 | ($c & 0x3F)); + $c = ($c >> 6) | 0x00000800; + case $c >= 0x00000080: + $v .= chr(0x80 | ($c & 0x3F)); + $c = ($c >> 6) | 0x000000C0; + default: + $v .= chr($c); + break; + } + $out .= strrev($v); + } + return $out; + } +} diff --git a/ipaylinks_statement/File/X509.php b/ipaylinks_statement/File/X509.php new file mode 100644 index 00000000..7d9534d0 --- /dev/null +++ b/ipaylinks_statement/File/X509.php @@ -0,0 +1,4937 @@ + + * @copyright 2012 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include File_ASN1 + */ +if (!class_exists('File_ASN1')) { + include_once 'ASN1.php'; +} + +/** + * Flag to only accept signatures signed by certificate authorities + * + * Not really used anymore but retained all the same to suppress E_NOTICEs from old installs + * + * @access public + */ +define('FILE_X509_VALIDATE_SIGNATURE_BY_CA', 1); + +/**#@+ + * @access public + * @see self::getDN() + */ +/** + * Return internal array representation + */ +define('FILE_X509_DN_ARRAY', 0); +/** + * Return string + */ +define('FILE_X509_DN_STRING', 1); +/** + * Return ASN.1 name string + */ +define('FILE_X509_DN_ASN1', 2); +/** + * Return OpenSSL compatible array + */ +define('FILE_X509_DN_OPENSSL', 3); +/** + * Return canonical ASN.1 RDNs string + */ +define('FILE_X509_DN_CANON', 4); +/** + * Return name hash for file indexing + */ +define('FILE_X509_DN_HASH', 5); +/**#@-*/ + +/**#@+ + * @access public + * @see self::saveX509() + * @see self::saveCSR() + * @see self::saveCRL() + */ +/** + * Save as PEM + * + * ie. a base64-encoded PEM with a header and a footer + */ +define('FILE_X509_FORMAT_PEM', 0); +/** + * Save as DER + */ +define('FILE_X509_FORMAT_DER', 1); +/** + * Save as a SPKAC + * + * Only works on CSRs. Not currently supported. + */ +define('FILE_X509_FORMAT_SPKAC', 2); +/** + * Auto-detect the format + * + * Used only by the load*() functions + */ +define('FILE_X509_FORMAT_AUTO_DETECT', 3); +/**#@-*/ + +/** + * Attribute value disposition. + * If disposition is >= 0, this is the index of the target value. + */ +define('FILE_X509_ATTR_ALL', -1); // All attribute values (array). +define('FILE_X509_ATTR_APPEND', -2); // Add a value. +define('FILE_X509_ATTR_REPLACE', -3); // Clear first, then add a value. + +/** + * Pure-PHP X.509 Parser + * + * @package File_X509 + * @author Jim Wigginton + * @access public + */ +class File_X509 +{ + /** + * ASN.1 syntax for X.509 certificates + * + * @var array + * @access private + */ + var $Certificate; + + /**#@+ + * ASN.1 syntax for various extensions + * + * @access private + */ + var $DirectoryString; + var $PKCS9String; + var $AttributeValue; + var $Extensions; + var $KeyUsage; + var $ExtKeyUsageSyntax; + var $BasicConstraints; + var $KeyIdentifier; + var $CRLDistributionPoints; + var $AuthorityKeyIdentifier; + var $CertificatePolicies; + var $AuthorityInfoAccessSyntax; + var $SubjectAltName; + var $SubjectDirectoryAttributes; + var $PrivateKeyUsagePeriod; + var $IssuerAltName; + var $PolicyMappings; + var $NameConstraints; + + var $CPSuri; + var $UserNotice; + + var $netscape_cert_type; + var $netscape_comment; + var $netscape_ca_policy_url; + + var $Name; + var $RelativeDistinguishedName; + var $CRLNumber; + var $CRLReason; + var $IssuingDistributionPoint; + var $InvalidityDate; + var $CertificateIssuer; + var $HoldInstructionCode; + var $SignedPublicKeyAndChallenge; + /**#@-*/ + + /**#@+ + * ASN.1 syntax for various DN attributes + * + * @access private + */ + var $PostalAddress; + /**#@-*/ + + /** + * ASN.1 syntax for Certificate Signing Requests (RFC2986) + * + * @var array + * @access private + */ + var $CertificationRequest; + + /** + * ASN.1 syntax for Certificate Revocation Lists (RFC5280) + * + * @var array + * @access private + */ + var $CertificateList; + + /** + * Distinguished Name + * + * @var array + * @access private + */ + var $dn; + + /** + * Public key + * + * @var string + * @access private + */ + var $publicKey; + + /** + * Private key + * + * @var string + * @access private + */ + var $privateKey; + + /** + * Object identifiers for X.509 certificates + * + * @var array + * @access private + * @link http://en.wikipedia.org/wiki/Object_identifier + */ + var $oids; + + /** + * The certificate authorities + * + * @var array + * @access private + */ + var $CAs; + + /** + * The currently loaded certificate + * + * @var array + * @access private + */ + var $currentCert; + + /** + * The signature subject + * + * There's no guarantee File_X509 is going to re-encode an X.509 cert in the same way it was originally + * encoded so we take save the portion of the original cert that the signature would have made for. + * + * @var string + * @access private + */ + var $signatureSubject; + + /** + * Certificate Start Date + * + * @var string + * @access private + */ + var $startDate; + + /** + * Certificate End Date + * + * @var string + * @access private + */ + var $endDate; + + /** + * Serial Number + * + * @var string + * @access private + */ + var $serialNumber; + + /** + * Key Identifier + * + * See {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.1 RFC5280#section-4.2.1.1} and + * {@link http://tools.ietf.org/html/rfc5280#section-4.2.1.2 RFC5280#section-4.2.1.2}. + * + * @var string + * @access private + */ + var $currentKeyIdentifier; + + /** + * CA Flag + * + * @var bool + * @access private + */ + var $caFlag = false; + + /** + * SPKAC Challenge + * + * @var string + * @access private + */ + var $challenge; + + /** + * Default Constructor. + * + * @return File_X509 + * @access public + */ + function __construct() + { + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + + // Explicitly Tagged Module, 1988 Syntax + // http://tools.ietf.org/html/rfc5280#appendix-A.1 + + $this->DirectoryString = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'teletexString' => array('type' => FILE_ASN1_TYPE_TELETEX_STRING), + 'printableString' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING), + 'universalString' => array('type' => FILE_ASN1_TYPE_UNIVERSAL_STRING), + 'utf8String' => array('type' => FILE_ASN1_TYPE_UTF8_STRING), + 'bmpString' => array('type' => FILE_ASN1_TYPE_BMP_STRING) + ) + ); + + $this->PKCS9String = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'ia5String' => array('type' => FILE_ASN1_TYPE_IA5_STRING), + 'directoryString' => $this->DirectoryString + ) + ); + + $this->AttributeValue = array('type' => FILE_ASN1_TYPE_ANY); + + $AttributeType = array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER); + + $AttributeTypeAndValue = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'type' => $AttributeType, + 'value'=> $this->AttributeValue + ) + ); + + /* + In practice, RDNs containing multiple name-value pairs (called "multivalued RDNs") are rare, + but they can be useful at times when either there is no unique attribute in the entry or you + want to ensure that the entry's DN contains some useful identifying information. + + - https://www.opends.org/wiki/page/DefinitionRelativeDistinguishedName + */ + $this->RelativeDistinguishedName = array( + 'type' => FILE_ASN1_TYPE_SET, + 'min' => 1, + 'max' => -1, + 'children' => $AttributeTypeAndValue + ); + + // http://tools.ietf.org/html/rfc5280#section-4.1.2.4 + $RDNSequence = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + // RDNSequence does not define a min or a max, which means it doesn't have one + 'min' => 0, + 'max' => -1, + 'children' => $this->RelativeDistinguishedName + ); + + $this->Name = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'rdnSequence' => $RDNSequence + ) + ); + + // http://tools.ietf.org/html/rfc5280#section-4.1.1.2 + $AlgorithmIdentifier = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'algorithm' => array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER), + 'parameters' => array( + 'type' => FILE_ASN1_TYPE_ANY, + 'optional' => true + ) + ) + ); + + /* + A certificate using system MUST reject the certificate if it encounters + a critical extension it does not recognize; however, a non-critical + extension may be ignored if it is not recognized. + + http://tools.ietf.org/html/rfc5280#section-4.2 + */ + $Extension = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'extnId' => array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER), + 'critical' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'optional' => true, + 'default' => false + ), + 'extnValue' => array('type' => FILE_ASN1_TYPE_OCTET_STRING) + ) + ); + + $this->Extensions = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + // technically, it's MAX, but we'll assume anything < 0 is MAX + 'max' => -1, + // if 'children' isn't an array then 'min' and 'max' must be defined + 'children' => $Extension + ); + + $SubjectPublicKeyInfo = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'algorithm' => $AlgorithmIdentifier, + 'subjectPublicKey' => array('type' => FILE_ASN1_TYPE_BIT_STRING) + ) + ); + + $UniqueIdentifier = array('type' => FILE_ASN1_TYPE_BIT_STRING); + + $Time = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'utcTime' => array('type' => FILE_ASN1_TYPE_UTC_TIME), + 'generalTime' => array('type' => FILE_ASN1_TYPE_GENERALIZED_TIME) + ) + ); + + // http://tools.ietf.org/html/rfc5280#section-4.1.2.5 + $Validity = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'notBefore' => $Time, + 'notAfter' => $Time + ) + ); + + $CertificateSerialNumber = array('type' => FILE_ASN1_TYPE_INTEGER); + + $Version = array( + 'type' => FILE_ASN1_TYPE_INTEGER, + 'mapping' => array('v1', 'v2', 'v3') + ); + + // assert($TBSCertificate['children']['signature'] == $Certificate['children']['signatureAlgorithm']) + $TBSCertificate = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + // technically, default implies optional, but we'll define it as being optional, none-the-less, just to + // reenforce that fact + 'version' => array( + 'constant' => 0, + 'optional' => true, + 'explicit' => true, + 'default' => 'v1' + ) + $Version, + 'serialNumber' => $CertificateSerialNumber, + 'signature' => $AlgorithmIdentifier, + 'issuer' => $this->Name, + 'validity' => $Validity, + 'subject' => $this->Name, + 'subjectPublicKeyInfo' => $SubjectPublicKeyInfo, + // implicit means that the T in the TLV structure is to be rewritten, regardless of the type + 'issuerUniqueID' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $UniqueIdentifier, + 'subjectUniqueID' => array( + 'constant' => 2, + 'optional' => true, + 'implicit' => true + ) + $UniqueIdentifier, + // doesn't use the EXPLICIT keyword but if + // it's not IMPLICIT, it's EXPLICIT + 'extensions' => array( + 'constant' => 3, + 'optional' => true, + 'explicit' => true + ) + $this->Extensions + ) + ); + + $this->Certificate = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'tbsCertificate' => $TBSCertificate, + 'signatureAlgorithm' => $AlgorithmIdentifier, + 'signature' => array('type' => FILE_ASN1_TYPE_BIT_STRING) + ) + ); + + $this->KeyUsage = array( + 'type' => FILE_ASN1_TYPE_BIT_STRING, + 'mapping' => array( + 'digitalSignature', + 'nonRepudiation', + 'keyEncipherment', + 'dataEncipherment', + 'keyAgreement', + 'keyCertSign', + 'cRLSign', + 'encipherOnly', + 'decipherOnly' + ) + ); + + $this->BasicConstraints = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'cA' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'optional' => true, + 'default' => false + ), + 'pathLenConstraint' => array( + 'type' => FILE_ASN1_TYPE_INTEGER, + 'optional' => true + ) + ) + ); + + $this->KeyIdentifier = array('type' => FILE_ASN1_TYPE_OCTET_STRING); + + $OrganizationalUnitNames = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => 4, // ub-organizational-units + 'children' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING) + ); + + $PersonalName = array( + 'type' => FILE_ASN1_TYPE_SET, + 'children' => array( + 'surname' => array( + 'type' => FILE_ASN1_TYPE_PRINTABLE_STRING, + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ), + 'given-name' => array( + 'type' => FILE_ASN1_TYPE_PRINTABLE_STRING, + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ), + 'initials' => array( + 'type' => FILE_ASN1_TYPE_PRINTABLE_STRING, + 'constant' => 2, + 'optional' => true, + 'implicit' => true + ), + 'generation-qualifier' => array( + 'type' => FILE_ASN1_TYPE_PRINTABLE_STRING, + 'constant' => 3, + 'optional' => true, + 'implicit' => true + ) + ) + ); + + $NumericUserIdentifier = array('type' => FILE_ASN1_TYPE_NUMERIC_STRING); + + $OrganizationName = array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING); + + $PrivateDomainName = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'numeric' => array('type' => FILE_ASN1_TYPE_NUMERIC_STRING), + 'printable' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING) + ) + ); + + $TerminalIdentifier = array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING); + + $NetworkAddress = array('type' => FILE_ASN1_TYPE_NUMERIC_STRING); + + $AdministrationDomainName = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + // if class isn't present it's assumed to be FILE_ASN1_CLASS_UNIVERSAL or + // (if constant is present) FILE_ASN1_CLASS_CONTEXT_SPECIFIC + 'class' => FILE_ASN1_CLASS_APPLICATION, + 'cast' => 2, + 'children' => array( + 'numeric' => array('type' => FILE_ASN1_TYPE_NUMERIC_STRING), + 'printable' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING) + ) + ); + + $CountryName = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + // if class isn't present it's assumed to be FILE_ASN1_CLASS_UNIVERSAL or + // (if constant is present) FILE_ASN1_CLASS_CONTEXT_SPECIFIC + 'class' => FILE_ASN1_CLASS_APPLICATION, + 'cast' => 1, + 'children' => array( + 'x121-dcc-code' => array('type' => FILE_ASN1_TYPE_NUMERIC_STRING), + 'iso-3166-alpha2-code' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING) + ) + ); + + $AnotherName = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'type-id' => array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER), + 'value' => array( + 'type' => FILE_ASN1_TYPE_ANY, + 'constant' => 0, + 'optional' => true, + 'explicit' => true + ) + ) + ); + + $ExtensionAttribute = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'extension-attribute-type' => array( + 'type' => FILE_ASN1_TYPE_PRINTABLE_STRING, + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ), + 'extension-attribute-value' => array( + 'type' => FILE_ASN1_TYPE_ANY, + 'constant' => 1, + 'optional' => true, + 'explicit' => true + ) + ) + ); + + $ExtensionAttributes = array( + 'type' => FILE_ASN1_TYPE_SET, + 'min' => 1, + 'max' => 256, // ub-extension-attributes + 'children' => $ExtensionAttribute + ); + + $BuiltInDomainDefinedAttribute = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'type' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING), + 'value' => array('type' => FILE_ASN1_TYPE_PRINTABLE_STRING) + ) + ); + + $BuiltInDomainDefinedAttributes = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => 4, // ub-domain-defined-attributes + 'children' => $BuiltInDomainDefinedAttribute + ); + + $BuiltInStandardAttributes = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'country-name' => array('optional' => true) + $CountryName, + 'administration-domain-name' => array('optional' => true) + $AdministrationDomainName, + 'network-address' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $NetworkAddress, + 'terminal-identifier' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $TerminalIdentifier, + 'private-domain-name' => array( + 'constant' => 2, + 'optional' => true, + 'explicit' => true + ) + $PrivateDomainName, + 'organization-name' => array( + 'constant' => 3, + 'optional' => true, + 'implicit' => true + ) + $OrganizationName, + 'numeric-user-identifier' => array( + 'constant' => 4, + 'optional' => true, + 'implicit' => true + ) + $NumericUserIdentifier, + 'personal-name' => array( + 'constant' => 5, + 'optional' => true, + 'implicit' => true + ) + $PersonalName, + 'organizational-unit-names' => array( + 'constant' => 6, + 'optional' => true, + 'implicit' => true + ) + $OrganizationalUnitNames + ) + ); + + $ORAddress = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'built-in-standard-attributes' => $BuiltInStandardAttributes, + 'built-in-domain-defined-attributes' => array('optional' => true) + $BuiltInDomainDefinedAttributes, + 'extension-attributes' => array('optional' => true) + $ExtensionAttributes + ) + ); + + $EDIPartyName = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'nameAssigner' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $this->DirectoryString, + // partyName is technically required but File_ASN1 doesn't currently support non-optional constants and + // setting it to optional gets the job done in any event. + 'partyName' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $this->DirectoryString + ) + ); + + $GeneralName = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'otherName' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $AnotherName, + 'rfc822Name' => array( + 'type' => FILE_ASN1_TYPE_IA5_STRING, + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ), + 'dNSName' => array( + 'type' => FILE_ASN1_TYPE_IA5_STRING, + 'constant' => 2, + 'optional' => true, + 'implicit' => true + ), + 'x400Address' => array( + 'constant' => 3, + 'optional' => true, + 'implicit' => true + ) + $ORAddress, + 'directoryName' => array( + 'constant' => 4, + 'optional' => true, + 'explicit' => true + ) + $this->Name, + 'ediPartyName' => array( + 'constant' => 5, + 'optional' => true, + 'implicit' => true + ) + $EDIPartyName, + 'uniformResourceIdentifier' => array( + 'type' => FILE_ASN1_TYPE_IA5_STRING, + 'constant' => 6, + 'optional' => true, + 'implicit' => true + ), + 'iPAddress' => array( + 'type' => FILE_ASN1_TYPE_OCTET_STRING, + 'constant' => 7, + 'optional' => true, + 'implicit' => true + ), + 'registeredID' => array( + 'type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER, + 'constant' => 8, + 'optional' => true, + 'implicit' => true + ) + ) + ); + + $GeneralNames = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $GeneralName + ); + + $this->IssuerAltName = $GeneralNames; + + $ReasonFlags = array( + 'type' => FILE_ASN1_TYPE_BIT_STRING, + 'mapping' => array( + 'unused', + 'keyCompromise', + 'cACompromise', + 'affiliationChanged', + 'superseded', + 'cessationOfOperation', + 'certificateHold', + 'privilegeWithdrawn', + 'aACompromise' + ) + ); + + $DistributionPointName = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'fullName' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $GeneralNames, + 'nameRelativeToCRLIssuer' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $this->RelativeDistinguishedName + ) + ); + + $DistributionPoint = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'distributionPoint' => array( + 'constant' => 0, + 'optional' => true, + 'explicit' => true + ) + $DistributionPointName, + 'reasons' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $ReasonFlags, + 'cRLIssuer' => array( + 'constant' => 2, + 'optional' => true, + 'implicit' => true + ) + $GeneralNames + ) + ); + + $this->CRLDistributionPoints = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $DistributionPoint + ); + + $this->AuthorityKeyIdentifier = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'keyIdentifier' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $this->KeyIdentifier, + 'authorityCertIssuer' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $GeneralNames, + 'authorityCertSerialNumber' => array( + 'constant' => 2, + 'optional' => true, + 'implicit' => true + ) + $CertificateSerialNumber + ) + ); + + $PolicyQualifierId = array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER); + + $PolicyQualifierInfo = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'policyQualifierId' => $PolicyQualifierId, + 'qualifier' => array('type' => FILE_ASN1_TYPE_ANY) + ) + ); + + $CertPolicyId = array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER); + + $PolicyInformation = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'policyIdentifier' => $CertPolicyId, + 'policyQualifiers' => array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 0, + 'max' => -1, + 'optional' => true, + 'children' => $PolicyQualifierInfo + ) + ) + ); + + $this->CertificatePolicies = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $PolicyInformation + ); + + $this->PolicyMappings = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'issuerDomainPolicy' => $CertPolicyId, + 'subjectDomainPolicy' => $CertPolicyId + ) + ) + ); + + $KeyPurposeId = array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER); + + $this->ExtKeyUsageSyntax = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $KeyPurposeId + ); + + $AccessDescription = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'accessMethod' => array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER), + 'accessLocation' => $GeneralName + ) + ); + + $this->AuthorityInfoAccessSyntax = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $AccessDescription + ); + + $this->SubjectAltName = $GeneralNames; + + $this->PrivateKeyUsagePeriod = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'notBefore' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true, + 'type' => FILE_ASN1_TYPE_GENERALIZED_TIME), + 'notAfter' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true, + 'type' => FILE_ASN1_TYPE_GENERALIZED_TIME) + ) + ); + + $BaseDistance = array('type' => FILE_ASN1_TYPE_INTEGER); + + $GeneralSubtree = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'base' => $GeneralName, + 'minimum' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true, + 'default' => new Math_BigInteger(0) + ) + $BaseDistance, + 'maximum' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true, + ) + $BaseDistance + ) + ); + + $GeneralSubtrees = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $GeneralSubtree + ); + + $this->NameConstraints = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'permittedSubtrees' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $GeneralSubtrees, + 'excludedSubtrees' => array( + 'constant' => 1, + 'optional' => true, + 'implicit' => true + ) + $GeneralSubtrees + ) + ); + + $this->CPSuri = array('type' => FILE_ASN1_TYPE_IA5_STRING); + + $DisplayText = array( + 'type' => FILE_ASN1_TYPE_CHOICE, + 'children' => array( + 'ia5String' => array('type' => FILE_ASN1_TYPE_IA5_STRING), + 'visibleString' => array('type' => FILE_ASN1_TYPE_VISIBLE_STRING), + 'bmpString' => array('type' => FILE_ASN1_TYPE_BMP_STRING), + 'utf8String' => array('type' => FILE_ASN1_TYPE_UTF8_STRING) + ) + ); + + $NoticeReference = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'organization' => $DisplayText, + 'noticeNumbers' => array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => 200, + 'children' => array('type' => FILE_ASN1_TYPE_INTEGER) + ) + ) + ); + + $this->UserNotice = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'noticeRef' => array( + 'optional' => true, + 'implicit' => true + ) + $NoticeReference, + 'explicitText' => array( + 'optional' => true, + 'implicit' => true + ) + $DisplayText + ) + ); + + // mapping is from + $this->netscape_cert_type = array( + 'type' => FILE_ASN1_TYPE_BIT_STRING, + 'mapping' => array( + 'SSLClient', + 'SSLServer', + 'Email', + 'ObjectSigning', + 'Reserved', + 'SSLCA', + 'EmailCA', + 'ObjectSigningCA' + ) + ); + + $this->netscape_comment = array('type' => FILE_ASN1_TYPE_IA5_STRING); + $this->netscape_ca_policy_url = array('type' => FILE_ASN1_TYPE_IA5_STRING); + + // attribute is used in RFC2986 but we're using the RFC5280 definition + + $Attribute = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'type' => $AttributeType, + 'value'=> array( + 'type' => FILE_ASN1_TYPE_SET, + 'min' => 1, + 'max' => -1, + 'children' => $this->AttributeValue + ) + ) + ); + + $this->SubjectDirectoryAttributes = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'min' => 1, + 'max' => -1, + 'children' => $Attribute + ); + + // adapted from + + $Attributes = array( + 'type' => FILE_ASN1_TYPE_SET, + 'min' => 1, + 'max' => -1, + 'children' => $Attribute + ); + + $CertificationRequestInfo = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'version' => array( + 'type' => FILE_ASN1_TYPE_INTEGER, + 'mapping' => array('v1') + ), + 'subject' => $this->Name, + 'subjectPKInfo' => $SubjectPublicKeyInfo, + 'attributes' => array( + 'constant' => 0, + 'optional' => true, + 'implicit' => true + ) + $Attributes, + ) + ); + + $this->CertificationRequest = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'certificationRequestInfo' => $CertificationRequestInfo, + 'signatureAlgorithm' => $AlgorithmIdentifier, + 'signature' => array('type' => FILE_ASN1_TYPE_BIT_STRING) + ) + ); + + $RevokedCertificate = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'userCertificate' => $CertificateSerialNumber, + 'revocationDate' => $Time, + 'crlEntryExtensions' => array( + 'optional' => true + ) + $this->Extensions + ) + ); + + $TBSCertList = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'version' => array( + 'optional' => true, + 'default' => 'v1' + ) + $Version, + 'signature' => $AlgorithmIdentifier, + 'issuer' => $this->Name, + 'thisUpdate' => $Time, + 'nextUpdate' => array( + 'optional' => true + ) + $Time, + 'revokedCertificates' => array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'optional' => true, + 'min' => 0, + 'max' => -1, + 'children' => $RevokedCertificate + ), + 'crlExtensions' => array( + 'constant' => 0, + 'optional' => true, + 'explicit' => true + ) + $this->Extensions + ) + ); + + $this->CertificateList = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'tbsCertList' => $TBSCertList, + 'signatureAlgorithm' => $AlgorithmIdentifier, + 'signature' => array('type' => FILE_ASN1_TYPE_BIT_STRING) + ) + ); + + $this->CRLNumber = array('type' => FILE_ASN1_TYPE_INTEGER); + + $this->CRLReason = array('type' => FILE_ASN1_TYPE_ENUMERATED, + 'mapping' => array( + 'unspecified', + 'keyCompromise', + 'cACompromise', + 'affiliationChanged', + 'superseded', + 'cessationOfOperation', + 'certificateHold', + // Value 7 is not used. + 8 => 'removeFromCRL', + 'privilegeWithdrawn', + 'aACompromise' + ) + ); + + $this->IssuingDistributionPoint = array('type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'distributionPoint' => array( + 'constant' => 0, + 'optional' => true, + 'explicit' => true + ) + $DistributionPointName, + 'onlyContainsUserCerts' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'constant' => 1, + 'optional' => true, + 'default' => false, + 'implicit' => true + ), + 'onlyContainsCACerts' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'constant' => 2, + 'optional' => true, + 'default' => false, + 'implicit' => true + ), + 'onlySomeReasons' => array( + 'constant' => 3, + 'optional' => true, + 'implicit' => true + ) + $ReasonFlags, + 'indirectCRL' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'constant' => 4, + 'optional' => true, + 'default' => false, + 'implicit' => true + ), + 'onlyContainsAttributeCerts' => array( + 'type' => FILE_ASN1_TYPE_BOOLEAN, + 'constant' => 5, + 'optional' => true, + 'default' => false, + 'implicit' => true + ) + ) + ); + + $this->InvalidityDate = array('type' => FILE_ASN1_TYPE_GENERALIZED_TIME); + + $this->CertificateIssuer = $GeneralNames; + + $this->HoldInstructionCode = array('type' => FILE_ASN1_TYPE_OBJECT_IDENTIFIER); + + $PublicKeyAndChallenge = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'spki' => $SubjectPublicKeyInfo, + 'challenge' => array('type' => FILE_ASN1_TYPE_IA5_STRING) + ) + ); + + $this->SignedPublicKeyAndChallenge = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'children' => array( + 'publicKeyAndChallenge' => $PublicKeyAndChallenge, + 'signatureAlgorithm' => $AlgorithmIdentifier, + 'signature' => array('type' => FILE_ASN1_TYPE_BIT_STRING) + ) + ); + + $this->PostalAddress = array( + 'type' => FILE_ASN1_TYPE_SEQUENCE, + 'optional' => true, + 'min' => 1, + 'max' => -1, + 'children' => $this->DirectoryString + ); + + // OIDs from RFC5280 and those RFCs mentioned in RFC5280#section-4.1.1.2 + $this->oids = array( + '1.3.6.1.5.5.7' => 'id-pkix', + '1.3.6.1.5.5.7.1' => 'id-pe', + '1.3.6.1.5.5.7.2' => 'id-qt', + '1.3.6.1.5.5.7.3' => 'id-kp', + '1.3.6.1.5.5.7.48' => 'id-ad', + '1.3.6.1.5.5.7.2.1' => 'id-qt-cps', + '1.3.6.1.5.5.7.2.2' => 'id-qt-unotice', + '1.3.6.1.5.5.7.48.1' =>'id-ad-ocsp', + '1.3.6.1.5.5.7.48.2' => 'id-ad-caIssuers', + '1.3.6.1.5.5.7.48.3' => 'id-ad-timeStamping', + '1.3.6.1.5.5.7.48.5' => 'id-ad-caRepository', + '2.5.4' => 'id-at', + '2.5.4.41' => 'id-at-name', + '2.5.4.4' => 'id-at-surname', + '2.5.4.42' => 'id-at-givenName', + '2.5.4.43' => 'id-at-initials', + '2.5.4.44' => 'id-at-generationQualifier', + '2.5.4.3' => 'id-at-commonName', + '2.5.4.7' => 'id-at-localityName', + '2.5.4.8' => 'id-at-stateOrProvinceName', + '2.5.4.10' => 'id-at-organizationName', + '2.5.4.11' => 'id-at-organizationalUnitName', + '2.5.4.12' => 'id-at-title', + '2.5.4.13' => 'id-at-description', + '2.5.4.46' => 'id-at-dnQualifier', + '2.5.4.6' => 'id-at-countryName', + '2.5.4.5' => 'id-at-serialNumber', + '2.5.4.65' => 'id-at-pseudonym', + '2.5.4.17' => 'id-at-postalCode', + '2.5.4.9' => 'id-at-streetAddress', + '2.5.4.45' => 'id-at-uniqueIdentifier', + '2.5.4.72' => 'id-at-role', + '2.5.4.16' => 'id-at-postalAddress', + + '0.9.2342.19200300.100.1.25' => 'id-domainComponent', + '1.2.840.113549.1.9' => 'pkcs-9', + '1.2.840.113549.1.9.1' => 'pkcs-9-at-emailAddress', + '2.5.29' => 'id-ce', + '2.5.29.35' => 'id-ce-authorityKeyIdentifier', + '2.5.29.14' => 'id-ce-subjectKeyIdentifier', + '2.5.29.15' => 'id-ce-keyUsage', + '2.5.29.16' => 'id-ce-privateKeyUsagePeriod', + '2.5.29.32' => 'id-ce-certificatePolicies', + '2.5.29.32.0' => 'anyPolicy', + + '2.5.29.33' => 'id-ce-policyMappings', + '2.5.29.17' => 'id-ce-subjectAltName', + '2.5.29.18' => 'id-ce-issuerAltName', + '2.5.29.9' => 'id-ce-subjectDirectoryAttributes', + '2.5.29.19' => 'id-ce-basicConstraints', + '2.5.29.30' => 'id-ce-nameConstraints', + '2.5.29.36' => 'id-ce-policyConstraints', + '2.5.29.31' => 'id-ce-cRLDistributionPoints', + '2.5.29.37' => 'id-ce-extKeyUsage', + '2.5.29.37.0' => 'anyExtendedKeyUsage', + '1.3.6.1.5.5.7.3.1' => 'id-kp-serverAuth', + '1.3.6.1.5.5.7.3.2' => 'id-kp-clientAuth', + '1.3.6.1.5.5.7.3.3' => 'id-kp-codeSigning', + '1.3.6.1.5.5.7.3.4' => 'id-kp-emailProtection', + '1.3.6.1.5.5.7.3.8' => 'id-kp-timeStamping', + '1.3.6.1.5.5.7.3.9' => 'id-kp-OCSPSigning', + '2.5.29.54' => 'id-ce-inhibitAnyPolicy', + '2.5.29.46' => 'id-ce-freshestCRL', + '1.3.6.1.5.5.7.1.1' => 'id-pe-authorityInfoAccess', + '1.3.6.1.5.5.7.1.11' => 'id-pe-subjectInfoAccess', + '2.5.29.20' => 'id-ce-cRLNumber', + '2.5.29.28' => 'id-ce-issuingDistributionPoint', + '2.5.29.27' => 'id-ce-deltaCRLIndicator', + '2.5.29.21' => 'id-ce-cRLReasons', + '2.5.29.29' => 'id-ce-certificateIssuer', + '2.5.29.23' => 'id-ce-holdInstructionCode', + '1.2.840.10040.2' => 'holdInstruction', + '1.2.840.10040.2.1' => 'id-holdinstruction-none', + '1.2.840.10040.2.2' => 'id-holdinstruction-callissuer', + '1.2.840.10040.2.3' => 'id-holdinstruction-reject', + '2.5.29.24' => 'id-ce-invalidityDate', + + '1.2.840.113549.2.2' => 'md2', + '1.2.840.113549.2.5' => 'md5', + '1.3.14.3.2.26' => 'id-sha1', + '1.2.840.10040.4.1' => 'id-dsa', + '1.2.840.10040.4.3' => 'id-dsa-with-sha1', + '1.2.840.113549.1.1' => 'pkcs-1', + '1.2.840.113549.1.1.1' => 'rsaEncryption', + '1.2.840.113549.1.1.2' => 'md2WithRSAEncryption', + '1.2.840.113549.1.1.4' => 'md5WithRSAEncryption', + '1.2.840.113549.1.1.5' => 'sha1WithRSAEncryption', + '1.2.840.10046.2.1' => 'dhpublicnumber', + '2.16.840.1.101.2.1.1.22' => 'id-keyExchangeAlgorithm', + '1.2.840.10045' => 'ansi-X9-62', + '1.2.840.10045.4' => 'id-ecSigType', + '1.2.840.10045.4.1' => 'ecdsa-with-SHA1', + '1.2.840.10045.1' => 'id-fieldType', + '1.2.840.10045.1.1' => 'prime-field', + '1.2.840.10045.1.2' => 'characteristic-two-field', + '1.2.840.10045.1.2.3' => 'id-characteristic-two-basis', + '1.2.840.10045.1.2.3.1' => 'gnBasis', + '1.2.840.10045.1.2.3.2' => 'tpBasis', + '1.2.840.10045.1.2.3.3' => 'ppBasis', + '1.2.840.10045.2' => 'id-publicKeyType', + '1.2.840.10045.2.1' => 'id-ecPublicKey', + '1.2.840.10045.3' => 'ellipticCurve', + '1.2.840.10045.3.0' => 'c-TwoCurve', + '1.2.840.10045.3.0.1' => 'c2pnb163v1', + '1.2.840.10045.3.0.2' => 'c2pnb163v2', + '1.2.840.10045.3.0.3' => 'c2pnb163v3', + '1.2.840.10045.3.0.4' => 'c2pnb176w1', + '1.2.840.10045.3.0.5' => 'c2pnb191v1', + '1.2.840.10045.3.0.6' => 'c2pnb191v2', + '1.2.840.10045.3.0.7' => 'c2pnb191v3', + '1.2.840.10045.3.0.8' => 'c2pnb191v4', + '1.2.840.10045.3.0.9' => 'c2pnb191v5', + '1.2.840.10045.3.0.10' => 'c2pnb208w1', + '1.2.840.10045.3.0.11' => 'c2pnb239v1', + '1.2.840.10045.3.0.12' => 'c2pnb239v2', + '1.2.840.10045.3.0.13' => 'c2pnb239v3', + '1.2.840.10045.3.0.14' => 'c2pnb239v4', + '1.2.840.10045.3.0.15' => 'c2pnb239v5', + '1.2.840.10045.3.0.16' => 'c2pnb272w1', + '1.2.840.10045.3.0.17' => 'c2pnb304w1', + '1.2.840.10045.3.0.18' => 'c2pnb359v1', + '1.2.840.10045.3.0.19' => 'c2pnb368w1', + '1.2.840.10045.3.0.20' => 'c2pnb431r1', + '1.2.840.10045.3.1' => 'primeCurve', + '1.2.840.10045.3.1.1' => 'prime192v1', + '1.2.840.10045.3.1.2' => 'prime192v2', + '1.2.840.10045.3.1.3' => 'prime192v3', + '1.2.840.10045.3.1.4' => 'prime239v1', + '1.2.840.10045.3.1.5' => 'prime239v2', + '1.2.840.10045.3.1.6' => 'prime239v3', + '1.2.840.10045.3.1.7' => 'prime256v1', + '1.2.840.113549.1.1.7' => 'id-RSAES-OAEP', + '1.2.840.113549.1.1.9' => 'id-pSpecified', + '1.2.840.113549.1.1.10' => 'id-RSASSA-PSS', + '1.2.840.113549.1.1.8' => 'id-mgf1', + '1.2.840.113549.1.1.14' => 'sha224WithRSAEncryption', + '1.2.840.113549.1.1.11' => 'sha256WithRSAEncryption', + '1.2.840.113549.1.1.12' => 'sha384WithRSAEncryption', + '1.2.840.113549.1.1.13' => 'sha512WithRSAEncryption', + '2.16.840.1.101.3.4.2.4' => 'id-sha224', + '2.16.840.1.101.3.4.2.1' => 'id-sha256', + '2.16.840.1.101.3.4.2.2' => 'id-sha384', + '2.16.840.1.101.3.4.2.3' => 'id-sha512', + '1.2.643.2.2.4' => 'id-GostR3411-94-with-GostR3410-94', + '1.2.643.2.2.3' => 'id-GostR3411-94-with-GostR3410-2001', + '1.2.643.2.2.20' => 'id-GostR3410-2001', + '1.2.643.2.2.19' => 'id-GostR3410-94', + // Netscape Object Identifiers from "Netscape Certificate Extensions" + '2.16.840.1.113730' => 'netscape', + '2.16.840.1.113730.1' => 'netscape-cert-extension', + '2.16.840.1.113730.1.1' => 'netscape-cert-type', + '2.16.840.1.113730.1.13' => 'netscape-comment', + '2.16.840.1.113730.1.8' => 'netscape-ca-policy-url', + // the following are X.509 extensions not supported by phpseclib + '1.3.6.1.5.5.7.1.12' => 'id-pe-logotype', + '1.2.840.113533.7.65.0' => 'entrustVersInfo', + '2.16.840.1.113733.1.6.9' => 'verisignPrivate', + // for Certificate Signing Requests + // see http://tools.ietf.org/html/rfc2985 + '1.2.840.113549.1.9.2' => 'pkcs-9-at-unstructuredName', // PKCS #9 unstructured name + '1.2.840.113549.1.9.7' => 'pkcs-9-at-challengePassword', // Challenge password for certificate revocations + '1.2.840.113549.1.9.14' => 'pkcs-9-at-extensionRequest' // Certificate extension request + ); + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function File_X509() + { + $this->__construct(); + } + + /** + * Load X.509 certificate + * + * Returns an associative array describing the X.509 cert or a false if the cert failed to load + * + * @param string $cert + * @param int $mode + * @access public + * @return mixed + */ + function loadX509($cert, $mode = FILE_X509_FORMAT_AUTO_DETECT) + { + if (is_array($cert) && isset($cert['tbsCertificate'])) { + unset($this->currentCert); + unset($this->currentKeyIdentifier); + $this->dn = $cert['tbsCertificate']['subject']; + if (!isset($this->dn)) { + return false; + } + $this->currentCert = $cert; + + $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier'); + $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null; + + unset($this->signatureSubject); + + return $cert; + } + + $asn1 = new File_ASN1(); + + if ($mode != FILE_X509_FORMAT_DER) { + $newcert = $this->_extractBER($cert); + if ($mode == FILE_X509_FORMAT_PEM && $cert == $newcert) { + return false; + } + $cert = $newcert; + } + + if ($cert === false) { + $this->currentCert = false; + return false; + } + + $asn1->loadOIDs($this->oids); + $decoded = $asn1->decodeBER($cert); + + if (!empty($decoded)) { + $x509 = $asn1->asn1map($decoded[0], $this->Certificate); + } + if (!isset($x509) || $x509 === false) { + $this->currentCert = false; + return false; + } + + $this->signatureSubject = substr($cert, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); + + if ($this->_isSubArrayValid($x509, 'tbsCertificate/extensions')) { + $this->_mapInExtensions($x509, 'tbsCertificate/extensions', $asn1); + } + $this->_mapInDNs($x509, 'tbsCertificate/issuer/rdnSequence', $asn1); + $this->_mapInDNs($x509, 'tbsCertificate/subject/rdnSequence', $asn1); + + $key = &$x509['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']; + $key = $this->_reformatKey($x509['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], $key); + + $this->currentCert = $x509; + $this->dn = $x509['tbsCertificate']['subject']; + + $currentKeyIdentifier = $this->getExtension('id-ce-subjectKeyIdentifier'); + $this->currentKeyIdentifier = is_string($currentKeyIdentifier) ? $currentKeyIdentifier : null; + + return $x509; + } + + /** + * Save X.509 certificate + * + * @param array $cert + * @param int $format optional + * @access public + * @return string + */ + function saveX509($cert, $format = FILE_X509_FORMAT_PEM) + { + if (!is_array($cert) || !isset($cert['tbsCertificate'])) { + return false; + } + + switch (true) { + // "case !$a: case !$b: break; default: whatever();" is the same thing as "if ($a && $b) whatever()" + case !($algorithm = $this->_subArray($cert, 'tbsCertificate/subjectPublicKeyInfo/algorithm/algorithm')): + case is_object($cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']): + break; + default: + switch ($algorithm) { + case 'rsaEncryption': + $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'] + = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $cert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']))); + /* "[For RSA keys] the parameters field MUST have ASN.1 type NULL for this algorithm identifier." + -- https://tools.ietf.org/html/rfc3279#section-2.3.1 + + given that and the fact that RSA keys appear ot be the only key type for which the parameters field can be blank, + it seems like perhaps the ASN.1 description ought not say the parameters field is OPTIONAL, but whatever. + */ + $cert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = null; + // https://tools.ietf.org/html/rfc3279#section-2.2.1 + $cert['signatureAlgorithm']['parameters'] = null; + $cert['tbsCertificate']['signature']['parameters'] = null; + } + } + + $asn1 = new File_ASN1(); + $asn1->loadOIDs($this->oids); + + $filters = array(); + $type_utf8_string = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $filters['tbsCertificate']['signature']['parameters'] = $type_utf8_string; + $filters['tbsCertificate']['signature']['issuer']['rdnSequence']['value'] = $type_utf8_string; + $filters['tbsCertificate']['issuer']['rdnSequence']['value'] = $type_utf8_string; + $filters['tbsCertificate']['subject']['rdnSequence']['value'] = $type_utf8_string; + $filters['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['parameters'] = $type_utf8_string; + $filters['signatureAlgorithm']['parameters'] = $type_utf8_string; + $filters['authorityCertIssuer']['directoryName']['rdnSequence']['value'] = $type_utf8_string; + //$filters['policyQualifiers']['qualifier'] = $type_utf8_string; + $filters['distributionPoint']['fullName']['directoryName']['rdnSequence']['value'] = $type_utf8_string; + $filters['directoryName']['rdnSequence']['value'] = $type_utf8_string; + + /* in the case of policyQualifiers/qualifier, the type has to be FILE_ASN1_TYPE_IA5_STRING. + FILE_ASN1_TYPE_PRINTABLE_STRING will cause OpenSSL's X.509 parser to spit out random + characters. + */ + $filters['policyQualifiers']['qualifier'] + = array('type' => FILE_ASN1_TYPE_IA5_STRING); + + $asn1->loadFilters($filters); + + $this->_mapOutExtensions($cert, 'tbsCertificate/extensions', $asn1); + $this->_mapOutDNs($cert, 'tbsCertificate/issuer/rdnSequence', $asn1); + $this->_mapOutDNs($cert, 'tbsCertificate/subject/rdnSequence', $asn1); + + $cert = $asn1->encodeDER($cert, $this->Certificate); + + switch ($format) { + case FILE_X509_FORMAT_DER: + return $cert; + // case FILE_X509_FORMAT_PEM: + default: + return "-----BEGIN CERTIFICATE-----\r\n" . chunk_split(base64_encode($cert), 64) . '-----END CERTIFICATE-----'; + } + } + + /** + * Map extension values from octet string to extension-specific internal + * format. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapInExtensions(&$root, $path, $asn1) + { + $extensions = &$this->_subArrayUnchecked($root, $path); + + if ($extensions) { + for ($i = 0; $i < count($extensions); $i++) { + $id = $extensions[$i]['extnId']; + $value = &$extensions[$i]['extnValue']; + $value = base64_decode($value); + $decoded = $asn1->decodeBER($value); + /* [extnValue] contains the DER encoding of an ASN.1 value + corresponding to the extension type identified by extnID */ + $map = $this->_getMapping($id); + if (!is_bool($map)) { + $mapped = $asn1->asn1map($decoded[0], $map, array('iPAddress' => array($this, '_decodeIP'))); + $value = $mapped === false ? $decoded[0] : $mapped; + + if ($id == 'id-ce-certificatePolicies') { + for ($j = 0; $j < count($value); $j++) { + if (!isset($value[$j]['policyQualifiers'])) { + continue; + } + for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) { + $subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId']; + $map = $this->_getMapping($subid); + $subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier']; + if ($map !== false) { + $decoded = $asn1->decodeBER($subvalue); + $mapped = $asn1->asn1map($decoded[0], $map); + $subvalue = $mapped === false ? $decoded[0] : $mapped; + } + } + } + } + } else { + $value = base64_encode($value); + } + } + } + } + + /** + * Map extension values from extension-specific internal format to + * octet string. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapOutExtensions(&$root, $path, $asn1) + { + $extensions = &$this->_subArray($root, $path); + + if (is_array($extensions)) { + $size = count($extensions); + for ($i = 0; $i < $size; $i++) { + if (is_object($extensions[$i]) && strtolower(get_class($extensions[$i])) == 'file_asn1_element') { + continue; + } + + $id = $extensions[$i]['extnId']; + $value = &$extensions[$i]['extnValue']; + + switch ($id) { + case 'id-ce-certificatePolicies': + for ($j = 0; $j < count($value); $j++) { + if (!isset($value[$j]['policyQualifiers'])) { + continue; + } + for ($k = 0; $k < count($value[$j]['policyQualifiers']); $k++) { + $subid = $value[$j]['policyQualifiers'][$k]['policyQualifierId']; + $map = $this->_getMapping($subid); + $subvalue = &$value[$j]['policyQualifiers'][$k]['qualifier']; + if ($map !== false) { + // by default File_ASN1 will try to render qualifier as a FILE_ASN1_TYPE_IA5_STRING since it's + // actual type is FILE_ASN1_TYPE_ANY + $subvalue = new File_ASN1_Element($asn1->encodeDER($subvalue, $map)); + } + } + } + break; + case 'id-ce-authorityKeyIdentifier': // use 00 as the serial number instead of an empty string + if (isset($value['authorityCertSerialNumber'])) { + if ($value['authorityCertSerialNumber']->toBytes() == '') { + $temp = chr((FILE_ASN1_CLASS_CONTEXT_SPECIFIC << 6) | 2) . "\1\0"; + $value['authorityCertSerialNumber'] = new File_ASN1_Element($temp); + } + } + } + + /* [extnValue] contains the DER encoding of an ASN.1 value + corresponding to the extension type identified by extnID */ + $map = $this->_getMapping($id); + if (is_bool($map)) { + if (!$map) { + user_error($id . ' is not a currently supported extension'); + unset($extensions[$i]); + } + } else { + $temp = $asn1->encodeDER($value, $map, array('iPAddress' => array($this, '_encodeIP'))); + $value = base64_encode($temp); + } + } + } + } + + /** + * Map attribute values from ANY type to attribute-specific internal + * format. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapInAttributes(&$root, $path, $asn1) + { + $attributes = &$this->_subArray($root, $path); + + if (is_array($attributes)) { + for ($i = 0; $i < count($attributes); $i++) { + $id = $attributes[$i]['type']; + /* $value contains the DER encoding of an ASN.1 value + corresponding to the attribute type identified by type */ + $map = $this->_getMapping($id); + if (is_array($attributes[$i]['value'])) { + $values = &$attributes[$i]['value']; + for ($j = 0; $j < count($values); $j++) { + $value = $asn1->encodeDER($values[$j], $this->AttributeValue); + $decoded = $asn1->decodeBER($value); + if (!is_bool($map)) { + $mapped = $asn1->asn1map($decoded[0], $map); + if ($mapped !== false) { + $values[$j] = $mapped; + } + if ($id == 'pkcs-9-at-extensionRequest' && $this->_isSubArrayValid($values, $j)) { + $this->_mapInExtensions($values, $j, $asn1); + } + } elseif ($map) { + $values[$j] = base64_encode($value); + } + } + } + } + } + } + + /** + * Map attribute values from attribute-specific internal format to + * ANY type. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapOutAttributes(&$root, $path, $asn1) + { + $attributes = &$this->_subArray($root, $path); + + if (is_array($attributes)) { + $size = count($attributes); + for ($i = 0; $i < $size; $i++) { + /* [value] contains the DER encoding of an ASN.1 value + corresponding to the attribute type identified by type */ + $id = $attributes[$i]['type']; + $map = $this->_getMapping($id); + if ($map === false) { + user_error($id . ' is not a currently supported attribute', E_USER_NOTICE); + unset($attributes[$i]); + } elseif (is_array($attributes[$i]['value'])) { + $values = &$attributes[$i]['value']; + for ($j = 0; $j < count($values); $j++) { + switch ($id) { + case 'pkcs-9-at-extensionRequest': + $this->_mapOutExtensions($values, $j, $asn1); + break; + } + + if (!is_bool($map)) { + $temp = $asn1->encodeDER($values[$j], $map); + $decoded = $asn1->decodeBER($temp); + $values[$j] = $asn1->asn1map($decoded[0], $this->AttributeValue); + } + } + } + } + } + } + + /** + * Map DN values from ANY type to DN-specific internal + * format. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapInDNs(&$root, $path, $asn1) + { + $dns = &$this->_subArray($root, $path); + + if (is_array($dns)) { + for ($i = 0; $i < count($dns); $i++) { + for ($j = 0; $j < count($dns[$i]); $j++) { + $type = $dns[$i][$j]['type']; + $value = &$dns[$i][$j]['value']; + if (is_object($value) && strtolower(get_class($value)) == 'file_asn1_element') { + $map = $this->_getMapping($type); + if (!is_bool($map)) { + $decoded = $asn1->decodeBER($value); + $value = $asn1->asn1map($decoded[0], $map); + } + } + } + } + } + } + + /** + * Map DN values from DN-specific internal format to + * ANY type. + * + * @param array ref $root + * @param string $path + * @param object $asn1 + * @access private + */ + function _mapOutDNs(&$root, $path, $asn1) + { + $dns = &$this->_subArray($root, $path); + + if (is_array($dns)) { + $size = count($dns); + for ($i = 0; $i < $size; $i++) { + for ($j = 0; $j < count($dns[$i]); $j++) { + $type = $dns[$i][$j]['type']; + $value = &$dns[$i][$j]['value']; + if (is_object($value) && strtolower(get_class($value)) == 'file_asn1_element') { + continue; + } + + $map = $this->_getMapping($type); + if (!is_bool($map)) { + $value = new File_ASN1_Element($asn1->encodeDER($value, $map)); + } + } + } + } + } + + /** + * Associate an extension ID to an extension mapping + * + * @param string $extnId + * @access private + * @return mixed + */ + function _getMapping($extnId) + { + if (!is_string($extnId)) { // eg. if it's a File_ASN1_Element object + return true; + } + + switch ($extnId) { + case 'id-ce-keyUsage': + return $this->KeyUsage; + case 'id-ce-basicConstraints': + return $this->BasicConstraints; + case 'id-ce-subjectKeyIdentifier': + return $this->KeyIdentifier; + case 'id-ce-cRLDistributionPoints': + return $this->CRLDistributionPoints; + case 'id-ce-authorityKeyIdentifier': + return $this->AuthorityKeyIdentifier; + case 'id-ce-certificatePolicies': + return $this->CertificatePolicies; + case 'id-ce-extKeyUsage': + return $this->ExtKeyUsageSyntax; + case 'id-pe-authorityInfoAccess': + return $this->AuthorityInfoAccessSyntax; + case 'id-ce-subjectAltName': + return $this->SubjectAltName; + case 'id-ce-subjectDirectoryAttributes': + return $this->SubjectDirectoryAttributes; + case 'id-ce-privateKeyUsagePeriod': + return $this->PrivateKeyUsagePeriod; + case 'id-ce-issuerAltName': + return $this->IssuerAltName; + case 'id-ce-policyMappings': + return $this->PolicyMappings; + case 'id-ce-nameConstraints': + return $this->NameConstraints; + + case 'netscape-cert-type': + return $this->netscape_cert_type; + case 'netscape-comment': + return $this->netscape_comment; + case 'netscape-ca-policy-url': + return $this->netscape_ca_policy_url; + + // since id-qt-cps isn't a constructed type it will have already been decoded as a string by the time it gets + // back around to asn1map() and we don't want it decoded again. + //case 'id-qt-cps': + // return $this->CPSuri; + case 'id-qt-unotice': + return $this->UserNotice; + + // the following OIDs are unsupported but we don't want them to give notices when calling saveX509(). + case 'id-pe-logotype': // http://www.ietf.org/rfc/rfc3709.txt + case 'entrustVersInfo': + // http://support.microsoft.com/kb/287547 + case '1.3.6.1.4.1.311.20.2': // szOID_ENROLL_CERTTYPE_EXTENSION + case '1.3.6.1.4.1.311.21.1': // szOID_CERTSRV_CA_VERSION + // "SET Secure Electronic Transaction Specification" + // http://www.maithean.com/docs/set_bk3.pdf + case '2.23.42.7.0': // id-set-hashedRootKey + // "Certificate Transparency" + // https://tools.ietf.org/html/rfc6962 + case '1.3.6.1.4.1.11129.2.4.2': + return true; + + // CSR attributes + case 'pkcs-9-at-unstructuredName': + return $this->PKCS9String; + case 'pkcs-9-at-challengePassword': + return $this->DirectoryString; + case 'pkcs-9-at-extensionRequest': + return $this->Extensions; + + // CRL extensions. + case 'id-ce-cRLNumber': + return $this->CRLNumber; + case 'id-ce-deltaCRLIndicator': + return $this->CRLNumber; + case 'id-ce-issuingDistributionPoint': + return $this->IssuingDistributionPoint; + case 'id-ce-freshestCRL': + return $this->CRLDistributionPoints; + case 'id-ce-cRLReasons': + return $this->CRLReason; + case 'id-ce-invalidityDate': + return $this->InvalidityDate; + case 'id-ce-certificateIssuer': + return $this->CertificateIssuer; + case 'id-ce-holdInstructionCode': + return $this->HoldInstructionCode; + case 'id-at-postalAddress': + return $this->PostalAddress; + } + + return false; + } + + /** + * Load an X.509 certificate as a certificate authority + * + * @param string $cert + * @access public + * @return bool + */ + function loadCA($cert) + { + $olddn = $this->dn; + $oldcert = $this->currentCert; + $oldsigsubj = $this->signatureSubject; + $oldkeyid = $this->currentKeyIdentifier; + + $cert = $this->loadX509($cert); + if (!$cert) { + $this->dn = $olddn; + $this->currentCert = $oldcert; + $this->signatureSubject = $oldsigsubj; + $this->currentKeyIdentifier = $oldkeyid; + + return false; + } + + /* From RFC5280 "PKIX Certificate and CRL Profile": + + If the keyUsage extension is present, then the subject public key + MUST NOT be used to verify signatures on certificates or CRLs unless + the corresponding keyCertSign or cRLSign bit is set. */ + //$keyUsage = $this->getExtension('id-ce-keyUsage'); + //if ($keyUsage && !in_array('keyCertSign', $keyUsage)) { + // return false; + //} + + /* From RFC5280 "PKIX Certificate and CRL Profile": + + The cA boolean indicates whether the certified public key may be used + to verify certificate signatures. If the cA boolean is not asserted, + then the keyCertSign bit in the key usage extension MUST NOT be + asserted. If the basic constraints extension is not present in a + version 3 certificate, or the extension is present but the cA boolean + is not asserted, then the certified public key MUST NOT be used to + verify certificate signatures. */ + //$basicConstraints = $this->getExtension('id-ce-basicConstraints'); + //if (!$basicConstraints || !$basicConstraints['cA']) { + // return false; + //} + + $this->CAs[] = $cert; + + $this->dn = $olddn; + $this->currentCert = $oldcert; + $this->signatureSubject = $oldsigsubj; + + return true; + } + + /** + * Validate an X.509 certificate against a URL + * + * From RFC2818 "HTTP over TLS": + * + * Matching is performed using the matching rules specified by + * [RFC2459]. If more than one identity of a given type is present in + * the certificate (e.g., more than one dNSName name, a match in any one + * of the set is considered acceptable.) Names may contain the wildcard + * character * which is considered to match any single domain name + * component or component fragment. E.g., *.a.com matches foo.a.com but + * not bar.foo.a.com. f*.com matches foo.com but not bar.com. + * + * @param string $url + * @access public + * @return bool + */ + function validateURL($url) + { + if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { + return false; + } + + $components = parse_url($url); + if (!isset($components['host'])) { + return false; + } + + if ($names = $this->getExtension('id-ce-subjectAltName')) { + foreach ($names as $name) { + foreach ($name as $key => $value) { + $value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value); + switch ($key) { + case 'dNSName': + /* From RFC2818 "HTTP over TLS": + + If a subjectAltName extension of type dNSName is present, that MUST + be used as the identity. Otherwise, the (most specific) Common Name + field in the Subject field of the certificate MUST be used. Although + the use of the Common Name is existing practice, it is deprecated and + Certification Authorities are encouraged to use the dNSName instead. */ + if (preg_match('#^' . $value . '$#', $components['host'])) { + return true; + } + break; + case 'iPAddress': + /* From RFC2818 "HTTP over TLS": + + In some cases, the URI is specified as an IP address rather than a + hostname. In this case, the iPAddress subjectAltName must be present + in the certificate and must exactly match the IP in the URI. */ + if (preg_match('#(?:\d{1-3}\.){4}#', $components['host'] . '.') && preg_match('#^' . $value . '$#', $components['host'])) { + return true; + } + } + } + } + return false; + } + + if ($value = $this->getDNProp('id-at-commonName')) { + $value = str_replace(array('.', '*'), array('\.', '[^.]*'), $value[0]); + return preg_match('#^' . $value . '$#', $components['host']); + } + + return false; + } + + /** + * Validate a date + * + * If $date isn't defined it is assumed to be the current date. + * + * @param int $date optional + * @access public + */ + function validateDate($date = null) + { + if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { + return false; + } + + if (!isset($date)) { + $date = class_exists('DateTime') ? + new DateTime($date, new DateTimeZone(@date_default_timezone_get())) : + time(); + } + + $notBefore = $this->currentCert['tbsCertificate']['validity']['notBefore']; + $notBefore = isset($notBefore['generalTime']) ? $notBefore['generalTime'] : $notBefore['utcTime']; + + $notAfter = $this->currentCert['tbsCertificate']['validity']['notAfter']; + $notAfter = isset($notAfter['generalTime']) ? $notAfter['generalTime'] : $notAfter['utcTime']; + + if (class_exists('DateTime')) { + $notBefore = new DateTime($notBefore, new DateTimeZone(@date_default_timezone_get())); + $notAfter = new DateTime($notAfter, new DateTimeZone(@date_default_timezone_get())); + } else { + $notBefore = @strtotime($notBefore); + $notAfter = @strtotime($notAfter); + } + + switch (true) { + case $date < $notBefore: + case $date > $notAfter: + return false; + } + + return true; + } + + /** + * Validate a signature + * + * Works on X.509 certs, CSR's and CRL's. + * Returns true if the signature is verified, false if it is not correct or null on error + * + * By default returns false for self-signed certs. Call validateSignature(false) to make this support + * self-signed. + * + * The behavior of this function is inspired by {@link http://php.net/openssl-verify openssl_verify}. + * + * @param bool $caonly optional + * @access public + * @return mixed + */ + function validateSignature($caonly = true) + { + if (!is_array($this->currentCert) || !isset($this->signatureSubject)) { + return null; + } + + /* TODO: + "emailAddress attribute values are not case-sensitive (e.g., "subscriber@example.com" is the same as "SUBSCRIBER@EXAMPLE.COM")." + -- http://tools.ietf.org/html/rfc5280#section-4.1.2.6 + + implement pathLenConstraint in the id-ce-basicConstraints extension */ + + switch (true) { + case isset($this->currentCert['tbsCertificate']): + // self-signed cert + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $this->currentCert['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getIssuerDN(FILE_X509_DN_STRING) === $this->getDN(FILE_X509_DN_STRING): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier'); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $this->currentCert; // working cert + } + } + + if (!empty($this->CAs)) { + for ($i = 0; $i < count($this->CAs); $i++) { + // even if the cert is a self-signed one we still want to see if it's a CA; + // if not, we'll conditionally return an error + $ca = $this->CAs[$i]; + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(FILE_X509_DN_STRING, $this->currentCert['tbsCertificate']['issuer']) === $this->getDN(FILE_X509_DN_STRING, $ca['tbsCertificate']['subject']): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $ca; // working cert + break 3; + } + } + } + if (count($this->CAs) == $i && $caonly) { + return false; + } + } elseif (!isset($signingCert) || $caonly) { + return false; + } + return $this->_validateSignature( + $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], + $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], + $this->currentCert['signatureAlgorithm']['algorithm'], + substr(base64_decode($this->currentCert['signature']), 1), + $this->signatureSubject + ); + case isset($this->currentCert['certificationRequestInfo']): + return $this->_validateSignature( + $this->currentCert['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm'], + $this->currentCert['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], + $this->currentCert['signatureAlgorithm']['algorithm'], + substr(base64_decode($this->currentCert['signature']), 1), + $this->signatureSubject + ); + case isset($this->currentCert['publicKeyAndChallenge']): + return $this->_validateSignature( + $this->currentCert['publicKeyAndChallenge']['spki']['algorithm']['algorithm'], + $this->currentCert['publicKeyAndChallenge']['spki']['subjectPublicKey'], + $this->currentCert['signatureAlgorithm']['algorithm'], + substr(base64_decode($this->currentCert['signature']), 1), + $this->signatureSubject + ); + case isset($this->currentCert['tbsCertList']): + if (!empty($this->CAs)) { + for ($i = 0; $i < count($this->CAs); $i++) { + $ca = $this->CAs[$i]; + switch (true) { + case !defined('FILE_X509_IGNORE_TYPE') && $this->currentCert['tbsCertList']['issuer'] === $ca['tbsCertificate']['subject']: + case defined('FILE_X509_IGNORE_TYPE') && $this->getDN(FILE_X509_DN_STRING, $this->currentCert['tbsCertList']['issuer']) === $this->getDN(FILE_X509_DN_STRING, $ca['tbsCertificate']['subject']): + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier'); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + $signingCert = $ca; // working cert + break 3; + } + } + } + } + if (!isset($signingCert)) { + return false; + } + return $this->_validateSignature( + $signingCert['tbsCertificate']['subjectPublicKeyInfo']['algorithm']['algorithm'], + $signingCert['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], + $this->currentCert['signatureAlgorithm']['algorithm'], + substr(base64_decode($this->currentCert['signature']), 1), + $this->signatureSubject + ); + default: + return false; + } + } + + /** + * Validates a signature + * + * Returns true if the signature is verified, false if it is not correct or null on error + * + * @param string $publicKeyAlgorithm + * @param string $publicKey + * @param string $signatureAlgorithm + * @param string $signature + * @param string $signatureSubject + * @access private + * @return int + */ + function _validateSignature($publicKeyAlgorithm, $publicKey, $signatureAlgorithm, $signature, $signatureSubject) + { + switch ($publicKeyAlgorithm) { + case 'rsaEncryption': + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $rsa = new Crypt_RSA(); + $rsa->loadKey($publicKey); + + switch ($signatureAlgorithm) { + case 'md2WithRSAEncryption': + case 'md5WithRSAEncryption': + case 'sha1WithRSAEncryption': + case 'sha224WithRSAEncryption': + case 'sha256WithRSAEncryption': + case 'sha384WithRSAEncryption': + case 'sha512WithRSAEncryption': + $rsa->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); + $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); + if (!@$rsa->verify($signatureSubject, $signature)) { + return false; + } + break; + default: + return null; + } + break; + default: + return null; + } + + return true; + } + + /** + * Reformat public keys + * + * Reformats a public key to a format supported by phpseclib (if applicable) + * + * @param string $algorithm + * @param string $key + * @access private + * @return string + */ + function _reformatKey($algorithm, $key) + { + switch ($algorithm) { + case 'rsaEncryption': + return + "-----BEGIN RSA PUBLIC KEY-----\r\n" . + // subjectPublicKey is stored as a bit string in X.509 certs. the first byte of a bit string represents how many bits + // in the last byte should be ignored. the following only supports non-zero stuff but as none of the X.509 certs Firefox + // uses as a cert authority actually use a non-zero bit I think it's safe to assume that none do. + chunk_split(base64_encode(substr(base64_decode($key), 1)), 64) . + '-----END RSA PUBLIC KEY-----'; + default: + return $key; + } + } + + /** + * Decodes an IP address + * + * Takes in a base64 encoded "blob" and returns a human readable IP address + * + * @param string $ip + * @access private + * @return string + */ + function _decodeIP($ip) + { + $ip = base64_decode($ip); + list(, $ip) = unpack('N', $ip); + return long2ip($ip); + } + + /** + * Encodes an IP address + * + * Takes a human readable IP address into a base64-encoded "blob" + * + * @param string $ip + * @access private + * @return string + */ + function _encodeIP($ip) + { + return base64_encode(pack('N', ip2long($ip))); + } + + /** + * "Normalizes" a Distinguished Name property + * + * @param string $propName + * @access private + * @return mixed + */ + function _translateDNProp($propName) + { + switch (strtolower($propName)) { + case 'id-at-countryname': + case 'countryname': + case 'c': + return 'id-at-countryName'; + case 'id-at-organizationname': + case 'organizationname': + case 'o': + return 'id-at-organizationName'; + case 'id-at-dnqualifier': + case 'dnqualifier': + return 'id-at-dnQualifier'; + case 'id-at-commonname': + case 'commonname': + case 'cn': + return 'id-at-commonName'; + case 'id-at-stateorprovincename': + case 'stateorprovincename': + case 'state': + case 'province': + case 'provincename': + case 'st': + return 'id-at-stateOrProvinceName'; + case 'id-at-localityname': + case 'localityname': + case 'l': + return 'id-at-localityName'; + case 'id-emailaddress': + case 'emailaddress': + return 'pkcs-9-at-emailAddress'; + case 'id-at-serialnumber': + case 'serialnumber': + return 'id-at-serialNumber'; + case 'id-at-postalcode': + case 'postalcode': + return 'id-at-postalCode'; + case 'id-at-streetaddress': + case 'streetaddress': + return 'id-at-streetAddress'; + case 'id-at-name': + case 'name': + return 'id-at-name'; + case 'id-at-givenname': + case 'givenname': + return 'id-at-givenName'; + case 'id-at-surname': + case 'surname': + case 'sn': + return 'id-at-surname'; + case 'id-at-initials': + case 'initials': + return 'id-at-initials'; + case 'id-at-generationqualifier': + case 'generationqualifier': + return 'id-at-generationQualifier'; + case 'id-at-organizationalunitname': + case 'organizationalunitname': + case 'ou': + return 'id-at-organizationalUnitName'; + case 'id-at-pseudonym': + case 'pseudonym': + return 'id-at-pseudonym'; + case 'id-at-title': + case 'title': + return 'id-at-title'; + case 'id-at-description': + case 'description': + return 'id-at-description'; + case 'id-at-role': + case 'role': + return 'id-at-role'; + case 'id-at-uniqueidentifier': + case 'uniqueidentifier': + case 'x500uniqueidentifier': + return 'id-at-uniqueIdentifier'; + case 'postaladdress': + case 'id-at-postaladdress': + return 'id-at-postalAddress'; + default: + return false; + } + } + + /** + * Set a Distinguished Name property + * + * @param string $propName + * @param mixed $propValue + * @param string $type optional + * @access public + * @return bool + */ + function setDNProp($propName, $propValue, $type = 'utf8String') + { + if (empty($this->dn)) { + $this->dn = array('rdnSequence' => array()); + } + + if (($propName = $this->_translateDNProp($propName)) === false) { + return false; + } + + foreach ((array) $propValue as $v) { + if (!is_array($v) && isset($type)) { + $v = array($type => $v); + } + $this->dn['rdnSequence'][] = array( + array( + 'type' => $propName, + 'value'=> $v + ) + ); + } + + return true; + } + + /** + * Remove Distinguished Name properties + * + * @param string $propName + * @access public + */ + function removeDNProp($propName) + { + if (empty($this->dn)) { + return; + } + + if (($propName = $this->_translateDNProp($propName)) === false) { + return; + } + + $dn = &$this->dn['rdnSequence']; + $size = count($dn); + for ($i = 0; $i < $size; $i++) { + if ($dn[$i][0]['type'] == $propName) { + unset($dn[$i]); + } + } + + $dn = array_values($dn); + } + + /** + * Get Distinguished Name properties + * + * @param string $propName + * @param array $dn optional + * @param bool $withType optional + * @return mixed + * @access public + */ + function getDNProp($propName, $dn = null, $withType = false) + { + if (!isset($dn)) { + $dn = $this->dn; + } + + if (empty($dn)) { + return false; + } + + if (($propName = $this->_translateDNProp($propName)) === false) { + return false; + } + + $asn1 = new File_ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['value'] = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); + $dn = $dn['rdnSequence']; + $result = array(); + for ($i = 0; $i < count($dn); $i++) { + if ($dn[$i][0]['type'] == $propName) { + $v = $dn[$i][0]['value']; + if (!$withType) { + if (is_array($v)) { + foreach ($v as $type => $s) { + $type = array_search($type, $asn1->ANYmap, true); + if ($type !== false && isset($asn1->stringTypeSize[$type])) { + $s = $asn1->convert($s, $type); + if ($s !== false) { + $v = $s; + break; + } + } + } + if (is_array($v)) { + $v = array_pop($v); // Always strip data type. + } + } elseif (is_object($v) && strtolower(get_class($v)) == 'file_asn1_element') { + $map = $this->_getMapping($propName); + if (!is_bool($map)) { + $decoded = $asn1->decodeBER($v); + $v = $asn1->asn1map($decoded[0], $map); + } + } + } + $result[] = $v; + } + } + + return $result; + } + + /** + * Set a Distinguished Name + * + * @param mixed $dn + * @param bool $merge optional + * @param string $type optional + * @access public + * @return bool + */ + function setDN($dn, $merge = false, $type = 'utf8String') + { + if (!$merge) { + $this->dn = null; + } + + if (is_array($dn)) { + if (isset($dn['rdnSequence'])) { + $this->dn = $dn; // No merge here. + return true; + } + + // handles stuff generated by openssl_x509_parse() + foreach ($dn as $prop => $value) { + if (!$this->setDNProp($prop, $value, $type)) { + return false; + } + } + return true; + } + + // handles everything else + $results = preg_split('#((?:^|, *|/)(?:C=|O=|OU=|CN=|L=|ST=|SN=|postalCode=|streetAddress=|emailAddress=|serialNumber=|organizationalUnitName=|title=|description=|role=|x500UniqueIdentifier=|postalAddress=))#', $dn, -1, PREG_SPLIT_DELIM_CAPTURE); + for ($i = 1; $i < count($results); $i+=2) { + $prop = trim($results[$i], ', =/'); + $value = $results[$i + 1]; + if (!$this->setDNProp($prop, $value, $type)) { + return false; + } + } + + return true; + } + + /** + * Get the Distinguished Name for a certificates subject + * + * @param mixed $format optional + * @param array $dn optional + * @access public + * @return bool + */ + function getDN($format = FILE_X509_DN_ARRAY, $dn = null) + { + if (!isset($dn)) { + $dn = isset($this->currentCert['tbsCertList']) ? $this->currentCert['tbsCertList']['issuer'] : $this->dn; + } + + switch ((int) $format) { + case FILE_X509_DN_ARRAY: + return $dn; + case FILE_X509_DN_ASN1: + $asn1 = new File_ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['rdnSequence']['value'] = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); + return $asn1->encodeDER($dn, $this->Name); + case FILE_X509_DN_CANON: + // No SEQUENCE around RDNs and all string values normalized as + // trimmed lowercase UTF-8 with all spacing as one blank. + // constructed RDNs will not be canonicalized + $asn1 = new File_ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['value'] = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $result = ''; + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); + foreach ($dn['rdnSequence'] as $rdn) { + foreach ($rdn as $i => $attr) { + $attr = &$rdn[$i]; + if (is_array($attr['value'])) { + foreach ($attr['value'] as $type => $v) { + $type = array_search($type, $asn1->ANYmap, true); + if ($type !== false && isset($asn1->stringTypeSize[$type])) { + $v = $asn1->convert($v, $type); + if ($v !== false) { + $v = preg_replace('/\s+/', ' ', $v); + $attr['value'] = strtolower(trim($v)); + break; + } + } + } + } + } + $result .= $asn1->encodeDER($rdn, $this->RelativeDistinguishedName); + } + return $result; + case FILE_X509_DN_HASH: + $dn = $this->getDN(FILE_X509_DN_CANON, $dn); + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + $hash = new Crypt_Hash('sha1'); + $hash = $hash->hash($dn); + extract(unpack('Vhash', $hash)); + return strtolower(bin2hex(pack('N', $hash))); + } + + // Default is to return a string. + $start = true; + $output = ''; + $result = array(); + $asn1 = new File_ASN1(); + $asn1->loadOIDs($this->oids); + $filters = array(); + $filters['rdnSequence']['value'] = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $asn1->loadFilters($filters); + $this->_mapOutDNs($dn, 'rdnSequence', $asn1); + foreach ($dn['rdnSequence'] as $field) { + $prop = $field[0]['type']; + $value = $field[0]['value']; + + $delim = ', '; + switch ($prop) { + case 'id-at-countryName': + $desc = 'C'; + break; + case 'id-at-stateOrProvinceName': + $desc = 'ST'; + break; + case 'id-at-organizationName': + $desc = 'O'; + break; + case 'id-at-organizationalUnitName': + $desc = 'OU'; + break; + case 'id-at-commonName': + $desc = 'CN'; + break; + case 'id-at-localityName': + $desc = 'L'; + break; + case 'id-at-surname': + $desc = 'SN'; + break; + case 'id-at-uniqueIdentifier': + $delim = '/'; + $desc = 'x500UniqueIdentifier'; + break; + case 'id-at-postalAddress': + $delim = '/'; + $desc = 'postalAddress'; + break; + default: + $delim = '/'; + $desc = preg_replace('#.+-([^-]+)$#', '$1', $prop); + } + + if (!$start) { + $output.= $delim; + } + if (is_array($value)) { + foreach ($value as $type => $v) { + $type = array_search($type, $asn1->ANYmap, true); + if ($type !== false && isset($asn1->stringTypeSize[$type])) { + $v = $asn1->convert($v, $type); + if ($v !== false) { + $value = $v; + break; + } + } + } + if (is_array($value)) { + $value = array_pop($value); // Always strip data type. + } + } elseif (is_object($value) && strtolower(get_class($value)) == 'file_asn1_element') { + $callback = create_function('$x', 'return "\x" . bin2hex($x[0]);'); + $value = strtoupper(preg_replace_callback('#[^\x20-\x7E]#', $callback, $value->element)); + } + $output.= $desc . '=' . $value; + $result[$desc] = isset($result[$desc]) ? + array_merge((array) $dn[$prop], array($value)) : + $value; + $start = false; + } + + return $format == FILE_X509_DN_OPENSSL ? $result : $output; + } + + /** + * Get the Distinguished Name for a certificate/crl issuer + * + * @param int $format optional + * @access public + * @return mixed + */ + function getIssuerDN($format = FILE_X509_DN_ARRAY) + { + switch (true) { + case !isset($this->currentCert) || !is_array($this->currentCert): + break; + case isset($this->currentCert['tbsCertificate']): + return $this->getDN($format, $this->currentCert['tbsCertificate']['issuer']); + case isset($this->currentCert['tbsCertList']): + return $this->getDN($format, $this->currentCert['tbsCertList']['issuer']); + } + + return false; + } + + /** + * Get the Distinguished Name for a certificate/csr subject + * Alias of getDN() + * + * @param int $format optional + * @access public + * @return mixed + */ + function getSubjectDN($format = FILE_X509_DN_ARRAY) + { + switch (true) { + case !empty($this->dn): + return $this->getDN($format); + case !isset($this->currentCert) || !is_array($this->currentCert): + break; + case isset($this->currentCert['tbsCertificate']): + return $this->getDN($format, $this->currentCert['tbsCertificate']['subject']); + case isset($this->currentCert['certificationRequestInfo']): + return $this->getDN($format, $this->currentCert['certificationRequestInfo']['subject']); + } + + return false; + } + + /** + * Get an individual Distinguished Name property for a certificate/crl issuer + * + * @param string $propName + * @param bool $withType optional + * @access public + * @return mixed + */ + function getIssuerDNProp($propName, $withType = false) + { + switch (true) { + case !isset($this->currentCert) || !is_array($this->currentCert): + break; + case isset($this->currentCert['tbsCertificate']): + return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['issuer'], $withType); + case isset($this->currentCert['tbsCertList']): + return $this->getDNProp($propName, $this->currentCert['tbsCertList']['issuer'], $withType); + } + + return false; + } + + /** + * Get an individual Distinguished Name property for a certificate/csr subject + * + * @param string $propName + * @param bool $withType optional + * @access public + * @return mixed + */ + function getSubjectDNProp($propName, $withType = false) + { + switch (true) { + case !empty($this->dn): + return $this->getDNProp($propName, null, $withType); + case !isset($this->currentCert) || !is_array($this->currentCert): + break; + case isset($this->currentCert['tbsCertificate']): + return $this->getDNProp($propName, $this->currentCert['tbsCertificate']['subject'], $withType); + case isset($this->currentCert['certificationRequestInfo']): + return $this->getDNProp($propName, $this->currentCert['certificationRequestInfo']['subject'], $withType); + } + + return false; + } + + /** + * Get the certificate chain for the current cert + * + * @access public + * @return mixed + */ + function getChain() + { + $chain = array($this->currentCert); + + if (!is_array($this->currentCert) || !isset($this->currentCert['tbsCertificate'])) { + return false; + } + if (empty($this->CAs)) { + return $chain; + } + while (true) { + $currentCert = $chain[count($chain) - 1]; + for ($i = 0; $i < count($this->CAs); $i++) { + $ca = $this->CAs[$i]; + if ($currentCert['tbsCertificate']['issuer'] === $ca['tbsCertificate']['subject']) { + $authorityKey = $this->getExtension('id-ce-authorityKeyIdentifier', $currentCert); + $subjectKeyID = $this->getExtension('id-ce-subjectKeyIdentifier', $ca); + switch (true) { + case !is_array($authorityKey): + case is_array($authorityKey) && isset($authorityKey['keyIdentifier']) && $authorityKey['keyIdentifier'] === $subjectKeyID: + if ($currentCert === $ca) { + break 3; + } + $chain[] = $ca; + break 2; + } + } + } + if ($i == count($this->CAs)) { + break; + } + } + foreach ($chain as $key => $value) { + $chain[$key] = new File_X509(); + $chain[$key]->loadX509($value); + } + return $chain; + } + + /** + * Set public key + * + * Key needs to be a Crypt_RSA object + * + * @param object $key + * @access public + * @return bool + */ + function setPublicKey($key) + { + $key->setPublicKey(); + $this->publicKey = $key; + } + + /** + * Set private key + * + * Key needs to be a Crypt_RSA object + * + * @param object $key + * @access public + */ + function setPrivateKey($key) + { + $this->privateKey = $key; + } + + /** + * Set challenge + * + * Used for SPKAC CSR's + * + * @param string $challenge + * @access public + */ + function setChallenge($challenge) + { + $this->challenge = $challenge; + } + + /** + * Gets the public key + * + * Returns a Crypt_RSA object or a false. + * + * @access public + * @return mixed + */ + function getPublicKey() + { + if (isset($this->publicKey)) { + return $this->publicKey; + } + + if (isset($this->currentCert) && is_array($this->currentCert)) { + foreach (array('tbsCertificate/subjectPublicKeyInfo', 'certificationRequestInfo/subjectPKInfo') as $path) { + $keyinfo = $this->_subArray($this->currentCert, $path); + if (!empty($keyinfo)) { + break; + } + } + } + if (empty($keyinfo)) { + return false; + } + + $key = $keyinfo['subjectPublicKey']; + + switch ($keyinfo['algorithm']['algorithm']) { + case 'rsaEncryption': + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $publicKey = new Crypt_RSA(); + $publicKey->loadKey($key); + $publicKey->setPublicKey(); + break; + default: + return false; + } + + return $publicKey; + } + + /** + * Load a Certificate Signing Request + * + * @param string $csr + * @access public + * @return mixed + */ + function loadCSR($csr, $mode = FILE_X509_FORMAT_AUTO_DETECT) + { + if (is_array($csr) && isset($csr['certificationRequestInfo'])) { + unset($this->currentCert); + unset($this->currentKeyIdentifier); + unset($this->signatureSubject); + $this->dn = $csr['certificationRequestInfo']['subject']; + if (!isset($this->dn)) { + return false; + } + + $this->currentCert = $csr; + return $csr; + } + + // see http://tools.ietf.org/html/rfc2986 + + $asn1 = new File_ASN1(); + + if ($mode != FILE_X509_FORMAT_DER) { + $newcsr = $this->_extractBER($csr); + if ($mode == FILE_X509_FORMAT_PEM && $csr == $newcsr) { + return false; + } + $csr = $newcsr; + } + $orig = $csr; + + if ($csr === false) { + $this->currentCert = false; + return false; + } + + $asn1->loadOIDs($this->oids); + $decoded = $asn1->decodeBER($csr); + + if (empty($decoded)) { + $this->currentCert = false; + return false; + } + + $csr = $asn1->asn1map($decoded[0], $this->CertificationRequest); + if (!isset($csr) || $csr === false) { + $this->currentCert = false; + return false; + } + + $this->_mapInAttributes($csr, 'certificationRequestInfo/attributes', $asn1); + $this->_mapInDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1); + + $this->dn = $csr['certificationRequestInfo']['subject']; + + $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); + + $algorithm = &$csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['algorithm']; + $key = &$csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']; + $key = $this->_reformatKey($algorithm, $key); + + switch ($algorithm) { + case 'rsaEncryption': + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $this->publicKey = new Crypt_RSA(); + $this->publicKey->loadKey($key); + $this->publicKey->setPublicKey(); + break; + default: + $this->publicKey = null; + } + + $this->currentKeyIdentifier = null; + $this->currentCert = $csr; + + return $csr; + } + + /** + * Save CSR request + * + * @param array $csr + * @param int $format optional + * @access public + * @return string + */ + function saveCSR($csr, $format = FILE_X509_FORMAT_PEM) + { + if (!is_array($csr) || !isset($csr['certificationRequestInfo'])) { + return false; + } + + switch (true) { + case !($algorithm = $this->_subArray($csr, 'certificationRequestInfo/subjectPKInfo/algorithm/algorithm')): + case is_object($csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']): + break; + default: + switch ($algorithm) { + case 'rsaEncryption': + $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'] + = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $csr['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']))); + $csr['certificationRequestInfo']['subjectPKInfo']['algorithm']['parameters'] = null; + $csr['signatureAlgorithm']['parameters'] = null; + $csr['certificationRequestInfo']['signature']['parameters'] = null; + } + } + + $asn1 = new File_ASN1(); + + $asn1->loadOIDs($this->oids); + + $filters = array(); + $filters['certificationRequestInfo']['subject']['rdnSequence']['value'] + = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + + $asn1->loadFilters($filters); + + $this->_mapOutDNs($csr, 'certificationRequestInfo/subject/rdnSequence', $asn1); + $this->_mapOutAttributes($csr, 'certificationRequestInfo/attributes', $asn1); + $csr = $asn1->encodeDER($csr, $this->CertificationRequest); + + switch ($format) { + case FILE_X509_FORMAT_DER: + return $csr; + // case FILE_X509_FORMAT_PEM: + default: + return "-----BEGIN CERTIFICATE REQUEST-----\r\n" . chunk_split(base64_encode($csr), 64) . '-----END CERTIFICATE REQUEST-----'; + } + } + + /** + * Load a SPKAC CSR + * + * SPKAC's are produced by the HTML5 keygen element: + * + * https://developer.mozilla.org/en-US/docs/HTML/Element/keygen + * + * @param string $csr + * @access public + * @return mixed + */ + function loadSPKAC($spkac) + { + if (is_array($spkac) && isset($spkac['publicKeyAndChallenge'])) { + unset($this->currentCert); + unset($this->currentKeyIdentifier); + unset($this->signatureSubject); + $this->currentCert = $spkac; + return $spkac; + } + + // see http://www.w3.org/html/wg/drafts/html/master/forms.html#signedpublickeyandchallenge + + $asn1 = new File_ASN1(); + + // OpenSSL produces SPKAC's that are preceded by the string SPKAC= + $temp = preg_replace('#(?:SPKAC=)|[ \r\n\\\]#', '', $spkac); + $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; + if ($temp != false) { + $spkac = $temp; + } + $orig = $spkac; + + if ($spkac === false) { + $this->currentCert = false; + return false; + } + + $asn1->loadOIDs($this->oids); + $decoded = $asn1->decodeBER($spkac); + + if (empty($decoded)) { + $this->currentCert = false; + return false; + } + + $spkac = $asn1->asn1map($decoded[0], $this->SignedPublicKeyAndChallenge); + + if (!isset($spkac) || $spkac === false) { + $this->currentCert = false; + return false; + } + + $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); + + $algorithm = &$spkac['publicKeyAndChallenge']['spki']['algorithm']['algorithm']; + $key = &$spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']; + $key = $this->_reformatKey($algorithm, $key); + + switch ($algorithm) { + case 'rsaEncryption': + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $this->publicKey = new Crypt_RSA(); + $this->publicKey->loadKey($key); + $this->publicKey->setPublicKey(); + break; + default: + $this->publicKey = null; + } + + $this->currentKeyIdentifier = null; + $this->currentCert = $spkac; + + return $spkac; + } + + /** + * Save a SPKAC CSR request + * + * @param array $csr + * @param int $format optional + * @access public + * @return string + */ + function saveSPKAC($spkac, $format = FILE_X509_FORMAT_PEM) + { + if (!is_array($spkac) || !isset($spkac['publicKeyAndChallenge'])) { + return false; + } + + $algorithm = $this->_subArray($spkac, 'publicKeyAndChallenge/spki/algorithm/algorithm'); + switch (true) { + case !$algorithm: + case is_object($spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']): + break; + default: + switch ($algorithm) { + case 'rsaEncryption': + $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey'] + = base64_encode("\0" . base64_decode(preg_replace('#-.+-|[\r\n]#', '', $spkac['publicKeyAndChallenge']['spki']['subjectPublicKey']))); + } + } + + $asn1 = new File_ASN1(); + + $asn1->loadOIDs($this->oids); + $spkac = $asn1->encodeDER($spkac, $this->SignedPublicKeyAndChallenge); + + switch ($format) { + case FILE_X509_FORMAT_DER: + return $spkac; + // case FILE_X509_FORMAT_PEM: + default: + // OpenSSL's implementation of SPKAC requires the SPKAC be preceded by SPKAC= and since there are pretty much + // no other SPKAC decoders phpseclib will use that same format + return 'SPKAC=' . base64_encode($spkac); + } + } + + /** + * Load a Certificate Revocation List + * + * @param string $crl + * @access public + * @return mixed + */ + function loadCRL($crl, $mode = FILE_X509_FORMAT_AUTO_DETECT) + { + if (is_array($crl) && isset($crl['tbsCertList'])) { + $this->currentCert = $crl; + unset($this->signatureSubject); + return $crl; + } + + $asn1 = new File_ASN1(); + + if ($mode != FILE_X509_FORMAT_DER) { + $newcrl = $this->_extractBER($crl); + if ($mode == FILE_X509_FORMAT_PEM && $crl == $newcrl) { + return false; + } + $crl = $newcrl; + } + $orig = $crl; + + if ($crl === false) { + $this->currentCert = false; + return false; + } + + $asn1->loadOIDs($this->oids); + $decoded = $asn1->decodeBER($crl); + + if (empty($decoded)) { + $this->currentCert = false; + return false; + } + + $crl = $asn1->asn1map($decoded[0], $this->CertificateList); + if (!isset($crl) || $crl === false) { + $this->currentCert = false; + return false; + } + + $this->signatureSubject = substr($orig, $decoded[0]['content'][0]['start'], $decoded[0]['content'][0]['length']); + + $this->_mapInDNs($crl, 'tbsCertList/issuer/rdnSequence', $asn1); + if ($this->_isSubArrayValid($crl, 'tbsCertList/crlExtensions')) { + $this->_mapInExtensions($crl, 'tbsCertList/crlExtensions', $asn1); + } + if ($this->_isSubArrayValid($crl, 'tbsCertList/revokedCertificates')) { + $rclist_ref = &$this->_subArrayUnchecked($crl, 'tbsCertList/revokedCertificates'); + if ($rclist_ref) { + $rclist = $crl['tbsCertList']['revokedCertificates']; + foreach ($rclist as $i => $extension) { + if ($this->_isSubArrayValid($rclist, "$i/crlEntryExtensions", $asn1)) { + $this->_mapInExtensions($rclist_ref, "$i/crlEntryExtensions", $asn1); + } + } + } + } + + $this->currentKeyIdentifier = null; + $this->currentCert = $crl; + + return $crl; + } + + /** + * Save Certificate Revocation List. + * + * @param array $crl + * @param int $format optional + * @access public + * @return string + */ + function saveCRL($crl, $format = FILE_X509_FORMAT_PEM) + { + if (!is_array($crl) || !isset($crl['tbsCertList'])) { + return false; + } + + $asn1 = new File_ASN1(); + + $asn1->loadOIDs($this->oids); + + $filters = array(); + $filters['tbsCertList']['issuer']['rdnSequence']['value'] + = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $filters['tbsCertList']['signature']['parameters'] + = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + $filters['signatureAlgorithm']['parameters'] + = array('type' => FILE_ASN1_TYPE_UTF8_STRING); + + if (empty($crl['tbsCertList']['signature']['parameters'])) { + $filters['tbsCertList']['signature']['parameters'] + = array('type' => FILE_ASN1_TYPE_NULL); + } + + if (empty($crl['signatureAlgorithm']['parameters'])) { + $filters['signatureAlgorithm']['parameters'] + = array('type' => FILE_ASN1_TYPE_NULL); + } + + $asn1->loadFilters($filters); + + $this->_mapOutDNs($crl, 'tbsCertList/issuer/rdnSequence', $asn1); + $this->_mapOutExtensions($crl, 'tbsCertList/crlExtensions', $asn1); + $rclist = &$this->_subArray($crl, 'tbsCertList/revokedCertificates'); + if (is_array($rclist)) { + foreach ($rclist as $i => $extension) { + $this->_mapOutExtensions($rclist, "$i/crlEntryExtensions", $asn1); + } + } + + $crl = $asn1->encodeDER($crl, $this->CertificateList); + + switch ($format) { + case FILE_X509_FORMAT_DER: + return $crl; + // case FILE_X509_FORMAT_PEM: + default: + return "-----BEGIN X509 CRL-----\r\n" . chunk_split(base64_encode($crl), 64) . '-----END X509 CRL-----'; + } + } + + /** + * Helper function to build a time field according to RFC 3280 section + * - 4.1.2.5 Validity + * - 5.1.2.4 This Update + * - 5.1.2.5 Next Update + * - 5.1.2.6 Revoked Certificates + * by choosing utcTime iff year of date given is before 2050 and generalTime else. + * + * @param string $date in format date('D, d M Y H:i:s O') + * @access private + * @return array + */ + function _timeField($date) + { + if (is_object($date) && strtolower(get_class($date)) == 'file_asn1_element') { + return $date; + } + if (!class_exists('DateTime')) { + $year = @gmdate("Y", @strtotime($date)); // the same way ASN1.php parses this + } else { + $dateObj = new DateTime($date, new DateTimeZone('GMT')); + $year = $dateObj->format('Y'); + } + if ($year < 2050) { + return array('utcTime' => $date); + } else { + return array('generalTime' => $date); + } + } + + /** + * Sign an X.509 certificate + * + * $issuer's private key needs to be loaded. + * $subject can be either an existing X.509 cert (if you want to resign it), + * a CSR or something with the DN and public key explicitly set. + * + * @param File_X509 $issuer + * @param File_X509 $subject + * @param string $signatureAlgorithm optional + * @access public + * @return mixed + */ + function sign($issuer, $subject, $signatureAlgorithm = 'sha1WithRSAEncryption') + { + if (!is_object($issuer->privateKey) || empty($issuer->dn)) { + return false; + } + + if (isset($subject->publicKey) && !($subjectPublicKey = $subject->_formatSubjectPublicKey())) { + return false; + } + + $currentCert = isset($this->currentCert) ? $this->currentCert : null; + $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; + + if (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertificate'])) { + $this->currentCert = $subject->currentCert; + $this->currentCert['tbsCertificate']['signature']['algorithm'] = $signatureAlgorithm; + $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; + + if (!empty($this->startDate)) { + $this->currentCert['tbsCertificate']['validity']['notBefore'] = $this->_timeField($this->startDate); + } + if (!empty($this->endDate)) { + $this->currentCert['tbsCertificate']['validity']['notAfter'] = $this->_timeField($this->endDate); + } + if (!empty($this->serialNumber)) { + $this->currentCert['tbsCertificate']['serialNumber'] = $this->serialNumber; + } + if (!empty($subject->dn)) { + $this->currentCert['tbsCertificate']['subject'] = $subject->dn; + } + if (!empty($subject->publicKey)) { + $this->currentCert['tbsCertificate']['subjectPublicKeyInfo'] = $subjectPublicKey; + } + $this->removeExtension('id-ce-authorityKeyIdentifier'); + if (isset($subject->domains)) { + $this->removeExtension('id-ce-subjectAltName'); + } + } elseif (isset($subject->currentCert) && is_array($subject->currentCert) && isset($subject->currentCert['tbsCertList'])) { + return false; + } else { + if (!isset($subject->publicKey)) { + return false; + } + + if (!class_exists('DateTime')) { + $startDate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O'); + $endDate = !empty($this->endDate) ? $this->endDate : @date('D, d M Y H:i:s O', strtotime('+1 year')); + } else { + $startDate = new DateTime('now', new DateTimeZone(@date_default_timezone_get())); + $startDate = !empty($this->startDate) ? $this->startDate : $startDate->format('D, d M Y H:i:s O'); + + $endDate = new DateTime('+1 year', new DateTimeZone(@date_default_timezone_get())); + $endDate = !empty($this->endDate) ? $this->endDate : $endDate->format('D, d M Y H:i:s O'); + } + if (!empty($this->serialNumber)) { + $serialNumber = $this->serialNumber; + } else { + if (!function_exists('crypt_random_string')) { + include_once 'Crypt/Random.php'; + } + /* "The serial number MUST be a positive integer" + "Conforming CAs MUST NOT use serialNumber values longer than 20 octets." + -- https://tools.ietf.org/html/rfc5280#section-4.1.2.2 + + for the integer to be positive the leading bit needs to be 0 hence the + application of a bitmap + */ + $serialNumber = new Math_BigInteger(crypt_random_string(20) & ("\x7F" . str_repeat("\xFF", 19)), 256); + } + + $this->currentCert = array( + 'tbsCertificate' => + array( + 'version' => 'v3', + 'serialNumber' => $serialNumber, // $this->setserialNumber() + 'signature' => array('algorithm' => $signatureAlgorithm), + 'issuer' => false, // this is going to be overwritten later + 'validity' => array( + 'notBefore' => $this->_timeField($startDate), // $this->setStartDate() + 'notAfter' => $this->_timeField($endDate) // $this->setEndDate() + ), + 'subject' => $subject->dn, + 'subjectPublicKeyInfo' => $subjectPublicKey + ), + 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), + 'signature' => false // this is going to be overwritten later + ); + + // Copy extensions from CSR. + $csrexts = $subject->getAttribute('pkcs-9-at-extensionRequest', 0); + + if (!empty($csrexts)) { + $this->currentCert['tbsCertificate']['extensions'] = $csrexts; + } + } + + $this->currentCert['tbsCertificate']['issuer'] = $issuer->dn; + + if (isset($issuer->currentKeyIdentifier)) { + $this->setExtension('id-ce-authorityKeyIdentifier', array( + //'authorityCertIssuer' => array( + // array( + // 'directoryName' => $issuer->dn + // ) + //), + 'keyIdentifier' => $issuer->currentKeyIdentifier + )); + //$extensions = &$this->currentCert['tbsCertificate']['extensions']; + //if (isset($issuer->serialNumber)) { + // $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber; + //} + //unset($extensions); + } + + if (isset($subject->currentKeyIdentifier)) { + $this->setExtension('id-ce-subjectKeyIdentifier', $subject->currentKeyIdentifier); + } + + $altName = array(); + + if (isset($subject->domains) && count($subject->domains)) { + $altName = array_map(array('File_X509', '_dnsName'), $subject->domains); + } + + if (isset($subject->ipAddresses) && count($subject->ipAddresses)) { + // should an IP address appear as the CN if no domain name is specified? idk + //$ips = count($subject->domains) ? $subject->ipAddresses : array_slice($subject->ipAddresses, 1); + $ipAddresses = array(); + foreach ($subject->ipAddresses as $ipAddress) { + $encoded = $subject->_ipAddress($ipAddress); + if ($encoded !== false) { + $ipAddresses[] = $encoded; + } + } + if (count($ipAddresses)) { + $altName = array_merge($altName, $ipAddresses); + } + } + + if (!empty($altName)) { + $this->setExtension('id-ce-subjectAltName', $altName); + } + + if ($this->caFlag) { + $keyUsage = $this->getExtension('id-ce-keyUsage'); + if (!$keyUsage) { + $keyUsage = array(); + } + + $this->setExtension( + 'id-ce-keyUsage', + array_values(array_unique(array_merge($keyUsage, array('cRLSign', 'keyCertSign')))) + ); + + $basicConstraints = $this->getExtension('id-ce-basicConstraints'); + if (!$basicConstraints) { + $basicConstraints = array(); + } + + $this->setExtension( + 'id-ce-basicConstraints', + array_unique(array_merge(array('cA' => true), $basicConstraints)), + true + ); + + if (!isset($subject->currentKeyIdentifier)) { + $this->setExtension('id-ce-subjectKeyIdentifier', base64_encode($this->computeKeyIdentifier($this->currentCert)), false, false); + } + } + + // resync $this->signatureSubject + // save $tbsCertificate in case there are any File_ASN1_Element objects in it + $tbsCertificate = $this->currentCert['tbsCertificate']; + $this->loadX509($this->saveX509($this->currentCert)); + + $result = $this->_sign($issuer->privateKey, $signatureAlgorithm); + $result['tbsCertificate'] = $tbsCertificate; + + $this->currentCert = $currentCert; + $this->signatureSubject = $signatureSubject; + + return $result; + } + + /** + * Sign a CSR + * + * @access public + * @return mixed + */ + function signCSR($signatureAlgorithm = 'sha1WithRSAEncryption') + { + if (!is_object($this->privateKey) || empty($this->dn)) { + return false; + } + + $origPublicKey = $this->publicKey; + $class = get_class($this->privateKey); + $this->publicKey = new $class(); + $this->publicKey->loadKey($this->privateKey->getPublicKey()); + $this->publicKey->setPublicKey(); + if (!($publicKey = $this->_formatSubjectPublicKey())) { + return false; + } + $this->publicKey = $origPublicKey; + + $currentCert = isset($this->currentCert) ? $this->currentCert : null; + $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; + + if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['certificationRequestInfo'])) { + $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; + if (!empty($this->dn)) { + $this->currentCert['certificationRequestInfo']['subject'] = $this->dn; + } + $this->currentCert['certificationRequestInfo']['subjectPKInfo'] = $publicKey; + } else { + $this->currentCert = array( + 'certificationRequestInfo' => + array( + 'version' => 'v1', + 'subject' => $this->dn, + 'subjectPKInfo' => $publicKey + ), + 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), + 'signature' => false // this is going to be overwritten later + ); + } + + // resync $this->signatureSubject + // save $certificationRequestInfo in case there are any File_ASN1_Element objects in it + $certificationRequestInfo = $this->currentCert['certificationRequestInfo']; + $this->loadCSR($this->saveCSR($this->currentCert)); + + $result = $this->_sign($this->privateKey, $signatureAlgorithm); + $result['certificationRequestInfo'] = $certificationRequestInfo; + + $this->currentCert = $currentCert; + $this->signatureSubject = $signatureSubject; + + return $result; + } + + /** + * Sign a SPKAC + * + * @access public + * @return mixed + */ + function signSPKAC($signatureAlgorithm = 'sha1WithRSAEncryption') + { + if (!is_object($this->privateKey)) { + return false; + } + + $origPublicKey = $this->publicKey; + $class = get_class($this->privateKey); + $this->publicKey = new $class(); + $this->publicKey->loadKey($this->privateKey->getPublicKey()); + $this->publicKey->setPublicKey(); + $publicKey = $this->_formatSubjectPublicKey(); + if (!$publicKey) { + return false; + } + $this->publicKey = $origPublicKey; + + $currentCert = isset($this->currentCert) ? $this->currentCert : null; + $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject: null; + + // re-signing a SPKAC seems silly but since everything else supports re-signing why not? + if (isset($this->currentCert) && is_array($this->currentCert) && isset($this->currentCert['publicKeyAndChallenge'])) { + $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; + $this->currentCert['publicKeyAndChallenge']['spki'] = $publicKey; + if (!empty($this->challenge)) { + // the bitwise AND ensures that the output is a valid IA5String + $this->currentCert['publicKeyAndChallenge']['challenge'] = $this->challenge & str_repeat("\x7F", strlen($this->challenge)); + } + } else { + $this->currentCert = array( + 'publicKeyAndChallenge' => + array( + 'spki' => $publicKey, + // quoting , + // "A challenge string that is submitted along with the public key. Defaults to an empty string if not specified." + // both Firefox and OpenSSL ("openssl spkac -key private.key") behave this way + // we could alternatively do this instead if we ignored the specs: + // crypt_random_string(8) & str_repeat("\x7F", 8) + 'challenge' => !empty($this->challenge) ? $this->challenge : '' + ), + 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), + 'signature' => false // this is going to be overwritten later + ); + } + + // resync $this->signatureSubject + // save $publicKeyAndChallenge in case there are any File_ASN1_Element objects in it + $publicKeyAndChallenge = $this->currentCert['publicKeyAndChallenge']; + $this->loadSPKAC($this->saveSPKAC($this->currentCert)); + + $result = $this->_sign($this->privateKey, $signatureAlgorithm); + $result['publicKeyAndChallenge'] = $publicKeyAndChallenge; + + $this->currentCert = $currentCert; + $this->signatureSubject = $signatureSubject; + + return $result; + } + + /** + * Sign a CRL + * + * $issuer's private key needs to be loaded. + * + * @param File_X509 $issuer + * @param File_X509 $crl + * @param string $signatureAlgorithm optional + * @access public + * @return mixed + */ + function signCRL($issuer, $crl, $signatureAlgorithm = 'sha1WithRSAEncryption') + { + if (!is_object($issuer->privateKey) || empty($issuer->dn)) { + return false; + } + + $currentCert = isset($this->currentCert) ? $this->currentCert : null; + $signatureSubject = isset($this->signatureSubject) ? $this->signatureSubject : null; + if (!class_exists('DateTime')) { + $thisUpdate = !empty($this->startDate) ? $this->startDate : @date('D, d M Y H:i:s O'); + } else { + $thisUpdate = new DateTime('now', new DateTimeZone(@date_default_timezone_get())); + $thisUpdate = !empty($this->startDate) ? $this->startDate : $thisUpdate->format('D, d M Y H:i:s O'); + } + + if (isset($crl->currentCert) && is_array($crl->currentCert) && isset($crl->currentCert['tbsCertList'])) { + $this->currentCert = $crl->currentCert; + $this->currentCert['tbsCertList']['signature']['algorithm'] = $signatureAlgorithm; + $this->currentCert['signatureAlgorithm']['algorithm'] = $signatureAlgorithm; + } else { + $this->currentCert = array( + 'tbsCertList' => + array( + 'version' => 'v2', + 'signature' => array('algorithm' => $signatureAlgorithm), + 'issuer' => false, // this is going to be overwritten later + 'thisUpdate' => $this->_timeField($thisUpdate) // $this->setStartDate() + ), + 'signatureAlgorithm' => array('algorithm' => $signatureAlgorithm), + 'signature' => false // this is going to be overwritten later + ); + } + + $tbsCertList = &$this->currentCert['tbsCertList']; + $tbsCertList['issuer'] = $issuer->dn; + $tbsCertList['thisUpdate'] = $this->_timeField($thisUpdate); + + if (!empty($this->endDate)) { + $tbsCertList['nextUpdate'] = $this->_timeField($this->endDate); // $this->setEndDate() + } else { + unset($tbsCertList['nextUpdate']); + } + + if (!empty($this->serialNumber)) { + $crlNumber = $this->serialNumber; + } else { + $crlNumber = $this->getExtension('id-ce-cRLNumber'); + // "The CRL number is a non-critical CRL extension that conveys a + // monotonically increasing sequence number for a given CRL scope and + // CRL issuer. This extension allows users to easily determine when a + // particular CRL supersedes another CRL." + // -- https://tools.ietf.org/html/rfc5280#section-5.2.3 + $crlNumber = $crlNumber !== false ? $crlNumber->add(new Math_BigInteger(1)) : null; + } + + $this->removeExtension('id-ce-authorityKeyIdentifier'); + $this->removeExtension('id-ce-issuerAltName'); + + // Be sure version >= v2 if some extension found. + $version = isset($tbsCertList['version']) ? $tbsCertList['version'] : 0; + if (!$version) { + if (!empty($tbsCertList['crlExtensions'])) { + $version = 1; // v2. + } elseif (!empty($tbsCertList['revokedCertificates'])) { + foreach ($tbsCertList['revokedCertificates'] as $cert) { + if (!empty($cert['crlEntryExtensions'])) { + $version = 1; // v2. + } + } + } + + if ($version) { + $tbsCertList['version'] = $version; + } + } + + // Store additional extensions. + if (!empty($tbsCertList['version'])) { // At least v2. + if (!empty($crlNumber)) { + $this->setExtension('id-ce-cRLNumber', $crlNumber); + } + + if (isset($issuer->currentKeyIdentifier)) { + $this->setExtension('id-ce-authorityKeyIdentifier', array( + //'authorityCertIssuer' => array( + // array( + // 'directoryName' => $issuer->dn + // ) + //), + 'keyIdentifier' => $issuer->currentKeyIdentifier + )); + //$extensions = &$tbsCertList['crlExtensions']; + //if (isset($issuer->serialNumber)) { + // $extensions[count($extensions) - 1]['authorityCertSerialNumber'] = $issuer->serialNumber; + //} + //unset($extensions); + } + + $issuerAltName = $this->getExtension('id-ce-subjectAltName', $issuer->currentCert); + + if ($issuerAltName !== false) { + $this->setExtension('id-ce-issuerAltName', $issuerAltName); + } + } + + if (empty($tbsCertList['revokedCertificates'])) { + unset($tbsCertList['revokedCertificates']); + } + + unset($tbsCertList); + + // resync $this->signatureSubject + // save $tbsCertList in case there are any File_ASN1_Element objects in it + $tbsCertList = $this->currentCert['tbsCertList']; + $this->loadCRL($this->saveCRL($this->currentCert)); + + $result = $this->_sign($issuer->privateKey, $signatureAlgorithm); + $result['tbsCertList'] = $tbsCertList; + + $this->currentCert = $currentCert; + $this->signatureSubject = $signatureSubject; + + return $result; + } + + /** + * X.509 certificate signing helper function. + * + * @param object $key + * @param File_X509 $subject + * @param string $signatureAlgorithm + * @access public + * @return mixed + */ + function _sign($key, $signatureAlgorithm) + { + switch (strtolower(get_class($key))) { + case 'crypt_rsa': + switch ($signatureAlgorithm) { + case 'md2WithRSAEncryption': + case 'md5WithRSAEncryption': + case 'sha1WithRSAEncryption': + case 'sha224WithRSAEncryption': + case 'sha256WithRSAEncryption': + case 'sha384WithRSAEncryption': + case 'sha512WithRSAEncryption': + $key->setHash(preg_replace('#WithRSAEncryption$#', '', $signatureAlgorithm)); + $key->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); + + $this->currentCert['signature'] = base64_encode("\0" . $key->sign($this->signatureSubject)); + return $this->currentCert; + } + default: + return false; + } + } + + /** + * Set certificate start date + * + * @param string $date + * @access public + */ + function setStartDate($date) + { + if (class_exists('DateTime')) { + $date = new DateTime($date, new DateTimeZone(@date_default_timezone_get())); + $this->startDate = $date->format('D, d M Y H:i:s O'); + } else { + $this->startDate = @date('D, d M Y H:i:s O', @strtotime($date)); + } + } + + /** + * Set certificate end date + * + * @param string $date + * @access public + */ + function setEndDate($date) + { + /* + To indicate that a certificate has no well-defined expiration date, + the notAfter SHOULD be assigned the GeneralizedTime value of + 99991231235959Z. + + -- http://tools.ietf.org/html/rfc5280#section-4.1.2.5 + */ + if (strtolower($date) == 'lifetime') { + $temp = '99991231235959Z'; + $asn1 = new File_ASN1(); + $temp = chr(FILE_ASN1_TYPE_GENERALIZED_TIME) . $asn1->_encodeLength(strlen($temp)) . $temp; + $this->endDate = new File_ASN1_Element($temp); + } else { + if (class_exists('DateTime')) { + $date = new DateTime($date, new DateTimeZone(@date_default_timezone_get())); + $this->endDate = $date->format('D, d M Y H:i:s O'); + } else { + $this->endDate = @date('D, d M Y H:i:s O', @strtotime($date)); + } + } + } + + /** + * Set Serial Number + * + * @param string $serial + * @param $base optional + * @access public + */ + function setSerialNumber($serial, $base = -256) + { + $this->serialNumber = new Math_BigInteger($serial, $base); + } + + /** + * Turns the certificate into a certificate authority + * + * @access public + */ + function makeCA() + { + $this->caFlag = true; + } + + /** + * Check for validity of subarray + * + * This is intended for use in conjunction with _subArrayUnchecked(), + * implementing the checks included in _subArray() but without copying + * a potentially large array by passing its reference by-value to is_array(). + * + * @param array $root + * @param string $path + * @return boolean + * @access private + */ + function _isSubArrayValid($root, $path) + { + if (!is_array($root)) { + return false; + } + + foreach (explode('/', $path) as $i) { + if (!is_array($root)) { + return false; + } + + if (!isset($root[$i])) { + return true; + } + + $root = $root[$i]; + } + + return true; + } + + /** + * Get a reference to a subarray + * + * This variant of _subArray() does no is_array() checking, + * so $root should be checked with _isSubArrayValid() first. + * + * This is here for performance reasons: + * Passing a reference (i.e. $root) by-value (i.e. to is_array()) + * creates a copy. If $root is an especially large array, this is expensive. + * + * @param array $root + * @param string $path absolute path with / as component separator + * @param bool $create optional + * @access private + * @return array|false + */ + function &_subArrayUnchecked(&$root, $path, $create = false) + { + $false = false; + + foreach (explode('/', $path) as $i) { + if (!isset($root[$i])) { + if (!$create) { + return $false; + } + + $root[$i] = array(); + } + + $root = &$root[$i]; + } + + return $root; + } + + /** + * Get a reference to a subarray + * + * @param array $root + * @param string $path absolute path with / as component separator + * @param bool $create optional + * @access private + * @return array|false + */ + function &_subArray(&$root, $path, $create = false) + { + $false = false; + + if (!is_array($root)) { + return $false; + } + + foreach (explode('/', $path) as $i) { + if (!is_array($root)) { + return $false; + } + + if (!isset($root[$i])) { + if (!$create) { + return $false; + } + + $root[$i] = array(); + } + + $root = &$root[$i]; + } + + return $root; + } + + /** + * Get a reference to an extension subarray + * + * @param array $root + * @param string $path optional absolute path with / as component separator + * @param bool $create optional + * @access private + * @return array|false + */ + function &_extensions(&$root, $path = null, $create = false) + { + if (!isset($root)) { + $root = $this->currentCert; + } + + switch (true) { + case !empty($path): + case !is_array($root): + break; + case isset($root['tbsCertificate']): + $path = 'tbsCertificate/extensions'; + break; + case isset($root['tbsCertList']): + $path = 'tbsCertList/crlExtensions'; + break; + case isset($root['certificationRequestInfo']): + $pth = 'certificationRequestInfo/attributes'; + $attributes = &$this->_subArray($root, $pth, $create); + + if (is_array($attributes)) { + foreach ($attributes as $key => $value) { + if ($value['type'] == 'pkcs-9-at-extensionRequest') { + $path = "$pth/$key/value/0"; + break 2; + } + } + if ($create) { + $key = count($attributes); + $attributes[] = array('type' => 'pkcs-9-at-extensionRequest', 'value' => array()); + $path = "$pth/$key/value/0"; + } + } + break; + } + + $extensions = &$this->_subArray($root, $path, $create); + + if (!is_array($extensions)) { + $false = false; + return $false; + } + + return $extensions; + } + + /** + * Remove an Extension + * + * @param string $id + * @param string $path optional + * @access private + * @return bool + */ + function _removeExtension($id, $path = null) + { + $extensions = &$this->_extensions($this->currentCert, $path); + + if (!is_array($extensions)) { + return false; + } + + $result = false; + foreach ($extensions as $key => $value) { + if ($value['extnId'] == $id) { + unset($extensions[$key]); + $result = true; + } + } + + $extensions = array_values($extensions); + return $result; + } + + /** + * Get an Extension + * + * Returns the extension if it exists and false if not + * + * @param string $id + * @param array $cert optional + * @param string $path optional + * @access private + * @return mixed + */ + function _getExtension($id, $cert = null, $path = null) + { + $extensions = $this->_extensions($cert, $path); + + if (!is_array($extensions)) { + return false; + } + + foreach ($extensions as $key => $value) { + if ($value['extnId'] == $id) { + return $value['extnValue']; + } + } + + return false; + } + + /** + * Returns a list of all extensions in use + * + * @param array $cert optional + * @param string $path optional + * @access private + * @return array + */ + function _getExtensions($cert = null, $path = null) + { + $exts = $this->_extensions($cert, $path); + $extensions = array(); + + if (is_array($exts)) { + foreach ($exts as $extension) { + $extensions[] = $extension['extnId']; + } + } + + return $extensions; + } + + /** + * Set an Extension + * + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional + * @param string $path optional + * @access private + * @return bool + */ + function _setExtension($id, $value, $critical = false, $replace = true, $path = null) + { + $extensions = &$this->_extensions($this->currentCert, $path, true); + + if (!is_array($extensions)) { + return false; + } + + $newext = array('extnId' => $id, 'critical' => $critical, 'extnValue' => $value); + + foreach ($extensions as $key => $value) { + if ($value['extnId'] == $id) { + if (!$replace) { + return false; + } + + $extensions[$key] = $newext; + return true; + } + } + + $extensions[] = $newext; + return true; + } + + /** + * Remove a certificate, CSR or CRL Extension + * + * @param string $id + * @access public + * @return bool + */ + function removeExtension($id) + { + return $this->_removeExtension($id); + } + + /** + * Get a certificate, CSR or CRL Extension + * + * Returns the extension if it exists and false if not + * + * @param string $id + * @param array $cert optional + * @access public + * @return mixed + */ + function getExtension($id, $cert = null) + { + return $this->_getExtension($id, $cert); + } + + /** + * Returns a list of all extensions in use in certificate, CSR or CRL + * + * @param array $cert optional + * @access public + * @return array + */ + function getExtensions($cert = null) + { + return $this->_getExtensions($cert); + } + + /** + * Set a certificate, CSR or CRL Extension + * + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional + * @access public + * @return bool + */ + function setExtension($id, $value, $critical = false, $replace = true) + { + return $this->_setExtension($id, $value, $critical, $replace); + } + + /** + * Remove a CSR attribute. + * + * @param string $id + * @param int $disposition optional + * @access public + * @return bool + */ + function removeAttribute($id, $disposition = FILE_X509_ATTR_ALL) + { + $attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes'); + + if (!is_array($attributes)) { + return false; + } + + $result = false; + foreach ($attributes as $key => $attribute) { + if ($attribute['type'] == $id) { + $n = count($attribute['value']); + switch (true) { + case $disposition == FILE_X509_ATTR_APPEND: + case $disposition == FILE_X509_ATTR_REPLACE: + return false; + case $disposition >= $n: + $disposition -= $n; + break; + case $disposition == FILE_X509_ATTR_ALL: + case $n == 1: + unset($attributes[$key]); + $result = true; + break; + default: + unset($attributes[$key]['value'][$disposition]); + $attributes[$key]['value'] = array_values($attributes[$key]['value']); + $result = true; + break; + } + if ($result && $disposition != FILE_X509_ATTR_ALL) { + break; + } + } + } + + $attributes = array_values($attributes); + return $result; + } + + /** + * Get a CSR attribute + * + * Returns the attribute if it exists and false if not + * + * @param string $id + * @param int $disposition optional + * @param array $csr optional + * @access public + * @return mixed + */ + function getAttribute($id, $disposition = FILE_X509_ATTR_ALL, $csr = null) + { + if (empty($csr)) { + $csr = $this->currentCert; + } + + $attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes'); + + if (!is_array($attributes)) { + return false; + } + + foreach ($attributes as $key => $attribute) { + if ($attribute['type'] == $id) { + $n = count($attribute['value']); + switch (true) { + case $disposition == FILE_X509_ATTR_APPEND: + case $disposition == FILE_X509_ATTR_REPLACE: + return false; + case $disposition == FILE_X509_ATTR_ALL: + return $attribute['value']; + case $disposition >= $n: + $disposition -= $n; + break; + default: + return $attribute['value'][$disposition]; + } + } + } + + return false; + } + + /** + * Returns a list of all CSR attributes in use + * + * @param array $csr optional + * @access public + * @return array + */ + function getAttributes($csr = null) + { + if (empty($csr)) { + $csr = $this->currentCert; + } + + $attributes = $this->_subArray($csr, 'certificationRequestInfo/attributes'); + $attrs = array(); + + if (is_array($attributes)) { + foreach ($attributes as $attribute) { + $attrs[] = $attribute['type']; + } + } + + return $attrs; + } + + /** + * Set a CSR attribute + * + * @param string $id + * @param mixed $value + * @param bool $disposition optional + * @access public + * @return bool + */ + function setAttribute($id, $value, $disposition = FILE_X509_ATTR_ALL) + { + $attributes = &$this->_subArray($this->currentCert, 'certificationRequestInfo/attributes', true); + + if (!is_array($attributes)) { + return false; + } + + switch ($disposition) { + case FILE_X509_ATTR_REPLACE: + $disposition = FILE_X509_ATTR_APPEND; + case FILE_X509_ATTR_ALL: + $this->removeAttribute($id); + break; + } + + foreach ($attributes as $key => $attribute) { + if ($attribute['type'] == $id) { + $n = count($attribute['value']); + switch (true) { + case $disposition == FILE_X509_ATTR_APPEND: + $last = $key; + break; + case $disposition >= $n: + $disposition -= $n; + break; + default: + $attributes[$key]['value'][$disposition] = $value; + return true; + } + } + } + + switch (true) { + case $disposition >= 0: + return false; + case isset($last): + $attributes[$last]['value'][] = $value; + break; + default: + $attributes[] = array('type' => $id, 'value' => $disposition == FILE_X509_ATTR_ALL ? $value: array($value)); + break; + } + + return true; + } + + /** + * Sets the subject key identifier + * + * This is used by the id-ce-authorityKeyIdentifier and the id-ce-subjectKeyIdentifier extensions. + * + * @param string $value + * @access public + */ + function setKeyIdentifier($value) + { + if (empty($value)) { + unset($this->currentKeyIdentifier); + } else { + $this->currentKeyIdentifier = base64_encode($value); + } + } + + /** + * Compute a public key identifier. + * + * Although key identifiers may be set to any unique value, this function + * computes key identifiers from public key according to the two + * recommended methods (4.2.1.2 RFC 3280). + * Highly polymorphic: try to accept all possible forms of key: + * - Key object + * - File_X509 object with public or private key defined + * - Certificate or CSR array + * - File_ASN1_Element object + * - PEM or DER string + * + * @param mixed $key optional + * @param int $method optional + * @access public + * @return string binary key identifier + */ + function computeKeyIdentifier($key = null, $method = 1) + { + if (is_null($key)) { + $key = $this; + } + + switch (true) { + case is_string($key): + break; + case is_array($key) && isset($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey']): + return $this->computeKeyIdentifier($key['tbsCertificate']['subjectPublicKeyInfo']['subjectPublicKey'], $method); + case is_array($key) && isset($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey']): + return $this->computeKeyIdentifier($key['certificationRequestInfo']['subjectPKInfo']['subjectPublicKey'], $method); + case !is_object($key): + return false; + case strtolower(get_class($key)) == 'file_asn1_element': + // Assume the element is a bitstring-packed key. + $asn1 = new File_ASN1(); + $decoded = $asn1->decodeBER($key->element); + if (empty($decoded)) { + return false; + } + $raw = $asn1->asn1map($decoded[0], array('type' => FILE_ASN1_TYPE_BIT_STRING)); + if (empty($raw)) { + return false; + } + $raw = base64_decode($raw); + // If the key is private, compute identifier from its corresponding public key. + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $key = new Crypt_RSA(); + if (!$key->loadKey($raw)) { + return false; // Not an unencrypted RSA key. + } + if ($key->getPrivateKey() !== false) { // If private. + return $this->computeKeyIdentifier($key, $method); + } + $key = $raw; // Is a public key. + break; + case strtolower(get_class($key)) == 'file_x509': + if (isset($key->publicKey)) { + return $this->computeKeyIdentifier($key->publicKey, $method); + } + if (isset($key->privateKey)) { + return $this->computeKeyIdentifier($key->privateKey, $method); + } + if (isset($key->currentCert['tbsCertificate']) || isset($key->currentCert['certificationRequestInfo'])) { + return $this->computeKeyIdentifier($key->currentCert, $method); + } + return false; + default: // Should be a key object (i.e.: Crypt_RSA). + $key = $key->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1); + break; + } + + // If in PEM format, convert to binary. + $key = $this->_extractBER($key); + + // Now we have the key string: compute its sha-1 sum. + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + $hash = new Crypt_Hash('sha1'); + $hash = $hash->hash($key); + + if ($method == 2) { + $hash = substr($hash, -8); + $hash[0] = chr((ord($hash[0]) & 0x0F) | 0x40); + } + + return $hash; + } + + /** + * Format a public key as appropriate + * + * @access private + * @return array + */ + function _formatSubjectPublicKey() + { + if (!isset($this->publicKey) || !is_object($this->publicKey)) { + return false; + } + + switch (strtolower(get_class($this->publicKey))) { + case 'crypt_rsa': + // the following two return statements do the same thing. i dunno.. i just prefer the later for some reason. + // the former is a good example of how to do fuzzing on the public key + //return new File_ASN1_Element(base64_decode(preg_replace('#-.+-|[\r\n]#', '', $this->publicKey->getPublicKey()))); + return array( + 'algorithm' => array('algorithm' => 'rsaEncryption'), + 'subjectPublicKey' => $this->publicKey->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1) + ); + default: + return false; + } + } + + /** + * Set the domain name's which the cert is to be valid for + * + * @access public + * @return array + */ + function setDomain() + { + $this->domains = func_get_args(); + $this->removeDNProp('id-at-commonName'); + $this->setDNProp('id-at-commonName', $this->domains[0]); + } + + /** + * Set the IP Addresses's which the cert is to be valid for + * + * @access public + * @param string $ipAddress optional + */ + function setIPAddress() + { + $this->ipAddresses = func_get_args(); + /* + if (!isset($this->domains)) { + $this->removeDNProp('id-at-commonName'); + $this->setDNProp('id-at-commonName', $this->ipAddresses[0]); + } + */ + } + + /** + * Helper function to build domain array + * + * @access private + * @param string $domain + * @return array + */ + function _dnsName($domain) + { + return array('dNSName' => $domain); + } + + /** + * Helper function to build IP Address array + * + * (IPv6 is not currently supported) + * + * @access private + * @param string $address + * @return array + */ + function _iPAddress($address) + { + return array('iPAddress' => $address); + } + + /** + * Get the index of a revoked certificate. + * + * @param array $rclist + * @param string $serial + * @param bool $create optional + * @access private + * @return int|false + */ + function _revokedCertificate(&$rclist, $serial, $create = false) + { + $serial = new Math_BigInteger($serial); + + foreach ($rclist as $i => $rc) { + if (!($serial->compare($rc['userCertificate']))) { + return $i; + } + } + + if (!$create) { + return false; + } + + if (!class_exists('DateTime')) { + $revocationDate = @date('D, d M Y H:i:s O'); + } else { + $revocationDate = new DateTime('now', new DateTimeZone(@date_default_timezone_get())); + $revocationDate = $revocationDate->format('D, d M Y H:i:s O'); + } + + $i = count($rclist); + $rclist[] = array('userCertificate' => $serial, + 'revocationDate' => $this->_timeField($revocationDate)); + return $i; + } + + /** + * Revoke a certificate. + * + * @param string $serial + * @param string $date optional + * @access public + * @return bool + */ + function revoke($serial, $date = null) + { + if (isset($this->currentCert['tbsCertList'])) { + if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) { + if ($this->_revokedCertificate($rclist, $serial) === false) { // If not yet revoked + if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) { + if (!empty($date)) { + $rclist[$i]['revocationDate'] = $this->_timeField($date); + } + + return true; + } + } + } + } + + return false; + } + + /** + * Unrevoke a certificate. + * + * @param string $serial + * @access public + * @return bool + */ + function unrevoke($serial) + { + if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { + if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { + unset($rclist[$i]); + $rclist = array_values($rclist); + return true; + } + } + + return false; + } + + /** + * Get a revoked certificate. + * + * @param string $serial + * @access public + * @return mixed + */ + function getRevoked($serial) + { + if (is_array($rclist = $this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { + if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { + return $rclist[$i]; + } + } + + return false; + } + + /** + * List revoked certificates + * + * @param array $crl optional + * @access public + * @return array + */ + function listRevoked($crl = null) + { + if (!isset($crl)) { + $crl = $this->currentCert; + } + + if (!isset($crl['tbsCertList'])) { + return false; + } + + $result = array(); + + if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { + foreach ($rclist as $rc) { + $result[] = $rc['userCertificate']->toString(); + } + } + + return $result; + } + + /** + * Remove a Revoked Certificate Extension + * + * @param string $serial + * @param string $id + * @access public + * @return bool + */ + function removeRevokedCertificateExtension($serial, $id) + { + if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates'))) { + if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { + return $this->_removeExtension($id, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); + } + } + + return false; + } + + /** + * Get a Revoked Certificate Extension + * + * Returns the extension if it exists and false if not + * + * @param string $serial + * @param string $id + * @param array $crl optional + * @access public + * @return mixed + */ + function getRevokedCertificateExtension($serial, $id, $crl = null) + { + if (!isset($crl)) { + $crl = $this->currentCert; + } + + if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { + if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { + return $this->_getExtension($id, $crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); + } + } + + return false; + } + + /** + * Returns a list of all extensions in use for a given revoked certificate + * + * @param string $serial + * @param array $crl optional + * @access public + * @return array + */ + function getRevokedCertificateExtensions($serial, $crl = null) + { + if (!isset($crl)) { + $crl = $this->currentCert; + } + + if (is_array($rclist = $this->_subArray($crl, 'tbsCertList/revokedCertificates'))) { + if (($i = $this->_revokedCertificate($rclist, $serial)) !== false) { + return $this->_getExtensions($crl, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); + } + } + + return false; + } + + /** + * Set a Revoked Certificate Extension + * + * @param string $serial + * @param string $id + * @param mixed $value + * @param bool $critical optional + * @param bool $replace optional + * @access public + * @return bool + */ + function setRevokedCertificateExtension($serial, $id, $value, $critical = false, $replace = true) + { + if (isset($this->currentCert['tbsCertList'])) { + if (is_array($rclist = &$this->_subArray($this->currentCert, 'tbsCertList/revokedCertificates', true))) { + if (($i = $this->_revokedCertificate($rclist, $serial, true)) !== false) { + return $this->_setExtension($id, $value, $critical, $replace, "tbsCertList/revokedCertificates/$i/crlEntryExtensions"); + } + } + } + + return false; + } + + /** + * Extract raw BER from Base64 encoding + * + * @access private + * @param string $str + * @return string + */ + function _extractBER($str) + { + /* X.509 certs are assumed to be base64 encoded but sometimes they'll have additional things in them + * above and beyond the ceritificate. + * ie. some may have the following preceding the -----BEGIN CERTIFICATE----- line: + * + * Bag Attributes + * localKeyID: 01 00 00 00 + * subject=/O=organization/OU=org unit/CN=common name + * issuer=/O=organization/CN=common name + */ + $temp = preg_replace('#.*?^-+[^-]+-+[\r\n ]*$#ms', '', $str, 1); + // remove the -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- stuff + $temp = preg_replace('#-+[^-]+-+#', '', $temp); + // remove new lines + $temp = str_replace(array("\r", "\n", ' '), '', $temp); + $temp = preg_match('#^[a-zA-Z\d/+]*={0,2}$#', $temp) ? base64_decode($temp) : false; + return $temp != false ? $temp : $str; + } + + /** + * Returns the OID corresponding to a name + * + * What's returned in the associative array returned by loadX509() (or load*()) is either a name or an OID if + * no OID to name mapping is available. The problem with this is that what may be an unmapped OID in one version + * of phpseclib may not be unmapped in the next version, so apps that are looking at this OID may not be able + * to work from version to version. + * + * This method will return the OID if a name is passed to it and if no mapping is avialable it'll assume that + * what's being passed to it already is an OID and return that instead. A few examples. + * + * getOID('2.16.840.1.101.3.4.2.1') == '2.16.840.1.101.3.4.2.1' + * getOID('id-sha256') == '2.16.840.1.101.3.4.2.1' + * getOID('zzz') == 'zzz' + * + * @access public + * @return string + */ + function getOID($name) + { + static $reverseMap; + if (!isset($reverseMap)) { + $reverseMap = array_flip($this->oids); + } + return isset($reverseMap[$name]) ? $reverseMap[$name] : $name; + } +} diff --git a/ipaylinks_statement/Math/BigInteger.php b/ipaylinks_statement/Math/BigInteger.php new file mode 100644 index 00000000..e2a219c7 --- /dev/null +++ b/ipaylinks_statement/Math/BigInteger.php @@ -0,0 +1,3812 @@ +> and << cannot be used, nor can the modulo operator %, + * which only supports integers. Although this fact will slow this library down, the fact that such a high + * base is being used should more than compensate. + * + * Numbers are stored in {@link http://en.wikipedia.org/wiki/Endianness little endian} format. ie. + * (new Math_BigInteger(pow(2, 26)))->value = array(0, 1) + * + * Useful resources are as follows: + * + * - {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf Handbook of Applied Cryptography (HAC)} + * - {@link http://math.libtomcrypt.com/files/tommath.pdf Multi-Precision Math (MPM)} + * - Java's BigInteger classes. See /j2se/src/share/classes/java/math in jdk-1_5_0-src-jrl.zip + * + * Here's an example of how to use this library: + * + * add($b); + * + * echo $c->toString(); // outputs 5 + * ?> + * + * + * LICENSE: 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. + * + * @category Math + * @package Math_BigInteger + * @author Jim Wigginton + * @copyright 2006 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://pear.php.net/package/Math_BigInteger + */ + +/**#@+ + * Reduction constants + * + * @access private + * @see self::_reduce() + */ +/** + * @see self::_montgomery() + * @see self::_prepMontgomery() + */ +define('MATH_BIGINTEGER_MONTGOMERY', 0); +/** + * @see self::_barrett() + */ +define('MATH_BIGINTEGER_BARRETT', 1); +/** + * @see self::_mod2() + */ +define('MATH_BIGINTEGER_POWEROF2', 2); +/** + * @see self::_remainder() + */ +define('MATH_BIGINTEGER_CLASSIC', 3); +/** + * @see self::__clone() + */ +define('MATH_BIGINTEGER_NONE', 4); +/**#@-*/ + +/**#@+ + * Array constants + * + * Rather than create a thousands and thousands of new Math_BigInteger objects in repeated function calls to add() and + * multiply() or whatever, we'll just work directly on arrays, taking them in as parameters and returning them. + * + * @access private + */ +/** + * $result[MATH_BIGINTEGER_VALUE] contains the value. + */ +define('MATH_BIGINTEGER_VALUE', 0); +/** + * $result[MATH_BIGINTEGER_SIGN] contains the sign. + */ +define('MATH_BIGINTEGER_SIGN', 1); +/**#@-*/ + +/**#@+ + * @access private + * @see self::_montgomery() + * @see self::_barrett() + */ +/** + * Cache constants + * + * $cache[MATH_BIGINTEGER_VARIABLE] tells us whether or not the cached data is still valid. + */ +define('MATH_BIGINTEGER_VARIABLE', 0); +/** + * $cache[MATH_BIGINTEGER_DATA] contains the cached data. + */ +define('MATH_BIGINTEGER_DATA', 1); +/**#@-*/ + +/**#@+ + * Mode constants. + * + * @access private + * @see self::Math_BigInteger() + */ +/** + * To use the pure-PHP implementation + */ +define('MATH_BIGINTEGER_MODE_INTERNAL', 1); +/** + * To use the BCMath library + * + * (if enabled; otherwise, the internal implementation will be used) + */ +define('MATH_BIGINTEGER_MODE_BCMATH', 2); +/** + * To use the GMP library + * + * (if present; otherwise, either the BCMath or the internal implementation will be used) + */ +define('MATH_BIGINTEGER_MODE_GMP', 3); +/**#@-*/ + +/** + * Karatsuba Cutoff + * + * At what point do we switch between Karatsuba multiplication and schoolbook long multiplication? + * + * @access private + */ +define('MATH_BIGINTEGER_KARATSUBA_CUTOFF', 25); + +/** + * Pure-PHP arbitrary precision integer arithmetic library. Supports base-2, base-10, base-16, and base-256 + * numbers. + * + * @package Math_BigInteger + * @author Jim Wigginton + * @access public + */ +class Math_BigInteger +{ + /** + * Holds the BigInteger's value. + * + * @var array + * @access private + */ + var $value; + + /** + * Holds the BigInteger's magnitude. + * + * @var bool + * @access private + */ + var $is_negative = false; + + /** + * Precision + * + * @see self::setPrecision() + * @access private + */ + var $precision = -1; + + /** + * Precision Bitmask + * + * @see self::setPrecision() + * @access private + */ + var $bitmask = false; + + /** + * Mode independent value used for serialization. + * + * If the bcmath or gmp extensions are installed $this->value will be a non-serializable resource, hence the need for + * a variable that'll be serializable regardless of whether or not extensions are being used. Unlike $this->value, + * however, $this->hex is only calculated when $this->__sleep() is called. + * + * @see self::__sleep() + * @see self::__wakeup() + * @var string + * @access private + */ + var $hex; + + /** + * Converts base-2, base-10, base-16, and binary strings (base-256) to BigIntegers. + * + * If the second parameter - $base - is negative, then it will be assumed that the number's are encoded using + * two's compliment. The sole exception to this is -10, which is treated the same as 10 is. + * + * Here's an example: + * + * toString(); // outputs 50 + * ?> + * + * + * @param $x base-10 number or base-$base number if $base set. + * @param int $base + * @return Math_BigInteger + * @access public + */ + function __construct($x = 0, $base = 10) + { + if (!defined('MATH_BIGINTEGER_MODE')) { + switch (true) { + case extension_loaded('gmp'): + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_GMP); + break; + case extension_loaded('bcmath'): + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_BCMATH); + break; + default: + define('MATH_BIGINTEGER_MODE', MATH_BIGINTEGER_MODE_INTERNAL); + } + } + + if (extension_loaded('openssl') && !defined('MATH_BIGINTEGER_OPENSSL_DISABLE') && !defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { + // some versions of XAMPP have mismatched versions of OpenSSL which causes it not to work + ob_start(); + @phpinfo(); + $content = ob_get_contents(); + ob_end_clean(); + + preg_match_all('#OpenSSL (Header|Library) Version(.*)#im', $content, $matches); + + $versions = array(); + if (!empty($matches[1])) { + for ($i = 0; $i < count($matches[1]); $i++) { + $fullVersion = trim(str_replace('=>', '', strip_tags($matches[2][$i]))); + + // Remove letter part in OpenSSL version + if (!preg_match('/(\d+\.\d+\.\d+)/i', $fullVersion, $m)) { + $versions[$matches[1][$i]] = $fullVersion; + } else { + $versions[$matches[1][$i]] = $m[0]; + } + } + } + + // it doesn't appear that OpenSSL versions were reported upon until PHP 5.3+ + switch (true) { + case !isset($versions['Header']): + case !isset($versions['Library']): + case $versions['Header'] == $versions['Library']: + case version_compare($versions['Header'], '1.0.0') >= 0 && version_compare($versions['Library'], '1.0.0') >= 0: + define('MATH_BIGINTEGER_OPENSSL_ENABLED', true); + break; + default: + define('MATH_BIGINTEGER_OPENSSL_DISABLE', true); + } + } + + if (!defined('PHP_INT_SIZE')) { + define('PHP_INT_SIZE', 4); + } + + if (!defined('MATH_BIGINTEGER_BASE') && MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_INTERNAL) { + switch (PHP_INT_SIZE) { + case 8: // use 64-bit integers if int size is 8 bytes + define('MATH_BIGINTEGER_BASE', 31); + define('MATH_BIGINTEGER_BASE_FULL', 0x80000000); + define('MATH_BIGINTEGER_MAX_DIGIT', 0x7FFFFFFF); + define('MATH_BIGINTEGER_MSB', 0x40000000); + // 10**9 is the closest we can get to 2**31 without passing it + define('MATH_BIGINTEGER_MAX10', 1000000000); + define('MATH_BIGINTEGER_MAX10_LEN', 9); + // the largest digit that may be used in addition / subtraction + define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 62)); + break; + //case 4: // use 64-bit floats if int size is 4 bytes + default: + define('MATH_BIGINTEGER_BASE', 26); + define('MATH_BIGINTEGER_BASE_FULL', 0x4000000); + define('MATH_BIGINTEGER_MAX_DIGIT', 0x3FFFFFF); + define('MATH_BIGINTEGER_MSB', 0x2000000); + // 10**7 is the closest to 2**26 without passing it + define('MATH_BIGINTEGER_MAX10', 10000000); + define('MATH_BIGINTEGER_MAX10_LEN', 7); + // the largest digit that may be used in addition / subtraction + // we do pow(2, 52) instead of using 4503599627370496 directly because some + // PHP installations will truncate 4503599627370496. + define('MATH_BIGINTEGER_MAX_DIGIT2', pow(2, 52)); + } + } + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + switch (true) { + case is_resource($x) && get_resource_type($x) == 'GMP integer': + // PHP 5.6 switched GMP from using resources to objects + case is_object($x) && get_class($x) == 'GMP': + $this->value = $x; + return; + } + $this->value = gmp_init(0); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $this->value = '0'; + break; + default: + $this->value = array(); + } + + // '0' counts as empty() but when the base is 256 '0' is equal to ord('0') or 48 + // '0' is the only value like this per http://php.net/empty + if (empty($x) && (abs($base) != 256 || $x !== '0')) { + return; + } + + switch ($base) { + case -256: + if (ord($x[0]) & 0x80) { + $x = ~$x; + $this->is_negative = true; + } + case 256: + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $this->value = function_exists('gmp_import') ? + gmp_import($x) : + gmp_init('0x' . bin2hex($x)); + if ($this->is_negative) { + $this->value = gmp_neg($this->value); + } + break; + case MATH_BIGINTEGER_MODE_BCMATH: + // round $len to the nearest 4 (thanks, DavidMJ!) + $len = (strlen($x) + 3) & 0xFFFFFFFC; + + $x = str_pad($x, $len, chr(0), STR_PAD_LEFT); + + for ($i = 0; $i < $len; $i+= 4) { + $this->value = bcmul($this->value, '4294967296', 0); // 4294967296 == 2**32 + $this->value = bcadd($this->value, 0x1000000 * ord($x[$i]) + ((ord($x[$i + 1]) << 16) | (ord($x[$i + 2]) << 8) | ord($x[$i + 3])), 0); + } + + if ($this->is_negative) { + $this->value = '-' . $this->value; + } + + break; + // converts a base-2**8 (big endian / msb) number to base-2**26 (little endian / lsb) + default: + while (strlen($x)) { + $this->value[] = $this->_bytes2int($this->_base256_rshift($x, MATH_BIGINTEGER_BASE)); + } + } + + if ($this->is_negative) { + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) { + $this->is_negative = false; + } + $temp = $this->add(new Math_BigInteger('-1')); + $this->value = $temp->value; + } + break; + case 16: + case -16: + if ($base > 0 && $x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = preg_replace('#^(?:0x)?([A-Fa-f0-9]*).*#', '$1', $x); + + $is_negative = false; + if ($base < 0 && hexdec($x[0]) >= 8) { + $this->is_negative = $is_negative = true; + $x = bin2hex(~pack('H*', $x)); + } + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = $this->is_negative ? '-0x' . $x : '0x' . $x; + $this->value = gmp_init($temp); + $this->is_negative = false; + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $x = (strlen($x) & 1) ? '0' . $x : $x; + $temp = new Math_BigInteger(pack('H*', $x), 256); + $this->value = $this->is_negative ? '-' . $temp->value : $temp->value; + $this->is_negative = false; + break; + default: + $x = (strlen($x) & 1) ? '0' . $x : $x; + $temp = new Math_BigInteger(pack('H*', $x), 256); + $this->value = $temp->value; + } + + if ($is_negative) { + $temp = $this->add(new Math_BigInteger('-1')); + $this->value = $temp->value; + } + break; + case 10: + case -10: + // (?value = gmp_init($x); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + // explicitly casting $x to a string is necessary, here, since doing $x[0] on -1 yields different + // results then doing it on '-1' does (modInverse does $x[0]) + $this->value = $x === '-' ? '0' : (string) $x; + break; + default: + $temp = new Math_BigInteger(); + + $multiplier = new Math_BigInteger(); + $multiplier->value = array(MATH_BIGINTEGER_MAX10); + + if ($x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = str_pad($x, strlen($x) + ((MATH_BIGINTEGER_MAX10_LEN - 1) * strlen($x)) % MATH_BIGINTEGER_MAX10_LEN, 0, STR_PAD_LEFT); + while (strlen($x)) { + $temp = $temp->multiply($multiplier); + $temp = $temp->add(new Math_BigInteger($this->_int2bytes(substr($x, 0, MATH_BIGINTEGER_MAX10_LEN)), 256)); + $x = substr($x, MATH_BIGINTEGER_MAX10_LEN); + } + + $this->value = $temp->value; + } + break; + case 2: // base-2 support originally implemented by Lluis Pamies - thanks! + case -2: + if ($base > 0 && $x[0] == '-') { + $this->is_negative = true; + $x = substr($x, 1); + } + + $x = preg_replace('#^([01]*).*#', '$1', $x); + $x = str_pad($x, strlen($x) + (3 * strlen($x)) % 4, 0, STR_PAD_LEFT); + + $str = '0x'; + while (strlen($x)) { + $part = substr($x, 0, 4); + $str.= dechex(bindec($part)); + $x = substr($x, 4); + } + + if ($this->is_negative) { + $str = '-' . $str; + } + + $temp = new Math_BigInteger($str, 8 * $base); // ie. either -16 or +16 + $this->value = $temp->value; + $this->is_negative = $temp->is_negative; + + break; + default: + // base not supported, so we'll let $this == 0 + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param $x base-10 number or base-$base number if $base set. + * @param int $base + * @access public + */ + function Math_BigInteger($x = 0, $base = 10) + { + $this->__construct($x, $base); + } + + /** + * Converts a BigInteger to a byte string (eg. base-256). + * + * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're + * saved as two's compliment. + * + * Here's an example: + * + * toBytes(); // outputs chr(65) + * ?> + * + * + * @param bool $twos_compliment + * @return string + * @access public + * @internal Converts a base-2**26 number to base-2**8 + */ + function toBytes($twos_compliment = false) + { + if ($twos_compliment) { + $comparison = $this->compare(new Math_BigInteger()); + if ($comparison == 0) { + return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; + } + + $temp = $comparison < 0 ? $this->add(new Math_BigInteger(1)) : $this->copy(); + $bytes = $temp->toBytes(); + + if (empty($bytes)) { // eg. if the number we're trying to convert is -1 + $bytes = chr(0); + } + + if (ord($bytes[0]) & 0x80) { + $bytes = chr(0) . $bytes; + } + + return $comparison < 0 ? ~$bytes : $bytes; + } + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + if (gmp_cmp($this->value, gmp_init(0)) == 0) { + return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; + } + + if (function_exists('gmp_export')) { + $temp = gmp_export($this->value); + } else { + $temp = gmp_strval(gmp_abs($this->value), 16); + $temp = (strlen($temp) & 1) ? '0' . $temp : $temp; + $temp = pack('H*', $temp); + } + + return $this->precision > 0 ? + substr(str_pad($temp, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) : + ltrim($temp, chr(0)); + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value === '0') { + return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; + } + + $value = ''; + $current = $this->value; + + if ($current[0] == '-') { + $current = substr($current, 1); + } + + while (bccomp($current, '0', 0) > 0) { + $temp = bcmod($current, '16777216'); + $value = chr($temp >> 16) . chr($temp >> 8) . chr($temp) . $value; + $current = bcdiv($current, '16777216', 0); + } + + return $this->precision > 0 ? + substr(str_pad($value, $this->precision >> 3, chr(0), STR_PAD_LEFT), -($this->precision >> 3)) : + ltrim($value, chr(0)); + } + + if (!count($this->value)) { + return $this->precision > 0 ? str_repeat(chr(0), ($this->precision + 1) >> 3) : ''; + } + $result = $this->_int2bytes($this->value[count($this->value) - 1]); + + $temp = $this->copy(); + + for ($i = count($temp->value) - 2; $i >= 0; --$i) { + $temp->_base256_lshift($result, MATH_BIGINTEGER_BASE); + $result = $result | str_pad($temp->_int2bytes($temp->value[$i]), strlen($result), chr(0), STR_PAD_LEFT); + } + + return $this->precision > 0 ? + str_pad(substr($result, -(($this->precision + 7) >> 3)), ($this->precision + 7) >> 3, chr(0), STR_PAD_LEFT) : + $result; + } + + /** + * Converts a BigInteger to a hex string (eg. base-16)). + * + * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're + * saved as two's compliment. + * + * Here's an example: + * + * toHex(); // outputs '41' + * ?> + * + * + * @param bool $twos_compliment + * @return string + * @access public + * @internal Converts a base-2**26 number to base-2**8 + */ + function toHex($twos_compliment = false) + { + return bin2hex($this->toBytes($twos_compliment)); + } + + /** + * Converts a BigInteger to a bit string (eg. base-2). + * + * Negative numbers are saved as positive numbers, unless $twos_compliment is set to true, at which point, they're + * saved as two's compliment. + * + * Here's an example: + * + * toBits(); // outputs '1000001' + * ?> + * + * + * @param bool $twos_compliment + * @return string + * @access public + * @internal Converts a base-2**26 number to base-2**2 + */ + function toBits($twos_compliment = false) + { + $hex = $this->toHex($twos_compliment); + $bits = ''; + for ($i = strlen($hex) - 8, $start = strlen($hex) & 7; $i >= $start; $i-=8) { + $bits = str_pad(decbin(hexdec(substr($hex, $i, 8))), 32, '0', STR_PAD_LEFT) . $bits; + } + if ($start) { // hexdec('') == 0 + $bits = str_pad(decbin(hexdec(substr($hex, 0, $start))), 8, '0', STR_PAD_LEFT) . $bits; + } + $result = $this->precision > 0 ? substr($bits, -$this->precision) : ltrim($bits, '0'); + + if ($twos_compliment && $this->compare(new Math_BigInteger()) > 0 && $this->precision <= 0) { + return '0' . $result; + } + + return $result; + } + + /** + * Converts a BigInteger to a base-10 number. + * + * Here's an example: + * + * toString(); // outputs 50 + * ?> + * + * + * @return string + * @access public + * @internal Converts a base-2**26 number to base-10**7 (which is pretty much base-10) + */ + function toString() + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_strval($this->value); + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value === '0') { + return '0'; + } + + return ltrim($this->value, '0'); + } + + if (!count($this->value)) { + return '0'; + } + + $temp = $this->copy(); + $temp->is_negative = false; + + $divisor = new Math_BigInteger(); + $divisor->value = array(MATH_BIGINTEGER_MAX10); + $result = ''; + while (count($temp->value)) { + list($temp, $mod) = $temp->divide($divisor); + $result = str_pad(isset($mod->value[0]) ? $mod->value[0] : '', MATH_BIGINTEGER_MAX10_LEN, '0', STR_PAD_LEFT) . $result; + } + $result = ltrim($result, '0'); + if (empty($result)) { + $result = '0'; + } + + if ($this->is_negative) { + $result = '-' . $result; + } + + return $result; + } + + /** + * Copy an object + * + * PHP5 passes objects by reference while PHP4 passes by value. As such, we need a function to guarantee + * that all objects are passed by value, when appropriate. More information can be found here: + * + * {@link http://php.net/language.oop5.basic#51624} + * + * @access public + * @see self::__clone() + * @return Math_BigInteger + */ + function copy() + { + $temp = new Math_BigInteger(); + $temp->value = $this->value; + $temp->is_negative = $this->is_negative; + $temp->precision = $this->precision; + $temp->bitmask = $this->bitmask; + return $temp; + } + + /** + * __toString() magic method + * + * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call + * toString(). + * + * @access public + * @internal Implemented per a suggestion by Techie-Michael - thanks! + */ + function __toString() + { + return $this->toString(); + } + + /** + * __clone() magic method + * + * Although you can call Math_BigInteger::__toString() directly in PHP5, you cannot call Math_BigInteger::__clone() + * directly in PHP5. You can in PHP4 since it's not a magic method, but in PHP5, you have to call it by using the PHP5 + * only syntax of $y = clone $x. As such, if you're trying to write an application that works on both PHP4 and PHP5, + * call Math_BigInteger::copy(), instead. + * + * @access public + * @see self::copy() + * @return Math_BigInteger + */ + function __clone() + { + return $this->copy(); + } + + /** + * __sleep() magic method + * + * Will be called, automatically, when serialize() is called on a Math_BigInteger object. + * + * @see self::__wakeup() + * @access public + */ + function __sleep() + { + $this->hex = $this->toHex(true); + $vars = array('hex'); + if ($this->precision > 0) { + $vars[] = 'precision'; + } + return $vars; + } + + /** + * __wakeup() magic method + * + * Will be called, automatically, when unserialize() is called on a Math_BigInteger object. + * + * @see self::__sleep() + * @access public + */ + function __wakeup() + { + $temp = new Math_BigInteger($this->hex, -16); + $this->value = $temp->value; + $this->is_negative = $temp->is_negative; + if ($this->precision > 0) { + // recalculate $this->bitmask + $this->setPrecision($this->precision); + } + } + + /** + * __debugInfo() magic method + * + * Will be called, automatically, when print_r() or var_dump() are called + * + * @access public + */ + function __debugInfo() + { + $opts = array(); + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $engine = 'gmp'; + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $engine = 'bcmath'; + break; + case MATH_BIGINTEGER_MODE_INTERNAL: + $engine = 'internal'; + $opts[] = PHP_INT_SIZE == 8 ? '64-bit' : '32-bit'; + } + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_GMP && defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { + $opts[] = 'OpenSSL'; + } + if (!empty($opts)) { + $engine.= ' (' . implode($opts, ', ') . ')'; + } + return array( + 'value' => '0x' . $this->toHex(true), + 'engine' => $engine + ); + } + + /** + * Adds two BigIntegers. + * + * Here's an example: + * + * add($b); + * + * echo $c->toString(); // outputs 30 + * ?> + * + * + * @param Math_BigInteger $y + * @return Math_BigInteger + * @access public + * @internal Performs base-2**52 addition + */ + function add($y) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_add($this->value, $y->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcadd($this->value, $y->value, 0); + + return $this->_normalize($temp); + } + + $temp = $this->_add($this->value, $this->is_negative, $y->value, $y->is_negative); + + $result = new Math_BigInteger(); + $result->value = $temp[MATH_BIGINTEGER_VALUE]; + $result->is_negative = $temp[MATH_BIGINTEGER_SIGN]; + + return $this->_normalize($result); + } + + /** + * Performs addition. + * + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array + * @access private + */ + function _add($x_value, $x_negative, $y_value, $y_negative) + { + $x_size = count($x_value); + $y_size = count($y_value); + + if ($x_size == 0) { + return array( + MATH_BIGINTEGER_VALUE => $y_value, + MATH_BIGINTEGER_SIGN => $y_negative + ); + } elseif ($y_size == 0) { + return array( + MATH_BIGINTEGER_VALUE => $x_value, + MATH_BIGINTEGER_SIGN => $x_negative + ); + } + + // subtract, if appropriate + if ($x_negative != $y_negative) { + if ($x_value == $y_value) { + return array( + MATH_BIGINTEGER_VALUE => array(), + MATH_BIGINTEGER_SIGN => false + ); + } + + $temp = $this->_subtract($x_value, false, $y_value, false); + $temp[MATH_BIGINTEGER_SIGN] = $this->_compare($x_value, false, $y_value, false) > 0 ? + $x_negative : $y_negative; + + return $temp; + } + + if ($x_size < $y_size) { + $size = $x_size; + $value = $y_value; + } else { + $size = $y_size; + $value = $x_value; + } + + $value[count($value)] = 0; // just in case the carry adds an extra digit + + $carry = 0; + for ($i = 0, $j = 1; $j < $size; $i+=2, $j+=2) { + $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] + $y_value[$j] * MATH_BIGINTEGER_BASE_FULL + $y_value[$i] + $carry; + $carry = $sum >= MATH_BIGINTEGER_MAX_DIGIT2; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 + $sum = $carry ? $sum - MATH_BIGINTEGER_MAX_DIGIT2 : $sum; + + $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31); + + $value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp); // eg. a faster alternative to fmod($sum, 0x4000000) + $value[$j] = $temp; + } + + if ($j == $size) { // ie. if $y_size is odd + $sum = $x_value[$i] + $y_value[$i] + $carry; + $carry = $sum >= MATH_BIGINTEGER_BASE_FULL; + $value[$i] = $carry ? $sum - MATH_BIGINTEGER_BASE_FULL : $sum; + ++$i; // ie. let $i = $j since we've just done $value[$i] + } + + if ($carry) { + for (; $value[$i] == MATH_BIGINTEGER_MAX_DIGIT; ++$i) { + $value[$i] = 0; + } + ++$value[$i]; + } + + return array( + MATH_BIGINTEGER_VALUE => $this->_trim($value), + MATH_BIGINTEGER_SIGN => $x_negative + ); + } + + /** + * Subtracts two BigIntegers. + * + * Here's an example: + * + * subtract($b); + * + * echo $c->toString(); // outputs -10 + * ?> + * + * + * @param Math_BigInteger $y + * @return Math_BigInteger + * @access public + * @internal Performs base-2**52 subtraction + */ + function subtract($y) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_sub($this->value, $y->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcsub($this->value, $y->value, 0); + + return $this->_normalize($temp); + } + + $temp = $this->_subtract($this->value, $this->is_negative, $y->value, $y->is_negative); + + $result = new Math_BigInteger(); + $result->value = $temp[MATH_BIGINTEGER_VALUE]; + $result->is_negative = $temp[MATH_BIGINTEGER_SIGN]; + + return $this->_normalize($result); + } + + /** + * Performs subtraction. + * + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array + * @access private + */ + function _subtract($x_value, $x_negative, $y_value, $y_negative) + { + $x_size = count($x_value); + $y_size = count($y_value); + + if ($x_size == 0) { + return array( + MATH_BIGINTEGER_VALUE => $y_value, + MATH_BIGINTEGER_SIGN => !$y_negative + ); + } elseif ($y_size == 0) { + return array( + MATH_BIGINTEGER_VALUE => $x_value, + MATH_BIGINTEGER_SIGN => $x_negative + ); + } + + // add, if appropriate (ie. -$x - +$y or +$x - -$y) + if ($x_negative != $y_negative) { + $temp = $this->_add($x_value, false, $y_value, false); + $temp[MATH_BIGINTEGER_SIGN] = $x_negative; + + return $temp; + } + + $diff = $this->_compare($x_value, $x_negative, $y_value, $y_negative); + + if (!$diff) { + return array( + MATH_BIGINTEGER_VALUE => array(), + MATH_BIGINTEGER_SIGN => false + ); + } + + // switch $x and $y around, if appropriate. + if ((!$x_negative && $diff < 0) || ($x_negative && $diff > 0)) { + $temp = $x_value; + $x_value = $y_value; + $y_value = $temp; + + $x_negative = !$x_negative; + + $x_size = count($x_value); + $y_size = count($y_value); + } + + // at this point, $x_value should be at least as big as - if not bigger than - $y_value + + $carry = 0; + for ($i = 0, $j = 1; $j < $y_size; $i+=2, $j+=2) { + $sum = $x_value[$j] * MATH_BIGINTEGER_BASE_FULL + $x_value[$i] - $y_value[$j] * MATH_BIGINTEGER_BASE_FULL - $y_value[$i] - $carry; + $carry = $sum < 0; // eg. floor($sum / 2**52); only possible values (in any base) are 0 and 1 + $sum = $carry ? $sum + MATH_BIGINTEGER_MAX_DIGIT2 : $sum; + + $temp = MATH_BIGINTEGER_BASE === 26 ? intval($sum / 0x4000000) : ($sum >> 31); + + $x_value[$i] = (int) ($sum - MATH_BIGINTEGER_BASE_FULL * $temp); + $x_value[$j] = $temp; + } + + if ($j == $y_size) { // ie. if $y_size is odd + $sum = $x_value[$i] - $y_value[$i] - $carry; + $carry = $sum < 0; + $x_value[$i] = $carry ? $sum + MATH_BIGINTEGER_BASE_FULL : $sum; + ++$i; + } + + if ($carry) { + for (; !$x_value[$i]; ++$i) { + $x_value[$i] = MATH_BIGINTEGER_MAX_DIGIT; + } + --$x_value[$i]; + } + + return array( + MATH_BIGINTEGER_VALUE => $this->_trim($x_value), + MATH_BIGINTEGER_SIGN => $x_negative + ); + } + + /** + * Multiplies two BigIntegers + * + * Here's an example: + * + * multiply($b); + * + * echo $c->toString(); // outputs 200 + * ?> + * + * + * @param Math_BigInteger $x + * @return Math_BigInteger + * @access public + */ + function multiply($x) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_mul($this->value, $x->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $temp = new Math_BigInteger(); + $temp->value = bcmul($this->value, $x->value, 0); + + return $this->_normalize($temp); + } + + $temp = $this->_multiply($this->value, $this->is_negative, $x->value, $x->is_negative); + + $product = new Math_BigInteger(); + $product->value = $temp[MATH_BIGINTEGER_VALUE]; + $product->is_negative = $temp[MATH_BIGINTEGER_SIGN]; + + return $this->_normalize($product); + } + + /** + * Performs multiplication. + * + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return array + * @access private + */ + function _multiply($x_value, $x_negative, $y_value, $y_negative) + { + //if ( $x_value == $y_value ) { + // return array( + // MATH_BIGINTEGER_VALUE => $this->_square($x_value), + // MATH_BIGINTEGER_SIGN => $x_sign != $y_value + // ); + //} + + $x_length = count($x_value); + $y_length = count($y_value); + + if (!$x_length || !$y_length) { // a 0 is being multiplied + return array( + MATH_BIGINTEGER_VALUE => array(), + MATH_BIGINTEGER_SIGN => false + ); + } + + return array( + MATH_BIGINTEGER_VALUE => min($x_length, $y_length) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ? + $this->_trim($this->_regularMultiply($x_value, $y_value)) : + $this->_trim($this->_karatsuba($x_value, $y_value)), + MATH_BIGINTEGER_SIGN => $x_negative != $y_negative + ); + } + + /** + * Performs long multiplication on two BigIntegers + * + * Modeled after 'multiply' in MutableBigInteger.java. + * + * @param array $x_value + * @param array $y_value + * @return array + * @access private + */ + function _regularMultiply($x_value, $y_value) + { + $x_length = count($x_value); + $y_length = count($y_value); + + if (!$x_length || !$y_length) { // a 0 is being multiplied + return array(); + } + + if ($x_length < $y_length) { + $temp = $x_value; + $x_value = $y_value; + $y_value = $temp; + + $x_length = count($x_value); + $y_length = count($y_value); + } + + $product_value = $this->_array_repeat(0, $x_length + $y_length); + + // the following for loop could be removed if the for loop following it + // (the one with nested for loops) initially set $i to 0, but + // doing so would also make the result in one set of unnecessary adds, + // since on the outermost loops first pass, $product->value[$k] is going + // to always be 0 + + $carry = 0; + + for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0 + $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0 + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + } + + $product_value[$j] = $carry; + + // the above for loop is what the previous comment was talking about. the + // following for loop is the "one with nested for loops" + for ($i = 1; $i < $y_length; ++$i) { + $carry = 0; + + for ($j = 0, $k = $i; $j < $x_length; ++$j, ++$k) { + $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry; + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + } + + $product_value[$k] = $carry; + } + + return $product_value; + } + + /** + * Performs Karatsuba multiplication on two BigIntegers + * + * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=120 MPM 5.2.3}. + * + * @param array $x_value + * @param array $y_value + * @return array + * @access private + */ + function _karatsuba($x_value, $y_value) + { + $m = min(count($x_value) >> 1, count($y_value) >> 1); + + if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) { + return $this->_regularMultiply($x_value, $y_value); + } + + $x1 = array_slice($x_value, $m); + $x0 = array_slice($x_value, 0, $m); + $y1 = array_slice($y_value, $m); + $y0 = array_slice($y_value, 0, $m); + + $z2 = $this->_karatsuba($x1, $y1); + $z0 = $this->_karatsuba($x0, $y0); + + $z1 = $this->_add($x1, false, $x0, false); + $temp = $this->_add($y1, false, $y0, false); + $z1 = $this->_karatsuba($z1[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_VALUE]); + $temp = $this->_add($z2, false, $z0, false); + $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false); + + $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2); + $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]); + + $xy = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]); + $xy = $this->_add($xy[MATH_BIGINTEGER_VALUE], $xy[MATH_BIGINTEGER_SIGN], $z0, false); + + return $xy[MATH_BIGINTEGER_VALUE]; + } + + /** + * Performs squaring + * + * @param array $x + * @return array + * @access private + */ + function _square($x = false) + { + return count($x) < 2 * MATH_BIGINTEGER_KARATSUBA_CUTOFF ? + $this->_trim($this->_baseSquare($x)) : + $this->_trim($this->_karatsubaSquare($x)); + } + + /** + * Performs traditional squaring on two BigIntegers + * + * Squaring can be done faster than multiplying a number by itself can be. See + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=7 HAC 14.2.4} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=141 MPM 5.3} for more information. + * + * @param array $value + * @return array + * @access private + */ + function _baseSquare($value) + { + if (empty($value)) { + return array(); + } + $square_value = $this->_array_repeat(0, 2 * count($value)); + + for ($i = 0, $max_index = count($value) - 1; $i <= $max_index; ++$i) { + $i2 = $i << 1; + + $temp = $square_value[$i2] + $value[$i] * $value[$i]; + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $square_value[$i2] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + + // note how we start from $i+1 instead of 0 as we do in multiplication. + for ($j = $i + 1, $k = $i2 + 1; $j <= $max_index; ++$j, ++$k) { + $temp = $square_value[$k] + 2 * $value[$j] * $value[$i] + $carry; + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $square_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + } + + // the following line can yield values larger 2**15. at this point, PHP should switch + // over to floats. + $square_value[$i + $max_index + 1] = $carry; + } + + return $square_value; + } + + /** + * Performs Karatsuba "squaring" on two BigIntegers + * + * See {@link http://en.wikipedia.org/wiki/Karatsuba_algorithm Karatsuba algorithm} and + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=151 MPM 5.3.4}. + * + * @param array $value + * @return array + * @access private + */ + function _karatsubaSquare($value) + { + $m = count($value) >> 1; + + if ($m < MATH_BIGINTEGER_KARATSUBA_CUTOFF) { + return $this->_baseSquare($value); + } + + $x1 = array_slice($value, $m); + $x0 = array_slice($value, 0, $m); + + $z2 = $this->_karatsubaSquare($x1); + $z0 = $this->_karatsubaSquare($x0); + + $z1 = $this->_add($x1, false, $x0, false); + $z1 = $this->_karatsubaSquare($z1[MATH_BIGINTEGER_VALUE]); + $temp = $this->_add($z2, false, $z0, false); + $z1 = $this->_subtract($z1, false, $temp[MATH_BIGINTEGER_VALUE], false); + + $z2 = array_merge(array_fill(0, 2 * $m, 0), $z2); + $z1[MATH_BIGINTEGER_VALUE] = array_merge(array_fill(0, $m, 0), $z1[MATH_BIGINTEGER_VALUE]); + + $xx = $this->_add($z2, false, $z1[MATH_BIGINTEGER_VALUE], $z1[MATH_BIGINTEGER_SIGN]); + $xx = $this->_add($xx[MATH_BIGINTEGER_VALUE], $xx[MATH_BIGINTEGER_SIGN], $z0, false); + + return $xx[MATH_BIGINTEGER_VALUE]; + } + + /** + * Divides two BigIntegers. + * + * Returns an array whose first element contains the quotient and whose second element contains the + * "common residue". If the remainder would be positive, the "common residue" and the remainder are the + * same. If the remainder would be negative, the "common residue" is equal to the sum of the remainder + * and the divisor (basically, the "common residue" is the first positive modulo). + * + * Here's an example: + * + * divide($b); + * + * echo $quotient->toString(); // outputs 0 + * echo "\r\n"; + * echo $remainder->toString(); // outputs 10 + * ?> + * + * + * @param Math_BigInteger $y + * @return array + * @access public + * @internal This function is based off of {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=9 HAC 14.20}. + */ + function divide($y) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $quotient = new Math_BigInteger(); + $remainder = new Math_BigInteger(); + + list($quotient->value, $remainder->value) = gmp_div_qr($this->value, $y->value); + + if (gmp_sign($remainder->value) < 0) { + $remainder->value = gmp_add($remainder->value, gmp_abs($y->value)); + } + + return array($this->_normalize($quotient), $this->_normalize($remainder)); + case MATH_BIGINTEGER_MODE_BCMATH: + $quotient = new Math_BigInteger(); + $remainder = new Math_BigInteger(); + + $quotient->value = bcdiv($this->value, $y->value, 0); + $remainder->value = bcmod($this->value, $y->value); + + if ($remainder->value[0] == '-') { + $remainder->value = bcadd($remainder->value, $y->value[0] == '-' ? substr($y->value, 1) : $y->value, 0); + } + + return array($this->_normalize($quotient), $this->_normalize($remainder)); + } + + if (count($y->value) == 1) { + list($q, $r) = $this->_divide_digit($this->value, $y->value[0]); + $quotient = new Math_BigInteger(); + $remainder = new Math_BigInteger(); + $quotient->value = $q; + $remainder->value = array($r); + $quotient->is_negative = $this->is_negative != $y->is_negative; + return array($this->_normalize($quotient), $this->_normalize($remainder)); + } + + static $zero; + if (!isset($zero)) { + $zero = new Math_BigInteger(); + } + + $x = $this->copy(); + $y = $y->copy(); + + $x_sign = $x->is_negative; + $y_sign = $y->is_negative; + + $x->is_negative = $y->is_negative = false; + + $diff = $x->compare($y); + + if (!$diff) { + $temp = new Math_BigInteger(); + $temp->value = array(1); + $temp->is_negative = $x_sign != $y_sign; + return array($this->_normalize($temp), $this->_normalize(new Math_BigInteger())); + } + + if ($diff < 0) { + // if $x is negative, "add" $y. + if ($x_sign) { + $x = $y->subtract($x); + } + return array($this->_normalize(new Math_BigInteger()), $this->_normalize($x)); + } + + // normalize $x and $y as described in HAC 14.23 / 14.24 + $msb = $y->value[count($y->value) - 1]; + for ($shift = 0; !($msb & MATH_BIGINTEGER_MSB); ++$shift) { + $msb <<= 1; + } + $x->_lshift($shift); + $y->_lshift($shift); + $y_value = &$y->value; + + $x_max = count($x->value) - 1; + $y_max = count($y->value) - 1; + + $quotient = new Math_BigInteger(); + $quotient_value = &$quotient->value; + $quotient_value = $this->_array_repeat(0, $x_max - $y_max + 1); + + static $temp, $lhs, $rhs; + if (!isset($temp)) { + $temp = new Math_BigInteger(); + $lhs = new Math_BigInteger(); + $rhs = new Math_BigInteger(); + } + $temp_value = &$temp->value; + $rhs_value = &$rhs->value; + + // $temp = $y << ($x_max - $y_max-1) in base 2**26 + $temp_value = array_merge($this->_array_repeat(0, $x_max - $y_max), $y_value); + + while ($x->compare($temp) >= 0) { + // calculate the "common residue" + ++$quotient_value[$x_max - $y_max]; + $x = $x->subtract($temp); + $x_max = count($x->value) - 1; + } + + for ($i = $x_max; $i >= $y_max + 1; --$i) { + $x_value = &$x->value; + $x_window = array( + isset($x_value[$i]) ? $x_value[$i] : 0, + isset($x_value[$i - 1]) ? $x_value[$i - 1] : 0, + isset($x_value[$i - 2]) ? $x_value[$i - 2] : 0 + ); + $y_window = array( + $y_value[$y_max], + ($y_max > 0) ? $y_value[$y_max - 1] : 0 + ); + + $q_index = $i - $y_max - 1; + if ($x_window[0] == $y_window[0]) { + $quotient_value[$q_index] = MATH_BIGINTEGER_MAX_DIGIT; + } else { + $quotient_value[$q_index] = $this->_safe_divide( + $x_window[0] * MATH_BIGINTEGER_BASE_FULL + $x_window[1], + $y_window[0] + ); + } + + $temp_value = array($y_window[1], $y_window[0]); + + $lhs->value = array($quotient_value[$q_index]); + $lhs = $lhs->multiply($temp); + + $rhs_value = array($x_window[2], $x_window[1], $x_window[0]); + + while ($lhs->compare($rhs) > 0) { + --$quotient_value[$q_index]; + + $lhs->value = array($quotient_value[$q_index]); + $lhs = $lhs->multiply($temp); + } + + $adjust = $this->_array_repeat(0, $q_index); + $temp_value = array($quotient_value[$q_index]); + $temp = $temp->multiply($y); + $temp_value = &$temp->value; + $temp_value = array_merge($adjust, $temp_value); + + $x = $x->subtract($temp); + + if ($x->compare($zero) < 0) { + $temp_value = array_merge($adjust, $y_value); + $x = $x->add($temp); + + --$quotient_value[$q_index]; + } + + $x_max = count($x_value) - 1; + } + + // unnormalize the remainder + $x->_rshift($shift); + + $quotient->is_negative = $x_sign != $y_sign; + + // calculate the "common residue", if appropriate + if ($x_sign) { + $y->_rshift($shift); + $x = $y->subtract($x); + } + + return array($this->_normalize($quotient), $this->_normalize($x)); + } + + /** + * Divides a BigInteger by a regular integer + * + * abc / x = a00 / x + b0 / x + c / x + * + * @param array $dividend + * @param array $divisor + * @return array + * @access private + */ + function _divide_digit($dividend, $divisor) + { + $carry = 0; + $result = array(); + + for ($i = count($dividend) - 1; $i >= 0; --$i) { + $temp = MATH_BIGINTEGER_BASE_FULL * $carry + $dividend[$i]; + $result[$i] = $this->_safe_divide($temp, $divisor); + $carry = (int) ($temp - $divisor * $result[$i]); + } + + return array($result, $carry); + } + + /** + * Performs modular exponentiation. + * + * Here's an example: + * + * modPow($b, $c); + * + * echo $c->toString(); // outputs 10 + * ?> + * + * + * @param Math_BigInteger $e + * @param Math_BigInteger $n + * @return Math_BigInteger + * @access public + * @internal The most naive approach to modular exponentiation has very unreasonable requirements, and + * and although the approach involving repeated squaring does vastly better, it, too, is impractical + * for our purposes. The reason being that division - by far the most complicated and time-consuming + * of the basic operations (eg. +,-,*,/) - occurs multiple times within it. + * + * Modular reductions resolve this issue. Although an individual modular reduction takes more time + * then an individual division, when performed in succession (with the same modulo), they're a lot faster. + * + * The two most commonly used modular reductions are Barrett and Montgomery reduction. Montgomery reduction, + * although faster, only works when the gcd of the modulo and of the base being used is 1. In RSA, when the + * base is a power of two, the modulo - a product of two primes - is always going to have a gcd of 1 (because + * the product of two odd numbers is odd), but what about when RSA isn't used? + * + * In contrast, Barrett reduction has no such constraint. As such, some bigint implementations perform a + * Barrett reduction after every operation in the modpow function. Others perform Barrett reductions when the + * modulo is even and Montgomery reductions when the modulo is odd. BigInteger.java's modPow method, however, + * uses a trick involving the Chinese Remainder Theorem to factor the even modulo into two numbers - one odd and + * the other, a power of two - and recombine them, later. This is the method that this modPow function uses. + * {@link http://islab.oregonstate.edu/papers/j34monex.pdf Montgomery Reduction with Even Modulus} elaborates. + */ + function modPow($e, $n) + { + $n = $this->bitmask !== false && $this->bitmask->compare($n) < 0 ? $this->bitmask : $n->abs(); + + if ($e->compare(new Math_BigInteger()) < 0) { + $e = $e->abs(); + + $temp = $this->modInverse($n); + if ($temp === false) { + return false; + } + + return $this->_normalize($temp->modPow($e, $n)); + } + + if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP) { + $temp = new Math_BigInteger(); + $temp->value = gmp_powm($this->value, $e->value, $n->value); + + return $this->_normalize($temp); + } + + if ($this->compare(new Math_BigInteger()) < 0 || $this->compare($n) > 0) { + list(, $temp) = $this->divide($n); + return $temp->modPow($e, $n); + } + + if (defined('MATH_BIGINTEGER_OPENSSL_ENABLED')) { + $components = array( + 'modulus' => $n->toBytes(true), + 'publicExponent' => $e->toBytes(true) + ); + + $components = array( + 'modulus' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['modulus'])), $components['modulus']), + 'publicExponent' => pack('Ca*a*', 2, $this->_encodeASN1Length(strlen($components['publicExponent'])), $components['publicExponent']) + ); + + $RSAPublicKey = pack( + 'Ca*a*a*', + 48, + $this->_encodeASN1Length(strlen($components['modulus']) + strlen($components['publicExponent'])), + $components['modulus'], + $components['publicExponent'] + ); + + $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA + $RSAPublicKey = chr(0) . $RSAPublicKey; + $RSAPublicKey = chr(3) . $this->_encodeASN1Length(strlen($RSAPublicKey)) . $RSAPublicKey; + + $encapsulated = pack( + 'Ca*a*', + 48, + $this->_encodeASN1Length(strlen($rsaOID . $RSAPublicKey)), + $rsaOID . $RSAPublicKey + ); + + $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" . + chunk_split(base64_encode($encapsulated)) . + '-----END PUBLIC KEY-----'; + + $plaintext = str_pad($this->toBytes(), strlen($n->toBytes(true)) - 1, "\0", STR_PAD_LEFT); + + if (openssl_public_encrypt($plaintext, $result, $RSAPublicKey, OPENSSL_NO_PADDING)) { + return new Math_BigInteger($result, 256); + } + } + + if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH) { + $temp = new Math_BigInteger(); + $temp->value = bcpowmod($this->value, $e->value, $n->value, 0); + + return $this->_normalize($temp); + } + + if (empty($e->value)) { + $temp = new Math_BigInteger(); + $temp->value = array(1); + return $this->_normalize($temp); + } + + if ($e->value == array(1)) { + list(, $temp) = $this->divide($n); + return $this->_normalize($temp); + } + + if ($e->value == array(2)) { + $temp = new Math_BigInteger(); + $temp->value = $this->_square($this->value); + list(, $temp) = $temp->divide($n); + return $this->_normalize($temp); + } + + return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_BARRETT)); + + // the following code, although not callable, can be run independently of the above code + // although the above code performed better in my benchmarks the following could might + // perform better under different circumstances. in lieu of deleting it it's just been + // made uncallable + + // is the modulo odd? + if ($n->value[0] & 1) { + return $this->_normalize($this->_slidingWindow($e, $n, MATH_BIGINTEGER_MONTGOMERY)); + } + // if it's not, it's even + + // find the lowest set bit (eg. the max pow of 2 that divides $n) + for ($i = 0; $i < count($n->value); ++$i) { + if ($n->value[$i]) { + $temp = decbin($n->value[$i]); + $j = strlen($temp) - strrpos($temp, '1') - 1; + $j+= 26 * $i; + break; + } + } + // at this point, 2^$j * $n/(2^$j) == $n + + $mod1 = $n->copy(); + $mod1->_rshift($j); + $mod2 = new Math_BigInteger(); + $mod2->value = array(1); + $mod2->_lshift($j); + + $part1 = ($mod1->value != array(1)) ? $this->_slidingWindow($e, $mod1, MATH_BIGINTEGER_MONTGOMERY) : new Math_BigInteger(); + $part2 = $this->_slidingWindow($e, $mod2, MATH_BIGINTEGER_POWEROF2); + + $y1 = $mod2->modInverse($mod1); + $y2 = $mod1->modInverse($mod2); + + $result = $part1->multiply($mod2); + $result = $result->multiply($y1); + + $temp = $part2->multiply($mod1); + $temp = $temp->multiply($y2); + + $result = $result->add($temp); + list(, $result) = $result->divide($n); + + return $this->_normalize($result); + } + + /** + * Performs modular exponentiation. + * + * Alias for Math_BigInteger::modPow() + * + * @param Math_BigInteger $e + * @param Math_BigInteger $n + * @return Math_BigInteger + * @access public + */ + function powMod($e, $n) + { + return $this->modPow($e, $n); + } + + /** + * Sliding Window k-ary Modular Exponentiation + * + * Based on {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=27 HAC 14.85} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=210 MPM 7.7}. In a departure from those algorithims, + * however, this function performs a modular reduction after every multiplication and squaring operation. + * As such, this function has the same preconditions that the reductions being used do. + * + * @param Math_BigInteger $e + * @param Math_BigInteger $n + * @param int $mode + * @return Math_BigInteger + * @access private + */ + function _slidingWindow($e, $n, $mode) + { + static $window_ranges = array(7, 25, 81, 241, 673, 1793); // from BigInteger.java's oddModPow function + //static $window_ranges = array(0, 7, 36, 140, 450, 1303, 3529); // from MPM 7.3.1 + + $e_value = $e->value; + $e_length = count($e_value) - 1; + $e_bits = decbin($e_value[$e_length]); + for ($i = $e_length - 1; $i >= 0; --$i) { + $e_bits.= str_pad(decbin($e_value[$i]), MATH_BIGINTEGER_BASE, '0', STR_PAD_LEFT); + } + + $e_length = strlen($e_bits); + + // calculate the appropriate window size. + // $window_size == 3 if $window_ranges is between 25 and 81, for example. + for ($i = 0, $window_size = 1; $i < count($window_ranges) && $e_length > $window_ranges[$i]; ++$window_size, ++$i) { + } + + $n_value = $n->value; + + // precompute $this^0 through $this^$window_size + $powers = array(); + $powers[1] = $this->_prepareReduce($this->value, $n_value, $mode); + $powers[2] = $this->_squareReduce($powers[1], $n_value, $mode); + + // we do every other number since substr($e_bits, $i, $j+1) (see below) is supposed to end + // in a 1. ie. it's supposed to be odd. + $temp = 1 << ($window_size - 1); + for ($i = 1; $i < $temp; ++$i) { + $i2 = $i << 1; + $powers[$i2 + 1] = $this->_multiplyReduce($powers[$i2 - 1], $powers[2], $n_value, $mode); + } + + $result = array(1); + $result = $this->_prepareReduce($result, $n_value, $mode); + + for ($i = 0; $i < $e_length;) { + if (!$e_bits[$i]) { + $result = $this->_squareReduce($result, $n_value, $mode); + ++$i; + } else { + for ($j = $window_size - 1; $j > 0; --$j) { + if (!empty($e_bits[$i + $j])) { + break; + } + } + + // eg. the length of substr($e_bits, $i, $j + 1) + for ($k = 0; $k <= $j; ++$k) { + $result = $this->_squareReduce($result, $n_value, $mode); + } + + $result = $this->_multiplyReduce($result, $powers[bindec(substr($e_bits, $i, $j + 1))], $n_value, $mode); + + $i += $j + 1; + } + } + + $temp = new Math_BigInteger(); + $temp->value = $this->_reduce($result, $n_value, $mode); + + return $temp; + } + + /** + * Modular reduction + * + * For most $modes this will return the remainder. + * + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @param int $mode + * @return array + */ + function _reduce($x, $n, $mode) + { + switch ($mode) { + case MATH_BIGINTEGER_MONTGOMERY: + return $this->_montgomery($x, $n); + case MATH_BIGINTEGER_BARRETT: + return $this->_barrett($x, $n); + case MATH_BIGINTEGER_POWEROF2: + $lhs = new Math_BigInteger(); + $lhs->value = $x; + $rhs = new Math_BigInteger(); + $rhs->value = $n; + return $x->_mod2($n); + case MATH_BIGINTEGER_CLASSIC: + $lhs = new Math_BigInteger(); + $lhs->value = $x; + $rhs = new Math_BigInteger(); + $rhs->value = $n; + list(, $temp) = $lhs->divide($rhs); + return $temp->value; + case MATH_BIGINTEGER_NONE: + return $x; + default: + // an invalid $mode was provided + } + } + + /** + * Modular reduction preperation + * + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @param int $mode + * @return array + */ + function _prepareReduce($x, $n, $mode) + { + if ($mode == MATH_BIGINTEGER_MONTGOMERY) { + return $this->_prepMontgomery($x, $n); + } + return $this->_reduce($x, $n, $mode); + } + + /** + * Modular multiply + * + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $y + * @param array $n + * @param int $mode + * @return array + */ + function _multiplyReduce($x, $y, $n, $mode) + { + if ($mode == MATH_BIGINTEGER_MONTGOMERY) { + return $this->_montgomeryMultiply($x, $y, $n); + } + $temp = $this->_multiply($x, false, $y, false); + return $this->_reduce($temp[MATH_BIGINTEGER_VALUE], $n, $mode); + } + + /** + * Modular square + * + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @param int $mode + * @return array + */ + function _squareReduce($x, $n, $mode) + { + if ($mode == MATH_BIGINTEGER_MONTGOMERY) { + return $this->_montgomeryMultiply($x, $x, $n); + } + return $this->_reduce($this->_square($x), $n, $mode); + } + + /** + * Modulos for Powers of Two + * + * Calculates $x%$n, where $n = 2**$e, for some $e. Since this is basically the same as doing $x & ($n-1), + * we'll just use this function as a wrapper for doing that. + * + * @see self::_slidingWindow() + * @access private + * @param Math_BigInteger + * @return Math_BigInteger + */ + function _mod2($n) + { + $temp = new Math_BigInteger(); + $temp->value = array(1); + return $this->bitwise_and($n->subtract($temp)); + } + + /** + * Barrett Modular Reduction + * + * See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=14 HAC 14.3.3} / + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=165 MPM 6.2.5} for more information. Modified slightly, + * so as not to require negative numbers (initially, this script didn't support negative numbers). + * + * Employs "folding", as described at + * {@link http://www.cosic.esat.kuleuven.be/publications/thesis-149.pdf#page=66 thesis-149.pdf#page=66}. To quote from + * it, "the idea [behind folding] is to find a value x' such that x (mod m) = x' (mod m), with x' being smaller than x." + * + * Unfortunately, the "Barrett Reduction with Folding" algorithm described in thesis-149.pdf is not, as written, all that + * usable on account of (1) its not using reasonable radix points as discussed in + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=162 MPM 6.2.2} and (2) the fact that, even with reasonable + * radix points, it only works when there are an even number of digits in the denominator. The reason for (2) is that + * (x >> 1) + (x >> 1) != x / 2 + x / 2. If x is even, they're the same, but if x is odd, they're not. See the in-line + * comments for details. + * + * @see self::_slidingWindow() + * @access private + * @param array $n + * @param array $m + * @return array + */ + function _barrett($n, $m) + { + static $cache = array( + MATH_BIGINTEGER_VARIABLE => array(), + MATH_BIGINTEGER_DATA => array() + ); + + $m_length = count($m); + + // if ($this->_compare($n, $this->_square($m)) >= 0) { + if (count($n) > 2 * $m_length) { + $lhs = new Math_BigInteger(); + $rhs = new Math_BigInteger(); + $lhs->value = $n; + $rhs->value = $m; + list(, $temp) = $lhs->divide($rhs); + return $temp->value; + } + + // if (m.length >> 1) + 2 <= m.length then m is too small and n can't be reduced + if ($m_length < 5) { + return $this->_regularBarrett($n, $m); + } + + // n = 2 * m.length + + if (($key = array_search($m, $cache[MATH_BIGINTEGER_VARIABLE])) === false) { + $key = count($cache[MATH_BIGINTEGER_VARIABLE]); + $cache[MATH_BIGINTEGER_VARIABLE][] = $m; + + $lhs = new Math_BigInteger(); + $lhs_value = &$lhs->value; + $lhs_value = $this->_array_repeat(0, $m_length + ($m_length >> 1)); + $lhs_value[] = 1; + $rhs = new Math_BigInteger(); + $rhs->value = $m; + + list($u, $m1) = $lhs->divide($rhs); + $u = $u->value; + $m1 = $m1->value; + + $cache[MATH_BIGINTEGER_DATA][] = array( + 'u' => $u, // m.length >> 1 (technically (m.length >> 1) + 1) + 'm1'=> $m1 // m.length + ); + } else { + extract($cache[MATH_BIGINTEGER_DATA][$key]); + } + + $cutoff = $m_length + ($m_length >> 1); + $lsd = array_slice($n, 0, $cutoff); // m.length + (m.length >> 1) + $msd = array_slice($n, $cutoff); // m.length >> 1 + $lsd = $this->_trim($lsd); + $temp = $this->_multiply($msd, false, $m1, false); + $n = $this->_add($lsd, false, $temp[MATH_BIGINTEGER_VALUE], false); // m.length + (m.length >> 1) + 1 + + if ($m_length & 1) { + return $this->_regularBarrett($n[MATH_BIGINTEGER_VALUE], $m); + } + + // (m.length + (m.length >> 1) + 1) - (m.length - 1) == (m.length >> 1) + 2 + $temp = array_slice($n[MATH_BIGINTEGER_VALUE], $m_length - 1); + // if even: ((m.length >> 1) + 2) + (m.length >> 1) == m.length + 2 + // if odd: ((m.length >> 1) + 2) + (m.length >> 1) == (m.length - 1) + 2 == m.length + 1 + $temp = $this->_multiply($temp, false, $u, false); + // if even: (m.length + 2) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) + 1 + // if odd: (m.length + 1) - ((m.length >> 1) + 1) = m.length - (m.length >> 1) + $temp = array_slice($temp[MATH_BIGINTEGER_VALUE], ($m_length >> 1) + 1); + // if even: (m.length - (m.length >> 1) + 1) + m.length = 2 * m.length - (m.length >> 1) + 1 + // if odd: (m.length - (m.length >> 1)) + m.length = 2 * m.length - (m.length >> 1) + $temp = $this->_multiply($temp, false, $m, false); + + // at this point, if m had an odd number of digits, we'd be subtracting a 2 * m.length - (m.length >> 1) digit + // number from a m.length + (m.length >> 1) + 1 digit number. ie. there'd be an extra digit and the while loop + // following this comment would loop a lot (hence our calling _regularBarrett() in that situation). + + $result = $this->_subtract($n[MATH_BIGINTEGER_VALUE], false, $temp[MATH_BIGINTEGER_VALUE], false); + + while ($this->_compare($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $m, false) >= 0) { + $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $m, false); + } + + return $result[MATH_BIGINTEGER_VALUE]; + } + + /** + * (Regular) Barrett Modular Reduction + * + * For numbers with more than four digits Math_BigInteger::_barrett() is faster. The difference between that and this + * is that this function does not fold the denominator into a smaller form. + * + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @return array + */ + function _regularBarrett($x, $n) + { + static $cache = array( + MATH_BIGINTEGER_VARIABLE => array(), + MATH_BIGINTEGER_DATA => array() + ); + + $n_length = count($n); + + if (count($x) > 2 * $n_length) { + $lhs = new Math_BigInteger(); + $rhs = new Math_BigInteger(); + $lhs->value = $x; + $rhs->value = $n; + list(, $temp) = $lhs->divide($rhs); + return $temp->value; + } + + if (($key = array_search($n, $cache[MATH_BIGINTEGER_VARIABLE])) === false) { + $key = count($cache[MATH_BIGINTEGER_VARIABLE]); + $cache[MATH_BIGINTEGER_VARIABLE][] = $n; + $lhs = new Math_BigInteger(); + $lhs_value = &$lhs->value; + $lhs_value = $this->_array_repeat(0, 2 * $n_length); + $lhs_value[] = 1; + $rhs = new Math_BigInteger(); + $rhs->value = $n; + list($temp, ) = $lhs->divide($rhs); // m.length + $cache[MATH_BIGINTEGER_DATA][] = $temp->value; + } + + // 2 * m.length - (m.length - 1) = m.length + 1 + $temp = array_slice($x, $n_length - 1); + // (m.length + 1) + m.length = 2 * m.length + 1 + $temp = $this->_multiply($temp, false, $cache[MATH_BIGINTEGER_DATA][$key], false); + // (2 * m.length + 1) - (m.length - 1) = m.length + 2 + $temp = array_slice($temp[MATH_BIGINTEGER_VALUE], $n_length + 1); + + // m.length + 1 + $result = array_slice($x, 0, $n_length + 1); + // m.length + 1 + $temp = $this->_multiplyLower($temp, false, $n, false, $n_length + 1); + // $temp == array_slice($temp->_multiply($temp, false, $n, false)->value, 0, $n_length + 1) + + if ($this->_compare($result, false, $temp[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_SIGN]) < 0) { + $corrector_value = $this->_array_repeat(0, $n_length + 1); + $corrector_value[count($corrector_value)] = 1; + $result = $this->_add($result, false, $corrector_value, false); + $result = $result[MATH_BIGINTEGER_VALUE]; + } + + // at this point, we're subtracting a number with m.length + 1 digits from another number with m.length + 1 digits + $result = $this->_subtract($result, false, $temp[MATH_BIGINTEGER_VALUE], $temp[MATH_BIGINTEGER_SIGN]); + while ($this->_compare($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $n, false) > 0) { + $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], $result[MATH_BIGINTEGER_SIGN], $n, false); + } + + return $result[MATH_BIGINTEGER_VALUE]; + } + + /** + * Performs long multiplication up to $stop digits + * + * If you're going to be doing array_slice($product->value, 0, $stop), some cycles can be saved. + * + * @see self::_regularBarrett() + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @param int $stop + * @return array + * @access private + */ + function _multiplyLower($x_value, $x_negative, $y_value, $y_negative, $stop) + { + $x_length = count($x_value); + $y_length = count($y_value); + + if (!$x_length || !$y_length) { // a 0 is being multiplied + return array( + MATH_BIGINTEGER_VALUE => array(), + MATH_BIGINTEGER_SIGN => false + ); + } + + if ($x_length < $y_length) { + $temp = $x_value; + $x_value = $y_value; + $y_value = $temp; + + $x_length = count($x_value); + $y_length = count($y_value); + } + + $product_value = $this->_array_repeat(0, $x_length + $y_length); + + // the following for loop could be removed if the for loop following it + // (the one with nested for loops) initially set $i to 0, but + // doing so would also make the result in one set of unnecessary adds, + // since on the outermost loops first pass, $product->value[$k] is going + // to always be 0 + + $carry = 0; + + for ($j = 0; $j < $x_length; ++$j) { // ie. $i = 0, $k = $i + $temp = $x_value[$j] * $y_value[0] + $carry; // $product_value[$k] == 0 + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $product_value[$j] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + } + + if ($j < $stop) { + $product_value[$j] = $carry; + } + + // the above for loop is what the previous comment was talking about. the + // following for loop is the "one with nested for loops" + + for ($i = 1; $i < $y_length; ++$i) { + $carry = 0; + + for ($j = 0, $k = $i; $j < $x_length && $k < $stop; ++$j, ++$k) { + $temp = $product_value[$k] + $x_value[$j] * $y_value[$i] + $carry; + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $product_value[$k] = (int) ($temp - MATH_BIGINTEGER_BASE_FULL * $carry); + } + + if ($k < $stop) { + $product_value[$k] = $carry; + } + } + + return array( + MATH_BIGINTEGER_VALUE => $this->_trim($product_value), + MATH_BIGINTEGER_SIGN => $x_negative != $y_negative + ); + } + + /** + * Montgomery Modular Reduction + * + * ($x->_prepMontgomery($n))->_montgomery($n) yields $x % $n. + * {@link http://math.libtomcrypt.com/files/tommath.pdf#page=170 MPM 6.3} provides insights on how this can be + * improved upon (basically, by using the comba method). gcd($n, 2) must be equal to one for this function + * to work correctly. + * + * @see self::_prepMontgomery() + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @return array + */ + function _montgomery($x, $n) + { + static $cache = array( + MATH_BIGINTEGER_VARIABLE => array(), + MATH_BIGINTEGER_DATA => array() + ); + + if (($key = array_search($n, $cache[MATH_BIGINTEGER_VARIABLE])) === false) { + $key = count($cache[MATH_BIGINTEGER_VARIABLE]); + $cache[MATH_BIGINTEGER_VARIABLE][] = $x; + $cache[MATH_BIGINTEGER_DATA][] = $this->_modInverse67108864($n); + } + + $k = count($n); + + $result = array(MATH_BIGINTEGER_VALUE => $x); + + for ($i = 0; $i < $k; ++$i) { + $temp = $result[MATH_BIGINTEGER_VALUE][$i] * $cache[MATH_BIGINTEGER_DATA][$key]; + $temp = $temp - MATH_BIGINTEGER_BASE_FULL * (MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); + $temp = $this->_regularMultiply(array($temp), $n); + $temp = array_merge($this->_array_repeat(0, $i), $temp); + $result = $this->_add($result[MATH_BIGINTEGER_VALUE], false, $temp, false); + } + + $result[MATH_BIGINTEGER_VALUE] = array_slice($result[MATH_BIGINTEGER_VALUE], $k); + + if ($this->_compare($result, false, $n, false) >= 0) { + $result = $this->_subtract($result[MATH_BIGINTEGER_VALUE], false, $n, false); + } + + return $result[MATH_BIGINTEGER_VALUE]; + } + + /** + * Montgomery Multiply + * + * Interleaves the montgomery reduction and long multiplication algorithms together as described in + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=13 HAC 14.36} + * + * @see self::_prepMontgomery() + * @see self::_montgomery() + * @access private + * @param array $x + * @param array $y + * @param array $m + * @return array + */ + function _montgomeryMultiply($x, $y, $m) + { + $temp = $this->_multiply($x, false, $y, false); + return $this->_montgomery($temp[MATH_BIGINTEGER_VALUE], $m); + + // the following code, although not callable, can be run independently of the above code + // although the above code performed better in my benchmarks the following could might + // perform better under different circumstances. in lieu of deleting it it's just been + // made uncallable + + static $cache = array( + MATH_BIGINTEGER_VARIABLE => array(), + MATH_BIGINTEGER_DATA => array() + ); + + if (($key = array_search($m, $cache[MATH_BIGINTEGER_VARIABLE])) === false) { + $key = count($cache[MATH_BIGINTEGER_VARIABLE]); + $cache[MATH_BIGINTEGER_VARIABLE][] = $m; + $cache[MATH_BIGINTEGER_DATA][] = $this->_modInverse67108864($m); + } + + $n = max(count($x), count($y), count($m)); + $x = array_pad($x, $n, 0); + $y = array_pad($y, $n, 0); + $m = array_pad($m, $n, 0); + $a = array(MATH_BIGINTEGER_VALUE => $this->_array_repeat(0, $n + 1)); + for ($i = 0; $i < $n; ++$i) { + $temp = $a[MATH_BIGINTEGER_VALUE][0] + $x[$i] * $y[0]; + $temp = $temp - MATH_BIGINTEGER_BASE_FULL * (MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); + $temp = $temp * $cache[MATH_BIGINTEGER_DATA][$key]; + $temp = $temp - MATH_BIGINTEGER_BASE_FULL * (MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31)); + $temp = $this->_add($this->_regularMultiply(array($x[$i]), $y), false, $this->_regularMultiply(array($temp), $m), false); + $a = $this->_add($a[MATH_BIGINTEGER_VALUE], false, $temp[MATH_BIGINTEGER_VALUE], false); + $a[MATH_BIGINTEGER_VALUE] = array_slice($a[MATH_BIGINTEGER_VALUE], 1); + } + if ($this->_compare($a[MATH_BIGINTEGER_VALUE], false, $m, false) >= 0) { + $a = $this->_subtract($a[MATH_BIGINTEGER_VALUE], false, $m, false); + } + return $a[MATH_BIGINTEGER_VALUE]; + } + + /** + * Prepare a number for use in Montgomery Modular Reductions + * + * @see self::_montgomery() + * @see self::_slidingWindow() + * @access private + * @param array $x + * @param array $n + * @return array + */ + function _prepMontgomery($x, $n) + { + $lhs = new Math_BigInteger(); + $lhs->value = array_merge($this->_array_repeat(0, count($n)), $x); + $rhs = new Math_BigInteger(); + $rhs->value = $n; + + list(, $temp) = $lhs->divide($rhs); + return $temp->value; + } + + /** + * Modular Inverse of a number mod 2**26 (eg. 67108864) + * + * Based off of the bnpInvDigit function implemented and justified in the following URL: + * + * {@link http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js} + * + * The following URL provides more info: + * + * {@link http://groups.google.com/group/sci.crypt/msg/7a137205c1be7d85} + * + * As for why we do all the bitmasking... strange things can happen when converting from floats to ints. For + * instance, on some computers, var_dump((int) -4294967297) yields int(-1) and on others, it yields + * int(-2147483648). To avoid problems stemming from this, we use bitmasks to guarantee that ints aren't + * auto-converted to floats. The outermost bitmask is present because without it, there's no guarantee that + * the "residue" returned would be the so-called "common residue". We use fmod, in the last step, because the + * maximum possible $x is 26 bits and the maximum $result is 16 bits. Thus, we have to be able to handle up to + * 40 bits, which only 64-bit floating points will support. + * + * Thanks to Pedro Gimeno Fortea for input! + * + * @see self::_montgomery() + * @access private + * @param array $x + * @return int + */ + function _modInverse67108864($x) // 2**26 == 67,108,864 + { + $x = -$x[0]; + $result = $x & 0x3; // x**-1 mod 2**2 + $result = ($result * (2 - $x * $result)) & 0xF; // x**-1 mod 2**4 + $result = ($result * (2 - ($x & 0xFF) * $result)) & 0xFF; // x**-1 mod 2**8 + $result = ($result * ((2 - ($x & 0xFFFF) * $result) & 0xFFFF)) & 0xFFFF; // x**-1 mod 2**16 + $result = fmod($result * (2 - fmod($x * $result, MATH_BIGINTEGER_BASE_FULL)), MATH_BIGINTEGER_BASE_FULL); // x**-1 mod 2**26 + return $result & MATH_BIGINTEGER_MAX_DIGIT; + } + + /** + * Calculates modular inverses. + * + * Say you have (30 mod 17 * x mod 17) mod 17 == 1. x can be found using modular inverses. + * + * Here's an example: + * + * modInverse($b); + * echo $c->toString(); // outputs 4 + * + * echo "\r\n"; + * + * $d = $a->multiply($c); + * list(, $d) = $d->divide($b); + * echo $d; // outputs 1 (as per the definition of modular inverse) + * ?> + * + * + * @param Math_BigInteger $n + * @return Math_BigInteger|false + * @access public + * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=21 HAC 14.64} for more information. + */ + function modInverse($n) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_invert($this->value, $n->value); + + return ($temp->value === false) ? false : $this->_normalize($temp); + } + + static $zero, $one; + if (!isset($zero)) { + $zero = new Math_BigInteger(); + $one = new Math_BigInteger(1); + } + + // $x mod -$n == $x mod $n. + $n = $n->abs(); + + if ($this->compare($zero) < 0) { + $temp = $this->abs(); + $temp = $temp->modInverse($n); + return $this->_normalize($n->subtract($temp)); + } + + extract($this->extendedGCD($n)); + + if (!$gcd->equals($one)) { + return false; + } + + $x = $x->compare($zero) < 0 ? $x->add($n) : $x; + + return $this->compare($zero) < 0 ? $this->_normalize($n->subtract($x)) : $this->_normalize($x); + } + + /** + * Calculates the greatest common divisor and Bezout's identity. + * + * Say you have 693 and 609. The GCD is 21. Bezout's identity states that there exist integers x and y such that + * 693*x + 609*y == 21. In point of fact, there are actually an infinite number of x and y combinations and which + * combination is returned is dependent upon which mode is in use. See + * {@link http://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity Bezout's identity - Wikipedia} for more information. + * + * Here's an example: + * + * extendedGCD($b)); + * + * echo $gcd->toString() . "\r\n"; // outputs 21 + * echo $a->toString() * $x->toString() + $b->toString() * $y->toString(); // outputs 21 + * ?> + * + * + * @param Math_BigInteger $n + * @return Math_BigInteger + * @access public + * @internal Calculates the GCD using the binary xGCD algorithim described in + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf#page=19 HAC 14.61}. As the text above 14.61 notes, + * the more traditional algorithim requires "relatively costly multiple-precision divisions". + */ + function extendedGCD($n) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + extract(gmp_gcdext($this->value, $n->value)); + + return array( + 'gcd' => $this->_normalize(new Math_BigInteger($g)), + 'x' => $this->_normalize(new Math_BigInteger($s)), + 'y' => $this->_normalize(new Math_BigInteger($t)) + ); + case MATH_BIGINTEGER_MODE_BCMATH: + // it might be faster to use the binary xGCD algorithim here, as well, but (1) that algorithim works + // best when the base is a power of 2 and (2) i don't think it'd make much difference, anyway. as is, + // the basic extended euclidean algorithim is what we're using. + + $u = $this->value; + $v = $n->value; + + $a = '1'; + $b = '0'; + $c = '0'; + $d = '1'; + + while (bccomp($v, '0', 0) != 0) { + $q = bcdiv($u, $v, 0); + + $temp = $u; + $u = $v; + $v = bcsub($temp, bcmul($v, $q, 0), 0); + + $temp = $a; + $a = $c; + $c = bcsub($temp, bcmul($a, $q, 0), 0); + + $temp = $b; + $b = $d; + $d = bcsub($temp, bcmul($b, $q, 0), 0); + } + + return array( + 'gcd' => $this->_normalize(new Math_BigInteger($u)), + 'x' => $this->_normalize(new Math_BigInteger($a)), + 'y' => $this->_normalize(new Math_BigInteger($b)) + ); + } + + $y = $n->copy(); + $x = $this->copy(); + $g = new Math_BigInteger(); + $g->value = array(1); + + while (!(($x->value[0] & 1)|| ($y->value[0] & 1))) { + $x->_rshift(1); + $y->_rshift(1); + $g->_lshift(1); + } + + $u = $x->copy(); + $v = $y->copy(); + + $a = new Math_BigInteger(); + $b = new Math_BigInteger(); + $c = new Math_BigInteger(); + $d = new Math_BigInteger(); + + $a->value = $d->value = $g->value = array(1); + $b->value = $c->value = array(); + + while (!empty($u->value)) { + while (!($u->value[0] & 1)) { + $u->_rshift(1); + if ((!empty($a->value) && ($a->value[0] & 1)) || (!empty($b->value) && ($b->value[0] & 1))) { + $a = $a->add($y); + $b = $b->subtract($x); + } + $a->_rshift(1); + $b->_rshift(1); + } + + while (!($v->value[0] & 1)) { + $v->_rshift(1); + if ((!empty($d->value) && ($d->value[0] & 1)) || (!empty($c->value) && ($c->value[0] & 1))) { + $c = $c->add($y); + $d = $d->subtract($x); + } + $c->_rshift(1); + $d->_rshift(1); + } + + if ($u->compare($v) >= 0) { + $u = $u->subtract($v); + $a = $a->subtract($c); + $b = $b->subtract($d); + } else { + $v = $v->subtract($u); + $c = $c->subtract($a); + $d = $d->subtract($b); + } + } + + return array( + 'gcd' => $this->_normalize($g->multiply($v)), + 'x' => $this->_normalize($c), + 'y' => $this->_normalize($d) + ); + } + + /** + * Calculates the greatest common divisor + * + * Say you have 693 and 609. The GCD is 21. + * + * Here's an example: + * + * extendedGCD($b); + * + * echo $gcd->toString() . "\r\n"; // outputs 21 + * ?> + * + * + * @param Math_BigInteger $n + * @return Math_BigInteger + * @access public + */ + function gcd($n) + { + extract($this->extendedGCD($n)); + return $gcd; + } + + /** + * Absolute value. + * + * @return Math_BigInteger + * @access public + */ + function abs() + { + $temp = new Math_BigInteger(); + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp->value = gmp_abs($this->value); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp->value = (bccomp($this->value, '0', 0) < 0) ? substr($this->value, 1) : $this->value; + break; + default: + $temp->value = $this->value; + } + + return $temp; + } + + /** + * Compares two numbers. + * + * Although one might think !$x->compare($y) means $x != $y, it, in fact, means the opposite. The reason for this is + * demonstrated thusly: + * + * $x > $y: $x->compare($y) > 0 + * $x < $y: $x->compare($y) < 0 + * $x == $y: $x->compare($y) == 0 + * + * Note how the same comparison operator is used. If you want to test for equality, use $x->equals($y). + * + * @param Math_BigInteger $y + * @return int < 0 if $this is less than $y; > 0 if $this is greater than $y, and 0 if they are equal. + * @access public + * @see self::equals() + * @internal Could return $this->subtract($x), but that's not as fast as what we do do. + */ + function compare($y) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_cmp($this->value, $y->value); + case MATH_BIGINTEGER_MODE_BCMATH: + return bccomp($this->value, $y->value, 0); + } + + return $this->_compare($this->value, $this->is_negative, $y->value, $y->is_negative); + } + + /** + * Compares two numbers. + * + * @param array $x_value + * @param bool $x_negative + * @param array $y_value + * @param bool $y_negative + * @return int + * @see self::compare() + * @access private + */ + function _compare($x_value, $x_negative, $y_value, $y_negative) + { + if ($x_negative != $y_negative) { + return (!$x_negative && $y_negative) ? 1 : -1; + } + + $result = $x_negative ? -1 : 1; + + if (count($x_value) != count($y_value)) { + return (count($x_value) > count($y_value)) ? $result : -$result; + } + $size = max(count($x_value), count($y_value)); + + $x_value = array_pad($x_value, $size, 0); + $y_value = array_pad($y_value, $size, 0); + + for ($i = count($x_value) - 1; $i >= 0; --$i) { + if ($x_value[$i] != $y_value[$i]) { + return ($x_value[$i] > $y_value[$i]) ? $result : -$result; + } + } + + return 0; + } + + /** + * Tests the equality of two numbers. + * + * If you need to see if one number is greater than or less than another number, use Math_BigInteger::compare() + * + * @param Math_BigInteger $x + * @return bool + * @access public + * @see self::compare() + */ + function equals($x) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_cmp($this->value, $x->value) == 0; + default: + return $this->value === $x->value && $this->is_negative == $x->is_negative; + } + } + + /** + * Set Precision + * + * Some bitwise operations give different results depending on the precision being used. Examples include left + * shift, not, and rotates. + * + * @param int $bits + * @access public + */ + function setPrecision($bits) + { + $this->precision = $bits; + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_BCMATH) { + $this->bitmask = new Math_BigInteger(chr((1 << ($bits & 0x7)) - 1) . str_repeat(chr(0xFF), $bits >> 3), 256); + } else { + $this->bitmask = new Math_BigInteger(bcpow('2', $bits, 0)); + } + + $temp = $this->_normalize($this); + $this->value = $temp->value; + } + + /** + * Logical And + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_and($x) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_and($this->value, $x->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $left = $this->toBytes(); + $right = $x->toBytes(); + + $length = max(strlen($left), strlen($right)); + + $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); + $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); + + return $this->_normalize(new Math_BigInteger($left & $right, 256)); + } + + $result = $this->copy(); + + $length = min(count($x->value), count($this->value)); + + $result->value = array_slice($result->value, 0, $length); + + for ($i = 0; $i < $length; ++$i) { + $result->value[$i]&= $x->value[$i]; + } + + return $this->_normalize($result); + } + + /** + * Logical Or + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_or($x) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_or($this->value, $x->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $left = $this->toBytes(); + $right = $x->toBytes(); + + $length = max(strlen($left), strlen($right)); + + $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); + $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); + + return $this->_normalize(new Math_BigInteger($left | $right, 256)); + } + + $length = max(count($this->value), count($x->value)); + $result = $this->copy(); + $result->value = array_pad($result->value, $length, 0); + $x->value = array_pad($x->value, $length, 0); + + for ($i = 0; $i < $length; ++$i) { + $result->value[$i]|= $x->value[$i]; + } + + return $this->_normalize($result); + } + + /** + * Logical Exclusive-Or + * + * @param Math_BigInteger $x + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_xor($x) + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + $temp = new Math_BigInteger(); + $temp->value = gmp_xor($this->value, $x->value); + + return $this->_normalize($temp); + case MATH_BIGINTEGER_MODE_BCMATH: + $left = $this->toBytes(); + $right = $x->toBytes(); + + $length = max(strlen($left), strlen($right)); + + $left = str_pad($left, $length, chr(0), STR_PAD_LEFT); + $right = str_pad($right, $length, chr(0), STR_PAD_LEFT); + + return $this->_normalize(new Math_BigInteger($left ^ $right, 256)); + } + + $length = max(count($this->value), count($x->value)); + $result = $this->copy(); + $result->value = array_pad($result->value, $length, 0); + $x->value = array_pad($x->value, $length, 0); + + for ($i = 0; $i < $length; ++$i) { + $result->value[$i]^= $x->value[$i]; + } + + return $this->_normalize($result); + } + + /** + * Logical Not + * + * @access public + * @internal Implemented per a request by Lluis Pamies i Juarez + * @return Math_BigInteger + */ + function bitwise_not() + { + // calculuate "not" without regard to $this->precision + // (will always result in a smaller number. ie. ~1 isn't 1111 1110 - it's 0) + $temp = $this->toBytes(); + if ($temp == '') { + return $this->_normalize(new Math_BigInteger()); + } + $pre_msb = decbin(ord($temp[0])); + $temp = ~$temp; + $msb = decbin(ord($temp[0])); + if (strlen($msb) == 8) { + $msb = substr($msb, strpos($msb, '0')); + } + $temp[0] = chr(bindec($msb)); + + // see if we need to add extra leading 1's + $current_bits = strlen($pre_msb) + 8 * strlen($temp) - 8; + $new_bits = $this->precision - $current_bits; + if ($new_bits <= 0) { + return $this->_normalize(new Math_BigInteger($temp, 256)); + } + + // generate as many leading 1's as we need to. + $leading_ones = chr((1 << ($new_bits & 0x7)) - 1) . str_repeat(chr(0xFF), $new_bits >> 3); + $this->_base256_lshift($leading_ones, $current_bits); + + $temp = str_pad($temp, strlen($leading_ones), chr(0), STR_PAD_LEFT); + + return $this->_normalize(new Math_BigInteger($leading_ones | $temp, 256)); + } + + /** + * Logical Right Shift + * + * Shifts BigInteger's by $shift bits, effectively dividing by 2**$shift. + * + * @param int $shift + * @return Math_BigInteger + * @access public + * @internal The only version that yields any speed increases is the internal version. + */ + function bitwise_rightShift($shift) + { + $temp = new Math_BigInteger(); + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + static $two; + + if (!isset($two)) { + $two = gmp_init('2'); + } + + $temp->value = gmp_div_q($this->value, gmp_pow($two, $shift)); + + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp->value = bcdiv($this->value, bcpow('2', $shift, 0), 0); + + break; + default: // could just replace _lshift with this, but then all _lshift() calls would need to be rewritten + // and I don't want to do that... + $temp->value = $this->value; + $temp->_rshift($shift); + } + + return $this->_normalize($temp); + } + + /** + * Logical Left Shift + * + * Shifts BigInteger's by $shift bits, effectively multiplying by 2**$shift. + * + * @param int $shift + * @return Math_BigInteger + * @access public + * @internal The only version that yields any speed increases is the internal version. + */ + function bitwise_leftShift($shift) + { + $temp = new Math_BigInteger(); + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + static $two; + + if (!isset($two)) { + $two = gmp_init('2'); + } + + $temp->value = gmp_mul($this->value, gmp_pow($two, $shift)); + + break; + case MATH_BIGINTEGER_MODE_BCMATH: + $temp->value = bcmul($this->value, bcpow('2', $shift, 0), 0); + + break; + default: // could just replace _rshift with this, but then all _lshift() calls would need to be rewritten + // and I don't want to do that... + $temp->value = $this->value; + $temp->_lshift($shift); + } + + return $this->_normalize($temp); + } + + /** + * Logical Left Rotate + * + * Instead of the top x bits being dropped they're appended to the shifted bit string. + * + * @param int $shift + * @return Math_BigInteger + * @access public + */ + function bitwise_leftRotate($shift) + { + $bits = $this->toBytes(); + + if ($this->precision > 0) { + $precision = $this->precision; + if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH) { + $mask = $this->bitmask->subtract(new Math_BigInteger(1)); + $mask = $mask->toBytes(); + } else { + $mask = $this->bitmask->toBytes(); + } + } else { + $temp = ord($bits[0]); + for ($i = 0; $temp >> $i; ++$i) { + } + $precision = 8 * strlen($bits) - 8 + $i; + $mask = chr((1 << ($precision & 0x7)) - 1) . str_repeat(chr(0xFF), $precision >> 3); + } + + if ($shift < 0) { + $shift+= $precision; + } + $shift%= $precision; + + if (!$shift) { + return $this->copy(); + } + + $left = $this->bitwise_leftShift($shift); + $left = $left->bitwise_and(new Math_BigInteger($mask, 256)); + $right = $this->bitwise_rightShift($precision - $shift); + $result = MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_BCMATH ? $left->bitwise_or($right) : $left->add($right); + return $this->_normalize($result); + } + + /** + * Logical Right Rotate + * + * Instead of the bottom x bits being dropped they're prepended to the shifted bit string. + * + * @param int $shift + * @return Math_BigInteger + * @access public + */ + function bitwise_rightRotate($shift) + { + return $this->bitwise_leftRotate(-$shift); + } + + /** + * Set random number generator function + * + * This function is deprecated. + * + * @param string $generator + * @access public + */ + function setRandomGenerator($generator) + { + } + + /** + * Generates a random BigInteger + * + * Byte length is equal to $length. Uses crypt_random if it's loaded and mt_rand if it's not. + * + * @param int $length + * @return Math_BigInteger + * @access private + */ + function _random_number_helper($size) + { + if (function_exists('crypt_random_string')) { + $random = crypt_random_string($size); + } else { + $random = ''; + + if ($size & 1) { + $random.= chr(mt_rand(0, 255)); + } + + $blocks = $size >> 1; + for ($i = 0; $i < $blocks; ++$i) { + // mt_rand(-2147483648, 0x7FFFFFFF) always produces -2147483648 on some systems + $random.= pack('n', mt_rand(0, 0xFFFF)); + } + } + + return new Math_BigInteger($random, 256); + } + + /** + * Generate a random number + * + * Returns a random number between $min and $max where $min and $max + * can be defined using one of the two methods: + * + * $min->random($max) + * $max->random($min) + * + * @param Math_BigInteger $arg1 + * @param Math_BigInteger $arg2 + * @return Math_BigInteger + * @access public + * @internal The API for creating random numbers used to be $a->random($min, $max), where $a was a Math_BigInteger object. + * That method is still supported for BC purposes. + */ + function random($arg1, $arg2 = false) + { + if ($arg1 === false) { + return false; + } + + if ($arg2 === false) { + $max = $arg1; + $min = $this; + } else { + $min = $arg1; + $max = $arg2; + } + + $compare = $max->compare($min); + + if (!$compare) { + return $this->_normalize($min); + } elseif ($compare < 0) { + // if $min is bigger then $max, swap $min and $max + $temp = $max; + $max = $min; + $min = $temp; + } + + static $one; + if (!isset($one)) { + $one = new Math_BigInteger(1); + } + + $max = $max->subtract($min->subtract($one)); + $size = strlen(ltrim($max->toBytes(), chr(0))); + + /* + doing $random % $max doesn't work because some numbers will be more likely to occur than others. + eg. if $max is 140 and $random's max is 255 then that'd mean both $random = 5 and $random = 145 + would produce 5 whereas the only value of random that could produce 139 would be 139. ie. + not all numbers would be equally likely. some would be more likely than others. + + creating a whole new random number until you find one that is within the range doesn't work + because, for sufficiently small ranges, the likelihood that you'd get a number within that range + would be pretty small. eg. with $random's max being 255 and if your $max being 1 the probability + would be pretty high that $random would be greater than $max. + + phpseclib works around this using the technique described here: + + http://crypto.stackexchange.com/questions/5708/creating-a-small-number-from-a-cryptographically-secure-random-string + */ + $random_max = new Math_BigInteger(chr(1) . str_repeat("\0", $size), 256); + $random = $this->_random_number_helper($size); + + list($max_multiple) = $random_max->divide($max); + $max_multiple = $max_multiple->multiply($max); + + while ($random->compare($max_multiple) >= 0) { + $random = $random->subtract($max_multiple); + $random_max = $random_max->subtract($max_multiple); + $random = $random->bitwise_leftShift(8); + $random = $random->add($this->_random_number_helper(1)); + $random_max = $random_max->bitwise_leftShift(8); + list($max_multiple) = $random_max->divide($max); + $max_multiple = $max_multiple->multiply($max); + } + list(, $random) = $random->divide($max); + + return $this->_normalize($random->add($min)); + } + + /** + * Generate a random prime number. + * + * If there's not a prime within the given range, false will be returned. + * If more than $timeout seconds have elapsed, give up and return false. + * + * @param Math_BigInteger $arg1 + * @param Math_BigInteger $arg2 + * @param int $timeout + * @return Math_BigInteger|false + * @access public + * @internal See {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=15 HAC 4.44}. + */ + function randomPrime($arg1, $arg2 = false, $timeout = false) + { + if ($arg1 === false) { + return false; + } + + if ($arg2 === false) { + $max = $arg1; + $min = $this; + } else { + $min = $arg1; + $max = $arg2; + } + + $compare = $max->compare($min); + + if (!$compare) { + return $min->isPrime() ? $min : false; + } elseif ($compare < 0) { + // if $min is bigger then $max, swap $min and $max + $temp = $max; + $max = $min; + $min = $temp; + } + + static $one, $two; + if (!isset($one)) { + $one = new Math_BigInteger(1); + $two = new Math_BigInteger(2); + } + + $start = time(); + + $x = $this->random($min, $max); + + // gmp_nextprime() requires PHP 5 >= 5.2.0 per . + if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_GMP && extension_loaded('gmp') && version_compare(PHP_VERSION, '5.2.0', '>=')) { + $p = new Math_BigInteger(); + $p->value = gmp_nextprime($x->value); + + if ($p->compare($max) <= 0) { + return $p; + } + + if (!$min->equals($x)) { + $x = $x->subtract($one); + } + + return $x->randomPrime($min, $x); + } + + if ($x->equals($two)) { + return $x; + } + + $x->_make_odd(); + if ($x->compare($max) > 0) { + // if $x > $max then $max is even and if $min == $max then no prime number exists between the specified range + if ($min->equals($max)) { + return false; + } + $x = $min->copy(); + $x->_make_odd(); + } + + $initial_x = $x->copy(); + + while (true) { + if ($timeout !== false && time() - $start > $timeout) { + return false; + } + + if ($x->isPrime()) { + return $x; + } + + $x = $x->add($two); + + if ($x->compare($max) > 0) { + $x = $min->copy(); + if ($x->equals($two)) { + return $x; + } + $x->_make_odd(); + } + + if ($x->equals($initial_x)) { + return false; + } + } + } + + /** + * Make the current number odd + * + * If the current number is odd it'll be unchanged. If it's even, one will be added to it. + * + * @see self::randomPrime() + * @access private + */ + function _make_odd() + { + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + gmp_setbit($this->value, 0); + break; + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value[strlen($this->value) - 1] % 2 == 0) { + $this->value = bcadd($this->value, '1'); + } + break; + default: + $this->value[0] |= 1; + } + } + + /** + * Checks a numer to see if it's prime + * + * Assuming the $t parameter is not set, this function has an error rate of 2**-80. The main motivation for the + * $t parameter is distributability. Math_BigInteger::randomPrime() can be distributed across multiple pageloads + * on a website instead of just one. + * + * @param Math_BigInteger $t + * @return bool + * @access public + * @internal Uses the + * {@link http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test Miller-Rabin primality test}. See + * {@link http://www.cacr.math.uwaterloo.ca/hac/about/chap4.pdf#page=8 HAC 4.24}. + */ + function isPrime($t = false) + { + $length = strlen($this->toBytes()); + + if (!$t) { + // see HAC 4.49 "Note (controlling the error probability)" + // @codingStandardsIgnoreStart + if ($length >= 163) { $t = 2; } // floor(1300 / 8) + else if ($length >= 106) { $t = 3; } // floor( 850 / 8) + else if ($length >= 81 ) { $t = 4; } // floor( 650 / 8) + else if ($length >= 68 ) { $t = 5; } // floor( 550 / 8) + else if ($length >= 56 ) { $t = 6; } // floor( 450 / 8) + else if ($length >= 50 ) { $t = 7; } // floor( 400 / 8) + else if ($length >= 43 ) { $t = 8; } // floor( 350 / 8) + else if ($length >= 37 ) { $t = 9; } // floor( 300 / 8) + else if ($length >= 31 ) { $t = 12; } // floor( 250 / 8) + else if ($length >= 25 ) { $t = 15; } // floor( 200 / 8) + else if ($length >= 18 ) { $t = 18; } // floor( 150 / 8) + else { $t = 27; } + // @codingStandardsIgnoreEnd + } + + // ie. gmp_testbit($this, 0) + // ie. isEven() or !isOdd() + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + return gmp_prob_prime($this->value, $t) != 0; + case MATH_BIGINTEGER_MODE_BCMATH: + if ($this->value === '2') { + return true; + } + if ($this->value[strlen($this->value) - 1] % 2 == 0) { + return false; + } + break; + default: + if ($this->value == array(2)) { + return true; + } + if (~$this->value[0] & 1) { + return false; + } + } + + static $primes, $zero, $one, $two; + + if (!isset($primes)) { + $primes = array( + 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, + 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, + 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, + 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, + 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, + 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, + 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, + 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, 709, 719, 727, + 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, 821, 823, 827, 829, + 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, + 953, 967, 971, 977, 983, 991, 997 + ); + + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) { + for ($i = 0; $i < count($primes); ++$i) { + $primes[$i] = new Math_BigInteger($primes[$i]); + } + } + + $zero = new Math_BigInteger(); + $one = new Math_BigInteger(1); + $two = new Math_BigInteger(2); + } + + if ($this->equals($one)) { + return false; + } + + // see HAC 4.4.1 "Random search for probable primes" + if (MATH_BIGINTEGER_MODE != MATH_BIGINTEGER_MODE_INTERNAL) { + foreach ($primes as $prime) { + list(, $r) = $this->divide($prime); + if ($r->equals($zero)) { + return $this->equals($prime); + } + } + } else { + $value = $this->value; + foreach ($primes as $prime) { + list(, $r) = $this->_divide_digit($value, $prime); + if (!$r) { + return count($value) == 1 && $value[0] == $prime; + } + } + } + + $n = $this->copy(); + $n_1 = $n->subtract($one); + $n_2 = $n->subtract($two); + + $r = $n_1->copy(); + $r_value = $r->value; + // ie. $s = gmp_scan1($n, 0) and $r = gmp_div_q($n, gmp_pow(gmp_init('2'), $s)); + if (MATH_BIGINTEGER_MODE == MATH_BIGINTEGER_MODE_BCMATH) { + $s = 0; + // if $n was 1, $r would be 0 and this would be an infinite loop, hence our $this->equals($one) check earlier + while ($r->value[strlen($r->value) - 1] % 2 == 0) { + $r->value = bcdiv($r->value, '2', 0); + ++$s; + } + } else { + for ($i = 0, $r_length = count($r_value); $i < $r_length; ++$i) { + $temp = ~$r_value[$i] & 0xFFFFFF; + for ($j = 1; ($temp >> $j) & 1; ++$j) { + } + if ($j != 25) { + break; + } + } + $s = 26 * $i + $j; + $r->_rshift($s); + } + + for ($i = 0; $i < $t; ++$i) { + $a = $this->random($two, $n_2); + $y = $a->modPow($r, $n); + + if (!$y->equals($one) && !$y->equals($n_1)) { + for ($j = 1; $j < $s && !$y->equals($n_1); ++$j) { + $y = $y->modPow($two, $n); + if ($y->equals($one)) { + return false; + } + } + + if (!$y->equals($n_1)) { + return false; + } + } + } + return true; + } + + /** + * Logical Left Shift + * + * Shifts BigInteger's by $shift bits. + * + * @param int $shift + * @access private + */ + function _lshift($shift) + { + if ($shift == 0) { + return; + } + + $num_digits = (int) ($shift / MATH_BIGINTEGER_BASE); + $shift %= MATH_BIGINTEGER_BASE; + $shift = 1 << $shift; + + $carry = 0; + + for ($i = 0; $i < count($this->value); ++$i) { + $temp = $this->value[$i] * $shift + $carry; + $carry = MATH_BIGINTEGER_BASE === 26 ? intval($temp / 0x4000000) : ($temp >> 31); + $this->value[$i] = (int) ($temp - $carry * MATH_BIGINTEGER_BASE_FULL); + } + + if ($carry) { + $this->value[count($this->value)] = $carry; + } + + while ($num_digits--) { + array_unshift($this->value, 0); + } + } + + /** + * Logical Right Shift + * + * Shifts BigInteger's by $shift bits. + * + * @param int $shift + * @access private + */ + function _rshift($shift) + { + if ($shift == 0) { + return; + } + + $num_digits = (int) ($shift / MATH_BIGINTEGER_BASE); + $shift %= MATH_BIGINTEGER_BASE; + $carry_shift = MATH_BIGINTEGER_BASE - $shift; + $carry_mask = (1 << $shift) - 1; + + if ($num_digits) { + $this->value = array_slice($this->value, $num_digits); + } + + $carry = 0; + + for ($i = count($this->value) - 1; $i >= 0; --$i) { + $temp = $this->value[$i] >> $shift | $carry; + $carry = ($this->value[$i] & $carry_mask) << $carry_shift; + $this->value[$i] = $temp; + } + + $this->value = $this->_trim($this->value); + } + + /** + * Normalize + * + * Removes leading zeros and truncates (if necessary) to maintain the appropriate precision + * + * @param Math_BigInteger + * @return Math_BigInteger + * @see self::_trim() + * @access private + */ + function _normalize($result) + { + $result->precision = $this->precision; + $result->bitmask = $this->bitmask; + + switch (MATH_BIGINTEGER_MODE) { + case MATH_BIGINTEGER_MODE_GMP: + if ($this->bitmask !== false) { + $result->value = gmp_and($result->value, $result->bitmask->value); + } + + return $result; + case MATH_BIGINTEGER_MODE_BCMATH: + if (!empty($result->bitmask->value)) { + $result->value = bcmod($result->value, $result->bitmask->value); + } + + return $result; + } + + $value = &$result->value; + + if (!count($value)) { + return $result; + } + + $value = $this->_trim($value); + + if (!empty($result->bitmask->value)) { + $length = min(count($value), count($this->bitmask->value)); + $value = array_slice($value, 0, $length); + + for ($i = 0; $i < $length; ++$i) { + $value[$i] = $value[$i] & $this->bitmask->value[$i]; + } + } + + return $result; + } + + /** + * Trim + * + * Removes leading zeros + * + * @param array $value + * @return Math_BigInteger + * @access private + */ + function _trim($value) + { + for ($i = count($value) - 1; $i >= 0; --$i) { + if ($value[$i]) { + break; + } + unset($value[$i]); + } + + return $value; + } + + /** + * Array Repeat + * + * @param $input Array + * @param $multiplier mixed + * @return array + * @access private + */ + function _array_repeat($input, $multiplier) + { + return ($multiplier) ? array_fill(0, $multiplier, $input) : array(); + } + + /** + * Logical Left Shift + * + * Shifts binary strings $shift bits, essentially multiplying by 2**$shift. + * + * @param $x String + * @param $shift Integer + * @return string + * @access private + */ + function _base256_lshift(&$x, $shift) + { + if ($shift == 0) { + return; + } + + $num_bytes = $shift >> 3; // eg. floor($shift/8) + $shift &= 7; // eg. $shift % 8 + + $carry = 0; + for ($i = strlen($x) - 1; $i >= 0; --$i) { + $temp = ord($x[$i]) << $shift | $carry; + $x[$i] = chr($temp); + $carry = $temp >> 8; + } + $carry = ($carry != 0) ? chr($carry) : ''; + $x = $carry . $x . str_repeat(chr(0), $num_bytes); + } + + /** + * Logical Right Shift + * + * Shifts binary strings $shift bits, essentially dividing by 2**$shift and returning the remainder. + * + * @param $x String + * @param $shift Integer + * @return string + * @access private + */ + function _base256_rshift(&$x, $shift) + { + if ($shift == 0) { + $x = ltrim($x, chr(0)); + return ''; + } + + $num_bytes = $shift >> 3; // eg. floor($shift/8) + $shift &= 7; // eg. $shift % 8 + + $remainder = ''; + if ($num_bytes) { + $start = $num_bytes > strlen($x) ? -strlen($x) : -$num_bytes; + $remainder = substr($x, $start); + $x = substr($x, 0, -$num_bytes); + } + + $carry = 0; + $carry_shift = 8 - $shift; + for ($i = 0; $i < strlen($x); ++$i) { + $temp = (ord($x[$i]) >> $shift) | $carry; + $carry = (ord($x[$i]) << $carry_shift) & 0xFF; + $x[$i] = chr($temp); + } + $x = ltrim($x, chr(0)); + + $remainder = chr($carry >> $carry_shift) . $remainder; + + return ltrim($remainder, chr(0)); + } + + // one quirk about how the following functions are implemented is that PHP defines N to be an unsigned long + // at 32-bits, while java's longs are 64-bits. + + /** + * Converts 32-bit integers to bytes. + * + * @param int $x + * @return string + * @access private + */ + function _int2bytes($x) + { + return ltrim(pack('N', $x), chr(0)); + } + + /** + * Converts bytes to 32-bit integers + * + * @param string $x + * @return int + * @access private + */ + function _bytes2int($x) + { + $temp = unpack('Nint', str_pad($x, 4, chr(0), STR_PAD_LEFT)); + return $temp['int']; + } + + /** + * DER-encode an integer + * + * The ability to DER-encode integers is needed to create RSA public keys for use with OpenSSL + * + * @see self::modPow() + * @access private + * @param int $length + * @return string + */ + function _encodeASN1Length($length) + { + if ($length <= 0x7F) { + return chr($length); + } + + $temp = ltrim(pack('N', $length), chr(0)); + return pack('Ca*', 0x80 | strlen($temp), $temp); + } + + /** + * Single digit division + * + * Even if int64 is being used the division operator will return a float64 value + * if the dividend is not evenly divisible by the divisor. Since a float64 doesn't + * have the precision of int64 this is a problem so, when int64 is being used, + * we'll guarantee that the dividend is divisible by first subtracting the remainder. + * + * @access private + * @param int $x + * @param int $y + * @return int + */ + function _safe_divide($x, $y) + { + if (MATH_BIGINTEGER_BASE === 26) { + return (int) ($x / $y); + } + + // MATH_BIGINTEGER_BASE === 31 + return ($x - ($x % $y)) / $y; + } +} diff --git a/ipaylinks_statement/Net/SCP.php b/ipaylinks_statement/Net/SCP.php new file mode 100644 index 00000000..354acea1 --- /dev/null +++ b/ipaylinks_statement/Net/SCP.php @@ -0,0 +1,373 @@ + + * login('username', 'password')) { + * exit('bad login'); + * } + * + * $scp = new Net_SCP($ssh); + * $scp->put('abcd', str_repeat('x', 1024*1024)); + * ?> + * + * + * LICENSE: 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. + * + * @category Net + * @package Net_SCP + * @author Jim Wigginton + * @copyright 2010 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * @access public + * @see self::put() + */ +/** + * Reads data from a local file. + */ +define('NET_SCP_LOCAL_FILE', 1); +/** + * Reads data from a string. + */ +define('NET_SCP_STRING', 2); +/**#@-*/ + +/**#@+ + * @access private + * @see self::_send() + * @see self::_receive() + */ +/** + * SSH1 is being used. + */ +define('NET_SCP_SSH1', 1); +/** + * SSH2 is being used. + */ +define('NET_SCP_SSH2', 2); +/**#@-*/ + +/** + * Pure-PHP implementations of SCP. + * + * @package Net_SCP + * @author Jim Wigginton + * @access public + */ +class Net_SCP +{ + /** + * SSH Object + * + * @var object + * @access private + */ + var $ssh; + + /** + * Packet Size + * + * @var int + * @access private + */ + var $packet_size; + + /** + * Mode + * + * @var int + * @access private + */ + var $mode; + + /** + * Default Constructor. + * + * Connects to an SSH server + * + * @param Net_SSH1|Net_SSH2 $ssh + * @return Net_SCP + * @access public + */ + function __construct($ssh) + { + if (!is_object($ssh)) { + return; + } + + switch (strtolower(get_class($ssh))) { + case 'net_ssh2': + $this->mode = NET_SCP_SSH2; + break; + case 'net_ssh1': + $this->packet_size = 50000; + $this->mode = NET_SCP_SSH1; + break; + default: + return; + } + + $this->ssh = $ssh; + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param Net_SSH1|Net_SSH2 $ssh + * @access public + */ + function Net_SCP($ssh) + { + $this->__construct($ssh); + } + + /** + * Uploads a file to the SCP server. + * + * By default, Net_SCP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. + * So, for example, if you set $data to 'filename.ext' and then do Net_SCP::get(), you will get a file, twelve bytes + * long, containing 'filename.ext' as its contents. + * + * Setting $mode to NET_SCP_LOCAL_FILE will change the above behavior. With NET_SCP_LOCAL_FILE, $remote_file will + * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how + * large $remote_file will be, as well. + * + * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take + * care of that, yourself. + * + * @param string $remote_file + * @param string $data + * @param int $mode + * @param callable $callback + * @return bool + * @access public + */ + function put($remote_file, $data, $mode = NET_SCP_STRING, $callback = null) + { + if (!isset($this->ssh)) { + return false; + } + + if (!$this->ssh->exec('scp -t ' . escapeshellarg($remote_file), false)) { // -t = to + return false; + } + + $temp = $this->_receive(); + if ($temp !== chr(0)) { + return false; + } + + if ($this->mode == NET_SCP_SSH2) { + $this->packet_size = $this->ssh->packet_size_client_to_server[NET_SSH2_CHANNEL_EXEC] - 4; + } + + $remote_file = basename($remote_file); + + if ($mode == NET_SCP_STRING) { + $size = strlen($data); + } else { + if (!is_file($data)) { + user_error("$data is not a valid file", E_USER_NOTICE); + return false; + } + + $fp = @fopen($data, 'rb'); + if (!$fp) { + return false; + } + $size = filesize($data); + } + + $this->_send('C0644 ' . $size . ' ' . $remote_file . "\n"); + + $temp = $this->_receive(); + if ($temp !== chr(0)) { + return false; + } + + $sent = 0; + while ($sent < $size) { + $temp = $mode & NET_SCP_STRING ? substr($data, $sent, $this->packet_size) : fread($fp, $this->packet_size); + $this->_send($temp); + $sent+= strlen($temp); + + if (is_callable($callback)) { + call_user_func($callback, $sent); + } + } + $this->_close(); + + if ($mode != NET_SCP_STRING) { + fclose($fp); + } + + return true; + } + + /** + * Downloads a file from the SCP server. + * + * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if + * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the + * operation + * + * @param string $remote_file + * @param string $local_file + * @return mixed + * @access public + */ + function get($remote_file, $local_file = false) + { + if (!isset($this->ssh)) { + return false; + } + + if (!$this->ssh->exec('scp -f ' . escapeshellarg($remote_file), false)) { // -f = from + return false; + } + + $this->_send("\0"); + + if (!preg_match('#(?[^ ]+) (?\d+) (?.+)#', rtrim($this->_receive()), $info)) { + return false; + } + + $this->_send("\0"); + + $size = 0; + + if ($local_file !== false) { + $fp = @fopen($local_file, 'wb'); + if (!$fp) { + return false; + } + } + + $content = ''; + while ($size < $info['size']) { + $data = $this->_receive(); + // SCP usually seems to split stuff out into 16k chunks + $size+= strlen($data); + + if ($local_file === false) { + $content.= $data; + } else { + fputs($fp, $data); + } + } + + $this->_close(); + + if ($local_file !== false) { + fclose($fp); + return true; + } + + return $content; + } + + /** + * Sends a packet to an SSH server + * + * @param string $data + * @access private + */ + function _send($data) + { + switch ($this->mode) { + case NET_SCP_SSH2: + $this->ssh->_send_channel_packet(NET_SSH2_CHANNEL_EXEC, $data); + break; + case NET_SCP_SSH1: + $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($data), $data); + $this->ssh->_send_binary_packet($data); + } + } + + /** + * Receives a packet from an SSH server + * + * @return string + * @access private + */ + function _receive() + { + switch ($this->mode) { + case NET_SCP_SSH2: + return $this->ssh->_get_channel_packet(NET_SSH2_CHANNEL_EXEC, true); + case NET_SCP_SSH1: + if (!$this->ssh->bitmap) { + return false; + } + while (true) { + $response = $this->ssh->_get_binary_packet(); + switch ($response[NET_SSH1_RESPONSE_TYPE]) { + case NET_SSH1_SMSG_STDOUT_DATA: + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 4) { + return false; + } + extract(unpack('Nlength', $response[NET_SSH1_RESPONSE_DATA])); + return $this->ssh->_string_shift($response[NET_SSH1_RESPONSE_DATA], $length); + case NET_SSH1_SMSG_STDERR_DATA: + break; + case NET_SSH1_SMSG_EXITSTATUS: + $this->ssh->_send_binary_packet(chr(NET_SSH1_CMSG_EXIT_CONFIRMATION)); + fclose($this->ssh->fsock); + $this->ssh->bitmap = 0; + return false; + default: + user_error('Unknown packet received', E_USER_NOTICE); + return false; + } + } + } + } + + /** + * Closes the connection to an SSH server + * + * @access private + */ + function _close() + { + switch ($this->mode) { + case NET_SCP_SSH2: + $this->ssh->_close_channel(NET_SSH2_CHANNEL_EXEC, true); + break; + case NET_SCP_SSH1: + $this->ssh->disconnect(); + } + } +} diff --git a/ipaylinks_statement/Net/SFTP.php b/ipaylinks_statement/Net/SFTP.php new file mode 100644 index 00000000..3f386522 --- /dev/null +++ b/ipaylinks_statement/Net/SFTP.php @@ -0,0 +1,3161 @@ + + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * echo $sftp->pwd() . "\r\n"; + * $sftp->put('filename.ext', 'hello, world!'); + * print_r($sftp->nlist()); + * ?> + * + * + * LICENSE: 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. + * + * @category Net + * @package Net_SFTP + * @author Jim Wigginton + * @copyright 2009 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * Include Net_SSH2 + */ +if (!class_exists('Net_SSH2')) { + include_once 'SSH2.php'; +} + +/**#@+ + * @access public + * @see self::getLog() + */ +/** + * Returns the message numbers + */ +define('NET_SFTP_LOG_SIMPLE', NET_SSH2_LOG_SIMPLE); +/** + * Returns the message content + */ +define('NET_SFTP_LOG_COMPLEX', NET_SSH2_LOG_COMPLEX); +/** + * Outputs the message content in real-time. + */ +define('NET_SFTP_LOG_REALTIME', 3); +/**#@-*/ + +/** + * SFTP channel constant + * + * Net_SSH2::exec() uses 0 and Net_SSH2::read() / Net_SSH2::write() use 1. + * + * @see Net_SSH2::_send_channel_packet() + * @see Net_SSH2::_get_channel_packet() + * @access private + */ +define('NET_SFTP_CHANNEL', 0x100); + +/**#@+ + * @access public + * @see self::put() + */ +/** + * Reads data from a local file. + */ +define('NET_SFTP_LOCAL_FILE', 1); +/** + * Reads data from a string. + */ +// this value isn't really used anymore but i'm keeping it reserved for historical reasons +define('NET_SFTP_STRING', 2); +/** + * Reads data from callback: + * function callback($length) returns string to proceed, null for EOF + */ +define('NET_SFTP_CALLBACK', 16); +/** + * Resumes an upload + */ +define('NET_SFTP_RESUME', 4); +/** + * Append a local file to an already existing remote file + */ +define('NET_SFTP_RESUME_START', 8); +/**#@-*/ + +/** + * Pure-PHP implementations of SFTP. + * + * @package Net_SFTP + * @author Jim Wigginton + * @access public + */ +class Net_SFTP extends Net_SSH2 +{ + /** + * Packet Types + * + * @see self::Net_SFTP() + * @var array + * @access private + */ + var $packet_types = array(); + + /** + * Status Codes + * + * @see self::Net_SFTP() + * @var array + * @access private + */ + var $status_codes = array(); + + /** + * The Request ID + * + * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support + * concurrent actions, so it's somewhat academic, here. + * + * @var int + * @see self::_send_sftp_packet() + * @access private + */ + var $request_id = false; + + /** + * The Packet Type + * + * The request ID exists in the off chance that a packet is sent out-of-order. Of course, this library doesn't support + * concurrent actions, so it's somewhat academic, here. + * + * @var int + * @see self::_get_sftp_packet() + * @access private + */ + var $packet_type = -1; + + /** + * Packet Buffer + * + * @var string + * @see self::_get_sftp_packet() + * @access private + */ + var $packet_buffer = ''; + + /** + * Extensions supported by the server + * + * @var array + * @see self::_initChannel() + * @access private + */ + var $extensions = array(); + + /** + * Server SFTP version + * + * @var int + * @see self::_initChannel() + * @access private + */ + var $version; + + /** + * Current working directory + * + * @var string + * @see self::realpath() + * @see self::chdir() + * @access private + */ + var $pwd = false; + + /** + * Packet Type Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $packet_type_log = array(); + + /** + * Packet Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $packet_log = array(); + + /** + * Error information + * + * @see self::getSFTPErrors() + * @see self::getLastSFTPError() + * @var array + * @access private + */ + var $sftp_errors = array(); + + /** + * Stat Cache + * + * Rather than always having to open a directory and close it immediately there after to see if a file is a directory + * we'll cache the results. + * + * @see self::_update_stat_cache() + * @see self::_remove_from_stat_cache() + * @see self::_query_stat_cache() + * @var array + * @access private + */ + var $stat_cache = array(); + + /** + * Max SFTP Packet Size + * + * @see self::Net_SFTP() + * @see self::get() + * @var array + * @access private + */ + var $max_sftp_packet; + + /** + * Stat Cache Flag + * + * @see self::disableStatCache() + * @see self::enableStatCache() + * @var bool + * @access private + */ + var $use_stat_cache = true; + + /** + * Sort Options + * + * @see self::_comparator() + * @see self::setListOrder() + * @var array + * @access private + */ + var $sortOptions = array(); + + /** + * Canonicalization Flag + * + * Determines whether or not paths should be canonicalized before being + * passed on to the remote server. + * + * @see self::enablePathCanonicalization() + * @see self::disablePathCanonicalization() + * @see self::realpath() + * @var bool + * @access private + */ + var $canonicalize_paths = true; + + /** + * Default Constructor. + * + * Connects to an SFTP server + * + * @param string $host + * @param int $port + * @param int $timeout + * @return Net_SFTP + * @access public + */ + function __construct($host, $port = 22, $timeout = 10) + { + parent::__construct($host, $port, $timeout); + + $this->max_sftp_packet = 1 << 15; + + $this->packet_types = array( + 1 => 'NET_SFTP_INIT', + 2 => 'NET_SFTP_VERSION', + /* the format of SSH_FXP_OPEN changed between SFTPv4 and SFTPv5+: + SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.1 + pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 */ + 3 => 'NET_SFTP_OPEN', + 4 => 'NET_SFTP_CLOSE', + 5 => 'NET_SFTP_READ', + 6 => 'NET_SFTP_WRITE', + 7 => 'NET_SFTP_LSTAT', + 9 => 'NET_SFTP_SETSTAT', + 11 => 'NET_SFTP_OPENDIR', + 12 => 'NET_SFTP_READDIR', + 13 => 'NET_SFTP_REMOVE', + 14 => 'NET_SFTP_MKDIR', + 15 => 'NET_SFTP_RMDIR', + 16 => 'NET_SFTP_REALPATH', + 17 => 'NET_SFTP_STAT', + /* the format of SSH_FXP_RENAME changed between SFTPv4 and SFTPv5+: + SFTPv5+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 + pre-SFTPv5 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.5 */ + 18 => 'NET_SFTP_RENAME', + 19 => 'NET_SFTP_READLINK', + 20 => 'NET_SFTP_SYMLINK', + + 101=> 'NET_SFTP_STATUS', + 102=> 'NET_SFTP_HANDLE', + /* the format of SSH_FXP_NAME changed between SFTPv3 and SFTPv4+: + SFTPv4+: http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.4 + pre-SFTPv4 : http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-7 */ + 103=> 'NET_SFTP_DATA', + 104=> 'NET_SFTP_NAME', + 105=> 'NET_SFTP_ATTRS', + + 200=> 'NET_SFTP_EXTENDED' + ); + $this->status_codes = array( + 0 => 'NET_SFTP_STATUS_OK', + 1 => 'NET_SFTP_STATUS_EOF', + 2 => 'NET_SFTP_STATUS_NO_SUCH_FILE', + 3 => 'NET_SFTP_STATUS_PERMISSION_DENIED', + 4 => 'NET_SFTP_STATUS_FAILURE', + 5 => 'NET_SFTP_STATUS_BAD_MESSAGE', + 6 => 'NET_SFTP_STATUS_NO_CONNECTION', + 7 => 'NET_SFTP_STATUS_CONNECTION_LOST', + 8 => 'NET_SFTP_STATUS_OP_UNSUPPORTED', + 9 => 'NET_SFTP_STATUS_INVALID_HANDLE', + 10 => 'NET_SFTP_STATUS_NO_SUCH_PATH', + 11 => 'NET_SFTP_STATUS_FILE_ALREADY_EXISTS', + 12 => 'NET_SFTP_STATUS_WRITE_PROTECT', + 13 => 'NET_SFTP_STATUS_NO_MEDIA', + 14 => 'NET_SFTP_STATUS_NO_SPACE_ON_FILESYSTEM', + 15 => 'NET_SFTP_STATUS_QUOTA_EXCEEDED', + 16 => 'NET_SFTP_STATUS_UNKNOWN_PRINCIPAL', + 17 => 'NET_SFTP_STATUS_LOCK_CONFLICT', + 18 => 'NET_SFTP_STATUS_DIR_NOT_EMPTY', + 19 => 'NET_SFTP_STATUS_NOT_A_DIRECTORY', + 20 => 'NET_SFTP_STATUS_INVALID_FILENAME', + 21 => 'NET_SFTP_STATUS_LINK_LOOP', + 22 => 'NET_SFTP_STATUS_CANNOT_DELETE', + 23 => 'NET_SFTP_STATUS_INVALID_PARAMETER', + 24 => 'NET_SFTP_STATUS_FILE_IS_A_DIRECTORY', + 25 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_CONFLICT', + 26 => 'NET_SFTP_STATUS_BYTE_RANGE_LOCK_REFUSED', + 27 => 'NET_SFTP_STATUS_DELETE_PENDING', + 28 => 'NET_SFTP_STATUS_FILE_CORRUPT', + 29 => 'NET_SFTP_STATUS_OWNER_INVALID', + 30 => 'NET_SFTP_STATUS_GROUP_INVALID', + 31 => 'NET_SFTP_STATUS_NO_MATCHING_BYTE_RANGE_LOCK' + ); + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-7.1 + // the order, in this case, matters quite a lot - see Net_SFTP::_parseAttributes() to understand why + $this->attributes = array( + 0x00000001 => 'NET_SFTP_ATTR_SIZE', + 0x00000002 => 'NET_SFTP_ATTR_UIDGID', // defined in SFTPv3, removed in SFTPv4+ + 0x00000004 => 'NET_SFTP_ATTR_PERMISSIONS', + 0x00000008 => 'NET_SFTP_ATTR_ACCESSTIME', + // 0x80000000 will yield a floating point on 32-bit systems and converting floating points to integers + // yields inconsistent behavior depending on how php is compiled. so we left shift -1 (which, in + // two's compliment, consists of all 1 bits) by 31. on 64-bit systems this'll yield 0xFFFFFFFF80000000. + // that's not a problem, however, and 'anded' and a 32-bit number, as all the leading 1 bits are ignored. + -1 << 31 => 'NET_SFTP_ATTR_EXTENDED' + ); + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-6.3 + // the flag definitions change somewhat in SFTPv5+. if SFTPv5+ support is added to this library, maybe name + // the array for that $this->open5_flags and similarly alter the constant names. + $this->open_flags = array( + 0x00000001 => 'NET_SFTP_OPEN_READ', + 0x00000002 => 'NET_SFTP_OPEN_WRITE', + 0x00000004 => 'NET_SFTP_OPEN_APPEND', + 0x00000008 => 'NET_SFTP_OPEN_CREATE', + 0x00000010 => 'NET_SFTP_OPEN_TRUNCATE', + 0x00000020 => 'NET_SFTP_OPEN_EXCL' + ); + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 + // see Net_SFTP::_parseLongname() for an explanation + $this->file_types = array( + 1 => 'NET_SFTP_TYPE_REGULAR', + 2 => 'NET_SFTP_TYPE_DIRECTORY', + 3 => 'NET_SFTP_TYPE_SYMLINK', + 4 => 'NET_SFTP_TYPE_SPECIAL', + 5 => 'NET_SFTP_TYPE_UNKNOWN', + // the followin types were first defined for use in SFTPv5+ + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2 + 6 => 'NET_SFTP_TYPE_SOCKET', + 7 => 'NET_SFTP_TYPE_CHAR_DEVICE', + 8 => 'NET_SFTP_TYPE_BLOCK_DEVICE', + 9 => 'NET_SFTP_TYPE_FIFO' + ); + $this->_define_array( + $this->packet_types, + $this->status_codes, + $this->attributes, + $this->open_flags, + $this->file_types + ); + + if (!defined('NET_SFTP_QUEUE_SIZE')) { + define('NET_SFTP_QUEUE_SIZE', 32); + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param string $host + * @param int $port + * @param int $timeout + * @access public + */ + function Net_SFTP($host, $port = 22, $timeout = 10) + { + $this->__construct($host, $port, $timeout); + } + + /** + * Login + * + * @param string $username + * @param string $password + * @return bool + * @access public + */ + function login($username) + { + $args = func_get_args(); + if (!call_user_func_array(array(&$this, '_login'), $args)) { + return false; + } + + $this->window_size_server_to_client[NET_SFTP_CHANNEL] = $this->window_size; + + $packet = pack( + 'CNa*N3', + NET_SSH2_MSG_CHANNEL_OPEN, + strlen('session'), + 'session', + NET_SFTP_CHANNEL, + $this->window_size, + 0x4000 + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_OPEN; + + $response = $this->_get_channel_packet(NET_SFTP_CHANNEL, true); + if ($response === false) { + return false; + } + + $packet = pack( + 'CNNa*CNa*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SFTP_CHANNEL], + strlen('subsystem'), + 'subsystem', + 1, + strlen('sftp'), + 'sftp' + ); + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST; + + $response = $this->_get_channel_packet(NET_SFTP_CHANNEL, true); + if ($response === false) { + // from PuTTY's psftp.exe + $command = "test -x /usr/lib/sftp-server && exec /usr/lib/sftp-server\n" . + "test -x /usr/local/lib/sftp-server && exec /usr/local/lib/sftp-server\n" . + "exec sftp-server"; + // we don't do $this->exec($command, false) because exec() operates on a different channel and plus the SSH_MSG_CHANNEL_OPEN that exec() does + // is redundant + $packet = pack( + 'CNNa*CNa*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SFTP_CHANNEL], + strlen('exec'), + 'exec', + 1, + strlen($command), + $command + ); + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_REQUEST; + + $response = $this->_get_channel_packet(NET_SFTP_CHANNEL, true); + if ($response === false) { + return false; + } + } + + $this->channel_status[NET_SFTP_CHANNEL] = NET_SSH2_MSG_CHANNEL_DATA; + + if (!$this->_send_sftp_packet(NET_SFTP_INIT, "\0\0\0\3")) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_VERSION) { + user_error('Expected SSH_FXP_VERSION'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nversion', $this->_string_shift($response, 4))); + $this->version = $version; + while (!empty($response)) { + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $key = $this->_string_shift($response, $length); + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $value = $this->_string_shift($response, $length); + $this->extensions[$key] = $value; + } + + /* + SFTPv4+ defines a 'newline' extension. SFTPv3 seems to have unofficial support for it via 'newline@vandyke.com', + however, I'm not sure what 'newline@vandyke.com' is supposed to do (the fact that it's unofficial means that it's + not in the official SFTPv3 specs) and 'newline@vandyke.com' / 'newline' are likely not drop-in substitutes for + one another due to the fact that 'newline' comes with a SSH_FXF_TEXT bitmask whereas it seems unlikely that + 'newline@vandyke.com' would. + */ + /* + if (isset($this->extensions['newline@vandyke.com'])) { + $this->extensions['newline'] = $this->extensions['newline@vandyke.com']; + unset($this->extensions['newline@vandyke.com']); + } + */ + + $this->request_id = 1; + + /* + A Note on SFTPv4/5/6 support: + states the following: + + "If the client wishes to interoperate with servers that support noncontiguous version + numbers it SHOULD send '3'" + + Given that the server only sends its version number after the client has already done so, the above + seems to be suggesting that v3 should be the default version. This makes sense given that v3 is the + most popular. + + states the following; + + "If the server did not send the "versions" extension, or the version-from-list was not included, the + server MAY send a status response describing the failure, but MUST then close the channel without + processing any further requests." + + So what do you do if you have a client whose initial SSH_FXP_INIT packet says it implements v3 and + a server whose initial SSH_FXP_VERSION reply says it implements v4 and only v4? If it only implements + v4, the "versions" extension is likely not going to have been sent so version re-negotiation as discussed + in draft-ietf-secsh-filexfer-13 would be quite impossible. As such, what Net_SFTP would do is close the + channel and reopen it with a new and updated SSH_FXP_INIT packet. + */ + switch ($this->version) { + case 2: + case 3: + break; + default: + return false; + } + + $this->pwd = $this->_realpath('.'); + + $this->_update_stat_cache($this->pwd, array()); + + return true; + } + + /** + * Disable the stat cache + * + * @access public + */ + function disableStatCache() + { + $this->use_stat_cache = false; + } + + /** + * Enable the stat cache + * + * @access public + */ + function enableStatCache() + { + $this->use_stat_cache = true; + } + + /** + * Clear the stat cache + * + * @access public + */ + function clearStatCache() + { + $this->stat_cache = array(); + } + + /** + * Enable path canonicalization + * + * @access public + */ + function enablePathCanonicalization() + { + $this->canonicalize_paths = true; + } + + /** + * Enable path canonicalization + * + * @access public + */ + function disablePathCanonicalization() + { + $this->canonicalize_paths = false; + } + + /** + * Returns the current directory name + * + * @return mixed + * @access public + */ + function pwd() + { + return $this->pwd; + } + + /** + * Logs errors + * + * @param string $response + * @param int $status + * @access public + */ + function _logError($response, $status = -1) + { + if ($status == -1) { + if (strlen($response) < 4) { + return; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + } + + $error = $this->status_codes[$status]; + + if ($this->version > 2 || strlen($response) < 4) { + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->sftp_errors[] = $error . ': ' . $this->_string_shift($response, $length); + } else { + $this->sftp_errors[] = $error; + } + } + + /** + * Returns canonicalized absolute pathname + * + * realpath() expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters in the input + * path and returns the canonicalized absolute pathname. + * + * @param string $path + * @return mixed + * @access public + */ + function realpath($path) + { + return $this->_realpath($path); + } + + /** + * Canonicalize the Server-Side Path Name + * + * SFTP doesn't provide a mechanism by which the current working directory can be changed, so we'll emulate it. Returns + * the absolute (canonicalized) path. + * + * If canonicalize_paths has been disabled using disablePathCanonicalization(), $path is returned as-is. + * + * @see self::chdir() + * @see self::disablePathCanonicalization() + * @param string $path + * @return mixed + * @access private + */ + function _realpath($path) + { + if (!$this->canonicalize_paths) { + return $path; + } + + if ($this->pwd === false) { + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.9 + if (!$this->_send_sftp_packet(NET_SFTP_REALPATH, pack('Na*', strlen($path), $path))) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_NAME: + // although SSH_FXP_NAME is implemented differently in SFTPv3 than it is in SFTPv4+, the following + // should work on all SFTP versions since the only part of the SSH_FXP_NAME packet the following looks + // at is the first part and that part is defined the same in SFTP versions 3 through 6. + $this->_string_shift($response, 4); // skip over the count - it should be 1, anyway + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + return $this->_string_shift($response, $length); + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); + return false; + } + } + + if ($path[0] != '/') { + $path = $this->pwd . '/' . $path; + } + + $path = explode('/', $path); + $new = array(); + foreach ($path as $dir) { + if (!strlen($dir)) { + continue; + } + switch ($dir) { + case '..': + array_pop($new); + case '.': + break; + default: + $new[] = $dir; + } + } + + return '/' . implode('/', $new); + } + + /** + * Changes the current directory + * + * @param string $dir + * @return bool + * @access public + */ + function chdir($dir) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + // assume current dir if $dir is empty + if ($dir === '') { + $dir = './'; + // suffix a slash if needed + } elseif ($dir[strlen($dir) - 1] != '/') { + $dir.= '/'; + } + + $dir = $this->_realpath($dir); + + // confirm that $dir is, in fact, a valid directory + if ($this->use_stat_cache && is_array($this->_query_stat_cache($dir))) { + $this->pwd = $dir; + return true; + } + + // we could do a stat on the alleged $dir to see if it's a directory but that doesn't tell us + // the currently logged in user has the appropriate permissions or not. maybe you could see if + // the file's uid / gid match the currently logged in user's uid / gid but how there's no easy + // way to get those with SFTP + + if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) { + return false; + } + + // see Net_SFTP::nlist() for a more thorough explanation of the following + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + $handle = substr($response, 4); + break; + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + + if (!$this->_close_handle($handle)) { + return false; + } + + $this->_update_stat_cache($dir, array()); + + $this->pwd = $dir; + return true; + } + + /** + * Returns a list of files in the given directory + * + * @param string $dir + * @param bool $recursive + * @return mixed + * @access public + */ + function nlist($dir = '.', $recursive = false) + { + return $this->_nlist_helper($dir, $recursive, ''); + } + + /** + * Helper method for nlist + * + * @param string $dir + * @param bool $recursive + * @param string $relativeDir + * @return mixed + * @access private + */ + function _nlist_helper($dir, $recursive, $relativeDir) + { + $files = $this->_list($dir, false); + + if (!$recursive || $files === false) { + return $files; + } + + $result = array(); + foreach ($files as $value) { + if ($value == '.' || $value == '..') { + if ($relativeDir == '') { + $result[] = $value; + } + continue; + } + if (is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $value)))) { + $temp = $this->_nlist_helper($dir . '/' . $value, true, $relativeDir . $value . '/'); + $result = array_merge($result, $temp); + } else { + $result[] = $relativeDir . $value; + } + } + + return $result; + } + + /** + * Returns a detailed list of files in the given directory + * + * @param string $dir + * @param bool $recursive + * @return mixed + * @access public + */ + function rawlist($dir = '.', $recursive = false) + { + $files = $this->_list($dir, true); + if (!$recursive || $files === false) { + return $files; + } + + static $depth = 0; + + foreach ($files as $key => $value) { + if ($depth != 0 && $key == '..') { + unset($files[$key]); + continue; + } + if ($key != '.' && $key != '..' && is_array($this->_query_stat_cache($this->_realpath($dir . '/' . $key)))) { + $depth++; + $files[$key] = $this->rawlist($dir . '/' . $key, true); + $depth--; + } else { + $files[$key] = (object) $value; + } + } + + return $files; + } + + /** + * Reads a list, be it detailed or not, of files in the given directory + * + * @param string $dir + * @param bool $raw + * @return mixed + * @access private + */ + function _list($dir, $raw = true) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $dir = $this->_realpath($dir . '/'); + if ($dir === false) { + return false; + } + + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.2 + if (!$this->_send_sftp_packet(NET_SFTP_OPENDIR, pack('Na*', strlen($dir), $dir))) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-9.2 + // since 'handle' is the last field in the SSH_FXP_HANDLE packet, we'll just remove the first four bytes that + // represent the length of the string and leave it at that + $handle = substr($response, 4); + break; + case NET_SFTP_STATUS: + // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + + $this->_update_stat_cache($dir, array()); + + $contents = array(); + while (true) { + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.2 + // why multiple SSH_FXP_READDIR packets would be sent when the response to a single one can span arbitrarily many + // SSH_MSG_CHANNEL_DATA messages is not known to me. + if (!$this->_send_sftp_packet(NET_SFTP_READDIR, pack('Na*', strlen($handle), $handle))) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_NAME: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Ncount', $this->_string_shift($response, 4))); + for ($i = 0; $i < $count; $i++) { + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $shortname = $this->_string_shift($response, $length); + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $longname = $this->_string_shift($response, $length); + $attributes = $this->_parseAttributes($response); + if (!isset($attributes['type'])) { + $fileType = $this->_parseLongname($longname); + if ($fileType) { + $attributes['type'] = $fileType; + } + } + $contents[$shortname] = $attributes + array('filename' => $shortname); + + if (isset($attributes['type']) && $attributes['type'] == NET_SFTP_TYPE_DIRECTORY && ($shortname != '.' && $shortname != '..')) { + $this->_update_stat_cache($dir . '/' . $shortname, array()); + } else { + if ($shortname == '..') { + $temp = $this->_realpath($dir . '/..') . '/.'; + } else { + $temp = $dir . '/' . $shortname; + } + $this->_update_stat_cache($temp, (object) array('lstat' => $attributes)); + } + // SFTPv6 has an optional boolean end-of-list field, but we'll ignore that, since the + // final SSH_FXP_STATUS packet should tell us that, already. + } + break; + case NET_SFTP_STATUS: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_EOF) { + $this->_logError($response, $status); + return false; + } + break 2; + default: + user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); + return false; + } + } + + if (!$this->_close_handle($handle)) { + return false; + } + + if (count($this->sortOptions)) { + uasort($contents, array(&$this, '_comparator')); + } + + return $raw ? $contents : array_keys($contents); + } + + /** + * Compares two rawlist entries using parameters set by setListOrder() + * + * Intended for use with uasort() + * + * @param array $a + * @param array $b + * @return int + * @access private + */ + function _comparator($a, $b) + { + switch (true) { + case $a['filename'] === '.' || $b['filename'] === '.': + if ($a['filename'] === $b['filename']) { + return 0; + } + return $a['filename'] === '.' ? -1 : 1; + case $a['filename'] === '..' || $b['filename'] === '..': + if ($a['filename'] === $b['filename']) { + return 0; + } + return $a['filename'] === '..' ? -1 : 1; + case isset($a['type']) && $a['type'] === NET_SFTP_TYPE_DIRECTORY: + if (!isset($b['type'])) { + return 1; + } + if ($b['type'] !== $a['type']) { + return -1; + } + break; + case isset($b['type']) && $b['type'] === NET_SFTP_TYPE_DIRECTORY: + return 1; + } + foreach ($this->sortOptions as $sort => $order) { + if (!isset($a[$sort]) || !isset($b[$sort])) { + if (isset($a[$sort])) { + return -1; + } + if (isset($b[$sort])) { + return 1; + } + return 0; + } + switch ($sort) { + case 'filename': + $result = strcasecmp($a['filename'], $b['filename']); + if ($result) { + return $order === SORT_DESC ? -$result : $result; + } + break; + case 'permissions': + case 'mode': + $a[$sort]&= 07777; + $b[$sort]&= 07777; + default: + if ($a[$sort] === $b[$sort]) { + break; + } + return $order === SORT_ASC ? $a[$sort] - $b[$sort] : $b[$sort] - $a[$sort]; + } + } + } + + /** + * Defines how nlist() and rawlist() will be sorted - if at all. + * + * If sorting is enabled directories and files will be sorted independently with + * directories appearing before files in the resultant array that is returned. + * + * Any parameter returned by stat is a valid sort parameter for this function. + * Filename comparisons are case insensitive. + * + * Examples: + * + * $sftp->setListOrder('filename', SORT_ASC); + * $sftp->setListOrder('size', SORT_DESC, 'filename', SORT_ASC); + * $sftp->setListOrder(true); + * Separates directories from files but doesn't do any sorting beyond that + * $sftp->setListOrder(); + * Don't do any sort of sorting + * + * @access public + */ + function setListOrder() + { + $this->sortOptions = array(); + $args = func_get_args(); + if (empty($args)) { + return; + } + $len = count($args) & 0x7FFFFFFE; + for ($i = 0; $i < $len; $i+=2) { + $this->sortOptions[$args[$i]] = $args[$i + 1]; + } + if (!count($this->sortOptions)) { + $this->sortOptions = array('bogus' => true); + } + } + + /** + * Returns the file size, in bytes, or false, on failure + * + * Files larger than 4GB will show up as being exactly 4GB. + * + * @param string $filename + * @return mixed + * @access public + */ + function size($filename) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $result = $this->stat($filename); + if ($result === false) { + return false; + } + return isset($result['size']) ? $result['size'] : -1; + } + + /** + * Save files / directories to cache + * + * @param string $path + * @param mixed $value + * @access private + */ + function _update_stat_cache($path, $value) + { + if ($this->use_stat_cache === false) { + return; + } + + // preg_replace('#^/|/(?=/)|/$#', '', $dir) == str_replace('//', '/', trim($path, '/')) + $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); + + $temp = &$this->stat_cache; + $max = count($dirs) - 1; + foreach ($dirs as $i => $dir) { + // if $temp is an object that means one of two things. + // 1. a file was deleted and changed to a directory behind phpseclib's back + // 2. it's a symlink. when lstat is done it's unclear what it's a symlink to + if (is_object($temp)) { + $temp = array(); + } + if (!isset($temp[$dir])) { + $temp[$dir] = array(); + } + if ($i === $max) { + if (is_object($temp[$dir])) { + if (!isset($value->stat) && isset($temp[$dir]->stat)) { + $value->stat = $temp[$dir]->stat; + } + if (!isset($value->lstat) && isset($temp[$dir]->lstat)) { + $value->lstat = $temp[$dir]->lstat; + } + } + $temp[$dir] = $value; + break; + } + $temp = &$temp[$dir]; + } + } + + /** + * Remove files / directories from cache + * + * @param string $path + * @return bool + * @access private + */ + function _remove_from_stat_cache($path) + { + $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); + + $temp = &$this->stat_cache; + $max = count($dirs) - 1; + foreach ($dirs as $i => $dir) { + if ($i === $max) { + unset($temp[$dir]); + return true; + } + if (!isset($temp[$dir])) { + return false; + } + $temp = &$temp[$dir]; + } + } + + /** + * Checks cache for path + * + * Mainly used by file_exists + * + * @param string $dir + * @return mixed + * @access private + */ + function _query_stat_cache($path) + { + $dirs = explode('/', preg_replace('#^/|/(?=/)|/$#', '', $path)); + + $temp = &$this->stat_cache; + foreach ($dirs as $dir) { + if (!isset($temp[$dir])) { + return null; + } + $temp = &$temp[$dir]; + } + return $temp; + } + + /** + * Returns general information about a file. + * + * Returns an array on success and false otherwise. + * + * @param string $filename + * @return mixed + * @access public + */ + function stat($filename) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $filename = $this->_realpath($filename); + if ($filename === false) { + return false; + } + + if ($this->use_stat_cache) { + $result = $this->_query_stat_cache($filename); + if (is_array($result) && isset($result['.']) && isset($result['.']->stat)) { + return $result['.']->stat; + } + if (is_object($result) && isset($result->stat)) { + return $result->stat; + } + } + + $stat = $this->_stat($filename, NET_SFTP_STAT); + if ($stat === false) { + $this->_remove_from_stat_cache($filename); + return false; + } + if (isset($stat['type'])) { + if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) { + $filename.= '/.'; + } + $this->_update_stat_cache($filename, (object) array('stat' => $stat)); + return $stat; + } + + $pwd = $this->pwd; + $stat['type'] = $this->chdir($filename) ? + NET_SFTP_TYPE_DIRECTORY : + NET_SFTP_TYPE_REGULAR; + $this->pwd = $pwd; + + if ($stat['type'] == NET_SFTP_TYPE_DIRECTORY) { + $filename.= '/.'; + } + $this->_update_stat_cache($filename, (object) array('stat' => $stat)); + + return $stat; + } + + /** + * Returns general information about a file or symbolic link. + * + * Returns an array on success and false otherwise. + * + * @param string $filename + * @return mixed + * @access public + */ + function lstat($filename) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $filename = $this->_realpath($filename); + if ($filename === false) { + return false; + } + + if ($this->use_stat_cache) { + $result = $this->_query_stat_cache($filename); + if (is_array($result) && isset($result['.']) && isset($result['.']->lstat)) { + return $result['.']->lstat; + } + if (is_object($result) && isset($result->lstat)) { + return $result->lstat; + } + } + + $lstat = $this->_stat($filename, NET_SFTP_LSTAT); + if ($lstat === false) { + $this->_remove_from_stat_cache($filename); + return false; + } + if (isset($lstat['type'])) { + if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) { + $filename.= '/.'; + } + $this->_update_stat_cache($filename, (object) array('lstat' => $lstat)); + return $lstat; + } + + $stat = $this->_stat($filename, NET_SFTP_STAT); + + if ($lstat != $stat) { + $lstat = array_merge($lstat, array('type' => NET_SFTP_TYPE_SYMLINK)); + $this->_update_stat_cache($filename, (object) array('lstat' => $lstat)); + return $stat; + } + + $pwd = $this->pwd; + $lstat['type'] = $this->chdir($filename) ? + NET_SFTP_TYPE_DIRECTORY : + NET_SFTP_TYPE_REGULAR; + $this->pwd = $pwd; + + if ($lstat['type'] == NET_SFTP_TYPE_DIRECTORY) { + $filename.= '/.'; + } + $this->_update_stat_cache($filename, (object) array('lstat' => $lstat)); + + return $lstat; + } + + /** + * Returns general information about a file or symbolic link + * + * Determines information without calling Net_SFTP::realpath(). + * The second parameter can be either NET_SFTP_STAT or NET_SFTP_LSTAT. + * + * @param string $filename + * @param int $type + * @return mixed + * @access private + */ + function _stat($filename, $type) + { + // SFTPv4+ adds an additional 32-bit integer field - flags - to the following: + $packet = pack('Na*', strlen($filename), $filename); + if (!$this->_send_sftp_packet($type, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_ATTRS: + return $this->_parseAttributes($response); + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + } + + user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS'); + return false; + } + + /** + * Truncates a file to a given length + * + * @param string $filename + * @param int $new_size + * @return bool + * @access public + */ + function truncate($filename, $new_size) + { + $attr = pack('N3', NET_SFTP_ATTR_SIZE, $new_size / 4294967296, $new_size); // 4294967296 == 0x100000000 == 1<<32 + + return $this->_setstat($filename, $attr, false); + } + + /** + * Sets access and modification time of file. + * + * If the file does not exist, it will be created. + * + * @param string $filename + * @param int $time + * @param int $atime + * @return bool + * @access public + */ + function touch($filename, $time = null, $atime = null) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $filename = $this->_realpath($filename); + if ($filename === false) { + return false; + } + + if (!isset($time)) { + $time = time(); + } + if (!isset($atime)) { + $atime = $time; + } + + $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE | NET_SFTP_OPEN_EXCL; + $attr = pack('N3', NET_SFTP_ATTR_ACCESSTIME, $time, $atime); + $packet = pack('Na*Na*', strlen($filename), $filename, $flags, $attr); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + return $this->_close_handle(substr($response, 4)); + case NET_SFTP_STATUS: + $this->_logError($response); + break; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + + return $this->_setstat($filename, $attr, false); + } + + /** + * Changes file or directory owner + * + * Returns true on success or false on error. + * + * @param string $filename + * @param int $uid + * @param bool $recursive + * @return bool + * @access public + */ + function chown($filename, $uid, $recursive = false) + { + // quoting from , + // "if the owner or group is specified as -1, then that ID is not changed" + $attr = pack('N3', NET_SFTP_ATTR_UIDGID, $uid, -1); + + return $this->_setstat($filename, $attr, $recursive); + } + + /** + * Changes file or directory group + * + * Returns true on success or false on error. + * + * @param string $filename + * @param int $gid + * @param bool $recursive + * @return bool + * @access public + */ + function chgrp($filename, $gid, $recursive = false) + { + $attr = pack('N3', NET_SFTP_ATTR_UIDGID, -1, $gid); + + return $this->_setstat($filename, $attr, $recursive); + } + + /** + * Set permissions on a file. + * + * Returns the new file permissions on success or false on error. + * If $recursive is true than this just returns true or false. + * + * @param int $mode + * @param string $filename + * @param bool $recursive + * @return mixed + * @access public + */ + function chmod($mode, $filename, $recursive = false) + { + if (is_string($mode) && is_int($filename)) { + $temp = $mode; + $mode = $filename; + $filename = $temp; + } + + $attr = pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777); + if (!$this->_setstat($filename, $attr, $recursive)) { + return false; + } + if ($recursive) { + return true; + } + + $filename = $this->realpath($filename); + // rather than return what the permissions *should* be, we'll return what they actually are. this will also + // tell us if the file actually exists. + // incidentally, SFTPv4+ adds an additional 32-bit integer field - flags - to the following: + $packet = pack('Na*', strlen($filename), $filename); + if (!$this->_send_sftp_packet(NET_SFTP_STAT, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_ATTRS: + $attrs = $this->_parseAttributes($response); + return $attrs['permissions']; + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + } + + user_error('Expected SSH_FXP_ATTRS or SSH_FXP_STATUS'); + return false; + } + + /** + * Sets information about a file + * + * @param string $filename + * @param string $attr + * @param bool $recursive + * @return bool + * @access private + */ + function _setstat($filename, $attr, $recursive) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $filename = $this->_realpath($filename); + if ($filename === false) { + return false; + } + + $this->_remove_from_stat_cache($filename); + + if ($recursive) { + $i = 0; + $result = $this->_setstat_recursive($filename, $attr, $i); + $this->_read_put_responses($i); + return $result; + } + + // SFTPv4+ has an additional byte field - type - that would need to be sent, as well. setting it to + // SSH_FILEXFER_TYPE_UNKNOWN might work. if not, we'd have to do an SSH_FXP_STAT before doing an SSH_FXP_SETSTAT. + if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($filename), $filename, $attr))) { + return false; + } + + /* + "Because some systems must use separate system calls to set various attributes, it is possible that a failure + response will be returned, but yet some of the attributes may be have been successfully modified. If possible, + servers SHOULD avoid this situation; however, clients MUST be aware that this is possible." + + -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.6 + */ + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + return false; + } + + return true; + } + + /** + * Recursively sets information on directories on the SFTP server + * + * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. + * + * @param string $path + * @param string $attr + * @param int $i + * @return bool + * @access private + */ + function _setstat_recursive($path, $attr, &$i) + { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + $entries = $this->_list($path, true); + + if ($entries === false) { + return $this->_setstat($path, $attr, false); + } + + // normally $entries would have at least . and .. but it might not if the directories + // permissions didn't allow reading + if (empty($entries)) { + return false; + } + + unset($entries['.'], $entries['..']); + foreach ($entries as $filename => $props) { + if (!isset($props['type'])) { + return false; + } + + $temp = $path . '/' . $filename; + if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) { + if (!$this->_setstat_recursive($temp, $attr, $i)) { + return false; + } + } else { + if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($temp), $temp, $attr))) { + return false; + } + + $i++; + + if ($i >= NET_SFTP_QUEUE_SIZE) { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + } + } + } + + if (!$this->_send_sftp_packet(NET_SFTP_SETSTAT, pack('Na*a*', strlen($path), $path, $attr))) { + return false; + } + + $i++; + + if ($i >= NET_SFTP_QUEUE_SIZE) { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + } + + return true; + } + + /** + * Return the target of a symbolic link + * + * @param string $link + * @return mixed + * @access public + */ + function readlink($link) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $link = $this->_realpath($link); + + if (!$this->_send_sftp_packet(NET_SFTP_READLINK, pack('Na*', strlen($link), $link))) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_NAME: + break; + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_NAME or SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Ncount', $this->_string_shift($response, 4))); + // the file isn't a symlink + if (!$count) { + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + return $this->_string_shift($response, $length); + } + + /** + * Create a symlink + * + * symlink() creates a symbolic link to the existing target with the specified name link. + * + * @param string $target + * @param string $link + * @return bool + * @access public + */ + function symlink($target, $link) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + //$target = $this->_realpath($target); + $link = $this->_realpath($link); + + $packet = pack('Na*Na*', strlen($target), $target, strlen($link), $link); + if (!$this->_send_sftp_packet(NET_SFTP_SYMLINK, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + return false; + } + + return true; + } + + /** + * Creates a directory. + * + * @param string $dir + * @return bool + * @access public + */ + function mkdir($dir, $mode = -1, $recursive = false) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $dir = $this->_realpath($dir); + // by not providing any permissions, hopefully the server will use the logged in users umask - their + // default permissions. + $attr = $mode == -1 ? "\0\0\0\0" : pack('N2', NET_SFTP_ATTR_PERMISSIONS, $mode & 07777); + + if ($recursive) { + $dirs = explode('/', preg_replace('#/(?=/)|/$#', '', $dir)); + if (empty($dirs[0])) { + array_shift($dirs); + $dirs[0] = '/' . $dirs[0]; + } + for ($i = 0; $i < count($dirs); $i++) { + $temp = array_slice($dirs, 0, $i + 1); + $temp = implode('/', $temp); + $result = $this->_mkdir_helper($temp, $attr); + } + return $result; + } + + return $this->_mkdir_helper($dir, $attr); + } + + /** + * Helper function for directory creation + * + * @param string $dir + * @return bool + * @access private + */ + function _mkdir_helper($dir, $attr) + { + if (!$this->_send_sftp_packet(NET_SFTP_MKDIR, pack('Na*a*', strlen($dir), $dir, $attr))) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + return false; + } + + return true; + } + + /** + * Removes a directory. + * + * @param string $dir + * @return bool + * @access public + */ + function rmdir($dir) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $dir = $this->_realpath($dir); + if ($dir === false) { + return false; + } + + if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($dir), $dir))) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED? + $this->_logError($response, $status); + return false; + } + + $this->_remove_from_stat_cache($dir); + // the following will do a soft delete, which would be useful if you deleted a file + // and then tried to do a stat on the deleted file. the above, in contrast, does + // a hard delete + //$this->_update_stat_cache($dir, false); + + return true; + } + + /** + * Uploads a file to the SFTP server. + * + * By default, Net_SFTP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. + * So, for example, if you set $data to 'filename.ext' and then do Net_SFTP::get(), you will get a file, twelve bytes + * long, containing 'filename.ext' as its contents. + * + * Setting $mode to NET_SFTP_LOCAL_FILE will change the above behavior. With NET_SFTP_LOCAL_FILE, $remote_file will + * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how + * large $remote_file will be, as well. + * + * If $data is a resource then it'll be used as a resource instead. + * + * + * Setting $mode to NET_SFTP_CALLBACK will use $data as callback function, which gets only one parameter -- number + * of bytes to return, and returns a string if there is some data or null if there is no more data + * + * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take + * care of that, yourself. + * + * $mode can take an additional two parameters - NET_SFTP_RESUME and NET_SFTP_RESUME_START. These are bitwise AND'd with + * $mode. So if you want to resume upload of a 300mb file on the local file system you'd set $mode to the following: + * + * NET_SFTP_LOCAL_FILE | NET_SFTP_RESUME + * + * If you wanted to simply append the full contents of a local file to the full contents of a remote file you'd replace + * NET_SFTP_RESUME with NET_SFTP_RESUME_START. + * + * If $mode & (NET_SFTP_RESUME | NET_SFTP_RESUME_START) then NET_SFTP_RESUME_START will be assumed. + * + * $start and $local_start give you more fine grained control over this process and take precident over NET_SFTP_RESUME + * when they're non-negative. ie. $start could let you write at the end of a file (like NET_SFTP_RESUME) or in the middle + * of one. $local_start could let you start your reading from the end of a file (like NET_SFTP_RESUME_START) or in the + * middle of one. + * + * Setting $local_start to > 0 or $mode | NET_SFTP_RESUME_START doesn't do anything unless $mode | NET_SFTP_LOCAL_FILE. + * + * @param string $remote_file + * @param string|resource $data + * @param int $mode + * @param int $start + * @param int $local_start + * @param callable|null $progressCallback + * @return bool + * @access public + * @internal ASCII mode for SFTPv4/5/6 can be supported by adding a new function - Net_SFTP::setMode(). + */ + function put($remote_file, $data, $mode = NET_SFTP_STRING, $start = -1, $local_start = -1, $progressCallback = null) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $remote_file = $this->_realpath($remote_file); + if ($remote_file === false) { + return false; + } + + $this->_remove_from_stat_cache($remote_file); + + $flags = NET_SFTP_OPEN_WRITE | NET_SFTP_OPEN_CREATE; + // according to the SFTP specs, NET_SFTP_OPEN_APPEND should "force all writes to append data at the end of the file." + // in practice, it doesn't seem to do that. + //$flags|= ($mode & NET_SFTP_RESUME) ? NET_SFTP_OPEN_APPEND : NET_SFTP_OPEN_TRUNCATE; + + if ($start >= 0) { + $offset = $start; + } elseif ($mode & NET_SFTP_RESUME) { + // if NET_SFTP_OPEN_APPEND worked as it should _size() wouldn't need to be called + $size = $this->size($remote_file); + $offset = $size !== false ? $size : 0; + } else { + $offset = 0; + $flags|= NET_SFTP_OPEN_TRUNCATE; + } + + $packet = pack('Na*N2', strlen($remote_file), $remote_file, $flags, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + $handle = substr($response, 4); + break; + case NET_SFTP_STATUS: + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.2.3 + $dataCallback = false; + switch (true) { + case $mode & NET_SFTP_CALLBACK: + if (!is_callable($data)) { + user_error("\$data should be is_callable if you set NET_SFTP_CALLBACK flag"); + } + $dataCallback = $data; + // do nothing + break; + case is_resource($data): + $mode = $mode & ~NET_SFTP_LOCAL_FILE; + $info = stream_get_meta_data($data); + if ($info['wrapper_type'] == 'PHP' && $info['stream_type'] == 'Input') { + $fp = fopen('php://memory', 'w+'); + stream_copy_to_stream($data, $fp); + rewind($fp); + } else { + $fp = $data; + } + break; + case $mode & NET_SFTP_LOCAL_FILE: + if (!is_file($data)) { + user_error("$data is not a valid file"); + return false; + } + $fp = @fopen($data, 'rb'); + if (!$fp) { + return false; + } + } + + if (isset($fp)) { + $stat = fstat($fp); + $size = !empty($stat) ? $stat['size'] : 0; + + if ($local_start >= 0) { + fseek($fp, $local_start); + $size-= $local_start; + } + } elseif ($dataCallback) { + $size = 0; + } else { + $size = strlen($data); + } + + $sent = 0; + $size = $size < 0 ? ($size & 0x7FFFFFFF) + 0x80000000 : $size; + + $sftp_packet_size = 4096; // PuTTY uses 4096 + // make the SFTP packet be exactly 4096 bytes by including the bytes in the NET_SFTP_WRITE packets "header" + $sftp_packet_size-= strlen($handle) + 25; + $i = 0; + while ($dataCallback || ($size === 0 || $sent < $size)) { + if ($dataCallback) { + $temp = call_user_func($dataCallback, $sftp_packet_size); + if (is_null($temp)) { + break; + } + } else { + $temp = isset($fp) ? fread($fp, $sftp_packet_size) : substr($data, $sent, $sftp_packet_size); + if ($temp === false || $temp === '') { + break; + } + } + + $subtemp = $offset + $sent; + $packet = pack('Na*N3a*', strlen($handle), $handle, $subtemp / 4294967296, $subtemp, strlen($temp), $temp); + if (!$this->_send_sftp_packet(NET_SFTP_WRITE, $packet)) { + if ($mode & NET_SFTP_LOCAL_FILE) { + fclose($fp); + } + return false; + } + $sent+= strlen($temp); + if (is_callable($progressCallback)) { + call_user_func($progressCallback, $sent); + } + + $i++; + + if ($i == NET_SFTP_QUEUE_SIZE) { + if (!$this->_read_put_responses($i)) { + $i = 0; + break; + } + $i = 0; + } + } + + if (!$this->_read_put_responses($i)) { + if ($mode & NET_SFTP_LOCAL_FILE) { + fclose($fp); + } + $this->_close_handle($handle); + return false; + } + + if ($mode & NET_SFTP_LOCAL_FILE) { + fclose($fp); + } + + return $this->_close_handle($handle); + } + + /** + * Reads multiple successive SSH_FXP_WRITE responses + * + * Sending an SSH_FXP_WRITE packet and immediately reading its response isn't as efficient as blindly sending out $i + * SSH_FXP_WRITEs, in succession, and then reading $i responses. + * + * @param int $i + * @return bool + * @access private + */ + function _read_put_responses($i) + { + while ($i--) { + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + break; + } + } + + return $i < 0; + } + + /** + * Close handle + * + * @param string $handle + * @return bool + * @access private + */ + function _close_handle($handle) + { + if (!$this->_send_sftp_packet(NET_SFTP_CLOSE, pack('Na*', strlen($handle), $handle))) { + return false; + } + + // "The client MUST release all resources associated with the handle regardless of the status." + // -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.1.3 + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + return false; + } + + return true; + } + + /** + * Downloads a file from the SFTP server. + * + * Returns a string containing the contents of $remote_file if $local_file is left undefined or a boolean false if + * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the + * operation. + * + * $offset and $length can be used to download files in chunks. + * + * @param string $remote_file + * @param string $local_file + * @param int $offset + * @param int $length + * @return mixed + * @access public + */ + function get($remote_file, $local_file = false, $offset = 0, $length = -1) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $remote_file = $this->_realpath($remote_file); + if ($remote_file === false) { + return false; + } + + $packet = pack('Na*N2', strlen($remote_file), $remote_file, NET_SFTP_OPEN_READ, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + $handle = substr($response, 4); + break; + case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + $this->_logError($response); + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + + if (is_resource($local_file)) { + $fp = $local_file; + $stat = fstat($fp); + $res_offset = $stat['size']; + } else { + $res_offset = 0; + if ($local_file !== false) { + $fp = fopen($local_file, 'wb'); + if (!$fp) { + return false; + } + } else { + $content = ''; + } + } + + $fclose_check = $local_file !== false && !is_resource($local_file); + + $start = $offset; + $read = 0; + while (true) { + $i = 0; + + while ($i < NET_SFTP_QUEUE_SIZE && ($length < 0 || $read < $length)) { + $tempoffset = $start + $read; + + $packet_size = $length > 0 ? min($this->max_sftp_packet, $length - $read) : $this->max_sftp_packet; + + $packet = pack('Na*N3', strlen($handle), $handle, $tempoffset / 4294967296, $tempoffset, $packet_size); + if (!$this->_send_sftp_packet(NET_SFTP_READ, $packet)) { + if ($fclose_check) { + fclose($fp); + } + return false; + } + $packet = null; + $read+= $packet_size; + $i++; + } + + if (!$i) { + break; + } + + $clear_responses = false; + while ($i > 0) { + $i--; + + if ($clear_responses) { + $this->_get_sftp_packet(); + continue; + } else { + $response = $this->_get_sftp_packet(); + } + + switch ($this->packet_type) { + case NET_SFTP_DATA: + $temp = substr($response, 4); + $offset+= strlen($temp); + if ($local_file === false) { + $content.= $temp; + } else { + fputs($fp, $temp); + } + $temp = null; + break; + case NET_SFTP_STATUS: + // could, in theory, return false if !strlen($content) but we'll hold off for the time being + $this->_logError($response); + $clear_responses = true; // don't break out of the loop yet, so we can read the remaining responses + break; + default: + if ($fclose_check) { + fclose($fp); + } + user_error('Expected SSH_FX_DATA or SSH_FXP_STATUS'); + } + $response = null; + } + + if ($clear_responses) { + break; + } + } + + if ($length > 0 && $length <= $offset - $start) { + if ($local_file === false) { + $content = substr($content, 0, $length); + } else { + ftruncate($fp, $length + $res_offset); + } + } + + if ($fclose_check) { + fclose($fp); + } + + if (!$this->_close_handle($handle)) { + return false; + } + + // if $content isn't set that means a file was written to + return isset($content) ? $content : true; + } + + /** + * Deletes a file on the SFTP server. + * + * @param string $path + * @param bool $recursive + * @return bool + * @access public + */ + function delete($path, $recursive = true) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + if (is_object($path)) { + // It's an object. Cast it as string before we check anything else. + $path = (string) $path; + } + + if (!is_string($path) || $path == '') { + return false; + } + + $path = $this->_realpath($path); + if ($path === false) { + return false; + } + + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 + if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($path), $path))) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + if (!$recursive) { + return false; + } + $i = 0; + $result = $this->_delete_recursive($path, $i); + $this->_read_put_responses($i); + return $result; + } + + $this->_remove_from_stat_cache($path); + + return true; + } + + /** + * Recursively deletes directories on the SFTP server + * + * Minimizes directory lookups and SSH_FXP_STATUS requests for speed. + * + * @param string $path + * @param int $i + * @return bool + * @access private + */ + function _delete_recursive($path, &$i) + { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + $entries = $this->_list($path, true); + + // normally $entries would have at least . and .. but it might not if the directories + // permissions didn't allow reading + if (empty($entries)) { + return false; + } + + unset($entries['.'], $entries['..']); + foreach ($entries as $filename => $props) { + if (!isset($props['type'])) { + return false; + } + + $temp = $path . '/' . $filename; + if ($props['type'] == NET_SFTP_TYPE_DIRECTORY) { + if (!$this->_delete_recursive($temp, $i)) { + return false; + } + } else { + if (!$this->_send_sftp_packet(NET_SFTP_REMOVE, pack('Na*', strlen($temp), $temp))) { + return false; + } + $this->_remove_from_stat_cache($temp); + + $i++; + + if ($i >= NET_SFTP_QUEUE_SIZE) { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + } + } + } + + if (!$this->_send_sftp_packet(NET_SFTP_RMDIR, pack('Na*', strlen($path), $path))) { + return false; + } + $this->_remove_from_stat_cache($path); + + $i++; + + if ($i >= NET_SFTP_QUEUE_SIZE) { + if (!$this->_read_put_responses($i)) { + return false; + } + $i = 0; + } + + return true; + } + + /** + * Checks whether a file or directory exists + * + * @param string $path + * @return bool + * @access public + */ + function file_exists($path) + { + if ($this->use_stat_cache) { + $path = $this->_realpath($path); + + $result = $this->_query_stat_cache($path); + + if (isset($result)) { + // return true if $result is an array or if it's an stdClass object + return $result !== false; + } + } + + return $this->stat($path) !== false; + } + + /** + * Tells whether the filename is a directory + * + * @param string $path + * @return bool + * @access public + */ + function is_dir($path) + { + $result = $this->_get_stat_cache_prop($path, 'type'); + if ($result === false) { + return false; + } + return $result === NET_SFTP_TYPE_DIRECTORY; + } + + /** + * Tells whether the filename is a regular file + * + * @param string $path + * @return bool + * @access public + */ + function is_file($path) + { + $result = $this->_get_stat_cache_prop($path, 'type'); + if ($result === false) { + return false; + } + return $result === NET_SFTP_TYPE_REGULAR; + } + + /** + * Tells whether the filename is a symbolic link + * + * @param string $path + * @return bool + * @access public + */ + function is_link($path) + { + $result = $this->_get_lstat_cache_prop($path, 'type'); + if ($result === false) { + return false; + } + return $result === NET_SFTP_TYPE_SYMLINK; + } + + /** + * Tells whether a file exists and is readable + * + * @param string $path + * @return bool + * @access public + */ + function is_readable($path) + { + $path = $this->_realpath($path); + + $packet = pack('Na*N2', strlen($path), $path, NET_SFTP_OPEN_READ, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + return true; + case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + } + + /** + * Tells whether the filename is writable + * + * @param string $path + * @return bool + * @access public + */ + function is_writable($path) + { + $path = $this->_realpath($path); + + $packet = pack('Na*N2', strlen($path), $path, NET_SFTP_OPEN_WRITE, 0); + if (!$this->_send_sftp_packet(NET_SFTP_OPEN, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + switch ($this->packet_type) { + case NET_SFTP_HANDLE: + return true; + case NET_SFTP_STATUS: // presumably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + return false; + default: + user_error('Expected SSH_FXP_HANDLE or SSH_FXP_STATUS'); + return false; + } + } + + /** + * Tells whether the filename is writeable + * + * Alias of is_writable + * + * @param string $path + * @return bool + * @access public + */ + function is_writeable($path) + { + return $this->is_writable($path); + } + + /** + * Gets last access time of file + * + * @param string $path + * @return mixed + * @access public + */ + function fileatime($path) + { + return $this->_get_stat_cache_prop($path, 'atime'); + } + + /** + * Gets file modification time + * + * @param string $path + * @return mixed + * @access public + */ + function filemtime($path) + { + return $this->_get_stat_cache_prop($path, 'mtime'); + } + + /** + * Gets file permissions + * + * @param string $path + * @return mixed + * @access public + */ + function fileperms($path) + { + return $this->_get_stat_cache_prop($path, 'permissions'); + } + + /** + * Gets file owner + * + * @param string $path + * @return mixed + * @access public + */ + function fileowner($path) + { + return $this->_get_stat_cache_prop($path, 'uid'); + } + + /** + * Gets file group + * + * @param string $path + * @return mixed + * @access public + */ + function filegroup($path) + { + return $this->_get_stat_cache_prop($path, 'gid'); + } + + /** + * Gets file size + * + * @param string $path + * @return mixed + * @access public + */ + function filesize($path) + { + return $this->_get_stat_cache_prop($path, 'size'); + } + + /** + * Gets file type + * + * @param string $path + * @return mixed + * @access public + */ + function filetype($path) + { + $type = $this->_get_stat_cache_prop($path, 'type'); + if ($type === false) { + return false; + } + + switch ($type) { + case NET_SFTP_TYPE_BLOCK_DEVICE: + return 'block'; + case NET_SFTP_TYPE_CHAR_DEVICE: + return 'char'; + case NET_SFTP_TYPE_DIRECTORY: + return 'dir'; + case NET_SFTP_TYPE_FIFO: + return 'fifo'; + case NET_SFTP_TYPE_REGULAR: + return 'file'; + case NET_SFTP_TYPE_SYMLINK: + return 'link'; + default: + return false; + } + } + + /** + * Return a stat properity + * + * Uses cache if appropriate. + * + * @param string $path + * @param string $prop + * @return mixed + * @access private + */ + function _get_stat_cache_prop($path, $prop) + { + return $this->_get_xstat_cache_prop($path, $prop, 'stat'); + } + + /** + * Return an lstat properity + * + * Uses cache if appropriate. + * + * @param string $path + * @param string $prop + * @return mixed + * @access private + */ + function _get_lstat_cache_prop($path, $prop) + { + return $this->_get_xstat_cache_prop($path, $prop, 'lstat'); + } + + /** + * Return a stat or lstat properity + * + * Uses cache if appropriate. + * + * @param string $path + * @param string $prop + * @return mixed + * @access private + */ + function _get_xstat_cache_prop($path, $prop, $type) + { + if ($this->use_stat_cache) { + $path = $this->_realpath($path); + + $result = $this->_query_stat_cache($path); + + if (is_object($result) && isset($result->$type)) { + return $result->{$type}[$prop]; + } + } + + $result = $this->$type($path); + + if ($result === false || !isset($result[$prop])) { + return false; + } + + return $result[$prop]; + } + + /** + * Renames a file or a directory on the SFTP server + * + * @param string $oldname + * @param string $newname + * @return bool + * @access public + */ + function rename($oldname, $newname) + { + if (!($this->bitmap & NET_SSH2_MASK_LOGIN)) { + return false; + } + + $oldname = $this->_realpath($oldname); + $newname = $this->_realpath($newname); + if ($oldname === false || $newname === false) { + return false; + } + + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-13#section-8.3 + $packet = pack('Na*Na*', strlen($oldname), $oldname, strlen($newname), $newname); + if (!$this->_send_sftp_packet(NET_SFTP_RENAME, $packet)) { + return false; + } + + $response = $this->_get_sftp_packet(); + if ($this->packet_type != NET_SFTP_STATUS) { + user_error('Expected SSH_FXP_STATUS'); + return false; + } + + // if $status isn't SSH_FX_OK it's probably SSH_FX_NO_SUCH_FILE or SSH_FX_PERMISSION_DENIED + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nstatus', $this->_string_shift($response, 4))); + if ($status != NET_SFTP_STATUS_OK) { + $this->_logError($response, $status); + return false; + } + + // don't move the stat cache entry over since this operation could very well change the + // atime and mtime attributes + //$this->_update_stat_cache($newname, $this->_query_stat_cache($oldname)); + $this->_remove_from_stat_cache($oldname); + $this->_remove_from_stat_cache($newname); + + return true; + } + + /** + * Parse Attributes + * + * See '7. File Attributes' of draft-ietf-secsh-filexfer-13 for more info. + * + * @param string $response + * @return array + * @access private + */ + function _parseAttributes(&$response) + { + $attr = array(); + if (strlen($response) < 4) { + user_error('Malformed file attributes'); + return array(); + } + extract(unpack('Nflags', $this->_string_shift($response, 4))); + // SFTPv4+ have a type field (a byte) that follows the above flag field + foreach ($this->attributes as $key => $value) { + switch ($flags & $key) { + case NET_SFTP_ATTR_SIZE: // 0x00000001 + // The size attribute is defined as an unsigned 64-bit integer. + // The following will use floats on 32-bit platforms, if necessary. + // As can be seen in the BigInteger class, floats are generally + // IEEE 754 binary64 "double precision" on such platforms and + // as such can represent integers of at least 2^50 without loss + // of precision. Interpreted in filesize, 2^50 bytes = 1024 TiB. + $attr['size'] = hexdec(bin2hex($this->_string_shift($response, 8))); + break; + case NET_SFTP_ATTR_UIDGID: // 0x00000002 (SFTPv3 only) + if (strlen($response) < 8) { + user_error('Malformed file attributes'); + return $attr; + } + $attr+= unpack('Nuid/Ngid', $this->_string_shift($response, 8)); + break; + case NET_SFTP_ATTR_PERMISSIONS: // 0x00000004 + if (strlen($response) < 4) { + user_error('Malformed file attributes'); + return $attr; + } + $attr+= unpack('Npermissions', $this->_string_shift($response, 4)); + // mode == permissions; permissions was the original array key and is retained for bc purposes. + // mode was added because that's the more industry standard terminology + $attr+= array('mode' => $attr['permissions']); + $fileType = $this->_parseMode($attr['permissions']); + if ($fileType !== false) { + $attr+= array('type' => $fileType); + } + break; + case NET_SFTP_ATTR_ACCESSTIME: // 0x00000008 + if (strlen($response) < 8) { + user_error('Malformed file attributes'); + return $attr; + } + $attr+= unpack('Natime/Nmtime', $this->_string_shift($response, 8)); + break; + case NET_SFTP_ATTR_EXTENDED: // 0x80000000 + if (strlen($response) < 4) { + user_error('Malformed file attributes'); + return $attr; + } + extract(unpack('Ncount', $this->_string_shift($response, 4))); + for ($i = 0; $i < $count; $i++) { + if (strlen($response) < 4) { + user_error('Malformed file attributes'); + return $attr; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $key = $this->_string_shift($response, $length); + if (strlen($response) < 4) { + user_error('Malformed file attributes'); + return $attr; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $attr[$key] = $this->_string_shift($response, $length); + } + } + } + return $attr; + } + + /** + * Attempt to identify the file type + * + * Quoting the SFTP RFC, "Implementations MUST NOT send bits that are not defined" but they seem to anyway + * + * @param int $mode + * @return int + * @access private + */ + function _parseMode($mode) + { + // values come from http://lxr.free-electrons.com/source/include/uapi/linux/stat.h#L12 + // see, also, http://linux.die.net/man/2/stat + switch ($mode & 0170000) {// ie. 1111 0000 0000 0000 + case 0000000: // no file type specified - figure out the file type using alternative means + return false; + case 0040000: + return NET_SFTP_TYPE_DIRECTORY; + case 0100000: + return NET_SFTP_TYPE_REGULAR; + case 0120000: + return NET_SFTP_TYPE_SYMLINK; + // new types introduced in SFTPv5+ + // http://tools.ietf.org/html/draft-ietf-secsh-filexfer-05#section-5.2 + case 0010000: // named pipe (fifo) + return NET_SFTP_TYPE_FIFO; + case 0020000: // character special + return NET_SFTP_TYPE_CHAR_DEVICE; + case 0060000: // block special + return NET_SFTP_TYPE_BLOCK_DEVICE; + case 0140000: // socket + return NET_SFTP_TYPE_SOCKET; + case 0160000: // whiteout + // "SPECIAL should be used for files that are of + // a known type which cannot be expressed in the protocol" + return NET_SFTP_TYPE_SPECIAL; + default: + return NET_SFTP_TYPE_UNKNOWN; + } + } + + /** + * Parse Longname + * + * SFTPv3 doesn't provide any easy way of identifying a file type. You could try to open + * a file as a directory and see if an error is returned or you could try to parse the + * SFTPv3-specific longname field of the SSH_FXP_NAME packet. That's what this function does. + * The result is returned using the + * {@link http://tools.ietf.org/html/draft-ietf-secsh-filexfer-04#section-5.2 SFTPv4 type constants}. + * + * If the longname is in an unrecognized format bool(false) is returned. + * + * @param string $longname + * @return mixed + * @access private + */ + function _parseLongname($longname) + { + // http://en.wikipedia.org/wiki/Unix_file_types + // http://en.wikipedia.org/wiki/Filesystem_permissions#Notation_of_traditional_Unix_permissions + if (preg_match('#^[^/]([r-][w-][xstST-]){3}#', $longname)) { + switch ($longname[0]) { + case '-': + return NET_SFTP_TYPE_REGULAR; + case 'd': + return NET_SFTP_TYPE_DIRECTORY; + case 'l': + return NET_SFTP_TYPE_SYMLINK; + default: + return NET_SFTP_TYPE_SPECIAL; + } + } + + return false; + } + + /** + * Sends SFTP Packets + * + * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info. + * + * @param int $type + * @param string $data + * @see self::_get_sftp_packet() + * @see Net_SSH2::_send_channel_packet() + * @return bool + * @access private + */ + function _send_sftp_packet($type, $data) + { + $packet = $this->request_id !== false ? + pack('NCNa*', strlen($data) + 5, $type, $this->request_id, $data) : + pack('NCa*', strlen($data) + 1, $type, $data); + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $result = $this->_send_channel_packet(NET_SFTP_CHANNEL, $packet); + $stop = strtok(microtime(), ' ') + strtok(''); + + if (defined('NET_SFTP_LOGGING')) { + $packet_type = '-> ' . $this->packet_types[$type] . + ' (' . round($stop - $start, 4) . 's)'; + if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) { + echo "
\r\n" . $this->_format_log(array($data), array($packet_type)) . "\r\n
\r\n"; + flush(); + ob_flush(); + } else { + $this->packet_type_log[] = $packet_type; + if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) { + $this->packet_log[] = $data; + } + } + } + + return $result; + } + + /** + * Receives SFTP Packets + * + * See '6. General Packet Format' of draft-ietf-secsh-filexfer-13 for more info. + * + * Incidentally, the number of SSH_MSG_CHANNEL_DATA messages has no bearing on the number of SFTP packets present. + * There can be one SSH_MSG_CHANNEL_DATA messages containing two SFTP packets or there can be two SSH_MSG_CHANNEL_DATA + * messages containing one SFTP packet. + * + * @see self::_send_sftp_packet() + * @return string + * @access private + */ + function _get_sftp_packet() + { + $this->curTimeout = false; + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + + // SFTP packet length + while (strlen($this->packet_buffer) < 4) { + $temp = $this->_get_channel_packet(NET_SFTP_CHANNEL, true); + if (is_bool($temp)) { + $this->packet_type = false; + $this->packet_buffer = ''; + return false; + } + $this->packet_buffer.= $temp; + } + if (strlen($this->packet_buffer) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($this->packet_buffer, 4))); + $tempLength = $length; + $tempLength-= strlen($this->packet_buffer); + + // SFTP packet type and data payload + while ($tempLength > 0) { + $temp = $this->_get_channel_packet(NET_SFTP_CHANNEL, true); + if (is_bool($temp)) { + $this->packet_type = false; + $this->packet_buffer = ''; + return false; + } + $this->packet_buffer.= $temp; + $tempLength-= strlen($temp); + } + + $stop = strtok(microtime(), ' ') + strtok(''); + + $this->packet_type = ord($this->_string_shift($this->packet_buffer)); + + if ($this->request_id !== false) { + $this->_string_shift($this->packet_buffer, 4); // remove the request id + $length-= 5; // account for the request id and the packet type + } else { + $length-= 1; // account for the packet type + } + + $packet = $this->_string_shift($this->packet_buffer, $length); + + if (defined('NET_SFTP_LOGGING')) { + $packet_type = '<- ' . $this->packet_types[$this->packet_type] . + ' (' . round($stop - $start, 4) . 's)'; + if (NET_SFTP_LOGGING == NET_SFTP_LOG_REALTIME) { + echo "
\r\n" . $this->_format_log(array($packet), array($packet_type)) . "\r\n
\r\n"; + flush(); + ob_flush(); + } else { + $this->packet_type_log[] = $packet_type; + if (NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX) { + $this->packet_log[] = $packet; + } + } + } + + return $packet; + } + + /** + * Returns a log of the packets that have been sent and received. + * + * Returns a string if NET_SFTP_LOGGING == NET_SFTP_LOG_COMPLEX, an array if NET_SFTP_LOGGING == NET_SFTP_LOG_SIMPLE and false if !defined('NET_SFTP_LOGGING') + * + * @access public + * @return string or Array + */ + function getSFTPLog() + { + if (!defined('NET_SFTP_LOGGING')) { + return false; + } + + switch (NET_SFTP_LOGGING) { + case NET_SFTP_LOG_COMPLEX: + return $this->_format_log($this->packet_log, $this->packet_type_log); + break; + //case NET_SFTP_LOG_SIMPLE: + default: + return $this->packet_type_log; + } + } + + /** + * Returns all errors + * + * @return array + * @access public + */ + function getSFTPErrors() + { + return $this->sftp_errors; + } + + /** + * Returns the last error + * + * @return string + * @access public + */ + function getLastSFTPError() + { + return count($this->sftp_errors) ? $this->sftp_errors[count($this->sftp_errors) - 1] : ''; + } + + /** + * Get supported SFTP versions + * + * @return array + * @access public + */ + function getSupportedVersions() + { + $temp = array('version' => $this->version); + if (isset($this->extensions['versions'])) { + $temp['extensions'] = $this->extensions['versions']; + } + return $temp; + } + + /** + * Disconnect + * + * @param int $reason + * @return bool + * @access private + */ + function _disconnect($reason) + { + $this->pwd = false; + parent::_disconnect($reason); + } +} diff --git a/ipaylinks_statement/Net/SFTP/Stream.php b/ipaylinks_statement/Net/SFTP/Stream.php new file mode 100644 index 00000000..a944d7f0 --- /dev/null +++ b/ipaylinks_statement/Net/SFTP/Stream.php @@ -0,0 +1,815 @@ + + * @copyright 2013 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/** + * SFTP Stream Wrapper + * + * @package Net_SFTP_Stream + * @author Jim Wigginton + * @access public + */ +class Net_SFTP_Stream +{ + /** + * SFTP instances + * + * Rather than re-create the connection we re-use instances if possible + * + * @var array + */ + static $instances; + + /** + * SFTP instance + * + * @var object + * @access private + */ + var $sftp; + + /** + * Path + * + * @var string + * @access private + */ + var $path; + + /** + * Mode + * + * @var string + * @access private + */ + var $mode; + + /** + * Position + * + * @var int + * @access private + */ + var $pos; + + /** + * Size + * + * @var int + * @access private + */ + var $size; + + /** + * Directory entries + * + * @var array + * @access private + */ + var $entries; + + /** + * EOF flag + * + * @var bool + * @access private + */ + var $eof; + + /** + * Context resource + * + * Technically this needs to be publically accessible so PHP can set it directly + * + * @var resource + * @access public + */ + var $context; + + /** + * Notification callback function + * + * @var callable + * @access public + */ + var $notification; + + /** + * Registers this class as a URL wrapper. + * + * @param string $protocol The wrapper name to be registered. + * @return bool True on success, false otherwise. + * @access public + */ + static function register($protocol = 'sftp') + { + if (in_array($protocol, stream_get_wrappers(), true)) { + return false; + } + $class = function_exists('get_called_class') ? get_called_class() : __CLASS__; + return stream_wrapper_register($protocol, $class); + } + + /** + * The Constructor + * + * @access public + */ + function __construct() + { + if (defined('NET_SFTP_STREAM_LOGGING')) { + echo "__construct()\r\n"; + } + + if (!class_exists('Net_SFTP')) { + include_once 'Net/SFTP.php'; + } + } + + /** + * Path Parser + * + * Extract a path from a URI and actually connect to an SSH server if appropriate + * + * If "notification" is set as a context parameter the message code for successful login is + * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE. + * + * @param string $path + * @return string + * @access private + */ + function _parse_path($path) + { + $orig = $path; + extract(parse_url($path) + array('port' => 22)); + if (isset($query)) { + $path.= '?' . $query; + } elseif (preg_match('/(\?|\?#)$/', $orig)) { + $path.= '?'; + } + if (isset($fragment)) { + $path.= '#' . $fragment; + } elseif ($orig[strlen($orig) - 1] == '#') { + $path.= '#'; + } + + if (!isset($host)) { + return false; + } + + if (isset($this->context)) { + $context = stream_context_get_params($this->context); + if (isset($context['notification'])) { + $this->notification = $context['notification']; + } + } + + if ($host[0] == '$') { + $host = substr($host, 1); + global $$host; + if (!is_object($$host) || get_class($$host) != 'Net_SFTP') { + return false; + } + $this->sftp = $$host; + } else { + if (isset($this->context)) { + $context = stream_context_get_options($this->context); + } + if (isset($context[$scheme]['session'])) { + $sftp = $context[$scheme]['session']; + } + if (isset($context[$scheme]['sftp'])) { + $sftp = $context[$scheme]['sftp']; + } + if (isset($sftp) && is_object($sftp) && get_class($sftp) == 'Net_SFTP') { + $this->sftp = $sftp; + return $path; + } + if (isset($context[$scheme]['username'])) { + $user = $context[$scheme]['username']; + } + if (isset($context[$scheme]['password'])) { + $pass = $context[$scheme]['password']; + } + if (isset($context[$scheme]['privkey']) && is_object($context[$scheme]['privkey']) && get_Class($context[$scheme]['privkey']) == 'Crypt_RSA') { + $pass = $context[$scheme]['privkey']; + } + + if (!isset($user) || !isset($pass)) { + return false; + } + + // casting $pass to a string is necessary in the event that it's a Crypt_RSA object + if (isset(self::$instances[$host][$port][$user][(string) $pass])) { + $this->sftp = self::$instances[$host][$port][$user][(string) $pass]; + } else { + $this->sftp = new Net_SFTP($host, $port); + $this->sftp->disableStatCache(); + if (isset($this->notification) && is_callable($this->notification)) { + /* if !is_callable($this->notification) we could do this: + + user_error('fopen(): failed to call user notifier', E_USER_WARNING); + + the ftp wrapper gives errors like that when the notifier isn't callable. + i've opted not to do that, however, since the ftp wrapper gives the line + on which the fopen occurred as the line number - not the line that the + user_error is on. + */ + call_user_func($this->notification, STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0); + call_user_func($this->notification, STREAM_NOTIFY_AUTH_REQUIRED, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0); + if (!$this->sftp->login($user, $pass)) { + call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_ERR, 'Login Failure', NET_SSH2_MSG_USERAUTH_FAILURE, 0, 0); + return false; + } + call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_INFO, 'Login Success', NET_SSH2_MSG_USERAUTH_SUCCESS, 0, 0); + } else { + if (!$this->sftp->login($user, $pass)) { + return false; + } + } + self::$instances[$host][$port][$user][(string) $pass] = $this->sftp; + } + } + + return $path; + } + + /** + * Opens file or URL + * + * @param string $path + * @param string $mode + * @param int $options + * @param string $opened_path + * @return bool + * @access public + */ + function _stream_open($path, $mode, $options, &$opened_path) + { + $path = $this->_parse_path($path); + + if ($path === false) { + return false; + } + $this->path = $path; + + $this->size = $this->sftp->size($path); + $this->mode = preg_replace('#[bt]$#', '', $mode); + $this->eof = false; + + if ($this->size === false) { + if ($this->mode[0] == 'r') { + return false; + } else { + $this->sftp->touch($path); + $this->size = 0; + } + } else { + switch ($this->mode[0]) { + case 'x': + return false; + case 'w': + $this->sftp->truncate($path, 0); + $this->size = 0; + } + } + + $this->pos = $this->mode[0] != 'a' ? 0 : $this->size; + + return true; + } + + /** + * Read from stream + * + * @param int $count + * @return mixed + * @access public + */ + function _stream_read($count) + { + switch ($this->mode) { + case 'w': + case 'a': + case 'x': + case 'c': + return false; + } + + // commented out because some files - eg. /dev/urandom - will say their size is 0 when in fact it's kinda infinite + //if ($this->pos >= $this->size) { + // $this->eof = true; + // return false; + //} + + $result = $this->sftp->get($this->path, false, $this->pos, $count); + if (isset($this->notification) && is_callable($this->notification)) { + if ($result === false) { + call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0); + return 0; + } + // seems that PHP calls stream_read in 8k chunks + call_user_func($this->notification, STREAM_NOTIFY_PROGRESS, STREAM_NOTIFY_SEVERITY_INFO, '', 0, strlen($result), $this->size); + } + + if (empty($result)) { // ie. false or empty string + $this->eof = true; + return false; + } + $this->pos+= strlen($result); + + return $result; + } + + /** + * Write to stream + * + * @param string $data + * @return mixed + * @access public + */ + function _stream_write($data) + { + switch ($this->mode) { + case 'r': + return false; + } + + $result = $this->sftp->put($this->path, $data, NET_SFTP_STRING, $this->pos); + if (isset($this->notification) && is_callable($this->notification)) { + if (!$result) { + call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0); + return 0; + } + // seems that PHP splits up strings into 8k blocks before calling stream_write + call_user_func($this->notification, STREAM_NOTIFY_PROGRESS, STREAM_NOTIFY_SEVERITY_INFO, '', 0, strlen($data), strlen($data)); + } + + if ($result === false) { + return false; + } + $this->pos+= strlen($data); + if ($this->pos > $this->size) { + $this->size = $this->pos; + } + $this->eof = false; + return strlen($data); + } + + /** + * Retrieve the current position of a stream + * + * @return int + * @access public + */ + function _stream_tell() + { + return $this->pos; + } + + /** + * Tests for end-of-file on a file pointer + * + * In my testing there are four classes functions that normally effect the pointer: + * fseek, fputs / fwrite, fgets / fread and ftruncate. + * + * Only fgets / fread, however, results in feof() returning true. do fputs($fp, 'aaa') on a blank file and feof() + * will return false. do fread($fp, 1) and feof() will then return true. do fseek($fp, 10) on ablank file and feof() + * will return false. do fread($fp, 1) and feof() will then return true. + * + * @return bool + * @access public + */ + function _stream_eof() + { + return $this->eof; + } + + /** + * Seeks to specific location in a stream + * + * @param int $offset + * @param int $whence + * @return bool + * @access public + */ + function _stream_seek($offset, $whence) + { + switch ($whence) { + case SEEK_SET: + if ($offset >= $this->size || $offset < 0) { + return false; + } + break; + case SEEK_CUR: + $offset+= $this->pos; + break; + case SEEK_END: + $offset+= $this->size; + } + + $this->pos = $offset; + $this->eof = false; + return true; + } + + /** + * Change stream options + * + * @param string $path + * @param int $option + * @param mixed $var + * @return bool + * @access public + */ + function _stream_metadata($path, $option, $var) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + + // stream_metadata was introduced in PHP 5.4.0 but as of 5.4.11 the constants haven't been defined + // see http://www.php.net/streamwrapper.stream-metadata and https://bugs.php.net/64246 + // and https://github.com/php/php-src/blob/master/main/php_streams.h#L592 + switch ($option) { + case 1: // PHP_STREAM_META_TOUCH + return $this->sftp->touch($path, $var[0], $var[1]); + case 2: // PHP_STREAM_OWNER_NAME + case 3: // PHP_STREAM_GROUP_NAME + return false; + case 4: // PHP_STREAM_META_OWNER + return $this->sftp->chown($path, $var); + case 5: // PHP_STREAM_META_GROUP + return $this->sftp->chgrp($path, $var); + case 6: // PHP_STREAM_META_ACCESS + return $this->sftp->chmod($path, $var) !== false; + } + } + + /** + * Retrieve the underlaying resource + * + * @param int $cast_as + * @return resource + * @access public + */ + function _stream_cast($cast_as) + { + return $this->sftp->fsock; + } + + /** + * Advisory file locking + * + * @param int $operation + * @return bool + * @access public + */ + function _stream_lock($operation) + { + return false; + } + + /** + * Renames a file or directory + * + * Attempts to rename oldname to newname, moving it between directories if necessary. + * If newname exists, it will be overwritten. This is a departure from what Net_SFTP + * does. + * + * @param string $path_from + * @param string $path_to + * @return bool + * @access public + */ + function _rename($path_from, $path_to) + { + $path1 = parse_url($path_from); + $path2 = parse_url($path_to); + unset($path1['path'], $path2['path']); + if ($path1 != $path2) { + return false; + } + + $path_from = $this->_parse_path($path_from); + $path_to = parse_url($path_to); + if ($path_from === false) { + return false; + } + + $path_to = $path_to['path']; // the $component part of parse_url() was added in PHP 5.1.2 + // "It is an error if there already exists a file with the name specified by newpath." + // -- http://tools.ietf.org/html/draft-ietf-secsh-filexfer-02#section-6.5 + if (!$this->sftp->rename($path_from, $path_to)) { + if ($this->sftp->stat($path_to)) { + return $this->sftp->delete($path_to, true) && $this->sftp->rename($path_from, $path_to); + } + return false; + } + + return true; + } + + /** + * Open directory handle + * + * The only $options is "whether or not to enforce safe_mode (0x04)". Since safe mode was deprecated in 5.3 and + * removed in 5.4 I'm just going to ignore it. + * + * Also, nlist() is the best that this function is realistically going to be able to do. When an SFTP client + * sends a SSH_FXP_READDIR packet you don't generally get info on just one file but on multiple files. Quoting + * the SFTP specs: + * + * The SSH_FXP_NAME response has the following format: + * + * uint32 id + * uint32 count + * repeats count times: + * string filename + * string longname + * ATTRS attrs + * + * @param string $path + * @param int $options + * @return bool + * @access public + */ + function _dir_opendir($path, $options) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + $this->pos = 0; + $this->entries = $this->sftp->nlist($path); + return $this->entries !== false; + } + + /** + * Read entry from directory handle + * + * @return mixed + * @access public + */ + function _dir_readdir() + { + if (isset($this->entries[$this->pos])) { + return $this->entries[$this->pos++]; + } + return false; + } + + /** + * Rewind directory handle + * + * @return bool + * @access public + */ + function _dir_rewinddir() + { + $this->pos = 0; + return true; + } + + /** + * Close directory handle + * + * @return bool + * @access public + */ + function _dir_closedir() + { + return true; + } + + /** + * Create a directory + * + * Only valid $options is STREAM_MKDIR_RECURSIVE + * + * @param string $path + * @param int $mode + * @param int $options + * @return bool + * @access public + */ + function _mkdir($path, $mode, $options) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + + return $this->sftp->mkdir($path, $mode, $options & STREAM_MKDIR_RECURSIVE); + } + + /** + * Removes a directory + * + * Only valid $options is STREAM_MKDIR_RECURSIVE per , however, + * does not have a $recursive parameter as mkdir() does so I don't know how + * STREAM_MKDIR_RECURSIVE is supposed to be set. Also, when I try it out with rmdir() I get 8 as + * $options. What does 8 correspond to? + * + * @param string $path + * @param int $mode + * @param int $options + * @return bool + * @access public + */ + function _rmdir($path, $options) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + + return $this->sftp->rmdir($path); + } + + /** + * Flushes the output + * + * See . Always returns true because Net_SFTP doesn't cache stuff before writing + * + * @return bool + * @access public + */ + function _stream_flush() + { + return true; + } + + /** + * Retrieve information about a file resource + * + * @return mixed + * @access public + */ + function _stream_stat() + { + $results = $this->sftp->stat($this->path); + if ($results === false) { + return false; + } + return $results; + } + + /** + * Delete a file + * + * @param string $path + * @return bool + * @access public + */ + function _unlink($path) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + + return $this->sftp->delete($path, false); + } + + /** + * Retrieve information about a file + * + * Ignores the STREAM_URL_STAT_QUIET flag because the entirety of Net_SFTP_Stream is quiet by default + * might be worthwhile to reconstruct bits 12-16 (ie. the file type) if mode doesn't have them but we'll + * cross that bridge when and if it's reached + * + * @param string $path + * @param int $flags + * @return mixed + * @access public + */ + function _url_stat($path, $flags) + { + $path = $this->_parse_path($path); + if ($path === false) { + return false; + } + + $results = $flags & STREAM_URL_STAT_LINK ? $this->sftp->lstat($path) : $this->sftp->stat($path); + if ($results === false) { + return false; + } + + return $results; + } + + /** + * Truncate stream + * + * @param int $new_size + * @return bool + * @access public + */ + function _stream_truncate($new_size) + { + if (!$this->sftp->truncate($this->path, $new_size)) { + return false; + } + + $this->eof = false; + $this->size = $new_size; + + return true; + } + + /** + * Change stream options + * + * STREAM_OPTION_WRITE_BUFFER isn't supported for the same reason stream_flush isn't. + * The other two aren't supported because of limitations in Net_SFTP. + * + * @param int $option + * @param int $arg1 + * @param int $arg2 + * @return bool + * @access public + */ + function _stream_set_option($option, $arg1, $arg2) + { + return false; + } + + /** + * Close an resource + * + * @access public + */ + function _stream_close() + { + } + + /** + * __call Magic Method + * + * When you're utilizing an SFTP stream you're not calling the methods in this class directly - PHP is calling them for you. + * Which kinda begs the question... what methods is PHP calling and what parameters is it passing to them? This function + * lets you figure that out. + * + * If NET_SFTP_STREAM_LOGGING is defined all calls will be output on the screen and then (regardless of whether or not + * NET_SFTP_STREAM_LOGGING is enabled) the parameters will be passed through to the appropriate method. + * + * @param string + * @param array + * @return mixed + * @access public + */ + function __call($name, $arguments) + { + if (defined('NET_SFTP_STREAM_LOGGING')) { + echo $name . '('; + $last = count($arguments) - 1; + foreach ($arguments as $i => $argument) { + var_export($argument); + if ($i != $last) { + echo ','; + } + } + echo ")\r\n"; + } + $name = '_' . $name; + if (!method_exists($this, $name)) { + return false; + } + return call_user_func_array(array($this, $name), $arguments); + } +} + +Net_SFTP_Stream::register(); diff --git a/ipaylinks_statement/Net/SSH1.php b/ipaylinks_statement/Net/SSH1.php new file mode 100644 index 00000000..55473d08 --- /dev/null +++ b/ipaylinks_statement/Net/SSH1.php @@ -0,0 +1,1691 @@ + + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * echo $ssh->exec('ls -la'); + * ?> + * + * + * Here's another short example: + * + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * echo $ssh->read('username@username:~$'); + * $ssh->write("ls -la\n"); + * echo $ssh->read('username@username:~$'); + * ?> + * + * + * More information on the SSHv1 specification can be found by reading + * {@link http://www.snailbook.com/docs/protocol-1.5.txt protocol-1.5.txt}. + * + * LICENSE: 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. + * + * @category Net + * @package Net_SSH1 + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * Encryption Methods + * + * @see self::getSupportedCiphers() + * @access public + */ +/** + * No encryption + * + * Not supported. + */ +define('NET_SSH1_CIPHER_NONE', 0); +/** + * IDEA in CFB mode + * + * Not supported. + */ +define('NET_SSH1_CIPHER_IDEA', 1); +/** + * DES in CBC mode + */ +define('NET_SSH1_CIPHER_DES', 2); +/** + * Triple-DES in CBC mode + * + * All implementations are required to support this + */ +define('NET_SSH1_CIPHER_3DES', 3); +/** + * TRI's Simple Stream encryption CBC + * + * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, does define it (see cipher.h), + * although it doesn't use it (see cipher.c) + */ +define('NET_SSH1_CIPHER_BROKEN_TSS', 4); +/** + * RC4 + * + * Not supported. + * + * @internal According to the SSH1 specs: + * + * "The first 16 bytes of the session key are used as the key for + * the server to client direction. The remaining 16 bytes are used + * as the key for the client to server direction. This gives + * independent 128-bit keys for each direction." + * + * This library currently only supports encryption when the same key is being used for both directions. This is + * because there's only one $crypto object. Two could be added ($encrypt and $decrypt, perhaps). + */ +define('NET_SSH1_CIPHER_RC4', 5); +/** + * Blowfish + * + * Not supported nor is it defined in the official SSH1 specs. OpenSSH, however, defines it (see cipher.h) and + * uses it (see cipher.c) + */ +define('NET_SSH1_CIPHER_BLOWFISH', 6); +/**#@-*/ + +/**#@+ + * Authentication Methods + * + * @see self::getSupportedAuthentications() + * @access public + */ +/** + * .rhosts or /etc/hosts.equiv + */ +define('NET_SSH1_AUTH_RHOSTS', 1); +/** + * pure RSA authentication + */ +define('NET_SSH1_AUTH_RSA', 2); +/** + * password authentication + * + * This is the only method that is supported by this library. + */ +define('NET_SSH1_AUTH_PASSWORD', 3); +/** + * .rhosts with RSA host authentication + */ +define('NET_SSH1_AUTH_RHOSTS_RSA', 4); +/**#@-*/ + +/**#@+ + * Terminal Modes + * + * @link http://3sp.com/content/developer/maverick-net/docs/Maverick.SSH.PseudoTerminalModesMembers.html + * @access private + */ +define('NET_SSH1_TTY_OP_END', 0); +/**#@-*/ + +/** + * The Response Type + * + * @see self::_get_binary_packet() + * @access private + */ +define('NET_SSH1_RESPONSE_TYPE', 1); + +/** + * The Response Data + * + * @see self::_get_binary_packet() + * @access private + */ +define('NET_SSH1_RESPONSE_DATA', 2); + +/**#@+ + * Execution Bitmap Masks + * + * @see self::bitmap + * @access private + */ +define('NET_SSH1_MASK_CONSTRUCTOR', 0x00000001); +define('NET_SSH1_MASK_CONNECTED', 0x00000002); +define('NET_SSH1_MASK_LOGIN', 0x00000004); +define('NET_SSH1_MASK_SHELL', 0x00000008); +/**#@-*/ + +/**#@+ + * @access public + * @see self::getLog() + */ +/** + * Returns the message numbers + */ +define('NET_SSH1_LOG_SIMPLE', 1); +/** + * Returns the message content + */ +define('NET_SSH1_LOG_COMPLEX', 2); +/** + * Outputs the content real-time + */ +define('NET_SSH1_LOG_REALTIME', 3); +/** + * Dumps the content real-time to a file + */ +define('NET_SSH1_LOG_REALTIME_FILE', 4); +/**#@-*/ + +/**#@+ + * @access public + * @see self::read() + */ +/** + * Returns when a string matching $expect exactly is found + */ +define('NET_SSH1_READ_SIMPLE', 1); +/** + * Returns when a string matching the regular expression $expect is found + */ +define('NET_SSH1_READ_REGEX', 2); +/**#@-*/ + +/** + * Pure-PHP implementation of SSHv1. + * + * @package Net_SSH1 + * @author Jim Wigginton + * @access public + */ +class Net_SSH1 +{ + /** + * The SSH identifier + * + * @var string + * @access private + */ + var $identifier = 'SSH-1.5-phpseclib'; + + /** + * The Socket Object + * + * @var object + * @access private + */ + var $fsock; + + /** + * The cryptography object + * + * @var object + * @access private + */ + var $crypto = false; + + /** + * Execution Bitmap + * + * The bits that are set represent functions that have been called already. This is used to determine + * if a requisite function has been successfully executed. If not, an error should be thrown. + * + * @var int + * @access private + */ + var $bitmap = 0; + + /** + * The Server Key Public Exponent + * + * Logged for debug purposes + * + * @see self::getServerKeyPublicExponent() + * @var string + * @access private + */ + var $server_key_public_exponent; + + /** + * The Server Key Public Modulus + * + * Logged for debug purposes + * + * @see self::getServerKeyPublicModulus() + * @var string + * @access private + */ + var $server_key_public_modulus; + + /** + * The Host Key Public Exponent + * + * Logged for debug purposes + * + * @see self::getHostKeyPublicExponent() + * @var string + * @access private + */ + var $host_key_public_exponent; + + /** + * The Host Key Public Modulus + * + * Logged for debug purposes + * + * @see self::getHostKeyPublicModulus() + * @var string + * @access private + */ + var $host_key_public_modulus; + + /** + * Supported Ciphers + * + * Logged for debug purposes + * + * @see self::getSupportedCiphers() + * @var array + * @access private + */ + var $supported_ciphers = array( + NET_SSH1_CIPHER_NONE => 'No encryption', + NET_SSH1_CIPHER_IDEA => 'IDEA in CFB mode', + NET_SSH1_CIPHER_DES => 'DES in CBC mode', + NET_SSH1_CIPHER_3DES => 'Triple-DES in CBC mode', + NET_SSH1_CIPHER_BROKEN_TSS => 'TRI\'s Simple Stream encryption CBC', + NET_SSH1_CIPHER_RC4 => 'RC4', + NET_SSH1_CIPHER_BLOWFISH => 'Blowfish' + ); + + /** + * Supported Authentications + * + * Logged for debug purposes + * + * @see self::getSupportedAuthentications() + * @var array + * @access private + */ + var $supported_authentications = array( + NET_SSH1_AUTH_RHOSTS => '.rhosts or /etc/hosts.equiv', + NET_SSH1_AUTH_RSA => 'pure RSA authentication', + NET_SSH1_AUTH_PASSWORD => 'password authentication', + NET_SSH1_AUTH_RHOSTS_RSA => '.rhosts with RSA host authentication' + ); + + /** + * Server Identification + * + * @see self::getServerIdentification() + * @var string + * @access private + */ + var $server_identification = ''; + + /** + * Protocol Flags + * + * @see self::Net_SSH1() + * @var array + * @access private + */ + var $protocol_flags = array(); + + /** + * Protocol Flag Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $protocol_flag_log = array(); + + /** + * Message Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $message_log = array(); + + /** + * Real-time log file pointer + * + * @see self::_append_log() + * @var resource + * @access private + */ + var $realtime_log_file; + + /** + * Real-time log file size + * + * @see self::_append_log() + * @var int + * @access private + */ + var $realtime_log_size; + + /** + * Real-time log file wrap boolean + * + * @see self::_append_log() + * @var bool + * @access private + */ + var $realtime_log_wrap; + + /** + * Interactive Buffer + * + * @see self::read() + * @var array + * @access private + */ + var $interactiveBuffer = ''; + + /** + * Timeout + * + * @see self::setTimeout() + * @access private + */ + var $timeout; + + /** + * Current Timeout + * + * @see self::_get_channel_packet() + * @access private + */ + var $curTimeout; + + /** + * Log Boundary + * + * @see self::_format_log() + * @access private + */ + var $log_boundary = ':'; + + /** + * Log Long Width + * + * @see self::_format_log() + * @access private + */ + var $log_long_width = 65; + + /** + * Log Short Width + * + * @see self::_format_log() + * @access private + */ + var $log_short_width = 16; + + /** + * Hostname + * + * @see self::Net_SSH1() + * @see self::_connect() + * @var string + * @access private + */ + var $host; + + /** + * Port Number + * + * @see self::Net_SSH1() + * @see self::_connect() + * @var int + * @access private + */ + var $port; + + /** + * Timeout for initial connection + * + * Set by the constructor call. Calling setTimeout() is optional. If it's not called functions like + * exec() won't timeout unless some PHP setting forces it too. The timeout specified in the constructor, + * however, is non-optional. There will be a timeout, whether or not you set it. If you don't it'll be + * 10 seconds. It is used by fsockopen() in that function. + * + * @see self::Net_SSH1() + * @see self::_connect() + * @var int + * @access private + */ + var $connectionTimeout; + + /** + * Default cipher + * + * @see self::Net_SSH1() + * @see self::_connect() + * @var int + * @access private + */ + var $cipher; + + /** + * Default Constructor. + * + * Connects to an SSHv1 server + * + * @param string $host + * @param int $port + * @param int $timeout + * @param int $cipher + * @return Net_SSH1 + * @access public + */ + function __construct($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES) + { + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + + // Include Crypt_Random + // the class_exists() will only be called if the crypt_random_string function hasn't been defined and + // will trigger a call to __autoload() if you're wanting to auto-load classes + // call function_exists() a second time to stop the include_once from being called outside + // of the auto loader + if (!function_exists('crypt_random_string') && !class_exists('Crypt_Random') && !function_exists('crypt_random_string')) { + include_once 'Crypt/Random.php'; + } + + $this->protocol_flags = array( + 1 => 'NET_SSH1_MSG_DISCONNECT', + 2 => 'NET_SSH1_SMSG_PUBLIC_KEY', + 3 => 'NET_SSH1_CMSG_SESSION_KEY', + 4 => 'NET_SSH1_CMSG_USER', + 9 => 'NET_SSH1_CMSG_AUTH_PASSWORD', + 10 => 'NET_SSH1_CMSG_REQUEST_PTY', + 12 => 'NET_SSH1_CMSG_EXEC_SHELL', + 13 => 'NET_SSH1_CMSG_EXEC_CMD', + 14 => 'NET_SSH1_SMSG_SUCCESS', + 15 => 'NET_SSH1_SMSG_FAILURE', + 16 => 'NET_SSH1_CMSG_STDIN_DATA', + 17 => 'NET_SSH1_SMSG_STDOUT_DATA', + 18 => 'NET_SSH1_SMSG_STDERR_DATA', + 19 => 'NET_SSH1_CMSG_EOF', + 20 => 'NET_SSH1_SMSG_EXITSTATUS', + 33 => 'NET_SSH1_CMSG_EXIT_CONFIRMATION' + ); + + $this->_define_array($this->protocol_flags); + + $this->host = $host; + $this->port = $port; + $this->connectionTimeout = $timeout; + $this->cipher = $cipher; + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param string $host + * @param int $port + * @param int $timeout + * @param int $cipher + * @access public + */ + function Net_SSH1($host, $port = 22, $timeout = 10, $cipher = NET_SSH1_CIPHER_3DES) + { + $this->__construct($host, $port, $timeout, $cipher); + } + + /** + * Connect to an SSHv1 server + * + * @return bool + * @access private + */ + function _connect() + { + $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->connectionTimeout); + if (!$this->fsock) { + user_error(rtrim("Cannot connect to {$this->host}:{$this->port}. Error $errno. $errstr")); + return false; + } + + $this->server_identification = $init_line = fgets($this->fsock, 255); + + if (defined('NET_SSH1_LOGGING')) { + $this->_append_log('<-', $this->server_identification); + $this->_append_log('->', $this->identifier . "\r\n"); + } + + if (!preg_match('#SSH-([0-9\.]+)-(.+)#', $init_line, $parts)) { + user_error('Can only connect to SSH servers'); + return false; + } + if ($parts[1][0] != 1) { + user_error("Cannot connect to SSH $parts[1] servers"); + return false; + } + + fputs($this->fsock, $this->identifier."\r\n"); + + $response = $this->_get_binary_packet(); + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_PUBLIC_KEY) { + user_error('Expected SSH_SMSG_PUBLIC_KEY'); + return false; + } + + $anti_spoofing_cookie = $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 8); + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) { + return false; + } + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $server_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->server_key_public_exponent = $server_key_public_exponent; + + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) { + return false; + } + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $server_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->server_key_public_modulus = $server_key_public_modulus; + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) { + return false; + } + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $host_key_public_exponent = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->host_key_public_exponent = $host_key_public_exponent; + + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 2) { + return false; + } + $temp = unpack('nlen', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 2)); + $host_key_public_modulus = new Math_BigInteger($this->_string_shift($response[NET_SSH1_RESPONSE_DATA], ceil($temp['len'] / 8)), 256); + $this->host_key_public_modulus = $host_key_public_modulus; + + $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4); + + // get a list of the supported ciphers + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 4) { + return false; + } + extract(unpack('Nsupported_ciphers_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4))); + foreach ($this->supported_ciphers as $mask => $name) { + if (($supported_ciphers_mask & (1 << $mask)) == 0) { + unset($this->supported_ciphers[$mask]); + } + } + + // get a list of the supported authentications + if (strlen($response[NET_SSH1_RESPONSE_DATA]) < 4) { + return false; + } + extract(unpack('Nsupported_authentications_mask', $this->_string_shift($response[NET_SSH1_RESPONSE_DATA], 4))); + foreach ($this->supported_authentications as $mask => $name) { + if (($supported_authentications_mask & (1 << $mask)) == 0) { + unset($this->supported_authentications[$mask]); + } + } + + $session_id = pack('H*', md5($host_key_public_modulus->toBytes() . $server_key_public_modulus->toBytes() . $anti_spoofing_cookie)); + + $session_key = crypt_random_string(32); + $double_encrypted_session_key = $session_key ^ str_pad($session_id, 32, chr(0)); + + if ($server_key_public_modulus->compare($host_key_public_modulus) < 0) { + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $server_key_public_exponent, + $server_key_public_modulus + ) + ); + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $host_key_public_exponent, + $host_key_public_modulus + ) + ); + } else { + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $host_key_public_exponent, + $host_key_public_modulus + ) + ); + $double_encrypted_session_key = $this->_rsa_crypt( + $double_encrypted_session_key, + array( + $server_key_public_exponent, + $server_key_public_modulus + ) + ); + } + + $cipher = isset($this->supported_ciphers[$this->cipher]) ? $this->cipher : NET_SSH1_CIPHER_3DES; + $data = pack('C2a*na*N', NET_SSH1_CMSG_SESSION_KEY, $cipher, $anti_spoofing_cookie, 8 * strlen($double_encrypted_session_key), $double_encrypted_session_key, 0); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_SESSION_KEY'); + return false; + } + + switch ($cipher) { + //case NET_SSH1_CIPHER_NONE: + // $this->crypto = new Crypt_Null(); + // break; + case NET_SSH1_CIPHER_DES: + if (!class_exists('Crypt_DES')) { + include_once 'Crypt/DES.php'; + } + $this->crypto = new Crypt_DES(); + $this->crypto->disablePadding(); + $this->crypto->enableContinuousBuffer(); + $this->crypto->setKey(substr($session_key, 0, 8)); + break; + case NET_SSH1_CIPHER_3DES: + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $this->crypto = new Crypt_TripleDES(CRYPT_DES_MODE_3CBC); + $this->crypto->disablePadding(); + $this->crypto->enableContinuousBuffer(); + $this->crypto->setKey(substr($session_key, 0, 24)); + break; + //case NET_SSH1_CIPHER_RC4: + // if (!class_exists('Crypt_RC4')) { + // include_once 'Crypt/RC4.php'; + // } + // $this->crypto = new Crypt_RC4(); + // $this->crypto->enableContinuousBuffer(); + // $this->crypto->setKey(substr($session_key, 0, 16)); + // break; + } + + $response = $this->_get_binary_packet(); + + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { + user_error('Expected SSH_SMSG_SUCCESS'); + return false; + } + + $this->bitmap = NET_SSH1_MASK_CONNECTED; + + return true; + } + + /** + * Login + * + * @param string $username + * @param string $password + * @return bool + * @access public + */ + function login($username, $password = '') + { + if (!($this->bitmap & NET_SSH1_MASK_CONSTRUCTOR)) { + $this->bitmap |= NET_SSH1_MASK_CONSTRUCTOR; + if (!$this->_connect()) { + return false; + } + } + + if (!($this->bitmap & NET_SSH1_MASK_CONNECTED)) { + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_USER, strlen($username), $username); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_USER'); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response === true) { + return false; + } + if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { + $this->bitmap |= NET_SSH1_MASK_LOGIN; + return true; + } elseif ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_FAILURE) { + user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE'); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen($password), $password); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_AUTH_PASSWORD'); + return false; + } + + // remove the username and password from the last logged packet + if (defined('NET_SSH1_LOGGING') && NET_SSH1_LOGGING == NET_SSH1_LOG_COMPLEX) { + $data = pack('CNa*', NET_SSH1_CMSG_AUTH_PASSWORD, strlen('password'), 'password'); + $this->message_log[count($this->message_log) - 1] = $data; + } + + $response = $this->_get_binary_packet(); + + if ($response === true) { + return false; + } + if ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_SUCCESS) { + $this->bitmap |= NET_SSH1_MASK_LOGIN; + return true; + } elseif ($response[NET_SSH1_RESPONSE_TYPE] == NET_SSH1_SMSG_FAILURE) { + return false; + } else { + user_error('Expected SSH_SMSG_SUCCESS or SSH_SMSG_FAILURE'); + return false; + } + } + + /** + * Set Timeout + * + * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. + * Setting $timeout to false or 0 will mean there is no timeout. + * + * @param mixed $timeout + */ + function setTimeout($timeout) + { + $this->timeout = $this->curTimeout = $timeout; + } + + /** + * Executes a command on a non-interactive shell, returns the output, and quits. + * + * An SSH1 server will close the connection after a command has been executed on a non-interactive shell. SSH2 + * servers don't, however, this isn't an SSH2 client. The way this works, on the server, is by initiating a + * shell with the -s option, as discussed in the following links: + * + * {@link http://www.faqs.org/docs/bashman/bashref_65.html http://www.faqs.org/docs/bashman/bashref_65.html} + * {@link http://www.faqs.org/docs/bashman/bashref_62.html http://www.faqs.org/docs/bashman/bashref_62.html} + * + * To execute further commands, a new Net_SSH1 object will need to be created. + * + * Returns false on failure and the output, otherwise. + * + * @see self::interactiveRead() + * @see self::interactiveWrite() + * @param string $cmd + * @return mixed + * @access public + */ + function exec($cmd, $block = true) + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()'); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_EXEC_CMD, strlen($cmd), $cmd); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_EXEC_CMD'); + return false; + } + + if (!$block) { + return true; + } + + $output = ''; + $response = $this->_get_binary_packet(); + + if ($response !== false) { + do { + $output.= substr($response[NET_SSH1_RESPONSE_DATA], 4); + $response = $this->_get_binary_packet(); + } while (is_array($response) && $response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_EXITSTATUS); + } + + $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION); + + // i don't think it's really all that important if this packet gets sent or not. + $this->_send_binary_packet($data); + + fclose($this->fsock); + + // reset the execution bitmap - a new Net_SSH1 object needs to be created. + $this->bitmap = 0; + + return $output; + } + + /** + * Creates an interactive shell + * + * @see self::interactiveRead() + * @see self::interactiveWrite() + * @return bool + * @access private + */ + function _initShell() + { + // connect using the sample parameters in protocol-1.5.txt. + // according to wikipedia.org's entry on text terminals, "the fundamental type of application running on a text + // terminal is a command line interpreter or shell". thus, opening a terminal session to run the shell. + $data = pack('CNa*N4C', NET_SSH1_CMSG_REQUEST_PTY, strlen('vt100'), 'vt100', 24, 80, 0, 0, NET_SSH1_TTY_OP_END); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_REQUEST_PTY'); + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response === true) { + return false; + } + if ($response[NET_SSH1_RESPONSE_TYPE] != NET_SSH1_SMSG_SUCCESS) { + user_error('Expected SSH_SMSG_SUCCESS'); + return false; + } + + $data = pack('C', NET_SSH1_CMSG_EXEC_SHELL); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_EXEC_SHELL'); + return false; + } + + $this->bitmap |= NET_SSH1_MASK_SHELL; + + //stream_set_blocking($this->fsock, 0); + + return true; + } + + /** + * Inputs a command into an interactive shell. + * + * @see self::interactiveWrite() + * @param string $cmd + * @return bool + * @access public + */ + function write($cmd) + { + return $this->interactiveWrite($cmd); + } + + /** + * Returns the output of an interactive shell when there's a match for $expect + * + * $expect can take the form of a string literal or, if $mode == NET_SSH1_READ_REGEX, + * a regular expression. + * + * @see self::write() + * @param string $expect + * @param int $mode + * @return bool + * @access public + */ + function read($expect, $mode = NET_SSH1_READ_SIMPLE) + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()'); + return false; + } + + if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session'); + return false; + } + + $match = $expect; + while (true) { + if ($mode == NET_SSH1_READ_REGEX) { + preg_match($expect, $this->interactiveBuffer, $matches); + $match = isset($matches[0]) ? $matches[0] : ''; + } + $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false; + if ($pos !== false) { + return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match)); + } + $response = $this->_get_binary_packet(); + + if ($response === true) { + return $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer)); + } + $this->interactiveBuffer.= substr($response[NET_SSH1_RESPONSE_DATA], 4); + } + } + + /** + * Inputs a command into an interactive shell. + * + * @see self::interactiveRead() + * @param string $cmd + * @return bool + * @access public + */ + function interactiveWrite($cmd) + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()'); + return false; + } + + if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session'); + return false; + } + + $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($cmd), $cmd); + + if (!$this->_send_binary_packet($data)) { + user_error('Error sending SSH_CMSG_STDIN'); + return false; + } + + return true; + } + + /** + * Returns the output of an interactive shell when no more output is available. + * + * Requires PHP 4.3.0 or later due to the use of the stream_select() function. If you see stuff like + * "^[[00m", you're seeing ANSI escape codes. According to + * {@link http://support.microsoft.com/kb/101875 How to Enable ANSI.SYS in a Command Window}, "Windows NT + * does not support ANSI escape sequences in Win32 Console applications", so if you're a Windows user, + * there's not going to be much recourse. + * + * @see self::interactiveRead() + * @return string + * @access public + */ + function interactiveRead() + { + if (!($this->bitmap & NET_SSH1_MASK_LOGIN)) { + user_error('Operation disallowed prior to login()'); + return false; + } + + if (!($this->bitmap & NET_SSH1_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session'); + return false; + } + + $read = array($this->fsock); + $write = $except = null; + if (stream_select($read, $write, $except, 0)) { + $response = $this->_get_binary_packet(); + return substr($response[NET_SSH1_RESPONSE_DATA], 4); + } else { + return ''; + } + } + + /** + * Disconnect + * + * @access public + */ + function disconnect() + { + $this->_disconnect(); + } + + /** + * Destructor. + * + * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call + * disconnect(). + * + * @access public + */ + function __destruct() + { + $this->_disconnect(); + } + + /** + * Disconnect + * + * @param string $msg + * @access private + */ + function _disconnect($msg = 'Client Quit') + { + if ($this->bitmap) { + $data = pack('C', NET_SSH1_CMSG_EOF); + $this->_send_binary_packet($data); + /* + $response = $this->_get_binary_packet(); + if ($response === true) { + $response = array(NET_SSH1_RESPONSE_TYPE => -1); + } + switch ($response[NET_SSH1_RESPONSE_TYPE]) { + case NET_SSH1_SMSG_EXITSTATUS: + $data = pack('C', NET_SSH1_CMSG_EXIT_CONFIRMATION); + break; + default: + $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg); + } + */ + $data = pack('CNa*', NET_SSH1_MSG_DISCONNECT, strlen($msg), $msg); + + $this->_send_binary_packet($data); + fclose($this->fsock); + $this->bitmap = 0; + } + } + + /** + * Gets Binary Packets + * + * See 'The Binary Packet Protocol' of protocol-1.5.txt for more info. + * + * Also, this function could be improved upon by adding detection for the following exploit: + * http://www.securiteam.com/securitynews/5LP042K3FY.html + * + * @see self::_send_binary_packet() + * @return array + * @access private + */ + function _get_binary_packet() + { + if (feof($this->fsock)) { + //user_error('connection closed prematurely'); + return false; + } + + if ($this->curTimeout) { + $read = array($this->fsock); + $write = $except = null; + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $sec = floor($this->curTimeout); + $usec = 1000000 * ($this->curTimeout - $sec); + // on windows this returns a "Warning: Invalid CRT parameters detected" error + if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { + //$this->_disconnect('Timeout'); + return true; + } + $elapsed = strtok(microtime(), ' ') + strtok('') - $start; + $this->curTimeout-= $elapsed; + } + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $data = fread($this->fsock, 4); + if (strlen($data) < 4) { + return false; + } + $temp = unpack('Nlength', $data); + + $padding_length = 8 - ($temp['length'] & 7); + $length = $temp['length'] + $padding_length; + $raw = ''; + + while ($length > 0) { + $temp = fread($this->fsock, $length); + $raw.= $temp; + $length-= strlen($temp); + } + $stop = strtok(microtime(), ' ') + strtok(''); + + if (strlen($raw) && $this->crypto !== false) { + $raw = $this->crypto->decrypt($raw); + } + + $padding = substr($raw, 0, $padding_length); + $type = $raw[$padding_length]; + $data = substr($raw, $padding_length + 1, -4); + + if (strlen($raw) < 4) { + return false; + } + $temp = unpack('Ncrc', substr($raw, -4)); + + //if ( $temp['crc'] != $this->_crc($padding . $type . $data) ) { + // user_error('Bad CRC in packet from server'); + // return false; + //} + + $type = ord($type); + + if (defined('NET_SSH1_LOGGING')) { + $temp = isset($this->protocol_flags[$type]) ? $this->protocol_flags[$type] : 'UNKNOWN'; + $temp = '<- ' . $temp . + ' (' . round($stop - $start, 4) . 's)'; + $this->_append_log($temp, $data); + } + + return array( + NET_SSH1_RESPONSE_TYPE => $type, + NET_SSH1_RESPONSE_DATA => $data + ); + } + + /** + * Sends Binary Packets + * + * Returns true on success, false on failure. + * + * @see self::_get_binary_packet() + * @param string $data + * @return bool + * @access private + */ + function _send_binary_packet($data) + { + if (feof($this->fsock)) { + //user_error('connection closed prematurely'); + return false; + } + + $length = strlen($data) + 4; + + $padding = crypt_random_string(8 - ($length & 7)); + + $orig = $data; + $data = $padding . $data; + $data.= pack('N', $this->_crc($data)); + + if ($this->crypto !== false) { + $data = $this->crypto->encrypt($data); + } + + $packet = pack('Na*', $length, $data); + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $result = strlen($packet) == fputs($this->fsock, $packet); + $stop = strtok(microtime(), ' ') + strtok(''); + + if (defined('NET_SSH1_LOGGING')) { + $temp = isset($this->protocol_flags[ord($orig[0])]) ? $this->protocol_flags[ord($orig[0])] : 'UNKNOWN'; + $temp = '-> ' . $temp . + ' (' . round($stop - $start, 4) . 's)'; + $this->_append_log($temp, $orig); + } + + return $result; + } + + /** + * Cyclic Redundancy Check (CRC) + * + * PHP's crc32 function is implemented slightly differently than the one that SSH v1 uses, so + * we've reimplemented it. A more detailed discussion of the differences can be found after + * $crc_lookup_table's initialization. + * + * @see self::_get_binary_packet() + * @see self::_send_binary_packet() + * @param string $data + * @return int + * @access private + */ + function _crc($data) + { + static $crc_lookup_table = array( + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, + 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, + 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, + 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, + 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, + 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, + 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, + 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, + 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, + 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, + 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, + 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, + 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, + 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, + 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, + 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, + 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, + 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, + 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, + 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, + 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, + 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, + 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, + 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, + 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, + 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, + 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, + 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, + 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, + 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, + 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, + 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, + 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, + 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, + 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, + 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, + 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, + 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, + 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, + 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, + 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, + 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, + 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, + 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, + 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, + 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, + 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, + 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, + 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, + 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, + 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, + 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, + 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, + 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, + 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + ); + + // For this function to yield the same output as PHP's crc32 function, $crc would have to be + // set to 0xFFFFFFFF, initially - not 0x00000000 as it currently is. + $crc = 0x00000000; + $length = strlen($data); + + for ($i=0; $i<$length; $i++) { + // We AND $crc >> 8 with 0x00FFFFFF because we want the eight newly added bits to all + // be zero. PHP, unfortunately, doesn't always do this. 0x80000000 >> 8, as an example, + // yields 0xFF800000 - not 0x00800000. The following link elaborates: + // http://www.php.net/manual/en/language.operators.bitwise.php#57281 + $crc = (($crc >> 8) & 0x00FFFFFF) ^ $crc_lookup_table[($crc & 0xFF) ^ ord($data[$i])]; + } + + // In addition to having to set $crc to 0xFFFFFFFF, initially, the return value must be XOR'd with + // 0xFFFFFFFF for this function to return the same thing that PHP's crc32 function would. + return $crc; + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @return string + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * RSA Encrypt + * + * Returns mod(pow($m, $e), $n), where $n should be the product of two (large) primes $p and $q and where $e + * should be a number with the property that gcd($e, ($p - 1) * ($q - 1)) == 1. Could just make anything that + * calls this call modexp, instead, but I think this makes things clearer, maybe... + * + * @see self::Net_SSH1() + * @param Math_BigInteger $m + * @param array $key + * @return Math_BigInteger + * @access private + */ + function _rsa_crypt($m, $key) + { + /* + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + + $rsa = new Crypt_RSA(); + $rsa->loadKey($key, CRYPT_RSA_PUBLIC_FORMAT_RAW); + $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1); + return $rsa->encrypt($m); + */ + + // To quote from protocol-1.5.txt: + // The most significant byte (which is only partial as the value must be + // less than the public modulus, which is never a power of two) is zero. + // + // The next byte contains the value 2 (which stands for public-key + // encrypted data in the PKCS standard [PKCS#1]). Then, there are non- + // zero random bytes to fill any unused space, a zero byte, and the data + // to be encrypted in the least significant bytes, the last byte of the + // data in the least significant byte. + + // Presumably the part of PKCS#1 they're refering to is "Section 7.2.1 Encryption Operation", + // under "7.2 RSAES-PKCS1-v1.5" and "7 Encryption schemes" of the following URL: + // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf + $modulus = $key[1]->toBytes(); + $length = strlen($modulus) - strlen($m) - 3; + $random = ''; + while (strlen($random) != $length) { + $block = crypt_random_string($length - strlen($random)); + $block = str_replace("\x00", '', $block); + $random.= $block; + } + $temp = chr(0) . chr(2) . $random . chr(0) . $m; + + $m = new Math_BigInteger($temp, 256); + $m = $m->modPow($key[0], $key[1]); + + return $m->toBytes(); + } + + /** + * Define Array + * + * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of + * named constants from it, using the value as the name of the constant and the index as the value of the constant. + * If any of the constants that would be defined already exists, none of the constants will be defined. + * + * @param array $array + * @access private + */ + function _define_array() + { + $args = func_get_args(); + foreach ($args as $arg) { + foreach ($arg as $key => $value) { + if (!defined($value)) { + define($value, $key); + } else { + break 2; + } + } + } + } + + /** + * Returns a log of the packets that have been sent and received. + * + * Returns a string if NET_SSH1_LOGGING == NET_SSH1_LOG_COMPLEX, an array if NET_SSH1_LOGGING == NET_SSH1_LOG_SIMPLE and false if !defined('NET_SSH1_LOGGING') + * + * @access public + * @return array|false|string + */ + function getLog() + { + if (!defined('NET_SSH1_LOGGING')) { + return false; + } + + switch (NET_SSH1_LOGGING) { + case NET_SSH1_LOG_SIMPLE: + return $this->message_number_log; + break; + case NET_SSH1_LOG_COMPLEX: + return $this->_format_log($this->message_log, $this->protocol_flags_log); + break; + default: + return false; + } + } + + /** + * Formats a log for printing + * + * @param array $message_log + * @param array $message_number_log + * @access private + * @return string + */ + function _format_log($message_log, $message_number_log) + { + $output = ''; + for ($i = 0; $i < count($message_log); $i++) { + $output.= $message_number_log[$i] . "\r\n"; + $current_log = $message_log[$i]; + $j = 0; + do { + if (strlen($current_log)) { + $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 '; + } + $fragment = $this->_string_shift($current_log, $this->log_short_width); + $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary)); + // replace non ASCII printable characters with dots + // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters + // also replace < with a . since < messes up the output on web browsers + $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment); + $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n"; + $j++; + } while (strlen($current_log)); + $output.= "\r\n"; + } + + return $output; + } + + /** + * Helper function for _format_log + * + * For use with preg_replace_callback() + * + * @param array $matches + * @access private + * @return string + */ + function _format_log_helper($matches) + { + return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT); + } + + /** + * Return the server key public exponent + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param bool $raw_output + * @return string + * @access public + */ + function getServerKeyPublicExponent($raw_output = false) + { + return $raw_output ? $this->server_key_public_exponent->toBytes() : $this->server_key_public_exponent->toString(); + } + + /** + * Return the server key public modulus + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param bool $raw_output + * @return string + * @access public + */ + function getServerKeyPublicModulus($raw_output = false) + { + return $raw_output ? $this->server_key_public_modulus->toBytes() : $this->server_key_public_modulus->toString(); + } + + /** + * Return the host key public exponent + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param bool $raw_output + * @return string + * @access public + */ + function getHostKeyPublicExponent($raw_output = false) + { + return $raw_output ? $this->host_key_public_exponent->toBytes() : $this->host_key_public_exponent->toString(); + } + + /** + * Return the host key public modulus + * + * Returns, by default, the base-10 representation. If $raw_output is set to true, returns, instead, + * the raw bytes. This behavior is similar to PHP's md5() function. + * + * @param bool $raw_output + * @return string + * @access public + */ + function getHostKeyPublicModulus($raw_output = false) + { + return $raw_output ? $this->host_key_public_modulus->toBytes() : $this->host_key_public_modulus->toString(); + } + + /** + * Return a list of ciphers supported by SSH1 server. + * + * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output + * is set to true, returns, instead, an array of constants. ie. instead of array('Triple-DES in CBC mode'), you'll + * get array(NET_SSH1_CIPHER_3DES). + * + * @param bool $raw_output + * @return array + * @access public + */ + function getSupportedCiphers($raw_output = false) + { + return $raw_output ? array_keys($this->supported_ciphers) : array_values($this->supported_ciphers); + } + + /** + * Return a list of authentications supported by SSH1 server. + * + * Just because a cipher is supported by an SSH1 server doesn't mean it's supported by this library. If $raw_output + * is set to true, returns, instead, an array of constants. ie. instead of array('password authentication'), you'll + * get array(NET_SSH1_AUTH_PASSWORD). + * + * @param bool $raw_output + * @return array + * @access public + */ + function getSupportedAuthentications($raw_output = false) + { + return $raw_output ? array_keys($this->supported_authentications) : array_values($this->supported_authentications); + } + + /** + * Return the server identification. + * + * @return string + * @access public + */ + function getServerIdentification() + { + return rtrim($this->server_identification); + } + + /** + * Logs data packets + * + * Makes sure that only the last 1MB worth of packets will be logged + * + * @param string $data + * @access private + */ + function _append_log($protocol_flags, $message) + { + switch (NET_SSH1_LOGGING) { + // useful for benchmarks + case NET_SSH1_LOG_SIMPLE: + $this->protocol_flags_log[] = $protocol_flags; + break; + // the most useful log for SSH1 + case NET_SSH1_LOG_COMPLEX: + $this->protocol_flags_log[] = $protocol_flags; + $this->_string_shift($message); + $this->log_size+= strlen($message); + $this->message_log[] = $message; + while ($this->log_size > NET_SSH1_LOG_MAX_SIZE) { + $this->log_size-= strlen(array_shift($this->message_log)); + array_shift($this->protocol_flags_log); + } + break; + // dump the output out realtime; packets may be interspersed with non packets, + // passwords won't be filtered out and select other packets may not be correctly + // identified + case NET_SSH1_LOG_REALTIME: + echo "
\r\n" . $this->_format_log(array($message), array($protocol_flags)) . "\r\n
\r\n"; + @flush(); + @ob_flush(); + break; + // basically the same thing as NET_SSH1_LOG_REALTIME with the caveat that NET_SSH1_LOG_REALTIME_FILE + // needs to be defined and that the resultant log file will be capped out at NET_SSH1_LOG_MAX_SIZE. + // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily + // at the beginning of the file + case NET_SSH1_LOG_REALTIME_FILE: + if (!isset($this->realtime_log_file)) { + // PHP doesn't seem to like using constants in fopen() + $filename = NET_SSH1_LOG_REALTIME_FILE; + $fp = fopen($filename, 'w'); + $this->realtime_log_file = $fp; + } + if (!is_resource($this->realtime_log_file)) { + break; + } + $entry = $this->_format_log(array($message), array($protocol_flags)); + if ($this->realtime_log_wrap) { + $temp = "<<< START >>>\r\n"; + $entry.= $temp; + fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp)); + } + $this->realtime_log_size+= strlen($entry); + if ($this->realtime_log_size > NET_SSH1_LOG_MAX_SIZE) { + fseek($this->realtime_log_file, 0); + $this->realtime_log_size = strlen($entry); + $this->realtime_log_wrap = true; + } + fputs($this->realtime_log_file, $entry); + } + } +} diff --git a/ipaylinks_statement/Net/SSH2.php b/ipaylinks_statement/Net/SSH2.php new file mode 100644 index 00000000..bdce0715 --- /dev/null +++ b/ipaylinks_statement/Net/SSH2.php @@ -0,0 +1,4723 @@ + + * login('username', 'password')) { + * exit('Login Failed'); + * } + * + * echo $ssh->exec('pwd'); + * echo $ssh->exec('ls -la'); + * ?> + * + * + * + * setPassword('whatever'); + * $key->loadKey(file_get_contents('privatekey')); + * + * $ssh = new Net_SSH2('www.domain.tld'); + * if (!$ssh->login('username', $key)) { + * exit('Login Failed'); + * } + * + * echo $ssh->read('username@username:~$'); + * $ssh->write("ls -la\n"); + * echo $ssh->read('username@username:~$'); + * ?> + * + * + * LICENSE: 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. + * + * @category Net + * @package Net_SSH2 + * @author Jim Wigginton + * @copyright 2007 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + */ + +/**#@+ + * Execution Bitmap Masks + * + * @see self::bitmap + * @access private + */ +define('NET_SSH2_MASK_CONSTRUCTOR', 0x00000001); +define('NET_SSH2_MASK_CONNECTED', 0x00000002); +define('NET_SSH2_MASK_LOGIN_REQ', 0x00000004); +define('NET_SSH2_MASK_LOGIN', 0x00000008); +define('NET_SSH2_MASK_SHELL', 0x00000010); +define('NET_SSH2_MASK_WINDOW_ADJUST', 0x00000020); +/**#@-*/ + +/**#@+ + * Channel constants + * + * RFC4254 refers not to client and server channels but rather to sender and recipient channels. we don't refer + * to them in that way because RFC4254 toggles the meaning. the client sends a SSH_MSG_CHANNEL_OPEN message with + * a sender channel and the server sends a SSH_MSG_CHANNEL_OPEN_CONFIRMATION in response, with a sender and a + * recepient channel. at first glance, you might conclude that SSH_MSG_CHANNEL_OPEN_CONFIRMATION's sender channel + * would be the same thing as SSH_MSG_CHANNEL_OPEN's sender channel, but it's not, per this snipet: + * The 'recipient channel' is the channel number given in the original + * open request, and 'sender channel' is the channel number allocated by + * the other side. + * + * @see self::_send_channel_packet() + * @see self::_get_channel_packet() + * @access private + */ +define('NET_SSH2_CHANNEL_EXEC', 1); // PuTTy uses 0x100 +define('NET_SSH2_CHANNEL_SHELL', 2); +define('NET_SSH2_CHANNEL_SUBSYSTEM', 3); +define('NET_SSH2_CHANNEL_AGENT_FORWARD', 4); +/**#@-*/ + +/**#@+ + * @access public + * @see self::getLog() + */ +/** + * Returns the message numbers + */ +define('NET_SSH2_LOG_SIMPLE', 1); +/** + * Returns the message content + */ +define('NET_SSH2_LOG_COMPLEX', 2); +/** + * Outputs the content real-time + */ +define('NET_SSH2_LOG_REALTIME', 3); +/** + * Dumps the content real-time to a file + */ +define('NET_SSH2_LOG_REALTIME_FILE', 4); +/** + * Make sure that the log never gets larger than this + */ +define('NET_SSH2_LOG_MAX_SIZE', 1024 * 1024); +/**#@-*/ + +/**#@+ + * @access public + * @see self::read() + */ +/** + * Returns when a string matching $expect exactly is found + */ +define('NET_SSH2_READ_SIMPLE', 1); +/** + * Returns when a string matching the regular expression $expect is found + */ +define('NET_SSH2_READ_REGEX', 2); +/** + * Returns when a string matching the regular expression $expect is found + */ +define('NET_SSH2_READ_NEXT', 3); +/**#@-*/ + +/** + * Pure-PHP implementation of SSHv2. + * + * @package Net_SSH2 + * @author Jim Wigginton + * @access public + */ +class Net_SSH2 +{ + /** + * The SSH identifier + * + * @var string + * @access private + */ + var $identifier; + + /** + * The Socket Object + * + * @var object + * @access private + */ + var $fsock; + + /** + * Execution Bitmap + * + * The bits that are set represent functions that have been called already. This is used to determine + * if a requisite function has been successfully executed. If not, an error should be thrown. + * + * @var int + * @access private + */ + var $bitmap = 0; + + /** + * Error information + * + * @see self::getErrors() + * @see self::getLastError() + * @var string + * @access private + */ + var $errors = array(); + + /** + * Server Identifier + * + * @see self::getServerIdentification() + * @var array|false + * @access private + */ + var $server_identifier = false; + + /** + * Key Exchange Algorithms + * + * @see self::getKexAlgorithims() + * @var array|false + * @access private + */ + var $kex_algorithms = false; + + /** + * Minimum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods + * + * @see self::_key_exchange() + * @var int + * @access private + */ + var $kex_dh_group_size_min = 1536; + + /** + * Preferred Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods + * + * @see self::_key_exchange() + * @var int + * @access private + */ + var $kex_dh_group_size_preferred = 2048; + + /** + * Maximum Diffie-Hellman Group Bit Size in RFC 4419 Key Exchange Methods + * + * @see self::_key_exchange() + * @var int + * @access private + */ + var $kex_dh_group_size_max = 4096; + + /** + * Server Host Key Algorithms + * + * @see self::getServerHostKeyAlgorithms() + * @var array|false + * @access private + */ + var $server_host_key_algorithms = false; + + /** + * Encryption Algorithms: Client to Server + * + * @see self::getEncryptionAlgorithmsClient2Server() + * @var array|false + * @access private + */ + var $encryption_algorithms_client_to_server = false; + + /** + * Encryption Algorithms: Server to Client + * + * @see self::getEncryptionAlgorithmsServer2Client() + * @var array|false + * @access private + */ + var $encryption_algorithms_server_to_client = false; + + /** + * MAC Algorithms: Client to Server + * + * @see self::getMACAlgorithmsClient2Server() + * @var array|false + * @access private + */ + var $mac_algorithms_client_to_server = false; + + /** + * MAC Algorithms: Server to Client + * + * @see self::getMACAlgorithmsServer2Client() + * @var array|false + * @access private + */ + var $mac_algorithms_server_to_client = false; + + /** + * Compression Algorithms: Client to Server + * + * @see self::getCompressionAlgorithmsClient2Server() + * @var array|false + * @access private + */ + var $compression_algorithms_client_to_server = false; + + /** + * Compression Algorithms: Server to Client + * + * @see self::getCompressionAlgorithmsServer2Client() + * @var array|false + * @access private + */ + var $compression_algorithms_server_to_client = false; + + /** + * Languages: Server to Client + * + * @see self::getLanguagesServer2Client() + * @var array|false + * @access private + */ + var $languages_server_to_client = false; + + /** + * Languages: Client to Server + * + * @see self::getLanguagesClient2Server() + * @var array|false + * @access private + */ + var $languages_client_to_server = false; + + /** + * Block Size for Server to Client Encryption + * + * "Note that the length of the concatenation of 'packet_length', + * 'padding_length', 'payload', and 'random padding' MUST be a multiple + * of the cipher block size or 8, whichever is larger. This constraint + * MUST be enforced, even when using stream ciphers." + * + * -- http://tools.ietf.org/html/rfc4253#section-6 + * + * @see self::Net_SSH2() + * @see self::_send_binary_packet() + * @var int + * @access private + */ + var $encrypt_block_size = 8; + + /** + * Block Size for Client to Server Encryption + * + * @see self::Net_SSH2() + * @see self::_get_binary_packet() + * @var int + * @access private + */ + var $decrypt_block_size = 8; + + /** + * Server to Client Encryption Object + * + * @see self::_get_binary_packet() + * @var object + * @access private + */ + var $decrypt = false; + + /** + * Client to Server Encryption Object + * + * @see self::_send_binary_packet() + * @var object + * @access private + */ + var $encrypt = false; + + /** + * Client to Server HMAC Object + * + * @see self::_send_binary_packet() + * @var object + * @access private + */ + var $hmac_create = false; + + /** + * Server to Client HMAC Object + * + * @see self::_get_binary_packet() + * @var object + * @access private + */ + var $hmac_check = false; + + /** + * Size of server to client HMAC + * + * We need to know how big the HMAC will be for the server to client direction so that we know how many bytes to read. + * For the client to server side, the HMAC object will make the HMAC as long as it needs to be. All we need to do is + * append it. + * + * @see self::_get_binary_packet() + * @var int + * @access private + */ + var $hmac_size = false; + + /** + * Server Public Host Key + * + * @see self::getServerPublicHostKey() + * @var string + * @access private + */ + var $server_public_host_key; + + /** + * Session identifier + * + * "The exchange hash H from the first key exchange is additionally + * used as the session identifier, which is a unique identifier for + * this connection." + * + * -- http://tools.ietf.org/html/rfc4253#section-7.2 + * + * @see self::_key_exchange() + * @var string + * @access private + */ + var $session_id = false; + + /** + * Exchange hash + * + * The current exchange hash + * + * @see self::_key_exchange() + * @var string + * @access private + */ + var $exchange_hash = false; + + /** + * Message Numbers + * + * @see self::Net_SSH2() + * @var array + * @access private + */ + var $message_numbers = array(); + + /** + * Disconnection Message 'reason codes' defined in RFC4253 + * + * @see self::Net_SSH2() + * @var array + * @access private + */ + var $disconnect_reasons = array(); + + /** + * SSH_MSG_CHANNEL_OPEN_FAILURE 'reason codes', defined in RFC4254 + * + * @see self::Net_SSH2() + * @var array + * @access private + */ + var $channel_open_failure_reasons = array(); + + /** + * Terminal Modes + * + * @link http://tools.ietf.org/html/rfc4254#section-8 + * @see self::Net_SSH2() + * @var array + * @access private + */ + var $terminal_modes = array(); + + /** + * SSH_MSG_CHANNEL_EXTENDED_DATA's data_type_codes + * + * @link http://tools.ietf.org/html/rfc4254#section-5.2 + * @see self::Net_SSH2() + * @var array + * @access private + */ + var $channel_extended_data_type_codes = array(); + + /** + * Send Sequence Number + * + * See 'Section 6.4. Data Integrity' of rfc4253 for more info. + * + * @see self::_send_binary_packet() + * @var int + * @access private + */ + var $send_seq_no = 0; + + /** + * Get Sequence Number + * + * See 'Section 6.4. Data Integrity' of rfc4253 for more info. + * + * @see self::_get_binary_packet() + * @var int + * @access private + */ + var $get_seq_no = 0; + + /** + * Server Channels + * + * Maps client channels to server channels + * + * @see self::_get_channel_packet() + * @see self::exec() + * @var array + * @access private + */ + var $server_channels = array(); + + /** + * Channel Buffers + * + * If a client requests a packet from one channel but receives two packets from another those packets should + * be placed in a buffer + * + * @see self::_get_channel_packet() + * @see self::exec() + * @var array + * @access private + */ + var $channel_buffers = array(); + + /** + * Channel Status + * + * Contains the type of the last sent message + * + * @see self::_get_channel_packet() + * @var array + * @access private + */ + var $channel_status = array(); + + /** + * Packet Size + * + * Maximum packet size indexed by channel + * + * @see self::_send_channel_packet() + * @var array + * @access private + */ + var $packet_size_client_to_server = array(); + + /** + * Message Number Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $message_number_log = array(); + + /** + * Message Log + * + * @see self::getLog() + * @var array + * @access private + */ + var $message_log = array(); + + /** + * The Window Size + * + * Bytes the other party can send before it must wait for the window to be adjusted (0x7FFFFFFF = 2GB) + * + * @var int + * @see self::_send_channel_packet() + * @see self::exec() + * @access private + */ + var $window_size = 0x7FFFFFFF; + + /** + * Window size, server to client + * + * Window size indexed by channel + * + * @see self::_send_channel_packet() + * @var array + * @access private + */ + var $window_size_server_to_client = array(); + + /** + * Window size, client to server + * + * Window size indexed by channel + * + * @see self::_get_channel_packet() + * @var array + * @access private + */ + var $window_size_client_to_server = array(); + + /** + * Server signature + * + * Verified against $this->session_id + * + * @see self::getServerPublicHostKey() + * @var string + * @access private + */ + var $signature = ''; + + /** + * Server signature format + * + * ssh-rsa or ssh-dss. + * + * @see self::getServerPublicHostKey() + * @var string + * @access private + */ + var $signature_format = ''; + + /** + * Interactive Buffer + * + * @see self::read() + * @var array + * @access private + */ + var $interactiveBuffer = ''; + + /** + * Current log size + * + * Should never exceed NET_SSH2_LOG_MAX_SIZE + * + * @see self::_send_binary_packet() + * @see self::_get_binary_packet() + * @var int + * @access private + */ + var $log_size; + + /** + * Timeout + * + * @see self::setTimeout() + * @access private + */ + var $timeout; + + /** + * Current Timeout + * + * @see self::_get_channel_packet() + * @access private + */ + var $curTimeout; + + /** + * Real-time log file pointer + * + * @see self::_append_log() + * @var resource + * @access private + */ + var $realtime_log_file; + + /** + * Real-time log file size + * + * @see self::_append_log() + * @var int + * @access private + */ + var $realtime_log_size; + + /** + * Has the signature been validated? + * + * @see self::getServerPublicHostKey() + * @var bool + * @access private + */ + var $signature_validated = false; + + /** + * Real-time log file wrap boolean + * + * @see self::_append_log() + * @access private + */ + var $realtime_log_wrap; + + /** + * Flag to suppress stderr from output + * + * @see self::enableQuietMode() + * @access private + */ + var $quiet_mode = false; + + /** + * Time of first network activity + * + * @var int + * @access private + */ + var $last_packet; + + /** + * Exit status returned from ssh if any + * + * @var int + * @access private + */ + var $exit_status; + + /** + * Flag to request a PTY when using exec() + * + * @var bool + * @see self::enablePTY() + * @access private + */ + var $request_pty = false; + + /** + * Flag set while exec() is running when using enablePTY() + * + * @var bool + * @access private + */ + var $in_request_pty_exec = false; + + /** + * Flag set after startSubsystem() is called + * + * @var bool + * @access private + */ + var $in_subsystem; + + /** + * Contents of stdError + * + * @var string + * @access private + */ + var $stdErrorLog; + + /** + * The Last Interactive Response + * + * @see self::_keyboard_interactive_process() + * @var string + * @access private + */ + var $last_interactive_response = ''; + + /** + * Keyboard Interactive Request / Responses + * + * @see self::_keyboard_interactive_process() + * @var array + * @access private + */ + var $keyboard_requests_responses = array(); + + /** + * Banner Message + * + * Quoting from the RFC, "in some jurisdictions, sending a warning message before + * authentication may be relevant for getting legal protection." + * + * @see self::_filter() + * @see self::getBannerMessage() + * @var string + * @access private + */ + var $banner_message = ''; + + /** + * Did read() timeout or return normally? + * + * @see self::isTimeout() + * @var bool + * @access private + */ + var $is_timeout = false; + + /** + * Log Boundary + * + * @see self::_format_log() + * @var string + * @access private + */ + var $log_boundary = ':'; + + /** + * Log Long Width + * + * @see self::_format_log() + * @var int + * @access private + */ + var $log_long_width = 65; + + /** + * Log Short Width + * + * @see self::_format_log() + * @var int + * @access private + */ + var $log_short_width = 16; + + /** + * Hostname + * + * @see self::Net_SSH2() + * @see self::_connect() + * @var string + * @access private + */ + var $host; + + /** + * Port Number + * + * @see self::Net_SSH2() + * @see self::_connect() + * @var int + * @access private + */ + var $port; + + /** + * Number of columns for terminal window size + * + * @see self::getWindowColumns() + * @see self::setWindowColumns() + * @see self::setWindowSize() + * @var int + * @access private + */ + var $windowColumns = 80; + + /** + * Number of columns for terminal window size + * + * @see self::getWindowRows() + * @see self::setWindowRows() + * @see self::setWindowSize() + * @var int + * @access private + */ + var $windowRows = 24; + + /** + * Crypto Engine + * + * @see self::setCryptoEngine() + * @see self::_key_exchange() + * @var int + * @access private + */ + var $crypto_engine = false; + + /** + * A System_SSH_Agent for use in the SSH2 Agent Forwarding scenario + * + * @var System_SSH_Agent + * @access private + */ + var $agent; + + /** + * Send the identification string first? + * + * @var bool + * @access private + */ + var $send_id_string_first = true; + + /** + * Send the key exchange initiation packet first? + * + * @var bool + * @access private + */ + var $send_kex_first = true; + + /** + * Some versions of OpenSSH incorrectly calculate the key size + * + * @var bool + * @access private + */ + var $bad_key_size_fix = false; + + /** + * The selected decryption algorithm + * + * @var string + * @access private + */ + var $decrypt_algorithm = ''; + + /** + * Should we try to re-connect to re-establish keys? + * + * @var bool + * @access private + */ + var $retry_connect = false; + + /** + * Binary Packet Buffer + * + * @var string|false + * @access private + */ + var $binary_packet_buffer = false; + + /** + * Default Constructor. + * + * $host can either be a string, representing the host, or a stream resource. + * + * @param mixed $host + * @param int $port + * @param int $timeout + * @see self::login() + * @return Net_SSH2 + * @access public + */ + function __construct($host, $port = 22, $timeout = 10) + { + // Include Math_BigInteger + // Used to do Diffie-Hellman key exchange and DSA/RSA signature verification. + if (!class_exists('Math_BigInteger')) { + include_once 'Math/BigInteger.php'; + } + + if (!function_exists('crypt_random_string')) { + include_once 'Crypt/Random.php'; + } + + if (!class_exists('Crypt_Hash')) { + include_once 'Crypt/Hash.php'; + } + + // include Crypt_Base so constants can be defined for setCryptoEngine() + if (!class_exists('Crypt_Base')) { + include_once 'Crypt/Base.php'; + } + + $this->message_numbers = array( + 1 => 'NET_SSH2_MSG_DISCONNECT', + 2 => 'NET_SSH2_MSG_IGNORE', + 3 => 'NET_SSH2_MSG_UNIMPLEMENTED', + 4 => 'NET_SSH2_MSG_DEBUG', + 5 => 'NET_SSH2_MSG_SERVICE_REQUEST', + 6 => 'NET_SSH2_MSG_SERVICE_ACCEPT', + 20 => 'NET_SSH2_MSG_KEXINIT', + 21 => 'NET_SSH2_MSG_NEWKEYS', + 30 => 'NET_SSH2_MSG_KEXDH_INIT', + 31 => 'NET_SSH2_MSG_KEXDH_REPLY', + 50 => 'NET_SSH2_MSG_USERAUTH_REQUEST', + 51 => 'NET_SSH2_MSG_USERAUTH_FAILURE', + 52 => 'NET_SSH2_MSG_USERAUTH_SUCCESS', + 53 => 'NET_SSH2_MSG_USERAUTH_BANNER', + + 80 => 'NET_SSH2_MSG_GLOBAL_REQUEST', + 81 => 'NET_SSH2_MSG_REQUEST_SUCCESS', + 82 => 'NET_SSH2_MSG_REQUEST_FAILURE', + 90 => 'NET_SSH2_MSG_CHANNEL_OPEN', + 91 => 'NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION', + 92 => 'NET_SSH2_MSG_CHANNEL_OPEN_FAILURE', + 93 => 'NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST', + 94 => 'NET_SSH2_MSG_CHANNEL_DATA', + 95 => 'NET_SSH2_MSG_CHANNEL_EXTENDED_DATA', + 96 => 'NET_SSH2_MSG_CHANNEL_EOF', + 97 => 'NET_SSH2_MSG_CHANNEL_CLOSE', + 98 => 'NET_SSH2_MSG_CHANNEL_REQUEST', + 99 => 'NET_SSH2_MSG_CHANNEL_SUCCESS', + 100 => 'NET_SSH2_MSG_CHANNEL_FAILURE' + ); + $this->disconnect_reasons = array( + 1 => 'NET_SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT', + 2 => 'NET_SSH2_DISCONNECT_PROTOCOL_ERROR', + 3 => 'NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED', + 4 => 'NET_SSH2_DISCONNECT_RESERVED', + 5 => 'NET_SSH2_DISCONNECT_MAC_ERROR', + 6 => 'NET_SSH2_DISCONNECT_COMPRESSION_ERROR', + 7 => 'NET_SSH2_DISCONNECT_SERVICE_NOT_AVAILABLE', + 8 => 'NET_SSH2_DISCONNECT_PROTOCOL_VERSION_NOT_SUPPORTED', + 9 => 'NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE', + 10 => 'NET_SSH2_DISCONNECT_CONNECTION_LOST', + 11 => 'NET_SSH2_DISCONNECT_BY_APPLICATION', + 12 => 'NET_SSH2_DISCONNECT_TOO_MANY_CONNECTIONS', + 13 => 'NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER', + 14 => 'NET_SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE', + 15 => 'NET_SSH2_DISCONNECT_ILLEGAL_USER_NAME' + ); + $this->channel_open_failure_reasons = array( + 1 => 'NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED' + ); + $this->terminal_modes = array( + 0 => 'NET_SSH2_TTY_OP_END' + ); + $this->channel_extended_data_type_codes = array( + 1 => 'NET_SSH2_EXTENDED_DATA_STDERR' + ); + + $this->_define_array( + $this->message_numbers, + $this->disconnect_reasons, + $this->channel_open_failure_reasons, + $this->terminal_modes, + $this->channel_extended_data_type_codes, + array(60 => 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'), + array(60 => 'NET_SSH2_MSG_USERAUTH_PK_OK'), + array(60 => 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST', + 61 => 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE'), + // RFC 4419 - diffie-hellman-group-exchange-sha{1,256} + array(30 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST_OLD', + 31 => 'NET_SSH2_MSG_KEXDH_GEX_GROUP', + 32 => 'NET_SSH2_MSG_KEXDH_GEX_INIT', + 33 => 'NET_SSH2_MSG_KEXDH_GEX_REPLY', + 34 => 'NET_SSH2_MSG_KEXDH_GEX_REQUEST') + ); + + if (is_resource($host)) { + $this->fsock = $host; + return; + } + + if (is_string($host)) { + $this->host = $host; + $this->port = $port; + $this->timeout = $timeout; + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param mixed $host + * @param int $port + * @param int $timeout + * @access public + */ + function Net_SSH2($host, $port = 22, $timeout = 10) + { + $this->__construct($host, $port, $timeout); + } + + /** + * Set Crypto Engine Mode + * + * Possible $engine values: + * CRYPT_MODE_INTERNAL, CRYPT_MODE_MCRYPT + * + * @param int $engine + * @access public + */ + function setCryptoEngine($engine) + { + $this->crypto_engine = $engine; + } + + /** + * Send Identification String First + * + * https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, + * both sides MUST send an identification string". It does not say which side sends it first. In + * theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy + * + * @access public + */ + function sendIdentificationStringFirst() + { + $this->send_id_string_first = true; + } + + /** + * Send Identification String Last + * + * https://tools.ietf.org/html/rfc4253#section-4.2 says "when the connection has been established, + * both sides MUST send an identification string". It does not say which side sends it first. In + * theory it shouldn't matter but it is a fact of life that some SSH servers are simply buggy + * + * @access public + */ + function sendIdentificationStringLast() + { + $this->send_id_string_first = false; + } + + /** + * Send SSH_MSG_KEXINIT First + * + * https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending + * sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory + * it shouldn't matter but it is a fact of life that some SSH servers are simply buggy + * + * @access public + */ + function sendKEXINITFirst() + { + $this->send_kex_first = true; + } + + /** + * Send SSH_MSG_KEXINIT Last + * + * https://tools.ietf.org/html/rfc4253#section-7.1 says "key exchange begins by each sending + * sending the [SSH_MSG_KEXINIT] packet". It does not say which side sends it first. In theory + * it shouldn't matter but it is a fact of life that some SSH servers are simply buggy + * + * @access public + */ + function sendKEXINITLast() + { + $this->send_kex_first = false; + } + + /** + * Connect to an SSHv2 server + * + * @return bool + * @access private + */ + function _connect() + { + if ($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR) { + return false; + } + + $this->bitmap |= NET_SSH2_MASK_CONSTRUCTOR; + + $this->curTimeout = $this->timeout; + + $this->last_packet = strtok(microtime(), ' ') + strtok(''); // == microtime(true) in PHP5 + + if (!is_resource($this->fsock)) { + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + // with stream_select a timeout of 0 means that no timeout takes place; + // with fsockopen a timeout of 0 means that you instantly timeout + // to resolve this incompatibility a timeout of 100,000 will be used for fsockopen if timeout is 0 + $this->fsock = @fsockopen($this->host, $this->port, $errno, $errstr, $this->curTimeout == 0 ? 100000 : $this->curTimeout); + if (!$this->fsock) { + $host = $this->host . ':' . $this->port; + user_error(rtrim("Cannot connect to $host. Error $errno. $errstr")); + return false; + } + $elapsed = strtok(microtime(), ' ') + strtok('') - $start; + + $this->curTimeout-= $elapsed; + + if ($this->curTimeout <= 0) { + $this->is_timeout = true; + return false; + } + } + + $this->identifier = $this->_generate_identifier(); + + if ($this->send_id_string_first) { + fputs($this->fsock, $this->identifier . "\r\n"); + } + + /* According to the SSH2 specs, + + "The server MAY send other lines of data before sending the version + string. Each line SHOULD be terminated by a Carriage Return and Line + Feed. Such lines MUST NOT begin with "SSH-", and SHOULD be encoded + in ISO-10646 UTF-8 [RFC3629] (language is not specified). Clients + MUST be able to process such lines." */ + $temp = ''; + $extra = ''; + while (!feof($this->fsock) && !preg_match('#^SSH-(\d\.\d+)#', $temp, $matches)) { + if (substr($temp, -2) == "\r\n") { + $extra.= $temp; + $temp = ''; + } + + if ($this->curTimeout) { + if ($this->curTimeout < 0) { + $this->is_timeout = true; + return false; + } + $read = array($this->fsock); + $write = $except = null; + $start = strtok(microtime(), ' ') + strtok(''); + $sec = floor($this->curTimeout); + $usec = 1000000 * ($this->curTimeout - $sec); + // on windows this returns a "Warning: Invalid CRT parameters detected" error + // the !count() is done as a workaround for + if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { + $this->is_timeout = true; + return false; + } + $elapsed = strtok(microtime(), ' ') + strtok('') - $start; + $this->curTimeout-= $elapsed; + } + + $temp.= fgets($this->fsock, 255); + } + + if (feof($this->fsock)) { + user_error('Connection closed by server'); + return false; + } + + if (defined('NET_SSH2_LOGGING')) { + $this->_append_log('<-', $extra . $temp); + $this->_append_log('->', $this->identifier . "\r\n"); + } + + $this->server_identifier = trim($temp, "\r\n"); + if (strlen($extra)) { + $this->errors[] = utf8_decode($extra); + } + + if (version_compare($matches[1], '1.99', '<')) { + user_error("Cannot connect to SSH $matches[1] servers"); + return false; + } + + if (!$this->send_id_string_first) { + fputs($this->fsock, $this->identifier . "\r\n"); + } + + if (!$this->send_kex_first) { + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response) || ord($response[0]) != NET_SSH2_MSG_KEXINIT) { + user_error('Expected SSH_MSG_KEXINIT'); + return false; + } + + if (!$this->_key_exchange($response)) { + return false; + } + } + + if ($this->send_kex_first && !$this->_key_exchange()) { + return false; + } + + $this->bitmap|= NET_SSH2_MASK_CONNECTED; + + return true; + } + + /** + * Generates the SSH identifier + * + * You should overwrite this method in your own class if you want to use another identifier + * + * @access protected + * @return string + */ + function _generate_identifier() + { + $identifier = 'SSH-2.0-phpseclib_1.0'; + + $ext = array(); + if (extension_loaded('openssl')) { + $ext[] = 'openssl'; + } elseif (extension_loaded('mcrypt')) { + $ext[] = 'mcrypt'; + } + + if (extension_loaded('gmp')) { + $ext[] = 'gmp'; + } elseif (extension_loaded('bcmath')) { + $ext[] = 'bcmath'; + } + + if (!empty($ext)) { + $identifier .= ' (' . implode(', ', $ext) . ')'; + } + + return $identifier; + } + + /** + * Key Exchange + * + * @param string $kexinit_payload_server optional + * @access private + */ + function _key_exchange($kexinit_payload_server = false) + { + static $kex_algorithms = array( + 'diffie-hellman-group1-sha1', // REQUIRED + 'diffie-hellman-group14-sha1', // REQUIRED + 'diffie-hellman-group-exchange-sha1', // RFC 4419 + 'diffie-hellman-group-exchange-sha256', // RFC 4419 + ); + + static $server_host_key_algorithms = array( + 'ssh-rsa', // RECOMMENDED sign Raw RSA Key + 'ssh-dss' // REQUIRED sign Raw DSS Key + ); + + static $encryption_algorithms = false; + if ($encryption_algorithms === false) { + $encryption_algorithms = array( + // from : + 'arcfour256', + 'arcfour128', + + //'arcfour', // OPTIONAL the ARCFOUR stream cipher with a 128-bit key + + // CTR modes from : + 'aes128-ctr', // RECOMMENDED AES (Rijndael) in SDCTR mode, with 128-bit key + 'aes192-ctr', // RECOMMENDED AES with 192-bit key + 'aes256-ctr', // RECOMMENDED AES with 256-bit key + + 'twofish128-ctr', // OPTIONAL Twofish in SDCTR mode, with 128-bit key + 'twofish192-ctr', // OPTIONAL Twofish with 192-bit key + 'twofish256-ctr', // OPTIONAL Twofish with 256-bit key + + 'aes128-cbc', // RECOMMENDED AES with a 128-bit key + 'aes192-cbc', // OPTIONAL AES with a 192-bit key + 'aes256-cbc', // OPTIONAL AES in CBC mode, with a 256-bit key + + 'twofish128-cbc', // OPTIONAL Twofish with a 128-bit key + 'twofish192-cbc', // OPTIONAL Twofish with a 192-bit key + 'twofish256-cbc', + 'twofish-cbc', // OPTIONAL alias for "twofish256-cbc" + // (this is being retained for historical reasons) + + 'blowfish-ctr', // OPTIONAL Blowfish in SDCTR mode + + 'blowfish-cbc', // OPTIONAL Blowfish in CBC mode + + '3des-ctr', // RECOMMENDED Three-key 3DES in SDCTR mode + + '3des-cbc', // REQUIRED three-key 3DES in CBC mode + //'none' // OPTIONAL no encryption; NOT RECOMMENDED + ); + + if (extension_loaded('openssl') && !extension_loaded('mcrypt')) { + // OpenSSL does not support arcfour256 in any capacity and arcfour128 / arcfour support is limited to + // instances that do not use continuous buffers + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('arcfour256', 'arcfour128', 'arcfour') + ); + } + + if (phpseclib_resolve_include_path('Crypt/RC4.php') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('arcfour256', 'arcfour128', 'arcfour') + ); + } + if (phpseclib_resolve_include_path('Crypt/Rijndael.php') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-cbc', 'aes192-cbc', 'aes256-cbc') + ); + } + if (phpseclib_resolve_include_path('Crypt/Twofish.php') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('twofish128-ctr', 'twofish192-ctr', 'twofish256-ctr', 'twofish128-cbc', 'twofish192-cbc', 'twofish256-cbc', 'twofish-cbc') + ); + } + if (phpseclib_resolve_include_path('Crypt/Blowfish.php') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('blowfish-ctr', 'blowfish-cbc') + ); + } + if (phpseclib_resolve_include_path('Crypt/TripleDES.php') === false) { + $encryption_algorithms = array_diff( + $encryption_algorithms, + array('3des-ctr', '3des-cbc') + ); + } + $encryption_algorithms = array_values($encryption_algorithms); + } + + $mac_algorithms = array( + // from : + 'hmac-sha2-256',// RECOMMENDED HMAC-SHA256 (digest length = key length = 32) + + 'hmac-sha1-96', // RECOMMENDED first 96 bits of HMAC-SHA1 (digest length = 12, key length = 20) + 'hmac-sha1', // REQUIRED HMAC-SHA1 (digest length = key length = 20) + 'hmac-md5-96', // OPTIONAL first 96 bits of HMAC-MD5 (digest length = 12, key length = 16) + 'hmac-md5', // OPTIONAL HMAC-MD5 (digest length = key length = 16) + //'none' // OPTIONAL no MAC; NOT RECOMMENDED + ); + + static $compression_algorithms = array( + 'none' // REQUIRED no compression + //'zlib' // OPTIONAL ZLIB (LZ77) compression + ); + + // some SSH servers have buggy implementations of some of the above algorithms + switch (true) { + case $this->server_identifier == 'SSH-2.0-SSHD': + case substr($this->server_identifier, 0, 13) == 'SSH-2.0-DLINK': + $mac_algorithms = array_values(array_diff( + $mac_algorithms, + array('hmac-sha1-96', 'hmac-md5-96') + )); + } + + static $str_kex_algorithms, $str_server_host_key_algorithms, + $encryption_algorithms_server_to_client, $mac_algorithms_server_to_client, $compression_algorithms_server_to_client, + $encryption_algorithms_client_to_server, $mac_algorithms_client_to_server, $compression_algorithms_client_to_server; + + if (empty($str_kex_algorithms)) { + $str_kex_algorithms = implode(',', $kex_algorithms); + $str_server_host_key_algorithms = implode(',', $server_host_key_algorithms); + $encryption_algorithms_server_to_client = $encryption_algorithms_client_to_server = implode(',', $encryption_algorithms); + $mac_algorithms_server_to_client = $mac_algorithms_client_to_server = implode(',', $mac_algorithms); + $compression_algorithms_server_to_client = $compression_algorithms_client_to_server = implode(',', $compression_algorithms); + } + + $client_cookie = crypt_random_string(16); + + $kexinit_payload_client = pack( + 'Ca*Na*Na*Na*Na*Na*Na*Na*Na*Na*Na*CN', + NET_SSH2_MSG_KEXINIT, + $client_cookie, + strlen($str_kex_algorithms), + $str_kex_algorithms, + strlen($str_server_host_key_algorithms), + $str_server_host_key_algorithms, + strlen($encryption_algorithms_client_to_server), + $encryption_algorithms_client_to_server, + strlen($encryption_algorithms_server_to_client), + $encryption_algorithms_server_to_client, + strlen($mac_algorithms_client_to_server), + $mac_algorithms_client_to_server, + strlen($mac_algorithms_server_to_client), + $mac_algorithms_server_to_client, + strlen($compression_algorithms_client_to_server), + $compression_algorithms_client_to_server, + strlen($compression_algorithms_server_to_client), + $compression_algorithms_server_to_client, + 0, + '', + 0, + '', + 0, + 0 + ); + + if ($this->send_kex_first) { + if (!$this->_send_binary_packet($kexinit_payload_client)) { + return false; + } + + $kexinit_payload_server = $this->_get_binary_packet(); + if ($kexinit_payload_server === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($kexinit_payload_server) || ord($kexinit_payload_server[0]) != NET_SSH2_MSG_KEXINIT) { + user_error('Expected SSH_MSG_KEXINIT'); + return false; + } + } + + $response = $kexinit_payload_server; + $this->_string_shift($response, 1); // skip past the message number (it should be SSH_MSG_KEXINIT) + $server_cookie = $this->_string_shift($response, 16); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->kex_algorithms = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->server_host_key_algorithms = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->encryption_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->encryption_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->mac_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->mac_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->compression_algorithms_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->compression_algorithms_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->languages_client_to_server = explode(',', $this->_string_shift($response, $temp['length'])); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->languages_server_to_client = explode(',', $this->_string_shift($response, $temp['length'])); + + if (!strlen($response)) { + return false; + } + extract(unpack('Cfirst_kex_packet_follows', $this->_string_shift($response, 1))); + $first_kex_packet_follows = $first_kex_packet_follows != 0; + + if (!$this->send_kex_first && !$this->_send_binary_packet($kexinit_payload_client)) { + return false; + } + + // we need to decide upon the symmetric encryption algorithms before we do the diffie-hellman key exchange + // we don't initialize any crypto-objects, yet - we do that, later. for now, we need the lengths to make the + // diffie-hellman key exchange as fast as possible + $decrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_server_to_client); + $decryptKeyLength = $this->_encryption_algorithm_to_key_size($decrypt); + if ($decryptKeyLength === null) { + user_error('No compatible server to client encryption algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $encrypt = $this->_array_intersect_first($encryption_algorithms, $this->encryption_algorithms_client_to_server); + $encryptKeyLength = $this->_encryption_algorithm_to_key_size($encrypt); + if ($encryptKeyLength === null) { + user_error('No compatible client to server encryption algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $keyLength = $decryptKeyLength > $encryptKeyLength ? $decryptKeyLength : $encryptKeyLength; + + // through diffie-hellman key exchange a symmetric key is obtained + $kex_algorithm = $this->_array_intersect_first($kex_algorithms, $this->kex_algorithms); + if ($kex_algorithm === false) { + user_error('No compatible key exchange algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + if (strpos($kex_algorithm, 'diffie-hellman-group-exchange') === 0) { + $dh_group_sizes_packed = pack( + 'NNN', + $this->kex_dh_group_size_min, + $this->kex_dh_group_size_preferred, + $this->kex_dh_group_size_max + ); + $packet = pack( + 'Ca*', + NET_SSH2_MSG_KEXDH_GEX_REQUEST, + $dh_group_sizes_packed + ); + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + if ($type != NET_SSH2_MSG_KEXDH_GEX_GROUP) { + user_error('Expected SSH_MSG_KEX_DH_GEX_GROUP'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('NprimeLength', $this->_string_shift($response, 4))); + $primeBytes = $this->_string_shift($response, $primeLength); + $prime = new Math_BigInteger($primeBytes, -256); + + if (strlen($response) < 4) { + return false; + } + extract(unpack('NgLength', $this->_string_shift($response, 4))); + $gBytes = $this->_string_shift($response, $gLength); + $g = new Math_BigInteger($gBytes, -256); + + $exchange_hash_rfc4419 = pack( + 'a*Na*Na*', + $dh_group_sizes_packed, + $primeLength, + $primeBytes, + $gLength, + $gBytes + ); + + $clientKexInitMessage = NET_SSH2_MSG_KEXDH_GEX_INIT; + $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_GEX_REPLY; + } else { + switch ($kex_algorithm) { + // see http://tools.ietf.org/html/rfc2409#section-6.2 and + // http://tools.ietf.org/html/rfc2412, appendex E + case 'diffie-hellman-group1-sha1': + $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' . + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' . + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' . + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE65381FFFFFFFFFFFFFFFF'; + break; + // see http://tools.ietf.org/html/rfc3526#section-3 + case 'diffie-hellman-group14-sha1': + $prime = 'FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74' . + '020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437' . + '4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED' . + 'EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05' . + '98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB' . + '9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B' . + 'E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718' . + '3995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF'; + break; + } + // For both diffie-hellman-group1-sha1 and diffie-hellman-group14-sha1 + // the generator field element is 2 (decimal) and the hash function is sha1. + $g = new Math_BigInteger(2); + $prime = new Math_BigInteger($prime, 16); + $exchange_hash_rfc4419 = ''; + $clientKexInitMessage = NET_SSH2_MSG_KEXDH_INIT; + $serverKexReplyMessage = NET_SSH2_MSG_KEXDH_REPLY; + } + + switch ($kex_algorithm) { + case 'diffie-hellman-group-exchange-sha256': + $kexHash = new Crypt_Hash('sha256'); + break; + default: + $kexHash = new Crypt_Hash('sha1'); + } + + /* To increase the speed of the key exchange, both client and server may + reduce the size of their private exponents. It should be at least + twice as long as the key material that is generated from the shared + secret. For more details, see the paper by van Oorschot and Wiener + [VAN-OORSCHOT]. + + -- http://tools.ietf.org/html/rfc4419#section-6.2 */ + $one = new Math_BigInteger(1); + $keyLength = min($keyLength, $kexHash->getLength()); + $max = $one->bitwise_leftShift(16 * $keyLength); // 2 * 8 * $keyLength + $max = $max->subtract($one); + + $x = $one->random($one, $max); + $e = $g->modPow($x, $prime); + + $eBytes = $e->toBytes(true); + $data = pack('CNa*', $clientKexInitMessage, strlen($eBytes), $eBytes); + + if (!$this->_send_binary_packet($data)) { + user_error('Connection closed by server'); + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + if ($type != $serverKexReplyMessage) { + user_error('Expected SSH_MSG_KEXDH_REPLY'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->server_public_host_key = $server_public_host_key = $this->_string_shift($response, $temp['length']); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $public_key_format = $this->_string_shift($server_public_host_key, $temp['length']); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $fBytes = $this->_string_shift($response, $temp['length']); + $f = new Math_BigInteger($fBytes, -256); + + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($response, 4)); + $this->signature = $this->_string_shift($response, $temp['length']); + + if (strlen($this->signature) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($this->signature, 4)); + $this->signature_format = $this->_string_shift($this->signature, $temp['length']); + + $key = $f->modPow($x, $prime); + $keyBytes = $key->toBytes(true); + + $this->exchange_hash = pack( + 'Na*Na*Na*Na*Na*a*Na*Na*Na*', + strlen($this->identifier), + $this->identifier, + strlen($this->server_identifier), + $this->server_identifier, + strlen($kexinit_payload_client), + $kexinit_payload_client, + strlen($kexinit_payload_server), + $kexinit_payload_server, + strlen($this->server_public_host_key), + $this->server_public_host_key, + $exchange_hash_rfc4419, + strlen($eBytes), + $eBytes, + strlen($fBytes), + $fBytes, + strlen($keyBytes), + $keyBytes + ); + + $this->exchange_hash = $kexHash->hash($this->exchange_hash); + + if ($this->session_id === false) { + $this->session_id = $this->exchange_hash; + } + + $server_host_key_algorithm = $this->_array_intersect_first($server_host_key_algorithms, $this->server_host_key_algorithms); + if ($server_host_key_algorithm === false) { + user_error('No compatible server host key algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + if ($public_key_format != $server_host_key_algorithm || $this->signature_format != $server_host_key_algorithm) { + user_error('Server Host Key Algorithm Mismatch'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $packet = pack( + 'C', + NET_SSH2_MSG_NEWKEYS + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + if ($type != NET_SSH2_MSG_NEWKEYS) { + user_error('Expected SSH_MSG_NEWKEYS'); + return false; + } + + switch ($encrypt) { + case '3des-cbc': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $this->encrypt = new Crypt_TripleDES(); + // $this->encrypt_block_size = 64 / 8 == the default + break; + case '3des-ctr': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $this->encrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR); + // $this->encrypt_block_size = 64 / 8 == the default + break; + case 'aes256-cbc': + case 'aes192-cbc': + case 'aes128-cbc': + if (!class_exists('Crypt_Rijndael')) { + include_once 'Crypt/Rijndael.php'; + } + $this->encrypt = new Crypt_Rijndael(); + $this->encrypt_block_size = 16; // eg. 128 / 8 + break; + case 'aes256-ctr': + case 'aes192-ctr': + case 'aes128-ctr': + if (!class_exists('Crypt_Rijndael')) { + include_once 'Crypt/Rijndael.php'; + } + $this->encrypt = new Crypt_Rijndael(CRYPT_RIJNDAEL_MODE_CTR); + $this->encrypt_block_size = 16; // eg. 128 / 8 + break; + case 'blowfish-cbc': + if (!class_exists('Crypt_Blowfish')) { + include_once 'Crypt/Blowfish.php'; + } + $this->encrypt = new Crypt_Blowfish(); + $this->encrypt_block_size = 8; + break; + case 'blowfish-ctr': + if (!class_exists('Crypt_Blowfish')) { + include_once 'Crypt/Blowfish.php'; + } + $this->encrypt = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR); + $this->encrypt_block_size = 8; + break; + case 'twofish128-cbc': + case 'twofish192-cbc': + case 'twofish256-cbc': + case 'twofish-cbc': + if (!class_exists('Crypt_Twofish')) { + include_once 'Crypt/Twofish.php'; + } + $this->encrypt = new Crypt_Twofish(); + $this->encrypt_block_size = 16; + break; + case 'twofish128-ctr': + case 'twofish192-ctr': + case 'twofish256-ctr': + if (!class_exists('Crypt_Twofish')) { + include_once 'Crypt/Twofish.php'; + } + $this->encrypt = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR); + $this->encrypt_block_size = 16; + break; + case 'arcfour': + case 'arcfour128': + case 'arcfour256': + if (!class_exists('Crypt_RC4')) { + include_once 'Crypt/RC4.php'; + } + $this->encrypt = new Crypt_RC4(); + break; + case 'none': + //$this->encrypt = new Crypt_Null(); + } + + switch ($decrypt) { + case '3des-cbc': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $this->decrypt = new Crypt_TripleDES(); + break; + case '3des-ctr': + if (!class_exists('Crypt_TripleDES')) { + include_once 'Crypt/TripleDES.php'; + } + $this->decrypt = new Crypt_TripleDES(CRYPT_DES_MODE_CTR); + break; + case 'aes256-cbc': + case 'aes192-cbc': + case 'aes128-cbc': + if (!class_exists('Crypt_Rijndael')) { + include_once 'Crypt/Rijndael.php'; + } + $this->decrypt = new Crypt_Rijndael(); + $this->decrypt_block_size = 16; + break; + case 'aes256-ctr': + case 'aes192-ctr': + case 'aes128-ctr': + if (!class_exists('Crypt_Rijndael')) { + include_once 'Crypt/Rijndael.php'; + } + $this->decrypt = new Crypt_Rijndael(CRYPT_RIJNDAEL_MODE_CTR); + $this->decrypt_block_size = 16; + break; + case 'blowfish-cbc': + if (!class_exists('Crypt_Blowfish')) { + include_once 'Crypt/Blowfish.php'; + } + $this->decrypt = new Crypt_Blowfish(); + $this->decrypt_block_size = 8; + break; + case 'blowfish-ctr': + if (!class_exists('Crypt_Blowfish')) { + include_once 'Crypt/Blowfish.php'; + } + $this->decrypt = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR); + $this->decrypt_block_size = 8; + break; + case 'twofish128-cbc': + case 'twofish192-cbc': + case 'twofish256-cbc': + case 'twofish-cbc': + if (!class_exists('Crypt_Twofish')) { + include_once 'Crypt/Twofish.php'; + } + $this->decrypt = new Crypt_Twofish(); + $this->decrypt_block_size = 16; + break; + case 'twofish128-ctr': + case 'twofish192-ctr': + case 'twofish256-ctr': + if (!class_exists('Crypt_Twofish')) { + include_once 'Crypt/Twofish.php'; + } + $this->decrypt = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR); + $this->decrypt_block_size = 16; + break; + case 'arcfour': + case 'arcfour128': + case 'arcfour256': + if (!class_exists('Crypt_RC4')) { + include_once 'Crypt/RC4.php'; + } + $this->decrypt = new Crypt_RC4(); + break; + case 'none': + //$this->decrypt = new Crypt_Null(); + } + + $this->decrypt_algorithm = $decrypt; + + $keyBytes = pack('Na*', strlen($keyBytes), $keyBytes); + + if ($this->encrypt) { + if ($this->crypto_engine) { + $this->encrypt->setEngine($this->crypto_engine); + } + $this->encrypt->enableContinuousBuffer(); + $this->encrypt->disablePadding(); + + $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'A' . $this->session_id); + while ($this->encrypt_block_size > strlen($iv)) { + $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); + } + $this->encrypt->setIV(substr($iv, 0, $this->encrypt_block_size)); + + $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'C' . $this->session_id); + while ($encryptKeyLength > strlen($key)) { + $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); + } + $this->encrypt->setKey(substr($key, 0, $encryptKeyLength)); + } + + if ($this->decrypt) { + if ($this->crypto_engine) { + $this->decrypt->setEngine($this->crypto_engine); + } + $this->decrypt->enableContinuousBuffer(); + $this->decrypt->disablePadding(); + + $iv = $kexHash->hash($keyBytes . $this->exchange_hash . 'B' . $this->session_id); + while ($this->decrypt_block_size > strlen($iv)) { + $iv.= $kexHash->hash($keyBytes . $this->exchange_hash . $iv); + } + $this->decrypt->setIV(substr($iv, 0, $this->decrypt_block_size)); + + $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'D' . $this->session_id); + while ($decryptKeyLength > strlen($key)) { + $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); + } + $this->decrypt->setKey(substr($key, 0, $decryptKeyLength)); + } + + /* The "arcfour128" algorithm is the RC4 cipher, as described in + [SCHNEIER], using a 128-bit key. The first 1536 bytes of keystream + generated by the cipher MUST be discarded, and the first byte of the + first encrypted packet MUST be encrypted using the 1537th byte of + keystream. + + -- http://tools.ietf.org/html/rfc4345#section-4 */ + if ($encrypt == 'arcfour128' || $encrypt == 'arcfour256') { + $this->encrypt->encrypt(str_repeat("\0", 1536)); + } + if ($decrypt == 'arcfour128' || $decrypt == 'arcfour256') { + $this->decrypt->decrypt(str_repeat("\0", 1536)); + } + + $mac_algorithm = $this->_array_intersect_first($mac_algorithms, $this->mac_algorithms_client_to_server); + if ($mac_algorithm === false) { + user_error('No compatible client to server message authentication algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $createKeyLength = 0; // ie. $mac_algorithm == 'none' + switch ($mac_algorithm) { + case 'hmac-sha2-256': + $this->hmac_create = new Crypt_Hash('sha256'); + $createKeyLength = 32; + break; + case 'hmac-sha1': + $this->hmac_create = new Crypt_Hash('sha1'); + $createKeyLength = 20; + break; + case 'hmac-sha1-96': + $this->hmac_create = new Crypt_Hash('sha1-96'); + $createKeyLength = 20; + break; + case 'hmac-md5': + $this->hmac_create = new Crypt_Hash('md5'); + $createKeyLength = 16; + break; + case 'hmac-md5-96': + $this->hmac_create = new Crypt_Hash('md5-96'); + $createKeyLength = 16; + } + + $mac_algorithm = $this->_array_intersect_first($mac_algorithms, $this->mac_algorithms_server_to_client); + if ($mac_algorithm === false) { + user_error('No compatible server to client message authentication algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $checkKeyLength = 0; + $this->hmac_size = 0; + switch ($mac_algorithm) { + case 'hmac-sha2-256': + $this->hmac_check = new Crypt_Hash('sha256'); + $checkKeyLength = 32; + $this->hmac_size = 32; + break; + case 'hmac-sha1': + $this->hmac_check = new Crypt_Hash('sha1'); + $checkKeyLength = 20; + $this->hmac_size = 20; + break; + case 'hmac-sha1-96': + $this->hmac_check = new Crypt_Hash('sha1-96'); + $checkKeyLength = 20; + $this->hmac_size = 12; + break; + case 'hmac-md5': + $this->hmac_check = new Crypt_Hash('md5'); + $checkKeyLength = 16; + $this->hmac_size = 16; + break; + case 'hmac-md5-96': + $this->hmac_check = new Crypt_Hash('md5-96'); + $checkKeyLength = 16; + $this->hmac_size = 12; + } + + $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'E' . $this->session_id); + while ($createKeyLength > strlen($key)) { + $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); + } + $this->hmac_create->setKey(substr($key, 0, $createKeyLength)); + + $key = $kexHash->hash($keyBytes . $this->exchange_hash . 'F' . $this->session_id); + while ($checkKeyLength > strlen($key)) { + $key.= $kexHash->hash($keyBytes . $this->exchange_hash . $key); + } + $this->hmac_check->setKey(substr($key, 0, $checkKeyLength)); + + $compression_algorithm = $this->_array_intersect_first($compression_algorithms, $this->compression_algorithms_server_to_client); + if ($compression_algorithm === false) { + user_error('No compatible server to client compression algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + $this->decompress = $compression_algorithm == 'zlib'; + + $compression_algorithm = $this->_array_intersect_first($compression_algorithms, $this->compression_algorithms_client_to_server); + if ($compression_algorithm === false) { + user_error('No compatible client to server compression algorithms found'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + $this->compress = $compression_algorithm == 'zlib'; + + return true; + } + + /** + * Maps an encryption algorithm name to the number of key bytes. + * + * @param string $algorithm Name of the encryption algorithm + * @return int|null Number of bytes as an integer or null for unknown + * @access private + */ + function _encryption_algorithm_to_key_size($algorithm) + { + if ($this->bad_key_size_fix && $this->_bad_algorithm_candidate($algorithm)) { + return 16; + } + + switch ($algorithm) { + case 'none': + return 0; + case 'aes128-cbc': + case 'aes128-ctr': + case 'arcfour': + case 'arcfour128': + case 'blowfish-cbc': + case 'blowfish-ctr': + case 'twofish128-cbc': + case 'twofish128-ctr': + return 16; + case '3des-cbc': + case '3des-ctr': + case 'aes192-cbc': + case 'aes192-ctr': + case 'twofish192-cbc': + case 'twofish192-ctr': + return 24; + case 'aes256-cbc': + case 'aes256-ctr': + case 'arcfour256': + case 'twofish-cbc': + case 'twofish256-cbc': + case 'twofish256-ctr': + return 32; + } + return null; + } + + /** + * Tests whether or not proposed algorithm has a potential for issues + * + * @link https://www.chiark.greenend.org.uk/~sgtatham/putty/wishlist/ssh2-aesctr-openssh.html + * @link https://bugzilla.mindrot.org/show_bug.cgi?id=1291 + * @param string $algorithm Name of the encryption algorithm + * @return bool + * @access private + */ + function _bad_algorithm_candidate($algorithm) + { + switch ($algorithm) { + case 'arcfour256': + case 'aes192-ctr': + case 'aes256-ctr': + return true; + } + + return false; + } + + /** + * Login + * + * The $password parameter can be a plaintext password, a Crypt_RSA object or an array + * + * @param string $username + * @param mixed $password + * @param mixed $... + * @return bool + * @see self::_login() + * @access public + */ + function login($username) + { + $args = func_get_args(); + return call_user_func_array(array(&$this, '_login'), $args); + } + + /** + * Login Helper + * + * @param string $username + * @param mixed $password + * @param mixed $... + * @return bool + * @see self::_login_helper() + * @access private + */ + function _login($username) + { + if (!($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR)) { + if (!$this->_connect()) { + return false; + } + } + + $args = array_slice(func_get_args(), 1); + if (empty($args)) { + return $this->_login_helper($username); + } + + foreach ($args as $arg) { + if ($this->_login_helper($username, $arg)) { + return true; + } + } + return false; + } + + /** + * Login Helper + * + * @param string $username + * @param string $password + * @return bool + * @access private + * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} + * by sending dummy SSH_MSG_IGNORE messages. + */ + function _login_helper($username, $password = null) + { + if (!($this->bitmap & NET_SSH2_MASK_CONNECTED)) { + return false; + } + + if (!($this->bitmap & NET_SSH2_MASK_LOGIN_REQ)) { + $packet = pack( + 'CNa*', + NET_SSH2_MSG_SERVICE_REQUEST, + strlen('ssh-userauth'), + 'ssh-userauth' + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + if ($this->retry_connect) { + $this->retry_connect = false; + if (!$this->_connect()) { + return false; + } + return $this->_login_helper($username, $password); + } + user_error('Connection closed by server'); + return false; + } + + if (strlen($response) < 4) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + if ($type != NET_SSH2_MSG_SERVICE_ACCEPT) { + user_error('Expected SSH_MSG_SERVICE_ACCEPT'); + return false; + } + $this->bitmap |= NET_SSH2_MASK_LOGIN_REQ; + } + + if (strlen($this->last_interactive_response)) { + return !is_string($password) && !is_array($password) ? false : $this->_keyboard_interactive_process($password); + } + + // although PHP5's get_class() preserves the case, PHP4's does not + if (is_object($password)) { + switch (strtolower(get_class($password))) { + case 'crypt_rsa': + return $this->_privatekey_login($username, $password); + case 'system_ssh_agent': + return $this->_ssh_agent_login($username, $password); + } + } + + if (is_array($password)) { + if ($this->_keyboard_interactive_login($username, $password)) { + $this->bitmap |= NET_SSH2_MASK_LOGIN; + return true; + } + return false; + } + + if (!isset($password)) { + $packet = pack( + 'CNa*Na*Na*', + NET_SSH2_MSG_USERAUTH_REQUEST, + strlen($username), + $username, + strlen('ssh-connection'), + 'ssh-connection', + strlen('none'), + 'none' + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + switch ($type) { + case NET_SSH2_MSG_USERAUTH_SUCCESS: + $this->bitmap |= NET_SSH2_MASK_LOGIN; + return true; + //case NET_SSH2_MSG_USERAUTH_FAILURE: + default: + return false; + } + } + + $packet = pack( + 'CNa*Na*Na*CNa*', + NET_SSH2_MSG_USERAUTH_REQUEST, + strlen($username), + $username, + strlen('ssh-connection'), + 'ssh-connection', + strlen('password'), + 'password', + 0, + strlen($password), + $password + ); + + // remove the username and password from the logged packet + if (!defined('NET_SSH2_LOGGING')) { + $logged = null; + } else { + $logged = pack( + 'CNa*Na*Na*CNa*', + NET_SSH2_MSG_USERAUTH_REQUEST, + strlen('username'), + 'username', + strlen('ssh-connection'), + 'ssh-connection', + strlen('password'), + 'password', + 0, + strlen('password'), + 'password' + ); + } + + if (!$this->_send_binary_packet($packet, $logged)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + switch ($type) { + case NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ: // in theory, the password can be changed + if (defined('NET_SSH2_LOGGING')) { + $this->message_number_log[count($this->message_number_log) - 1] = 'NET_SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ'; + } + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->errors[] = 'SSH_MSG_USERAUTH_PASSWD_CHANGEREQ: ' . utf8_decode($this->_string_shift($response, $length)); + return $this->_disconnect(NET_SSH2_DISCONNECT_AUTH_CANCELLED_BY_USER); + case NET_SSH2_MSG_USERAUTH_FAILURE: + // can we use keyboard-interactive authentication? if not then either the login is bad or the server employees + // multi-factor authentication + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $auth_methods = explode(',', $this->_string_shift($response, $length)); + if (!strlen($response)) { + return false; + } + extract(unpack('Cpartial_success', $this->_string_shift($response, 1))); + $partial_success = $partial_success != 0; + + if (!$partial_success && in_array('keyboard-interactive', $auth_methods)) { + if ($this->_keyboard_interactive_login($username, $password)) { + $this->bitmap |= NET_SSH2_MASK_LOGIN; + return true; + } + return false; + } + return false; + case NET_SSH2_MSG_USERAUTH_SUCCESS: + $this->bitmap |= NET_SSH2_MASK_LOGIN; + return true; + } + + return false; + } + + /** + * Login via keyboard-interactive authentication + * + * See {@link http://tools.ietf.org/html/rfc4256 RFC4256} for details. This is not a full-featured keyboard-interactive authenticator. + * + * @param string $username + * @param string $password + * @return bool + * @access private + */ + function _keyboard_interactive_login($username, $password) + { + $packet = pack( + 'CNa*Na*Na*Na*Na*', + NET_SSH2_MSG_USERAUTH_REQUEST, + strlen($username), + $username, + strlen('ssh-connection'), + 'ssh-connection', + strlen('keyboard-interactive'), + 'keyboard-interactive', + 0, + '', + 0, + '' + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + return $this->_keyboard_interactive_process($password); + } + + /** + * Handle the keyboard-interactive requests / responses. + * + * @param string $responses... + * @return bool + * @access private + */ + function _keyboard_interactive_process() + { + $responses = func_get_args(); + + if (strlen($this->last_interactive_response)) { + $response = $this->last_interactive_response; + } else { + $orig = $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + switch ($type) { + case NET_SSH2_MSG_USERAUTH_INFO_REQUEST: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->_string_shift($response, $length); // name; may be empty + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->_string_shift($response, $length); // instruction; may be empty + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->_string_shift($response, $length); // language tag; may be empty + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nnum_prompts', $this->_string_shift($response, 4))); + + for ($i = 0; $i < count($responses); $i++) { + if (is_array($responses[$i])) { + foreach ($responses[$i] as $key => $value) { + $this->keyboard_requests_responses[$key] = $value; + } + unset($responses[$i]); + } + } + $responses = array_values($responses); + + if (isset($this->keyboard_requests_responses)) { + for ($i = 0; $i < $num_prompts; $i++) { + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + // prompt - ie. "Password: "; must not be empty + $prompt = $this->_string_shift($response, $length); + //$echo = $this->_string_shift($response) != chr(0); + foreach ($this->keyboard_requests_responses as $key => $value) { + if (substr($prompt, 0, strlen($key)) == $key) { + $responses[] = $value; + break; + } + } + } + } + + // see http://tools.ietf.org/html/rfc4256#section-3.2 + if (strlen($this->last_interactive_response)) { + $this->last_interactive_response = ''; + } elseif (defined('NET_SSH2_LOGGING')) { + $this->message_number_log[count($this->message_number_log) - 1] = str_replace( + 'UNKNOWN', + 'NET_SSH2_MSG_USERAUTH_INFO_REQUEST', + $this->message_number_log[count($this->message_number_log) - 1] + ); + } + + if (!count($responses) && $num_prompts) { + $this->last_interactive_response = $orig; + return false; + } + + /* + After obtaining the requested information from the user, the client + MUST respond with an SSH_MSG_USERAUTH_INFO_RESPONSE message. + */ + // see http://tools.ietf.org/html/rfc4256#section-3.4 + $packet = $logged = pack('CN', NET_SSH2_MSG_USERAUTH_INFO_RESPONSE, count($responses)); + for ($i = 0; $i < count($responses); $i++) { + $packet.= pack('Na*', strlen($responses[$i]), $responses[$i]); + $logged.= pack('Na*', strlen('dummy-answer'), 'dummy-answer'); + } + + if (!$this->_send_binary_packet($packet, $logged)) { + return false; + } + + if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) { + $this->message_number_log[count($this->message_number_log) - 1] = str_replace( + 'UNKNOWN', + 'NET_SSH2_MSG_USERAUTH_INFO_RESPONSE', + $this->message_number_log[count($this->message_number_log) - 1] + ); + } + + /* + After receiving the response, the server MUST send either an + SSH_MSG_USERAUTH_SUCCESS, SSH_MSG_USERAUTH_FAILURE, or another + SSH_MSG_USERAUTH_INFO_REQUEST message. + */ + // maybe phpseclib should force close the connection after x request / responses? unless something like that is done + // there could be an infinite loop of request / responses. + return $this->_keyboard_interactive_process(); + case NET_SSH2_MSG_USERAUTH_SUCCESS: + return true; + case NET_SSH2_MSG_USERAUTH_FAILURE: + return false; + } + + return false; + } + + /** + * Login with an ssh-agent provided key + * + * @param string $username + * @param System_SSH_Agent $agent + * @return bool + * @access private + */ + function _ssh_agent_login($username, $agent) + { + $this->agent = $agent; + $keys = $agent->requestIdentities(); + foreach ($keys as $key) { + if ($this->_privatekey_login($username, $key)) { + return true; + } + } + + return false; + } + + /** + * Login with an RSA private key + * + * @param string $username + * @param Crypt_RSA $password + * @return bool + * @access private + * @internal It might be worthwhile, at some point, to protect against {@link http://tools.ietf.org/html/rfc4251#section-9.3.9 traffic analysis} + * by sending dummy SSH_MSG_IGNORE messages. + */ + function _privatekey_login($username, $privatekey) + { + // see http://tools.ietf.org/html/rfc4253#page-15 + $publickey = $privatekey->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_RAW); + if ($publickey === false) { + return false; + } + + $publickey = array( + 'e' => $publickey['e']->toBytes(true), + 'n' => $publickey['n']->toBytes(true) + ); + $publickey = pack( + 'Na*Na*Na*', + strlen('ssh-rsa'), + 'ssh-rsa', + strlen($publickey['e']), + $publickey['e'], + strlen($publickey['n']), + $publickey['n'] + ); + + $part1 = pack( + 'CNa*Na*Na*', + NET_SSH2_MSG_USERAUTH_REQUEST, + strlen($username), + $username, + strlen('ssh-connection'), + 'ssh-connection', + strlen('publickey'), + 'publickey' + ); + $part2 = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publickey), $publickey); + + $packet = $part1 . chr(0) . $part2; + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + switch ($type) { + case NET_SSH2_MSG_USERAUTH_FAILURE: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->errors[] = 'SSH_MSG_USERAUTH_FAILURE: ' . $this->_string_shift($response, $length); + return false; + case NET_SSH2_MSG_USERAUTH_PK_OK: + // we'll just take it on faith that the public key blob and the public key algorithm name are as + // they should be + if (defined('NET_SSH2_LOGGING') && NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX) { + $this->message_number_log[count($this->message_number_log) - 1] = str_replace( + 'UNKNOWN', + 'NET_SSH2_MSG_USERAUTH_PK_OK', + $this->message_number_log[count($this->message_number_log) - 1] + ); + } + } + + $packet = $part1 . chr(1) . $part2; + $privatekey->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); + $signature = $privatekey->sign(pack('Na*a*', strlen($this->session_id), $this->session_id, $packet)); + $signature = pack('Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($signature), $signature); + $packet.= pack('Na*', strlen($signature), $signature); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + switch ($type) { + case NET_SSH2_MSG_USERAUTH_FAILURE: + // either the login is bad or the server employs multi-factor authentication + return false; + case NET_SSH2_MSG_USERAUTH_SUCCESS: + $this->bitmap |= NET_SSH2_MASK_LOGIN; + return true; + } + + return false; + } + + /** + * Set Timeout + * + * $ssh->exec('ping 127.0.0.1'); on a Linux host will never return and will run indefinitely. setTimeout() makes it so it'll timeout. + * Setting $timeout to false or 0 will mean there is no timeout. + * + * @param mixed $timeout + * @access public + */ + function setTimeout($timeout) + { + $this->timeout = $this->curTimeout = $timeout; + } + + /** + * Get the output from stdError + * + * @access public + */ + function getStdError() + { + return $this->stdErrorLog; + } + + /** + * Execute Command + * + * If $callback is set to false then Net_SSH2::_get_channel_packet(NET_SSH2_CHANNEL_EXEC) will need to be called manually. + * In all likelihood, this is not a feature you want to be taking advantage of. + * + * @param string $command + * @param Callback $callback + * @return string + * @access public + */ + function exec($command, $callback = null) + { + $this->curTimeout = $this->timeout; + $this->is_timeout = false; + $this->stdErrorLog = ''; + + if (!$this->isAuthenticated()) { + return false; + } + + if ($this->in_request_pty_exec) { + user_error('If you want to run multiple exec()\'s you will need to disable (and re-enable if appropriate) a PTY for each one.'); + return false; + } + + // RFC4254 defines the (client) window size as "bytes the other party can send before it must wait for the window to + // be adjusted". 0x7FFFFFFF is, at 2GB, the max size. technically, it should probably be decremented, but, + // honestly, if you're transferring more than 2GB, you probably shouldn't be using phpseclib, anyway. + // see http://tools.ietf.org/html/rfc4254#section-5.2 for more info + $this->window_size_server_to_client[NET_SSH2_CHANNEL_EXEC] = $this->window_size; + // 0x8000 is the maximum max packet size, per http://tools.ietf.org/html/rfc4253#section-6.1, although since PuTTy + // uses 0x4000, that's what will be used here, as well. + $packet_size = 0x4000; + + $packet = pack( + 'CNa*N3', + NET_SSH2_MSG_CHANNEL_OPEN, + strlen('session'), + 'session', + NET_SSH2_CHANNEL_EXEC, + $this->window_size_server_to_client[NET_SSH2_CHANNEL_EXEC], + $packet_size + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_OPEN; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC); + if ($response === false) { + return false; + } + + if ($this->request_pty === true) { + $terminal_modes = pack('C', NET_SSH2_TTY_OP_END); + $packet = pack( + 'CNNa*CNa*N5a*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SSH2_CHANNEL_EXEC], + strlen('pty-req'), + 'pty-req', + 1, + strlen('vt100'), + 'vt100', + $this->windowColumns, + $this->windowRows, + 0, + 0, + strlen($terminal_modes), + $terminal_modes + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + list(, $type) = unpack('C', $this->_string_shift($response, 1)); + + switch ($type) { + case NET_SSH2_MSG_CHANNEL_SUCCESS: + break; + case NET_SSH2_MSG_CHANNEL_FAILURE: + default: + user_error('Unable to request pseudo-terminal'); + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + $this->in_request_pty_exec = true; + } + + // sending a pty-req SSH_MSG_CHANNEL_REQUEST message is unnecessary and, in fact, in most cases, slows things + // down. the one place where it might be desirable is if you're doing something like Net_SSH2::exec('ping localhost &'). + // with a pty-req SSH_MSG_CHANNEL_REQUEST, exec() will return immediately and the ping process will then + // then immediately terminate. without such a request exec() will loop indefinitely. the ping process won't end but + // neither will your script. + + // although, in theory, the size of SSH_MSG_CHANNEL_REQUEST could exceed the maximum packet size established by + // SSH_MSG_CHANNEL_OPEN_CONFIRMATION, RFC4254#section-5.1 states that the "maximum packet size" refers to the + // "maximum size of an individual data packet". ie. SSH_MSG_CHANNEL_DATA. RFC4254#section-5.2 corroborates. + $packet = pack( + 'CNNa*CNa*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SSH2_CHANNEL_EXEC], + strlen('exec'), + 'exec', + 1, + strlen($command), + $command + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_REQUEST; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC); + if ($response === false) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_EXEC] = NET_SSH2_MSG_CHANNEL_DATA; + + if ($callback === false || $this->in_request_pty_exec) { + return true; + } + + $output = ''; + while (true) { + $temp = $this->_get_channel_packet(NET_SSH2_CHANNEL_EXEC); + switch (true) { + case $temp === true: + return is_callable($callback) ? true : $output; + case $temp === false: + return false; + default: + if (is_callable($callback)) { + if (call_user_func($callback, $temp) === true) { + $this->_close_channel(NET_SSH2_CHANNEL_EXEC); + return true; + } + } else { + $output.= $temp; + } + } + } + } + + /** + * Creates an interactive shell + * + * @see self::read() + * @see self::write() + * @return bool + * @access private + */ + function _initShell() + { + if ($this->in_request_pty_exec === true) { + return true; + } + + $this->window_size_server_to_client[NET_SSH2_CHANNEL_SHELL] = $this->window_size; + $packet_size = 0x4000; + + $packet = pack( + 'CNa*N3', + NET_SSH2_MSG_CHANNEL_OPEN, + strlen('session'), + 'session', + NET_SSH2_CHANNEL_SHELL, + $this->window_size_server_to_client[NET_SSH2_CHANNEL_SHELL], + $packet_size + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_OPEN; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SHELL); + if ($response === false) { + return false; + } + + $terminal_modes = pack('C', NET_SSH2_TTY_OP_END); + $packet = pack( + 'CNNa*CNa*N5a*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SSH2_CHANNEL_SHELL], + strlen('pty-req'), + 'pty-req', + 1, + strlen('vt100'), + 'vt100', + $this->windowColumns, + $this->windowRows, + 0, + 0, + strlen($terminal_modes), + $terminal_modes + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $response = $this->_get_binary_packet(); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + + if (!strlen($response)) { + return false; + } + list(, $type) = unpack('C', $this->_string_shift($response, 1)); + + switch ($type) { + case NET_SSH2_MSG_CHANNEL_SUCCESS: + // if a pty can't be opened maybe commands can still be executed + case NET_SSH2_MSG_CHANNEL_FAILURE: + break; + default: + user_error('Unable to request pseudo-terminal'); + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + + $packet = pack( + 'CNNa*C', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SSH2_CHANNEL_SHELL], + strlen('shell'), + 'shell', + 1 + ); + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_REQUEST; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SHELL); + if ($response === false) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SHELL] = NET_SSH2_MSG_CHANNEL_DATA; + + $this->bitmap |= NET_SSH2_MASK_SHELL; + + return true; + } + + /** + * Return the channel to be used with read() / write() + * + * @see self::read() + * @see self::write() + * @return int + * @access public + */ + function _get_interactive_channel() + { + switch (true) { + case $this->in_subsystem: + return NET_SSH2_CHANNEL_SUBSYSTEM; + case $this->in_request_pty_exec: + return NET_SSH2_CHANNEL_EXEC; + default: + return NET_SSH2_CHANNEL_SHELL; + } + } + + /** + * Return an available open channel + * + * @return int + * @access public + */ + function _get_open_channel() + { + $channel = NET_SSH2_CHANNEL_EXEC; + do { + if (isset($this->channel_status[$channel]) && $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_OPEN) { + return $channel; + } + } while ($channel++ < NET_SSH2_CHANNEL_SUBSYSTEM); + + return false; + } + + /** + * Returns the output of an interactive shell + * + * Returns when there's a match for $expect, which can take the form of a string literal or, + * if $mode == NET_SSH2_READ_REGEX, a regular expression. + * + * @see self::write() + * @param string $expect + * @param int $mode + * @return string + * @access public + */ + function read($expect = '', $mode = NET_SSH2_READ_SIMPLE) + { + $this->curTimeout = $this->timeout; + $this->is_timeout = false; + + if (!$this->isAuthenticated()) { + user_error('Operation disallowed prior to login()'); + return false; + } + + if (!($this->bitmap & NET_SSH2_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session'); + return false; + } + + $channel = $this->_get_interactive_channel(); + + if ($mode == NET_SSH2_READ_NEXT) { + return $this->_get_channel_packet($channel); + } + + $match = $expect; + while (true) { + if ($mode == NET_SSH2_READ_REGEX) { + preg_match($expect, substr($this->interactiveBuffer, -1024), $matches); + $match = isset($matches[0]) ? $matches[0] : ''; + } + $pos = strlen($match) ? strpos($this->interactiveBuffer, $match) : false; + if ($pos !== false) { + return $this->_string_shift($this->interactiveBuffer, $pos + strlen($match)); + } + $response = $this->_get_channel_packet($channel); + if (is_bool($response)) { + $this->in_request_pty_exec = false; + return $response ? $this->_string_shift($this->interactiveBuffer, strlen($this->interactiveBuffer)) : false; + } + + $this->interactiveBuffer.= $response; + } + } + + /** + * Inputs a command into an interactive shell. + * + * @see self::read() + * @param string $cmd + * @return bool + * @access public + */ + function write($cmd) + { + if (!$this->isAuthenticated()) { + user_error('Operation disallowed prior to login()'); + return false; + } + + if (!($this->bitmap & NET_SSH2_MASK_SHELL) && !$this->_initShell()) { + user_error('Unable to initiate an interactive shell session'); + return false; + } + + return $this->_send_channel_packet($this->_get_interactive_channel(), $cmd); + } + + /** + * Start a subsystem. + * + * Right now only one subsystem at a time is supported. To support multiple subsystem's stopSubsystem() could accept + * a string that contained the name of the subsystem, but at that point, only one subsystem of each type could be opened. + * To support multiple subsystem's of the same name maybe it'd be best if startSubsystem() generated a new channel id and + * returns that and then that that was passed into stopSubsystem() but that'll be saved for a future date and implemented + * if there's sufficient demand for such a feature. + * + * @see self::stopSubsystem() + * @param string $subsystem + * @return bool + * @access public + */ + function startSubsystem($subsystem) + { + $this->window_size_server_to_client[NET_SSH2_CHANNEL_SUBSYSTEM] = $this->window_size; + + $packet = pack( + 'CNa*N3', + NET_SSH2_MSG_CHANNEL_OPEN, + strlen('session'), + 'session', + NET_SSH2_CHANNEL_SUBSYSTEM, + $this->window_size, + 0x4000 + ); + + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_OPEN; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SUBSYSTEM); + if ($response === false) { + return false; + } + + $packet = pack( + 'CNNa*CNa*', + NET_SSH2_MSG_CHANNEL_REQUEST, + $this->server_channels[NET_SSH2_CHANNEL_SUBSYSTEM], + strlen('subsystem'), + 'subsystem', + 1, + strlen($subsystem), + $subsystem + ); + if (!$this->_send_binary_packet($packet)) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_REQUEST; + + $response = $this->_get_channel_packet(NET_SSH2_CHANNEL_SUBSYSTEM); + + if ($response === false) { + return false; + } + + $this->channel_status[NET_SSH2_CHANNEL_SUBSYSTEM] = NET_SSH2_MSG_CHANNEL_DATA; + + $this->bitmap |= NET_SSH2_MASK_SHELL; + $this->in_subsystem = true; + + return true; + } + + /** + * Stops a subsystem. + * + * @see self::startSubsystem() + * @return bool + * @access public + */ + function stopSubsystem() + { + $this->in_subsystem = false; + $this->_close_channel(NET_SSH2_CHANNEL_SUBSYSTEM); + return true; + } + + /** + * Closes a channel + * + * If read() timed out you might want to just close the channel and have it auto-restart on the next read() call + * + * @access public + */ + function reset() + { + $this->_close_channel($this->_get_interactive_channel()); + } + + /** + * Is timeout? + * + * Did exec() or read() return because they timed out or because they encountered the end? + * + * @access public + */ + function isTimeout() + { + return $this->is_timeout; + } + + /** + * Disconnect + * + * @access public + */ + function disconnect() + { + $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + if (isset($this->realtime_log_file) && is_resource($this->realtime_log_file)) { + fclose($this->realtime_log_file); + } + } + + /** + * Destructor. + * + * Will be called, automatically, if you're supporting just PHP5. If you're supporting PHP4, you'll need to call + * disconnect(). + * + * @access public + */ + function __destruct() + { + $this->disconnect(); + } + + /** + * Is the connection still active? + * + * @return bool + * @access public + */ + function isConnected() + { + return (bool) ($this->bitmap & NET_SSH2_MASK_CONNECTED); + } + + /** + * Have you successfully been logged in? + * + * @return bool + * @access public + */ + function isAuthenticated() + { + return (bool) ($this->bitmap & NET_SSH2_MASK_LOGIN); + } + + /** + * Resets a connection for re-use + * + * @param int $reason + * @access private + */ + function _reset_connection($reason) + { + $this->_disconnect($reason); + $this->decrypt = $this->encrypt = false; + $this->decrypt_block_size = $this->encrypt_block_size = 8; + $this->hmac_check = $this->hmac_create = false; + $this->hmac_size = false; + $this->session_id = false; + $this->retry_connect = true; + $this->get_seq_no = $this->send_seq_no = 0; + } + + /** + * Gets Binary Packets + * + * See '6. Binary Packet Protocol' of rfc4253 for more info. + * + * @see self::_send_binary_packet() + * @return string + * @access private + */ + function _get_binary_packet($skip_channel_filter = false) + { + if (!is_resource($this->fsock) || feof($this->fsock)) { + user_error('Connection closed prematurely'); + $this->bitmap = 0; + return false; + } + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $raw = fread($this->fsock, $this->decrypt_block_size); + + if (!strlen($raw)) { + return ''; + } + + if ($this->decrypt !== false) { + $raw = $this->decrypt->decrypt($raw); + } + if ($raw === false) { + user_error('Unable to decrypt content'); + return false; + } + + if (strlen($raw) < 5) { + return false; + } + extract(unpack('Npacket_length/Cpadding_length', $this->_string_shift($raw, 5))); + + $remaining_length = $packet_length + 4 - $this->decrypt_block_size; + + // quoting , + // "implementations SHOULD check that the packet length is reasonable" + // PuTTY uses 0x9000 as the actual max packet size and so to shall we + if ($remaining_length < -$this->decrypt_block_size || $remaining_length > 0x9000 || $remaining_length % $this->decrypt_block_size != 0) { + if (!$this->bad_key_size_fix && $this->_bad_algorithm_candidate($this->decrypt_algorithm) && !($this->bitmap & NET_SSH2_MASK_LOGIN)) { + $this->bad_key_size_fix = true; + $this->_reset_connection(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + return false; + } + user_error('Invalid size'); + return false; + } + + $buffer = ''; + while ($remaining_length > 0) { + $temp = fread($this->fsock, $remaining_length); + if ($temp === false || feof($this->fsock)) { + user_error('Error reading from socket'); + $this->bitmap = 0; + return false; + } + $buffer.= $temp; + $remaining_length-= strlen($temp); + } + + $stop = strtok(microtime(), ' ') + strtok(''); + if (strlen($buffer)) { + $raw.= $this->decrypt !== false ? $this->decrypt->decrypt($buffer) : $buffer; + } + + $payload = $this->_string_shift($raw, $packet_length - $padding_length - 1); + $padding = $this->_string_shift($raw, $padding_length); // should leave $raw empty + + if ($this->hmac_check !== false) { + $hmac = fread($this->fsock, $this->hmac_size); + if ($hmac === false || strlen($hmac) != $this->hmac_size) { + user_error('Error reading socket'); + $this->bitmap = 0; + return false; + } elseif ($hmac != $this->hmac_check->hash(pack('NNCa*', $this->get_seq_no, $packet_length, $padding_length, $payload . $padding))) { + user_error('Invalid HMAC'); + return false; + } + } + + //if ($this->decompress) { + // $payload = gzinflate(substr($payload, 2)); + //} + + $this->get_seq_no++; + + if (defined('NET_SSH2_LOGGING')) { + $current = strtok(microtime(), ' ') + strtok(''); + $message_number = isset($this->message_numbers[ord($payload[0])]) ? $this->message_numbers[ord($payload[0])] : 'UNKNOWN (' . ord($payload[0]) . ')'; + $message_number = '<- ' . $message_number . + ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)'; + $this->_append_log($message_number, $payload); + $this->last_packet = $current; + } + + return $this->_filter($payload, $skip_channel_filter); + } + + /** + * Filter Binary Packets + * + * Because some binary packets need to be ignored... + * + * @see self::_get_binary_packet() + * @return string + * @access private + */ + function _filter($payload, $skip_channel_filter) + { + switch (ord($payload[0])) { + case NET_SSH2_MSG_DISCONNECT: + $this->_string_shift($payload, 1); + if (strlen($payload) < 8) { + return false; + } + extract(unpack('Nreason_code/Nlength', $this->_string_shift($payload, 8))); + $this->errors[] = 'SSH_MSG_DISCONNECT: ' . $this->disconnect_reasons[$reason_code] . "\r\n" . utf8_decode($this->_string_shift($payload, $length)); + $this->bitmap = 0; + return false; + case NET_SSH2_MSG_IGNORE: + $payload = $this->_get_binary_packet($skip_channel_filter); + break; + case NET_SSH2_MSG_DEBUG: + $this->_string_shift($payload, 2); + if (strlen($payload) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($payload, 4))); + $this->errors[] = 'SSH_MSG_DEBUG: ' . utf8_decode($this->_string_shift($payload, $length)); + $payload = $this->_get_binary_packet($skip_channel_filter); + break; + case NET_SSH2_MSG_UNIMPLEMENTED: + return false; + case NET_SSH2_MSG_KEXINIT: + if ($this->session_id !== false) { + $this->send_kex_first = false; + if (!$this->_key_exchange($payload)) { + $this->bitmap = 0; + return false; + } + $payload = $this->_get_binary_packet($skip_channel_filter); + } + } + + // see http://tools.ietf.org/html/rfc4252#section-5.4; only called when the encryption has been activated and when we haven't already logged in + if (($this->bitmap & NET_SSH2_MASK_CONNECTED) && !$this->isAuthenticated() && ord($payload[0]) == NET_SSH2_MSG_USERAUTH_BANNER) { + $this->_string_shift($payload, 1); + if (strlen($payload) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($payload, 4))); + $this->banner_message = utf8_decode($this->_string_shift($payload, $length)); + $payload = $this->_get_binary_packet(); + } + + // only called when we've already logged in + if (($this->bitmap & NET_SSH2_MASK_CONNECTED) && $this->isAuthenticated()) { + switch (ord($payload[0])) { + case NET_SSH2_MSG_CHANNEL_DATA: + case NET_SSH2_MSG_CHANNEL_EXTENDED_DATA: + case NET_SSH2_MSG_CHANNEL_REQUEST: + case NET_SSH2_MSG_CHANNEL_CLOSE: + case NET_SSH2_MSG_CHANNEL_EOF: + if (!$skip_channel_filter && !empty($this->server_channels)) { + $this->binary_packet_buffer = $payload; + $this->_get_channel_packet(true); + $payload = $this->_get_binary_packet(); + } + break; + case NET_SSH2_MSG_GLOBAL_REQUEST: // see http://tools.ietf.org/html/rfc4254#section-4 + if (strlen($payload) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($payload, 4))); + $this->errors[] = 'SSH_MSG_GLOBAL_REQUEST: ' . $this->_string_shift($payload, $length); + + if (!$this->_send_binary_packet(pack('C', NET_SSH2_MSG_REQUEST_FAILURE))) { + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + + $payload = $this->_get_binary_packet($skip_channel_filter); + break; + case NET_SSH2_MSG_CHANNEL_OPEN: // see http://tools.ietf.org/html/rfc4254#section-5.1 + $this->_string_shift($payload, 1); + if (strlen($payload) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($payload, 4))); + $data = $this->_string_shift($payload, $length); + if (strlen($payload) < 4) { + return false; + } + extract(unpack('Nserver_channel', $this->_string_shift($payload, 4))); + switch ($data) { + case 'auth-agent': + case 'auth-agent@openssh.com': + if (isset($this->agent)) { + $new_channel = NET_SSH2_CHANNEL_AGENT_FORWARD; + + if (strlen($payload) < 8) { + return false; + } + extract(unpack('Nremote_window_size', $this->_string_shift($payload, 4))); + extract(unpack('Nremote_maximum_packet_size', $this->_string_shift($payload, 4))); + + $this->packet_size_client_to_server[$new_channel] = $remote_window_size; + $this->window_size_server_to_client[$new_channel] = $remote_maximum_packet_size; + $this->window_size_client_to_server[$new_channel] = $this->window_size; + + $packet_size = 0x4000; + + $packet = pack( + 'CN4', + NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION, + $server_channel, + $new_channel, + $packet_size, + $packet_size + ); + + $this->server_channels[$new_channel] = $server_channel; + $this->channel_status[$new_channel] = NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION; + if (!$this->_send_binary_packet($packet)) { + return false; + } + } + break; + default: + $packet = pack( + 'CN3a*Na*', + NET_SSH2_MSG_REQUEST_FAILURE, + $server_channel, + NET_SSH2_OPEN_ADMINISTRATIVELY_PROHIBITED, + 0, + '', + 0, + '' + ); + + if (!$this->_send_binary_packet($packet)) { + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + } + $payload = $this->_get_binary_packet($skip_channel_filter); + break; + case NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST: + $this->_string_shift($payload, 1); + if (strlen($payload) < 8) { + return false; + } + extract(unpack('Nchannel', $this->_string_shift($payload, 4))); + extract(unpack('Nwindow_size', $this->_string_shift($payload, 4))); + $this->window_size_client_to_server[$channel]+= $window_size; + + $payload = ($this->bitmap & NET_SSH2_MASK_WINDOW_ADJUST) ? true : $this->_get_binary_packet($skip_channel_filter); + } + } + + return $payload; + } + + /** + * Enable Quiet Mode + * + * Suppress stderr from output + * + * @access public + */ + function enableQuietMode() + { + $this->quiet_mode = true; + } + + /** + * Disable Quiet Mode + * + * Show stderr in output + * + * @access public + */ + function disableQuietMode() + { + $this->quiet_mode = false; + } + + /** + * Returns whether Quiet Mode is enabled or not + * + * @see self::enableQuietMode() + * @see self::disableQuietMode() + * + * @access public + * @return bool + */ + function isQuietModeEnabled() + { + return $this->quiet_mode; + } + + /** + * Enable request-pty when using exec() + * + * @access public + */ + function enablePTY() + { + $this->request_pty = true; + } + + /** + * Disable request-pty when using exec() + * + * @access public + */ + function disablePTY() + { + if ($this->in_request_pty_exec) { + $this->_close_channel(NET_SSH2_CHANNEL_EXEC); + $this->in_request_pty_exec = false; + } + $this->request_pty = false; + } + + /** + * Returns whether request-pty is enabled or not + * + * @see self::enablePTY() + * @see self::disablePTY() + * + * @access public + * @return bool + */ + function isPTYEnabled() + { + return $this->request_pty; + } + + /** + * Gets channel data + * + * Returns the data as a string if it's available and false if not. + * + * @param $client_channel + * @return mixed + * @access private + */ + function _get_channel_packet($client_channel, $skip_extended = false) + { + if (!empty($this->channel_buffers[$client_channel])) { + return array_shift($this->channel_buffers[$client_channel]); + } + + while (true) { + if ($this->binary_packet_buffer !== false) { + $response = $this->binary_packet_buffer; + $this->binary_packet_buffer = false; + } else { + if ($this->curTimeout) { + if ($this->curTimeout < 0) { + $this->is_timeout = true; + return true; + } + + $read = array($this->fsock); + $write = $except = null; + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $sec = floor($this->curTimeout); + $usec = 1000000 * ($this->curTimeout - $sec); + // on windows this returns a "Warning: Invalid CRT parameters detected" error + if (!@stream_select($read, $write, $except, $sec, $usec) && !count($read)) { + $this->is_timeout = true; + return true; + } + $elapsed = strtok(microtime(), ' ') + strtok('') - $start; + $this->curTimeout-= $elapsed; + } + + $response = $this->_get_binary_packet(true); + if ($response === false) { + user_error('Connection closed by server'); + return false; + } + } + + if ($client_channel == -1 && $response === true) { + return true; + } + if (!strlen($response)) { + return ''; + } + + if (!strlen($response)) { + return false; + } + extract(unpack('Ctype', $this->_string_shift($response, 1))); + + if (strlen($response) < 4) { + return false; + } + if ($type == NET_SSH2_MSG_CHANNEL_OPEN) { + extract(unpack('Nlength', $this->_string_shift($response, 4))); + } else { + extract(unpack('Nchannel', $this->_string_shift($response, 4))); + } + + // will not be setup yet on incoming channel open request + if (isset($channel) && isset($this->channel_status[$channel]) && isset($this->window_size_server_to_client[$channel])) { + $this->window_size_server_to_client[$channel]-= strlen($response); + + // resize the window, if appropriate + if ($this->window_size_server_to_client[$channel] < 0) { + $packet = pack('CNN', NET_SSH2_MSG_CHANNEL_WINDOW_ADJUST, $this->server_channels[$channel], $this->window_size); + if (!$this->_send_binary_packet($packet)) { + return false; + } + $this->window_size_server_to_client[$channel]+= $this->window_size; + } + + if ($type == NET_SSH2_MSG_CHANNEL_EXTENDED_DATA) { + /* + if ($client_channel == NET_SSH2_CHANNEL_EXEC) { + $this->_send_channel_packet($client_channel, chr(0)); + } + */ + // currently, there's only one possible value for $data_type_code: NET_SSH2_EXTENDED_DATA_STDERR + if (strlen($response) < 8) { + return false; + } + extract(unpack('Ndata_type_code/Nlength', $this->_string_shift($response, 8))); + $data = $this->_string_shift($response, $length); + $this->stdErrorLog.= $data; + if ($skip_extended || $this->quiet_mode) { + continue; + } + if ($client_channel == $channel && $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_DATA) { + return $data; + } + if (!isset($this->channel_buffers[$channel])) { + $this->channel_buffers[$channel] = array(); + } + $this->channel_buffers[$channel][] = $data; + + continue; + } + + switch ($this->channel_status[$channel]) { + case NET_SSH2_MSG_CHANNEL_OPEN: + switch ($type) { + case NET_SSH2_MSG_CHANNEL_OPEN_CONFIRMATION: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nserver_channel', $this->_string_shift($response, 4))); + $this->server_channels[$channel] = $server_channel; + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nwindow_size', $this->_string_shift($response, 4))); + if ($window_size < 0) { + $window_size&= 0x7FFFFFFF; + $window_size+= 0x80000000; + } + $this->window_size_client_to_server[$channel] = $window_size; + if (strlen($response) < 4) { + return false; + } + $temp = unpack('Npacket_size_client_to_server', $this->_string_shift($response, 4)); + $this->packet_size_client_to_server[$channel] = $temp['packet_size_client_to_server']; + $result = $client_channel == $channel ? true : $this->_get_channel_packet($client_channel, $skip_extended); + $this->_on_channel_open(); + return $result; + //case NET_SSH2_MSG_CHANNEL_OPEN_FAILURE: + default: + user_error('Unable to open channel'); + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + break; + case NET_SSH2_MSG_CHANNEL_REQUEST: + switch ($type) { + case NET_SSH2_MSG_CHANNEL_SUCCESS: + return true; + case NET_SSH2_MSG_CHANNEL_FAILURE: + return false; + default: + user_error('Unable to fulfill channel request'); + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + case NET_SSH2_MSG_CHANNEL_CLOSE: + return $type == NET_SSH2_MSG_CHANNEL_CLOSE ? true : $this->_get_channel_packet($client_channel, $skip_extended); + } + } + + // ie. $this->channel_status[$channel] == NET_SSH2_MSG_CHANNEL_DATA + + switch ($type) { + case NET_SSH2_MSG_CHANNEL_DATA: + /* + if ($channel == NET_SSH2_CHANNEL_EXEC) { + // SCP requires null packets, such as this, be sent. further, in the case of the ssh.com SSH server + // this actually seems to make things twice as fast. more to the point, the message right after + // SSH_MSG_CHANNEL_DATA (usually SSH_MSG_IGNORE) won't block for as long as it would have otherwise. + // in OpenSSH it slows things down but only by a couple thousandths of a second. + $this->_send_channel_packet($channel, chr(0)); + } + */ + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $data = $this->_string_shift($response, $length); + + if ($channel == NET_SSH2_CHANNEL_AGENT_FORWARD) { + $agent_response = $this->agent->_forward_data($data); + if (!is_bool($agent_response)) { + $this->_send_channel_packet($channel, $agent_response); + } + break; + } + + if ($client_channel == $channel) { + return $data; + } + if (!isset($this->channel_buffers[$channel])) { + $this->channel_buffers[$channel] = array(); + } + $this->channel_buffers[$channel][] = $data; + break; + case NET_SSH2_MSG_CHANNEL_REQUEST: + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $value = $this->_string_shift($response, $length); + switch ($value) { + case 'exit-signal': + $this->_string_shift($response, 1); + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + $this->errors[] = 'SSH_MSG_CHANNEL_REQUEST (exit-signal): ' . $this->_string_shift($response, $length); + $this->_string_shift($response, 1); + if (strlen($response) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($response, 4))); + if ($length) { + $this->errors[count($this->errors)].= "\r\n" . $this->_string_shift($response, $length); + } + + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel])); + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel])); + + $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_EOF; + + break; + case 'exit-status': + if (strlen($response) < 5) { + return false; + } + extract(unpack('Cfalse/Nexit_status', $this->_string_shift($response, 5))); + $this->exit_status = $exit_status; + + // "The client MAY ignore these messages." + // -- http://tools.ietf.org/html/rfc4254#section-6.10 + + break; + default: + // "Some systems may not implement signals, in which case they SHOULD ignore this message." + // -- http://tools.ietf.org/html/rfc4254#section-6.9 + break; + } + break; + case NET_SSH2_MSG_CHANNEL_CLOSE: + $this->curTimeout = 0; + + if ($this->bitmap & NET_SSH2_MASK_SHELL) { + $this->bitmap&= ~NET_SSH2_MASK_SHELL; + } + if ($this->channel_status[$channel] != NET_SSH2_MSG_CHANNEL_EOF) { + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$channel])); + } + + $this->channel_status[$channel] = NET_SSH2_MSG_CHANNEL_CLOSE; + if ($client_channel == $channel) { + return true; + } + case NET_SSH2_MSG_CHANNEL_EOF: + break; + default: + user_error('Error reading channel data'); + return $this->_disconnect(NET_SSH2_DISCONNECT_BY_APPLICATION); + } + } + } + + /** + * Sends Binary Packets + * + * See '6. Binary Packet Protocol' of rfc4253 for more info. + * + * @param string $data + * @param string $logged + * @see self::_get_binary_packet() + * @return bool + * @access private + */ + function _send_binary_packet($data, $logged = null) + { + if (!is_resource($this->fsock) || feof($this->fsock)) { + user_error('Connection closed prematurely'); + $this->bitmap = 0; + return false; + } + + //if ($this->compress) { + // // the -4 removes the checksum: + // // http://php.net/function.gzcompress#57710 + // $data = substr(gzcompress($data), 0, -4); + //} + + // 4 (packet length) + 1 (padding length) + 4 (minimal padding amount) == 9 + $packet_length = strlen($data) + 9; + // round up to the nearest $this->encrypt_block_size + $packet_length+= (($this->encrypt_block_size - 1) * $packet_length) % $this->encrypt_block_size; + // subtracting strlen($data) is obvious - subtracting 5 is necessary because of packet_length and padding_length + $padding_length = $packet_length - strlen($data) - 5; + $padding = crypt_random_string($padding_length); + + // we subtract 4 from packet_length because the packet_length field isn't supposed to include itself + $packet = pack('NCa*', $packet_length - 4, $padding_length, $data . $padding); + + $hmac = $this->hmac_create !== false ? $this->hmac_create->hash(pack('Na*', $this->send_seq_no, $packet)) : ''; + $this->send_seq_no++; + + if ($this->encrypt !== false) { + $packet = $this->encrypt->encrypt($packet); + } + + $packet.= $hmac; + + $start = strtok(microtime(), ' ') + strtok(''); // http://php.net/microtime#61838 + $result = strlen($packet) == fputs($this->fsock, $packet); + $stop = strtok(microtime(), ' ') + strtok(''); + + if (defined('NET_SSH2_LOGGING')) { + $current = strtok(microtime(), ' ') + strtok(''); + $message_number = isset($this->message_numbers[ord($data[0])]) ? $this->message_numbers[ord($data[0])] : 'UNKNOWN (' . ord($data[0]) . ')'; + $message_number = '-> ' . $message_number . + ' (since last: ' . round($current - $this->last_packet, 4) . ', network: ' . round($stop - $start, 4) . 's)'; + $this->_append_log($message_number, isset($logged) ? $logged : $data); + $this->last_packet = $current; + } + + return $result; + } + + /** + * Logs data packets + * + * Makes sure that only the last 1MB worth of packets will be logged + * + * @param string $data + * @access private + */ + function _append_log($message_number, $message) + { + // remove the byte identifying the message type from all but the first two messages (ie. the identification strings) + if (strlen($message_number) > 2) { + $this->_string_shift($message); + } + + switch (NET_SSH2_LOGGING) { + // useful for benchmarks + case NET_SSH2_LOG_SIMPLE: + $this->message_number_log[] = $message_number; + break; + // the most useful log for SSH2 + case NET_SSH2_LOG_COMPLEX: + $this->message_number_log[] = $message_number; + $this->log_size+= strlen($message); + $this->message_log[] = $message; + while ($this->log_size > NET_SSH2_LOG_MAX_SIZE) { + $this->log_size-= strlen(array_shift($this->message_log)); + array_shift($this->message_number_log); + } + break; + // dump the output out realtime; packets may be interspersed with non packets, + // passwords won't be filtered out and select other packets may not be correctly + // identified + case NET_SSH2_LOG_REALTIME: + switch (PHP_SAPI) { + case 'cli': + $start = $stop = "\r\n"; + break; + default: + $start = '
';
+                        $stop = '
'; + } + echo $start . $this->_format_log(array($message), array($message_number)) . $stop; + @flush(); + @ob_flush(); + break; + // basically the same thing as NET_SSH2_LOG_REALTIME with the caveat that NET_SSH2_LOG_REALTIME_FILE + // needs to be defined and that the resultant log file will be capped out at NET_SSH2_LOG_MAX_SIZE. + // the earliest part of the log file is denoted by the first <<< START >>> and is not going to necessarily + // at the beginning of the file + case NET_SSH2_LOG_REALTIME_FILE: + if (!isset($this->realtime_log_file)) { + // PHP doesn't seem to like using constants in fopen() + $filename = NET_SSH2_LOG_REALTIME_FILENAME; + $fp = fopen($filename, 'w'); + $this->realtime_log_file = $fp; + } + if (!is_resource($this->realtime_log_file)) { + break; + } + $entry = $this->_format_log(array($message), array($message_number)); + if ($this->realtime_log_wrap) { + $temp = "<<< START >>>\r\n"; + $entry.= $temp; + fseek($this->realtime_log_file, ftell($this->realtime_log_file) - strlen($temp)); + } + $this->realtime_log_size+= strlen($entry); + if ($this->realtime_log_size > NET_SSH2_LOG_MAX_SIZE) { + fseek($this->realtime_log_file, 0); + $this->realtime_log_size = strlen($entry); + $this->realtime_log_wrap = true; + } + fputs($this->realtime_log_file, $entry); + } + } + + /** + * Sends channel data + * + * Spans multiple SSH_MSG_CHANNEL_DATAs if appropriate + * + * @param int $client_channel + * @param string $data + * @return bool + * @access private + */ + function _send_channel_packet($client_channel, $data) + { + while (strlen($data)) { + if (!$this->window_size_client_to_server[$client_channel]) { + $this->bitmap^= NET_SSH2_MASK_WINDOW_ADJUST; + // using an invalid channel will let the buffers be built up for the valid channels + $this->_get_channel_packet(-1); + $this->bitmap^= NET_SSH2_MASK_WINDOW_ADJUST; + } + + /* The maximum amount of data allowed is determined by the maximum + packet size for the channel, and the current window size, whichever + is smaller. + -- http://tools.ietf.org/html/rfc4254#section-5.2 */ + $max_size = min( + $this->packet_size_client_to_server[$client_channel], + $this->window_size_client_to_server[$client_channel] + ); + + $temp = $this->_string_shift($data, $max_size); + $packet = pack( + 'CN2a*', + NET_SSH2_MSG_CHANNEL_DATA, + $this->server_channels[$client_channel], + strlen($temp), + $temp + ); + $this->window_size_client_to_server[$client_channel]-= strlen($temp); + if (!$this->_send_binary_packet($packet)) { + return false; + } + } + + return true; + } + + /** + * Closes and flushes a channel + * + * Net_SSH2 doesn't properly close most channels. For exec() channels are normally closed by the server + * and for SFTP channels are presumably closed when the client disconnects. This functions is intended + * for SCP more than anything. + * + * @param int $client_channel + * @param bool $want_reply + * @return bool + * @access private + */ + function _close_channel($client_channel, $want_reply = false) + { + // see http://tools.ietf.org/html/rfc4254#section-5.3 + + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_EOF, $this->server_channels[$client_channel])); + + if (!$want_reply) { + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel])); + } + + $this->channel_status[$client_channel] = NET_SSH2_MSG_CHANNEL_CLOSE; + + $this->curTimeout = 0; + + while (!is_bool($this->_get_channel_packet($client_channel))) { + } + + if ($want_reply) { + $this->_send_binary_packet(pack('CN', NET_SSH2_MSG_CHANNEL_CLOSE, $this->server_channels[$client_channel])); + } + + if ($this->bitmap & NET_SSH2_MASK_SHELL) { + $this->bitmap&= ~NET_SSH2_MASK_SHELL; + } + } + + /** + * Disconnect + * + * @param int $reason + * @return bool + * @access private + */ + function _disconnect($reason) + { + if ($this->bitmap & NET_SSH2_MASK_CONNECTED) { + $data = pack('CNNa*Na*', NET_SSH2_MSG_DISCONNECT, $reason, 0, '', 0, ''); + $this->_send_binary_packet($data); + $this->bitmap = 0; + fclose($this->fsock); + return false; + } + } + + /** + * String Shift + * + * Inspired by array_shift + * + * @param string $string + * @param int $index + * @return string + * @access private + */ + function _string_shift(&$string, $index = 1) + { + $substr = substr($string, 0, $index); + $string = substr($string, $index); + return $substr; + } + + /** + * Define Array + * + * Takes any number of arrays whose indices are integers and whose values are strings and defines a bunch of + * named constants from it, using the value as the name of the constant and the index as the value of the constant. + * If any of the constants that would be defined already exists, none of the constants will be defined. + * + * @param array $array + * @access private + */ + function _define_array() + { + $args = func_get_args(); + foreach ($args as $arg) { + foreach ($arg as $key => $value) { + if (!defined($value)) { + define($value, $key); + } else { + break 2; + } + } + } + } + + /** + * Returns a log of the packets that have been sent and received. + * + * Returns a string if NET_SSH2_LOGGING == NET_SSH2_LOG_COMPLEX, an array if NET_SSH2_LOGGING == NET_SSH2_LOG_SIMPLE and false if !defined('NET_SSH2_LOGGING') + * + * @access public + * @return array|false|string + */ + function getLog() + { + if (!defined('NET_SSH2_LOGGING')) { + return false; + } + + switch (NET_SSH2_LOGGING) { + case NET_SSH2_LOG_SIMPLE: + return $this->message_number_log; + case NET_SSH2_LOG_COMPLEX: + $log = $this->_format_log($this->message_log, $this->message_number_log); + return PHP_SAPI == 'cli' ? $log : '
' . $log . '
'; + default: + return false; + } + } + + /** + * Formats a log for printing + * + * @param array $message_log + * @param array $message_number_log + * @access private + * @return string + */ + function _format_log($message_log, $message_number_log) + { + $output = ''; + for ($i = 0; $i < count($message_log); $i++) { + $output.= $message_number_log[$i] . "\r\n"; + $current_log = $message_log[$i]; + $j = 0; + do { + if (strlen($current_log)) { + $output.= str_pad(dechex($j), 7, '0', STR_PAD_LEFT) . '0 '; + } + $fragment = $this->_string_shift($current_log, $this->log_short_width); + $hex = substr(preg_replace_callback('#.#s', array($this, '_format_log_helper'), $fragment), strlen($this->log_boundary)); + // replace non ASCII printable characters with dots + // http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters + // also replace < with a . since < messes up the output on web browsers + $raw = preg_replace('#[^\x20-\x7E]|<#', '.', $fragment); + $output.= str_pad($hex, $this->log_long_width - $this->log_short_width, ' ') . $raw . "\r\n"; + $j++; + } while (strlen($current_log)); + $output.= "\r\n"; + } + + return $output; + } + + /** + * Helper function for _format_log + * + * For use with preg_replace_callback() + * + * @param array $matches + * @access private + * @return string + */ + function _format_log_helper($matches) + { + return $this->log_boundary . str_pad(dechex(ord($matches[0])), 2, '0', STR_PAD_LEFT); + } + + /** + * Helper function for agent->_on_channel_open() + * + * Used when channels are created to inform agent + * of said channel opening. Must be called after + * channel open confirmation received + * + * @access private + */ + function _on_channel_open() + { + if (isset($this->agent)) { + $this->agent->_on_channel_open($this); + } + } + + /** + * Returns the first value of the intersection of two arrays or false if + * the intersection is empty. The order is defined by the first parameter. + * + * @param array $array1 + * @param array $array2 + * @return mixed False if intersection is empty, else intersected value. + * @access private + */ + function _array_intersect_first($array1, $array2) + { + foreach ($array1 as $value) { + if (in_array($value, $array2)) { + return $value; + } + } + return false; + } + + /** + * Returns all errors + * + * @return string[] + * @access public + */ + function getErrors() + { + return $this->errors; + } + + /** + * Returns the last error + * + * @return string + * @access public + */ + function getLastError() + { + $count = count($this->errors); + + if ($count > 0) { + return $this->errors[$count - 1]; + } + } + + /** + * Return the server identification. + * + * @return string + * @access public + */ + function getServerIdentification() + { + $this->_connect(); + + return $this->server_identifier; + } + + /** + * Return a list of the key exchange algorithms the server supports. + * + * @return array + * @access public + */ + function getKexAlgorithms() + { + $this->_connect(); + + return $this->kex_algorithms; + } + + /** + * Return a list of the host key (public key) algorithms the server supports. + * + * @return array + * @access public + */ + function getServerHostKeyAlgorithms() + { + $this->_connect(); + + return $this->server_host_key_algorithms; + } + + /** + * Return a list of the (symmetric key) encryption algorithms the server supports, when receiving stuff from the client. + * + * @return array + * @access public + */ + function getEncryptionAlgorithmsClient2Server() + { + $this->_connect(); + + return $this->encryption_algorithms_client_to_server; + } + + /** + * Return a list of the (symmetric key) encryption algorithms the server supports, when sending stuff to the client. + * + * @return array + * @access public + */ + function getEncryptionAlgorithmsServer2Client() + { + $this->_connect(); + + return $this->encryption_algorithms_server_to_client; + } + + /** + * Return a list of the MAC algorithms the server supports, when receiving stuff from the client. + * + * @return array + * @access public + */ + function getMACAlgorithmsClient2Server() + { + $this->_connect(); + + return $this->mac_algorithms_client_to_server; + } + + /** + * Return a list of the MAC algorithms the server supports, when sending stuff to the client. + * + * @return array + * @access public + */ + function getMACAlgorithmsServer2Client() + { + $this->_connect(); + + return $this->mac_algorithms_server_to_client; + } + + /** + * Return a list of the compression algorithms the server supports, when receiving stuff from the client. + * + * @return array + * @access public + */ + function getCompressionAlgorithmsClient2Server() + { + $this->_connect(); + + return $this->compression_algorithms_client_to_server; + } + + /** + * Return a list of the compression algorithms the server supports, when sending stuff to the client. + * + * @return array + * @access public + */ + function getCompressionAlgorithmsServer2Client() + { + $this->_connect(); + + return $this->compression_algorithms_server_to_client; + } + + /** + * Return a list of the languages the server supports, when sending stuff to the client. + * + * @return array + * @access public + */ + function getLanguagesServer2Client() + { + $this->_connect(); + + return $this->languages_server_to_client; + } + + /** + * Return a list of the languages the server supports, when receiving stuff from the client. + * + * @return array + * @access public + */ + function getLanguagesClient2Server() + { + $this->_connect(); + + return $this->languages_client_to_server; + } + + /** + * Returns the banner message. + * + * Quoting from the RFC, "in some jurisdictions, sending a warning message before + * authentication may be relevant for getting legal protection." + * + * @return string + * @access public + */ + function getBannerMessage() + { + return $this->banner_message; + } + + /** + * Returns the server public host key. + * + * Caching this the first time you connect to a server and checking the result on subsequent connections + * is recommended. Returns false if the server signature is not signed correctly with the public host key. + * + * @return mixed + * @access public + */ + function getServerPublicHostKey() + { + if (!($this->bitmap & NET_SSH2_MASK_CONSTRUCTOR)) { + if (!$this->_connect()) { + return false; + } + } + + $signature = $this->signature; + $server_public_host_key = $this->server_public_host_key; + + if (strlen($server_public_host_key) < 4) { + return false; + } + extract(unpack('Nlength', $this->_string_shift($server_public_host_key, 4))); + $this->_string_shift($server_public_host_key, $length); + + if ($this->signature_validated) { + return $this->bitmap ? + $this->signature_format . ' ' . base64_encode($this->server_public_host_key) : + false; + } + + $this->signature_validated = true; + + switch ($this->signature_format) { + case 'ssh-dss': + $zero = new Math_BigInteger(); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $p = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $q = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $g = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $y = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); + + /* The value for 'dss_signature_blob' is encoded as a string containing + r, followed by s (which are 160-bit integers, without lengths or + padding, unsigned, and in network byte order). */ + $temp = unpack('Nlength', $this->_string_shift($signature, 4)); + if ($temp['length'] != 40) { + user_error('Invalid signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $r = new Math_BigInteger($this->_string_shift($signature, 20), 256); + $s = new Math_BigInteger($this->_string_shift($signature, 20), 256); + + switch (true) { + case $r->equals($zero): + case $r->compare($q) >= 0: + case $s->equals($zero): + case $s->compare($q) >= 0: + user_error('Invalid signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $w = $s->modInverse($q); + + $u1 = $w->multiply(new Math_BigInteger(sha1($this->exchange_hash), 16)); + list(, $u1) = $u1->divide($q); + + $u2 = $w->multiply($r); + list(, $u2) = $u2->divide($q); + + $g = $g->modPow($u1, $p); + $y = $y->modPow($u2, $p); + + $v = $g->multiply($y); + list(, $v) = $v->divide($p); + list(, $v) = $v->divide($q); + + if (!$v->equals($r)) { + user_error('Bad server signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + } + + break; + case 'ssh-rsa': + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $e = new Math_BigInteger($this->_string_shift($server_public_host_key, $temp['length']), -256); + + if (strlen($server_public_host_key) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($server_public_host_key, 4)); + $rawN = $this->_string_shift($server_public_host_key, $temp['length']); + $n = new Math_BigInteger($rawN, -256); + $nLength = strlen(ltrim($rawN, "\0")); + + /* + if (strlen($signature) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($signature, 4)); + $signature = $this->_string_shift($signature, $temp['length']); + + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + + $rsa = new Crypt_RSA(); + $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1); + $rsa->loadKey(array('e' => $e, 'n' => $n), CRYPT_RSA_PUBLIC_FORMAT_RAW); + if (!$rsa->verify($this->exchange_hash, $signature)) { + user_error('Bad server signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + } + */ + + if (strlen($signature) < 4) { + return false; + } + $temp = unpack('Nlength', $this->_string_shift($signature, 4)); + $s = new Math_BigInteger($this->_string_shift($signature, $temp['length']), 256); + + // validate an RSA signature per "8.2 RSASSA-PKCS1-v1_5", "5.2.2 RSAVP1", and "9.1 EMSA-PSS" in the + // following URL: + // ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1.pdf + + // also, see SSHRSA.c (rsa2_verifysig) in PuTTy's source. + + if ($s->compare(new Math_BigInteger()) < 0 || $s->compare($n->subtract(new Math_BigInteger(1))) > 0) { + user_error('Invalid signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_KEY_EXCHANGE_FAILED); + } + + $s = $s->modPow($e, $n); + $s = $s->toBytes(); + + $h = pack('N4H*', 0x00302130, 0x0906052B, 0x0E03021A, 0x05000414, sha1($this->exchange_hash)); + $h = chr(0x01) . str_repeat(chr(0xFF), $nLength - 2 - strlen($h)) . $h; + + if ($s != $h) { + user_error('Bad server signature'); + return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + } + break; + default: + user_error('Unsupported signature format'); + return $this->_disconnect(NET_SSH2_DISCONNECT_HOST_KEY_NOT_VERIFIABLE); + } + + return $this->signature_format . ' ' . base64_encode($this->server_public_host_key); + } + + /** + * Returns the exit status of an SSH command or false. + * + * @return false|int + * @access public + */ + function getExitStatus() + { + if (is_null($this->exit_status)) { + return false; + } + return $this->exit_status; + } + + /** + * Returns the number of columns for the terminal window size. + * + * @return int + * @access public + */ + function getWindowColumns() + { + return $this->windowColumns; + } + + /** + * Returns the number of rows for the terminal window size. + * + * @return int + * @access public + */ + function getWindowRows() + { + return $this->windowRows; + } + + /** + * Sets the number of columns for the terminal window size. + * + * @param int $value + * @access public + */ + function setWindowColumns($value) + { + $this->windowColumns = $value; + } + + /** + * Sets the number of rows for the terminal window size. + * + * @param int $value + * @access public + */ + function setWindowRows($value) + { + $this->windowRows = $value; + } + + /** + * Sets the number of columns and rows for the terminal window size. + * + * @param int $columns + * @param int $rows + * @access public + */ + function setWindowSize($columns = 80, $rows = 24) + { + $this->windowColumns = $columns; + $this->windowRows = $rows; + } +} diff --git a/ipaylinks_statement/System/SSH/Agent.php b/ipaylinks_statement/System/SSH/Agent.php new file mode 100644 index 00000000..7388cb47 --- /dev/null +++ b/ipaylinks_statement/System/SSH/Agent.php @@ -0,0 +1,486 @@ + + * login('username', $agent)) { + * exit('Login Failed'); + * } + * + * echo $ssh->exec('pwd'); + * echo $ssh->exec('ls -la'); + * ?> + * + * + * LICENSE: 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. + * + * @category System + * @package System_SSH_Agent + * @author Jim Wigginton + * @copyright 2014 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + * @internal See http://api.libssh.org/rfc/PROTOCOL.agent + */ + +/**#@+ + * Message numbers + * + * @access private + */ +// to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1) +define('SYSTEM_SSH_AGENTC_REQUEST_IDENTITIES', 11); +// this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2). +define('SYSTEM_SSH_AGENT_IDENTITIES_ANSWER', 12); +define('SYSTEM_SSH_AGENT_FAILURE', 5); +// the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3) +define('SYSTEM_SSH_AGENTC_SIGN_REQUEST', 13); +// the SSH1 response is SSH_AGENT_RSA_RESPONSE (4) +define('SYSTEM_SSH_AGENT_SIGN_RESPONSE', 14); + + +/**@+ + * Agent forwarding status + * + * @access private + */ +// no forwarding requested and not active +define('SYSTEM_SSH_AGENT_FORWARD_NONE', 0); +// request agent forwarding when opportune +define('SYSTEM_SSH_AGENT_FORWARD_REQUEST', 1); +// forwarding has been request and is active +define('SYSTEM_SSH_AGENT_FORWARD_ACTIVE', 2); + +/**#@-*/ + +/** + * Pure-PHP ssh-agent client identity object + * + * Instantiation should only be performed by System_SSH_Agent class. + * This could be thought of as implementing an interface that Crypt_RSA + * implements. ie. maybe a Net_SSH_Auth_PublicKey interface or something. + * The methods in this interface would be getPublicKey, setSignatureMode + * and sign since those are the methods phpseclib looks for to perform + * public key authentication. + * + * @package System_SSH_Agent + * @author Jim Wigginton + * @access internal + */ +class System_SSH_Agent_Identity +{ + /** + * Key Object + * + * @var Crypt_RSA + * @access private + * @see self::getPublicKey() + */ + var $key; + + /** + * Key Blob + * + * @var string + * @access private + * @see self::sign() + */ + var $key_blob; + + /** + * Socket Resource + * + * @var resource + * @access private + * @see self::sign() + */ + var $fsock; + + /** + * Default Constructor. + * + * @param resource $fsock + * @return System_SSH_Agent_Identity + * @access private + */ + function __construct($fsock) + { + $this->fsock = $fsock; + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @param resource $fsock + * @access public + */ + function System_SSH_Agent_Identity($fsock) + { + $this->__construct($fsock); + } + + /** + * Set Public Key + * + * Called by System_SSH_Agent::requestIdentities() + * + * @param Crypt_RSA $key + * @access private + */ + function setPublicKey($key) + { + $this->key = $key; + $this->key->setPublicKey(); + } + + /** + * Set Public Key + * + * Called by System_SSH_Agent::requestIdentities(). The key blob could be extracted from $this->key + * but this saves a small amount of computation. + * + * @param string $key_blob + * @access private + */ + function setPublicKeyBlob($key_blob) + { + $this->key_blob = $key_blob; + } + + /** + * Get Public Key + * + * Wrapper for $this->key->getPublicKey() + * + * @param int $format optional + * @return mixed + * @access public + */ + function getPublicKey($format = null) + { + return !isset($format) ? $this->key->getPublicKey() : $this->key->getPublicKey($format); + } + + /** + * Set Signature Mode + * + * Doesn't do anything as ssh-agent doesn't let you pick and choose the signature mode. ie. + * ssh-agent's only supported mode is CRYPT_RSA_SIGNATURE_PKCS1 + * + * @param int $mode + * @access public + */ + function setSignatureMode($mode) + { + } + + /** + * Create a signature + * + * See "2.6.2 Protocol 2 private key signature request" + * + * @param string $message + * @return string + * @access public + */ + function sign($message) + { + // the last parameter (currently 0) is for flags and ssh-agent only defines one flag (for ssh-dss): SSH_AGENT_OLD_SIGNATURE + $packet = pack('CNa*Na*N', SYSTEM_SSH_AGENTC_SIGN_REQUEST, strlen($this->key_blob), $this->key_blob, strlen($message), $message, 0); + $packet = pack('Na*', strlen($packet), $packet); + if (strlen($packet) != fputs($this->fsock, $packet)) { + user_error('Connection closed during signing'); + } + + $length = current(unpack('N', fread($this->fsock, 4))); + $type = ord(fread($this->fsock, 1)); + if ($type != SYSTEM_SSH_AGENT_SIGN_RESPONSE) { + user_error('Unable to retreive signature'); + } + + $signature_blob = fread($this->fsock, $length - 1); + // the only other signature format defined - ssh-dss - is the same length as ssh-rsa + // the + 12 is for the other various SSH added length fields + return substr($signature_blob, strlen('ssh-rsa') + 12); + } +} + +/** + * Pure-PHP ssh-agent client identity factory + * + * requestIdentities() method pumps out System_SSH_Agent_Identity objects + * + * @package System_SSH_Agent + * @author Jim Wigginton + * @access internal + */ +class System_SSH_Agent +{ + /** + * Socket Resource + * + * @var resource + * @access private + */ + var $fsock; + + /** + * Agent forwarding status + * + * @access private + */ + var $forward_status = SYSTEM_SSH_AGENT_FORWARD_NONE; + + /** + * Buffer for accumulating forwarded authentication + * agent data arriving on SSH data channel destined + * for agent unix socket + * + * @access private + */ + var $socket_buffer = ''; + + /** + * Tracking the number of bytes we are expecting + * to arrive for the agent socket on the SSH data + * channel + */ + var $expected_bytes = 0; + + /** + * Default Constructor + * + * @return System_SSH_Agent + * @access public + */ + function __construct() + { + switch (true) { + case isset($_SERVER['SSH_AUTH_SOCK']): + $address = $_SERVER['SSH_AUTH_SOCK']; + break; + case isset($_ENV['SSH_AUTH_SOCK']): + $address = $_ENV['SSH_AUTH_SOCK']; + break; + default: + user_error('SSH_AUTH_SOCK not found'); + return false; + } + + $this->fsock = fsockopen('unix://' . $address, 0, $errno, $errstr); + if (!$this->fsock) { + user_error("Unable to connect to ssh-agent (Error $errno: $errstr)"); + } + } + + /** + * PHP4 compatible Default Constructor. + * + * @see self::__construct() + * @access public + */ + function System_SSH_Agent() + { + $this->__construct(); + } + + /** + * Request Identities + * + * See "2.5.2 Requesting a list of protocol 2 keys" + * Returns an array containing zero or more System_SSH_Agent_Identity objects + * + * @return array + * @access public + */ + function requestIdentities() + { + if (!$this->fsock) { + return array(); + } + + $packet = pack('NC', 1, SYSTEM_SSH_AGENTC_REQUEST_IDENTITIES); + if (strlen($packet) != fputs($this->fsock, $packet)) { + user_error('Connection closed while requesting identities'); + } + + $length = current(unpack('N', fread($this->fsock, 4))); + $type = ord(fread($this->fsock, 1)); + if ($type != SYSTEM_SSH_AGENT_IDENTITIES_ANSWER) { + user_error('Unable to request identities'); + } + + $identities = array(); + $keyCount = current(unpack('N', fread($this->fsock, 4))); + for ($i = 0; $i < $keyCount; $i++) { + $length = current(unpack('N', fread($this->fsock, 4))); + $key_blob = fread($this->fsock, $length); + $key_str = 'ssh-rsa ' . base64_encode($key_blob); + $length = current(unpack('N', fread($this->fsock, 4))); + if ($length) { + $key_str.= ' ' . fread($this->fsock, $length); + } + $length = current(unpack('N', substr($key_blob, 0, 4))); + $key_type = substr($key_blob, 4, $length); + switch ($key_type) { + case 'ssh-rsa': + if (!class_exists('Crypt_RSA')) { + include_once 'Crypt/RSA.php'; + } + $key = new Crypt_RSA(); + $key->loadKey($key_str); + break; + case 'ssh-dss': + // not currently supported + break; + } + // resources are passed by reference by default + if (isset($key)) { + $identity = new System_SSH_Agent_Identity($this->fsock); + $identity->setPublicKey($key); + $identity->setPublicKeyBlob($key_blob); + $identities[] = $identity; + unset($key); + } + } + + return $identities; + } + + /** + * Signal that agent forwarding should + * be requested when a channel is opened + * + * @param Net_SSH2 $ssh + * @return bool + * @access public + */ + function startSSHForwarding($ssh) + { + if ($this->forward_status == SYSTEM_SSH_AGENT_FORWARD_NONE) { + $this->forward_status = SYSTEM_SSH_AGENT_FORWARD_REQUEST; + } + } + + /** + * Request agent forwarding of remote server + * + * @param Net_SSH2 $ssh + * @return bool + * @access private + */ + function _request_forwarding($ssh) + { + $request_channel = $ssh->_get_open_channel(); + if ($request_channel === false) { + return false; + } + + $packet = pack( + 'CNNa*C', + NET_SSH2_MSG_CHANNEL_REQUEST, + $ssh->server_channels[$request_channel], + strlen('auth-agent-req@openssh.com'), + 'auth-agent-req@openssh.com', + 1 + ); + + $ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_REQUEST; + + if (!$ssh->_send_binary_packet($packet)) { + return false; + } + + $response = $ssh->_get_channel_packet($request_channel); + if ($response === false) { + return false; + } + + $ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_OPEN; + $this->forward_status = SYSTEM_SSH_AGENT_FORWARD_ACTIVE; + + return true; + } + + /** + * On successful channel open + * + * This method is called upon successful channel + * open to give the SSH Agent an opportunity + * to take further action. i.e. request agent forwarding + * + * @param Net_SSH2 $ssh + * @access private + */ + function _on_channel_open($ssh) + { + if ($this->forward_status == SYSTEM_SSH_AGENT_FORWARD_REQUEST) { + $this->_request_forwarding($ssh); + } + } + + /** + * Forward data to SSH Agent and return data reply + * + * @param string $data + * @return data from SSH Agent + * @access private + */ + function _forward_data($data) + { + if ($this->expected_bytes > 0) { + $this->socket_buffer.= $data; + $this->expected_bytes -= strlen($data); + } else { + $agent_data_bytes = current(unpack('N', $data)); + $current_data_bytes = strlen($data); + $this->socket_buffer = $data; + if ($current_data_bytes != $agent_data_bytes + 4) { + $this->expected_bytes = ($agent_data_bytes + 4) - $current_data_bytes; + return false; + } + } + + if (strlen($this->socket_buffer) != fwrite($this->fsock, $this->socket_buffer)) { + user_error('Connection closed attempting to forward data to SSH agent'); + } + + $this->socket_buffer = ''; + $this->expected_bytes = 0; + + $agent_reply_bytes = current(unpack('N', fread($this->fsock, 4))); + + $agent_reply_data = fread($this->fsock, $agent_reply_bytes); + $agent_reply_data = current(unpack('a*', $agent_reply_data)); + + return pack('Na*', $agent_reply_bytes, $agent_reply_data); + } +} diff --git a/ipaylinks_statement/System/SSH_Agent.php b/ipaylinks_statement/System/SSH_Agent.php new file mode 100644 index 00000000..ea434b9c --- /dev/null +++ b/ipaylinks_statement/System/SSH_Agent.php @@ -0,0 +1,39 @@ + + * @copyright 2014 Jim Wigginton + * @license http://www.opensource.org/licenses/mit-license.html MIT License + * @link http://phpseclib.sourceforge.net + * @internal See http://api.libssh.org/rfc/PROTOCOL.agent + */ + +require_once 'SSH/Agent.php'; diff --git a/ipaylinks_statement/bootstrap.php b/ipaylinks_statement/bootstrap.php new file mode 100644 index 00000000..0da0999f --- /dev/null +++ b/ipaylinks_statement/bootstrap.php @@ -0,0 +1,16 @@ +login('10000004000', 'YRATF0OtDaYa2Uhv6cWO8BV9FPBup5')) { + exit('Login Failed'); +} +// 获取前一天的对账单 +// target remote +$target_folder = str_replace("-", "/", date("/Y-m", strtotime("-1 day")) ); +$file_list = array_values(array_diff($sftp->nlist($target_folder), array(".",".."))); +// target local +$target_local = "statement_files" . $target_folder; +if ( ! is_dir($target_local)) { + mkdir($target_local, 0777); +} +// local files +$local_files = array_values(array_diff(scandir($target_local), array('.', '..'))); +// new files +$new_files = array_values(array_diff($file_list, $local_files)); +// copies filename.remote to filename.local from the SFTP server +$new_cnt = 0; +foreach ($new_files as $key => $new) { + $file_path = $target_folder . "/" . $new; + $sftp->get($file_path, $target_local . "/" . $new); + $new_cnt++; +} +echo "Copied new statements count: " . $new_cnt; diff --git a/ipaylinks_statement/openssl.cnf b/ipaylinks_statement/openssl.cnf new file mode 100644 index 00000000..2b8b52f9 --- /dev/null +++ b/ipaylinks_statement/openssl.cnf @@ -0,0 +1,6 @@ +# minimalist openssl.cnf file for use with phpseclib + +HOME = . +RANDFILE = $ENV::HOME/.rnd + +[ v3_ca ] diff --git a/ipaylinks_statement/statement_files/2018/01/20180127.xlsx b/ipaylinks_statement/statement_files/2018/01/20180127.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e1ede5b18295d2fc53a52bd87e44b3d583ed7a69 GIT binary patch literal 12239 zcma)i2V9fO@-`(xK#&kniXaKScMuf_Awfc~!VzhQCJ2H8f=Gu*M?#Y#U8+)~hynsC zi1c2iN>h68?R$fIkN4br&-Y(`A>n0bXXcq_XJ@mksX`2*B>;oL1cVrARf69dHSpQO z!CceP;hvL_xr3vn;KRFi1(9kh^}>*Vm80|U9hWFU49{IUtqY(}XY^yLA3NKHwvj58 zE!18fHsT9WjELTGV+l}tEt?zp?)ip)m&6RibI@z?rL?L<*=0!^sp6HyO_C=U3ZU%%lDzG6<7CLE*(B2>I}hmKihPub?g zXsB7iW_(2ItO1!+hCH+MYFORni=8|txBpbXus#v^I5C^&nVuNk<;hhK*8^dp)N@}* z(>c01;h9&5RpvB7c1q4MU+c`&YNK-c`nK#*&yv_Qfg1&8A7!?U=yAmeX|tO4si zI_rroVw8~A37bBzY!YoTCJZGnu~HvGl5dDEEgFQ>+19J9_U^P#Feg0!{2rmY_mtZr znZ$x4j=`8)O#`iClm=~|w>#D$rE4(lDm3Fg3TB?w;8L+NX=ZQ^^Trq%2|n;TGZFc^ zFaLw)$MM)P8WwedBtw*bH6b1weQsm6DZumVME`^h4bbBj%E8{*(%#ub*X^FAlhG-^ zqFVrrAPPHs$ zcb=d`Vo_zA`o?<0`=)CY>9utx9){BHwNiWJs}_3Ju7;11sk`^WG)87*y!Ept>#7_= z^zp!ROn}>^077zu{t0-<@6-Cvd-w3Dt3CNZ{!ti$Uhz_BtR9_5qPt`Kz$uGJ1T1q{ zveQn!L>V!j)H~HG9FbGmRx}yTQzch0G7wISkqmn>t0&7cFwcIiS_ef=O>?a^gNgf% zH#m#D(s>Nv6)K8jxnjWad56#TVQT=9K)rUNMK zr|R36`))ZHk9#gmH+(vKo6~YCc4@_KX=y3-?W2XIQBUb;al534?mPQJ<6~E3ZiTcv zB>AL`R!3hP*xqsQc6D-EnSY)9On*Dz)*Dxs;*E`4uJ*=5pHIfzY@JrNlau)zmW_so zhHBl+b&^${T`n>l9~~U~QdLv^y4G{|duUw*V)V<%_}CXazS6!E&yBsWQ;18)3(H>- zsmzDlFQp_BIe+|-}d#hM&6V<0$ugU z!&f#7)vUMI4Q6~s?Xfu)ogZ=IX=-MpwI5N* zAnuCHabv}TzW3U~9BS;bMKOoZ?1Z$arRe%QR9aLFZsG;I*ez_fRhz&{TP#+6n>O&8 zq;IacX8<>f^G!82*8B`V?bs!LHqjjq@mnlgt%^?cR7ul>JbQMU8cIIRF`%*x|BC`x z5bVhnxuqBncjtM3TLK+o`uR1*_LGV5Ikpe*XU4+s)oWdvzC}OB zQ6?^a66~NpA7G!-vTXcHQB;?gc?v4R9lhN(9VmUFDL0>BCL{P=1u7)CxU*`-4Bizo z-J_`phbz*e&4r>vKUI1Ryy1mtPo5_?wjT?xw%}<(V?`Ay!I}I;8nszgq#W4iU(`}M@z?jEkbX5f!gs+K-_F{clULQ*ysb)ls)Zi6M&If+=H(K6yC z-HZll5vxjAY+0h!xU~DDeQc*AUwU1QOgmk8g6PaRm{&7USi7(H6G?kQU3>C}@S5Re z{?+^-SEVwil(X`tZiUaK>FC7dosc#6lgCKMG}-$pH@n5J#FdCMe|)I!{JlH0vbjh6 zi&OWM^|$5N2gdS6#{Oa3#)Xn0yjPspmz?cPu`auLqF%gZzWu7ttts_w(=_j2StH4^ z8kL*vr9IyZ?GZ&od8k|1@@c8ZOwV+v-0DWpgNulL82JUPl3vcj!&ece@>bL);crYH zP35QML<=v8hMke0Ri~<9`t(#i(|&fl;LQr1hL4lZJPA<^zWFfHUlCx+ z6fGw*VM`~Y6*qlKAL>BjoE(Yi#+cD4&hI9MURTd3$a$KM^?Kl%wU@}3@P<+8uDoKP z2J%z-1$V`iEWPk>&`wWv%a>z53msnL>b273WFDI9UIN&5+gY3Ek>oEsd&&q)xE|Dx zLL0gE2}FwTZI5K}NFGwg3B|9f1?POJzaBAG+E4uf5mT&tk@?GKM)w;^v6%+r3HJyJ zIQXFnsW#z3vDApOX`B^zF6St*-c>8gQ_Iie*nn-Cn)}mDH-I!VWHg_2>IkomjbJVM zeA~8h(4o~kWG&Cnv}XOWlG>wVB9xk_8dBPNa6o5rS@NFvn;AG1L7q#9YHV=h?D2i( zX)IHcB4N@wGCk~AE6w^*-?308n>AL=TqURR1Ke*-hcdtQaev^DZ!e>8Oi5Ddr{m{N z+)m+U=QZRnE{q7oaJFDr3KMxsjs1ujNZ-;@zO{+|KAb6pvoTl>%m1ipmxvmJ)4%T` zVSs;s#p59v*xq@$tN1Zp%1arJvB=r^eu9Wtqlb+5@{&7R?^|A&%oJb&@t&<|3Q>FUc`cVRWO@XDHy-PcaS z?N%~s1yc3M4G_-NRhC|;9eRk+w0GQ z^;ylfi*4I&1V7xRrIewb@Tb0u+iYlW6z}Y;v5y`Rq3Nxt{ zY%B&6(a6#oH95B_`?g-N5*4!%=W=$Ir_&F?9Wk=Z8!NKv8Mt2)N8GLp7#dzYTc26d z;o*Eg3-c~cmuN3WTE~K`m*#4jVI24@okrz+0{XMPTCPLHHR%uuZCeh7JLMe>rJD7I z_9IkuAy*|?bxS;(N}zL-+LY^;rAf%%nM+af7h<<%lKWzL$8{Ctsb^n&XI?87HZjVR zSJs%QkePCuZF19GFGv+A%g!tkH(=9`tDO(+sS4^o7 zvXuSV=2nCES%m^ZzRb9!C9Y-gG^r*447cwv$8=H(8~TE`$5=6Esqbx;JGT!~JZJx? z4&My0Q?Be7s+sAb=_uheGR#B9!P8b;d=SGqh@_;>)cCGX5(?q8KEBQ#Bu6Y;30eq> z^sLr9->x_%#B^cOE_{8da-+tG^IdWDK~hd%_%XD+v{JiopL*qybXz1#h2Z#ILt0AS zgtga4N!T-Covc#E3=ifrf=v_nCI^}to2C4_B)N#(z9$E1*M7_;H!|dLY)fGOLO80b zrJ8gp`ekOQZO9kq59tpD72t zTlE4XF6f%*$26p0)XyF{9udxWhlNAS#{C;vraNQ7=(%v2U8u;SA*{ef*_*3Xf8d6a zjsj*-^?ZTr(zSCZv7`I*vtwh&+b5?Ry&l+cxCyYwrI7fi0-f?_f$r>PXL(wgXGQhe0JVKnL<43wY59D_iog1tg&jHb>~m<)m}o-2eR*HhaPv1TO|}-ebp?KOFEq#kaWY> zXuzt*HSG>dbbeER%gh6-*y}fE-@dtc@m;QUL^@6-A=VA`P`6){%yN1B(=*YLn|9%K zyrR?C21b(Hvu-pJx)-#2t3@Au+pO2odnVGfz^$6xeqWERg4-%jdEcvL@5_6^iVsU) zLBawl$S?65I<6h!tC`)o*`e+6Jj-$44Jrmma~h(bUS?rR{C{V59gK(QhVc3TNrjit4o+dPxV) zp`tbMX)n2TnF!}h7!$pdCyF>q_gIIn%J!_E?y{apg-?V4o5nB1{}e>3A3=0=aI`gZ zaInR1u)?1d<9F%-t|=cYlfMvRVIe(PFM7k%UsY{q6*CS;c9gvXu@${<{`isj#-zwS z?Z={`$zG$b<41jmpB~snMB1%FLlOuAj7iOp^gd2Ka&sfy*w46%eLIYOWzMj}p01WB zbcJg)Lr46q%>FwYd1u}k`Zr1YLCu<>@rIv^uy1G7Z&Gog7*3|ZYUUDxeqJu$dz7HX zIy`Y%{o9}|htj~tFy%i+LNAhq&x3sj`d+z}JWLalLT5XdxEsC<2Z`J}q>^$;;oN9W z$4-47*!gy_wng~|e?cTff0l7DDBqF)dXsZgj>#4kelMEyMKNs-z`*n$zwcrEfzpq! ze16C3$JalRr@WV2ISOfXO>~L=`Snl98ll#_WZxI|63XG@6dzDN6nyU5&GM;lahXF& zvr5&hYxMrUmHBdi-YdRXXFB0_^3aL&SvhwiS5p48*y87UUaB*a6AInc{fpA=Pg~-J zr`1_(%A<4`olBNYNqb+usO)oY@+sH6<9lPco#1X2WAAa&Dq?qV=XqV=cVjDx^|}jf zV^EiC=^pTQQx)P6UxkWR-Ok$m{K9#*Z)8FWvg-(n{sD2R>sMbX#yA8QbsxCTXnOC9 zKU!P4yGDY?X0`o~fL_3J;eY(ThyE`HIaym;Iy(VdcHm9qluF6BoGvycpvQOgg?DRE zM58btN~I?cdb(pe9}m9TS#OPm1&c&UAsw$D@2NByU%hM>bC7)u|zc)xW!nF_4& zsQJU#*x1OUqT=Y$@%*QQVWGgH@r%+`2#<$u$19;5q548zJ|~{;yW96Rzm={m9Xq=2 zEbP?A>G~)j@?g-dJo|>Y0f9cH6}M_;{+ecC^O(aC0+fMq^>g(f#$! zqV|rlqvO?wJ2T$LYbS@+JBx93byEw&pP$7DL*HST#* z*JIjospjNpaqjb_l;Z(}u~E(2-Km3!-e7IP@AH%I~ryl%9-A*HzxiwyO9vswq=L|ag0Tt%iKxocuFXPpj4L>38!`AiP z+ZNd;6hW$61VOD^5-`yrZ$h-y0q|kef$3(m^NDnkww!|Av;eGx^_pD$+|*$jUv4Ag z65-9YZr2W#@iw7qHkF$Lgpiv9w$_-qOAw<+))?GnpYPorFKOlKnH>nbvPjW!US6Gj zk?PmWNG(37j3b0R5w)97oJH#iAqk?4zDjK>|nblnK$Y^JDU;%1!(z zRF(23)8k{8a1ugC^KNtc8!9UpuH=gZk=|?roj5@mSmoxE&5}X~rsAwreIB3hq_RK8 zI|2;dRM>eW$GN@#@>^DIqRAu0M@SO6>G8(DG@cNQNtvl2inIwLmunseIL`srrm{Fc zt^t>jTC}LtdKvF;9d=(UiK<}wH-&@U*M5j~Wd;5w^}U-|w0QH`x2*A202aQ{1;VcC zON`xk0D!mZG3s0UZm~o`%UeGU-|#Q&qyu^-3@*IsP^nD@Ow_9!AkJ`?`Qbw~n||fM zFHOHj0-!v<4|IXixF1cfyDg<2OI7W@H=J|P2wUFieOibRxkGSA1+n8Rau#&;G5yi^ zobui?^|_RO#rpFRUWYVdYkRd)&6^i|X_9U(ENg_>pY%SxLP+oAC$Bncz7m5)TY2*hTv7q$hYIUTvAO8d=x=nF`41)PY4XF=8~XNgRI$P|$Mc!u4> z>*+sJuS!b->^bo4q$(jNLb1 zLkR0UkPjuILtX&4Hq3)e^VPwVa%Qb$ollp}AzA6a)0)}2g5{CG6C^+8sCbkxK5sOg z!#@Y zgc<5&qrisLlOWlHlMk&C_$^}PAgrA7XVUo|fRMJY(KrrH8cphwaKE&?1KepV!nM16^E0GL(DY*V+_2N(yG0Qb{`(qDT)5O#nM zyg3UMl3OXP0uJWLLu}6xwDty~&T_=zpC#*{FvNHKTF)Z+gRA?ojIhfnz_1drW~8W6 z*bp4US&U-TW)pv)Tx}WM0(*vTXeRZ`_W*Y*(N=0JLdx`jmzD~|BCwyZ8)fJ~Rzgn% z+X0c;Q1}`dW!Cf1w#K=b>-xC4g?hQuLpF~lkV}mu3jW2>GI`OfY z7-Vy4YzF&f&j(%574%PwqL(=*3CoOlO>GeX_EWaY*Fk}hmaMvv`926zQz?vr70g?V z;*$U&^#LWw8Bs8xgcwOIe^CMr(S@1^q%|y7yn*Ec@!$UPA_#9R1vMyk5dIPlPRxZ@ zUeI;H50m1`2gK z2A`+x&WHlA$LW#O6%E1#c&QV4d2bmEow4B%R*^X;0kcrB#Oa;FmY+*;P6t2D_;~%N zV(R1Jep4}nz#n9I3GJaXN*uy1Dtx?z-8wf0PC3t8ECO`R6s6_`-_&AYkHw2*La$i> zHs~l=s_<69@<3KLmsd`8{0I%8BdQsl`>!Y9DCI@m`Pkm{yo?f#SRwTvW?m}#D;^+u1d+cERg;>zglA5n35)-QIw@97? z%LAgXr5LJ=ya8~}vcT0%>A+X#ph9s}a5zl5Okz0{zg z$KIfVUMOfT7>wOSgDBh8)gq(Z{IHw7v@S{=XqfnY&J0B5fk?$6wWE;Ci6|_Sv?xzP zOu_LCyF@l=5n0KPdHUniv|!`3C}tja>D_hf$%zN!-OaKXKHr=33cSSfk5*5;vjM#8 zmD&_d3?<;kp(kI_tfqwgZT19s)Pdodg3$b)Gj{hm5I`OeL6RH z-vi6}WNHVXwtpEkK5LZGA9v|&z)$c@V1oZ-s=*K` zp4(N@B={!=FWCIvLLZCQUeDDBlH6LaN9(SnsSBZ4_v(>*!@Eu|D~p_gus3fV&({OI zSb{QO%U+-{%t)h>g9atw9cOgq68OAdFNCo4Y`h4)C#CbY81c0&lnS3d(txa0yQ3CZ zsb)4n2`qRutyD-ufUJJ4R2!{=rVXZ>5}iXG6pOu70{Mn+nKNGZvU^Y{V);sQ0+5%F zU;+!K@sI$w2Z!(i^0Ns>@54TPw@oWeWf;t3shkajy#!^Kx@SYWg^~$;S^Ugnxh=fF zPi}C^KZb48N&mY&p*;FXRWj8aiFO~H*Czt-A!IrR-`x?IZ4e8u_}hTXB+rX{+r6wz zbG)P;IjF5qGCmXtPvK#Llstk)iS3})j~St&2=<~^WLR?KY@nMJov^v^KI8Yr+axaY zffuw3{czBD^_BM*@dAE;08TptFdoB0lP-_j`!i+eOe=j@4awDm1mEQSbjz5Ru;+mN z*T|@W?v6lr$Z2=*fA6jUbk6`~_pp5?meiz?HKB0vm4?gxt^TE(h-82q~i z_%3lL3$ts;< z^fzoyjqg#JB*o^ZsIDu`NA1CzxX1ve0l)(!PyH=aTd1FrQcoRW{{I_OPqpw=qtG88 zS>r&UYKkVPV98aPC#BU!Kr+2B02TgAU>8oY)MtfdZn4Wv0Q%8zJcOsS>OY~h{SnxG z)05NjeOb~}W=Vl*Lhy@ff14(Sc#`llfF(PdIZG%nisi12WZeU^q}>YG&YoLWdh*n>?_b|6ubc^@Y0-klH9ou|3($ zRSY1pC3P2vR;6-!UDiddPqziam|k`EOs!Df~E>LvOwba%4sW)8$cHgAZfITN&UH9|>F~ivUo-bE+WbrvmL?3dBH2nt;Kwct@Ig{P1-^ zhHKCUmWo`JJ78LE6oEwm5NWbJIMI)UrJP*e;txsO{Ze6bWrnkn2k>DXhIMX%0p$=r zCkCA6L>z!`BhM*Q?-y>-_@xCqBtLtqV=vwAh>+@;vs4DEeGY%v4zY97p`83IY2XNz zFM!m)^6saKejx_1nn%;1a~n_vlBwPn8f0xWex(3F3+BZ`3j)gAQ)qR6K^sSbxk8=zcHgVVuUQSEOVl&BWI!yR zXh<`SuZ(E{Nb!X+=2X{dc9$9e{wcoI@LKIG@8wgY91KyIXj?o%G*1bFFN^U6N&86< zgJ@eUXVk*4{yCRRfSjR~0E+G95JN+CiKYWEe#-dZA%6w$d@M-qe5^q32nfj`oNUY_ zNzl6xt22=Kzirafg^J(ME&t*5<~F%3P|KMDEp18 zDAZ!b0tChf0UvNbU=hRz9L)PO;162ltj$^m%QGDp+@4bx$5um;R!dL%uodtp+K%AZ@@Eq8sMJby;sy;H8Yb+0A&&w19>hVk{5X30mC_o41 zmkx-h`M2ICVSo*$lcbepD% zsCv(GZi{bJJHA`yG50#DbITD@dzmWdJ&Ug{l4s|$beT$;NCLLGw6Ms2+A?MLddb_x zCx_J2iJ-0hiLdWty!haNCW~iyP2FujG=ZglY1*O5=B!EM7d&9|28nPXt7QYFgtJVv zgIK*mT3jj>2)|ciQM}xEBiliY(Mq|}3;Pewe<+rwMQQFHO>0h^M1Fp)R=O>SjCleoBV zg9VhgqjE(Et+p(*09cg34Oj%bDm-(b0u42LGs2=ItW3Mh7JOZ+`G^|(oJ^cETGOrH z)0^;)Ohv67;59lEv}HSP610BAp`=uNYdM0Qi-Y_yl06IWLP_^87x?tEIlaDBz8$%= z$A(cQn_o(h&)(cAL`Ne0dSkLiSdjLNO6Ox7y+K_zMBz>Bx+xEiDEW10-1g1x$D|5I z9nz+aT@pbzr--nVA0kIZz0+d$h`DzZS#M}IA5zOzovImha(Bk&<#j}S((RPupZ9+It^0vy4U}qIPN1j9FxubeO=q1U7PI- z9k-XgG~aggdANw`cI}9a?3kyUo7Y~?PL&B_WK`zTa_z~IO~<}7a5Qij*AYk+fymt` zJs6HiJznXEaIHPsxGj|OW!J^^WFf-E_(%wURNX1;h1_4mpSBSa(GvW1_xkrc z#rV6||K9%NCidUOf4_E%zj*vtlLrp1e!GVJcfsGUjpA?R{?&|u6P^EZNB8do{C-gr zf4lUrHUJzd{>$*6cTN8;{rf30{xauZEgQJU`rod0{(Xesk1+A4&3`pTz#RMt|2ljA zyXf!ddiXQWzZwPfRP^^#yuSGZznVG#2rv%b ai2pb=(^NS_g6~NN{2+ipJrcnG_5T38BwTL* literal 0 HcmV?d00001 diff --git a/ipaylinks_statement/statement_files/2018/01/20180128.xlsx b/ipaylinks_statement/statement_files/2018/01/20180128.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..63ce48dbc6cb30378e284fe488858d856a853c32 GIT binary patch literal 10029 zcma)i1zglk*EX@h(hEp~EXYbIsUU)Mcc*kH0!o7*xuAqJlF}d{ASEp+(kZcYNOwsK zy#Gb-SKs@2?)&?OADeS#&biKY&YYPY6?t^fH54!yjDjj7sDScEBLZHV+nT93*xEUA znAtj5us?rlQy8fz-@*xbwS7)Xf8-Ly-mW*!o^cx-jH`9cmY#OPbYGNs^K`q%1rhvh zV1B`KI>1Ej*`XEV_R0@qCrP(fW>Gdpft3##ggv|lgNn(F@9q+~_Ubs9h$x%Np9LS% zkD@hpU60w(4RKa53{huj8E`g!=|M^>);mhcjF&+w+Sn93E-4*eFE;M2UE!cQe(zo{ zTnjBMR|Sjk!Te4Src>voZhZ91$upDm>?fVs!`)v(`5sJ7Pxf`?_#KK`27OclvnU^m z@n1uINK7kvT&y!tv|#V-Hf-}G`A)qOrSks%t6g{re6bJqV=XnQZJ_FuA?2NPX>F}g zT9>0*b6-(@w6cmk78re0j{_YQ1?4;Nukw!w;sOX7Iat^@aJXT&}>1q`QC~t**g|3l@FC?1 z-+hXoBwEWDQI_WW^ECx0YjSUH=mmeaZjs*^I_jOJO~`C(6jnHiWj0U7G>64e8Zs*? zOQ;*95%;dyT&QD_w;B(8Fl9XtqFqvEl7D2>N$C{gEn{H7?(Bsz8(BVF(4^8l6EjUh zr^J?|FRopOio`~n+3?0ZV7V09zhOfH^mr(4`^?GWnUj%*o1KND!4v zT@SC-TKGcbzG8&KG%`GVN|-`58_a9poxixrvIx@)Ug<1dntt(2%AQB}p|}<#`tU=x z8E*zC>API5n_}uC*F{+JT}jm*UQ}Yy5_z6Y2LkORrZHdApc51VrowP7^G~h!3B}l3 zXpT=TotoacQtGoiri#9WN33D$mE293{9s>dASwO&}!Hmu=q{P7y)vd7}kJ(Uwo zlNFk~d4u%H={|d&5nffPyC$BEF%pG73Xk1(y8x%T4- z$BW<;9cj*-hwEr0pll`Z|IaaY4fyuC4TqzpiGzi?x|73`XOA6`CcV@%c&*=YqV!jDK;be z@tC`8-8*uvy6gpqdXBA#SZ>Xkmb3Fgp89av*|=@^^z>;@)A`t3$L_nQ+%7NHXODY3 z-UhVU8jRQ5pNF#BHdGw>O^w;qJ1;LZ?dmV71W!C93?uYDpPiNC*yFXe?Fa~a99Oa3 zyL{wTRd%P=@o0ACusdl|fG;-ED0x!2MlkMj+S~fE%l1Xn=Do+Rgak{{w%f(!_RA}W zbGwJrTN`$^uJx53hhO&Qm0ewzUepR`ewDvG+g$Ei_SU~xpW932AaA&IcYMD4ePC~@ zsIUIiW_N*w!cgdP_WN+=AbAm)w-=qa+iuV2!3Lowvl-!wm9st})tMhl$%92HY(@`+ z&S$x_^?WZ* z;#zs@&lWc52*1$mstPL?UVNWeY%}5w7*pH2?VNN^x}DoXK56V_H!nnz$AafsX03De zI!;;J^!OXYlQG2u82f;Zb<8K6n2$GjVOAwPUr1q7*CcGY`&-_GlnuF{>$b%@4#>Z_ zSEV);QK$W^YImRRX>d}xWka%`nl-a!Icm?M!cD&p@`+-a#iCo-wtnq1HJ|QZOJn7_ zWvOTrMTRM+&JmJ9{9YAK(VuI+$=dRX##fE}&PTR*{qKmR-9`(c*UoE0nCqox)l3p{ zC+?HGOFnHm){4E2CdThyXJ=stSP)0s(9;&J8|&Y{t)ew?x*KZUIld8z-{GG$lwzP@ zGkR;rWi0W{@Bztkf=s7q@53>AzHO5L-VOps6?w$GjdN1#SGyNOm0Dt=(pkph8Q7I= zDxn!tNsqenY6KV4p2gW3&>O!z*2WbShfpNkWG@*Bc-3&*+8cYiTm}4G)CI++$6*fj zCV`7vhMEIvWQl_=>axyGGMNVg(I!v9Vv@ePPGV3XWseTBFcg#yb{E^*`QX&?yvXb} z<%naZO`oH{V4!ol9zvn&+I!~`pDg?`%N{y@1HE`m*nOpxY<~q7S?|pxT%SRj!X*vu zTB#76v_j+QN6xF!pXurEKMat-P+o8e8hWtkB08*Q9)Q1&)*iwrjYk=5&ws(t-JOL0 z^?tlXzOE=!LbV+^8Z8E}8PSsa^GAZb$+Cf#AB?VE}F zinV%WyccauinUeoOT}Yl7#5;4PY@g1a9N0*V(Mi!n!p27nWPLNmBeDDZ)N5v+{+`9 zn|GBc3P3Ov7rtne`#95Jgyn>!Ap?EvXxcLZeF>X4=1+XmAR=tt$~U4-d9bUzEQrY^ zgR5ffbTV;82`KRuVKnQo3I@B@m~#Yz=HA!Bb(}+POs71}DoZsODuE>p`5ejSsgjJd zGkJ7pKO*;0^H+n5FT?!9QoV2z8jt`T47EQe_UoT z!7-Fa88Nx}E+mDQnu zJGJIDJ6xuf+s&(+ldSh)C9Dgh4q7N~w?CHNT6YhPJcZsjnm=e~j-AC(^L(as($S;Y zj`c8!fSsL;nk*Sw|AF!455KBqot9|zk;TqrboF(pV57%gRe;D!EKEn8&sHQPq}!p~ zG)|bU3-PM8JgX2krOY_6;PxL)* zxTAu$)o!#RoL|1_uc4xU z6i1e{MD!ILl?)Ef@2%nO@uIx3Cpzm+$n}(RXiW=Uc=!FSLn5briNZ62R^iyQSP0vb z1x}W>?>A|?O*O>{Zx&Blp^ z={NZXQ5yI8c}o)^)THhbq&0ppcNw=*De`s3ajUV>Dln>fC?@|y|6WLvxTQ%MG`3i+ zP5-rZsFkxmMKwmH<8G>OlIPKnZ=vGRvKz7@N@;eSVfk%1>niJ^jy2Kx`J|g5W}3Xb zxI!ITQfr=?SHwIhc4>AhH%=Zlvcn0~i=-a&bu{OG7jG6-^dx50U9k}l)kddf3{&A# zQ_qhc*L|9&N;FLR29ai$m92IHnhqba;tWhFQgmi}PPc-HI`o%jA;4*~YMEm>i)8{k zJr@|gZr~kl-HvM^cik@W;w{<2UYMZAvF}$=Qrt*3)%U6e!FRZYGbsFYv7@EtDDZ^3nyq{d$Q}AFG zRzZibU8MD@e^yS`JN#VLkF$mj(Na_a>F>jjuv3}O%q`(BDQx4pwQZbFf`i4=G>lMY zVWqO_mp8;}a;1u78LCB1#nYbOdGcX@=XSAE*89E1PEV@$++xMXs!k@WX`Qdn)Ra!~ zpA@pL?%aHRXInz(L-6QphJHoE&}HyG*Zh_+`)v-5`_{0tlUQ&sU_zVmy3YKuekWA@SFCl!_T??8%qD%<2soMVJ9vkGLlG%r+PpH;-# zp(@tHi_hdwpANVUJ>F;t9B-t3uzN{@8N2B52`f3yF!GrMVj%=hAuk>5p$Vdzu$E;0 z$Rc9+>fQ2tn_W%PCt;toFoH{8mw$7TBha8)FOTq2JuP9SjMl(8BFWANP7%c*qR7H*>@FQQ67#B~UzJfg?+tIB~I2P()b&t(e09 zRZKa#*;rgvQSYLEZCM^jz7bgGW%O5hNFXDgL`jS&aGnTk`4ELy{y=jJ`qS;TdkjY=cXx(RK~2~zxMMH-XC5UK z@fUY;{dH9$P7cTKaRi!SIG=~{Gt6eFd(R8>h${VCTnJUv1_A;wMoxyA@L zw#C-Wm$%%Lx;CMoS-BVdTd6Q}aotFGG|1G3>bTvPzqhDsz2)jyXI4n=wb!~)&HN}& z?$oR6WW15Rx@mI`#L1Q-Iv&5TUaYcIhl5JN?@y=m? z;N6xs{$Aylc{+t>mb@f4??-ye$#0Ns45t>GS_+*ATNHWqk-gvUsY)MhzdO#oY?LO6 zOCcex)UdCWbmsJ$yFNZGpIL(jb=8O}(K~sz2v&B&Fvc%5xOY_%hw+8Z1_K5DIQqXi zk?^MzU2Pq#O>J$hk;QOmSP61h^~yD+xh8oW)gKx>`0o8sXnJw&;ky#5iO9Z>pFlT? z8atbt(KWwu*{Qwc=1%sSa-BIJ{_(}xCOpz+hd4L^<&`0p*|}Epyt|tl*8XV*zkk() zf3X?m5o5Yy9>;yAsSNeIxPqsjo`^ZIE>ct`od$NQypGpzEAp>eRMI765~sYJ2P>NK zu*1DvRt9B>OVnB7-i;iB4s6Q;+C$`YCSOxyhpvHr5yQo9rO(su@JVDlmA=r=4+U}A z{UGFXNx8Y-neIQ|hB#V2+daV7xm_3u(O#k&4J>fDE!E-Fkz;f~h@^VXxOCbofPwM9 z?#-!wqV#in{wG#Hx9X8sycgL%4{mo&bcz18RWIE|RbAs99%n4YpSVcz0TmE~2?TU2 z=9lBL#*&s~>lk(^{CsN)L`>{Ts6QLex?MhZ#Clu7oXC_^uyALit%a2kgLhW)Yu(7k zgWlM#c+LeSx+fJ;>QqjpTgF&J`R{9nojQCfRIGe8Cwfty)=~{!B<%!otZB*j@ooTvt>|Hc+SONO-w@ zeha+inwEcx&dYdzqxtKbnkc*HuAA0URQ3i{ZR@X}*VooI)Sn-oKHnW&-5uDP2$%>*%m_6IT{K*Jo*6xE^Y+*e&=!8S z?NxUPoP&fD{HQ!bv>6?qZC`piI9$$kZ7r=`2S9)+~8z=YM^Z@Cx51X>(b?H zetGI(nd3}6HeWn3fY7t*-2L*nFZ1oX_}HJ04T+UWbkDF_~&_qF4 zxX=%mhK9P6wuZ|-vs&qfjjbcwqNBc=-R+2Q+N!E?qdGTd*R%PRt^Ni2O+rFpnkc~< z@8k28oszT9-sk5%tNGD0bV8?e-};np8xs4GOv!(14!VHtk~76}1XU^(7!q$M=`=8U zxtQ)pQ6%%dkp1NP?FX#nB~i3!GD@T>n@@YOA(~p-!2%~jnPgf}@%hnl!q&-S^Q=p} zK)eH#z>otBDEFv0s)W=T8@@<0YhC+zm% zoO`Q(B5^3Y8x5V*Su8a8WHhR zZ9=nQp35?7^Xat!+e*_@e*1^ z!^d{OZojX5zV>8IdtZIKU9HstMM7#04H(w7CHp#6l(3I01lhF{9H=n6@I3jVEh;OF7e#<Kz-_HBHT%K?fK|6E3*SfP@(Na@N%Vy~^jF#rM22b|hm8)28#%2lN3-{nKUpD; z2+Q%ZKfQYtK=+u5E;0&n4tkg5S(`FX_k3c8}$;qKmdmD&#+ePWw9b?RHdvf=j~QEk7+T7& zi<)ENK)2iT7?ydW#?osXq6;#0oJYNn>NfX9;655$cr*(F$lh=Akb} z^_#>!kiI2hN(K9tq38R$5f`+ipD$thQ6Z~B0o#`j98yH!dxHWnt7Mp-6C+PJ+rN=4 z>tb{bMZwxRw|ADI7}NKDB|qx7B)xRVs9#I`wOp=2F=L{ezEb`Q`2C565MNb_ETdxa zn^VK?p?yuZo!#C#cng*ixch?p32;*7XD^+9gE5oCjUx zwbp=&VvFP~199ez1tC~>45Aa%SOv}H%BO}#U^9U4GMLBsiL(bbYT$k47^S~O3$_|2 z7}nDVO*3%uhog&W34$?E8tZRSLGVcGjLJ| z4J4DJi}D|mgA&Nlx`?RD_UP?sqeX6rX$gTwZXC2PK;pxJ@#(-;ZwL)|ptX%YjM-&9 zlAy7}j7B(PD=&qrnVt~J!ix|%AfqRwVqG!7Y)9|+9oI#s3k!ZKb<(d%SBmQ)W2$kE z4tx(Whl7)3Y!u>fae!B7q2N_GYJ>rOuJp~o#*h|*)nH#0vyPRNO+lyiP7KtLtqw}a z*F9e-iT@pTuvIrNy%>~40%F<1^_3$Z#X(dgTmiDbO1=@{W%g2KULgNN5ge>9YyMsS zmjCyMx8Mp8Uyh*ARfN{Hb`TMWis&oH2S5lkVjkhuM6h~K8_ZK*v-bY}7{(GKx1I)Z z7PU1ym|GNd$jF;53Bv$h0iOJr3u?z8;(H@{iXo6C2@@;KD0P2hFsn+OIT3*AUyzHZ zAZM%(8Hy*3@s&*g<|xhJ9_^M91cWCjOT@J_(1yk*hcu&0aTVlDZTv{Yv@|ep!Z?w} z1a~%ODF6uQs#3{=*tEr*&tN+A*=|5_HixoXO${m1DL2e_0GzL^2 z+-are;wvi~vgt3@jvN-$iXmzb=%(Mv*dGXV@l}>ZY9s`6X%Ciz>q%NTv(`4|0p61! zG8f3;jKX2CV=dtV#?9fz2ACyjF{_~lKL|d8>l_sS+rkzttm;_j0bWIFE%Din3 z-V-$%PZo2nJ*)-e7fgL$FqABi&^}R>Rk3!}FiP$evSSS@*;EAsp8%{yPQu2@@{_*+ zm?8i_^RD>I#!6&$EymNC^~GM92BdM6odp1%u^luQf(xfAyHf_aav)a(ZIW|42CDBb zuam`qd4fCZi{LT@%F&BCfOqsX)U0m?E`WJjc5g{I1oI=~L_2VS+1VkM|Gt7EZRstL zXyGjhXV$aEJP^QRHLxx|5g%X$2=y(mBB8G;B@pghJRn}!K^qV-Z-(ed&^g)IG@?rh z0YCFk8Sp~Q^CgYd)S!d#JC9^d0yJ> z0A2vHMTVa;6~>?oMkJLl7+u=6@Zfs#QU^?Djj5pQ!6^$MO$hz`TE*;YaM`p-sJEOt zpeU470(hjU9b?S3FRL!NSm54a@?CXu9rFQnRkJ?q&TdR?Y5h)(2j8ex6ip+dKgUFe zdOrt50eeC+XN;jk$Czfi=N%Ta%4mbDTcy6xDFYYLLLkF=6H^anL|w(Pgv@I>AAN|g zFeNfi>S-_xF|)=Er|Q?dUWD8I)bPrqU@#JhD@I(!aRxDz90cMP?asLpBmM}Gr>huF78ZQap&IDfokm!*4M+;W*2o5d)VpApp+caeiv-_I4QSqRbILgN- z!;s-TeM}`7XY#X2YDg&+8kAhZSd)1EKlVtF>8=Lpp*r%B@l32eKzQia7sDab$}So%+=S- zaUex@uZeaP0h|S-R0>&;Xb3hO`l9za1dzDSBlMR@E)-&goxvZIe-&GW<>1vQ(SIC& zB?_78b%5~~y<%~j6O<|s2|&r~NC|kNx+uy#9OWwJ0q=F+nea(~Z{UWN8_?6ZyXbo7 z1=O$6bFu=yCO`0r5K2ygBE)Aki09qGNmrn*n*0J4012NI#51j0@?L6@6)DksAV>;c zeai|4{2&G60uoRzkb^;h`!czWv!Q2jvqIZ^(cFXj#K#;3veP=~FEE_9PkbWk%5QQZ znZzgs6TKPOg3L`s6fswhrm^;PBo!-!Wl{l_=Yp~kPY=+=PBCx!hyVqEYzQs`Co2%W zfK+2HUOY>C{j5%rCIs}93ZDB*C+AxSKK<1=4F5C%mGxAgN07?Ag>=4^#s{=a;&{V* zv_MUunm`c)Xil7o3?@?`E5pGdoxhO!wJiMVex&~Y?ha&9XC79BuPU}e(G3CUReA=) zH6ShVP;hDGHyB_zYoO0hvf34t=St+NYJA97ttJSOGj^YPDRdl|rV?OD z)3_q{pZ#3~x-jMxijrv{Ux6@&fJAPBfdv#L0SXil07!0+s5#XmJkv`mVCd;1Q3Kkd zARrp*uFF$EN?|wbuY90%<%2w=5BUD_!9#Aa6&ocGJXpx?b<))I54nkRkjQ*PA|sQ8 zX0kdgngRWH0zpJ8Z+ zex%Q^D*2N=^#cyU9Bycq5J&_XxbS7-KSeOw^gO}-dK|_@N{jq<0PoIW8=x`kQIdbw z2v}#eRCWK-s4O1~C@vJPwEl0ykN>rfBap#ggcXOZMgF}zmE>YJf6QBCa3b#L0>zjH z+5#LZgK-tjq!K{*%U}?3{tUIya+g!$bSc&9Jf+2(Nc|5?maZf~K=~$T3gkR>px8lX z)}Igo_P&<$|2YHoQJFrZ_q#Q)rvICVn@UD9uBKSchoa>GoTftseiR0Z0)Rt6X#&(- zzc@7ee>wCFNT}FALUs47IroVmi$U=P#G@$4C1y2%%KNvI0S0kYLaaz*hVv$WQs^s? zQ2&`i8y~MVeU$BADow}=!8aJ`{u!bJ zMmn+3viirvc@J=r7zw_+2h9p-Ky?s>WWk}WAkhdM24I!Sf`fl8YLuiPF*Z?+oW0vu zUgr9NE>>fX^3Pt5!}F(-Z`E~X?VId#5ak=xJ)5hDI zJpACXs7Su6-1R#i{xVuIQ7n#cBy^j*_r1Cs+5d+?SUDRdXIZjWoV~-PMdgH%{$|ni zr&F&3H|-BwLPp-T!l#SKa}hUBkJCZFhJ)2ZmxkIG$D7bnj@tZi>zJ8 z{onQ<_niJN{^z9@qbkm~-~pEB^nr_St8jtsspA#z%laAP9&O{4xlC95}%L2G;rtcGfm;nf0yh z44IrQEy|*0r8`)l?{=>UC{7$>2n`r4@4qAje?eA_YYMQp2>pgCS+m*vY+CDahf$`xzZ^PqFpykvHKxXEuv-%l zw2zDYzw4FiALymwQbd#^JzgqVgW7d6!QMd2AfSl45hfnjgZQEAhU)mxq0gUe32Sg| zL;`r6=ZONXxw4e5zqh45S!%_`;FMM3B4EG&?B|}l(*+B2=DjJ@Y?>ijiaefa>2(FL zg`|DlLc5-9b4=mS4cCv^vi+xwhP+QFBKBjdVwNw^J&(Tk51VMdCHg)@H97Z#WN`U; z@%-vI=T|xfX;etBLL4CyA_Br8@KN}$5ySu@sAFen@s^nh{<|!uRj!={^WCmT2>r?E zY!p;T)=5yJLDqy9CNaZhh9@43y1b2s3Kqt6oPV%-vMOIaz5Ua8KaAl8x>Wh57&_*= zQVhSC$iR!y@EJ#yQU3YTPX-5TdW8851~lR;&KObOg0xptDBm3nD;=ctvSUGOlMlTs zO;gMzbcm`;{JC30(pA{Dx70)0%{!#`Mo#+YA0_8@wFt3}~^(v0!nR44|Lvfbin9Z`fu2E%w-5PwNRrlqQX9{O1Z`MdS ziiauEv%L>IqCEe~+<)WI5-(EbEhE}@(v}nTn7ME;uw$_89_p3C*vGO2ZzAbXLKF`= z#}6&`q+c}PDuKuCJ< z{|Y?x&$NDHV*`)6Y(y)18w*rq*Hg5+X?8Ay1XozZ$}4`d@eS%1O-jP(ICwAma!BYu+P#S|_O`fxNIPy= zP%T5@(oR!A)W-2VG*MTFG3#f{=u0GZU^51cjpLV}ym4y1|bZz8g4w zYwj*~+ugy`C`8?Fso#}3S>HJ4RvCSJT&$zxwcS_YXtk}?P~~RT8)>!K*S|CRkXdKi zV|ivw`hMo4jWMOwW+z8$>zlsOhZVa!i^=K-W69%A6;}sG>BeKipH9ozlT4g;XU0k{ zE}k_vH#IpOjizs^9(O)`=H$5F%WO4M?`cSO(|FW#JoioGg{t>!(JK ztDf4~vR}q0<>>+qUe|kb#(`v>?v8FZmy?!{)FQ8UOXRV4Zx;4+tVypI7h0`J)349w zcedM|$oS4KWBpz@ef=JIBEaqHez6wXh3e&+`Q3eQIaS>2Q@hv2O8O6vUth(I`k8<5 zpI^=`+}|bf*t>TV-u!X$tJ^La-}Q8C;0@P{Pj64wTFJ2aJvP@qegwMPy*io?Z9v_f zW8ZDMnv4zf+Ob&NjLf*al5Oz`8~dL8QQ&%GuN`$Z)9;sqjVEOLka-SSCms8#garjR zMP#WL^Vz|$rd*-8j_ZD4VW2uu`dcHTM;y6+4>jK8@=p#9BiWW77rzVWDCeJcZ5b1m zDkS@K_zUAa2%G7w_rCm%dWn7mvHL@s)P)C=?W3!#b;uSJBlD@;@{#%V#M@PQG4z!j zgpbn{CQU-D@L%w@FXP#`Br=p!VL5H#!=9dq`uXD@N&Ek_iPVCa`BmNxEMOcinmxIdtWGp&apE$u)QCh|cp`nNpGQW>x(+@fx`g7bZ$|!aH07Sk>hD z1mEwK@ORA&x>_gh&)_axl+l3bsyhBM3G!YdP}~q?^!V|!gxHR7JUEJ9^=C-a?q7P= z@lWztC#fPJ?4Gvra<(qU+156b-}>jCI*-TCWt8e<%st%@P<+g%CWb_R9Pw;w5vy-d zjA%B7UP@V__AqRiJ#&HTqZ|opv>Rg|@4|B1gTzZQ90?u*R-el@_7XZ9&u?~NOZkNY z34;hM`*b))8wq{(ex+TP?v)w2P7(2Yq>d2^>y6G4^O~e2{vSeDh%puq@gM0wgKp$7 zKV{N$>DZb(h|4%o7}yq%GqTLF))M;2=^Y?L z*^eaRB<8+6diSA!fVEs*OfAGm5I-t1jc?q{UT1H8>E%{nI-F(-#vjh!phu@#vqAE-zLmuSB>*gBb-L% z;hV39?*gLOCNLGjc_zUR(|n~E{j}7~@L%lkDW3FSxkZVh?lK-_=Af>1R`^P@8r1q%}y z6vt4qAMqDd5yBPzKEi(5In=Cg z;V`=LwtR{ucC;@V{aNGAhiy+%-t*NJwvmU{B>blph{+6Z^JX7qyu@gzXK9&{c)ac` zFzF|M?hDoRcd5?AH5an4nR--I)9PJX8Q8~2iNxm5dNe4S88ctm6t02C^MhK$j%N?0 z*e|U61KOEGVkJlvT&38)l?#>33*_GeaXOb6%Bw3?)JC?Q#qqrkV}He(J)qpjb4cM} zASi;Z@#aFp=O{L!3c2js8I0FELuUcYv@q!`H_Z|rGj1qyen8rEXt4AqSyx+8iYwZ& z4RHw9QglUJz8S_Pd!`jIQ_bLq_0syjh?_&!`mbXdU-d|bex#bR7NnyIFc;$e8Flnm z38{RHZ!GesdcjD${Vz72fkG99^PJFVE#}6@@@g{jOLs1GLsw2HZ1@lYD+NvWYVPwn z8~g}9deug2*wu!`^d+H-?x;JbD$F8nDvFKyr#whcdOX{?>}L&%tSq0>*rs?f&2%gY z_n>XqD(2wR!xqjqF>cKJPlr?TUWy23EE7D!&$G%_d1R-oZneXMuZuKkqS(~r!TqKL z+3R&+%!>&LHGGO#mR3ZR?$b7ZS^U%w0p~<>d(vNvwDyQI9qW(sU5X4~FtE1?0JRitT^p6!{DLp|K5Z zddWgw8v?%=<3Lb_C4RZKsGE_T-j~c)p7POMNE0<0_v!cDOm~l)rIjYWr&Hp~xp=tY z$NZc_MH*CJsSDpV#ZqEEN_(33bX2*~VRbWrve%7wx7tB0GSSZU z_L#hscr6j5?N)8!_93dtyIkd!<6vf_97frWs;G5^+vbj> zQg3kuX!*p9I5N0I;9XH{j(#VB5YOTd**eMuS2^==>qwk*Y+2SuRrV&UZ|XT*m!#0TZzBpB&#OzkFh8yS3B6et zhO28@qr~%6W$Pd2DFexI25E=qdlq6%D=UxBwhY**EYU3U2=)uLJ+>NCC(ec*pWEBi zMa>zZL~l78e&2c4I-`~vI=92CR`k9E{H5@PBHMJ5esH{wm^N?k=(vowhDW+A+OVip zpo`#+0Yy{Bj=E%%es%3^E5?zEyS=(Z3G_X_JB91IX6WdWU;A8brhfj&E4IgIW%u>m z~c!5Kg$6BOB>Fy#2Qr}pFH3qwC`)k^lER@3CHu87j8;mQQ=XSf^X zr)xF%ITQ&Y9OP??yu`Stv)Ged7-)z0(AbQ{pH99QLb{2u=E~*5Li$8nnGwzEdUYP# z_sJq){{0k4PgQUXLrpb4$zhzQ_QCPc&VUYq=13BZ>x7$`Grtv6i15Ut z^hu(V&uWaN5>e=VlX@`*V=BmO+WQM(83bm{7DvjPwSlQ?0Gw7%4&&^Fw3*30Yr;NWG z*3tK|5D@+n`Cn5;puz2w(cZhTxqZslOLLZ=(uMcZLvnW^c5fmlSQ>=Xz{__ z!krc@bs+tWpIbU9?8gH^935Re{qh})WHMGJTzIt4qrIf0xA3+`Gb{B>_|F6kD?Gmw zzTf@!SN23V#}wPDPL?Rf0}*k#=3lSUF6=|uJ||_B&?}Q5uImt|c%{!*(0n+foaEsj zKDeFtM{tMFhX9W;rjY&@h}d@^I$7J9>secy!>9b=5moSKNAH|6+UnD%5dFzRhV$Q# zglAVa9OqXNPe*^RX#`VMwDh#KA*uXiwNVUUV@vm(b^38Ndilk{A~M=y4>u$k;hi?B z{?)6tMOPOW)L-X0JpO-8`&a4{ols}X7BfGmo6S+;z~DP?G!?RETz>E|?L4SQAv8&| ztHS@UWjQr$I$@%lMTo3ECzG$IzUApXyF?WpYhR3 zmulxMc5aaZ`)W7Ml5jAq%_TOsV+QT7o^1ccuJM!Ai~S?4*H6l#p{gsy6G5eRPsG03 ze=XEG!iH15a7sLD9f*PM|9k>Td>5s=hme29>h6JL^eyjUyH_FIPAQJDzaL0e?<2n4 z;2NExuEv_a&hQ48;zI7dP^(*9P0X82Taj#{+<)NbQ(p>uV^j68U3cE)#`!I3Y8`zF zU0Uf9`&L&6BQ`SEyy#HV*cNYpLT?hwk{p?7U5pa3ef5qm>PX4^`ceC@-gOFQJ}T4w z2$l`RBiCtr0;dxvx$S{#+D4cM?S$Xva2;P{yHoV*N+X5%h<@r*9%w!*+!9NUoYhq|< z{}y_g)BX5X8Oh2zM;Sb#ci)9^w4_?=cB`tUYGV43$qtpg}Ee|_kOLDHGR4`-8=Hi z@HpSI-@7`SEKF_oxccGc?tF22y)J)+eWCA_cJE^Ua_ieJcBE70^)A^>X2oL0mHWls z>0)44tm$R$(m0yt9PeDCyQkMl*W}f3lziaTN-tT)J;3$eAKx>sC)W zm3q}h806LO37~3Y=CCmbk7N7t=JdVmX|&zu>(uMRAKg+nL{PO2;Ik!v z&P5B-K0~6s3D<0cxo#j10)5H#Z$1{^8nISo@LogZ$IL4vh4LLuqiVfjaxFv6vn|W~ zoPKV4G4i4s&j3Z_`r#*kpTiNPoI+BRm>UG`=X!;n4N{0A1sBA3PMmN1m9yLzEJu8P zQ2fK|#nA=aTzd28f9k|W`U*s;L+;8k9u$;TGtLr~;R-t(u_m(*_+*lbDv|r`1rVV? zxMYzfDf!e&>z%FGNT#W)zumO_rAy9t1dkT~+D3OC&@7y57x0nnqkI!pY@LfY(9z$~ z$+OI$a@_b>f)A_t=67ek=S9}zKGA7j7_p_c)Bg61z?JQ=|W+3ejEujh!3ROj;mBtBJ2D+I9%JTUdKYa1$6IC5#r{0P=p&wLcrwk z-}t%;g;0G-$P;qb1pgMKA@?U}Ej2Nf?^~E`d|F6KY;)b3ACl5m67M zg>=zO`HzzkWH#B~5CmxHqWe6b8by52zyq!ZuKKcP__y3g0envIhY;0*+S9l&fRtTA*0S3m6et;pIg<~t^7(ia+5d2z8 z?|!$49@7@FV3Za$C|4p3*%#$Q!`Bu@+5mJRM**TDQN1TnAI%Q5Nh}({vKKw0ERH^U z)M8F8eUM2$!+E0MD%gOoV--YGU$KbXATboijjQhiiKCM1F24`vWO{J*{?P^O1#a#| zfRTTV3wgIA0rF2A)ZvOp2nXq+g4w=No+q%}$>W?BK9oS6;6dRAv7&tfk>;r`{>sRX zwbp*f`h6U*8ae1D$ZtIn2f>BhS117eC?&83hO6%a!K9XR9pQy?a30uHFAR9ZuOdE} zRpFwtAK*nWa6#xifcZ`K3kULI3uX&N?OeFZ=BklUqsa8@f1mIyh`ZHx`T>M;*6M6zgXh5S%_v$Uw7B}rRItifTHN_5>^?@`Tw zt6;3UaTwT&jX@bYWK3Yffgz$x=ht4rot=vU%8J!8{(-7@6zefh7d$v?#x8VTgDwb| zpzu@I4~0@8P7<(74hcs>3XV)(2b!9aq(VutCZ{2piIko__H!r zfD6vSr8AHPpf9i^i1z?a4K`V^3)X+y!leK_W~_>U>ykky0Q$rPIwK5%Dc|)!sC=)a zhy?UfGR(>)6=$dbmjVsUdJH8Q9W1~l_qxYK54c_sBlaP10rZlH1OUWTDL8;wcDXX7 zhXNYkvDW{Qh{BQ)tr~6tktHMI0SpWf9L|zrAb)B6vc_oiIpc+O8GY6r z+6QE!%5P}GjeG#1dj)zSK+g(Ap{x#Gc-4XGd{ zIP5%ka5$9|&mb4zCTTxg>w|*`Bq|U_zgsvd>6IZvO#&5gE)=kFUxxg~;}f9io_hjv zTk;=LKza}8PATIW_&|UF)D%;9gAl`z^)B`v%K^st0|c{rjRZtR*L60F9WSpUpgs?t z7sVZ|w{3Co8Sgj*VAQ&xng-Yk;Y{h7{fa>r`;6aLcNmL@{Wl4hnj$%p09Vw2l7xIm zRcdB$nK=YWz`mHQVj#f^?C$^8LMO>axpbj81oq0nCDT3};LuSxnqwf3(l>lg2i;YmrCB6Mh@)HI%4NH?{f>8HVAWTs&TM$n$s!58s@>ZfrJ}pa< z3df|!0FhD1aadAevEZ#H-|_=zc$Aen@bXeam`pj`nw{qvY+0Jtsk`S`Nr5=8%hCxR z=j^vA0m*DDOA39Wm0M`r-ydSBnyeed73m|6xJw?RDG-ZYLxx8G+lt zaPN@}4L3A}P#fB8#joV<;!+muGiL8EC7Q)#zV{)^snVen1|qn0VirSIn%!FJA>sLf z7N~^P#}sD^DNBjwF`4DrXlfS-3O~%qUWqOSj2mPX&gThu^W5L(fi#Rlh?O#Vrvk2uQ(0W>L`5 z+9!#ea$61P2rLTVB@H-|=O{8db8-e-Awr0+dM30aFAXFKkVYdPS}h+0Q-qJ2I)`=e z$TBGJ4Q%02?#00e0r_A+!vM3{M}CS|O3&f7P4J`HH^?L%P+f290DKsO-(&$w|1P0u zYUB_z523WnA;$xy>G?)`rNOW$4mI0}?;#F0Bj$95XdWH!o3J16!414v{#Br6V8z>-x-8;N!)e_)3Hty>XzsWK> zSl5`Ler>#x?qeS!dsRS_78k;S1h^ho{KKYL*5lio87qXPXo$O^%_S$%7IES1Y5!Yw zk7fK*DP5F{bx!}oRV4@@(S|ENY&nkLLJfy=^C=>5suNI>g6W7gP+n_l)=b>%q5H&V zaKOcMn!pfB90_R>+2&JlHx+;;c=9s?4_Bm!?o+?Tim$rk+}oXa#22ILJF}K9)M=CJ z74hF7>))Rsf}^vfUVH-!p3l+=#lG_;w`9Q?LWzy&7hZ@81U;CJiBuZ87n?N}k$hEI zK&g<}vSrbQDdf0~kiJq3nW2d=8jonvy1f}CW7&Y*FIis&-iax^%Cj{zz`s%6>jEdT^`P`Y$%#p=ybvOCL@uigVPp8=T$Bj}J8 zJAxoJ$SXK^GM{QM5ng+(QnU4cNq|A@x6un9o_j`Fh2G~u&f+t>M|f*04P1v8?V)=z7(Mk5oqq-6#bgqM`wWB{SKh?4-*%6_F3%$+P0 zA!mWZ`u8auh)i1aPPuSVRfARYZ#|Rd?;zFVm_XnlVA_a+>CN9->YE}WzER;o`sPm` z_e(Udz>4-cyF3Y!E?~N#4Ecq?`<8YAra0dfO=oA-lWsB7i+Y+YpY&oJ6>uwZ!VKzpSaWhKA`d%wQ0-^#Xt($!${ zI~J~ZQh*d>3&;xsV}ndwFjlxk>G1({LR#1HT;d>XpeUN$WJm&hjQc?2M)l4@^mVGA zh;Ip4q-_of5?@*i0#5mozH)K_SjO_gZ5^nmLlmXJ&<1>k2HkRwpc-buu8Q~pEUsf) zreZ`jGN2qds!0lZi`LignTJI&stk4^2fkr~DOmva2n7H)xP2-uPg)06HO(8wf$3dE zl`AmydkT=ps+fqPVH^Rdp3c&`0+Rv-3XBe}-!6=+r_%^w8N0krU#750XbG!NHy4vg zr-1>stHIl+{i{8lWhT^Ki1=AX*XV0fBz?5LB8^pm&z*SW*g!QvLJUI%0e7Hq9athQ zn#g^)Bp&&-V^^Nz5YD9$+oSld7F7`Y)DDlovK%59n3UZ{NfpS<|A^Ajr~!oYc%4jD z!^J*#*~i9cL@ShCs9v6o90Hd43R=Jfw^6_+1^?m6d6p0P+61Jd5{1$x9`K}^T__#J zcPkkg{uM?JQccEZRPF{S)>ns08!Ut{N%C_=#ei4$-_8N|MkF-1gS&WNWZsZG1bSqgEwNb2D#R$ z3>yxEbKJq_G2}hsbXemZ#qXh2yXb$;kwZee-$ArUz6&Prp(sYdg%o@acNSWhGf3xelF_WWsUxCCt+ATclWTjEj5Z|9wy*heSkX0^8D4{#)20!C$+ ziAj+a)l-KY-~_$&r6=FGWqR$vlqpCmm53ouj2C(XvEu28_5S3i6XH- zYk0|m>1ogpqKg#a?F~%-XkT^K(7>IsM5Ryw4nJlxDwv6+8N)AJK9gu?H5Yk0vIfSl|`fGFBSEX z%-M|C&9#00$PBi;FOu^dpevb+qa z3Fb#O8R?=jF1S3vT~|s;Sfv^&gbDIfdPo7x3g*8xtf$249H}_rdQI-oG;vMITg*e< zj@GQ6gzkG;)sTsPu7lFvG# zQjAVL8p&K6o@*jrYR{I;>`6LH>2trpv9fPDUsT4sG%9Qx$7U_P^yDu(G5{UzAJ~(wybP3+N1!VFT5I#5{9T|TE;tnfzao_L zbdwrBa2Gkor|%XwkS_-6T2&$9U0u661{l8G8_c(j=LYaEaLp($Y7WG<;SlUfJHZ$&p7rF^j?ur1d&Y zp!Yf@r0+qM>HW0;U2bRS7FU21y^G5}{y$j4fq9qOvHbJT*$o@~ya8IB!)cZCH?2JW zq}BPkBllpTFr4dKfu~8;vx2a*NQ(ua7FOmfWd=ESA&a_hV{-5kJC$=<6pCji?fCISMLkBpK1j8lRBOHQn3@2+Um_fA_lBG7W<-Ene~T_cq@yt!rAR ziw=_@Ak5uI1YW5}1mPq6v-RiCEiLe^KmU3BKO2GmE&k`O5BR>9e-0sFh5C;os7KzA^&eOYqN80Boc9 z|LrXJcMpHQuK<6w!6aVL!C;Y!g{68z?3ew0Z@Rn%6j{pGF89V&j{{iP+lX?IE literal 0 HcmV?d00001 diff --git a/ipaylinks_statement/statement_files/2018/01/20180130.xlsx b/ipaylinks_statement/statement_files/2018/01/20180130.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..f257e8e8700185012ee62a3623e0dae7333aa50f GIT binary patch literal 13749 zcmaKT2RvNe_BLZMh!`bm!WcyFC8CbrdkdmO4}wJR28kY{1<^avyAUA>f+TwHQKAzf zME}mn+rIaI?>+gA%$&2=UTZz;S!?fe_Su>$SYR>?2n2$GsVJ$6@sEQT_-^HFsrkg& z#g*IA`H3}`*CWUBxOd7OJkV#m{*fqO(H?RuyhjvT9p;N z8=ZL{doIuEKIBi_>_WcD`_Vecv_h2!uIE#$oQ{_mn|4#XqZd!sD?D@8a_}jwcm(IR z%G6VH>>z_%&xdSz$9TPYof7GvS75V`mO2vaN1L>VO9}BQ3QuXbtgZDhC!Tv+=aCoq zyMExXBU=b!*jPZ?-h4Y5_S>=&f1t!%8zTMI@b_uPBEUjBIb_+5(m@!KG?^V%N*)CMM9wQhFq_^y=YcZeC3Kw zdHie7$_PT@W5Z5IV`e<`MkN-?UR&+2S&$d7S}`en^CCcf2{&DR34gXfth4{}6F(ue zKJ_4|>fuWVMKh|J(oo@dkr{e?+gnDF9~?SVzK!HGOx9wJgenhV$1>^W`UO=p$LO_LwG^ED-ez54GKyU5t@$?R>m>hJ(9l>$ADVDj zQD`ZY3r;^!Zt+&jvhiGD$`Fv#`XYo$B2}#-xc%h1K|1p!@NH$957^(p{3h@PhA5;N!Xl%-~R%7NfMZEEtpN zEOo2mnBuOxt;ep{=0SH2wm84Z=%`+iy53RiuLbryW^cZiwoc>TaoU!wTET5}f8cyM zY1}_M5qNoEb8UN{l84i z-eDPY-=uwe@L_v9#MW%0#rxd6>F3a#MCRGz*ml}D(Oz3)*1Uw*`r+Kq)$67c)1q&V z7aN3=8=Xzts@vSx7vIIGP!Mt7YCBrr!=*Esk$B_w*jS-!@Y4TB&)#XE@Wpt>QlOvr zL0V;>q(t-S$zGb-?CIH3p65>d$B(;hzWdvo%w~SR2Sts?pB2pJ?;d{=J)1moKHE8s zl@xFdIG^fS-MtmK*VWVF{N47f#f|EGlpHBbaSVtw~Dc7Vs=w2B~QNn3h8f-?L2ON5^!VYn0YRu zvJaP;UKWqH&g~*8%#(J=plX=@{xso?{;EQj-=e~5SgvP?t3K8(fxJ>-FTM?&tgT{` z9n{vxoI$G}I24s}j@P(S|r#?eC>f^Fhzy9@c!rms(;xgpkV&kYup$->N?s`DaRr>weF5Q|@*xeVKT%HFC| ziu!Dx(L_JJP4xy3&n*u|k7KvG=w% zaE??<2CgsF{;MJ1K$h=7FzvgjzdGnP*#?Kp@q1Kg%(KuGvkBRtdqJj5+Wqf;NQ-?+ zzW$xC(@CwMD)|SDpcq#N#3<(IagmgvFvdkR&X7tfJjr{Hk;X8^7kA%x?KF5FutaRMC$F=e?v@Ay{DycY+H3I(3&Ry*uFmvCyYC}Y3Q_8xzZ z^I2=_CKH@O-f*DVuBq9g+}k=o9J{1rhu@_+dH&_&<>#{_I*vR}WCVH%_l54;t}=^i z_!eW^p%k}{mzXQ5$7DU*FuEfLg>EkwJ3cdTc;#?#gG!m_E+sjgQEiELLsMB)?VzAI zMSP&nQu=$`?0mg4!lY%1Y%KzRqpwjUCJOH_ba~^o^Ia^mH;fvn?&T(h$_acByW?ZM z5K{-Yd7BaO_Ej=9UB%59jD!~s@;LI5mjoQ2ZCP-Xoo!Di`$)eJKKuUgc&fsCMg(Jy zGDsnEf$-Rd_?@LAyngw*Gxn0f`&e1?&*Xf}coQNjB-uFc2A~Y=MBk>YNBas}OE)Rb zHughbk}&XPOCf1v_BxxwE%9GS^#-@eG4%)<`ka4Wip|o0p6Pu*y9Y}%;nf3KLpJjf z8Y;*-{*bw9h~MXIGNasU4T!tOgm&!!aY;rZj`DCSb zu0&sJZ*-QHEGKW`ST_glNfSJJ$dx1*oy$}IwO7g3+@FW+a~a5S;^0mGEj#AATEYsg z7AyV)mt@b8mdWhUm0%p}B1NY%gi&douGk60ch&Lk!2##Cy{>u|uYIkGN=u=1_q+*VG1GD^6DEmVl8|F-=m<6 zH67SIN4=4JO6IXUTdJLTQ=fi0Zs|UZ*}I+-A=HeIU$y)|qQq&8e@8=rVCI(kD}HdA zGjl?MEUC|eVR_sc!h$(Sl~h|oM_HHE_H5z8n$sopCz;{agLmir2h&Z|I3giW(|dT3 z`67>77h>|qzu6rG%X$xu-5vf!?}e>6fyp>vWt{J#a8Tx+Oy%P1-p`ci26`WIZARx+ ze7hcP=Q?Fj*NdPjZ+M1!&@GjkqL+8QcmxO{#sps7+&6-8BB{N&@q#}o;XC^ zpinGwD)fqquoS6S$KR`I|Ab8$?igfiO9`UkF5n8Qp^o%6R#T&S3E}9Vy>u&6p{wrS}adPM4zOO#aS86z?A&0ztVKm9GQB6-~i(hl(&E(y}#{B$2TCRh5Y<*B; zkFp9!;`V*2{&^a0>aS!Awc_`$kq3~a;&H(_UKnL?$*M68Y8Upn-y=>Zi4`Ps78=VR zAm>Ptx*yq4^^IL3= zhJQ9o&yd)}Qs`colt!N4E8fIObfDJcWQ-C`y9-t&7zy!}5QDQ;2Wi>yYPrm zP~(gIdS2zlT@w-CpQB6t7Y@3PBLq2lPgOD{;iX>;Ha`i8GpKa7Vaw^(9|Rc1I**EG zJ#zKCFMsr6CKcRDoVR*O-rmQ7v(?k{!i3%Q^23*?R^F%aQ!16za&wOd8P2HJo3pl! zT_?Ork);Tw*Ooll3QAT25O(@Lw;zOJL<8nJ{gbq0i8%S*o+5Gwtk|(LD>2iL3cqJd z9%@fI;^!N(JmB@`mxDw|eHM6nyYw4x*ds|b9Xm}d<*nOgp$YJXXRUoTLzWQw2%jOD zx=%YM@Q3ELiHTAUJ{baohLP+^WG`$lKsaO$JUw=!uVaXVJ}lc6*_}2f55l_Sph4PO zkNa#`jf5hk8l&N|WeD>MaY6AL$#t7^MkEfY!`4__MkNKSkzOA|lo~XR`tiVaBnwWh z=ffU~`-HTQxP_d^GeUHSC^8EN2#m1n%kI^sCAipiz$w@MZ%82(Mt+1mba?7Mejl}&MUeH0?srh=(+@>^J|X_2X*`s;Kw^eI-K) zyp8+fbZs6|m8wib)iiAlM2O3Y*FVoxSe zwJLQ62lP0MQwVyod2){dVLS_jVj#8@u5GYve{#!X zjx9=ern2h=Av98VH_CC=zs5s87zbdN^EVS0%!rE)xxIuv-Huuf5-OP zrM|_f<#==@%gnHCqpMbWdiCHb?ajTxn3;R9WVZ};EYz`rr2*+W;D62HM9qrplB@Ky zhrvdDMv5xA%v$2NzjbsM6^Yd1G5Eo(eBYVR5avs5jBho3w+N8NALOSWlfNlw8{>ao zg10GOm1e{*h{+|2ZVEAmY8qcxlu4%|883664)3Ulzg90Mu0C8%h(s+6O$2WBtIsTZ zh6pYarjLg{z0dhV8$(~$!I9wj&FuZT?v{P{(F1|+BbeZKcxwccPY330QY%HOdbx{n zmouKF>mg0XZQgoj+tVeK^^AR5akoj5H~iMrNJI0c*e*5)rIMQDE#sv-#)oIUGvArU zH)H4+^MQ?TIkbx!raonP=gy@G~--|vG z)Y#MXVItB_rLhAs3(tByCLH-_sR^-~EUvf5ON!{0>2l<009j@(ZkfI0KO6`b==dno zr_r%Qr|M)UM0)#fT%fYb7U|Y#R+WXF#IdAxWk5gqtKBb6ITPIiQ@|8ITaJKIRzbb( zhkp90TNK~hlXfkzcnSpO@CM8AXR z>HNgO!r9pYeOn*%yc+#{=$U8c`{s-(%urb5aKWpQn4GGX!-8t+>A3#7H(-X!_TKmJ zvGf*sU9_L_@nrP2*Cy7kOcxH-gd9MF{$;aCp_s2=DNNCe^Xq6?^ z5o3;83HM#**<2j~0`ZeK52fAMRwx_OPr`dOqf+jFtPE{hQ8y%FmZ7>_f~Z*vas>x? ztPLxXRO_%N7mOW(e>&HObw?}Tn~9>qi`jr6$49HYYrL}gg=GufYJBgP#(;TU&WMCP zGH?Ir%?VxlIDWKxy7!at9!Gf`)ZiQSM0nW~4*4Fpo+7iKL};oPO(|rr0~nb9&!>#k zzft=Apz)tr{eI{ecg1_e?s;Ul=Sz=-KOQ>P>|ttc2#roL)(}o#WCnrDNFdim4I7qL zlk+FjzbUoC_b5Y<&1HxOF4Z(2%on^by2lD{U7@;-#Enc7_2 z|3Lm_j>JPW$B(|xTm>r?%mhh!;r0d~{s=xLNzP#4!1z62}Oxc-sDcI^|5rtZ${x1b0LthyQBuqXqMy znBVug122DVcFyn6(n`(*`nbP7{vm?(-AOGXz@yq@F*wZjG z+WGleaTBp0S+r&*Zv%Z!w&zXXc%AK?&wiZ#=)4oya(ZxfdAxq{b!mI}hZ$W!z}~Ov z53}1X+?Q)hmE6sxrQ1=ljdT(wZv&2ZK74G^$f9}U)pWW(y3*#%W%efE82fCV$TLtZ z^Xz!hwMBAf{&N4Adu6ut)9Q}+?8SF8&$hYqUv5WdM@3=tyAqe16o>t7r$b4XUQJ$} zN5k8@Z4&3J=XCS){=bgThkvkqTzw#MnMb!9=zq2^$t@A!MeFD3y|;I`Yj$x&M>i+l z8hD{|^u=j@yK%f_Z-4RQJYCj~6y#XuY=jJq6DWi!+jN8C#NhYvo^n` z%caGyuX|P>T>d&H>JMr4Iy*axS`9q>bryI&y;+*feQ|i4b&>F^lr+uN;z_P3vs3z7 ze}r=eWnaW@I%R*v9d*b4h~12d4ARbsP1nV8(o@$(4F1~*B3STRBh0vm;-H$(n^CKl z=Rboy&4|2?R_5J`F6C`bDucRpHG;bD&tt$7&N*Rx)AN|{;q$II^}^HBpKRE#x{19B z!f(c5!Qv0R{ReKm>gE*z@$KjAw$YvhoDYZ&^*qkNh+Fc(B3#c2WAjSn2-n@`h(!-J_3&X&UilIbuH(@`#Sb<^Dh4Q0n;Br^ert_@qz7OzUw0rw0z;na z5urdnV5j)O0O}0)d)FVrKJUYx9SmUQh6Mo5p1}2<2VL`90{}aBLW^$j5kXD9Ny%LK z3Fyr6?6`jJlLQK<^|4bV5{LP$jpLf+a08bg-aOf?47>2TlB%bLwvNgCB~}01(ntp5 zzs_E{IOre_i*Y!=*vy%)r1Mc|@F~ZYt^A3`2EYXnFaJ}U>1GbS_(9NGjv1ZX)3@$bk1&5BXcC3|TO%0Jj^LQa$ zrX`X-C(MP9FXq#QTh<TMwU~%<|lqBQKaRDOEsq^}~$9OG@`Db;5Z+;XX1X394o+ zi*3~oJbVeZt*E3{x@R@tB^by2F4ckmO?%4H(*_Q__Io7R<)#S>(aaB8)#+^p7!k%V zz~&ryo0gR$bfc0T0%!e&X7SK&N%IPKL&fL{f)Y*@5YG#+ol5evb}y2#O)~StW|4fL zCnU}_w1LgijD^**GaPI#q)iCmnlht&a>SnoTDM(*<#~#A!UsFy_0~#|GIO3o1wBo#9`#0w2m$_Yks(qj24Mq|UjhfUBMi-YPOa?(*m zG~sc;c~6WFLs6VCtRzVExmRe+BtG9j1X`k;9*@f}~GU?hgvuYWiBBbV$dY3 zl1lp&NujXe(8P(9xrZ3bNC^Io&;#`lqgn*`IUi*}=k<~b`QopoEuGpP$O6W$Lta>Z z*Gm|IY?U)HP3?IvvRD=WMzEs_mQ=&5d@e(HFlY1xgNYt|#7K{;p@zVbiMOE@lipYl zr#YTdR8G^f;ng)aYwco~RcSB6fW#6Babxo6)=vW0>nBB3Y=KOaqPM+Z-3?-}e83SW z@oE$&JKlx>0JUBSti>KhSC=4b&Vk%Z0RQafq5;=)(L_~mfh?7xcZgGxWuwwVod!g185EToz()Li4i6H0!UUVfx_w%Xu ze9#wY=48MjH9CNfkUaxO)f+<6gimKVyJ`rcnRuItEv376#IYE z$z;e#4MKQ$y(=1z-b7Z@fgEDa0Ub%1^MU984&_(^i~!6-9{%&I!4?WQJ<{}Z>y!!F zlQ*(_egItbH*6=Yw?W9d^4SMh9y@OazO5`~i}9O)P{ zfs;;yLu4hmu=Wl+EWcFQ{tF55R%u6m;DrB02*FL+zxdl2F_cc z9pZ!s&n8{f0`!-TdobYd#0yS1#GVsQZZL^kL6V~GNudT_-^r!1{{kXzQg-}IPK+!? zs{ndwQsw~gxX(0JEeMt>7wlMMJ8jnkbbQOjqc@fTSHx2ifCX)mqucdvKgE~!=z$0s zSkM#7R=ph1oxN!K39I5mnR}n%FwB+m>EOO|8^RwG@jf{*9@(>0cI#u6@ZykT= ze|Cdr*bJxwXD@jQg22Zkrnyn)4(FJyPZIMZ7Zjudh zM?kCqRgVf}y1A&4W#BGSDVqTj;_hB_nI?(rR^Etbf}@fqQka6X_2KGsIH_;0lhh^e zAkra2x5Dp?y!?IDL?Hf18V8NsAkZIR8baS9Y%3Q~kz3u}OOHxwcWcIcEPbWpslSW>) z28c}<0JR`D9_EYfjV{qq%E4RW%gEB-nOzJnZnNiL``D@X99ar39Dn3TD&1V1kFNaa zOw+JF&7sh2qP1@`+?)1w>ekaYv4VnKB7L+rPVu)h8l zn{t34Y4yL9N0QihfAbCRB@07wo zSQmI*woosXL#Yd&+*e(pOaVlE=gFi`-m;?cOHsD}Ja-5C5BrYPv>X7A>Ry5F544Io zQj1|Wt5uS)T~c-4O_Nrfzav*}2#b%MLcJPpxds$BfZZ~+&eM!^jY@Bw68z?#0dp>@ ziOn%83*ID4b2jAqPdQUkX^&?RRe)mj1#>11ZkmVZrvX zT^BUG$?fvDh`nPe5~7M8f9i%2;6fnlWzE^DWyYx?!A71`Q6)FAbnsLwxyjR@Q+6@>!L?F zRVH`EqoP~H_A?$%6gsa7Rhf8No#1KEp=ovdFK=JqMz<>A7!RMShc2@nic9+pA{4o) zAwAV%7|U6G1VZ{2mTc^JQ$kiN9&t(2Xx47p`$;QW0}Mz-=kK8tz4;kK!wufhgGNAQ4Mwyzl6rVv1aqGU4CJlPuu{3< z&7f-GG9onH8`VRp+uWUiaRONcE^IW2CAO-h%|lbLsH1CZ3+i=MANq)pMd;G)1(fa# z7{oqR&!#^j3%wv6=`c$u>23+)cf5NTM_!6 z*nV)hE*R=~4E6dA;lV~1`a9fN3 z>)G;+$>uPY`IU?7HX9qP*bA=Rtw62gY>AP+iu6)s-BK9X_%JNbHdWY`)uw^E7QFrCY9yQ2r`H$ zpDedsU;}0)^esO_tASI7fQUux)?7k%SL>=%Tv7`VS^kNZkB}PASj=Su!i{+OVEjov zELapUXV9c?wFiHuH~(gSAXw~rpK8LJmR##Kfh-eGh<`p2FgL`2>_bzO*_OQ_x&Xm7 z=|6oCafPJZrSvD2O;xIbsd67831Tc&qOYQJ`9BOQ9cg#|N{)&vAbUN*A^i4mcPqGnd=G*0?r zl^5ad`oEpOMcmSAZXhwP6$3Y*Q)tM4TtG-t4&2N~8K_1rYSBp3{G@TM*Cd-ANp-LiPAdJ1 z9rG_0#VWpEz=(!w5}2ey8Gl$%>O;F`diZa+VB~-3+2PNC)=Wps>T4%+KqJb)-TlN7 zW%<%CfZ+h=AI<{=DGmj zx06g3bO;-acw3my^^mqo(BBe*coCMbNw3(L(N<7B`7*vaKLXNameBQlV!KOddb3m4 z6c=EzlxL|1Wc?8iA|NuG%aD;o2M?tH=S|X8)F8(E|053wv<&Qv3G=VHVvtIoRigZ%ufi#tWSS)3tc?_6Ss6sabE%^(b=Rzht8oG zQnVm7rKe&<$U>lUvRQdU1gzUXzgu(ATy5g3`XR>ga$jU1vHjXf3XoRz4nZ)W;T5zx z{~6kwEA9&{NUE)B&QM43RL2tFPJ^~s@RLkc0h%J(kJK!G7)K+tah57482rs3(lL#g z_qku}i&UX?giiqzeLfNuC6gLO#up^8SXm3!5@4PWQla`g9%4jM1#hl%0O5Gs;R8%m zs3Ho`N=Q`jfZV7~)a~Af-s=rY{YSVtR@}{50S+R+;L*2OF}{dzw(?fwU_xYub!cnT zf08k0#j?3BZx$l*F$tNm@}TWrum4s19H6}(6w;HlYrGNv4U@9Pv<lPFC~&+UN6iKp#aKvhV{08b`l-0J}m3oDz$pvb%{T#=BQSGcnG)xTY( z&gr^-b`EDf+NlwP_FX%%S_ev2pArfenDilCa6rFj0L3V5i$Ah_@&0Cr-^fId$-Fo0 z1Ss_dV4Hy=FXqq@Z4%%<5WoT&-mZNW5Cr%IAG-3~ST&mGeyVACXC+`T@f4v0;$JJm zynS_tOC+1kibNv7FM)^vI^Y9|S9Mf){6v&l8W@fjS&x9R#Ad)Yi#gQsY7zs~d;|=n zaa9z6LF5WugLH>_ZHQpmNC0utDMA6 zw5|vh>G}wm(NRbBei_YWlf3i>9u&l|c`+BdJy1$40<{!W!@6Ci60sTB^r{l&8IafU z1eg;vy~hM;RRw=k-|bPz=E9@ic4bpt*9&FoRmkSX%k=|;_|dIb8C+8SX#LaYz3x(Q z&Fc;I{jYBc_P-7kb3aW<8H&Q!N+eo)vHF3&H%tc=o2~m!J2TdO4TW&!!%MQA?WdC! z?58_dk^ogJ4HS=bB$}C#G)Bzs`!RYXuyiXd-l+z3@TC8tL+=64s0(FU=~qTN%}U=<1ASz z36j%@0x>$|rE2!w)X?7AonzRm)Yxsn7y{)1yLl&z-b&zhq|?b;g5-uW*)l_1&b{6r z#A^fKmkCP6Vw(Z}^sl`ACo`5AP`N{gxWK_sH6cN>yRL zQO$2@rJD(U;OB|iTJu~yyaiL~X#17W_7@8L#uQcXr@z_!qdaSArD%Mtl?RG7k~LIc zUn-WddVKm3=cSViql>uP3Ev%l2P5MN& zeyk|%f{`vl65FnBl{mHLC#z;+ETB>LSn=$k_A7JNen2CZo%-#Z{j%v3vXZeAH`hgt zJLvW!VGPVyZma-iU}#B@1inmU10oUkYZ&8qBpM{-UcHtO|I>#Lk*dch0{cZHoc#*R z8pvQj*^5MFAc%p~Xx82Etr$D${#dwov)ATN6?OekzJmT-s2pGoD*|oU?E?H401Gb! zg1%Xiu=O`fBmwk(TAubLLUNYzf-GArDCjeJ!{J;bB$ltD*n1$Q>e|H=HQ|9oCPT|%G=)YMdwt13E zSV-+WHQ~m5QRiBXbL?U_qCm@BcyMb_R!bt=IFl%hg-%^cB3K(+#am)5M+Wqzhfz1v z-G3KHCx*h=vH6dwW6JP6+h0+@eQ4?41N(EMfUrcGIv86Mi4jgZ(T z@y8#qBU0nD_PNCpsgMh>(Tnlqij5x`27j}$diBH|#h~3XwyolstI;A0@OOhhomA)W z2PZ%-;3q(?gFncX`xm+T8x`vV-fpWOJWO5#f^zzX?|%u9)Qx^LiJdUrOz=wEkFKy*C;X0j8)76VIPMduqFXWpZunaRJJ6_ej}FDe~RgZEW6x4Dvfp6 z5&;Id+tE7E&1ExBa zN6aU68V9Th<5L$=?ZXuhpc;&De!@kdh_c1#&>A@CFx?b?Yj8T^2ArPT)i`*V1vuSs z_|*v=^2D|b%9fR5MTt0Bpu8O`lAtO7+Xs8?^(LV=l1qDwz>?eS@R#l3?ak!2*$Y1d zXS#rk@9TSuVW&k!r?Hh>m2Z#F^v1JxcC&V9B`(X`-gpIip6+a#1+<>7uM@a??|uKe zdUScYT68*paqMg+*0}fa`~$byl=u17y6y1#;hz3Y3=9uqOyJFROb{8y-#cvnxpM@) z!{+}#{?C4!e~bTfa|L>P$=`=Gut@xm%_jdA{O9HX^xliV4^vtRX zhv4sH99YEv%kV#T6#QHIpKooTU)lfrCwf8&|^rW#Rqb{rr;@=w<1@j}G#`jQBr` W)S4>TIOvvmz&}YKQ0DyTU;hs=iEWVp literal 0 HcmV?d00001 diff --git a/ipaylinks_statement/statement_files/2018/01/20180131.xlsx b/ipaylinks_statement/statement_files/2018/01/20180131.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..b3a7af81b5491ef0df944b756151e8ef021bc34d GIT binary patch literal 13756 zcmaib1zc2H7cUG03?VUqbT=raD1r_Q4&B`$(jXupAYDo~C>=0$;q_x5WL<#C!s%distInp5#iu1qsGcC$^=ho-+Cchi;v0e{mWM zUL06j_LvQLqHJ?u$+Z3L%+OKnWjh=Eww%znqICQ(_w9GQtE5S4R=OV-JmKNOLizGq1!5rnz2g@p-zjO#Q{wsyFtP&T!-Xtoo|E`%*z zv>}d-`?>(fFFGRNbR=xrNo@o+Ur=Mb`_1TP7P~RC#HtHUDwzkEXk^w4>1YvX8Q<7lAz($2&|?}}eBJ%Eo0 z#14nCFV4)rD`o z$z?)rVtBBkf50Wf;A=$wH%kcz%hV>IWJEYg;!ke)_^AI4mJ;gd3X4c_|!B}6&`%SnoUFOuiuhybv z(!z5|!%Mw95jnMAiWkG!>qH8t$HIsu?}di1s>5i<)|rGFR32j!5()LDQ?XUsKM6PU zwkF+U88gW)lcj&z!kkV1`R;>|w}u8ZK?`5+N;HKD49 zI7fVTi0z4Yf`**Vg1hs06ku#M@blkej2QUV#hTl}{E5AZv5KR;g^ig5a!Rjsro#2w z2tE2WG(CmgYV)_Fc*~L_5#)?u@!(%ZTBacNpYc48W9xm0ZA2sU(eVkGz(G(#C<6n8 zZNZH1&MJ4AWy+&9>uhyfCja&ZZne5v%aIQsV5Br>ZOJ+P=kD7RepAkev;y0h&KJ|O z7lm~S)3aW?KEEOi+|1Sbg zJviCVG2^D4ar=H0r?Bm{H#@L#*txP)Ju7g$m=zPzC~&f5b@oLfrNM4@ZS1(RSpQ;6 zW4qz$?D0ehD{aHevz;DR+xp((owaQ4m;045+!s!lFFVAPY0=xuVFEv;jUk2&I zJomXJXy=4nSLA+8htN)6E-NJWAMGZedU>I)H;HeY_6}`(dY&Bw%=9d}>pf`1zStz$ zZq-=xdrPNg6cpWidt-y)K9_?~vYy9T>2|y`;wam}REzY>dN=;Sl-m6xV~u{U*yf2k z_elD?b@j(CSV~4*YJIcz=Mr_UA>1YNVOHXr!JFmkF#NpH@}4x@w%H^dO67aLX0=kj zHZ=)4G;KE+JYO6yOnsXF^qRW<`Gn1LBf;7<9-$jy1%0YmAEf)JX`c_ANMaho{^nDF~1or>OSG$ajJ9R|xwtve-X2cutKm+YN$iK*oUG{U$%@XB0=*#z8r z;$%dMa1pmI+WGx(c^#a8*%0J^0I%Be9?{=w^KobjU49qjN4u%7F}{1_KEcXQHZ?AM zejSxe`YAW`uY@1=!&PS7RWjOE6L)Hq9w34pU~?Z$-FLfN##9rVH}IxQFaHc$9lt@3>QyxO_x|3C{WkBM|{!ikLx?>N(4)M(QONqRM|nZt~2y) zY;QlWvq+u!F`a9~szl3mpWGxL`A=VemrGA+wV^59LBtroh9 zm2wd$ihpVpQr0!sM0vq-j`AzdsI#Q?#F1q4o!EEX`${wJtkiW$g>O-J1YP+-22ra4 zP*R67?(PNAaB94OUQ5E#@{ozqn>19fmTy^S#8oS?vu3&)55LcYZ0r=G>CV1E1l>gO zJ}z6CF-p45JCF8a@57XY#6Xj91-4$TGu*HRW z#77e-QyoRR&`F|kRw}8y?&h=j;CHK8`>TJr-NLK-o*=u8adssPGa1Y$S(1o$CU=XB zSaas!^t_H9D*Dku3&p6mO>t)|l8J1AkZ&EfmoL_5V3%h*0hg6RB4W=*4)dhUGauOR z9~7os*yAp&^L>A;>pH#nFv}JDergo`1c$Kda735yI)^|eRpNFB+r83cN)E}=Wf4m? zvue#x=Z;&b)#g*78_6<3agnd?6M&v^saIhOJS}}NBon>9@{GXqF&Zj9W}kZn_k1)~ zVQ7iTCMMK4*U2n2{N@1(s5wbdLHtbz^C3r;D0W*Dh1l$f?A#y8%?zOwK(rOI7Z#?+Du z-FxTP_eLk2AG5jmt+WhrDAclCFVo`Tf^kJ0uL;+*CQ7zZzI5zXtG3pe{gdy+0vu9L zGPZlnODM;B$HWX=_$()tN+&wiV&~M?u)~)ii4z|%-%wjt9Y521Gd8la4SO`H*s|Ad zLb>uu<1)IB`!?Rs^%X91eSDH29l2+n*myS|KA{*)CM~geTjEVj&3MbY*op$Tv$`JF zj<@syMg*p6(mfjgC)h5*1`r4vi7I;?s=LbVpV(tOcyW6ik8rg7rxm-Htg|!P#T@I? z@QvxtZoTj(b(45kCW^+EHmiX1;~x7>ZL>j?1M#D(HDgn2v;^6A6hMTjcG%dlJTl)15WmO2uCx zR%mks>E0zn#CN2mEA4l19v1M@N+>>boh%{RO;o)-DR_@F}E zCcG-CuFTECvQ23B*&r$j;sz>7zlfOQODxrNSA&~_MS5PEOgT5@^XEXHX=B>DNK!Dr z_@5}T9S2IWobHzb1w)$LqxGKaex4aorzujXot3?Nkb0l|t=$lUHa;es1 z{p3{D>ALk)l;b>`7&{75X>ay0Eek~dsBq}Mc(YZH=d*OeLA36P&%Q=9pJTQ*a^GsWj4uQs|#wsDntoY6~XK-9H zTqzlmUUpoIQX5n?ENF%A)g;)8tR*0s`g

7ianzm6}%17&j{?HPY2~j zIEz$E8#cn`(iy@>eET;^T+2%D_H0)>q(`G*uAY2Q+6}ZeiSQ4+#U@LC?3Ur3y#X&z=gXezd%_+i3rojJakE$ll`Ks<^LnL{ z)uaCQ=uAR`q-h~{;3BKbSXD{b>%>JvL;5LrGdVcCWZf!G(c!mk(2to2mTxVtk8>P# z;`O7Qo5x9Ln59P=(RUkt`SEz87&J==`Xn89Ol6QPy#~9 zjO}V)w=()Guk)Tve9B;30-f=52t$C==vZN0fs25Rc2#{GrE1KnnwxpCQDBqFF54<=Dq;{L9yGHz1NWM4#`{rR zTu#3i>`Z66?RX;p89&>35S3WQQRdUq#!(%va*_NPQ3S?rpIGZ)`6#)sB$ho#U|c>p z{@bFu?0{zAvg3+lvYb{$UXT7{!Y^xt1to{7z2Fm%H7oN>2%#LWIbYb+h zA4xJg>KJB6l?F^+&%77!F@pGXMC4R%J`a#0*f<1{kCP*+K9Ueen^KMPBt+j@+RnVM zKx$^R*IC>%vAbAFHuW;S@hGuD(c2u)`h4?tj+uFI3`!*ZzFLM&r$+Uz$Ur*LV6U#1 zH{M{Moska~6{8geTByLvOh6biAHGgE|OHL0YYxpogIP(+s=5LM-IaNMzu z6wSj0dWg!UKK|C*Tb#a_e!PSE{-E-)P8ZnlpulNWF}jqhupi?f>eZ9`deabl*L22Z zan}Va_!-^K_wuE)h|ei7D+z&$E*`fhUzIc~7aUGRSH;4fQ0Pr#Q<%w?PQG7MRr>1w z{Z1kE(K=hV6h>Xgp@?O*hn7yL4^@v2`o*aM51ves2K~2f+wZp&_PvFfANhW(qZV+P z8fU29tN+C)aUPbjrS*-eum5{rUvu+9+vU}rXYx~DHvv2p6tL+3y7Rp8`_9wxrM1b` zEoWBD@8>%Y#bSjv?lJi*>flK}P9len6}*@VY%Pk$t$g@MeyH?@PvrdIxYuUC{PeQ3 zAOGTwq%r?jy0_mbqo}J|S>qhn&*;u}*6lJJKDqmI7!}-%^$lm@)z>-Ggkr&xZth&n z<>c2%YCd{nrk|WsEooy4x<-3eUYN#-Yps5)rlhRTHIGP(lu3wt`PfBuln=|~$6Q+? z-?Wx>SPKW=vVS`TMlQ}vB7W7I%EJwOu4{X(D(Z>6T^nq&$$ih&8Ee=~^Q2EadyXfY zxN4fW7Qj5W-@_;4f2ouxt~Ow!QrV0XmN!tlu`xmW;@N+^{ia{!^O*t7rUhwU#P)5bgRPV%i8q>AB?AtdA* zf2k*(I)?ClicigFQ>8-vZb0$QD|x<{x%`-6LJ&5zdj(>+K-hdR@HAu+?SFxYe+{Cu zt-Y0zt*sUE$w63nDe@82Yv=c$Ym+BY{po^-vOWxlrIpkjWR+4(MfF$IgBgpPx<7wL zQ(NS?2mwtNOL^q@ZY>aSe-G47MwbJ34k(KwPjyBGxvjc<|J1 zMbYczuItYBvmFeiZ+`Y^z8(f<&htMXWRm^EAO~|36GsQ&SrqUe?-iAjbsT0!qCTb7cq znkf1g--}Z`ADo^aTr4cjtZA&xIFqiKRj16&Hk=+EpXdL&Jl@{EeBpJGGj_SV8&P+f zLJOOog}r~YlR~SX?B(Kqwm+v|@8WX0a4__x#o4)W*3g=c5Z&sG9xBD$ zq$tDWPPg8AJ(N4xTwbA4UB%W&q0W67px%14b*|c00iIk{qXV8VhMHv zF&2-?a9v=mMnGFjT+0u_$lJE(N6$7o_6wbjBjplNqIL{K8LmdAkD~cWU0P@mp-eR) z8Ote|se=zFKgr|_6_bZah`7$4YytX;0DY9?m*7A|jX$Dx-}~F>V}{#1R9A8+QRUMl zOoN4(h-y!dL6UX`8E3F@zfR+6)qWjPAEOsz3}eQvL+0x~G|(>ECQ1qGjj;@3kv(tx zYx50K9AA}6#xl}T&YqkD3X1`S8R|#g=C6Kt2tYtr!WgUe0e{lDKEwP&s&j63AZiQU z_IzP#^va)w`u%9>qn zF21MaC*t?2U;YdlXmsz+I#me8_O|~{E6l^>?GvEhyvzbi(su1}B{Vq%Po=$ev%!Y4SQ`$-cWG2Wn_@Cp zAroUYa?8?ora5m>TEFq5tne|TAp5QE2`))%MyLc1aH4jbNTamJmcS0Bmj+_cc*A;p zY&2sD;=P(S_kvO48}y-yTq>f5D9T(794ObCGDtCEdtwR3y_=^w!z8%z0xd?cLP*BZ z_33!r@`=1l1?fxB*!$$;P(odsn?6EEmxzsq@i12H(xf4}&4xeX?DHNVWLv1$Z<>|h z6u=GfoSabF`|x~(Btxl*=-wt%gZy{`RRT-PAI}p)p8_(X6cNeP-WJK!H#16bl0=aL z-U6gfu8?U_BU$X&-adSvr}1D8$OJh<$&DahesDWIUZ*@ExU!Eh#BCh?fS#AsDVnac z59$*j8H(i_Jt2meXJqlg7Ih*gj1Ov!rvnKQVj7PTqP!@?32IZ>1gS)kZCS<>l!bIR zX)(2f;awOch`@lLwkA3yrZ* z!ivOUfT$7-rbm|nO`Lr3o^7ZWNY{f+E>o_WDwn(otw3C><`j;ox+;b| zGcOB7+EmPBUKNSp@0P%(yjD~#B`K>J4i3_sGW;ZIqk_}F2Lrd2{(pxzUuyG@B#HA; zkpeiisHsFQ5GR%D%UFgK4B~}@<(c`^RROd)0^0JZK!DL(jqymB=-kM->^PAAqVuBT z`VHNL%5xtT0PZWlho#$VCUw&T!wghK2GMQd)G&2|;XZLv;nTce0POCBSWu`9#MB=;0Po{yS zXv#GorGgamGj-j&>3_2Oe6I{J7VVVoZpyg|txZS5qgcRkk;y!u6aZPoyvm~YW++^7 zBewJ?_VK(5Xvhk`3lUj#i6ko+#>}FU5=}=0MqgJW*f>~JYtqH+rRx2};s+}d>EACI zk9};Y0zz}8OO!YG?DJI|9T=UgGn`axScGPZ$70|oAfcQ3hU#XFJw#U8 zPz29-aAKi3%`ce#CmZiuOZpNvKfqT*p9LMLc^r5SDOw*~{CfH5?PnteJfBBcvfJAx z44t#R#N#n!ovk8~Br(ev@2DVyZrYIVk8bAN5n5cxmw(YhyRkz%{ zBH#d`VgJa67EU`hfLMxrZV?(^WfFjdmnSS0iN#RD>i1oP>Z>|B{A&??VB7oYk5MbW zcG+Vrxmam_*dQP+c=N(V__p+19|OIS%A5s(z(#2Ym%`42(FSpF{V8nsr*T8*KoJ0< ziK#69;y}Jr0@7Tnu@3S#WZVe-Zh}0NruwQ6=t`pxjJXeEDRu`}%OGV0Nf5iU9m{PI zv9jEJ5Fif#LaqsLK;=s`<6Ue?ipZOBkjmihwv1^o&2L|5DUrLx0tuKc0SF`sSO$EvavjyfIY%JN{W#Sa^^`yB4_m z8q72_n{^+cr0-SA@YBD_F*1MWnDN-erfl$)(}0X}{q`T-lL9tRTZ15dc}>TNYp^;ofhnlvKk*R2~4yh^OJeUk+lSBsH-~ zvgD%@)K!to)Tw`m2ADh07};R;(2fJZ(-7mCln@YU934RRK+A!~!>0frSL9wrS{@K- zs-R_Lr2XA=wY+Gn{v|TgZx0u^V@?SW=Vn~&7cgol7AV@{aFFt9Rr3A2(a7WPOm0tg z6PdMm{6vX>)USLG2t`#RzS|tA_E%W`)r2urEI@aggV2&VZfQ|9+(!kgH&sT6{(3P1 zh!ddWpHq}9l7hhM@tc$?ze#!30?L768jCT*k!u)7M^hfy z^eb01)?X_Sn0M0l#?@+UXE~_~q)~$3DP6&MK9^D=aBET328m=dg)zY(BiN*zdl4P! zE=I7(g<3swb&Vj1{Q?Uk6^LuztZorYbBnzZFTj7QBJ&!%Q(Ccc+Cx5 zfG<{Ah|cgEK5$@x21RRe{#C==xT;}ryOA}FaU~l3_URK|wrU?ZRC*uWF!clbL`&sGd6z;&tV&0HfN+&?b_^wzsozn|E&1@ z{;2q-0X2QkZjt)mp#P$BUB#px zc|FhWJGvOey!w?u`)R0ih)xa8w6x*96OK|WdXE%dI9E_pQLD96EMyZ{E9fN?xr*5m zWf*>P`W6R%oxZ|6KJj?-B8PQ-Ea!j4Mnn>2{Z>G zS~d7Up?2@!;(`Bgu!!Wo$YbS4hIAunBG~~Y7;stlcQ175E1#3n)=q8Liz>%we zHNXLnx;VO1Cr-F$C}dN*H+#zg<(T)XW-#MpOQdB4HS)!KwGk#TK`f~mZ#LS~9>q0T zZ*CMqCU`->sNmPk7-dfphMGXdfL`_(@l}}|D4%}2p@!yWojvV1Ah5R|LnLa6AXp9v zM8acroqv=!-^J>@J(d$1qQvZPlEa+iQnevc{HZvo2Kn5Cg#XDY3cBHm)KEqYR1OC7( zk3G6&x&q_j^qDX(-u91tHwLbu0qOy?1mN?^sPFVVoIs^%3RIdMaY2uUTAuK7;`?X; z;p|#WICziTcQY1_!Xm~*)kr~DZ;g=^5Xe)jQ_5`M~ z@kv}#fgG~W5tLd3CDXYCY8fV9kymt&5a6o}yUEFwLBmL3DL@#|R`~E^4p0J`W*CU1 z5Db<<0j}V7ffsNgAUY!8#*e_*SJMnx2Adi@C*Sv=hwx8#x0FB_?10&fW6q;eY@z)m z>jD#gjBD}+Sb@Bc1IjrCud70Pk?$QH#1hMBhXdb71FP5Ez(+!|5rj_wVfe}6g9-=h z0}%iyfYf(;C-_Zh=voPx5DW{N0Nw%|;zPcF?2kn+Wa90y>WjQ{5h1vWW@KGv)^u%A z;T8la{voBBaRE&qz^20z+$_F(QUNmFKwmX1TnIx6aNG9^n24bo1`_i{?R@7j#g;nQ zE&UaGzy|XD7q^K-*Y(iAfDu<3G=O}8)X?vFJp=6s4u~&BSQT(%_7GX{WWdyU=`#c9_0n;eBQlfUP z1eAY85|Xh=piHC?GjT4Bk2APv;K1^2*WZxNt|(#ZR`Y35)*@K06_I{L_=-a^?=JM4 zpwFr?AxClTn|N7%%ibU9LIVN_{m~aO2HVV?!#LMk*OkyjEf-@RyQD!Nb`~kxrzE zL>^!mD?Gzf*U(5hL^)lO)@MwL;5(z8P=+Ep` z0X9`QF!PTYSa(@N6km>1#>M2dbB5K1oCm=`5wWQQpN5-b53C5qP9W~ezQ9COC;%{O zV4(85zrpwf3d?I3`dS;(0!Z}4rYfa0B*qU0LjEi8z!& zNHp|-7ZUkKT%L=KB_HMJEvA6(PC7q~AG|O~7ooj-YY0;$6+c~;RtiAyJEM2eZ|82D zmc(1`ft+W8ye641*hMm63Ie=Y+~st^dr?O@C{Zxza3k#GlT@0$aFN%dD zEk|gP0yU)=0Ol3jf;=W`q^Xj$Jh#RI9%tgG>e9lIJb6l8E1&v6%Re~3s9%C6!ScPq zYa(DAK#9ku58z_N1^bPjeZu1$L=BALGL{X%B?aReLBPdIUw-xcZIrtJ@5bT5 zPW*CB&z~=*H~}5Lnn&dGnp|KiW=6CMqX#0Vj`Y(8Aclry`l74rF99+4$Zfw1@;)G%)EQ2^2lnYqwVa!cm+G89mMtE>$>f zg`t~U^~3qDu?zA*x~cTHn~eSfqWSnKf#@wHh^CAzeDQ7~_N z4{#c`a#6&KzYI5|<%H+JlOmzXkLI9f0=cUuYk=peYx2Q2sUb zssqK_Do*F1|0V!F9&(W7--!6_sj8FE?bg^a+W%_M^G9&niu;8Jr56C3hyXSfhC2e- zZKDC$odIYAoVr3A85~z=7uEJ{cdBk2czP|S93c6mu3`H>1&V8rb0jOzhW=LIp&Z3t z*MJ|}r~nOEIZ5?*8v=rXB@J8Uq`^kk+%^u;O%g4TEA@#n+{65VaZ8Y&AQK)3;97`_ zQ8yJ|stEnvTPhG1Dph)s8qsLQS9xI^{?J;{K)zSt9>olI37R^Z$NCT5KQ?&O*T1ZP zdA>WAcv!u^dU4*-k8dVC`v^Ac;rhaJXXfp;%Y~!!p^Mw)N>0wkDt`6-?N8@Fd$trJ z4Dx=JpGIs8pItW6ZhM}0Y=3g;-szY*?>G2We?f`dKRlomBs-x*K@r7A1zuoB1rekC zbI|6`10=|UHvjkaAIEO~E&k^j3*;%2e=bpABlnLpC;t}w^NaxU2*y8`KCsLA|2UBG z?*aaND<653;Gb&@*l7RT@ZSdu{w@9In-$16_y4)FfkO-bulM->J;I;c`p7ph{<-LY z`5;I5`+bami~hOSjokPD=UM@50Yv}Y+5WfipPRwR?eKptoSRp||7COh-{bsA3gp)D fKNlQ7Vu9P0LttR@~{5`nfn+` literal 0 HcmV?d00001 diff --git a/webht/config/config.php b/webht/config/config.php index c3620ebb..ea305f7b 100644 --- a/webht/config/config.php +++ b/webht/config/config.php @@ -180,7 +180,7 @@ $config['directory_trigger'] = 'd'; // experimental not currently in use | your log files will fill up very fast. | */ -$config['log_threshold'] = 0; +$config['log_threshold'] = 1; /* |-------------------------------------------------------------------------- @@ -377,4 +377,4 @@ $config['site'] = array( 'mbj' => array('site_code' => 'mbj', 'site_id' => 98, 'site_lgc' => '1', 'site_url' => 'http://www.mybeijingchina.com'), 'ct' => array('site_code' => 'ct', 'site_id' => 1000, 'site_lgc' => '104', 'site_url' => 'http://www.chinatravel.com'), 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'http://www.diychinatours.com') -); \ No newline at end of file +); diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 3c3ab578..866eb72e 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -387,8 +387,8 @@ class IPayLinksService extends CI_Controller //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { - $item->IPL_currencyCode = trim($item->IPL_currencyCode); - $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, mb_strtoupper($item->IPL_currencyCode)); + $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->IPL_currencyCode))); + $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; @@ -406,7 +406,7 @@ class IPayLinksService extends CI_Controller $advisor_info->COLI_ID, $item->IPL_orderAmount, $item->IPL_completeTime, - mb_strtoupper($item->IPL_currencyCode), + $currencyCode, $ssje, $item->IPL_completeTime, $item->IPL_completeTime, @@ -428,7 +428,7 @@ class IPayLinksService extends CI_Controller $GAI_COLI_SN, $item->IPL_orderAmount, $item->IPL_acquiringTime, - mb_strtoupper($item->IPL_currencyCode), + $currencyCode, $ssje, $item->IPL_completeTime, $item->IPL_completeTime, @@ -1054,4 +1054,145 @@ class IPayLinksService extends CI_Controller return $query_resp->data->refundDetails->detail; } + public function auto_update_statement() + { + $target_folder = date("Y-m", strtotime("-1 day")); + $target_folder = str_replace("-", "\\", $target_folder); + $today_time = strtotime(date('Ymd000000')); + // 解析excel + $statement_folder = FCPATH.'ipaylinks_statement\statement_files\\' . $target_folder; + if ( ! is_dir($statement_folder)) { + return; + } + $files = array_values(array_diff(scandir($statement_folder), array('.', '..'))); + if (empty($files)) { + echo "none excel."; + return; + } + $settle_cnt = 0; + $update_cnt = 0; + bcscale(4); + // 仅处理今天新增的新文件 + foreach ($files as $k => $fe) { + $file_path = $statement_folder . '\\' . $fe; + $modify_time = filemtime($file_path); + if ($modify_time < $today_time) { + continue; + } + $settlement_record = $this->read_excel($file_path); + if (empty($settlement_record)) { + continue; + } + foreach ($settlement_record as $settle) { + // old data + $orderid_info = $this->analysis_orderid(trim($settle['orderid'])); + $orderid_info = json_decode($orderid_info); + if (empty($orderid_info)) { + continue; + } + if (strcasecmp($orderid_info->ordertype, "B") === 0) { + $old_info = $this->IPayLinks_model->get_money_b(trim($settle['pn_invoice'])); + } else if (strcasecmp($orderid_info->ordertype, "T") === 0){ + $old_info = $this->IPayLinks_model->get_money_t(trim($settle['pn_invoice'])); + } # 没有重复的交易号, 不处理了 + if (empty($old_info)) { + continue; + } + $entry_sum_RMB = $entry_sum = bcadd(floatval($settle['entry_security']), floatval($settle['entry_basic'])); + if (strcasecmp(trim($settle['entry_currency']), "CNY")) { + $entry_sum_RMB = $this->cal_ssje($entry_sum, trim($settle['entry_currency'])); + } + $warrant["PW_GAI_AccreditNo"] = trim($settle['pn_invoice']); + $warrant["PW_GAI_Type"] = 15018; + $warrant["PW_entry_currency"] = trim($settle['entry_currency']); + $warrant["PW_entry_amount"] = $entry_sum; + $warrant["PW_GAI_SSJE_new"] = $entry_sum_RMB; + $warrant["PW_COLI_SN"] = $old_info[0]->GAI_COLI_SN; + $warrant["PW_GAI_SQJECurrency_pre"] = $old_info[0]->GAI_SQJECurrency; + $warrant["PW_GAI_SSJE_pre"] = $old_info[0]->GAI_SSJE; + $warrant["PW_orderType"] = $orderid_info->ordertype; + $this->Note_model->new_warrant($warrant); + if (strcasecmp($orderid_info->ordertype, "B") === 0) { + $this->IPayLinks_model + ->update_money_b($entry_sum_RMB, trim($settle['pn_invoice'])); + } else if (strcasecmp($orderid_info->ordertype, "T") === 0){ + $this->IPayLinks_model + ->update_money_t($entry_sum_RMB, trim($settle['pn_invoice'])); + } + $warrant = NULL; + $update_cnt++; + } + $settlement_record = null; // reset + $settle_cnt++; + } + echo "Found $settle_cnt Excels; Updated $update_cnt records;"; + return; + } + + public function read_excel($filePath) + { + $tarr1=array(); + $this->load->library('PHPExcel'); + $PHPExcel = new PHPExcel(); + /**默认用excel2007读取excel,若格式不对,则用之前的版本进行读取*/ + $PHPReader = new PHPExcel_Reader_Excel2007(); + if(!$PHPReader->canRead($filePath)){ + $PHPReader = new PHPExcel_Reader_Excel5(); + if(!$PHPReader->canRead($filePath)){ + echo 'no Excel'; + return ; + } + } + $PHPExcel = $PHPReader->load($filePath); + /**读取excel文件中的第一个工作表*/ + $currentSheet = $PHPExcel->getSheet(0); + + /**取得最大的列号*/ + $allColumn = $currentSheet->getHighestColumn(); + + /**取得一共有多少行*/ + $allRow = $currentSheet->getHighestRow(); + /**从第二行开始输出,因为excel表中第一行为列名*/ + for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ + $row_tmp = array(); + /**从第A列开始输出*/ + for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){ + /**ord()将字符转为十进制数*/ + $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue(); + $col_mean = $this->col_title()[$currentColumn]; + if($col_mean == 'data_type' && strcasecmp('清算', $val) !== 0) + { + break; + } + if ($col_mean == 'settlement_amount' && floatval($val) <= 0) { + break; + } + $row_tmp[$col_mean] = $val; + } + if (isset($row_tmp['settlement_amount'])) { + $tarr1[] = $row_tmp; + } + } + return $tarr1; + } + public function col_title() + { + return array( + "A" => "complete_date", + "B" => "pn_invoice", + "C" => "orderid", + "D" => "data_type", + "E" => "currency", + "F" => "order_amount", + "G" => "settlement_rate", + "H" => "settlement_amount", + "I" => "service_fee", + "J" => "transaction_fee", + "K" => "mark_memo", + "L" => "entry_currency", + "M" => "entry_security", + "N" => "entry_basic" + ); + } + } diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel.php new file mode 100644 index 00000000..bf6f60f5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel.php @@ -0,0 +1,1139 @@ +_hasMacros; + } + + /** + * Define if a workbook has macros + * + * @param true|false + */ + public function setHasMacros($hasMacros=false){ + $this->_hasMacros=(bool)$hasMacros; + } + + /** + * Set the macros code + * + * @param binary string|null + */ + public function setMacrosCode($MacrosCode){ + $this->_macrosCode=$MacrosCode; + $this->setHasMacros(!is_null($MacrosCode)); + } + + /** + * Return the macros code + * + * @return binary|null + */ + public function getMacrosCode(){ + return $this->_macrosCode; + } + + /** + * Set the macros certificate + * + * @param binary|null + */ + public function setMacrosCertificate($Certificate=NULL){ + $this->_macrosCertificate=$Certificate; + } + + /** + * Is the project signed ? + * + * @return true|false + */ + public function hasMacrosCertificate(){ + return !is_null($this->_macrosCertificate); + } + + /** + * Return the macros certificate + * + * @return binary|null + */ + public function getMacrosCertificate(){ + return $this->_macrosCertificate; + } + + /** + * Remove all macros, certificate from spreadsheet + * + * @param none + * @return void + */ + public function discardMacros(){ + $this->_hasMacros=false; + $this->_macrosCode=NULL; + $this->_macrosCertificate=NULL; + } + + /** + * set ribbon XML data + * + */ + public function setRibbonXMLData($Target=NULL, $XMLData=NULL){ + if(!is_null($Target) && !is_null($XMLData)){ + $this->_ribbonXMLData=array('target'=>$Target, 'data'=>$XMLData); + }else{ + $this->_ribbonXMLData=NULL; + } + } + + /** + * retrieve ribbon XML Data + * + * return string|null|array + */ + public function getRibbonXMLData($What='all'){//we need some constants here... + $ReturnData=NULL; + $What=strtolower($What); + switch($What){ + case 'all': + $ReturnData=$this->_ribbonXMLData; + break; + case 'target': + case 'data': + if(is_array($this->_ribbonXMLData) && array_key_exists($What,$this->_ribbonXMLData)){ + $ReturnData=$this->_ribbonXMLData[$What]; + }//else $ReturnData stay at null + break; + }//default: $ReturnData at null + return $ReturnData; + } + + /** + * store binaries ribbon objects (pictures) + * + */ + public function setRibbonBinObjects($BinObjectsNames=NULL, $BinObjectsData=NULL){ + if(!is_null($BinObjectsNames) && !is_null($BinObjectsData)){ + $this->_ribbonBinObjects=array('names'=>$BinObjectsNames, 'data'=>$BinObjectsData); + }else{ + $this->_ribbonBinObjects=NULL; + } + } + /** + * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function) + * + */ + private function _getExtensionOnly($ThePath){ + return pathinfo($ThePath, PATHINFO_EXTENSION); + } + + /** + * retrieve Binaries Ribbon Objects + * + */ + public function getRibbonBinObjects($What='all'){ + $ReturnData=NULL; + $What=strtolower($What); + switch($What){ + case 'all': + return $this->_ribbonBinObjects; + break; + case 'names': + case 'data': + if(is_array($this->_ribbonBinObjects) && array_key_exists($What, $this->_ribbonBinObjects)){ + $ReturnData=$this->_ribbonBinObjects[$What]; + } + break; + case 'types': + if(is_array($this->_ribbonBinObjects) && array_key_exists('data', $this->_ribbonBinObjects) && is_array($this->_ribbonBinObjects['data'])){ + $tmpTypes=array_keys($this->_ribbonBinObjects['data']); + $ReturnData=array_unique(array_map(array($this,'_getExtensionOnly'), $tmpTypes)); + }else + $ReturnData=array();//the caller want an array... not null if empty + break; + } + return $ReturnData; + } + + /** + * This workbook have a custom UI ? + * + * @return true|false + */ + public function hasRibbon(){ + return !is_null($this->_ribbonXMLData); + } + + /** + * This workbook have additionnal object for the ribbon ? + * + * @return true|false + */ + public function hasRibbonBinObjects(){ + return !is_null($this->_ribbonBinObjects); + } + + /** + * Check if a sheet with a specified code name already exists + * + * @param string $pSheetCodeName Name of the worksheet to check + * @return boolean + */ + public function sheetCodeNameExists($pSheetCodeName) + { + return ($this->getSheetByCodeName($pSheetCodeName) !== NULL); + } + + /** + * Get sheet by code name. Warning : sheet don't have always a code name ! + * + * @param string $pName Sheet name + * @return PHPExcel_Worksheet + */ + public function getSheetByCodeName($pName = '') + { + $worksheetCount = count($this->_workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + if ($this->_workSheetCollection[$i]->getCodeName() == $pName) { + return $this->_workSheetCollection[$i]; + } + } + + return null; + } + + /** + * Create a new PHPExcel with one Worksheet + */ + public function __construct() + { + $this->_uniqueID = uniqid(); + $this->_calculationEngine = PHPExcel_Calculation::getInstance($this); + + // Initialise worksheet collection and add one worksheet + $this->_workSheetCollection = array(); + $this->_workSheetCollection[] = new PHPExcel_Worksheet($this); + $this->_activeSheetIndex = 0; + + // Create document properties + $this->_properties = new PHPExcel_DocumentProperties(); + + // Create document security + $this->_security = new PHPExcel_DocumentSecurity(); + + // Set named ranges + $this->_namedRanges = array(); + + // Create the cellXf supervisor + $this->_cellXfSupervisor = new PHPExcel_Style(true); + $this->_cellXfSupervisor->bindParent($this); + + // Create the default style + $this->addCellXf(new PHPExcel_Style); + $this->addCellStyleXf(new PHPExcel_Style); + } + + /** + * Code to execute when this worksheet is unset() + * + */ + public function __destruct() { + PHPExcel_Calculation::unsetInstance($this); + $this->disconnectWorksheets(); + } // function __destruct() + + /** + * Disconnect all worksheets from this PHPExcel workbook object, + * typically so that the PHPExcel object can be unset + * + */ + public function disconnectWorksheets() + { + $worksheet = NULL; + foreach($this->_workSheetCollection as $k => &$worksheet) { + $worksheet->disconnectCells(); + $this->_workSheetCollection[$k] = null; + } + unset($worksheet); + $this->_workSheetCollection = array(); + } + + /** + * Return the calculation engine for this worksheet + * + * @return PHPExcel_Calculation + */ + public function getCalculationEngine() + { + return $this->_calculationEngine; + } // function getCellCacheController() + + /** + * Get properties + * + * @return PHPExcel_DocumentProperties + */ + public function getProperties() + { + return $this->_properties; + } + + /** + * Set properties + * + * @param PHPExcel_DocumentProperties $pValue + */ + public function setProperties(PHPExcel_DocumentProperties $pValue) + { + $this->_properties = $pValue; + } + + /** + * Get security + * + * @return PHPExcel_DocumentSecurity + */ + public function getSecurity() + { + return $this->_security; + } + + /** + * Set security + * + * @param PHPExcel_DocumentSecurity $pValue + */ + public function setSecurity(PHPExcel_DocumentSecurity $pValue) + { + $this->_security = $pValue; + } + + /** + * Get active sheet + * + * @return PHPExcel_Worksheet + */ + public function getActiveSheet() + { + return $this->_workSheetCollection[$this->_activeSheetIndex]; + } + + /** + * Create sheet and add it to this workbook + * + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function createSheet($iSheetIndex = NULL) + { + $newSheet = new PHPExcel_Worksheet($this); + $this->addSheet($newSheet, $iSheetIndex); + return $newSheet; + } + + /** + * Check if a sheet with a specified name already exists + * + * @param string $pSheetName Name of the worksheet to check + * @return boolean + */ + public function sheetNameExists($pSheetName) + { + return ($this->getSheetByName($pSheetName) !== NULL); + } + + /** + * Add sheet + * + * @param PHPExcel_Worksheet $pSheet + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function addSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = NULL) + { + if ($this->sheetNameExists($pSheet->getTitle())) { + throw new PHPExcel_Exception( + "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first." + ); + } + + if($iSheetIndex === NULL) { + if ($this->_activeSheetIndex < 0) { + $this->_activeSheetIndex = 0; + } + $this->_workSheetCollection[] = $pSheet; + } else { + // Insert the sheet at the requested index + array_splice( + $this->_workSheetCollection, + $iSheetIndex, + 0, + array($pSheet) + ); + + // Adjust active sheet index if necessary + if ($this->_activeSheetIndex >= $iSheetIndex) { + ++$this->_activeSheetIndex; + } + } + + if ($pSheet->getParent() === null) { + $pSheet->rebindParent($this); + } + + return $pSheet; + } + + /** + * Remove sheet by index + * + * @param int $pIndex Active sheet index + * @throws PHPExcel_Exception + */ + public function removeSheetByIndex($pIndex = 0) + { + + $numSheets = count($this->_workSheetCollection); + + if ($pIndex > $numSheets - 1) { + throw new PHPExcel_Exception( + "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + ); + } else { + array_splice($this->_workSheetCollection, $pIndex, 1); + } + // Adjust active sheet index if necessary + if (($this->_activeSheetIndex >= $pIndex) && + ($pIndex > count($this->_workSheetCollection) - 1)) { + --$this->_activeSheetIndex; + } + + } + + /** + * Get sheet by index + * + * @param int $pIndex Sheet index + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function getSheet($pIndex = 0) + { + + $numSheets = count($this->_workSheetCollection); + + if ($pIndex > $numSheets - 1) { + throw new PHPExcel_Exception( + "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}." + ); + } else { + return $this->_workSheetCollection[$pIndex]; + } + } + + /** + * Get all sheets + * + * @return PHPExcel_Worksheet[] + */ + public function getAllSheets() + { + return $this->_workSheetCollection; + } + + /** + * Get sheet by name + * + * @param string $pName Sheet name + * @return PHPExcel_Worksheet + */ + public function getSheetByName($pName = '') + { + $worksheetCount = count($this->_workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + if ($this->_workSheetCollection[$i]->getTitle() === $pName) { + return $this->_workSheetCollection[$i]; + } + } + + return NULL; + } + + /** + * Get index for sheet + * + * @param PHPExcel_Worksheet $pSheet + * @return Sheet index + * @throws PHPExcel_Exception + */ + public function getIndex(PHPExcel_Worksheet $pSheet) + { + foreach ($this->_workSheetCollection as $key => $value) { + if ($value->getHashCode() == $pSheet->getHashCode()) { + return $key; + } + } + + throw new PHPExcel_Exception("Sheet does not exist."); + } + + /** + * Set index for sheet by sheet name. + * + * @param string $sheetName Sheet name to modify index for + * @param int $newIndex New index for the sheet + * @return New sheet index + * @throws PHPExcel_Exception + */ + public function setIndexByName($sheetName, $newIndex) + { + $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); + $pSheet = array_splice( + $this->_workSheetCollection, + $oldIndex, + 1 + ); + array_splice( + $this->_workSheetCollection, + $newIndex, + 0, + $pSheet + ); + return $newIndex; + } + + /** + * Get sheet count + * + * @return int + */ + public function getSheetCount() + { + return count($this->_workSheetCollection); + } + + /** + * Get active sheet index + * + * @return int Active sheet index + */ + public function getActiveSheetIndex() + { + return $this->_activeSheetIndex; + } + + /** + * Set active sheet index + * + * @param int $pIndex Active sheet index + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setActiveSheetIndex($pIndex = 0) + { + $numSheets = count($this->_workSheetCollection); + + if ($pIndex > $numSheets - 1) { + throw new PHPExcel_Exception( + "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + ); + } else { + $this->_activeSheetIndex = $pIndex; + } + return $this->getActiveSheet(); + } + + /** + * Set active sheet index by name + * + * @param string $pValue Sheet title + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function setActiveSheetIndexByName($pValue = '') + { + if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) { + $this->setActiveSheetIndex($this->getIndex($worksheet)); + return $worksheet; + } + + throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue); + } + + /** + * Get sheet names + * + * @return string[] + */ + public function getSheetNames() + { + $returnValue = array(); + $worksheetCount = $this->getSheetCount(); + for ($i = 0; $i < $worksheetCount; ++$i) { + $returnValue[] = $this->getSheet($i)->getTitle(); + } + + return $returnValue; + } + + /** + * Add external sheet + * + * @param PHPExcel_Worksheet $pSheet External sheet to add + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) { + if ($this->sheetNameExists($pSheet->getTitle())) { + throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); + } + + // count how many cellXfs there are in this workbook currently, we will need this below + $countCellXfs = count($this->_cellXfCollection); + + // copy all the shared cellXfs from the external workbook and append them to the current + foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { + $this->addCellXf(clone $cellXf); + } + + // move sheet to this workbook + $pSheet->rebindParent($this); + + // update the cellXfs + foreach ($pSheet->getCellCollection(false) as $cellID) { + $cell = $pSheet->getCell($cellID); + $cell->setXfIndex( $cell->getXfIndex() + $countCellXfs ); + } + + return $this->addSheet($pSheet, $iSheetIndex); + } + + /** + * Get named ranges + * + * @return PHPExcel_NamedRange[] + */ + public function getNamedRanges() { + return $this->_namedRanges; + } + + /** + * Add named range + * + * @param PHPExcel_NamedRange $namedRange + * @return PHPExcel + */ + public function addNamedRange(PHPExcel_NamedRange $namedRange) { + if ($namedRange->getScope() == null) { + // global scope + $this->_namedRanges[$namedRange->getName()] = $namedRange; + } else { + // local scope + $this->_namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange; + } + return true; + } + + /** + * Get named range + * + * @param string $namedRange + * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope + * @return PHPExcel_NamedRange|null + */ + public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) { + $returnValue = null; + + if ($namedRange != '' && ($namedRange !== NULL)) { + // first look for global defined name + if (isset($this->_namedRanges[$namedRange])) { + $returnValue = $this->_namedRanges[$namedRange]; + } + + // then look for local defined name (has priority over global defined name if both names exist) + if (($pSheet !== NULL) && isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { + $returnValue = $this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange]; + } + } + + return $returnValue; + } + + /** + * Remove named range + * + * @param string $namedRange + * @param PHPExcel_Worksheet|null $pSheet Scope: use null for global scope. + * @return PHPExcel + */ + public function removeNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) { + if ($pSheet === NULL) { + if (isset($this->_namedRanges[$namedRange])) { + unset($this->_namedRanges[$namedRange]); + } + } else { + if (isset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { + unset($this->_namedRanges[$pSheet->getTitle() . '!' . $namedRange]); + } + } + return $this; + } + + /** + * Get worksheet iterator + * + * @return PHPExcel_WorksheetIterator + */ + public function getWorksheetIterator() { + return new PHPExcel_WorksheetIterator($this); + } + + /** + * Copy workbook (!= clone!) + * + * @return PHPExcel + */ + public function copy() { + $copied = clone $this; + + $worksheetCount = count($this->_workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + $this->_workSheetCollection[$i] = $this->_workSheetCollection[$i]->copy(); + $this->_workSheetCollection[$i]->rebindParent($this); + } + + return $copied; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + foreach($this as $key => $val) { + if (is_object($val) || (is_array($val))) { + $this->{$key} = unserialize(serialize($val)); + } + } + } + + /** + * Get the workbook collection of cellXfs + * + * @return PHPExcel_Style[] + */ + public function getCellXfCollection() + { + return $this->_cellXfCollection; + } + + /** + * Get cellXf by index + * + * @param int $pIndex + * @return PHPExcel_Style + */ + public function getCellXfByIndex($pIndex = 0) + { + return $this->_cellXfCollection[$pIndex]; + } + + /** + * Get cellXf by hash code + * + * @param string $pValue + * @return PHPExcel_Style|false + */ + public function getCellXfByHashCode($pValue = '') + { + foreach ($this->_cellXfCollection as $cellXf) { + if ($cellXf->getHashCode() == $pValue) { + return $cellXf; + } + } + return false; + } + + /** + * Check if style exists in style collection + * + * @param PHPExcel_Style $pCellStyle + * @return boolean + */ + public function cellXfExists($pCellStyle = null) + { + return in_array($pCellStyle, $this->_cellXfCollection, true); + } + + /** + * Get default style + * + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getDefaultStyle() + { + if (isset($this->_cellXfCollection[0])) { + return $this->_cellXfCollection[0]; + } + throw new PHPExcel_Exception('No default style found for this workbook'); + } + + /** + * Add a cellXf to the workbook + * + * @param PHPExcel_Style $style + */ + public function addCellXf(PHPExcel_Style $style) + { + $this->_cellXfCollection[] = $style; + $style->setIndex(count($this->_cellXfCollection) - 1); + } + + /** + * Remove cellXf by index. It is ensured that all cells get their xf index updated. + * + * @param int $pIndex Index to cellXf + * @throws PHPExcel_Exception + */ + public function removeCellXfByIndex($pIndex = 0) + { + if ($pIndex > count($this->_cellXfCollection) - 1) { + throw new PHPExcel_Exception("CellXf index is out of bounds."); + } else { + // first remove the cellXf + array_splice($this->_cellXfCollection, $pIndex, 1); + + // then update cellXf indexes for cells + foreach ($this->_workSheetCollection as $worksheet) { + foreach ($worksheet->getCellCollection(false) as $cellID) { + $cell = $worksheet->getCell($cellID); + $xfIndex = $cell->getXfIndex(); + if ($xfIndex > $pIndex ) { + // decrease xf index by 1 + $cell->setXfIndex($xfIndex - 1); + } else if ($xfIndex == $pIndex) { + // set to default xf index 0 + $cell->setXfIndex(0); + } + } + } + } + } + + /** + * Get the cellXf supervisor + * + * @return PHPExcel_Style + */ + public function getCellXfSupervisor() + { + return $this->_cellXfSupervisor; + } + + /** + * Get the workbook collection of cellStyleXfs + * + * @return PHPExcel_Style[] + */ + public function getCellStyleXfCollection() + { + return $this->_cellStyleXfCollection; + } + + /** + * Get cellStyleXf by index + * + * @param int $pIndex + * @return PHPExcel_Style + */ + public function getCellStyleXfByIndex($pIndex = 0) + { + return $this->_cellStyleXfCollection[$pIndex]; + } + + /** + * Get cellStyleXf by hash code + * + * @param string $pValue + * @return PHPExcel_Style|false + */ + public function getCellStyleXfByHashCode($pValue = '') + { + foreach ($this->_cellXfStyleCollection as $cellStyleXf) { + if ($cellStyleXf->getHashCode() == $pValue) { + return $cellStyleXf; + } + } + return false; + } + + /** + * Add a cellStyleXf to the workbook + * + * @param PHPExcel_Style $pStyle + */ + public function addCellStyleXf(PHPExcel_Style $pStyle) + { + $this->_cellStyleXfCollection[] = $pStyle; + $pStyle->setIndex(count($this->_cellStyleXfCollection) - 1); + } + + /** + * Remove cellStyleXf by index + * + * @param int $pIndex + * @throws PHPExcel_Exception + */ + public function removeCellStyleXfByIndex($pIndex = 0) + { + if ($pIndex > count($this->_cellStyleXfCollection) - 1) { + throw new PHPExcel_Exception("CellStyleXf index is out of bounds."); + } else { + array_splice($this->_cellStyleXfCollection, $pIndex, 1); + } + } + + /** + * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells + * and columns in the workbook + */ + public function garbageCollect() + { + // how many references are there to each cellXf ? + $countReferencesCellXf = array(); + foreach ($this->_cellXfCollection as $index => $cellXf) { + $countReferencesCellXf[$index] = 0; + } + + foreach ($this->getWorksheetIterator() as $sheet) { + + // from cells + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + ++$countReferencesCellXf[$cell->getXfIndex()]; + } + + // from row dimensions + foreach ($sheet->getRowDimensions() as $rowDimension) { + if ($rowDimension->getXfIndex() !== null) { + ++$countReferencesCellXf[$rowDimension->getXfIndex()]; + } + } + + // from column dimensions + foreach ($sheet->getColumnDimensions() as $columnDimension) { + ++$countReferencesCellXf[$columnDimension->getXfIndex()]; + } + } + + // remove cellXfs without references and create mapping so we can update xfIndex + // for all cells and columns + $countNeededCellXfs = 0; + foreach ($this->_cellXfCollection as $index => $cellXf) { + if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf + ++$countNeededCellXfs; + } else { + unset($this->_cellXfCollection[$index]); + } + $map[$index] = $countNeededCellXfs - 1; + } + $this->_cellXfCollection = array_values($this->_cellXfCollection); + + // update the index for all cellXfs + foreach ($this->_cellXfCollection as $i => $cellXf) { + $cellXf->setIndex($i); + } + + // make sure there is always at least one cellXf (there should be) + if (empty($this->_cellXfCollection)) { + $this->_cellXfCollection[] = new PHPExcel_Style(); + } + + // update the xfIndex for all cells, row dimensions, column dimensions + foreach ($this->getWorksheetIterator() as $sheet) { + + // for all cells + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + $cell->setXfIndex( $map[$cell->getXfIndex()] ); + } + + // for all row dimensions + foreach ($sheet->getRowDimensions() as $rowDimension) { + if ($rowDimension->getXfIndex() !== null) { + $rowDimension->setXfIndex( $map[$rowDimension->getXfIndex()] ); + } + } + + // for all column dimensions + foreach ($sheet->getColumnDimensions() as $columnDimension) { + $columnDimension->setXfIndex( $map[$columnDimension->getXfIndex()] ); + } + + // also do garbage collection for all the sheets + $sheet->garbageCollect(); + } + } + + /** + * Return the unique ID value assigned to this spreadsheet workbook + * + * @return string + */ + public function getID() { + return $this->_uniqueID; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php new file mode 100644 index 00000000..a36dfcc9 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php @@ -0,0 +1,85 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + if (!apc_store($this->_cachePrefix.$this->_currentObjectID.'.cache',serialize($this->_currentObject),$this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in APC'); + } + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @access public + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + $this->_cellCache[$pCoord] = true; + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @access public + * @param string $pCoord Coordinate address of the cell to check + * @return void + * @return boolean + */ + public function isDataSet($pCoord) { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->_currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in apc + $success = apc_fetch($this->_cachePrefix.$pCoord.'.cache'); + if ($success === FALSE) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); + } + return true; + } + return false; + } // function isDataSet() + + + /** + * Get cell at a specific coordinate + * + * @access public + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (parent::isDataSet($pCoord)) { + $obj = apc_fetch($this->_cachePrefix.$pCoord.'.cache'); + if ($obj === FALSE) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Delete a cell in cache identified by coordinate address + * + * @access public + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + // Delete the entry from APC + apc_delete($this->_cachePrefix.$pCoord.'.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } // function deleteCacheData() + + + /** + * Clone the cell collection + * + * @access public + * @param PHPExcel_Worksheet $parent The new worksheet + * @throws PHPExcel_Exception + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->_getUniqueID(); + $newCachePrefix = substr(md5($baseUnique),0,8).'.'; + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + if ($cellID != $this->_currentObjectID) { + $obj = apc_fetch($this->_cachePrefix.$cellID.'.cache'); + if ($obj === FALSE) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in APC'); + } + if (!apc_store($newCachePrefix.$cellID.'.cache',$obj,$this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in APC'); + } + } + } + $this->_cachePrefix = $newCachePrefix; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if ($this->_currentObject !== NULL) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + + // Flush the APC cache + $this->__destruct(); + + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) { + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if ($this->_cachePrefix === NULL) { + $baseUnique = $this->_getUniqueID(); + $this->_cachePrefix = substr(md5($baseUnique),0,8).'.'; + $this->_cacheTime = $cacheTime; + + parent::__construct($parent); + } + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + apc_delete($this->_cachePrefix.$cellID.'.cache'); + } + } // function __destruct() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!function_exists('apc_store')) { + return FALSE; + } + if (apc_sma_info() === FALSE) { + return FALSE; + } + + return TRUE; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php new file mode 100644 index 00000000..84a0416c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php @@ -0,0 +1,347 @@ +_parent = $parent; + } // function __construct() + + + /** + * Return the parent worksheet for this cell collection + * + * @return PHPExcel_Worksheet + */ + public function getParent() + { + return $this->_parent; + } + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return true; + } + // Check if the requested entry exists in the cache + return isset($this->_cellCache[$pCoord]); + } // function isDataSet() + + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) { + if ($fromAddress === $this->_currentObjectID) { + $this->_currentObjectID = $toAddress; + } + $this->_currentCellIsDirty = true; + if (isset($this->_cellCache[$fromAddress])) { + $this->_cellCache[$toAddress] = &$this->_cellCache[$fromAddress]; + unset($this->_cellCache[$fromAddress]); + } + + return TRUE; + } // function moveCell() + + + /** + * Add or Update a cell in cache + * + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function updateCacheData(PHPExcel_Cell $cell) { + return $this->addCacheData($cell->getCoordinate(),$cell); + } // function updateCacheData() + + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + $this->_currentObject->detach(); + $this->_currentObjectID = $this->_currentObject = null; + } + + if (is_object($this->_cellCache[$pCoord])) { + $this->_cellCache[$pCoord]->detach(); + unset($this->_cellCache[$pCoord]); + } + $this->_currentCellIsDirty = false; + } // function deleteCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + return array_keys($this->_cellCache); + } // function getCellList() + + + /** + * Sort the list of all cell addresses currently held in cache by row and column + * + * @return void + */ + public function getSortedCellList() { + $sortKeys = array(); + foreach ($this->getCellList() as $coord) { + sscanf($coord,'%[A-Z]%d', $column, $row); + $sortKeys[sprintf('%09d%3s',$row,$column)] = $coord; + } + ksort($sortKeys); + + return array_values($sortKeys); + } // function sortCellList() + + + + /** + * Get highest worksheet column and highest row that have cell records + * + * @return array Highest column name and highest row number + */ + public function getHighestRowAndColumn() + { + // Lookup highest column and highest row + $col = array('A' => '1A'); + $row = array(1); + foreach ($this->getCellList() as $coord) { + sscanf($coord,'%[A-Z]%d', $c, $r); + $row[$r] = $r; + $col[$c] = strlen($c).$c; + } + if (!empty($row)) { + // Determine highest column and row + $highestRow = max($row); + $highestColumn = substr(max($col),1); + } + + return array( 'row' => $highestRow, + 'column' => $highestColumn + ); + } + + + /** + * Return the cell address of the currently active cell object + * + * @return string + */ + public function getCurrentAddress() + { + return $this->_currentObjectID; + } + + /** + * Return the column address of the currently active cell object + * + * @return string + */ + public function getCurrentColumn() + { + sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row); + return $column; + } + + /** + * Return the row address of the currently active cell object + * + * @return string + */ + public function getCurrentRow() + { + sscanf($this->_currentObjectID, '%[A-Z]%d', $column, $row); + return $row; + } + + /** + * Get highest worksheet column + * + * @param string $row Return the highest column for the specified row, + * or the highest column of any row if no row number is passed + * @return string Highest column name + */ + public function getHighestColumn($row = null) + { + if ($row == null) { + $colRow = $this->getHighestRowAndColumn(); + return $colRow['column']; + } + + $columnList = array(1); + foreach ($this->getCellList() as $coord) { + sscanf($coord,'%[A-Z]%d', $c, $r); + if ($r != $row) { + continue; + } + $columnList[] = PHPExcel_Cell::columnIndexFromString($c); + } + return PHPExcel_Cell::stringFromColumnIndex(max($columnList) - 1); + } + + /** + * Get highest worksheet row + * + * @param string $column Return the highest row for the specified column, + * or the highest row of any column if no column letter is passed + * @return int Highest row number + */ + public function getHighestRow($column = null) + { + if ($column == null) { + $colRow = $this->getHighestRowAndColumn(); + return $colRow['row']; + } + + $rowList = array(0); + foreach ($this->getCellList() as $coord) { + sscanf($coord,'%[A-Z]%d', $c, $r); + if ($c != $column) { + continue; + } + $rowList[] = $r; + } + + return max($rowList); + } + + + /** + * Generate a unique ID for cache referencing + * + * @return string Unique Reference + */ + protected function _getUniqueID() { + if (function_exists('posix_getpid')) { + $baseUnique = posix_getpid(); + } else { + $baseUnique = mt_rand(); + } + return uniqid($baseUnique,true); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + $this->_currentCellIsDirty; + $this->_storeData(); + + $this->_parent = $parent; + if (($this->_currentObject !== NULL) && (is_object($this->_currentObject))) { + $this->_currentObject->attach($this); + } + } // function copyCellCollection() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php new file mode 100644 index 00000000..492abea8 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php @@ -0,0 +1,219 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + fseek($this->_fileHandle,0,SEEK_END); + $offset = ftell($this->_fileHandle); + fwrite($this->_fileHandle, serialize($this->_currentObject)); + $this->_cellCache[$this->_currentObjectID] = array('ptr' => $offset, + 'sz' => ftell($this->_fileHandle) - $offset + ); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']); + $this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz'])); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->_getUniqueID(); + $newFileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache'; + // Copy the existing cell cache file + copy ($this->_fileName,$newFileName); + $this->_fileName = $newFileName; + // Open the copied cell cache file + $this->_fileHandle = fopen($this->_fileName,'a+'); + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) { + $this->_cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== NULL)) + ? $arguments['dir'] + : PHPExcel_Shared_File::sys_get_temp_dir(); + + parent::__construct($parent); + if (is_null($this->_fileHandle)) { + $baseUnique = $this->_getUniqueID(); + $this->_fileName = $this->_cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache'; + $this->_fileHandle = fopen($this->_fileName,'a+'); + } + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + if (!is_null($this->_fileHandle)) { + fclose($this->_fileHandle); + unlink($this->_fileName); + } + $this->_fileHandle = null; + } // function __destruct() + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php new file mode 100644 index 00000000..c3f2c14d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php @@ -0,0 +1,112 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $this->_cellCache[$this->_currentObjectID] = igbinary_serialize($this->_currentObject); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = igbinary_unserialize($this->_cellCache[$pCoord]); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!function_exists('igbinary_serialize')) { + return false; + } + + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php new file mode 100644 index 00000000..9061a31a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php @@ -0,0 +1,312 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $obj = serialize($this->_currentObject); + if (!$this->_memcache->replace($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) { + if (!$this->_memcache->add($this->_cachePrefix.$this->_currentObjectID.'.cache',$obj,NULL,$this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in MemCache'); + } + } + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + $this->_cellCache[$pCoord] = true; + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return void + * @return boolean + */ + public function isDataSet($pCoord) { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->_currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in Memcache + $success = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache'); + if ($success === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache'); + } + return true; + } + return false; + } // function isDataSet() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (parent::isDataSet($pCoord)) { + $obj = $this->_memcache->get($this->_cachePrefix.$pCoord.'.cache'); + if ($obj === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache'); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + // Delete the entry from Memcache + $this->_memcache->delete($this->_cachePrefix.$pCoord.'.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } // function deleteCacheData() + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->_getUniqueID(); + $newCachePrefix = substr(md5($baseUnique),0,8).'.'; + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + if ($cellID != $this->_currentObjectID) { + $obj = $this->_memcache->get($this->_cachePrefix.$cellID.'.cache'); + if ($obj === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in MemCache'); + } + if (!$this->_memcache->add($newCachePrefix.$cellID.'.cache',$obj,NULL,$this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in MemCache'); + } + } + } + $this->_cachePrefix = $newCachePrefix; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + + // Flush the Memcache cache + $this->__destruct(); + + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) { + $memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost'; + $memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211; + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if (is_null($this->_cachePrefix)) { + $baseUnique = $this->_getUniqueID(); + $this->_cachePrefix = substr(md5($baseUnique),0,8).'.'; + + // Set a new Memcache object and connect to the Memcache server + $this->_memcache = new Memcache(); + if (!$this->_memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) { + throw new PHPExcel_Exception('Could not connect to MemCache server at '.$memcacheServer.':'.$memcachePort); + } + $this->_cacheTime = $cacheTime; + + parent::__construct($parent); + } + } // function __construct() + + + /** + * Memcache error handler + * + * @param string $host Memcache server + * @param integer $port Memcache port + * @throws PHPExcel_Exception + */ + public function failureCallback($host, $port) { + throw new PHPExcel_Exception('memcache '.$host.':'.$port.' failed'); + } + + + /** + * Destroy this cell collection + */ + public function __destruct() { + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + $this->_memcache->delete($this->_cachePrefix.$cellID.'.cache'); + } + } // function __destruct() + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!function_exists('memcache_add')) { + return false; + } + + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php new file mode 100644 index 00000000..20cd59f6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php @@ -0,0 +1,125 @@ +_cellCache[$pCoord] = $cell; + + // Set current entry to the new/updated entry + $this->_currentObjectID = $pCoord; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + $this->_currentObjectID = NULL; + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + + // Return requested entry + return $this->_cellCache[$pCoord]; + } // function getCacheData() + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + + $newCollection = array(); + foreach($this->_cellCache as $k => &$cell) { + $newCollection[$k] = clone $cell; + $newCollection[$k]->attach($this); + } + + $this->_cellCache = $newCollection; + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + // Because cells are all stored as intact objects in memory, we need to detach each one from the parent + foreach($this->_cellCache as $k => &$cell) { + $cell->detach(); + $this->_cellCache[$k] = null; + } + unset($cell); + + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php new file mode 100644 index 00000000..692c1bfc --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php @@ -0,0 +1,137 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $this->_cellCache[$this->_currentObjectID] = gzdeflate(serialize($this->_currentObject)); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = unserialize(gzinflate($this->_cellCache[$pCoord])); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php new file mode 100644 index 00000000..fdd021a8 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php @@ -0,0 +1,137 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $this->_cellCache[$this->_currentObjectID] = serialize($this->_currentObject); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = unserialize($this->_cellCache[$pCoord]); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php new file mode 100644 index 00000000..b00c19bb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php @@ -0,0 +1,206 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + fseek($this->_fileHandle,0,SEEK_END); + $offset = ftell($this->_fileHandle); + fwrite($this->_fileHandle, serialize($this->_currentObject)); + $this->_cellCache[$this->_currentObjectID] = array('ptr' => $offset, + 'sz' => ftell($this->_fileHandle) - $offset + ); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->_cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + fseek($this->_fileHandle,$this->_cellCache[$pCoord]['ptr']); + $this->_currentObject = unserialize(fread($this->_fileHandle,$this->_cellCache[$pCoord]['sz'])); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + // Open a new stream for the cell cache data + $newFileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+'); + // Copy the existing cell cache data to the new stream + fseek($this->_fileHandle,0); + while (!feof($this->_fileHandle)) { + fwrite($newFileHandle,fread($this->_fileHandle, 1024)); + } + $this->_fileHandle = $newFileHandle; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + + // Close down the php://temp file + $this->__destruct(); + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) { + $this->_memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB'; + + parent::__construct($parent); + if (is_null($this->_fileHandle)) { + $this->_fileHandle = fopen('php://temp/maxmemory:'.$this->_memoryCacheSize,'a+'); + } + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + if (!is_null($this->_fileHandle)) { + fclose($this->_fileHandle); + } + $this->_fileHandle = null; + } // function __destruct() + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php new file mode 100644 index 00000000..75b99c68 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php @@ -0,0 +1,306 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + if (!$this->_DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES('".$this->_currentObjectID."','".sqlite_escape_string(serialize($this->_currentObject))."')")) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + $query = "SELECT value FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'"; + $cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC); + if ($cellResultSet === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + } elseif ($cellResultSet->numRows() == 0) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + + $cellResult = $cellResultSet->fetchSingle(); + $this->_currentObject = unserialize($cellResult); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Is a value set for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return true; + } + + // Check if the requested entry exists in the cache + $query = "SELECT id FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'"; + $cellResultSet = $this->_DBHandle->query($query,SQLITE_ASSOC); + if ($cellResultSet === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + } elseif ($cellResultSet->numRows() == 0) { + // Return null if requested entry doesn't exist in cache + return false; + } + return true; + } // function isDataSet() + + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + $this->_currentObject->detach(); + $this->_currentObjectID = $this->_currentObject = null; + } + + // Check if the requested entry exists in the cache + $query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$pCoord."'"; + if (!$this->_DBHandle->queryExec($query)) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + + $this->_currentCellIsDirty = false; + } // function deleteCacheData() + + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) { + if ($fromAddress === $this->_currentObjectID) { + $this->_currentObjectID = $toAddress; + } + + $query = "DELETE FROM kvp_".$this->_TableName." WHERE id='".$toAddress."'"; + $result = $this->_DBHandle->exec($query); + if ($result === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + $query = "UPDATE kvp_".$this->_TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'"; + $result = $this->_DBHandle->exec($query); + if ($result === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + return TRUE; + } // function moveCell() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + $query = "SELECT id FROM kvp_".$this->_TableName; + $cellIdsResult = $this->_DBHandle->unbufferedQuery($query,SQLITE_ASSOC); + if ($cellIdsResult === false) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + + $cellKeys = array(); + foreach($cellIdsResult as $row) { + $cellKeys[] = $row['id']; + } + + return $cellKeys; + } // function getCellList() + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + $this->_currentCellIsDirty; + $this->_storeData(); + + // Get a new id for the new table name + $tableName = str_replace('.','_',$this->_getUniqueID()); + if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_'.$this->_TableName)) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + + // Copy the existing cell cache file + $this->_TableName = $tableName; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + */ + public function __construct(PHPExcel_Worksheet $parent) { + parent::__construct($parent); + if (is_null($this->_DBHandle)) { + $this->_TableName = str_replace('.','_',$this->_getUniqueID()); + $_DBName = ':memory:'; + + $this->_DBHandle = new SQLiteDatabase($_DBName); + if ($this->_DBHandle === false) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + if (!$this->_DBHandle->queryExec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) + throw new PHPExcel_Exception(sqlite_error_string($this->_DBHandle->lastError())); + } + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + if (!is_null($this->_DBHandle)) { + $this->_DBHandle->queryExec('DROP TABLE kvp_'.$this->_TableName); + } + $this->_DBHandle = null; + } // function __destruct() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!function_exists('sqlite_open')) { + return false; + } + + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php new file mode 100644 index 00000000..bcfe159b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php @@ -0,0 +1,345 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $this->_insertQuery->bindValue('id',$this->_currentObjectID,SQLITE3_TEXT); + $this->_insertQuery->bindValue('data',serialize($this->_currentObject),SQLITE3_BLOB); + $result = $this->_insertQuery->execute(); + if ($result === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + $this->_currentCellIsDirty = false; + } + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + $this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT); + $cellResult = $this->_selectQuery->execute(); + if ($cellResult === FALSE) { + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + } + $cellData = $cellResult->fetchArray(SQLITE3_ASSOC); + if ($cellData === FALSE) { + // Return null if requested entry doesn't exist in cache + return NULL; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + + $this->_currentObject = unserialize($cellData['value']); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Is a value set for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return TRUE; + } + + // Check if the requested entry exists in the cache + $this->_selectQuery->bindValue('id',$pCoord,SQLITE3_TEXT); + $cellResult = $this->_selectQuery->execute(); + if ($cellResult === FALSE) { + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + } + $cellData = $cellResult->fetchArray(SQLITE3_ASSOC); + + return ($cellData === FALSE) ? FALSE : TRUE; + } // function isDataSet() + + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + $this->_currentObject->detach(); + $this->_currentObjectID = $this->_currentObject = NULL; + } + + // Check if the requested entry exists in the cache + $this->_deleteQuery->bindValue('id',$pCoord,SQLITE3_TEXT); + $result = $this->_deleteQuery->execute(); + if ($result === FALSE) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + $this->_currentCellIsDirty = FALSE; + } // function deleteCacheData() + + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) { + if ($fromAddress === $this->_currentObjectID) { + $this->_currentObjectID = $toAddress; + } + + $this->_deleteQuery->bindValue('id',$toAddress,SQLITE3_TEXT); + $result = $this->_deleteQuery->execute(); + if ($result === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + $this->_updateQuery->bindValue('toid',$toAddress,SQLITE3_TEXT); + $this->_updateQuery->bindValue('fromid',$fromAddress,SQLITE3_TEXT); + $result = $this->_updateQuery->execute(); + if ($result === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + return TRUE; + } // function moveCell() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + $query = "SELECT id FROM kvp_".$this->_TableName; + $cellIdsResult = $this->_DBHandle->query($query); + if ($cellIdsResult === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + $cellKeys = array(); + while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) { + $cellKeys[] = $row['id']; + } + + return $cellKeys; + } // function getCellList() + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + $this->_currentCellIsDirty; + $this->_storeData(); + + // Get a new id for the new table name + $tableName = str_replace('.','_',$this->_getUniqueID()); + if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_'.$this->_TableName)) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + + // Copy the existing cell cache file + $this->_TableName = $tableName; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + */ + public function __construct(PHPExcel_Worksheet $parent) { + parent::__construct($parent); + if (is_null($this->_DBHandle)) { + $this->_TableName = str_replace('.','_',$this->_getUniqueID()); + $_DBName = ':memory:'; + + $this->_DBHandle = new SQLite3($_DBName); + if ($this->_DBHandle === false) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + if (!$this->_DBHandle->exec('CREATE TABLE kvp_'.$this->_TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) + throw new PHPExcel_Exception($this->_DBHandle->lastErrorMsg()); + } + + $this->_selectQuery = $this->_DBHandle->prepare("SELECT value FROM kvp_".$this->_TableName." WHERE id = :id"); + $this->_insertQuery = $this->_DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->_TableName." VALUES(:id,:data)"); + $this->_updateQuery = $this->_DBHandle->prepare("UPDATE kvp_".$this->_TableName." SET id=:toId WHERE id=:fromId"); + $this->_deleteQuery = $this->_DBHandle->prepare("DELETE FROM kvp_".$this->_TableName." WHERE id = :id"); + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + if (!is_null($this->_DBHandle)) { + $this->_DBHandle->exec('DROP TABLE kvp_'.$this->_TableName); + $this->_DBHandle->close(); + } + $this->_DBHandle = null; + } // function __destruct() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!class_exists('SQLite3',FALSE)) { + return false; + } + + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php new file mode 100644 index 00000000..96dca662 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php @@ -0,0 +1,294 @@ +_currentCellIsDirty && !empty($this->_currentObjectID)) { + $this->_currentObject->detach(); + + $obj = serialize($this->_currentObject); + if (wincache_ucache_exists($this->_cachePrefix.$this->_currentObjectID.'.cache')) { + if (!wincache_ucache_set($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache'); + } + } else { + if (!wincache_ucache_add($this->_cachePrefix.$this->_currentObjectID.'.cache', $obj, $this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->_currentObjectID.' in WinCache'); + } + } + $this->_currentCellIsDirty = false; + } + + $this->_currentObjectID = $this->_currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return void + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) { + if (($pCoord !== $this->_currentObjectID) && ($this->_currentObjectID !== null)) { + $this->_storeData(); + } + $this->_cellCache[$pCoord] = true; + + $this->_currentObjectID = $pCoord; + $this->_currentObject = $cell; + $this->_currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->_currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in cache + $success = wincache_ucache_exists($this->_cachePrefix.$pCoord.'.cache'); + if ($success === false) { + // Entry no longer exists in Wincache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); + } + return true; + } + return false; + } // function isDataSet() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) { + if ($pCoord === $this->_currentObjectID) { + return $this->_currentObject; + } + $this->_storeData(); + + // Check if the entry that has been requested actually exists + $obj = null; + if (parent::isDataSet($pCoord)) { + $success = false; + $obj = wincache_ucache_get($this->_cachePrefix.$pCoord.'.cache', $success); + if ($success === false) { + // Entry no longer exists in WinCache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->_currentObjectID = $pCoord; + $this->_currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->_currentObject->attach($this); + + // Return requested entry + return $this->_currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return array of string + */ + public function getCellList() { + if ($this->_currentObjectID !== null) { + $this->_storeData(); + } + + return parent::getCellList(); + } + + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) { + // Delete the entry from Wincache + wincache_ucache_delete($this->_cachePrefix.$pCoord.'.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } // function deleteCacheData() + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->_getUniqueID(); + $newCachePrefix = substr(md5($baseUnique),0,8).'.'; + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + if ($cellID != $this->_currentObjectID) { + $success = false; + $obj = wincache_ucache_get($this->_cachePrefix.$cellID.'.cache', $success); + if ($success === false) { + // Entry no longer exists in WinCache, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in Wincache'); + } + if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->_cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in Wincache'); + } + } + } + $this->_cachePrefix = $newCachePrefix; + } // function copyCellCollection() + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() { + if(!is_null($this->_currentObject)) { + $this->_currentObject->detach(); + $this->_currentObject = $this->_currentObjectID = null; + } + + // Flush the WinCache cache + $this->__destruct(); + + $this->_cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->_parent = null; + } // function unsetWorksheetCells() + + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) { + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if (is_null($this->_cachePrefix)) { + $baseUnique = $this->_getUniqueID(); + $this->_cachePrefix = substr(md5($baseUnique),0,8).'.'; + $this->_cacheTime = $cacheTime; + + parent::__construct($parent); + } + } // function __construct() + + + /** + * Destroy this cell collection + */ + public function __destruct() { + $cacheList = $this->getCellList(); + foreach($cacheList as $cellID) { + wincache_ucache_delete($this->_cachePrefix.$cellID.'.cache'); + } + } // function __destruct() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() { + if (!function_exists('wincache_ucache_add')) { + return false; + } + + return true; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php new file mode 100644 index 00000000..6c3ec15c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php @@ -0,0 +1,251 @@ + array( + ), + self::cache_in_memory_gzip => array( + ), + self::cache_in_memory_serialized => array( + ), + self::cache_igbinary => array( + ), + self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB' + ), + self::cache_to_discISAM => array( 'dir' => NULL + ), + self::cache_to_apc => array( 'cacheTime' => 600 + ), + self::cache_to_memcache => array( 'memcacheServer' => 'localhost', + 'memcachePort' => 11211, + 'cacheTime' => 600 + ), + self::cache_to_wincache => array( 'cacheTime' => 600 + ), + self::cache_to_sqlite => array( + ), + self::cache_to_sqlite3 => array( + ), + ); + + + /** + * Arguments for the active cache storage method + * + * @var array of mixed array + */ + private static $_storageMethodParameters = array(); + + + /** + * Return the current cache storage method + * + * @return string|NULL + **/ + public static function getCacheStorageMethod() + { + return self::$_cacheStorageMethod; + } // function getCacheStorageMethod() + + + /** + * Return the current cache storage class + * + * @return PHPExcel_CachedObjectStorage_ICache|NULL + **/ + public static function getCacheStorageClass() + { + return self::$_cacheStorageClass; + } // function getCacheStorageClass() + + + /** + * Return the list of all possible cache storage methods + * + * @return string[] + **/ + public static function getAllCacheStorageMethods() + { + return self::$_storageMethods; + } // function getCacheStorageMethods() + + + /** + * Return the list of all available cache storage methods + * + * @return string[] + **/ + public static function getCacheStorageMethods() + { + $activeMethods = array(); + foreach(self::$_storageMethods as $storageMethod) { + $cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $storageMethod; + if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) { + $activeMethods[] = $storageMethod; + } + } + return $activeMethods; + } // function getCacheStorageMethods() + + + /** + * Identify the cache storage method to use + * + * @param string $method Name of the method to use for cell cacheing + * @param array of mixed $arguments Additional arguments to pass to the cell caching class + * when instantiating + * @return boolean + **/ + public static function initialize($method = self::cache_in_memory, $arguments = array()) + { + if (!in_array($method,self::$_storageMethods)) { + return FALSE; + } + + $cacheStorageClass = 'PHPExcel_CachedObjectStorage_'.$method; + if (!call_user_func(array( $cacheStorageClass, + 'cacheMethodIsAvailable'))) { + return FALSE; + } + + self::$_storageMethodParameters[$method] = self::$_storageMethodDefaultParameters[$method]; + foreach($arguments as $k => $v) { + if (array_key_exists($k, self::$_storageMethodParameters[$method])) { + self::$_storageMethodParameters[$method][$k] = $v; + } + } + + if (self::$_cacheStorageMethod === NULL) { + self::$_cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $method; + self::$_cacheStorageMethod = $method; + } + return TRUE; + } // function initialize() + + + /** + * Initialise the cache storage + * + * @param PHPExcel_Worksheet $parent Enable cell caching for this worksheet + * @return PHPExcel_CachedObjectStorage_ICache + **/ + public static function getInstance(PHPExcel_Worksheet $parent) + { + $cacheMethodIsAvailable = TRUE; + if (self::$_cacheStorageMethod === NULL) { + $cacheMethodIsAvailable = self::initialize(); + } + + if ($cacheMethodIsAvailable) { + $instance = new self::$_cacheStorageClass( $parent, + self::$_storageMethodParameters[self::$_cacheStorageMethod] + ); + if ($instance !== NULL) { + return $instance; + } + } + + return FALSE; + } // function getInstance() + + + /** + * Clear the cache storage + * + **/ + public static function finalize() + { + self::$_cacheStorageMethod = NULL; + self::$_cacheStorageClass = NULL; + self::$_storageMethodParameters = array(); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php new file mode 100644 index 00000000..02591935 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php @@ -0,0 +1,98 @@ +_stack); + } + + /** + * Push a new entry onto the stack + * + * @param mixed $value + */ + public function push($value) { + $this->_stack[] = $value; + } // function push() + + /** + * Pop the last entry from the stack + * + * @return mixed + */ + public function pop() { + return array_pop($this->_stack); + } // function pop() + + /** + * Test to see if a specified entry exists on the stack + * + * @param mixed $value The value to test + */ + public function onStack($value) { + return in_array($value, $this->_stack); + } + + /** + * Clear the stack + */ + public function clear() { + $this->_stack = array(); + } // function push() + + /** + * Return an array of all entries on the stack + * + * @return mixed[] + */ + public function showStack() { + return $this->_stack; + } + +} // class PHPExcel_CalcEngine_CyclicReferenceStack diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php new file mode 100644 index 00000000..2048df3e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php @@ -0,0 +1,153 @@ +_cellStack = $stack; + } + + /** + * Enable/Disable Calculation engine logging + * + * @param boolean $pValue + */ + public function setWriteDebugLog($pValue = FALSE) { + $this->_writeDebugLog = $pValue; + } + + /** + * Return whether calculation engine logging is enabled or disabled + * + * @return boolean + */ + public function getWriteDebugLog() { + return $this->_writeDebugLog; + } + + /** + * Enable/Disable echoing of debug log information + * + * @param boolean $pValue + */ + public function setEchoDebugLog($pValue = FALSE) { + $this->_echoDebugLog = $pValue; + } + + /** + * Return whether echoing of debug log information is enabled or disabled + * + * @return boolean + */ + public function getEchoDebugLog() { + return $this->_echoDebugLog; + } + + /** + * Write an entry to the calculation engine debug log + */ + public function writeDebugLog() { + // Only write the debug log if logging is enabled + if ($this->_writeDebugLog) { + $message = implode(func_get_args()); + $cellReference = implode(' -> ', $this->_cellStack->showStack()); + if ($this->_echoDebugLog) { + echo $cellReference, + ($this->_cellStack->count() > 0 ? ' => ' : ''), + $message, + PHP_EOL; + } + $this->_debugLog[] = $cellReference . + ($this->_cellStack->count() > 0 ? ' => ' : '') . + $message; + } + } // function _writeDebug() + + /** + * Clear the calculation engine debug log + */ + public function clearLog() { + $this->_debugLog = array(); + } // function flushLogger() + + /** + * Return the calculation engine debug log + * + * @return string[] + */ + public function getLog() { + return $this->_debugLog; + } // function flushLogger() + +} // class PHPExcel_CalcEngine_Logger + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php new file mode 100644 index 00000000..b609b0d8 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php @@ -0,0 +1,3933 @@ +=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})'); + // Named Range of cells + define('CALCULATION_REGEXP_NAMEDRANGE','((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)'); + } else { + // Cell reference (cell or range of cells, with or without a sheet reference) + define('CALCULATION_REGEXP_CELLREF','(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)'); + // Named Range of cells + define('CALCULATION_REGEXP_NAMEDRANGE','(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)'); + } +} + + +/** + * PHPExcel_Calculation (Multiton) + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Calculation { + + /** Constants */ + /** Regular Expressions */ + // Numeric operand + const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; + // String operand + const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; + // Opening bracket + const CALCULATION_REGEXP_OPENBRACE = '\('; + // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) + const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\('; + // Cell reference (cell or range of cells, with or without a sheet reference) + const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF; + // Named Range of cells + const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE; + // Error + const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; + + + /** constants */ + const RETURN_ARRAY_AS_ERROR = 'error'; + const RETURN_ARRAY_AS_VALUE = 'value'; + const RETURN_ARRAY_AS_ARRAY = 'array'; + + private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; + + + /** + * Instance of this class + * + * @access private + * @var PHPExcel_Calculation + */ + private static $_instance; + + + /** + * Instance of the workbook this Calculation Engine is using + * + * @access private + * @var PHPExcel + */ + private $_workbook; + + /** + * List of instances of the calculation engine that we've instantiated for individual workbooks + * + * @access private + * @var PHPExcel_Calculation[] + */ + private static $_workbookSets; + + /** + * Calculation cache + * + * @access private + * @var array + */ + private $_calculationCache = array (); + + + /** + * Calculation cache enabled + * + * @access private + * @var boolean + */ + private $_calculationCacheEnabled = TRUE; + + + /** + * List of operators that can be used within formulae + * The true/false value indicates whether it is a binary operator or a unary operator + * + * @access private + * @var array + */ + private static $_operators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE, + '^' => TRUE, '&' => TRUE, '%' => FALSE, '~' => FALSE, + '>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE, + '<=' => TRUE, '<>' => TRUE, '|' => TRUE, ':' => TRUE + ); + + + /** + * List of binary operators (those that expect two operands) + * + * @access private + * @var array + */ + private static $_binaryOperators = array('+' => TRUE, '-' => TRUE, '*' => TRUE, '/' => TRUE, + '^' => TRUE, '&' => TRUE, '>' => TRUE, '<' => TRUE, + '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE, + '|' => TRUE, ':' => TRUE + ); + + /** + * The debug log generated by the calculation engine + * + * @access private + * @var PHPExcel_CalcEngine_Logger + * + */ + private $debugLog; + + /** + * Flag to determine how formula errors should be handled + * If true, then a user error will be triggered + * If false, then an exception will be thrown + * + * @access public + * @var boolean + * + */ + public $suppressFormulaErrors = FALSE; + + /** + * Error message for any error that was raised/thrown by the calculation engine + * + * @access public + * @var string + * + */ + public $formulaError = NULL; + + /** + * An array of the nested cell references accessed by the calculation engine, used for the debug log + * + * @access private + * @var array of string + * + */ + private $_cyclicReferenceStack; + + /** + * Current iteration counter for cyclic formulae + * If the value is 0 (or less) then cyclic formulae will throw an exception, + * otherwise they will iterate to the limit defined here before returning a result + * + * @var integer + * + */ + private $_cyclicFormulaCount = 0; + + private $_cyclicFormulaCell = ''; + + /** + * Number of iterations for cyclic formulae + * + * @var integer + * + */ + public $cyclicFormulaCount = 0; + + /** + * Precision used for calculations + * + * @var integer + * + */ + private $_savedPrecision = 14; + + + /** + * The current locale setting + * + * @var string + * + */ + private static $_localeLanguage = 'en_us'; // US English (default locale) + + /** + * List of available locale settings + * Note that this is read for the locale subdirectory only when requested + * + * @var string[] + * + */ + private static $_validLocaleLanguages = array( 'en' // English (default language) + ); + /** + * Locale-specific argument separator for function arguments + * + * @var string + * + */ + private static $_localeArgumentSeparator = ','; + private static $_localeFunctions = array(); + + /** + * Locale-specific translations for Excel constants (True, False and Null) + * + * @var string[] + * + */ + public static $_localeBoolean = array( 'TRUE' => 'TRUE', + 'FALSE' => 'FALSE', + 'NULL' => 'NULL' + ); + + + /** + * Excel constant string translations to their PHP equivalents + * Constant conversion from text name/value to actual (datatyped) value + * + * @var string[] + * + */ + private static $_ExcelConstants = array('TRUE' => TRUE, + 'FALSE' => FALSE, + 'NULL' => NULL + ); + + // PHPExcel functions + private static $_PHPExcelFunctions = array( // PHPExcel functions + 'ABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'abs', + 'argumentCount' => '1' + ), + 'ACCRINT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINT', + 'argumentCount' => '4-7' + ), + 'ACCRINTM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINTM', + 'argumentCount' => '3-5' + ), + 'ACOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'acos', + 'argumentCount' => '1' + ), + 'ACOSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'acosh', + 'argumentCount' => '1' + ), + 'ADDRESS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::CELL_ADDRESS', + 'argumentCount' => '2-5' + ), + 'AMORDEGRC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::AMORDEGRC', + 'argumentCount' => '6,7' + ), + 'AMORLINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::AMORLINC', + 'argumentCount' => '6,7' + ), + 'AND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_AND', + 'argumentCount' => '1+' + ), + 'AREAS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ASC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ASIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'asin', + 'argumentCount' => '1' + ), + 'ASINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'asinh', + 'argumentCount' => '1' + ), + 'ATAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'atan', + 'argumentCount' => '1' + ), + 'ATAN2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ATAN2', + 'argumentCount' => '2' + ), + 'ATANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'atanh', + 'argumentCount' => '1' + ), + 'AVEDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVEDEV', + 'argumentCount' => '1+' + ), + 'AVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGE', + 'argumentCount' => '1+' + ), + 'AVERAGEA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEA', + 'argumentCount' => '1+' + ), + 'AVERAGEIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEIF', + 'argumentCount' => '2,3' + ), + 'AVERAGEIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3+' + ), + 'BAHTTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'BESSELI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELI', + 'argumentCount' => '2' + ), + 'BESSELJ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELJ', + 'argumentCount' => '2' + ), + 'BESSELK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELK', + 'argumentCount' => '2' + ), + 'BESSELY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELY', + 'argumentCount' => '2' + ), + 'BETADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BETADIST', + 'argumentCount' => '3-5' + ), + 'BETAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BETAINV', + 'argumentCount' => '3-5' + ), + 'BIN2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTODEC', + 'argumentCount' => '1' + ), + 'BIN2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOHEX', + 'argumentCount' => '1,2' + ), + 'BIN2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOOCT', + 'argumentCount' => '1,2' + ), + 'BINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BINOMDIST', + 'argumentCount' => '4' + ), + 'CEILING' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::CEILING', + 'argumentCount' => '2' + ), + 'CELL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1,2' + ), + 'CHAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::CHARACTER', + 'argumentCount' => '1' + ), + 'CHIDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIDIST', + 'argumentCount' => '2' + ), + 'CHIINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIINV', + 'argumentCount' => '2' + ), + 'CHITEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'CHOOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::CHOOSE', + 'argumentCount' => '2+' + ), + 'CLEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMNONPRINTABLE', + 'argumentCount' => '1' + ), + 'CODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::ASCIICODE', + 'argumentCount' => '1' + ), + 'COLUMN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMN', + 'argumentCount' => '-1', + 'passByReference' => array(TRUE) + ), + 'COLUMNS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMNS', + 'argumentCount' => '1' + ), + 'COMBIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::COMBIN', + 'argumentCount' => '2' + ), + 'COMPLEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::COMPLEX', + 'argumentCount' => '2,3' + ), + 'CONCATENATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::CONCATENATE', + 'argumentCount' => '1+' + ), + 'CONFIDENCE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CONFIDENCE', + 'argumentCount' => '3' + ), + 'CONVERT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::CONVERTUOM', + 'argumentCount' => '3' + ), + 'CORREL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL', + 'argumentCount' => '2' + ), + 'COS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'cos', + 'argumentCount' => '1' + ), + 'COSH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'cosh', + 'argumentCount' => '1' + ), + 'COUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNT', + 'argumentCount' => '1+' + ), + 'COUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTA', + 'argumentCount' => '1+' + ), + 'COUNTBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTBLANK', + 'argumentCount' => '1' + ), + 'COUNTIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTIF', + 'argumentCount' => '2' + ), + 'COUNTIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'COUPDAYBS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYBS', + 'argumentCount' => '3,4' + ), + 'COUPDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYS', + 'argumentCount' => '3,4' + ), + 'COUPDAYSNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYSNC', + 'argumentCount' => '3,4' + ), + 'COUPNCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNCD', + 'argumentCount' => '3,4' + ), + 'COUPNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNUM', + 'argumentCount' => '3,4' + ), + 'COUPPCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPPCD', + 'argumentCount' => '3,4' + ), + 'COVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COVAR', + 'argumentCount' => '2' + ), + 'CRITBINOM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CRITBINOM', + 'argumentCount' => '3' + ), + 'CUBEKPIMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEMEMBERPROPERTY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBERANKEDMEMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBESET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBESETCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUMIPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::CUMIPMT', + 'argumentCount' => '6' + ), + 'CUMPRINC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::CUMPRINC', + 'argumentCount' => '6' + ), + 'DATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATE', + 'argumentCount' => '3' + ), + 'DATEDIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEDIF', + 'argumentCount' => '2,3' + ), + 'DATEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEVALUE', + 'argumentCount' => '1' + ), + 'DAVERAGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DAVERAGE', + 'argumentCount' => '3' + ), + 'DAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFMONTH', + 'argumentCount' => '1' + ), + 'DAYS360' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYS360', + 'argumentCount' => '2,3' + ), + 'DB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DB', + 'argumentCount' => '4,5' + ), + 'DCOUNT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNT', + 'argumentCount' => '3' + ), + 'DCOUNTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNTA', + 'argumentCount' => '3' + ), + 'DDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DDB', + 'argumentCount' => '4,5' + ), + 'DEC2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOBIN', + 'argumentCount' => '1,2' + ), + 'DEC2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOHEX', + 'argumentCount' => '1,2' + ), + 'DEC2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOOCT', + 'argumentCount' => '1,2' + ), + 'DEGREES' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'rad2deg', + 'argumentCount' => '1' + ), + 'DELTA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DELTA', + 'argumentCount' => '1,2' + ), + 'DEVSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::DEVSQ', + 'argumentCount' => '1+' + ), + 'DGET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DGET', + 'argumentCount' => '3' + ), + 'DISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DISC', + 'argumentCount' => '4,5' + ), + 'DMAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DMAX', + 'argumentCount' => '3' + ), + 'DMIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DMIN', + 'argumentCount' => '3' + ), + 'DOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::DOLLAR', + 'argumentCount' => '1,2' + ), + 'DOLLARDE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARDE', + 'argumentCount' => '2' + ), + 'DOLLARFR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARFR', + 'argumentCount' => '2' + ), + 'DPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DPRODUCT', + 'argumentCount' => '3' + ), + 'DSTDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEV', + 'argumentCount' => '3' + ), + 'DSTDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEVP', + 'argumentCount' => '3' + ), + 'DSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSUM', + 'argumentCount' => '3' + ), + 'DURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5,6' + ), + 'DVAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DVAR', + 'argumentCount' => '3' + ), + 'DVARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DVARP', + 'argumentCount' => '3' + ), + 'EDATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::EDATE', + 'argumentCount' => '2' + ), + 'EFFECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::EFFECT', + 'argumentCount' => '2' + ), + 'EOMONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::EOMONTH', + 'argumentCount' => '2' + ), + 'ERF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::ERF', + 'argumentCount' => '1,2' + ), + 'ERFC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::ERFC', + 'argumentCount' => '1' + ), + 'ERROR.TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::ERROR_TYPE', + 'argumentCount' => '1' + ), + 'EVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::EVEN', + 'argumentCount' => '1' + ), + 'EXACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'EXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'exp', + 'argumentCount' => '1' + ), + 'EXPONDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::EXPONDIST', + 'argumentCount' => '3' + ), + 'FACT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACT', + 'argumentCount' => '1' + ), + 'FACTDOUBLE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACTDOUBLE', + 'argumentCount' => '1' + ), + 'FALSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::FALSE', + 'argumentCount' => '0' + ), + 'FDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3' + ), + 'FIND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE', + 'argumentCount' => '2,3' + ), + 'FINDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE', + 'argumentCount' => '2,3' + ), + 'FINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3' + ), + 'FISHER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHER', + 'argumentCount' => '1' + ), + 'FISHERINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHERINV', + 'argumentCount' => '1' + ), + 'FIXED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::FIXEDFORMAT', + 'argumentCount' => '1-3' + ), + 'FLOOR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FLOOR', + 'argumentCount' => '2' + ), + 'FORECAST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FORECAST', + 'argumentCount' => '3' + ), + 'FREQUENCY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'FTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'FV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::FV', + 'argumentCount' => '3-5' + ), + 'FVSCHEDULE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::FVSCHEDULE', + 'argumentCount' => '2' + ), + 'GAMMADIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMADIST', + 'argumentCount' => '4' + ), + 'GAMMAINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMAINV', + 'argumentCount' => '3' + ), + 'GAMMALN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMALN', + 'argumentCount' => '1' + ), + 'GCD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::GCD', + 'argumentCount' => '1+' + ), + 'GEOMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GEOMEAN', + 'argumentCount' => '1+' + ), + 'GESTEP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::GESTEP', + 'argumentCount' => '1,2' + ), + 'GETPIVOTDATA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2+' + ), + 'GROWTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GROWTH', + 'argumentCount' => '1-4' + ), + 'HARMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::HARMEAN', + 'argumentCount' => '1+' + ), + 'HEX2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOBIN', + 'argumentCount' => '1,2' + ), + 'HEX2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTODEC', + 'argumentCount' => '1' + ), + 'HEX2OCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOOCT', + 'argumentCount' => '1,2' + ), + 'HLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::HLOOKUP', + 'argumentCount' => '3,4' + ), + 'HOUR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::HOUROFDAY', + 'argumentCount' => '1' + ), + 'HYPERLINK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::HYPERLINK', + 'argumentCount' => '1,2', + 'passCellReference'=> TRUE + ), + 'HYPGEOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::HYPGEOMDIST', + 'argumentCount' => '4' + ), + 'IF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::STATEMENT_IF', + 'argumentCount' => '1-3' + ), + 'IFERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::IFERROR', + 'argumentCount' => '2' + ), + 'IMABS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMABS', + 'argumentCount' => '1' + ), + 'IMAGINARY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMAGINARY', + 'argumentCount' => '1' + ), + 'IMARGUMENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMARGUMENT', + 'argumentCount' => '1' + ), + 'IMCONJUGATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCONJUGATE', + 'argumentCount' => '1' + ), + 'IMCOS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCOS', + 'argumentCount' => '1' + ), + 'IMDIV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMDIV', + 'argumentCount' => '2' + ), + 'IMEXP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMEXP', + 'argumentCount' => '1' + ), + 'IMLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLN', + 'argumentCount' => '1' + ), + 'IMLOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG10', + 'argumentCount' => '1' + ), + 'IMLOG2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG2', + 'argumentCount' => '1' + ), + 'IMPOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPOWER', + 'argumentCount' => '2' + ), + 'IMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPRODUCT', + 'argumentCount' => '1+' + ), + 'IMREAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMREAL', + 'argumentCount' => '1' + ), + 'IMSIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSIN', + 'argumentCount' => '1' + ), + 'IMSQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSQRT', + 'argumentCount' => '1' + ), + 'IMSUB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUB', + 'argumentCount' => '2' + ), + 'IMSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUM', + 'argumentCount' => '1+' + ), + 'INDEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDEX', + 'argumentCount' => '1-4' + ), + 'INDIRECT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDIRECT', + 'argumentCount' => '1,2', + 'passCellReference'=> TRUE + ), + 'INFO' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'INT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::INT', + 'argumentCount' => '1' + ), + 'INTERCEPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::INTERCEPT', + 'argumentCount' => '2' + ), + 'INTRATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::INTRATE', + 'argumentCount' => '4,5' + ), + 'IPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::IPMT', + 'argumentCount' => '4-6' + ), + 'IRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::IRR', + 'argumentCount' => '1,2' + ), + 'ISBLANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_BLANK', + 'argumentCount' => '1' + ), + 'ISERR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERR', + 'argumentCount' => '1' + ), + 'ISERROR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERROR', + 'argumentCount' => '1' + ), + 'ISEVEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_EVEN', + 'argumentCount' => '1' + ), + 'ISLOGICAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_LOGICAL', + 'argumentCount' => '1' + ), + 'ISNA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NA', + 'argumentCount' => '1' + ), + 'ISNONTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NONTEXT', + 'argumentCount' => '1' + ), + 'ISNUMBER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NUMBER', + 'argumentCount' => '1' + ), + 'ISODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ODD', + 'argumentCount' => '1' + ), + 'ISPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ISPMT', + 'argumentCount' => '4' + ), + 'ISREF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ISTEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_TEXT', + 'argumentCount' => '1' + ), + 'JIS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'KURT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::KURT', + 'argumentCount' => '1+' + ), + 'LARGE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LARGE', + 'argumentCount' => '2' + ), + 'LCM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::LCM', + 'argumentCount' => '1+' + ), + 'LEFT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT', + 'argumentCount' => '1,2' + ), + 'LEFTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT', + 'argumentCount' => '1,2' + ), + 'LEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH', + 'argumentCount' => '1' + ), + 'LENB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH', + 'argumentCount' => '1' + ), + 'LINEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LINEST', + 'argumentCount' => '1-4' + ), + 'LN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'log', + 'argumentCount' => '1' + ), + 'LOG' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::LOG_BASE', + 'argumentCount' => '1,2' + ), + 'LOG10' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'log10', + 'argumentCount' => '1' + ), + 'LOGEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGEST', + 'argumentCount' => '1-4' + ), + 'LOGINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGINV', + 'argumentCount' => '3' + ), + 'LOGNORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGNORMDIST', + 'argumentCount' => '3' + ), + 'LOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::LOOKUP', + 'argumentCount' => '2,3' + ), + 'LOWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LOWERCASE', + 'argumentCount' => '1' + ), + 'MATCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::MATCH', + 'argumentCount' => '2,3' + ), + 'MAX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAX', + 'argumentCount' => '1+' + ), + 'MAXA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXA', + 'argumentCount' => '1+' + ), + 'MAXIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXIF', + 'argumentCount' => '2+' + ), + 'MDETERM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MDETERM', + 'argumentCount' => '1' + ), + 'MDURATION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5,6' + ), + 'MEDIAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MEDIAN', + 'argumentCount' => '1+' + ), + 'MEDIANIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2+' + ), + 'MID' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::MID', + 'argumentCount' => '3' + ), + 'MIDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::MID', + 'argumentCount' => '3' + ), + 'MIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MIN', + 'argumentCount' => '1+' + ), + 'MINA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MINA', + 'argumentCount' => '1+' + ), + 'MINIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MINIF', + 'argumentCount' => '2+' + ), + 'MINUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::MINUTEOFHOUR', + 'argumentCount' => '1' + ), + 'MINVERSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MINVERSE', + 'argumentCount' => '1' + ), + 'MIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::MIRR', + 'argumentCount' => '3' + ), + 'MMULT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MMULT', + 'argumentCount' => '2' + ), + 'MOD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MOD', + 'argumentCount' => '2' + ), + 'MODE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MODE', + 'argumentCount' => '1+' + ), + 'MONTH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::MONTHOFYEAR', + 'argumentCount' => '1' + ), + 'MROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MROUND', + 'argumentCount' => '2' + ), + 'MULTINOMIAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MULTINOMIAL', + 'argumentCount' => '1+' + ), + 'N' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::N', + 'argumentCount' => '1' + ), + 'NA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::NA', + 'argumentCount' => '0' + ), + 'NEGBINOMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NEGBINOMDIST', + 'argumentCount' => '3' + ), + 'NETWORKDAYS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::NETWORKDAYS', + 'argumentCount' => '2+' + ), + 'NOMINAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NOMINAL', + 'argumentCount' => '2' + ), + 'NORMDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMDIST', + 'argumentCount' => '4' + ), + 'NORMINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMINV', + 'argumentCount' => '3' + ), + 'NORMSDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSDIST', + 'argumentCount' => '1' + ), + 'NORMSINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSINV', + 'argumentCount' => '1' + ), + 'NOT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::NOT', + 'argumentCount' => '1' + ), + 'NOW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATETIMENOW', + 'argumentCount' => '0' + ), + 'NPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NPER', + 'argumentCount' => '3-5' + ), + 'NPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NPV', + 'argumentCount' => '2+' + ), + 'OCT2BIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOBIN', + 'argumentCount' => '1,2' + ), + 'OCT2DEC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTODEC', + 'argumentCount' => '1' + ), + 'OCT2HEX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOHEX', + 'argumentCount' => '1,2' + ), + 'ODD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ODD', + 'argumentCount' => '1' + ), + 'ODDFPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '8,9' + ), + 'ODDFYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '8,9' + ), + 'ODDLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '7,8' + ), + 'ODDLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '7,8' + ), + 'OFFSET' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::OFFSET', + 'argumentCount' => '3,5', + 'passCellReference'=> TRUE, + 'passByReference' => array(TRUE) + ), + 'OR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_OR', + 'argumentCount' => '1+' + ), + 'PEARSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL', + 'argumentCount' => '2' + ), + 'PERCENTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTILE', + 'argumentCount' => '2' + ), + 'PERCENTRANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTRANK', + 'argumentCount' => '2,3' + ), + 'PERMUT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERMUT', + 'argumentCount' => '2' + ), + 'PHONETIC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'PI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'pi', + 'argumentCount' => '0' + ), + 'PMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PMT', + 'argumentCount' => '3-5' + ), + 'POISSON' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::POISSON', + 'argumentCount' => '3' + ), + 'POWER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::POWER', + 'argumentCount' => '2' + ), + 'PPMT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PPMT', + 'argumentCount' => '4-6' + ), + 'PRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICE', + 'argumentCount' => '6,7' + ), + 'PRICEDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEDISC', + 'argumentCount' => '4,5' + ), + 'PRICEMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEMAT', + 'argumentCount' => '5,6' + ), + 'PROB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3,4' + ), + 'PRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::PRODUCT', + 'argumentCount' => '1+' + ), + 'PROPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::PROPERCASE', + 'argumentCount' => '1' + ), + 'PV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PV', + 'argumentCount' => '3-5' + ), + 'QUARTILE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::QUARTILE', + 'argumentCount' => '2' + ), + 'QUOTIENT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::QUOTIENT', + 'argumentCount' => '2' + ), + 'RADIANS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'deg2rad', + 'argumentCount' => '1' + ), + 'RAND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND', + 'argumentCount' => '0' + ), + 'RANDBETWEEN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND', + 'argumentCount' => '2' + ), + 'RANK' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::RANK', + 'argumentCount' => '2,3' + ), + 'RATE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::RATE', + 'argumentCount' => '3-6' + ), + 'RECEIVED' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::RECEIVED', + 'argumentCount' => '4-5' + ), + 'REPLACE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE', + 'argumentCount' => '4' + ), + 'REPLACEB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE', + 'argumentCount' => '4' + ), + 'REPT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'str_repeat', + 'argumentCount' => '2' + ), + 'RIGHT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT', + 'argumentCount' => '1,2' + ), + 'RIGHTB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT', + 'argumentCount' => '1,2' + ), + 'ROMAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROMAN', + 'argumentCount' => '1,2' + ), + 'ROUND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'round', + 'argumentCount' => '2' + ), + 'ROUNDDOWN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDDOWN', + 'argumentCount' => '2' + ), + 'ROUNDUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDUP', + 'argumentCount' => '2' + ), + 'ROW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROW', + 'argumentCount' => '-1', + 'passByReference' => array(TRUE) + ), + 'ROWS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROWS', + 'argumentCount' => '1' + ), + 'RSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::RSQ', + 'argumentCount' => '2' + ), + 'RTD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1+' + ), + 'SEARCH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE', + 'argumentCount' => '2,3' + ), + 'SEARCHB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE', + 'argumentCount' => '2,3' + ), + 'SECOND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::SECONDOFMINUTE', + 'argumentCount' => '1' + ), + 'SERIESSUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SERIESSUM', + 'argumentCount' => '4' + ), + 'SIGN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SIGN', + 'argumentCount' => '1' + ), + 'SIN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sin', + 'argumentCount' => '1' + ), + 'SINH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sinh', + 'argumentCount' => '1' + ), + 'SKEW' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SKEW', + 'argumentCount' => '1+' + ), + 'SLN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::SLN', + 'argumentCount' => '3' + ), + 'SLOPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SLOPE', + 'argumentCount' => '2' + ), + 'SMALL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SMALL', + 'argumentCount' => '2' + ), + 'SQRT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sqrt', + 'argumentCount' => '1' + ), + 'SQRTPI' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SQRTPI', + 'argumentCount' => '1' + ), + 'STANDARDIZE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STANDARDIZE', + 'argumentCount' => '3' + ), + 'STDEV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEV', + 'argumentCount' => '1+' + ), + 'STDEVA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVA', + 'argumentCount' => '1+' + ), + 'STDEVP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVP', + 'argumentCount' => '1+' + ), + 'STDEVPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVPA', + 'argumentCount' => '1+' + ), + 'STEYX' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STEYX', + 'argumentCount' => '2' + ), + 'SUBSTITUTE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SUBSTITUTE', + 'argumentCount' => '3,4' + ), + 'SUBTOTAL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUBTOTAL', + 'argumentCount' => '2+' + ), + 'SUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUM', + 'argumentCount' => '1+' + ), + 'SUMIF' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIF', + 'argumentCount' => '2,3' + ), + 'SUMIFS' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'SUMPRODUCT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMPRODUCT', + 'argumentCount' => '1+' + ), + 'SUMSQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMSQ', + 'argumentCount' => '1+' + ), + 'SUMX2MY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2MY2', + 'argumentCount' => '2' + ), + 'SUMX2PY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2PY2', + 'argumentCount' => '2' + ), + 'SUMXMY2' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMXMY2', + 'argumentCount' => '2' + ), + 'SYD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::SYD', + 'argumentCount' => '4' + ), + 'T' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RETURNSTRING', + 'argumentCount' => '1' + ), + 'TAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'tan', + 'argumentCount' => '1' + ), + 'TANH' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'tanh', + 'argumentCount' => '1' + ), + 'TBILLEQ' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLEQ', + 'argumentCount' => '3' + ), + 'TBILLPRICE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLPRICE', + 'argumentCount' => '3' + ), + 'TBILLYIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLYIELD', + 'argumentCount' => '3' + ), + 'TDIST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TDIST', + 'argumentCount' => '3' + ), + 'TEXT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TEXTFORMAT', + 'argumentCount' => '2' + ), + 'TIME' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::TIME', + 'argumentCount' => '3' + ), + 'TIMEVALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::TIMEVALUE', + 'argumentCount' => '1' + ), + 'TINV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TINV', + 'argumentCount' => '2' + ), + 'TODAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATENOW', + 'argumentCount' => '0' + ), + 'TRANSPOSE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::TRANSPOSE', + 'argumentCount' => '1' + ), + 'TREND' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TREND', + 'argumentCount' => '1-4' + ), + 'TRIM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMSPACES', + 'argumentCount' => '1' + ), + 'TRIMMEAN' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TRIMMEAN', + 'argumentCount' => '2' + ), + 'TRUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::TRUE', + 'argumentCount' => '0' + ), + 'TRUNC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::TRUNC', + 'argumentCount' => '1,2' + ), + 'TTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '4' + ), + 'TYPE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::TYPE', + 'argumentCount' => '1' + ), + 'UPPER' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::UPPERCASE', + 'argumentCount' => '1' + ), + 'USDOLLAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'VALUE' => array('category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'VAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARFunc', + 'argumentCount' => '1+' + ), + 'VARA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARA', + 'argumentCount' => '1+' + ), + 'VARP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARP', + 'argumentCount' => '1+' + ), + 'VARPA' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARPA', + 'argumentCount' => '1+' + ), + 'VDB' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5-7' + ), + 'VERSION' => array('category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::VERSION', + 'argumentCount' => '0' + ), + 'VLOOKUP' => array('category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::VLOOKUP', + 'argumentCount' => '3,4' + ), + 'WEEKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFWEEK', + 'argumentCount' => '1,2' + ), + 'WEEKNUM' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::WEEKOFYEAR', + 'argumentCount' => '1,2' + ), + 'WEIBULL' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::WEIBULL', + 'argumentCount' => '4' + ), + 'WORKDAY' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::WORKDAY', + 'argumentCount' => '2+' + ), + 'XIRR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::XIRR', + 'argumentCount' => '2,3' + ), + 'XNPV' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::XNPV', + 'argumentCount' => '3' + ), + 'YEAR' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::YEAR', + 'argumentCount' => '1' + ), + 'YEARFRAC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::YEARFRAC', + 'argumentCount' => '2,3' + ), + 'YIELD' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '6,7' + ), + 'YIELDDISC' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDDISC', + 'argumentCount' => '4,5' + ), + 'YIELDMAT' => array('category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDMAT', + 'argumentCount' => '5,6' + ), + 'ZTEST' => array('category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::ZTEST', + 'argumentCount' => '2-3' + ) + ); + + + // Internal functions used for special control purposes + private static $_controlFunctions = array( + 'MKMATRIX' => array('argumentCount' => '*', + 'functionCall' => 'self::_mkMatrix' + ) + ); + + + + + private function __construct(PHPExcel $workbook = NULL) { + $setPrecision = (PHP_INT_SIZE == 4) ? 14 : 16; + $this->_savedPrecision = ini_get('precision'); + if ($this->_savedPrecision < $setPrecision) { + ini_set('precision',$setPrecision); + } + + if ($workbook !== NULL) { + self::$_workbookSets[$workbook->getID()] = $this; + } + + $this->_workbook = $workbook; + $this->_cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack(); + $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->_cyclicReferenceStack); + } // function __construct() + + + public function __destruct() { + if ($this->_savedPrecision != ini_get('precision')) { + ini_set('precision',$this->_savedPrecision); + } + } + + private static function _loadLocales() { + $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/'; + foreach (glob($localeFileDirectory.'/*',GLOB_ONLYDIR) as $filename) { + $filename = substr($filename,strlen($localeFileDirectory)+1); + if ($filename != 'en') { + self::$_validLocaleLanguages[] = $filename; + } + } + } + + /** + * Get an instance of this class + * + * @access public + * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object, + * or NULL to create a standalone claculation engine + * @return PHPExcel_Calculation + */ + public static function getInstance(PHPExcel $workbook = NULL) { + if ($workbook !== NULL) { + if (isset(self::$_workbookSets[$workbook->getID()])) { + return self::$_workbookSets[$workbook->getID()]; + } + return new PHPExcel_Calculation($workbook); + } + + if (!isset(self::$_instance) || (self::$_instance === NULL)) { + self::$_instance = new PHPExcel_Calculation(); + } + + return self::$_instance; + } // function getInstance() + + /** + * Unset an instance of this class + * + * @access public + * @param PHPExcel $workbook Injected workbook identifying the instance to unset + */ + public static function unsetInstance(PHPExcel $workbook = NULL) { + if ($workbook !== NULL) { + if (isset(self::$_workbookSets[$workbook->getID()])) { + unset(self::$_workbookSets[$workbook->getID()]); + } + } + } + + /** + * Flush the calculation cache for any existing instance of this class + * but only if a PHPExcel_Calculation instance exists + * + * @access public + * @return null + */ + public function flushInstance() { + $this->clearCalculationCache(); + } // function flushInstance() + + + /** + * Get the debuglog for this claculation engine instance + * + * @access public + * @return PHPExcel_CalcEngine_Logger + */ + public function getDebugLog() { + return $this->_debugLog; + } + + /** + * __clone implementation. Cloning should not be allowed in a Singleton! + * + * @access public + * @throws PHPExcel_Calculation_Exception + */ + public final function __clone() { + throw new PHPExcel_Calculation_Exception ('Cloning the calculation engine is not allowed!'); + } // function __clone() + + + /** + * Return the locale-specific translation of TRUE + * + * @access public + * @return string locale-specific translation of TRUE + */ + public static function getTRUE() { + return self::$_localeBoolean['TRUE']; + } + + /** + * Return the locale-specific translation of FALSE + * + * @access public + * @return string locale-specific translation of FALSE + */ + public static function getFALSE() { + return self::$_localeBoolean['FALSE']; + } + + /** + * Set the Array Return Type (Array or Value of first element in the array) + * + * @access public + * @param string $returnType Array return type + * @return boolean Success or failure + */ + public static function setArrayReturnType($returnType) { + if (($returnType == self::RETURN_ARRAY_AS_VALUE) || + ($returnType == self::RETURN_ARRAY_AS_ERROR) || + ($returnType == self::RETURN_ARRAY_AS_ARRAY)) { + self::$returnArrayAsType = $returnType; + return TRUE; + } + return FALSE; + } // function setArrayReturnType() + + + /** + * Return the Array Return Type (Array or Value of first element in the array) + * + * @access public + * @return string $returnType Array return type + */ + public static function getArrayReturnType() { + return self::$returnArrayAsType; + } // function getArrayReturnType() + + + /** + * Is calculation caching enabled? + * + * @access public + * @return boolean + */ + public function getCalculationCacheEnabled() { + return $this->_calculationCacheEnabled; + } // function getCalculationCacheEnabled() + + /** + * Enable/disable calculation cache + * + * @access public + * @param boolean $pValue + */ + public function setCalculationCacheEnabled($pValue = TRUE) { + $this->_calculationCacheEnabled = $pValue; + $this->clearCalculationCache(); + } // function setCalculationCacheEnabled() + + + /** + * Enable calculation cache + */ + public function enableCalculationCache() { + $this->setCalculationCacheEnabled(TRUE); + } // function enableCalculationCache() + + + /** + * Disable calculation cache + */ + public function disableCalculationCache() { + $this->setCalculationCacheEnabled(FALSE); + } // function disableCalculationCache() + + + /** + * Clear calculation cache + */ + public function clearCalculationCache() { + $this->_calculationCache = array(); + } // function clearCalculationCache() + + /** + * Clear calculation cache for a specified worksheet + * + * @param string $worksheetName + */ + public function clearCalculationCacheForWorksheet($worksheetName) { + if (isset($this->_calculationCache[$worksheetName])) { + unset($this->_calculationCache[$worksheetName]); + } + } // function clearCalculationCacheForWorksheet() + + /** + * Rename calculation cache for a specified worksheet + * + * @param string $fromWorksheetName + * @param string $toWorksheetName + */ + public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) { + if (isset($this->_calculationCache[$fromWorksheetName])) { + $this->_calculationCache[$toWorksheetName] = &$this->_calculationCache[$fromWorksheetName]; + unset($this->_calculationCache[$fromWorksheetName]); + } + } // function renameCalculationCacheForWorksheet() + + + /** + * Get the currently defined locale code + * + * @return string + */ + public function getLocale() { + return self::$_localeLanguage; + } // function getLocale() + + + /** + * Set the locale code + * + * @param string $locale The locale to use for formula translation + * @return boolean + */ + public function setLocale($locale = 'en_us') { + // Identify our locale and language + $language = $locale = strtolower($locale); + if (strpos($locale,'_') !== FALSE) { + list($language) = explode('_',$locale); + } + + if (count(self::$_validLocaleLanguages) == 1) + self::_loadLocales(); + + // Test whether we have any language data for this language (any locale) + if (in_array($language,self::$_validLocaleLanguages)) { + // initialise language/locale settings + self::$_localeFunctions = array(); + self::$_localeArgumentSeparator = ','; + self::$_localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'); + // Default is English, if user isn't requesting english, then read the necessary data from the locale files + if ($locale != 'en_us') { + // Search for a file with a list of function names for locale + $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'functions'; + if (!file_exists($functionNamesFile)) { + // If there isn't a locale specific function file, look for a language specific function file + $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions'; + if (!file_exists($functionNamesFile)) { + return FALSE; + } + } + // Retrieve the list of locale or language specific function names + $localeFunctions = file($functionNamesFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeFunctions as $localeFunction) { + list($localeFunction) = explode('##',$localeFunction); // Strip out comments + if (strpos($localeFunction,'=') !== FALSE) { + list($fName,$lfName) = explode('=',$localeFunction); + $fName = trim($fName); + $lfName = trim($lfName); + if ((isset(self::$_PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { + self::$_localeFunctions[$fName] = $lfName; + } + } + } + // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions + if (isset(self::$_localeFunctions['TRUE'])) { self::$_localeBoolean['TRUE'] = self::$_localeFunctions['TRUE']; } + if (isset(self::$_localeFunctions['FALSE'])) { self::$_localeBoolean['FALSE'] = self::$_localeFunctions['FALSE']; } + + $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_',DIRECTORY_SEPARATOR,$locale).DIRECTORY_SEPARATOR.'config'; + if (!file_exists($configFile)) { + $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config'; + } + if (file_exists($configFile)) { + $localeSettings = file($configFile,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeSettings as $localeSetting) { + list($localeSetting) = explode('##',$localeSetting); // Strip out comments + if (strpos($localeSetting,'=') !== FALSE) { + list($settingName,$settingValue) = explode('=',$localeSetting); + $settingName = strtoupper(trim($settingName)); + switch ($settingName) { + case 'ARGUMENTSEPARATOR' : + self::$_localeArgumentSeparator = trim($settingValue); + break; + } + } + } + } + } + + self::$functionReplaceFromExcel = self::$functionReplaceToExcel = + self::$functionReplaceFromLocale = self::$functionReplaceToLocale = NULL; + self::$_localeLanguage = $locale; + return TRUE; + } + return FALSE; + } // function setLocale() + + + + public static function _translateSeparator($fromSeparator,$toSeparator,$formula,&$inBraces) { + $strlen = mb_strlen($formula); + for ($i = 0; $i < $strlen; ++$i) { + $chr = mb_substr($formula,$i,1); + switch ($chr) { + case '{' : $inBraces = TRUE; + break; + case '}' : $inBraces = FALSE; + break; + case $fromSeparator : + if (!$inBraces) { + $formula = mb_substr($formula,0,$i).$toSeparator.mb_substr($formula,$i+1); + } + } + } + return $formula; + } + + private static function _translateFormula($from,$to,$formula,$fromSeparator,$toSeparator) { + // Convert any Excel function names to the required language + if (self::$_localeLanguage !== 'en_us') { + $inBraces = FALSE; + // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators + if (strpos($formula,'"') !== FALSE) { + // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded + // the formula + $temp = explode('"',$formula); + $i = FALSE; + foreach($temp as &$value) { + // Only count/replace in alternating array entries + if ($i = !$i) { + $value = preg_replace($from,$to,$value); + $value = self::_translateSeparator($fromSeparator,$toSeparator,$value,$inBraces); + } + } + unset($value); + // Then rebuild the formula string + $formula = implode('"',$temp); + } else { + // If there's no quoted strings, then we do a simple count/replace + $formula = preg_replace($from,$to,$formula); + $formula = self::_translateSeparator($fromSeparator,$toSeparator,$formula,$inBraces); + } + } + + return $formula; + } + + private static $functionReplaceFromExcel = NULL; + private static $functionReplaceToLocale = NULL; + + public function _translateFormulaToLocale($formula) { + if (self::$functionReplaceFromExcel === NULL) { + self::$functionReplaceFromExcel = array(); + foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) { + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui'; + } + foreach(array_keys(self::$_localeBoolean) as $excelBoolean) { + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + } + + } + + if (self::$functionReplaceToLocale === NULL) { + self::$functionReplaceToLocale = array(); + foreach(array_values(self::$_localeFunctions) as $localeFunctionName) { + self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2'; + } + foreach(array_values(self::$_localeBoolean) as $localeBoolean) { + self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2'; + } + } + + return self::_translateFormula(self::$functionReplaceFromExcel,self::$functionReplaceToLocale,$formula,',',self::$_localeArgumentSeparator); + } // function _translateFormulaToLocale() + + + private static $functionReplaceFromLocale = NULL; + private static $functionReplaceToExcel = NULL; + + public function _translateFormulaToEnglish($formula) { + if (self::$functionReplaceFromLocale === NULL) { + self::$functionReplaceFromLocale = array(); + foreach(array_values(self::$_localeFunctions) as $localeFunctionName) { + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui'; + } + foreach(array_values(self::$_localeBoolean) as $excelBoolean) { + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + } + } + + if (self::$functionReplaceToExcel === NULL) { + self::$functionReplaceToExcel = array(); + foreach(array_keys(self::$_localeFunctions) as $excelFunctionName) { + self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2'; + } + foreach(array_keys(self::$_localeBoolean) as $excelBoolean) { + self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2'; + } + } + + return self::_translateFormula(self::$functionReplaceFromLocale,self::$functionReplaceToExcel,$formula,self::$_localeArgumentSeparator,','); + } // function _translateFormulaToEnglish() + + + public static function _localeFunc($function) { + if (self::$_localeLanguage !== 'en_us') { + $functionName = trim($function,'('); + if (isset(self::$_localeFunctions[$functionName])) { + $brace = ($functionName != $function); + $function = self::$_localeFunctions[$functionName]; + if ($brace) { $function .= '('; } + } + } + return $function; + } + + + + + /** + * Wrap string values in quotes + * + * @param mixed $value + * @return mixed + */ + public static function _wrapResult($value) { + if (is_string($value)) { + // Error values cannot be "wrapped" + if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) { + // Return Excel errors "as is" + return $value; + } + // Return strings wrapped in quotes + return '"'.$value.'"'; + // Convert numeric errors to NaN error + } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return $value; + } // function _wrapResult() + + + /** + * Remove quotes used as a wrapper to identify string values + * + * @param mixed $value + * @return mixed + */ + public static function _unwrapResult($value) { + if (is_string($value)) { + if ((isset($value{0})) && ($value{0} == '"') && (substr($value,-1) == '"')) { + return substr($value,1,-1); + } + // Convert numeric errors to NaN error + } else if((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $value; + } // function _unwrapResult() + + + + + /** + * Calculate cell value (using formula from a cell ID) + * Retained for backward compatibility + * + * @access public + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculate(PHPExcel_Cell $pCell = NULL) { + try { + return $this->calculateCellValue($pCell); + } catch (PHPExcel_Exception $e) { + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + } // function calculate() + + + /** + * Calculate the value of a cell formula + * + * @access public + * @param PHPExcel_Cell $pCell Cell to calculate + * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculateCellValue(PHPExcel_Cell $pCell = NULL, $resetLog = TRUE) { + if ($pCell === NULL) { + return NULL; + } + + $returnArrayAsType = self::$returnArrayAsType; + if ($resetLog) { + // Initialise the logging settings if requested + $this->formulaError = null; + $this->_debugLog->clearLog(); + $this->_cyclicReferenceStack->clear(); + $this->_cyclicFormulaCount = 1; + + self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY; + } + + // Execute the calculation for the cell formula + try { + $result = self::_unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell)); + } catch (PHPExcel_Exception $e) { + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + + if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { + self::$returnArrayAsType = $returnArrayAsType; + $testResult = PHPExcel_Calculation_Functions::flattenArray($result); + if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) { + return PHPExcel_Calculation_Functions::VALUE(); + } + // If there's only a single cell in the array, then we allow it + if (count($testResult) != 1) { + // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it + $r = array_keys($result); + $r = array_shift($r); + if (!is_numeric($r)) { return PHPExcel_Calculation_Functions::VALUE(); } + if (is_array($result[$r])) { + $c = array_keys($result[$r]); + $c = array_shift($c); + if (!is_numeric($c)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + } + $result = array_shift($testResult); + } + self::$returnArrayAsType = $returnArrayAsType; + + + if ($result === NULL) { + return 0; + } elseif((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $result; + } // function calculateCellValue( + + + /** + * Validate and parse a formula string + * + * @param string $formula Formula to parse + * @return array + * @throws PHPExcel_Calculation_Exception + */ + public function parseFormula($formula) { + // Basic validation that this is indeed a formula + // We return an empty array if not + $formula = trim($formula); + if ((!isset($formula{0})) || ($formula{0} != '=')) return array(); + $formula = ltrim(substr($formula,1)); + if (!isset($formula{0})) return array(); + + // Parse the formula and return the token stack + return $this->_parseFormula($formula); + } // function parseFormula() + + + /** + * Calculate the value of a formula + * + * @param string $formula Formula to parse + * @param string $cellID Address of the cell to calculate + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculateFormula($formula, $cellID=NULL, PHPExcel_Cell $pCell = NULL) { + // Initialise the logging settings + $this->formulaError = null; + $this->_debugLog->clearLog(); + $this->_cyclicReferenceStack->clear(); + + // Disable calculation cacheing because it only applies to cell calculations, not straight formulae + // But don't actually flush any cache + $resetCache = $this->getCalculationCacheEnabled(); + $this->_calculationCacheEnabled = FALSE; + // Execute the calculation + try { + $result = self::_unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell)); + } catch (PHPExcel_Exception $e) { + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + + // Reset calculation cacheing to its previous state + $this->_calculationCacheEnabled = $resetCache; + + return $result; + } // function calculateFormula() + + + public function getValueFromCache($worksheetName, $cellID, &$cellValue) { + // Is calculation cacheing enabled? + // Is the value present in calculation cache? +//echo 'Test cache for ',$worksheetName,'!',$cellID,PHP_EOL; + $this->_debugLog->writeDebugLog('Testing cache value for cell ', $worksheetName, '!', $cellID); + if (($this->_calculationCacheEnabled) && (isset($this->_calculationCache[$worksheetName][$cellID]))) { +//echo 'Retrieve from cache',PHP_EOL; + $this->_debugLog->writeDebugLog('Retrieving value for cell ', $worksheetName, '!', $cellID, ' from cache'); + // Return the cached result + $cellValue = $this->_calculationCache[$worksheetName][$cellID]; + return TRUE; + } + return FALSE; + } + + public function saveValueToCache($worksheetName, $cellID, $cellValue) { + if ($this->_calculationCacheEnabled) { + $this->_calculationCache[$worksheetName][$cellID] = $cellValue; + } + } + + /** + * Parse a cell formula and calculate its value + * + * @param string $formula The formula to parse and calculate + * @param string $cellID The ID (e.g. A3) of the cell that we are calculating + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) { + $cellValue = ''; + + // Basic validation that this is indeed a formula + // We simply return the cell value if not + $formula = trim($formula); + if ($formula{0} != '=') return self::_wrapResult($formula); + $formula = ltrim(substr($formula,1)); + if (!isset($formula{0})) return self::_wrapResult($formula); + + $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL; + $wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk"; + + if (($cellID !== NULL) && ($this->getValueFromCache($wsTitle, $cellID, $cellValue))) { + return $cellValue; + } + + if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) { + if ($this->cyclicFormulaCount <= 0) { + return $this->_raiseFormulaError('Cyclic Reference in Formula'); + } elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) && + ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) { + return $cellValue; + } elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) { + ++$this->_cyclicFormulaCount; + if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) { + return $cellValue; + } + } elseif ($this->_cyclicFormulaCell == '') { + $this->_cyclicFormulaCell = $wsTitle.'!'.$cellID; + if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) { + return $cellValue; + } + } + } + + // Parse the formula onto the token stack and calculate the value + $this->_cyclicReferenceStack->push($wsTitle.'!'.$cellID); + $cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell); + $this->_cyclicReferenceStack->pop(); + + // Save to calculation cache + if ($cellID !== NULL) { + $this->saveValueToCache($wsTitle, $cellID, $cellValue); + } + + // Return the calculated value + return $cellValue; + } // function _calculateFormulaValue() + + + /** + * Ensure that paired matrix operands are both matrices and of the same size + * + * @param mixed &$operand1 First matrix operand + * @param mixed &$operand2 Second matrix operand + * @param integer $resize Flag indicating whether the matrices should be resized to match + * and (if so), whether the smaller dimension should grow or the + * larger should shrink. + * 0 = no resize + * 1 = shrink to fit + * 2 = extend to fit + */ + private static function _checkMatrixOperands(&$operand1,&$operand2,$resize = 1) { + // Examine each of the two operands, and turn them into an array if they aren't one already + // Note that this function should only be called if one or both of the operand is already an array + if (!is_array($operand1)) { + list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand2); + $operand1 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand1)); + $resize = 0; + } elseif (!is_array($operand2)) { + list($matrixRows,$matrixColumns) = self::_getMatrixDimensions($operand1); + $operand2 = array_fill(0,$matrixRows,array_fill(0,$matrixColumns,$operand2)); + $resize = 0; + } + + list($matrix1Rows,$matrix1Columns) = self::_getMatrixDimensions($operand1); + list($matrix2Rows,$matrix2Columns) = self::_getMatrixDimensions($operand2); + if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { + $resize = 1; + } + + if ($resize == 2) { + // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger + self::_resizeMatricesExtend($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns); + } elseif ($resize == 1) { + // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller + self::_resizeMatricesShrink($operand1,$operand2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns); + } + return array( $matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns); + } // function _checkMatrixOperands() + + + /** + * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0 + * + * @param mixed &$matrix matrix operand + * @return array An array comprising the number of rows, and number of columns + */ + public static function _getMatrixDimensions(&$matrix) { + $matrixRows = count($matrix); + $matrixColumns = 0; + foreach($matrix as $rowKey => $rowValue) { + $matrixColumns = max(count($rowValue),$matrixColumns); + if (!is_array($rowValue)) { + $matrix[$rowKey] = array($rowValue); + } else { + $matrix[$rowKey] = array_values($rowValue); + } + } + $matrix = array_values($matrix); + return array($matrixRows,$matrixColumns); + } // function _getMatrixDimensions() + + + /** + * Ensure that paired matrix operands are both matrices of the same size + * + * @param mixed &$matrix1 First matrix operand + * @param mixed &$matrix2 Second matrix operand + * @param integer $matrix1Rows Row size of first matrix operand + * @param integer $matrix1Columns Column size of first matrix operand + * @param integer $matrix2Rows Row size of second matrix operand + * @param integer $matrix2Columns Column size of second matrix operand + */ + private static function _resizeMatricesShrink(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) { + if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { + if ($matrix2Rows < $matrix1Rows) { + for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { + unset($matrix1[$i]); + } + } + if ($matrix2Columns < $matrix1Columns) { + for ($i = 0; $i < $matrix1Rows; ++$i) { + for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { + unset($matrix1[$i][$j]); + } + } + } + } + + if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { + if ($matrix1Rows < $matrix2Rows) { + for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { + unset($matrix2[$i]); + } + } + if ($matrix1Columns < $matrix2Columns) { + for ($i = 0; $i < $matrix2Rows; ++$i) { + for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { + unset($matrix2[$i][$j]); + } + } + } + } + } // function _resizeMatricesShrink() + + + /** + * Ensure that paired matrix operands are both matrices of the same size + * + * @param mixed &$matrix1 First matrix operand + * @param mixed &$matrix2 Second matrix operand + * @param integer $matrix1Rows Row size of first matrix operand + * @param integer $matrix1Columns Column size of first matrix operand + * @param integer $matrix2Rows Row size of second matrix operand + * @param integer $matrix2Columns Column size of second matrix operand + */ + private static function _resizeMatricesExtend(&$matrix1,&$matrix2,$matrix1Rows,$matrix1Columns,$matrix2Rows,$matrix2Columns) { + if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { + if ($matrix2Columns < $matrix1Columns) { + for ($i = 0; $i < $matrix2Rows; ++$i) { + $x = $matrix2[$i][$matrix2Columns-1]; + for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { + $matrix2[$i][$j] = $x; + } + } + } + if ($matrix2Rows < $matrix1Rows) { + $x = $matrix2[$matrix2Rows-1]; + for ($i = 0; $i < $matrix1Rows; ++$i) { + $matrix2[$i] = $x; + } + } + } + + if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { + if ($matrix1Columns < $matrix2Columns) { + for ($i = 0; $i < $matrix1Rows; ++$i) { + $x = $matrix1[$i][$matrix1Columns-1]; + for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { + $matrix1[$i][$j] = $x; + } + } + } + if ($matrix1Rows < $matrix2Rows) { + $x = $matrix1[$matrix1Rows-1]; + for ($i = 0; $i < $matrix2Rows; ++$i) { + $matrix1[$i] = $x; + } + } + } + } // function _resizeMatricesExtend() + + + /** + * Format details of an operand for display in the log (based on operand type) + * + * @param mixed $value First matrix operand + * @return mixed + */ + private function _showValue($value) { + if ($this->_debugLog->getWriteDebugLog()) { + $testArray = PHPExcel_Calculation_Functions::flattenArray($value); + if (count($testArray) == 1) { + $value = array_pop($testArray); + } + + if (is_array($value)) { + $returnMatrix = array(); + $pad = $rpad = ', '; + foreach($value as $row) { + if (is_array($row)) { + $returnMatrix[] = implode($pad,array_map(array($this,'_showValue'),$row)); + $rpad = '; '; + } else { + $returnMatrix[] = $this->_showValue($row); + } + } + return '{ '.implode($rpad,$returnMatrix).' }'; + } elseif(is_string($value) && (trim($value,'"') == $value)) { + return '"'.$value.'"'; + } elseif(is_bool($value)) { + return ($value) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + } + } + return PHPExcel_Calculation_Functions::flattenSingleValue($value); + } // function _showValue() + + + /** + * Format type and details of an operand for display in the log (based on operand type) + * + * @param mixed $value First matrix operand + * @return mixed + */ + private function _showTypeDetails($value) { + if ($this->_debugLog->getWriteDebugLog()) { + $testArray = PHPExcel_Calculation_Functions::flattenArray($value); + if (count($testArray) == 1) { + $value = array_pop($testArray); + } + + if ($value === NULL) { + return 'a NULL value'; + } elseif (is_float($value)) { + $typeString = 'a floating point number'; + } elseif(is_int($value)) { + $typeString = 'an integer number'; + } elseif(is_bool($value)) { + $typeString = 'a boolean'; + } elseif(is_array($value)) { + $typeString = 'a matrix'; + } else { + if ($value == '') { + return 'an empty string'; + } elseif ($value{0} == '#') { + return 'a '.$value.' error'; + } else { + $typeString = 'a string'; + } + } + return $typeString.' with a value of '.$this->_showValue($value); + } + } // function _showTypeDetails() + + + private static function _convertMatrixReferences($formula) { + static $matrixReplaceFrom = array('{',';','}'); + static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(','),MKMATRIX(','))'); + + // Convert any Excel matrix references to the MKMATRIX() function + if (strpos($formula,'{') !== FALSE) { + // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators + if (strpos($formula,'"') !== FALSE) { + // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded + // the formula + $temp = explode('"',$formula); + // Open and Closed counts used for trapping mismatched braces in the formula + $openCount = $closeCount = 0; + $i = FALSE; + foreach($temp as &$value) { + // Only count/replace in alternating array entries + if ($i = !$i) { + $openCount += substr_count($value,'{'); + $closeCount += substr_count($value,'}'); + $value = str_replace($matrixReplaceFrom,$matrixReplaceTo,$value); + } + } + unset($value); + // Then rebuild the formula string + $formula = implode('"',$temp); + } else { + // If there's no quoted strings, then we do a simple count/replace + $openCount = substr_count($formula,'{'); + $closeCount = substr_count($formula,'}'); + $formula = str_replace($matrixReplaceFrom,$matrixReplaceTo,$formula); + } + // Trap for mismatched braces and trigger an appropriate error + if ($openCount < $closeCount) { + if ($openCount > 0) { + return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '}'"); + } else { + return $this->_raiseFormulaError("Formula Error: Unexpected '}' encountered"); + } + } elseif ($openCount > $closeCount) { + if ($closeCount > 0) { + return $this->_raiseFormulaError("Formula Error: Mismatched matrix braces '{'"); + } else { + return $this->_raiseFormulaError("Formula Error: Unexpected '{' encountered"); + } + } + } + + return $formula; + } // function _convertMatrixReferences() + + + private static function _mkMatrix() { + return func_get_args(); + } // function _mkMatrix() + + + // Binary Operators + // These operators always work on two values + // Array key is the operator, the value indicates whether this is a left or right associative operator + private static $_operatorAssociativity = array( + '^' => 0, // Exponentiation + '*' => 0, '/' => 0, // Multiplication and Division + '+' => 0, '-' => 0, // Addition and Subtraction + '&' => 0, // Concatenation + '|' => 0, ':' => 0, // Intersect and Range + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison + ); + + // Comparison (Boolean) Operators + // These operators work on two values, but always return a boolean result + private static $_comparisonOperators = array('>' => TRUE, '<' => TRUE, '=' => TRUE, '>=' => TRUE, '<=' => TRUE, '<>' => TRUE); + + // Operator Precedence + // This list includes all valid operators, whether binary (including boolean) or unary (such as %) + // Array key is the operator, the value is its precedence + private static $_operatorPrecedence = array( + ':' => 8, // Range + '|' => 7, // Intersect + '~' => 6, // Negation + '%' => 5, // Percentage + '^' => 4, // Exponentiation + '*' => 3, '/' => 3, // Multiplication and Division + '+' => 2, '-' => 2, // Addition and Subtraction + '&' => 1, // Concatenation + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison + ); + + // Convert infix to postfix notation + private function _parseFormula($formula, PHPExcel_Cell $pCell = NULL) { + if (($formula = self::_convertMatrixReferences(trim($formula))) === FALSE) { + return FALSE; + } + + // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), + // so we store the parent worksheet so that we can re-attach it when necessary + $pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL; + + $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION. + '|'.self::CALCULATION_REGEXP_CELLREF. + '|'.self::CALCULATION_REGEXP_NUMBER. + '|'.self::CALCULATION_REGEXP_STRING. + '|'.self::CALCULATION_REGEXP_OPENBRACE. + '|'.self::CALCULATION_REGEXP_NAMEDRANGE. + '|'.self::CALCULATION_REGEXP_ERROR. + ')/si'; + + // Start with initialisation + $index = 0; + $stack = new PHPExcel_Calculation_Token_Stack; + $output = array(); + $expectingOperator = FALSE; // We use this test in syntax-checking the expression to determine when a + // - is a negation or + is a positive operator rather than an operation + $expectingOperand = FALSE; // We use this test in syntax-checking the expression to determine whether an operand + // should be null in a function call + // The guts of the lexical parser + // Loop through the formula extracting each operator and operand in turn + while(TRUE) { +//echo 'Assessing Expression '.substr($formula, $index),PHP_EOL; + $opCharacter = $formula{$index}; // Get the first character of the value at the current index position +//echo 'Initial character of expression block is '.$opCharacter,PHP_EOL; + if ((isset(self::$_comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$_comparisonOperators[$formula{$index+1}]))) { + $opCharacter .= $formula{++$index}; +//echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL; + } + + // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand + $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match); +//echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').PHP_EOL; +//var_dump($match); + + if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus? +//echo 'Element is a Negation operator',PHP_EOL; + $stack->push('Unary Operator','~'); // Put a negation on the stack + ++$index; // and drop the negation symbol + } elseif ($opCharacter == '%' && $expectingOperator) { +//echo 'Element is a Percentage operator',PHP_EOL; + $stack->push('Unary Operator','%'); // Put a percentage on the stack + ++$index; + } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? +//echo 'Element is a Positive number, not Plus operator',PHP_EOL; + ++$index; // Drop the redundant plus symbol + } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal + return $this->_raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression + + } elseif ((isset(self::$_operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? +//echo 'Element with value '.$opCharacter.' is an Operator',PHP_EOL; + while($stack->count() > 0 && + ($o2 = $stack->last()) && + isset(self::$_operators[$o2['value']]) && + @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) { + $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output + } + $stack->push('Binary Operator',$opCharacter); // Finally put our current operator onto the stack + ++$index; + $expectingOperator = FALSE; + + } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis? +//echo 'Element is a Closing bracket',PHP_EOL; + $expectingOperand = FALSE; + while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + if ($o2 === NULL) return $this->_raiseFormulaError('Formula Error: Unexpected closing brace ")"'); + else $output[] = $o2; + } + $d = $stack->last(2); + if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function? + $functionName = $matches[1]; // Get the function name +//echo 'Closed Function is '.$functionName,PHP_EOL; + $d = $stack->pop(); + $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack) +//if ($argumentCount == 0) { +// echo 'With no arguments',PHP_EOL; +//} elseif ($argumentCount == 1) { +// echo 'With 1 argument',PHP_EOL; +//} else { +// echo 'With '.$argumentCount.' arguments',PHP_EOL; +//} + $output[] = $d; // Dump the argument count on the output + $output[] = $stack->pop(); // Pop the function and push onto the output + if (isset(self::$_controlFunctions[$functionName])) { +//echo 'Built-in function '.$functionName,PHP_EOL; + $expectedArgumentCount = self::$_controlFunctions[$functionName]['argumentCount']; + $functionCall = self::$_controlFunctions[$functionName]['functionCall']; + } elseif (isset(self::$_PHPExcelFunctions[$functionName])) { +//echo 'PHPExcel function '.$functionName,PHP_EOL; + $expectedArgumentCount = self::$_PHPExcelFunctions[$functionName]['argumentCount']; + $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall']; + } else { // did we somehow push a non-function on the stack? this should never happen + return $this->_raiseFormulaError("Formula Error: Internal error, non-function on stack"); + } + // Check the argument count + $argumentCountError = FALSE; + if (is_numeric($expectedArgumentCount)) { + if ($expectedArgumentCount < 0) { +//echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount),PHP_EOL; + if ($argumentCount > abs($expectedArgumentCount)) { + $argumentCountError = TRUE; + $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount); + } + } else { +//echo '$expectedArgumentCount is numeric '.$expectedArgumentCount,PHP_EOL; + if ($argumentCount != $expectedArgumentCount) { + $argumentCountError = TRUE; + $expectedArgumentCountString = $expectedArgumentCount; + } + } + } elseif ($expectedArgumentCount != '*') { + $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/',$expectedArgumentCount,$argMatch); +//print_r($argMatch); +//echo PHP_EOL; + switch ($argMatch[2]) { + case '+' : + if ($argumentCount < $argMatch[1]) { + $argumentCountError = TRUE; + $expectedArgumentCountString = $argMatch[1].' or more '; + } + break; + case '-' : + if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { + $argumentCountError = TRUE; + $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3]; + } + break; + case ',' : + if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { + $argumentCountError = TRUE; + $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3]; + } + break; + } + } + if ($argumentCountError) { + return $this->_raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected"); + } + } + ++$index; + + } elseif ($opCharacter == ',') { // Is this the separator for function arguments? +//echo 'Element is a Function argument separator',PHP_EOL; + while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + if ($o2 === NULL) return $this->_raiseFormulaError("Formula Error: Unexpected ,"); + else $output[] = $o2; // pop the argument expression stuff and push onto the output + } + // If we've a comma when we're expecting an operand, then what we actually have is a null operand; + // so push a null onto the stack + if (($expectingOperand) || (!$expectingOperator)) { + $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL); + } + // make sure there was a function + $d = $stack->last(2); + if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) + return $this->_raiseFormulaError("Formula Error: Unexpected ,"); + $d = $stack->pop(); + $stack->push($d['type'],++$d['value'],$d['reference']); // increment the argument count + $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again + $expectingOperator = FALSE; + $expectingOperand = TRUE; + ++$index; + + } elseif ($opCharacter == '(' && !$expectingOperator) { +// echo 'Element is an Opening Bracket
'; + $stack->push('Brace', '('); + ++$index; + + } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number? + $expectingOperator = TRUE; + $expectingOperand = FALSE; + $val = $match[1]; + $length = strlen($val); +// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function
'; + + if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) { + $val = preg_replace('/\s/','',$val); +// echo 'Element '.$val.' is a Function
'; + if (isset(self::$_PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$_controlFunctions[strtoupper($matches[1])])) { // it's a function + $stack->push('Function', strtoupper($val)); + $ax = preg_match('/^\s*(\s*\))/i', substr($formula, $index+$length), $amatch); + if ($ax) { + $stack->push('Operand Count for Function '.strtoupper($val).')', 0); + $expectingOperator = TRUE; + } else { + $stack->push('Operand Count for Function '.strtoupper($val).')', 1); + $expectingOperator = FALSE; + } + $stack->push('Brace', '('); + } else { // it's a var w/ implicit multiplication + $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => NULL); + } + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) { +// echo 'Element '.$val.' is a Cell reference
'; + // Watch for this case-change when modifying to allow cell references in different worksheets... + // Should only be applied to the actual cell column, not the worksheet name + + // If the last entry on the stack was a : operator, then we have a cell range reference + $testPrevOp = $stack->last(1); + if ($testPrevOp['value'] == ':') { + // If we have a worksheet reference, then we're playing with a 3D reference + if ($matches[2] == '') { + // Otherwise, we 'inherit' the worksheet reference from the start cell reference + // The start of the cell range reference should be the last entry in $output + $startCellRef = $output[count($output)-1]['value']; + preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches); + if ($startMatches[2] > '') { + $val = $startMatches[2].'!'.$val; + } + } else { + return $this->_raiseFormulaError("3D Range references are not yet supported"); + } + } + + $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val); +// $expectingOperator = FALSE; + } else { // it's a variable, constant, string, number or boolean +// echo 'Element is a Variable, Constant, String, Number or Boolean
'; + // If the last entry on the stack was a : operator, then we may have a row or column range reference + $testPrevOp = $stack->last(1); + if ($testPrevOp['value'] == ':') { + $startRowColRef = $output[count($output)-1]['value']; + $rangeWS1 = ''; + if (strpos('!',$startRowColRef) !== FALSE) { + list($rangeWS1,$startRowColRef) = explode('!',$startRowColRef); + } + if ($rangeWS1 != '') $rangeWS1 .= '!'; + $rangeWS2 = $rangeWS1; + if (strpos('!',$val) !== FALSE) { + list($rangeWS2,$val) = explode('!',$val); + } + if ($rangeWS2 != '') $rangeWS2 .= '!'; + if ((is_integer($startRowColRef)) && (ctype_digit($val)) && + ($startRowColRef <= 1048576) && ($val <= 1048576)) { + // Row range + $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007 + $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef; + $val = $rangeWS2.$endRowColRef.$val; + } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) && + (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) { + // Column range + $endRowColRef = ($pCellParent !== NULL) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007 + $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1'; + $val = $rangeWS2.$val.$endRowColRef; + } + } + + $localeConstant = FALSE; + if ($opCharacter == '"') { +// echo 'Element is a String
'; + // UnEscape any quotes within the string + $val = self::_wrapResult(str_replace('""','"',self::_unwrapResult($val))); + } elseif (is_numeric($val)) { +// echo 'Element is a Number
'; + if ((strpos($val,'.') !== FALSE) || (stripos($val,'e') !== FALSE) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { +// echo 'Casting '.$val.' to float
'; + $val = (float) $val; + } else { +// echo 'Casting '.$val.' to integer
'; + $val = (integer) $val; + } + } elseif (isset(self::$_ExcelConstants[trim(strtoupper($val))])) { + $excelConstant = trim(strtoupper($val)); +// echo 'Element '.$excelConstant.' is an Excel Constant
'; + $val = self::$_ExcelConstants[$excelConstant]; + } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$_localeBoolean)) !== FALSE) { +// echo 'Element '.$localeConstant.' is an Excel Constant
'; + $val = self::$_ExcelConstants[$localeConstant]; + } + $details = array('type' => 'Value', 'value' => $val, 'reference' => NULL); + if ($localeConstant) { $details['localeValue'] = $localeConstant; } + $output[] = $details; + } + $index += $length; + + } elseif ($opCharacter == '$') { // absolute row or column range + ++$index; + } elseif ($opCharacter == ')') { // miscellaneous error checking + if ($expectingOperand) { + $output[] = array('type' => 'NULL Value', 'value' => self::$_ExcelConstants['NULL'], 'reference' => NULL); + $expectingOperand = FALSE; + $expectingOperator = TRUE; + } else { + return $this->_raiseFormulaError("Formula Error: Unexpected ')'"); + } + } elseif (isset(self::$_operators[$opCharacter]) && !$expectingOperator) { + return $this->_raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); + } else { // I don't even want to know what you did to get here + return $this->_raiseFormulaError("Formula Error: An unexpected error occured"); + } + // Test for end of formula string + if ($index == strlen($formula)) { + // Did we end with an operator?. + // Only valid for the % unary operator + if ((isset(self::$_operators[$opCharacter])) && ($opCharacter != '%')) { + return $this->_raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); + } else { + break; + } + } + // Ignore white space + while (($formula{$index} == "\n") || ($formula{$index} == "\r")) { + ++$index; + } + if ($formula{$index} == ' ') { + while ($formula{$index} == ' ') { + ++$index; + } + // If we're expecting an operator, but only have a space between the previous and next operands (and both are + // Cell References) then we have an INTERSECTION operator +// echo 'Possible Intersect Operator
'; + if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) && + ($output[count($output)-1]['type'] == 'Cell Reference')) { +// echo 'Element is an Intersect Operator
'; + while($stack->count() > 0 && + ($o2 = $stack->last()) && + isset(self::$_operators[$o2['value']]) && + @(self::$_operatorAssociativity[$opCharacter] ? self::$_operatorPrecedence[$opCharacter] < self::$_operatorPrecedence[$o2['value']] : self::$_operatorPrecedence[$opCharacter] <= self::$_operatorPrecedence[$o2['value']])) { + $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output + } + $stack->push('Binary Operator','|'); // Put an Intersect Operator on the stack + $expectingOperator = FALSE; + } + } + } + + while (($op = $stack->pop()) !== NULL) { // pop everything off the stack and push onto output + if ((is_array($op) && $op['value'] == '(') || ($op === '(')) + return $this->_raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced + $output[] = $op; + } + return $output; + } // function _parseFormula() + + + private static function _dataTestReference(&$operandData) + { + $operand = $operandData['value']; + if (($operandData['reference'] === NULL) && (is_array($operand))) { + $rKeys = array_keys($operand); + $rowKey = array_shift($rKeys); + $cKeys = array_keys(array_keys($operand[$rowKey])); + $colKey = array_shift($cKeys); + if (ctype_upper($colKey)) { + $operandData['reference'] = $colKey.$rowKey; + } + } + return $operand; + } + + // evaluate postfix notation + private function _processTokenStack($tokens, $cellID = NULL, PHPExcel_Cell $pCell = NULL) { + if ($tokens == FALSE) return FALSE; + + // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), + // so we store the parent cell collection so that we can re-attach it when necessary + $pCellWorksheet = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL; + $pCellParent = ($pCell !== NULL) ? $pCell->getParent() : null; + $stack = new PHPExcel_Calculation_Token_Stack; + + // Loop through each token in turn + foreach ($tokens as $tokenData) { +// print_r($tokenData); +// echo '
'; + $token = $tokenData['value']; +// echo 'Token is '.$token.'
'; + // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack + if (isset(self::$_binaryOperators[$token])) { +// echo 'Token is a binary operator
'; + // We must have two operands, error if we don't + if (($operand2Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack'); + if (($operand1Data = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack'); + + $operand1 = self::_dataTestReference($operand1Data); + $operand2 = self::_dataTestReference($operand2Data); + + // Log what we're doing + if ($token == ':') { + $this->_debugLog->writeDebugLog('Evaluating Range ', $this->_showValue($operand1Data['reference']), ' ', $token, ' ', $this->_showValue($operand2Data['reference'])); + } else { + $this->_debugLog->writeDebugLog('Evaluating ', $this->_showValue($operand1), ' ', $token, ' ', $this->_showValue($operand2)); + } + + // Process the operation in the appropriate manner + switch ($token) { + // Comparison (Boolean) Operators + case '>' : // Greater than + case '<' : // Less than + case '>=' : // Greater than or Equal to + case '<=' : // Less than or Equal to + case '=' : // Equality + case '<>' : // Inequality + $this->_executeBinaryComparisonOperation($cellID,$operand1,$operand2,$token,$stack); + break; + // Binary Operators + case ':' : // Range + $sheet1 = $sheet2 = ''; + if (strpos($operand1Data['reference'],'!') !== FALSE) { + list($sheet1,$operand1Data['reference']) = explode('!',$operand1Data['reference']); + } else { + $sheet1 = ($pCellParent !== NULL) ? $pCellWorksheet->getTitle() : ''; + } + if (strpos($operand2Data['reference'],'!') !== FALSE) { + list($sheet2,$operand2Data['reference']) = explode('!',$operand2Data['reference']); + } else { + $sheet2 = $sheet1; + } + if ($sheet1 == $sheet2) { + if ($operand1Data['reference'] === NULL) { + if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { + $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value']; + } elseif (trim($operand1Data['reference']) == '') { + $operand1Data['reference'] = $pCell->getCoordinate(); + } else { + $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow(); + } + } + if ($operand2Data['reference'] === NULL) { + if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { + $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value']; + } elseif (trim($operand2Data['reference']) == '') { + $operand2Data['reference'] = $pCell->getCoordinate(); + } else { + $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow(); + } + } + + $oData = array_merge(explode(':',$operand1Data['reference']),explode(':',$operand2Data['reference'])); + $oCol = $oRow = array(); + foreach($oData as $oDatum) { + $oCR = PHPExcel_Cell::coordinateFromString($oDatum); + $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1; + $oRow[] = $oCR[1]; + } + $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow); + if ($pCellParent !== NULL) { + $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($sheet1), FALSE); + } else { + return $this->_raiseFormulaError('Unable to access Cell Reference'); + } + $stack->push('Cell Reference',$cellValue,$cellRef); + } else { + $stack->push('Error',PHPExcel_Calculation_Functions::REF(),NULL); + } + + break; + case '+' : // Addition + $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'plusEquals',$stack); + break; + case '-' : // Subtraction + $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'minusEquals',$stack); + break; + case '*' : // Multiplication + $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayTimesEquals',$stack); + break; + case '/' : // Division + $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'arrayRightDivide',$stack); + break; + case '^' : // Exponential + $this->_executeNumericBinaryOperation($cellID,$operand1,$operand2,$token,'power',$stack); + break; + case '&' : // Concatenation + // If either of the operands is a matrix, we need to treat them both as matrices + // (converting the other operand to a matrix if need be); then perform the required + // matrix operation + if (is_bool($operand1)) { + $operand1 = ($operand1) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + } + if (is_bool($operand2)) { + $operand2 = ($operand2) ? self::$_localeBoolean['TRUE'] : self::$_localeBoolean['FALSE']; + } + if ((is_array($operand1)) || (is_array($operand2))) { + // Ensure that both operands are arrays/matrices + self::_checkMatrixOperands($operand1,$operand2,2); + try { + // Convert operand 1 from a PHP array to a matrix + $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1); + // Perform the required operation against the operand 1 matrix, passing in operand 2 + $matrixResult = $matrix->concat($operand2); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + } else { + $result = '"'.str_replace('""','"',self::_unwrapResult($operand1,'"').self::_unwrapResult($operand2,'"')).'"'; + } + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result)); + $stack->push('Value',$result); + break; + case '|' : // Intersect + $rowIntersect = array_intersect_key($operand1,$operand2); + $cellIntersect = $oCol = $oRow = array(); + foreach(array_keys($rowIntersect) as $row) { + $oRow[] = $row; + foreach($rowIntersect[$row] as $col => $data) { + $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1; + $cellIntersect[$row] = array_intersect_key($operand1[$row],$operand2[$row]); + } + } + $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($cellIntersect)); + $stack->push('Value',$cellIntersect,$cellRef); + break; + } + + // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on + } elseif (($token === '~') || ($token === '%')) { +// echo 'Token is a unary operator
'; + if (($arg = $stack->pop()) === NULL) return $this->_raiseFormulaError('Internal error - Operand value missing from stack'); + $arg = $arg['value']; + if ($token === '~') { +// echo 'Token is a negation operator
'; + $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->_showValue($arg)); + $multiplier = -1; + } else { +// echo 'Token is a percentile operator
'; + $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->_showValue($arg)); + $multiplier = 0.01; + } + if (is_array($arg)) { + self::_checkMatrixOperands($arg,$multiplier,2); + try { + $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg); + $matrixResult = $matrix1->arrayTimesEquals($multiplier); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result)); + $stack->push('Value',$result); + } else { + $this->_executeNumericBinaryOperation($cellID,$multiplier,$arg,'*','arrayTimesEquals',$stack); + } + + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) { + $cellRef = NULL; +// echo 'Element '.$token.' is a Cell reference
'; + if (isset($matches[8])) { +// echo 'Reference is a Range of cells
'; + if ($pCell === NULL) { +// We can't access the range, so return a REF error + $cellValue = PHPExcel_Calculation_Functions::REF(); + } else { + $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10]; + if ($matches[2] > '') { + $matches[2] = trim($matches[2],"\"'"); + if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) { + // It's a Reference to an external workbook (not currently supported) + return $this->_raiseFormulaError('Unable to access External Workbook'); + } + $matches[2] = trim($matches[2],"\"'"); +// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
'; + $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]); + if ($pCellParent !== NULL) { + $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE); + } else { + return $this->_raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue)); +// $cellRef = $matches[2].'!'.$cellRef; + } else { +// echo '$cellRef='.$cellRef.' in current worksheet
'; + $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet'); + if ($pCellParent !== NULL) { + $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE); + } else { + return $this->_raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->_showTypeDetails($cellValue)); + } + } + } else { +// echo 'Reference is a single Cell
'; + if ($pCell === NULL) { +// We can't access the cell, so return a REF error + $cellValue = PHPExcel_Calculation_Functions::REF(); + } else { + $cellRef = $matches[6].$matches[7]; + if ($matches[2] > '') { + $matches[2] = trim($matches[2],"\"'"); + if ((strpos($matches[2],'[') !== FALSE) || (strpos($matches[2],']') !== FALSE)) { + // It's a Reference to an external workbook (not currently supported) + return $this->_raiseFormulaError('Unable to access External Workbook'); + } +// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'
'; + $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]); + if ($pCellParent !== NULL) { + $cellSheet = $this->_workbook->getSheetByName($matches[2]); + if ($cellSheet && $cellSheet->cellExists($cellRef)) { + $cellValue = $this->extractCellRange($cellRef, $this->_workbook->getSheetByName($matches[2]), FALSE); + $pCell->attach($pCellParent); + } else { + $cellValue = NULL; + } + } else { + return $this->_raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->_showTypeDetails($cellValue)); +// $cellRef = $matches[2].'!'.$cellRef; + } else { +// echo '$cellRef='.$cellRef.' in current worksheet
'; + $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet'); + if ($pCellParent->isDataSet($cellRef)) { + $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, FALSE); + $pCell->attach($pCellParent); + } else { + $cellValue = NULL; + } + $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->_showTypeDetails($cellValue)); + } + } + } + $stack->push('Value',$cellValue,$cellRef); + + // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) { +// echo 'Token is a function
'; + $functionName = $matches[1]; + $argCount = $stack->pop(); + $argCount = $argCount['value']; + if ($functionName != 'MKMATRIX') { + $this->_debugLog->writeDebugLog('Evaluating Function ', self::_localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); + } + if ((isset(self::$_PHPExcelFunctions[$functionName])) || (isset(self::$_controlFunctions[$functionName]))) { // function + if (isset(self::$_PHPExcelFunctions[$functionName])) { + $functionCall = self::$_PHPExcelFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$_PHPExcelFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$_PHPExcelFunctions[$functionName]['passCellReference']); + } elseif (isset(self::$_controlFunctions[$functionName])) { + $functionCall = self::$_controlFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$_controlFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$_controlFunctions[$functionName]['passCellReference']); + } + // get the arguments for this function +// echo 'Function '.$functionName.' expects '.$argCount.' arguments
'; + $args = $argArrayVals = array(); + for ($i = 0; $i < $argCount; ++$i) { + $arg = $stack->pop(); + $a = $argCount - $i - 1; + if (($passByReference) && + (isset(self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) && + (self::$_PHPExcelFunctions[$functionName]['passByReference'][$a])) { + if ($arg['reference'] === NULL) { + $args[] = $cellID; + if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($cellID); } + } else { + $args[] = $arg['reference']; + if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['reference']); } + } + } else { + $args[] = self::_unwrapResult($arg['value']); + if ($functionName != 'MKMATRIX') { $argArrayVals[] = $this->_showValue($arg['value']); } + } + } + // Reverse the order of the arguments + krsort($args); + if (($passByReference) && ($argCount == 0)) { + $args[] = $cellID; + $argArrayVals[] = $this->_showValue($cellID); + } +// echo 'Arguments are: '; +// print_r($args); +// echo '
'; + if ($functionName != 'MKMATRIX') { + if ($this->_debugLog->getWriteDebugLog()) { + krsort($argArrayVals); + $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', implode(self::$_localeArgumentSeparator.' ',PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )'); + } + } + // Process each argument in turn, building the return value as an array +// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) { +// $operand1 = $args[1]; +// $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->_showValue($operand1)); +// $result = array(); +// $row = 0; +// foreach($operand1 as $args) { +// if (is_array($args)) { +// foreach($args as $arg) { +// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($arg), ' )'); +// $r = call_user_func_array($functionCall,$arg); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); +// $result[$row][] = $r; +// } +// ++$row; +// } else { +// $this->_debugLog->writeDebugLog('Evaluating ', self::_localeFunc($functionName), '( ', $this->_showValue($args), ' )'); +// $r = call_user_func_array($functionCall,$args); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($r)); +// $result[] = $r; +// } +// } +// } else { + // Process the argument with the appropriate function call + if ($passCellReference) { + $args[] = $pCell; + } + if (strpos($functionCall,'::') !== FALSE) { + $result = call_user_func_array(explode('::',$functionCall),$args); + } else { + foreach($args as &$arg) { + $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg); + } + unset($arg); + $result = call_user_func_array($functionCall,$args); + } +// } + if ($functionName != 'MKMATRIX') { + $this->_debugLog->writeDebugLog('Evaluation Result for ', self::_localeFunc($functionName), '() function call is ', $this->_showTypeDetails($result)); + } + $stack->push('Value',self::_wrapResult($result)); + } + + } else { + // if the token is a number, boolean, string or an Excel error, push it onto the stack + if (isset(self::$_ExcelConstants[strtoupper($token)])) { + $excelConstant = strtoupper($token); +// echo 'Token is a PHPExcel constant: '.$excelConstant.'
'; + $stack->push('Constant Value',self::$_ExcelConstants[$excelConstant]); + $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->_showTypeDetails(self::$_ExcelConstants[$excelConstant])); + } elseif ((is_numeric($token)) || ($token === NULL) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) { +// echo 'Token is a number, boolean, string, null or an Excel error
'; + $stack->push('Value',$token); + // if the token is a named range, push the named range name onto the stack + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) { +// echo 'Token is a named range
'; + $namedRange = $matches[6]; +// echo 'Named Range is '.$namedRange.'
'; + $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange); + $cellValue = $this->extractNamedRange($namedRange, ((NULL !== $pCell) ? $pCellWorksheet : NULL), FALSE); + $pCell->attach($pCellParent); + $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->_showTypeDetails($cellValue)); + $stack->push('Named Range',$cellValue,$namedRange); + } else { + return $this->_raiseFormulaError("undefined variable '$token'"); + } + } + } + // when we're out of tokens, the stack should have a single element, the final result + if ($stack->count() != 1) return $this->_raiseFormulaError("internal error"); + $output = $stack->pop(); + $output = $output['value']; + +// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { +// return array_shift(PHPExcel_Calculation_Functions::flattenArray($output)); +// } + return $output; + } // function _processTokenStack() + + + private function _validateBinaryOperand($cellID, &$operand, &$stack) { + if (is_array($operand)) { + if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) { + do { + $operand = array_pop($operand); + } while (is_array($operand)); + } + } + // Numbers, matrices and booleans can pass straight through, as they're already valid + if (is_string($operand)) { + // We only need special validations for the operand if it is a string + // Start by stripping off the quotation marks we use to identify true excel string values internally + if ($operand > '' && $operand{0} == '"') { $operand = self::_unwrapResult($operand); } + // If the string is a numeric value, we treat it as a numeric, so no further testing + if (!is_numeric($operand)) { + // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations + if ($operand > '' && $operand{0} == '#') { + $stack->push('Value', $operand); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($operand)); + return FALSE; + } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) { + // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations + $stack->push('Value', '#VALUE!'); + $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->_showTypeDetails('#VALUE!')); + return FALSE; + } + } + } + + // return a true if the value of the operand is one that we can use in normal binary operations + return TRUE; + } // function _validateBinaryOperand() + + + private function _executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays=FALSE) { + // If we're dealing with matrix operations, we want a matrix result + if ((is_array($operand1)) || (is_array($operand2))) { + $result = array(); + if ((is_array($operand1)) && (!is_array($operand2))) { + foreach($operand1 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2)); + $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2,$operation,$stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } elseif ((!is_array($operand1)) && (is_array($operand2))) { + foreach($operand2 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operand1), ' ', $operation, ' ', $this->_showValue($operandData)); + $this->_executeBinaryComparisonOperation($cellID,$operand1,$operandData,$operation,$stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } else { + if (!$recursingArrays) { self::_checkMatrixOperands($operand1,$operand2,2); } + foreach($operand1 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->_showValue($operandData), ' ', $operation, ' ', $this->_showValue($operand2[$x])); + $this->_executeBinaryComparisonOperation($cellID,$operandData,$operand2[$x],$operation,$stack,TRUE); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } + // Log the result details + $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->_showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Array',$result); + return TRUE; + } + + // Simple validate the two operands if they are string values + if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { $operand1 = self::_unwrapResult($operand1); } + if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { $operand2 = self::_unwrapResult($operand2); } + + // Use case insensitive comparaison if not OpenOffice mode + if (PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) + { + if (is_string($operand1)) { + $operand1 = strtoupper($operand1); + } + + if (is_string($operand2)) { + $operand2 = strtoupper($operand2); + } + } + + $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE; + + // execute the necessary operation + switch ($operation) { + // Greater than + case '>': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0; + } else { + $result = ($operand1 > $operand2); + } + break; + // Less than + case '<': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0; + } else { + $result = ($operand1 < $operand2); + } + break; + // Equality + case '=': + $result = ($operand1 == $operand2); + break; + // Greater than or equal + case '>=': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0; + } else { + $result = ($operand1 >= $operand2); + } + break; + // Less than or equal + case '<=': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0; + } else { + $result = ($operand1 <= $operand2); + } + break; + // Inequality + case '<>': + $result = ($operand1 != $operand2); + break; + } + + // Log the result details + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Value',$result); + return TRUE; + } // function _executeBinaryComparisonOperation() + + /** + * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters + * @param string $str1 + * @param string $str2 + * @return integer + */ + private function strcmpLowercaseFirst($str1, $str2) + { + $from = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; + $to = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; + $inversedStr1 = strtr($str1, $from, $to); + $inversedStr2 = strtr($str2, $from, $to); + + return strcmp($inversedStr1, $inversedStr2); + } + + private function _executeNumericBinaryOperation($cellID,$operand1,$operand2,$operation,$matrixFunction,&$stack) { + // Validate the two operands + if (!$this->_validateBinaryOperand($cellID,$operand1,$stack)) return FALSE; + if (!$this->_validateBinaryOperand($cellID,$operand2,$stack)) return FALSE; + + // If either of the operands is a matrix, we need to treat them both as matrices + // (converting the other operand to a matrix if need be); then perform the required + // matrix operation + if ((is_array($operand1)) || (is_array($operand2))) { + // Ensure that both operands are arrays/matrices of the same size + self::_checkMatrixOperands($operand1, $operand2, 2); + + try { + // Convert operand 1 from a PHP array to a matrix + $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1); + // Perform the required operation against the operand 1 matrix, passing in operand 2 + $matrixResult = $matrix->$matrixFunction($operand2); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + } else { + if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) && + ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) || + (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) { + $result = PHPExcel_Calculation_Functions::VALUE(); + } else { + // If we're dealing with non-matrix operations, execute the necessary operation + switch ($operation) { + // Addition + case '+': + $result = $operand1 + $operand2; + break; + // Subtraction + case '-': + $result = $operand1 - $operand2; + break; + // Multiplication + case '*': + $result = $operand1 * $operand2; + break; + // Division + case '/': + if ($operand2 == 0) { + // Trap for Divide by Zero error + $stack->push('Value','#DIV/0!'); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails('#DIV/0!')); + return FALSE; + } else { + $result = $operand1 / $operand2; + } + break; + // Power + case '^': + $result = pow($operand1, $operand2); + break; + } + } + } + + // Log the result details + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->_showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Value',$result); + return TRUE; + } // function _executeNumericBinaryOperation() + + + // trigger an error, but nicely, if need be + protected function _raiseFormulaError($errorMessage) { + $this->formulaError = $errorMessage; + $this->_cyclicReferenceStack->clear(); + if (!$this->suppressFormulaErrors) throw new PHPExcel_Calculation_Exception($errorMessage); + trigger_error($errorMessage, E_USER_ERROR); + } // function _raiseFormulaError() + + + /** + * Extract range values + * + * @param string &$pRange String based range representation + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param boolean $resetLog Flag indicating whether calculation log should be reset or not + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. + * @throws PHPExcel_Calculation_Exception + */ + public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = NULL, $resetLog = TRUE) { + // Return value + $returnValue = array (); + +// echo 'extractCellRange('.$pRange.')',PHP_EOL; + if ($pSheet !== NULL) { + $pSheetName = $pSheet->getTitle(); +// echo 'Passed sheet name is '.$pSheetName.PHP_EOL; +// echo 'Range reference is '.$pRange.PHP_EOL; + if (strpos ($pRange, '!') !== false) { +// echo '$pRange reference includes sheet reference',PHP_EOL; + list($pSheetName,$pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); +// echo 'New sheet name is '.$pSheetName,PHP_EOL; +// echo 'Adjusted Range reference is '.$pRange,PHP_EOL; + $pSheet = $this->_workbook->getSheetByName($pSheetName); + } + + // Extract range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); + $pRange = $pSheetName.'!'.$pRange; + if (!isset($aReferences[1])) { + // Single cell in range + sscanf($aReferences[0],'%[A-Z]%d', $currentCol, $currentRow); + $cellValue = NULL; + if ($pSheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = NULL; + } + } else { + // Extract cell data for all cells in the range + foreach ($aReferences as $reference) { + // Extract range + sscanf($reference,'%[A-Z]%d', $currentCol, $currentRow); + $cellValue = NULL; + if ($pSheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = NULL; + } + } + } + } + + // Return + return $returnValue; + } // function extractCellRange() + + + /** + * Extract range values + * + * @param string &$pRange String based range representation + * @param PHPExcel_Worksheet $pSheet Worksheet + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. + * @param boolean $resetLog Flag indicating whether calculation log should be reset or not + * @throws PHPExcel_Calculation_Exception + */ + public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = NULL, $resetLog = TRUE) { + // Return value + $returnValue = array (); + +// echo 'extractNamedRange('.$pRange.')
'; + if ($pSheet !== NULL) { + $pSheetName = $pSheet->getTitle(); +// echo 'Current sheet name is '.$pSheetName.'
'; +// echo 'Range reference is '.$pRange.'
'; + if (strpos ($pRange, '!') !== false) { +// echo '$pRange reference includes sheet reference',PHP_EOL; + list($pSheetName,$pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); +// echo 'New sheet name is '.$pSheetName,PHP_EOL; +// echo 'Adjusted Range reference is '.$pRange,PHP_EOL; + $pSheet = $this->_workbook->getSheetByName($pSheetName); + } + + // Named range? + $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet); + if ($namedRange !== NULL) { + $pSheet = $namedRange->getWorksheet(); +// echo 'Named Range '.$pRange.' ('; + $pRange = $namedRange->getRange(); + $splitRange = PHPExcel_Cell::splitRange($pRange); + // Convert row and column references + if (ctype_alpha($splitRange[0][0])) { + $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow(); + } elseif(ctype_digit($splitRange[0][0])) { + $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; + } +// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'
'; + +// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) { +// if (!$namedRange->getLocalOnly()) { +// $pSheet = $namedRange->getWorksheet(); +// } else { +// return $returnValue; +// } +// } + } else { + return PHPExcel_Calculation_Functions::REF(); + } + + // Extract range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); +// var_dump($aReferences); + if (!isset($aReferences[1])) { + // Single cell (or single column or row) in range + list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]); + $cellValue = NULL; + if ($pSheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = NULL; + } + } else { + // Extract cell data for all cells in the range + foreach ($aReferences as $reference) { + // Extract range + list($currentCol,$currentRow) = PHPExcel_Cell::coordinateFromString($reference); +// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'
'; + $cellValue = NULL; + if ($pSheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = NULL; + } + } + } +// print_r($returnValue); +// echo '
'; + } + + // Return + return $returnValue; + } // function extractNamedRange() + + + /** + * Is a specific function implemented? + * + * @param string $pFunction Function Name + * @return boolean + */ + public function isImplemented($pFunction = '') { + $pFunction = strtoupper ($pFunction); + if (isset(self::$_PHPExcelFunctions[$pFunction])) { + return (self::$_PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY'); + } else { + return FALSE; + } + } // function isImplemented() + + + /** + * Get a list of all implemented functions as an array of function objects + * + * @return array of PHPExcel_Calculation_Function + */ + public function listFunctions() { + // Return value + $returnValue = array(); + // Loop functions + foreach(self::$_PHPExcelFunctions as $functionName => $function) { + if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { + $returnValue[$functionName] = new PHPExcel_Calculation_Function($function['category'], + $functionName, + $function['functionCall'] + ); + } + } + + // Return + return $returnValue; + } // function listFunctions() + + + /** + * Get a list of all Excel function names + * + * @return array + */ + public function listAllFunctionNames() { + return array_keys(self::$_PHPExcelFunctions); + } // function listAllFunctionNames() + + /** + * Get a list of implemented Excel function names + * + * @return array + */ + public function listFunctionNames() { + // Return value + $returnValue = array(); + // Loop functions + foreach(self::$_PHPExcelFunctions as $functionName => $function) { + if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { + $returnValue[] = $functionName; + } + } + + // Return + return $returnValue; + } // function listFunctionNames() + +} // class PHPExcel_Calculation + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php new file mode 100644 index 00000000..c3e86d76 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php @@ -0,0 +1,725 @@ + $criteriaName) { + $testCondition = array(); + $testConditionCount = 0; + foreach($criteria as $row => $criterion) { + if ($criterion[$key] > '') { + $testCondition[] = '[:'.$criteriaName.']'.PHPExcel_Calculation_Functions::_ifCondition($criterion[$key]); + $testConditionCount++; + } + } + if ($testConditionCount > 1) { + $testConditions[] = 'OR('.implode(',',$testCondition).')'; + $testConditionsCount++; + } elseif($testConditionCount == 1) { + $testConditions[] = $testCondition[0]; + $testConditionsCount++; + } + } + + if ($testConditionsCount > 1) { + $testConditionSet = 'AND('.implode(',',$testConditions).')'; + } elseif($testConditionsCount == 1) { + $testConditionSet = $testConditions[0]; + } + + // Loop through each row of the database + foreach($database as $dataRow => $dataValues) { + // Substitute actual values from the database row for our [:placeholders] + $testConditionList = $testConditionSet; + foreach($criteriaNames as $key => $criteriaName) { + $k = array_search($criteriaName,$fieldNames); + if (isset($dataValues[$k])) { + $dataValue = $dataValues[$k]; + $dataValue = (is_string($dataValue)) ? PHPExcel_Calculation::_wrapResult(strtoupper($dataValue)) : $dataValue; + $testConditionList = str_replace('[:'.$criteriaName.']',$dataValue,$testConditionList); + } + } + // evaluate the criteria against the row data + $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList); + // If the row failed to meet the criteria, remove it from the database + if (!$result) { + unset($database[$dataRow]); + } + } + + return $database; + } + + + /** + * DAVERAGE + * + * Averages the values in a column of a list or database that match conditions you specify. + * + * Excel Function: + * DAVERAGE(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DAVERAGE($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::AVERAGE($colData); + } // function DAVERAGE() + + + /** + * DCOUNT + * + * Counts the cells that contain numbers in a column of a list or database that match conditions + * that you specify. + * + * Excel Function: + * DCOUNT(database,[field],criteria) + * + * Excel Function: + * DAVERAGE(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return integer + * + * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the + * database that match the criteria. + * + */ + public static function DCOUNT($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::COUNT($colData); + } // function DCOUNT() + + + /** + * DCOUNTA + * + * Counts the nonblank cells in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DCOUNTA(database,[field],criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return integer + * + * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the + * database that match the criteria. + * + */ + public static function DCOUNTA($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::COUNTA($colData); + } // function DCOUNTA() + + + /** + * DGET + * + * Extracts a single value from a column of a list or database that matches conditions that you + * specify. + * + * Excel Function: + * DGET(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return mixed + * + */ + public static function DGET($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + if (count($colData) > 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return $colData[0]; + } // function DGET() + + + /** + * DMAX + * + * Returns the largest number in a column of a list or database that matches conditions you that + * specify. + * + * Excel Function: + * DMAX(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DMAX($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::MAX($colData); + } // function DMAX() + + + /** + * DMIN + * + * Returns the smallest number in a column of a list or database that matches conditions you that + * specify. + * + * Excel Function: + * DMIN(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DMIN($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::MIN($colData); + } // function DMIN() + + + /** + * DPRODUCT + * + * Multiplies the values in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DPRODUCT(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DPRODUCT($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_MathTrig::PRODUCT($colData); + } // function DPRODUCT() + + + /** + * DSTDEV + * + * Estimates the standard deviation of a population based on a sample by using the numbers in a + * column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSTDEV(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSTDEV($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::STDEV($colData); + } // function DSTDEV() + + + /** + * DSTDEVP + * + * Calculates the standard deviation of a population based on the entire population by using the + * numbers in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSTDEVP(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSTDEVP($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::STDEVP($colData); + } // function DSTDEVP() + + + /** + * DSUM + * + * Adds the numbers in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSUM(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSUM($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_MathTrig::SUM($colData); + } // function DSUM() + + + /** + * DVAR + * + * Estimates the variance of a population based on a sample by using the numbers in a column + * of a list or database that match conditions that you specify. + * + * Excel Function: + * DVAR(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DVAR($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::VARFunc($colData); + } // function DVAR() + + + /** + * DVARP + * + * Calculates the variance of a population based on the entire population by using the numbers + * in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DVARP(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DVARP($database,$field,$criteria) { + $field = self::__fieldExtract($database,$field); + if (is_null($field)) { + return NULL; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::__filter($database,$criteria); + // extract an array of values for the requested column + $colData = array(); + foreach($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::VARP($colData); + } // function DVARP() + + +} // class PHPExcel_Calculation_Database diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php new file mode 100644 index 00000000..debd1315 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php @@ -0,0 +1,1475 @@ +format('m'); + $oYear = (int) $PHPDateObject->format('Y'); + + $adjustmentMonthsString = (string) $adjustmentMonths; + if ($adjustmentMonths > 0) { + $adjustmentMonthsString = '+'.$adjustmentMonths; + } + if ($adjustmentMonths != 0) { + $PHPDateObject->modify($adjustmentMonthsString.' months'); + } + $nMonth = (int) $PHPDateObject->format('m'); + $nYear = (int) $PHPDateObject->format('Y'); + + $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); + if ($monthDiff != $adjustmentMonths) { + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-'.$adjustDays.' days'; + $PHPDateObject->modify($adjustDaysString); + } + return $PHPDateObject; + } // function _adjustDateByMonths() + + + /** + * DATETIMENOW + * + * Returns the current date and time. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * NOW() + * + * @access public + * @category Date/Time Functions + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATETIMENOW() { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $retValue = False; + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time()); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + $retValue = (integer) time(); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + $retValue = new DateTime(); + break; + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } // function DATETIMENOW() + + + /** + * DATENOW + * + * Returns the current date. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TODAY() + * + * @access public + * @category Date/Time Functions + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATENOW() { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $retValue = False; + $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time())); + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + $retValue = (float) $excelDateTime; + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime); + break; + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } // function DATENOW() + + + /** + * DATE + * + * The DATE function returns a value that represents a particular date. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * DATE(year,month,day) + * + * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function. + * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, + * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. + * + * @access public + * @category Date/Time Functions + * @param integer $year The value of the year argument can include one to four digits. + * Excel interprets the year argument according to the configured + * date system: 1900 or 1904. + * If year is between 0 (zero) and 1899 (inclusive), Excel adds that + * value to 1900 to calculate the year. For example, DATE(108,1,2) + * returns January 2, 2008 (1900+108). + * If year is between 1900 and 9999 (inclusive), Excel uses that + * value as the year. For example, DATE(2008,1,2) returns January 2, + * 2008. + * If year is less than 0 or is 10000 or greater, Excel returns the + * #NUM! error value. + * @param integer $month A positive or negative integer representing the month of the year + * from 1 to 12 (January to December). + * If month is greater than 12, month adds that number of months to + * the first month in the year specified. For example, DATE(2008,14,2) + * returns the serial number representing February 2, 2009. + * If month is less than 1, month subtracts the magnitude of that + * number of months, plus 1, from the first month in the year + * specified. For example, DATE(2008,-3,2) returns the serial number + * representing September 2, 2007. + * @param integer $day A positive or negative integer representing the day of the month + * from 1 to 31. + * If day is greater than the number of days in the month specified, + * day adds that number of days to the first day in the month. For + * example, DATE(2008,1,35) returns the serial number representing + * February 4, 2008. + * If day is less than 1, day subtracts the magnitude that number of + * days, plus one, from the first day of the month specified. For + * example, DATE(2008,1,-15) returns the serial number representing + * December 16, 2007. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATE($year = 0, $month = 1, $day = 1) { + $year = PHPExcel_Calculation_Functions::flattenSingleValue($year); + $month = PHPExcel_Calculation_Functions::flattenSingleValue($month); + $day = PHPExcel_Calculation_Functions::flattenSingleValue($day); + + if (($month !== NULL) && (!is_numeric($month))) { + $month = PHPExcel_Shared_Date::monthStringToNumber($month); + } + + if (($day !== NULL) && (!is_numeric($day))) { + $day = PHPExcel_Shared_Date::dayStringToNumber($day); + } + + $year = ($year !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0; + $month = ($month !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0; + $day = ($day !== NULL) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0; + if ((!is_numeric($year)) || + (!is_numeric($month)) || + (!is_numeric($day))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $year = (integer) $year; + $month = (integer) $month; + $day = (integer) $day; + + $baseYear = PHPExcel_Shared_Date::getExcelCalendar(); + // Validate parameters + if ($year < ($baseYear-1900)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (($year < $baseYear) && ($year >= ($baseYear-1900))) { + $year += 1900; + } + + if ($month < 1) { + // Handle year/month adjustment if month < 1 + --$month; + $year += ceil($month / 12) - 1; + $month = 13 - abs($month % 12); + } elseif ($month > 12) { + // Handle year/month adjustment if month > 12 + $year += floor($month / 12); + $month = ($month % 12); + } + + // Re-validate the year parameter after adjustments + if (($year < $baseYear) || ($year >= 10000)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day); + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue); + } + } // function DATE() + + + /** + * TIME + * + * The TIME function returns a value that represents a particular time. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TIME(hour,minute,second) + * + * @access public + * @category Date/Time Functions + * @param integer $hour A number from 0 (zero) to 32767 representing the hour. + * Any value greater than 23 will be divided by 24 and the remainder + * will be treated as the hour value. For example, TIME(27,0,0) = + * TIME(3,0,0) = .125 or 3:00 AM. + * @param integer $minute A number from 0 to 32767 representing the minute. + * Any value greater than 59 will be converted to hours and minutes. + * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. + * @param integer $second A number from 0 to 32767 representing the second. + * Any value greater than 59 will be converted to hours, minutes, + * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 + * or 12:33:20 AM + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function TIME($hour = 0, $minute = 0, $second = 0) { + $hour = PHPExcel_Calculation_Functions::flattenSingleValue($hour); + $minute = PHPExcel_Calculation_Functions::flattenSingleValue($minute); + $second = PHPExcel_Calculation_Functions::flattenSingleValue($second); + + if ($hour == '') { $hour = 0; } + if ($minute == '') { $minute = 0; } + if ($second == '') { $second = 0; } + + if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $hour = (integer) $hour; + $minute = (integer) $minute; + $second = (integer) $second; + + if ($second < 0) { + $minute += floor($second / 60); + $second = 60 - abs($second % 60); + if ($second == 60) { $second = 0; } + } elseif ($second >= 60) { + $minute += floor($second / 60); + $second = $second % 60; + } + if ($minute < 0) { + $hour += floor($minute / 60); + $minute = 60 - abs($minute % 60); + if ($minute == 60) { $minute = 0; } + } elseif ($minute >= 60) { + $hour += floor($minute / 60); + $minute = $minute % 60; + } + + if ($hour > 23) { + $hour = $hour % 24; + } elseif ($hour < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + $date = 0; + $calendar = PHPExcel_Shared_Date::getExcelCalendar(); + if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) { + $date = 1; + } + return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + $dayAdjust = 0; + if ($hour < 0) { + $dayAdjust = floor($hour / 24); + $hour = 24 - abs($hour % 24); + if ($hour == 24) { $hour = 0; } + } elseif ($hour >= 24) { + $dayAdjust = floor($hour / 24); + $hour = $hour % 24; + } + $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second); + if ($dayAdjust != 0) { + $phpDateObject->modify($dayAdjust.' days'); + } + return $phpDateObject; + } + } // function TIME() + + + /** + * DATEVALUE + * + * Returns a value that represents a particular date. + * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp + * value. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * DATEVALUE(dateValue) + * + * @access public + * @category Date/Time Functions + * @param string $dateValue Text that represents a date in a Microsoft Excel date format. + * For example, "1/30/2008" or "30-Jan-2008" are text strings within + * quotation marks that represent dates. Using the default date + * system in Excel for Windows, date_text must represent a date from + * January 1, 1900, to December 31, 9999. Using the default date + * system in Excel for the Macintosh, date_text must represent a date + * from January 1, 1904, to December 31, 9999. DATEVALUE returns the + * #VALUE! error value if date_text is out of this range. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATEVALUE($dateValue = 1) { + $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue),'"'); + // Strip any ordinals because they're allowed in Excel (English only) + $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui','$1$3',$dateValue); + // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) + $dateValue = str_replace(array('/','.','-',' '),array(' ',' ',' ',' '),$dateValue); + + $yearFound = false; + $t1 = explode(' ',$dateValue); + foreach($t1 as &$t) { + if ((is_numeric($t)) && ($t > 31)) { + if ($yearFound) { + return PHPExcel_Calculation_Functions::VALUE(); + } else { + if ($t < 100) { $t += 1900; } + $yearFound = true; + } + } + } + if ((count($t1) == 1) && (strpos($t,':') != false)) { + // We've been fed a time value without any date + return 0.0; + } elseif (count($t1) == 2) { + // We only have two parts of the date: either day/month or month/year + if ($yearFound) { + array_unshift($t1,1); + } else { + array_push($t1,date('Y')); + } + } + unset($t); + $dateValue = implode(' ',$t1); + + $PHPDateArray = date_parse($dateValue); + if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) { + $testVal1 = strtok($dateValue,'- '); + if ($testVal1 !== False) { + $testVal2 = strtok('- '); + if ($testVal2 !== False) { + $testVal3 = strtok('- '); + if ($testVal3 === False) { + $testVal3 = strftime('%Y'); + } + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3); + if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) { + $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3); + if (($PHPDateArray === False) || ($PHPDateArray['error_count'] > 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + } + + if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) { + // Execute function + if ($PHPDateArray['year'] == '') { $PHPDateArray['year'] = strftime('%Y'); } + if ($PHPDateArray['year'] < 1900) + return PHPExcel_Calculation_Functions::VALUE(); + if ($PHPDateArray['month'] == '') { $PHPDateArray['month'] = strftime('%m'); } + if ($PHPDateArray['day'] == '') { $PHPDateArray['day'] = strftime('%d'); } + $excelDateValue = floor(PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second'])); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00'); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function DATEVALUE() + + + /** + * TIMEVALUE + * + * Returns a value that represents a particular time. + * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp + * value. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TIMEVALUE(timeValue) + * + * @access public + * @category Date/Time Functions + * @param string $timeValue A text string that represents a time in any one of the Microsoft + * Excel time formats; for example, "6:45 PM" and "18:45" text strings + * within quotation marks that represent time. + * Date information in time_text is ignored. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function TIMEVALUE($timeValue) { + $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue),'"'); + $timeValue = str_replace(array('/','.'),array('-','-'),$timeValue); + + $PHPDateArray = date_parse($timeValue); + if (($PHPDateArray !== False) && ($PHPDateArray['error_count'] == 0)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($PHPDateArray['year'],$PHPDateArray['month'],$PHPDateArray['day'],$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']); + } else { + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900,1,1,$PHPDateArray['hour'],$PHPDateArray['minute'],$PHPDateArray['second']) - 1; + } + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TIMEVALUE() + + + /** + * DATEDIF + * + * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object + * or a standard date string + * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object + * or a standard date string + * @param string $unit + * @return integer Interval between the dates + */ + public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit)); + + if (is_string($startDate = self::_getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::_getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Validate parameters + if ($startDate >= $endDate) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $difference = $endDate - $startDate; + + $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate); + $startDays = $PHPStartDateObject->format('j'); + $startMonths = $PHPStartDateObject->format('n'); + $startYears = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + $endDays = $PHPEndDateObject->format('j'); + $endMonths = $PHPEndDateObject->format('n'); + $endYears = $PHPEndDateObject->format('Y'); + + $retVal = PHPExcel_Calculation_Functions::NaN(); + switch ($unit) { + case 'D': + $retVal = intval($difference); + break; + case 'M': + $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12); + // We're only interested in full months + if ($endDays < $startDays) { + --$retVal; + } + break; + case 'Y': + $retVal = intval($endYears - $startYears); + // We're only interested in full months + if ($endMonths < $startMonths) { + --$retVal; + } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) { + --$retVal; + } + break; + case 'MD': + if ($endDays < $startDays) { + $retVal = $endDays; + $PHPEndDateObject->modify('-'.$endDays.' days'); + $adjustDays = $PHPEndDateObject->format('j'); + if ($adjustDays > $startDays) { + $retVal += ($adjustDays - $startDays); + } + } else { + $retVal = $endDays - $startDays; + } + break; + case 'YM': + $retVal = intval($endMonths - $startMonths); + if ($retVal < 0) $retVal = 12 + $retVal; + // We're only interested in full months + if ($endDays < $startDays) { + --$retVal; + } + break; + case 'YD': + $retVal = intval($difference); + if ($endYears > $startYears) { + while ($endYears > $startYears) { + $PHPEndDateObject->modify('-1 year'); + $endYears = $PHPEndDateObject->format('Y'); + } + $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z'); + if ($retVal < 0) { $retVal += 365; } + } + break; + default: + $retVal = PHPExcel_Calculation_Functions::NaN(); + } + return $retVal; + } // function DATEDIF() + + + /** + * DAYS360 + * + * Returns the number of days between two dates based on a 360-day year (twelve 30-day months), + * which is used in some accounting calculations. Use this function to help compute payments if + * your accounting system is based on twelve 30-day months. + * + * Excel Function: + * DAYS360(startDate,endDate[,method]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param boolean $method US or European Method + * FALSE or omitted: U.S. (NASD) method. If the starting date is + * the last day of a month, it becomes equal to the 30th of the + * same month. If the ending date is the last day of a month and + * the starting date is earlier than the 30th of a month, the + * ending date becomes equal to the 1st of the next month; + * otherwise the ending date becomes equal to the 30th of the + * same month. + * TRUE: European method. Starting dates and ending dates that + * occur on the 31st of a month become equal to the 30th of the + * same month. + * @return integer Number of days between start date and end date + */ + public static function DAYS360($startDate = 0, $endDate = 0, $method = false) { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + + if (is_string($startDate = self::_getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::_getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (!is_bool($method)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate); + $startDay = $PHPStartDateObject->format('j'); + $startMonth = $PHPStartDateObject->format('n'); + $startYear = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + $endDay = $PHPEndDateObject->format('j'); + $endMonth = $PHPEndDateObject->format('n'); + $endYear = $PHPEndDateObject->format('Y'); + + return self::_dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); + } // function DAYS360() + + + /** + * YEARFRAC + * + * Calculates the fraction of the year represented by the number of whole days between two dates + * (the start_date and the end_date). + * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or + * obligations to assign to a specific term. + * + * Excel Function: + * YEARFRAC(startDate,endDate[,method]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param integer $method Method used for the calculation + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float fraction of the year + */ + public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + $method = PHPExcel_Calculation_Functions::flattenSingleValue($method); + + if (is_string($startDate = self::_getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::_getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) { + switch($method) { + case 0 : + return self::DAYS360($startDate,$endDate) / 360; + case 1 : + $days = self::DATEDIF($startDate,$endDate); + $startYear = self::YEAR($startDate); + $endYear = self::YEAR($endDate); + $years = $endYear - $startYear + 1; + $leapDays = 0; + if ($years == 1) { + if (self::_isLeapYear($endYear)) { + $startMonth = self::MONTHOFYEAR($startDate); + $endMonth = self::MONTHOFYEAR($endDate); + $endDay = self::DAYOFMONTH($endDate); + if (($startMonth < 3) || + (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) { + $leapDays += 1; + } + } + } else { + for($year = $startYear; $year <= $endYear; ++$year) { + if ($year == $startYear) { + $startMonth = self::MONTHOFYEAR($startDate); + $startDay = self::DAYOFMONTH($startDate); + if ($startMonth < 3) { + $leapDays += (self::_isLeapYear($year)) ? 1 : 0; + } + } elseif($year == $endYear) { + $endMonth = self::MONTHOFYEAR($endDate); + $endDay = self::DAYOFMONTH($endDate); + if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) { + $leapDays += (self::_isLeapYear($year)) ? 1 : 0; + } + } else { + $leapDays += (self::_isLeapYear($year)) ? 1 : 0; + } + } + if ($years == 2) { + if (($leapDays == 0) && (self::_isLeapYear($startYear)) && ($days > 365)) { + $leapDays = 1; + } elseif ($days < 366) { + $years = 1; + } + } + $leapDays /= $years; + } + return $days / (365 + $leapDays); + case 2 : + return self::DATEDIF($startDate,$endDate) / 360; + case 3 : + return self::DATEDIF($startDate,$endDate) / 365; + case 4 : + return self::DAYS360($startDate,$endDate,True) / 360; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function YEARFRAC() + + + /** + * NETWORKDAYS + * + * Returns the number of whole working days between start_date and end_date. Working days + * exclude weekends and any dates identified in holidays. + * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days + * worked during a specific term. + * + * Excel Function: + * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date + * timestamp (integer), PHP DateTime object, or a standard date + * strings that will be excluded from the working calendar, such + * as state and federal holidays and floating holidays. + * @return integer Interval between the dates + */ + public static function NETWORKDAYS($startDate,$endDate) { + // Retrieve the mandatory start and end date that are referenced in the function definition + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days + $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + array_shift($dateArgs); + array_shift($dateArgs); + + // Validate the start and end dates + if (is_string($startDate = $sDate = self::_getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $startDate = (float) floor($startDate); + if (is_string($endDate = $eDate = self::_getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $endDate = (float) floor($endDate); + + if ($sDate > $eDate) { + $startDate = $eDate; + $endDate = $sDate; + } + + // Execute function + $startDoW = 6 - self::DAYOFWEEK($startDate,2); + if ($startDoW < 0) { $startDoW = 0; } + $endDoW = self::DAYOFWEEK($endDate,2); + if ($endDoW >= 6) { $endDoW = 0; } + + $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5; + $partWeekDays = $endDoW + $startDoW; + if ($partWeekDays > 5) { + $partWeekDays -= 5; + } + + // Test any extra holiday parameters + $holidayCountedArray = array(); + foreach ($dateArgs as $holidayDate) { + if (is_string($holidayDate = self::_getDateValue($holidayDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if ((self::DAYOFWEEK($holidayDate,2) < 6) && (!in_array($holidayDate,$holidayCountedArray))) { + --$partWeekDays; + $holidayCountedArray[] = $holidayDate; + } + } + } + + if ($sDate > $eDate) { + return 0 - ($wholeWeekDays + $partWeekDays); + } + return $wholeWeekDays + $partWeekDays; + } // function NETWORKDAYS() + + + /** + * WORKDAY + * + * Returns the date that is the indicated number of working days before or after a date (the + * starting date). Working days exclude weekends and any dates identified as holidays. + * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected + * delivery times, or the number of days of work performed. + * + * Excel Function: + * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param integer $endDays The number of nonweekend and nonholiday days before or after + * startDate. A positive value for days yields a future date; a + * negative value yields a past date. + * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date + * timestamp (integer), PHP DateTime object, or a standard date + * strings that will be excluded from the working calendar, such + * as state and federal holidays and floating holidays. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function WORKDAY($startDate,$endDays) { + // Retrieve the mandatory start date and days that are referenced in the function definition + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays); + // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days + $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + array_shift($dateArgs); + array_shift($dateArgs); + + if ((is_string($startDate = self::_getDateValue($startDate))) || (!is_numeric($endDays))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $startDate = (float) floor($startDate); + $endDays = (int) floor($endDays); + // If endDays is 0, we always return startDate + if ($endDays == 0) { return $startDate; } + + $decrementing = ($endDays < 0) ? True : False; + + // Adjust the start date if it falls over a weekend + + $startDoW = self::DAYOFWEEK($startDate,3); + if (self::DAYOFWEEK($startDate,3) >= 5) { + $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW; + ($decrementing) ? $endDays++ : $endDays--; + } + + // Add endDays + $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5); + + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::DAYOFWEEK($endDate,3); + if ($endDoW >= 5) { + $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW; + } + + // Test any extra holiday parameters + if (!empty($dateArgs)) { + $holidayCountedArray = $holidayDates = array(); + foreach ($dateArgs as $holidayDate) { + if (($holidayDate !== NULL) && (trim($holidayDate) > '')) { + if (is_string($holidayDate = self::_getDateValue($holidayDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (self::DAYOFWEEK($holidayDate,3) < 5) { + $holidayDates[] = $holidayDate; + } + } + } + if ($decrementing) { + rsort($holidayDates, SORT_NUMERIC); + } else { + sort($holidayDates, SORT_NUMERIC); + } + foreach ($holidayDates as $holidayDate) { + if ($decrementing) { + if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { + if (!in_array($holidayDate,$holidayCountedArray)) { + --$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + } else { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if (!in_array($holidayDate,$holidayCountedArray)) { + ++$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::DAYOFWEEK($endDate,3); + if ($endDoW >= 5) { + $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW; + } + + } + } + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) $endDate; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + } + } // function WORKDAY() + + + /** + * DAYOFMONTH + * + * Returns the day of the month, for a specified date. The day is given as an integer + * ranging from 1 to 31. + * + * Excel Function: + * DAY(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Day of the month + */ + public static function DAYOFMONTH($dateValue = 1) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue == 0.0) { + return 0; + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('j'); + } // function DAYOFMONTH() + + + /** + * DAYOFWEEK + * + * Returns the day of the week for a specified date. The day is given as an integer + * ranging from 0 to 7 (dependent on the requested style). + * + * Excel Function: + * WEEKDAY(dateValue[,style]) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $style A number that determines the type of return value + * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). + * 2 Numbers 1 (Monday) through 7 (Sunday). + * 3 Numbers 0 (Monday) through 6 (Sunday). + * @return int Day of the week value + */ + public static function DAYOFWEEK($dateValue = 1, $style = 1) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $style = PHPExcel_Calculation_Functions::flattenSingleValue($style); + + if (!is_numeric($style)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif (($style < 1) || ($style > 3)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $style = floor($style); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + $DoW = $PHPDateObject->format('w'); + + $firstDay = 1; + switch ($style) { + case 1: ++$DoW; + break; + case 2: if ($DoW == 0) { $DoW = 7; } + break; + case 3: if ($DoW == 0) { $DoW = 7; } + $firstDay = 0; + --$DoW; + break; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) { + // Test for Excel's 1900 leap year, and introduce the error as required + if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) { + --$DoW; + if ($DoW < $firstDay) { + $DoW += 7; + } + } + } + + return (int) $DoW; + } // function DAYOFWEEK() + + + /** + * WEEKOFYEAR + * + * Returns the week of the year for a specified date. + * The WEEKNUM function considers the week containing January 1 to be the first week of the year. + * However, there is a European standard that defines the first week as the one with the majority + * of days (four or more) falling in the new year. This means that for years in which there are + * three days or less in the first week of January, the WEEKNUM function returns week numbers + * that are incorrect according to the European standard. + * + * Excel Function: + * WEEKNUM(dateValue[,style]) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param boolean $method Week begins on Sunday or Monday + * 1 or omitted Week begins on Sunday. + * 2 Week begins on Monday. + * @return int Week Number + */ + public static function WEEKOFYEAR($dateValue = 1, $method = 1) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $method = PHPExcel_Calculation_Functions::flattenSingleValue($method); + + if (!is_numeric($method)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif (($method < 1) || ($method > 2)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $method = floor($method); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + $dayOfYear = $PHPDateObject->format('z'); + $dow = $PHPDateObject->format('w'); + $PHPDateObject->modify('-'.$dayOfYear.' days'); + $dow = $PHPDateObject->format('w'); + $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7); + $dayOfYear -= $daysInFirstWeek; + $weekOfYear = ceil($dayOfYear / 7) + 1; + + return (int) $weekOfYear; + } // function WEEKOFYEAR() + + + /** + * MONTHOFYEAR + * + * Returns the month of a date represented by a serial number. + * The month is given as an integer, ranging from 1 (January) to 12 (December). + * + * Excel Function: + * MONTH(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Month of the year + */ + public static function MONTHOFYEAR($dateValue = 1) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('n'); + } // function MONTHOFYEAR() + + + /** + * YEAR + * + * Returns the year corresponding to a date. + * The year is returned as an integer in the range 1900-9999. + * + * Excel Function: + * YEAR(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Year + */ + public static function YEAR($dateValue = 1) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('Y'); + } // function YEAR() + + + /** + * HOUROFDAY + * + * Returns the hour of a time value. + * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). + * + * Excel Function: + * HOUR(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Hour + */ + public static function HOUROFDAY($timeValue = 0) { + $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue,'/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::_getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue,1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('G',$timeValue); + } // function HOUROFDAY() + + + /** + * MINUTEOFHOUR + * + * Returns the minutes of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * MINUTE(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Minute + */ + public static function MINUTEOFHOUR($timeValue = 0) { + $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue,'/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::_getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue,1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('i',$timeValue); + } // function MINUTEOFHOUR() + + + /** + * SECONDOFMINUTE + * + * Returns the seconds of a time value. + * The second is given as an integer in the range 0 (zero) to 59. + * + * Excel Function: + * SECOND(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Second + */ + public static function SECONDOFMINUTE($timeValue = 0) { + $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue,'/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::_getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue,1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('s',$timeValue); + } // function SECONDOFMINUTE() + + + /** + * EDATE + * + * Returns the serial number that represents the date that is the indicated number of months + * before or after a specified date (the start_date). + * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month + * as the date of issue. + * + * Excel Function: + * EDATE(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function EDATE($dateValue = 1, $adjustmentMonths = 0) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths); + + if (!is_numeric($adjustmentMonths)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $adjustmentMonths = floor($adjustmentMonths); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject)); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return $PHPDateObject; + } + } // function EDATE() + + + /** + * EOMONTH + * + * Returns the date value for the last day of the month that is the indicated number of months + * before or after start_date. + * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. + * + * Excel Function: + * EOMONTH(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths); + + if (!is_numeric($adjustmentMonths)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $adjustmentMonths = floor($adjustmentMonths); + + if (is_string($dateValue = self::_getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPDateObject = self::_adjustDateByMonths($dateValue,$adjustmentMonths+1); + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-'.$adjustDays.' days'; + $PHPDateObject->modify($adjustDaysString); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL : + return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC : + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject)); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT : + return $PHPDateObject; + } + } // function EOMONTH() + +} // class PHPExcel_Calculation_DateTime + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php new file mode 100644 index 00000000..7e32aa87 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php @@ -0,0 +1,2505 @@ + array( 'Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => True ), + 'sg' => array( 'Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => False ), + 'lbm' => array( 'Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => False ), + 'u' => array( 'Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => True ), + 'ozm' => array( 'Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => False ), + 'm' => array( 'Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => True ), + 'mi' => array( 'Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => False ), + 'Nmi' => array( 'Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => False ), + 'in' => array( 'Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => False ), + 'ft' => array( 'Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => False ), + 'yd' => array( 'Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => False ), + 'ang' => array( 'Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => True ), + 'Pica' => array( 'Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => False ), + 'yr' => array( 'Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => False ), + 'day' => array( 'Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => False ), + 'hr' => array( 'Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => False ), + 'mn' => array( 'Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => False ), + 'sec' => array( 'Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => True ), + 'Pa' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ), + 'p' => array( 'Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => True ), + 'atm' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ), + 'at' => array( 'Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => True ), + 'mmHg' => array( 'Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => True ), + 'N' => array( 'Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => True ), + 'dyn' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ), + 'dy' => array( 'Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => True ), + 'lbf' => array( 'Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => False ), + 'J' => array( 'Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => True ), + 'e' => array( 'Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => True ), + 'c' => array( 'Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => True ), + 'cal' => array( 'Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => True ), + 'eV' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ), + 'ev' => array( 'Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => True ), + 'HPh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ), + 'hh' => array( 'Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => False ), + 'Wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ), + 'wh' => array( 'Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => True ), + 'flb' => array( 'Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => False ), + 'BTU' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ), + 'btu' => array( 'Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => False ), + 'HP' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ), + 'h' => array( 'Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => False ), + 'W' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ), + 'w' => array( 'Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => True ), + 'T' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => True ), + 'ga' => array( 'Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => True ), + 'C' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ), + 'cel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => False ), + 'F' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ), + 'fah' => array( 'Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => False ), + 'K' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ), + 'kel' => array( 'Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => False ), + 'tsp' => array( 'Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => False ), + 'tbs' => array( 'Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => False ), + 'oz' => array( 'Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => False ), + 'cup' => array( 'Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => False ), + 'pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ), + 'us_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => False ), + 'uk_pt' => array( 'Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => False ), + 'qt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => False ), + 'gal' => array( 'Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => False ), + 'l' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ), + 'lt' => array( 'Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => True ) + ); + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() + * + * @var mixed[] + */ + private static $_conversionMultipliers = array( 'Y' => array( 'multiplier' => 1E24, 'name' => 'yotta' ), + 'Z' => array( 'multiplier' => 1E21, 'name' => 'zetta' ), + 'E' => array( 'multiplier' => 1E18, 'name' => 'exa' ), + 'P' => array( 'multiplier' => 1E15, 'name' => 'peta' ), + 'T' => array( 'multiplier' => 1E12, 'name' => 'tera' ), + 'G' => array( 'multiplier' => 1E9, 'name' => 'giga' ), + 'M' => array( 'multiplier' => 1E6, 'name' => 'mega' ), + 'k' => array( 'multiplier' => 1E3, 'name' => 'kilo' ), + 'h' => array( 'multiplier' => 1E2, 'name' => 'hecto' ), + 'e' => array( 'multiplier' => 1E1, 'name' => 'deka' ), + 'd' => array( 'multiplier' => 1E-1, 'name' => 'deci' ), + 'c' => array( 'multiplier' => 1E-2, 'name' => 'centi' ), + 'm' => array( 'multiplier' => 1E-3, 'name' => 'milli' ), + 'u' => array( 'multiplier' => 1E-6, 'name' => 'micro' ), + 'n' => array( 'multiplier' => 1E-9, 'name' => 'nano' ), + 'p' => array( 'multiplier' => 1E-12, 'name' => 'pico' ), + 'f' => array( 'multiplier' => 1E-15, 'name' => 'femto' ), + 'a' => array( 'multiplier' => 1E-18, 'name' => 'atto' ), + 'z' => array( 'multiplier' => 1E-21, 'name' => 'zepto' ), + 'y' => array( 'multiplier' => 1E-24, 'name' => 'yocto' ) + ); + + /** + * Details of the Units of measure conversion factors, organised by group + * + * @var mixed[] + */ + private static $_unitConversions = array( 'Mass' => array( 'g' => array( 'g' => 1.0, + 'sg' => 6.85220500053478E-05, + 'lbm' => 2.20462291469134E-03, + 'u' => 6.02217000000000E+23, + 'ozm' => 3.52739718003627E-02 + ), + 'sg' => array( 'g' => 1.45938424189287E+04, + 'sg' => 1.0, + 'lbm' => 3.21739194101647E+01, + 'u' => 8.78866000000000E+27, + 'ozm' => 5.14782785944229E+02 + ), + 'lbm' => array( 'g' => 4.5359230974881148E+02, + 'sg' => 3.10810749306493E-02, + 'lbm' => 1.0, + 'u' => 2.73161000000000E+26, + 'ozm' => 1.60000023429410E+01 + ), + 'u' => array( 'g' => 1.66053100460465E-24, + 'sg' => 1.13782988532950E-28, + 'lbm' => 3.66084470330684E-27, + 'u' => 1.0, + 'ozm' => 5.85735238300524E-26 + ), + 'ozm' => array( 'g' => 2.83495152079732E+01, + 'sg' => 1.94256689870811E-03, + 'lbm' => 6.24999908478882E-02, + 'u' => 1.70725600000000E+25, + 'ozm' => 1.0 + ) + ), + 'Distance' => array( 'm' => array( 'm' => 1.0, + 'mi' => 6.21371192237334E-04, + 'Nmi' => 5.39956803455724E-04, + 'in' => 3.93700787401575E+01, + 'ft' => 3.28083989501312E+00, + 'yd' => 1.09361329797891E+00, + 'ang' => 1.00000000000000E+10, + 'Pica' => 2.83464566929116E+03 + ), + 'mi' => array( 'm' => 1.60934400000000E+03, + 'mi' => 1.0, + 'Nmi' => 8.68976241900648E-01, + 'in' => 6.33600000000000E+04, + 'ft' => 5.28000000000000E+03, + 'yd' => 1.76000000000000E+03, + 'ang' => 1.60934400000000E+13, + 'Pica' => 4.56191999999971E+06 + ), + 'Nmi' => array( 'm' => 1.85200000000000E+03, + 'mi' => 1.15077944802354E+00, + 'Nmi' => 1.0, + 'in' => 7.29133858267717E+04, + 'ft' => 6.07611548556430E+03, + 'yd' => 2.02537182785694E+03, + 'ang' => 1.85200000000000E+13, + 'Pica' => 5.24976377952723E+06 + ), + 'in' => array( 'm' => 2.54000000000000E-02, + 'mi' => 1.57828282828283E-05, + 'Nmi' => 1.37149028077754E-05, + 'in' => 1.0, + 'ft' => 8.33333333333333E-02, + 'yd' => 2.77777777686643E-02, + 'ang' => 2.54000000000000E+08, + 'Pica' => 7.19999999999955E+01 + ), + 'ft' => array( 'm' => 3.04800000000000E-01, + 'mi' => 1.89393939393939E-04, + 'Nmi' => 1.64578833693305E-04, + 'in' => 1.20000000000000E+01, + 'ft' => 1.0, + 'yd' => 3.33333333223972E-01, + 'ang' => 3.04800000000000E+09, + 'Pica' => 8.63999999999946E+02 + ), + 'yd' => array( 'm' => 9.14400000300000E-01, + 'mi' => 5.68181818368230E-04, + 'Nmi' => 4.93736501241901E-04, + 'in' => 3.60000000118110E+01, + 'ft' => 3.00000000000000E+00, + 'yd' => 1.0, + 'ang' => 9.14400000300000E+09, + 'Pica' => 2.59200000085023E+03 + ), + 'ang' => array( 'm' => 1.00000000000000E-10, + 'mi' => 6.21371192237334E-14, + 'Nmi' => 5.39956803455724E-14, + 'in' => 3.93700787401575E-09, + 'ft' => 3.28083989501312E-10, + 'yd' => 1.09361329797891E-10, + 'ang' => 1.0, + 'Pica' => 2.83464566929116E-07 + ), + 'Pica' => array( 'm' => 3.52777777777800E-04, + 'mi' => 2.19205948372629E-07, + 'Nmi' => 1.90484761219114E-07, + 'in' => 1.38888888888898E-02, + 'ft' => 1.15740740740748E-03, + 'yd' => 3.85802469009251E-04, + 'ang' => 3.52777777777800E+06, + 'Pica' => 1.0 + ) + ), + 'Time' => array( 'yr' => array( 'yr' => 1.0, + 'day' => 365.25, + 'hr' => 8766.0, + 'mn' => 525960.0, + 'sec' => 31557600.0 + ), + 'day' => array( 'yr' => 2.73785078713210E-03, + 'day' => 1.0, + 'hr' => 24.0, + 'mn' => 1440.0, + 'sec' => 86400.0 + ), + 'hr' => array( 'yr' => 1.14077116130504E-04, + 'day' => 4.16666666666667E-02, + 'hr' => 1.0, + 'mn' => 60.0, + 'sec' => 3600.0 + ), + 'mn' => array( 'yr' => 1.90128526884174E-06, + 'day' => 6.94444444444444E-04, + 'hr' => 1.66666666666667E-02, + 'mn' => 1.0, + 'sec' => 60.0 + ), + 'sec' => array( 'yr' => 3.16880878140289E-08, + 'day' => 1.15740740740741E-05, + 'hr' => 2.77777777777778E-04, + 'mn' => 1.66666666666667E-02, + 'sec' => 1.0 + ) + ), + 'Pressure' => array( 'Pa' => array( 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923299998193E-06, + 'at' => 9.86923299998193E-06, + 'mmHg' => 7.50061707998627E-03 + ), + 'p' => array( 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923299998193E-06, + 'at' => 9.86923299998193E-06, + 'mmHg' => 7.50061707998627E-03 + ), + 'atm' => array( 'Pa' => 1.01324996583000E+05, + 'p' => 1.01324996583000E+05, + 'atm' => 1.0, + 'at' => 1.0, + 'mmHg' => 760.0 + ), + 'at' => array( 'Pa' => 1.01324996583000E+05, + 'p' => 1.01324996583000E+05, + 'atm' => 1.0, + 'at' => 1.0, + 'mmHg' => 760.0 + ), + 'mmHg' => array( 'Pa' => 1.33322363925000E+02, + 'p' => 1.33322363925000E+02, + 'atm' => 1.31578947368421E-03, + 'at' => 1.31578947368421E-03, + 'mmHg' => 1.0 + ) + ), + 'Force' => array( 'N' => array( 'N' => 1.0, + 'dyn' => 1.0E+5, + 'dy' => 1.0E+5, + 'lbf' => 2.24808923655339E-01 + ), + 'dyn' => array( 'N' => 1.0E-5, + 'dyn' => 1.0, + 'dy' => 1.0, + 'lbf' => 2.24808923655339E-06 + ), + 'dy' => array( 'N' => 1.0E-5, + 'dyn' => 1.0, + 'dy' => 1.0, + 'lbf' => 2.24808923655339E-06 + ), + 'lbf' => array( 'N' => 4.448222, + 'dyn' => 4.448222E+5, + 'dy' => 4.448222E+5, + 'lbf' => 1.0 + ) + ), + 'Energy' => array( 'J' => array( 'J' => 1.0, + 'e' => 9.99999519343231E+06, + 'c' => 2.39006249473467E-01, + 'cal' => 2.38846190642017E-01, + 'eV' => 6.24145700000000E+18, + 'ev' => 6.24145700000000E+18, + 'HPh' => 3.72506430801000E-07, + 'hh' => 3.72506430801000E-07, + 'Wh' => 2.77777916238711E-04, + 'wh' => 2.77777916238711E-04, + 'flb' => 2.37304222192651E+01, + 'BTU' => 9.47815067349015E-04, + 'btu' => 9.47815067349015E-04 + ), + 'e' => array( 'J' => 1.00000048065700E-07, + 'e' => 1.0, + 'c' => 2.39006364353494E-08, + 'cal' => 2.38846305445111E-08, + 'eV' => 6.24146000000000E+11, + 'ev' => 6.24146000000000E+11, + 'HPh' => 3.72506609848824E-14, + 'hh' => 3.72506609848824E-14, + 'Wh' => 2.77778049754611E-11, + 'wh' => 2.77778049754611E-11, + 'flb' => 2.37304336254586E-06, + 'BTU' => 9.47815522922962E-11, + 'btu' => 9.47815522922962E-11 + ), + 'c' => array( 'J' => 4.18399101363672E+00, + 'e' => 4.18398900257312E+07, + 'c' => 1.0, + 'cal' => 9.99330315287563E-01, + 'eV' => 2.61142000000000E+19, + 'ev' => 2.61142000000000E+19, + 'HPh' => 1.55856355899327E-06, + 'hh' => 1.55856355899327E-06, + 'Wh' => 1.16222030532950E-03, + 'wh' => 1.16222030532950E-03, + 'flb' => 9.92878733152102E+01, + 'BTU' => 3.96564972437776E-03, + 'btu' => 3.96564972437776E-03 + ), + 'cal' => array( 'J' => 4.18679484613929E+00, + 'e' => 4.18679283372801E+07, + 'c' => 1.00067013349059E+00, + 'cal' => 1.0, + 'eV' => 2.61317000000000E+19, + 'ev' => 2.61317000000000E+19, + 'HPh' => 1.55960800463137E-06, + 'hh' => 1.55960800463137E-06, + 'Wh' => 1.16299914807955E-03, + 'wh' => 1.16299914807955E-03, + 'flb' => 9.93544094443283E+01, + 'BTU' => 3.96830723907002E-03, + 'btu' => 3.96830723907002E-03 + ), + 'eV' => array( 'J' => 1.60219000146921E-19, + 'e' => 1.60218923136574E-12, + 'c' => 3.82933423195043E-20, + 'cal' => 3.82676978535648E-20, + 'eV' => 1.0, + 'ev' => 1.0, + 'HPh' => 5.96826078912344E-26, + 'hh' => 5.96826078912344E-26, + 'Wh' => 4.45053000026614E-23, + 'wh' => 4.45053000026614E-23, + 'flb' => 3.80206452103492E-18, + 'BTU' => 1.51857982414846E-22, + 'btu' => 1.51857982414846E-22 + ), + 'ev' => array( 'J' => 1.60219000146921E-19, + 'e' => 1.60218923136574E-12, + 'c' => 3.82933423195043E-20, + 'cal' => 3.82676978535648E-20, + 'eV' => 1.0, + 'ev' => 1.0, + 'HPh' => 5.96826078912344E-26, + 'hh' => 5.96826078912344E-26, + 'Wh' => 4.45053000026614E-23, + 'wh' => 4.45053000026614E-23, + 'flb' => 3.80206452103492E-18, + 'BTU' => 1.51857982414846E-22, + 'btu' => 1.51857982414846E-22 + ), + 'HPh' => array( 'J' => 2.68451741316170E+06, + 'e' => 2.68451612283024E+13, + 'c' => 6.41616438565991E+05, + 'cal' => 6.41186757845835E+05, + 'eV' => 1.67553000000000E+25, + 'ev' => 1.67553000000000E+25, + 'HPh' => 1.0, + 'hh' => 1.0, + 'Wh' => 7.45699653134593E+02, + 'wh' => 7.45699653134593E+02, + 'flb' => 6.37047316692964E+07, + 'BTU' => 2.54442605275546E+03, + 'btu' => 2.54442605275546E+03 + ), + 'hh' => array( 'J' => 2.68451741316170E+06, + 'e' => 2.68451612283024E+13, + 'c' => 6.41616438565991E+05, + 'cal' => 6.41186757845835E+05, + 'eV' => 1.67553000000000E+25, + 'ev' => 1.67553000000000E+25, + 'HPh' => 1.0, + 'hh' => 1.0, + 'Wh' => 7.45699653134593E+02, + 'wh' => 7.45699653134593E+02, + 'flb' => 6.37047316692964E+07, + 'BTU' => 2.54442605275546E+03, + 'btu' => 2.54442605275546E+03 + ), + 'Wh' => array( 'J' => 3.59999820554720E+03, + 'e' => 3.59999647518369E+10, + 'c' => 8.60422069219046E+02, + 'cal' => 8.59845857713046E+02, + 'eV' => 2.24692340000000E+22, + 'ev' => 2.24692340000000E+22, + 'HPh' => 1.34102248243839E-03, + 'hh' => 1.34102248243839E-03, + 'Wh' => 1.0, + 'wh' => 1.0, + 'flb' => 8.54294774062316E+04, + 'BTU' => 3.41213254164705E+00, + 'btu' => 3.41213254164705E+00 + ), + 'wh' => array( 'J' => 3.59999820554720E+03, + 'e' => 3.59999647518369E+10, + 'c' => 8.60422069219046E+02, + 'cal' => 8.59845857713046E+02, + 'eV' => 2.24692340000000E+22, + 'ev' => 2.24692340000000E+22, + 'HPh' => 1.34102248243839E-03, + 'hh' => 1.34102248243839E-03, + 'Wh' => 1.0, + 'wh' => 1.0, + 'flb' => 8.54294774062316E+04, + 'BTU' => 3.41213254164705E+00, + 'btu' => 3.41213254164705E+00 + ), + 'flb' => array( 'J' => 4.21400003236424E-02, + 'e' => 4.21399800687660E+05, + 'c' => 1.00717234301644E-02, + 'cal' => 1.00649785509554E-02, + 'eV' => 2.63015000000000E+17, + 'ev' => 2.63015000000000E+17, + 'HPh' => 1.56974211145130E-08, + 'hh' => 1.56974211145130E-08, + 'Wh' => 1.17055614802000E-05, + 'wh' => 1.17055614802000E-05, + 'flb' => 1.0, + 'BTU' => 3.99409272448406E-05, + 'btu' => 3.99409272448406E-05 + ), + 'BTU' => array( 'J' => 1.05505813786749E+03, + 'e' => 1.05505763074665E+10, + 'c' => 2.52165488508168E+02, + 'cal' => 2.51996617135510E+02, + 'eV' => 6.58510000000000E+21, + 'ev' => 6.58510000000000E+21, + 'HPh' => 3.93015941224568E-04, + 'hh' => 3.93015941224568E-04, + 'Wh' => 2.93071851047526E-01, + 'wh' => 2.93071851047526E-01, + 'flb' => 2.50369750774671E+04, + 'BTU' => 1.0, + 'btu' => 1.0, + ), + 'btu' => array( 'J' => 1.05505813786749E+03, + 'e' => 1.05505763074665E+10, + 'c' => 2.52165488508168E+02, + 'cal' => 2.51996617135510E+02, + 'eV' => 6.58510000000000E+21, + 'ev' => 6.58510000000000E+21, + 'HPh' => 3.93015941224568E-04, + 'hh' => 3.93015941224568E-04, + 'Wh' => 2.93071851047526E-01, + 'wh' => 2.93071851047526E-01, + 'flb' => 2.50369750774671E+04, + 'BTU' => 1.0, + 'btu' => 1.0, + ) + ), + 'Power' => array( 'HP' => array( 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45701000000000E+02, + 'w' => 7.45701000000000E+02 + ), + 'h' => array( 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45701000000000E+02, + 'w' => 7.45701000000000E+02 + ), + 'W' => array( 'HP' => 1.34102006031908E-03, + 'h' => 1.34102006031908E-03, + 'W' => 1.0, + 'w' => 1.0 + ), + 'w' => array( 'HP' => 1.34102006031908E-03, + 'h' => 1.34102006031908E-03, + 'W' => 1.0, + 'w' => 1.0 + ) + ), + 'Magnetism' => array( 'T' => array( 'T' => 1.0, + 'ga' => 10000.0 + ), + 'ga' => array( 'T' => 0.0001, + 'ga' => 1.0 + ) + ), + 'Liquid' => array( 'tsp' => array( 'tsp' => 1.0, + 'tbs' => 3.33333333333333E-01, + 'oz' => 1.66666666666667E-01, + 'cup' => 2.08333333333333E-02, + 'pt' => 1.04166666666667E-02, + 'us_pt' => 1.04166666666667E-02, + 'uk_pt' => 8.67558516821960E-03, + 'qt' => 5.20833333333333E-03, + 'gal' => 1.30208333333333E-03, + 'l' => 4.92999408400710E-03, + 'lt' => 4.92999408400710E-03 + ), + 'tbs' => array( 'tsp' => 3.00000000000000E+00, + 'tbs' => 1.0, + 'oz' => 5.00000000000000E-01, + 'cup' => 6.25000000000000E-02, + 'pt' => 3.12500000000000E-02, + 'us_pt' => 3.12500000000000E-02, + 'uk_pt' => 2.60267555046588E-02, + 'qt' => 1.56250000000000E-02, + 'gal' => 3.90625000000000E-03, + 'l' => 1.47899822520213E-02, + 'lt' => 1.47899822520213E-02 + ), + 'oz' => array( 'tsp' => 6.00000000000000E+00, + 'tbs' => 2.00000000000000E+00, + 'oz' => 1.0, + 'cup' => 1.25000000000000E-01, + 'pt' => 6.25000000000000E-02, + 'us_pt' => 6.25000000000000E-02, + 'uk_pt' => 5.20535110093176E-02, + 'qt' => 3.12500000000000E-02, + 'gal' => 7.81250000000000E-03, + 'l' => 2.95799645040426E-02, + 'lt' => 2.95799645040426E-02 + ), + 'cup' => array( 'tsp' => 4.80000000000000E+01, + 'tbs' => 1.60000000000000E+01, + 'oz' => 8.00000000000000E+00, + 'cup' => 1.0, + 'pt' => 5.00000000000000E-01, + 'us_pt' => 5.00000000000000E-01, + 'uk_pt' => 4.16428088074541E-01, + 'qt' => 2.50000000000000E-01, + 'gal' => 6.25000000000000E-02, + 'l' => 2.36639716032341E-01, + 'lt' => 2.36639716032341E-01 + ), + 'pt' => array( 'tsp' => 9.60000000000000E+01, + 'tbs' => 3.20000000000000E+01, + 'oz' => 1.60000000000000E+01, + 'cup' => 2.00000000000000E+00, + 'pt' => 1.0, + 'us_pt' => 1.0, + 'uk_pt' => 8.32856176149081E-01, + 'qt' => 5.00000000000000E-01, + 'gal' => 1.25000000000000E-01, + 'l' => 4.73279432064682E-01, + 'lt' => 4.73279432064682E-01 + ), + 'us_pt' => array( 'tsp' => 9.60000000000000E+01, + 'tbs' => 3.20000000000000E+01, + 'oz' => 1.60000000000000E+01, + 'cup' => 2.00000000000000E+00, + 'pt' => 1.0, + 'us_pt' => 1.0, + 'uk_pt' => 8.32856176149081E-01, + 'qt' => 5.00000000000000E-01, + 'gal' => 1.25000000000000E-01, + 'l' => 4.73279432064682E-01, + 'lt' => 4.73279432064682E-01 + ), + 'uk_pt' => array( 'tsp' => 1.15266000000000E+02, + 'tbs' => 3.84220000000000E+01, + 'oz' => 1.92110000000000E+01, + 'cup' => 2.40137500000000E+00, + 'pt' => 1.20068750000000E+00, + 'us_pt' => 1.20068750000000E+00, + 'uk_pt' => 1.0, + 'qt' => 6.00343750000000E-01, + 'gal' => 1.50085937500000E-01, + 'l' => 5.68260698087162E-01, + 'lt' => 5.68260698087162E-01 + ), + 'qt' => array( 'tsp' => 1.92000000000000E+02, + 'tbs' => 6.40000000000000E+01, + 'oz' => 3.20000000000000E+01, + 'cup' => 4.00000000000000E+00, + 'pt' => 2.00000000000000E+00, + 'us_pt' => 2.00000000000000E+00, + 'uk_pt' => 1.66571235229816E+00, + 'qt' => 1.0, + 'gal' => 2.50000000000000E-01, + 'l' => 9.46558864129363E-01, + 'lt' => 9.46558864129363E-01 + ), + 'gal' => array( 'tsp' => 7.68000000000000E+02, + 'tbs' => 2.56000000000000E+02, + 'oz' => 1.28000000000000E+02, + 'cup' => 1.60000000000000E+01, + 'pt' => 8.00000000000000E+00, + 'us_pt' => 8.00000000000000E+00, + 'uk_pt' => 6.66284940919265E+00, + 'qt' => 4.00000000000000E+00, + 'gal' => 1.0, + 'l' => 3.78623545651745E+00, + 'lt' => 3.78623545651745E+00 + ), + 'l' => array( 'tsp' => 2.02840000000000E+02, + 'tbs' => 6.76133333333333E+01, + 'oz' => 3.38066666666667E+01, + 'cup' => 4.22583333333333E+00, + 'pt' => 2.11291666666667E+00, + 'us_pt' => 2.11291666666667E+00, + 'uk_pt' => 1.75975569552166E+00, + 'qt' => 1.05645833333333E+00, + 'gal' => 2.64114583333333E-01, + 'l' => 1.0, + 'lt' => 1.0 + ), + 'lt' => array( 'tsp' => 2.02840000000000E+02, + 'tbs' => 6.76133333333333E+01, + 'oz' => 3.38066666666667E+01, + 'cup' => 4.22583333333333E+00, + 'pt' => 2.11291666666667E+00, + 'us_pt' => 2.11291666666667E+00, + 'uk_pt' => 1.75975569552166E+00, + 'qt' => 1.05645833333333E+00, + 'gal' => 2.64114583333333E-01, + 'l' => 1.0, + 'lt' => 1.0 + ) + ) + ); + + + /** + * _parseComplex + * + * Parses a complex number into its real and imaginary parts, and an I or J suffix + * + * @param string $complexNumber The complex number + * @return string[] Indexed on "real", "imaginary" and "suffix" + */ + public static function _parseComplex($complexNumber) { + $workString = (string) $complexNumber; + + $realNumber = $imaginary = 0; + // Extract the suffix, if there is one + $suffix = substr($workString,-1); + if (!is_numeric($suffix)) { + $workString = substr($workString,0,-1); + } else { + $suffix = ''; + } + + // Split the input into its Real and Imaginary components + $leadingSign = 0; + if (strlen($workString) > 0) { + $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0; + } + $power = ''; + $realNumber = strtok($workString, '+-'); + if (strtoupper(substr($realNumber,-1)) == 'E') { + $power = strtok('+-'); + ++$leadingSign; + } + + $realNumber = substr($workString,0,strlen($realNumber)+strlen($power)+$leadingSign); + + if ($suffix != '') { + $imaginary = substr($workString,strlen($realNumber)); + + if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) { + $imaginary = $realNumber.'1'; + $realNumber = '0'; + } else if ($imaginary == '') { + $imaginary = $realNumber; + $realNumber = '0'; + } elseif (($imaginary == '+') || ($imaginary == '-')) { + $imaginary .= '1'; + } + } + + return array( 'real' => $realNumber, + 'imaginary' => $imaginary, + 'suffix' => $suffix + ); + } // function _parseComplex() + + + /** + * Cleans the leading characters in a complex number string + * + * @param string $complexNumber The complex number to clean + * @return string The "cleaned" complex number + */ + private static function _cleanComplex($complexNumber) { + if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1); + if ($complexNumber{0} == '0') $complexNumber = substr($complexNumber,1); + if ($complexNumber{0} == '.') $complexNumber = '0'.$complexNumber; + if ($complexNumber{0} == '+') $complexNumber = substr($complexNumber,1); + return $complexNumber; + } + + /** + * Formats a number base string value with leading zeroes + * + * @param string $xVal The "number" to pad + * @param integer $places The length that we want to pad this value + * @return string The padded "number" + */ + private static function _nbrConversionFormat($xVal, $places) { + if (!is_null($places)) { + if (strlen($xVal) <= $places) { + return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10); + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + return substr($xVal, -10); + } // function _nbrConversionFormat() + + /** + * BESSELI + * + * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated + * for purely imaginary arguments + * + * Excel Function: + * BESSELI(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELI returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. + * If ord is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. + * If $ord < 0, BESSELI returns the #NUM! error value. + * @return float + * + */ + public static function BESSELI($x, $ord) { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + $ord = floor($ord); + if ($ord < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (abs($x) <= 30) { + $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord); + $ordK = 1; + $fSqrX = ($x * $x) / 4; + do { + $fTerm *= $fSqrX; + $fTerm /= ($ordK * ($ordK + $ord)); + $fResult += $fTerm; + } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); + } else { + $f_2_PI = 2 * M_PI; + + $fXAbs = abs($x); + $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs); + if (($ord & 1) && ($x < 0)) { + $fResult = -$fResult; + } + } + return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BESSELI() + + + /** + * BESSELJ + * + * Returns the Bessel function + * + * Excel Function: + * BESSELJ(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELJ returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. + * If $ord < 0, BESSELJ returns the #NUM! error value. + * @return float + * + */ + public static function BESSELJ($x, $ord) { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + $ord = floor($ord); + if ($ord < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $fResult = 0; + if (abs($x) <= 30) { + $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord); + $ordK = 1; + $fSqrX = ($x * $x) / -4; + do { + $fTerm *= $fSqrX; + $fTerm /= ($ordK * ($ordK + $ord)); + $fResult += $fTerm; + } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); + } else { + $f_PI_DIV_2 = M_PI / 2; + $f_PI_DIV_4 = M_PI / 4; + + $fXAbs = abs($x); + $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4); + if (($ord & 1) && ($x < 0)) { + $fResult = -$fResult; + } + } + return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BESSELJ() + + + private static function _Besselk0($fNum) { + if ($fNum <= 2) { + $fNum2 = $fNum * 0.5; + $y = ($fNum2 * $fNum2); + $fRet = -log($fNum2) * self::BESSELI($fNum, 0) + + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * + (0.10750e-3 + $y * 0.74e-5)))))); + } else { + $y = 2 / $fNum; + $fRet = exp(-$fNum) / sqrt($fNum) * + (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * + (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); + } + return $fRet; + } // function _Besselk0() + + + private static function _Besselk1($fNum) { + if ($fNum <= 2) { + $fNum2 = $fNum * 0.5; + $y = ($fNum2 * $fNum2); + $fRet = log($fNum2) * self::BESSELI($fNum, 1) + + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * + (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum; + } else { + $y = 2 / $fNum; + $fRet = exp(-$fNum) / sqrt($fNum) * + (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * + (0.325614e-2 + $y * (-0.68245e-3))))))); + } + return $fRet; + } // function _Besselk1() + + + /** + * BESSELK + * + * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated + * for purely imaginary arguments. + * + * Excel Function: + * BESSELK(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. + * If $ord < 0, BESSELK returns the #NUM! error value. + * @return float + * + */ + public static function BESSELK($x, $ord) { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + if (($ord < 0) || ($x == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch(floor($ord)) { + case 0 : return self::_Besselk0($x); + break; + case 1 : return self::_Besselk1($x); + break; + default : $fTox = 2 / $x; + $fBkm = self::_Besselk0($x); + $fBk = self::_Besselk1($x); + for ($n = 1; $n < $ord; ++$n) { + $fBkp = $fBkm + $n * $fTox * $fBk; + $fBkm = $fBk; + $fBk = $fBkp; + } + } + return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BESSELK() + + + private static function _Bessely0($fNum) { + if ($fNum < 8.0) { + $y = ($fNum * $fNum); + $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); + $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); + $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum); + } else { + $z = 8.0 / $fNum; + $y = ($z * $z); + $xx = $fNum - 0.785398164; + $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); + $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2); + } + return $fRet; + } // function _Bessely0() + + + private static function _Bessely1($fNum) { + if ($fNum < 8.0) { + $y = ($fNum * $fNum); + $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * + (-0.4237922726e7 + $y * 0.8511937935e4))))); + $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * + (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); + $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum); + } else { + $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491); + } + return $fRet; + } // function _Bessely1() + + + /** + * BESSELY + * + * Returns the Bessel function, which is also called the Weber function or the Neumann function. + * + * Excel Function: + * BESSELY(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. + * If $ord < 0, BESSELK returns the #NUM! error value. + * + * @return float + */ + public static function BESSELY($x, $ord) { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + if (($ord < 0) || ($x == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch(floor($ord)) { + case 0 : return self::_Bessely0($x); + break; + case 1 : return self::_Bessely1($x); + break; + default: $fTox = 2 / $x; + $fBym = self::_Bessely0($x); + $fBy = self::_Bessely1($x); + for ($n = 1; $n < $ord; ++$n) { + $fByp = $n * $fTox * $fBy - $fBym; + $fBym = $fBy; + $fBy = $fByp; + } + } + return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BESSELY() + + + /** + * BINTODEC + * + * Return a binary value as decimal. + * + * Excel Function: + * BIN2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. + * @return string + */ + public static function BINTODEC($x) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/',$x,$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + $x = substr($x,-9); + return '-'.(512-bindec($x)); + } + return bindec($x); + } // function BINTODEC() + + + /** + * BINTOHEX + * + * Return a binary value as hex. + * + * Excel Function: + * BIN2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. + * If places is negative, BIN2HEX returns the #NUM! error value. + * @return string + */ + public static function BINTOHEX($x, $places=NULL) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/',$x,$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + return str_repeat('F',8).substr(strtoupper(dechex(bindec(substr($x,-9)))),-2); + } + $hexVal = (string) strtoupper(dechex(bindec($x))); + + return self::_nbrConversionFormat($hexVal,$places); + } // function BINTOHEX() + + + /** + * BINTOOCT + * + * Return a binary value as octal. + * + * Excel Function: + * BIN2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. + * If places is negative, BIN2OCT returns the #NUM! error value. + * @return string + */ + public static function BINTOOCT($x, $places=NULL) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/',$x,$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + return str_repeat('7',7).substr(strtoupper(decoct(bindec(substr($x,-9)))),-3); + } + $octVal = (string) decoct(bindec($x)); + + return self::_nbrConversionFormat($octVal,$places); + } // function BINTOOCT() + + + /** + * DECTOBIN + * + * Return a decimal value as binary. + * + * Excel Function: + * DEC2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * valid place values are ignored and DEC2BIN returns a 10-character + * (10-bit) binary number in which the most significant bit is the sign + * bit. The remaining 9 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error + * value. + * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If DEC2BIN requires more than places characters, it returns the #NUM! + * error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If places is zero or negative, DEC2BIN returns the #NUM! error value. + * @return string + */ + public static function DECTOBIN($x, $places=NULL) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = decbin($x); + if (strlen($r) == 32) { + // Two's Complement + $r = substr($r,-10); + } elseif (strlen($r) > 11) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::_nbrConversionFormat($r,$places); + } // function DECTOBIN() + + + /** + * DECTOHEX + * + * Return a decimal value as hex. + * + * Excel Function: + * DEC2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2HEX returns a 10-character (40-bit) + * hexadecimal number in which the most significant bit is the sign + * bit. The remaining 39 bits are magnitude bits. Negative numbers + * are represented using two's-complement notation. + * If number < -549,755,813,888 or if number > 549,755,813,887, + * DEC2HEX returns the #NUM! error value. + * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If DEC2HEX requires more than places characters, it returns the + * #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If places is zero or negative, DEC2HEX returns the #NUM! error value. + * @return string + */ + public static function DECTOHEX($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = strtoupper(dechex($x)); + if (strlen($r) == 8) { + // Two's Complement + $r = 'FF'.$r; + } + + return self::_nbrConversionFormat($r,$places); + } // function DECTOHEX() + + + /** + * DECTOOCT + * + * Return an decimal value as octal. + * + * Excel Function: + * DEC2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2OCT returns a 10-character (30-bit) + * octal number in which the most significant bit is the sign bit. + * The remaining 29 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -536,870,912 or if number > 536,870,911, DEC2OCT + * returns the #NUM! error value. + * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If DEC2OCT requires more than places characters, it returns the + * #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If places is zero or negative, DEC2OCT returns the #NUM! error value. + * @return string + */ + public static function DECTOOCT($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/',$x,$out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = decoct($x); + if (strlen($r) == 11) { + // Two's Complement + $r = substr($r,-10); + } + + return self::_nbrConversionFormat($r,$places); + } // function DECTOOCT() + + + /** + * HEXTOBIN + * + * Return a hex value as binary. + * + * Excel Function: + * HEX2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x the hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit (40th bit from the right). The remaining + * 9 bits are magnitude bits. Negative numbers are represented + * using two's-complement notation. + * If number is negative, HEX2BIN ignores places and returns a + * 10-character binary number. + * If number is negative, it cannot be less than FFFFFFFE00, and + * if number is positive, it cannot be greater than 1FF. + * If number is not a valid hexadecimal number, HEX2BIN returns + * the #NUM! error value. + * If HEX2BIN requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, + * HEX2BIN uses the minimum number of characters necessary. Places + * is useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. + * If places is negative, HEX2BIN returns the #NUM! error value. + * @return string + */ + public static function HEXTOBIN($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $binVal = decbin(hexdec($x)); + + return substr(self::_nbrConversionFormat($binVal,$places),-10); + } // function HEXTOBIN() + + + /** + * HEXTODEC + * + * Return a hex value as decimal. + * + * Excel Function: + * HEX2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The hexadecimal number you want to convert. This number cannot + * contain more than 10 characters (40 bits). The most significant + * bit of number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is not a valid hexadecimal number, HEX2DEC returns the + * #NUM! error value. + * @return string + */ + public static function HEXTODEC($x) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return hexdec($x); + } // function HEXTODEC() + + + /** + * HEXTOOCT + * + * Return a hex value as octal. + * + * Excel Function: + * HEX2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is negative, HEX2OCT ignores places and returns a + * 10-character octal number. + * If number is negative, it cannot be less than FFE0000000, and + * if number is positive, it cannot be greater than 1FFFFFFF. + * If number is not a valid hexadecimal number, HEX2OCT returns + * the #NUM! error value. + * If HEX2OCT requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, HEX2OCT + * uses the minimum number of characters necessary. Places is + * useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2OCT returns the #VALUE! error + * value. + * If places is negative, HEX2OCT returns the #NUM! error value. + * @return string + */ + public static function HEXTOOCT($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/',strtoupper($x),$out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $octVal = decoct(hexdec($x)); + + return self::_nbrConversionFormat($octVal,$places); + } // function HEXTOOCT() + + + /** + * OCTTOBIN + * + * Return an octal value as binary. + * + * Excel Function: + * OCT2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not + * contain more than 10 characters. The most significant + * bit of number is the sign bit. The remaining 29 bits + * are magnitude bits. Negative numbers are represented + * using two's-complement notation. + * If number is negative, OCT2BIN ignores places and returns + * a 10-character binary number. + * If number is negative, it cannot be less than 7777777000, + * and if number is positive, it cannot be greater than 777. + * If number is not a valid octal number, OCT2BIN returns + * the #NUM! error value. + * If OCT2BIN requires more than places characters, it + * returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, + * OCT2BIN uses the minimum number of characters necessary. + * Places is useful for padding the return value with + * leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2BIN returns the #VALUE! + * error value. + * If places is negative, OCT2BIN returns the #NUM! error + * value. + * @return string + */ + public static function OCTTOBIN($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $r = decbin(octdec($x)); + + return self::_nbrConversionFormat($r,$places); + } // function OCTTOBIN() + + + /** + * OCTTODEC + * + * Return an octal value as decimal. + * + * Excel Function: + * OCT2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is not a valid octal number, OCT2DEC returns the + * #NUM! error value. + * @return string + */ + public static function OCTTODEC($x) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return octdec($x); + } // function OCTTODEC() + + + /** + * OCTTOHEX + * + * Return an octal value as hex. + * + * Excel Function: + * OCT2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is negative, OCT2HEX ignores places and returns a + * 10-character hexadecimal number. + * If number is not a valid octal number, OCT2HEX returns the + * #NUM! error value. + * If OCT2HEX requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, OCT2HEX + * uses the minimum number of characters necessary. Places is useful + * for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. + * If places is negative, OCT2HEX returns the #NUM! error value. + * @return string + */ + public static function OCTTOHEX($x, $places=null) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/',$x,$out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $hexVal = strtoupper(dechex(octdec($x))); + + return self::_nbrConversionFormat($hexVal,$places); + } // function OCTTOHEX() + + + /** + * COMPLEX + * + * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj. + * + * Excel Function: + * COMPLEX(realNumber,imaginary[,places]) + * + * @access public + * @category Engineering Functions + * @param float $realNumber The real coefficient of the complex number. + * @param float $imaginary The imaginary coefficient of the complex number. + * @param string $suffix The suffix for the imaginary component of the complex number. + * If omitted, the suffix is assumed to be "i". + * @return string + */ + public static function COMPLEX($realNumber=0.0, $imaginary=0.0, $suffix='i') { + $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber); + $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary); + $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix); + + if (((is_numeric($realNumber)) && (is_numeric($imaginary))) && + (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) { + $realNumber = (float) $realNumber; + $imaginary = (float) $imaginary; + + if ($suffix == '') $suffix = 'i'; + if ($realNumber == 0.0) { + if ($imaginary == 0.0) { + return (string) '0'; + } elseif ($imaginary == 1.0) { + return (string) $suffix; + } elseif ($imaginary == -1.0) { + return (string) '-'.$suffix; + } + return (string) $imaginary.$suffix; + } elseif ($imaginary == 0.0) { + return (string) $realNumber; + } elseif ($imaginary == 1.0) { + return (string) $realNumber.'+'.$suffix; + } elseif ($imaginary == -1.0) { + return (string) $realNumber.'-'.$suffix; + } + if ($imaginary > 0) { $imaginary = (string) '+'.$imaginary; } + return (string) $realNumber.$imaginary.$suffix; + } + + return PHPExcel_Calculation_Functions::VALUE(); + } // function COMPLEX() + + + /** + * IMAGINARY + * + * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMAGINARY(complexNumber) + * + * @access public + * @category Engineering Functions + * @param string $complexNumber The complex number for which you want the imaginary + * coefficient. + * @return float + */ + public static function IMAGINARY($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + return $parsedComplex['imaginary']; + } // function IMAGINARY() + + + /** + * IMREAL + * + * Returns the real coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMREAL(complexNumber) + * + * @access public + * @category Engineering Functions + * @param string $complexNumber The complex number for which you want the real coefficient. + * @return float + */ + public static function IMREAL($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + return $parsedComplex['real']; + } // function IMREAL() + + + /** + * IMABS + * + * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMABS(complexNumber) + * + * @param string $complexNumber The complex number for which you want the absolute value. + * @return float + */ + public static function IMABS($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + return sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])); + } // function IMABS() + + + /** + * IMARGUMENT + * + * Returns the argument theta of a complex number, i.e. the angle in radians from the real + * axis to the representation of the number in polar coordinates. + * + * Excel Function: + * IMARGUMENT(complexNumber) + * + * @param string $complexNumber The complex number for which you want the argument theta. + * @return float + */ + public static function IMARGUMENT($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if ($parsedComplex['real'] == 0.0) { + if ($parsedComplex['imaginary'] == 0.0) { + return 0.0; + } elseif($parsedComplex['imaginary'] < 0.0) { + return M_PI / -2; + } else { + return M_PI / 2; + } + } elseif ($parsedComplex['real'] > 0.0) { + return atan($parsedComplex['imaginary'] / $parsedComplex['real']); + } elseif ($parsedComplex['imaginary'] < 0.0) { + return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real']))); + } else { + return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real'])); + } + } // function IMARGUMENT() + + + /** + * IMCONJUGATE + * + * Returns the complex conjugate of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCONJUGATE(complexNumber) + * + * @param string $complexNumber The complex number for which you want the conjugate. + * @return string + */ + public static function IMCONJUGATE($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return $parsedComplex['real']; + } else { + return self::_cleanComplex( self::COMPLEX( $parsedComplex['real'], + 0 - $parsedComplex['imaginary'], + $parsedComplex['suffix'] + ) + ); + } + } // function IMCONJUGATE() + + + /** + * IMCOS + * + * Returns the cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOS(complexNumber) + * + * @param string $complexNumber The complex number for which you want the cosine. + * @return string|float + */ + public static function IMCOS($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return cos($parsedComplex['real']); + } else { + return self::IMCONJUGATE(self::COMPLEX(cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix'])); + } + } // function IMCOS() + + + /** + * IMSIN + * + * Returns the sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSIN(complexNumber) + * + * @param string $complexNumber The complex number for which you want the sine. + * @return string|float + */ + public static function IMSIN($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return sin($parsedComplex['real']); + } else { + return self::COMPLEX(sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),$parsedComplex['suffix']); + } + } // function IMSIN() + + + /** + * IMSQRT + * + * Returns the square root of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSQRT(complexNumber) + * + * @param string $complexNumber The complex number for which you want the square root. + * @return string + */ + public static function IMSQRT($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + $theta = self::IMARGUMENT($complexNumber); + $d1 = cos($theta / 2); + $d2 = sin($theta / 2); + $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']))); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($d1 * $r,$d2 * $r); + } else { + return self::COMPLEX($d1 * $r,$d2 * $r,$parsedComplex['suffix']); + } + } // function IMSQRT() + + + /** + * IMLN + * + * Returns the natural logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLN(complexNumber) + * + * @param string $complexNumber The complex number for which you want the natural logarithm. + * @return string + */ + public static function IMLN($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']))); + $t = self::IMARGUMENT($complexNumber); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($logR,$t); + } else { + return self::COMPLEX($logR,$t,$parsedComplex['suffix']); + } + } // function IMLN() + + + /** + * IMLOG10 + * + * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG10(complexNumber) + * + * @param string $complexNumber The complex number for which you want the common logarithm. + * @return string + */ + public static function IMLOG10($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return log10($parsedComplex['real']); + } + + return self::IMPRODUCT(log10(EULER),self::IMLN($complexNumber)); + } // function IMLOG10() + + + /** + * IMLOG2 + * + * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG2(complexNumber) + * + * @param string $complexNumber The complex number for which you want the base-2 logarithm. + * @return string + */ + public static function IMLOG2($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return log($parsedComplex['real'],2); + } + + return self::IMPRODUCT(log(EULER,2),self::IMLN($complexNumber)); + } // function IMLOG2() + + + /** + * IMEXP + * + * Returns the exponential of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMEXP(complexNumber) + * + * @param string $complexNumber The complex number for which you want the exponential. + * @return string + */ + public static function IMEXP($complexNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::_parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return '1'; + } + + $e = exp($parsedComplex['real']); + $eX = $e * cos($parsedComplex['imaginary']); + $eY = $e * sin($parsedComplex['imaginary']); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($eX,$eY); + } else { + return self::COMPLEX($eX,$eY,$parsedComplex['suffix']); + } + } // function IMEXP() + + + /** + * IMPOWER + * + * Returns a complex number in x + yi or x + yj text format raised to a power. + * + * Excel Function: + * IMPOWER(complexNumber,realNumber) + * + * @param string $complexNumber The complex number you want to raise to a power. + * @param float $realNumber The power to which you want to raise the complex number. + * @return string + */ + public static function IMPOWER($complexNumber,$realNumber) { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber); + + if (!is_numeric($realNumber)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $parsedComplex = self::_parseComplex($complexNumber); + + $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])); + $rPower = pow($r,$realNumber); + $theta = self::IMARGUMENT($complexNumber) * $realNumber; + if ($theta == 0) { + return 1; + } elseif ($parsedComplex['imaginary'] == 0.0) { + return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']); + } else { + return self::COMPLEX($rPower * cos($theta),$rPower * sin($theta),$parsedComplex['suffix']); + } + } // function IMPOWER() + + + /** + * IMDIV + * + * Returns the quotient of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMDIV(complexDividend,complexDivisor) + * + * @param string $complexDividend The complex numerator or dividend. + * @param string $complexDivisor The complex denominator or divisor. + * @return string + */ + public static function IMDIV($complexDividend,$complexDivisor) { + $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend); + $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor); + + $parsedComplexDividend = self::_parseComplex($complexDividend); + $parsedComplexDivisor = self::_parseComplex($complexDivisor); + + if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') && + ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) { + $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix']; + } + + $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']); + $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']); + $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']); + + $r = $d1/$d3; + $i = $d2/$d3; + + if ($i > 0.0) { + return self::_cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']); + } elseif ($i < 0.0) { + return self::_cleanComplex($r.$i.$parsedComplexDivisor['suffix']); + } else { + return $r; + } + } // function IMDIV() + + + /** + * IMSUB + * + * Returns the difference of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUB(complexNumber1,complexNumber2) + * + * @param string $complexNumber1 The complex number from which to subtract complexNumber2. + * @param string $complexNumber2 The complex number to subtract from complexNumber1. + * @return string + */ + public static function IMSUB($complexNumber1,$complexNumber2) { + $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1); + $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2); + + $parsedComplex1 = self::_parseComplex($complexNumber1); + $parsedComplex2 = self::_parseComplex($complexNumber2); + + if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) && + ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) { + $parsedComplex1['suffix'] = $parsedComplex2['suffix']; + } + + $d1 = $parsedComplex1['real'] - $parsedComplex2['real']; + $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary']; + + return self::COMPLEX($d1,$d2,$parsedComplex1['suffix']); + } // function IMSUB() + + + /** + * IMSUM + * + * Returns the sum of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUM(complexNumber[,complexNumber[,...]]) + * + * @param string $complexNumber,... Series of complex numbers to add + * @return string + */ + public static function IMSUM() { + // Return value + $returnValue = self::_parseComplex('0'); + $activeSuffix = ''; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + $parsedComplex = self::_parseComplex($arg); + + if ($activeSuffix == '') { + $activeSuffix = $parsedComplex['suffix']; + } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $returnValue['real'] += $parsedComplex['real']; + $returnValue['imaginary'] += $parsedComplex['imaginary']; + } + + if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; } + return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix); + } // function IMSUM() + + + /** + * IMPRODUCT + * + * Returns the product of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMPRODUCT(complexNumber[,complexNumber[,...]]) + * + * @param string $complexNumber,... Series of complex numbers to multiply + * @return string + */ + public static function IMPRODUCT() { + // Return value + $returnValue = self::_parseComplex('1'); + $activeSuffix = ''; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + $parsedComplex = self::_parseComplex($arg); + + $workValue = $returnValue; + if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) { + $activeSuffix = $parsedComplex['suffix']; + } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } + $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']); + $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']); + } + + if ($returnValue['imaginary'] == 0.0) { $activeSuffix = ''; } + return self::COMPLEX($returnValue['real'],$returnValue['imaginary'],$activeSuffix); + } // function IMPRODUCT() + + + /** + * DELTA + * + * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. + * Use this function to filter a set of values. For example, by summing several DELTA + * functions you calculate the count of equal pairs. This function is also known as the + * Kronecker Delta function. + * + * Excel Function: + * DELTA(a[,b]) + * + * @param float $a The first number. + * @param float $b The second number. If omitted, b is assumed to be zero. + * @return int + */ + public static function DELTA($a, $b=0) { + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + return (int) ($a == $b); + } // function DELTA() + + + /** + * GESTEP + * + * Excel Function: + * GESTEP(number[,step]) + * + * Returns 1 if number >= step; returns 0 (zero) otherwise + * Use this function to filter a set of values. For example, by summing several GESTEP + * functions you calculate the count of values that exceed a threshold. + * + * @param float $number The value to test against step. + * @param float $step The threshold value. + * If you omit a value for step, GESTEP uses zero. + * @return int + */ + public static function GESTEP($number, $step=0) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $step = PHPExcel_Calculation_Functions::flattenSingleValue($step); + + return (int) ($number >= $step); + } // function GESTEP() + + + // + // Private method to calculate the erf value + // + private static $_two_sqrtpi = 1.128379167095512574; + + public static function _erfVal($x) { + if (abs($x) > 2.2) { + return 1 - self::_erfcVal($x); + } + $sum = $term = $x; + $xsqr = ($x * $x); + $j = 1; + do { + $term *= $xsqr / $j; + $sum -= $term / (2 * $j + 1); + ++$j; + $term *= $xsqr / $j; + $sum += $term / (2 * $j + 1); + ++$j; + if ($sum == 0.0) { + break; + } + } while (abs($term / $sum) > PRECISION); + return self::$_two_sqrtpi * $sum; + } // function _erfVal() + + + /** + * ERF + * + * Returns the error function integrated between the lower and upper bound arguments. + * + * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments, + * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was + * improved, so that it can now calculate the function for both positive and negative ranges. + * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments. + * + * Excel Function: + * ERF(lower[,upper]) + * + * @param float $lower lower bound for integrating ERF + * @param float $upper upper bound for integrating ERF. + * If omitted, ERF integrates between zero and lower_limit + * @return float + */ + public static function ERF($lower, $upper = NULL) { + $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower); + $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper); + + if (is_numeric($lower)) { + if (is_null($upper)) { + return self::_erfVal($lower); + } + if (is_numeric($upper)) { + return self::_erfVal($upper) - self::_erfVal($lower); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ERF() + + + // + // Private method to calculate the erfc value + // + private static $_one_sqrtpi = 0.564189583547756287; + + private static function _erfcVal($x) { + if (abs($x) < 2.2) { + return 1 - self::_erfVal($x); + } + if ($x < 0) { + return 2 - self::ERFC(-$x); + } + $a = $n = 1; + $b = $c = $x; + $d = ($x * $x) + 0.5; + $q1 = $q2 = $b / $d; + $t = 0; + do { + $t = $a * $n + $b * $x; + $a = $b; + $b = $t; + $t = $c * $n + $d * $x; + $c = $d; + $d = $t; + $n += 0.5; + $q1 = $q2; + $q2 = $b / $d; + } while ((abs($q1 - $q2) / $q2) > PRECISION); + return self::$_one_sqrtpi * exp(-$x * $x) * $q2; + } // function _erfcVal() + + + /** + * ERFC + * + * Returns the complementary ERF function integrated between x and infinity + * + * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument, + * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was + * improved, so that it can now calculate the function for both positive and negative x values. + * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments. + * + * Excel Function: + * ERFC(x) + * + * @param float $x The lower bound for integrating ERFC + * @return float + */ + public static function ERFC($x) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_numeric($x)) { + return self::_erfcVal($x); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ERFC() + + + /** + * getConversionGroups + * Returns a list of the different conversion groups for UOM conversions + * + * @return array + */ + public static function getConversionGroups() { + $conversionGroups = array(); + foreach(self::$_conversionUnits as $conversionUnit) { + $conversionGroups[] = $conversionUnit['Group']; + } + return array_merge(array_unique($conversionGroups)); + } // function getConversionGroups() + + + /** + * getConversionGroupUnits + * Returns an array of units of measure, for a specified conversion group, or for all groups + * + * @param string $group The group whose units of measure you want to retrieve + * @return array + */ + public static function getConversionGroupUnits($group = NULL) { + $conversionGroups = array(); + foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) { + if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { + $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; + } + } + return $conversionGroups; + } // function getConversionGroupUnits() + + + /** + * getConversionGroupUnitDetails + * + * @param string $group The group whose units of measure you want to retrieve + * @return array + */ + public static function getConversionGroupUnitDetails($group = NULL) { + $conversionGroups = array(); + foreach(self::$_conversionUnits as $conversionUnit => $conversionGroup) { + if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { + $conversionGroups[$conversionGroup['Group']][] = array( 'unit' => $conversionUnit, + 'description' => $conversionGroup['Unit Name'] + ); + } + } + return $conversionGroups; + } // function getConversionGroupUnitDetails() + + + /** + * getConversionMultipliers + * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() + * + * @return array of mixed + */ + public static function getConversionMultipliers() { + return self::$_conversionMultipliers; + } // function getConversionGroups() + + + /** + * CONVERTUOM + * + * Converts a number from one measurement system to another. + * For example, CONVERT can translate a table of distances in miles to a table of distances + * in kilometers. + * + * Excel Function: + * CONVERT(value,fromUOM,toUOM) + * + * @param float $value The value in fromUOM to convert. + * @param string $fromUOM The units for value. + * @param string $toUOM The units for the result. + * + * @return float + */ + public static function CONVERTUOM($value, $fromUOM, $toUOM) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM); + $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM); + + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $fromMultiplier = 1.0; + if (isset(self::$_conversionUnits[$fromUOM])) { + $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group']; + } else { + $fromMultiplier = substr($fromUOM,0,1); + $fromUOM = substr($fromUOM,1); + if (isset(self::$_conversionMultipliers[$fromMultiplier])) { + $fromMultiplier = self::$_conversionMultipliers[$fromMultiplier]['multiplier']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + if ((isset(self::$_conversionUnits[$fromUOM])) && (self::$_conversionUnits[$fromUOM]['AllowPrefix'])) { + $unitGroup1 = self::$_conversionUnits[$fromUOM]['Group']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + } + $value *= $fromMultiplier; + + $toMultiplier = 1.0; + if (isset(self::$_conversionUnits[$toUOM])) { + $unitGroup2 = self::$_conversionUnits[$toUOM]['Group']; + } else { + $toMultiplier = substr($toUOM,0,1); + $toUOM = substr($toUOM,1); + if (isset(self::$_conversionMultipliers[$toMultiplier])) { + $toMultiplier = self::$_conversionMultipliers[$toMultiplier]['multiplier']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + if ((isset(self::$_conversionUnits[$toUOM])) && (self::$_conversionUnits[$toUOM]['AllowPrefix'])) { + $unitGroup2 = self::$_conversionUnits[$toUOM]['Group']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + } + if ($unitGroup1 != $unitGroup2) { + return PHPExcel_Calculation_Functions::NA(); + } + + if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) { + // We've already factored $fromMultiplier into the value, so we need + // to reverse it again + return $value / $fromMultiplier; + } elseif ($unitGroup1 == 'Temperature') { + if (($fromUOM == 'F') || ($fromUOM == 'fah')) { + if (($toUOM == 'F') || ($toUOM == 'fah')) { + return $value; + } else { + $value = (($value - 32) / 1.8); + if (($toUOM == 'K') || ($toUOM == 'kel')) { + $value += 273.15; + } + return $value; + } + } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) && + (($toUOM == 'K') || ($toUOM == 'kel'))) { + return $value; + } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) && + (($toUOM == 'C') || ($toUOM == 'cel'))) { + return $value; + } + if (($toUOM == 'F') || ($toUOM == 'fah')) { + if (($fromUOM == 'K') || ($fromUOM == 'kel')) { + $value -= 273.15; + } + return ($value * 1.8) + 32; + } + if (($toUOM == 'C') || ($toUOM == 'cel')) { + return $value - 273.15; + } + return $value + 273.15; + } + return ($value * self::$_unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier; + } // function CONVERTUOM() + +} // class PHPExcel_Calculation_Engineering diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php new file mode 100644 index 00000000..037f7884 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php @@ -0,0 +1,52 @@ +line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php new file mode 100644 index 00000000..389f6477 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php @@ -0,0 +1,49 @@ +format('d') == $testDate->format('t')); + } // function _lastDayOfMonth() + + + /** + * _firstDayOfMonth + * + * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month + * + * @param DateTime $testDate The date for testing + * @return boolean + */ + private static function _firstDayOfMonth($testDate) + { + return ($testDate->format('d') == 1); + } // function _firstDayOfMonth() + + + private static function _coupFirstPeriodDate($settlement, $maturity, $frequency, $next) + { + $months = 12 / $frequency; + + $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity); + $eom = self::_lastDayOfMonth($result); + + while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) { + $result->modify('-'.$months.' months'); + } + if ($next) { + $result->modify('+'.$months.' months'); + } + + if ($eom) { + $result->modify('-1 day'); + } + + return PHPExcel_Shared_Date::PHPToExcel($result); + } // function _coupFirstPeriodDate() + + + private static function _validFrequency($frequency) + { + if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) { + return true; + } + if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) && + (($frequency == 6) || ($frequency == 12))) { + return true; + } + return false; + } // function _validFrequency() + + + /** + * _daysPerYear + * + * Returns the number of days in a specified year, as defined by the "basis" value + * + * @param integer $year The year against which we're testing + * @param integer $basis The type of day count: + * 0 or omitted US (NASD) 360 + * 1 Actual (365 or 366 in a leap year) + * 2 360 + * 3 365 + * 4 European 360 + * @return integer + */ + private static function _daysPerYear($year, $basis=0) + { + switch ($basis) { + case 0 : + case 2 : + case 4 : + $daysPerYear = 360; + break; + case 3 : + $daysPerYear = 365; + break; + case 1 : + $daysPerYear = (PHPExcel_Calculation_DateTime::_isLeapYear($year)) ? 366 : 365; + break; + default : + return PHPExcel_Calculation_Functions::NaN(); + } + return $daysPerYear; + } // function _daysPerYear() + + + private static function _interestAndPrincipal($rate=0, $per=0, $nper=0, $pv=0, $fv=0, $type=0) + { + $pmt = self::PMT($rate, $nper, $pv, $fv, $type); + $capital = $pv; + for ($i = 1; $i<= $per; ++$i) { + $interest = ($type && $i == 1) ? 0 : -$capital * $rate; + $principal = $pmt - $interest; + $capital += $principal; + } + return array($interest, $principal); + } // function _interestAndPrincipal() + + + /** + * ACCRINT + * + * Returns the accrued interest for a security that pays periodic interest. + * + * Excel Function: + * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed $issue The security's issue date. + * @param mixed $firstinterest The security's first interest date. + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date + * when the security is traded to the buyer. + * @param float $rate The security's annual coupon rate. + * @param float $par The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param integer $frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par=1000, $frequency=1, $basis=0) + { + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest); + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par); + $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($rate)) && (is_numeric($par))) { + $rate = (float) $rate; + $par = (float) $par; + if (($rate <= 0) || ($par <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + + return $par * $rate * $daysBetweenIssueAndSettlement; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ACCRINT() + + + /** + * ACCRINTM + * + * Returns the accrued interest for a security that pays interest at maturity. + * + * Excel Function: + * ACCRINTM(issue,settlement,rate[,par[,basis]]) + * + * @access public + * @category Financial Functions + * @param mixed issue The security's issue date. + * @param mixed settlement The security's settlement (or maturity) date. + * @param float rate The security's annual coupon rate. + * @param float par The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function ACCRINTM($issue, $settlement, $rate, $par=1000, $basis=0) { + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par); + $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($rate)) && (is_numeric($par))) { + $rate = (float) $rate; + $par = (float) $par; + if (($rate <= 0) || ($par <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + return $par * $rate * $daysBetweenIssueAndSettlement; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ACCRINTM() + + + /** + * AMORDEGRC + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * The function is similar to AMORLINC, except that a depreciation coefficient is applied in + * the calculation depending on the life of the assets. + * This function will return the depreciation until the last period of the life of the assets + * or until the cumulated value of depreciation is greater than the cost of the assets minus + * the salvage value. + * + * Excel Function: + * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @access public + * @category Financial Functions + * @param float cost The cost of the asset. + * @param mixed purchased Date of the purchase of the asset. + * @param mixed firstPeriod Date of the end of the first period. + * @param mixed salvage The salvage value at the end of the life of the asset. + * @param float period The period. + * @param float rate Rate of depreciation. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased); + $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period)); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // The depreciation coefficients are: + // Life of assets (1/rate) Depreciation coefficient + // Less than 3 years 1 + // Between 3 and 4 years 1.5 + // Between 5 and 6 years 2 + // More than 6 years 2.5 + $fUsePer = 1.0 / $rate; + if ($fUsePer < 3.0) { + $amortiseCoeff = 1.0; + } elseif ($fUsePer < 5.0) { + $amortiseCoeff = 1.5; + } elseif ($fUsePer <= 6.0) { + $amortiseCoeff = 2.0; + } else { + $amortiseCoeff = 2.5; + } + + $rate *= $amortiseCoeff; + $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost,0); + $cost -= $fNRate; + $fRest = $cost - $salvage; + + for ($n = 0; $n < $period; ++$n) { + $fNRate = round($rate * $cost,0); + $fRest -= $fNRate; + + if ($fRest < 0.0) { + switch ($period - $n) { + case 0 : + case 1 : return round($cost * 0.5, 0); + break; + default : return 0.0; + break; + } + } + $cost -= $fNRate; + } + return $fNRate; + } // function AMORDEGRC() + + + /** + * AMORLINC + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * + * Excel Function: + * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @access public + * @category Financial Functions + * @param float cost The cost of the asset. + * @param mixed purchased Date of the purchase of the asset. + * @param mixed firstPeriod Date of the end of the first period. + * @param mixed salvage The salvage value at the end of the life of the asset. + * @param float period The period. + * @param float rate Rate of depreciation. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis=0) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased); + $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + $fOneRate = $cost * $rate; + $fCostDelta = $cost - $salvage; + // Note, quirky variation for leap years on the YEARFRAC for this function + $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased); + $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis); + + if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::_isLeapYear($purchasedYear))) { + $yearFrac *= 365 / 366; + } + + $f0Rate = $yearFrac * $rate * $cost; + $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate); + + if ($period == 0) { + return $f0Rate; + } elseif ($period <= $nNumOfFullPeriods) { + return $fOneRate; + } elseif ($period == ($nNumOfFullPeriods + 1)) { + return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate); + } else { + return 0.0; + } + } // function AMORLINC() + + + /** + * COUPDAYBS + * + * Returns the number of days from the beginning of the coupon period to the settlement date. + * + * Excel Function: + * COUPDAYBS(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYBS($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis); + $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False); + + return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear; + } // function COUPDAYBS() + + + /** + * COUPDAYS + * + * Returns the number of days in the coupon period that contains the settlement date. + * + * Excel Function: + * COUPDAYS(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYS($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch ($basis) { + case 3: // Actual/365 + return 365 / $frequency; + case 1: // Actual/actual + if ($frequency == 1) { + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity),$basis); + return ($daysPerYear / $frequency); + } else { + $prev = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False); + $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True); + return ($next - $prev); + } + default: // US (NASD) 30/360, Actual/360 or European 30/360 + return 360 / $frequency; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function COUPDAYS() + + + /** + * COUPDAYSNC + * + * Returns the number of days from the settlement date to the next coupon date. + * + * Excel Function: + * COUPDAYSNC(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis); + $next = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True); + + return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear; + } // function COUPDAYSNC() + + + /** + * COUPNCD + * + * Returns the next coupon date after the settlement date. + * + * Excel Function: + * COUPNCD(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPNCD($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True); + } // function COUPNCD() + + + /** + * COUPNUM + * + * Returns the number of coupons payable between the settlement date and maturity date, + * rounded up to the nearest whole coupon. + * + * Excel Function: + * COUPNUM(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return integer + */ + public static function COUPNUM($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $settlement = self::_coupFirstPeriodDate($settlement, $maturity, $frequency, True); + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365; + + switch ($frequency) { + case 1: // annual payments + return ceil($daysBetweenSettlementAndMaturity / 360); + case 2: // half-yearly + return ceil($daysBetweenSettlementAndMaturity / 180); + case 4: // quarterly + return ceil($daysBetweenSettlementAndMaturity / 90); + case 6: // bimonthly + return ceil($daysBetweenSettlementAndMaturity / 60); + case 12: // monthly + return ceil($daysBetweenSettlementAndMaturity / 30); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function COUPNUM() + + + /** + * COUPPCD + * + * Returns the previous coupon date before the settlement date. + * + * Excel Function: + * COUPPCD(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPPCD($settlement, $maturity, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::_coupFirstPeriodDate($settlement, $maturity, $frequency, False); + } // function COUPPCD() + + + /** + * CUMIPMT + * + * Returns the cumulative interest paid on a loan between the start and end periods. + * + * Excel Function: + * CUMIPMT(rate,nper,pv,start,end[,type]) + * + * @access public + * @category Financial Functions + * @param float $rate The Interest rate + * @param integer $nper The total number of payment periods + * @param float $pv Present Value + * @param integer $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param integer $end The last period in the calculation. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start); + $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($start < 1 || $start > $end) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interest = 0; + for ($per = $start; $per <= $end; ++$per) { + $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type); + } + + return $interest; + } // function CUMIPMT() + + + /** + * CUMPRINC + * + * Returns the cumulative principal paid on a loan between the start and end periods. + * + * Excel Function: + * CUMPRINC(rate,nper,pv,start,end[,type]) + * + * @access public + * @category Financial Functions + * @param float $rate The Interest rate + * @param integer $nper The total number of payment periods + * @param float $pv Present Value + * @param integer $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param integer $end The last period in the calculation. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start); + $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($start < 1 || $start > $end) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $principal = 0; + for ($per = $start; $per <= $end; ++$per) { + $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type); + } + + return $principal; + } // function CUMPRINC() + + + /** + * DB + * + * Returns the depreciation of an asset for a specified period using the + * fixed-declining balance method. + * This form of depreciation is used if you want to get a higher depreciation value + * at the beginning of the depreciation (as opposed to linear depreciation). The + * depreciation value is reduced with every depreciation period by the depreciation + * already deducted from the initial cost. + * + * Excel Function: + * DB(cost,salvage,life,period[,month]) + * + * @access public + * @category Financial Functions + * @param float cost Initial cost of the asset. + * @param float salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param integer life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param integer period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param integer month Number of months in the first year. If month is omitted, + * it defaults to 12. + * @return float + */ + public static function DB($cost, $salvage, $life, $period, $month=12) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $month = PHPExcel_Calculation_Functions::flattenSingleValue($month); + + // Validate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) { + $cost = (float) $cost; + $salvage = (float) $salvage; + $life = (int) $life; + $period = (int) $period; + $month = (int) $month; + if ($cost == 0) { + return 0.0; + } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + $previousDepreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + if ($per == 1) { + $depreciation = $cost * $fixedDepreciationRate * $month / 12; + } elseif ($per == ($life + 1)) { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; + } else { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; + } + $previousDepreciation += $depreciation; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $depreciation = round($depreciation,2); + } + return $depreciation; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function DB() + + + /** + * DDB + * + * Returns the depreciation of an asset for a specified period using the + * double-declining balance method or some other method you specify. + * + * Excel Function: + * DDB(cost,salvage,life,period[,factor]) + * + * @access public + * @category Financial Functions + * @param float cost Initial cost of the asset. + * @param float salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param integer life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param integer period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param float factor The rate at which the balance declines. + * If factor is omitted, it is assumed to be 2 (the + * double-declining balance method). + * @return float + */ + public static function DDB($cost, $salvage, $life, $period, $factor=2.0) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor); + + // Validate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) { + $cost = (float) $cost; + $salvage = (float) $salvage; + $life = (int) $life; + $period = (int) $period; + $factor = (float) $factor; + if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + $previousDepreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + $depreciation = min( ($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation) ); + $previousDepreciation += $depreciation; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $depreciation = round($depreciation,2); + } + return $depreciation; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function DDB() + + + /** + * DISC + * + * Returns the discount rate for a security. + * + * Excel Function: + * DISC(settlement,maturity,price,redemption[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param integer price The security's price per $100 face value. + * @param integer redemption The security's redemption value per $100 face value. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function DISC($settlement, $maturity, $price, $redemption, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) { + $price = (float) $price; + $redemption = (float) $redemption; + $basis = (int) $basis; + if (($price <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function DISC() + + + /** + * DOLLARDE + * + * Converts a dollar price expressed as an integer part and a fraction + * part into a dollar price expressed as a decimal number. + * Fractional dollar numbers are sometimes used for security prices. + * + * Excel Function: + * DOLLARDE(fractional_dollar,fraction) + * + * @access public + * @category Financial Functions + * @param float $fractional_dollar Fractional Dollar + * @param integer $fraction Fraction + * @return float + */ + public static function DOLLARDE($fractional_dollar = Null, $fraction = 0) { + $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar); + $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction); + + // Validate parameters + if (is_null($fractional_dollar) || $fraction < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($fraction == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $dollars = floor($fractional_dollar); + $cents = fmod($fractional_dollar,1); + $cents /= $fraction; + $cents *= pow(10,ceil(log10($fraction))); + return $dollars + $cents; + } // function DOLLARDE() + + + /** + * DOLLARFR + * + * Converts a dollar price expressed as a decimal number into a dollar price + * expressed as a fraction. + * Fractional dollar numbers are sometimes used for security prices. + * + * Excel Function: + * DOLLARFR(decimal_dollar,fraction) + * + * @access public + * @category Financial Functions + * @param float $decimal_dollar Decimal Dollar + * @param integer $fraction Fraction + * @return float + */ + public static function DOLLARFR($decimal_dollar = Null, $fraction = 0) { + $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar); + $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction); + + // Validate parameters + if (is_null($decimal_dollar) || $fraction < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($fraction == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $dollars = floor($decimal_dollar); + $cents = fmod($decimal_dollar,1); + $cents *= $fraction; + $cents *= pow(10,-ceil(log10($fraction))); + return $dollars + $cents; + } // function DOLLARFR() + + + /** + * EFFECT + * + * Returns the effective interest rate given the nominal rate and the number of + * compounding payments per year. + * + * Excel Function: + * EFFECT(nominal_rate,npery) + * + * @access public + * @category Financial Functions + * @param float $nominal_rate Nominal interest rate + * @param integer $npery Number of compounding payments per year + * @return float + */ + public static function EFFECT($nominal_rate = 0, $npery = 0) { + $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate); + $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery); + + // Validate parameters + if ($nominal_rate <= 0 || $npery < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return pow((1 + $nominal_rate / $npery), $npery) - 1; + } // function EFFECT() + + + /** + * FV + * + * Returns the Future Value of a cash flow with constant payments and interest rate (annuities). + * + * Excel Function: + * FV(rate,nper,pmt[,pv[,type]]) + * + * @access public + * @category Financial Functions + * @param float $rate The interest rate per period + * @param int $nper Total number of payment periods in an annuity + * @param float $pmt The payment made each period: it cannot change over the + * life of the annuity. Typically, pmt contains principal + * and interest but no other fees or taxes. + * @param float $pv Present Value, or the lump-sum amount that a series of + * future payments is worth right now. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate; + } else { + return -$pv - $pmt * $nper; + } + } // function FV() + + + /** + * FVSCHEDULE + * + * Returns the future value of an initial principal after applying a series of compound interest rates. + * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate. + * + * Excel Function: + * FVSCHEDULE(principal,schedule) + * + * @param float $principal The present value. + * @param float[] $schedule An array of interest rates to apply. + * @return float + */ + public static function FVSCHEDULE($principal, $schedule) { + $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal); + $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule); + + foreach($schedule as $rate) { + $principal *= 1 + $rate; + } + + return $principal; + } // function FVSCHEDULE() + + + /** + * INTRATE + * + * Returns the interest rate for a fully invested security. + * + * Excel Function: + * INTRATE(settlement,maturity,investment,redemption[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param integer $investment The amount invested in the security. + * @param integer $redemption The amount to be received at maturity. + * @param integer $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) { + $investment = (float) $investment; + $redemption = (float) $redemption; + $basis = (int) $basis; + if (($investment <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function INTRATE() + + + /** + * IPMT + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * + * Excel Function: + * IPMT(rate,per,nper,pv[,fv][,type]) + * + * @param float $rate Interest rate per period + * @param int $per Period for which we want to find the interest + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($per <= 0 || $per > $nper) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[0]; + } // function IPMT() + + /** + * IRR + * + * Returns the internal rate of return for a series of cash flows represented by the numbers in values. + * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur + * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received + * for an investment consisting of payments (negative values) and income (positive values) that occur at regular + * periods. + * + * Excel Function: + * IRR(values[,guess]) + * + * @param float[] $values An array or a reference to cells that contain numbers for which you want + * to calculate the internal rate of return. + * Values must contain at least one positive value and one negative value to + * calculate the internal rate of return. + * @param float $guess A number that you guess is close to the result of IRR + * @return float + */ + public static function IRR($values, $guess = 0.1) { + if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE(); + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess); + + // create an initial range, with a root somewhere between 0 and guess + $x1 = 0.0; + $x2 = $guess; + $f1 = self::NPV($x1, $values); + $f2 = self::NPV($x2, $values); + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + if (($f1 * $f2) < 0.0) break; + if (abs($f1) < abs($f2)) { + $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values); + } else { + $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values); + } + } + if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE(); + + $f = self::NPV($x1, $values); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::NPV($x_mid, $values); + if ($f_mid <= 0.0) + $rtb = $x_mid; + if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) + return $x_mid; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function IRR() + + + /** + * ISPMT + * + * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. + * + * Excel Function: + * =ISPMT(interest_rate, period, number_payments, PV) + * + * interest_rate is the interest rate for the investment + * + * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. + * + * number_payments is the number of payments for the annuity + * + * PV is the loan amount or present value of the payments + */ + public static function ISPMT() { + // Return value + $returnValue = 0; + + // Get the parameters + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $interestRate = array_shift($aArgs); + $period = array_shift($aArgs); + $numberPeriods = array_shift($aArgs); + $principleRemaining = array_shift($aArgs); + + // Calculate + $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0); + for($i=0; $i <= $period; ++$i) { + $returnValue = $interestRate * $principleRemaining * -1; + $principleRemaining -= $principlePayment; + // principle needs to be 0 after the last payment, don't let floating point screw it up + if($i == $numberPeriods) { + $returnValue = 0; + } + } + return($returnValue); + } // function ISPMT() + + + /** + * MIRR + * + * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both + * the cost of the investment and the interest received on reinvestment of cash. + * + * Excel Function: + * MIRR(values,finance_rate, reinvestment_rate) + * + * @param float[] $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param float $finance_rate The interest rate you pay on the money used in the cash flows + * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them + * @return float + */ + public static function MIRR($values, $finance_rate, $reinvestment_rate) { + if (!is_array($values)) return PHPExcel_Calculation_Functions::VALUE(); + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate); + $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate); + $n = count($values); + + $rr = 1.0 + $reinvestment_rate; + $fr = 1.0 + $finance_rate; + + $npv_pos = $npv_neg = 0.0; + foreach($values as $i => $v) { + if ($v >= 0) { + $npv_pos += $v / pow($rr, $i); + } else { + $npv_neg += $v / pow($fr, $i); + } + } + + if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $mirr = pow((-$npv_pos * pow($rr, $n)) + / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0; + + return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE()); + } // function MIRR() + + + /** + * NOMINAL + * + * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. + * + * @param float $effect_rate Effective interest rate + * @param int $npery Number of compounding payments per year + * @return float + */ + public static function NOMINAL($effect_rate = 0, $npery = 0) { + $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate); + $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery); + + // Validate parameters + if ($effect_rate <= 0 || $npery < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + return $npery * (pow($effect_rate + 1, 1 / $npery) - 1); + } // function NOMINAL() + + + /** + * NPER + * + * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. + * + * @param float $rate Interest rate per period + * @param int $pmt Periodic payment (annuity) + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + if ($pmt == 0 && $pv == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate); + } else { + if ($pmt == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (-$pv -$fv) / $pmt; + } + } // function NPER() + + /** + * NPV + * + * Returns the Net Present Value of a cash flow series given a discount rate. + * + * @return float + */ + public static function NPV() { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $rate = array_shift($aArgs); + for ($i = 1; $i <= count($aArgs); ++$i) { + // Is it a numeric value? + if (is_numeric($aArgs[$i - 1])) { + $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i); + } + } + + // Return + return $returnValue; + } // function NPV() + + /** + * PMT + * + * Returns the constant payment (annuity) for a cash flow with a constant interest rate. + * + * @param float $rate Interest rate per period + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate); + } else { + return (-$pv - $fv) / $nper; + } + } // function PMT() + + + /** + * PPMT + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * + * @param float $rate Interest rate per period + * @param int $per Period for which we want to find the interest + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($per <= 0 || $per > $nper) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interestAndPrincipal = self::_interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[1]; + } // function PPMT() + + + public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield); + $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::_getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::_validFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis); + $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis); + $n = self::COUPNUM($settlement, $maturity, $frequency, $basis); + $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis); + + $baseYF = 1.0 + ($yield / $frequency); + $rfp = 100 * ($rate / $frequency); + $de = $dsc / $e; + + $result = $redemption / pow($baseYF, (--$n + $de)); + for($k = 0; $k <= $n; ++$k) { + $result += $rfp / (pow($baseYF, ($k + $de))); + } + $result -= $rfp * ($a / $e); + + return $result; + } // function PRICE() + + + /** + * PRICEDISC + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int discount The security's discount rate. + * @param int redemption The security's redemption value per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount); + $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) { + if (($discount <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function PRICEDISC() + + + /** + * PRICEMAT + * + * Returns the price per $100 face value of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed issue The security's issue date. + * @param int rate The security's interest rate at date of issue. + * @param int yield The security's annual yield. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($rate) && is_numeric($yield)) { + if (($rate <= 0) || ($yield <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / + (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function PRICEMAT() + + + /** + * PV + * + * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). + * + * @param float $rate Interest rate per period + * @param int $nper Number of periods + * @param float $pmt Periodic payment (annuity) + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper); + } else { + return -$fv - $pmt * $nper; + } + } // function PV() + + + /** + * RATE + * + * Returns the interest rate per period of an annuity. + * RATE is calculated by iteration and can have zero or more solutions. + * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, + * RATE returns the #NUM! error value. + * + * Excel Function: + * RATE(nper,pmt,pv[,fv[,type[,guess]]]) + * + * @access public + * @category Financial Functions + * @param float nper The total number of payment periods in an annuity. + * @param float pmt The payment made each period and cannot change over the life + * of the annuity. + * Typically, pmt includes principal and interest but no other + * fees or taxes. + * @param float pv The present value - the total amount that a series of future + * payments is worth now. + * @param float fv The future value, or a cash balance you want to attain after + * the last payment is made. If fv is omitted, it is assumed + * to be 0 (the future value of a loan, for example, is 0). + * @param integer type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @param float guess Your guess for what the rate will be. + * If you omit guess, it is assumed to be 10 percent. + * @return float + **/ + public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) { + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess); + + $rate = $guess; + if (abs($rate) < FINANCIAL_PRECISION) { + $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; + } else { + $f = exp($nper * log(1 + $rate)); + $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + } + $y0 = $pv + $pmt * $nper + $fv; + $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + + // find root by secant method + $i = $x0 = 0.0; + $x1 = $rate; + while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) { + $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0); + $x0 = $x1; + $x1 = $rate; + if (($nper * abs($pmt)) > ($pv - $fv)) + $x1 = abs($x1); + + if (abs($rate) < FINANCIAL_PRECISION) { + $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; + } else { + $f = exp($nper * log(1 + $rate)); + $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + } + + $y0 = $y1; + $y1 = $y; + ++$i; + } + return $rate; + } // function RATE() + + + /** + * RECEIVED + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int investment The amount invested in the security. + * @param int discount The security's discount rate. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment); + $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) { + if (($investment <= 0) || ($discount <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function RECEIVED() + + + /** + * SLN + * + * Returns the straight-line depreciation of an asset for one period + * + * @param cost Initial cost of the asset + * @param salvage Value at the end of the depreciation + * @param life Number of periods over which the asset is depreciated + * @return float + */ + public static function SLN($cost, $salvage, $life) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + + // Calculate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) { + if ($life < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return ($cost - $salvage) / $life; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SLN() + + + /** + * SYD + * + * Returns the sum-of-years' digits depreciation of an asset for a specified period. + * + * @param cost Initial cost of the asset + * @param salvage Value at the end of the depreciation + * @param life Number of periods over which the asset is depreciated + * @param period Period + * @return float + */ + public static function SYD($cost, $salvage, $life, $period) { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + + // Calculate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) { + if (($life < 1) || ($period > $life)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SYD() + + + /** + * TBILLEQ + * + * Returns the bond-equivalent yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int discount The Treasury bill's discount rate. + * @return float + */ + public static function TBILLEQ($settlement, $maturity, $discount) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount); + + // Use TBILLPRICE for validation + $testValue = self::TBILLPRICE($settlement, $maturity, $discount); + if (is_string($testValue)) { + return $testValue; + } + + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement)); + } + + return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + } // function TBILLEQ() + + + /** + * TBILLPRICE + * + * Returns the yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int discount The Treasury bill's discount rate. + * @return float + */ + public static function TBILLPRICE($settlement, $maturity, $discount) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount); + + if (is_string($maturity = PHPExcel_Calculation_DateTime::_getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Validate + if (is_numeric($discount)) { + if ($discount <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement)); + } + + if ($daysBetweenSettlementAndMaturity > 360) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); + if ($price <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $price; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TBILLPRICE() + + + /** + * TBILLYIELD + * + * Returns the yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int price The Treasury bill's price per $100 face value. + * @return float + */ + public static function TBILLYIELD($settlement, $maturity, $price) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + + // Validate + if (is_numeric($price)) { + if ($price <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::_getDateValue($maturity) - PHPExcel_Calculation_DateTime::_getDateValue($settlement)); + } + + if ($daysBetweenSettlementAndMaturity > 360) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TBILLYIELD() + + + public static function XIRR($values, $dates, $guess = 0.1) { + if ((!is_array($values)) && (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE(); + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $dates = PHPExcel_Calculation_Functions::flattenArray($dates); + $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess); + if (count($values) != count($dates)) return PHPExcel_Calculation_Functions::NaN(); + + // create an initial range, with a root somewhere between 0 and guess + $x1 = 0.0; + $x2 = $guess; + $f1 = self::XNPV($x1, $values, $dates); + $f2 = self::XNPV($x2, $values, $dates); + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + if (($f1 * $f2) < 0.0) break; + if (abs($f1) < abs($f2)) { + $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates); + } else { + $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates); + } + } + if (($f1 * $f2) > 0.0) return PHPExcel_Calculation_Functions::VALUE(); + + $f = self::XNPV($x1, $values, $dates); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::XNPV($x_mid, $values, $dates); + if ($f_mid <= 0.0) $rtb = $x_mid; + if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) return $x_mid; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * XNPV + * + * Returns the net present value for a schedule of cash flows that is not necessarily periodic. + * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. + * + * Excel Function: + * =XNPV(rate,values,dates) + * + * @param float $rate The discount rate to apply to the cash flows. + * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. The series of values must contain at least one positive value and one negative value. + * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. The first payment date indicates the beginning of the schedule of payments. All other dates must be later than this date, but they may occur in any order. + * @return float + */ + public static function XNPV($rate, $values, $dates) { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + if (!is_numeric($rate)) return PHPExcel_Calculation_Functions::VALUE(); + if ((!is_array($values)) || (!is_array($dates))) return PHPExcel_Calculation_Functions::VALUE(); + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $dates = PHPExcel_Calculation_Functions::flattenArray($dates); + $valCount = count($values); + if ($valCount != count($dates)) return PHPExcel_Calculation_Functions::NaN(); + if ((min($values) > 0) || (max($values) < 0)) return PHPExcel_Calculation_Functions::VALUE(); + + $xnpv = 0.0; + for ($i = 0; $i < $valCount; ++$i) { + if (!is_numeric($values[$i])) return PHPExcel_Calculation_Functions::VALUE(); + $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0],$dates[$i],'d') / 365); + } + return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE(); + } // function XNPV() + + + /** + * YIELDDISC + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int price The security's price per $100 face value. + * @param int redemption The security's redemption value per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($price) && is_numeric($redemption)) { + if (($price <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity,$basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function YIELDDISC() + + + /** + * YIELDMAT + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed issue The security's issue date. + * @param int rate The security's interest rate at date of issue. + * @param int price The security's price per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis=0) { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($rate) && is_numeric($price)) { + if (($rate <= 0) || ($price <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::_daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement),$basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * + ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function YIELDMAT() + +} // class PHPExcel_Calculation_Financial diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php new file mode 100644 index 00000000..754a638d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php @@ -0,0 +1,614 @@ +<"; + const OPERATORS_POSTFIX = "%"; + + /** + * Formula + * + * @var string + */ + private $_formula; + + /** + * Tokens + * + * @var PHPExcel_Calculation_FormulaToken[] + */ + private $_tokens = array(); + + /** + * Create a new PHPExcel_Calculation_FormulaParser + * + * @param string $pFormula Formula to parse + * @throws PHPExcel_Calculation_Exception + */ + public function __construct($pFormula = '') + { + // Check parameters + if (is_null($pFormula)) { + throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula"); + } + + // Initialise values + $this->_formula = trim($pFormula); + // Parse! + $this->_parseToTokens(); + } + + /** + * Get Formula + * + * @return string + */ + public function getFormula() { + return $this->_formula; + } + + /** + * Get Token + * + * @param int $pId Token id + * @return string + * @throws PHPExcel_Calculation_Exception + */ + public function getToken($pId = 0) { + if (isset($this->_tokens[$pId])) { + return $this->_tokens[$pId]; + } else { + throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist."); + } + } + + /** + * Get Token count + * + * @return string + */ + public function getTokenCount() { + return count($this->_tokens); + } + + /** + * Get Tokens + * + * @return PHPExcel_Calculation_FormulaToken[] + */ + public function getTokens() { + return $this->_tokens; + } + + /** + * Parse to tokens + */ + private function _parseToTokens() { + // No attempt is made to verify formulas; assumes formulas are derived from Excel, where + // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. + + // Check if the formula has a valid starting = + $formulaLength = strlen($this->_formula); + if ($formulaLength < 2 || $this->_formula{0} != '=') return; + + // Helper variables + $tokens1 = $tokens2 = $stack = array(); + $inString = $inPath = $inRange = $inError = false; + $token = $previousToken = $nextToken = null; + + $index = 1; + $value = ''; + + $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"); + $COMPARATORS_MULTI = array(">=", "<=", "<>"); + + while ($index < $formulaLength) { + // state-dependent character evaluation (order is important) + + // double-quoted strings + // embeds are doubled + // end marks token + if ($inString) { + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) { + if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) { + $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE; + ++$index; + } else { + $inString = false; + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT); + $value = ""; + } + } else { + $value .= $this->_formula{$index}; + } + ++$index; + continue; + } + + // single-quoted strings (links) + // embeds are double + // end does not mark a token + if ($inPath) { + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) { + if ((($index + 2) <= $formulaLength) && ($this->_formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) { + $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE; + ++$index; + } else { + $inPath = false; + } + } else { + $value .= $this->_formula{$index}; + } + ++$index; + continue; + } + + // bracked strings (R1C1 range index or linked workbook name) + // no embeds (changed to "()" by Excel) + // end does not mark a token + if ($inRange) { + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) { + $inRange = false; + } + $value .= $this->_formula{$index}; + ++$index; + continue; + } + + // error values + // end marks a token, determined from absolute list of values + if ($inError) { + $value .= $this->_formula{$index}; + ++$index; + if (in_array($value, $ERRORS)) { + $inError = false; + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR); + $value = ""; + } + continue; + } + + // scientific notation check + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->_formula{$index}) !== false) { + if (strlen($value) > 1) { + if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->_formula{$index}) != 0) { + $value .= $this->_formula{$index}; + ++$index; + continue; + } + } + } + + // independent character evaluation (order not important) + + // establish state-dependent character evaluations + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) { + if (strlen($value > 0)) { // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inString = true; + ++$index; + continue; + } + + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) { + if (strlen($value) > 0) { // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inPath = true; + ++$index; + continue; + } + + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) { + $inRange = true; + $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN; + ++$index; + continue; + } + + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) { + if (strlen($value) > 0) { // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inError = true; + $value .= PHPExcel_Calculation_FormulaParser::ERROR_START; + ++$index; + continue; + } + + // mark start and end of arrays and array rows + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) { + if (strlen($value) > 0) { // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + ++$index; + continue; + } + + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT); + $tokens1[] = $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + ++$index; + continue; + } + + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + ++$index; + continue; + } + + // trim white-space + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE); + ++$index; + while (($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) { + ++$index; + } + continue; + } + + // multi-character comparators + if (($index + 2) <= $formulaLength) { + if (in_array(substr($this->_formula, $index, 2), $COMPARATORS_MULTI)) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->_formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + $index += 2; + continue; + } + } + + // standard infix operators + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->_formula{$index}) !== false) { + if (strlen($value) > 0) { + $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX); + ++$index; + continue; + } + + // standard postfix operators (only one) + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->_formula{$index}) !== false) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->_formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); + ++$index; + continue; + } + + // start subexpression or function + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) { + if (strlen($value) > 0) { + $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + $value = ""; + } else { + $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + } + ++$index; + continue; + } + + // function, subexpression, or array parameters, or operand unions + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $stack[] = $tmp; + + if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION); + } else { + $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT); + } + ++$index; + continue; + } + + // stop subexpression + if ($this->_formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + ++$index; + continue; + } + + // token accumulation + $value .= $this->_formula{$index}; + ++$index; + } + + // dump remaining accumulation + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + } + + // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections + $tokenCount = count($tokens1); + for ($i = 0; $i < $tokenCount; ++$i) { + $token = $tokens1[$i]; + if (isset($tokens1[$i - 1])) { + $previousToken = $tokens1[$i - 1]; + } else { + $previousToken = null; + } + if (isset($tokens1[$i + 1])) { + $nextToken = $tokens1[$i + 1]; + } else { + $nextToken = null; + } + + if (is_null($token)) { + continue; + } + + if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) { + $tokens2[] = $token; + continue; + } + + if (is_null($previousToken)) { + continue; + } + + if (! ( + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) ) { + continue; + } + + if (is_null($nextToken)) { + continue; + } + + if (! ( + (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) || + (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) || + ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) ) { + continue; + } + + $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION); + } + + // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators + // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names + $this->_tokens = array(); + + $tokenCount = count($tokens2); + for ($i = 0; $i < $tokenCount; ++$i) { + $token = $tokens2[$i]; + if (isset($tokens2[$i - 1])) { + $previousToken = $tokens2[$i - 1]; + } else { + $previousToken = null; + } + if (isset($tokens2[$i + 1])) { + $nextToken = $tokens2[$i + 1]; + } else { + $nextToken = null; + } + + if (is_null($token)) { + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") { + if ($i == 0) { + $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX); + } else if ( + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } else { + $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX); + } + + $this->_tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") { + if ($i == 0) { + continue; + } else if ( + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } else { + continue; + } + + $this->_tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + } else if ($token->getValue() == "&") { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION); + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } + + $this->_tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND && $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if (!is_numeric($token->getValue())) { + if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE); + } + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER); + } + + $this->_tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) { + if (strlen($token->getValue() > 0)) { + if (substr($token->getValue(), 0, 1) == "@") { + $token->setValue(substr($token->getValue(), 1)); + } + } + } + + $this->_tokens[] = $token; + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php new file mode 100644 index 00000000..fd5e2e53 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php @@ -0,0 +1,176 @@ +_value = $pValue; + $this->_tokenType = $pTokenType; + $this->_tokenSubType = $pTokenSubType; + } + + /** + * Get Value + * + * @return string + */ + public function getValue() { + return $this->_value; + } + + /** + * Set Value + * + * @param string $value + */ + public function setValue($value) { + $this->_value = $value; + } + + /** + * Get Token Type (represented by TOKEN_TYPE_*) + * + * @return string + */ + public function getTokenType() { + return $this->_tokenType; + } + + /** + * Set Token Type + * + * @param string $value + */ + public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) { + $this->_tokenType = $value; + } + + /** + * Get Token SubType (represented by TOKEN_SUBTYPE_*) + * + * @return string + */ + public function getTokenSubType() { + return $this->_tokenSubType; + } + + /** + * Set Token SubType + * + * @param string $value + */ + public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) { + $this->_tokenSubType = $value; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php new file mode 100644 index 00000000..7299834e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php @@ -0,0 +1,149 @@ +_category = $pCategory; + $this->_excelName = $pExcelName; + $this->_phpExcelName = $pPHPExcelName; + } else { + throw new PHPExcel_Calculation_Exception("Invalid parameters passed."); + } + } + + /** + * Get Category (represented by CATEGORY_*) + * + * @return string + */ + public function getCategory() { + return $this->_category; + } + + /** + * Set Category (represented by CATEGORY_*) + * + * @param string $value + * @throws PHPExcel_Calculation_Exception + */ + public function setCategory($value = null) { + if (!is_null($value)) { + $this->_category = $value; + } else { + throw new PHPExcel_Calculation_Exception("Invalid parameter passed."); + } + } + + /** + * Get Excel name + * + * @return string + */ + public function getExcelName() { + return $this->_excelName; + } + + /** + * Set Excel name + * + * @param string $value + */ + public function setExcelName($value) { + $this->_excelName = $value; + } + + /** + * Get PHPExcel name + * + * @return string + */ + public function getPHPExcelName() { + return $this->_phpExcelName; + } + + /** + * Set PHPExcel name + * + * @param string $value + */ + public function setPHPExcelName($value) { + $this->_phpExcelName = $value; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php new file mode 100644 index 00000000..71bfa19b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php @@ -0,0 +1,726 @@ + '#NULL!', + 'divisionbyzero' => '#DIV/0!', + 'value' => '#VALUE!', + 'reference' => '#REF!', + 'name' => '#NAME?', + 'num' => '#NUM!', + 'na' => '#N/A', + 'gettingdata' => '#GETTING_DATA' + ); + + + /** + * Set the Compatibility Mode + * + * @access public + * @category Function Configuration + * @param string $compatibilityMode Compatibility Mode + * Permitted values are: + * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel' + * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + * @return boolean (Success or Failure) + */ + public static function setCompatibilityMode($compatibilityMode) { + if (($compatibilityMode == self::COMPATIBILITY_EXCEL) || + ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || + ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) { + self::$compatibilityMode = $compatibilityMode; + return True; + } + return False; + } // function setCompatibilityMode() + + + /** + * Return the current Compatibility Mode + * + * @access public + * @category Function Configuration + * @return string Compatibility Mode + * Possible Return values are: + * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel' + * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + */ + public static function getCompatibilityMode() { + return self::$compatibilityMode; + } // function getCompatibilityMode() + + + /** + * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) + * + * @access public + * @category Function Configuration + * @param string $returnDateType Return Date Format + * Permitted values are: + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P' + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O' + * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E' + * @return boolean Success or failure + */ + public static function setReturnDateType($returnDateType) { + if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) || + ($returnDateType == self::RETURNDATE_PHP_OBJECT) || + ($returnDateType == self::RETURNDATE_EXCEL)) { + self::$ReturnDateType = $returnDateType; + return True; + } + return False; + } // function setReturnDateType() + + + /** + * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) + * + * @access public + * @category Function Configuration + * @return string Return Date Format + * Possible Return values are: + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P' + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O' + * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E' + */ + public static function getReturnDateType() { + return self::$ReturnDateType; + } // function getReturnDateType() + + + /** + * DUMMY + * + * @access public + * @category Error Returns + * @return string #Not Yet Implemented + */ + public static function DUMMY() { + return '#Not Yet Implemented'; + } // function DUMMY() + + + /** + * DIV0 + * + * @access public + * @category Error Returns + * @return string #Not Yet Implemented + */ + public static function DIV0() { + return self::$_errorCodes['divisionbyzero']; + } // function DIV0() + + + /** + * NA + * + * Excel Function: + * =NA() + * + * Returns the error value #N/A + * #N/A is the error value that means "no value is available." + * + * @access public + * @category Logical Functions + * @return string #N/A! + */ + public static function NA() { + return self::$_errorCodes['na']; + } // function NA() + + + /** + * NaN + * + * Returns the error value #NUM! + * + * @access public + * @category Error Returns + * @return string #NUM! + */ + public static function NaN() { + return self::$_errorCodes['num']; + } // function NaN() + + + /** + * NAME + * + * Returns the error value #NAME? + * + * @access public + * @category Error Returns + * @return string #NAME? + */ + public static function NAME() { + return self::$_errorCodes['name']; + } // function NAME() + + + /** + * REF + * + * Returns the error value #REF! + * + * @access public + * @category Error Returns + * @return string #REF! + */ + public static function REF() { + return self::$_errorCodes['reference']; + } // function REF() + + + /** + * NULL + * + * Returns the error value #NULL! + * + * @access public + * @category Error Returns + * @return string #NULL! + */ + public static function NULL() { + return self::$_errorCodes['null']; + } // function NULL() + + + /** + * VALUE + * + * Returns the error value #VALUE! + * + * @access public + * @category Error Returns + * @return string #VALUE! + */ + public static function VALUE() { + return self::$_errorCodes['value']; + } // function VALUE() + + + public static function isMatrixValue($idx) { + return ((substr_count($idx,'.') <= 1) || (preg_match('/\.[A-Z]/',$idx) > 0)); + } + + + public static function isValue($idx) { + return (substr_count($idx,'.') == 0); + } + + + public static function isCellValue($idx) { + return (substr_count($idx,'.') > 1); + } + + + public static function _ifCondition($condition) { + $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition); + if (!isset($condition{0})) + $condition = '=""'; + if (!in_array($condition{0},array('>', '<', '='))) { + if (!is_numeric($condition)) { $condition = PHPExcel_Calculation::_wrapResult(strtoupper($condition)); } + return '='.$condition; + } else { + preg_match('/([<>=]+)(.*)/',$condition,$matches); + list(,$operator,$operand) = $matches; + + if (!is_numeric($operand)) { + $operand = str_replace('"', '""', $operand); + $operand = PHPExcel_Calculation::_wrapResult(strtoupper($operand)); + } + + return $operator.$operand; + } + } // function _ifCondition() + + + /** + * ERROR_TYPE + * + * @param mixed $value Value to check + * @return boolean + */ + public static function ERROR_TYPE($value = '') { + $value = self::flattenSingleValue($value); + + $i = 1; + foreach(self::$_errorCodes as $errorCode) { + if ($value === $errorCode) { + return $i; + } + ++$i; + } + return self::NA(); + } // function ERROR_TYPE() + + + /** + * IS_BLANK + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_BLANK($value = NULL) { + if (!is_null($value)) { + $value = self::flattenSingleValue($value); + } + + return is_null($value); + } // function IS_BLANK() + + + /** + * IS_ERR + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ERR($value = '') { + $value = self::flattenSingleValue($value); + + return self::IS_ERROR($value) && (!self::IS_NA($value)); + } // function IS_ERR() + + + /** + * IS_ERROR + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ERROR($value = '') { + $value = self::flattenSingleValue($value); + + if (!is_string($value)) + return false; + return in_array($value, array_values(self::$_errorCodes)); + } // function IS_ERROR() + + + /** + * IS_NA + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NA($value = '') { + $value = self::flattenSingleValue($value); + + return ($value === self::NA()); + } // function IS_NA() + + + /** + * IS_EVEN + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_EVEN($value = NULL) { + $value = self::flattenSingleValue($value); + + if ($value === NULL) + return self::NAME(); + if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) + return self::VALUE(); + return ($value % 2 == 0); + } // function IS_EVEN() + + + /** + * IS_ODD + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ODD($value = NULL) { + $value = self::flattenSingleValue($value); + + if ($value === NULL) + return self::NAME(); + if ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) + return self::VALUE(); + return (abs($value) % 2 == 1); + } // function IS_ODD() + + + /** + * IS_NUMBER + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NUMBER($value = NULL) { + $value = self::flattenSingleValue($value); + + if (is_string($value)) { + return False; + } + return is_numeric($value); + } // function IS_NUMBER() + + + /** + * IS_LOGICAL + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_LOGICAL($value = NULL) { + $value = self::flattenSingleValue($value); + + return is_bool($value); + } // function IS_LOGICAL() + + + /** + * IS_TEXT + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_TEXT($value = NULL) { + $value = self::flattenSingleValue($value); + + return (is_string($value) && !self::IS_ERROR($value)); + } // function IS_TEXT() + + + /** + * IS_NONTEXT + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NONTEXT($value = NULL) { + return !self::IS_TEXT($value); + } // function IS_NONTEXT() + + + /** + * VERSION + * + * @return string Version information + */ + public static function VERSION() { + return 'PHPExcel 1.8.0, 2014-03-02'; + } // function VERSION() + + + /** + * N + * + * Returns a value converted to a number + * + * @param value The value you want converted + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number That number + * A date The serial number of that date + * TRUE 1 + * FALSE 0 + * An error value The error value + * Anything else 0 + */ + public static function N($value = NULL) { + while (is_array($value)) { + $value = array_shift($value); + } + + switch (gettype($value)) { + case 'double' : + case 'float' : + case 'integer' : + return $value; + break; + case 'boolean' : + return (integer) $value; + break; + case 'string' : + // Errors + if ((strlen($value) > 0) && ($value{0} == '#')) { + return $value; + } + break; + } + return 0; + } // function N() + + + /** + * TYPE + * + * Returns a number that identifies the type of a value + * + * @param value The value you want tested + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number 1 + * Text 2 + * Logical Value 4 + * An error value 16 + * Array or Matrix 64 + */ + public static function TYPE($value = NULL) { + $value = self::flattenArrayIndexed($value); + if (is_array($value) && (count($value) > 1)) { + $a = array_keys($value); + $a = array_pop($a); + // Range of cells is an error + if (self::isCellValue($a)) { + return 16; + // Test for Matrix + } elseif (self::isMatrixValue($a)) { + return 64; + } + } elseif(empty($value)) { + // Empty Cell + return 1; + } + $value = self::flattenSingleValue($value); + + if (($value === NULL) || (is_float($value)) || (is_int($value))) { + return 1; + } elseif(is_bool($value)) { + return 4; + } elseif(is_array($value)) { + return 64; + break; + } elseif(is_string($value)) { + // Errors + if ((strlen($value) > 0) && ($value{0} == '#')) { + return 16; + } + return 2; + } + return 0; + } // function TYPE() + + + /** + * Convert a multi-dimensional array to a simple 1-dimensional array + * + * @param array $array Array to be flattened + * @return array Flattened array + */ + public static function flattenArray($array) { + if (!is_array($array)) { + return (array) $array; + } + + $arrayValues = array(); + foreach ($array as $value) { + if (is_array($value)) { + foreach ($value as $val) { + if (is_array($val)) { + foreach ($val as $v) { + $arrayValues[] = $v; + } + } else { + $arrayValues[] = $val; + } + } + } else { + $arrayValues[] = $value; + } + } + + return $arrayValues; + } // function flattenArray() + + + /** + * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing + * + * @param array $array Array to be flattened + * @return array Flattened array + */ + public static function flattenArrayIndexed($array) { + if (!is_array($array)) { + return (array) $array; + } + + $arrayValues = array(); + foreach ($array as $k1 => $value) { + if (is_array($value)) { + foreach ($value as $k2 => $val) { + if (is_array($val)) { + foreach ($val as $k3 => $v) { + $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v; + } + } else { + $arrayValues[$k1.'.'.$k2] = $val; + } + } + } else { + $arrayValues[$k1] = $value; + } + } + + return $arrayValues; + } // function flattenArrayIndexed() + + + /** + * Convert an array to a single scalar value by extracting the first element + * + * @param mixed $value Array or scalar value + * @return mixed + */ + public static function flattenSingleValue($value = '') { + while (is_array($value)) { + $value = array_pop($value); + } + + return $value; + } // function flattenSingleValue() + +} // class PHPExcel_Calculation_Functions + + +// +// There are a few mathematical functions that aren't available on all versions of PHP for all platforms +// These functions aren't available in Windows implementations of PHP prior to version 5.3.0 +// So we test if they do exist for this version of PHP/operating platform; and if not we create them +// +if (!function_exists('acosh')) { + function acosh($x) { + return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2)); + } // function acosh() +} + +if (!function_exists('asinh')) { + function asinh($x) { + return log($x + sqrt(1 + $x * $x)); + } // function asinh() +} + +if (!function_exists('atanh')) { + function atanh($x) { + return (log(1 + $x) - log(1 - $x)) / 2; + } // function atanh() +} + + +// +// Strangely, PHP doesn't have a mb_str_replace multibyte function +// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set +// +if ((!function_exists('mb_str_replace')) && + (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) { + function mb_str_replace($search, $replace, $subject) { + if(is_array($subject)) { + $ret = array(); + foreach($subject as $key => $val) { + $ret[$key] = mb_str_replace($search, $replace, $val); + } + return $ret; + } + + foreach((array) $search as $key => $s) { + if($s == '') { + continue; + } + $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : ''); + $pos = mb_strpos($subject, $s, 0, 'UTF-8'); + while($pos !== false) { + $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8'); + $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8'); + } + } + return $subject; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php new file mode 100644 index 00000000..bb206a14 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php @@ -0,0 +1,288 @@ + $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $returnValue = $returnValue && $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue = $returnValue && ($arg != 0); + } elseif (is_string($arg)) { + $arg = strtoupper($arg); + if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) { + $arg = TRUE; + } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) { + $arg = FALSE; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $returnValue = $returnValue && ($arg != 0); + } + } + + // Return + if ($argCount < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + return $returnValue; + } // function LOGICAL_AND() + + + /** + * LOGICAL_OR + * + * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. + * + * Excel Function: + * =OR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds + * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @access public + * @category Logical Functions + * @param mixed $arg,... Data values + * @return boolean The logical OR of the arguments. + */ + public static function LOGICAL_OR() { + // Return value + $returnValue = FALSE; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $argCount = -1; + foreach ($aArgs as $argCount => $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $returnValue = $returnValue || $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue = $returnValue || ($arg != 0); + } elseif (is_string($arg)) { + $arg = strtoupper($arg); + if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) { + $arg = TRUE; + } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) { + $arg = FALSE; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $returnValue = $returnValue || ($arg != 0); + } + } + + // Return + if ($argCount < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + return $returnValue; + } // function LOGICAL_OR() + + + /** + * NOT + * + * Returns the boolean inverse of the argument. + * + * Excel Function: + * =NOT(logical) + * + * The argument must evaluate to a logical value such as TRUE or FALSE + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds + * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @access public + * @category Logical Functions + * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE + * @return boolean The boolean inverse of the argument. + */ + public static function NOT($logical=FALSE) { + $logical = PHPExcel_Calculation_Functions::flattenSingleValue($logical); + if (is_string($logical)) { + $logical = strtoupper($logical); + if (($logical == 'TRUE') || ($logical == PHPExcel_Calculation::getTRUE())) { + return FALSE; + } elseif (($logical == 'FALSE') || ($logical == PHPExcel_Calculation::getFALSE())) { + return TRUE; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + return !$logical; + } // function NOT() + + /** + * STATEMENT_IF + * + * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE. + * + * Excel Function: + * =IF(condition[,returnIfTrue[,returnIfFalse]]) + * + * Condition is any value or expression that can be evaluated to TRUE or FALSE. + * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100, + * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. + * This argument can use any comparison calculation operator. + * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. + * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE, + * then the IF function returns the text "Within budget" + * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use + * the logical value TRUE for this argument. + * ReturnIfTrue can be another formula. + * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. + * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE, + * then the IF function returns the text "Over budget". + * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. + * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. + * ReturnIfFalse can be another formula. + * + * @access public + * @category Logical Functions + * @param mixed $condition Condition to evaluate + * @param mixed $returnIfTrue Value to return when condition is true + * @param mixed $returnIfFalse Optional value to return when condition is false + * @return mixed The value of returnIfTrue or returnIfFalse determined by condition + */ + public static function STATEMENT_IF($condition = TRUE, $returnIfTrue = 0, $returnIfFalse = FALSE) { + $condition = (is_null($condition)) ? TRUE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition); + $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue); + $returnIfFalse = (is_null($returnIfFalse)) ? FALSE : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse); + + return ($condition) ? $returnIfTrue : $returnIfFalse; + } // function STATEMENT_IF() + + + /** + * IFERROR + * + * Excel Function: + * =IFERROR(testValue,errorpart) + * + * @access public + * @category Logical Functions + * @param mixed $testValue Value to check, is also the value returned when no error + * @param mixed $errorpart Value to return when testValue is an error condition + * @return mixed The value of errorpart or testValue determined by error condition + */ + public static function IFERROR($testValue = '', $errorpart = '') { + $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue); + $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart); + + return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue); + } // function IFERROR() + +} // class PHPExcel_Calculation_Logical diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php new file mode 100644 index 00000000..e1285d90 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php @@ -0,0 +1,881 @@ + '') { + if (strpos($sheetText,' ') !== False) { $sheetText = "'".$sheetText."'"; } + $sheetText .='!'; + } + if ((!is_bool($referenceStyle)) || $referenceStyle) { + $rowRelative = $columnRelative = '$'; + $column = PHPExcel_Cell::stringFromColumnIndex($column-1); + if (($relativity == 2) || ($relativity == 4)) { $columnRelative = ''; } + if (($relativity == 3) || ($relativity == 4)) { $rowRelative = ''; } + return $sheetText.$columnRelative.$column.$rowRelative.$row; + } else { + if (($relativity == 2) || ($relativity == 4)) { $column = '['.$column.']'; } + if (($relativity == 3) || ($relativity == 4)) { $row = '['.$row.']'; } + return $sheetText.'R'.$row.'C'.$column; + } + } // function CELL_ADDRESS() + + + /** + * COLUMN + * + * Returns the column number of the given cell reference + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the + * reference of the cell in which the COLUMN function appears; otherwise this function returns 0. + * + * Excel Function: + * =COLUMN([cellAddress]) + * + * @param cellAddress A reference to a range of cells for which you want the column numbers + * @return integer or array of integer + */ + public static function COLUMN($cellAddress=Null) { + if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; } + + if (is_array($cellAddress)) { + foreach($cellAddress as $columnKey => $value) { + $columnKey = preg_replace('/[^a-z]/i','',$columnKey); + return (integer) PHPExcel_Cell::columnIndexFromString($columnKey); + } + } else { + if (strpos($cellAddress,'!') !== false) { + list($sheet,$cellAddress) = explode('!',$cellAddress); + } + if (strpos($cellAddress,':') !== false) { + list($startAddress,$endAddress) = explode(':',$cellAddress); + $startAddress = preg_replace('/[^a-z]/i','',$startAddress); + $endAddress = preg_replace('/[^a-z]/i','',$endAddress); + $returnValue = array(); + do { + $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress); + } while ($startAddress++ != $endAddress); + return $returnValue; + } else { + $cellAddress = preg_replace('/[^a-z]/i','',$cellAddress); + return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress); + } + } + } // function COLUMN() + + + /** + * COLUMNS + * + * Returns the number of columns in an array or reference. + * + * Excel Function: + * =COLUMNS(cellAddress) + * + * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns + * @return integer The number of columns in cellAddress + */ + public static function COLUMNS($cellAddress=Null) { + if (is_null($cellAddress) || $cellAddress === '') { + return 1; + } elseif (!is_array($cellAddress)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $x = array_keys($cellAddress); + $x = array_shift($x); + $isMatrix = (is_numeric($x)); + list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $rows; + } else { + return $columns; + } + } // function COLUMNS() + + + /** + * ROW + * + * Returns the row number of the given cell reference + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the + * reference of the cell in which the ROW function appears; otherwise this function returns 0. + * + * Excel Function: + * =ROW([cellAddress]) + * + * @param cellAddress A reference to a range of cells for which you want the row numbers + * @return integer or array of integer + */ + public static function ROW($cellAddress=Null) { + if (is_null($cellAddress) || trim($cellAddress) === '') { return 0; } + + if (is_array($cellAddress)) { + foreach($cellAddress as $columnKey => $rowValue) { + foreach($rowValue as $rowKey => $cellValue) { + return (integer) preg_replace('/[^0-9]/i','',$rowKey); + } + } + } else { + if (strpos($cellAddress,'!') !== false) { + list($sheet,$cellAddress) = explode('!',$cellAddress); + } + if (strpos($cellAddress,':') !== false) { + list($startAddress,$endAddress) = explode(':',$cellAddress); + $startAddress = preg_replace('/[^0-9]/','',$startAddress); + $endAddress = preg_replace('/[^0-9]/','',$endAddress); + $returnValue = array(); + do { + $returnValue[][] = (integer) $startAddress; + } while ($startAddress++ != $endAddress); + return $returnValue; + } else { + list($cellAddress) = explode(':',$cellAddress); + return (integer) preg_replace('/[^0-9]/','',$cellAddress); + } + } + } // function ROW() + + + /** + * ROWS + * + * Returns the number of rows in an array or reference. + * + * Excel Function: + * =ROWS(cellAddress) + * + * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows + * @return integer The number of rows in cellAddress + */ + public static function ROWS($cellAddress=Null) { + if (is_null($cellAddress) || $cellAddress === '') { + return 1; + } elseif (!is_array($cellAddress)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $i = array_keys($cellAddress); + $isMatrix = (is_numeric(array_shift($i))); + list($columns,$rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $columns; + } else { + return $rows; + } + } // function ROWS() + + + /** + * HYPERLINK + * + * Excel Function: + * =HYPERLINK(linkURL,displayName) + * + * @access public + * @category Logical Functions + * @param string $linkURL Value to check, is also the value returned when no error + * @param string $displayName Value to return when testValue is an error condition + * @param PHPExcel_Cell $pCell The cell to set the hyperlink in + * @return mixed The value of $displayName (or $linkURL if $displayName was blank) + */ + public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null) { + $args = func_get_args(); + $pCell = array_pop($args); + + $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL); + $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName); + + if ((!is_object($pCell)) || (trim($linkURL) == '')) { + return PHPExcel_Calculation_Functions::REF(); + } + + if ((is_object($displayName)) || trim($displayName) == '') { + $displayName = $linkURL; + } + + $pCell->getHyperlink()->setUrl($linkURL); + + return $displayName; + } // function HYPERLINK() + + + /** + * INDIRECT + * + * Returns the reference specified by a text string. + * References are immediately evaluated to display their contents. + * + * Excel Function: + * =INDIRECT(cellAddress) + * + * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 + * + * @param cellAddress $cellAddress The cell address of the current cell (containing this formula) + * @param PHPExcel_Cell $pCell The current cell (containing this formula) + * @return mixed The cells referenced by cellAddress + * + * @todo Support for the optional a1 parameter introduced in Excel 2010 + * + */ + public static function INDIRECT($cellAddress = NULL, PHPExcel_Cell $pCell = NULL) { + $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress); + if (is_null($cellAddress) || $cellAddress === '') { + return PHPExcel_Calculation_Functions::REF(); + } + + $cellAddress1 = $cellAddress; + $cellAddress2 = NULL; + if (strpos($cellAddress,':') !== false) { + list($cellAddress1,$cellAddress2) = explode(':',$cellAddress); + } + + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) || + ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) { + if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) { + return PHPExcel_Calculation_Functions::REF(); + } + + if (strpos($cellAddress,'!') !== FALSE) { + list($sheetName, $cellAddress) = explode('!',$cellAddress); + $sheetName = trim($sheetName, "'"); + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, FALSE); + } + + if (strpos($cellAddress,'!') !== FALSE) { + list($sheetName,$cellAddress) = explode('!',$cellAddress); + $sheetName = trim($sheetName, "'"); + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, FALSE); + } // function INDIRECT() + + + /** + * OFFSET + * + * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. + * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and + * the number of columns to be returned. + * + * Excel Function: + * =OFFSET(cellAddress, rows, cols, [height], [width]) + * + * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or + * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value. + * @param rows The number of rows, up or down, that you want the upper-left cell to refer to. + * Using 5 as the rows argument specifies that the upper-left cell in the reference is + * five rows below reference. Rows can be positive (which means below the starting reference) + * or negative (which means above the starting reference). + * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result + * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the + * reference is five columns to the right of reference. Cols can be positive (which means + * to the right of the starting reference) or negative (which means to the left of the + * starting reference). + * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number. + * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number. + * @return string A reference to a cell or range of cells + */ + public static function OFFSET($cellAddress=Null,$rows=0,$columns=0,$height=null,$width=null) { + $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows); + $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns); + $height = PHPExcel_Calculation_Functions::flattenSingleValue($height); + $width = PHPExcel_Calculation_Functions::flattenSingleValue($width); + if ($cellAddress == Null) { + return 0; + } + + $args = func_get_args(); + $pCell = array_pop($args); + if (!is_object($pCell)) { + return PHPExcel_Calculation_Functions::REF(); + } + + $sheetName = NULL; + if (strpos($cellAddress,"!")) { + list($sheetName,$cellAddress) = explode("!",$cellAddress); + $sheetName = trim($sheetName, "'"); + } + if (strpos($cellAddress,":")) { + list($startCell,$endCell) = explode(":",$cellAddress); + } else { + $startCell = $endCell = $cellAddress; + } + list($startCellColumn,$startCellRow) = PHPExcel_Cell::coordinateFromString($startCell); + list($endCellColumn,$endCellRow) = PHPExcel_Cell::coordinateFromString($endCell); + + $startCellRow += $rows; + $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1; + $startCellColumn += $columns; + + if (($startCellRow <= 0) || ($startCellColumn < 0)) { + return PHPExcel_Calculation_Functions::REF(); + } + $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1; + if (($width != null) && (!is_object($width))) { + $endCellColumn = $startCellColumn + $width - 1; + } else { + $endCellColumn += $columns; + } + $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn); + + if (($height != null) && (!is_object($height))) { + $endCellRow = $startCellRow + $height - 1; + } else { + $endCellRow += $rows; + } + + if (($endCellRow <= 0) || ($endCellColumn < 0)) { + return PHPExcel_Calculation_Functions::REF(); + } + $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn); + + $cellAddress = $startCellColumn.$startCellRow; + if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { + $cellAddress .= ':'.$endCellColumn.$endCellRow; + } + + if ($sheetName !== NULL) { + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, False); + } // function OFFSET() + + + /** + * CHOOSE + * + * Uses lookup_value to return a value from the list of value arguments. + * Use CHOOSE to select one of up to 254 values based on the lookup_value. + * + * Excel Function: + * =CHOOSE(index_num, value1, [value2], ...) + * + * @param index_num Specifies which value argument is selected. + * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number + * between 1 and 254. + * @param value1... Value1 is required, subsequent values are optional. + * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on + * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or + * text. + * @return mixed The selected value + */ + public static function CHOOSE() { + $chooseArgs = func_get_args(); + $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs)); + $entryCount = count($chooseArgs) - 1; + + if(is_array($chosenEntry)) { + $chosenEntry = array_shift($chosenEntry); + } + if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) { + --$chosenEntry; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $chosenEntry = floor($chosenEntry); + if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_array($chooseArgs[$chosenEntry])) { + return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]); + } else { + return $chooseArgs[$chosenEntry]; + } + } // function CHOOSE() + + + /** + * MATCH + * + * The MATCH function searches for a specified item in a range of cells + * + * Excel Function: + * =MATCH(lookup_value, lookup_array, [match_type]) + * + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered. + * @return integer The relative position of the found item + */ + public static function MATCH($lookup_value, $lookup_array, $match_type=1) { + $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array); + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type); + // MATCH is not case sensitive + $lookup_value = strtolower($lookup_value); + + // lookup_value type has to be number, text, or logical values + if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) { + return PHPExcel_Calculation_Functions::NA(); + } + + // match_type is 0, 1 or -1 + if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) { + return PHPExcel_Calculation_Functions::NA(); + } + + // lookup_array should not be empty + $lookupArraySize = count($lookup_array); + if ($lookupArraySize <= 0) { + return PHPExcel_Calculation_Functions::NA(); + } + + // lookup_array should contain only number, text, or logical values, or empty (null) cells + foreach($lookup_array as $i => $lookupArrayValue) { + // check the type of the value + if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) && + (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) { + return PHPExcel_Calculation_Functions::NA(); + } + // convert strings to lowercase for case-insensitive testing + if (is_string($lookupArrayValue)) { + $lookup_array[$i] = strtolower($lookupArrayValue); + } + if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) { + $lookup_array = array_slice($lookup_array,0,$i-1); + } + } + + // if match_type is 1 or -1, the list has to be ordered + if ($match_type == 1) { + asort($lookup_array); + $keySet = array_keys($lookup_array); + } elseif($match_type == -1) { + arsort($lookup_array); + $keySet = array_keys($lookup_array); + } + + // ** + // find the match + // ** + // loop on the cells +// var_dump($lookup_array); +// echo '
'; + foreach($lookup_array as $i => $lookupArrayValue) { + if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) { + // exact match + return ++$i; + } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) { +// echo '$i = '.$i.' => '; +// var_dump($lookupArrayValue); +// echo '
'; +// echo 'Keyset = '; +// var_dump($keySet); +// echo '
'; + $i = array_search($i,$keySet); +// echo '$i='.$i.'
'; + // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value + if ($i < 1){ + // 1st cell was allready smaller than the lookup_value + break; + } else { + // the previous cell was the match + return $keySet[$i-1]+1; + } + } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) { +// echo '$i = '.$i.' => '; +// var_dump($lookupArrayValue); +// echo '
'; +// echo 'Keyset = '; +// var_dump($keySet); +// echo '
'; + $i = array_search($i,$keySet); +// echo '$i='.$i.'
'; + // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value + if ($i < 1){ + // 1st cell was allready bigger than the lookup_value + break; + } else { + // the previous cell was the match + return $keySet[$i-1]+1; + } + } + } + + // unsuccessful in finding a match, return #N/A error value + return PHPExcel_Calculation_Functions::NA(); + } // function MATCH() + + + /** + * INDEX + * + * Uses an index to choose a value from a reference or array + * + * Excel Function: + * =INDEX(range_array, row_num, [column_num]) + * + * @param range_array A range of cells or an array constant + * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required. + * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required. + * @return mixed the value of a specified cell or array of cells + */ + public static function INDEX($arrayValues,$rowNum = 0,$columnNum = 0) { + + if (($rowNum < 0) || ($columnNum < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (!is_array($arrayValues)) { + return PHPExcel_Calculation_Functions::REF(); + } + + $rowKeys = array_keys($arrayValues); + $columnKeys = @array_keys($arrayValues[$rowKeys[0]]); + + if ($columnNum > count($columnKeys)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($columnNum == 0) { + if ($rowNum == 0) { + return $arrayValues; + } + $rowNum = $rowKeys[--$rowNum]; + $returnArray = array(); + foreach($arrayValues as $arrayColumn) { + if (is_array($arrayColumn)) { + if (isset($arrayColumn[$rowNum])) { + $returnArray[] = $arrayColumn[$rowNum]; + } else { + return $arrayValues[$rowNum]; + } + } else { + return $arrayValues[$rowNum]; + } + } + return $returnArray; + } + $columnNum = $columnKeys[--$columnNum]; + if ($rowNum > count($rowKeys)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($rowNum == 0) { + return $arrayValues[$columnNum]; + } + $rowNum = $rowKeys[--$rowNum]; + + return $arrayValues[$rowNum][$columnNum]; + } // function INDEX() + + + /** + * TRANSPOSE + * + * @param array $matrixData A matrix of values + * @return array + * + * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix. + */ + public static function TRANSPOSE($matrixData) { + $returnMatrix = array(); + if (!is_array($matrixData)) { $matrixData = array(array($matrixData)); } + + $column = 0; + foreach($matrixData as $matrixRow) { + $row = 0; + foreach($matrixRow as $matrixCell) { + $returnMatrix[$row][$column] = $matrixCell; + ++$row; + } + ++$column; + } + return $returnMatrix; + } // function TRANSPOSE() + + + private static function _vlookupSort($a,$b) { + $f = array_keys($a); + $firstColumn = array_shift($f); + if (strtolower($a[$firstColumn]) == strtolower($b[$firstColumn])) { + return 0; + } + return (strtolower($a[$firstColumn]) < strtolower($b[$firstColumn])) ? -1 : 1; + } // function _vlookupSort() + + + /** + * VLOOKUP + * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1. + * @param not_exact_match Determines if you are looking for an exact match based on lookup_value. + * @return mixed The value of the found cell + */ + public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number); + $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match); + + // index_number must be greater than or equal to 1 + if ($index_number < 1) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // index_number must be less than or equal to the number of columns in lookup_array + if ((!is_array($lookup_array)) || (empty($lookup_array))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $f = array_keys($lookup_array); + $firstRow = array_pop($f); + if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $columnKeys = array_keys($lookup_array[$firstRow]); + $returnColumn = $columnKeys[--$index_number]; + $firstColumn = array_shift($columnKeys); + } + } + + if (!$not_exact_match) { + uasort($lookup_array,array('self','_vlookupSort')); + } + + $rowNumber = $rowValue = False; + foreach($lookup_array as $rowKey => $rowData) { + if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) || + (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) { + break; + } + $rowNumber = $rowKey; + $rowValue = $rowData[$firstColumn]; + } + + if ($rowNumber !== false) { + if ((!$not_exact_match) && ($rowValue != $lookup_value)) { + // if an exact match is required, we have what we need to return an appropriate response + return PHPExcel_Calculation_Functions::NA(); + } else { + // otherwise return the appropriate value + $result = $lookup_array[$rowNumber][$returnColumn]; + if ((is_numeric($lookup_value) && is_numeric($result)) || + (!is_numeric($lookup_value) && !is_numeric($result))) { + return $result; + } + } + } + + return PHPExcel_Calculation_Functions::NA(); + } // function VLOOKUP() + + +/** + * HLOOKUP + * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1. + * @param not_exact_match Determines if you are looking for an exact match based on lookup_value. + * @return mixed The value of the found cell + */ + public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match=true) { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number); + $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match); + + // index_number must be greater than or equal to 1 + if ($index_number < 1) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // index_number must be less than or equal to the number of columns in lookup_array + if ((!is_array($lookup_array)) || (empty($lookup_array))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $f = array_keys($lookup_array); + $firstRow = array_pop($f); + if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $columnKeys = array_keys($lookup_array[$firstRow]); + $firstkey = $f[0] - 1; + $returnColumn = $firstkey + $index_number; + $firstColumn = array_shift($f); + } + } + + if (!$not_exact_match) { + $firstRowH = asort($lookup_array[$firstColumn]); + } + + $rowNumber = $rowValue = False; + foreach($lookup_array[$firstColumn] as $rowKey => $rowData) { + if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) || + (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) { + break; + } + $rowNumber = $rowKey; + $rowValue = $rowData; + } + + if ($rowNumber !== false) { + if ((!$not_exact_match) && ($rowValue != $lookup_value)) { + // if an exact match is required, we have what we need to return an appropriate response + return PHPExcel_Calculation_Functions::NA(); + } else { + // otherwise return the appropriate value + $result = $lookup_array[$returnColumn][$rowNumber]; + return $result; + } + } + + return PHPExcel_Calculation_Functions::NA(); + } // function HLOOKUP() + + + /** + * LOOKUP + * The LOOKUP function searches for value either from a one-row or one-column range or from an array. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_vector The range of cells being searched + * @param result_vector The column from which the matching value must be returned + * @return mixed The value of the found cell + */ + public static function LOOKUP($lookup_value, $lookup_vector, $result_vector=null) { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + + if (!is_array($lookup_vector)) { + return PHPExcel_Calculation_Functions::NA(); + } + $lookupRows = count($lookup_vector); + $l = array_keys($lookup_vector); + $l = array_shift($l); + $lookupColumns = count($lookup_vector[$l]); + if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) { + $lookup_vector = self::TRANSPOSE($lookup_vector); + $lookupRows = count($lookup_vector); + $l = array_keys($lookup_vector); + $lookupColumns = count($lookup_vector[array_shift($l)]); + } + + if (is_null($result_vector)) { + $result_vector = $lookup_vector; + } + $resultRows = count($result_vector); + $l = array_keys($result_vector); + $l = array_shift($l); + $resultColumns = count($result_vector[$l]); + if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) { + $result_vector = self::TRANSPOSE($result_vector); + $resultRows = count($result_vector); + $r = array_keys($result_vector); + $resultColumns = count($result_vector[array_shift($r)]); + } + + if ($lookupRows == 2) { + $result_vector = array_pop($lookup_vector); + $lookup_vector = array_shift($lookup_vector); + } + if ($lookupColumns != 2) { + foreach($lookup_vector as &$value) { + if (is_array($value)) { + $k = array_keys($value); + $key1 = $key2 = array_shift($k); + $key2++; + $dataValue1 = $value[$key1]; + } else { + $key1 = 0; + $key2 = 1; + $dataValue1 = $value; + } + $dataValue2 = array_shift($result_vector); + if (is_array($dataValue2)) { + $dataValue2 = array_shift($dataValue2); + } + $value = array($key1 => $dataValue1, $key2 => $dataValue2); + } + unset($value); + } + + return self::VLOOKUP($lookup_value,$lookup_vector,2); + } // function LOOKUP() + +} // class PHPExcel_Calculation_LookupRef diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php new file mode 100644 index 00000000..10930552 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php @@ -0,0 +1,1373 @@ + 1; --$i) { + if (($value % $i) == 0) { + $factorArray = array_merge($factorArray,self::_factors($value / $i)); + $factorArray = array_merge($factorArray,self::_factors($i)); + if ($i <= sqrt($value)) { + break; + } + } + } + if (!empty($factorArray)) { + rsort($factorArray); + return $factorArray; + } else { + return array((integer) $value); + } + } // function _factors() + + + private static function _romanCut($num, $n) { + return ($num - ($num % $n ) ) / $n; + } // function _romanCut() + + + /** + * ATAN2 + * + * This function calculates the arc tangent of the two variables x and y. It is similar to + * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used + * to determine the quadrant of the result. + * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a + * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between + * -pi and pi, excluding -pi. + * + * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard + * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. + * + * Excel Function: + * ATAN2(xCoordinate,yCoordinate) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $xCoordinate The x-coordinate of the point. + * @param float $yCoordinate The y-coordinate of the point. + * @return float The inverse tangent of the specified x- and y-coordinates. + */ + public static function ATAN2($xCoordinate = NULL, $yCoordinate = NULL) { + $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate); + $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate); + + $xCoordinate = ($xCoordinate !== NULL) ? $xCoordinate : 0.0; + $yCoordinate = ($yCoordinate !== NULL) ? $yCoordinate : 0.0; + + if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && + ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { + $xCoordinate = (float) $xCoordinate; + $yCoordinate = (float) $yCoordinate; + + if (($xCoordinate == 0) && ($yCoordinate == 0)) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + return atan2($yCoordinate, $xCoordinate); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ATAN2() + + + /** + * CEILING + * + * Returns number rounded up, away from zero, to the nearest multiple of significance. + * For example, if you want to avoid using pennies in your prices and your product is + * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the + * nearest nickel. + * + * Excel Function: + * CEILING(number[,significance]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number The number you want to round. + * @param float $significance The multiple to which you want to round. + * @return float Rounded Number + */ + public static function CEILING($number, $significance = NULL) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + if ((is_null($significance)) && + (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) { + $significance = $number/abs($number); + } + + if ((is_numeric($number)) && (is_numeric($significance))) { + if ($significance == 0.0) { + return 0.0; + } elseif (self::SIGN($number) == self::SIGN($significance)) { + return ceil($number / $significance) * $significance; + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function CEILING() + + + /** + * COMBIN + * + * Returns the number of combinations for a given number of items. Use COMBIN to + * determine the total possible number of groups for a given number of items. + * + * Excel Function: + * COMBIN(numObjs,numInSet) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param int $numObjs Number of different objects + * @param int $numInSet Number of objects in each combination + * @return int Number of combinations + */ + public static function COMBIN($numObjs, $numInSet) { + $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs); + $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet); + + if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { + if ($numObjs < $numInSet) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif ($numInSet < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function COMBIN() + + + /** + * EVEN + * + * Returns number rounded up to the nearest even integer. + * You can use this function for processing items that come in twos. For example, + * a packing crate accepts rows of one or two items. The crate is full when + * the number of items, rounded up to the nearest two, matches the crate's + * capacity. + * + * Excel Function: + * EVEN(number) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to round + * @return int Rounded Number + */ + public static function EVEN($number) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 0; + } elseif (is_bool($number)) { + $number = (int) $number; + } + + if (is_numeric($number)) { + $significance = 2 * self::SIGN($number); + return (int) self::CEILING($number,$significance); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function EVEN() + + + /** + * FACT + * + * Returns the factorial of a number. + * The factorial of a number is equal to 1*2*3*...* number. + * + * Excel Function: + * FACT(factVal) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $factVal Factorial Value + * @return int Factorial + */ + public static function FACT($factVal) { + $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal); + + if (is_numeric($factVal)) { + if ($factVal < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $factLoop = floor($factVal); + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + if ($factVal > $factLoop) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + } + return $factorial ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function FACT() + + + /** + * FACTDOUBLE + * + * Returns the double factorial of a number. + * + * Excel Function: + * FACTDOUBLE(factVal) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $factVal Factorial Value + * @return int Double Factorial + */ + public static function FACTDOUBLE($factVal) { + $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal); + + if (is_numeric($factLoop)) { + $factLoop = floor($factLoop); + if ($factVal < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + --$factLoop; + } + return $factorial ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function FACTDOUBLE() + + + /** + * FLOOR + * + * Rounds number down, toward zero, to the nearest multiple of significance. + * + * Excel Function: + * FLOOR(number[,significance]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to round + * @param float $significance Significance + * @return float Rounded Number + */ + public static function FLOOR($number, $significance = NULL) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + if ((is_null($significance)) && (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) { + $significance = $number/abs($number); + } + + if ((is_numeric($number)) && (is_numeric($significance))) { + if ((float) $significance == 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + if (self::SIGN($number) == self::SIGN($significance)) { + return floor($number / $significance) * $significance; + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function FLOOR() + + + /** + * GCD + * + * Returns the greatest common divisor of a series of numbers. + * The greatest common divisor is the largest integer that divides both + * number1 and number2 without a remainder. + * + * Excel Function: + * GCD(number1[,number2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return integer Greatest Common Divisor + */ + public static function GCD() { + $returnValue = 1; + $allValuesFactors = array(); + // Loop through arguments + foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) { + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($value == 0) { + continue; + } elseif($value < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $myFactors = self::_factors($value); + $myCountedFactors = array_count_values($myFactors); + $allValuesFactors[] = $myCountedFactors; + } + $allValuesCount = count($allValuesFactors); + if ($allValuesCount == 0) { + return 0; + } + + $mergedArray = $allValuesFactors[0]; + for ($i=1;$i < $allValuesCount; ++$i) { + $mergedArray = array_intersect_key($mergedArray,$allValuesFactors[$i]); + } + $mergedArrayValues = count($mergedArray); + if ($mergedArrayValues == 0) { + return $returnValue; + } elseif ($mergedArrayValues > 1) { + foreach($mergedArray as $mergedKey => $mergedValue) { + foreach($allValuesFactors as $highestPowerTest) { + foreach($highestPowerTest as $testKey => $testValue) { + if (($testKey == $mergedKey) && ($testValue < $mergedValue)) { + $mergedArray[$mergedKey] = $testValue; + $mergedValue = $testValue; + } + } + } + } + + $returnValue = 1; + foreach($mergedArray as $key => $value) { + $returnValue *= pow($key,$value); + } + return $returnValue; + } else { + $keys = array_keys($mergedArray); + $key = $keys[0]; + $value = $mergedArray[$key]; + foreach($allValuesFactors as $testValue) { + foreach($testValue as $mergedKey => $mergedValue) { + if (($mergedKey == $key) && ($mergedValue < $value)) { + $value = $mergedValue; + } + } + } + return pow($key,$value); + } + } // function GCD() + + + /** + * INT + * + * Casts a floating point value to an integer + * + * Excel Function: + * INT(number) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to cast to an integer + * @return integer Integer value + */ + public static function INT($number) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 0; + } elseif (is_bool($number)) { + return (int) $number; + } + if (is_numeric($number)) { + return (int) floor($number); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function INT() + + + /** + * LCM + * + * Returns the lowest common multiplier of a series of numbers + * The least common multiple is the smallest positive integer that is a multiple + * of all integer arguments number1, number2, and so on. Use LCM to add fractions + * with different denominators. + * + * Excel Function: + * LCM(number1[,number2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return int Lowest Common Multiplier + */ + public static function LCM() { + $returnValue = 1; + $allPoweredFactors = array(); + // Loop through arguments + foreach(PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) { + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if ($value == 0) { + return 0; + } elseif ($value < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $myFactors = self::_factors(floor($value)); + $myCountedFactors = array_count_values($myFactors); + $myPoweredFactors = array(); + foreach($myCountedFactors as $myCountedFactor => $myCountedPower) { + $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor,$myCountedPower); + } + foreach($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { + if (array_key_exists($myPoweredValue,$allPoweredFactors)) { + if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } else { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } + } + foreach($allPoweredFactors as $allPoweredFactor) { + $returnValue *= (integer) $allPoweredFactor; + } + return $returnValue; + } // function LCM() + + + /** + * LOG_BASE + * + * Returns the logarithm of a number to a specified base. The default base is 10. + * + * Excel Function: + * LOG(number[,base]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number The positive real number for which you want the logarithm + * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. + * @return float + */ + public static function LOG_BASE($number = NULL, $base = 10) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base); + + if ((!is_numeric($base)) || (!is_numeric($number))) + return PHPExcel_Calculation_Functions::VALUE(); + if (($base <= 0) || ($number <= 0)) + return PHPExcel_Calculation_Functions::NaN(); + return log($number, $base); + } // function LOG_BASE() + + + /** + * MDETERM + * + * Returns the matrix determinant of an array. + * + * Excel Function: + * MDETERM(array) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param array $matrixValues A matrix of values + * @return float + */ + public static function MDETERM($matrixValues) { + $matrixData = array(); + if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); } + + $row = $maxColumn = 0; + foreach($matrixValues as $matrixRow) { + if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); } + $column = 0; + foreach($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixData[$column][$row] = $matrixCell; + ++$column; + } + if ($column > $maxColumn) { $maxColumn = $column; } + ++$row; + } + if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); } + + try { + $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData); + return $matrix->det(); + } catch (PHPExcel_Exception $ex) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } // function MDETERM() + + + /** + * MINVERSE + * + * Returns the inverse matrix for the matrix stored in an array. + * + * Excel Function: + * MINVERSE(array) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param array $matrixValues A matrix of values + * @return array + */ + public static function MINVERSE($matrixValues) { + $matrixData = array(); + if (!is_array($matrixValues)) { $matrixValues = array(array($matrixValues)); } + + $row = $maxColumn = 0; + foreach($matrixValues as $matrixRow) { + if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); } + $column = 0; + foreach($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixData[$column][$row] = $matrixCell; + ++$column; + } + if ($column > $maxColumn) { $maxColumn = $column; } + ++$row; + } + if ($row != $maxColumn) { return PHPExcel_Calculation_Functions::VALUE(); } + + try { + $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData); + return $matrix->inverse()->getArray(); + } catch (PHPExcel_Exception $ex) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } // function MINVERSE() + + + /** + * MMULT + * + * @param array $matrixData1 A matrix of values + * @param array $matrixData2 A matrix of values + * @return array + */ + public static function MMULT($matrixData1,$matrixData2) { + $matrixAData = $matrixBData = array(); + if (!is_array($matrixData1)) { $matrixData1 = array(array($matrixData1)); } + if (!is_array($matrixData2)) { $matrixData2 = array(array($matrixData2)); } + + $rowA = 0; + foreach($matrixData1 as $matrixRow) { + if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); } + $columnA = 0; + foreach($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixAData[$rowA][$columnA] = $matrixCell; + ++$columnA; + } + ++$rowA; + } + try { + $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData); + $rowB = 0; + foreach($matrixData2 as $matrixRow) { + if (!is_array($matrixRow)) { $matrixRow = array($matrixRow); } + $columnB = 0; + foreach($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixBData[$rowB][$columnB] = $matrixCell; + ++$columnB; + } + ++$rowB; + } + $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData); + + if (($rowA != $columnB) || ($rowB != $columnA)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + return $matrixA->times($matrixB)->getArray(); + } catch (PHPExcel_Exception $ex) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } // function MMULT() + + + /** + * MOD + * + * @param int $a Dividend + * @param int $b Divisor + * @return int Remainder + */ + public static function MOD($a = 1, $b = 1) { + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + if ($b == 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } elseif (($a < 0.0) && ($b > 0.0)) { + return $b - fmod(abs($a),$b); + } elseif (($a > 0.0) && ($b < 0.0)) { + return $b + fmod($a,abs($b)); + } + + return fmod($a,$b); + } // function MOD() + + + /** + * MROUND + * + * Rounds a number to the nearest multiple of a specified value + * + * @param float $number Number to round + * @param int $multiple Multiple to which you want to round $number + * @return float Rounded Number + */ + public static function MROUND($number,$multiple) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple); + + if ((is_numeric($number)) && (is_numeric($multiple))) { + if ($multiple == 0) { + return 0; + } + if ((self::SIGN($number)) == (self::SIGN($multiple))) { + $multiplier = 1 / $multiple; + return round($number * $multiplier) / $multiplier; + } + return PHPExcel_Calculation_Functions::NaN(); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function MROUND() + + + /** + * MULTINOMIAL + * + * Returns the ratio of the factorial of a sum of values to the product of factorials. + * + * @param array of mixed Data Series + * @return float + */ + public static function MULTINOMIAL() { + $summer = 0; + $divisor = 1; + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if (is_numeric($arg)) { + if ($arg < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + $summer += floor($arg); + $divisor *= self::FACT($arg); + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + // Return + if ($summer > 0) { + $summer = self::FACT($summer); + return $summer / $divisor; + } + return 0; + } // function MULTINOMIAL() + + + /** + * ODD + * + * Returns number rounded up to the nearest odd integer. + * + * @param float $number Number to round + * @return int Rounded Number + */ + public static function ODD($number) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 1; + } elseif (is_bool($number)) { + $number = (int) $number; + } + + if (is_numeric($number)) { + $significance = self::SIGN($number); + if ($significance == 0) { + return 1; + } + + $result = self::CEILING($number,$significance); + if ($result == self::EVEN($result)) { + $result += $significance; + } + + return (int) $result; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ODD() + + + /** + * POWER + * + * Computes x raised to the power y. + * + * @param float $x + * @param float $y + * @return float + */ + public static function POWER($x = 0, $y = 2) { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $y = PHPExcel_Calculation_Functions::flattenSingleValue($y); + + // Validate parameters + if ($x == 0.0 && $y == 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif ($x == 0.0 && $y < 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + // Return + $result = pow($x, $y); + return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN(); + } // function POWER() + + + /** + * PRODUCT + * + * PRODUCT returns the product of all the values and cells referenced in the argument list. + * + * Excel Function: + * PRODUCT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function PRODUCT() { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue *= $arg; + } + } + } + + // Return + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } // function PRODUCT() + + + /** + * QUOTIENT + * + * QUOTIENT function returns the integer portion of a division. Numerator is the divided number + * and denominator is the divisor. + * + * Excel Function: + * QUOTIENT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function QUOTIENT() { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = ($arg == 0) ? 0 : $arg; + } else { + if (($returnValue == 0) || ($arg == 0)) { + $returnValue = 0; + } else { + $returnValue /= $arg; + } + } + } + } + + // Return + return intval($returnValue); + } // function QUOTIENT() + + + /** + * RAND + * + * @param int $min Minimal value + * @param int $max Maximal value + * @return int Random number + */ + public static function RAND($min = 0, $max = 0) { + $min = PHPExcel_Calculation_Functions::flattenSingleValue($min); + $max = PHPExcel_Calculation_Functions::flattenSingleValue($max); + + if ($min == 0 && $max == 0) { + return (rand(0,10000000)) / 10000000; + } else { + return rand($min, $max); + } + } // function RAND() + + + public static function ROMAN($aValue, $style=0) { + $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue); + $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style); + if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $aValue = (integer) $aValue; + if ($aValue == 0) { + return ''; + } + + $mill = Array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'); + $cent = Array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'); + $tens = Array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'); + $ones = Array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'); + + $roman = ''; + while ($aValue > 5999) { + $roman .= 'M'; + $aValue -= 1000; + } + $m = self::_romanCut($aValue, 1000); $aValue %= 1000; + $c = self::_romanCut($aValue, 100); $aValue %= 100; + $t = self::_romanCut($aValue, 10); $aValue %= 10; + + return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue]; + } // function ROMAN() + + + /** + * ROUNDUP + * + * Rounds a number up to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * @return float Rounded Number + */ + public static function ROUNDUP($number,$digits) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + if ((is_numeric($number)) && (is_numeric($digits))) { + $significance = pow(10,(int) $digits); + if ($number < 0.0) { + return floor($number * $significance) / $significance; + } else { + return ceil($number * $significance) / $significance; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ROUNDUP() + + + /** + * ROUNDDOWN + * + * Rounds a number down to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * @return float Rounded Number + */ + public static function ROUNDDOWN($number,$digits) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + if ((is_numeric($number)) && (is_numeric($digits))) { + $significance = pow(10,(int) $digits); + if ($number < 0.0) { + return ceil($number * $significance) / $significance; + } else { + return floor($number * $significance) / $significance; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function ROUNDDOWN() + + + /** + * SERIESSUM + * + * Returns the sum of a power series + * + * @param float $x Input value to the power series + * @param float $n Initial power to which you want to raise $x + * @param float $m Step by which to increase $n for each term in the series + * @param array of mixed Data Series + * @return float + */ + public static function SERIESSUM() { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $x = array_shift($aArgs); + $n = array_shift($aArgs); + $m = array_shift($aArgs); + + if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) { + // Calculate + $i = 0; + foreach($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += $arg * pow($x,$n + ($m * $i++)); + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Return + return $returnValue; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SERIESSUM() + + + /** + * SIGN + * + * Determines the sign of a number. Returns 1 if the number is positive, zero (0) + * if the number is 0, and -1 if the number is negative. + * + * @param float $number Number to round + * @return int sign value + */ + public static function SIGN($number) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_bool($number)) + return (int) $number; + if (is_numeric($number)) { + if ($number == 0.0) { + return 0; + } + return $number / abs($number); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SIGN() + + + /** + * SQRTPI + * + * Returns the square root of (number * pi). + * + * @param float $number Number + * @return float Square Root of Number * Pi + */ + public static function SQRTPI($number) { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_numeric($number)) { + if ($number < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return sqrt($number * M_PI) ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SQRTPI() + + + /** + * SUBTOTAL + * + * Returns a subtotal in a list or database. + * + * @param int the number 1 to 11 that specifies which function to + * use in calculating subtotals within a list. + * @param array of mixed Data Series + * @return float + */ + public static function SUBTOTAL() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $subtotal = array_shift($aArgs); + + if ((is_numeric($subtotal)) && (!is_string($subtotal))) { + switch($subtotal) { + case 1 : + return PHPExcel_Calculation_Statistical::AVERAGE($aArgs); + break; + case 2 : + return PHPExcel_Calculation_Statistical::COUNT($aArgs); + break; + case 3 : + return PHPExcel_Calculation_Statistical::COUNTA($aArgs); + break; + case 4 : + return PHPExcel_Calculation_Statistical::MAX($aArgs); + break; + case 5 : + return PHPExcel_Calculation_Statistical::MIN($aArgs); + break; + case 6 : + return self::PRODUCT($aArgs); + break; + case 7 : + return PHPExcel_Calculation_Statistical::STDEV($aArgs); + break; + case 8 : + return PHPExcel_Calculation_Statistical::STDEVP($aArgs); + break; + case 9 : + return self::SUM($aArgs); + break; + case 10 : + return PHPExcel_Calculation_Statistical::VARFunc($aArgs); + break; + case 11 : + return PHPExcel_Calculation_Statistical::VARP($aArgs); + break; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SUBTOTAL() + + + /** + * SUM + * + * SUM computes the sum of all the values and cells referenced in the argument list. + * + * Excel Function: + * SUM(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUM() { + // Return value + $returnValue = 0; + + // Loop through the arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += $arg; + } + } + + // Return + return $returnValue; + } // function SUM() + + + /** + * SUMIF + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * SUMIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be summed. + * @return float + */ + public static function SUMIF($aArgs,$condition,$sumArgs = array()) { + // Return value + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::_ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { + $arg = str_replace('"', '""', $arg); + $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); + } + + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + // Is it a value within our criteria + $returnValue += $sumArgs[$key]; + } + } + + // Return + return $returnValue; + } // function SUMIF() + + + /** + * SUMPRODUCT + * + * Excel Function: + * SUMPRODUCT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUMPRODUCT() { + $arrayList = func_get_args(); + + $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList)); + $wrkCellCount = count($wrkArray); + + for ($i=0; $i< $wrkCellCount; ++$i) { + if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { + $wrkArray[$i] = 0; + } + } + + foreach($arrayList as $matrixData) { + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData); + $count = count($array2); + if ($wrkCellCount != $count) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + foreach ($array2 as $i => $val) { + if ((!is_numeric($val)) || (is_string($val))) { + $val = 0; + } + $wrkArray[$i] *= $val; + } + } + + return array_sum($wrkArray); + } // function SUMPRODUCT() + + + /** + * SUMSQ + * + * SUMSQ returns the sum of the squares of the arguments + * + * Excel Function: + * SUMSQ(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUMSQ() { + // Return value + $returnValue = 0; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += ($arg * $arg); + } + } + + // Return + return $returnValue; + } // function SUMSQ() + + + /** + * SUMX2MY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMX2MY2($matrixData1,$matrixData2) { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count1 = count($array1); + $count2 = count($array2); + if ($count1 < $count2) { + $count = $count1; + } else { + $count = $count2; + } + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); + } + } + + return $result; + } // function SUMX2MY2() + + + /** + * SUMX2PY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMX2PY2($matrixData1,$matrixData2) { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count1 = count($array1); + $count2 = count($array2); + if ($count1 < $count2) { + $count = $count1; + } else { + $count = $count2; + } + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); + } + } + + return $result; + } // function SUMX2PY2() + + + /** + * SUMXMY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMXMY2($matrixData1,$matrixData2) { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count1 = count($array1); + $count2 = count($array2); + if ($count1 < $count2) { + $count = $count1; + } else { + $count = $count2; + } + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); + } + } + + return $result; + } // function SUMXMY2() + + + /** + * TRUNC + * + * Truncates value to the number of fractional digits by number_digits. + * + * @param float $value + * @param int $digits + * @return float Truncated value + */ + public static function TRUNC($value = 0, $digits = 0) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + // Validate parameters + if ((!is_numeric($value)) || (!is_numeric($digits))) + return PHPExcel_Calculation_Functions::VALUE(); + $digits = floor($digits); + + // Truncate + $adjust = pow(10, $digits); + + if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust),'0') < $adjust/10)) + return $value; + + return (intval($value * $adjust)) / $adjust; + } // function TRUNC() + +} // class PHPExcel_Calculation_MathTrig diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php new file mode 100644 index 00000000..32b9c781 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php @@ -0,0 +1,3651 @@ + $value) { + if ((is_bool($value)) || (is_string($value)) || (is_null($value))) { + unset($array1[$key]); + unset($array2[$key]); + } + } + foreach($array2 as $key => $value) { + if ((is_bool($value)) || (is_string($value)) || (is_null($value))) { + unset($array1[$key]); + unset($array2[$key]); + } + } + $array1 = array_merge($array1); + $array2 = array_merge($array2); + + return True; + } // function _checkTrendArrays() + + + /** + * Beta function. + * + * @author Jaco van Kooten + * + * @param p require p>0 + * @param q require q>0 + * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + */ + private static function _beta($p, $q) { + if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) { + return 0.0; + } else { + return exp(self::_logBeta($p, $q)); + } + } // function _beta() + + + /** + * Incomplete beta function + * + * @author Jaco van Kooten + * @author Paul Meagher + * + * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). + * @param x require 0<=x<=1 + * @param p require p>0 + * @param q require q>0 + * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow + */ + private static function _incompleteBeta($x, $p, $q) { + if ($x <= 0.0) { + return 0.0; + } elseif ($x >= 1.0) { + return 1.0; + } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) { + return 0.0; + } + $beta_gam = exp((0 - self::_logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); + if ($x < ($p + 1.0) / ($p + $q + 2.0)) { + return $beta_gam * self::_betaFraction($x, $p, $q) / $p; + } else { + return 1.0 - ($beta_gam * self::_betaFraction(1 - $x, $q, $p) / $q); + } + } // function _incompleteBeta() + + + // Function cache for _logBeta function + private static $_logBetaCache_p = 0.0; + private static $_logBetaCache_q = 0.0; + private static $_logBetaCache_result = 0.0; + + /** + * The natural logarithm of the beta function. + * + * @param p require p>0 + * @param q require q>0 + * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + * @author Jaco van Kooten + */ + private static function _logBeta($p, $q) { + if ($p != self::$_logBetaCache_p || $q != self::$_logBetaCache_q) { + self::$_logBetaCache_p = $p; + self::$_logBetaCache_q = $q; + if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) { + self::$_logBetaCache_result = 0.0; + } else { + self::$_logBetaCache_result = self::_logGamma($p) + self::_logGamma($q) - self::_logGamma($p + $q); + } + } + return self::$_logBetaCache_result; + } // function _logBeta() + + + /** + * Evaluates of continued fraction part of incomplete beta function. + * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). + * @author Jaco van Kooten + */ + private static function _betaFraction($x, $p, $q) { + $c = 1.0; + $sum_pq = $p + $q; + $p_plus = $p + 1.0; + $p_minus = $p - 1.0; + $h = 1.0 - $sum_pq * $x / $p_plus; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $frac = $h; + $m = 1; + $delta = 0.0; + while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION ) { + $m2 = 2 * $m; + // even index for d + $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < XMININ) { + $c = XMININ; + } + $frac *= $h * $c; + // odd index for d + $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < XMININ) { + $c = XMININ; + } + $delta = $h * $c; + $frac *= $delta; + ++$m; + } + return $frac; + } // function _betaFraction() + + + /** + * logGamma function + * + * @version 1.1 + * @author Jaco van Kooten + * + * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. + * + * The natural logarithm of the gamma function.
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz
+ * Applied Mathematics Division
+ * Argonne National Laboratory
+ * Argonne, IL 60439
+ *

+ * References: + *

    + *
  1. W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural + * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.
  2. + *
  3. K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.
  4. + *
  5. Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.
  6. + *
+ *

+ *

+ * From the original documentation: + *

+ *

+ * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + *

+ *

+ * Error returns:
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. + * The computation is believed to be free of underflow and overflow. + *

+ * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 + */ + + // Function cache for logGamma + private static $_logGammaCache_result = 0.0; + private static $_logGammaCache_x = 0.0; + + private static function _logGamma($x) { + // Log Gamma related constants + static $lg_d1 = -0.5772156649015328605195174; + static $lg_d2 = 0.4227843350984671393993777; + static $lg_d4 = 1.791759469228055000094023; + + static $lg_p1 = array( 4.945235359296727046734888, + 201.8112620856775083915565, + 2290.838373831346393026739, + 11319.67205903380828685045, + 28557.24635671635335736389, + 38484.96228443793359990269, + 26377.48787624195437963534, + 7225.813979700288197698961 ); + static $lg_p2 = array( 4.974607845568932035012064, + 542.4138599891070494101986, + 15506.93864978364947665077, + 184793.2904445632425417223, + 1088204.76946882876749847, + 3338152.967987029735917223, + 5106661.678927352456275255, + 3074109.054850539556250927 ); + static $lg_p4 = array( 14745.02166059939948905062, + 2426813.369486704502836312, + 121475557.4045093227939592, + 2663432449.630976949898078, + 29403789566.34553899906876, + 170266573776.5398868392998, + 492612579337.743088758812, + 560625185622.3951465078242 ); + + static $lg_q1 = array( 67.48212550303777196073036, + 1113.332393857199323513008, + 7738.757056935398733233834, + 27639.87074403340708898585, + 54993.10206226157329794414, + 61611.22180066002127833352, + 36351.27591501940507276287, + 8785.536302431013170870835 ); + static $lg_q2 = array( 183.0328399370592604055942, + 7765.049321445005871323047, + 133190.3827966074194402448, + 1136705.821321969608938755, + 5267964.117437946917577538, + 13467014.54311101692290052, + 17827365.30353274213975932, + 9533095.591844353613395747 ); + static $lg_q4 = array( 2690.530175870899333379843, + 639388.5654300092398984238, + 41355999.30241388052042842, + 1120872109.61614794137657, + 14886137286.78813811542398, + 101680358627.2438228077304, + 341747634550.7377132798597, + 446315818741.9713286462081 ); + + static $lg_c = array( -0.001910444077728, + 8.4171387781295e-4, + -5.952379913043012e-4, + 7.93650793500350248e-4, + -0.002777777777777681622553, + 0.08333333333333333331554247, + 0.0057083835261 ); + + // Rough estimate of the fourth root of logGamma_xBig + static $lg_frtbig = 2.25e76; + static $pnt68 = 0.6796875; + + + if ($x == self::$_logGammaCache_x) { + return self::$_logGammaCache_result; + } + $y = $x; + if ($y > 0.0 && $y <= LOG_GAMMA_X_MAX_VALUE) { + if ($y <= EPS) { + $res = -log(y); + } elseif ($y <= 1.5) { + // --------------------- + // EPS .LT. X .LE. 1.5 + // --------------------- + if ($y < $pnt68) { + $corr = -log($y); + $xm1 = $y; + } else { + $corr = 0.0; + $xm1 = $y - 1.0; + } + if ($y <= 0.5 || $y >= $pnt68) { + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm1 + $lg_p1[$i]; + $xden = $xden * $xm1 + $lg_q1[$i]; + } + $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden)); + } else { + $xm2 = $y - 1.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + $lg_p2[$i]; + $xden = $xden * $xm2 + $lg_q2[$i]; + } + $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); + } + } elseif ($y <= 4.0) { + // --------------------- + // 1.5 .LT. X .LE. 4.0 + // --------------------- + $xm2 = $y - 2.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + $lg_p2[$i]; + $xden = $xden * $xm2 + $lg_q2[$i]; + } + $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); + } elseif ($y <= 12.0) { + // ---------------------- + // 4.0 .LT. X .LE. 12.0 + // ---------------------- + $xm4 = $y - 4.0; + $xden = -1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm4 + $lg_p4[$i]; + $xden = $xden * $xm4 + $lg_q4[$i]; + } + $res = $lg_d4 + $xm4 * ($xnum / $xden); + } else { + // --------------------------------- + // Evaluate for argument .GE. 12.0 + // --------------------------------- + $res = 0.0; + if ($y <= $lg_frtbig) { + $res = $lg_c[6]; + $ysq = $y * $y; + for ($i = 0; $i < 6; ++$i) + $res = $res / $ysq + $lg_c[$i]; + } + $res /= $y; + $corr = log($y); + $res = $res + log(SQRT2PI) - 0.5 * $corr; + $res += $y * ($corr - 1.0); + } + } else { + // -------------------------- + // Return for bad arguments + // -------------------------- + $res = MAX_VALUE; + } + // ------------------------------ + // Final adjustments and return + // ------------------------------ + self::$_logGammaCache_x = $x; + self::$_logGammaCache_result = $res; + return $res; + } // function _logGamma() + + + // + // Private implementation of the incomplete Gamma function + // + private static function _incompleteGamma($a,$x) { + static $max = 32; + $summer = 0; + for ($n=0; $n<=$max; ++$n) { + $divisor = $a; + for ($i=1; $i<=$n; ++$i) { + $divisor *= ($a + $i); + } + $summer += (pow($x,$n) / $divisor); + } + return pow($x,$a) * exp(0-$x) * $summer; + } // function _incompleteGamma() + + + // + // Private implementation of the Gamma function + // + private static function _gamma($data) { + if ($data == 0.0) return 0; + + static $p0 = 1.000000000190015; + static $p = array ( 1 => 76.18009172947146, + 2 => -86.50532032941677, + 3 => 24.01409824083091, + 4 => -1.231739572450155, + 5 => 1.208650973866179e-3, + 6 => -5.395239384953e-6 + ); + + $y = $x = $data; + $tmp = $x + 5.5; + $tmp -= ($x + 0.5) * log($tmp); + + $summer = $p0; + for ($j=1;$j<=6;++$j) { + $summer += ($p[$j] / ++$y); + } + return exp(0 - $tmp + log(SQRT2PI * $summer / $x)); + } // function _gamma() + + + /*************************************************************************** + * inverse_ncdf.php + * ------------------- + * begin : Friday, January 16, 2004 + * copyright : (C) 2004 Michael Nickerson + * email : nickersonm@yahoo.com + * + ***************************************************************************/ + private static function _inverse_ncdf($p) { + // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to + // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as + // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html + // I have not checked the accuracy of this implementation. Be aware that PHP + // will truncate the coeficcients to 14 digits. + + // You have permission to use and distribute this function freely for + // whatever purpose you want, but please show common courtesy and give credit + // where credit is due. + + // Input paramater is $p - probability - where 0 < p < 1. + + // Coefficients in rational approximations + static $a = array( 1 => -3.969683028665376e+01, + 2 => 2.209460984245205e+02, + 3 => -2.759285104469687e+02, + 4 => 1.383577518672690e+02, + 5 => -3.066479806614716e+01, + 6 => 2.506628277459239e+00 + ); + + static $b = array( 1 => -5.447609879822406e+01, + 2 => 1.615858368580409e+02, + 3 => -1.556989798598866e+02, + 4 => 6.680131188771972e+01, + 5 => -1.328068155288572e+01 + ); + + static $c = array( 1 => -7.784894002430293e-03, + 2 => -3.223964580411365e-01, + 3 => -2.400758277161838e+00, + 4 => -2.549732539343734e+00, + 5 => 4.374664141464968e+00, + 6 => 2.938163982698783e+00 + ); + + static $d = array( 1 => 7.784695709041462e-03, + 2 => 3.224671290700398e-01, + 3 => 2.445134137142996e+00, + 4 => 3.754408661907416e+00 + ); + + // Define lower and upper region break-points. + $p_low = 0.02425; //Use lower region approx. below this + $p_high = 1 - $p_low; //Use upper region approx. above this + + if (0 < $p && $p < $p_low) { + // Rational approximation for lower region. + $q = sqrt(-2 * log($p)); + return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } elseif ($p_low <= $p && $p <= $p_high) { + // Rational approximation for central region. + $q = $p - 0.5; + $r = $q * $q; + return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / + ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); + } elseif ($p_high < $p && $p < 1) { + // Rational approximation for upper region. + $q = sqrt(-2 * log(1 - $p)); + return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } + // If 0 < p < 1, return a null value + return PHPExcel_Calculation_Functions::NULL(); + } // function _inverse_ncdf() + + + private static function _inverse_ncdf2($prob) { + // Approximation of inverse standard normal CDF developed by + // B. Moro, "The Full Monte," Risk 8(2), Feb 1995, 57-58. + + $a1 = 2.50662823884; + $a2 = -18.61500062529; + $a3 = 41.39119773534; + $a4 = -25.44106049637; + + $b1 = -8.4735109309; + $b2 = 23.08336743743; + $b3 = -21.06224101826; + $b4 = 3.13082909833; + + $c1 = 0.337475482272615; + $c2 = 0.976169019091719; + $c3 = 0.160797971491821; + $c4 = 2.76438810333863E-02; + $c5 = 3.8405729373609E-03; + $c6 = 3.951896511919E-04; + $c7 = 3.21767881768E-05; + $c8 = 2.888167364E-07; + $c9 = 3.960315187E-07; + + $y = $prob - 0.5; + if (abs($y) < 0.42) { + $z = ($y * $y); + $z = $y * ((($a4 * $z + $a3) * $z + $a2) * $z + $a1) / (((($b4 * $z + $b3) * $z + $b2) * $z + $b1) * $z + 1); + } else { + if ($y > 0) { + $z = log(-log(1 - $prob)); + } else { + $z = log(-log($prob)); + } + $z = $c1 + $z * ($c2 + $z * ($c3 + $z * ($c4 + $z * ($c5 + $z * ($c6 + $z * ($c7 + $z * ($c8 + $z * $c9))))))); + if ($y < 0) { + $z = -$z; + } + } + return $z; + } // function _inverse_ncdf2() + + + private static function _inverse_ncdf3($p) { + // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3. + // Produces the normal deviate Z corresponding to a given lower + // tail area of P; Z is accurate to about 1 part in 10**16. + // + // This is a PHP version of the original FORTRAN code that can + // be found at http://lib.stat.cmu.edu/apstat/ + $split1 = 0.425; + $split2 = 5; + $const1 = 0.180625; + $const2 = 1.6; + + // coefficients for p close to 0.5 + $a0 = 3.3871328727963666080; + $a1 = 1.3314166789178437745E+2; + $a2 = 1.9715909503065514427E+3; + $a3 = 1.3731693765509461125E+4; + $a4 = 4.5921953931549871457E+4; + $a5 = 6.7265770927008700853E+4; + $a6 = 3.3430575583588128105E+4; + $a7 = 2.5090809287301226727E+3; + + $b1 = 4.2313330701600911252E+1; + $b2 = 6.8718700749205790830E+2; + $b3 = 5.3941960214247511077E+3; + $b4 = 2.1213794301586595867E+4; + $b5 = 3.9307895800092710610E+4; + $b6 = 2.8729085735721942674E+4; + $b7 = 5.2264952788528545610E+3; + + // coefficients for p not close to 0, 0.5 or 1. + $c0 = 1.42343711074968357734; + $c1 = 4.63033784615654529590; + $c2 = 5.76949722146069140550; + $c3 = 3.64784832476320460504; + $c4 = 1.27045825245236838258; + $c5 = 2.41780725177450611770E-1; + $c6 = 2.27238449892691845833E-2; + $c7 = 7.74545014278341407640E-4; + + $d1 = 2.05319162663775882187; + $d2 = 1.67638483018380384940; + $d3 = 6.89767334985100004550E-1; + $d4 = 1.48103976427480074590E-1; + $d5 = 1.51986665636164571966E-2; + $d6 = 5.47593808499534494600E-4; + $d7 = 1.05075007164441684324E-9; + + // coefficients for p near 0 or 1. + $e0 = 6.65790464350110377720; + $e1 = 5.46378491116411436990; + $e2 = 1.78482653991729133580; + $e3 = 2.96560571828504891230E-1; + $e4 = 2.65321895265761230930E-2; + $e5 = 1.24266094738807843860E-3; + $e6 = 2.71155556874348757815E-5; + $e7 = 2.01033439929228813265E-7; + + $f1 = 5.99832206555887937690E-1; + $f2 = 1.36929880922735805310E-1; + $f3 = 1.48753612908506148525E-2; + $f4 = 7.86869131145613259100E-4; + $f5 = 1.84631831751005468180E-5; + $f6 = 1.42151175831644588870E-7; + $f7 = 2.04426310338993978564E-15; + + $q = $p - 0.5; + + // computation for p close to 0.5 + if (abs($q) <= split1) { + $R = $const1 - $q * $q; + $z = $q * ((((((($a7 * $R + $a6) * $R + $a5) * $R + $a4) * $R + $a3) * $R + $a2) * $R + $a1) * $R + $a0) / + ((((((($b7 * $R + $b6) * $R + $b5) * $R + $b4) * $R + $b3) * $R + $b2) * $R + $b1) * $R + 1); + } else { + if ($q < 0) { + $R = $p; + } else { + $R = 1 - $p; + } + $R = pow(-log($R),2); + + // computation for p not close to 0, 0.5 or 1. + If ($R <= $split2) { + $R = $R - $const2; + $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) / + ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1); + } else { + // computation for p near 0 or 1. + $R = $R - $split2; + $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) / + ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1); + } + if ($q < 0) { + $z = -$z; + } + } + return $z; + } // function _inverse_ncdf3() + + + /** + * AVEDEV + * + * Returns the average of the absolute deviations of data points from their mean. + * AVEDEV is a measure of the variability in a data set. + * + * Excel Function: + * AVEDEV(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVEDEV() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if ($aMean != PHPExcel_Calculation_Functions::DIV0()) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = abs($arg - $aMean); + } else { + $returnValue += abs($arg - $aMean); + } + ++$aCount; + } + } + + // Return + if ($aCount == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + return $returnValue / $aCount; + } + return PHPExcel_Calculation_Functions::NaN(); + } // function AVEDEV() + + + /** + * AVERAGE + * + * Returns the average (arithmetic mean) of the arguments + * + * Excel Function: + * AVERAGE(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVERAGE() { + $returnValue = $aCount = 0; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue += $arg; + } + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } else { + return PHPExcel_Calculation_Functions::DIV0(); + } + } // function AVERAGE() + + + /** + * AVERAGEA + * + * Returns the average of its arguments, including numbers, text, and logical values + * + * Excel Function: + * AVERAGEA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVERAGEA() { + // Return value + $returnValue = null; + + $aCount = 0; + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue += $arg; + } + ++$aCount; + } + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } else { + return PHPExcel_Calculation_Functions::DIV0(); + } + } // function AVERAGEA() + + + /** + * AVERAGEIF + * + * Returns the average value from a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * AVERAGEIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @param mixed[] $averageArgs Data values + * @return float + */ + public static function AVERAGEIF($aArgs,$condition,$averageArgs = array()) { + // Return value + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $averageArgs = PHPExcel_Calculation_Functions::flattenArray($averageArgs); + if (empty($averageArgs)) { + $averageArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::_ifCondition($condition); + // Loop through arguments + $aCount = 0; + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue += $arg; + ++$aCount; + } + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } else { + return PHPExcel_Calculation_Functions::DIV0(); + } + } // function AVERAGEIF() + + + /** + * BETADIST + * + * Returns the beta distribution. + * + * @param float $value Value at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @param boolean $cumulative + * @return float + * + */ + public static function BETADIST($value,$alpha,$beta,$rMin=0,$rMax=1) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin); + $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax); + + if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { + if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + $value -= $rMin; + $value /= ($rMax - $rMin); + return self::_incompleteBeta($value,$alpha,$beta); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BETADIST() + + + /** + * BETAINV + * + * Returns the inverse of the beta distribution. + * + * @param float $probability Probability at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @param float $rMin Minimum value + * @param float $rMax Maximum value + * @param boolean $cumulative + * @return float + * + */ + public static function BETAINV($probability,$alpha,$beta,$rMin=0,$rMax=1) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin); + $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax); + + if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { + if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + $a = 0; + $b = 2; + + $i = 0; + while ((($b - $a) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + $guess = ($a + $b) / 2; + $result = self::BETADIST($guess, $alpha, $beta); + if (($result == $probability) || ($result == 0)) { + $b = $a; + } elseif ($result > $probability) { + $b = $guess; + } else { + $a = $guess; + } + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($rMin + $guess * ($rMax - $rMin),12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BETAINV() + + + /** + * BINOMDIST + * + * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with + * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, + * when trials are independent, and when the probability of success is constant throughout the + * experiment. For example, BINOMDIST can calculate the probability that two of the next three + * babies born are male. + * + * @param float $value Number of successes in trials + * @param float $trials Number of trials + * @param float $probability Probability of success on each trial + * @param boolean $cumulative + * @return float + * + * @todo Cumulative distribution function + * + */ + public static function BINOMDIST($value, $trials, $probability, $cumulative) { + $value = floor(PHPExcel_Calculation_Functions::flattenSingleValue($value)); + $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + + if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) { + if (($value < 0) || ($value > $trials)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + $summer = 0; + for ($i = 0; $i <= $value; ++$i) { + $summer += PHPExcel_Calculation_MathTrig::COMBIN($trials,$i) * pow($probability,$i) * pow(1 - $probability,$trials - $i); + } + return $summer; + } else { + return PHPExcel_Calculation_MathTrig::COMBIN($trials,$value) * pow($probability,$value) * pow(1 - $probability,$trials - $value) ; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function BINOMDIST() + + + /** + * CHIDIST + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $value Value for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function CHIDIST($value, $degrees) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($value)) && (is_numeric($degrees))) { + if ($degrees < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($value < 0) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + return PHPExcel_Calculation_Functions::NaN(); + } + return 1 - (self::_incompleteGamma($degrees/2,$value/2) / self::_gamma($degrees/2)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function CHIDIST() + + + /** + * CHIINV + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $probability Probability for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function CHIINV($probability, $degrees) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($probability)) && (is_numeric($degrees))) { + + $xLo = 100; + $xHi = 0; + + $x = $xNew = 1; + $dx = 1; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::CHIDIST($x, $degrees); + $error = $result - $probability; + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($x,12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function CHIINV() + + + /** + * CONFIDENCE + * + * Returns the confidence interval for a population mean + * + * @param float $alpha + * @param float $stdDev Standard Deviation + * @param float $size + * @return float + * + */ + public static function CONFIDENCE($alpha,$stdDev,$size) { + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + $size = floor(PHPExcel_Calculation_Functions::flattenSingleValue($size)); + + if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) { + if (($alpha <= 0) || ($alpha >= 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($stdDev <= 0) || ($size < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function CONFIDENCE() + + + /** + * CORREL + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function CORREL($yValues,$xValues=null) { + if ((is_null($xValues)) || (!is_array($yValues)) || (!is_array($xValues))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getCorrelation(); + } // function CORREL() + + + /** + * COUNT + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * COUNT(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNT() { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + ++$returnValue; + } + } + + // Return + return $returnValue; + } // function COUNT() + + + /** + * COUNTA + * + * Counts the number of cells that are not empty within the list of arguments + * + * Excel Function: + * COUNTA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNTA() { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric, boolean or string value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + ++$returnValue; + } + } + + // Return + return $returnValue; + } // function COUNTA() + + + /** + * COUNTBLANK + * + * Counts the number of empty cells within the list of arguments + * + * Excel Function: + * COUNTBLANK(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNTBLANK() { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a blank cell? + if ((is_null($arg)) || ((is_string($arg)) && ($arg == ''))) { + ++$returnValue; + } + } + + // Return + return $returnValue; + } // function COUNTBLANK() + + + /** + * COUNTIF + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * COUNTIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be counted. + * @return int + */ + public static function COUNTIF($aArgs,$condition) { + // Return value + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $condition = PHPExcel_Calculation_Functions::_ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $arg) { + if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + // Is it a value within our criteria + ++$returnValue; + } + } + + // Return + return $returnValue; + } // function COUNTIF() + + + /** + * COVAR + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function COVAR($yValues,$xValues) { + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getCovariance(); + } // function COVAR() + + + /** + * CRITBINOM + * + * Returns the smallest value for which the cumulative binomial distribution is greater + * than or equal to a criterion value + * + * See http://support.microsoft.com/kb/828117/ for details of the algorithm used + * + * @param float $trials number of Bernoulli trials + * @param float $probability probability of a success on each trial + * @param float $alpha criterion value + * @return int + * + * @todo Warning. This implementation differs from the algorithm detailed on the MS + * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess + * This eliminates a potential endless loop error, but may have an adverse affect on the + * accuracy of the function (although all my tests have so far returned correct results). + * + */ + public static function CRITBINOM($trials, $probability, $alpha) { + $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + + if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) { + if ($trials < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($alpha < 0) || ($alpha > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($alpha <= 0.5) { + $t = sqrt(log(1 / ($alpha * $alpha))); + $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t)); + } else { + $t = sqrt(log(1 / pow(1 - $alpha,2))); + $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t); + } + $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability))); + if ($Guess < 0) { + $Guess = 0; + } elseif ($Guess > $trials) { + $Guess = $trials; + } + + $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0; + $EssentiallyZero = 10e-12; + + $m = floor($trials * $probability); + ++$TotalUnscaledProbability; + if ($m == $Guess) { ++$UnscaledPGuess; } + if ($m <= $Guess) { ++$UnscaledCumPGuess; } + + $PreviousValue = 1; + $Done = False; + $k = $m + 1; + while ((!$Done) && ($k <= $trials)) { + $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability)); + $TotalUnscaledProbability += $CurrentValue; + if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; } + if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; } + if ($CurrentValue <= $EssentiallyZero) { $Done = True; } + $PreviousValue = $CurrentValue; + ++$k; + } + + $PreviousValue = 1; + $Done = False; + $k = $m - 1; + while ((!$Done) && ($k >= 0)) { + $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability); + $TotalUnscaledProbability += $CurrentValue; + if ($k == $Guess) { $UnscaledPGuess += $CurrentValue; } + if ($k <= $Guess) { $UnscaledCumPGuess += $CurrentValue; } + if ($CurrentValue <= $EssentiallyZero) { $Done = True; } + $PreviousValue = $CurrentValue; + --$k; + } + + $PGuess = $UnscaledPGuess / $TotalUnscaledProbability; + $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability; + +// $CumPGuessMinus1 = $CumPGuess - $PGuess; + $CumPGuessMinus1 = $CumPGuess - 1; + + while (True) { + if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) { + return $Guess; + } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) { + $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability); + $CumPGuessMinus1 = $CumPGuess; + $CumPGuess = $CumPGuess + $PGuessPlus1; + $PGuess = $PGuessPlus1; + ++$Guess; + } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) { + $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability; + $CumPGuess = $CumPGuessMinus1; + $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess; + $PGuess = $PGuessMinus1; + --$Guess; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function CRITBINOM() + + + /** + * DEVSQ + * + * Returns the sum of squares of deviations of data points from their sample mean. + * + * Excel Function: + * DEVSQ(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function DEVSQ() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if ($aMean != PHPExcel_Calculation_Functions::DIV0()) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + // Is it a numeric value? + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean),2); + } else { + $returnValue += pow(($arg - $aMean),2); + } + ++$aCount; + } + } + + // Return + if (is_null($returnValue)) { + return PHPExcel_Calculation_Functions::NaN(); + } else { + return $returnValue; + } + } + return self::NA(); + } // function DEVSQ() + + + /** + * EXPONDIST + * + * Returns the exponential distribution. Use EXPONDIST to model the time between events, + * such as how long an automated bank teller takes to deliver cash. For example, you can + * use EXPONDIST to determine the probability that the process takes at most 1 minute. + * + * @param float $value Value of the function + * @param float $lambda The parameter value + * @param boolean $cumulative + * @return float + */ + public static function EXPONDIST($value, $lambda, $cumulative) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $lambda = PHPExcel_Calculation_Functions::flattenSingleValue($lambda); + $cumulative = PHPExcel_Calculation_Functions::flattenSingleValue($cumulative); + + if ((is_numeric($value)) && (is_numeric($lambda))) { + if (($value < 0) || ($lambda < 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 1 - exp(0-$value*$lambda); + } else { + return $lambda * exp(0-$value*$lambda); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function EXPONDIST() + + + /** + * FISHER + * + * Returns the Fisher transformation at x. This transformation produces a function that + * is normally distributed rather than skewed. Use this function to perform hypothesis + * testing on the correlation coefficient. + * + * @param float $value + * @return float + */ + public static function FISHER($value) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + if (($value <= -1) || ($value >= 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return 0.5 * log((1+$value)/(1-$value)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function FISHER() + + + /** + * FISHERINV + * + * Returns the inverse of the Fisher transformation. Use this transformation when + * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then + * FISHERINV(y) = x. + * + * @param float $value + * @return float + */ + public static function FISHERINV($value) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + return (exp(2 * $value) - 1) / (exp(2 * $value) + 1); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function FISHERINV() + + + /** + * FORECAST + * + * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value. + * + * @param float Value of X for which we want to find Y + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function FORECAST($xValue,$yValues,$xValues) { + $xValue = PHPExcel_Calculation_Functions::flattenSingleValue($xValue); + if (!is_numeric($xValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getValueOfYForX($xValue); + } // function FORECAST() + + + /** + * GAMMADIST + * + * Returns the gamma distribution. + * + * @param float $value Value at which you want to evaluate the distribution + * @param float $a Parameter to the distribution + * @param float $b Parameter to the distribution + * @param boolean $cumulative + * @return float + * + */ + public static function GAMMADIST($value,$a,$b,$cumulative) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) { + if (($value < 0) || ($a <= 0) || ($b <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return self::_incompleteGamma($a,$value / $b) / self::_gamma($a); + } else { + return (1 / (pow($b,$a) * self::_gamma($a))) * pow($value,$a-1) * exp(0-($value / $b)); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function GAMMADIST() + + + /** + * GAMMAINV + * + * Returns the inverse of the beta distribution. + * + * @param float $probability Probability at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @return float + * + */ + public static function GAMMAINV($probability,$alpha,$beta) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + + if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) { + if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $xLo = 0; + $xHi = $alpha * $beta * 5; + + $x = $xNew = 1; + $error = $pdf = 0; + $dx = 1024; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $error = self::GAMMADIST($x, $alpha, $beta, True) - $probability; + if ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + $pdf = self::GAMMADIST($x, $alpha, $beta, False); + // Avoid division by zero + if ($pdf != 0.0) { + $dx = $error / $pdf; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return $x; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function GAMMAINV() + + + /** + * GAMMALN + * + * Returns the natural logarithm of the gamma function. + * + * @param float $value + * @return float + */ + public static function GAMMALN($value) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + if ($value <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return log(self::_gamma($value)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function GAMMALN() + + + /** + * GEOMEAN + * + * Returns the geometric mean of an array or range of positive data. For example, you + * can use GEOMEAN to calculate average growth rate given compound interest with + * variable rates. + * + * Excel Function: + * GEOMEAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function GEOMEAN() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $aMean = PHPExcel_Calculation_MathTrig::PRODUCT($aArgs); + if (is_numeric($aMean) && ($aMean > 0)) { + $aCount = self::COUNT($aArgs) ; + if (self::MIN($aArgs) > 0) { + return pow($aMean, (1 / $aCount)); + } + } + return PHPExcel_Calculation_Functions::NaN(); + } // GEOMEAN() + + + /** + * GROWTH + * + * Returns values along a predicted emponential trend + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param array of mixed Values of X for which we want to find Y + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @return array of float + */ + public static function GROWTH($yValues,$xValues=array(),$newValues=array(),$const=True) { + $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues); + $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues); + $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues); + $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + + $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const); + if (empty($newValues)) { + $newValues = $bestFitExponential->getXValues(); + } + + $returnArray = array(); + foreach($newValues as $xValue) { + $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue); + } + + return $returnArray; + } // function GROWTH() + + + /** + * HARMEAN + * + * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the + * arithmetic mean of reciprocals. + * + * Excel Function: + * HARMEAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function HARMEAN() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::NA(); + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + if (self::MIN($aArgs) < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $aCount = 0; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ($arg <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (is_null($returnValue)) { + $returnValue = (1 / $arg); + } else { + $returnValue += (1 / $arg); + } + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return 1 / ($returnValue / $aCount); + } else { + return $returnValue; + } + } // function HARMEAN() + + + /** + * HYPGEOMDIST + * + * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of + * sample successes, given the sample size, population successes, and population size. + * + * @param float $sampleSuccesses Number of successes in the sample + * @param float $sampleNumber Size of the sample + * @param float $populationSuccesses Number of successes in the population + * @param float $populationNumber Population size + * @return float + * + */ + public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) { + $sampleSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleSuccesses)); + $sampleNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleNumber)); + $populationSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationSuccesses)); + $populationNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationNumber)); + + if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) { + if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return PHPExcel_Calculation_MathTrig::COMBIN($populationSuccesses,$sampleSuccesses) * + PHPExcel_Calculation_MathTrig::COMBIN($populationNumber - $populationSuccesses,$sampleNumber - $sampleSuccesses) / + PHPExcel_Calculation_MathTrig::COMBIN($populationNumber,$sampleNumber); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function HYPGEOMDIST() + + + /** + * INTERCEPT + * + * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function INTERCEPT($yValues,$xValues) { + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getIntersect(); + } // function INTERCEPT() + + + /** + * KURT + * + * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness + * or flatness of a distribution compared with the normal distribution. Positive + * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a + * relatively flat distribution. + * + * @param array Data Series + * @return float + */ + public static function KURT() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $mean = self::AVERAGE($aArgs); + $stdDev = self::STDEV($aArgs); + + if ($stdDev > 0) { + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += pow((($arg - $mean) / $stdDev),4) ; + ++$count; + } + } + } + + // Return + if ($count > 3) { + return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1,2) / (($count-2) * ($count-3))); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function KURT() + + + /** + * LARGE + * + * Returns the nth largest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * LARGE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Position (ordered from the largest) in the array or range of data to return + * @return float + * + */ + public static function LARGE() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = floor(array_pop($aArgs)); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $count = self::COUNT($mArgs); + $entry = floor(--$entry); + if (($entry < 0) || ($entry >= $count) || ($count == 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + rsort($mArgs); + return $mArgs[$entry]; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function LARGE() + + + /** + * LINEST + * + * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, + * and then returns an array that describes the line. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param boolean A logical value specifying whether to return additional regression statistics. + * @return array + */ + public static function LINEST($yValues, $xValues = NULL, $const = TRUE, $stats = FALSE) { + $const = (is_null($const)) ? TRUE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + $stats = (is_null($stats)) ? FALSE : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats); + if (is_null($xValues)) $xValues = range(1,count(PHPExcel_Calculation_Functions::flattenArray($yValues))); + + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return 0; + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const); + if ($stats) { + return array( array( $bestFitLinear->getSlope(), + $bestFitLinear->getSlopeSE(), + $bestFitLinear->getGoodnessOfFit(), + $bestFitLinear->getF(), + $bestFitLinear->getSSRegression(), + ), + array( $bestFitLinear->getIntersect(), + $bestFitLinear->getIntersectSE(), + $bestFitLinear->getStdevOfResiduals(), + $bestFitLinear->getDFResiduals(), + $bestFitLinear->getSSResiduals() + ) + ); + } else { + return array( $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect() + ); + } + } // function LINEST() + + + /** + * LOGEST + * + * Calculates an exponential curve that best fits the X and Y data series, + * and then returns an array that describes the line. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param boolean A logical value specifying whether to return additional regression statistics. + * @return array + */ + public static function LOGEST($yValues,$xValues=null,$const=True,$stats=False) { + $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + $stats = (is_null($stats)) ? False : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats); + if (is_null($xValues)) $xValues = range(1,count(PHPExcel_Calculation_Functions::flattenArray($yValues))); + + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + foreach($yValues as $value) { + if ($value <= 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return 1; + } + + $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL,$yValues,$xValues,$const); + if ($stats) { + return array( array( $bestFitExponential->getSlope(), + $bestFitExponential->getSlopeSE(), + $bestFitExponential->getGoodnessOfFit(), + $bestFitExponential->getF(), + $bestFitExponential->getSSRegression(), + ), + array( $bestFitExponential->getIntersect(), + $bestFitExponential->getIntersectSE(), + $bestFitExponential->getStdevOfResiduals(), + $bestFitExponential->getDFResiduals(), + $bestFitExponential->getSSResiduals() + ) + ); + } else { + return array( $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect() + ); + } + } // function LOGEST() + + + /** + * LOGINV + * + * Returns the inverse of the normal cumulative distribution + * + * @param float $probability + * @param float $mean + * @param float $stdDev + * @return float + * + * @todo Try implementing P J Acklam's refinement algorithm for greater + * accuracy if I can get my head round the mathematics + * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ + */ + public static function LOGINV($probability, $mean, $stdDev) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return exp($mean + $stdDev * self::NORMSINV($probability)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function LOGINV() + + + /** + * LOGNORMDIST + * + * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed + * with parameters mean and standard_dev. + * + * @param float $value + * @param float $mean + * @param float $stdDev + * @return float + */ + public static function LOGNORMDIST($value, $mean, $stdDev) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($value <= 0) || ($stdDev <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::NORMSDIST((log($value) - $mean) / $stdDev); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function LOGNORMDIST() + + + /** + * MAX + * + * MAX returns the value of the element of the values passed that has the highest value, + * with negative numbers considered smaller than positive numbers. + * + * Excel Function: + * MAX(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MAX() { + // Return value + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + if(is_null($returnValue)) { + return 0; + } + return $returnValue; + } // function MAX() + + + /** + * MAXA + * + * Returns the greatest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MAXA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MAXA() { + // Return value + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + if(is_null($returnValue)) { + return 0; + } + return $returnValue; + } // function MAXA() + + + /** + * MAXIF + * + * Counts the maximum value within a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * MAXIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @return float + */ + public static function MAXIF($aArgs,$condition,$sumArgs = array()) { + // Return value + $returnValue = null; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::_ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + return $returnValue; + } // function MAXIF() + + + /** + * MEDIAN + * + * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. + * + * Excel Function: + * MEDIAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MEDIAN() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::NaN(); + + $mArgs = array(); + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs,SORT_NUMERIC); + $mValueCount = $mValueCount / 2; + if ($mValueCount == floor($mValueCount)) { + $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2; + } else { + $mValueCount == floor($mValueCount); + $returnValue = $mArgs[$mValueCount]; + } + } + + // Return + return $returnValue; + } // function MEDIAN() + + + /** + * MIN + * + * MIN returns the value of the element of the values passed that has the smallest value, + * with negative numbers considered smaller than positive numbers. + * + * Excel Function: + * MIN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MIN() { + // Return value + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + if(is_null($returnValue)) { + return 0; + } + return $returnValue; + } // function MIN() + + + /** + * MINA + * + * Returns the smallest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MINA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MINA() { + // Return value + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + if(is_null($returnValue)) { + return 0; + } + return $returnValue; + } // function MINA() + + + /** + * MINIF + * + * Returns the minimum value within a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * MINIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @return float + */ + public static function MINIF($aArgs,$condition,$sumArgs = array()) { + // Return value + $returnValue = null; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::_ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { $arg = PHPExcel_Calculation::_wrapResult(strtoupper($arg)); } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + // Return + return $returnValue; + } // function MINIF() + + + // + // Special variant of array_count_values that isn't limited to strings and integers, + // but can work with floating point numbers as values + // + private static function _modeCalc($data) { + $frequencyArray = array(); + foreach($data as $datum) { + $found = False; + foreach($frequencyArray as $key => $value) { + if ((string) $value['value'] == (string) $datum) { + ++$frequencyArray[$key]['frequency']; + $found = True; + break; + } + } + if (!$found) { + $frequencyArray[] = array('value' => $datum, + 'frequency' => 1 ); + } + } + + foreach($frequencyArray as $key => $value) { + $frequencyList[$key] = $value['frequency']; + $valueList[$key] = $value['value']; + } + array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray); + + if ($frequencyArray[0]['frequency'] == 1) { + return PHPExcel_Calculation_Functions::NA(); + } + return $frequencyArray[0]['value']; + } // function _modeCalc() + + + /** + * MODE + * + * Returns the most frequently occurring, or repetitive, value in an array or range of data + * + * Excel Function: + * MODE(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MODE() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::NA(); + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + if (!empty($mArgs)) { + return self::_modeCalc($mArgs); + } + + // Return + return $returnValue; + } // function MODE() + + + /** + * NEGBINOMDIST + * + * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that + * there will be number_f failures before the number_s-th success, when the constant + * probability of a success is probability_s. This function is similar to the binomial + * distribution, except that the number of successes is fixed, and the number of trials is + * variable. Like the binomial, trials are assumed to be independent. + * + * @param float $failures Number of Failures + * @param float $successes Threshold number of Successes + * @param float $probability Probability of success on each trial + * @return float + * + */ + public static function NEGBINOMDIST($failures, $successes, $probability) { + $failures = floor(PHPExcel_Calculation_Functions::flattenSingleValue($failures)); + $successes = floor(PHPExcel_Calculation_Functions::flattenSingleValue($successes)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + + if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) { + if (($failures < 0) || ($successes < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + if (($failures + $successes - 1) <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + return (PHPExcel_Calculation_MathTrig::COMBIN($failures + $successes - 1,$successes - 1)) * (pow($probability,$successes)) * (pow(1 - $probability,$failures)) ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function NEGBINOMDIST() + + + /** + * NORMDIST + * + * Returns the normal distribution for the specified mean and standard deviation. This + * function has a very wide range of applications in statistics, including hypothesis + * testing. + * + * @param float $value + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @param boolean $cumulative + * @return float + * + */ + public static function NORMDIST($value, $mean, $stdDev, $cumulative) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if ($stdDev < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 0.5 * (1 + PHPExcel_Calculation_Engineering::_erfVal(($value - $mean) / ($stdDev * sqrt(2)))); + } else { + return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean,2) / (2 * ($stdDev * $stdDev)))); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function NORMDIST() + + + /** + * NORMINV + * + * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. + * + * @param float $value + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @return float + * + */ + public static function NORMINV($probability,$mean,$stdDev) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($stdDev < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (self::_inverse_ncdf($probability) * $stdDev) + $mean; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function NORMINV() + + + /** + * NORMSDIST + * + * Returns the standard normal cumulative distribution function. The distribution has + * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a + * table of standard normal curve areas. + * + * @param float $value + * @return float + */ + public static function NORMSDIST($value) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + return self::NORMDIST($value, 0, 1, True); + } // function NORMSDIST() + + + /** + * NORMSINV + * + * Returns the inverse of the standard normal cumulative distribution + * + * @param float $value + * @return float + */ + public static function NORMSINV($value) { + return self::NORMINV($value, 0, 1); + } // function NORMSINV() + + + /** + * PERCENTILE + * + * Returns the nth percentile of values in a range.. + * + * Excel Function: + * PERCENTILE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param float $entry Percentile value in the range 0..1, inclusive. + * @return float + */ + public static function PERCENTILE() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + if (($entry < 0) || ($entry > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs); + $count = self::COUNT($mArgs); + $index = $entry * ($count-1); + $iBase = floor($index); + if ($index == $iBase) { + return $mArgs[$index]; + } else { + $iNext = $iBase + 1; + $iProportion = $index - $iBase; + return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function PERCENTILE() + + + /** + * PERCENTRANK + * + * Returns the rank of a value in a data set as a percentage of the data set. + * + * @param array of number An array of, or a reference to, a list of numbers. + * @param number The number whose rank you want to find. + * @param number The number of significant digits for the returned percentage value. + * @return float + */ + public static function PERCENTRANK($valueSet,$value,$significance=3) { + $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet); + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $significance = (is_null($significance)) ? 3 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + foreach($valueSet as $key => $valueEntry) { + if (!is_numeric($valueEntry)) { + unset($valueSet[$key]); + } + } + sort($valueSet,SORT_NUMERIC); + $valueCount = count($valueSet); + if ($valueCount == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $valueAdjustor = $valueCount - 1; + if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { + return PHPExcel_Calculation_Functions::NA(); + } + + $pos = array_search($value,$valueSet); + if ($pos === False) { + $pos = 0; + $testValue = $valueSet[0]; + while ($testValue < $value) { + $testValue = $valueSet[++$pos]; + } + --$pos; + $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); + } + + return round($pos / $valueAdjustor,$significance); + } // function PERCENTRANK() + + + /** + * PERMUT + * + * Returns the number of permutations for a given number of objects that can be + * selected from number objects. A permutation is any set or subset of objects or + * events where internal order is significant. Permutations are different from + * combinations, for which the internal order is not significant. Use this function + * for lottery-style probability calculations. + * + * @param int $numObjs Number of different objects + * @param int $numInSet Number of objects in each permutation + * @return int Number of permutations + */ + public static function PERMUT($numObjs,$numInSet) { + $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs); + $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet); + + if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { + $numInSet = floor($numInSet); + if ($numObjs < $numInSet) { + return PHPExcel_Calculation_Functions::NaN(); + } + return round(PHPExcel_Calculation_MathTrig::FACT($numObjs) / PHPExcel_Calculation_MathTrig::FACT($numObjs - $numInSet)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function PERMUT() + + + /** + * POISSON + * + * Returns the Poisson distribution. A common application of the Poisson distribution + * is predicting the number of events over a specific time, such as the number of + * cars arriving at a toll plaza in 1 minute. + * + * @param float $value + * @param float $mean Mean Value + * @param boolean $cumulative + * @return float + * + */ + public static function POISSON($value, $mean, $cumulative) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + + if ((is_numeric($value)) && (is_numeric($mean))) { + if (($value <= 0) || ($mean <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + $summer = 0; + for ($i = 0; $i <= floor($value); ++$i) { + $summer += pow($mean,$i) / PHPExcel_Calculation_MathTrig::FACT($i); + } + return exp(0-$mean) * $summer; + } else { + return (exp(0-$mean) * pow($mean,$value)) / PHPExcel_Calculation_MathTrig::FACT($value); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function POISSON() + + + /** + * QUARTILE + * + * Returns the quartile of a data set. + * + * Excel Function: + * QUARTILE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Quartile value in the range 1..3, inclusive. + * @return float + */ + public static function QUARTILE() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = floor(array_pop($aArgs)); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $entry /= 4; + if (($entry < 0) || ($entry > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::PERCENTILE($aArgs,$entry); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function QUARTILE() + + + /** + * RANK + * + * Returns the rank of a number in a list of numbers. + * + * @param number The number whose rank you want to find. + * @param array of number An array of, or a reference to, a list of numbers. + * @param mixed Order to sort the values in the value set + * @return float + */ + public static function RANK($value,$valueSet,$order=0) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet); + $order = (is_null($order)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($order); + + foreach($valueSet as $key => $valueEntry) { + if (!is_numeric($valueEntry)) { + unset($valueSet[$key]); + } + } + + if ($order == 0) { + rsort($valueSet,SORT_NUMERIC); + } else { + sort($valueSet,SORT_NUMERIC); + } + $pos = array_search($value,$valueSet); + if ($pos === False) { + return PHPExcel_Calculation_Functions::NA(); + } + + return ++$pos; + } // function RANK() + + + /** + * RSQ + * + * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function RSQ($yValues,$xValues) { + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getGoodnessOfFit(); + } // function RSQ() + + + /** + * SKEW + * + * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry + * of a distribution around its mean. Positive skewness indicates a distribution with an + * asymmetric tail extending toward more positive values. Negative skewness indicates a + * distribution with an asymmetric tail extending toward more negative values. + * + * @param array Data Series + * @return float + */ + public static function SKEW() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $mean = self::AVERAGE($aArgs); + $stdDev = self::STDEV($aArgs); + + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += pow((($arg - $mean) / $stdDev),3) ; + ++$count; + } + } + } + + // Return + if ($count > 2) { + return $summer * ($count / (($count-1) * ($count-2))); + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function SKEW() + + + /** + * SLOPE + * + * Returns the slope of the linear regression line through data points in known_y's and known_x's. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function SLOPE($yValues,$xValues) { + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getSlope(); + } // function SLOPE() + + + /** + * SMALL + * + * Returns the nth smallest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * SMALL(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Position (ordered from the smallest) in the array or range of data to return + * @return float + */ + public static function SMALL() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $count = self::COUNT($mArgs); + $entry = floor(--$entry); + if (($entry < 0) || ($entry >= $count) || ($count == 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + sort($mArgs); + return $mArgs[$entry]; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SMALL() + + + /** + * STANDARDIZE + * + * Returns a normalized value from a distribution characterized by mean and standard_dev. + * + * @param float $value Value to normalize + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @return float Standardized value + */ + public static function STANDARDIZE($value,$mean,$stdDev) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if ($stdDev <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return ($value - $mean) / $stdDev ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function STANDARDIZE() + + + /** + * STDEV + * + * Estimates standard deviation based on a sample. The standard deviation is a measure of how + * widely values are dispersed from the average value (the mean). + * + * Excel Function: + * STDEV(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEV() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if (!is_null($aMean)) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean),2); + } else { + $returnValue += pow(($arg - $aMean),2); + } + ++$aCount; + } + } + + // Return + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function STDEV() + + + /** + * STDEVA + * + * Estimates standard deviation based on a sample, including numbers, text, and logical values + * + * Excel Function: + * STDEVA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVA() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGEA($aArgs); + if (!is_null($aMean)) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean),2); + } else { + $returnValue += pow(($arg - $aMean),2); + } + ++$aCount; + } + } + } + + // Return + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function STDEVA() + + + /** + * STDEVP + * + * Calculates standard deviation based on the entire population + * + * Excel Function: + * STDEVP(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVP() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if (!is_null($aMean)) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean),2); + } else { + $returnValue += pow(($arg - $aMean),2); + } + ++$aCount; + } + } + + // Return + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function STDEVP() + + + /** + * STDEVPA + * + * Calculates standard deviation based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * STDEVPA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVPA() { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGEA($aArgs); + if (!is_null($aMean)) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean),2); + } else { + $returnValue += pow(($arg - $aMean),2); + } + ++$aCount; + } + } + } + + // Return + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } // function STDEVPA() + + + /** + * STEYX + * + * Returns the standard error of the predicted y-value for each x in the regression. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function STEYX($yValues,$xValues) { + if (!self::_checkTrendArrays($yValues,$xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues); + return $bestFitLinear->getStdevOfResiduals(); + } // function STEYX() + + + /** + * TDIST + * + * Returns the probability of Student's T distribution. + * + * @param float $value Value for the function + * @param float $degrees degrees of freedom + * @param float $tails number of tails (1 or 2) + * @return float + */ + public static function TDIST($value, $degrees, $tails) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + $tails = floor(PHPExcel_Calculation_Functions::flattenSingleValue($tails)); + + if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) { + if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // tdist, which finds the probability that corresponds to a given value + // of t with k degrees of freedom. This algorithm is translated from a + // pascal function on p81 of "Statistical Computing in Pascal" by D + // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: + // London). The above Pascal algorithm is itself a translation of the + // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer + // Laboratory as reported in (among other places) "Applied Statistics + // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis + // Horwood Ltd.; W. Sussex, England). + $tterm = $degrees; + $ttheta = atan2($value,sqrt($tterm)); + $tc = cos($ttheta); + $ts = sin($ttheta); + $tsum = 0; + + if (($degrees % 2) == 1) { + $ti = 3; + $tterm = $tc; + } else { + $ti = 2; + $tterm = 1; + } + + $tsum = $tterm; + while ($ti < $degrees) { + $tterm *= $tc * $tc * ($ti - 1) / $ti; + $tsum += $tterm; + $ti += 2; + } + $tsum *= $ts; + if (($degrees % 2) == 1) { $tsum = M_2DIVPI * ($tsum + $ttheta); } + $tValue = 0.5 * (1 + $tsum); + if ($tails == 1) { + return 1 - abs($tValue); + } else { + return 1 - abs((1 - $tValue) - $tValue); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TDIST() + + + /** + * TINV + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $probability Probability for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function TINV($probability, $degrees) { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($probability)) && (is_numeric($degrees))) { + $xLo = 100; + $xHi = 0; + + $x = $xNew = 1; + $dx = 1; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::TDIST($x, $degrees, 2); + $error = $result - $probability; + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($x,12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TINV() + + + /** + * TREND + * + * Returns values along a linear trend + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param array of mixed Values of X for which we want to find Y + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @return array of float + */ + public static function TREND($yValues,$xValues=array(),$newValues=array(),$const=True) { + $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues); + $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues); + $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues); + $const = (is_null($const)) ? True : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR,$yValues,$xValues,$const); + if (empty($newValues)) { + $newValues = $bestFitLinear->getXValues(); + } + + $returnArray = array(); + foreach($newValues as $xValue) { + $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue); + } + + return $returnArray; + } // function TREND() + + + /** + * TRIMMEAN + * + * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean + * taken by excluding a percentage of data points from the top and bottom tails + * of a data set. + * + * Excel Function: + * TRIMEAN(value1[,value2[, ...]],$discard) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param float $discard Percentage to discard + * @return float + */ + public static function TRIMMEAN() { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $percent = array_pop($aArgs); + + if ((is_numeric($percent)) && (!is_string($percent))) { + if (($percent < 0) || ($percent > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $discard = floor(self::COUNT($mArgs) * $percent / 2); + sort($mArgs); + for ($i=0; $i < $discard; ++$i) { + array_pop($mArgs); + array_shift($mArgs); + } + return self::AVERAGE($mArgs); + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function TRIMMEAN() + + + /** + * VARFunc + * + * Estimates variance based on a sample. + * + * Excel Function: + * VAR(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARFunc() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $aCount = 0; + foreach ($aArgs as $arg) { + if (is_bool($arg)) { $arg = (integer) $arg; } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + // Return + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + return $returnValue; + } // function VARFunc() + + + /** + * VARA + * + * Estimates variance based on a sample, including numbers, text, and logical values + * + * Excel Function: + * VARA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARA() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && + (PHPExcel_Calculation_Functions::isValue($k))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ((is_string($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + // Return + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + return $returnValue; + } // function VARA() + + + /** + * VARP + * + * Calculates variance based on the entire population + * + * Excel Function: + * VARP(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARP() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $aCount = 0; + foreach ($aArgs as $arg) { + if (is_bool($arg)) { $arg = (integer) $arg; } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * $aCount); + } + return $returnValue; + } // function VARP() + + + /** + * VARPA + * + * Calculates variance based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * VARPA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARPA() { + // Return value + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && + (PHPExcel_Calculation_Functions::isValue($k))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ((is_string($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + // Return + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * $aCount); + } + return $returnValue; + } // function VARPA() + + + /** + * WEIBULL + * + * Returns the Weibull distribution. Use this distribution in reliability + * analysis, such as calculating a device's mean time to failure. + * + * @param float $value + * @param float $alpha Alpha Parameter + * @param float $beta Beta Parameter + * @param boolean $cumulative + * @return float + * + */ + public static function WEIBULL($value, $alpha, $beta, $cumulative) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + + if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) { + if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 1 - exp(0 - pow($value / $beta,$alpha)); + } else { + return ($alpha / pow($beta,$alpha)) * pow($value,$alpha - 1) * exp(0 - pow($value / $beta,$alpha)); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function WEIBULL() + + + /** + * ZTEST + * + * Returns the Weibull distribution. Use this distribution in reliability + * analysis, such as calculating a device's mean time to failure. + * + * @param float $dataSet + * @param float $m0 Alpha Parameter + * @param float $sigma Beta Parameter + * @param boolean $cumulative + * @return float + * + */ + public static function ZTEST($dataSet, $m0, $sigma = NULL) { + $dataSet = PHPExcel_Calculation_Functions::flattenArrayIndexed($dataSet); + $m0 = PHPExcel_Calculation_Functions::flattenSingleValue($m0); + $sigma = PHPExcel_Calculation_Functions::flattenSingleValue($sigma); + + if (is_null($sigma)) { + $sigma = self::STDEV($dataSet); + } + $n = count($dataSet); + + return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0)/($sigma/SQRT($n))); + } // function ZTEST() + +} // class PHPExcel_Calculation_Statistical diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php new file mode 100644 index 00000000..d1ba2728 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php @@ -0,0 +1,590 @@ +=0 && ord($c{0}) <= 127) + return ord($c{0}); + if (ord($c{0}) >= 192 && ord($c{0}) <= 223) + return (ord($c{0})-192)*64 + (ord($c{1})-128); + if (ord($c{0}) >= 224 && ord($c{0}) <= 239) + return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128); + if (ord($c{0}) >= 240 && ord($c{0}) <= 247) + return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128); + if (ord($c{0}) >= 248 && ord($c{0}) <= 251) + return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128); + if (ord($c{0}) >= 252 && ord($c{0}) <= 253) + return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128); + if (ord($c{0}) >= 254 && ord($c{0}) <= 255) //error + return PHPExcel_Calculation_Functions::VALUE(); + return 0; + } // function _uniord() + + /** + * CHARACTER + * + * @param string $character Value + * @return int + */ + public static function CHARACTER($character) { + $character = PHPExcel_Calculation_Functions::flattenSingleValue($character); + + if ((!is_numeric($character)) || ($character < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (function_exists('mb_convert_encoding')) { + return mb_convert_encoding('&#'.intval($character).';', 'UTF-8', 'HTML-ENTITIES'); + } else { + return chr(intval($character)); + } + } + + + /** + * TRIMNONPRINTABLE + * + * @param mixed $stringValue Value to check + * @return string + */ + public static function TRIMNONPRINTABLE($stringValue = '') { + $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue); + + if (is_bool($stringValue)) { + return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (self::$_invalidChars == Null) { + self::$_invalidChars = range(chr(0),chr(31)); + } + + if (is_string($stringValue) || is_numeric($stringValue)) { + return str_replace(self::$_invalidChars,'',trim($stringValue,"\x00..\x1F")); + } + return NULL; + } // function TRIMNONPRINTABLE() + + + /** + * TRIMSPACES + * + * @param mixed $stringValue Value to check + * @return string + */ + public static function TRIMSPACES($stringValue = '') { + $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue); + + if (is_bool($stringValue)) { + return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (is_string($stringValue) || is_numeric($stringValue)) { + return trim(preg_replace('/ +/',' ',trim($stringValue,' '))); + } + return NULL; + } // function TRIMSPACES() + + + /** + * ASCIICODE + * + * @param string $characters Value + * @return int + */ + public static function ASCIICODE($characters) { + if (($characters === NULL) || ($characters === '')) + return PHPExcel_Calculation_Functions::VALUE(); + $characters = PHPExcel_Calculation_Functions::flattenSingleValue($characters); + if (is_bool($characters)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $characters = (int) $characters; + } else { + $characters = ($characters) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + } + + $character = $characters; + if ((function_exists('mb_strlen')) && (function_exists('mb_substr'))) { + if (mb_strlen($characters, 'UTF-8') > 1) { $character = mb_substr($characters, 0, 1, 'UTF-8'); } + return self::_uniord($character); + } else { + if (strlen($characters) > 0) { $character = substr($characters, 0, 1); } + return ord($character); + } + } // function ASCIICODE() + + + /** + * CONCATENATE + * + * @return string + */ + public static function CONCATENATE() { + // Return value + $returnValue = ''; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + if (is_bool($arg)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $arg = (int) $arg; + } else { + $arg = ($arg) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + } + $returnValue .= $arg; + } + + // Return + return $returnValue; + } // function CONCATENATE() + + + /** + * DOLLAR + * + * This function converts a number to text using currency format, with the decimals rounded to the specified place. + * The format used is $#,##0.00_);($#,##0.00).. + * + * @param float $value The value to format + * @param int $decimals The number of digits to display to the right of the decimal point. + * If decimals is negative, number is rounded to the left of the decimal point. + * If you omit decimals, it is assumed to be 2 + * @return string + */ + public static function DOLLAR($value = 0, $decimals = 2) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $decimals = is_null($decimals) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($decimals); + + // Validate parameters + if (!is_numeric($value) || !is_numeric($decimals)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $decimals = floor($decimals); + + $mask = '$#,##0'; + if ($decimals > 0) { + $mask .= '.' . str_repeat('0',$decimals); + } else { + $round = pow(10,abs($decimals)); + if ($value < 0) { $round = 0-$round; } + $value = PHPExcel_Calculation_MathTrig::MROUND($value, $round); + } + + return PHPExcel_Style_NumberFormat::toFormattedString($value, $mask); + + } // function DOLLAR() + + + /** + * SEARCHSENSITIVE + * + * @param string $needle The string to look for + * @param string $haystack The string in which to look + * @param int $offset Offset within $haystack + * @return string + */ + public static function SEARCHSENSITIVE($needle,$haystack,$offset=1) { + $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle); + $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack); + $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset); + + if (!is_bool($needle)) { + if (is_bool($haystack)) { + $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) { + if (PHPExcel_Shared_String::CountCharacters($needle) == 0) { + return $offset; + } + if (function_exists('mb_strpos')) { + $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); + } else { + $pos = strpos($haystack, $needle, --$offset); + } + if ($pos !== false) { + return ++$pos; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SEARCHSENSITIVE() + + + /** + * SEARCHINSENSITIVE + * + * @param string $needle The string to look for + * @param string $haystack The string in which to look + * @param int $offset Offset within $haystack + * @return string + */ + public static function SEARCHINSENSITIVE($needle,$haystack,$offset=1) { + $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle); + $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack); + $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset); + + if (!is_bool($needle)) { + if (is_bool($haystack)) { + $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) { + if (PHPExcel_Shared_String::CountCharacters($needle) == 0) { + return $offset; + } + if (function_exists('mb_stripos')) { + $pos = mb_stripos($haystack, $needle, --$offset,'UTF-8'); + } else { + $pos = stripos($haystack, $needle, --$offset); + } + if ($pos !== false) { + return ++$pos; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } // function SEARCHINSENSITIVE() + + + /** + * FIXEDFORMAT + * + * @param mixed $value Value to check + * @param integer $decimals + * @param boolean $no_commas + * @return boolean + */ + public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = FALSE) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $decimals = PHPExcel_Calculation_Functions::flattenSingleValue($decimals); + $no_commas = PHPExcel_Calculation_Functions::flattenSingleValue($no_commas); + + // Validate parameters + if (!is_numeric($value) || !is_numeric($decimals)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $decimals = floor($decimals); + + $valueResult = round($value,$decimals); + if ($decimals < 0) { $decimals = 0; } + if (!$no_commas) { + $valueResult = number_format($valueResult,$decimals); + } + + return (string) $valueResult; + } // function FIXEDFORMAT() + + + /** + * LEFT + * + * @param string $value Value + * @param int $chars Number of characters + * @return string + */ + public static function LEFT($value = '', $chars = 1) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if ($chars < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_substr')) { + return mb_substr($value, 0, $chars, 'UTF-8'); + } else { + return substr($value, 0, $chars); + } + } // function LEFT() + + + /** + * MID + * + * @param string $value Value + * @param int $start Start character + * @param int $chars Number of characters + * @return string + */ + public static function MID($value = '', $start = 1, $chars = null) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $start = PHPExcel_Calculation_Functions::flattenSingleValue($start); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if (($start < 1) || ($chars < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_substr')) { + return mb_substr($value, --$start, $chars, 'UTF-8'); + } else { + return substr($value, --$start, $chars); + } + } // function MID() + + + /** + * RIGHT + * + * @param string $value Value + * @param int $chars Number of characters + * @return string + */ + public static function RIGHT($value = '', $chars = 1) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if ($chars < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if ((function_exists('mb_substr')) && (function_exists('mb_strlen'))) { + return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); + } else { + return substr($value, strlen($value) - $chars); + } + } // function RIGHT() + + + /** + * STRINGLENGTH + * + * @param string $value Value + * @return string + */ + public static function STRINGLENGTH($value = '') { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_strlen')) { + return mb_strlen($value, 'UTF-8'); + } else { + return strlen($value); + } + } // function STRINGLENGTH() + + + /** + * LOWERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function LOWERCASE($mixedCaseString) { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToLower($mixedCaseString); + } // function LOWERCASE() + + + /** + * UPPERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function UPPERCASE($mixedCaseString) { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToUpper($mixedCaseString); + } // function UPPERCASE() + + + /** + * PROPERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function PROPERCASE($mixedCaseString) { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToTitle($mixedCaseString); + } // function PROPERCASE() + + + /** + * REPLACE + * + * @param string $oldText String to modify + * @param int $start Start character + * @param int $chars Number of characters + * @param string $newText String to replace in defined position + * @return string + */ + public static function REPLACE($oldText = '', $start = 1, $chars = null, $newText) { + $oldText = PHPExcel_Calculation_Functions::flattenSingleValue($oldText); + $start = PHPExcel_Calculation_Functions::flattenSingleValue($start); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + $newText = PHPExcel_Calculation_Functions::flattenSingleValue($newText); + + $left = self::LEFT($oldText,$start-1); + $right = self::RIGHT($oldText,self::STRINGLENGTH($oldText)-($start+$chars)+1); + + return $left.$newText.$right; + } // function REPLACE() + + + /** + * SUBSTITUTE + * + * @param string $text Value + * @param string $fromText From Value + * @param string $toText To Value + * @param integer $instance Instance Number + * @return string + */ + public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) { + $text = PHPExcel_Calculation_Functions::flattenSingleValue($text); + $fromText = PHPExcel_Calculation_Functions::flattenSingleValue($fromText); + $toText = PHPExcel_Calculation_Functions::flattenSingleValue($toText); + $instance = floor(PHPExcel_Calculation_Functions::flattenSingleValue($instance)); + + if ($instance == 0) { + if(function_exists('mb_str_replace')) { + return mb_str_replace($fromText,$toText,$text); + } else { + return str_replace($fromText,$toText,$text); + } + } else { + $pos = -1; + while($instance > 0) { + if (function_exists('mb_strpos')) { + $pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8'); + } else { + $pos = strpos($text, $fromText, $pos+1); + } + if ($pos === false) { + break; + } + --$instance; + } + if ($pos !== false) { + if (function_exists('mb_strlen')) { + return self::REPLACE($text,++$pos,mb_strlen($fromText, 'UTF-8'),$toText); + } else { + return self::REPLACE($text,++$pos,strlen($fromText),$toText); + } + } + } + + return $text; + } // function SUBSTITUTE() + + + /** + * RETURNSTRING + * + * @param mixed $testValue Value to check + * @return boolean + */ + public static function RETURNSTRING($testValue = '') { + $testValue = PHPExcel_Calculation_Functions::flattenSingleValue($testValue); + + if (is_string($testValue)) { + return $testValue; + } + return Null; + } // function RETURNSTRING() + + + /** + * TEXTFORMAT + * + * @param mixed $value Value to check + * @param string $format Format mask to use + * @return boolean + */ + public static function TEXTFORMAT($value,$format) { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $format = PHPExcel_Calculation_Functions::flattenSingleValue($format); + + if ((is_string($value)) && (!is_numeric($value)) && PHPExcel_Shared_Date::isDateTimeFormatCode($format)) { + $value = PHPExcel_Calculation_DateTime::DATEVALUE($value); + } + + return (string) PHPExcel_Style_NumberFormat::toFormattedString($value,$format); + } // function TEXTFORMAT() + +} // class PHPExcel_Calculation_TextData diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php new file mode 100644 index 00000000..821f3bd2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php @@ -0,0 +1,115 @@ +_count; + } // function count() + + /** + * Push a new entry onto the stack + * + * @param mixed $type + * @param mixed $value + * @param mixed $reference + */ + public function push($type, $value, $reference = NULL) { + $this->_stack[$this->_count++] = array('type' => $type, + 'value' => $value, + 'reference' => $reference + ); + if ($type == 'Function') { + $localeFunction = PHPExcel_Calculation::_localeFunc($value); + if ($localeFunction != $value) { + $this->_stack[($this->_count - 1)]['localeValue'] = $localeFunction; + } + } + } // function push() + + /** + * Pop the last entry from the stack + * + * @return mixed + */ + public function pop() { + if ($this->_count > 0) { + return $this->_stack[--$this->_count]; + } + return NULL; + } // function pop() + + /** + * Return an entry from the stack without removing it + * + * @param integer $n number indicating how far back in the stack we want to look + * @return mixed + */ + public function last($n = 1) { + if ($this->_count - $n < 0) { + return NULL; + } + return $this->_stack[$this->_count - $n]; + } // function last() + + /** + * Clear the stack + */ + function clear() { + $this->_stack = array(); + $this->_count = 0; + } + +} // class PHPExcel_Calculation_Token_Stack diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt new file mode 100644 index 00000000..67dbd49c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt @@ -0,0 +1,351 @@ +ABS +ACCRINT +ACCRINTM +ACOS +ACOSH +ADDRESS +AMORDEGRC +AMORLINC +AND +AREAS +ASC +ASIN +ASINH +ATAN +ATAN2 +ATANH +AVEDEV +AVERAGE +AVERAGEA +AVERAGEIF +AVERAGEIFS +BAHTTEXT +BESSELI +BESSELJ +BESSELK +BESSELY +BETADIST +BETAINV +BIN2DEC +BIN2HEX +BIN2OCT +BINOMDIST +CEILING +CELL +CHAR +CHIDIST +CHIINV +CHITEST +CHOOSE +CLEAN +CODE +COLUMN +COLUMNS +COMBIN +COMPLEX +CONCATENATE +CONFIDENCE +CONVERT +CORREL +COS +COSH +COUNT +COUNTA +COUNTBLANK +COUNTIF +COUNTIFS +COUPDAYBS +COUPDAYBS +COUPDAYSNC +COUPNCD +COUPNUM +COUPPCD +COVAR +CRITBINOM +CUBEKPIMEMBER +CUBEMEMBER +CUBEMEMBERPROPERTY +CUBERANKEDMEMBER +CUBESET +CUBESETCOUNT +CUBEVALUE +CUMIPMT +CUMPRINC +DATE +DATEDIF +DATEVALUE +DAVERAGE +DAY +DAYS360 +DB +DCOUNT +DCOUNTA +DDB +DEC2BIN +DEC2HEX +DEC2OCT +DEGREES +DELTA +DEVSQ +DGET +DISC +DMAX +DMIN +DOLLAR +DOLLARDE +DOLLARFR +DPRODUCT +DSTDEV +DSTDEVP +DSUM +DURATION +DVAR +DVARP +EDATE +EFFECT +EOMONTH +ERF +ERFC +ERROR.TYPE +EVEN +EXACT +EXP +EXPONDIST +FACT +FACTDOUBLE +FALSE +FDIST +FIND +FINDB +FINV +FISHER +FISHERINV +FIXED +FLOOR +FORECAST +FREQUENCY +FTEST +FV +FVSCHEDULE +GAMAMDIST +GAMMAINV +GAMMALN +GCD +GEOMEAN +GESTEP +GETPIVOTDATA +GROWTH +HARMEAN +HEX2BIN +HEX2OCT +HLOOKUP +HOUR +HYPERLINK +HYPGEOMDIST +IF +IFERROR +IMABS +IMAGINARY +IMARGUMENT +IMCONJUGATE +IMCOS +IMEXP +IMLN +IMLOG10 +IMLOG2 +IMPOWER +IMPRODUCT +IMREAL +IMSIN +IMSQRT +IMSUB +IMSUM +INDEX +INDIRECT +INFO +INT +INTERCEPT +INTRATE +IPMT +IRR +ISBLANK +ISERR +ISERROR +ISEVEN +ISLOGICAL +ISNA +ISNONTEXT +ISNUMBER +ISODD +ISPMT +ISREF +ISTEXT +JIS +KURT +LARGE +LCM +LEFT +LEFTB +LEN +LENB +LINEST +LN +LOG +LOG10 +LOGEST +LOGINV +LOGNORMDIST +LOOKUP +LOWER +MATCH +MAX +MAXA +MDETERM +MDURATION +MEDIAN +MID +MIDB +MIN +MINA +MINUTE +MINVERSE +MIRR +MMULT +MOD +MODE +MONTH +MROUND +MULTINOMIAL +N +NA +NEGBINOMDIST +NETWORKDAYS +NOMINAL +NORMDIST +NORMINV +NORMSDIST +NORMSINV +NOT +NOW +NPER +NPV +OCT2BIN +OCT2DEC +OCT2HEX +ODD +ODDFPRICE +ODDFYIELD +ODDLPRICE +ODDLYIELD +OFFSET +OR +PEARSON +PERCENTILE +PERCENTRANK +PERMUT +PHONETIC +PI +PMT +POISSON +POWER +PPMT +PRICE +PRICEDISC +PRICEMAT +PROB +PRODUCT +PROPER +PV +QUARTILE +QUOTIENT +RADIANS +RAND +RANDBETWEEN +RANK +RATE +RECEIVED +REPLACE +REPLACEB +REPT +RIGHT +RIGHTB +ROMAN +ROUND +ROUNDDOWN +ROUNDUP +ROW +ROWS +RSQ +RTD +SEARCH +SEARCHB +SECOND +SERIESSUM +SIGN +SIN +SINH +SKEW +SLN +SLOPE +SMALL +SQRT +SQRTPI +STANDARDIZE +STDEV +STDEVA +STDEVP +STDEVPA +STEYX +SUBSTITUTE +SUBTOTAL +SUM +SUMIF +SUMIFS +SUMPRODUCT +SUMSQ +SUMX2MY2 +SUMX2PY2 +SUMXMY2 +SYD +T +TAN +TANH +TBILLEQ +TBILLPRICE +TBILLYIELD +TDIST +TEXT +TIME +TIMEVALUE +TINV +TODAY +TRANSPOSE +TREND +TRIM +TRIMMEAN +TRUE +TRUNC +TTEST +TYPE +UPPER +USDOLLAR +VALUE +VAR +VARA +VARP +VARPA +VDB +VERSION +VLOOKUP +WEEKDAY +WEEKNUM +WEIBULL +WORKDAY +XIRR +XNPV +YEAR +YEARFRAC +YIELD +YIELDDISC +YIELDMAT +ZTEST diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php new file mode 100644 index 00000000..1788559f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php @@ -0,0 +1,990 @@ +_parent->updateCacheData($this); + + return $this; + } + + public function detach() { + $this->_parent = NULL; + } + + public function attach(PHPExcel_CachedObjectStorage_CacheBase $parent) { + + + $this->_parent = $parent; + } + + + /** + * Create a new Cell + * + * @param mixed $pValue + * @param string $pDataType + * @param PHPExcel_Worksheet $pSheet + * @throws PHPExcel_Exception + */ + public function __construct($pValue = NULL, $pDataType = NULL, PHPExcel_Worksheet $pSheet = NULL) + { + // Initialise cell value + $this->_value = $pValue; + + // Set worksheet cache + $this->_parent = $pSheet->getCellCacheController(); + + // Set datatype? + if ($pDataType !== NULL) { + if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + $this->_dataType = $pDataType; + } else { + if (!self::getValueBinder()->bindValue($this, $pValue)) { + throw new PHPExcel_Exception("Value could not be bound to cell."); + } + } + + // set default index to cellXf + $this->_xfIndex = 0; + } + + /** + * Get cell coordinate column + * + * @return string + */ + public function getColumn() + { + return $this->_parent->getCurrentColumn(); + } + + /** + * Get cell coordinate row + * + * @return int + */ + public function getRow() + { + return $this->_parent->getCurrentRow(); + } + + /** + * Get cell coordinate + * + * @return string + */ + public function getCoordinate() + { + return $this->_parent->getCurrentAddress(); + } + + /** + * Get cell value + * + * @return mixed + */ + public function getValue() + { + return $this->_value; + } + + /** + * Get cell value with formatting + * + * @return string + */ + public function getFormattedValue() + { + return (string) PHPExcel_Style_NumberFormat::toFormattedString( + $this->getCalculatedValue(), + $this->getWorksheet()->getParent()->getCellXfByIndex($this->getXfIndex()) + ->getNumberFormat()->getFormatCode() + ); + } + + /** + * Set cell value + * + * Sets the value for a cell, automatically determining the datatype using the value binder + * + * @param mixed $pValue Value + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setValue($pValue = NULL) + { + if (!self::getValueBinder()->bindValue($this, $pValue)) { + throw new PHPExcel_Exception("Value could not be bound to cell."); + } + return $this; + } + + /** + * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder) + * + * @param mixed $pValue Value + * @param string $pDataType Explicit data type + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setValueExplicit($pValue = NULL, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING) + { + // set the value according to data type + switch ($pDataType) { + case PHPExcel_Cell_DataType::TYPE_NULL: + $this->_value = $pValue; + break; + case PHPExcel_Cell_DataType::TYPE_STRING2: + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + case PHPExcel_Cell_DataType::TYPE_STRING: + case PHPExcel_Cell_DataType::TYPE_INLINE: + $this->_value = PHPExcel_Cell_DataType::checkString($pValue); + break; + case PHPExcel_Cell_DataType::TYPE_NUMERIC: + $this->_value = (float)$pValue; + break; + case PHPExcel_Cell_DataType::TYPE_FORMULA: + $this->_value = (string)$pValue; + break; + case PHPExcel_Cell_DataType::TYPE_BOOL: + $this->_value = (bool)$pValue; + break; + case PHPExcel_Cell_DataType::TYPE_ERROR: + $this->_value = PHPExcel_Cell_DataType::checkErrorCode($pValue); + break; + default: + throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType); + break; + } + + // set the datatype + $this->_dataType = $pDataType; + + return $this->notifyCacheController(); + } + + /** + * Get calculated cell value + * + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + * + * @param boolean $resetLog Whether the calculation engine logger should be reset or not + * @return mixed + * @throws PHPExcel_Exception + */ + public function getCalculatedValue($resetLog = TRUE) + { +//echo 'Cell '.$this->getCoordinate().' value is a '.$this->_dataType.' with a value of '.$this->getValue().PHP_EOL; + if ($this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) { + try { +//echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL; + $result = PHPExcel_Calculation::getInstance( + $this->getWorksheet()->getParent() + )->calculateCellValue($this,$resetLog); +//echo $this->getCoordinate().' calculation result is '.$result.PHP_EOL; + // We don't yet handle array returns + if (is_array($result)) { + while (is_array($result)) { + $result = array_pop($result); + } + } + } catch ( PHPExcel_Exception $ex ) { + if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->_calculatedValue !== NULL)) { +//echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->_calculatedValue; // Fallback for calculations referencing external files. + } +//echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL; + $result = '#N/A'; + throw new PHPExcel_Calculation_Exception( + $this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage() + ); + } + + if ($result === '#Not Yet Implemented') { +//echo 'Returning fallback value of '.$this->_calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->_calculatedValue; // Fallback if calculation engine does not support the formula. + } +//echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL; + return $result; + } elseif($this->_value instanceof PHPExcel_RichText) { +// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->_value.'
'; + return $this->_value->getPlainText(); + } +// echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->_value.'
'; + return $this->_value; + } + + /** + * Set old calculated value (cached) + * + * @param mixed $pValue Value + * @return PHPExcel_Cell + */ + public function setCalculatedValue($pValue = NULL) + { + if ($pValue !== NULL) { + $this->_calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; + } + + return $this->notifyCacheController(); + } + + /** + * Get old calculated value (cached) + * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to + * create the original spreadsheet file. + * Note that this value is not guaranteed to refelect the actual calculated value because it is + * possible that auto-calculation was disabled in the original spreadsheet, and underlying data + * values used by the formula have changed since it was last calculated. + * + * @return mixed + */ + public function getOldCalculatedValue() + { + return $this->_calculatedValue; + } + + /** + * Get cell data type + * + * @return string + */ + public function getDataType() + { + return $this->_dataType; + } + + /** + * Set cell data type + * + * @param string $pDataType + * @return PHPExcel_Cell + */ + public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING) + { + if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + + $this->_dataType = $pDataType; + + return $this->notifyCacheController(); + } + + /** + * Identify if the cell contains a formula + * + * @return boolean + */ + public function isFormula() + { + return $this->_dataType == PHPExcel_Cell_DataType::TYPE_FORMULA; + } + + /** + * Does this cell contain Data validation rules? + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function hasDataValidation() + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet'); + } + + return $this->getWorksheet()->dataValidationExists($this->getCoordinate()); + } + + /** + * Get Data validation rules + * + * @return PHPExcel_Cell_DataValidation + * @throws PHPExcel_Exception + */ + public function getDataValidation() + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet'); + } + + return $this->getWorksheet()->getDataValidation($this->getCoordinate()); + } + + /** + * Set Data validation rules + * + * @param PHPExcel_Cell_DataValidation $pDataValidation + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = NULL) + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet'); + } + + $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation); + + return $this->notifyCacheController(); + } + + /** + * Does this cell contain a Hyperlink? + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function hasHyperlink() + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet'); + } + + return $this->getWorksheet()->hyperlinkExists($this->getCoordinate()); + } + + /** + * Get Hyperlink + * + * @return PHPExcel_Cell_Hyperlink + * @throws PHPExcel_Exception + */ + public function getHyperlink() + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet'); + } + + return $this->getWorksheet()->getHyperlink($this->getCoordinate()); + } + + /** + * Set Hyperlink + * + * @param PHPExcel_Cell_Hyperlink $pHyperlink + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = NULL) + { + if (!isset($this->_parent)) { + throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); + } + + $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink); + + return $this->notifyCacheController(); + } + + /** + * Get parent worksheet + * + * @return PHPExcel_CachedObjectStorage_CacheBase + */ + public function getParent() { + return $this->_parent; + } + + /** + * Get parent worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() { + return $this->_parent->getParent(); + } + + /** + * Get cell style + * + * @return PHPExcel_Style + */ + public function getStyle() + { + return $this->getWorksheet()->getParent()->getCellXfByIndex($this->getXfIndex()); + } + + /** + * Re-bind parent + * + * @param PHPExcel_Worksheet $parent + * @return PHPExcel_Cell + */ + public function rebindParent(PHPExcel_Worksheet $parent) { + $this->_parent = $parent->getCellCacheController(); + + return $this->notifyCacheController(); + } + + /** + * Is cell in a specific range? + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return boolean + */ + public function isInRange($pRange = 'A1:A1') + { + list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange); + + // Translate properties + $myColumn = self::columnIndexFromString($this->getColumn()); + $myRow = $this->getRow(); + + // Verify if cell is in range + return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && + ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow) + ); + } + + /** + * Coordinate from string + * + * @param string $pCoordinateString + * @return array Array containing column and row (indexes 0 and 1) + * @throws PHPExcel_Exception + */ + public static function coordinateFromString($pCoordinateString = 'A1') + { + if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) { + return array($matches[1],$matches[2]); + } elseif ((strpos($pCoordinateString,':') !== FALSE) || (strpos($pCoordinateString,',') !== FALSE)) { + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } elseif ($pCoordinateString == '') { + throw new PHPExcel_Exception('Cell coordinate can not be zero-length string'); + } + + throw new PHPExcel_Exception('Invalid cell coordinate '.$pCoordinateString); + } + + /** + * Make string row, column or cell coordinate absolute + * + * @param string $pCoordinateString e.g. 'A' or '1' or 'A1' + * Note that this value can be a row or column reference as well as a cell reference + * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' + * @throws PHPExcel_Exception + */ + public static function absoluteReference($pCoordinateString = 'A1') + { + if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) { + // Split out any worksheet name from the reference + $worksheet = ''; + $cellAddress = explode('!',$pCoordinateString); + if (count($cellAddress) > 1) { + list($worksheet,$pCoordinateString) = $cellAddress; + } + if ($worksheet > '') $worksheet .= '!'; + + // Create absolute coordinate + if (ctype_digit($pCoordinateString)) { + return $worksheet . '$' . $pCoordinateString; + } elseif (ctype_alpha($pCoordinateString)) { + return $worksheet . '$' . strtoupper($pCoordinateString); + } + return $worksheet . self::absoluteCoordinate($pCoordinateString); + } + + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } + + /** + * Make string coordinate absolute + * + * @param string $pCoordinateString e.g. 'A1' + * @return string Absolute coordinate e.g. '$A$1' + * @throws PHPExcel_Exception + */ + public static function absoluteCoordinate($pCoordinateString = 'A1') + { + if (strpos($pCoordinateString,':') === FALSE && strpos($pCoordinateString,',') === FALSE) { + // Split out any worksheet name from the coordinate + $worksheet = ''; + $cellAddress = explode('!',$pCoordinateString); + if (count($cellAddress) > 1) { + list($worksheet,$pCoordinateString) = $cellAddress; + } + if ($worksheet > '') $worksheet .= '!'; + + // Create absolute coordinate + list($column, $row) = self::coordinateFromString($pCoordinateString); + $column = ltrim($column,'$'); + $row = ltrim($row,'$'); + return $worksheet . '$' . $column . '$' . $row; + } + + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } + + /** + * Split range into coordinate strings + * + * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' + * @return array Array containg one or more arrays containing one or two coordinate strings + * e.g. array('B4','D9') or array(array('B4','D9'),array('H2','O11')) + * or array('B4') + */ + public static function splitRange($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if(empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + $exploded = explode(',', $pRange); + $counter = count($exploded); + for ($i = 0; $i < $counter; ++$i) { + $exploded[$i] = explode(':', $exploded[$i]); + } + return $exploded; + } + + /** + * Build range from coordinate strings + * + * @param array $pRange Array containg one or more arrays containing one or two coordinate strings + * @return string String representation of $pRange + * @throws PHPExcel_Exception + */ + public static function buildRange($pRange) + { + // Verify range + if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) { + throw new PHPExcel_Exception('Range does not contain any information'); + } + + // Build range + $imploded = array(); + $counter = count($pRange); + for ($i = 0; $i < $counter; ++$i) { + $pRange[$i] = implode(':', $pRange[$i]); + } + $imploded = implode(',', $pRange); + + return $imploded; + } + + /** + * Calculate range boundaries + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range coordinates array(Start Cell, End Cell) + * where Start Cell and End Cell are arrays (Column Number, Row Number) + */ + public static function rangeBoundaries($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if(empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Extract range + if (strpos($pRange, ':') === FALSE) { + $rangeA = $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + // Calculate range outer borders + $rangeStart = self::coordinateFromString($rangeA); + $rangeEnd = self::coordinateFromString($rangeB); + + // Translate column into index + $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); + $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); + + return array($rangeStart, $rangeEnd); + } + + /** + * Calculate range dimension + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range dimension (width, height) + */ + public static function rangeDimension($pRange = 'A1:A1') + { + // Calculate range outer borders + list($rangeStart,$rangeEnd) = self::rangeBoundaries($pRange); + + return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) ); + } + + /** + * Calculate range boundaries + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range coordinates array(Start Cell, End Cell) + * where Start Cell and End Cell are arrays (Column ID, Row Number) + */ + public static function getRangeBoundaries($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if(empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Extract range + if (strpos($pRange, ':') === FALSE) { + $rangeA = $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + return array( self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)); + } + + /** + * Column index from string + * + * @param string $pString + * @return int Column index (base 1 !!!) + */ + public static function columnIndexFromString($pString = 'A') + { + // Using a lookup cache adds a slight memory overhead, but boosts speed + // caching using a static within the method is faster than a class static, + // though it's additional memory overhead + static $_indexCache = array(); + + if (isset($_indexCache[$pString])) + return $_indexCache[$pString]; + + // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() + // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant + // memory overhead either + static $_columnLookup = array( + 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, + 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, + 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, + 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26 + ); + + // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString + // for improved performance + if (isset($pString{0})) { + if (!isset($pString{1})) { + $_indexCache[$pString] = $_columnLookup[$pString]; + return $_indexCache[$pString]; + } elseif(!isset($pString{2})) { + $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}]; + return $_indexCache[$pString]; + } elseif(!isset($pString{3})) { + $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}]; + return $_indexCache[$pString]; + } + } + throw new PHPExcel_Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty")); + } + + /** + * String from columnindex + * + * @param int $pColumnIndex Column index (base 0 !!!) + * @return string + */ + public static function stringFromColumnIndex($pColumnIndex = 0) + { + // Using a lookup cache adds a slight memory overhead, but boosts speed + // caching using a static within the method is faster than a class static, + // though it's additional memory overhead + static $_indexCache = array(); + + if (!isset($_indexCache[$pColumnIndex])) { + // Determine column string + if ($pColumnIndex < 26) { + $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex); + } elseif ($pColumnIndex < 702) { + $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . + chr(65 + $pColumnIndex % 26); + } else { + $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . + chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . + chr(65 + $pColumnIndex % 26); + } + } + return $_indexCache[$pColumnIndex]; + } + + /** + * Extract all cell references in range + * + * @param string $pRange Range (e.g. A1 or A1:C10 or A1:E10 A20:E25) + * @return array Array containing single cell references + */ + public static function extractAllCellReferencesInRange($pRange = 'A1') { + // Returnvalue + $returnValue = array(); + + // Explode spaces + $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange))); + foreach ($cellBlocks as $cellBlock) { + // Single cell? + if (strpos($cellBlock,':') === FALSE && strpos($cellBlock,',') === FALSE) { + $returnValue[] = $cellBlock; + continue; + } + + // Range... + $ranges = self::splitRange($cellBlock); + foreach($ranges as $range) { + // Single cell? + if (!isset($range[1])) { + $returnValue[] = $range[0]; + continue; + } + + // Range... + list($rangeStart, $rangeEnd) = $range; + sscanf($rangeStart,'%[A-Z]%d', $startCol, $startRow); + sscanf($rangeEnd,'%[A-Z]%d', $endCol, $endRow); + $endCol++; + + // Current data + $currentCol = $startCol; + $currentRow = $startRow; + + // Loop cells + while ($currentCol != $endCol) { + while ($currentRow <= $endRow) { + $returnValue[] = $currentCol.$currentRow; + ++$currentRow; + } + ++$currentCol; + $currentRow = $startRow; + } + } + } + + // Sort the result by column and row + $sortKeys = array(); + foreach (array_unique($returnValue) as $coord) { + sscanf($coord,'%[A-Z]%d', $column, $row); + $sortKeys[sprintf('%3s%09d',$column,$row)] = $coord; + } + ksort($sortKeys); + + // Return value + return array_values($sortKeys); + } + + /** + * Compare 2 cells + * + * @param PHPExcel_Cell $a Cell a + * @param PHPExcel_Cell $b Cell b + * @return int Result of comparison (always -1 or 1, never zero!) + */ + public static function compareCells(PHPExcel_Cell $a, PHPExcel_Cell $b) + { + if ($a->getRow() < $b->getRow()) { + return -1; + } elseif ($a->getRow() > $b->getRow()) { + return 1; + } elseif (self::columnIndexFromString($a->getColumn()) < self::columnIndexFromString($b->getColumn())) { + return -1; + } else { + return 1; + } + } + + /** + * Get value binder to use + * + * @return PHPExcel_Cell_IValueBinder + */ + public static function getValueBinder() { + if (self::$_valueBinder === NULL) { + self::$_valueBinder = new PHPExcel_Cell_DefaultValueBinder(); + } + + return self::$_valueBinder; + } + + /** + * Set value binder to use + * + * @param PHPExcel_Cell_IValueBinder $binder + * @throws PHPExcel_Exception + */ + public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = NULL) { + if ($binder === NULL) { + throw new PHPExcel_Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly."); + } + + self::$_valueBinder = $binder; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != '_parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + /** + * Get index to cellXf + * + * @return int + */ + public function getXfIndex() + { + return $this->_xfIndex; + } + + /** + * Set index to cellXf + * + * @param int $pValue + * @return PHPExcel_Cell + */ + public function setXfIndex($pValue = 0) + { + $this->_xfIndex = $pValue; + + return $this->notifyCacheController(); + } + + /** + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + */ + public function setFormulaAttributes($pAttributes) + { + $this->_formulaAttributes = $pAttributes; + return $this; + } + + /** + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + */ + public function getFormulaAttributes() + { + return $this->_formulaAttributes; + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() + { + return (string) $this->getValue(); + } + +} + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php new file mode 100644 index 00000000..00a2b57f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php @@ -0,0 +1,192 @@ +setValueExplicit( TRUE, PHPExcel_Cell_DataType::TYPE_BOOL); + return true; + } elseif($value == PHPExcel_Calculation::getFALSE()) { + $cell->setValueExplicit( FALSE, PHPExcel_Cell_DataType::TYPE_BOOL); + return true; + } + + // Check for number in scientific format + if (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NUMBER.'$/', $value)) { + $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + return true; + } + + // Check for fraction + if (preg_match('/^([+-]?)\s*([0-9]+)\s?\/\s*([0-9]+)$/', $value, $matches)) { + // Convert value to number + $value = $matches[2] / $matches[3]; + if ($matches[1] == '-') $value = 0 - $value; + $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( '??/??' ); + return true; + } elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) { + // Convert value to number + $value = $matches[2] + ($matches[3] / $matches[4]); + if ($matches[1] == '-') $value = 0 - $value; + $cell->setValueExplicit( (float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( '# ??/??' ); + return true; + } + + // Check for percentage + if (preg_match('/^\-?[0-9]*\.?[0-9]*\s?\%$/', $value)) { + // Convert value to number + $value = (float) str_replace('%', '', $value) / 100; + $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00 ); + return true; + } + + // Check for currency + $currencyCode = PHPExcel_Shared_String::getCurrencyCode(); + $decimalSeparator = PHPExcel_Shared_String::getDecimalSeparator(); + $thousandsSeparator = PHPExcel_Shared_String::getThousandsSeparator(); + if (preg_match('/^'.preg_quote($currencyCode).' *(\d{1,3}('.preg_quote($thousandsSeparator).'\d{3})*|(\d+))('.preg_quote($decimalSeparator).'\d{2})?$/', $value)) { + // Convert value to number + $value = (float) trim(str_replace(array($currencyCode, $thousandsSeparator, $decimalSeparator), array('', '', '.'), $value)); + $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( + str_replace('$', $currencyCode, PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE ) + ); + return true; + } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) { + // Convert value to number + $value = (float) trim(str_replace(array('$',','), '', $value)); + $cell->setValueExplicit( $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE ); + return true; + } + + // Check for time without seconds e.g. '9:45', '09:45' + if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { + // Convert value to number + list($h, $m) = explode(':', $value); + $days = $h / 24 + $m / 1440; + $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3 ); + return true; + } + + // Check for time with seconds '9:45:59', '09:45:59' + if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { + // Convert value to number + list($h, $m, $s) = explode(':', $value); + $days = $h / 24 + $m / 1440 + $s / 86400; + // Convert value to number + $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode( PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4 ); + return true; + } + + // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' + if (($d = PHPExcel_Shared_Date::stringToExcel($value)) !== false) { + // Convert value to number + $cell->setValueExplicit($d, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Determine style. Either there is a time part or not. Look for ':' + if (strpos($value, ':') !== false) { + $formatCode = 'yyyy-mm-dd h:mm'; + } else { + $formatCode = 'yyyy-mm-dd'; + } + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getNumberFormat()->setFormatCode($formatCode); + return true; + } + + // Check for newline character "\n" + if (strpos($value, "\n") !== FALSE) { + $value = PHPExcel_Shared_String::SanitizeUTF8($value); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); + // Set style + $cell->getWorksheet()->getStyle( $cell->getCoordinate() ) + ->getAlignment()->setWrapText(TRUE); + return true; + } + } + + // Not bound yet? Use parent... + return parent::bindValue($cell, $value); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php new file mode 100644 index 00000000..85765426 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php @@ -0,0 +1,122 @@ + 0, + '#DIV/0!' => 1, + '#VALUE!' => 2, + '#REF!' => 3, + '#NAME?' => 4, + '#NUM!' => 5, + '#N/A' => 6 + ); + + /** + * Get list of error codes + * + * @return array + */ + public static function getErrorCodes() { + return self::$_errorCodes; + } + + /** + * DataType for value + * + * @deprecated Replaced by PHPExcel_Cell_IValueBinder infrastructure, will be removed in version 1.8.0 + * @param mixed $pValue + * @return string + */ + public static function dataTypeForValue($pValue = null) { + return PHPExcel_Cell_DefaultValueBinder::dataTypeForValue($pValue); + } + + /** + * Check a string that it satisfies Excel requirements + * + * @param mixed Value to sanitize to an Excel string + * @return mixed Sanitized value + */ + public static function checkString($pValue = null) + { + if ($pValue instanceof PHPExcel_RichText) { + // TODO: Sanitize Rich-Text string (max. character count is 32,767) + return $pValue; + } + + // string must never be longer than 32,767 characters, truncate if necessary + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 32767); + + // we require that newline is represented as "\n" in core, not as "\r\n" or "\r" + $pValue = str_replace(array("\r\n", "\r"), "\n", $pValue); + + return $pValue; + } + + /** + * Check a value that it is a valid error code + * + * @param mixed Value to sanitize to an Excel error code + * @return string Sanitized value + */ + public static function checkErrorCode($pValue = null) + { + $pValue = (string) $pValue; + + if ( !array_key_exists($pValue, self::$_errorCodes) ) { + $pValue = '#NULL!'; + } + + return $pValue; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php new file mode 100644 index 00000000..3174a3fe --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php @@ -0,0 +1,472 @@ +_formula1 = ''; + $this->_formula2 = ''; + $this->_type = PHPExcel_Cell_DataValidation::TYPE_NONE; + $this->_errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; + $this->_operator = ''; + $this->_allowBlank = FALSE; + $this->_showDropDown = FALSE; + $this->_showInputMessage = FALSE; + $this->_showErrorMessage = FALSE; + $this->_errorTitle = ''; + $this->_error = ''; + $this->_promptTitle = ''; + $this->_prompt = ''; + } + + /** + * Get Formula 1 + * + * @return string + */ + public function getFormula1() { + return $this->_formula1; + } + + /** + * Set Formula 1 + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setFormula1($value = '') { + $this->_formula1 = $value; + return $this; + } + + /** + * Get Formula 2 + * + * @return string + */ + public function getFormula2() { + return $this->_formula2; + } + + /** + * Set Formula 2 + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setFormula2($value = '') { + $this->_formula2 = $value; + return $this; + } + + /** + * Get Type + * + * @return string + */ + public function getType() { + return $this->_type; + } + + /** + * Set Type + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setType($value = PHPExcel_Cell_DataValidation::TYPE_NONE) { + $this->_type = $value; + return $this; + } + + /** + * Get Error style + * + * @return string + */ + public function getErrorStyle() { + return $this->_errorStyle; + } + + /** + * Set Error style + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setErrorStyle($value = PHPExcel_Cell_DataValidation::STYLE_STOP) { + $this->_errorStyle = $value; + return $this; + } + + /** + * Get Operator + * + * @return string + */ + public function getOperator() { + return $this->_operator; + } + + /** + * Set Operator + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setOperator($value = '') { + $this->_operator = $value; + return $this; + } + + /** + * Get Allow Blank + * + * @return boolean + */ + public function getAllowBlank() { + return $this->_allowBlank; + } + + /** + * Set Allow Blank + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setAllowBlank($value = false) { + $this->_allowBlank = $value; + return $this; + } + + /** + * Get Show DropDown + * + * @return boolean + */ + public function getShowDropDown() { + return $this->_showDropDown; + } + + /** + * Set Show DropDown + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowDropDown($value = false) { + $this->_showDropDown = $value; + return $this; + } + + /** + * Get Show InputMessage + * + * @return boolean + */ + public function getShowInputMessage() { + return $this->_showInputMessage; + } + + /** + * Set Show InputMessage + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowInputMessage($value = false) { + $this->_showInputMessage = $value; + return $this; + } + + /** + * Get Show ErrorMessage + * + * @return boolean + */ + public function getShowErrorMessage() { + return $this->_showErrorMessage; + } + + /** + * Set Show ErrorMessage + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowErrorMessage($value = false) { + $this->_showErrorMessage = $value; + return $this; + } + + /** + * Get Error title + * + * @return string + */ + public function getErrorTitle() { + return $this->_errorTitle; + } + + /** + * Set Error title + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setErrorTitle($value = '') { + $this->_errorTitle = $value; + return $this; + } + + /** + * Get Error + * + * @return string + */ + public function getError() { + return $this->_error; + } + + /** + * Set Error + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setError($value = '') { + $this->_error = $value; + return $this; + } + + /** + * Get Prompt title + * + * @return string + */ + public function getPromptTitle() { + return $this->_promptTitle; + } + + /** + * Set Prompt title + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setPromptTitle($value = '') { + $this->_promptTitle = $value; + return $this; + } + + /** + * Get Prompt + * + * @return string + */ + public function getPrompt() { + return $this->_prompt; + } + + /** + * Set Prompt + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setPrompt($value = '') { + $this->_prompt = $value; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_formula1 + . $this->_formula2 + . $this->_type = PHPExcel_Cell_DataValidation::TYPE_NONE + . $this->_errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP + . $this->_operator + . ($this->_allowBlank ? 't' : 'f') + . ($this->_showDropDown ? 't' : 'f') + . ($this->_showInputMessage ? 't' : 'f') + . ($this->_showErrorMessage ? 't' : 'f') + . $this->_errorTitle + . $this->_error + . $this->_promptTitle + . $this->_prompt + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php new file mode 100644 index 00000000..f1880faa --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php @@ -0,0 +1,106 @@ +setValueExplicit( $value, self::dataTypeForValue($value) ); + + // Done! + return TRUE; + } + + /** + * DataType for value + * + * @param mixed $pValue + * @return string + */ + public static function dataTypeForValue($pValue = null) { + // Match the value against a few data types + if (is_null($pValue)) { + return PHPExcel_Cell_DataType::TYPE_NULL; + + } elseif ($pValue === '') { + return PHPExcel_Cell_DataType::TYPE_STRING; + + } elseif ($pValue instanceof PHPExcel_RichText) { + return PHPExcel_Cell_DataType::TYPE_INLINE; + + } elseif ($pValue{0} === '=' && strlen($pValue) > 1) { + return PHPExcel_Cell_DataType::TYPE_FORMULA; + + } elseif (is_bool($pValue)) { + return PHPExcel_Cell_DataType::TYPE_BOOL; + + } elseif (is_float($pValue) || is_int($pValue)) { + return PHPExcel_Cell_DataType::TYPE_NUMERIC; + + } elseif (preg_match('/^\-?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)$/', $pValue)) { + return PHPExcel_Cell_DataType::TYPE_NUMERIC; + + } elseif (is_string($pValue) && array_key_exists($pValue, PHPExcel_Cell_DataType::getErrorCodes())) { + return PHPExcel_Cell_DataType::TYPE_ERROR; + + } else { + return PHPExcel_Cell_DataType::TYPE_STRING; + + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php new file mode 100644 index 00000000..06edfad0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php @@ -0,0 +1,126 @@ +_url = $pUrl; + $this->_tooltip = $pTooltip; + } + + /** + * Get URL + * + * @return string + */ + public function getUrl() { + return $this->_url; + } + + /** + * Set URL + * + * @param string $value + * @return PHPExcel_Cell_Hyperlink + */ + public function setUrl($value = '') { + $this->_url = $value; + return $this; + } + + /** + * Get tooltip + * + * @return string + */ + public function getTooltip() { + return $this->_tooltip; + } + + /** + * Set tooltip + * + * @param string $value + * @return PHPExcel_Cell_Hyperlink + */ + public function setTooltip($value = '') { + $this->_tooltip = $value; + return $this; + } + + /** + * Is this hyperlink internal? (to another worksheet) + * + * @return boolean + */ + public function isInternal() { + return strpos($this->_url, 'sheet://') !== false; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_url + . $this->_tooltip + . __CLASS__ + ); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php new file mode 100644 index 00000000..bc7b468b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php @@ -0,0 +1,46 @@ +_name = $name; + $this->_title = $title; + $this->_legend = $legend; + $this->_xAxisLabel = $xAxisLabel; + $this->_yAxisLabel = $yAxisLabel; + $this->_plotArea = $plotArea; + $this->_plotVisibleOnly = $plotVisibleOnly; + $this->_displayBlanksAs = $displayBlanksAs; + } + + /** + * Get Name + * + * @return string + */ + public function getName() { + return $this->_name; + } + + /** + * Get Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() { + return $this->_worksheet; + } + + /** + * Set Worksheet + * + * @param PHPExcel_Worksheet $pValue + * @throws PHPExcel_Chart_Exception + * @return PHPExcel_Chart + */ + public function setWorksheet(PHPExcel_Worksheet $pValue = null) { + $this->_worksheet = $pValue; + + return $this; + } + + /** + * Get Title + * + * @return PHPExcel_Chart_Title + */ + public function getTitle() { + return $this->_title; + } + + /** + * Set Title + * + * @param PHPExcel_Chart_Title $title + * @return PHPExcel_Chart + */ + public function setTitle(PHPExcel_Chart_Title $title) { + $this->_title = $title; + + return $this; + } + + /** + * Get Legend + * + * @return PHPExcel_Chart_Legend + */ + public function getLegend() { + return $this->_legend; + } + + /** + * Set Legend + * + * @param PHPExcel_Chart_Legend $legend + * @return PHPExcel_Chart + */ + public function setLegend(PHPExcel_Chart_Legend $legend) { + $this->_legend = $legend; + + return $this; + } + + /** + * Get X-Axis Label + * + * @return PHPExcel_Chart_Title + */ + public function getXAxisLabel() { + return $this->_xAxisLabel; + } + + /** + * Set X-Axis Label + * + * @param PHPExcel_Chart_Title $label + * @return PHPExcel_Chart + */ + public function setXAxisLabel(PHPExcel_Chart_Title $label) { + $this->_xAxisLabel = $label; + + return $this; + } + + /** + * Get Y-Axis Label + * + * @return PHPExcel_Chart_Title + */ + public function getYAxisLabel() { + return $this->_yAxisLabel; + } + + /** + * Set Y-Axis Label + * + * @param PHPExcel_Chart_Title $label + * @return PHPExcel_Chart + */ + public function setYAxisLabel(PHPExcel_Chart_Title $label) { + $this->_yAxisLabel = $label; + + return $this; + } + + /** + * Get Plot Area + * + * @return PHPExcel_Chart_PlotArea + */ + public function getPlotArea() { + return $this->_plotArea; + } + + /** + * Get Plot Visible Only + * + * @return boolean + */ + public function getPlotVisibleOnly() { + return $this->_plotVisibleOnly; + } + + /** + * Set Plot Visible Only + * + * @param boolean $plotVisibleOnly + * @return PHPExcel_Chart + */ + public function setPlotVisibleOnly($plotVisibleOnly = true) { + $this->_plotVisibleOnly = $plotVisibleOnly; + + return $this; + } + + /** + * Get Display Blanks as + * + * @return string + */ + public function getDisplayBlanksAs() { + return $this->_displayBlanksAs; + } + + /** + * Set Display Blanks as + * + * @param string $displayBlanksAs + * @return PHPExcel_Chart + */ + public function setDisplayBlanksAs($displayBlanksAs = '0') { + $this->_displayBlanksAs = $displayBlanksAs; + } + + + /** + * Set the Top Left position for the chart + * + * @param string $cell + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setTopLeftPosition($cell, $xOffset=null, $yOffset=null) { + $this->_topLeftCellRef = $cell; + if (!is_null($xOffset)) + $this->setTopLeftXOffset($xOffset); + if (!is_null($yOffset)) + $this->setTopLeftYOffset($yOffset); + + return $this; + } + + /** + * Get the top left position of the chart + * + * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + */ + public function getTopLeftPosition() { + return array( 'cell' => $this->_topLeftCellRef, + 'xOffset' => $this->_topLeftXOffset, + 'yOffset' => $this->_topLeftYOffset + ); + } + + /** + * Get the cell address where the top left of the chart is fixed + * + * @return string + */ + public function getTopLeftCell() { + return $this->_topLeftCellRef; + } + + /** + * Set the Top Left cell position for the chart + * + * @param string $cell + * @return PHPExcel_Chart + */ + public function setTopLeftCell($cell) { + $this->_topLeftCellRef = $cell; + + return $this; + } + + /** + * Set the offset position within the Top Left cell for the chart + * + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setTopLeftOffset($xOffset=null,$yOffset=null) { + if (!is_null($xOffset)) + $this->setTopLeftXOffset($xOffset); + if (!is_null($yOffset)) + $this->setTopLeftYOffset($yOffset); + + return $this; + } + + /** + * Get the offset position within the Top Left cell for the chart + * + * @return integer[] + */ + public function getTopLeftOffset() { + return array( 'X' => $this->_topLeftXOffset, + 'Y' => $this->_topLeftYOffset + ); + } + + public function setTopLeftXOffset($xOffset) { + $this->_topLeftXOffset = $xOffset; + + return $this; + } + + public function getTopLeftXOffset() { + return $this->_topLeftXOffset; + } + + public function setTopLeftYOffset($yOffset) { + $this->_topLeftYOffset = $yOffset; + + return $this; + } + + public function getTopLeftYOffset() { + return $this->_topLeftYOffset; + } + + /** + * Set the Bottom Right position of the chart + * + * @param string $cell + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setBottomRightPosition($cell, $xOffset=null, $yOffset=null) { + $this->_bottomRightCellRef = $cell; + if (!is_null($xOffset)) + $this->setBottomRightXOffset($xOffset); + if (!is_null($yOffset)) + $this->setBottomRightYOffset($yOffset); + + return $this; + } + + /** + * Get the bottom right position of the chart + * + * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + */ + public function getBottomRightPosition() { + return array( 'cell' => $this->_bottomRightCellRef, + 'xOffset' => $this->_bottomRightXOffset, + 'yOffset' => $this->_bottomRightYOffset + ); + } + + public function setBottomRightCell($cell) { + $this->_bottomRightCellRef = $cell; + + return $this; + } + + /** + * Get the cell address where the bottom right of the chart is fixed + * + * @return string + */ + public function getBottomRightCell() { + return $this->_bottomRightCellRef; + } + + /** + * Set the offset position within the Bottom Right cell for the chart + * + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setBottomRightOffset($xOffset=null,$yOffset=null) { + if (!is_null($xOffset)) + $this->setBottomRightXOffset($xOffset); + if (!is_null($yOffset)) + $this->setBottomRightYOffset($yOffset); + + return $this; + } + + /** + * Get the offset position within the Bottom Right cell for the chart + * + * @return integer[] + */ + public function getBottomRightOffset() { + return array( 'X' => $this->_bottomRightXOffset, + 'Y' => $this->_bottomRightYOffset + ); + } + + public function setBottomRightXOffset($xOffset) { + $this->_bottomRightXOffset = $xOffset; + + return $this; + } + + public function getBottomRightXOffset() { + return $this->_bottomRightXOffset; + } + + public function setBottomRightYOffset($yOffset) { + $this->_bottomRightYOffset = $yOffset; + + return $this; + } + + public function getBottomRightYOffset() { + return $this->_bottomRightYOffset; + } + + + public function refresh() { + if ($this->_worksheet !== NULL) { + $this->_plotArea->refresh($this->_worksheet); + } + } + + public function render($outputDestination = null) { + $libraryName = PHPExcel_Settings::getChartRendererName(); + if (is_null($libraryName)) { + return false; + } + // Ensure that data series values are up-to-date before we render + $this->refresh(); + + $libraryPath = PHPExcel_Settings::getChartRendererPath(); + $includePath = str_replace('\\','/',get_include_path()); + $rendererPath = str_replace('\\','/',$libraryPath); + if (strpos($rendererPath,$includePath) === false) { + set_include_path(get_include_path() . PATH_SEPARATOR . $libraryPath); + } + + $rendererName = 'PHPExcel_Chart_Renderer_'.$libraryName; + $renderer = new $rendererName($this); + + if ($outputDestination == 'php://output') { + $outputDestination = null; + } + return $renderer->render($outputDestination); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php new file mode 100644 index 00000000..f5391aae --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php @@ -0,0 +1,365 @@ +_plotType = $plotType; + $this->_plotGrouping = $plotGrouping; + $this->_plotOrder = $plotOrder; + $keys = array_keys($plotValues); + $this->_plotValues = $plotValues; + if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) { + $plotLabel[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); + } + + $this->_plotLabel = $plotLabel; + if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) { + $plotCategory[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); + } + $this->_plotCategory = $plotCategory; + $this->_smoothLine = $smoothLine; + $this->_plotStyle = $plotStyle; + } + + /** + * Get Plot Type + * + * @return string + */ + public function getPlotType() { + return $this->_plotType; + } + + /** + * Set Plot Type + * + * @param string $plotType + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotType($plotType = '') { + $this->_plotType = $plotType; + return $this; + } + + /** + * Get Plot Grouping Type + * + * @return string + */ + public function getPlotGrouping() { + return $this->_plotGrouping; + } + + /** + * Set Plot Grouping Type + * + * @param string $groupingType + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotGrouping($groupingType = null) { + $this->_plotGrouping = $groupingType; + return $this; + } + + /** + * Get Plot Direction + * + * @return string + */ + public function getPlotDirection() { + return $this->_plotDirection; + } + + /** + * Set Plot Direction + * + * @param string $plotDirection + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotDirection($plotDirection = null) { + $this->_plotDirection = $plotDirection; + return $this; + } + + /** + * Get Plot Order + * + * @return string + */ + public function getPlotOrder() { + return $this->_plotOrder; + } + + /** + * Get Plot Labels + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotLabels() { + return $this->_plotLabel; + } + + /** + * Get Plot Label by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotLabelByIndex($index) { + $keys = array_keys($this->_plotLabel); + if (in_array($index,$keys)) { + return $this->_plotLabel[$index]; + } elseif(isset($keys[$index])) { + return $this->_plotLabel[$keys[$index]]; + } + return false; + } + + /** + * Get Plot Categories + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotCategories() { + return $this->_plotCategory; + } + + /** + * Get Plot Category by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotCategoryByIndex($index) { + $keys = array_keys($this->_plotCategory); + if (in_array($index,$keys)) { + return $this->_plotCategory[$index]; + } elseif(isset($keys[$index])) { + return $this->_plotCategory[$keys[$index]]; + } + return false; + } + + /** + * Get Plot Style + * + * @return string + */ + public function getPlotStyle() { + return $this->_plotStyle; + } + + /** + * Set Plot Style + * + * @param string $plotStyle + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotStyle($plotStyle = null) { + $this->_plotStyle = $plotStyle; + return $this; + } + + /** + * Get Plot Values + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotValues() { + return $this->_plotValues; + } + + /** + * Get Plot Values by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotValuesByIndex($index) { + $keys = array_keys($this->_plotValues); + if (in_array($index,$keys)) { + return $this->_plotValues[$index]; + } elseif(isset($keys[$index])) { + return $this->_plotValues[$keys[$index]]; + } + return false; + } + + /** + * Get Number of Plot Series + * + * @return integer + */ + public function getPlotSeriesCount() { + return count($this->_plotValues); + } + + /** + * Get Smooth Line + * + * @return boolean + */ + public function getSmoothLine() { + return $this->_smoothLine; + } + + /** + * Set Smooth Line + * + * @param boolean $smoothLine + * @return PHPExcel_Chart_DataSeries + */ + public function setSmoothLine($smoothLine = TRUE) { + $this->_smoothLine = $smoothLine; + return $this; + } + + public function refresh(PHPExcel_Worksheet $worksheet) { + foreach($this->_plotValues as $plotValues) { + if ($plotValues !== NULL) + $plotValues->refresh($worksheet, TRUE); + } + foreach($this->_plotLabel as $plotValues) { + if ($plotValues !== NULL) + $plotValues->refresh($worksheet, TRUE); + } + foreach($this->_plotCategory as $plotValues) { + if ($plotValues !== NULL) + $plotValues->refresh($worksheet, FALSE); + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php new file mode 100644 index 00000000..930542b5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php @@ -0,0 +1,327 @@ +setDataType($dataType); + $this->_dataSource = $dataSource; + $this->_formatCode = $formatCode; + $this->_pointCount = $pointCount; + $this->_dataValues = $dataValues; + $this->_marker = $marker; + } + + /** + * Get Series Data Type + * + * @return string + */ + public function getDataType() { + return $this->_dataType; + } + + /** + * Set Series Data Type + * + * @param string $dataType Datatype of this data series + * Typical values are: + * PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_STRING + * Normally used for axis point values + * PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER + * Normally used for chart data values + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) { + if (!in_array($dataType, self::$_dataTypeValues)) { + throw new PHPExcel_Chart_Exception('Invalid datatype for chart data series values'); + } + $this->_dataType = $dataType; + + return $this; + } + + /** + * Get Series Data Source (formula) + * + * @return string + */ + public function getDataSource() { + return $this->_dataSource; + } + + /** + * Set Series Data Source (formula) + * + * @param string $dataSource + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataSource($dataSource = null, $refreshDataValues = true) { + $this->_dataSource = $dataSource; + + if ($refreshDataValues) { + // TO DO + } + + return $this; + } + + /** + * Get Point Marker + * + * @return string + */ + public function getPointMarker() { + return $this->_marker; + } + + /** + * Set Point Marker + * + * @param string $marker + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setPointMarker($marker = null) { + $this->_marker = $marker; + + return $this; + } + + /** + * Get Series Format Code + * + * @return string + */ + public function getFormatCode() { + return $this->_formatCode; + } + + /** + * Set Series Format Code + * + * @param string $formatCode + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setFormatCode($formatCode = null) { + $this->_formatCode = $formatCode; + + return $this; + } + + /** + * Get Series Point Count + * + * @return integer + */ + public function getPointCount() { + return $this->_pointCount; + } + + /** + * Identify if the Data Series is a multi-level or a simple series + * + * @return boolean + */ + public function isMultiLevelSeries() { + if (count($this->_dataValues) > 0) { + return is_array($this->_dataValues[0]); + } + return null; + } + + /** + * Return the level count of a multi-level Data Series + * + * @return boolean + */ + public function multiLevelCount() { + $levelCount = 0; + foreach($this->_dataValues as $dataValueSet) { + $levelCount = max($levelCount,count($dataValueSet)); + } + return $levelCount; + } + + /** + * Get Series Data Values + * + * @return array of mixed + */ + public function getDataValues() { + return $this->_dataValues; + } + + /** + * Get the first Series Data value + * + * @return mixed + */ + public function getDataValue() { + $count = count($this->_dataValues); + if ($count == 0) { + return null; + } elseif ($count == 1) { + return $this->_dataValues[0]; + } + return $this->_dataValues; + } + + /** + * Set Series Data Values + * + * @param array $dataValues + * @param boolean $refreshDataSource + * TRUE - refresh the value of _dataSource based on the values of $dataValues + * FALSE - don't change the value of _dataSource + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataValues($dataValues = array(), $refreshDataSource = TRUE) { + $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($dataValues); + $this->_pointCount = count($dataValues); + + if ($refreshDataSource) { + // TO DO + } + + return $this; + } + + private function _stripNulls($var) { + return $var !== NULL; + } + + public function refresh(PHPExcel_Worksheet $worksheet, $flatten = TRUE) { + if ($this->_dataSource !== NULL) { + $calcEngine = PHPExcel_Calculation::getInstance($worksheet->getParent()); + $newDataValues = PHPExcel_Calculation::_unwrapResult( + $calcEngine->_calculateFormulaValue( + '='.$this->_dataSource, + NULL, + $worksheet->getCell('A1') + ) + ); + if ($flatten) { + $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + foreach($this->_dataValues as &$dataValue) { + if ((!empty($dataValue)) && ($dataValue[0] == '#')) { + $dataValue = 0.0; + } + } + unset($dataValue); + } else { + $cellRange = explode('!',$this->_dataSource); + if (count($cellRange) > 1) { + list(,$cellRange) = $cellRange; + } + + $dimensions = PHPExcel_Cell::rangeDimension(str_replace('$','',$cellRange)); + if (($dimensions[0] == 1) || ($dimensions[1] == 1)) { + $this->_dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + } else { + $newArray = array_values(array_shift($newDataValues)); + foreach($newArray as $i => $newDataSet) { + $newArray[$i] = array($newDataSet); + } + + foreach($newDataValues as $newDataSet) { + $i = 0; + foreach($newDataSet as $newDataVal) { + array_unshift($newArray[$i++],$newDataVal); + } + } + $this->_dataValues = $newArray; + } + } + $this->_pointCount = count($this->_dataValues); + } + + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php new file mode 100644 index 00000000..ecf3c438 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php @@ -0,0 +1,52 @@ +line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php new file mode 100644 index 00000000..d749dfed --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php @@ -0,0 +1,445 @@ +_layoutTarget = $layout['layoutTarget']; } + if (isset($layout['xMode'])) { $this->_xMode = $layout['xMode']; } + if (isset($layout['yMode'])) { $this->_yMode = $layout['yMode']; } + if (isset($layout['x'])) { $this->_xPos = (float) $layout['x']; } + if (isset($layout['y'])) { $this->_yPos = (float) $layout['y']; } + if (isset($layout['w'])) { $this->_width = (float) $layout['w']; } + if (isset($layout['h'])) { $this->_height = (float) $layout['h']; } + } + + /** + * Get Layout Target + * + * @return string + */ + public function getLayoutTarget() { + return $this->_layoutTarget; + } + + /** + * Set Layout Target + * + * @param Layout Target $value + * @return PHPExcel_Chart_Layout + */ + public function setLayoutTarget($value) { + $this->_layoutTarget = $value; + return $this; + } + + /** + * Get X-Mode + * + * @return string + */ + public function getXMode() { + return $this->_xMode; + } + + /** + * Set X-Mode + * + * @param X-Mode $value + * @return PHPExcel_Chart_Layout + */ + public function setXMode($value) { + $this->_xMode = $value; + return $this; + } + + /** + * Get Y-Mode + * + * @return string + */ + public function getYMode() { + return $this->_yMode; + } + + /** + * Set Y-Mode + * + * @param Y-Mode $value + * @return PHPExcel_Chart_Layout + */ + public function setYMode($value) { + $this->_yMode = $value; + return $this; + } + + /** + * Get X-Position + * + * @return number + */ + public function getXPosition() { + return $this->_xPos; + } + + /** + * Set X-Position + * + * @param X-Position $value + * @return PHPExcel_Chart_Layout + */ + public function setXPosition($value) { + $this->_xPos = $value; + return $this; + } + + /** + * Get Y-Position + * + * @return number + */ + public function getYPosition() { + return $this->_yPos; + } + + /** + * Set Y-Position + * + * @param Y-Position $value + * @return PHPExcel_Chart_Layout + */ + public function setYPosition($value) { + $this->_yPos = $value; + return $this; + } + + /** + * Get Width + * + * @return number + */ + public function getWidth() { + return $this->_width; + } + + /** + * Set Width + * + * @param Width $value + * @return PHPExcel_Chart_Layout + */ + public function setWidth($value) { + $this->_width = $value; + return $this; + } + + /** + * Get Height + * + * @return number + */ + public function getHeight() { + return $this->_height; + } + + /** + * Set Height + * + * @param Height $value + * @return PHPExcel_Chart_Layout + */ + public function setHeight($value) { + $this->_height = $value; + return $this; + } + + + /** + * Get show legend key + * + * @return boolean + */ + public function getShowLegendKey() { + return $this->_showLegendKey; + } + + /** + * Set show legend key + * Specifies that legend keys should be shown in data labels. + * + * @param boolean $value Show legend key + * @return PHPExcel_Chart_Layout + */ + public function setShowLegendKey($value) { + $this->_showLegendKey = $value; + return $this; + } + + /** + * Get show value + * + * @return boolean + */ + public function getShowVal() { + return $this->_showVal; + } + + /** + * Set show val + * Specifies that the value should be shown in data labels. + * + * @param boolean $value Show val + * @return PHPExcel_Chart_Layout + */ + public function setShowVal($value) { + $this->_showVal = $value; + return $this; + } + + /** + * Get show category name + * + * @return boolean + */ + public function getShowCatName() { + return $this->_showCatName; + } + + /** + * Set show cat name + * Specifies that the category name should be shown in data labels. + * + * @param boolean $value Show cat name + * @return PHPExcel_Chart_Layout + */ + public function setShowCatName($value) { + $this->_showCatName = $value; + return $this; + } + + /** + * Get show data series name + * + * @return boolean + */ + public function getShowSerName() { + return $this->_showSerName; + } + + /** + * Set show ser name + * Specifies that the series name should be shown in data labels. + * + * @param boolean $value Show series name + * @return PHPExcel_Chart_Layout + */ + public function setShowSerName($value) { + $this->_showSerName = $value; + return $this; + } + + /** + * Get show percentage + * + * @return boolean + */ + public function getShowPercent() { + return $this->_showPercent; + } + + /** + * Set show percentage + * Specifies that the percentage should be shown in data labels. + * + * @param boolean $value Show percentage + * @return PHPExcel_Chart_Layout + */ + public function setShowPercent($value) { + $this->_showPercent = $value; + return $this; + } + + /** + * Get show bubble size + * + * @return boolean + */ + public function getShowBubbleSize() { + return $this->_showBubbleSize; + } + + /** + * Set show bubble size + * Specifies that the bubble size should be shown in data labels. + * + * @param boolean $value Show bubble size + * @return PHPExcel_Chart_Layout + */ + public function setShowBubbleSize($value) { + $this->_showBubbleSize = $value; + return $this; + } + + /** + * Get show leader lines + * + * @return boolean + */ + public function getShowLeaderLines() { + return $this->_showLeaderLines; + } + + /** + * Set show leader lines + * Specifies that leader lines should be shown in data labels. + * + * @param boolean $value Show leader lines + * @return PHPExcel_Chart_Layout + */ + public function setShowLeaderLines($value) { + $this->_showLeaderLines = $value; + return $this; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php new file mode 100644 index 00000000..4b7c6449 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php @@ -0,0 +1,171 @@ + self::POSITION_BOTTOM, + self::xlLegendPositionCorner => self::POSITION_TOPRIGHT, + self::xlLegendPositionCustom => '??', + self::xlLegendPositionLeft => self::POSITION_LEFT, + self::xlLegendPositionRight => self::POSITION_RIGHT, + self::xlLegendPositionTop => self::POSITION_TOP + ); + + /** + * Legend position + * + * @var string + */ + private $_position = self::POSITION_RIGHT; + + /** + * Allow overlay of other elements? + * + * @var boolean + */ + private $_overlay = TRUE; + + /** + * Legend Layout + * + * @var PHPExcel_Chart_Layout + */ + private $_layout = NULL; + + + /** + * Create a new PHPExcel_Chart_Legend + */ + public function __construct($position = self::POSITION_RIGHT, PHPExcel_Chart_Layout $layout = NULL, $overlay = FALSE) + { + $this->setPosition($position); + $this->_layout = $layout; + $this->setOverlay($overlay); + } + + /** + * Get legend position as an excel string value + * + * @return string + */ + public function getPosition() { + return $this->_position; + } + + /** + * Get legend position using an excel string value + * + * @param string $position + */ + public function setPosition($position = self::POSITION_RIGHT) { + if (!in_array($position,self::$_positionXLref)) { + return false; + } + + $this->_position = $position; + return true; + } + + /** + * Get legend position as an Excel internal numeric value + * + * @return number + */ + public function getPositionXL() { + return array_search($this->_position,self::$_positionXLref); + } + + /** + * Set legend position using an Excel internal numeric value + * + * @param number $positionXL + */ + public function setPositionXL($positionXL = self::xlLegendPositionRight) { + if (!array_key_exists($positionXL,self::$_positionXLref)) { + return false; + } + + $this->_position = self::$_positionXLref[$positionXL]; + return true; + } + + /** + * Get allow overlay of other elements? + * + * @return boolean + */ + public function getOverlay() { + return $this->_overlay; + } + + /** + * Set allow overlay of other elements? + * + * @param boolean $overlay + * @return boolean + */ + public function setOverlay($overlay = FALSE) { + if (!is_bool($overlay)) { + return false; + } + + $this->_overlay = $overlay; + return true; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() { + return $this->_layout; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php new file mode 100644 index 00000000..237d29b0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php @@ -0,0 +1,128 @@ +_layout = $layout; + $this->_plotSeries = $plotSeries; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() { + return $this->_layout; + } + + /** + * Get Number of Plot Groups + * + * @return array of PHPExcel_Chart_DataSeries + */ + public function getPlotGroupCount() { + return count($this->_plotSeries); + } + + /** + * Get Number of Plot Series + * + * @return integer + */ + public function getPlotSeriesCount() { + $seriesCount = 0; + foreach($this->_plotSeries as $plot) { + $seriesCount += $plot->getPlotSeriesCount(); + } + return $seriesCount; + } + + /** + * Get Plot Series + * + * @return array of PHPExcel_Chart_DataSeries + */ + public function getPlotGroup() { + return $this->_plotSeries; + } + + /** + * Get Plot Series by Index + * + * @return PHPExcel_Chart_DataSeries + */ + public function getPlotGroupByIndex($index) { + return $this->_plotSeries[$index]; + } + + /** + * Set Plot Series + * + * @param [PHPExcel_Chart_DataSeries] + * @return PHPExcel_Chart_PlotArea + */ + public function setPlotSeries($plotSeries = array()) { + $this->_plotSeries = $plotSeries; + + return $this; + } + + public function refresh(PHPExcel_Worksheet $worksheet) { + foreach($this->_plotSeries as $plotSeries) { + $plotSeries->refresh($worksheet); + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt new file mode 100644 index 00000000..faaa61d1 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt @@ -0,0 +1,17 @@ +ChartDirector + http://www.advsofteng.com/cdphp.html + +GraPHPite + http://graphpite.sourceforge.net/ + +JpGraph + http://www.aditus.nu/jpgraph/ + +LibChart + http://naku.dohcrew.com/libchart/pages/introduction/ + +pChart + http://pchart.sourceforge.net/ + +TeeChart + http://www.steema.com/products/teechart/overview.html diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php new file mode 100644 index 00000000..14ba2a04 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php @@ -0,0 +1,855 @@ + MARK_DIAMOND, + 'square' => MARK_SQUARE, + 'triangle' => MARK_UTRIANGLE, + 'x' => MARK_X, + 'star' => MARK_STAR, + 'dot' => MARK_FILLEDCIRCLE, + 'dash' => MARK_DTRIANGLE, + 'circle' => MARK_CIRCLE, + 'plus' => MARK_CROSS + ); + + + private $_chart = null; + + private $_graph = null; + + private static $_plotColour = 0; + + private static $_plotMark = 0; + + + private function _formatPointMarker($seriesPlot,$markerID) { + $plotMarkKeys = array_keys(self::$_markSet); + if (is_null($markerID)) { + // Use default plot marker (next marker in the series) + self::$_plotMark %= count(self::$_markSet); + $seriesPlot->mark->SetType(self::$_markSet[$plotMarkKeys[self::$_plotMark++]]); + } elseif ($markerID !== 'none') { + // Use specified plot marker (if it exists) + if (isset(self::$_markSet[$markerID])) { + $seriesPlot->mark->SetType(self::$_markSet[$markerID]); + } else { + // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) + self::$_plotMark %= count(self::$_markSet); + $seriesPlot->mark->SetType(self::$_markSet[$plotMarkKeys[self::$_plotMark++]]); + } + } else { + // Hide plot marker + $seriesPlot->mark->Hide(); + } + $seriesPlot->mark->SetColor(self::$_colourSet[self::$_plotColour]); + $seriesPlot->mark->SetFillColor(self::$_colourSet[self::$_plotColour]); + $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + + return $seriesPlot; + } // function _formatPointMarker() + + + private function _formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') { + $datasetLabelFormatCode = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); + if (!is_null($datasetLabelFormatCode)) { + // Retrieve any label formatting code + $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); + } + + $testCurrentIndex = 0; + foreach($datasetLabels as $i => $datasetLabel) { + if (is_array($datasetLabel)) { + if ($rotation == 'bar') { + $datasetLabels[$i] = implode(" ",$datasetLabel); + } else { + $datasetLabel = array_reverse($datasetLabel); + $datasetLabels[$i] = implode("\n",$datasetLabel); + } + } else { + // Format labels according to any formatting code + if (!is_null($datasetLabelFormatCode)) { + $datasetLabels[$i] = PHPExcel_Style_NumberFormat::toFormattedString($datasetLabel,$datasetLabelFormatCode); + } + } + ++$testCurrentIndex; + } + + return $datasetLabels; + } // function _formatDataSetLabels() + + + private function _percentageSumCalculation($groupID,$seriesCount) { + // Adjust our values to a percentage value across all series in the group + for($i = 0; $i < $seriesCount; ++$i) { + if ($i == 0) { + $sumValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + } else { + $nextValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + foreach($nextValues as $k => $value) { + if (isset($sumValues[$k])) { + $sumValues[$k] += $value; + } else { + $sumValues[$k] = $value; + } + } + } + } + + return $sumValues; + } // function _percentageSumCalculation() + + + private function _percentageAdjustValues($dataValues,$sumValues) { + foreach($dataValues as $k => $dataValue) { + $dataValues[$k] = $dataValue / $sumValues[$k] * 100; + } + + return $dataValues; + } // function _percentageAdjustValues() + + + private function _getCaption($captionElement) { + // Read any caption + $caption = (!is_null($captionElement)) ? $captionElement->getCaption() : NULL; + // Test if we have a title caption to display + if (!is_null($caption)) { + // If we do, it could be a plain string or an array + if (is_array($caption)) { + // Implode an array to a plain string + $caption = implode('',$caption); + } + } + return $caption; + } // function _getCaption() + + + private function _renderTitle() { + $title = $this->_getCaption($this->_chart->getTitle()); + if (!is_null($title)) { + $this->_graph->title->Set($title); + } + } // function _renderTitle() + + + private function _renderLegend() { + $legend = $this->_chart->getLegend(); + if (!is_null($legend)) { + $legendPosition = $legend->getPosition(); + $legendOverlay = $legend->getOverlay(); + switch ($legendPosition) { + case 'r' : + $this->_graph->legend->SetPos(0.01,0.5,'right','center'); // right + $this->_graph->legend->SetColumns(1); + break; + case 'l' : + $this->_graph->legend->SetPos(0.01,0.5,'left','center'); // left + $this->_graph->legend->SetColumns(1); + break; + case 't' : + $this->_graph->legend->SetPos(0.5,0.01,'center','top'); // top + break; + case 'b' : + $this->_graph->legend->SetPos(0.5,0.99,'center','bottom'); // bottom + break; + default : + $this->_graph->legend->SetPos(0.01,0.01,'right','top'); // top-right + $this->_graph->legend->SetColumns(1); + break; + } + } else { + $this->_graph->legend->Hide(); + } + } // function _renderLegend() + + + private function _renderCartesianPlotArea($type='textlin') { + $this->_graph = new Graph(self::$_width,self::$_height); + $this->_graph->SetScale($type); + + $this->_renderTitle(); + + // Rotate for bar rather than column chart + $rotation = $this->_chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); + $reverse = ($rotation == 'bar') ? true : false; + + $xAxisLabel = $this->_chart->getXAxisLabel(); + if (!is_null($xAxisLabel)) { + $title = $this->_getCaption($xAxisLabel); + if (!is_null($title)) { + $this->_graph->xaxis->SetTitle($title,'center'); + $this->_graph->xaxis->title->SetMargin(35); + if ($reverse) { + $this->_graph->xaxis->title->SetAngle(90); + $this->_graph->xaxis->title->SetMargin(90); + } + } + } + + $yAxisLabel = $this->_chart->getYAxisLabel(); + if (!is_null($yAxisLabel)) { + $title = $this->_getCaption($yAxisLabel); + if (!is_null($title)) { + $this->_graph->yaxis->SetTitle($title,'center'); + if ($reverse) { + $this->_graph->yaxis->title->SetAngle(0); + $this->_graph->yaxis->title->SetMargin(-55); + } + } + } + } // function _renderCartesianPlotArea() + + + private function _renderPiePlotArea($doughnut = False) { + $this->_graph = new PieGraph(self::$_width,self::$_height); + + $this->_renderTitle(); + } // function _renderPiePlotArea() + + + private function _renderRadarPlotArea() { + $this->_graph = new RadarGraph(self::$_width,self::$_height); + $this->_graph->SetScale('lin'); + + $this->_renderTitle(); + } // function _renderRadarPlotArea() + + + private function _renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') { + $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->_graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->_percentageSumCalculation($groupID,$seriesCount); + } + + // Loop through each data series in turn + for($i = 0; $i < $seriesCount; ++$i) { + $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + if ($grouping == 'percentStacked') { + $dataValues = $this->_percentageAdjustValues($dataValues,$sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach($dataValues as $k => $dataValue) { + while($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + $seriesPlot = new LinePlot($dataValues); + if ($combination) { + $seriesPlot->SetBarCenter(); + } + + if ($filled) { + $seriesPlot->SetFilled(true); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour++]); + } else { + // Set the appropriate plot marker + $this->_formatPointMarker($seriesPlot,$marker); + } + $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + + if ($grouping == 'standard') { + $groupPlot = $seriesPlots; + } else { + $groupPlot = new AccLinePlot($seriesPlots); + } + $this->_graph->Add($groupPlot); + } // function _renderPlotLine() + + + private function _renderPlotBar($groupID, $dimensions = '2d') { + $rotation = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); + // Rotate for bar rather than column chart + if (($groupID == 0) && ($rotation == 'bar')) { + $this->_graph->Set90AndMargin(); + } + $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); + // Rotate for bar rather than column chart + if ($rotation == 'bar') { + $datasetLabels = array_reverse($datasetLabels); + $this->_graph->yaxis->SetPos('max'); + $this->_graph->yaxis->SetLabelAlign('center','top'); + $this->_graph->yaxis->SetLabelSide(SIDE_RIGHT); + } + $this->_graph->xaxis->SetTickLabels($datasetLabels); + } + + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->_percentageSumCalculation($groupID,$seriesCount); + } + + // Loop through each data series in turn + for($j = 0; $j < $seriesCount; ++$j) { + $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + if ($grouping == 'percentStacked') { + $dataValues = $this->_percentageAdjustValues($dataValues,$sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach($dataValues as $k => $dataValue) { + while($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + // Reverse the $dataValues order for bar rather than column chart + if ($rotation == 'bar') { + $dataValues = array_reverse($dataValues); + } + $seriesPlot = new BarPlot($dataValues); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour++]); + if ($dimensions == '3d') { + $seriesPlot->SetShadow(); + } + if (!$this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { + $dataLabel = ''; + } else { + $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); + } + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + // Reverse the plot order for bar rather than column chart + if (($rotation == 'bar') && (!($grouping == 'percentStacked'))) { + $seriesPlots = array_reverse($seriesPlots); + } + + if ($grouping == 'clustered') { + $groupPlot = new GroupBarPlot($seriesPlots); + } elseif ($grouping == 'standard') { + $groupPlot = new GroupBarPlot($seriesPlots); + } else { + $groupPlot = new AccBarPlot($seriesPlots); + if ($dimensions == '3d') { + $groupPlot->SetShadow(); + } + } + + $this->_graph->Add($groupPlot); + } // function _renderPlotBar() + + + private function _renderPlotScatter($groupID,$bubble) { + $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $scatterStyle = $bubbleSize = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + foreach($dataValuesY as $k => $dataValueY) { + $dataValuesY[$k] = $k; + } + + $seriesPlot = new ScatterPlot($dataValuesX,$dataValuesY); + if ($scatterStyle == 'lineMarker') { + $seriesPlot->SetLinkPoints(); + $seriesPlot->link->SetColor(self::$_colourSet[self::$_plotColour]); + } elseif ($scatterStyle == 'smoothMarker') { + $spline = new Spline($dataValuesY,$dataValuesX); + list($splineDataY,$splineDataX) = $spline->Get(count($dataValuesX) * self::$_width / 20); + $lplot = new LinePlot($splineDataX,$splineDataY); + $lplot->SetColor(self::$_colourSet[self::$_plotColour]); + + $this->_graph->Add($lplot); + } + + if ($bubble) { + $this->_formatPointMarker($seriesPlot,'dot'); + $seriesPlot->mark->SetColor('black'); + $seriesPlot->mark->SetSize($bubbleSize); + } else { + $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $this->_formatPointMarker($seriesPlot,$marker); + } + $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $this->_graph->Add($seriesPlot); + } + } // function _renderPlotScatter() + + + private function _renderPlotRadar($groupID) { + $radarStyle = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + $dataValues = array(); + foreach($dataValuesY as $k => $dataValueY) { + $dataValues[$k] = implode(' ',array_reverse($dataValueY)); + } + $tmp = array_shift($dataValues); + $dataValues[] = $tmp; + $tmp = array_shift($dataValuesX); + $dataValuesX[] = $tmp; + + $this->_graph->SetTitles(array_reverse($dataValues)); + + $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); + + $dataLabel = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + if ($radarStyle == 'filled') { + $seriesPlot->SetFillColor(self::$_colourSet[self::$_plotColour]); + } + $this->_formatPointMarker($seriesPlot,$marker); + $seriesPlot->SetLegend($dataLabel); + + $this->_graph->Add($seriesPlot); + } + } // function _renderPlotRadar() + + + private function _renderPlotContour($groupID) { + $contourStyle = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + $dataValues = array(); + // Loop through each data series in turn + for($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + $dataValues[$i] = $dataValuesX; + } + $seriesPlot = new ContourPlot($dataValues); + + $this->_graph->Add($seriesPlot); + } // function _renderPlotContour() + + + private function _renderPlotStock($groupID) { + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $plotOrder = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); + + $dataValues = array(); + // Loop through each data series in turn and build the plot arrays + foreach($plotOrder as $i => $v) { + $dataValuesX = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); + foreach($dataValuesX as $j => $dataValueX) { + $dataValues[$plotOrder[$i]][$j] = $dataValueX; + } + } + if(empty($dataValues)) { + return; + } + + $dataValuesPlot = array(); + // Flatten the plot arrays to a single dimensional array to work with jpgraph + for($j = 0; $j < count($dataValues[0]); $j++) { + for($i = 0; $i < $seriesCount; $i++) { + $dataValuesPlot[] = $dataValues[$i][$j]; + } + } + + // Set the x-axis labels + $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->_graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesPlot = new StockPlot($dataValuesPlot); + $seriesPlot->SetWidth(20); + + $this->_graph->Add($seriesPlot); + } // function _renderPlotStock() + + + private function _renderAreaChart($groupCount, $dimensions = '2d') { + require_once('jpgraph_line.php'); + + $this->_renderCartesianPlotArea(); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotLine($i,True,False,$dimensions); + } + } // function _renderAreaChart() + + + private function _renderLineChart($groupCount, $dimensions = '2d') { + require_once('jpgraph_line.php'); + + $this->_renderCartesianPlotArea(); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotLine($i,False,False,$dimensions); + } + } // function _renderLineChart() + + + private function _renderBarChart($groupCount, $dimensions = '2d') { + require_once('jpgraph_bar.php'); + + $this->_renderCartesianPlotArea(); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotBar($i,$dimensions); + } + } // function _renderBarChart() + + + private function _renderScatterChart($groupCount) { + require_once('jpgraph_scatter.php'); + require_once('jpgraph_regstat.php'); + require_once('jpgraph_line.php'); + + $this->_renderCartesianPlotArea('linlin'); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotScatter($i,false); + } + } // function _renderScatterChart() + + + private function _renderBubbleChart($groupCount) { + require_once('jpgraph_scatter.php'); + + $this->_renderCartesianPlotArea('linlin'); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotScatter($i,true); + } + } // function _renderBubbleChart() + + + private function _renderPieChart($groupCount, $dimensions = '2d', $doughnut = False, $multiplePlots = False) { + require_once('jpgraph_pie.php'); + if ($dimensions == '3d') { + require_once('jpgraph_pie3d.php'); + } + + $this->_renderPiePlotArea($doughnut); + + $iLimit = ($multiplePlots) ? $groupCount : 1; + for($groupID = 0; $groupID < $iLimit; ++$groupID) { + $grouping = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $exploded = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + if ($groupID == 0) { + $labelCount = count($this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->_formatDataSetLabels($groupID, $datasetLabels, $labelCount); + } + } + + $seriesCount = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + // For pie charts, we only display the first series: doughnut charts generally display all series + $jLimit = ($multiplePlots) ? $seriesCount : 1; + // Loop through each data series in turn + for($j = 0; $j < $jLimit; ++$j) { + $dataValues = $this->_chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach($dataValues as $k => $dataValue) { + while($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + if ($dimensions == '3d') { + $seriesPlot = new PiePlot3D($dataValues); + } else { + if ($doughnut) { + $seriesPlot = new PiePlotC($dataValues); + } else { + $seriesPlot = new PiePlot($dataValues); + } + } + + if ($multiplePlots) { + $seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); + } + + if ($doughnut) { + $seriesPlot->SetMidColor('white'); + } + + $seriesPlot->SetColor(self::$_colourSet[self::$_plotColour++]); + if (count($datasetLabels) > 0) + $seriesPlot->SetLabels(array_fill(0,count($datasetLabels),'')); + if ($dimensions != '3d') { + $seriesPlot->SetGuideLines(false); + } + if ($j == 0) { + if ($exploded) { + $seriesPlot->ExplodeAll(); + } + $seriesPlot->SetLegends($datasetLabels); + } + + $this->_graph->Add($seriesPlot); + } + } + } // function _renderPieChart() + + + private function _renderRadarChart($groupCount) { + require_once('jpgraph_radar.php'); + + $this->_renderRadarPlotArea(); + + for($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->_renderPlotRadar($groupID); + } + } // function _renderRadarChart() + + + private function _renderStockChart($groupCount) { + require_once('jpgraph_stock.php'); + + $this->_renderCartesianPlotArea('intint'); + + for($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->_renderPlotStock($groupID); + } + } // function _renderStockChart() + + + private function _renderContourChart($groupCount,$dimensions) { + require_once('jpgraph_contour.php'); + + $this->_renderCartesianPlotArea('intint'); + + for($i = 0; $i < $groupCount; ++$i) { + $this->_renderPlotContour($i); + } + } // function _renderContourChart() + + + private function _renderCombinationChart($groupCount,$dimensions,$outputDestination) { + require_once('jpgraph_line.php'); + require_once('jpgraph_bar.php'); + require_once('jpgraph_scatter.php'); + require_once('jpgraph_regstat.php'); + require_once('jpgraph_line.php'); + + $this->_renderCartesianPlotArea(); + + for($i = 0; $i < $groupCount; ++$i) { + $dimensions = null; + $chartType = $this->_chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + switch ($chartType) { + case 'area3DChart' : + $dimensions = '3d'; + case 'areaChart' : + $this->_renderPlotLine($i,True,True,$dimensions); + break; + case 'bar3DChart' : + $dimensions = '3d'; + case 'barChart' : + $this->_renderPlotBar($i,$dimensions); + break; + case 'line3DChart' : + $dimensions = '3d'; + case 'lineChart' : + $this->_renderPlotLine($i,False,True,$dimensions); + break; + case 'scatterChart' : + $this->_renderPlotScatter($i,false); + break; + case 'bubbleChart' : + $this->_renderPlotScatter($i,true); + break; + default : + $this->_graph = null; + return false; + } + } + + $this->_renderLegend(); + + $this->_graph->Stroke($outputDestination); + return true; + } // function _renderCombinationChart() + + + public function render($outputDestination) { + self::$_plotColour = 0; + + $groupCount = $this->_chart->getPlotArea()->getPlotGroupCount(); + + $dimensions = null; + if ($groupCount == 1) { + $chartType = $this->_chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); + } else { + $chartTypes = array(); + for($i = 0; $i < $groupCount; ++$i) { + $chartTypes[] = $this->_chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + } + $chartTypes = array_unique($chartTypes); + if (count($chartTypes) == 1) { + $chartType = array_pop($chartTypes); + } elseif (count($chartTypes) == 0) { + echo 'Chart is not yet implemented
'; + return false; + } else { + return $this->_renderCombinationChart($groupCount,$dimensions,$outputDestination); + } + } + + switch ($chartType) { + case 'area3DChart' : + $dimensions = '3d'; + case 'areaChart' : + $this->_renderAreaChart($groupCount,$dimensions); + break; + case 'bar3DChart' : + $dimensions = '3d'; + case 'barChart' : + $this->_renderBarChart($groupCount,$dimensions); + break; + case 'line3DChart' : + $dimensions = '3d'; + case 'lineChart' : + $this->_renderLineChart($groupCount,$dimensions); + break; + case 'pie3DChart' : + $dimensions = '3d'; + case 'pieChart' : + $this->_renderPieChart($groupCount,$dimensions,False,False); + break; + case 'doughnut3DChart' : + $dimensions = '3d'; + case 'doughnutChart' : + $this->_renderPieChart($groupCount,$dimensions,True,True); + break; + case 'scatterChart' : + $this->_renderScatterChart($groupCount); + break; + case 'bubbleChart' : + $this->_renderBubbleChart($groupCount); + break; + case 'radarChart' : + $this->_renderRadarChart($groupCount); + break; + case 'surface3DChart' : + $dimensions = '3d'; + case 'surfaceChart' : + $this->_renderContourChart($groupCount,$dimensions); + break; + case 'stockChart' : + $this->_renderStockChart($groupCount,$dimensions); + break; + default : + echo $chartType.' is not yet implemented
'; + return false; + } + $this->_renderLegend(); + + $this->_graph->Stroke($outputDestination); + return true; + } // function render() + + + /** + * Create a new PHPExcel_Chart_Renderer_jpgraph + */ + public function __construct(PHPExcel_Chart $chart) + { + $this->_graph = null; + $this->_chart = $chart; + } // function __construct() + +} // PHPExcel_Chart_Renderer_jpgraph diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php new file mode 100644 index 00000000..415551b3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php @@ -0,0 +1,92 @@ +_caption = $caption; + $this->_layout = $layout; + } + + /** + * Get caption + * + * @return string + */ + public function getCaption() { + return $this->_caption; + } + + /** + * Set caption + * + * @param string $caption + * @return PHPExcel_Chart_Title + */ + public function setCaption($caption = null) { + $this->_caption = $caption; + + return $this; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() { + return $this->_layout; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php new file mode 100644 index 00000000..a2422c60 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php @@ -0,0 +1,327 @@ +_author = 'Author'; + $this->_text = new PHPExcel_RichText(); + $this->_fillColor = new PHPExcel_Style_Color('FFFFFFE1'); + $this->_alignment = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + } + + /** + * Get Author + * + * @return string + */ + public function getAuthor() { + return $this->_author; + } + + /** + * Set Author + * + * @param string $pValue + * @return PHPExcel_Comment + */ + public function setAuthor($pValue = '') { + $this->_author = $pValue; + return $this; + } + + /** + * Get Rich text comment + * + * @return PHPExcel_RichText + */ + public function getText() { + return $this->_text; + } + + /** + * Set Rich text comment + * + * @param PHPExcel_RichText $pValue + * @return PHPExcel_Comment + */ + public function setText(PHPExcel_RichText $pValue) { + $this->_text = $pValue; + return $this; + } + + /** + * Get comment width (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getWidth() { + return $this->_width; + } + + /** + * Set comment width (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setWidth($value = '96pt') { + $this->_width = $value; + return $this; + } + + /** + * Get comment height (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getHeight() { + return $this->_height; + } + + /** + * Set comment height (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setHeight($value = '55.5pt') { + $this->_height = $value; + return $this; + } + + /** + * Get left margin (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getMarginLeft() { + return $this->_marginLeft; + } + + /** + * Set left margin (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setMarginLeft($value = '59.25pt') { + $this->_marginLeft = $value; + return $this; + } + + /** + * Get top margin (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getMarginTop() { + return $this->_marginTop; + } + + /** + * Set top margin (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setMarginTop($value = '1.5pt') { + $this->_marginTop = $value; + return $this; + } + + /** + * Is the comment visible by default? + * + * @return boolean + */ + public function getVisible() { + return $this->_visible; + } + + /** + * Set comment default visibility + * + * @param boolean $value + * @return PHPExcel_Comment + */ + public function setVisible($value = false) { + $this->_visible = $value; + return $this; + } + + /** + * Get fill color + * + * @return PHPExcel_Style_Color + */ + public function getFillColor() { + return $this->_fillColor; + } + + /** + * Set Alignment + * + * @param string $pValue + * @return PHPExcel_Comment + */ + public function setAlignment($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) { + $this->_alignment = $pValue; + return $this; + } + + /** + * Get Alignment + * + * @return string + */ + public function getAlignment() { + return $this->_alignment; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_author + . $this->_text->getHashCode() + . $this->_width + . $this->_height + . $this->_marginLeft + . $this->_marginTop + . ($this->_visible ? 1 : 0) + . $this->_fillColor->getHashCode() + . $this->_alignment + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() { + return $this->_text->getPlainText(); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php new file mode 100644 index 00000000..2f1fa1ed --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php @@ -0,0 +1,587 @@ +_lastModifiedBy = $this->_creator; + $this->_created = time(); + $this->_modified = time(); + } + + /** + * Get Creator + * + * @return string + */ + public function getCreator() { + return $this->_creator; + } + + /** + * Set Creator + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCreator($pValue = '') { + $this->_creator = $pValue; + return $this; + } + + /** + * Get Last Modified By + * + * @return string + */ + public function getLastModifiedBy() { + return $this->_lastModifiedBy; + } + + /** + * Set Last Modified By + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setLastModifiedBy($pValue = '') { + $this->_lastModifiedBy = $pValue; + return $this; + } + + /** + * Get Created + * + * @return datetime + */ + public function getCreated() { + return $this->_created; + } + + /** + * Set Created + * + * @param datetime $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCreated($pValue = null) { + if ($pValue === NULL) { + $pValue = time(); + } elseif (is_string($pValue)) { + if (is_numeric($pValue)) { + $pValue = intval($pValue); + } else { + $pValue = strtotime($pValue); + } + } + + $this->_created = $pValue; + return $this; + } + + /** + * Get Modified + * + * @return datetime + */ + public function getModified() { + return $this->_modified; + } + + /** + * Set Modified + * + * @param datetime $pValue + * @return PHPExcel_DocumentProperties + */ + public function setModified($pValue = null) { + if ($pValue === NULL) { + $pValue = time(); + } elseif (is_string($pValue)) { + if (is_numeric($pValue)) { + $pValue = intval($pValue); + } else { + $pValue = strtotime($pValue); + } + } + + $this->_modified = $pValue; + return $this; + } + + /** + * Get Title + * + * @return string + */ + public function getTitle() { + return $this->_title; + } + + /** + * Set Title + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setTitle($pValue = '') { + $this->_title = $pValue; + return $this; + } + + /** + * Get Description + * + * @return string + */ + public function getDescription() { + return $this->_description; + } + + /** + * Set Description + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setDescription($pValue = '') { + $this->_description = $pValue; + return $this; + } + + /** + * Get Subject + * + * @return string + */ + public function getSubject() { + return $this->_subject; + } + + /** + * Set Subject + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setSubject($pValue = '') { + $this->_subject = $pValue; + return $this; + } + + /** + * Get Keywords + * + * @return string + */ + public function getKeywords() { + return $this->_keywords; + } + + /** + * Set Keywords + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setKeywords($pValue = '') { + $this->_keywords = $pValue; + return $this; + } + + /** + * Get Category + * + * @return string + */ + public function getCategory() { + return $this->_category; + } + + /** + * Set Category + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCategory($pValue = '') { + $this->_category = $pValue; + return $this; + } + + /** + * Get Company + * + * @return string + */ + public function getCompany() { + return $this->_company; + } + + /** + * Set Company + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCompany($pValue = '') { + $this->_company = $pValue; + return $this; + } + + /** + * Get Manager + * + * @return string + */ + public function getManager() { + return $this->_manager; + } + + /** + * Set Manager + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setManager($pValue = '') { + $this->_manager = $pValue; + return $this; + } + + /** + * Get a List of Custom Property Names + * + * @return array of string + */ + public function getCustomProperties() { + return array_keys($this->_customProperties); + } + + /** + * Check if a Custom Property is defined + * + * @param string $propertyName + * @return boolean + */ + public function isCustomPropertySet($propertyName) { + return isset($this->_customProperties[$propertyName]); + } + + /** + * Get a Custom Property Value + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyValue($propertyName) { + if (isset($this->_customProperties[$propertyName])) { + return $this->_customProperties[$propertyName]['value']; + } + + } + + /** + * Get a Custom Property Type + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyType($propertyName) { + if (isset($this->_customProperties[$propertyName])) { + return $this->_customProperties[$propertyName]['type']; + } + + } + + /** + * Set a Custom Property + * + * @param string $propertyName + * @param mixed $propertyValue + * @param string $propertyType + * 'i' : Integer + * 'f' : Floating Point + * 's' : String + * 'd' : Date/Time + * 'b' : Boolean + * @return PHPExcel_DocumentProperties + */ + public function setCustomProperty($propertyName,$propertyValue='',$propertyType=NULL) { + if (($propertyType === NULL) || (!in_array($propertyType,array(self::PROPERTY_TYPE_INTEGER, + self::PROPERTY_TYPE_FLOAT, + self::PROPERTY_TYPE_STRING, + self::PROPERTY_TYPE_DATE, + self::PROPERTY_TYPE_BOOLEAN)))) { + if ($propertyValue === NULL) { + $propertyType = self::PROPERTY_TYPE_STRING; + } elseif (is_float($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_FLOAT; + } elseif(is_int($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_INTEGER; + } elseif (is_bool($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_BOOLEAN; + } else { + $propertyType = self::PROPERTY_TYPE_STRING; + } + } + + $this->_customProperties[$propertyName] = array('value' => $propertyValue, 'type' => $propertyType); + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + public static function convertProperty($propertyValue,$propertyType) { + switch ($propertyType) { + case 'empty' : // Empty + return ''; + break; + case 'null' : // Null + return NULL; + break; + case 'i1' : // 1-Byte Signed Integer + case 'i2' : // 2-Byte Signed Integer + case 'i4' : // 4-Byte Signed Integer + case 'i8' : // 8-Byte Signed Integer + case 'int' : // Integer + return (int) $propertyValue; + break; + case 'ui1' : // 1-Byte Unsigned Integer + case 'ui2' : // 2-Byte Unsigned Integer + case 'ui4' : // 4-Byte Unsigned Integer + case 'ui8' : // 8-Byte Unsigned Integer + case 'uint' : // Unsigned Integer + return abs((int) $propertyValue); + break; + case 'r4' : // 4-Byte Real Number + case 'r8' : // 8-Byte Real Number + case 'decimal' : // Decimal + return (float) $propertyValue; + break; + case 'lpstr' : // LPSTR + case 'lpwstr' : // LPWSTR + case 'bstr' : // Basic String + return $propertyValue; + break; + case 'date' : // Date and Time + case 'filetime' : // File Time + return strtotime($propertyValue); + break; + case 'bool' : // Boolean + return ($propertyValue == 'true') ? True : False; + break; + case 'cy' : // Currency + case 'error' : // Error Status Code + case 'vector' : // Vector + case 'array' : // Array + case 'blob' : // Binary Blob + case 'oblob' : // Binary Blob Object + case 'stream' : // Binary Stream + case 'ostream' : // Binary Stream Object + case 'storage' : // Binary Storage + case 'ostorage' : // Binary Storage Object + case 'vstream' : // Binary Versioned Stream + case 'clsid' : // Class ID + case 'cf' : // Clipboard Data + return $propertyValue; + break; + } + return $propertyValue; + } + + public static function convertPropertyType($propertyType) { + switch ($propertyType) { + case 'i1' : // 1-Byte Signed Integer + case 'i2' : // 2-Byte Signed Integer + case 'i4' : // 4-Byte Signed Integer + case 'i8' : // 8-Byte Signed Integer + case 'int' : // Integer + case 'ui1' : // 1-Byte Unsigned Integer + case 'ui2' : // 2-Byte Unsigned Integer + case 'ui4' : // 4-Byte Unsigned Integer + case 'ui8' : // 8-Byte Unsigned Integer + case 'uint' : // Unsigned Integer + return self::PROPERTY_TYPE_INTEGER; + break; + case 'r4' : // 4-Byte Real Number + case 'r8' : // 8-Byte Real Number + case 'decimal' : // Decimal + return self::PROPERTY_TYPE_FLOAT; + break; + case 'empty' : // Empty + case 'null' : // Null + case 'lpstr' : // LPSTR + case 'lpwstr' : // LPWSTR + case 'bstr' : // Basic String + return self::PROPERTY_TYPE_STRING; + break; + case 'date' : // Date and Time + case 'filetime' : // File Time + return self::PROPERTY_TYPE_DATE; + break; + case 'bool' : // Boolean + return self::PROPERTY_TYPE_BOOLEAN; + break; + case 'cy' : // Currency + case 'error' : // Error Status Code + case 'vector' : // Vector + case 'array' : // Array + case 'blob' : // Binary Blob + case 'oblob' : // Binary Blob Object + case 'stream' : // Binary Stream + case 'ostream' : // Binary Stream Object + case 'storage' : // Binary Storage + case 'ostorage' : // Binary Storage Object + case 'vstream' : // Binary Versioned Stream + case 'clsid' : // Class ID + case 'cf' : // Clipboard Data + return self::PROPERTY_TYPE_UNKNOWN; + break; + } + return self::PROPERTY_TYPE_UNKNOWN; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php new file mode 100644 index 00000000..340504e8 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php @@ -0,0 +1,218 @@ +_lockRevision = false; + $this->_lockStructure = false; + $this->_lockWindows = false; + $this->_revisionsPassword = ''; + $this->_workbookPassword = ''; + } + + /** + * Is some sort of dcument security enabled? + * + * @return boolean + */ + function isSecurityEnabled() { + return $this->_lockRevision || + $this->_lockStructure || + $this->_lockWindows; + } + + /** + * Get LockRevision + * + * @return boolean + */ + function getLockRevision() { + return $this->_lockRevision; + } + + /** + * Set LockRevision + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + function setLockRevision($pValue = false) { + $this->_lockRevision = $pValue; + return $this; + } + + /** + * Get LockStructure + * + * @return boolean + */ + function getLockStructure() { + return $this->_lockStructure; + } + + /** + * Set LockStructure + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + function setLockStructure($pValue = false) { + $this->_lockStructure = $pValue; + return $this; + } + + /** + * Get LockWindows + * + * @return boolean + */ + function getLockWindows() { + return $this->_lockWindows; + } + + /** + * Set LockWindows + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + function setLockWindows($pValue = false) { + $this->_lockWindows = $pValue; + return $this; + } + + /** + * Get RevisionsPassword (hashed) + * + * @return string + */ + function getRevisionsPassword() { + return $this->_revisionsPassword; + } + + /** + * Set RevisionsPassword + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_DocumentSecurity + */ + function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->_revisionsPassword = $pValue; + return $this; + } + + /** + * Get WorkbookPassword (hashed) + * + * @return string + */ + function getWorkbookPassword() { + return $this->_workbookPassword; + } + + /** + * Set WorkbookPassword + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_DocumentSecurity + */ + function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->_workbookPassword = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php new file mode 100644 index 00000000..683e9099 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php @@ -0,0 +1,52 @@ +line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php new file mode 100644 index 00000000..7a9205e5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php @@ -0,0 +1,202 @@ +addFromSource($pSource); + } + } + + /** + * Add HashTable items from source + * + * @param PHPExcel_IComparable[] $pSource Source array to create HashTable from + * @throws PHPExcel_Exception + */ + public function addFromSource($pSource = null) { + // Check if an array was passed + if ($pSource == null) { + return; + } else if (!is_array($pSource)) { + throw new PHPExcel_Exception('Invalid array parameter passed.'); + } + + foreach ($pSource as $item) { + $this->add($item); + } + } + + /** + * Add HashTable item + * + * @param PHPExcel_IComparable $pSource Item to add + * @throws PHPExcel_Exception + */ + public function add(PHPExcel_IComparable $pSource = null) { + $hash = $pSource->getHashCode(); + if (!isset($this->_items[$hash])) { + $this->_items[$hash] = $pSource; + $this->_keyMap[count($this->_items) - 1] = $hash; + } + } + + /** + * Remove HashTable item + * + * @param PHPExcel_IComparable $pSource Item to remove + * @throws PHPExcel_Exception + */ + public function remove(PHPExcel_IComparable $pSource = null) { + $hash = $pSource->getHashCode(); + if (isset($this->_items[$hash])) { + unset($this->_items[$hash]); + + $deleteKey = -1; + foreach ($this->_keyMap as $key => $value) { + if ($deleteKey >= 0) { + $this->_keyMap[$key - 1] = $value; + } + + if ($value == $hash) { + $deleteKey = $key; + } + } + unset($this->_keyMap[count($this->_keyMap) - 1]); + } + } + + /** + * Clear HashTable + * + */ + public function clear() { + $this->_items = array(); + $this->_keyMap = array(); + } + + /** + * Count + * + * @return int + */ + public function count() { + return count($this->_items); + } + + /** + * Get index for hash code + * + * @param string $pHashCode + * @return int Index + */ + public function getIndexForHashCode($pHashCode = '') { + return array_search($pHashCode, $this->_keyMap); + } + + /** + * Get by index + * + * @param int $pIndex + * @return PHPExcel_IComparable + * + */ + public function getByIndex($pIndex = 0) { + if (isset($this->_keyMap[$pIndex])) { + return $this->getByHashCode( $this->_keyMap[$pIndex] ); + } + + return null; + } + + /** + * Get by hashcode + * + * @param string $pHashCode + * @return PHPExcel_IComparable + * + */ + public function getByHashCode($pHashCode = '') { + if (isset($this->_items[$pHashCode])) { + return $this->_items[$pHashCode]; + } + + return null; + } + + /** + * HashTable to array + * + * @return PHPExcel_IComparable[] + */ + public function toArray() { + return $this->_items; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php new file mode 100644 index 00000000..6b1e18aa --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php @@ -0,0 +1,43 @@ + 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'PHPExcel_Writer_{0}' ), + array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'PHPExcel_Reader_{0}' ) + ); + + /** + * Autoresolve classes + * + * @var array + * @access private + * @static + */ + private static $_autoResolveClasses = array( + 'Excel2007', + 'Excel5', + 'Excel2003XML', + 'OOCalc', + 'SYLK', + 'Gnumeric', + 'HTML', + 'CSV', + ); + + /** + * Private constructor for PHPExcel_IOFactory + */ + private function __construct() { } + + /** + * Get search locations + * + * @static + * @access public + * @return array + */ + public static function getSearchLocations() { + return self::$_searchLocations; + } // function getSearchLocations() + + /** + * Set search locations + * + * @static + * @access public + * @param array $value + * @throws PHPExcel_Reader_Exception + */ + public static function setSearchLocations($value) { + if (is_array($value)) { + self::$_searchLocations = $value; + } else { + throw new PHPExcel_Reader_Exception('Invalid parameter passed.'); + } + } // function setSearchLocations() + + /** + * Add search location + * + * @static + * @access public + * @param string $type Example: IWriter + * @param string $location Example: PHPExcel/Writer/{0}.php + * @param string $classname Example: PHPExcel_Writer_{0} + */ + public static function addSearchLocation($type = '', $location = '', $classname = '') { + self::$_searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname ); + } // function addSearchLocation() + + /** + * Create PHPExcel_Writer_IWriter + * + * @static + * @access public + * @param PHPExcel $phpExcel + * @param string $writerType Example: Excel2007 + * @return PHPExcel_Writer_IWriter + * @throws PHPExcel_Reader_Exception + */ + public static function createWriter(PHPExcel $phpExcel, $writerType = '') { + // Search type + $searchType = 'IWriter'; + + // Include class + foreach (self::$_searchLocations as $searchLocation) { + if ($searchLocation['type'] == $searchType) { + $className = str_replace('{0}', $writerType, $searchLocation['class']); + + $instance = new $className($phpExcel); + if ($instance !== NULL) { + return $instance; + } + } + } + + // Nothing found... + throw new PHPExcel_Reader_Exception("No $searchType found for type $writerType"); + } // function createWriter() + + /** + * Create PHPExcel_Reader_IReader + * + * @static + * @access public + * @param string $readerType Example: Excel2007 + * @return PHPExcel_Reader_IReader + * @throws PHPExcel_Reader_Exception + */ + public static function createReader($readerType = '') { + // Search type + $searchType = 'IReader'; + + // Include class + foreach (self::$_searchLocations as $searchLocation) { + if ($searchLocation['type'] == $searchType) { + $className = str_replace('{0}', $readerType, $searchLocation['class']); + + $instance = new $className(); + if ($instance !== NULL) { + return $instance; + } + } + } + + // Nothing found... + throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType"); + } // function createReader() + + /** + * Loads PHPExcel from file using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public static function load($pFilename) { + $reader = self::createReaderForFile($pFilename); + return $reader->load($pFilename); + } // function load() + + /** + * Identify file type using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file to identify + * @return string + * @throws PHPExcel_Reader_Exception + */ + public static function identify($pFilename) { + $reader = self::createReaderForFile($pFilename); + $className = get_class($reader); + $classType = explode('_',$className); + unset($reader); + return array_pop($classType); + } // function identify() + + /** + * Create PHPExcel_Reader_IReader for file using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file + * @return PHPExcel_Reader_IReader + * @throws PHPExcel_Reader_Exception + */ + public static function createReaderForFile($pFilename) { + + // First, lucky guess by inspecting file extension + $pathinfo = pathinfo($pFilename); + + $extensionType = NULL; + if (isset($pathinfo['extension'])) { + switch (strtolower($pathinfo['extension'])) { + case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet + case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded) + case 'xltx': // Excel (OfficeOpenXML) Template + case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded) + $extensionType = 'Excel2007'; + break; + case 'xls': // Excel (BIFF) Spreadsheet + case 'xlt': // Excel (BIFF) Template + $extensionType = 'Excel5'; + break; + case 'ods': // Open/Libre Offic Calc + case 'ots': // Open/Libre Offic Calc Template + $extensionType = 'OOCalc'; + break; + case 'slk': + $extensionType = 'SYLK'; + break; + case 'xml': // Excel 2003 SpreadSheetML + $extensionType = 'Excel2003XML'; + break; + case 'gnumeric': + $extensionType = 'Gnumeric'; + break; + case 'htm': + case 'html': + $extensionType = 'HTML'; + break; + case 'csv': + // Do nothing + // We must not try to use CSV reader since it loads + // all files including Excel files etc. + break; + default: + break; + } + + if ($extensionType !== NULL) { + $reader = self::createReader($extensionType); + // Let's see if we are lucky + if (isset($reader) && $reader->canRead($pFilename)) { + return $reader; + } + } + } + + // If we reach here then "lucky guess" didn't give any result + // Try walking through all the options in self::$_autoResolveClasses + foreach (self::$_autoResolveClasses as $autoResolveClass) { + // Ignore our original guess, we know that won't work + if ($autoResolveClass !== $extensionType) { + $reader = self::createReader($autoResolveClass); + if ($reader->canRead($pFilename)) { + return $reader; + } + } + } + + throw new PHPExcel_Reader_Exception('Unable to identify a reader for this file'); + } // function createReaderForFile() +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php new file mode 100644 index 00000000..3ad5caab --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php @@ -0,0 +1,246 @@ +_worksheet) + * + * @var bool + */ + private $_localOnly; + + /** + * Scope + * + * @var PHPExcel_Worksheet + */ + private $_scope; + + /** + * Create a new NamedRange + * + * @param string $pName + * @param PHPExcel_Worksheet $pWorksheet + * @param string $pRange + * @param bool $pLocalOnly + * @param PHPExcel_Worksheet|null $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope. + * @throws PHPExcel_Exception + */ + public function __construct($pName = null, PHPExcel_Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null) + { + // Validate data + if (($pName === NULL) || ($pWorksheet === NULL) || ($pRange === NULL)) { + throw new PHPExcel_Exception('Parameters can not be null.'); + } + + // Set local members + $this->_name = $pName; + $this->_worksheet = $pWorksheet; + $this->_range = $pRange; + $this->_localOnly = $pLocalOnly; + $this->_scope = ($pLocalOnly == true) ? + (($pScope == null) ? $pWorksheet : $pScope) : null; + } + + /** + * Get name + * + * @return string + */ + public function getName() { + return $this->_name; + } + + /** + * Set name + * + * @param string $value + * @return PHPExcel_NamedRange + */ + public function setName($value = null) { + if ($value !== NULL) { + // Old title + $oldTitle = $this->_name; + + // Re-attach + if ($this->_worksheet !== NULL) { + $this->_worksheet->getParent()->removeNamedRange($this->_name,$this->_worksheet); + } + $this->_name = $value; + + if ($this->_worksheet !== NULL) { + $this->_worksheet->getParent()->addNamedRange($this); + } + + // New title + $newTitle = $this->_name; + PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->_worksheet->getParent(), $oldTitle, $newTitle); + } + return $this; + } + + /** + * Get worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() { + return $this->_worksheet; + } + + /** + * Set worksheet + * + * @param PHPExcel_Worksheet $value + * @return PHPExcel_NamedRange + */ + public function setWorksheet(PHPExcel_Worksheet $value = null) { + if ($value !== NULL) { + $this->_worksheet = $value; + } + return $this; + } + + /** + * Get range + * + * @return string + */ + public function getRange() { + return $this->_range; + } + + /** + * Set range + * + * @param string $value + * @return PHPExcel_NamedRange + */ + public function setRange($value = null) { + if ($value !== NULL) { + $this->_range = $value; + } + return $this; + } + + /** + * Get localOnly + * + * @return bool + */ + public function getLocalOnly() { + return $this->_localOnly; + } + + /** + * Set localOnly + * + * @param bool $value + * @return PHPExcel_NamedRange + */ + public function setLocalOnly($value = false) { + $this->_localOnly = $value; + $this->_scope = $value ? $this->_worksheet : null; + return $this; + } + + /** + * Get scope + * + * @return PHPExcel_Worksheet|null + */ + public function getScope() { + return $this->_scope; + } + + /** + * Set scope + * + * @param PHPExcel_Worksheet|null $value + * @return PHPExcel_NamedRange + */ + public function setScope(PHPExcel_Worksheet $value = null) { + $this->_scope = $value; + $this->_localOnly = ($value == null) ? false : true; + return $this; + } + + /** + * Resolve a named range to a regular cell range + * + * @param string $pNamedRange Named range + * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope + * @return PHPExcel_NamedRange + */ + public static function resolveRange($pNamedRange = '', PHPExcel_Worksheet $pSheet) { + return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php new file mode 100644 index 00000000..0d5180c6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php @@ -0,0 +1,227 @@ +_readDataOnly; + } + + /** + * Set read data only + * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information. + * Set to false (the default) to advise the Reader to read both data and formatting for cells. + * + * @param boolean $pValue + * + * @return PHPExcel_Reader_IReader + */ + public function setReadDataOnly($pValue = FALSE) { + $this->_readDataOnly = $pValue; + return $this; + } + + /** + * Read charts in workbook? + * If this is true, then the Reader will include any charts that exist in the workbook. + * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. + * If false (the default) it will ignore any charts defined in the workbook file. + * + * @return boolean + */ + public function getIncludeCharts() { + return $this->_includeCharts; + } + + /** + * Set read charts in workbook + * Set to true, to advise the Reader to include any charts that exist in the workbook. + * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. + * Set to false (the default) to discard charts. + * + * @param boolean $pValue + * + * @return PHPExcel_Reader_IReader + */ + public function setIncludeCharts($pValue = FALSE) { + $this->_includeCharts = (boolean) $pValue; + return $this; + } + + /** + * Get which sheets to load + * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null + * indicating that all worksheets in the workbook should be loaded. + * + * @return mixed + */ + public function getLoadSheetsOnly() + { + return $this->_loadSheetsOnly; + } + + /** + * Set which sheets to load + * + * @param mixed $value + * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name. + * If NULL, then it tells the Reader to read all worksheets in the workbook + * + * @return PHPExcel_Reader_IReader + */ + public function setLoadSheetsOnly($value = NULL) + { + $this->_loadSheetsOnly = is_array($value) ? + $value : array($value); + return $this; + } + + /** + * Set all sheets to load + * Tells the Reader to load all worksheets from the workbook. + * + * @return PHPExcel_Reader_IReader + */ + public function setLoadAllSheets() + { + $this->_loadSheetsOnly = NULL; + return $this; + } + + /** + * Read filter + * + * @return PHPExcel_Reader_IReadFilter + */ + public function getReadFilter() { + return $this->_readFilter; + } + + /** + * Set read filter + * + * @param PHPExcel_Reader_IReadFilter $pValue + * @return PHPExcel_Reader_IReader + */ + public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) { + $this->_readFilter = $pValue; + return $this; + } + + /** + * Open file for reading + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + * @return resource + */ + protected function _openFile($pFilename) + { + // Check if file exists + if (!file_exists($pFilename) || !is_readable($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Open file + $this->_fileHandle = fopen($pFilename, 'r'); + if ($this->_fileHandle === FALSE) { + throw new PHPExcel_Reader_Exception("Could not open file " . $pFilename . " for reading."); + } + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + try { + $this->_openFile($pFilename); + } catch (Exception $e) { + return FALSE; + } + + $readable = $this->_isValidFormat(); + fclose ($this->_fileHandle); + return $readable; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php new file mode 100644 index 00000000..8bf7b848 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php @@ -0,0 +1,415 @@ +_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is a CSV file + * + * @return boolean + */ + protected function _isValidFormat() + { + return TRUE; + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'UTF-8') + { + $this->_inputEncoding = $pValue; + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->_inputEncoding; + } + + /** + * Move filepointer past any BOM marker + * + */ + protected function _skipBOM() + { + rewind($this->_fileHandle); + + switch ($this->_inputEncoding) { + case 'UTF-8': + fgets($this->_fileHandle, 4) == "\xEF\xBB\xBF" ? + fseek($this->_fileHandle, 3) : fseek($this->_fileHandle, 0); + break; + case 'UTF-16LE': + fgets($this->_fileHandle, 3) == "\xFF\xFE" ? + fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0); + break; + case 'UTF-16BE': + fgets($this->_fileHandle, 3) == "\xFE\xFF" ? + fseek($this->_fileHandle, 2) : fseek($this->_fileHandle, 0); + break; + case 'UTF-32LE': + fgets($this->_fileHandle, 5) == "\xFF\xFE\x00\x00" ? + fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0); + break; + case 'UTF-32BE': + fgets($this->_fileHandle, 5) == "\x00\x00\xFE\xFF" ? + fseek($this->_fileHandle, 4) : fseek($this->_fileHandle, 0); + break; + default: + break; + } + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Open file + $this->_openFile($pFilename); + if (!$this->_isValidFormat()) { + fclose ($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->_fileHandle; + + // Skip BOM, if any + $this->_skipBOM(); + + $escapeEnclosures = array( "\\" . $this->_enclosure, $this->_enclosure . $this->_enclosure ); + + $worksheetInfo = array(); + $worksheetInfo[0]['worksheetName'] = 'Worksheet'; + $worksheetInfo[0]['lastColumnLetter'] = 'A'; + $worksheetInfo[0]['lastColumnIndex'] = 0; + $worksheetInfo[0]['totalRows'] = 0; + $worksheetInfo[0]['totalColumns'] = 0; + + // Loop through each line of the file in turn + while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) { + $worksheetInfo[0]['totalRows']++; + $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); + } + + $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); + $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; + + // Close file + fclose($fileHandle); + + return $worksheetInfo; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + $lineEnding = ini_get('auto_detect_line_endings'); + ini_set('auto_detect_line_endings', true); + + // Open file + $this->_openFile($pFilename); + if (!$this->_isValidFormat()) { + fclose ($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->_fileHandle; + + // Skip BOM, if any + $this->_skipBOM(); + + // Create new PHPExcel object + while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { + $objPHPExcel->createSheet(); + } + $sheet = $objPHPExcel->setActiveSheetIndex($this->_sheetIndex); + + $escapeEnclosures = array( "\\" . $this->_enclosure, + $this->_enclosure . $this->_enclosure + ); + + // Set our starting row based on whether we're in contiguous mode or not + $currentRow = 1; + if ($this->_contiguous) { + $currentRow = ($this->_contiguousRow == -1) ? $sheet->getHighestRow(): $this->_contiguousRow; + } + + // Loop through each line of the file in turn + while (($rowData = fgetcsv($fileHandle, 0, $this->_delimiter, $this->_enclosure)) !== FALSE) { + $columnLetter = 'A'; + foreach($rowData as $rowDatum) { + if ($rowDatum != '' && $this->_readFilter->readCell($columnLetter, $currentRow)) { + // Unescape enclosures + $rowDatum = str_replace($escapeEnclosures, $this->_enclosure, $rowDatum); + + // Convert encoding if necessary + if ($this->_inputEncoding !== 'UTF-8') { + $rowDatum = PHPExcel_Shared_String::ConvertEncoding($rowDatum, 'UTF-8', $this->_inputEncoding); + } + + // Set cell value + $sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum); + } + ++$columnLetter; + } + ++$currentRow; + } + + // Close file + fclose($fileHandle); + + if ($this->_contiguous) { + $this->_contiguousRow = $currentRow; + } + + ini_set('auto_detect_line_endings', $lineEnding); + + // Return + return $objPHPExcel; + } + + /** + * Get delimiter + * + * @return string + */ + public function getDelimiter() { + return $this->_delimiter; + } + + /** + * Set delimiter + * + * @param string $pValue Delimiter, defaults to , + * @return PHPExcel_Reader_CSV + */ + public function setDelimiter($pValue = ',') { + $this->_delimiter = $pValue; + return $this; + } + + /** + * Get enclosure + * + * @return string + */ + public function getEnclosure() { + return $this->_enclosure; + } + + /** + * Set enclosure + * + * @param string $pValue Enclosure, defaults to " + * @return PHPExcel_Reader_CSV + */ + public function setEnclosure($pValue = '"') { + if ($pValue == '') { + $pValue = '"'; + } + $this->_enclosure = $pValue; + return $this; + } + + /** + * Get line ending + * + * @return string + */ + public function getLineEnding() { + return $this->_lineEnding; + } + + /** + * Set line ending + * + * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL) + * @return PHPExcel_Reader_CSV + */ + public function setLineEnding($pValue = PHP_EOL) { + $this->_lineEnding = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return integer + */ + public function getSheetIndex() { + return $this->_sheetIndex; + } + + /** + * Set sheet index + * + * @param integer $pValue Sheet index + * @return PHPExcel_Reader_CSV + */ + public function setSheetIndex($pValue = 0) { + $this->_sheetIndex = $pValue; + return $this; + } + + /** + * Set Contiguous + * + * @param boolean $contiguous + */ + public function setContiguous($contiguous = FALSE) + { + $this->_contiguous = (bool) $contiguous; + if (!$contiguous) { + $this->_contiguousRow = -1; + } + + return $this; + } + + /** + * Get Contiguous + * + * @return boolean + */ + public function getContiguous() { + return $this->_contiguous; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php new file mode 100644 index 00000000..228ed108 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php @@ -0,0 +1,58 @@ +_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + + // Office xmlns:o="urn:schemas-microsoft-com:office:office" + // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" + // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" + // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet" + // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" + // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" + // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset" + // Rowset xmlns:z="#RowsetSchema" + // + + $signature = array( + '' + ); + + // Open file + $this->_openFile($pFilename); + $fileHandle = $this->_fileHandle; + + // Read sample data (first 2 KB will do) + $data = fread($fileHandle, 2048); + fclose($fileHandle); + + $valid = true; + foreach($signature as $match) { + // every part of the signature must be present + if (strpos($data, $match) === false) { + $valid = false; + break; + } + } + + // Retrieve charset encoding + if(preg_match('//um',$data,$matches)) { + $this->_charSet = strtoupper($matches[1]); + } +// echo 'Character Set is ',$this->_charSet,'
'; + + return $valid; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + if (!$this->canRead($pFilename)) { + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + + $worksheetNames = array(); + + $xml = simplexml_load_file($pFilename, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $xml_ss = $xml->children($namespaces['ss']); + foreach($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + $worksheetNames[] = self::_convertStringEncoding((string) $worksheet_ss['Name'],$this->_charSet); + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $xml = simplexml_load_file($pFilename, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $worksheetID = 1; + $xml_ss = $xml->children($namespaces['ss']); + foreach($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + + $tmpInfo = array(); + $tmpInfo['worksheetName'] = ''; + $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['lastColumnIndex'] = 0; + $tmpInfo['totalRows'] = 0; + $tmpInfo['totalColumns'] = 0; + + if (isset($worksheet_ss['Name'])) { + $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; + } else { + $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; + } + + if (isset($worksheet->Table->Row)) { + $rowIndex = 0; + + foreach($worksheet->Table->Row as $rowData) { + $columnIndex = 0; + $rowHasData = false; + + foreach($rowData->Cell as $cell) { + if (isset($cell->Data)) { + $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); + $rowHasData = true; + } + + ++$columnIndex; + } + + ++$rowIndex; + + if ($rowHasData) { + $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); + } + } + } + + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; + + $worksheetInfo[] = $tmpInfo; + ++$worksheetID; + } + + return $worksheetInfo; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + + private static function identifyFixedStyleValue($styleList,&$styleAttributeValue) { + $styleAttributeValue = strtolower($styleAttributeValue); + foreach($styleList as $style) { + if ($styleAttributeValue == strtolower($style)) { + $styleAttributeValue = $style; + return true; + } + } + return false; + } + + + /** + * pixel units to excel width units(units of 1/256th of a character width) + * @param pxs + * @return + */ + private static function _pixel2WidthUnits($pxs) { + $UNIT_OFFSET_MAP = array(0, 36, 73, 109, 146, 182, 219); + + $widthUnits = 256 * ($pxs / 7); + $widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)]; + return $widthUnits; + } + + + /** + * excel width units(units of 1/256th of a character width) to pixel units + * @param widthUnits + * @return + */ + private static function _widthUnits2Pixel($widthUnits) { + $pixels = ($widthUnits / 256) * 7; + $offsetWidthUnits = $widthUnits % 256; + $pixels += round($offsetWidthUnits / (256 / 7)); + return $pixels; + } + + + private static function _hex2str($hex) { + return chr(hexdec($hex[1])); + } + + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + $fromFormats = array('\-', '\ '); + $toFormats = array('-', ' '); + + $underlineStyles = array ( + PHPExcel_Style_Font::UNDERLINE_NONE, + PHPExcel_Style_Font::UNDERLINE_DOUBLE, + PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING, + PHPExcel_Style_Font::UNDERLINE_SINGLE, + PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING + ); + $verticalAlignmentStyles = array ( + PHPExcel_Style_Alignment::VERTICAL_BOTTOM, + PHPExcel_Style_Alignment::VERTICAL_TOP, + PHPExcel_Style_Alignment::VERTICAL_CENTER, + PHPExcel_Style_Alignment::VERTICAL_JUSTIFY + ); + $horizontalAlignmentStyles = array ( + PHPExcel_Style_Alignment::HORIZONTAL_GENERAL, + PHPExcel_Style_Alignment::HORIZONTAL_LEFT, + PHPExcel_Style_Alignment::HORIZONTAL_RIGHT, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS, + PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY + ); + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + if (!$this->canRead($pFilename)) { + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + + $xml = simplexml_load_file($pFilename, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $docProps = $objPHPExcel->getProperties(); + if (isset($xml->DocumentProperties[0])) { + foreach($xml->DocumentProperties[0] as $propertyName => $propertyValue) { + switch ($propertyName) { + case 'Title' : + $docProps->setTitle(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Subject' : + $docProps->setSubject(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Author' : + $docProps->setCreator(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Created' : + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + break; + case 'LastAuthor' : + $docProps->setLastModifiedBy(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'LastSaved' : + $lastSaveDate = strtotime($propertyValue); + $docProps->setModified($lastSaveDate); + break; + case 'Company' : + $docProps->setCompany(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Category' : + $docProps->setCategory(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Manager' : + $docProps->setManager(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Keywords' : + $docProps->setKeywords(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + case 'Description' : + $docProps->setDescription(self::_convertStringEncoding($propertyValue,$this->_charSet)); + break; + } + } + } + if (isset($xml->CustomDocumentProperties)) { + foreach($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { + $propertyAttributes = $propertyValue->attributes($namespaces['dt']); + $propertyName = preg_replace_callback('/_x([0-9a-z]{4})_/','PHPExcel_Reader_Excel2003XML::_hex2str',$propertyName); + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_UNKNOWN; + switch((string) $propertyAttributes) { + case 'string' : + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + $propertyValue = trim($propertyValue); + break; + case 'boolean' : + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN; + $propertyValue = (bool) $propertyValue; + break; + case 'integer' : + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_INTEGER; + $propertyValue = intval($propertyValue); + break; + case 'float' : + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT; + $propertyValue = floatval($propertyValue); + break; + case 'dateTime.tz' : + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE; + $propertyValue = strtotime(trim($propertyValue)); + break; + } + $docProps->setCustomProperty($propertyName,$propertyValue,$propertyType); + } + } + + foreach($xml->Styles[0] as $style) { + $style_ss = $style->attributes($namespaces['ss']); + $styleID = (string) $style_ss['ID']; +// echo 'Style ID = '.$styleID.'
'; + if ($styleID == 'Default') { + $this->_styles['Default'] = array(); + } else { + $this->_styles[$styleID] = $this->_styles['Default']; + } + foreach ($style as $styleType => $styleData) { + $styleAttributes = $styleData->attributes($namespaces['ss']); +// echo $styleType.'
'; + switch ($styleType) { + case 'Alignment' : + foreach($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'Vertical' : + if (self::identifyFixedStyleValue($verticalAlignmentStyles,$styleAttributeValue)) { + $this->_styles[$styleID]['alignment']['vertical'] = $styleAttributeValue; + } + break; + case 'Horizontal' : + if (self::identifyFixedStyleValue($horizontalAlignmentStyles,$styleAttributeValue)) { + $this->_styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue; + } + break; + case 'WrapText' : + $this->_styles[$styleID]['alignment']['wrap'] = true; + break; + } + } + break; + case 'Borders' : + foreach($styleData->Border as $borderStyle) { + $borderAttributes = $borderStyle->attributes($namespaces['ss']); + $thisBorder = array(); + foreach($borderAttributes as $borderStyleKey => $borderStyleValue) { +// echo $borderStyleKey.' = '.$borderStyleValue.'
'; + switch ($borderStyleKey) { + case 'LineStyle' : + $thisBorder['style'] = PHPExcel_Style_Border::BORDER_MEDIUM; +// $thisBorder['style'] = $borderStyleValue; + break; + case 'Weight' : +// $thisBorder['style'] = $borderStyleValue; + break; + case 'Position' : + $borderPosition = strtolower($borderStyleValue); + break; + case 'Color' : + $borderColour = substr($borderStyleValue,1); + $thisBorder['color']['rgb'] = $borderColour; + break; + } + } + if (!empty($thisBorder)) { + if (($borderPosition == 'left') || ($borderPosition == 'right') || ($borderPosition == 'top') || ($borderPosition == 'bottom')) { + $this->_styles[$styleID]['borders'][$borderPosition] = $thisBorder; + } + } + } + break; + case 'Font' : + foreach($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'FontName' : + $this->_styles[$styleID]['font']['name'] = $styleAttributeValue; + break; + case 'Size' : + $this->_styles[$styleID]['font']['size'] = $styleAttributeValue; + break; + case 'Color' : + $this->_styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue,1); + break; + case 'Bold' : + $this->_styles[$styleID]['font']['bold'] = true; + break; + case 'Italic' : + $this->_styles[$styleID]['font']['italic'] = true; + break; + case 'Underline' : + if (self::identifyFixedStyleValue($underlineStyles,$styleAttributeValue)) { + $this->_styles[$styleID]['font']['underline'] = $styleAttributeValue; + } + break; + } + } + break; + case 'Interior' : + foreach($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + switch ($styleAttributeKey) { + case 'Color' : + $this->_styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue,1); + break; + } + } + break; + case 'NumberFormat' : + foreach($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + $styleAttributeValue = str_replace($fromFormats,$toFormats,$styleAttributeValue); + switch ($styleAttributeValue) { + case 'Short Date' : + $styleAttributeValue = 'dd/mm/yyyy'; + break; + } + if ($styleAttributeValue > '') { + $this->_styles[$styleID]['numberformat']['code'] = $styleAttributeValue; + } + } + break; + case 'Protection' : + foreach($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'
'; + } + break; + } + } +// print_r($this->_styles[$styleID]); +// echo '
'; + } +// echo '
'; + + $worksheetID = 0; + $xml_ss = $xml->children($namespaces['ss']); + + foreach($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + + if ((isset($this->_loadSheetsOnly)) && (isset($worksheet_ss['Name'])) && + (!in_array($worksheet_ss['Name'], $this->_loadSheetsOnly))) { + continue; + } + +// echo '

Worksheet: ',$worksheet_ss['Name'],'

'; +// + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + if (isset($worksheet_ss['Name'])) { + $worksheetName = self::_convertStringEncoding((string) $worksheet_ss['Name'],$this->_charSet); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in + // formula cells... during the load, all formulae should be correct, and we're simply bringing + // the worksheet name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName,false); + } + + $columnID = 'A'; + if (isset($worksheet->Table->Column)) { + foreach($worksheet->Table->Column as $columnData) { + $columnData_ss = $columnData->attributes($namespaces['ss']); + if (isset($columnData_ss['Index'])) { + $columnID = PHPExcel_Cell::stringFromColumnIndex($columnData_ss['Index']-1); + } + if (isset($columnData_ss['Width'])) { + $columnWidth = $columnData_ss['Width']; +// echo 'Setting column width for '.$columnID.' to '.$columnWidth.'
'; + $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4); + } + ++$columnID; + } + } + + $rowID = 1; + if (isset($worksheet->Table->Row)) { + foreach($worksheet->Table->Row as $rowData) { + $rowHasData = false; + $row_ss = $rowData->attributes($namespaces['ss']); + if (isset($row_ss['Index'])) { + $rowID = (integer) $row_ss['Index']; + } +// echo 'Row '.$rowID.'
'; + + $columnID = 'A'; + foreach($rowData->Cell as $cell) { + + $cell_ss = $cell->attributes($namespaces['ss']); + if (isset($cell_ss['Index'])) { + $columnID = PHPExcel_Cell::stringFromColumnIndex($cell_ss['Index']-1); + } + $cellRange = $columnID.$rowID; + + if ($this->getReadFilter() !== NULL) { + if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { + continue; + } + } + + if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { + $columnTo = $columnID; + if (isset($cell_ss['MergeAcross'])) { + $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1); + } + $rowTo = $rowID; + if (isset($cell_ss['MergeDown'])) { + $rowTo = $rowTo + $cell_ss['MergeDown']; + } + $cellRange .= ':'.$columnTo.$rowTo; + $objPHPExcel->getActiveSheet()->mergeCells($cellRange); + } + + $cellIsSet = $hasCalculatedValue = false; + $cellDataFormula = ''; + if (isset($cell_ss['Formula'])) { + $cellDataFormula = $cell_ss['Formula']; + // added this as a check for array formulas + if (isset($cell_ss['ArrayRange'])) { + $cellDataCSEFormula = $cell_ss['ArrayRange']; +// echo "found an array formula at ".$columnID.$rowID."
"; + } + $hasCalculatedValue = true; + } + if (isset($cell->Data)) { + $cellValue = $cellData = $cell->Data; + $type = PHPExcel_Cell_DataType::TYPE_NULL; + $cellData_ss = $cellData->attributes($namespaces['ss']); + if (isset($cellData_ss['Type'])) { + $cellDataType = $cellData_ss['Type']; + switch ($cellDataType) { + /* + const TYPE_STRING = 's'; + const TYPE_FORMULA = 'f'; + const TYPE_NUMERIC = 'n'; + const TYPE_BOOL = 'b'; + const TYPE_NULL = 'null'; + const TYPE_INLINE = 'inlineStr'; + const TYPE_ERROR = 'e'; + */ + case 'String' : + $cellValue = self::_convertStringEncoding($cellValue,$this->_charSet); + $type = PHPExcel_Cell_DataType::TYPE_STRING; + break; + case 'Number' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $cellValue = (float) $cellValue; + if (floor($cellValue) == $cellValue) { + $cellValue = (integer) $cellValue; + } + break; + case 'Boolean' : + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $cellValue = ($cellValue != 0); + break; + case 'DateTime' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $cellValue = PHPExcel_Shared_Date::PHPToExcel(strtotime($cellValue)); + break; + case 'Error' : + $type = PHPExcel_Cell_DataType::TYPE_ERROR; + break; + } + } + + if ($hasCalculatedValue) { +// echo 'FORMULA
'; + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + $columnNumber = PHPExcel_Cell::columnIndexFromString($columnID); + if (substr($cellDataFormula,0,3) == 'of:') { + $cellDataFormula = substr($cellDataFormula,3); +// echo 'Before: ',$cellDataFormula,'
'; + $temp = explode('"',$cellDataFormula); + $key = false; + foreach($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + $value = str_replace(array('[.','.',']'),'',$value); + } + } + } else { + // Convert R1C1 style references to A1 style references (but only when not quoted) +// echo 'Before: ',$cellDataFormula,'
'; + $temp = explode('"',$cellDataFormula); + $key = false; + foreach($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach($cellReferences as $cellReference) { + $rowReference = $cellReference[2][0]; + // Empty R reference is the current row + if ($rowReference == '') $rowReference = $rowID; + // Bracketed R references are relative to the current row + if ($rowReference{0} == '[') $rowReference = $rowID + trim($rowReference,'[]'); + $columnReference = $cellReference[4][0]; + // Empty C reference is the current column + if ($columnReference == '') $columnReference = $columnNumber; + // Bracketed C references are relative to the current column + if ($columnReference{0} == '[') $columnReference = $columnNumber + trim($columnReference,'[]'); + $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; + $value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0])); + } + } + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"',$temp); +// echo 'After: ',$cellDataFormula,'
'; + } + +// echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'
'; +// + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue),$type); + if ($hasCalculatedValue) { +// echo 'Formula result is '.$cellValue.'
'; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue); + } + $cellIsSet = $rowHasData = true; + } + + if (isset($cell->Comment)) { +// echo 'comment found
'; + $commentAttributes = $cell->Comment->attributes($namespaces['ss']); + $author = 'unknown'; + if (isset($commentAttributes->Author)) { + $author = (string)$commentAttributes->Author; +// echo 'Author: ',$author,'
'; + } + $node = $cell->Comment->Data->asXML(); +// $annotation = str_replace('html:','',substr($node,49,-10)); +// echo $annotation,'
'; + $annotation = strip_tags($node); +// echo 'Annotation: ',$annotation,'
'; + $objPHPExcel->getActiveSheet()->getComment( $columnID.$rowID ) + ->setAuthor(self::_convertStringEncoding($author ,$this->_charSet)) + ->setText($this->_parseRichText($annotation) ); + } + + if (($cellIsSet) && (isset($cell_ss['StyleID']))) { + $style = (string) $cell_ss['StyleID']; +// echo 'Cell style for '.$columnID.$rowID.' is '.$style.'
'; + if ((isset($this->_styles[$style])) && (!empty($this->_styles[$style]))) { +// echo 'Cell '.$columnID.$rowID.'
'; +// print_r($this->_styles[$style]); +// echo '
'; + if (!$objPHPExcel->getActiveSheet()->cellExists($columnID.$rowID)) { + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValue(NULL); + } + $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->_styles[$style]); + } + } + ++$columnID; + } + + if ($rowHasData) { + if (isset($row_ss['StyleID'])) { + $rowStyle = $row_ss['StyleID']; + } + if (isset($row_ss['Height'])) { + $rowHeight = $row_ss['Height']; +// echo 'Setting row height to '.$rowHeight.'
'; + $objPHPExcel->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight); + } + } + + ++$rowID; + } + } + ++$worksheetID; + } + + // Return + return $objPHPExcel; + } + + + private static function _convertStringEncoding($string,$charset) { + if ($charset != 'UTF-8') { + return PHPExcel_Shared_String::ConvertEncoding($string,'UTF-8',$charset); + } + return $string; + } + + + private function _parseRichText($is = '') { + $value = new PHPExcel_RichText(); + + $value->createText(self::_convertStringEncoding($is,$this->_charSet)); + + return $value; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php new file mode 100644 index 00000000..d8344ac7 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php @@ -0,0 +1,2069 @@ +_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + $this->_referenceHelper = PHPExcel_ReferenceHelper::getInstance(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + // Check if zip class exists +// if (!class_exists($zipClass, FALSE)) { +// throw new PHPExcel_Reader_Exception($zipClass . " library is not enabled"); +// } + + $xl = false; + // Load file + $zip = new $zipClass; + if ($zip->open($pFilename) === true) { + // check if it is an OOXML archive + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if ($rels !== false) { + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + if (basename($rel["Target"]) == 'workbook.xml') { + $xl = true; + } + break; + + } + } + } + $zip->close(); + } + + return $xl; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetNames = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader + $rels = simplexml_load_string( + $this->_getFromZipArchive($zip, "_rels/.rels", 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()) + ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $xmlWorkbook = simplexml_load_string( + $this->_getFromZipArchive($zip, "{$rel['Target']}", 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()) + ); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + // Check if sheet should be skipped + $worksheetNames[] = (string) $eleSheet["name"]; + } + } + } + } + + $zip->close(); + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $worksheets = array(); + foreach ($relsWorkbook->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + } + } + + $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if ($xmlWorkbook->sheets) { + $dir = dirname($rel["Target"]); + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + $tmpInfo = array( + 'worksheetName' => (string) $eleSheet["name"], + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + + $xml = new XMLReader(); + $res = $xml->open('zip://'.PHPExcel_Shared_File::realpath($pFilename).'#'."$dir/$fileWorksheet", null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2,true); + + $currCells = 0; + while ($xml->read()) { + if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { + $row = $xml->getAttribute('r'); + $tmpInfo['totalRows'] = $row; + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $currCells = 0; + } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { + $currCells++; + } + } + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $xml->close(); + + $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + + $worksheetInfo[] = $tmpInfo; + } + } + } + } + + $zip->close(); + + return $worksheetInfo; + } + + + private static function _castToBool($c) { +// echo 'Initial Cast to Boolean', PHP_EOL; + $value = isset($c->v) ? (string) $c->v : NULL; + if ($value == '0') { + return FALSE; + } elseif ($value == '1') { + return TRUE; + } else { + return (bool)$c->v; + } + return $value; + } // function _castToBool() + + + private static function _castToError($c) { +// echo 'Initial Cast to Error', PHP_EOL; + return isset($c->v) ? (string) $c->v : NULL; + } // function _castToError() + + + private static function _castToString($c) { +// echo 'Initial Cast to String, PHP_EOL; + return isset($c->v) ? (string) $c->v : NULL; + } // function _castToString() + + + private function _castToFormula($c,$r,&$cellDataType,&$value,&$calculatedValue,&$sharedFormulas,$castBaseType) { +// echo 'Formula', PHP_EOL; +// echo '$c->f is ', $c->f, PHP_EOL; + $cellDataType = 'f'; + $value = "={$c->f}"; + $calculatedValue = self::$castBaseType($c); + + // Shared formula? + if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') { +// echo 'SHARED FORMULA', PHP_EOL; + $instance = (string)$c->f['si']; + +// echo 'Instance ID = ', $instance, PHP_EOL; +// +// echo 'Shared Formula Array:', PHP_EOL; +// print_r($sharedFormulas); + if (!isset($sharedFormulas[(string)$c->f['si']])) { +// echo 'SETTING NEW SHARED FORMULA', PHP_EOL; +// echo 'Master is ', $r, PHP_EOL; +// echo 'Formula is ', $value, PHP_EOL; + $sharedFormulas[$instance] = array( 'master' => $r, + 'formula' => $value + ); +// echo 'New Shared Formula Array:', PHP_EOL; +// print_r($sharedFormulas); + } else { +// echo 'GETTING SHARED FORMULA', PHP_EOL; +// echo 'Master is ', $sharedFormulas[$instance]['master'], PHP_EOL; +// echo 'Formula is ', $sharedFormulas[$instance]['formula'], PHP_EOL; + $master = PHPExcel_Cell::coordinateFromString($sharedFormulas[$instance]['master']); + $current = PHPExcel_Cell::coordinateFromString($r); + + $difference = array(0, 0); + $difference[0] = PHPExcel_Cell::columnIndexFromString($current[0]) - PHPExcel_Cell::columnIndexFromString($master[0]); + $difference[1] = $current[1] - $master[1]; + + $value = $this->_referenceHelper->updateFormulaReferences( $sharedFormulas[$instance]['formula'], + 'A1', + $difference[0], + $difference[1] + ); +// echo 'Adjusted Formula is ', $value, PHP_EOL; + } + } + } + + + public function _getFromZipArchive($archive, $fileName = '') + { + // Root-relative paths + if (strpos($fileName, '//') !== false) + { + $fileName = substr($fileName, strpos($fileName, '//') + 1); + } + $fileName = PHPExcel_Shared_File::realpath($fileName); + + // Apache POI fixes + $contents = $archive->getFromName($fileName); + if ($contents === false) + { + $contents = $archive->getFromName(substr($fileName, 1)); + } + + return $contents; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Initialisations + $excel = new PHPExcel; + $excel->removeSheetByIndex(0); + if (!$this->_readDataOnly) { + $excel->removeCellStyleXfByIndex(0); // remove the default style + $excel->removeCellXfByIndex(0); // remove the default style + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // Read the theme first, because we need the colour scheme when reading the styles + $wbRels = simplexml_load_string($this->_getFromZipArchive($zip, "xl/_rels/workbook.xml.rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($wbRels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme": + $themeOrderArray = array('lt1','dk1','lt2','dk2'); + $themeOrderAdditional = count($themeOrderArray); + + $xmlTheme = simplexml_load_string($this->_getFromZipArchive($zip, "xl/{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlTheme)) { + $xmlThemeName = $xmlTheme->attributes(); + $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + $themeName = (string)$xmlThemeName['name']; + + $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); + $colourSchemeName = (string)$colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + + $themeColours = array(); + foreach ($colourScheme as $k => $xmlColour) { + $themePos = array_search($k,$themeOrderArray); + if ($themePos === false) { + $themePos = $themeOrderAdditional++; + } + if (isset($xmlColour->sysClr)) { + $xmlColourData = $xmlColour->sysClr->attributes(); + $themeColours[$themePos] = $xmlColourData['lastClr']; + } elseif (isset($xmlColour->srgbClr)) { + $xmlColourData = $xmlColour->srgbClr->attributes(); + $themeColours[$themePos] = $xmlColourData['val']; + } + } + self::$_theme = new PHPExcel_Reader_Excel2007_Theme($themeName,$colourSchemeName,$themeColours); + } + break; + } + } + + $rels = simplexml_load_string($this->_getFromZipArchive($zip, "_rels/.rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); + $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); + $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + $docProps = $excel->getProperties(); + $docProps->setCreator((string) self::array_item($xmlCore->xpath("dc:creator"))); + $docProps->setLastModifiedBy((string) self::array_item($xmlCore->xpath("cp:lastModifiedBy"))); + $docProps->setCreated(strtotime(self::array_item($xmlCore->xpath("dcterms:created")))); //! respect xsi:type + $docProps->setModified(strtotime(self::array_item($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type + $docProps->setTitle((string) self::array_item($xmlCore->xpath("dc:title"))); + $docProps->setDescription((string) self::array_item($xmlCore->xpath("dc:description"))); + $docProps->setSubject((string) self::array_item($xmlCore->xpath("dc:subject"))); + $docProps->setKeywords((string) self::array_item($xmlCore->xpath("cp:keywords"))); + $docProps->setCategory((string) self::array_item($xmlCore->xpath("cp:category"))); + } + break; + + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + if (isset($xmlCore->Company)) + $docProps->setCompany((string) $xmlCore->Company); + if (isset($xmlCore->Manager)) + $docProps->setManager((string) $xmlCore->Manager); + } + break; + + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties": + $xmlCore = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + foreach ($xmlCore as $xmlProperty) { + $cellDataOfficeAttributes = $xmlProperty->attributes(); + if (isset($cellDataOfficeAttributes['name'])) { + $propertyName = (string) $cellDataOfficeAttributes['name']; + $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + $attributeType = $cellDataOfficeChildren->getName(); + $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; + $attributeValue = PHPExcel_DocumentProperties::convertProperty($attributeValue,$attributeType); + $attributeType = PHPExcel_DocumentProperties::convertPropertyType($attributeType); + $docProps->setCustomProperty($propertyName,$attributeValue,$attributeType); + } + } + } + break; + //Ribbon + case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility": + $customUI = $rel['Target']; + if(!is_null($customUI)){ + $this->_readRibbon($excel, $customUI, $zip); + } + break; + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $sharedStrings = array(); + $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); + $xmlStrings = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if (isset($xmlStrings) && isset($xmlStrings->si)) { + foreach ($xmlStrings->si as $val) { + if (isset($val->t)) { + $sharedStrings[] = PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $val->t ); + } elseif (isset($val->r)) { + $sharedStrings[] = $this->_parseRichText($val); + } + } + } + + $worksheets = array(); + $macros = $customUI = NULL; + foreach ($relsWorkbook->Relationship as $ele) { + switch($ele['Type']){ + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet": + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + break; + // a vbaProject ? (: some macros) + case "http://schemas.microsoft.com/office/2006/relationships/vbaProject": + $macros = $ele["Target"]; + break; + } + } + + if(!is_null($macros)){ + $macrosCode = $this->_getFromZipArchive($zip, 'xl/vbaProject.bin');//vbaProject.bin always in 'xl' dir and always named vbaProject.bin + if($macrosCode !== false){ + $excel->setMacrosCode($macrosCode); + $excel->setHasMacros(true); + //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir + $Certificate = $this->_getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); + if($Certificate !== false) + $excel->setMacrosCertificate($Certificate); + } + } + $styles = array(); + $cellStyles = array(); + $xpath = self::array_item($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xmlStyles = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$xpath[Target]"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $numFmts = null; + if ($xmlStyles && $xmlStyles->numFmts[0]) { + $numFmts = $xmlStyles->numFmts[0]; + } + if (isset($numFmts) && ($numFmts !== NULL)) { + $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + } + if (!$this->_readDataOnly && $xmlStyles) { + foreach ($xmlStyles->cellXfs->xf as $xf) { + $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + + if ($xf["numFmtId"]) { + if (isset($numFmts)) { + $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } + } + + if ((int)$xf["numFmtId"] < 164) { + $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + $quotePrefix = false; + if (isset($xf["quotePrefix"])) { + $quotePrefix = (boolean) $xf["quotePrefix"]; + } + //$numFmt = str_replace('mm', 'i', $numFmt); + //$numFmt = str_replace('h', 'H', $numFmt); + + $style = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $styles[] = $style; + + // add style to cellXf collection + $objStyle = new PHPExcel_Style; + self::_readStyle($objStyle, $style); + $excel->addCellXf($objStyle); + } + + foreach ($xmlStyles->cellStyleXfs->xf as $xf) { + $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + if ($numFmts && $xf["numFmtId"]) { + $tmpNumFmt = self::array_item($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } else if ((int)$xf["numFmtId"] < 165) { + $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + + $cellStyle = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $cellStyles[] = $cellStyle; + + // add style to cellStyleXf collection + $objStyle = new PHPExcel_Style; + self::_readStyle($objStyle, $cellStyle); + $excel->addCellStyleXf($objStyle); + } + } + + $dxfs = array(); + if (!$this->_readDataOnly && $xmlStyles) { + // Conditional Styles + if ($xmlStyles->dxfs) { + foreach ($xmlStyles->dxfs->dxf as $dxf) { + $style = new PHPExcel_Style(FALSE, TRUE); + self::_readStyle($style, $dxf); + $dxfs[] = $style; + } + } + // Cell Styles + if ($xmlStyles->cellStyles) { + foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) { + if (intval($cellStyle['builtinId']) == 0) { + if (isset($cellStyles[intval($cellStyle['xfId'])])) { + // Set default style + $style = new PHPExcel_Style; + self::_readStyle($style, $cellStyles[intval($cellStyle['xfId'])]); + + // normal style, currently not using it for anything + } + } + } + } + } + + $xmlWorkbook = simplexml_load_string($this->_getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + // Set base date + if ($xmlWorkbook->workbookPr) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900); + if (isset($xmlWorkbook->workbookPr['date1904'])) { + if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904); + } + } + } + + $sheetId = 0; // keep track of new sheet id in final workbook + $oldSheetId = -1; // keep track of old sheet id in final workbook + $countSkippedSheets = 0; // keep track of number of skipped sheets + $mapSheetId = array(); // mapping of sheet ids from old to new + + + $charts = $chartDetails = array(); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + ++$oldSheetId; + + // Check if sheet should be skipped + if (isset($this->_loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->_loadSheetsOnly)) { + ++$countSkippedSheets; + $mapSheetId[$oldSheetId] = null; + continue; + } + + // Map old sheet id in original workbook to new sheet id. + // They will differ if loadSheetsOnly() is being used + $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; + + // Load sheet + $docSheet = $excel->createSheet(); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet + // references in formula cells... during the load, all formulae should be correct, + // and we're simply bringing the worksheet name in line with the formula, not the + // reverse + $docSheet->setTitle((string) $eleSheet["name"],false); + $fileWorksheet = $worksheets[(string) self::array_item($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $xmlSheet = simplexml_load_string($this->_getFromZipArchive($zip, "$dir/$fileWorksheet"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + $sharedFormulas = array(); + + if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') { + $docSheet->setSheetState( (string) $eleSheet["state"] ); + } + + if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) { + if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) { + $docSheet->getSheetView()->setZoomScale( intval($xmlSheet->sheetViews->sheetView['zoomScale']) ); + } + + if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) { + $docSheet->getSheetView()->setZoomScaleNormal( intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal']) ); + } + + if (isset($xmlSheet->sheetViews->sheetView['view'])) { + $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']); + } + + if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) { + $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines'])); + } + + if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) { + $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'])); + } + + if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) { + $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft'])); + } + + if (isset($xmlSheet->sheetViews->sheetView->pane)) { + if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) { + $docSheet->freezePane( (string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell'] ); + } else { + $xSplit = 0; + $ySplit = 0; + + if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) { + $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']); + } + + if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) { + $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']); + } + + $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit); + } + } + + if (isset($xmlSheet->sheetViews->sheetView->selection)) { + if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) { + $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref']; + $sqref = explode(' ', $sqref); + $sqref = $sqref[0]; + $docSheet->setSelectedCells($sqref); + } + } + + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) { + if (isset($xmlSheet->sheetPr->tabColor['rgb'])) { + $docSheet->getTabColor()->setARGB( (string)$xmlSheet->sheetPr->tabColor['rgb'] ); + } + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) { + $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName']); + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) { + if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) { + $docSheet->setShowSummaryRight(FALSE); + } else { + $docSheet->setShowSummaryRight(TRUE); + } + + if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) { + $docSheet->setShowSummaryBelow(FALSE); + } else { + $docSheet->setShowSummaryBelow(TRUE); + } + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) { + if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && + !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) { + $docSheet->getPageSetup()->setFitToPage(FALSE); + } else { + $docSheet->getPageSetup()->setFitToPage(TRUE); + } + } + + if (isset($xmlSheet->sheetFormatPr)) { + if (isset($xmlSheet->sheetFormatPr['customHeight']) && + self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) && + isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) { + $docSheet->getDefaultRowDimension()->setRowHeight( (float)$xmlSheet->sheetFormatPr['defaultRowHeight'] ); + } + if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) { + $docSheet->getDefaultColumnDimension()->setWidth( (float)$xmlSheet->sheetFormatPr['defaultColWidth'] ); + } + if (isset($xmlSheet->sheetFormatPr['zeroHeight']) && + ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { + $docSheet->getDefaultRowDimension()->setzeroHeight(true); + } + } + + if (isset($xmlSheet->cols) && !$this->_readDataOnly) { + foreach ($xmlSheet->cols->col as $col) { + for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) { + if ($col["style"] && !$this->_readDataOnly) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"])); + } + if (self::boolean($col["bestFit"])) { + //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(TRUE); + } + if (self::boolean($col["hidden"])) { + // echo PHPExcel_Cell::stringFromColumnIndex($i),': HIDDEN COLUMN',PHP_EOL; + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setVisible(FALSE); + } + if (self::boolean($col["collapsed"])) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setCollapsed(TRUE); + } + if ($col["outlineLevel"] > 0) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"])); + } + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"])); + + if (intval($col["max"]) == 16384) { + break; + } + } + } + } + + if (isset($xmlSheet->printOptions) && !$this->_readDataOnly) { + if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) { + $docSheet->setShowGridlines(TRUE); + } + + if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) { + $docSheet->setPrintGridlines(TRUE); + } + + if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) { + $docSheet->getPageSetup()->setHorizontalCentered(TRUE); + } + if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) { + $docSheet->getPageSetup()->setVerticalCentered(TRUE); + } + } + + if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { + foreach ($xmlSheet->sheetData->row as $row) { + if ($row["ht"] && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"])); + } + if (self::boolean($row["hidden"]) && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setVisible(FALSE); + } + if (self::boolean($row["collapsed"])) { + $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(TRUE); + } + if ($row["outlineLevel"] > 0) { + $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"])); + } + if ($row["s"] && !$this->_readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"])); + } + + foreach ($row->c as $c) { + $r = (string) $c["r"]; + $cellDataType = (string) $c["t"]; + $value = null; + $calculatedValue = null; + + // Read cell? + if ($this->getReadFilter() !== NULL) { + $coordinates = PHPExcel_Cell::coordinateFromString($r); + + if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) { + continue; + } + } + + // echo 'Reading cell ', $coordinates[0], $coordinates[1], PHP_EOL; + // print_r($c); + // echo PHP_EOL; + // echo 'Cell Data Type is ', $cellDataType, ': '; + // + // Read cell! + switch ($cellDataType) { + case "s": + // echo 'String', PHP_EOL; + if ((string)$c->v != '') { + $value = $sharedStrings[intval($c->v)]; + + if ($value instanceof PHPExcel_RichText) { + $value = clone $value; + } + } else { + $value = ''; + } + + break; + case "b": + // echo 'Boolean', PHP_EOL; + if (!isset($c->f)) { + $value = self::_castToBool($c); + } else { + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToBool'); + if (isset($c->f['t'])) { + $att = array(); + $att = $c->f; + $docSheet->getCell($r)->setFormulaAttributes($att); + } + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + break; + case "inlineStr": + // echo 'Inline String', PHP_EOL; + $value = $this->_parseRichText($c->is); + + break; + case "e": + // echo 'Error', PHP_EOL; + if (!isset($c->f)) { + $value = self::_castToError($c); + } else { + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToError'); + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + + break; + + default: + // echo 'Default', PHP_EOL; + if (!isset($c->f)) { + // echo 'Not a Formula', PHP_EOL; + $value = self::_castToString($c); + } else { + // echo 'Treat as Formula', PHP_EOL; + // Formula + $this->_castToFormula($c,$r,$cellDataType,$value,$calculatedValue,$sharedFormulas,'_castToString'); + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + + break; + } + // echo 'Value is ', $value, PHP_EOL; + + // Check for numeric values + if (is_numeric($value) && $cellDataType != 's') { + if ($value == (int)$value) $value = (int)$value; + elseif ($value == (float)$value) $value = (float)$value; + elseif ($value == (double)$value) $value = (double)$value; + } + + // Rich text? + if ($value instanceof PHPExcel_RichText && $this->_readDataOnly) { + $value = $value->getPlainText(); + } + + $cell = $docSheet->getCell($r); + // Assign value + if ($cellDataType != '') { + $cell->setValueExplicit($value, $cellDataType); + } else { + $cell->setValue($value); + } + if ($calculatedValue !== NULL) { + $cell->setCalculatedValue($calculatedValue); + } + + // Style information? + if ($c["s"] && !$this->_readDataOnly) { + // no style index means 0, it seems + $cell->setXfIndex(isset($styles[intval($c["s"])]) ? + intval($c["s"]) : 0); + } + } + } + } + + $conditionals = array(); + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { + foreach ($xmlSheet->conditionalFormatting as $conditional) { + foreach ($conditional->cfRule as $cfRule) { + if ( + ( + (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE || + (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS || + (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT || + (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION + ) && isset($dxfs[intval($cfRule["dxfId"])]) + ) { + $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule; + } + } + } + + foreach ($conditionals as $ref => $cfRules) { + ksort($cfRules); + $conditionalStyles = array(); + foreach ($cfRules as $cfRule) { + $objConditional = new PHPExcel_Style_Conditional(); + $objConditional->setConditionType((string)$cfRule["type"]); + $objConditional->setOperatorType((string)$cfRule["operator"]); + + if ((string)$cfRule["text"] != '') { + $objConditional->setText((string)$cfRule["text"]); + } + + if (count($cfRule->formula) > 1) { + foreach ($cfRule->formula as $formula) { + $objConditional->addCondition((string)$formula); + } + } else { + $objConditional->addCondition((string)$cfRule->formula); + } + $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]); + $conditionalStyles[] = $objConditional; + } + + // Extract all cell references in $ref + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($ref); + foreach ($aReferences as $reference) { + $docSheet->getStyle($reference)->setConditionalStyles($conditionalStyles); + } + } + } + + $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells"); + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + foreach ($aKeys as $key) { + $method = "set" . ucfirst($key); + $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key])); + } + } + + if (!$this->_readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], TRUE); + if ($xmlSheet->protectedRanges->protectedRange) { + foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { + $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true); + } + } + } + + if ($xmlSheet && $xmlSheet->autoFilter && !$this->_readDataOnly) { + $autoFilter = $docSheet->getAutoFilter(); + $autoFilter->setRange((string) $xmlSheet->autoFilter["ref"]); + foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) { + $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]); + // Check for standard filters + if ($filterColumn->filters) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER); + $filters = $filterColumn->filters; + if ((isset($filters["blank"])) && ($filters["blank"] == 1)) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + '' + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Standard filters are always an OR join, so no join rule needs to be set + // Entries can be either filter elements + foreach ($filters->filter as $filterRule) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + (string) $filterRule["val"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Or Date Group elements + foreach ($filters->dateGroupItem as $dateGroupItem) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + array( + 'year' => (string) $dateGroupItem["year"], + 'month' => (string) $dateGroupItem["month"], + 'day' => (string) $dateGroupItem["day"], + 'hour' => (string) $dateGroupItem["hour"], + 'minute' => (string) $dateGroupItem["minute"], + 'second' => (string) $dateGroupItem["second"], + ), + (string) $dateGroupItem["dateTimeGrouping"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP); + } + } + // Check for custom filters + if ($filterColumn->customFilters) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $customFilters = $filterColumn->customFilters; + // Custom filters can an AND or an OR join; + // and there should only ever be one or two entries + if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) { + $column->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); + } + foreach ($customFilters->customFilter as $filterRule) { + $column->createRule()->setRule( + (string) $filterRule["operator"], + (string) $filterRule["val"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + } + } + // Check for dynamic filters + if ($filterColumn->dynamicFilter) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + // We should only ever have one dynamic filter + foreach ($filterColumn->dynamicFilter as $filterRule) { + $column->createRule()->setRule( + NULL, // Operator is undefined, but always treated as EQUAL + (string) $filterRule["val"], + (string) $filterRule["type"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + if (isset($filterRule["val"])) { + $column->setAttribute('val',(string) $filterRule["val"]); + } + if (isset($filterRule["maxVal"])) { + $column->setAttribute('maxVal',(string) $filterRule["maxVal"]); + } + } + } + // Check for dynamic filters + if ($filterColumn->top10) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + // We should only ever have one top10 filter + foreach ($filterColumn->top10 as $filterRule) { + $column->createRule()->setRule( + (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1)) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE + ), + (string) $filterRule["val"], + (((isset($filterRule["top"])) && ($filterRule["top"] == 1)) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM + ) + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + } + } + } + } + + if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->_readDataOnly) { + foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) { + $mergeRef = (string) $mergeCell["ref"]; + if (strpos($mergeRef,':') !== FALSE) { + $docSheet->mergeCells((string) $mergeCell["ref"]); + } + } + } + + if ($xmlSheet && $xmlSheet->pageMargins && !$this->_readDataOnly) { + $docPageMargins = $docSheet->getPageMargins(); + $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"])); + $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"])); + $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"])); + $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"])); + $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"])); + $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"])); + } + + if ($xmlSheet && $xmlSheet->pageSetup && !$this->_readDataOnly) { + $docPageSetup = $docSheet->getPageSetup(); + + if (isset($xmlSheet->pageSetup["orientation"])) { + $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]); + } + if (isset($xmlSheet->pageSetup["paperSize"])) { + $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"])); + } + if (isset($xmlSheet->pageSetup["scale"])) { + $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), FALSE); + } + if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) { + $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), FALSE); + } + if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) { + $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), FALSE); + } + if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) && + self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) { + $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"])); + } + } + + if ($xmlSheet && $xmlSheet->headerFooter && !$this->_readDataOnly) { + $docHeaderFooter = $docSheet->getHeaderFooter(); + + if (isset($xmlSheet->headerFooter["differentOddEven"]) && + self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) { + $docHeaderFooter->setDifferentOddEven(TRUE); + } else { + $docHeaderFooter->setDifferentOddEven(FALSE); + } + if (isset($xmlSheet->headerFooter["differentFirst"]) && + self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) { + $docHeaderFooter->setDifferentFirst(TRUE); + } else { + $docHeaderFooter->setDifferentFirst(FALSE); + } + if (isset($xmlSheet->headerFooter["scaleWithDoc"]) && + !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) { + $docHeaderFooter->setScaleWithDocument(FALSE); + } else { + $docHeaderFooter->setScaleWithDocument(TRUE); + } + if (isset($xmlSheet->headerFooter["alignWithMargins"]) && + !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) { + $docHeaderFooter->setAlignWithMargins(FALSE); + } else { + $docHeaderFooter->setAlignWithMargins(TRUE); + } + + $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); + $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); + $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); + $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); + $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); + $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); + } + + if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->_readDataOnly) { + foreach ($xmlSheet->rowBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW); + } + } + } + if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->_readDataOnly) { + foreach ($xmlSheet->colBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN); + } + } + } + + if ($xmlSheet && $xmlSheet->dataValidations && !$this->_readDataOnly) { + foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) { + // Uppercase coordinate + $range = strtoupper($dataValidation["sqref"]); + $rangeSet = explode(' ',$range); + foreach($rangeSet as $range) { + $stRange = $docSheet->shrinkRangeToFit($range); + + // Extract all cell references in $range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($stRange); + foreach ($aReferences as $reference) { + // Create validation + $docValidation = $docSheet->getCell($reference)->getDataValidation(); + $docValidation->setType((string) $dataValidation["type"]); + $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]); + $docValidation->setOperator((string) $dataValidation["operator"]); + $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0); + $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0); + $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0); + $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0); + $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]); + $docValidation->setError((string) $dataValidation["error"]); + $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]); + $docValidation->setPrompt((string) $dataValidation["prompt"]); + $docValidation->setFormula1((string) $dataValidation->formula1); + $docValidation->setFormula2((string) $dataValidation->formula2); + } + } + } + } + + // Add hyperlinks + $hyperlinks = array(); + if (!$this->_readDataOnly) { + // Locate hyperlink relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { + $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through hyperlinks + if ($xmlSheet && $xmlSheet->hyperlinks) { + foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) { + // Link url + $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { + $cell = $docSheet->getCell( $cellReference ); + if (isset($linkRel['id'])) { + $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ]; + if (isset($hyperlink['location'])) { + $hyperlinkUrl .= '#' . (string) $hyperlink['location']; + } + $cell->getHyperlink()->setUrl($hyperlinkUrl); + } elseif (isset($hyperlink['location'])) { + $cell->getHyperlink()->setUrl( 'sheet://' . (string)$hyperlink['location'] ); + } + + // Tooltip + if (isset($hyperlink['tooltip'])) { + $cell->getHyperlink()->setTooltip( (string)$hyperlink['tooltip'] ); + } + } + } + } + } + + // Add comments + $comments = array(); + $vmlComments = array(); + if (!$this->_readDataOnly) { + // Locate comment relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") { + $comments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through comments + foreach ($comments as $relName => $relPath) { + // Load comments file + $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $commentsFile = simplexml_load_string($this->_getFromZipArchive($zip, $relPath) , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + + // Utility variables + $authors = array(); + + // Loop through authors + foreach ($commentsFile->authors->author as $author) { + $authors[] = (string)$author; + } + + // Loop through contents + foreach ($commentsFile->commentList->comment as $comment) { + $docSheet->getComment( (string)$comment['ref'] )->setAuthor( $authors[(string)$comment['authorId']] ); + $docSheet->getComment( (string)$comment['ref'] )->setText( $this->_parseRichText($comment->text) ); + } + } + + // Loop through VML comments + foreach ($vmlComments as $relName => $relPath) { + // Load VML comments file + $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $vmlCommentsFile = simplexml_load_string( $this->_getFromZipArchive($zip, $relPath) , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $shapes = $vmlCommentsFile->xpath('//v:shape'); + foreach ($shapes as $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + if (isset($shape['style'])) { + $style = (string)$shape['style']; + $fillColor = strtoupper( substr( (string)$shape['fillcolor'], 1 ) ); + $column = null; + $row = null; + + $clientData = $shape->xpath('.//x:ClientData'); + if (is_array($clientData) && !empty($clientData)) { + $clientData = $clientData[0]; + + if ( isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note' ) { + $temp = $clientData->xpath('.//x:Row'); + if (is_array($temp)) $row = $temp[0]; + + $temp = $clientData->xpath('.//x:Column'); + if (is_array($temp)) $column = $temp[0]; + } + } + + if (($column !== NULL) && ($row !== NULL)) { + // Set comment properties + $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1); + $comment->getFillColor()->setRGB( $fillColor ); + + // Parse style + $styleArray = explode(';', str_replace(' ', '', $style)); + foreach ($styleArray as $stylePair) { + $stylePair = explode(':', $stylePair); + + if ($stylePair[0] == 'margin-left') $comment->setMarginLeft($stylePair[1]); + if ($stylePair[0] == 'margin-top') $comment->setMarginTop($stylePair[1]); + if ($stylePair[0] == 'width') $comment->setWidth($stylePair[1]); + if ($stylePair[0] == 'height') $comment->setHeight($stylePair[1]); + if ($stylePair[0] == 'visibility') $comment->setVisible( $stylePair[1] == 'visible' ); + + } + } + } + } + } + + // Header/footer images + if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->_readDataOnly) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $vmlRelationship = ''; + + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlRelationship = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); + } + } + + if ($vmlRelationship != '') { + // Fetch linked images + $relsVML = simplexml_load_string($this->_getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels' ), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsVML->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $drawings[(string) $ele["Id"]] = self::dir_add($vmlRelationship, $ele["Target"]); + } + } + + // Fetch VML document + $vmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $vmlRelationship), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $hfImages = array(); + + $shapes = $vmlDrawing->xpath('//v:shape'); + foreach ($shapes as $idx => $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $imageData = $shape->xpath('//v:imagedata'); + $imageData = $imageData[$idx]; + + $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); + $style = self::toCSSArray( (string)$shape['style'] ); + + $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing(); + if (isset($imageData['title'])) { + $hfImages[ (string)$shape['id'] ]->setName( (string)$imageData['title'] ); + } + + $hfImages[ (string)$shape['id'] ]->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(false); + $hfImages[ (string)$shape['id'] ]->setWidth($style['width']); + $hfImages[ (string)$shape['id'] ]->setHeight($style['height']); + if (isset($style['margin-left'])) { + $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']); + } + $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(true); + } + + $docSheet->getHeaderFooter()->setImages($hfImages); + } + } + } + + } + + // TODO: Autoshapes from twoCellAnchors! + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->_getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels") , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") { + $drawings[(string) $ele["Id"]] = self::dir_add("$dir/$fileWorksheet", $ele["Target"]); + } + } + if ($xmlSheet->drawing && !$this->_readDataOnly) { + foreach ($xmlSheet->drawing as $drawing) { + $fileDrawing = $drawings[(string) self::array_item($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $relsDrawing = simplexml_load_string($this->_getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels") , 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $images = array(); + + if ($relsDrawing && $relsDrawing->Relationship) { + foreach ($relsDrawing->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $images[(string) $ele["Id"]] = self::dir_add($fileDrawing, $ele["Target"]); + } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") { + if ($this->_includeCharts) { + $charts[self::dir_add($fileDrawing, $ele["Target"])] = array('id' => (string) $ele["Id"], + 'sheet' => $docSheet->getTitle() + ); + } + } + } + } + $xmlDrawing = simplexml_load_string($this->_getFromZipArchive($zip, $fileDrawing), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions())->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); + + if ($xmlDrawing->oneCellAnchor) { + foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) { + if ($oneCellAnchor->pic->blipFill) { + $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPExcel_Worksheet_Drawing; + $objDrawing->setName((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::array_item($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy"))); + if ($xfrm) { + $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } else { + // ? Can charts be positioned with a oneCellAnchor ? + $coordinates = PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1); + $offsetX = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff); + $offsetY = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff); + $width = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cx")); + $height = PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($oneCellAnchor->ext->attributes(), "cy")); + } + } + } + if ($xmlDrawing->twoCellAnchor) { + foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) { + if ($twoCellAnchor->pic->blipFill) { + $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPExcel_Worksheet_Drawing; + $objDrawing->setName((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::array_item($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::array_item($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + + $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::array_item($xfrm->ext->attributes(), "cy"))); + + if ($xfrm) { + $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::array_item($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::array_item($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::array_item($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::array_item($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::array_item($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } elseif(($this->_includeCharts) && ($twoCellAnchor->graphicFrame)) { + $fromCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1); + $fromOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff); + $fromOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff); + $toCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); + $toOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff); + $toOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff); + $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic; + $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart; + $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + + $chartDetails[$docSheet->getTitle().'!'.$thisChart] = + array( 'fromCoordinate' => $fromCoordinate, + 'fromOffsetX' => $fromOffsetX, + 'fromOffsetY' => $fromOffsetY, + 'toCoordinate' => $toCoordinate, + 'toOffsetX' => $toOffsetX, + 'toOffsetY' => $toOffsetY, + 'worksheetTitle' => $docSheet->getTitle() + ); + } + } + } + + } + } + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange,'!')) !== false) { + $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== FALSE || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) { + // Switch on type + switch ((string)$definedName['name']) { + + case '_xlnm._FilterDatabase': + if ((string)$definedName['hidden'] !== '1') { + $docSheet->getAutoFilter()->setRange($extractedRange); + } + break; + + case '_xlnm.Print_Titles': + // Split $extractedRange + $extractedRange = explode(',', $extractedRange); + + // Set print titles + foreach ($extractedRange as $range) { + $matches = array(); + $range = str_replace('$', '', $range); + + // check for repeating columns, e g. 'A:A' or 'A:D' + if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2])); + } + // check for repeating rows, e.g. '1:1' or '1:5' + elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { + $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2])); + } + } + break; + + case '_xlnm.Print_Area': + $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma? + $newRangeSets = array(); + foreach($rangeSets as $rangeSet) { + $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark? + $rangeSet = isset($range[1]) ? $range[1] : $range[0]; + if (strpos($rangeSet, ':') === FALSE) { + $rangeSet = $rangeSet . ':' . $rangeSet; + } + $newRangeSets[] = str_replace('$', '', $rangeSet); + } + $docSheet->getPageSetup()->setPrintArea(implode(',',$newRangeSets)); + break; + + default: + break; + } + } + } + } + + // Next sheet id + ++$sheetId; + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange,'!')) !== false) { + $extractedRange = substr($extractedRange,0,$spos).str_replace('$', '', substr($extractedRange,$spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '') { + // Local defined name + // Switch on type + switch ((string)$definedName['name']) { + + case '_xlnm._FilterDatabase': + case '_xlnm.Print_Titles': + case '_xlnm.Print_Area': + break; + + default: + if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) { + $range = explode('!', (string)$definedName); + if (count($range) == 2) { + $range[0] = str_replace("''", "'", $range[0]); + $range[0] = str_replace("'", "", $range[0]); + if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { + $extractedRange = str_replace('$', '', $range[1]); + $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]); + $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope) ); + } + } + } + break; + } + } else if (!isset($definedName['localSheetId'])) { + // "Global" definedNames + $locatedSheet = null; + $extractedSheetName = ''; + if (strpos( (string)$definedName, '!' ) !== false) { + // Extract sheet name + $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle( (string)$definedName, true ); + $extractedSheetName = $extractedSheetName[0]; + + // Locate sheet + $locatedSheet = $excel->getSheetByName($extractedSheetName); + + // Modify range + $range = explode('!', $extractedRange); + $extractedRange = isset($range[1]) ? $range[1] : $range[0]; + } + + if ($locatedSheet !== NULL) { + $excel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false) ); + } + } + } + } + } + + if ((!$this->_readDataOnly) || (!empty($this->_loadSheetsOnly))) { + // active sheet index + $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index + + // keep active sheet index if sheet is still loaded, else first sheet is set as the active + if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { + $excel->setActiveSheetIndex($mapSheetId[$activeTab]); + } else { + if ($excel->getSheetCount() == 0) { + $excel->createSheet(); + } + $excel->setActiveSheetIndex(0); + } + } + break; + } + + } + + + if (!$this->_readDataOnly) { + $contentTypes = simplexml_load_string($this->_getFromZipArchive($zip, "[Content_Types].xml"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + foreach ($contentTypes->Override as $contentType) { + switch ($contentType["ContentType"]) { + case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": + if ($this->_includeCharts) { + $chartEntryRef = ltrim($contentType['PartName'],'/'); + $chartElements = simplexml_load_string($this->_getFromZipArchive($zip, $chartEntryRef), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $objChart = PHPExcel_Reader_Excel2007_Chart::readChart($chartElements,basename($chartEntryRef,'.xml')); + +// echo 'Chart ',$chartEntryRef,'
'; +// var_dump($charts[$chartEntryRef]); +// + if (isset($charts[$chartEntryRef])) { + $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id']; +// echo 'Position Ref ',$chartPositionRef,'
'; + if (isset($chartDetails[$chartPositionRef])) { +// var_dump($chartDetails[$chartPositionRef]); + + $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); + $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); + $objChart->setTopLeftPosition( $chartDetails[$chartPositionRef]['fromCoordinate'], + $chartDetails[$chartPositionRef]['fromOffsetX'], + $chartDetails[$chartPositionRef]['fromOffsetY'] + ); + $objChart->setBottomRightPosition( $chartDetails[$chartPositionRef]['toCoordinate'], + $chartDetails[$chartPositionRef]['toOffsetX'], + $chartDetails[$chartPositionRef]['toOffsetY'] + ); + } + } + } + } + } + } + + $zip->close(); + + return $excel; + } + + + private static function _readColor($color, $background=FALSE) { + if (isset($color["rgb"])) { + return (string)$color["rgb"]; + } else if (isset($color["indexed"])) { + return PHPExcel_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB(); + } else if (isset($color["theme"])) { + if (self::$_theme !== NULL) { + $returnColour = self::$_theme->getColourByIndex((int)$color["theme"]); + if (isset($color["tint"])) { + $tintAdjust = (float) $color["tint"]; + $returnColour = PHPExcel_Style_Color::changeBrightness($returnColour, $tintAdjust); + } + return 'FF'.$returnColour; + } + } + + if ($background) { + return 'FFFFFFFF'; + } + return 'FF000000'; + } + + + private static function _readStyle($docStyle, $style) { + // format code +// if (isset($style->numFmt)) { +// if (isset($style->numFmt['formatCode'])) { +// $docStyle->getNumberFormat()->setFormatCode((string) $style->numFmt['formatCode']); +// } else { + $docStyle->getNumberFormat()->setFormatCode($style->numFmt); +// } +// } + + // font + if (isset($style->font)) { + $docStyle->getFont()->setName((string) $style->font->name["val"]); + $docStyle->getFont()->setSize((string) $style->font->sz["val"]); + if (isset($style->font->b)) { + $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || self::boolean((string) $style->font->b["val"])); + } + if (isset($style->font->i)) { + $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || self::boolean((string) $style->font->i["val"])); + } + if (isset($style->font->strike)) { + $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || self::boolean((string) $style->font->strike["val"])); + } + $docStyle->getFont()->getColor()->setARGB(self::_readColor($style->font->color)); + + if (isset($style->font->u) && !isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } else if (isset($style->font->u) && isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline((string)$style->font->u["val"]); + } + + if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) { + $vertAlign = strtolower((string)$style->font->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $docStyle->getFont()->setSuperScript(true); + } + if ($vertAlign == 'subscript') { + $docStyle->getFont()->setSubScript(true); + } + } + } + + // fill + if (isset($style->fill)) { + if ($style->fill->gradientFill) { + $gradientFill = $style->fill->gradientFill[0]; + if(!empty($gradientFill["type"])) { + $docStyle->getFill()->setFillType((string) $gradientFill["type"]); + } + $docStyle->getFill()->setRotation(floatval($gradientFill["degree"])); + $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $docStyle->getFill()->getStartColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=0]"))->color) ); + $docStyle->getFill()->getEndColor()->setARGB(self::_readColor( self::array_item($gradientFill->xpath("sml:stop[@position=1]"))->color) ); + } elseif ($style->fill->patternFill) { + $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid'; + $docStyle->getFill()->setFillType($patternType); + if ($style->fill->patternFill->fgColor) { + $docStyle->getFill()->getStartColor()->setARGB(self::_readColor($style->fill->patternFill->fgColor,true)); + } else { + $docStyle->getFill()->getStartColor()->setARGB('FF000000'); + } + if ($style->fill->patternFill->bgColor) { + $docStyle->getFill()->getEndColor()->setARGB(self::_readColor($style->fill->patternFill->bgColor,true)); + } + } + } + + // border + if (isset($style->border)) { + $diagonalUp = self::boolean((string) $style->border["diagonalUp"]); + $diagonalDown = self::boolean((string) $style->border["diagonalDown"]); + if (!$diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE); + } elseif ($diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP); + } elseif (!$diagonalUp && $diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN); + } else { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH); + } + self::_readBorder($docStyle->getBorders()->getLeft(), $style->border->left); + self::_readBorder($docStyle->getBorders()->getRight(), $style->border->right); + self::_readBorder($docStyle->getBorders()->getTop(), $style->border->top); + self::_readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); + self::_readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); + } + + // alignment + if (isset($style->alignment)) { + $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]); + $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]); + + $textRotation = 0; + if ((int)$style->alignment["textRotation"] <= 90) { + $textRotation = (int)$style->alignment["textRotation"]; + } else if ((int)$style->alignment["textRotation"] > 90) { + $textRotation = 90 - (int)$style->alignment["textRotation"]; + } + + $docStyle->getAlignment()->setTextRotation(intval($textRotation)); + $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment["wrapText"])); + $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment["shrinkToFit"])); + $docStyle->getAlignment()->setIndent( intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0 ); + } + + // protection + if (isset($style->protection)) { + if (isset($style->protection['locked'])) { + if (self::boolean((string) $style->protection['locked'])) { + $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + } + } + + if (isset($style->protection['hidden'])) { + if (self::boolean((string) $style->protection['hidden'])) { + $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + } + } + } + + // top-level style settings + if (isset($style->quotePrefix)) { + $docStyle->setQuotePrefix($style->quotePrefix); + } + } + + + private static function _readBorder($docBorder, $eleBorder) { + if (isset($eleBorder["style"])) { + $docBorder->setBorderStyle((string) $eleBorder["style"]); + } + if (isset($eleBorder->color)) { + $docBorder->getColor()->setARGB(self::_readColor($eleBorder->color)); + } + } + + + private function _parseRichText($is = null) { + $value = new PHPExcel_RichText(); + + if (isset($is->t)) { + $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $is->t ) ); + } else { + foreach ($is->r as $run) { + if (!isset($run->rPr)) { + $objText = $value->createText( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); + + } else { + $objText = $value->createTextRun( PHPExcel_Shared_String::ControlCharacterOOXML2PHP( (string) $run->t ) ); + + if (isset($run->rPr->rFont["val"])) { + $objText->getFont()->setName((string) $run->rPr->rFont["val"]); + } + + if (isset($run->rPr->sz["val"])) { + $objText->getFont()->setSize((string) $run->rPr->sz["val"]); + } + + if (isset($run->rPr->color)) { + $objText->getFont()->setColor( new PHPExcel_Style_Color( self::_readColor($run->rPr->color) ) ); + } + + if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) || + (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) { + $objText->getFont()->setBold(TRUE); + } + + if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) || + (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) { + $objText->getFont()->setItalic(TRUE); + } + + if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) { + $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $objText->getFont()->setSuperScript(TRUE); + } + if ($vertAlign == 'subscript') { + $objText->getFont()->setSubScript(TRUE); + } + } + + if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } else if (isset($run->rPr->u) && isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline((string)$run->rPr->u["val"]); + } + + if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) || + (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) { + $objText->getFont()->setStrikethrough(TRUE); + } + } + } + } + + return $value; + } + + private function _readRibbon($excel, $customUITarget, $zip) + { + $baseDir = dirname($customUITarget); + $nameCustomUI = basename($customUITarget); + // get the xml file (ribbon) + $localRibbon = $this->_getFromZipArchive($zip, $customUITarget); + $customUIImagesNames = array(); + $customUIImagesBinaries = array(); + // something like customUI/_rels/customUI.xml.rels + $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; + $dataRels = $this->_getFromZipArchive($zip, $pathRels); + if ($dataRels) { + // exists and not empty if the ribbon have some pictures (other than internal MSO) + $UIRels = simplexml_load_string($dataRels, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if ($UIRels) { + // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image + foreach ($UIRels->Relationship as $ele) { + if ($ele["Type"] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + // an image ? + $customUIImagesNames[(string) $ele['Id']] = (string)$ele['Target']; + $customUIImagesBinaries[(string)$ele['Target']] = $this->_getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); + } + } + } + } + if ($localRibbon) { + $excel->setRibbonXMLData($customUITarget, $localRibbon); + if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { + $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); + } else { + $excel->setRibbonBinObjects(NULL); + } + } else { + $excel->setRibbonXMLData(NULL); + $excel->setRibbonBinObjects(NULL); + } + } + + private static function array_item($array, $key = 0) { + return (isset($array[$key]) ? $array[$key] : null); + } + + + private static function dir_add($base, $add) { + return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); + } + + + private static function toCSSArray($style) { + $style = str_replace(array("\r","\n"), "", $style); + + $temp = explode(';', $style); + $style = array(); + foreach ($temp as $item) { + $item = explode(':', $item); + + if (strpos($item[1], 'px') !== false) { + $item[1] = str_replace('px', '', $item[1]); + } + if (strpos($item[1], 'pt') !== false) { + $item[1] = str_replace('pt', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::fontSizeToPixels($item[1]); + } + if (strpos($item[1], 'in') !== false) { + $item[1] = str_replace('in', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::inchSizeToPixels($item[1]); + } + if (strpos($item[1], 'cm') !== false) { + $item[1] = str_replace('cm', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::centimeterSizeToPixels($item[1]); + } + + $style[$item[0]] = $item[1]; + } + + return $style; + } + + private static function boolean($value = NULL) + { + if (is_object($value)) { + $value = (string) $value; + } + if (is_numeric($value)) { + return (bool) $value; + } + return ($value === 'true' || $value === 'TRUE'); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php new file mode 100644 index 00000000..0de88acb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php @@ -0,0 +1,517 @@ +attributes(); + if (isset($attributes[$name])) { + if ($format == 'string') { + return (string) $attributes[$name]; + } elseif ($format == 'integer') { + return (integer) $attributes[$name]; + } elseif ($format == 'boolean') { + return (boolean) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true; + } else { + return (float) $attributes[$name]; + } + } + return null; + } // function _getAttribute() + + + private static function _readColor($color,$background=false) { + if (isset($color["rgb"])) { + return (string)$color["rgb"]; + } else if (isset($color["indexed"])) { + return PHPExcel_Style_Color::indexedColor($color["indexed"]-7,$background)->getARGB(); + } + } + + + public static function readChart($chartElements,$chartName) { + $namespacesChartMeta = $chartElements->getNamespaces(true); + $chartElementsC = $chartElements->children($namespacesChartMeta['c']); + + $XaxisLabel = $YaxisLabel = $legend = $title = NULL; + $dispBlanksAs = $plotVisOnly = NULL; + + foreach($chartElementsC as $chartElementKey => $chartElement) { + switch ($chartElementKey) { + case "chart": + foreach($chartElement as $chartDetailsKey => $chartDetails) { + $chartDetailsC = $chartDetails->children($namespacesChartMeta['c']); + switch ($chartDetailsKey) { + case "plotArea": + $plotAreaLayout = $XaxisLable = $YaxisLable = null; + $plotSeries = $plotAttributes = array(); + foreach($chartDetails as $chartDetailKey => $chartDetail) { + switch ($chartDetailKey) { + case "layout": + $plotAreaLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'plotArea'); + break; + case "catAx": + if (isset($chartDetail->title)) { + $XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat'); + } + break; + case "dateAx": + if (isset($chartDetail->title)) { + $XaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat'); + } + break; + case "valAx": + if (isset($chartDetail->title)) { + $YaxisLabel = self::_chartTitle($chartDetail->title->children($namespacesChartMeta['c']),$namespacesChartMeta,'cat'); + } + break; + case "barChart": + case "bar3DChart": + $barDirection = self::_getAttribute($chartDetail->barDir, 'val', 'string'); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotDirection($barDirection); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "lineChart": + case "line3DChart": + $plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "areaChart": + case "area3DChart": + $plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "doughnutChart": + case "pieChart": + case "pie3DChart": + $explosion = isset($chartDetail->ser->explosion); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotStyle($explosion); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "scatterChart": + $scatterStyle = self::_getAttribute($chartDetail->scatterStyle, 'val', 'string'); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotStyle($scatterStyle); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "bubbleChart": + $bubbleScale = self::_getAttribute($chartDetail->bubbleScale, 'val', 'integer'); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotStyle($bubbleScale); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "radarChart": + $radarStyle = self::_getAttribute($chartDetail->radarStyle, 'val', 'string'); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotStyle($radarStyle); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "surfaceChart": + case "surface3DChart": + $wireFrame = self::_getAttribute($chartDetail->wireframe, 'val', 'boolean'); + $plotSer = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotSer->setPlotStyle($wireFrame); + $plotSeries[] = $plotSer; + $plotAttributes = self::_readChartAttributes($chartDetail); + break; + case "stockChart": + $plotSeries[] = self::_chartDataSeries($chartDetail,$namespacesChartMeta,$chartDetailKey); + $plotAttributes = self::_readChartAttributes($plotAreaLayout); + break; + } + } + if ($plotAreaLayout == NULL) { + $plotAreaLayout = new PHPExcel_Chart_Layout(); + } + $plotArea = new PHPExcel_Chart_PlotArea($plotAreaLayout,$plotSeries); + self::_setChartAttributes($plotAreaLayout,$plotAttributes); + break; + case "plotVisOnly": + $plotVisOnly = self::_getAttribute($chartDetails, 'val', 'string'); + break; + case "dispBlanksAs": + $dispBlanksAs = self::_getAttribute($chartDetails, 'val', 'string'); + break; + case "title": + $title = self::_chartTitle($chartDetails,$namespacesChartMeta,'title'); + break; + case "legend": + $legendPos = 'r'; + $legendLayout = null; + $legendOverlay = false; + foreach($chartDetails as $chartDetailKey => $chartDetail) { + switch ($chartDetailKey) { + case "legendPos": + $legendPos = self::_getAttribute($chartDetail, 'val', 'string'); + break; + case "overlay": + $legendOverlay = self::_getAttribute($chartDetail, 'val', 'boolean'); + break; + case "layout": + $legendLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta,'legend'); + break; + } + } + $legend = new PHPExcel_Chart_Legend($legendPos, $legendLayout, $legendOverlay); + break; + } + } + } + } + $chart = new PHPExcel_Chart($chartName,$title,$legend,$plotArea,$plotVisOnly,$dispBlanksAs,$XaxisLabel,$YaxisLabel); + + return $chart; + } // function readChart() + + + private static function _chartTitle($titleDetails,$namespacesChartMeta,$type) { + $caption = array(); + $titleLayout = null; + foreach($titleDetails as $titleDetailKey => $chartDetail) { + switch ($titleDetailKey) { + case "tx": + $titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']); + foreach($titleDetails as $titleKey => $titleDetail) { + switch ($titleKey) { + case "p": + $titleDetailPart = $titleDetail->children($namespacesChartMeta['a']); + $caption[] = self::_parseRichText($titleDetailPart); + } + } + break; + case "layout": + $titleLayout = self::_chartLayoutDetails($chartDetail,$namespacesChartMeta); + break; + } + } + + return new PHPExcel_Chart_Title($caption, $titleLayout); + } // function _chartTitle() + + + private static function _chartLayoutDetails($chartDetail,$namespacesChartMeta) { + if (!isset($chartDetail->manualLayout)) { + return null; + } + $details = $chartDetail->manualLayout->children($namespacesChartMeta['c']); + if (is_null($details)) { + return null; + } + $layout = array(); + foreach($details as $detailKey => $detail) { +// echo $detailKey,' => ',self::_getAttribute($detail, 'val', 'string'),PHP_EOL; + $layout[$detailKey] = self::_getAttribute($detail, 'val', 'string'); + } + return new PHPExcel_Chart_Layout($layout); + } // function _chartLayoutDetails() + + + private static function _chartDataSeries($chartDetail,$namespacesChartMeta,$plotType) { + $multiSeriesType = NULL; + $smoothLine = false; + $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array(); + + $seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']); + foreach($seriesDetailSet as $seriesDetailKey => $seriesDetails) { + switch ($seriesDetailKey) { + case "grouping": + $multiSeriesType = self::_getAttribute($chartDetail->grouping, 'val', 'string'); + break; + case "ser": + $marker = NULL; + foreach($seriesDetails as $seriesKey => $seriesDetail) { + switch ($seriesKey) { + case "idx": + $seriesIndex = self::_getAttribute($seriesDetail, 'val', 'integer'); + break; + case "order": + $seriesOrder = self::_getAttribute($seriesDetail, 'val', 'integer'); + $plotOrder[$seriesIndex] = $seriesOrder; + break; + case "tx": + $seriesLabel[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta); + break; + case "marker": + $marker = self::_getAttribute($seriesDetail->symbol, 'val', 'string'); + break; + case "smooth": + $smoothLine = self::_getAttribute($seriesDetail, 'val', 'boolean'); + break; + case "cat": + $seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta); + break; + case "val": + $seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker); + break; + case "xVal": + $seriesCategory[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker); + break; + case "yVal": + $seriesValues[$seriesIndex] = self::_chartDataSeriesValueSet($seriesDetail,$namespacesChartMeta,$marker); + break; + } + } + } + } + return new PHPExcel_Chart_DataSeries($plotType,$multiSeriesType,$plotOrder,$seriesLabel,$seriesCategory,$seriesValues,$smoothLine); + } // function _chartDataSeries() + + + private static function _chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) { + if (isset($seriesDetail->strRef)) { + $seriesSource = (string) $seriesDetail->strRef->f; + $seriesData = self::_chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']),'s'); + + return new PHPExcel_Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine); + } elseif (isset($seriesDetail->numRef)) { + $seriesSource = (string) $seriesDetail->numRef->f; + $seriesData = self::_chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + + return new PHPExcel_Chart_DataSeriesValues('Number',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine); + } elseif (isset($seriesDetail->multiLvlStrRef)) { + $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; + $seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']),'s'); + $seriesData['pointCount'] = count($seriesData['dataValues']); + + return new PHPExcel_Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine); + } elseif (isset($seriesDetail->multiLvlNumRef)) { + $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; + $seriesData = self::_chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']),'s'); + $seriesData['pointCount'] = count($seriesData['dataValues']); + + return new PHPExcel_Chart_DataSeriesValues('String',$seriesSource,$seriesData['formatCode'],$seriesData['pointCount'],$seriesData['dataValues'],$marker,$smoothLine); + } + return null; + } // function _chartDataSeriesValueSet() + + + private static function _chartDataSeriesValues($seriesValueSet,$dataType='n') { + $seriesVal = array(); + $formatCode = ''; + $pointCount = 0; + + foreach($seriesValueSet as $seriesValueIdx => $seriesValue) { + switch ($seriesValueIdx) { + case 'ptCount': + $pointCount = self::_getAttribute($seriesValue, 'val', 'integer'); + break; + case 'formatCode': + $formatCode = (string) $seriesValue; + break; + case 'pt': + $pointVal = self::_getAttribute($seriesValue, 'idx', 'integer'); + if ($dataType == 's') { + $seriesVal[$pointVal] = (string) $seriesValue->v; + } else { + $seriesVal[$pointVal] = (float) $seriesValue->v; + } + break; + } + } + + if (empty($seriesVal)) { + $seriesVal = NULL; + } + + return array( 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal + ); + } // function _chartDataSeriesValues() + + + private static function _chartDataSeriesValuesMultiLevel($seriesValueSet,$dataType='n') { + $seriesVal = array(); + $formatCode = ''; + $pointCount = 0; + + foreach($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) { + foreach($seriesLevel as $seriesValueIdx => $seriesValue) { + switch ($seriesValueIdx) { + case 'ptCount': + $pointCount = self::_getAttribute($seriesValue, 'val', 'integer'); + break; + case 'formatCode': + $formatCode = (string) $seriesValue; + break; + case 'pt': + $pointVal = self::_getAttribute($seriesValue, 'idx', 'integer'); + if ($dataType == 's') { + $seriesVal[$pointVal][] = (string) $seriesValue->v; + } else { + $seriesVal[$pointVal][] = (float) $seriesValue->v; + } + break; + } + } + } + + return array( 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal + ); + } // function _chartDataSeriesValuesMultiLevel() + + private static function _parseRichText($titleDetailPart = null) { + $value = new PHPExcel_RichText(); + + foreach($titleDetailPart as $titleDetailElementKey => $titleDetailElement) { + if (isset($titleDetailElement->t)) { + $objText = $value->createTextRun( (string) $titleDetailElement->t ); + } + if (isset($titleDetailElement->rPr)) { + if (isset($titleDetailElement->rPr->rFont["val"])) { + $objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]); + } + + $fontSize = (self::_getAttribute($titleDetailElement->rPr, 'sz', 'integer')); + if (!is_null($fontSize)) { + $objText->getFont()->setSize(floor($fontSize / 100)); + } + + $fontColor = (self::_getAttribute($titleDetailElement->rPr, 'color', 'string')); + if (!is_null($fontColor)) { + $objText->getFont()->setColor( new PHPExcel_Style_Color( self::_readColor($fontColor) ) ); + } + + $bold = self::_getAttribute($titleDetailElement->rPr, 'b', 'boolean'); + if (!is_null($bold)) { + $objText->getFont()->setBold($bold); + } + + $italic = self::_getAttribute($titleDetailElement->rPr, 'i', 'boolean'); + if (!is_null($italic)) { + $objText->getFont()->setItalic($italic); + } + + $baseline = self::_getAttribute($titleDetailElement->rPr, 'baseline', 'integer'); + if (!is_null($baseline)) { + if ($baseline > 0) { + $objText->getFont()->setSuperScript(true); + } elseif($baseline < 0) { + $objText->getFont()->setSubScript(true); + } + } + + $underscore = (self::_getAttribute($titleDetailElement->rPr, 'u', 'string')); + if (!is_null($underscore)) { + if ($underscore == 'sng') { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } elseif($underscore == 'dbl') { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLE); + } else { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_NONE); + } + } + + $strikethrough = (self::_getAttribute($titleDetailElement->rPr, 's', 'string')); + if (!is_null($strikethrough)) { + if ($strikethrough == 'noStrike') { + $objText->getFont()->setStrikethrough(false); + } else { + $objText->getFont()->setStrikethrough(true); + } + } + } + } + + return $value; + } + + private static function _readChartAttributes($chartDetail) { + $plotAttributes = array(); + if (isset($chartDetail->dLbls)) { + if (isset($chartDetail->dLbls->howLegendKey)) { + $plotAttributes['showLegendKey'] = self::_getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showVal)) { + $plotAttributes['showVal'] = self::_getAttribute($chartDetail->dLbls->showVal, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showCatName)) { + $plotAttributes['showCatName'] = self::_getAttribute($chartDetail->dLbls->showCatName, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showSerName)) { + $plotAttributes['showSerName'] = self::_getAttribute($chartDetail->dLbls->showSerName, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showPercent)) { + $plotAttributes['showPercent'] = self::_getAttribute($chartDetail->dLbls->showPercent, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showBubbleSize)) { + $plotAttributes['showBubbleSize'] = self::_getAttribute($chartDetail->dLbls->showBubbleSize, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showLeaderLines)) { + $plotAttributes['showLeaderLines'] = self::_getAttribute($chartDetail->dLbls->showLeaderLines, 'val', 'string'); + } + } + + return $plotAttributes; + } + + private static function _setChartAttributes($plotArea,$plotAttributes) + { + foreach($plotAttributes as $plotAttributeKey => $plotAttributeValue) { + switch($plotAttributeKey) { + case 'showLegendKey' : + $plotArea->setShowLegendKey($plotAttributeValue); + break; + case 'showVal' : + $plotArea->setShowVal($plotAttributeValue); + break; + case 'showCatName' : + $plotArea->setShowCatName($plotAttributeValue); + break; + case 'showSerName' : + $plotArea->setShowSerName($plotAttributeValue); + break; + case 'showPercent' : + $plotArea->setShowPercent($plotAttributeValue); + break; + case 'showBubbleSize' : + $plotArea->setShowBubbleSize($plotAttributeValue); + break; + case 'showLeaderLines' : + $plotArea->setShowLeaderLines($plotAttributeValue); + break; + } + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php new file mode 100644 index 00000000..820fa96d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php @@ -0,0 +1,124 @@ +_themeName = $themeName; + $this->_colourSchemeName = $colourSchemeName; + $this->_colourMap = $colourMap; + } + + /** + * Get Theme Name + * + * @return string + */ + public function getThemeName() + { + return $this->_themeName; + } + + /** + * Get colour Scheme Name + * + * @return string + */ + public function getColourSchemeName() { + return $this->_colourSchemeName; + } + + /** + * Get colour Map Value by Position + * + * @return string + */ + public function getColourByIndex($index=0) { + if (isset($this->_colourMap[$index])) { + return $this->_colourMap[$index]; + } + return null; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != '_parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php new file mode 100644 index 00000000..91e0fa08 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php @@ -0,0 +1,7084 @@ +_data + * + * @var int + */ + private $_dataSize; + + /** + * Current position in stream + * + * @var integer + */ + private $_pos; + + /** + * Workbook to be returned by the reader. + * + * @var PHPExcel + */ + private $_phpExcel; + + /** + * Worksheet that is currently being built by the reader. + * + * @var PHPExcel_Worksheet + */ + private $_phpSheet; + + /** + * BIFF version + * + * @var int + */ + private $_version; + + /** + * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95) + * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE' + * + * @var string + */ + private $_codepage; + + /** + * Shared formats + * + * @var array + */ + private $_formats; + + /** + * Shared fonts + * + * @var array + */ + private $_objFonts; + + /** + * Color palette + * + * @var array + */ + private $_palette; + + /** + * Worksheets + * + * @var array + */ + private $_sheets; + + /** + * External books + * + * @var array + */ + private $_externalBooks; + + /** + * REF structures. Only applies to BIFF8. + * + * @var array + */ + private $_ref; + + /** + * External names + * + * @var array + */ + private $_externalNames; + + /** + * Defined names + * + * @var array + */ + private $_definedname; + + /** + * Shared strings. Only applies to BIFF8. + * + * @var array + */ + private $_sst; + + /** + * Panes are frozen? (in sheet currently being read). See WINDOW2 record. + * + * @var boolean + */ + private $_frozen; + + /** + * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. + * + * @var boolean + */ + private $_isFitToPages; + + /** + * Objects. One OBJ record contributes with one entry. + * + * @var array + */ + private $_objs; + + /** + * Text Objects. One TXO record corresponds with one entry. + * + * @var array + */ + private $_textObjects; + + /** + * Cell Annotations (BIFF8) + * + * @var array + */ + private $_cellNotes; + + /** + * The combined MSODRAWINGGROUP data + * + * @var string + */ + private $_drawingGroupData; + + /** + * The combined MSODRAWING data (per sheet) + * + * @var string + */ + private $_drawingData; + + /** + * Keep track of XF index + * + * @var int + */ + private $_xfIndex; + + /** + * Mapping of XF index (that is a cell XF) to final index in cellXf collection + * + * @var array + */ + private $_mapCellXfIndex; + + /** + * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection + * + * @var array + */ + private $_mapCellStyleXfIndex; + + /** + * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value. + * + * @var array + */ + private $_sharedFormulas; + + /** + * The shared formula parts in a sheet. One FORMULA record contributes with one value if it + * refers to a shared formula. + * + * @var array + */ + private $_sharedFormulaParts; + + /** + * The type of encryption in use + * + * @var int + */ + private $_encryption = 0; + + /** + * The position in the stream after which contents are encrypted + * + * @var int + */ + private $_encryptionStartPos = false; + + /** + * The current RC4 decryption object + * + * @var PHPExcel_Reader_Excel5_RC4 + */ + private $_rc4Key = null; + + /** + * The position in the stream that the RC4 decryption object was left at + * + * @var int + */ + private $_rc4Pos = 0; + + /** + * The current MD5 context state + * + * @var string + */ + private $_md5Ctxt = null; + + /** + * Create a new PHPExcel_Reader_Excel5 instance + */ + public function __construct() { + $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + try { + // Use ParseXL for the hard work. + $ole = new PHPExcel_Shared_OLERead(); + + // get excel data + $res = $ole->read($pFilename); + return true; + } catch (PHPExcel_Exception $e) { + return false; + } + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetNames = array(); + + // Read the OLE file + $this->_loadOLE($pFilename); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->_dataSize = strlen($this->_data); + + $this->_pos = 0; + $this->_sheets = array(); + + // Parse Workbook Global Substream + while ($this->_pos < $this->_dataSize) { + $code = self::_GetInt2d($this->_data, $this->_pos); + + switch ($code) { + case self::XLS_Type_BOF: $this->_readBof(); break; + case self::XLS_Type_SHEET: $this->_readSheet(); break; + case self::XLS_Type_EOF: $this->_readDefault(); break 2; + default: $this->_readDefault(); break; + } + } + + foreach ($this->_sheets as $sheet) { + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module + continue; + } + + $worksheetNames[] = $sheet['name']; + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + // Read the OLE file + $this->_loadOLE($pFilename); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->_dataSize = strlen($this->_data); + + // initialize + $this->_pos = 0; + $this->_sheets = array(); + + // Parse Workbook Global Substream + while ($this->_pos < $this->_dataSize) { + $code = self::_GetInt2d($this->_data, $this->_pos); + + switch ($code) { + case self::XLS_Type_BOF: $this->_readBof(); break; + case self::XLS_Type_SHEET: $this->_readSheet(); break; + case self::XLS_Type_EOF: $this->_readDefault(); break 2; + default: $this->_readDefault(); break; + } + } + + // Parse the individual sheets + foreach ($this->_sheets as $sheet) { + + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet + // 0x02: Chart + // 0x06: Visual Basic module + continue; + } + + $tmpInfo = array(); + $tmpInfo['worksheetName'] = $sheet['name']; + $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['lastColumnIndex'] = 0; + $tmpInfo['totalRows'] = 0; + $tmpInfo['totalColumns'] = 0; + + $this->_pos = $sheet['offset']; + + while ($this->_pos <= $this->_dataSize - 4) { + $code = self::_GetInt2d($this->_data, $this->_pos); + + switch ($code) { + case self::XLS_Type_RK: + case self::XLS_Type_LABELSST: + case self::XLS_Type_NUMBER: + case self::XLS_Type_FORMULA: + case self::XLS_Type_BOOLERR: + case self::XLS_Type_LABEL: + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + $rowIndex = self::_GetInt2d($recordData, 0) + 1; + $columnIndex = self::_GetInt2d($recordData, 2); + + $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); + $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); + break; + case self::XLS_Type_BOF: $this->_readBof(); break; + case self::XLS_Type_EOF: $this->_readDefault(); break 2; + default: $this->_readDefault(); break; + } + } + + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; + + $worksheetInfo[] = $tmpInfo; + } + + return $worksheetInfo; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Read the OLE file + $this->_loadOLE($pFilename); + + // Initialisations + $this->_phpExcel = new PHPExcel; + $this->_phpExcel->removeSheetByIndex(0); // remove 1st sheet + if (!$this->_readDataOnly) { + $this->_phpExcel->removeCellStyleXfByIndex(0); // remove the default style + $this->_phpExcel->removeCellXfByIndex(0); // remove the default style + } + + // Read the summary information stream (containing meta data) + $this->_readSummaryInformation(); + + // Read the Additional document summary information stream (containing application-specific meta data) + $this->_readDocumentSummaryInformation(); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->_dataSize = strlen($this->_data); + + // initialize + $this->_pos = 0; + $this->_codepage = 'CP1252'; + $this->_formats = array(); + $this->_objFonts = array(); + $this->_palette = array(); + $this->_sheets = array(); + $this->_externalBooks = array(); + $this->_ref = array(); + $this->_definedname = array(); + $this->_sst = array(); + $this->_drawingGroupData = ''; + $this->_xfIndex = ''; + $this->_mapCellXfIndex = array(); + $this->_mapCellStyleXfIndex = array(); + + // Parse Workbook Global Substream + while ($this->_pos < $this->_dataSize) { + $code = self::_GetInt2d($this->_data, $this->_pos); + + switch ($code) { + case self::XLS_Type_BOF: $this->_readBof(); break; + case self::XLS_Type_FILEPASS: $this->_readFilepass(); break; + case self::XLS_Type_CODEPAGE: $this->_readCodepage(); break; + case self::XLS_Type_DATEMODE: $this->_readDateMode(); break; + case self::XLS_Type_FONT: $this->_readFont(); break; + case self::XLS_Type_FORMAT: $this->_readFormat(); break; + case self::XLS_Type_XF: $this->_readXf(); break; + case self::XLS_Type_XFEXT: $this->_readXfExt(); break; + case self::XLS_Type_STYLE: $this->_readStyle(); break; + case self::XLS_Type_PALETTE: $this->_readPalette(); break; + case self::XLS_Type_SHEET: $this->_readSheet(); break; + case self::XLS_Type_EXTERNALBOOK: $this->_readExternalBook(); break; + case self::XLS_Type_EXTERNNAME: $this->_readExternName(); break; + case self::XLS_Type_EXTERNSHEET: $this->_readExternSheet(); break; + case self::XLS_Type_DEFINEDNAME: $this->_readDefinedName(); break; + case self::XLS_Type_MSODRAWINGGROUP: $this->_readMsoDrawingGroup(); break; + case self::XLS_Type_SST: $this->_readSst(); break; + case self::XLS_Type_EOF: $this->_readDefault(); break 2; + default: $this->_readDefault(); break; + } + } + + // Resolve indexed colors for font, fill, and border colors + // Cannot be resolved already in XF record, because PALETTE record comes afterwards + if (!$this->_readDataOnly) { + foreach ($this->_objFonts as $objFont) { + if (isset($objFont->colorIndex)) { + $color = self::_readColor($objFont->colorIndex,$this->_palette,$this->_version); + $objFont->getColor()->setRGB($color['rgb']); + } + } + + foreach ($this->_phpExcel->getCellXfCollection() as $objStyle) { + // fill start and end color + $fill = $objStyle->getFill(); + + if (isset($fill->startcolorIndex)) { + $startColor = self::_readColor($fill->startcolorIndex,$this->_palette,$this->_version); + $fill->getStartColor()->setRGB($startColor['rgb']); + } + + if (isset($fill->endcolorIndex)) { + $endColor = self::_readColor($fill->endcolorIndex,$this->_palette,$this->_version); + $fill->getEndColor()->setRGB($endColor['rgb']); + } + + // border colors + $top = $objStyle->getBorders()->getTop(); + $right = $objStyle->getBorders()->getRight(); + $bottom = $objStyle->getBorders()->getBottom(); + $left = $objStyle->getBorders()->getLeft(); + $diagonal = $objStyle->getBorders()->getDiagonal(); + + if (isset($top->colorIndex)) { + $borderTopColor = self::_readColor($top->colorIndex,$this->_palette,$this->_version); + $top->getColor()->setRGB($borderTopColor['rgb']); + } + + if (isset($right->colorIndex)) { + $borderRightColor = self::_readColor($right->colorIndex,$this->_palette,$this->_version); + $right->getColor()->setRGB($borderRightColor['rgb']); + } + + if (isset($bottom->colorIndex)) { + $borderBottomColor = self::_readColor($bottom->colorIndex,$this->_palette,$this->_version); + $bottom->getColor()->setRGB($borderBottomColor['rgb']); + } + + if (isset($left->colorIndex)) { + $borderLeftColor = self::_readColor($left->colorIndex,$this->_palette,$this->_version); + $left->getColor()->setRGB($borderLeftColor['rgb']); + } + + if (isset($diagonal->colorIndex)) { + $borderDiagonalColor = self::_readColor($diagonal->colorIndex,$this->_palette,$this->_version); + $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']); + } + } + } + + // treat MSODRAWINGGROUP records, workbook-level Escher + if (!$this->_readDataOnly && $this->_drawingGroupData) { + $escherWorkbook = new PHPExcel_Shared_Escher(); + $reader = new PHPExcel_Reader_Excel5_Escher($escherWorkbook); + $escherWorkbook = $reader->load($this->_drawingGroupData); + + // debug Escher stream + //$debug = new Debug_Escher(new PHPExcel_Shared_Escher()); + //$debug->load($this->_drawingGroupData); + } + + // Parse the individual sheets + foreach ($this->_sheets as $sheet) { + + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module + continue; + } + + // check if sheet should be skipped + if (isset($this->_loadSheetsOnly) && !in_array($sheet['name'], $this->_loadSheetsOnly)) { + continue; + } + + // add sheet to PHPExcel object + $this->_phpSheet = $this->_phpExcel->createSheet(); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula + // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet + // name in line with the formula, not the reverse + $this->_phpSheet->setTitle($sheet['name'],false); + $this->_phpSheet->setSheetState($sheet['sheetState']); + + $this->_pos = $sheet['offset']; + + // Initialize isFitToPages. May change after reading SHEETPR record. + $this->_isFitToPages = false; + + // Initialize drawingData + $this->_drawingData = ''; + + // Initialize objs + $this->_objs = array(); + + // Initialize shared formula parts + $this->_sharedFormulaParts = array(); + + // Initialize shared formulas + $this->_sharedFormulas = array(); + + // Initialize text objs + $this->_textObjects = array(); + + // Initialize cell annotations + $this->_cellNotes = array(); + $this->textObjRef = -1; + + while ($this->_pos <= $this->_dataSize - 4) { + $code = self::_GetInt2d($this->_data, $this->_pos); + + switch ($code) { + case self::XLS_Type_BOF: $this->_readBof(); break; + case self::XLS_Type_PRINTGRIDLINES: $this->_readPrintGridlines(); break; + case self::XLS_Type_DEFAULTROWHEIGHT: $this->_readDefaultRowHeight(); break; + case self::XLS_Type_SHEETPR: $this->_readSheetPr(); break; + case self::XLS_Type_HORIZONTALPAGEBREAKS: $this->_readHorizontalPageBreaks(); break; + case self::XLS_Type_VERTICALPAGEBREAKS: $this->_readVerticalPageBreaks(); break; + case self::XLS_Type_HEADER: $this->_readHeader(); break; + case self::XLS_Type_FOOTER: $this->_readFooter(); break; + case self::XLS_Type_HCENTER: $this->_readHcenter(); break; + case self::XLS_Type_VCENTER: $this->_readVcenter(); break; + case self::XLS_Type_LEFTMARGIN: $this->_readLeftMargin(); break; + case self::XLS_Type_RIGHTMARGIN: $this->_readRightMargin(); break; + case self::XLS_Type_TOPMARGIN: $this->_readTopMargin(); break; + case self::XLS_Type_BOTTOMMARGIN: $this->_readBottomMargin(); break; + case self::XLS_Type_PAGESETUP: $this->_readPageSetup(); break; + case self::XLS_Type_PROTECT: $this->_readProtect(); break; + case self::XLS_Type_SCENPROTECT: $this->_readScenProtect(); break; + case self::XLS_Type_OBJECTPROTECT: $this->_readObjectProtect(); break; + case self::XLS_Type_PASSWORD: $this->_readPassword(); break; + case self::XLS_Type_DEFCOLWIDTH: $this->_readDefColWidth(); break; + case self::XLS_Type_COLINFO: $this->_readColInfo(); break; + case self::XLS_Type_DIMENSION: $this->_readDefault(); break; + case self::XLS_Type_ROW: $this->_readRow(); break; + case self::XLS_Type_DBCELL: $this->_readDefault(); break; + case self::XLS_Type_RK: $this->_readRk(); break; + case self::XLS_Type_LABELSST: $this->_readLabelSst(); break; + case self::XLS_Type_MULRK: $this->_readMulRk(); break; + case self::XLS_Type_NUMBER: $this->_readNumber(); break; + case self::XLS_Type_FORMULA: $this->_readFormula(); break; + case self::XLS_Type_SHAREDFMLA: $this->_readSharedFmla(); break; + case self::XLS_Type_BOOLERR: $this->_readBoolErr(); break; + case self::XLS_Type_MULBLANK: $this->_readMulBlank(); break; + case self::XLS_Type_LABEL: $this->_readLabel(); break; + case self::XLS_Type_BLANK: $this->_readBlank(); break; + case self::XLS_Type_MSODRAWING: $this->_readMsoDrawing(); break; + case self::XLS_Type_OBJ: $this->_readObj(); break; + case self::XLS_Type_WINDOW2: $this->_readWindow2(); break; + case self::XLS_Type_PAGELAYOUTVIEW: $this->_readPageLayoutView(); break; + case self::XLS_Type_SCL: $this->_readScl(); break; + case self::XLS_Type_PANE: $this->_readPane(); break; + case self::XLS_Type_SELECTION: $this->_readSelection(); break; + case self::XLS_Type_MERGEDCELLS: $this->_readMergedCells(); break; + case self::XLS_Type_HYPERLINK: $this->_readHyperLink(); break; + case self::XLS_Type_DATAVALIDATIONS: $this->_readDataValidations(); break; + case self::XLS_Type_DATAVALIDATION: $this->_readDataValidation(); break; + case self::XLS_Type_SHEETLAYOUT: $this->_readSheetLayout(); break; + case self::XLS_Type_SHEETPROTECTION: $this->_readSheetProtection(); break; + case self::XLS_Type_RANGEPROTECTION: $this->_readRangeProtection(); break; + case self::XLS_Type_NOTE: $this->_readNote(); break; + //case self::XLS_Type_IMDATA: $this->_readImData(); break; + case self::XLS_Type_TXO: $this->_readTextObject(); break; + case self::XLS_Type_CONTINUE: $this->_readContinue(); break; + case self::XLS_Type_EOF: $this->_readDefault(); break 2; + default: $this->_readDefault(); break; + } + + } + + // treat MSODRAWING records, sheet-level Escher + if (!$this->_readDataOnly && $this->_drawingData) { + $escherWorksheet = new PHPExcel_Shared_Escher(); + $reader = new PHPExcel_Reader_Excel5_Escher($escherWorksheet); + $escherWorksheet = $reader->load($this->_drawingData); + + // debug Escher stream + //$debug = new Debug_Escher(new PHPExcel_Shared_Escher()); + //$debug->load($this->_drawingData); + + // get all spContainers in one long array, so they can be mapped to OBJ records + $allSpContainers = $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers(); + } + + // treat OBJ records + foreach ($this->_objs as $n => $obj) { +// echo '
Object reference is ',$n,'
'; +// var_dump($obj); +// echo '
'; + + // the first shape container never has a corresponding OBJ record, hence $n + 1 + if (isset($allSpContainers[$n + 1]) && is_object($allSpContainers[$n + 1])) { + $spContainer = $allSpContainers[$n + 1]; + + // we skip all spContainers that are a part of a group shape since we cannot yet handle those + if ($spContainer->getNestingLevel() > 1) { + continue; + } + + // calculate the width and height of the shape + list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($spContainer->getStartCoordinates()); + list($endColumn, $endRow) = PHPExcel_Cell::coordinateFromString($spContainer->getEndCoordinates()); + + $startOffsetX = $spContainer->getStartOffsetX(); + $startOffsetY = $spContainer->getStartOffsetY(); + $endOffsetX = $spContainer->getEndOffsetX(); + $endOffsetY = $spContainer->getEndOffsetY(); + + $width = PHPExcel_Shared_Excel5::getDistanceX($this->_phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); + $height = PHPExcel_Shared_Excel5::getDistanceY($this->_phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); + + // calculate offsetX and offsetY of the shape + $offsetX = $startOffsetX * PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, $startColumn) / 1024; + $offsetY = $startOffsetY * PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $startRow) / 256; + + switch ($obj['otObjType']) { + case 0x19: + // Note +// echo 'Cell Annotation Object
'; +// echo 'Object ID is ',$obj['idObjID'],'
'; +// + if (isset($this->_cellNotes[$obj['idObjID']])) { + $cellNote = $this->_cellNotes[$obj['idObjID']]; + + if (isset($this->_textObjects[$obj['idObjID']])) { + $textObject = $this->_textObjects[$obj['idObjID']]; + $this->_cellNotes[$obj['idObjID']]['objTextData'] = $textObject; + } + } + break; + + case 0x08: +// echo 'Picture Object
'; + // picture + + // get index to BSE entry (1-based) + $BSEindex = $spContainer->getOPT(0x0104); + $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); + $BSE = $BSECollection[$BSEindex - 1]; + $blipType = $BSE->getBlipType(); + + // need check because some blip types are not supported by Escher reader such as EMF + if ($blip = $BSE->getBlip()) { + $ih = imagecreatefromstring($blip->getData()); + $drawing = new PHPExcel_Worksheet_MemoryDrawing(); + $drawing->setImageResource($ih); + + // width, height, offsetX, offsetY + $drawing->setResizeProportional(false); + $drawing->setWidth($width); + $drawing->setHeight($height); + $drawing->setOffsetX($offsetX); + $drawing->setOffsetY($offsetY); + + switch ($blipType) { + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG: + $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG); + $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG); + break; + + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG: + $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG); + $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG); + break; + } + + $drawing->setWorksheet($this->_phpSheet); + $drawing->setCoordinates($spContainer->getStartCoordinates()); + } + + break; + + default: + // other object type + break; + + } + } + } + + // treat SHAREDFMLA records + if ($this->_version == self::XLS_BIFF8) { + foreach ($this->_sharedFormulaParts as $cell => $baseCell) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($cell); + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle()) ) { + $formula = $this->_getFormulaFromStructure($this->_sharedFormulas[$baseCell], $cell); + $this->_phpSheet->getCell($cell)->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + } + } + } + + if (!empty($this->_cellNotes)) { + foreach($this->_cellNotes as $note => $noteDetails) { + if (!isset($noteDetails['objTextData'])) { + if (isset($this->_textObjects[$note])) { + $textObject = $this->_textObjects[$note]; + $noteDetails['objTextData'] = $textObject; + } else { + $noteDetails['objTextData']['text'] = ''; + } + } +// echo 'Cell annotation ',$note,'
'; +// var_dump($noteDetails); +// echo '
'; + $cellAddress = str_replace('$','',$noteDetails['cellRef']); + $this->_phpSheet->getComment( $cellAddress ) + ->setAuthor( $noteDetails['author'] ) + ->setText($this->_parseRichText($noteDetails['objTextData']['text']) ); + } + } + } + + // add the named ranges (defined names) + foreach ($this->_definedname as $definedName) { + if ($definedName['isBuiltInName']) { + switch ($definedName['name']) { + + case pack('C', 0x06): + // print area + // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2 + $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? + + $extractedRanges = array(); + foreach ($ranges as $range) { + // $range should look like one of these + // Foo!$C$7:$J$66 + // Bar!$A$1:$IV$2 + + $explodes = explode('!', $range); // FIXME: what if sheetname contains exclamation mark? + $sheetName = trim($explodes[0], "'"); + + if (count($explodes) == 2) { + if (strpos($explodes[1], ':') === FALSE) { + $explodes[1] = $explodes[1] . ':' . $explodes[1]; + } + $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66 + } + } + if ($docSheet = $this->_phpExcel->getSheetByName($sheetName)) { + $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2 + } + break; + + case pack('C', 0x07): + // print titles (repeating rows) + // Assuming BIFF8, there are 3 cases + // 1. repeating rows + // formula looks like this: Sheet!$A$1:$IV$2 + // rows 1-2 repeat + // 2. repeating columns + // formula looks like this: Sheet!$A$1:$B$65536 + // columns A-B repeat + // 3. both repeating rows and repeating columns + // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2 + + $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? + + foreach ($ranges as $range) { + // $range should look like this one of these + // Sheet!$A$1:$B$65536 + // Sheet!$A$1:$IV$2 + + $explodes = explode('!', $range); + + if (count($explodes) == 2) { + if ($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) { + + $extractedRange = $explodes[1]; + $extractedRange = str_replace('$', '', $extractedRange); + + $coordinateStrings = explode(':', $extractedRange); + if (count($coordinateStrings) == 2) { + list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[0]); + list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[1]); + + if ($firstColumn == 'A' and $lastColumn == 'IV') { + // then we have repeating rows + $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($firstRow, $lastRow)); + } elseif ($firstRow == 1 and $lastRow == 65536) { + // then we have repeating columns + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($firstColumn, $lastColumn)); + } + } + } + } + } + break; + + } + } else { + // Extract range + $explodes = explode('!', $definedName['formula']); + + if (count($explodes) == 2) { + if (($docSheet = $this->_phpExcel->getSheetByName($explodes[0])) || + ($docSheet = $this->_phpExcel->getSheetByName(trim($explodes[0],"'")))) { + $extractedRange = $explodes[1]; + $extractedRange = str_replace('$', '', $extractedRange); + + $localOnly = ($definedName['scope'] == 0) ? false : true; + + $scope = ($definedName['scope'] == 0) ? + null : $this->_phpExcel->getSheetByName($this->_sheets[$definedName['scope'] - 1]['name']); + + $this->_phpExcel->addNamedRange( new PHPExcel_NamedRange((string)$definedName['name'], $docSheet, $extractedRange, $localOnly, $scope) ); + } + } else { + // Named Value + // TODO Provide support for named values + } + } + } + + return $this->_phpExcel; + } + + /** + * Read record data from stream, decrypting as required + * + * @param string $data Data stream to read from + * @param int $pos Position to start reading from + * @param int $length Record data length + * + * @return string Record data + */ + private function _readRecordData($data, $pos, $len) + { + $data = substr($data, $pos, $len); + + // File not encrypted, or record before encryption start point + if ($this->_encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->_encryptionStartPos) { + return $data; + } + + $recordData = ''; + if ($this->_encryption == self::MS_BIFF_CRYPTO_RC4) { + + $oldBlock = floor($this->_rc4Pos / self::REKEY_BLOCK); + $block = floor($pos / self::REKEY_BLOCK); + $endBlock = floor(($pos + $len) / self::REKEY_BLOCK); + + // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting + // at a point earlier in the current block, re-use it as we can save some time. + if ($block != $oldBlock || $pos < $this->_rc4Pos || !$this->_rc4Key) { + $this->_rc4Key = $this->_makeKey($block, $this->_md5Ctxt); + $step = $pos % self::REKEY_BLOCK; + } else { + $step = $pos - $this->_rc4Pos; + } + $this->_rc4Key->RC4(str_repeat("\0", $step)); + + // Decrypt record data (re-keying at the end of every block) + while ($block != $endBlock) { + $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK); + $recordData .= $this->_rc4Key->RC4(substr($data, 0, $step)); + $data = substr($data, $step); + $pos += $step; + $len -= $step; + $block++; + $this->_rc4Key = $this->_makeKey($block, $this->_md5Ctxt); + } + $recordData .= $this->_rc4Key->RC4(substr($data, 0, $len)); + + // Keep track of the position of this decryptor. + // We'll try and re-use it later if we can to speed things up + $this->_rc4Pos = $pos + $len; + + } elseif ($this->_encryption == self::MS_BIFF_CRYPTO_XOR) { + throw new PHPExcel_Reader_Exception('XOr encryption not supported'); + } + return $recordData; + } + + /** + * Use OLE reader to extract the relevant data streams from the OLE file + * + * @param string $pFilename + */ + private function _loadOLE($pFilename) + { + // OLE reader + $ole = new PHPExcel_Shared_OLERead(); + + // get excel data, + $res = $ole->read($pFilename); + // Get workbook data: workbook stream + sheet streams + $this->_data = $ole->getStream($ole->wrkbook); + + // Get summary information data + $this->_summaryInformation = $ole->getStream($ole->summaryInformation); + + // Get additional document summary information data + $this->_documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation); + + // Get user-defined property data +// $this->_userDefinedProperties = $ole->getUserDefinedProperties(); + } + + + /** + * Read summary information + */ + private function _readSummaryInformation() + { + if (!isset($this->_summaryInformation)) { + return; + } + + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + // offset: 2; size: 2; + // offset: 4; size: 2; OS version + // offset: 6; size: 2; OS indicator + // offset: 8; size: 16 + // offset: 24; size: 4; section count + $secCount = self::_GetInt4d($this->_summaryInformation, 24); + + // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 + // offset: 44; size: 4 + $secOffset = self::_GetInt4d($this->_summaryInformation, 44); + + // section header + // offset: $secOffset; size: 4; section length + $secLength = self::_GetInt4d($this->_summaryInformation, $secOffset); + + // offset: $secOffset+4; size: 4; property count + $countProperties = self::_GetInt4d($this->_summaryInformation, $secOffset+4); + + // initialize code page (used to resolve string values) + $codePage = 'CP1252'; + + // offset: ($secOffset+8); size: var + // loop through property decarations and properties + for ($i = 0; $i < $countProperties; ++$i) { + + // offset: ($secOffset+8) + (8 * $i); size: 4; property ID + $id = self::_GetInt4d($this->_summaryInformation, ($secOffset+8) + (8 * $i)); + + // Use value of property id as appropriate + // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48) + $offset = self::_GetInt4d($this->_summaryInformation, ($secOffset+12) + (8 * $i)); + + $type = self::_GetInt4d($this->_summaryInformation, $secOffset + $offset); + + // initialize property value + $value = null; + + // extract property value based on property type + switch ($type) { + case 0x02: // 2 byte signed integer + $value = self::_GetInt2d($this->_summaryInformation, $secOffset + 4 + $offset); + break; + + case 0x03: // 4 byte signed integer + $value = self::_GetInt4d($this->_summaryInformation, $secOffset + 4 + $offset); + break; + + case 0x13: // 4 byte unsigned integer + // not needed yet, fix later if necessary + break; + + case 0x1E: // null-terminated string prepended by dword string length + $byteLength = self::_GetInt4d($this->_summaryInformation, $secOffset + 4 + $offset); + $value = substr($this->_summaryInformation, $secOffset + 8 + $offset, $byteLength); + $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage); + $value = rtrim($value); + break; + + case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + // PHP-time + $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->_summaryInformation, $secOffset + 4 + $offset, 8)); + break; + + case 0x47: // Clipboard format + // not needed yet, fix later if necessary + break; + } + + switch ($id) { + case 0x01: // Code Page + $codePage = PHPExcel_Shared_CodePage::NumberToName($value); + break; + + case 0x02: // Title + $this->_phpExcel->getProperties()->setTitle($value); + break; + + case 0x03: // Subject + $this->_phpExcel->getProperties()->setSubject($value); + break; + + case 0x04: // Author (Creator) + $this->_phpExcel->getProperties()->setCreator($value); + break; + + case 0x05: // Keywords + $this->_phpExcel->getProperties()->setKeywords($value); + break; + + case 0x06: // Comments (Description) + $this->_phpExcel->getProperties()->setDescription($value); + break; + + case 0x07: // Template + // Not supported by PHPExcel + break; + + case 0x08: // Last Saved By (LastModifiedBy) + $this->_phpExcel->getProperties()->setLastModifiedBy($value); + break; + + case 0x09: // Revision + // Not supported by PHPExcel + break; + + case 0x0A: // Total Editing Time + // Not supported by PHPExcel + break; + + case 0x0B: // Last Printed + // Not supported by PHPExcel + break; + + case 0x0C: // Created Date/Time + $this->_phpExcel->getProperties()->setCreated($value); + break; + + case 0x0D: // Modified Date/Time + $this->_phpExcel->getProperties()->setModified($value); + break; + + case 0x0E: // Number of Pages + // Not supported by PHPExcel + break; + + case 0x0F: // Number of Words + // Not supported by PHPExcel + break; + + case 0x10: // Number of Characters + // Not supported by PHPExcel + break; + + case 0x11: // Thumbnail + // Not supported by PHPExcel + break; + + case 0x12: // Name of creating application + // Not supported by PHPExcel + break; + + case 0x13: // Security + // Not supported by PHPExcel + break; + + } + } + } + + + /** + * Read additional document summary information + */ + private function _readDocumentSummaryInformation() + { + if (!isset($this->_documentSummaryInformation)) { + return; + } + + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + // offset: 2; size: 2; + // offset: 4; size: 2; OS version + // offset: 6; size: 2; OS indicator + // offset: 8; size: 16 + // offset: 24; size: 4; section count + $secCount = self::_GetInt4d($this->_documentSummaryInformation, 24); +// echo '$secCount = ',$secCount,'
'; + + // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae + // offset: 44; size: 4; first section offset + $secOffset = self::_GetInt4d($this->_documentSummaryInformation, 44); +// echo '$secOffset = ',$secOffset,'
'; + + // section header + // offset: $secOffset; size: 4; section length + $secLength = self::_GetInt4d($this->_documentSummaryInformation, $secOffset); +// echo '$secLength = ',$secLength,'
'; + + // offset: $secOffset+4; size: 4; property count + $countProperties = self::_GetInt4d($this->_documentSummaryInformation, $secOffset+4); +// echo '$countProperties = ',$countProperties,'
'; + + // initialize code page (used to resolve string values) + $codePage = 'CP1252'; + + // offset: ($secOffset+8); size: var + // loop through property decarations and properties + for ($i = 0; $i < $countProperties; ++$i) { +// echo 'Property ',$i,'
'; + // offset: ($secOffset+8) + (8 * $i); size: 4; property ID + $id = self::_GetInt4d($this->_documentSummaryInformation, ($secOffset+8) + (8 * $i)); +// echo 'ID is ',$id,'
'; + + // Use value of property id as appropriate + // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48) + $offset = self::_GetInt4d($this->_documentSummaryInformation, ($secOffset+12) + (8 * $i)); + + $type = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + $offset); +// echo 'Type is ',$type,', '; + + // initialize property value + $value = null; + + // extract property value based on property type + switch ($type) { + case 0x02: // 2 byte signed integer + $value = self::_GetInt2d($this->_documentSummaryInformation, $secOffset + 4 + $offset); + break; + + case 0x03: // 4 byte signed integer + $value = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + 4 + $offset); + break; + + case 0x0B: // Boolean + $value = self::_GetInt2d($this->_documentSummaryInformation, $secOffset + 4 + $offset); + $value = ($value == 0 ? false : true); + break; + + case 0x13: // 4 byte unsigned integer + // not needed yet, fix later if necessary + break; + + case 0x1E: // null-terminated string prepended by dword string length + $byteLength = self::_GetInt4d($this->_documentSummaryInformation, $secOffset + 4 + $offset); + $value = substr($this->_documentSummaryInformation, $secOffset + 8 + $offset, $byteLength); + $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage); + $value = rtrim($value); + break; + + case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + // PHP-Time + $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->_documentSummaryInformation, $secOffset + 4 + $offset, 8)); + break; + + case 0x47: // Clipboard format + // not needed yet, fix later if necessary + break; + } + + switch ($id) { + case 0x01: // Code Page + $codePage = PHPExcel_Shared_CodePage::NumberToName($value); + break; + + case 0x02: // Category + $this->_phpExcel->getProperties()->setCategory($value); + break; + + case 0x03: // Presentation Target + // Not supported by PHPExcel + break; + + case 0x04: // Bytes + // Not supported by PHPExcel + break; + + case 0x05: // Lines + // Not supported by PHPExcel + break; + + case 0x06: // Paragraphs + // Not supported by PHPExcel + break; + + case 0x07: // Slides + // Not supported by PHPExcel + break; + + case 0x08: // Notes + // Not supported by PHPExcel + break; + + case 0x09: // Hidden Slides + // Not supported by PHPExcel + break; + + case 0x0A: // MM Clips + // Not supported by PHPExcel + break; + + case 0x0B: // Scale Crop + // Not supported by PHPExcel + break; + + case 0x0C: // Heading Pairs + // Not supported by PHPExcel + break; + + case 0x0D: // Titles of Parts + // Not supported by PHPExcel + break; + + case 0x0E: // Manager + $this->_phpExcel->getProperties()->setManager($value); + break; + + case 0x0F: // Company + $this->_phpExcel->getProperties()->setCompany($value); + break; + + case 0x10: // Links up-to-date + // Not supported by PHPExcel + break; + + } + } + } + + + /** + * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. + */ + private function _readDefault() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); +// $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + } + + + /** + * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, + * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. + */ + private function _readNote() + { +// echo 'Read Cell Annotation
'; + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + $cellAddress = $this->_readBIFF8CellAddress(substr($recordData, 0, 4)); + if ($this->_version == self::XLS_BIFF8) { + $noteObjID = self::_GetInt2d($recordData, 6); + $noteAuthor = self::_readUnicodeStringLong(substr($recordData, 8)); + $noteAuthor = $noteAuthor['value']; +// echo 'Note Address=',$cellAddress,'
'; +// echo 'Note Object ID=',$noteObjID,'
'; +// echo 'Note Author=',$noteAuthor,'
'; +// + $this->_cellNotes[$noteObjID] = array('cellRef' => $cellAddress, + 'objectID' => $noteObjID, + 'author' => $noteAuthor + ); + } else { + $extension = false; + if ($cellAddress == '$B$65536') { + // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation + // note from the previous cell annotation. We're not yet handling this, so annotations longer than the + // max 2048 bytes will probably throw a wobbly. + $row = self::_GetInt2d($recordData, 0); + $extension = true; + $cellAddress = array_pop(array_keys($this->_phpSheet->getComments())); + } +// echo 'Note Address=',$cellAddress,'
'; + + $cellAddress = str_replace('$','',$cellAddress); + $noteLength = self::_GetInt2d($recordData, 4); + $noteText = trim(substr($recordData, 6)); +// echo 'Note Length=',$noteLength,'
'; +// echo 'Note Text=',$noteText,'
'; + + if ($extension) { + // Concatenate this extension with the currently set comment for the cell + $comment = $this->_phpSheet->getComment( $cellAddress ); + $commentText = $comment->getText()->getPlainText(); + $comment->setText($this->_parseRichText($commentText.$noteText) ); + } else { + // Set comment for the cell + $this->_phpSheet->getComment( $cellAddress ) +// ->setAuthor( $author ) + ->setText($this->_parseRichText($noteText) ); + } + } + + } + + + /** + * The TEXT Object record contains the text associated with a cell annotation. + */ + private function _readTextObject() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // recordData consists of an array of subrecords looking like this: + // grbit: 2 bytes; Option Flags + // rot: 2 bytes; rotation + // cchText: 2 bytes; length of the text (in the first continue record) + // cbRuns: 2 bytes; length of the formatting (in the second continue record) + // followed by the continuation records containing the actual text and formatting + $grbitOpts = self::_GetInt2d($recordData, 0); + $rot = self::_GetInt2d($recordData, 2); + $cchText = self::_GetInt2d($recordData, 10); + $cbRuns = self::_GetInt2d($recordData, 12); + $text = $this->_getSplicedRecordData(); + + $this->_textObjects[$this->textObjRef] = array( + 'text' => substr($text["recordData"],$text["spliceOffsets"][0]+1,$cchText), + 'format' => substr($text["recordData"],$text["spliceOffsets"][1],$cbRuns), + 'alignment' => $grbitOpts, + 'rotation' => $rot + ); + +// echo '_readTextObject()
'; +// var_dump($this->_textObjects[$this->textObjRef]); +// echo '
'; + } + + + /** + * Read BOF + */ + private function _readBof() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = substr($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 2; size: 2; type of the following data + $substreamType = self::_GetInt2d($recordData, 2); + + switch ($substreamType) { + case self::XLS_WorkbookGlobals: + $version = self::_GetInt2d($recordData, 0); + if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) { + throw new PHPExcel_Reader_Exception('Cannot read this Excel file. Version is too old.'); + } + $this->_version = $version; + break; + + case self::XLS_Worksheet: + // do not use this version information for anything + // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream + break; + + default: + // substream, e.g. chart + // just skip the entire substream + do { + $code = self::_GetInt2d($this->_data, $this->_pos); + $this->_readDefault(); + } while ($code != self::XLS_Type_EOF && $this->_pos < $this->_dataSize); + break; + } + } + + + /** + * FILEPASS + * + * This record is part of the File Protection Block. It + * contains information about the read/write password of the + * file. All record contents following this record will be + * encrypted. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + * + * The decryption functions and objects used from here on in + * are based on the source of Spreadsheet-ParseExcel: + * http://search.cpan.org/~jmcnamara/Spreadsheet-ParseExcel/ + */ + private function _readFilepass() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + + if ($length != 54) { + throw new PHPExcel_Reader_Exception('Unexpected file pass record length'); + } + + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_verifyPassword( + 'VelvetSweatshop', + substr($recordData, 6, 16), + substr($recordData, 22, 16), + substr($recordData, 38, 16), + $this->_md5Ctxt + )) { + throw new PHPExcel_Reader_Exception('Decryption password incorrect'); + } + + $this->_encryption = self::MS_BIFF_CRYPTO_RC4; + + // Decryption required from the record after next onwards + $this->_encryptionStartPos = $this->_pos + self::_GetInt2d($this->_data, $this->_pos + 2); + } + + /** + * Make an RC4 decryptor for the given block + * + * @var int $block Block for which to create decrypto + * @var string $valContext MD5 context state + * + * @return PHPExcel_Reader_Excel5_RC4 + */ + private function _makeKey($block, $valContext) + { + $pwarray = str_repeat("\0", 64); + + for ($i = 0; $i < 5; $i++) { + $pwarray[$i] = $valContext[$i]; + } + + $pwarray[5] = chr($block & 0xff); + $pwarray[6] = chr(($block >> 8) & 0xff); + $pwarray[7] = chr(($block >> 16) & 0xff); + $pwarray[8] = chr(($block >> 24) & 0xff); + + $pwarray[9] = "\x80"; + $pwarray[56] = "\x48"; + + $md5 = new PHPExcel_Reader_Excel5_MD5(); + $md5->add($pwarray); + + $s = $md5->getContext(); + return new PHPExcel_Reader_Excel5_RC4($s); + } + + /** + * Verify RC4 file password + * + * @var string $password Password to check + * @var string $docid Document id + * @var string $salt_data Salt data + * @var string $hashedsalt_data Hashed salt data + * @var string &$valContext Set to the MD5 context of the value + * + * @return bool Success + */ + private function _verifyPassword($password, $docid, $salt_data, $hashedsalt_data, &$valContext) + { + $pwarray = str_repeat("\0", 64); + + for ($i = 0; $i < strlen($password); $i++) { + $o = ord(substr($password, $i, 1)); + $pwarray[2 * $i] = chr($o & 0xff); + $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xff); + } + $pwarray[2 * $i] = chr(0x80); + $pwarray[56] = chr(($i << 4) & 0xff); + + $md5 = new PHPExcel_Reader_Excel5_MD5(); + $md5->add($pwarray); + + $mdContext1 = $md5->getContext(); + + $offset = 0; + $keyoffset = 0; + $tocopy = 5; + + $md5->reset(); + + while ($offset != 16) { + if ((64 - $offset) < 5) { + $tocopy = 64 - $offset; + } + + for ($i = 0; $i <= $tocopy; $i++) { + $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i]; + } + + $offset += $tocopy; + + if ($offset == 64) { + $md5->add($pwarray); + $keyoffset = $tocopy; + $tocopy = 5 - $tocopy; + $offset = 0; + continue; + } + + $keyoffset = 0; + $tocopy = 5; + for ($i = 0; $i < 16; $i++) { + $pwarray[$offset + $i] = $docid[$i]; + } + $offset += 16; + } + + $pwarray[16] = "\x80"; + for ($i = 0; $i < 47; $i++) { + $pwarray[17 + $i] = "\0"; + } + $pwarray[56] = "\x80"; + $pwarray[57] = "\x0a"; + + $md5->add($pwarray); + $valContext = $md5->getContext(); + + $key = $this->_makeKey(0, $valContext); + + $salt = $key->RC4($salt_data); + $hashedsalt = $key->RC4($hashedsalt_data); + + $salt .= "\x80" . str_repeat("\0", 47); + $salt[56] = "\x80"; + + $md5->reset(); + $md5->add($salt); + $mdContext2 = $md5->getContext(); + + return $mdContext2 == $hashedsalt; + } + + /** + * CODEPAGE + * + * This record stores the text encoding used to write byte + * strings, stored as MS Windows code page identifier. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readCodepage() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; code page identifier + $codepage = self::_GetInt2d($recordData, 0); + + $this->_codepage = PHPExcel_Shared_CodePage::NumberToName($codepage); + } + + + /** + * DATEMODE + * + * This record specifies the base date for displaying date + * values. All dates are stored as count of days past this + * base date. In BIFF2-BIFF4 this record is part of the + * Calculation Settings Block. In BIFF5-BIFF8 it is + * stored in the Workbook Globals Substream. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readDateMode() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; 0 = base 1900, 1 = base 1904 + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900); + if (ord($recordData{0}) == 1) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904); + } + } + + + /** + * Read a FONT record + */ + private function _readFont() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + $objFont = new PHPExcel_Style_Font(); + + // offset: 0; size: 2; height of the font (in twips = 1/20 of a point) + $size = self::_GetInt2d($recordData, 0); + $objFont->setSize($size / 20); + + // offset: 2; size: 2; option flags + // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8) + // bit: 1; mask 0x0002; italic + $isItalic = (0x0002 & self::_GetInt2d($recordData, 2)) >> 1; + if ($isItalic) $objFont->setItalic(true); + + // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8) + // bit: 3; mask 0x0008; strike + $isStrike = (0x0008 & self::_GetInt2d($recordData, 2)) >> 3; + if ($isStrike) $objFont->setStrikethrough(true); + + // offset: 4; size: 2; colour index + $colorIndex = self::_GetInt2d($recordData, 4); + $objFont->colorIndex = $colorIndex; + + // offset: 6; size: 2; font weight + $weight = self::_GetInt2d($recordData, 6); + switch ($weight) { + case 0x02BC: + $objFont->setBold(true); + break; + } + + // offset: 8; size: 2; escapement type + $escapement = self::_GetInt2d($recordData, 8); + switch ($escapement) { + case 0x0001: + $objFont->setSuperScript(true); + break; + case 0x0002: + $objFont->setSubScript(true); + break; + } + + // offset: 10; size: 1; underline type + $underlineType = ord($recordData{10}); + switch ($underlineType) { + case 0x00: + break; // no underline + case 0x01: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + break; + case 0x02: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLE); + break; + case 0x21: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING); + break; + case 0x22: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING); + break; + } + + // offset: 11; size: 1; font family + // offset: 12; size: 1; character set + // offset: 13; size: 1; not used + // offset: 14; size: var; font name + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringShort(substr($recordData, 14)); + } else { + $string = $this->_readByteStringShort(substr($recordData, 14)); + } + $objFont->setName($string['value']); + + $this->_objFonts[] = $objFont; + } + } + + + /** + * FORMAT + * + * This record contains information about a number format. + * All FORMAT records occur together in a sequential list. + * + * In BIFF2-BIFF4 other records referencing a FORMAT record + * contain a zero-based index into this list. From BIFF5 on + * the FORMAT record contains the index itself that will be + * used by other records. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readFormat() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + $indexCode = self::_GetInt2d($recordData, 0); + + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringLong(substr($recordData, 2)); + } else { + // BIFF7 + $string = $this->_readByteStringShort(substr($recordData, 2)); + } + + $formatString = $string['value']; + $this->_formats[$indexCode] = $formatString; + } + } + + + /** + * XF - Extended Format + * + * This record contains formatting information for cells, rows, columns or styles. + * According to http://support.microsoft.com/kb/147732 there are always at least 15 cell style XF + * and 1 cell XF. + * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF + * and XF record 15 is a cell XF + * We only read the first cell style XF and skip the remaining cell style XF records + * We read all cell XF records. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readXf() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + $objStyle = new PHPExcel_Style(); + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; Index to FONT record + if (self::_GetInt2d($recordData, 0) < 4) { + $fontIndex = self::_GetInt2d($recordData, 0); + } else { + // this has to do with that index 4 is omitted in all BIFF versions for some strange reason + // check the OpenOffice documentation of the FONT record + $fontIndex = self::_GetInt2d($recordData, 0) - 1; + } + $objStyle->setFont($this->_objFonts[$fontIndex]); + + // offset: 2; size: 2; Index to FORMAT record + $numberFormatIndex = self::_GetInt2d($recordData, 2); + if (isset($this->_formats[$numberFormatIndex])) { + // then we have user-defined format code + $numberformat = array('code' => $this->_formats[$numberFormatIndex]); + } elseif (($code = PHPExcel_Style_NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') { + // then we have built-in format code + $numberformat = array('code' => $code); + } else { + // we set the general format code + $numberformat = array('code' => 'General'); + } + $objStyle->getNumberFormat()->setFormatCode($numberformat['code']); + + // offset: 4; size: 2; XF type, cell protection, and parent style XF + // bit 2-0; mask 0x0007; XF_TYPE_PROT + $xfTypeProt = self::_GetInt2d($recordData, 4); + // bit 0; mask 0x01; 1 = cell is locked + $isLocked = (0x01 & $xfTypeProt) >> 0; + $objStyle->getProtection()->setLocked($isLocked ? + PHPExcel_Style_Protection::PROTECTION_INHERIT : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + + // bit 1; mask 0x02; 1 = Formula is hidden + $isHidden = (0x02 & $xfTypeProt) >> 1; + $objStyle->getProtection()->setHidden($isHidden ? + PHPExcel_Style_Protection::PROTECTION_PROTECTED : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + + // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF + $isCellStyleXf = (0x04 & $xfTypeProt) >> 2; + + // offset: 6; size: 1; Alignment and text break + // bit 2-0, mask 0x07; horizontal alignment + $horAlign = (0x07 & ord($recordData{6})) >> 0; + switch ($horAlign) { + case 0: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_GENERAL); + break; + case 1: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); + break; + case 2: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); + break; + case 3: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + break; + case 4: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_FILL); + break; + case 5: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY); + break; + case 6: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS); + break; + } + // bit 3, mask 0x08; wrap text + $wrapText = (0x08 & ord($recordData{6})) >> 3; + switch ($wrapText) { + case 0: + $objStyle->getAlignment()->setWrapText(false); + break; + case 1: + $objStyle->getAlignment()->setWrapText(true); + break; + } + // bit 6-4, mask 0x70; vertical alignment + $vertAlign = (0x70 & ord($recordData{6})) >> 4; + switch ($vertAlign) { + case 0: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); + break; + case 1: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); + break; + case 2: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_BOTTOM); + break; + case 3: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_JUSTIFY); + break; + } + + if ($this->_version == self::XLS_BIFF8) { + // offset: 7; size: 1; XF_ROTATION: Text rotation angle + $angle = ord($recordData{7}); + $rotation = 0; + if ($angle <= 90) { + $rotation = $angle; + } else if ($angle <= 180) { + $rotation = 90 - $angle; + } else if ($angle == 255) { + $rotation = -165; + } + $objStyle->getAlignment()->setTextRotation($rotation); + + // offset: 8; size: 1; Indentation, shrink to cell size, and text direction + // bit: 3-0; mask: 0x0F; indent level + $indent = (0x0F & ord($recordData{8})) >> 0; + $objStyle->getAlignment()->setIndent($indent); + + // bit: 4; mask: 0x10; 1 = shrink content to fit into cell + $shrinkToFit = (0x10 & ord($recordData{8})) >> 4; + switch ($shrinkToFit) { + case 0: + $objStyle->getAlignment()->setShrinkToFit(false); + break; + case 1: + $objStyle->getAlignment()->setShrinkToFit(true); + break; + } + + // offset: 9; size: 1; Flags used for attribute groups + + // offset: 10; size: 4; Cell border lines and background area + // bit: 3-0; mask: 0x0000000F; left style + if ($bordersLeftStyle = self::_mapBorderStyle((0x0000000F & self::_GetInt4d($recordData, 10)) >> 0)) { + $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle); + } + // bit: 7-4; mask: 0x000000F0; right style + if ($bordersRightStyle = self::_mapBorderStyle((0x000000F0 & self::_GetInt4d($recordData, 10)) >> 4)) { + $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle); + } + // bit: 11-8; mask: 0x00000F00; top style + if ($bordersTopStyle = self::_mapBorderStyle((0x00000F00 & self::_GetInt4d($recordData, 10)) >> 8)) { + $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle); + } + // bit: 15-12; mask: 0x0000F000; bottom style + if ($bordersBottomStyle = self::_mapBorderStyle((0x0000F000 & self::_GetInt4d($recordData, 10)) >> 12)) { + $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle); + } + // bit: 22-16; mask: 0x007F0000; left color + $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::_GetInt4d($recordData, 10)) >> 16; + + // bit: 29-23; mask: 0x3F800000; right color + $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::_GetInt4d($recordData, 10)) >> 23; + + // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom + $diagonalDown = (0x40000000 & self::_GetInt4d($recordData, 10)) >> 30 ? + true : false; + + // bit: 31; mask: 0x80000000; 1 = diagonal line from bottom left to top right + $diagonalUp = (0x80000000 & self::_GetInt4d($recordData, 10)) >> 31 ? + true : false; + + if ($diagonalUp == false && $diagonalDown == false) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE); + } elseif ($diagonalUp == true && $diagonalDown == false) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP); + } elseif ($diagonalUp == false && $diagonalDown == true) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN); + } elseif ($diagonalUp == true && $diagonalDown == true) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH); + } + + // offset: 14; size: 4; + // bit: 6-0; mask: 0x0000007F; top color + $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::_GetInt4d($recordData, 14)) >> 0; + + // bit: 13-7; mask: 0x00003F80; bottom color + $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::_GetInt4d($recordData, 14)) >> 7; + + // bit: 20-14; mask: 0x001FC000; diagonal color + $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::_GetInt4d($recordData, 14)) >> 14; + + // bit: 24-21; mask: 0x01E00000; diagonal style + if ($bordersDiagonalStyle = self::_mapBorderStyle((0x01E00000 & self::_GetInt4d($recordData, 14)) >> 21)) { + $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle); + } + + // bit: 31-26; mask: 0xFC000000 fill pattern + if ($fillType = self::_mapFillPattern((0xFC000000 & self::_GetInt4d($recordData, 14)) >> 26)) { + $objStyle->getFill()->setFillType($fillType); + } + // offset: 18; size: 2; pattern and background colour + // bit: 6-0; mask: 0x007F; color index for pattern color + $objStyle->getFill()->startcolorIndex = (0x007F & self::_GetInt2d($recordData, 18)) >> 0; + + // bit: 13-7; mask: 0x3F80; color index for pattern background + $objStyle->getFill()->endcolorIndex = (0x3F80 & self::_GetInt2d($recordData, 18)) >> 7; + } else { + // BIFF5 + + // offset: 7; size: 1; Text orientation and flags + $orientationAndFlags = ord($recordData{7}); + + // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation + $xfOrientation = (0x03 & $orientationAndFlags) >> 0; + switch ($xfOrientation) { + case 0: + $objStyle->getAlignment()->setTextRotation(0); + break; + case 1: + $objStyle->getAlignment()->setTextRotation(-165); + break; + case 2: + $objStyle->getAlignment()->setTextRotation(90); + break; + case 3: + $objStyle->getAlignment()->setTextRotation(-90); + break; + } + + // offset: 8; size: 4; cell border lines and background area + $borderAndBackground = self::_GetInt4d($recordData, 8); + + // bit: 6-0; mask: 0x0000007F; color index for pattern color + $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0; + + // bit: 13-7; mask: 0x00003F80; color index for pattern background + $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7; + + // bit: 21-16; mask: 0x003F0000; fill pattern + $objStyle->getFill()->setFillType(self::_mapFillPattern((0x003F0000 & $borderAndBackground) >> 16)); + + // bit: 24-22; mask: 0x01C00000; bottom line style + $objStyle->getBorders()->getBottom()->setBorderStyle(self::_mapBorderStyle((0x01C00000 & $borderAndBackground) >> 22)); + + // bit: 31-25; mask: 0xFE000000; bottom line color + $objStyle->getBorders()->getBottom()->colorIndex = (0xFE000000 & $borderAndBackground) >> 25; + + // offset: 12; size: 4; cell border lines + $borderLines = self::_GetInt4d($recordData, 12); + + // bit: 2-0; mask: 0x00000007; top line style + $objStyle->getBorders()->getTop()->setBorderStyle(self::_mapBorderStyle((0x00000007 & $borderLines) >> 0)); + + // bit: 5-3; mask: 0x00000038; left line style + $objStyle->getBorders()->getLeft()->setBorderStyle(self::_mapBorderStyle((0x00000038 & $borderLines) >> 3)); + + // bit: 8-6; mask: 0x000001C0; right line style + $objStyle->getBorders()->getRight()->setBorderStyle(self::_mapBorderStyle((0x000001C0 & $borderLines) >> 6)); + + // bit: 15-9; mask: 0x0000FE00; top line color index + $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9; + + // bit: 22-16; mask: 0x007F0000; left line color index + $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16; + + // bit: 29-23; mask: 0x3F800000; right line color index + $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23; + } + + // add cellStyleXf or cellXf and update mapping + if ($isCellStyleXf) { + // we only read one style XF record which is always the first + if ($this->_xfIndex == 0) { + $this->_phpExcel->addCellStyleXf($objStyle); + $this->_mapCellStyleXfIndex[$this->_xfIndex] = 0; + } + } else { + // we read all cell XF records + $this->_phpExcel->addCellXf($objStyle); + $this->_mapCellXfIndex[$this->_xfIndex] = count($this->_phpExcel->getCellXfCollection()) - 1; + } + + // update XF index for when we read next record + ++$this->_xfIndex; + } + } + + + /** + * + */ + private function _readXfExt() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; 0x087D = repeated header + + // offset: 2; size: 2 + + // offset: 4; size: 8; not used + + // offset: 12; size: 2; record version + + // offset: 14; size: 2; index to XF record which this record modifies + $ixfe = self::_GetInt2d($recordData, 14); + + // offset: 16; size: 2; not used + + // offset: 18; size: 2; number of extension properties that follow + $cexts = self::_GetInt2d($recordData, 18); + + // start reading the actual extension data + $offset = 20; + while ($offset < $length) { + // extension type + $extType = self::_GetInt2d($recordData, $offset); + + // extension length + $cb = self::_GetInt2d($recordData, $offset + 2); + + // extension data + $extData = substr($recordData, $offset + 4, $cb); + + switch ($extType) { + case 4: // fill start color + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $fill = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFill(); + $fill->getStartColor()->setRGB($rgb); + unset($fill->startcolorIndex); // normal color index does not apply, discard + } + } + break; + + case 5: // fill end color + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $fill = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFill(); + $fill->getEndColor()->setRGB($rgb); + unset($fill->endcolorIndex); // normal color index does not apply, discard + } + } + break; + + case 7: // border color top + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $top = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getTop(); + $top->getColor()->setRGB($rgb); + unset($top->colorIndex); // normal color index does not apply, discard + } + } + break; + + case 8: // border color bottom + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $bottom = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getBottom(); + $bottom->getColor()->setRGB($rgb); + unset($bottom->colorIndex); // normal color index does not apply, discard + } + } + break; + + case 9: // border color left + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $left = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getLeft(); + $left->getColor()->setRGB($rgb); + unset($left->colorIndex); // normal color index does not apply, discard + } + } + break; + + case 10: // border color right + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $right = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getRight(); + $right->getColor()->setRGB($rgb); + unset($right->colorIndex); // normal color index does not apply, discard + } + } + break; + + case 11: // border color diagonal + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $diagonal = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getBorders()->getDiagonal(); + $diagonal->getColor()->setRGB($rgb); + unset($diagonal->colorIndex); // normal color index does not apply, discard + } + } + break; + + case 13: // font color + $xclfType = self::_GetInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if ( isset($this->_mapCellXfIndex[$ixfe]) ) { + $font = $this->_phpExcel->getCellXfByIndex($this->_mapCellXfIndex[$ixfe])->getFont(); + $font->getColor()->setRGB($rgb); + unset($font->colorIndex); // normal color index does not apply, discard + } + } + break; + } + + $offset += $cb; + } + } + + } + + + /** + * Read STYLE record + */ + private function _readStyle() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; index to XF record and flag for built-in style + $ixfe = self::_GetInt2d($recordData, 0); + + // bit: 11-0; mask 0x0FFF; index to XF record + $xfIndex = (0x0FFF & $ixfe) >> 0; + + // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style + $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15); + + if ($isBuiltIn) { + // offset: 2; size: 1; identifier for built-in style + $builtInId = ord($recordData{2}); + + switch ($builtInId) { + case 0x00: + // currently, we are not using this for anything + break; + + default: + break; + } + + } else { + // user-defined; not supported by PHPExcel + } + } + } + + + /** + * Read PALETTE record + */ + private function _readPalette() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; number of following colors + $nm = self::_GetInt2d($recordData, 0); + + // list of RGB colors + for ($i = 0; $i < $nm; ++$i) { + $rgb = substr($recordData, 2 + 4 * $i, 4); + $this->_palette[] = self::_readRGB($rgb); + } + } + } + + + /** + * SHEET + * + * This record is located in the Workbook Globals + * Substream and represents a sheet inside the workbook. + * One SHEET record is written for each sheet. It stores the + * sheet name and a stream offset to the BOF record of the + * respective Sheet Substream within the Workbook Stream. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readSheet() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // offset: 0; size: 4; absolute stream position of the BOF record of the sheet + // NOTE: not encrypted + $rec_offset = self::_GetInt4d($this->_data, $this->_pos + 4); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 4; size: 1; sheet state + switch (ord($recordData{4})) { + case 0x00: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; break; + case 0x01: $sheetState = PHPExcel_Worksheet::SHEETSTATE_HIDDEN; break; + case 0x02: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN; break; + default: $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; break; + } + + // offset: 5; size: 1; sheet type + $sheetType = ord($recordData{5}); + + // offset: 6; size: var; sheet name + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringShort(substr($recordData, 6)); + $rec_name = $string['value']; + } elseif ($this->_version == self::XLS_BIFF7) { + $string = $this->_readByteStringShort(substr($recordData, 6)); + $rec_name = $string['value']; + } + + $this->_sheets[] = array( + 'name' => $rec_name, + 'offset' => $rec_offset, + 'sheetState' => $sheetState, + 'sheetType' => $sheetType, + ); + } + + + /** + * Read EXTERNALBOOK record + */ + private function _readExternalBook() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset within record data + $offset = 0; + + // there are 4 types of records + if (strlen($recordData) > 4) { + // external reference + // offset: 0; size: 2; number of sheet names ($nm) + $nm = self::_GetInt2d($recordData, 0); + $offset += 2; + + // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length) + $encodedUrlString = self::_readUnicodeStringLong(substr($recordData, 2)); + $offset += $encodedUrlString['size']; + + // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length) + $externalSheetNames = array(); + for ($i = 0; $i < $nm; ++$i) { + $externalSheetNameString = self::_readUnicodeStringLong(substr($recordData, $offset)); + $externalSheetNames[] = $externalSheetNameString['value']; + $offset += $externalSheetNameString['size']; + } + + // store the record data + $this->_externalBooks[] = array( + 'type' => 'external', + 'encodedUrl' => $encodedUrlString['value'], + 'externalSheetNames' => $externalSheetNames, + ); + + } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) { + // internal reference + // offset: 0; size: 2; number of sheet in this document + // offset: 2; size: 2; 0x01 0x04 + $this->_externalBooks[] = array( + 'type' => 'internal', + ); + } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) { + // add-in function + // offset: 0; size: 2; 0x0001 + $this->_externalBooks[] = array( + 'type' => 'addInFunction', + ); + } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) { + // DDE links, OLE links + // offset: 0; size: 2; 0x0000 + // offset: 2; size: var; encoded source document name + $this->_externalBooks[] = array( + 'type' => 'DDEorOLE', + ); + } + } + + + /** + * Read EXTERNNAME record. + */ + private function _readExternName() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // external sheet references provided for named cells + if ($this->_version == self::XLS_BIFF8) { + // offset: 0; size: 2; options + $options = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; + + // offset: 4; size: 2; not used + + // offset: 6; size: var + $nameString = self::_readUnicodeStringShort(substr($recordData, 6)); + + // offset: var; size: var; formula data + $offset = 6 + $nameString['size']; + $formula = $this->_getFormulaFromStructure(substr($recordData, $offset)); + + $this->_externalNames[] = array( + 'name' => $nameString['value'], + 'formula' => $formula, + ); + } + } + + + /** + * Read EXTERNSHEET record + */ + private function _readExternSheet() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // external sheet references provided for named cells + if ($this->_version == self::XLS_BIFF8) { + // offset: 0; size: 2; number of following ref structures + $nm = self::_GetInt2d($recordData, 0); + for ($i = 0; $i < $nm; ++$i) { + $this->_ref[] = array( + // offset: 2 + 6 * $i; index to EXTERNALBOOK record + 'externalBookIndex' => self::_GetInt2d($recordData, 2 + 6 * $i), + // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record + 'firstSheetIndex' => self::_GetInt2d($recordData, 4 + 6 * $i), + // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record + 'lastSheetIndex' => self::_GetInt2d($recordData, 6 + 6 * $i), + ); + } + } + } + + + /** + * DEFINEDNAME + * + * This record is part of a Link Table. It contains the name + * and the token array of an internal defined name. Token + * arrays of defined names contain tokens with aberrant + * token classes. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readDefinedName() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8) { + // retrieves named cells + + // offset: 0; size: 2; option flags + $opts = self::_GetInt2d($recordData, 0); + + // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name + $isBuiltInName = (0x0020 & $opts) >> 5; + + // offset: 2; size: 1; keyboard shortcut + + // offset: 3; size: 1; length of the name (character count) + $nlen = ord($recordData{3}); + + // offset: 4; size: 2; size of the formula data (it can happen that this is zero) + // note: there can also be additional data, this is not included in $flen + $flen = self::_GetInt2d($recordData, 4); + + // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based) + $scope = self::_GetInt2d($recordData, 8); + + // offset: 14; size: var; Name (Unicode string without length field) + $string = self::_readUnicodeString(substr($recordData, 14), $nlen); + + // offset: var; size: $flen; formula data + $offset = 14 + $string['size']; + $formulaStructure = pack('v', $flen) . substr($recordData, $offset); + + try { + $formula = $this->_getFormulaFromStructure($formulaStructure); + } catch (PHPExcel_Exception $e) { + $formula = ''; + } + + $this->_definedname[] = array( + 'isBuiltInName' => $isBuiltInName, + 'name' => $string['value'], + 'formula' => $formula, + 'scope' => $scope, + ); + } + } + + + /** + * Read MSODRAWINGGROUP record + */ + private function _readMsoDrawingGroup() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + + // get spliced record data + $splicedRecordData = $this->_getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + $this->_drawingGroupData .= $recordData; + } + + + /** + * SST - Shared String Table + * + * This record contains a list of all strings used anywhere + * in the workbook. Each string occurs only once. The + * workbook uses indexes into the list to reference the + * strings. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + **/ + private function _readSst() + { + // offset within (spliced) record data + $pos = 0; + + // get spliced record data + $splicedRecordData = $this->_getSplicedRecordData(); + + $recordData = $splicedRecordData['recordData']; + $spliceOffsets = $splicedRecordData['spliceOffsets']; + + // offset: 0; size: 4; total number of strings in the workbook + $pos += 4; + + // offset: 4; size: 4; number of following strings ($nm) + $nm = self::_GetInt4d($recordData, 4); + $pos += 4; + + // loop through the Unicode strings (16-bit length) + for ($i = 0; $i < $nm; ++$i) { + + // number of characters in the Unicode string + $numChars = self::_GetInt2d($recordData, $pos); + $pos += 2; + + // option flags + $optionFlags = ord($recordData{$pos}); + ++$pos; + + // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed + $isCompressed = (($optionFlags & 0x01) == 0) ; + + // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic + $hasAsian = (($optionFlags & 0x04) != 0); + + // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text + $hasRichText = (($optionFlags & 0x08) != 0); + + if ($hasRichText) { + // number of Rich-Text formatting runs + $formattingRuns = self::_GetInt2d($recordData, $pos); + $pos += 2; + } + + if ($hasAsian) { + // size of Asian phonetic setting + $extendedRunLength = self::_GetInt4d($recordData, $pos); + $pos += 4; + } + + // expected byte length of character array if not split + $len = ($isCompressed) ? $numChars : $numChars * 2; + + // look up limit position + foreach ($spliceOffsets as $spliceOffset) { + // it can happen that the string is empty, therefore we need + // <= and not just < + if ($pos <= $spliceOffset) { + $limitpos = $spliceOffset; + break; + } + } + + if ($pos + $len <= $limitpos) { + // character array is not split between records + + $retstr = substr($recordData, $pos, $len); + $pos += $len; + + } else { + // character array is split between records + + // first part of character array + $retstr = substr($recordData, $pos, $limitpos - $pos); + + $bytesRead = $limitpos - $pos; + + // remaining characters in Unicode string + $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2)); + + $pos = $limitpos; + + // keep reading the characters + while ($charsLeft > 0) { + + // look up next limit position, in case the string span more than one continue record + foreach ($spliceOffsets as $spliceOffset) { + if ($pos < $spliceOffset) { + $limitpos = $spliceOffset; + break; + } + } + + // repeated option flags + // OpenOffice.org documentation 5.21 + $option = ord($recordData{$pos}); + ++$pos; + + if ($isCompressed && ($option == 0)) { + // 1st fragment compressed + // this fragment compressed + $len = min($charsLeft, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len; + $isCompressed = true; + + } elseif (!$isCompressed && ($option != 0)) { + // 1st fragment uncompressed + // this fragment uncompressed + $len = min($charsLeft * 2, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len / 2; + $isCompressed = false; + + } elseif (!$isCompressed && ($option == 0)) { + // 1st fragment uncompressed + // this fragment compressed + $len = min($charsLeft, $limitpos - $pos); + for ($j = 0; $j < $len; ++$j) { + $retstr .= $recordData{$pos + $j} . chr(0); + } + $charsLeft -= $len; + $isCompressed = false; + + } else { + // 1st fragment compressed + // this fragment uncompressed + $newstr = ''; + for ($j = 0; $j < strlen($retstr); ++$j) { + $newstr .= $retstr[$j] . chr(0); + } + $retstr = $newstr; + $len = min($charsLeft * 2, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len / 2; + $isCompressed = false; + } + + $pos += $len; + } + } + + // convert to UTF-8 + $retstr = self::_encodeUTF16($retstr, $isCompressed); + + // read additional Rich-Text information, if any + $fmtRuns = array(); + if ($hasRichText) { + // list of formatting runs + for ($j = 0; $j < $formattingRuns; ++$j) { + // first formatted character; zero-based + $charPos = self::_GetInt2d($recordData, $pos + $j * 4); + + // index to font record + $fontIndex = self::_GetInt2d($recordData, $pos + 2 + $j * 4); + + $fmtRuns[] = array( + 'charPos' => $charPos, + 'fontIndex' => $fontIndex, + ); + } + $pos += 4 * $formattingRuns; + } + + // read additional Asian phonetics information, if any + if ($hasAsian) { + // For Asian phonetic settings, we skip the extended string data + $pos += $extendedRunLength; + } + + // store the shared sting + $this->_sst[] = array( + 'value' => $retstr, + 'fmtRuns' => $fmtRuns, + ); + } + + // _getSplicedRecordData() takes care of moving current position in data stream + } + + + /** + * Read PRINTGRIDLINES record + */ + private function _readPrintGridlines() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) { + // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines + $printGridlines = (bool) self::_GetInt2d($recordData, 0); + $this->_phpSheet->setPrintGridlines($printGridlines); + } + } + + + /** + * Read DEFAULTROWHEIGHT record + */ + private function _readDefaultRowHeight() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; option flags + // offset: 2; size: 2; default height for unused rows, (twips 1/20 point) + $height = self::_GetInt2d($recordData, 2); + $this->_phpSheet->getDefaultRowDimension()->setRowHeight($height / 20); + } + + + /** + * Read SHEETPR record + */ + private function _readSheetPr() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2 + + // bit: 6; mask: 0x0040; 0 = outline buttons above outline group + $isSummaryBelow = (0x0040 & self::_GetInt2d($recordData, 0)) >> 6; + $this->_phpSheet->setShowSummaryBelow($isSummaryBelow); + + // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group + $isSummaryRight = (0x0080 & self::_GetInt2d($recordData, 0)) >> 7; + $this->_phpSheet->setShowSummaryRight($isSummaryRight); + + // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages + // this corresponds to radio button setting in page setup dialog in Excel + $this->_isFitToPages = (bool) ((0x0100 & self::_GetInt2d($recordData, 0)) >> 8); + } + + + /** + * Read HORIZONTALPAGEBREAKS record + */ + private function _readHorizontalPageBreaks() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) { + + // offset: 0; size: 2; number of the following row index structures + $nm = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 6 * $nm; list of $nm row index structures + for ($i = 0; $i < $nm; ++$i) { + $r = self::_GetInt2d($recordData, 2 + 6 * $i); + $cf = self::_GetInt2d($recordData, 2 + 6 * $i + 2); + $cl = self::_GetInt2d($recordData, 2 + 6 * $i + 4); + + // not sure why two column indexes are necessary? + $this->_phpSheet->setBreakByColumnAndRow($cf, $r, PHPExcel_Worksheet::BREAK_ROW); + } + } + } + + + /** + * Read VERTICALPAGEBREAKS record + */ + private function _readVerticalPageBreaks() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) { + // offset: 0; size: 2; number of the following column index structures + $nm = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 6 * $nm; list of $nm row index structures + for ($i = 0; $i < $nm; ++$i) { + $c = self::_GetInt2d($recordData, 2 + 6 * $i); + $rf = self::_GetInt2d($recordData, 2 + 6 * $i + 2); + $rl = self::_GetInt2d($recordData, 2 + 6 * $i + 4); + + // not sure why two row indexes are necessary? + $this->_phpSheet->setBreakByColumnAndRow($c, $rf, PHPExcel_Worksheet::BREAK_COLUMN); + } + } + } + + + /** + * Read HEADER record + */ + private function _readHeader() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: var + // realized that $recordData can be empty even when record exists + if ($recordData) { + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringLong($recordData); + } else { + $string = $this->_readByteStringShort($recordData); + } + + $this->_phpSheet->getHeaderFooter()->setOddHeader($string['value']); + $this->_phpSheet->getHeaderFooter()->setEvenHeader($string['value']); + } + } + } + + + /** + * Read FOOTER record + */ + private function _readFooter() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: var + // realized that $recordData can be empty even when record exists + if ($recordData) { + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringLong($recordData); + } else { + $string = $this->_readByteStringShort($recordData); + } + $this->_phpSheet->getHeaderFooter()->setOddFooter($string['value']); + $this->_phpSheet->getHeaderFooter()->setEvenFooter($string['value']); + } + } + } + + + /** + * Read HCENTER record + */ + private function _readHcenter() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally + $isHorizontalCentered = (bool) self::_GetInt2d($recordData, 0); + + $this->_phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered); + } + } + + + /** + * Read VCENTER record + */ + private function _readVcenter() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered + $isVerticalCentered = (bool) self::_GetInt2d($recordData, 0); + + $this->_phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered); + } + } + + + /** + * Read LEFTMARGIN record + */ + private function _readLeftMargin() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 8 + $this->_phpSheet->getPageMargins()->setLeft(self::_extractNumber($recordData)); + } + } + + + /** + * Read RIGHTMARGIN record + */ + private function _readRightMargin() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 8 + $this->_phpSheet->getPageMargins()->setRight(self::_extractNumber($recordData)); + } + } + + + /** + * Read TOPMARGIN record + */ + private function _readTopMargin() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 8 + $this->_phpSheet->getPageMargins()->setTop(self::_extractNumber($recordData)); + } + } + + + /** + * Read BOTTOMMARGIN record + */ + private function _readBottomMargin() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 8 + $this->_phpSheet->getPageMargins()->setBottom(self::_extractNumber($recordData)); + } + } + + + /** + * Read PAGESETUP record + */ + private function _readPageSetup() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; paper size + $paperSize = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; scaling factor + $scale = self::_GetInt2d($recordData, 2); + + // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed + $fitToWidth = self::_GetInt2d($recordData, 6); + + // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed + $fitToHeight = self::_GetInt2d($recordData, 8); + + // offset: 10; size: 2; option flags + + // bit: 1; mask: 0x0002; 0=landscape, 1=portrait + $isPortrait = (0x0002 & self::_GetInt2d($recordData, 10)) >> 1; + + // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init + // when this bit is set, do not use flags for those properties + $isNotInit = (0x0004 & self::_GetInt2d($recordData, 10)) >> 2; + + if (!$isNotInit) { + $this->_phpSheet->getPageSetup()->setPaperSize($paperSize); + switch ($isPortrait) { + case 0: $this->_phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE); break; + case 1: $this->_phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT); break; + } + + $this->_phpSheet->getPageSetup()->setScale($scale, false); + $this->_phpSheet->getPageSetup()->setFitToPage((bool) $this->_isFitToPages); + $this->_phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false); + $this->_phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false); + } + + // offset: 16; size: 8; header margin (IEEE 754 floating-point value) + $marginHeader = self::_extractNumber(substr($recordData, 16, 8)); + $this->_phpSheet->getPageMargins()->setHeader($marginHeader); + + // offset: 24; size: 8; footer margin (IEEE 754 floating-point value) + $marginFooter = self::_extractNumber(substr($recordData, 24, 8)); + $this->_phpSheet->getPageMargins()->setFooter($marginFooter); + } + } + + + /** + * PROTECT - Sheet protection (BIFF2 through BIFF8) + * if this record is omitted, then it also means no sheet protection + */ + private function _readProtect() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit 0, mask 0x01; 1 = sheet is protected + $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0; + $this->_phpSheet->getProtection()->setSheet((bool)$bool); + } + + + /** + * SCENPROTECT + */ + private function _readScenProtect() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit: 0, mask 0x01; 1 = scenarios are protected + $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0; + + $this->_phpSheet->getProtection()->setScenarios((bool)$bool); + } + + + /** + * OBJECTPROTECT + */ + private function _readObjectProtect() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit: 0, mask 0x01; 1 = objects are protected + $bool = (0x01 & self::_GetInt2d($recordData, 0)) >> 0; + + $this->_phpSheet->getProtection()->setObjects((bool)$bool); + } + + + /** + * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8) + */ + private function _readPassword() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; 16-bit hash value of password + $password = strtoupper(dechex(self::_GetInt2d($recordData, 0))); // the hashed password + $this->_phpSheet->getProtection()->setPassword($password, true); + } + } + + + /** + * Read DEFCOLWIDTH record + */ + private function _readDefColWidth() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; default column width + $width = self::_GetInt2d($recordData, 0); + if ($width != 8) { + $this->_phpSheet->getDefaultColumnDimension()->setWidth($width); + } + } + + + /** + * Read COLINFO record + */ + private function _readColInfo() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; index to first column in range + $fc = self::_GetInt2d($recordData, 0); // first column index + + // offset: 2; size: 2; index to last column in range + $lc = self::_GetInt2d($recordData, 2); // first column index + + // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character + $width = self::_GetInt2d($recordData, 4); + + // offset: 6; size: 2; index to XF record for default column formatting + $xfIndex = self::_GetInt2d($recordData, 6); + + // offset: 8; size: 2; option flags + + // bit: 0; mask: 0x0001; 1= columns are hidden + $isHidden = (0x0001 & self::_GetInt2d($recordData, 8)) >> 0; + + // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline) + $level = (0x0700 & self::_GetInt2d($recordData, 8)) >> 8; + + // bit: 12; mask: 0x1000; 1 = collapsed + $isCollapsed = (0x1000 & self::_GetInt2d($recordData, 8)) >> 12; + + // offset: 10; size: 2; not used + + for ($i = $fc; $i <= $lc; ++$i) { + if ($lc == 255 || $lc == 256) { + $this->_phpSheet->getDefaultColumnDimension()->setWidth($width / 256); + break; + } + $this->_phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256); + $this->_phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden); + $this->_phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level); + $this->_phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed); + $this->_phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * ROW + * + * This record contains the properties of a single row in a + * sheet. Rows and cells in a sheet are divided into blocks + * of 32 rows. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readRow() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; index of this row + $r = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to column of the first cell which is described by a cell record + + // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1 + + // offset: 6; size: 2; + + // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point + $height = (0x7FFF & self::_GetInt2d($recordData, 6)) >> 0; + + // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height + $useDefaultHeight = (0x8000 & self::_GetInt2d($recordData, 6)) >> 15; + + if (!$useDefaultHeight) { + $this->_phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20); + } + + // offset: 8; size: 2; not used + + // offset: 10; size: 2; not used in BIFF5-BIFF8 + + // offset: 12; size: 4; option flags and default row formatting + + // bit: 2-0: mask: 0x00000007; outline level of the row + $level = (0x00000007 & self::_GetInt4d($recordData, 12)) >> 0; + $this->_phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); + + // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed + $isCollapsed = (0x00000010 & self::_GetInt4d($recordData, 12)) >> 4; + $this->_phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); + + // bit: 5; mask: 0x00000020; 1 = row is hidden + $isHidden = (0x00000020 & self::_GetInt4d($recordData, 12)) >> 5; + $this->_phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden); + + // bit: 7; mask: 0x00000080; 1 = row has explicit format + $hasExplicitFormat = (0x00000080 & self::_GetInt4d($recordData, 12)) >> 7; + + // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record + $xfIndex = (0x0FFF0000 & self::_GetInt4d($recordData, 12)) >> 16; + + if ($hasExplicitFormat) { + $this->_phpSheet->getRowDimension($r + 1)->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read RK record + * This record represents a cell that contains an RK value + * (encoded integer or floating-point value). If a + * floating-point value cannot be encoded to an RK value, + * a NUMBER record will be written. This record replaces the + * record INTEGER written in BIFF2. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readRk() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::_GetInt2d($recordData, 4); + + // offset: 6; size: 4; RK value + $rknum = self::_GetInt4d($recordData, 6); + $numValue = self::_GetIEEE754($rknum); + + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + if (!$this->_readDataOnly) { + // add style information + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + + // add cell + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + } + + + /** + * Read LABELSST record + * This record represents a cell that contains a string. It + * replaces the LABEL record and RSTRING record used in + * BIFF2-BIFF5. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readLabelSst() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::_GetInt2d($recordData, 4); + + // offset: 6; size: 4; index to SST record + $index = self::_GetInt4d($recordData, 6); + + // add cell + if (($fmtRuns = $this->_sst[$index]['fmtRuns']) && !$this->_readDataOnly) { + // then we should treat as rich text + $richText = new PHPExcel_RichText(); + $charPos = 0; + $sstCount = count($this->_sst[$index]['fmtRuns']); + for ($i = 0; $i <= $sstCount; ++$i) { + if (isset($fmtRuns[$i])) { + $text = PHPExcel_Shared_String::Substring($this->_sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos); + $charPos = $fmtRuns[$i]['charPos']; + } else { + $text = PHPExcel_Shared_String::Substring($this->_sst[$index]['value'], $charPos, PHPExcel_Shared_String::CountCharacters($this->_sst[$index]['value'])); + } + + if (PHPExcel_Shared_String::CountCharacters($text) > 0) { + if ($i == 0) { // first text run, no style + $richText->createText($text); + } else { + $textRun = $richText->createTextRun($text); + if (isset($fmtRuns[$i - 1])) { + if ($fmtRuns[$i - 1]['fontIndex'] < 4) { + $fontIndex = $fmtRuns[$i - 1]['fontIndex']; + } else { + // this has to do with that index 4 is omitted in all BIFF versions for some strange reason + // check the OpenOffice documentation of the FONT record + $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1; + } + $textRun->setFont(clone $this->_objFonts[$fontIndex]); + } + } + } + } + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($richText, PHPExcel_Cell_DataType::TYPE_STRING); + } else { + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($this->_sst[$index]['value'], PHPExcel_Cell_DataType::TYPE_STRING); + } + + if (!$this->_readDataOnly) { + // add style information + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read MULRK record + * This record represents a cell range containing RK value + * cells. All cells are located in the same row. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readMulRk() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to first column + $colFirst = self::_GetInt2d($recordData, 2); + + // offset: var; size: 2; index to last column + $colLast = self::_GetInt2d($recordData, $length - 2); + $columns = $colLast - $colFirst + 1; + + // offset within record data + $offset = 4; + + for ($i = 0; $i < $columns; ++$i) { + $columnString = PHPExcel_Cell::stringFromColumnIndex($colFirst + $i); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + + // offset: var; size: 2; index to XF record + $xfIndex = self::_GetInt2d($recordData, $offset); + + // offset: var; size: 4; RK value + $numValue = self::_GetIEEE754(self::_GetInt4d($recordData, $offset + 2)); + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + if (!$this->_readDataOnly) { + // add style + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + + // add cell value + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + + $offset += 6; + } + } + + + /** + * Read NUMBER record + * This record represents a cell that contains a + * floating-point value. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readNumber() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size 2; index to column + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset 4; size: 2; index to XF record + $xfIndex = self::_GetInt2d($recordData, 4); + + $numValue = self::_extractNumber(substr($recordData, 6, 8)); + + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + if (!$this->_readDataOnly) { + // add cell style + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + + // add cell value + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + } + + + /** + * Read FORMULA record + perhaps a following STRING record if formula result is a string + * This record contains the token array and the result of a + * formula cell. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readFormula() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; col index + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // offset: 20: size: variable; formula structure + $formulaStructure = substr($recordData, 20); + + // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc. + $options = self::_GetInt2d($recordData, 14); + + // bit: 0; mask: 0x0001; 1 = recalculate always + // bit: 1; mask: 0x0002; 1 = calculate on open + // bit: 2; mask: 0x0008; 1 = part of a shared formula + $isPartOfSharedFormula = (bool) (0x0008 & $options); + + // WARNING: + // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true + // the formula data may be ordinary formula data, therefore we need to check + // explicitly for the tExp token (0x01) + $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure{2}) == 0x01; + + if ($isPartOfSharedFormula) { + // part of shared formula which means there will be a formula with a tExp token and nothing else + // get the base cell, grab tExp token + $baseRow = self::_GetInt2d($formulaStructure, 3); + $baseCol = self::_GetInt2d($formulaStructure, 5); + $this->_baseCell = PHPExcel_Cell::stringFromColumnIndex($baseCol). ($baseRow + 1); + } + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + + if ($isPartOfSharedFormula) { + // formula is added to this cell after the sheet has been read + $this->_sharedFormulaParts[$columnString . ($row + 1)] = $this->_baseCell; + } + + // offset: 16: size: 4; not used + + // offset: 4; size: 2; XF index + $xfIndex = self::_GetInt2d($recordData, 4); + + // offset: 6; size: 8; result of the formula + if ( (ord($recordData{6}) == 0) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255) ) { + + // String formula. Result follows in appended STRING record + $dataType = PHPExcel_Cell_DataType::TYPE_STRING; + + // read possible SHAREDFMLA record + $code = self::_GetInt2d($this->_data, $this->_pos); + if ($code == self::XLS_Type_SHAREDFMLA) { + $this->_readSharedFmla(); + } + + // read STRING record + $value = $this->_readString(); + + } elseif ((ord($recordData{6}) == 1) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + + // Boolean formula. Result is in +2; 0=false, 1=true + $dataType = PHPExcel_Cell_DataType::TYPE_BOOL; + $value = (bool) ord($recordData{8}); + + } elseif ((ord($recordData{6}) == 2) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + + // Error formula. Error code is in +2 + $dataType = PHPExcel_Cell_DataType::TYPE_ERROR; + $value = self::_mapErrorCode(ord($recordData{8})); + + } elseif ((ord($recordData{6}) == 3) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + + // Formula result is a null string + $dataType = PHPExcel_Cell_DataType::TYPE_NULL; + $value = ''; + + } else { + + // forumla result is a number, first 14 bytes like _NUMBER record + $dataType = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $value = self::_extractNumber(substr($recordData, 6, 8)); + + } + + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + if (!$this->_readDataOnly) { + // add cell style + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + + // store the formula + if (!$isPartOfSharedFormula) { + // not part of shared formula + // add cell value. If we can read formula, populate with formula, otherwise just used cached value + try { + if ($this->_version != self::XLS_BIFF8) { + throw new PHPExcel_Reader_Exception('Not BIFF8. Can only read BIFF8 formulas'); + } + $formula = $this->_getFormulaFromStructure($formulaStructure); // get formula in human language + $cell->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + + } catch (PHPExcel_Exception $e) { + $cell->setValueExplicit($value, $dataType); + } + } else { + if ($this->_version == self::XLS_BIFF8) { + // do nothing at this point, formula id added later in the code + } else { + $cell->setValueExplicit($value, $dataType); + } + } + + // store the cached calculated value + $cell->setCalculatedValue($value); + } + } + + + /** + * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader, + * which usually contains relative references. + * These will be used to construct the formula in each shared formula part after the sheet is read. + */ + private function _readSharedFmla() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything + $cellRange = substr($recordData, 0, 6); + $cellRange = $this->_readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax + + // offset: 6, size: 1; not used + + // offset: 7, size: 1; number of existing FORMULA records for this shared formula + $no = ord($recordData{7}); + + // offset: 8, size: var; Binary token array of the shared formula + $formula = substr($recordData, 8); + + // at this point we only store the shared formula for later use + $this->_sharedFormulas[$this->_baseCell] = $formula; + + } + + + /** + * Read a STRING record from current stream position and advance the stream pointer to next record + * This record is used for storing result from FORMULA record when it is a string, and + * it occurs directly after the FORMULA record + * + * @return string The string contents as UTF-8 + */ + private function _readString() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringLong($recordData); + $value = $string['value']; + } else { + $string = $this->_readByteStringLong($recordData); + $value = $string['value']; + } + + return $value; + } + + + /** + * Read BOOLERR record + * This record represents a Boolean value or error value + * cell. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readBoolErr() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; column index + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::_GetInt2d($recordData, 4); + + // offset: 6; size: 1; the boolean value or error value + $boolErr = ord($recordData{6}); + + // offset: 7; size: 1; 0=boolean; 1=error + $isError = ord($recordData{7}); + + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + switch ($isError) { + case 0: // boolean + $value = (bool) $boolErr; + + // add cell value + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_BOOL); + break; + + case 1: // error type + $value = self::_mapErrorCode($boolErr); + + // add cell value + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_ERROR); + break; + } + + if (!$this->_readDataOnly) { + // add cell style + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read MULBLANK record + * This record represents a cell range of empty cells. All + * cells are located in the same row + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readMulBlank() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to first column + $fc = self::_GetInt2d($recordData, 2); + + // offset: 4; size: 2 x nc; list of indexes to XF records + // add style information + if (!$this->_readDataOnly) { + for ($i = 0; $i < $length / 2 - 3; ++$i) { + $columnString = PHPExcel_Cell::stringFromColumnIndex($fc + $i); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + $xfIndex = self::_GetInt2d($recordData, 4 + 2 * $i); + $this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + // offset: 6; size 2; index to last column (not needed) + } + + + /** + * Read LABEL record + * This record represents a cell that contains a string. In + * BIFF8 it is usually replaced by the LABELSST record. + * Excel still uses this record, if it copies unformatted + * text cells to the clipboard. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readLabel() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset: 4; size: 2; XF index + $xfIndex = self::_GetInt2d($recordData, 4); + + // add cell value + // todo: what if string is very long? continue record + if ($this->_version == self::XLS_BIFF8) { + $string = self::_readUnicodeStringLong(substr($recordData, 6)); + $value = $string['value']; + } else { + $string = $this->_readByteStringLong(substr($recordData, 6)); + $value = $string['value']; + } + $cell = $this->_phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); + + if (!$this->_readDataOnly) { + // add cell style + $cell->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read BLANK record + */ + private function _readBlank() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; col index + $col = self::_GetInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($col); + + // Read cell? + if (($this->getReadFilter() !== NULL) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->_phpSheet->getTitle()) ) { + // offset: 4; size: 2; XF index + $xfIndex = self::_GetInt2d($recordData, 4); + + // add style information + if (!$this->_readDataOnly) { + $this->_phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->_mapCellXfIndex[$xfIndex]); + } + } + + } + + + /** + * Read MSODRAWING record + */ + private function _readMsoDrawing() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + + // get spliced record data + $splicedRecordData = $this->_getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + $this->_drawingData .= $recordData; + } + + + /** + * Read OBJ record + */ + private function _readObj() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly || $this->_version != self::XLS_BIFF8) { + return; + } + + // recordData consists of an array of subrecords looking like this: + // ft: 2 bytes; ftCmo type (0x15) + // cb: 2 bytes; size in bytes of ftCmo data + // ot: 2 bytes; Object Type + // id: 2 bytes; Object id number + // grbit: 2 bytes; Option Flags + // data: var; subrecord data + + // for now, we are just interested in the second subrecord containing the object type + $ftCmoType = self::_GetInt2d($recordData, 0); + $cbCmoSize = self::_GetInt2d($recordData, 2); + $otObjType = self::_GetInt2d($recordData, 4); + $idObjID = self::_GetInt2d($recordData, 6); + $grbitOpts = self::_GetInt2d($recordData, 6); + + $this->_objs[] = array( + 'ftCmoType' => $ftCmoType, + 'cbCmoSize' => $cbCmoSize, + 'otObjType' => $otObjType, + 'idObjID' => $idObjID, + 'grbitOpts' => $grbitOpts + ); + $this->textObjRef = $idObjID; + +// echo '_readObj()
'; +// var_dump(end($this->_objs)); +// echo '
'; + } + + + /** + * Read WINDOW2 record + */ + private function _readWindow2() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; option flags + $options = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; index to first visible row + $firstVisibleRow = self::_GetInt2d($recordData, 2); + + // offset: 4; size: 2; index to first visible colum + $firstVisibleColumn = self::_GetInt2d($recordData, 4); + if ($this->_version === self::XLS_BIFF8) { + // offset: 8; size: 2; not used + // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) + // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%) + // offset: 14; size: 4; not used + $zoomscaleInPageBreakPreview = self::_GetInt2d($recordData, 10); + if ($zoomscaleInPageBreakPreview === 0) $zoomscaleInPageBreakPreview = 60; + $zoomscaleInNormalView = self::_GetInt2d($recordData, 12); + if ($zoomscaleInNormalView === 0) $zoomscaleInNormalView = 100; + } + + // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines + $showGridlines = (bool) ((0x0002 & $options) >> 1); + $this->_phpSheet->setShowGridlines($showGridlines); + + // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers + $showRowColHeaders = (bool) ((0x0004 & $options) >> 2); + $this->_phpSheet->setShowRowColHeaders($showRowColHeaders); + + // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen + $this->_frozen = (bool) ((0x0008 & $options) >> 3); + + // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left + $this->_phpSheet->setRightToLeft((bool)((0x0040 & $options) >> 6)); + + // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active + $isActive = (bool) ((0x0400 & $options) >> 10); + if ($isActive) { + $this->_phpExcel->setActiveSheetIndex($this->_phpExcel->getIndex($this->_phpSheet)); + } + + // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view + $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11); + + //FIXME: set $firstVisibleRow and $firstVisibleColumn + + if ($this->_phpSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT) { + //NOTE: this setting is inferior to page layout view(Excel2007-) + $view = $isPageBreakPreview? PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : + PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL; + $this->_phpSheet->getSheetView()->setView($view); + if ($this->_version === self::XLS_BIFF8) { + $zoomScale = $isPageBreakPreview? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView; + $this->_phpSheet->getSheetView()->setZoomScale($zoomScale); + $this->_phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView); + } + } + } + + /** + * Read PLV Record(Created by Excel2007 or upper) + */ + private function _readPageLayoutView(){ + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + //var_dump(unpack("vrt/vgrbitFrt/V2reserved/vwScalePLV/vgrbit", $recordData)); + + // offset: 0; size: 2; rt + //->ignore + $rt = self::_GetInt2d($recordData, 0); + // offset: 2; size: 2; grbitfr + //->ignore + $grbitFrt = self::_GetInt2d($recordData, 2); + // offset: 4; size: 8; reserved + //->ignore + + // offset: 12; size 2; zoom scale + $wScalePLV = self::_GetInt2d($recordData, 12); + // offset: 14; size 2; grbit + $grbit = self::_GetInt2d($recordData, 14); + + // decomprise grbit + $fPageLayoutView = $grbit & 0x01; + $fRulerVisible = ($grbit >> 1) & 0x01; //no support + $fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support + + if ($fPageLayoutView === 1) { + $this->_phpSheet->getSheetView()->setView(PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT); + $this->_phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT + } + //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW. + } + + /** + * Read SCL record + */ + private function _readScl() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // offset: 0; size: 2; numerator of the view magnification + $numerator = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; numerator of the view magnification + $denumerator = self::_GetInt2d($recordData, 2); + + // set the zoom scale (in percent) + $this->_phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator); + } + + + /** + * Read PANE record + */ + private function _readPane() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; position of vertical split + $px = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; position of horizontal split + $py = self::_GetInt2d($recordData, 2); + + if ($this->_frozen) { + // frozen panes + $this->_phpSheet->freezePane(PHPExcel_Cell::stringFromColumnIndex($px) . ($py + 1)); + } else { + // unfrozen panes; split windows; not supported by PHPExcel core + } + } + } + + + /** + * Read SELECTION record. There is one such record for each pane in the sheet. + */ + private function _readSelection() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 1; pane identifier + $paneId = ord($recordData{0}); + + // offset: 1; size: 2; index to row of the active cell + $r = self::_GetInt2d($recordData, 1); + + // offset: 3; size: 2; index to column of the active cell + $c = self::_GetInt2d($recordData, 3); + + // offset: 5; size: 2; index into the following cell range list to the + // entry that contains the active cell + $index = self::_GetInt2d($recordData, 5); + + // offset: 7; size: var; cell range address list containing all selected cell ranges + $data = substr($recordData, 7); + $cellRangeAddressList = $this->_readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax + + $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0]; + + // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!) + if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) { + $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells); + } + + // first row '1' + last row '65536' indicates that full column is selected + if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) { + $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells); + } + + // first column 'A' + last column 'IV' indicates that full row is selected + if (preg_match('/^(A[0-9]+\:)IV([0-9]+)$/', $selectedCells)) { + $selectedCells = preg_replace('/^(A[0-9]+\:)IV([0-9]+)$/', '${1}XFD${2}', $selectedCells); + } + + $this->_phpSheet->setSelectedCells($selectedCells); + } + } + + + private function _includeCellRangeFiltered($cellRangeAddress) + { + $includeCellRange = true; + if ($this->getReadFilter() !== NULL) { + $includeCellRange = false; + $rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($cellRangeAddress); + $rangeBoundaries[1][0]++; + for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; $row++) { + for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; $column++) { + if ($this->getReadFilter()->readCell($column, $row, $this->_phpSheet->getTitle())) { + $includeCellRange = true; + break 2; + } + } + } + } + return $includeCellRange; + } + + + /** + * MERGEDCELLS + * + * This record contains the addresses of merged cell ranges + * in the current sheet. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function _readMergedCells() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_version == self::XLS_BIFF8 && !$this->_readDataOnly) { + $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($recordData); + foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) { + if ((strpos($cellRangeAddress,':') !== FALSE) && + ($this->_includeCellRangeFiltered($cellRangeAddress))) { + $this->_phpSheet->mergeCells($cellRangeAddress); + } + } + } + } + + + /** + * Read HYPERLINK record + */ + private function _readHyperLink() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer forward to next record + $this->_pos += 4 + $length; + + if (!$this->_readDataOnly) { + // offset: 0; size: 8; cell range address of all cells containing this hyperlink + try { + $cellRange = $this->_readBIFF8CellRangeAddressFixed($recordData, 0, 8); + } catch (PHPExcel_Exception $e) { + return; + } + + // offset: 8, size: 16; GUID of StdLink + + // offset: 24, size: 4; unknown value + + // offset: 28, size: 4; option flags + + // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL + $isFileLinkOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 0; + + // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL + $isAbsPathOrUrl = (0x00000001 & self::_GetInt2d($recordData, 28)) >> 1; + + // bit: 2 (and 4); mask: 0x00000014; 0 = no description + $hasDesc = (0x00000014 & self::_GetInt2d($recordData, 28)) >> 2; + + // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text + $hasText = (0x00000008 & self::_GetInt2d($recordData, 28)) >> 3; + + // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame + $hasFrame = (0x00000080 & self::_GetInt2d($recordData, 28)) >> 7; + + // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name) + $isUNC = (0x00000100 & self::_GetInt2d($recordData, 28)) >> 8; + + // offset within record data + $offset = 32; + + if ($hasDesc) { + // offset: 32; size: var; character count of description text + $dl = self::_GetInt4d($recordData, 32); + // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated + $desc = self::_encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false); + $offset += 4 + 2 * $dl; + } + if ($hasFrame) { + $fl = self::_GetInt4d($recordData, $offset); + $offset += 4 + 2 * $fl; + } + + // detect type of hyperlink (there are 4 types) + $hyperlinkType = null; + + if ($isUNC) { + $hyperlinkType = 'UNC'; + } else if (!$isFileLinkOrUrl) { + $hyperlinkType = 'workbook'; + } else if (ord($recordData{$offset}) == 0x03) { + $hyperlinkType = 'local'; + } else if (ord($recordData{$offset}) == 0xE0) { + $hyperlinkType = 'URL'; + } + + switch ($hyperlinkType) { + case 'URL': + // section 5.58.2: Hyperlink containing a URL + // e.g. http://example.org/index.php + + // offset: var; size: 16; GUID of URL Moniker + $offset += 16; + // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word + $us = self::_GetInt4d($recordData, $offset); + $offset += 4; + // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated + $url = self::_encodeUTF16(substr($recordData, $offset, $us - 2), false); + $url .= $hasText ? '#' : ''; + $offset += $us; + break; + + case 'local': + // section 5.58.3: Hyperlink to local file + // examples: + // mydoc.txt + // ../../somedoc.xls#Sheet!A1 + + // offset: var; size: 16; GUI of File Moniker + $offset += 16; + + // offset: var; size: 2; directory up-level count. + $upLevelCount = self::_GetInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word + $sl = self::_GetInt4d($recordData, $offset); + $offset += 4; + + // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string) + $shortenedFilePath = substr($recordData, $offset, $sl); + $shortenedFilePath = self::_encodeUTF16($shortenedFilePath, true); + $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero + + $offset += $sl; + + // offset: var; size: 24; unknown sequence + $offset += 24; + + // extended file path + // offset: var; size: 4; size of the following file link field including string lenth mark + $sz = self::_GetInt4d($recordData, $offset); + $offset += 4; + + // only present if $sz > 0 + if ($sz > 0) { + // offset: var; size: 4; size of the character array of the extended file path and name + $xl = self::_GetInt4d($recordData, $offset); + $offset += 4; + + // offset: var; size 2; unknown + $offset += 2; + + // offset: var; size $xl; character array of the extended file path and name. + $extendedFilePath = substr($recordData, $offset, $xl); + $extendedFilePath = self::_encodeUTF16($extendedFilePath, false); + $offset += $xl; + } + + // construct the path + $url = str_repeat('..\\', $upLevelCount); + $url .= ($sz > 0) ? + $extendedFilePath : $shortenedFilePath; // use extended path if available + $url .= $hasText ? '#' : ''; + + break; + + + case 'UNC': + // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path + // todo: implement + return; + + case 'workbook': + // section 5.58.5: Hyperlink to the Current Workbook + // e.g. Sheet2!B1:C2, stored in text mark field + $url = 'sheet://'; + break; + + default: + return; + + } + + if ($hasText) { + // offset: var; size: 4; character count of text mark including trailing zero word + $tl = self::_GetInt4d($recordData, $offset); + $offset += 4; + // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated + $text = self::_encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false); + $url .= $text; + } + + // apply the hyperlink to all the relevant cells + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cellRange) as $coordinate) { + $this->_phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url); + } + } + } + + + /** + * Read DATAVALIDATIONS record + */ + private function _readDataValidations() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer forward to next record + $this->_pos += 4 + $length; + } + + + /** + * Read DATAVALIDATION record + */ + private function _readDataValidation() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer forward to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // offset: 0; size: 4; Options + $options = self::_GetInt4d($recordData, 0); + + // bit: 0-3; mask: 0x0000000F; type + $type = (0x0000000F & $options) >> 0; + switch ($type) { + case 0x00: $type = PHPExcel_Cell_DataValidation::TYPE_NONE; break; + case 0x01: $type = PHPExcel_Cell_DataValidation::TYPE_WHOLE; break; + case 0x02: $type = PHPExcel_Cell_DataValidation::TYPE_DECIMAL; break; + case 0x03: $type = PHPExcel_Cell_DataValidation::TYPE_LIST; break; + case 0x04: $type = PHPExcel_Cell_DataValidation::TYPE_DATE; break; + case 0x05: $type = PHPExcel_Cell_DataValidation::TYPE_TIME; break; + case 0x06: $type = PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH; break; + case 0x07: $type = PHPExcel_Cell_DataValidation::TYPE_CUSTOM; break; + } + + // bit: 4-6; mask: 0x00000070; error type + $errorStyle = (0x00000070 & $options) >> 4; + switch ($errorStyle) { + case 0x00: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; break; + case 0x01: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_WARNING; break; + case 0x02: $errorStyle = PHPExcel_Cell_DataValidation::STYLE_INFORMATION; break; + } + + // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list) + // I have only seen cases where this is 1 + $explicitFormula = (0x00000080 & $options) >> 7; + + // bit: 8; mask: 0x00000100; 1= empty cells allowed + $allowBlank = (0x00000100 & $options) >> 8; + + // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity + $suppressDropDown = (0x00000200 & $options) >> 9; + + // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected + $showInputMessage = (0x00040000 & $options) >> 18; + + // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered + $showErrorMessage = (0x00080000 & $options) >> 19; + + // bit: 20-23; mask: 0x00F00000; condition operator + $operator = (0x00F00000 & $options) >> 20; + switch ($operator) { + case 0x00: $operator = PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN ; break; + case 0x01: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN ; break; + case 0x02: $operator = PHPExcel_Cell_DataValidation::OPERATOR_EQUAL ; break; + case 0x03: $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL ; break; + case 0x04: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN ; break; + case 0x05: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN ; break; + case 0x06: $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL; break; + case 0x07: $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL ; break; + } + + // offset: 4; size: var; title of the prompt box + $offset = 4; + $string = self::_readUnicodeStringLong(substr($recordData, $offset)); + $promptTitle = $string['value'] !== chr(0) ? + $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; title of the error box + $string = self::_readUnicodeStringLong(substr($recordData, $offset)); + $errorTitle = $string['value'] !== chr(0) ? + $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; text of the prompt box + $string = self::_readUnicodeStringLong(substr($recordData, $offset)); + $prompt = $string['value'] !== chr(0) ? + $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; text of the error box + $string = self::_readUnicodeStringLong(substr($recordData, $offset)); + $error = $string['value'] !== chr(0) ? + $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: 2; size of the formula data for the first condition + $sz1 = self::_GetInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 2; not used + $offset += 2; + + // offset: var; size: $sz1; formula data for first condition (without size field) + $formula1 = substr($recordData, $offset, $sz1); + $formula1 = pack('v', $sz1) . $formula1; // prepend the length + try { + $formula1 = $this->_getFormulaFromStructure($formula1); + + // in list type validity, null characters are used as item separators + if ($type == PHPExcel_Cell_DataValidation::TYPE_LIST) { + $formula1 = str_replace(chr(0), ',', $formula1); + } + } catch (PHPExcel_Exception $e) { + return; + } + $offset += $sz1; + + // offset: var; size: 2; size of the formula data for the first condition + $sz2 = self::_GetInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 2; not used + $offset += 2; + + // offset: var; size: $sz2; formula data for second condition (without size field) + $formula2 = substr($recordData, $offset, $sz2); + $formula2 = pack('v', $sz2) . $formula2; // prepend the length + try { + $formula2 = $this->_getFormulaFromStructure($formula2); + } catch (PHPExcel_Exception $e) { + return; + } + $offset += $sz2; + + // offset: var; size: var; cell range address list with + $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList(substr($recordData, $offset)); + $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; + + foreach ($cellRangeAddresses as $cellRange) { + $stRange = $this->_phpSheet->shrinkRangeToFit($cellRange); + $stRange = PHPExcel_Cell::extractAllCellReferencesInRange($stRange); + foreach ($stRange as $coordinate) { + $objValidation = $this->_phpSheet->getCell($coordinate)->getDataValidation(); + $objValidation->setType($type); + $objValidation->setErrorStyle($errorStyle); + $objValidation->setAllowBlank((bool)$allowBlank); + $objValidation->setShowInputMessage((bool)$showInputMessage); + $objValidation->setShowErrorMessage((bool)$showErrorMessage); + $objValidation->setShowDropDown(!$suppressDropDown); + $objValidation->setOperator($operator); + $objValidation->setErrorTitle($errorTitle); + $objValidation->setError($error); + $objValidation->setPromptTitle($promptTitle); + $objValidation->setPrompt($prompt); + $objValidation->setFormula1($formula1); + $objValidation->setFormula2($formula2); + } + } + + } + + + /** + * Read SHEETLAYOUT record. Stores sheet tab color information. + */ + private function _readSheetLayout() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // local pointer in record data + $offset = 0; + + if (!$this->_readDataOnly) { + // offset: 0; size: 2; repeated record identifier 0x0862 + + // offset: 2; size: 10; not used + + // offset: 12; size: 4; size of record data + // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?) + $sz = self::_GetInt4d($recordData, 12); + + switch ($sz) { + case 0x14: + // offset: 16; size: 2; color index for sheet tab + $colorIndex = self::_GetInt2d($recordData, 16); + $color = self::_readColor($colorIndex,$this->_palette,$this->_version); + $this->_phpSheet->getTabColor()->setRGB($color['rgb']); + break; + + case 0x28: + // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007 + return; + break; + } + } + } + + + /** + * Read SHEETPROTECTION record (FEATHEADR) + */ + private function _readSheetProtection() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + if ($this->_readDataOnly) { + return; + } + + // offset: 0; size: 2; repeated record header + + // offset: 2; size: 2; FRT cell reference flag (=0 currently) + + // offset: 4; size: 8; Currently not used and set to 0 + + // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag) + $isf = self::_GetInt2d($recordData, 12); + if ($isf != 2) { + return; + } + + // offset: 14; size: 1; =1 since this is a feat header + + // offset: 15; size: 4; size of rgbHdrSData + + // rgbHdrSData, assume "Enhanced Protection" + // offset: 19; size: 2; option flags + $options = self::_GetInt2d($recordData, 19); + + // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects + $bool = (0x0001 & $options) >> 0; + $this->_phpSheet->getProtection()->setObjects(!$bool); + + // bit: 1; mask 0x0002; edit scenarios + $bool = (0x0002 & $options) >> 1; + $this->_phpSheet->getProtection()->setScenarios(!$bool); + + // bit: 2; mask 0x0004; format cells + $bool = (0x0004 & $options) >> 2; + $this->_phpSheet->getProtection()->setFormatCells(!$bool); + + // bit: 3; mask 0x0008; format columns + $bool = (0x0008 & $options) >> 3; + $this->_phpSheet->getProtection()->setFormatColumns(!$bool); + + // bit: 4; mask 0x0010; format rows + $bool = (0x0010 & $options) >> 4; + $this->_phpSheet->getProtection()->setFormatRows(!$bool); + + // bit: 5; mask 0x0020; insert columns + $bool = (0x0020 & $options) >> 5; + $this->_phpSheet->getProtection()->setInsertColumns(!$bool); + + // bit: 6; mask 0x0040; insert rows + $bool = (0x0040 & $options) >> 6; + $this->_phpSheet->getProtection()->setInsertRows(!$bool); + + // bit: 7; mask 0x0080; insert hyperlinks + $bool = (0x0080 & $options) >> 7; + $this->_phpSheet->getProtection()->setInsertHyperlinks(!$bool); + + // bit: 8; mask 0x0100; delete columns + $bool = (0x0100 & $options) >> 8; + $this->_phpSheet->getProtection()->setDeleteColumns(!$bool); + + // bit: 9; mask 0x0200; delete rows + $bool = (0x0200 & $options) >> 9; + $this->_phpSheet->getProtection()->setDeleteRows(!$bool); + + // bit: 10; mask 0x0400; select locked cells + $bool = (0x0400 & $options) >> 10; + $this->_phpSheet->getProtection()->setSelectLockedCells(!$bool); + + // bit: 11; mask 0x0800; sort cell range + $bool = (0x0800 & $options) >> 11; + $this->_phpSheet->getProtection()->setSort(!$bool); + + // bit: 12; mask 0x1000; auto filter + $bool = (0x1000 & $options) >> 12; + $this->_phpSheet->getProtection()->setAutoFilter(!$bool); + + // bit: 13; mask 0x2000; pivot tables + $bool = (0x2000 & $options) >> 13; + $this->_phpSheet->getProtection()->setPivotTables(!$bool); + + // bit: 14; mask 0x4000; select unlocked cells + $bool = (0x4000 & $options) >> 14; + $this->_phpSheet->getProtection()->setSelectUnlockedCells(!$bool); + + // offset: 21; size: 2; not used + } + + + /** + * Read RANGEPROTECTION record + * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, + * where it is referred to as FEAT record + */ + private function _readRangeProtection() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // move stream pointer to next record + $this->_pos += 4 + $length; + + // local pointer in record data + $offset = 0; + + if (!$this->_readDataOnly) { + $offset += 12; + + // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag + $isf = self::_GetInt2d($recordData, 12); + if ($isf != 2) { + // we only read FEAT records of type 2 + return; + } + $offset += 2; + + $offset += 5; + + // offset: 19; size: 2; count of ref ranges this feature is on + $cref = self::_GetInt2d($recordData, 19); + $offset += 2; + + $offset += 6; + + // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record) + $cellRanges = array(); + for ($i = 0; $i < $cref; ++$i) { + try { + $cellRange = $this->_readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8)); + } catch (PHPExcel_Exception $e) { + return; + } + $cellRanges[] = $cellRange; + $offset += 8; + } + + // offset: var; size: var; variable length of feature specific data + $rgbFeat = substr($recordData, $offset); + $offset += 4; + + // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit) + $wPassword = self::_GetInt4d($recordData, $offset); + $offset += 4; + + // Apply range protection to sheet + if ($cellRanges) { + $this->_phpSheet->protectCells(implode(' ', $cellRanges), strtoupper(dechex($wPassword)), true); + } + } + } + + + /** + * Read IMDATA record + */ + private function _readImData() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + + // get spliced record data + $splicedRecordData = $this->_getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + // UNDER CONSTRUCTION + + // offset: 0; size: 2; image format + $cf = self::_GetInt2d($recordData, 0); + + // offset: 2; size: 2; environment from which the file was written + $env = self::_GetInt2d($recordData, 2); + + // offset: 4; size: 4; length of the image data + $lcb = self::_GetInt4d($recordData, 4); + + // offset: 8; size: var; image data + $iData = substr($recordData, 8); + + switch ($cf) { + case 0x09: // Windows bitmap format + // BITMAPCOREINFO + // 1. BITMAPCOREHEADER + // offset: 0; size: 4; bcSize, Specifies the number of bytes required by the structure + $bcSize = self::_GetInt4d($iData, 0); +// var_dump($bcSize); + + // offset: 4; size: 2; bcWidth, specifies the width of the bitmap, in pixels + $bcWidth = self::_GetInt2d($iData, 4); +// var_dump($bcWidth); + + // offset: 6; size: 2; bcHeight, specifies the height of the bitmap, in pixels. + $bcHeight = self::_GetInt2d($iData, 6); +// var_dump($bcHeight); + $ih = imagecreatetruecolor($bcWidth, $bcHeight); + + // offset: 8; size: 2; bcPlanes, specifies the number of planes for the target device. This value must be 1 + + // offset: 10; size: 2; bcBitCount specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24 + $bcBitCount = self::_GetInt2d($iData, 10); +// var_dump($bcBitCount); + + $rgbString = substr($iData, 12); + $rgbTriples = array(); + while (strlen($rgbString) > 0) { + $rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString); + $rgbString = substr($rgbString, 3); + } + $x = 0; + $y = 0; + foreach ($rgbTriples as $i => $rgbTriple) { + $color = imagecolorallocate($ih, $rgbTriple['r'], $rgbTriple['g'], $rgbTriple['b']); + imagesetpixel($ih, $x, $bcHeight - 1 - $y, $color); + $x = ($x + 1) % $bcWidth; + $y = $y + floor(($x + 1) / $bcWidth); + } + //imagepng($ih, 'image.png'); + + $drawing = new PHPExcel_Worksheet_Drawing(); + $drawing->setPath($filename); + $drawing->setWorksheet($this->_phpSheet); + + break; + + case 0x02: // Windows metafile or Macintosh PICT format + case 0x0e: // native format + default; + break; + + } + + // _getSplicedRecordData() takes care of moving current position in data stream + } + + + /** + * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record + * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. + * In this case, we must treat the CONTINUE record as a MSODRAWING record + */ + private function _readContinue() + { + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $recordData = $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + // check if we are reading drawing data + // this is in case a free CONTINUE record occurs in other circumstances we are unaware of + if ($this->_drawingData == '') { + // move stream pointer to next record + $this->_pos += 4 + $length; + + return; + } + + // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data + if ($length < 4) { + // move stream pointer to next record + $this->_pos += 4 + $length; + + return; + } + + // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record + // look inside CONTINUE record to see if it looks like a part of an Escher stream + // we know that Escher stream may be split at least at + // 0xF003 MsofbtSpgrContainer + // 0xF004 MsofbtSpContainer + // 0xF00D MsofbtClientTextbox + $validSplitPoints = array(0xF003, 0xF004, 0xF00D); // add identifiers if we find more + + $splitPoint = self::_GetInt2d($recordData, 2); + if (in_array($splitPoint, $validSplitPoints)) { + // get spliced record data (and move pointer to next record) + $splicedRecordData = $this->_getSplicedRecordData(); + $this->_drawingData .= $splicedRecordData['recordData']; + + return; + } + + // move stream pointer to next record + $this->_pos += 4 + $length; + + } + + + /** + * Reads a record from current position in data stream and continues reading data as long as CONTINUE + * records are found. Splices the record data pieces and returns the combined string as if record data + * is in one piece. + * Moves to next current position in data stream to start of next record different from a CONtINUE record + * + * @return array + */ + private function _getSplicedRecordData() + { + $data = ''; + $spliceOffsets = array(); + + $i = 0; + $spliceOffsets[0] = 0; + + do { + ++$i; + + // offset: 0; size: 2; identifier + $identifier = self::_GetInt2d($this->_data, $this->_pos); + // offset: 2; size: 2; length + $length = self::_GetInt2d($this->_data, $this->_pos + 2); + $data .= $this->_readRecordData($this->_data, $this->_pos + 4, $length); + + $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length; + + $this->_pos += 4 + $length; + $nextIdentifier = self::_GetInt2d($this->_data, $this->_pos); + } + while ($nextIdentifier == self::XLS_Type_CONTINUE); + + $splicedData = array( + 'recordData' => $data, + 'spliceOffsets' => $spliceOffsets, + ); + + return $splicedData; + + } + + + /** + * Convert formula structure into human readable Excel formula like 'A3+A5*5' + * + * @param string $formulaStructure The complete binary data for the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function _getFormulaFromStructure($formulaStructure, $baseCell = 'A1') + { + // offset: 0; size: 2; size of the following formula data + $sz = self::_GetInt2d($formulaStructure, 0); + + // offset: 2; size: sz + $formulaData = substr($formulaStructure, 2, $sz); + + // for debug: dump the formula data + //echo ''; + //echo 'size: ' . $sz . "\n"; + //echo 'the entire formula data: '; + //Debug::dump($formulaData); + //echo "\n----\n"; + + // offset: 2 + sz; size: variable (optional) + if (strlen($formulaStructure) > 2 + $sz) { + $additionalData = substr($formulaStructure, 2 + $sz); + + // for debug: dump the additional data + //echo 'the entire additional data: '; + //Debug::dump($additionalData); + //echo "\n----\n"; + + } else { + $additionalData = ''; + } + + return $this->_getFormulaFromData($formulaData, $additionalData, $baseCell); + } + + + /** + * Take formula data and additional data for formula and return human readable formula + * + * @param string $formulaData The binary data for the formula itself + * @param string $additionalData Additional binary data going with the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function _getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1') + { + // start parsing the formula data + $tokens = array(); + + while (strlen($formulaData) > 0 and $token = $this->_getNextToken($formulaData, $baseCell)) { + $tokens[] = $token; + $formulaData = substr($formulaData, $token['size']); + + // for debug: dump the token + //var_dump($token); + } + + $formulaString = $this->_createFormulaFromTokens($tokens, $additionalData); + + return $formulaString; + } + + + /** + * Take array of tokens together with additional data for formula and return human readable formula + * + * @param array $tokens + * @param array $additionalData Additional binary data going with the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function _createFormulaFromTokens($tokens, $additionalData) + { + // empty formula? + if (empty($tokens)) { + return ''; + } + + $formulaStrings = array(); + foreach ($tokens as $token) { + // initialize spaces + $space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen + $space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen + $space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis + $space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis + $space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis + $space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis + + switch ($token['name']) { + case 'tAdd': // addition + case 'tConcat': // addition + case 'tDiv': // division + case 'tEQ': // equality + case 'tGE': // greater than or equal + case 'tGT': // greater than + case 'tIsect': // intersection + case 'tLE': // less than or equal + case 'tList': // less than or equal + case 'tLT': // less than + case 'tMul': // multiplication + case 'tNE': // multiplication + case 'tPower': // power + case 'tRange': // range + case 'tSub': // subtraction + $op2 = array_pop($formulaStrings); + $op1 = array_pop($formulaStrings); + $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2"; + unset($space0, $space1); + break; + case 'tUplus': // unary plus + case 'tUminus': // unary minus + $op = array_pop($formulaStrings); + $formulaStrings[] = "$space1$space0{$token['data']}$op"; + unset($space0, $space1); + break; + case 'tPercent': // percent sign + $op = array_pop($formulaStrings); + $formulaStrings[] = "$op$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + case 'tAttrVolatile': // indicates volatile function + case 'tAttrIf': + case 'tAttrSkip': + case 'tAttrChoose': + // token is only important for Excel formula evaluator + // do nothing + break; + case 'tAttrSpace': // space / carriage return + // space will be used when next token arrives, do not alter formulaString stack + switch ($token['data']['spacetype']) { + case 'type0': + $space0 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type1': + $space1 = str_repeat("\n", $token['data']['spacecount']); + break; + case 'type2': + $space2 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type3': + $space3 = str_repeat("\n", $token['data']['spacecount']); + break; + case 'type4': + $space4 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type5': + $space5 = str_repeat("\n", $token['data']['spacecount']); + break; + } + break; + case 'tAttrSum': // SUM function with one parameter + $op = array_pop($formulaStrings); + $formulaStrings[] = "{$space1}{$space0}SUM($op)"; + unset($space0, $space1); + break; + case 'tFunc': // function with fixed number of arguments + case 'tFuncV': // function with variable number of arguments + if ($token['data']['function'] != '') { + // normal function + $ops = array(); // array of operators + for ($i = 0; $i < $token['data']['args']; ++$i) { + $ops[] = array_pop($formulaStrings); + } + $ops = array_reverse($ops); + $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ")"; + unset($space0, $space1); + } else { + // add-in function + $ops = array(); // array of operators + for ($i = 0; $i < $token['data']['args'] - 1; ++$i) { + $ops[] = array_pop($formulaStrings); + } + $ops = array_reverse($ops); + $function = array_pop($formulaStrings); + $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ")"; + unset($space0, $space1); + } + break; + case 'tParen': // parenthesis + $expression = array_pop($formulaStrings); + $formulaStrings[] = "$space3$space2($expression$space5$space4)"; + unset($space2, $space3, $space4, $space5); + break; + case 'tArray': // array constant + $constantArray = self::_readBIFF8ConstantArray($additionalData); + $formulaStrings[] = $space1 . $space0 . $constantArray['value']; + $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data + unset($space0, $space1); + break; + case 'tMemArea': + // bite off chunk of additional data + $cellRangeAddressList = $this->_readBIFF8CellRangeAddressList($additionalData); + $additionalData = substr($additionalData, $cellRangeAddressList['size']); + $formulaStrings[] = "$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + case 'tArea': // cell range address + case 'tBool': // boolean + case 'tErr': // error code + case 'tInt': // integer + case 'tMemErr': + case 'tMemFunc': + case 'tMissArg': + case 'tName': + case 'tNameX': + case 'tNum': // number + case 'tRef': // single cell reference + case 'tRef3d': // 3d cell reference + case 'tArea3d': // 3d cell range reference + case 'tRefN': + case 'tAreaN': + case 'tStr': // string + $formulaStrings[] = "$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + } + } + $formulaString = $formulaStrings[0]; + + // for debug: dump the human readable formula + //echo '----' . "\n"; + //echo 'Formula: ' . $formulaString; + + return $formulaString; + } + + + /** + * Fetch next token from binary formula data + * + * @param string Formula data + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return array + * @throws PHPExcel_Reader_Exception + */ + private function _getNextToken($formulaData, $baseCell = 'A1') + { + // offset: 0; size: 1; token id + $id = ord($formulaData[0]); // token id + $name = false; // initialize token name + + switch ($id) { + case 0x03: $name = 'tAdd'; $size = 1; $data = '+'; break; + case 0x04: $name = 'tSub'; $size = 1; $data = '-'; break; + case 0x05: $name = 'tMul'; $size = 1; $data = '*'; break; + case 0x06: $name = 'tDiv'; $size = 1; $data = '/'; break; + case 0x07: $name = 'tPower'; $size = 1; $data = '^'; break; + case 0x08: $name = 'tConcat'; $size = 1; $data = '&'; break; + case 0x09: $name = 'tLT'; $size = 1; $data = '<'; break; + case 0x0A: $name = 'tLE'; $size = 1; $data = '<='; break; + case 0x0B: $name = 'tEQ'; $size = 1; $data = '='; break; + case 0x0C: $name = 'tGE'; $size = 1; $data = '>='; break; + case 0x0D: $name = 'tGT'; $size = 1; $data = '>'; break; + case 0x0E: $name = 'tNE'; $size = 1; $data = '<>'; break; + case 0x0F: $name = 'tIsect'; $size = 1; $data = ' '; break; + case 0x10: $name = 'tList'; $size = 1; $data = ','; break; + case 0x11: $name = 'tRange'; $size = 1; $data = ':'; break; + case 0x12: $name = 'tUplus'; $size = 1; $data = '+'; break; + case 0x13: $name = 'tUminus'; $size = 1; $data = '-'; break; + case 0x14: $name = 'tPercent'; $size = 1; $data = '%'; break; + case 0x15: // parenthesis + $name = 'tParen'; + $size = 1; + $data = null; + break; + case 0x16: // missing argument + $name = 'tMissArg'; + $size = 1; + $data = ''; + break; + case 0x17: // string + $name = 'tStr'; + // offset: 1; size: var; Unicode string, 8-bit string length + $string = self::_readUnicodeStringShort(substr($formulaData, 1)); + $size = 1 + $string['size']; + $data = self::_UTF8toExcelDoubleQuoted($string['value']); + break; + case 0x19: // Special attribute + // offset: 1; size: 1; attribute type flags: + switch (ord($formulaData[1])) { + case 0x01: + $name = 'tAttrVolatile'; + $size = 4; + $data = null; + break; + case 0x02: + $name = 'tAttrIf'; + $size = 4; + $data = null; + break; + case 0x04: + $name = 'tAttrChoose'; + // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1) + $nc = self::_GetInt2d($formulaData, 2); + // offset: 4; size: 2 * $nc + // offset: 4 + 2 * $nc; size: 2 + $size = 2 * $nc + 6; + $data = null; + break; + case 0x08: + $name = 'tAttrSkip'; + $size = 4; + $data = null; + break; + case 0x10: + $name = 'tAttrSum'; + $size = 4; + $data = null; + break; + case 0x40: + case 0x41: + $name = 'tAttrSpace'; + $size = 4; + // offset: 2; size: 2; space type and position + switch (ord($formulaData[2])) { + case 0x00: + $spacetype = 'type0'; + break; + case 0x01: + $spacetype = 'type1'; + break; + case 0x02: + $spacetype = 'type2'; + break; + case 0x03: + $spacetype = 'type3'; + break; + case 0x04: + $spacetype = 'type4'; + break; + case 0x05: + $spacetype = 'type5'; + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized space type in tAttrSpace token'); + break; + } + // offset: 3; size: 1; number of inserted spaces/carriage returns + $spacecount = ord($formulaData[3]); + + $data = array('spacetype' => $spacetype, 'spacecount' => $spacecount); + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized attribute flag in tAttr token'); + break; + } + break; + case 0x1C: // error code + // offset: 1; size: 1; error code + $name = 'tErr'; + $size = 2; + $data = self::_mapErrorCode(ord($formulaData[1])); + break; + case 0x1D: // boolean + // offset: 1; size: 1; 0 = false, 1 = true; + $name = 'tBool'; + $size = 2; + $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE'; + break; + case 0x1E: // integer + // offset: 1; size: 2; unsigned 16-bit integer + $name = 'tInt'; + $size = 3; + $data = self::_GetInt2d($formulaData, 1); + break; + case 0x1F: // number + // offset: 1; size: 8; + $name = 'tNum'; + $size = 9; + $data = self::_extractNumber(substr($formulaData, 1)); + $data = str_replace(',', '.', (string)$data); // in case non-English locale + break; + case 0x20: // array constant + case 0x40: + case 0x60: + // offset: 1; size: 7; not used + $name = 'tArray'; + $size = 8; + $data = null; + break; + case 0x21: // function with fixed number of arguments + case 0x41: + case 0x61: + $name = 'tFunc'; + $size = 3; + // offset: 1; size: 2; index to built-in sheet function + switch (self::_GetInt2d($formulaData, 1)) { + case 2: $function = 'ISNA'; $args = 1; break; + case 3: $function = 'ISERROR'; $args = 1; break; + case 10: $function = 'NA'; $args = 0; break; + case 15: $function = 'SIN'; $args = 1; break; + case 16: $function = 'COS'; $args = 1; break; + case 17: $function = 'TAN'; $args = 1; break; + case 18: $function = 'ATAN'; $args = 1; break; + case 19: $function = 'PI'; $args = 0; break; + case 20: $function = 'SQRT'; $args = 1; break; + case 21: $function = 'EXP'; $args = 1; break; + case 22: $function = 'LN'; $args = 1; break; + case 23: $function = 'LOG10'; $args = 1; break; + case 24: $function = 'ABS'; $args = 1; break; + case 25: $function = 'INT'; $args = 1; break; + case 26: $function = 'SIGN'; $args = 1; break; + case 27: $function = 'ROUND'; $args = 2; break; + case 30: $function = 'REPT'; $args = 2; break; + case 31: $function = 'MID'; $args = 3; break; + case 32: $function = 'LEN'; $args = 1; break; + case 33: $function = 'VALUE'; $args = 1; break; + case 34: $function = 'TRUE'; $args = 0; break; + case 35: $function = 'FALSE'; $args = 0; break; + case 38: $function = 'NOT'; $args = 1; break; + case 39: $function = 'MOD'; $args = 2; break; + case 40: $function = 'DCOUNT'; $args = 3; break; + case 41: $function = 'DSUM'; $args = 3; break; + case 42: $function = 'DAVERAGE'; $args = 3; break; + case 43: $function = 'DMIN'; $args = 3; break; + case 44: $function = 'DMAX'; $args = 3; break; + case 45: $function = 'DSTDEV'; $args = 3; break; + case 48: $function = 'TEXT'; $args = 2; break; + case 61: $function = 'MIRR'; $args = 3; break; + case 63: $function = 'RAND'; $args = 0; break; + case 65: $function = 'DATE'; $args = 3; break; + case 66: $function = 'TIME'; $args = 3; break; + case 67: $function = 'DAY'; $args = 1; break; + case 68: $function = 'MONTH'; $args = 1; break; + case 69: $function = 'YEAR'; $args = 1; break; + case 71: $function = 'HOUR'; $args = 1; break; + case 72: $function = 'MINUTE'; $args = 1; break; + case 73: $function = 'SECOND'; $args = 1; break; + case 74: $function = 'NOW'; $args = 0; break; + case 75: $function = 'AREAS'; $args = 1; break; + case 76: $function = 'ROWS'; $args = 1; break; + case 77: $function = 'COLUMNS'; $args = 1; break; + case 83: $function = 'TRANSPOSE'; $args = 1; break; + case 86: $function = 'TYPE'; $args = 1; break; + case 97: $function = 'ATAN2'; $args = 2; break; + case 98: $function = 'ASIN'; $args = 1; break; + case 99: $function = 'ACOS'; $args = 1; break; + case 105: $function = 'ISREF'; $args = 1; break; + case 111: $function = 'CHAR'; $args = 1; break; + case 112: $function = 'LOWER'; $args = 1; break; + case 113: $function = 'UPPER'; $args = 1; break; + case 114: $function = 'PROPER'; $args = 1; break; + case 117: $function = 'EXACT'; $args = 2; break; + case 118: $function = 'TRIM'; $args = 1; break; + case 119: $function = 'REPLACE'; $args = 4; break; + case 121: $function = 'CODE'; $args = 1; break; + case 126: $function = 'ISERR'; $args = 1; break; + case 127: $function = 'ISTEXT'; $args = 1; break; + case 128: $function = 'ISNUMBER'; $args = 1; break; + case 129: $function = 'ISBLANK'; $args = 1; break; + case 130: $function = 'T'; $args = 1; break; + case 131: $function = 'N'; $args = 1; break; + case 140: $function = 'DATEVALUE'; $args = 1; break; + case 141: $function = 'TIMEVALUE'; $args = 1; break; + case 142: $function = 'SLN'; $args = 3; break; + case 143: $function = 'SYD'; $args = 4; break; + case 162: $function = 'CLEAN'; $args = 1; break; + case 163: $function = 'MDETERM'; $args = 1; break; + case 164: $function = 'MINVERSE'; $args = 1; break; + case 165: $function = 'MMULT'; $args = 2; break; + case 184: $function = 'FACT'; $args = 1; break; + case 189: $function = 'DPRODUCT'; $args = 3; break; + case 190: $function = 'ISNONTEXT'; $args = 1; break; + case 195: $function = 'DSTDEVP'; $args = 3; break; + case 196: $function = 'DVARP'; $args = 3; break; + case 198: $function = 'ISLOGICAL'; $args = 1; break; + case 199: $function = 'DCOUNTA'; $args = 3; break; + case 207: $function = 'REPLACEB'; $args = 4; break; + case 210: $function = 'MIDB'; $args = 3; break; + case 211: $function = 'LENB'; $args = 1; break; + case 212: $function = 'ROUNDUP'; $args = 2; break; + case 213: $function = 'ROUNDDOWN'; $args = 2; break; + case 214: $function = 'ASC'; $args = 1; break; + case 215: $function = 'DBCS'; $args = 1; break; + case 221: $function = 'TODAY'; $args = 0; break; + case 229: $function = 'SINH'; $args = 1; break; + case 230: $function = 'COSH'; $args = 1; break; + case 231: $function = 'TANH'; $args = 1; break; + case 232: $function = 'ASINH'; $args = 1; break; + case 233: $function = 'ACOSH'; $args = 1; break; + case 234: $function = 'ATANH'; $args = 1; break; + case 235: $function = 'DGET'; $args = 3; break; + case 244: $function = 'INFO'; $args = 1; break; + case 252: $function = 'FREQUENCY'; $args = 2; break; + case 261: $function = 'ERROR.TYPE'; $args = 1; break; + case 271: $function = 'GAMMALN'; $args = 1; break; + case 273: $function = 'BINOMDIST'; $args = 4; break; + case 274: $function = 'CHIDIST'; $args = 2; break; + case 275: $function = 'CHIINV'; $args = 2; break; + case 276: $function = 'COMBIN'; $args = 2; break; + case 277: $function = 'CONFIDENCE'; $args = 3; break; + case 278: $function = 'CRITBINOM'; $args = 3; break; + case 279: $function = 'EVEN'; $args = 1; break; + case 280: $function = 'EXPONDIST'; $args = 3; break; + case 281: $function = 'FDIST'; $args = 3; break; + case 282: $function = 'FINV'; $args = 3; break; + case 283: $function = 'FISHER'; $args = 1; break; + case 284: $function = 'FISHERINV'; $args = 1; break; + case 285: $function = 'FLOOR'; $args = 2; break; + case 286: $function = 'GAMMADIST'; $args = 4; break; + case 287: $function = 'GAMMAINV'; $args = 3; break; + case 288: $function = 'CEILING'; $args = 2; break; + case 289: $function = 'HYPGEOMDIST'; $args = 4; break; + case 290: $function = 'LOGNORMDIST'; $args = 3; break; + case 291: $function = 'LOGINV'; $args = 3; break; + case 292: $function = 'NEGBINOMDIST'; $args = 3; break; + case 293: $function = 'NORMDIST'; $args = 4; break; + case 294: $function = 'NORMSDIST'; $args = 1; break; + case 295: $function = 'NORMINV'; $args = 3; break; + case 296: $function = 'NORMSINV'; $args = 1; break; + case 297: $function = 'STANDARDIZE'; $args = 3; break; + case 298: $function = 'ODD'; $args = 1; break; + case 299: $function = 'PERMUT'; $args = 2; break; + case 300: $function = 'POISSON'; $args = 3; break; + case 301: $function = 'TDIST'; $args = 3; break; + case 302: $function = 'WEIBULL'; $args = 4; break; + case 303: $function = 'SUMXMY2'; $args = 2; break; + case 304: $function = 'SUMX2MY2'; $args = 2; break; + case 305: $function = 'SUMX2PY2'; $args = 2; break; + case 306: $function = 'CHITEST'; $args = 2; break; + case 307: $function = 'CORREL'; $args = 2; break; + case 308: $function = 'COVAR'; $args = 2; break; + case 309: $function = 'FORECAST'; $args = 3; break; + case 310: $function = 'FTEST'; $args = 2; break; + case 311: $function = 'INTERCEPT'; $args = 2; break; + case 312: $function = 'PEARSON'; $args = 2; break; + case 313: $function = 'RSQ'; $args = 2; break; + case 314: $function = 'STEYX'; $args = 2; break; + case 315: $function = 'SLOPE'; $args = 2; break; + case 316: $function = 'TTEST'; $args = 4; break; + case 325: $function = 'LARGE'; $args = 2; break; + case 326: $function = 'SMALL'; $args = 2; break; + case 327: $function = 'QUARTILE'; $args = 2; break; + case 328: $function = 'PERCENTILE'; $args = 2; break; + case 331: $function = 'TRIMMEAN'; $args = 2; break; + case 332: $function = 'TINV'; $args = 2; break; + case 337: $function = 'POWER'; $args = 2; break; + case 342: $function = 'RADIANS'; $args = 1; break; + case 343: $function = 'DEGREES'; $args = 1; break; + case 346: $function = 'COUNTIF'; $args = 2; break; + case 347: $function = 'COUNTBLANK'; $args = 1; break; + case 350: $function = 'ISPMT'; $args = 4; break; + case 351: $function = 'DATEDIF'; $args = 3; break; + case 352: $function = 'DATESTRING'; $args = 1; break; + case 353: $function = 'NUMBERSTRING'; $args = 2; break; + case 360: $function = 'PHONETIC'; $args = 1; break; + case 368: $function = 'BAHTTEXT'; $args = 1; break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized function in formula'); + break; + } + $data = array('function' => $function, 'args' => $args); + break; + case 0x22: // function with variable number of arguments + case 0x42: + case 0x62: + $name = 'tFuncV'; + $size = 4; + // offset: 1; size: 1; number of arguments + $args = ord($formulaData[1]); + // offset: 2: size: 2; index to built-in sheet function + $index = self::_GetInt2d($formulaData, 2); + switch ($index) { + case 0: $function = 'COUNT'; break; + case 1: $function = 'IF'; break; + case 4: $function = 'SUM'; break; + case 5: $function = 'AVERAGE'; break; + case 6: $function = 'MIN'; break; + case 7: $function = 'MAX'; break; + case 8: $function = 'ROW'; break; + case 9: $function = 'COLUMN'; break; + case 11: $function = 'NPV'; break; + case 12: $function = 'STDEV'; break; + case 13: $function = 'DOLLAR'; break; + case 14: $function = 'FIXED'; break; + case 28: $function = 'LOOKUP'; break; + case 29: $function = 'INDEX'; break; + case 36: $function = 'AND'; break; + case 37: $function = 'OR'; break; + case 46: $function = 'VAR'; break; + case 49: $function = 'LINEST'; break; + case 50: $function = 'TREND'; break; + case 51: $function = 'LOGEST'; break; + case 52: $function = 'GROWTH'; break; + case 56: $function = 'PV'; break; + case 57: $function = 'FV'; break; + case 58: $function = 'NPER'; break; + case 59: $function = 'PMT'; break; + case 60: $function = 'RATE'; break; + case 62: $function = 'IRR'; break; + case 64: $function = 'MATCH'; break; + case 70: $function = 'WEEKDAY'; break; + case 78: $function = 'OFFSET'; break; + case 82: $function = 'SEARCH'; break; + case 100: $function = 'CHOOSE'; break; + case 101: $function = 'HLOOKUP'; break; + case 102: $function = 'VLOOKUP'; break; + case 109: $function = 'LOG'; break; + case 115: $function = 'LEFT'; break; + case 116: $function = 'RIGHT'; break; + case 120: $function = 'SUBSTITUTE'; break; + case 124: $function = 'FIND'; break; + case 125: $function = 'CELL'; break; + case 144: $function = 'DDB'; break; + case 148: $function = 'INDIRECT'; break; + case 167: $function = 'IPMT'; break; + case 168: $function = 'PPMT'; break; + case 169: $function = 'COUNTA'; break; + case 183: $function = 'PRODUCT'; break; + case 193: $function = 'STDEVP'; break; + case 194: $function = 'VARP'; break; + case 197: $function = 'TRUNC'; break; + case 204: $function = 'USDOLLAR'; break; + case 205: $function = 'FINDB'; break; + case 206: $function = 'SEARCHB'; break; + case 208: $function = 'LEFTB'; break; + case 209: $function = 'RIGHTB'; break; + case 216: $function = 'RANK'; break; + case 219: $function = 'ADDRESS'; break; + case 220: $function = 'DAYS360'; break; + case 222: $function = 'VDB'; break; + case 227: $function = 'MEDIAN'; break; + case 228: $function = 'SUMPRODUCT'; break; + case 247: $function = 'DB'; break; + case 255: $function = ''; break; + case 269: $function = 'AVEDEV'; break; + case 270: $function = 'BETADIST'; break; + case 272: $function = 'BETAINV'; break; + case 317: $function = 'PROB'; break; + case 318: $function = 'DEVSQ'; break; + case 319: $function = 'GEOMEAN'; break; + case 320: $function = 'HARMEAN'; break; + case 321: $function = 'SUMSQ'; break; + case 322: $function = 'KURT'; break; + case 323: $function = 'SKEW'; break; + case 324: $function = 'ZTEST'; break; + case 329: $function = 'PERCENTRANK'; break; + case 330: $function = 'MODE'; break; + case 336: $function = 'CONCATENATE'; break; + case 344: $function = 'SUBTOTAL'; break; + case 345: $function = 'SUMIF'; break; + case 354: $function = 'ROMAN'; break; + case 358: $function = 'GETPIVOTDATA'; break; + case 359: $function = 'HYPERLINK'; break; + case 361: $function = 'AVERAGEA'; break; + case 362: $function = 'MAXA'; break; + case 363: $function = 'MINA'; break; + case 364: $function = 'STDEVPA'; break; + case 365: $function = 'VARPA'; break; + case 366: $function = 'STDEVA'; break; + case 367: $function = 'VARA'; break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized function in formula'); + break; + } + $data = array('function' => $function, 'args' => $args); + break; + case 0x23: // index to defined name + case 0x43: + case 0x63: + $name = 'tName'; + $size = 5; + // offset: 1; size: 2; one-based index to definedname record + $definedNameIndex = self::_GetInt2d($formulaData, 1) - 1; + // offset: 2; size: 2; not used + $data = $this->_definedname[$definedNameIndex]['name']; + break; + case 0x24: // single cell reference e.g. A5 + case 0x44: + case 0x64: + $name = 'tRef'; + $size = 5; + $data = $this->_readBIFF8CellAddress(substr($formulaData, 1, 4)); + break; + case 0x25: // cell range reference to cells in the same sheet (2d) + case 0x45: + case 0x65: + $name = 'tArea'; + $size = 9; + $data = $this->_readBIFF8CellRangeAddress(substr($formulaData, 1, 8)); + break; + case 0x26: // Constant reference sub-expression + case 0x46: + case 0x66: + $name = 'tMemArea'; + // offset: 1; size: 4; not used + // offset: 5; size: 2; size of the following subexpression + $subSize = self::_GetInt2d($formulaData, 5); + $size = 7 + $subSize; + $data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize)); + break; + case 0x27: // Deleted constant reference sub-expression + case 0x47: + case 0x67: + $name = 'tMemErr'; + // offset: 1; size: 4; not used + // offset: 5; size: 2; size of the following subexpression + $subSize = self::_GetInt2d($formulaData, 5); + $size = 7 + $subSize; + $data = $this->_getFormulaFromData(substr($formulaData, 7, $subSize)); + break; + case 0x29: // Variable reference sub-expression + case 0x49: + case 0x69: + $name = 'tMemFunc'; + // offset: 1; size: 2; size of the following sub-expression + $subSize = self::_GetInt2d($formulaData, 1); + $size = 3 + $subSize; + $data = $this->_getFormulaFromData(substr($formulaData, 3, $subSize)); + break; + + case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places + case 0x4C: + case 0x6C: + $name = 'tRefN'; + $size = 5; + $data = $this->_readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell); + break; + + case 0x2D: // Relative 2d range reference + case 0x4D: + case 0x6D: + $name = 'tAreaN'; + $size = 9; + $data = $this->_readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell); + break; + + case 0x39: // External name + case 0x59: + case 0x79: + $name = 'tNameX'; + $size = 7; + // offset: 1; size: 2; index to REF entry in EXTERNSHEET record + // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record + $index = self::_GetInt2d($formulaData, 3); + // assume index is to EXTERNNAME record + $data = $this->_externalNames[$index - 1]['name']; + // offset: 5; size: 2; not used + break; + + case 0x3A: // 3d reference to cell + case 0x5A: + case 0x7A: + $name = 'tRef3d'; + $size = 7; + + try { + // offset: 1; size: 2; index to REF entry + $sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1)); + // offset: 3; size: 4; cell address + $cellAddress = $this->_readBIFF8CellAddress(substr($formulaData, 3, 4)); + + $data = "$sheetRange!$cellAddress"; + } catch (PHPExcel_Exception $e) { + // deleted sheet reference + $data = '#REF!'; + } + + break; + case 0x3B: // 3d reference to cell range + case 0x5B: + case 0x7B: + $name = 'tArea3d'; + $size = 11; + + try { + // offset: 1; size: 2; index to REF entry + $sheetRange = $this->_readSheetRangeByRefIndex(self::_GetInt2d($formulaData, 1)); + // offset: 3; size: 8; cell address + $cellRangeAddress = $this->_readBIFF8CellRangeAddress(substr($formulaData, 3, 8)); + + $data = "$sheetRange!$cellRangeAddress"; + } catch (PHPExcel_Exception $e) { + // deleted sheet reference + $data = '#REF!'; + } + + break; + // Unknown cases // don't know how to deal with + default: + throw new PHPExcel_Reader_Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula'); + break; + } + + return array( + 'id' => $id, + 'name' => $name, + 'size' => $size, + 'data' => $data, + ); + } + + + /** + * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2' + * section 3.3.4 + * + * @param string $cellAddressStructure + * @return string + */ + private function _readBIFF8CellAddress($cellAddressStructure) + { + // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) + $row = self::_GetInt2d($cellAddressStructure, 0) + 1; + + // offset: 2; size: 2; index to column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $column = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($cellAddressStructure, 2)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) { + $column = '$' . $column; + } + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) { + $row = '$' . $row; + } + + return $column . $row; + } + + + /** + * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column + * to indicate offsets from a base cell + * section 3.3.4 + * + * @param string $cellAddressStructure + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string + */ + private function _readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1') + { + list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell); + $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1; + + // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) + $rowIndex = self::_GetInt2d($cellAddressStructure, 0); + $row = self::_GetInt2d($cellAddressStructure, 0) + 1; + + // offset: 2; size: 2; index to column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $colIndex = 0x00FF & self::_GetInt2d($cellAddressStructure, 2); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($cellAddressStructure, 2))) { + $column = PHPExcel_Cell::stringFromColumnIndex($colIndex); + $column = '$' . $column; + } else { + $colIndex = ($colIndex <= 127) ? $colIndex : $colIndex - 256; + $column = PHPExcel_Cell::stringFromColumnIndex($baseCol + $colIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($cellAddressStructure, 2))) { + $row = '$' . $row; + } else { + $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536; + $row = $baseRow + $rowIndex; + } + + return $column . $row; + } + + + /** + * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1' + * always fixed range + * section 2.5.14 + * + * @param string $subData + * @return string + * @throws PHPExcel_Reader_Exception + */ + private function _readBIFF5CellRangeAddressFixed($subData) + { + // offset: 0; size: 2; index to first row + $fr = self::_GetInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row + $lr = self::_GetInt2d($subData, 2) + 1; + + // offset: 4; size: 1; index to first column + $fc = ord($subData{4}); + + // offset: 5; size: 1; index to last column + $lc = ord($subData{5}); + + // check values + if ($fr > $lr || $fc > $lc) { + throw new PHPExcel_Reader_Exception('Not a cell range address'); + } + + // column index to letter + $fc = PHPExcel_Cell::stringFromColumnIndex($fc); + $lc = PHPExcel_Cell::stringFromColumnIndex($lc); + + if ($fr == $lr and $fc == $lc) { + return "$fc$fr"; + } + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1' + * always fixed range + * section 2.5.14 + * + * @param string $subData + * @return string + * @throws PHPExcel_Reader_Exception + */ + private function _readBIFF8CellRangeAddressFixed($subData) + { + // offset: 0; size: 2; index to first row + $fr = self::_GetInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row + $lr = self::_GetInt2d($subData, 2) + 1; + + // offset: 4; size: 2; index to first column + $fc = self::_GetInt2d($subData, 4); + + // offset: 6; size: 2; index to last column + $lc = self::_GetInt2d($subData, 6); + + // check values + if ($fr > $lr || $fc > $lc) { + throw new PHPExcel_Reader_Exception('Not a cell range address'); + } + + // column index to letter + $fc = PHPExcel_Cell::stringFromColumnIndex($fc); + $lc = PHPExcel_Cell::stringFromColumnIndex($lc); + + if ($fr == $lr and $fc == $lc) { + return "$fc$fr"; + } + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6' + * there are flags indicating whether column/row index is relative + * section 3.3.4 + * + * @param string $subData + * @return string + */ + private function _readBIFF8CellRangeAddress($subData) + { + // todo: if cell range is just a single cell, should this funciton + // not just return e.g. 'A1' and not 'A1:A1' ? + + // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767)) + $fr = self::_GetInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767)) + $lr = self::_GetInt2d($subData, 2) + 1; + + // offset: 4; size: 2; index to first column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $fc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 4)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($subData, 4))) { + $fc = '$' . $fc; + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($subData, 4))) { + $fr = '$' . $fr; + } + + // offset: 6; size: 2; index to last column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $lc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::_GetInt2d($subData, 6)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($subData, 6))) { + $lc = '$' . $lc; + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($subData, 6))) { + $lr = '$' . $lr; + } + + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column + * to indicate offsets from a base cell + * section 3.3.4 + * + * @param string $subData + * @param string $baseCell Base cell + * @return string Cell range address + */ + private function _readBIFF8CellRangeAddressB($subData, $baseCell = 'A1') + { + list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell); + $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1; + + // TODO: if cell range is just a single cell, should this funciton + // not just return e.g. 'A1' and not 'A1:A1' ? + + // offset: 0; size: 2; first row + $frIndex = self::_GetInt2d($subData, 0); // adjust below + + // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767) + $lrIndex = self::_GetInt2d($subData, 2); // adjust below + + // offset: 4; size: 2; first column with relative/absolute flags + + // bit: 7-0; mask 0x00FF; column index + $fcIndex = 0x00FF & self::_GetInt2d($subData, 4); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($subData, 4))) { + // absolute column index + $fc = PHPExcel_Cell::stringFromColumnIndex($fcIndex); + $fc = '$' . $fc; + } else { + // column offset + $fcIndex = ($fcIndex <= 127) ? $fcIndex : $fcIndex - 256; + $fc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $fcIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($subData, 4))) { + // absolute row index + $fr = $frIndex + 1; + $fr = '$' . $fr; + } else { + // row offset + $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536; + $fr = $baseRow + $frIndex; + } + + // offset: 6; size: 2; last column with relative/absolute flags + + // bit: 7-0; mask 0x00FF; column index + $lcIndex = 0x00FF & self::_GetInt2d($subData, 6); + $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256; + $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::_GetInt2d($subData, 6))) { + // absolute column index + $lc = PHPExcel_Cell::stringFromColumnIndex($lcIndex); + $lc = '$' . $lc; + } else { + // column offset + $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256; + $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::_GetInt2d($subData, 6))) { + // absolute row index + $lr = $lrIndex + 1; + $lr = '$' . $lr; + } else { + // row offset + $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536; + $lr = $baseRow + $lrIndex; + } + + return "$fc$fr:$lc$lr"; + } + + + /** + * Read BIFF8 cell range address list + * section 2.5.15 + * + * @param string $subData + * @return array + */ + private function _readBIFF8CellRangeAddressList($subData) + { + $cellRangeAddresses = array(); + + // offset: 0; size: 2; number of the following cell range addresses + $nm = self::_GetInt2d($subData, 0); + + $offset = 2; + // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses + for ($i = 0; $i < $nm; ++$i) { + $cellRangeAddresses[] = $this->_readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8)); + $offset += 8; + } + + return array( + 'size' => 2 + 8 * $nm, + 'cellRangeAddresses' => $cellRangeAddresses, + ); + } + + + /** + * Read BIFF5 cell range address list + * section 2.5.15 + * + * @param string $subData + * @return array + */ + private function _readBIFF5CellRangeAddressList($subData) + { + $cellRangeAddresses = array(); + + // offset: 0; size: 2; number of the following cell range addresses + $nm = self::_GetInt2d($subData, 0); + + $offset = 2; + // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses + for ($i = 0; $i < $nm; ++$i) { + $cellRangeAddresses[] = $this->_readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6)); + $offset += 6; + } + + return array( + 'size' => 2 + 6 * $nm, + 'cellRangeAddresses' => $cellRangeAddresses, + ); + } + + + /** + * Get a sheet range like Sheet1:Sheet3 from REF index + * Note: If there is only one sheet in the range, one gets e.g Sheet1 + * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets, + * in which case an PHPExcel_Reader_Exception is thrown + * + * @param int $index + * @return string|false + * @throws PHPExcel_Reader_Exception + */ + private function _readSheetRangeByRefIndex($index) + { + if (isset($this->_ref[$index])) { + + $type = $this->_externalBooks[$this->_ref[$index]['externalBookIndex']]['type']; + + switch ($type) { + case 'internal': + // check if we have a deleted 3d reference + if ($this->_ref[$index]['firstSheetIndex'] == 0xFFFF or $this->_ref[$index]['lastSheetIndex'] == 0xFFFF) { + throw new PHPExcel_Reader_Exception('Deleted sheet reference'); + } + + // we have normal sheet range (collapsed or uncollapsed) + $firstSheetName = $this->_sheets[$this->_ref[$index]['firstSheetIndex']]['name']; + $lastSheetName = $this->_sheets[$this->_ref[$index]['lastSheetIndex']]['name']; + + if ($firstSheetName == $lastSheetName) { + // collapsed sheet range + $sheetRange = $firstSheetName; + } else { + $sheetRange = "$firstSheetName:$lastSheetName"; + } + + // escape the single-quotes + $sheetRange = str_replace("'", "''", $sheetRange); + + // if there are special characters, we need to enclose the range in single-quotes + // todo: check if we have identified the whole set of special characters + // it seems that the following characters are not accepted for sheet names + // and we may assume that they are not present: []*/:\? + if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/", $sheetRange)) { + $sheetRange = "'$sheetRange'"; + } + + return $sheetRange; + break; + + default: + // TODO: external sheet support + throw new PHPExcel_Reader_Exception('Excel5 reader only supports internal sheets in fomulas'); + break; + } + } + return false; + } + + + /** + * read BIFF8 constant value array from array data + * returns e.g. array('value' => '{1,2;3,4}', 'size' => 40} + * section 2.5.8 + * + * @param string $arrayData + * @return array + */ + private static function _readBIFF8ConstantArray($arrayData) + { + // offset: 0; size: 1; number of columns decreased by 1 + $nc = ord($arrayData[0]); + + // offset: 1; size: 2; number of rows decreased by 1 + $nr = self::_GetInt2d($arrayData, 1); + $size = 3; // initialize + $arrayData = substr($arrayData, 3); + + // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values + $matrixChunks = array(); + for ($r = 1; $r <= $nr + 1; ++$r) { + $items = array(); + for ($c = 1; $c <= $nc + 1; ++$c) { + $constant = self::_readBIFF8Constant($arrayData); + $items[] = $constant['value']; + $arrayData = substr($arrayData, $constant['size']); + $size += $constant['size']; + } + $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"' + } + $matrix = '{' . implode(';', $matrixChunks) . '}'; + + return array( + 'value' => $matrix, + 'size' => $size, + ); + } + + + /** + * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value' + * section 2.5.7 + * returns e.g. array('value' => '5', 'size' => 9) + * + * @param string $valueData + * @return array + */ + private static function _readBIFF8Constant($valueData) + { + // offset: 0; size: 1; identifier for type of constant + $identifier = ord($valueData[0]); + + switch ($identifier) { + case 0x00: // empty constant (what is this?) + $value = ''; + $size = 9; + break; + case 0x01: // number + // offset: 1; size: 8; IEEE 754 floating-point value + $value = self::_extractNumber(substr($valueData, 1, 8)); + $size = 9; + break; + case 0x02: // string value + // offset: 1; size: var; Unicode string, 16-bit string length + $string = self::_readUnicodeStringLong(substr($valueData, 1)); + $value = '"' . $string['value'] . '"'; + $size = 1 + $string['size']; + break; + case 0x04: // boolean + // offset: 1; size: 1; 0 = FALSE, 1 = TRUE + if (ord($valueData[1])) { + $value = 'TRUE'; + } else { + $value = 'FALSE'; + } + $size = 9; + break; + case 0x10: // error code + // offset: 1; size: 1; error code + $value = self::_mapErrorCode(ord($valueData[1])); + $size = 9; + break; + } + return array( + 'value' => $value, + 'size' => $size, + ); + } + + + /** + * Extract RGB color + * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4 + * + * @param string $rgb Encoded RGB value (4 bytes) + * @return array + */ + private static function _readRGB($rgb) + { + // offset: 0; size 1; Red component + $r = ord($rgb{0}); + + // offset: 1; size: 1; Green component + $g = ord($rgb{1}); + + // offset: 2; size: 1; Blue component + $b = ord($rgb{2}); + + // HEX notation, e.g. 'FF00FC' + $rgb = sprintf('%02X%02X%02X', $r, $g, $b); + + return array('rgb' => $rgb); + } + + + /** + * Read byte string (8-bit string length) + * OpenOffice documentation: 2.5.2 + * + * @param string $subData + * @return array + */ + private function _readByteStringShort($subData) + { + // offset: 0; size: 1; length of the string (character count) + $ln = ord($subData[0]); + + // offset: 1: size: var; character array (8-bit characters) + $value = $this->_decodeCodepage(substr($subData, 1, $ln)); + + return array( + 'value' => $value, + 'size' => 1 + $ln, // size in bytes of data structure + ); + } + + + /** + * Read byte string (16-bit string length) + * OpenOffice documentation: 2.5.2 + * + * @param string $subData + * @return array + */ + private function _readByteStringLong($subData) + { + // offset: 0; size: 2; length of the string (character count) + $ln = self::_GetInt2d($subData, 0); + + // offset: 2: size: var; character array (8-bit characters) + $value = $this->_decodeCodepage(substr($subData, 2)); + + //return $string; + return array( + 'value' => $value, + 'size' => 2 + $ln, // size in bytes of data structure + ); + } + + + /** + * Extracts an Excel Unicode short string (8-bit string length) + * OpenOffice documentation: 2.5.3 + * function will automatically find out where the Unicode string ends. + * + * @param string $subData + * @return array + */ + private static function _readUnicodeStringShort($subData) + { + $value = ''; + + // offset: 0: size: 1; length of the string (character count) + $characterCount = ord($subData[0]); + + $string = self::_readUnicodeString(substr($subData, 1), $characterCount); + + // add 1 for the string length + $string['size'] += 1; + + return $string; + } + + + /** + * Extracts an Excel Unicode long string (16-bit string length) + * OpenOffice documentation: 2.5.3 + * this function is under construction, needs to support rich text, and Asian phonetic settings + * + * @param string $subData + * @return array + */ + private static function _readUnicodeStringLong($subData) + { + $value = ''; + + // offset: 0: size: 2; length of the string (character count) + $characterCount = self::_GetInt2d($subData, 0); + + $string = self::_readUnicodeString(substr($subData, 2), $characterCount); + + // add 2 for the string length + $string['size'] += 2; + + return $string; + } + + + /** + * Read Unicode string with no string length field, but with known character count + * this function is under construction, needs to support rich text, and Asian phonetic settings + * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3 + * + * @param string $subData + * @param int $characterCount + * @return array + */ + private static function _readUnicodeString($subData, $characterCount) + { + $value = ''; + + // offset: 0: size: 1; option flags + + // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit) + $isCompressed = !((0x01 & ord($subData[0])) >> 0); + + // bit: 2; mask: 0x04; Asian phonetic settings + $hasAsian = (0x04) & ord($subData[0]) >> 2; + + // bit: 3; mask: 0x08; Rich-Text settings + $hasRichText = (0x08) & ord($subData[0]) >> 3; + + // offset: 1: size: var; character array + // this offset assumes richtext and Asian phonetic settings are off which is generally wrong + // needs to be fixed + $value = self::_encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed); + + return array( + 'value' => $value, + 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags + ); + } + + + /** + * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas. + * Example: hello"world --> "hello""world" + * + * @param string $value UTF-8 encoded string + * @return string + */ + private static function _UTF8toExcelDoubleQuoted($value) + { + return '"' . str_replace('"', '""', $value) . '"'; + } + + + /** + * Reads first 8 bytes of a string and return IEEE 754 float + * + * @param string $data Binary string that is at least 8 bytes long + * @return float + */ + private static function _extractNumber($data) + { + $rknumhigh = self::_GetInt4d($data, 4); + $rknumlow = self::_GetInt4d($data, 0); + $sign = ($rknumhigh & 0x80000000) >> 31; + $exp = (($rknumhigh & 0x7ff00000) >> 20) - 1023; + $mantissa = (0x100000 | ($rknumhigh & 0x000fffff)); + $mantissalow1 = ($rknumlow & 0x80000000) >> 31; + $mantissalow2 = ($rknumlow & 0x7fffffff); + $value = $mantissa / pow( 2 , (20 - $exp)); + + if ($mantissalow1 != 0) { + $value += 1 / pow (2 , (21 - $exp)); + } + + $value += $mantissalow2 / pow (2 , (52 - $exp)); + if ($sign) { + $value *= -1; + } + + return $value; + } + + + private static function _GetIEEE754($rknum) + { + if (($rknum & 0x02) != 0) { + $value = $rknum >> 2; + } else { + // changes by mmp, info on IEEE754 encoding from + // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html + // The RK format calls for using only the most significant 30 bits + // of the 64 bit floating point value. The other 34 bits are assumed + // to be 0 so we use the upper 30 bits of $rknum as follows... + $sign = ($rknum & 0x80000000) >> 31; + $exp = ($rknum & 0x7ff00000) >> 20; + $mantissa = (0x100000 | ($rknum & 0x000ffffc)); + $value = $mantissa / pow( 2 , (20- ($exp - 1023))); + if ($sign) { + $value = -1 * $value; + } + //end of changes by mmp + } + if (($rknum & 0x01) != 0) { + $value /= 100; + } + return $value; + } + + + /** + * Get UTF-8 string from (compressed or uncompressed) UTF-16 string + * + * @param string $string + * @param bool $compressed + * @return string + */ + private static function _encodeUTF16($string, $compressed = '') + { + if ($compressed) { + $string = self::_uncompressByteString($string); + } + + return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', 'UTF-16LE'); + } + + + /** + * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8. + * + * @param string $string + * @return string + */ + private static function _uncompressByteString($string) + { + $uncompressedString = ''; + $strLen = strlen($string); + for ($i = 0; $i < $strLen; ++$i) { + $uncompressedString .= $string[$i] . "\0"; + } + + return $uncompressedString; + } + + + /** + * Convert string to UTF-8. Only used for BIFF5. + * + * @param string $string + * @return string + */ + private function _decodeCodepage($string) + { + return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', $this->_codepage); + } + + + /** + * Read 16-bit unsigned integer + * + * @param string $data + * @param int $pos + * @return int + */ + public static function _GetInt2d($data, $pos) + { + return ord($data[$pos]) | (ord($data[$pos+1]) << 8); + } + + + /** + * Read 32-bit signed integer + * + * @param string $data + * @param int $pos + * @return int + */ + public static function _GetInt4d($data, $pos) + { + // FIX: represent numbers correctly on 64-bit system + // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 + // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems + $_or_24 = ord($data[$pos + 3]); + if ($_or_24 >= 128) { + // negative number + $_ord_24 = -abs((256 - $_or_24) << 24); + } else { + $_ord_24 = ($_or_24 & 127) << 24; + } + return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | $_ord_24; + } + + + /** + * Read color + * + * @param int $color Indexed color + * @param array $palette Color palette + * @return array RGB color value, example: array('rgb' => 'FF0000') + */ + private static function _readColor($color,$palette,$version) + { + if ($color <= 0x07 || $color >= 0x40) { + // special built-in color + return self::_mapBuiltInColor($color); + } elseif (isset($palette) && isset($palette[$color - 8])) { + // palette color, color index 0x08 maps to pallete index 0 + return $palette[$color - 8]; + } else { + // default color table + if ($version == self::XLS_BIFF8) { + return self::_mapColor($color); + } else { + // BIFF5 + return self::_mapColorBIFF5($color); + } + } + + return $color; + } + + + /** + * Map border style + * OpenOffice documentation: 2.5.11 + * + * @param int $index + * @return string + */ + private static function _mapBorderStyle($index) + { + switch ($index) { + case 0x00: return PHPExcel_Style_Border::BORDER_NONE; + case 0x01: return PHPExcel_Style_Border::BORDER_THIN; + case 0x02: return PHPExcel_Style_Border::BORDER_MEDIUM; + case 0x03: return PHPExcel_Style_Border::BORDER_DASHED; + case 0x04: return PHPExcel_Style_Border::BORDER_DOTTED; + case 0x05: return PHPExcel_Style_Border::BORDER_THICK; + case 0x06: return PHPExcel_Style_Border::BORDER_DOUBLE; + case 0x07: return PHPExcel_Style_Border::BORDER_HAIR; + case 0x08: return PHPExcel_Style_Border::BORDER_MEDIUMDASHED; + case 0x09: return PHPExcel_Style_Border::BORDER_DASHDOT; + case 0x0A: return PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT; + case 0x0B: return PHPExcel_Style_Border::BORDER_DASHDOTDOT; + case 0x0C: return PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT; + case 0x0D: return PHPExcel_Style_Border::BORDER_SLANTDASHDOT; + default: return PHPExcel_Style_Border::BORDER_NONE; + } + } + + + /** + * Get fill pattern from index + * OpenOffice documentation: 2.5.12 + * + * @param int $index + * @return string + */ + private static function _mapFillPattern($index) + { + switch ($index) { + case 0x00: return PHPExcel_Style_Fill::FILL_NONE; + case 0x01: return PHPExcel_Style_Fill::FILL_SOLID; + case 0x02: return PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY; + case 0x03: return PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY; + case 0x04: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY; + case 0x05: return PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL; + case 0x06: return PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL; + case 0x07: return PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN; + case 0x08: return PHPExcel_Style_Fill::FILL_PATTERN_DARKUP; + case 0x09: return PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID; + case 0x0A: return PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS; + case 0x0B: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL; + case 0x0C: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL; + case 0x0D: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN; + case 0x0E: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP; + case 0x0F: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID; + case 0x10: return PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS; + case 0x11: return PHPExcel_Style_Fill::FILL_PATTERN_GRAY125; + case 0x12: return PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625; + default: return PHPExcel_Style_Fill::FILL_NONE; + } + } + + + /** + * Map error code, e.g. '#N/A' + * + * @param int $subData + * @return string + */ + private static function _mapErrorCode($subData) + { + switch ($subData) { + case 0x00: return '#NULL!'; break; + case 0x07: return '#DIV/0!'; break; + case 0x0F: return '#VALUE!'; break; + case 0x17: return '#REF!'; break; + case 0x1D: return '#NAME?'; break; + case 0x24: return '#NUM!'; break; + case 0x2A: return '#N/A'; break; + default: return false; + } + } + + + /** + * Map built-in color to RGB value + * + * @param int $color Indexed color + * @return array + */ + private static function _mapBuiltInColor($color) + { + switch ($color) { + case 0x00: return array('rgb' => '000000'); + case 0x01: return array('rgb' => 'FFFFFF'); + case 0x02: return array('rgb' => 'FF0000'); + case 0x03: return array('rgb' => '00FF00'); + case 0x04: return array('rgb' => '0000FF'); + case 0x05: return array('rgb' => 'FFFF00'); + case 0x06: return array('rgb' => 'FF00FF'); + case 0x07: return array('rgb' => '00FFFF'); + case 0x40: return array('rgb' => '000000'); // system window text color + case 0x41: return array('rgb' => 'FFFFFF'); // system window background color + default: return array('rgb' => '000000'); + } + } + + + /** + * Map color array from BIFF5 built-in color index + * + * @param int $subData + * @return array + */ + private static function _mapColorBIFF5($subData) + { + switch ($subData) { + case 0x08: return array('rgb' => '000000'); + case 0x09: return array('rgb' => 'FFFFFF'); + case 0x0A: return array('rgb' => 'FF0000'); + case 0x0B: return array('rgb' => '00FF00'); + case 0x0C: return array('rgb' => '0000FF'); + case 0x0D: return array('rgb' => 'FFFF00'); + case 0x0E: return array('rgb' => 'FF00FF'); + case 0x0F: return array('rgb' => '00FFFF'); + case 0x10: return array('rgb' => '800000'); + case 0x11: return array('rgb' => '008000'); + case 0x12: return array('rgb' => '000080'); + case 0x13: return array('rgb' => '808000'); + case 0x14: return array('rgb' => '800080'); + case 0x15: return array('rgb' => '008080'); + case 0x16: return array('rgb' => 'C0C0C0'); + case 0x17: return array('rgb' => '808080'); + case 0x18: return array('rgb' => '8080FF'); + case 0x19: return array('rgb' => '802060'); + case 0x1A: return array('rgb' => 'FFFFC0'); + case 0x1B: return array('rgb' => 'A0E0F0'); + case 0x1C: return array('rgb' => '600080'); + case 0x1D: return array('rgb' => 'FF8080'); + case 0x1E: return array('rgb' => '0080C0'); + case 0x1F: return array('rgb' => 'C0C0FF'); + case 0x20: return array('rgb' => '000080'); + case 0x21: return array('rgb' => 'FF00FF'); + case 0x22: return array('rgb' => 'FFFF00'); + case 0x23: return array('rgb' => '00FFFF'); + case 0x24: return array('rgb' => '800080'); + case 0x25: return array('rgb' => '800000'); + case 0x26: return array('rgb' => '008080'); + case 0x27: return array('rgb' => '0000FF'); + case 0x28: return array('rgb' => '00CFFF'); + case 0x29: return array('rgb' => '69FFFF'); + case 0x2A: return array('rgb' => 'E0FFE0'); + case 0x2B: return array('rgb' => 'FFFF80'); + case 0x2C: return array('rgb' => 'A6CAF0'); + case 0x2D: return array('rgb' => 'DD9CB3'); + case 0x2E: return array('rgb' => 'B38FEE'); + case 0x2F: return array('rgb' => 'E3E3E3'); + case 0x30: return array('rgb' => '2A6FF9'); + case 0x31: return array('rgb' => '3FB8CD'); + case 0x32: return array('rgb' => '488436'); + case 0x33: return array('rgb' => '958C41'); + case 0x34: return array('rgb' => '8E5E42'); + case 0x35: return array('rgb' => 'A0627A'); + case 0x36: return array('rgb' => '624FAC'); + case 0x37: return array('rgb' => '969696'); + case 0x38: return array('rgb' => '1D2FBE'); + case 0x39: return array('rgb' => '286676'); + case 0x3A: return array('rgb' => '004500'); + case 0x3B: return array('rgb' => '453E01'); + case 0x3C: return array('rgb' => '6A2813'); + case 0x3D: return array('rgb' => '85396A'); + case 0x3E: return array('rgb' => '4A3285'); + case 0x3F: return array('rgb' => '424242'); + default: return array('rgb' => '000000'); + } + } + + + /** + * Map color array from BIFF8 built-in color index + * + * @param int $subData + * @return array + */ + private static function _mapColor($subData) + { + switch ($subData) { + case 0x08: return array('rgb' => '000000'); + case 0x09: return array('rgb' => 'FFFFFF'); + case 0x0A: return array('rgb' => 'FF0000'); + case 0x0B: return array('rgb' => '00FF00'); + case 0x0C: return array('rgb' => '0000FF'); + case 0x0D: return array('rgb' => 'FFFF00'); + case 0x0E: return array('rgb' => 'FF00FF'); + case 0x0F: return array('rgb' => '00FFFF'); + case 0x10: return array('rgb' => '800000'); + case 0x11: return array('rgb' => '008000'); + case 0x12: return array('rgb' => '000080'); + case 0x13: return array('rgb' => '808000'); + case 0x14: return array('rgb' => '800080'); + case 0x15: return array('rgb' => '008080'); + case 0x16: return array('rgb' => 'C0C0C0'); + case 0x17: return array('rgb' => '808080'); + case 0x18: return array('rgb' => '9999FF'); + case 0x19: return array('rgb' => '993366'); + case 0x1A: return array('rgb' => 'FFFFCC'); + case 0x1B: return array('rgb' => 'CCFFFF'); + case 0x1C: return array('rgb' => '660066'); + case 0x1D: return array('rgb' => 'FF8080'); + case 0x1E: return array('rgb' => '0066CC'); + case 0x1F: return array('rgb' => 'CCCCFF'); + case 0x20: return array('rgb' => '000080'); + case 0x21: return array('rgb' => 'FF00FF'); + case 0x22: return array('rgb' => 'FFFF00'); + case 0x23: return array('rgb' => '00FFFF'); + case 0x24: return array('rgb' => '800080'); + case 0x25: return array('rgb' => '800000'); + case 0x26: return array('rgb' => '008080'); + case 0x27: return array('rgb' => '0000FF'); + case 0x28: return array('rgb' => '00CCFF'); + case 0x29: return array('rgb' => 'CCFFFF'); + case 0x2A: return array('rgb' => 'CCFFCC'); + case 0x2B: return array('rgb' => 'FFFF99'); + case 0x2C: return array('rgb' => '99CCFF'); + case 0x2D: return array('rgb' => 'FF99CC'); + case 0x2E: return array('rgb' => 'CC99FF'); + case 0x2F: return array('rgb' => 'FFCC99'); + case 0x30: return array('rgb' => '3366FF'); + case 0x31: return array('rgb' => '33CCCC'); + case 0x32: return array('rgb' => '99CC00'); + case 0x33: return array('rgb' => 'FFCC00'); + case 0x34: return array('rgb' => 'FF9900'); + case 0x35: return array('rgb' => 'FF6600'); + case 0x36: return array('rgb' => '666699'); + case 0x37: return array('rgb' => '969696'); + case 0x38: return array('rgb' => '003366'); + case 0x39: return array('rgb' => '339966'); + case 0x3A: return array('rgb' => '003300'); + case 0x3B: return array('rgb' => '333300'); + case 0x3C: return array('rgb' => '993300'); + case 0x3D: return array('rgb' => '993366'); + case 0x3E: return array('rgb' => '333399'); + case 0x3F: return array('rgb' => '333333'); + default: return array('rgb' => '000000'); + } + } + + + private function _parseRichText($is = '') { + $value = new PHPExcel_RichText(); + + $value->createText($is); + + return $value; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php new file mode 100644 index 00000000..3ed82c62 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php @@ -0,0 +1,640 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Reader_Excel5_Escher + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Excel5_Escher +{ + const DGGCONTAINER = 0xF000; + const BSTORECONTAINER = 0xF001; + const DGCONTAINER = 0xF002; + const SPGRCONTAINER = 0xF003; + const SPCONTAINER = 0xF004; + const DGG = 0xF006; + const BSE = 0xF007; + const DG = 0xF008; + const SPGR = 0xF009; + const SP = 0xF00A; + const OPT = 0xF00B; + const CLIENTTEXTBOX = 0xF00D; + const CLIENTANCHOR = 0xF010; + const CLIENTDATA = 0xF011; + const BLIPJPEG = 0xF01D; + const BLIPPNG = 0xF01E; + const SPLITMENUCOLORS = 0xF11E; + const TERTIARYOPT = 0xF122; + + /** + * Escher stream data (binary) + * + * @var string + */ + private $_data; + + /** + * Size in bytes of the Escher stream data + * + * @var int + */ + private $_dataSize; + + /** + * Current position of stream pointer in Escher stream data + * + * @var int + */ + private $_pos; + + /** + * The object to be returned by the reader. Modified during load. + * + * @var mixed + */ + private $_object; + + /** + * Create a new PHPExcel_Reader_Excel5_Escher instance + * + * @param mixed $object + */ + public function __construct($object) + { + $this->_object = $object; + } + + /** + * Load Escher stream data. May be a partial Escher stream. + * + * @param string $data + */ + public function load($data) + { + $this->_data = $data; + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->_dataSize = strlen($this->_data); + + $this->_pos = 0; + + // Parse Escher stream + while ($this->_pos < $this->_dataSize) { + + // offset: 2; size: 2: Record Type + $fbt = PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos + 2); + + switch ($fbt) { + case self::DGGCONTAINER: $this->_readDggContainer(); break; + case self::DGG: $this->_readDgg(); break; + case self::BSTORECONTAINER: $this->_readBstoreContainer(); break; + case self::BSE: $this->_readBSE(); break; + case self::BLIPJPEG: $this->_readBlipJPEG(); break; + case self::BLIPPNG: $this->_readBlipPNG(); break; + case self::OPT: $this->_readOPT(); break; + case self::TERTIARYOPT: $this->_readTertiaryOPT(); break; + case self::SPLITMENUCOLORS: $this->_readSplitMenuColors(); break; + case self::DGCONTAINER: $this->_readDgContainer(); break; + case self::DG: $this->_readDg(); break; + case self::SPGRCONTAINER: $this->_readSpgrContainer(); break; + case self::SPCONTAINER: $this->_readSpContainer(); break; + case self::SPGR: $this->_readSpgr(); break; + case self::SP: $this->_readSp(); break; + case self::CLIENTTEXTBOX: $this->_readClientTextbox(); break; + case self::CLIENTANCHOR: $this->_readClientAnchor(); break; + case self::CLIENTDATA: $this->_readClientData(); break; + default: $this->_readDefault(); break; + } + } + + return $this->_object; + } + + /** + * Read a generic record + */ + private function _readDefault() + { + // offset 0; size: 2; recVer and recInstance + $verInstance = PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos); + + // offset: 2; size: 2: Record Type + $fbt = PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos + 2); + + // bit: 0-3; mask: 0x000F; recVer + $recVer = (0x000F & $verInstance) >> 0; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read DggContainer record (Drawing Group Container) + */ + private function _readDggContainer() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // record is a container, read contents + $dggContainer = new PHPExcel_Shared_Escher_DggContainer(); + $this->_object->setDggContainer($dggContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($dggContainer); + $reader->load($recordData); + } + + /** + * Read Dgg record (Drawing Group) + */ + private function _readDgg() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read BstoreContainer record (Blip Store Container) + */ + private function _readBstoreContainer() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // record is a container, read contents + $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer(); + $this->_object->setBstoreContainer($bstoreContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($bstoreContainer); + $reader->load($recordData); + } + + /** + * Read BSE record + */ + private function _readBSE() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // add BSE to BstoreContainer + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $this->_object->addBSE($BSE); + + $BSE->setBLIPType($recInstance); + + // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) + $btWin32 = ord($recordData[0]); + + // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) + $btMacOS = ord($recordData[1]); + + // offset: 2; size: 16; MD4 digest + $rgbUid = substr($recordData, 2, 16); + + // offset: 18; size: 2; tag + $tag = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 18); + + // offset: 20; size: 4; size of BLIP in bytes + $size = PHPExcel_Reader_Excel5::_GetInt4d($recordData, 20); + + // offset: 24; size: 4; number of references to this BLIP + $cRef = PHPExcel_Reader_Excel5::_GetInt4d($recordData, 24); + + // offset: 28; size: 4; MSOFO file offset + $foDelay = PHPExcel_Reader_Excel5::_GetInt4d($recordData, 28); + + // offset: 32; size: 1; unused1 + $unused1 = ord($recordData{32}); + + // offset: 33; size: 1; size of nameData in bytes (including null terminator) + $cbName = ord($recordData{33}); + + // offset: 34; size: 1; unused2 + $unused2 = ord($recordData{34}); + + // offset: 35; size: 1; unused3 + $unused3 = ord($recordData{35}); + + // offset: 36; size: $cbName; nameData + $nameData = substr($recordData, 36, $cbName); + + // offset: 36 + $cbName, size: var; the BLIP data + $blipData = substr($recordData, 36 + $cbName); + + // record is a container, read contents + $reader = new PHPExcel_Reader_Excel5_Escher($BSE); + $reader->load($blipData); + } + + /** + * Read BlipJPEG record. Holds raw JPEG image data + */ + private function _readBlipJPEG() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + $pos = 0; + + // offset: 0; size: 16; rgbUid1 (MD4 digest of) + $rgbUid1 = substr($recordData, 0, 16); + $pos += 16; + + // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 + if (in_array($recInstance, array(0x046B, 0x06E3))) { + $rgbUid2 = substr($recordData, 16, 16); + $pos += 16; + } + + // offset: var; size: 1; tag + $tag = ord($recordData{$pos}); + $pos += 1; + + // offset: var; size: var; the raw image data + $data = substr($recordData, $pos); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($data); + + $this->_object->setBlip($blip); + } + + /** + * Read BlipPNG record. Holds raw PNG image data + */ + private function _readBlipPNG() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + $pos = 0; + + // offset: 0; size: 16; rgbUid1 (MD4 digest of) + $rgbUid1 = substr($recordData, 0, 16); + $pos += 16; + + // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 + if ($recInstance == 0x06E1) { + $rgbUid2 = substr($recordData, 16, 16); + $pos += 16; + } + + // offset: var; size: 1; tag + $tag = ord($recordData{$pos}); + $pos += 1; + + // offset: var; size: var; the raw image data + $data = substr($recordData, $pos); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($data); + + $this->_object->setBlip($blip); + } + + /** + * Read OPT record. This record may occur within DggContainer record or SpContainer + */ + private function _readOPT() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + $this->_readOfficeArtRGFOPTE($recordData, $recInstance); + } + + /** + * Read TertiaryOPT record + */ + private function _readTertiaryOPT() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read SplitMenuColors record + */ + private function _readSplitMenuColors() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read DgContainer record (Drawing Container) + */ + private function _readDgContainer() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // record is a container, read contents + $dgContainer = new PHPExcel_Shared_Escher_DgContainer(); + $this->_object->setDgContainer($dgContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($dgContainer); + $escher = $reader->load($recordData); + } + + /** + * Read Dg record (Drawing) + */ + private function _readDg() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read SpgrContainer record (Shape Group Container) + */ + private function _readSpgrContainer() + { + // context is either context DgContainer or SpgrContainer + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // record is a container, read contents + $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer(); + + if ($this->_object instanceof PHPExcel_Shared_Escher_DgContainer) { + // DgContainer + $this->_object->setSpgrContainer($spgrContainer); + } else { + // SpgrContainer + $this->_object->addChild($spgrContainer); + } + + $reader = new PHPExcel_Reader_Excel5_Escher($spgrContainer); + $escher = $reader->load($recordData); + } + + /** + * Read SpContainer record (Shape Container) + */ + private function _readSpContainer() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // add spContainer to spgrContainer + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + $this->_object->addChild($spContainer); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // record is a container, read contents + $reader = new PHPExcel_Reader_Excel5_Escher($spContainer); + $escher = $reader->load($recordData); + } + + /** + * Read Spgr record (Shape Group) + */ + private function _readSpgr() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read Sp record (Shape) + */ + private function _readSp() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read ClientTextbox record + */ + private function _readClientTextbox() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::_GetInt2d($this->_data, $this->_pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet + */ + private function _readClientAnchor() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + + // offset: 2; size: 2; upper-left corner column index (0-based) + $c1 = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 2); + + // offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width + $startOffsetX = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 4); + + // offset: 6; size: 2; upper-left corner row index (0-based) + $r1 = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 6); + + // offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height + $startOffsetY = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 8); + + // offset: 10; size: 2; bottom-right corner column index (0-based) + $c2 = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 10); + + // offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width + $endOffsetX = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 12); + + // offset: 14; size: 2; bottom-right corner row index (0-based) + $r2 = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 14); + + // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height + $endOffsetY = PHPExcel_Reader_Excel5::_GetInt2d($recordData, 16); + + // set the start coordinates + $this->_object->setStartCoordinates(PHPExcel_Cell::stringFromColumnIndex($c1) . ($r1 + 1)); + + // set the start offsetX + $this->_object->setStartOffsetX($startOffsetX); + + // set the start offsetY + $this->_object->setStartOffsetY($startOffsetY); + + // set the end coordinates + $this->_object->setEndCoordinates(PHPExcel_Cell::stringFromColumnIndex($c2) . ($r2 + 1)); + + // set the end offsetX + $this->_object->setEndOffsetX($endOffsetX); + + // set the end offsetY + $this->_object->setEndOffsetY($endOffsetY); + } + + /** + * Read ClientData record + */ + private function _readClientData() + { + $length = PHPExcel_Reader_Excel5::_GetInt4d($this->_data, $this->_pos + 4); + $recordData = substr($this->_data, $this->_pos + 8, $length); + + // move stream pointer to next record + $this->_pos += 8 + $length; + } + + /** + * Read OfficeArtRGFOPTE table of property-value pairs + * + * @param string $data Binary data + * @param int $n Number of properties + */ + private function _readOfficeArtRGFOPTE($data, $n) { + + $splicedComplexData = substr($data, 6 * $n); + + // loop through property-value pairs + for ($i = 0; $i < $n; ++$i) { + // read 6 bytes at a time + $fopte = substr($data, 6 * $i, 6); + + // offset: 0; size: 2; opid + $opid = PHPExcel_Reader_Excel5::_GetInt2d($fopte, 0); + + // bit: 0-13; mask: 0x3FFF; opid.opid + $opidOpid = (0x3FFF & $opid) >> 0; + + // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier + $opidFBid = (0x4000 & $opid) >> 14; + + // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data + $opidFComplex = (0x8000 & $opid) >> 15; + + // offset: 2; size: 4; the value for this property + $op = PHPExcel_Reader_Excel5::_GetInt4d($fopte, 2); + + if ($opidFComplex) { + $complexData = substr($splicedComplexData, 0, $op); + $splicedComplexData = substr($splicedComplexData, $op); + + // we store string value with complex data + $value = $complexData; + } else { + // we store integer value + $value = $op; + } + + $this->_object->setOPT($opidOpid, $value); + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php new file mode 100644 index 00000000..946d5a0d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php @@ -0,0 +1,221 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Reader_Excel5_MD5 + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Excel5_MD5 +{ + // Context + private $a; + private $b; + private $c; + private $d; + + + /** + * MD5 stream constructor + */ + public function __construct() + { + $this->reset(); + } + + + /** + * Reset the MD5 stream context + */ + public function reset() + { + $this->a = 0x67452301; + $this->b = 0xEFCDAB89; + $this->c = 0x98BADCFE; + $this->d = 0x10325476; + } + + + /** + * Get MD5 stream context + * + * @return string + */ + public function getContext() + { + $s = ''; + foreach (array('a', 'b', 'c', 'd') as $i) { + $v = $this->{$i}; + $s .= chr($v & 0xff); + $s .= chr(($v >> 8) & 0xff); + $s .= chr(($v >> 16) & 0xff); + $s .= chr(($v >> 24) & 0xff); + } + + return $s; + } + + + /** + * Add data to context + * + * @param string $data Data to add + */ + public function add($data) + { + $words = array_values(unpack('V16', $data)); + + $A = $this->a; + $B = $this->b; + $C = $this->c; + $D = $this->d; + + $F = array('PHPExcel_Reader_Excel5_MD5','F'); + $G = array('PHPExcel_Reader_Excel5_MD5','G'); + $H = array('PHPExcel_Reader_Excel5_MD5','H'); + $I = array('PHPExcel_Reader_Excel5_MD5','I'); + + /* ROUND 1 */ + self::step($F, $A, $B, $C, $D, $words[0], 7, 0xd76aa478); + self::step($F, $D, $A, $B, $C, $words[1], 12, 0xe8c7b756); + self::step($F, $C, $D, $A, $B, $words[2], 17, 0x242070db); + self::step($F, $B, $C, $D, $A, $words[3], 22, 0xc1bdceee); + self::step($F, $A, $B, $C, $D, $words[4], 7, 0xf57c0faf); + self::step($F, $D, $A, $B, $C, $words[5], 12, 0x4787c62a); + self::step($F, $C, $D, $A, $B, $words[6], 17, 0xa8304613); + self::step($F, $B, $C, $D, $A, $words[7], 22, 0xfd469501); + self::step($F, $A, $B, $C, $D, $words[8], 7, 0x698098d8); + self::step($F, $D, $A, $B, $C, $words[9], 12, 0x8b44f7af); + self::step($F, $C, $D, $A, $B, $words[10], 17, 0xffff5bb1); + self::step($F, $B, $C, $D, $A, $words[11], 22, 0x895cd7be); + self::step($F, $A, $B, $C, $D, $words[12], 7, 0x6b901122); + self::step($F, $D, $A, $B, $C, $words[13], 12, 0xfd987193); + self::step($F, $C, $D, $A, $B, $words[14], 17, 0xa679438e); + self::step($F, $B, $C, $D, $A, $words[15], 22, 0x49b40821); + + /* ROUND 2 */ + self::step($G, $A, $B, $C, $D, $words[1], 5, 0xf61e2562); + self::step($G, $D, $A, $B, $C, $words[6], 9, 0xc040b340); + self::step($G, $C, $D, $A, $B, $words[11], 14, 0x265e5a51); + self::step($G, $B, $C, $D, $A, $words[0], 20, 0xe9b6c7aa); + self::step($G, $A, $B, $C, $D, $words[5], 5, 0xd62f105d); + self::step($G, $D, $A, $B, $C, $words[10], 9, 0x02441453); + self::step($G, $C, $D, $A, $B, $words[15], 14, 0xd8a1e681); + self::step($G, $B, $C, $D, $A, $words[4], 20, 0xe7d3fbc8); + self::step($G, $A, $B, $C, $D, $words[9], 5, 0x21e1cde6); + self::step($G, $D, $A, $B, $C, $words[14], 9, 0xc33707d6); + self::step($G, $C, $D, $A, $B, $words[3], 14, 0xf4d50d87); + self::step($G, $B, $C, $D, $A, $words[8], 20, 0x455a14ed); + self::step($G, $A, $B, $C, $D, $words[13], 5, 0xa9e3e905); + self::step($G, $D, $A, $B, $C, $words[2], 9, 0xfcefa3f8); + self::step($G, $C, $D, $A, $B, $words[7], 14, 0x676f02d9); + self::step($G, $B, $C, $D, $A, $words[12], 20, 0x8d2a4c8a); + + /* ROUND 3 */ + self::step($H, $A, $B, $C, $D, $words[5], 4, 0xfffa3942); + self::step($H, $D, $A, $B, $C, $words[8], 11, 0x8771f681); + self::step($H, $C, $D, $A, $B, $words[11], 16, 0x6d9d6122); + self::step($H, $B, $C, $D, $A, $words[14], 23, 0xfde5380c); + self::step($H, $A, $B, $C, $D, $words[1], 4, 0xa4beea44); + self::step($H, $D, $A, $B, $C, $words[4], 11, 0x4bdecfa9); + self::step($H, $C, $D, $A, $B, $words[7], 16, 0xf6bb4b60); + self::step($H, $B, $C, $D, $A, $words[10], 23, 0xbebfbc70); + self::step($H, $A, $B, $C, $D, $words[13], 4, 0x289b7ec6); + self::step($H, $D, $A, $B, $C, $words[0], 11, 0xeaa127fa); + self::step($H, $C, $D, $A, $B, $words[3], 16, 0xd4ef3085); + self::step($H, $B, $C, $D, $A, $words[6], 23, 0x04881d05); + self::step($H, $A, $B, $C, $D, $words[9], 4, 0xd9d4d039); + self::step($H, $D, $A, $B, $C, $words[12], 11, 0xe6db99e5); + self::step($H, $C, $D, $A, $B, $words[15], 16, 0x1fa27cf8); + self::step($H, $B, $C, $D, $A, $words[2], 23, 0xc4ac5665); + + /* ROUND 4 */ + self::step($I, $A, $B, $C, $D, $words[0], 6, 0xf4292244); + self::step($I, $D, $A, $B, $C, $words[7], 10, 0x432aff97); + self::step($I, $C, $D, $A, $B, $words[14], 15, 0xab9423a7); + self::step($I, $B, $C, $D, $A, $words[5], 21, 0xfc93a039); + self::step($I, $A, $B, $C, $D, $words[12], 6, 0x655b59c3); + self::step($I, $D, $A, $B, $C, $words[3], 10, 0x8f0ccc92); + self::step($I, $C, $D, $A, $B, $words[10], 15, 0xffeff47d); + self::step($I, $B, $C, $D, $A, $words[1], 21, 0x85845dd1); + self::step($I, $A, $B, $C, $D, $words[8], 6, 0x6fa87e4f); + self::step($I, $D, $A, $B, $C, $words[15], 10, 0xfe2ce6e0); + self::step($I, $C, $D, $A, $B, $words[6], 15, 0xa3014314); + self::step($I, $B, $C, $D, $A, $words[13], 21, 0x4e0811a1); + self::step($I, $A, $B, $C, $D, $words[4], 6, 0xf7537e82); + self::step($I, $D, $A, $B, $C, $words[11], 10, 0xbd3af235); + self::step($I, $C, $D, $A, $B, $words[2], 15, 0x2ad7d2bb); + self::step($I, $B, $C, $D, $A, $words[9], 21, 0xeb86d391); + + $this->a = ($this->a + $A) & 0xffffffff; + $this->b = ($this->b + $B) & 0xffffffff; + $this->c = ($this->c + $C) & 0xffffffff; + $this->d = ($this->d + $D) & 0xffffffff; + } + + + private static function F($X, $Y, $Z) + { + return (($X & $Y) | ((~ $X) & $Z)); // X AND Y OR NOT X AND Z + } + + + private static function G($X, $Y, $Z) + { + return (($X & $Z) | ($Y & (~ $Z))); // X AND Z OR Y AND NOT Z + } + + + private static function H($X, $Y, $Z) + { + return ($X ^ $Y ^ $Z); // X XOR Y XOR Z + } + + + private static function I($X, $Y, $Z) + { + return ($Y ^ ($X | (~ $Z))) ; // Y XOR (X OR NOT Z) + } + + + private static function step($func, &$A, $B, $C, $D, $M, $s, $t) + { + $A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff; + $A = self::rotate($A, $s); + $A = ($B + $A) & 0xffffffff; + } + + + private static function rotate($decimal, $bits) + { + $binary = str_pad(decbin($decimal), 32, "0", STR_PAD_LEFT); + return bindec(substr($binary, $bits).substr($binary, 0, $bits)); + } +} \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php new file mode 100644 index 00000000..dc6327c0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php @@ -0,0 +1,88 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Reader_Excel5_RC4 + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Excel5_RC4 +{ + // Context + var $s = array(); + var $i = 0; + var $j = 0; + + /** + * RC4 stream decryption/encryption constrcutor + * + * @param string $key Encryption key/passphrase + */ + public function __construct($key) + { + $len = strlen($key); + + for ($this->i = 0; $this->i < 256; $this->i++) { + $this->s[$this->i] = $this->i; + } + + $this->j = 0; + for ($this->i = 0; $this->i < 256; $this->i++) { + $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256; + $t = $this->s[$this->i]; + $this->s[$this->i] = $this->s[$this->j]; + $this->s[$this->j] = $t; + } + $this->i = $this->j = 0; + } + + /** + * Symmetric decryption/encryption function + * + * @param string $data Data to encrypt/decrypt + * + * @return string + */ + public function RC4($data) + { + $len = strlen($data); + for ($c = 0; $c < $len; $c++) { + $this->i = ($this->i + 1) % 256; + $this->j = ($this->j + $this->s[$this->i]) % 256; + $t = $this->s[$this->i]; + $this->s[$this->i] = $this->s[$this->j]; + $this->s[$this->j] = $t; + + $t = ($this->s[$this->i] + $this->s[$this->j]) % 256; + + $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); + } + return $data; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php new file mode 100644 index 00000000..f42a1aaf --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php @@ -0,0 +1,52 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Reader_Exception + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Exception extends PHPExcel_Exception { + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php new file mode 100644 index 00000000..6db7c496 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php @@ -0,0 +1,873 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_Gnumeric + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Gnumeric extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Formats + * + * @var array + */ + private $_styles = array(); + + /** + * Shared Expressions + * + * @var array + */ + private $_expressions = array(); + + private $_referenceHelper = null; + + + /** + * Create a new PHPExcel_Reader_Gnumeric + */ + public function __construct() { + $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + $this->_referenceHelper = PHPExcel_ReferenceHelper::getInstance(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Check if gzlib functions are available + if (!function_exists('gzread')) { + throw new PHPExcel_Reader_Exception("gzlib library is not enabled"); + } + + // Read signature data (first 3 bytes) + $fh = fopen($pFilename, 'r'); + $data = fread($fh, 2); + fclose($fh); + + if ($data != chr(0x1F).chr(0x8B)) { + return false; + } + + return true; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $xml = new XMLReader(); + $xml->open( + 'compress.zlib://'.realpath($pFilename), null, PHPExcel_Settings::getLibXmlLoaderOptions() + ); + $xml->setParserProperty(2,true); + + $worksheetNames = array(); + while ($xml->read()) { + if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $worksheetNames[] = (string) $xml->value; + } elseif ($xml->name == 'gnm:Sheets') { + // break out of the loop once we've got our sheet names rather than parse the entire file + break; + } + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $xml = new XMLReader(); + $xml->open( + 'compress.zlib://'.realpath($pFilename), null, PHPExcel_Settings::getLibXmlLoaderOptions() + ); + $xml->setParserProperty(2,true); + + $worksheetInfo = array(); + while ($xml->read()) { + if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) { + $tmpInfo = array( + 'worksheetName' => '', + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + while ($xml->read()) { + if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['worksheetName'] = (string) $xml->value; + } elseif ($xml->name == 'gnm:MaxCol' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['lastColumnIndex'] = (int) $xml->value; + $tmpInfo['totalColumns'] = (int) $xml->value + 1; + } elseif ($xml->name == 'gnm:MaxRow' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['totalRows'] = (int) $xml->value + 1; + break; + } + } + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $worksheetInfo[] = $tmpInfo; + } + } + + return $worksheetInfo; + } + + + private function _gzfileGetContents($filename) { + $file = @gzopen($filename, 'rb'); + if ($file !== false) { + $data = ''; + while (!gzeof($file)) { + $data .= gzread($file, 1024); + } + gzclose($file); + } + return $data; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + $gFileData = $this->_gzfileGetContents($pFilename); + +// echo '<pre>'; +// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); +// echo '</pre><hr />'; +// + $xml = simplexml_load_string($gFileData, 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesMeta = $xml->getNamespaces(true); + +// var_dump($namespacesMeta); +// + $gnmXML = $xml->children($namespacesMeta['gnm']); + + $docProps = $objPHPExcel->getProperties(); + // Document Properties are held differently, depending on the version of Gnumeric + if (isset($namespacesMeta['office'])) { + $officeXML = $xml->children($namespacesMeta['office']); + $officeDocXML = $officeXML->{'document-meta'}; + $officeDocMetaXML = $officeDocXML->meta; + + foreach($officeDocMetaXML as $officePropertyData) { + + $officePropertyDC = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); + } + foreach($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'title' : + $docProps->setTitle(trim($propertyValue)); + break; + case 'subject' : + $docProps->setSubject(trim($propertyValue)); + break; + case 'creator' : + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'date' : + $creationDate = strtotime(trim($propertyValue)); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'description' : + $docProps->setDescription(trim($propertyValue)); + break; + } + } + $officePropertyMeta = array(); + if (isset($namespacesMeta['meta'])) { + $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); + } + foreach($officePropertyMeta as $propertyName => $propertyValue) { + $attributes = $propertyValue->attributes($namespacesMeta['meta']); + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'keyword' : + $docProps->setKeywords(trim($propertyValue)); + break; + case 'initial-creator' : + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'creation-date' : + $creationDate = strtotime(trim($propertyValue)); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'user-defined' : + list(,$attrName) = explode(':',$attributes['name']); + switch ($attrName) { + case 'publisher' : + $docProps->setCompany(trim($propertyValue)); + break; + case 'category' : + $docProps->setCategory(trim($propertyValue)); + break; + case 'manager' : + $docProps->setManager(trim($propertyValue)); + break; + } + break; + } + } + } + } elseif (isset($gnmXML->Summary)) { + foreach($gnmXML->Summary->Item as $summaryItem) { + $propertyName = $summaryItem->name; + $propertyValue = $summaryItem->{'val-string'}; + switch ($propertyName) { + case 'title' : + $docProps->setTitle(trim($propertyValue)); + break; + case 'comments' : + $docProps->setDescription(trim($propertyValue)); + break; + case 'keywords' : + $docProps->setKeywords(trim($propertyValue)); + break; + case 'category' : + $docProps->setCategory(trim($propertyValue)); + break; + case 'manager' : + $docProps->setManager(trim($propertyValue)); + break; + case 'author' : + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'company' : + $docProps->setCompany(trim($propertyValue)); + break; + } + } + } + + $worksheetID = 0; + foreach($gnmXML->Sheets->Sheet as $sheet) { + $worksheetName = (string) $sheet->Name; +// echo '<b>Worksheet: ',$worksheetName,'</b><br />'; + if ((isset($this->_loadSheetsOnly)) && (!in_array($worksheetName, $this->_loadSheetsOnly))) { + continue; + } + + $maxRow = $maxCol = 0; + + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula + // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet + // name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName,false); + + if ((!$this->_readDataOnly) && (isset($sheet->PrintInformation))) { + if (isset($sheet->PrintInformation->Margins)) { + foreach($sheet->PrintInformation->Margins->children('gnm',TRUE) as $key => $margin) { + $marginAttributes = $margin->attributes(); + $marginSize = 72 / 100; // Default + switch($marginAttributes['PrefUnit']) { + case 'mm' : + $marginSize = intval($marginAttributes['Points']) / 100; + break; + } + switch($key) { + case 'top' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setTop($marginSize); + break; + case 'bottom' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom($marginSize); + break; + case 'left' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft($marginSize); + break; + case 'right' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setRight($marginSize); + break; + case 'header' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setHeader($marginSize); + break; + case 'footer' : + $objPHPExcel->getActiveSheet()->getPageMargins()->setFooter($marginSize); + break; + } + } + } + } + + foreach($sheet->Cells->Cell as $cell) { + $cellAttributes = $cell->attributes(); + $row = (int) $cellAttributes->Row + 1; + $column = (int) $cellAttributes->Col; + + if ($row > $maxRow) $maxRow = $row; + if ($column > $maxCol) $maxCol = $column; + + $column = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if ($this->getReadFilter() !== NULL) { + if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) { + continue; + } + } + + $ValueType = $cellAttributes->ValueType; + $ExprID = (string) $cellAttributes->ExprID; +// echo 'Cell ',$column,$row,'<br />'; +// echo 'Type is ',$ValueType,'<br />'; +// echo 'Value is ',$cell,'<br />'; + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + if ($ExprID > '') { + if (((string) $cell) > '') { + + $this->_expressions[$ExprID] = array( 'column' => $cellAttributes->Col, + 'row' => $cellAttributes->Row, + 'formula' => (string) $cell + ); +// echo 'NEW EXPRESSION ',$ExprID,'<br />'; + } else { + $expression = $this->_expressions[$ExprID]; + + $cell = $this->_referenceHelper->updateFormulaReferences( $expression['formula'], + 'A1', + $cellAttributes->Col - $expression['column'], + $cellAttributes->Row - $expression['row'], + $worksheetName + ); +// echo 'SHARED EXPRESSION ',$ExprID,'<br />'; +// echo 'New Value is ',$cell,'<br />'; + } + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + } else { + switch($ValueType) { + case '10' : // NULL + $type = PHPExcel_Cell_DataType::TYPE_NULL; + break; + case '20' : // Boolean + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $cell = ($cell == 'TRUE') ? True : False; + break; + case '30' : // Integer + $cell = intval($cell); + case '40' : // Float + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + break; + case '50' : // Error + $type = PHPExcel_Cell_DataType::TYPE_ERROR; + break; + case '60' : // String + $type = PHPExcel_Cell_DataType::TYPE_STRING; + break; + case '70' : // Cell Range + case '80' : // Array + } + } + $objPHPExcel->getActiveSheet()->getCell($column.$row)->setValueExplicit($cell,$type); + } + + if ((!$this->_readDataOnly) && (isset($sheet->Objects))) { + foreach($sheet->Objects->children('gnm',TRUE) as $key => $comment) { + $commentAttributes = $comment->attributes(); + // Only comment objects are handled at the moment + if ($commentAttributes->Text) { + $objPHPExcel->getActiveSheet()->getComment( (string)$commentAttributes->ObjectBound ) + ->setAuthor( (string)$commentAttributes->Author ) + ->setText($this->_parseRichText((string)$commentAttributes->Text) ); + } + } + } +// echo '$maxCol=',$maxCol,'; $maxRow=',$maxRow,'<br />'; +// + foreach($sheet->Styles->StyleRegion as $styleRegion) { + $styleAttributes = $styleRegion->attributes(); + if (($styleAttributes['startRow'] <= $maxRow) && + ($styleAttributes['startCol'] <= $maxCol)) { + + $startColumn = PHPExcel_Cell::stringFromColumnIndex((int) $styleAttributes['startCol']); + $startRow = $styleAttributes['startRow'] + 1; + + $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; + $endColumn = PHPExcel_Cell::stringFromColumnIndex($endColumn); + $endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow']; + $endRow += 1; + $cellRange = $startColumn.$startRow.':'.$endColumn.$endRow; +// echo $cellRange,'<br />'; + + $styleAttributes = $styleRegion->Style->attributes(); +// var_dump($styleAttributes); +// echo '<br />'; + + // We still set the number format mask for date/time values, even if _readDataOnly is true + if ((!$this->_readDataOnly) || + (PHPExcel_Shared_Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) { + $styleArray = array(); + $styleArray['numberformat']['code'] = (string) $styleAttributes['Format']; + // If _readDataOnly is false, we set all formatting information + if (!$this->_readDataOnly) { + switch($styleAttributes['HAlign']) { + case '1' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + break; + case '2' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_LEFT; + break; + case '4' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT; + break; + case '8' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; + break; + case '16' : + case '64' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS; + break; + case '32' : + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY; + break; + } + + switch($styleAttributes['VAlign']) { + case '1' : + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_TOP; + break; + case '2' : + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + break; + case '4' : + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_CENTER; + break; + case '8' : + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY; + break; + } + + $styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '1') ? True : False; + $styleArray['alignment']['shrinkToFit'] = ($styleAttributes['ShrinkToFit'] == '1') ? True : False; + $styleArray['alignment']['indent'] = (intval($styleAttributes["Indent"]) > 0) ? $styleAttributes["indent"] : 0; + + $RGB = self::_parseGnumericColour($styleAttributes["Fore"]); + $styleArray['font']['color']['rgb'] = $RGB; + $RGB = self::_parseGnumericColour($styleAttributes["Back"]); + $shade = $styleAttributes["Shade"]; + if (($RGB != '000000') || ($shade != '0')) { + $styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB; + $RGB2 = self::_parseGnumericColour($styleAttributes["PatternColor"]); + $styleArray['fill']['endcolor']['rgb'] = $RGB2; + switch($shade) { + case '1' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_SOLID; + break; + case '2' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR; + break; + case '3' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_PATH; + break; + case '4' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN; + break; + case '5' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY; + break; + case '6' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID; + break; + case '7' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL; + break; + case '8' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS; + break; + case '9' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKUP; + break; + case '10' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL; + break; + case '11' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625; + break; + case '12' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY125; + break; + case '13' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN; + break; + case '14' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY; + break; + case '15' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID; + break; + case '16' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL; + break; + case '17' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS; + break; + case '18' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP; + break; + case '19' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL; + break; + case '20' : + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY; + break; + } + } + + $fontAttributes = $styleRegion->Style->Font->attributes(); +// var_dump($fontAttributes); +// echo '<br />'; + $styleArray['font']['name'] = (string) $styleRegion->Style->Font; + $styleArray['font']['size'] = intval($fontAttributes['Unit']); + $styleArray['font']['bold'] = ($fontAttributes['Bold'] == '1') ? True : False; + $styleArray['font']['italic'] = ($fontAttributes['Italic'] == '1') ? True : False; + $styleArray['font']['strike'] = ($fontAttributes['StrikeThrough'] == '1') ? True : False; + switch($fontAttributes['Underline']) { + case '1' : + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLE; + break; + case '2' : + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLE; + break; + case '3' : + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING; + break; + case '4' : + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING; + break; + default : + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_NONE; + break; + } + switch($fontAttributes['Script']) { + case '1' : + $styleArray['font']['superScript'] = True; + break; + case '-1' : + $styleArray['font']['subScript'] = True; + break; + } + + if (isset($styleRegion->Style->StyleBorder)) { + if (isset($styleRegion->Style->StyleBorder->Top)) { + $styleArray['borders']['top'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Top->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Bottom)) { + $styleArray['borders']['bottom'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Bottom->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Left)) { + $styleArray['borders']['left'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Left->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Right)) { + $styleArray['borders']['right'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Right->attributes()); + } + if ((isset($styleRegion->Style->StyleBorder->Diagonal)) && (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}))) { + $styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_BOTH; + } elseif (isset($styleRegion->Style->StyleBorder->Diagonal)) { + $styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_UP; + } elseif (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::_parseBorderAttributes($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_DOWN; + } + } + if (isset($styleRegion->Style->HyperLink)) { + // TO DO + $hyperlink = $styleRegion->Style->HyperLink->attributes(); + } + } +// var_dump($styleArray); +// echo '<br />'; + $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); + } + } + } + + if ((!$this->_readDataOnly) && (isset($sheet->Cols))) { + // Column Widths + $columnAttributes = $sheet->Cols->attributes(); + $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; + $c = 0; + foreach($sheet->Cols->ColInfo as $columnOverride) { + $columnAttributes = $columnOverride->attributes(); + $column = $columnAttributes['No']; + $columnWidth = $columnAttributes['Unit'] / 5.4; + $hidden = ((isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false; + $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; + while ($c < $column) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); + ++$c; + } + while (($c < ($column+$columnCount)) && ($c <= $maxCol)) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($columnWidth); + if ($hidden) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setVisible(false); + } + ++$c; + } + } + while ($c <= $maxCol) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); + ++$c; + } + } + + if ((!$this->_readDataOnly) && (isset($sheet->Rows))) { + // Row Heights + $rowAttributes = $sheet->Rows->attributes(); + $defaultHeight = $rowAttributes['DefaultSizePts']; + $r = 0; + + foreach($sheet->Rows->RowInfo as $rowOverride) { + $rowAttributes = $rowOverride->attributes(); + $row = $rowAttributes['No']; + $rowHeight = $rowAttributes['Unit']; + $hidden = ((isset($rowAttributes['Hidden'])) && ($rowAttributes['Hidden'] == '1')) ? true : false; + $rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1; + while ($r < $row) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + } + while (($r < ($row+$rowCount)) && ($r < $maxRow)) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); + if ($hidden) { + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setVisible(false); + } + } + } + while ($r < $maxRow) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + } + } + + // Handle Merged Cells in this worksheet + if (isset($sheet->MergedRegions)) { + foreach($sheet->MergedRegions->Merge as $mergeCells) { + if (strpos($mergeCells,':') !== FALSE) { + $objPHPExcel->getActiveSheet()->mergeCells($mergeCells); + } + } + } + + $worksheetID++; + } + + // Loop through definedNames (global named ranges) + if (isset($gnmXML->Names)) { + foreach($gnmXML->Names->Name as $namedRange) { + $name = (string) $namedRange->name; + $range = (string) $namedRange->value; + if (stripos($range, '#REF!') !== false) { + continue; + } + + $range = explode('!',$range); + $range[0] = trim($range[0],"'");; + if ($worksheet = $objPHPExcel->getSheetByName($range[0])) { + $extractedRange = str_replace('$', '', $range[1]); + $objPHPExcel->addNamedRange( new PHPExcel_NamedRange($name, $worksheet, $extractedRange) ); + } + } + } + + + // Return + return $objPHPExcel; + } + + + private static function _parseBorderAttributes($borderAttributes) + { + $styleArray = array(); + + if (isset($borderAttributes["Color"])) { + $RGB = self::_parseGnumericColour($borderAttributes["Color"]); + $styleArray['color']['rgb'] = $RGB; + } + + switch ($borderAttributes["Style"]) { + case '0' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_NONE; + break; + case '1' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case '2' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUM; + break; + case '4' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHED; + break; + case '5' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_THICK; + break; + case '6' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DOUBLE; + break; + case '7' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DOTTED; + break; + case '9' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHDOT; + break; + case '10' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT; + break; + case '11' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHDOTDOT; + break; + case '12' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT; + break; + case '13' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT; + break; + case '3' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_SLANTDASHDOT; + break; + case '8' : + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHED; + break; + } + return $styleArray; + } + + + private function _parseRichText($is = '') { + $value = new PHPExcel_RichText(); + + $value->createText($is); + + return $value; + } + + + private static function _parseGnumericColour($gnmColour) { + list($gnmR,$gnmG,$gnmB) = explode(':',$gnmColour); + $gnmR = substr(str_pad($gnmR,4,'0',STR_PAD_RIGHT),0,2); + $gnmG = substr(str_pad($gnmG,4,'0',STR_PAD_RIGHT),0,2); + $gnmB = substr(str_pad($gnmB,4,'0',STR_PAD_RIGHT),0,2); + $RGB = $gnmR.$gnmG.$gnmB; +// echo 'Excel Colour: ',$RGB,'<br />'; + return $RGB; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php new file mode 100644 index 00000000..16964710 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php @@ -0,0 +1,468 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_HTML + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_HTML extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Input encoding + * + * @var string + */ + private $_inputEncoding = 'ANSI'; + + /** + * Sheet index to read + * + * @var int + */ + private $_sheetIndex = 0; + + /** + * Formats + * + * @var array + */ + private $_formats = array( 'h1' => array( 'font' => array( 'bold' => true, + 'size' => 24, + ), + ), // Bold, 24pt + 'h2' => array( 'font' => array( 'bold' => true, + 'size' => 18, + ), + ), // Bold, 18pt + 'h3' => array( 'font' => array( 'bold' => true, + 'size' => 13.5, + ), + ), // Bold, 13.5pt + 'h4' => array( 'font' => array( 'bold' => true, + 'size' => 12, + ), + ), // Bold, 12pt + 'h5' => array( 'font' => array( 'bold' => true, + 'size' => 10, + ), + ), // Bold, 10pt + 'h6' => array( 'font' => array( 'bold' => true, + 'size' => 7.5, + ), + ), // Bold, 7.5pt + 'a' => array( 'font' => array( 'underline' => true, + 'color' => array( 'argb' => PHPExcel_Style_Color::COLOR_BLUE, + ), + ), + ), // Blue underlined + 'hr' => array( 'borders' => array( 'bottom' => array( 'style' => PHPExcel_Style_Border::BORDER_THIN, + 'color' => array( PHPExcel_Style_Color::COLOR_BLACK, + ), + ), + ), + ), // Bottom border + ); + + + /** + * Create a new PHPExcel_Reader_HTML + */ + public function __construct() { + $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is an HTML file + * + * @return boolean + */ + protected function _isValidFormat() + { + // Reading 2048 bytes should be enough to validate that the format is HTML + $data = fread($this->_fileHandle, 2048); + if ((strpos($data, '<') !== FALSE) && + (strlen($data) !== strlen(strip_tags($data)))) { + return TRUE; + } + + return FALSE; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'ANSI') + { + $this->_inputEncoding = $pValue; + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->_inputEncoding; + } + + // Data Array used for testing only, should write to PHPExcel object on completion of tests + private $_dataArray = array(); + + private $_tableLevel = 0; + private $_nestedColumn = array('A'); + + private function _setTableStartColumn($column) { + if ($this->_tableLevel == 0) + $column = 'A'; + ++$this->_tableLevel; + $this->_nestedColumn[$this->_tableLevel] = $column; + + return $this->_nestedColumn[$this->_tableLevel]; + } + + private function _getTableStartColumn() { + return $this->_nestedColumn[$this->_tableLevel]; + } + + private function _releaseTableStartColumn() { + --$this->_tableLevel; + return array_pop($this->_nestedColumn); + } + + private function _flushCell($sheet,$column,$row,&$cellContent) { + if (is_string($cellContent)) { + // Simple String content + if (trim($cellContent) > '') { + // Only actually write it if there's content in the string +// echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '<br />'; + // Write to worksheet to be done here... + // ... we return the cell so we can mess about with styles more easily + $cell = $sheet->setCellValue($column.$row,$cellContent,true); + $this->_dataArray[$row][$column] = $cellContent; + } + } else { + // We have a Rich Text run + // TODO + $this->_dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; + } + $cellContent = (string) ''; + } + + private function _processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent){ + foreach($element->childNodes as $child){ + if ($child instanceof DOMText) { + $domText = preg_replace('/\s+/',' ',trim($child->nodeValue)); + if (is_string($cellContent)) { + // simply append the text if the cell content is a plain text string + $cellContent .= $domText; + } else { + // but if we have a rich text run instead, we need to append it correctly + // TODO + } + } elseif($child instanceof DOMElement) { +// echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />'; + + $attributeArray = array(); + foreach($child->attributes as $attribute) { +// echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />'; + $attributeArray[$attribute->name] = $attribute->value; + } + + switch($child->nodeName) { + case 'meta' : + foreach($attributeArray as $attributeName => $attributeValue) { + switch($attributeName) { + case 'content': + // TODO + // Extract character set, so we can convert to UTF-8 if required + break; + } + } + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + break; + case 'title' : + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + $sheet->setTitle($cellContent); + $cellContent = ''; + break; + case 'span' : + case 'div' : + case 'font' : + case 'i' : + case 'em' : + case 'strong': + case 'b' : +// echo 'STYLING, SPAN OR DIV<br />'; + if ($cellContent > '') + $cellContent .= ' '; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + if ($cellContent > '') + $cellContent .= ' '; +// echo 'END OF STYLING, SPAN OR DIV<br />'; + break; + case 'hr' : + $this->_flushCell($sheet,$column,$row,$cellContent); + ++$row; + if (isset($this->_formats[$child->nodeName])) { + $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + } else { + $cellContent = '----------'; + $this->_flushCell($sheet,$column,$row,$cellContent); + } + ++$row; + case 'br' : + if ($this->_tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; + } else { + // Otherwise flush our existing content and move the row cursor on + $this->_flushCell($sheet,$column,$row,$cellContent); + ++$row; + } +// echo 'HARD LINE BREAK: ' , '<br />'; + break; + case 'a' : +// echo 'START OF HYPERLINK: ' , '<br />'; + foreach($attributeArray as $attributeName => $attributeValue) { + switch($attributeName) { + case 'href': +// echo 'Link to ' , $attributeValue , '<br />'; + $sheet->getCell($column.$row)->getHyperlink()->setUrl($attributeValue); + if (isset($this->_formats[$child->nodeName])) { + $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + } + break; + } + } + $cellContent .= ' '; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF HYPERLINK:' , '<br />'; + break; + case 'h1' : + case 'h2' : + case 'h3' : + case 'h4' : + case 'h5' : + case 'h6' : + case 'ol' : + case 'ul' : + case 'p' : + if ($this->_tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; +// echo 'LIST ENTRY: ' , '<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + } else { + if ($cellContent > '') { + $this->_flushCell($sheet,$column,$row,$cellContent); + $row += 2; + } +// echo 'START OF PARAGRAPH: ' , '<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF PARAGRAPH:' , '<br />'; + $this->_flushCell($sheet,$column,$row,$cellContent); + + if (isset($this->_formats[$child->nodeName])) { + $sheet->getStyle($column.$row)->applyFromArray($this->_formats[$child->nodeName]); + } + + $row += 2; + $column = 'A'; + } + break; + case 'li' : + if ($this->_tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; +// echo 'LIST ENTRY: ' , '<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + } else { + if ($cellContent > '') { + $this->_flushCell($sheet,$column,$row,$cellContent); + } + ++$row; +// echo 'LIST ENTRY: ' , '<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + $this->_flushCell($sheet,$column,$row,$cellContent); + $column = 'A'; + } + break; + case 'table' : + $this->_flushCell($sheet,$column,$row,$cellContent); + $column = $this->_setTableStartColumn($column); +// echo 'START OF TABLE LEVEL ' , $this->_tableLevel , '<br />'; + if ($this->_tableLevel > 1) + --$row; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF TABLE LEVEL ' , $this->_tableLevel , '<br />'; + $column = $this->_releaseTableStartColumn(); + if ($this->_tableLevel > 1) { + ++$column; + } else { + ++$row; + } + break; + case 'thead' : + case 'tbody' : + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + break; + case 'tr' : + ++$row; + $column = $this->_getTableStartColumn(); + $cellContent = ''; +// echo 'START OF TABLE ' , $this->_tableLevel , ' ROW<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF TABLE ' , $this->_tableLevel , ' ROW<br />'; + break; + case 'th' : + case 'td' : +// echo 'START OF TABLE ' , $this->_tableLevel , ' CELL<br />'; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); +// echo 'END OF TABLE ' , $this->_tableLevel , ' CELL<br />'; + $this->_flushCell($sheet,$column,$row,$cellContent); + ++$column; + break; + case 'body' : + $row = 1; + $column = 'A'; + $content = ''; + $this->_tableLevel = 0; + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + break; + default: + $this->_processDomElement($child,$sheet,$row,$column,$cellContent); + } + } + } + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Open file to validate + $this->_openFile($pFilename); + if (!$this->_isValidFormat()) { + fclose ($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid HTML file."); + } + // Close after validating + fclose ($this->_fileHandle); + + // Create new PHPExcel + while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { + $objPHPExcel->createSheet(); + } + $objPHPExcel->setActiveSheetIndex( $this->_sheetIndex ); + + // Create a new DOM object + $dom = new domDocument; + // Reload the HTML file into the DOM object + $loaded = $dom->loadHTMLFile($pFilename, PHPExcel_Settings::getLibXmlLoaderOptions()); + if ($loaded === FALSE) { + throw new PHPExcel_Reader_Exception('Failed to load ',$pFilename,' as a DOM Document'); + } + + // Discard white space + $dom->preserveWhiteSpace = false; + + + $row = 0; + $column = 'A'; + $content = ''; + $this->_processDomElement($dom,$objPHPExcel->getActiveSheet(),$row,$column,$content); + +// echo '<hr />'; +// var_dump($this->_dataArray); + + // Return + return $objPHPExcel; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() { + return $this->_sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Reader_HTML + */ + public function setSheetIndex($pValue = 0) { + $this->_sheetIndex = $pValue; + return $this; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php new file mode 100644 index 00000000..5a691a5f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php @@ -0,0 +1,47 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Reader_IReadFilter + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +interface PHPExcel_Reader_IReadFilter +{ + /** + * Should this cell be read? + * + * @param $column String column index + * @param $row Row index + * @param $worksheetName Optional worksheet name + * @return boolean + */ + public function readCell($column, $row, $worksheetName = ''); +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php new file mode 100644 index 00000000..6c3e878e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php @@ -0,0 +1,53 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Reader_IReader + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +interface PHPExcel_Reader_IReader +{ + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + */ + public function canRead($pFilename); + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename); +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php new file mode 100644 index 00000000..8ad7061c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php @@ -0,0 +1,707 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_OOCalc + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_OOCalc extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Formats + * + * @var array + */ + private $_styles = array(); + + + /** + * Create a new PHPExcel_Reader_OOCalc + */ + public function __construct() { + $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + // Check if zip class exists +// if (!class_exists($zipClass, FALSE)) { +// throw new PHPExcel_Reader_Exception($zipClass . " library is not enabled"); +// } + + $mimeType = 'UNKNOWN'; + // Load file + $zip = new $zipClass; + if ($zip->open($pFilename) === true) { + // check if it is an OOXML archive + $stat = $zip->statName('mimetype'); + if ($stat && ($stat['size'] <= 255)) { + $mimeType = $zip->getFromName($stat['name']); + } elseif($stat = $zip->statName('META-INF/manifest.xml')) { + $xml = simplexml_load_string($zip->getFromName('META-INF/manifest.xml'), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesContent = $xml->getNamespaces(true); + if (isset($namespacesContent['manifest'])) { + $manifest = $xml->children($namespacesContent['manifest']); + foreach($manifest as $manifestDataSet) { + $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); + if ($manifestAttributes->{'full-path'} == '/') { + $mimeType = (string) $manifestAttributes->{'media-type'}; + break; + } + } + } + } + + $zip->close(); + + return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet'); + } + + return FALSE; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + + $worksheetNames = array(); + + $xml = new XMLReader(); + $res = $xml->open('zip://'.realpath($pFilename).'#content.xml', null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2,true); + + // Step into the first level of content of the XML + $xml->read(); + while ($xml->read()) { + // Quickly jump through to the office:body node + while ($xml->name !== 'office:body') { + if ($xml->isEmptyElement) + $xml->read(); + else + $xml->next(); + } + // Now read each node until we find our first table:table node + while ($xml->read()) { + if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + // Loop through each table:table node reading the table:name attribute for each worksheet name + do { + $worksheetNames[] = $xml->getAttribute('table:name'); + $xml->next(); + } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); + } + } + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + + $xml = new XMLReader(); + $res = $xml->open('zip://'.realpath($pFilename).'#content.xml', null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2,true); + + // Step into the first level of content of the XML + $xml->read(); + while ($xml->read()) { + // Quickly jump through to the office:body node + while ($xml->name !== 'office:body') { + if ($xml->isEmptyElement) + $xml->read(); + else + $xml->next(); + } + // Now read each node until we find our first table:table node + while ($xml->read()) { + if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + $worksheetNames[] = $xml->getAttribute('table:name'); + + $tmpInfo = array( + 'worksheetName' => $xml->getAttribute('table:name'), + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + // Loop through each child node of the table:table element reading + $currCells = 0; + do { + $xml->read(); + if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { + $rowspan = $xml->getAttribute('table:number-rows-repeated'); + $rowspan = empty($rowspan) ? 1 : $rowspan; + $tmpInfo['totalRows'] += $rowspan; + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $currCells = 0; + // Step into the row + $xml->read(); + do { + if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + if (!$xml->isEmptyElement) { + $currCells++; + $xml->next(); + } else { + $xml->read(); + } + } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + $mergeSize = $xml->getAttribute('table:number-columns-repeated'); + $currCells += $mergeSize; + $xml->read(); + } + } while ($xml->name != 'table:table-row'); + } + } while ($xml->name != 'table:table'); + + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'],$currCells); + $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $worksheetInfo[] = $tmpInfo; + } + } + +// foreach($workbookData->table as $worksheetDataSet) { +// $worksheetData = $worksheetDataSet->children($namespacesContent['table']); +// $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']); +// +// $rowIndex = 0; +// foreach ($worksheetData as $key => $rowData) { +// switch ($key) { +// case 'table-row' : +// $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']); +// $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? +// $rowDataTableAttributes['number-rows-repeated'] : 1; +// $columnIndex = 0; +// +// foreach ($rowData as $key => $cellData) { +// $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']); +// $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? +// $cellDataTableAttributes['number-columns-repeated'] : 1; +// $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']); +// if (isset($cellDataOfficeAttributes['value-type'])) { +// $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex + $colRepeats - 1); +// $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex + $rowRepeats); +// } +// $columnIndex += $colRepeats; +// } +// $rowIndex += $rowRepeats; +// break; +// } +// } +// +// $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); +// $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; +// +// } +// } + } + + return $worksheetInfo; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + + private static function identifyFixedStyleValue($styleList,&$styleAttributeValue) { + $styleAttributeValue = strtolower($styleAttributeValue); + foreach($styleList as $style) { + if ($styleAttributeValue == strtolower($style)) { + $styleAttributeValue = $style; + return true; + } + } + return false; + } + + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + +// echo '<h1>Meta Information</h1>'; + $xml = simplexml_load_string($zip->getFromName("meta.xml"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesMeta = $xml->getNamespaces(true); +// echo '<pre>'; +// print_r($namespacesMeta); +// echo '</pre><hr />'; + + $docProps = $objPHPExcel->getProperties(); + $officeProperty = $xml->children($namespacesMeta['office']); + foreach($officeProperty as $officePropertyData) { + $officePropertyDC = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); + } + foreach($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'title' : + $docProps->setTitle($propertyValue); + break; + case 'subject' : + $docProps->setSubject($propertyValue); + break; + case 'creator' : + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + break; + case 'date' : + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'description' : + $docProps->setDescription($propertyValue); + break; + } + } + $officePropertyMeta = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); + } + foreach($officePropertyMeta as $propertyName => $propertyValue) { + $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']); + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'initial-creator' : + $docProps->setCreator($propertyValue); + break; + case 'keyword' : + $docProps->setKeywords($propertyValue); + break; + case 'creation-date' : + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + break; + case 'user-defined' : + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + foreach ($propertyValueAttributes as $key => $value) { + if ($key == 'name') { + $propertyValueName = (string) $value; + } elseif($key == 'value-type') { + switch ($value) { + case 'date' : + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'date'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE; + break; + case 'boolean' : + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'bool'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN; + break; + case 'float' : + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'r4'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT; + break; + default : + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + } + } + } + $docProps->setCustomProperty($propertyValueName,$propertyValue,$propertyValueType); + break; + } + } + } + + +// echo '<h1>Workbook Content</h1>'; + $xml = simplexml_load_string($zip->getFromName("content.xml"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesContent = $xml->getNamespaces(true); +// echo '<pre>'; +// print_r($namespacesContent); +// echo '</pre><hr />'; + + $workbook = $xml->children($namespacesContent['office']); + foreach($workbook->body->spreadsheet as $workbookData) { + $workbookData = $workbookData->children($namespacesContent['table']); + $worksheetID = 0; + foreach($workbookData->table as $worksheetDataSet) { + $worksheetData = $worksheetDataSet->children($namespacesContent['table']); +// print_r($worksheetData); +// echo '<br />'; + $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']); +// print_r($worksheetDataAttributes); +// echo '<br />'; + if ((isset($this->_loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) && + (!in_array($worksheetDataAttributes['name'], $this->_loadSheetsOnly))) { + continue; + } + +// echo '<h2>Worksheet '.$worksheetDataAttributes['name'].'</h2>'; + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + if (isset($worksheetDataAttributes['name'])) { + $worksheetName = (string) $worksheetDataAttributes['name']; + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in + // formula cells... during the load, all formulae should be correct, and we're simply + // bringing the worksheet name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName,false); + } + + $rowID = 1; + foreach($worksheetData as $key => $rowData) { +// echo '<b>'.$key.'</b><br />'; + switch ($key) { + case 'table-header-rows': + foreach ($rowData as $key=>$cellData) { + $rowData = $cellData; + break; + } + case 'table-row' : + $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']); + $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? + $rowDataTableAttributes['number-rows-repeated'] : 1; + $columnID = 'A'; + foreach($rowData as $key => $cellData) { + if ($this->getReadFilter() !== NULL) { + if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { + continue; + } + } + +// echo '<b>'.$columnID.$rowID.'</b><br />'; + $cellDataText = (isset($namespacesContent['text'])) ? + $cellData->children($namespacesContent['text']) : + ''; + $cellDataOffice = $cellData->children($namespacesContent['office']); + $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']); + $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']); + +// echo 'Office Attributes: '; +// print_r($cellDataOfficeAttributes); +// echo '<br />Table Attributes: '; +// print_r($cellDataTableAttributes); +// echo '<br />Cell Data Text'; +// print_r($cellDataText); +// echo '<br />'; +// + $type = $formatting = $hyperlink = null; + $hasCalculatedValue = false; + $cellDataFormula = ''; + if (isset($cellDataTableAttributes['formula'])) { + $cellDataFormula = $cellDataTableAttributes['formula']; + $hasCalculatedValue = true; + } + + if (isset($cellDataOffice->annotation)) { +// echo 'Cell has comment<br />'; + $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']); + $textArray = array(); + foreach($annotationText as $t) { + foreach($t->span as $text) { + $textArray[] = (string)$text; + } + } + $text = implode("\n",$textArray); +// echo $text,'<br />'; + $objPHPExcel->getActiveSheet()->getComment( $columnID.$rowID ) +// ->setAuthor( $author ) + ->setText($this->_parseRichText($text) ); + } + + if (isset($cellDataText->p)) { + // Consolidate if there are multiple p records (maybe with spans as well) + $dataArray = array(); + // Text can have multiple text:p and within those, multiple text:span. + // text:p newlines, but text:span does not. + // Also, here we assume there is no text data is span fields are specified, since + // we have no way of knowing proper positioning anyway. + foreach ($cellDataText->p as $pData) { + if (isset($pData->span)) { + // span sections do not newline, so we just create one large string here + $spanSection = ""; + foreach ($pData->span as $spanData) { + $spanSection .= $spanData; + } + array_push($dataArray, $spanSection); + } else { + array_push($dataArray, $pData); + } + } + $allCellDataText = implode($dataArray, "\n"); + +// echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'<br />'; + switch ($cellDataOfficeAttributes['value-type']) { + case 'string' : + $type = PHPExcel_Cell_DataType::TYPE_STRING; + $dataValue = $allCellDataText; + if (isset($dataValue->a)) { + $dataValue = $dataValue->a; + $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']); + $hyperlink = $cellXLinkAttributes['href']; + } + break; + case 'boolean' : + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $dataValue = ($allCellDataText == 'TRUE') ? True : False; + break; + case 'percentage' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + $dataValue = (integer) $dataValue; + } + $formatting = PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00; + break; + case 'currency' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + $dataValue = (integer) $dataValue; + } + $formatting = PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE; + break; + case 'float' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + if ($dataValue == (integer) $dataValue) + $dataValue = (integer) $dataValue; + else + $dataValue = (float) $dataValue; + } + break; + case 'date' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT); + $dateObj->setTimeZone($timezoneObj); + list($year,$month,$day,$hour,$minute,$second) = explode(' ',$dateObj->format('Y m d H i s')); + $dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year,$month,$day,$hour,$minute,$second); + if ($dataValue != floor($dataValue)) { + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15.' '.PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4; + } else { + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15; + } + break; + case 'time' : + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 '.implode(':',sscanf($cellDataOfficeAttributes['time-value'],'PT%dH%dM%dS')))); + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4; + break; + } +// echo 'Data value is '.$dataValue.'<br />'; +// if ($hyperlink !== NULL) { +// echo 'Hyperlink is '.$hyperlink.'<br />'; +// } + } else { + $type = PHPExcel_Cell_DataType::TYPE_NULL; + $dataValue = NULL; + } + + if ($hasCalculatedValue) { + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; +// echo 'Formula: ', $cellDataFormula, PHP_EOL; + $cellDataFormula = substr($cellDataFormula,strpos($cellDataFormula,':=')+1); + $temp = explode('"',$cellDataFormula); + $tKey = false; + foreach($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($tKey = !$tKey) { + $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/Ui','$1!$2:$3',$value); // Cell range reference in another sheet + $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/Ui','$1!$2',$value); // Cell reference in another sheet + $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/Ui','$1:$2',$value); // Cell range reference + $value = preg_replace('/\[\.([^\.]+)\]/Ui','$1',$value); // Simple cell reference + $value = PHPExcel_Calculation::_translateSeparator(';',',',$value,$inBraces); + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"',$temp); +// echo 'Adjusted Formula: ', $cellDataFormula, PHP_EOL; + } + + $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? + $cellDataTableAttributes['number-columns-repeated'] : 1; + if ($type !== NULL) { + for ($i = 0; $i < $colRepeats; ++$i) { + if ($i > 0) { + ++$columnID; + } + if ($type !== PHPExcel_Cell_DataType::TYPE_NULL) { + for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) { + $rID = $rowID + $rowAdjust; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue),$type); + if ($hasCalculatedValue) { +// echo 'Forumla result is '.$dataValue.'<br />'; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setCalculatedValue($dataValue); + } + if ($formatting !== NULL) { + $objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode($formatting); + } else { + $objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL); + } + if ($hyperlink !== NULL) { + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->getHyperlink()->setUrl($hyperlink); + } + } + } + } + } + + // Merged cells + if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) { + if (($type !== PHPExcel_Cell_DataType::TYPE_NULL) || (!$this->_readDataOnly)) { + $columnTo = $columnID; + if (isset($cellDataTableAttributes['number-columns-spanned'])) { + $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] -2); + } + $rowTo = $rowID; + if (isset($cellDataTableAttributes['number-rows-spanned'])) { + $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1; + } + $cellRange = $columnID.$rowID.':'.$columnTo.$rowTo; + $objPHPExcel->getActiveSheet()->mergeCells($cellRange); + } + } + + ++$columnID; + } + $rowID += $rowRepeats; + break; + } + } + ++$worksheetID; + } + } + + // Return + return $objPHPExcel; + } + + + private function _parseRichText($is = '') { + $value = new PHPExcel_RichText(); + + $value->createText($is); + + return $value; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php new file mode 100644 index 00000000..cd87ce56 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php @@ -0,0 +1,450 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_SYLK + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Input encoding + * + * @var string + */ + private $_inputEncoding = 'ANSI'; + + /** + * Sheet index to read + * + * @var int + */ + private $_sheetIndex = 0; + + /** + * Formats + * + * @var array + */ + private $_formats = array(); + + /** + * Format Count + * + * @var int + */ + private $_format = 0; + + /** + * Create a new PHPExcel_Reader_SYLK + */ + public function __construct() { + $this->_readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is a SYLK file + * + * @return boolean + */ + protected function _isValidFormat() + { + // Read sample data (first 2 KB will do) + $data = fread($this->_fileHandle, 2048); + + // Count delimiters in file + $delimiterCount = substr_count($data, ';'); + if ($delimiterCount < 1) { + return FALSE; + } + + // Analyze first line looking for ID; signature + $lines = explode("\n", $data); + if (substr($lines[0],0,4) != 'ID;P') { + return FALSE; + } + + return TRUE; + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'ANSI') + { + $this->_inputEncoding = $pValue; + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->_inputEncoding; + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Open file + $this->_openFile($pFilename); + if (!$this->_isValidFormat()) { + fclose ($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->_fileHandle; + rewind($fileHandle); + + $worksheetInfo = array(); + $worksheetInfo[0]['worksheetName'] = 'Worksheet'; + $worksheetInfo[0]['lastColumnLetter'] = 'A'; + $worksheetInfo[0]['lastColumnIndex'] = 0; + $worksheetInfo[0]['totalRows'] = 0; + $worksheetInfo[0]['totalColumns'] = 0; + + // Loop through file + $rowData = array(); + + // loop through one row (line) at a time in the file + $rowIndex = 0; + while (($rowData = fgets($fileHandle)) !== FALSE) { + $columnIndex = 0; + + // convert SYLK encoded $rowData to UTF-8 + $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); + + // explode each row at semicolons while taking into account that literal semicolon (;) + // is escaped like this (;;) + $rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData))))); + + $dataType = array_shift($rowData); + if ($dataType == 'C') { + // Read cell value data + foreach($rowData as $rowDatum) { + switch($rowDatum{0}) { + case 'C' : + case 'X' : + $columnIndex = substr($rowDatum,1) - 1; + break; + case 'R' : + case 'Y' : + $rowIndex = substr($rowDatum,1); + break; + } + + $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); + $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); + } + } + } + + $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); + $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; + + // Close file + fclose($fileHandle); + + return $worksheetInfo; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Open file + $this->_openFile($pFilename); + if (!$this->_isValidFormat()) { + fclose ($this->_fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->_fileHandle; + rewind($fileHandle); + + // Create new PHPExcel + while ($objPHPExcel->getSheetCount() <= $this->_sheetIndex) { + $objPHPExcel->createSheet(); + } + $objPHPExcel->setActiveSheetIndex( $this->_sheetIndex ); + + $fromFormats = array('\-', '\ '); + $toFormats = array('-', ' '); + + // Loop through file + $rowData = array(); + $column = $row = ''; + + // loop through one row (line) at a time in the file + while (($rowData = fgets($fileHandle)) !== FALSE) { + + // convert SYLK encoded $rowData to UTF-8 + $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); + + // explode each row at semicolons while taking into account that literal semicolon (;) + // is escaped like this (;;) + $rowData = explode("\t",str_replace('¤',';',str_replace(';',"\t",str_replace(';;','¤',rtrim($rowData))))); + + $dataType = array_shift($rowData); + // Read shared styles + if ($dataType == 'P') { + $formatArray = array(); + foreach($rowData as $rowDatum) { + switch($rowDatum{0}) { + case 'P' : $formatArray['numberformat']['code'] = str_replace($fromFormats,$toFormats,substr($rowDatum,1)); + break; + case 'E' : + case 'F' : $formatArray['font']['name'] = substr($rowDatum,1); + break; + case 'L' : $formatArray['font']['size'] = substr($rowDatum,1); + break; + case 'S' : $styleSettings = substr($rowDatum,1); + for ($i=0;$i<strlen($styleSettings);++$i) { + switch ($styleSettings{$i}) { + case 'I' : $formatArray['font']['italic'] = true; + break; + case 'D' : $formatArray['font']['bold'] = true; + break; + case 'T' : $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'B' : $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'L' : $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'R' : $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + } + } + break; + } + } + $this->_formats['P'.$this->_format++] = $formatArray; + // Read cell value data + } elseif ($dataType == 'C') { + $hasCalculatedValue = false; + $cellData = $cellDataFormula = ''; + foreach($rowData as $rowDatum) { + switch($rowDatum{0}) { + case 'C' : + case 'X' : $column = substr($rowDatum,1); + break; + case 'R' : + case 'Y' : $row = substr($rowDatum,1); + break; + case 'K' : $cellData = substr($rowDatum,1); + break; + case 'E' : $cellDataFormula = '='.substr($rowDatum,1); + // Convert R1C1 style references to A1 style references (but only when not quoted) + $temp = explode('"',$cellDataFormula); + $key = false; + foreach($temp as &$value) { + // Only count/replace in alternate array entries + if ($key = !$key) { + preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/',$value, $cellReferences,PREG_SET_ORDER+PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach($cellReferences as $cellReference) { + $rowReference = $cellReference[2][0]; + // Empty R reference is the current row + if ($rowReference == '') $rowReference = $row; + // Bracketed R references are relative to the current row + if ($rowReference{0} == '[') $rowReference = $row + trim($rowReference,'[]'); + $columnReference = $cellReference[4][0]; + // Empty C reference is the current column + if ($columnReference == '') $columnReference = $column; + // Bracketed C references are relative to the current column + if ($columnReference{0} == '[') $columnReference = $column + trim($columnReference,'[]'); + $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; + + $value = substr_replace($value,$A1CellReference,$cellReference[0][1],strlen($cellReference[0][0])); + } + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"',$temp); + $hasCalculatedValue = true; + break; + } + } + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + $cellData = PHPExcel_Calculation::_unwrapResult($cellData); + + // Set cell value + $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); + if ($hasCalculatedValue) { + $cellData = PHPExcel_Calculation::_unwrapResult($cellData); + $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); + } + // Read cell formatting + } elseif ($dataType == 'F') { + $formatStyle = $columnWidth = $styleSettings = ''; + $styleData = array(); + foreach($rowData as $rowDatum) { + switch($rowDatum{0}) { + case 'C' : + case 'X' : $column = substr($rowDatum,1); + break; + case 'R' : + case 'Y' : $row = substr($rowDatum,1); + break; + case 'P' : $formatStyle = $rowDatum; + break; + case 'W' : list($startCol,$endCol,$columnWidth) = explode(' ',substr($rowDatum,1)); + break; + case 'S' : $styleSettings = substr($rowDatum,1); + for ($i=0;$i<strlen($styleSettings);++$i) { + switch ($styleSettings{$i}) { + case 'I' : $styleData['font']['italic'] = true; + break; + case 'D' : $styleData['font']['bold'] = true; + break; + case 'T' : $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'B' : $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'L' : $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'R' : $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + } + } + break; + } + } + if (($formatStyle > '') && ($column > '') && ($row > '')) { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + if (isset($this->_formats[$formatStyle])) { + $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->_formats[$formatStyle]); + } + } + if ((!empty($styleData)) && ($column > '') && ($row > '')) { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); + } + if ($columnWidth > '') { + if ($startCol == $endCol) { + $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); + } else { + $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1); + $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); + do { + $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); + } while ($startCol != $endCol); + } + } + } else { + foreach($rowData as $rowDatum) { + switch($rowDatum{0}) { + case 'C' : + case 'X' : $column = substr($rowDatum,1); + break; + case 'R' : + case 'Y' : $row = substr($rowDatum,1); + break; + } + } + } + } + + // Close file + fclose($fileHandle); + + // Return + return $objPHPExcel; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() { + return $this->_sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Reader_SYLK + */ + public function setSheetIndex($pValue = 0) { + $this->_sheetIndex = $pValue; + return $this; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php new file mode 100644 index 00000000..402f2b47 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php @@ -0,0 +1,922 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_ReferenceHelper (Singleton) + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_ReferenceHelper +{ + /** Constants */ + /** Regular Expressions */ + const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; + const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; + const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)'; + const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; + + /** + * Instance of this class + * + * @var PHPExcel_ReferenceHelper + */ + private static $_instance; + + /** + * Get an instance of this class + * + * @return PHPExcel_ReferenceHelper + */ + public static function getInstance() { + if (!isset(self::$_instance) || (self::$_instance === NULL)) { + self::$_instance = new PHPExcel_ReferenceHelper(); + } + + return self::$_instance; + } + + /** + * Create a new PHPExcel_ReferenceHelper + */ + protected function __construct() { + } + + /** + * Compare two column addresses + * Intended for use as a Callback function for sorting column addresses by column + * + * @param string $a First column to test (e.g. 'AA') + * @param string $b Second column to test (e.g. 'Z') + * @return integer + */ + public static function columnSort($a, $b) { + return strcasecmp(strlen($a) . $a, strlen($b) . $b); + } + + /** + * Compare two column addresses + * Intended for use as a Callback function for reverse sorting column addresses by column + * + * @param string $a First column to test (e.g. 'AA') + * @param string $b Second column to test (e.g. 'Z') + * @return integer + */ + public static function columnReverseSort($a, $b) { + return 1 - strcasecmp(strlen($a) . $a, strlen($b) . $b); + } + + /** + * Compare two cell addresses + * Intended for use as a Callback function for sorting cell addresses by column and row + * + * @param string $a First cell to test (e.g. 'AA1') + * @param string $b Second cell to test (e.g. 'Z1') + * @return integer + */ + public static function cellSort($a, $b) { + sscanf($a,'%[A-Z]%d', $ac, $ar); + sscanf($b,'%[A-Z]%d', $bc, $br); + + if ($ar == $br) { + return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); + } + return ($ar < $br) ? -1 : 1; + } + + /** + * Compare two cell addresses + * Intended for use as a Callback function for sorting cell addresses by column and row + * + * @param string $a First cell to test (e.g. 'AA1') + * @param string $b Second cell to test (e.g. 'Z1') + * @return integer + */ + public static function cellReverseSort($a, $b) { + sscanf($a,'%[A-Z]%d', $ac, $ar); + sscanf($b,'%[A-Z]%d', $bc, $br); + + if ($ar == $br) { + return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); + } + return ($ar < $br) ? 1 : -1; + } + + /** + * Test whether a cell address falls within a defined range of cells + * + * @param string $cellAddress Address of the cell we're testing + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @return boolean + */ + private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) { + list($cellColumn, $cellRow) = PHPExcel_Cell::coordinateFromString($cellAddress); + $cellColumnIndex = PHPExcel_Cell::columnIndexFromString($cellColumn); + // Is cell within the range of rows/columns if we're deleting + if ($pNumRows < 0 && + ($cellRow >= ($beforeRow + $pNumRows)) && + ($cellRow < $beforeRow)) { + return TRUE; + } elseif ($pNumCols < 0 && + ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && + ($cellColumnIndex < $beforeColumnIndex)) { + return TRUE; + } + return FALSE; + } + + /** + * Update page breaks when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustPageBreaks(PHPExcel_Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aBreaks = $pSheet->getBreaks(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aBreaks, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aBreaks, array('PHPExcel_ReferenceHelper','cellSort')); + + foreach ($aBreaks as $key => $value) { + if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + // If we're deleting, then clear any defined breaks that are within the range + // of rows/columns that we're deleting + $pSheet->setBreak($key, PHPExcel_Worksheet::BREAK_NONE); + } else { + // Otherwise update any affected breaks by inserting a new break at the appropriate point + // and removing the old affected break + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setBreak($newReference, $value) + ->setBreak($key, PHPExcel_Worksheet::BREAK_NONE); + } + } + } + } + + /** + * Update cell comments when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aComments = $pSheet->getComments(); + $aNewComments = array(); // the new array of all comments + + foreach ($aComments as $key => &$value) { + // Any comments inside a deleted range will be ignored + if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + // Otherwise build a new array of comments indexed by the adjusted cell reference + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $aNewComments[$newReference] = $value; + } + } + // Replace the comments array with the new set of comments + $pSheet->setComments($aNewComments); + } + + /** + * Update hyperlinks when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aHyperlinkCollection = $pSheet->getHyperlinkCollection(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellSort')); + + foreach ($aHyperlinkCollection as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setHyperlink( $newReference, $value ); + $pSheet->setHyperlink( $key, null ); + } + } + } + + /** + * Update data validations when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aDataValidationCollection = $pSheet->getDataValidationCollection(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellSort')); + foreach ($aDataValidationCollection as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setDataValidation( $newReference, $value ); + $pSheet->setDataValidation( $key, null ); + } + } + } + + /** + * Update merged cells when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aMergeCells = $pSheet->getMergeCells(); + $aNewMergeCells = array(); // the new array of all merge cells + foreach ($aMergeCells as $key => &$value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $aNewMergeCells[$newReference] = $newReference; + } + $pSheet->setMergeCells($aNewMergeCells); // replace the merge cells array + } + + /** + * Update protected cells when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aProtectedCells = $pSheet->getProtectedCells(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aProtectedCells, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aProtectedCells, array('PHPExcel_ReferenceHelper','cellSort')); + foreach ($aProtectedCells as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->protectCells( $newReference, $value, true ); + $pSheet->unprotectCells( $key ); + } + } + } + + /** + * Update column dimensions when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true); + if (!empty($aColumnDimensions)) { + foreach ($aColumnDimensions as $objColumnDimension) { + $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows); + list($newReference) = PHPExcel_Cell::coordinateFromString($newReference); + if ($objColumnDimension->getColumnIndex() != $newReference) { + $objColumnDimension->setColumnIndex($newReference); + } + } + $pSheet->refreshColumnDimensions(); + } + } + + /** + * Update row dimensions when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function _adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true); + if (!empty($aRowDimensions)) { + foreach ($aRowDimensions as $objRowDimension) { + $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows); + list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference); + if ($objRowDimension->getRowIndex() != $newReference) { + $objRowDimension->setRowIndex($newReference); + } + } + $pSheet->refreshRowDimensions(); + + $copyDimension = $pSheet->getRowDimension($beforeRow - 1); + for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) { + $newDimension = $pSheet->getRowDimension($i); + $newDimension->setRowHeight($copyDimension->getRowHeight()); + $newDimension->setVisible($copyDimension->getVisible()); + $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); + $newDimension->setCollapsed($copyDimension->getCollapsed()); + } + } + } + + /** + * Insert a new column or row, updating all possible related data + * + * @param string $pBefore Insert before this cell address (e.g. 'A1') + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @throws PHPExcel_Exception + */ + public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = NULL) + { + $remove = ($pNumCols < 0 || $pNumRows < 0); + $aCellCollection = $pSheet->getCellCollection(); + + // Get coordinates of $pBefore + $beforeColumn = 'A'; + $beforeRow = 1; + list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore); + $beforeColumnIndex = PHPExcel_Cell::columnIndexFromString($beforeColumn); + + // Clear cells if we are removing columns or rows + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); + + // 1. Clear column strips if we are removing columns + if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) { + for ($i = 1; $i <= $highestRow - 1; ++$i) { + for ($j = $beforeColumnIndex - 1 + $pNumCols; $j <= $beforeColumnIndex - 2; ++$j) { + $coordinate = PHPExcel_Cell::stringFromColumnIndex($j) . $i; + $pSheet->removeConditionalStyles($coordinate); + if ($pSheet->cellExists($coordinate)) { + $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL); + $pSheet->getCell($coordinate)->setXfIndex(0); + } + } + } + } + + // 2. Clear row strips if we are removing rows + if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) { + for ($i = $beforeColumnIndex - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) { + for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) { + $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . $j; + $pSheet->removeConditionalStyles($coordinate); + if ($pSheet->cellExists($coordinate)) { + $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL); + $pSheet->getCell($coordinate)->setXfIndex(0); + } + } + } + } + + // Loop through cells, bottom-up, and change cell coordinates + if($remove) { + // It's faster to reverse and pop than to use unshift, especially with large cell collections + $aCellCollection = array_reverse($aCellCollection); + } + while ($cellID = array_pop($aCellCollection)) { + $cell = $pSheet->getCell($cellID); + $cellIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn()); + + if ($cellIndex-1 + $pNumCols < 0) { + continue; + } + + // New coordinates + $newCoordinates = PHPExcel_Cell::stringFromColumnIndex($cellIndex-1 + $pNumCols) . ($cell->getRow() + $pNumRows); + + // Should the cell be updated? Move value and cellXf index from one cell to another. + if (($cellIndex >= $beforeColumnIndex) && + ($cell->getRow() >= $beforeRow)) { + + // Update cell styles + $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex()); + + // Insert this cell at its new location + if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { + // Formula should be adjusted + $pSheet->getCell($newCoordinates) + ->setValue($this->updateFormulaReferences($cell->getValue(), + $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + } else { + // Formula should not be adjusted + $pSheet->getCell($newCoordinates)->setValue($cell->getValue()); + } + + // Clear the original cell + $pSheet->getCellCacheController()->deleteCacheData($cellID); + + } else { + /* We don't need to update styles for rows/columns before our insertion position, + but we do still need to adjust any formulae in those cells */ + if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { + // Formula should be adjusted + $cell->setValue($this->updateFormulaReferences($cell->getValue(), + $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + } + + } + } + + // Duplicate styles for the newly inserted cells + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); + + if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) { + for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { + + // Style + $coordinate = PHPExcel_Cell::stringFromColumnIndex( $beforeColumnIndex - 2 ) . $i; + if ($pSheet->cellExists($coordinate)) { + $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? + $pSheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) { + $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); + if ($conditionalStyles) { + $cloned = array(); + foreach ($conditionalStyles as $conditionalStyle) { + $cloned[] = clone $conditionalStyle; + } + $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned); + } + } + } + + } + } + + if ($pNumRows > 0 && $beforeRow - 1 > 0) { + for ($i = $beforeColumnIndex - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) { + + // Style + $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1); + if ($pSheet->cellExists($coordinate)) { + $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? + $pSheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { + $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); + if ($conditionalStyles) { + $cloned = array(); + foreach ($conditionalStyles as $conditionalStyle) { + $cloned[] = clone $conditionalStyle; + } + $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned); + } + } + } + } + } + + // Update worksheet: column dimensions + $this->_adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: row dimensions + $this->_adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: page breaks + $this->_adjustPageBreaks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: comments + $this->_adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: hyperlinks + $this->_adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: data validations + $this->_adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: merge cells + $this->_adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: protected cells + $this->_adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: autofilter + $autoFilter = $pSheet->getAutoFilter(); + $autoFilterRange = $autoFilter->getRange(); + if (!empty($autoFilterRange)) { + if ($pNumCols != 0) { + $autoFilterColumns = array_keys($autoFilter->getColumns()); + if (count($autoFilterColumns) > 0) { + sscanf($pBefore,'%[A-Z]%d', $column, $row); + $columnIndex = PHPExcel_Cell::columnIndexFromString($column); + list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($autoFilterRange); + if ($columnIndex <= $rangeEnd[0]) { + if ($pNumCols < 0) { + // If we're actually deleting any columns that fall within the autofilter range, + // then we delete any rules for those columns + $deleteColumn = $columnIndex + $pNumCols - 1; + $deleteCount = abs($pNumCols); + for ($i = 1; $i <= $deleteCount; ++$i) { + if (in_array(PHPExcel_Cell::stringFromColumnIndex($deleteColumn),$autoFilterColumns)) { + $autoFilter->clearColumn(PHPExcel_Cell::stringFromColumnIndex($deleteColumn)); + } + ++$deleteColumn; + } + } + $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; + + // Shuffle columns in autofilter range + if ($pNumCols > 0) { + // For insert, we shuffle from end to beginning to avoid overwriting + $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]); + + $startColRef = $startCol; + $endColRef = $rangeEnd[0]; + $toColRef = $rangeEnd[0]+$pNumCols; + + do { + $autoFilter->shiftColumn(PHPExcel_Cell::stringFromColumnIndex($endColRef-1),PHPExcel_Cell::stringFromColumnIndex($toColRef-1)); + --$endColRef; + --$toColRef; + } while ($startColRef <= $endColRef); + } else { + // For delete, we shuffle from beginning to end to avoid overwriting + $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]); + do { + $autoFilter->shiftColumn($startColID,$toColID); + ++$startColID; + ++$toColID; + } while ($startColID != $endColID); + } + } + } + } + $pSheet->setAutoFilter( $this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows) ); + } + + // Update worksheet: freeze pane + if ($pSheet->getFreezePane() != '') { + $pSheet->freezePane( $this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows) ); + } + + // Page setup + if ($pSheet->getPageSetup()->isPrintAreaSet()) { + $pSheet->getPageSetup()->setPrintArea( $this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows) ); + } + + // Update worksheet: drawings + $aDrawings = $pSheet->getDrawingCollection(); + foreach ($aDrawings as $objDrawing) { + $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows); + if ($objDrawing->getCoordinates() != $newReference) { + $objDrawing->setCoordinates($newReference); + } + } + + // Update workbook: named ranges + if (count($pSheet->getParent()->getNamedRanges()) > 0) { + foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) { + if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) { + $namedRange->setRange( + $this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows) + ); + } + } + } + + // Garbage collect + $pSheet->garbageCollect(); + } + + /** + * Update references within formulas + * + * @param string $pFormula Formula to update + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to insert + * @param int $pNumRows Number of rows to insert + * @param string $sheetName Worksheet name/title + * @return string Updated formula + * @throws PHPExcel_Exception + */ + public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') { + // Update cell references in the formula + $formulaBlocks = explode('"',$pFormula); + $i = false; + foreach($formulaBlocks as &$formulaBlock) { + // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) + if ($i = !$i) { + $adjustCount = 0; + $newCellTokens = $cellTokens = array(); + // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_ROWRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = substr($this->updateCellReference('$A'.$match[3],$pBefore,$pNumCols,$pNumRows),2); + $modified4 = substr($this->updateCellReference('$A'.$match[4],$pBefore,$pNumCols,$pNumRows),2); + + if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { + if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = 100000; + $row = 10000000+trim($match[3],'$'); + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<!\d\$\!)'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_COLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = substr($this->updateCellReference($match[3].'$1',$pBefore,$pNumCols,$pNumRows),0,-2); + $modified4 = substr($this->updateCellReference($match[4].'$1',$pBefore,$pNumCols,$pNumRows),0,-2); + + if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { + if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($match[3],'$')) + 100000; + $row = 10000000; + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?![A-Z])/i'; + ++$adjustCount; + } + } + } + } + // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = $this->updateCellReference($match[3],$pBefore,$pNumCols,$pNumRows); + $modified4 = $this->updateCellReference($match[4],$pBefore,$pNumCols,$pNumRows); + + if ($match[3].$match[4] !== $modified3.$modified4) { + if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + list($column,$row) = PHPExcel_Cell::coordinateFromString($match[3]); + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($column,'$')) + 100000; + $row = trim($row,'$') + 10000000; + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLREF.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + + if ($matchCount > 0) { + foreach($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3]; + + $modified3 = $this->updateCellReference($match[3],$pBefore,$pNumCols,$pNumRows); + if ($match[3] !== $modified3) { + if (($match[2] == '') || (trim($match[2],"'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3; + list($column,$row) = PHPExcel_Cell::coordinateFromString($match[3]); + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($column,'$')) + 100000; + $row = trim($row,'$') + 10000000; + $cellIndex = $row . $column; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + if ($adjustCount > 0) { + if ($pNumCols > 0 || $pNumRows > 0) { + krsort($cellTokens); + krsort($newCellTokens); + } else { + ksort($cellTokens); + ksort($newCellTokens); + } // Update cell references in the formula + $formulaBlock = str_replace('\\','',preg_replace($cellTokens,$newCellTokens,$formulaBlock)); + } + } + } + unset($formulaBlock); + + // Then rebuild the formula string + return implode('"',$formulaBlocks); + } + + /** + * Update cell reference + * + * @param string $pCellRange Cell range + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell range + * @throws PHPExcel_Exception + */ + public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + // Is it in another worksheet? Will not have to update anything. + if (strpos($pCellRange, "!") !== false) { + return $pCellRange; + // Is it a range or a single cell? + } elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) { + // Single cell + return $this->_updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows); + } elseif (strpos($pCellRange, ':') !== false || strpos($pCellRange, ',') !== false) { + // Range + return $this->_updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows); + } else { + // Return original + return $pCellRange; + } + } + + /** + * Update named formulas (i.e. containing worksheet references / named ranges) + * + * @param PHPExcel $pPhpExcel Object to update + * @param string $oldName Old name (name to replace) + * @param string $newName New name + */ + public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') { + if ($oldName == '') { + return; + } + + foreach ($pPhpExcel->getWorksheetIterator() as $sheet) { + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + if (($cell !== NULL) && ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA)) { + $formula = $cell->getValue(); + if (strpos($formula, $oldName) !== false) { + $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); + $formula = str_replace($oldName . "!", $newName . "!", $formula); + $cell->setValueExplicit($formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + } + } + } + } + } + + /** + * Update cell range + * + * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell range + * @throws PHPExcel_Exception + */ + private function _updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + if (strpos($pCellRange,':') !== false || strpos($pCellRange, ',') !== false) { + // Update range + $range = PHPExcel_Cell::splitRange($pCellRange); + $ic = count($range); + for ($i = 0; $i < $ic; ++$i) { + $jc = count($range[$i]); + for ($j = 0; $j < $jc; ++$j) { + if (ctype_alpha($range[$i][$j])) { + $r = PHPExcel_Cell::coordinateFromString($this->_updateSingleCellReference($range[$i][$j].'1', $pBefore, $pNumCols, $pNumRows)); + $range[$i][$j] = $r[0]; + } elseif(ctype_digit($range[$i][$j])) { + $r = PHPExcel_Cell::coordinateFromString($this->_updateSingleCellReference('A'.$range[$i][$j], $pBefore, $pNumCols, $pNumRows)); + $range[$i][$j] = $r[1]; + } else { + $range[$i][$j] = $this->_updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); + } + } + } + + // Recreate range string + return PHPExcel_Cell::buildRange($range); + } else { + throw new PHPExcel_Exception("Only cell ranges may be passed to this method."); + } + } + + /** + * Update single cell reference + * + * @param string $pCellReference Single cell reference + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell reference + * @throws PHPExcel_Exception + */ + private function _updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) { + if (strpos($pCellReference, ':') === false && strpos($pCellReference, ',') === false) { + // Get coordinates of $pBefore + list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString( $pBefore ); + + // Get coordinates of $pCellReference + list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString( $pCellReference ); + + // Verify which parts should be updated + $updateColumn = (($newColumn{0} != '$') && ($beforeColumn{0} != '$') && + PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn)); + $updateRow = (($newRow{0} != '$') && ($beforeRow{0} != '$') && + $newRow >= $beforeRow); + + // Create new column reference + if ($updateColumn) { + $newColumn = PHPExcel_Cell::stringFromColumnIndex( PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols ); + } + + // Create new row reference + if ($updateRow) { + $newRow = $newRow + $pNumRows; + } + + // Return new reference + return $newColumn . $newRow; + } else { + throw new PHPExcel_Exception("Only single cell references may be passed to this method."); + } + } + + /** + * __clone implementation. Cloning should not be allowed in a Singleton! + * + * @throws PHPExcel_Exception + */ + public final function __clone() { + throw new PHPExcel_Exception("Cloning a Singleton is not allowed!"); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php new file mode 100644 index 00000000..2f172a05 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php @@ -0,0 +1,199 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_RichText + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_RichText implements PHPExcel_IComparable +{ + /** + * Rich text elements + * + * @var PHPExcel_RichText_ITextElement[] + */ + private $_richTextElements; + + /** + * Create a new PHPExcel_RichText instance + * + * @param PHPExcel_Cell $pCell + * @throws PHPExcel_Exception + */ + public function __construct(PHPExcel_Cell $pCell = null) + { + // Initialise variables + $this->_richTextElements = array(); + + // Rich-Text string attached to cell? + if ($pCell !== NULL) { + // Add cell text and style + if ($pCell->getValue() != "") { + $objRun = new PHPExcel_RichText_Run($pCell->getValue()); + $objRun->setFont(clone $pCell->getParent()->getStyle($pCell->getCoordinate())->getFont()); + $this->addText($objRun); + } + + // Set parent value + $pCell->setValueExplicit($this, PHPExcel_Cell_DataType::TYPE_STRING); + } + } + + /** + * Add text + * + * @param PHPExcel_RichText_ITextElement $pText Rich text element + * @throws PHPExcel_Exception + * @return PHPExcel_RichText + */ + public function addText(PHPExcel_RichText_ITextElement $pText = null) + { + $this->_richTextElements[] = $pText; + return $this; + } + + /** + * Create text + * + * @param string $pText Text + * @return PHPExcel_RichText_TextElement + * @throws PHPExcel_Exception + */ + public function createText($pText = '') + { + $objText = new PHPExcel_RichText_TextElement($pText); + $this->addText($objText); + return $objText; + } + + /** + * Create text run + * + * @param string $pText Text + * @return PHPExcel_RichText_Run + * @throws PHPExcel_Exception + */ + public function createTextRun($pText = '') + { + $objText = new PHPExcel_RichText_Run($pText); + $this->addText($objText); + return $objText; + } + + /** + * Get plain text + * + * @return string + */ + public function getPlainText() + { + // Return value + $returnValue = ''; + + // Loop through all PHPExcel_RichText_ITextElement + foreach ($this->_richTextElements as $text) { + $returnValue .= $text->getText(); + } + + // Return + return $returnValue; + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() + { + return $this->getPlainText(); + } + + /** + * Get Rich Text elements + * + * @return PHPExcel_RichText_ITextElement[] + */ + public function getRichTextElements() + { + return $this->_richTextElements; + } + + /** + * Set Rich Text elements + * + * @param PHPExcel_RichText_ITextElement[] $pElements Array of elements + * @throws PHPExcel_Exception + * @return PHPExcel_RichText + */ + public function setRichTextElements($pElements = null) + { + if (is_array($pElements)) { + $this->_richTextElements = $pElements; + } else { + throw new PHPExcel_Exception("Invalid PHPExcel_RichText_ITextElement[] array passed."); + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + $hashElements = ''; + foreach ($this->_richTextElements as $element) { + $hashElements .= $element->getHashCode(); + } + + return md5( + $hashElements + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php new file mode 100644 index 00000000..ec19498d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php @@ -0,0 +1,64 @@ +<?php +/** + * PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_RichText_ITextElement + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +interface PHPExcel_RichText_ITextElement +{ + /** + * Get text + * + * @return string Text + */ + public function getText(); + + /** + * Set text + * + * @param $pText string Text + * @return PHPExcel_RichText_ITextElement + */ + public function setText($pText = ''); + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont(); + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode(); +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php new file mode 100644 index 00000000..71545fc2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php @@ -0,0 +1,102 @@ +<?php +/** + * PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_RichText_Run + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_RichText_Run extends PHPExcel_RichText_TextElement implements PHPExcel_RichText_ITextElement +{ + /** + * Font + * + * @var PHPExcel_Style_Font + */ + private $_font; + + /** + * Create a new PHPExcel_RichText_Run instance + * + * @param string $pText Text + */ + public function __construct($pText = '') + { + // Initialise variables + $this->setText($pText); + $this->_font = new PHPExcel_Style_Font(); + } + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont() { + return $this->_font; + } + + /** + * Set font + * + * @param PHPExcel_Style_Font $pFont Font + * @throws PHPExcel_Exception + * @return PHPExcel_RichText_ITextElement + */ + public function setFont(PHPExcel_Style_Font $pFont = null) { + $this->_font = $pFont; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->getText() + . $this->_font->getHashCode() + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php new file mode 100644 index 00000000..3593c6e1 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php @@ -0,0 +1,108 @@ +<?php +/** + * PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_RichText_TextElement + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_RichText_TextElement implements PHPExcel_RichText_ITextElement +{ + /** + * Text + * + * @var string + */ + private $_text; + + /** + * Create a new PHPExcel_RichText_TextElement instance + * + * @param string $pText Text + */ + public function __construct($pText = '') + { + // Initialise variables + $this->_text = $pText; + } + + /** + * Get text + * + * @return string Text + */ + public function getText() { + return $this->_text; + } + + /** + * Set text + * + * @param $pText string Text + * @return PHPExcel_RichText_ITextElement + */ + public function setText($pText = '') { + $this->_text = $pText; + return $this; + } + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont() { + return null; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_text + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php new file mode 100644 index 00000000..b8996132 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php @@ -0,0 +1,387 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Settings + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + + +class PHPExcel_Settings +{ + /** constants */ + /** Available Zip library classes */ + const PCLZIP = 'PHPExcel_Shared_ZipArchive'; + const ZIPARCHIVE = 'ZipArchive'; + + /** Optional Chart Rendering libraries */ + const CHART_RENDERER_JPGRAPH = 'jpgraph'; + + /** Optional PDF Rendering libraries */ + const PDF_RENDERER_TCPDF = 'tcPDF'; + const PDF_RENDERER_DOMPDF = 'DomPDF'; + const PDF_RENDERER_MPDF = 'mPDF'; + + + private static $_chartRenderers = array( + self::CHART_RENDERER_JPGRAPH, + ); + + private static $_pdfRenderers = array( + self::PDF_RENDERER_TCPDF, + self::PDF_RENDERER_DOMPDF, + self::PDF_RENDERER_MPDF, + ); + + + /** + * Name of the class used for Zip file management + * e.g. + * ZipArchive + * + * @var string + */ + private static $_zipClass = self::ZIPARCHIVE; + + + /** + * Name of the external Library used for rendering charts + * e.g. + * jpgraph + * + * @var string + */ + private static $_chartRendererName = NULL; + + /** + * Directory Path to the external Library used for rendering charts + * + * @var string + */ + private static $_chartRendererPath = NULL; + + + /** + * Name of the external Library used for rendering PDF files + * e.g. + * mPDF + * + * @var string + */ + private static $_pdfRendererName = NULL; + + /** + * Directory Path to the external Library used for rendering PDF files + * + * @var string + */ + private static $_pdfRendererPath = NULL; + + /** + * Default options for libxml loader + * + * @var int + */ + private static $_libXmlLoaderOptions = null; + + /** + * Set the Zip handler Class that PHPExcel should use for Zip file management (PCLZip or ZipArchive) + * + * @param string $zipClass The Zip handler class that PHPExcel should use for Zip file management + * e.g. PHPExcel_Settings::PCLZip or PHPExcel_Settings::ZipArchive + * @return boolean Success or failure + */ + public static function setZipClass($zipClass) + { + if (($zipClass === self::PCLZIP) || + ($zipClass === self::ZIPARCHIVE)) { + self::$_zipClass = $zipClass; + return TRUE; + } + return FALSE; + } // function setZipClass() + + + /** + * Return the name of the Zip handler Class that PHPExcel is configured to use (PCLZip or ZipArchive) + * or Zip file management + * + * @return string Name of the Zip handler Class that PHPExcel is configured to use + * for Zip file management + * e.g. PHPExcel_Settings::PCLZip or PHPExcel_Settings::ZipArchive + */ + public static function getZipClass() + { + return self::$_zipClass; + } // function getZipClass() + + + /** + * Return the name of the method that is currently configured for cell cacheing + * + * @return string Name of the cacheing method + */ + public static function getCacheStorageMethod() + { + return PHPExcel_CachedObjectStorageFactory::getCacheStorageMethod(); + } // function getCacheStorageMethod() + + + /** + * Return the name of the class that is currently being used for cell cacheing + * + * @return string Name of the class currently being used for cacheing + */ + public static function getCacheStorageClass() + { + return PHPExcel_CachedObjectStorageFactory::getCacheStorageClass(); + } // function getCacheStorageClass() + + + /** + * Set the method that should be used for cell cacheing + * + * @param string $method Name of the cacheing method + * @param array $arguments Optional configuration arguments for the cacheing method + * @return boolean Success or failure + */ + public static function setCacheStorageMethod( + $method = PHPExcel_CachedObjectStorageFactory::cache_in_memory, + $arguments = array() + ) + { + return PHPExcel_CachedObjectStorageFactory::initialize($method, $arguments); + } // function setCacheStorageMethod() + + + /** + * Set the locale code to use for formula translations and any special formatting + * + * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") + * @return boolean Success or failure + */ + public static function setLocale($locale='en_us') + { + return PHPExcel_Calculation::getInstance()->setLocale($locale); + } // function setLocale() + + + /** + * Set details of the external library that PHPExcel should use for rendering charts + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + * @param string $libraryBaseDir Directory path to the library's base folder + * + * @return boolean Success or failure + */ + public static function setChartRenderer($libraryName, $libraryBaseDir) + { + if (!self::setChartRendererName($libraryName)) + return FALSE; + return self::setChartRendererPath($libraryBaseDir); + } // function setChartRenderer() + + + /** + * Identify to PHPExcel the external library to use for rendering charts + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + * + * @return boolean Success or failure + */ + public static function setChartRendererName($libraryName) + { + if (!in_array($libraryName,self::$_chartRenderers)) { + return FALSE; + } + + self::$_chartRendererName = $libraryName; + + return TRUE; + } // function setChartRendererName() + + + /** + * Tell PHPExcel where to find the external library to use for rendering charts + * + * @param string $libraryBaseDir Directory path to the library's base folder + * @return boolean Success or failure + */ + public static function setChartRendererPath($libraryBaseDir) + { + if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) { + return FALSE; + } + self::$_chartRendererPath = $libraryBaseDir; + + return TRUE; + } // function setChartRendererPath() + + + /** + * Return the Chart Rendering Library that PHPExcel is currently configured to use (e.g. jpgraph) + * + * @return string|NULL Internal reference name of the Chart Rendering Library that PHPExcel is + * currently configured to use + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + */ + public static function getChartRendererName() + { + return self::$_chartRendererName; + } // function getChartRendererName() + + + /** + * Return the directory path to the Chart Rendering Library that PHPExcel is currently configured to use + * + * @return string|NULL Directory Path to the Chart Rendering Library that PHPExcel is + * currently configured to use + */ + public static function getChartRendererPath() + { + return self::$_chartRendererPath; + } // function getChartRendererPath() + + + /** + * Set details of the external library that PHPExcel should use for rendering PDF files + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + * @param string $libraryBaseDir Directory path to the library's base folder + * + * @return boolean Success or failure + */ + public static function setPdfRenderer($libraryName, $libraryBaseDir) + { + if (!self::setPdfRendererName($libraryName)) + return FALSE; + return self::setPdfRendererPath($libraryBaseDir); + } // function setPdfRenderer() + + + /** + * Identify to PHPExcel the external library to use for rendering PDF files + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + * + * @return boolean Success or failure + */ + public static function setPdfRendererName($libraryName) + { + if (!in_array($libraryName,self::$_pdfRenderers)) { + return FALSE; + } + + self::$_pdfRendererName = $libraryName; + + return TRUE; + } // function setPdfRendererName() + + + /** + * Tell PHPExcel where to find the external library to use for rendering PDF files + * + * @param string $libraryBaseDir Directory path to the library's base folder + * @return boolean Success or failure + */ + public static function setPdfRendererPath($libraryBaseDir) + { + if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) { + return FALSE; + } + self::$_pdfRendererPath = $libraryBaseDir; + + return TRUE; + } // function setPdfRendererPath() + + + /** + * Return the PDF Rendering Library that PHPExcel is currently configured to use (e.g. dompdf) + * + * @return string|NULL Internal reference name of the PDF Rendering Library that PHPExcel is + * currently configured to use + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + */ + public static function getPdfRendererName() + { + return self::$_pdfRendererName; + } // function getPdfRendererName() + + /** + * Return the directory path to the PDF Rendering Library that PHPExcel is currently configured to use + * + * @return string|NULL Directory Path to the PDF Rendering Library that PHPExcel is + * currently configured to use + */ + public static function getPdfRendererPath() + { + return self::$_pdfRendererPath; + } // function getPdfRendererPath() + + /** + * Set default options for libxml loader + * + * @param int $options Default options for libxml loader + */ + public static function setLibXmlLoaderOptions($options = null) + { + if (is_null($options)) { + $options = LIBXML_DTDLOAD | LIBXML_DTDATTR; + } + @libxml_disable_entity_loader($options == (LIBXML_DTDLOAD | LIBXML_DTDATTR)); + self::$_libXmlLoaderOptions = $options; + } // function setLibXmlLoaderOptions + + /** + * Get default options for libxml loader. + * Defaults to LIBXML_DTDLOAD | LIBXML_DTDATTR when not set explicitly. + * + * @return int Default options for libxml loader + */ + public static function getLibXmlLoaderOptions() + { + if (is_null(self::$_libXmlLoaderOptions)) { + self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); + } + @libxml_disable_entity_loader($options == (LIBXML_DTDLOAD | LIBXML_DTDATTR)); + return self::$_libXmlLoaderOptions; + } // function getLibXmlLoaderOptions +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php new file mode 100644 index 00000000..2807ab37 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php @@ -0,0 +1,102 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_CodePage + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_CodePage +{ + /** + * Convert Microsoft Code Page Identifier to Code Page Name which iconv + * and mbstring understands + * + * @param integer $codePage Microsoft Code Page Indentifier + * @return string Code Page Name + * @throws PHPExcel_Exception + */ + public static function NumberToName($codePage = 1252) + { + switch ($codePage) { + case 367: return 'ASCII'; break; // ASCII + case 437: return 'CP437'; break; // OEM US + case 720: throw new PHPExcel_Exception('Code page 720 not supported.'); + break; // OEM Arabic + case 737: return 'CP737'; break; // OEM Greek + case 775: return 'CP775'; break; // OEM Baltic + case 850: return 'CP850'; break; // OEM Latin I + case 852: return 'CP852'; break; // OEM Latin II (Central European) + case 855: return 'CP855'; break; // OEM Cyrillic + case 857: return 'CP857'; break; // OEM Turkish + case 858: return 'CP858'; break; // OEM Multilingual Latin I with Euro + case 860: return 'CP860'; break; // OEM Portugese + case 861: return 'CP861'; break; // OEM Icelandic + case 862: return 'CP862'; break; // OEM Hebrew + case 863: return 'CP863'; break; // OEM Canadian (French) + case 864: return 'CP864'; break; // OEM Arabic + case 865: return 'CP865'; break; // OEM Nordic + case 866: return 'CP866'; break; // OEM Cyrillic (Russian) + case 869: return 'CP869'; break; // OEM Greek (Modern) + case 874: return 'CP874'; break; // ANSI Thai + case 932: return 'CP932'; break; // ANSI Japanese Shift-JIS + case 936: return 'CP936'; break; // ANSI Chinese Simplified GBK + case 949: return 'CP949'; break; // ANSI Korean (Wansung) + case 950: return 'CP950'; break; // ANSI Chinese Traditional BIG5 + case 1200: return 'UTF-16LE'; break; // UTF-16 (BIFF8) + case 1250: return 'CP1250'; break; // ANSI Latin II (Central European) + case 1251: return 'CP1251'; break; // ANSI Cyrillic + case 0: // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program + case 1252: return 'CP1252'; break; // ANSI Latin I (BIFF4-BIFF7) + case 1253: return 'CP1253'; break; // ANSI Greek + case 1254: return 'CP1254'; break; // ANSI Turkish + case 1255: return 'CP1255'; break; // ANSI Hebrew + case 1256: return 'CP1256'; break; // ANSI Arabic + case 1257: return 'CP1257'; break; // ANSI Baltic + case 1258: return 'CP1258'; break; // ANSI Vietnamese + case 1361: return 'CP1361'; break; // ANSI Korean (Johab) + case 10000: return 'MAC'; break; // Apple Roman + case 10006: return 'MACGREEK'; break; // Macintosh Greek + case 10007: return 'MACCYRILLIC'; break; // Macintosh Cyrillic + case 10008: return 'CP936'; break; // Macintosh - Simplified Chinese (GB 2312) + case 10029: return 'MACCENTRALEUROPE'; break; // Macintosh Central Europe + case 10079: return 'MACICELAND'; break; // Macintosh Icelandic + case 10081: return 'MACTURKISH'; break; // Macintosh Turkish + case 32768: return 'MAC'; break; // Apple Roman + case 32769: throw new PHPExcel_Exception('Code page 32769 not supported.'); + break; // ANSI Latin I (BIFF2-BIFF3) + case 65000: return 'UTF-7'; break; // Unicode (UTF-7) + case 65001: return 'UTF-8'; break; // Unicode (UTF-8) + } + + throw new PHPExcel_Exception('Unknown codepage: ' . $codePage); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php new file mode 100644 index 00000000..7fe4f420 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php @@ -0,0 +1,393 @@ +<?php + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_Date + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Date +{ + /** constants */ + const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0 + const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0 + + /* + * Names of the months of the year, indexed by shortname + * Planned usage for locale settings + * + * @public + * @var string[] + */ + public static $_monthNames = array( 'Jan' => 'January', + 'Feb' => 'February', + 'Mar' => 'March', + 'Apr' => 'April', + 'May' => 'May', + 'Jun' => 'June', + 'Jul' => 'July', + 'Aug' => 'August', + 'Sep' => 'September', + 'Oct' => 'October', + 'Nov' => 'November', + 'Dec' => 'December', + ); + + /* + * Names of the months of the year, indexed by shortname + * Planned usage for locale settings + * + * @public + * @var string[] + */ + public static $_numberSuffixes = array( 'st', + 'nd', + 'rd', + 'th', + ); + + /* + * Base calendar year to use for calculations + * + * @private + * @var int + */ + protected static $_excelBaseDate = self::CALENDAR_WINDOWS_1900; + + /** + * Set the Excel calendar (Windows 1900 or Mac 1904) + * + * @param integer $baseDate Excel base date (1900 or 1904) + * @return boolean Success or failure + */ + public static function setExcelCalendar($baseDate) { + if (($baseDate == self::CALENDAR_WINDOWS_1900) || + ($baseDate == self::CALENDAR_MAC_1904)) { + self::$_excelBaseDate = $baseDate; + return TRUE; + } + return FALSE; + } // function setExcelCalendar() + + + /** + * Return the Excel calendar (Windows 1900 or Mac 1904) + * + * @return integer Excel base date (1900 or 1904) + */ + public static function getExcelCalendar() { + return self::$_excelBaseDate; + } // function getExcelCalendar() + + + /** + * Convert a date from Excel to PHP + * + * @param long $dateValue Excel date/time value + * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as + * a UST timestamp, or adjusted to UST + * @param string $timezone The timezone for finding the adjustment from UST + * @return long PHP serialized date/time + */ + public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { + if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { + $my_excelBaseDate = 25569; + // Adjust for the spurious 29-Feb-1900 (Day 60) + if ($dateValue < 60) { + --$my_excelBaseDate; + } + } else { + $my_excelBaseDate = 24107; + } + + // Perform conversion + if ($dateValue >= 1) { + $utcDays = $dateValue - $my_excelBaseDate; + $returnValue = round($utcDays * 86400); + if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) { + $returnValue = (integer) $returnValue; + } + } else { + $hours = round($dateValue * 24); + $mins = round($dateValue * 1440) - round($hours * 60); + $secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60); + $returnValue = (integer) gmmktime($hours, $mins, $secs); + } + + $timezoneAdjustment = ($adjustToTimezone) ? + PHPExcel_Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) : + 0; + + // Return + return $returnValue + $timezoneAdjustment; + } // function ExcelToPHP() + + + /** + * Convert a date from Excel to a PHP Date/Time object + * + * @param integer $dateValue Excel date/time value + * @return integer PHP date/time object + */ + public static function ExcelToPHPObject($dateValue = 0) { + $dateTime = self::ExcelToPHP($dateValue); + $days = floor($dateTime / 86400); + $time = round((($dateTime / 86400) - $days) * 86400); + $hours = round($time / 3600); + $minutes = round($time / 60) - ($hours * 60); + $seconds = round($time) - ($hours * 3600) - ($minutes * 60); + + $dateObj = date_create('1-Jan-1970+'.$days.' days'); + $dateObj->setTime($hours,$minutes,$seconds); + + return $dateObj; + } // function ExcelToPHPObject() + + + /** + * Convert a date from PHP to Excel + * + * @param mixed $dateValue PHP serialized date/time or date object + * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as + * a UST timestamp, or adjusted to UST + * @param string $timezone The timezone for finding the adjustment from UST + * @return mixed Excel date/time value + * or boolean FALSE on failure + */ + public static function PHPToExcel($dateValue = 0, $adjustToTimezone = FALSE, $timezone = NULL) { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $retValue = FALSE; + if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) { + $retValue = self::FormattedPHPToExcel( $dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'), + $dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s') + ); + } elseif (is_numeric($dateValue)) { + $retValue = self::FormattedPHPToExcel( date('Y',$dateValue), date('m',$dateValue), date('d',$dateValue), + date('H',$dateValue), date('i',$dateValue), date('s',$dateValue) + ); + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } // function PHPToExcel() + + + /** + * FormattedPHPToExcel + * + * @param long $year + * @param long $month + * @param long $day + * @param long $hours + * @param long $minutes + * @param long $seconds + * @return long Excel date/time value + */ + public static function FormattedPHPToExcel($year, $month, $day, $hours=0, $minutes=0, $seconds=0) { + if (self::$_excelBaseDate == self::CALENDAR_WINDOWS_1900) { + // + // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel + // This affects every date following 28th February 1900 + // + $excel1900isLeapYear = TRUE; + if (($year == 1900) && ($month <= 2)) { $excel1900isLeapYear = FALSE; } + $my_excelBaseDate = 2415020; + } else { + $my_excelBaseDate = 2416481; + $excel1900isLeapYear = FALSE; + } + + // Julian base date Adjustment + if ($month > 2) { + $month -= 3; + } else { + $month += 9; + --$year; + } + + // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) + $century = substr($year,0,2); + $decade = substr($year,2,2); + $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $my_excelBaseDate + $excel1900isLeapYear; + + $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; + + return (float) $excelDate + $excelTime; + } // function FormattedPHPToExcel() + + + /** + * Is a given cell a date/time? + * + * @param PHPExcel_Cell $pCell + * @return boolean + */ + public static function isDateTime(PHPExcel_Cell $pCell) { + return self::isDateTimeFormat( + $pCell->getWorksheet()->getStyle( + $pCell->getCoordinate() + )->getNumberFormat() + ); + } // function isDateTime() + + + /** + * Is a given number format a date/time? + * + * @param PHPExcel_Style_NumberFormat $pFormat + * @return boolean + */ + public static function isDateTimeFormat(PHPExcel_Style_NumberFormat $pFormat) { + return self::isDateTimeFormatCode($pFormat->getFormatCode()); + } // function isDateTimeFormat() + + + private static $possibleDateFormatCharacters = 'eymdHs'; + + /** + * Is a given number format code a date/time? + * + * @param string $pFormatCode + * @return boolean + */ + public static function isDateTimeFormatCode($pFormatCode = '') { + if (strtolower($pFormatCode) === strtolower(PHPExcel_Style_NumberFormat::FORMAT_GENERAL)) + // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) + return FALSE; + if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) + // Scientific format + return FALSE; + // Switch on formatcode + switch ($pFormatCode) { + // Explicitly defined date formats + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22: + return TRUE; + } + + // Typically number, currency or accounting (or occasionally fraction) formats + if ((substr($pFormatCode,0,1) == '_') || (substr($pFormatCode,0,2) == '0 ')) { + return FALSE; + } + // Try checking for any of the date formatting characters that don't appear within square braces + if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$pFormatCode)) { + // We might also have a format mask containing quoted strings... + // we don't want to test for any of our characters within the quoted blocks + if (strpos($pFormatCode,'"') !== FALSE) { + $segMatcher = FALSE; + foreach(explode('"',$pFormatCode) as $subVal) { + // Only test in alternate array entries (the non-quoted blocks) + if (($segMatcher = !$segMatcher) && + (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i',$subVal))) { + return TRUE; + } + } + return FALSE; + } + return TRUE; + } + + // No date... + return FALSE; + } // function isDateTimeFormatCode() + + + /** + * Convert a date/time string to Excel time + * + * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' + * @return float|FALSE Excel date/time serial value + */ + public static function stringToExcel($dateValue = '') { + if (strlen($dateValue) < 2) + return FALSE; + if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) + return FALSE; + + $dateValueNew = PHPExcel_Calculation_DateTime::DATEVALUE($dateValue); + + if ($dateValueNew === PHPExcel_Calculation_Functions::VALUE()) { + return FALSE; + } else { + if (strpos($dateValue, ':') !== FALSE) { + $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($dateValue); + if ($timeValue === PHPExcel_Calculation_Functions::VALUE()) { + return FALSE; + } + $dateValueNew += $timeValue; + } + return $dateValueNew; + } + + + } + + public static function monthStringToNumber($month) { + $monthIndex = 1; + foreach(self::$_monthNames as $shortMonthName => $longMonthName) { + if (($month === $longMonthName) || ($month === $shortMonthName)) { + return $monthIndex; + } + ++$monthIndex; + } + return $month; + } + + public static function dayStringToNumber($day) { + $strippedDayValue = (str_replace(self::$_numberSuffixes,'',$day)); + if (is_numeric($strippedDayValue)) { + return $strippedDayValue; + } + return $day; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php new file mode 100644 index 00000000..1d7af16b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php @@ -0,0 +1,272 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_Drawing + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Drawing +{ + /** + * Convert pixels to EMU + * + * @param int $pValue Value in pixels + * @return int Value in EMU + */ + public static function pixelsToEMU($pValue = 0) { + return round($pValue * 9525); + } + + /** + * Convert EMU to pixels + * + * @param int $pValue Value in EMU + * @return int Value in pixels + */ + public static function EMUToPixels($pValue = 0) { + if ($pValue != 0) { + return round($pValue / 9525); + } else { + return 0; + } + } + + /** + * Convert pixels to column width. Exact algorithm not known. + * By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875 + * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. + * + * @param int $pValue Value in pixels + * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook + * @return int Value in cell dimension + */ + public static function pixelsToCellDimension($pValue = 0, PHPExcel_Style_Font $pDefaultFont) { + // Font name and size + $name = $pDefaultFont->getName(); + $size = $pDefaultFont->getSize(); + + if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { + // Exact width can be determined + $colWidth = $pValue + * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width'] + / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px']; + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $colWidth = $pValue * 11 + * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] + / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; + } + + return $colWidth; + } + + /** + * Convert column width from (intrinsic) Excel units to pixels + * + * @param float $pValue Value in cell dimension + * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook + * @return int Value in pixels + */ + public static function cellDimensionToPixels($pValue = 0, PHPExcel_Style_Font $pDefaultFont) { + // Font name and size + $name = $pDefaultFont->getName(); + $size = $pDefaultFont->getSize(); + + if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { + // Exact width can be determined + $colWidth = $pValue + * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px'] + / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width']; + + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $colWidth = $pValue * $size + * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] + / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; + } + + // Round pixels to closest integer + $colWidth = (int) round($colWidth); + + return $colWidth; + } + + /** + * Convert pixels to points + * + * @param int $pValue Value in pixels + * @return int Value in points + */ + public static function pixelsToPoints($pValue = 0) { + return $pValue * 0.67777777; + } + + /** + * Convert points to pixels + * + * @param int $pValue Value in points + * @return int Value in pixels + */ + public static function pointsToPixels($pValue = 0) { + if ($pValue != 0) { + return (int) ceil($pValue * 1.333333333); + } else { + return 0; + } + } + + /** + * Convert degrees to angle + * + * @param int $pValue Degrees + * @return int Angle + */ + public static function degreesToAngle($pValue = 0) { + return (int)round($pValue * 60000); + } + + /** + * Convert angle to degrees + * + * @param int $pValue Angle + * @return int Degrees + */ + public static function angleToDegrees($pValue = 0) { + if ($pValue != 0) { + return round($pValue / 60000); + } else { + return 0; + } + } + + /** + * Create a new image from file. By alexander at alexauto dot nl + * + * @link http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 + * @param string $filename Path to Windows DIB (BMP) image + * @return resource + */ + public static function imagecreatefrombmp($p_sFile) + { + // Load the image into a string + $file = fopen($p_sFile,"rb"); + $read = fread($file,10); + while(!feof($file)&&($read<>"")) + $read .= fread($file,1024); + + $temp = unpack("H*",$read); + $hex = $temp[1]; + $header = substr($hex,0,108); + + // Process the header + // Structure: http://www.fastgraph.com/help/bmp_header_format.html + if (substr($header,0,4)=="424d") + { + // Cut it in parts of 2 bytes + $header_parts = str_split($header,2); + + // Get the width 4 bytes + $width = hexdec($header_parts[19].$header_parts[18]); + + // Get the height 4 bytes + $height = hexdec($header_parts[23].$header_parts[22]); + + // Unset the header params + unset($header_parts); + } + + // Define starting X and Y + $x = 0; + $y = 1; + + // Create newimage + $image = imagecreatetruecolor($width,$height); + + // Grab the body from the image + $body = substr($hex,108); + + // Calculate if padding at the end-line is needed + // Divided by two to keep overview. + // 1 byte = 2 HEX-chars + $body_size = (strlen($body)/2); + $header_size = ($width*$height); + + // Use end-line padding? Only when needed + $usePadding = ($body_size>($header_size*3)+4); + + // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption + // Calculate the next DWORD-position in the body + for ($i=0;$i<$body_size;$i+=3) + { + // Calculate line-ending and padding + if ($x>=$width) + { + // If padding needed, ignore image-padding + // Shift i to the ending of the current 32-bit-block + if ($usePadding) + $i += $width%4; + + // Reset horizontal position + $x = 0; + + // Raise the height-position (bottom-up) + $y++; + + // Reached the image-height? Break the for-loop + if ($y>$height) + break; + } + + // Calculation of the RGB-pixel (defined as BGR in image-data) + // Define $i_pos as absolute position in the body + $i_pos = $i*2; + $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); + $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); + $b = hexdec($body[$i_pos].$body[$i_pos+1]); + + // Calculate and draw the pixel + $color = imagecolorallocate($image,$r,$g,$b); + imagesetpixel($image,$x,$height-$y,$color); + + // Raise the horizontal position + $x++; + } + + // Unset the body / free the memory + unset($body); + + // Return image-object + return $image; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php new file mode 100644 index 00000000..983cbdaa --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php @@ -0,0 +1,91 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher +{ + /** + * Drawing Group Container + * + * @var PHPExcel_Shared_Escher_DggContainer + */ + private $_dggContainer; + + /** + * Drawing Container + * + * @var PHPExcel_Shared_Escher_DgContainer + */ + private $_dgContainer; + + /** + * Get Drawing Group Container + * + * @return PHPExcel_Shared_Escher_DgContainer + */ + public function getDggContainer() + { + return $this->_dggContainer; + } + + /** + * Set Drawing Group Container + * + * @param PHPExcel_Shared_Escher_DggContainer $dggContainer + */ + public function setDggContainer($dggContainer) + { + return $this->_dggContainer = $dggContainer; + } + + /** + * Get Drawing Container + * + * @return PHPExcel_Shared_Escher_DgContainer + */ + public function getDgContainer() + { + return $this->_dgContainer; + } + + /** + * Set Drawing Container + * + * @param PHPExcel_Shared_Escher_DgContainer $dgContainer + */ + public function setDgContainer($dgContainer) + { + return $this->_dgContainer = $dgContainer; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php new file mode 100644 index 00000000..3ec564c5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php @@ -0,0 +1,83 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DgContainer + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DgContainer +{ + /** + * Drawing index, 1-based. + * + * @var int + */ + private $_dgId; + + /** + * Last shape index in this drawing + * + * @var int + */ + private $_lastSpId; + + private $_spgrContainer = null; + + public function getDgId() + { + return $this->_dgId; + } + + public function setDgId($value) + { + $this->_dgId = $value; + } + + public function getLastSpId() + { + return $this->_lastSpId; + } + + public function setLastSpId($value) + { + $this->_lastSpId = $value; + } + + public function getSpgrContainer() + { + return $this->_spgrContainer; + } + + public function setSpgrContainer($spgrContainer) + { + return $this->_spgrContainer = $spgrContainer; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php new file mode 100644 index 00000000..651eaf0e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php @@ -0,0 +1,109 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DgContainer_SpgrContainer + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DgContainer_SpgrContainer +{ + /** + * Parent Shape Group Container + * + * @var PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + private $_parent; + + /** + * Shape Container collection + * + * @var array + */ + private $_children = array(); + + /** + * Set parent Shape Group Container + * + * @param PHPExcel_Shared_Escher_DgContainer_SpgrContainer $parent + */ + public function setParent($parent) + { + $this->_parent = $parent; + } + + /** + * Get the parent Shape Group Container if any + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer|null + */ + public function getParent() + { + return $this->_parent; + } + + /** + * Add a child. This will be either spgrContainer or spContainer + * + * @param mixed $child + */ + public function addChild($child) + { + $this->_children[] = $child; + $child->setParent($this); + } + + /** + * Get collection of Shape Containers + */ + public function getChildren() + { + return $this->_children; + } + + /** + * Recursively get all spContainers within this spgrContainer + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer[] + */ + public function getAllSpContainers() + { + $allSpContainers = array(); + + foreach ($this->_children as $child) { + if ($child instanceof PHPExcel_Shared_Escher_DgContainer_SpgrContainer) { + $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); + } else { + $allSpContainers[] = $child; + } + } + + return $allSpContainers; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php new file mode 100644 index 00000000..dde11540 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php @@ -0,0 +1,395 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer +{ + /** + * Parent Shape Group Container + * + * @var PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + private $_parent; + + /** + * Is this a group shape? + * + * @var boolean + */ + private $_spgr = false; + + /** + * Shape type + * + * @var int + */ + private $_spType; + + /** + * Shape flag + * + * @var int + */ + private $_spFlag; + + /** + * Shape index (usually group shape has index 0, and the rest: 1,2,3...) + * + * @var boolean + */ + private $_spId; + + /** + * Array of options + * + * @var array + */ + private $_OPT; + + /** + * Cell coordinates of upper-left corner of shape, e.g. 'A1' + * + * @var string + */ + private $_startCoordinates; + + /** + * Horizontal offset of upper-left corner of shape measured in 1/1024 of column width + * + * @var int + */ + private $_startOffsetX; + + /** + * Vertical offset of upper-left corner of shape measured in 1/256 of row height + * + * @var int + */ + private $_startOffsetY; + + /** + * Cell coordinates of bottom-right corner of shape, e.g. 'B2' + * + * @var string + */ + private $_endCoordinates; + + /** + * Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width + * + * @var int + */ + private $_endOffsetX; + + /** + * Vertical offset of bottom-right corner of shape measured in 1/256 of row height + * + * @var int + */ + private $_endOffsetY; + + /** + * Set parent Shape Group Container + * + * @param PHPExcel_Shared_Escher_DgContainer_SpgrContainer $parent + */ + public function setParent($parent) + { + $this->_parent = $parent; + } + + /** + * Get the parent Shape Group Container + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + public function getParent() + { + return $this->_parent; + } + + /** + * Set whether this is a group shape + * + * @param boolean $value + */ + public function setSpgr($value = false) + { + $this->_spgr = $value; + } + + /** + * Get whether this is a group shape + * + * @return boolean + */ + public function getSpgr() + { + return $this->_spgr; + } + + /** + * Set the shape type + * + * @param int $value + */ + public function setSpType($value) + { + $this->_spType = $value; + } + + /** + * Get the shape type + * + * @return int + */ + public function getSpType() + { + return $this->_spType; + } + + /** + * Set the shape flag + * + * @param int $value + */ + public function setSpFlag($value) + { + $this->_spFlag = $value; + } + + /** + * Get the shape flag + * + * @return int + */ + public function getSpFlag() + { + return $this->_spFlag; + } + + /** + * Set the shape index + * + * @param int $value + */ + public function setSpId($value) + { + $this->_spId = $value; + } + + /** + * Get the shape index + * + * @return int + */ + public function getSpId() + { + return $this->_spId; + } + + /** + * Set an option for the Shape Group Container + * + * @param int $property The number specifies the option + * @param mixed $value + */ + public function setOPT($property, $value) + { + $this->_OPT[$property] = $value; + } + + /** + * Get an option for the Shape Group Container + * + * @param int $property The number specifies the option + * @return mixed + */ + public function getOPT($property) + { + if (isset($this->_OPT[$property])) { + return $this->_OPT[$property]; + } + return null; + } + + /** + * Get the collection of options + * + * @return array + */ + public function getOPTCollection() + { + return $this->_OPT; + } + + /** + * Set cell coordinates of upper-left corner of shape + * + * @param string $value + */ + public function setStartCoordinates($value = 'A1') + { + $this->_startCoordinates = $value; + } + + /** + * Get cell coordinates of upper-left corner of shape + * + * @return string + */ + public function getStartCoordinates() + { + return $this->_startCoordinates; + } + + /** + * Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width + * + * @param int $startOffsetX + */ + public function setStartOffsetX($startOffsetX = 0) + { + $this->_startOffsetX = $startOffsetX; + } + + /** + * Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width + * + * @return int + */ + public function getStartOffsetX() + { + return $this->_startOffsetX; + } + + /** + * Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height + * + * @param int $startOffsetY + */ + public function setStartOffsetY($startOffsetY = 0) + { + $this->_startOffsetY = $startOffsetY; + } + + /** + * Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height + * + * @return int + */ + public function getStartOffsetY() + { + return $this->_startOffsetY; + } + + /** + * Set cell coordinates of bottom-right corner of shape + * + * @param string $value + */ + public function setEndCoordinates($value = 'A1') + { + $this->_endCoordinates = $value; + } + + /** + * Get cell coordinates of bottom-right corner of shape + * + * @return string + */ + public function getEndCoordinates() + { + return $this->_endCoordinates; + } + + /** + * Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width + * + * @param int $startOffsetX + */ + public function setEndOffsetX($endOffsetX = 0) + { + $this->_endOffsetX = $endOffsetX; + } + + /** + * Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width + * + * @return int + */ + public function getEndOffsetX() + { + return $this->_endOffsetX; + } + + /** + * Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height + * + * @param int $endOffsetY + */ + public function setEndOffsetY($endOffsetY = 0) + { + $this->_endOffsetY = $endOffsetY; + } + + /** + * Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height + * + * @return int + */ + public function getEndOffsetY() + { + return $this->_endOffsetY; + } + + /** + * Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and + * the dgContainer. A value of 1 = immediately within first spgrContainer + * Higher nesting level occurs if and only if spContainer is part of a shape group + * + * @return int Nesting level + */ + public function getNestingLevel() + { + $nestingLevel = 0; + + $parent = $this->getParent(); + while ($parent instanceof PHPExcel_Shared_Escher_DgContainer_SpgrContainer) { + ++$nestingLevel; + $parent = $parent->getParent(); + } + + return $nestingLevel; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php new file mode 100644 index 00000000..bf5f61f2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php @@ -0,0 +1,203 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DggContainer + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DggContainer +{ + /** + * Maximum shape index of all shapes in all drawings increased by one + * + * @var int + */ + private $_spIdMax; + + /** + * Total number of drawings saved + * + * @var int + */ + private $_cDgSaved; + + /** + * Total number of shapes saved (including group shapes) + * + * @var int + */ + private $_cSpSaved; + + /** + * BLIP Store Container + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + private $_bstoreContainer; + + /** + * Array of options for the drawing group + * + * @var array + */ + private $_OPT = array(); + + /** + * Array of identifier clusters containg information about the maximum shape identifiers + * + * @var array + */ + private $_IDCLs = array(); + + /** + * Get maximum shape index of all shapes in all drawings (plus one) + * + * @return int + */ + public function getSpIdMax() + { + return $this->_spIdMax; + } + + /** + * Set maximum shape index of all shapes in all drawings (plus one) + * + * @param int + */ + public function setSpIdMax($value) + { + $this->_spIdMax = $value; + } + + /** + * Get total number of drawings saved + * + * @return int + */ + public function getCDgSaved() + { + return $this->_cDgSaved; + } + + /** + * Set total number of drawings saved + * + * @param int + */ + public function setCDgSaved($value) + { + $this->_cDgSaved = $value; + } + + /** + * Get total number of shapes saved (including group shapes) + * + * @return int + */ + public function getCSpSaved() + { + return $this->_cSpSaved; + } + + /** + * Set total number of shapes saved (including group shapes) + * + * @param int + */ + public function setCSpSaved($value) + { + $this->_cSpSaved = $value; + } + + /** + * Get BLIP Store Container + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + public function getBstoreContainer() + { + return $this->_bstoreContainer; + } + + /** + * Set BLIP Store Container + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer $bstoreContainer + */ + public function setBstoreContainer($bstoreContainer) + { + $this->_bstoreContainer = $bstoreContainer; + } + + /** + * Set an option for the drawing group + * + * @param int $property The number specifies the option + * @param mixed $value + */ + public function setOPT($property, $value) + { + $this->_OPT[$property] = $value; + } + + /** + * Get an option for the drawing group + * + * @param int $property The number specifies the option + * @return mixed + */ + public function getOPT($property) + { + if (isset($this->_OPT[$property])) { + return $this->_OPT[$property]; + } + return null; + } + + /** + * Get identifier clusters + * + * @return array + */ + public function getIDCLs() + { + return $this->_IDCLs; + } + + /** + * Set identifier clusters. array(<drawingId> => <max shape id>, ...) + * + * @param array $pValue + */ + public function setIDCLs($pValue) + { + $this->_IDCLs = $pValue; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php new file mode 100644 index 00000000..d16bfc76 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php @@ -0,0 +1,65 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer +{ + /** + * BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture) + * + * @var array + */ + private $_BSECollection = array(); + + /** + * Add a BLIP Store Entry + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $BSE + */ + public function addBSE($BSE) + { + $this->_BSECollection[] = $BSE; + $BSE->setParent($this); + } + + /** + * Get the collection of BLIP Store Entries + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE[] + */ + public function getBSECollection() + { + return $this->_BSECollection; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php new file mode 100644 index 00000000..ea3c52a3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php @@ -0,0 +1,120 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE +{ + const BLIPTYPE_ERROR = 0x00; + const BLIPTYPE_UNKNOWN = 0x01; + const BLIPTYPE_EMF = 0x02; + const BLIPTYPE_WMF = 0x03; + const BLIPTYPE_PICT = 0x04; + const BLIPTYPE_JPEG = 0x05; + const BLIPTYPE_PNG = 0x06; + const BLIPTYPE_DIB = 0x07; + const BLIPTYPE_TIFF = 0x11; + const BLIPTYPE_CMYKJPEG = 0x12; + + /** + * The parent BLIP Store Entry Container + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + private $_parent; + + /** + * The BLIP (Big Large Image or Picture) + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + */ + private $_blip; + + /** + * The BLIP type + * + * @var int + */ + private $_blipType; + + /** + * Set parent BLIP Store Entry Container + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer $parent + */ + public function setParent($parent) + { + $this->_parent = $parent; + } + + /** + * Get the BLIP + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + */ + public function getBlip() + { + return $this->_blip; + } + + /** + * Set the BLIP + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip $blip + */ + public function setBlip($blip) + { + $this->_blip = $blip; + $blip->setParent($this); + } + + /** + * Get the BLIP type + * + * @return int + */ + public function getBlipType() + { + return $this->_blipType; + } + + /** + * Set the BLIP type + * + * @param int + */ + public function setBlipType($blipType) + { + $this->_blipType = $blipType; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php new file mode 100644 index 00000000..802ce6d9 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php @@ -0,0 +1,91 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip +{ + /** + * The parent BSE + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE + */ + private $_parent; + + /** + * Raw image data + * + * @var string + */ + private $_data; + + /** + * Get the raw image data + * + * @return string + */ + public function getData() + { + return $this->_data; + } + + /** + * Set the raw image data + * + * @param string + */ + public function setData($data) + { + $this->_data = $data; + } + + /** + * Set parent BSE + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $parent + */ + public function setParent($parent) + { + $this->_parent = $parent; + } + + /** + * Get parent BSE + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $parent + */ + public function getParent() + { + return $this->_parent; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php new file mode 100644 index 00000000..927dace9 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php @@ -0,0 +1,317 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_Excel5 + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Excel5 +{ + /** + * Get the width of a column in pixels. We use the relationship y = ceil(7x) where + * x is the width in intrinsic Excel units (measuring width in number of normal characters) + * This holds for Arial 10 + * + * @param PHPExcel_Worksheet $sheet The sheet + * @param string $col The column + * @return integer The width in pixels + */ + public static function sizeCol($sheet, $col = 'A') + { + // default font of the workbook + $font = $sheet->getParent()->getDefaultStyle()->getFont(); + + $columnDimensions = $sheet->getColumnDimensions(); + + // first find the true column width in pixels (uncollapsed and unhidden) + if ( isset($columnDimensions[$col]) and $columnDimensions[$col]->getWidth() != -1 ) { + + // then we have column dimension with explicit width + $columnDimension = $columnDimensions[$col]; + $width = $columnDimension->getWidth(); + $pixelWidth = PHPExcel_Shared_Drawing::cellDimensionToPixels($width, $font); + + } else if ($sheet->getDefaultColumnDimension()->getWidth() != -1) { + + // then we have default column dimension with explicit width + $defaultColumnDimension = $sheet->getDefaultColumnDimension(); + $width = $defaultColumnDimension->getWidth(); + $pixelWidth = PHPExcel_Shared_Drawing::cellDimensionToPixels($width, $font); + + } else { + + // we don't even have any default column dimension. Width depends on default font + $pixelWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($font, true); + } + + // now find the effective column width in pixels + if (isset($columnDimensions[$col]) and !$columnDimensions[$col]->getVisible()) { + $effectivePixelWidth = 0; + } else { + $effectivePixelWidth = $pixelWidth; + } + + return $effectivePixelWidth; + } + + /** + * Convert the height of a cell from user's units to pixels. By interpolation + * the relationship is: y = 4/3x. If the height hasn't been set by the user we + * use the default value. If the row is hidden we use a value of zero. + * + * @param PHPExcel_Worksheet $sheet The sheet + * @param integer $row The row index (1-based) + * @return integer The width in pixels + */ + public static function sizeRow($sheet, $row = 1) + { + // default font of the workbook + $font = $sheet->getParent()->getDefaultStyle()->getFont(); + + $rowDimensions = $sheet->getRowDimensions(); + + // first find the true row height in pixels (uncollapsed and unhidden) + if ( isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) { + + // then we have a row dimension + $rowDimension = $rowDimensions[$row]; + $rowHeight = $rowDimension->getRowHeight(); + $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 + + } else if ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { + + // then we have a default row dimension with explicit height + $defaultRowDimension = $sheet->getDefaultRowDimension(); + $rowHeight = $defaultRowDimension->getRowHeight(); + $pixelRowHeight = PHPExcel_Shared_Drawing::pointsToPixels($rowHeight); + + } else { + + // we don't even have any default row dimension. Height depends on default font + $pointRowHeight = PHPExcel_Shared_Font::getDefaultRowHeightByFont($font); + $pixelRowHeight = PHPExcel_Shared_Font::fontSizeToPixels($pointRowHeight); + + } + + // now find the effective row height in pixels + if ( isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible() ) { + $effectivePixelRowHeight = 0; + } else { + $effectivePixelRowHeight = $pixelRowHeight; + } + + return $effectivePixelRowHeight; + } + + /** + * Get the horizontal distance in pixels between two anchors + * The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets + * + * @param PHPExcel_Worksheet $sheet + * @param string $startColumn + * @param integer $startOffsetX Offset within start cell measured in 1/1024 of the cell width + * @param string $endColumn + * @param integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width + * @return integer Horizontal measured in pixels + */ + public static function getDistanceX(PHPExcel_Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) + { + $distanceX = 0; + + // add the widths of the spanning columns + $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1; // 1-based + $endColumnIndex = PHPExcel_Cell::columnIndexFromString($endColumn) - 1; // 1-based + for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { + $distanceX += self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($i)); + } + + // correct for offsetX in startcell + $distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); + + // correct for offsetX in endcell + $distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024)); + + return $distanceX; + } + + /** + * Get the vertical distance in pixels between two anchors + * The distanceY is found as sum of all the spanning rows minus two offsets + * + * @param PHPExcel_Worksheet $sheet + * @param integer $startRow (1-based) + * @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height + * @param integer $endRow (1-based) + * @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height + * @return integer Vertical distance measured in pixels + */ + public static function getDistanceY(PHPExcel_Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) + { + $distanceY = 0; + + // add the widths of the spanning rows + for ($row = $startRow; $row <= $endRow; ++$row) { + $distanceY += self::sizeRow($sheet, $row); + } + + // correct for offsetX in startcell + $distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256); + + // correct for offsetX in endcell + $distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); + + return $distanceY; + } + + /** + * Convert 1-cell anchor coordinates to 2-cell anchor coordinates + * This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications + * + * Calculate the vertices that define the position of the image as required by + * the OBJ record. + * + * +------------+------------+ + * | A | B | + * +-----+------------+------------+ + * | |(x1,y1) | | + * | 1 |(A1)._______|______ | + * | | | | | + * | | | | | + * +-----+----| BITMAP |-----+ + * | | | | | + * | 2 | |______________. | + * | | | (B2)| + * | | | (x2,y2)| + * +---- +------------+------------+ + * + * Example of a bitmap that covers some of the area from cell A1 to cell B2. + * + * Based on the width and height of the bitmap we need to calculate 8 vars: + * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. + * The width and height of the cells are also variable and have to be taken into + * account. + * The values of $col_start and $row_start are passed in from the calling + * function. The values of $col_end and $row_end are calculated by subtracting + * the width and height of the bitmap from the width and height of the + * underlying cells. + * The vertices are expressed as a percentage of the underlying cell width as + * follows (rhs values are in pixels): + * + * x1 = X / W *1024 + * y1 = Y / H *256 + * x2 = (X-1) / W *1024 + * y2 = (Y-1) / H *256 + * + * Where: X is distance from the left side of the underlying cell + * Y is distance from the top of the underlying cell + * W is the width of the cell + * H is the height of the cell + * + * @param PHPExcel_Worksheet $sheet + * @param string $coordinates E.g. 'A1' + * @param integer $offsetX Horizontal offset in pixels + * @param integer $offsetY Vertical offset in pixels + * @param integer $width Width in pixels + * @param integer $height Height in pixels + * @return array + */ + public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) + { + list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinates); + $col_start = PHPExcel_Cell::columnIndexFromString($column) - 1; + $row_start = $row - 1; + + $x1 = $offsetX; + $y1 = $offsetY; + + // Initialise end cell to the same as the start cell + $col_end = $col_start; // Col containing lower right corner of object + $row_end = $row_start; // Row containing bottom right corner of object + + // Zero the specified offset if greater than the cell dimensions + if ($x1 >= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) { + $x1 = 0; + } + if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { + $y1 = 0; + } + + $width = $width + $x1 -1; + $height = $height + $y1 -1; + + // Subtract the underlying cell widths to find the end cell of the image + while ($width >= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) { + $width -= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)); + ++$col_end; + } + + // Subtract the underlying cell heights to find the end cell of the image + while ($height >= self::sizeRow($sheet, $row_end + 1)) { + $height -= self::sizeRow($sheet, $row_end + 1); + ++$row_end; + } + + // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell + // with zero height or width. + if (self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) { + return; + } + if (self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) { + return; + } + if (self::sizeRow($sheet, $row_start + 1) == 0) { + return; + } + if (self::sizeRow($sheet, $row_end + 1) == 0) { + return; + } + + // Convert the pixel values to the percentage value expected by Excel + $x1 = $x1 / self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; + $x2 = ($width + 1) / self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object + + $startCoordinates = PHPExcel_Cell::stringFromColumnIndex($col_start) . ($row_start + 1); + $endCoordinates = PHPExcel_Cell::stringFromColumnIndex($col_end) . ($row_end + 1); + + $twoAnchor = array( + 'startCoordinates' => $startCoordinates, + 'startOffsetX' => $x1, + 'startOffsetY' => $y1, + 'endCoordinates' => $endCoordinates, + 'endOffsetX' => $x2, + 'endOffsetY' => $y2, + ); + + return $twoAnchor; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php new file mode 100644 index 00000000..70756a04 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php @@ -0,0 +1,178 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_File + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_File +{ + /* + * Use Temp or File Upload Temp for temporary files + * + * @protected + * @var boolean + */ + protected static $_useUploadTempDirectory = FALSE; + + + /** + * Set the flag indicating whether the File Upload Temp directory should be used for temporary files + * + * @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false) + */ + public static function setUseUploadTempDirectory($useUploadTempDir = FALSE) { + self::$_useUploadTempDirectory = (boolean) $useUploadTempDir; + } // function setUseUploadTempDirectory() + + + /** + * Get the flag indicating whether the File Upload Temp directory should be used for temporary files + * + * @return boolean Use File Upload Temporary directory (true or false) + */ + public static function getUseUploadTempDirectory() { + return self::$_useUploadTempDirectory; + } // function getUseUploadTempDirectory() + + + /** + * Verify if a file exists + * + * @param string $pFilename Filename + * @return bool + */ + public static function file_exists($pFilename) { + // Sick construction, but it seems that + // file_exists returns strange values when + // doing the original file_exists on ZIP archives... + if ( strtolower(substr($pFilename, 0, 3)) == 'zip' ) { + // Open ZIP file and verify if the file exists + $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); + $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); + + $zip = new ZipArchive(); + if ($zip->open($zipFile) === true) { + $returnValue = ($zip->getFromName($archiveFile) !== false); + $zip->close(); + return $returnValue; + } else { + return false; + } + } else { + // Regular file_exists + return file_exists($pFilename); + } + } + + /** + * Returns canonicalized absolute pathname, also for ZIP archives + * + * @param string $pFilename + * @return string + */ + public static function realpath($pFilename) { + // Returnvalue + $returnValue = ''; + + // Try using realpath() + if (file_exists($pFilename)) { + $returnValue = realpath($pFilename); + } + + // Found something? + if ($returnValue == '' || ($returnValue === NULL)) { + $pathArray = explode('/' , $pFilename); + while(in_array('..', $pathArray) && $pathArray[0] != '..') { + for ($i = 0; $i < count($pathArray); ++$i) { + if ($pathArray[$i] == '..' && $i > 0) { + unset($pathArray[$i]); + unset($pathArray[$i - 1]); + break; + } + } + } + $returnValue = implode('/', $pathArray); + } + + // Return + return $returnValue; + } + + /** + * Get the systems temporary directory. + * + * @return string + */ + public static function sys_get_temp_dir() + { + if (self::$_useUploadTempDirectory) { + // use upload-directory when defined to allow running on environments having very restricted + // open_basedir configs + if (ini_get('upload_tmp_dir') !== FALSE) { + if ($temp = ini_get('upload_tmp_dir')) { + if (file_exists($temp)) + return realpath($temp); + } + } + } + + // sys_get_temp_dir is only available since PHP 5.2.1 + // http://php.net/manual/en/function.sys-get-temp-dir.php#94119 + if ( !function_exists('sys_get_temp_dir')) { + if ($temp = getenv('TMP') ) { + if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + } + if ($temp = getenv('TEMP') ) { + if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + } + if ($temp = getenv('TMPDIR') ) { + if ((!empty($temp)) && (file_exists($temp))) { return realpath($temp); } + } + + // trick for creating a file in system's temporary dir + // without knowing the path of the system's temporary dir + $temp = tempnam(__FILE__, ''); + if (file_exists($temp)) { + unlink($temp); + return realpath(dirname($temp)); + } + + return null; + } + + // use ordinary built-in PHP function + // There should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only + // be called if we're running 5.2.1 or earlier + return realpath(sys_get_temp_dir()); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php new file mode 100644 index 00000000..203d4ecb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php @@ -0,0 +1,775 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_Font + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Font +{ + /* Methods for resolving autosize value */ + const AUTOSIZE_METHOD_APPROX = 'approx'; + const AUTOSIZE_METHOD_EXACT = 'exact'; + + private static $_autoSizeMethods = array( + self::AUTOSIZE_METHOD_APPROX, + self::AUTOSIZE_METHOD_EXACT, + ); + + /** Character set codes used by BIFF5-8 in Font records */ + const CHARSET_ANSI_LATIN = 0x00; + const CHARSET_SYSTEM_DEFAULT = 0x01; + const CHARSET_SYMBOL = 0x02; + const CHARSET_APPLE_ROMAN = 0x4D; + const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80; + const CHARSET_ANSI_KOREAN_HANGUL = 0x81; + const CHARSET_ANSI_KOREAN_JOHAB = 0x82; + const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312 + const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5 + const CHARSET_ANSI_GREEK = 0xA1; + const CHARSET_ANSI_TURKISH = 0xA2; + const CHARSET_ANSI_VIETNAMESE = 0xA3; + const CHARSET_ANSI_HEBREW = 0xB1; + const CHARSET_ANSI_ARABIC = 0xB2; + const CHARSET_ANSI_BALTIC = 0xBA; + const CHARSET_ANSI_CYRILLIC = 0xCC; + const CHARSET_ANSI_THAI = 0xDD; + const CHARSET_ANSI_LATIN_II = 0xEE; + const CHARSET_OEM_LATIN_I = 0xFF; + + // XXX: Constants created! + /** Font filenames */ + const ARIAL = 'arial.ttf'; + const ARIAL_BOLD = 'arialbd.ttf'; + const ARIAL_ITALIC = 'ariali.ttf'; + const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; + + const CALIBRI = 'CALIBRI.TTF'; + const CALIBRI_BOLD = 'CALIBRIB.TTF'; + const CALIBRI_ITALIC = 'CALIBRII.TTF'; + const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; + + const COMIC_SANS_MS = 'comic.ttf'; + const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; + + const COURIER_NEW = 'cour.ttf'; + const COURIER_NEW_BOLD = 'courbd.ttf'; + const COURIER_NEW_ITALIC = 'couri.ttf'; + const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf'; + + const GEORGIA = 'georgia.ttf'; + const GEORGIA_BOLD = 'georgiab.ttf'; + const GEORGIA_ITALIC = 'georgiai.ttf'; + const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf'; + + const IMPACT = 'impact.ttf'; + + const LIBERATION_SANS = 'LiberationSans-Regular.ttf'; + const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf'; + const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf'; + const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf'; + + const LUCIDA_CONSOLE = 'lucon.ttf'; + const LUCIDA_SANS_UNICODE = 'l_10646.ttf'; + + const MICROSOFT_SANS_SERIF = 'micross.ttf'; + + const PALATINO_LINOTYPE = 'pala.ttf'; + const PALATINO_LINOTYPE_BOLD = 'palab.ttf'; + const PALATINO_LINOTYPE_ITALIC = 'palai.ttf'; + const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf'; + + const SYMBOL = 'symbol.ttf'; + + const TAHOMA = 'tahoma.ttf'; + const TAHOMA_BOLD = 'tahomabd.ttf'; + + const TIMES_NEW_ROMAN = 'times.ttf'; + const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf'; + const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf'; + const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf'; + + const TREBUCHET_MS = 'trebuc.ttf'; + const TREBUCHET_MS_BOLD = 'trebucbd.ttf'; + const TREBUCHET_MS_ITALIC = 'trebucit.ttf'; + const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf'; + + const VERDANA = 'verdana.ttf'; + const VERDANA_BOLD = 'verdanab.ttf'; + const VERDANA_ITALIC = 'verdanai.ttf'; + const VERDANA_BOLD_ITALIC = 'verdanaz.ttf'; + + /** + * AutoSize method + * + * @var string + */ + private static $autoSizeMethod = self::AUTOSIZE_METHOD_APPROX; + + /** + * Path to folder containing TrueType font .ttf files + * + * @var string + */ + private static $trueTypeFontPath = null; + + /** + * How wide is a default column for a given default font and size? + * Empirical data found by inspecting real Excel files and reading off the pixel width + * in Microsoft Office Excel 2007. + * + * @var array + */ + public static $defaultColumnWidths = array( + 'Arial' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 56, 'width' => 9.33203125), + 9 => array('px' => 64, 'width' => 9.14062500), + 10 => array('px' => 64, 'width' => 9.14062500), + ), + 'Calibri' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 56, 'width' => 9.33203125), + 9 => array('px' => 56, 'width' => 9.33203125), + 10 => array('px' => 64, 'width' => 9.14062500), + 11 => array('px' => 64, 'width' => 9.14062500), + ), + 'Verdana' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 64, 'width' => 9.14062500), + 9 => array('px' => 72, 'width' => 9.00000000), + 10 => array('px' => 72, 'width' => 9.00000000), + ), + ); + + /** + * Set autoSize method + * + * @param string $pValue + * @return boolean Success or failure + */ + public static function setAutoSizeMethod($pValue = self::AUTOSIZE_METHOD_APPROX) + { + if (!in_array($pValue,self::$_autoSizeMethods)) { + return FALSE; + } + + self::$autoSizeMethod = $pValue; + + return TRUE; + } + + /** + * Get autoSize method + * + * @return string + */ + public static function getAutoSizeMethod() + { + return self::$autoSizeMethod; + } + + /** + * Set the path to the folder containing .ttf files. There should be a trailing slash. + * Typical locations on variout some platforms: + * <ul> + * <li>C:/Windows/Fonts/</li> + * <li>/usr/share/fonts/truetype/</li> + * <li>~/.fonts/</li> + * </ul> + * + * @param string $pValue + */ + public static function setTrueTypeFontPath($pValue = '') + { + self::$trueTypeFontPath = $pValue; + } + + /** + * Get the path to the folder containing .ttf files. + * + * @return string + */ + public static function getTrueTypeFontPath() + { + return self::$trueTypeFontPath; + } + + /** + * Calculate an (approximate) OpenXML column width, based on font size and text contained + * + * @param PHPExcel_Style_Font $font Font object + * @param PHPExcel_RichText|string $cellText Text to calculate width + * @param integer $rotation Rotation angle + * @param PHPExcel_Style_Font|NULL $defaultFont Font object + * @return integer Column width + */ + public static function calculateColumnWidth(PHPExcel_Style_Font $font, $cellText = '', $rotation = 0, PHPExcel_Style_Font $defaultFont = null) { + + // If it is rich text, use plain text + if ($cellText instanceof PHPExcel_RichText) { + $cellText = $cellText->getPlainText(); + } + + // Special case if there are one or more newline characters ("\n") + if (strpos($cellText, "\n") !== false) { + $lineTexts = explode("\n", $cellText); + $lineWitdhs = array(); + foreach ($lineTexts as $lineText) { + $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); + } + return max($lineWidths); // width of longest line in cell + } + + // Try to get the exact text width in pixels + try { + // If autosize method is set to 'approx', use approximation + if (self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX) { + throw new PHPExcel_Exception('AutoSize method is set to approx'); + } + + // Width of text in pixels excl. padding + $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation); + + // Excel adds some padding, use 1.07 of the width of an 'n' glyph + $columnWidth += ceil(self::getTextWidthPixelsExact('0', $font, 0) * 1.07); // pixels incl. padding + + } catch (PHPExcel_Exception $e) { + // Width of text in pixels excl. padding, approximation + $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation); + + // Excel adds some padding, just use approx width of 'n' glyph + $columnWidth += self::getTextWidthPixelsApprox('n', $font, 0); + } + + // Convert from pixel width to column width + $columnWidth = PHPExcel_Shared_Drawing::pixelsToCellDimension($columnWidth, $defaultFont); + + // Return + return round($columnWidth, 6); + } + + /** + * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle + * + * @param string $text + * @param PHPExcel_Style_Font + * @param int $rotation + * @return int + * @throws PHPExcel_Exception + */ + public static function getTextWidthPixelsExact($text, PHPExcel_Style_Font $font, $rotation = 0) { + if (!function_exists('imagettfbbox')) { + throw new PHPExcel_Exception('GD library needs to be enabled'); + } + + // font size should really be supplied in pixels in GD2, + // but since GD2 seems to assume 72dpi, pixels and points are the same + $fontFile = self::getTrueTypeFontFileFromFont($font); + $textBox = imagettfbbox($font->getSize(), $rotation, $fontFile, $text); + + // Get corners positions + $lowerLeftCornerX = $textBox[0]; + $lowerLeftCornerY = $textBox[1]; + $lowerRightCornerX = $textBox[2]; + $lowerRightCornerY = $textBox[3]; + $upperRightCornerX = $textBox[4]; + $upperRightCornerY = $textBox[5]; + $upperLeftCornerX = $textBox[6]; + $upperLeftCornerY = $textBox[7]; + + // Consider the rotation when calculating the width + $textWidth = max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX); + + return $textWidth; + } + + /** + * Get approximate width in pixels for a string of text in a certain font at a certain rotation angle + * + * @param string $columnText + * @param PHPExcel_Style_Font $font + * @param int $rotation + * @return int Text width in pixels (no padding added) + */ + public static function getTextWidthPixelsApprox($columnText, PHPExcel_Style_Font $font = null, $rotation = 0) + { + $fontName = $font->getName(); + $fontSize = $font->getSize(); + + // Calculate column width in pixels. We assume fixed glyph width. Result varies with font name and size. + switch ($fontName) { + case 'Calibri': + // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font. + $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; + + case 'Arial': + // value 7 was found via interpolation by inspecting real Excel files with Arial 10 font. + $columnWidth = (int) (7 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; + + case 'Verdana': + // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font. + $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; + + default: + // just assume Calibri + $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; + } + + // Calculate approximate rotated column width + if ($rotation !== 0) { + if ($rotation == -165) { + // stacked text + $columnWidth = 4; // approximation + } else { + // rotated text + $columnWidth = $columnWidth * cos(deg2rad($rotation)) + + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation + } + } + + // pixel width is an integer + $columnWidth = (int) $columnWidth; + return $columnWidth; + } + + /** + * Calculate an (approximate) pixel size, based on a font points size + * + * @param int $fontSizeInPoints Font size (in points) + * @return int Font size (in pixels) + */ + public static function fontSizeToPixels($fontSizeInPoints = 11) { + return (int) ((4 / 3) * $fontSizeInPoints); + } + + /** + * Calculate an (approximate) pixel size, based on inch size + * + * @param int $sizeInInch Font size (in inch) + * @return int Size (in pixels) + */ + public static function inchSizeToPixels($sizeInInch = 1) { + return ($sizeInInch * 96); + } + + /** + * Calculate an (approximate) pixel size, based on centimeter size + * + * @param int $sizeInCm Font size (in centimeters) + * @return int Size (in pixels) + */ + public static function centimeterSizeToPixels($sizeInCm = 1) { + return ($sizeInCm * 37.795275591); + } + + /** + * Returns the font path given the font + * + * @param PHPExcel_Style_Font + * @return string Path to TrueType font file + */ + public static function getTrueTypeFontFileFromFont($font) { + if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) { + throw new PHPExcel_Exception('Valid directory to TrueType Font files not specified'); + } + + $name = $font->getName(); + $bold = $font->getBold(); + $italic = $font->getItalic(); + + // Check if we can map font to true type font file + switch ($name) { + case 'Arial': + $fontFile = ( + $bold ? ($italic ? self::ARIAL_BOLD_ITALIC : self::ARIAL_BOLD) + : ($italic ? self::ARIAL_ITALIC : self::ARIAL) + ); + break; + + case 'Calibri': + $fontFile = ( + $bold ? ($italic ? self::CALIBRI_BOLD_ITALIC : self::CALIBRI_BOLD) + : ($italic ? self::CALIBRI_ITALIC : self::CALIBRI) + ); + break; + + case 'Courier New': + $fontFile = ( + $bold ? ($italic ? self::COURIER_NEW_BOLD_ITALIC : self::COURIER_NEW_BOLD) + : ($italic ? self::COURIER_NEW_ITALIC : self::COURIER_NEW) + ); + break; + + case 'Comic Sans MS': + $fontFile = ( + $bold ? self::COMIC_SANS_MS_BOLD : self::COMIC_SANS_MS + ); + break; + + case 'Georgia': + $fontFile = ( + $bold ? ($italic ? self::GEORGIA_BOLD_ITALIC : self::GEORGIA_BOLD) + : ($italic ? self::GEORGIA_ITALIC : self::GEORGIA) + ); + break; + + case 'Impact': + $fontFile = self::IMPACT; + break; + + case 'Liberation Sans': + $fontFile = ( + $bold ? ($italic ? self::LIBERATION_SANS_BOLD_ITALIC : self::LIBERATION_SANS_BOLD) + : ($italic ? self::LIBERATION_SANS_ITALIC : self::LIBERATION_SANS) + ); + break; + + case 'Lucida Console': + $fontFile = self::LUCIDA_CONSOLE; + break; + + case 'Lucida Sans Unicode': + $fontFile = self::LUCIDA_SANS_UNICODE; + break; + + case 'Microsoft Sans Serif': + $fontFile = self::MICROSOFT_SANS_SERIF; + break; + + case 'Palatino Linotype': + $fontFile = ( + $bold ? ($italic ? self::PALATINO_LINOTYPE_BOLD_ITALIC : self::PALATINO_LINOTYPE_BOLD) + : ($italic ? self::PALATINO_LINOTYPE_ITALIC : self::PALATINO_LINOTYPE) + ); + break; + + case 'Symbol': + $fontFile = self::SYMBOL; + break; + + case 'Tahoma': + $fontFile = ( + $bold ? self::TAHOMA_BOLD : self::TAHOMA + ); + break; + + case 'Times New Roman': + $fontFile = ( + $bold ? ($italic ? self::TIMES_NEW_ROMAN_BOLD_ITALIC : self::TIMES_NEW_ROMAN_BOLD) + : ($italic ? self::TIMES_NEW_ROMAN_ITALIC : self::TIMES_NEW_ROMAN) + ); + break; + + case 'Trebuchet MS': + $fontFile = ( + $bold ? ($italic ? self::TREBUCHET_MS_BOLD_ITALIC : self::TREBUCHET_MS_BOLD) + : ($italic ? self::TREBUCHET_MS_ITALIC : self::TREBUCHET_MS) + ); + break; + + case 'Verdana': + $fontFile = ( + $bold ? ($italic ? self::VERDANA_BOLD_ITALIC : self::VERDANA_BOLD) + : ($italic ? self::VERDANA_ITALIC : self::VERDANA) + ); + break; + + default: + throw new PHPExcel_Exception('Unknown font name "'. $name .'". Cannot map to TrueType font file'); + break; + } + + $fontFile = self::$trueTypeFontPath . $fontFile; + + // Check if file actually exists + if (!file_exists($fontFile)) { + throw New PHPExcel_Exception('TrueType Font file not found'); + } + + return $fontFile; + } + + /** + * Returns the associated charset for the font name. + * + * @param string $name Font name + * @return int Character set code + */ + public static function getCharsetFromFontName($name) + { + switch ($name) { + // Add more cases. Check FONT records in real Excel files. + case 'EucrosiaUPC': return self::CHARSET_ANSI_THAI; + case 'Wingdings': return self::CHARSET_SYMBOL; + case 'Wingdings 2': return self::CHARSET_SYMBOL; + case 'Wingdings 3': return self::CHARSET_SYMBOL; + default: return self::CHARSET_ANSI_LATIN; + } + } + + /** + * Get the effective column width for columns without a column dimension or column with width -1 + * For example, for Calibri 11 this is 9.140625 (64 px) + * + * @param PHPExcel_Style_Font $font The workbooks default font + * @param boolean $pPixels true = return column width in pixels, false = return in OOXML units + * @return mixed Column width + */ + public static function getDefaultColumnWidthByFont(PHPExcel_Style_Font $font, $pPixels = false) + { + if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) { + // Exact width can be determined + $columnWidth = $pPixels ? + self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] + : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; + + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $columnWidth = $pPixels ? + self::$defaultColumnWidths['Calibri'][11]['px'] + : self::$defaultColumnWidths['Calibri'][11]['width']; + $columnWidth = $columnWidth * $font->getSize() / 11; + + // Round pixels to closest integer + if ($pPixels) { + $columnWidth = (int) round($columnWidth); + } + } + + return $columnWidth; + } + + /** + * Get the effective row height for rows without a row dimension or rows with height -1 + * For example, for Calibri 11 this is 15 points + * + * @param PHPExcel_Style_Font $font The workbooks default font + * @return float Row height in points + */ + public static function getDefaultRowHeightByFont(PHPExcel_Style_Font $font) + { + switch ($font->getName()) { + case 'Arial': + switch ($font->getSize()) { + case 10: + // inspection of Arial 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + + case 9: + // inspection of Arial 9 workbook says 12.00pt ~16px + $rowHeight = 12; + break; + + case 8: + // inspection of Arial 8 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + + case 7: + // inspection of Arial 7 workbook says 9.00pt ~12px + $rowHeight = 9; + break; + + case 6: + case 5: + // inspection of Arial 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + + case 4: + // inspection of Arial 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + + case 3: + // inspection of Arial 3 workbook says 6.00pt ~8px + $rowHeight = 6; + break; + + case 2: + case 1: + // inspection of Arial 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + + default: + // use Arial 10 workbook as an approximation, extrapolation + $rowHeight = 12.75 * $font->getSize() / 10; + break; + } + break; + + case 'Calibri': + switch ($font->getSize()) { + case 11: + // inspection of Calibri 11 workbook says 15.00pt ~20px + $rowHeight = 15; + break; + + case 10: + // inspection of Calibri 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + + case 9: + // inspection of Calibri 9 workbook says 12.00pt ~16px + $rowHeight = 12; + break; + + case 8: + // inspection of Calibri 8 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + + case 7: + // inspection of Calibri 7 workbook says 9.00pt ~12px + $rowHeight = 9; + break; + + case 6: + case 5: + // inspection of Calibri 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + + case 4: + // inspection of Calibri 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + + case 3: + // inspection of Calibri 3 workbook says 6.00pt ~8px + $rowHeight = 6.00; + break; + + case 2: + case 1: + // inspection of Calibri 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + + default: + // use Calibri 11 workbook as an approximation, extrapolation + $rowHeight = 15 * $font->getSize() / 11; + break; + } + break; + + case 'Verdana': + switch ($font->getSize()) { + case 10: + // inspection of Verdana 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + + case 9: + // inspection of Verdana 9 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + + case 8: + // inspection of Verdana 8 workbook says 10.50pt ~14px + $rowHeight = 10.50; + break; + + case 7: + // inspection of Verdana 7 workbook says 9.00pt ~12px + $rowHeight = 9.00; + break; + + case 6: + case 5: + // inspection of Verdana 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + + case 4: + // inspection of Verdana 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + + case 3: + // inspection of Verdana 3 workbook says 6.00pt ~8px + $rowHeight = 6; + break; + + case 2: + case 1: + // inspection of Verdana 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + + default: + // use Verdana 10 workbook as an approximation, extrapolation + $rowHeight = 12.75 * $font->getSize() / 10; + break; + } + break; + + default: + // just use Calibri as an approximation + $rowHeight = 15 * $font->getSize() / 11; + break; + } + + return $rowHeight; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT new file mode 100644 index 00000000..1c18a5da --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT @@ -0,0 +1,16 @@ +Mar 1, 2005 11:15 AST by PM + ++ For consistency, renamed Math.php to Maths.java, utils to util, + tests to test, docs to doc - + ++ Removed conditional logic from top of Matrix class. + ++ Switched to using hypo function in Maths.php for all php-hypot calls. + NOTE TO SELF: Need to make sure that all decompositions have been + switched over to using the bundled hypo. + +Feb 25, 2005 at 10:00 AST by PM + ++ Recommend using simpler Error.php instead of JAMA_Error.php but + can be persuaded otherwise. + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php new file mode 100644 index 00000000..cfbaa53b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php @@ -0,0 +1,149 @@ +<?php +/** + * @package JAMA + * + * Cholesky decomposition class + * + * For a symmetric, positive definite matrix A, the Cholesky decomposition + * is an lower triangular matrix L so that A = L*L'. + * + * If the matrix is not symmetric or positive definite, the constructor + * returns a partial decomposition and sets an internal flag that may + * be queried by the isSPD() method. + * + * @author Paul Meagher + * @author Michael Bommarito + * @version 1.2 + */ +class CholeskyDecomposition { + + /** + * Decomposition storage + * @var array + * @access private + */ + private $L = array(); + + /** + * Matrix row and column dimension + * @var int + * @access private + */ + private $m; + + /** + * Symmetric positive definite flag + * @var boolean + * @access private + */ + private $isspd = true; + + + /** + * CholeskyDecomposition + * + * Class constructor - decomposes symmetric positive definite matrix + * @param mixed Matrix square symmetric positive definite matrix + */ + public function __construct($A = null) { + if ($A instanceof Matrix) { + $this->L = $A->getArray(); + $this->m = $A->getRowDimension(); + + for($i = 0; $i < $this->m; ++$i) { + for($j = $i; $j < $this->m; ++$j) { + for($sum = $this->L[$i][$j], $k = $i - 1; $k >= 0; --$k) { + $sum -= $this->L[$i][$k] * $this->L[$j][$k]; + } + if ($i == $j) { + if ($sum >= 0) { + $this->L[$i][$i] = sqrt($sum); + } else { + $this->isspd = false; + } + } else { + if ($this->L[$i][$i] != 0) { + $this->L[$j][$i] = $sum / $this->L[$i][$i]; + } + } + } + + for ($k = $i+1; $k < $this->m; ++$k) { + $this->L[$i][$k] = 0.0; + } + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException)); + } + } // function __construct() + + + /** + * Is the matrix symmetric and positive definite? + * + * @return boolean + */ + public function isSPD() { + return $this->isspd; + } // function isSPD() + + + /** + * getL + * + * Return triangular factor. + * @return Matrix Lower triangular matrix + */ + public function getL() { + return new Matrix($this->L); + } // function getL() + + + /** + * Solve A*X = B + * + * @param $B Row-equal matrix + * @return Matrix L * L' * X = B + */ + public function solve($B = null) { + if ($B instanceof Matrix) { + if ($B->getRowDimension() == $this->m) { + if ($this->isspd) { + $X = $B->getArrayCopy(); + $nx = $B->getColumnDimension(); + + for ($k = 0; $k < $this->m; ++$k) { + for ($i = $k + 1; $i < $this->m; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->L[$i][$k]; + } + } + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->L[$k][$k]; + } + } + + for ($k = $this->m - 1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->L[$k][$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->L[$k][$i]; + } + } + } + + return new Matrix($X, $this->m, $nx); + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixSPDException)); + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixDimensionException)); + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException)); + } + } // function solve() + +} // class CholeskyDecomposition diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php new file mode 100644 index 00000000..2a696d00 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php @@ -0,0 +1,862 @@ +<?php +/** + * @package JAMA + * + * Class to obtain eigenvalues and eigenvectors of a real matrix. + * + * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D + * is diagonal and the eigenvector matrix V is orthogonal (i.e. + * A = V.times(D.times(V.transpose())) and V.times(V.transpose()) + * equals the identity matrix). + * + * If A is not symmetric, then the eigenvalue matrix D is block diagonal + * with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, + * lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The + * columns of V represent the eigenvectors in the sense that A*V = V*D, + * i.e. A.times(V) equals V.times(D). The matrix V may be badly + * conditioned, or even singular, so the validity of the equation + * A = V*D*inverse(V) depends upon V.cond(). + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class EigenvalueDecomposition { + + /** + * Row and column dimension (square matrix). + * @var int + */ + private $n; + + /** + * Internal symmetry flag. + * @var int + */ + private $issymmetric; + + /** + * Arrays for internal storage of eigenvalues. + * @var array + */ + private $d = array(); + private $e = array(); + + /** + * Array for internal storage of eigenvectors. + * @var array + */ + private $V = array(); + + /** + * Array for internal storage of nonsymmetric Hessenberg form. + * @var array + */ + private $H = array(); + + /** + * Working storage for nonsymmetric algorithm. + * @var array + */ + private $ort; + + /** + * Used for complex scalar division. + * @var float + */ + private $cdivr; + private $cdivi; + + + /** + * Symmetric Householder reduction to tridiagonal form. + * + * @access private + */ + private function tred2 () { + // This is derived from the Algol procedures tred2 by + // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutine in EISPACK. + $this->d = $this->V[$this->n-1]; + // Householder reduction to tridiagonal form. + for ($i = $this->n-1; $i > 0; --$i) { + $i_ = $i -1; + // Scale to avoid under/overflow. + $h = $scale = 0.0; + $scale += array_sum(array_map(abs, $this->d)); + if ($scale == 0.0) { + $this->e[$i] = $this->d[$i_]; + $this->d = array_slice($this->V[$i_], 0, $i_); + for ($j = 0; $j < $i; ++$j) { + $this->V[$j][$i] = $this->V[$i][$j] = 0.0; + } + } else { + // Generate Householder vector. + for ($k = 0; $k < $i; ++$k) { + $this->d[$k] /= $scale; + $h += pow($this->d[$k], 2); + } + $f = $this->d[$i_]; + $g = sqrt($h); + if ($f > 0) { + $g = -$g; + } + $this->e[$i] = $scale * $g; + $h = $h - $f * $g; + $this->d[$i_] = $f - $g; + for ($j = 0; $j < $i; ++$j) { + $this->e[$j] = 0.0; + } + // Apply similarity transformation to remaining columns. + for ($j = 0; $j < $i; ++$j) { + $f = $this->d[$j]; + $this->V[$j][$i] = $f; + $g = $this->e[$j] + $this->V[$j][$j] * $f; + for ($k = $j+1; $k <= $i_; ++$k) { + $g += $this->V[$k][$j] * $this->d[$k]; + $this->e[$k] += $this->V[$k][$j] * $f; + } + $this->e[$j] = $g; + } + $f = 0.0; + for ($j = 0; $j < $i; ++$j) { + $this->e[$j] /= $h; + $f += $this->e[$j] * $this->d[$j]; + } + $hh = $f / (2 * $h); + for ($j=0; $j < $i; ++$j) { + $this->e[$j] -= $hh * $this->d[$j]; + } + for ($j = 0; $j < $i; ++$j) { + $f = $this->d[$j]; + $g = $this->e[$j]; + for ($k = $j; $k <= $i_; ++$k) { + $this->V[$k][$j] -= ($f * $this->e[$k] + $g * $this->d[$k]); + } + $this->d[$j] = $this->V[$i-1][$j]; + $this->V[$i][$j] = 0.0; + } + } + $this->d[$i] = $h; + } + + // Accumulate transformations. + for ($i = 0; $i < $this->n-1; ++$i) { + $this->V[$this->n-1][$i] = $this->V[$i][$i]; + $this->V[$i][$i] = 1.0; + $h = $this->d[$i+1]; + if ($h != 0.0) { + for ($k = 0; $k <= $i; ++$k) { + $this->d[$k] = $this->V[$k][$i+1] / $h; + } + for ($j = 0; $j <= $i; ++$j) { + $g = 0.0; + for ($k = 0; $k <= $i; ++$k) { + $g += $this->V[$k][$i+1] * $this->V[$k][$j]; + } + for ($k = 0; $k <= $i; ++$k) { + $this->V[$k][$j] -= $g * $this->d[$k]; + } + } + } + for ($k = 0; $k <= $i; ++$k) { + $this->V[$k][$i+1] = 0.0; + } + } + + $this->d = $this->V[$this->n-1]; + $this->V[$this->n-1] = array_fill(0, $j, 0.0); + $this->V[$this->n-1][$this->n-1] = 1.0; + $this->e[0] = 0.0; + } + + + /** + * Symmetric tridiagonal QL algorithm. + * + * This is derived from the Algol procedures tql2, by + * Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + * Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutine in EISPACK. + * + * @access private + */ + private function tql2() { + for ($i = 1; $i < $this->n; ++$i) { + $this->e[$i-1] = $this->e[$i]; + } + $this->e[$this->n-1] = 0.0; + $f = 0.0; + $tst1 = 0.0; + $eps = pow(2.0,-52.0); + + for ($l = 0; $l < $this->n; ++$l) { + // Find small subdiagonal element + $tst1 = max($tst1, abs($this->d[$l]) + abs($this->e[$l])); + $m = $l; + while ($m < $this->n) { + if (abs($this->e[$m]) <= $eps * $tst1) + break; + ++$m; + } + // If m == l, $this->d[l] is an eigenvalue, + // otherwise, iterate. + if ($m > $l) { + $iter = 0; + do { + // Could check iteration count here. + $iter += 1; + // Compute implicit shift + $g = $this->d[$l]; + $p = ($this->d[$l+1] - $g) / (2.0 * $this->e[$l]); + $r = hypo($p, 1.0); + if ($p < 0) + $r *= -1; + $this->d[$l] = $this->e[$l] / ($p + $r); + $this->d[$l+1] = $this->e[$l] * ($p + $r); + $dl1 = $this->d[$l+1]; + $h = $g - $this->d[$l]; + for ($i = $l + 2; $i < $this->n; ++$i) + $this->d[$i] -= $h; + $f += $h; + // Implicit QL transformation. + $p = $this->d[$m]; + $c = 1.0; + $c2 = $c3 = $c; + $el1 = $this->e[$l + 1]; + $s = $s2 = 0.0; + for ($i = $m-1; $i >= $l; --$i) { + $c3 = $c2; + $c2 = $c; + $s2 = $s; + $g = $c * $this->e[$i]; + $h = $c * $p; + $r = hypo($p, $this->e[$i]); + $this->e[$i+1] = $s * $r; + $s = $this->e[$i] / $r; + $c = $p / $r; + $p = $c * $this->d[$i] - $s * $g; + $this->d[$i+1] = $h + $s * ($c * $g + $s * $this->d[$i]); + // Accumulate transformation. + for ($k = 0; $k < $this->n; ++$k) { + $h = $this->V[$k][$i+1]; + $this->V[$k][$i+1] = $s * $this->V[$k][$i] + $c * $h; + $this->V[$k][$i] = $c * $this->V[$k][$i] - $s * $h; + } + } + $p = -$s * $s2 * $c3 * $el1 * $this->e[$l] / $dl1; + $this->e[$l] = $s * $p; + $this->d[$l] = $c * $p; + // Check for convergence. + } while (abs($this->e[$l]) > $eps * $tst1); + } + $this->d[$l] = $this->d[$l] + $f; + $this->e[$l] = 0.0; + } + + // Sort eigenvalues and corresponding vectors. + for ($i = 0; $i < $this->n - 1; ++$i) { + $k = $i; + $p = $this->d[$i]; + for ($j = $i+1; $j < $this->n; ++$j) { + if ($this->d[$j] < $p) { + $k = $j; + $p = $this->d[$j]; + } + } + if ($k != $i) { + $this->d[$k] = $this->d[$i]; + $this->d[$i] = $p; + for ($j = 0; $j < $this->n; ++$j) { + $p = $this->V[$j][$i]; + $this->V[$j][$i] = $this->V[$j][$k]; + $this->V[$j][$k] = $p; + } + } + } + } + + + /** + * Nonsymmetric reduction to Hessenberg form. + * + * This is derived from the Algol procedures orthes and ortran, + * by Martin and Wilkinson, Handbook for Auto. Comp., + * Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutines in EISPACK. + * + * @access private + */ + private function orthes () { + $low = 0; + $high = $this->n-1; + + for ($m = $low+1; $m <= $high-1; ++$m) { + // Scale column. + $scale = 0.0; + for ($i = $m; $i <= $high; ++$i) { + $scale = $scale + abs($this->H[$i][$m-1]); + } + if ($scale != 0.0) { + // Compute Householder transformation. + $h = 0.0; + for ($i = $high; $i >= $m; --$i) { + $this->ort[$i] = $this->H[$i][$m-1] / $scale; + $h += $this->ort[$i] * $this->ort[$i]; + } + $g = sqrt($h); + if ($this->ort[$m] > 0) { + $g *= -1; + } + $h -= $this->ort[$m] * $g; + $this->ort[$m] -= $g; + // Apply Householder similarity transformation + // H = (I -u * u' / h) * H * (I -u * u') / h) + for ($j = $m; $j < $this->n; ++$j) { + $f = 0.0; + for ($i = $high; $i >= $m; --$i) { + $f += $this->ort[$i] * $this->H[$i][$j]; + } + $f /= $h; + for ($i = $m; $i <= $high; ++$i) { + $this->H[$i][$j] -= $f * $this->ort[$i]; + } + } + for ($i = 0; $i <= $high; ++$i) { + $f = 0.0; + for ($j = $high; $j >= $m; --$j) { + $f += $this->ort[$j] * $this->H[$i][$j]; + } + $f = $f / $h; + for ($j = $m; $j <= $high; ++$j) { + $this->H[$i][$j] -= $f * $this->ort[$j]; + } + } + $this->ort[$m] = $scale * $this->ort[$m]; + $this->H[$m][$m-1] = $scale * $g; + } + } + + // Accumulate transformations (Algol's ortran). + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->V[$i][$j] = ($i == $j ? 1.0 : 0.0); + } + } + for ($m = $high-1; $m >= $low+1; --$m) { + if ($this->H[$m][$m-1] != 0.0) { + for ($i = $m+1; $i <= $high; ++$i) { + $this->ort[$i] = $this->H[$i][$m-1]; + } + for ($j = $m; $j <= $high; ++$j) { + $g = 0.0; + for ($i = $m; $i <= $high; ++$i) { + $g += $this->ort[$i] * $this->V[$i][$j]; + } + // Double division avoids possible underflow + $g = ($g / $this->ort[$m]) / $this->H[$m][$m-1]; + for ($i = $m; $i <= $high; ++$i) { + $this->V[$i][$j] += $g * $this->ort[$i]; + } + } + } + } + } + + + /** + * Performs complex division. + * + * @access private + */ + private function cdiv($xr, $xi, $yr, $yi) { + if (abs($yr) > abs($yi)) { + $r = $yi / $yr; + $d = $yr + $r * $yi; + $this->cdivr = ($xr + $r * $xi) / $d; + $this->cdivi = ($xi - $r * $xr) / $d; + } else { + $r = $yr / $yi; + $d = $yi + $r * $yr; + $this->cdivr = ($r * $xr + $xi) / $d; + $this->cdivi = ($r * $xi - $xr) / $d; + } + } + + + /** + * Nonsymmetric reduction from Hessenberg to real Schur form. + * + * Code is derived from the Algol procedure hqr2, + * by Martin and Wilkinson, Handbook for Auto. Comp., + * Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutine in EISPACK. + * + * @access private + */ + private function hqr2 () { + // Initialize + $nn = $this->n; + $n = $nn - 1; + $low = 0; + $high = $nn - 1; + $eps = pow(2.0, -52.0); + $exshift = 0.0; + $p = $q = $r = $s = $z = 0; + // Store roots isolated by balanc and compute matrix norm + $norm = 0.0; + + for ($i = 0; $i < $nn; ++$i) { + if (($i < $low) OR ($i > $high)) { + $this->d[$i] = $this->H[$i][$i]; + $this->e[$i] = 0.0; + } + for ($j = max($i-1, 0); $j < $nn; ++$j) { + $norm = $norm + abs($this->H[$i][$j]); + } + } + + // Outer loop over eigenvalue index + $iter = 0; + while ($n >= $low) { + // Look for single small sub-diagonal element + $l = $n; + while ($l > $low) { + $s = abs($this->H[$l-1][$l-1]) + abs($this->H[$l][$l]); + if ($s == 0.0) { + $s = $norm; + } + if (abs($this->H[$l][$l-1]) < $eps * $s) { + break; + } + --$l; + } + // Check for convergence + // One root found + if ($l == $n) { + $this->H[$n][$n] = $this->H[$n][$n] + $exshift; + $this->d[$n] = $this->H[$n][$n]; + $this->e[$n] = 0.0; + --$n; + $iter = 0; + // Two roots found + } else if ($l == $n-1) { + $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; + $p = ($this->H[$n-1][$n-1] - $this->H[$n][$n]) / 2.0; + $q = $p * $p + $w; + $z = sqrt(abs($q)); + $this->H[$n][$n] = $this->H[$n][$n] + $exshift; + $this->H[$n-1][$n-1] = $this->H[$n-1][$n-1] + $exshift; + $x = $this->H[$n][$n]; + // Real pair + if ($q >= 0) { + if ($p >= 0) { + $z = $p + $z; + } else { + $z = $p - $z; + } + $this->d[$n-1] = $x + $z; + $this->d[$n] = $this->d[$n-1]; + if ($z != 0.0) { + $this->d[$n] = $x - $w / $z; + } + $this->e[$n-1] = 0.0; + $this->e[$n] = 0.0; + $x = $this->H[$n][$n-1]; + $s = abs($x) + abs($z); + $p = $x / $s; + $q = $z / $s; + $r = sqrt($p * $p + $q * $q); + $p = $p / $r; + $q = $q / $r; + // Row modification + for ($j = $n-1; $j < $nn; ++$j) { + $z = $this->H[$n-1][$j]; + $this->H[$n-1][$j] = $q * $z + $p * $this->H[$n][$j]; + $this->H[$n][$j] = $q * $this->H[$n][$j] - $p * $z; + } + // Column modification + for ($i = 0; $i <= n; ++$i) { + $z = $this->H[$i][$n-1]; + $this->H[$i][$n-1] = $q * $z + $p * $this->H[$i][$n]; + $this->H[$i][$n] = $q * $this->H[$i][$n] - $p * $z; + } + // Accumulate transformations + for ($i = $low; $i <= $high; ++$i) { + $z = $this->V[$i][$n-1]; + $this->V[$i][$n-1] = $q * $z + $p * $this->V[$i][$n]; + $this->V[$i][$n] = $q * $this->V[$i][$n] - $p * $z; + } + // Complex pair + } else { + $this->d[$n-1] = $x + $p; + $this->d[$n] = $x + $p; + $this->e[$n-1] = $z; + $this->e[$n] = -$z; + } + $n = $n - 2; + $iter = 0; + // No convergence yet + } else { + // Form shift + $x = $this->H[$n][$n]; + $y = 0.0; + $w = 0.0; + if ($l < $n) { + $y = $this->H[$n-1][$n-1]; + $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; + } + // Wilkinson's original ad hoc shift + if ($iter == 10) { + $exshift += $x; + for ($i = $low; $i <= $n; ++$i) { + $this->H[$i][$i] -= $x; + } + $s = abs($this->H[$n][$n-1]) + abs($this->H[$n-1][$n-2]); + $x = $y = 0.75 * $s; + $w = -0.4375 * $s * $s; + } + // MATLAB's new ad hoc shift + if ($iter == 30) { + $s = ($y - $x) / 2.0; + $s = $s * $s + $w; + if ($s > 0) { + $s = sqrt($s); + if ($y < $x) { + $s = -$s; + } + $s = $x - $w / (($y - $x) / 2.0 + $s); + for ($i = $low; $i <= $n; ++$i) { + $this->H[$i][$i] -= $s; + } + $exshift += $s; + $x = $y = $w = 0.964; + } + } + // Could check iteration count here. + $iter = $iter + 1; + // Look for two consecutive small sub-diagonal elements + $m = $n - 2; + while ($m >= $l) { + $z = $this->H[$m][$m]; + $r = $x - $z; + $s = $y - $z; + $p = ($r * $s - $w) / $this->H[$m+1][$m] + $this->H[$m][$m+1]; + $q = $this->H[$m+1][$m+1] - $z - $r - $s; + $r = $this->H[$m+2][$m+1]; + $s = abs($p) + abs($q) + abs($r); + $p = $p / $s; + $q = $q / $s; + $r = $r / $s; + if ($m == $l) { + break; + } + if (abs($this->H[$m][$m-1]) * (abs($q) + abs($r)) < + $eps * (abs($p) * (abs($this->H[$m-1][$m-1]) + abs($z) + abs($this->H[$m+1][$m+1])))) { + break; + } + --$m; + } + for ($i = $m + 2; $i <= $n; ++$i) { + $this->H[$i][$i-2] = 0.0; + if ($i > $m+2) { + $this->H[$i][$i-3] = 0.0; + } + } + // Double QR step involving rows l:n and columns m:n + for ($k = $m; $k <= $n-1; ++$k) { + $notlast = ($k != $n-1); + if ($k != $m) { + $p = $this->H[$k][$k-1]; + $q = $this->H[$k+1][$k-1]; + $r = ($notlast ? $this->H[$k+2][$k-1] : 0.0); + $x = abs($p) + abs($q) + abs($r); + if ($x != 0.0) { + $p = $p / $x; + $q = $q / $x; + $r = $r / $x; + } + } + if ($x == 0.0) { + break; + } + $s = sqrt($p * $p + $q * $q + $r * $r); + if ($p < 0) { + $s = -$s; + } + if ($s != 0) { + if ($k != $m) { + $this->H[$k][$k-1] = -$s * $x; + } elseif ($l != $m) { + $this->H[$k][$k-1] = -$this->H[$k][$k-1]; + } + $p = $p + $s; + $x = $p / $s; + $y = $q / $s; + $z = $r / $s; + $q = $q / $p; + $r = $r / $p; + // Row modification + for ($j = $k; $j < $nn; ++$j) { + $p = $this->H[$k][$j] + $q * $this->H[$k+1][$j]; + if ($notlast) { + $p = $p + $r * $this->H[$k+2][$j]; + $this->H[$k+2][$j] = $this->H[$k+2][$j] - $p * $z; + } + $this->H[$k][$j] = $this->H[$k][$j] - $p * $x; + $this->H[$k+1][$j] = $this->H[$k+1][$j] - $p * $y; + } + // Column modification + for ($i = 0; $i <= min($n, $k+3); ++$i) { + $p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k+1]; + if ($notlast) { + $p = $p + $z * $this->H[$i][$k+2]; + $this->H[$i][$k+2] = $this->H[$i][$k+2] - $p * $r; + } + $this->H[$i][$k] = $this->H[$i][$k] - $p; + $this->H[$i][$k+1] = $this->H[$i][$k+1] - $p * $q; + } + // Accumulate transformations + for ($i = $low; $i <= $high; ++$i) { + $p = $x * $this->V[$i][$k] + $y * $this->V[$i][$k+1]; + if ($notlast) { + $p = $p + $z * $this->V[$i][$k+2]; + $this->V[$i][$k+2] = $this->V[$i][$k+2] - $p * $r; + } + $this->V[$i][$k] = $this->V[$i][$k] - $p; + $this->V[$i][$k+1] = $this->V[$i][$k+1] - $p * $q; + } + } // ($s != 0) + } // k loop + } // check convergence + } // while ($n >= $low) + + // Backsubstitute to find vectors of upper triangular form + if ($norm == 0.0) { + return; + } + + for ($n = $nn-1; $n >= 0; --$n) { + $p = $this->d[$n]; + $q = $this->e[$n]; + // Real vector + if ($q == 0) { + $l = $n; + $this->H[$n][$n] = 1.0; + for ($i = $n-1; $i >= 0; --$i) { + $w = $this->H[$i][$i] - $p; + $r = 0.0; + for ($j = $l; $j <= $n; ++$j) { + $r = $r + $this->H[$i][$j] * $this->H[$j][$n]; + } + if ($this->e[$i] < 0.0) { + $z = $w; + $s = $r; + } else { + $l = $i; + if ($this->e[$i] == 0.0) { + if ($w != 0.0) { + $this->H[$i][$n] = -$r / $w; + } else { + $this->H[$i][$n] = -$r / ($eps * $norm); + } + // Solve real equations + } else { + $x = $this->H[$i][$i+1]; + $y = $this->H[$i+1][$i]; + $q = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i]; + $t = ($x * $s - $z * $r) / $q; + $this->H[$i][$n] = $t; + if (abs($x) > abs($z)) { + $this->H[$i+1][$n] = (-$r - $w * $t) / $x; + } else { + $this->H[$i+1][$n] = (-$s - $y * $t) / $z; + } + } + // Overflow control + $t = abs($this->H[$i][$n]); + if (($eps * $t) * $t > 1) { + for ($j = $i; $j <= $n; ++$j) { + $this->H[$j][$n] = $this->H[$j][$n] / $t; + } + } + } + } + // Complex vector + } else if ($q < 0) { + $l = $n-1; + // Last vector component imaginary so matrix is triangular + if (abs($this->H[$n][$n-1]) > abs($this->H[$n-1][$n])) { + $this->H[$n-1][$n-1] = $q / $this->H[$n][$n-1]; + $this->H[$n-1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n-1]; + } else { + $this->cdiv(0.0, -$this->H[$n-1][$n], $this->H[$n-1][$n-1] - $p, $q); + $this->H[$n-1][$n-1] = $this->cdivr; + $this->H[$n-1][$n] = $this->cdivi; + } + $this->H[$n][$n-1] = 0.0; + $this->H[$n][$n] = 1.0; + for ($i = $n-2; $i >= 0; --$i) { + // double ra,sa,vr,vi; + $ra = 0.0; + $sa = 0.0; + for ($j = $l; $j <= $n; ++$j) { + $ra = $ra + $this->H[$i][$j] * $this->H[$j][$n-1]; + $sa = $sa + $this->H[$i][$j] * $this->H[$j][$n]; + } + $w = $this->H[$i][$i] - $p; + if ($this->e[$i] < 0.0) { + $z = $w; + $r = $ra; + $s = $sa; + } else { + $l = $i; + if ($this->e[$i] == 0) { + $this->cdiv(-$ra, -$sa, $w, $q); + $this->H[$i][$n-1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; + } else { + // Solve complex equations + $x = $this->H[$i][$i+1]; + $y = $this->H[$i+1][$i]; + $vr = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i] - $q * $q; + $vi = ($this->d[$i] - $p) * 2.0 * $q; + if ($vr == 0.0 & $vi == 0.0) { + $vr = $eps * $norm * (abs($w) + abs($q) + abs($x) + abs($y) + abs($z)); + } + $this->cdiv($x * $r - $z * $ra + $q * $sa, $x * $s - $z * $sa - $q * $ra, $vr, $vi); + $this->H[$i][$n-1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; + if (abs($x) > (abs($z) + abs($q))) { + $this->H[$i+1][$n-1] = (-$ra - $w * $this->H[$i][$n-1] + $q * $this->H[$i][$n]) / $x; + $this->H[$i+1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n-1]) / $x; + } else { + $this->cdiv(-$r - $y * $this->H[$i][$n-1], -$s - $y * $this->H[$i][$n], $z, $q); + $this->H[$i+1][$n-1] = $this->cdivr; + $this->H[$i+1][$n] = $this->cdivi; + } + } + // Overflow control + $t = max(abs($this->H[$i][$n-1]),abs($this->H[$i][$n])); + if (($eps * $t) * $t > 1) { + for ($j = $i; $j <= $n; ++$j) { + $this->H[$j][$n-1] = $this->H[$j][$n-1] / $t; + $this->H[$j][$n] = $this->H[$j][$n] / $t; + } + } + } // end else + } // end for + } // end else for complex case + } // end for + + // Vectors of isolated roots + for ($i = 0; $i < $nn; ++$i) { + if ($i < $low | $i > $high) { + for ($j = $i; $j < $nn; ++$j) { + $this->V[$i][$j] = $this->H[$i][$j]; + } + } + } + + // Back transformation to get eigenvectors of original matrix + for ($j = $nn-1; $j >= $low; --$j) { + for ($i = $low; $i <= $high; ++$i) { + $z = 0.0; + for ($k = $low; $k <= min($j,$high); ++$k) { + $z = $z + $this->V[$i][$k] * $this->H[$k][$j]; + } + $this->V[$i][$j] = $z; + } + } + } // end hqr2 + + + /** + * Constructor: Check for symmetry, then construct the eigenvalue decomposition + * + * @access public + * @param A Square matrix + * @return Structure to access D and V. + */ + public function __construct($Arg) { + $this->A = $Arg->getArray(); + $this->n = $Arg->getColumnDimension(); + + $issymmetric = true; + for ($j = 0; ($j < $this->n) & $issymmetric; ++$j) { + for ($i = 0; ($i < $this->n) & $issymmetric; ++$i) { + $issymmetric = ($this->A[$i][$j] == $this->A[$j][$i]); + } + } + + if ($issymmetric) { + $this->V = $this->A; + // Tridiagonalize. + $this->tred2(); + // Diagonalize. + $this->tql2(); + } else { + $this->H = $this->A; + $this->ort = array(); + // Reduce to Hessenberg form. + $this->orthes(); + // Reduce Hessenberg to real Schur form. + $this->hqr2(); + } + } + + + /** + * Return the eigenvector matrix + * + * @access public + * @return V + */ + public function getV() { + return new Matrix($this->V, $this->n, $this->n); + } + + + /** + * Return the real parts of the eigenvalues + * + * @access public + * @return real(diag(D)) + */ + public function getRealEigenvalues() { + return $this->d; + } + + + /** + * Return the imaginary parts of the eigenvalues + * + * @access public + * @return imag(diag(D)) + */ + public function getImagEigenvalues() { + return $this->e; + } + + + /** + * Return the block diagonal eigenvalue matrix + * + * @access public + * @return D + */ + public function getD() { + for ($i = 0; $i < $this->n; ++$i) { + $D[$i] = array_fill(0, $this->n, 0.0); + $D[$i][$i] = $this->d[$i]; + if ($this->e[$i] == 0) { + continue; + } + $o = ($this->e[$i] > 0) ? $i + 1 : $i - 1; + $D[$i][$o] = $this->e[$i]; + } + return new Matrix($D); + } + +} // class EigenvalueDecomposition diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php new file mode 100644 index 00000000..08e500cf --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php @@ -0,0 +1,258 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n + * unit lower triangular matrix L, an n-by-n upper triangular matrix U, + * and a permutation vector piv of length m so that A(piv,:) = L*U. + * If m < n, then L is m-by-m and U is m-by-n. + * + * The LU decompostion with pivoting always exists, even if the matrix is + * singular, so the constructor will never fail. The primary use of the + * LU decomposition is in the solution of square systems of simultaneous + * linear equations. This will fail if isNonsingular() returns false. + * + * @author Paul Meagher + * @author Bartosz Matosiuk + * @author Michael Bommarito + * @version 1.1 + * @license PHP v3.0 + */ +class PHPExcel_Shared_JAMA_LUDecomposition { + + const MatrixSingularException = "Can only perform operation on singular matrix."; + const MatrixSquareException = "Mismatched Row dimension"; + + /** + * Decomposition storage + * @var array + */ + private $LU = array(); + + /** + * Row dimension. + * @var int + */ + private $m; + + /** + * Column dimension. + * @var int + */ + private $n; + + /** + * Pivot sign. + * @var int + */ + private $pivsign; + + /** + * Internal storage of pivot vector. + * @var array + */ + private $piv = array(); + + + /** + * LU Decomposition constructor. + * + * @param $A Rectangular matrix + * @return Structure to access L, U and piv. + */ + public function __construct($A) { + if ($A instanceof PHPExcel_Shared_JAMA_Matrix) { + // Use a "left-looking", dot-product, Crout/Doolittle algorithm. + $this->LU = $A->getArray(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + for ($i = 0; $i < $this->m; ++$i) { + $this->piv[$i] = $i; + } + $this->pivsign = 1; + $LUrowi = $LUcolj = array(); + + // Outer loop. + for ($j = 0; $j < $this->n; ++$j) { + // Make a copy of the j-th column to localize references. + for ($i = 0; $i < $this->m; ++$i) { + $LUcolj[$i] = &$this->LU[$i][$j]; + } + // Apply previous transformations. + for ($i = 0; $i < $this->m; ++$i) { + $LUrowi = $this->LU[$i]; + // Most of the time is spent in the following dot product. + $kmax = min($i,$j); + $s = 0.0; + for ($k = 0; $k < $kmax; ++$k) { + $s += $LUrowi[$k] * $LUcolj[$k]; + } + $LUrowi[$j] = $LUcolj[$i] -= $s; + } + // Find pivot and exchange if necessary. + $p = $j; + for ($i = $j+1; $i < $this->m; ++$i) { + if (abs($LUcolj[$i]) > abs($LUcolj[$p])) { + $p = $i; + } + } + if ($p != $j) { + for ($k = 0; $k < $this->n; ++$k) { + $t = $this->LU[$p][$k]; + $this->LU[$p][$k] = $this->LU[$j][$k]; + $this->LU[$j][$k] = $t; + } + $k = $this->piv[$p]; + $this->piv[$p] = $this->piv[$j]; + $this->piv[$j] = $k; + $this->pivsign = $this->pivsign * -1; + } + // Compute multipliers. + if (($j < $this->m) && ($this->LU[$j][$j] != 0.0)) { + for ($i = $j+1; $i < $this->m; ++$i) { + $this->LU[$i][$j] /= $this->LU[$j][$j]; + } + } + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException); + } + } // function __construct() + + + /** + * Get lower triangular factor. + * + * @return array Lower triangular factor + */ + public function getL() { + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i > $j) { + $L[$i][$j] = $this->LU[$i][$j]; + } elseif ($i == $j) { + $L[$i][$j] = 1.0; + } else { + $L[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($L); + } // function getL() + + + /** + * Get upper triangular factor. + * + * @return array Upper triangular factor + */ + public function getU() { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i <= $j) { + $U[$i][$j] = $this->LU[$i][$j]; + } else { + $U[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($U); + } // function getU() + + + /** + * Return pivot permutation vector. + * + * @return array Pivot vector + */ + public function getPivot() { + return $this->piv; + } // function getPivot() + + + /** + * Alias for getPivot + * + * @see getPivot + */ + public function getDoublePivot() { + return $this->getPivot(); + } // function getDoublePivot() + + + /** + * Is the matrix nonsingular? + * + * @return true if U, and hence A, is nonsingular. + */ + public function isNonsingular() { + for ($j = 0; $j < $this->n; ++$j) { + if ($this->LU[$j][$j] == 0) { + return false; + } + } + return true; + } // function isNonsingular() + + + /** + * Count determinants + * + * @return array d matrix deterninat + */ + public function det() { + if ($this->m == $this->n) { + $d = $this->pivsign; + for ($j = 0; $j < $this->n; ++$j) { + $d *= $this->LU[$j][$j]; + } + return $d; + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException); + } + } // function det() + + + /** + * Solve A*X = B + * + * @param $B A Matrix with as many rows as A and any number of columns. + * @return X so that L*U*X = B(piv,:) + * @PHPExcel_Calculation_Exception IllegalArgumentException Matrix row dimensions must agree. + * @PHPExcel_Calculation_Exception RuntimeException Matrix is singular. + */ + public function solve($B) { + if ($B->getRowDimension() == $this->m) { + if ($this->isNonsingular()) { + // Copy right hand side with pivoting + $nx = $B->getColumnDimension(); + $X = $B->getMatrix($this->piv, 0, $nx-1); + // Solve L*Y = B(piv,:) + for ($k = 0; $k < $this->n; ++$k) { + for ($i = $k+1; $i < $this->n; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k]; + } + } + } + // Solve U*X = Y; + for ($k = $this->n-1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$k][$j] /= $this->LU[$k][$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k]; + } + } + } + return $X; + } else { + throw new PHPExcel_Calculation_Exception(self::MatrixSingularException); + } + } else { + throw new PHPExcel_Calculation_Exception(self::MatrixSquareException); + } + } // function solve() + +} // class PHPExcel_Shared_JAMA_LUDecomposition diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php new file mode 100644 index 00000000..b893a447 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php @@ -0,0 +1,1059 @@ +<?php +/** + * @package JAMA + */ + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + + +/* + * Matrix class + * + * @author Paul Meagher + * @author Michael Bommarito + * @author Lukasz Karapuda + * @author Bartek Matosiuk + * @version 1.8 + * @license PHP v3.0 + * @see http://math.nist.gov/javanumerics/jama/ + */ +class PHPExcel_Shared_JAMA_Matrix { + + + const PolymorphicArgumentException = "Invalid argument pattern for polymorphic function."; + const ArgumentTypeException = "Invalid argument type."; + const ArgumentBoundsException = "Invalid argument range."; + const MatrixDimensionException = "Matrix dimensions are not equal."; + const ArrayLengthException = "Array length must be a multiple of m."; + + /** + * Matrix storage + * + * @var array + * @access public + */ + public $A = array(); + + /** + * Matrix row dimension + * + * @var int + * @access private + */ + private $m; + + /** + * Matrix column dimension + * + * @var int + * @access private + */ + private $n; + + + /** + * Polymorphic constructor + * + * As PHP has no support for polymorphic constructors, we hack our own sort of polymorphism using func_num_args, func_get_arg, and gettype. In essence, we're just implementing a simple RTTI filter and calling the appropriate constructor. + */ + public function __construct() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + //Rectangular matrix - m x n initialized from 2D array + case 'array': + $this->m = count($args[0]); + $this->n = count($args[0][0]); + $this->A = $args[0]; + break; + //Square matrix - n x n + case 'integer': + $this->m = $args[0]; + $this->n = $args[0]; + $this->A = array_fill(0, $this->m, array_fill(0, $this->n, 0)); + break; + //Rectangular matrix - m x n + case 'integer,integer': + $this->m = $args[0]; + $this->n = $args[1]; + $this->A = array_fill(0, $this->m, array_fill(0, $this->n, 0)); + break; + //Rectangular matrix - m x n initialized from packed array + case 'array,integer': + $this->m = $args[1]; + if ($this->m != 0) { + $this->n = count($args[0]) / $this->m; + } else { + $this->n = 0; + } + if (($this->m * $this->n) == count($args[0])) { + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $args[0][$i + $j * $this->m]; + } + } + } else { + throw new PHPExcel_Calculation_Exception(self::ArrayLengthException); + } + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function __construct() + + + /** + * getArray + * + * @return array Matrix array + */ + public function getArray() { + return $this->A; + } // function getArray() + + + /** + * getRowDimension + * + * @return int Row dimension + */ + public function getRowDimension() { + return $this->m; + } // function getRowDimension() + + + /** + * getColumnDimension + * + * @return int Column dimension + */ + public function getColumnDimension() { + return $this->n; + } // function getColumnDimension() + + + /** + * get + * + * Get the i,j-th element of the matrix. + * @param int $i Row position + * @param int $j Column position + * @return mixed Element (int/float/double) + */ + public function get($i = null, $j = null) { + return $this->A[$i][$j]; + } // function get() + + + /** + * getMatrix + * + * Get a submatrix + * @param int $i0 Initial row index + * @param int $iF Final row index + * @param int $j0 Initial column index + * @param int $jF Final column index + * @return Matrix Submatrix + */ + public function getMatrix() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + //A($i0...; $j0...) + case 'integer,integer': + list($i0, $j0) = $args; + if ($i0 >= 0) { $m = $this->m - $i0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if ($j0 >= 0) { $n = $this->n - $j0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for($i = $i0; $i < $this->m; ++$i) { + for($j = $j0; $j < $this->n; ++$j) { + $R->set($i, $j, $this->A[$i][$j]); + } + } + return $R; + break; + //A($i0...$iF; $j0...$jF) + case 'integer,integer,integer,integer': + list($i0, $iF, $j0, $jF) = $args; + if (($iF > $i0) && ($this->m >= $iF) && ($i0 >= 0)) { $m = $iF - $i0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if (($jF > $j0) && ($this->n >= $jF) && ($j0 >= 0)) { $n = $jF - $j0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m+1, $n+1); + for($i = $i0; $i <= $iF; ++$i) { + for($j = $j0; $j <= $jF; ++$j) { + $R->set($i - $i0, $j - $j0, $this->A[$i][$j]); + } + } + return $R; + break; + //$R = array of row indices; $C = array of column indices + case 'array,array': + list($RL, $CL) = $args; + if (count($RL) > 0) { $m = count($RL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if (count($CL) > 0) { $n = count($CL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for($i = 0; $i < $m; ++$i) { + for($j = 0; $j < $n; ++$j) { + $R->set($i - $i0, $j - $j0, $this->A[$RL[$i]][$CL[$j]]); + } + } + return $R; + break; + //$RL = array of row indices; $CL = array of column indices + case 'array,array': + list($RL, $CL) = $args; + if (count($RL) > 0) { $m = count($RL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if (count($CL) > 0) { $n = count($CL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for($i = 0; $i < $m; ++$i) { + for($j = 0; $j < $n; ++$j) { + $R->set($i, $j, $this->A[$RL[$i]][$CL[$j]]); + } + } + return $R; + break; + //A($i0...$iF); $CL = array of column indices + case 'integer,integer,array': + list($i0, $iF, $CL) = $args; + if (($iF > $i0) && ($this->m >= $iF) && ($i0 >= 0)) { $m = $iF - $i0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if (count($CL) > 0) { $n = count($CL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for($i = $i0; $i < $iF; ++$i) { + for($j = 0; $j < $n; ++$j) { + $R->set($i - $i0, $j, $this->A[$RL[$i]][$j]); + } + } + return $R; + break; + //$RL = array of row indices + case 'array,integer,integer': + list($RL, $j0, $jF) = $args; + if (count($RL) > 0) { $m = count($RL); } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + if (($jF >= $j0) && ($this->n >= $jF) && ($j0 >= 0)) { $n = $jF - $j0; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentBoundsException); } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n+1); + for($i = 0; $i < $m; ++$i) { + for($j = $j0; $j <= $jF; ++$j) { + $R->set($i, $j - $j0, $this->A[$RL[$i]][$j]); + } + } + return $R; + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function getMatrix() + + + /** + * checkMatrixDimensions + * + * Is matrix B the same size? + * @param Matrix $B Matrix B + * @return boolean + */ + public function checkMatrixDimensions($B = null) { + if ($B instanceof PHPExcel_Shared_JAMA_Matrix) { + if (($this->m == $B->getRowDimension()) && ($this->n == $B->getColumnDimension())) { + return true; + } else { + throw new PHPExcel_Calculation_Exception(self::MatrixDimensionException); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); + } + } // function checkMatrixDimensions() + + + + /** + * set + * + * Set the i,j-th element of the matrix. + * @param int $i Row position + * @param int $j Column position + * @param mixed $c Int/float/double value + * @return mixed Element (int/float/double) + */ + public function set($i = null, $j = null, $c = null) { + // Optimized set version just has this + $this->A[$i][$j] = $c; + } // function set() + + + /** + * identity + * + * Generate an identity matrix. + * @param int $m Row dimension + * @param int $n Column dimension + * @return Matrix Identity matrix + */ + public function identity($m = null, $n = null) { + return $this->diagonal($m, $n, 1); + } // function identity() + + + /** + * diagonal + * + * Generate a diagonal matrix + * @param int $m Row dimension + * @param int $n Column dimension + * @param mixed $c Diagonal value + * @return Matrix Diagonal matrix + */ + public function diagonal($m = null, $n = null, $c = 1) { + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for($i = 0; $i < $m; ++$i) { + $R->set($i, $i, $c); + } + return $R; + } // function diagonal() + + + /** + * getMatrixByRow + * + * Get a submatrix by row index/range + * @param int $i0 Initial row index + * @param int $iF Final row index + * @return Matrix Submatrix + */ + public function getMatrixByRow($i0 = null, $iF = null) { + if (is_int($i0)) { + if (is_int($iF)) { + return $this->getMatrix($i0, 0, $iF + 1, $this->n); + } else { + return $this->getMatrix($i0, 0, $i0 + 1, $this->n); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); + } + } // function getMatrixByRow() + + + /** + * getMatrixByCol + * + * Get a submatrix by column index/range + * @param int $i0 Initial column index + * @param int $iF Final column index + * @return Matrix Submatrix + */ + public function getMatrixByCol($j0 = null, $jF = null) { + if (is_int($j0)) { + if (is_int($jF)) { + return $this->getMatrix(0, $j0, $this->m, $jF + 1); + } else { + return $this->getMatrix(0, $j0, $this->m, $j0 + 1); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); + } + } // function getMatrixByCol() + + + /** + * transpose + * + * Tranpose matrix + * @return Matrix Transposed matrix + */ + public function transpose() { + $R = new PHPExcel_Shared_JAMA_Matrix($this->n, $this->m); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $R->set($j, $i, $this->A[$i][$j]); + } + } + return $R; + } // function transpose() + + + /** + * trace + * + * Sum of diagonal elements + * @return float Sum of diagonal elements + */ + public function trace() { + $s = 0; + $n = min($this->m, $this->n); + for($i = 0; $i < $n; ++$i) { + $s += $this->A[$i][$i]; + } + return $s; + } // function trace() + + + /** + * uminus + * + * Unary minus matrix -A + * @return Matrix Unary minus matrix + */ + public function uminus() { + } // function uminus() + + + /** + * plus + * + * A + B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function plus() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) + $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function plus() + + + /** + * plusEquals + * + * A = A + B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function plusEquals() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $validValues = True; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value,'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] += $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function plusEquals() + + + /** + * minus + * + * A - B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function minus() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) - $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function minus() + + + /** + * minusEquals + * + * A = A - B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function minusEquals() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $validValues = True; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value,'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] -= $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function minusEquals() + + + /** + * arrayTimes + * + * Element-by-element multiplication + * Cij = Aij * Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Cij + */ + public function arrayTimes() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) * $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayTimes() + + + /** + * arrayTimesEquals + * + * Element-by-element multiplication + * Aij = Aij * Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayTimesEquals() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $validValues = True; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value,'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] *= $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayTimesEquals() + + + /** + * arrayRightDivide + * + * Element-by-element right division + * A / B + * @param Matrix $B Matrix B + * @return Matrix Division result + */ + public function arrayRightDivide() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $validValues = True; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value,'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + if ($value == 0) { + // Trap for Divide by Zero error + $M->set($i, $j, '#DIV/0!'); + } else { + $M->set($i, $j, $this->A[$i][$j] / $value); + } + } else { + $M->set($i, $j, PHPExcel_Calculation_Functions::NaN()); + } + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayRightDivide() + + + /** + * arrayRightDivideEquals + * + * Element-by-element right division + * Aij = Aij / Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayRightDivideEquals() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $this->A[$i][$j] / $M->get($i, $j); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayRightDivideEquals() + + + /** + * arrayLeftDivide + * + * Element-by-element Left division + * A / B + * @param Matrix $B Matrix B + * @return Matrix Division result + */ + public function arrayLeftDivide() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) / $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayLeftDivide() + + + /** + * arrayLeftDivideEquals + * + * Element-by-element Left division + * Aij = Aij / Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayLeftDivideEquals() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $M->get($i, $j) / $this->A[$i][$j]; + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function arrayLeftDivideEquals() + + + /** + * times + * + * Matrix multiplication + * @param mixed $n Matrix/Array/Scalar + * @return Matrix Product + */ + public function times() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $B = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + if ($this->n == $B->m) { + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $B->n); + for($j = 0; $j < $B->n; ++$j) { + for ($k = 0; $k < $this->n; ++$k) { + $Bcolj[$k] = $B->A[$k][$j]; + } + for($i = 0; $i < $this->m; ++$i) { + $Arowi = $this->A[$i]; + $s = 0; + for($k = 0; $k < $this->n; ++$k) { + $s += $Arowi[$k] * $Bcolj[$k]; + } + $C->A[$i][$j] = $s; + } + } + return $C; + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixDimensionMismatch)); + } + break; + case 'array': + $B = new PHPExcel_Shared_JAMA_Matrix($args[0]); + if ($this->n == $B->m) { + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $B->n); + for($i = 0; $i < $C->m; ++$i) { + for($j = 0; $j < $C->n; ++$j) { + $s = "0"; + for($k = 0; $k < $C->n; ++$k) { + $s += $this->A[$i][$k] * $B->A[$k][$j]; + } + $C->A[$i][$j] = $s; + } + } + return $C; + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixDimensionMismatch)); + } + return $M; + break; + case 'integer': + $C = new PHPExcel_Shared_JAMA_Matrix($this->A); + for($i = 0; $i < $C->m; ++$i) { + for($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] *= $args[0]; + } + } + return $C; + break; + case 'double': + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $this->n); + for($i = 0; $i < $C->m; ++$i) { + for($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] = $args[0] * $this->A[$i][$j]; + } + } + return $C; + break; + case 'float': + $C = new PHPExcel_Shared_JAMA_Matrix($this->A); + for($i = 0; $i < $C->m; ++$i) { + for($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] *= $args[0]; + } + } + return $C; + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function times() + + + /** + * power + * + * A = A ^ B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function power() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $validValues = True; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value,'"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] = pow($this->A[$i][$j],$value); + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function power() + + + /** + * concat + * + * A = A & B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function concat() { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { $M = $args[0]; } else { throw new PHPExcel_Calculation_Exception(self::ArgumentTypeException); } + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + break; + } + $this->checkMatrixDimensions($M); + for($i = 0; $i < $this->m; ++$i) { + for($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = trim($this->A[$i][$j],'"').trim($M->get($i, $j),'"'); + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::PolymorphicArgumentException); + } + } // function concat() + + + /** + * Solve A*X = B. + * + * @param Matrix $B Right hand side + * @return Matrix ... Solution if A is square, least squares solution otherwise + */ + public function solve($B) { + if ($this->m == $this->n) { + $LU = new PHPExcel_Shared_JAMA_LUDecomposition($this); + return $LU->solve($B); + } else { + $QR = new QRDecomposition($this); + return $QR->solve($B); + } + } // function solve() + + + /** + * Matrix inverse or pseudoinverse. + * + * @return Matrix ... Inverse(A) if A is square, pseudoinverse otherwise. + */ + public function inverse() { + return $this->solve($this->identity($this->m, $this->m)); + } // function inverse() + + + /** + * det + * + * Calculate determinant + * @return float Determinant + */ + public function det() { + $L = new PHPExcel_Shared_JAMA_LUDecomposition($this); + return $L->det(); + } // function det() + + +} // class PHPExcel_Shared_JAMA_Matrix diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php new file mode 100644 index 00000000..75384629 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php @@ -0,0 +1,234 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n + * orthogonal matrix Q and an n-by-n upper triangular matrix R so that + * A = Q*R. + * + * The QR decompostion always exists, even if the matrix does not have + * full rank, so the constructor will never fail. The primary use of the + * QR decomposition is in the least squares solution of nonsquare systems + * of simultaneous linear equations. This will fail if isFullRank() + * returns false. + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class PHPExcel_Shared_JAMA_QRDecomposition { + + const MatrixRankException = "Can only perform operation on full-rank matrix."; + + /** + * Array for internal storage of decomposition. + * @var array + */ + private $QR = array(); + + /** + * Row dimension. + * @var integer + */ + private $m; + + /** + * Column dimension. + * @var integer + */ + private $n; + + /** + * Array for internal storage of diagonal of R. + * @var array + */ + private $Rdiag = array(); + + + /** + * QR Decomposition computed by Householder reflections. + * + * @param matrix $A Rectangular matrix + * @return Structure to access R and the Householder vectors and compute Q. + */ + public function __construct($A) { + if($A instanceof PHPExcel_Shared_JAMA_Matrix) { + // Initialize. + $this->QR = $A->getArrayCopy(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + // Main loop. + for ($k = 0; $k < $this->n; ++$k) { + // Compute 2-norm of k-th column without under/overflow. + $nrm = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $nrm = hypo($nrm, $this->QR[$i][$k]); + } + if ($nrm != 0.0) { + // Form k-th Householder vector. + if ($this->QR[$k][$k] < 0) { + $nrm = -$nrm; + } + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$k] /= $nrm; + } + $this->QR[$k][$k] += 1.0; + // Apply transformation to remaining columns. + for ($j = $k+1; $j < $this->n; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $this->QR[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + $this->Rdiag[$k] = -$nrm; + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ArgumentTypeException); + } + } // function __construct() + + + /** + * Is the matrix full rank? + * + * @return boolean true if R, and hence A, has full rank, else false. + */ + public function isFullRank() { + for ($j = 0; $j < $this->n; ++$j) { + if ($this->Rdiag[$j] == 0) { + return false; + } + } + return true; + } // function isFullRank() + + + /** + * Return the Householder vectors + * + * @return Matrix Lower trapezoidal matrix whose columns define the reflections + */ + public function getH() { + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i >= $j) { + $H[$i][$j] = $this->QR[$i][$j]; + } else { + $H[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($H); + } // function getH() + + + /** + * Return the upper triangular factor + * + * @return Matrix upper triangular factor + */ + public function getR() { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i < $j) { + $R[$i][$j] = $this->QR[$i][$j]; + } elseif ($i == $j) { + $R[$i][$j] = $this->Rdiag[$i]; + } else { + $R[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($R); + } // function getR() + + + /** + * Generate and return the (economy-sized) orthogonal factor + * + * @return Matrix orthogonal factor + */ + public function getQ() { + for ($k = $this->n-1; $k >= 0; --$k) { + for ($i = 0; $i < $this->m; ++$i) { + $Q[$i][$k] = 0.0; + } + $Q[$k][$k] = 1.0; + for ($j = $k; $j < $this->n; ++$j) { + if ($this->QR[$k][$k] != 0) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $Q[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $Q[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + } + /* + for($i = 0; $i < count($Q); ++$i) { + for($j = 0; $j < count($Q); ++$j) { + if(! isset($Q[$i][$j]) ) { + $Q[$i][$j] = 0; + } + } + } + */ + return new PHPExcel_Shared_JAMA_Matrix($Q); + } // function getQ() + + + /** + * Least squares solution of A*X = B + * + * @param Matrix $B A Matrix with as many rows as A and any number of columns. + * @return Matrix Matrix that minimizes the two norm of Q*R*X-B. + */ + public function solve($B) { + if ($B->getRowDimension() == $this->m) { + if ($this->isFullRank()) { + // Copy right hand side + $nx = $B->getColumnDimension(); + $X = $B->getArrayCopy(); + // Compute Y = transpose(Q)*B + for ($k = 0; $k < $this->n; ++$k) { + for ($j = 0; $j < $nx; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $X[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $X[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + // Solve R*X = Y; + for ($k = $this->n-1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->Rdiag[$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j]* $this->QR[$i][$k]; + } + } + } + $X = new PHPExcel_Shared_JAMA_Matrix($X); + return ($X->getMatrix(0, $this->n-1, 0, $nx)); + } else { + throw new PHPExcel_Calculation_Exception(self::MatrixRankException); + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MatrixDimensionException); + } + } // function solve() + +} // PHPExcel_Shared_JAMA_class QRDecomposition diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php new file mode 100644 index 00000000..a4b096c5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php @@ -0,0 +1,526 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the singular value decomposition is + * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and + * an n-by-n orthogonal matrix V so that A = U*S*V'. + * + * The singular values, sigma[$k] = S[$k][$k], are ordered so that + * sigma[0] >= sigma[1] >= ... >= sigma[n-1]. + * + * The singular value decompostion always exists, so the constructor will + * never fail. The matrix condition number and the effective numerical + * rank can be computed from this decomposition. + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class SingularValueDecomposition { + + /** + * Internal storage of U. + * @var array + */ + private $U = array(); + + /** + * Internal storage of V. + * @var array + */ + private $V = array(); + + /** + * Internal storage of singular values. + * @var array + */ + private $s = array(); + + /** + * Row dimension. + * @var int + */ + private $m; + + /** + * Column dimension. + * @var int + */ + private $n; + + + /** + * Construct the singular value decomposition + * + * Derived from LINPACK code. + * + * @param $A Rectangular matrix + * @return Structure to access U, S and V. + */ + public function __construct($Arg) { + + // Initialize. + $A = $Arg->getArrayCopy(); + $this->m = $Arg->getRowDimension(); + $this->n = $Arg->getColumnDimension(); + $nu = min($this->m, $this->n); + $e = array(); + $work = array(); + $wantu = true; + $wantv = true; + $nct = min($this->m - 1, $this->n); + $nrt = max(0, min($this->n - 2, $this->m)); + + // Reduce A to bidiagonal form, storing the diagonal elements + // in s and the super-diagonal elements in e. + for ($k = 0; $k < max($nct,$nrt); ++$k) { + + if ($k < $nct) { + // Compute the transformation for the k-th column and + // place the k-th diagonal in s[$k]. + // Compute 2-norm of k-th column without under/overflow. + $this->s[$k] = 0; + for ($i = $k; $i < $this->m; ++$i) { + $this->s[$k] = hypo($this->s[$k], $A[$i][$k]); + } + if ($this->s[$k] != 0.0) { + if ($A[$k][$k] < 0.0) { + $this->s[$k] = -$this->s[$k]; + } + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$k] /= $this->s[$k]; + } + $A[$k][$k] += 1.0; + } + $this->s[$k] = -$this->s[$k]; + } + + for ($j = $k + 1; $j < $this->n; ++$j) { + if (($k < $nct) & ($this->s[$k] != 0.0)) { + // Apply the transformation. + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $A[$i][$k] * $A[$i][$j]; + } + $t = -$t / $A[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $A[$i][$k]; + } + // Place the k-th row of A into e for the + // subsequent calculation of the row transformation. + $e[$j] = $A[$k][$j]; + } + } + + if ($wantu AND ($k < $nct)) { + // Place the transformation in U for subsequent back + // multiplication. + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$k] = $A[$i][$k]; + } + } + + if ($k < $nrt) { + // Compute the k-th row transformation and place the + // k-th super-diagonal in e[$k]. + // Compute 2-norm without under/overflow. + $e[$k] = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$k] = hypo($e[$k], $e[$i]); + } + if ($e[$k] != 0.0) { + if ($e[$k+1] < 0.0) { + $e[$k] = -$e[$k]; + } + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$i] /= $e[$k]; + } + $e[$k+1] += 1.0; + } + $e[$k] = -$e[$k]; + if (($k+1 < $this->m) AND ($e[$k] != 0.0)) { + // Apply the transformation. + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] = 0.0; + } + for ($j = $k+1; $j < $this->n; ++$j) { + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] += $e[$j] * $A[$i][$j]; + } + } + for ($j = $k + 1; $j < $this->n; ++$j) { + $t = -$e[$j] / $e[$k+1]; + for ($i = $k + 1; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $work[$i]; + } + } + } + if ($wantv) { + // Place the transformation in V for subsequent + // back multiplication. + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$k] = $e[$i]; + } + } + } + } + + // Set up the final bidiagonal matrix or order p. + $p = min($this->n, $this->m + 1); + if ($nct < $this->n) { + $this->s[$nct] = $A[$nct][$nct]; + } + if ($this->m < $p) { + $this->s[$p-1] = 0.0; + } + if ($nrt + 1 < $p) { + $e[$nrt] = $A[$nrt][$p-1]; + } + $e[$p-1] = 0.0; + // If required, generate U. + if ($wantu) { + for ($j = $nct; $j < $nu; ++$j) { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$j] = 0.0; + } + $this->U[$j][$j] = 1.0; + } + for ($k = $nct - 1; $k >= 0; --$k) { + if ($this->s[$k] != 0.0) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $this->U[$i][$k] * $this->U[$i][$j]; + } + $t = -$t / $this->U[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$j] += $t * $this->U[$i][$k]; + } + } + for ($i = $k; $i < $this->m; ++$i ) { + $this->U[$i][$k] = -$this->U[$i][$k]; + } + $this->U[$k][$k] = 1.0 + $this->U[$k][$k]; + for ($i = 0; $i < $k - 1; ++$i) { + $this->U[$i][$k] = 0.0; + } + } else { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$k] = 0.0; + } + $this->U[$k][$k] = 1.0; + } + } + } + + // If required, generate V. + if ($wantv) { + for ($k = $this->n - 1; $k >= 0; --$k) { + if (($k < $nrt) AND ($e[$k] != 0.0)) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $t += $this->V[$i][$k]* $this->V[$i][$j]; + } + $t = -$t / $this->V[$k+1][$k]; + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$j] += $t * $this->V[$i][$k]; + } + } + } + for ($i = 0; $i < $this->n; ++$i) { + $this->V[$i][$k] = 0.0; + } + $this->V[$k][$k] = 1.0; + } + } + + // Main iteration loop for the singular values. + $pp = $p - 1; + $iter = 0; + $eps = pow(2.0, -52.0); + + while ($p > 0) { + // Here is where a test for too many iterations would go. + // This section of the program inspects for negligible + // elements in the s and e arrays. On completion the + // variables kase and k are set as follows: + // kase = 1 if s(p) and e[k-1] are negligible and k<p + // kase = 2 if s(k) is negligible and k<p + // kase = 3 if e[k-1] is negligible, k<p, and + // s(k), ..., s(p) are not negligible (qr step). + // kase = 4 if e(p-1) is negligible (convergence). + for ($k = $p - 2; $k >= -1; --$k) { + if ($k == -1) { + break; + } + if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { + $e[$k] = 0.0; + break; + } + } + if ($k == $p - 2) { + $kase = 4; + } else { + for ($ks = $p - 1; $ks >= $k; --$ks) { + if ($ks == $k) { + break; + } + $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); + if (abs($this->s[$ks]) <= $eps * $t) { + $this->s[$ks] = 0.0; + break; + } + } + if ($ks == $k) { + $kase = 3; + } else if ($ks == $p-1) { + $kase = 1; + } else { + $kase = 2; + $k = $ks; + } + } + ++$k; + + // Perform the task indicated by kase. + switch ($kase) { + // Deflate negligible s(p). + case 1: + $f = $e[$p-2]; + $e[$p-2] = 0.0; + for ($j = $p - 2; $j >= $k; --$j) { + $t = hypo($this->s[$j],$f); + $cs = $this->s[$j] / $t; + $sn = $f / $t; + $this->s[$j] = $t; + if ($j != $k) { + $f = -$sn * $e[$j-1]; + $e[$j-1] = $cs * $e[$j-1]; + } + if ($wantv) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1]; + $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1]; + $this->V[$i][$j] = $t; + } + } + } + break; + // Split at negligible s(k). + case 2: + $f = $e[$k-1]; + $e[$k-1] = 0.0; + for ($j = $k; $j < $p; ++$j) { + $t = hypo($this->s[$j], $f); + $cs = $this->s[$j] / $t; + $sn = $f / $t; + $this->s[$j] = $t; + $f = -$sn * $e[$j]; + $e[$j] = $cs * $e[$j]; + if ($wantu) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1]; + $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1]; + $this->U[$i][$j] = $t; + } + } + } + break; + // Perform one qr step. + case 3: + // Calculate the shift. + $scale = max(max(max(max( + abs($this->s[$p-1]),abs($this->s[$p-2])),abs($e[$p-2])), + abs($this->s[$k])), abs($e[$k])); + $sp = $this->s[$p-1] / $scale; + $spm1 = $this->s[$p-2] / $scale; + $epm1 = $e[$p-2] / $scale; + $sk = $this->s[$k] / $scale; + $ek = $e[$k] / $scale; + $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; + $c = ($sp * $epm1) * ($sp * $epm1); + $shift = 0.0; + if (($b != 0.0) || ($c != 0.0)) { + $shift = sqrt($b * $b + $c); + if ($b < 0.0) { + $shift = -$shift; + } + $shift = $c / ($b + $shift); + } + $f = ($sk + $sp) * ($sk - $sp) + $shift; + $g = $sk * $ek; + // Chase zeros. + for ($j = $k; $j < $p-1; ++$j) { + $t = hypo($f,$g); + $cs = $f/$t; + $sn = $g/$t; + if ($j != $k) { + $e[$j-1] = $t; + } + $f = $cs * $this->s[$j] + $sn * $e[$j]; + $e[$j] = $cs * $e[$j] - $sn * $this->s[$j]; + $g = $sn * $this->s[$j+1]; + $this->s[$j+1] = $cs * $this->s[$j+1]; + if ($wantv) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1]; + $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1]; + $this->V[$i][$j] = $t; + } + } + $t = hypo($f,$g); + $cs = $f/$t; + $sn = $g/$t; + $this->s[$j] = $t; + $f = $cs * $e[$j] + $sn * $this->s[$j+1]; + $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1]; + $g = $sn * $e[$j+1]; + $e[$j+1] = $cs * $e[$j+1]; + if ($wantu && ($j < $this->m - 1)) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1]; + $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1]; + $this->U[$i][$j] = $t; + } + } + } + $e[$p-2] = $f; + $iter = $iter + 1; + break; + // Convergence. + case 4: + // Make the singular values positive. + if ($this->s[$k] <= 0.0) { + $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0); + if ($wantv) { + for ($i = 0; $i <= $pp; ++$i) { + $this->V[$i][$k] = -$this->V[$i][$k]; + } + } + } + // Order the singular values. + while ($k < $pp) { + if ($this->s[$k] >= $this->s[$k+1]) { + break; + } + $t = $this->s[$k]; + $this->s[$k] = $this->s[$k+1]; + $this->s[$k+1] = $t; + if ($wantv AND ($k < $this->n - 1)) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $this->V[$i][$k+1]; + $this->V[$i][$k+1] = $this->V[$i][$k]; + $this->V[$i][$k] = $t; + } + } + if ($wantu AND ($k < $this->m-1)) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $this->U[$i][$k+1]; + $this->U[$i][$k+1] = $this->U[$i][$k]; + $this->U[$i][$k] = $t; + } + } + ++$k; + } + $iter = 0; + --$p; + break; + } // end switch + } // end while + + } // end constructor + + + /** + * Return the left singular vectors + * + * @access public + * @return U + */ + public function getU() { + return new Matrix($this->U, $this->m, min($this->m + 1, $this->n)); + } + + + /** + * Return the right singular vectors + * + * @access public + * @return V + */ + public function getV() { + return new Matrix($this->V); + } + + + /** + * Return the one-dimensional array of singular values + * + * @access public + * @return diagonal of S. + */ + public function getSingularValues() { + return $this->s; + } + + + /** + * Return the diagonal matrix of singular values + * + * @access public + * @return S + */ + public function getS() { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $S[$i][$j] = 0.0; + } + $S[$i][$i] = $this->s[$i]; + } + return new Matrix($S); + } + + + /** + * Two norm + * + * @access public + * @return max(S) + */ + public function norm2() { + return $this->s[0]; + } + + + /** + * Two norm condition number + * + * @access public + * @return max(S)/min(S) + */ + public function cond() { + return $this->s[0] / $this->s[min($this->m, $this->n) - 1]; + } + + + /** + * Effective numerical matrix rank + * + * @access public + * @return Number of nonnegligible singular values. + */ + public function rank() { + $eps = pow(2.0, -52.0); + $tol = max($this->m, $this->n) * $this->s[0] * $eps; + $r = 0; + for ($i = 0; $i < count($this->s); ++$i) { + if ($this->s[$i] > $tol) { + ++$r; + } + } + return $r; + } + +} // class SingularValueDecomposition diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php new file mode 100644 index 00000000..e73252b3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php @@ -0,0 +1,82 @@ +<?php +/** + * @package JAMA + * + * Error handling + * @author Michael Bommarito + * @version 01292005 + */ + +//Language constant +define('JAMALANG', 'EN'); + + +//All errors may be defined by the following format: +//define('ExceptionName', N); +//$error['lang'][ExceptionName] = 'Error message'; +$error = array(); + +/* +I've used Babelfish and a little poor knowledge of Romance/Germanic languages for the translations here. +Feel free to correct anything that looks amiss to you. +*/ + +define('PolymorphicArgumentException', -1); +$error['EN'][PolymorphicArgumentException] = "Invalid argument pattern for polymorphic function."; +$error['FR'][PolymorphicArgumentException] = "Modèle inadmissible d'argument pour la fonction polymorphe.". +$error['DE'][PolymorphicArgumentException] = "Unzulässiges Argumentmuster für polymorphe Funktion."; + +define('ArgumentTypeException', -2); +$error['EN'][ArgumentTypeException] = "Invalid argument type."; +$error['FR'][ArgumentTypeException] = "Type inadmissible d'argument."; +$error['DE'][ArgumentTypeException] = "Unzulässige Argumentart."; + +define('ArgumentBoundsException', -3); +$error['EN'][ArgumentBoundsException] = "Invalid argument range."; +$error['FR'][ArgumentBoundsException] = "Gamme inadmissible d'argument."; +$error['DE'][ArgumentBoundsException] = "Unzulässige Argumentstrecke."; + +define('MatrixDimensionException', -4); +$error['EN'][MatrixDimensionException] = "Matrix dimensions are not equal."; +$error['FR'][MatrixDimensionException] = "Les dimensions de Matrix ne sont pas égales."; +$error['DE'][MatrixDimensionException] = "Matrixmaße sind nicht gleich."; + +define('PrecisionLossException', -5); +$error['EN'][PrecisionLossException] = "Significant precision loss detected."; +$error['FR'][PrecisionLossException] = "Perte significative de précision détectée."; +$error['DE'][PrecisionLossException] = "Bedeutender Präzision Verlust ermittelte."; + +define('MatrixSPDException', -6); +$error['EN'][MatrixSPDException] = "Can only perform operation on symmetric positive definite matrix."; +$error['FR'][MatrixSPDException] = "Perte significative de précision détectée."; +$error['DE'][MatrixSPDException] = "Bedeutender Präzision Verlust ermittelte."; + +define('MatrixSingularException', -7); +$error['EN'][MatrixSingularException] = "Can only perform operation on singular matrix."; + +define('MatrixRankException', -8); +$error['EN'][MatrixRankException] = "Can only perform operation on full-rank matrix."; + +define('ArrayLengthException', -9); +$error['EN'][ArrayLengthException] = "Array length must be a multiple of m."; + +define('RowLengthException', -10); +$error['EN'][RowLengthException] = "All rows must have the same length."; + +/** + * Custom error handler + * @param int $num Error number + */ +function JAMAError($errorNumber = null) { + global $error; + + if (isset($errorNumber)) { + if (isset($error[JAMALANG][$errorNumber])) { + return $error[JAMALANG][$errorNumber]; + } else { + return $error['EN'][$errorNumber]; + } + } else { + return ("Invalid argument to JAMAError()"); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php new file mode 100644 index 00000000..aa09a8bb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php @@ -0,0 +1,43 @@ +<?php +/** + * @package JAMA + * + * Pythagorean Theorem: + * + * a = 3 + * b = 4 + * r = sqrt(square(a) + square(b)) + * r = 5 + * + * r = sqrt(a^2 + b^2) without under/overflow. + */ +function hypo($a, $b) { + if (abs($a) > abs($b)) { + $r = $b / $a; + $r = abs($a) * sqrt(1 + $r * $r); + } elseif ($b != 0) { + $r = $a / $b; + $r = abs($b) * sqrt(1 + $r * $r); + } else { + $r = 0.0; + } + return $r; +} // function hypo() + + +/** + * Mike Bommarito's version. + * Compute n-dimensional hyotheneuse. + * +function hypot() { + $s = 0; + foreach (func_get_args() as $d) { + if (is_numeric($d)) { + $s += pow($d, 2); + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ArgumentTypeException)); + } + } + return sqrt($s); +} +*/ diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php new file mode 100644 index 00000000..9796282a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php @@ -0,0 +1,531 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: OLE.php,v 1.13 2007/03/07 14:38:25 schmidt Exp $ + + +/** +* Array for storing OLE instances that are accessed from +* OLE_ChainedBlockStream::stream_open(). +* @var array +*/ +$GLOBALS['_OLE_INSTANCES'] = array(); + +/** +* OLE package base class. +* +* @author Xavier Noguer <xnoguer@php.net> +* @author Christian Schmidt <schmidt@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE +{ + const OLE_PPS_TYPE_ROOT = 5; + const OLE_PPS_TYPE_DIR = 1; + const OLE_PPS_TYPE_FILE = 2; + const OLE_DATA_SIZE_SMALL = 0x1000; + const OLE_LONG_INT_SIZE = 4; + const OLE_PPS_SIZE = 0x80; + + /** + * The file handle for reading an OLE container + * @var resource + */ + public $_file_handle; + + /** + * Array of PPS's found on the OLE container + * @var array + */ + public $_list = array(); + + /** + * Root directory of OLE container + * @var OLE_PPS_Root + */ + public $root; + + /** + * Big Block Allocation Table + * @var array (blockId => nextBlockId) + */ + public $bbat; + + /** + * Short Block Allocation Table + * @var array (blockId => nextBlockId) + */ + public $sbat; + + /** + * Size of big blocks. This is usually 512. + * @var int number of octets per block. + */ + public $bigBlockSize; + + /** + * Size of small blocks. This is usually 64. + * @var int number of octets per block + */ + public $smallBlockSize; + + /** + * Reads an OLE container from the contents of the file given. + * + * @acces public + * @param string $file + * @return mixed true on success, PEAR_Error on failure + */ + public function read($file) + { + $fh = fopen($file, "r"); + if (!$fh) { + throw new PHPExcel_Reader_Exception("Can't open file $file"); + } + $this->_file_handle = $fh; + + $signature = fread($fh, 8); + if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) { + throw new PHPExcel_Reader_Exception("File doesn't seem to be an OLE container."); + } + fseek($fh, 28); + if (fread($fh, 2) != "\xFE\xFF") { + // This shouldn't be a problem in practice + throw new PHPExcel_Reader_Exception("Only Little-Endian encoding is supported."); + } + // Size of blocks and short blocks in bytes + $this->bigBlockSize = pow(2, self::_readInt2($fh)); + $this->smallBlockSize = pow(2, self::_readInt2($fh)); + + // Skip UID, revision number and version number + fseek($fh, 44); + // Number of blocks in Big Block Allocation Table + $bbatBlockCount = self::_readInt4($fh); + + // Root chain 1st block + $directoryFirstBlockId = self::_readInt4($fh); + + // Skip unused bytes + fseek($fh, 56); + // Streams shorter than this are stored using small blocks + $this->bigBlockThreshold = self::_readInt4($fh); + // Block id of first sector in Short Block Allocation Table + $sbatFirstBlockId = self::_readInt4($fh); + // Number of blocks in Short Block Allocation Table + $sbbatBlockCount = self::_readInt4($fh); + // Block id of first sector in Master Block Allocation Table + $mbatFirstBlockId = self::_readInt4($fh); + // Number of blocks in Master Block Allocation Table + $mbbatBlockCount = self::_readInt4($fh); + $this->bbat = array(); + + // Remaining 4 * 109 bytes of current block is beginning of Master + // Block Allocation Table + $mbatBlocks = array(); + for ($i = 0; $i < 109; ++$i) { + $mbatBlocks[] = self::_readInt4($fh); + } + + // Read rest of Master Block Allocation Table (if any is left) + $pos = $this->_getBlockOffset($mbatFirstBlockId); + for ($i = 0; $i < $mbbatBlockCount; ++$i) { + fseek($fh, $pos); + for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) { + $mbatBlocks[] = self::_readInt4($fh); + } + // Last block id in each block points to next block + $pos = $this->_getBlockOffset(self::_readInt4($fh)); + } + + // Read Big Block Allocation Table according to chain specified by + // $mbatBlocks + for ($i = 0; $i < $bbatBlockCount; ++$i) { + $pos = $this->_getBlockOffset($mbatBlocks[$i]); + fseek($fh, $pos); + for ($j = 0 ; $j < $this->bigBlockSize / 4; ++$j) { + $this->bbat[] = self::_readInt4($fh); + } + } + + // Read short block allocation table (SBAT) + $this->sbat = array(); + $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; + $sbatFh = $this->getStream($sbatFirstBlockId); + for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { + $this->sbat[$blockId] = self::_readInt4($sbatFh); + } + fclose($sbatFh); + + $this->_readPpsWks($directoryFirstBlockId); + + return true; + } + + /** + * @param int block id + * @param int byte offset from beginning of file + * @access public + */ + public function _getBlockOffset($blockId) + { + return 512 + $blockId * $this->bigBlockSize; + } + + /** + * Returns a stream for use with fread() etc. External callers should + * use PHPExcel_Shared_OLE_PPS_File::getStream(). + * @param int|PPS block id or PPS + * @return resource read-only stream + */ + public function getStream($blockIdOrPps) + { + static $isRegistered = false; + if (!$isRegistered) { + stream_wrapper_register('ole-chainedblockstream', + 'PHPExcel_Shared_OLE_ChainedBlockStream'); + $isRegistered = true; + } + + // Store current instance in global array, so that it can be accessed + // in OLE_ChainedBlockStream::stream_open(). + // Object is removed from self::$instances in OLE_Stream::close(). + $GLOBALS['_OLE_INSTANCES'][] = $this; + $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES'])); + + $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; + if ($blockIdOrPps instanceof PHPExcel_Shared_OLE_PPS) { + $path .= '&blockId=' . $blockIdOrPps->_StartBlock; + $path .= '&size=' . $blockIdOrPps->Size; + } else { + $path .= '&blockId=' . $blockIdOrPps; + } + return fopen($path, 'r'); + } + + /** + * Reads a signed char. + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt1($fh) + { + list(, $tmp) = unpack("c", fread($fh, 1)); + return $tmp; + } + + /** + * Reads an unsigned short (2 octets). + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt2($fh) + { + list(, $tmp) = unpack("v", fread($fh, 2)); + return $tmp; + } + + /** + * Reads an unsigned long (4 octets). + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt4($fh) + { + list(, $tmp) = unpack("V", fread($fh, 4)); + return $tmp; + } + + /** + * Gets information about all PPS's on the OLE container from the PPS WK's + * creates an OLE_PPS object for each one. + * + * @access public + * @param integer the block id of the first block + * @return mixed true on success, PEAR_Error on failure + */ + public function _readPpsWks($blockId) + { + $fh = $this->getStream($blockId); + for ($pos = 0; ; $pos += 128) { + fseek($fh, $pos, SEEK_SET); + $nameUtf16 = fread($fh, 64); + $nameLength = self::_readInt2($fh); + $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); + // Simple conversion from UTF-16LE to ISO-8859-1 + $name = str_replace("\x00", "", $nameUtf16); + $type = self::_readInt1($fh); + switch ($type) { + case self::OLE_PPS_TYPE_ROOT: + $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array()); + $this->root = $pps; + break; + case self::OLE_PPS_TYPE_DIR: + $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, + null, null, null, null, array()); + break; + case self::OLE_PPS_TYPE_FILE: + $pps = new PHPExcel_Shared_OLE_PPS_File($name); + break; + default: + continue; + } + fseek($fh, 1, SEEK_CUR); + $pps->Type = $type; + $pps->Name = $name; + $pps->PrevPps = self::_readInt4($fh); + $pps->NextPps = self::_readInt4($fh); + $pps->DirPps = self::_readInt4($fh); + fseek($fh, 20, SEEK_CUR); + $pps->Time1st = self::OLE2LocalDate(fread($fh, 8)); + $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8)); + $pps->_StartBlock = self::_readInt4($fh); + $pps->Size = self::_readInt4($fh); + $pps->No = count($this->_list); + $this->_list[] = $pps; + + // check if the PPS tree (starting from root) is complete + if (isset($this->root) && + $this->_ppsTreeComplete($this->root->No)) { + + break; + } + } + fclose($fh); + + // Initialize $pps->children on directories + foreach ($this->_list as $pps) { + if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) { + $nos = array($pps->DirPps); + $pps->children = array(); + while ($nos) { + $no = array_pop($nos); + if ($no != -1) { + $childPps = $this->_list[$no]; + $nos[] = $childPps->PrevPps; + $nos[] = $childPps->NextPps; + $pps->children[] = $childPps; + } + } + } + } + + return true; + } + + /** + * It checks whether the PPS tree is complete (all PPS's read) + * starting with the given PPS (not necessarily root) + * + * @access public + * @param integer $index The index of the PPS from which we are checking + * @return boolean Whether the PPS tree for the given PPS is complete + */ + public function _ppsTreeComplete($index) + { + return isset($this->_list[$index]) && + ($pps = $this->_list[$index]) && + ($pps->PrevPps == -1 || + $this->_ppsTreeComplete($pps->PrevPps)) && + ($pps->NextPps == -1 || + $this->_ppsTreeComplete($pps->NextPps)) && + ($pps->DirPps == -1 || + $this->_ppsTreeComplete($pps->DirPps)); + } + + /** + * Checks whether a PPS is a File PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @access public + * @param integer $index The index for the PPS + * @return bool true if it's a File PPS, false otherwise + */ + public function isFile($index) + { + if (isset($this->_list[$index])) { + return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE); + } + return false; + } + + /** + * Checks whether a PPS is a Root PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @access public + * @param integer $index The index for the PPS. + * @return bool true if it's a Root PPS, false otherwise + */ + public function isRoot($index) + { + if (isset($this->_list[$index])) { + return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT); + } + return false; + } + + /** + * Gives the total number of PPS's found in the OLE container. + * + * @access public + * @return integer The total number of PPS's found in the OLE container + */ + public function ppsTotal() + { + return count($this->_list); + } + + /** + * Gets data from a PPS + * If there is no PPS for the index given, it will return an empty string. + * + * @access public + * @param integer $index The index for the PPS + * @param integer $position The position from which to start reading + * (relative to the PPS) + * @param integer $length The amount of bytes to read (at most) + * @return string The binary string containing the data requested + * @see OLE_PPS_File::getStream() + */ + public function getData($index, $position, $length) + { + // if position is not valid return empty string + if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) { + return ''; + } + $fh = $this->getStream($this->_list[$index]); + $data = stream_get_contents($fh, $length, $position); + fclose($fh); + return $data; + } + + /** + * Gets the data length from a PPS + * If there is no PPS for the index given, it will return 0. + * + * @access public + * @param integer $index The index for the PPS + * @return integer The amount of bytes in data the PPS has + */ + public function getDataLength($index) + { + if (isset($this->_list[$index])) { + return $this->_list[$index]->Size; + } + return 0; + } + + /** + * Utility function to transform ASCII text to Unicode + * + * @access public + * @static + * @param string $ascii The ASCII string to transform + * @return string The string in Unicode + */ + public static function Asc2Ucs($ascii) + { + $rawname = ''; + for ($i = 0; $i < strlen($ascii); ++$i) { + $rawname .= $ascii{$i} . "\x00"; + } + return $rawname; + } + + /** + * Utility function + * Returns a string for the OLE container with the date given + * + * @access public + * @static + * @param integer $date A timestamp + * @return string The string for the OLE container + */ + public static function LocalDate2OLE($date = null) + { + if (!isset($date)) { + return "\x00\x00\x00\x00\x00\x00\x00\x00"; + } + + // factor used for separating numbers into 4 bytes parts + $factor = pow(2, 32); + + // days from 1-1-1601 until the beggining of UNIX era + $days = 134774; + // calculate seconds + $big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date), + date("m",$date),date("d",$date),date("Y",$date)); + // multiply just to make MS happy + $big_date *= 10000000; + + $high_part = floor($big_date / $factor); + // lower 4 bytes + $low_part = floor((($big_date / $factor) - $high_part) * $factor); + + // Make HEX string + $res = ''; + + for ($i = 0; $i < 4; ++$i) { + $hex = $low_part % 0x100; + $res .= pack('c', $hex); + $low_part /= 0x100; + } + for ($i = 0; $i < 4; ++$i) { + $hex = $high_part % 0x100; + $res .= pack('c', $hex); + $high_part /= 0x100; + } + return $res; + } + + /** + * Returns a timestamp from an OLE container's date + * + * @access public + * @static + * @param integer $string A binary string with the encoded date + * @return string The timestamp corresponding to the string + */ + public static function OLE2LocalDate($string) + { + if (strlen($string) != 8) { + return new PEAR_Error("Expecting 8 byte string"); + } + + // factor used for separating numbers into 4 bytes parts + $factor = pow(2,32); + list(, $high_part) = unpack('V', substr($string, 4, 4)); + list(, $low_part) = unpack('V', substr($string, 0, 4)); + + $big_date = ($high_part * $factor) + $low_part; + // translate to seconds + $big_date /= 10000000; + + // days from 1-1-1601 until the beggining of UNIX era + $days = 134774; + + // translate to seconds from beggining of UNIX era + $big_date -= $days * 24 * 3600; + return floor($big_date); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php new file mode 100644 index 00000000..3dcd7e1d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php @@ -0,0 +1,230 @@ +<?php +/** + * PHPExcel + * + * Copyright (C) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_OLE + * @copyright Copyright (c) 2006 - 2007 Christian Schmidt + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +/** + * PHPExcel_Shared_OLE_ChainedBlockStream + * + * Stream wrapper for reading data stored in an OLE file. Implements methods + * for PHP's stream_wrapper_register(). For creating streams using this + * wrapper, use PHPExcel_Shared_OLE_PPS_File::getStream(). + * + * @category PHPExcel + * @package PHPExcel_Shared_OLE + */ +class PHPExcel_Shared_OLE_ChainedBlockStream +{ + /** + * The OLE container of the file that is being read. + * @var OLE + */ + public $ole; + + /** + * Parameters specified by fopen(). + * @var array + */ + public $params; + + /** + * The binary data of the file. + * @var string + */ + public $data; + + /** + * The file pointer. + * @var int byte offset + */ + public $pos; + + /** + * Implements support for fopen(). + * For creating streams using this wrapper, use OLE_PPS_File::getStream(). + * + * @param string $path resource name including scheme, e.g. + * ole-chainedblockstream://oleInstanceId=1 + * @param string $mode only "r" is supported + * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH + * @param string &$openedPath absolute path of the opened stream (out parameter) + * @return bool true on success + */ + public function stream_open($path, $mode, $options, &$openedPath) + { + if ($mode != 'r') { + if ($options & STREAM_REPORT_ERRORS) { + trigger_error('Only reading is supported', E_USER_WARNING); + } + return false; + } + + // 25 is length of "ole-chainedblockstream://" + parse_str(substr($path, 25), $this->params); + if (!isset($this->params['oleInstanceId'], + $this->params['blockId'], + $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { + + if ($options & STREAM_REPORT_ERRORS) { + trigger_error('OLE stream not found', E_USER_WARNING); + } + return false; + } + $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; + + $blockId = $this->params['blockId']; + $this->data = ''; + if (isset($this->params['size']) && + $this->params['size'] < $this->ole->bigBlockThreshold && + $blockId != $this->ole->root->_StartBlock) { + + // Block id refers to small blocks + $rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock); + while ($blockId != -2) { + $pos = $rootPos + $blockId * $this->ole->bigBlockSize; + $blockId = $this->ole->sbat[$blockId]; + fseek($this->ole->_file_handle, $pos); + $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); + } + } else { + // Block id refers to big blocks + while ($blockId != -2) { + $pos = $this->ole->_getBlockOffset($blockId); + fseek($this->ole->_file_handle, $pos); + $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); + $blockId = $this->ole->bbat[$blockId]; + } + } + if (isset($this->params['size'])) { + $this->data = substr($this->data, 0, $this->params['size']); + } + + if ($options & STREAM_USE_PATH) { + $openedPath = $path; + } + + return true; + } + + /** + * Implements support for fclose(). + * + */ + public function stream_close() + { + $this->ole = null; + unset($GLOBALS['_OLE_INSTANCES']); + } + + /** + * Implements support for fread(), fgets() etc. + * + * @param int $count maximum number of bytes to read + * @return string + */ + public function stream_read($count) + { + if ($this->stream_eof()) { + return false; + } + $s = substr($this->data, $this->pos, $count); + $this->pos += $count; + return $s; + } + + /** + * Implements support for feof(). + * + * @return bool TRUE if the file pointer is at EOF; otherwise FALSE + */ + public function stream_eof() + { +// As we don't support below 5.2 anymore, this is simply redundancy and overhead +// $eof = $this->pos >= strlen($this->data); +// // Workaround for bug in PHP 5.0.x: http://bugs.php.net/27508 +// if (version_compare(PHP_VERSION, '5.0', '>=') && +// version_compare(PHP_VERSION, '5.1', '<')) { +// $eof = !$eof; +// } +// return $eof; + return $this->pos >= strlen($this->data); + } + + /** + * Returns the position of the file pointer, i.e. its offset into the file + * stream. Implements support for ftell(). + * + * @return int + */ + public function stream_tell() + { + return $this->pos; + } + + /** + * Implements support for fseek(). + * + * @param int $offset byte offset + * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END + * @return bool + */ + public function stream_seek($offset, $whence) + { + if ($whence == SEEK_SET && $offset >= 0) { + $this->pos = $offset; + } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) { + $this->pos += $offset; + } elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) { + $this->pos = strlen($this->data) + $offset; + } else { + return false; + } + return true; + } + + /** + * Implements support for fstat(). Currently the only supported field is + * "size". + * @return array + */ + public function stream_stat() + { + return array( + 'size' => strlen($this->data), + ); + } + + // Methods used by stream_wrapper_register() that are not implemented: + // bool stream_flush ( void ) + // int stream_write ( string data ) + // bool rename ( string path_from, string path_to ) + // bool mkdir ( string path, int mode, int options ) + // bool rmdir ( string path, int options ) + // bool dir_opendir ( string path, int options ) + // array url_stat ( string path, int flags ) + // string dir_readdir ( void ) + // bool dir_rewinddir ( void ) + // bool dir_closedir ( void ) +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php new file mode 100644 index 00000000..4db0ae4e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php @@ -0,0 +1,230 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: PPS.php,v 1.7 2007/02/13 21:00:42 schmidt Exp $ + + +/** +* Class for creating PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS +{ + /** + * The PPS index + * @var integer + */ + public $No; + + /** + * The PPS name (in Unicode) + * @var string + */ + public $Name; + + /** + * The PPS type. Dir, Root or File + * @var integer + */ + public $Type; + + /** + * The index of the previous PPS + * @var integer + */ + public $PrevPps; + + /** + * The index of the next PPS + * @var integer + */ + public $NextPps; + + /** + * The index of it's first child if this is a Dir or Root PPS + * @var integer + */ + public $DirPps; + + /** + * A timestamp + * @var integer + */ + public $Time1st; + + /** + * A timestamp + * @var integer + */ + public $Time2nd; + + /** + * Starting block (small or big) for this PPS's data inside the container + * @var integer + */ + public $_StartBlock; + + /** + * The size of the PPS's data (in bytes) + * @var integer + */ + public $Size; + + /** + * The PPS's data (only used if it's not using a temporary file) + * @var string + */ + public $_data; + + /** + * Array of child PPS's (only used by Root and Dir PPS's) + * @var array + */ + public $children = array(); + + /** + * Pointer to OLE container + * @var OLE + */ + public $ole; + + /** + * The constructor + * + * @access public + * @param integer $No The PPS index + * @param string $name The PPS name + * @param integer $type The PPS type. Dir, Root or File + * @param integer $prev The index of the previous PPS + * @param integer $next The index of the next PPS + * @param integer $dir The index of it's first child if this is a Dir or Root PPS + * @param integer $time_1st A timestamp + * @param integer $time_2nd A timestamp + * @param string $data The (usually binary) source data of the PPS + * @param array $children Array containing children PPS for this PPS + */ + public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children) + { + $this->No = $No; + $this->Name = $name; + $this->Type = $type; + $this->PrevPps = $prev; + $this->NextPps = $next; + $this->DirPps = $dir; + $this->Time1st = $time_1st; + $this->Time2nd = $time_2nd; + $this->_data = $data; + $this->children = $children; + if ($data != '') { + $this->Size = strlen($data); + } else { + $this->Size = 0; + } + } + + /** + * Returns the amount of data saved for this PPS + * + * @access public + * @return integer The amount of data (in bytes) + */ + public function _DataLen() + { + if (!isset($this->_data)) { + return 0; + } + //if (isset($this->_PPS_FILE)) { + // fseek($this->_PPS_FILE, 0); + // $stats = fstat($this->_PPS_FILE); + // return $stats[7]; + //} else { + return strlen($this->_data); + //} + } + + /** + * Returns a string with the PPS's WK (What is a WK?) + * + * @access public + * @return string The binary string + */ + public function _getPpsWk() + { + $ret = str_pad($this->Name,64,"\x00"); + + $ret .= pack("v", strlen($this->Name) + 2) // 66 + . pack("c", $this->Type) // 67 + . pack("c", 0x00) //UK // 68 + . pack("V", $this->PrevPps) //Prev // 72 + . pack("V", $this->NextPps) //Next // 76 + . pack("V", $this->DirPps) //Dir // 80 + . "\x00\x09\x02\x00" // 84 + . "\x00\x00\x00\x00" // 88 + . "\xc0\x00\x00\x00" // 92 + . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root + . "\x00\x00\x00\x00" // 100 + . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time1st) // 108 + . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time2nd) // 116 + . pack("V", isset($this->_StartBlock)? + $this->_StartBlock:0) // 120 + . pack("V", $this->Size) // 124 + . pack("V", 0); // 128 + return $ret; + } + + /** + * Updates index and pointers to previous, next and children PPS's for this + * PPS. I don't think it'll work with Dir PPS's. + * + * @access public + * @param array &$raList Reference to the array of PPS's for the whole OLE + * container + * @return integer The index for this PPS + */ + public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) + { + if ( !is_array($to_save) || (empty($to_save)) ) { + return 0xFFFFFFFF; + } elseif( count($to_save) == 1 ) { + $cnt = count($raList); + // If the first entry, it's the root... Don't clone it! + $raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0]; + $raList[$cnt]->No = $cnt; + $raList[$cnt]->PrevPps = 0xFFFFFFFF; + $raList[$cnt]->NextPps = 0xFFFFFFFF; + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + } else { + $iPos = floor(count($to_save) / 2); + $aPrev = array_slice($to_save, 0, $iPos); + $aNext = array_slice($to_save, $iPos + 1); + $cnt = count($raList); + // If the first entry, it's the root... Don't clone it! + $raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos]; + $raList[$cnt]->No = $cnt; + $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++); + $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++); + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + + } + return $cnt; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php new file mode 100644 index 00000000..f061f568 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php @@ -0,0 +1,84 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: File.php,v 1.11 2007/02/13 21:00:42 schmidt Exp $ + + +/** +* Class for creating File PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS_File extends PHPExcel_Shared_OLE_PPS + { + /** + * The constructor + * + * @access public + * @param string $name The name of the file (in Unicode) + * @see OLE::Asc2Ucs() + */ + public function __construct($name) + { + parent::__construct( + null, + $name, + PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE, + null, + null, + null, + null, + null, + '', + array()); + } + + /** + * Initialization method. Has to be called right after OLE_PPS_File(). + * + * @access public + * @return mixed true on success + */ + public function init() + { + return true; + } + + /** + * Append data to PPS + * + * @access public + * @param string $data The data to append + */ + public function append($data) + { + $this->_data .= $data; + } + + /** + * Returns a stream for reading this file using fread() etc. + * @return resource a read-only stream + */ + public function getStream() + { + $this->ole->getStream($this); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php new file mode 100644 index 00000000..8c6dcda0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php @@ -0,0 +1,467 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: Root.php,v 1.9 2005/04/23 21:53:49 dufuz Exp $ + + +/** +* Class for creating Root PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS_Root extends PHPExcel_Shared_OLE_PPS + { + + /** + * Directory for temporary files + * @var string + */ + protected $_tmp_dir = NULL; + + /** + * @param integer $time_1st A timestamp + * @param integer $time_2nd A timestamp + */ + public function __construct($time_1st, $time_2nd, $raChild) + { + $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + + parent::__construct( + null, + PHPExcel_Shared_OLE::Asc2Ucs('Root Entry'), + PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT, + null, + null, + null, + $time_1st, + $time_2nd, + null, + $raChild); + } + + /** + * Method for saving the whole OLE container (including files). + * In fact, if called with an empty argument (or '-'), it saves to a + * temporary file and then outputs it's contents to stdout. + * If a resource pointer to a stream created by fopen() is passed + * it will be used, but you have to close such stream by yourself. + * + * @param string|resource $filename The name of the file or stream where to save the OLE container. + * @access public + * @return mixed true on success + */ + public function save($filename) + { + // Initial Setting for saving + $this->_BIG_BLOCK_SIZE = pow(2, + ((isset($this->_BIG_BLOCK_SIZE))? self::_adjust2($this->_BIG_BLOCK_SIZE) : 9)); + $this->_SMALL_BLOCK_SIZE= pow(2, + ((isset($this->_SMALL_BLOCK_SIZE))? self::_adjust2($this->_SMALL_BLOCK_SIZE): 6)); + + if (is_resource($filename)) { + $this->_FILEH_ = $filename; + } else if ($filename == '-' || $filename == '') { + if ($this->_tmp_dir === NULL) + $this->_tmp_dir = PHPExcel_Shared_File::sys_get_temp_dir(); + $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_Root"); + $this->_FILEH_ = fopen($this->_tmp_filename,"w+b"); + if ($this->_FILEH_ == false) { + throw new PHPExcel_Writer_Exception("Can't create temporary file."); + } + } else { + $this->_FILEH_ = fopen($filename, "wb"); + } + if ($this->_FILEH_ == false) { + throw new PHPExcel_Writer_Exception("Can't open $filename. It may be in use or protected."); + } + // Make an array of PPS's (for Save) + $aList = array(); + PHPExcel_Shared_OLE_PPS::_savePpsSetPnt($aList, array($this)); + // calculate values for header + list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo); + // Save Header + $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt); + + // Make Small Data string (write SBD) + $this->_data = $this->_makeSmallData($aList); + + // Write BB + $this->_saveBigData($iSBDcnt, $aList); + // Write PPS + $this->_savePps($aList); + // Write Big Block Depot and BDList and Adding Header informations + $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt); + + if (!is_resource($filename)) { + fclose($this->_FILEH_); + } + + return true; + } + + /** + * Calculate some numbers + * + * @access public + * @param array $raList Reference to an array of PPS's + * @return array The array of numbers + */ + public function _calcSize(&$raList) + { + // Calculate Basic Setting + list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0); + $iSmallLen = 0; + $iSBcnt = 0; + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) { + $raList[$i]->Size = $raList[$i]->_DataLen(); + if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) { + $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); + } else { + $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); + } + } + } + $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE; + $iSlCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE); + $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0); + $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) + + (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0)); + $iCnt = count($raList); + $iBdCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE; + $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); + + return array($iSBDcnt, $iBBcnt, $iPPScnt); + } + + /** + * Helper function for caculating a magic value for block sizes + * + * @access public + * @param integer $i2 The argument + * @see save() + * @return integer + */ + private static function _adjust2($i2) + { + $iWk = log($i2)/log(2); + return ($iWk > floor($iWk))? floor($iWk)+1:$iWk; + } + + /** + * Save OLE header + * + * @access public + * @param integer $iSBDcnt + * @param integer $iBBcnt + * @param integer $iPPScnt + */ + public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) + { + $FILE = $this->_FILEH_; + + // Calculate Basic Setting + $iBlCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + + $iBdExL = 0; + $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; + $iAllW = $iAll; + $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); + + // Calculate BD count + if ($iBdCnt > $i1stBdL) { + while (1) { + ++$iBdExL; + ++$iAllW; + $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) { + break; + } + } + } + + // Save Header + fwrite($FILE, + "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . pack("v", 0x3b) + . pack("v", 0x03) + . pack("v", -2) + . pack("v", 9) + . pack("v", 6) + . pack("v", 0) + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . pack("V", $iBdCnt) + . pack("V", $iBBcnt+$iSBDcnt) //ROOT START + . pack("V", 0) + . pack("V", 0x1000) + . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot + . pack("V", $iSBDcnt) + ); + // Extra BDList Start, Count + if ($iBdCnt < $i1stBdL) { + fwrite($FILE, + pack("V", -2) // Extra BDList Start + . pack("V", 0) // Extra BDList Count + ); + } else { + fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL)); + } + + // BDList + for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) { + fwrite($FILE, pack("V", $iAll+$i)); + } + if ($i < $i1stBdL) { + $jB = $i1stBdL - $i; + for ($j = 0; $j < $jB; ++$j) { + fwrite($FILE, (pack("V", -1))); + } + } + } + + /** + * Saving big data (PPS's with data bigger than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) + * + * @access public + * @param integer $iStBlk + * @param array &$raList Reference to array of PPS's + */ + public function _saveBigData($iStBlk, &$raList) + { + $FILE = $this->_FILEH_; + + // cycle through PPS's + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + if ($raList[$i]->Type != PHPExcel_Shared_OLE::OLE_PPS_TYPE_DIR) { + $raList[$i]->Size = $raList[$i]->_DataLen(); + if (($raList[$i]->Size >= PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) || + (($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) + { + // Write Data + //if (isset($raList[$i]->_PPS_FILE)) { + // $iLen = 0; + // fseek($raList[$i]->_PPS_FILE, 0); // To The Top + // while($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) { + // $iLen += strlen($sBuff); + // fwrite($FILE, $sBuff); + // } + //} else { + fwrite($FILE, $raList[$i]->_data); + //} + + if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) { + fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE))); + } + // Set For PPS + $raList[$i]->_StartBlock = $iStBlk; + $iStBlk += + (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); + } + // Close file for each PPS, and unlink it + //if (isset($raList[$i]->_PPS_FILE)) { + // fclose($raList[$i]->_PPS_FILE); + // $raList[$i]->_PPS_FILE = null; + // unlink($raList[$i]->_tmp_filename); + //} + } + } + } + + /** + * get small data (PPS's with data smaller than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) + * + * @access public + * @param array &$raList Reference to array of PPS's + */ + public function _makeSmallData(&$raList) + { + $sRes = ''; + $FILE = $this->_FILEH_; + $iSmBlk = 0; + + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + // Make SBD, small data string + if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) { + if ($raList[$i]->Size <= 0) { + continue; + } + if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) { + $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); + // Add to SBD + $jB = $iSmbCnt - 1; + for ($j = 0; $j < $jB; ++$j) { + fwrite($FILE, pack("V", $j+$iSmBlk+1)); + } + fwrite($FILE, pack("V", -2)); + + //// Add to Data String(this will be written for RootEntry) + //if ($raList[$i]->_PPS_FILE) { + // fseek($raList[$i]->_PPS_FILE, 0); // To The Top + // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) { + // $sRes .= $sBuff; + // } + //} else { + $sRes .= $raList[$i]->_data; + //} + if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) { + $sRes .= str_repeat("\x00",$this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)); + } + // Set for PPS + $raList[$i]->_StartBlock = $iSmBlk; + $iSmBlk += $iSmbCnt; + } + } + } + $iSbCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE); + if ($iSmBlk % $iSbCnt) { + $iB = $iSbCnt - ($iSmBlk % $iSbCnt); + for ($i = 0; $i < $iB; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + return $sRes; + } + + /** + * Saves all the PPS's WKs + * + * @access public + * @param array $raList Reference to an array with all PPS's + */ + public function _savePps(&$raList) + { + // Save each PPS WK + $iC = count($raList); + for ($i = 0; $i < $iC; ++$i) { + fwrite($this->_FILEH_, $raList[$i]->_getPpsWk()); + } + // Adjust for Block + $iCnt = count($raList); + $iBCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE; + if ($iCnt % $iBCnt) { + fwrite($this->_FILEH_, str_repeat("\x00",($iBCnt - ($iCnt % $iBCnt)) * PHPExcel_Shared_OLE::OLE_PPS_SIZE)); + } + } + + /** + * Saving Big Block Depot + * + * @access public + * @param integer $iSbdSize + * @param integer $iBsize + * @param integer $iPpsCnt + */ + public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt) + { + $FILE = $this->_FILEH_; + // Calculate Basic Setting + $iBbCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + + $iBdExL = 0; + $iAll = $iBsize + $iPpsCnt + $iSbdSize; + $iAllW = $iAll; + $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); + // Calculate BD count + if ($iBdCnt >$i1stBdL) { + while (1) { + ++$iBdExL; + ++$iAllW; + $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) { + break; + } + } + } + + // Making BD + // Set for SBD + if ($iSbdSize > 0) { + for ($i = 0; $i < ($iSbdSize - 1); ++$i) { + fwrite($FILE, pack("V", $i+1)); + } + fwrite($FILE, pack("V", -2)); + } + // Set for B + for ($i = 0; $i < ($iBsize - 1); ++$i) { + fwrite($FILE, pack("V", $i+$iSbdSize+1)); + } + fwrite($FILE, pack("V", -2)); + + // Set for PPS + for ($i = 0; $i < ($iPpsCnt - 1); ++$i) { + fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1)); + } + fwrite($FILE, pack("V", -2)); + // Set for BBD itself ( 0xFFFFFFFD : BBD) + for ($i = 0; $i < $iBdCnt; ++$i) { + fwrite($FILE, pack("V", 0xFFFFFFFD)); + } + // Set for ExtraBDList + for ($i = 0; $i < $iBdExL; ++$i) { + fwrite($FILE, pack("V", 0xFFFFFFFC)); + } + // Adjust for Block + if (($iAllW + $iBdCnt) % $iBbCnt) { + $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); + for ($i = 0; $i < $iBlock; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + // Extra BDList + if ($iBdCnt > $i1stBdL) { + $iN=0; + $iNb=0; + for ($i = $i1stBdL;$i < $iBdCnt; $i++, ++$iN) { + if ($iN >= ($iBbCnt - 1)) { + $iN = 0; + ++$iNb; + fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb)); + } + fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i)); + } + if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) { + $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)); + for ($i = 0; $i < $iB; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + fwrite($FILE, pack("V", -2)); + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php new file mode 100644 index 00000000..c4cb7da3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php @@ -0,0 +1,317 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +defined('IDENTIFIER_OLE') || + define('IDENTIFIER_OLE', pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1)); + +class PHPExcel_Shared_OLERead { + private $data = ''; + + // OLE identifier + const IDENTIFIER_OLE = IDENTIFIER_OLE; + + // Size of a sector = 512 bytes + const BIG_BLOCK_SIZE = 0x200; + + // Size of a short sector = 64 bytes + const SMALL_BLOCK_SIZE = 0x40; + + // Size of a directory entry always = 128 bytes + const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; + + // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams + const SMALL_BLOCK_THRESHOLD = 0x1000; + + // header offsets + const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c; + const ROOT_START_BLOCK_POS = 0x30; + const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c; + const EXTENSION_BLOCK_POS = 0x44; + const NUM_EXTENSION_BLOCK_POS = 0x48; + const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c; + + // property storage offsets (directory offsets) + const SIZE_OF_NAME_POS = 0x40; + const TYPE_POS = 0x42; + const START_BLOCK_POS = 0x74; + const SIZE_POS = 0x78; + + + + public $wrkbook = null; + public $summaryInformation = null; + public $documentSummaryInformation = null; + + + /** + * Read the file + * + * @param $sFileName string Filename + * @throws PHPExcel_Reader_Exception + */ + public function read($sFileName) + { + // Check if file exists and is readable + if(!is_readable($sFileName)) { + throw new PHPExcel_Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable."); + } + + // Get the file identifier + // Don't bother reading the whole file until we know it's a valid OLE file + $this->data = file_get_contents($sFileName, FALSE, NULL, 0, 8); + + // Check OLE identifier + if ($this->data != self::IDENTIFIER_OLE) { + throw new PHPExcel_Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file'); + } + + // Get the file data + $this->data = file_get_contents($sFileName); + + // Total number of sectors used for the SAT + $this->numBigBlockDepotBlocks = self::_GetInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); + + // SecID of the first sector of the directory stream + $this->rootStartBlock = self::_GetInt4d($this->data, self::ROOT_START_BLOCK_POS); + + // SecID of the first sector of the SSAT (or -2 if not extant) + $this->sbdStartBlock = self::_GetInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS); + + // SecID of the first sector of the MSAT (or -2 if no additional sectors are used) + $this->extensionBlock = self::_GetInt4d($this->data, self::EXTENSION_BLOCK_POS); + + // Total number of sectors used by MSAT + $this->numExtensionBlocks = self::_GetInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS); + + $bigBlockDepotBlocks = array(); + $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; + + $bbdBlocks = $this->numBigBlockDepotBlocks; + + if ($this->numExtensionBlocks != 0) { + $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4; + } + + for ($i = 0; $i < $bbdBlocks; ++$i) { + $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos); + $pos += 4; + } + + for ($j = 0; $j < $this->numExtensionBlocks; ++$j) { + $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE; + $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1); + + for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) { + $bigBlockDepotBlocks[$i] = self::_GetInt4d($this->data, $pos); + $pos += 4; + } + + $bbdBlocks += $blocksToRead; + if ($bbdBlocks < $this->numBigBlockDepotBlocks) { + $this->extensionBlock = self::_GetInt4d($this->data, $pos); + } + } + + $pos = 0; + $this->bigBlockChain = ''; + $bbs = self::BIG_BLOCK_SIZE / 4; + for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { + $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; + + $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs); + $pos += 4*$bbs; + } + + $pos = 0; + $sbdBlock = $this->sbdStartBlock; + $this->smallBlockChain = ''; + while ($sbdBlock != -2) { + $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; + + $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs); + $pos += 4*$bbs; + + $sbdBlock = self::_GetInt4d($this->bigBlockChain, $sbdBlock*4); + } + + // read the directory stream + $block = $this->rootStartBlock; + $this->entry = $this->_readData($block); + + $this->_readPropertySets(); + } + + /** + * Extract binary stream data + * + * @return string + */ + public function getStream($stream) + { + if ($stream === NULL) { + return null; + } + + $streamData = ''; + + if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) { + $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']); + + $block = $this->props[$stream]['startBlock']; + + while ($block != -2) { + $pos = $block * self::SMALL_BLOCK_SIZE; + $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); + + $block = self::_GetInt4d($this->smallBlockChain, $block*4); + } + + return $streamData; + } else { + $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE; + if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) { + ++$numBlocks; + } + + if ($numBlocks == 0) return ''; + + $block = $this->props[$stream]['startBlock']; + + while ($block != -2) { + $pos = ($block + 1) * self::BIG_BLOCK_SIZE; + $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + $block = self::_GetInt4d($this->bigBlockChain, $block*4); + } + + return $streamData; + } + } + + /** + * Read a standard stream (by joining sectors using information from SAT) + * + * @param int $bl Sector ID where the stream starts + * @return string Data for standard stream + */ + private function _readData($bl) + { + $block = $bl; + $data = ''; + + while ($block != -2) { + $pos = ($block + 1) * self::BIG_BLOCK_SIZE; + $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + $block = self::_GetInt4d($this->bigBlockChain, $block*4); + } + return $data; + } + + /** + * Read entries in the directory stream. + */ + private function _readPropertySets() { + $offset = 0; + + // loop through entires, each entry is 128 bytes + $entryLen = strlen($this->entry); + while ($offset < $entryLen) { + // entry data (128 bytes) + $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); + + // size in bytes of name + $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8); + + // type of entry + $type = ord($d[self::TYPE_POS]); + + // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook) + // sectorID of first sector of the short-stream container stream, if this entry is root entry + $startBlock = self::_GetInt4d($d, self::START_BLOCK_POS); + + $size = self::_GetInt4d($d, self::SIZE_POS); + + $name = str_replace("\x00", "", substr($d,0,$nameSize)); + + + $this->props[] = array ( + 'name' => $name, + 'type' => $type, + 'startBlock' => $startBlock, + 'size' => $size); + + // tmp helper to simplify checks + $upName = strtoupper($name); + + // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook) + if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) { + $this->wrkbook = count($this->props) - 1; + } + else if ( $upName === 'ROOT ENTRY' || $upName === 'R') { + // Root entry + $this->rootentry = count($this->props) - 1; + } + + // Summary information + if ($name == chr(5) . 'SummaryInformation') { +// echo 'Summary Information<br />'; + $this->summaryInformation = count($this->props) - 1; + } + + // Additional Document Summary information + if ($name == chr(5) . 'DocumentSummaryInformation') { +// echo 'Document Summary Information<br />'; + $this->documentSummaryInformation = count($this->props) - 1; + } + + $offset += self::PROPERTY_STORAGE_BLOCK_SIZE; + } + + } + + /** + * Read 4 bytes of data at specified position + * + * @param string $data + * @param int $pos + * @return int + */ + private static function _GetInt4d($data, $pos) + { + // FIX: represent numbers correctly on 64-bit system + // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 + // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems + $_or_24 = ord($data[$pos + 3]); + if ($_or_24 >= 128) { + // negative number + $_ord_24 = -abs((256 - $_or_24) << 24); + } else { + $_ord_24 = ($_or_24 & 127) << 24; + } + return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt new file mode 100644 index 00000000..b1e3f5a2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php new file mode 100644 index 00000000..e7facc1e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php @@ -0,0 +1,5694 @@ +<?php +// -------------------------------------------------------------------------------- +// PhpConcept Library - Zip Module 2.8.2 +// -------------------------------------------------------------------------------- +// License GNU/LGPL - Vincent Blavet - August 2009 +// http://www.phpconcept.net +// -------------------------------------------------------------------------------- +// +// Presentation : +// PclZip is a PHP library that manage ZIP archives. +// So far tests show that archives generated by PclZip are readable by +// WinZip application and other tools. +// +// Description : +// See readme.txt and http://www.phpconcept.net +// +// Warning : +// This library and the associated files are non commercial, non professional +// work. +// It should not have unexpected results. However if any damage is caused by +// this software the author can not be responsible. +// The use of this software is at the risk of the user. +// +// -------------------------------------------------------------------------------- +// $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ +// -------------------------------------------------------------------------------- + + // ----- Constants + if (!defined('PCLZIP_READ_BLOCK_SIZE')) { + define( 'PCLZIP_READ_BLOCK_SIZE', 2048 ); + } + + // ----- File list separator + // In version 1.x of PclZip, the separator for file list is a space + // (which is not a very smart choice, specifically for windows paths !). + // A better separator should be a comma (,). This constant gives you the + // abilty to change that. + // However notice that changing this value, may have impact on existing + // scripts, using space separated filenames. + // Recommanded values for compatibility with older versions : + //define( 'PCLZIP_SEPARATOR', ' ' ); + // Recommanded values for smart separation of filenames. + if (!defined('PCLZIP_SEPARATOR')) { + define( 'PCLZIP_SEPARATOR', ',' ); + } + + // ----- Error configuration + // 0 : PclZip Class integrated error handling + // 1 : PclError external library error handling. By enabling this + // you must ensure that you have included PclError library. + // [2,...] : reserved for futur use + if (!defined('PCLZIP_ERROR_EXTERNAL')) { + define( 'PCLZIP_ERROR_EXTERNAL', 0 ); + } + + // ----- Optional static temporary directory + // By default temporary files are generated in the script current + // path. + // If defined : + // - MUST BE terminated by a '/'. + // - MUST be a valid, already created directory + // Samples : + // define( 'PCLZIP_TEMPORARY_DIR', '/temp/' ); + // define( 'PCLZIP_TEMPORARY_DIR', 'C:/Temp/' ); + if (!defined('PCLZIP_TEMPORARY_DIR')) { + define( 'PCLZIP_TEMPORARY_DIR', '' ); + } + + // ----- Optional threshold ratio for use of temporary files + // Pclzip sense the size of the file to add/extract and decide to + // use or not temporary file. The algorythm is looking for + // memory_limit of PHP and apply a ratio. + // threshold = memory_limit * ratio. + // Recommended values are under 0.5. Default 0.47. + // Samples : + // define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.5 ); + if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { + define( 'PCLZIP_TEMPORARY_FILE_RATIO', 0.47 ); + } + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** +// -------------------------------------------------------------------------------- + + // ----- Global variables + $g_pclzip_version = "2.8.2"; + + // ----- Error codes + // -1 : Unable to open file in binary write mode + // -2 : Unable to open file in binary read mode + // -3 : Invalid parameters + // -4 : File does not exist + // -5 : Filename is too long (max. 255) + // -6 : Not a valid zip file + // -7 : Invalid extracted file size + // -8 : Unable to create directory + // -9 : Invalid archive extension + // -10 : Invalid archive format + // -11 : Unable to delete file (unlink) + // -12 : Unable to rename file (rename) + // -13 : Invalid header checksum + // -14 : Invalid archive size + define( 'PCLZIP_ERR_USER_ABORTED', 2 ); + define( 'PCLZIP_ERR_NO_ERROR', 0 ); + define( 'PCLZIP_ERR_WRITE_OPEN_FAIL', -1 ); + define( 'PCLZIP_ERR_READ_OPEN_FAIL', -2 ); + define( 'PCLZIP_ERR_INVALID_PARAMETER', -3 ); + define( 'PCLZIP_ERR_MISSING_FILE', -4 ); + define( 'PCLZIP_ERR_FILENAME_TOO_LONG', -5 ); + define( 'PCLZIP_ERR_INVALID_ZIP', -6 ); + define( 'PCLZIP_ERR_BAD_EXTRACTED_FILE', -7 ); + define( 'PCLZIP_ERR_DIR_CREATE_FAIL', -8 ); + define( 'PCLZIP_ERR_BAD_EXTENSION', -9 ); + define( 'PCLZIP_ERR_BAD_FORMAT', -10 ); + define( 'PCLZIP_ERR_DELETE_FILE_FAIL', -11 ); + define( 'PCLZIP_ERR_RENAME_FILE_FAIL', -12 ); + define( 'PCLZIP_ERR_BAD_CHECKSUM', -13 ); + define( 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); + define( 'PCLZIP_ERR_MISSING_OPTION_VALUE', -15 ); + define( 'PCLZIP_ERR_INVALID_OPTION_VALUE', -16 ); + define( 'PCLZIP_ERR_ALREADY_A_DIRECTORY', -17 ); + define( 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18 ); + define( 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19 ); + define( 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20 ); + define( 'PCLZIP_ERR_DIRECTORY_RESTRICTION', -21 ); + + // ----- Options values + define( 'PCLZIP_OPT_PATH', 77001 ); + define( 'PCLZIP_OPT_ADD_PATH', 77002 ); + define( 'PCLZIP_OPT_REMOVE_PATH', 77003 ); + define( 'PCLZIP_OPT_REMOVE_ALL_PATH', 77004 ); + define( 'PCLZIP_OPT_SET_CHMOD', 77005 ); + define( 'PCLZIP_OPT_EXTRACT_AS_STRING', 77006 ); + define( 'PCLZIP_OPT_NO_COMPRESSION', 77007 ); + define( 'PCLZIP_OPT_BY_NAME', 77008 ); + define( 'PCLZIP_OPT_BY_INDEX', 77009 ); + define( 'PCLZIP_OPT_BY_EREG', 77010 ); + define( 'PCLZIP_OPT_BY_PREG', 77011 ); + define( 'PCLZIP_OPT_COMMENT', 77012 ); + define( 'PCLZIP_OPT_ADD_COMMENT', 77013 ); + define( 'PCLZIP_OPT_PREPEND_COMMENT', 77014 ); + define( 'PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015 ); + define( 'PCLZIP_OPT_REPLACE_NEWER', 77016 ); + define( 'PCLZIP_OPT_STOP_ON_ERROR', 77017 ); + // Having big trouble with crypt. Need to multiply 2 long int + // which is not correctly supported by PHP ... + //define( 'PCLZIP_OPT_CRYPT', 77018 ); + define( 'PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019 ); + define( 'PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020 ); // alias + define( 'PCLZIP_OPT_TEMP_FILE_ON', 77021 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021 ); // alias + define( 'PCLZIP_OPT_TEMP_FILE_OFF', 77022 ); + define( 'PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022 ); // alias + + // ----- File description attributes + define( 'PCLZIP_ATT_FILE_NAME', 79001 ); + define( 'PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002 ); + define( 'PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003 ); + define( 'PCLZIP_ATT_FILE_MTIME', 79004 ); + define( 'PCLZIP_ATT_FILE_CONTENT', 79005 ); + define( 'PCLZIP_ATT_FILE_COMMENT', 79006 ); + + // ----- Call backs values + define( 'PCLZIP_CB_PRE_EXTRACT', 78001 ); + define( 'PCLZIP_CB_POST_EXTRACT', 78002 ); + define( 'PCLZIP_CB_PRE_ADD', 78003 ); + define( 'PCLZIP_CB_POST_ADD', 78004 ); + /* For futur use + define( 'PCLZIP_CB_PRE_LIST', 78005 ); + define( 'PCLZIP_CB_POST_LIST', 78006 ); + define( 'PCLZIP_CB_PRE_DELETE', 78007 ); + define( 'PCLZIP_CB_POST_DELETE', 78008 ); + */ + + // -------------------------------------------------------------------------------- + // Class : PclZip + // Description : + // PclZip is the class that represent a Zip archive. + // The public methods allow the manipulation of the archive. + // Attributes : + // Attributes must not be accessed directly. + // Methods : + // PclZip() : Object creator + // create() : Creates the Zip archive + // listContent() : List the content of the Zip archive + // extract() : Extract the content of the archive + // properties() : List the properties of the archive + // -------------------------------------------------------------------------------- + class PclZip + { + // ----- Filename of the zip file + var $zipname = ''; + + // ----- File descriptor of the zip file + var $zip_fd = 0; + + // ----- Internal error handling + var $error_code = 1; + var $error_string = ''; + + // ----- Current status of the magic_quotes_runtime + // This value store the php configuration for magic_quotes + // The class can then disable the magic_quotes and reset it after + var $magic_quotes_status; + + // -------------------------------------------------------------------------------- + // Function : PclZip() + // Description : + // Creates a PclZip object and set the name of the associated Zip archive + // filename. + // Note that no real action is taken, if the archive does not exist it is not + // created. Use create() for that. + // -------------------------------------------------------------------------------- + function PclZip($p_zipname) + { + + // ----- Tests the zlib + if (!function_exists('gzopen')) + { + die('Abort '.basename(__FILE__).' : Missing zlib extensions'); + } + + // ----- Set the attributes + $this->zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; + + // ----- Return + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function create($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Invalid number / type of arguments"); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + else { + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function add($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = FALSE; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } + + // ----- The list is a list of string names + else { + $v_string_list = $p_filelist; + } + } + + // ----- Look if the $p_filelist is a string + else if (is_string($p_filelist)) { + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } + + // ----- Invalid variable type for $p_filelist + else { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes + = array ( PCLZIP_ATT_FILE_NAME => 'mandatory' + ,PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional' + ,PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional' + ,PCLZIP_ATT_FILE_MTIME => 'optional' + ,PCLZIP_ATT_FILE_CONTENT => 'optional' + ,PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, + $v_filedescr_list[], + $v_options, + $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + function listContent() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) + { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function extract() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, + $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + function extractByIndex($p_index) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); +// $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional' + ,PCLZIP_OPT_STOP_ON_ERROR => 'optional' + ,PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = FALSE; + } + else { + } + } + + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + else { + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } + else if ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, + array (PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + function delete() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, + array (PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + function deleteByIndex($p_index) + { + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + function properties() + { + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) + { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + function duplicate($p_archive) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) + { + + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } + + // ----- Look if the $p_archive is a string (so a filename) + else if (is_string($p_archive)) + { + + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } + else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + function merge($p_archive_to_add) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) + { + + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } + + // ----- Look if the $p_archive_to_add is a string (so a filename) + else if (is_string($p_archive_to_add)) + { + + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } + + // ----- Invalid variable + else + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } + else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorName($p_with_code=false) + { + $v_name = array ( PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION' + ,PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE' + ,PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION' + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } + else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } + else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function errorInfo($p_full=false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } + else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } + else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- + + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** +// ***** ***** +// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** +// -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + function privCheckFormat($p_level=0) + { + $v_result = true; + + // ----- Reset the file system cache + clearstatcache(); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + return(false); + } + + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + return(false); + } + + // ----- Check the magic code + // TBC + + // ----- Check the central header + // TBC + + // ----- Check each file header + // TBC + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options=false) + { + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH : + case PCLZIP_OPT_REMOVE_PATH : + case PCLZIP_OPT_ADD_PATH : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_THRESHOLD : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_TEMP_FILE_OFF : + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if ( is_string($p_options_list[$i+1]) + && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], FALSE); + $i++; + } + else { + } + break; + + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG : + // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG + // to PCLZIP_OPT_BY_PREG + $p_options_list[$i] = PCLZIP_OPT_BY_PREG; + case PCLZIP_OPT_BY_PREG : + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT : + case PCLZIP_OPT_ADD_COMMENT : + case PCLZIP_OPT_PREPEND_COMMENT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, + "Missing parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, + "Wrong parameter value for option '" + .PclZipUtilOptionText($p_options_list[$i]) + ."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } + else if (is_integer($p_options_list[$i+1])) { + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } + else if (is_array($p_options_list[$i+1])) { + $v_work_list = $p_options_list[$i+1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j<sizeof($v_work_list); $j++) { + // ----- Explode the item + $v_item_list = explode("-", $v_work_list[$j]); + $v_size_item_list = sizeof($v_item_list); + + // ----- TBC : Here we might check that each item is a + // real integer ... + + // ----- Look for single value + if ($v_size_item_list == 1) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0]; + } + elseif ($v_size_item_list == 2) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1]; + } + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + + // ----- Look for list sort + if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { + $v_sort_flag=true; + + // ----- TBC : An automatic sort should be writen ... + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; + } + + // ----- Sort the items + if ($v_sort_flag) { + // TBC : To Be Completed + } + + // ----- Next option + $i++; + break; + + // ----- Look for options that request no value + case PCLZIP_OPT_REMOVE_ALL_PATH : + case PCLZIP_OPT_EXTRACT_AS_STRING : + case PCLZIP_OPT_NO_COMPRESSION : + case PCLZIP_OPT_EXTRACT_IN_OUTPUT : + case PCLZIP_OPT_REPLACE_NEWER : + case PCLZIP_OPT_STOP_ON_ERROR : + $v_result_list[$p_options_list[$i]] = true; + break; + + // ----- Look for options that request an octal value + case PCLZIP_OPT_SET_CHMOD : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT : + case PCLZIP_CB_POST_EXTRACT : + case PCLZIP_CB_PRE_ADD : + case PCLZIP_CB_POST_ADD : + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '" + .$p_options_list[$i]."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Next options + $i++; + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + + // ----- Return + return PclZip::errorCode(); + } + } + } + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privOptionDefaultThreshold(&$p_options) + { + $v_result=1; + + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + return $v_result; + } + + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + + if($last == 'g') + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit*1073741824; + if($last == 'm') + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit*1048576; + if($last == 'k') + $v_memory_limit = $v_memory_limit*1024; + + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + + + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options=false) + { + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + break; + + case PCLZIP_ATT_FILE_NEW_SHORT_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + case PCLZIP_ATT_FILE_NEW_FULL_NAME : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT : + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['comment'] = $v_value; + break; + + case PCLZIP_ATT_FILE_MTIME : + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['mtime'] = $v_value; + break; + + case PCLZIP_ATT_FILE_CONTENT : + $p_filedescr['content'] = $v_value; + break; + + default : + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, + "Unknown parameter '".$v_key."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + return PclZip::errorCode(); + } + } + } + } + + // end foreach + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $i<sizeof($p_filedescr_list); $i++) { + + // ----- Get filedescr + $v_descr = $p_filedescr_list[$i]; + + // ----- Reduce the filename + $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false); + $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']); + + // ----- Look for real file or folder + if (file_exists($v_descr['filename'])) { + if (@is_file($v_descr['filename'])) { + $v_descr['type'] = 'file'; + } + else if (@is_dir($v_descr['filename'])) { + $v_descr['type'] = 'folder'; + } + else if (@is_link($v_descr['filename'])) { + // skip + continue; + } + else { + // skip + continue; + } + } + + // ----- Look for string added as file + else if (isset($v_descr['content'])) { + $v_descr['type'] = 'virtual_file'; + } + + // ----- Missing file + else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Calculate the stored filename + $this->privCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if (($v_descr['stored_filename'] != $v_descr['filename']) + && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } + else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } + else { + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + return $v_result; + } + + // ----- Concat the resulting list + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + } + else { + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) + { + + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) + { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privOpenFd($p_mode) + { + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privCloseFd() + { + $v_result=1; + + if ($this->zip_fd != 0) + @fclose($this->zip_fd); + $this->zip_fd = 0; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- +// function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0,$v_count=0; $i<sizeof($v_header_list); $i++) + { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) + { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + + // ----- Loop on the files + for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) { + // ----- Format the filename + $p_filedescr_list[$j]['filename'] + = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false); + + + // ----- Skip empty file names + // TBC : Can this be possible ? not checked in DescrParseAtt ? + if ($p_filedescr_list[$j]['filename'] == "") { + continue; + } + + // ----- Check the filename + if ( ($p_filedescr_list[$j]['type'] != 'virtual_file') + && (!file_exists($p_filedescr_list[$j]['filename']))) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist"); + return PclZip::errorCode(); + } + + // ----- Look if it is a file or a dir with no all path remove option + // or a dir with all its path removed +// if ( (is_file($p_filedescr_list[$j]['filename'])) +// || ( is_dir($p_filedescr_list[$j]['filename']) + if ( ($p_filedescr_list[$j]['type'] == 'file') + || ($p_filedescr_list[$j]['type'] == 'virtual_file') + || ( ($p_filedescr_list[$j]['type'] == 'folder') + && ( !isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) + || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) + ) { + + // ----- Add the file + $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, + $p_options); + if ($v_result != 1) { + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + } + else { + $v_stored_filename = $p_filedescr['stored_filename']; + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; +// TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for regular folder + else if ($p_filedescr['type']=='folder') { + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } + + // ----- Look for virtual file + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + $p_header['mtime'] = $p_filedescr['mtime']; + } + else if ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = time(); + } + else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } + else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])) ) ) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Use "in memory" zip algo + else { + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + + } + + } + + // ----- Look for a virtual file (a file from string) + else if ($p_filedescr['type'] == 'virtual_file') { + + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } + + // ----- Look for normal compression + else { + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + + // ----- Look for a directory + else if ($p_filedescr['type'] == 'folder') { + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) + { + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); + + // ----- Check the minimum file size + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); + return PclZip::errorCode(); + } + + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + + // ----- Check some parameters + $v_data_header['os'] = bin2hex($v_data_header['os']); + + // ----- Read the gzip file footer + @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + $v_binary_data = @fread($v_file_compressed, 8); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } + + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) + { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } + else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } + else { + $p_remove_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + else { + $p_remove_all_dir = 0; + } + + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + } + + // ----- Look for path and/or short name change + else { + + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + } + else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + } + // ----- Look for partial path remove + else if ($p_remove_dir != "") { + if (substr($p_remove_dir, -1) != '/') + $p_remove_dir .= "/"; + + if ( (substr($p_filename, 0, 2) == "./") + || (substr($p_remove_dir, 0, 2) == "./")) { + + if ( (substr($p_filename, 0, 2) == "./") + && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ( (substr($p_filename, 0, 2) != "./") + && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, + $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } + else { + $v_stored_filename = substr($v_stored_filename, + strlen($p_remove_dir)); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") + $v_stored_filename = $p_add_dir.$v_stored_filename; + else + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteFileHeader(&$p_header) + { + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, + $p_header['version_extracted'], $p_header['flag'], + $p_header['compression'], $v_mtime, $v_mdate, + $p_header['crc'], $p_header['compressed_size'], + $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralFileHeader(&$p_header) + { + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, + $p_header['version'], $p_header['version_extracted'], + $p_header['flag'], $p_header['compression'], + $v_mtime, $v_mdate, $p_header['crc'], + $p_header['compressed_size'], $p_header['size'], + strlen($p_header['stored_filename']), + $p_header['extra_len'], $p_header['comment_len'], + $p_header['disk'], $p_header['internal'], + $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) + { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) + { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) + { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + $v_result=1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, + $p_nb_entries, $p_size, + $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) + { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privList(&$p_list) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) + { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of Central Dir + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) + { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) + { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privConvertHeader2FileInfo($p_header, &$p_info) + { + $v_result=1; + + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if ( ($p_path == "") + || ( (substr($p_path, 0, 1) != "/") + && (substr($p_path, 0, 3) != "../") + && (substr($p_path,1,2)!=":/"))) + $p_path = "./".$p_path; + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) + { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") + { + $p_path = substr($p_path, 0, strlen($p_path)-1); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) + { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) + { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { + + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { + + // ----- Look if the directory is in the filename path + if ( (strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } + } + // ----- Look for a filename + elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_extract = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { + + if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + + // ----- Look for no rule, which means extract all the archive + else { + $v_extract = true; + } + + // ----- Check compression method + if ( ($v_extract) + && ( ($v_header['compression'] != 8) + && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, + "Filename '".$v_header['stored_filename']."' is " + ."compressed by an unsupported compression " + ."method (".$v_header['compression'].") "); + + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, + "Unsupported encryption for " + ." filename '".$v_header['stored_filename'] + ."'"); + + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, + $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) + { + + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) + { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for extraction in standard output + elseif ( (isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) + && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + // ----- Look for normal extraction + else { + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, + $p_path, $p_remove_path, + $p_remove_all_path, + $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + + $p_entry['status'] = "filtered"; + + return $v_result; + } + + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } + + // ----- Look for path to remove + else if ($p_remove_path != "") + { + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) + { + + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) + { + + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion + = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], + $p_entry['filename']); + if ($v_inclusion == 0) { + + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, + "Filename '".$p_entry['filename']."' is " + ."outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) + { + + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, + "Filename '".$p_entry['filename']."' is " + ."already used by an existing directory"); + + return PclZip::errorCode(); + } + } + // ----- Look if file is write protected + else if (!is_writeable($p_entry['filename'])) + { + + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Filename '".$p_entry['filename']."' exists " + ."and is write protected"); + + return PclZip::errorCode(); + } + } + + // ----- Look if the extracted file is older + else if (filemtime($p_entry['filename']) > $p_entry['mtime']) + { + // ----- Change the file status + if ( (isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) + && ($p_options[PCLZIP_OPT_REPLACE_NEWER]===true)) { + } + else { + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ( (isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) + && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, + "Newer version of '".$p_entry['filename']."' exists " + ."and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + + return PclZip::errorCode(); + } + } + } + else { + } + } + + // ----- Check the directory availability and create it if necessary + else { + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) + $v_dir_to_check = $p_entry['filename']; + else if (!strstr($p_entry['filename'], "/")) + $v_dir_to_check = ""; + else + $v_dir_to_check = dirname($p_entry['filename']); + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) + { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) + { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + return $v_result; + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + + + } + else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + return PclZip::errorCode(); + } + + + // ----- Look for using temporary file to unzip + if ( (!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) + && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) + || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) + && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])) ) ) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } + + // ----- Look for extract in memory + else { + + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === FALSE) { + + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + + // ----- Change the file status + $p_entry['status'] = "write_error"; + + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); + + // ----- Close the temporary file + @fclose($v_dest_file); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + $p_entry['status'] = "write_error"; + return $v_result; + } + + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + @fclose($v_dest_file); + @gzclose($v_src_file); + + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileInOutput(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Trace + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } + else { + + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) + { + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) + { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + // if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } + else { + + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === FALSE) { + // TBC + } + } + + // ----- Trace + } + else { + // TBC : error : can not extract a folder in a string + } + + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } + + // ----- Look for post-extract callback + elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. +// eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + + // ----- Get extra_fields + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } + else { + $p_header['extra'] = ''; + } + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + $p_header['compression'] = $v_data['compression']; + $p_header['size'] = $v_data['size']; + $p_header['compressed_size'] = $v_data['compressed_size']; + $p_header['crc'] = $v_data['crc']; + $p_header['flag'] = $v_data['flag']; + $p_header['filename_len'] = $v_data['filename_len']; + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadCentralFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) + { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + if ($p_header['filename_len'] != 0) + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + else + $p_header['filename'] = ''; + + // ----- Get extra + if ($p_header['extra_len'] != 0) + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + else + $p_header['extra'] = ''; + + // ----- Get comment + if ($p_header['comment_len'] != 0) + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + else + $p_header['comment'] = ''; + + // ----- Extract properties + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) + { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } + else + { + $p_header['mtime'] = time(); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + } + + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privReadEndCentralDir(&$p_central_dir) + { + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + @fseek($this->zip_fd, $v_size); + if (@ftell($this->zip_fd) != $v_size) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + @fseek($this->zip_fd, $v_size-22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) + $v_maximum_size = $v_size; + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) + { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = ( ($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) + { + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) + { + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, + 'The central dir is not at the end of the archive.' + .' Some trailing bytes exists after the archive.'); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Get comment + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } + else + $p_central_dir['comment'] = ''; + + $p_central_dir['entries'] = $v_data['entries']; + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + $p_central_dir['offset'] = $v_data['offset']; + $p_central_dir['size'] = $v_data['size']; + $p_central_dir['disk'] = $v_data['disk']; + $p_central_dir['disk_start'] = $v_data['disk_start']; + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + //} + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDeleteByRule(&$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) + { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) + { + + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) + { + // ----- Close the zip file + $this->privCloseFd(); + + return $v_result; + } + + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ( (isset($p_options[PCLZIP_OPT_BY_NAME])) + && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + + // ----- Look if the filename is in the list + for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) { + + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { + + // ----- Look if the directory is in the filename path + if ( (strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) + && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ + && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + } + // ----- Look for a filename + elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + $v_found = true; + } + } + } + + // ----- Look for extract by ereg rule + // ereg() is deprecated with PHP 5.3 + /* + else if ( (isset($p_options[PCLZIP_OPT_BY_EREG])) + && ($p_options[PCLZIP_OPT_BY_EREG] != "")) { + + if (ereg($p_options[PCLZIP_OPT_BY_EREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + */ + + // ----- Look for extract by preg rule + else if ( (isset($p_options[PCLZIP_OPT_BY_PREG])) + && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } + + // ----- Look for extract by index rule + else if ( (isset($p_options[PCLZIP_OPT_BY_INDEX])) + && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + + // ----- Look if the index is in the list + for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) { + + if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } + else { + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) + { + unset($v_header_list[$v_nb_extracted]); + } + else + { + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $i<sizeof($v_header_list); $i++) { + + // ----- Calculate the position of the header + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, + $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + + // ----- Re-Create the Central Dir files header + for ($i=0; $i<sizeof($v_header_list); $i++) { + // ----- Create the file header + if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } + + // ----- Remove every files : reset the file + else if ($v_central_dir['entries'] != 0) { + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + function privDirCheck($p_dir, $p_is_dir=false) + { + $v_result = 1; + + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) + { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) + { + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + + // ----- Just a check + if ($p_parent_dir != $p_dir) + { + // ----- Look for parent directory + if ($p_parent_dir != "") + { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) + { + return $v_result; + } + } + } + + // ----- Create the directory + if (!@mkdir($p_dir, 0777)) + { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privMerge(&$p_archive_to_add) + { + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) + { + + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) + { + + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) + { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Open the archive_to_add file + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) + { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + return $v_result; + } + + // ----- Go to beginning of File + @rewind($p_archive_to_add->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) + { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDuplicate($p_archive_filename) + { + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) + { + + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('wb')) != 1) + { + // ----- Return + return $v_result; + } + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) + { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) + { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorLog($p_error_code=0, $p_error_string='') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } + else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + function privErrorReset() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } + else { + $this->error_code = 0; + $this->error_string = ''; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privDisableMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function privSwapBackMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ( (!function_exists("get_magic_quotes_runtime")) + || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + } + // End of class + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathReduction() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilPathReduction($p_dir) + { + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } + else if ($v_list[$i] == "..") { + $v_skip++; + } + else if ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; + } + } + // ----- Last '/' i.e. indicates a directory + else if ($i == (sizeof($v_list)-1)) { + $v_result = $v_list[$i]; + } + // ----- Double '/' inside the path + else { + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } + else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } + else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilPathInclusion() + // Description : + // This function indicates if the path $p_path is under the $p_dir tree. Or, + // said in an other way, if the file or sub-dir $p_path is inside the dir + // $p_dir. + // The function indicates also if the path is exactly the same as the dir. + // This function supports path with duplicated '/' like '//', but does not + // support '.' or '..' statements. + // Parameters : + // Return Values : + // 0 if $p_path is not inside directory $p_dir + // 1 if $p_path is inside directory $p_dir + // 2 if $p_path is exactly the same as $p_dir + // -------------------------------------------------------------------------------- + function PclZipUtilPathInclusion($p_dir, $p_path) + { + $v_result = 1; + + // ----- Look for path beginning by ./ + if ( ($p_dir == '.') + || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_dir, 1); + } + if ( ($p_path == '.') + || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), FALSE).'/'.substr($p_path, 1); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ( $v_list_path[$j] != '')) { + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } + else if ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilCopyBlock() + // Description : + // Parameters : + // $p_mode : read/write compression mode + // 0 : src & dest normal + // 1 : src gzip, dest normal + // 2 : src normal, dest gzip + // 3 : src & dest gzip + // Return Values : + // -------------------------------------------------------------------------------- + function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode=0) + { + $v_result = 1; + + if ($p_mode==0) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==1) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==2) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + else if ($p_mode==3) + { + while ($p_size != 0) + { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilRename() + // Description : + // This function tries to do a simple rename() function. If it fails, it + // tries to copy the $p_src file in a new $p_dest file and then unlink the + // first one. + // Parameters : + // $p_src : Old filename + // $p_dest : New filename + // Return Values : + // 1 on success, 0 on failure. + // -------------------------------------------------------------------------------- + function PclZipUtilRename($p_src, $p_dest) + { + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; + } + else if (!@unlink($p_src)) { + $v_result = 0; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilOptionText() + // Description : + // Translate option value in text. Mainly for debug purpose. + // Parameters : + // $p_option : the option value. + // Return Values : + // The option text value. + // -------------------------------------------------------------------------------- + function PclZipUtilOptionText($p_option) + { + + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if (( ($v_prefix == 'PCLZIP_OPT') + || ($v_prefix == 'PCLZIP_CB_') + || ($v_prefix == 'PCLZIP_ATT')) + && ($v_list[$v_key] == $p_option)) { + return $v_key; + } + } + + $v_result = 'Unknown'; + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : PclZipUtilTranslateWinPath() + // Description : + // Translate windows path by replacing '\' by '/' and optionally removing + // drive letter. + // Parameters : + // $p_path : path to translate. + // $p_remove_disk_letter : true | false + // Return Values : + // The path translated. + // -------------------------------------------------------------------------------- + function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter=true) + { + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; + } + // -------------------------------------------------------------------------------- + + +?> diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt new file mode 100644 index 00000000..d1b11e25 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt @@ -0,0 +1,421 @@ +// -------------------------------------------------------------------------------- +// PclZip 2.8.2 - readme.txt +// -------------------------------------------------------------------------------- +// License GNU/LGPL - August 2009 +// Vincent Blavet - vincent@phpconcept.net +// http://www.phpconcept.net +// -------------------------------------------------------------------------------- +// $Id: readme.txt,v 1.60 2009/09/30 20:35:21 vblavet Exp $ +// -------------------------------------------------------------------------------- + + + +0 - Sommaire +============ + 1 - Introduction + 2 - What's new + 3 - Corrected bugs + 4 - Known bugs or limitations + 5 - License + 6 - Warning + 7 - Documentation + 8 - Author + 9 - Contribute + +1 - Introduction +================ + + PclZip is a library that allow you to manage a Zip archive. + + Full documentation about PclZip can be found here : http://www.phpconcept.net/pclzip + +2 - What's new +============== + + Version 2.8.2 : + - PCLZIP_CB_PRE_EXTRACT and PCLZIP_CB_POST_EXTRACT are now supported with + extraction as a string (PCLZIP_OPT_EXTRACT_AS_STRING). The string + can also be modified in the post-extract call back. + **Bugs correction : + - PCLZIP_OPT_REMOVE_ALL_PATH was not working correctly + - Remove use of eval() and do direct call to callback functions + - Correct support of 64bits systems (Thanks to WordPress team) + + Version 2.8.1 : + - Move option PCLZIP_OPT_BY_EREG to PCLZIP_OPT_BY_PREG because ereg() is + deprecated in PHP 5.3. When using option PCLZIP_OPT_BY_EREG, PclZip will + automatically replace it by PCLZIP_OPT_BY_PREG. + + Version 2.8 : + - Improve extraction of zip archive for large files by using temporary files + This feature is working like the one defined in r2.7. + Options are renamed : PCLZIP_OPT_TEMP_FILE_ON, PCLZIP_OPT_TEMP_FILE_OFF, + PCLZIP_OPT_TEMP_FILE_THRESHOLD + - Add a ratio constant PCLZIP_TEMPORARY_FILE_RATIO to configure the auto + sense of temporary file use. + - Bug correction : Reduce filepath in returned file list to remove ennoying + './/' preambule in file path. + + Version 2.7 : + - Improve creation of zip archive for large files : + PclZip will now autosense the configured memory and use temporary files + when large file is suspected. + This feature can also ne triggered by manual options in create() and add() + methods. 'PCLZIP_OPT_ADD_TEMP_FILE_ON' force the use of temporary files, + 'PCLZIP_OPT_ADD_TEMP_FILE_OFF' disable the autosense technic, + 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD' allow for configuration of a size + threshold to use temporary files. + Using "temporary files" rather than "memory" might take more time, but + might give the ability to zip very large files : + Tested on my win laptop with a 88Mo file : + Zip "in-memory" : 18sec (max_execution_time=30, memory_limit=180Mo) + Zip "tmporary-files" : 23sec (max_execution_time=30, memory_limit=30Mo) + - Replace use of mktime() by time() to limit the E_STRICT error messages. + - Bug correction : When adding files with full windows path (drive letter) + PclZip is now working. Before, if the drive letter is not the default + path, PclZip was not able to add the file. + + Version 2.6 : + - Code optimisation + - New attributes PCLZIP_ATT_FILE_COMMENT gives the ability to + add a comment for a specific file. (Don't really know if this is usefull) + - New attribute PCLZIP_ATT_FILE_CONTENT gives the ability to add a string + as a file. + - New attribute PCLZIP_ATT_FILE_MTIME modify the timestamp associated with + a file. + - Correct a bug. Files archived with a timestamp with 0h0m0s were extracted + with current time + - Add CRC value in the informations returned back for each file after an + action. + - Add missing closedir() statement. + - When adding a folder, and removing the path of this folder, files were + incorrectly added with a '/' at the beginning. Which means files are + related to root in unix systems. Corrected. + - Add conditional if before constant definition. This will allow users + to redefine constants without changing the file, and then improve + upgrade of pclzip code for new versions. + + Version 2.5 : + - Introduce the ability to add file/folder with individual properties (file descriptor). + This gives for example the ability to change the filename of a zipped file. + . Able to add files individually + . Able to change full name + . Able to change short name + . Compatible with global options + - New attributes : PCLZIP_ATT_FILE_NAME, PCLZIP_ATT_FILE_NEW_SHORT_NAME, PCLZIP_ATT_FILE_NEW_FULL_NAME + - New error code : PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE + - Add a security control feature. PclZip can extract any file in any folder + of a system. People may use this to upload a zip file and try to override + a system file. The PCLZIP_OPT_EXTRACT_DIR_RESTRICTION will give the + ability to forgive any directory transversal behavior. + - New PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : check extraction path + - New error code : PCLZIP_ERR_DIRECTORY_RESTRICTION + - Modification in PclZipUtilPathInclusion() : dir and path beginning with ./ will be prepend + by current path (getcwd()) + + Version 2.4 : + - Code improvment : try to speed up the code by removing unusefull call to pack() + - Correct bug in delete() : delete() should be called with no argument. This was not + the case in 2.3. This is corrected in 2.4. + - Correct a bug in path_inclusion function. When the path has several '../../', the + result was bad. + - Add a check for magic_quotes_runtime configuration. If enabled, PclZip will + disable it while working and det it back to its original value. + This resolve a lots of bad formated archive errors. + - Bug correction : PclZip now correctly unzip file in some specific situation, + when compressed content has same size as uncompressed content. + - Bug correction : When selecting option 'PCLZIP_OPT_REMOVE_ALL_PATH', + directories are not any more created. + - Code improvment : correct unclosed opendir(), better handling of . and .. in + loops. + + + Version 2.3 : + - Correct a bug with PHP5 : affecting the value 0xFE49FFE0 to a variable does not + give the same result in PHP4 and PHP5 .... + + Version 2.2 : + - Try development of PCLZIP_OPT_CRYPT ..... + However this becomes to a stop. To crypt/decrypt I need to multiply 2 long integers, + the result (greater than a long) is not supported by PHP. Even the use of bcmath + functions does not help. I did not find yet a solution ...; + - Add missing '/' at end of directory entries + - Check is a file is encrypted or not. Returns status 'unsupported_encryption' and/or + error code PCLZIP_ERR_UNSUPPORTED_ENCRYPTION. + - Corrected : Bad "version need to extract" field in local file header + - Add private method privCheckFileHeaders() in order to check local and central + file headers. PclZip is now supporting purpose bit flag bit 3. Purpose bit flag bit 3 gives + the ability to have a local file header without size, compressed size and crc filled. + - Add a generic status 'error' for file status + - Add control of compression type. PclZip only support deflate compression method. + Before v2.2, PclZip does not check the compression method used in an archive while + extracting. With v2.2 PclZip returns a new error status for a file using an unsupported + compression method. New status is "unsupported_compression". New error code is + PCLZIP_ERR_UNSUPPORTED_COMPRESSION. + - Add optional attribute PCLZIP_OPT_STOP_ON_ERROR. This will stop the extract of files + when errors like 'a folder with same name exists' or 'a newer file exists' or + 'a write protected file' exists, rather than set a status for the concerning file + and resume the extract of the zip. + - Add optional attribute PCLZIP_OPT_REPLACE_NEWER. This will force, during an extract' the + replacement of the file, even if a newer version of the file exists. + Note that today if a file with the same name already exists but is older it will be + replaced by the extracted one. + - Improve PclZipUtilOption() + - Support of zip archive with trailing bytes. Before 2.2, PclZip checks that the central + directory structure is the last data in the archive. Crypt encryption/decryption of + zip archive put trailing 0 bytes after decryption. PclZip is now supporting this. + + Version 2.1 : + - Add the ability to abort the extraction by using a user callback function. + The user can now return the value '2' in its callback which indicates to stop the + extraction. For a pre call-back extract is stopped before the extration of the current + file. For a post call back, the extraction is stopped after. + - Add the ability to extract a file (or several files) directly in the standard output. + This is done by the new parameter PCLZIP_OPT_EXTRACT_IN_OUTPUT with method extract(). + - Add support for parameters PCLZIP_OPT_COMMENT, PCLZIP_OPT_ADD_COMMENT, + PCLZIP_OPT_PREPEND_COMMENT. This will create, replace, add, or prepend comments + in the zip archive. + - When merging two archives, the comments are not any more lost, but merged, with a + blank space separator. + - Corrected bug : Files are not deleted when all files are asked to be deleted. + - Corrected bug : Folders with name '0' made PclZip to abort the create or add feature. + + + Version 2.0 : + ***** Warning : Some new features may break the backward compatibility for your scripts. + Please carefully read the readme file. + - Add the ability to delete by Index, name and regular expression. This feature is + performed by the method delete(), which uses the optional parameters + PCLZIP_OPT_BY_INDEX, PCLZIP_OPT_BY_NAME, PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG. + - Add the ability to extract by regular expression. To extract by regexp you must use the method + extract(), with the option PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG + (depending if you want to use ereg() or preg_match() syntax) followed by the + regular expression pattern. + - Add the ability to extract by index, directly with the extract() method. This is a + code improvment of the extractByIndex() method. + - Add the ability to extract by name. To extract by name you must use the method + extract(), with the option PCLZIP_OPT_BY_NAME followed by the filename to + extract or an array of filenames to extract. To extract all a folder, use the folder + name rather than the filename with a '/' at the end. + - Add the ability to add files without compression. This is done with a new attribute + which is PCLZIP_OPT_NO_COMPRESSION. + - Add the attribute PCLZIP_OPT_EXTRACT_AS_STRING, which allow to extract a file directly + in a string without using any file (or temporary file). + - Add constant PCLZIP_SEPARATOR for static configuration of filename separators in a single string. + The default separator is now a comma (,) and not any more a blank space. + THIS BREAK THE BACKWARD COMPATIBILITY : Please check if this may have an impact with + your script. + - Improve algorythm performance by removing the use of temporary files when adding or + extracting files in an archive. + - Add (correct) detection of empty filename zipping. This can occurs when the removed + path is the same + as a zipped dir. The dir is not zipped (['status'] = filtered), only its content. + - Add better support for windows paths (thanks for help from manus@manusfreedom.com). + - Corrected bug : When the archive file already exists with size=0, the add() method + fails. Corrected in 2.0. + - Remove the use of OS_WINDOWS constant. Use php_uname() function rather. + - Control the order of index ranges in extract by index feature. + - Change the internal management of folders (better handling of internal flag). + + + Version 1.3 : + - Removing the double include check. This is now done by include_once() and require_once() + PHP directives. + - Changing the error handling mecanism : Remove the use of an external error library. + The former PclError...() functions are replaced by internal equivalent methods. + By changing the environment variable PCLZIP_ERROR_EXTERNAL you can still use the former library. + Introducing the use of constants for error codes rather than integer values. This will help + in futur improvment. + Introduction of error handling functions like errorCode(), errorName() and errorInfo(). + - Remove the deprecated use of calling function with arguments passed by reference. + - Add the calling of extract(), extractByIndex(), create() and add() functions + with variable options rather than fixed arguments. + - Add the ability to remove all the file path while extracting or adding, + without any need to specify the path to remove. + This is available for extract(), extractByIndex(), create() and add() functionS by using + the new variable options parameters : + - PCLZIP_OPT_REMOVE_ALL_PATH : by indicating this option while calling the fct. + - Ability to change the mode of a file after the extraction (chmod()). + This is available for extract() and extractByIndex() functionS by using + the new variable options parameters. + - PCLZIP_OPT_SET_CHMOD : by setting the value of this option. + - Ability to definition call-back options. These call-back will be called during the adding, + or the extracting of file (extract(), extractByIndex(), create() and add() functions) : + - PCLZIP_CB_PRE_EXTRACT : will be called before each extraction of a file. The user + can trigerred the change the filename of the extracted file. The user can triggered the + skip of the extraction. This is adding a 'skipped' status in the file list result value. + - PCLZIP_CB_POST_EXTRACT : will be called after each extraction of a file. + Nothing can be triggered from that point. + - PCLZIP_CB_PRE_ADD : will be called before each add of a file. The user + can trigerred the change the stored filename of the added file. The user can triggered the + skip of the add. This is adding a 'skipped' status in the file list result value. + - PCLZIP_CB_POST_ADD : will be called after each add of a file. + Nothing can be triggered from that point. + - Two status are added in the file list returned as function result : skipped & filename_too_long + 'skipped' is used when a call-back function ask for skipping the file. + 'filename_too_long' is used while adding a file with a too long filename to archive (the file is + not added) + - Adding the function PclZipUtilPathInclusion(), that check the inclusion of a path into + a directory. + - Add a check of the presence of the archive file before some actions (like list, ...) + - Add the initialisation of field "index" in header array. This means that by + default index will be -1 when not explicitly set by the methods. + + Version 1.2 : + - Adding a duplicate function. + - Adding a merge function. The merge function is a "quick merge" function, + it just append the content of an archive at the end of the first one. There + is no check for duplicate files or more recent files. + - Improve the search of the central directory end. + + Version 1.1.2 : + + - Changing the license of PclZip. PclZip is now released under the GNU / LGPL license + (see License section). + - Adding the optional support of a static temporary directory. You will need to configure + the constant PCLZIP_TEMPORARY_DIR if you want to use this feature. + - Improving the rename() function. In some cases rename() does not work (different + Filesystems), so it will be replaced by a copy() + unlink() functions. + + Version 1.1.1 : + + - Maintenance release, no new feature. + + Version 1.1 : + + - New method Add() : adding files in the archive + - New method ExtractByIndex() : partial extract of the archive, files are identified by + their index in the archive + - New method DeleteByIndex() : delete some files/folder entries from the archive, + files are identified by their index in the archive. + - Adding a test of the zlib extension presence. If not present abort the script. + + Version 1.0.1 : + + - No new feature + + +3 - Corrected bugs +================== + + Corrected in Version 2.0 : + - Corrected : During an extraction, if a call-back fucntion is used and try to skip + a file, all the extraction process is stopped. + + Corrected in Version 1.3 : + - Corrected : Support of static synopsis for method extract() is broken. + - Corrected : invalid size of archive content field (0xFF) should be (0xFFFF). + - Corrected : When an extract is done with a remove_path parameter, the entry for + the directory with exactly the same path is not skipped/filtered. + - Corrected : extractByIndex() and deleteByIndex() were not managing index in the + right way. For example indexes '1,3-5,11' will only extract files 1 and 11. This + is due to a sort of the index resulting table that puts 11 before 3-5 (sort on + string and not interger). The sort is temporarilly removed, this means that + you must provide a sorted list of index ranges. + + Corrected in Version 1.2 : + + - Nothing. + + Corrected in Version 1.1.2 : + + - Corrected : Winzip is unable to delete or add new files in a PclZip created archives. + + Corrected in Version 1.1.1 : + + - Corrected : When archived file is not compressed (0% compression), the + extract method fails. + + Corrected in Version 1.1 : + + - Corrected : Adding a complete tree of folder may result in a bad archive + creation. + + Corrected in Version 1.0.1 : + + - Corrected : Error while compressing files greater than PCLZIP_READ_BLOCK_SIZE (default=1024). + + +4 - Known bugs or limitations +============================= + + Please publish bugs reports in SourceForge : + http://sourceforge.net/tracker/?group_id=40254&atid=427564 + + In Version 2.x : + - PclZip does only support file uncompressed or compressed with deflate (compression method 8) + - PclZip does not support password protected zip archive + - Some concern were seen when changing mtime of a file while archiving. + Seems to be linked to Daylight Saving Time (PclTest_changing_mtime). + + In Version 1.2 : + + - merge() methods does not check for duplicate files or last date of modifications. + + In Version 1.1 : + + - Limitation : Using 'extract' fields in the file header in the zip archive is not supported. + - WinZip is unable to delete a single file in a PclZip created archive. It is also unable to + add a file in a PclZip created archive. (Corrected in v.1.2) + + In Version 1.0.1 : + + - Adding a complete tree of folder may result in a bad archive + creation. (Corrected in V.1.1). + - Path given to methods must be in the unix format (/) and not the Windows format (\). + Workaround : Use only / directory separators. + - PclZip is using temporary files that are sometime the name of the file with a .tmp or .gz + added suffix. Files with these names may already exist and may be overwritten. + Workaround : none. + - PclZip does not check if the zlib extension is present. If it is absent, the zip + file is not created and the lib abort without warning. + Workaround : enable the zlib extension on the php install + + In Version 1.0 : + + - Error while compressing files greater than PCLZIP_READ_BLOCK_SIZE (default=1024). + (Corrected in v.1.0.1) + - Limitation : Multi-disk zip archive are not supported. + + +5 - License +=========== + + Since version 1.1.2, PclZip Library is released under GNU/LGPL license. + This library is free, so you can use it at no cost. + + HOWEVER, if you release a script, an application, a library or any kind of + code using PclZip library (or a part of it), YOU MUST : + - Indicate in the documentation (or a readme file), that your work + uses PclZip Library, and make a reference to the author and the web site + http://www.phpconcept.net + - Gives the ability to the final user to update the PclZip libary. + + I will also appreciate that you send me a mail (vincent@phpconcept.net), just to + be aware that someone is using PclZip. + + For more information about GNU/LGPL license : http://www.gnu.org + +6 - Warning +================= + + This library and the associated files are non commercial, non professional work. + It should not have unexpected results. However if any damage is caused by this software + the author can not be responsible. + The use of this software is at the risk of the user. + +7 - Documentation +================= + PclZip User Manuel is available in English on PhpConcept : http://www.phpconcept.net/pclzip/man/en/index.php + A Russian translation was done by Feskov Kuzma : http://php.russofile.ru/ru/authors/unsort/zip/ + +8 - Author +========== + + This software was written by Vincent Blavet (vincent@phpconcept.net) on its leasure time. + +9 - Contribute +============== + If you want to contribute to the development of PclZip, please contact vincent@phpconcept.net. + If you can help in financing PhpConcept hosting service, please go to + http://www.phpconcept.net/soutien.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php new file mode 100644 index 00000000..4f505a2a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php @@ -0,0 +1,66 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_PasswordHasher + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_PasswordHasher +{ + /** + * Create a password hash from a given string. + * + * This method is based on the algorithm provided by + * Daniel Rentz of OpenOffice and the PEAR package + * Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>. + * + * @param string $pPassword Password to hash + * @return string Hashed password + */ + public static function hashPassword($pPassword = '') { + $password = 0x0000; + $charPos = 1; // char position + + // split the plain text password in its component characters + $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY); + foreach ($chars as $char) { + $value = ord($char) << $charPos++; // shifted ASCII value + $rotated_bits = $value >> 15; // rotated bits beyond bit 15 + $value &= 0x7fff; // first 15 bits + $password ^= ($value | $rotated_bits); + } + + $password ^= strlen($pPassword); + $password ^= 0xCE4B; + + return(strtoupper(dechex($password))); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php new file mode 100644 index 00000000..49d217a5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php @@ -0,0 +1,776 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_String + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_String +{ + /** Constants */ + /** Regular Expressions */ + // Fraction + const STRING_REGEXP_FRACTION = '(-?)(\d+)\s+(\d+\/\d+)'; + + + /** + * Control characters array + * + * @var string[] + */ + private static $_controlCharacters = array(); + + /** + * SYLK Characters array + * + * $var array + */ + private static $_SYLKCharacters = array(); + + /** + * Decimal separator + * + * @var string + */ + private static $_decimalSeparator; + + /** + * Thousands separator + * + * @var string + */ + private static $_thousandsSeparator; + + /** + * Currency code + * + * @var string + */ + private static $_currencyCode; + + /** + * Is mbstring extension avalable? + * + * @var boolean + */ + private static $_isMbstringEnabled; + + /** + * Is iconv extension avalable? + * + * @var boolean + */ + private static $_isIconvEnabled; + + /** + * Build control characters array + */ + private static function _buildControlCharacters() { + for ($i = 0; $i <= 31; ++$i) { + if ($i != 9 && $i != 10 && $i != 13) { + $find = '_x' . sprintf('%04s' , strtoupper(dechex($i))) . '_'; + $replace = chr($i); + self::$_controlCharacters[$find] = $replace; + } + } + } + + /** + * Build SYLK characters array + */ + private static function _buildSYLKCharacters() + { + self::$_SYLKCharacters = array( + "\x1B 0" => chr(0), + "\x1B 1" => chr(1), + "\x1B 2" => chr(2), + "\x1B 3" => chr(3), + "\x1B 4" => chr(4), + "\x1B 5" => chr(5), + "\x1B 6" => chr(6), + "\x1B 7" => chr(7), + "\x1B 8" => chr(8), + "\x1B 9" => chr(9), + "\x1B :" => chr(10), + "\x1B ;" => chr(11), + "\x1B <" => chr(12), + "\x1B :" => chr(13), + "\x1B >" => chr(14), + "\x1B ?" => chr(15), + "\x1B!0" => chr(16), + "\x1B!1" => chr(17), + "\x1B!2" => chr(18), + "\x1B!3" => chr(19), + "\x1B!4" => chr(20), + "\x1B!5" => chr(21), + "\x1B!6" => chr(22), + "\x1B!7" => chr(23), + "\x1B!8" => chr(24), + "\x1B!9" => chr(25), + "\x1B!:" => chr(26), + "\x1B!;" => chr(27), + "\x1B!<" => chr(28), + "\x1B!=" => chr(29), + "\x1B!>" => chr(30), + "\x1B!?" => chr(31), + "\x1B'?" => chr(127), + "\x1B(0" => '€', // 128 in CP1252 + "\x1B(2" => '‚', // 130 in CP1252 + "\x1B(3" => 'ƒ', // 131 in CP1252 + "\x1B(4" => '„', // 132 in CP1252 + "\x1B(5" => '…', // 133 in CP1252 + "\x1B(6" => '†', // 134 in CP1252 + "\x1B(7" => '‡', // 135 in CP1252 + "\x1B(8" => 'ˆ', // 136 in CP1252 + "\x1B(9" => '‰', // 137 in CP1252 + "\x1B(:" => 'Š', // 138 in CP1252 + "\x1B(;" => '‹', // 139 in CP1252 + "\x1BNj" => 'Œ', // 140 in CP1252 + "\x1B(>" => 'Ž', // 142 in CP1252 + "\x1B)1" => '‘', // 145 in CP1252 + "\x1B)2" => '’', // 146 in CP1252 + "\x1B)3" => '“', // 147 in CP1252 + "\x1B)4" => '”', // 148 in CP1252 + "\x1B)5" => '•', // 149 in CP1252 + "\x1B)6" => '–', // 150 in CP1252 + "\x1B)7" => '—', // 151 in CP1252 + "\x1B)8" => '˜', // 152 in CP1252 + "\x1B)9" => '™', // 153 in CP1252 + "\x1B):" => 'š', // 154 in CP1252 + "\x1B);" => '›', // 155 in CP1252 + "\x1BNz" => 'œ', // 156 in CP1252 + "\x1B)>" => 'ž', // 158 in CP1252 + "\x1B)?" => 'Ÿ', // 159 in CP1252 + "\x1B*0" => ' ', // 160 in CP1252 + "\x1BN!" => '¡', // 161 in CP1252 + "\x1BN\"" => '¢', // 162 in CP1252 + "\x1BN#" => '£', // 163 in CP1252 + "\x1BN(" => '¤', // 164 in CP1252 + "\x1BN%" => '¥', // 165 in CP1252 + "\x1B*6" => '¦', // 166 in CP1252 + "\x1BN'" => '§', // 167 in CP1252 + "\x1BNH " => '¨', // 168 in CP1252 + "\x1BNS" => '©', // 169 in CP1252 + "\x1BNc" => 'ª', // 170 in CP1252 + "\x1BN+" => '«', // 171 in CP1252 + "\x1B*<" => '¬', // 172 in CP1252 + "\x1B*=" => '­', // 173 in CP1252 + "\x1BNR" => '®', // 174 in CP1252 + "\x1B*?" => '¯', // 175 in CP1252 + "\x1BN0" => '°', // 176 in CP1252 + "\x1BN1" => '±', // 177 in CP1252 + "\x1BN2" => '²', // 178 in CP1252 + "\x1BN3" => '³', // 179 in CP1252 + "\x1BNB " => '´', // 180 in CP1252 + "\x1BN5" => 'µ', // 181 in CP1252 + "\x1BN6" => '¶', // 182 in CP1252 + "\x1BN7" => '·', // 183 in CP1252 + "\x1B+8" => '¸', // 184 in CP1252 + "\x1BNQ" => '¹', // 185 in CP1252 + "\x1BNk" => 'º', // 186 in CP1252 + "\x1BN;" => '»', // 187 in CP1252 + "\x1BN<" => '¼', // 188 in CP1252 + "\x1BN=" => '½', // 189 in CP1252 + "\x1BN>" => '¾', // 190 in CP1252 + "\x1BN?" => '¿', // 191 in CP1252 + "\x1BNAA" => 'À', // 192 in CP1252 + "\x1BNBA" => 'Á', // 193 in CP1252 + "\x1BNCA" => 'Â', // 194 in CP1252 + "\x1BNDA" => 'Ã', // 195 in CP1252 + "\x1BNHA" => 'Ä', // 196 in CP1252 + "\x1BNJA" => 'Å', // 197 in CP1252 + "\x1BNa" => 'Æ', // 198 in CP1252 + "\x1BNKC" => 'Ç', // 199 in CP1252 + "\x1BNAE" => 'È', // 200 in CP1252 + "\x1BNBE" => 'É', // 201 in CP1252 + "\x1BNCE" => 'Ê', // 202 in CP1252 + "\x1BNHE" => 'Ë', // 203 in CP1252 + "\x1BNAI" => 'Ì', // 204 in CP1252 + "\x1BNBI" => 'Í', // 205 in CP1252 + "\x1BNCI" => 'Î', // 206 in CP1252 + "\x1BNHI" => 'Ï', // 207 in CP1252 + "\x1BNb" => 'Ð', // 208 in CP1252 + "\x1BNDN" => 'Ñ', // 209 in CP1252 + "\x1BNAO" => 'Ò', // 210 in CP1252 + "\x1BNBO" => 'Ó', // 211 in CP1252 + "\x1BNCO" => 'Ô', // 212 in CP1252 + "\x1BNDO" => 'Õ', // 213 in CP1252 + "\x1BNHO" => 'Ö', // 214 in CP1252 + "\x1B-7" => '×', // 215 in CP1252 + "\x1BNi" => 'Ø', // 216 in CP1252 + "\x1BNAU" => 'Ù', // 217 in CP1252 + "\x1BNBU" => 'Ú', // 218 in CP1252 + "\x1BNCU" => 'Û', // 219 in CP1252 + "\x1BNHU" => 'Ü', // 220 in CP1252 + "\x1B-=" => 'Ý', // 221 in CP1252 + "\x1BNl" => 'Þ', // 222 in CP1252 + "\x1BN{" => 'ß', // 223 in CP1252 + "\x1BNAa" => 'à', // 224 in CP1252 + "\x1BNBa" => 'á', // 225 in CP1252 + "\x1BNCa" => 'â', // 226 in CP1252 + "\x1BNDa" => 'ã', // 227 in CP1252 + "\x1BNHa" => 'ä', // 228 in CP1252 + "\x1BNJa" => 'å', // 229 in CP1252 + "\x1BNq" => 'æ', // 230 in CP1252 + "\x1BNKc" => 'ç', // 231 in CP1252 + "\x1BNAe" => 'è', // 232 in CP1252 + "\x1BNBe" => 'é', // 233 in CP1252 + "\x1BNCe" => 'ê', // 234 in CP1252 + "\x1BNHe" => 'ë', // 235 in CP1252 + "\x1BNAi" => 'ì', // 236 in CP1252 + "\x1BNBi" => 'í', // 237 in CP1252 + "\x1BNCi" => 'î', // 238 in CP1252 + "\x1BNHi" => 'ï', // 239 in CP1252 + "\x1BNs" => 'ð', // 240 in CP1252 + "\x1BNDn" => 'ñ', // 241 in CP1252 + "\x1BNAo" => 'ò', // 242 in CP1252 + "\x1BNBo" => 'ó', // 243 in CP1252 + "\x1BNCo" => 'ô', // 244 in CP1252 + "\x1BNDo" => 'õ', // 245 in CP1252 + "\x1BNHo" => 'ö', // 246 in CP1252 + "\x1B/7" => '÷', // 247 in CP1252 + "\x1BNy" => 'ø', // 248 in CP1252 + "\x1BNAu" => 'ù', // 249 in CP1252 + "\x1BNBu" => 'ú', // 250 in CP1252 + "\x1BNCu" => 'û', // 251 in CP1252 + "\x1BNHu" => 'ü', // 252 in CP1252 + "\x1B/=" => 'ý', // 253 in CP1252 + "\x1BN|" => 'þ', // 254 in CP1252 + "\x1BNHy" => 'ÿ', // 255 in CP1252 + ); + } + + /** + * Get whether mbstring extension is available + * + * @return boolean + */ + public static function getIsMbstringEnabled() + { + if (isset(self::$_isMbstringEnabled)) { + return self::$_isMbstringEnabled; + } + + self::$_isMbstringEnabled = function_exists('mb_convert_encoding') ? + true : false; + + return self::$_isMbstringEnabled; + } + + /** + * Get whether iconv extension is available + * + * @return boolean + */ + public static function getIsIconvEnabled() + { + if (isset(self::$_isIconvEnabled)) { + return self::$_isIconvEnabled; + } + + // Fail if iconv doesn't exist + if (!function_exists('iconv')) { + self::$_isIconvEnabled = false; + return false; + } + + // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false, + if (!@iconv('UTF-8', 'UTF-16LE', 'x')) { + self::$_isIconvEnabled = false; + return false; + } + + // Sometimes iconv_substr('A', 0, 1, 'UTF-8') just returns false in PHP 5.2.0 + // we cannot use iconv in that case either (http://bugs.php.net/bug.php?id=37773) + if (!@iconv_substr('A', 0, 1, 'UTF-8')) { + self::$_isIconvEnabled = false; + return false; + } + + // CUSTOM: IBM AIX iconv() does not work + if ( defined('PHP_OS') && @stristr(PHP_OS, 'AIX') + && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) + && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0) ) + { + self::$_isIconvEnabled = false; + return false; + } + + // If we reach here no problems were detected with iconv + self::$_isIconvEnabled = true; + return true; + } + + public static function buildCharacterSets() { + if(empty(self::$_controlCharacters)) { + self::_buildControlCharacters(); + } + if(empty(self::$_SYLKCharacters)) { + self::_buildSYLKCharacters(); + } + } + + /** + * Convert from OpenXML escaped control character to PHP control character + * + * Excel 2007 team: + * ---------------- + * That's correct, control characters are stored directly in the shared-strings table. + * We do encode characters that cannot be represented in XML using the following escape sequence: + * _xHHHH_ where H represents a hexadecimal character in the character's value... + * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) + * element or in the shared string <t> element. + * + * @param string $value Value to unescape + * @return string + */ + public static function ControlCharacterOOXML2PHP($value = '') { + return str_replace( array_keys(self::$_controlCharacters), array_values(self::$_controlCharacters), $value ); + } + + /** + * Convert from PHP control character to OpenXML escaped control character + * + * Excel 2007 team: + * ---------------- + * That's correct, control characters are stored directly in the shared-strings table. + * We do encode characters that cannot be represented in XML using the following escape sequence: + * _xHHHH_ where H represents a hexadecimal character in the character's value... + * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) + * element or in the shared string <t> element. + * + * @param string $value Value to escape + * @return string + */ + public static function ControlCharacterPHP2OOXML($value = '') { + return str_replace( array_values(self::$_controlCharacters), array_keys(self::$_controlCharacters), $value ); + } + + /** + * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters. + * + * @param string $value + * @return string + */ + public static function SanitizeUTF8($value) + { + if (self::getIsIconvEnabled()) { + $value = @iconv('UTF-8', 'UTF-8', $value); + return $value; + } + + if (self::getIsMbstringEnabled()) { + $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); + return $value; + } + + // else, no conversion + return $value; + } + + /** + * Check if a string contains UTF8 data + * + * @param string $value + * @return boolean + */ + public static function IsUTF8($value = '') { + return $string === '' || preg_match('/^./su', $string) === 1; + } + + /** + * Formats a numeric value as a string for output in various output writers forcing + * point as decimal separator in case locale is other than English. + * + * @param mixed $value + * @return string + */ + public static function FormatNumber($value) { + if (is_float($value)) { + return str_replace(',', '.', $value); + } + return (string) $value; + } + + /** + * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length) + * Writes the string using uncompressed notation, no rich text, no Asian phonetics + * If mbstring extension is not available, ASCII is assumed, and compressed notation is used + * although this will give wrong results for non-ASCII strings + * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3 + * + * @param string $value UTF-8 encoded string + * @param mixed[] $arrcRuns Details of rich text runs in $value + * @return string + */ + public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = array()) + { + // character count + $ln = self::CountCharacters($value, 'UTF-8'); + // option flags + if(empty($arrcRuns)){ + $opt = (self::getIsIconvEnabled() || self::getIsMbstringEnabled()) ? + 0x0001 : 0x0000; + $data = pack('CC', $ln, $opt); + // characters + $data .= self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + } + else { + $data = pack('vC', $ln, 0x09); + $data .= pack('v', count($arrcRuns)); + // characters + $data .= self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + foreach ($arrcRuns as $cRun){ + $data .= pack('v', $cRun['strlen']); + $data .= pack('v', $cRun['fontidx']); + } + } + return $data; + } + + /** + * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length) + * Writes the string using uncompressed notation, no rich text, no Asian phonetics + * If mbstring extension is not available, ASCII is assumed, and compressed notation is used + * although this will give wrong results for non-ASCII strings + * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3 + * + * @param string $value UTF-8 encoded string + * @return string + */ + public static function UTF8toBIFF8UnicodeLong($value) + { + // character count + $ln = self::CountCharacters($value, 'UTF-8'); + + // option flags + $opt = (self::getIsIconvEnabled() || self::getIsMbstringEnabled()) ? + 0x0001 : 0x0000; + + // characters + $chars = self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + + $data = pack('vC', $ln, $opt) . $chars; + return $data; + } + + /** + * Convert string from one encoding to another. First try mbstring, then iconv, finally strlen + * + * @param string $value + * @param string $to Encoding to convert to, e.g. 'UTF-8' + * @param string $from Encoding to convert from, e.g. 'UTF-16LE' + * @return string + */ + public static function ConvertEncoding($value, $to, $from) + { + if (self::getIsIconvEnabled()) { + return iconv($from, $to, $value); + } + + if (self::getIsMbstringEnabled()) { + return mb_convert_encoding($value, $to, $from); + } + + if($from == 'UTF-16LE'){ + return self::utf16_decode($value, false); + }else if($from == 'UTF-16BE'){ + return self::utf16_decode($value); + } + // else, no conversion + return $value; + } + + /** + * Decode UTF-16 encoded strings. + * + * Can handle both BOM'ed data and un-BOM'ed data. + * Assumes Big-Endian byte order if no BOM is available. + * This function was taken from http://php.net/manual/en/function.utf8-decode.php + * and $bom_be parameter added. + * + * @param string $str UTF-16 encoded data to decode. + * @return string UTF-8 / ISO encoded data. + * @access public + * @version 0.2 / 2010-05-13 + * @author Rasmus Andersson {@link http://rasmusandersson.se/} + * @author vadik56 + */ + public static function utf16_decode($str, $bom_be = TRUE) { + if( strlen($str) < 2 ) return $str; + $c0 = ord($str{0}); + $c1 = ord($str{1}); + if( $c0 == 0xfe && $c1 == 0xff ) { $str = substr($str,2); } + elseif( $c0 == 0xff && $c1 == 0xfe ) { $str = substr($str,2); $bom_be = false; } + $len = strlen($str); + $newstr = ''; + for($i=0;$i<$len;$i+=2) { + if( $bom_be ) { $val = ord($str{$i}) << 4; $val += ord($str{$i+1}); } + else { $val = ord($str{$i+1}) << 4; $val += ord($str{$i}); } + $newstr .= ($val == 0x228) ? "\n" : chr($val); + } + return $newstr; + } + + /** + * Get character count. First try mbstring, then iconv, finally strlen + * + * @param string $value + * @param string $enc Encoding + * @return int Character count + */ + public static function CountCharacters($value, $enc = 'UTF-8') + { + if (self::getIsMbstringEnabled()) { + return mb_strlen($value, $enc); + } + + if (self::getIsIconvEnabled()) { + return iconv_strlen($value, $enc); + } + + // else strlen + return strlen($value); + } + + /** + * Get a substring of a UTF-8 encoded string. First try mbstring, then iconv, finally strlen + * + * @param string $pValue UTF-8 encoded string + * @param int $pStart Start offset + * @param int $pLength Maximum number of characters in substring + * @return string + */ + public static function Substring($pValue = '', $pStart = 0, $pLength = 0) + { + if (self::getIsMbstringEnabled()) { + return mb_substr($pValue, $pStart, $pLength, 'UTF-8'); + } + + if (self::getIsIconvEnabled()) { + return iconv_substr($pValue, $pStart, $pLength, 'UTF-8'); + } + + // else substr + return substr($pValue, $pStart, $pLength); + } + + /** + * Convert a UTF-8 encoded string to upper case + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToUpper($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_UPPER, "UTF-8"); + } + return strtoupper($pValue); + } + + /** + * Convert a UTF-8 encoded string to lower case + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToLower($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_LOWER, "UTF-8"); + } + return strtolower($pValue); + } + + /** + * Convert a UTF-8 encoded string to title/proper case + * (uppercase every first character in each word, lower case all other characters) + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToTitle($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_TITLE, "UTF-8"); + } + return ucwords($pValue); + } + + /** + * Identify whether a string contains a fractional numeric value, + * and convert it to a numeric if it is + * + * @param string &$operand string value to test + * @return boolean + */ + public static function convertToNumberIfFraction(&$operand) { + if (preg_match('/^'.self::STRING_REGEXP_FRACTION.'$/i', $operand, $match)) { + $sign = ($match[1] == '-') ? '-' : '+'; + $fractionFormula = '='.$sign.$match[2].$sign.$match[3]; + $operand = PHPExcel_Calculation::getInstance()->_calculateFormulaValue($fractionFormula); + return true; + } + return false; + } // function convertToNumberIfFraction() + + /** + * Get the decimal separator. If it has not yet been set explicitly, try to obtain number + * formatting information from locale. + * + * @return string + */ + public static function getDecimalSeparator() + { + if (!isset(self::$_decimalSeparator)) { + $localeconv = localeconv(); + self::$_decimalSeparator = ($localeconv['decimal_point'] != '') + ? $localeconv['decimal_point'] : $localeconv['mon_decimal_point']; + + if (self::$_decimalSeparator == '') { + // Default to . + self::$_decimalSeparator = '.'; + } + } + return self::$_decimalSeparator; + } + + /** + * Set the decimal separator. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for decimal separator + */ + public static function setDecimalSeparator($pValue = '.') + { + self::$_decimalSeparator = $pValue; + } + + /** + * Get the thousands separator. If it has not yet been set explicitly, try to obtain number + * formatting information from locale. + * + * @return string + */ + public static function getThousandsSeparator() + { + if (!isset(self::$_thousandsSeparator)) { + $localeconv = localeconv(); + self::$_thousandsSeparator = ($localeconv['thousands_sep'] != '') + ? $localeconv['thousands_sep'] : $localeconv['mon_thousands_sep']; + + if (self::$_thousandsSeparator == '') { + // Default to . + self::$_thousandsSeparator = ','; + } + } + return self::$_thousandsSeparator; + } + + /** + * Set the thousands separator. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for thousands separator + */ + public static function setThousandsSeparator($pValue = ',') + { + self::$_thousandsSeparator = $pValue; + } + + /** + * Get the currency code. If it has not yet been set explicitly, try to obtain the + * symbol information from locale. + * + * @return string + */ + public static function getCurrencyCode() + { + if (!isset(self::$_currencyCode)) { + $localeconv = localeconv(); + self::$_currencyCode = ($localeconv['currency_symbol'] != '') + ? $localeconv['currency_symbol'] : $localeconv['int_curr_symbol']; + + if (self::$_currencyCode == '') { + // Default to $ + self::$_currencyCode = '$'; + } + } + return self::$_currencyCode; + } + + /** + * Set the currency code. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for currency code + */ + public static function setCurrencyCode($pValue = '$') + { + self::$_currencyCode = $pValue; + } + + /** + * Convert SYLK encoded string to UTF-8 + * + * @param string $pValue + * @return string UTF-8 encoded string + */ + public static function SYLKtoUTF8($pValue = '') + { + // If there is no escape character in the string there is nothing to do + if (strpos($pValue, '') === false) { + return $pValue; + } + + foreach (self::$_SYLKCharacters as $k => $v) { + $pValue = str_replace($k, $v, $pValue); + } + + return $pValue; + } + + /** + * Retrieve any leading numeric part of a string, or return the full string if no leading numeric + * (handles basic integer or float, but not exponent or non decimal) + * + * @param string $value + * @return mixed string or only the leading numeric part of the string + */ + public static function testStringAsNumeric($value) + { + if (is_numeric($value)) + return $value; + $v = floatval($value); + return (is_numeric(substr($value,0,strlen($v)))) ? $v : $value; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php new file mode 100644 index 00000000..d5fa2ade --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php @@ -0,0 +1,140 @@ +<?php + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_TimeZone + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_TimeZone +{ + /* + * Default Timezone used for date/time conversions + * + * @private + * @var string + */ + protected static $_timezone = 'UTC'; + + /** + * Validate a Timezone name + * + * @param string $timezone Time zone (e.g. 'Europe/London') + * @return boolean Success or failure + */ + public static function _validateTimeZone($timezone) { + if (in_array($timezone, DateTimeZone::listIdentifiers())) { + return TRUE; + } + return FALSE; + } + + /** + * Set the Default Timezone used for date/time conversions + * + * @param string $timezone Time zone (e.g. 'Europe/London') + * @return boolean Success or failure + */ + public static function setTimeZone($timezone) { + if (self::_validateTimezone($timezone)) { + self::$_timezone = $timezone; + return TRUE; + } + return FALSE; + } // function setTimezone() + + + /** + * Return the Default Timezone used for date/time conversions + * + * @return string Timezone (e.g. 'Europe/London') + */ + public static function getTimeZone() { + return self::$_timezone; + } // function getTimezone() + + + /** + * Return the Timezone transition for the specified timezone and timestamp + * + * @param DateTimeZone $objTimezone The timezone for finding the transitions + * @param integer $timestamp PHP date/time value for finding the current transition + * @return array The current transition details + */ + private static function _getTimezoneTransitions($objTimezone, $timestamp) { + $allTransitions = $objTimezone->getTransitions(); + $transitions = array(); + foreach($allTransitions as $key => $transition) { + if ($transition['ts'] > $timestamp) { + $transitions[] = ($key > 0) ? $allTransitions[$key - 1] : $transition; + break; + } + if (empty($transitions)) { + $transitions[] = end($allTransitions); + } + } + + return $transitions; + } + + /** + * Return the Timezone offset used for date/time conversions to/from UST + * This requires both the timezone and the calculated date/time to allow for local DST + * + * @param string $timezone The timezone for finding the adjustment to UST + * @param integer $timestamp PHP date/time value + * @return integer Number of seconds for timezone adjustment + * @throws PHPExcel_Exception + */ + public static function getTimeZoneAdjustment($timezone, $timestamp) { + if ($timezone !== NULL) { + if (!self::_validateTimezone($timezone)) { + throw new PHPExcel_Exception("Invalid timezone " . $timezone); + } + } else { + $timezone = self::$_timezone; + } + + if ($timezone == 'UST') { + return 0; + } + + $objTimezone = new DateTimeZone($timezone); + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + $transitions = $objTimezone->getTransitions($timestamp,$timestamp); + } else { + $transitions = self::_getTimezoneTransitions($objTimezone, $timestamp); + } + + return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php new file mode 100644 index 00000000..0b0b5539 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php @@ -0,0 +1,127 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +if (!defined('DATE_W3C')) { + define('DATE_W3C', 'Y-m-d\TH:i:sP'); +} + +if (!defined('DEBUGMODE_ENABLED')) { + define('DEBUGMODE_ENABLED', false); +} + + +/** + * PHPExcel_Shared_XMLWriter + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_XMLWriter extends XMLWriter { + /** Temporary storage method */ + const STORAGE_MEMORY = 1; + const STORAGE_DISK = 2; + + /** + * Temporary filename + * + * @var string + */ + private $_tempFileName = ''; + + /** + * Create a new PHPExcel_Shared_XMLWriter instance + * + * @param int $pTemporaryStorage Temporary storage location + * @param string $pTemporaryStorageFolder Temporary storage folder + */ + public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = NULL) { + // Open temporary storage + if ($pTemporaryStorage == self::STORAGE_MEMORY) { + $this->openMemory(); + } else { + // Create temporary filename + if ($pTemporaryStorageFolder === NULL) + $pTemporaryStorageFolder = PHPExcel_Shared_File::sys_get_temp_dir(); + $this->_tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); + + // Open storage + if ($this->openUri($this->_tempFileName) === false) { + // Fallback to memory... + $this->openMemory(); + } + } + + // Set default values + if (DEBUGMODE_ENABLED) { + $this->setIndent(true); + } + } + + /** + * Destructor + */ + public function __destruct() { + // Unlink temporary files + if ($this->_tempFileName != '') { + @unlink($this->_tempFileName); + } + } + + /** + * Get written data + * + * @return $data + */ + public function getData() { + if ($this->_tempFileName == '') { + return $this->outputMemory(true); + } else { + $this->flush(); + return file_get_contents($this->_tempFileName); + } + } + + /** + * Fallback method for writeRaw, introduced in PHP 5.2 + * + * @param string $text + * @return string + */ + public function writeRawData($text) + { + if (is_array($text)) { + $text = implode("\n",$text); + } + + if (method_exists($this, 'writeRaw')) { + return $this->writeRaw(htmlspecialchars($text)); + } + + return $this->text($text); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php new file mode 100644 index 00000000..ab551afe --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php @@ -0,0 +1,175 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_ZipArchive + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', PHPExcel_Shared_File::sys_get_temp_dir()); +} +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/PCLZip/pclzip.lib.php'; + + +/** + * PHPExcel_Shared_ZipArchive + * + * @category PHPExcel + * @package PHPExcel_Shared_ZipArchive + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_ZipArchive +{ + + /** constants */ + const OVERWRITE = 'OVERWRITE'; + const CREATE = 'CREATE'; + + + /** + * Temporary storage directory + * + * @var string + */ + private $_tempDir; + + /** + * Zip Archive Stream Handle + * + * @var string + */ + private $_zip; + + + /** + * Open a new zip archive + * + * @param string $fileName Filename for the zip archive + * @return boolean + */ + public function open($fileName) + { + $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + + $this->_zip = new PclZip($fileName); + + return true; + } + + + /** + * Close this zip archive + * + */ + public function close() + { + } + + + /** + * Add a new file to the zip archive from a string of raw data. + * + * @param string $localname Directory/Name of the file to add to the zip archive + * @param string $contents String of data to add to the zip archive + */ + public function addFromString($localname, $contents) + { + $filenameParts = pathinfo($localname); + + $handle = fopen($this->_tempDir.'/'.$filenameParts["basename"], "wb"); + fwrite($handle, $contents); + fclose($handle); + + $res = $this->_zip->add($this->_tempDir.'/'.$filenameParts["basename"], + PCLZIP_OPT_REMOVE_PATH, $this->_tempDir, + PCLZIP_OPT_ADD_PATH, $filenameParts["dirname"] + ); + if ($res == 0) { + throw new PHPExcel_Writer_Exception("Error zipping files : " . $this->_zip->errorInfo(true)); + } + + unlink($this->_tempDir.'/'.$filenameParts["basename"]); + } + + /** + * Find if given fileName exist in archive (Emulate ZipArchive locateName()) + * + * @param string $fileName Filename for the file in zip archive + * @return boolean + */ + public function locateName($fileName) + { + $list = $this->_zip->listContent(); + $listCount = count($list); + $list_index = -1; + for ($i = 0; $i < $listCount; ++$i) { + if (strtolower($list[$i]["filename"]) == strtolower($fileName) || + strtolower($list[$i]["stored_filename"]) == strtolower($fileName)) { + $list_index = $i; + break; + } + } + return ($list_index > -1); + } + + /** + * Extract file from archive by given fileName (Emulate ZipArchive getFromName()) + * + * @param string $fileName Filename for the file in zip archive + * @return string $contents File string contents + */ + public function getFromName($fileName) + { + $list = $this->_zip->listContent(); + $listCount = count($list); + $list_index = -1; + for ($i = 0; $i < $listCount; ++$i) { + if (strtolower($list[$i]["filename"]) == strtolower($fileName) || + strtolower($list[$i]["stored_filename"]) == strtolower($fileName)) { + $list_index = $i; + break; + } + } + + $extracted = ""; + if ($list_index != -1) { + $extracted = $this->_zip->extractByIndex($list_index, PCLZIP_OPT_EXTRACT_AS_STRING); + } else { + $filename = substr($fileName, 1); + $list_index = -1; + for ($i = 0; $i < $listCount; ++$i) { + if (strtolower($list[$i]["filename"]) == strtolower($fileName) || + strtolower($list[$i]["stored_filename"]) == strtolower($fileName)) { + $list_index = $i; + break; + } + } + $extracted = $this->_zip->extractByIndex($list_index, PCLZIP_OPT_EXTRACT_AS_STRING); + } + if ((is_array($extracted)) && ($extracted != 0)) { + $contents = $extracted[0]["content"]; + } + + return $contents; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php new file mode 100644 index 00000000..696072bb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php @@ -0,0 +1,201 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_ZipStreamWrapper + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_ZipStreamWrapper { + /** + * Internal ZipAcrhive + * + * @var ZipAcrhive + */ + private $_archive; + + /** + * Filename in ZipAcrhive + * + * @var string + */ + private $_fileNameInArchive = ''; + + /** + * Position in file + * + * @var int + */ + private $_position = 0; + + /** + * Data + * + * @var mixed + */ + private $_data = ''; + + /** + * Register wrapper + */ + public static function register() { + @stream_wrapper_unregister("zip"); + @stream_wrapper_register("zip", __CLASS__); + } + + /** + * Implements support for fopen(). + * + * @param string $path resource name including scheme, e.g. + * @param string $mode only "r" is supported + * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH + * @param string &$openedPath absolute path of the opened stream (out parameter) + * @return bool true on success + */ + public function stream_open($path, $mode, $options, &$opened_path) { + // Check for mode + if ($mode{0} != 'r') { + throw new PHPExcel_Reader_Exception('Mode ' . $mode . ' is not supported. Only read mode is supported.'); + } + + $pos = strrpos($path, '#'); + $url['host'] = substr($path, 6, $pos - 6); // 6: strlen('zip://') + $url['fragment'] = substr($path, $pos + 1); + + // Open archive + $this->_archive = new ZipArchive(); + $this->_archive->open($url['host']); + + $this->_fileNameInArchive = $url['fragment']; + $this->_position = 0; + $this->_data = $this->_archive->getFromName( $this->_fileNameInArchive ); + + return true; + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function statName() { + return $this->_fileNameInArchive; + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function url_stat() { + return $this->statName( $this->_fileNameInArchive ); + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function stream_stat() { + return $this->_archive->statName( $this->_fileNameInArchive ); + } + + /** + * Implements support for fread(), fgets() etc. + * + * @param int $count maximum number of bytes to read + * @return string + */ + function stream_read($count) { + $ret = substr($this->_data, $this->_position, $count); + $this->_position += strlen($ret); + return $ret; + } + + /** + * Returns the position of the file pointer, i.e. its offset into the file + * stream. Implements support for ftell(). + * + * @return int + */ + public function stream_tell() { + return $this->_position; + } + + /** + * EOF stream + * + * @return bool + */ + public function stream_eof() { + return $this->_position >= strlen($this->_data); + } + + /** + * Seek stream + * + * @param int $offset byte offset + * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END + * @return bool + */ + public function stream_seek($offset, $whence) { + switch ($whence) { + case SEEK_SET: + if ($offset < strlen($this->_data) && $offset >= 0) { + $this->_position = $offset; + return true; + } else { + return false; + } + break; + + case SEEK_CUR: + if ($offset >= 0) { + $this->_position += $offset; + return true; + } else { + return false; + } + break; + + case SEEK_END: + if (strlen($this->_data) + $offset >= 0) { + $this->_position = strlen($this->_data) + $offset; + return true; + } else { + return false; + } + break; + + default: + return false; + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php new file mode 100644 index 00000000..088ce067 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php @@ -0,0 +1,432 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Best_Fit +{ + /** + * Indicator flag for a calculation error + * + * @var boolean + **/ + protected $_error = False; + + /** + * Algorithm type to use for best-fit + * + * @var string + **/ + protected $_bestFitType = 'undetermined'; + + /** + * Number of entries in the sets of x- and y-value arrays + * + * @var int + **/ + protected $_valueCount = 0; + + /** + * X-value dataseries of values + * + * @var float[] + **/ + protected $_xValues = array(); + + /** + * Y-value dataseries of values + * + * @var float[] + **/ + protected $_yValues = array(); + + /** + * Flag indicating whether values should be adjusted to Y=0 + * + * @var boolean + **/ + protected $_adjustToZero = False; + + /** + * Y-value series of best-fit values + * + * @var float[] + **/ + protected $_yBestFitValues = array(); + + protected $_goodnessOfFit = 1; + + protected $_stdevOfResiduals = 0; + + protected $_covariance = 0; + + protected $_correlation = 0; + + protected $_SSRegression = 0; + + protected $_SSResiduals = 0; + + protected $_DFResiduals = 0; + + protected $_F = 0; + + protected $_slope = 0; + + protected $_slopeSE = 0; + + protected $_intersect = 0; + + protected $_intersectSE = 0; + + protected $_Xoffset = 0; + + protected $_Yoffset = 0; + + + public function getError() { + return $this->_error; + } // function getBestFitType() + + + public function getBestFitType() { + return $this->_bestFitType; + } // function getBestFitType() + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + */ + public function getValueOfYForX($xValue) { + return False; + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + */ + public function getValueOfXForY($yValue) { + return False; + } // function getValueOfXForY() + + + /** + * Return the original set of X-Values + * + * @return float[] X-Values + */ + public function getXValues() { + return $this->_xValues; + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getEquation($dp=0) { + return False; + } // function getEquation() + + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getSlope($dp=0) { + if ($dp != 0) { + return round($this->_slope,$dp); + } + return $this->_slope; + } // function getSlope() + + + /** + * Return the standard error of the Slope + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getSlopeSE($dp=0) { + if ($dp != 0) { + return round($this->_slopeSE,$dp); + } + return $this->_slopeSE; + } // function getSlopeSE() + + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getIntersect($dp=0) { + if ($dp != 0) { + return round($this->_intersect,$dp); + } + return $this->_intersect; + } // function getIntersect() + + + /** + * Return the standard error of the Intersect + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getIntersectSE($dp=0) { + if ($dp != 0) { + return round($this->_intersectSE,$dp); + } + return $this->_intersectSE; + } // function getIntersectSE() + + + /** + * Return the goodness of fit for this regression + * + * @param int $dp Number of places of decimal precision to return + * @return float + */ + public function getGoodnessOfFit($dp=0) { + if ($dp != 0) { + return round($this->_goodnessOfFit,$dp); + } + return $this->_goodnessOfFit; + } // function getGoodnessOfFit() + + + public function getGoodnessOfFitPercent($dp=0) { + if ($dp != 0) { + return round($this->_goodnessOfFit * 100,$dp); + } + return $this->_goodnessOfFit * 100; + } // function getGoodnessOfFitPercent() + + + /** + * Return the standard deviation of the residuals for this regression + * + * @param int $dp Number of places of decimal precision to return + * @return float + */ + public function getStdevOfResiduals($dp=0) { + if ($dp != 0) { + return round($this->_stdevOfResiduals,$dp); + } + return $this->_stdevOfResiduals; + } // function getStdevOfResiduals() + + + public function getSSRegression($dp=0) { + if ($dp != 0) { + return round($this->_SSRegression,$dp); + } + return $this->_SSRegression; + } // function getSSRegression() + + + public function getSSResiduals($dp=0) { + if ($dp != 0) { + return round($this->_SSResiduals,$dp); + } + return $this->_SSResiduals; + } // function getSSResiduals() + + + public function getDFResiduals($dp=0) { + if ($dp != 0) { + return round($this->_DFResiduals,$dp); + } + return $this->_DFResiduals; + } // function getDFResiduals() + + + public function getF($dp=0) { + if ($dp != 0) { + return round($this->_F,$dp); + } + return $this->_F; + } // function getF() + + + public function getCovariance($dp=0) { + if ($dp != 0) { + return round($this->_covariance,$dp); + } + return $this->_covariance; + } // function getCovariance() + + + public function getCorrelation($dp=0) { + if ($dp != 0) { + return round($this->_correlation,$dp); + } + return $this->_correlation; + } // function getCorrelation() + + + public function getYBestFitValues() { + return $this->_yBestFitValues; + } // function getYBestFitValues() + + + protected function _calculateGoodnessOfFit($sumX,$sumY,$sumX2,$sumY2,$sumXY,$meanX,$meanY, $const) { + $SSres = $SScov = $SScor = $SStot = $SSsex = 0.0; + foreach($this->_xValues as $xKey => $xValue) { + $bestFitY = $this->_yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); + + $SSres += ($this->_yValues[$xKey] - $bestFitY) * ($this->_yValues[$xKey] - $bestFitY); + if ($const) { + $SStot += ($this->_yValues[$xKey] - $meanY) * ($this->_yValues[$xKey] - $meanY); + } else { + $SStot += $this->_yValues[$xKey] * $this->_yValues[$xKey]; + } + $SScov += ($this->_xValues[$xKey] - $meanX) * ($this->_yValues[$xKey] - $meanY); + if ($const) { + $SSsex += ($this->_xValues[$xKey] - $meanX) * ($this->_xValues[$xKey] - $meanX); + } else { + $SSsex += $this->_xValues[$xKey] * $this->_xValues[$xKey]; + } + } + + $this->_SSResiduals = $SSres; + $this->_DFResiduals = $this->_valueCount - 1 - $const; + + if ($this->_DFResiduals == 0.0) { + $this->_stdevOfResiduals = 0.0; + } else { + $this->_stdevOfResiduals = sqrt($SSres / $this->_DFResiduals); + } + if (($SStot == 0.0) || ($SSres == $SStot)) { + $this->_goodnessOfFit = 1; + } else { + $this->_goodnessOfFit = 1 - ($SSres / $SStot); + } + + $this->_SSRegression = $this->_goodnessOfFit * $SStot; + $this->_covariance = $SScov / $this->_valueCount; + $this->_correlation = ($this->_valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->_valueCount * $sumX2 - pow($sumX,2)) * ($this->_valueCount * $sumY2 - pow($sumY,2))); + $this->_slopeSE = $this->_stdevOfResiduals / sqrt($SSsex); + $this->_intersectSE = $this->_stdevOfResiduals * sqrt(1 / ($this->_valueCount - ($sumX * $sumX) / $sumX2)); + if ($this->_SSResiduals != 0.0) { + if ($this->_DFResiduals == 0.0) { + $this->_F = 0.0; + } else { + $this->_F = $this->_SSRegression / ($this->_SSResiduals / $this->_DFResiduals); + } + } else { + if ($this->_DFResiduals == 0.0) { + $this->_F = 0.0; + } else { + $this->_F = $this->_SSRegression / $this->_DFResiduals; + } + } + } // function _calculateGoodnessOfFit() + + + protected function _leastSquareFit($yValues, $xValues, $const) { + // calculate sums + $x_sum = array_sum($xValues); + $y_sum = array_sum($yValues); + $meanX = $x_sum / $this->_valueCount; + $meanY = $y_sum / $this->_valueCount; + $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0; + for($i = 0; $i < $this->_valueCount; ++$i) { + $xy_sum += $xValues[$i] * $yValues[$i]; + $xx_sum += $xValues[$i] * $xValues[$i]; + $yy_sum += $yValues[$i] * $yValues[$i]; + + if ($const) { + $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY); + $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX); + } else { + $mBase += $xValues[$i] * $yValues[$i]; + $mDivisor += $xValues[$i] * $xValues[$i]; + } + } + + // calculate slope +// $this->_slope = (($this->_valueCount * $xy_sum) - ($x_sum * $y_sum)) / (($this->_valueCount * $xx_sum) - ($x_sum * $x_sum)); + $this->_slope = $mBase / $mDivisor; + + // calculate intersect +// $this->_intersect = ($y_sum - ($this->_slope * $x_sum)) / $this->_valueCount; + if ($const) { + $this->_intersect = $meanY - ($this->_slope * $meanX); + } else { + $this->_intersect = 0; + } + + $this->_calculateGoodnessOfFit($x_sum,$y_sum,$xx_sum,$yy_sum,$xy_sum,$meanX,$meanY,$const); + } // function _leastSquareFit() + + + /** + * Define the regression + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($yValues, $xValues=array(), $const=True) { + // Calculate number of points + $nY = count($yValues); + $nX = count($xValues); + + // Define X Values if necessary + if ($nX == 0) { + $xValues = range(1,$nY); + $nX = $nY; + } elseif ($nY != $nX) { + // Ensure both arrays of points are the same size + $this->_error = True; + return False; + } + + $this->_valueCount = $nY; + $this->_xValues = $xValues; + $this->_yValues = $yValues; + } // function __construct() + +} // class bestFit diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php new file mode 100644 index 00000000..44c7aee8 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php @@ -0,0 +1,148 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + + +/** + * PHPExcel_Exponential_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Exponential_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $_bestFitType = 'exponential'; + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) { + return $this->getIntersect() * pow($this->getSlope(),($xValue - $this->_Xoffset)); + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) { + return log(($yValue + $this->_Yoffset) / $this->getIntersect()) / log($this->getSlope()); + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp=0) { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = '.$intersect.' * '.$slope.'^X'; + } // function getEquation() + + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getSlope($dp=0) { + if ($dp != 0) { + return round(exp($this->_slope),$dp); + } + return exp($this->_slope); + } // function getSlope() + + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getIntersect($dp=0) { + if ($dp != 0) { + return round(exp($this->_intersect),$dp); + } + return exp($this->_intersect); + } // function getIntersect() + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function _exponential_regression($yValues, $xValues, $const) { + foreach($yValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->_leastSquareFit($yValues, $xValues, $const); + } // function _exponential_regression() + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($yValues, $xValues=array(), $const=True) { + if (parent::__construct($yValues, $xValues) !== False) { + $this->_exponential_regression($yValues, $xValues, $const); + } + } // function __construct() + +} // class exponentialBestFit \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php new file mode 100644 index 00000000..00da8411 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php @@ -0,0 +1,111 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + + +/** + * PHPExcel_Linear_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Linear_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $_bestFitType = 'linear'; + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) { + return $this->getIntersect() + $this->getSlope() * $xValue; + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) { + return ($yValue - $this->getIntersect()) / $this->getSlope(); + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp=0) { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = '.$intersect.' + '.$slope.' * X'; + } // function getEquation() + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function _linear_regression($yValues, $xValues, $const) { + $this->_leastSquareFit($yValues, $xValues,$const); + } // function _linear_regression() + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($yValues, $xValues=array(), $const=True) { + if (parent::__construct($yValues, $xValues) !== False) { + $this->_linear_regression($yValues, $xValues, $const); + } + } // function __construct() + +} // class linearBestFit \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php new file mode 100644 index 00000000..ac9c1e20 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php @@ -0,0 +1,120 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + + +/** + * PHPExcel_Logarithmic_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Logarithmic_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $_bestFitType = 'logarithmic'; + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) { + return $this->getIntersect() + $this->getSlope() * log($xValue - $this->_Xoffset); + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) { + return exp(($yValue - $this->getIntersect()) / $this->getSlope()); + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp=0) { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = '.$intersect.' + '.$slope.' * log(X)'; + } // function getEquation() + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function _logarithmic_regression($yValues, $xValues, $const) { + foreach($xValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->_leastSquareFit($yValues, $xValues, $const); + } // function _logarithmic_regression() + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($yValues, $xValues=array(), $const=True) { + if (parent::__construct($yValues, $xValues) !== False) { + $this->_logarithmic_regression($yValues, $xValues, $const); + } + } // function __construct() + +} // class logarithmicBestFit \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php new file mode 100644 index 00000000..a5079752 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php @@ -0,0 +1,224 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/JAMA/Matrix.php'; + + +/** + * PHPExcel_Polynomial_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Polynomial_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $_bestFitType = 'polynomial'; + + /** + * Polynomial order + * + * @protected + * @var int + **/ + protected $_order = 0; + + + /** + * Return the order of this polynomial + * + * @return int + **/ + public function getOrder() { + return $this->_order; + } // function getOrder() + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) { + $retVal = $this->getIntersect(); + $slope = $this->getSlope(); + foreach($slope as $key => $value) { + if ($value != 0.0) { + $retVal += $value * pow($xValue, $key + 1); + } + } + return $retVal; + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) { + return ($yValue - $this->getIntersect()) / $this->getSlope(); + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp=0) { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + $equation = 'Y = '.$intersect; + foreach($slope as $key => $value) { + if ($value != 0.0) { + $equation .= ' + '.$value.' * X'; + if ($key > 0) { + $equation .= '^'.($key + 1); + } + } + } + return $equation; + } // function getEquation() + + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getSlope($dp=0) { + if ($dp != 0) { + $coefficients = array(); + foreach($this->_slope as $coefficient) { + $coefficients[] = round($coefficient,$dp); + } + return $coefficients; + } + return $this->_slope; + } // function getSlope() + + + public function getCoefficients($dp=0) { + return array_merge(array($this->getIntersect($dp)),$this->getSlope($dp)); + } // function getCoefficients() + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param int $order Order of Polynomial for this regression + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function _polynomial_regression($order, $yValues, $xValues, $const) { + // calculate sums + $x_sum = array_sum($xValues); + $y_sum = array_sum($yValues); + $xx_sum = $xy_sum = 0; + for($i = 0; $i < $this->_valueCount; ++$i) { + $xy_sum += $xValues[$i] * $yValues[$i]; + $xx_sum += $xValues[$i] * $xValues[$i]; + $yy_sum += $yValues[$i] * $yValues[$i]; + } + /* + * This routine uses logic from the PHP port of polyfit version 0.1 + * written by Michael Bommarito and Paul Meagher + * + * The function fits a polynomial function of order $order through + * a series of x-y data points using least squares. + * + */ + for ($i = 0; $i < $this->_valueCount; ++$i) { + for ($j = 0; $j <= $order; ++$j) { + $A[$i][$j] = pow($xValues[$i], $j); + } + } + for ($i=0; $i < $this->_valueCount; ++$i) { + $B[$i] = array($yValues[$i]); + } + $matrixA = new Matrix($A); + $matrixB = new Matrix($B); + $C = $matrixA->solve($matrixB); + + $coefficients = array(); + for($i = 0; $i < $C->m; ++$i) { + $r = $C->get($i, 0); + if (abs($r) <= pow(10, -9)) { + $r = 0; + } + $coefficients[] = $r; + } + + $this->_intersect = array_shift($coefficients); + $this->_slope = $coefficients; + + $this->_calculateGoodnessOfFit($x_sum,$y_sum,$xx_sum,$yy_sum,$xy_sum); + foreach($this->_xValues as $xKey => $xValue) { + $this->_yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); + } + } // function _polynomial_regression() + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param int $order Order of Polynomial for this regression + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($order, $yValues, $xValues=array(), $const=True) { + if (parent::__construct($yValues, $xValues) !== False) { + if ($order < $this->_valueCount) { + $this->_bestFitType .= '_'.$order; + $this->_order = $order; + $this->_polynomial_regression($order, $yValues, $xValues, $const); + if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) { + $this->_error = True; + } + } else { + $this->_error = True; + } + } + } // function __construct() + +} // class polynomialBestFit \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php new file mode 100644 index 00000000..158e0c45 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php @@ -0,0 +1,142 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'; + + +/** + * PHPExcel_Power_Best_Fit + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Power_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $_bestFitType = 'power'; + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) { + return $this->getIntersect() * pow(($xValue - $this->_Xoffset),$this->getSlope()); + } // function getValueOfYForX() + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) { + return pow((($yValue + $this->_Yoffset) / $this->getIntersect()),(1 / $this->getSlope())); + } // function getValueOfXForY() + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp=0) { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = '.$intersect.' * X^'.$slope; + } // function getEquation() + + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getIntersect($dp=0) { + if ($dp != 0) { + return round(exp($this->_intersect),$dp); + } + return exp($this->_intersect); + } // function getIntersect() + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function _power_regression($yValues, $xValues, $const) { + foreach($xValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + foreach($yValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->_leastSquareFit($yValues, $xValues, $const); + } // function _power_regression() + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + function __construct($yValues, $xValues=array(), $const=True) { + if (parent::__construct($yValues, $xValues) !== False) { + $this->_power_regression($yValues, $xValues, $const); + } + } // function __construct() + +} // class powerBestFit \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php new file mode 100644 index 00000000..d891a7dc --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php @@ -0,0 +1,156 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/linearBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/logarithmicBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/exponentialBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/powerBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/polynomialBestFitClass.php'; + + +/** + * PHPExcel_trendClass + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class trendClass +{ + const TREND_LINEAR = 'Linear'; + const TREND_LOGARITHMIC = 'Logarithmic'; + const TREND_EXPONENTIAL = 'Exponential'; + const TREND_POWER = 'Power'; + const TREND_POLYNOMIAL_2 = 'Polynomial_2'; + const TREND_POLYNOMIAL_3 = 'Polynomial_3'; + const TREND_POLYNOMIAL_4 = 'Polynomial_4'; + const TREND_POLYNOMIAL_5 = 'Polynomial_5'; + const TREND_POLYNOMIAL_6 = 'Polynomial_6'; + const TREND_BEST_FIT = 'Bestfit'; + const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials'; + + /** + * Names of the best-fit trend analysis methods + * + * @var string[] + **/ + private static $_trendTypes = array( self::TREND_LINEAR, + self::TREND_LOGARITHMIC, + self::TREND_EXPONENTIAL, + self::TREND_POWER + ); + /** + * Names of the best-fit trend polynomial orders + * + * @var string[] + **/ + private static $_trendTypePolyOrders = array( self::TREND_POLYNOMIAL_2, + self::TREND_POLYNOMIAL_3, + self::TREND_POLYNOMIAL_4, + self::TREND_POLYNOMIAL_5, + self::TREND_POLYNOMIAL_6 + ); + + /** + * Cached results for each method when trying to identify which provides the best fit + * + * @var PHPExcel_Best_Fit[] + **/ + private static $_trendCache = array(); + + + public static function calculate($trendType=self::TREND_BEST_FIT, $yValues, $xValues=array(), $const=True) { + // Calculate number of points in each dataset + $nY = count($yValues); + $nX = count($xValues); + + // Define X Values if necessary + if ($nX == 0) { + $xValues = range(1,$nY); + $nX = $nY; + } elseif ($nY != $nX) { + // Ensure both arrays of points are the same size + trigger_error("trend(): Number of elements in coordinate arrays do not match.", E_USER_ERROR); + } + + $key = md5($trendType.$const.serialize($yValues).serialize($xValues)); + // Determine which trend method has been requested + switch ($trendType) { + // Instantiate and return the class for the requested trend method + case self::TREND_LINEAR : + case self::TREND_LOGARITHMIC : + case self::TREND_EXPONENTIAL : + case self::TREND_POWER : + if (!isset(self::$_trendCache[$key])) { + $className = 'PHPExcel_'.$trendType.'_Best_Fit'; + self::$_trendCache[$key] = new $className($yValues,$xValues,$const); + } + return self::$_trendCache[$key]; + break; + case self::TREND_POLYNOMIAL_2 : + case self::TREND_POLYNOMIAL_3 : + case self::TREND_POLYNOMIAL_4 : + case self::TREND_POLYNOMIAL_5 : + case self::TREND_POLYNOMIAL_6 : + if (!isset(self::$_trendCache[$key])) { + $order = substr($trendType,-1); + self::$_trendCache[$key] = new PHPExcel_Polynomial_Best_Fit($order,$yValues,$xValues,$const); + } + return self::$_trendCache[$key]; + break; + case self::TREND_BEST_FIT : + case self::TREND_BEST_FIT_NO_POLY : + // If the request is to determine the best fit regression, then we test each trend line in turn + // Start by generating an instance of each available trend method + foreach(self::$_trendTypes as $trendMethod) { + $className = 'PHPExcel_'.$trendMethod.'BestFit'; + $bestFit[$trendMethod] = new $className($yValues,$xValues,$const); + $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); + } + if ($trendType != self::TREND_BEST_FIT_NO_POLY) { + foreach(self::$_trendTypePolyOrders as $trendMethod) { + $order = substr($trendMethod,-1); + $bestFit[$trendMethod] = new PHPExcel_Polynomial_Best_Fit($order,$yValues,$xValues,$const); + if ($bestFit[$trendMethod]->getError()) { + unset($bestFit[$trendMethod]); + } else { + $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); + } + } + } + // Determine which of our trend lines is the best fit, and then we return the instance of that trend class + arsort($bestFitValue); + $bestFitType = key($bestFitValue); + return $bestFit[$bestFitType]; + break; + default : + return false; + } + } // function calculate() + +} // class trendClass \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php new file mode 100644 index 00000000..715ae113 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php @@ -0,0 +1,668 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /** + * Font + * + * @var PHPExcel_Style_Font + */ + protected $_font; + + /** + * Fill + * + * @var PHPExcel_Style_Fill + */ + protected $_fill; + + /** + * Borders + * + * @var PHPExcel_Style_Borders + */ + protected $_borders; + + /** + * Alignment + * + * @var PHPExcel_Style_Alignment + */ + protected $_alignment; + + /** + * Number Format + * + * @var PHPExcel_Style_NumberFormat + */ + protected $_numberFormat; + + /** + * Conditional styles + * + * @var PHPExcel_Style_Conditional[] + */ + protected $_conditionalStyles; + + /** + * Protection + * + * @var PHPExcel_Style_Protection + */ + protected $_protection; + + /** + * Index of style in collection. Only used for real style. + * + * @var int + */ + protected $_index; + + /** + * Use Quote Prefix when displaying in cell editor. Only used for real style. + * + * @var boolean + */ + protected $_quotePrefix = false; + + /** + * Create a new PHPExcel_Style + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + $this->_isSupervisor = $isSupervisor; + + // Initialise values + $this->_conditionalStyles = array(); + $this->_font = new PHPExcel_Style_Font($isSupervisor, $isConditional); + $this->_fill = new PHPExcel_Style_Fill($isSupervisor, $isConditional); + $this->_borders = new PHPExcel_Style_Borders($isSupervisor, $isConditional); + $this->_alignment = new PHPExcel_Style_Alignment($isSupervisor, $isConditional); + $this->_numberFormat = new PHPExcel_Style_NumberFormat($isSupervisor, $isConditional); + $this->_protection = new PHPExcel_Style_Protection($isSupervisor, $isConditional); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->_font->bindParent($this); + $this->_fill->bindParent($this); + $this->_borders->bindParent($this); + $this->_alignment->bindParent($this); + $this->_numberFormat->bindParent($this); + $this->_protection->bindParent($this); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style + */ + public function getSharedComponent() + { + $activeSheet = $this->getActiveSheet(); + $selectedCell = $this->getActiveCell(); // e.g. 'A1' + + if ($activeSheet->cellExists($selectedCell)) { + $xfIndex = $activeSheet->getCell($selectedCell)->getXfIndex(); + } else { + $xfIndex = 0; + } + + return $this->_parent->getCellXfByIndex($xfIndex); + } + + /** + * Get parent. Only used for style supervisor + * + * @return PHPExcel + */ + public function getParent() + { + return $this->_parent; + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('quotePrefix' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray( + * array( + * 'font' => array( + * 'name' => 'Arial', + * 'bold' => true, + * 'italic' => false, + * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE, + * 'strike' => false, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'borders' => array( + * 'bottom' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'top' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ), + * 'quotePrefix' => true + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @param boolean $pAdvanced Advanced mode for setting borders. + * @throws PHPExcel_Exception + * @return PHPExcel_Style + */ + public function applyFromArray($pStyles = null, $pAdvanced = true) + { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + + $pRange = $this->getSelectedCells(); + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Is it a cell range or a single cell? + if (strpos($pRange, ':') === false) { + $rangeA = $pRange; + $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + // Calculate range outer borders + $rangeStart = PHPExcel_Cell::coordinateFromString($rangeA); + $rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB); + + // Translate column into index + $rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]) - 1; + $rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]) - 1; + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // ADVANCED MODE: + + if ($pAdvanced && isset($pStyles['borders'])) { + + // 'allborders' is a shorthand property for 'outline' and 'inside' and + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['allborders'])) { + foreach (array('outline', 'inside') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['allborders']; + } + } + unset($pStyles['borders']['allborders']); // not needed any more + } + + // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left' + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['outline'])) { + foreach (array('top', 'right', 'bottom', 'left') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['outline']; + } + } + unset($pStyles['borders']['outline']); // not needed any more + } + + // 'inside' is a shorthand property for 'vertical' and 'horizontal' + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['inside'])) { + foreach (array('vertical', 'horizontal') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['inside']; + } + } + unset($pStyles['borders']['inside']); // not needed any more + } + + // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) + $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3); + $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3); + + // loop through up to 3 x 3 = 9 regions + for ($x = 1; $x <= $xMax; ++$x) { + // start column index for region + $colStart = ($x == 3) ? + PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]) + : PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $x - 1); + + // end column index for region + $colEnd = ($x == 1) ? + PHPExcel_Cell::stringFromColumnIndex($rangeStart[0]) + : PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] - $xMax + $x); + + for ($y = 1; $y <= $yMax; ++$y) { + + // which edges are touching the region + $edges = array(); + + // are we at left edge + if ($x == 1) { + $edges[] = 'left'; + } + + // are we at right edge + if ($x == $xMax) { + $edges[] = 'right'; + } + + // are we at top edge? + if ($y == 1) { + $edges[] = 'top'; + } + + // are we at bottom edge? + if ($y == $yMax) { + $edges[] = 'bottom'; + } + + // start row index for region + $rowStart = ($y == 3) ? + $rangeEnd[1] : $rangeStart[1] + $y - 1; + + // end row index for region + $rowEnd = ($y == 1) ? + $rangeStart[1] : $rangeEnd[1] - $yMax + $y; + + // build range for region + $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; + + // retrieve relevant style array for region + $regionStyles = $pStyles; + unset($regionStyles['borders']['inside']); + + // what are the inner edges of the region when looking at the selection + $innerEdges = array_diff( array('top', 'right', 'bottom', 'left'), $edges ); + + // inner edges that are not touching the region should take the 'inside' border properties if they have been set + foreach ($innerEdges as $innerEdge) { + switch ($innerEdge) { + case 'top': + case 'bottom': + // should pick up 'horizontal' border property if set + if (isset($pStyles['borders']['horizontal'])) { + $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal']; + } else { + unset($regionStyles['borders'][$innerEdge]); + } + break; + case 'left': + case 'right': + // should pick up 'vertical' border property if set + if (isset($pStyles['borders']['vertical'])) { + $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical']; + } else { + unset($regionStyles['borders'][$innerEdge]); + } + break; + } + } + + // apply region style to region by calling applyFromArray() in simple mode + $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false); + } + } + return $this; + } + + // SIMPLE MODE: + + // Selection type, inspect + if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) { + $selectionType = 'COLUMN'; + } else if (preg_match('/^A[0-9]+:XFD[0-9]+$/', $pRange)) { + $selectionType = 'ROW'; + } else { + $selectionType = 'CELL'; + } + + // First loop through columns, rows, or cells to find out which styles are affected by this operation + switch ($selectionType) { + case 'COLUMN': + $oldXfIndexes = array(); + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; + } + break; + + case 'ROW': + $oldXfIndexes = array(); + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) { + $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style + } else { + $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; + } + } + break; + + case 'CELL': + $oldXfIndexes = array(); + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; + } + } + break; + } + + // clone each of the affected styles, apply the style array, and add the new styles to the workbook + $workbook = $this->getActiveSheet()->getParent(); + foreach ($oldXfIndexes as $oldXfIndex => $dummy) { + $style = $workbook->getCellXfByIndex($oldXfIndex); + $newStyle = clone $style; + $newStyle->applyFromArray($pStyles); + + if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) { + // there is already such cell Xf in our collection + $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex(); + } else { + // we don't have such a cell Xf, need to add + $workbook->addCellXf($newStyle); + $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); + } + } + + // Loop through columns, rows, or cells again and update the XF index + switch ($selectionType) { + case 'COLUMN': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col); + $oldXfIndex = $columnDimension->getXfIndex(); + $columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]); + } + break; + + case 'ROW': + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $rowDimension = $this->getActiveSheet()->getRowDimension($row); + $oldXfIndex = $rowDimension->getXfIndex() === null ? + 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style + $rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]); + } + break; + + case 'CELL': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row); + $oldXfIndex = $cell->getXfIndex(); + $cell->setXfIndex($newXfIndexes[$oldXfIndex]); + } + } + break; + } + + } else { + // not a supervisor, just apply the style array directly on style object + if (array_key_exists('fill', $pStyles)) { + $this->getFill()->applyFromArray($pStyles['fill']); + } + if (array_key_exists('font', $pStyles)) { + $this->getFont()->applyFromArray($pStyles['font']); + } + if (array_key_exists('borders', $pStyles)) { + $this->getBorders()->applyFromArray($pStyles['borders']); + } + if (array_key_exists('alignment', $pStyles)) { + $this->getAlignment()->applyFromArray($pStyles['alignment']); + } + if (array_key_exists('numberformat', $pStyles)) { + $this->getNumberFormat()->applyFromArray($pStyles['numberformat']); + } + if (array_key_exists('protection', $pStyles)) { + $this->getProtection()->applyFromArray($pStyles['protection']); + } + if (array_key_exists('quotePrefix', $pStyles)) { + $this->_quotePrefix = $pStyles['quotePrefix']; + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Fill + * + * @return PHPExcel_Style_Fill + */ + public function getFill() + { + return $this->_fill; + } + + /** + * Get Font + * + * @return PHPExcel_Style_Font + */ + public function getFont() + { + return $this->_font; + } + + /** + * Set font + * + * @param PHPExcel_Style_Font $font + * @return PHPExcel_Style + */ + public function setFont(PHPExcel_Style_Font $font) + { + $this->_font = $font; + return $this; + } + + /** + * Get Borders + * + * @return PHPExcel_Style_Borders + */ + public function getBorders() + { + return $this->_borders; + } + + /** + * Get Alignment + * + * @return PHPExcel_Style_Alignment + */ + public function getAlignment() + { + return $this->_alignment; + } + + /** + * Get Number Format + * + * @return PHPExcel_Style_NumberFormat + */ + public function getNumberFormat() + { + return $this->_numberFormat; + } + + /** + * Get Conditional Styles. Only used on supervisor. + * + * @return PHPExcel_Style_Conditional[] + */ + public function getConditionalStyles() + { + return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell()); + } + + /** + * Set Conditional Styles. Only used on supervisor. + * + * @param PHPExcel_Style_Conditional[] $pValue Array of condtional styles + * @return PHPExcel_Style + */ + public function setConditionalStyles($pValue = null) + { + if (is_array($pValue)) { + $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue); + } + return $this; + } + + /** + * Get Protection + * + * @return PHPExcel_Style_Protection + */ + public function getProtection() + { + return $this->_protection; + } + + /** + * Get quote prefix + * + * @return boolean + */ + public function getQuotePrefix() + { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getQuotePrefix(); + } + return $this->_quotePrefix; + } + + /** + * Set quote prefix + * + * @param boolean $pValue + */ + public function setQuotePrefix($pValue) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = array('quotePrefix' => $pValue); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_quotePrefix = (boolean) $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + $hashConditionals = ''; + foreach ($this->_conditionalStyles as $conditional) { + $hashConditionals .= $conditional->getHashCode(); + } + + return md5( + $this->_fill->getHashCode() + . $this->_font->getHashCode() + . $this->_borders->getHashCode() + . $this->_alignment->getHashCode() + . $this->_numberFormat->getHashCode() + . $hashConditionals + . $this->_protection->getHashCode() + . ($this->_quotePrefix ? 't' : 'f') + . __CLASS__ + ); + } + + /** + * Get own index in style collection + * + * @return int + */ + public function getIndex() + { + return $this->_index; + } + + /** + * Set own index in style collection + * + * @param int $pValue + */ + public function setIndex($pValue) + { + $this->_index = $pValue; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php new file mode 100644 index 00000000..0d9e0767 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php @@ -0,0 +1,412 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Alignment + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Alignment extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Horizontal alignment styles */ + const HORIZONTAL_GENERAL = 'general'; + const HORIZONTAL_LEFT = 'left'; + const HORIZONTAL_RIGHT = 'right'; + const HORIZONTAL_CENTER = 'center'; + const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'; + const HORIZONTAL_JUSTIFY = 'justify'; + const HORIZONTAL_FILL = 'fill'; + const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only + + /* Vertical alignment styles */ + const VERTICAL_BOTTOM = 'bottom'; + const VERTICAL_TOP = 'top'; + const VERTICAL_CENTER = 'center'; + const VERTICAL_JUSTIFY = 'justify'; + const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only + + /** + * Horizontal + * + * @var string + */ + protected $_horizontal = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + + /** + * Vertical + * + * @var string + */ + protected $_vertical = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + + /** + * Text rotation + * + * @var int + */ + protected $_textRotation = 0; + + /** + * Wrap text + * + * @var boolean + */ + protected $_wrapText = FALSE; + + /** + * Shrink to fit + * + * @var boolean + */ + protected $_shrinkToFit = FALSE; + + /** + * Indent - only possible with horizontal alignment left and right + * + * @var int + */ + protected $_indent = 0; + + /** + * Create a new PHPExcel_Style_Alignment + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + if ($isConditional) { + $this->_horizontal = NULL; + $this->_vertical = NULL; + $this->_textRotation = NULL; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Alignment + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getAlignment(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('alignment' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray( + * array( + * 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, + * 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, + * 'rotation' => 0, + * 'wrap' => TRUE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Alignment + */ + public function applyFromArray($pStyles = NULL) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells()) + ->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['horizontal'])) { + $this->setHorizontal($pStyles['horizontal']); + } + if (isset($pStyles['vertical'])) { + $this->setVertical($pStyles['vertical']); + } + if (isset($pStyles['rotation'])) { + $this->setTextRotation($pStyles['rotation']); + } + if (isset($pStyles['wrap'])) { + $this->setWrapText($pStyles['wrap']); + } + if (isset($pStyles['shrinkToFit'])) { + $this->setShrinkToFit($pStyles['shrinkToFit']); + } + if (isset($pStyles['indent'])) { + $this->setIndent($pStyles['indent']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Horizontal + * + * @return string + */ + public function getHorizontal() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHorizontal(); + } + return $this->_horizontal; + } + + /** + * Set Horizontal + * + * @param string $pValue + * @return PHPExcel_Style_Alignment + */ + public function setHorizontal($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) { + if ($pValue == '') { + $pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + } + + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('horizontal' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } + else { + $this->_horizontal = $pValue; + } + return $this; + } + + /** + * Get Vertical + * + * @return string + */ + public function getVertical() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getVertical(); + } + return $this->_vertical; + } + + /** + * Set Vertical + * + * @param string $pValue + * @return PHPExcel_Style_Alignment + */ + public function setVertical($pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM) { + if ($pValue == '') { + $pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + } + + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('vertical' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_vertical = $pValue; + } + return $this; + } + + /** + * Get TextRotation + * + * @return int + */ + public function getTextRotation() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getTextRotation(); + } + return $this->_textRotation; + } + + /** + * Set TextRotation + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Alignment + */ + public function setTextRotation($pValue = 0) { + // Excel2007 value 255 => PHPExcel value -165 + if ($pValue == 255) { + $pValue = -165; + } + + // Set rotation + if ( ($pValue >= -90 && $pValue <= 90) || $pValue == -165 ) { + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_textRotation = $pValue; + } + } else { + throw new PHPExcel_Exception("Text rotation should be a value between -90 and 90."); + } + + return $this; + } + + /** + * Get Wrap Text + * + * @return boolean + */ + public function getWrapText() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getWrapText(); + } + return $this->_wrapText; + } + + /** + * Set Wrap Text + * + * @param boolean $pValue + * @return PHPExcel_Style_Alignment + */ + public function setWrapText($pValue = FALSE) { + if ($pValue == '') { + $pValue = FALSE; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('wrap' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_wrapText = $pValue; + } + return $this; + } + + /** + * Get Shrink to fit + * + * @return boolean + */ + public function getShrinkToFit() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getShrinkToFit(); + } + return $this->_shrinkToFit; + } + + /** + * Set Shrink to fit + * + * @param boolean $pValue + * @return PHPExcel_Style_Alignment + */ + public function setShrinkToFit($pValue = FALSE) { + if ($pValue == '') { + $pValue = FALSE; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_shrinkToFit = $pValue; + } + return $this; + } + + /** + * Get indent + * + * @return int + */ + public function getIndent() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getIndent(); + } + return $this->_indent; + } + + /** + * Set indent + * + * @param int $pValue + * @return PHPExcel_Style_Alignment + */ + public function setIndent($pValue = 0) { + if ($pValue > 0) { + if ($this->getHorizontal() != self::HORIZONTAL_GENERAL && + $this->getHorizontal() != self::HORIZONTAL_LEFT && + $this->getHorizontal() != self::HORIZONTAL_RIGHT) { + $pValue = 0; // indent not supported + } + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('indent' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_indent = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_horizontal + . $this->_vertical + . $this->_textRotation + . ($this->_wrapText ? 't' : 'f') + . ($this->_shrinkToFit ? 't' : 'f') + . $this->_indent + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php new file mode 100644 index 00000000..3b7eba9a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php @@ -0,0 +1,294 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Border + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Border extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Border style */ + const BORDER_NONE = 'none'; + const BORDER_DASHDOT = 'dashDot'; + const BORDER_DASHDOTDOT = 'dashDotDot'; + const BORDER_DASHED = 'dashed'; + const BORDER_DOTTED = 'dotted'; + const BORDER_DOUBLE = 'double'; + const BORDER_HAIR = 'hair'; + const BORDER_MEDIUM = 'medium'; + const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; + const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; + const BORDER_MEDIUMDASHED = 'mediumDashed'; + const BORDER_SLANTDASHDOT = 'slantDashDot'; + const BORDER_THICK = 'thick'; + const BORDER_THIN = 'thin'; + + /** + * Border style + * + * @var string + */ + protected $_borderStyle = PHPExcel_Style_Border::BORDER_NONE; + + /** + * Border color + * + * @var PHPExcel_Style_Color + */ + protected $_color; + + /** + * Parent property name + * + * @var string + */ + protected $_parentPropertyName; + + /** + * Create a new PHPExcel_Style_Border + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->_color->bindParent($this, '_color'); + } + } + + /** + * Bind parent. Only used for supervisor + * + * @param PHPExcel_Style_Borders $parent + * @param string $parentPropertyName + * @return PHPExcel_Style_Border + */ + public function bindParent($parent, $parentPropertyName=NULL) + { + $this->_parent = $parent; + $this->_parentPropertyName = $parentPropertyName; + return $this; + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getSharedComponent() + { + switch ($this->_parentPropertyName) { + case '_allBorders': + case '_horizontal': + case '_inside': + case '_outline': + case '_vertical': + throw new PHPExcel_Exception('Cannot get shared component for a pseudo-border.'); + break; + case '_bottom': + return $this->_parent->getSharedComponent()->getBottom(); break; + case '_diagonal': + return $this->_parent->getSharedComponent()->getDiagonal(); break; + case '_left': + return $this->_parent->getSharedComponent()->getLeft(); break; + case '_right': + return $this->_parent->getSharedComponent()->getRight(); break; + case '_top': + return $this->_parent->getSharedComponent()->getTop(); break; + + } + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + switch ($this->_parentPropertyName) { + case '_allBorders': + $key = 'allborders'; break; + case '_bottom': + $key = 'bottom'; break; + case '_diagonal': + $key = 'diagonal'; break; + case '_horizontal': + $key = 'horizontal'; break; + case '_inside': + $key = 'inside'; break; + case '_left': + $key = 'left'; break; + case '_outline': + $key = 'outline'; break; + case '_right': + $key = 'right'; break; + case '_top': + $key = 'top'; break; + case '_vertical': + $key = 'vertical'; break; + } + return $this->_parent->getStyleArray(array($key => $array)); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray( + * array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Border + */ + public function applyFromArray($pStyles = null) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['style'])) { + $this->setBorderStyle($pStyles['style']); + } + if (isset($pStyles['color'])) { + $this->getColor()->applyFromArray($pStyles['color']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Border style + * + * @return string + */ + public function getBorderStyle() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getBorderStyle(); + } + return $this->_borderStyle; + } + + /** + * Set Border style + * + * @param string|boolean $pValue + * When passing a boolean, FALSE equates PHPExcel_Style_Border::BORDER_NONE + * and TRUE to PHPExcel_Style_Border::BORDER_MEDIUM + * @return PHPExcel_Style_Border + */ + public function setBorderStyle($pValue = PHPExcel_Style_Border::BORDER_NONE) { + + if (empty($pValue)) { + $pValue = PHPExcel_Style_Border::BORDER_NONE; + } elseif(is_bool($pValue) && $pValue) { + $pValue = PHPExcel_Style_Border::BORDER_MEDIUM; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('style' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_borderStyle = $pValue; + } + return $this; + } + + /** + * Get Border Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() { + return $this->_color; + } + + /** + * Set Border Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Border + */ + public function setColor(PHPExcel_Style_Color $pValue = null) { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->_isSupervisor) { + $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_color = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_borderStyle + . $this->_color->getHashCode() + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php new file mode 100644 index 00000000..b90838a6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php @@ -0,0 +1,424 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Borders + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Borders extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Diagonal directions */ + const DIAGONAL_NONE = 0; + const DIAGONAL_UP = 1; + const DIAGONAL_DOWN = 2; + const DIAGONAL_BOTH = 3; + + /** + * Left + * + * @var PHPExcel_Style_Border + */ + protected $_left; + + /** + * Right + * + * @var PHPExcel_Style_Border + */ + protected $_right; + + /** + * Top + * + * @var PHPExcel_Style_Border + */ + protected $_top; + + /** + * Bottom + * + * @var PHPExcel_Style_Border + */ + protected $_bottom; + + /** + * Diagonal + * + * @var PHPExcel_Style_Border + */ + protected $_diagonal; + + /** + * DiagonalDirection + * + * @var int + */ + protected $_diagonalDirection; + + /** + * All borders psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $_allBorders; + + /** + * Outline psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $_outline; + + /** + * Inside psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $_inside; + + /** + * Vertical pseudo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $_vertical; + + /** + * Horizontal pseudo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $_horizontal; + + /** + * Create a new PHPExcel_Style_Borders + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + $this->_left = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->_right = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->_top = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->_bottom = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->_diagonal = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->_diagonalDirection = PHPExcel_Style_Borders::DIAGONAL_NONE; + + // Specially for supervisor + if ($isSupervisor) { + // Initialize pseudo-borders + $this->_allBorders = new PHPExcel_Style_Border(TRUE); + $this->_outline = new PHPExcel_Style_Border(TRUE); + $this->_inside = new PHPExcel_Style_Border(TRUE); + $this->_vertical = new PHPExcel_Style_Border(TRUE); + $this->_horizontal = new PHPExcel_Style_Border(TRUE); + + // bind parent if we are a supervisor + $this->_left->bindParent($this, '_left'); + $this->_right->bindParent($this, '_right'); + $this->_top->bindParent($this, '_top'); + $this->_bottom->bindParent($this, '_bottom'); + $this->_diagonal->bindParent($this, '_diagonal'); + $this->_allBorders->bindParent($this, '_allBorders'); + $this->_outline->bindParent($this, '_outline'); + $this->_inside->bindParent($this, '_inside'); + $this->_vertical->bindParent($this, '_vertical'); + $this->_horizontal->bindParent($this, '_horizontal'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Borders + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getBorders(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('borders' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( + * array( + * 'bottom' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'top' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ) + * ); + * </code> + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( + * array( + * 'allborders' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Borders + */ + public function applyFromArray($pStyles = null) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('left', $pStyles)) { + $this->getLeft()->applyFromArray($pStyles['left']); + } + if (array_key_exists('right', $pStyles)) { + $this->getRight()->applyFromArray($pStyles['right']); + } + if (array_key_exists('top', $pStyles)) { + $this->getTop()->applyFromArray($pStyles['top']); + } + if (array_key_exists('bottom', $pStyles)) { + $this->getBottom()->applyFromArray($pStyles['bottom']); + } + if (array_key_exists('diagonal', $pStyles)) { + $this->getDiagonal()->applyFromArray($pStyles['diagonal']); + } + if (array_key_exists('diagonaldirection', $pStyles)) { + $this->setDiagonalDirection($pStyles['diagonaldirection']); + } + if (array_key_exists('allborders', $pStyles)) { + $this->getLeft()->applyFromArray($pStyles['allborders']); + $this->getRight()->applyFromArray($pStyles['allborders']); + $this->getTop()->applyFromArray($pStyles['allborders']); + $this->getBottom()->applyFromArray($pStyles['allborders']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Left + * + * @return PHPExcel_Style_Border + */ + public function getLeft() { + return $this->_left; + } + + /** + * Get Right + * + * @return PHPExcel_Style_Border + */ + public function getRight() { + return $this->_right; + } + + /** + * Get Top + * + * @return PHPExcel_Style_Border + */ + public function getTop() { + return $this->_top; + } + + /** + * Get Bottom + * + * @return PHPExcel_Style_Border + */ + public function getBottom() { + return $this->_bottom; + } + + /** + * Get Diagonal + * + * @return PHPExcel_Style_Border + */ + public function getDiagonal() { + return $this->_diagonal; + } + + /** + * Get AllBorders (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getAllBorders() { + if (!$this->_isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->_allBorders; + } + + /** + * Get Outline (pseudo-border). Only applies to supervisor. + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function getOutline() { + if (!$this->_isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->_outline; + } + + /** + * Get Inside (pseudo-border). Only applies to supervisor. + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function getInside() { + if (!$this->_isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->_inside; + } + + /** + * Get Vertical (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getVertical() { + if (!$this->_isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->_vertical; + } + + /** + * Get Horizontal (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getHorizontal() { + if (!$this->_isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->_horizontal; + } + + /** + * Get DiagonalDirection + * + * @return int + */ + public function getDiagonalDirection() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getDiagonalDirection(); + } + return $this->_diagonalDirection; + } + + /** + * Set DiagonalDirection + * + * @param int $pValue + * @return PHPExcel_Style_Borders + */ + public function setDiagonalDirection($pValue = PHPExcel_Style_Borders::DIAGONAL_NONE) { + if ($pValue == '') { + $pValue = PHPExcel_Style_Borders::DIAGONAL_NONE; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_diagonalDirection = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashcode(); + } + return md5( + $this->getLeft()->getHashCode() + . $this->getRight()->getHashCode() + . $this->getTop()->getHashCode() + . $this->getBottom()->getHashCode() + . $this->getDiagonal()->getHashCode() + . $this->getDiagonalDirection() + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php new file mode 100644 index 00000000..4d34504f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php @@ -0,0 +1,429 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Color + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Color extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Colors */ + const COLOR_BLACK = 'FF000000'; + const COLOR_WHITE = 'FFFFFFFF'; + const COLOR_RED = 'FFFF0000'; + const COLOR_DARKRED = 'FF800000'; + const COLOR_BLUE = 'FF0000FF'; + const COLOR_DARKBLUE = 'FF000080'; + const COLOR_GREEN = 'FF00FF00'; + const COLOR_DARKGREEN = 'FF008000'; + const COLOR_YELLOW = 'FFFFFF00'; + const COLOR_DARKYELLOW = 'FF808000'; + + /** + * Indexed colors array + * + * @var array + */ + protected static $_indexedColors; + + /** + * ARGB - Alpha RGB + * + * @var string + */ + protected $_argb = NULL; + + /** + * Parent property name + * + * @var string + */ + protected $_parentPropertyName; + + + /** + * Create a new PHPExcel_Style_Color + * + * @param string $pARGB ARGB value for the colour + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($pARGB = PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if (!$isConditional) { + $this->_argb = $pARGB; + } + } + + /** + * Bind parent. Only used for supervisor + * + * @param mixed $parent + * @param string $parentPropertyName + * @return PHPExcel_Style_Color + */ + public function bindParent($parent, $parentPropertyName=NULL) + { + $this->_parent = $parent; + $this->_parentPropertyName = $parentPropertyName; + return $this; + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Color + */ + public function getSharedComponent() + { + switch ($this->_parentPropertyName) { + case '_endColor': + return $this->_parent->getSharedComponent()->getEndColor(); break; + case '_color': + return $this->_parent->getSharedComponent()->getColor(); break; + case '_startColor': + return $this->_parent->getSharedComponent()->getStartColor(); break; + } + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + switch ($this->_parentPropertyName) { + case '_endColor': + $key = 'endcolor'; + break; + case '_color': + $key = 'color'; + break; + case '_startColor': + $key = 'startcolor'; + break; + + } + return $this->_parent->getStyleArray(array($key => $array)); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Color + */ + public function applyFromArray($pStyles = NULL) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('rgb', $pStyles)) { + $this->setRGB($pStyles['rgb']); + } + if (array_key_exists('argb', $pStyles)) { + $this->setARGB($pStyles['argb']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get ARGB + * + * @return string + */ + public function getARGB() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getARGB(); + } + return $this->_argb; + } + + /** + * Set ARGB + * + * @param string $pValue + * @return PHPExcel_Style_Color + */ + public function setARGB($pValue = PHPExcel_Style_Color::COLOR_BLACK) { + if ($pValue == '') { + $pValue = PHPExcel_Style_Color::COLOR_BLACK; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('argb' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_argb = $pValue; + } + return $this; + } + + /** + * Get RGB + * + * @return string + */ + public function getRGB() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getRGB(); + } + return substr($this->_argb, 2); + } + + /** + * Set RGB + * + * @param string $pValue RGB value + * @return PHPExcel_Style_Color + */ + public function setRGB($pValue = '000000') { + if ($pValue == '') { + $pValue = '000000'; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_argb = 'FF' . $pValue; + } + return $this; + } + + /** + * Get a specified colour component of an RGB value + * + * @private + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param int $offset Position within the RGB value to extract + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The extracted colour component + */ + private static function _getColourComponent($RGB,$offset,$hex=TRUE) { + $colour = substr($RGB, $offset, 2); + if (!$hex) + $colour = hexdec($colour); + return $colour; + } + + /** + * Get the red colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The red colour component + */ + public static function getRed($RGB,$hex=TRUE) { + return self::_getColourComponent($RGB, strlen($RGB) - 6, $hex); + } + + /** + * Get the green colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The green colour component + */ + public static function getGreen($RGB,$hex=TRUE) { + return self::_getColourComponent($RGB, strlen($RGB) - 4, $hex); + } + + /** + * Get the blue colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The blue colour component + */ + public static function getBlue($RGB,$hex=TRUE) { + return self::_getColourComponent($RGB, strlen($RGB) - 2, $hex); + } + + /** + * Adjust the brightness of a color + * + * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) + * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1 + * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) + */ + public static function changeBrightness($hex, $adjustPercentage) { + $rgba = (strlen($hex) == 8); + + $red = self::getRed($hex, FALSE); + $green = self::getGreen($hex, FALSE); + $blue = self::getBlue($hex, FALSE); + if ($adjustPercentage > 0) { + $red += (255 - $red) * $adjustPercentage; + $green += (255 - $green) * $adjustPercentage; + $blue += (255 - $blue) * $adjustPercentage; + } else { + $red += $red * $adjustPercentage; + $green += $green * $adjustPercentage; + $blue += $blue * $adjustPercentage; + } + + if ($red < 0) $red = 0; + elseif ($red > 255) $red = 255; + if ($green < 0) $green = 0; + elseif ($green > 255) $green = 255; + if ($blue < 0) $blue = 0; + elseif ($blue > 255) $blue = 255; + + $rgb = strtoupper( str_pad(dechex($red), 2, '0', 0) . + str_pad(dechex($green), 2, '0', 0) . + str_pad(dechex($blue), 2, '0', 0) + ); + return (($rgba) ? 'FF' : '') . $rgb; + } + + /** + * Get indexed color + * + * @param int $pIndex Index entry point into the colour array + * @param boolean $background Flag to indicate whether default background or foreground colour + * should be returned if the indexed colour doesn't exist + * @return PHPExcel_Style_Color + */ + public static function indexedColor($pIndex, $background=FALSE) { + // Clean parameter + $pIndex = intval($pIndex); + + // Indexed colors + if (is_null(self::$_indexedColors)) { + self::$_indexedColors = array( + 1 => 'FF000000', // System Colour #1 - Black + 2 => 'FFFFFFFF', // System Colour #2 - White + 3 => 'FFFF0000', // System Colour #3 - Red + 4 => 'FF00FF00', // System Colour #4 - Green + 5 => 'FF0000FF', // System Colour #5 - Blue + 6 => 'FFFFFF00', // System Colour #6 - Yellow + 7 => 'FFFF00FF', // System Colour #7- Magenta + 8 => 'FF00FFFF', // System Colour #8- Cyan + 9 => 'FF800000', // Standard Colour #9 + 10 => 'FF008000', // Standard Colour #10 + 11 => 'FF000080', // Standard Colour #11 + 12 => 'FF808000', // Standard Colour #12 + 13 => 'FF800080', // Standard Colour #13 + 14 => 'FF008080', // Standard Colour #14 + 15 => 'FFC0C0C0', // Standard Colour #15 + 16 => 'FF808080', // Standard Colour #16 + 17 => 'FF9999FF', // Chart Fill Colour #17 + 18 => 'FF993366', // Chart Fill Colour #18 + 19 => 'FFFFFFCC', // Chart Fill Colour #19 + 20 => 'FFCCFFFF', // Chart Fill Colour #20 + 21 => 'FF660066', // Chart Fill Colour #21 + 22 => 'FFFF8080', // Chart Fill Colour #22 + 23 => 'FF0066CC', // Chart Fill Colour #23 + 24 => 'FFCCCCFF', // Chart Fill Colour #24 + 25 => 'FF000080', // Chart Line Colour #25 + 26 => 'FFFF00FF', // Chart Line Colour #26 + 27 => 'FFFFFF00', // Chart Line Colour #27 + 28 => 'FF00FFFF', // Chart Line Colour #28 + 29 => 'FF800080', // Chart Line Colour #29 + 30 => 'FF800000', // Chart Line Colour #30 + 31 => 'FF008080', // Chart Line Colour #31 + 32 => 'FF0000FF', // Chart Line Colour #32 + 33 => 'FF00CCFF', // Standard Colour #33 + 34 => 'FFCCFFFF', // Standard Colour #34 + 35 => 'FFCCFFCC', // Standard Colour #35 + 36 => 'FFFFFF99', // Standard Colour #36 + 37 => 'FF99CCFF', // Standard Colour #37 + 38 => 'FFFF99CC', // Standard Colour #38 + 39 => 'FFCC99FF', // Standard Colour #39 + 40 => 'FFFFCC99', // Standard Colour #40 + 41 => 'FF3366FF', // Standard Colour #41 + 42 => 'FF33CCCC', // Standard Colour #42 + 43 => 'FF99CC00', // Standard Colour #43 + 44 => 'FFFFCC00', // Standard Colour #44 + 45 => 'FFFF9900', // Standard Colour #45 + 46 => 'FFFF6600', // Standard Colour #46 + 47 => 'FF666699', // Standard Colour #47 + 48 => 'FF969696', // Standard Colour #48 + 49 => 'FF003366', // Standard Colour #49 + 50 => 'FF339966', // Standard Colour #50 + 51 => 'FF003300', // Standard Colour #51 + 52 => 'FF333300', // Standard Colour #52 + 53 => 'FF993300', // Standard Colour #53 + 54 => 'FF993366', // Standard Colour #54 + 55 => 'FF333399', // Standard Colour #55 + 56 => 'FF333333' // Standard Colour #56 + ); + } + + if (array_key_exists($pIndex, self::$_indexedColors)) { + return new PHPExcel_Style_Color(self::$_indexedColors[$pIndex]); + } + + if ($background) { + return new PHPExcel_Style_Color('FFFFFFFF'); + } + return new PHPExcel_Style_Color('FF000000'); + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_argb + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php new file mode 100644 index 00000000..ffd7a9f9 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php @@ -0,0 +1,277 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Conditional + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Conditional implements PHPExcel_IComparable +{ + /* Condition types */ + const CONDITION_NONE = 'none'; + const CONDITION_CELLIS = 'cellIs'; + const CONDITION_CONTAINSTEXT = 'containsText'; + const CONDITION_EXPRESSION = 'expression'; + + /* Operator types */ + const OPERATOR_NONE = ''; + const OPERATOR_BEGINSWITH = 'beginsWith'; + const OPERATOR_ENDSWITH = 'endsWith'; + const OPERATOR_EQUAL = 'equal'; + const OPERATOR_GREATERTHAN = 'greaterThan'; + const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const OPERATOR_LESSTHAN = 'lessThan'; + const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; + const OPERATOR_NOTEQUAL = 'notEqual'; + const OPERATOR_CONTAINSTEXT = 'containsText'; + const OPERATOR_NOTCONTAINS = 'notContains'; + const OPERATOR_BETWEEN = 'between'; + + /** + * Condition type + * + * @var int + */ + private $_conditionType; + + /** + * Operator type + * + * @var int + */ + private $_operatorType; + + /** + * Text + * + * @var string + */ + private $_text; + + /** + * Condition + * + * @var string[] + */ + private $_condition = array(); + + /** + * Style + * + * @var PHPExcel_Style + */ + private $_style; + + /** + * Create a new PHPExcel_Style_Conditional + */ + public function __construct() + { + // Initialise values + $this->_conditionType = PHPExcel_Style_Conditional::CONDITION_NONE; + $this->_operatorType = PHPExcel_Style_Conditional::OPERATOR_NONE; + $this->_text = null; + $this->_condition = array(); + $this->_style = new PHPExcel_Style(FALSE, TRUE); + } + + /** + * Get Condition type + * + * @return string + */ + public function getConditionType() { + return $this->_conditionType; + } + + /** + * Set Condition type + * + * @param string $pValue PHPExcel_Style_Conditional condition type + * @return PHPExcel_Style_Conditional + */ + public function setConditionType($pValue = PHPExcel_Style_Conditional::CONDITION_NONE) { + $this->_conditionType = $pValue; + return $this; + } + + /** + * Get Operator type + * + * @return string + */ + public function getOperatorType() { + return $this->_operatorType; + } + + /** + * Set Operator type + * + * @param string $pValue PHPExcel_Style_Conditional operator type + * @return PHPExcel_Style_Conditional + */ + public function setOperatorType($pValue = PHPExcel_Style_Conditional::OPERATOR_NONE) { + $this->_operatorType = $pValue; + return $this; + } + + /** + * Get text + * + * @return string + */ + public function getText() { + return $this->_text; + } + + /** + * Set text + * + * @param string $value + * @return PHPExcel_Style_Conditional + */ + public function setText($value = null) { + $this->_text = $value; + return $this; + } + + /** + * Get Condition + * + * @deprecated Deprecated, use getConditions instead + * @return string + */ + public function getCondition() { + if (isset($this->_condition[0])) { + return $this->_condition[0]; + } + + return ''; + } + + /** + * Set Condition + * + * @deprecated Deprecated, use setConditions instead + * @param string $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function setCondition($pValue = '') { + if (!is_array($pValue)) + $pValue = array($pValue); + + return $this->setConditions($pValue); + } + + /** + * Get Conditions + * + * @return string[] + */ + public function getConditions() { + return $this->_condition; + } + + /** + * Set Conditions + * + * @param string[] $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function setConditions($pValue) { + if (!is_array($pValue)) + $pValue = array($pValue); + + $this->_condition = $pValue; + return $this; + } + + /** + * Add Condition + * + * @param string $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function addCondition($pValue = '') { + $this->_condition[] = $pValue; + return $this; + } + + /** + * Get Style + * + * @return PHPExcel_Style + */ + public function getStyle() { + return $this->_style; + } + + /** + * Set Style + * + * @param PHPExcel_Style $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Conditional + */ + public function setStyle(PHPExcel_Style $pValue = null) { + $this->_style = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_conditionType + . $this->_operatorType + . implode(';', $this->_condition) + . $this->_style->getHashCode() + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php new file mode 100644 index 00000000..1b4d0ad3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php @@ -0,0 +1,321 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Fill + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Fill extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Fill types */ + const FILL_NONE = 'none'; + const FILL_SOLID = 'solid'; + const FILL_GRADIENT_LINEAR = 'linear'; + const FILL_GRADIENT_PATH = 'path'; + const FILL_PATTERN_DARKDOWN = 'darkDown'; + const FILL_PATTERN_DARKGRAY = 'darkGray'; + const FILL_PATTERN_DARKGRID = 'darkGrid'; + const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; + const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; + const FILL_PATTERN_DARKUP = 'darkUp'; + const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; + const FILL_PATTERN_GRAY0625 = 'gray0625'; + const FILL_PATTERN_GRAY125 = 'gray125'; + const FILL_PATTERN_LIGHTDOWN = 'lightDown'; + const FILL_PATTERN_LIGHTGRAY = 'lightGray'; + const FILL_PATTERN_LIGHTGRID = 'lightGrid'; + const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'; + const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; + const FILL_PATTERN_LIGHTUP = 'lightUp'; + const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; + const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; + + /** + * Fill type + * + * @var string + */ + protected $_fillType = PHPExcel_Style_Fill::FILL_NONE; + + /** + * Rotation + * + * @var double + */ + protected $_rotation = 0; + + /** + * Start color + * + * @var PHPExcel_Style_Color + */ + protected $_startColor; + + /** + * End color + * + * @var PHPExcel_Style_Color + */ + protected $_endColor; + + /** + * Create a new PHPExcel_Style_Fill + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if ($isConditional) { + $this->_fillType = NULL; + } + $this->_startColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_WHITE, $isSupervisor, $isConditional); + $this->_endColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->_startColor->bindParent($this, '_startColor'); + $this->_endColor->bindParent($this, '_endColor'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Fill + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getFill(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('fill' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( + * array( + * 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR, + * 'rotation' => 0, + * 'startcolor' => array( + * 'rgb' => '000000' + * ), + * 'endcolor' => array( + * 'argb' => 'FFFFFFFF' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function applyFromArray($pStyles = null) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('type', $pStyles)) { + $this->setFillType($pStyles['type']); + } + if (array_key_exists('rotation', $pStyles)) { + $this->setRotation($pStyles['rotation']); + } + if (array_key_exists('startcolor', $pStyles)) { + $this->getStartColor()->applyFromArray($pStyles['startcolor']); + } + if (array_key_exists('endcolor', $pStyles)) { + $this->getEndColor()->applyFromArray($pStyles['endcolor']); + } + if (array_key_exists('color', $pStyles)) { + $this->getStartColor()->applyFromArray($pStyles['color']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Fill Type + * + * @return string + */ + public function getFillType() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getFillType(); + } + return $this->_fillType; + } + + /** + * Set Fill Type + * + * @param string $pValue PHPExcel_Style_Fill fill type + * @return PHPExcel_Style_Fill + */ + public function setFillType($pValue = PHPExcel_Style_Fill::FILL_NONE) { + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('type' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_fillType = $pValue; + } + return $this; + } + + /** + * Get Rotation + * + * @return double + */ + public function getRotation() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getRotation(); + } + return $this->_rotation; + } + + /** + * Set Rotation + * + * @param double $pValue + * @return PHPExcel_Style_Fill + */ + public function setRotation($pValue = 0) { + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_rotation = $pValue; + } + return $this; + } + + /** + * Get Start Color + * + * @return PHPExcel_Style_Color + */ + public function getStartColor() { + return $this->_startColor; + } + + /** + * Set Start Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function setStartColor(PHPExcel_Style_Color $pValue = null) { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->_isSupervisor) { + $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_startColor = $color; + } + return $this; + } + + /** + * Get End Color + * + * @return PHPExcel_Style_Color + */ + public function getEndColor() { + return $this->_endColor; + } + + /** + * Set End Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function setEndColor(PHPExcel_Style_Color $pValue = null) { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->_isSupervisor) { + $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_endColor = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->getFillType() + . $this->getRotation() + . $this->getStartColor()->getHashCode() + . $this->getEndColor()->getHashCode() + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php new file mode 100644 index 00000000..e89488c2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php @@ -0,0 +1,532 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Font + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Font extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Underline types */ + const UNDERLINE_NONE = 'none'; + const UNDERLINE_DOUBLE = 'double'; + const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting'; + const UNDERLINE_SINGLE = 'single'; + const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting'; + + /** + * Font Name + * + * @var string + */ + protected $_name = 'Calibri'; + + /** + * Font Size + * + * @var float + */ + protected $_size = 11; + + /** + * Bold + * + * @var boolean + */ + protected $_bold = FALSE; + + /** + * Italic + * + * @var boolean + */ + protected $_italic = FALSE; + + /** + * Superscript + * + * @var boolean + */ + protected $_superScript = FALSE; + + /** + * Subscript + * + * @var boolean + */ + protected $_subScript = FALSE; + + /** + * Underline + * + * @var string + */ + protected $_underline = self::UNDERLINE_NONE; + + /** + * Strikethrough + * + * @var boolean + */ + protected $_strikethrough = FALSE; + + /** + * Foreground color + * + * @var PHPExcel_Style_Color + */ + protected $_color; + + /** + * Create a new PHPExcel_Style_Font + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if ($isConditional) { + $this->_name = NULL; + $this->_size = NULL; + $this->_bold = NULL; + $this->_italic = NULL; + $this->_superScript = NULL; + $this->_subScript = NULL; + $this->_underline = NULL; + $this->_strikethrough = NULL; + $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional); + } else { + $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor); + } + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->_color->bindParent($this, '_color'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Font + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getFont(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('font' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray( + * array( + * 'name' => 'Arial', + * 'bold' => TRUE, + * 'italic' => FALSE, + * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE, + * 'strike' => FALSE, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Font + */ + public function applyFromArray($pStyles = null) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('name', $pStyles)) { + $this->setName($pStyles['name']); + } + if (array_key_exists('bold', $pStyles)) { + $this->setBold($pStyles['bold']); + } + if (array_key_exists('italic', $pStyles)) { + $this->setItalic($pStyles['italic']); + } + if (array_key_exists('superScript', $pStyles)) { + $this->setSuperScript($pStyles['superScript']); + } + if (array_key_exists('subScript', $pStyles)) { + $this->setSubScript($pStyles['subScript']); + } + if (array_key_exists('underline', $pStyles)) { + $this->setUnderline($pStyles['underline']); + } + if (array_key_exists('strike', $pStyles)) { + $this->setStrikethrough($pStyles['strike']); + } + if (array_key_exists('color', $pStyles)) { + $this->getColor()->applyFromArray($pStyles['color']); + } + if (array_key_exists('size', $pStyles)) { + $this->setSize($pStyles['size']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Name + * + * @return string + */ + public function getName() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getName(); + } + return $this->_name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Style_Font + */ + public function setName($pValue = 'Calibri') { + if ($pValue == '') { + $pValue = 'Calibri'; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('name' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_name = $pValue; + } + return $this; + } + + /** + * Get Size + * + * @return double + */ + public function getSize() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getSize(); + } + return $this->_size; + } + + /** + * Set Size + * + * @param double $pValue + * @return PHPExcel_Style_Font + */ + public function setSize($pValue = 10) { + if ($pValue == '') { + $pValue = 10; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('size' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_size = $pValue; + } + return $this; + } + + /** + * Get Bold + * + * @return boolean + */ + public function getBold() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getBold(); + } + return $this->_bold; + } + + /** + * Set Bold + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setBold($pValue = false) { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('bold' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_bold = $pValue; + } + return $this; + } + + /** + * Get Italic + * + * @return boolean + */ + public function getItalic() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getItalic(); + } + return $this->_italic; + } + + /** + * Set Italic + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setItalic($pValue = false) { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('italic' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_italic = $pValue; + } + return $this; + } + + /** + * Get SuperScript + * + * @return boolean + */ + public function getSuperScript() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getSuperScript(); + } + return $this->_superScript; + } + + /** + * Set SuperScript + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setSuperScript($pValue = false) { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('superScript' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_superScript = $pValue; + $this->_subScript = !$pValue; + } + return $this; + } + + /** + * Get SubScript + * + * @return boolean + */ + public function getSubScript() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getSubScript(); + } + return $this->_subScript; + } + + /** + * Set SubScript + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setSubScript($pValue = false) { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('subScript' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_subScript = $pValue; + $this->_superScript = !$pValue; + } + return $this; + } + + /** + * Get Underline + * + * @return string + */ + public function getUnderline() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getUnderline(); + } + return $this->_underline; + } + + /** + * Set Underline + * + * @param string|boolean $pValue PHPExcel_Style_Font underline type + * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, + * false equates to UNDERLINE_NONE + * @return PHPExcel_Style_Font + */ + public function setUnderline($pValue = self::UNDERLINE_NONE) { + if (is_bool($pValue)) { + $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; + } elseif ($pValue == '') { + $pValue = self::UNDERLINE_NONE; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('underline' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_underline = $pValue; + } + return $this; + } + + /** + * Get Strikethrough + * + * @return boolean + */ + public function getStrikethrough() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getStrikethrough(); + } + return $this->_strikethrough; + } + + /** + * Set Strikethrough + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setStrikethrough($pValue = false) { + if ($pValue == '') { + $pValue = false; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('strike' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_strikethrough = $pValue; + } + return $this; + } + + /** + * Get Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() { + return $this->_color; + } + + /** + * Set Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Font + */ + public function setColor(PHPExcel_Style_Color $pValue = null) { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->_isSupervisor) { + $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_color = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_name + . $this->_size + . ($this->_bold ? 't' : 'f') + . ($this->_italic ? 't' : 'f') + . ($this->_superScript ? 't' : 'f') + . ($this->_subScript ? 't' : 'f') + . $this->_underline + . ($this->_strikethrough ? 't' : 'f') + . $this->_color->getHashCode() + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php new file mode 100644 index 00000000..e8a978fb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php @@ -0,0 +1,711 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_NumberFormat + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_NumberFormat extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Pre-defined formats */ + const FORMAT_GENERAL = 'General'; + + const FORMAT_TEXT = '@'; + + const FORMAT_NUMBER = '0'; + const FORMAT_NUMBER_00 = '0.00'; + const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'; + const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'; + + const FORMAT_PERCENTAGE = '0%'; + const FORMAT_PERCENTAGE_00 = '0.00%'; + + const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; + const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd'; + const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy'; + const FORMAT_DATE_DMYSLASH = 'd/m/y'; + const FORMAT_DATE_DMYMINUS = 'd-m-y'; + const FORMAT_DATE_DMMINUS = 'd-m'; + const FORMAT_DATE_MYMINUS = 'm-y'; + const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; + const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; + const FORMAT_DATE_XLSX16 = 'd-mmm'; + const FORMAT_DATE_XLSX17 = 'mmm-yy'; + const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; + const FORMAT_DATE_DATETIME = 'd/m/y h:mm'; + const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; + const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; + const FORMAT_DATE_TIME3 = 'h:mm'; + const FORMAT_DATE_TIME4 = 'h:mm:ss'; + const FORMAT_DATE_TIME5 = 'mm:ss'; + const FORMAT_DATE_TIME6 = 'h:mm:ss'; + const FORMAT_DATE_TIME7 = 'i:s.S'; + const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; + const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@'; + + const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'; + const FORMAT_CURRENCY_USD = '$#,##0_-'; + const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-'; + + /** + * Excel built-in number formats + * + * @var array + */ + protected static $_builtInFormats; + + /** + * Excel built-in number formats (flipped, for faster lookups) + * + * @var array + */ + protected static $_flippedBuiltInFormats; + + /** + * Format Code + * + * @var string + */ + protected $_formatCode = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + + /** + * Built-in format Code + * + * @var string + */ + protected $_builtInFormatCode = 0; + + /** + * Create a new PHPExcel_Style_NumberFormat + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + if ($isConditional) { + $this->_formatCode = NULL; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_NumberFormat + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getNumberFormat(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('numberformat' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray( + * array( + * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_NumberFormat + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('code', $pStyles)) { + $this->setFormatCode($pStyles['code']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Format Code + * + * @return string + */ + public function getFormatCode() + { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getFormatCode(); + } + if ($this->_builtInFormatCode !== false) + { + return self::builtInFormatCode($this->_builtInFormatCode); + } + return $this->_formatCode; + } + + /** + * Set Format Code + * + * @param string $pValue + * @return PHPExcel_Style_NumberFormat + */ + public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + } + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('code' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_formatCode = $pValue; + $this->_builtInFormatCode = self::builtInFormatCodeIndex($pValue); + } + return $this; + } + + /** + * Get Built-In Format Code + * + * @return int + */ + public function getBuiltInFormatCode() + { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getBuiltInFormatCode(); + } + return $this->_builtInFormatCode; + } + + /** + * Set Built-In Format Code + * + * @param int $pValue + * @return PHPExcel_Style_NumberFormat + */ + public function setBuiltInFormatCode($pValue = 0) + { + + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue))); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_builtInFormatCode = $pValue; + $this->_formatCode = self::builtInFormatCode($pValue); + } + return $this; + } + + /** + * Fill built-in format codes + */ + private static function fillBuiltInFormatCodes() + { + // Built-in format codes + if (is_null(self::$_builtInFormats)) { + self::$_builtInFormats = array(); + + // General + self::$_builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + self::$_builtInFormats[1] = '0'; + self::$_builtInFormats[2] = '0.00'; + self::$_builtInFormats[3] = '#,##0'; + self::$_builtInFormats[4] = '#,##0.00'; + + self::$_builtInFormats[9] = '0%'; + self::$_builtInFormats[10] = '0.00%'; + self::$_builtInFormats[11] = '0.00E+00'; + self::$_builtInFormats[12] = '# ?/?'; + self::$_builtInFormats[13] = '# ??/??'; + self::$_builtInFormats[14] = 'mm-dd-yy'; + self::$_builtInFormats[15] = 'd-mmm-yy'; + self::$_builtInFormats[16] = 'd-mmm'; + self::$_builtInFormats[17] = 'mmm-yy'; + self::$_builtInFormats[18] = 'h:mm AM/PM'; + self::$_builtInFormats[19] = 'h:mm:ss AM/PM'; + self::$_builtInFormats[20] = 'h:mm'; + self::$_builtInFormats[21] = 'h:mm:ss'; + self::$_builtInFormats[22] = 'm/d/yy h:mm'; + + self::$_builtInFormats[37] = '#,##0 ;(#,##0)'; + self::$_builtInFormats[38] = '#,##0 ;[Red](#,##0)'; + self::$_builtInFormats[39] = '#,##0.00;(#,##0.00)'; + self::$_builtInFormats[40] = '#,##0.00;[Red](#,##0.00)'; + + self::$_builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; + self::$_builtInFormats[45] = 'mm:ss'; + self::$_builtInFormats[46] = '[h]:mm:ss'; + self::$_builtInFormats[47] = 'mmss.0'; + self::$_builtInFormats[48] = '##0.0E+0'; + self::$_builtInFormats[49] = '@'; + + // CHT + self::$_builtInFormats[27] = '[$-404]e/m/d'; + self::$_builtInFormats[30] = 'm/d/yy'; + self::$_builtInFormats[36] = '[$-404]e/m/d'; + self::$_builtInFormats[50] = '[$-404]e/m/d'; + self::$_builtInFormats[57] = '[$-404]e/m/d'; + + // THA + self::$_builtInFormats[59] = 't0'; + self::$_builtInFormats[60] = 't0.00'; + self::$_builtInFormats[61] = 't#,##0'; + self::$_builtInFormats[62] = 't#,##0.00'; + self::$_builtInFormats[67] = 't0%'; + self::$_builtInFormats[68] = 't0.00%'; + self::$_builtInFormats[69] = 't# ?/?'; + self::$_builtInFormats[70] = 't# ??/??'; + + // Flip array (for faster lookups) + self::$_flippedBuiltInFormats = array_flip(self::$_builtInFormats); + } + } + + /** + * Get built-in format code + * + * @param int $pIndex + * @return string + */ + public static function builtInFormatCode($pIndex) + { + // Clean parameter + $pIndex = intval($pIndex); + + // Ensure built-in format codes are available + self::fillBuiltInFormatCodes(); + + // Lookup format code + if (isset(self::$_builtInFormats[$pIndex])) { + return self::$_builtInFormats[$pIndex]; + } + + return ''; + } + + /** + * Get built-in format code index + * + * @param string $formatCode + * @return int|boolean + */ + public static function builtInFormatCodeIndex($formatCode) + { + // Ensure built-in format codes are available + self::fillBuiltInFormatCodes(); + + // Lookup format code + if (isset(self::$_flippedBuiltInFormats[$formatCode])) { + return self::$_flippedBuiltInFormats[$formatCode]; + } + + return false; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_formatCode + . $this->_builtInFormatCode + . __CLASS__ + ); + } + + /** + * Search/replace values to convert Excel date/time format masks to PHP format masks + * + * @var array + */ + private static $_dateFormatReplacements = array( + // first remove escapes related to non-format characters + '\\' => '', + // 12-hour suffix + 'am/pm' => 'A', + // 4-digit year + 'e' => 'Y', + 'yyyy' => 'Y', + // 2-digit year + 'yy' => 'y', + // first letter of month - no php equivalent + 'mmmmm' => 'M', + // full month name + 'mmmm' => 'F', + // short month name + 'mmm' => 'M', + // mm is minutes if time, but can also be month w/leading zero + // so we try to identify times be the inclusion of a : separator in the mask + // It isn't perfect, but the best way I know how + ':mm' => ':i', + 'mm:' => 'i:', + // month leading zero + 'mm' => 'm', + // month no leading zero + 'm' => 'n', + // full day of week name + 'dddd' => 'l', + // short day of week name + 'ddd' => 'D', + // days leading zero + 'dd' => 'd', + // days no leading zero + 'd' => 'j', + // seconds + 'ss' => 's', + // fractional seconds - no php equivalent + '.s' => '' + ); + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock) + * + * @var array + */ + private static $_dateFormatReplacements24 = array( + 'hh' => 'H', + 'h' => 'G' + ); + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock) + * + * @var array + */ + private static $_dateFormatReplacements12 = array( + 'hh' => 'h', + 'h' => 'g' + ); + + private static function _formatAsDate(&$value, &$format) + { + // dvc: convert Excel formats to PHP date formats + + // strip off first part containing e.g. [$-F800] or [$USD-409] + // general syntax: [$<Currency string>-<language info>] + // language info is in hexadecimal + $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format); + + // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case + $format = strtolower($format); + + $format = strtr($format,self::$_dateFormatReplacements); + if (!strpos($format,'A')) { // 24-hour time format + $format = strtr($format,self::$_dateFormatReplacements24); + } else { // 12-hour time format + $format = strtr($format,self::$_dateFormatReplacements12); + } + + $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value); + $value = $dateObj->format($format); + } + + private static function _formatAsPercentage(&$value, &$format) + { + if ($format === self::FORMAT_PERCENTAGE) { + $value = round( (100 * $value), 0) . '%'; + } else { + if (preg_match('/\.[#0]+/i', $format, $m)) { + $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1); + $format = str_replace($m[0], $s, $format); + } + if (preg_match('/^[#0]+/', $format, $m)) { + $format = str_replace($m[0], strlen($m[0]), $format); + } + $format = '%' . str_replace('%', 'f%%', $format); + + $value = sprintf($format, 100 * $value); + } + } + + private static function _formatAsFraction(&$value, &$format) + { + $sign = ($value < 0) ? '-' : ''; + + $integerPart = floor(abs($value)); + $decimalPart = trim(fmod(abs($value),1),'0.'); + $decimalLength = strlen($decimalPart); + $decimalDivisor = pow(10,$decimalLength); + + $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart,$decimalDivisor); + + $adjustedDecimalPart = $decimalPart/$GCD; + $adjustedDecimalDivisor = $decimalDivisor/$GCD; + + if ((strpos($format,'0') !== false) || (strpos($format,'#') !== false) || (substr($format,0,3) == '? ?')) { + if ($integerPart == 0) { + $integerPart = ''; + } + $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; + } else { + $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; + $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor"; + } + } + + private static function _complexNumberFormatMask($number, $mask) { + if (strpos($mask,'.') !== false) { + $numbers = explode('.', $number . '.0'); + $masks = explode('.', $mask . '.0'); + $result1 = self::_complexNumberFormatMask($numbers[0], $masks[0]); + $result2 = strrev(self::_complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]))); + return $result1 . '.' . $result2; + } + + $r = preg_match_all('/0+/', $mask, $result, PREG_OFFSET_CAPTURE); + if ($r > 1) { + $result = array_reverse($result[0]); + + foreach($result as $block) { + $divisor = 1 . $block[0]; + $size = strlen($block[0]); + $offset = $block[1]; + + $blockValue = sprintf( + '%0' . $size . 'd', + fmod($number, $divisor) + ); + $number = floor($number / $divisor); + $mask = substr_replace($mask,$blockValue, $offset, $size); + } + if ($number > 0) { + $mask = substr_replace($mask, $number, $offset, 0); + } + $result = $mask; + } else { + $result = $number; + } + + return $result; + } + + /** + * Convert a value in a pre-defined format to a PHP string + * + * @param mixed $value Value to format + * @param string $format Format code + * @param array $callBack Callback function for additional formatting of string + * @return string Formatted string + */ + public static function toFormattedString($value = '0', $format = PHPExcel_Style_NumberFormat::FORMAT_GENERAL, $callBack = null) + { + // For now we do not treat strings although section 4 of a format code affects strings + if (!is_numeric($value)) return $value; + + // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, + // it seems to round numbers to a total of 10 digits. + if (($format === PHPExcel_Style_NumberFormat::FORMAT_GENERAL) || ($format === PHPExcel_Style_NumberFormat::FORMAT_TEXT)) { + return $value; + } + + // Get the sections, there can be up to four sections + $sections = explode(';', $format); + + // Fetch the relevant section depending on whether number is positive, negative, or zero? + // Text not supported yet. + // Here is how the sections apply to various values in Excel: + // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] + // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] + // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] + // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] + switch (count($sections)) { + case 1: + $format = $sections[0]; + break; + + case 2: + $format = ($value >= 0) ? $sections[0] : $sections[1]; + $value = abs($value); // Use the absolute value + break; + + case 3: + $format = ($value > 0) ? + $sections[0] : ( ($value < 0) ? + $sections[1] : $sections[2]); + $value = abs($value); // Use the absolute value + break; + + case 4: + $format = ($value > 0) ? + $sections[0] : ( ($value < 0) ? + $sections[1] : $sections[2]); + $value = abs($value); // Use the absolute value + break; + + default: + // something is wrong, just use first section + $format = $sections[0]; + break; + } + + // Save format with color information for later use below + $formatColor = $format; + + // Strip color information + $color_regex = '/^\\[[a-zA-Z]+\\]/'; + $format = preg_replace($color_regex, '', $format); + + // Let's begin inspecting the format and converting the value to a formatted string + if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $format)) { // datetime format + self::_formatAsDate($value, $format); + } else if (preg_match('/%$/', $format)) { // % number format + self::_formatAsPercentage($value, $format); + } else { + if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) { + $value = 'EUR ' . sprintf('%1.2f', $value); + } else { + // In Excel formats, "_" is used to add spacing, which we can't do in HTML + $format = preg_replace('/_./', '', $format); + + // Some non-number characters are escaped with \, which we don't need + $format = preg_replace("/\\\\/", '', $format); + + // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols + $format = str_replace(array('"','*'), '', $format); + + // Find out if we need thousands separator + // This is indicated by a comma enclosed by a digit placeholder: + // #,# or 0,0 + $useThousands = preg_match('/(#,#|0,0)/', $format); + if ($useThousands) { + $format = preg_replace('/0,0/', '00', $format); + $format = preg_replace('/#,#/', '##', $format); + } + + // Scale thousands, millions,... + // This is indicated by a number of commas after a digit placeholder: + // #, or 0.0,, + $scale = 1; // same as no scale + $matches = array(); + if (preg_match('/(#|0)(,+)/', $format, $matches)) { + $scale = pow(1000, strlen($matches[2])); + + // strip the commas + $format = preg_replace('/0,+/', '0', $format); + $format = preg_replace('/#,+/', '#', $format); + } + + if (preg_match('/#?.*\?\/\?/', $format, $m)) { + //echo 'Format mask is fractional '.$format.' <br />'; + if ($value != (int)$value) { + self::_formatAsFraction($value, $format); + } + + } else { + // Handle the number itself + + // scale number + $value = $value / $scale; + + // Strip # + $format = preg_replace('/\\#/', '0', $format); + + $n = "/\[[^\]]+\]/"; + $m = preg_replace($n, '', $format); + $number_regex = "/(0+)(\.?)(0*)/"; + if (preg_match($number_regex, $m, $matches)) { + $left = $matches[1]; + $dec = $matches[2]; + $right = $matches[3]; + + // minimun width of formatted number (including dot) + $minWidth = strlen($left) + strlen($dec) + strlen($right); + if ($useThousands) { + $value = number_format( + $value + , strlen($right) + , PHPExcel_Shared_String::getDecimalSeparator() + , PHPExcel_Shared_String::getThousandsSeparator() + ); + $value = preg_replace($number_regex, $value, $format); + } else { + if (preg_match('/[0#]E[+-]0/i', $format)) { + // Scientific format + $value = sprintf('%5.2E', $value); + } elseif (preg_match('/0([^\d\.]+)0/', $format)) { + $value = self::_complexNumberFormatMask($value, $format); + } else { + $sprintf_pattern = "%0$minWidth." . strlen($right) . "f"; + $value = sprintf($sprintf_pattern, $value); + $value = preg_replace($number_regex, $value, $format); + } + } + } + } + if (preg_match('/\[\$(.*)\]/u', $format, $m)) { + // Currency or Accounting + $currencyFormat = $m[0]; + $currencyCode = $m[1]; + list($currencyCode) = explode('-',$currencyCode); + if ($currencyCode == '') { + $currencyCode = PHPExcel_Shared_String::getCurrencyCode(); + } + $value = preg_replace('/\[\$([^\]]*)\]/u',$currencyCode,$value); + } + } + } + + // Additional formatting provided by callback function + if ($callBack !== null) { + list($writerInstance, $function) = $callBack; + $value = $writerInstance->$function($value, $formatColor); + } + + return $value; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php new file mode 100644 index 00000000..8dc1f31a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php @@ -0,0 +1,207 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.4.5, 2007-08-23 + */ + + +/** + * PHPExcel_Style_Protection + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Protection extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /** Protection styles */ + const PROTECTION_INHERIT = 'inherit'; + const PROTECTION_PROTECTED = 'protected'; + const PROTECTION_UNPROTECTED = 'unprotected'; + + /** + * Locked + * + * @var string + */ + protected $_locked; + + /** + * Hidden + * + * @var string + */ + protected $_hidden; + + /** + * Create a new PHPExcel_Style_Protection + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE, $isConditional = FALSE) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if (!$isConditional) { + $this->_locked = self::PROTECTION_INHERIT; + $this->_hidden = self::PROTECTION_INHERIT; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Protection + */ + public function getSharedComponent() + { + return $this->_parent->getSharedComponent()->getProtection(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('protection' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray( + * array( + * 'locked' => TRUE, + * 'hidden' => FALSE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Protection + */ + public function applyFromArray($pStyles = NULL) { + if (is_array($pStyles)) { + if ($this->_isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['locked'])) { + $this->setLocked($pStyles['locked']); + } + if (isset($pStyles['hidden'])) { + $this->setHidden($pStyles['hidden']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get locked + * + * @return string + */ + public function getLocked() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getLocked(); + } + return $this->_locked; + } + + /** + * Set locked + * + * @param string $pValue + * @return PHPExcel_Style_Protection + */ + public function setLocked($pValue = self::PROTECTION_INHERIT) { + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('locked' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_locked = $pValue; + } + return $this; + } + + /** + * Get hidden + * + * @return string + */ + public function getHidden() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHidden(); + } + return $this->_hidden; + } + + /** + * Set hidden + * + * @param string $pValue + * @return PHPExcel_Style_Protection + */ + public function setHidden($pValue = self::PROTECTION_INHERIT) { + if ($this->_isSupervisor) { + $styleArray = $this->getStyleArray(array('hidden' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->_hidden = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->_locked + . $this->_hidden + . __CLASS__ + ); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php new file mode 100644 index 00000000..c2ce9c03 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php @@ -0,0 +1,132 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Style_Supervisor + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +abstract class PHPExcel_Style_Supervisor +{ + /** + * Supervisor? + * + * @var boolean + */ + protected $_isSupervisor; + + /** + * Parent. Only used for supervisor + * + * @var PHPExcel_Style + */ + protected $_parent; + + /** + * Create a new PHPExcel_Style_Alignment + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = FALSE) + { + // Supervisor? + $this->_isSupervisor = $isSupervisor; + } + + /** + * Bind parent. Only used for supervisor + * + * @param PHPExcel $parent + * @return PHPExcel_Style_Supervisor + */ + public function bindParent($parent, $parentPropertyName=NULL) + { + $this->_parent = $parent; + return $this; + } + + /** + * Is this a supervisor or a cell style component? + * + * @return boolean + */ + public function getIsSupervisor() + { + return $this->_isSupervisor; + } + + /** + * Get the currently active sheet. Only used for supervisor + * + * @return PHPExcel_Worksheet + */ + public function getActiveSheet() + { + return $this->_parent->getActiveSheet(); + } + + /** + * Get the currently active cell coordinate in currently active sheet. + * Only used for supervisor + * + * @return string E.g. 'A1' + */ + public function getSelectedCells() + { + return $this->getActiveSheet()->getSelectedCells(); + } + + /** + * Get the currently active cell coordinate in currently active sheet. + * Only used for supervisor + * + * @return string E.g. 'A1' + */ + public function getActiveCell() + { + return $this->getActiveSheet()->getActiveCell(); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != '_parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php new file mode 100644 index 00000000..682ad983 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php @@ -0,0 +1,2909 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet implements PHPExcel_IComparable +{ + /* Break types */ + const BREAK_NONE = 0; + const BREAK_ROW = 1; + const BREAK_COLUMN = 2; + + /* Sheet state */ + const SHEETSTATE_VISIBLE = 'visible'; + const SHEETSTATE_HIDDEN = 'hidden'; + const SHEETSTATE_VERYHIDDEN = 'veryHidden'; + + /** + * Invalid characters in sheet title + * + * @var array + */ + private static $_invalidCharacters = array('*', ':', '/', '\\', '?', '[', ']'); + + /** + * Parent spreadsheet + * + * @var PHPExcel + */ + private $_parent; + + /** + * Cacheable collection of cells + * + * @var PHPExcel_CachedObjectStorage_xxx + */ + private $_cellCollection = null; + + /** + * Collection of row dimensions + * + * @var PHPExcel_Worksheet_RowDimension[] + */ + private $_rowDimensions = array(); + + /** + * Default row dimension + * + * @var PHPExcel_Worksheet_RowDimension + */ + private $_defaultRowDimension = null; + + /** + * Collection of column dimensions + * + * @var PHPExcel_Worksheet_ColumnDimension[] + */ + private $_columnDimensions = array(); + + /** + * Default column dimension + * + * @var PHPExcel_Worksheet_ColumnDimension + */ + private $_defaultColumnDimension = null; + + /** + * Collection of drawings + * + * @var PHPExcel_Worksheet_BaseDrawing[] + */ + private $_drawingCollection = null; + + /** + * Collection of Chart objects + * + * @var PHPExcel_Chart[] + */ + private $_chartCollection = array(); + + /** + * Worksheet title + * + * @var string + */ + private $_title; + + /** + * Sheet state + * + * @var string + */ + private $_sheetState; + + /** + * Page setup + * + * @var PHPExcel_Worksheet_PageSetup + */ + private $_pageSetup; + + /** + * Page margins + * + * @var PHPExcel_Worksheet_PageMargins + */ + private $_pageMargins; + + /** + * Page header/footer + * + * @var PHPExcel_Worksheet_HeaderFooter + */ + private $_headerFooter; + + /** + * Sheet view + * + * @var PHPExcel_Worksheet_SheetView + */ + private $_sheetView; + + /** + * Protection + * + * @var PHPExcel_Worksheet_Protection + */ + private $_protection; + + /** + * Collection of styles + * + * @var PHPExcel_Style[] + */ + private $_styles = array(); + + /** + * Conditional styles. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $_conditionalStylesCollection = array(); + + /** + * Is the current cell collection sorted already? + * + * @var boolean + */ + private $_cellCollectionIsSorted = false; + + /** + * Collection of breaks + * + * @var array + */ + private $_breaks = array(); + + /** + * Collection of merged cell ranges + * + * @var array + */ + private $_mergeCells = array(); + + /** + * Collection of protected cell ranges + * + * @var array + */ + private $_protectedCells = array(); + + /** + * Autofilter Range and selection + * + * @var PHPExcel_Worksheet_AutoFilter + */ + private $_autoFilter = NULL; + + /** + * Freeze pane + * + * @var string + */ + private $_freezePane = ''; + + /** + * Show gridlines? + * + * @var boolean + */ + private $_showGridlines = true; + + /** + * Print gridlines? + * + * @var boolean + */ + private $_printGridlines = false; + + /** + * Show row and column headers? + * + * @var boolean + */ + private $_showRowColHeaders = true; + + /** + * Show summary below? (Row/Column outline) + * + * @var boolean + */ + private $_showSummaryBelow = true; + + /** + * Show summary right? (Row/Column outline) + * + * @var boolean + */ + private $_showSummaryRight = true; + + /** + * Collection of comments + * + * @var PHPExcel_Comment[] + */ + private $_comments = array(); + + /** + * Active cell. (Only one!) + * + * @var string + */ + private $_activeCell = 'A1'; + + /** + * Selected cells + * + * @var string + */ + private $_selectedCells = 'A1'; + + /** + * Cached highest column + * + * @var string + */ + private $_cachedHighestColumn = 'A'; + + /** + * Cached highest row + * + * @var int + */ + private $_cachedHighestRow = 1; + + /** + * Right-to-left? + * + * @var boolean + */ + private $_rightToLeft = false; + + /** + * Hyperlinks. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $_hyperlinkCollection = array(); + + /** + * Data validation objects. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $_dataValidationCollection = array(); + + /** + * Tab color + * + * @var PHPExcel_Style_Color + */ + private $_tabColor; + + /** + * Dirty flag + * + * @var boolean + */ + private $_dirty = true; + + /** + * Hash + * + * @var string + */ + private $_hash = null; + + /** + * CodeName + * + * @var string + */ + private $_codeName = null; + + /** + * Create a new worksheet + * + * @param PHPExcel $pParent + * @param string $pTitle + */ + public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet') + { + // Set parent and title + $this->_parent = $pParent; + $this->setTitle($pTitle, FALSE); + // setTitle can change $pTitle + $this->setCodeName($this->getTitle()); + $this->setSheetState(PHPExcel_Worksheet::SHEETSTATE_VISIBLE); + + $this->_cellCollection = PHPExcel_CachedObjectStorageFactory::getInstance($this); + + // Set page setup + $this->_pageSetup = new PHPExcel_Worksheet_PageSetup(); + + // Set page margins + $this->_pageMargins = new PHPExcel_Worksheet_PageMargins(); + + // Set page header/footer + $this->_headerFooter = new PHPExcel_Worksheet_HeaderFooter(); + + // Set sheet view + $this->_sheetView = new PHPExcel_Worksheet_SheetView(); + + // Drawing collection + $this->_drawingCollection = new ArrayObject(); + + // Chart collection + $this->_chartCollection = new ArrayObject(); + + // Protection + $this->_protection = new PHPExcel_Worksheet_Protection(); + + // Default row dimension + $this->_defaultRowDimension = new PHPExcel_Worksheet_RowDimension(NULL); + + // Default column dimension + $this->_defaultColumnDimension = new PHPExcel_Worksheet_ColumnDimension(NULL); + + $this->_autoFilter = new PHPExcel_Worksheet_AutoFilter(NULL, $this); + } + + + /** + * Disconnect all cells from this PHPExcel_Worksheet object, + * typically so that the worksheet object can be unset + * + */ + public function disconnectCells() { + if ( $this->_cellCollection !== NULL){ + $this->_cellCollection->unsetWorksheetCells(); + $this->_cellCollection = NULL; + } + // detach ourself from the workbook, so that it can then delete this worksheet successfully + $this->_parent = null; + } + + /** + * Code to execute when this worksheet is unset() + * + */ + function __destruct() { + PHPExcel_Calculation::getInstance($this->_parent) + ->clearCalculationCacheForWorksheet($this->_title); + + $this->disconnectCells(); + } + + /** + * Return the cache controller for the cell collection + * + * @return PHPExcel_CachedObjectStorage_xxx + */ + public function getCellCacheController() { + return $this->_cellCollection; + } // function getCellCacheController() + + + /** + * Get array of invalid characters for sheet title + * + * @return array + */ + public static function getInvalidCharacters() + { + return self::$_invalidCharacters; + } + + /** + * Check sheet code name for valid Excel syntax + * + * @param string $pValue The string to check + * @return string The valid string + * @throws Exception + */ + private static function _checkSheetCodeName($pValue) + { + $CharCount = PHPExcel_Shared_String::CountCharacters($pValue); + if ($CharCount == 0) { + throw new PHPExcel_Exception('Sheet code name cannot be empty.'); + } + // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" + if ((str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) || + (PHPExcel_Shared_String::Substring($pValue,-1,1)=='\'') || + (PHPExcel_Shared_String::Substring($pValue,0,1)=='\'')) { + throw new PHPExcel_Exception('Invalid character found in sheet code name'); + } + + // Maximum 31 characters allowed for sheet title + if ($CharCount > 31) { + throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet code name.'); + } + + return $pValue; + } + + /** + * Check sheet title for valid Excel syntax + * + * @param string $pValue The string to check + * @return string The valid string + * @throws PHPExcel_Exception + */ + private static function _checkSheetTitle($pValue) + { + // Some of the printable ASCII characters are invalid: * : / \ ? [ ] + if (str_replace(self::$_invalidCharacters, '', $pValue) !== $pValue) { + throw new PHPExcel_Exception('Invalid character found in sheet title'); + } + + // Maximum 31 characters allowed for sheet title + if (PHPExcel_Shared_String::CountCharacters($pValue) > 31) { + throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet title.'); + } + + return $pValue; + } + + /** + * Get collection of cells + * + * @param boolean $pSorted Also sort the cell collection? + * @return PHPExcel_Cell[] + */ + public function getCellCollection($pSorted = true) + { + if ($pSorted) { + // Re-order cell collection + return $this->sortCellCollection(); + } + if ($this->_cellCollection !== NULL) { + return $this->_cellCollection->getCellList(); + } + return array(); + } + + /** + * Sort collection of cells + * + * @return PHPExcel_Worksheet + */ + public function sortCellCollection() + { + if ($this->_cellCollection !== NULL) { + return $this->_cellCollection->getSortedCellList(); + } + return array(); + } + + /** + * Get collection of row dimensions + * + * @return PHPExcel_Worksheet_RowDimension[] + */ + public function getRowDimensions() + { + return $this->_rowDimensions; + } + + /** + * Get default row dimension + * + * @return PHPExcel_Worksheet_RowDimension + */ + public function getDefaultRowDimension() + { + return $this->_defaultRowDimension; + } + + /** + * Get collection of column dimensions + * + * @return PHPExcel_Worksheet_ColumnDimension[] + */ + public function getColumnDimensions() + { + return $this->_columnDimensions; + } + + /** + * Get default column dimension + * + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getDefaultColumnDimension() + { + return $this->_defaultColumnDimension; + } + + /** + * Get collection of drawings + * + * @return PHPExcel_Worksheet_BaseDrawing[] + */ + public function getDrawingCollection() + { + return $this->_drawingCollection; + } + + /** + * Get collection of charts + * + * @return PHPExcel_Chart[] + */ + public function getChartCollection() + { + return $this->_chartCollection; + } + + /** + * Add chart + * + * @param PHPExcel_Chart $pChart + * @param int|null $iChartIndex Index where chart should go (0,1,..., or null for last) + * @return PHPExcel_Chart + */ + public function addChart(PHPExcel_Chart $pChart = null, $iChartIndex = null) + { + $pChart->setWorksheet($this); + if (is_null($iChartIndex)) { + $this->_chartCollection[] = $pChart; + } else { + // Insert the chart at the requested index + array_splice($this->_chartCollection, $iChartIndex, 0, array($pChart)); + } + + return $pChart; + } + + /** + * Return the count of charts on this worksheet + * + * @return int The number of charts + */ + public function getChartCount() + { + return count($this->_chartCollection); + } + + /** + * Get a chart by its index position + * + * @param string $index Chart index position + * @return false|PHPExcel_Chart + * @throws PHPExcel_Exception + */ + public function getChartByIndex($index = null) + { + $chartCount = count($this->_chartCollection); + if ($chartCount == 0) { + return false; + } + if (is_null($index)) { + $index = --$chartCount; + } + if (!isset($this->_chartCollection[$index])) { + return false; + } + + return $this->_chartCollection[$index]; + } + + /** + * Return an array of the names of charts on this worksheet + * + * @return string[] The names of charts + * @throws PHPExcel_Exception + */ + public function getChartNames() + { + $chartNames = array(); + foreach($this->_chartCollection as $chart) { + $chartNames[] = $chart->getName(); + } + return $chartNames; + } + + /** + * Get a chart by name + * + * @param string $chartName Chart name + * @return false|PHPExcel_Chart + * @throws PHPExcel_Exception + */ + public function getChartByName($chartName = '') + { + $chartCount = count($this->_chartCollection); + if ($chartCount == 0) { + return false; + } + foreach($this->_chartCollection as $index => $chart) { + if ($chart->getName() == $chartName) { + return $this->_chartCollection[$index]; + } + } + return false; + } + + /** + * Refresh column dimensions + * + * @return PHPExcel_Worksheet + */ + public function refreshColumnDimensions() + { + $currentColumnDimensions = $this->getColumnDimensions(); + $newColumnDimensions = array(); + + foreach ($currentColumnDimensions as $objColumnDimension) { + $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; + } + + $this->_columnDimensions = $newColumnDimensions; + + return $this; + } + + /** + * Refresh row dimensions + * + * @return PHPExcel_Worksheet + */ + public function refreshRowDimensions() + { + $currentRowDimensions = $this->getRowDimensions(); + $newRowDimensions = array(); + + foreach ($currentRowDimensions as $objRowDimension) { + $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; + } + + $this->_rowDimensions = $newRowDimensions; + + return $this; + } + + /** + * Calculate worksheet dimension + * + * @return string String containing the dimension of this worksheet + */ + public function calculateWorksheetDimension() + { + // Return + return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); + } + + /** + * Calculate worksheet data dimension + * + * @return string String containing the dimension of this worksheet that actually contain data + */ + public function calculateWorksheetDataDimension() + { + // Return + return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow(); + } + + /** + * Calculate widths for auto-size columns + * + * @param boolean $calculateMergeCells Calculate merge cell width + * @return PHPExcel_Worksheet; + */ + public function calculateColumnWidths($calculateMergeCells = false) + { + // initialize $autoSizes array + $autoSizes = array(); + foreach ($this->getColumnDimensions() as $colDimension) { + if ($colDimension->getAutoSize()) { + $autoSizes[$colDimension->getColumnIndex()] = -1; + } + } + + // There is only something to do if there are some auto-size columns + if (!empty($autoSizes)) { + + // build list of cells references that participate in a merge + $isMergeCell = array(); + foreach ($this->getMergeCells() as $cells) { + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) { + $isMergeCell[$cellReference] = true; + } + } + + // loop through all cells in the worksheet + foreach ($this->getCellCollection(false) as $cellID) { + $cell = $this->getCell($cellID); + if (isset($autoSizes[$this->_cellCollection->getCurrentColumn()])) { + // Determine width if cell does not participate in a merge + if (!isset($isMergeCell[$this->_cellCollection->getCurrentAddress()])) { + // Calculated value + // To formatted string + $cellValue = PHPExcel_Style_NumberFormat::toFormattedString( + $cell->getCalculatedValue(), + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() + ); + + $autoSizes[$this->_cellCollection->getCurrentColumn()] = max( + (float) $autoSizes[$this->_cellCollection->getCurrentColumn()], + (float)PHPExcel_Shared_Font::calculateColumnWidth( + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), + $cellValue, + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), + $this->getDefaultStyle()->getFont() + ) + ); + } + } + } + + // adjust column widths + foreach ($autoSizes as $columnIndex => $width) { + if ($width == -1) $width = $this->getDefaultColumnDimension()->getWidth(); + $this->getColumnDimension($columnIndex)->setWidth($width); + } + } + + return $this; + } + + /** + * Get parent + * + * @return PHPExcel + */ + public function getParent() { + return $this->_parent; + } + + /** + * Re-bind parent + * + * @param PHPExcel $parent + * @return PHPExcel_Worksheet + */ + public function rebindParent(PHPExcel $parent) { + if ($this->_parent !== null) { + $namedRanges = $this->_parent->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + $parent->addNamedRange($namedRange); + } + + $this->_parent->removeSheetByIndex( + $this->_parent->getIndex($this) + ); + } + $this->_parent = $parent; + + return $this; + } + + /** + * Get title + * + * @return string + */ + public function getTitle() + { + return $this->_title; + } + + /** + * Set title + * + * @param string $pValue String containing the dimension of this worksheet + * @param string $updateFormulaCellReferences boolean Flag indicating whether cell references in formulae should + * be updated to reflect the new sheet name. + * This should be left as the default true, unless you are + * certain that no formula cells on any worksheet contain + * references to this worksheet + * @return PHPExcel_Worksheet + */ + public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = true) + { + // Is this a 'rename' or not? + if ($this->getTitle() == $pValue) { + return $this; + } + + // Syntax check + self::_checkSheetTitle($pValue); + + // Old title + $oldTitle = $this->getTitle(); + + if ($this->_parent) { + // Is there already such sheet name? + if ($this->_parent->sheetNameExists($pValue)) { + // Use name, but append with lowest possible integer + + if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,29); + } + $i = 1; + while ($this->_parent->sheetNameExists($pValue . ' ' . $i)) { + ++$i; + if ($i == 10) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,28); + } + } elseif ($i == 100) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,27); + } + } + } + + $altTitle = $pValue . ' ' . $i; + return $this->setTitle($altTitle,$updateFormulaCellReferences); + } + } + + // Set title + $this->_title = $pValue; + $this->_dirty = true; + + if ($this->_parent) { + // New title + $newTitle = $this->getTitle(); + PHPExcel_Calculation::getInstance($this->_parent) + ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); + if ($updateFormulaCellReferences) + PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->_parent, $oldTitle, $newTitle); + } + + return $this; + } + + /** + * Get sheet state + * + * @return string Sheet state (visible, hidden, veryHidden) + */ + public function getSheetState() { + return $this->_sheetState; + } + + /** + * Set sheet state + * + * @param string $value Sheet state (visible, hidden, veryHidden) + * @return PHPExcel_Worksheet + */ + public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE) { + $this->_sheetState = $value; + return $this; + } + + /** + * Get page setup + * + * @return PHPExcel_Worksheet_PageSetup + */ + public function getPageSetup() + { + return $this->_pageSetup; + } + + /** + * Set page setup + * + * @param PHPExcel_Worksheet_PageSetup $pValue + * @return PHPExcel_Worksheet + */ + public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue) + { + $this->_pageSetup = $pValue; + return $this; + } + + /** + * Get page margins + * + * @return PHPExcel_Worksheet_PageMargins + */ + public function getPageMargins() + { + return $this->_pageMargins; + } + + /** + * Set page margins + * + * @param PHPExcel_Worksheet_PageMargins $pValue + * @return PHPExcel_Worksheet + */ + public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue) + { + $this->_pageMargins = $pValue; + return $this; + } + + /** + * Get page header/footer + * + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function getHeaderFooter() + { + return $this->_headerFooter; + } + + /** + * Set page header/footer + * + * @param PHPExcel_Worksheet_HeaderFooter $pValue + * @return PHPExcel_Worksheet + */ + public function setHeaderFooter(PHPExcel_Worksheet_HeaderFooter $pValue) + { + $this->_headerFooter = $pValue; + return $this; + } + + /** + * Get sheet view + * + * @return PHPExcel_Worksheet_SheetView + */ + public function getSheetView() + { + return $this->_sheetView; + } + + /** + * Set sheet view + * + * @param PHPExcel_Worksheet_SheetView $pValue + * @return PHPExcel_Worksheet + */ + public function setSheetView(PHPExcel_Worksheet_SheetView $pValue) + { + $this->_sheetView = $pValue; + return $this; + } + + /** + * Get Protection + * + * @return PHPExcel_Worksheet_Protection + */ + public function getProtection() + { + return $this->_protection; + } + + /** + * Set Protection + * + * @param PHPExcel_Worksheet_Protection $pValue + * @return PHPExcel_Worksheet + */ + public function setProtection(PHPExcel_Worksheet_Protection $pValue) + { + $this->_protection = $pValue; + $this->_dirty = true; + + return $this; + } + + /** + * Get highest worksheet column + * + * @param string $row Return the data highest column for the specified row, + * or the highest column of any row if no row number is passed + * @return string Highest column name + */ + public function getHighestColumn($row = null) + { + if ($row == null) { + return $this->_cachedHighestColumn; + } + return $this->getHighestDataColumn($row); + } + + /** + * Get highest worksheet column that contains data + * + * @param string $row Return the highest data column for the specified row, + * or the highest data column of any row if no row number is passed + * @return string Highest column name that contains data + */ + public function getHighestDataColumn($row = null) + { + return $this->_cellCollection->getHighestColumn($row); + } + + /** + * Get highest worksheet row + * + * @param string $column Return the highest data row for the specified column, + * or the highest row of any column if no column letter is passed + * @return int Highest row number + */ + public function getHighestRow($column = null) + { + if ($column == null) { + return $this->_cachedHighestRow; + } + return $this->getHighestDataRow($column); + } + + /** + * Get highest worksheet row that contains data + * + * @param string $column Return the highest data row for the specified column, + * or the highest data row of any column if no column letter is passed + * @return string Highest row number that contains data + */ + public function getHighestDataRow($column = null) + { + return $this->_cellCollection->getHighestRow($column); + } + + /** + * Get highest worksheet column and highest row that have cell records + * + * @return array Highest column name and highest row number + */ + public function getHighestRowAndColumn() + { + return $this->_cellCollection->getHighestRowAndColumn(); + } + + /** + * Set a cell value + * + * @param string $pCoordinate Coordinate of the cell + * @param mixed $pValue Value of the cell + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false) + { + $cell = $this->getCell($pCoordinate)->setValue($pValue); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell (A = 0) + * @param string $pRow Numeric row coordinate of the cell + * @param mixed $pValue Value of the cell + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $returnCell = false) + { + $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value + * + * @param string $pCoordinate Coordinate of the cell + * @param mixed $pValue Value of the cell + * @param string $pDataType Explicit data type + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false) + { + // Set value + $cell = $this->getCell($pCoordinate)->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell + * @param string $pRow Numeric row coordinate of the cell + * @param mixed $pValue Value of the cell + * @param string $pDataType Explicit data type + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false) + { + $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoordinate Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found + */ + public function getCell($pCoordinate = 'A1') + { + // Check cell collection + if ($this->_cellCollection->isDataSet($pCoordinate)) { + return $this->_cellCollection->getCacheData($pCoordinate); + } + + // Worksheet reference? + if (strpos($pCoordinate, '!') !== false) { + $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true); + return $this->_parent->getSheetByName($worksheetReference[0])->getCell($worksheetReference[1]); + } + + // Named range? + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && + (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this); + if ($namedRange !== NULL) { + $pCoordinate = $namedRange->getRange(); + return $namedRange->getWorksheet()->getCell($pCoordinate); + } + } + + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) { + throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.'); + } elseif (strpos($pCoordinate, '$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } + + // Create new cell object + return $this->_createNewCell($pCoordinate); + } + + /** + * Get cell at a specific coordinate by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell + * @param string $pRow Numeric row coordinate of the cell + * @return PHPExcel_Cell Cell that was found + */ + public function getCellByColumnAndRow($pColumn = 0, $pRow = 1) + { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($pColumn); + $coordinate = $columnLetter . $pRow; + + if ($this->_cellCollection->isDataSet($coordinate)) { + return $this->_cellCollection->getCacheData($coordinate); + } + + return $this->_createNewCell($coordinate); + } + + /** + * Create a new cell at the specified coordinate + * + * @param string $pCoordinate Coordinate of the cell + * @return PHPExcel_Cell Cell that was created + */ + private function _createNewCell($pCoordinate) + { + $cell = $this->_cellCollection->addCacheData( + $pCoordinate, + new PHPExcel_Cell( + NULL, + PHPExcel_Cell_DataType::TYPE_NULL, + $this + ) + ); + $this->_cellCollectionIsSorted = false; + + // Coordinates + $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); + if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($aCoordinates[0])) + $this->_cachedHighestColumn = $aCoordinates[0]; + $this->_cachedHighestRow = max($this->_cachedHighestRow, $aCoordinates[1]); + + // Cell needs appropriate xfIndex from dimensions records + // but don't create dimension records if they don't already exist + $rowDimension = $this->getRowDimension($aCoordinates[1], FALSE); + $columnDimension = $this->getColumnDimension($aCoordinates[0], FALSE); + + if ($rowDimension !== NULL && $rowDimension->getXfIndex() > 0) { + // then there is a row dimension with explicit style, assign it to the cell + $cell->setXfIndex($rowDimension->getXfIndex()); + } elseif ($columnDimension !== NULL && $columnDimension->getXfIndex() > 0) { + // then there is a column dimension, assign it to the cell + $cell->setXfIndex($columnDimension->getXfIndex()); + } + + return $cell; + } + + /** + * Does the cell at a specific coordinate exist? + * + * @param string $pCoordinate Coordinate of the cell + * @throws PHPExcel_Exception + * @return boolean + */ + public function cellExists($pCoordinate = 'A1') + { + // Worksheet reference? + if (strpos($pCoordinate, '!') !== false) { + $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true); + return $this->_parent->getSheetByName($worksheetReference[0])->cellExists($worksheetReference[1]); + } + + // Named range? + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && + (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this); + if ($namedRange !== NULL) { + $pCoordinate = $namedRange->getRange(); + if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { + if (!$namedRange->getLocalOnly()) { + return $namedRange->getWorksheet()->cellExists($pCoordinate); + } else { + throw new PHPExcel_Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); + } + } + } + else { return false; } + } + + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) { + throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.'); + } elseif (strpos($pCoordinate,'$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } else { + // Coordinates + $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); + + // Cell exists? + return $this->_cellCollection->isDataSet($pCoordinate); + } + } + + /** + * Cell at a specific coordinate by using numeric cell coordinates exists? + * + * @param string $pColumn Numeric column coordinate of the cell + * @param string $pRow Numeric row coordinate of the cell + * @return boolean + */ + public function cellExistsByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->cellExists(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get row dimension at a specific row + * + * @param int $pRow Numeric index of the row + * @return PHPExcel_Worksheet_RowDimension + */ + public function getRowDimension($pRow = 1, $create = TRUE) + { + // Found + $found = null; + + // Get row dimension + if (!isset($this->_rowDimensions[$pRow])) { + if (!$create) + return NULL; + $this->_rowDimensions[$pRow] = new PHPExcel_Worksheet_RowDimension($pRow); + + $this->_cachedHighestRow = max($this->_cachedHighestRow,$pRow); + } + return $this->_rowDimensions[$pRow]; + } + + /** + * Get column dimension at a specific column + * + * @param string $pColumn String index of the column + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getColumnDimension($pColumn = 'A', $create = TRUE) + { + // Uppercase coordinate + $pColumn = strtoupper($pColumn); + + // Fetch dimensions + if (!isset($this->_columnDimensions[$pColumn])) { + if (!$create) + return NULL; + $this->_columnDimensions[$pColumn] = new PHPExcel_Worksheet_ColumnDimension($pColumn); + + if (PHPExcel_Cell::columnIndexFromString($this->_cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($pColumn)) + $this->_cachedHighestColumn = $pColumn; + } + return $this->_columnDimensions[$pColumn]; + } + + /** + * Get column dimension at a specific column by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getColumnDimensionByColumn($pColumn = 0) + { + return $this->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($pColumn)); + } + + /** + * Get styles + * + * @return PHPExcel_Style[] + */ + public function getStyles() + { + return $this->_styles; + } + + /** + * Get default style of workbook. + * + * @deprecated + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getDefaultStyle() + { + return $this->_parent->getDefaultStyle(); + } + + /** + * Set default style - should only be used by PHPExcel_IReader implementations! + * + * @deprecated + * @param PHPExcel_Style $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setDefaultStyle(PHPExcel_Style $pValue) + { + $this->_parent->getDefaultStyle()->applyFromArray(array( + 'font' => array( + 'name' => $pValue->getFont()->getName(), + 'size' => $pValue->getFont()->getSize(), + ), + )); + return $this; + } + + /** + * Get style for cell + * + * @param string $pCellCoordinate Cell coordinate to get style for + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getStyle($pCellCoordinate = 'A1') + { + // set this sheet as active + $this->_parent->setActiveSheetIndex($this->_parent->getIndex($this)); + + // set cell coordinate as active + $this->setSelectedCells($pCellCoordinate); + + return $this->_parent->getCellXfSupervisor(); + } + + /** + * Get conditional styles for a cell + * + * @param string $pCoordinate + * @return PHPExcel_Style_Conditional[] + */ + public function getConditionalStyles($pCoordinate = 'A1') + { + if (!isset($this->_conditionalStylesCollection[$pCoordinate])) { + $this->_conditionalStylesCollection[$pCoordinate] = array(); + } + return $this->_conditionalStylesCollection[$pCoordinate]; + } + + /** + * Do conditional styles exist for this cell? + * + * @param string $pCoordinate + * @return boolean + */ + public function conditionalStylesExists($pCoordinate = 'A1') + { + if (isset($this->_conditionalStylesCollection[$pCoordinate])) { + return true; + } + return false; + } + + /** + * Removes conditional styles for a cell + * + * @param string $pCoordinate + * @return PHPExcel_Worksheet + */ + public function removeConditionalStyles($pCoordinate = 'A1') + { + unset($this->_conditionalStylesCollection[$pCoordinate]); + return $this; + } + + /** + * Get collection of conditional styles + * + * @return array + */ + public function getConditionalStylesCollection() + { + return $this->_conditionalStylesCollection; + } + + /** + * Set conditional styles + * + * @param $pCoordinate string E.g. 'A1' + * @param $pValue PHPExcel_Style_Conditional[] + * @return PHPExcel_Worksheet + */ + public function setConditionalStyles($pCoordinate = 'A1', $pValue) + { + $this->_conditionalStylesCollection[$pCoordinate] = $pValue; + return $this; + } + + /** + * Get style for cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @return PHPExcel_Style + */ + public function getStyleByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->getStyle(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Set shared cell style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @deprecated + * @param PHPExcel_Style $pSharedCellStyle Cell style to share + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSharedStyle(PHPExcel_Style $pSharedCellStyle = null, $pRange = '') + { + $this->duplicateStyle($pSharedCellStyle, $pRange); + return $this; + } + + /** + * Duplicate cell style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @param PHPExcel_Style $pCellStyle Cell style to duplicate + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '') + { + // make sure we have a real style and not supervisor + $style = $pCellStyle->getIsSupervisor() ? $pCellStyle->getSharedComponent() : $pCellStyle; + + // Add the style to the workbook if necessary + $workbook = $this->_parent; + if ($existingStyle = $this->_parent->getCellXfByHashCode($pCellStyle->getHashCode())) { + // there is already such cell Xf in our collection + $xfIndex = $existingStyle->getIndex(); + } else { + // we don't have such a cell Xf, need to add + $workbook->addCellXf($pCellStyle); + $xfIndex = $pCellStyle->getIndex(); + } + + // Calculate range outer borders + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange); + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // Loop through cells and apply styles + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $this->getCell(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row)->setXfIndex($xfIndex); + } + } + + return $this; + } + + /** + * Duplicate conditional style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @param array of PHPExcel_Style_Conditional $pCellStyle Cell style to duplicate + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateConditionalStyle(array $pCellStyle = null, $pRange = '') + { + foreach($pCellStyle as $cellStyle) { + if (!($cellStyle instanceof PHPExcel_Style_Conditional)) { + throw new PHPExcel_Exception('Style is not a conditional style'); + } + } + + // Calculate range outer borders + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange); + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // Loop through cells and apply styles + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $this->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row, $pCellStyle); + } + } + + return $this; + } + + /** + * Duplicate cell style array to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range, + * if they are in the styles array. For example, if you decide to set a range of + * cells to font bold, only include font bold in the styles array. + * + * @deprecated + * @param array $pStyles Array containing style information + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @param boolean $pAdvanced Advanced mode for setting borders. + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateStyleArray($pStyles = null, $pRange = '', $pAdvanced = true) + { + $this->getStyle($pRange)->applyFromArray($pStyles, $pAdvanced); + return $this; + } + + /** + * Set break on a cell + * + * @param string $pCell Cell coordinate (e.g. A1) + * @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE) + { + // Uppercase coordinate + $pCell = strtoupper($pCell); + + if ($pCell != '') { + if ($pBreak == PHPExcel_Worksheet::BREAK_NONE) { + if (isset($this->_breaks[$pCell])) { + unset($this->_breaks[$pCell]); + } + } else { + $this->_breaks[$pCell] = $pBreak; + } + } else { + throw new PHPExcel_Exception('No cell coordinate specified.'); + } + + return $this; + } + + /** + * Set break on a cell by using numeric cell coordinates + * + * @param integer $pColumn Numeric column coordinate of the cell + * @param integer $pRow Numeric row coordinate of the cell + * @param integer $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) + * @return PHPExcel_Worksheet + */ + public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = PHPExcel_Worksheet::BREAK_NONE) + { + return $this->setBreak(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow, $pBreak); + } + + /** + * Get breaks + * + * @return array[] + */ + public function getBreaks() + { + return $this->_breaks; + } + + /** + * Set merge on a cell range + * + * @param string $pRange Cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function mergeCells($pRange = 'A1:A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (strpos($pRange,':') !== false) { + $this->_mergeCells[$pRange] = $pRange; + + // make sure cells are created + + // get the cells in the range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); + + // create upper left cell if it does not already exist + $upperLeft = $aReferences[0]; + if (!$this->cellExists($upperLeft)) { + $this->getCell($upperLeft)->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL); + } + + // create or blank out the rest of the cells in the range + $count = count($aReferences); + for ($i = 1; $i < $count; $i++) { + $this->getCell($aReferences[$i])->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL); + } + + } else { + throw new PHPExcel_Exception('Merge must be set on a range of cells.'); + } + + return $this; + } + + /** + * Set merge on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function mergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->mergeCells($cellRange); + } + + /** + * Remove merge on a cell range + * + * @param string $pRange Cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unmergeCells($pRange = 'A1:A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (strpos($pRange,':') !== false) { + if (isset($this->_mergeCells[$pRange])) { + unset($this->_mergeCells[$pRange]); + } else { + throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as merged.'); + } + } else { + throw new PHPExcel_Exception('Merge can only be removed from a range of cells.'); + } + + return $this; + } + + /** + * Remove merge on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unmergeCells($cellRange); + } + + /** + * Get merge cells array. + * + * @return array[] + */ + public function getMergeCells() + { + return $this->_mergeCells; + } + + /** + * Set merge cells array for the entire sheet. Use instead mergeCells() to merge + * a single cell range. + * + * @param array + */ + public function setMergeCells($pValue = array()) + { + $this->_mergeCells = $pValue; + + return $this; + } + + /** + * Set protection on a cell range + * + * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed = false) + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (!$pAlreadyHashed) { + $pPassword = PHPExcel_Shared_PasswordHasher::hashPassword($pPassword); + } + $this->_protectedCells[$pRange] = $pPassword; + + return $this; + } + + /** + * Set protection on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->protectCells($cellRange, $pPassword, $pAlreadyHashed); + } + + /** + * Remove protection on a cell range + * + * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unprotectCells($pRange = 'A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (isset($this->_protectedCells[$pRange])) { + unset($this->_protectedCells[$pRange]); + } else { + throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as protected.'); + } + return $this; + } + + /** + * Remove protection on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed); + } + + /** + * Get protected cells + * + * @return array[] + */ + public function getProtectedCells() + { + return $this->_protectedCells; + } + + /** + * Get Autofilter + * + * @return PHPExcel_Worksheet_AutoFilter + */ + public function getAutoFilter() + { + return $this->_autoFilter; + } + + /** + * Set AutoFilter + * + * @param PHPExcel_Worksheet_AutoFilter|string $pValue + * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setAutoFilter($pValue) + { + if (is_string($pValue)) { + $this->_autoFilter->setRange($pValue); + } elseif(is_object($pValue) && ($pValue instanceof PHPExcel_Worksheet_AutoFilter)) { + $this->_autoFilter = $pValue; + } + return $this; + } + + /** + * Set Autofilter Range by using numeric cell coordinates + * + * @param integer $pColumn1 Numeric column coordinate of the first cell + * @param integer $pRow1 Numeric row coordinate of the first cell + * @param integer $pColumn2 Numeric column coordinate of the second cell + * @param integer $pRow2 Numeric row coordinate of the second cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setAutoFilterByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + return $this->setAutoFilter( + PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 + . ':' . + PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2 + ); + } + + /** + * Remove autofilter + * + * @return PHPExcel_Worksheet + */ + public function removeAutoFilter() + { + $this->_autoFilter->setRange(NULL); + return $this; + } + + /** + * Get Freeze Pane + * + * @return string + */ + public function getFreezePane() + { + return $this->_freezePane; + } + + /** + * Freeze Pane + * + * @param string $pCell Cell (i.e. A2) + * Examples: + * A2 will freeze the rows above cell A2 (i.e row 1) + * B1 will freeze the columns to the left of cell B1 (i.e column A) + * B2 will freeze the rows above and to the left of cell A2 + * (i.e row 1 and column A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function freezePane($pCell = '') + { + // Uppercase coordinate + $pCell = strtoupper($pCell); + + if (strpos($pCell,':') === false && strpos($pCell,',') === false) { + $this->_freezePane = $pCell; + } else { + throw new PHPExcel_Exception('Freeze pane can not be set on a range of cells.'); + } + return $this; + } + + /** + * Freeze Pane by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function freezePaneByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->freezePane(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Unfreeze Pane + * + * @return PHPExcel_Worksheet + */ + public function unfreezePane() + { + return $this->freezePane(''); + } + + /** + * Insert a new row, updating all possible related data + * + * @param int $pBefore Insert before this one + * @param int $pNumRows Number of rows to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewRowBefore($pBefore = 1, $pNumRows = 1) { + if ($pBefore >= 1) { + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); + } else { + throw new PHPExcel_Exception("Rows can only be inserted before at least row 1."); + } + return $this; + } + + /** + * Insert a new column, updating all possible related data + * + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) { + if (!is_numeric($pBefore)) { + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); + } else { + throw new PHPExcel_Exception("Column references should not be numeric."); + } + return $this; + } + + /** + * Insert a new column, updating all possible related data + * + * @param int $pBefore Insert before this one (numeric column coordinate of the cell) + * @param int $pNumCols Number of columns to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) { + if ($pBefore >= 0) { + return $this->insertNewColumnBefore(PHPExcel_Cell::stringFromColumnIndex($pBefore), $pNumCols); + } else { + throw new PHPExcel_Exception("Columns can only be inserted before at least column A (0)."); + } + } + + /** + * Delete a row, updating all possible related data + * + * @param int $pRow Remove starting with this one + * @param int $pNumRows Number of rows to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeRow($pRow = 1, $pNumRows = 1) { + if ($pRow >= 1) { + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); + } else { + throw new PHPExcel_Exception("Rows to be deleted should at least start from row 1."); + } + return $this; + } + + /** + * Remove a column, updating all possible related data + * + * @param int $pColumn Remove starting with this one + * @param int $pNumCols Number of columns to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeColumn($pColumn = 'A', $pNumCols = 1) { + if (!is_numeric($pColumn)) { + $pColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($pColumn) - 1 + $pNumCols); + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); + } else { + throw new PHPExcel_Exception("Column references should not be numeric."); + } + return $this; + } + + /** + * Remove a column, updating all possible related data + * + * @param int $pColumn Remove starting with this one (numeric column coordinate of the cell) + * @param int $pNumCols Number of columns to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeColumnByIndex($pColumn = 0, $pNumCols = 1) { + if ($pColumn >= 0) { + return $this->removeColumn(PHPExcel_Cell::stringFromColumnIndex($pColumn), $pNumCols); + } else { + throw new PHPExcel_Exception("Columns to be deleted should at least start from column 0"); + } + } + + /** + * Show gridlines? + * + * @return boolean + */ + public function getShowGridlines() { + return $this->_showGridlines; + } + + /** + * Set show gridlines + * + * @param boolean $pValue Show gridlines (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowGridlines($pValue = false) { + $this->_showGridlines = $pValue; + return $this; + } + + /** + * Print gridlines? + * + * @return boolean + */ + public function getPrintGridlines() { + return $this->_printGridlines; + } + + /** + * Set print gridlines + * + * @param boolean $pValue Print gridlines (true/false) + * @return PHPExcel_Worksheet + */ + public function setPrintGridlines($pValue = false) { + $this->_printGridlines = $pValue; + return $this; + } + + /** + * Show row and column headers? + * + * @return boolean + */ + public function getShowRowColHeaders() { + return $this->_showRowColHeaders; + } + + /** + * Set show row and column headers + * + * @param boolean $pValue Show row and column headers (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowRowColHeaders($pValue = false) { + $this->_showRowColHeaders = $pValue; + return $this; + } + + /** + * Show summary below? (Row/Column outlining) + * + * @return boolean + */ + public function getShowSummaryBelow() { + return $this->_showSummaryBelow; + } + + /** + * Set show summary below + * + * @param boolean $pValue Show summary below (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowSummaryBelow($pValue = true) { + $this->_showSummaryBelow = $pValue; + return $this; + } + + /** + * Show summary right? (Row/Column outlining) + * + * @return boolean + */ + public function getShowSummaryRight() { + return $this->_showSummaryRight; + } + + /** + * Set show summary right + * + * @param boolean $pValue Show summary right (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowSummaryRight($pValue = true) { + $this->_showSummaryRight = $pValue; + return $this; + } + + /** + * Get comments + * + * @return PHPExcel_Comment[] + */ + public function getComments() + { + return $this->_comments; + } + + /** + * Set comments array for the entire sheet. + * + * @param array of PHPExcel_Comment + * @return PHPExcel_Worksheet + */ + public function setComments($pValue = array()) + { + $this->_comments = $pValue; + + return $this; + } + + /** + * Get comment for cell + * + * @param string $pCellCoordinate Cell coordinate to get comment for + * @return PHPExcel_Comment + * @throws PHPExcel_Exception + */ + public function getComment($pCellCoordinate = 'A1') + { + // Uppercase coordinate + $pCellCoordinate = strtoupper($pCellCoordinate); + + if (strpos($pCellCoordinate,':') !== false || strpos($pCellCoordinate,',') !== false) { + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells.'); + } else if (strpos($pCellCoordinate,'$') !== false) { + throw new PHPExcel_Exception('Cell coordinate string must not be absolute.'); + } else if ($pCellCoordinate == '') { + throw new PHPExcel_Exception('Cell coordinate can not be zero-length string.'); + } else { + // Check if we already have a comment for this cell. + // If not, create a new comment. + if (isset($this->_comments[$pCellCoordinate])) { + return $this->_comments[$pCellCoordinate]; + } else { + $newComment = new PHPExcel_Comment(); + $this->_comments[$pCellCoordinate] = $newComment; + return $newComment; + } + } + } + + /** + * Get comment for cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @return PHPExcel_Comment + */ + public function getCommentByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->getComment(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get selected cell + * + * @deprecated + * @return string + */ + public function getSelectedCell() + { + return $this->getSelectedCells(); + } + + /** + * Get active cell + * + * @return string Example: 'A1' + */ + public function getActiveCell() + { + return $this->_activeCell; + } + + /** + * Get selected cells + * + * @return string + */ + public function getSelectedCells() + { + return $this->_selectedCells; + } + + /** + * Selected cell + * + * @param string $pCoordinate Cell (i.e. A1) + * @return PHPExcel_Worksheet + */ + public function setSelectedCell($pCoordinate = 'A1') + { + return $this->setSelectedCells($pCoordinate); + } + + /** + * Select a range of cells. + * + * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6' + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSelectedCells($pCoordinate = 'A1') + { + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + // Convert 'A' to 'A:A' + $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); + + // Convert '1' to '1:1' + $pCoordinate = preg_replace('/^([0-9]+)$/', '${1}:${1}', $pCoordinate); + + // Convert 'A:C' to 'A1:C1048576' + $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); + + // Convert '1:3' to 'A1:XFD3' + $pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate); + + if (strpos($pCoordinate,':') !== false || strpos($pCoordinate,',') !== false) { + list($first, ) = PHPExcel_Cell::splitRange($pCoordinate); + $this->_activeCell = $first[0]; + } else { + $this->_activeCell = $pCoordinate; + } + $this->_selectedCells = $pCoordinate; + return $this; + } + + /** + * Selected cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSelectedCellByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->setSelectedCells(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get right-to-left + * + * @return boolean + */ + public function getRightToLeft() { + return $this->_rightToLeft; + } + + /** + * Set right-to-left + * + * @param boolean $value Right-to-left true/false + * @return PHPExcel_Worksheet + */ + public function setRightToLeft($value = false) { + $this->_rightToLeft = $value; + return $this; + } + + /** + * Fill worksheet from values in array + * + * @param array $source Source array + * @param mixed $nullValue Value in source array that stands for blank cell + * @param string $startCell Insert array starting from this cell address as the top left coordinate + * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) { + if (is_array($source)) { + // Convert a 1-D array to 2-D (for ease of looping) + if (!is_array(end($source))) { + $source = array($source); + } + + // start coordinate + list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($startCell); + + // Loop through $source + foreach ($source as $rowData) { + $currentColumn = $startColumn; + foreach($rowData as $cellValue) { + if ($strictNullComparison) { + if ($cellValue !== $nullValue) { + // Set cell value + $this->getCell($currentColumn . $startRow)->setValue($cellValue); + } + } else { + if ($cellValue != $nullValue) { + // Set cell value + $this->getCell($currentColumn . $startRow)->setValue($cellValue); + } + } + ++$currentColumn; + } + ++$startRow; + } + } else { + throw new PHPExcel_Exception("Parameter \$source should be an array."); + } + return $this; + } + + /** + * Create array from a range of cells + * + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + */ + public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { + // Returnvalue + $returnValue = array(); + // Identify the range that we need to extract from the worksheet + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange); + $minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1); + $minRow = $rangeStart[1]; + $maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1); + $maxRow = $rangeEnd[1]; + + $maxCol++; + // Loop through rows + $r = -1; + for ($row = $minRow; $row <= $maxRow; ++$row) { + $rRef = ($returnCellRef) ? $row : ++$r; + $c = -1; + // Loop through columns in the current row + for ($col = $minCol; $col != $maxCol; ++$col) { + $cRef = ($returnCellRef) ? $col : ++$c; + // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen + // so we test and retrieve directly against _cellCollection + if ($this->_cellCollection->isDataSet($col.$row)) { + // Cell exists + $cell = $this->_cellCollection->getCacheData($col.$row); + if ($cell->getValue() !== null) { + if ($cell->getValue() instanceof PHPExcel_RichText) { + $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText(); + } else { + if ($calculateFormulas) { + $returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); + } else { + $returnValue[$rRef][$cRef] = $cell->getValue(); + } + } + + if ($formatData) { + $style = $this->_parent->getCellXfByIndex($cell->getXfIndex()); + $returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString( + $returnValue[$rRef][$cRef], + ($style && $style->getNumberFormat()) ? + $style->getNumberFormat()->getFormatCode() : + PHPExcel_Style_NumberFormat::FORMAT_GENERAL + ); + } + } else { + // Cell holds a NULL + $returnValue[$rRef][$cRef] = $nullValue; + } + } else { + // Cell doesn't exist + $returnValue[$rRef][$cRef] = $nullValue; + } + } + } + + // Return + return $returnValue; + } + + + /** + * Create array from a range of cells + * + * @param string $pNamedRange Name of the Named Range + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + * @throws PHPExcel_Exception + */ + public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { + $namedRange = PHPExcel_NamedRange::resolveRange($pNamedRange, $this); + if ($namedRange !== NULL) { + $pWorkSheet = $namedRange->getWorksheet(); + $pCellRange = $namedRange->getRange(); + + return $pWorkSheet->rangeToArray( $pCellRange, + $nullValue, $calculateFormulas, $formatData, $returnCellRef); + } + + throw new PHPExcel_Exception('Named Range '.$pNamedRange.' does not exist.'); + } + + + /** + * Create array from worksheet + * + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + */ + public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) { + // Garbage collect... + $this->garbageCollect(); + + // Identify the range that we need to extract from the worksheet + $maxCol = $this->getHighestColumn(); + $maxRow = $this->getHighestRow(); + // Return + return $this->rangeToArray( 'A1:'.$maxCol.$maxRow, + $nullValue, $calculateFormulas, $formatData, $returnCellRef); + } + + /** + * Get row iterator + * + * @param integer $startRow The row number at which to start iterating + * @return PHPExcel_Worksheet_RowIterator + */ + public function getRowIterator($startRow = 1) { + return new PHPExcel_Worksheet_RowIterator($this,$startRow); + } + + /** + * Run PHPExcel garabage collector. + * + * @return PHPExcel_Worksheet + */ + public function garbageCollect() { + // Flush cache + $this->_cellCollection->getCacheData('A1'); + // Build a reference table from images +// $imageCoordinates = array(); +// $iterator = $this->getDrawingCollection()->getIterator(); +// while ($iterator->valid()) { +// $imageCoordinates[$iterator->current()->getCoordinates()] = true; +// +// $iterator->next(); +// } +// + // Lookup highest column and highest row if cells are cleaned + $colRow = $this->_cellCollection->getHighestRowAndColumn(); + $highestRow = $colRow['row']; + $highestColumn = PHPExcel_Cell::columnIndexFromString($colRow['column']); + + // Loop through column dimensions + foreach ($this->_columnDimensions as $dimension) { + $highestColumn = max($highestColumn,PHPExcel_Cell::columnIndexFromString($dimension->getColumnIndex())); + } + + // Loop through row dimensions + foreach ($this->_rowDimensions as $dimension) { + $highestRow = max($highestRow,$dimension->getRowIndex()); + } + + // Cache values + if ($highestColumn < 0) { + $this->_cachedHighestColumn = 'A'; + } else { + $this->_cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn); + } + $this->_cachedHighestRow = $highestRow; + + // Return + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + if ($this->_dirty) { + $this->_hash = md5( $this->_title . + $this->_autoFilter . + ($this->_protection->isProtectionEnabled() ? 't' : 'f') . + __CLASS__ + ); + $this->_dirty = false; + } + return $this->_hash; + } + + /** + * Extract worksheet title from range. + * + * Example: extractSheetTitle("testSheet!A1") ==> 'A1' + * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> array('testSheet 1', 'A1'); + * + * @param string $pRange Range to extract title from + * @param bool $returnRange Return range? (see example) + * @return mixed + */ + public static function extractSheetTitle($pRange, $returnRange = false) { + // Sheet title included? + if (($sep = strpos($pRange, '!')) === false) { + return ''; + } + + if ($returnRange) { + return array( trim(substr($pRange, 0, $sep),"'"), + substr($pRange, $sep + 1) + ); + } + + return substr($pRange, $sep + 1); + } + + /** + * Get hyperlink + * + * @param string $pCellCoordinate Cell coordinate to get hyperlink for + */ + public function getHyperlink($pCellCoordinate = 'A1') + { + // return hyperlink if we already have one + if (isset($this->_hyperlinkCollection[$pCellCoordinate])) { + return $this->_hyperlinkCollection[$pCellCoordinate]; + } + + // else create hyperlink + $this->_hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink(); + return $this->_hyperlinkCollection[$pCellCoordinate]; + } + + /** + * Set hyperlnk + * + * @param string $pCellCoordinate Cell coordinate to insert hyperlink + * @param PHPExcel_Cell_Hyperlink $pHyperlink + * @return PHPExcel_Worksheet + */ + public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $pHyperlink = null) + { + if ($pHyperlink === null) { + unset($this->_hyperlinkCollection[$pCellCoordinate]); + } else { + $this->_hyperlinkCollection[$pCellCoordinate] = $pHyperlink; + } + return $this; + } + + /** + * Hyperlink at a specific coordinate exists? + * + * @param string $pCoordinate + * @return boolean + */ + public function hyperlinkExists($pCoordinate = 'A1') + { + return isset($this->_hyperlinkCollection[$pCoordinate]); + } + + /** + * Get collection of hyperlinks + * + * @return PHPExcel_Cell_Hyperlink[] + */ + public function getHyperlinkCollection() + { + return $this->_hyperlinkCollection; + } + + /** + * Get data validation + * + * @param string $pCellCoordinate Cell coordinate to get data validation for + */ + public function getDataValidation($pCellCoordinate = 'A1') + { + // return data validation if we already have one + if (isset($this->_dataValidationCollection[$pCellCoordinate])) { + return $this->_dataValidationCollection[$pCellCoordinate]; + } + + // else create data validation + $this->_dataValidationCollection[$pCellCoordinate] = new PHPExcel_Cell_DataValidation(); + return $this->_dataValidationCollection[$pCellCoordinate]; + } + + /** + * Set data validation + * + * @param string $pCellCoordinate Cell coordinate to insert data validation + * @param PHPExcel_Cell_DataValidation $pDataValidation + * @return PHPExcel_Worksheet + */ + public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataValidation $pDataValidation = null) + { + if ($pDataValidation === null) { + unset($this->_dataValidationCollection[$pCellCoordinate]); + } else { + $this->_dataValidationCollection[$pCellCoordinate] = $pDataValidation; + } + return $this; + } + + /** + * Data validation at a specific coordinate exists? + * + * @param string $pCoordinate + * @return boolean + */ + public function dataValidationExists($pCoordinate = 'A1') + { + return isset($this->_dataValidationCollection[$pCoordinate]); + } + + /** + * Get collection of data validations + * + * @return PHPExcel_Cell_DataValidation[] + */ + public function getDataValidationCollection() + { + return $this->_dataValidationCollection; + } + + /** + * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet + * + * @param string $range + * @return string Adjusted range value + */ + public function shrinkRangeToFit($range) { + $maxCol = $this->getHighestColumn(); + $maxRow = $this->getHighestRow(); + $maxCol = PHPExcel_Cell::columnIndexFromString($maxCol); + + $rangeBlocks = explode(' ',$range); + foreach ($rangeBlocks as &$rangeSet) { + $rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($rangeSet); + + if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { $rangeBoundaries[0][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); } + if ($rangeBoundaries[0][1] > $maxRow) { $rangeBoundaries[0][1] = $maxRow; } + if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { $rangeBoundaries[1][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); } + if ($rangeBoundaries[1][1] > $maxRow) { $rangeBoundaries[1][1] = $maxRow; } + $rangeSet = $rangeBoundaries[0][0].$rangeBoundaries[0][1].':'.$rangeBoundaries[1][0].$rangeBoundaries[1][1]; + } + unset($rangeSet); + $stRange = implode(' ',$rangeBlocks); + + return $stRange; + } + + /** + * Get tab color + * + * @return PHPExcel_Style_Color + */ + public function getTabColor() + { + if ($this->_tabColor === NULL) + $this->_tabColor = new PHPExcel_Style_Color(); + + return $this->_tabColor; + } + + /** + * Reset tab color + * + * @return PHPExcel_Worksheet + */ + public function resetTabColor() + { + $this->_tabColor = null; + unset($this->_tabColor); + + return $this; + } + + /** + * Tab color set? + * + * @return boolean + */ + public function isTabColorSet() + { + return ($this->_tabColor !== NULL); + } + + /** + * Copy worksheet (!= clone!) + * + * @return PHPExcel_Worksheet + */ + public function copy() { + $copied = clone $this; + + return $copied; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + foreach ($this as $key => $val) { + if ($key == '_parent') { + continue; + } + + if (is_object($val) || (is_array($val))) { + if ($key == '_cellCollection') { + $newCollection = clone $this->_cellCollection; + $newCollection->copyCellCollection($this); + $this->_cellCollection = $newCollection; + } elseif ($key == '_drawingCollection') { + $newCollection = clone $this->_drawingCollection; + $this->_drawingCollection = $newCollection; + } elseif (($key == '_autoFilter') && ($this->_autoFilter instanceof PHPExcel_Worksheet_AutoFilter)) { + $newAutoFilter = clone $this->_autoFilter; + $this->_autoFilter = $newAutoFilter; + $this->_autoFilter->setParent($this); + } else { + $this->{$key} = unserialize(serialize($val)); + } + } + } + } +/** + * Define the code name of the sheet + * + * @param null|string Same rule as Title minus space not allowed (but, like Excel, change silently space to underscore) + * @return objWorksheet + * @throws PHPExcel_Exception + */ + public function setCodeName($pValue=null){ + // Is this a 'rename' or not? + if ($this->getCodeName() == $pValue) { + return $this; + } + $pValue = str_replace(' ', '_', $pValue);//Excel does this automatically without flinching, we are doing the same + // Syntax check + // throw an exception if not valid + self::_checkSheetCodeName($pValue); + + // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' + + if ($this->getParent()) { + // Is there already such sheet name? + if ($this->getParent()->sheetCodeNameExists($pValue)) { + // Use name, but append with lowest possible integer + + if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,29); + } + $i = 1; + while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) { + ++$i; + if ($i == 10) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,28); + } + } elseif ($i == 100) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) { + $pValue = PHPExcel_Shared_String::Substring($pValue,0,27); + } + } + } + + $pValue = $pValue . '_' . $i;// ok, we have a valid name + //codeName is'nt used in formula : no need to call for an update + //return $this->setTitle($altTitle,$updateFormulaCellReferences); + } + } + + $this->_codeName=$pValue; + return $this; + } + /** + * Return the code name of the sheet + * + * @return null|string + */ + public function getCodeName(){ + return $this->_codeName; + } + /** + * Sheet has a code name ? + * @return boolean + */ + public function hasCodeName(){ + return !(is_null($this->_codeName)); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php new file mode 100644 index 00000000..03055e10 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php @@ -0,0 +1,858 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_AutoFilter + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_AutoFilter +{ + /** + * Autofilter Worksheet + * + * @var PHPExcel_Worksheet + */ + private $_workSheet = NULL; + + + /** + * Autofilter Range + * + * @var string + */ + private $_range = ''; + + + /** + * Autofilter Column Ruleset + * + * @var array of PHPExcel_Worksheet_AutoFilter_Column + */ + private $_columns = array(); + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter + * + * @param string $pRange Cell range (i.e. A1:E10) + * @param PHPExcel_Worksheet $pSheet + */ + public function __construct($pRange = '', PHPExcel_Worksheet $pSheet = NULL) + { + $this->_range = $pRange; + $this->_workSheet = $pSheet; + } + + /** + * Get AutoFilter Parent Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getParent() { + return $this->_workSheet; + } + + /** + * Set AutoFilter Parent Worksheet + * + * @param PHPExcel_Worksheet $pSheet + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setParent(PHPExcel_Worksheet $pSheet = NULL) { + $this->_workSheet = $pSheet; + + return $this; + } + + /** + * Get AutoFilter Range + * + * @return string + */ + public function getRange() { + return $this->_range; + } + + /** + * Set AutoFilter Range + * + * @param string $pRange Cell range (i.e. A1:E10) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setRange($pRange = '') { + // Uppercase coordinate + $cellAddress = explode('!',strtoupper($pRange)); + if (count($cellAddress) > 1) { + list($worksheet,$pRange) = $cellAddress; + } + + if (strpos($pRange,':') !== FALSE) { + $this->_range = $pRange; + } elseif(empty($pRange)) { + $this->_range = ''; + } else { + throw new PHPExcel_Exception('Autofilter must be set on a range of cells.'); + } + + if (empty($pRange)) { + // Discard all column rules + $this->_columns = array(); + } else { + // Discard any column rules that are no longer valid within this range + list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range); + foreach($this->_columns as $key => $value) { + $colIndex = PHPExcel_Cell::columnIndexFromString($key); + if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { + unset($this->_columns[$key]); + } + } + } + + return $this; + } + + /** + * Get all AutoFilter Columns + * + * @throws PHPExcel_Exception + * @return array of PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumns() { + return $this->_columns; + } + + /** + * Validate that the specified column is in the AutoFilter range + * + * @param string $column Column name (e.g. A) + * @throws PHPExcel_Exception + * @return integer The column offset within the autofilter range + */ + public function testColumnInRange($column) { + if (empty($this->_range)) { + throw new PHPExcel_Exception("No autofilter range is defined."); + } + + $columnIndex = PHPExcel_Cell::columnIndexFromString($column); + list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range); + if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { + throw new PHPExcel_Exception("Column is outside of current autofilter range."); + } + + return $columnIndex - $rangeStart[0]; + } + + /** + * Get a specified AutoFilter Column Offset within the defined AutoFilter range + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return integer The offset of the specified column within the autofilter range + */ + public function getColumnOffset($pColumn) { + return $this->testColumnInRange($pColumn); + } + + /** + * Get a specified AutoFilter Column + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumn($pColumn) { + $this->testColumnInRange($pColumn); + + if (!isset($this->_columns[$pColumn])) { + $this->_columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this); + } + + return $this->_columns[$pColumn]; + } + + /** + * Get a specified AutoFilter Column by it's offset + * + * @param integer $pColumnOffset Column offset within range (starting from 0) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumnByOffset($pColumnOffset = 0) { + list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range); + $pColumn = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1); + + return $this->getColumn($pColumn); + } + + /** + * Set AutoFilter + * + * @param PHPExcel_Worksheet_AutoFilter_Column|string $pColumn + * A simple string containing a Column ID like 'A' is permitted + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setColumn($pColumn) + { + if ((is_string($pColumn)) && (!empty($pColumn))) { + $column = $pColumn; + } elseif(is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) { + $column = $pColumn->getColumnIndex(); + } else { + throw new PHPExcel_Exception("Column is not within the autofilter range."); + } + $this->testColumnInRange($column); + + if (is_string($pColumn)) { + $this->_columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this); + } elseif(is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) { + $pColumn->setParent($this); + $this->_columns[$column] = $pColumn; + } + ksort($this->_columns); + + return $this; + } + + /** + * Clear a specified AutoFilter Column + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function clearColumn($pColumn) { + $this->testColumnInRange($pColumn); + + if (isset($this->_columns[$pColumn])) { + unset($this->_columns[$pColumn]); + } + + return $this; + } + + /** + * Shift an AutoFilter Column Rule to a different column + * + * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range. + * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value. + * Use with caution. + * + * @param string $fromColumn Column name (e.g. A) + * @param string $toColumn Column name (e.g. B) + * @return PHPExcel_Worksheet_AutoFilter + */ + public function shiftColumn($fromColumn=NULL,$toColumn=NULL) { + $fromColumn = strtoupper($fromColumn); + $toColumn = strtoupper($toColumn); + + if (($fromColumn !== NULL) && (isset($this->_columns[$fromColumn])) && ($toColumn !== NULL)) { + $this->_columns[$fromColumn]->setParent(); + $this->_columns[$fromColumn]->setColumnIndex($toColumn); + $this->_columns[$toColumn] = $this->_columns[$fromColumn]; + $this->_columns[$toColumn]->setParent($this); + unset($this->_columns[$fromColumn]); + + ksort($this->_columns); + } + + return $this; + } + + + /** + * Test if cell value is in the defined set of values + * + * @param mixed $cellValue + * @param mixed[] $dataSet + * @return boolean + */ + private static function _filterTestInSimpleDataSet($cellValue,$dataSet) + { + $dataSetValues = $dataSet['filterValues']; + $blanks = $dataSet['blanks']; + if (($cellValue == '') || ($cellValue === NULL)) { + return $blanks; + } + return in_array($cellValue,$dataSetValues); + } + + /** + * Test if cell value is in the defined set of Excel date values + * + * @param mixed $cellValue + * @param mixed[] $dataSet + * @return boolean + */ + private static function _filterTestInDateGroupSet($cellValue,$dataSet) + { + $dateSet = $dataSet['filterValues']; + $blanks = $dataSet['blanks']; + if (($cellValue == '') || ($cellValue === NULL)) { + return $blanks; + } + + if (is_numeric($cellValue)) { + $dateValue = PHPExcel_Shared_Date::ExcelToPHP($cellValue); + if ($cellValue < 1) { + // Just the time part + $dtVal = date('His',$dateValue); + $dateSet = $dateSet['time']; + } elseif($cellValue == floor($cellValue)) { + // Just the date part + $dtVal = date('Ymd',$dateValue); + $dateSet = $dateSet['date']; + } else { + // date and time parts + $dtVal = date('YmdHis',$dateValue); + $dateSet = $dateSet['dateTime']; + } + foreach($dateSet as $dateValue) { + // Use of substr to extract value at the appropriate group level + if (substr($dtVal,0,strlen($dateValue)) == $dateValue) + return TRUE; + } + } + + return FALSE; + } + + /** + * Test if cell value is within a set of values defined by a ruleset + * + * @param mixed $cellValue + * @param mixed[] $ruleSet + * @return boolean + */ + private static function _filterTestInCustomDataSet($cellValue, $ruleSet) + { + $dataSet = $ruleSet['filterRules']; + $join = $ruleSet['join']; + $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : FALSE; + + if (!$customRuleForBlanks) { + // Blank cells are always ignored, so return a FALSE + if (($cellValue == '') || ($cellValue === NULL)) { + return FALSE; + } + } + $returnVal = ($join == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); + foreach($dataSet as $rule) { + if (is_numeric($rule['value'])) { + // Numeric values are tested using the appropriate operator + switch ($rule['operator']) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL : + $retVal = ($cellValue == $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL : + $retVal = ($cellValue != $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN : + $retVal = ($cellValue > $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL : + $retVal = ($cellValue >= $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN : + $retVal = ($cellValue < $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL : + $retVal = ($cellValue <= $rule['value']); + break; + } + } elseif($rule['value'] == '') { + switch ($rule['operator']) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL : + $retVal = (($cellValue == '') || ($cellValue === NULL)); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL : + $retVal = (($cellValue != '') && ($cellValue !== NULL)); + break; + default : + $retVal = TRUE; + break; + } + } else { + // String values are always tested for equality, factoring in for wildcards (hence a regexp test) + $retVal = preg_match('/^'.$rule['value'].'$/i',$cellValue); + } + // If there are multiple conditions, then we need to test both using the appropriate join operator + switch ($join) { + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR : + $returnVal = $returnVal || $retVal; + // Break as soon as we have a TRUE match for OR joins, + // to avoid unnecessary additional code execution + if ($returnVal) + return $returnVal; + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND : + $returnVal = $returnVal && $retVal; + break; + } + } + + return $returnVal; + } + + /** + * Test if cell date value is matches a set of values defined by a set of months + * + * @param mixed $cellValue + * @param mixed[] $monthSet + * @return boolean + */ + private static function _filterTestInPeriodDateSet($cellValue, $monthSet) + { + // Blank cells are always ignored, so return a FALSE + if (($cellValue == '') || ($cellValue === NULL)) { + return FALSE; + } + + if (is_numeric($cellValue)) { + $dateValue = date('m',PHPExcel_Shared_Date::ExcelToPHP($cellValue)); + if (in_array($dateValue,$monthSet)) { + return TRUE; + } + } + + return FALSE; + } + + /** + * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching + * + * @var array + */ + private static $_fromReplace = array('\*', '\?', '~~', '~.*', '~.?'); + private static $_toReplace = array('.*', '.', '~', '\*', '\?'); + + + /** + * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation + * + * @param string $dynamicRuleType + * @param PHPExcel_Worksheet_AutoFilter_Column &$filterColumn + * @return mixed[] + */ + private function _dynamicFilterDateRange($dynamicRuleType, &$filterColumn) + { + $rDateType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC); + $val = $maxVal = NULL; + + $ruleValues = array(); + $baseDate = PHPExcel_Calculation_DateTime::DATENOW(); + // Calculate start/end dates for the required date range based on current date + switch ($dynamicRuleType) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK : + $baseDate = strtotime('-7 days',$baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK : + $baseDate = strtotime('-7 days',$baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH : + $baseDate = strtotime('-1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH : + $baseDate = strtotime('+1 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER : + $baseDate = strtotime('-3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER : + $baseDate = strtotime('+3 month',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR : + $baseDate = strtotime('-1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR : + $baseDate = strtotime('+1 year',gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + } + + switch ($dynamicRuleType) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW : + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate)); + $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE : + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day',$baseDate)); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR : + $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,31,12,date('Y',$baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1,date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER : + $thisMonth = date('m',$baseDate); + $thisQuarter = floor(--$thisMonth / 3); + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),(1+$thisQuarter)*3,date('Y',$baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,1+$thisQuarter*3,date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH : + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0,0,0,date('t',$baseDate),date('m',$baseDate),date('Y',$baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0,0,0,1,date('m',$baseDate),date('Y',$baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK : + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK : + $dayOfWeek = date('w',$baseDate); + $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate) - $dayOfWeek; + $maxVal = $val + 7; + break; + } + + switch ($dynamicRuleType) { + // Adjust Today dates for Yesterday and Tomorrow + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY : + --$maxVal; + --$val; + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW : + ++$maxVal; + ++$val; + break; + } + + // Set the filter column rule attributes ready for writing + $filterColumn->setAttributes(array( 'val' => $val, + 'maxVal' => $maxVal + ) + ); + + // Set the rules for identifying rows for hide/show + $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, + 'value' => $val + ); + $ruleValues[] = array( 'operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, + 'value' => $maxVal + ); + PHPExcel_Calculation_Functions::setReturnDateType($rDateType); + + return array( + 'method' => '_filterTestInCustomDataSet', + 'arguments' => array( 'filterRules' => $ruleValues, + 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND + ) + ); + } + + private function _calculateTopTenValue($columnID,$startRow,$endRow,$ruleType,$ruleValue) { + $range = $columnID.$startRow.':'.$columnID.$endRow; + $dataValues = PHPExcel_Calculation_Functions::flattenArray( + $this->_workSheet->rangeToArray($range,NULL,TRUE,FALSE) + ); + + $dataValues = array_filter($dataValues); + if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { + rsort($dataValues); + } else { + sort($dataValues); + } + + return array_pop(array_slice($dataValues,0,$ruleValue)); + } + + /** + * Apply the AutoFilter rules to the AutoFilter Range + * + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function showHideRows() + { + list($rangeStart,$rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->_range); + + // The heading row should always be visible +// echo 'AutoFilter Heading Row ',$rangeStart[1],' is always SHOWN',PHP_EOL; + $this->_workSheet->getRowDimension($rangeStart[1])->setVisible(TRUE); + + $columnFilterTests = array(); + foreach($this->_columns as $columnID => $filterColumn) { + $rules = $filterColumn->getRules(); + switch ($filterColumn->getFilterType()) { + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER : + $ruleValues = array(); + // Build a list of the filter value selections + foreach($rules as $rule) { + $ruleType = $rule->getRuleType(); + $ruleValues[] = $rule->getValue(); + } + // Test if we want to include blanks in our filter criteria + $blanks = FALSE; + $ruleDataSet = array_filter($ruleValues); + if (count($ruleValues) != count($ruleDataSet)) + $blanks = TRUE; + if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) { + // Filter on absolute values + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInSimpleDataSet', + 'arguments' => array( 'filterValues' => $ruleDataSet, + 'blanks' => $blanks + ) + ); + } else { + // Filter on date group values + $arguments = array(); + foreach($ruleDataSet as $ruleValue) { + $date = $time = ''; + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')) + $date .= sprintf('%04d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')) + $date .= sprintf('%02d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')) + $date .= sprintf('%02d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')) + $time .= sprintf('%02d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')) + $time .= sprintf('%02d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')) + $time .= sprintf('%02d',$ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); + $dateTime = $date . $time; + $arguments['date'][] = $date; + $arguments['time'][] = $time; + $arguments['dateTime'][] = $dateTime; + } + // Remove empty elements + $arguments['date'] = array_filter($arguments['date']); + $arguments['time'] = array_filter($arguments['time']); + $arguments['dateTime'] = array_filter($arguments['dateTime']); + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInDateGroupSet', + 'arguments' => array( 'filterValues' => $arguments, + 'blanks' => $blanks + ) + ); + } + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER : + $customRuleForBlanks = FALSE; + $ruleValues = array(); + // Build a list of the filter value selections + foreach($rules as $rule) { + $ruleType = $rule->getRuleType(); + $ruleValue = $rule->getValue(); + if (!is_numeric($ruleValue)) { + // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards + $ruleValue = preg_quote($ruleValue); + $ruleValue = str_replace(self::$_fromReplace,self::$_toReplace,$ruleValue); + if (trim($ruleValue) == '') { + $customRuleForBlanks = TRUE; + $ruleValue = trim($ruleValue); + } + } + $ruleValues[] = array( 'operator' => $rule->getOperator(), + 'value' => $ruleValue + ); + } + $join = $filterColumn->getJoin(); + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInCustomDataSet', + 'arguments' => array( 'filterRules' => $ruleValues, + 'join' => $join, + 'customRuleForBlanks' => $customRuleForBlanks + ) + ); + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER : + $ruleValues = array(); + foreach($rules as $rule) { + // We should only ever have one Dynamic Filter Rule anyway + $dynamicRuleType = $rule->getGrouping(); + if (($dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || + ($dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) { + // Number (Average) based + // Calculate the average + $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')'; + $average = PHPExcel_Calculation::getInstance()->calculateFormula($averageFormula,NULL,$this->_workSheet->getCell('A1')); + // Set above/below rule based on greaterThan or LessTan + $operator = ($dynamicRuleType === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; + $ruleValues[] = array( 'operator' => $operator, + 'value' => $average + ); + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInCustomDataSet', + 'arguments' => array( 'filterRules' => $ruleValues, + 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR + ) + ); + } else { + // Date based + if ($dynamicRuleType{0} == 'M' || $dynamicRuleType{0} == 'Q') { + // Month or Quarter + sscanf($dynamicRuleType,'%[A-Z]%d', $periodType, $period); + if ($periodType == 'M') { + $ruleValues = array($period); + } else { + --$period; + $periodEnd = (1+$period)*3; + $periodStart = 1+$period*3; + $ruleValues = range($periodStart,periodEnd); + } + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInPeriodDateSet', + 'arguments' => $ruleValues + ); + $filterColumn->setAttributes(array()); + } else { + // Date Range + $columnFilterTests[$columnID] = $this->_dynamicFilterDateRange($dynamicRuleType, $filterColumn); + break; + } + } + } + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER : + $ruleValues = array(); + $dataRowCount = $rangeEnd[1] - $rangeStart[1]; + foreach($rules as $rule) { + // We should only ever have one Dynamic Filter Rule anyway + $toptenRuleType = $rule->getGrouping(); + $ruleValue = $rule->getValue(); + $ruleOperator = $rule->getOperator(); + } + if ($ruleOperator === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { + $ruleValue = floor($ruleValue * ($dataRowCount / 100)); + } + if ($ruleValue < 1) $ruleValue = 1; + if ($ruleValue > 500) $ruleValue = 500; + + $maxVal = $this->_calculateTopTenValue($columnID,$rangeStart[1]+1,$rangeEnd[1],$toptenRuleType,$ruleValue); + + $operator = ($toptenRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; + $ruleValues[] = array( 'operator' => $operator, + 'value' => $maxVal + ); + $columnFilterTests[$columnID] = array( + 'method' => '_filterTestInCustomDataSet', + 'arguments' => array( 'filterRules' => $ruleValues, + 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR + ) + ); + $filterColumn->setAttributes( + array('maxVal' => $maxVal) + ); + break; + } + } + +// echo 'Column Filter Test CRITERIA',PHP_EOL; +// var_dump($columnFilterTests); +// + // Execute the column tests for each row in the autoFilter range to determine show/hide, + for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) { +// echo 'Testing Row = ',$row,PHP_EOL; + $result = TRUE; + foreach($columnFilterTests as $columnID => $columnFilterTest) { +// echo 'Testing cell ',$columnID.$row,PHP_EOL; + $cellValue = $this->_workSheet->getCell($columnID.$row)->getCalculatedValue(); +// echo 'Value is ',$cellValue,PHP_EOL; + // Execute the filter test + $result = $result && + call_user_func_array( + array('PHPExcel_Worksheet_AutoFilter',$columnFilterTest['method']), + array( + $cellValue, + $columnFilterTest['arguments'] + ) + ); +// echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL; + // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests + if (!$result) + break; + } + // Set show/hide for the row based on the result of the autoFilter result +// echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL; + $this->_workSheet->getRowDimension($row)->setVisible($result); + } + + return $this; + } + + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == '_workSheet') { + // Detach from worksheet + $this->{$key} = NULL; + } else { + $this->{$key} = clone $value; + } + } elseif ((is_array($value)) && ($key == '_columns')) { + // The columns array of PHPExcel_Worksheet_AutoFilter objects + $this->{$key} = array(); + foreach ($value as $k => $v) { + $this->{$key}[$k] = clone $v; + // attach the new cloned Column to this new cloned Autofilter object + $this->{$key}[$k]->setParent($this); + } + } else { + $this->{$key} = $value; + } + } + } + + /** + * toString method replicates previous behavior by returning the range if object is + * referenced as a property of its parent. + */ + public function __toString() { + return (string) $this->_range; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php new file mode 100644 index 00000000..12043d5a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php @@ -0,0 +1,394 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_AutoFilter_Column + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_AutoFilter_Column +{ + const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; + const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; + // Supports no more than 2 rules, with an And/Or join criteria + // if more than 1 rule is defined + const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; + // Even though the filter rule is constant, the filtered data can vary + // e.g. filtered by date = TODAY + const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; + + /** + * Types of autofilter rules + * + * @var string[] + */ + private static $_filterTypes = array( + // Currently we're not handling + // colorFilter + // extLst + // iconFilter + self::AUTOFILTER_FILTERTYPE_FILTER, + self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, + self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, + self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, + ); + + /* Multiple Rule Connections */ + const AUTOFILTER_COLUMN_JOIN_AND = 'and'; + const AUTOFILTER_COLUMN_JOIN_OR = 'or'; + + /** + * Join options for autofilter rules + * + * @var string[] + */ + private static $_ruleJoins = array( + self::AUTOFILTER_COLUMN_JOIN_AND, + self::AUTOFILTER_COLUMN_JOIN_OR, + ); + + /** + * Autofilter + * + * @var PHPExcel_Worksheet_AutoFilter + */ + private $_parent = NULL; + + + /** + * Autofilter Column Index + * + * @var string + */ + private $_columnIndex = ''; + + + /** + * Autofilter Column Filter Type + * + * @var string + */ + private $_filterType = self::AUTOFILTER_FILTERTYPE_FILTER; + + + /** + * Autofilter Multiple Rules And/Or + * + * @var string + */ + private $_join = self::AUTOFILTER_COLUMN_JOIN_OR; + + + /** + * Autofilter Column Rules + * + * @var array of PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + private $_ruleset = array(); + + + /** + * Autofilter Column Dynamic Attributes + * + * @var array of mixed + */ + private $_attributes = array(); + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter_Column + * + * @param string $pColumn Column (e.g. A) + * @param PHPExcel_Worksheet_AutoFilter $pParent Autofilter for this column + */ + public function __construct($pColumn, PHPExcel_Worksheet_AutoFilter $pParent = NULL) + { + $this->_columnIndex = $pColumn; + $this->_parent = $pParent; + } + + /** + * Get AutoFilter Column Index + * + * @return string + */ + public function getColumnIndex() { + return $this->_columnIndex; + } + + /** + * Set AutoFilter Column Index + * + * @param string $pColumn Column (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setColumnIndex($pColumn) { + // Uppercase coordinate + $pColumn = strtoupper($pColumn); + if ($this->_parent !== NULL) { + $this->_parent->testColumnInRange($pColumn); + } + + $this->_columnIndex = $pColumn; + + return $this; + } + + /** + * Get this Column's AutoFilter Parent + * + * @return PHPExcel_Worksheet_AutoFilter + */ + public function getParent() { + return $this->_parent; + } + + /** + * Set this Column's AutoFilter Parent + * + * @param PHPExcel_Worksheet_AutoFilter + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setParent(PHPExcel_Worksheet_AutoFilter $pParent = NULL) { + $this->_parent = $pParent; + + return $this; + } + + /** + * Get AutoFilter Type + * + * @return string + */ + public function getFilterType() { + return $this->_filterType; + } + + /** + * Set AutoFilter Type + * + * @param string $pFilterType + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER) { + if (!in_array($pFilterType,self::$_filterTypes)) { + throw new PHPExcel_Exception('Invalid filter type for column AutoFilter.'); + } + + $this->_filterType = $pFilterType; + + return $this; + } + + /** + * Get AutoFilter Multiple Rules And/Or Join + * + * @return string + */ + public function getJoin() { + return $this->_join; + } + + /** + * Set AutoFilter Multiple Rules And/Or + * + * @param string $pJoin And/Or + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR) { + // Lowercase And/Or + $pJoin = strtolower($pJoin); + if (!in_array($pJoin,self::$_ruleJoins)) { + throw new PHPExcel_Exception('Invalid rule connection for column AutoFilter.'); + } + + $this->_join = $pJoin; + + return $this; + } + + /** + * Set AutoFilter Attributes + * + * @param string[] $pAttributes + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setAttributes($pAttributes = array()) { + $this->_attributes = $pAttributes; + + return $this; + } + + /** + * Set An AutoFilter Attribute + * + * @param string $pName Attribute Name + * @param string $pValue Attribute Value + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setAttribute($pName, $pValue) { + $this->_attributes[$pName] = $pValue; + + return $this; + } + + /** + * Get AutoFilter Column Attributes + * + * @return string + */ + public function getAttributes() { + return $this->_attributes; + } + + /** + * Get specific AutoFilter Column Attribute + * + * @param string $pName Attribute Name + * @return string + */ + public function getAttribute($pName) { + if (isset($this->_attributes[$pName])) + return $this->_attributes[$pName]; + return NULL; + } + + /** + * Get all AutoFilter Column Rules + * + * @throws PHPExcel_Exception + * @return array of PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function getRules() { + return $this->_ruleset; + } + + /** + * Get a specified AutoFilter Column Rule + * + * @param integer $pIndex Rule index in the ruleset array + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function getRule($pIndex) { + if (!isset($this->_ruleset[$pIndex])) { + $this->_ruleset[$pIndex] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this); + } + return $this->_ruleset[$pIndex]; + } + + /** + * Create a new AutoFilter Column Rule in the ruleset + * + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function createRule() { + $this->_ruleset[] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this); + + return end($this->_ruleset); + } + + /** + * Add a new AutoFilter Column Rule to the ruleset + * + * @param PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule + * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned + * @return PHPExcel_Worksheet_AutoFilter_Column|PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function addRule(PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule, $returnRule=TRUE) { + $pRule->setParent($this); + $this->_ruleset[] = $pRule; + + return ($returnRule) ? $pRule : $this; + } + + /** + * Delete a specified AutoFilter Column Rule + * If the number of rules is reduced to 1, then we reset And/Or logic to Or + * + * @param integer $pIndex Rule index in the ruleset array + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function deleteRule($pIndex) { + if (isset($this->_ruleset[$pIndex])) { + unset($this->_ruleset[$pIndex]); + // If we've just deleted down to a single rule, then reset And/Or joining to Or + if (count($this->_ruleset) <= 1) { + $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); + } + } + + return $this; + } + + /** + * Delete all AutoFilter Column Rules + * + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function clearRules() { + $this->_ruleset = array(); + $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == '_parent') { + // Detach from autofilter parent + $this->$key = NULL; + } else { + $this->$key = clone $value; + } + } elseif ((is_array($value)) && ($key == '_ruleset')) { + // The columns array of PHPExcel_Worksheet_AutoFilter objects + $this->$key = array(); + foreach ($value as $k => $v) { + $this->$key[$k] = clone $v; + // attach the new cloned Rule to this new cloned Autofilter Cloned object + $this->$key[$k]->setParent($this); + } + } else { + $this->$key = $value; + } + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php new file mode 100644 index 00000000..ae33683f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php @@ -0,0 +1,464 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_AutoFilter_Column_Rule + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_AutoFilter_Column_Rule +{ + const AUTOFILTER_RULETYPE_FILTER = 'filter'; + const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; + const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; + const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; + const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; + + private static $_ruleTypes = array( + // Currently we're not handling + // colorFilter + // extLst + // iconFilter + self::AUTOFILTER_RULETYPE_FILTER, + self::AUTOFILTER_RULETYPE_DATEGROUP, + self::AUTOFILTER_RULETYPE_CUSTOMFILTER, + self::AUTOFILTER_RULETYPE_DYNAMICFILTER, + self::AUTOFILTER_RULETYPE_TOPTENFILTER, + ); + + const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; + const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; + const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; + const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; + const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; + const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; + + private static $_dateTimeGroups = array( + self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, + self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, + self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, + self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, + self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, + self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, + ); + + const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; + const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; + const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; + const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; + const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; + const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; + const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; + const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; + const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; + const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; + const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; + const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; + const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; + const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; + const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; + const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; + const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; + const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; + + private static $_dynamicTypes = array( + self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, + self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, + self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, + self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, + self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, + self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, + ); + + /* + * The only valid filter rule operators for filter and customFilter types are: + * <xsd:enumeration value="equal"/> + * <xsd:enumeration value="lessThan"/> + * <xsd:enumeration value="lessThanOrEqual"/> + * <xsd:enumeration value="notEqual"/> + * <xsd:enumeration value="greaterThanOrEqual"/> + * <xsd:enumeration value="greaterThan"/> + */ + const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; + const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; + const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; + const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; + const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; + + private static $_operators = array( + self::AUTOFILTER_COLUMN_RULE_EQUAL, + self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, + self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, + self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, + self::AUTOFILTER_COLUMN_RULE_LESSTHAN, + self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, + ); + + const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; + + private static $_topTenValue = array( + self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, + self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, + ); + + const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; + + private static $_topTenType = array( + self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, + self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, + ); + + + /* Rule Operators (Numeric, Boolean etc) */ +// const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 + /* Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values */ +// const AUTOFILTER_COLUMN_RULE_TOPTEN = 'topTen'; // greaterThan calculated value +// const AUTOFILTER_COLUMN_RULE_TOPTENPERCENT = 'topTenPercent'; // greaterThan calculated value +// const AUTOFILTER_COLUMN_RULE_ABOVEAVERAGE = 'aboveAverage'; // Value is calculated as the average +// const AUTOFILTER_COLUMN_RULE_BELOWAVERAGE = 'belowAverage'; // Value is calculated as the average + /* Rule Operators (String) which are set as wild-carded values */ +// const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* +// const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z +// const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* +// const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* + /* Rule Operators (Date Special) which are translated to standard numeric operators with calculated values */ +// const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; +// const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; +// const AUTOFILTER_COLUMN_RULE_YESTERDAY = 'yesterday'; +// const AUTOFILTER_COLUMN_RULE_TODAY = 'today'; +// const AUTOFILTER_COLUMN_RULE_TOMORROW = 'tomorrow'; +// const AUTOFILTER_COLUMN_RULE_LASTWEEK = 'lastWeek'; +// const AUTOFILTER_COLUMN_RULE_THISWEEK = 'thisWeek'; +// const AUTOFILTER_COLUMN_RULE_NEXTWEEK = 'nextWeek'; +// const AUTOFILTER_COLUMN_RULE_LASTMONTH = 'lastMonth'; +// const AUTOFILTER_COLUMN_RULE_THISMONTH = 'thisMonth'; +// const AUTOFILTER_COLUMN_RULE_NEXTMONTH = 'nextMonth'; +// const AUTOFILTER_COLUMN_RULE_LASTQUARTER = 'lastQuarter'; +// const AUTOFILTER_COLUMN_RULE_THISQUARTER = 'thisQuarter'; +// const AUTOFILTER_COLUMN_RULE_NEXTQUARTER = 'nextQuarter'; +// const AUTOFILTER_COLUMN_RULE_LASTYEAR = 'lastYear'; +// const AUTOFILTER_COLUMN_RULE_THISYEAR = 'thisYear'; +// const AUTOFILTER_COLUMN_RULE_NEXTYEAR = 'nextYear'; +// const AUTOFILTER_COLUMN_RULE_YEARTODATE = 'yearToDate'; // <dynamicFilter val="40909" type="yearToDate" maxVal="41113"/> +// const AUTOFILTER_COLUMN_RULE_ALLDATESINMONTH = 'allDatesInMonth'; // <dynamicFilter type="M2"/> for Month/February +// const AUTOFILTER_COLUMN_RULE_ALLDATESINQUARTER = 'allDatesInQuarter'; // <dynamicFilter type="Q2"/> for Quarter 2 + + /** + * Autofilter Column + * + * @var PHPExcel_Worksheet_AutoFilter_Column + */ + private $_parent = NULL; + + + /** + * Autofilter Rule Type + * + * @var string + */ + private $_ruleType = self::AUTOFILTER_RULETYPE_FILTER; + + + /** + * Autofilter Rule Value + * + * @var string + */ + private $_value = ''; + + /** + * Autofilter Rule Operator + * + * @var string + */ + private $_operator = ''; + + /** + * DateTimeGrouping Group Value + * + * @var string + */ + private $_grouping = ''; + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter_Column_Rule + * + * @param PHPExcel_Worksheet_AutoFilter_Column $pParent + */ + public function __construct(PHPExcel_Worksheet_AutoFilter_Column $pParent = NULL) + { + $this->_parent = $pParent; + } + + /** + * Get AutoFilter Rule Type + * + * @return string + */ + public function getRuleType() { + return $this->_ruleType; + } + + /** + * Set AutoFilter Rule Type + * + * @param string $pRuleType + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setRuleType($pRuleType = self::AUTOFILTER_RULETYPE_FILTER) { + if (!in_array($pRuleType,self::$_ruleTypes)) { + throw new PHPExcel_Exception('Invalid rule type for column AutoFilter Rule.'); + } + + $this->_ruleType = $pRuleType; + + return $this; + } + + /** + * Get AutoFilter Rule Value + * + * @return string + */ + public function getValue() { + return $this->_value; + } + + /** + * Set AutoFilter Rule Value + * + * @param string|string[] $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setValue($pValue = '') { + if (is_array($pValue)) { + $grouping = -1; + foreach($pValue as $key => $value) { + // Validate array entries + if (!in_array($key,self::$_dateTimeGroups)) { + // Remove any invalid entries from the value array + unset($pValue[$key]); + } else { + // Work out what the dateTime grouping will be + $grouping = max($grouping,array_search($key,self::$_dateTimeGroups)); + } + } + if (count($pValue) == 0) { + throw new PHPExcel_Exception('Invalid rule value for column AutoFilter Rule.'); + } + // Set the dateTime grouping that we've anticipated + $this->setGrouping(self::$_dateTimeGroups[$grouping]); + } + $this->_value = $pValue; + + return $this; + } + + /** + * Get AutoFilter Rule Operator + * + * @return string + */ + public function getOperator() { + return $this->_operator; + } + + /** + * Set AutoFilter Rule Operator + * + * @param string $pOperator + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setOperator($pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL) { + if (empty($pOperator)) + $pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL; + if ((!in_array($pOperator,self::$_operators)) && + (!in_array($pOperator,self::$_topTenValue))) { + throw new PHPExcel_Exception('Invalid operator for column AutoFilter Rule.'); + } + $this->_operator = $pOperator; + + return $this; + } + + /** + * Get AutoFilter Rule Grouping + * + * @return string + */ + public function getGrouping() { + return $this->_grouping; + } + + /** + * Set AutoFilter Rule Grouping + * + * @param string $pGrouping + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setGrouping($pGrouping = NULL) { + if (($pGrouping !== NULL) && + (!in_array($pGrouping,self::$_dateTimeGroups)) && + (!in_array($pGrouping,self::$_dynamicTypes)) && + (!in_array($pGrouping,self::$_topTenType))) { + throw new PHPExcel_Exception('Invalid rule type for column AutoFilter Rule.'); + } + + $this->_grouping = $pGrouping; + + return $this; + } + + /** + * Set AutoFilter Rule + * + * @param string $pOperator + * @param string|string[] $pValue + * @param string $pGrouping + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setRule($pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL, $pValue = '', $pGrouping = NULL) { + $this->setOperator($pOperator); + $this->setValue($pValue); + // Only set grouping if it's been passed in as a user-supplied argument, + // otherwise we're calculating it when we setValue() and don't want to overwrite that + // If the user supplies an argumnet for grouping, then on their own head be it + if ($pGrouping !== NULL) + $this->setGrouping($pGrouping); + + return $this; + } + + /** + * Get this Rule's AutoFilter Column Parent + * + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getParent() { + return $this->_parent; + } + + /** + * Set this Rule's AutoFilter Column Parent + * + * @param PHPExcel_Worksheet_AutoFilter_Column + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setParent(PHPExcel_Worksheet_AutoFilter_Column $pParent = NULL) { + $this->_parent = $pParent; + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == '_parent') { + // Detach from autofilter column parent + $this->$key = NULL; + } else { + $this->$key = clone $value; + } + } else { + $this->$key = $value; + } + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php new file mode 100644 index 00000000..4db0f882 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php @@ -0,0 +1,485 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_BaseDrawing + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /** + * Image counter + * + * @var int + */ + private static $_imageCounter = 0; + + /** + * Image index + * + * @var int + */ + private $_imageIndex = 0; + + /** + * Name + * + * @var string + */ + protected $_name; + + /** + * Description + * + * @var string + */ + protected $_description; + + /** + * Worksheet + * + * @var PHPExcel_Worksheet + */ + protected $_worksheet; + + /** + * Coordinates + * + * @var string + */ + protected $_coordinates; + + /** + * Offset X + * + * @var int + */ + protected $_offsetX; + + /** + * Offset Y + * + * @var int + */ + protected $_offsetY; + + /** + * Width + * + * @var int + */ + protected $_width; + + /** + * Height + * + * @var int + */ + protected $_height; + + /** + * Proportional resize + * + * @var boolean + */ + protected $_resizeProportional; + + /** + * Rotation + * + * @var int + */ + protected $_rotation; + + /** + * Shadow + * + * @var PHPExcel_Worksheet_Drawing_Shadow + */ + protected $_shadow; + + /** + * Create a new PHPExcel_Worksheet_BaseDrawing + */ + public function __construct() + { + // Initialise values + $this->_name = ''; + $this->_description = ''; + $this->_worksheet = null; + $this->_coordinates = 'A1'; + $this->_offsetX = 0; + $this->_offsetY = 0; + $this->_width = 0; + $this->_height = 0; + $this->_resizeProportional = true; + $this->_rotation = 0; + $this->_shadow = new PHPExcel_Worksheet_Drawing_Shadow(); + + // Set image index + self::$_imageCounter++; + $this->_imageIndex = self::$_imageCounter; + } + + /** + * Get image index + * + * @return int + */ + public function getImageIndex() { + return $this->_imageIndex; + } + + /** + * Get Name + * + * @return string + */ + public function getName() { + return $this->_name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setName($pValue = '') { + $this->_name = $pValue; + return $this; + } + + /** + * Get Description + * + * @return string + */ + public function getDescription() { + return $this->_description; + } + + /** + * Set Description + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setDescription($pValue = '') { + $this->_description = $pValue; + return $this; + } + + /** + * Get Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() { + return $this->_worksheet; + } + + /** + * Set Worksheet + * + * @param PHPExcel_Worksheet $pValue + * @param bool $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWorksheet(PHPExcel_Worksheet $pValue = null, $pOverrideOld = false) { + if (is_null($this->_worksheet)) { + // Add drawing to PHPExcel_Worksheet + $this->_worksheet = $pValue; + $this->_worksheet->getCell($this->_coordinates); + $this->_worksheet->getDrawingCollection()->append($this); + } else { + if ($pOverrideOld) { + // Remove drawing from old PHPExcel_Worksheet + $iterator = $this->_worksheet->getDrawingCollection()->getIterator(); + + while ($iterator->valid()) { + if ($iterator->current()->getHashCode() == $this->getHashCode()) { + $this->_worksheet->getDrawingCollection()->offsetUnset( $iterator->key() ); + $this->_worksheet = null; + break; + } + } + + // Set new PHPExcel_Worksheet + $this->setWorksheet($pValue); + } else { + throw new PHPExcel_Exception("A PHPExcel_Worksheet has already been assigned. Drawings can only exist on one PHPExcel_Worksheet."); + } + } + return $this; + } + + /** + * Get Coordinates + * + * @return string + */ + public function getCoordinates() { + return $this->_coordinates; + } + + /** + * Set Coordinates + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setCoordinates($pValue = 'A1') { + $this->_coordinates = $pValue; + return $this; + } + + /** + * Get OffsetX + * + * @return int + */ + public function getOffsetX() { + return $this->_offsetX; + } + + /** + * Set OffsetX + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setOffsetX($pValue = 0) { + $this->_offsetX = $pValue; + return $this; + } + + /** + * Get OffsetY + * + * @return int + */ + public function getOffsetY() { + return $this->_offsetY; + } + + /** + * Set OffsetY + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setOffsetY($pValue = 0) { + $this->_offsetY = $pValue; + return $this; + } + + /** + * Get Width + * + * @return int + */ + public function getWidth() { + return $this->_width; + } + + /** + * Set Width + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWidth($pValue = 0) { + // Resize proportional? + if ($this->_resizeProportional && $pValue != 0) { + $ratio = $this->_height / $this->_width; + $this->_height = round($ratio * $pValue); + } + + // Set width + $this->_width = $pValue; + + return $this; + } + + /** + * Get Height + * + * @return int + */ + public function getHeight() { + return $this->_height; + } + + /** + * Set Height + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setHeight($pValue = 0) { + // Resize proportional? + if ($this->_resizeProportional && $pValue != 0) { + $ratio = $this->_width / $this->_height; + $this->_width = round($ratio * $pValue); + } + + // Set height + $this->_height = $pValue; + + return $this; + } + + /** + * Set width and height with proportional resize + * Example: + * <code> + * $objDrawing->setResizeProportional(true); + * $objDrawing->setWidthAndHeight(160,120); + * </code> + * + * @author Vincent@luo MSN:kele_100@hotmail.com + * @param int $width + * @param int $height + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWidthAndHeight($width = 0, $height = 0) { + $xratio = $width / $this->_width; + $yratio = $height / $this->_height; + if ($this->_resizeProportional && !($width == 0 || $height == 0)) { + if (($xratio * $this->_height) < $height) { + $this->_height = ceil($xratio * $this->_height); + $this->_width = $width; + } else { + $this->_width = ceil($yratio * $this->_width); + $this->_height = $height; + } + } + return $this; + } + + /** + * Get ResizeProportional + * + * @return boolean + */ + public function getResizeProportional() { + return $this->_resizeProportional; + } + + /** + * Set ResizeProportional + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setResizeProportional($pValue = true) { + $this->_resizeProportional = $pValue; + return $this; + } + + /** + * Get Rotation + * + * @return int + */ + public function getRotation() { + return $this->_rotation; + } + + /** + * Set Rotation + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setRotation($pValue = 0) { + $this->_rotation = $pValue; + return $this; + } + + /** + * Get Shadow + * + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function getShadow() { + return $this->_shadow; + } + + /** + * Set Shadow + * + * @param PHPExcel_Worksheet_Drawing_Shadow $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setShadow(PHPExcel_Worksheet_Drawing_Shadow $pValue = null) { + $this->_shadow = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_name + . $this->_description + . $this->_worksheet->getHashCode() + . $this->_coordinates + . $this->_offsetX + . $this->_offsetY + . $this->_width + . $this->_height + . $this->_rotation + . $this->_shadow->getHashCode() + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php new file mode 100644 index 00000000..4b968167 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php @@ -0,0 +1,161 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_CellIterator + * + * Used to iterate rows in a PHPExcel_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_CellIterator implements Iterator +{ + /** + * PHPExcel_Worksheet to iterate + * + * @var PHPExcel_Worksheet + */ + private $_subject; + + /** + * Row index + * + * @var int + */ + private $_rowIndex; + + /** + * Current iterator position + * + * @var int + */ + private $_position = 0; + + /** + * Loop only existing cells + * + * @var boolean + */ + private $_onlyExistingCells = true; + + /** + * Create a new cell iterator + * + * @param PHPExcel_Worksheet $subject + * @param int $rowIndex + */ + public function __construct(PHPExcel_Worksheet $subject = null, $rowIndex = 1) { + // Set subject and row index + $this->_subject = $subject; + $this->_rowIndex = $rowIndex; + } + + /** + * Destructor + */ + public function __destruct() { + unset($this->_subject); + } + + /** + * Rewind iterator + */ + public function rewind() { + $this->_position = 0; + } + + /** + * Current PHPExcel_Cell + * + * @return PHPExcel_Cell + */ + public function current() { + return $this->_subject->getCellByColumnAndRow($this->_position, $this->_rowIndex); + } + + /** + * Current key + * + * @return int + */ + public function key() { + return $this->_position; + } + + /** + * Next value + */ + public function next() { + ++$this->_position; + } + + /** + * Are there any more PHPExcel_Cell instances available? + * + * @return boolean + */ + public function valid() { + // columnIndexFromString() returns an index based at one, + // treat it as a count when comparing it to the base zero + // position. + $columnCount = PHPExcel_Cell::columnIndexFromString($this->_subject->getHighestColumn()); + + if ($this->_onlyExistingCells) { + // If we aren't looking at an existing cell, either + // because the first column doesn't exist or next() has + // been called onto a nonexistent cell, then loop until we + // find one, or pass the last column. + while ($this->_position < $columnCount && + !$this->_subject->cellExistsByColumnAndRow($this->_position, $this->_rowIndex)) { + ++$this->_position; + } + } + + return $this->_position < $columnCount; + } + + /** + * Get loop only existing cells + * + * @return boolean + */ + public function getIterateOnlyExistingCells() { + return $this->_onlyExistingCells; + } + + /** + * Set the iterator to loop only existing cells + * + * @param boolean $value + */ + public function setIterateOnlyExistingCells($value = true) { + $this->_onlyExistingCells = $value; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php new file mode 100644 index 00000000..79db1c58 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php @@ -0,0 +1,266 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_ColumnDimension + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_ColumnDimension +{ + /** + * Column index + * + * @var int + */ + private $_columnIndex; + + /** + * Column width + * + * When this is set to a negative value, the column width should be ignored by IWriter + * + * @var double + */ + private $_width = -1; + + /** + * Auto size? + * + * @var bool + */ + private $_autoSize = false; + + /** + * Visible? + * + * @var bool + */ + private $_visible = true; + + /** + * Outline level + * + * @var int + */ + private $_outlineLevel = 0; + + /** + * Collapsed + * + * @var bool + */ + private $_collapsed = false; + + /** + * Index to cellXf + * + * @var int + */ + private $_xfIndex; + + /** + * Create a new PHPExcel_Worksheet_ColumnDimension + * + * @param string $pIndex Character column index + */ + public function __construct($pIndex = 'A') + { + // Initialise values + $this->_columnIndex = $pIndex; + + // set default index to cellXf + $this->_xfIndex = 0; + } + + /** + * Get ColumnIndex + * + * @return string + */ + public function getColumnIndex() { + return $this->_columnIndex; + } + + /** + * Set ColumnIndex + * + * @param string $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setColumnIndex($pValue) { + $this->_columnIndex = $pValue; + return $this; + } + + /** + * Get Width + * + * @return double + */ + public function getWidth() { + return $this->_width; + } + + /** + * Set Width + * + * @param double $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setWidth($pValue = -1) { + $this->_width = $pValue; + return $this; + } + + /** + * Get Auto Size + * + * @return bool + */ + public function getAutoSize() { + return $this->_autoSize; + } + + /** + * Set Auto Size + * + * @param bool $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setAutoSize($pValue = false) { + $this->_autoSize = $pValue; + return $this; + } + + /** + * Get Visible + * + * @return bool + */ + public function getVisible() { + return $this->_visible; + } + + /** + * Set Visible + * + * @param bool $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setVisible($pValue = true) { + $this->_visible = $pValue; + return $this; + } + + /** + * Get Outline Level + * + * @return int + */ + public function getOutlineLevel() { + return $this->_outlineLevel; + } + + /** + * Set Outline Level + * + * Value must be between 0 and 7 + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setOutlineLevel($pValue) { + if ($pValue < 0 || $pValue > 7) { + throw new PHPExcel_Exception("Outline level must range between 0 and 7."); + } + + $this->_outlineLevel = $pValue; + return $this; + } + + /** + * Get Collapsed + * + * @return bool + */ + public function getCollapsed() { + return $this->_collapsed; + } + + /** + * Set Collapsed + * + * @param bool $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setCollapsed($pValue = true) { + $this->_collapsed = $pValue; + return $this; + } + + /** + * Get index to cellXf + * + * @return int + */ + public function getXfIndex() + { + return $this->_xfIndex; + } + + /** + * Set index to cellXf + * + * @param int $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setXfIndex($pValue = 0) + { + $this->_xfIndex = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php new file mode 100644 index 00000000..56f0cfde --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php @@ -0,0 +1,148 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_Drawing + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /** + * Path + * + * @var string + */ + private $_path; + + /** + * Create a new PHPExcel_Worksheet_Drawing + */ + public function __construct() + { + // Initialise values + $this->_path = ''; + + // Initialize parent + parent::__construct(); + } + + /** + * Get Filename + * + * @return string + */ + public function getFilename() { + return basename($this->_path); + } + + /** + * Get indexed filename (using image index) + * + * @return string + */ + public function getIndexedFilename() { + $fileName = $this->getFilename(); + $fileName = str_replace(' ', '_', $fileName); + return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); + } + + /** + * Get Extension + * + * @return string + */ + public function getExtension() { + $exploded = explode(".", basename($this->_path)); + return $exploded[count($exploded) - 1]; + } + + /** + * Get Path + * + * @return string + */ + public function getPath() { + return $this->_path; + } + + /** + * Set Path + * + * @param string $pValue File path + * @param boolean $pVerifyFile Verify file + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_Drawing + */ + public function setPath($pValue = '', $pVerifyFile = true) { + if ($pVerifyFile) { + if (file_exists($pValue)) { + $this->_path = $pValue; + + if ($this->_width == 0 && $this->_height == 0) { + // Get width/height + list($this->_width, $this->_height) = getimagesize($pValue); + } + } else { + throw new PHPExcel_Exception("File $pValue not found!"); + } + } else { + $this->_path = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_path + . parent::getHashCode() + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php new file mode 100644 index 00000000..5df44896 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php @@ -0,0 +1,288 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_Drawing_Shadow + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable +{ + /* Shadow alignment */ + const SHADOW_BOTTOM = 'b'; + const SHADOW_BOTTOM_LEFT = 'bl'; + const SHADOW_BOTTOM_RIGHT = 'br'; + const SHADOW_CENTER = 'ctr'; + const SHADOW_LEFT = 'l'; + const SHADOW_TOP = 't'; + const SHADOW_TOP_LEFT = 'tl'; + const SHADOW_TOP_RIGHT = 'tr'; + + /** + * Visible + * + * @var boolean + */ + private $_visible; + + /** + * Blur radius + * + * Defaults to 6 + * + * @var int + */ + private $_blurRadius; + + /** + * Shadow distance + * + * Defaults to 2 + * + * @var int + */ + private $_distance; + + /** + * Shadow direction (in degrees) + * + * @var int + */ + private $_direction; + + /** + * Shadow alignment + * + * @var int + */ + private $_alignment; + + /** + * Color + * + * @var PHPExcel_Style_Color + */ + private $_color; + + /** + * Alpha + * + * @var int + */ + private $_alpha; + + /** + * Create a new PHPExcel_Worksheet_Drawing_Shadow + */ + public function __construct() + { + // Initialise values + $this->_visible = false; + $this->_blurRadius = 6; + $this->_distance = 2; + $this->_direction = 0; + $this->_alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT; + $this->_color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK); + $this->_alpha = 50; + } + + /** + * Get Visible + * + * @return boolean + */ + public function getVisible() { + return $this->_visible; + } + + /** + * Set Visible + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setVisible($pValue = false) { + $this->_visible = $pValue; + return $this; + } + + /** + * Get Blur radius + * + * @return int + */ + public function getBlurRadius() { + return $this->_blurRadius; + } + + /** + * Set Blur radius + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setBlurRadius($pValue = 6) { + $this->_blurRadius = $pValue; + return $this; + } + + /** + * Get Shadow distance + * + * @return int + */ + public function getDistance() { + return $this->_distance; + } + + /** + * Set Shadow distance + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setDistance($pValue = 2) { + $this->_distance = $pValue; + return $this; + } + + /** + * Get Shadow direction (in degrees) + * + * @return int + */ + public function getDirection() { + return $this->_direction; + } + + /** + * Set Shadow direction (in degrees) + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setDirection($pValue = 0) { + $this->_direction = $pValue; + return $this; + } + + /** + * Get Shadow alignment + * + * @return int + */ + public function getAlignment() { + return $this->_alignment; + } + + /** + * Set Shadow alignment + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setAlignment($pValue = 0) { + $this->_alignment = $pValue; + return $this; + } + + /** + * Get Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() { + return $this->_color; + } + + /** + * Set Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setColor(PHPExcel_Style_Color $pValue = null) { + $this->_color = $pValue; + return $this; + } + + /** + * Get Alpha + * + * @return int + */ + public function getAlpha() { + return $this->_alpha; + } + + /** + * Set Alpha + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setAlpha($pValue = 0) { + $this->_alpha = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + ($this->_visible ? 't' : 'f') + . $this->_blurRadius + . $this->_distance + . $this->_direction + . $this->_alignment + . $this->_color->getHashCode() + . $this->_alpha + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php new file mode 100644 index 00000000..82d7faf6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php @@ -0,0 +1,465 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_HeaderFooter + * + * <code> + * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970: + * + * There are a number of formatting codes that can be written inline with the actual header / footer text, which + * affect the formatting in the header or footer. + * + * Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on + * the second line (center section). + * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D + * + * General Rules: + * There is no required order in which these codes must appear. + * + * The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: + * - strikethrough + * - superscript + * - subscript + * Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, + * while the first is ON. + * &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When + * two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the + * order of appearance, and placed into the left section. + * &P - code for "current page #" + * &N - code for "total pages" + * &font size - code for "text font size", where font size is a font size in points. + * &K - code for "text font color" + * RGB Color is specified as RRGGBB + * Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade + * value, NN is the tint/shade value. + * &S - code for "text strikethrough" on / off + * &X - code for "text super script" on / off + * &Y - code for "text subscript" on / off + * &C - code for "center section". When two or more occurrences of this section marker exist, the contents + * from all markers are concatenated, in the order of appearance, and placed into the center section. + * + * &D - code for "date" + * &T - code for "time" + * &G - code for "picture as background" + * &U - code for "text single underline" + * &E - code for "double underline" + * &R - code for "right section". When two or more occurrences of this section marker exist, the contents + * from all markers are concatenated, in the order of appearance, and placed into the right section. + * &Z - code for "this workbook's file path" + * &F - code for "this workbook's file name" + * &A - code for "sheet tab name" + * &+ - code for add to page #. + * &- - code for subtract from page #. + * &"font name,font type" - code for "text font name" and "text font type", where font name and font type + * are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font + * name, it means "none specified". Both of font name and font type can be localized values. + * &"-,Bold" - code for "bold font style" + * &B - also means "bold font style". + * &"-,Regular" - code for "regular font style" + * &"-,Italic" - code for "italic font style" + * &I - also means "italic font style" + * &"-,Bold Italic" code for "bold italic font style" + * &O - code for "outline style" + * &H - code for "shadow style" + * </code> + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_HeaderFooter +{ + /* Header/footer image location */ + const IMAGE_HEADER_LEFT = 'LH'; + const IMAGE_HEADER_CENTER = 'CH'; + const IMAGE_HEADER_RIGHT = 'RH'; + const IMAGE_FOOTER_LEFT = 'LF'; + const IMAGE_FOOTER_CENTER = 'CF'; + const IMAGE_FOOTER_RIGHT = 'RF'; + + /** + * OddHeader + * + * @var string + */ + private $_oddHeader = ''; + + /** + * OddFooter + * + * @var string + */ + private $_oddFooter = ''; + + /** + * EvenHeader + * + * @var string + */ + private $_evenHeader = ''; + + /** + * EvenFooter + * + * @var string + */ + private $_evenFooter = ''; + + /** + * FirstHeader + * + * @var string + */ + private $_firstHeader = ''; + + /** + * FirstFooter + * + * @var string + */ + private $_firstFooter = ''; + + /** + * Different header for Odd/Even, defaults to false + * + * @var boolean + */ + private $_differentOddEven = false; + + /** + * Different header for first page, defaults to false + * + * @var boolean + */ + private $_differentFirst = false; + + /** + * Scale with document, defaults to true + * + * @var boolean + */ + private $_scaleWithDocument = true; + + /** + * Align with margins, defaults to true + * + * @var boolean + */ + private $_alignWithMargins = true; + + /** + * Header/footer images + * + * @var PHPExcel_Worksheet_HeaderFooterDrawing[] + */ + private $_headerFooterImages = array(); + + /** + * Create a new PHPExcel_Worksheet_HeaderFooter + */ + public function __construct() + { + } + + /** + * Get OddHeader + * + * @return string + */ + public function getOddHeader() { + return $this->_oddHeader; + } + + /** + * Set OddHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setOddHeader($pValue) { + $this->_oddHeader = $pValue; + return $this; + } + + /** + * Get OddFooter + * + * @return string + */ + public function getOddFooter() { + return $this->_oddFooter; + } + + /** + * Set OddFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setOddFooter($pValue) { + $this->_oddFooter = $pValue; + return $this; + } + + /** + * Get EvenHeader + * + * @return string + */ + public function getEvenHeader() { + return $this->_evenHeader; + } + + /** + * Set EvenHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setEvenHeader($pValue) { + $this->_evenHeader = $pValue; + return $this; + } + + /** + * Get EvenFooter + * + * @return string + */ + public function getEvenFooter() { + return $this->_evenFooter; + } + + /** + * Set EvenFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setEvenFooter($pValue) { + $this->_evenFooter = $pValue; + return $this; + } + + /** + * Get FirstHeader + * + * @return string + */ + public function getFirstHeader() { + return $this->_firstHeader; + } + + /** + * Set FirstHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstHeader($pValue) { + $this->_firstHeader = $pValue; + return $this; + } + + /** + * Get FirstFooter + * + * @return string + */ + public function getFirstFooter() { + return $this->_firstFooter; + } + + /** + * Set FirstFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstFooter($pValue) { + $this->_firstFooter = $pValue; + return $this; + } + + /** + * Get DifferentOddEven + * + * @return boolean + */ + public function getDifferentOddEven() { + return $this->_differentOddEven; + } + + /** + * Set DifferentOddEven + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setDifferentOddEven($pValue = false) { + $this->_differentOddEven = $pValue; + return $this; + } + + /** + * Get DifferentFirst + * + * @return boolean + */ + public function getDifferentFirst() { + return $this->_differentFirst; + } + + /** + * Set DifferentFirst + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setDifferentFirst($pValue = false) { + $this->_differentFirst = $pValue; + return $this; + } + + /** + * Get ScaleWithDocument + * + * @return boolean + */ + public function getScaleWithDocument() { + return $this->_scaleWithDocument; + } + + /** + * Set ScaleWithDocument + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setScaleWithDocument($pValue = true) { + $this->_scaleWithDocument = $pValue; + return $this; + } + + /** + * Get AlignWithMargins + * + * @return boolean + */ + public function getAlignWithMargins() { + return $this->_alignWithMargins; + } + + /** + * Set AlignWithMargins + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setAlignWithMargins($pValue = true) { + $this->_alignWithMargins = $pValue; + return $this; + } + + /** + * Add header/footer image + * + * @param PHPExcel_Worksheet_HeaderFooterDrawing $image + * @param string $location + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) { + $this->_headerFooterImages[$location] = $image; + return $this; + } + + /** + * Remove header/footer image + * + * @param string $location + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function removeImage($location = self::IMAGE_HEADER_LEFT) { + if (isset($this->_headerFooterImages[$location])) { + unset($this->_headerFooterImages[$location]); + } + return $this; + } + + /** + * Set header/footer images + * + * @param PHPExcel_Worksheet_HeaderFooterDrawing[] $images + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setImages($images) { + if (!is_array($images)) { + throw new PHPExcel_Exception('Invalid parameter!'); + } + + $this->_headerFooterImages = $images; + return $this; + } + + /** + * Get header/footer images + * + * @return PHPExcel_Worksheet_HeaderFooterDrawing[] + */ + public function getImages() { + // Sort array + $images = array(); + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_LEFT])) $images[self::IMAGE_HEADER_LEFT] = $this->_headerFooterImages[self::IMAGE_HEADER_LEFT]; + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_CENTER])) $images[self::IMAGE_HEADER_CENTER] = $this->_headerFooterImages[self::IMAGE_HEADER_CENTER]; + if (isset($this->_headerFooterImages[self::IMAGE_HEADER_RIGHT])) $images[self::IMAGE_HEADER_RIGHT] = $this->_headerFooterImages[self::IMAGE_HEADER_RIGHT]; + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_LEFT])) $images[self::IMAGE_FOOTER_LEFT] = $this->_headerFooterImages[self::IMAGE_FOOTER_LEFT]; + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_CENTER])) $images[self::IMAGE_FOOTER_CENTER] = $this->_headerFooterImages[self::IMAGE_FOOTER_CENTER]; + if (isset($this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT])) $images[self::IMAGE_FOOTER_RIGHT] = $this->_headerFooterImages[self::IMAGE_FOOTER_RIGHT]; + $this->_headerFooterImages = $images; + + return $this->_headerFooterImages; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php new file mode 100644 index 00000000..1c6f4e19 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php @@ -0,0 +1,350 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_HeaderFooterDrawing + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_HeaderFooterDrawing extends PHPExcel_Worksheet_Drawing implements PHPExcel_IComparable +{ + /** + * Path + * + * @var string + */ + private $_path; + + /** + * Name + * + * @var string + */ + protected $_name; + + /** + * Offset X + * + * @var int + */ + protected $_offsetX; + + /** + * Offset Y + * + * @var int + */ + protected $_offsetY; + + /** + * Width + * + * @var int + */ + protected $_width; + + /** + * Height + * + * @var int + */ + protected $_height; + + /** + * Proportional resize + * + * @var boolean + */ + protected $_resizeProportional; + + /** + * Create a new PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function __construct() + { + // Initialise values + $this->_path = ''; + $this->_name = ''; + $this->_offsetX = 0; + $this->_offsetY = 0; + $this->_width = 0; + $this->_height = 0; + $this->_resizeProportional = true; + } + + /** + * Get Name + * + * @return string + */ + public function getName() { + return $this->_name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setName($pValue = '') { + $this->_name = $pValue; + return $this; + } + + /** + * Get OffsetX + * + * @return int + */ + public function getOffsetX() { + return $this->_offsetX; + } + + /** + * Set OffsetX + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setOffsetX($pValue = 0) { + $this->_offsetX = $pValue; + return $this; + } + + /** + * Get OffsetY + * + * @return int + */ + public function getOffsetY() { + return $this->_offsetY; + } + + /** + * Set OffsetY + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setOffsetY($pValue = 0) { + $this->_offsetY = $pValue; + return $this; + } + + /** + * Get Width + * + * @return int + */ + public function getWidth() { + return $this->_width; + } + + /** + * Set Width + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setWidth($pValue = 0) { + // Resize proportional? + if ($this->_resizeProportional && $pValue != 0) { + $ratio = $this->_width / $this->_height; + $this->_height = round($ratio * $pValue); + } + + // Set width + $this->_width = $pValue; + + return $this; + } + + /** + * Get Height + * + * @return int + */ + public function getHeight() { + return $this->_height; + } + + /** + * Set Height + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setHeight($pValue = 0) { + // Resize proportional? + if ($this->_resizeProportional && $pValue != 0) { + $ratio = $this->_width / $this->_height; + $this->_width = round($ratio * $pValue); + } + + // Set height + $this->_height = $pValue; + + return $this; + } + + /** + * Set width and height with proportional resize + * Example: + * <code> + * $objDrawing->setResizeProportional(true); + * $objDrawing->setWidthAndHeight(160,120); + * </code> + * + * @author Vincent@luo MSN:kele_100@hotmail.com + * @param int $width + * @param int $height + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setWidthAndHeight($width = 0, $height = 0) { + $xratio = $width / $this->_width; + $yratio = $height / $this->_height; + if ($this->_resizeProportional && !($width == 0 || $height == 0)) { + if (($xratio * $this->_height) < $height) { + $this->_height = ceil($xratio * $this->_height); + $this->_width = $width; + } else { + $this->_width = ceil($yratio * $this->_width); + $this->_height = $height; + } + } + return $this; + } + + /** + * Get ResizeProportional + * + * @return boolean + */ + public function getResizeProportional() { + return $this->_resizeProportional; + } + + /** + * Set ResizeProportional + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setResizeProportional($pValue = true) { + $this->_resizeProportional = $pValue; + return $this; + } + + /** + * Get Filename + * + * @return string + */ + public function getFilename() { + return basename($this->_path); + } + + /** + * Get Extension + * + * @return string + */ + public function getExtension() { + $parts = explode(".", basename($this->_path)); + return end($parts); + } + + /** + * Get Path + * + * @return string + */ + public function getPath() { + return $this->_path; + } + + /** + * Set Path + * + * @param string $pValue File path + * @param boolean $pVerifyFile Verify file + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setPath($pValue = '', $pVerifyFile = true) { + if ($pVerifyFile) { + if (file_exists($pValue)) { + $this->_path = $pValue; + + if ($this->_width == 0 && $this->_height == 0) { + // Get width/height + list($this->_width, $this->_height) = getimagesize($pValue); + } + } else { + throw new PHPExcel_Exception("File $pValue not found!"); + } + } else { + $this->_path = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_path + . $this->_name + . $this->_offsetX + . $this->_offsetY + . $this->_width + . $this->_height + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php new file mode 100644 index 00000000..93266d21 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php @@ -0,0 +1,200 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_MemoryDrawing + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_MemoryDrawing extends PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /* Rendering functions */ + const RENDERING_DEFAULT = 'imagepng'; + const RENDERING_PNG = 'imagepng'; + const RENDERING_GIF = 'imagegif'; + const RENDERING_JPEG = 'imagejpeg'; + + /* MIME types */ + const MIMETYPE_DEFAULT = 'image/png'; + const MIMETYPE_PNG = 'image/png'; + const MIMETYPE_GIF = 'image/gif'; + const MIMETYPE_JPEG = 'image/jpeg'; + + /** + * Image resource + * + * @var resource + */ + private $_imageResource; + + /** + * Rendering function + * + * @var string + */ + private $_renderingFunction; + + /** + * Mime type + * + * @var string + */ + private $_mimeType; + + /** + * Unique name + * + * @var string + */ + private $_uniqueName; + + /** + * Create a new PHPExcel_Worksheet_MemoryDrawing + */ + public function __construct() + { + // Initialise values + $this->_imageResource = null; + $this->_renderingFunction = self::RENDERING_DEFAULT; + $this->_mimeType = self::MIMETYPE_DEFAULT; + $this->_uniqueName = md5(rand(0, 9999). time() . rand(0, 9999)); + + // Initialize parent + parent::__construct(); + } + + /** + * Get image resource + * + * @return resource + */ + public function getImageResource() { + return $this->_imageResource; + } + + /** + * Set image resource + * + * @param $value resource + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setImageResource($value = null) { + $this->_imageResource = $value; + + if (!is_null($this->_imageResource)) { + // Get width/height + $this->_width = imagesx($this->_imageResource); + $this->_height = imagesy($this->_imageResource); + } + return $this; + } + + /** + * Get rendering function + * + * @return string + */ + public function getRenderingFunction() { + return $this->_renderingFunction; + } + + /** + * Set rendering function + * + * @param string $value + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT) { + $this->_renderingFunction = $value; + return $this; + } + + /** + * Get mime type + * + * @return string + */ + public function getMimeType() { + return $this->_mimeType; + } + + /** + * Set mime type + * + * @param string $value + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT) { + $this->_mimeType = $value; + return $this; + } + + /** + * Get indexed filename (using image index) + * + * @return string + */ + public function getIndexedFilename() { + $extension = strtolower($this->getMimeType()); + $extension = explode('/', $extension); + $extension = $extension[1]; + + return $this->_uniqueName . $this->getImageIndex() . '.' . $extension; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() { + return md5( + $this->_renderingFunction + . $this->_mimeType + . $this->_uniqueName + . parent::getHashCode() + . __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php new file mode 100644 index 00000000..671711ff --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php @@ -0,0 +1,220 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_PageMargins + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_PageMargins +{ + /** + * Left + * + * @var double + */ + private $_left = 0.7; + + /** + * Right + * + * @var double + */ + private $_right = 0.7; + + /** + * Top + * + * @var double + */ + private $_top = 0.75; + + /** + * Bottom + * + * @var double + */ + private $_bottom = 0.75; + + /** + * Header + * + * @var double + */ + private $_header = 0.3; + + /** + * Footer + * + * @var double + */ + private $_footer = 0.3; + + /** + * Create a new PHPExcel_Worksheet_PageMargins + */ + public function __construct() + { + } + + /** + * Get Left + * + * @return double + */ + public function getLeft() { + return $this->_left; + } + + /** + * Set Left + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setLeft($pValue) { + $this->_left = $pValue; + return $this; + } + + /** + * Get Right + * + * @return double + */ + public function getRight() { + return $this->_right; + } + + /** + * Set Right + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setRight($pValue) { + $this->_right = $pValue; + return $this; + } + + /** + * Get Top + * + * @return double + */ + public function getTop() { + return $this->_top; + } + + /** + * Set Top + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setTop($pValue) { + $this->_top = $pValue; + return $this; + } + + /** + * Get Bottom + * + * @return double + */ + public function getBottom() { + return $this->_bottom; + } + + /** + * Set Bottom + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setBottom($pValue) { + $this->_bottom = $pValue; + return $this; + } + + /** + * Get Header + * + * @return double + */ + public function getHeader() { + return $this->_header; + } + + /** + * Set Header + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setHeader($pValue) { + $this->_header = $pValue; + return $this; + } + + /** + * Get Footer + * + * @return double + */ + public function getFooter() { + return $this->_footer; + } + + /** + * Set Footer + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setFooter($pValue) { + $this->_footer = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php new file mode 100644 index 00000000..9512dbe4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php @@ -0,0 +1,798 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_PageSetup + * + * <code> + * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988: + * + * 1 = Letter paper (8.5 in. by 11 in.) + * 2 = Letter small paper (8.5 in. by 11 in.) + * 3 = Tabloid paper (11 in. by 17 in.) + * 4 = Ledger paper (17 in. by 11 in.) + * 5 = Legal paper (8.5 in. by 14 in.) + * 6 = Statement paper (5.5 in. by 8.5 in.) + * 7 = Executive paper (7.25 in. by 10.5 in.) + * 8 = A3 paper (297 mm by 420 mm) + * 9 = A4 paper (210 mm by 297 mm) + * 10 = A4 small paper (210 mm by 297 mm) + * 11 = A5 paper (148 mm by 210 mm) + * 12 = B4 paper (250 mm by 353 mm) + * 13 = B5 paper (176 mm by 250 mm) + * 14 = Folio paper (8.5 in. by 13 in.) + * 15 = Quarto paper (215 mm by 275 mm) + * 16 = Standard paper (10 in. by 14 in.) + * 17 = Standard paper (11 in. by 17 in.) + * 18 = Note paper (8.5 in. by 11 in.) + * 19 = #9 envelope (3.875 in. by 8.875 in.) + * 20 = #10 envelope (4.125 in. by 9.5 in.) + * 21 = #11 envelope (4.5 in. by 10.375 in.) + * 22 = #12 envelope (4.75 in. by 11 in.) + * 23 = #14 envelope (5 in. by 11.5 in.) + * 24 = C paper (17 in. by 22 in.) + * 25 = D paper (22 in. by 34 in.) + * 26 = E paper (34 in. by 44 in.) + * 27 = DL envelope (110 mm by 220 mm) + * 28 = C5 envelope (162 mm by 229 mm) + * 29 = C3 envelope (324 mm by 458 mm) + * 30 = C4 envelope (229 mm by 324 mm) + * 31 = C6 envelope (114 mm by 162 mm) + * 32 = C65 envelope (114 mm by 229 mm) + * 33 = B4 envelope (250 mm by 353 mm) + * 34 = B5 envelope (176 mm by 250 mm) + * 35 = B6 envelope (176 mm by 125 mm) + * 36 = Italy envelope (110 mm by 230 mm) + * 37 = Monarch envelope (3.875 in. by 7.5 in.). + * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) + * 39 = US standard fanfold (14.875 in. by 11 in.) + * 40 = German standard fanfold (8.5 in. by 12 in.) + * 41 = German legal fanfold (8.5 in. by 13 in.) + * 42 = ISO B4 (250 mm by 353 mm) + * 43 = Japanese double postcard (200 mm by 148 mm) + * 44 = Standard paper (9 in. by 11 in.) + * 45 = Standard paper (10 in. by 11 in.) + * 46 = Standard paper (15 in. by 11 in.) + * 47 = Invite envelope (220 mm by 220 mm) + * 50 = Letter extra paper (9.275 in. by 12 in.) + * 51 = Legal extra paper (9.275 in. by 15 in.) + * 52 = Tabloid extra paper (11.69 in. by 18 in.) + * 53 = A4 extra paper (236 mm by 322 mm) + * 54 = Letter transverse paper (8.275 in. by 11 in.) + * 55 = A4 transverse paper (210 mm by 297 mm) + * 56 = Letter extra transverse paper (9.275 in. by 12 in.) + * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) + * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) + * 59 = Letter plus paper (8.5 in. by 12.69 in.) + * 60 = A4 plus paper (210 mm by 330 mm) + * 61 = A5 transverse paper (148 mm by 210 mm) + * 62 = JIS B5 transverse paper (182 mm by 257 mm) + * 63 = A3 extra paper (322 mm by 445 mm) + * 64 = A5 extra paper (174 mm by 235 mm) + * 65 = ISO B5 extra paper (201 mm by 276 mm) + * 66 = A2 paper (420 mm by 594 mm) + * 67 = A3 transverse paper (297 mm by 420 mm) + * 68 = A3 extra transverse paper (322 mm by 445 mm) + * </code> + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_PageSetup +{ + /* Paper size */ + const PAPERSIZE_LETTER = 1; + const PAPERSIZE_LETTER_SMALL = 2; + const PAPERSIZE_TABLOID = 3; + const PAPERSIZE_LEDGER = 4; + const PAPERSIZE_LEGAL = 5; + const PAPERSIZE_STATEMENT = 6; + const PAPERSIZE_EXECUTIVE = 7; + const PAPERSIZE_A3 = 8; + const PAPERSIZE_A4 = 9; + const PAPERSIZE_A4_SMALL = 10; + const PAPERSIZE_A5 = 11; + const PAPERSIZE_B4 = 12; + const PAPERSIZE_B5 = 13; + const PAPERSIZE_FOLIO = 14; + const PAPERSIZE_QUARTO = 15; + const PAPERSIZE_STANDARD_1 = 16; + const PAPERSIZE_STANDARD_2 = 17; + const PAPERSIZE_NOTE = 18; + const PAPERSIZE_NO9_ENVELOPE = 19; + const PAPERSIZE_NO10_ENVELOPE = 20; + const PAPERSIZE_NO11_ENVELOPE = 21; + const PAPERSIZE_NO12_ENVELOPE = 22; + const PAPERSIZE_NO14_ENVELOPE = 23; + const PAPERSIZE_C = 24; + const PAPERSIZE_D = 25; + const PAPERSIZE_E = 26; + const PAPERSIZE_DL_ENVELOPE = 27; + const PAPERSIZE_C5_ENVELOPE = 28; + const PAPERSIZE_C3_ENVELOPE = 29; + const PAPERSIZE_C4_ENVELOPE = 30; + const PAPERSIZE_C6_ENVELOPE = 31; + const PAPERSIZE_C65_ENVELOPE = 32; + const PAPERSIZE_B4_ENVELOPE = 33; + const PAPERSIZE_B5_ENVELOPE = 34; + const PAPERSIZE_B6_ENVELOPE = 35; + const PAPERSIZE_ITALY_ENVELOPE = 36; + const PAPERSIZE_MONARCH_ENVELOPE = 37; + const PAPERSIZE_6_3_4_ENVELOPE = 38; + const PAPERSIZE_US_STANDARD_FANFOLD = 39; + const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; + const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; + const PAPERSIZE_ISO_B4 = 42; + const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; + const PAPERSIZE_STANDARD_PAPER_1 = 44; + const PAPERSIZE_STANDARD_PAPER_2 = 45; + const PAPERSIZE_STANDARD_PAPER_3 = 46; + const PAPERSIZE_INVITE_ENVELOPE = 47; + const PAPERSIZE_LETTER_EXTRA_PAPER = 48; + const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; + const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; + const PAPERSIZE_A4_EXTRA_PAPER = 51; + const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; + const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; + const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; + const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; + const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; + const PAPERSIZE_LETTER_PLUS_PAPER = 57; + const PAPERSIZE_A4_PLUS_PAPER = 58; + const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; + const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; + const PAPERSIZE_A3_EXTRA_PAPER = 61; + const PAPERSIZE_A5_EXTRA_PAPER = 62; + const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; + const PAPERSIZE_A2_PAPER = 64; + const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; + const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; + + /* Page orientation */ + const ORIENTATION_DEFAULT = 'default'; + const ORIENTATION_LANDSCAPE = 'landscape'; + const ORIENTATION_PORTRAIT = 'portrait'; + + /* Print Range Set Method */ + const SETPRINTRANGE_OVERWRITE = 'O'; + const SETPRINTRANGE_INSERT = 'I'; + + + /** + * Paper size + * + * @var int + */ + private $_paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER; + + /** + * Orientation + * + * @var string + */ + private $_orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT; + + /** + * Scale (Print Scale) + * + * Print scaling. Valid values range from 10 to 400 + * This setting is overridden when fitToWidth and/or fitToHeight are in use + * + * @var int? + */ + private $_scale = 100; + + /** + * Fit To Page + * Whether scale or fitToWith / fitToHeight applies + * + * @var boolean + */ + private $_fitToPage = FALSE; + + /** + * Fit To Height + * Number of vertical pages to fit on + * + * @var int? + */ + private $_fitToHeight = 1; + + /** + * Fit To Width + * Number of horizontal pages to fit on + * + * @var int? + */ + private $_fitToWidth = 1; + + /** + * Columns to repeat at left + * + * @var array Containing start column and end column, empty array if option unset + */ + private $_columnsToRepeatAtLeft = array('', ''); + + /** + * Rows to repeat at top + * + * @var array Containing start row number and end row number, empty array if option unset + */ + private $_rowsToRepeatAtTop = array(0, 0); + + /** + * Center page horizontally + * + * @var boolean + */ + private $_horizontalCentered = FALSE; + + /** + * Center page vertically + * + * @var boolean + */ + private $_verticalCentered = FALSE; + + /** + * Print area + * + * @var string + */ + private $_printArea = NULL; + + /** + * First page number + * + * @var int + */ + private $_firstPageNumber = NULL; + + /** + * Create a new PHPExcel_Worksheet_PageSetup + */ + public function __construct() + { + } + + /** + * Get Paper Size + * + * @return int + */ + public function getPaperSize() { + return $this->_paperSize; + } + + /** + * Set Paper Size + * + * @param int $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) { + $this->_paperSize = $pValue; + return $this; + } + + /** + * Get Orientation + * + * @return string + */ + public function getOrientation() { + return $this->_orientation; + } + + /** + * Set Orientation + * + * @param string $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) { + $this->_orientation = $pValue; + return $this; + } + + /** + * Get Scale + * + * @return int? + */ + public function getScale() { + return $this->_scale; + } + + /** + * Set Scale + * + * Print scaling. Valid values range from 10 to 400 + * This setting is overridden when fitToWidth and/or fitToHeight are in use + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setScale($pValue = 100, $pUpdate = true) { + // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, + // but it is apparently still able to handle any scale >= 0, where 0 results in 100 + if (($pValue >= 0) || is_null($pValue)) { + $this->_scale = $pValue; + if ($pUpdate) { + $this->_fitToPage = false; + } + } else { + throw new PHPExcel_Exception("Scale must not be negative"); + } + return $this; + } + + /** + * Get Fit To Page + * + * @return boolean + */ + public function getFitToPage() { + return $this->_fitToPage; + } + + /** + * Set Fit To Page + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToPage($pValue = TRUE) { + $this->_fitToPage = $pValue; + return $this; + } + + /** + * Get Fit To Height + * + * @return int? + */ + public function getFitToHeight() { + return $this->_fitToHeight; + } + + /** + * Set Fit To Height + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToHeight($pValue = 1, $pUpdate = TRUE) { + $this->_fitToHeight = $pValue; + if ($pUpdate) { + $this->_fitToPage = TRUE; + } + return $this; + } + + /** + * Get Fit To Width + * + * @return int? + */ + public function getFitToWidth() { + return $this->_fitToWidth; + } + + /** + * Set Fit To Width + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToWidth($pValue = 1, $pUpdate = TRUE) { + $this->_fitToWidth = $pValue; + if ($pUpdate) { + $this->_fitToPage = TRUE; + } + return $this; + } + + /** + * Is Columns to repeat at left set? + * + * @return boolean + */ + public function isColumnsToRepeatAtLeftSet() { + if (is_array($this->_columnsToRepeatAtLeft)) { + if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') { + return true; + } + } + + return false; + } + + /** + * Get Columns to repeat at left + * + * @return array Containing start column and end column, empty array if option unset + */ + public function getColumnsToRepeatAtLeft() { + return $this->_columnsToRepeatAtLeft; + } + + /** + * Set Columns to repeat at left + * + * @param array $pValue Containing start column and end column, empty array if option unset + * @return PHPExcel_Worksheet_PageSetup + */ + public function setColumnsToRepeatAtLeft($pValue = null) { + if (is_array($pValue)) { + $this->_columnsToRepeatAtLeft = $pValue; + } + return $this; + } + + /** + * Set Columns to repeat at left by start and end + * + * @param string $pStart + * @param string $pEnd + * @return PHPExcel_Worksheet_PageSetup + */ + public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') { + $this->_columnsToRepeatAtLeft = array($pStart, $pEnd); + return $this; + } + + /** + * Is Rows to repeat at top set? + * + * @return boolean + */ + public function isRowsToRepeatAtTopSet() { + if (is_array($this->_rowsToRepeatAtTop)) { + if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) { + return true; + } + } + + return false; + } + + /** + * Get Rows to repeat at top + * + * @return array Containing start column and end column, empty array if option unset + */ + public function getRowsToRepeatAtTop() { + return $this->_rowsToRepeatAtTop; + } + + /** + * Set Rows to repeat at top + * + * @param array $pValue Containing start column and end column, empty array if option unset + * @return PHPExcel_Worksheet_PageSetup + */ + public function setRowsToRepeatAtTop($pValue = null) { + if (is_array($pValue)) { + $this->_rowsToRepeatAtTop = $pValue; + } + return $this; + } + + /** + * Set Rows to repeat at top by start and end + * + * @param int $pStart + * @param int $pEnd + * @return PHPExcel_Worksheet_PageSetup + */ + public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) { + $this->_rowsToRepeatAtTop = array($pStart, $pEnd); + return $this; + } + + /** + * Get center page horizontally + * + * @return bool + */ + public function getHorizontalCentered() { + return $this->_horizontalCentered; + } + + /** + * Set center page horizontally + * + * @param bool $value + * @return PHPExcel_Worksheet_PageSetup + */ + public function setHorizontalCentered($value = false) { + $this->_horizontalCentered = $value; + return $this; + } + + /** + * Get center page vertically + * + * @return bool + */ + public function getVerticalCentered() { + return $this->_verticalCentered; + } + + /** + * Set center page vertically + * + * @param bool $value + * @return PHPExcel_Worksheet_PageSetup + */ + public function setVerticalCentered($value = false) { + $this->_verticalCentered = $value; + return $this; + } + + /** + * Get print area + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string + * Otherwise, the specific range identified by the value of $index will be returned + * Print areas are numbered from 1 + * @throws PHPExcel_Exception + * @return string + */ + public function getPrintArea($index = 0) { + if ($index == 0) { + return $this->_printArea; + } + $printAreas = explode(',',$this->_printArea); + if (isset($printAreas[$index-1])) { + return $printAreas[$index-1]; + } + throw new PHPExcel_Exception("Requested Print Area does not exist"); + } + + /** + * Is print area set? + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or an index value of 0, will identify whether any print range is set + * Otherwise, existence of the range identified by the value of $index will be returned + * Print areas are numbered from 1 + * @return boolean + */ + public function isPrintAreaSet($index = 0) { + if ($index == 0) { + return !is_null($this->_printArea); + } + $printAreas = explode(',',$this->_printArea); + return isset($printAreas[$index-1]); + } + + /** + * Clear a print area + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or an index value of 0, will clear all print ranges that are set + * Otherwise, the range identified by the value of $index will be removed from the series + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + */ + public function clearPrintArea($index = 0) { + if ($index == 0) { + $this->_printArea = NULL; + } else { + $printAreas = explode(',',$this->_printArea); + if (isset($printAreas[$index-1])) { + unset($printAreas[$index-1]); + $this->_printArea = implode(',',$printAreas); + } + } + + return $this; + } + + /** + * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20' + * + * @param string $value + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * When the method is "O"verwrite, then a positive integer index will overwrite that indexed + * entry in the print areas list; a negative index value will identify which entry to + * overwrite working bacward through the print area to the list, with the last entry as -1. + * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. + * When the method is "I"nsert, then a positive index will insert after that indexed entry in + * the print areas list, while a negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @param string $method Determines the method used when setting multiple print areas + * Default behaviour, or the "O" method, overwrites existing print area + * The "I" method, inserts the new print area before any specified index, or at the end of the list + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { + if (strpos($value,'!') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not specify a worksheet.'); + } elseif (strpos($value,':') === false) { + throw new PHPExcel_Exception('Cell coordinate must be a range of cells.'); + } elseif (strpos($value,'$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } + $value = strtoupper($value); + + if ($method == self::SETPRINTRANGE_OVERWRITE) { + if ($index == 0) { + $this->_printArea = $value; + } else { + $printAreas = explode(',',$this->_printArea); + if($index < 0) { + $index = count($printAreas) - abs($index) + 1; + } + if (($index <= 0) || ($index > count($printAreas))) { + throw new PHPExcel_Exception('Invalid index for setting print range.'); + } + $printAreas[$index-1] = $value; + $this->_printArea = implode(',',$printAreas); + } + } elseif($method == self::SETPRINTRANGE_INSERT) { + if ($index == 0) { + $this->_printArea .= ($this->_printArea == '') ? $value : ','.$value; + } else { + $printAreas = explode(',',$this->_printArea); + if($index < 0) { + $index = abs($index) - 1; + } + if ($index > count($printAreas)) { + throw new PHPExcel_Exception('Invalid index for setting print range.'); + } + $printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index)); + $this->_printArea = implode(',',$printAreas); + } + } else { + throw new PHPExcel_Exception('Invalid method for setting print range.'); + } + + return $this; + } + + /** + * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas + * + * @param string $value + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * A positive index will insert after that indexed entry in the print areas list, while a + * negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function addPrintArea($value, $index = -1) { + return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); + } + + /** + * Set print area + * + * @param int $column1 Column 1 + * @param int $row1 Row 1 + * @param int $column2 Column 2 + * @param int $row2 Row 2 + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * When the method is "O"verwrite, then a positive integer index will overwrite that indexed + * entry in the print areas list; a negative index value will identify which entry to + * overwrite working bacward through the print area to the list, with the last entry as -1. + * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. + * When the method is "I"nsert, then a positive index will insert after that indexed entry in + * the print areas list, while a negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @param string $method Determines the method used when setting multiple print areas + * Default behaviour, or the "O" method, overwrites existing print area + * The "I" method, inserts the new print area before any specified index, or at the end of the list + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) + { + return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, $method); + } + + /** + * Add a new print area to the list of print areas + * + * @param int $column1 Start Column for the print area + * @param int $row1 Start Row for the print area + * @param int $column2 End Column for the print area + * @param int $row2 End Row for the print area + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * A positive index will insert after that indexed entry in the print areas list, while a + * negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) + { + return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT); + } + + /** + * Get first page number + * + * @return int + */ + public function getFirstPageNumber() { + return $this->_firstPageNumber; + } + + /** + * Set first page number + * + * @param int $value + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstPageNumber($value = null) { + $this->_firstPageNumber = $value; + return $this; + } + + /** + * Reset first page number + * + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function resetFirstPageNumber() { + return $this->setFirstPageNumber(null); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php new file mode 100644 index 00000000..f41dd53a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php @@ -0,0 +1,545 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_Protection + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_Protection +{ + /** + * Sheet + * + * @var boolean + */ + private $_sheet = false; + + /** + * Objects + * + * @var boolean + */ + private $_objects = false; + + /** + * Scenarios + * + * @var boolean + */ + private $_scenarios = false; + + /** + * Format cells + * + * @var boolean + */ + private $_formatCells = false; + + /** + * Format columns + * + * @var boolean + */ + private $_formatColumns = false; + + /** + * Format rows + * + * @var boolean + */ + private $_formatRows = false; + + /** + * Insert columns + * + * @var boolean + */ + private $_insertColumns = false; + + /** + * Insert rows + * + * @var boolean + */ + private $_insertRows = false; + + /** + * Insert hyperlinks + * + * @var boolean + */ + private $_insertHyperlinks = false; + + /** + * Delete columns + * + * @var boolean + */ + private $_deleteColumns = false; + + /** + * Delete rows + * + * @var boolean + */ + private $_deleteRows = false; + + /** + * Select locked cells + * + * @var boolean + */ + private $_selectLockedCells = false; + + /** + * Sort + * + * @var boolean + */ + private $_sort = false; + + /** + * AutoFilter + * + * @var boolean + */ + private $_autoFilter = false; + + /** + * Pivot tables + * + * @var boolean + */ + private $_pivotTables = false; + + /** + * Select unlocked cells + * + * @var boolean + */ + private $_selectUnlockedCells = false; + + /** + * Password + * + * @var string + */ + private $_password = ''; + + /** + * Create a new PHPExcel_Worksheet_Protection + */ + public function __construct() + { + } + + /** + * Is some sort of protection enabled? + * + * @return boolean + */ + function isProtectionEnabled() { + return $this->_sheet || + $this->_objects || + $this->_scenarios || + $this->_formatCells || + $this->_formatColumns || + $this->_formatRows || + $this->_insertColumns || + $this->_insertRows || + $this->_insertHyperlinks || + $this->_deleteColumns || + $this->_deleteRows || + $this->_selectLockedCells || + $this->_sort || + $this->_autoFilter || + $this->_pivotTables || + $this->_selectUnlockedCells; + } + + /** + * Get Sheet + * + * @return boolean + */ + function getSheet() { + return $this->_sheet; + } + + /** + * Set Sheet + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setSheet($pValue = false) { + $this->_sheet = $pValue; + return $this; + } + + /** + * Get Objects + * + * @return boolean + */ + function getObjects() { + return $this->_objects; + } + + /** + * Set Objects + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setObjects($pValue = false) { + $this->_objects = $pValue; + return $this; + } + + /** + * Get Scenarios + * + * @return boolean + */ + function getScenarios() { + return $this->_scenarios; + } + + /** + * Set Scenarios + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setScenarios($pValue = false) { + $this->_scenarios = $pValue; + return $this; + } + + /** + * Get FormatCells + * + * @return boolean + */ + function getFormatCells() { + return $this->_formatCells; + } + + /** + * Set FormatCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setFormatCells($pValue = false) { + $this->_formatCells = $pValue; + return $this; + } + + /** + * Get FormatColumns + * + * @return boolean + */ + function getFormatColumns() { + return $this->_formatColumns; + } + + /** + * Set FormatColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setFormatColumns($pValue = false) { + $this->_formatColumns = $pValue; + return $this; + } + + /** + * Get FormatRows + * + * @return boolean + */ + function getFormatRows() { + return $this->_formatRows; + } + + /** + * Set FormatRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setFormatRows($pValue = false) { + $this->_formatRows = $pValue; + return $this; + } + + /** + * Get InsertColumns + * + * @return boolean + */ + function getInsertColumns() { + return $this->_insertColumns; + } + + /** + * Set InsertColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setInsertColumns($pValue = false) { + $this->_insertColumns = $pValue; + return $this; + } + + /** + * Get InsertRows + * + * @return boolean + */ + function getInsertRows() { + return $this->_insertRows; + } + + /** + * Set InsertRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setInsertRows($pValue = false) { + $this->_insertRows = $pValue; + return $this; + } + + /** + * Get InsertHyperlinks + * + * @return boolean + */ + function getInsertHyperlinks() { + return $this->_insertHyperlinks; + } + + /** + * Set InsertHyperlinks + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setInsertHyperlinks($pValue = false) { + $this->_insertHyperlinks = $pValue; + return $this; + } + + /** + * Get DeleteColumns + * + * @return boolean + */ + function getDeleteColumns() { + return $this->_deleteColumns; + } + + /** + * Set DeleteColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setDeleteColumns($pValue = false) { + $this->_deleteColumns = $pValue; + return $this; + } + + /** + * Get DeleteRows + * + * @return boolean + */ + function getDeleteRows() { + return $this->_deleteRows; + } + + /** + * Set DeleteRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setDeleteRows($pValue = false) { + $this->_deleteRows = $pValue; + return $this; + } + + /** + * Get SelectLockedCells + * + * @return boolean + */ + function getSelectLockedCells() { + return $this->_selectLockedCells; + } + + /** + * Set SelectLockedCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setSelectLockedCells($pValue = false) { + $this->_selectLockedCells = $pValue; + return $this; + } + + /** + * Get Sort + * + * @return boolean + */ + function getSort() { + return $this->_sort; + } + + /** + * Set Sort + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setSort($pValue = false) { + $this->_sort = $pValue; + return $this; + } + + /** + * Get AutoFilter + * + * @return boolean + */ + function getAutoFilter() { + return $this->_autoFilter; + } + + /** + * Set AutoFilter + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setAutoFilter($pValue = false) { + $this->_autoFilter = $pValue; + return $this; + } + + /** + * Get PivotTables + * + * @return boolean + */ + function getPivotTables() { + return $this->_pivotTables; + } + + /** + * Set PivotTables + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setPivotTables($pValue = false) { + $this->_pivotTables = $pValue; + return $this; + } + + /** + * Get SelectUnlockedCells + * + * @return boolean + */ + function getSelectUnlockedCells() { + return $this->_selectUnlockedCells; + } + + /** + * Set SelectUnlockedCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + function setSelectUnlockedCells($pValue = false) { + $this->_selectUnlockedCells = $pValue; + return $this; + } + + /** + * Get Password (hashed) + * + * @return string + */ + function getPassword() { + return $this->_password; + } + + /** + * Set Password + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_Worksheet_Protection + */ + function setPassword($pValue = '', $pAlreadyHashed = false) { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->_password = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php new file mode 100644 index 00000000..2e9bd132 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php @@ -0,0 +1,90 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_Row + * + * Represents a row in PHPExcel_Worksheet, used by PHPExcel_Worksheet_RowIterator + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_Row +{ + /** + * PHPExcel_Worksheet + * + * @var PHPExcel_Worksheet + */ + private $_parent; + + /** + * Row index + * + * @var int + */ + private $_rowIndex = 0; + + /** + * Create a new row + * + * @param PHPExcel_Worksheet $parent + * @param int $rowIndex + */ + public function __construct(PHPExcel_Worksheet $parent = null, $rowIndex = 1) { + // Set parent and row index + $this->_parent = $parent; + $this->_rowIndex = $rowIndex; + } + + /** + * Destructor + */ + public function __destruct() { + unset($this->_parent); + } + + /** + * Get row index + * + * @return int + */ + public function getRowIndex() { + return $this->_rowIndex; + } + + /** + * Get cell iterator + * + * @return PHPExcel_Worksheet_CellIterator + */ + public function getCellIterator() { + return new PHPExcel_Worksheet_CellIterator($this->_parent, $this->_rowIndex); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php new file mode 100644 index 00000000..69b7ba81 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php @@ -0,0 +1,265 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_RowDimension + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_RowDimension +{ + /** + * Row index + * + * @var int + */ + private $_rowIndex; + + /** + * Row height (in pt) + * + * When this is set to a negative value, the row height should be ignored by IWriter + * + * @var double + */ + private $_rowHeight = -1; + + /** + * ZeroHeight for Row? + * + * @var bool + */ + private $_zeroHeight = false; + + /** + * Visible? + * + * @var bool + */ + private $_visible = true; + + /** + * Outline level + * + * @var int + */ + private $_outlineLevel = 0; + + /** + * Collapsed + * + * @var bool + */ + private $_collapsed = false; + + /** + * Index to cellXf. Null value means row has no explicit cellXf format. + * + * @var int|null + */ + private $_xfIndex; + + /** + * Create a new PHPExcel_Worksheet_RowDimension + * + * @param int $pIndex Numeric row index + */ + public function __construct($pIndex = 0) + { + // Initialise values + $this->_rowIndex = $pIndex; + + // set row dimension as unformatted by default + $this->_xfIndex = null; + } + + /** + * Get Row Index + * + * @return int + */ + public function getRowIndex() { + return $this->_rowIndex; + } + + /** + * Set Row Index + * + * @param int $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setRowIndex($pValue) { + $this->_rowIndex = $pValue; + return $this; + } + + /** + * Get Row Height + * + * @return double + */ + public function getRowHeight() { + return $this->_rowHeight; + } + + /** + * Set Row Height + * + * @param double $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setRowHeight($pValue = -1) { + $this->_rowHeight = $pValue; + return $this; + } + + /** + * Get ZeroHeight + * + * @return bool + */ + public function getzeroHeight() { + return $this->_zeroHeight; + } + + /** + * Set ZeroHeight + * + * @param bool $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setzeroHeight($pValue = false) { + $this->_zeroHeight = $pValue; + return $this; + } + + /** + * Get Visible + * + * @return bool + */ + public function getVisible() { + return $this->_visible; + } + + /** + * Set Visible + * + * @param bool $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setVisible($pValue = true) { + $this->_visible = $pValue; + return $this; + } + + /** + * Get Outline Level + * + * @return int + */ + public function getOutlineLevel() { + return $this->_outlineLevel; + } + + /** + * Set Outline Level + * + * Value must be between 0 and 7 + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_RowDimension + */ + public function setOutlineLevel($pValue) { + if ($pValue < 0 || $pValue > 7) { + throw new PHPExcel_Exception("Outline level must range between 0 and 7."); + } + + $this->_outlineLevel = $pValue; + return $this; + } + + /** + * Get Collapsed + * + * @return bool + */ + public function getCollapsed() { + return $this->_collapsed; + } + + /** + * Set Collapsed + * + * @param bool $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setCollapsed($pValue = true) { + $this->_collapsed = $pValue; + return $this; + } + + /** + * Get index to cellXf + * + * @return int + */ + public function getXfIndex() + { + return $this->_xfIndex; + } + + /** + * Set index to cellXf + * + * @param int $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setXfIndex($pValue = 0) + { + $this->_xfIndex = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php new file mode 100644 index 00000000..f2d962f5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php @@ -0,0 +1,148 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_RowIterator + * + * Used to iterate rows in a PHPExcel_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_RowIterator implements Iterator +{ + /** + * PHPExcel_Worksheet to iterate + * + * @var PHPExcel_Worksheet + */ + private $_subject; + + /** + * Current iterator position + * + * @var int + */ + private $_position = 1; + + /** + * Start position + * + * @var int + */ + private $_startRow = 1; + + + /** + * Create a new row iterator + * + * @param PHPExcel_Worksheet $subject The worksheet to iterate over + * @param integer $startRow The row number at which to start iterating + */ + public function __construct(PHPExcel_Worksheet $subject = null, $startRow = 1) { + // Set subject + $this->_subject = $subject; + $this->resetStart($startRow); + } + + /** + * Destructor + */ + public function __destruct() { + unset($this->_subject); + } + + /** + * (Re)Set the start row and the current row pointer + * + * @param integer $startRow The row number at which to start iterating + */ + public function resetStart($startRow = 1) { + $this->_startRow = $startRow; + $this->seek($startRow); + } + + /** + * Set the row pointer to the selected row + * + * @param integer $row The row number to set the current pointer at + */ + public function seek($row = 1) { + $this->_position = $row; + } + + /** + * Rewind the iterator to the starting row + */ + public function rewind() { + $this->_position = $this->_startRow; + } + + /** + * Return the current row in this worksheet + * + * @return PHPExcel_Worksheet_Row + */ + public function current() { + return new PHPExcel_Worksheet_Row($this->_subject, $this->_position); + } + + /** + * Return the current iterator key + * + * @return int + */ + public function key() { + return $this->_position; + } + + /** + * Set the iterator to its next value + */ + public function next() { + ++$this->_position; + } + + /** + * Set the iterator to its previous value + */ + public function prev() { + if ($this->_position > 1) + --$this->_position; + } + + /** + * Indicate if more rows exist in the worksheet + * + * @return boolean + */ + public function valid() { + return $this->_position <= $this->_subject->getHighestRow(); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php new file mode 100644 index 00000000..05fbf286 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php @@ -0,0 +1,188 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Worksheet_SheetView + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_SheetView +{ + + /* Sheet View types */ + const SHEETVIEW_NORMAL = 'normal'; + const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; + const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; + + private static $_sheetViewTypes = array( + self::SHEETVIEW_NORMAL, + self::SHEETVIEW_PAGE_LAYOUT, + self::SHEETVIEW_PAGE_BREAK_PREVIEW, + ); + + /** + * ZoomScale + * + * Valid values range from 10 to 400. + * + * @var int + */ + private $_zoomScale = 100; + + /** + * ZoomScaleNormal + * + * Valid values range from 10 to 400. + * + * @var int + */ + private $_zoomScaleNormal = 100; + + /** + * View + * + * Valid values range from 10 to 400. + * + * @var string + */ + private $_sheetviewType = self::SHEETVIEW_NORMAL; + + /** + * Create a new PHPExcel_Worksheet_SheetView + */ + public function __construct() + { + } + + /** + * Get ZoomScale + * + * @return int + */ + public function getZoomScale() { + return $this->_zoomScale; + } + + /** + * Set ZoomScale + * + * Valid values range from 10 to 400. + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setZoomScale($pValue = 100) { + // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, + // but it is apparently still able to handle any scale >= 1 + if (($pValue >= 1) || is_null($pValue)) { + $this->_zoomScale = $pValue; + } else { + throw new PHPExcel_Exception("Scale must be greater than or equal to 1."); + } + return $this; + } + + /** + * Get ZoomScaleNormal + * + * @return int + */ + public function getZoomScaleNormal() { + return $this->_zoomScaleNormal; + } + + /** + * Set ZoomScale + * + * Valid values range from 10 to 400. + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setZoomScaleNormal($pValue = 100) { + if (($pValue >= 1) || is_null($pValue)) { + $this->_zoomScaleNormal = $pValue; + } else { + throw new PHPExcel_Exception("Scale must be greater than or equal to 1."); + } + return $this; + } + + /** + * Get View + * + * @return string + */ + public function getView() { + return $this->_sheetviewType; + } + + /** + * Set View + * + * Valid values are + * 'normal' self::SHEETVIEW_NORMAL + * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT + * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW + * + * @param string $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setView($pValue = NULL) { + // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' + // via the user interface + if ($pValue === NULL) + $pValue = self::SHEETVIEW_NORMAL; + if (in_array($pValue, self::$_sheetViewTypes)) { + $this->_sheetviewType = $pValue; + } else { + throw new PHPExcel_Exception("Invalid sheetview layout type."); + } + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php new file mode 100644 index 00000000..624b49b6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php @@ -0,0 +1,118 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_WorksheetIterator + * + * Used to iterate worksheets in PHPExcel + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_WorksheetIterator implements Iterator +{ + /** + * Spreadsheet to iterate + * + * @var PHPExcel + */ + private $_subject; + + /** + * Current iterator position + * + * @var int + */ + private $_position = 0; + + /** + * Create a new worksheet iterator + * + * @param PHPExcel $subject + */ + public function __construct(PHPExcel $subject = null) + { + // Set subject + $this->_subject = $subject; + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->_subject); + } + + /** + * Rewind iterator + */ + public function rewind() + { + $this->_position = 0; + } + + /** + * Current PHPExcel_Worksheet + * + * @return PHPExcel_Worksheet + */ + public function current() + { + return $this->_subject->getSheet($this->_position); + } + + /** + * Current key + * + * @return int + */ + public function key() + { + return $this->_position; + } + + /** + * Next value + */ + public function next() + { + ++$this->_position; + } + + /** + * More PHPExcel_Worksheet instances available? + * + * @return boolean + */ + public function valid() + { + return $this->_position < $this->_subject->getSheetCount(); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php new file mode 100644 index 00000000..7e09ef83 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php @@ -0,0 +1,158 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Abstract + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * Write charts that are defined in the workbook? + * Identifies whether the Writer should write definitions for any charts that exist in the PHPExcel object; + * + * @var boolean + */ + protected $_includeCharts = FALSE; + + /** + * Pre-calculate formulas + * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are + * immediately available to MS Excel or other office spreadsheet viewer when opening the file + * + * @var boolean + */ + protected $_preCalculateFormulas = TRUE; + + /** + * Use disk caching where possible? + * + * @var boolean + */ + protected $_useDiskCaching = FALSE; + + /** + * Disk caching directory + * + * @var string + */ + protected $_diskCachingDirectory = './'; + + /** + * Write charts in workbook? + * If this is true, then the Writer will write definitions for any charts that exist in the PHPExcel object. + * If false (the default) it will ignore any charts defined in the PHPExcel object. + * + * @return boolean + */ + public function getIncludeCharts() { + return $this->_includeCharts; + } + + /** + * Set write charts in workbook + * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object. + * Set to false (the default) to ignore charts. + * + * @param boolean $pValue + * @return PHPExcel_Writer_IWriter + */ + public function setIncludeCharts($pValue = FALSE) { + $this->_includeCharts = (boolean) $pValue; + return $this; + } + + /** + * Get Pre-Calculate Formulas flag + * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving, + * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet + * viewer when opening the file + * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower + * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself + * + * @return boolean + */ + public function getPreCalculateFormulas() { + return $this->_preCalculateFormulas; + } + + /** + * Set Pre-Calculate Formulas + * Set to true (the default) to advise the Writer to calculate all formulae on save + * Set to false to prevent precalculation of formulae on save. + * + * @param boolean $pValue Pre-Calculate Formulas? + * @return PHPExcel_Writer_IWriter + */ + public function setPreCalculateFormulas($pValue = TRUE) { + $this->_preCalculateFormulas = (boolean) $pValue; + return $this; + } + + /** + * Get use disk caching where possible? + * + * @return boolean + */ + public function getUseDiskCaching() { + return $this->_useDiskCaching; + } + + /** + * Set use disk caching where possible? + * + * @param boolean $pValue + * @param string $pDirectory Disk caching directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_Excel2007 + */ + public function setUseDiskCaching($pValue = FALSE, $pDirectory = NULL) { + $this->_useDiskCaching = $pValue; + + if ($pDirectory !== NULL) { + if (is_dir($pDirectory)) { + $this->_diskCachingDirectory = $pDirectory; + } else { + throw new PHPExcel_Writer_Exception("Directory does not exist: $pDirectory"); + } + } + return $this; + } + + /** + * Get disk caching directory + * + * @return string + */ + public function getDiskCachingDirectory() { + return $this->_diskCachingDirectory; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php new file mode 100644 index 00000000..521874f2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php @@ -0,0 +1,310 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_CSV + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_CSV + * + * @category PHPExcel + * @package PHPExcel_Writer_CSV + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_CSV extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter { + /** + * PHPExcel object + * + * @var PHPExcel + */ + private $_phpExcel; + + /** + * Delimiter + * + * @var string + */ + private $_delimiter = ','; + + /** + * Enclosure + * + * @var string + */ + private $_enclosure = '"'; + + /** + * Line ending + * + * @var string + */ + private $_lineEnding = PHP_EOL; + + /** + * Sheet index to write + * + * @var int + */ + private $_sheetIndex = 0; + + /** + * Whether to write a BOM (for UTF8). + * + * @var boolean + */ + private $_useBOM = false; + + /** + * Whether to write a fully Excel compatible CSV file. + * + * @var boolean + */ + private $_excelCompatibility = false; + + /** + * Create a new PHPExcel_Writer_CSV + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) { + $this->_phpExcel = $phpExcel; + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) { + // Fetch sheet + $sheet = $this->_phpExcel->getSheet($this->_sheetIndex); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE); + $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Open file + $fileHandle = fopen($pFilename, 'wb+'); + if ($fileHandle === false) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + if ($this->_excelCompatibility) { + fwrite($fileHandle, "\xEF\xBB\xBF"); // Enforce UTF-8 BOM Header + $this->setEnclosure('"'); // Set enclosure to " + $this->setDelimiter(";"); // Set delimiter to a semi-colon + $this->setLineEnding("\r\n"); + fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->_lineEnding); + } elseif ($this->_useBOM) { + // Write the UTF-8 BOM code if required + fwrite($fileHandle, "\xEF\xBB\xBF"); + } + + // Identify the range that we need to extract from the worksheet + $maxCol = $sheet->getHighestDataColumn(); + $maxRow = $sheet->getHighestDataRow(); + + // Write rows to file + for($row = 1; $row <= $maxRow; ++$row) { + // Convert the row to an array... + $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row,'', $this->_preCalculateFormulas); + // ... and write to the file + $this->_writeLine($fileHandle, $cellsArray[0]); + } + + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Get delimiter + * + * @return string + */ + public function getDelimiter() { + return $this->_delimiter; + } + + /** + * Set delimiter + * + * @param string $pValue Delimiter, defaults to , + * @return PHPExcel_Writer_CSV + */ + public function setDelimiter($pValue = ',') { + $this->_delimiter = $pValue; + return $this; + } + + /** + * Get enclosure + * + * @return string + */ + public function getEnclosure() { + return $this->_enclosure; + } + + /** + * Set enclosure + * + * @param string $pValue Enclosure, defaults to " + * @return PHPExcel_Writer_CSV + */ + public function setEnclosure($pValue = '"') { + if ($pValue == '') { + $pValue = null; + } + $this->_enclosure = $pValue; + return $this; + } + + /** + * Get line ending + * + * @return string + */ + public function getLineEnding() { + return $this->_lineEnding; + } + + /** + * Set line ending + * + * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL) + * @return PHPExcel_Writer_CSV + */ + public function setLineEnding($pValue = PHP_EOL) { + $this->_lineEnding = $pValue; + return $this; + } + + /** + * Get whether BOM should be used + * + * @return boolean + */ + public function getUseBOM() { + return $this->_useBOM; + } + + /** + * Set whether BOM should be used + * + * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false + * @return PHPExcel_Writer_CSV + */ + public function setUseBOM($pValue = false) { + $this->_useBOM = $pValue; + return $this; + } + + /** + * Get whether the file should be saved with full Excel Compatibility + * + * @return boolean + */ + public function getExcelCompatibility() { + return $this->_excelCompatibility; + } + + /** + * Set whether the file should be saved with full Excel Compatibility + * + * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file + * Note that this overrides other settings such as useBOM, enclosure and delimiter + * @return PHPExcel_Writer_CSV + */ + public function setExcelCompatibility($pValue = false) { + $this->_excelCompatibility = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() { + return $this->_sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Writer_CSV + */ + public function setSheetIndex($pValue = 0) { + $this->_sheetIndex = $pValue; + return $this; + } + + /** + * Write line to CSV file + * + * @param mixed $pFileHandle PHP filehandle + * @param array $pValues Array containing values in a row + * @throws PHPExcel_Writer_Exception + */ + private function _writeLine($pFileHandle = null, $pValues = null) { + if (is_array($pValues)) { + // No leading delimiter + $writeDelimiter = false; + + // Build the line + $line = ''; + + foreach ($pValues as $element) { + // Escape enclosures + $element = str_replace($this->_enclosure, $this->_enclosure . $this->_enclosure, $element); + + // Add delimiter + if ($writeDelimiter) { + $line .= $this->_delimiter; + } else { + $writeDelimiter = true; + } + + // Add enclosed string + $line .= $this->_enclosure . $element . $this->_enclosure; + } + + // Add line ending + $line .= $this->_lineEnding; + + // Write to file + fwrite($pFileHandle, $line); + } else { + throw new PHPExcel_Writer_Exception("Invalid data row passed to CSV writer."); + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php new file mode 100644 index 00000000..a8f7593c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php @@ -0,0 +1,532 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007 + * + * @category PHPExcel + * @package PHPExcel_Writer_2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007 extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * Pre-calculate formulas + * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are + * immediately available to MS Excel or other office spreadsheet viewer when opening the file + * + * Overrides the default TRUE for this specific writer for performance reasons + * + * @var boolean + */ + protected $_preCalculateFormulas = FALSE; + + /** + * Office2003 compatibility + * + * @var boolean + */ + private $_office2003compatibility = false; + + /** + * Private writer parts + * + * @var PHPExcel_Writer_Excel2007_WriterPart[] + */ + private $_writerParts = array(); + + /** + * Private PHPExcel + * + * @var PHPExcel + */ + private $_spreadSheet; + + /** + * Private string table + * + * @var string[] + */ + private $_stringTable = array(); + + /** + * Private unique PHPExcel_Style_Conditional HashTable + * + * @var PHPExcel_HashTable + */ + private $_stylesConditionalHashTable; + + /** + * Private unique PHPExcel_Style HashTable + * + * @var PHPExcel_HashTable + */ + private $_styleHashTable; + + /** + * Private unique PHPExcel_Style_Fill HashTable + * + * @var PHPExcel_HashTable + */ + private $_fillHashTable; + + /** + * Private unique PHPExcel_Style_Font HashTable + * + * @var PHPExcel_HashTable + */ + private $_fontHashTable; + + /** + * Private unique PHPExcel_Style_Borders HashTable + * + * @var PHPExcel_HashTable + */ + private $_bordersHashTable ; + + /** + * Private unique PHPExcel_Style_NumberFormat HashTable + * + * @var PHPExcel_HashTable + */ + private $_numFmtHashTable; + + /** + * Private unique PHPExcel_Worksheet_BaseDrawing HashTable + * + * @var PHPExcel_HashTable + */ + private $_drawingHashTable; + + /** + * Create a new PHPExcel_Writer_Excel2007 + * + * @param PHPExcel $pPHPExcel + */ + public function __construct(PHPExcel $pPHPExcel = null) + { + // Assign PHPExcel + $this->setPHPExcel($pPHPExcel); + + $writerPartsArray = array( 'stringtable' => 'PHPExcel_Writer_Excel2007_StringTable', + 'contenttypes' => 'PHPExcel_Writer_Excel2007_ContentTypes', + 'docprops' => 'PHPExcel_Writer_Excel2007_DocProps', + 'rels' => 'PHPExcel_Writer_Excel2007_Rels', + 'theme' => 'PHPExcel_Writer_Excel2007_Theme', + 'style' => 'PHPExcel_Writer_Excel2007_Style', + 'workbook' => 'PHPExcel_Writer_Excel2007_Workbook', + 'worksheet' => 'PHPExcel_Writer_Excel2007_Worksheet', + 'drawing' => 'PHPExcel_Writer_Excel2007_Drawing', + 'comments' => 'PHPExcel_Writer_Excel2007_Comments', + 'chart' => 'PHPExcel_Writer_Excel2007_Chart', + 'relsvba' => 'PHPExcel_Writer_Excel2007_RelsVBA', + 'relsribbonobjects' => 'PHPExcel_Writer_Excel2007_RelsRibbon' + ); + + // Initialise writer parts + // and Assign their parent IWriters + foreach ($writerPartsArray as $writer => $class) { + $this->_writerParts[$writer] = new $class($this); + } + + $hashTablesArray = array( '_stylesConditionalHashTable', '_fillHashTable', '_fontHashTable', + '_bordersHashTable', '_numFmtHashTable', '_drawingHashTable', + '_styleHashTable' + ); + + // Set HashTable variables + foreach ($hashTablesArray as $tableName) { + $this->$tableName = new PHPExcel_HashTable(); + } + } + + /** + * Get writer part + * + * @param string $pPartName Writer part name + * @return PHPExcel_Writer_Excel2007_WriterPart + */ + public function getWriterPart($pPartName = '') { + if ($pPartName != '' && isset($this->_writerParts[strtolower($pPartName)])) { + return $this->_writerParts[strtolower($pPartName)]; + } else { + return null; + } + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + if ($this->_spreadSheet !== NULL) { + // garbage collect + $this->_spreadSheet->garbageCollect(); + + // If $pFilename is php://output or php://stdout, make it a temporary file... + $originalFilename = $pFilename; + if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp'); + if ($pFilename == '') { + $pFilename = $originalFilename; + } + } + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog(FALSE); + $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + + // Create string lookup table + $this->_stringTable = array(); + for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { + $this->_stringTable = $this->getWriterPart('StringTable')->createStringTable($this->_spreadSheet->getSheet($i), $this->_stringTable); + } + + // Create styles dictionaries + $this->_styleHashTable->addFromSource( $this->getWriterPart('Style')->allStyles($this->_spreadSheet) ); + $this->_stylesConditionalHashTable->addFromSource( $this->getWriterPart('Style')->allConditionalStyles($this->_spreadSheet) ); + $this->_fillHashTable->addFromSource( $this->getWriterPart('Style')->allFills($this->_spreadSheet) ); + $this->_fontHashTable->addFromSource( $this->getWriterPart('Style')->allFonts($this->_spreadSheet) ); + $this->_bordersHashTable->addFromSource( $this->getWriterPart('Style')->allBorders($this->_spreadSheet) ); + $this->_numFmtHashTable->addFromSource( $this->getWriterPart('Style')->allNumberFormats($this->_spreadSheet) ); + + // Create drawing dictionary + $this->_drawingHashTable->addFromSource( $this->getWriterPart('Drawing')->allDrawings($this->_spreadSheet) ); + + // Create new ZIP file and open it for writing + $zipClass = PHPExcel_Settings::getZipClass(); + $objZip = new $zipClass(); + + // Retrieve OVERWRITE and CREATE constants from the instantiated zip class + // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP + $ro = new ReflectionObject($objZip); + $zipOverWrite = $ro->getConstant('OVERWRITE'); + $zipCreate = $ro->getConstant('CREATE'); + + if (file_exists($pFilename)) { + unlink($pFilename); + } + // Try opening the ZIP file + if ($objZip->open($pFilename, $zipOverWrite) !== true) { + if ($objZip->open($pFilename, $zipCreate) !== true) { + throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing."); + } + } + + // Add [Content_Types].xml to ZIP file + $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->_spreadSheet, $this->_includeCharts)); + + //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) + if($this->_spreadSheet->hasMacros()){ + $macrosCode=$this->_spreadSheet->getMacrosCode(); + if(!is_null($macrosCode)){// we have the code ? + $objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin + if($this->_spreadSheet->hasMacrosCertificate()){//signed macros ? + // Yes : add the certificate file and the related rels file + $objZip->addFromString('xl/vbaProjectSignature.bin', $this->_spreadSheet->getMacrosCertificate()); + $objZip->addFromString('xl/_rels/vbaProject.bin.rels', + $this->getWriterPart('RelsVBA')->writeVBARelationships($this->_spreadSheet)); + } + } + } + //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) + if($this->_spreadSheet->hasRibbon()){ + $tmpRibbonTarget=$this->_spreadSheet->getRibbonXMLData('target'); + $objZip->addFromString($tmpRibbonTarget, $this->_spreadSheet->getRibbonXMLData('data')); + if($this->_spreadSheet->hasRibbonBinObjects()){ + $tmpRootPath=dirname($tmpRibbonTarget).'/'; + $ribbonBinObjects=$this->_spreadSheet->getRibbonBinObjects('data');//the files to write + foreach($ribbonBinObjects as $aPath=>$aContent){ + $objZip->addFromString($tmpRootPath.$aPath, $aContent); + } + //the rels for files + $objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels', + $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->_spreadSheet)); + } + } + + // Add relationships to ZIP file + $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->_spreadSheet)); + $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->_spreadSheet)); + + // Add document properties to ZIP file + $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->_spreadSheet)); + $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->_spreadSheet)); + $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->_spreadSheet); + if ($customPropertiesPart !== NULL) { + $objZip->addFromString('docProps/custom.xml', $customPropertiesPart); + } + + // Add theme to ZIP file + $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->_spreadSheet)); + + // Add string table to ZIP file + $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->_stringTable)); + + // Add styles to ZIP file + $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->_spreadSheet)); + + // Add workbook to ZIP file + $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->_spreadSheet, $this->_preCalculateFormulas)); + + $chartCount = 0; + // Add worksheets + for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { + $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->_spreadSheet->getSheet($i), $this->_stringTable, $this->_includeCharts)); + if ($this->_includeCharts) { + $charts = $this->_spreadSheet->getSheet($i)->getChartCollection(); + if (count($charts) > 0) { + foreach($charts as $chart) { + $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart)); + $chartCount++; + } + } + } + } + + $chartRef1 = $chartRef2 = 0; + // Add worksheet relationships (drawings, ...) + for ($i = 0; $i < $this->_spreadSheet->getSheetCount(); ++$i) { + + // Add relationships + $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->_spreadSheet->getSheet($i), ($i + 1), $this->_includeCharts)); + + $drawings = $this->_spreadSheet->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + if ($this->_includeCharts) { + $chartCount = $this->_spreadSheet->getSheet($i)->getChartCount(); + } + + // Add drawing and image relationship parts + if (($drawingCount > 0) || ($chartCount > 0)) { + // Drawing relationships + $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->_spreadSheet->getSheet($i),$chartRef1, $this->_includeCharts)); + + // Drawings + $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->_spreadSheet->getSheet($i),$chartRef2,$this->_includeCharts)); + } + + // Add comment relationship parts + if (count($this->_spreadSheet->getSheet($i)->getComments()) > 0) { + // VML Comments + $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->_spreadSheet->getSheet($i))); + + // Comments + $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->_spreadSheet->getSheet($i))); + } + + // Add header/footer relationship parts + if (count($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { + // VML Drawings + $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->_spreadSheet->getSheet($i))); + + // VML Drawing relationships + $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->_spreadSheet->getSheet($i))); + + // Media + foreach ($this->_spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { + $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); + } + } + } + + // Add media + for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { + if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { + $imageContents = null; + $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); + if (strpos($imagePath, 'zip://') !== false) { + $imagePath = substr($imagePath, 6); + $imagePathSplitted = explode('#', $imagePath); + + $imageZip = new ZipArchive(); + $imageZip->open($imagePathSplitted[0]); + $imageContents = $imageZip->getFromName($imagePathSplitted[1]); + $imageZip->close(); + unset($imageZip); + } else { + $imageContents = file_get_contents($imagePath); + } + + $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + } else if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { + ob_start(); + call_user_func( + $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), + $this->getDrawingHashTable()->getByIndex($i)->getImageResource() + ); + $imageContents = ob_get_contents(); + ob_end_clean(); + + $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + } + } + + PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); + PHPExcel_Calculation::getInstance($this->_spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); + + // Close file + if ($objZip->close() === false) { + throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename."); + } + + // If a temporary file was used, copy it to the correct file stream + if ($originalFilename != $pFilename) { + if (copy($pFilename, $originalFilename) === false) { + throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename."); + } + @unlink($pFilename); + } + } else { + throw new PHPExcel_Writer_Exception("PHPExcel object unassigned."); + } + } + + /** + * Get PHPExcel object + * + * @return PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function getPHPExcel() { + if ($this->_spreadSheet !== null) { + return $this->_spreadSheet; + } else { + throw new PHPExcel_Writer_Exception("No PHPExcel assigned."); + } + } + + /** + * Set PHPExcel object + * + * @param PHPExcel $pPHPExcel PHPExcel object + * @throws PHPExcel_Writer_Exception + * @return PHPExcel_Writer_Excel2007 + */ + public function setPHPExcel(PHPExcel $pPHPExcel = null) { + $this->_spreadSheet = $pPHPExcel; + return $this; + } + + /** + * Get string table + * + * @return string[] + */ + public function getStringTable() { + return $this->_stringTable; + } + + /** + * Get PHPExcel_Style HashTable + * + * @return PHPExcel_HashTable + */ + public function getStyleHashTable() { + return $this->_styleHashTable; + } + + /** + * Get PHPExcel_Style_Conditional HashTable + * + * @return PHPExcel_HashTable + */ + public function getStylesConditionalHashTable() { + return $this->_stylesConditionalHashTable; + } + + /** + * Get PHPExcel_Style_Fill HashTable + * + * @return PHPExcel_HashTable + */ + public function getFillHashTable() { + return $this->_fillHashTable; + } + + /** + * Get PHPExcel_Style_Font HashTable + * + * @return PHPExcel_HashTable + */ + public function getFontHashTable() { + return $this->_fontHashTable; + } + + /** + * Get PHPExcel_Style_Borders HashTable + * + * @return PHPExcel_HashTable + */ + public function getBordersHashTable() { + return $this->_bordersHashTable; + } + + /** + * Get PHPExcel_Style_NumberFormat HashTable + * + * @return PHPExcel_HashTable + */ + public function getNumFmtHashTable() { + return $this->_numFmtHashTable; + } + + /** + * Get PHPExcel_Worksheet_BaseDrawing HashTable + * + * @return PHPExcel_HashTable + */ + public function getDrawingHashTable() { + return $this->_drawingHashTable; + } + + /** + * Get Office2003 compatibility + * + * @return boolean + */ + public function getOffice2003Compatibility() { + return $this->_office2003compatibility; + } + + /** + * Set Office2003 compatibility + * + * @param boolean $pValue Office2003 compatibility? + * @return PHPExcel_Writer_Excel2007 + */ + public function setOffice2003Compatibility($pValue = false) { + $this->_office2003compatibility = $pValue; + return $this; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php new file mode 100644 index 00000000..526daa92 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php @@ -0,0 +1,1203 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Chart + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write charts to XML format + * + * @param PHPExcel_Chart $pChart + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeChart(PHPExcel_Chart $pChart = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + // Ensure that data series values are up-to-date before we save + $pChart->refresh(); + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // c:chartSpace + $objWriter->startElement('c:chartSpace'); + $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + $objWriter->startElement('c:date1904'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + $objWriter->startElement('c:lang'); + $objWriter->writeAttribute('val', "en-GB"); + $objWriter->endElement(); + $objWriter->startElement('c:roundedCorners'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $this->_writeAlternateContent($objWriter); + + $objWriter->startElement('c:chart'); + + $this->_writeTitle($pChart->getTitle(), $objWriter); + + $objWriter->startElement('c:autoTitleDeleted'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $this->_writePlotArea($pChart->getPlotArea(), + $pChart->getXAxisLabel(), + $pChart->getYAxisLabel(), + $objWriter, + $pChart->getWorksheet() + ); + + $this->_writeLegend($pChart->getLegend(), $objWriter); + + + $objWriter->startElement('c:plotVisOnly'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:dispBlanksAs'); + $objWriter->writeAttribute('val', "gap"); + $objWriter->endElement(); + + $objWriter->startElement('c:showDLblsOverMax'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + $this->_writePrintSettings($objWriter); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write Chart Title + * + * @param PHPExcel_Chart_Title $title + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeTitle(PHPExcel_Chart_Title $title = null, $objWriter) + { + if (is_null($title)) { + return; + } + + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + + $caption = $title->getCaption(); + if ((is_array($caption)) && (count($caption) > 0)) + $caption = $caption[0]; + $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a'); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $layout = $title->getLayout(); + $this->_writeLayout($layout, $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Chart Legend + * + * @param PHPExcel_Chart_Legend $legend + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter) + { + if (is_null($legend)) { + return; + } + + $objWriter->startElement('c:legend'); + + $objWriter->startElement('c:legendPos'); + $objWriter->writeAttribute('val', $legend->getPosition()); + $objWriter->endElement(); + + $layout = $legend->getLayout(); + $this->_writeLayout($layout, $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0'); + $objWriter->endElement(); + + $objWriter->startElement('c:txPr'); + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:pPr'); + $objWriter->writeAttribute('rtl', 0); + + $objWriter->startElement('a:defRPr'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('a:endParaRPr'); + $objWriter->writeAttribute('lang', "en-US"); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Chart Plot Area + * + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $xAxisLabel + * @param PHPExcel_Chart_Title $yAxisLabel + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writePlotArea(PHPExcel_Chart_PlotArea $plotArea, + PHPExcel_Chart_Title $xAxisLabel = NULL, + PHPExcel_Chart_Title $yAxisLabel = NULL, + $objWriter, + PHPExcel_Worksheet $pSheet) + { + if (is_null($plotArea)) { + return; + } + + $id1 = $id2 = 0; + $this->_seriesIndex = 0; + $objWriter->startElement('c:plotArea'); + + $layout = $plotArea->getLayout(); + + $this->_writeLayout($layout, $objWriter); + + $chartTypes = self::_getChartType($plotArea); + $catIsMultiLevelSeries = $valIsMultiLevelSeries = FALSE; + $plotGroupingType = ''; + foreach($chartTypes as $chartType) { + $objWriter->startElement('c:'.$chartType); + + $groupCount = $plotArea->getPlotGroupCount(); + for($i = 0; $i < $groupCount; ++$i) { + $plotGroup = $plotArea->getPlotGroupByIndex($i); + $groupType = $plotGroup->getPlotType(); + if ($groupType == $chartType) { + + $plotStyle = $plotGroup->getPlotStyle(); + if ($groupType === PHPExcel_Chart_DataSeries::TYPE_RADARCHART) { + $objWriter->startElement('c:radarStyle'); + $objWriter->writeAttribute('val', $plotStyle ); + $objWriter->endElement(); + } elseif ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART) { + $objWriter->startElement('c:scatterStyle'); + $objWriter->writeAttribute('val', $plotStyle ); + $objWriter->endElement(); + } + + $this->_writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet); + } + } + + $this->_writeDataLbls($objWriter, $layout); + + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_LINECHART) { + // Line only, Line3D can't be smoothed + + $objWriter->startElement('c:smooth'); + $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine() ); + $objWriter->endElement(); + } elseif (($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) || + ($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) { + + $objWriter->startElement('c:gapWidth'); + $objWriter->writeAttribute('val', 150 ); + $objWriter->endElement(); + + if ($plotGroupingType == 'percentStacked' || + $plotGroupingType == 'stacked') { + + $objWriter->startElement('c:overlap'); + $objWriter->writeAttribute('val', 100 ); + $objWriter->endElement(); + } + } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + + $objWriter->startElement('c:bubbleScale'); + $objWriter->writeAttribute('val', 25 ); + $objWriter->endElement(); + + $objWriter->startElement('c:showNegBubbles'); + $objWriter->writeAttribute('val', 0 ); + $objWriter->endElement(); + } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) { + + $objWriter->startElement('c:hiLowLines'); + $objWriter->endElement(); + + $objWriter->startElement( 'c:upDownBars' ); + + $objWriter->startElement( 'c:gapWidth' ); + $objWriter->writeAttribute('val', 300); + $objWriter->endElement(); + + $objWriter->startElement( 'c:upBars' ); + $objWriter->endElement(); + + $objWriter->startElement( 'c:downBars' ); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + // Generate 2 unique numbers to use for axId values +// $id1 = $id2 = rand(10000000,99999999); +// do { +// $id2 = rand(10000000,99999999); +// } while ($id1 == $id2); + $id1 = '75091328'; + $id2 = '75089408'; + + if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && + ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && + ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id1 ); + $objWriter->endElement(); + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id2 ); + $objWriter->endElement(); + } else { + $objWriter->startElement('c:firstSliceAng'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) { + + $objWriter->startElement('c:holeSize'); + $objWriter->writeAttribute('val', 50); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && + ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && + ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $this->_writeValAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries); + } else { + $this->_writeCatAx($objWriter,$plotArea,$xAxisLabel,$chartType,$id1,$id2,$catIsMultiLevelSeries); + } + + $this->_writeValAx($objWriter,$plotArea,$yAxisLabel,$chartType,$id1,$id2,$valIsMultiLevelSeries); + } + + $objWriter->endElement(); + } + + /** + * Write Data Labels + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_Layout $chartLayout Chart layout + * @throws PHPExcel_Writer_Exception + */ + private function _writeDataLbls($objWriter, $chartLayout) + { + $objWriter->startElement('c:dLbls'); + + $objWriter->startElement('c:showLegendKey'); + $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey(); + $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1) ); + $objWriter->endElement(); + + + $objWriter->startElement('c:showVal'); + $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal(); + $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->startElement('c:showCatName'); + $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName(); + $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->startElement('c:showSerName'); + $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName(); + $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->startElement('c:showPercent'); + $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent(); + $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->startElement('c:showBubbleSize'); + $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize(); + $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->startElement('c:showLeaderLines'); + $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines(); + $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1) ); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Category Axis + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $xAxisLabel + * @param string $groupType Chart type + * @param string $id1 + * @param string $id2 + * @param boolean $isMultiLevelSeries + * @throws PHPExcel_Writer_Exception + */ + private function _writeCatAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries) + { + $objWriter->startElement('c:catAx'); + + if ($id1 > 0) { + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id1); + $objWriter->endElement(); + } + + $objWriter->startElement('c:scaling'); + $objWriter->startElement('c:orientation'); + $objWriter->writeAttribute('val', "minMax"); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:delete'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:axPos'); + $objWriter->writeAttribute('val', "b"); + $objWriter->endElement(); + + if (!is_null($xAxisLabel)) { + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:r'); + + $caption = $xAxisLabel->getCaption(); + if (is_array($caption)) + $caption = $caption[0]; + $objWriter->startElement('a:t'); +// $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $caption )); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $layout = $xAxisLabel->getLayout(); + $this->_writeLayout($layout, $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + } + + $objWriter->startElement('c:numFmt'); + $objWriter->writeAttribute('formatCode', "General"); + $objWriter->writeAttribute('sourceLinked', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:majorTickMark'); + $objWriter->writeAttribute('val', "out"); + $objWriter->endElement(); + + $objWriter->startElement('c:minorTickMark'); + $objWriter->writeAttribute('val', "none"); + $objWriter->endElement(); + + $objWriter->startElement('c:tickLblPos'); + $objWriter->writeAttribute('val', "nextTo"); + $objWriter->endElement(); + + if ($id2 > 0) { + $objWriter->startElement('c:crossAx'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + + $objWriter->startElement('c:crosses'); + $objWriter->writeAttribute('val', "autoZero"); + $objWriter->endElement(); + } + + $objWriter->startElement('c:auto'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:lblAlgn'); + $objWriter->writeAttribute('val', "ctr"); + $objWriter->endElement(); + + $objWriter->startElement('c:lblOffset'); + $objWriter->writeAttribute('val', 100); + $objWriter->endElement(); + + if ($isMultiLevelSeries) { + $objWriter->startElement('c:noMultiLvlLbl'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + $objWriter->endElement(); + + } + + + /** + * Write Value Axis + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $yAxisLabel + * @param string $groupType Chart type + * @param string $id1 + * @param string $id2 + * @param boolean $isMultiLevelSeries + * @throws PHPExcel_Writer_Exception + */ + private function _writeValAx($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries) + { + $objWriter->startElement('c:valAx'); + + if ($id2 > 0) { + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + } + + $objWriter->startElement('c:scaling'); + $objWriter->startElement('c:orientation'); + $objWriter->writeAttribute('val', "minMax"); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:delete'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:axPos'); + $objWriter->writeAttribute('val', "l"); + $objWriter->endElement(); + + $objWriter->startElement('c:majorGridlines'); + $objWriter->endElement(); + + if (!is_null($yAxisLabel)) { + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:r'); + + $caption = $yAxisLabel->getCaption(); + if (is_array($caption)) + $caption = $caption[0]; + $objWriter->startElement('a:t'); +// $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $caption )); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $layout = $yAxisLabel->getLayout(); + $this->_writeLayout($layout, $objWriter); + } + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + $objWriter->startElement('c:numFmt'); + $objWriter->writeAttribute('formatCode', "General"); + $objWriter->writeAttribute('sourceLinked', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:majorTickMark'); + $objWriter->writeAttribute('val', "out"); + $objWriter->endElement(); + + $objWriter->startElement('c:minorTickMark'); + $objWriter->writeAttribute('val', "none"); + $objWriter->endElement(); + + $objWriter->startElement('c:tickLblPos'); + $objWriter->writeAttribute('val', "nextTo"); + $objWriter->endElement(); + + if ($id1 > 0) { + $objWriter->startElement('c:crossAx'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + + $objWriter->startElement('c:crosses'); + $objWriter->writeAttribute('val', "autoZero"); + $objWriter->endElement(); + + $objWriter->startElement('c:crossBetween'); + $objWriter->writeAttribute('val', "midCat"); + $objWriter->endElement(); + } + + if ($isMultiLevelSeries) { + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $objWriter->startElement('c:noMultiLvlLbl'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + } + $objWriter->endElement(); + + } + + + /** + * Get the data series type(s) for a chart plot series + * + * @param PHPExcel_Chart_PlotArea $plotArea + * @return string|array + * @throws PHPExcel_Writer_Exception + */ + private static function _getChartType($plotArea) + { + $groupCount = $plotArea->getPlotGroupCount(); + + if ($groupCount == 1) { + $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType()); + } else { + $chartTypes = array(); + for($i = 0; $i < $groupCount; ++$i) { + $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType(); + } + $chartType = array_unique($chartTypes); + if (count($chartTypes) == 0) { + throw new PHPExcel_Writer_Exception('Chart is not yet implemented'); + } + } + + return $chartType; + } + + /** + * Write Plot Group (series of related plots) + * + * @param PHPExcel_Chart_DataSeries $plotGroup + * @param string $groupType Type of plot for dataseries + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param boolean &$catIsMultiLevelSeries Is category a multi-series category + * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set + * @param string &$plotGroupingType Type of grouping for multi-series values + * @param PHPExcel_Worksheet $pSheet + * @throws PHPExcel_Writer_Exception + */ + private function _writePlotGroup( $plotGroup, + $groupType, + $objWriter, + &$catIsMultiLevelSeries, + &$valIsMultiLevelSeries, + &$plotGroupingType, + PHPExcel_Worksheet $pSheet + ) + { + if (is_null($plotGroup)) { + return; + } + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) { + $objWriter->startElement('c:barDir'); + $objWriter->writeAttribute('val', $plotGroup->getPlotDirection()); + $objWriter->endElement(); + } + + if (!is_null($plotGroup->getPlotGrouping())) { + $plotGroupingType = $plotGroup->getPlotGrouping(); + $objWriter->startElement('c:grouping'); + $objWriter->writeAttribute('val', $plotGroupingType); + $objWriter->endElement(); + } + + // Get these details before the loop, because we can use the count to check for varyColors + $plotSeriesOrder = $plotGroup->getPlotOrder(); + $plotSeriesCount = count($plotSeriesOrder); + + if (($groupType !== PHPExcel_Chart_DataSeries::TYPE_RADARCHART) && + ($groupType !== PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) { + + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_LINECHART) { + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) || + ($plotSeriesCount > 1)) { + $objWriter->startElement('c:varyColors'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + } else { + $objWriter->startElement('c:varyColors'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + } + } + + foreach($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { + $objWriter->startElement('c:ser'); + + $objWriter->startElement('c:idx'); + $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx); + $objWriter->endElement(); + + $objWriter->startElement('c:order'); + $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef); + $objWriter->endElement(); + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + + $objWriter->startElement('c:dPt'); + $objWriter->startElement('c:idx'); + $objWriter->writeAttribute('val', 3); + $objWriter->endElement(); + + $objWriter->startElement('c:bubble3D'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:spPr'); + $objWriter->startElement('a:solidFill'); + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FF9900'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + } + + // Labels + $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef); + if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) { + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:strRef'); + $this->_writePlotSeriesLabel($plotSeriesLabel, $objWriter); + $objWriter->endElement(); + $objWriter->endElement(); + } + + // Formatting for the points + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_LINECHART) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) { + $objWriter->startElement('c:spPr'); + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', 12700); + if ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) { + $objWriter->startElement('a:noFill'); + $objWriter->endElement(); + } + $objWriter->endElement(); + $objWriter->endElement(); + } + + $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef); + if ($plotSeriesValues) { + $plotSeriesMarker = $plotSeriesValues->getPointMarker(); + if ($plotSeriesMarker) { + $objWriter->startElement('c:marker'); + $objWriter->startElement('c:symbol'); + $objWriter->writeAttribute('val', $plotSeriesMarker); + $objWriter->endElement(); + + if ($plotSeriesMarker !== 'none') { + $objWriter->startElement('c:size'); + $objWriter->writeAttribute('val', 3); + $objWriter->endElement(); + } + $objWriter->endElement(); + } + } + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) || + ($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D) || + ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART)) { + + $objWriter->startElement('c:invertIfNegative'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + + // Category Labels + $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef); + if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) { + $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries(); + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || + ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + + if (!is_null($plotGroup->getPlotStyle())) { + $plotStyle = $plotGroup->getPlotStyle(); + if ($plotStyle) { + $objWriter->startElement('c:explosion'); + $objWriter->writeAttribute('val', 25); + $objWriter->endElement(); + } + } + } + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || + ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) { + $objWriter->startElement('c:xVal'); + } else { + $objWriter->startElement('c:cat'); + } + + $this->_writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet); + $objWriter->endElement(); + } + + // Values + if ($plotSeriesValues) { + $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries(); + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || + ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) { + $objWriter->startElement('c:yVal'); + } else { + $objWriter->startElement('c:val'); + } + + $this->_writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet); + $objWriter->endElement(); + } + + if ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $this->_writeBubbles($plotSeriesValues, $objWriter, $pSheet); + } + + $objWriter->endElement(); + + } + + $this->_seriesIndex += $plotSeriesIdx + 1; + } + + /** + * Write Plot Series Label + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesLabel + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writePlotSeriesLabel($plotSeriesLabel, $objWriter) + { + if (is_null($plotSeriesLabel)) { + return; + } + + $objWriter->startElement('c:f'); + $objWriter->writeRawData($plotSeriesLabel->getDataSource()); + $objWriter->endElement(); + + $objWriter->startElement('c:strCache'); + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount() ); + $objWriter->endElement(); + + foreach($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotLabelKey ); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData( $plotLabelValue ); + $objWriter->endElement(); + $objWriter->endElement(); + } + $objWriter->endElement(); + + } + + /** + * Write Plot Series Values + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $groupType Type of plot for dataseries + * @param string $dataType Datatype of series values + * @param PHPExcel_Worksheet $pSheet + * @throws PHPExcel_Writer_Exception + */ + private function _writePlotSeriesValues( $plotSeriesValues, + $objWriter, + $groupType, + $dataType='str', + PHPExcel_Worksheet $pSheet + ) + { + if (is_null($plotSeriesValues)) { + return; + } + + if ($plotSeriesValues->isMultiLevelSeries()) { + $levelCount = $plotSeriesValues->multiLevelCount(); + + $objWriter->startElement('c:multiLvlStrRef'); + + $objWriter->startElement('c:f'); + $objWriter->writeRawData( $plotSeriesValues->getDataSource() ); + $objWriter->endElement(); + + $objWriter->startElement('c:multiLvlStrCache'); + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() ); + $objWriter->endElement(); + + for ($level = 0; $level < $levelCount; ++$level) { + $objWriter->startElement('c:lvl'); + + foreach($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) { + if (isset($plotSeriesValue[$level])) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey ); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData( $plotSeriesValue[$level] ); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } else { + $objWriter->startElement('c:'.$dataType.'Ref'); + + $objWriter->startElement('c:f'); + $objWriter->writeRawData( $plotSeriesValues->getDataSource() ); + $objWriter->endElement(); + + $objWriter->startElement('c:'.$dataType.'Cache'); + + if (($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART) && + ($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && + ($groupType != PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + + if (($plotSeriesValues->getFormatCode() !== NULL) && + ($plotSeriesValues->getFormatCode() !== '')) { + $objWriter->startElement('c:formatCode'); + $objWriter->writeRawData( $plotSeriesValues->getFormatCode() ); + $objWriter->endElement(); + } + } + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() ); + $objWriter->endElement(); + + $dataValues = $plotSeriesValues->getDataValues(); + if (!empty($dataValues)) { + if (is_array($dataValues)) { + foreach($dataValues as $plotSeriesKey => $plotSeriesValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey ); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData( $plotSeriesValue ); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write Bubble Chart Details + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet) + { + if (is_null($plotSeriesValues)) { + return; + } + + $objWriter->startElement('c:bubbleSize'); + $objWriter->startElement('c:numLit'); + + $objWriter->startElement('c:formatCode'); + $objWriter->writeRawData( 'General' ); + $objWriter->endElement(); + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount() ); + $objWriter->endElement(); + + $dataValues = $plotSeriesValues->getDataValues(); + if (!empty($dataValues)) { + if (is_array($dataValues)) { + foreach($dataValues as $plotSeriesKey => $plotSeriesValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey ); + $objWriter->startElement('c:v'); + $objWriter->writeRawData( 1 ); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + } + + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:bubble3D'); + $objWriter->writeAttribute('val', 0 ); + $objWriter->endElement(); + } + + /** + * Write Layout + * + * @param PHPExcel_Chart_Layout $layout + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeLayout(PHPExcel_Chart_Layout $layout = NULL, $objWriter) + { + $objWriter->startElement('c:layout'); + + if (!is_null($layout)) { + $objWriter->startElement('c:manualLayout'); + + $layoutTarget = $layout->getLayoutTarget(); + if (!is_null($layoutTarget)) { + $objWriter->startElement('c:layoutTarget'); + $objWriter->writeAttribute('val', $layoutTarget); + $objWriter->endElement(); + } + + $xMode = $layout->getXMode(); + if (!is_null($xMode)) { + $objWriter->startElement('c:xMode'); + $objWriter->writeAttribute('val', $xMode); + $objWriter->endElement(); + } + + $yMode = $layout->getYMode(); + if (!is_null($yMode)) { + $objWriter->startElement('c:yMode'); + $objWriter->writeAttribute('val', $yMode); + $objWriter->endElement(); + } + + $x = $layout->getXPosition(); + if (!is_null($x)) { + $objWriter->startElement('c:x'); + $objWriter->writeAttribute('val', $x); + $objWriter->endElement(); + } + + $y = $layout->getYPosition(); + if (!is_null($y)) { + $objWriter->startElement('c:y'); + $objWriter->writeAttribute('val', $y); + $objWriter->endElement(); + } + + $w = $layout->getWidth(); + if (!is_null($w)) { + $objWriter->startElement('c:w'); + $objWriter->writeAttribute('val', $w); + $objWriter->endElement(); + } + + $h = $layout->getHeight(); + if (!is_null($h)) { + $objWriter->startElement('c:h'); + $objWriter->writeAttribute('val', $h); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Alternate Content block + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeAlternateContent($objWriter) + { + $objWriter->startElement('mc:AlternateContent'); + $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + + $objWriter->startElement('mc:Choice'); + $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart'); + $objWriter->writeAttribute('Requires', 'c14'); + + $objWriter->startElement('c14:style'); + $objWriter->writeAttribute('val', '102'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('mc:Fallback'); + $objWriter->startElement('c:style'); + $objWriter->writeAttribute('val', '2'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Printer Settings + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writePrintSettings($objWriter) + { + $objWriter->startElement('c:printSettings'); + + $objWriter->startElement('c:headerFooter'); + $objWriter->endElement(); + + $objWriter->startElement('c:pageMargins'); + $objWriter->writeAttribute('footer', 0.3); + $objWriter->writeAttribute('header', 0.3); + $objWriter->writeAttribute('r', 0.7); + $objWriter->writeAttribute('l', 0.7); + $objWriter->writeAttribute('t', 0.75); + $objWriter->writeAttribute('b', 0.75); + $objWriter->endElement(); + + $objWriter->startElement('c:pageSetup'); + $objWriter->writeAttribute('orientation', "portrait"); + $objWriter->endElement(); + + $objWriter->endElement(); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php new file mode 100644 index 00000000..436219c6 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php @@ -0,0 +1,268 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Comments + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write comments to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeComments(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Comments cache + $comments = $pWorksheet->getComments(); + + // Authors cache + $authors = array(); + $authorId = 0; + foreach ($comments as $comment) { + if (!isset($authors[$comment->getAuthor()])) { + $authors[$comment->getAuthor()] = $authorId++; + } + } + + // comments + $objWriter->startElement('comments'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + + // Loop through authors + $objWriter->startElement('authors'); + foreach ($authors as $author => $index) { + $objWriter->writeElement('author', $author); + } + $objWriter->endElement(); + + // Loop through comments + $objWriter->startElement('commentList'); + foreach ($comments as $key => $value) { + $this->_writeComment($objWriter, $key, $value, $authors); + } + $objWriter->endElement(); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pCellReference Cell reference + * @param PHPExcel_Comment $pComment Comment + * @param array $pAuthors Array of authors + * @throws PHPExcel_Writer_Exception + */ + public function _writeComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null, $pAuthors = null) + { + // comment + $objWriter->startElement('comment'); + $objWriter->writeAttribute('ref', $pCellReference); + $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]); + + // text + $objWriter->startElement('text'); + $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write VML comments to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVMLComments(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Comments cache + $comments = $pWorksheet->getComments(); + + // xml + $objWriter->startElement('xml'); + $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); + + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); + + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t202'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '202'); + $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); + + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Loop through comments + foreach ($comments as $key => $value) { + $this->_writeVMLComment($objWriter, $key, $value); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write VML comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pCellReference Cell reference + * @param PHPExcel_Comment $pComment Comment + * @throws PHPExcel_Writer_Exception + */ + public function _writeVMLComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null) + { + // Metadata + list($column, $row) = PHPExcel_Cell::coordinateFromString($pCellReference); + $column = PHPExcel_Cell::columnIndexFromString($column); + $id = 1024 + $column + $row; + $id = substr($id, 0, 4); + + // v:shape + $objWriter->startElement('v:shape'); + $objWriter->writeAttribute('id', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t202'); + $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden')); + $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('o:insetmode', 'auto'); + + // v:fill + $objWriter->startElement('v:fill'); + $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->endElement(); + + // v:shadow + $objWriter->startElement('v:shadow'); + $objWriter->writeAttribute('on', 't'); + $objWriter->writeAttribute('color', 'black'); + $objWriter->writeAttribute('obscured', 't'); + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('o:connecttype', 'none'); + $objWriter->endElement(); + + // v:textbox + $objWriter->startElement('v:textbox'); + $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); + + // div + $objWriter->startElement('div'); + $objWriter->writeAttribute('style', 'text-align:left'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // x:ClientData + $objWriter->startElement('x:ClientData'); + $objWriter->writeAttribute('ObjectType', 'Note'); + + // x:MoveWithCells + $objWriter->writeElement('x:MoveWithCells', ''); + + // x:SizeWithCells + $objWriter->writeElement('x:SizeWithCells', ''); + + // x:Anchor + //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18'); + + // x:AutoFill + $objWriter->writeElement('x:AutoFill', 'False'); + + // x:Row + $objWriter->writeElement('x:Row', ($row - 1)); + + // x:Column + $objWriter->writeElement('x:Column', ($column - 1)); + + $objWriter->endElement(); + + $objWriter->endElement(); + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php new file mode 100644 index 00000000..3c17a169 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php @@ -0,0 +1,287 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_ContentTypes + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_ContentTypes extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write content types to XML format + * + * @param PHPExcel $pPHPExcel + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeContentTypes(PHPExcel $pPHPExcel = null, $includeCharts = FALSE) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Types + $objWriter->startElement('Types'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types'); + + // Theme + $this->_writeOverrideContentType( + $objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml' + ); + + // Styles + $this->_writeOverrideContentType( + $objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml' + ); + + // Rels + $this->_writeDefaultContentType( + $objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml' + ); + + // XML + $this->_writeDefaultContentType( + $objWriter, 'xml', 'application/xml' + ); + + // VML + $this->_writeDefaultContentType( + $objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing' + ); + + // Workbook + if($pPHPExcel->hasMacros()){ //Macros in workbook ? + // Yes : not standard content but "macroEnabled" + $this->_writeOverrideContentType( + $objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml' + ); + //... and define a new type for the VBA project + $this->_writeDefaultContentType( + $objWriter, 'bin', 'application/vnd.ms-office.vbaProject' + ); + if($pPHPExcel->hasMacrosCertificate()){// signed macros ? + // Yes : add needed information + $this->_writeOverrideContentType( + $objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature' + ); + } + }else{// no macros in workbook, so standard type + $this->_writeOverrideContentType( + $objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml' + ); + } + + // DocProps + $this->_writeOverrideContentType( + $objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml' + ); + + $this->_writeOverrideContentType( + $objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml' + ); + + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (!empty($customPropertyList)) { + $this->_writeOverrideContentType( + $objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml' + ); + } + + // Worksheets + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $this->_writeOverrideContentType( + $objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml' + ); + } + + // Shared strings + $this->_writeOverrideContentType( + $objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml' + ); + + // Add worksheet relationship content types + $chart = 1; + for ($i = 0; $i < $sheetCount; ++$i) { + $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0; + + // We need a drawing relationship for the worksheet if we have either drawings or charts + if (($drawingCount > 0) || ($chartCount > 0)) { + $this->_writeOverrideContentType( + $objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml' + ); + } + + // If we have charts, then we need a chart relationship for every individual chart + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->_writeOverrideContentType( + $objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml' + ); + } + } + } + + // Comments + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet($i)->getComments()) > 0) { + $this->_writeOverrideContentType( + $objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml' + ); + } + } + + // Add media content-types + $aMediaContentTypes = array(); + $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); + for ($i = 0; $i < $mediaCount; ++$i) { + $extension = ''; + $mimeType = ''; + + if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); + $mimeType = $this->_getImageMimeType( $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath() ); + } else if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); + $extension = explode('/', $extension); + $extension = $extension[1]; + + $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); + } + + if (!isset( $aMediaContentTypes[$extension]) ) { + $aMediaContentTypes[$extension] = $mimeType; + + $this->_writeDefaultContentType( + $objWriter, $extension, $mimeType + ); + } + } + if($pPHPExcel->hasRibbonBinObjects()){//Some additional objects in the ribbon ? + //we need to write "Extension" but not already write for media content + $tabRibbonTypes=array_diff($pPHPExcel->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); + foreach($tabRibbonTypes as $aRibbonType){ + $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor + $this->_writeDefaultContentType( + $objWriter, $aRibbonType, $mimeType + ); + } + } + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) { + foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) { + if (!isset( $aMediaContentTypes[strtolower($image->getExtension())]) ) { + $aMediaContentTypes[strtolower($image->getExtension())] = $this->_getImageMimeType( $image->getPath() ); + + $this->_writeDefaultContentType( + $objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())] + ); + } + } + } + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Get image mime type + * + * @param string $pFile Filename + * @return string Mime Type + * @throws PHPExcel_Writer_Exception + */ + private function _getImageMimeType($pFile = '') + { + if (PHPExcel_Shared_File::file_exists($pFile)) { + $image = getimagesize($pFile); + return image_type_to_mime_type($image[2]); + } else { + throw new PHPExcel_Writer_Exception("File $pFile does not exist"); + } + } + + /** + * Write Default content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pPartname Part name + * @param string $pContentType Content type + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefaultContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') + { + if ($pPartname != '' && $pContentType != '') { + // Write content type + $objWriter->startElement('Default'); + $objWriter->writeAttribute('Extension', $pPartname); + $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Override content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pPartname Part name + * @param string $pContentType Content type + * @throws PHPExcel_Writer_Exception + */ + private function _writeOverrideContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') + { + if ($pPartname != '' && $pContentType != '') { + // Write content type + $objWriter->startElement('Override'); + $objWriter->writeAttribute('PartName', $pPartname); + $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php new file mode 100644 index 00000000..cfc30890 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php @@ -0,0 +1,272 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_DocProps + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_DocProps extends PHPExcel_Writer_Excel2007_WriterPart +{ +/** + * Write docProps/app.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsApp(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Properties + $objWriter->startElement('Properties'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); + $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + // Application + $objWriter->writeElement('Application', 'Microsoft Excel'); + + // DocSecurity + $objWriter->writeElement('DocSecurity', '0'); + + // ScaleCrop + $objWriter->writeElement('ScaleCrop', 'false'); + + // HeadingPairs + $objWriter->startElement('HeadingPairs'); + + // Vector + $objWriter->startElement('vt:vector'); + $objWriter->writeAttribute('size', '2'); + $objWriter->writeAttribute('baseType', 'variant'); + + // Variant + $objWriter->startElement('vt:variant'); + $objWriter->writeElement('vt:lpstr', 'Worksheets'); + $objWriter->endElement(); + + // Variant + $objWriter->startElement('vt:variant'); + $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount()); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // TitlesOfParts + $objWriter->startElement('TitlesOfParts'); + + // Vector + $objWriter->startElement('vt:vector'); + $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount()); + $objWriter->writeAttribute('baseType', 'lpstr'); + + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle()); + } + + $objWriter->endElement(); + + $objWriter->endElement(); + + // Company + $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany()); + + // Company + $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager()); + + // LinksUpToDate + $objWriter->writeElement('LinksUpToDate', 'false'); + + // SharedDoc + $objWriter->writeElement('SharedDoc', 'false'); + + // HyperlinksChanged + $objWriter->writeElement('HyperlinksChanged', 'false'); + + // AppVersion + $objWriter->writeElement('AppVersion', '12.0000'); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write docProps/core.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsCore(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // cp:coreProperties + $objWriter->startElement('cp:coreProperties'); + $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); + $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); + $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + + // dc:creator + $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator()); + + // cp:lastModifiedBy + $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy()); + + // dcterms:created + $objWriter->startElement('dcterms:created'); + $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated())); + $objWriter->endElement(); + + // dcterms:modified + $objWriter->startElement('dcterms:modified'); + $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified())); + $objWriter->endElement(); + + // dc:title + $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle()); + + // dc:description + $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription()); + + // dc:subject + $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject()); + + // cp:keywords + $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords()); + + // cp:category + $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory()); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write docProps/custom.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsCustom(PHPExcel $pPHPExcel = null) + { + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (empty($customPropertyList)) { + return; + } + + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // cp:coreProperties + $objWriter->startElement('Properties'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'); + $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + + foreach($customPropertyList as $key => $customProperty) { + $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty); + $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty); + + $objWriter->startElement('property'); + $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); + $objWriter->writeAttribute('pid', $key+2); + $objWriter->writeAttribute('name', $customProperty); + + switch($propertyType) { + case 'i' : + $objWriter->writeElement('vt:i4', $propertyValue); + break; + case 'f' : + $objWriter->writeElement('vt:r8', $propertyValue); + break; + case 'b' : + $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); + break; + case 'd' : + $objWriter->startElement('vt:filetime'); + $objWriter->writeRawData(date(DATE_W3C, $propertyValue)); + $objWriter->endElement(); + break; + default : + $objWriter->writeElement('vt:lpwstr', $propertyValue); + break; + } + + $objWriter->endElement(); + } + + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php new file mode 100644 index 00000000..3c52723a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php @@ -0,0 +1,598 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Drawing + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write drawings to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int &$chartRef Chart ID + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // xdr:wsDr + $objWriter->startElement('xdr:wsDr'); + $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + + // Loop through images and write drawings + $i = 1; + $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + $this->_writeDrawing($objWriter, $iterator->current(), $i); + + $iterator->next(); + ++$i; + } + + if ($includeCharts) { + $chartCount = $pWorksheet->getChartCount(); + // Loop through charts and write the chart position + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i); + } + } + } + + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write drawings to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart $pChart + * @param int $pRelationId + * @throws PHPExcel_Writer_Exception + */ + public function _writeChart(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Chart $pChart = null, $pRelationId = -1) + { + $tl = $pChart->getTopLeftPosition(); + $tl['colRow'] = PHPExcel_Cell::coordinateFromString($tl['cell']); + $br = $pChart->getBottomRightPosition(); + $br['colRow'] = PHPExcel_Cell::coordinateFromString($br['cell']); + + $objWriter->startElement('xdr:twoCellAnchor'); + + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($tl['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['xOffset'])); + $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['yOffset'])); + $objWriter->endElement(); + $objWriter->startElement('xdr:to'); + $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($br['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['xOffset'])); + $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['yOffset'])); + $objWriter->endElement(); + + $objWriter->startElement('xdr:graphicFrame'); + $objWriter->writeAttribute('macro', ''); + $objWriter->startElement('xdr:nvGraphicFramePr'); + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('name', 'Chart '.$pRelationId); + $objWriter->writeAttribute('id', 1025 * $pRelationId); + $objWriter->endElement(); + $objWriter->startElement('xdr:cNvGraphicFramePr'); + $objWriter->startElement('a:graphicFrameLocks'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('xdr:xfrm'); + $objWriter->startElement('a:off'); + $objWriter->writeAttribute('x', '0'); + $objWriter->writeAttribute('y', '0'); + $objWriter->endElement(); + $objWriter->startElement('a:ext'); + $objWriter->writeAttribute('cx', '0'); + $objWriter->writeAttribute('cy', '0'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('a:graphic'); + $objWriter->startElement('a:graphicData'); + $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->startElement('c:chart'); + $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:id', 'rId'.$pRelationId); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('xdr:clientData'); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write drawings to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet_BaseDrawing $pDrawing + * @param int $pRelationId + * @throws PHPExcel_Writer_Exception + */ + public function _writeDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1) + { + if ($pRelationId >= 0) { + // xdr:oneCellAnchor + $objWriter->startElement('xdr:oneCellAnchor'); + // Image location + $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates()); + $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]); + + // xdr:from + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX())); + $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY())); + $objWriter->endElement(); + + // xdr:ext + $objWriter->startElement('xdr:ext'); + $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth())); + $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight())); + $objWriter->endElement(); + + // xdr:pic + $objWriter->startElement('xdr:pic'); + + // xdr:nvPicPr + $objWriter->startElement('xdr:nvPicPr'); + + // xdr:cNvPr + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('id', $pRelationId); + $objWriter->writeAttribute('name', $pDrawing->getName()); + $objWriter->writeAttribute('descr', $pDrawing->getDescription()); + $objWriter->endElement(); + + // xdr:cNvPicPr + $objWriter->startElement('xdr:cNvPicPr'); + + // a:picLocks + $objWriter->startElement('a:picLocks'); + $objWriter->writeAttribute('noChangeAspect', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:blipFill + $objWriter->startElement('xdr:blipFill'); + + // a:blip + $objWriter->startElement('a:blip'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId); + $objWriter->endElement(); + + // a:stretch + $objWriter->startElement('a:stretch'); + $objWriter->writeElement('a:fillRect', null); + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:spPr + $objWriter->startElement('xdr:spPr'); + + // a:xfrm + $objWriter->startElement('a:xfrm'); + $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation())); + $objWriter->endElement(); + + // a:prstGeom + $objWriter->startElement('a:prstGeom'); + $objWriter->writeAttribute('prst', 'rect'); + + // a:avLst + $objWriter->writeElement('a:avLst', null); + + $objWriter->endElement(); + +// // a:solidFill +// $objWriter->startElement('a:solidFill'); + +// // a:srgbClr +// $objWriter->startElement('a:srgbClr'); +// $objWriter->writeAttribute('val', 'FFFFFF'); + +///* SHADE +// // a:shade +// $objWriter->startElement('a:shade'); +// $objWriter->writeAttribute('val', '85000'); +// $objWriter->endElement(); +//*/ + +// $objWriter->endElement(); + +// $objWriter->endElement(); +/* + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '88900'); + $objWriter->writeAttribute('cap', 'sq'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:miter + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + + if ($pDrawing->getShadow()->getVisible()) { + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius())); + $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance())); + $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection())); + $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment()); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB()); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + } +/* + + // a:scene3d + $objWriter->startElement('a:scene3d'); + + // a:camera + $objWriter->startElement('a:camera'); + $objWriter->writeAttribute('prst', 'orthographicFront'); + $objWriter->endElement(); + + // a:lightRig + $objWriter->startElement('a:lightRig'); + $objWriter->writeAttribute('rig', 'twoPt'); + $objWriter->writeAttribute('dir', 't'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ +/* + // a:sp3d + $objWriter->startElement('a:sp3d'); + + // a:bevelT + $objWriter->startElement('a:bevelT'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('h', '19050'); + $objWriter->endElement(); + + // a:contourClr + $objWriter->startElement('a:contourClr'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:clientData + $objWriter->writeElement('xdr:clientData', null); + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write VML header/footer images to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVMLHeaderFooterImages(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Header/footer images + $images = $pWorksheet->getHeaderFooter()->getImages(); + + // xml + $objWriter->startElement('xml'); + $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); + + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); + + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t75'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '75'); + $objWriter->writeAttribute('o:preferrelative', 't'); + $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); + $objWriter->writeAttribute('filled', 'f'); + $objWriter->writeAttribute('stroked', 'f'); + + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); + + // v:formulas + $objWriter->startElement('v:formulas'); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 1 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @2 1 2'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 0 1'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @6 1 2'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('o:extrusionok', 'f'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); + + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('aspectratio', 't'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Loop through images + foreach ($images as $key => $value) { + $this->_writeVMLHeaderFooterImage($objWriter, $key, $value); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write VML comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pReference Reference + * @param PHPExcel_Worksheet_HeaderFooterDrawing $pImage Image + * @throws PHPExcel_Writer_Exception + */ + public function _writeVMLHeaderFooterImage(PHPExcel_Shared_XMLWriter $objWriter = null, $pReference = '', PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null) + { + // Calculate object id + preg_match('{(\d+)}', md5($pReference), $m); + $id = 1500 + (substr($m[1], 0, 2) * 1); + + // Calculate offset + $width = $pImage->getWidth(); + $height = $pImage->getHeight(); + $marginLeft = $pImage->getOffsetX(); + $marginTop = $pImage->getOffsetY(); + + // v:shape + $objWriter->startElement('v:shape'); + $objWriter->writeAttribute('id', $pReference); + $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t75'); + $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); + + // v:imagedata + $objWriter->startElement('v:imagedata'); + $objWriter->writeAttribute('o:relid', 'rId' . $pReference); + $objWriter->writeAttribute('o:title', $pImage->getName()); + $objWriter->endElement(); + + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('rotation', 't'); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + + /** + * Get an array of all drawings + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Worksheet_Drawing[] All drawings in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allDrawings(PHPExcel $pPHPExcel = null) + { + // Get an array of all drawings + $aDrawings = array(); + + // Loop through PHPExcel + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // Loop through images and add to array + $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + $aDrawings[] = $iterator->current(); + + $iterator->next(); + } + } + + return $aDrawings; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php new file mode 100644 index 00000000..0bdb667c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php @@ -0,0 +1,437 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Rels + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Rels extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeRelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (!empty($customPropertyList)) { + // Relationship docProps/app.xml + $this->_writeRelationship( + $objWriter, + 4, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties', + 'docProps/custom.xml' + ); + + } + + // Relationship docProps/app.xml + $this->_writeRelationship( + $objWriter, + 3, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties', + 'docProps/app.xml' + ); + + // Relationship docProps/core.xml + $this->_writeRelationship( + $objWriter, + 2, + 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', + 'docProps/core.xml' + ); + + // Relationship xl/workbook.xml + $this->_writeRelationship( + $objWriter, + 1, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', + 'xl/workbook.xml' + ); + // a custom UI in workbook ? + if($pPHPExcel->hasRibbon()){ + $this->_writeRelationShip( + $objWriter, + 5, + 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility', + $pPHPExcel->getRibbonXMLData('target') + ); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write workbook relationships to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Relationship styles.xml + $this->_writeRelationship( + $objWriter, + 1, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', + 'styles.xml' + ); + + // Relationship theme/theme1.xml + $this->_writeRelationship( + $objWriter, + 2, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme', + 'theme/theme1.xml' + ); + + // Relationship sharedStrings.xml + $this->_writeRelationship( + $objWriter, + 3, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', + 'sharedStrings.xml' + ); + + // Relationships with sheets + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $this->_writeRelationship( + $objWriter, + ($i + 1 + 3), + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', + 'worksheets/sheet' . ($i + 1) . '.xml' + ); + } + // Relationships for vbaProject if needed + // id : just after the last sheet + if($pPHPExcel->hasMacros()){ + $this->_writeRelationShip( + $objWriter, + ($i + 1 + 3), + 'http://schemas.microsoft.com/office/2006/relationships/vbaProject', + 'vbaProject.bin' + ); + ++$i;//increment i if needed for an another relation + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write worksheet relationships to XML format + * + * Numbering is as follows: + * rId1 - Drawings + * rId_hyperlink_x - Hyperlinks + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int $pWorksheetId + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = FALSE) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Write drawing relationships? + $d = 0; + if ($includeCharts) { + $charts = $pWorksheet->getChartCollection(); + } else { + $charts = array(); + } + if (($pWorksheet->getDrawingCollection()->count() > 0) || + (count($charts) > 0)) { + $this->_writeRelationship( + $objWriter, + ++$d, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing', + '../drawings/drawing' . $pWorksheetId . '.xml' + ); + } + + // Write chart relationships? +// $chartCount = 0; +// $charts = $pWorksheet->getChartCollection(); +// echo 'Chart Rels: ' , count($charts) , '<br />'; +// if (count($charts) > 0) { +// foreach($charts as $chart) { +// $this->_writeRelationship( +// $objWriter, +// ++$d, +// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', +// '../charts/chart' . ++$chartCount . '.xml' +// ); +// } +// } +// + // Write hyperlink relationships? + $i = 1; + foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) { + if (!$hyperlink->isInternal()) { + $this->_writeRelationship( + $objWriter, + '_hyperlink_' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', + $hyperlink->getUrl(), + 'External' + ); + + ++$i; + } + } + + // Write comments relationship? + $i = 1; + if (count($pWorksheet->getComments()) > 0) { + $this->_writeRelationship( + $objWriter, + '_comments_vml' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', + '../drawings/vmlDrawing' . $pWorksheetId . '.vml' + ); + + $this->_writeRelationship( + $objWriter, + '_comments' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments', + '../comments' . $pWorksheetId . '.xml' + ); + } + + // Write header/footer relationship? + $i = 1; + if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) { + $this->_writeRelationship( + $objWriter, + '_headerfooter_vml' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', + '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml' + ); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write drawing relationships to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int &$chartRef Chart ID + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = FALSE) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Loop through images and write relationships + $i = 1; + $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing + || $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) { + // Write relationship for image drawing + $this->_writeRelationship( + $objWriter, + $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename()) + ); + } + + $iterator->next(); + ++$i; + } + + if ($includeCharts) { + // Loop through charts and write relationships + $chartCount = $pWorksheet->getChartCount(); + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->_writeRelationship( + $objWriter, + $i++, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', + '../charts/chart' . ++$chartRef . '.xml' + ); + } + } + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write header/footer drawing relationships to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Loop through images and write relationships + foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) { + // Write relationship for image drawing + $this->_writeRelationship( + $objWriter, + $key, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + '../media/' . $value->getIndexedFilename() + ); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write Override content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param int $pId Relationship ID. rId will be prepended! + * @param string $pType Relationship type + * @param string $pTarget Relationship target + * @param string $pTargetMode Relationship target mode + * @throws PHPExcel_Writer_Exception + */ + private function _writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') + { + if ($pType != '' && $pTarget != '') { + // Write relationship + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', 'rId' . $pId); + $objWriter->writeAttribute('Type', $pType); + $objWriter->writeAttribute('Target', $pTarget); + + if ($pTargetMode != '') { + $objWriter->writeAttribute('TargetMode', $pTargetMode); + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php new file mode 100644 index 00000000..f924a1d4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php @@ -0,0 +1,77 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_RelsRibbon + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_RelsRibbon extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships for additional objects of custom UI (ribbon) + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeRibbonRelationships(PHPExcel $pPHPExcel = null){ + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $localRels=$pPHPExcel->getRibbonBinObjects('names'); + if(is_array($localRels)){ + foreach($localRels as $aId=>$aTarget){ + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', $aId); + $objWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); + $objWriter->writeAttribute('Target', $aTarget); + $objWriter->endElement();//Relationship + } + } + $objWriter->endElement();//Relationships + + // Return + return $objWriter->getData(); + + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php new file mode 100644 index 00000000..aecb0b8d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php @@ -0,0 +1,72 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_RelsVBA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_RelsVBA extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships for a signed VBA Project + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVBARelationships(PHPExcel $pPHPExcel = null){ + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', 'rId1'); + $objWriter->writeAttribute('Type', 'http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature'); + $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin'); + $objWriter->endElement();//Relationship + $objWriter->endElement();//Relationships + + // Return + return $objWriter->getData(); + + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php new file mode 100644 index 00000000..0e8a259b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php @@ -0,0 +1,319 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_StringTable + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_StringTable extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Create worksheet stringtable + * + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param string[] $pExistingTable Existing table to eventually merge with + * @return string[] String table for worksheet + * @throws PHPExcel_Writer_Exception + */ + public function createStringTable($pSheet = null, $pExistingTable = null) + { + if ($pSheet !== NULL) { + // Create string lookup table + $aStringTable = array(); + $cellCollection = null; + $aFlippedStringTable = null; // For faster lookup + + // Is an existing table given? + if (($pExistingTable !== NULL) && is_array($pExistingTable)) { + $aStringTable = $pExistingTable; + } + + // Fill index array + $aFlippedStringTable = $this->flipStringTable($aStringTable); + + // Loop through cells + foreach ($pSheet->getCellCollection() as $cellID) { + $cell = $pSheet->getCell($cellID); + $cellValue = $cell->getValue(); + if (!is_object($cellValue) && + ($cellValue !== NULL) && + $cellValue !== '' && + !isset($aFlippedStringTable[$cellValue]) && + ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING2 || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NULL)) { + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue] = true; + } elseif ($cellValue instanceof PHPExcel_RichText && + ($cellValue !== NULL) && + !isset($aFlippedStringTable[$cellValue->getHashCode()])) { + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue->getHashCode()] = true; + } + } + + // Return + return $aStringTable; + } else { + throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed."); + } + } + + /** + * Write string table to XML format + * + * @param string[] $pStringTable + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeStringTable($pStringTable = null) + { + if ($pStringTable !== NULL) { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // String table + $objWriter->startElement('sst'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('uniqueCount', count($pStringTable)); + + // Loop through string table + foreach ($pStringTable as $textElement) { + $objWriter->startElement('si'); + + if (! $textElement instanceof PHPExcel_RichText) { + $textToWrite = PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $textElement ); + $objWriter->startElement('t'); + if ($textToWrite !== trim($textToWrite)) { + $objWriter->writeAttribute('xml:space', 'preserve'); + } + $objWriter->writeRawData($textToWrite); + $objWriter->endElement(); + } else if ($textElement instanceof PHPExcel_RichText) { + $this->writeRichText($objWriter, $textElement); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } else { + throw new PHPExcel_Writer_Exception("Invalid string table array passed."); + } + } + + /** + * Write Rich Text + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_RichText $pRichText Rich text + * @param string $prefix Optional Namespace prefix + * @throws PHPExcel_Writer_Exception + */ + public function writeRichText(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_RichText $pRichText = null, $prefix=NULL) + { + if ($prefix !== NULL) + $prefix .= ':'; + // Loop through rich text elements + $elements = $pRichText->getRichTextElements(); + foreach ($elements as $element) { + // r + $objWriter->startElement($prefix.'r'); + + // rPr + if ($element instanceof PHPExcel_RichText_Run) { + // rPr + $objWriter->startElement($prefix.'rPr'); + + // rFont + $objWriter->startElement($prefix.'rFont'); + $objWriter->writeAttribute('val', $element->getFont()->getName()); + $objWriter->endElement(); + + // Bold + $objWriter->startElement($prefix.'b'); + $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false')); + $objWriter->endElement(); + + // Italic + $objWriter->startElement($prefix.'i'); + $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false')); + $objWriter->endElement(); + + // Superscript / subscript + if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) { + $objWriter->startElement($prefix.'vertAlign'); + if ($element->getFont()->getSuperScript()) { + $objWriter->writeAttribute('val', 'superscript'); + } else if ($element->getFont()->getSubScript()) { + $objWriter->writeAttribute('val', 'subscript'); + } + $objWriter->endElement(); + } + + // Strikethrough + $objWriter->startElement($prefix.'strike'); + $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false')); + $objWriter->endElement(); + + // Color + $objWriter->startElement($prefix.'color'); + $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB()); + $objWriter->endElement(); + + // Size + $objWriter->startElement($prefix.'sz'); + $objWriter->writeAttribute('val', $element->getFont()->getSize()); + $objWriter->endElement(); + + // Underline + $objWriter->startElement($prefix.'u'); + $objWriter->writeAttribute('val', $element->getFont()->getUnderline()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + // t + $objWriter->startElement($prefix.'t'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $element->getText() )); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write Rich Text + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string|PHPExcel_RichText $pRichText text string or Rich text + * @param string $prefix Optional Namespace prefix + * @throws PHPExcel_Writer_Exception + */ + public function writeRichTextForCharts(PHPExcel_Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix=NULL) + { + if (!$pRichText instanceof PHPExcel_RichText) { + $textRun = $pRichText; + $pRichText = new PHPExcel_RichText(); + $pRichText->createTextRun($textRun); + } + + if ($prefix !== NULL) + $prefix .= ':'; + // Loop through rich text elements + $elements = $pRichText->getRichTextElements(); + foreach ($elements as $element) { + // r + $objWriter->startElement($prefix.'r'); + + // rPr + $objWriter->startElement($prefix.'rPr'); + + // Bold + $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0)); + // Italic + $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0)); + // Underline + $underlineType = $element->getFont()->getUnderline(); + switch($underlineType) { + case 'single' : + $underlineType = 'sng'; + break; + case 'double' : + $underlineType = 'dbl'; + break; + } + $objWriter->writeAttribute('u', $underlineType); + // Strikethrough + $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike')); + + // rFont + $objWriter->startElement($prefix.'latin'); + $objWriter->writeAttribute('typeface', $element->getFont()->getName()); + $objWriter->endElement(); + + // Superscript / subscript +// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) { +// $objWriter->startElement($prefix.'vertAlign'); +// if ($element->getFont()->getSuperScript()) { +// $objWriter->writeAttribute('val', 'superscript'); +// } else if ($element->getFont()->getSubScript()) { +// $objWriter->writeAttribute('val', 'subscript'); +// } +// $objWriter->endElement(); +// } +// + $objWriter->endElement(); + + // t + $objWriter->startElement($prefix.'t'); +// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML( $element->getText() )); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Flip string table (for index searching) + * + * @param array $stringTable Stringtable + * @return array + */ + public function flipStringTable($stringTable = array()) { + // Return value + $returnValue = array(); + + // Loop through stringtable and add flipped items to $returnValue + foreach ($stringTable as $key => $value) { + if (! $value instanceof PHPExcel_RichText) { + $returnValue[$value] = $key; + } else if ($value instanceof PHPExcel_RichText) { + $returnValue[$value->getHashCode()] = $key; + } + } + + // Return + return $returnValue; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php new file mode 100644 index 00000000..849ad127 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php @@ -0,0 +1,704 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Style + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Style extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write styles to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeStyles(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // styleSheet + $objWriter->startElement('styleSheet'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + + // numFmts + $objWriter->startElement('numFmts'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count()); + + // numFmt + for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) { + $this->_writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i); + } + + $objWriter->endElement(); + + // fonts + $objWriter->startElement('fonts'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count()); + + // font + for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) { + $this->_writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // fills + $objWriter->startElement('fills'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count()); + + // fill + for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) { + $this->_writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // borders + $objWriter->startElement('borders'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count()); + + // border + for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) { + $this->_writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // cellStyleXfs + $objWriter->startElement('cellStyleXfs'); + $objWriter->writeAttribute('count', 1); + + // xf + $objWriter->startElement('xf'); + $objWriter->writeAttribute('numFmtId', 0); + $objWriter->writeAttribute('fontId', 0); + $objWriter->writeAttribute('fillId', 0); + $objWriter->writeAttribute('borderId', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + // cellXfs + $objWriter->startElement('cellXfs'); + $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection())); + + // xf + foreach ($pPHPExcel->getCellXfCollection() as $cellXf) { + $this->_writeCellStyleXf($objWriter, $cellXf, $pPHPExcel); + } + + $objWriter->endElement(); + + // cellStyles + $objWriter->startElement('cellStyles'); + $objWriter->writeAttribute('count', 1); + + // cellStyle + $objWriter->startElement('cellStyle'); + $objWriter->writeAttribute('name', 'Normal'); + $objWriter->writeAttribute('xfId', 0); + $objWriter->writeAttribute('builtinId', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + // dxfs + $objWriter->startElement('dxfs'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count()); + + // dxf + for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) { + $this->_writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle()); + } + + $objWriter->endElement(); + + // tableStyles + $objWriter->startElement('tableStyles'); + $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9'); + $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function _writeFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // Check if this is a pattern type or gradient type + if ($pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR || + $pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_PATH) { + // Gradient fill + $this->_writeGradientFill($objWriter, $pFill); + } elseif($pFill->getFillType() !== NULL) { + // Pattern fill + $this->_writePatternFill($objWriter, $pFill); + } + } + + /** + * Write Gradient Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function _writeGradientFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // fill + $objWriter->startElement('fill'); + + // gradientFill + $objWriter->startElement('gradientFill'); + $objWriter->writeAttribute('type', $pFill->getFillType()); + $objWriter->writeAttribute('degree', $pFill->getRotation()); + + // stop + $objWriter->startElement('stop'); + $objWriter->writeAttribute('position', '0'); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + + // stop + $objWriter->startElement('stop'); + $objWriter->writeAttribute('position', '1'); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Pattern Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function _writePatternFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // fill + $objWriter->startElement('fill'); + + // patternFill + $objWriter->startElement('patternFill'); + $objWriter->writeAttribute('patternType', $pFill->getFillType()); + + if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) { + // fgColor + if ($pFill->getStartColor()->getARGB()) { + $objWriter->startElement('fgColor'); + $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->endElement(); + } + } + if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) { + // bgColor + if ($pFill->getEndColor()->getARGB()) { + $objWriter->startElement('bgColor'); + $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Font + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Font $pFont Font style + * @throws PHPExcel_Writer_Exception + */ + private function _writeFont(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Font $pFont = null) + { + // font + $objWriter->startElement('font'); + // Weird! The order of these elements actually makes a difference when opening Excel2007 + // files in Excel2003 with the compatibility pack. It's not documented behaviour, + // and makes for a real WTF! + + // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does + // for conditional formatting). Otherwise it will apparently not be picked up in conditional + // formatting style dialog + if ($pFont->getBold() !== NULL) { + $objWriter->startElement('b'); + $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0'); + $objWriter->endElement(); + } + + // Italic + if ($pFont->getItalic() !== NULL) { + $objWriter->startElement('i'); + $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0'); + $objWriter->endElement(); + } + + // Strikethrough + if ($pFont->getStrikethrough() !== NULL) { + $objWriter->startElement('strike'); + $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0'); + $objWriter->endElement(); + } + + // Underline + if ($pFont->getUnderline() !== NULL) { + $objWriter->startElement('u'); + $objWriter->writeAttribute('val', $pFont->getUnderline()); + $objWriter->endElement(); + } + + // Superscript / subscript + if ($pFont->getSuperScript() === TRUE || $pFont->getSubScript() === TRUE) { + $objWriter->startElement('vertAlign'); + if ($pFont->getSuperScript() === TRUE) { + $objWriter->writeAttribute('val', 'superscript'); + } else if ($pFont->getSubScript() === TRUE) { + $objWriter->writeAttribute('val', 'subscript'); + } + $objWriter->endElement(); + } + + // Size + if ($pFont->getSize() !== NULL) { + $objWriter->startElement('sz'); + $objWriter->writeAttribute('val', $pFont->getSize()); + $objWriter->endElement(); + } + + // Foreground color + if ($pFont->getColor()->getARGB() !== NULL) { + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB()); + $objWriter->endElement(); + } + + // Name + if ($pFont->getName() !== NULL) { + $objWriter->startElement('name'); + $objWriter->writeAttribute('val', $pFont->getName()); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Border + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Borders $pBorders Borders style + * @throws PHPExcel_Writer_Exception + */ + private function _writeBorder(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Borders $pBorders = null) + { + // Write border + $objWriter->startElement('border'); + // Diagonal? + switch ($pBorders->getDiagonalDirection()) { + case PHPExcel_Style_Borders::DIAGONAL_UP: + $objWriter->writeAttribute('diagonalUp', 'true'); + $objWriter->writeAttribute('diagonalDown', 'false'); + break; + case PHPExcel_Style_Borders::DIAGONAL_DOWN: + $objWriter->writeAttribute('diagonalUp', 'false'); + $objWriter->writeAttribute('diagonalDown', 'true'); + break; + case PHPExcel_Style_Borders::DIAGONAL_BOTH: + $objWriter->writeAttribute('diagonalUp', 'true'); + $objWriter->writeAttribute('diagonalDown', 'true'); + break; + } + + // BorderPr + $this->_writeBorderPr($objWriter, 'left', $pBorders->getLeft()); + $this->_writeBorderPr($objWriter, 'right', $pBorders->getRight()); + $this->_writeBorderPr($objWriter, 'top', $pBorders->getTop()); + $this->_writeBorderPr($objWriter, 'bottom', $pBorders->getBottom()); + $this->_writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal()); + $objWriter->endElement(); + } + + /** + * Write Cell Style Xf + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style $pStyle Style + * @param PHPExcel $pPHPExcel Workbook + * @throws PHPExcel_Writer_Exception + */ + private function _writeCellStyleXf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null, PHPExcel $pPHPExcel = null) + { + // xf + $objWriter->startElement('xf'); + $objWriter->writeAttribute('xfId', 0); + $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode())); + if ($pStyle->getQuotePrefix()) { + $objWriter->writeAttribute('quotePrefix', 1); + } + + if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) { + $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164) ); + } else { + $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode()); + } + + $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode())); + $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode())); + + // Apply styles? + $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0'); + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('applyProtection', 'true'); + } + + // alignment + $objWriter->startElement('alignment'); + $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); + $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + + $textRotation = 0; + if ($pStyle->getAlignment()->getTextRotation() >= 0) { + $textRotation = $pStyle->getAlignment()->getTextRotation(); + } else if ($pStyle->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + } + $objWriter->writeAttribute('textRotation', $textRotation); + + $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false')); + $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false')); + + if ($pStyle->getAlignment()->getIndent() > 0) { + $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent()); + } + $objWriter->endElement(); + + // protection + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->startElement('protection'); + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + if ($pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Cell Style Dxf + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style $pStyle Style + * @throws PHPExcel_Writer_Exception + */ + private function _writeCellStyleDxf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null) + { + // dxf + $objWriter->startElement('dxf'); + + // font + $this->_writeFont($objWriter, $pStyle->getFont()); + + // numFmt + $this->_writeNumFmt($objWriter, $pStyle->getNumberFormat()); + + // fill + $this->_writeFill($objWriter, $pStyle->getFill()); + + // alignment + $objWriter->startElement('alignment'); + if ($pStyle->getAlignment()->getHorizontal() !== NULL) { + $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); + } + if ($pStyle->getAlignment()->getVertical() !== NULL) { + $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + } + + if ($pStyle->getAlignment()->getTextRotation() !== NULL) { + $textRotation = 0; + if ($pStyle->getAlignment()->getTextRotation() >= 0) { + $textRotation = $pStyle->getAlignment()->getTextRotation(); + } else if ($pStyle->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + } + $objWriter->writeAttribute('textRotation', $textRotation); + } + $objWriter->endElement(); + + // border + $this->_writeBorder($objWriter, $pStyle->getBorders()); + + // protection + if (($pStyle->getProtection()->getLocked() !== NULL) || + ($pStyle->getProtection()->getHidden() !== NULL)) { + if ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT || + $pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->startElement('protection'); + if (($pStyle->getProtection()->getLocked() !== NULL) && + ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) { + $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + if (($pStyle->getProtection()->getHidden() !== NULL) && + ($pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) { + $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + /** + * Write BorderPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pName Element name + * @param PHPExcel_Style_Border $pBorder Border style + * @throws PHPExcel_Writer_Exception + */ + private function _writeBorderPr(PHPExcel_Shared_XMLWriter $objWriter = null, $pName = 'left', PHPExcel_Style_Border $pBorder = null) + { + // Write BorderPr + if ($pBorder->getBorderStyle() != PHPExcel_Style_Border::BORDER_NONE) { + $objWriter->startElement($pName); + $objWriter->writeAttribute('style', $pBorder->getBorderStyle()); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write NumberFormat + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_NumberFormat $pNumberFormat Number Format + * @param int $pId Number Format identifier + * @throws PHPExcel_Writer_Exception + */ + private function _writeNumFmt(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_NumberFormat $pNumberFormat = null, $pId = 0) + { + // Translate formatcode + $formatCode = $pNumberFormat->getFormatCode(); + + // numFmt + if ($formatCode !== NULL) { + $objWriter->startElement('numFmt'); + $objWriter->writeAttribute('numFmtId', ($pId + 164)); + $objWriter->writeAttribute('formatCode', $formatCode); + $objWriter->endElement(); + } + } + + /** + * Get an array of all styles + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style[] All styles in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allStyles(PHPExcel $pPHPExcel = null) + { + $aStyles = $pPHPExcel->getCellXfCollection(); + + return $aStyles; + } + + /** + * Get an array of all conditional styles + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Conditional[] All conditional styles in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allConditionalStyles(PHPExcel $pPHPExcel = null) + { + // Get an array of all styles + $aStyles = array(); + + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) { + foreach ($conditionalStyles as $conditionalStyle) { + $aStyles[] = $conditionalStyle; + } + } + } + + return $aStyles; + } + + /** + * Get an array of all fills + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Fill[] All fills in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allFills(PHPExcel $pPHPExcel = null) + { + // Get an array of unique fills + $aFills = array(); + + // Two first fills are predefined + $fill0 = new PHPExcel_Style_Fill(); + $fill0->setFillType(PHPExcel_Style_Fill::FILL_NONE); + $aFills[] = $fill0; + + $fill1 = new PHPExcel_Style_Fill(); + $fill1->setFillType(PHPExcel_Style_Fill::FILL_PATTERN_GRAY125); + $aFills[] = $fill1; + // The remaining fills + $aStyles = $this->allStyles($pPHPExcel); + foreach ($aStyles as $style) { + if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) { + $aFills[ $style->getFill()->getHashCode() ] = $style->getFill(); + } + } + + return $aFills; + } + + /** + * Get an array of all fonts + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Font[] All fonts in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allFonts(PHPExcel $pPHPExcel = null) + { + // Get an array of unique fonts + $aFonts = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) { + $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont(); + } + } + + return $aFonts; + } + + /** + * Get an array of all borders + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Borders[] All borders in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allBorders(PHPExcel $pPHPExcel = null) + { + // Get an array of unique borders + $aBorders = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) { + $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders(); + } + } + + return $aBorders; + } + + /** + * Get an array of all number formats + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_NumberFormat[] All number formats in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allNumberFormats(PHPExcel $pPHPExcel = null) + { + // Get an array of unique number formats + $aNumFmts = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) { + $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat(); + } + } + + return $aNumFmts; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php new file mode 100644 index 00000000..064c3edc --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php @@ -0,0 +1,871 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Theme + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Theme extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Map of Major fonts to write + * @static array of string + * + */ + private static $_majorFonts = array( + 'Jpan' => 'MS Pゴシック', + 'Hang' => '맑은 고딕', + 'Hans' => '宋体', + 'Hant' => '新細明體', + 'Arab' => 'Times New Roman', + 'Hebr' => 'Times New Roman', + 'Thai' => 'Tahoma', + 'Ethi' => 'Nyala', + 'Beng' => 'Vrinda', + 'Gujr' => 'Shruti', + 'Khmr' => 'MoolBoran', + 'Knda' => 'Tunga', + 'Guru' => 'Raavi', + 'Cans' => 'Euphemia', + 'Cher' => 'Plantagenet Cherokee', + 'Yiii' => 'Microsoft Yi Baiti', + 'Tibt' => 'Microsoft Himalaya', + 'Thaa' => 'MV Boli', + 'Deva' => 'Mangal', + 'Telu' => 'Gautami', + 'Taml' => 'Latha', + 'Syrc' => 'Estrangelo Edessa', + 'Orya' => 'Kalinga', + 'Mlym' => 'Kartika', + 'Laoo' => 'DokChampa', + 'Sinh' => 'Iskoola Pota', + 'Mong' => 'Mongolian Baiti', + 'Viet' => 'Times New Roman', + 'Uigh' => 'Microsoft Uighur', + 'Geor' => 'Sylfaen', + ); + + /** + * Map of Minor fonts to write + * @static array of string + * + */ + private static $_minorFonts = array( + 'Jpan' => 'MS Pゴシック', + 'Hang' => '맑은 고딕', + 'Hans' => '宋体', + 'Hant' => '新細明體', + 'Arab' => 'Arial', + 'Hebr' => 'Arial', + 'Thai' => 'Tahoma', + 'Ethi' => 'Nyala', + 'Beng' => 'Vrinda', + 'Gujr' => 'Shruti', + 'Khmr' => 'DaunPenh', + 'Knda' => 'Tunga', + 'Guru' => 'Raavi', + 'Cans' => 'Euphemia', + 'Cher' => 'Plantagenet Cherokee', + 'Yiii' => 'Microsoft Yi Baiti', + 'Tibt' => 'Microsoft Himalaya', + 'Thaa' => 'MV Boli', + 'Deva' => 'Mangal', + 'Telu' => 'Gautami', + 'Taml' => 'Latha', + 'Syrc' => 'Estrangelo Edessa', + 'Orya' => 'Kalinga', + 'Mlym' => 'Kartika', + 'Laoo' => 'DokChampa', + 'Sinh' => 'Iskoola Pota', + 'Mong' => 'Mongolian Baiti', + 'Viet' => 'Arial', + 'Uigh' => 'Microsoft Uighur', + 'Geor' => 'Sylfaen', + ); + + /** + * Map of core colours + * @static array of string + * + */ + private static $_colourScheme = array( + 'dk2' => '1F497D', + 'lt2' => 'EEECE1', + 'accent1' => '4F81BD', + 'accent2' => 'C0504D', + 'accent3' => '9BBB59', + 'accent4' => '8064A2', + 'accent5' => '4BACC6', + 'accent6' => 'F79646', + 'hlink' => '0000FF', + 'folHlink' => '800080', + ); + + /** + * Write theme to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeTheme(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // a:theme + $objWriter->startElement('a:theme'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $objWriter->writeAttribute('name', 'Office Theme'); + + // a:themeElements + $objWriter->startElement('a:themeElements'); + + // a:clrScheme + $objWriter->startElement('a:clrScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:dk1 + $objWriter->startElement('a:dk1'); + + // a:sysClr + $objWriter->startElement('a:sysClr'); + $objWriter->writeAttribute('val', 'windowText'); + $objWriter->writeAttribute('lastClr', '000000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lt1 + $objWriter->startElement('a:lt1'); + + // a:sysClr + $objWriter->startElement('a:sysClr'); + $objWriter->writeAttribute('val', 'window'); + $objWriter->writeAttribute('lastClr', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:dk2 + $this->_writeColourScheme($objWriter); + + $objWriter->endElement(); + + // a:fontScheme + $objWriter->startElement('a:fontScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:majorFont + $objWriter->startElement('a:majorFont'); + $this->_writeFonts($objWriter, 'Cambria', self::$_majorFonts); + $objWriter->endElement(); + + // a:minorFont + $objWriter->startElement('a:minorFont'); + $this->_writeFonts($objWriter, 'Calibri', self::$_minorFonts); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:fmtScheme + $objWriter->startElement('a:fmtScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:fillStyleLst + $objWriter->startElement('a:fillStyleLst'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '50000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '35000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '37000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '15000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lin + $objWriter->startElement('a:lin'); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '51000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '80000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '93000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '94000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '135000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lin + $objWriter->startElement('a:lin'); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lnStyleLst + $objWriter->startElement('a:lnStyleLst'); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '9525'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '95000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '105000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '38100'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + + + // a:effectStyleLst + $objWriter->startElement('a:effectStyleLst'); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '20000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '38000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:scene3d + $objWriter->startElement('a:scene3d'); + + // a:camera + $objWriter->startElement('a:camera'); + $objWriter->writeAttribute('prst', 'orthographicFront'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lightRig + $objWriter->startElement('a:lightRig'); + $objWriter->writeAttribute('rig', 'threePt'); + $objWriter->writeAttribute('dir', 't'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '1200000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:sp3d + $objWriter->startElement('a:sp3d'); + + // a:bevelT + $objWriter->startElement('a:bevelT'); + $objWriter->writeAttribute('w', '63500'); + $objWriter->writeAttribute('h', '25400'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:bgFillStyleLst + $objWriter->startElement('a:bgFillStyleLst'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '40000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '40000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '45000'); + $objWriter->endElement(); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '99000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '20000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '255000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:path + $objWriter->startElement('a:path'); + $objWriter->writeAttribute('path', 'circle'); + + // a:fillToRect + $objWriter->startElement('a:fillToRect'); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '-80000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '180000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '80000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '30000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '200000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:path + $objWriter->startElement('a:path'); + $objWriter->writeAttribute('path', 'circle'); + + // a:fillToRect + $objWriter->startElement('a:fillToRect'); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '50000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '50000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:objectDefaults + $objWriter->writeElement('a:objectDefaults', null); + + // a:extraClrSchemeLst + $objWriter->writeElement('a:extraClrSchemeLst', null); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write fonts to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @param string $latinFont + * @param array of string $fontSet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + private function _writeFonts($objWriter, $latinFont, $fontSet) + { + // a:latin + $objWriter->startElement('a:latin'); + $objWriter->writeAttribute('typeface', $latinFont); + $objWriter->endElement(); + + // a:ea + $objWriter->startElement('a:ea'); + $objWriter->writeAttribute('typeface', ''); + $objWriter->endElement(); + + // a:cs + $objWriter->startElement('a:cs'); + $objWriter->writeAttribute('typeface', ''); + $objWriter->endElement(); + + foreach($fontSet as $fontScript => $typeface) { + $objWriter->startElement('a:font'); + $objWriter->writeAttribute('script', $fontScript); + $objWriter->writeAttribute('typeface', $typeface); + $objWriter->endElement(); + } + + } + + /** + * Write colour scheme to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + private function _writeColourScheme($objWriter) + { + foreach(self::$_colourScheme as $colourName => $colourValue) { + $objWriter->startElement('a:'.$colourName); + + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $colourValue); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php new file mode 100644 index 00000000..d1fe666e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php @@ -0,0 +1,456 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Workbook + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Workbook extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write workbook to XML format + * + * @param PHPExcel $pPHPExcel + * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorkbook(PHPExcel $pPHPExcel = null, $recalcRequired = FALSE) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // workbook + $objWriter->startElement('workbook'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + // fileVersion + $this->_writeFileVersion($objWriter); + + // workbookPr + $this->_writeWorkbookPr($objWriter); + + // workbookProtection + $this->_writeWorkbookProtection($objWriter, $pPHPExcel); + + // bookViews + if ($this->getParentWriter()->getOffice2003Compatibility() === false) { + $this->_writeBookViews($objWriter, $pPHPExcel); + } + + // sheets + $this->_writeSheets($objWriter, $pPHPExcel); + + // definedNames + $this->_writeDefinedNames($objWriter, $pPHPExcel); + + // calcPr + $this->_writeCalcPr($objWriter,$recalcRequired); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write file version + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeFileVersion(PHPExcel_Shared_XMLWriter $objWriter = null) + { + $objWriter->startElement('fileVersion'); + $objWriter->writeAttribute('appName', 'xl'); + $objWriter->writeAttribute('lastEdited', '4'); + $objWriter->writeAttribute('lowestEdited', '4'); + $objWriter->writeAttribute('rupBuild', '4505'); + $objWriter->endElement(); + } + + /** + * Write WorkbookPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function _writeWorkbookPr(PHPExcel_Shared_XMLWriter $objWriter = null) + { + $objWriter->startElement('workbookPr'); + + if (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) { + $objWriter->writeAttribute('date1904', '1'); + } + + $objWriter->writeAttribute('codeName', 'ThisWorkbook'); + + $objWriter->endElement(); + } + + /** + * Write BookViews + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function _writeBookViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // bookViews + $objWriter->startElement('bookViews'); + + // workbookView + $objWriter->startElement('workbookView'); + + $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex()); + $objWriter->writeAttribute('autoFilterDateGrouping', '1'); + $objWriter->writeAttribute('firstSheet', '0'); + $objWriter->writeAttribute('minimized', '0'); + $objWriter->writeAttribute('showHorizontalScroll', '1'); + $objWriter->writeAttribute('showSheetTabs', '1'); + $objWriter->writeAttribute('showVerticalScroll', '1'); + $objWriter->writeAttribute('tabRatio', '600'); + $objWriter->writeAttribute('visibility', 'visible'); + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write WorkbookProtection + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function _writeWorkbookProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + if ($pPHPExcel->getSecurity()->isSecurityEnabled()) { + $objWriter->startElement('workbookProtection'); + $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false')); + $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false')); + $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false')); + + if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') { + $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword()); + } + + if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') { + $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword()); + } + + $objWriter->endElement(); + } + } + + /** + * Write calcPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing + * @throws PHPExcel_Writer_Exception + */ + private function _writeCalcPr(PHPExcel_Shared_XMLWriter $objWriter = null, $recalcRequired = TRUE) + { + $objWriter->startElement('calcPr'); + + // Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc + // If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit + // because the file has changed + $objWriter->writeAttribute('calcId', '999999'); + $objWriter->writeAttribute('calcMode', 'auto'); + // fullCalcOnLoad isn't needed if we've recalculating for the save + $objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? 1 : 0); + $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? 0 : 1); + + $objWriter->endElement(); + } + + /** + * Write sheets + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheets(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // Write sheets + $objWriter->startElement('sheets'); + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // sheet + $this->_writeSheet( + $objWriter, + $pPHPExcel->getSheet($i)->getTitle(), + ($i + 1), + ($i + 1 + 3), + $pPHPExcel->getSheet($i)->getSheetState() + ); + } + + $objWriter->endElement(); + } + + /** + * Write sheet + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pSheetname Sheet name + * @param int $pSheetId Sheet id + * @param int $pRelId Relationship ID + * @param string $sheetState Sheet state (visible, hidden, veryHidden) + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheet(PHPExcel_Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible') + { + if ($pSheetname != '') { + // Write sheet + $objWriter->startElement('sheet'); + $objWriter->writeAttribute('name', $pSheetname); + $objWriter->writeAttribute('sheetId', $pSheetId); + if ($sheetState != 'visible' && $sheetState != '') { + $objWriter->writeAttribute('state', $sheetState); + } + $objWriter->writeAttribute('r:id', 'rId' . $pRelId); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Defined Names + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefinedNames(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // Write defined names + $objWriter->startElement('definedNames'); + + // Named ranges + if (count($pPHPExcel->getNamedRanges()) > 0) { + // Named ranges + $this->_writeNamedRanges($objWriter, $pPHPExcel); + } + + // Other defined names + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // definedName for autoFilter + $this->_writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i); + + // definedName for Print_Titles + $this->_writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i); + + // definedName for Print_Area + $this->_writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i); + } + + $objWriter->endElement(); + } + + /** + * Write named ranges + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function _writeNamedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel) + { + // Loop named ranges + $namedRanges = $pPHPExcel->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + $this->_writeDefinedNameForNamedRange($objWriter, $namedRange); + } + } + + /** + * Write Defined Name for named range + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_NamedRange $pNamedRange + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefinedNameForNamedRange(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_NamedRange $pNamedRange) + { + // definedName for named range + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', $pNamedRange->getName()); + if ($pNamedRange->getLocalOnly()) { + $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope())); + } + + // Create absolute coordinate and write as raw text + $range = PHPExcel_Cell::splitRange($pNamedRange->getRange()); + for ($i = 0; $i < count($range); $i++) { + $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteReference($range[$i][0]); + if (isset($range[$i][1])) { + $range[$i][1] = PHPExcel_Cell::absoluteReference($range[$i][1]); + } + } + $range = PHPExcel_Cell::buildRange($range); + + $objWriter->writeRawData($range); + + $objWriter->endElement(); + } + + /** + * Write Defined Name for autoFilter + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefinedNameForAutofilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for autoFilter + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + $objWriter->writeAttribute('hidden', '1'); + + // Create absolute coordinate and write as raw text + $range = PHPExcel_Cell::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref so we can make the cell ref absolute + if (strpos($range[0],'!') !== false) { + list($ws,$range[0]) = explode('!',$range[0]); + } + + $range[0] = PHPExcel_Cell::absoluteCoordinate($range[0]); + $range[1] = PHPExcel_Cell::absoluteCoordinate($range[1]); + $range = implode(':', $range); + + $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range); + + $objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefinedNameForPrintTitles(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for PrintTitles + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm.Print_Titles'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + + // Setting string + $settingString = ''; + + // Columns to repeat + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); + + $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + // Rows to repeat + if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $settingString .= ','; + } + + $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop(); + + $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + $objWriter->writeRawData($settingString); + + $objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function _writeDefinedNameForPrintArea(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for PrintArea + if ($pSheet->getPageSetup()->isPrintAreaSet()) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm.Print_Area'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + + // Setting string + $settingString = ''; + + // Print area + $printArea = PHPExcel_Cell::splitRange($pSheet->getPageSetup()->getPrintArea()); + + $chunks = array(); + foreach ($printArea as $printAreaRect) { + $printAreaRect[0] = PHPExcel_Cell::absoluteReference($printAreaRect[0]); + $printAreaRect[1] = PHPExcel_Cell::absoluteReference($printAreaRect[1]); + $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect); + } + + $objWriter->writeRawData(implode(',', $chunks)); + + $objWriter->endElement(); + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php new file mode 100644 index 00000000..7d93f5a4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php @@ -0,0 +1,1220 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write worksheet to XML format + * + * @param PHPExcel_Worksheet $pSheet + * @param string[] $pStringTable + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = FALSE) + { + if (!is_null($pSheet)) { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0','UTF-8','yes'); + + // Worksheet + $objWriter->startElement('worksheet'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + // sheetPr + $this->_writeSheetPr($objWriter, $pSheet); + + // Dimension + $this->_writeDimension($objWriter, $pSheet); + + // sheetViews + $this->_writeSheetViews($objWriter, $pSheet); + + // sheetFormatPr + $this->_writeSheetFormatPr($objWriter, $pSheet); + + // cols + $this->_writeCols($objWriter, $pSheet); + + // sheetData + $this->_writeSheetData($objWriter, $pSheet, $pStringTable); + + // sheetProtection + $this->_writeSheetProtection($objWriter, $pSheet); + + // protectedRanges + $this->_writeProtectedRanges($objWriter, $pSheet); + + // autoFilter + $this->_writeAutoFilter($objWriter, $pSheet); + + // mergeCells + $this->_writeMergeCells($objWriter, $pSheet); + + // conditionalFormatting + $this->_writeConditionalFormatting($objWriter, $pSheet); + + // dataValidations + $this->_writeDataValidations($objWriter, $pSheet); + + // hyperlinks + $this->_writeHyperlinks($objWriter, $pSheet); + + // Print options + $this->_writePrintOptions($objWriter, $pSheet); + + // Page margins + $this->_writePageMargins($objWriter, $pSheet); + + // Page setup + $this->_writePageSetup($objWriter, $pSheet); + + // Header / footer + $this->_writeHeaderFooter($objWriter, $pSheet); + + // Breaks + $this->_writeBreaks($objWriter, $pSheet); + + // Drawings and/or Charts + $this->_writeDrawings($objWriter, $pSheet, $includeCharts); + + // LegacyDrawing + $this->_writeLegacyDrawing($objWriter, $pSheet); + + // LegacyDrawingHF + $this->_writeLegacyDrawingHF($objWriter, $pSheet); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } else { + throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed."); + } + } + + /** + * Write SheetPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheetPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetPr + $objWriter->startElement('sheetPr'); + //$objWriter->writeAttribute('codeName', $pSheet->getTitle()); + if($pSheet->getParent()->hasMacros()){//if the workbook have macros, we need to have codeName for the sheet + if($pSheet->hasCodeName()==false){ + $pSheet->setCodeName($pSheet->getTitle()); + } + $objWriter->writeAttribute('codeName', $pSheet->getCodeName()); + } + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $objWriter->writeAttribute('filterMode', 1); + $pSheet->getAutoFilter()->showHideRows(); + } + + // tabColor + if ($pSheet->isTabColorSet()) { + $objWriter->startElement('tabColor'); + $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); + $objWriter->endElement(); + } + + // outlinePr + $objWriter->startElement('outlinePr'); + $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); + $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); + $objWriter->endElement(); + + // pageSetUpPr + if ($pSheet->getPageSetup()->getFitToPage()) { + $objWriter->startElement('pageSetUpPr'); + $objWriter->writeAttribute('fitToPage', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Dimension + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeDimension(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // dimension + $objWriter->startElement('dimension'); + $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); + $objWriter->endElement(); + } + + /** + * Write SheetViews + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheetViews(PHPExcel_Shared_XMLWriter $objWriter = NULL, PHPExcel_Worksheet $pSheet = NULL) + { + // sheetViews + $objWriter->startElement('sheetViews'); + + // Sheet selected? + $sheetSelected = false; + if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex()) + $sheetSelected = true; + + + // sheetView + $objWriter->startElement('sheetView'); + $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); + $objWriter->writeAttribute('workbookViewId', '0'); + + // Zoom scales + if ($pSheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + } + if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + } + + // View Layout Type + if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + } + + // Gridlines + if ($pSheet->getShowGridlines()) { + $objWriter->writeAttribute('showGridLines', 'true'); + } else { + $objWriter->writeAttribute('showGridLines', 'false'); + } + + // Row and column headers + if ($pSheet->getShowRowColHeaders()) { + $objWriter->writeAttribute('showRowColHeaders', '1'); + } else { + $objWriter->writeAttribute('showRowColHeaders', '0'); + } + + // Right-to-left + if ($pSheet->getRightToLeft()) { + $objWriter->writeAttribute('rightToLeft', 'true'); + } + + $activeCell = $pSheet->getActiveCell(); + + // Pane + $pane = ''; + $topLeftCell = $pSheet->getFreezePane(); + if (($topLeftCell != '') && ($topLeftCell != 'A1')) { + $activeCell = $topLeftCell; + // Calculate freeze coordinates + $xSplit = $ySplit = 0; + + list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell); + $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit); + + // pane + $pane = 'topRight'; + $objWriter->startElement('pane'); + if ($xSplit > 1) + $objWriter->writeAttribute('xSplit', $xSplit - 1); + if ($ySplit > 1) { + $objWriter->writeAttribute('ySplit', $ySplit - 1); + $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft'; + } + $objWriter->writeAttribute('topLeftCell', $topLeftCell); + $objWriter->writeAttribute('activePane', $pane); + $objWriter->writeAttribute('state', 'frozen'); + $objWriter->endElement(); + + if (($xSplit > 1) && ($ySplit > 1)) { + // Write additional selections if more than two panes (ie both an X and a Y split) + $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'topRight'); $objWriter->endElement(); + $objWriter->startElement('selection'); $objWriter->writeAttribute('pane', 'bottomLeft'); $objWriter->endElement(); + } + } + + // Selection +// if ($pane != '') { + // Only need to write selection element if we have a split pane + // We cheat a little by over-riding the active cell selection, setting it to the split cell + $objWriter->startElement('selection'); + if ($pane != '') { + $objWriter->writeAttribute('pane', $pane); + } + $objWriter->writeAttribute('activeCell', $activeCell); + $objWriter->writeAttribute('sqref', $activeCell); + $objWriter->endElement(); +// } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write SheetFormatPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheetFormatPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetFormatPr + $objWriter->startElement('sheetFormatPr'); + + // Default row height + if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { + $objWriter->writeAttribute('customHeight', 'true'); + $objWriter->writeAttribute('defaultRowHeight', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); + } else { + $objWriter->writeAttribute('defaultRowHeight', '14.4'); + } + + // Set Zero Height row + if ((string)$pSheet->getDefaultRowDimension()->getzeroHeight() == '1' || + strtolower((string)$pSheet->getDefaultRowDimension()->getzeroHeight()) == 'true' ) { + $objWriter->writeAttribute('zeroHeight', '1'); + } + + // Default column width + if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { + $objWriter->writeAttribute('defaultColWidth', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth())); + } + + // Outline level - row + $outlineLevelRow = 0; + foreach ($pSheet->getRowDimensions() as $dimension) { + if ($dimension->getOutlineLevel() > $outlineLevelRow) { + $outlineLevelRow = $dimension->getOutlineLevel(); + } + } + $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow); + + // Outline level - column + $outlineLevelCol = 0; + foreach ($pSheet->getColumnDimensions() as $dimension) { + if ($dimension->getOutlineLevel() > $outlineLevelCol) { + $outlineLevelCol = $dimension->getOutlineLevel(); + } + } + $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol); + + $objWriter->endElement(); + } + + /** + * Write Cols + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeCols(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // cols + if (count($pSheet->getColumnDimensions()) > 0) { + $objWriter->startElement('cols'); + + $pSheet->calculateColumnWidths(); + + // Loop through column dimensions + foreach ($pSheet->getColumnDimensions() as $colDimension) { + // col + $objWriter->startElement('col'); + $objWriter->writeAttribute('min', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex())); + $objWriter->writeAttribute('max', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex())); + + if ($colDimension->getWidth() < 0) { + // No width set, apply default of 10 + $objWriter->writeAttribute('width', '9.10'); + } else { + // Width set + $objWriter->writeAttribute('width', PHPExcel_Shared_String::FormatNumber($colDimension->getWidth())); + } + + // Column visibility + if ($colDimension->getVisible() == false) { + $objWriter->writeAttribute('hidden', 'true'); + } + + // Auto size? + if ($colDimension->getAutoSize()) { + $objWriter->writeAttribute('bestFit', 'true'); + } + + // Custom width? + if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { + $objWriter->writeAttribute('customWidth', 'true'); + } + + // Collapsed + if ($colDimension->getCollapsed() == true) { + $objWriter->writeAttribute('collapsed', 'true'); + } + + // Outline level + if ($colDimension->getOutlineLevel() > 0) { + $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel()); + } + + // Style + $objWriter->writeAttribute('style', $colDimension->getXfIndex()); + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write SheetProtection + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheetProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetProtection + $objWriter->startElement('sheetProtection'); + + if ($pSheet->getProtection()->getPassword() != '') { + $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword()); + } + + $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false')); + $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false')); + $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false')); + $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false')); + $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false')); + $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false')); + $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false')); + $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false')); + $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false')); + $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false')); + $objWriter->endElement(); + } + + /** + * Write ConditionalFormatting + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeConditionalFormatting(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Conditional id + $id = 1; + + // Loop through styles in the current worksheet + foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + // WHY was this again? + // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() ) == '') { + // continue; + // } + if ($conditional->getConditionType() != PHPExcel_Style_Conditional::CONDITION_NONE) { + // conditionalFormatting + $objWriter->startElement('conditionalFormatting'); + $objWriter->writeAttribute('sqref', $cellCoordinate); + + // cfRule + $objWriter->startElement('cfRule'); + $objWriter->writeAttribute('type', $conditional->getConditionType()); + $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode( $conditional->getHashCode() )); + $objWriter->writeAttribute('priority', $id++); + + if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS + || + $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT) + && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) { + $objWriter->writeAttribute('operator', $conditional->getOperatorType()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeAttribute('text', $conditional->getText()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))'); + } else if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) { + foreach ($conditional->getConditions() as $formula) { + // Formula + $objWriter->writeElement('formula', $formula); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + } + } + + /** + * Write DataValidations + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeDataValidations(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Datavalidation collection + $dataValidationCollection = $pSheet->getDataValidationCollection(); + + // Write data validations? + if (!empty($dataValidationCollection)) { + $objWriter->startElement('dataValidations'); + $objWriter->writeAttribute('count', count($dataValidationCollection)); + + foreach ($dataValidationCollection as $coordinate => $dv) { + $objWriter->startElement('dataValidation'); + + if ($dv->getType() != '') { + $objWriter->writeAttribute('type', $dv->getType()); + } + + if ($dv->getErrorStyle() != '') { + $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle()); + } + + if ($dv->getOperator() != '') { + $objWriter->writeAttribute('operator', $dv->getOperator()); + } + + $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0')); + $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0')); + $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0')); + $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0')); + + if ($dv->getErrorTitle() !== '') { + $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle()); + } + if ($dv->getError() !== '') { + $objWriter->writeAttribute('error', $dv->getError()); + } + if ($dv->getPromptTitle() !== '') { + $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle()); + } + if ($dv->getPrompt() !== '') { + $objWriter->writeAttribute('prompt', $dv->getPrompt()); + } + + $objWriter->writeAttribute('sqref', $coordinate); + + if ($dv->getFormula1() !== '') { + $objWriter->writeElement('formula1', $dv->getFormula1()); + } + if ($dv->getFormula2() !== '') { + $objWriter->writeElement('formula2', $dv->getFormula2()); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write Hyperlinks + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeHyperlinks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Hyperlink collection + $hyperlinkCollection = $pSheet->getHyperlinkCollection(); + + // Relation ID + $relationId = 1; + + // Write hyperlinks? + if (!empty($hyperlinkCollection)) { + $objWriter->startElement('hyperlinks'); + + foreach ($hyperlinkCollection as $coordinate => $hyperlink) { + $objWriter->startElement('hyperlink'); + + $objWriter->writeAttribute('ref', $coordinate); + if (!$hyperlink->isInternal()) { + $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId); + ++$relationId; + } else { + $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl())); + } + + if ($hyperlink->getTooltip() != '') { + $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip()); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write ProtectedRanges + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeProtectedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + if (count($pSheet->getProtectedCells()) > 0) { + // protectedRanges + $objWriter->startElement('protectedRanges'); + + // Loop protectedRanges + foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + // protectedRange + $objWriter->startElement('protectedRange'); + $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); + $objWriter->writeAttribute('sqref', $protectedCell); + if (!empty($passwordHash)) { + $objWriter->writeAttribute('password', $passwordHash); + } + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write MergeCells + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeMergeCells(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + if (count($pSheet->getMergeCells()) > 0) { + // mergeCells + $objWriter->startElement('mergeCells'); + + // Loop mergeCells + foreach ($pSheet->getMergeCells() as $mergeCell) { + // mergeCell + $objWriter->startElement('mergeCell'); + $objWriter->writeAttribute('ref', $mergeCell); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write PrintOptions + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writePrintOptions(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // printOptions + $objWriter->startElement('printOptions'); + + $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false')); + $objWriter->writeAttribute('gridLinesSet', 'true'); + + if ($pSheet->getPageSetup()->getHorizontalCentered()) { + $objWriter->writeAttribute('horizontalCentered', 'true'); + } + + if ($pSheet->getPageSetup()->getVerticalCentered()) { + $objWriter->writeAttribute('verticalCentered', 'true'); + } + + $objWriter->endElement(); + } + + /** + * Write PageMargins + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writePageMargins(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // pageMargins + $objWriter->startElement('pageMargins'); + $objWriter->writeAttribute('left', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft())); + $objWriter->writeAttribute('right', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight())); + $objWriter->writeAttribute('top', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop())); + $objWriter->writeAttribute('bottom', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom())); + $objWriter->writeAttribute('header', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader())); + $objWriter->writeAttribute('footer', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter())); + $objWriter->endElement(); + } + + /** + * Write AutoFilter + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeAutoFilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + // autoFilter + $objWriter->startElement('autoFilter'); + + // Strip any worksheet reference from the filter coordinates + $range = PHPExcel_Cell::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref + if (strpos($range[0],'!') !== false) { + list($ws,$range[0]) = explode('!',$range[0]); + } + $range = implode(':', $range); + + $objWriter->writeAttribute('ref', str_replace('$','',$range)); + + $columns = $pSheet->getAutoFilter()->getColumns(); + if (count($columns > 0)) { + foreach($columns as $columnID => $column) { + $rules = $column->getRules(); + if (count($rules > 0)) { + $objWriter->startElement('filterColumn'); + $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + + $objWriter->startElement( $column->getFilterType()); + if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) { + $objWriter->writeAttribute('and', 1); + } + + foreach ($rules as $rule) { + if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) && + ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && + ($rule->getValue() === '')) { + // Filter rule for Blanks + $objWriter->writeAttribute('blank', 1); + } elseif($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { + // Dynamic Filter Rule + $objWriter->writeAttribute('type', $rule->getGrouping()); + $val = $column->getAttribute('val'); + if ($val !== NULL) { + $objWriter->writeAttribute('val', $val); + } + $maxVal = $column->getAttribute('maxVal'); + if ($maxVal !== NULL) { + $objWriter->writeAttribute('maxVal', $maxVal); + } + } elseif($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { + // Top 10 Filter Rule + $objWriter->writeAttribute('val', $rule->getValue()); + $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); + $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0')); + } else { + // Filter, DateGroupItem or CustomFilter + $objWriter->startElement($rule->getRuleType()); + + if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { + $objWriter->writeAttribute('operator', $rule->getOperator()); + } + if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) { + // Date Group filters + foreach($rule->getValue() as $key => $value) { + if ($value > '') $objWriter->writeAttribute($key, $value); + } + $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); + } else { + $objWriter->writeAttribute('val', $rule->getValue()); + } + + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + } + + $objWriter->endElement(); + } + } + + /** + * Write PageSetup + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writePageSetup(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // pageSetup + $objWriter->startElement('pageSetup'); + $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); + $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); + + if (!is_null($pSheet->getPageSetup()->getScale())) { + $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); + } + if (!is_null($pSheet->getPageSetup()->getFitToHeight())) { + $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); + } else { + $objWriter->writeAttribute('fitToHeight', '0'); + } + if (!is_null($pSheet->getPageSetup()->getFitToWidth())) { + $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); + } else { + $objWriter->writeAttribute('fitToWidth', '0'); + } + if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) { + $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); + $objWriter->writeAttribute('useFirstPageNumber', '1'); + } + + $objWriter->endElement(); + } + + /** + * Write Header / Footer + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeHeaderFooter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // headerFooter + $objWriter->startElement('headerFooter'); + $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); + $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); + $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); + $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); + + $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); + $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); + $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); + $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); + $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); + $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); + $objWriter->endElement(); + } + + /** + * Write Breaks + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeBreaks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Get row and column breaks + $aRowBreaks = array(); + $aColumnBreaks = array(); + foreach ($pSheet->getBreaks() as $cell => $breakType) { + if ($breakType == PHPExcel_Worksheet::BREAK_ROW) { + $aRowBreaks[] = $cell; + } else if ($breakType == PHPExcel_Worksheet::BREAK_COLUMN) { + $aColumnBreaks[] = $cell; + } + } + + // rowBreaks + if (!empty($aRowBreaks)) { + $objWriter->startElement('rowBreaks'); + $objWriter->writeAttribute('count', count($aRowBreaks)); + $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks)); + + foreach ($aRowBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); + + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', $coords[1]); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + // Second, write column breaks + if (!empty($aColumnBreaks)) { + $objWriter->startElement('colBreaks'); + $objWriter->writeAttribute('count', count($aColumnBreaks)); + $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks)); + + foreach ($aColumnBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); + + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write SheetData + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param string[] $pStringTable String table + * @throws PHPExcel_Writer_Exception + */ + private function _writeSheetData(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pStringTable = null) + { + if (is_array($pStringTable)) { + // Flipped stringtable, for faster index searching + $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable); + + // sheetData + $objWriter->startElement('sheetData'); + + // Get column count + $colCount = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()); + + // Highest row number + $highestRow = $pSheet->getHighestRow(); + + // Loop through cells + $cellsByRow = array(); + foreach ($pSheet->getCellCollection() as $cellID) { + $cellAddress = PHPExcel_Cell::coordinateFromString($cellID); + $cellsByRow[$cellAddress[1]][] = $cellID; + } + + $currentRow = 0; + while($currentRow++ < $highestRow) { + // Get row dimension + $rowDimension = $pSheet->getRowDimension($currentRow); + + // Write current row? + $writeCurrentRow = isset($cellsByRow[$currentRow]) || + $rowDimension->getRowHeight() >= 0 || + $rowDimension->getVisible() == false || + $rowDimension->getCollapsed() == true || + $rowDimension->getOutlineLevel() > 0 || + $rowDimension->getXfIndex() !== null; + + if ($writeCurrentRow) { + // Start a new row + $objWriter->startElement('row'); + $objWriter->writeAttribute('r', $currentRow); + $objWriter->writeAttribute('spans', '1:' . $colCount); + + // Row dimensions + if ($rowDimension->getRowHeight() >= 0) { + $objWriter->writeAttribute('customHeight', '1'); + $objWriter->writeAttribute('ht', PHPExcel_Shared_String::FormatNumber($rowDimension->getRowHeight())); + } + + // Row visibility + if ($rowDimension->getVisible() == false) { + $objWriter->writeAttribute('hidden', 'true'); + } + + // Collapsed + if ($rowDimension->getCollapsed() == true) { + $objWriter->writeAttribute('collapsed', 'true'); + } + + // Outline level + if ($rowDimension->getOutlineLevel() > 0) { + $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel()); + } + + // Style + if ($rowDimension->getXfIndex() !== null) { + $objWriter->writeAttribute('s', $rowDimension->getXfIndex()); + $objWriter->writeAttribute('customFormat', '1'); + } + + // Write cells + if (isset($cellsByRow[$currentRow])) { + foreach($cellsByRow[$currentRow] as $cellAddress) { + // Write cell + $this->_writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable); + } + } + + // End row + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Cell + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param PHPExcel_Cell $pCellAddress Cell Address + * @param string[] $pStringTable String table + * @param string[] $pFlippedStringTable String table (flipped), for faster index searching + * @throws PHPExcel_Writer_Exception + */ + private function _writeCell(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null) + { + if (is_array($pStringTable) && is_array($pFlippedStringTable)) { + // Cell + $pCell = $pSheet->getCell($pCellAddress); + $objWriter->startElement('c'); + $objWriter->writeAttribute('r', $pCellAddress); + + // Sheet styles + if ($pCell->getXfIndex() != '') { + $objWriter->writeAttribute('s', $pCell->getXfIndex()); + } + + // If cell value is supplied, write cell value + $cellValue = $pCell->getValue(); + if (is_object($cellValue) || $cellValue !== '') { + // Map type + $mappedType = $pCell->getDataType(); + + // Write data type depending on its type + switch (strtolower($mappedType)) { + case 'inlinestr': // Inline string + case 's': // String + case 'b': // Boolean + $objWriter->writeAttribute('t', $mappedType); + break; + case 'f': // Formula + $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ? + $pCell->getCalculatedValue() : + $cellValue; + if (is_string($calculatedValue)) { + $objWriter->writeAttribute('t', 'str'); + } + break; + case 'e': // Error + $objWriter->writeAttribute('t', $mappedType); + } + + // Write data depending on its type + switch (strtolower($mappedType)) { + case 'inlinestr': // Inline string + if (! $cellValue instanceof PHPExcel_RichText) { + $objWriter->writeElement('t', PHPExcel_Shared_String::ControlCharacterPHP2OOXML( htmlspecialchars($cellValue) ) ); + } else if ($cellValue instanceof PHPExcel_RichText) { + $objWriter->startElement('is'); + $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue); + $objWriter->endElement(); + } + + break; + case 's': // String + if (! $cellValue instanceof PHPExcel_RichText) { + if (isset($pFlippedStringTable[$cellValue])) { + $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]); + } + } else if ($cellValue instanceof PHPExcel_RichText) { + $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]); + } + + break; + case 'f': // Formula + $attributes = $pCell->getFormulaAttributes(); + if($attributes['t'] == 'array') { + $objWriter->startElement('f'); + $objWriter->writeAttribute('t', 'array'); + $objWriter->writeAttribute('ref', $pCellAddress); + $objWriter->writeAttribute('aca', '1'); + $objWriter->writeAttribute('ca', '1'); + $objWriter->text(substr($cellValue, 1)); + $objWriter->endElement(); + } else { + $objWriter->writeElement('f', substr($cellValue, 1)); + } + if ($this->getParentWriter()->getOffice2003Compatibility() === false) { + if ($this->getParentWriter()->getPreCalculateFormulas()) { +// $calculatedValue = $pCell->getCalculatedValue(); + if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') { + $objWriter->writeElement('v', PHPExcel_Shared_String::FormatNumber($calculatedValue)); + } else { + $objWriter->writeElement('v', '0'); + } + } else { + $objWriter->writeElement('v', '0'); + } + } + break; + case 'n': // Numeric + // force point as decimal separator in case current locale uses comma + $objWriter->writeElement('v', str_replace(',', '.', $cellValue)); + break; + case 'b': // Boolean + $objWriter->writeElement('v', ($cellValue ? '1' : '0')); + break; + case 'e': // Error + if (substr($cellValue, 0, 1) == '=') { + $objWriter->writeElement('f', substr($cellValue, 1)); + $objWriter->writeElement('v', substr($cellValue, 1)); + } else { + $objWriter->writeElement('v', $cellValue); + } + + break; + } + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Drawings + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @throws PHPExcel_Writer_Exception + */ + private function _writeDrawings(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $includeCharts = FALSE) + { + $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; + // If sheet contains drawings, add the relationships + if (($pSheet->getDrawingCollection()->count() > 0) || + ($chartCount > 0)) { + $objWriter->startElement('drawing'); + $objWriter->writeAttribute('r:id', 'rId1'); + $objWriter->endElement(); + } + } + + /** + * Write LegacyDrawing + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeLegacyDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // If sheet contains comments, add the relationships + if (count($pSheet->getComments()) > 0) { + $objWriter->startElement('legacyDrawing'); + $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); + $objWriter->endElement(); + } + } + + /** + * Write LegacyDrawingHF + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function _writeLegacyDrawingHF(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // If sheet contains images, add the relationships + if (count($pSheet->getHeaderFooter()->getImages()) > 0) { + $objWriter->startElement('legacyDrawingHF'); + $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); + $objWriter->endElement(); + } + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php new file mode 100644 index 00000000..982117bc --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php @@ -0,0 +1,81 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel2007_WriterPart + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +abstract class PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Parent IWriter object + * + * @var PHPExcel_Writer_IWriter + */ + private $_parentWriter; + + /** + * Set parent IWriter object + * + * @param PHPExcel_Writer_IWriter $pWriter + * @throws PHPExcel_Writer_Exception + */ + public function setParentWriter(PHPExcel_Writer_IWriter $pWriter = null) { + $this->_parentWriter = $pWriter; + } + + /** + * Get parent IWriter object + * + * @return PHPExcel_Writer_IWriter + * @throws PHPExcel_Writer_Exception + */ + public function getParentWriter() { + if (!is_null($this->_parentWriter)) { + return $this->_parentWriter; + } else { + throw new PHPExcel_Writer_Exception("No parent PHPExcel_Writer_IWriter assigned."); + } + } + + /** + * Set parent IWriter object + * + * @param PHPExcel_Writer_IWriter $pWriter + * @throws PHPExcel_Writer_Exception + */ + public function __construct(PHPExcel_Writer_IWriter $pWriter = null) { + if (!is_null($pWriter)) { + $this->_parentWriter = $pWriter; + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php new file mode 100644 index 00000000..3f816fa1 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php @@ -0,0 +1,935 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel5 + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5 extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * PHPExcel object + * + * @var PHPExcel + */ + private $_phpExcel; + + /** + * Total number of shared strings in workbook + * + * @var int + */ + private $_str_total = 0; + + /** + * Number of unique shared strings in workbook + * + * @var int + */ + private $_str_unique = 0; + + /** + * Array of unique shared strings in workbook + * + * @var array + */ + private $_str_table = array(); + + /** + * Color cache. Mapping between RGB value and color index. + * + * @var array + */ + private $_colors; + + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $_parser; + + /** + * Identifier clusters for drawings. Used in MSODRAWINGGROUP record. + * + * @var array + */ + private $_IDCLs; + + /** + * Basic OLE object summary information + * + * @var array + */ + private $_summaryInformation; + + /** + * Extended OLE object document summary information + * + * @var array + */ + private $_documentSummaryInformation; + + /** + * Create a new PHPExcel_Writer_Excel5 + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) { + $this->_phpExcel = $phpExcel; + + $this->_parser = new PHPExcel_Writer_Excel5_Parser(); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) { + + // garbage collect + $this->_phpExcel->garbageCollect(); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE); + $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + + // initialize colors array + $this->_colors = array(); + + // Initialise workbook writer + $this->_writerWorkbook = new PHPExcel_Writer_Excel5_Workbook($this->_phpExcel, + $this->_str_total, $this->_str_unique, $this->_str_table, + $this->_colors, $this->_parser); + + // Initialise worksheet writers + $countSheets = $this->_phpExcel->getSheetCount(); + for ($i = 0; $i < $countSheets; ++$i) { + $this->_writerWorksheets[$i] = new PHPExcel_Writer_Excel5_Worksheet($this->_str_total, $this->_str_unique, + $this->_str_table, $this->_colors, + $this->_parser, + $this->_preCalculateFormulas, + $this->_phpExcel->getSheet($i)); + } + + // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook. + $this->_buildWorksheetEschers(); + $this->_buildWorkbookEscher(); + + // add 15 identical cell style Xfs + // for now, we use the first cellXf instead of cellStyleXf + $cellXfCollection = $this->_phpExcel->getCellXfCollection(); + for ($i = 0; $i < 15; ++$i) { + $this->_writerWorkbook->addXfWriter($cellXfCollection[0], true); + } + + // add all the cell Xfs + foreach ($this->_phpExcel->getCellXfCollection() as $style) { + $this->_writerWorkbook->addXfWriter($style, false); + } + + // add fonts from rich text eleemnts + for ($i = 0; $i < $countSheets; ++$i) { + foreach ($this->_writerWorksheets[$i]->_phpSheet->getCellCollection() as $cellID) { + $cell = $this->_writerWorksheets[$i]->_phpSheet->getCell($cellID); + $cVal = $cell->getValue(); + if ($cVal instanceof PHPExcel_RichText) { + $elements = $cVal->getRichTextElements(); + foreach ($elements as $element) { + if ($element instanceof PHPExcel_RichText_Run) { + $font = $element->getFont(); + $this->_writerWorksheets[$i]->_fntHashIndex[$font->getHashCode()] = $this->_writerWorkbook->_addFont($font); + } + } + } + } + } + + // initialize OLE file + $workbookStreamName = 'Workbook'; + $OLE = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs($workbookStreamName)); + + // Write the worksheet streams before the global workbook stream, + // because the byte sizes of these are needed in the global workbook stream + $worksheetSizes = array(); + for ($i = 0; $i < $countSheets; ++$i) { + $this->_writerWorksheets[$i]->close(); + $worksheetSizes[] = $this->_writerWorksheets[$i]->_datasize; + } + + // add binary data for global workbook stream + $OLE->append($this->_writerWorkbook->writeWorkbook($worksheetSizes)); + + // add binary data for sheet streams + for ($i = 0; $i < $countSheets; ++$i) { + $OLE->append($this->_writerWorksheets[$i]->getData()); + } + + $this->_documentSummaryInformation = $this->_writeDocumentSummaryInformation(); + // initialize OLE Document Summary Information + if(isset($this->_documentSummaryInformation) && !empty($this->_documentSummaryInformation)){ + $OLE_DocumentSummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation')); + $OLE_DocumentSummaryInformation->append($this->_documentSummaryInformation); + } + + $this->_summaryInformation = $this->_writeSummaryInformation(); + // initialize OLE Summary Information + if(isset($this->_summaryInformation) && !empty($this->_summaryInformation)){ + $OLE_SummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation')); + $OLE_SummaryInformation->append($this->_summaryInformation); + } + + // define OLE Parts + $arrRootData = array($OLE); + // initialize OLE Properties file + if(isset($OLE_SummaryInformation)){ + $arrRootData[] = $OLE_SummaryInformation; + } + // initialize OLE Extended Properties file + if(isset($OLE_DocumentSummaryInformation)){ + $arrRootData[] = $OLE_DocumentSummaryInformation; + } + + $root = new PHPExcel_Shared_OLE_PPS_Root(time(), time(), $arrRootData); + // save the OLE file + $res = $root->save($pFilename); + + PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Set temporary storage directory + * + * @deprecated + * @param string $pValue Temporary storage directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_Excel5 + */ + public function setTempDir($pValue = '') { + return $this; + } + + /** + * Build the Worksheet Escher objects + * + */ + private function _buildWorksheetEschers() + { + // 1-based index to BstoreContainer + $blipIndex = 0; + $lastReducedSpId = 0; + $lastSpId = 0; + + foreach ($this->_phpExcel->getAllsheets() as $sheet) { + // sheet index + $sheetIndex = $sheet->getParent()->getIndex($sheet); + + $escher = null; + + // check if there are any shapes for this sheet + $filterRange = $sheet->getAutoFilter()->getRange(); + if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) { + continue; + } + + // create intermediate Escher object + $escher = new PHPExcel_Shared_Escher(); + + // dgContainer + $dgContainer = new PHPExcel_Shared_Escher_DgContainer(); + + // set the drawing index (we use sheet index + 1) + $dgId = $sheet->getParent()->getIndex($sheet) + 1; + $dgContainer->setDgId($dgId); + $escher->setDgContainer($dgContainer); + + // spgrContainer + $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer(); + $dgContainer->setSpgrContainer($spgrContainer); + + // add one shape which is the group shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + $spContainer->setSpgr(true); + $spContainer->setSpType(0); + $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10); + $spgrContainer->addChild($spContainer); + + // add the shapes + + $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet + + foreach ($sheet->getDrawingCollection() as $drawing) { + ++$blipIndex; + + ++$countShapes[$sheetIndex]; + + // add the shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + + // set the shape type + $spContainer->setSpType(0x004B); + // set the shape flag + $spContainer->setSpFlag(0x02); + + // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) + $reducedSpId = $countShapes[$sheetIndex]; + $spId = $reducedSpId + | ($sheet->getParent()->getIndex($sheet) + 1) << 10; + $spContainer->setSpId($spId); + + // keep track of last reducedSpId + $lastReducedSpId = $reducedSpId; + + // keep track of last spId + $lastSpId = $spId; + + // set the BLIP index + $spContainer->setOPT(0x4104, $blipIndex); + + // set coordinates and offsets, client anchor + $coordinates = $drawing->getCoordinates(); + $offsetX = $drawing->getOffsetX(); + $offsetY = $drawing->getOffsetY(); + $width = $drawing->getWidth(); + $height = $drawing->getHeight(); + + $twoAnchor = PHPExcel_Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height); + + $spContainer->setStartCoordinates($twoAnchor['startCoordinates']); + $spContainer->setStartOffsetX($twoAnchor['startOffsetX']); + $spContainer->setStartOffsetY($twoAnchor['startOffsetY']); + $spContainer->setEndCoordinates($twoAnchor['endCoordinates']); + $spContainer->setEndOffsetX($twoAnchor['endOffsetX']); + $spContainer->setEndOffsetY($twoAnchor['endOffsetY']); + + $spgrContainer->addChild($spContainer); + } + + // AutoFilters + if(!empty($filterRange)){ + $rangeBounds = PHPExcel_Cell::rangeBoundaries($filterRange); + $iNumColStart = $rangeBounds[0][0]; + $iNumColEnd = $rangeBounds[1][0]; + + $iInc = $iNumColStart; + while($iInc <= $iNumColEnd){ + ++$countShapes[$sheetIndex]; + + // create an Drawing Object for the dropdown + $oDrawing = new PHPExcel_Worksheet_BaseDrawing(); + // get the coordinates of drawing + $cDrawing = PHPExcel_Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1]; + $oDrawing->setCoordinates($cDrawing); + $oDrawing->setWorksheet($sheet); + + // add the shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + // set the shape type + $spContainer->setSpType(0x00C9); + // set the shape flag + $spContainer->setSpFlag(0x01); + + // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) + $reducedSpId = $countShapes[$sheetIndex]; + $spId = $reducedSpId + | ($sheet->getParent()->getIndex($sheet) + 1) << 10; + $spContainer->setSpId($spId); + + // keep track of last reducedSpId + $lastReducedSpId = $reducedSpId; + + // keep track of last spId + $lastSpId = $spId; + + $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping + $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape + $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest + $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash + $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint + + // set coordinates and offsets, client anchor + $endCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::stringFromColumnIndex($iInc - 1)); + $endCoordinates .= $rangeBounds[0][1] + 1; + + $spContainer->setStartCoordinates($cDrawing); + $spContainer->setStartOffsetX(0); + $spContainer->setStartOffsetY(0); + $spContainer->setEndCoordinates($endCoordinates); + $spContainer->setEndOffsetX(0); + $spContainer->setEndOffsetY(0); + + $spgrContainer->addChild($spContainer); + $iInc++; + } + } + + // identifier clusters, used for workbook Escher object + $this->_IDCLs[$dgId] = $lastReducedSpId; + + // set last shape index + $dgContainer->setLastSpId($lastSpId); + + // set the Escher object + $this->_writerWorksheets[$sheetIndex]->setEscher($escher); + } + } + + /** + * Build the Escher object corresponding to the MSODRAWINGGROUP record + */ + private function _buildWorkbookEscher() + { + $escher = null; + + // any drawings in this workbook? + $found = false; + foreach ($this->_phpExcel->getAllSheets() as $sheet) { + if (count($sheet->getDrawingCollection()) > 0) { + $found = true; + break; + } + } + + // nothing to do if there are no drawings + if (!$found) { + return; + } + + // if we reach here, then there are drawings in the workbook + $escher = new PHPExcel_Shared_Escher(); + + // dggContainer + $dggContainer = new PHPExcel_Shared_Escher_DggContainer(); + $escher->setDggContainer($dggContainer); + + // set IDCLs (identifier clusters) + $dggContainer->setIDCLs($this->_IDCLs); + + // this loop is for determining maximum shape identifier of all drawing + $spIdMax = 0; + $totalCountShapes = 0; + $countDrawings = 0; + + foreach ($this->_phpExcel->getAllsheets() as $sheet) { + $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet + + if (count($sheet->getDrawingCollection()) > 0) { + ++$countDrawings; + + foreach ($sheet->getDrawingCollection() as $drawing) { + ++$sheetCountShapes; + ++$totalCountShapes; + + $spId = $sheetCountShapes + | ($this->_phpExcel->getIndex($sheet) + 1) << 10; + $spIdMax = max($spId, $spIdMax); + } + } + } + + $dggContainer->setSpIdMax($spIdMax + 1); + $dggContainer->setCDgSaved($countDrawings); + $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing + + // bstoreContainer + $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer(); + $dggContainer->setBstoreContainer($bstoreContainer); + + // the BSE's (all the images) + foreach ($this->_phpExcel->getAllsheets() as $sheet) { + foreach ($sheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + + $filename = $drawing->getPath(); + + list($imagesx, $imagesy, $imageFormat) = getimagesize($filename); + + switch ($imageFormat) { + + case 1: // GIF, not supported by BIFF8, we convert to PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + ob_start(); + imagepng(imagecreatefromgif($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + break; + + case 2: // JPEG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG; + $blipData = file_get_contents($filename); + break; + + case 3: // PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + $blipData = file_get_contents($filename); + break; + + case 6: // Windows DIB (BMP), we convert to PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + ob_start(); + imagepng(PHPExcel_Shared_Drawing::imagecreatefrombmp($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + break; + + default: continue 2; + + } + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($blipData); + + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + + } else if ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) { + + switch ($drawing->getRenderingFunction()) { + + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG: + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG; + $renderingFunction = 'imagejpeg'; + break; + + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF: + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG: + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT: + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + $renderingFunction = 'imagepng'; + break; + + } + + ob_start(); + call_user_func($renderingFunction, $drawing->getImageResource()); + $blipData = ob_get_contents(); + ob_end_clean(); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($blipData); + + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + } + } + } + + // Set the Escher object + $this->_writerWorkbook->setEscher($escher); + } + + /** + * Build the OLE Part for DocumentSummary Information + * @return string + */ + private function _writeDocumentSummaryInformation(){ + + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + $data = pack('v', 0xFFFE); + // offset: 2; size: 2; + $data .= pack('v', 0x0000); + // offset: 4; size: 2; OS version + $data .= pack('v', 0x0106); + // offset: 6; size: 2; OS indicator + $data .= pack('v', 0x0002); + // offset: 8; size: 16 + $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); + // offset: 24; size: 4; section count + $data .= pack('V', 0x0001); + + // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae + $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9); + // offset: 44; size: 4; offset of the start + $data .= pack('V', 0x30); + + // SECTION + $dataSection = array(); + $dataSection_NumProps = 0; + $dataSection_Summary = ''; + $dataSection_Content = ''; + + // GKPIDDSI_CODEPAGE: CodePage + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer + 'data' => array('data' => 1252)); + $dataSection_NumProps++; + + // GKPIDDSI_CATEGORY : Category + if($this->_phpExcel->getProperties()->getCategory()){ + $dataProp = $this->_phpExcel->getProperties()->getCategory(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // GKPIDDSI_VERSION :Version of the application that wrote the property storage + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x03), + 'data' => array('pack' => 'V', 'data' => 0x000C0000)); + $dataSection_NumProps++; + // GKPIDDSI_SCALE : FALSE + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_SHAREDOC : FALSE + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + + // GKPIDDSI_DOCSPARTS + // MS-OSHARED p75 (2.3.3.2.2.1) + // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9) + // cElements + $dataProp = pack('v', 0x0001); + $dataProp .= pack('v', 0x0000); + // array of UnalignedLpstr + // cch + $dataProp .= pack('v', 0x000A); + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= 'Worksheet'.chr(0); + + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x101E), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + + // GKPIDDSI_HEADINGPAIR + // VtVecHeadingPairValue + // cElements + $dataProp = pack('v', 0x0002); + $dataProp .= pack('v', 0x0000); + // Array of vtHeadingPair + // vtUnalignedString - headingString + // stringType + $dataProp .= pack('v', 0x001E); + // padding + $dataProp .= pack('v', 0x0000); + // UnalignedLpstr + // cch + $dataProp .= pack('v', 0x0013); + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= 'Feuilles de calcul'; + // vtUnalignedString - headingParts + // wType : 0x0003 = 32 bit signed integer + $dataProp .= pack('v', 0x0300); + // padding + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= pack('v', 0x0100); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x100C), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + + // 4 Section Length + // 4 Property count + // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) + $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; + foreach ($dataSection as $dataProp){ + // Summary + $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); + // Offset + $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); + // DataType + $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); + // Data + if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } + elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } + elseif($dataProp['type']['data'] == 0x0B){ // Boolean + if($dataProp['data']['data'] == false){ + $dataSection_Content .= pack('V', 0x0000); + } else { + $dataSection_Content .= pack('V', 0x0001); + } + $dataSection_Content_Offset += 4 + 4; + } + elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length + // Null-terminated string + $dataProp['data']['data'] .= chr(0); + $dataProp['data']['length'] += 1; + // Complete the string with null string for being a %4 + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); + + $dataSection_Content .= pack('V', $dataProp['data']['length']); + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); + } + elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 8; + } + else { + // Data Type Not Used at the moment + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + $dataProp['data']['length']; + } + } + // Now $dataSection_Content_Offset contains the size of the content + + // section header + // offset: $secOffset; size: 4; section length + // + x Size of the content (summary + content) + $data .= pack('V', $dataSection_Content_Offset); + // offset: $secOffset+4; size: 4; property count + $data .= pack('V', $dataSection_NumProps); + // Section Summary + $data .= $dataSection_Summary; + // Section Content + $data .= $dataSection_Content; + + return $data; + } + + /** + * Build the OLE Part for Summary Information + * @return string + */ + private function _writeSummaryInformation(){ + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + $data = pack('v', 0xFFFE); + // offset: 2; size: 2; + $data .= pack('v', 0x0000); + // offset: 4; size: 2; OS version + $data .= pack('v', 0x0106); + // offset: 6; size: 2; OS indicator + $data .= pack('v', 0x0002); + // offset: 8; size: 16 + $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); + // offset: 24; size: 4; section count + $data .= pack('V', 0x0001); + + // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 + $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3); + // offset: 44; size: 4; offset of the start + $data .= pack('V', 0x30); + + // SECTION + $dataSection = array(); + $dataSection_NumProps = 0; + $dataSection_Summary = ''; + $dataSection_Content = ''; + + // CodePage : CP-1252 + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer + 'data' => array('data' => 1252)); + $dataSection_NumProps++; + + // Title + if($this->_phpExcel->getProperties()->getTitle()){ + $dataProp = $this->_phpExcel->getProperties()->getTitle(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Subject + if($this->_phpExcel->getProperties()->getSubject()){ + $dataProp = $this->_phpExcel->getProperties()->getSubject(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Author (Creator) + if($this->_phpExcel->getProperties()->getCreator()){ + $dataProp = $this->_phpExcel->getProperties()->getCreator(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Keywords + if($this->_phpExcel->getProperties()->getKeywords()){ + $dataProp = $this->_phpExcel->getProperties()->getKeywords(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Comments (Description) + if($this->_phpExcel->getProperties()->getDescription()){ + $dataProp = $this->_phpExcel->getProperties()->getDescription(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Last Saved By (LastModifiedBy) + if($this->_phpExcel->getProperties()->getLastModifiedBy()){ + $dataProp = $this->_phpExcel->getProperties()->getLastModifiedBy(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Created Date/Time + if($this->_phpExcel->getProperties()->getCreated()){ + $dataProp = $this->_phpExcel->getProperties()->getCreated(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp))); + $dataSection_NumProps++; + } + // Modified Date/Time + if($this->_phpExcel->getProperties()->getModified()){ + $dataProp = $this->_phpExcel->getProperties()->getModified(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp))); + $dataSection_NumProps++; + } + // Security + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer + 'data' => array('data' => 0x00)); + $dataSection_NumProps++; + + + // 4 Section Length + // 4 Property count + // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) + $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; + foreach ($dataSection as $dataProp){ + // Summary + $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); + // Offset + $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); + // DataType + $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); + // Data + if($dataProp['type']['data'] == 0x02){ // 2 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } + elseif($dataProp['type']['data'] == 0x03){ // 4 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } + elseif($dataProp['type']['data'] == 0x1E){ // null-terminated string prepended by dword string length + // Null-terminated string + $dataProp['data']['data'] .= chr(0); + $dataProp['data']['length'] += 1; + // Complete the string with null string for being a %4 + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); + + $dataSection_Content .= pack('V', $dataProp['data']['length']); + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); + } + elseif($dataProp['type']['data'] == 0x40){ // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 8; + } + else { + // Data Type Not Used at the moment + } + } + // Now $dataSection_Content_Offset contains the size of the content + + // section header + // offset: $secOffset; size: 4; section length + // + x Size of the content (summary + content) + $data .= pack('V', $dataSection_Content_Offset); + // offset: $secOffset+4; size: 4; property count + $data .= pack('V', $dataSection_NumProps); + // Section Summary + $data .= $dataSection_Summary; + // Section Content + $data .= $dataSection_Content; + + return $data; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php new file mode 100644 index 00000000..b3e48bc3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php @@ -0,0 +1,255 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ + + +/** + * PHPExcel_Writer_Excel5_BIFFwriter + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * The byte order of this architecture. 0 => little endian, 1 => big endian + * @var integer + */ + private static $_byte_order; + + /** + * The string containing the data of the BIFF stream + * @var string + */ + public $_data; + + /** + * The size of the data in bytes. Should be the same as strlen($this->_data) + * @var integer + */ + public $_datasize; + + /** + * The maximum length for a BIFF record (excluding record header and length field). See _addContinue() + * @var integer + * @see _addContinue() + */ + public $_limit = 8224; + + /** + * Constructor + */ + public function __construct() + { + $this->_data = ''; + $this->_datasize = 0; +// $this->_limit = 8224; + } + + /** + * Determine the byte order and store it as class data to avoid + * recalculating it for each call to new(). + * + * @return int + */ + public static function getByteOrder() + { + if (!isset(self::$_byte_order)) { + // Check if "pack" gives the required IEEE 64bit float + $teststr = pack("d", 1.2345); + $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); + if ($number == $teststr) { + $byte_order = 0; // Little Endian + } elseif ($number == strrev($teststr)){ + $byte_order = 1; // Big Endian + } else { + // Give up. I'll fix this in a later version. + throw new PHPExcel_Writer_Exception("Required floating point format not supported on this platform."); + } + self::$_byte_order = $byte_order; + } + + return self::$_byte_order; + } + + /** + * General storage function + * + * @param string $data binary data to append + * @access private + */ + function _append($data) + { + if (strlen($data) - 4 > $this->_limit) { + $data = $this->_addContinue($data); + } + $this->_data .= $data; + $this->_datasize += strlen($data); + } + + /** + * General storage function like _append, but returns string instead of modifying $this->_data + * + * @param string $data binary data to write + * @return string + */ + public function writeData($data) + { + if (strlen($data) - 4 > $this->_limit) { + $data = $this->_addContinue($data); + } + $this->_datasize += strlen($data); + + return $data; + } + + /** + * Writes Excel BOF record to indicate the beginning of a stream or + * sub-stream in the BIFF file. + * + * @param integer $type Type of BIFF file to write: 0x0005 Workbook, + * 0x0010 Worksheet. + * @access private + */ + function _storeBof($type) + { + $record = 0x0809; // Record identifier (BIFF5-BIFF8) + $length = 0x0010; + + // by inspection of real files, MS Office Excel 2007 writes the following + $unknown = pack("VV", 0x000100D1, 0x00000406); + + $build = 0x0DBB; // Excel 97 + $year = 0x07CC; // Excel 97 + + $version = 0x0600; // BIFF8 + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $version, $type, $build, $year); + $this->_append($header . $data . $unknown); + } + + /** + * Writes Excel EOF record to indicate the end of a BIFF stream. + * + * @access private + */ + function _storeEof() + { + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $this->_append($header); + } + + /** + * Writes Excel EOF record to indicate the end of a BIFF stream. + * + * @access private + */ + public function writeEof() + { + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow + $header = pack("vv", $record, $length); + return $this->writeData($header); + } + + /** + * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In + * Excel 97 the limit is 8228 bytes. Records that are longer than these limits + * must be split up into CONTINUE blocks. + * + * This function takes a long BIFF record and inserts CONTINUE records as + * necessary. + * + * @param string $data The original binary data to be written + * @return string A very convenient string of continue blocks + * @access private + */ + function _addContinue($data) + { + $limit = $this->_limit; + $record = 0x003C; // Record identifier + + // The first 2080/8224 bytes remain intact. However, we have to change + // the length field of the record. + $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit); + + $header = pack("vv", $record, $limit); // Headers for continue records + + // Retrieve chunks of 2080/8224 bytes +4 for the header. + $data_length = strlen($data); + for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) { + $tmp .= $header; + $tmp .= substr($data, $i, $limit); + } + + // Retrieve the last chunk of data + $header = pack("vv", $record, strlen($data) - $i); + $tmp .= $header; + $tmp .= substr($data, $i, strlen($data) - $i); + + return $tmp; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php new file mode 100644 index 00000000..7e9b73a3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php @@ -0,0 +1,537 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Escher +{ + /** + * The object we are writing + */ + private $_object; + + /** + * The written binary data + */ + private $_data; + + /** + * Shape offsets. Positions in binary stream where a new shape record begins + * + * @var array + */ + private $_spOffsets; + + /** + * Shape types. + * + * @var array + */ + private $_spTypes; + + /** + * Constructor + * + * @param mixed + */ + public function __construct($object) + { + $this->_object = $object; + } + + /** + * Process the object to be written + */ + public function close() + { + // initialize + $this->_data = ''; + + switch (get_class($this->_object)) { + + case 'PHPExcel_Shared_Escher': + if ($dggContainer = $this->_object->getDggContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($dggContainer); + $this->_data = $writer->close(); + } else if ($dgContainer = $this->_object->getDgContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($dgContainer); + $this->_data = $writer->close(); + $this->_spOffsets = $writer->getSpOffsets(); + $this->_spTypes = $writer->getSpTypes(); + } + break; + + case 'PHPExcel_Shared_Escher_DggContainer': + // this is a container record + + // initialize + $innerData = ''; + + // write the dgg + $recVer = 0x0; + $recInstance = 0x0000; + $recType = 0xF006; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + // dgg data + $dggData = + pack('VVVV' + , $this->_object->getSpIdMax() // maximum shape identifier increased by one + , $this->_object->getCDgSaved() + 1 // number of file identifier clusters increased by one + , $this->_object->getCSpSaved() + , $this->_object->getCDgSaved() // count total number of drawings saved + ); + + // add file identifier clusters (one per drawing) + $IDCLs = $this->_object->getIDCLs(); + + foreach ($IDCLs as $dgId => $maxReducedSpId) { + $dggData .= pack('VV', $dgId, $maxReducedSpId + 1); + } + + $header = pack('vvV', $recVerInstance, $recType, strlen($dggData)); + $innerData .= $header . $dggData; + + // write the bstoreContainer + if ($bstoreContainer = $this->_object->getBstoreContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($bstoreContainer); + $innerData .= $writer->close(); + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF000; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header . $innerData; + break; + + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer': + // this is a container record + + // initialize + $innerData = ''; + + // treat the inner data + if ($BSECollection = $this->_object->getBSECollection()) { + foreach ($BSECollection as $BSE) { + $writer = new PHPExcel_Writer_Excel5_Escher($BSE); + $innerData .= $writer->close(); + } + } + + // write the record + $recVer = 0xF; + $recInstance = count($this->_object->getBSECollection()); + $recType = 0xF001; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header . $innerData; + break; + + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE': + // this is a semi-container record + + // initialize + $innerData = ''; + + // here we treat the inner data + if ($blip = $this->_object->getBlip()) { + $writer = new PHPExcel_Writer_Excel5_Escher($blip); + $innerData .= $writer->close(); + } + + // initialize + $data = ''; + + $btWin32 = $this->_object->getBlipType(); + $btMacOS = $this->_object->getBlipType(); + $data .= pack('CC', $btWin32, $btMacOS); + + $rgbUid = pack('VVVV', 0,0,0,0); // todo + $data .= $rgbUid; + + $tag = 0; + $size = strlen($innerData); + $cRef = 1; + $foDelay = 0; //todo + $unused1 = 0x0; + $cbName = 0x0; + $unused2 = 0x0; + $unused3 = 0x0; + $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3); + + $data .= $innerData; + + // write the record + $recVer = 0x2; + $recInstance = $this->_object->getBlipType(); + $recType = 0xF007; + $length = strlen($data); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header; + + $this->_data .= $data; + break; + + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip': + // this is an atom record + + // write the record + switch ($this->_object->getParent()->getBlipType()) { + + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG: + // initialize + $innerData = ''; + + $rgbUid1 = pack('VVVV', 0,0,0,0); // todo + $innerData .= $rgbUid1; + + $tag = 0xFF; // todo + $innerData .= pack('C', $tag); + + $innerData .= $this->_object->getData(); + + $recVer = 0x0; + $recInstance = 0x46A; + $recType = 0xF01D; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header; + + $this->_data .= $innerData; + break; + + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG: + // initialize + $innerData = ''; + + $rgbUid1 = pack('VVVV', 0,0,0,0); // todo + $innerData .= $rgbUid1; + + $tag = 0xFF; // todo + $innerData .= pack('C', $tag); + + $innerData .= $this->_object->getData(); + + $recVer = 0x0; + $recInstance = 0x6E0; + $recType = 0xF01E; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header; + + $this->_data .= $innerData; + break; + + } + break; + + case 'PHPExcel_Shared_Escher_DgContainer': + // this is a container record + + // initialize + $innerData = ''; + + // write the dg + $recVer = 0x0; + $recInstance = $this->_object->getDgId(); + $recType = 0xF008; + $length = 8; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + // number of shapes in this drawing (including group shape) + $countShapes = count($this->_object->getSpgrContainer()->getChildren()); + $innerData .= $header . pack('VV', $countShapes, $this->_object->getLastSpId()); + //$innerData .= $header . pack('VV', 0, 0); + + // write the spgrContainer + if ($spgrContainer = $this->_object->getSpgrContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($spgrContainer); + $innerData .= $writer->close(); + + // get the shape offsets relative to the spgrContainer record + $spOffsets = $writer->getSpOffsets(); + $spTypes = $writer->getSpTypes(); + + // save the shape offsets relative to dgContainer + foreach ($spOffsets as & $spOffset) { + $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes) + } + + $this->_spOffsets = $spOffsets; + $this->_spTypes = $spTypes; + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF002; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header . $innerData; + break; + + case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer': + // this is a container record + + // initialize + $innerData = ''; + + // initialize spape offsets + $totalSize = 8; + $spOffsets = array(); + $spTypes = array(); + + // treat the inner data + foreach ($this->_object->getChildren() as $spContainer) { + $writer = new PHPExcel_Writer_Excel5_Escher($spContainer); + $spData = $writer->close(); + $innerData .= $spData; + + // save the shape offsets (where new shape records begin) + $totalSize += strlen($spData); + $spOffsets[] = $totalSize; + + $spTypes = array_merge($spTypes, $writer->getSpTypes()); + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF003; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header . $innerData; + $this->_spOffsets = $spOffsets; + $this->_spTypes = $spTypes; + break; + + case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer': + // initialize + $data = ''; + + // build the data + + // write group shape record, if necessary? + if ($this->_object->getSpgr()) { + $recVer = 0x1; + $recInstance = 0x0000; + $recType = 0xF009; + $length = 0x00000010; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $data .= $header . pack('VVVV', 0,0,0,0); + } + $this->_spTypes[] = ($this->_object->getSpType()); + + // write the shape record + $recVer = 0x2; + $recInstance = $this->_object->getSpType(); // shape type + $recType = 0xF00A; + $length = 0x00000008; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $data .= $header . pack('VV', $this->_object->getSpId(), $this->_object->getSpgr() ? 0x0005 : 0x0A00); + + + // the options + if ($this->_object->getOPTCollection()) { + $optData = ''; + + $recVer = 0x3; + $recInstance = count($this->_object->getOPTCollection()); + $recType = 0xF00B; + foreach ($this->_object->getOPTCollection() as $property => $value) { + $optData .= pack('vV', $property, $value); + } + $length = strlen($optData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $optData; + } + + // the client anchor + if ($this->_object->getStartCoordinates()) { + $clientAnchorData = ''; + + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF010; + + // start coordinates + list($column, $row) = PHPExcel_Cell::coordinateFromString($this->_object->getStartCoordinates()); + $c1 = PHPExcel_Cell::columnIndexFromString($column) - 1; + $r1 = $row - 1; + + // start offsetX + $startOffsetX = $this->_object->getStartOffsetX(); + + // start offsetY + $startOffsetY = $this->_object->getStartOffsetY(); + + // end coordinates + list($column, $row) = PHPExcel_Cell::coordinateFromString($this->_object->getEndCoordinates()); + $c2 = PHPExcel_Cell::columnIndexFromString($column) - 1; + $r2 = $row - 1; + + // end offsetX + $endOffsetX = $this->_object->getEndOffsetX(); + + // end offsetY + $endOffsetY = $this->_object->getEndOffsetY(); + + $clientAnchorData = pack('vvvvvvvvv', $this->_object->getSpFlag(), + $c1, $startOffsetX, $r1, $startOffsetY, + $c2, $endOffsetX, $r2, $endOffsetY); + + $length = strlen($clientAnchorData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $clientAnchorData; + } + + // the client data, just empty for now + if (!$this->_object->getSpgr()) { + $clientDataData = ''; + + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF011; + + $length = strlen($clientDataData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $clientDataData; + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF004; + $length = strlen($data); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->_data = $header . $data; + break; + + } + + return $this->_data; + } + + /** + * Gets the shape offsets + * + * @return array + */ + public function getSpOffsets() + { + return $this->_spOffsets; + } + + /** + * Gets the shape types + * + * @return array + */ + public function getSpTypes() + { + return $this->_spTypes; + } + + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php new file mode 100644 index 00000000..f2dbab20 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php @@ -0,0 +1,165 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Excel5_Font + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Font +{ + /** + * Color index + * + * @var int + */ + private $_colorIndex; + + /** + * Font + * + * @var PHPExcel_Style_Font + */ + private $_font; + + /** + * Constructor + * + * @param PHPExcel_Style_Font $font + */ + public function __construct(PHPExcel_Style_Font $font = null) + { + $this->_colorIndex = 0x7FFF; + $this->_font = $font; + } + + /** + * Set the color index + * + * @param int $colorIndex + */ + public function setColorIndex($colorIndex) + { + $this->_colorIndex = $colorIndex; + } + + /** + * Get font record data + * + * @return string + */ + public function writeFont() + { + $font_outline = 0; + $font_shadow = 0; + + $icv = $this->_colorIndex; // Index to color palette + if ($this->_font->getSuperScript()) { + $sss = 1; + } else if ($this->_font->getSubScript()) { + $sss = 2; + } else { + $sss = 0; + } + $bFamily = 0; // Font family + $bCharSet = PHPExcel_Shared_Font::getCharsetFromFontName($this->_font->getName()); // Character set + + $record = 0x31; // Record identifier + $reserved = 0x00; // Reserved + $grbit = 0x00; // Font attributes + if ($this->_font->getItalic()) { + $grbit |= 0x02; + } + if ($this->_font->getStrikethrough()) { + $grbit |= 0x08; + } + if ($font_outline) { + $grbit |= 0x10; + } + if ($font_shadow) { + $grbit |= 0x20; + } + + $data = pack("vvvvvCCCC", + $this->_font->getSize() * 20, // Fontsize (in twips) + $grbit, + $icv, // Colour + self::_mapBold($this->_font->getBold()), // Font weight + $sss, // Superscript/Subscript + self::_mapUnderline($this->_font->getUnderline()), + $bFamily, + $bCharSet, + $reserved + ); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($this->_font->getName()); + + $length = strlen($data); + $header = pack("vv", $record, $length); + + return($header . $data); + } + + /** + * Map to BIFF5-BIFF8 codes for bold + * + * @param boolean $bold + * @return int + */ + private static function _mapBold($bold) { + if ($bold) { + return 0x2BC; // 700 = Bold font weight + } + return 0x190; // 400 = Normal font weight + } + + /** + * Map of BIFF2-BIFF8 codes for underline styles + * @static array of int + * + */ + private static $_mapUnderline = array( PHPExcel_Style_Font::UNDERLINE_NONE => 0x00, + PHPExcel_Style_Font::UNDERLINE_SINGLE => 0x01, + PHPExcel_Style_Font::UNDERLINE_DOUBLE => 0x02, + PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21, + PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, + ); + /** + * Map underline + * + * @param string + * @return int + */ + private static function _mapUnderline($underline) { + if (isset(self::$_mapUnderline[$underline])) + return self::$_mapUnderline[$underline]; + return 0x00; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php new file mode 100644 index 00000000..04e674a2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php @@ -0,0 +1,1582 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// * Class for parsing Excel formulas +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ + + +/** + * PHPExcel_Writer_Excel5_Parser + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Parser +{ + /** Constants */ + // Sheet title in unquoted form + // Invalid sheet title characters cannot occur in the sheet title: + // *:/\?[] + // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?) + // +-% '^&<>=,;#()"{} + const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+'; + + // Sheet title in quoted form (without surrounding quotes) + // Invalid sheet title characters cannot occur in the sheet title: + // *:/\?[] (usual invalid sheet title characters) + // Single quote is represented as a pair '' + const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+'; + + /** + * The index of the character we are currently looking at + * @var integer + */ + public $_current_char; + + /** + * The token we are working on. + * @var string + */ + public $_current_token; + + /** + * The formula to parse + * @var string + */ + public $_formula; + + /** + * The character ahead of the current char + * @var string + */ + public $_lookahead; + + /** + * The parse tree to be generated + * @var string + */ + public $_parse_tree; + + /** + * Array of external sheets + * @var array + */ + public $_ext_sheets; + + /** + * Array of sheet references in the form of REF structures + * @var array + */ + public $_references; + + /** + * The class constructor + * + */ + public function __construct() + { + $this->_current_char = 0; + $this->_current_token = ''; // The token we are working on. + $this->_formula = ''; // The formula to parse. + $this->_lookahead = ''; // The character ahead of the current char. + $this->_parse_tree = ''; // The parse tree to be generated. + $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's + $this->_ext_sheets = array(); + $this->_references = array(); + } + + /** + * Initialize the ptg and function hashes. + * + * @access private + */ + function _initializeHashes() + { + // The Excel ptg indices + $this->ptg = array( + 'ptgExp' => 0x01, + 'ptgTbl' => 0x02, + 'ptgAdd' => 0x03, + 'ptgSub' => 0x04, + 'ptgMul' => 0x05, + 'ptgDiv' => 0x06, + 'ptgPower' => 0x07, + 'ptgConcat' => 0x08, + 'ptgLT' => 0x09, + 'ptgLE' => 0x0A, + 'ptgEQ' => 0x0B, + 'ptgGE' => 0x0C, + 'ptgGT' => 0x0D, + 'ptgNE' => 0x0E, + 'ptgIsect' => 0x0F, + 'ptgUnion' => 0x10, + 'ptgRange' => 0x11, + 'ptgUplus' => 0x12, + 'ptgUminus' => 0x13, + 'ptgPercent' => 0x14, + 'ptgParen' => 0x15, + 'ptgMissArg' => 0x16, + 'ptgStr' => 0x17, + 'ptgAttr' => 0x19, + 'ptgSheet' => 0x1A, + 'ptgEndSheet' => 0x1B, + 'ptgErr' => 0x1C, + 'ptgBool' => 0x1D, + 'ptgInt' => 0x1E, + 'ptgNum' => 0x1F, + 'ptgArray' => 0x20, + 'ptgFunc' => 0x21, + 'ptgFuncVar' => 0x22, + 'ptgName' => 0x23, + 'ptgRef' => 0x24, + 'ptgArea' => 0x25, + 'ptgMemArea' => 0x26, + 'ptgMemErr' => 0x27, + 'ptgMemNoMem' => 0x28, + 'ptgMemFunc' => 0x29, + 'ptgRefErr' => 0x2A, + 'ptgAreaErr' => 0x2B, + 'ptgRefN' => 0x2C, + 'ptgAreaN' => 0x2D, + 'ptgMemAreaN' => 0x2E, + 'ptgMemNoMemN' => 0x2F, + 'ptgNameX' => 0x39, + 'ptgRef3d' => 0x3A, + 'ptgArea3d' => 0x3B, + 'ptgRefErr3d' => 0x3C, + 'ptgAreaErr3d' => 0x3D, + 'ptgArrayV' => 0x40, + 'ptgFuncV' => 0x41, + 'ptgFuncVarV' => 0x42, + 'ptgNameV' => 0x43, + 'ptgRefV' => 0x44, + 'ptgAreaV' => 0x45, + 'ptgMemAreaV' => 0x46, + 'ptgMemErrV' => 0x47, + 'ptgMemNoMemV' => 0x48, + 'ptgMemFuncV' => 0x49, + 'ptgRefErrV' => 0x4A, + 'ptgAreaErrV' => 0x4B, + 'ptgRefNV' => 0x4C, + 'ptgAreaNV' => 0x4D, + 'ptgMemAreaNV' => 0x4E, + 'ptgMemNoMemN' => 0x4F, + 'ptgFuncCEV' => 0x58, + 'ptgNameXV' => 0x59, + 'ptgRef3dV' => 0x5A, + 'ptgArea3dV' => 0x5B, + 'ptgRefErr3dV' => 0x5C, + 'ptgAreaErr3d' => 0x5D, + 'ptgArrayA' => 0x60, + 'ptgFuncA' => 0x61, + 'ptgFuncVarA' => 0x62, + 'ptgNameA' => 0x63, + 'ptgRefA' => 0x64, + 'ptgAreaA' => 0x65, + 'ptgMemAreaA' => 0x66, + 'ptgMemErrA' => 0x67, + 'ptgMemNoMemA' => 0x68, + 'ptgMemFuncA' => 0x69, + 'ptgRefErrA' => 0x6A, + 'ptgAreaErrA' => 0x6B, + 'ptgRefNA' => 0x6C, + 'ptgAreaNA' => 0x6D, + 'ptgMemAreaNA' => 0x6E, + 'ptgMemNoMemN' => 0x6F, + 'ptgFuncCEA' => 0x78, + 'ptgNameXA' => 0x79, + 'ptgRef3dA' => 0x7A, + 'ptgArea3dA' => 0x7B, + 'ptgRefErr3dA' => 0x7C, + 'ptgAreaErr3d' => 0x7D + ); + + // Thanks to Michael Meeks and Gnumeric for the initial arg values. + // + // The following hash was generated by "function_locale.pl" in the distro. + // Refer to function_locale.pl for non-English function names. + // + // The array elements are as follow: + // ptg: The Excel function ptg code. + // args: The number of arguments that the function takes: + // >=0 is a fixed number of arguments. + // -1 is a variable number of arguments. + // class: The reference, value or array class of the function args. + // vol: The function is volatile. + // + $this->_functions = array( + // function ptg args class vol + 'COUNT' => array( 0, -1, 0, 0 ), + 'IF' => array( 1, -1, 1, 0 ), + 'ISNA' => array( 2, 1, 1, 0 ), + 'ISERROR' => array( 3, 1, 1, 0 ), + 'SUM' => array( 4, -1, 0, 0 ), + 'AVERAGE' => array( 5, -1, 0, 0 ), + 'MIN' => array( 6, -1, 0, 0 ), + 'MAX' => array( 7, -1, 0, 0 ), + 'ROW' => array( 8, -1, 0, 0 ), + 'COLUMN' => array( 9, -1, 0, 0 ), + 'NA' => array( 10, 0, 0, 0 ), + 'NPV' => array( 11, -1, 1, 0 ), + 'STDEV' => array( 12, -1, 0, 0 ), + 'DOLLAR' => array( 13, -1, 1, 0 ), + 'FIXED' => array( 14, -1, 1, 0 ), + 'SIN' => array( 15, 1, 1, 0 ), + 'COS' => array( 16, 1, 1, 0 ), + 'TAN' => array( 17, 1, 1, 0 ), + 'ATAN' => array( 18, 1, 1, 0 ), + 'PI' => array( 19, 0, 1, 0 ), + 'SQRT' => array( 20, 1, 1, 0 ), + 'EXP' => array( 21, 1, 1, 0 ), + 'LN' => array( 22, 1, 1, 0 ), + 'LOG10' => array( 23, 1, 1, 0 ), + 'ABS' => array( 24, 1, 1, 0 ), + 'INT' => array( 25, 1, 1, 0 ), + 'SIGN' => array( 26, 1, 1, 0 ), + 'ROUND' => array( 27, 2, 1, 0 ), + 'LOOKUP' => array( 28, -1, 0, 0 ), + 'INDEX' => array( 29, -1, 0, 1 ), + 'REPT' => array( 30, 2, 1, 0 ), + 'MID' => array( 31, 3, 1, 0 ), + 'LEN' => array( 32, 1, 1, 0 ), + 'VALUE' => array( 33, 1, 1, 0 ), + 'TRUE' => array( 34, 0, 1, 0 ), + 'FALSE' => array( 35, 0, 1, 0 ), + 'AND' => array( 36, -1, 0, 0 ), + 'OR' => array( 37, -1, 0, 0 ), + 'NOT' => array( 38, 1, 1, 0 ), + 'MOD' => array( 39, 2, 1, 0 ), + 'DCOUNT' => array( 40, 3, 0, 0 ), + 'DSUM' => array( 41, 3, 0, 0 ), + 'DAVERAGE' => array( 42, 3, 0, 0 ), + 'DMIN' => array( 43, 3, 0, 0 ), + 'DMAX' => array( 44, 3, 0, 0 ), + 'DSTDEV' => array( 45, 3, 0, 0 ), + 'VAR' => array( 46, -1, 0, 0 ), + 'DVAR' => array( 47, 3, 0, 0 ), + 'TEXT' => array( 48, 2, 1, 0 ), + 'LINEST' => array( 49, -1, 0, 0 ), + 'TREND' => array( 50, -1, 0, 0 ), + 'LOGEST' => array( 51, -1, 0, 0 ), + 'GROWTH' => array( 52, -1, 0, 0 ), + 'PV' => array( 56, -1, 1, 0 ), + 'FV' => array( 57, -1, 1, 0 ), + 'NPER' => array( 58, -1, 1, 0 ), + 'PMT' => array( 59, -1, 1, 0 ), + 'RATE' => array( 60, -1, 1, 0 ), + 'MIRR' => array( 61, 3, 0, 0 ), + 'IRR' => array( 62, -1, 0, 0 ), + 'RAND' => array( 63, 0, 1, 1 ), + 'MATCH' => array( 64, -1, 0, 0 ), + 'DATE' => array( 65, 3, 1, 0 ), + 'TIME' => array( 66, 3, 1, 0 ), + 'DAY' => array( 67, 1, 1, 0 ), + 'MONTH' => array( 68, 1, 1, 0 ), + 'YEAR' => array( 69, 1, 1, 0 ), + 'WEEKDAY' => array( 70, -1, 1, 0 ), + 'HOUR' => array( 71, 1, 1, 0 ), + 'MINUTE' => array( 72, 1, 1, 0 ), + 'SECOND' => array( 73, 1, 1, 0 ), + 'NOW' => array( 74, 0, 1, 1 ), + 'AREAS' => array( 75, 1, 0, 1 ), + 'ROWS' => array( 76, 1, 0, 1 ), + 'COLUMNS' => array( 77, 1, 0, 1 ), + 'OFFSET' => array( 78, -1, 0, 1 ), + 'SEARCH' => array( 82, -1, 1, 0 ), + 'TRANSPOSE' => array( 83, 1, 1, 0 ), + 'TYPE' => array( 86, 1, 1, 0 ), + 'ATAN2' => array( 97, 2, 1, 0 ), + 'ASIN' => array( 98, 1, 1, 0 ), + 'ACOS' => array( 99, 1, 1, 0 ), + 'CHOOSE' => array( 100, -1, 1, 0 ), + 'HLOOKUP' => array( 101, -1, 0, 0 ), + 'VLOOKUP' => array( 102, -1, 0, 0 ), + 'ISREF' => array( 105, 1, 0, 0 ), + 'LOG' => array( 109, -1, 1, 0 ), + 'CHAR' => array( 111, 1, 1, 0 ), + 'LOWER' => array( 112, 1, 1, 0 ), + 'UPPER' => array( 113, 1, 1, 0 ), + 'PROPER' => array( 114, 1, 1, 0 ), + 'LEFT' => array( 115, -1, 1, 0 ), + 'RIGHT' => array( 116, -1, 1, 0 ), + 'EXACT' => array( 117, 2, 1, 0 ), + 'TRIM' => array( 118, 1, 1, 0 ), + 'REPLACE' => array( 119, 4, 1, 0 ), + 'SUBSTITUTE' => array( 120, -1, 1, 0 ), + 'CODE' => array( 121, 1, 1, 0 ), + 'FIND' => array( 124, -1, 1, 0 ), + 'CELL' => array( 125, -1, 0, 1 ), + 'ISERR' => array( 126, 1, 1, 0 ), + 'ISTEXT' => array( 127, 1, 1, 0 ), + 'ISNUMBER' => array( 128, 1, 1, 0 ), + 'ISBLANK' => array( 129, 1, 1, 0 ), + 'T' => array( 130, 1, 0, 0 ), + 'N' => array( 131, 1, 0, 0 ), + 'DATEVALUE' => array( 140, 1, 1, 0 ), + 'TIMEVALUE' => array( 141, 1, 1, 0 ), + 'SLN' => array( 142, 3, 1, 0 ), + 'SYD' => array( 143, 4, 1, 0 ), + 'DDB' => array( 144, -1, 1, 0 ), + 'INDIRECT' => array( 148, -1, 1, 1 ), + 'CALL' => array( 150, -1, 1, 0 ), + 'CLEAN' => array( 162, 1, 1, 0 ), + 'MDETERM' => array( 163, 1, 2, 0 ), + 'MINVERSE' => array( 164, 1, 2, 0 ), + 'MMULT' => array( 165, 2, 2, 0 ), + 'IPMT' => array( 167, -1, 1, 0 ), + 'PPMT' => array( 168, -1, 1, 0 ), + 'COUNTA' => array( 169, -1, 0, 0 ), + 'PRODUCT' => array( 183, -1, 0, 0 ), + 'FACT' => array( 184, 1, 1, 0 ), + 'DPRODUCT' => array( 189, 3, 0, 0 ), + 'ISNONTEXT' => array( 190, 1, 1, 0 ), + 'STDEVP' => array( 193, -1, 0, 0 ), + 'VARP' => array( 194, -1, 0, 0 ), + 'DSTDEVP' => array( 195, 3, 0, 0 ), + 'DVARP' => array( 196, 3, 0, 0 ), + 'TRUNC' => array( 197, -1, 1, 0 ), + 'ISLOGICAL' => array( 198, 1, 1, 0 ), + 'DCOUNTA' => array( 199, 3, 0, 0 ), + 'USDOLLAR' => array( 204, -1, 1, 0 ), + 'FINDB' => array( 205, -1, 1, 0 ), + 'SEARCHB' => array( 206, -1, 1, 0 ), + 'REPLACEB' => array( 207, 4, 1, 0 ), + 'LEFTB' => array( 208, -1, 1, 0 ), + 'RIGHTB' => array( 209, -1, 1, 0 ), + 'MIDB' => array( 210, 3, 1, 0 ), + 'LENB' => array( 211, 1, 1, 0 ), + 'ROUNDUP' => array( 212, 2, 1, 0 ), + 'ROUNDDOWN' => array( 213, 2, 1, 0 ), + 'ASC' => array( 214, 1, 1, 0 ), + 'DBCS' => array( 215, 1, 1, 0 ), + 'RANK' => array( 216, -1, 0, 0 ), + 'ADDRESS' => array( 219, -1, 1, 0 ), + 'DAYS360' => array( 220, -1, 1, 0 ), + 'TODAY' => array( 221, 0, 1, 1 ), + 'VDB' => array( 222, -1, 1, 0 ), + 'MEDIAN' => array( 227, -1, 0, 0 ), + 'SUMPRODUCT' => array( 228, -1, 2, 0 ), + 'SINH' => array( 229, 1, 1, 0 ), + 'COSH' => array( 230, 1, 1, 0 ), + 'TANH' => array( 231, 1, 1, 0 ), + 'ASINH' => array( 232, 1, 1, 0 ), + 'ACOSH' => array( 233, 1, 1, 0 ), + 'ATANH' => array( 234, 1, 1, 0 ), + 'DGET' => array( 235, 3, 0, 0 ), + 'INFO' => array( 244, 1, 1, 1 ), + 'DB' => array( 247, -1, 1, 0 ), + 'FREQUENCY' => array( 252, 2, 0, 0 ), + 'ERROR.TYPE' => array( 261, 1, 1, 0 ), + 'REGISTER.ID' => array( 267, -1, 1, 0 ), + 'AVEDEV' => array( 269, -1, 0, 0 ), + 'BETADIST' => array( 270, -1, 1, 0 ), + 'GAMMALN' => array( 271, 1, 1, 0 ), + 'BETAINV' => array( 272, -1, 1, 0 ), + 'BINOMDIST' => array( 273, 4, 1, 0 ), + 'CHIDIST' => array( 274, 2, 1, 0 ), + 'CHIINV' => array( 275, 2, 1, 0 ), + 'COMBIN' => array( 276, 2, 1, 0 ), + 'CONFIDENCE' => array( 277, 3, 1, 0 ), + 'CRITBINOM' => array( 278, 3, 1, 0 ), + 'EVEN' => array( 279, 1, 1, 0 ), + 'EXPONDIST' => array( 280, 3, 1, 0 ), + 'FDIST' => array( 281, 3, 1, 0 ), + 'FINV' => array( 282, 3, 1, 0 ), + 'FISHER' => array( 283, 1, 1, 0 ), + 'FISHERINV' => array( 284, 1, 1, 0 ), + 'FLOOR' => array( 285, 2, 1, 0 ), + 'GAMMADIST' => array( 286, 4, 1, 0 ), + 'GAMMAINV' => array( 287, 3, 1, 0 ), + 'CEILING' => array( 288, 2, 1, 0 ), + 'HYPGEOMDIST' => array( 289, 4, 1, 0 ), + 'LOGNORMDIST' => array( 290, 3, 1, 0 ), + 'LOGINV' => array( 291, 3, 1, 0 ), + 'NEGBINOMDIST' => array( 292, 3, 1, 0 ), + 'NORMDIST' => array( 293, 4, 1, 0 ), + 'NORMSDIST' => array( 294, 1, 1, 0 ), + 'NORMINV' => array( 295, 3, 1, 0 ), + 'NORMSINV' => array( 296, 1, 1, 0 ), + 'STANDARDIZE' => array( 297, 3, 1, 0 ), + 'ODD' => array( 298, 1, 1, 0 ), + 'PERMUT' => array( 299, 2, 1, 0 ), + 'POISSON' => array( 300, 3, 1, 0 ), + 'TDIST' => array( 301, 3, 1, 0 ), + 'WEIBULL' => array( 302, 4, 1, 0 ), + 'SUMXMY2' => array( 303, 2, 2, 0 ), + 'SUMX2MY2' => array( 304, 2, 2, 0 ), + 'SUMX2PY2' => array( 305, 2, 2, 0 ), + 'CHITEST' => array( 306, 2, 2, 0 ), + 'CORREL' => array( 307, 2, 2, 0 ), + 'COVAR' => array( 308, 2, 2, 0 ), + 'FORECAST' => array( 309, 3, 2, 0 ), + 'FTEST' => array( 310, 2, 2, 0 ), + 'INTERCEPT' => array( 311, 2, 2, 0 ), + 'PEARSON' => array( 312, 2, 2, 0 ), + 'RSQ' => array( 313, 2, 2, 0 ), + 'STEYX' => array( 314, 2, 2, 0 ), + 'SLOPE' => array( 315, 2, 2, 0 ), + 'TTEST' => array( 316, 4, 2, 0 ), + 'PROB' => array( 317, -1, 2, 0 ), + 'DEVSQ' => array( 318, -1, 0, 0 ), + 'GEOMEAN' => array( 319, -1, 0, 0 ), + 'HARMEAN' => array( 320, -1, 0, 0 ), + 'SUMSQ' => array( 321, -1, 0, 0 ), + 'KURT' => array( 322, -1, 0, 0 ), + 'SKEW' => array( 323, -1, 0, 0 ), + 'ZTEST' => array( 324, -1, 0, 0 ), + 'LARGE' => array( 325, 2, 0, 0 ), + 'SMALL' => array( 326, 2, 0, 0 ), + 'QUARTILE' => array( 327, 2, 0, 0 ), + 'PERCENTILE' => array( 328, 2, 0, 0 ), + 'PERCENTRANK' => array( 329, -1, 0, 0 ), + 'MODE' => array( 330, -1, 2, 0 ), + 'TRIMMEAN' => array( 331, 2, 0, 0 ), + 'TINV' => array( 332, 2, 1, 0 ), + 'CONCATENATE' => array( 336, -1, 1, 0 ), + 'POWER' => array( 337, 2, 1, 0 ), + 'RADIANS' => array( 342, 1, 1, 0 ), + 'DEGREES' => array( 343, 1, 1, 0 ), + 'SUBTOTAL' => array( 344, -1, 0, 0 ), + 'SUMIF' => array( 345, -1, 0, 0 ), + 'COUNTIF' => array( 346, 2, 0, 0 ), + 'COUNTBLANK' => array( 347, 1, 0, 0 ), + 'ISPMT' => array( 350, 4, 1, 0 ), + 'DATEDIF' => array( 351, 3, 1, 0 ), + 'DATESTRING' => array( 352, 1, 1, 0 ), + 'NUMBERSTRING' => array( 353, 2, 1, 0 ), + 'ROMAN' => array( 354, -1, 1, 0 ), + 'GETPIVOTDATA' => array( 358, -1, 0, 0 ), + 'HYPERLINK' => array( 359, -1, 1, 0 ), + 'PHONETIC' => array( 360, 1, 0, 0 ), + 'AVERAGEA' => array( 361, -1, 0, 0 ), + 'MAXA' => array( 362, -1, 0, 0 ), + 'MINA' => array( 363, -1, 0, 0 ), + 'STDEVPA' => array( 364, -1, 0, 0 ), + 'VARPA' => array( 365, -1, 0, 0 ), + 'STDEVA' => array( 366, -1, 0, 0 ), + 'VARA' => array( 367, -1, 0, 0 ), + 'BAHTTEXT' => array( 368, 1, 0, 0 ), + ); + } + + /** + * Convert a token to the proper ptg value. + * + * @access private + * @param mixed $token The token to convert. + * @return mixed the converted token on success + */ + function _convert($token) + { + if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) { + return $this->_convertString($token); + + } elseif (is_numeric($token)) { + return $this->_convertNumber($token); + + // match references like A1 or $A$1 + } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) { + return $this->_convertRef2d($token); + + // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1 + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) { + return $this->_convertRef3d($token); + + // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1 + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u",$token)) { + return $this->_convertRef3d($token); + + // match ranges like A1:B2 or $A$1:$B$2 + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) { + return $this->_convertRange2d($token); + + // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) { + return $this->_convertRange3d($token); + + // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u",$token)) { + return $this->_convertRange3d($token); + + // operators (including parentheses) + } elseif (isset($this->ptg[$token])) { + return pack("C", $this->ptg[$token]); + + // match error codes + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') { + return $this->_convertError($token); + + // commented so argument number can be processed correctly. See toReversePolish(). + /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token)) + { + return($this->_convertFunction($token,$this->_func_args)); + }*/ + + // if it's an argument, ignore the token (the argument remains) + } elseif ($token == 'arg') { + return ''; + } + + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown token $token"); + } + + /** + * Convert a number token to ptgInt or ptgNum + * + * @access private + * @param mixed $num an integer or double for conversion to its ptg value + */ + function _convertNumber($num) + { + // Integer in the range 0..2**16-1 + if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) { + return pack("Cv", $this->ptg['ptgInt'], $num); + } else { // A float + if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian + $num = strrev($num); + } + return pack("Cd", $this->ptg['ptgNum'], $num); + } + } + + /** + * Convert a string token to ptgStr + * + * @access private + * @param string $string A string for conversion to its ptg value. + * @return mixed the converted token on success + */ + function _convertString($string) + { + // chop away beggining and ending quotes + $string = substr($string, 1, strlen($string) - 2); + if (strlen($string) > 255) { + throw new PHPExcel_Writer_Exception("String is too long"); + } + + return pack('C', $this->ptg['ptgStr']) . PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($string); + } + + /** + * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of + * args that it takes. + * + * @access private + * @param string $token The name of the function for convertion to ptg value. + * @param integer $num_args The number of arguments the function receives. + * @return string The packed ptg for the function + */ + function _convertFunction($token, $num_args) + { + $args = $this->_functions[$token][1]; +// $volatile = $this->_functions[$token][3]; + + // Fixed number of args eg. TIME($i,$j,$k). + if ($args >= 0) { + return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]); + } + // Variable number of args eg. SUM($i,$j,$k, ..). + if ($args == -1) { + return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]); + } + } + + /** + * Convert an Excel range such as A1:D4 to a ptgRefV. + * + * @access private + * @param string $range An Excel range in the A1:A2 + * @param int $class + */ + function _convertRange2d($range, $class=0) + { + + // TODO: possible class value 0,1,2 check Formula.pm + // Split the range into 2 cell refs + if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) { + list($cell1, $cell2) = explode(':', $range); + } else { + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown range separator"); + } + + // Convert the cell references + list($row1, $col1) = $this->_cellToPackedRowcol($cell1); + list($row2, $col2) = $this->_cellToPackedRowcol($cell2); + + // The ptg value depends on the class of the ptg. + if ($class == 0) { + $ptgArea = pack("C", $this->ptg['ptgArea']); + } elseif ($class == 1) { + $ptgArea = pack("C", $this->ptg['ptgAreaV']); + } elseif ($class == 2) { + $ptgArea = pack("C", $this->ptg['ptgAreaA']); + } else { + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown class $class"); + } + return $ptgArea . $row1 . $row2 . $col1. $col2; + } + + /** + * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to + * a ptgArea3d. + * + * @access private + * @param string $token An Excel range in the Sheet1!A1:A2 format. + * @return mixed The packed ptgArea3d token on success. + */ + function _convertRange3d($token) + { +// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B) + + // Split the ref at the ! symbol + list($ext_ref, $range) = explode('!', $token); + + // Convert the external reference part (different for BIFF8) + $ext_ref = $this->_getRefIndex($ext_ref); + + // Split the range into 2 cell refs + list($cell1, $cell2) = explode(':', $range); + + // Convert the cell references + if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) { + list($row1, $col1) = $this->_cellToPackedRowcol($cell1); + list($row2, $col2) = $this->_cellToPackedRowcol($cell2); + } else { // It's a rows range (like 26:27) + list($row1, $col1, $row2, $col2) = $this->_rangeToPackedRange($cell1.':'.$cell2); + } + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { + $ptgArea = pack("C", $this->ptg['ptgArea3d']); +// } elseif ($class == 1) { +// $ptgArea = pack("C", $this->ptg['ptgArea3dV']); +// } elseif ($class == 2) { +// $ptgArea = pack("C", $this->ptg['ptgArea3dA']); +// } else { +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + + return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2; + } + + /** + * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. + * + * @access private + * @param string $cell An Excel cell reference + * @return string The cell in packed() format with the corresponding ptg + */ + function _convertRef2d($cell) + { +// $class = 2; // as far as I know, this is magick. + + // Convert the cell reference + $cell_array = $this->_cellToPackedRowcol($cell); + list($row, $col) = $cell_array; + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { +// $ptgRef = pack("C", $this->ptg['ptgRef']); +// } elseif ($class == 1) { +// $ptgRef = pack("C", $this->ptg['ptgRefV']); +// } elseif ($class == 2) { + $ptgRef = pack("C", $this->ptg['ptgRefA']); +// } else { +// // TODO: use real error codes +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + return $ptgRef.$row.$col; + } + + /** + * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a + * ptgRef3d. + * + * @access private + * @param string $cell An Excel cell reference + * @return mixed The packed ptgRef3d token on success. + */ + function _convertRef3d($cell) + { +// $class = 2; // as far as I know, this is magick. + + // Split the ref at the ! symbol + list($ext_ref, $cell) = explode('!', $cell); + + // Convert the external reference part (different for BIFF8) + $ext_ref = $this->_getRefIndex($ext_ref); + + // Convert the cell reference part + list($row, $col) = $this->_cellToPackedRowcol($cell); + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { +// $ptgRef = pack("C", $this->ptg['ptgRef3d']); +// } elseif ($class == 1) { +// $ptgRef = pack("C", $this->ptg['ptgRef3dV']); +// } elseif ($class == 2) { + $ptgRef = pack("C", $this->ptg['ptgRef3dA']); +// } else { +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + + return $ptgRef . $ext_ref. $row . $col; + } + + /** + * Convert an error code to a ptgErr + * + * @access private + * @param string $errorCode The error code for conversion to its ptg value + * @return string The error code ptgErr + */ + function _convertError($errorCode) + { + switch ($errorCode) { + case '#NULL!': return pack("C", 0x00); + case '#DIV/0!': return pack("C", 0x07); + case '#VALUE!': return pack("C", 0x0F); + case '#REF!': return pack("C", 0x17); + case '#NAME?': return pack("C", 0x1D); + case '#NUM!': return pack("C", 0x24); + case '#N/A': return pack("C", 0x2A); + } + return pack("C", 0xFF); + } + + /** + * Convert the sheet name part of an external reference, for example "Sheet1" or + * "Sheet1:Sheet2", to a packed structure. + * + * @access private + * @param string $ext_ref The name of the external reference + * @return string The reference index in packed() format + */ + function _packExtRef($ext_ref) + { + $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. + $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + + // Check if there is a sheet range eg., Sheet1:Sheet2. + if (preg_match("/:/", $ext_ref)) { + list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); + + $sheet1 = $this->_getSheetIndex($sheet_name1); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula"); + } + $sheet2 = $this->_getSheetIndex($sheet_name2); + if ($sheet2 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula"); + } + + // Reverse max and min sheet numbers if necessary + if ($sheet1 > $sheet2) { + list($sheet1, $sheet2) = array($sheet2, $sheet1); + } + } else { // Single sheet name only. + $sheet1 = $this->_getSheetIndex($ext_ref); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula"); + } + $sheet2 = $sheet1; + } + + // References are stored relative to 0xFFFF. + $offset = -1 - $sheet1; + + return pack('vdvv', $offset, 0x00, $sheet1, $sheet2); + } + + /** + * Look up the REF index that corresponds to an external sheet name + * (or range). If it doesn't exist yet add it to the workbook's references + * array. It assumes all sheet names given must exist. + * + * @access private + * @param string $ext_ref The name of the external reference + * @return mixed The reference index in packed() format on success + */ + function _getRefIndex($ext_ref) + { + $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. + $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with ' + + // Check if there is a sheet range eg., Sheet1:Sheet2. + if (preg_match("/:/", $ext_ref)) { + list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); + + $sheet1 = $this->_getSheetIndex($sheet_name1); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula"); + } + $sheet2 = $this->_getSheetIndex($sheet_name2); + if ($sheet2 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula"); + } + + // Reverse max and min sheet numbers if necessary + if ($sheet1 > $sheet2) { + list($sheet1, $sheet2) = array($sheet2, $sheet1); + } + } else { // Single sheet name only. + $sheet1 = $this->_getSheetIndex($ext_ref); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula"); + } + $sheet2 = $sheet1; + } + + // assume all references belong to this document + $supbook_index = 0x00; + $ref = pack('vvv', $supbook_index, $sheet1, $sheet2); + $total_references = count($this->_references); + $index = -1; + for ($i = 0; $i < $total_references; ++$i) { + if ($ref == $this->_references[$i]) { + $index = $i; + break; + } + } + // if REF was not found add it to references array + if ($index == -1) { + $this->_references[$total_references] = $ref; + $index = $total_references; + } + + return pack('v', $index); + } + + /** + * Look up the index that corresponds to an external sheet name. The hash of + * sheet names is updated by the addworksheet() method of the + * PHPExcel_Writer_Excel5_Workbook class. + * + * @access private + * @param string $sheet_name Sheet name + * @return integer The sheet index, -1 if the sheet was not found + */ + function _getSheetIndex($sheet_name) + { + if (!isset($this->_ext_sheets[$sheet_name])) { + return -1; + } else { + return $this->_ext_sheets[$sheet_name]; + } + } + + /** + * This method is used to update the array of sheet names. It is + * called by the addWorksheet() method of the + * PHPExcel_Writer_Excel5_Workbook class. + * + * @access public + * @see PHPExcel_Writer_Excel5_Workbook::addWorksheet() + * @param string $name The name of the worksheet being added + * @param integer $index The index of the worksheet being added + */ + function setExtSheet($name, $index) + { + $this->_ext_sheets[$name] = $index; + } + + /** + * pack() row and column into the required 3 or 4 byte format. + * + * @access private + * @param string $cell The Excel cell reference to be packed + * @return array Array containing the row and column in packed() format + */ + function _cellToPackedRowcol($cell) + { + $cell = strtoupper($cell); + list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell); + if ($col >= 256) { + throw new PHPExcel_Writer_Exception("Column in: $cell greater than 255"); + } + if ($row >= 65536) { + throw new PHPExcel_Writer_Exception("Row in: $cell greater than 65536 "); + } + + // Set the high bits to indicate if row or col are relative. + $col |= $col_rel << 14; + $col |= $row_rel << 15; + $col = pack('v', $col); + + $row = pack('v', $row); + + return array($row, $col); + } + + /** + * pack() row range into the required 3 or 4 byte format. + * Just using maximum col/rows, which is probably not the correct solution + * + * @access private + * @param string $range The Excel range to be packed + * @return array Array containing (row1,col1,row2,col2) in packed() format + */ + function _rangeToPackedRange($range) + { + preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); + // return absolute rows if there is a $ in the ref + $row1_rel = empty($match[1]) ? 1 : 0; + $row1 = $match[2]; + $row2_rel = empty($match[3]) ? 1 : 0; + $row2 = $match[4]; + // Convert 1-index to zero-index + --$row1; + --$row2; + // Trick poor inocent Excel + $col1 = 0; + $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!) + + // FIXME: this changes for BIFF8 + if (($row1 >= 65536) or ($row2 >= 65536)) { + throw new PHPExcel_Writer_Exception("Row in: $range greater than 65536 "); + } + + // Set the high bits to indicate if rows are relative. + $col1 |= $row1_rel << 15; + $col2 |= $row2_rel << 15; + $col1 = pack('v', $col1); + $col2 = pack('v', $col2); + + $row1 = pack('v', $row1); + $row2 = pack('v', $row2); + + return array($row1, $col1, $row2, $col2); + } + + /** + * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero + * indexed row and column number. Also returns two (0,1) values to indicate + * whether the row or column are relative references. + * + * @access private + * @param string $cell The Excel cell reference in A1 format. + * @return array + */ + function _cellToRowcol($cell) + { + preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match); + // return absolute column if there is a $ in the ref + $col_rel = empty($match[1]) ? 1 : 0; + $col_ref = $match[2]; + $row_rel = empty($match[3]) ? 1 : 0; + $row = $match[4]; + + // Convert base26 column string to a number. + $expn = strlen($col_ref) - 1; + $col = 0; + $col_ref_length = strlen($col_ref); + for ($i = 0; $i < $col_ref_length; ++$i) { + $col += (ord($col_ref{$i}) - 64) * pow(26, $expn); + --$expn; + } + + // Convert 1-index to zero-index + --$row; + --$col; + + return array($row, $col, $row_rel, $col_rel); + } + + /** + * Advance to the next valid token. + * + * @access private + */ + function _advance() + { + $i = $this->_current_char; + $formula_length = strlen($this->_formula); + // eat up white spaces + if ($i < $formula_length) { + while ($this->_formula{$i} == " ") { + ++$i; + } + + if ($i < ($formula_length - 1)) { + $this->_lookahead = $this->_formula{$i+1}; + } + $token = ''; + } + + while ($i < $formula_length) { + $token .= $this->_formula{$i}; + + if ($i < ($formula_length - 1)) { + $this->_lookahead = $this->_formula{$i+1}; + } else { + $this->_lookahead = ''; + } + + if ($this->_match($token) != '') { + //if ($i < strlen($this->_formula) - 1) { + // $this->_lookahead = $this->_formula{$i+1}; + //} + $this->_current_char = $i + 1; + $this->_current_token = $token; + return 1; + } + + if ($i < ($formula_length - 2)) { + $this->_lookahead = $this->_formula{$i+2}; + } else { // if we run out of characters _lookahead becomes empty + $this->_lookahead = ''; + } + ++$i; + } + //die("Lexical error ".$this->_current_char); + } + + /** + * Checks if it's a valid token. + * + * @access private + * @param mixed $token The token to check. + * @return mixed The checked token or false on failure + */ + function _match($token) + { + switch($token) { + case "+": + case "-": + case "*": + case "/": + case "(": + case ")": + case ",": + case ";": + case ">=": + case "<=": + case "=": + case "<>": + case "^": + case "&": + case "%": + return $token; + break; + case ">": + if ($this->_lookahead == '=') { // it's a GE token + break; + } + return $token; + break; + case "<": + // it's a LE or a NE token + if (($this->_lookahead == '=') or ($this->_lookahead == '>')) { + break; + } + return $token; + break; + default: + // if it's a reference A1 or $A$1 or $A1 or A$1 + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and + !preg_match("/[0-9]/",$this->_lookahead) and + ($this->_lookahead != ':') and ($this->_lookahead != '.') and + ($this->_lookahead != '!')) + { + return $token; + } + // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) + elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and + !preg_match("/[0-9]/",$this->_lookahead) and + ($this->_lookahead != ':') and ($this->_lookahead != '.')) + { + return $token; + } + // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) + elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$token) and + !preg_match("/[0-9]/",$this->_lookahead) and + ($this->_lookahead != ':') and ($this->_lookahead != '.')) + { + return $token; + } + // if it's a range A1:A2 or $A$1:$A$2 + elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) and + !preg_match("/[0-9]/",$this->_lookahead)) + { + return $token; + } + // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 + elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and + !preg_match("/[0-9]/",$this->_lookahead)) + { + return $token; + } + // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 + elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$token) and + !preg_match("/[0-9]/",$this->_lookahead)) + { + return $token; + } + // If it's a number (check that it's not a sheet name or range) + elseif (is_numeric($token) and + (!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and + ($this->_lookahead != '!') and ($this->_lookahead != ':')) + { + return $token; + } + // If it's a string (of maximum 255 characters) + elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/",$token) and $this->_lookahead != '"' and (substr_count($token, '"')%2 == 0)) + { + return $token; + } + // If it's an error code + elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') + { + return $token; + } + // if it's a function call + elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$token) and ($this->_lookahead == "(")) + { + return $token; + } + // It's an argument of some description (e.g. a named range), + // precise nature yet to be determined + elseif(substr($token,-1) == ')') { + return $token; + } + return ''; + } + } + + /** + * The parsing method. It parses a formula. + * + * @access public + * @param string $formula The formula to parse, without the initial equal + * sign (=). + * @return mixed true on success + */ + function parse($formula) + { + $this->_current_char = 0; + $this->_formula = $formula; + $this->_lookahead = isset($formula{1}) ? $formula{1} : ''; + $this->_advance(); + $this->_parse_tree = $this->_condition(); + return true; + } + + /** + * It parses a condition. It assumes the following rule: + * Cond -> Expr [(">" | "<") Expr] + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + function _condition() + { + $result = $this->_expression(); + if ($this->_current_token == "<") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgLT', $result, $result2); + } elseif ($this->_current_token == ">") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgGT', $result, $result2); + } elseif ($this->_current_token == "<=") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgLE', $result, $result2); + } elseif ($this->_current_token == ">=") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgGE', $result, $result2); + } elseif ($this->_current_token == "=") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgEQ', $result, $result2); + } elseif ($this->_current_token == "<>") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgNE', $result, $result2); + } elseif ($this->_current_token == "&") { + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgConcat', $result, $result2); + } + return $result; + } + + /** + * It parses a expression. It assumes the following rule: + * Expr -> Term [("+" | "-") Term] + * -> "string" + * -> "-" Term : Negative value + * -> "+" Term : Positive value + * -> Error code + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + function _expression() + { + // If it's a string return a string node + if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->_current_token)) { + $tmp = str_replace('""', '"', $this->_current_token); + if (($tmp == '"') || ($tmp == '')) $tmp = '""'; // Trap for "" that has been used for an empty string + $result = $this->_createTree($tmp, '', ''); + $this->_advance(); + return $result; + // If it's an error code + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->_current_token) or $this->_current_token == '#N/A'){ + $result = $this->_createTree($this->_current_token, 'ptgErr', ''); + $this->_advance(); + return $result; + // If it's a negative value + } elseif ($this->_current_token == "-") { + // catch "-" Term + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgUminus', $result2, ''); + return $result; + // If it's a positive value + } elseif ($this->_current_token == "+") { + // catch "+" Term + $this->_advance(); + $result2 = $this->_expression(); + $result = $this->_createTree('ptgUplus', $result2, ''); + return $result; + } + $result = $this->_term(); + while (($this->_current_token == "+") or + ($this->_current_token == "-") or + ($this->_current_token == "^")) { + /**/ + if ($this->_current_token == "+") { + $this->_advance(); + $result2 = $this->_term(); + $result = $this->_createTree('ptgAdd', $result, $result2); + } elseif ($this->_current_token == "-") { + $this->_advance(); + $result2 = $this->_term(); + $result = $this->_createTree('ptgSub', $result, $result2); + } else { + $this->_advance(); + $result2 = $this->_term(); + $result = $this->_createTree('ptgPower', $result, $result2); + } + } + return $result; + } + + /** + * This function just introduces a ptgParen element in the tree, so that Excel + * doesn't get confused when working with a parenthesized formula afterwards. + * + * @access private + * @see _fact() + * @return array The parsed ptg'd tree + */ + function _parenthesizedExpression() + { + $result = $this->_createTree('ptgParen', $this->_expression(), ''); + return $result; + } + + /** + * It parses a term. It assumes the following rule: + * Term -> Fact [("*" | "/") Fact] + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + function _term() + { + $result = $this->_fact(); + while (($this->_current_token == "*") or + ($this->_current_token == "/")) { + /**/ + if ($this->_current_token == "*") { + $this->_advance(); + $result2 = $this->_fact(); + $result = $this->_createTree('ptgMul', $result, $result2); + } else { + $this->_advance(); + $result2 = $this->_fact(); + $result = $this->_createTree('ptgDiv', $result, $result2); + } + } + return $result; + } + + /** + * It parses a factor. It assumes the following rule: + * Fact -> ( Expr ) + * | CellRef + * | CellRange + * | Number + * | Function + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + function _fact() + { + if ($this->_current_token == "(") { + $this->_advance(); // eat the "(" + $result = $this->_parenthesizedExpression(); + if ($this->_current_token != ")") { + throw new PHPExcel_Writer_Exception("')' token expected."); + } + $this->_advance(); // eat the ")" + return $result; + } + // if it's a reference + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$this->_current_token)) + { + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) + elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token)) + { + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) + elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u",$this->_current_token)) + { + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // if it's a range A1:B2 or $A$1:$B$2 + elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token) or + preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/',$this->_current_token)) + { + // must be an error? + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) + elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token)) + { + // must be an error? + //$result = $this->_current_token; + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) + elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u",$this->_current_token)) + { + // must be an error? + //$result = $this->_current_token; + $result = $this->_createTree($this->_current_token, '', ''); + $this->_advance(); + return $result; + } + // If it's a number or a percent + elseif (is_numeric($this->_current_token)) + { + if($this->_lookahead == '%'){ + $result = $this->_createTree('ptgPercent', $this->_current_token, ''); + } else { + $result = $this->_createTree($this->_current_token, '', ''); + } + $this->_advance(); + return $result; + } + // if it's a function call + elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i",$this->_current_token)) + { + $result = $this->_func(); + return $result; + } + throw new PHPExcel_Writer_Exception("Syntax error: ".$this->_current_token. + ", lookahead: ".$this->_lookahead. + ", current char: ".$this->_current_char); + } + + /** + * It parses a function call. It assumes the following rule: + * Func -> ( Expr [,Expr]* ) + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + function _func() + { + $num_args = 0; // number of arguments received + $function = strtoupper($this->_current_token); + $result = ''; // initialize result + $this->_advance(); + $this->_advance(); // eat the "(" + while ($this->_current_token != ')') { + /**/ + if ($num_args > 0) { + if ($this->_current_token == "," or + $this->_current_token == ";") + { + $this->_advance(); // eat the "," or ";" + } else { + throw new PHPExcel_Writer_Exception("Syntax error: comma expected in ". + "function $function, arg #{$num_args}"); + } + $result2 = $this->_condition(); + $result = $this->_createTree('arg', $result, $result2); + } else { // first argument + $result2 = $this->_condition(); + $result = $this->_createTree('arg', '', $result2); + } + ++$num_args; + } + if (!isset($this->_functions[$function])) { + throw new PHPExcel_Writer_Exception("Function $function() doesn't exist"); + } + $args = $this->_functions[$function][1]; + // If fixed number of args eg. TIME($i,$j,$k). Check that the number of args is valid. + if (($args >= 0) and ($args != $num_args)) { + throw new PHPExcel_Writer_Exception("Incorrect number of arguments in function $function() "); + } + + $result = $this->_createTree($function, $result, $num_args); + $this->_advance(); // eat the ")" + return $result; + } + + /** + * Creates a tree. In fact an array which may have one or two arrays (sub-trees) + * as elements. + * + * @access private + * @param mixed $value The value of this node. + * @param mixed $left The left array (sub-tree) or a final node. + * @param mixed $right The right array (sub-tree) or a final node. + * @return array A tree + */ + function _createTree($value, $left, $right) + { + return array('value' => $value, 'left' => $left, 'right' => $right); + } + + /** + * Builds a string containing the tree in reverse polish notation (What you + * would use in a HP calculator stack). + * The following tree: + * + * + + * / \ + * 2 3 + * + * produces: "23+" + * + * The following tree: + * + * + + * / \ + * 3 * + * / \ + * 6 A1 + * + * produces: "36A1*+" + * + * In fact all operands, functions, references, etc... are written as ptg's + * + * @access public + * @param array $tree The optional tree to convert. + * @return string The tree in reverse polish notation + */ + function toReversePolish($tree = array()) + { + $polish = ""; // the string we are going to return + if (empty($tree)) { // If it's the first call use _parse_tree + $tree = $this->_parse_tree; + } + + if (is_array($tree['left'])) { + $converted_tree = $this->toReversePolish($tree['left']); + $polish .= $converted_tree; + } elseif ($tree['left'] != '') { // It's a final node + $converted_tree = $this->_convert($tree['left']); + $polish .= $converted_tree; + } + if (is_array($tree['right'])) { + $converted_tree = $this->toReversePolish($tree['right']); + $polish .= $converted_tree; + } elseif ($tree['right'] != '') { // It's a final node + $converted_tree = $this->_convert($tree['right']); + $polish .= $converted_tree; + } + // if it's a function convert it here (so we can set it's arguments) + if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and + !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and + !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and + !is_numeric($tree['value']) and + !isset($this->ptg[$tree['value']])) + { + // left subtree for a function is always an array. + if ($tree['left'] != '') { + $left_tree = $this->toReversePolish($tree['left']); + } else { + $left_tree = ''; + } + // add it's left subtree and return. + return $left_tree.$this->_convertFunction($tree['value'], $tree['right']); + } else { + $converted_tree = $this->_convert($tree['value']); + } + $polish .= $converted_tree; + return $polish; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php new file mode 100644 index 00000000..e14bcba4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php @@ -0,0 +1,1450 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ + + +/** + * PHPExcel_Writer_Excel5_Workbook + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Workbook extends PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $_parser; + + /** + * The BIFF file size for the workbook. + * @var integer + * @see _calcSheetOffsets() + */ + public $_biffsize; + + /** + * XF Writers + * @var PHPExcel_Writer_Excel5_Xf[] + */ + private $_xfWriters = array(); + + /** + * Array containing the colour palette + * @var array + */ + public $_palette; + + /** + * The codepage indicates the text encoding used for strings + * @var integer + */ + public $_codepage; + + /** + * The country code used for localization + * @var integer + */ + public $_country_code; + + /** + * Workbook + * @var PHPExcel + */ + private $_phpExcel; + + /** + * Fonts writers + * + * @var PHPExcel_Writer_Excel5_Font[] + */ + private $_fontWriters = array(); + + /** + * Added fonts. Maps from font's hash => index in workbook + * + * @var array + */ + private $_addedFonts = array(); + + /** + * Shared number formats + * + * @var array + */ + private $_numberFormats = array(); + + /** + * Added number formats. Maps from numberFormat's hash => index in workbook + * + * @var array + */ + private $_addedNumberFormats = array(); + + /** + * Sizes of the binary worksheet streams + * + * @var array + */ + private $_worksheetSizes = array(); + + /** + * Offsets of the binary worksheet streams relative to the start of the global workbook stream + * + * @var array + */ + private $_worksheetOffsets = array(); + + /** + * Total number of shared strings in workbook + * + * @var int + */ + private $_str_total; + + /** + * Number of unique shared strings in workbook + * + * @var int + */ + private $_str_unique; + + /** + * Array of unique shared strings in workbook + * + * @var array + */ + private $_str_table; + + /** + * Color cache + */ + private $_colors; + + /** + * Escher object corresponding to MSODRAWINGGROUP + * + * @var PHPExcel_Shared_Escher + */ + private $_escher; + + + /** + * Class constructor + * + * @param PHPExcel $phpExcel The Workbook + * @param int &$str_total Total number of strings + * @param int &$str_unique Total number of unique strings + * @param array &$str_table String Table + * @param array &$colors Colour Table + * @param mixed $parser The formula parser created for the Workbook + */ + public function __construct(PHPExcel $phpExcel = null, + &$str_total, &$str_unique, &$str_table, &$colors, + $parser ) + { + // It needs to call its parent's constructor explicitly + parent::__construct(); + + $this->_parser = $parser; + $this->_biffsize = 0; + $this->_palette = array(); + $this->_country_code = -1; + + $this->_str_total = &$str_total; + $this->_str_unique = &$str_unique; + $this->_str_table = &$str_table; + $this->_colors = &$colors; + $this->_setPaletteXl97(); + + $this->_phpExcel = $phpExcel; + + // set BIFFwriter limit for CONTINUE records + // $this->_limit = 8224; + $this->_codepage = 0x04B0; + + // Add empty sheets and Build color cache + $countSheets = $phpExcel->getSheetCount(); + for ($i = 0; $i < $countSheets; ++$i) { + $phpSheet = $phpExcel->getSheet($i); + + $this->_parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser + + $supbook_index = 0x00; + $ref = pack('vvv', $supbook_index, $i, $i); + $this->_parser->_references[] = $ref; // Register reference with parser + + // Sheet tab colors? + if ($phpSheet->isTabColorSet()) { + $this->_addColor($phpSheet->getTabColor()->getRGB()); + } + } + + } + + /** + * Add a new XF writer + * + * @param PHPExcel_Style + * @param boolean Is it a style XF? + * @return int Index to XF record + */ + public function addXfWriter($style, $isStyleXf = false) + { + $xfWriter = new PHPExcel_Writer_Excel5_Xf($style); + $xfWriter->setIsStyleXf($isStyleXf); + + // Add the font if not already added + $fontIndex = $this->_addFont($style->getFont()); + + // Assign the font index to the xf record + $xfWriter->setFontIndex($fontIndex); + + // Background colors, best to treat these after the font so black will come after white in custom palette + $xfWriter->setFgColor($this->_addColor($style->getFill()->getStartColor()->getRGB())); + $xfWriter->setBgColor($this->_addColor($style->getFill()->getEndColor()->getRGB())); + $xfWriter->setBottomColor($this->_addColor($style->getBorders()->getBottom()->getColor()->getRGB())); + $xfWriter->setTopColor($this->_addColor($style->getBorders()->getTop()->getColor()->getRGB())); + $xfWriter->setRightColor($this->_addColor($style->getBorders()->getRight()->getColor()->getRGB())); + $xfWriter->setLeftColor($this->_addColor($style->getBorders()->getLeft()->getColor()->getRGB())); + $xfWriter->setDiagColor($this->_addColor($style->getBorders()->getDiagonal()->getColor()->getRGB())); + + // Add the number format if it is not a built-in one and not already added + if ($style->getNumberFormat()->getBuiltInFormatCode() === false) { + $numberFormatHashCode = $style->getNumberFormat()->getHashCode(); + + if (isset($this->_addedNumberFormats[$numberFormatHashCode])) { + $numberFormatIndex = $this->_addedNumberFormats[$numberFormatHashCode]; + } else { + $numberFormatIndex = 164 + count($this->_numberFormats); + $this->_numberFormats[$numberFormatIndex] = $style->getNumberFormat(); + $this->_addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex; + } + } else { + $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode(); + } + + // Assign the number format index to xf record + $xfWriter->setNumberFormatIndex($numberFormatIndex); + + $this->_xfWriters[] = $xfWriter; + + $xfIndex = count($this->_xfWriters) - 1; + return $xfIndex; + } + + /** + * Add a font to added fonts + * + * @param PHPExcel_Style_Font $font + * @return int Index to FONT record + */ + public function _addFont(PHPExcel_Style_Font $font) + { + $fontHashCode = $font->getHashCode(); + if(isset($this->_addedFonts[$fontHashCode])){ + $fontIndex = $this->_addedFonts[$fontHashCode]; + } else { + $countFonts = count($this->_fontWriters); + $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1; + + $fontWriter = new PHPExcel_Writer_Excel5_Font($font); + $fontWriter->setColorIndex($this->_addColor($font->getColor()->getRGB())); + $this->_fontWriters[] = $fontWriter; + + $this->_addedFonts[$fontHashCode] = $fontIndex; + } + return $fontIndex; + } + + /** + * Alter color palette adding a custom color + * + * @param string $rgb E.g. 'FF00AA' + * @return int Color index + */ + private function _addColor($rgb) { + if (!isset($this->_colors[$rgb])) { + if (count($this->_colors) < 57) { + // then we add a custom color altering the palette + $colorIndex = 8 + count($this->_colors); + $this->_palette[$colorIndex] = + array( + hexdec(substr($rgb, 0, 2)), + hexdec(substr($rgb, 2, 2)), + hexdec(substr($rgb, 4)), + 0 + ); + $this->_colors[$rgb] = $colorIndex; + } else { + // no room for more custom colors, just map to black + $colorIndex = 0; + } + } else { + // fetch already added custom color + $colorIndex = $this->_colors[$rgb]; + } + + return $colorIndex; + } + + /** + * Sets the colour palette to the Excel 97+ default. + * + * @access private + */ + function _setPaletteXl97() + { + $this->_palette = array( + 0x08 => array(0x00, 0x00, 0x00, 0x00), + 0x09 => array(0xff, 0xff, 0xff, 0x00), + 0x0A => array(0xff, 0x00, 0x00, 0x00), + 0x0B => array(0x00, 0xff, 0x00, 0x00), + 0x0C => array(0x00, 0x00, 0xff, 0x00), + 0x0D => array(0xff, 0xff, 0x00, 0x00), + 0x0E => array(0xff, 0x00, 0xff, 0x00), + 0x0F => array(0x00, 0xff, 0xff, 0x00), + 0x10 => array(0x80, 0x00, 0x00, 0x00), + 0x11 => array(0x00, 0x80, 0x00, 0x00), + 0x12 => array(0x00, 0x00, 0x80, 0x00), + 0x13 => array(0x80, 0x80, 0x00, 0x00), + 0x14 => array(0x80, 0x00, 0x80, 0x00), + 0x15 => array(0x00, 0x80, 0x80, 0x00), + 0x16 => array(0xc0, 0xc0, 0xc0, 0x00), + 0x17 => array(0x80, 0x80, 0x80, 0x00), + 0x18 => array(0x99, 0x99, 0xff, 0x00), + 0x19 => array(0x99, 0x33, 0x66, 0x00), + 0x1A => array(0xff, 0xff, 0xcc, 0x00), + 0x1B => array(0xcc, 0xff, 0xff, 0x00), + 0x1C => array(0x66, 0x00, 0x66, 0x00), + 0x1D => array(0xff, 0x80, 0x80, 0x00), + 0x1E => array(0x00, 0x66, 0xcc, 0x00), + 0x1F => array(0xcc, 0xcc, 0xff, 0x00), + 0x20 => array(0x00, 0x00, 0x80, 0x00), + 0x21 => array(0xff, 0x00, 0xff, 0x00), + 0x22 => array(0xff, 0xff, 0x00, 0x00), + 0x23 => array(0x00, 0xff, 0xff, 0x00), + 0x24 => array(0x80, 0x00, 0x80, 0x00), + 0x25 => array(0x80, 0x00, 0x00, 0x00), + 0x26 => array(0x00, 0x80, 0x80, 0x00), + 0x27 => array(0x00, 0x00, 0xff, 0x00), + 0x28 => array(0x00, 0xcc, 0xff, 0x00), + 0x29 => array(0xcc, 0xff, 0xff, 0x00), + 0x2A => array(0xcc, 0xff, 0xcc, 0x00), + 0x2B => array(0xff, 0xff, 0x99, 0x00), + 0x2C => array(0x99, 0xcc, 0xff, 0x00), + 0x2D => array(0xff, 0x99, 0xcc, 0x00), + 0x2E => array(0xcc, 0x99, 0xff, 0x00), + 0x2F => array(0xff, 0xcc, 0x99, 0x00), + 0x30 => array(0x33, 0x66, 0xff, 0x00), + 0x31 => array(0x33, 0xcc, 0xcc, 0x00), + 0x32 => array(0x99, 0xcc, 0x00, 0x00), + 0x33 => array(0xff, 0xcc, 0x00, 0x00), + 0x34 => array(0xff, 0x99, 0x00, 0x00), + 0x35 => array(0xff, 0x66, 0x00, 0x00), + 0x36 => array(0x66, 0x66, 0x99, 0x00), + 0x37 => array(0x96, 0x96, 0x96, 0x00), + 0x38 => array(0x00, 0x33, 0x66, 0x00), + 0x39 => array(0x33, 0x99, 0x66, 0x00), + 0x3A => array(0x00, 0x33, 0x00, 0x00), + 0x3B => array(0x33, 0x33, 0x00, 0x00), + 0x3C => array(0x99, 0x33, 0x00, 0x00), + 0x3D => array(0x99, 0x33, 0x66, 0x00), + 0x3E => array(0x33, 0x33, 0x99, 0x00), + 0x3F => array(0x33, 0x33, 0x33, 0x00), + ); + } + + /** + * Assemble worksheets into a workbook and send the BIFF data to an OLE + * storage. + * + * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams + * @return string Binary data for workbook stream + */ + public function writeWorkbook($pWorksheetSizes = null) + { + $this->_worksheetSizes = $pWorksheetSizes; + + // Calculate the number of selected worksheet tabs and call the finalization + // methods for each worksheet + $total_worksheets = $this->_phpExcel->getSheetCount(); + + // Add part 1 of the Workbook globals, what goes before the SHEET records + $this->_storeBof(0x0005); + $this->_writeCodepage(); + $this->_writeWindow1(); + + $this->_writeDatemode(); + $this->_writeAllFonts(); + $this->_writeAllNumFormats(); + $this->_writeAllXfs(); + $this->_writeAllStyles(); + $this->_writePalette(); + + // Prepare part 3 of the workbook global stream, what goes after the SHEET records + $part3 = ''; + if ($this->_country_code != -1) { + $part3 .= $this->_writeCountry(); + } + $part3 .= $this->_writeRecalcId(); + + $part3 .= $this->_writeSupbookInternal(); + /* TODO: store external SUPBOOK records and XCT and CRN records + in case of external references for BIFF8 */ + $part3 .= $this->_writeExternsheetBiff8(); + $part3 .= $this->_writeAllDefinedNamesBiff8(); + $part3 .= $this->_writeMsoDrawingGroup(); + $part3 .= $this->_writeSharedStringsTable(); + + $part3 .= $this->writeEof(); + + // Add part 2 of the Workbook globals, the SHEET records + $this->_calcSheetOffsets(); + for ($i = 0; $i < $total_worksheets; ++$i) { + $this->_writeBoundsheet($this->_phpExcel->getSheet($i), $this->_worksheetOffsets[$i]); + } + + // Add part 3 of the Workbook globals + $this->_data .= $part3; + + return $this->_data; + } + + /** + * Calculate offsets for Worksheet BOF records. + * + * @access private + */ + function _calcSheetOffsets() + { + $boundsheet_length = 10; // fixed length for a BOUNDSHEET record + + // size of Workbook globals part 1 + 3 + $offset = $this->_datasize; + + // add size of Workbook globals part 2, the length of the SHEET records + $total_worksheets = count($this->_phpExcel->getAllSheets()); + foreach ($this->_phpExcel->getWorksheetIterator() as $sheet) { + $offset += $boundsheet_length + strlen(PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle())); + } + + // add the sizes of each of the Sheet substreams, respectively + for ($i = 0; $i < $total_worksheets; ++$i) { + $this->_worksheetOffsets[$i] = $offset; + $offset += $this->_worksheetSizes[$i]; + } + $this->_biffsize = $offset; + } + + /** + * Store the Excel FONT records. + */ + private function _writeAllFonts() + { + foreach ($this->_fontWriters as $fontWriter) { + $this->_append($fontWriter->writeFont()); + } + } + + /** + * Store user defined numerical formats i.e. FORMAT records + */ + private function _writeAllNumFormats() + { + foreach ($this->_numberFormats as $numberFormatIndex => $numberFormat) { + $this->_writeNumFormat($numberFormat->getFormatCode(), $numberFormatIndex); + } + } + + /** + * Write all XF records. + */ + private function _writeAllXfs() + { + foreach ($this->_xfWriters as $xfWriter) { + $this->_append($xfWriter->writeXf()); + } + } + + /** + * Write all STYLE records. + */ + private function _writeAllStyles() + { + $this->_writeStyle(); + } + + /** + * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for + * the NAME records. + */ + private function _writeExterns() + { + $countSheets = $this->_phpExcel->getSheetCount(); + // Create EXTERNCOUNT with number of worksheets + $this->_writeExterncount($countSheets); + + // Create EXTERNSHEET for each worksheet + for ($i = 0; $i < $countSheets; ++$i) { + $this->_writeExternsheet($this->_phpExcel->getSheet($i)->getTitle()); + } + } + + /** + * Write the NAME record to define the print area and the repeat rows and cols. + */ + private function _writeNames() + { + // total number of sheets + $total_worksheets = $this->_phpExcel->getSheetCount(); + + // Create the print area NAME records + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup(); + // Write a Name record if the print area has been defined + if ($sheetSetup->isPrintAreaSet()) { + // Print area + $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea()); + $printArea = $printArea[0]; + $printArea[0] = PHPExcel_Cell::coordinateFromString($printArea[0]); + $printArea[1] = PHPExcel_Cell::coordinateFromString($printArea[1]); + + $print_rowmin = $printArea[0][1] - 1; + $print_rowmax = $printArea[1][1] - 1; + $print_colmin = PHPExcel_Cell::columnIndexFromString($printArea[0][0]) - 1; + $print_colmax = PHPExcel_Cell::columnIndexFromString($printArea[1][0]) - 1; + + $this->_writeNameShort( + $i, // sheet index + 0x06, // NAME type + $print_rowmin, + $print_rowmax, + $print_colmin, + $print_colmax + ); + } + } + + // Create the print title NAME records + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup(); + + // simultaneous repeatColumns repeatRows + if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + + $this->_writeNameLong( + $i, // sheet index + 0x07, // NAME type + $rowmin, + $rowmax, + $colmin, + $colmax + ); + + // (exclusive) either repeatColumns or repeatRows + } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { + + // Columns to repeat + if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + } else { + $colmin = 0; + $colmax = 255; + } + + // Rows to repeat + if ($sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + } else { + $rowmin = 0; + $rowmax = 65535; + } + + $this->_writeNameShort( + $i, // sheet index + 0x07, // NAME type + $rowmin, + $rowmax, + $colmin, + $colmax + ); + } + } + } + + /** + * Writes all the DEFINEDNAME records (BIFF8). + * So far this is only used for repeating rows/columns (print titles) and print areas + */ + private function _writeAllDefinedNamesBiff8() + { + $chunk = ''; + + // Named ranges + if (count($this->_phpExcel->getNamedRanges()) > 0) { + // Loop named ranges + $namedRanges = $this->_phpExcel->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + + // Create absolute coordinate + $range = PHPExcel_Cell::splitRange($namedRange->getRange()); + for ($i = 0; $i < count($range); $i++) { + $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteCoordinate($range[$i][0]); + if (isset($range[$i][1])) { + $range[$i][1] = PHPExcel_Cell::absoluteCoordinate($range[$i][1]); + } + } + $range = PHPExcel_Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2 + + // parse formula + try { + $error = $this->_parser->parse($range); + $formulaData = $this->_parser->toReversePolish(); + + // make sure tRef3d is of type tRef3dR (0x3A) + if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) { + $formulaData = "\x3A" . substr($formulaData, 1); + } + + if ($namedRange->getLocalOnly()) { + // local scope + $scope = $this->_phpExcel->getIndex($namedRange->getScope()) + 1; + } else { + // global scope + $scope = 0; + } + $chunk .= $this->writeData($this->_writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false)); + + } catch(PHPExcel_Exception $e) { + // do nothing + } + } + } + + // total number of sheets + $total_worksheets = $this->_phpExcel->getSheetCount(); + + // write the print titles (repeating rows, columns), if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup(); + // simultaneous repeatColumns repeatRows + if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + + // construct formula data manually + $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc + $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d + $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d + $formulaData .= pack('C', 0x10); // tList + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); + + // (exclusive) either repeatColumns or repeatRows + } else if ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { + + // Columns to repeat + if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + } else { + $colmin = 0; + $colmax = 255; + } + // Rows to repeat + if ($sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + } else { + $rowmin = 0; + $rowmax = 65535; + } + + // construct formula data manually because parser does not recognize absolute 3d cell references + $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax); + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); + } + } + + // write the print areas, if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->_phpExcel->getSheet($i)->getPageSetup(); + if ($sheetSetup->isPrintAreaSet()) { + // Print area, e.g. A3:J6,H1:X20 + $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea()); + $countPrintArea = count($printArea); + + $formulaData = ''; + for ($j = 0; $j < $countPrintArea; ++$j) { + $printAreaRect = $printArea[$j]; // e.g. A3:J6 + $printAreaRect[0] = PHPExcel_Cell::coordinateFromString($printAreaRect[0]); + $printAreaRect[1] = PHPExcel_Cell::coordinateFromString($printAreaRect[1]); + + $print_rowmin = $printAreaRect[0][1] - 1; + $print_rowmax = $printAreaRect[1][1] - 1; + $print_colmin = PHPExcel_Cell::columnIndexFromString($printAreaRect[0][0]) - 1; + $print_colmax = PHPExcel_Cell::columnIndexFromString($printAreaRect[1][0]) - 1; + + // construct formula data manually because parser does not recognize absolute 3d cell references + $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); + + if ($j > 0) { + $formulaData .= pack('C', 0x10); // list operator token ',' + } + } + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->_writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true)); + } + } + + // write autofilters, if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetAutoFilter = $this->_phpExcel->getSheet($i)->getAutoFilter(); + $autoFilterRange = $sheetAutoFilter->getRange(); + if(!empty($autoFilterRange)) { + $rangeBounds = PHPExcel_Cell::rangeBoundaries($autoFilterRange); + + //Autofilter built in name + $name = pack('C', 0x0D); + + $chunk .= $this->writeData($this->_writeShortNameBiff8($name, $i + 1, $rangeBounds, true)); + } + } + + return $chunk; + } + + /** + * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data + * + * @param string $name The name in UTF-8 + * @param string $formulaData The binary formula data + * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param boolean $isBuiltIn Built-in name? + * @return string Complete binary record data + */ + private function _writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false) + { + $record = 0x0018; + + // option flags + $options = $isBuiltIn ? 0x20 : 0x00; + + // length of the name, character count + $nlen = PHPExcel_Shared_String::CountCharacters($name); + + // name with stripped length field + $name = substr(PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($name), 2); + + // size of the formula (in bytes) + $sz = strlen($formulaData); + + // combine the parts + $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0) + . $name . $formulaData; + $length = strlen($data); + + $header = pack('vv', $record, $length); + + return $header . $data; + } + + /** + * Write a short NAME record + * + * @param string $name + * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param integer[][] $rangeBounds range boundaries + * @param boolean $isHidden + * @return string Complete binary record data + * */ + private function _writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false){ + $record = 0x0018; + + // option flags + $options = ($isHidden ? 0x21 : 0x00); + + $extra = pack('Cvvvvv', + 0x3B, + $sheetIndex - 1, + $rangeBounds[0][1] - 1, + $rangeBounds[1][1] - 1, + $rangeBounds[0][0] - 1, + $rangeBounds[1][0] - 1); + + // size of the formula (in bytes) + $sz = strlen($extra); + + // combine the parts + $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0) + . $name . $extra; + $length = strlen($data); + + $header = pack('vv', $record, $length); + + return $header . $data; + } + + /** + * Stores the CODEPAGE biff record. + */ + private function _writeCodepage() + { + $record = 0x0042; // Record identifier + $length = 0x0002; // Number of bytes to follow + $cv = $this->_codepage; // The code page + + $header = pack('vv', $record, $length); + $data = pack('v', $cv); + + $this->_append($header . $data); + } + + /** + * Write Excel BIFF WINDOW1 record. + */ + private function _writeWindow1() + { + $record = 0x003D; // Record identifier + $length = 0x0012; // Number of bytes to follow + + $xWn = 0x0000; // Horizontal position of window + $yWn = 0x0000; // Vertical position of window + $dxWn = 0x25BC; // Width of window + $dyWn = 0x1572; // Height of window + + $grbit = 0x0038; // Option flags + + // not supported by PHPExcel, so there is only one selected sheet, the active + $ctabsel = 1; // Number of workbook tabs selected + + $wTabRatio = 0x0258; // Tab to scrollbar ratio + + // not supported by PHPExcel, set to 0 + $itabFirst = 0; // 1st displayed worksheet + $itabCur = $this->_phpExcel->getActiveSheetIndex(); // Active worksheet + + $header = pack("vv", $record, $length); + $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn, + $grbit, + $itabCur, $itabFirst, + $ctabsel, $wTabRatio); + $this->_append($header . $data); + } + + /** + * Writes Excel BIFF BOUNDSHEET record. + * + * @param PHPExcel_Worksheet $sheet Worksheet name + * @param integer $offset Location of worksheet BOF + */ + private function _writeBoundsheet($sheet, $offset) + { + $sheetname = $sheet->getTitle(); + $record = 0x0085; // Record identifier + + // sheet state + switch ($sheet->getSheetState()) { + case PHPExcel_Worksheet::SHEETSTATE_VISIBLE: $ss = 0x00; break; + case PHPExcel_Worksheet::SHEETSTATE_HIDDEN: $ss = 0x01; break; + case PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN: $ss = 0x02; break; + default: $ss = 0x00; break; + } + + // sheet type + $st = 0x00; + + $grbit = 0x0000; // Visibility and sheet type + + $data = pack("VCC", $offset, $ss, $st); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheetname); + + $length = strlen($data); + $header = pack("vv", $record, $length); + $this->_append($header . $data); + } + + /** + * Write Internal SUPBOOK record + */ + private function _writeSupbookInternal() + { + $record = 0x01AE; // Record identifier + $length = 0x0004; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", $this->_phpExcel->getSheetCount(), 0x0401); + return $this->writeData($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. + * + */ + private function _writeExternsheetBiff8() + { + $total_references = count($this->_parser->_references); + $record = 0x0017; // Record identifier + $length = 2 + 6 * $total_references; // Number of bytes to follow + + $supbook_index = 0; // FIXME: only using internal SUPBOOK record + $header = pack("vv", $record, $length); + $data = pack('v', $total_references); + for ($i = 0; $i < $total_references; ++$i) { + $data .= $this->_parser->_references[$i]; + } + return $this->writeData($header . $data); + } + + /** + * Write Excel BIFF STYLE records. + */ + private function _writeStyle() + { + $record = 0x0293; // Record identifier + $length = 0x0004; // Bytes to follow + + $ixfe = 0x8000; // Index to cell style XF + $BuiltIn = 0x00; // Built-in style + $iLevel = 0xff; // Outline style level + + $header = pack("vv", $record, $length); + $data = pack("vCC", $ixfe, $BuiltIn, $iLevel); + $this->_append($header . $data); + } + + /** + * Writes Excel FORMAT record for non "built-in" numerical formats. + * + * @param string $format Custom format string + * @param integer $ifmt Format index code + */ + private function _writeNumFormat($format, $ifmt) + { + $record = 0x041E; // Record identifier + + $numberFormatString = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($format); + $length = 2 + strlen($numberFormatString); // Number of bytes to follow + + + $header = pack("vv", $record, $length); + $data = pack("v", $ifmt) . $numberFormatString; + $this->_append($header . $data); + } + + /** + * Write DATEMODE record to indicate the date system in use (1904 or 1900). + */ + private function _writeDatemode() + { + $record = 0x0022; // Record identifier + $length = 0x0002; // Bytes to follow + + $f1904 = (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) ? + 1 : 0; // Flag for 1904 date system + + $header = pack("vv", $record, $length); + $data = pack("v", $f1904); + $this->_append($header . $data); + } + + /** + * Write BIFF record EXTERNCOUNT to indicate the number of external sheet + * references in the workbook. + * + * Excel only stores references to external sheets that are used in NAME. + * The workbook NAME record is required to define the print area and the repeat + * rows and columns. + * + * A similar method is used in Worksheet.php for a slightly different purpose. + * + * @param integer $cxals Number of external references + */ + private function _writeExterncount($cxals) + { + $record = 0x0016; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cxals); + $this->_append($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. NAME record is required to define the print area and the repeat + * rows and columns. + * + * A similar method is used in Worksheet.php for a slightly different purpose. + * + * @param string $sheetname Worksheet name + */ + private function _writeExternsheet($sheetname) + { + $record = 0x0017; // Record identifier + $length = 0x02 + strlen($sheetname); // Number of bytes to follow + + $cch = strlen($sheetname); // Length of sheet name + $rgch = 0x03; // Filename encoding + + $header = pack("vv", $record, $length); + $data = pack("CC", $cch, $rgch); + $this->_append($header . $data . $sheetname); + } + + /** + * Store the NAME record in the short format that is used for storing the print + * area, repeat rows only and repeat columns only. + * + * @param integer $index Sheet index + * @param integer $type Built-in name type + * @param integer $rowmin Start row + * @param integer $rowmax End row + * @param integer $colmin Start colum + * @param integer $colmax End column + */ + private function _writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax) + { + $record = 0x0018; // Record identifier + $length = 0x0024; // Number of bytes to follow + + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x0015; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text + $cchDescription = 0x00; // Length of description text + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type + + $unknown03 = 0x3b; + $unknown04 = 0xffff-$index; + $unknown05 = 0x0000; + $unknown06 = 0x0000; + $unknown07 = 0x1087; + $unknown08 = 0x8005; + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $data .= pack("C", $chKey); + $data .= pack("C", $cch); + $data .= pack("v", $cce); + $data .= pack("v", $ixals); + $data .= pack("v", $itab); + $data .= pack("C", $cchCustMenu); + $data .= pack("C", $cchDescription); + $data .= pack("C", $cchHelptopic); + $data .= pack("C", $cchStatustext); + $data .= pack("C", $rgch); + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", $rowmin); + $data .= pack("v", $rowmax); + $data .= pack("C", $colmin); + $data .= pack("C", $colmax); + $this->_append($header . $data); + } + + /** + * Store the NAME record in the long format that is used for storing the repeat + * rows and columns when both are specified. This shares a lot of code with + * _writeNameShort() but we use a separate method to keep the code clean. + * Code abstraction for reuse can be carried too far, and I should know. ;-) + * + * @param integer $index Sheet index + * @param integer $type Built-in name type + * @param integer $rowmin Start row + * @param integer $rowmax End row + * @param integer $colmin Start colum + * @param integer $colmax End column + */ + private function _writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax) + { + $record = 0x0018; // Record identifier + $length = 0x003d; // Number of bytes to follow + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x002e; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text + $cchDescription = 0x00; // Length of description text + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type + + $unknown01 = 0x29; + $unknown02 = 0x002b; + $unknown03 = 0x3b; + $unknown04 = 0xffff-$index; + $unknown05 = 0x0000; + $unknown06 = 0x0000; + $unknown07 = 0x1087; + $unknown08 = 0x8008; + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $data .= pack("C", $chKey); + $data .= pack("C", $cch); + $data .= pack("v", $cce); + $data .= pack("v", $ixals); + $data .= pack("v", $itab); + $data .= pack("C", $cchCustMenu); + $data .= pack("C", $cchDescription); + $data .= pack("C", $cchHelptopic); + $data .= pack("C", $cchStatustext); + $data .= pack("C", $rgch); + $data .= pack("C", $unknown01); + $data .= pack("v", $unknown02); + // Column definition + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", 0x0000); + $data .= pack("v", 0x3fff); + $data .= pack("C", $colmin); + $data .= pack("C", $colmax); + // Row definition + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", $rowmin); + $data .= pack("v", $rowmax); + $data .= pack("C", 0x00); + $data .= pack("C", 0xff); + // End of data + $data .= pack("C", 0x10); + $this->_append($header . $data); + } + + /** + * Stores the COUNTRY record for localization + * + * @return string + */ + private function _writeCountry() + { + $record = 0x008C; // Record identifier + $length = 4; // Number of bytes to follow + + $header = pack('vv', $record, $length); + /* using the same country code always for simplicity */ + $data = pack('vv', $this->_country_code, $this->_country_code); + //$this->_append($header . $data); + return $this->writeData($header . $data); + } + + /** + * Write the RECALCID record + * + * @return string + */ + private function _writeRecalcId() + { + $record = 0x01C1; // Record identifier + $length = 8; // Number of bytes to follow + + $header = pack('vv', $record, $length); + + // by inspection of real Excel files, MS Office Excel 2007 writes this + $data = pack('VV', 0x000001C1, 0x00001E667); + + return $this->writeData($header . $data); + } + + /** + * Stores the PALETTE biff record. + */ + private function _writePalette() + { + $aref = $this->_palette; + + $record = 0x0092; // Record identifier + $length = 2 + 4 * count($aref); // Number of bytes to follow + $ccv = count($aref); // Number of RGB values to follow + $data = ''; // The RGB data + + // Pack the RGB data + foreach ($aref as $color) { + foreach ($color as $byte) { + $data .= pack("C",$byte); + } + } + + $header = pack("vvv", $record, $length, $ccv); + $this->_append($header . $data); + } + + /** + * Handling of the SST continue blocks is complicated by the need to include an + * additional continuation byte depending on whether the string is split between + * blocks or whether it starts at the beginning of the block. (There are also + * additional complications that will arise later when/if Rich Strings are + * supported). + * + * The Excel documentation says that the SST record should be followed by an + * EXTSST record. The EXTSST record is a hash table that is used to optimise + * access to SST. However, despite the documentation it doesn't seem to be + * required so we will ignore it. + * + * @return string Binary data + */ + private function _writeSharedStringsTable() + { + // maximum size of record data (excluding record header) + $continue_limit = 8224; + + // initialize array of record data blocks + $recordDatas = array(); + + // start SST record data block with total number of strings, total number of unique strings + $recordData = pack("VV", $this->_str_total, $this->_str_unique); + + // loop through all (unique) strings in shared strings table + foreach (array_keys($this->_str_table) as $string) { + + // here $string is a BIFF8 encoded string + + // length = character count + $headerinfo = unpack("vlength/Cencoding", $string); + + // currently, this is always 1 = uncompressed + $encoding = $headerinfo["encoding"]; + + // initialize finished writing current $string + $finished = false; + + while ($finished === false) { + + // normally, there will be only one cycle, but if string cannot immediately be written as is + // there will be need for more than one cylcle, if string longer than one record data block, there + // may be need for even more cycles + + if (strlen($recordData) + strlen($string) <= $continue_limit) { + // then we can write the string (or remainder of string) without any problems + $recordData .= $string; + + if (strlen($recordData) + strlen($string) == $continue_limit) { + // we close the record data block, and initialize a new one + $recordDatas[] = $recordData; + $recordData = ''; + } + + // we are finished writing this string + $finished = true; + } else { + // special treatment writing the string (or remainder of the string) + // If the string is very long it may need to be written in more than one CONTINUE record. + + // check how many bytes more there is room for in the current record + $space_remaining = $continue_limit - strlen($recordData); + + // minimum space needed + // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character + // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character + $min_space_needed = ($encoding == 1) ? 5 : 4; + + // We have two cases + // 1. space remaining is less than minimum space needed + // here we must waste the space remaining and move to next record data block + // 2. space remaining is greater than or equal to minimum space needed + // here we write as much as we can in the current block, then move to next record data block + + // 1. space remaining is less than minimum space needed + if ($space_remaining < $min_space_needed) { + // we close the block, store the block data + $recordDatas[] = $recordData; + + // and start new record data block where we start writing the string + $recordData = ''; + + // 2. space remaining is greater than or equal to minimum space needed + } else { + // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below + $effective_space_remaining = $space_remaining; + + // for uncompressed strings, sometimes effective space remaining is reduced by 1 + if ( $encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1 ) { + --$effective_space_remaining; + } + + // one block fininshed, store the block data + $recordData .= substr($string, 0, $effective_space_remaining); + + $string = substr($string, $effective_space_remaining); // for next cycle in while loop + $recordDatas[] = $recordData; + + // start new record data block with the repeated option flags + $recordData = pack('C', $encoding); + } + } + } + } + + // Store the last record data block unless it is empty + // if there was no need for any continue records, this will be the for SST record data block itself + if (strlen($recordData) > 0) { + $recordDatas[] = $recordData; + } + + // combine into one chunk with all the blocks SST, CONTINUE,... + $chunk = ''; + foreach ($recordDatas as $i => $recordData) { + // first block should have the SST record header, remaing should have CONTINUE header + $record = ($i == 0) ? 0x00FC : 0x003C; + + $header = pack("vv", $record, strlen($recordData)); + $data = $header . $recordData; + + $chunk .= $this->writeData($data); + } + + return $chunk; + } + + /** + * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records. + */ + private function _writeMsoDrawingGroup() + { + // write the Escher stream if necessary + if (isset($this->_escher)) { + $writer = new PHPExcel_Writer_Excel5_Escher($this->_escher); + $data = $writer->close(); + + $record = 0x00EB; + $length = strlen($data); + $header = pack("vv", $record, $length); + + return $this->writeData($header . $data); + + } else { + return ''; + } + } + + /** + * Get Escher object + * + * @return PHPExcel_Shared_Escher + */ + public function getEscher() + { + return $this->_escher; + } + + /** + * Set Escher object + * + * @param PHPExcel_Shared_Escher $pValue + */ + public function setEscher(PHPExcel_Shared_Escher $pValue = null) + { + $this->_escher = $pValue; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php new file mode 100644 index 00000000..55da26f3 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php @@ -0,0 +1,3681 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ + + +/** + * PHPExcel_Writer_Excel5_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Worksheet extends PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $_parser; + + /** + * Maximum number of characters for a string (LABEL record in BIFF5) + * @var integer + */ + public $_xls_strmax; + + /** + * Array containing format information for columns + * @var array + */ + public $_colinfo; + + /** + * Array containing the selected area for the worksheet + * @var array + */ + public $_selection; + + /** + * The active pane for the worksheet + * @var integer + */ + public $_active_pane; + + /** + * Whether to use outline. + * @var integer + */ + public $_outline_on; + + /** + * Auto outline styles. + * @var bool + */ + public $_outline_style; + + /** + * Whether to have outline summary below. + * @var bool + */ + public $_outline_below; + + /** + * Whether to have outline summary at the right. + * @var bool + */ + public $_outline_right; + + /** + * Reference to the total number of strings in the workbook + * @var integer + */ + public $_str_total; + + /** + * Reference to the number of unique strings in the workbook + * @var integer + */ + public $_str_unique; + + /** + * Reference to the array containing all the unique strings in the workbook + * @var array + */ + public $_str_table; + + /** + * Color cache + */ + private $_colors; + + /** + * Index of first used row (at least 0) + * @var int + */ + private $_firstRowIndex; + + /** + * Index of last used row. (no used rows means -1) + * @var int + */ + private $_lastRowIndex; + + /** + * Index of first used column (at least 0) + * @var int + */ + private $_firstColumnIndex; + + /** + * Index of last used column (no used columns means -1) + * @var int + */ + private $_lastColumnIndex; + + /** + * Sheet object + * @var PHPExcel_Worksheet + */ + public $_phpSheet; + + /** + * Count cell style Xfs + * + * @var int + */ + private $_countCellStyleXfs; + + /** + * Escher object corresponding to MSODRAWING + * + * @var PHPExcel_Shared_Escher + */ + private $_escher; + + /** + * Array of font hashes associated to FONT records index + * + * @var array + */ + public $_fntHashIndex; + + /** + * Constructor + * + * @param int &$str_total Total number of strings + * @param int &$str_unique Total number of unique strings + * @param array &$str_table String Table + * @param array &$colors Colour Table + * @param mixed $parser The formula parser created for the Workbook + * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written + * @param string $phpSheet The worksheet to write + * @param PHPExcel_Worksheet $phpSheet + */ + public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, + $parser, $preCalculateFormulas, $phpSheet) + { + // It needs to call its parent's constructor explicitly + parent::__construct(); + + // change BIFFwriter limit for CONTINUE records +// $this->_limit = 8224; + + + $this->_preCalculateFormulas = $preCalculateFormulas; + $this->_str_total = &$str_total; + $this->_str_unique = &$str_unique; + $this->_str_table = &$str_table; + $this->_colors = &$colors; + $this->_parser = $parser; + + $this->_phpSheet = $phpSheet; + + //$this->ext_sheets = array(); + //$this->offset = 0; + $this->_xls_strmax = 255; + $this->_colinfo = array(); + $this->_selection = array(0,0,0,0); + $this->_active_pane = 3; + + $this->_print_headers = 0; + + $this->_outline_style = 0; + $this->_outline_below = 1; + $this->_outline_right = 1; + $this->_outline_on = 1; + + $this->_fntHashIndex = array(); + + // calculate values for DIMENSIONS record + $minR = 1; + $minC = 'A'; + + $maxR = $this->_phpSheet->getHighestRow(); + $maxC = $this->_phpSheet->getHighestColumn(); + + // Determine lowest and highest column and row +// $this->_firstRowIndex = ($minR > 65535) ? 65535 : $minR; + $this->_lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ; + + $this->_firstColumnIndex = PHPExcel_Cell::columnIndexFromString($minC); + $this->_lastColumnIndex = PHPExcel_Cell::columnIndexFromString($maxC); + +// if ($this->_firstColumnIndex > 255) $this->_firstColumnIndex = 255; + if ($this->_lastColumnIndex > 255) $this->_lastColumnIndex = 255; + + $this->_countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection()); + } + + /** + * Add data to the beginning of the workbook (note the reverse order) + * and to the end of the workbook. + * + * @access public + * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook() + */ + function close() + { + $_phpSheet = $this->_phpSheet; + + $num_sheets = $_phpSheet->getParent()->getSheetCount(); + + // Write BOF record + $this->_storeBof(0x0010); + + // Write PRINTHEADERS + $this->_writePrintHeaders(); + + // Write PRINTGRIDLINES + $this->_writePrintGridlines(); + + // Write GRIDSET + $this->_writeGridset(); + + // Calculate column widths + $_phpSheet->calculateColumnWidths(); + + // Column dimensions + if (($defaultWidth = $_phpSheet->getDefaultColumnDimension()->getWidth()) < 0) { + $defaultWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($_phpSheet->getParent()->getDefaultStyle()->getFont()); + } + + $columnDimensions = $_phpSheet->getColumnDimensions(); + $maxCol = $this->_lastColumnIndex -1; + for ($i = 0; $i <= $maxCol; ++$i) { + $hidden = 0; + $level = 0; + $xfIndex = 15; // there are 15 cell style Xfs + + $width = $defaultWidth; + + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i); + if (isset($columnDimensions[$columnLetter])) { + $columnDimension = $columnDimensions[$columnLetter]; + if ($columnDimension->getWidth() >= 0) { + $width = $columnDimension->getWidth(); + } + $hidden = $columnDimension->getVisible() ? 0 : 1; + $level = $columnDimension->getOutlineLevel(); + $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs + } + + // Components of _colinfo: + // $firstcol first column on the range + // $lastcol last column on the range + // $width width to set + // $xfIndex The optional cell style Xf index to apply to the columns + // $hidden The optional hidden atribute + // $level The optional outline level + $this->_colinfo[] = array($i, $i, $width, $xfIndex, $hidden, $level); + } + + // Write GUTS + $this->_writeGuts(); + + // Write DEFAULTROWHEIGHT + $this->_writeDefaultRowHeight(); + + // Write WSBOOL + $this->_writeWsbool(); + + // Write horizontal and vertical page breaks + $this->_writeBreaks(); + + // Write page header + $this->_writeHeader(); + + // Write page footer + $this->_writeFooter(); + + // Write page horizontal centering + $this->_writeHcenter(); + + // Write page vertical centering + $this->_writeVcenter(); + + // Write left margin + $this->_writeMarginLeft(); + + // Write right margin + $this->_writeMarginRight(); + + // Write top margin + $this->_writeMarginTop(); + + // Write bottom margin + $this->_writeMarginBottom(); + + // Write page setup + $this->_writeSetup(); + + // Write sheet protection + $this->_writeProtect(); + + // Write SCENPROTECT + $this->_writeScenProtect(); + + // Write OBJECTPROTECT + $this->_writeObjectProtect(); + + // Write sheet password + $this->_writePassword(); + + // Write DEFCOLWIDTH record + $this->_writeDefcol(); + + // Write the COLINFO records if they exist + if (!empty($this->_colinfo)) { + $colcount = count($this->_colinfo); + for ($i = 0; $i < $colcount; ++$i) { + $this->_writeColinfo($this->_colinfo[$i]); + } + } + $autoFilterRange = $_phpSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + // Write AUTOFILTERINFO + $this->_writeAutoFilterInfo(); + } + + // Write sheet dimensions + $this->_writeDimensions(); + + // Row dimensions + foreach ($_phpSheet->getRowDimensions() as $rowDimension) { + $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs + $this->_writeRow( $rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel() ); + } + + // Write Cells + foreach ($_phpSheet->getCellCollection() as $cellID) { + $cell = $_phpSheet->getCell($cellID); + $row = $cell->getRow() - 1; + $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1; + + // Don't break Excel! +// if ($row + 1 > 65536 or $column + 1 > 256) { + if ($row > 65535 || $column > 255) { + break; + } + + // Write cell value + $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs + + $cVal = $cell->getValue(); + if ($cVal instanceof PHPExcel_RichText) { + // $this->_writeString($row, $column, $cVal->getPlainText(), $xfIndex); + $arrcRun = array(); + $str_len = PHPExcel_Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8'); + $str_pos = 0; + $elements = $cVal->getRichTextElements(); + foreach ($elements as $element) { + // FONT Index + if ($element instanceof PHPExcel_RichText_Run) { + $str_fontidx = $this->_fntHashIndex[$element->getFont()->getHashCode()]; + } + else { + $str_fontidx = 0; + } + $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx); + // Position FROM + $str_pos += PHPExcel_Shared_String::CountCharacters($element->getText(), 'UTF-8'); + } + $this->_writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun); + } else { + switch ($cell->getDatatype()) { + case PHPExcel_Cell_DataType::TYPE_STRING: + case PHPExcel_Cell_DataType::TYPE_NULL: + if ($cVal === '' || $cVal === null) { + $this->_writeBlank($row, $column, $xfIndex); + } else { + $this->_writeString($row, $column, $cVal, $xfIndex); + } + break; + + case PHPExcel_Cell_DataType::TYPE_NUMERIC: + $this->_writeNumber($row, $column, $cVal, $xfIndex); + break; + + case PHPExcel_Cell_DataType::TYPE_FORMULA: + $calculatedValue = $this->_preCalculateFormulas ? + $cell->getCalculatedValue() : null; + $this->_writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue); + break; + + case PHPExcel_Cell_DataType::TYPE_BOOL: + $this->_writeBoolErr($row, $column, $cVal, 0, $xfIndex); + break; + + case PHPExcel_Cell_DataType::TYPE_ERROR: + $this->_writeBoolErr($row, $column, self::_mapErrorCode($cVal), 1, $xfIndex); + break; + + } + } + } + + // Append + $this->_writeMsoDrawing(); + + // Write WINDOW2 record + $this->_writeWindow2(); + + // Write PLV record + $this->_writePageLayoutView(); + + // Write ZOOM record + $this->_writeZoom(); + if ($_phpSheet->getFreezePane()) { + $this->_writePanes(); + } + + // Write SELECTION record + $this->_writeSelection(); + + // Write MergedCellsTable Record + $this->_writeMergedCells(); + + // Hyperlinks + foreach ($_phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate); + + $url = $hyperlink->getUrl(); + + if ( strpos($url, 'sheet://') !== false ) { + // internal to current workbook + $url = str_replace('sheet://', 'internal:', $url); + + } else if ( preg_match('/^(http:|https:|ftp:|mailto:)/', $url) ) { + // URL + // $url = $url; + + } else { + // external (local file) + $url = 'external:' . $url; + } + + $this->_writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url); + } + + $this->_writeDataValidity(); + $this->_writeSheetLayout(); + + // Write SHEETPROTECTION record + $this->_writeSheetProtection(); + $this->_writeRangeProtection(); + + $arrConditionalStyles = $_phpSheet->getConditionalStylesCollection(); + if(!empty($arrConditionalStyles)){ + $arrConditional = array(); + // @todo CFRule & CFHeader + // Write CFHEADER record + $this->_writeCFHeader(); + // Write ConditionalFormattingTable records + foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){ + if(!in_array($conditional->getHashCode(), $arrConditional)){ + $arrConditional[] = $conditional->getHashCode(); + // Write CFRULE record + $this->_writeCFRule($conditional); + } + } + } + } + } + + $this->_storeEof(); + } + + /** + * Write a cell range address in BIFF8 + * always fixed range + * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format + * + * @param string $range E.g. 'A1' or 'A1:B6' + * @return string Binary data + */ + private function _writeBIFF8CellRangeAddressFixed($range = 'A1') + { + $explodes = explode(':', $range); + + // extract first cell, e.g. 'A1' + $firstCell = $explodes[0]; + + // extract last cell, e.g. 'B6' + if (count($explodes) == 1) { + $lastCell = $firstCell; + } else { + $lastCell = $explodes[1]; + } + + $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1) + $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6) + + return(pack('vvvv', + $firstCellCoordinates[1] - 1, + $lastCellCoordinates[1] - 1, + PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1, + PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1 + )); + } + + /** + * Retrieves data from memory in one chunk, or from disk in $buffer + * sized chunks. + * + * @return string The data + */ + function getData() + { + $buffer = 4096; + + // Return data stored in memory + if (isset($this->_data)) { + $tmp = $this->_data; + unset($this->_data); + return $tmp; + } + // No data to return + return false; + } + + /** + * Set the option to print the row and column headers on the printed page. + * + * @access public + * @param integer $print Whether to print the headers or not. Defaults to 1 (print). + */ + function printRowColHeaders($print = 1) + { + $this->_print_headers = $print; + } + + /** + * This method sets the properties for outlining and grouping. The defaults + * correspond to Excel's defaults. + * + * @param bool $visible + * @param bool $symbols_below + * @param bool $symbols_right + * @param bool $auto_style + */ + function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false) + { + $this->_outline_on = $visible; + $this->_outline_below = $symbols_below; + $this->_outline_right = $symbols_right; + $this->_outline_style = $auto_style; + + // Ensure this is a boolean vale for Window2 + if ($this->_outline_on) { + $this->_outline_on = 1; + } + } + + /** + * Write a double to the specified row and column (zero indexed). + * An integer can be written as a double. Excel will display an + * integer. $format is optional. + * + * Returns 0 : normal termination + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param float $num The number to write + * @param mixed $xfIndex The optional XF format + * @return integer + */ + private function _writeNumber($row, $col, $num, $xfIndex) + { + $record = 0x0203; // Record identifier + $length = 0x000E; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $xfIndex); + $xl_double = pack("d", $num); + if (self::getByteOrder()) { // if it's Big Endian + $xl_double = strrev($xl_double); + } + + $this->_append($header.$data.$xl_double); + return(0); + } + + /** + * Write a LABELSST record or a LABEL record. Which one depends on BIFF version + * + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param string $str The string + * @param int $xfIndex Index to XF record + */ + private function _writeString($row, $col, $str, $xfIndex) + { + $this->_writeLabelSst($row, $col, $str, $xfIndex); + } + + /** + * Write a LABELSST record or a LABEL record. Which one depends on BIFF version + * It differs from _writeString by the writing of rich text strings. + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param string $str The string + * @param mixed $xfIndex The XF format index for the cell + * @param array $arrcRun Index to Font record and characters beginning + */ + private function _writeRichTextString($row, $col, $str, $xfIndex, $arrcRun){ + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow + $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun); + + /* check if string is already present */ + if (!isset($this->_str_table[$str])) { + $this->_str_table[$str] = $this->_str_unique++; + } + $this->_str_total++; + + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]); + $this->_append($header.$data); + } + + /** + * Write a string to the specified row and column (zero indexed). + * NOTE: there is an Excel 5 defined limit of 255 characters. + * $format is optional. + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @access public + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $str The string to write + * @param mixed $xfIndex The XF format index for the cell + * @return integer + */ + private function _writeLabel($row, $col, $str, $xfIndex) + { + $strlen = strlen($str); + $record = 0x0204; // Record identifier + $length = 0x0008 + $strlen; // Bytes to follow + + $str_error = 0; + + if ($strlen > $this->_xls_strmax) { // LABEL must be < 255 chars + $str = substr($str, 0, $this->_xls_strmax); + $length = 0x0008 + $this->_xls_strmax; + $strlen = $this->_xls_strmax; + $str_error = -3; + } + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row, $col, $xfIndex, $strlen); + $this->_append($header . $data . $str); + return($str_error); + } + + /** + * Write a string to the specified row and column (zero indexed). + * This is the BIFF8 version (no 255 chars limit). + * $format is optional. + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @access public + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $str The string to write + * @param mixed $xfIndex The XF format index for the cell + * @return integer + */ + private function _writeLabelSst($row, $col, $str, $xfIndex) + { + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow + + $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str); + + /* check if string is already present */ + if (!isset($this->_str_table[$str])) { + $this->_str_table[$str] = $this->_str_unique++; + } + $this->_str_total++; + + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->_str_table[$str]); + $this->_append($header.$data); + } + + /** + * Writes a note associated with the cell given by the row and column. + * NOTE records don't have a length limit. + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $note The note to write + */ + private function _writeNote($row, $col, $note) + { + $note_length = strlen($note); + $record = 0x001C; // Record identifier + $max_length = 2048; // Maximun length for a NOTE record + + // Length for this record is no more than 2048 + 6 + $length = 0x0006 + min($note_length, 2048); + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $note_length); + $this->_append($header . $data . substr($note, 0, 2048)); + + for ($i = $max_length; $i < $note_length; $i += $max_length) { + $chunk = substr($note, $i, $max_length); + $length = 0x0006 + strlen($chunk); + $header = pack("vv", $record, $length); + $data = pack("vvv", -1, 0, strlen($chunk)); + $this->_append($header.$data.$chunk); + } + return(0); + } + + /** + * Write a blank cell to the specified row and column (zero indexed). + * A blank cell is used to specify formatting without adding a string + * or a number. + * + * A blank cell without a format serves no purpose. Therefore, we don't write + * a BLANK record unless a format is specified. + * + * Returns 0 : normal termination (including no format) + * -1 : insufficient number of arguments + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param mixed $xfIndex The XF format index + */ + function _writeBlank($row, $col, $xfIndex) + { + $record = 0x0201; // Record identifier + $length = 0x0006; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $xfIndex); + $this->_append($header . $data); + return 0; + } + + /** + * Write a boolean or an error type to the specified row and column (zero indexed) + * + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param int $value + * @param boolean $isError Error or Boolean? + * @param int $xfIndex + */ + private function _writeBoolErr($row, $col, $value, $isError, $xfIndex) + { + $record = 0x0205; + $length = 8; + + $header = pack("vv", $record, $length); + $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError); + $this->_append($header . $data); + return 0; + } + + /** + * Write a formula to the specified row and column (zero indexed). + * The textual representation of the formula is passed to the parser in + * Parser.php which returns a packed binary string. + * + * Returns 0 : normal termination + * -1 : formula errors (bad formula) + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $formula The formula text string + * @param mixed $xfIndex The XF format index + * @param mixed $calculatedValue Calculated value + * @return integer + */ + private function _writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) + { + $record = 0x0006; // Record identifier + + // Initialize possible additional value for STRING record that should be written after the FORMULA record? + $stringValue = null; + + // calculated value + if (isset($calculatedValue)) { + // Since we can't yet get the data type of the calculated value, + // we use best effort to determine data type + if (is_bool($calculatedValue)) { + // Boolean value + $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF); + } elseif (is_int($calculatedValue) || is_float($calculatedValue)) { + // Numeric value + $num = pack('d', $calculatedValue); + } elseif (is_string($calculatedValue)) { + if (array_key_exists($calculatedValue, PHPExcel_Cell_DataType::getErrorCodes())) { + // Error value + $num = pack('CCCvCv', 0x02, 0x00, self::_mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF); + } elseif ($calculatedValue === '') { + // Empty string (and BIFF8) + $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); + } else { + // Non-empty string value (or empty string BIFF5) + $stringValue = $calculatedValue; + $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF); + } + } else { + // We are really not supposed to reach here + $num = pack('d', 0x00); + } + } else { + $num = pack('d', 0x00); + } + + $grbit = 0x03; // Option flags + $unknown = 0x0000; // Must be zero + + // Strip the '=' or '@' sign at the beginning of the formula string + if ($formula{0} == '=') { + $formula = substr($formula,1); + } else { + // Error handling + $this->_writeString($row, $col, 'Unrecognised character for formula'); + return -1; + } + + // Parse the formula using the parser in Parser.php + try { + $error = $this->_parser->parse($formula); + $formula = $this->_parser->toReversePolish(); + + $formlen = strlen($formula); // Length of the binary string + $length = 0x16 + $formlen; // Length of the record data + + $header = pack("vv", $record, $length); + + $data = pack("vvv", $row, $col, $xfIndex) + . $num + . pack("vVv", $grbit, $unknown, $formlen); + $this->_append($header . $data . $formula); + + // Append also a STRING record if necessary + if ($stringValue !== null) { + $this->_writeStringRecord($stringValue); + } + + return 0; + + } catch (PHPExcel_Exception $e) { + // do nothing + } + + } + + /** + * Write a STRING record. This + * + * @param string $stringValue + */ + private function _writeStringRecord($stringValue) + { + $record = 0x0207; // Record identifier + $data = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($stringValue); + + $length = strlen($data); + $header = pack('vv', $record, $length); + + $this->_append($header . $data); + } + + /** + * Write a hyperlink. + * This is comprised of two elements: the visible label and + * the invisible link. The visible label is the same as the link unless an + * alternative string is specified. The label is written using the + * _writeString() method. Therefore the 255 characters string limit applies. + * $string and $format are optional. + * + * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external + * directory url. + * + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @param integer $row Row + * @param integer $col Column + * @param string $url URL string + * @return integer + */ + private function _writeUrl($row, $col, $url) + { + // Add start row and col to arg list + return($this->_writeUrlRange($row, $col, $row, $col, $url)); + } + + /** + * This is the more general form of _writeUrl(). It allows a hyperlink to be + * written to a range of cells. This function also decides the type of hyperlink + * to be written. These are either, Web (http, ftp, mailto), Internal + * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). + * + * @access private + * @see _writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + function _writeUrlRange($row1, $col1, $row2, $col2, $url) + { + // Check for internal/external sheet links or default to web link + if (preg_match('[^internal:]', $url)) { + return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url)); + } + if (preg_match('[^external:]', $url)) { + return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url)); + } + return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url)); + } + + /** + * Used to write http, ftp and mailto hyperlinks. + * The link type ($options) is 0x03 is the same as absolute dir ref without + * sheet. However it is differentiated by the $unknown2 data stream. + * + * @access private + * @see _writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + function _writeUrlWeb($row1, $col1, $row2, $col2, $url) + { + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); + $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B"); + + // Pack the option flags + $options = pack("V", 0x03); + + // Convert URL to a null terminated wchar string + $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); + $url = $url . "\0\0\0"; + + // Pack the length of the URL + $url_len = pack("V", strlen($url)); + + // Calculate the data length + $length = 0x34 + strlen($url); + + // Pack the header data + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row1, $row2, $col1, $col2); + + // Write the packed data + $this->_append($header . $data . + $unknown1 . $options . + $unknown2 . $url_len . $url); + return 0; + } + + /** + * Used to write internal reference hyperlinks such as "Sheet1!A1". + * + * @access private + * @see _writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + function _writeUrlInternal($row1, $col1, $row2, $col2, $url) + { + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Strip URL type + $url = preg_replace('/^internal:/', '', $url); + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); + + // Pack the option flags + $options = pack("V", 0x08); + + // Convert the URL type and to a null terminated wchar string + $url .= "\0"; + + // character count + $url_len = PHPExcel_Shared_String::CountCharacters($url); + $url_len = pack('V', $url_len); + + $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8'); + + // Calculate the data length + $length = 0x24 + strlen($url); + + // Pack the header data + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row1, $row2, $col1, $col2); + + // Write the packed data + $this->_append($header . $data . + $unknown1 . $options . + $url_len . $url); + return 0; + } + + /** + * Write links to external directory names such as 'c:\foo.xls', + * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'. + * + * Note: Excel writes some relative links with the $dir_long string. We ignore + * these cases for the sake of simpler code. + * + * @access private + * @see _writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + function _writeUrlExternal($row1, $col1, $row2, $col2, $url) + { + // Network drives are different. We will handle them separately + // MS/Novell network drives and shares start with \\ + if (preg_match('[^external:\\\\]', $url)) { + return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); + } + + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Strip URL type and change Unix dir separator to Dos style (if needed) + // + $url = preg_replace('/^external:/', '', $url); + $url = preg_replace('/\//', "\\", $url); + + // Determine if the link is relative or absolute: + // relative if link contains no dir separator, "somefile.xls" + // relative if link starts with up-dir, "..\..\somefile.xls" + // otherwise, absolute + + $absolute = 0x00; // relative path + if ( preg_match('/^[A-Z]:/', $url) ) { + $absolute = 0x02; // absolute path on Windows, e.g. C:\... + } + $link_type = 0x01 | $absolute; + + // Determine if the link contains a sheet reference and change some of the + // parameters accordingly. + // Split the dir name and sheet name (if it exists) + $dir_long = $url; + if (preg_match("/\#/", $url)) { + $link_type |= 0x08; + } + + + // Pack the link type + $link_type = pack("V", $link_type); + + // Calculate the up-level dir count e.g.. (..\..\..\ == 3) + $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless); + $up_count = pack("v", $up_count); + + // Store the short dos dir name (null terminated) + $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0"; + + // Store the long dir name as a wchar string (non-null terminated) + $dir_long = $dir_long . "\0"; + + // Pack the lengths of the dir strings + $dir_short_len = pack("V", strlen($dir_short) ); + $dir_long_len = pack("V", strlen($dir_long) ); + $stream_len = pack("V", 0);//strlen($dir_long) + 0x06); + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' ); + $unknown2 = pack("H*",'0303000000000000C000000000000046' ); + $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000'); + $unknown4 = pack("v", 0x03 ); + + // Pack the main data stream + $data = pack("vvvv", $row1, $row2, $col1, $col2) . + $unknown1 . + $link_type . + $unknown2 . + $up_count . + $dir_short_len. + $dir_short . + $unknown3 . + $stream_len ;/*. + $dir_long_len . + $unknown4 . + $dir_long . + $sheet_len . + $sheet ;*/ + + // Pack the header data + $length = strlen($data); + $header = pack("vv", $record, $length); + + // Write the packed data + $this->_append($header. $data); + return 0; + } + + /** + * This method is used to set the height and format for a row. + * + * @param integer $row The row to set + * @param integer $height Height we are giving to the row. + * Use null to set XF without setting height + * @param integer $xfIndex The optional cell style Xf index to apply to the columns + * @param bool $hidden The optional hidden attribute + * @param integer $level The optional outline level for row, in range [0,7] + */ + private function _writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) + { + $record = 0x0208; // Record identifier + $length = 0x0010; // Number of bytes to follow + + $colMic = 0x0000; // First defined column + $colMac = 0x0000; // Last defined column + $irwMac = 0x0000; // Used by Excel to optimise loading + $reserved = 0x0000; // Reserved + $grbit = 0x0000; // Option flags + $ixfe = $xfIndex; + + if ( $height < 0 ){ + $height = null; + } + + // Use _writeRow($row, null, $XF) to set XF format without setting height + if ($height != null) { + $miyRw = $height * 20; // row height + } else { + $miyRw = 0xff; // default row height is 256 + } + + // Set the options flags. fUnsynced is used to show that the font and row + // heights are not compatible. This is usually the case for WriteExcel. + // The collapsed flag 0x10 doesn't seem to be used to indicate that a row + // is collapsed. Instead it is used to indicate that the previous row is + // collapsed. The zero height flag, 0x20, is used to collapse a row. + + $grbit |= $level; + if ($hidden) { + $grbit |= 0x0020; + } + if ($height !== null) { + $grbit |= 0x0040; // fUnsynced + } + if ($xfIndex !== 0xF) { + $grbit |= 0x0080; + } + $grbit |= 0x0100; + + $header = pack("vv", $record, $length); + $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw, + $irwMac,$reserved, $grbit, $ixfe); + $this->_append($header.$data); + } + + /** + * Writes Excel DIMENSIONS to define the area in which there is data. + */ + private function _writeDimensions() + { + $record = 0x0200; // Record identifier + + $length = 0x000E; + $data = pack('VVvvv' + , $this->_firstRowIndex + , $this->_lastRowIndex + 1 + , $this->_firstColumnIndex + , $this->_lastColumnIndex + 1 + , 0x0000 // reserved + ); + + $header = pack("vv", $record, $length); + $this->_append($header.$data); + } + + /** + * Write BIFF record Window2. + */ + private function _writeWindow2() + { + $record = 0x023E; // Record identifier + $length = 0x0012; + + $grbit = 0x00B6; // Option flags + $rwTop = 0x0000; // Top row visible in window + $colLeft = 0x0000; // Leftmost column visible in window + + + // The options flags that comprise $grbit + $fDspFmla = 0; // 0 - bit + $fDspGrid = $this->_phpSheet->getShowGridlines() ? 1 : 0; // 1 + $fDspRwCol = $this->_phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 + $fFrozen = $this->_phpSheet->getFreezePane() ? 1 : 0; // 3 + $fDspZeros = 1; // 4 + $fDefaultHdr = 1; // 5 + $fArabic = $this->_phpSheet->getRightToLeft() ? 1 : 0; // 6 + $fDspGuts = $this->_outline_on; // 7 + $fFrozenNoSplit = 0; // 0 - bit + // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet + $fSelected = ($this->_phpSheet === $this->_phpSheet->getParent()->getActiveSheet()) ? 1 : 0; + $fPaged = 1; // 2 + $fPageBreakPreview = $this->_phpSheet->getSheetView()->getView() === PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW; + + $grbit = $fDspFmla; + $grbit |= $fDspGrid << 1; + $grbit |= $fDspRwCol << 2; + $grbit |= $fFrozen << 3; + $grbit |= $fDspZeros << 4; + $grbit |= $fDefaultHdr << 5; + $grbit |= $fArabic << 6; + $grbit |= $fDspGuts << 7; + $grbit |= $fFrozenNoSplit << 8; + $grbit |= $fSelected << 9; + $grbit |= $fPaged << 10; + $grbit |= $fPageBreakPreview << 11; + + $header = pack("vv", $record, $length); + $data = pack("vvv", $grbit, $rwTop, $colLeft); + + // FIXME !!! + $rgbHdr = 0x0040; // Row/column heading and gridline color index + $zoom_factor_page_break = ($fPageBreakPreview? $this->_phpSheet->getSheetView()->getZoomScale() : 0x0000); + $zoom_factor_normal = $this->_phpSheet->getSheetView()->getZoomScaleNormal(); + + $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); + + $this->_append($header.$data); + } + + /** + * Write BIFF record DEFAULTROWHEIGHT. + */ + private function _writeDefaultRowHeight() + { + $defaultRowHeight = $this->_phpSheet->getDefaultRowDimension()->getRowHeight(); + + if ($defaultRowHeight < 0) { + return; + } + + // convert to twips + $defaultRowHeight = (int) 20 * $defaultRowHeight; + + $record = 0x0225; // Record identifier + $length = 0x0004; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", 1, $defaultRowHeight); + $this->_append($header . $data); + } + + /** + * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. + */ + private function _writeDefcol() + { + $defaultColWidth = 8; + + $record = 0x0055; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $defaultColWidth); + $this->_append($header . $data); + } + + /** + * Write BIFF record COLINFO to define column widths + * + * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C + * length record. + * + * @param array $col_array This is the only parameter received and is composed of the following: + * 0 => First formatted column, + * 1 => Last formatted column, + * 2 => Col width (8.43 is Excel default), + * 3 => The optional XF format of the column, + * 4 => Option flags. + * 5 => Optional outline level + */ + private function _writeColinfo($col_array) + { + if (isset($col_array[0])) { + $colFirst = $col_array[0]; + } + if (isset($col_array[1])) { + $colLast = $col_array[1]; + } + if (isset($col_array[2])) { + $coldx = $col_array[2]; + } else { + $coldx = 8.43; + } + if (isset($col_array[3])) { + $xfIndex = $col_array[3]; + } else { + $xfIndex = 15; + } + if (isset($col_array[4])) { + $grbit = $col_array[4]; + } else { + $grbit = 0; + } + if (isset($col_array[5])) { + $level = $col_array[5]; + } else { + $level = 0; + } + $record = 0x007D; // Record identifier + $length = 0x000C; // Number of bytes to follow + + $coldx *= 256; // Convert to units of 1/256 of a char + + $ixfe = $xfIndex; + $reserved = 0x0000; // Reserved + + $level = max(0, min($level, 7)); + $grbit |= $level << 8; + + $header = pack("vv", $record, $length); + $data = pack("vvvvvv", $colFirst, $colLast, $coldx, + $ixfe, $grbit, $reserved); + $this->_append($header.$data); + } + + /** + * Write BIFF record SELECTION. + */ + private function _writeSelection() + { + // look up the selected cell range + $selectedCells = $this->_phpSheet->getSelectedCells(); + $selectedCells = PHPExcel_Cell::splitRange($this->_phpSheet->getSelectedCells()); + $selectedCells = $selectedCells[0]; + if (count($selectedCells) == 2) { + list($first, $last) = $selectedCells; + } else { + $first = $selectedCells[0]; + $last = $selectedCells[0]; + } + + list($colFirst, $rwFirst) = PHPExcel_Cell::coordinateFromString($first); + $colFirst = PHPExcel_Cell::columnIndexFromString($colFirst) - 1; // base 0 column index + --$rwFirst; // base 0 row index + + list($colLast, $rwLast) = PHPExcel_Cell::coordinateFromString($last); + $colLast = PHPExcel_Cell::columnIndexFromString($colLast) - 1; // base 0 column index + --$rwLast; // base 0 row index + + // make sure we are not out of bounds + $colFirst = min($colFirst, 255); + $colLast = min($colLast, 255); + + $rwFirst = min($rwFirst, 65535); + $rwLast = min($rwLast, 65535); + + $record = 0x001D; // Record identifier + $length = 0x000F; // Number of bytes to follow + + $pnn = $this->_active_pane; // Pane position + $rwAct = $rwFirst; // Active row + $colAct = $colFirst; // Active column + $irefAct = 0; // Active cell ref + $cref = 1; // Number of refs + + if (!isset($rwLast)) { + $rwLast = $rwFirst; // Last row in reference + } + if (!isset($colLast)) { + $colLast = $colFirst; // Last col in reference + } + + // Swap last row/col for first row/col as necessary + if ($rwFirst > $rwLast) { + list($rwFirst, $rwLast) = array($rwLast, $rwFirst); + } + + if ($colFirst > $colLast) { + list($colFirst, $colLast) = array($colLast, $colFirst); + } + + $header = pack("vv", $record, $length); + $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct, + $irefAct, $cref, + $rwFirst, $rwLast, + $colFirst, $colLast); + $this->_append($header . $data); + } + + /** + * Store the MERGEDCELLS records for all ranges of merged cells + */ + private function _writeMergedCells() + { + $mergeCells = $this->_phpSheet->getMergeCells(); + $countMergeCells = count($mergeCells); + + if ($countMergeCells == 0) { + return; + } + + // maximum allowed number of merged cells per record + $maxCountMergeCellsPerRecord = 1027; + + // record identifier + $record = 0x00E5; + + // counter for total number of merged cells treated so far by the writer + $i = 0; + + // counter for number of merged cells written in record currently being written + $j = 0; + + // initialize record data + $recordData = ''; + + // loop through the merged cells + foreach ($mergeCells as $mergeCell) { + ++$i; + ++$j; + + // extract the row and column indexes + $range = PHPExcel_Cell::splitRange($mergeCell); + list($first, $last) = $range[0]; + list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first); + list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last); + + $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1); + + // flush record if we have reached limit for number of merged cells, or reached final merged cell + if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) { + $recordData = pack('v', $j) . $recordData; + $length = strlen($recordData); + $header = pack('vv', $record, $length); + $this->_append($header . $recordData); + + // initialize for next record, if any + $recordData = ''; + $j = 0; + } + } + } + + /** + * Write SHEETLAYOUT record + */ + private function _writeSheetLayout() + { + if (!$this->_phpSheet->isTabColorSet()) { + return; + } + + $recordData = pack( + 'vvVVVvv' + , 0x0862 + , 0x0000 // unused + , 0x00000000 // unused + , 0x00000000 // unused + , 0x00000014 // size of record data + , $this->_colors[$this->_phpSheet->getTabColor()->getRGB()] // color index + , 0x0000 // unused + ); + + $length = strlen($recordData); + + $record = 0x0862; // Record identifier + $header = pack('vv', $record, $length); + $this->_append($header . $recordData); + } + + /** + * Write SHEETPROTECTION + */ + private function _writeSheetProtection() + { + // record identifier + $record = 0x0867; + + // prepare options + $options = (int) !$this->_phpSheet->getProtection()->getObjects() + | (int) !$this->_phpSheet->getProtection()->getScenarios() << 1 + | (int) !$this->_phpSheet->getProtection()->getFormatCells() << 2 + | (int) !$this->_phpSheet->getProtection()->getFormatColumns() << 3 + | (int) !$this->_phpSheet->getProtection()->getFormatRows() << 4 + | (int) !$this->_phpSheet->getProtection()->getInsertColumns() << 5 + | (int) !$this->_phpSheet->getProtection()->getInsertRows() << 6 + | (int) !$this->_phpSheet->getProtection()->getInsertHyperlinks() << 7 + | (int) !$this->_phpSheet->getProtection()->getDeleteColumns() << 8 + | (int) !$this->_phpSheet->getProtection()->getDeleteRows() << 9 + | (int) !$this->_phpSheet->getProtection()->getSelectLockedCells() << 10 + | (int) !$this->_phpSheet->getProtection()->getSort() << 11 + | (int) !$this->_phpSheet->getProtection()->getAutoFilter() << 12 + | (int) !$this->_phpSheet->getProtection()->getPivotTables() << 13 + | (int) !$this->_phpSheet->getProtection()->getSelectUnlockedCells() << 14 ; + + // record data + $recordData = pack( + 'vVVCVVvv' + , 0x0867 // repeated record identifier + , 0x0000 // not used + , 0x0000 // not used + , 0x00 // not used + , 0x01000200 // unknown data + , 0xFFFFFFFF // unknown data + , $options // options + , 0x0000 // not used + ); + + $length = strlen($recordData); + $header = pack('vv', $record, $length); + + $this->_append($header . $recordData); + } + + /** + * Write BIFF record RANGEPROTECTION + * + * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records + * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records + */ + private function _writeRangeProtection() + { + foreach ($this->_phpSheet->getProtectedCells() as $range => $password) { + // number of ranges, e.g. 'A1:B3 C20:D25' + $cellRanges = explode(' ', $range); + $cref = count($cellRanges); + + $recordData = pack( + 'vvVVvCVvVv', + 0x0868, + 0x00, + 0x0000, + 0x0000, + 0x02, + 0x0, + 0x0000, + $cref, + 0x0000, + 0x00 + ); + + foreach ($cellRanges as $cellRange) { + $recordData .= $this->_writeBIFF8CellRangeAddressFixed($cellRange); + } + + // the rgbFeat structure + $recordData .= pack( + 'VV', + 0x0000, + hexdec($password) + ); + + $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData)); + + $length = strlen($recordData); + + $record = 0x0868; // Record identifier + $header = pack("vv", $record, $length); + $this->_append($header . $recordData); + } + } + + /** + * Write BIFF record EXTERNCOUNT to indicate the number of external sheet + * references in a worksheet. + * + * Excel only stores references to external sheets that are used in formulas. + * For simplicity we store references to all the sheets in the workbook + * regardless of whether they are used or not. This reduces the overall + * complexity and eliminates the need for a two way dialogue between the formula + * parser the worksheet objects. + * + * @param integer $count The number of external sheet references in this worksheet + */ + private function _writeExterncount($count) + { + $record = 0x0016; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $count); + $this->_append($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. A formula references a sheet name via an index. Since we store a + * reference to all of the external worksheets the EXTERNSHEET index is the same + * as the worksheet index. + * + * @param string $sheetname The name of a external worksheet + */ + private function _writeExternsheet($sheetname) + { + $record = 0x0017; // Record identifier + + // References to the current sheet are encoded differently to references to + // external sheets. + // + if ($this->_phpSheet->getTitle() == $sheetname) { + $sheetname = ''; + $length = 0x02; // The following 2 bytes + $cch = 1; // The following byte + $rgch = 0x02; // Self reference + } else { + $length = 0x02 + strlen($sheetname); + $cch = strlen($sheetname); + $rgch = 0x03; // Reference to a sheet in the current workbook + } + + $header = pack("vv", $record, $length); + $data = pack("CC", $cch, $rgch); + $this->_append($header . $data . $sheetname); + } + + /** + * Writes the Excel BIFF PANE record. + * The panes can either be frozen or thawed (unfrozen). + * Frozen panes are specified in terms of an integer number of rows and columns. + * Thawed panes are specified in terms of Excel's units for rows and columns. + */ + private function _writePanes() + { + $panes = array(); + if ($freezePane = $this->_phpSheet->getFreezePane()) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane); + $panes[0] = $row - 1; + $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1; + } else { + // thaw panes + return; + } + + $y = isset($panes[0]) ? $panes[0] : null; + $x = isset($panes[1]) ? $panes[1] : null; + $rwTop = isset($panes[2]) ? $panes[2] : null; + $colLeft = isset($panes[3]) ? $panes[3] : null; + if (count($panes) > 4) { // if Active pane was received + $pnnAct = $panes[4]; + } else { + $pnnAct = null; + } + $record = 0x0041; // Record identifier + $length = 0x000A; // Number of bytes to follow + + // Code specific to frozen or thawed panes. + if ($this->_phpSheet->getFreezePane()) { + // Set default values for $rwTop and $colLeft + if (!isset($rwTop)) { + $rwTop = $y; + } + if (!isset($colLeft)) { + $colLeft = $x; + } + } else { + // Set default values for $rwTop and $colLeft + if (!isset($rwTop)) { + $rwTop = 0; + } + if (!isset($colLeft)) { + $colLeft = 0; + } + + // Convert Excel's row and column units to the internal units. + // The default row height is 12.75 + // The default column width is 8.43 + // The following slope and intersection values were interpolated. + // + $y = 20*$y + 255; + $x = 113.879*$x + 390; + } + + + // Determine which pane should be active. There is also the undocumented + // option to override this should it be necessary: may be removed later. + // + if (!isset($pnnAct)) { + if ($x != 0 && $y != 0) { + $pnnAct = 0; // Bottom right + } + if ($x != 0 && $y == 0) { + $pnnAct = 1; // Top right + } + if ($x == 0 && $y != 0) { + $pnnAct = 2; // Bottom left + } + if ($x == 0 && $y == 0) { + $pnnAct = 3; // Top left + } + } + + $this->_active_pane = $pnnAct; // Used in _writeSelection + + $header = pack("vv", $record, $length); + $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct); + $this->_append($header . $data); + } + + /** + * Store the page setup SETUP BIFF record. + */ + private function _writeSetup() + { + $record = 0x00A1; // Record identifier + $length = 0x0022; // Number of bytes to follow + + $iPaperSize = $this->_phpSheet->getPageSetup()->getPaperSize(); // Paper size + + $iScale = $this->_phpSheet->getPageSetup()->getScale() ? + $this->_phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor + + $iPageStart = 0x01; // Starting page number + $iFitWidth = (int) $this->_phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide + $iFitHeight = (int) $this->_phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high + $grbit = 0x00; // Option flags + $iRes = 0x0258; // Print resolution + $iVRes = 0x0258; // Vertical print resolution + + $numHdr = $this->_phpSheet->getPageMargins()->getHeader(); // Header Margin + + $numFtr = $this->_phpSheet->getPageMargins()->getFooter(); // Footer Margin + $iCopies = 0x01; // Number of copies + + $fLeftToRight = 0x0; // Print over then down + + // Page orientation + $fLandscape = ($this->_phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? + 0x0 : 0x1; + + $fNoPls = 0x0; // Setup not read from printer + $fNoColor = 0x0; // Print black and white + $fDraft = 0x0; // Print draft quality + $fNotes = 0x0; // Print notes + $fNoOrient = 0x0; // Orientation not set + $fUsePage = 0x0; // Use custom starting page + + $grbit = $fLeftToRight; + $grbit |= $fLandscape << 1; + $grbit |= $fNoPls << 2; + $grbit |= $fNoColor << 3; + $grbit |= $fDraft << 4; + $grbit |= $fNotes << 5; + $grbit |= $fNoOrient << 6; + $grbit |= $fUsePage << 7; + + $numHdr = pack("d", $numHdr); + $numFtr = pack("d", $numFtr); + if (self::getByteOrder()) { // if it's Big Endian + $numHdr = strrev($numHdr); + $numFtr = strrev($numFtr); + } + + $header = pack("vv", $record, $length); + $data1 = pack("vvvvvvvv", $iPaperSize, + $iScale, + $iPageStart, + $iFitWidth, + $iFitHeight, + $grbit, + $iRes, + $iVRes); + $data2 = $numHdr.$numFtr; + $data3 = pack("v", $iCopies); + $this->_append($header . $data1 . $data2 . $data3); + } + + /** + * Store the header caption BIFF record. + */ + private function _writeHeader() + { + $record = 0x0014; // Record identifier + + /* removing for now + // need to fix character count (multibyte!) + if (strlen($this->_phpSheet->getHeaderFooter()->getOddHeader()) <= 255) { + $str = $this->_phpSheet->getHeaderFooter()->getOddHeader(); // header string + } else { + $str = ''; + } + */ + + $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddHeader()); + $length = strlen($recordData); + + $header = pack("vv", $record, $length); + + $this->_append($header . $recordData); + } + + /** + * Store the footer caption BIFF record. + */ + private function _writeFooter() + { + $record = 0x0015; // Record identifier + + /* removing for now + // need to fix character count (multibyte!) + if (strlen($this->_phpSheet->getHeaderFooter()->getOddFooter()) <= 255) { + $str = $this->_phpSheet->getHeaderFooter()->getOddFooter(); + } else { + $str = ''; + } + */ + + $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->_phpSheet->getHeaderFooter()->getOddFooter()); + $length = strlen($recordData); + + $header = pack("vv", $record, $length); + + $this->_append($header . $recordData); + } + + /** + * Store the horizontal centering HCENTER BIFF record. + * + * @access private + */ + private function _writeHcenter() + { + $record = 0x0083; // Record identifier + $length = 0x0002; // Bytes to follow + + $fHCenter = $this->_phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering + + $header = pack("vv", $record, $length); + $data = pack("v", $fHCenter); + + $this->_append($header.$data); + } + + /** + * Store the vertical centering VCENTER BIFF record. + */ + private function _writeVcenter() + { + $record = 0x0084; // Record identifier + $length = 0x0002; // Bytes to follow + + $fVCenter = $this->_phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering + + $header = pack("vv", $record, $length); + $data = pack("v", $fVCenter); + $this->_append($header . $data); + } + + /** + * Store the LEFTMARGIN BIFF record. + */ + private function _writeMarginLeft() + { + $record = 0x0026; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->_phpSheet->getPageMargins()->getLeft(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->_append($header . $data); + } + + /** + * Store the RIGHTMARGIN BIFF record. + */ + private function _writeMarginRight() + { + $record = 0x0027; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->_phpSheet->getPageMargins()->getRight(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->_append($header . $data); + } + + /** + * Store the TOPMARGIN BIFF record. + */ + private function _writeMarginTop() + { + $record = 0x0028; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->_phpSheet->getPageMargins()->getTop(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->_append($header . $data); + } + + /** + * Store the BOTTOMMARGIN BIFF record. + */ + private function _writeMarginBottom() + { + $record = 0x0029; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->_phpSheet->getPageMargins()->getBottom(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->_append($header . $data); + } + + /** + * Write the PRINTHEADERS BIFF record. + */ + private function _writePrintHeaders() + { + $record = 0x002a; // Record identifier + $length = 0x0002; // Bytes to follow + + $fPrintRwCol = $this->_print_headers; // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fPrintRwCol); + $this->_append($header . $data); + } + + /** + * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the + * GRIDSET record. + */ + private function _writePrintGridlines() + { + $record = 0x002b; // Record identifier + $length = 0x0002; // Bytes to follow + + $fPrintGrid = $this->_phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fPrintGrid); + $this->_append($header . $data); + } + + /** + * Write the GRIDSET BIFF record. Must be used in conjunction with the + * PRINTGRIDLINES record. + */ + private function _writeGridset() + { + $record = 0x0082; // Record identifier + $length = 0x0002; // Bytes to follow + + $fGridSet = !$this->_phpSheet->getPrintGridlines(); // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fGridSet); + $this->_append($header . $data); + } + + /** + * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet. + */ + private function _writeAutoFilterInfo(){ + $record = 0x009D; // Record identifier + $length = 0x0002; // Bytes to follow + + $rangeBounds = PHPExcel_Cell::rangeBoundaries($this->_phpSheet->getAutoFilter()->getRange()); + $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0]; + + $header = pack("vv", $record, $length); + $data = pack("v", $iNumFilters); + $this->_append($header . $data); + } + + /** + * Write the GUTS BIFF record. This is used to configure the gutter margins + * where Excel outline symbols are displayed. The visibility of the gutters is + * controlled by a flag in WSBOOL. + * + * @see _writeWsbool() + */ + private function _writeGuts() + { + $record = 0x0080; // Record identifier + $length = 0x0008; // Bytes to follow + + $dxRwGut = 0x0000; // Size of row gutter + $dxColGut = 0x0000; // Size of col gutter + + // determine maximum row outline level + $maxRowOutlineLevel = 0; + foreach ($this->_phpSheet->getRowDimensions() as $rowDimension) { + $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel()); + } + + $col_level = 0; + + // Calculate the maximum column outline level. The equivalent calculation + // for the row outline level is carried out in _writeRow(). + $colcount = count($this->_colinfo); + for ($i = 0; $i < $colcount; ++$i) { + $col_level = max($this->_colinfo[$i][5], $col_level); + } + + // Set the limits for the outline levels (0 <= x <= 7). + $col_level = max(0, min($col_level, 7)); + + // The displayed level is one greater than the max outline levels + if ($maxRowOutlineLevel) { + ++$maxRowOutlineLevel; + } + if ($col_level) { + ++$col_level; + } + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); + + $this->_append($header.$data); + } + + /** + * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction + * with the SETUP record. + */ + private function _writeWsbool() + { + $record = 0x0081; // Record identifier + $length = 0x0002; // Bytes to follow + $grbit = 0x0000; + + // The only option that is of interest is the flag for fit to page. So we + // set all the options in one go. + // + // Set the option flags + $grbit |= 0x0001; // Auto page breaks visible + if ($this->_outline_style) { + $grbit |= 0x0020; // Auto outline styles + } + if ($this->_phpSheet->getShowSummaryBelow()) { + $grbit |= 0x0040; // Outline summary below + } + if ($this->_phpSheet->getShowSummaryRight()) { + $grbit |= 0x0080; // Outline summary right + } + if ($this->_phpSheet->getPageSetup()->getFitToPage()) { + $grbit |= 0x0100; // Page setup fit to page + } + if ($this->_outline_on) { + $grbit |= 0x0400; // Outline symbols displayed + } + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $this->_append($header . $data); + } + + /** + * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records. + */ + private function _writeBreaks() + { + // initialize + $vbreaks = array(); + $hbreaks = array(); + + foreach ($this->_phpSheet->getBreaks() as $cell => $breakType) { + // Fetch coordinates + $coordinates = PHPExcel_Cell::coordinateFromString($cell); + + // Decide what to do by the type of break + switch ($breakType) { + case PHPExcel_Worksheet::BREAK_COLUMN: + // Add to list of vertical breaks + $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1; + break; + + case PHPExcel_Worksheet::BREAK_ROW: + // Add to list of horizontal breaks + $hbreaks[] = $coordinates[1]; + break; + + case PHPExcel_Worksheet::BREAK_NONE: + default: + // Nothing to do + break; + } + } + + //horizontal page breaks + if (!empty($hbreaks)) { + + // Sort and filter array of page breaks + sort($hbreaks, SORT_NUMERIC); + if ($hbreaks[0] == 0) { // don't use first break if it's 0 + array_shift($hbreaks); + } + + $record = 0x001b; // Record identifier + $cbrk = count($hbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cbrk); + + // Append each page break + foreach ($hbreaks as $hbreak) { + $data .= pack("vvv", $hbreak, 0x0000, 0x00ff); + } + + $this->_append($header . $data); + } + + // vertical page breaks + if (!empty($vbreaks)) { + + // 1000 vertical pagebreaks appears to be an internal Excel 5 limit. + // It is slightly higher in Excel 97/200, approx. 1026 + $vbreaks = array_slice($vbreaks, 0, 1000); + + // Sort and filter array of page breaks + sort($vbreaks, SORT_NUMERIC); + if ($vbreaks[0] == 0) { // don't use first break if it's 0 + array_shift($vbreaks); + } + + $record = 0x001a; // Record identifier + $cbrk = count($vbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cbrk); + + // Append each page break + foreach ($vbreaks as $vbreak) { + $data .= pack("vvv", $vbreak, 0x0000, 0xffff); + } + + $this->_append($header . $data); + } + } + + /** + * Set the Biff PROTECT record to indicate that the worksheet is protected. + */ + private function _writeProtect() + { + // Exit unless sheet protection has been specified + if (!$this->_phpSheet->getProtection()->getSheet()) { + return; + } + + $record = 0x0012; // Record identifier + $length = 0x0002; // Bytes to follow + + $fLock = 1; // Worksheet is protected + + $header = pack("vv", $record, $length); + $data = pack("v", $fLock); + + $this->_append($header.$data); + } + + /** + * Write SCENPROTECT + */ + private function _writeScenProtect() + { + // Exit if sheet protection is not active + if (!$this->_phpSheet->getProtection()->getSheet()) { + return; + } + + // Exit if scenarios are not protected + if (!$this->_phpSheet->getProtection()->getScenarios()) { + return; + } + + $record = 0x00DD; // Record identifier + $length = 0x0002; // Bytes to follow + + $header = pack('vv', $record, $length); + $data = pack('v', 1); + + $this->_append($header . $data); + } + + /** + * Write OBJECTPROTECT + */ + private function _writeObjectProtect() + { + // Exit if sheet protection is not active + if (!$this->_phpSheet->getProtection()->getSheet()) { + return; + } + + // Exit if objects are not protected + if (!$this->_phpSheet->getProtection()->getObjects()) { + return; + } + + $record = 0x0063; // Record identifier + $length = 0x0002; // Bytes to follow + + $header = pack('vv', $record, $length); + $data = pack('v', 1); + + $this->_append($header . $data); + } + + /** + * Write the worksheet PASSWORD record. + */ + private function _writePassword() + { + // Exit unless sheet protection and password have been specified + if (!$this->_phpSheet->getProtection()->getSheet() || !$this->_phpSheet->getProtection()->getPassword()) { + return; + } + + $record = 0x0013; // Record identifier + $length = 0x0002; // Bytes to follow + + $wPassword = hexdec($this->_phpSheet->getProtection()->getPassword()); // Encoded password + + $header = pack("vv", $record, $length); + $data = pack("v", $wPassword); + + $this->_append($header . $data); + } + + /** + * Insert a 24bit bitmap image in a worksheet. + * + * @access public + * @param integer $row The row we are going to insert the bitmap into + * @param integer $col The column we are going to insert the bitmap into + * @param mixed $bitmap The bitmap filename or GD-image resource + * @param integer $x The horizontal position (offset) of the image inside the cell. + * @param integer $y The vertical position (offset) of the image inside the cell. + * @param float $scale_x The horizontal scale + * @param float $scale_y The vertical scale + */ + function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1) + { + $bitmap_array = (is_resource($bitmap) ? $this->_processBitmapGd($bitmap) : $this->_processBitmap($bitmap)); + list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap); + + // Scale the frame of the image. + $width *= $scale_x; + $height *= $scale_y; + + // Calculate the vertices of the image and write the OBJ record + $this->_positionImage($col, $row, $x, $y, $width, $height); + + // Write the IMDATA record to store the bitmap data + $record = 0x007f; + $length = 8 + $size; + $cf = 0x09; + $env = 0x01; + $lcb = $size; + + $header = pack("vvvvV", $record, $length, $cf, $env, $lcb); + $this->_append($header.$data); + } + + /** + * Calculate the vertices that define the position of the image as required by + * the OBJ record. + * + * +------------+------------+ + * | A | B | + * +-----+------------+------------+ + * | |(x1,y1) | | + * | 1 |(A1)._______|______ | + * | | | | | + * | | | | | + * +-----+----| BITMAP |-----+ + * | | | | | + * | 2 | |______________. | + * | | | (B2)| + * | | | (x2,y2)| + * +---- +------------+------------+ + * + * Example of a bitmap that covers some of the area from cell A1 to cell B2. + * + * Based on the width and height of the bitmap we need to calculate 8 vars: + * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. + * The width and height of the cells are also variable and have to be taken into + * account. + * The values of $col_start and $row_start are passed in from the calling + * function. The values of $col_end and $row_end are calculated by subtracting + * the width and height of the bitmap from the width and height of the + * underlying cells. + * The vertices are expressed as a percentage of the underlying cell width as + * follows (rhs values are in pixels): + * + * x1 = X / W *1024 + * y1 = Y / H *256 + * x2 = (X-1) / W *1024 + * y2 = (Y-1) / H *256 + * + * Where: X is distance from the left side of the underlying cell + * Y is distance from the top of the underlying cell + * W is the width of the cell + * H is the height of the cell + * The SDK incorrectly states that the height should be expressed as a + * percentage of 1024. + * + * @access private + * @param integer $col_start Col containing upper left corner of object + * @param integer $row_start Row containing top left corner of object + * @param integer $x1 Distance to left side of object + * @param integer $y1 Distance to top of object + * @param integer $width Width of image frame + * @param integer $height Height of image frame + */ + function _positionImage($col_start, $row_start, $x1, $y1, $width, $height) + { + // Initialise end cell to the same as the start cell + $col_end = $col_start; // Col containing lower right corner of object + $row_end = $row_start; // Row containing bottom right corner of object + + // Zero the specified offset if greater than the cell dimensions + if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) { + $x1 = 0; + } + if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1)) { + $y1 = 0; + } + + $width = $width + $x1 -1; + $height = $height + $y1 -1; + + // Subtract the underlying cell widths to find the end cell of the image + while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) { + $width -= PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)); + ++$col_end; + } + + // Subtract the underlying cell heights to find the end cell of the image + while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1)) { + $height -= PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1); + ++$row_end; + } + + // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell + // with zero eight or width. + // + if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) == 0) { + return; + } + + // Convert the pixel values to the percentage value expected by Excel + $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_start + 1) * 256; + $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->_phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->_phpSheet, $row_end + 1) * 256; // Distance to bottom of object + + $this->_writeObjPicture($col_start, $x1, + $row_start, $y1, + $col_end, $x2, + $row_end, $y2); + } + + /** + * Store the OBJ record that precedes an IMDATA record. This could be generalise + * to support other Excel objects. + * + * @param integer $colL Column containing upper left corner of object + * @param integer $dxL Distance from left side of cell + * @param integer $rwT Row containing top left corner of object + * @param integer $dyT Distance from top of cell + * @param integer $colR Column containing lower right corner of object + * @param integer $dxR Distance from right of cell + * @param integer $rwB Row containing bottom right corner of object + * @param integer $dyB Distance from bottom of cell + */ + private function _writeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB) + { + $record = 0x005d; // Record identifier + $length = 0x003c; // Bytes to follow + + $cObj = 0x0001; // Count of objects in file (set to 1) + $OT = 0x0008; // Object type. 8 = Picture + $id = 0x0001; // Object ID + $grbit = 0x0614; // Option flags + + $cbMacro = 0x0000; // Length of FMLA structure + $Reserved1 = 0x0000; // Reserved + $Reserved2 = 0x0000; // Reserved + + $icvBack = 0x09; // Background colour + $icvFore = 0x09; // Foreground colour + $fls = 0x00; // Fill pattern + $fAuto = 0x00; // Automatic fill + $icv = 0x08; // Line colour + $lns = 0xff; // Line style + $lnw = 0x01; // Line weight + $fAutoB = 0x00; // Automatic border + $frs = 0x0000; // Frame style + $cf = 0x0009; // Image format, 9 = bitmap + $Reserved3 = 0x0000; // Reserved + $cbPictFmla = 0x0000; // Length of FMLA structure + $Reserved4 = 0x0000; // Reserved + $grbit2 = 0x0001; // Option flags + $Reserved5 = 0x0000; // Reserved + + + $header = pack("vv", $record, $length); + $data = pack("V", $cObj); + $data .= pack("v", $OT); + $data .= pack("v", $id); + $data .= pack("v", $grbit); + $data .= pack("v", $colL); + $data .= pack("v", $dxL); + $data .= pack("v", $rwT); + $data .= pack("v", $dyT); + $data .= pack("v", $colR); + $data .= pack("v", $dxR); + $data .= pack("v", $rwB); + $data .= pack("v", $dyB); + $data .= pack("v", $cbMacro); + $data .= pack("V", $Reserved1); + $data .= pack("v", $Reserved2); + $data .= pack("C", $icvBack); + $data .= pack("C", $icvFore); + $data .= pack("C", $fls); + $data .= pack("C", $fAuto); + $data .= pack("C", $icv); + $data .= pack("C", $lns); + $data .= pack("C", $lnw); + $data .= pack("C", $fAutoB); + $data .= pack("v", $frs); + $data .= pack("V", $cf); + $data .= pack("v", $Reserved3); + $data .= pack("v", $cbPictFmla); + $data .= pack("v", $Reserved4); + $data .= pack("v", $grbit2); + $data .= pack("V", $Reserved5); + + $this->_append($header . $data); + } + + /** + * Convert a GD-image into the internal format. + * + * @access private + * @param resource $image The image to process + * @return array Array with data and properties of the bitmap + */ + function _processBitmapGd($image) { + $width = imagesx($image); + $height = imagesy($image); + + $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); + for ($j=$height; $j--; ) { + for ($i=0; $i < $width; ++$i) { + $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); + foreach (array("red", "green", "blue") as $key) { + $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127); + } + $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]); + } + if (3*$width % 4) { + $data .= str_repeat("\x00", 4 - 3*$width % 4); + } + } + + return array($width, $height, strlen($data), $data); + } + + /** + * Convert a 24 bit bitmap into the modified internal format used by Windows. + * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the + * MSDN library. + * + * @access private + * @param string $bitmap The bitmap to process + * @return array Array with data and properties of the bitmap + */ + function _processBitmap($bitmap) + { + // Open file. + $bmp_fd = @fopen($bitmap,"rb"); + if (!$bmp_fd) { + throw new PHPExcel_Writer_Exception("Couldn't import $bitmap"); + } + + // Slurp the file into a string. + $data = fread($bmp_fd, filesize($bitmap)); + + // Check that the file is big enough to be a bitmap. + if (strlen($data) <= 0x36) { + throw new PHPExcel_Writer_Exception("$bitmap doesn't contain enough data.\n"); + } + + // The first 2 bytes are used to identify the bitmap. + $identity = unpack("A2ident", $data); + if ($identity['ident'] != "BM") { + throw new PHPExcel_Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n"); + } + + // Remove bitmap data: ID. + $data = substr($data, 2); + + // Read and remove the bitmap size. This is more reliable than reading + // the data size at offset 0x22. + // + $size_array = unpack("Vsa", substr($data, 0, 4)); + $size = $size_array['sa']; + $data = substr($data, 4); + $size -= 0x36; // Subtract size of bitmap header. + $size += 0x0C; // Add size of BIFF header. + + // Remove bitmap data: reserved, offset, header length. + $data = substr($data, 12); + + // Read and remove the bitmap width and height. Verify the sizes. + $width_and_height = unpack("V2", substr($data, 0, 8)); + $width = $width_and_height[1]; + $height = $width_and_height[2]; + $data = substr($data, 8); + if ($width > 0xFFFF) { + throw new PHPExcel_Writer_Exception("$bitmap: largest image width supported is 65k.\n"); + } + if ($height > 0xFFFF) { + throw new PHPExcel_Writer_Exception("$bitmap: largest image height supported is 65k.\n"); + } + + // Read and remove the bitmap planes and bpp data. Verify them. + $planes_and_bitcount = unpack("v2", substr($data, 0, 4)); + $data = substr($data, 4); + if ($planes_and_bitcount[2] != 24) { // Bitcount + throw new PHPExcel_Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n"); + } + if ($planes_and_bitcount[1] != 1) { + throw new PHPExcel_Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n"); + } + + // Read and remove the bitmap compression. Verify compression. + $compression = unpack("Vcomp", substr($data, 0, 4)); + $data = substr($data, 4); + + //$compression = 0; + if ($compression['comp'] != 0) { + throw new PHPExcel_Writer_Exception("$bitmap: compression not supported in bitmap image.\n"); + } + + // Remove bitmap data: data size, hres, vres, colours, imp. colours. + $data = substr($data, 20); + + // Add the BITMAPCOREHEADER data + $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); + $data = $header . $data; + + return (array($width, $height, $size, $data)); + } + + /** + * Store the window zoom factor. This should be a reduced fraction but for + * simplicity we will store all fractions with a numerator of 100. + */ + private function _writeZoom() + { + // If scale is 100 we don't need to write a record + if ($this->_phpSheet->getSheetView()->getZoomScale() == 100) { + return; + } + + $record = 0x00A0; // Record identifier + $length = 0x0004; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", $this->_phpSheet->getSheetView()->getZoomScale(), 100); + $this->_append($header . $data); + } + + /** + * Get Escher object + * + * @return PHPExcel_Shared_Escher + */ + public function getEscher() + { + return $this->_escher; + } + + /** + * Set Escher object + * + * @param PHPExcel_Shared_Escher $pValue + */ + public function setEscher(PHPExcel_Shared_Escher $pValue = null) + { + $this->_escher = $pValue; + } + + /** + * Write MSODRAWING record + */ + private function _writeMsoDrawing() + { + // write the Escher stream if necessary + if (isset($this->_escher)) { + $writer = new PHPExcel_Writer_Excel5_Escher($this->_escher); + $data = $writer->close(); + $spOffsets = $writer->getSpOffsets(); + $spTypes = $writer->getSpTypes(); + // write the neccesary MSODRAWING, OBJ records + + // split the Escher stream + $spOffsets[0] = 0; + $nm = count($spOffsets) - 1; // number of shapes excluding first shape + for ($i = 1; $i <= $nm; ++$i) { + // MSODRAWING record + $record = 0x00EC; // Record identifier + + // chunk of Escher stream for one shape + $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]); + + $length = strlen($dataChunk); + $header = pack("vv", $record, $length); + + $this->_append($header . $dataChunk); + + // OBJ record + $record = 0x005D; // record identifier + $objData = ''; + + // ftCmo + if($spTypes[$i] == 0x00C9){ + // Add ftCmo (common object data) subobject + $objData .= + pack('vvvvvVVV' + , 0x0015 // 0x0015 = ftCmo + , 0x0012 // length of ftCmo data + , 0x0014 // object type, 0x0014 = filter + , $i // object id number, Excel seems to use 1-based index, local for the sheet + , 0x2101 // option flags, 0x2001 is what OpenOffice.org uses + , 0 // reserved + , 0 // reserved + , 0 // reserved + ); + + // Add ftSbs Scroll bar subobject + $objData .= pack('vv', 0x00C, 0x0014); + $objData .= pack('H*', '0000000000000000640001000A00000010000100'); + // Add ftLbsData (List box data) subobject + $objData .= pack('vv', 0x0013, 0x1FEE); + $objData .= pack('H*', '00000000010001030000020008005700'); + } + else { + // Add ftCmo (common object data) subobject + $objData .= + pack('vvvvvVVV' + , 0x0015 // 0x0015 = ftCmo + , 0x0012 // length of ftCmo data + , 0x0008 // object type, 0x0008 = picture + , $i // object id number, Excel seems to use 1-based index, local for the sheet + , 0x6011 // option flags, 0x6011 is what OpenOffice.org uses + , 0 // reserved + , 0 // reserved + , 0 // reserved + ); + } + + // ftEnd + $objData .= + pack('vv' + , 0x0000 // 0x0000 = ftEnd + , 0x0000 // length of ftEnd data + ); + + $length = strlen($objData); + $header = pack('vv', $record, $length); + $this->_append($header . $objData); + } + } + } + + /** + * Store the DATAVALIDATIONS and DATAVALIDATION records. + */ + private function _writeDataValidity() + { + // Datavalidation collection + $dataValidationCollection = $this->_phpSheet->getDataValidationCollection(); + + // Write data validations? + if (!empty($dataValidationCollection)) { + + // DATAVALIDATIONS record + $record = 0x01B2; // Record identifier + $length = 0x0012; // Bytes to follow + + $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records + $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position + $verPos = 0x00000000; // Vertical position of prompt box, if fixed position + $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible + + $header = pack('vv', $record, $length); + $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, + count($dataValidationCollection)); + $this->_append($header.$data); + + // DATAVALIDATION records + $record = 0x01BE; // Record identifier + + foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { + // initialize record data + $data = ''; + + // options + $options = 0x00000000; + + // data type + $type = $dataValidation->getType(); + switch ($type) { + case PHPExcel_Cell_DataValidation::TYPE_NONE: $type = 0x00; break; + case PHPExcel_Cell_DataValidation::TYPE_WHOLE: $type = 0x01; break; + case PHPExcel_Cell_DataValidation::TYPE_DECIMAL: $type = 0x02; break; + case PHPExcel_Cell_DataValidation::TYPE_LIST: $type = 0x03; break; + case PHPExcel_Cell_DataValidation::TYPE_DATE: $type = 0x04; break; + case PHPExcel_Cell_DataValidation::TYPE_TIME: $type = 0x05; break; + case PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH: $type = 0x06; break; + case PHPExcel_Cell_DataValidation::TYPE_CUSTOM: $type = 0x07; break; + } + $options |= $type << 0; + + // error style + $errorStyle = $dataValidation->getType(); + switch ($errorStyle) { + case PHPExcel_Cell_DataValidation::STYLE_STOP: $errorStyle = 0x00; break; + case PHPExcel_Cell_DataValidation::STYLE_WARNING: $errorStyle = 0x01; break; + case PHPExcel_Cell_DataValidation::STYLE_INFORMATION: $errorStyle = 0x02; break; + } + $options |= $errorStyle << 4; + + // explicit formula? + if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) { + $options |= 0x01 << 7; + } + + // empty cells allowed + $options |= $dataValidation->getAllowBlank() << 8; + + // show drop down + $options |= (!$dataValidation->getShowDropDown()) << 9; + + // show input message + $options |= $dataValidation->getShowInputMessage() << 18; + + // show error message + $options |= $dataValidation->getShowErrorMessage() << 19; + + // condition operator + $operator = $dataValidation->getOperator(); + switch ($operator) { + case PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN: $operator = 0x00 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN: $operator = 0x01 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_EQUAL: $operator = 0x02 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL: $operator = 0x03 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN: $operator = 0x04 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN: $operator = 0x05 ; break; + case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: $operator = 0x06; break; + case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: $operator = 0x07 ; break; + } + $options |= $operator << 20; + + $data = pack('V', $options); + + // prompt title + $promptTitle = $dataValidation->getPromptTitle() !== '' ? + $dataValidation->getPromptTitle() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($promptTitle); + + // error title + $errorTitle = $dataValidation->getErrorTitle() !== '' ? + $dataValidation->getErrorTitle() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($errorTitle); + + // prompt text + $prompt = $dataValidation->getPrompt() !== '' ? + $dataValidation->getPrompt() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($prompt); + + // error text + $error = $dataValidation->getError() !== '' ? + $dataValidation->getError() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($error); + + // formula 1 + try { + $formula1 = $dataValidation->getFormula1(); + if ($type == 0x03) { // list type + $formula1 = str_replace(',', chr(0), $formula1); + } + $this->_parser->parse($formula1); + $formula1 = $this->_parser->toReversePolish(); + $sz1 = strlen($formula1); + + } catch(PHPExcel_Exception $e) { + $sz1 = 0; + $formula1 = ''; + } + $data .= pack('vv', $sz1, 0x0000); + $data .= $formula1; + + // formula 2 + try { + $formula2 = $dataValidation->getFormula2(); + if ($formula2 === '') { + throw new PHPExcel_Writer_Exception('No formula2'); + } + $this->_parser->parse($formula2); + $formula2 = $this->_parser->toReversePolish(); + $sz2 = strlen($formula2); + + } catch(PHPExcel_Exception $e) { + $sz2 = 0; + $formula2 = ''; + } + $data .= pack('vv', $sz2, 0x0000); + $data .= $formula2; + + // cell range address list + $data .= pack('v', 0x0001); + $data .= $this->_writeBIFF8CellRangeAddressFixed($cellCoordinate); + + $length = strlen($data); + $header = pack("vv", $record, $length); + + $this->_append($header . $data); + } + } + } + + /** + * Map Error code + * + * @param string $errorCode + * @return int + */ + private static function _mapErrorCode($errorCode) { + switch ($errorCode) { + case '#NULL!': return 0x00; + case '#DIV/0!': return 0x07; + case '#VALUE!': return 0x0F; + case '#REF!': return 0x17; + case '#NAME?': return 0x1D; + case '#NUM!': return 0x24; + case '#N/A': return 0x2A; + } + + return 0; + } + + /** + * Write PLV Record + */ + private function _writePageLayoutView(){ + $record = 0x088B; // Record identifier + $length = 0x0010; // Bytes to follow + + $rt = 0x088B; // 2 + $grbitFrt = 0x0000; // 2 + $reserved = 0x0000000000000000; // 8 + $wScalvePLV = $this->_phpSheet->getSheetView()->getZoomScale(); // 2 + + // The options flags that comprise $grbit + if($this->_phpSheet->getSheetView()->getView() == PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT){ + $fPageLayoutView = 1; + } else { + $fPageLayoutView = 0; + } + $fRulerVisible = 0; + $fWhitespaceHidden = 0; + + $grbit = $fPageLayoutView; // 2 + $grbit |= $fRulerVisible << 1; + $grbit |= $fWhitespaceHidden << 3; + + $header = pack("vv", $record, $length); + $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); + $this->_append($header . $data); + } + + /** + * Write CFRule Record + * @param PHPExcel_Style_Conditional $conditional + */ + private function _writeCFRule(PHPExcel_Style_Conditional $conditional){ + $record = 0x01B1; // Record identifier + + // $type : Type of the CF + // $operatorType : Comparison operator + if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION){ + $type = 0x02; + $operatorType = 0x00; + } else if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){ + $type = 0x01; + + switch ($conditional->getOperatorType()){ + case PHPExcel_Style_Conditional::OPERATOR_NONE: + $operatorType = 0x00; + break; + case PHPExcel_Style_Conditional::OPERATOR_EQUAL: + $operatorType = 0x03; + break; + case PHPExcel_Style_Conditional::OPERATOR_GREATERTHAN: + $operatorType = 0x05; + break; + case PHPExcel_Style_Conditional::OPERATOR_GREATERTHANOREQUAL: + $operatorType = 0x07; + break; + case PHPExcel_Style_Conditional::OPERATOR_LESSTHAN: + $operatorType = 0x06; + break; + case PHPExcel_Style_Conditional::OPERATOR_LESSTHANOREQUAL: + $operatorType = 0x08; + break; + case PHPExcel_Style_Conditional::OPERATOR_NOTEQUAL: + $operatorType = 0x04; + break; + case PHPExcel_Style_Conditional::OPERATOR_BETWEEN: + $operatorType = 0x01; + break; + // not OPERATOR_NOTBETWEEN 0x02 + } + } + + // $szValue1 : size of the formula data for first value or formula + // $szValue2 : size of the formula data for second value or formula + $arrConditions = $conditional->getConditions(); + $numConditions = sizeof($arrConditions); + if($numConditions == 1){ + $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); + $szValue2 = 0x0000; + $operand1 = pack('Cv', 0x1E, $arrConditions[0]); + $operand2 = null; + } else if($numConditions == 2 && ($conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BETWEEN)){ + $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); + $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000); + $operand1 = pack('Cv', 0x1E, $arrConditions[0]); + $operand2 = pack('Cv', 0x1E, $arrConditions[1]); + } else { + $szValue1 = 0x0000; + $szValue2 = 0x0000; + $operand1 = null; + $operand2 = null; + } + + // $flags : Option flags + // Alignment + $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0); + $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0); + $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0); + $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0); + $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0); + $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0); + if($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0){ + $bFormatAlign = 1; + } else { + $bFormatAlign = 0; + } + // Protection + $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0); + $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0); + if($bProtLocked == 0 || $bProtHidden == 0){ + $bFormatProt = 1; + } else { + $bFormatProt = 0; + } + // Border + $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + if($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0){ + $bFormatBorder = 1; + } else { + $bFormatBorder = 0; + } + // Pattern + $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1); + $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1); + $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1); + if($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0){ + $bFormatFill = 1; + } else { + $bFormatFill = 0; + } + // Font + if($conditional->getStyle()->getFont()->getName() != null + || $conditional->getStyle()->getFont()->getSize() != null + || $conditional->getStyle()->getFont()->getBold() != null + || $conditional->getStyle()->getFont()->getItalic() != null + || $conditional->getStyle()->getFont()->getSuperScript() != null + || $conditional->getStyle()->getFont()->getSubScript() != null + || $conditional->getStyle()->getFont()->getUnderline() != null + || $conditional->getStyle()->getFont()->getStrikethrough() != null + || $conditional->getStyle()->getFont()->getColor()->getARGB() != null){ + $bFormatFont = 1; + } else { + $bFormatFont = 0; + } + // Alignment + $flags = 0; + $flags |= (1 == $bAlignHz ? 0x00000001 : 0); + $flags |= (1 == $bAlignVt ? 0x00000002 : 0); + $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0); + $flags |= (1 == $bTxRotation ? 0x00000008 : 0); + // Justify last line flag + $flags |= (1 == 1 ? 0x00000010 : 0); + $flags |= (1 == $bIndent ? 0x00000020 : 0); + $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0); + // Default + $flags |= (1 == 1 ? 0x00000080 : 0); + // Protection + $flags |= (1 == $bProtLocked ? 0x00000100 : 0); + $flags |= (1 == $bProtHidden ? 0x00000200 : 0); + // Border + $flags |= (1 == $bBorderLeft ? 0x00000400 : 0); + $flags |= (1 == $bBorderRight ? 0x00000800 : 0); + $flags |= (1 == $bBorderTop ? 0x00001000 : 0); + $flags |= (1 == $bBorderBottom ? 0x00002000 : 0); + $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border + $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border + // Pattern + $flags |= (1 == $bFillStyle ? 0x00010000 : 0); + $flags |= (1 == $bFillColor ? 0x00020000 : 0); + $flags |= (1 == $bFillColorBg ? 0x00040000 : 0); + $flags |= (1 == 1 ? 0x00380000 : 0); + // Font + $flags |= (1 == $bFormatFont ? 0x04000000 : 0); + // Alignment : + $flags |= (1 == $bFormatAlign ? 0x08000000 : 0); + // Border + $flags |= (1 == $bFormatBorder ? 0x10000000 : 0); + // Pattern + $flags |= (1 == $bFormatFill ? 0x20000000 : 0); + // Protection + $flags |= (1 == $bFormatProt ? 0x40000000 : 0); + // Text direction + $flags |= (1 == 0 ? 0x80000000 : 0); + + // Data Blocks + if($bFormatFont == 1){ + // Font Name + if($conditional->getStyle()->getFont()->getName() == null){ + $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); + $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); + } else { + $dataBlockFont = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); + } + // Font Size + if($conditional->getStyle()->getFont()->getSize() == null){ + $dataBlockFont .= pack('V', 20 * 11); + } else { + $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); + } + // Font Options + $dataBlockFont .= pack('V', 0); + // Font weight + if($conditional->getStyle()->getFont()->getBold() == true){ + $dataBlockFont .= pack('v', 0x02BC); + } else { + $dataBlockFont .= pack('v', 0x0190); + } + // Escapement type + if($conditional->getStyle()->getFont()->getSubScript() == true){ + $dataBlockFont .= pack('v', 0x02); + $fontEscapement = 0; + } else if($conditional->getStyle()->getFont()->getSuperScript() == true){ + $dataBlockFont .= pack('v', 0x01); + $fontEscapement = 0; + } else { + $dataBlockFont .= pack('v', 0x00); + $fontEscapement = 1; + } + // Underline type + switch ($conditional->getStyle()->getFont()->getUnderline()){ + case PHPExcel_Style_Font::UNDERLINE_NONE : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 0; break; + case PHPExcel_Style_Font::UNDERLINE_DOUBLE : $dataBlockFont .= pack('C', 0x02); $fontUnderline = 0; break; + case PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING : $dataBlockFont .= pack('C', 0x22); $fontUnderline = 0; break; + case PHPExcel_Style_Font::UNDERLINE_SINGLE : $dataBlockFont .= pack('C', 0x01); $fontUnderline = 0; break; + case PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING : $dataBlockFont .= pack('C', 0x21); $fontUnderline = 0; break; + default : $dataBlockFont .= pack('C', 0x00); $fontUnderline = 1; break; + } + // Not used (3) + $dataBlockFont .= pack('vC', 0x0000, 0x00); + // Font color index + switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) { + case '000000': $colorIdx = 0x08; break; + case 'FFFFFF': $colorIdx = 0x09; break; + case 'FF0000': $colorIdx = 0x0A; break; + case '00FF00': $colorIdx = 0x0B; break; + case '0000FF': $colorIdx = 0x0C; break; + case 'FFFF00': $colorIdx = 0x0D; break; + case 'FF00FF': $colorIdx = 0x0E; break; + case '00FFFF': $colorIdx = 0x0F; break; + case '800000': $colorIdx = 0x10; break; + case '008000': $colorIdx = 0x11; break; + case '000080': $colorIdx = 0x12; break; + case '808000': $colorIdx = 0x13; break; + case '800080': $colorIdx = 0x14; break; + case '008080': $colorIdx = 0x15; break; + case 'C0C0C0': $colorIdx = 0x16; break; + case '808080': $colorIdx = 0x17; break; + case '9999FF': $colorIdx = 0x18; break; + case '993366': $colorIdx = 0x19; break; + case 'FFFFCC': $colorIdx = 0x1A; break; + case 'CCFFFF': $colorIdx = 0x1B; break; + case '660066': $colorIdx = 0x1C; break; + case 'FF8080': $colorIdx = 0x1D; break; + case '0066CC': $colorIdx = 0x1E; break; + case 'CCCCFF': $colorIdx = 0x1F; break; + case '000080': $colorIdx = 0x20; break; + case 'FF00FF': $colorIdx = 0x21; break; + case 'FFFF00': $colorIdx = 0x22; break; + case '00FFFF': $colorIdx = 0x23; break; + case '800080': $colorIdx = 0x24; break; + case '800000': $colorIdx = 0x25; break; + case '008080': $colorIdx = 0x26; break; + case '0000FF': $colorIdx = 0x27; break; + case '00CCFF': $colorIdx = 0x28; break; + case 'CCFFFF': $colorIdx = 0x29; break; + case 'CCFFCC': $colorIdx = 0x2A; break; + case 'FFFF99': $colorIdx = 0x2B; break; + case '99CCFF': $colorIdx = 0x2C; break; + case 'FF99CC': $colorIdx = 0x2D; break; + case 'CC99FF': $colorIdx = 0x2E; break; + case 'FFCC99': $colorIdx = 0x2F; break; + case '3366FF': $colorIdx = 0x30; break; + case '33CCCC': $colorIdx = 0x31; break; + case '99CC00': $colorIdx = 0x32; break; + case 'FFCC00': $colorIdx = 0x33; break; + case 'FF9900': $colorIdx = 0x34; break; + case 'FF6600': $colorIdx = 0x35; break; + case '666699': $colorIdx = 0x36; break; + case '969696': $colorIdx = 0x37; break; + case '003366': $colorIdx = 0x38; break; + case '339966': $colorIdx = 0x39; break; + case '003300': $colorIdx = 0x3A; break; + case '333300': $colorIdx = 0x3B; break; + case '993300': $colorIdx = 0x3C; break; + case '993366': $colorIdx = 0x3D; break; + case '333399': $colorIdx = 0x3E; break; + case '333333': $colorIdx = 0x3F; break; + default: $colorIdx = 0x00; break; + } + $dataBlockFont .= pack('V', $colorIdx); + // Not used (4) + $dataBlockFont .= pack('V', 0x00000000); + // Options flags for modified font attributes + $optionsFlags = 0; + $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0); + $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); + $optionsFlags |= (1 == 1 ? 0x00000008 : 0); + $optionsFlags |= (1 == 1 ? 0x00000010 : 0); + $optionsFlags |= (1 == 0 ? 0x00000020 : 0); + $optionsFlags |= (1 == 1 ? 0x00000080 : 0); + $dataBlockFont .= pack('V', $optionsFlags); + // Escapement type + $dataBlockFont .= pack('V', $fontEscapement); + // Underline type + $dataBlockFont .= pack('V', $fontUnderline); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Not used (8) + $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); + // Always + $dataBlockFont .= pack('v', 0x0001); + } + if($bFormatAlign == 1){ + $blockAlign = 0; + // Alignment and text break + switch ($conditional->getStyle()->getAlignment()->getHorizontal()){ + case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL : $blockAlign = 0; break; + case PHPExcel_Style_Alignment::HORIZONTAL_LEFT : $blockAlign = 1; break; + case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT : $blockAlign = 3; break; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER : $blockAlign = 2; break; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS : $blockAlign = 6; break; + case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY : $blockAlign = 5; break; + } + if($conditional->getStyle()->getAlignment()->getWrapText() == true){ + $blockAlign |= 1 << 3; + } else { + $blockAlign |= 0 << 3; + } + switch ($conditional->getStyle()->getAlignment()->getVertical()){ + case PHPExcel_Style_Alignment::VERTICAL_BOTTOM : $blockAlign = 2 << 4; break; + case PHPExcel_Style_Alignment::VERTICAL_TOP : $blockAlign = 0 << 4; break; + case PHPExcel_Style_Alignment::VERTICAL_CENTER : $blockAlign = 1 << 4; break; + case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY : $blockAlign = 3 << 4; break; + } + $blockAlign |= 0 << 7; + + // Text rotation angle + $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); + + // Indentation + $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); + if($conditional->getStyle()->getAlignment()->getShrinkToFit() == true){ + $blockIndent |= 1 << 4; + } else { + $blockIndent |= 0 << 4; + } + $blockIndent |= 0 << 6; + + // Relative indentation + $blockIndentRelative = 255; + + $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); + } + if($bFormatBorder == 1){ + $blockLineStyle = 0; + switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()){ + case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00; break; + case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01; break; + case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02; break; + case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03; break; + case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04; break; + case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05; break; + case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06; break; + case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08; break; + case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A; break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C; break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D; break; + } + switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()){ + case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 4; break; + case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 4; break; + case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 4; break; + case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 4; break; + case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 4; break; + case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 4; break; + case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 4; break; + case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 4; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 4; break; + case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 4; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 4; break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 4; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 4; break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 4; break; + } + switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()){ + case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 8; break; + case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 8; break; + case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 8; break; + case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 8; break; + case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 8; break; + case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 8; break; + case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 8; break; + case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 8; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 8; break; + case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 8; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 8; break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 8; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 8; break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 8; break; + } + switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()){ + case PHPExcel_Style_Border::BORDER_NONE : $blockLineStyle |= 0x00 << 12; break; + case PHPExcel_Style_Border::BORDER_THIN : $blockLineStyle |= 0x01 << 12; break; + case PHPExcel_Style_Border::BORDER_MEDIUM : $blockLineStyle |= 0x02 << 12; break; + case PHPExcel_Style_Border::BORDER_DASHED : $blockLineStyle |= 0x03 << 12; break; + case PHPExcel_Style_Border::BORDER_DOTTED : $blockLineStyle |= 0x04 << 12; break; + case PHPExcel_Style_Border::BORDER_THICK : $blockLineStyle |= 0x05 << 12; break; + case PHPExcel_Style_Border::BORDER_DOUBLE : $blockLineStyle |= 0x06 << 12; break; + case PHPExcel_Style_Border::BORDER_HAIR : $blockLineStyle |= 0x07 << 12; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockLineStyle |= 0x08 << 12; break; + case PHPExcel_Style_Border::BORDER_DASHDOT : $blockLineStyle |= 0x09 << 12; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockLineStyle |= 0x0A << 12; break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockLineStyle |= 0x0B << 12; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockLineStyle |= 0x0C << 12; break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockLineStyle |= 0x0D << 12; break; + } + //@todo _writeCFRule() => $blockLineStyle => Index Color for left line + //@todo _writeCFRule() => $blockLineStyle => Index Color for right line + //@todo _writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off + //@todo _writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off + $blockColor = 0; + //@todo _writeCFRule() => $blockColor => Index Color for top line + //@todo _writeCFRule() => $blockColor => Index Color for bottom line + //@todo _writeCFRule() => $blockColor => Index Color for diagonal line + switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()){ + case PHPExcel_Style_Border::BORDER_NONE : $blockColor |= 0x00 << 21; break; + case PHPExcel_Style_Border::BORDER_THIN : $blockColor |= 0x01 << 21; break; + case PHPExcel_Style_Border::BORDER_MEDIUM : $blockColor |= 0x02 << 21; break; + case PHPExcel_Style_Border::BORDER_DASHED : $blockColor |= 0x03 << 21; break; + case PHPExcel_Style_Border::BORDER_DOTTED : $blockColor |= 0x04 << 21; break; + case PHPExcel_Style_Border::BORDER_THICK : $blockColor |= 0x05 << 21; break; + case PHPExcel_Style_Border::BORDER_DOUBLE : $blockColor |= 0x06 << 21; break; + case PHPExcel_Style_Border::BORDER_HAIR : $blockColor |= 0x07 << 21; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED : $blockColor |= 0x08 << 21; break; + case PHPExcel_Style_Border::BORDER_DASHDOT : $blockColor |= 0x09 << 21; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT : $blockColor |= 0x0A << 21; break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT : $blockColor |= 0x0B << 21; break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT : $blockColor |= 0x0C << 21; break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT : $blockColor |= 0x0D << 21; break; + } + $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); + } + if($bFormatFill == 1){ + // Fill Patern Style + $blockFillPatternStyle = 0; + switch ($conditional->getStyle()->getFill()->getFillType()){ + case PHPExcel_Style_Fill::FILL_NONE : $blockFillPatternStyle = 0x00; break; + case PHPExcel_Style_Fill::FILL_SOLID : $blockFillPatternStyle = 0x01; break; + case PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY : $blockFillPatternStyle = 0x02; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY : $blockFillPatternStyle = 0x03; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY : $blockFillPatternStyle = 0x04; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL : $blockFillPatternStyle = 0x05; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL : $blockFillPatternStyle = 0x06; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN : $blockFillPatternStyle = 0x07; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKUP : $blockFillPatternStyle = 0x08; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID : $blockFillPatternStyle = 0x09; break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS : $blockFillPatternStyle = 0x0A; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL : $blockFillPatternStyle = 0x0B; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL : $blockFillPatternStyle = 0x0C; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN : $blockFillPatternStyle = 0x0D; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP : $blockFillPatternStyle = 0x0E; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID : $blockFillPatternStyle = 0x0F; break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS : $blockFillPatternStyle = 0x10; break; + case PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 : $blockFillPatternStyle = 0x11; break; + case PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 : $blockFillPatternStyle = 0x12; break; + case PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8 + case PHPExcel_Style_Fill::FILL_GRADIENT_PATH : $blockFillPatternStyle = 0x00; break; // does not exist in BIFF8 + default : $blockFillPatternStyle = 0x00; break; + } + // Color + switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) { + case '000000': $colorIdxBg = 0x08; break; + case 'FFFFFF': $colorIdxBg = 0x09; break; + case 'FF0000': $colorIdxBg = 0x0A; break; + case '00FF00': $colorIdxBg = 0x0B; break; + case '0000FF': $colorIdxBg = 0x0C; break; + case 'FFFF00': $colorIdxBg = 0x0D; break; + case 'FF00FF': $colorIdxBg = 0x0E; break; + case '00FFFF': $colorIdxBg = 0x0F; break; + case '800000': $colorIdxBg = 0x10; break; + case '008000': $colorIdxBg = 0x11; break; + case '000080': $colorIdxBg = 0x12; break; + case '808000': $colorIdxBg = 0x13; break; + case '800080': $colorIdxBg = 0x14; break; + case '008080': $colorIdxBg = 0x15; break; + case 'C0C0C0': $colorIdxBg = 0x16; break; + case '808080': $colorIdxBg = 0x17; break; + case '9999FF': $colorIdxBg = 0x18; break; + case '993366': $colorIdxBg = 0x19; break; + case 'FFFFCC': $colorIdxBg = 0x1A; break; + case 'CCFFFF': $colorIdxBg = 0x1B; break; + case '660066': $colorIdxBg = 0x1C; break; + case 'FF8080': $colorIdxBg = 0x1D; break; + case '0066CC': $colorIdxBg = 0x1E; break; + case 'CCCCFF': $colorIdxBg = 0x1F; break; + case '000080': $colorIdxBg = 0x20; break; + case 'FF00FF': $colorIdxBg = 0x21; break; + case 'FFFF00': $colorIdxBg = 0x22; break; + case '00FFFF': $colorIdxBg = 0x23; break; + case '800080': $colorIdxBg = 0x24; break; + case '800000': $colorIdxBg = 0x25; break; + case '008080': $colorIdxBg = 0x26; break; + case '0000FF': $colorIdxBg = 0x27; break; + case '00CCFF': $colorIdxBg = 0x28; break; + case 'CCFFFF': $colorIdxBg = 0x29; break; + case 'CCFFCC': $colorIdxBg = 0x2A; break; + case 'FFFF99': $colorIdxBg = 0x2B; break; + case '99CCFF': $colorIdxBg = 0x2C; break; + case 'FF99CC': $colorIdxBg = 0x2D; break; + case 'CC99FF': $colorIdxBg = 0x2E; break; + case 'FFCC99': $colorIdxBg = 0x2F; break; + case '3366FF': $colorIdxBg = 0x30; break; + case '33CCCC': $colorIdxBg = 0x31; break; + case '99CC00': $colorIdxBg = 0x32; break; + case 'FFCC00': $colorIdxBg = 0x33; break; + case 'FF9900': $colorIdxBg = 0x34; break; + case 'FF6600': $colorIdxBg = 0x35; break; + case '666699': $colorIdxBg = 0x36; break; + case '969696': $colorIdxBg = 0x37; break; + case '003366': $colorIdxBg = 0x38; break; + case '339966': $colorIdxBg = 0x39; break; + case '003300': $colorIdxBg = 0x3A; break; + case '333300': $colorIdxBg = 0x3B; break; + case '993300': $colorIdxBg = 0x3C; break; + case '993366': $colorIdxBg = 0x3D; break; + case '333399': $colorIdxBg = 0x3E; break; + case '333333': $colorIdxBg = 0x3F; break; + default: $colorIdxBg = 0x41; break; + } + // Fg Color + switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) { + case '000000': $colorIdxFg = 0x08; break; + case 'FFFFFF': $colorIdxFg = 0x09; break; + case 'FF0000': $colorIdxFg = 0x0A; break; + case '00FF00': $colorIdxFg = 0x0B; break; + case '0000FF': $colorIdxFg = 0x0C; break; + case 'FFFF00': $colorIdxFg = 0x0D; break; + case 'FF00FF': $colorIdxFg = 0x0E; break; + case '00FFFF': $colorIdxFg = 0x0F; break; + case '800000': $colorIdxFg = 0x10; break; + case '008000': $colorIdxFg = 0x11; break; + case '000080': $colorIdxFg = 0x12; break; + case '808000': $colorIdxFg = 0x13; break; + case '800080': $colorIdxFg = 0x14; break; + case '008080': $colorIdxFg = 0x15; break; + case 'C0C0C0': $colorIdxFg = 0x16; break; + case '808080': $colorIdxFg = 0x17; break; + case '9999FF': $colorIdxFg = 0x18; break; + case '993366': $colorIdxFg = 0x19; break; + case 'FFFFCC': $colorIdxFg = 0x1A; break; + case 'CCFFFF': $colorIdxFg = 0x1B; break; + case '660066': $colorIdxFg = 0x1C; break; + case 'FF8080': $colorIdxFg = 0x1D; break; + case '0066CC': $colorIdxFg = 0x1E; break; + case 'CCCCFF': $colorIdxFg = 0x1F; break; + case '000080': $colorIdxFg = 0x20; break; + case 'FF00FF': $colorIdxFg = 0x21; break; + case 'FFFF00': $colorIdxFg = 0x22; break; + case '00FFFF': $colorIdxFg = 0x23; break; + case '800080': $colorIdxFg = 0x24; break; + case '800000': $colorIdxFg = 0x25; break; + case '008080': $colorIdxFg = 0x26; break; + case '0000FF': $colorIdxFg = 0x27; break; + case '00CCFF': $colorIdxFg = 0x28; break; + case 'CCFFFF': $colorIdxFg = 0x29; break; + case 'CCFFCC': $colorIdxFg = 0x2A; break; + case 'FFFF99': $colorIdxFg = 0x2B; break; + case '99CCFF': $colorIdxFg = 0x2C; break; + case 'FF99CC': $colorIdxFg = 0x2D; break; + case 'CC99FF': $colorIdxFg = 0x2E; break; + case 'FFCC99': $colorIdxFg = 0x2F; break; + case '3366FF': $colorIdxFg = 0x30; break; + case '33CCCC': $colorIdxFg = 0x31; break; + case '99CC00': $colorIdxFg = 0x32; break; + case 'FFCC00': $colorIdxFg = 0x33; break; + case 'FF9900': $colorIdxFg = 0x34; break; + case 'FF6600': $colorIdxFg = 0x35; break; + case '666699': $colorIdxFg = 0x36; break; + case '969696': $colorIdxFg = 0x37; break; + case '003366': $colorIdxFg = 0x38; break; + case '339966': $colorIdxFg = 0x39; break; + case '003300': $colorIdxFg = 0x3A; break; + case '333300': $colorIdxFg = 0x3B; break; + case '993300': $colorIdxFg = 0x3C; break; + case '993366': $colorIdxFg = 0x3D; break; + case '333399': $colorIdxFg = 0x3E; break; + case '333333': $colorIdxFg = 0x3F; break; + default: $colorIdxFg = 0x40; break; + } + $dataBlockFill = pack('v', $blockFillPatternStyle); + $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); + } + if($bFormatProt == 1){ + $dataBlockProtection = 0; + if($conditional->getStyle()->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED){ + $dataBlockProtection = 1; + } + if($conditional->getStyle()->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED){ + $dataBlockProtection = 1 << 1; + } + } + + $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); + if($bFormatFont == 1){ // Block Formatting : OK + $data .= $dataBlockFont; + } + if($bFormatAlign == 1){ + $data .= $dataBlockAlign; + } + if($bFormatBorder == 1){ + $data .= $dataBlockBorder; + } + if($bFormatFill == 1){ // Block Formatting : OK + $data .= $dataBlockFill; + } + if($bFormatProt == 1){ + $data .= $dataBlockProtection; + } + if(!is_null($operand1)){ + $data .= $operand1; + } + if(!is_null($operand2)){ + $data .= $operand2; + } + $header = pack('vv', $record, strlen($data)); + $this->_append($header . $data); + } + + /** + * Write CFHeader record + */ + private function _writeCFHeader(){ + $record = 0x01B0; // Record identifier + $length = 0x0016; // Bytes to follow + + $numColumnMin = null; + $numColumnMax = null; + $numRowMin = null; + $numRowMax = null; + $arrConditional = array(); + foreach ($this->_phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + if($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS){ + if(!in_array($conditional->getHashCode(), $arrConditional)){ + $arrConditional[] = $conditional->getHashCode(); + } + // Cells + $arrCoord = PHPExcel_Cell::coordinateFromString($cellCoordinate); + if(!is_numeric($arrCoord[0])){ + $arrCoord[0] = PHPExcel_Cell::columnIndexFromString($arrCoord[0]); + } + if(is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])){ + $numColumnMin = $arrCoord[0]; + } + if(is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])){ + $numColumnMax = $arrCoord[0]; + } + if(is_null($numRowMin) || ($numRowMin > $arrCoord[1])){ + $numRowMin = $arrCoord[1]; + } + if(is_null($numRowMax) || ($numRowMax < $arrCoord[1])){ + $numRowMax = $arrCoord[1]; + } + } + } + } + $needRedraw = 1; + $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1); + + $header = pack('vv', $record, $length); + $data = pack('vv', count($arrConditional), $needRedraw); + $data .= $cellRange; + $data .= pack('v', 0x0001); + $data .= $cellRange; + $this->_append($header . $data); + } +} \ No newline at end of file diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php new file mode 100644 index 00000000..f803f683 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php @@ -0,0 +1,547 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ + + +/** + * PHPExcel_Writer_Excel5_Xf + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Xf +{ + /** + * Style XF or a cell XF ? + * + * @var boolean + */ + private $_isStyleXf; + + /** + * Index to the FONT record. Index 4 does not exist + * @var integer + */ + private $_fontIndex; + + /** + * An index (2 bytes) to a FORMAT record (number format). + * @var integer + */ + public $_numberFormatIndex; + + /** + * 1 bit, apparently not used. + * @var integer + */ + public $_text_justlast; + + /** + * The cell's foreground color. + * @var integer + */ + public $_fg_color; + + /** + * The cell's background color. + * @var integer + */ + public $_bg_color; + + /** + * Color of the bottom border of the cell. + * @var integer + */ + public $_bottom_color; + + /** + * Color of the top border of the cell. + * @var integer + */ + public $_top_color; + + /** + * Color of the left border of the cell. + * @var integer + */ + public $_left_color; + + /** + * Color of the right border of the cell. + * @var integer + */ + public $_right_color; + + /** + * Constructor + * + * @access public + * @param PHPExcel_Style The XF format + */ + public function __construct(PHPExcel_Style $style = null) + { + $this->_isStyleXf = false; + $this->_fontIndex = 0; + + $this->_numberFormatIndex = 0; + + $this->_text_justlast = 0; + + $this->_fg_color = 0x40; + $this->_bg_color = 0x41; + + $this->_diag = 0; + + $this->_bottom_color = 0x40; + $this->_top_color = 0x40; + $this->_left_color = 0x40; + $this->_right_color = 0x40; + $this->_diag_color = 0x40; + $this->_style = $style; + + } + + + /** + * Generate an Excel BIFF XF record (style or cell). + * + * @return string The XF record + */ + function writeXf() + { + // Set the type of the XF record and some of the attributes. + if ($this->_isStyleXf) { + $style = 0xFFF5; + } else { + $style = self::_mapLocked($this->_style->getProtection()->getLocked()); + $style |= self::_mapHidden($this->_style->getProtection()->getHidden()) << 1; + } + + // Flags to indicate if attributes have been set. + $atr_num = ($this->_numberFormatIndex != 0)?1:0; + $atr_fnt = ($this->_fontIndex != 0)?1:0; + $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; + $atr_bdr = (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || + self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || + self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || + self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0; + $atr_pat = (($this->_fg_color != 0x40) || + ($this->_bg_color != 0x41) || + self::_mapFillType($this->_style->getFill()->getFillType()))?1:0; + $atr_prot = self::_mapLocked($this->_style->getProtection()->getLocked()) + | self::_mapHidden($this->_style->getProtection()->getHidden()); + + // Zero the default border colour if the border has not been set. + if (self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) { + $this->_bottom_color = 0; + } + if (self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { + $this->_top_color = 0; + } + if (self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) { + $this->_right_color = 0; + } + if (self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) { + $this->_left_color = 0; + } + if (self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) { + $this->_diag_color = 0; + } + + $record = 0x00E0; // Record identifier + $length = 0x0014; // Number of bytes to follow + + $ifnt = $this->_fontIndex; // Index to FONT record + $ifmt = $this->_numberFormatIndex; // Index to FORMAT record + + $align = $this->_mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment + $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; + $align |= self::_mapVAlign($this->_style->getAlignment()->getVertical()) << 4; + $align |= $this->_text_justlast << 7; + + $used_attrib = $atr_num << 2; + $used_attrib |= $atr_fnt << 3; + $used_attrib |= $atr_alc << 4; + $used_attrib |= $atr_bdr << 5; + $used_attrib |= $atr_pat << 6; + $used_attrib |= $atr_prot << 7; + + $icv = $this->_fg_color; // fg and bg pattern colors + $icv |= $this->_bg_color << 7; + + $border1 = self::_mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color + $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; + $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; + $border1 |= self::_mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; + $border1 |= $this->_left_color << 16; + $border1 |= $this->_right_color << 23; + + $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection(); + $diag_tl_to_rb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH + || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_DOWN; + $diag_tr_to_lb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH + || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_UP; + $border1 |= $diag_tl_to_rb << 30; + $border1 |= $diag_tr_to_lb << 31; + + $border2 = $this->_top_color; // Border color + $border2 |= $this->_bottom_color << 7; + $border2 |= $this->_diag_color << 14; + $border2 |= self::_mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; + $border2 |= self::_mapFillType($this->_style->getFill()->getFillType()) << 26; + + $header = pack("vv", $record, $length); + + //BIFF8 options: identation, shrinkToFit and text direction + $biff8_options = $this->_style->getAlignment()->getIndent(); + $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4; + + $data = pack("vvvC", $ifnt, $ifmt, $style, $align); + $data .= pack("CCC" + , self::_mapTextRotation($this->_style->getAlignment()->getTextRotation()) + , $biff8_options + , $used_attrib + ); + $data .= pack("VVv", $border1, $border2, $icv); + + return($header . $data); + } + + /** + * Is this a style XF ? + * + * @param boolean $value + */ + public function setIsStyleXf($value) + { + $this->_isStyleXf = $value; + } + + /** + * Sets the cell's bottom border color + * + * @access public + * @param int $colorIndex Color index + */ + function setBottomColor($colorIndex) + { + $this->_bottom_color = $colorIndex; + } + + /** + * Sets the cell's top border color + * + * @access public + * @param int $colorIndex Color index + */ + function setTopColor($colorIndex) + { + $this->_top_color = $colorIndex; + } + + /** + * Sets the cell's left border color + * + * @access public + * @param int $colorIndex Color index + */ + function setLeftColor($colorIndex) + { + $this->_left_color = $colorIndex; + } + + /** + * Sets the cell's right border color + * + * @access public + * @param int $colorIndex Color index + */ + function setRightColor($colorIndex) + { + $this->_right_color = $colorIndex; + } + + /** + * Sets the cell's diagonal border color + * + * @access public + * @param int $colorIndex Color index + */ + function setDiagColor($colorIndex) + { + $this->_diag_color = $colorIndex; + } + + + /** + * Sets the cell's foreground color + * + * @access public + * @param int $colorIndex Color index + */ + function setFgColor($colorIndex) + { + $this->_fg_color = $colorIndex; + } + + /** + * Sets the cell's background color + * + * @access public + * @param int $colorIndex Color index + */ + function setBgColor($colorIndex) + { + $this->_bg_color = $colorIndex; + } + + /** + * Sets the index to the number format record + * It can be date, time, currency, etc... + * + * @access public + * @param integer $numberFormatIndex Index to format record + */ + function setNumberFormatIndex($numberFormatIndex) + { + $this->_numberFormatIndex = $numberFormatIndex; + } + + /** + * Set the font index. + * + * @param int $value Font index, note that value 4 does not exist + */ + public function setFontIndex($value) + { + $this->_fontIndex = $value; + } + + /** + * Map of BIFF2-BIFF8 codes for border styles + * @static array of int + * + */ + private static $_mapBorderStyle = array ( PHPExcel_Style_Border::BORDER_NONE => 0x00, + PHPExcel_Style_Border::BORDER_THIN => 0x01, + PHPExcel_Style_Border::BORDER_MEDIUM => 0x02, + PHPExcel_Style_Border::BORDER_DASHED => 0x03, + PHPExcel_Style_Border::BORDER_DOTTED => 0x04, + PHPExcel_Style_Border::BORDER_THICK => 0x05, + PHPExcel_Style_Border::BORDER_DOUBLE => 0x06, + PHPExcel_Style_Border::BORDER_HAIR => 0x07, + PHPExcel_Style_Border::BORDER_MEDIUMDASHED => 0x08, + PHPExcel_Style_Border::BORDER_DASHDOT => 0x09, + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT => 0x0A, + PHPExcel_Style_Border::BORDER_DASHDOTDOT => 0x0B, + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, + PHPExcel_Style_Border::BORDER_SLANTDASHDOT => 0x0D, + ); + + /** + * Map border style + * + * @param string $borderStyle + * @return int + */ + private static function _mapBorderStyle($borderStyle) { + if (isset(self::$_mapBorderStyle[$borderStyle])) + return self::$_mapBorderStyle[$borderStyle]; + return 0x00; + } + + /** + * Map of BIFF2-BIFF8 codes for fill types + * @static array of int + * + */ + private static $_mapFillType = array( PHPExcel_Style_Fill::FILL_NONE => 0x00, + PHPExcel_Style_Fill::FILL_SOLID => 0x01, + PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, + PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY => 0x03, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04, + PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, + PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06, + PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN => 0x07, + PHPExcel_Style_Fill::FILL_PATTERN_DARKUP => 0x08, + PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID => 0x09, + PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, + PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 => 0x11, + PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 => 0x12, + PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 + PHPExcel_Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 + ); + /** + * Map fill type + * + * @param string $fillType + * @return int + */ + private static function _mapFillType($fillType) { + if (isset(self::$_mapFillType[$fillType])) + return self::$_mapFillType[$fillType]; + return 0x00; + } + + /** + * Map of BIFF2-BIFF8 codes for horizontal alignment + * @static array of int + * + */ + private static $_mapHAlign = array( PHPExcel_Style_Alignment::HORIZONTAL_GENERAL => 0, + PHPExcel_Style_Alignment::HORIZONTAL_LEFT => 1, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER => 2, + PHPExcel_Style_Alignment::HORIZONTAL_RIGHT => 3, + PHPExcel_Style_Alignment::HORIZONTAL_FILL => 4, + PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY => 5, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, + ); + /** + * Map to BIFF2-BIFF8 codes for horizontal alignment + * + * @param string $hAlign + * @return int + */ + private function _mapHAlign($hAlign) + { + if (isset(self::$_mapHAlign[$hAlign])) + return self::$_mapHAlign[$hAlign]; + return 0; + } + + /** + * Map of BIFF2-BIFF8 codes for vertical alignment + * @static array of int + * + */ + private static $_mapVAlign = array( PHPExcel_Style_Alignment::VERTICAL_TOP => 0, + PHPExcel_Style_Alignment::VERTICAL_CENTER => 1, + PHPExcel_Style_Alignment::VERTICAL_BOTTOM => 2, + PHPExcel_Style_Alignment::VERTICAL_JUSTIFY => 3, + ); + /** + * Map to BIFF2-BIFF8 codes for vertical alignment + * + * @param string $vAlign + * @return int + */ + private static function _mapVAlign($vAlign) { + if (isset(self::$_mapVAlign[$vAlign])) + return self::$_mapVAlign[$vAlign]; + return 2; + } + + /** + * Map to BIFF8 codes for text rotation angle + * + * @param int $textRotation + * @return int + */ + private static function _mapTextRotation($textRotation) { + if ($textRotation >= 0) { + return $textRotation; + } + if ($textRotation == -165) { + return 255; + } + if ($textRotation < 0) { + return 90 - $textRotation; + } + } + + /** + * Map locked + * + * @param string + * @return int + */ + private static function _mapLocked($locked) { + switch ($locked) { + case PHPExcel_Style_Protection::PROTECTION_INHERIT: return 1; + case PHPExcel_Style_Protection::PROTECTION_PROTECTED: return 1; + case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: return 0; + default: return 1; + } + } + + /** + * Map hidden + * + * @param string + * @return int + */ + private static function _mapHidden($hidden) { + switch ($hidden) { + case PHPExcel_Style_Protection::PROTECTION_INHERIT: return 0; + case PHPExcel_Style_Protection::PROTECTION_PROTECTED: return 1; + case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: return 0; + default: return 0; + } + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php new file mode 100644 index 00000000..e8fe9be7 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php @@ -0,0 +1,52 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_Exception + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Exception extends PHPExcel_Exception { + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php new file mode 100644 index 00000000..0f2cc089 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php @@ -0,0 +1,1532 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_HTML + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_HTML + * + * @category PHPExcel + * @package PHPExcel_Writer_HTML + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_HTML extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter { + /** + * PHPExcel object + * + * @var PHPExcel + */ + protected $_phpExcel; + + /** + * Sheet index to write + * + * @var int + */ + private $_sheetIndex = 0; + + /** + * Images root + * + * @var string + */ + private $_imagesRoot = '.'; + + /** + * embed images, or link to images + * + * @var boolean + */ + private $_embedImages = FALSE; + + /** + * Use inline CSS? + * + * @var boolean + */ + private $_useInlineCss = false; + + /** + * Array of CSS styles + * + * @var array + */ + private $_cssStyles = null; + + /** + * Array of column widths in points + * + * @var array + */ + private $_columnWidths = null; + + /** + * Default font + * + * @var PHPExcel_Style_Font + */ + private $_defaultFont; + + /** + * Flag whether spans have been calculated + * + * @var boolean + */ + private $_spansAreCalculated = false; + + /** + * Excel cells that should not be written as HTML cells + * + * @var array + */ + private $_isSpannedCell = array(); + + /** + * Excel cells that are upper-left corner in a cell merge + * + * @var array + */ + private $_isBaseCell = array(); + + /** + * Excel rows that should not be written as HTML rows + * + * @var array + */ + private $_isSpannedRow = array(); + + /** + * Is the current writer creating PDF? + * + * @var boolean + */ + protected $_isPdf = false; + + /** + * Generate the Navigation block + * + * @var boolean + */ + private $_generateSheetNavigationBlock = true; + + /** + * Create a new PHPExcel_Writer_HTML + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) { + $this->_phpExcel = $phpExcel; + $this->_defaultFont = $this->_phpExcel->getDefaultStyle()->getFont(); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) { + // garbage collect + $this->_phpExcel->garbageCollect(); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog(FALSE); + $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Build CSS + $this->buildCSS(!$this->_useInlineCss); + + // Open file + $fileHandle = fopen($pFilename, 'wb+'); + if ($fileHandle === false) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + // Write headers + fwrite($fileHandle, $this->generateHTMLHeader(!$this->_useInlineCss)); + + // Write navigation (tabs) + if ((!$this->_isPdf) && ($this->_generateSheetNavigationBlock)) { + fwrite($fileHandle, $this->generateNavigation()); + } + + // Write data + fwrite($fileHandle, $this->generateSheetData()); + + // Write footer + fwrite($fileHandle, $this->generateHTMLFooter()); + + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType); + PHPExcel_Calculation::getInstance($this->_phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Map VAlign + * + * @param string $vAlign Vertical alignment + * @return string + */ + private function _mapVAlign($vAlign) { + switch ($vAlign) { + case PHPExcel_Style_Alignment::VERTICAL_BOTTOM: return 'bottom'; + case PHPExcel_Style_Alignment::VERTICAL_TOP: return 'top'; + case PHPExcel_Style_Alignment::VERTICAL_CENTER: + case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY: return 'middle'; + default: return 'baseline'; + } + } + + /** + * Map HAlign + * + * @param string $hAlign Horizontal alignment + * @return string|false + */ + private function _mapHAlign($hAlign) { + switch ($hAlign) { + case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL: return false; + case PHPExcel_Style_Alignment::HORIZONTAL_LEFT: return 'left'; + case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT: return 'right'; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER: + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: return 'center'; + case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY: return 'justify'; + default: return false; + } + } + + /** + * Map border style + * + * @param int $borderStyle Sheet index + * @return string + */ + private function _mapBorderStyle($borderStyle) { + switch ($borderStyle) { + case PHPExcel_Style_Border::BORDER_NONE: return 'none'; + case PHPExcel_Style_Border::BORDER_DASHDOT: return '1px dashed'; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: return '1px dotted'; + case PHPExcel_Style_Border::BORDER_DASHED: return '1px dashed'; + case PHPExcel_Style_Border::BORDER_DOTTED: return '1px dotted'; + case PHPExcel_Style_Border::BORDER_DOUBLE: return '3px double'; + case PHPExcel_Style_Border::BORDER_HAIR: return '1px solid'; + case PHPExcel_Style_Border::BORDER_MEDIUM: return '2px solid'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: return '2px dashed'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: return '2px dotted'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: return '2px dashed'; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: return '2px dashed'; + case PHPExcel_Style_Border::BORDER_THICK: return '3px solid'; + case PHPExcel_Style_Border::BORDER_THIN: return '1px solid'; + default: return '1px solid'; // map others to thin + } + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() { + return $this->_sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Writer_HTML + */ + public function setSheetIndex($pValue = 0) { + $this->_sheetIndex = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return boolean + */ + public function getGenerateSheetNavigationBlock() { + return $this->_generateSheetNavigationBlock; + } + + /** + * Set sheet index + * + * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not + * @return PHPExcel_Writer_HTML + */ + public function setGenerateSheetNavigationBlock($pValue = true) { + $this->_generateSheetNavigationBlock = (bool) $pValue; + return $this; + } + + /** + * Write all sheets (resets sheetIndex to NULL) + */ + public function writeAllSheets() { + $this->_sheetIndex = null; + return $this; + } + + /** + * Generate HTML header + * + * @param boolean $pIncludeStyles Include styles? + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateHTMLHeader($pIncludeStyles = false) { + // PHPExcel object known? + if (is_null($this->_phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Construct HTML + $properties = $this->_phpExcel->getProperties(); + $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . PHP_EOL; + $html .= '<!-- Generated by PHPExcel - http://www.phpexcel.net -->' . PHP_EOL; + $html .= '<html>' . PHP_EOL; + $html .= ' <head>' . PHP_EOL; + $html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . PHP_EOL; + if ($properties->getTitle() > '') + $html .= ' <title>' . htmlspecialchars($properties->getTitle()) . '</title>' . PHP_EOL; + + if ($properties->getCreator() > '') + $html .= ' <meta name="author" content="' . htmlspecialchars($properties->getCreator()) . '" />' . PHP_EOL; + if ($properties->getTitle() > '') + $html .= ' <meta name="title" content="' . htmlspecialchars($properties->getTitle()) . '" />' . PHP_EOL; + if ($properties->getDescription() > '') + $html .= ' <meta name="description" content="' . htmlspecialchars($properties->getDescription()) . '" />' . PHP_EOL; + if ($properties->getSubject() > '') + $html .= ' <meta name="subject" content="' . htmlspecialchars($properties->getSubject()) . '" />' . PHP_EOL; + if ($properties->getKeywords() > '') + $html .= ' <meta name="keywords" content="' . htmlspecialchars($properties->getKeywords()) . '" />' . PHP_EOL; + if ($properties->getCategory() > '') + $html .= ' <meta name="category" content="' . htmlspecialchars($properties->getCategory()) . '" />' . PHP_EOL; + if ($properties->getCompany() > '') + $html .= ' <meta name="company" content="' . htmlspecialchars($properties->getCompany()) . '" />' . PHP_EOL; + if ($properties->getManager() > '') + $html .= ' <meta name="manager" content="' . htmlspecialchars($properties->getManager()) . '" />' . PHP_EOL; + + if ($pIncludeStyles) { + $html .= $this->generateStyles(true); + } + + $html .= ' </head>' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= ' <body>' . PHP_EOL; + + // Return + return $html; + } + + /** + * Generate sheet data + * + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateSheetData() { + // PHPExcel object known? + if (is_null($this->_phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Ensure that Spans have been calculated? + if (!$this->_spansAreCalculated) { + $this->_calculateSpans(); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->_sheetIndex)) { + $sheets = $this->_phpExcel->getAllSheets(); + } else { + $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex); + } + + // Construct HTML + $html = ''; + + // Loop all sheets + $sheetId = 0; + foreach ($sheets as $sheet) { + // Write table header + $html .= $this->_generateTableHeader($sheet); + + // Get worksheet dimension + $dimension = explode(':', $sheet->calculateWorksheetDimension()); + $dimension[0] = PHPExcel_Cell::coordinateFromString($dimension[0]); + $dimension[0][0] = PHPExcel_Cell::columnIndexFromString($dimension[0][0]) - 1; + $dimension[1] = PHPExcel_Cell::coordinateFromString($dimension[1]); + $dimension[1][0] = PHPExcel_Cell::columnIndexFromString($dimension[1][0]) - 1; + + // row min,max + $rowMin = $dimension[0][1]; + $rowMax = $dimension[1][1]; + + // calculate start of <tbody>, <thead> + $tbodyStart = $rowMin; + $theadStart = $theadEnd = 0; // default: no <thead> no </thead> + if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); + + // we can only support repeating rows that start at top row + if ($rowsToRepeatAtTop[0] == 1) { + $theadStart = $rowsToRepeatAtTop[0]; + $theadEnd = $rowsToRepeatAtTop[1]; + $tbodyStart = $rowsToRepeatAtTop[1] + 1; + } + } + + // Loop through cells + $row = $rowMin-1; + while($row++ < $rowMax) { + // <thead> ? + if ($row == $theadStart) { + $html .= ' <thead>' . PHP_EOL; + } + + // <tbody> ? + if ($row == $tbodyStart) { + $html .= ' <tbody>' . PHP_EOL; + } + + // Write row if there are HTML table cells in it + if ( !isset($this->_isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row]) ) { + // Start a new rowData + $rowData = array(); + // Loop through columns + $column = $dimension[0][0] - 1; + while($column++ < $dimension[1][0]) { + // Cell exists? + if ($sheet->cellExistsByColumnAndRow($column, $row)) { + $rowData[$column] = PHPExcel_Cell::stringFromColumnIndex($column) . $row; + } else { + $rowData[$column] = ''; + } + } + $html .= $this->_generateRow($sheet, $rowData, $row - 1); + } + + // </thead> ? + if ($row == $theadEnd) { + $html .= ' </thead>' . PHP_EOL; + } + } + $html .= $this->_extendRowsForChartsAndImages($sheet, $row); + + // Close table body. + $html .= ' </tbody>' . PHP_EOL; + + // Write table footer + $html .= $this->_generateTableFooter(); + + // Writing PDF? + if ($this->_isPdf) { + if (is_null($this->_sheetIndex) && $sheetId + 1 < $this->_phpExcel->getSheetCount()) { + $html .= '<div style="page-break-before:always" />'; + } + } + + // Next sheet + ++$sheetId; + } + + // Return + return $html; + } + + /** + * Generate sheet tabs + * + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateNavigation() + { + // PHPExcel object known? + if (is_null($this->_phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->_sheetIndex)) { + $sheets = $this->_phpExcel->getAllSheets(); + } else { + $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex); + } + + // Construct HTML + $html = ''; + + // Only if there are more than 1 sheets + if (count($sheets) > 1) { + // Loop all sheets + $sheetId = 0; + + $html .= '<ul class="navigation">' . PHP_EOL; + + foreach ($sheets as $sheet) { + $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL; + ++$sheetId; + } + + $html .= '</ul>' . PHP_EOL; + } + + return $html; + } + + private function _extendRowsForChartsAndImages(PHPExcel_Worksheet $pSheet, $row) { + $rowMax = $row; + $colMax = 'A'; + if ($this->_includeCharts) { + foreach ($pSheet->getChartCollection() as $chart) { + if ($chart instanceof PHPExcel_Chart) { + $chartCoordinates = $chart->getTopLeftPosition(); + $chartTL = PHPExcel_Cell::coordinateFromString($chartCoordinates['cell']); + $chartCol = PHPExcel_Cell::columnIndexFromString($chartTL[0]); + if ($chartTL[1] > $rowMax) { + $rowMax = $chartTL[1]; + if ($chartCol > PHPExcel_Cell::columnIndexFromString($colMax)) { + $colMax = $chartTL[0]; + } + } + } + } + } + + foreach ($pSheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + $imageTL = PHPExcel_Cell::coordinateFromString($drawing->getCoordinates()); + $imageCol = PHPExcel_Cell::columnIndexFromString($imageTL[0]); + if ($imageTL[1] > $rowMax) { + $rowMax = $imageTL[1]; + if ($imageCol > PHPExcel_Cell::columnIndexFromString($colMax)) { + $colMax = $imageTL[0]; + } + } + } + } + $html = ''; + $colMax++; + while ($row < $rowMax) { + $html .= '<tr>'; + for ($col = 'A'; $col != $colMax; ++$col) { + $html .= '<td>'; + $html .= $this->_writeImageInCell($pSheet, $col.$row); + if ($this->_includeCharts) { + $html .= $this->_writeChartInCell($pSheet, $col.$row); + } + $html .= '</td>'; + } + ++$row; + $html .= '</tr>'; + } + return $html; + } + + + /** + * Generate image tag in cell + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param string $coordinates Cell coordinates + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function _writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) { + // Construct HTML + $html = ''; + + // Write images + foreach ($pSheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + if ($drawing->getCoordinates() == $coordinates) { + $filename = $drawing->getPath(); + + // Strip off eventual '.' + if (substr($filename, 0, 1) == '.') { + $filename = substr($filename, 1); + } + + // Prepend images root + $filename = $this->getImagesRoot() . $filename; + + // Strip off eventual '.' + if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') { + $filename = substr($filename, 1); + } + + // Convert UTF8 data to PCDATA + $filename = htmlspecialchars($filename); + + $html .= PHP_EOL; + if ((!$this->_embedImages) || ($this->_isPdf)) { + $imageData = $filename; + } else { + $imageDetails = getimagesize($filename); + if ($fp = fopen($filename,"rb", 0)) { + $picture = fread($fp,filesize($filename)); + fclose($fp); + // base64 encode the binary data, then break it + // into chunks according to RFC 2045 semantics + $base64 = chunk_split(base64_encode($picture)); + $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + } else { + $imageData = $filename; + } + } + + $html .= '<div style="position: relative;">'; + $html .= '<img style="position: absolute; z-index: 1; left: ' . + $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . + $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . + $imageData . '" border="0" />'; + $html .= '</div>'; + } + } + } + + // Return + return $html; + } + + /** + * Generate chart tag in cell + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param string $coordinates Cell coordinates + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function _writeChartInCell(PHPExcel_Worksheet $pSheet, $coordinates) { + // Construct HTML + $html = ''; + + // Write charts + foreach ($pSheet->getChartCollection() as $chart) { + if ($chart instanceof PHPExcel_Chart) { + $chartCoordinates = $chart->getTopLeftPosition(); + if ($chartCoordinates['cell'] == $coordinates) { + $chartFileName = PHPExcel_Shared_File::sys_get_temp_dir().'/'.uniqid().'.png'; + if (!$chart->render($chartFileName)) { + return; + } + + $html .= PHP_EOL; + $imageDetails = getimagesize($chartFileName); + if ($fp = fopen($chartFileName,"rb", 0)) { + $picture = fread($fp,filesize($chartFileName)); + fclose($fp); + // base64 encode the binary data, then break it + // into chunks according to RFC 2045 semantics + $base64 = chunk_split(base64_encode($picture)); + $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + + $html .= '<div style="position: relative;">'; + $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" border="0" />' . PHP_EOL; + $html .= '</div>'; + + unlink($chartFileName); + } + } + } + } + + // Return + return $html; + } + + /** + * Generate CSS styles + * + * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (<style> and </style>) + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateStyles($generateSurroundingHTML = true) { + // PHPExcel object known? + if (is_null($this->_phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Build CSS + $css = $this->buildCSS($generateSurroundingHTML); + + // Construct HTML + $html = ''; + + // Start styles + if ($generateSurroundingHTML) { + $html .= ' <style type="text/css">' . PHP_EOL; + $html .= ' html { ' . $this->_assembleCSS($css['html']) . ' }' . PHP_EOL; + } + + // Write all other styles + foreach ($css as $styleName => $styleDefinition) { + if ($styleName != 'html') { + $html .= ' ' . $styleName . ' { ' . $this->_assembleCSS($styleDefinition) . ' }' . PHP_EOL; + } + } + + // End styles + if ($generateSurroundingHTML) { + $html .= ' </style>' . PHP_EOL; + } + + // Return + return $html; + } + + /** + * Build CSS styles + * + * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { }) + * @return array + * @throws PHPExcel_Writer_Exception + */ + public function buildCSS($generateSurroundingHTML = true) { + // PHPExcel object known? + if (is_null($this->_phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Cached? + if (!is_null($this->_cssStyles)) { + return $this->_cssStyles; + } + + // Ensure that spans have been calculated + if (!$this->_spansAreCalculated) { + $this->_calculateSpans(); + } + + // Construct CSS + $css = array(); + + // Start styles + if ($generateSurroundingHTML) { + // html { } + $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; + $css['html']['font-size'] = '11pt'; + $css['html']['background-color'] = 'white'; + } + + + // table { } + $css['table']['border-collapse'] = 'collapse'; + if (!$this->_isPdf) { + $css['table']['page-break-after'] = 'always'; + } + + // .gridlines td { } + $css['.gridlines td']['border'] = '1px dotted black'; + + // .b {} + $css['.b']['text-align'] = 'center'; // BOOL + + // .e {} + $css['.e']['text-align'] = 'center'; // ERROR + + // .f {} + $css['.f']['text-align'] = 'right'; // FORMULA + + // .inlineStr {} + $css['.inlineStr']['text-align'] = 'left'; // INLINE + + // .n {} + $css['.n']['text-align'] = 'right'; // NUMERIC + + // .s {} + $css['.s']['text-align'] = 'left'; // STRING + + // Calculate cell style hashes + foreach ($this->_phpExcel->getCellXfCollection() as $index => $style) { + $css['td.style' . $index] = $this->_createCSSStyle( $style ); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->_sheetIndex)) { + $sheets = $this->_phpExcel->getAllSheets(); + } else { + $sheets[] = $this->_phpExcel->getSheet($this->_sheetIndex); + } + + // Build styles per sheet + foreach ($sheets as $sheet) { + // Calculate hash code + $sheetIndex = $sheet->getParent()->getIndex($sheet); + + // Build styles + // Calculate column widths + $sheet->calculateColumnWidths(); + + // col elements, initialize + $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1; + $column = -1; + while($column++ < $highestColumnIndex) { + $this->_columnWidths[$sheetIndex][$column] = 42; // approximation + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt'; + } + + // col elements, loop through columnDimensions and set width + foreach ($sheet->getColumnDimensions() as $columnDimension) { + if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->_defaultFont)) >= 0) { + $width = PHPExcel_Shared_Drawing::pixelsToPoints($width); + $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; + $this->_columnWidths[$sheetIndex][$column] = $width; + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt'; + + if ($columnDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse'; + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7 + } + } + } + + // Default row height + $rowDimension = $sheet->getDefaultRowDimension(); + + // table.sheetN tr { } + $css['table.sheet' . $sheetIndex . ' tr'] = array(); + + if ($rowDimension->getRowHeight() == -1) { + $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont()); + } else { + $pt_height = $rowDimension->getRowHeight(); + } + $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; + if ($rowDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; + $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; + } + + // Calculate row heights + foreach ($sheet->getRowDimensions() as $rowDimension) { + $row = $rowDimension->getRowIndex() - 1; + + // table.sheetN tr.rowYYYYYY { } + $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array(); + + if ($rowDimension->getRowHeight() == -1) { + $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->_phpExcel->getDefaultStyle()->getFont()); + } else { + $pt_height = $rowDimension->getRowHeight(); + } + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt'; + if ($rowDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none'; + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden'; + } + } + } + + // Cache + if (is_null($this->_cssStyles)) { + $this->_cssStyles = $css; + } + + // Return + return $css; + } + + /** + * Create CSS style + * + * @param PHPExcel_Style $pStyle PHPExcel_Style + * @return array + */ + private function _createCSSStyle(PHPExcel_Style $pStyle) { + // Construct CSS + $css = ''; + + // Create CSS + $css = array_merge( + $this->_createCSSStyleAlignment($pStyle->getAlignment()) + , $this->_createCSSStyleBorders($pStyle->getBorders()) + , $this->_createCSSStyleFont($pStyle->getFont()) + , $this->_createCSSStyleFill($pStyle->getFill()) + ); + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Alignment) + * + * @param PHPExcel_Style_Alignment $pStyle PHPExcel_Style_Alignment + * @return array + */ + private function _createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle) { + // Construct CSS + $css = array(); + + // Create CSS + $css['vertical-align'] = $this->_mapVAlign($pStyle->getVertical()); + if ($textAlign = $this->_mapHAlign($pStyle->getHorizontal())) { + $css['text-align'] = $textAlign; + if(in_array($textAlign,array('left','right'))) + $css['padding-'.$textAlign] = (string)((int)$pStyle->getIndent() * 9).'px'; + } + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Font) + * + * @param PHPExcel_Style_Font $pStyle PHPExcel_Style_Font + * @return array + */ + private function _createCSSStyleFont(PHPExcel_Style_Font $pStyle) { + // Construct CSS + $css = array(); + + // Create CSS + if ($pStyle->getBold()) { + $css['font-weight'] = 'bold'; + } + if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) { + $css['text-decoration'] = 'underline line-through'; + } else if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) { + $css['text-decoration'] = 'underline'; + } else if ($pStyle->getStrikethrough()) { + $css['text-decoration'] = 'line-through'; + } + if ($pStyle->getItalic()) { + $css['font-style'] = 'italic'; + } + + $css['color'] = '#' . $pStyle->getColor()->getRGB(); + $css['font-family'] = '\'' . $pStyle->getName() . '\''; + $css['font-size'] = $pStyle->getSize() . 'pt'; + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Borders) + * + * @param PHPExcel_Style_Borders $pStyle PHPExcel_Style_Borders + * @return array + */ + private function _createCSSStyleBorders(PHPExcel_Style_Borders $pStyle) { + // Construct CSS + $css = array(); + + // Create CSS + $css['border-bottom'] = $this->_createCSSStyleBorder($pStyle->getBottom()); + $css['border-top'] = $this->_createCSSStyleBorder($pStyle->getTop()); + $css['border-left'] = $this->_createCSSStyleBorder($pStyle->getLeft()); + $css['border-right'] = $this->_createCSSStyleBorder($pStyle->getRight()); + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Border) + * + * @param PHPExcel_Style_Border $pStyle PHPExcel_Style_Border + * @return string + */ + private function _createCSSStyleBorder(PHPExcel_Style_Border $pStyle) { + // Create CSS +// $css = $this->_mapBorderStyle($pStyle->getBorderStyle()) . ' #' . $pStyle->getColor()->getRGB(); + // Create CSS - add !important to non-none border styles for merged cells + $borderStyle = $this->_mapBorderStyle($pStyle->getBorderStyle()); + $css = $borderStyle . ' #' . $pStyle->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important'); + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Fill) + * + * @param PHPExcel_Style_Fill $pStyle PHPExcel_Style_Fill + * @return array + */ + private function _createCSSStyleFill(PHPExcel_Style_Fill $pStyle) { + // Construct HTML + $css = array(); + + // Create CSS + $value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ? + 'white' : '#' . $pStyle->getStartColor()->getRGB(); + $css['background-color'] = $value; + + // Return + return $css; + } + + /** + * Generate HTML footer + */ + public function generateHTMLFooter() { + // Construct HTML + $html = ''; + $html .= ' </body>' . PHP_EOL; + $html .= '</html>' . PHP_EOL; + + // Return + return $html; + } + + /** + * Generate table header + * + * @param PHPExcel_Worksheet $pSheet The worksheet for the table we are writing + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function _generateTableHeader($pSheet) { + $sheetIndex = $pSheet->getParent()->getIndex($pSheet); + + // Construct HTML + $html = ''; + $html .= $this->_setMargins($pSheet); + + if (!$this->_useInlineCss) { + $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : ''; + $html .= ' <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL; + } else { + $style = isset($this->_cssStyles['table']) ? + $this->_assembleCSS($this->_cssStyles['table']) : ''; + + if ($this->_isPdf && $pSheet->getShowGridlines()) { + $html .= ' <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="1" style="' . $style . '">' . PHP_EOL; + } else { + $html .= ' <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="0" style="' . $style . '">' . PHP_EOL; + } + } + + // Write <col> elements + $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1; + $i = -1; + while($i++ < $highestColumnIndex) { + if (!$this->_isPdf) { + if (!$this->_useInlineCss) { + $html .= ' <col class="col' . $i . '">' . PHP_EOL; + } else { + $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ? + $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : ''; + $html .= ' <col style="' . $style . '">' . PHP_EOL; + } + } + } + + // Return + return $html; + } + + /** + * Generate table footer + * + * @throws PHPExcel_Writer_Exception + */ + private function _generateTableFooter() { + // Construct HTML + $html = ''; + $html .= ' </table>' . PHP_EOL; + + // Return + return $html; + } + + /** + * Generate row + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param array $pValues Array containing cells in a row + * @param int $pRow Row number (0-based) + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function _generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0) { + if (is_array($pValues)) { + // Construct HTML + $html = ''; + + // Sheet index + $sheetIndex = $pSheet->getParent()->getIndex($pSheet); + + // DomPDF and breaks + if ($this->_isPdf && count($pSheet->getBreaks()) > 0) { + $breaks = $pSheet->getBreaks(); + + // check if a break is needed before this row + if (isset($breaks['A' . $pRow])) { + // close table: </table> + $html .= $this->_generateTableFooter(); + + // insert page break + $html .= '<div style="page-break-before:always" />'; + + // open table again: <table> + <col> etc. + $html .= $this->_generateTableHeader($pSheet); + } + } + + // Write row start + if (!$this->_useInlineCss) { + $html .= ' <tr class="row' . $pRow . '">' . PHP_EOL; + } else { + $style = isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) + ? $this->_assembleCSS($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : ''; + + $html .= ' <tr style="' . $style . '">' . PHP_EOL; + } + + // Write cells + $colNum = 0; + foreach ($pValues as $cellAddress) { + $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : ''; + $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1); + if (!$this->_useInlineCss) { + $cssClass = ''; + $cssClass = 'column' . $colNum; + } else { + $cssClass = array(); + if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) { + $this->_cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum]; + } + } + $colSpan = 1; + $rowSpan = 1; + + // initialize + $cellData = '&nbsp;'; + + // PHPExcel_Cell + if ($cell instanceof PHPExcel_Cell) { + $cellData = ''; + if (is_null($cell->getParent())) { + $cell->attach($pSheet); + } + // Value + if ($cell->getValue() instanceof PHPExcel_RichText) { + // Loop through rich text elements + $elements = $cell->getValue()->getRichTextElements(); + foreach ($elements as $element) { + // Rich text start? + if ($element instanceof PHPExcel_RichText_Run) { + $cellData .= '<span style="' . $this->_assembleCSS($this->_createCSSStyleFont($element->getFont())) . '">'; + + if ($element->getFont()->getSuperScript()) { + $cellData .= '<sup>'; + } else if ($element->getFont()->getSubScript()) { + $cellData .= '<sub>'; + } + } + + // Convert UTF8 data to PCDATA + $cellText = $element->getText(); + $cellData .= htmlspecialchars($cellText); + + if ($element instanceof PHPExcel_RichText_Run) { + if ($element->getFont()->getSuperScript()) { + $cellData .= '</sup>'; + } else if ($element->getFont()->getSubScript()) { + $cellData .= '</sub>'; + } + + $cellData .= '</span>'; + } + } + } else { + if ($this->_preCalculateFormulas) { + $cellData = PHPExcel_Style_NumberFormat::toFormattedString( + $cell->getCalculatedValue(), + $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(), + array($this, 'formatColor') + ); + } else { + $cellData = PHPExcel_Style_NumberFormat::ToFormattedString( + $cell->getValue(), + $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getNumberFormat()->getFormatCode(), + array($this, 'formatColor') + ); + } + $cellData = htmlspecialchars($cellData); + if ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSuperScript()) { + $cellData = '<sup>'.$cellData.'</sup>'; + } elseif ($pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() )->getFont()->getSubScript()) { + $cellData = '<sub>'.$cellData.'</sub>'; + } + } + + // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp; + // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world" + $cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData); + + // convert newline "\n" to '<br>' + $cellData = nl2br($cellData); + + // Extend CSS class? + if (!$this->_useInlineCss) { + $cssClass .= ' style' . $cell->getXfIndex(); + $cssClass .= ' ' . $cell->getDataType(); + } else { + if (isset($this->_cssStyles['td.style' . $cell->getXfIndex()])) { + $cssClass = array_merge($cssClass, $this->_cssStyles['td.style' . $cell->getXfIndex()]); + } + + // General horizontal alignment: Actual horizontal alignment depends on dataType + $sharedStyle = $pSheet->getParent()->getCellXfByIndex( $cell->getXfIndex() ); + if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL + && isset($this->_cssStyles['.' . $cell->getDataType()]['text-align'])) + { + $cssClass['text-align'] = $this->_cssStyles['.' . $cell->getDataType()]['text-align']; + } + } + } + + // Hyperlink? + if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) { + $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>'; + } + + // Should the cell be written or is it swallowed by a rowspan or colspan? + $writeCell = ! ( isset($this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]) + && $this->_isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum] ); + + // Colspan and Rowspan + $colspan = 1; + $rowspan = 1; + if (isset($this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) { + $spans = $this->_isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]; + $rowSpan = $spans['rowspan']; + $colSpan = $spans['colspan']; + + // Also apply style from last cell in merge to fix borders - + // relies on !important for non-none border declarations in _createCSSStyleBorder + $endCellCoord = PHPExcel_Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan); + if (!$this->_useInlineCss) { + $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex(); + } + } + + // Write + if ($writeCell) { + // Column start + $html .= ' <td'; + if (!$this->_useInlineCss) { + $html .= ' class="' . $cssClass . '"'; + } else { + //** Necessary redundant code for the sake of PHPExcel_Writer_PDF ** + // We must explicitly write the width of the <td> element because TCPDF + // does not recognize e.g. <col style="width:42pt"> + $width = 0; + $i = $colNum - 1; + $e = $colNum + $colSpan - 1; + while($i++ < $e) { + if (isset($this->_columnWidths[$sheetIndex][$i])) { + $width += $this->_columnWidths[$sheetIndex][$i]; + } + } + $cssClass['width'] = $width . 'pt'; + + // We must also explicitly write the height of the <td> element because TCPDF + // does not recognize e.g. <tr style="height:50pt"> + if (isset($this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) { + $height = $this->_cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height']; + $cssClass['height'] = $height; + } + //** end of redundant code ** + + $html .= ' style="' . $this->_assembleCSS($cssClass) . '"'; + } + if ($colSpan > 1) { + $html .= ' colspan="' . $colSpan . '"'; + } + if ($rowSpan > 1) { + $html .= ' rowspan="' . $rowSpan . '"'; + } + $html .= '>'; + + // Image? + $html .= $this->_writeImageInCell($pSheet, $coordinate); + + // Chart? + if ($this->_includeCharts) { + $html .= $this->_writeChartInCell($pSheet, $coordinate); + } + + // Cell data + $html .= $cellData; + + // Column end + $html .= '</td>' . PHP_EOL; + } + + // Next column + ++$colNum; + } + + // Write row end + $html .= ' </tr>' . PHP_EOL; + + // Return + return $html; + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Takes array where of CSS properties / values and converts to CSS string + * + * @param array + * @return string + */ + private function _assembleCSS($pValue = array()) + { + $pairs = array(); + foreach ($pValue as $property => $value) { + $pairs[] = $property . ':' . $value; + } + $string = implode('; ', $pairs); + + return $string; + } + + /** + * Get images root + * + * @return string + */ + public function getImagesRoot() { + return $this->_imagesRoot; + } + + /** + * Set images root + * + * @param string $pValue + * @return PHPExcel_Writer_HTML + */ + public function setImagesRoot($pValue = '.') { + $this->_imagesRoot = $pValue; + return $this; + } + + /** + * Get embed images + * + * @return boolean + */ + public function getEmbedImages() { + return $this->_embedImages; + } + + /** + * Set embed images + * + * @param boolean $pValue + * @return PHPExcel_Writer_HTML + */ + public function setEmbedImages($pValue = '.') { + $this->_embedImages = $pValue; + return $this; + } + + /** + * Get use inline CSS? + * + * @return boolean + */ + public function getUseInlineCss() { + return $this->_useInlineCss; + } + + /** + * Set use inline CSS? + * + * @param boolean $pValue + * @return PHPExcel_Writer_HTML + */ + public function setUseInlineCss($pValue = false) { + $this->_useInlineCss = $pValue; + return $this; + } + + /** + * Add color to formatted string as inline style + * + * @param string $pValue Plain formatted value without color + * @param string $pFormat Format code + * @return string + */ + public function formatColor($pValue, $pFormat) + { + // Color information, e.g. [Red] is always at the beginning + $color = null; // initialize + $matches = array(); + + $color_regex = '/^\\[[a-zA-Z]+\\]/'; + if (preg_match($color_regex, $pFormat, $matches)) { + $color = str_replace('[', '', $matches[0]); + $color = str_replace(']', '', $color); + $color = strtolower($color); + } + + // convert to PCDATA + $value = htmlspecialchars($pValue); + + // color span tag + if ($color !== null) { + $value = '<span style="color:' . $color . '">' . $value . '</span>'; + } + + return $value; + } + + /** + * Calculate information about HTML colspan and rowspan which is not always the same as Excel's + */ + private function _calculateSpans() + { + // Identify all cells that should be omitted in HTML due to cell merge. + // In HTML only the upper-left cell should be written and it should have + // appropriate rowspan / colspan attribute + $sheetIndexes = $this->_sheetIndex !== null ? + array($this->_sheetIndex) : range(0, $this->_phpExcel->getSheetCount() - 1); + + foreach ($sheetIndexes as $sheetIndex) { + $sheet = $this->_phpExcel->getSheet($sheetIndex); + + $candidateSpannedRow = array(); + + // loop through all Excel merged cells + foreach ($sheet->getMergeCells() as $cells) { + list($cells, ) = PHPExcel_Cell::splitRange($cells); + $first = $cells[0]; + $last = $cells[1]; + + list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first); + $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1; + + list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last); + $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1; + + // loop through the individual cells in the individual merge + $r = $fr - 1; + while($r++ < $lr) { + // also, flag this row as a HTML row that is candidate to be omitted + $candidateSpannedRow[$r] = $r; + + $c = $fc - 1; + while($c++ < $lc) { + if ( !($c == $fc && $r == $fr) ) { + // not the upper-left cell (should not be written in HTML) + $this->_isSpannedCell[$sheetIndex][$r][$c] = array( + 'baseCell' => array($fr, $fc), + ); + } else { + // upper-left is the base cell that should hold the colspan/rowspan attribute + $this->_isBaseCell[$sheetIndex][$r][$c] = array( + 'xlrowspan' => $lr - $fr + 1, // Excel rowspan + 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change + 'xlcolspan' => $lc - $fc + 1, // Excel colspan + 'colspan' => $lc - $fc + 1, // HTML colspan, value may change + ); + } + } + } + } + + // Identify which rows should be omitted in HTML. These are the rows where all the cells + // participate in a merge and the where base cells are somewhere above. + $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()); + foreach ($candidateSpannedRow as $rowIndex) { + if (isset($this->_isSpannedCell[$sheetIndex][$rowIndex])) { + if (count($this->_isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) { + $this->_isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex; + }; + } + } + + // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 + if ( isset($this->_isSpannedRow[$sheetIndex]) ) { + foreach ($this->_isSpannedRow[$sheetIndex] as $rowIndex) { + $adjustedBaseCells = array(); + $c = -1; + $e = $countColumns - 1; + while($c++ < $e) { + $baseCell = $this->_isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell']; + + if ( !in_array($baseCell, $adjustedBaseCells) ) { + // subtract rowspan by 1 + --$this->_isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan']; + $adjustedBaseCells[] = $baseCell; + } + } + } + } + + // TODO: Same for columns + } + + // We have calculated the spans + $this->_spansAreCalculated = true; + } + + private function _setMargins(PHPExcel_Worksheet $pSheet) { + $htmlPage = '@page { '; + $htmlBody = 'body { '; + + $left = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; '; + $htmlPage .= 'left-margin: ' . $left; + $htmlBody .= 'left-margin: ' . $left; + $right = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; '; + $htmlPage .= 'right-margin: ' . $right; + $htmlBody .= 'right-margin: ' . $right; + $top = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; '; + $htmlPage .= 'top-margin: ' . $top; + $htmlBody .= 'top-margin: ' . $top; + $bottom = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; '; + $htmlPage .= 'bottom-margin: ' . $bottom; + $htmlBody .= 'bottom-margin: ' . $bottom; + + $htmlPage .= "}\n"; + $htmlBody .= "}\n"; + + return "<style>\n" . $htmlPage . $htmlBody . "</style>\n"; + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php new file mode 100644 index 00000000..6974c93c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php @@ -0,0 +1,46 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_IWriter + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +interface PHPExcel_Writer_IWriter +{ + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = NULL); + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php new file mode 100644 index 00000000..65fb50ed --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php @@ -0,0 +1,90 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_PDF + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_PDF +{ + + /** + * The wrapper for the requested PDF rendering engine + * + * @var PHPExcel_Writer_PDF_Core + */ + private $_renderer = NULL; + + /** + * Instantiate a new renderer of the configured type within this container class + * + * @param PHPExcel $phpExcel PHPExcel object + * @throws PHPExcel_Writer_Exception when PDF library is not configured + */ + public function __construct(PHPExcel $phpExcel) + { + $pdfLibraryName = PHPExcel_Settings::getPdfRendererName(); + if (is_null($pdfLibraryName)) { + throw new PHPExcel_Writer_Exception("PDF Rendering library has not been defined."); + } + + $pdfLibraryPath = PHPExcel_Settings::getPdfRendererPath(); + if (is_null($pdfLibraryName)) { + throw new PHPExcel_Writer_Exception("PDF Rendering library path has not been defined."); + } + $includePath = str_replace('\\', '/', get_include_path()); + $rendererPath = str_replace('\\', '/', $pdfLibraryPath); + if (strpos($rendererPath, $includePath) === false) { + set_include_path(get_include_path() . PATH_SEPARATOR . $pdfLibraryPath); + } + + $rendererName = 'PHPExcel_Writer_PDF_' . $pdfLibraryName; + $this->_renderer = new $rendererName($phpExcel); + } + + + /** + * Magic method to handle direct calls to the configured PDF renderer wrapper class. + * + * @param string $name Renderer library method name + * @param mixed[] $arguments Array of arguments to pass to the renderer method + * @return mixed Returned data from the PDF renderer wrapper method + */ + public function __call($name, $arguments) + { + if ($this->_renderer === NULL) { + throw new PHPExcel_Writer_Exception("PDF Rendering library has not been defined."); + } + + return call_user_func_array(array($this->_renderer, $name), $arguments); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php new file mode 100644 index 00000000..3b281f4e --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php @@ -0,0 +1,364 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** + * PHPExcel_Writer_PDF_Core + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +abstract class PHPExcel_Writer_PDF_Core extends PHPExcel_Writer_HTML +{ + /** + * Temporary storage directory + * + * @var string + */ + protected $_tempDir = ''; + + /** + * Font + * + * @var string + */ + protected $_font = 'freesans'; + + /** + * Orientation (Over-ride) + * + * @var string + */ + protected $_orientation = NULL; + + /** + * Paper size (Over-ride) + * + * @var int + */ + protected $_paperSize = NULL; + + + /** + * Temporary storage for Save Array Return type + * + * @var string + */ + private $_saveArrayReturnType; + + /** + * Paper Sizes xRef List + * + * @var array + */ + protected static $_paperSizes = array( + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_SMALL + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID + => array(792.00, 1224.00), // (11 in. by 17 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEDGER + => array(1224.00, 792.00), // (17 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL + => 'LEGAL', // (8.5 in. by 14 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STATEMENT + => array(396.00, 612.00), // (5.5 in. by 8.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_EXECUTIVE + => 'EXECUTIVE', // (7.25 in. by 10.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3 + => 'A3', // (297 mm by 420 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4 + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_SMALL + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5 + => 'A5', // (148 mm by 210 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4 + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5 + => 'B5', // (176 mm by 250 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_FOLIO + => 'FOLIO', // (8.5 in. by 13 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_QUARTO + => array(609.45, 779.53), // (215 mm by 275 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_1 + => array(720.00, 1008.00), // (10 in. by 14 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_2 + => array(792.00, 1224.00), // (11 in. by 17 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NOTE + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO9_ENVELOPE + => array(279.00, 639.00), // (3.875 in. by 8.875 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO10_ENVELOPE + => array(297.00, 684.00), // (4.125 in. by 9.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO11_ENVELOPE + => array(324.00, 747.00), // (4.5 in. by 10.375 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO12_ENVELOPE + => array(342.00, 792.00), // (4.75 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO14_ENVELOPE + => array(360.00, 828.00), // (5 in. by 11.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C + => array(1224.00, 1584.00), // (17 in. by 22 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_D + => array(1584.00, 2448.00), // (22 in. by 34 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_E + => array(2448.00, 3168.00), // (34 in. by 44 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_DL_ENVELOPE + => array(311.81, 623.62), // (110 mm by 220 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C5_ENVELOPE + => 'C5', // (162 mm by 229 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C3_ENVELOPE + => 'C3', // (324 mm by 458 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C4_ENVELOPE + => 'C4', // (229 mm by 324 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C6_ENVELOPE + => 'C6', // (114 mm by 162 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C65_ENVELOPE + => array(323.15, 649.13), // (114 mm by 229 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4_ENVELOPE + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5_ENVELOPE + => 'B5', // (176 mm by 250 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B6_ENVELOPE + => array(498.90, 354.33), // (176 mm by 125 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ITALY_ENVELOPE + => array(311.81, 651.97), // (110 mm by 230 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_MONARCH_ENVELOPE + => array(279.00, 540.00), // (3.875 in. by 7.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_6_3_4_ENVELOPE + => array(261.00, 468.00), // (3.625 in. by 6.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_US_STANDARD_FANFOLD + => array(1071.00, 792.00), // (14.875 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD + => array(612.00, 864.00), // (8.5 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD + => 'FOLIO', // (8.5 in. by 13 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B4 + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD + => array(566.93, 419.53), // (200 mm by 148 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_1 + => array(648.00, 792.00), // (9 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_2 + => array(720.00, 792.00), // (10 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_3 + => array(1080.00, 792.00), // (15 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_INVITE_ENVELOPE + => array(623.62, 623.62), // (220 mm by 220 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER + => array(667.80, 864.00), // (9.275 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER + => array(667.80, 1080.00), // (9.275 in. by 15 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER + => array(841.68, 1296.00), // (11.69 in. by 18 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_EXTRA_PAPER + => array(668.98, 912.76), // (236 mm by 322 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER + => array(595.80, 792.00), // (8.275 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER + => array(667.80, 864.00), // (9.275 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER + => array(643.46, 1009.13), // (227 mm by 356 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER + => array(864.57, 1380.47), // (305 mm by 487 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_PLUS_PAPER + => array(612.00, 913.68), // (8.5 in. by 12.69 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_PLUS_PAPER + => array(595.28, 935.43), // (210 mm by 330 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER + => 'A5', // (148 mm by 210 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER + => array(515.91, 728.50), // (182 mm by 257 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_PAPER + => array(912.76, 1261.42), // (322 mm by 445 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_EXTRA_PAPER + => array(493.23, 666.14), // (174 mm by 235 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER + => array(569.76, 782.36), // (201 mm by 276 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER + => 'A2', // (420 mm by 594 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER + => 'A3', // (297 mm by 420 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER + => array(912.76, 1261.42) // (322 mm by 445 mm) + ); + + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + $this->setUseInlineCss(TRUE); + $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + } + + /** + * Get Font + * + * @return string + */ + public function getFont() + { + return $this->_font; + } + + /** + * Set font. Examples: + * 'arialunicid0-chinese-simplified' + * 'arialunicid0-chinese-traditional' + * 'arialunicid0-korean' + * 'arialunicid0-japanese' + * + * @param string $fontName + */ + public function setFont($fontName) + { + $this->_font = $fontName; + return $this; + } + + /** + * Get Paper Size + * + * @return int + */ + public function getPaperSize() + { + return $this->_paperSize; + } + + /** + * Set Paper Size + * + * @param string $pValue Paper size + * @return PHPExcel_Writer_PDF + */ + public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) + { + $this->_paperSize = $pValue; + return $this; + } + + /** + * Get Orientation + * + * @return string + */ + public function getOrientation() + { + return $this->_orientation; + } + + /** + * Set Orientation + * + * @param string $pValue Page orientation + * @return PHPExcel_Writer_PDF + */ + public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + { + $this->_orientation = $pValue; + return $this; + } + + /** + * Get temporary storage directory + * + * @return string + */ + public function getTempDir() + { + return $this->_tempDir; + } + + /** + * Set temporary storage directory + * + * @param string $pValue Temporary storage directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_PDF + */ + public function setTempDir($pValue = '') + { + if (is_dir($pValue)) { + $this->_tempDir = $pValue; + } else { + throw new PHPExcel_Writer_Exception("Directory does not exist: $pValue"); + } + return $this; + } + + /** + * Save PHPExcel to PDF file, pre-save + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + protected function prepareForSave($pFilename = NULL) + { + // garbage collect + $this->_phpExcel->garbageCollect(); + + $this->_saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Open file + $fileHandle = fopen($pFilename, 'w'); + if ($fileHandle === FALSE) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + // Set PDF + $this->_isPdf = TRUE; + // Build CSS + $this->buildCSS(TRUE); + + return $fileHandle; + } + + /** + * Save PHPExcel to PDF file, post-save + * + * @param resource $fileHandle + * @throws PHPExcel_Writer_Exception + */ + protected function restoreStateAfterSave($fileHandle) + { + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($this->_saveArrayReturnType); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php new file mode 100644 index 00000000..111dd360 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php @@ -0,0 +1,120 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** Require DomPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/dompdf_config.inc.php'; +if (file_exists($pdfRendererClassFile)) { + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_DomPDF + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_PDF_DomPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = NULL) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT + : $this->getOrientation(); + } + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$_paperSizes[$printPaperSize])) { + $paperSize = self::$_paperSizes[$printPaperSize]; + } + + $orientation = ($orientation == 'L') ? 'landscape' : 'portrait'; + + // Create PDF + $pdf = new DOMPDF(); + $pdf->set_paper(strtolower($paperSize), $orientation); + + $pdf->load_html( + $this->generateHTMLHeader(FALSE) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + $pdf->render(); + + // Write to file + fwrite($fileHandle, $pdf->output()); + + parent::restoreStateAfterSave($fileHandle); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php new file mode 100644 index 00000000..8e274f4c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php @@ -0,0 +1,130 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** Require mPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/mpdf.php'; +if (file_exists($pdfRendererClassFile)) { + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_mPDF + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_PDF_mPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = NULL) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + $this->setOrientation($orientation); + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT + : $this->getOrientation(); + } + $orientation = strtoupper($orientation); + + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$_paperSizes[$printPaperSize])) { + $paperSize = self::$_paperSizes[$printPaperSize]; + } + + // Create PDF + $pdf = new mpdf(); + $ortmp = $orientation; + $pdf->_setPageSize(strtoupper($paperSize), $ortmp); + $pdf->DefOrientation = $orientation; + $pdf->AddPage($orientation); + + // Document info + $pdf->SetTitle($this->_phpExcel->getProperties()->getTitle()); + $pdf->SetAuthor($this->_phpExcel->getProperties()->getCreator()); + $pdf->SetSubject($this->_phpExcel->getProperties()->getSubject()); + $pdf->SetKeywords($this->_phpExcel->getProperties()->getKeywords()); + $pdf->SetCreator($this->_phpExcel->getProperties()->getCreator()); + + $pdf->WriteHTML( + $this->generateHTMLHeader(FALSE) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + + // Write to file + fwrite($fileHandle, $pdf->Output('', 'S')); + + parent::restoreStateAfterSave($fileHandle); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php new file mode 100644 index 00000000..c3809ec7 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php @@ -0,0 +1,136 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2014 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version 1.8.0, 2014-03-02 + */ + + +/** Require tcPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/tcpdf.php'; +if (file_exists($pdfRendererClassFile)) { + $k_path_url = PHPExcel_Settings::getPdfRendererPath(); + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_tcPDF + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_PDF_tcPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = NULL) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->_phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + $printPaperSize = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->_phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + } + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$_paperSizes[$printPaperSize])) { + $paperSize = self::$_paperSizes[$printPaperSize]; + } + + + // Create PDF + $pdf = new TCPDF($orientation, 'pt', $paperSize); + $pdf->setFontSubsetting(FALSE); + // Set margins, converting inches to points (using 72 dpi) + $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72); + $pdf->SetAutoPageBreak(TRUE, $printMargins->getBottom() * 72); + + $pdf->setPrintHeader(FALSE); + $pdf->setPrintFooter(FALSE); + + $pdf->AddPage(); + + // Set the appropriate font + $pdf->SetFont($this->getFont()); + $pdf->writeHTML( + $this->generateHTMLHeader(FALSE) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + + // Document info + $pdf->SetTitle($this->_phpExcel->getProperties()->getTitle()); + $pdf->SetAuthor($this->_phpExcel->getProperties()->getCreator()); + $pdf->SetSubject($this->_phpExcel->getProperties()->getSubject()); + $pdf->SetKeywords($this->_phpExcel->getProperties()->getKeywords()); + $pdf->SetCreator($this->_phpExcel->getProperties()->getCreator()); + + // Write to file + fwrite($fileHandle, $pdf->output($pFilename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } + +} diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config new file mode 100644 index 00000000..d7ecb2b2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config @@ -0,0 +1,49 @@ +## +## PHPExcel +## + +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = лв + + +## +## Excel Error Codes (For future use) + +## +NULL = #ПРАЗНО! +DIV0 = #ДЕЛ/0! +VALUE = #СТОЙНОСТ! +REF = #РЕФ! +NAME = #ИМЕ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config new file mode 100644 index 00000000..af4589b0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = Kč + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #HODNOTA! +REF = #REF! +NAME = #NÁZEV? +NUM = #NUM! +NA = #N/A diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions new file mode 100644 index 00000000..f324759d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funkce doplňků a automatizace +## +GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena. + + +## +## Cube functions Funkce pro práci s krychlemi +## +CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace. +CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice. +CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena. +CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů. +CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel. +CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině +CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle. + + +## +## Database functions Funkce databáze +## +DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze. +DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla. +DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné. +DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria. +DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze. +DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze. +DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria. +DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze. +DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze. +DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria. +DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze. +DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze. + + +## +## Date and time functions Funkce data a času +## +DATE = DATUM ## Vrátí pořadové číslo určitého data. +DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo. +DAY = DEN ## Převede pořadové číslo na den v měsíci. +DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny. +EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu. +EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců. +HOUR = HODINA ## Převede pořadové číslo na hodinu. +MINUTE = MINUTA ## Převede pořadové číslo na minutu. +MONTH = MĚSÍC ## Převede pořadové číslo na měsíc. +NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty. +NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času. +SECOND = SEKUNDA ## Převede pořadové číslo na sekundu. +TIME = ČAS ## Vrátí pořadové číslo určitého času. +TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo. +TODAY = DNES ## Vrátí pořadové číslo dnešního data. +WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu. +WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce. +WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní. +YEAR = ROK ## Převede pořadové číslo na rok. +YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem. + + +## +## Engineering functions Inženýrské funkce (Technické funkce) +## +BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x). +BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x). +BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x). +BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x). +BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové. +BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové. +BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové. +COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo. +CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému. +DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové +DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové. +DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové. +DELTA = DELTA ## Testuje rovnost dvou hodnot. +ERF = ERF ## Vrátí chybovou funkci. +ERFC = ERFC ## Vrátí doplňkovou chybovou funkci. +GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota. +HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární. +HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové. +HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové. +IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla. +IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla. +IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech. +IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu. +IMCOS = IMCOS ## Vrátí kosinus komplexního čísla. +IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel. +IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla. +IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla. +IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla. +IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2. +IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo. +IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel. +IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla. +IMSIN = IMSIN ## Vrátí sinus komplexního čísla. +IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla. +IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly. +IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel. +OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární. +OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové. +OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové. + + +## +## Financial functions Finanční funkce +## +ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech. +ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti. +AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace. +AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období. +COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti. +COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování. +COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu. +COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování. +COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti. +COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování. +CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími. +CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky. +DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem. +DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte. +DISC = DISC ## Vrátí diskontní sazbu cenného papíru. +DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem. +DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem. +DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami. +EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu. +FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice. +FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku. +INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru. +IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období. +IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků. +ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období. +MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč. +MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb. +NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu. +NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici. +NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby. +ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím. +ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím. +ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím. +ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím. +PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity. +PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období. +PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech. +PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč. +PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti. +PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice. +RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity. +RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru. +SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období. +SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období. +TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace. +TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč. +TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny. +VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu. +XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický. +XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický. +YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech. +YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny. +YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti. + + +## +## Information functions Informační funkce +## +CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky. +ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby. +INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí. +ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku. +ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A). +ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota. +ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé. +ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota. +ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A. +ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text. +ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo. +ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché. +ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz. +ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text. +N = N ## Vrátí hodnotu převedenou na číslo. +NA = NEDEF ## Vrátí chybovou hodnotu #N/A. +TYPE = TYP ## Vrátí číslo označující datový typ hodnoty. + + +## +## Logical functions Logické funkce +## +AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA. +FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA. +IF = KDYŽ ## Určí, který logický test má proběhnout. +IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce. +NOT = NE ## Provede logickou negaci argumentu funkce. +OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA. +TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA. + + +## +## Lookup and reference functions Vyhledávací funkce +## +ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu. +AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu. +CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot. +COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu. +COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu. +HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky. +HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet. +INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice. +INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou. +LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici. +MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici. +OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu. +ROW = ŘÁDEK ## Vrátí číslo řádku odkazu. +ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu. +RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).). +TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici. +VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky. + + +## +## Math and trigonometry functions Matematické a trigonometrické funkce +## +ABS = ABS ## Vrátí absolutní hodnotu čísla. +ACOS = ARCCOS ## Vrátí arkuskosinus čísla. +ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla. +ASIN = ARCSIN ## Vrátí arkussinus čísla. +ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla. +ATAN = ARCTG ## Vrátí arkustangens čísla. +ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice. +ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla. +CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty. +COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek. +COS = COS ## Vrátí kosinus čísla. +COSH = COSH ## Vrátí hyperbolický kosinus čísla. +DEGREES = DEGREES ## Převede radiány na stupně. +EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo. +EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo. +FACT = FAKTORIÁL ## Vrátí faktoriál čísla. +FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla. +FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule. +GCD = GCD ## Vrátí největší společný dělitel. +INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo. +LCM = LCM ## Vrátí nejmenší společný násobek. +LN = LN ## Vrátí přirozený logaritmus čísla. +LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu. +LOG10 = LOG ## Vrátí dekadický logaritmus čísla. +MDETERM = DETERMINANT ## Vrátí determinant matice. +MINVERSE = INVERZE ## Vrátí inverzní matici. +MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic. +MOD = MOD ## Vrátí zbytek po dělení. +MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek. +MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel. +ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo. +PI = PI ## Vrátí hodnotu čísla pí. +POWER = POWER ## Umocní číslo na zadanou mocninu. +PRODUCT = SOUČIN ## Vynásobí argumenty funkce. +QUOTIENT = QUOTIENT ## Vrátí celou část dělení. +RADIANS = RADIANS ## Převede stupně na radiány. +RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1. +RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly. +ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu. +ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic. +ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule. +ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly. +SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce. +SIGN = SIGN ## Vrátí znaménko čísla. +SIN = SIN ## Vrátí sinus daného úhlu. +SINH = SINH ## Vrátí hyperbolický sinus čísla. +SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu. +SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí). +SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi. +SUM = SUMA ## Sečte argumenty funkce. +SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií. +SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami. +SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic. +SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů. +SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích. +SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích. +SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích. +TAN = TGTG ## Vrátí tangens čísla. +TANH = TGH ## Vrátí hyperbolický tangens čísla. +TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo. + + +## +## Statistical functions Statistické funkce +## +AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty. +AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů. +AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot. +AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce. +AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám. +BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta. +BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta. +BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin. +CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát. +CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát. +CHITEST = CHITEST ## Vrátí test nezávislosti. +CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru. +CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat. +COUNT = POČET ## Vrátí počet čísel v seznamu argumentů. +COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů. +COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti. +COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím. +COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím. +COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek +CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria. +DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek. +EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení. +FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F. +FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F. +FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace. +FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci. +FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu. +FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici. +FTEST = FTEST ## Vrátí výsledek F-testu. +GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama. +GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama. +GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x). +GEOMEAN = GEOMEAN ## Vrátí geometrický průměr. +GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu. +HARMEAN = HARMEAN ## Vrátí harmonický průměr. +HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení. +INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry. +KURT = KURT ## Vrátí hodnotu excesu množiny dat. +LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat. +LINEST = LINREGRESE ## Vrátí parametry lineárního trendu. +LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu. +LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení. +LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení. +MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů. +MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot. +MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel. +MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů. +MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot. +MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji. +NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení. +NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení. +NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení. +NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení. +NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení. +PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient. +PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti. +PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat. +PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů. +POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení. +PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami. +QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat. +RANK = RANK ## Vrátí pořadí čísla v seznamu čísel. +RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu. +SKEW = SKEW ## Vrátí zešikmení rozdělení. +SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry. +SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat. +STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu. +STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru. +STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot. +STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru. +STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot. +STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi. +TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení. +TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení. +TREND = LINTREND ## Vrátí hodnoty lineárního trendu. +TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat. +TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem. +VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru. +VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot. +VARP = VAR ## Vypočte rozptyl základního souboru. +VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot. +WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení. +ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu. + + +## +## Text functions Textové funkce +## +ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové). +BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht). +CHAR = ZNAK ## Vrátí znak určený číslem kódu. +CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky. +CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce. +CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné. +DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna). +EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné. +FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). +FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). +FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst. +JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové). +LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. +LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. +LEN = DÉLKA ## Vrátí počet znaků textového řetězce. +LENB = LENB ## Vrátí počet znaků textového řetězce. +LOWER = MALÁ ## Převede text na malá písmena. +MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. +MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. +PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce. +PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké. +REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu. +REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu. +REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování. +RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. +RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. +SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). +SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). +SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým. +T = T ## Převede argumenty na text. +TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text. +TRIM = PROČISTIT ## Odstraní z textu mezery. +UPPER = VELKÁ ## Převede text na velká písmena. +VALUE = HODNOTA ## Převede textový argument na číslo. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config new file mode 100644 index 00000000..1ddecb93 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config @@ -0,0 +1,48 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + + +## +## Excel Error Codes (For future use) +## +NULL = #NUL! +DIV0 = #DIVISION/0! +VALUE = #VÆRDI! +REF = #REFERENCE! +NAME = #NAVN? +NUM = #NUM! +NA = #I/T diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions new file mode 100644 index 00000000..102d5784 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner +## +GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport + + +## +## Cube functions Kubefunktioner +## +CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer. +CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben. +CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet. +CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever. +CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel. +CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt. +CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube. + + +## +## Database functions Databasefunktioner +## +DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter +DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database +DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database +DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database +DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter +DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter +DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database +DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter +DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter +DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne +DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter +DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter + + +## +## Date and time functions Dato- og klokkeslætsfunktioner +## +DATE = DATO ## Returnerer serienummeret for en bestemt dato +DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer +DAY = DAG ## Konverterer et serienummer til en dag i måneden +DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage +EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen +EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder +HOUR = TIME ## Konverterer et serienummer til en time +MINUTE = MINUT ## Konverterer et serienummer til et minut +MONTH = MÅNED ## Konverterer et serienummer til en måned +NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer +NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt +SECOND = SEKUND ## Konverterer et serienummer til et sekund +TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt +TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer +TODAY = IDAG ## Returnerer serienummeret for dags dato +WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag +WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året +WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage +YEAR = ÅR ## Konverterer et serienummer til et år +YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato + + +## +## Engineering functions Tekniske funktioner +## +BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x) +BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x) +BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x) +BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x) +BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal +BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal +BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal. +COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal +CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden +DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal +DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal +DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal +DELTA = DELTA ## Tester, om to værdier er ens +ERF = FEJLFUNK ## Returner fejlfunktionen +ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion +GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi +HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal +HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal +HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal +IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal +IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal +IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer +IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal +IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus +IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal +IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion +IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme +IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme) +IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme) +IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens +IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal +IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal +IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus +IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod +IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal +IMSUM = IMAGSUM ## Returnerer summen af komplekse tal +OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal +OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal +OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal + + +## +## Financial functions Finansielle funktioner +## +ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger +ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb +AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient +AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode +COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen +COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen +COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen +COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen +COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen +COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen +CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder +CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder +DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden +DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver +DISC = DISKONTO ## Returnerer et værdipapirs diskonto +DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal +DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk +DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger +EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente +FV = FV ## Returnerer fremtidsværdien af en investering +FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser +INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir +IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode +IRR = IA ## Returnerer den interne rente for en række pengestrømme +ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode +MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100 +MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente +NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente +NPER = NPER ## Returnerer antallet af perioder for en investering +NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats +ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode +ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode +ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode +ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode +PMT = YDELSE ## Returnerer renten fra en investering for en given periode +PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode +PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger +PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir +PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb +PV = NV ## Returnerer den nuværende værdi af en investering +RATE = RENTE ## Returnerer renten i hver periode for en annuitet +RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir +SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode +SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode +TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation +TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation +TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation +VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden +XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske +XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske +YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger +YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation +YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb + + +## +## Information functions Informationsfunktioner +## +CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle +ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype +INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø +ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom +ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T +ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi +ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige +ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi +ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T +ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst +ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal +ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige +ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference +ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst +N = TAL ## Returnerer en værdi konverteret til et tal +NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T +TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi + + +## +## Logical functions Logiske funktioner +## +AND = OG ## Returnerer SAND, hvis alle argumenterne er sande +FALSE = FALSK ## Returnerer den logiske værdi FALSK +IF = HVIS ## Angiver en logisk test, der skal udføres +IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen +NOT = IKKE ## Vender argumentets logik om +OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt +TRUE = SAND ## Returnerer den logiske værdi SAND + + +## +## Lookup and reference functions Opslags- og referencefunktioner +## +ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark +AREAS = OMRÅDER ## Returnerer antallet af områder i en reference +CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier +COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference +COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference +HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle +HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet +INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix +INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi +LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix +MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix +OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference +ROW = RÆKKE ## Returnerer rækkenummeret for en reference +ROWS = RÆKKER ## Returnerer antallet af rækker i en reference +RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).) +TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix +VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi + + +## +## Math and trigonometry functions Matematiske og trigonometriske funktioner +## +ABS = ABS ## Returnerer den absolutte værdi af et tal +ACOS = ARCCOS ## Returnerer et tals arcus cosinus +ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal +ASIN = ARCSIN ## Returnerer et tals arcus sinus +ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal +ATAN = ARCTAN ## Returnerer et tals arcus tangens +ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens +ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens +CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning +COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter +COS = COS ## Returnerer et tals cosinus +COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal +DEGREES = GRADER ## Konverterer radianer til grader +EVEN = LIGE ## Runder et tal op til nærmeste lige heltal +EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal +FACT = FAKULTET ## Returnerer et tals fakultet +FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet +FLOOR = AFRUND.GULV ## Runder et tal ned mod nul +GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor +INT = HELTAL ## Nedrunder et tal til det nærmeste heltal +LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum +LN = LN ## Returnerer et tals naturlige logaritme +LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal +LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal +MDETERM = MDETERM ## Returnerer determinanten for en matrix +MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix +MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer +MOD = REST ## Returnerer restværdien fra division +MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum +MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt +ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal +PI = PI ## Returnerer værdien af pi +POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens +PRODUCT = PRODUKT ## Multiplicerer argumenterne +QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division +RADIANS = RADIANER ## Konverterer grader til radianer +RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1 +RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives +ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst +ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler +ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul +ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul) +SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel +SIGN = FORTEGN ## Returnerer et tals fortegn +SIN = SIN ## Returnerer en given vinkels sinusværdi +SINH = SINH ## Returnerer den hyperbolske sinus af et tal +SQRT = KVROD ## Returnerer en positiv kvadratrod +SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;) +SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database +SUM = SUM ## Lægger argumenterne sammen +SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium. +SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier. +SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter +SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater +SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer +SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer +SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer +TAN = TAN ## Returnerer et tals tangens +TANH = TANH ## Returnerer et tals hyperbolske tangens +TRUNC = AFKORT ## Afkorter et tal til et heltal + + +## +## Statistical functions Statistiske funktioner +## +AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi +AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne +AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier +AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område +AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier. +BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion +BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling +BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen +CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling +CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling +CHITEST = CHITEST ## Foretager en test for uafhængighed +CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population +CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt +COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter +COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter +COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område +COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område +COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område +COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler +CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien. +DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien +EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen +FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen +FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen +FISHER = FISHER ## Returnerer Fisher-transformationen +FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation +FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens +FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor +FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians +GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen +GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen +GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x) +GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit +GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens +HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit +HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling +INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression +KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel +LARGE = STOR ## Returnerer den k'te største værdi i et datasæt +LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens +LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens +LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen +LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen +MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter. +MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier +MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal +MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter. +MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier +MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt +NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling +NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen +NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen +NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen +NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen +PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient +PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet +PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt +PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter +POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling +PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden +QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt +RANK = PLADS ## Returnerer rangen for et tal på en liste med tal +RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression +SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel +SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression +SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet +STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi +STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve +STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier +STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population +STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier +STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression +TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling +TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling +TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens +TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet +TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test +VAR = VARIANS ## Beregner variansen på basis af en prøve +VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier +VARP = VARIANSP ## Beregner variansen på basis af hele populationen +VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier +WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen +ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test + + +## +## Text functions Tekstfunktioner +## +ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte) +BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht) +CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret +CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst +CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng +CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement +DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner) +EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske +FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) +FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) +FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler +JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte) +LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi +LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi +LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng +LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng +LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver +MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition +MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition +PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng +PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav +REPLACE = ERSTAT ## Erstatter tegn i tekst +REPLACEB = ERSTATB ## Erstatter tegn i tekst +REPT = GENTAG ## Gentager tekst et givet antal gange +RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi +RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi +SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) +SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) +SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng +T = T ## Konverterer argumenterne til tekst +TEXT = TEKST ## Formaterer et tal og konverterer det til tekst +TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst +UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver +VALUE = VÆRDI ## Konverterer et tekstargument til et tal diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config new file mode 100644 index 00000000..c9972751 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #WERT! +REF = #BEZUG! +NAME = #NAME? +NUM = #ZAHL! +NA = #NV diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions new file mode 100644 index 00000000..8ce08de4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Add-In- und Automatisierungsfunktionen +## +GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben. + + +## +## Cube functions Cubefunktionen +## +CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann. +CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist. +CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben. +CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer. +CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt. +CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück. +CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück. + + +## +## Database functions Datenbankfunktionen +## +DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück +DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank +DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank +DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht +DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück +DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück +DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen +DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen +DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge +DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen +DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge +DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge + + +## +## Date and time functions Datums- und Zeitfunktionen +## +DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück +DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um +DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um +DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat +EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt +EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück +HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um +MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um +MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um +NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück +NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück +SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um +TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück +TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um +TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück +WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um +WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt +WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück +YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um +YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück + + +## +## Engineering functions Konstruktionsfunktionen +## +BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück +BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück +BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück +BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück +BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um +BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um +BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um +COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um +CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um +DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um +DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um +DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um +DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind +ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück +ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück +GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist +HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um +HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um +HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um +IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück +IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück +IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird +IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück +IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück +IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück +IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück +IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück +IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück +IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück +IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl +IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück +IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück +IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück +IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück +IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück +IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück +OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um +OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um +OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um + + +## +## Financial functions Finanzmathematische Funktionen +## +ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück +ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden +AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück +AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück +COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück +COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt +COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück +COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück +COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück +COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück +CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind +CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist +DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück +DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück +DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück +DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um +DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um +DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück +EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück +FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück +FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück +INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück +IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück +IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück +ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen +MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück +MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden +NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück +NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück +NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück +ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück +ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück +ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück +ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück +PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück +PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück +PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt +PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück +PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt +PV = BW ## Gibt den Barwert einer Investition zurück +RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück +RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück +SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück +SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück +TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück +TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück +TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück +VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück +XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück +XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück +YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt +YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück +YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt + + +## +## Information functions Informationsfunktionen +## +CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück +ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht +INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück +ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist +ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist +ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist +ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt +ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist +ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist +ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält +ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist +ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt +ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist +ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält +N = N ## Gibt den in eine Zahl umgewandelten Wert zurück +NA = NV ## Gibt den Fehlerwert #NV zurück +TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt + + +## +## Logical functions Logische Funktionen +## +AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind +FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück +IF = WENN ## Gibt einen logischen Test zum Ausführen an +IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben +NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um +OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist +TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück + + +## +## Lookup and reference functions Nachschlage- und Verweisfunktionen +## +ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück +AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück +CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus +COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück +COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück +HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück +HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird +INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen +INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird +LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix +MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix +OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück +ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück +ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück +RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt +TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück +VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben + + +## +## Math and trigonometry functions Mathematische und trigonometrische Funktionen +## +ABS = ABS ## Gibt den Absolutwert einer Zahl zurück +ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück +ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück +ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück +ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück +ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück +ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück +ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück +CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt +COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück +COS = COS ## Gibt den Kosinus einer Zahl zurück +COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück +DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um +EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf +EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl +FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück +FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück +FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab +GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück +INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab +LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück +LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück +LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück +LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück +MDETERM = MDET ## Gibt die Determinante einer Matrix zurück +MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück +MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück +MOD = REST ## Gibt den Rest einer Division zurück +MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück +MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück +ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf +PI = PI ## Gibt den Wert Pi zurück +POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück +PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente +QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück +RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um +RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück +RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück +ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um +ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen +ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab +ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf +SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück +SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück +SIN = SIN ## Gibt den Sinus einer Zahl zurück +SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück +SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück +SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück +SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück +SUM = SUMME ## Addiert die zugehörigen Argumente +SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen +SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt +SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück +SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück +SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück +SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück +SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück +TAN = TAN ## Gibt den Tangens einer Zahl zurück +TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück +TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück + + +## +## Statistical functions Statistische Funktionen +## +AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück +AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück +AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück +AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben +AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen +BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück +BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück +BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück +CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück +CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück +CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück +CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen +CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück +COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an +COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an +COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an +COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen +COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen +COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen +CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind +DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück +EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück +FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück +FINV = FINV ## Gibt Quantile der F-Verteilung zurück +FISHER = FISHER ## Gibt die Fisher-Transformation zurück +FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück +FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt +FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück +FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück +GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück +GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück +GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x) +GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück +GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben +HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück +HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück +INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück +KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück +LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück +LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück +LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück +LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück +LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück +MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück +MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten +MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück +MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück +MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten +MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück +NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück +NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück +NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück +NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück +NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück +PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück +PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück +PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück +PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen +POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück +PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück +QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück +RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt +RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück +SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück +SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück +SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück +STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück +STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe +STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält +STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit +STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält +STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück +TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück +TINV = TINV ## Gibt Quantile der t-Verteilung zurück +TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben +TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen +TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück +VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe +VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält +VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit +VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält +WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück +ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück + + +## +## Text functions Textfunktionen +## +ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text +BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um +CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück +CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text +CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück +CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement +DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um +EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind +FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) +FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) +FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen +JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text +LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück +LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück +LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück +LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück +LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um +MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück +MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück +PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge +PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um +REPLACE = ERSETZEN ## Ersetzt Zeichen in Text +REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text +REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben +RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück +RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück +SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) +SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) +SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten +T = T ## Wandelt die zugehörigen Argumente in Text um +TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um +TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text +UPPER = GROSS ## Wandelt Text in Großbuchstaben um +VALUE = WERT ## Wandelt ein Textargument in eine Zahl um diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config new file mode 100644 index 00000000..dfcc63b0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config @@ -0,0 +1,32 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +## +## (For future use) +## +currencySymbol = £ diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config new file mode 100644 index 00000000..0b11eb7a --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than € + + +## +## Excel Error Codes (For future use) +## +NULL = #¡NULO! +DIV0 = #¡DIV/0! +VALUE = #¡VALOR! +REF = #¡REF! +NAME = #¿NOMBRE? +NUM = #¡NÚM! +NA = #N/A diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions new file mode 100644 index 00000000..f6e6fd2b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funciones de complementos y automatización +## +GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica. + + +## +## Cube functions Funciones de cubo +## +CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización. +CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo. +CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro. +CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos. +CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel. +CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto. +CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo. + + +## +## Database functions Funciones de base de datos +## +DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos. +DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos. +DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos. +DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados. +DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos. +DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos. +DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados. +DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos. +DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos. +DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios. +DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos. +DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos. + + +## +## Date and time functions Funciones de fecha y hora +## +DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada. +DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie. +DAY = DIA ## Convierte un número de serie en un valor de día del mes. +DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días. +EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial. +EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado. +HOUR = HORA ## Convierte un número de serie en un valor de hora. +MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto. +MONTH = MES ## Convierte un número de serie en un valor de mes. +NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas. +NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales. +SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo. +TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada. +TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie. +TODAY = HOY ## Devuelve el número de serie correspondiente al día actual. +WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana. +WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año. +WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables. +YEAR = AÑO ## Convierte un número de serie en un valor de año. +YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final. + + +## +## Engineering functions Funciones de ingeniería +## +BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada. +BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x). +BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada. +BESSELY = BESSELY ## Devuelve la función Bessel Yn(x). +BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal. +BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal. +BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal. +COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo. +CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro. +DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario. +DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal. +DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal. +DELTA = DELTA ## Comprueba si dos valores son iguales. +ERF = FUN.ERROR ## Devuelve la función de error. +ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario. +GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral. +HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario. +HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal. +HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal. +IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo. +IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo. +IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes. +IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo. +IMCOS = IM.COS ## Devuelve el coseno de un número complejo. +IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos. +IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo. +IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo. +IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo. +IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo. +IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera. +IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos. +IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo. +IMSIN = IM.SENO ## Devuelve el seno de un número complejo. +IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo. +IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos. +IMSUM = IM.SUM ## Devuelve la suma de números complejos. +OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario. +OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal. +OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal. + + +## +## Financial functions Funciones financieras +## +ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos. +ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento. +AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización. +AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables. +COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación. +COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación. +COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón. +COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación. +COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento. +COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación. +CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos. +CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos. +DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo. +DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique. +DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil. +DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal. +DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria. +DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico. +EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva. +FV = VF ## Devuelve el valor futuro de una inversión. +FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto. +INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil. +IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado. +IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos. +ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión. +MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $. +MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes. +NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual. +NPER = NPER ## Devuelve el número de períodos de una inversión. +NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento. +ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar. +ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar. +ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar. +ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar. +PMT = PAGO ## Devuelve el pago periódico de una anualidad. +PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado. +PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico. +PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento. +PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento. +PV = VALACT ## Devuelve el valor actual de una inversión. +RATE = TASA ## Devuelve la tasa de interés por período de una anualidad. +RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido. +SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado. +SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado. +TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.) +TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.) +TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.) +VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución. +XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico. +XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico. +YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos. +YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.) +YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento. + + +## +## Information functions Funciones de información +## +CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda. +ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error. +INFO = INFO ## Devuelve información acerca del entorno operativo en uso. +ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco. +ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A. +ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error. +ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par. +ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico. +ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A. +ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto. +ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número. +ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar. +ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia. +ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto. +N = N ## Devuelve un valor convertido en un número. +NA = ND ## Devuelve el valor de error #N/A. +TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor. + + +## +## Logical functions Funciones lógicas +## +AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO. +FALSE = FALSO ## Devuelve el valor lógico FALSO. +IF = SI ## Especifica una prueba lógica que realizar. +IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula. +NOT = NO ## Invierte el valor lógico del argumento. +OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO. +TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO. + + +## +## Lookup and reference functions Funciones de búsqueda y referencia +## +ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo. +AREAS = AREAS ## Devuelve el número de áreas de una referencia. +CHOOSE = ELEGIR ## Elige un valor de una lista de valores. +COLUMN = COLUMNA ## Devuelve el número de columna de una referencia. +COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia. +HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada. +HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet. +INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz. +INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto. +LOOKUP = BUSCAR ## Busca valores de un vector o una matriz. +MATCH = COINCIDIR ## Busca valores de una referencia o matriz. +OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada. +ROW = FILA ## Devuelve el número de fila de una referencia. +ROWS = FILAS ## Devuelve el número de filas de una referencia. +RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).). +TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz. +VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda. + + +## +## Math and trigonometry functions Funciones matemáticas y trigonométricas +## +ABS = ABS ## Devuelve el valor absoluto de un número. +ACOS = ACOS ## Devuelve el arcocoseno de un número. +ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número. +ASIN = ASENO ## Devuelve el arcoseno de un número. +ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número. +ATAN = ATAN ## Devuelve la arcotangente de un número. +ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y". +ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número. +CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano. +COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos. +COS = COS ## Devuelve el coseno de un número. +COSH = COSH ## Devuelve el coseno hiperbólico de un número. +DEGREES = GRADOS ## Convierte radianes en grados. +EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo. +EXP = EXP ## Devuelve e elevado a la potencia de un número dado. +FACT = FACT ## Devuelve el factorial de un número. +FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número. +FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero. +GCD = M.C.D ## Devuelve el máximo común divisor. +INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo. +LCM = M.C.M ## Devuelve el mínimo común múltiplo. +LN = LN ## Devuelve el logaritmo natural (neperiano) de un número. +LOG = LOG ## Devuelve el logaritmo de un número en una base especificada. +LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número. +MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz. +MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz. +MMULT = MMULT ## Devuelve el producto de matriz de dos matrices. +MOD = RESIDUO ## Devuelve el resto de la división. +MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado. +MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números. +ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo. +PI = PI ## Devuelve el valor de pi. +POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia. +PRODUCT = PRODUCTO ## Multiplica sus argumentos. +QUOTIENT = COCIENTE ## Devuelve la parte entera de una división. +RADIANS = RADIANES ## Convierte grados en radianes. +RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1. +RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique. +ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto. +ROUND = REDONDEAR ## Redondea un número al número de decimales especificado. +ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero. +ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero. +SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula. +SIGN = SIGNO ## Devuelve el signo de un número. +SIN = SENO ## Devuelve el seno de un ángulo determinado. +SINH = SENOH ## Devuelve el seno hiperbólico de un número. +SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número. +SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi). +SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos. +SUM = SUMA ## Suma sus argumentos. +SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados. +SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios. +SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz. +SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos. +SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices. +SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices. +SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices. +TAN = TAN ## Devuelve la tangente de un número. +TANH = TANH ## Devuelve la tangente hiperbólica de un número. +TRUNC = TRUNCAR ## Trunca un número a un entero. + + +## +## Statistical functions Funciones estadísticas +## +AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos. +AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos. +AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos. +AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados. +AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios. +BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa. +BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada. +BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial. +CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. +CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. +CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia. +CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población. +CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos. +COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos. +COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos. +COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango. +COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado. +COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios. +COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos. +CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio. +DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones. +EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial. +FDIST = DISTR.F ## Devuelve la distribución de probabilidad F. +FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F. +FISHER = FISHER ## Devuelve la transformación Fisher. +FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher. +FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal. +FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical. +FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F. +GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma. +GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa. +GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x). +GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica. +GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial. +HARMEAN = MEDIA.ARMO ## Devuelve la media armónica. +HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica. +INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal. +KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos. +LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos. +LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal. +LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial. +LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal. +LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa. +MAX = MAX ## Devuelve el valor máximo de una lista de argumentos. +MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos. +MEDIAN = MEDIANA ## Devuelve la mediana de los números dados. +MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos. +MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos. +MODE = MODA ## Devuelve el valor más común de un conjunto de datos. +NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa. +NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa. +NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa. +NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa. +NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa. +PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson. +PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango. +PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos. +PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos. +POISSON = POISSON ## Devuelve la distribución de Poisson. +PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites. +QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos. +RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números. +RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson. +SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución. +SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal. +SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos. +STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado. +STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra. +STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos. +STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población. +STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos. +STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión. +TDIST = DISTR.T ## Devuelve la distribución de t de Student. +TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student. +TREND = TENDENCIA ## Devuelve valores en una tendencia lineal. +TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos. +TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student. +VAR = VAR ## Calcula la varianza en función de una muestra. +VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos. +VARP = VARP ## Calcula la varianza en función de toda la población. +VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos. +WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull. +ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z. + + +## +## Text functions Funciones de texto +## +ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte). +BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht). +CHAR = CARACTER ## Devuelve el carácter especificado por el número de código. +CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles. +CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto. +CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo. +DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar). +EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos. +FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). +FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). +FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales. +JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes). +LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto. +LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto. +LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto. +LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto. +LOWER = MINUSC ## Pone el texto en minúsculas. +MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. +MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. +PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto. +PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto. +REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto. +REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto. +REPT = REPETIR ## Repite el texto un número determinado de veces. +RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto. +RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto. +SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). +SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). +SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto. +T = T ## Convierte sus argumentos a texto. +TEXT = TEXTO ## Da formato a un número y lo convierte en texto. +TRIM = ESPACIOS ## Quita los espacios del texto. +UPPER = MAYUSC ## Pone el texto en mayúsculas. +VALUE = VALOR ## Convierte un argumento de texto en un número. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config new file mode 100644 index 00000000..380f3979 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = $ # Symbol not known, should it be a € (Euro)? + + +## +## Excel Error Codes (For future use) +## +NULL = #TYHJÄ! +DIV0 = #JAKO/0! +VALUE = #ARVO! +REF = #VIITTAUS! +NAME = #NIMI? +NUM = #LUKU! +NA = #PUUTTUU diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions new file mode 100644 index 00000000..bf60bec0 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot +## +GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja. + + +## +## Cube functions Kuutiofunktiot +## +CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä. +CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa. +CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden. +CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa. +CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille. +CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän. +CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta. + + +## +## Database functions Tietokantafunktiot +## +DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon. +DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän. +DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän. +DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta. +DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta. +DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta. +DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot. +DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella. +DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella. +DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen. +DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella. +DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella. + + +## +## Date and time functions Päivämäärä- ja aikafunktiot +## +DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun. +DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi. +DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi. +DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta. +EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin. +EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin. +HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi. +MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi. +MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi. +NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän. +NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron. +SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi. +TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun. +TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi. +TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun. +WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi. +WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna. +WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin. +YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi. +YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta. + + +## +## Engineering functions Tekniset funktiot +## +BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x). +BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x). +BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x). +BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x). +BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi. +BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi. +BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi. +COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi. +CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi. +DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi. +DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi. +DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi. +DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria. +ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion. +ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion. +GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo. +HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi. +HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi. +HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi. +IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen). +IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen. +IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma. +IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun. +IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin. +IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän. +IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin. +IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin. +IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin. +IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin. +IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun. +IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon. +IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen. +IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin. +IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren. +IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen. +IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan. +OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi. +OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi. +OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi. + + +## +## Financial functions Rahoitusfunktiot +## +ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin. +ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä. +AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä. +AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston. +COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän. +COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu. +COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän. +COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän. +COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän. +COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän. +CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron. +CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen. +DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. +DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan. +DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron. +DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi. +DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi. +DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti. +EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron. +FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon. +FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti. +INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille. +IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron. +IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle. +ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla. +MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa. +MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen. +NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron. +NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän. +NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella. +ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton. +ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton. +ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton. +ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton. +PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän. +PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen. +PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin. +PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden. +PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä. +PV = NA ## Palauttaa sijoituksen nykyarvon. +RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan. +RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle. +SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta. +SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla. +TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona. +TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden. +TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton. +VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. +XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä. +XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen. +YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin. +YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton. +YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton. + + +## +## Information functions Erikoisfunktiot +## +CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä. +ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun. +INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä. +ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä. +ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!. +ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo. +ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen. +ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo. +ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!. +ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti. +ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku. +ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton. +ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus. +ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti. +N = N ## Palauttaa arvon luvuksi muunnettuna. +NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!. +TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin. + + +## +## Logical functions Loogiset funktiot +## +AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI. +FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI. +IF = JOS ## Määrittää suoritettavan loogisen testin. +IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen. +NOT = EI ## Kääntää argumentin loogisen arvon. +OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI. +TRUE = TOSI ## Palauttaa totuusarvon TOSI. + + +## +## Lookup and reference functions Haku- ja viitefunktiot +## +ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä. +AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän. +CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta. +COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron. +COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän. +HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon. +HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston. +INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan. +INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen. +LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista. +MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista. +OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän. +ROW = RIVI ## Palauttaa viittauksen rivinumeron. +ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän. +RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja. +TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin. +VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon. + + +## +## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot +## +ABS = ITSEISARVO ## Palauttaa luvun itseisarvon. +ACOS = ACOS ## Palauttaa luvun arkuskosinin. +ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin. +ASIN = ASIN ## Palauttaa luvun arkussinin. +ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin. +ATAN = ATAN ## Palauttaa luvun arkustangentin. +ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella. +ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin. +CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen. +COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle. +COS = COS ## Palauttaa luvun kosinin. +COSH = COSH ## Palauttaa luvun hyperbolisen kosinin. +DEGREES = ASTEET ## Muuntaa radiaanit asteiksi. +EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun. +EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin. +FACT = KERTOMA ## Palauttaa luvun kertoman. +FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman. +FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). +GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän. +INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun. +LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän. +LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin. +LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua. +LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin. +MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin. +MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin. +MMULT = MKERRO ## Palauttaa kahden matriisin tulon. +MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen. +MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen. +MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin. +ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun. +PI = PII ## Palauttaa piin arvon. +POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin. +PRODUCT = TULO ## Kertoo annetut argumentit. +QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan. +RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi. +RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1. +RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä. +ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi. +ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja. +ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). +ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta). +SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon. +SIGN = ETUMERKKI ## Palauttaa luvun etumerkin. +SIN = SIN ## Palauttaa annetun kulman sinin. +SINH = SINH ## Palauttaa luvun hyperbolisen sinin. +SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren. +SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren. +SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman. +SUM = SUMMA ## Laskee yhteen annetut argumentit. +SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan. +SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut. +SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan. +SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan. +SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen. +SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan. +SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman. +TAN = TAN ## Palauttaa luvun tangentin. +TANH = TANH ## Palauttaa luvun hyperbolisen tangentin. +TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi. + + +## +## Statistical functions Tilastolliset funktiot +## +AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon. +AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon. +AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon. +AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot. +AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja. +BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon. +BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon. +BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden. +CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden. +CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon. +CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen. +CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle. +CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen. +COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän. +COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän. +COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän. +COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja. +COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja. +COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista. +CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo. +DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman. +EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman. +FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman. +FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion. +FISHER = FISHER ## Palauttaa Fisher-muunnoksen. +FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen. +FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon. +FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina. +FTEST = FTESTI ## Palauttaa F-testin tuloksen. +GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman. +GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion. +GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x). +GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon. +GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon. +HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon. +HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman. +INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen. +KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden. +LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon. +LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit. +LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit. +LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion. +LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion. +MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta. +MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon. +MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin. +MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta. +MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon. +MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon. +NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman. +NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion. +NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion. +NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion. +NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon. +PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen. +PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen. +PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun. +PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle. +POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman. +PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä. +QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen. +RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa. +RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön. +SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden. +SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen. +SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon. +STANDARDIZE = NORMITA ## Palauttaa normitetun arvon. +STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella. +STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. +STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella. +STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. +STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen. +TDIST = TJAKAUMA ## Palauttaa t-jakautuman. +TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman. +TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja. +TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon. +TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden. +VAR = VAR ## Arvioi populaation varianssia otoksen perusteella. +VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. +VARP = VARP ## Laskee varianssin koko populaation perusteella. +VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. +WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman. +ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon. + + +## +## Text functions Tekstifunktiot +## +ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi. +BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä. +CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin. +CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit. +CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin. +CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi. +DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä. +EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset. +FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). +FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). +FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja. +JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi. +LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit. +LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit. +LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän. +LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän. +LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi. +MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. +MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. +PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta. +PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi. +REPLACE = KORVAA ## Korvaa tekstissä olevat merkit. +REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit. +REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja. +RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit. +RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit. +SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). +SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). +SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella. +T = T ## Muuntaa argumentit tekstiksi. +TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi. +TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä. +UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi. +VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config new file mode 100644 index 00000000..368b3c3c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NUL! +DIV0 = #DIV/0! +VALUE = #VALEUR! +REF = #REF! +NAME = #NOM? +NUM = #NOMBRE! +NA = #N/A diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions new file mode 100644 index 00000000..e85dba5b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Fonctions de complément et d’automatisation +## +GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique. + + +## +## Cube functions Fonctions Cube +## +CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise. +CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube. +CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre. +CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants. +CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel. +CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu. +CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube. + + +## +## Database functions Fonctions de base de données +## +DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées. +DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres. +DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données. +DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés. +DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées. +DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées. +DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés. +DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées. +DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées. +DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères. +DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées. +DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées. + + +## +## Date and time functions Fonctions de date et d’heure +## +DATE = DATE ## Renvoie le numéro de série d’une date précise. +DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série. +DAY = JOUR ## Convertit un numéro de série en jour du mois. +DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours. +EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué. +EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué. +HOUR = HEURE ## Convertit un numéro de série en heure. +MINUTE = MINUTE ## Convertit un numéro de série en minute. +MONTH = MOIS ## Convertit un numéro de série en mois. +NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates. +NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour. +SECOND = SECONDE ## Convertit un numéro de série en seconde. +TIME = TEMPS ## Renvoie le numéro de série d’une heure précise. +TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série. +TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour. +WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine. +WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année. +WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés. +YEAR = ANNEE ## Convertit un numéro de série en année. +YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin. + + +## +## Engineering functions Fonctions d’ingénierie +## +BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x). +BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x). +BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x). +BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x). +BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal. +BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal. +BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal. +COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe. +CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre. +DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire. +DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal. +DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal. +DELTA = DELTA ## Teste l’égalité de deux nombres. +ERF = ERF ## Renvoie la valeur de la fonction d’erreur. +ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire. +GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil. +HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire. +HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal. +HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal. +IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe. +IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe. +IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians. +IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe. +IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe. +IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes. +IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe. +IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe. +IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe. +IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe. +IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière. +IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes. +IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe. +IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe. +IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe. +IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes. +IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes. +OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire. +OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal. +OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal. + + +## +## Financial functions Fonctions financières +## +ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement. +ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance. +AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement. +AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée. +COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation. +COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation. +COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation. +COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement. +COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance. +COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement. +CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes. +CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes. +DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe. +DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier. +DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction. +DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal. +DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction. +DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement. +EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif. +FV = VC ## Renvoie la valeur future d’un investissement. +FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites. +INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi. +IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée. +IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries. +ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée. +MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros. +MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents. +NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel. +NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt. +NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte. +ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. +ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière. +ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. +ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière. +PMT = VPM ## Calcule le paiement périodique d’un investissement donné. +PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement. +PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros. +PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros. +PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance. +PV = PV ## Calcule la valeur actuelle d’un investissement. +RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité. +RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce. +SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée. +SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante). +TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor. +TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros. +TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor. +VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe. +XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques. +XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques. +YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement. +YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor). +YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance. + + +## +## Information functions Fonctions d’information +## +CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule. +ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur. +INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel. +ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide. +ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A. +ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur. +ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair. +ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique. +ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A. +ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte. +ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre. +ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair. +ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence. +ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte. +N = N ## Renvoie une valeur convertie en nombre. +NA = NA ## Renvoie la valeur d’erreur #N/A. +TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur. + + +## +## Logical functions Fonctions logiques +## +AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI. +FALSE = FAUX ## Renvoie la valeur logique FAUX. +IF = SI ## Spécifie un test logique à effectuer. +IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule. +NOT = NON ## Inverse la logique de cet argument. +OR = OU ## Renvoie VRAI si un des arguments est VRAI. +TRUE = VRAI ## Renvoie la valeur logique VRAI. + + +## +## Lookup and reference functions Fonctions de recherche et de référence +## +ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul. +AREAS = ZONES ## Renvoie le nombre de zones dans une référence. +CHOOSE = CHOISIR ## Choisit une valeur dans une liste. +COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence. +COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence. +HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée. +HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet. +INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice. +INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte. +LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice. +MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice. +OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée. +ROW = LIGNE ## Renvoie le numéro de ligne d’une référence. +ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence. +RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).). +TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice. +VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule. + + +## +## Math and trigonometry functions Fonctions mathématiques et trigonométriques +## +ABS = ABS ## Renvoie la valeur absolue d’un nombre. +ACOS = ACOS ## Renvoie l’arccosinus d’un nombre. +ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre. +ASIN = ASIN ## Renvoie l’arcsinus d’un nombre. +ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre. +ATAN = ATAN ## Renvoie l’arctangente d’un nombre. +ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y. +ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre. +CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro. +COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets. +COS = COS ## Renvoie le cosinus d’un nombre. +COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre. +DEGREES = DEGRES ## Convertit des radians en degrés. +EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro. +EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné. +FACT = FACT ## Renvoie la factorielle d’un nombre. +FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre. +FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro). +GCD = PGCD ## Renvoie le plus grand commun diviseur. +INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur. +LCM = PPCM ## Renvoie le plus petit commun multiple. +LN = LN ## Renvoie le logarithme népérien d’un nombre. +LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée. +LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre. +MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice. +MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice. +MMULT = PRODUITMAT ## Renvoie le produit de deux matrices. +MOD = MOD ## Renvoie le reste d’une division. +MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié. +MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres. +ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro. +PI = PI ## Renvoie la valeur de pi. +POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance. +PRODUCT = PRODUIT ## Multiplie ses arguments. +QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division. +RADIANS = RADIANS ## Convertit des degrés en radians. +RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1. +RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez. +ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte. +ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué. +ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro). +ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro. +SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante : +SIGN = SIGNE ## Renvoie le signe d’un nombre. +SIN = SIN ## Renvoie le sinus d’un angle donné. +SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre. +SQRT = RACINE ## Renvoie la racine carrée d’un nombre. +SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi). +SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données. +SUM = SOMME ## Calcule la somme de ses arguments. +SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné. +SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères. +SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits. +SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments. +SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices. +SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices. +SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices. +TAN = TAN ## Renvoie la tangente d’un nombre. +TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre. +TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre. + + +## +## Statistical functions Fonctions statistiques +## +AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données. +AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments. +AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus. +AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés. +AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères. +BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée. +BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée. +BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale. +CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux. +CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux. +CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance. +CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population. +CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données. +COUNT = NB ## Détermine les nombres compris dans la liste des arguments. +COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments. +COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage. +COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage. +COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères. +COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations. +CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère. +DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts. +EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle. +FDIST = LOI.F ## Renvoie la distribution de probabilité F. +FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F. +FISHER = FISHER ## Renvoie la transformation de Fisher. +FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher. +FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire. +FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale. +FTEST = TEST.F ## Renvoie le résultat d’un test F. +GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma. +GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma. +GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x) +GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique. +GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle. +HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique. +HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique. +INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire. +KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données. +LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données. +LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire. +LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle. +LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale. +LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale. +MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments. +MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus. +MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés. +MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments. +MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus. +MODE = MODE ## Renvoie la valeur la plus courante d’une série de données. +NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative. +NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale. +NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard. +NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard. +NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard. +PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson. +PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage. +PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données. +PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets. +POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson. +PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites. +QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données. +RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste. +RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire. +SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution. +SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire. +SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données. +STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite. +STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population. +STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus. +STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière. +STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus. +STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression. +TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student. +TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student. +TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire. +TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données. +TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student. +VAR = VAR ## Calcule la variance sur la base d’un échantillon. +VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses. +VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population. +VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus. +WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull. +ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z. + + +## +## Text functions Fonctions de texte +## +ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet). +BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht). +CHAR = CAR ## Renvoie le caractère spécifié par le code numérique. +CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte. +CODE = CODE ## Renvoie le numéro de code du premier caractère du texte. +CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul. +DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro). +EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques. +FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse. +FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse. +FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié. +JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets). +LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. +LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. +LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte. +LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte. +LOWER = MINUSCULE ## Convertit le texte en minuscules. +MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. +MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. +PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte. +PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle. +REPLACE = REMPLACER ## Remplace des caractères dans un texte. +REPLACEB = REMPLACERB ## Remplace des caractères dans un texte. +REPT = REPT ## Répète un texte un certain nombre de fois. +RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. +RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. +SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse). +SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse). +SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau. +T = T ## Convertit ses arguments en texte. +TEXT = TEXTE ## Convertit un nombre au format texte. +TRIM = SUPPRESPACE ## Supprime les espaces du texte. +UPPER = MAJUSCULE ## Convertit le texte en majuscules. +VALUE = CNUM ## Convertit un argument textuel en nombre diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config new file mode 100644 index 00000000..e04151cb --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = Ft + + +## +## Excel Error Codes (For future use) +## +NULL = #NULLA! +DIV0 = #ZÉRÓOSZTÓ! +VALUE = #ÉRTÉK! +REF = #HIV! +NAME = #NÉV? +NUM = #SZÁM! +NA = #HIÁNYZIK diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions new file mode 100644 index 00000000..77cae928 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Bővítmények és automatizálási függvények +## +GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható. + + +## +## Cube functions Kockafüggvények +## +CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók. +CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord. +CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság. +CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót. +CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak. +CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül. +CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül. + + +## +## Database functions Adatbázis-kezelő függvények +## +DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki. +DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat. +DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat. +DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek. +DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül. +DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül. +DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja. +DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást. +DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást. +DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat. +DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre. +DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet. + + +## +## Date and time functions Dátumfüggvények +## +DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül. +DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át. +DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít. +DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján. +EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül. +EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül. +HOUR = ÓRA ## Időértéket órákká alakít. +MINUTE = PERC ## Időértéket percekké alakít. +MONTH = HÓNAP ## Időértéket hónapokká alakít. +NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg. +NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül. +SECOND = MPERC ## Időértéket másodpercekké alakít át. +TIME = IDŐ ## Adott időpont időértékét adja meg. +TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át. +TODAY = MA ## A napi dátum dátumértékét adja eredményül. +WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át. +WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik. +WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül. +YEAR = ÉV ## Sorszámot évvé alakít át. +YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg. + + +## +## Engineering functions Mérnöki függvények +## +BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül. +BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül. +BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül. +BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül. +BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át. +BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át. +BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át. +COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez. +CONVERT = CONVERT ## Mértékegységeket vált át. +DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át. +DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át. +DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át. +DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e. +ERF = ERF ## A hibafüggvény értékét adja eredményül. +ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül. +GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél. +HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át. +HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át. +HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át. +IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül. +IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül. +IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül. +IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül. +IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül. +IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül. +IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül. +IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül. +IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül. +IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül. +IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül. +IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül. +IMREAL = IMREAL ## Komplex szám valós részét adja eredményül. +IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül. +IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül. +IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül. +IMSUM = IMSUM ## Komplex számok összegét adja eredményül. +OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át. +OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át. +OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át. + + +## +## Financial functions Pénzügyi függvények +## +ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül. +ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül. +AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan. +AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg. +COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza. +COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban. +COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg. +COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül. +COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül. +COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül. +CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül. +CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül. +DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával. +DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával. +DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül. +DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át. +DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át. +DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül. +EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül. +FV = JBÉ ## Befektetés jövőbeli értékét számítja ki. +FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül. +INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül. +IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. +IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz. +ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki. +MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül. +MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett. +NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül. +NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg. +NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett. +ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül. +ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül. +ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül. +ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül. +PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki. +PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. +PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül. +PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül. +PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül. +PV = MÉ ## Befektetés jelenlegi értékét számítja ki. +RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki. +RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül. +SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva. +SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján. +TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül. +TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül. +TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül. +VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával. +XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül. +XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül. +YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül. +YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül. +YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül. + + +## +## Information functions Információs függvények +## +CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül. +ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül. +INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást. +ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres. +ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével. +ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték. +ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám. +ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték. +ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték. +ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg. +ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám. +ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám. +ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás. +ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg. +N = N ## Argumentumának értékét számmá alakítja. +NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték. +TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül. + + +## +## Logical functions Logikai függvények +## +AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ. +FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül. +IF = HA ## Logikai vizsgálatot hajt végre. +IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül. +NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül. +OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ. +TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül. + + +## +## Lookup and reference functions Keresési és hivatkozási függvények +## +ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül. +AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül. +CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet. +COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül. +COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül. +HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza. +HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre. +INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza. +INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül. +LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket. +MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres. +OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg. +ROW = SOR ## Egy hivatkozás sorának számát adja meg. +ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg. +RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból. +TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül. +VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül. + + +## +## Math and trigonometry functions Matematikai és trigonometrikus függvények +## +ABS = ABS ## Egy szám abszolút értékét adja eredményül. +ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki. +ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki. +ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki. +ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki. +ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki. +ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket. +ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki. +CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít. +COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki. +COS = COS ## Egy szám koszinuszát számítja ki. +COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki. +DEGREES = FOK ## Radiánt fokká alakít át. +EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít. +EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül. +FACT = FAKT ## Egy szám faktoriálisát számítja ki. +FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül. +FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít. +GCD = GCD ## A legnagyobb közös osztót adja eredményül. +INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre. +LCM = LCM ## A legkisebb közös többszöröst adja eredményül. +LN = LN ## Egy szám természetes logaritmusát számítja ki. +LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki. +LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki. +MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki. +MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül. +MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg. +MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül. +MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül. +MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül. +ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít. +PI = PI ## A pi matematikai állandót adja vissza. +POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki. +PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki. +QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül. +RADIANS = RADIÁN ## Fokot radiánná alakít át. +RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül. +RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő. +ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül. +ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít. +ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít. +ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít. +SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül. +SIGN = ELŐJEL ## Egy szám előjelét adja meg. +SIN = SIN ## Egy szög szinuszát számítja ki. +SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki. +SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki. +SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül. +SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül. +SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat. +SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze. +SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül. +SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki. +SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki. +SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi. +SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi. +SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki. +TAN = TAN ## Egy szám tangensét számítja ki. +TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki. +TRUNC = CSONK ## Egy számot egésszé csonkít. + + +## +## Statistical functions Statisztikai függvények +## +AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki. +AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki. +AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket). +AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül. +AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül. +BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki. +BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét. +BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki. +CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki. +CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki. +CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre. +CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül. +CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki. +COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található. +COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található. +COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat. +COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek. +COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek. +COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki. +CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél. +DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki. +EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki. +FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki. +FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki. +FISHER = FISHER ## Fisher-transzformációt hajt végre. +FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre. +FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül. +FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül. +FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül. +GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki. +GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki. +GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki. +GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést. +HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki. +HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki. +INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg. +KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki. +LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül. +LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg. +LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg. +LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki. +LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki. +MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg. +MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket). +MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki. +MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg. +MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket. +MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot. +NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki. +NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki. +NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki. +NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki. +PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül. +PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki. +PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki. +POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki. +PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek. +QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki. +RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban. +RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét. +SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg. +SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki. +SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg. +STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül. +STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását. +STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket). +STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását. +STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket). +STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki. +TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki. +TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki. +TREND = TREND ## Lineáris trend értékeit számítja ki. +TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki. +TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki. +VAR = VAR ## Minta alapján becslést ad a varianciára. +VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket). +VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki. +VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket). +WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki. +ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki. + + +## +## Text functions Szövegműveletekhez használható függvények +## +ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja. +BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával. +CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül. +CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert. +CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül. +CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze. +DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át. +EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e. +FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). +FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). +FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve. +JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja. +LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül. +LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül. +LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül. +LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül. +LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át. +MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. +MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. +PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza. +PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli. +REPLACE = CSERE ## A szövegen belül karaktereket cserél. +REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél. +REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt. +RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül. +RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül. +SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). +SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). +SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél. +T = T ## Argumentumát szöveggé alakítja át. +TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé. +TRIM = TRIM ## A szövegből eltávolítja a szóközöket. +UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át. +VALUE = ÉRTÉK ## Szöveget számmá alakít át. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config new file mode 100644 index 00000000..94499fe2 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULLO! +DIV0 = #DIV/0! +VALUE = #VALORE! +REF = #RIF! +NAME = #NOME? +NUM = #NUM! +NA = #N/D diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions new file mode 100644 index 00000000..033b9696 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi +## +GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot + + +## +## Cube functions Funzioni cubo +## +CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione. +CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo. +CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro. +CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti. +CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel. +CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme. +CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo. + + +## +## Database functions Funzioni di database +## +DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate +DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri +DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database +DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati +DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database +DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate +DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database +DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate +DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate +DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri +DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate +DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate + + +## +## Date and time functions Funzioni data e ora +## +DATE = DATA ## Restituisce il numero seriale di una determinata data +DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale +DAY = GIORNO ## Converte un numero seriale in un giorno del mese +DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni +EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio +EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi +HOUR = ORA ## Converte un numero seriale in un'ora +MINUTE = MINUTO ## Converte un numero seriale in un minuto +MONTH = MESE ## Converte un numero seriale in un mese +NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date +NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente +SECOND = SECONDO ## Converte un numero seriale in un secondo +TIME = ORARIO ## Restituisce il numero seriale di una determinata ora +TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale +TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna +WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana +WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno +WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi +YEAR = ANNO ## Converte un numero seriale in un anno +YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale + + +## +## Engineering functions Funzioni ingegneristiche +## +BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x) +BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x) +BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x) +BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x) +BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale +BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale +BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale +COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi +CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro +DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario +DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale +DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale +DELTA = DELTA ## Verifica se due valori sono uguali +ERF = FUNZ.ERRORE ## Restituisce la funzione di errore +ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare +GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia +HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario +HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale +HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale +IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso +IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso +IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti +IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso +IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso +IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi +IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso +IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso +IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso +IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso +IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera +IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29 +IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso +IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso +IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso +IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi +IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi +OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario +OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale +OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale + + +## +## Financial functions Funzioni finanziarie +## +ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici +ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza +AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento +AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile +COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione +COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione +COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva +COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione +COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza +COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione +CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi +CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi +DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti +DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati +DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo +DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale +DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione +DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico +EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo +FV = VAL.FUT ## Restituisce il valore futuro di un investimento +FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti +INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito +IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico +IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa +ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico +MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100 +MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti +NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale +NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento +NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto +ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare +ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare +ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare +ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare +PMT = RATA ## Restituisce il pagamento periodico di una rendita annua +PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo +PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici +PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100 +PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza +PV = VA ## Restituisce il valore attuale di un investimento +RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità +RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito +SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo +SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato +TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro +TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100 +TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro +VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui +XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa +XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici +YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici +YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro +YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza + + +## +## Information functions Funzioni relative alle informazioni +## +CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella +ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore +INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente +ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto +ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D +ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi +ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari +ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico +ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D +ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo +ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero +ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari +ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento +ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo +N = NUM ## Restituisce un valore convertito in numero +NA = NON.DISP ## Restituisce il valore di errore #N/D +TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore + + +## +## Logical functions Funzioni logiche +## +AND = E ## Restituisce VERO se tutti gli argomenti sono VERO +FALSE = FALSO ## Restituisce il valore logico FALSO +IF = SE ## Specifica un test logico da eseguire +IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula +NOT = NON ## Inverte la logica degli argomenti +OR = O ## Restituisce VERO se un argomento qualsiasi è VERO +TRUE = VERO ## Restituisce il valore logico VERO + + +## +## Lookup and reference functions Funzioni di ricerca e di riferimento +## +ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro +AREAS = AREE ## Restituisce il numero di aree in un riferimento +CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori +COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento +COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento +HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata +HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet +INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice +INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo +LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice +MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice +OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato +ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento +ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento +RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).) +TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice +VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella + + +## +## Math and trigonometry functions Funzioni matematiche e trigonometriche +## +ABS = ASS ## Restituisce il valore assoluto di un numero. +ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero +ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero +ASIN = ARCSEN ## Restituisce l'arcoseno di un numero +ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero +ATAN = ARCTAN ## Restituisce l'arcotangente di un numero +ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate +ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero +CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso +COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi +COS = COS ## Restituisce il coseno dell'angolo specificato +COSH = COSH ## Restituisce il coseno iperbolico di un numero +DEGREES = GRADI ## Converte i radianti in gradi +EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari +EXP = ESP ## Restituisce il numero e elevato alla potenza di num +FACT = FATTORIALE ## Restituisce il fattoriale di un numero +FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero +FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero +GCD = MCD ## Restituisce il massimo comune divisore +INT = INT ## Arrotonda un numero per difetto al numero intero più vicino +LCM = MCM ## Restituisce il minimo comune multiplo +LN = LN ## Restituisce il logaritmo naturale di un numero +LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base +LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero +MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice +MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice +MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici +MOD = RESTO ## Restituisce il resto della divisione +MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato +MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri +ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari +PI = PI.GRECO ## Restituisce il valore di pi greco +POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza +PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti +QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione +RADIANS = RADIANTI ## Converte i gradi in radianti +RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1 +RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati +ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo +ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato +ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto +ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso +SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula +SIGN = SEGNO ## Restituisce il segno di un numero +SIN = SEN ## Restituisce il seno di un dato angolo +SINH = SENH ## Restituisce il seno iperbolico di un numero +SQRT = RADQ ## Restituisce una radice quadrata +SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco) +SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database +SUM = SOMMA ## Somma i suoi argomenti +SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio +SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri +SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice +SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti +SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici +SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici +SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici +TAN = TAN ## Restituisce la tangente di un numero +TANH = TANH ## Restituisce la tangente iperbolica di un numero +TRUNC = TRONCA ## Tronca la parte decimale di un numero + + +## +## Statistical functions Funzioni statistiche +## +AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media +AVERAGE = MEDIA ## Restituisce la media degli argomenti +AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici +AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio +AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri +BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta +BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata +BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale +CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato +CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato +CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza +CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione +CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati +COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti +COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti +COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo +COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati +COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri. +COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate +CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio +DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni +EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale +FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F +FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F +FISHER = FISHER ## Restituisce la trasformazione di Fisher +FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher +FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare +FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale +FTEST = TEST.F ## Restituisce il risultato di un test F +GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma +GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma +GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x) +GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica +GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale +HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica +HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica +INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare +KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati +LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati +LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare +LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale +LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale +LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa +MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti +MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici +MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati +MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti +MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici +MODE = MODA ## Restituisce il valore più comune in un insieme di dati +NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa +NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale +NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard +NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard +NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale +PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson +PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo +PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale +PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti +POISSON = POISSON ## Restituisce la distribuzione di Poisson +PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti +QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati +RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri +RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson +SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione +SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare +SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati +STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato +STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione +STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici +STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione +STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici +STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione +TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student +TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student +TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare +TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati +TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student +VAR = VAR ## Stima la varianza sulla base di un campione +VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici +VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione +VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici +WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull +ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z + + +## +## Text functions Funzioni di testo +## +ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte +BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht) +CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice +CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare +CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo +CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo +DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro) +EXACT = IDENTICO ## Verifica se due valori di testo sono uguali +FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) +FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) +FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali +JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio. +LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo +LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo +LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo +LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo +LOWER = MINUSC ## Converte il testo in lettere minuscole +MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata +MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata +PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo. +PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo +REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo +REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo +REPT = RIPETI ## Ripete un testo per un dato numero di volte +RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo +RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo +SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) +SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) +SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa +T = T ## Converte gli argomenti in testo +TEXT = TESTO ## Formatta un numero e lo converte in testo +TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo +UPPER = MAIUSC ## Converte il testo in lettere maiuscole +VALUE = VALORE ## Converte un argomento di testo in numero diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config new file mode 100644 index 00000000..00c1b0ff --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #LEEG! +DIV0 = #DEEL/0! +VALUE = #WAARDE! +REF = #VERW! +NAME = #NAAM? +NUM = #GETAL! +NA = #N/B diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions new file mode 100644 index 00000000..63800086 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen +## +GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat + + +## +## Cube functions Kubusfuncties +## +CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken +CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is +CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid +CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten +CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel +CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set +CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus + + +## +## Database functions Databasefuncties +## +DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens +DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database +DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database +DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database +DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens +DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens +DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database +DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens +DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens +DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria +DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens +DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens + + +## +## Date and time functions Datum- en tijdfuncties +## +DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum +DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal +DAY = DAG ## Converteert een serieel getal naar een dag van de maand +DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen +EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt +EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden +HOUR = UUR ## Converteert een serieel getal naar uren +MINUTE = MINUUT ## Converteert een serieel naar getal minuten +MONTH = MAAND ## Converteert een serieel getal naar een maand +NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums +NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd +SECOND = SECONDE ## Converteert een serieel getal naar seconden +TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip +TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal +TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum +WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag +WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer +WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen +YEAR = JAAR ## Converteert een serieel getal naar een jaar +YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum + + +## +## Engineering functions Technische functies +## +BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x) +BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x) +BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x) +BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x) +BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal +BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal +BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal +COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal +CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid +DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal +DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal +DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal +DELTA = DELTA ## Test of twee waarden gelijk zijn +ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie +ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie +GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde +HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal +HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal +HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal +IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal +IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal +IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen +IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal +IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal +IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen +IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal +IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal +IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal +IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal +IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal +IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen +IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal +IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal +IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal +IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen +IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen +OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal +OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal +OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal + + +## +## Financial functions Financiële functies +## +ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd +AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen +AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode +COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum +COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt +COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum +COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum +COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum +COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum +CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd +CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald +DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode +DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft +DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier +DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal +DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk +DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen +EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage +FV = TW ## Geeft als resultaat de toekomstige waarde van een investering +FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages +INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier +IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn +IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows +ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering +MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt +MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten +NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage +NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering +NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage +ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn +ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn +ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn +ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn +PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit +PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn +PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier +PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum +PV = HW ## Geeft als resultaat de huidige waarde van een investering +RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit +RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier +SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn +SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode +TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties +TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier +TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier +VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode +XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows +XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows +YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier +YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum + + +## +## Information functions Informatiefuncties +## +CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel +ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel +INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving +ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is +ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B +ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is +ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is +ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is +ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is +ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is +ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is +ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is +ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is +ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is +N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal +NA = NB ## Geeft als resultaat de foutwaarde #N/B +TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft + + +## +## Logical functions Logische functies +## +AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn +FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR +IF = ALS ## Geeft een logische test aan +IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd +NOT = NIET ## Keert de logische waarde van het argument om +OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is +TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR + + +## +## Lookup and reference functions Zoek- en verwijzingsfuncties +## +ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad +AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing +CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden +COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing +COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing +HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel +HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet +INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix +INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde +LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix +MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix +OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing +ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing +ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing +RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt +TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix +VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel + + +## +## Math and trigonometry functions Wiskundige en trigonometrische functies +## +ABS = ABS ## Geeft als resultaat de absolute waarde van een getal +ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal +ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal +ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal +ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal +ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal +ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten +ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal +CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud +COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten +COS = COS ## Geeft als resultaat de cosinus van een getal +COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal +DEGREES = GRADEN ## Converteert radialen naar graden +EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal +EXP = EXP ## Verheft e tot de macht van een bepaald getal +FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal +FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal +FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af +GCD = GGD ## Geeft als resultaat de grootste gemene deler +INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal +LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud +LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal +LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal +LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal +MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix +MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix +MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices +MOD = REST ## Geeft als resultaat het restgetal van een deling +MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud +MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen +ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal +PI = PI ## Geeft als resultaat de waarde van pi +POWER = MACHT ## Verheft een getal tot een macht +PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar +QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal +RADIANS = RADIALEN ## Converteert graden naar radialen +RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1 +RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven +ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst +ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen +ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af +ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af +SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule +SIGN = POS.NEG ## Geeft als resultaat het teken van een getal +SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek +SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal +SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal +SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi) +SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik +SUM = SOM ## Telt de argumenten op +SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium +SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen +SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen +SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten +SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices +SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices +SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices +TAN = TAN ## Geeft als resultaat de tangens van een getal +TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal +TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal + + +## +## Statistical functions Statistische functies +## +AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde +AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten +AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden +AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria +AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen +BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie +BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling +BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling +CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling +CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling +CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets +CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie +CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen +COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst +COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst +COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik +COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium +COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria +COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties +CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium +DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat +EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling +FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling +FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling +FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie +FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie +FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend +FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix +FTEST = F.TOETS ## Geeft als resultaat een F-toets +GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling +GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling +GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x) +GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde +GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend +HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde +HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling +INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as +KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling +LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling +LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend +LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend +LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling +LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling +MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten +MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden +MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen +MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten +MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden +MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling +NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling +NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling +NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling +NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling +NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling +PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson +PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik +PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling +PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten +POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling +PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden +QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling +RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen +RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt +SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling +SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn +SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling +STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde +STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef +STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden +STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie +STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden +STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie +TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling +TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling +TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend +TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling +TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets +VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef +VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden +VARP = VARP ## Berekent de variantie op basis van de volledige populatie +VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden +WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling +ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets + + +## +## Text functions Tekstfuncties +## +ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens) +BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht) +CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code +CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst +CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks +CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment +DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro) +EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn +FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op +JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens) +LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks +LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks +LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks +LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks +LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters +MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft +MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft +PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op +PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter +REPLACE = VERVANG ## Vervangt tekens binnen een tekst +REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst +REPT = HERHALING ## Herhaalt een tekst een aantal malen +RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks +RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks +SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks +T = T ## Converteert de argumenten naar tekst +TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst +TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst +UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters +VALUE = WAARDE ## Converteert tekst naar een getal diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config new file mode 100644 index 00000000..5bf96a1b --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #VERDI! +REF = #REF! +NAME = #NAVN? +NUM = #NUM! +NA = #I/T diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions new file mode 100644 index 00000000..917c7f7d --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funksjonene Tillegg og Automatisering +## +GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport + + +## +## Cube functions Kubefunksjoner +## +CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon. +CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben. +CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet. +CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene. +CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel. +CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett. +CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube. + + +## +## Database functions Databasefunksjoner +## +DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter +DCOUNT = DANTALL ## Teller celler som inneholder tall i en database +DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database +DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår +DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter +DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter +DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database +DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter +DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen +DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene +DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter +DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen + + +## +## Date and time functions Dato- og tidsfunksjoner +## +DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato +DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer +DAY = DAG ## Konverterer et serienummer til en dag i måneden +DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager +EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen +EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder +HOUR = TIME ## Konverterer et serienummer til en time +MINUTE = MINUTT ## Konverterer et serienummer til et minutt +MONTH = MÅNED ## Konverterer et serienummer til en måned +NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer +NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett +SECOND = SEKUND ## Konverterer et serienummer til et sekund +TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett +TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer +TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato +WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag +WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år +WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager +YEAR = ÅR ## Konverterer et serienummer til et år +YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato + + +## +## Engineering functions Tekniske funksjoner +## +BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x) +BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x) +BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x) +BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x) +BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall +BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall +BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall +COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall +CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet +DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall +DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall +DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall +DELTA = DELTA ## Undersøker om to verdier er like +ERF = FEILF ## Returnerer feilfunksjonen +ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen +GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi +HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall +HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet +HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall +IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall +IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall +IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer +IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall +IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall +IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall +IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall +IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall +IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall +IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall +IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens +IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall +IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall +IMSIN = IMSIN ## Returnerer sinus til et komplekst tall +IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall +IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall +IMSUM = IMSUMMER ## Returnerer summen av komplekse tall +OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall +OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall +OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall + + +## +## Financial functions Økonomiske funksjoner +## +ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente +ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall +AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient +AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode +COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen +COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen +COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato +COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen +COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen +COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen +CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder +CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder +DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning +DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir +DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir +DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall +DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk +DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk +EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen +FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering +FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser +INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir +IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode +IRR = IR ## Returnerer internrenten for en serie kontantstrømmer +ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode +MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00 +MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser +NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats +NPER = PERIODER ## Returnerer antall perioder for en investering +NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats +ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode +ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode +ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode +ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode +PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet +PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode +PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning +PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir +PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall +PV = NÅVERDI ## Returnerer nåverdien av en investering +RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet +RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir +SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode +SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode +TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon +TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon +TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon +VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning +XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske +XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske +YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente +YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel +YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato + + +## +## Information functions Informasjonsfunksjoner +## +CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle +ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype +INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø +ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom +ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T +ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi +ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall +ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi +ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T +ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst +ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall +ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall +ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse +ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst +N = N ## Returnerer en verdi som er konvertert til et tall +NA = IT ## Returnerer feilverdien #I/T +TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi + + +## +## Logical functions Logiske funksjoner +## +AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN +FALSE = USANN ## Returnerer den logiske verdien USANN +IF = HVIS ## Angir en logisk test som skal utføres +IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen. +NOT = IKKE ## Reverserer logikken til argumentet +OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN +TRUE = SANN ## Returnerer den logiske verdien SANN + + +## +## Lookup and reference functions Oppslag- og referansefunksjoner +## +ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark +AREAS = OMRÅDER ## Returnerer antall områder i en referanse +CHOOSE = VELG ## Velger en verdi fra en liste med verdier +COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse +COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse +HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen +HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett +INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise +INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi +LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise +MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise +OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse +ROW = RAD ## Returnerer radnummeret for en referanse +ROWS = RADER ## Returnerer antall rader i en referanse +RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).) +TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise +VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle + + +## +## Math and trigonometry functions Matematikk- og trigonometrifunksjoner +## +ABS = ABS ## Returnerer absoluttverdien til et tall +ACOS = ARCCOS ## Returnerer arcus cosinus til et tall +ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall +ASIN = ARCSIN ## Returnerer arcus sinus til et tall +ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall +ATAN = ARCTAN ## Returnerer arcus tangens til et tall +ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater +ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall +CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum +COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter +COS = COS ## Returnerer cosinus til et tall +COSH = COSH ## Returnerer den hyperbolske cosinus til et tall +DEGREES = GRADER ## Konverterer radianer til grader +EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall +EXP = EKSP ## Returnerer e opphøyd i en angitt potens +FACT = FAKULTET ## Returnerer fakultet til et tall +FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet +FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null +GCD = SFF ## Returnerer høyeste felles divisor +INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall +LCM = MFM ## Returnerer minste felles multiplum +LN = LN ## Returnerer den naturlige logaritmen til et tall +LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall +LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall +MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise +MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise +MMULT = MMULT ## Returnerer matriseproduktet av to matriser +MOD = REST ## Returnerer resten fra en divisjon +MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum +MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall +ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall +PI = PI ## Returnerer verdien av pi +POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens +PRODUCT = PRODUKT ## Multipliserer argumentene +QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon +RADIANS = RADIANER ## Konverterer grader til radianer +RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1 +RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område +ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst +ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre +ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null +ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null +SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen +SIGN = FORTEGN ## Returnerer fortegnet for et tall +SIN = SIN ## Returnerer sinus til en gitt vinkel +SINH = SINH ## Returnerer den hyperbolske sinus til et tall +SQRT = ROT ## Returnerer en positiv kvadratrot +SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi) +SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database +SUM = SUMMER ## Legger sammen argumentene +SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår +SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår +SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter +SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene +SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser +SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser +SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser +TAN = TAN ## Returnerer tangens for et tall +TANH = TANH ## Returnerer den hyperbolske tangens for et tall +TRUNC = AVKORT ## Korter av et tall til et heltall + + +## +## Statistical functions Statistiske funksjoner +## +AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien +AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene +AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier +AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår +AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår. +BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen +BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling +BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen +CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling +CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen +CHITEST = KJI.TEST ## Utfører testen for uavhengighet +CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon +CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett +COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten +COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten +COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område. +COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår +COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår +COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik +CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi +DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik +EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen +FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen +FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen +FISHER = FISHER ## Returnerer Fisher-transformasjonen +FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen +FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend +FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise +FTEST = FTEST ## Returnerer resultatet av en F-test +GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen +GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen +GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x) +GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien +GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend +HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien +HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen +INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen +KURT = KURT ## Returnerer kurtosen til et datasett +LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett +LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend +LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend +LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen +LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen +MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste +MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier +MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt +MIN = MIN ## Returnerer minimumsverdien i en argumentliste +MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier +MODE = MODUS ## Returnerer den vanligste verdien i et datasett +NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen +NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen +NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen +NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling +NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen +PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson +PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område +PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett +PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter +POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling +PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser +QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett +RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke +RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r) +SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling +SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen +SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett +STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi +STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg +STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier +STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen +STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier +STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen +TDIST = TFORDELING ## Returnerer en Student t-fordeling +TINV = TINV ## Returnerer den inverse Student t-fordelingen +TREND = TREND ## Returnerer verdier langs en lineær trend +TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett +TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test +VAR = VARIANS ## Estimerer varians basert på et utvalg +VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier +VARP = VARIANSP ## Beregner varians basert på hele populasjonen +VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier +WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen +ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test + + +## +## Text functions Tekstfunksjoner +## +ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn +BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht) +CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret +CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten +CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng +CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement +DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar) +EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like +FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) +FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) +FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler +JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn +LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi +LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi +LEN = LENGDE ## Returnerer antall tegn i en tekststreng +LENB = LENGDEB ## Returnerer antall tegn i en tekststreng +LOWER = SMÅ ## Konverterer tekst til små bokstaver +MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir +MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir +PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng +PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav +REPLACE = ERSTATT ## Erstatter tegn i en tekst +REPLACEB = ERSTATTB ## Erstatter tegn i en tekst +REPT = GJENTA ## Gjentar tekst et gitt antall ganger +RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi +RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi +SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) +SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) +SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng +T = T ## Konverterer argumentene til tekst +TEXT = TEKST ## Formaterer et tall og konverterer det til tekst +TRIM = TRIMME ## Fjerner mellomrom fra tekst +UPPER = STORE ## Konverterer tekst til store bokstaver +VALUE = VERDI ## Konverterer et tekstargument til et tall diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config new file mode 100644 index 00000000..5061311c --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = zł + + +## +## Excel Error Codes (For future use) +## +NULL = #ZERO! +DIV0 = #DZIEL/0! +VALUE = #ARG! +REF = #ADR! +NAME = #NAZWA? +NUM = #LICZBA! +NA = #N/D! diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions new file mode 100644 index 00000000..14499c05 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funkcje dodatków i automatyzacji +## +GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej. + + +## +## Cube functions Funkcje modułów +## +CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji. +CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module. +CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu. +CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów. +CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel. +CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu. +CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu. + + +## +## Database functions Funkcje baz danych +## +DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych. +DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych. +DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych. +DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria. +DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych. +DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych. +DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych. +DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych. +DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych. +DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria. +DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych. +DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych. + + +## +## Date and time functions Funkcje dat, godzin i czasu +## +DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty. +DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną. +DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca. +DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego. +EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej. +EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej. +HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę. +MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę. +MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc. +NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami. +NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny. +SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę. +TIME = CZAS ## Zwraca liczbę seryjną określonego czasu. +TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną. +TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej. +WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia. +WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku. +WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej. +YEAR = ROK ## Konwertuje liczbę seryjną na rok. +YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową. + + +## +## Engineering functions Funkcje inżynierskie +## +BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x). +BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x). +BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x). +BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x). +BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej. +BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej. +BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej. +COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną. +CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny. +DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową. +DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej. +DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej. +DELTA = DELTA ## Sprawdza, czy dwie wartości są równe. +ERF = ERF ## Zwraca wartość funkcji błędu. +ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu. +GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa. +HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej. +HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej. +HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej. +IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej. +IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej. +IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach. +IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej. +IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej. +IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych. +IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej. +IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej. +IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej. +IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2. +IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej. +IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych. +IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej. +IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej. +IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej. +IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych. +IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych. +OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej. +OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej. +OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej. + + +## +## Financial functions Funkcje finansowe +## +ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym. +ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu. +AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji. +AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego. +COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego. +COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego. +COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy. +COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym. +COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu. +COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym. +CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami. +CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami. +DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej. +DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika. +DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego. +DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej. +DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej. +DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania. +EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej. +FV = FV ## Zwraca przyszłą wartość lokaty. +FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych. +INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego. +IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres. +IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych. +ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty. +MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł. +MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy. +NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej. +NPER = NPER ## Zwraca liczbę okresów dla lokaty. +NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej. +ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem. +ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem. +ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem. +ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem. +PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej. +PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu. +PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym. +PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego. +PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu. +PV = PV ## Zwraca wartość bieżącą lokaty. +RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej. +RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego. +SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową. +SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji. +TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego. +TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego. +TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego. +VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną. +XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. +XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. +YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym. +YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego. +YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie. + + +## +## Information functions Funkcje informacyjne +## +CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki. +ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu. +INFO = INFO ## Zwraca informację o aktualnym środowisku pracy. +ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta. +ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!. +ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu. +ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta. +ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną. +ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!. +ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem. +ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą. +ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta. +ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem. +ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem. +N = L ## Zwraca wartość przekonwertowaną na postać liczbową. +NA = BRAK ## Zwraca wartość błędu #N/D!. +TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości. + + +## +## Logical functions Funkcje logiczne +## +AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA. +FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ. +IF = JEŻELI ## Określa warunek logiczny do sprawdzenia. +IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły. +NOT = NIE ## Odwraca wartość logiczną argumentu. +OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA. +TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA. + + +## +## Lookup and reference functions Funkcje wyszukiwania i odwołań +## +ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową. +AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu. +CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości. +COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania. +COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania. +HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki. +HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie. +INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy. +INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową. +LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy. +MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy. +OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania. +ROW = WIERSZ ## Zwraca numer wiersza odwołania. +ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania. +RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).). +TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę. +VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki. + + +## +## Math and trigonometry functions Funkcje matematyczne i trygonometryczne +## +ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby. +ACOS = ACOS ## Zwraca arcus cosinus liczby. +ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby. +ASIN = ASIN ## Zwraca arcus sinus liczby. +ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby. +ATAN = ATAN ## Zwraca arcus tangens liczby. +ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y. +ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby. +CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności. +COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów. +COS = COS ## Zwraca cosinus liczby. +COSH = COSH ## Zwraca cosinus hiperboliczny liczby. +DEGREES = STOPNIE ## Konwertuje radiany na stopnie. +EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej. +EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę. +FACT = SILNIA ## Zwraca silnię liczby. +FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby. +FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. +GCD = GCD ## Zwraca największy wspólny dzielnik. +INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej. +LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność. +LN = LN ## Zwraca logarytm naturalny podanej liczby. +LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie. +LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby. +MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy. +MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy. +MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic. +MOD = MOD ## Zwraca resztę z dzielenia. +MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności. +MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb. +ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej. +PI = PI ## Zwraca wartość liczby Pi. +POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi. +PRODUCT = ILOCZYN ## Mnoży argumenty. +QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity). +RADIANS = RADIANY ## Konwertuje stopnie na radiany. +RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1. +RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty. +ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst. +ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr. +ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. +ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera. +SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru. +SIGN = ZNAK.LICZBY ## Zwraca znak liczby. +SIN = SIN ## Zwraca sinus danego kąta. +SINH = SINH ## Zwraca sinus hiperboliczny liczby. +SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy. +SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi). +SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych. +SUM = SUMA ## Dodaje argumenty. +SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium. +SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów. +SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy. +SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów. +SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach. +SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach. +SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach. +TAN = TAN ## Zwraca tangens liczby. +TANH = TANH ## Zwraca tangens hiperboliczny liczby. +TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej. + + +## +## Statistical functions Funkcje statystyczne +## +AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej. +AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów. +AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria. +AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów. +BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta. +BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta. +BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa. +CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. +CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. +CHITEST = TEST.CHI ## Zwraca test niezależności. +CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji. +CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych. +COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów. +COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów. +COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie. +COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria. +COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów. +COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń. +CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej. +DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń. +EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy. +FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F. +FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F. +FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera. +FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera. +FORECAST = REGLINX ## Zwraca wartość trendu liniowego. +FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową. +FTEST = TEST.F ## Zwraca wynik testu F. +GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma. +GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma. +GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x). +GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną. +GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego. +HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną. +HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny. +INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej. +KURT = KURTOZA ## Zwraca kurtozę zbioru danych. +LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych. +LINEST = REGLINP ## Zwraca parametry trendu liniowego. +LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego. +LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego. +LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego. +MAX = MAX ## Zwraca maksymalną wartość listy argumentów. +MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +MEDIAN = MEDIANA ## Zwraca medianę podanych liczb. +MIN = MIN ## Zwraca minimalną wartość listy argumentów. +MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych. +NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy. +NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany. +NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego. +NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany. +NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego. +PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona. +PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie. +PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych. +PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów. +POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona. +PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami. +QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych. +RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb. +RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona. +SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu. +SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej. +SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych. +STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną. +STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki. +STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. +STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji. +STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych. +STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji. +TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta. +TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta. +TREND = REGLINW ## Zwraca wartości trendu liniowego. +TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych. +TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta. +VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki. +VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. +VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji. +VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych. +WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla. +ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z. + + +## +## Text functions Funkcje tekstowe +## +ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe). +BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht). +CHAR = ZNAK ## Zwraca znak o podanym numerze kodu. +CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane. +CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym. +CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst. +DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar). +EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych. +FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). +FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). +FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych. +JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe). +LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej. +LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej. +LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego. +LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego. +LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery. +MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. +MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. +PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego. +PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą. +REPLACE = ZASTĄP ## Zastępuje znaki w tekście. +REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście. +REPT = POWT ## Powiela tekst daną liczbę razy. +RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej. +RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej. +SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). +SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). +SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym. +T = T ## Konwertuje argumenty na tekst. +TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst. +TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu. +UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery. +VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config new file mode 100644 index 00000000..b4bf7041 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = R$ + + +## +## Excel Error Codes (For future use) +## +NULL = #NULO! +DIV0 = #DIV/0! +VALUE = #VALOR! +REF = #REF! +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions new file mode 100644 index 00000000..a062a7fa --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Funções Suplemento e Automação +## +GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica + + +## +## Cube functions Funções de Cubo +## +CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização. +CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo. +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro. +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos. +CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel. +CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto. +CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo. + + +## +## Database functions Funções de banco de dados +## +DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados +DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados +DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados +DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico +DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados +DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados +DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados +DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados +DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados +DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério +DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados +DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados + + +## +## Date and time functions Funções de data e hora +## +DATE = DATA ## Retorna o número de série de uma data específica +DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série +DAY = DIA ## Converte um número de série em um dia do mês +DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias +EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial +EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses +HOUR = HORA ## Converte um número de série em uma hora +MINUTE = MINUTO ## Converte um número de série em um minuto +MONTH = MÊS ## Converte um número de série em um mês +NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas +NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais +SECOND = SEGUNDO ## Converte um número de série em um segundo +TIME = HORA ## Retorna o número de série de uma hora específica +TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série +TODAY = HOJE ## Retorna o número de série da data de hoje +WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana +WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano +WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis +YEAR = ANO ## Converte um número de série em um ano +YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final + + +## +## Engineering functions Funções de engenharia +## +BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada +BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x) +BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada +BESSELY = BESSELY ## Retorna a função de Bessel Yn(x) +BIN2DEC = BIN2DEC ## Converte um número binário em decimal +BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal +BIN2OCT = BIN2OCT ## Converte um número binário em octal +COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo +CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro +DEC2BIN = DECABIN ## Converte um número decimal em binário +DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal +DEC2OCT = DECAOCT ## Converte um número decimal em octal +DELTA = DELTA ## Testa se dois valores são iguais +ERF = FUNERRO ## Retorna a função de erro +ERFC = FUNERROCOMPL ## Retorna a função de erro complementar +GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite +HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário +HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal +HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal +IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo +IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo +IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos +IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo +IMCOS = IMCOS ## Retorna o cosseno de um número complexo +IMDIV = IMDIV ## Retorna o quociente de dois números complexos +IMEXP = IMEXP ## Retorna o exponencial de um número complexo +IMLN = IMLN ## Retorna o logaritmo natural de um número complexo +IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo +IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo +IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira +IMPRODUCT = IMPROD ## Retorna o produto de números complexos +IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo +IMSIN = IMSENO ## Retorna o seno de um número complexo +IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo +IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos +IMSUM = IMSOMA ## Retorna a soma de números complexos +OCT2BIN = OCTABIN ## Converte um número octal em binário +OCT2DEC = OCTADEC ## Converte um número octal em decimal +OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal + + +## +## Financial functions Funções financeiras +## +ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros +ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento +AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação +AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil +COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação +COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação +COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom +COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação +COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento +COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação +CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos +CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos +DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo +DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você +DISC = DESC ## Retorna a taxa de desconto de um título +DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal +DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária +DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos +EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva +FV = VF ## Retorna o valor futuro de um investimento +FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas +INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido +IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período +IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa +ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento +MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100 +MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas +NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual +NPER = NPER ## Retorna o número de períodos de um investimento +NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto +ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido +ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido +ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido +ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido +PMT = PGTO ## Retorna o pagamento periódico de uma anuidade +PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento +PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos +PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado +PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento +PV = VP ## Retorna o valor presente de um investimento +RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade +RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido +SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período +SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado +TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro +TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro +TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro +VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante +XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico +XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico +YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos +YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro +YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento + + +## +## Information functions Funções de informação +## +CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula +ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro +INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual +ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio +ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D +ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro +ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par +ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico +ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D +ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto +ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número +ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar +ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência +ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto +N = N ## Retorna um valor convertido em um número +NA = NÃO.DISP ## Retorna o valor de erro #N/D +TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor + + +## +## Logical functions Funções lógicas +## +AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS +FALSE = FALSO ## Retorna o valor lógico FALSO +IF = SE ## Especifica um teste lógico a ser executado +IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula +NOT = NÃO ## Inverte o valor lógico do argumento +OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO +TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO + + +## +## Lookup and reference functions Funções de pesquisa e referência +## +ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha +AREAS = ÁREAS ## Retorna o número de áreas em uma referência +CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores +COLUMN = COL ## Retorna o número da coluna de uma referência +COLUMNS = COLS ## Retorna o número de colunas em uma referência +HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada +HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet +INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz +INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto +LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz +MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz +OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência +ROW = LIN ## Retorna o número da linha de uma referência +ROWS = LINS ## Retorna o número de linhas em uma referência +RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).) +TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz +VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula + + +## +## Math and trigonometry functions Funções matemáticas e trigonométricas +## +ABS = ABS ## Retorna o valor absoluto de um número +ACOS = ACOS ## Retorna o arco cosseno de um número +ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número +ASIN = ASEN ## Retorna o arco seno de um número +ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número +ATAN = ATAN ## Retorna o arco tangente de um número +ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas +ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número +CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância +COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos +COS = COS ## Retorna o cosseno de um número +COSH = COSH ## Retorna o cosseno hiperbólico de um número +DEGREES = GRAUS ## Converte radianos em graus +EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo +EXP = EXP ## Retorna e elevado à potência de um número especificado +FACT = FATORIAL ## Retorna o fatorial de um número +FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número +FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero +GCD = MDC ## Retorna o máximo divisor comum +INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo +LCM = MMC ## Retorna o mínimo múltiplo comum +LN = LN ## Retorna o logaritmo natural de um número +LOG = LOG ## Retorna o logaritmo de um número de uma base especificada +LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número +MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz +MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz +MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes +MOD = RESTO ## Retorna o resto da divisão +MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado +MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números +ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo +PI = PI ## Retorna o valor de Pi +POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência +PRODUCT = MULT ## Multiplica seus argumentos +QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão +RADIANS = RADIANOS ## Converte graus em radianos +RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1 +RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados +ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto +ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos +ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero +ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero +SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula +SIGN = SINAL ## Retorna o sinal de um número +SIN = SEN ## Retorna o seno de um ângulo dado +SINH = SENH ## Retorna o seno hiperbólico de um número +SQRT = RAIZ ## Retorna uma raiz quadrada positiva +SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi) +SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados +SUM = SOMA ## Soma seus argumentos +SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério +SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios +SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes +SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos +SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes +SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes +SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes +TAN = TAN ## Retorna a tangente de um número +TANH = TANH ## Retorna a tangente hiperbólica de um número +TRUNC = TRUNCAR ## Trunca um número para um inteiro + + +## +## Statistical functions Funções estatísticas +## +AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média +AVERAGE = MÉDIA ## Retorna a média dos argumentos +AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos +AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério +AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios. +BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta +BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada +BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual +CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada +CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada +CHITEST = TESTE.QUI ## Retorna o teste para independência +CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população +CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados +COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos +COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos +COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado +COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios +COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios +COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares +CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão +DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios +EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial +FDIST = DISTF ## Retorna a distribuição de probabilidade F +FINV = INVF ## Retorna o inverso da distribuição de probabilidades F +FISHER = FISHER ## Retorna a transformação Fisher +FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher +FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta +FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical +FTEST = TESTEF ## Retorna o resultado de um teste F +GAMMADIST = DISTGAMA ## Retorna a distribuição gama +GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama +GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x) +GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica +GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial +HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica +HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica +INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear +KURT = CURT ## Retorna a curtose de um conjunto de dados +LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados +LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear +LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial +LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal +LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa +MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos +MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos +MEDIAN = MED ## Retorna a mediana dos números indicados +MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos +MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos +MODE = MODO ## Retorna o valor mais comum em um conjunto de dados +NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa +NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal +NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal +NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão +NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão +PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson +PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo +PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados +PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos +POISSON = POISSON ## Retorna a distribuição Poisson +PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites +QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados +RANK = ORDEM ## Retorna a posição de um número em uma lista de números +RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson +SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição +SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear +SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados +STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado +STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra +STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos +STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total +STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos +STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão +TDIST = DISTT ## Retorna a distribuição t de Student +TINV = INVT ## Retorna o inverso da distribuição t de Student +TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear +TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados +TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student +VAR = VAR ## Estima a variância com base em uma amostra +VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos +VARP = VARP ## Calcula a variância com base na população inteira +VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos +WEIBULL = WEIBULL ## Retorna a distribuição Weibull +ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z + + +## +## Text functions Funções de texto +## +ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único) +BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht) +CHAR = CARACT ## Retorna o caractere especificado pelo número de código +CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos +CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto +CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto +DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar) +EXACT = EXATO ## Verifica se dois valores de texto são idênticos +FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) +FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) +FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais +JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos) +LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto +LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto +LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto +LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto +LOWER = MINÚSCULA ## Converte texto para minúsculas +MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada +MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada +PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto +PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto +REPLACE = MUDAR ## Muda os caracteres dentro do texto +REPLACEB = MUDARB ## Muda os caracteres dentro do texto +REPT = REPT ## Repete o texto um determinado número de vezes +RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto +RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto +SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) +SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) +SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto +T = T ## Converte os argumentos em texto +TEXT = TEXTO ## Formata um número e o converte em texto +TRIM = ARRUMAR ## Remove espaços do texto +UPPER = MAIÚSCULA ## Converte o texto em maiúsculas +VALUE = VALOR ## Converte um argumento de texto em um número diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config new file mode 100644 index 00000000..60b422bd --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULO! +DIV0 = #DIV/0! +VALUE = #VALOR! +REF = #REF! +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions new file mode 100644 index 00000000..ba4eb471 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Funções de Suplemento e Automatização +## +GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica + + +## +## Cube functions Funções de cubo +## +CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização. +CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo. +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro. +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos. +CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel. +CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto. +CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo. + + +## +## Database functions Funções de base de dados +## +DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas +DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados +DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados +DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados +DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas +DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas +DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados +DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas +DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas +DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios +DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas +DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas + + +## +## Date and time functions Funções de data e hora +## +DATE = DATA ## Devolve o número de série de uma determinada data +DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série +DAY = DIA ## Converte um número de série num dia do mês +DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias +EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início +EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado +HOUR = HORA ## Converte um número de série numa hora +MINUTE = MINUTO ## Converte um número de série num minuto +MONTH = MÊS ## Converte um número de série num mês +NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas +NOW = AGORA ## Devolve o número de série da data e hora actuais +SECOND = SEGUNDO ## Converte um número de série num segundo +TIME = TEMPO ## Devolve o número de série de um determinado tempo +TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série +TODAY = HOJE ## Devolve o número de série da data actual +WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana +WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano +WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado +YEAR = ANO ## Converte um número de série num ano +YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim + + +## +## Engineering functions Funções de engenharia +## +BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x) +BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x) +BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x) +BESSELY = BESSELY ## Devolve a função de Bessel Yn(x) +BIN2DEC = BINADEC ## Converte um número binário em decimal +BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal +BIN2OCT = BINAOCT ## Converte um número binário em octal +COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo +CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro +DEC2BIN = DECABIN ## Converte um número decimal em binário +DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal +DEC2OCT = DECAOCT ## Converte um número decimal em octal +DELTA = DELTA ## Testa se dois valores são iguais +ERF = FUNCERRO ## Devolve a função de erro +ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar +GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite +HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário +HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal +HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal +IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo +IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo +IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos +IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo +IMCOS = IMCOS ## Devolve o co-seno de um número complexo +IMDIV = IMDIV ## Devolve o quociente de dois números complexos +IMEXP = IMEXP ## Devolve o exponencial de um número complexo +IMLN = IMLN ## Devolve o logaritmo natural de um número complexo +IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo +IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo +IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira +IMPRODUCT = IMPROD ## Devolve o produto de números complexos +IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo +IMSIN = IMSENO ## Devolve o seno de um número complexo +IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo +IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos +IMSUM = IMSOMA ## Devolve a soma de números complexos +OCT2BIN = OCTABIN ## Converte um número octal em binário +OCT2DEC = OCTADEC ## Converte um número octal em decimal +OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal + + +## +## Financial functions Funções financeiras +## +ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos +ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento +AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação +AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico +COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização +COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização +COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte +COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização +COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento +COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização +CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos +CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos +DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas +DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado +DISC = DESC ## Devolve a taxa de desconto de um título +DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal +DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção +DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos +EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva +FV = VF ## Devolve o valor futuro de um investimento +FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas +INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade +IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período +IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários +ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento +MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100 +MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes +NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual +NPER = NPER ## Devolve o número de períodos de um investimento +NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto +ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto +ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto +ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto +ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto +PMT = PGTO ## Devolve o pagamento periódico de uma anuidade +PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período +PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos +PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado +PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento +PV = VA ## Devolve o valor actual de um investimento +RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade +RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade +SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período +SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado +TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro +TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro +TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro +VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas +XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica +XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico +YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos +YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro +YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento + + +## +## Information functions Funções de informação +## +CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula +ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro +INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual +ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco +ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D +ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro +ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par +ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico +ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D +ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto +ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número +ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar +ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência +ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto +N = N ## Devolve um valor convertido num número +NA = NÃO.DISP ## Devolve o valor de erro #N/D +TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor + + +## +## Logical functions Funções lógicas +## +AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO +FALSE = FALSO ## Devolve o valor lógico FALSO +IF = SE ## Especifica um teste lógico a ser executado +IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro +NOT = NÃO ## Inverte a lógica do respectivo argumento +OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO +TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO + + +## +## Lookup and reference functions Funções de pesquisa e referência +## +ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto +AREAS = ÁREAS ## Devolve o número de áreas numa referência +CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores +COLUMN = COL ## Devolve o número da coluna de uma referência +COLUMNS = COLS ## Devolve o número de colunas numa referência +HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada +HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet +INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz +INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto +LOOKUP = PROC ## Procura valores num vector ou numa matriz +MATCH = CORRESP ## Procura valores numa referência ou numa matriz +OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência +ROW = LIN ## Devolve o número da linha de uma referência +ROWS = LINS ## Devolve o número de linhas numa referência +RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).) +TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz +VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula + + +## +## Math and trigonometry functions Funções matemáticas e trigonométricas +## +ABS = ABS ## Devolve o valor absoluto de um número +ACOS = ACOS ## Devolve o arco de co-seno de um número +ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número +ASIN = ASEN ## Devolve o arco de seno de um número +ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número +ATAN = ATAN ## Devolve o arco de tangente de um número +ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y +ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número +CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo +COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos +COS = COS ## Devolve o co-seno de um número +COSH = COSH ## Devolve o co-seno hiperbólico de um número +DEGREES = GRAUS ## Converte radianos em graus +EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo +EXP = EXP ## Devolve e elevado à potência de um determinado número +FACT = FACTORIAL ## Devolve o factorial de um número +FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número +FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero +GCD = MDC ## Devolve o maior divisor comum +INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo +LCM = MMC ## Devolve o mínimo múltiplo comum +LN = LN ## Devolve o logaritmo natural de um número +LOG = LOG ## Devolve o logaritmo de um número com uma base especificada +LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número +MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz +MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz +MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes +MOD = RESTO ## Devolve o resto da divisão +MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido +MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números +ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo +PI = PI ## Devolve o valor de pi +POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência +PRODUCT = PRODUTO ## Multiplica os respectivos argumentos +QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão +RADIANS = RADIANOS ## Converte graus em radianos +RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1 +RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados +ROMAN = ROMANO ## Converte um número árabe em romano, como texto +ROUND = ARRED ## Arredonda um número para um número de dígitos especificado +ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero +ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero +SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula +SIGN = SINAL ## Devolve o sinal de um número +SIN = SEN ## Devolve o seno de um determinado ângulo +SINH = SENH ## Devolve o seno hiperbólico de um número +SQRT = RAIZQ ## Devolve uma raiz quadrada positiva +SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi) +SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados +SUM = SOMA ## Adiciona os respectivos argumentos +SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério +SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios +SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes +SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos +SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes +SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes +SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes +TAN = TAN ## Devolve a tangente de um número +TANH = TANH ## Devolve a tangente hiperbólica de um número +TRUNC = TRUNCAR ## Trunca um número para um número inteiro + + +## +## Statistical functions Funções estatísticas +## +AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados +AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos +AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos +AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério +AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios +BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta +BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica +BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual +CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada +CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada +CHITEST = TESTE.CHI ## Devolve o teste para independência +CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população +CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados +COUNT = CONTAR ## Conta os números que existem na lista de argumentos +COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos +COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo +COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados +COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios +COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares +CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério +DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios +EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial +FDIST = DISTF ## Devolve a distribuição da probabilidade F +FINV = INVF ## Devolve o inverso da distribuição da probabilidade F +FISHER = FISHER ## Devolve a transformação Fisher +FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher +FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear +FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical +FTEST = TESTEF ## Devolve o resultado de um teste F +GAMMADIST = DISTGAMA ## Devolve a distribuição gama +GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa +GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x) +GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica +GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial +HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica +HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica +INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear +KURT = CURT ## Devolve a curtose de um conjunto de dados +LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados +LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear +LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial +LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica +LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa +MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos +MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos +MEDIAN = MED ## Devolve a mediana dos números indicados +MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos +MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos +MODE = MODA ## Devolve o valor mais comum num conjunto de dados +NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa +NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal +NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal +NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão +NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão +PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson +PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo +PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados +PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos +POISSON = POISSON ## Devolve a distribuição de Poisson +PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites +QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados +RANK = ORDEM ## Devolve a ordem de um número numa lista numérica +RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson +SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição +SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear +SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados +STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado +STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra +STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos +STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total +STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos +STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão +TDIST = DISTT ## Devolve a distribuição t de Student +TINV = INVT ## Devolve o inverso da distribuição t de Student +TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear +TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados +TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student +VAR = VAR ## Calcula a variância com base numa amostra +VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos +VARP = VARP ## Calcula a variância com base na população total +VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos +WEIBULL = WEIBULL ## Devolve a distribuição Weibull +ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z + + +## +## Text functions Funções de texto +## +ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único) +BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht) +CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código +CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis +CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto +CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto +DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro) +EXACT = EXACTO ## Verifica se dois valores de texto são idênticos +FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) +FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) +FIXED = FIXA ## Formata um número como texto com um número fixo de decimais +JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo) +LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto +LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto +LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto +LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto +LOWER = MINÚSCULAS ## Converte o texto em minúsculas +MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada +MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada +PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto +PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto +REPLACE = SUBSTITUIR ## Substitui caracteres no texto +REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto +REPT = REPETIR ## Repete texto um determinado número de vezes +RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto +RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto +SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) +SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) +SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto +T = T ## Converte os respectivos argumentos em texto +TEXT = TEXTO ## Formata um número e converte-o em texto +TRIM = COMPACTAR ## Remove espaços do texto +UPPER = MAIÚSCULAS ## Converte texto em maiúsculas +VALUE = VALOR ## Converte um argumento de texto num número diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config new file mode 100644 index 00000000..6f6ace23 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = р + + +## +## Excel Error Codes (For future use) +## +NULL = #ПУСТО! +DIV0 = #ДЕЛ/0! +VALUE = #ЗНАЧ! +REF = #ССЫЛ! +NAME = #ИМЯ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions new file mode 100644 index 00000000..bd636861 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from information provided by web-junior (http://www.web-junior.net/) +## +## + + +## +## Add-in and Automation functions Функции надстроек и автоматизации +## +GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы. + + +## +## Cube functions Функции Куб +## +CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации. +CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе. +CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента. +CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов. +CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel. +CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества. +CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба. + + +## +## Database functions Функции для работы с базами данных +## +DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных. +DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных. +DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных. +DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию. +DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных. +DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных. +DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию. +DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных. +DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных +DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию. +DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных +DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных + + +## +## Date and time functions Функции даты и времени +## +DATE = ДАТА ## Возвращает заданную дату в числовом формате. +DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат. +DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца. +DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года. +EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты. +EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев. +HOUR = ЧАС ## Преобразует дату в числовом формате в часы. +MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты. +MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы. +NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами. +NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате. +SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды. +TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате. +TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат. +TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате. +WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели. +WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата. +WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней. +YEAR = ГОД ## Преобразует дату в числовом формате в год. +YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами. + + +## +## Engineering functions Инженерные функции +## +BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x). +BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x). +BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x). +BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x). +BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное. +BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное. +BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное. +COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число. +CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую. +DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное. +DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное. +DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное. +DELTA = ДЕЛЬТА ## Проверяет равенство двух значений. +ERF = ФОШ ## Возвращает функцию ошибки. +ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки. +GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения. +HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное. +HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное. +HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное. +IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа. +IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа. +IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах. +IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число. +IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа. +IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел. +IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа. +IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа. +IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа. +IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа. +IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень. +IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел. +IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа. +IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа. +IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа. +IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел. +IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел. +OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное. +OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное. +OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное. + + +## +## Financial functions Финансовые функции +## +ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов. +ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения. +AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации. +AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода. +COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения. +COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения. +COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона. +COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения. +COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу. +COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения. +CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами. +CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами. +DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка. +DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод. +DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг. +DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом. +DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби. +DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам. +EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки. +FV = БС ## Возвращает будущую стоимость инвестиции. +FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов. +INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг. +IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период. +IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств. +ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции. +MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей. +MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки. +NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку. +NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада. +NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования. +ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом. +ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом. +ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом. +ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом. +PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета. +PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период. +PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов. +PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка. +PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения. +PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции. +RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период. +RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг. +SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период. +SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел. +TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку. +TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека. +TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку. +VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса. +XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер. +XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими. +YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов. +YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки). +YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения. + + +## +## Information functions Информационные функции +## +CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки. +ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки. +INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде. +ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку. +ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д. +ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки. +ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом. +ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение. +ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д. +ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом. +ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число. +ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом. +ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой. +ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом. +N = Ч ## Возвращает значение, преобразованное в число. +NA = НД ## Возвращает значение ошибки #Н/Д. +TYPE = ТИП ## Возвращает число, обозначающее тип данных значения. + + +## +## Logical functions Логические функции +## +AND = И ## Renvoie VRAI si tous ses arguments sont VRAI. +FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ. +IF = ЕСЛИ ## Выполняет проверку условия. +IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления. +NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное. +OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА. +TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА. + + +## +## Lookup and reference functions Функции ссылки и поиска +## +ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста. +AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке. +CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу. +COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка. +COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке. +HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки +HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете. +INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива. +INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением. +LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве. +MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве. +OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки. +ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой. +ROWS = ЧСТРОК ## Возвращает количество строк в ссылке. +RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).). +TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив. +VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце. + + +## +## Math and trigonometry functions Математические и тригонометрические функции +## +ABS = ABS ## Возвращает модуль (абсолютную величину) числа. +ACOS = ACOS ## Возвращает арккосинус числа. +ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа. +ASIN = ASIN ## Возвращает арксинус числа. +ASINH = ASINH ## Возвращает гиперболический арксинус числа. +ATAN = ATAN ## Возвращает арктангенс числа. +ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y. +ATANH = ATANH ## Возвращает гиперболический арктангенс числа. +CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению. +COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов. +COS = COS ## Возвращает косинус числа. +COSH = COSH ## Возвращает гиперболический косинус числа. +DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы. +EVEN = ЧЁТН ## Округляет число до ближайшего четного целого. +EXP = EXP ## Возвращает число e, возведенное в указанную степень. +FACT = ФАКТР ## Возвращает факториал числа. +FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа. +FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. +GCD = НОД ## Возвращает наибольший общий делитель. +INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого. +LCM = НОК ## Возвращает наименьшее общее кратное. +LN = LN ## Возвращает натуральный логарифм числа. +LOG = LOG ## Возвращает логарифм числа по заданному основанию. +LOG10 = LOG10 ## Возвращает десятичный логарифм числа. +MDETERM = МОПРЕД ## Возвращает определитель матрицы массива. +MINVERSE = МОБР ## Возвращает обратную матрицу массива. +MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов. +MOD = ОСТАТ ## Возвращает остаток от деления. +MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью. +MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел. +ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого. +PI = ПИ ## Возвращает число пи. +POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень. +PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов. +QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении. +RADIANS = РАДИАНЫ ## Преобразует градусы в радианы. +RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1. +RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами. +ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста. +ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов. +ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. +ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения. +SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле. +SIGN = ЗНАК ## Возвращает знак числа. +SIN = SIN ## Возвращает синус заданного угла. +SINH = SINH ## Возвращает гиперболический синус числа. +SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня. +SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ). +SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных. +SUM = СУММ ## Суммирует аргументы. +SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию. +SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям. +SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов. +SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов. +SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах. +SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов. +SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах. +TAN = TAN ## Возвращает тангенс числа. +TANH = TANH ## Возвращает гиперболический тангенс числа. +TRUNC = ОТБР ## Отбрасывает дробную часть числа. + + +## +## Statistical functions Статистические функции +## +AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего. +AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов. +AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения. +AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию. +AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям. +BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения. +BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения. +BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения. +CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат. +CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат. +CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость. +CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности. +CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных. +COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов. +COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов. +COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне +COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию +COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям. +COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений +CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию. +DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений. +EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение. +FDIST = FРАСП ## Возвращает F-распределение вероятности. +FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности. +FISHER = ФИШЕР ## Возвращает преобразование Фишера. +FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера. +FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда. +FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива. +FTEST = ФТЕСТ ## Возвращает результат F-теста. +GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение. +GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение. +GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x). +GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое. +GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом. +HARMEAN = СРГАРМ ## Возвращает среднее гармоническое. +HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение. +INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии. +KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных. +LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных. +LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда. +LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда. +LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение. +LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение. +MAX = МАКС ## Возвращает наибольшее значение в списке аргументов. +MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения. +MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел. +MIN = МИН ## Возвращает наименьшее значение в списке аргументов. +MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения. +MODE = МОДА ## Возвращает значение моды множества данных. +NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение. +NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения. +NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение. +NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение. +NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения. +PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона. +PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона. +PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных. +PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов. +POISSON = ПУАССОН ## Возвращает распределение Пуассона. +PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов. +QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных. +RANK = РАНГ ## Возвращает ранг числа в списке чисел. +RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона. +SKEW = СКОС ## Возвращает асимметрию распределения. +SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии. +SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных. +STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение. +STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке. +STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения. +STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности. +STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения. +STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии. +TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента. +TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента. +TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом. +TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных. +TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента. +VAR = ДИСП ## Оценивает дисперсию по выборке. +VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения. +VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности. +VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения. +WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла. +ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста. + + +## +## Text functions Текстовые функции +## +ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые). +BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ). +CHAR = СИМВОЛ ## Возвращает знак с заданным кодом. +CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста. +CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке. +CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один. +DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат. +EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений. +FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). +FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). +FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков. +JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые). +LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения. +LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения. +LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке. +LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке. +LOWER = СТРОЧН ## Преобразует все буквы текста в строчные. +MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. +MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. +PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки. +PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную. +REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте. +REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте. +REPT = ПОВТОР ## Повторяет текст заданное число раз. +RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки. +RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки. +SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра). +SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра). +SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым. +T = Т ## Преобразует аргументы в текст. +TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст. +TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы. +UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные. +VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число. diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config new file mode 100644 index 00000000..5d1a9a9f --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + +## +## Excel Error Codes (For future use) +## +NULL = #Skärning! +DIV0 = #Division/0! +VALUE = #Värdefel! +REF = #Referens! +NAME = #Namn? +NUM = #Ogiltigt! +NA = #Saknas! diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions new file mode 100644 index 00000000..73b2deb5 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner +## +GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport + + +## +## Cube functions Kubfunktioner +## +CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat. +CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben. +CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen. +CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna. +CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel. +CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning. +CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub. + + +## +## Database functions Databasfunktioner +## +DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna +DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas +DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas +DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren +DMAX = DMAX ## Returnerar det största värdet från databasposterna +DMIN = DMIN ## Returnerar det minsta värdet från databasposterna +DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret +DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna +DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter +DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret +DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna +DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter + + +## +## Date and time functions Tid- och datumfunktioner +## +DATE = DATUM ## Returnerar ett serienummer för ett visst datum +DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer +DAY = DAG ## Konverterar ett serienummer till dag i månaden +DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår +EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet +EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare +HOUR = TIMME ## Konverterar ett serienummer till en timme +MINUTE = MINUT ## Konverterar ett serienummer till en minut +MONTH = MÅNAD ## Konverterar ett serienummer till en månad +NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum +NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid +SECOND = SEKUND ## Konverterar ett serienummer till en sekund +TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid +TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer +TODAY = IDAG ## Returnerar serienumret för dagens datum +WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan +WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer +WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare +YEAR = ÅR ## Konverterar ett serienummer till ett år +YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum + + +## +## Engineering functions Tekniska funktioner +## +BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x) +BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x) +BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x) +BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x) +BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt +BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt +BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt +COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal +CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat +DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt +DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt +DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt +DELTA = DELTA ## Testar om två värden är lika +ERF = FELF ## Returnerar felfunktionen +ERFC = FELFK ## Returnerar den komplementära felfunktionen +GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde +HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt +HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt +HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt +IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal +IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal +IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer +IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat +IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal +IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal +IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal +IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal +IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal +IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal +IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent +IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal +IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal +IMSIN = IMSIN ## Returnerar sinus för ett komplext tal +IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal +IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal +IMSUM = IMSUM ## Returnerar summan av komplexa tal +OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt +OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt +OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt + + +## +## Financial functions Finansiella funktioner +## +ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta +ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen +AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient +AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod +COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen +COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet +COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum +COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen +COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen +COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen +CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder +CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder +DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning +DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger +DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper +DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal +DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk +DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar +EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen +FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering +FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer +INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper +IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period +IRR = IR ## Returnerar internräntan för en serie betalningar +ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod +MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr +MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor +NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen +NPER = PERIODER ## Returnerar antalet perioder för en investering +NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta +ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period +ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period +ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period +ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period +PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet +PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period +PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta +PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper +PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen +PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar +RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet +RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper +SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period +SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period +TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel +TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel +TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel +VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning) +XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska +XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska +YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta +YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel +YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen + + +## +## Information functions Informationsfunktioner +## +CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell +ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde +INFO = INFO ## Returnerar information om operativsystemet +ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt +ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS! +ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde +ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt +ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde +ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS! +ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text +ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal +ISODD = ÄRUDDA ## Returnerar SANT om talet är udda +ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens +ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text +N = N ## Returnerar ett värde omvandlat till ett tal +NA = SAKNAS ## Returnerar felvärdet #SAKNAS! +TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp + + +## +## Logical functions Logiska funktioner +## +AND = OCH ## Returnerar SANT om alla argument är sanna +FALSE = FALSKT ## Returnerar det logiska värdet FALSKT +IF = OM ## Anger vilket logiskt test som ska utföras +IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln +NOT = ICKE ## Inverterar logiken för argumenten +OR = ELLER ## Returnerar SANT om något argument är SANT +TRUE = SANT ## Returnerar det logiska värdet SANT + + +## +## Lookup and reference functions Sök- och referensfunktioner +## +ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad +AREAS = OMRÅDEN ## Returnerar antalet områden i en referens +CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden +COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens +COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens +HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell +HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet +INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris +INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde +LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris +MATCH = PASSA ## Letar upp värden i en referens eller matris +OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens +ROW = RAD ## Returnerar radnumret för en referens +ROWS = RADER ## Returnerar antalet rader i en referens +RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).) +TRANSPOSE = TRANSPONERA ## Transponerar en matris +VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell + + +## +## Math and trigonometry functions Matematiska och trigonometriska funktioner +## +ABS = ABS ## Returnerar absolutvärdet av ett tal +ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal +ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal +ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal +ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal +ATAN = ARCTAN ## Returnerar arcus tangens för ett tal +ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat +ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal +CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel +COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt +COS = COS ## Returnerar cosinus för ett tal +COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal +DEGREES = GRADER ## Omvandlar radianer till grader +EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal +EXP = EXP ## Returnerar e upphöjt till ett givet tal +FACT = FAKULTET ## Returnerar fakulteten för ett tal +FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal +FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll +GCD = SGD ## Returnerar den största gemensamma nämnaren +INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal +LCM = MGM ## Returnerar den minsta gemensamma multipeln +LN = LN ## Returnerar den naturliga logaritmen för ett tal +LOG = LOG ## Returnerar logaritmen för ett tal för en given bas +LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal +MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris +MINVERSE = MINVERT ## Returnerar matrisinversen av en matris +MMULT = MMULT ## Returnerar matrisprodukten av två matriser +MOD = REST ## Returnerar resten vid en division +MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel +MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal +ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal +PI = PI ## Returnerar värdet pi +POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent +PRODUCT = PRODUKT ## Multiplicerar argumenten +QUOTIENT = KVOT ## Returnerar heltalsdelen av en division +RADIANS = RADIANER ## Omvandlar grader till radianer +RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1 +RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger +ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text +ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror +ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll +ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll +SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln +SIGN = TECKEN ## Returnerar tecknet för ett tal +SIN = SIN ## Returnerar sinus för en given vinkel +SINH = SINH ## Returnerar hyperbolisk sinus för ett tal +SQRT = ROT ## Returnerar den positiva kvadratroten +SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi) +SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas +SUM = SUMMA ## Summerar argumenten +SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor +SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier +SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter +SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater +SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser +SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser +SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser +TAN = TAN ## Returnerar tangens för ett tal +TANH = TANH ## Returnerar hyperbolisk tangens för ett tal +TRUNC = AVKORTA ## Avkortar ett tal till ett heltal + + +## +## Statistical functions Statistiska funktioner +## +AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde +AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten +AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden +AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium +AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor. +BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen +BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning +BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen +CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen +CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen +CHITEST = CHI2TEST ## Returnerar oberoendetesten +CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde +CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder +COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten +COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten +COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område +COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor. +COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor. +COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser +CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde +DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser +EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen +FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen +FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen +FISHER = FISHER ## Returnerar Fisher-transformationen +FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen +FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje +FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris +FTEST = FTEST ## Returnerar resultatet av en F-test +GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen +GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen +GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x) +GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet +GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend +HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet +HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen +INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje +KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data +LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data +LINEST = REGR ## Returnerar parametrar till en linjär trendlinje +LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend +LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen +LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen +MAX = MAX ## Returnerar det största värdet i en lista av argument +MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden +MEDIAN = MEDIAN ## Returnerar medianen för angivna tal +MIN = MIN ## Returnerar det minsta värdet i en lista med argument +MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden +MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd +NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen +NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen +NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen +NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen +NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen +PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt +PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område +PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd +PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt +POISSON = POISSON ## Returnerar Poisson-fördelningen +PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser +QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data +RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal +RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient +SKEW = SNEDHET ## Returnerar snedheten för en fördelning +SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje +SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data +STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde +STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval +STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden +STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen +STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden +STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen +TDIST = TFÖRD ## Returnerar Students t-fördelning +TINV = TINV ## Returnerar inversen till Students t-fördelning +TREND = TREND ## Returnerar värden längs en linjär trend +TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd +TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test +VAR = VARIANS ## Uppskattar variansen baserat på ett urval +VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden +VARP = VARIANSP ## Beräknar variansen baserat på hela populationen +VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden +WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen +ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test + + +## +## Text functions Textfunktioner +## +ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte) +BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht) +CHAR = TECKENKOD ## Returnerar tecknet som anges av kod +CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text +CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng +CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng +DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat +EXACT = EXAKT ## Kontrollerar om två textvärden är identiska +FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler) +FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler) +FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler +JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte) +LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng +LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng +LEN = LÄNGD ## Returnerar antalet tecken i en textsträng +LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng +LOWER = GEMENER ## Omvandlar text till gemener +MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger +MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger +PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng +PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal +REPLACE = ERSÄTT ## Ersätter tecken i text +REPLACEB = ERSÄTTB ## Ersätter tecken i text +REPT = REP ## Upprepar en text ett bestämt antal gånger +RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng +RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng +SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) +SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) +SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng +T = T ## Omvandlar argumenten till text +TEXT = TEXT ## Formaterar ett tal och omvandlar det till text +TRIM = RENSA ## Tar bort blanksteg från text +UPPER = VERSALER ## Omvandlar text till versaler +VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config new file mode 100644 index 00000000..de69cf58 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = YTL + + +## +## Excel Error Codes (For future use) +## +NULL = #BOŞ! +DIV0 = #SAYI/0! +VALUE = #DEĞER! +REF = #BAŞV! +NAME = #AD? +NUM = #SAYI! +NA = #YOK diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions new file mode 100644 index 00000000..c327bca4 --- /dev/null +++ b/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version 1.8.0, 2014-03-02 +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları +## +GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir. + + +## +## Cube functions Küp işlevleri +## +CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir. +CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır. +CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır. +CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır. +CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar. +CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir. +CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir. + + +## +## Database functions Veritabanı işlevleri +## +DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir. +DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar. +DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar. +DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır. +DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir. +DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir. +DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar. +DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder. +DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar. +DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar. +DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder. +DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar. + + +## +## Date and time functions Tarih ve saat işlevleri +## +DATE = TARİH ## Belirli bir tarihin seri numarasını verir. +DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür. +DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür. +DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar. +EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir. +EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir. +HOUR = SAAT ## Bir seri numarasını saate dönüştürür. +MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür. +MONTH = AY ## Bir seri numarasını aya dönüştürür. +NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir. +NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir. +SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür. +TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir. +TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür. +TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür. +WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür. +WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür. +WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir. +YEAR = YIL ## Bir seri numarasını yıla dönüştürür. +YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir. + + +## +## Engineering functions Mühendislik işlevleri +## +BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir. +BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir. +BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir. +BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir. +BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür. +BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür. +BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür. +COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür. +CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür. +DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür. +DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür. +DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür. +DELTA = DELTA ## İki değerin eşit olup olmadığını sınar. +ERF = HATAİŞLEV ## Hata işlevini verir. +ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir. +GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar. +HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür. +HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür. +HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür. +IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir. +IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir. +IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir. +IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir. +IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir. +IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir. +IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir. +IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir. +IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir. +IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir. +IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir. +IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir. +IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir. +IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir. +IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir. +IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir. +IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir. +OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür. +OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür. +OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür. + + +## +## Financial functions Finansal fonksiyonlar +## +ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir. +ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir. +AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir. +AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir. +COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir. +COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir. +COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir. +COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir. +COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir. +COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir. +CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir. +CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir. +DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir. +DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir. +DISC = İNDİRİM ## Bir tahvilin indirim oranını verir. +DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür. +DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür. +DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir. +EFFECT = ETKİN ## Efektif yıllık faiz oranını verir. +FV = ANBD ## Bir yatırımın gelecekteki değerini verir. +FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir. +INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir. +IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir. +IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir. +ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar. +MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir. +MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir. +NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir. +NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir. +NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir. +ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir. +ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir. +ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir. +ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir. +PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir. +PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir. +PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir. +PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir. +PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir. +PV = BD ## Bir yatırımın bugünkü değerini verir. +RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir. +RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir. +SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir. +SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir. +TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir. +TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir. +TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir. +VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir. +XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir. +XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir. +YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir. +YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun. +YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir. + + +## +## Information functions Bilgi fonksiyonları +## +CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir. +ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir. +INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir. +ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir. +ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir. +ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir. +ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir. +ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir. +ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir. +ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir. +ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir. +ISODD = TEKTİR ## Sayı tekse, DOĞRU verir. +ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir. +ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir. +N = N ## Sayıya dönüştürülmüş bir değer verir. +NA = YOKSAY ## #YOK hata değerini verir. +TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir. + + +## +## Logical functions Mantıksal fonksiyonlar +## +AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir. +FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir. +IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir. +IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir. +NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir. +OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir. +TRUE = DOĞRU ## DOĞRU mantıksal değerini verir. + + +## +## Lookup and reference functions Arama ve Başvuru fonksiyonları +## +ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir. +AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence. +CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer. +COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir. +COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir. +HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir. +HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur. +INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır. +INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir. +LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar. +MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar. +OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir. +ROW = SATIR ## Bir başvurunun satır sayısını verir. +ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir. +RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır. +TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir. +VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder. + + +## +## Math and trigonometry functions Matematik ve trigonometri fonksiyonları +## +ABS = MUTLAK ## Bir sayının mutlak değerini verir. +ACOS = ACOS ## Bir sayının ark kosinüsünü verir. +ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir. +ASIN = ASİN ## Bir sayının ark sinüsünü verir. +ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir. +ATAN = ATAN ## Bir sayının ark tanjantını verir. +ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir. +ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir. +CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar. +COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir. +COS = COS ## Bir sayının kosinüsünü verir. +COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir. +DEGREES = DERECE ## Radyanları dereceye dönüştürür. +EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar. +EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir. +FACT = ÇARPINIM ## Bir sayının faktörünü verir. +FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir. +FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. +GCD = OBEB ## En büyük ortak böleni verir. +INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar. +LCM = OKEK ## En küçük ortak katı verir. +LN = LN ## Bir sayının doğal logaritmasını verir. +LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir. +LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir. +MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir. +MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir. +MMULT = DÇARP ## İki dizinin dizey çarpımını verir. +MOD = MODÜLO ## Bölmeden kalanı verir. +MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir. +MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir. +ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar. +PI = Pİ ## Pi değerini verir. +POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir. +PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar. +QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir. +RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür. +RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir. +RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir. +ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir. +ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar. +ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. +ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar. +SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir. +SIGN = İŞARET ## Bir sayının işaretini verir. +SIN = SİN ## Verilen bir açının sinüsünü verir. +SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir. +SQRT = KAREKÖK ## Pozitif bir karekök verir. +SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir. +SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir. +SUM = TOPLA ## Bağımsız değişkenlerini toplar. +SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar. +SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler. +SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir. +SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir. +SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir. +SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir. +SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir. +TAN = TAN ## Bir sayının tanjantını verir. +TANH = TANH ## Bir sayının hiperbolik tanjantını verir. +TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar. + + +## +## Statistical functions İstatistiksel fonksiyonlar +## +AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir. +AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir. +AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir. +AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar. +AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar. +BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir. +BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir. +BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir. +CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir. +CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir. +CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir. +CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir. +CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir. +COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar. +COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar. +COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar. +COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar. +COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar. +COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir. +CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir. +DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir. +EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir. +FDIST = FDAĞ ## F olasılık dağılımını verir. +FINV = FTERS ## F olasılık dağılımının tersini verir. +FISHER = FISHER ## Fisher dönüşümünü verir. +FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir. +FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir. +FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir. +FTEST = FTEST ## Bir F-test'in sonucunu verir. +GAMMADIST = GAMADAĞ ## Gama dağılımını verir. +GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir. +GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir. +GEOMEAN = GEOORT ## Geometrik ortayı verir. +GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir. +HARMEAN = HARORT ## Harmonik ortayı verir. +HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir. +INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir. +KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir. +LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir. +LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir. +LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir. +LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir. +LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir. +MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir. +MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir. +MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir. +MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir. +MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir. +MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir. +NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir. +NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir. +NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir. +NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir. +NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir. +PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir. +PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir. +PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir. +PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir. +POISSON = POISSON ## Poisson dağılımını verir. +PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir. +QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir. +RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir. +RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir. +SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir. +SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir. +SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir. +STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir. +STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder. +STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. +STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar. +STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. +STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir. +TDIST = TDAĞ ## T-dağılımını verir. +TINV = TTERS ## T-dağılımının tersini verir. +TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir. +TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir. +TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir. +VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder. +VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. +VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar. +VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. +WEIBULL = WEIBULL ## Weibull dağılımını hesaplar. +ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar. + + +## +## Text functions Metin fonksiyonları +## +ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir. +BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür. +CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir. +CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır. +CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir. +CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir. +DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür. +EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler. +FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). +FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). +FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir. +JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir. +LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir. +LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir. +LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir. +LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir. +LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir. +MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. +MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. +PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar. +PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir. +REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir. +REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir. +REPT = YİNELE ## Metni belirtilen sayıda yineler. +RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir. +RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir. +SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). +SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). +SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar. +T = M ## Bağımsız değerlerini metne dönüştürür. +TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür. +TRIM = KIRP ## Metindeki boşlukları kaldırır. +UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir. +VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür. diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index b616707f..8aa64abc 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -306,4 +306,38 @@ class IPayLinks_model extends CI_Model { $query = $this->HT->query($sql, array($COLI_SN)); return $query; } + + //根据交易号获取收款记录(传统订单) + public function get_money_t($pn_invoice) { + $sql = "SELECT GroupAccountInfo.* + from GroupAccountInfo + where GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + //根据交易号获取收款记录(商务订单) + public function get_money_b($pn_invoice) { + $sql = "SELECT BIZ_GroupAccountInfo.* + from BIZ_GroupAccountInfo + where GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + // 根据对账单更新实收金额(传统订单) + public function update_money_t($entry_sum_RMB, $pn_invoice) + { + $sql = "UPDATE GroupAccountInfo SET GAI_SSJE=? WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice)); + return $query; + } + // 根据对账单更新实收金额(商务订单) + public function update_money_b($entry_sum_RMB, $pn_invoice) { + $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_SSJE=? WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice)); + return $query; + } } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index a9745543..7954f428 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -233,4 +233,44 @@ class Note_model extends CI_Model { return $query; } + /** 插入实收金额更改记录日志 */ + public function new_warrant($warrant_arr = array()) + { + $sql = "INSERT INTO PayWarrantLog + (PW_GAI_AccreditNo + ,PW_GAI_Type + ,PW_orderType + ,PW_COLI_SN + ,PW_GAI_SQJECurrency_pre + ,PW_GAI_SSJE_pre + ,PW_entry_currency + ,PW_entry_amount + ,PW_GAI_SSJE_new + ,PW_time) + VALUES + (? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,GETDATE() + )"; + $query = $this->INFO->query($sql,array( + $warrant_arr['PW_GAI_AccreditNo'], + $warrant_arr['PW_GAI_Type'], + $warrant_arr['PW_orderType'], + $warrant_arr['PW_COLI_SN'], + $warrant_arr['PW_GAI_SQJECurrency_pre'], + $warrant_arr['PW_GAI_SSJE_pre'], + $warrant_arr['PW_entry_currency'], + $warrant_arr['PW_entry_amount'], + $warrant_arr['PW_GAI_SSJE_new'] + )); + return $query; + } + } From 4540765c10cc50fc97f8d72c32566dc6d7425710 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 2 Feb 2018 11:40:45 +0800 Subject: [PATCH 030/382] =?UTF-8?q?ipaylinks=20=E4=B8=8B=E8=BD=BD=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E5=8D=95,=20=E5=88=86=E6=9E=90,=20=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E4=BB=98=E6=AC=BE=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../statement_files/2018/01/20180127.xlsx | Bin 12239 -> 0 bytes .../statement_files/2018/01/20180128.xlsx | Bin 10029 -> 0 bytes .../statement_files/2018/01/20180129.xlsx | Bin 13902 -> 0 bytes .../statement_files/2018/01/20180130.xlsx | Bin 13749 -> 0 bytes .../statement_files/2018/01/20180131.xlsx | Bin 13756 -> 0 bytes 5 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 ipaylinks_statement/statement_files/2018/01/20180127.xlsx delete mode 100644 ipaylinks_statement/statement_files/2018/01/20180128.xlsx delete mode 100644 ipaylinks_statement/statement_files/2018/01/20180129.xlsx delete mode 100644 ipaylinks_statement/statement_files/2018/01/20180130.xlsx delete mode 100644 ipaylinks_statement/statement_files/2018/01/20180131.xlsx diff --git a/ipaylinks_statement/statement_files/2018/01/20180127.xlsx b/ipaylinks_statement/statement_files/2018/01/20180127.xlsx deleted file mode 100644 index e1ede5b18295d2fc53a52bd87e44b3d583ed7a69..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12239 zcma)i2V9fO@-`(xK#&kniXaKScMuf_Awfc~!VzhQCJ2H8f=Gu*M?#Y#U8+)~hynsC zi1c2iN>h68?R$fIkN4br&-Y(`A>n0bXXcq_XJ@mksX`2*B>;oL1cVrARf69dHSpQO z!CceP;hvL_xr3vn;KRFi1(9kh^}>*Vm80|U9hWFU49{IUtqY(}XY^yLA3NKHwvj58 zE!18fHsT9WjELTGV+l}tEt?zp?)ip)m&6RibI@z?rL?L<*=0!^<bYa~ZnxCPRr9XL zgfhVbOSWGEO;rel+;u<R7U>sp6HyO_C=U3ZU%%lDzG6<7CLE*(B2>I}hmKihPub?g zXsB7iW_(2ItO1!+hCH+MYFORni=8|txBpbXus#v^I5C^&nVuNk<;hhK*8^dp)N@}* z(>c01;h9&5RpvB7c1q4MU+c`&YNK-c`nK#*&yv<yEv4H+nWs3+Ia+qkAI_&H=XAZD z6-~)fEUB)&lF{O%{h_1CHcCTNg%oTvzx<k*kbqzlcxnDm1kVBpnmAh8ISC2ke-}i3 zP_GlF2w3q9;oj*R#X;oNT#=Y6HEU@(%!uS28pUAJnI$q(5Q@TOg8tjiH;t0vrODfC zVLaE!l?xZHlT!rbpY@N52t4QuA91<SCp(c}VX^+*>_Qfg1&8A7!?U=yAmeX|tO4si zI_rroVw8~A37bBzY!YoTCJZGnu~HvGl5dDEEgFQ>+19J9_U^P#Feg0!{2rmY_mtZr znZ$x4j=`8)O#`iClm=~|w>#D$rE4(lDm3Fg3TB?w;8L+NX=ZQ^^Trq%2|n;TGZFc^ zFaLw)$MM)P8WwedBtw*bH6b1weQsm6DZumVME`^h4bbBj%E8{*(%#ub*X^FAlhG-^ zqFVrrAPPHs<Sn;ot1NvX%H3xoICL{Se2TfkZ`4{;WgWS5^2~4;gnVx<nH_VtzkXlh z<}H*SBzn6r+gvgOl(eZ_<))Tu<vPQWEUuu{CP@fI7OO}sIiAx`;u`WjAG}9!j;kO- z&*ELf6)JhbdZyhyYv&JHt_+5PPN~Reez<uOgJSW7k;3~WmWsl`Q40m-pZj#Nre(AY z-#lh|FKh0R{P~?pJg*0yobI#kiSv4!y7s5%`&e{=kE%lJ&c_TKpHNO$V13uebEHR_ z{cj4M`Y@=3ULf)0I`e{po=n7ccjOReybt#Nw(_*EDk89uQX@Gi?UGZy3G2~8l}->$ zcb=d`Vo_zA`o?<0`=)CY>9utx9){BHwNiWJs}_3Ju7;11sk`^WG)87*y!Ept>#7_= z^zp!ROn}>^077zu{t0-<@6-Cvd-w3Dt3CNZ{!ti$Uhz_BtR9_5qPt`Kz$uGJ1T1q{ zveQn!L>V!j)H~HG9FbGmRx}yTQzch0G7wISkqmn>t0&7cFwcIiS_ef=O>?a^gNgf% z<DXA%``FQKat>H#m#D(s>Nv6)K8jxnjWad56#TVQT=9K)<aMT(yJwUO_UZL+Q__)+ zD(c|O-j35A?vQ((+b71m^VP$3FcL8K4e<KkbBq@F??XEwC+j~QEiH7M9c}DyJK<gO zG#Gwz<1@8qhklwH!oBjvN|*3cI8uv9&q7Yb4GGeqAg91G+-iCjY4*zUt0A@YV6nwe zFe^0|2JI3CJyEqHIc9y?VWji&4Ww~-tm@8#2S$2*vbTy3=V!xdRu)Hws=RD>rUNMK zr|R36`))ZHk9#gmH+(vKo6~YCc4@_KX=y3-?W2XIQBUb;al534?mPQJ<6~E3ZiTcv zB>AL`R!3hP*xqsQc6D-EnSY)9On*Dz)*Dxs;*E`4uJ*=5pHIfzY@JrNlau)zmW_so zhHBl+b&^${T`n>l9~~U~QdLv^y4G{|duUw*V)V<%_}CXazS6!E&yBsWQ;18)3(H>- zsmzDlFQ<k{saBY4PWnQH5Z4~A;_O&tkH3H4tA3u-L3MlxkMmgF8hu_XJK-+0a&kO# zJC#1cq}FwF=6PMtPK0b_$Ih<%MzqK3*RGA)+K1Z?PEn*(5h;gr6C2}9N6VLnWDh4C zNHth4y*p`qw=+g3lya2i6y|_%TZ^djA->p_BIe+|-}d#hM&<B)rfQO^ILkP7j&_o@ zo)Ged3N!+-e)W=OS5sbU(lgn_vhOoGAMd(&Y)$U1Fq^FVJGD<(hgv<DB>6V<0$ugU z!&f#7)vUMI4Q6~s?Xfu<Iajmm=<&RJioopk`#KzdMieP?U?yc$bzG`(1@Fz?uMx&I zrsv2jDB{mOwm$36Rj&L1vrTK;nS{y9V|?CP!0~nW`gGa|M1ULiIzEHtBRzX?F_QI( ztp9ZLjLxiqHmNQK6!Rv6WLJ)v_&kxE!sM2d<{e}~wZIbQMMHe4r!}X8e%9@%^cOcj z3Fuh+vy_%?C@Ayv3w?W~{OZ-ji&*!pi!nDf157;$zT!wDWhL{vh@WXB3%dj-=1-k5 z^MzNE<x5X%X`VC2sVFgP{@Hpq^WkAzeX+O4wsf~oF6{1*I4t>)ogZ=IX=-MpwI5N* zAnuCHabv}TzW3U~9BS;bMKOoZ?1Z$arRe%QR9aLFZsG;I*ez_fRhz&{TP#+6n>O&8 zq;IacX8<>f^G!82*8B`V?bs!LHqjjq@mnlgt%^?cR7ul>JbQMU8cIIRF`%*x|BC`x z5bVhnxuqBncjtM3TLK+o`uR1*_LGV5Ikpe*XU4+s)oWdvz<nRP$ayt#GB3X7>C}OB zQ6?^a66~NpA7G!-vTXcHQB;?gc?v4R9lhN(9VmUFDL0>BCL{P=1u7)CxU*`-4Bizo z-J_`phbz*e&4r>vKUI1Ryy1mtPo5_?wjT?xw%}<(V?`Ay!I}<dx5%MU@?^z{Q%N#x zO=@IPN-;IsLeF4&QEKiF8e7}%gDva-_!6XZZ(7i*p+whuX_R1KweS9=cn=HRG{wq{ z>I;8nszgq#W4iU(`}M@z?jEkbX5f!gs+K-_F{clULQ*ysb)ls)Zi6M&If+=H(K6yC z-HZll5vxjAY+0h!xU~DDeQc*AUwU1QOgmk8g6PaRm{&7USi7(H6G?kQU3>C}@S5Re z{?+^-SEVwil(X`tZiUaK>FC7dosc#6lgCKMG}-$pH@n5J#FdCMe|)I!{JlH0vbjh6 zi&OWM^|$5N2gdS6#{Oa3#)Xn0yjPspmz?cPu`auLqF%gZzWu7ttts_w(=_j2StH4^ z8kL*vr9IyZ?GZ&od8k|1@@c8ZOwV+v-0DWpgNulL82JUPl3vcj!&ece@>bL);crYH zP35QML<=v8hMke0Ri~<9`t(#i(|&fl;LQr1hL4lZJ<d5v$NAT)>PA<^zWFfHUlCx+ z6fGw*VM`~Y6*qlKAL>BjoE(Yi#+cD4&hI9MURTd3$a$KM^?Kl%wU@}3@P<+8uDoKP z2J%z-1$V`iEWPk>&`wWv%a>z53msnL>b273WFDI9UIN&5+gY3Ek>oEsd&&q)xE|Dx zLL0gE2}FwTZI5K}NFGwg3B|9f1?POJzaBAG+E4uf5mT&tk@?GKM)w;^v6%+r3HJyJ zIQXFnsW#z3vDApOX`B^zF6St*-c>8gQ_Iie*nn-Cn)}mDH-I!VWHg_2>IkomjbJVM zeA~8h(4o~kWG&Cnv}XOWlG>wVB9xk_8dBPNa6o5rS@NFvn;AG1L7q#9YHV=h?D2i( zX)IHcB4N@wGCk~AE6w^*-?308n>AL=TqURR1Ke*-hcdtQaev^DZ!e>8Oi5Ddr{m{N z+)m+U=QZRnE{q7oaJFDr3KMxsjs1ujNZ-;@zO{+|KAb6pvoTl>%m1ipmxvmJ)4%T` zVSs;s#p59v*xq@$tN1Zp%1arJvB=r^eu9Wtqlb+5@{&7R?^|A&%o<pV#^o)VYqJF} z+BP%k#muc<63CS(v(-7$mEjiK4$rCa*cq+kI$83vusfn;SfRL^`vJ<6UZWCb{epe} zjtIZ-^*AE%^|+?;yvLIixmRVV36rmKJ6?wQmwo)IQq15j$od?5KychkLnvfx!h_si z3bTjH%RKaF2J@r24F*E`uMU0~HAM50J*#m>Jb&@t&<|3Q>FUc`cVRWO@XDHy-PcaS z?N%~s<NJJU+#$L_nC-||FujbzMIjaH9&xal-CmnE`d<1VZwZvJ)*pOB#VpQ?y7Q?G zor05EpcAdbvgdua*WqBJxlmk)fx+|s<?#1o6-^8@>1yc3M4G_-NRhC|;9eRk+w0GQ z^;ylfi*4I&1V7xRrIewb@Tb0u+iYlW6z}Y;v5y`Rq3N<F#i+cw8_V;_iP8V4yu4C( zlje@fmOQqS=}*#_68lU)QJ7!l9uccNmNoNe4Edhf{6oPuI_;RQ49&CS0Ah7~fOX<W zzn6$4{}Py$;$Qdj{dyF$f&}$lbnvx4=!e#-%iXOvZNGjPyY8FY^!D<m_EVvJ^e%l& z*<Bs#+_|@!y_n$X$nuE(sMT%%lf$o{-bBRJs$HoWg)8U3G_Lz<{xZ;lT(}ON`9!0W zzu4qaXWwJqUO$+y8vK&z=uRwCh3DWa(YeV)R+B_lcbT3edNG|$yC4m^f%6||G>xt{ zY%B&6(a6#oH95B_`?g-N5*4!%=W=$Ir_&F?9Wk=Z8!NKv8Mt2)N8GLp7#dzYTc26d z;o*Eg3-c~cmuN3WTE~K`m*#4jVI24@okrz+0{XMPTCPLHHR%uuZCeh7JLMe>rJD7I z_9IkuAy*|?bxS;(N}zL-+LY^;rAf%%nM+af7h<<%lKWzL$8{Ctsb^n&XI?87HZjVR zSJs%QkePCuZF19GFGv+A<Z)b5HM8kr&BQo7DMNefT%L6eFB4ao{w%dYVA{}P$A2C0 zN}?w?IYE%NOVE0)&~{}%MXZ=XOQpM&(c*p<_?TSb3B}Is13UKangC%1JLo%Y+Al{L zBFj9J3C}2JhbAjoZIaPBH4;5h87L^&$WVVOk#T+Qeqn>%g!tkH(=9`tDO(+sS4^o7 zvXuSV=2nCES%m^ZzRb9!C9Y-gG^r*447cwv$8=H(8~TE`$5=6Esqbx;JGT!~JZJx? z4&My0Q?Be7s+sAb=_uheGR#B9!P8b;d=SGqh@_;>)cCGX5(?q8KEBQ#Bu6Y;30eq> z^sLr9->x_%#B^cOE_{8da-+tG^IdWDK~hd%_%XD+v{JiopL*qybXz1#h2Z#ILt0AS zgtga4N!T-Covc#E3=ifrf=v_nCI^}to2C4_B)N#(z9$E1*M7_;H!|dLY)fGOLO80b zrJ8gp`ekOQZO9kq59tpD<i^MM!WRzj-W8Tf2yYuJuSh+4bx#dORQh00#<vV<$>72t zTlE4XF6f%*$26p0)XyF{9udxWhlNAS#{C;vraNQ7=(%v2U8u;SA*{ef*_*3Xf8d6a zjsj*-^?ZTr(zSCZv7`I*vtwh&+b5?Ry&l+cxCyYwrI7fi0-f?_f$r>PXL(wgXGQ<q z21_f%Tw9Q2$7<d>he0JVKnL<43<uR0Mp3+$mQn91ru4;4bPswjcBqd`yZTE^QYH;x z9~%lh)h5u>wY59D_iog1tg&jHb>~m<)m}o-2eR*HhaPv1TO|}-ebp?KOFEq#kaWY> zXuzt*HSG>dbbeER%gh6-*y}fE-@dtc@m;QUL^@6-A=VA`P`6){%yN1B(=*YLn|9%K zyrR?C21b(Hvu-pJx)-#2t3@Au+pO2odnVGfz^$6xeqWERg4-%jdEcvL@5_6^iVsU) zLBawl$S?65I<GWmtH}wO><6h!tC`)o*`e+6Jj-$44Jrmma~h(<Y`%WH<|v`Drum42 zN;~1AH4&H8sLOrI-p}TmV2h#L*LTQbgBwu|cEaUE<|&hlCW&I(ok8ODpRcxS)K9Uf z+FMJ~a9)Y@R#sW0S?o)FWo9kAhp;U2>bUS?rR{C{V59gK(QhVc3TNrjit4o+dPxV) zp`tbMX)n2TnF!}h7!$pdCyF>q_gIIn%J!_E?y{apg-?V4o5nB1{}e>3A3=0=aI`gZ zaInR1u)?1d<9F%-t|=cYlfMvRVIe(PFM7k%UsY{q6*CS;c9gvXu@${<{`isj#-zwS z?Z={`$zG$b<41jmpB~snMB1%FLlOuAj7iOp^gd2Ka&sfy*w46%eLIYOWzMj}p01WB zbcJg)Lr46q%>FwYd1u}k`Zr1YLCu<>@rIv^uy1G7Z&Gog7*3|ZYUUDxeqJu$dz7HX zIy`Y%{o9}|htj~tFy%i+LNAhq&x3sj`d+z}JWLalLT5XdxEsC<2Z`J}q>^$;;oN9W z$4-47*!gy_wng~|e?cTff0l7DDBqF)dXsZgj>#4kelMEyMKNs-z`*n$zwcrEfzpq! ze16C3$JalRr@WV2ISOfXO>~L=`Snl98ll#_WZxI|63XG@6dzDN6nyU5&GM;lahXF& zvr5&hYxMrUmHBdi-YdRXXFB0_^3aL&SvhwiS5p48*y87UUaB*a6AInc{fpA=Pg~-J zr`1_(%A<4`olBNYNqb+usO)oY@+sH6<9lPco#1X2WAAa&Dq?qV=XqV=cVjDx^|}jf zV^EiC=^pTQQx)P6UxkWR-Ok$m{K9#*Z)8FWvg-(n{sD2R>sMbX#yA8QbsxCTXnOC9 zKU!P4yGDY?X0`o~fL_3J;eY(ThyE`HIaym;Iy(VdcHm9qluF6BoGvycpvQOgg?DRE zM58btN~I?cdb(pe9}m9TS#OPm1&c&UAsw$D@2NByU%<INx@Kb6B->h<rO6W2*C%wm zxg(U?aV#~07#Z{QbgS8&TR&U`wzi`O!$mA6DJKKoHOB*Od#T1pEujvsJGHVNSD7w# zr0f<^33VW3WRJHU=;)|cWSMJ5qz|2UhQBWKoNRnuK5l87>M>bC7)u|zc)xW!nF_4& zsQJU#*x1OUqT=Y$@%*QQVWGgH@r%+`2#<$u$19;5q548zJ|~{;yW96Rzm={m9Xq=2 zEbP?A><D$FR_;99Xc<43O0{x{O2gax-O17FQI62!XOolf&E6xa)d-Kbdq*2nCMz{Z z9&e9!=hkduUgrEMd(>G~)j@?g-dJo|>Y0f9cH6}M_;{+ecC^O(aC0+fMq^>g(f#$! zqV|rlqvO?wJ2T$LYbS@+JBx93byEw&pP$<wqSh5j3mq;w7+1foJ#cY3>7DL*HST#* z*JIjospjNpaqjb_l;Z(}u~E(2-Km3!<LKQ|nou3HduDFRhS$21q2Bj15FEzWim!5v zN!@>-e7IP@AH%I~ryl%9-A*HzxiwyO9vswq=L|ag0Tt%iKxocuFXPpj4L>38!`AiP z+ZNd;6hW$61VOD^5-`yrZ$h-y0q|kef$3(m^NDnkww!|Av;eGx^_pD$+|*$jUv4Ag z65-9YZr2W#@iw7qHkF$Lgpiv9w$_-qOAw<+))?GnpYPorFKOlKnH>nbvPjW!US6Gj zk?PmWNG(37j3b0R5w)97oJH#iAq<le;+ZN`L4q>k?4zDjK>|nblnK$Y^JDU;%1!(z zRF(23)8k{8a1ugC^KNtc8!9UpuH=gZk=|?roj5@mSmoxE&5}X~rsAwreIB3hq_RK8 zI|2;dRM>eW$GN@#@>^DIqRAu0M@SO6>G8(DG@cNQNtvl2inIwLmunseIL`srrm{Fc zt^t>jTC}LtdKvF;9d=(UiK<}wH-&@U*M5j~Wd;5w^}U-|w0QH`x2*A202aQ{1;VcC zON`xk0D!mZG3s0UZm~o`%UeGU-|#Q&qyu^-3@*IsP^nD@Ow_9!AkJ`?`Qbw~n||fM zFHOHj0-!v<4|IXixF1cfyDg<2OI7W@H=J|P2wUFieOibRxkGSA1+n8Rau#&;G5yi^ zobui?^|_RO#rpFRUWYVdYkRd)&6^i|X_9U(ENg_>pY%SxLP+oAC$<c_Jwmnt$T$&| zS*jB>Bncz7m5)TY2*hTv7q$hYIUTvAO8d=x=nF`41)PY4XF=8~XNgRI$P|$Mc!u4> z>*+sJuS!b->^<P%6Q7&5cjdw^kOFGpU;^JEYfpl(YkwN&K%R3Dy|z>bo4q$(jNLb1 zLkR0UkPjuILtX&4Hq3)e^VPwVa%Qb$ollp}AzA6a)0)}2g5{CG6C^+8sCbkxK5sOg z!#@<p2(q$$KqRck1)77207lv7se_3=%H=?M@@V|RaP&^{IH<Pw=8k;5>Y<r+m)}PP z94%34-#8`p^IE2ia$r0I%-y+_K%e_utqZhfoBC+Hsf`r=#rkG~TRUj5+F`bJS5%z> zgc<5&qrisLlOWlHlMk&C_$^}PAgrA7XVUo|fRMJY(KrrH8cphwaKE&?<P3$7P?!$; z^$r;d@Q^VzD71c%3nXFnOaUSYNWg~${jibrPH3EnS)g4l%=%89HFAm-!x-G9!%8e) zZV9^2CSnD?)4Cl7b5zBW%a_}NDu5?JFgNz=f#r(UW&?keZ{BCfjHv%^N{V$JfHj_@ zJF|zE@j3L-g6TrEQJS_c&D=pS|F8N<wh|zDod9e2v?v%J+!d`(EWfW14HH8{P-f=) zYBaFRXh5QSC9yY=ffd6FNG#&|Az-y$NXv8oz?54RaG$OX4Pto%6vQHcpn(DzZbM0k zyT}UR1=~;}3liWyBB)lXTC>1KepV!nM16^E0GL(DY*V+_2N(yG0Qb{`(qDT)5O#nM zyg3UMl3OXP0uJWLLu}6xwDty~&T_=zpC#*{FvNHKTF)Z+gRA?ojIhfnz_1drW~8W6 z*bp4US&U-TW)pv)Tx}WM0(*vTXeRZ`_W*Y*(N=0JLdx`jmzD~|BCwyZ8)fJ~Rzgn% z+X0c;Q1}`d<nn+G)Z;Tg#k9b(*{^E|Qi8Ycgursy8)P|hMbxqh)-{6Va$%WGw6CpF zp-4Rj3c#KIJ77OangHvYGop>W!Cf1w#K=b>-xC4g?hQuLpF~lkV}mu3jW2>GI`OfY z7-Vy4YzF&f&j(%574%PwqL(=*3CoOlO>GeX_EWaY*Fk}hmaMvv`926zQz?vr70g?V z;*$U&^#LWw8Bs8xgcwOIe^CMr(S@1^q%|y7yn*Ec@!$UPA_#9R1vMyk5dIPlPRxZ@ zUeI;H50m1`2<c`df{TDew)vUntbx!V&e4I-W6J{4`WF-4!g47BOo~wkD44hw%2^<H z(GPFgwm2m7TUeo%5+yKXBY!VoQ34?I^v=KZG&%$B?~|d*(n|cLS||v^QoH~~pEJos zQ8*l<AN|oR*$)oPMXv+IA)*(nKV0P#y(IyXQ_M+Fr|gnIu~VrNKMzbJ!ItH+H&R4O z%c_OjX#JG3(NY4K6ZI`OnlvvDWuVI{uBGcDP_XD%23U7i0+y-3fdu$oP~T9N3u>gK z2A`+x&WHlA$LW#O6%E1#c&QV4d2bmEow4B%R*^X;0kcrB#Oa;FmY+*;P6t2D_;~%N zV(R1Jep4}nz#n9I3GJaXN*uy1Dtx?z-8wf0PC3t8ECO`R6s6_`-_&AYkHw2*La$i> zHs~l=s_<69@<3KLmsd`8{0I%8BdQsl`>!Y9DCI@m`Pkm{yo?f#SR<S+QEBh3U=l38 zpR!piq&NP2EK(bf@vkRH?clpNwUjz_wT7aa1u?w7H}5<}{A;|lhMyXMIQfrdL@}~r zc!8POTbvP<7MxMypk&Fy9{Zku>wTvW?m}#D;^+u1d+cERg;>zglA5n35)-QIw@97? z%LAgXr5LJ=<qT=A;fVD-HEcr&pz_FcqJbC+q{JbaeTp@n|35&-%K(fyjmfq^-Xgq1 z6eU&K3rNWu=xW<qflcxL0ICw;MCpEjdf>ya8~}vcT0%>A+X#ph9s}a5zl5Okz0{zg z$KIfVUMOfT7>wOSgDBh8)gq(Z{IHw7v@S{=XqfnY&J0B5fk?$6wWE;Ci6|_Sv?xzP zOu_LCyF@l=5n0KPdHUniv|!`3C}tja>D_hf$%zN!-OaKXKHr=33cSSfk5*5;vjM#8 zm<RF}7|5dg`R7hK1-PfANM*A~omk0Ko&{i{M^swoZU!mgGxG=NCk7<ys_QsCJcFwE zBr$x!A}EjzhfAYi7>D&_d3?<;kp(kI_tfqwgZT19s)Pdodg3$b)Gj{hm5I`OeL6RH z-vi6}WNHVXwtpEkK5LZGA9v|<PJb%|X%HMfhrH$23IW2^*xU>&z)$c@V1oZ-s=*K` zp4(N@B={!=FWCIvLLZCQUeDDBlH6LaN9(SnsSBZ4_v(>*!@Eu|D~p_gus3fV&({OI zSb{QO%U+-{%t)h>g9atw9cOgq68OAdFNCo4Y`h4)C#CbY81c0&lnS3d(txa0yQ3CZ zsb)4n2`qRutyD-ufUJJ4R2!{=rVXZ>5}iXG6pOu70{Mn+nKNGZvU^Y{V);sQ0+5%F zU;+!K@sI$w2Z!(i^0Ns>@54TPw@oWeWf;t3shkajy#!^Kx@SYWg^~$;S^Ugnxh=fF zPi}C^KZb48N&mY&p*;FXRWj8aiFO~H*Czt-A!IrR-`x?IZ4e8u_}hTXB+rX{+r6wz zbG)P;IjF5qGCmXtPvK#Llstk)iS3})j~St&2=<~^WLR?KY@nMJov^v^KI8Yr+axaY zffuw3{czBD^_BM*@dAE;08TptFdoB0lP-_j`!i+eOe=j@4awDm1mEQSbjz5Ru;+mN z*T|@W?v6lr$Z2=*fA6jUbk6`~_pp5?me<pex103>iz?HKB0vm4?gxt^TE(h-82q~i z<ZdIxUg;ppu#V^1W8OQHQ-W{GB(TTya%`ZYG@*dQr?$h=DE<nTC!KK%SCO9wG`_u% zUjehA<TFCm%dtgFp2q?%*_q_nV@J*h`uw}~Gtv4;SpZH?CP?=qC~Osl)4==M$aU%~ z@J?(+aovPC`Ka~1`cdb46JJE}2vxiD)nZ`UY7qUOf}09}b1|Iy|1|td7{2$}aO#rF z^PGF^51I~f)6oEDqCBEt8-Q&jza#(4cDk}taHgYA!O;M~!K^C*)I`cM{2tinad){K zh6BE9v9#eME84`Br!pJJp32_%Q;DC4=)X}p^&R=TlIhi|6(;ygu4s>_%3lL3$ts;< z^fzoyjqg#JB*o^ZsIDu`NA1CzxX1ve0l)(!PyH=aTd1FrQcoRW{{I_OPqpw=qtG88 zS>r&UYKkVPV98aPC#BU!Kr+2B02TgAU>8oY)MtfdZn4Wv0Q%8zJcOsS>OY~h{SnxG z)05NjeOb~}W=Vl*Lhy@ff14(Sc#`<eZAxMZ;RRgO^L+r^!Sas~V7cW$xm?^|_!Rf- zcU~e>llfF(PdIZG%nisi12WZeU^q}>YG&YoLWdh*n>?_b|6ubc^@Y0-klH9ou|3($ zRSY1pC<!bFl3>3P2vR;6-!UDiddPqziam|k`EOs!Df~E>LvOwba%4sW)8$cHgAZ<u z4h57TLEKu66x8ULU`;q)q1GvdCJh(DwZUp5+^_8!X0A5kRUBOb4IMav9Z?_#4su}V zFkrc72Nnj=X8e2vs^n^?C)n&llACXEj?7rRj`U_9U`Z#afCKsBF_5q^Kt_a$qCjv< ze179=e?4~IzcU7Ipj>fITN&UH9|>F~ivUo-bE+WbrvmL?3dBH2nt;Kwct@Ig{P1-^ zhHKCUmWo`JJ78LE6oEwm5NWbJIMI)UrJP*e;txsO{Ze6bWrnkn2k>DXhIMX%0p$=r zCkCA6L>z!`BhM*Q?-y>-_@xCqBtLtqV=vwAh>+@;vs4DEeGY%v4zY97p`83IY2XNz zFM!m)^6saKejx_1nn%;1a~n_vlBwPn8f0xWex(3F3+BZ`3j)gAQ)qR6K^sSb<rFL* zD@${v0mZ&|-uEj4;ysuMY$PDMr}5_f8SmWFDFLW>xk8=zcHgVVuUQSEOVl&BWI!yR zXh<`SuZ(E{Nb!X+=2X{dc9$9e{wcoI@LKIG@8wgY91KyIXj?o%G*1bFFN^U6N&86< zgJ@eUXVk*4{yCRRfSjR~0E+G95JN+CiKYWEe#-dZA%6w$d@M-qe5^q32nfj`oNUY_ zNzl6xt22=Kzirafg^J(ME&t*5<~F%3P|K<MDbGhSu#)i-I-=N-9KW0NB}CZ|sJiZ+ z<$Z&9p-7*Y5`0?!`c-BI$iaa^*(wMP%p^uu{4x%#X@fR0EGT&$<V^XQ*kM>MDEp18 zDAZ!b0tChf0UvNbU=hRz9L)PO;162ltj$^m%QGDp+@4<im|!gA&j9HbAchHpoSP_+ z@>bx$5um;R!dL%uodtp+K%AZ@@Eq8sMJby;sy;H8Yb+0A&&w19>hVk{5X30mC_o41 zmkx<QnDsnI^6*n#d;d&m{FrffFm4t?;ES)3@zVld)#8y=`i1N)uz8$@{OWI<y21kK zW+H+K0~H~j9hhJ2$os_(CZhCUCbQwF=DR@6*t0-9N{rm+UX_qD4T9yNfk}<i1(F&T zuj(}6hdAB+Rhhp*YLlrtINVie3~Bxc7Ycx?^hK_n(u^cfXU}a#wh;m)Rdgnh@dGeX z%043yC2b{q+WBQsdB*yQcWrwf+(5g65|5HQjtcIHqxxSyWT_AP^7wJqSnvzp(%w7j zD18FUeRF#+z8mF?uHbofYo7e6_AQ8IO;9Gea-JB}I!?}9lq~kP(ddWX`rzSDGn0)h zNJk~jqOQ63F_-E%Lk_7k<M?Ne!RsxU7ilpEY(c^_)~cN8>-h`M2ICVSo*$lcbepD% zsCv(GZi{bJJHA`yG50#DbITD@dzmWdJ&Ug{l4s|$beT$;NCLLGw6Ms2+A?MLddb_x zCx_J2iJ-0hiLdWty!haNCW~iyP2FujG=ZglY1*O5=B!EM7d&9|28nPXt7QYFgtJVv zgIK*mT3jj>2)|ciQM}xEBiliY(Mq|}3;Pew<h^X#cYZJ(0o!8F9rz3-%@zl90Xo=I z@j6O6etLsA)iIfWYvNPy^sytpKZqlDfJ>e<+rwMQQFHO>0h^M1Fp)R=O>SjCleoBV zg9VhgqjE(Et+p(*09cg34Oj%bDm-(b0u42LGs2=ItW3Mh7JOZ+`G^|(oJ^cETGOrH z)0^;)Ohv67;59lEv}HSP610BAp`=uNYdM0Qi-Y_yl06IWLP_^87x?tEIlaDBz8$%= z$A(cQn_o(h&)(cAL`Ne0dSkLiSdjLNO6Ox7y+K_zMBz>Bx+xEiDEW10-1g1x$D|5I z9nz+aT@pbzr--nVA0kIZz0+d$h`DzZS#M}IA5zOzovImha(Bk&<#j}S((<artn2tZ z@|?VH+PqDd*2tpd6`~E;hEM~TQh|s%6!*b<j@*ZRPKnEYR`OZPqcY8~ZSkvSQAgrA z)j6Y9bfiq$EqkgcM|Y_++hDwu%xt>RPupZ9+It^0vy4U}qIPN1j9Fxu<GWQffDp2; z@!*Hw6_3P+5Hs0BfDfV6!m!E)sTNJddHxHEYjdo@8iey(O1-{32U`M~(-G{l3OqZC z&{R(CGXN4w9*lSvpN~BpaC$2lJ%cw5GYL53{wS8`V4sL~k1bdOh(=_6PB5O1fFMa{ zysG@n%{N6t7&R}?D<K+mN*?5z4pgPk*CjbOga4OV(hC=g*s|94Kh@>beO=q1U7PI- z9k-XgG~aggdANw`cI}9a?3kyUo7Y~?PL&B_WK`zTa_z~IO~<}7a5Qij*AYk+fymt` zJs6HiJznXEaIHPsxGj|OW!J^^WFf-E_(%wUR<c|&>NX1;h1_4mpSBSa(GvW1_xkrc z#rV6||K9%NCidUOf4_E%zj*vtlLrp1e!GVJcfsGUjpA?R{?&|u6P^EZNB8do{C-gr zf4lUrHUJzd{>$*6cTN8;{rf30{xauZEgQJU`rod0{(Xesk1+A4&3`pTz#RMt|2ljA zyXf!ddiXQWzZwPfRP^^#yuS<oe(;4q`unSi0yqMC|Hnb#-^cl#6!>GZznVG#2rv%b ai2pb=(^NS_g6~NN{2+ipJrcnG_5T38BwTL* diff --git a/ipaylinks_statement/statement_files/2018/01/20180128.xlsx b/ipaylinks_statement/statement_files/2018/01/20180128.xlsx deleted file mode 100644 index 63ce48dbc6cb30378e284fe488858d856a853c32..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 10029 zcma)i1zglk*EX@h(hEp~EXYbIsUU)Mcc*kH0!o7*xuAqJlF}d{ASEp+(kZcYNOwsK zy#Gb-SKs@2?)&?OADeS#&biKY&YYPY6?t^fH54!yjDjj7sDScEBLZHV+nT93*xEUA znAtj5us?rlQy8fz-@*xbwS7)Xf8-Ly-mW*!o^cx-jH`9cmY#OPbYGNs^K`q%1rhvh zV1B`KI>1Ej*`XEV_R0@qCrP(fW>Gdpft3##ggv|lgNn(F@9q+~_Ubs9h$x%Np9LS% zkD@hpU60w(4RKa53{huj8E`g!=|M^>);mhcjF&+w+Sn93E-4*eFE;M2UE!cQe(zo{ zTnjBMR|Sjk!Te4Src>voZhZ91$upDm>?fVs!`)v(`5sJ7Pxf`?_#KK`27OclvnU^m z@n1uINK7kvT&y!tv|#V-Hf-}G`A)qOrSks%t6g{re6bJqV=XnQZJ_FuA?2NPX>F}g zT9>0*b6-(@w6cmk78re0j{_YQ1?4;Nukw!w;sOX7Iat^@a<C&G3!|EpK6B!|+V%`) zJ{q2ifQTu&ipta~T0RhwndG%1kq*LI+{DHLiQ~D<QY;@WE0<1eetWzd!Xkhp_hDTM z2k%t@u3uDmz}ax<q>JXT&}>1q`QC~t**g|<nDo+f+=!k)!{tPVS9^o%dx>3l@FC?1 z-+hXoBwEWDQI_WW^ECx0YjSUH=mmeaZjs*^I_jOJO~`C(6jnHiWj0U7G>64e8Zs*? zOQ;*95%;dyT&QD_w;B(8Fl9XtqFqvEl7D2>N$C{gEn{H7?(Bsz8(BVF(4^8l6EjUh zr^J?|FRopOio`~n+3?0ZV7V09zhOfH^mr(4`^?GWnUj%*o1KND!4<!vy8w(Jl1C>v zT@SC-TKGcbzG8&KG%`GVN|-`58_a9poxixrvIx@)Ug<1dntt(2%AQB}p|}<#`tU=x z8E*zC>API5n_}uC*F{+JT}jm*UQ}Yy5_z6Y2LkORrZHdApc51VrowP7^G~h!3B}l3 zXpT=TotoacQtGoiri#9WN33D$mE293{9s>dA<Y>SwO&}!Hmu=q{P7y)vd7}kJ(Uwo zlNFk~d4u%H={|d&5nffPyC$BEF%pG73X<JN%^4B5IC2I8S_Ya4u+CLRDhp$MDCJ+1 zVR|xQyvL)!=CVGX`~fvQ1$!@V#}3zq2YkR+P7X}F?$~0)aDG;+9thP~Ln-CikUu2S z+-q&@5Wq`s_-y2%|KLRf-wDo+xt67?{!7u+W4jRL$wfhL?RVck*V+baBY}s_f_wP@ zLNbH?4S2|(VQpe(heTa5tO=)?6C$zgCD~p#wI(X@^$i@HvLPxA&6?otw-GCq6P`&L zn(yWe&#CDt`WDJkD^fU#2)!o58xpppB}9i<V-%=U7snwY5$MjKVXkyA3482gL;n3H z!Xmp=f!^&iESs|V?)}$s#zxnJ=KAkSH-<(^(c~Xv$Q7PaXg|g$$C{E>k1(y8x%T4- z$BW<;9cj*-hwEr0pll`Z|IaaY4fyuC4TqzpiGzi?x|73`XOA6`CcV@%c&*<?<k?rG zb9jE}qUjwlOeG&AYaD|m$-vAZ)=q8RRGV)pMPCHhDdlq5U=(vNHsf>=YqV!jDK;be z@tC`8-8*uvy6gpqdXBA#SZ>Xkmb3Fgp89av*|=@^^z>;@)A`t3$L_nQ+%7NHXODY3 z-UhVU8jRQ5pNF#BHdGw>O^w;qJ1;LZ?dmV71W!C93?uYDpPiNC*yFXe?Fa~a99Oa3 zyL{wTRd%P=@o0ACusdl|fG;-ED0x!2MlkMj+S~fE%l1Xn=Do+Rgak{{w%f(!_RA}W zbGwJrTN`$^uJx53hhO&Qm0ewzUepR`ewDvG+g$Ei_SU~xpW932AaA&IcYMD4ePC~@ zsIUIiW_N*w!cgdP_WN+=AbAm)w-=qa+iuV2!3Lowvl-!wm9st})tMhl$%92HY(@`+ z&S$x<e_kIEaN9l~)b<vBabjB@&7`c{@MG}X{!FshF&K|y=4|5Im%%T!eM2>_^?WZ* z;#zs@&lWc52*1$mstPL?UVNWeY%}5w7*pH2?VNN^x}DoXK56V_H!nnz$AafsX03De zI!;;J^!OXYlQG2u82f;Zb<8K6n2$GjVOAwPUr1q7*CcGY`&-_GlnuF{>$b%@4#>Z_ zSEV);QK$W^YImRRX>d}xWka%`nl-a!Icm?M!cD&p@`+-a#iCo-wtnq1HJ|QZOJn7_ zWvOTrMTRM+&JmJ9{9YAK(VuI+$=dRX##fE}&PTR*{qKmR-9`(c*UoE0nCqox)l3p{ zC+?HGOFnHm){4E2CdThyXJ=stSP)0s(9;&J8|&Y{t)ew?x*KZUIld8z-{GG$lwzP@ zGkR;rWi0W{@Bztkf=s7q@53>AzHO5L-VOps6?w$GjdN1#SGyNOm0Dt=(pkph8Q7I= zDxn!tNsqenY6KV4p2gW3&>O!z*2WbShfpNkWG@*Bc-3&*+8cYiTm}4G)CI++$6*fj zCV`7vhMEIvWQl_=>axyGGMNVg(I!v9Vv@ePPGV3XWseTBFcg#yb{E^*`QX&?yvXb} z<%naZO`oH{V4!ol9zvn&+I!~`pDg?`%N{y@1HE`m*nOpxY<~q7S?|pxT%SRj!X*vu zTB#76v_j+QN6xF!pXurEKMat-P+o8e8hWtkB08*Q9)Q1&)*iwrjYk=5&ws(t-JOL0 z^?tlXzOE=!Lb<Mxb(sS$xM|KEBnlrl!2y3>V+^8Z8E}8PSsa^GAZb$+Cf#AB?VE}F zinV%WyccauinUeoOT}Yl7#5;4PY@g1a9N0*V(Mi!n!p27nWPLNmBeDDZ)N5v+{+`9 zn|GBc3P3Ov7rtne`#95Jgyn>!Ap?EvXxcLZeF>X4=1+XmAR=tt$~U4-d9bUzEQrY^ zgR5ffbTV;82`KRuVKnQo3I@B@m~#Yz=HA!Bb(}+POs71}DoZsODuE>p`5ejSsgjJd zGkJ7pKO*;0^H+n5FT?!9QoV2<s<+hjW#jZCd?Ga=sm;O<%hKa>z8jt`T47EQe_UoT z!7-Fa88Nx}E+mD<G$Poc^Det773%V#FPUm<JKqR+7!%_Q6}E<dhjIQa4UC7U`>Qnu zJGJIDJ6xuf+s&(+ldSh)C9Dgh4q7N~w?CHNT6YhPJcZsjnm=e~j-AC(^L(as($S;Y zj`c8!fSsL;nk*Sw|AF!455KBqot9|zk;TqrboF(pV57%gRe;D!EKEn8&sHQPq}!p~ zG)|bU3<Z0^hXwmBiUYSo(rp1pk}3`t%}fZvkqcK~@qpE>-PM8JgX2krOY_6;PxL)* zxTAu$)o!#RoL|1_uc4x<SFKx5Zmm5}-I`%!QHI@?g{!$4&0-ElMBt+`3Ftg7jSJb% zncVPOz^w|H?(w(sL7Sk7sef{p{ic|M<s^tg{uSHsZNyGp1e39r4d*@7I}l$=wR<>U z6i1e{MD!ILl?)Ef@2%nO@uIx3Cpzm+$n}(RXiW=Uc=!FSLn5briNZ62R^iyQSP0vb z1x}W>?>A|?O*<kZlPeXY{h_MrNr|Q27K?WiB5e({LlP*_LzC`+@!{v>O>{Zx&Blp^ z={NZXQ5yI8c}o)^)THhbq&0ppcNw=*De`s3ajUV>Dln>fC?@|y|6WLvxTQ%MG`3i+ zP5-rZsFkxmMKwmH<8G>OlIPKnZ=vGRvKz7@N@;eSVfk%1>niJ^jy2Kx`J|g5W}3Xb zxI!ITQfr=?SHwIhc4>AhH%=Zlvcn0~i=-a&bu{OG7jG6-^dx50U9k}l)kddf3{&A# zQ_qhc*L|9&N;FLR29ai$m92IHnhqba;tWhFQgmi}PPc-HI`o%jA;4*~YMEm>i)8{k zJr@|gZr~kl-HvM^cik@W;w{<2UYMZAvF}$=Qrt*3)%U6e!FRZYGbsF<MF&{NaHXHn zU}gDcfJNA@5d_=7#C#tfQ4-VNhxAJZG)FR+czkIa=_tc+&h7`<(EuuGaCHXs`w+CJ zTgl?*2a++Z3CCavl^*B%R%gAQJJrbuN5_%2@^4-Ugk;kxQ{kDsYV8~Jqrxf8T$;)X zq-mq9h)Q!RkRz^pQ&96vKOf$*IGLBnpE5k2Uxb@XM4>Yv7@EtDDZ^3nyq{d$Q}AFG zRzZibU8MD@e^yS`JN#VLkF$mj(Na_a>F>jjuv3}O%q`(BDQx4pwQZbFf`i4=G>lMY zVWqO_mp8;}a;1u78LCB1#nYbOdGcX@=XSAE*89E1PEV@$++xMXs!k@WX`Qdn)Ra!~ zpA@pL?%aHRXInz(L-6QphJHoE&}HyG*Zh_+`)v-5`_<AcCt6z{XWKaa-J5jy)JP;l z2ji=>{0tlUQ&sU_zVmy3YKuekWA@SFCl!_T??8%qD%<2soMVJ9vkGLlG%r+PpH;-# zp(@tHi_hdwpANVUJ>F;t9B-t3uzN{@8N2B52`f3yF!GrMVj%=hAuk>5p$Vdzu$E;0 z$Rc9+>fQ2tn_W%PCt;toFoH{8mw$7TBha8)FOTq<OJz`GSbWdK)Lrh&GWNItT+${h z#}cfs>2JuP9SjMl(8BFWANP7%c*qR7H*>@FQQ67#B~UzJfg?+tIB~I2P()b&t(e09 zRZKa#*;rgvQSYLEZCM^jz7bgGW%O5hNFXDgL`jS&aGnTk`4ELy{y<P^ums;XV)pB( z_eP)6<btao&o}%eg#Sx@wpcY3Ee&fM+>=jJ`qS;TdkjY=cXx(RK~2~zxMMH-XC5UK z@fUY;<YFx(ze>{dH9$P7cTKaRi!SIG=~{Gt6eFd(R8>h${VCTnJUv1_A;wMoxyA@L zw#C-Wm$%%Lx;CMoS-BVdTd6Q}aotFGG|1G3>bTvPzqhDsz2)jyXI4n=wb!~)&HN}& z?$oR6WW15Rx@mI`#L1Q-Iv&5TUaYcIhl5J<Y?P?1j`jsJBXMs$%U0ZqUNr(Mr!_j{ z$y~F51CR2qiaU%@ErHq+jfro{#U6jC%}fPsK9*Z<g&h;rF5YUxS%GGj@@>N?@y=m? z;N6xs{$Aylc{+t>mb@f4??-ye$#0Ns45t>GS_+*ATNHWqk-gvUsY)MhzdO#oY?LO6 zOCcex)UdCWbmsJ$yFNZGpIL(jb=8O}(K~sz2v&B&Fvc%5xOY_%hw+8Z1_K5DIQqXi zk?^MzU2Pq#O>J$hk;QOmSP61h^~yD+xh8oW)gKx>`0o8sXnJw&;ky#5iO9Z>pFlT? z8atbt(KWwu*{Qwc=1%sSa-BIJ{_(}xCOpz+hd4L^<&`0p*|}Epyt|tl*8XV*zkk() zf3X?m5o5Yy9>;yAsSNeIxPqsjo`^ZIE>ct`od$NQypGpzEAp>eRMI765~sYJ2P>NK zu*1DvRt9B>OVnB7-i;iB4s6Q;+C$`YCSOxyhpvHr5yQo9rO(su@JVDlmA=r=4+U}A z{UGFXNx8Y-neIQ|hB#V2+daV7xm_3u(O#k&4J>fDE!E-Fkz;f~h@^VXxOCbofPwM9 z?#-!wqV#in{wG#Hx9X8sycgL%4{mo&bcz18RWIE|RbAs99%n4YpSVcz0TmE~2?TU2 z=9lBL#*&s~>lk(^{CsN)L`>{Ts6QLex?MhZ#Clu7oXC_^uyALit%a2kgLhW)Yu(7k zgWlM#c+LeSx+fJ;>QqjpTgF&J`R{9nojQCfRIGe8Cwfty)=~{!B<%<vj~-=y4p=dK zgtzyZtY@0oMIhaSzSmeDJ=j;Wx?7{a;k4kx+Kpvw4oRUsVZ0H<T|O!PV(B-wK}BEB zUM#A3pWb!f-F~`@iNt27SLf9bU^(Z%?#(HFGsw}>!otZB*j@ooTvt>|Hc+SONO-w@ zeha+inwEcx&dYdzqxtKbnkc*HuAA0UR<bSNbf1(+?|SMD*jy4*W^WH(_k;6C^$7u; zl}eAb>Q3i{ZR@X}*VooI)Sn-oKHnW&-5uDP2$%>*%m_6IT{K*Jo*6xE^Y+*e&=!8S z?NxUPoP&fD{HQ!bv>6?qZC`piI9$$kZ7r=`<V<YW+6G+iuO4nKS$Q8HZ0&cPAJt9` zx3v*Yc?hm5DI=KfX(MLBW<H%h_bfX*?4KQ&+8SJ+7iJ4np8n(xy7a0$v%lO}&J1wz zuC6;jn2Xz;U!NC0I@E6X(YLj}_1Vky*wg!HVry=Y>2S9)+~8z=YM^Z@Cx51X>(b?H zetGI(nd3}6HeWn3fY7t*-2L*nFZ1oX_}<j+K+mu+-R1fG>HJ04T+UWbkDF_~&_qF4 zxX=%mhK9P6wuZ|-vs&qfjjbcwqNBc=-R+2Q+N!E?qdGTd*R%PRt^Ni2O+rFpnkc~< z@8k28oszT9-sk5%tNGD0bV8?e-};np8xs4GOv!(14!VHtk~76}1XU^(7!q$M=`=8U zxtQ)pQ6%%dkp1NP?FX#nB~i3!GD@T>n@@YOA(~p-!2%~jnPgf}@%hnl!q&-S^Q=p} zK)eH#z>otBDEFv0s)W=T8<cx;n`YI#$~z^TTkKjw<dIK%hz%;yJLP>@@<0YhC+zm% zoO<uXQ!lSI+EsHyED>`<jx_pY_rMHw!ayZKDF4B}s+6>Q(B5^3Y8x5V*Su8a8WHhR zZ9<v(BCnIX2VEz5u36;fC=%>=<oyv!bvJkq`XkzRXe9>nQp35?7^Xat!+e*_@e*1^ z!^d{OZojX5zV>8IdtZIKU9HstMM7#04H(w7CHp#6l(3I01lhF{9H=n<LfU36odZxn zmVD*4;STB({T+m|dP7R8yL7C36P5(W@&8T;-G&A$oqN0?g6NV=3z(`CdIHlc*YK4_ zg|MUQ?hM(cWP9BaJ_svVumx0A`{eV=X^lRZ?8wK`nJ_RGcmlK}I}X!Hzyg#Fd5u)q z{P}A8>6@I3jVEh;OF7e#<<mo`8LrM(Qyyv);&<rO`!Szt3)5MEBw82iZUCSCoK(a} zVmr>Kz-_HBHT%K?fK|6E3*SfP@(Na@N%Vy~^jF#rM22b|hm8)28#%2lN3-{nKUpD; z2+Q%ZKfQYtK=+u5E<QAi6LQ0zJ(n%n+gJf*D7Km(A`OGIPzFU}EC_ODqpgK^Lfh+9 zyv^}Ag6>;0&n4tkg5S(`FX_k3c8}$;qK<RJ_~zw&D#+f00?p*&!|xCe<`E~^!$iCl zu=lIU*OZIoP#%q`i1D0}JtL_mPP(sN8%}X>mdmD&#+ePWw9b?RHdvf=j~QEk7+T7& zi<<rv3y<}0OuA>)ENK)2iT7?ydW#?osXq6;#0oJYNn>NfX9;655$cr*(F$lh=Akb} z^_#>!kiI2hN(K9tq38R$5f`+ipD$thQ6Z~B0o#`j98yH!dxHWnt7Mp-6C+PJ+rN=4 z>tb{bMZwxRw|ADI7}NKDB|qx7B)xRVs9#I`wOp=2F=L{ezEb`Q`2C565MNb_ETdxa zn^<r?_gt4bh8^6X`{fS4(0p>VK?p?yuZo!#C#cng*ixch?p32;*7XD^+9gE5oCjUx zwbp=&VvFP~199ez1tC~>45Aa%SOv}H%BO}#U^9U4GMLBsiL(bbYT$k47^S~O3$_|2 z7}nDVO*3%uhog&W34$<ha01_(X7ObQG@3KE4namkhUnDAjqj>?E8tZRSLGVcGjLJ| z4J4DJi}D|mgA&Nlx`?RD_UP?sqeX6rX$gTwZXC2PK;pxJ@#(-;ZwL)|ptX%YjM-&9 zlAy7}j7B(PD=&qrnVt~J!ix|%AfqRwVqG!7Y)9|+9oI#s3k!ZKb<(d%SBmQ)W2$kE z4tx(Whl7)3Y!u>fae!B7q2N_GYJ>rOuJp~o#*h|*)nH#0vyPRNO+lyiP7KtLtqw}a z*F9e-iT@pTuvIrNy%>~40%F<1^_3$Z#X(dgTmiDbO1=@{W%g2KULgNN5ge>9YyMsS zmjCyMx8Mp8Uyh*ARfN{Hb`TMWis&oH2S5lkVjkhuM6h~K8_ZK*v-bY}7{(GKx1I)Z z7PU1ym|GNd$jF;53Bv$h0iOJr3u?z8;(H@{iXo6C2@@;KD0P2hFsn+OIT3*AUyzHZ zAZM%(8Hy*3@s&*g<|xhJ9_^M91cWCjOT@J_(1yk*hcu&0aTVlDZTv{Yv@|ep!Z?w} z1a~%ODF6uQs#3<k8M;9tVXS5vP>{=*tEr*&tN+A*=|5_HixoXO${m1DL2e_0GzL^2 z+-are;wvi~vgt3@jvN-$iXmzb=%(Mv*dGXV@l}>ZY9s`6X%Ciz>q%NTv(`4|0p61! zG8f3;jKX2CV=dtV#?9fz2ACyjF{_~lK<ld>L|d8>l_sS+rkzttm;_j0bWIFE%Din3 z-V-$%PZo2nJ*)-e7fgL$FqABi&^}R>Rk3!}FiP$evSSS@*;EAsp8%{yPQu2@@{_*+ zm?8i_^RD>I#!6&$EymNC^~GM92BdM6odp1%u^luQf(xfAyHf_aav)a(ZIW|42CDBb zuam`qd4fCZi{LT@%F&BCfOqsX)U0m?E`WJjc5g{I1oI=~L_2VS+1VkM|Gt7EZRstL zXyGjhXV$aEJP^QRHLxx|5g%X$2=y(mBB8G;B@pghJRn}!K^qV-Z-(ed&^g)IG@?rh z0YCFk8Sp~Q^CgYd)S!d#JC9^d0yJ><?WIf=aDByP&$-w@1c2N}6a{(Q;nWRuZ{m2R zqYZq}s-ro3F3+IYtg@+@ds)zw78jCO-ye}c<HTo`F_HY8wqY2m87sIjr#p^rbUN&& z^|wg}|BwY@B&~Jh(VZP8WJJ1@Q65JlseBwgN?$vc75%O7ZO@wWp|3EuLQZWLrvFt> z0A2vHMTVa;6~>?oMkJLl7+u=6@Zfs#QU^?Djj5pQ!6^$MO$hz`TE*;YaM`p-sJEOt zpeU470(hjU9b?S3FRL!NSm54a@?CXu9rFQnRkJ?q&TdR?Y5h)(2j8ex6ip+dKgUFe zdOrt50eeC+XN;jk$Czfi=N%Ta%4mbDTcy6xDFYYLLLkF=6H^anL|w(Pgv@I>AAN|g zFeNfi>S-_xF|)=Er|Q?dUWD8I)bPrqU@#JhD@I(!aRxDz90cMP?asLpBmM}Gr>h<Z zu=$scWHCdD*uYyP-?0A-<m2eS0y#9p;bbEyyyFI46VDYE!1PWZf@M;EfV)pMNFyKo z-~!(z&LTv`i+|dvAbN-)Q1~<a6W??J5tgmaVJiYe6H<NoAf#Pyf!HB7hsQszK)r)8 zM!xaUfF5jRK>uF78ZQap&IDfokm!*4M+;W*2o5d)VpApp+caeiv-_I4QSqRbILgN- z!;s-TeM}`7XY#X2YDg&+8kAhZSd)1EKl<AhY_j{MjTlHdv&Q+V0|c1B$MWA`NB`&k zJps_%MRAQB2THz}MyHDCDCmT&Yy>VtF>8=Lpp*r%B@l32eKzQia7sDab$}So%+=S- zaUex@uZeaP0h|S-R0>&;Xb3hO`l9za1dzDSBlMR@E)-&goxvZIe-&GW<>1vQ(SIC& zB?_78b%5~~y<%~j6O<|s2|&r~NC|kNx+uy#9OWwJ0q=F+nea(~Z{UWN8_?6ZyXbo7 z1=O$6bFu=yCO`0r5K2ygBE)Aki09qGNmrn*n*0J4012NI#51j0@?L6@6)DksAV>;c zeai|4{2&G60uoRzkb^;h`!czWv!Q2jvqIZ^(cFXj#K#;3veP=~FEE_9PkbWk%5QQZ znZzgs6TKPOg3L`s6fswhrm^;PBo!-!Wl{l_=Yp~kPY=+=PBCx!hyVqEYzQs`Co2%W zfK+2HUOY>C{j5%rCIs}93ZDB*C+AxSKK<1=4F5C%mGxAgN07?Ag>=4^#s{=a;&{V* zv_MUunm`c)Xil7o3?@?`E5pGdoxhO!wJiMVex&~Y?ha&9XC79BuPU}e(G3CUReA=) zH6ShVP;hDGHyB_zYoO0hvf34t=St+NYJA97ttJSOGj^YPDRd<P1&m~D#Q>l|rV?OD z)3_q{pZ#3~x-jMxijrv{Ux6@&fJAPBfdv#L0SXil07!0+s5#XmJkv`mVCd;1Q3Kkd zARrp*uFF$EN?|wbuY90%<%2w=5BUD_!9#Aa6&ocGJXpx?b<))I54nkRkjQ*PA|sQ8 z<gTweC35g4U~nLIqEwSRoo6-B2G=u#vHWd1e)b7cM=n)Y6M>X0kdgngRWH0zpJ8Z+ zex%Q^D*2N=^#cyU9Bycq5J&_XxbS7-KSeOw^gO}-dK|_@N{jq<0PoIW8=x`kQIdbw z2v}#eRCWK-s4O1~C@vJPwEl0ykN>rfBap#ggcXOZMgF}zmE>YJf6QBCa3b#L0>zjH z+5#LZgK-tjq!K{*%U}?3{tUIya+g!$bSc&9Jf+2(Nc|5?maZf~K=~$T3gkR>px8lX z)}Igo_P&<$|2YHoQJFrZ_q#Q)rvICVn@UD9uBKSchoa>GoTftseiR0Z0)Rt6X#&(- zzc@7ee>wCFNT}FALUs47IroVmi$U=P#G@$4C1y2%%KNvI0S0kYLaaz*hVv$WQs^s? zQ2&`i8y~M<Naflezfe!^R7A4Ec7xpyTHEz6tWZ`o{MKFZ0Z7@uW}u;leEmH0PZ|Lh zf1UyJ5O~}EWr9FQKt##{IvC00mMXxGpGydk#(sry%7S>VeU$BADow}=!8aJ`{u!bJ zMmn+3viirvc@J=r7zw_+2h9p-Ky?s>WWk}WAkhdM24I!Sf`fl8YLuiPF*Z?+oW0vu zUgr9NE>>fX^3Pt5!}F(-Z`E~X?VId#5ak<OuYH8+6YD;`jrNbB3`E<{s>=xJ)5hDI zJpACXs7Su6-1R#i{xVuIQ7n#cBy^j*_r1Cs+5d+?SUDRdXIZjWoV~-PMdgH%{$|ni zr&F&3H|-BwLPp-T!l#SKa}hUBkJCZFhJ)2ZmxkIG$D7bnj@tZi<pz%_&v9Y3HfdKx zYQvAqzO#w#%ae_c^iaA=*9M`A{Usyh=~ktJWlcOWaPs#7c|MAYb`9nC&89zZ>>zJ8 z{onQ<_niJN{^z9@<h7pPO$<0@{Ns|(-v$4?l!3hS^1B%VXK?@J2F%|F`12YB^6tj( zh5(L%|5x!}H#z<;{pYzq@~Xt|mJQqz`EM5|{yxH=ht9~~2Y$DG;4N~5|NXV#@1lR6 z#3E0nf43^&Eg<^mx$EDB|2(Qh9@hSD(*O*B@IM^g{(YQ3Nr61r{M}9g9{f_`KaM$7 U<S{UjJ+Xm5VZc$NjL3KY16IZ|5&!@I diff --git a/ipaylinks_statement/statement_files/2018/01/20180129.xlsx b/ipaylinks_statement/statement_files/2018/01/20180129.xlsx deleted file mode 100644 index a5f253ecba2a0cae087e564fcc2a40cf183ecc05..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13902 zcmaKT1zc2H7cUG03?)M<h;*woh)4|GAtBO8cS(0jcXyXG0$vG80RfS25TrY#^PK_j zyMFh*?>qbkm~-~pEB^nr_St8jtsspA#z%laAP9&O{4xlC95}%L2G;rtcGfm;nf0yh z44IrQEy|*0r8`)l?{=>UC{7$>2n`r4@4qAje?eA_YYMQp2>pgCS+m*vY+CDah<Ie| zi3`~~$y)xR=*HY%euJFLM7iKvj_s_56#gBq^^o#Z>f$`xzZ^PqFpykvHKxXEuv-%l zw2zDYzw4FiALymwQbd#^JzgqVgW7d6!QMd2AfSl45hfnjgZQEAhU)mxq0gUe32Sg| zL;`r6=ZONXxw4e5zqh45S!%_`;FMM3B4EG&?B|}l(*+B2=DjJ@Y?>ijiaefa>2(FL zg`|DlLc5-9b4=mS4cCv^vi+xwhP+QFBKBjdVwNw^J&(Tk51VMdCHg)@H97Z#WN`U; z@%-vI=T|xfX;etBLL4CyA_Br8@KN}$5ySu@sAFen@s^nh{<|!uRj!={^WCmT2>r?E zY!p;T)=5yJLDqy9CNaZhh9@43y1b2s3Kqt6oPV%-vMOIaz5Ua8KaAl8x>Wh57&_*= zQVhSC$iR!y@EJ#yQU3YTPX-5TdW8851~lR;&KObOg0xptDBm3nD;=ctvSUGOlMlTs zO;gMzbcm`;{JC30(pA{Dx70)0%{!#`Mo#+YA0_8@wFt<ZCD0qBqZrU65^2-R%8Mvz zW#RU3SX?Wi-tW{MEZ1Ya3VyUAPbY1p(?et*<|Uz}#pK|LJRe;<TH316_9K1{k4)}q znx?R76Cyk|s`T1ai-6~1p#K#cJfMY!u(g%Fp_RRkvWt!3TdiAu#r6U*f{LD;q4#Rw zHyHXrrG}6rX_Rx^y{qWLRhkVN@~_-z8J20(L)Ln#SLWQT#B4d$G=yJ4V~@)V^tp1t zX@^n`F0z?MPRlgu9HKA3aUtRgR!MVi+uc)5qnq?02tGr&M^_g4%Am3HIkpf}2g&J~ ziG6Fn6Oks<+f2b!->3}~^(v0!nR44|Lvfbin9Z`fu2E%w-5PwNRrlqQX9{O1Z`MdS ziiauEv%L>IqCEe~+<)WI5-(EbEhE}@(v}nTn7ME;uw$_89_p3C*vGO2ZzAbXLKF`= z<oB2l&{)k+XD-RL&mmr`y9uKWk%8q{^65cYq;ETPD6cLWl!C~WHxQ~hx1^78R1P{@ zzP`ZBZf@6c*W`6;<~~E;Gk9g<q!}QXd1@0TKeNo|rJDb<y}>#}6&`q+c}PDuKuCJ< z{|Y?x&$NDHV*`)6Y(y)18w*rq*Hg5+X?8<UWGK!TlCdQyK%O_vHDDoBEhX?HZDg^J zC9<&oTgA_Ch6Y&K%y>Ay1XozZ$}4`d@eS%1O-jP(ICwAma!BYu+P#S|_O`fxNIPy= zP%T5@(oR!A)W-2VG*MTFG<acvL%bzCT8yOR6j`e5{DG=5)_v4jaiu7|zkc9fo}hc) zJ4b@Mv*7MD5e*po5%~P~9K#2$I$JQmHF;xaXrN?oXKH2q7Vc7jhF0XGFE}3GD=LpY zj2arw*{j1rID#R;3M?-#4b+T~685I{nO>3#f{=u0GZU^51cjpLV}ym4y1|bZz8g4w zYwj*~+ugy`C`8?Fso#}3S>HJ4RvCSJT&$zxwcS_YXtk}?P~~RT8)>!K*S|CRkXdKi zV|ivw`hMo4jWMOwW+z8$>zlsOhZVa!i^=K-W69%A6;}sG>BeKipH9ozlT4g;XU0k{ zE}k_vH#IpOjizs^9(O)`=H$5F%WO4M?`cSO(|FW#JoioGg{t<Pn}f0O&AIt>>!(JK ztDf4~vR}q0<>>+qUe|kb#(`v>?v8FZmy?!{)FQ8UOXRV4Zx;4+tVypI7h0`J)349w zcedM|$oS4KWBpz@ef=JIBEaqHez6wXh3e&+`Q3eQIaS>2Q@hv2O8O6vUth(I`k8<5 zpI^=`+}|bf*t>TV-u!X$tJ^La-}Q8C;0@P{Pj64wTFJ2aJvP@qegwMPy*io?Z9v_f zW8ZDMnv4zf+Ob&NjLf*al5Oz`8~dL8QQ&%GuN`$Z)9;sqjVEOLka-SSCms8#garjR zMP#WL^Vz|$rd*-8j_ZD4VW2uu`dcHTM;y6+4>jK8@=p#9BiWW77rzVWDCeJcZ5b1m zDkS@K_zUAa2%G7w_rCm%dWn7mvHL@s)P)C=?W3!#b;uSJBlD@;@{#%V#M@PQG4z!j zgpbn{CQU-D@L%w@FXP#`Br=p!V<uY1{|tHE(>L5H#!=9dq`uXD@N&<XDL?m1v`N+X z<jlpSZPu}ukkYu$dixM<^2!wVwHDll{0W|{p!zu0m=Cx?11ExK2?(V@4{DqDeoAfT znlBuP`eCNFQdH{q>Ek_iPVCa`BmNxEMOcinmxIdtWGp&apE$u)QCh|<Tms83QMC9I zi8~YDYf?7$O6s?MajbY?2TVtN{*box1>cp`nNpGQW>x(+@fx`g7bZ$|!aH07Sk>hD z1mEwK@ORA&x>_gh&)_axl+l3bsyhBM3G!YdP}~q?^!V|!gxHR7JUEJ9^=C-a?q7P= z@lWztC#fPJ?4Gvra<(qU+156b-}>jCI*-TCWt8e<%st%@P<+g%CWb_R9Pw;w5vy-d zjA%B7UP@V__AqRiJ#&HTqZ|opv>Rg|@4|B1gTzZQ90?u*R-el@_7XZ9&u?~NOZkNY z34;hM`*b))8wq{(ex+TP?v)w2P7(2Yq>d2^>y6G4^O~e2{vSeDh%puq@gM0wgKp$7 zKV{N$>DZb(h<NR~rshhXa1XIM*6fMgH`_Aj`}?WpnsN3o=Zcv)+1}tJqGM?)Zf#}r zR~hsxJR}K2j(5wdMyAoPj5IpY%F6LQNN_3@G|Yk7_~EM<tx(00QISO0QjB`b87~)= z1wMYM*q%?5tBkje!6y_ISdEX8Q;#6&|E~Ov3+@zUV#11g0z2EA*5s~6sLq~L%T4af z(p4r+??4+tO)+&N<CavCltSZ#;!y99y?s3AoIN}CO#vs#%oeZb+Mi9zK+O9#NEvD2 zOId5lBt_V^G6_T91}K(cq=bF`0vCt|f&OF9s}@iy>|4%o7}yq%GqTLF))M;2=^Y?L z*^eaRB<8+6diSA!fVEs*OfAGm5I-t1jc?q<w03XlM^)b72X}_J<p*nzgwS96uuf<G zM6_k&^;n;j#epqGtJILf?DQfKEz;IxPDS=za^Hk7`?IwtKL2b=d%3Q@Bv;khZAQ{G z%PRRn(B`EgV+yR507<!wPl3xpHVpv*mjWSfz1@Y`)E_TD`1v9EWUlx5VOkAVO)&Bl z%2O@$8o5oSdn@ke(W|51TL`E={^dS+u)p<J&3wJzvX;83{wG(_PGv$f$URa8`5|SR z&jI~UP;XjCLks(S1fITLcwzsfgMhbx)y&?XXEY;0#Z4w!vMjIashJuSnZUJtK<&$J z)${5PEvIN<E^1$)30YU+g$^q3U%D^6!ORO6VI_Pc{BT+k{MHINIG$cLs`S-6ZHT^m zMgR*G+zf4pB5T5oMA{->{UT1H8>E%{nI-F(-#vjh!phu@#vqAE-zLmuSB>*gBb-L% z;hV39?*gLOCNLGjc_zUR(|n~E{j}7~@L%lkDW3FSxkZVh?lK<Ea1I5Xz7nnbzF3=t z2mR1tvEB8(f);v;q-bE$XeRY2fEa~p@J-c37$$lGYCf9=l4`d<t-!BX=`G2f_&36@ zHftlP-|32VJj!9G5q)ZQA{o-#EvES`VjTSbb@D}qCC+0<4u!lbrpZ@gr`}u|$yVfQ zxzgz!L1XkLI^9plROQJXrc}C<OR*W#agpnEEGnZrC?&=YQuBM*b<NaO-02pf2@B_) zxe{Pe)*MR?`NuZrb)H<UQi_PZ4jY5sqVC6sjxx>-_=<U2&D*b&pB#kb7zc#5rIc%v zd*{Qb(X=5}&AH%gTs3JrUc#b+S#6{JmoP^)I?Fbi0mQOw2OG{9V~I$sDq5Vk=M&?& zvmoJsO1nDzmDjIJ-D%UOFfhN;A_}RQnC(Sk5P(HO@ipJ4E2;#bKzUlPFpjLE^Ao4= zHFf)l+wk!hF3lB^N#0n@G<Q_tcoHYO1wUuI|9oM{VlaQklvg>Af>1R`^P@8r1q%}y z6vt4qA<ay+r;gx5D?vD@1t$uGSiPLD=l%BOxMcofux^6mO_|-vRHvDws|DsOq(SwZ z^?NG_nnR&e6i`(TNbb_l4YsRJbys=nhXk+VA8R4G^#-s!>MqDd5yBPzKEi(5In=Cg z;V`=LwtR{ucC;@V{aNGAhiy+%-t*NJwvmU{B>blph{+6Z^JX7qyu@gzXK9&{c)ac` zFzF|M?hDoRcd5?AH5an4nR--I)9PJX8Q8~2iNxm5dNe4S88ctm6t02C^MhK$j%N?0 z*e|U61KOEGVkJlvT&38)l?#>33*_GeaXOb6%Bw3?)JC?Q#qqrkV}He(J)qpjb4cM} zASi;Z@#aFp=O{L!3c2js8I0FELuUcYv@q!`H_Z|rGj1qyen8rEXt4AqSyx+8iYwZ& z4RHw9QglUJz8S_Pd!`jIQ_bLq_0syjh?_&!`mbXdU-d|bex#bR7NnyIFc;$e8Flnm z38{RHZ!GesdcjD${Vz72fkG99^PJFVE#}6@@@g{jOLs1GLsw2HZ1@lYD+NvWYVPwn z8~g}9deug2*wu!`^d+H-?x;JbD$F8nDvFKyr#whcdOX{?>}L&%tSq0>*rs?f&2%gY z_n>XqD(2wR!xqjqF>cKJPlr?TUWy23EE7D!&$G%_d1R-oZneXMuZuKkqS(~r!TqKL z+3R&+%!>&LHGGO#mR3ZR?$b7ZS^U%w0p~<q6GdfwSiF-qrP*8q%K8ZH40+w3Itx@P zUYp&^i+_fZB={(Z6Q(^Vp=^_p!10dUg+h*gII5JhJzs*@4%(Z6BFB}r&|0r|YMC<{ z0!qaWf}+)D`j*l5aYsh><>d(vNvwDyQI9qW(sU5X4~FtE1?0JRitT^p6!{DLp|K5Z zddWgw8v?%=<3Lb_C4RZKsGE_T-j~c)p7POMNE0<0_v!cDOm~l)rIjYWr&Hp~xp=tY z$NZc_MH*CJsSDpV#ZqEEN_(33bX2*~VRbWrve%7wx7tB0GSSZU<MS%*YgY#83XXQe zrC`kd1T;n-if8Xsdk6Z+tkNWc@AcpBDe2Wozw#Fm5yuNyWYB`jtm@Oq2G<5zaN@{> z_L#hscr6j5?N)8!_93dtyIkd!<6vf_97frWs;G5^+vb<FsX=C`;TO4d(gArVy}YI! z6<)?<1*K+P_NwU{Lq^3#4R%Xo6GjY#VZp7#t&?mZhbS}Vxr%_mnq!yh{61dxM`>j> zQg3kuX!*p9I5N0I;9XH{j(#VB5YOTd**eMuS2^==>qwk*Y+2SuRrV&UZ|X<rzI4`R z#uFZt)Hl9*p;44-W-<2?2`jt?Jk~rMNnG%;mJ>T*m!#0TZzBpB&#OzkFh8yS3B6et zhO28@qr~%6W$Pd2DFexI25E=qdlq6%D=UxBwhY**EYU3U2=)uLJ+>NCC(ec*pWEBi zMa>zZL~l78e&2c4I-`~vI=92CR`k9E{H5@PBHMJ5esH{wm^N?k=(vowhDW+A+OVip zpo`#+0Yy{Bj=E%%es%3^E5?zEyS=(Z3G_X_JB91IX6WdWU;A8brhfj&E4IgIW%u>m z<GdK{*$hW^IP7z&sPC)YWUCJSkU=9|V#~eSWRMKVtqgUvw^0|18s;`If3%pT8p+wn z-roXvRs)?h{t>~c!5Kg$6BOB>Fy#2Qr}pFH3qwC`)k^lER@3CHu87j8;mQQ=XSf^X zr)xF%ITQ&Y9OP??yu`Stv)Ged7-)z0(AbQ{pH99QLb{2u=E~*5Li$8nnGwzEdUYP# z_sJq){{0k4PgQUXLrpb4$zh<?l<2B^RMc_XOn<9wrcu$=j9nU$@J)%{Q{#%cCYuG( zZL@&9g<i*6lx$fYejc5B=ugA#+f{r&<r>zQ_QCPc&VUYq=13BZ>x7$`Grtv6i15Ut z^hu(V&uWaN5>e=VlX@`*V=BmO+<dPd<GC{J@~r9+O6TYG`I@LYx*F7}Nv=<in|hGH z#<?FFWS3exHkE$Ak6w4o+mx!PeFQTdQHkoi_{E%4@O%_kD=<~Jf8fp6u)w{+*!-L! z6p1X<Ophr@m&7H(qnRi8Q6_F>WQM(83bm{7DvjPwSlQ?0Gw7%4&&^Fw3*30Yr;NWG z*3tK|5D@+n`Cn5;puz2w(cZ<v@OG}4AN%{k46kV1i%l+Se+7+u62fUjxZ|Y`(?K2O zF_^Wyd~(B8SUyqnLla(G-{oeOocuU{Vx^7y2WUP`P(*m8Y;J*Z);Oy<*WGYHdGdy1 zZv+wCinfL^88Gm}D7k{CvWK|{bt(N_nu?FsxY1{)EHkp$(ywE^%MM2IVrnaYeSG+^ zvB)GcJ4!k^-bL71d5jIsaOcODRJIv4i|}?vwk7{gVw55b7d%d7LdB6LHrLg|4y9MA ztY0_jWzzd?Ur~LcH!7Ao_v}5JYGL}+y1f8qd72?OmGn!gQemYD9g)Op0_Q{1BR6_# z-2Nnnoy0ZuPvfYCov~r23vDm#IOX>hTxqZslOLLZ=(uMcZLvnW^c5fmlSQ>=Xz{__ z!krc@bs+tWpIbU9?8gH^935Re{qh})WHMGJTzIt4qrIf0xA3+`Gb{B>_|F6kD?Gmw zzTf@!SN23V#}wPDPL?Rf0}*k#=3lSUF6=|uJ||_B&?}Q5uImt|c%{!*(0n+foaEsj zKDeFtM{tMFhX9W;rjY&@h}d@^I$7J9>secy!>9b=5moSKNAH|6+UnD%5dFzRhV$Q# zglAVa9OqXNPe*^RX#`VMwDh#KA*uXiwNVUUV@vm(b^38Ndilk{A~M=y4>u$k;hi?B z{?)6tMOPOW)L-X0JpO-8`&a4{ols}X7BfGmo6S+;z~DP?G!?RETz>E|?L4SQAv8&| ztHS@UWjQr$I$@%lMTo3ECzG$I<Jzz!Zj};4V*c1M_{jQ0V0W0*>zUApXyF?WpYhR3 zmulxMc5aaZ`)W7Ml5jAq%_TOsV+QT7o^1ccuJM!Ai~S?4*H6l#p{gsy6G5eRPsG03 ze=XEG!iH15a7sLD9f*PM|9k>Td>5s=hme29>h6JL^eyjUyH_FIPAQJDzaL0e?<2n4 z;2NExuEv_a&hQ48;zI7dP^(*9P0X82Taj#{+<)NbQ(p>uV^j68U3cE)#`!I3Y8`zF zU0Uf9`&L&6BQ`SEyy#HV*cNYpLT?hwk{p?7U5pa3ef5qm>PX4^`ceC@-gOFQJ}T4w z2$l`RBiCtr0;dxvx$S{#+D4cM?S$Xva2;P{yHoV*N+X5%h<@r*9%w!<E#IJ8MPnA_ zKM=qi8|UB_<Ea#nvktBpx^P=o@H*#k-QTs`M}fy?umAPC5x{en|M>*+!9NUoYhq|< z{}y<N1pHyWrBb@q+Zi#}fZbn@UpGdIA|Un2NDaLr)a-qlqgL#$J&gOb_(?ERjP~w# z9jOK!u~l9z?q|Vqysiy{+@y`p1wJm<h0Px4&d1}^7lGJLnL24s0-9-=v!0%BPmbGH zotXP?R-3&p$J@^`wXb`B3GD26c{qEyT{s_iczHV8USIF;fAn%Y-dgx}F)jZLTVUqO z@#1X#=2!3RRbgsZVe?$G+wtD?)%LgPikr3JF5{~&Uk<m1zXg6@WzKBA+FL*Vm5BI# z$J)!q_Ih{r>_g)BX5X8Oh2zM;Sb<CrqLbBz2A$^1{6-JkYmTO_)XbaB<HhaNuIa*N zfw>#ci)9^w4_?=c<HeU<SCiAzI#!-Hr>B`tUYGV43$qtpg}Ee|_kOLDHGR4`-8=Hi z@HpSI-@7`SEKF_oxccGc?tF22y)J)+eWCA_cJE^Ua_ieJcBE70^)A^>X2oL0mHWls z>0)44tm$R$(m0yt9PeDCyQkMl*W}f3lziaTN-tT)J;3$eAKx>sC)<Z_jw+a$GXyR+ z6TQyme}0#<|AF@b@9Lx@AFutSLnm#*L;iBD<CJf|CwSfMCmr4K54<nIz!h`4h#z>W zm3q}h806LO37~3Y=CCmbk7N7t=JdVmX|&zu>(uMRAKg+nL{PO2;Ik<WGpM=&1(hC0 zdUxA3+vO!LUz;{a`7qjvX(Le@FQG#v&#OHK2;O%;uSYRhQW9`~anycX?39=IiwB8v z^#~VbNC`VA!}Wngl&bey@sDyvglPLl6cKqoa@UQI*!4VY-8foEL;J-)JYF0%Y%A?{ zlLvAmQ3g7rA*~mq0?ja~hdq{q($BXUk)dZrZdiAxuZ{&(lR_^)I$?EZ$X}gqk3>!v z&P5B-K0~6s3D<0cxo#j10)5H#Z$1{^8nISo@LogZ$IL4vh4LLuqiVfjaxFv6vn|W~ zoPKV4G4i4s&j3Z_`r#*kpTiNPoI+BRm>UG`=X!;n4N{0A1sBA3PMmN1m9yLzEJu8P zQ2fK|#nA=aTzd28f9k|W`U*s;L+;8k9u$;TGtLr~;R-t(u_m(*_+*lbDv|r`1rVV? zxMYzfDf!e&>z%FGNT#W)zumO_rAy9t1dkT~+D3OC&@7y57x0nnqkI!pY@LfY(9z$~ z$+OI$a@_b>f)A_t=67ek=S9}zKGA7j7_p_c)Bg61z?JQ<B_wv!Lh-OVSB``XFFg)~ zmaW=pq)tlc2t$WSySTn7deGnlaF@0zKdrO3slCT+@bIQDHTQ?{&d3MbmnKi7K`aU2 z2hynmy1Z!94(O~?H-oPez`9S+rr|PENVvl$pazv=hw@-vw0@ErY-+KGg2cTs2w^mc zokQBt2l8!>=|W+3ejEujh!3ROj;mBtBJ2D+I9%JTUdKYa1$6IC5#r{0P=p&wLcrwk z-}t%;g;0G-$P;qb1pgMKA@?U}Ej2Nf?^~E`d|F6K<q<m1{b8uM`jR#)CLTh%U_YLK z2b*{x28l2liUD5^vQ0d1(<8JJqAd_7q;K#XtXnD%*#i0k8(*?hK>Y;)b3ACl5m67M zg>=zO`HzzkWH#B~5CmxHqWe6b8by52zyq!ZuKKcP__y3g0envIhY<n#AbAwux?&Jy z9;1~!+XC4FotNKhnHZ(83G8@{>;0*+S9l&fRtTA*0S3m6et;pIg<~t^7(ia+5d2z8 z?|!$49@7@FV3Za$C|4p3*%#$Q!`Bu@+5mJRM**TDQN1TnAI%Q5Nh}({vKKw0ERH^U z)M8F8eUM2$!+E0MD%gOoV--YGU$KbXATboijjQhiiKCM1F24`vWO{J*{?P^O1#a#| zfRTTV3wgIA0rF2A)ZvOp2nXq+g4w=No+q%}$>W?BK9oS6;6dRAv7&tfk>;r`{>sRX zwbp*f`h6U*8ae1D$ZtIn2f>BhS117eC?&83hO6%a!K9XR9pQy?a30uHFAR9ZuOdE} zRpFwtAK*nWa6#xifcZ`K3kULI3uX&N?OeFZ=Bkl<SHUdEJinkh5JP;=#mL`rLVZH0 z#ZFSbLAE)dK4H|IAVI(Ndj{UTP{6u@JRgWVH7j9Ii}+9fV?g3wIIL8x8as@dwI0c` zQ|LZ%P>Uqsa8@f1mIyh`ZHx`T>M;*6M6zgXh5S%_v$Uw7B}rRItifTHN_5>^?@`Tw zt6;3UaTwT&jX@bYWK3Yffgz$x=ht4rot=vU%8J!8{(-7@6zefh7d$v?#x8VTgDwb| zpzu@I4~0@8P7<(74hcs>3XV)(2b!9aq(VutCZ{2piIko__H<YjXS`3*ts`nmL_s}y z3KSAf$xQ`=K=UHZd(A)nON*(CMwQERs<B0ASnEGnigl;-z?5(OC@sbmF@!@YYe>!r zfD6vSr8AHPpf9i^i1z?a4K`V^3)X+y!leK_W~_>U>ykky0Q$rPIwK5%Dc|)!sC=)a zhy?UfGR(>)6=$dbmjVsUdJH8Q9W1~l_qxYK54c_sBlaP10rZlH1OUWTDL8;wcDXX7 zhXNYkvDW{Qh{BQ)tr~6tktHMI0SpW<a!Pr~1PFyPK$d8rqiivy=cNU92$_aH2x8A# zzClctB%_dh(M`#N;A*f%6pEmE8b#W}CWH{(C(!9Y9b2Fa$`KRBz&BVT2OS(N;+Bkn zaWUi=A_p@ZSOu~)Fw&qb1wn~aDdKOSXkJ)4ub?a*VEu1R5E&p~M}{ax<LR`C%3nb^ zNm6Oi$doMc04P!Lza6j1K}x}R)iCG?dWRWfV2d(nc=KI05yd72NJ;WGyGVaGKZ5!c z11Q0}h&qCTYh8mzmGAi!gA2y7gxQ70guw;3OfljU(PfMk3Lu{)J4^xW)MbP-1?UfA zb_6XcCIKm-$y7XiXXIZR2)B+9Lfpqh<WmgCWGe>f9L|zrAb)B6vc_oiIpc+O8GY6r z+6QE!%5P}GjeG#1dj)zSK+g(A<av7N0Iqi`5<(dK)%DE&mhkHjiwZ7oxuc1U3~~XS zy=<%me`~0ckr~v*Vy)GXU1nm5Z#k?NG#0xJqxK|zk`#$ds+8|mtt>p{x#Gc-4XGd{ zIP5%ka5$9|&mb4zCTTxg>w|*`Bq|U_zgsvd>6IZvO#&5gE)=kFUxxg~;}f9io_hjv zTk;=LKza}8PATIW_&|UF)D%;9gAl`z^)B`v%K^st0|c{rjRZtR*L60F9WSpUpgs?t z7sVZ|w{3Co8Sgj*VAQ&xng-Yk;Y{h7{fa>r`;6aLcNmL@{Wl4hnj$%p09Vw2l7xIm zRcdB$nK=YWz`mHQVj#f^?C$^8L<QuNE<B$GbjOrYZbMgH!1fPa0D)IZpHh0XZoz?v z8pta+I|TiJ98S8;;gjn|+HQa@J@bGw-6>MO>axpbj81oq0nCDT3};Lu<x8@qTr@S( zx=nn&Lsov`-XW+-&-}z=mSbW;J@txEZJK4KsJNEHIyH0(b25;mWSF53%7<f$D0pd! zs>Sxnqwf3(l>lg2i;YmrCB6Mh@)HI%4NH?{f>8HVAWTs&TM$n$s!58s@>ZfrJ}pa< z3df|!0FhD1aadAevEZ#H-|_=zc$Aen@bXeam`pj`nw{qvY+0Jtsk`S`Nr5=8%hCxR z=j^vA0m*DD<T@PuA9BKMRC%gcKoa6O1LUb7{vGEgGbjKpuc6H;0UdDN`(0?Kiawxh zjjI=Fp-*>OA39Wm0<aq4wvNlv{Z40V9#aksFbiSOHavHl)<ueJho9dwCkM%+-3g`2 z{jJKH=dRWW*73a)`v3!H+)*x7&Y$>M`r-ydSBnyeed73m|6xJw?RDG-ZYLxx8G+lt zaPN@}4L3A}P#fB8#joV<;!+muGiL8EC7Q)#zV{)^snVen1|qn0VirSIn%!FJA>sLf z7N~^P#}sD^DNBjwF`4DrXlfS-3O~%qUWq<O3BgSgJi+@0QM-WB!!wy934kZ(w%&R` z@NetwOQ7C*kQa^emxkD3;?uDBHAzF@u!`PQn_~(a03@NPCg~u!wF$T0R3H0fy}GD$ z?P1-EYr#Bbq5!&p@ZJ^=nP)->OSj2mPX&gThu^W5L(fi#Rlh?O#Vrvk2uQ(0W>L`5 z+9!#ea$61P2rLTVB@H-<mK;l2w2)VzqA2H+2R5p7LZir&1?o++|9y$uYT$i2zIT^7 zrW_ZNjWESq8UU#~;+i;6Bh|wIQ1sTcn&R6O&4Z^XxEtwrioz>|<lh5_LT+)|E6L}d zdJbUR>=O<CcS8#dLEp!wGjl;$0xsliaz6S@r5b*6g8wq)LmjN8R6`@b02m0!8GMK= zO7Mk_(e6f7jwEEtyJYYX0>{8db8-e-Awr0+dM30aFAXFKkVYdPS}h+0Q-qJ2I)`=e z$TBGJ4Q%02?#00e0r_A+!vM3{M}CS|O3&f7P4J`HH^?L%P+f290DKsO-(&$w|1P0u zYUB_z523WnA;$xy>G?)`rNOW$4<V@ihzND_UswT$T{qf@OTqBUc9^IHt(Kr}Zc4vA z<-#g>mI0}?;#F0Bj$95XdWH!o3J16!414v{#Br6V8z>-x-8;N!)e_)3Hty>XzsWK> zSl5`Ler>#x?qeS!dsRS_78k;S1h^ho{KKYL*5lio87qXPXo$O^%_S$%7IES1Y5!Yw zk7fK*DP5F{bx!}oRV4@@(S|ENY&nkLLJfy=^C=>5suNI>g6W7gP+n_l)=b>%q5H&V za<YKI|4<1;9toC}r1HsKF9gE~g8{=N1ZdVKp5SuOgp1f*5*X)g(+Gth+cop_dd$P6 z>KOcMn!pfB90_R>+2&JlHx+;;c=9s?4_Bm!?o+?Tim$rk+}oXa#22ILJF}K9)M=CJ z74hF7>))Rsf}^vfUVH-!p3l+=#lG_;w`9Q?LWzy&7hZ@81U;CJiBuZ87n?N}k$hEI zK&g<}vSrbQDdf0~kiJq3nW2d=8jonvy1f<N_SXL;13rKUkG<L)Rj|ywi;?-nrx9#q z>}CW7&Y*FIis&-iax^%Cj{zz`s%6>jEdT^`P`Y$%#p=ybvOCL@uigVPp8=T$Bj}J8 zJAxoJ$SXK^GM{QM5ng+(QnU4cNq|A@x6un9o_j`Fh2G~u&f+t<KJ8}&pq`273tW#C z8`k2ffTINvh>>M|f*04P1v8?V)=z7(Mk5oqq-6#bgqM`wWB{SKh?4-*%6_F3%$+P0 zA!mWZ`u8auh)i1aPPuSVRfARYZ#|Rd?;zFVm_XnlVA_a+>CN9->YE}WzER;o`sPm` z_e(Udz>4-cyF3Y!E?~N#4<GJhQRL~oMffcQ{0Gnmegne9fs@2R6AI|H6?4QxS1`Zn zdqa>Ecq?<o4h#YGFjBOX7%`CeaH@j$6I^%@=KP1M)Tm9Qh=XrcSqtHq&G?hP@^JwS zVtFww=m)d_{nqp>`<8YA<Zjc@N2%hJ(4^M=af3?pG)G}wxQI>ra<q+6;k3Syzp^eM z<jnx|%;Av>0dfO=oA-lWsB7i+Y+YpY&oJ6>uwZ!VKzpSaWhKA`d%wQ0-^#Xt($!${ zI~J~ZQh*d>3&;xsV}ndwFjlxk>G1({LR#1HT;d>XpeUN$WJm&hjQc?2M)l4@^mVGA zh;Ip4q-_of5?@*i0#5mozH)K_SjO_gZ5^nmLlmXJ&<1>k2HkRwpc-buu8Q~pEUsf) zreZ`jGN2qds!0lZi`LignTJI&stk4^2fkr~DOmva2n7H)xP2-uPg)06HO(8wf$3dE zl`AmydkT=ps+fqPVH^Rdp3c&`<WQfFz!1V{;4@)V4l+WE`2177Boe{I!m@~`bnF27 zT3T0ZS|K3n46<iJ8q}f=Lh^x>0+Rv-3XBe}-!6=+r_%^w8N0krU#750XbG!NHy4vg zr-1>stHIl+{i{8lWhT^Ki1=AX*XV0fBz?5LB8^pm&z*SW*g!QvLJUI%0e7Hq9athQ zn#g^)Bp&&-V^^Nz5YD9$+oSld7F7`Y)DDlovK%59n3UZ{NfpS<|A^Ajr~!oYc%4jD z!^J*#*~i9cL@ShCs9v6o90Hd43R=Jfw^6_+1^?m6d6p0P+61Jd5{1$x9`K}^T__#J zcPkkg{uM?JQccEZRPF{<eY-R3OYJMAV1;&NQdK1vOc@%M+#TL@97QEGC;-E4d!@Vf zz>S)>ns08!Ut{N%C_=#ei4$-_8N|MkF-1gS&WNWZsZ<T4zMZA$F&5uW9&WKVEpwpS z<NQ-V-mxE|rj(o{l@fzY$r=w#f^n530knOJF_UPx&qK^D?<Qz}E8trCp9*Zt%I@ZW z1qTm++f%XGVqW;|sUD-L6k$+@GHA(1LWTwiD{!-|n=rrjxV)A#9$cH!GpbCAqyzvr zU1AK(_GDyeWWR!<lca!|a&U2;(Cw@Y4%?U7x&mDEboazPE%N$M6&263Uq;jrVh6m_ zzBtcT(YQiTVSW{P_gld@WGY6L$~ZA9pK@FiNy6-(?=?cdD(7}>G1bSqgEwNb2D#R$ z3>yxEbKJq_G2}hs<Se<0$kHzSpul99bTuSiRqL5F%jo6hn*71SXN-e|fg*X#KAH6h zv>bXemZ#qXh2yXb$;kwZee-$ArUz6&Prp(sYdg%o@acNSWhGf3x<F0lGeK=K63A&( za9HP04`_IX1}Jl7hugJE#gc|rLmjH%GJ1r9EM2S3GN833cYxz8=PTyXXdou#)p8gE z$jtM=W$J#*Kr?P-Y)7}v*$PrJ$rdH~LEDl8CXqKR`4^T!K+BC-xGMs`UAg(&6{k6t z(FxaKEg8Bq$P;?OT>elF_WWsUxCCt+ATclWTjEj5Z|9wy*heSkX0^8D4{#)20!C$+ ziAj+a)l-KY-~_$&r6=<t4woW$vU~>FGWqR$vlqpCmm53ouj2C(XvEu28_5S3i6XH- zYk0|m>1ogpqKg#a?F~%-XkT^K(7>IsM5Ryw4nJlxDwv6+8N)AJK9gu<co`Mhk*3G+ zU3^{+502o$`%N+VJoRS%9}aZaHPV+1u-vOS;4Onp5b{};sTx0muR8)D2pDB}2FWS` z9+Zd{HExV$QjTuOH{f|q(Olza4QkJPi#sZWz2wLBLWeF>?H5Yk0vIfSl|`fGFBSEX z%-M|C&9#0<B-3$cl$`Wl___M8WQN&sVf-&h1<U(3K|dGpJE-UZ2)pzj)=R;qLN-lz z)jQq}ySBTHW6_;S90Ha#Eu}LwH;SCc6)c|x9Wp3HMM`8U0>0$PBi;FOu^dpevb+qa z3Fb#O8R?=jF1S3vT~|s;Sfv^&gbDIfdPo7x3g*8xtf$249H}_rdQI-oG;vMITg*e< zj@GQ6<q8phnQE{Q0r1BoC64iR&#&mUVT3!+=e(e!Lu9kT{M)!5=mUA!^8GT&*9aj8 z(SSTX(6Q_-d=iJI2zS)o6$mn0kAyo8x2XCDx^B-QszO|(NG3=GaLQEiz3!h5q+XN1 zH$N_<JFk%j99CMrVt6^1DfZtTcJq=_{vg0NSg4gFkC<{OPGVHhC=h<gAlv&3XI&|a zoGh9@UoivFhB6TIL}*#%<Ql(dY&l<`s?b9Z5U|f-S1J(j_H`bpc|wXH$m@OJOr4LO zQ0)x<oqL)Ne4ot=)Ene4@Z6^8j`6c3$=cJBhYHgGl2ae!10>gzkG;)sTsPu7lFvG# zQjAVL8p&K6o@*jrYR{I;>`6<mo(%x_p{t&O9Y{|mC&=%6D^!>LH>2trpv9fP<h2CS zmf)e6t@raZlFIa<{O^(VAPy<+TvX8V%8|bSqRFw&p31ItE`k5@zXo@+{iRIp=ZsDH zL(@zEF4_x<hyN>DUsT4sG%9Qx$7U_P^yDu(G5{UzAJ~<Q1iW*c;m(Kr?L6;4&TpZ{ zn|WRgWljw9R{?Guw>(wybP3+N1!VFT5I#5{9T|TE;tnfz<d@qr&71%%^0;;~>ao_L zbdwrBa2Gkor|%XwkS_-6T2&$9U0u661{l8G8_c(j=LYaEa<pIOY+Kqu-c&s!vO5Dv z+Mq3l_yYhN4(|j59L9?JAD^M4^&UiWhwD*rpFK()je5$NfmAS2Pr&vjCxf~0#{gKU z@q^YFec&SH^*TC5%D>Lp($<D4;80xeJymq{K>Y7WG<;SlUfJHZ$&p7rF^j?ur1d&Y zp!Yf@r0+qM>HW0;U2bRS7FU21y^G5}{y$j4fq9qOvHbJT*$o@~ya8IB!)cZCH?2JW zq}BPkBllpTFr4dKfu~8;vx2a*NQ(ua7FOmfW<GQi#a{xd$SEX}FltG4!B#yZN+gSR zQEPGLq+Vccvi)Lux~n&}D>d=ESA&a_hV{-5kJC$=<6pCji?fCISMLkBpK<Q%?Cg+Q z?>1j<GdS#8ThDo3^ma|_kTxr>8lRBOHQn3@2+Um_fA_lBG7W<-Ene~T_cq@yt!rAR ziw=_@Ak5uI1YW5}1mPq6v-RiCEiLe^KmU3BKO2GmE&k`O5BR>9e-0sFh5C<OF#i_( zbJqfVQ^-GuHn4pA|Jfq)?+*UlCjj5v@Xs+0yg~4P4gbB>;os7KzA^&eOYqN80Boc9 z|LrXJcMpHQuK<6w<ey^__g^oX{9E+TMSS=R4gVY&fGvRXKbP$PE&S&yH+-G{pQD4| tR`|cH`v1G1KS=>!6aVL!C;Y!g{68z?3ew0Z@Rn%6j{pGF89V&j{{iP+lX?IE diff --git a/ipaylinks_statement/statement_files/2018/01/20180130.xlsx b/ipaylinks_statement/statement_files/2018/01/20180130.xlsx deleted file mode 100644 index f257e8e8700185012ee62a3623e0dae7333aa50f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13749 zcmaKT2RvNe_BLZMh!`bm!WcyFC8CbrdkdmO4}wJR28kY{1<^avyAUA>f+TwHQKAzf zME}mn+rIaI?>+gA%$&2=UTZz;S!?fe_Su>$SYR>?2n2$GsVJ$6@sEQT_-^HFsrkg& z#g*IA`H3}`*CWUBxOd7OJkV#m{*fqO(H?RuyhjvT<ls(h_TD*Zk%mqoJf*tL>9p;N z8=ZL{doIuEKIBi_>_WcD`_Vecv_h2!uIE#$oQ{_mn|4#XqZd!sD?D@8a_}jwcm(IR z%G6VH>>z_%&xdSz$9TPYof7GvS75V`mO2vaN1L>VO9}BQ3QuXbtgZDhC!Tv+=aCoq zyMExXBU=b!*jPZ?-h4Y5<a7{7{>_S>=&f1t!<RLzS+ARj!&Y0S!@Q5{#w8TXQTllF zos(RNGE`OcgY@siI^zSFG>%8zTMI@b_uPBEUjBIb_+5(m@!KG?^V%N*)CMM9wQh<Y zM|Tw5yw&l49lPu8<7ukkLR!T8)vz!zFb;r^=6^+y06@^}iM69EHy8SEdHg%|4?Ne< z*s&aq&Z3~wYMxSxEoydR2*nv8ds2l6+?8!ST(HbFj|Ixrqg9QX>Fq_^y=YcZeC3Kw zdHie7$_PT@W5Z5IV`e<`MkN-?UR&+2S&$d7S}`en^CCcf2{&DR34gXfth4{}6F(ue zKJ_4|>fuWVMKh|J(oo@dkr{e?+gnDF9~?SVzK<OBE!;}Y``9k2di;XLDg(!gDVfTY zMNLCi$0VDiZ^Q9I2bZGDe6YfT?L6YvHw|VL8?#<2x9C7c6B91?0PKah`q8p?n(yb6 z=1A$(In(dU7_?%du`ysVWmp0{mk0eXY)F9?#xl-MZq`n2X1d-k)~+U3{7U!)U<8#r zI>!HGOx9wJgenhV$1>^W`UO=p$LO_LwG^ED-ez54GKyU5t@$?R>m>hJ(9l>$ADVDj zQD`ZY3r;^!Zt+&jvhiGD$`Fv#`XYo$B2}#-xc%h1K|1p!@<zll#&zcMSbeKEU3ZD3 zxjJtCI<|9rSKvu?pUX8%DlHhbfn!uHkUCTGxW-z6CnA2cyy4@hZm4-38P%%a%E%qf zW1I(THw8+D=`(VI_We--O<8*n{M(ac%Y#(qJ|Df$MX_@i4Tg0LzQ2xpt~u6N{vwD< zC5jx!pBekrHA*~QhhH;iFw+xA;Og#+(U#b-3PO#H@N8Pw4m0@qX^T!cOm_pLMsQ2z zkXUcOtG!3`T29*sGr#*{zHP$C_}{Jc?L6;4mCE|%60I?_A|7Z^u=t_HInn?PJktWC zPZ%I13;2Hl5B+CaKX7qDqptS+9sYYBsO)ZlTzBj2hLr43VlX6gOG*-!KP@!iC|#p0 zIiEhV^qD8NsQF9fVhn2wqI_mNhD=c?`uR6~3A*tOM$uLs8GK?=(a*UzSsI@_cy1fy zNO5p`+`6zvmEQXUQz6xRfxA)3=4P}JUk3yf+GFD6Z<hYTRxUrGG_WP4z@1glL0L4- zlbs#m2V6hFLc8<T&vPOUFt!o+{P!Fq1Fm{Ga=Y3+cw%j(<M!mCldUV-C4Xa+*jt^% z{{59zhv$7B27wA)kOWw6nHEnJ=*>NH$957^(p{3h@PhA5;N!Xl%-~R%7NfMZEEtpN zEOo2mnBuOxt;ep{=0SH2wm84Z=%`+iy53RiuLbryW^cZiwoc>TaoU!wTET5}f8cyM zY1}_M5qN<tXZEBs94*J?K3`aT_wMUcTj$m{f#II^;l>oEb8UN{l8<O<!)i2)DR>4i z-eDPY-=uwe@L_v9#MW%0#rxd6>F3a#MCRGz*ml}D(Oz3)*1Uw*`r+Kq)$67c)1q&V z7aN3=8=Xzts@vSx7vIIGP!Mt7YCBrr!=*Esk$B_w*jS-!@Y4TB&)#XE@Wpt>QlOvr zL0V;>q(t-S$zGb-?CIH3p65>d$B(;hzWdvo%w~SR2Sts?pB2pJ?;d{=J)1moKHE8s zl@xFdIG^fS-MtmK*VWVF{N47f<sp-EtN;G?{Eq*zb8WomPNv`C$2^Sy|NZIlo~5P6 z3!j6|*}OaR{PV4c>#f|EGlpHBbaSVtw~Dc7Vs=w2B~QNn3h8f-?L2ON5^!VYn0YRu zvJaP;UKWqH&g~*8%#(J=plX=@{xso?{;EQj-=e~5SgvP?t3K8(fxJ>-FTM?&tgT{` z9n{vxoI<IsaaRJbdIZO++3S<Kw_jg<+McT5?U%7B&}OVE=*sC_i~*t6o_*^mQ!%2I zw(r2_Oc@NL^F2A!<a(eu=vW+fqw0poVk&EX39GbFWm#4!^L^8DWtF`%g7TWA(%z)W z4{xW=7D@$&RO`W``P8oG2fb5jdF(MwCC)jTU;JpKtBsa(NX$xH%HL4Ramk48MiZ&^ z>$G}I24s}j@P(S|r#?eC>f^Fh<tI&j)^kWwVt-(i5x|Lg5#2Us*0stzT^W)`T=kxX z*UaJpr{ML;ozL>zy9@c!rms(;xgpkV&kYup$->N?s`DaRr>weF5Q|@*xeVKT%HFC| ziu!Dx(L_JJP4xy3<gCPcPTJ8p$K_+2^s3dof+Ho*zrGhm-Z0RZe>&n*u|k7KvG=w% zaE??<2CgsF{;MJ1K$h=7FzvgjzdGnP*#?Kp@q1Kg%(KuGvkBRtdqJj5+Wqf;NQ-?+ zzW$xC(@CwMD)|SDpcq#N#3<(IagmgvFvdkR&X7tfJjr{Hk;X8^7kA<Dy{T?$b^(I9 z-1c8$2{E$x>%x?KF5FutaRMC$F=e?v@Ay{DycY+H3I(3&Ry*uFmvCyYC}Y3Q_8xzZ z^I2=_CKH@O-f*DVuBq9g+}k=o9J{1rhu@_+dH&_&<>#{_I*vR}WCVH%_l54;t}=^i z_!eW^p%k}{mzXQ5$7DU*FuEfLg>EkwJ3cdTc;#?#gG!m_E+sjgQEiELLsMB)?VzAI zMSP&nQu=$`?0mg4!lY%1Y%KzRqpwjUCJOH_ba~^o^Ia^mH;fvn?&T(h$_acByW?ZM z5K{-Yd7BaO_Ej=9UB%59jD!~s@;LI5mjoQ2ZCP-Xoo!Di`$)eJKKuUgc&fsCMg(Jy zGDsnEf$-Rd_?@LAyngw*Gxn0f`&e1?&*Xf}coQNjB-uFc2A~Y=MBk>YNBas}OE)Rb zHughbk}&XPOCf1v_BxxwE%9GS^#-@eG4%)<`ka4Wip|o0p6Pu*y9Y}%;nf3KLpJjf z8Y;*-{*bw9h~MXIGNasU4T!tOgm&<z#!(EISydwVc8{IlLe^<XJ99?Ncp?@P4VMk) zHBQR(hm@f7`Z`C)$ASCzyD754DfGq&Iw}!mvG;jwtDc!SHy;U-^<m$!f1PVj45b<+ zk=}*h5jmR(#<EU^Na!bgNsQEFbAPmgr_e99l;_o8#mRH$DFIp6w>!!aY;rZj`DCSb zu0&sJZ*-QHEGKW`ST_glNfSJJ$dx1*oy$}IwO7g3+@FW+a~a5S;^0mGEj#AATEYsg z7AyV)mt@b8mdWhUm0%p}B1NY%gi&douGk60ch&Lk!2##Cy{>u|uYIkG<t<F}1yphq z%L1M~Q|Xvu{5x5d+nrEnstWwWdFcm*gb8EM>N=u=1_q+*VG1GD^6DEmVl8|F-=m<6 zH67SIN4=4JO6IXUTdJLTQ=fi0Zs|UZ*}I+-A=HeIU$y)|qQq&8e@8=rVCI(kD}HdA zGjl?MEUC|eVR_sc!h$(Sl~h|oM_HHE_H5z8n$sopCz;{agLmir2h&Z|I3giW(|dT3 z`67>77h>|qzu6rG%X$xu-5vf!?}e>6fyp>vWt{J#a8Tx+Oy%P1-p`ci26`WIZARx+ ze7hcP=Q?Fj*NdPjZ+M1!&@GjkqL+8QcmxO{#sps7+&6-8BB{N&<TXjN>@q#}o;XC^ zpinGwD)fqquoS6S$KR`I|Ab8$?igfiO9`UkF5n8Qp^o%6R#T&S3E}9Vy>u&6<BBV= zO!Q`1PbQO5jpRFfZh=I#vfVPp7M;=@E~G2Tc=x3@K5rEACOqRdgv_$_+4X`a(b|Iy zA7XxyphRSrVhqAP%e1~M5z(qEQb$S5e!y;6k1Xud^jW=DMXAIkUI5aGbbBgo&KQuV zJNATLaTBHbrm?U+Ka-_(8{XR6-oRee=}MK1z{{cDyR5gTC#95|5S^C#8ADF!s^!4$ z<x_>p{wrS}adPM4zOO#aS86z?A&0ztVKm9GQB6-~i(hl(&E(y}#{B$2TCRh5Y<*B; zkFp9!;`V*2{&^a0>aS!Awc_`$kq3~a;&H(_UKnL?$*M68Y8Upn-y=>Zi4`Ps78=VR zAm>Ptx*yq4^^IL3<yzy90n1JM4|glWvKt;5c+IP)X*A?;3clzLA7;Z^vEUi5B%&>= zhJQ9o&yd)}Qs`colt!N4E8fIObfDJcWQ-C`y9-t&7zy!}5Q<x{F3SKxs;s=Rp=s{- z;)UW)1))Qn(nAzc{IL@5qZFKR>D<w%qxKnN+&qlMCC%g+2kp<MGQ#yI6Xe(PTRxVE z43(J_@PukOQ9bzCq~!-MSZPXqP8@7%eS<T~t*mAryFk8QW!%#SF+v>Q;2Wi>yYPrm zP~(gIdS2zlT@w-CpQB6t7Y@3PBLq2lPgOD{;iX>;Ha`i8GpKa7Vaw^(9|Rc1I**EG zJ#zKCFMsr6CKcRDoVR*O-rmQ7v(?k{!i3%Q^23*?R^F%aQ!16za&wOd8P2HJo3pl! zT_?Ork);Tw*Ooll3QAT25O(@Lw;zOJL<8nJ{gbq0i8%S*o+5Gwtk|(LD>2iL3cqJd z9%@fI;^!N(JmB@`mxDw|eHM6nyYw4x*ds|b9Xm}d<*nOgp$YJXXRUoTLzWQw2%jOD zx=%YM@Q3ELiHTAUJ{baohLP+^WG`$lKsaO$JUw=!uVaXVJ}lc6*_}2f55l_Sph4PO zkNa#`jf5hk8l&N|WeD>MaY6AL$#t7^MkEfY!`4__MkNKSkzOA|lo~XR`tiVaBnwWh z=ffU~`-HTQxP_d^GeUHSC^8EN2#m1n%kI^<ypntP`owPffIYyrvznbfQnMt@<f}ZV zpxxK_$*>sCAipiz$w@MZ%82(Mt+1mba?7Mejl}&M<X8FkPZwnM3z9xxvvt53?+sCz zYG3OZ=2PG6A+Axz3#UcfKnupheV|WM#z?n{<EB4Sh-Xv_n3ZY;2&M`=)_-cFP4_On zr9_urY#G0|2AoYDf0j<=fExraVk~$^(0)TIO4#8&8ST7^c6wvyQP&E5X2`t`u^=pt z(G`$D!ycr!Of?p9_oRP!*Z=5ZQrshI^1xn*F5_WtV?foa(13!P*gAbBTj}N60!#OL zxl3hW)YHK|?_yQxqc8p6My5+85+r(rZRu~UuvG~W-<pBM=Lg4I%OzyXA3884Cj1yo zWjQBAW=^=tTC=^X@xY|Zh!`@`R-53bD_Mayr|P}2a$)FZZuL)klq@q%;$`hG7?qA$ z&erPFt6;lW=e(TD`L4))Qs<7ioq17phU>UeH0?srh=(+@>^J|X_2X*`s;Kw^eI-K) zyp8+fbZs6|m8wib)iiAlM2O3Y*F<y~ctd%QN9e_CYtty$eVCH2_hFZaht7D>VoxSe zwJLQ62lP0MQ<N46J;`z)TUv`4TpxG$pYJ85y~71}HD|KE2Drqg<jlxu{Ia~VW1TpM zeP^oT=dn?-fQSfb(H)#fl-b+pO$*$G($DaS>wVyod2){dVLS_jVj#8@u5GYve{#!X zjx9=ern2h=Av98VH_CC=zs5s87zbdN^EVS0%!rE)xxIuv-Hu<S2x}RyQqW>uf5-OP zrM|_f<#==@%gnHCqpMbWdiCHb?ajTxn3;R9WVZ};EYz`rr2*+W;D62HM9qrplB@Ky zhrvdDMv5xA%v$2NzjbsM6^Yd1G5Eo(eBYVR5avs5jBho3w+N8NALOSWlfNlw8{>ao zg10GOm1e{*<q$C96a0esu3b9rll%E??oWDbaTVzq!I<q^pB4J^BaF<P2On?NzGC4c zQO3Pv@uraKBq3i*6_-g#txA)n7*_Pia9N+)sax{7w~h^=tBBWa2y9SR#fjEwg4tu% zme}j(4o_jCIv0*k{-fu6(<FMg=8;rgd^c(g^8u2;#5Wm7Pp8^hA9tJ12pB+9Q-&|h zEwm*#v7?7O)*Pa4%|{BgtP#~y_8Uc#m2c7)dhAzjp1rg=6SC)G-$Ge-2pgry1%x%8 zw(!<V?nfK2Ftq7T9_*QfKbVuBk`NYta}bEWEwp!6FdHSrz<7Z8U$=!ogR9#@H*ZJl ztNX!%gg+j>h{+|2ZVEAmY8qcxlu4%|883664)3Ulzg90Mu0C8%h(s+6O$2WBtIsTZ zh6pYarjLg{z0dhV8$(~$!I9wj&FuZT?v{P{(F1|+BbeZKcxwccPY330QY%HOdbx{n zmouKF>mg0XZQgoj+tVeK^^AR5akoj5H~iMrNJI0c*e*5)rIMQDE#sv-#)oIUGvArU zH)H4+^MQ?TIkbx!r<lN-R8W^(d!&`mXZ4^%M?a0XXOl%Wqwldk!)q3s66KSCPsda3 zT(944e+Bb!W=c(^{Lrb={ML$(dDCfvxVH6{FAF0{Ukd9^@|w}>aonP=gy@G~--|vG z)Y#MXVItB_rLhAs3(tByCLH-_sR^-~EUvf5ON!{0>2l<009j@(ZkfI0KO6`b==dno zr_r%Qr|M)UM0)#fT%fYb7U|Y#R+WXF#IdAxWk5gqtKBb6ITPIiQ@|8ITaJKIRzbb( zhkp90TNK~hl<ZO#-J6)}X4EeOGZreDYLDTQA`-*<SNHbMg<}>XfkzcnSpO@CM8AXR z>HNgO!r9pYeOn*%yc+#{=$U8c`{s-(%urb5aKWpQn4GGX!-8t+>A3#7H(-X!_TKmJ zvGf*sU9_L_@nr<edd{DZo^`rA#>P2*Cy7kOcxH-gd9MF{$;aCp_s2=DNNCe^Xq6?^ z5o3;83HM#**<2j~0`ZeK52fAMRwx_OPr`dOqf+jFtPE{hQ8y%FmZ7>_f~Z*vas>x? ztPLxXRO_%N7mOW(e>&HObw?}Tn~9>qi`jr6$49HYYrL}gg=GufYJBgP#(;TU&WMCP zGH?Ir%?VxlIDWKxy7!at9!Gf`)ZiQSM0nW~4*4Fpo+7iKL};oPO(|rr0~nb9&!>#k zzft=Apz)tr{eI{ecg1_e?s;Ul=Sz=-KOQ>P>|ttc2#roL)(}o#WCnrDNFdim4I7qL zlk+FjzbUoC_b5Y<&1HxOF4Z(2%on^by<BnA8dzR3r<X1BZ++}wBf=J1kQ-_p+Y;-0 z@hOF8S)J}-L%a^PTg{F+?nvpY=25qvpaxBQq~3HN#-kSMk&E>2lD{U7@;-#Enc7_2 z|3Lm_j>JPW$B(|xTm>r<Dfjxb?m*i~S;Yp!Djv6-#J=RUv2g)md66oGMCXXgp;O-# z&A<}@pS|5jdpKxpzW3dGHUfCg^FN<5QvS^#S37HKH&@_65%3@H6_qlKU1#)t<mP{{ z-}8&@>?%mhh!;r0d~{s=xLNzP#4!1z62}Oxc-sDcI^|5rtZ${x1b0LthyQBuqXqMy znBVug122DVcFyn6(n`(*`nbP7{<g8dxHBAkv@79v0@VG>vm?(-AOGXz@yq@F*wZjG z+WGleaTBp0S+r&*Zv%Z!w&zXXc%AK?&wiZ#=)4oya(ZxfdAxq{b!mI}hZ$W!z}~Ov z53}1X+?Q)hmE6sxrQ1=ljdT(wZv&2ZK74G^$f9}U)pWW(y3*#%W%efE82fCV$TLtZ z^Xz!hwMBAf{&N4Adu6ut)9Q}+?8SF8&$hYqUv5WdM@3=tyAqe16o>t7r$b4XUQJ$} zN5k8@Z4&3J=XCS){=bgThkvkqTzw#MnMb!9=zq2^$t@A!MeFD3y|;I`Yj$x&M>i+l z8hD{|^u=j@yK%f_Z-4RQJYCj~<i&i}Wfu3g>6y#XuY=jJq6DWi!+jN8C#NhYvo^n` z%caGyuX|P>T>d&H>JMr4Iy*axS`9q>bryI&y;+*feQ|i4b&>F^lr+uN;z_P3vs3z7 ze}r=eWnaW@I%R*v9d*b4h~12d4ARbsP1nV8(o@$(4F1~*B3STRBh0vm;-H$(n^CKl z=Rboy&4|2?R_5J`F6C`bDucRpHG;bD&tt$7&N*Rx)AN|{;q$II^}^HBpKRE#x{19B z!f(c5!Qv0R{ReKm>gE*z@$KjAw$YvhoDYZ&^*qkNh+Fc(B3#c2WAj<V9F*BrtPG=t z-mSm}KF*lHwV<61;Mx-mHrW3B95ITM?&Rxc4&4}0D?{teIy~rIyE_9YTA$+FRUgE` zfT+dgXr%$`^K05GoVtTDME-*^Z4ztv{&D%VnCrg=V$F!on*!EuQRQEf!n9X#sE1^T z!Y>Sn2-n@`h(!-J_3&X&UilIbuH(@`#Sb<^Dh4Q0n;Br^ert_@qz7OzUw0rw0z;na z5urdnV5j)O0O}0)d)FVrKJUYx9SmUQh6Mo5p1}2<2VL`90{}aBLW^$j5kXD9Ny%LK z3Fyr6?6`jJlLQK<^|4bV5{LP$jpLf+a08bg-aOf?47>2TlB%bLwvNgCB~}01(ntp5 zzs_E{IOre_i*Y!=*vy%)r1Mc|@F~ZYt^A3`2EYXnFaJ}U>1GbS_(9NGjv1ZX)3<B& zw5YE70N0;CCnPT)|6IVT9sMNEBicHrW9)MlF^HjQ>@$bk1&5BXcC3|TO%0Jj^LQa$ zrX`X-C(MP9FXq#QTh&ltTMwU~%<|lqBQKaRDOEsq^}~$9OG@`Db;5Z+;XX1X394o+ zi*3~oJbVeZt*E3{x@R@tB^by2F4ckmO?%4H(*_Q__Io7R<)#S>(aaB8)#+^p7!k%V zz~&ryo0gR$bfc0T0%!e&X7SK&N%IPKL&fL{f)Y*@5YG#+ol5evb}y2#O)~StW|4fL zCnU}_w1LgijD^**GaPI#q)iCmnlht&a>SnoTDM(*<#~#A!UsFy_0~#|GIO3o<?}&o z2Hx@;OBOhHkknusXLk8wS8J6n1QCg)R(6-;7fP1*`I=JQ`Y}jm#;ze~iu4wWlLpVe zoQA@r3D1w7*Py|Lv0MK+Qh>1wBo#9`#0w2m$_Yks(qj24Mq|UjhfUBMi-YPOa?(*m zG~sc;c~6WFLs6VCtRzVExmRe+BtG9j1X`k;9*<g(7^!!y%dEP({C04*2?KGI@eKG$ z9A(UQ=zu9HF{Ql478zzV?e-lEZ+NgYHvOy$qI{AS?h^CvJG)2sVLWtXLaoLydg-?2 z^NzJ=&+u}zu!y}BIO;}ap;i=x!4-le;K^BRM6=FUPN{%+2qPm;KzugsBq5GejA*nI zZ=8uaJYsNulsWW(HUu_pN7kh1sOrpzvHwM03NUcaM$@5TiDe)Ttxa*4A8J2i=N5(9 z0?{i)JB_DQq2?Y!t&osJMxjDaY7B1}+QQc1>@f}~GU?hgvuYWiBBbV$dY<TH=-Ty9 zSW?m3GK}3GaF7)e0}b7}92Sg7R<jtE?@2xK5*tKG&~b95NB}}j<4JAO28ItLbgb>3 zl1lp&NujXe(8P(9xrZ3bNC^Io&;#`lqgn*`IUi*}=k<~b`QopoEuGpP$O6W$Lta>Z z*Gm|IY?U)HP3?IvvRD=WMzEs_mQ=&5d@e(HFlY1xgNYt|#7K{;p@zVbiMOE@lipYl zr#YTdR8G^f;ng)aYwco~RcSB6fW#6Babxo6)=vW0>nBB3Y=KOaqPM+Z-3?-}e83SW z@oE$&JKlx>0JUBSti>KhSC=4b&Vk%Z0RQafq5;=)(L_~mfh?7xcZgG<HJ{|oIU=eP zz@ydZZwb=azE;UG<`j&)<l*LYjC>xWuwwVod!g185EToz()Li4i6H0!UUVfx_w%Xu ze9#wY=48MjH9CNfkUaxO)f+<6gimKVyJ`rcnRuItEv376#IY<Ro(d3mOtjio8S}B~ zLTh~c%|BhK7zR}A;tjlgygSL=Ttnmrh|pO|EAEQp)r2j9Od?{|SwR4DfcN=D5PLNs zXyUgi)|9tU;;agqmc)a93ULBL6vSXd7+Pi$D*;&nV9b#p1qlYCUvU-v=5R!Db@&>E z$z;e#4MKQ$y(=1z-b7Z@fgEDa0Ub%1^MU984&_(^i~!6-9{%&I!4?WQJ<{}Z>y!!F zlQ*(_egItbH*6=Yw?W<uZ1^SWsJbgwJxv{+4diHM>9d^4SMh9y@OazO5`~i}9O)P{ zfs;;yLu4hmu=Wl+EWcFQ{tF55R%u6<o1PMi3C^Mm9nxcx@`!}ES@WDl-U5Dj6xYAH z?`BQ6rfe=U%gRUpXV`<f!~j<Sw?fe_0ohKB#sNE6WCXt>m;DrB02*FL+zxdl2F_cc z9pZ!s&n8{f0`!-TdobYd#0yS1#GVsQZZL^kL6V~GNudT_-^r!1{{kXzQg-}IPK+!? zs{ndwQsw~gxX(0JEeMt>7wlMMJ8jnkbbQOjqc@fTSHx2ifCX)mqucdvKgE~!=z$0s zSkM#7R=p<KoM6Jr&T;R#r)y1DjP~Nb0KJt%I6@B~Z+6#bRqR)267ccgC`KEKeARJ1 zH5Fd`le|by?>h1oxN!K39I5mnR}n%FwB+m>EOO|8^RwG@jf{*9@(>0cI#u6@ZykT= ze|Cdr*bJxwXD@j<DxLtA@?^BGgu#6KiRx`4fS*Ez=<pMxO9vMmGNc0rINh#i5#~mW z1gL|Samiajx)j!WUcvyT01$kQ&Vpw@2R;hqR{>Qg22Zkrnyn)4(FJyPZIMZ7Zjudh zM?kCqRgVf}y1A&4W#BGSDVqTj;_hB_nI?(rR^Etbf}@fqQka6X_2KGsIH_;0lhh^e zAkra2x5Dp?y!?IDL?Hf18V8NsAkZIR8baS9Y%3Q~kz3u}OOHxwcWcIcEPbWps<f|X zFiTyTrMN4GSAzi8T$LL1*_N)1)v7;b;vNI(BUU0vAPZx!=54V7+MzSfK_12)Q4L6u zh~|4{Lh5(KC=Blczf$^y^x;-ffcC54Y^l9RmR*%6OC~@YLLcWt<pjNN5sy@iIPnKK zdl*6=G(6d*9D1;N4b7QuWk=P(K3F%17zoaKKNUIy4XLiRS%d)%La8NfuSJ#J1R3I~ z7ES-U9eiM-3iywGg$^ehmSHL&G?~kXLX#6@7;&pcj!7y;Zl$Tam-ov57-t}>lSW>) z28c}<0JR`D9_EYfjV{qq%E4RW%gEB-nOzJnZnNiL``D@X99ar39Dn3TD&1V1kFNaa zOw+<c;a+8$921bXko&(gO^%6t>JF&7sh2qP1@`+?)1w>ekaYv4VnKB7L+rPVu)h8l zn{t3<U!6o3gbkFFp%}dGAvo6zL=2GIXVyTNe#8L=(o>4Y4yL9N0QihfAbCRB@07wo zSQmI*woosXL#Yd&+*e(pOaVlE=gFi`-m;?cOHsD}Ja-5C5BrYPv>X7A>Ry5F544Io zQj1|Wt5uS)T~c-4O_Nrfzav*}2#b%MLcJPpxds$BfZZ~+&eM!^jY@Bw68z?#0dp>@ ziOn%83*ID4b2jAqPdQUkX^&?RRe)m<JJrUmR?KcJbhIX^;5=8r>j1#>11ZkmVZrvX zT^BUG$?fvDh`nPe5~7M8f9i%2;6fnlWzE^DWyYx?!A71`Q6)FAbnsLwxyjR@Q+6<r z&J_xq0172&6nqGQ#%S6V0<@!hCtJKn_4)CihILv1TBfN|epjnm51hg)rcU>@>!L?F zRVH`EqoP~H_A?$%6gsa7Rhf8No#1KEp=ovdFK=JqMz<>A7!RMShc2@nic9+pA{4o) zAwAV%7|U6G1VZ{2mTc^JQ$kiN9&t(2Xx47p`$;QW0}Mz-=kK8tz4;kK<fc15?;%wu zTH`}N<Ij&01rXJx<ml~1)<&mVF@nB>!wufhgGNAQ4Mwyzl6rVv1aqGU4CJlPuu{3< z&7f-GG9onH8`VRp+uWUiaRONcE^IW2CAO-h%|lbLsH1CZ3+i=MANq)pMd;G)1(fa# z7{oq<o?PQKp%~zrzbhgAd3geQ5|K$lbEO7>R&!#^j3%wv6=`c$u>23+)cf5NTM_!6 z*nV)hE*R=~4E6dA;l<dWM4uNy7k~xU5cCLkF&3d|i8Xt;Y&_HRvFV-HB*g@Dh|mqP zElAvR=XDOssmmJ+#f(l6ZLJ8D9Q;_sbKl#^{xcUfFj=6EDw)A4BuSYQ>V~1`a9fN3 z>)G;+$>uPY<A8||TfPOG`E^Ww+`LMujHTZ8z8_WLy^ml3@!UTQgrY7IrBGRLkPhDG z>`IU?7HX9qP*bA=Rtw62gY>AP+iu6)s-BK9X_%JNbHdWY`)uw^E7QFrCY9yQ2r`H$ zpDedsU;}0)^esO_tASI7fQUux)?7k%SL>=%Tv7`VS^kNZkB}PASj=Su!i{+OVEjov zELapUXV9c?wFiHuH~(gSAXw~rpK8LJmR##Kfh-eGh<`p2FgL`2>_bzO*_OQ_x&Xm7 z=|6oCafPJZrSvD<xM_gnkr^hZzjObgH*GqVo9|30%9IZySPYTOL8RIJW8un`V${lm zjJx2^H>2O;xIbsd67831Tc&qOYQJ`9BOQ9cg#|N{)&vAbUN*A^i4mcPqGnd=G*0?r zl^5ad`oEpOMcmS<zXLJ`Fme^8&liPb1nbCVvzMTOGXYAZZnrw|=D*x9d`$q5I3%(O zkN*6e1|}>AZXhwP6$3Y*Q)tM4TtG-t4&2N~8K_1rYSBp3{G@TM*Cd-ANp-LiPAdJ1 z9rG_0#VWpEz=(!w5}2ey8Gl$%>O;F`diZa+VB~-3+2PNC)=Wps>T4%+KqJb)-TlN7 zW%<%CfZ+h=AI<{<geNc}+Em4!!L1spmM1ufkU+CcpcybnxKSf^r66Q*JiG6)wfU;| zJ=GO19yD0{+M!!QA&!|V^gKzr-9MlyK(gcj-MfE-^0@MxP><ZLxVFVXG#*v>=DGmj zx06g3bO;-acw3my^^mqo(BBe*coCMbNw3(L(N<7B`7*vaKLXNameBQlV!KOddb3m4 z6c=EzlxL|1Wc?8iA|NuG%aD;o2M?tH=S|X8)F8(E|053wv<&Qv3G=VHVvtIo<X=ai zaM$8jF!8-<Z|;i$iTQuMSxXiJ>RigZ%ufi#tWSS)3tc?_6Ss6sabE%^(b=Rzht8oG zQnVm7rKe&<$U>lUvRQdU1gzUXzgu(ATy5g3`XR>ga$jU1vHjXf3XoRz4nZ)W;T5zx z{~6kwEA9&{NUE)B&QM43RL2tFPJ^~s@RLkc0h%J(kJK!G7)K+tah57482rs3(lL#g z_qku}i&UX?giiqzeLfNuC6gLO#up^8SXm3!5@4PWQla`g9%4jM1#hl%0O5Gs;R8%m zs3Ho`N=Q`jfZV7~)a~Af-s=rY{YSVtR@}{50S+R+;L*2OF}{dzw(?fwU_xYub!cnT zf08k0#j?3BZx$l*F$tNm@}TWrum4s19H6}(6w;HlYrGNv4U@9Pv<<U+9|fd_;twbf zz}b*NgLL^>lPFC~&+UN6iKp#aKvhV{08b`l-0J}m3oDz$pvb%{T#=BQSGcnG)xTY( z&gr^-b`EDf+NlwP_FX%%S_ev2pArfenDilCa6rFj0L3V5i$Ah_@&0Cr-^fId$-Fo0 z1Ss_dV4Hy=FXqq@Z4%%<5WoT&-mZNW5Cr%IAG-3~ST&mGeyVACXC+`T@f4v0;$JJm zynS_tOC+1kibNv7FM)^vI^Y9|S9Mf){6v&l8W@fjS&x9R#Ad)Yi#gQsY7zs~d;|=n zaa9z6LF5WugLH>_ZHQpmNC0utDMA<M-*T2z+P(m?j{xVAP(oy3KmmP<ZwL!+{oTJn z%t`wRaZZ<d_<1g%p%BoZlm^u%lmccU0K)(UYJVuO`%{5G6TNhd0m%-9#%m&AunLh_ zk)*eZQjSjrW-B@%EcEb%<~VxDxr*T9ibq;Xnhsj8!+ZUKv4HBQ_c3tOpd0_C?q4>6 zw5|vh>G}wm(NRbBei_YWlf3i>9u&l|c`+BdJy1$40<{!W!@6Ci60sTB^r{l&8IafU z1eg;vy~hM;RRw=k-|bPz=E9@ic4bpt*9&FoRmkSX%k=|;_|dIb8C+8SX#LaYz3x(Q z&Fc;I{jYBc_P-7kb3aW<8H&Q!N+eo)vHF3&H%tc=o2~m!J2TdO4TW&!!%MQA?WdC! z?58_dk^ogJ4HS=bB$}C#G)Bzs`!RYXuyiXd-l+z3@TC8tL+=64s0(FU=~qTN<SL_G zUF;rD0c{9i(}D=vriMRkf@c2F{`^cz_s1D;<}$-TCOGEM2($3)BtAuB>%}U=<1ASz z36j%@0x>$|rE2!w)X?7AonzRm)Yxsn7y{)1yLl&z-b&zhq|?b;g5-uW*)l_1&b{6r z#A^fKmkCP6Vw(Z}^sl`ACo`5AP`N<wtjy@%y|mE1^X8#@zY~e>{gxWK_sH6cN>yRL zQO$2@rJD(U;OB|iTJu~yyaiL~X#17W_7@8L#uQcXr@z_!qdaSArD%Mtl?RG7k~LIc zUn-WddVKm3=cSViql>uP3E<hDaeE+LReHtH^HNIpQ=p^z+4}9hB8-?rdY(c@e|)m# zkY?*+pk!hKV6p;XTVV+LGsutpBXu48oA2%wrFCS11g3s;t4^Mf0VXYKVCMQUUI?Ju zuQKcvVg4q?-|cBA98g4I^1if5tj1X&x#J)Jr<=Kc!q~?U<r^F;$M?d1>v%l2P5MN& zeyk|%f{`vl65FnBl{mHLC#z;+ETB>LSn=$k_A7JNen2CZo%-#Z{j%v3vXZeAH`hgt zJLvW!VGPVyZma-iU}#B@1inmU10oUkYZ&8qBpM{-UcHtO|I>#Lk*dch0{cZHoc#*R z8pvQj*^5MFAc%p~Xx82Etr$D${#dwov)ATN6?OekzJmT-s2pGoD*|oU?E?H401Gb! zg1%Xiu=O`fBmwk(TAubLLUNYzf-GArD<dss$g_g@zl#LKUN1?&C19dszHm$Ur4uCY zpXg+vJpWah?7ui7oOP&6(=hH+_Nex+c;r1-J^sn`-+Tcw=!cZ<=E+dTuVF59#7{Jr zIucFHf`a`t8#(AOq$Gj>CjeJ!{J;bB$ltD*n1$Q>e|H=HQ|9oCPT|%G=)YMdwt13E zSV-+WHQ~m5QRiBXbL?U_qCm@BcyMb_R!bt=IFl%hg-%^cB3K(+#am)5M+Wqzhfz1v z-G3KHCx*h=vH6d<k1)fS^A9FlX>wW6JP6+h0+@eQ4?41N(EMfUrcGIv86Mi4jgZ(T z@y8#qBU0nD_PNCpsgMh>(Tnlqij5x`27j}$diBH|#h~3XwyolstI;A0@OOhhomA)W z2PZ%-;3q(?gFncX`xm+T8x`vV-fpWOJWO5#f^zzX?|%u9)Qx^LiJdUrOz=wEk<Idm zkifPp)fiS+J>FKy*C;X0j8)76VIPMduqFXWpZunaRJJ6_ej}FDe~RgZEW6x4Dvfp6 z5&<yRA0N5`Sg%wP3{-{)3BrHYoj+Sk+!N(p@!=S{qHq2ceNV3F>;Id+tE7E&1ExBa zN6aU68V9Th<5L$=?ZXuhpc;&De!@kdh_c1#&>A@CFx?b?Yj8T^2ArPT)i`*V1vuSs z_|*v=^2D|b%9fR5MTt0Bpu8O`lAtO7+Xs8?^(LV=l1qDwz>?eS@R#l3?ak!2*$Y1d zXS#rk@9TSuVW&k!r?Hh>m2Z#F^v1JxcC&V9B`(X`-gpIip6+a#1+<>7uM@a??|uKe zdUScYT68*paqMg+*0}fa`~$byl=u17y6y1#;hz3Y3=9uqOyJFROb{8y-#cvnxpM@) z!{+}#{?C4!e~bTfa|L>P$=`=Gut@xm%_jdA{O9HX^xliV4^v<T^*`*y_;&~Yd>tRX zhv4sH99YEv%kV#T6#QHIpKooTU)lfrC<JyZ{HGWA|J}nsUl~BZ-SPL)O7gFFJ^n5F z&vkV4I|Y9q!GJA*@_(+H|6BN<3(e@I_P>wf8&|^rW#Rqb{rr;@=w<1@j}G#`jQBr` W)S4>TIOvvmz&}YKQ0DyTU;hs=iEWVp diff --git a/ipaylinks_statement/statement_files/2018/01/20180131.xlsx b/ipaylinks_statement/statement_files/2018/01/20180131.xlsx deleted file mode 100644 index b3a7af81b5491ef0df944b756151e8ef021bc34d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 13756 zcmaib1zc2H7cUG03?VUqbT=raD1r_Q4&B`$(jXupAYDo~C<sWGbV~_HhalZuN{Aqx z?+keF_1*7%-#h*oVb5NBt-b#Lwe~t^pRFi^1|~*<Kp-f1l5km+KQ2PxcVpY9iuSg4 z4%|;|?M=8`o>>=0$;q_x5WL<#C!s%distInp5#iu1qsGcC$^=ho-+Cchi;v0e{mWM zUL06j_LvQLqHJ?u$+Z3L%+OKnWjh=Eww%znqICQ(_w<J3l9{sZ;yL$eIzACmFp@b9 zKA;~5HTBTM{nQG5A*&y%!q7VK!tj+l3AJe7I5`_`Itjd~`OT!5M8qf2NiU5md!@<y z_xpU+LE*WInD`HuetyAl?7q~Bk9jqH`XnveqC0z}w=GQI;mquGe@~9z0o**OLLS1d za3Cs3jH&~r7CS1@94KCX{^I3`wMFusPx4yt`DS_adDNHJ`kBwxQ<6FcKAteV&ypys ztAnNXI4FPaFV2rqP?W)hkko&;frg5LvIqPq{#Os;03I~3H?el$=0biJMmNj1@Zi4Q z_6TM>9GQtE5S4R=OV-JmKNOLizGq1!5rnz2g@p-zjO#Q{wsyFtP&T!-Xtoo|E`%*z zv>}d-`?>(fFFGRNbR=xrNo@o+Ur=Mb`_1TP7P~RC#HtHU<d;DGwRa4!cZXDV-}T(N zK~R~n=Urm)&PvjNye!{epgA~Mjc;pHJGjNFRp#gLVc$G;LPkfEu<Y?0HsfRrW9GNy z`fPFv2o=3lXy3Z^g$gEVyWv2Q5yyED^{N7^jHy94xnro8q@Etv3s3a<sLGLoX2s8Q zakE6U^0$+8A8RzAB7LL5rq8$p%v>DwzkEXk^w4>1YvX8Q<7lAz($2&|?}}eBJ%Eo0 z#14<Kdvu8FOneBW2hk&#Rny(QOIgFz8jb6+&fQqpSD3Yfzjc?b&brx%Kj+udd8|$l zb5NB1^j<nRX-~TDrCf@s^9pnFT`{FE_fVnmQW^d&dpwOK)(Ibypkov~*1`yN<NEdo z_@Z2`R7c0=j?G!l<hooADey$!$aM_u(z^-MMbFDjBzS_NHwvpdMpXR`D~QS0+*gM0 zD;{G!`9^g&Z-_oQ&3o4)((_}=&J&NOI7FehtXS{i=k!QU?wo;u)`8D>nCFV4)rD`o z$z?)rVtBBkf50Wf;<Y-OKBLn=fq1QLzZt2E2q?OtkQ|sw<IrlraDG~+5=f`Ij#9?I zDRV%mw%gv+C4`&S*ka(W`_QdX;28U-vAVgl?kjl8kzJ_5^vWYIjjY9%I@@3kq~n?A zA$<Y>A=$wH%kcz%hV>IWJEYg;!ke)_^AI4mJ;gd3X4c_|!B}6&`%SnoUFOuiuhybv z(!z5|!%Mw95jnMAiWkG!>qH8t$HIsu?}di1s>5i<)|rGFR32j!5()LDQ?XUsKM6PU zwkF+U88gW)lcj&z!kkV1`R;>|w}u8ZK?`5+N;HK<iBshtp-UH@kZG9RAjO=KP>D49 zI7fVTi0z4Yf`**Vg1hs06ku#M@blkej2QUV#hTl}{E5AZv5KR;g^ig5a!Rjsro#2w z2tE2WG(CmgYV)_Fc*~L_5#)?u@!(%ZTBacNpYc48W9xm0ZA2sU(eVkGz(G(#C<6n8 zZNZH1&MJ4AWy+&9>uhyfCja&ZZne5v%aIQsV5Br>ZOJ+P=kD7RepAkev;y0h&KJ|O z7lm~S)3aW?KEEOi+|1Sbg<W=ZNb&IS`e$lSr!VM#<oPDPpK3fWUppu&cx&Ie*1sTj ziiw}(wf^&Gg6;Mu)wHYScHbAjg&%j^PCxF()b-ESybSb$oi6t^-|7D`<Gwhb*U-=+ zq_7?6@N%v1%hc%_x4ytfkDbp8ZA<rs1w2n@aD)O#xi`OcyY73XG<uzlZbw}1f8G&> zJviCVG2^D4ar=H0r?Bm{H#@L#*txP)Ju7g$m=zPzC~&f5b@oLfrNM4@ZS1(RSpQ;6 zW4qz$?D0ehD{aHevz;DR+xp((owaQ4m;045+!s!lF<yz>FVAPY0=xuVFEv;jUk2&I zJomXJXy=4nSLA+8htN)6E-NJWAMGZedU>I)H;HeY_6}`(dY&Bw%=9d}>pf`1zStz$ zZq-=xdrPNg6cpWidt-y)K9_?~vYy9T>2|y`;wam}REzY>dN=;Sl-m6xV~u{U*yf2k z_elD?b@j(CSV~4*YJIcz=Mr_UA>1YNVOHXr!JFmkF#NpH@}4x@w%H^dO67aLX0=kj zHZ=)4G;KE+JYO6yOnsXF^qRW<`Gn1LBf;7<9-$jy1%0YmAEf)JX`c_ANM<aSCL)xL zrAONDd1l9|oFYoAL&rSw)!Av$=04J6lxydn5n!_8SRN~;zHx59!BY95+%l^(Ebg^A ze<WX^o}B)hFDrU6@zOZd4SYer2yjL?aiii>aho{^nDF~1or>OSG$ajJ9R|<RqgGEs z{IOx$&WQRP;?vK%pI0-JWI7<N{8>xwtve-X2cutKm+YN$iK*oUG{U$%@XB0=*#z8r z;$%dMa1pmI+WGx(c^#a8*%0J^0I%Be9?{=w^KobjU49qjN4u%7F}{1_KEcXQHZ?AM zejSxe`YAW`uY@1=!&PS7RWjOE6L)Hq9w34pU~?Z$-FLfN#<p~<wzSICvAvt?NspPL z?_#|QP%bRD5eCoGK9!<29Q|4fr~c^ELI8PVYHC<dZZI(CZm{r`x83r-b^Q+xDY7<) z5>#9rVH}IxQFaHc$9lt@3>QyxO_x|3C{WkBM|{!ikLx?>N(4)M(QONqRM|nZt~2y) z<SIM2UQgQy!*CPGJ}84z@|IPZjk=YXNzc@x+dvweyeJ55I#=d^R4vus?-+d2HC1Xn zPB%Y!jK`QZ#5_xBO{>Y;QlWvq+u!F`a9~szl3mpWGxL`A=VemrGA+wV^59LBtroh9 zm2wd$ihpVpQr0!sM0vq-j`AzdsI#Q?#F1q4o!EEX`${wJtkiW$g>O-J1YP+-22ra4 zP*R67?(PNAaB94OUQ5E#@{ozqn>19fmTy^S#8oS?vu3&)55LcYZ0r=G>CV1E1l>gO zJ}z6<d628zN4ZA+D|b|3qEa&2ePdjvDZilE$n<7DxnZMunKu(tA;lIA^^2HqMkT#` zFV0{}_}td~^j2Ia4eKOXrZKNQ-G7a~+pCQXn(+2?mr;76jTso;tQGWv&0o+qt|dju z{=USdW2{4QuJo#Y39d3u3*{}P=?}3CPB{E*+^_WB$9<k942+{`XDL-CZ^zDUh_fMf ze4|(tLZ+a%<@T1g)J@!(Y@Q(SHqp=96VnwOY;Ct{sPl4O1x3F$%EupmHvMqQ7H|GN zPtDGtgcB|0Q`%+WsfhOtO=u=<QUUd~v5>CF-p45JCF8a@57XY#6Xj91-4$TGu*HRW z#77e-QyoRR&`F|kRw}8y?&h=j;CHK8`>TJr-NLK-o*=u8adssPGa1Y$S(1o$CU=XB zSaas!^t_H9D*Dku3&p6mO>t)|l8J1AkZ&EfmoL_5V3%h*0hg6RB4W=*4)dhUGauOR z9~7os*yAp&^L>A;>pH#nFv}JDergo`1c$Kda735yI)^|eRpNFB+r83cN)E}=Wf4m? zvue#x=Z;&b)#g*78_6<3agnd?6M&v^saIhOJS}}NBon>9@{GXqF&Zj9W}kZn_k1)~ zVQ7iTCMMK4*U2n2{N@1(s5wbdLHtbz^C3r;D0W*Dh1<Md0ZQ`sRSrj@DGePrhXQ|{ zfZiGf!&{RovRG+lP6N8dpoV%mN}V5Q;5$CASHim>l$f?A#y8%?zOwK(rOI7Z#?+Du z-FxTP_eLk2AG5jmt+WhrDAclCFVo`Tf^kJ0uL;+*CQ7zZzI5zXtG3pe{gdy+0vu9L zGPZlnODM;B$HWX=_$()tN+&wiV&~M?u)~)ii4z|%-%wjt9Y521Gd8la4SO`H*s|Ad zLb>uu<1)IB`!?Rs^%X91eSDH29l2+n*myS|KA{*)CM~geTjEVj&3MbY*op$Tv$`JF zj<@syMg*p6(mfjgC)h5*1`r4vi7I;?s=LbVpV(tOcyW6ik8rg7rxm-Htg|!P#T@I? z@QvxtZoTj(b(45kCW^+EHmiX1;~x7>ZL>j?1M#D(HDgn2v;^6A<Eca?f{`?<vfN)( zv!Z@nOd7r?yJbgNFr2qFYb<WDvkJdS(5g1fYA9G$Fy7$mQApt)M;JM7Rga)deie2U z+f<P?Ul2^iJem7$T`s;NYLL@$6&4y~(!Ju(ZA*+M7GR{jd3SpwQXG$ouB;{pH4nmO z9`ovF`Wxwt!kNNg!9K1}WQJ3A9@Yh{y24JP^q^UYY>6hMTjcG%dlJTl)15WmO2uCx zR%mks>E0zn#CN2mEA4l19v1M@N+<J%DOk&^d`rTpe4$M>>>boh%{RO;o)-DR_@F}E zCcG-CuFTECvQ23B*&r$j;sz>7zlfOQODxrNSA&~_MS5PEOgT5@^XEXHX=B>DNK!Dr z_@5}T9S2IW<?m2ohREuC4zdpoKC$qz6B;NJQiB#+HGme#J~<y?wDG|;-b5Pd8doXi z=W16Gp10)N?f7#S8qQ>obHzb1w)$LqxGKaex4aorzujXot3?Nkb0l|t=$lUHa;es1 z{p3{D>ALk)l;b>`7&{75X>ay0Eek~dsBq}Mc(YZH=d*OeLA36P&%Q=9pJ<iKZtzok zkraySacz=`=J<cW-BiLRx}a4|=T^2B{$WzFzgk;3BhMOurz$2H1a<Rpmgwy``9XNg zX23;1jCAvU0c9G*A52zRG@d-5My#-UARFN5>TQ*a^GsWj4uQs|#wsDntoY6~XK-9H zTqzlm<D4V?U`t<w-K?%W@usP7zX|1{M9PIj=__(`8+*wN41_vrV9f0=b8HW^<=xAl zwaR5<MT?evk?6K2WOvf`m$dMpdt6Ewg^jvu>UUpoIQX5n?ENF%A)g;)8tR*0s`g<P zsP|u82BPr0y@|x&QkQC|p3VC4e4fPiP}ZJsCU1R#x`+6leO7ytq=u8L7{=l{N`qF9 zt(xtm$ojDlQ}V*R@LDe{<p*5+y)_eIk)p37-hsA$SmLj*nQJ(Lh|dPRRo0YR88kHv z-TUM3&xhfBgx_wi3PF|lo6vMBS_<VtM{jDETRUa#g;yO&`Q&3ZK~$SOnmxL9zDhlM zr03TZ)Mr1ZvY!guV?~?%PQrI@ZJzdCd9N={so9;0VCU>7ianzm6}%17&j{?HPY2~j zIEz$E8#cn`(iy@>eET;^T+2%D_H0)>q(`G*uAY2Q+6}ZeiSQ4<A?2oOJ81Oqqqa6! z{vcgKx@SaUqjHF|qy;4fyQ2z|tx9Lhu-GQNohC!`HZ#8vY|e(Cr#FVI=&qETKu#eK zgGm)SICDTm#S~pv4n^>+#U@LC?3Ur3y#X&z=gXezd%_+i3rojJakE$ll`Ks<^LnL{ z)uaCQ=uAR`q-h~{;3BKbSXD{b>%>JvL;5LrGdVcCWZf!G(c!mk(2to2mTxVtk8>P# z;`O7Qo5x9Ln59P=(RUkt`SEz87&J==`Xn89Ol6QP<q)|lIptMGM`;%BK&Z~T>y#~9 zjO}V)w=()Guk)Tve9B;30-f=52t$C==vZN0fs25<AKCdU5k@Tc+8<imd3?edAv*BI zpN~eS47z2<Ci<oBPLz~K;PlPMsY)W!ONh<u<-Hg{L#23T#aj=sD7+ADwc9att1tF2 zDQ66x%lht}SrLXj)!?>Rc2#{GrE1KnnwxpCQDBqFF54<=Dq;{L9yGHz1NWM4#`{rR zTu#3i>`Z66?RX;p89&>35S3WQQRdUq#!(%va*_NPQ3S?rpIGZ)`6#)sB$ho#U|c>p z{@bFu?0{zAvg3+lvYb{$UXT7{!Y^xt1to{7z2Fm%<e0hr%Fs>H7oN>2%#LWIbYb+h zA4xJg>KJB6l?F^+&%77!F@pGXMC4R%J`a#0*f<1{kCP*+K9Ueen^KMPBt+j@+RnVM zKx$^R*IC>%vAbAFHuW;S@hGuD(c2u)`h4?tj+uFI3`!*ZzFLM&r$+Uz$Ur*LV6U#1 zH{<gL4{aH>M{Moska~6{8geTByLvOh6biAHGgE|OHL0YYxpogIP(+s=5LM-IaNMzu z6wSj0dWg!UKK|C*Tb#a_e!PSE{-E-)P8ZnlpulNWF}jqhupi?f>eZ9`deabl*L22Z zan}Va_!-^K_wuE)h|ei7D+z&$E*`fhUzIc~7aUGRSH;4fQ0Pr#Q<%w?PQG7MRr>1w z{Z1kE(K=hV6h>Xgp@?O*hn7yL4^@v2`o*aM51ves2K~2f+wZp&_PvFfANhW(qZV+P z8fU29tN+C)aUPbjrS*-eum5{rUvu+9+vU}rXYx~DHvv2p6tL+3y7Rp8`_9wxrM1b` zEoWBD@8>%Y#bSjv?lJi*>flK}P9len6}*@VY%Pk$t$g@MeyH?@PvrdIxYuUC{PeQ3 zAOGTwq%r?jy0_mbqo}J|S>qhn&*;u}*6lJJKDqmI7!}-%^$lm@)z>-Ggkr&xZth&n z<>c2%YCd{nrk|WsEooy4x<-3eUYN#-Yps5)rlhRTHIGP(lu3wt`PfBuln=|~$6Q+? z-?Wx>SPKW=vVS`TMlQ}vB7W7I%EJwOu4{X(D(Z>6T^nq&$$ih&8Ee=~^Q2EadyXfY zxN4fW7Qj5W-@_;4f2ouxt~Ow!QrV0XmN!tlu`xmW;@N+^{ia<rhMChI6Kb*WS;(GW zVMo!G8DBYp(j3GpFyr+6#&E||MTqf4ZlxtwTu|rZc59w0(9`#en+EUh9DEJD+u9-6 zr_j1YD{EtZkBH?#l$W&3Ceh|dN{Nv<>{!^O*t7rUhwU#P)5bgRPV%i8q>AB?AtdA* zf2k*(I)?ClicigFQ>8-vZb0$QD|x<{x%`-6LJ&5zdj(>+K-hdR@HAu+?SFxYe+{Cu zt-Y0zt*sUE$w63nDe@82Yv=c$Ym+BY{po^-vOWxlrIpkjWR+4(MfF$IgBgpPx<7wL zQ(NS<Q+~zAm+U#?Ja;~F*7m|WBFg$FG&lj}wLa$4bM?<lt}kC={yIq)^#3^JU-Fdv zkSR?rkNW}ZOuEWloJS}17NU+ED`eG4CxP9HA@RB$#r_{x<hAfwACq4$LFAtDbNPBY zeH)U3ma4G7%^E!b@7tCKbcRZ6PKQupg{?z;#zsnBmbs+f5kO=+mbvNXhk<$R&hQ1C z-n0DbPV-;t7&}}$-PymPd8;srKx36+Jg~t2mUx$ASB}9xKJp<;&ZI=@cfbdR|MNj6 z#kH5NpJo2(tLx{QQCGYd***{MbbjX)^ZU7G*$%4G`n{1!rm`DT7w^5n1yBf{kXF^w z+S|;Dq*bW~h8;3LpV|VECw8TjEr#<iFI^lk6RX(Xu_hHP-`VVF<-kY3H!n8WFuM7$ z?@doU&$2wNMOCy4g=5(dL(Jj)549tXUEWoSmOg4zeJIcBD26YRehMFrA7-=!eA73@ z-EFz~Wftlrl;%#~XDEXf>?2mwtNOL^q@ZY>aSe-G47MwbJ34k(KwPjyBGxvjc<|J1 zMbYczuItYBvmFeiZ+`Y^z8(f<&htMXWRm^EAO~|36GsQ&SrqUe?-iAjbsT0!<NW8= zG)j(OH&LmQdSWw&!J#X1Mk(*!ZQQv%5Z(Re8-s<AuyAZNAzoc0^_~m^3+>qCTb7cq znkf1g--}Z`ADo^aTr4cjtZA&xIFqiKRj16&Hk=+EpXdL&Jl@{EeBpJGGj_SV8&P+f zLJOOog}r~YlR~SX?B(Kqwm+v|@8WX0a4__x#o4)W*3<LE%d@ub((%{P-qQIgDSqSZ z+-&{niA;*;%K-yjYXkS%<D=uV{T^pp;Tg}1=%1Sx2RRyRm$S)@F6X<PM~$?$mo5Uw zhZAq>g=c5Z&sG9<e~cUt{iLz=JS(0uu$hC+!p_fJE~mEM&Urp*yf`0AJL@=~sGCZ$ z@jPAG5#GKyS~yrb#g9-Zr%K5_-jlK2_I!DCl46zugUNjo7Cv?SHCB9i-qGP4LHqt< z#H(6pFJQ~_{`-`M^R0!QA48Yt=a<Lt4mUfd0y?&ZVefI5w&@%3=66?jR`+{O>xBD$ zq$tDWPPg8AJ(N4xT<GaHQ)oQ+xz~7cak97)GS_&vE*vN<H1LR(h4o~uHH)alVUb(j z`aRK{5HE~%R-n{F{%pSW#{;FLabeb?B!P#lMNis{mCQtp)i~+O3M53{yztnm7@NCS ze_6F~J~sDV!AnB@q~E(!S;4zg+W^E6a!x8@T-k_;cyk)Y*l_C*e?tiy5k*}CLO3l` z5GbA0!@grH8ApVBht}`6R2R~YR?kN1AG`n|4)&qY@1tnxI`~20muP`D=dQ7!z}zKl zf*Ds4$Bi*oJ!*1eaS0K@*^@8Tg>wbA4UB%W&q0W67px%14b*|c00iIk{qXV8VhMHv zF&2-?a9v=mMnGFjT+0u_$lJE(N6$7o_6wbjBjplNqIL{K8LmdAkD~cWU0P@mp-eR) z8Ote|se=zFKgr|_6_bZah`7$4YytX;0DY9?m*7A|jX$Dx-}~F>V}{#1R9A8+QRUMl zOoN4(h-y!dL6UX`8E3F@zfR+6)qWjPAEOsz3}eQvL+0x~G|(>ECQ1qGjj;@3kv(tx zYx50K9AA}6#xl}T&YqkD3X1`S8R|#g=C6Kt2tYtr!WgUe0e{lDKEwP&s&j63AZiQU z_IzP#^va)w`u%9>q<fK))ii+jBsRUb1D_$?c_&(~&iC5-VujkzcKhD=EzizIoJr>n zF21MaC*t?2U;YdlXmsz+I#me8_O|~{E6l^<Lnlw)UQgYb#X%=-LeSeV=(0zK(p&VL z;G6uz1};V4J3_zqy?M>>?GvEhyvzbi(su1}B{Vq%Po=$ev%!Y4SQ`$-cWG2Wn_@Cp zAroUYa?8?ora5m>TEFq5tne|TAp5QE2`))%MyLc1aH4jbNTamJmcS0Bmj+_cc*A;p zY&2sD;=P(S_kvO48}y-yTq>f5D9T(794ObCGDtCEdtwR3y_=^w!z8%z0xd?cLP*BZ z_33!r@`=1l1?fxB*!$$;P(odsn?6EEmxzsq@i12H(xf4}&4xeX?DHNVWLv1$Z<>|h z6u=GfoSabF`|x~(Btxl*=-wt%gZy{`RRT-PAI}p)p8_(X6cNeP-WJK!H#16bl0=aL z-U6gfu8?U_BU$X&-adSvr}1D8$OJh<$&DahesDWIUZ*@ExU!Eh#BCh?fS#AsDVnac z59$*j8H(i_Jt2meXJqlg7Ih*gj1Ov!rvnKQVj7PTqP!@?32IZ>1gS)kZCS<>l!bIR zX)(2f;awOch<Prg1SJW=kQe&Y7a}W86*;Sn$bGI-s*}{tRYDOo;E_Zys1pKCpaZoK z#(dur^VTJRr;0|3*QQ&u1U9|I%{F*0qAmj+W@9;R^V~!`jUr3#^pAWK1J-g@G88f5 zD`Z98#mk^mgiCTtcbh&F_rWBWZCv!O$VB8SsT_phOki>`@lLwkA<UHHeT!5>3yrZ* z!ivOUfT$7-rbm|nO`Lr3o^7ZWN<oSlxtj`t_%k2v;V2n;JVc_So{&f^5E&7ec_<x9 zM~WcGrOOm!Hn{^wdFrc~axEk@#l~^^gb*<=#gHM!EUK*vHTH$*O37x6F^g~oA}tF6 zEc1ngb{U?KU;^TzVd-TC1zoTbmZ*VrDE(~?EIv5+OK^PeyI3@5J}gzpV0IEGQsV4y ziNbXI=WM4<X-wj$<}CgNxwsFdjbsU8dxN{1GG##|$QEm4i;r9oT3LE@s=87QS)7NV zDl}t;p9rqQ$$^#=jhsb!I-ea!j0igY?-s<o>Y{f+E>o_WDwn(otw3C><`j;ox+;b| zGcOB7+EmPBUKNSp@0P%(yjD~#B`K>J4i3_sGW;ZIqk_}F2Lrd2{(pxzUuyG@B#HA; zkpeiisHsFQ5GR%D%UFgK4B~}@<(c`^RROd)0^0JZK!DL(jqymB=-kM->^PAAqVuBT z`VHNL%5xtT0PZWlho#$VCUw&T!wghK2GMQd)G&2|;XZ<DV0Z(EZz`M_9tq<J_?jC{ zXP*BK(kpFPa0eqMfdyh|VZ_UcSyrJ+)TAi`7HOzNC^8L!d7L8c+Fe<ni*N+)3%nu| z5*6VR5=D7xshQ%IwG&U~ZDH|5vm)}LfZXepH?a^4DX9rroUWyzSXmiqe^p#~s&C|* zSa1SW^jdBVW}bzJwlc#o8+$-o4izW`8n5pr$>Lv;nTce0POCBSWu`9#MB=;0Po{yS zXv#GorGgamGj-j&>3_2Oe6I{J7VVVoZpyg|txZS5qgcRkk;y!u6aZPoyvm~YW++^7 zBewJ?_VK(5Xvhk`3lUj#i6ko+#>}FU5=}=0MqgJW*f>~JYtqH+rRx2};s+}d>EACI zk9};Y0zz}8OO!YG?DJI|9T=UgGn`<fXdWL`1+>axScGPZ$70|oAfcQ3hU#XFJw#U8 zPz29-aAKi3%`ce#CmZiuOZpNvKfqT*p9LMLc^r5SDOw*~{CfH5?PnteJfBBcvfJAx z44t#R#N#n!ovk8~Br(ev@2DVyZrYIVk8b<R68b#G3Qfc(mY5rSrMUD+FR?9c8jQ!x z({K+i2gze$OKd1-w`1c?fMtnAHdM1CIj~j%DSLY#9nXa4T>AN5n5cxmw(YhyRkz%{ zBH#d`VgJa67EU`hfLMxrZV?(^WfFjdmnSS0iN#RD>i1oP>Z>|B{A&??VB7oYk5MbW zcG+Vrxmam_*dQP+c=N(V__p+19|OIS%A5s(z(#2Ym%`42(FSpF{V8nsr*T8*KoJ0< ziK#69;y}Jr0@7Tnu@3S#WZVe-Zh}0NruwQ6=t`pxjJXeEDRu`}%OGV0Nf5iU9m{PI zv9jEJ5Fif#LaqsLK;=s`<6Ue?ipZOBkjmihwv1^o&2L|5DUrLx0tuKc0SF`s<dptu z0YyYFZvGBuniZCxYyfYtEJZtkG?8(|8)W9_W>SO$EvavjyfIY%JN{W#Sa^^`yB4_m z8q72_n{^+cr0-SA@YBD_F*1MWnDN-erfl$)(}0X}{q<E+%Ke>`T-lL9t<H?s87%Fq zEw*B$ZUZX+?JmHU-oLU~>RTZ15dc}>TNYp^;ofhnlvKk*R2~4yh^OJeUk+lSBsH-~ zvgD%@)K!to)Tw`m2ADh07};R;(2fJZ(-7mCln@YU934RRK+A!~!>0frSL9wrS{@K- zs-R_Lr2XA=wY+Gn{v|TgZx0u^V@?SW=Vn~&7cgol7AV@{aFFt9Rr3A2(a7WPOm0tg z6PdMm{6vX>)USLG2t`#RzS|tA_E%W`)r2urEI@aggV2&VZfQ|9+(!kgH&sT6{(3P1 z<XQf;zJTQcP6IScho-43z1(ekw;aR&^A)L8kO%<XavgtHfE5z{u4=1mXkzfknG8y# zU{BD{$`mx{hmrZ&9ydwa5aZOF<gfJo-xE6UpjtPno7axRhrA*LNHhRp@&F)EyDA<p z-?(1I{%Ru>h!ddW<iN5diTjO>pHq}9l7hhM@tc$?ze#!30?L768jCT*k!u)7M^hfy z^eb01)?X_Sn0M0l#?@+UXE~_~q)~$3DP6&MK9^D=aBET328m=dg)zY(BiN*zdl4P! zE=I7(g<3swb&Vj1{Q?Uk6^Luz<HQ60g7AkEOts}rBWdHu-$|D#0YNUNfG?(NSvtXl z0B63dVZedhn+L#eQTU}+JokBAsa{fd;i(oE#0=vZ=R1PId|W^Xh<13_9tYa*m0yGW zniJRXYmh_ui}<Qq7=VF*IaQ@&(KmFbB6B+6I(=8XNF3iYG5&0bvcYxwG&P8U(`uxy zxoU=XKQmMX(k+T)T`d>tZorYbBnzZFTj7QBJ&!<cL+K`6^xhXuz0J#31Z#nuGtn(Z zDmG||P_jrgxRZ-FeqAmZ=q;4Yp)jb_uf;V<G}Pirat&VmgLt<ai&U4#_3vdCmLE@b zy{&3qFH@KHFL0EERVTaKCPr(0k94;e0&-c|ApP+Vr`?6E<({d#bez->%Q(Ccc+Cx5 zfG<{Ah|cgEK5$@x21RRe{#C==xT;}ryOA}FaU~l3_URK|wrU?ZR<B`UEF|Hafb2RY zP2l^$k?8-`0`ddUKltzcM}GI$LMOZ$0ogy(xq;AfdVlsd#tIh?n-6(G9F)FcLvBKq zpf#6{C*ed1C4nv)$VmGcY>C*uWF!clbL`&sGd6z;&tV&0HfN+&?b_^wzsozn|E&1@ z{;2q-0X2QkZjt)mp#<iBU917Xqjmvm|4YdS)QQtKfXwd)jSs5?R`08l5RCDkQH)%f zuA^97sYZvYTMt;6%1Z%Ie&?jr|IA70f9E71h9m4rU1FQ8kq!VtZZe+%03Pl8R2GW8 z7_d^nCu?2ACUl`d#Pl|@bcG9Ss%zD_#ML$BgH4})iG^rsVMWR?@Nn`bj>P$BUB#px zc|FhWJGvOey!w?u`)R0ih)xa8w6x*96OK|WdXE%dI9E_pQLD96EMyZ{E9fN?xr*5m zWf*>P`W<UfMCrK==IUSuwG~aHJ2CT6x-F22Iz`e++P)Z!lqDpVJYBoC4ZTd1!9~gh zVDTov;*Wf#0Pm-P`KyD<2Uv!&=<^vNe2>6R%oxZ|6KJj?-B8PQ-Ea!j4Mnn>2{Z>G zS~d7Up?2@!;(`Bgu!!Wo$YbS4hIAunBG~~<ifJMr0=%zy?*Z^$gXKUMKSZMjza9`6 zwF!&VcYzv{fJI#Ie0S^3)_9LnLxaqeMBs!tZ8(8(FyvEe43p4e38jJQG`G#l?4#Rn z0Rn7gy(bvtz5`tjfRIH~Gq6QcGnh*Xjey~<5@>Y7;stlcQ175E1#3n)=q8Liz>%we zHNXLnx;VO1Cr-F$C}dN*H+#zg<(T)XW-#MpOQdB4HS)!KwGk#TK`f~mZ#LS~9>q0T zZ*CMqCU`->sNmPk7-dfphMGXdfL`_(@l}}|D4%}2p@!yWojvV1Ah5R|LnLa6AXp9v zM8ac<Kv{N0R*e;IN5N&s^b93Pe5j&4wXxE~tyVlsIS+mGuzJPoSXlk{hNQt)J$Qi$ zf$D&@7CAFth3{Zw6^QXXoRi3{D4;EW8dD#D^cjCLL79s9q8flGeym*M(T&IrdLU~| z=F>roqv=!-^J>@J(d$1qQvZPlEa+iQnevc{HZvo2Kn5Cg#XDY3cBHm)KEqYR1OC7( zk3G6&x&q_j^qDX(-u91tHwLbu0qOy?1mN?^sPFVVoIs^%3RIdMaY2uUTAuK7;`?X; z;p|#WICziTcQY1_<iNeH7}U<aNaXULf@@N)f&u>!Xm~*)kr~DZ;g=^5Xe)jQ_5`M~ z@kv}#fgG~W5tLd3CDXYCY8fV9kymt&5a6o}yUEFwLBmL3DL@#|R`~E^4p0J`W*CU1 z5Db<<0j}V7ffsNgAUY!8#*e_*SJMnx2Adi@C*Sv=hwx8#x0FB_?10&fW6q;eY@z)m z>jD#gjBD}+Sb@Bc1IjrCud70Pk?$QH#1hMBhXdb71FP5Ez(+!|5rj_wVfe}6g9-=h z0}%iyfYf(;C-_Zh=voPx5DW{N0Nw%|;zPcF?2kn+Wa90y>WjQ{5h1vWW@KGv)^u%A z;T8la{voBBaRE&qz^20z+$_F(QUNmFKwmX1TnIx6aNG9^n24bo1`_i{?R@7j#g;nQ zE&UaGzy|XD7q^K-*Y(iAfDu<3G=O}8)X?vFJp=6s4u~&BSQT(%_7GX{WWdyU=`#<j zQ9xJq4;`@V0Y#th)%uO3Z?KhzA{@n$?|jWyv!MI2p&IDUdbt1*P>c9_0n;eBQlfUP z1eAY85|Xh=piHC?GjT4Bk2APv;K1^2*WZxNt|(#ZR`Y35)*@K06_I{L_=-a^?=JM4 zpwFr?AxClTn|N7%%ibU9LIV<pdeFP;4hlrdC-XzhN|_N&pO^yo2+87=a(!br7=Q8* znakfy+x=kG)}@-UyvcP!<neJ1{lw0E*sPi*yJC|mcn`J3-a`O!g3`TD=+7Zp0~<}- z0Kbb7%dKD6_U0SO6{!nZK+yV>N_{m~aO2HVV?!#LMk*OkyjEf-@RyQD!Nb`~kxrzE zL>^!mD?Gzf*U(5hL^)lO)@MwL;5(z8P=+Ep`<R5G3(MD}TcRs!W4p0=rXGUtzcH3P z!lI}|e`3_VG1Pk8`lJR1-6jHhE_yPooIuX{e_K?9pZ@M-9O!Nb$D-KhZ3<!+Ze$W? z!|U0P(o6$vhu$GZ4j=G)_`_c~^<?EQQX1;UlfN<Yh+$D|Y4K)P9Q(2jN*IPh5hsv> z0X9`QF!PTYSa(@N6km>1#>M2dbB5K1oCm=`5wWQQpN5-b53C5qP9W~ezQ9COC;%{O zV4(85zrpwf3d?I3`dS;(0!Z}4rYfa0B*qU0L<BK-fUDTyfVTv~L`gDrX?>jEi8z!& zNHp|-7ZUkKT%L=KB_HMJEvA6(PC7q~AG|O~7ooj-YY0;$6+c~;RtiAyJEM2eZ|82D zmc(1`ft+W8ye641*hMm63Ie=Y+~st^dr?O@C{Zxz<y|bbNP7>a3k#GlT@0$aFN%dD zEk|gP0yU)=0Ol3jf;=W`q^Xj$Jh#RI9%tgG>e9lIJb6l8E1&v6%Re~3s9%C6!ScPq zYa(DAK#9ku58z_N1^bPjeZu1$L=BALGL{X%B?aReLBPdIUw-xcZIrtJ@5<WSPT?#7 z!t1WfDbSS@$+IDpYf_y|W2uB;D%AdH72bkg5~mK(Xc%{&;R8kmd0_(_*-?nO;>bT5 zPW*CB&z~=*H~}5Lnn&dGnp|KiW=6CMqX#0Vj`Y(8Aclry`l74rF<fV;)?+GpJV(z6 zaP4}FJCTZMF`C$}<fe+ZBu$XVJ0#5?LQn5{Uq{o#27+3<+P049v_b~xBJN@N+^E}T z4kUJRB|-aJ0``|gkzi~Ng1=|z@BV}KM%|Ns-V7d02kat%VKBKXyn{R_ka)*w%uM=4 zS|%Hu00IhE3i@n}y8F0Ad|>99+4$Zfw1@;)G%)EQ2^2lnYqwVa!cm+G89mMtE>$>f zg`t~U^~3qDu?zA*x~cTHn~eSfqWS<oQ@i@`6j0)9aAR-b>nKf#@wHh^CAzeDQ7~_N z4{#c`a#6&KzY<AKWijK3rNMRpfHq*dj)$~^QFlLgl!r8s6A%aNN<|T!Fy`+4sPP<B zWO!itPH{_CZbn?R!nTM`iBk(7iG{>I5|<%H+JlOmzXkLI9f0=cUuYk=peYx2Q2sUb zssqK_Do*F1|0V!F9&(W7--!6_sj8FE?bg^a+W%_M^G9&niu;8Jr56C3hyXSfhC2e- zZKDC$odIYAoVr3A85~z=7uEJ{cdBk2czP|S93c6mu3`H>1&V8rb0jOzhW=LIp&Z3t z*MJ|}r~nOEIZ5?*8v=rXB@J8Uq`^kk+%^u;O%g4TEA@#n+{65VaZ8Y&AQK)3;97`_ zQ8yJ|stEnvTPhG1Dph)s8qsLQS9xI^{?J;{K)zSt9>olI37R^Z$NCT5KQ?&O*T1ZP zdA>WAcv!u^dU4*-k8dVC`v^Ac;rhaJXXfp;%Y~!!p^Mw)N>0wkDt`6-?N8@Fd$trJ z4Dx=JpGIs8pItW6ZhM}0Y=3g;-szY*?>G2We?f`dKRlomBs-x*K@r7A1zuoB1rekC zbI|6`10=|UHvjkaAIEO~E&k^j3*;%2e=bpABlnLpC;t}w^NaxU2*y8`KCsLA|2UBG z?*aaND<653;Gb&@*l7RT@ZSdu{w@9In-$16_y4)FfkO-bulM->J;I;c`p7ph{<-LY z`5;I5`+bami~hOSjokPD=UM@50Yv}Y+5WfipPRwR?eKptoSRp||7COh-{bsA3gp)D fKNl<M-$wk$MzW#|ItH>Q7Vu9P0LttR@~{5`nfn+` From 23e0470ce4d9dc74cc34218ec30ea9b3eda287fb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 5 Feb 2018 12:01:33 +0800 Subject: [PATCH 031/382] =?UTF-8?q?alipay=20=E4=BA=BA=E6=B0=91=E5=B8=81?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81=E5=9C=A8=E5=BD=95=E5=85=A5=E4=BB=98?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95=E6=97=B6=E7=94=B1CNY=E6=94=B9?= =?UTF-8?q?=E6=88=90RMB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 0724ef10..4b7aebe4 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -368,6 +368,7 @@ class AlipayTradeService extends CI_Controller //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { + $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->ALI_currencyCode))); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; @@ -385,7 +386,7 @@ class AlipayTradeService extends CI_Controller $advisor_info->COLI_ID, $item->ALI_orderAmount, $item->ALI_completeTime, - mb_strtoupper($item->ALI_currencyCode), + $currencyCode, $item->ALI_completeTime, $item->ALI_completeTime, $item->ALI_acquiringTime, @@ -404,7 +405,7 @@ class AlipayTradeService extends CI_Controller $GAI_COLI_SN, $item->ALI_orderAmount, $item->ALI_acquiringTime, - mb_strtoupper($item->ALI_currencyCode), + $currencyCode, $item->ALI_completeTime, $item->ALI_completeTime, $item->ALI_acquiringTime, @@ -476,7 +477,7 @@ class AlipayTradeService extends CI_Controller } $response = $this->Query($this->AlipayTradeQueryContentBuilder); if ( strcmp(trim($response->code), "10000")) { - log_message('error',"Alipay payment failed! error code:".$response->code."; result Msg: ".$response->msg.'; orderId:'.$response->out_trade_no.'; dealId:'.$response->trade_no."; "); + log_message('error',"Alipay query failed! error code:".$response->code."; result Msg: ".$response->msg.'; orderId:'.$response->out_trade_no.'; dealId:'.$response->trade_no."; "); } $html = '<table>'; foreach ($response as $key => $value) { From b39652478fde98123071256a61318aed6e43470d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 5 Feb 2018 14:39:37 +0800 Subject: [PATCH 032/382] =?UTF-8?q?ipaylinks=20=E8=87=AA=E5=8A=A8=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E4=BB=98=E6=AC=BE=E8=AE=B0=E5=BD=95=E6=B5=8B=E8=AF=95?= =?UTF-8?q?:=20=E8=AE=B0=E5=BD=95=E6=97=A5=E5=BF=97,=20=E4=B8=8D=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E7=BA=AA=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ipaylinks_statement/download_files.php | 2 +- .../pay/controllers/iPayLinksService.php | 17 +++++++++++------ .../third_party/pay/models/IPayLinks_model.php | 8 ++++---- 3 files changed, 16 insertions(+), 11 deletions(-) diff --git a/ipaylinks_statement/download_files.php b/ipaylinks_statement/download_files.php index cb34c551..f93850de 100644 --- a/ipaylinks_statement/download_files.php +++ b/ipaylinks_statement/download_files.php @@ -12,7 +12,7 @@ $file_list = array_values(array_diff($sftp->nlist($target_folder), array(".",".. // target local $target_local = "statement_files" . $target_folder; if ( ! is_dir($target_local)) { - mkdir($target_local, 0777); + mkdir($target_local, 0777, true); } // local files $local_files = array_values(array_diff(scandir($target_local), array('.', '..'))); diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 866eb72e..ab91c0d4 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1112,12 +1112,13 @@ class IPayLinksService extends CI_Controller $warrant["PW_GAI_SSJE_pre"] = $old_info[0]->GAI_SSJE; $warrant["PW_orderType"] = $orderid_info->ordertype; $this->Note_model->new_warrant($warrant); + // 2018.02.05 暂不更新付款记录, 测试观察一段 if (strcasecmp($orderid_info->ordertype, "B") === 0) { - $this->IPayLinks_model - ->update_money_b($entry_sum_RMB, trim($settle['pn_invoice'])); + // $this->IPayLinks_model + // ->update_money_b($entry_sum_RMB, trim($settle['pn_invoice'])); } else if (strcasecmp($orderid_info->ordertype, "T") === 0){ - $this->IPayLinks_model - ->update_money_t($entry_sum_RMB, trim($settle['pn_invoice'])); + // $this->IPayLinks_model + // ->update_money_t($entry_sum_RMB, trim($settle['pn_invoice'])); } $warrant = NULL; $update_cnt++; @@ -1125,7 +1126,10 @@ class IPayLinksService extends CI_Controller $settlement_record = null; // reset $settle_cnt++; } - echo "Found $settle_cnt Excels; Updated $update_cnt records;"; + $result = "auto_update_statement result: " . date('Y-m-d H:i:s') . " ------ \r\n"; + $result .= "Found $settle_cnt Excels; Updated $update_cnt records;"; + log_message('error', $result); + echo $result; return; } @@ -1152,6 +1156,7 @@ class IPayLinksService extends CI_Controller /**取得一共有多少行*/ $allRow = $currentSheet->getHighestRow(); + $col_titles = $this->col_title(); /**从第二行开始输出,因为excel表中第一行为列名*/ for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ $row_tmp = array(); @@ -1159,7 +1164,7 @@ class IPayLinksService extends CI_Controller for($currentColumn= 'A';$currentColumn<= $allColumn; $currentColumn++){ /**ord()将字符转为十进制数*/ $val = $currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue(); - $col_mean = $this->col_title()[$currentColumn]; + $col_mean = $col_titles[$currentColumn]; if($col_mean == 'data_type' && strcasecmp('清算', $val) !== 0) { break; diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 8aa64abc..a6b8dfed 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -311,7 +311,7 @@ class IPayLinks_model extends CI_Model { public function get_money_t($pn_invoice) { $sql = "SELECT GroupAccountInfo.* from GroupAccountInfo - where GAI_AccreditNo=? + where GAI_Type='15018' and GAI_AccreditNo=? "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -321,7 +321,7 @@ class IPayLinks_model extends CI_Model { public function get_money_b($pn_invoice) { $sql = "SELECT BIZ_GroupAccountInfo.* from BIZ_GroupAccountInfo - where GAI_AccreditNo=? + where GAI_Type='15018' and GAI_AccreditNo=? "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -330,13 +330,13 @@ class IPayLinks_model extends CI_Model { // 根据对账单更新实收金额(传统订单) public function update_money_t($entry_sum_RMB, $pn_invoice) { - $sql = "UPDATE GroupAccountInfo SET GAI_SSJE=? WHERE GAI_AccreditNo=?"; + $sql = "UPDATE GroupAccountInfo SET GAI_SSJE=? WHERE GAI_Type='15018' and GAI_AccreditNo=?"; $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice)); return $query; } // 根据对账单更新实收金额(商务订单) public function update_money_b($entry_sum_RMB, $pn_invoice) { - $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_SSJE=? WHERE GAI_AccreditNo=?"; + $sql = "UPDATE BIZ_GroupAccountInfo SET GAI_SSJE=? WHERE GAI_Type='15018' and GAI_AccreditNo=?"; $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice)); return $query; } From 36003c5d0005fd0427ae968f4818263d87dd990e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 6 Feb 2018 13:36:05 +0800 Subject: [PATCH 033/382] =?UTF-8?q?ipaylinks=20=E5=AF=B9=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E5=AE=9E=E6=94=B6=E9=87=91=E9=A2=9D,USD=E8=BD=ACRMB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- webht/third_party/pay/models/IPayLinks_model.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index ab91c0d4..1159a2ab 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1100,7 +1100,7 @@ class IPayLinksService extends CI_Controller } $entry_sum_RMB = $entry_sum = bcadd(floatval($settle['entry_security']), floatval($settle['entry_basic'])); if (strcasecmp(trim($settle['entry_currency']), "CNY")) { - $entry_sum_RMB = $this->cal_ssje($entry_sum, trim($settle['entry_currency'])); + $entry_sum_RMB = $this->IPayLinks_model->get_ssje($entry_sum, trim($settle['entry_currency']), 0); } $warrant["PW_GAI_AccreditNo"] = trim($settle['pn_invoice']); $warrant["PW_GAI_Type"] = 15018; diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index a6b8dfed..214407b0 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -284,10 +284,10 @@ class IPayLinks_model extends CI_Model { * @param decimal(18,3) $amount * @param varchar(6) $currency */ - public function get_ssje($amount, $currency='USD') + public function get_ssje($amount, $currency='USD', $code='15018') { $sql = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje"; - $query = $this->HT->query($sql,array('15018', $currency, $amount)); + $query = $this->HT->query($sql,array($code, $currency, $amount)); $result = $query->result(); if ( ! empty($result)) { return $result[0]->ssje; From 3e49a01c981fd3a745ea30e6c5492dc6600d4696 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 27 Feb 2018 17:29:15 +0800 Subject: [PATCH 034/382] =?UTF-8?q?ipaylinks=20=E5=AF=BC=E5=87=BA=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95,=E6=89=93=E5=8D=B0=E7=BB=99?= =?UTF-8?q?=E9=93=B6=E8=A1=8C=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 67 ++++++++++++++++ webht/third_party/pay/models/note_model.php | 13 +++ .../third_party/pay/views/iPayLinks_list.php | 80 ++++++++++++++++--- 3 files changed, 150 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 1159a2ab..12938264 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1200,4 +1200,71 @@ class IPayLinksService extends CI_Controller ); } + public function export_list() + { + $from_date = $this->input->post("from_date"); + $to_date = $this->input->post("to_date"); + $currency = $this->input->post("currency"); + $export_list = $this->Note_model->date_range($from_date, $to_date, $currency); + if ($export_list == false) { + echo "Not found any records for export."; + return false; + } + $this->load->library('PHPExcel'); + $objPHPExcel = new PHPExcel(); + $objPHPExcel->setActiveSheetIndex(0); + //set width + $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); + $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30); + $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); + $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); + // 对齐 + $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); + $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + // 表标题行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A1', '#') + ->SetCellValue('B1', '团号') + ->SetCellValue('C1', '金额') + ->SetCellValue('D1', '付款人') + ->SetCellValue('E1', '交易号') + ->SetCellValue('F1', '收单时间'); + $currency_sum = array(); + bcscale(2); + $rowCount = 2; + foreach ($export_list as $key => $row) { + if( trim($row->IPL_currencyCode) != "") { + $currency_sum[trim($row->IPL_currencyCode)] = bcadd($currency_sum[trim($row->IPL_currencyCode)], $row->IPL_orderAmount); + } + $payer = $row->IPL_payerName ? ($row->IPL_payerName . "<" . $row->IPL_payerEmail . ">") : "退款"; + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, ($rowCount-1)) + ->setCellValueExplicit('B'.$rowCount, $row->IPL_orderId,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('C'.$rowCount, trim($row->IPL_currencyCode) . number_format($row->IPL_orderAmount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('D'.$rowCount, $payer) + ->setCellValueExplicit('E'.$rowCount, $row->IPL_dealId,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('F'.$rowCount, $row->IPL_acquiringTime); + $payer = ""; + $rowCount++; + } + $rowCount++; // 隔一行 + // 汇总行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A' . $rowCount, '合计'); + foreach ($currency_sum as $kc => $cur) { + $objPHPExcel->getActiveSheet() + ->SetCellValue('B' . $rowCount, $kc) + ->setCellValueExplicit('C' . $rowCount, number_format($cur, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING); + $rowCount++; + } + $filename = "export_ipaylinks_" . date('Y-m-d'); + header('Content-Type: application/vnd.ms-excel'); + header('Content-Disposition: attachment;filename="' . $filename . '.xls"'); + header('Cache-Control: max-age=0'); + $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); + $objWriter->save('php://output'); + } + } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 7954f428..0f30a40c 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -273,4 +273,17 @@ class Note_model extends CI_Model { return $query; } + public function date_range($from, $to, $currency=NULL) + { + $this->init(); + $search_sql = " AND pn.IPL_resultCode='0000' "; + $search_sql .= " AND pn.IPL_acquiringTime BETWEEN '$from 00:00:00' AND '$to 23:59:59' "; + if ( ! empty($currency)) { + $search_sql .= " AND IPL_currencyCode = '$currency' "; + } + $this->search = $search_sql; + $this->orderby = ""; + return $this->get_list(); + } + } diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 35e291f7..9551b14a 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -23,7 +23,7 @@ <style type="text/css"> p{margin-bottom: 8.5px;} a{text-decoration: none;} - .navbar-header h1{display: inline-block;margin-left: 30px;} + .navbar-header h1{display: inline-block;margin-left: 30px;margin-right: 30px;} .pageTitle{margin-left: 300px;} .pageTitle h1{color: #fff;border:none;font-size: 30px;} .mobileTitle h1{color: #fff;border:none;font-size: 20px;} @@ -39,24 +39,51 @@ /*.input-group{border: 1px solid #ccc;}*/ .input-group-btn{border: 1px solid #ccc;padding: 5px;} .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} + .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;} </style> </head> <body> - <div id="wrapper" class="chkVisible"> + <div id="wrapper" class="chkVisible print-none"> <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>iPayLinks Notes</h1> - <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> - </ul> + + <div class="export_form_area "> + + <form class="form-inline " method="post" id="search_list" action="/webht.php/apps/pay/ipaylinksservice/export_list/"> + <div class="form-group "> + <label for="from_date" class="">Date From</label> + <input type="text" class="form-control" id="from_date" name="from_date" required> + </div> + <div class="form-group "> + <label for="to_date" class="">To</label> + <input type="text" class="form-control" id="to_date" name="to_date" required> + </div> + <div class="form-group "> + <label for="currency" class="">Currency</label> + <select class="form-control" id="currency" name="currency"> + <option value="">All</option> + <option value="CNY">CNY</option> + <option value="USD">USD</option> + <option value="EUR">EUR</option> + <option value="CAD">CAD</option> + <option value="AUD">AUD</option> + <option value="GBP">GBP</option> + </select> + </div> + <button type="submit" class="btn btn-primary">Export</button> + </form> + + </div> </div> </div> <div id="content"> <div class="container-fluid marginTop"> <div class="row"> <!-- left --> - <div class="col-md-4 col-xs-24"> + <div class="col-md-4 col-xs-24 print-none"> <div class="row"> <form method="post" id="search_list" action="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list/"> <div class="input-group"> @@ -95,8 +122,8 @@ <li class="col-sm-5 "><strong>付款人</strong></li> <li class="col-sm-4 "><strong>交易号</strong></li> <li class="col-sm-3 "><strong>收单时间</strong></li> - <li class="col-sm-3 "><strong>通知时间</strong></li> - <li class="col-sm-2 "><strong>通知状态</strong></li> + <li class="col-sm-3 print-none"><strong>通知时间</strong></li> + <li class="col-sm-2 print-none"><strong>通知状态</strong></li> </a> </ul> <?php @@ -125,8 +152,8 @@ <li class="col-sm-4 nopadding-L" style="overflow:hidden;word-break: break-all;"><?php echo $item->IPL_dealId; ?></li> <li class="col-sm-3 nopadding-L" style="overflow:hidden;word-break: break-all;"><?php echo $item->IPL_acquiringTime; ?></li> - <li class="col-sm-3 nopadding-L" ><?php echo $item->IPL_noticeTime; ?></li> - <li class="col-sm-2" > + <li class="col-sm-3 nopadding-L print-none" ><?php echo $item->IPL_noticeTime; ?></li> + <li class="col-sm-2 print-none" > <?php $show_send = ''; $class_css = ''; @@ -146,7 +173,7 @@ <?php } ?> </div> <!-- </div> --> - <div class="pay_footer text-right"> + <div class="pay_footer text-right print-none"> <p>© 1998 China Highlights. <a href="https://www.chinahighlights.com/privacy.htm" rel="nofollow">Privacy Statement</a> </p> @@ -194,6 +221,39 @@ }); $(".ui-datepicker").css('width', '15.7em'); + var dateFormat = "yy-mm-dd", + from = $( "#from_date" ) + .datepicker({ + // defaultDate: "+1w", + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + to.datepicker( "option", "minDate", getDate( this ) ); + }), + to = $( "#to_date" ).datepicker({ + // defaultDate: "+1w", + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + from.datepicker( "option", "maxDate", getDate( this ) ); + }); + + function getDate( element ) { + var date; + try { + date = $.datepicker.parseDate( dateFormat, element.value ); + } catch( error ) { + date = null; + } + + return date; + } }); function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order) { if (pn_txn_id) { From c2e8694236176286debd23660ccd4187b4de3899 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 28 Feb 2018 11:06:08 +0800 Subject: [PATCH 035/382] =?UTF-8?q?paypal=20=E5=AF=BC=E5=87=BA=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay => }/libraries/PHPExcel/PHPExcel.php | 0 .../PHPExcel/PHPExcel/Autoloader.php | 0 .../PHPExcel/CachedObjectStorage/APC.php | 0 .../CachedObjectStorage/CacheBase.php | 0 .../PHPExcel/CachedObjectStorage/DiscISAM.php | 0 .../PHPExcel/CachedObjectStorage/ICache.php | 0 .../PHPExcel/CachedObjectStorage/Igbinary.php | 0 .../PHPExcel/CachedObjectStorage/Memcache.php | 0 .../PHPExcel/CachedObjectStorage/Memory.php | 0 .../CachedObjectStorage/MemoryGZip.php | 0 .../CachedObjectStorage/MemorySerialized.php | 0 .../PHPExcel/CachedObjectStorage/PHPTemp.php | 0 .../PHPExcel/CachedObjectStorage/SQLite.php | 0 .../PHPExcel/CachedObjectStorage/SQLite3.php | 0 .../PHPExcel/CachedObjectStorage/Wincache.php | 0 .../PHPExcel/CachedObjectStorageFactory.php | 0 .../CalcEngine/CyclicReferenceStack.php | 0 .../PHPExcel/PHPExcel/CalcEngine/Logger.php | 0 .../PHPExcel/PHPExcel/Calculation.php | 0 .../PHPExcel/Calculation/Database.php | 0 .../PHPExcel/Calculation/DateTime.php | 0 .../PHPExcel/Calculation/Engineering.php | 0 .../PHPExcel/Calculation/Exception.php | 0 .../PHPExcel/Calculation/ExceptionHandler.php | 0 .../PHPExcel/Calculation/Financial.php | 0 .../PHPExcel/Calculation/FormulaParser.php | 0 .../PHPExcel/Calculation/FormulaToken.php | 0 .../PHPExcel/Calculation/Function.php | 0 .../PHPExcel/Calculation/Functions.php | 0 .../PHPExcel/PHPExcel/Calculation/Logical.php | 0 .../PHPExcel/Calculation/LookupRef.php | 0 .../PHPExcel/Calculation/MathTrig.php | 0 .../PHPExcel/Calculation/Statistical.php | 0 .../PHPExcel/Calculation/TextData.php | 0 .../PHPExcel/Calculation/Token/Stack.php | 0 .../PHPExcel/Calculation/functionlist.txt | 0 .../libraries/PHPExcel/PHPExcel/Cell.php | 0 .../PHPExcel/Cell/AdvancedValueBinder.php | 0 .../PHPExcel/PHPExcel/Cell/DataType.php | 0 .../PHPExcel/PHPExcel/Cell/DataValidation.php | 0 .../PHPExcel/Cell/DefaultValueBinder.php | 0 .../PHPExcel/PHPExcel/Cell/Hyperlink.php | 0 .../PHPExcel/PHPExcel/Cell/IValueBinder.php | 0 .../libraries/PHPExcel/PHPExcel/Chart.php | 0 .../PHPExcel/PHPExcel/Chart/DataSeries.php | 0 .../PHPExcel/Chart/DataSeriesValues.php | 0 .../PHPExcel/PHPExcel/Chart/Exception.php | 0 .../PHPExcel/PHPExcel/Chart/Layout.php | 0 .../PHPExcel/PHPExcel/Chart/Legend.php | 0 .../PHPExcel/PHPExcel/Chart/PlotArea.php | 0 .../Chart/Renderer/PHP Charting Libraries.txt | 0 .../PHPExcel/Chart/Renderer/jpgraph.php | 0 .../PHPExcel/PHPExcel/Chart/Title.php | 0 .../libraries/PHPExcel/PHPExcel/Comment.php | 0 .../PHPExcel/PHPExcel/DocumentProperties.php | 0 .../PHPExcel/PHPExcel/DocumentSecurity.php | 0 .../libraries/PHPExcel/PHPExcel/Exception.php | 0 .../libraries/PHPExcel/PHPExcel/HashTable.php | 0 .../PHPExcel/PHPExcel/IComparable.php | 0 .../libraries/PHPExcel/PHPExcel/IOFactory.php | 0 .../PHPExcel/PHPExcel/NamedRange.php | 0 .../PHPExcel/PHPExcel/Reader/Abstract.php | 0 .../PHPExcel/PHPExcel/Reader/CSV.php | 0 .../PHPExcel/Reader/DefaultReadFilter.php | 0 .../PHPExcel/PHPExcel/Reader/Excel2003XML.php | 0 .../PHPExcel/PHPExcel/Reader/Excel2007.php | 0 .../PHPExcel/Reader/Excel2007/Chart.php | 0 .../PHPExcel/Reader/Excel2007/Theme.php | 0 .../PHPExcel/PHPExcel/Reader/Excel5.php | 0 .../PHPExcel/Reader/Excel5/Escher.php | 0 .../PHPExcel/PHPExcel/Reader/Excel5/MD5.php | 0 .../PHPExcel/PHPExcel/Reader/Excel5/RC4.php | 0 .../PHPExcel/PHPExcel/Reader/Exception.php | 0 .../PHPExcel/PHPExcel/Reader/Gnumeric.php | 0 .../PHPExcel/PHPExcel/Reader/HTML.php | 0 .../PHPExcel/PHPExcel/Reader/IReadFilter.php | 0 .../PHPExcel/PHPExcel/Reader/IReader.php | 0 .../PHPExcel/PHPExcel/Reader/OOCalc.php | 0 .../PHPExcel/PHPExcel/Reader/SYLK.php | 0 .../PHPExcel/PHPExcel/ReferenceHelper.php | 0 .../libraries/PHPExcel/PHPExcel/RichText.php | 0 .../PHPExcel/RichText/ITextElement.php | 0 .../PHPExcel/PHPExcel/RichText/Run.php | 0 .../PHPExcel/RichText/TextElement.php | 0 .../libraries/PHPExcel/PHPExcel/Settings.php | 0 .../PHPExcel/PHPExcel/Shared/CodePage.php | 0 .../PHPExcel/PHPExcel/Shared/Date.php | 0 .../PHPExcel/PHPExcel/Shared/Drawing.php | 0 .../PHPExcel/PHPExcel/Shared/Escher.php | 0 .../PHPExcel/Shared/Escher/DgContainer.php | 0 .../Escher/DgContainer/SpgrContainer.php | 0 .../DgContainer/SpgrContainer/SpContainer.php | 0 .../PHPExcel/Shared/Escher/DggContainer.php | 0 .../Escher/DggContainer/BstoreContainer.php | 0 .../DggContainer/BstoreContainer/BSE.php | 0 .../DggContainer/BstoreContainer/BSE/Blip.php | 0 .../PHPExcel/PHPExcel/Shared/Excel5.php | 0 .../PHPExcel/PHPExcel/Shared/File.php | 0 .../PHPExcel/PHPExcel/Shared/Font.php | 0 .../PHPExcel/Shared/JAMA/CHANGELOG.TXT | 0 .../Shared/JAMA/CholeskyDecomposition.php | 0 .../Shared/JAMA/EigenvalueDecomposition.php | 0 .../PHPExcel/Shared/JAMA/LUDecomposition.php | 0 .../PHPExcel/PHPExcel/Shared/JAMA/Matrix.php | 0 .../PHPExcel/Shared/JAMA/QRDecomposition.php | 0 .../JAMA/SingularValueDecomposition.php | 0 .../PHPExcel/Shared/JAMA/utils/Error.php | 0 .../PHPExcel/Shared/JAMA/utils/Maths.php | 0 .../PHPExcel/PHPExcel/Shared/OLE.php | 0 .../Shared/OLE/ChainedBlockStream.php | 0 .../PHPExcel/PHPExcel/Shared/OLE/PPS.php | 0 .../PHPExcel/PHPExcel/Shared/OLE/PPS/File.php | 0 .../PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php | 0 .../PHPExcel/PHPExcel/Shared/OLERead.php | 0 .../PHPExcel/Shared/PCLZip/gnu-lgpl.txt | 0 .../PHPExcel/Shared/PCLZip/pclzip.lib.php | 0 .../PHPExcel/Shared/PCLZip/readme.txt | 0 .../PHPExcel/Shared/PasswordHasher.php | 0 .../PHPExcel/PHPExcel/Shared/String.php | 0 .../PHPExcel/PHPExcel/Shared/TimeZone.php | 0 .../PHPExcel/PHPExcel/Shared/XMLWriter.php | 0 .../PHPExcel/PHPExcel/Shared/ZipArchive.php | 0 .../PHPExcel/Shared/ZipStreamWrapper.php | 0 .../PHPExcel/Shared/trend/bestFitClass.php | 0 .../Shared/trend/exponentialBestFitClass.php | 0 .../Shared/trend/linearBestFitClass.php | 0 .../Shared/trend/logarithmicBestFitClass.php | 0 .../Shared/trend/polynomialBestFitClass.php | 0 .../Shared/trend/powerBestFitClass.php | 0 .../PHPExcel/Shared/trend/trendClass.php | 0 .../libraries/PHPExcel/PHPExcel/Style.php | 0 .../PHPExcel/PHPExcel/Style/Alignment.php | 0 .../PHPExcel/PHPExcel/Style/Border.php | 0 .../PHPExcel/PHPExcel/Style/Borders.php | 0 .../PHPExcel/PHPExcel/Style/Color.php | 0 .../PHPExcel/PHPExcel/Style/Conditional.php | 0 .../PHPExcel/PHPExcel/Style/Fill.php | 0 .../PHPExcel/PHPExcel/Style/Font.php | 0 .../PHPExcel/PHPExcel/Style/NumberFormat.php | 0 .../PHPExcel/PHPExcel/Style/Protection.php | 0 .../PHPExcel/PHPExcel/Style/Supervisor.php | 0 .../libraries/PHPExcel/PHPExcel/Worksheet.php | 0 .../PHPExcel/Worksheet/AutoFilter.php | 0 .../PHPExcel/Worksheet/AutoFilter/Column.php | 0 .../Worksheet/AutoFilter/Column/Rule.php | 0 .../PHPExcel/Worksheet/BaseDrawing.php | 0 .../PHPExcel/Worksheet/CellIterator.php | 0 .../PHPExcel/Worksheet/ColumnDimension.php | 0 .../PHPExcel/PHPExcel/Worksheet/Drawing.php | 0 .../PHPExcel/Worksheet/Drawing/Shadow.php | 0 .../PHPExcel/Worksheet/HeaderFooter.php | 0 .../Worksheet/HeaderFooterDrawing.php | 0 .../PHPExcel/Worksheet/MemoryDrawing.php | 0 .../PHPExcel/Worksheet/PageMargins.php | 0 .../PHPExcel/PHPExcel/Worksheet/PageSetup.php | 0 .../PHPExcel/Worksheet/Protection.php | 0 .../PHPExcel/PHPExcel/Worksheet/Row.php | 0 .../PHPExcel/Worksheet/RowDimension.php | 0 .../PHPExcel/Worksheet/RowIterator.php | 0 .../PHPExcel/PHPExcel/Worksheet/SheetView.php | 0 .../PHPExcel/PHPExcel/WorksheetIterator.php | 0 .../PHPExcel/PHPExcel/Writer/Abstract.php | 0 .../PHPExcel/PHPExcel/Writer/CSV.php | 0 .../PHPExcel/PHPExcel/Writer/Excel2007.php | 0 .../PHPExcel/Writer/Excel2007/Chart.php | 0 .../PHPExcel/Writer/Excel2007/Comments.php | 0 .../Writer/Excel2007/ContentTypes.php | 0 .../PHPExcel/Writer/Excel2007/DocProps.php | 0 .../PHPExcel/Writer/Excel2007/Drawing.php | 0 .../PHPExcel/Writer/Excel2007/Rels.php | 0 .../PHPExcel/Writer/Excel2007/RelsRibbon.php | 0 .../PHPExcel/Writer/Excel2007/RelsVBA.php | 0 .../PHPExcel/Writer/Excel2007/StringTable.php | 0 .../PHPExcel/Writer/Excel2007/Style.php | 0 .../PHPExcel/Writer/Excel2007/Theme.php | 0 .../PHPExcel/Writer/Excel2007/Workbook.php | 0 .../PHPExcel/Writer/Excel2007/Worksheet.php | 0 .../PHPExcel/Writer/Excel2007/WriterPart.php | 0 .../PHPExcel/PHPExcel/Writer/Excel5.php | 0 .../PHPExcel/Writer/Excel5/BIFFwriter.php | 0 .../PHPExcel/Writer/Excel5/Escher.php | 0 .../PHPExcel/PHPExcel/Writer/Excel5/Font.php | 0 .../PHPExcel/Writer/Excel5/Parser.php | 0 .../PHPExcel/Writer/Excel5/Workbook.php | 0 .../PHPExcel/Writer/Excel5/Worksheet.php | 0 .../PHPExcel/PHPExcel/Writer/Excel5/Xf.php | 0 .../PHPExcel/PHPExcel/Writer/Exception.php | 0 .../PHPExcel/PHPExcel/Writer/HTML.php | 0 .../PHPExcel/PHPExcel/Writer/IWriter.php | 0 .../PHPExcel/PHPExcel/Writer/PDF.php | 0 .../PHPExcel/PHPExcel/Writer/PDF/Core.php | 0 .../PHPExcel/PHPExcel/Writer/PDF/DomPDF.php | 0 .../PHPExcel/PHPExcel/Writer/PDF/mPDF.php | 0 .../PHPExcel/PHPExcel/Writer/PDF/tcPDF.php | 0 .../PHPExcel/PHPExcel/locale/bg/config | 0 .../PHPExcel/PHPExcel/locale/cs/config | 0 .../PHPExcel/PHPExcel/locale/cs/functions | 0 .../PHPExcel/PHPExcel/locale/da/config | 0 .../PHPExcel/PHPExcel/locale/da/functions | 0 .../PHPExcel/PHPExcel/locale/de/config | 0 .../PHPExcel/PHPExcel/locale/de/functions | 0 .../PHPExcel/PHPExcel/locale/en/uk/config | 0 .../PHPExcel/PHPExcel/locale/es/config | 0 .../PHPExcel/PHPExcel/locale/es/functions | 0 .../PHPExcel/PHPExcel/locale/fi/config | 0 .../PHPExcel/PHPExcel/locale/fi/functions | 0 .../PHPExcel/PHPExcel/locale/fr/config | 0 .../PHPExcel/PHPExcel/locale/fr/functions | 0 .../PHPExcel/PHPExcel/locale/hu/config | 0 .../PHPExcel/PHPExcel/locale/hu/functions | 0 .../PHPExcel/PHPExcel/locale/it/config | 0 .../PHPExcel/PHPExcel/locale/it/functions | 0 .../PHPExcel/PHPExcel/locale/nl/config | 0 .../PHPExcel/PHPExcel/locale/nl/functions | 0 .../PHPExcel/PHPExcel/locale/no/config | 0 .../PHPExcel/PHPExcel/locale/no/functions | 0 .../PHPExcel/PHPExcel/locale/pl/config | 0 .../PHPExcel/PHPExcel/locale/pl/functions | 0 .../PHPExcel/PHPExcel/locale/pt/br/config | 0 .../PHPExcel/PHPExcel/locale/pt/br/functions | 0 .../PHPExcel/PHPExcel/locale/pt/config | 0 .../PHPExcel/PHPExcel/locale/pt/functions | 0 .../PHPExcel/PHPExcel/locale/ru/config | 0 .../PHPExcel/PHPExcel/locale/ru/functions | 0 .../PHPExcel/PHPExcel/locale/sv/config | 0 .../PHPExcel/PHPExcel/locale/sv/functions | 0 .../PHPExcel/PHPExcel/locale/tr/config | 0 .../PHPExcel/PHPExcel/locale/tr/functions | 0 .../pay/controllers/iPayLinksService.php | 2 +- .../third_party/pay/views/iPayLinks_list.php | 2 - .../third_party/paypal/controllers/index.php | 68 ++++++++++++++++++ .../third_party/paypal/models/note_model.php | 31 +++++--- webht/third_party/paypal/views/note_list.php | 72 +++++++++++++++++-- webht/views/n-header.php | 12 ++-- 234 files changed, 164 insertions(+), 23 deletions(-) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Autoloader.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Database.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Exception.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Financial.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Function.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Functions.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Logical.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/TextData.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/DataType.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Exception.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Layout.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Legend.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Chart/Title.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Comment.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/DocumentProperties.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/DocumentSecurity.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Exception.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/HashTable.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/IComparable.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/IOFactory.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/NamedRange.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Abstract.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/CSV.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel5.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Exception.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/HTML.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/IReader.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Reader/SYLK.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/ReferenceHelper.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/RichText.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/RichText/Run.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/RichText/TextElement.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Settings.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/CodePage.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Date.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Drawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Excel5.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/File.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/Font.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLE.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/OLERead.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/String.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Alignment.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Border.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Borders.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Color.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Conditional.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Fill.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Font.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Protection.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Style/Supervisor.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/Row.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/WorksheetIterator.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Abstract.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/CSV.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/Exception.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/HTML.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/IWriter.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/PDF.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/bg/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/cs/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/cs/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/da/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/da/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/de/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/de/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/en/uk/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/es/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/es/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/fi/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/fi/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/fr/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/fr/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/hu/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/hu/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/it/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/it/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/nl/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/nl/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/no/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/no/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pl/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pl/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pt/br/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pt/br/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pt/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/pt/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/ru/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/ru/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/sv/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/sv/functions (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/tr/config (100%) rename webht/{third_party/pay => }/libraries/PHPExcel/PHPExcel/locale/tr/functions (100%) diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel.php b/webht/libraries/PHPExcel/PHPExcel.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel.php rename to webht/libraries/PHPExcel/PHPExcel.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php b/webht/libraries/PHPExcel/PHPExcel/Autoloader.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Autoloader.php rename to webht/libraries/PHPExcel/PHPExcel/Autoloader.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/APC.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/CacheBase.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/DiscISAM.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/ICache.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Igbinary.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memcache.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Memory.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemoryGZip.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/MemorySerialized.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/PHPTemp.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/SQLite3.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorage/Wincache.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php b/webht/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php rename to webht/libraries/PHPExcel/PHPExcel/CachedObjectStorageFactory.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php b/webht/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php rename to webht/libraries/PHPExcel/PHPExcel/CalcEngine/CyclicReferenceStack.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php b/webht/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php rename to webht/libraries/PHPExcel/PHPExcel/CalcEngine/Logger.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php b/webht/libraries/PHPExcel/PHPExcel/Calculation.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Database.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Database.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Database.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/DateTime.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Engineering.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Exception.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Exception.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Exception.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/ExceptionHandler.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Financial.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Financial.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Financial.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Financial.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/FormulaParser.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/FormulaToken.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Function.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Function.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Function.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Functions.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Functions.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Functions.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Logical.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Logical.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Logical.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/LookupRef.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/MathTrig.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Statistical.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/TextData.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/TextData.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/TextData.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php b/webht/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php rename to webht/libraries/PHPExcel/PHPExcel/Calculation/Token/Stack.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt b/webht/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt rename to webht/libraries/PHPExcel/PHPExcel/Calculation/functionlist.txt diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php b/webht/libraries/PHPExcel/PHPExcel/Cell.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell.php rename to webht/libraries/PHPExcel/PHPExcel/Cell.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php b/webht/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/AdvancedValueBinder.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php b/webht/libraries/PHPExcel/PHPExcel/Cell/DataType.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataType.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/DataType.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php b/webht/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/DataValidation.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php b/webht/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/DefaultValueBinder.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php b/webht/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/Hyperlink.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php b/webht/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php rename to webht/libraries/PHPExcel/PHPExcel/Cell/IValueBinder.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart.php b/webht/libraries/PHPExcel/PHPExcel/Chart.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart.php rename to webht/libraries/PHPExcel/PHPExcel/Chart.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php b/webht/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/DataSeries.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php b/webht/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/DataSeriesValues.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php b/webht/libraries/PHPExcel/PHPExcel/Chart/Exception.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Exception.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/Exception.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php b/webht/libraries/PHPExcel/PHPExcel/Chart/Layout.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Layout.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/Layout.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php b/webht/libraries/PHPExcel/PHPExcel/Chart/Legend.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Legend.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/Legend.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php b/webht/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/PlotArea.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt b/webht/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt rename to webht/libraries/PHPExcel/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php b/webht/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/Renderer/jpgraph.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php b/webht/libraries/PHPExcel/PHPExcel/Chart/Title.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Chart/Title.php rename to webht/libraries/PHPExcel/PHPExcel/Chart/Title.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php b/webht/libraries/PHPExcel/PHPExcel/Comment.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Comment.php rename to webht/libraries/PHPExcel/PHPExcel/Comment.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php b/webht/libraries/PHPExcel/PHPExcel/DocumentProperties.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentProperties.php rename to webht/libraries/PHPExcel/PHPExcel/DocumentProperties.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php b/webht/libraries/PHPExcel/PHPExcel/DocumentSecurity.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/DocumentSecurity.php rename to webht/libraries/PHPExcel/PHPExcel/DocumentSecurity.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php b/webht/libraries/PHPExcel/PHPExcel/Exception.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Exception.php rename to webht/libraries/PHPExcel/PHPExcel/Exception.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php b/webht/libraries/PHPExcel/PHPExcel/HashTable.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/HashTable.php rename to webht/libraries/PHPExcel/PHPExcel/HashTable.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php b/webht/libraries/PHPExcel/PHPExcel/IComparable.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/IComparable.php rename to webht/libraries/PHPExcel/PHPExcel/IComparable.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/IOFactory.php b/webht/libraries/PHPExcel/PHPExcel/IOFactory.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/IOFactory.php rename to webht/libraries/PHPExcel/PHPExcel/IOFactory.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php b/webht/libraries/PHPExcel/PHPExcel/NamedRange.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/NamedRange.php rename to webht/libraries/PHPExcel/PHPExcel/NamedRange.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Abstract.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Abstract.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Abstract.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php b/webht/libraries/PHPExcel/PHPExcel/Reader/CSV.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/CSV.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/CSV.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php b/webht/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/DefaultReadFilter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel2003XML.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Chart.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel2007/Theme.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel5.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel5.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/Escher.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/MD5.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Excel5/RC4.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Exception.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Exception.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Exception.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php b/webht/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/Gnumeric.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php b/webht/libraries/PHPExcel/PHPExcel/Reader/HTML.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/HTML.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/HTML.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php b/webht/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/IReadFilter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php b/webht/libraries/PHPExcel/PHPExcel/Reader/IReader.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/IReader.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/IReader.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php b/webht/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/OOCalc.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php b/webht/libraries/PHPExcel/PHPExcel/Reader/SYLK.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Reader/SYLK.php rename to webht/libraries/PHPExcel/PHPExcel/Reader/SYLK.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php b/webht/libraries/PHPExcel/PHPExcel/ReferenceHelper.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/ReferenceHelper.php rename to webht/libraries/PHPExcel/PHPExcel/ReferenceHelper.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php b/webht/libraries/PHPExcel/PHPExcel/RichText.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText.php rename to webht/libraries/PHPExcel/PHPExcel/RichText.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php b/webht/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php rename to webht/libraries/PHPExcel/PHPExcel/RichText/ITextElement.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php b/webht/libraries/PHPExcel/PHPExcel/RichText/Run.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/Run.php rename to webht/libraries/PHPExcel/PHPExcel/RichText/Run.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php b/webht/libraries/PHPExcel/PHPExcel/RichText/TextElement.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/RichText/TextElement.php rename to webht/libraries/PHPExcel/PHPExcel/RichText/TextElement.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php b/webht/libraries/PHPExcel/PHPExcel/Settings.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Settings.php rename to webht/libraries/PHPExcel/PHPExcel/Settings.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php b/webht/libraries/PHPExcel/PHPExcel/Shared/CodePage.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/CodePage.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/CodePage.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Date.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Date.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Date.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Drawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Drawing.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Drawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Excel5.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Excel5.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Excel5.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php b/webht/libraries/PHPExcel/PHPExcel/Shared/File.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/File.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/File.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php b/webht/libraries/PHPExcel/PHPExcel/Shared/Font.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/Font.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/Font.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/CHANGELOG.TXT diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/CholeskyDecomposition.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/LUDecomposition.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/Matrix.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/QRDecomposition.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/SingularValueDecomposition.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Error.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php b/webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/JAMA/utils/Maths.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLE.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLE.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLE/ChainedBlockStream.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/File.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLE/PPS/Root.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php b/webht/libraries/PHPExcel/PHPExcel/Shared/OLERead.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/OLERead.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/OLERead.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt b/webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt rename to webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/gnu-lgpl.txt diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php b/webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/pclzip.lib.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt b/webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt rename to webht/libraries/PHPExcel/PHPExcel/Shared/PCLZip/readme.txt diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php b/webht/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/PasswordHasher.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php b/webht/libraries/PHPExcel/PHPExcel/Shared/String.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/String.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/String.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php b/webht/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/TimeZone.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php b/webht/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/XMLWriter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php b/webht/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/ZipArchive.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php b/webht/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/ZipStreamWrapper.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/bestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/exponentialBestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/linearBestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/logarithmicBestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/polynomialBestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/powerBestFitClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php b/webht/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php rename to webht/libraries/PHPExcel/PHPExcel/Shared/trend/trendClass.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php b/webht/libraries/PHPExcel/PHPExcel/Style.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style.php rename to webht/libraries/PHPExcel/PHPExcel/Style.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php b/webht/libraries/PHPExcel/PHPExcel/Style/Alignment.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Alignment.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Alignment.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php b/webht/libraries/PHPExcel/PHPExcel/Style/Border.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Border.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Border.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php b/webht/libraries/PHPExcel/PHPExcel/Style/Borders.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Borders.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Borders.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php b/webht/libraries/PHPExcel/PHPExcel/Style/Color.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Color.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Color.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php b/webht/libraries/PHPExcel/PHPExcel/Style/Conditional.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Conditional.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Conditional.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php b/webht/libraries/PHPExcel/PHPExcel/Style/Fill.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Fill.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Fill.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php b/webht/libraries/PHPExcel/PHPExcel/Style/Font.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Font.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Font.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php b/webht/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php rename to webht/libraries/PHPExcel/PHPExcel/Style/NumberFormat.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php b/webht/libraries/PHPExcel/PHPExcel/Style/Protection.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Protection.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Protection.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php b/webht/libraries/PHPExcel/PHPExcel/Style/Supervisor.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Style/Supervisor.php rename to webht/libraries/PHPExcel/PHPExcel/Style/Supervisor.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/AutoFilter/Column/Rule.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/BaseDrawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/CellIterator.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/ColumnDimension.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/Drawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/Drawing/Shadow.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/HeaderFooterDrawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/MemoryDrawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/PageMargins.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/PageSetup.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/Protection.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/Row.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/Row.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/Row.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/RowDimension.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/RowIterator.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php b/webht/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php rename to webht/libraries/PHPExcel/PHPExcel/Worksheet/SheetView.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php b/webht/libraries/PHPExcel/PHPExcel/WorksheetIterator.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/WorksheetIterator.php rename to webht/libraries/PHPExcel/PHPExcel/WorksheetIterator.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Abstract.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Abstract.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Abstract.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php b/webht/libraries/PHPExcel/PHPExcel/Writer/CSV.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/CSV.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/CSV.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Chart.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Comments.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/ContentTypes.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/DocProps.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Drawing.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Rels.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsRibbon.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/RelsVBA.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/StringTable.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Style.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Theme.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Workbook.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/Worksheet.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel2007/WriterPart.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/BIFFwriter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Escher.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Font.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Parser.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Workbook.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Worksheet.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Excel5/Xf.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php b/webht/libraries/PHPExcel/PHPExcel/Writer/Exception.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/Exception.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/Exception.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php b/webht/libraries/PHPExcel/PHPExcel/Writer/HTML.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/HTML.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/HTML.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php b/webht/libraries/PHPExcel/PHPExcel/Writer/IWriter.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/IWriter.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/IWriter.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php b/webht/libraries/PHPExcel/PHPExcel/Writer/PDF.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/PDF.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php b/webht/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/PDF/Core.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php b/webht/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/PDF/DomPDF.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php b/webht/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/PDF/mPDF.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php b/webht/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php rename to webht/libraries/PHPExcel/PHPExcel/Writer/PDF/tcPDF.php diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config b/webht/libraries/PHPExcel/PHPExcel/locale/bg/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/bg/config rename to webht/libraries/PHPExcel/PHPExcel/locale/bg/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config b/webht/libraries/PHPExcel/PHPExcel/locale/cs/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/config rename to webht/libraries/PHPExcel/PHPExcel/locale/cs/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions b/webht/libraries/PHPExcel/PHPExcel/locale/cs/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/cs/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/cs/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config b/webht/libraries/PHPExcel/PHPExcel/locale/da/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/config rename to webht/libraries/PHPExcel/PHPExcel/locale/da/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions b/webht/libraries/PHPExcel/PHPExcel/locale/da/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/da/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/da/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config b/webht/libraries/PHPExcel/PHPExcel/locale/de/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/config rename to webht/libraries/PHPExcel/PHPExcel/locale/de/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions b/webht/libraries/PHPExcel/PHPExcel/locale/de/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/de/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/de/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config b/webht/libraries/PHPExcel/PHPExcel/locale/en/uk/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/en/uk/config rename to webht/libraries/PHPExcel/PHPExcel/locale/en/uk/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config b/webht/libraries/PHPExcel/PHPExcel/locale/es/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/config rename to webht/libraries/PHPExcel/PHPExcel/locale/es/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions b/webht/libraries/PHPExcel/PHPExcel/locale/es/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/es/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/es/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config b/webht/libraries/PHPExcel/PHPExcel/locale/fi/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/config rename to webht/libraries/PHPExcel/PHPExcel/locale/fi/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions b/webht/libraries/PHPExcel/PHPExcel/locale/fi/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fi/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/fi/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config b/webht/libraries/PHPExcel/PHPExcel/locale/fr/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/config rename to webht/libraries/PHPExcel/PHPExcel/locale/fr/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions b/webht/libraries/PHPExcel/PHPExcel/locale/fr/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/fr/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/fr/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config b/webht/libraries/PHPExcel/PHPExcel/locale/hu/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/config rename to webht/libraries/PHPExcel/PHPExcel/locale/hu/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions b/webht/libraries/PHPExcel/PHPExcel/locale/hu/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/hu/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/hu/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config b/webht/libraries/PHPExcel/PHPExcel/locale/it/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/config rename to webht/libraries/PHPExcel/PHPExcel/locale/it/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions b/webht/libraries/PHPExcel/PHPExcel/locale/it/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/it/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/it/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config b/webht/libraries/PHPExcel/PHPExcel/locale/nl/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/config rename to webht/libraries/PHPExcel/PHPExcel/locale/nl/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions b/webht/libraries/PHPExcel/PHPExcel/locale/nl/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/nl/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/nl/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config b/webht/libraries/PHPExcel/PHPExcel/locale/no/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/config rename to webht/libraries/PHPExcel/PHPExcel/locale/no/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions b/webht/libraries/PHPExcel/PHPExcel/locale/no/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/no/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/no/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config b/webht/libraries/PHPExcel/PHPExcel/locale/pl/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/config rename to webht/libraries/PHPExcel/PHPExcel/locale/pl/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions b/webht/libraries/PHPExcel/PHPExcel/locale/pl/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pl/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/pl/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config b/webht/libraries/PHPExcel/PHPExcel/locale/pt/br/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/config rename to webht/libraries/PHPExcel/PHPExcel/locale/pt/br/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions b/webht/libraries/PHPExcel/PHPExcel/locale/pt/br/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/br/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/pt/br/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config b/webht/libraries/PHPExcel/PHPExcel/locale/pt/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/config rename to webht/libraries/PHPExcel/PHPExcel/locale/pt/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions b/webht/libraries/PHPExcel/PHPExcel/locale/pt/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/pt/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/pt/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config b/webht/libraries/PHPExcel/PHPExcel/locale/ru/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/config rename to webht/libraries/PHPExcel/PHPExcel/locale/ru/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions b/webht/libraries/PHPExcel/PHPExcel/locale/ru/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/ru/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/ru/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config b/webht/libraries/PHPExcel/PHPExcel/locale/sv/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/config rename to webht/libraries/PHPExcel/PHPExcel/locale/sv/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions b/webht/libraries/PHPExcel/PHPExcel/locale/sv/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/sv/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/sv/functions diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config b/webht/libraries/PHPExcel/PHPExcel/locale/tr/config similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/config rename to webht/libraries/PHPExcel/PHPExcel/locale/tr/config diff --git a/webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions b/webht/libraries/PHPExcel/PHPExcel/locale/tr/functions similarity index 100% rename from webht/third_party/pay/libraries/PHPExcel/PHPExcel/locale/tr/functions rename to webht/libraries/PHPExcel/PHPExcel/locale/tr/functions diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 12938264..16855b9f 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1236,7 +1236,7 @@ class IPayLinksService extends CI_Controller $rowCount = 2; foreach ($export_list as $key => $row) { if( trim($row->IPL_currencyCode) != "") { - $currency_sum[trim($row->IPL_currencyCode)] = bcadd($currency_sum[trim($row->IPL_currencyCode)], $row->IPL_orderAmount); + $currency_sum[trim($row->IPL_currencyCode)] = @ bcadd($currency_sum[trim($row->IPL_currencyCode)], $row->IPL_orderAmount); } $payer = $row->IPL_payerName ? ($row->IPL_payerName . "<" . $row->IPL_payerEmail . ">") : "退款"; $objPHPExcel->getActiveSheet() diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 9551b14a..9ffe7de7 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -224,7 +224,6 @@ var dateFormat = "yy-mm-dd", from = $( "#from_date" ) .datepicker({ - // defaultDate: "+1w", dateFormat: dateFormat, changeMonth: true, changeYear: true, @@ -234,7 +233,6 @@ to.datepicker( "option", "minDate", getDate( this ) ); }), to = $( "#to_date" ).datepicker({ - // defaultDate: "+1w", dateFormat: dateFormat, changeMonth: true, changeYear: true, diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 9ca58990..72aaa8ec 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -924,4 +924,72 @@ class Index extends CI_Controller { echo json_encode('没找到数据!'); } + public function export_list() + { + $from_date = $this->input->post("from_date"); + $to_date = $this->input->post("to_date"); + $currency = $this->input->post("currency"); + $export_list = $this->Note_model->date_range($from_date, $to_date, $currency); + if ($export_list == false) { + echo "Not found any records for export."; + return false; + } + $this->load->library('PHPExcel'); + $objPHPExcel = new PHPExcel(); + $objPHPExcel->setActiveSheetIndex(0); + //set width + $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); + $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30); + $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); + $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); + // 对齐 + $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); + $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + // 表标题行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A1', '#') + ->SetCellValue('B1', '团号') + ->SetCellValue('C1', '金额') + ->SetCellValue('D1', '付款人') + ->SetCellValue('E1', '交易号') + ->SetCellValue('F1', '收单时间'); + $currency_sum = array(); + bcscale(2); + $rowCount = 2; + foreach ($export_list as $key => $row) { + if( trim($row->pn_mc_currency) != "") { + $currency_sum[trim($row->pn_mc_currency)] = @ bcadd($currency_sum[trim($row->pn_mc_currency)], $row->pn_mc_gross); + } + $payer = $row->pn_payer ? ($row->pn_payer . "<" . $row->pn_payer_email . ">") : "退款"; + $orderid = $row->pn_invoice ? $row->pn_invoice : $row->pn_item_number; + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, ($rowCount-1)) + ->setCellValueExplicit('B'.$rowCount, $orderid,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('C'.$rowCount, trim($row->pn_mc_currency) . number_format($row->pn_mc_gross, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('D'.$rowCount, $payer) + ->setCellValueExplicit('E'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('F'.$rowCount, $row->pn_datetime); + $payer = $orderid = ""; + $rowCount++; + } + $rowCount++; // 隔一行 + // 汇总行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A' . $rowCount, '合计'); + foreach ($currency_sum as $kc => $cur) { + $objPHPExcel->getActiveSheet() + ->SetCellValue('B' . $rowCount, $kc) + ->setCellValueExplicit('C' . $rowCount, number_format($cur, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING); + $rowCount++; + } + $filename = "export_paypal_" . date('Y-m-d'); + header('Content-Type: application/vnd.ms-excel'); + header('Content-Disposition: attachment;filename="' . $filename . '.xls"'); + header('Cache-Control: max-age=0'); + $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); + $objWriter->save('php://output'); + } + } diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index e01702f1..d5f6c022 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -50,7 +50,7 @@ class Note_model extends CI_Model { $this->orderby=" ORDER BY CASE pn.pn_send WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.pn_sn DESC "; return $this->get_list(); } - + public function note($pn_txn_id){ $this->init(); $this->topnum=1; @@ -64,12 +64,12 @@ class Note_model extends CI_Model { $search_sql = ''; $search_key = trim($search_key); if (!empty($search_key)) { - $search_sql.=" AND ( pn.pn_txn_id = '$search_key' - OR pn.pn_invoice like '%$search_key%' - OR pn.pn_custom like '%$search_key%' + $search_sql.=" AND ( pn.pn_txn_id = '$search_key' + OR pn.pn_invoice like '%$search_key%' + OR pn.pn_custom like '%$search_key%' OR pn.pn_item_name like '%$search_key%' OR pn.pn_item_number like '%$search_key%' - OR pn.pn_payer like '%$search_key%' + OR pn.pn_payer like '%$search_key%' OR pn.pn_payer_email like '%$search_key%' )"; } $this->search = $search_sql; @@ -95,7 +95,7 @@ class Note_model extends CI_Model { public function get_list() { $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT "; - $sql .= " + $sql .= " pn.pn_sn ,pn.pn_txn_id ,pn.pn_invoice @@ -112,7 +112,7 @@ class Note_model extends CI_Model { ,pn.pn_payment_date ,pn.pn_send FROM paypal_note pn - WHERE 1=1 + WHERE 1=1 "; $this->pn_send ? $sql.=$this->pn_send : false; $this->search ? $sql.=$this->search : false; @@ -136,7 +136,7 @@ class Note_model extends CI_Model { $sql = " UPDATE paypal_note SET pn_send = ? - WHERE pn_txn_id = ? + WHERE pn_txn_id = ? "; return $this->HT->query($sql, array($pn_send, $pn_txn_id)); } @@ -146,9 +146,22 @@ class Note_model extends CI_Model { $sql = " UPDATE paypal_note SET pn_invoice = ? - WHERE pn_txn_id = ? + WHERE pn_txn_id = ? "; return $this->HT->query($sql, array($pn_invoice, $pn_txn_id)); } + public function date_range($from, $to, $currency=NULL) + { + $this->init(); + $search_sql = " AND pn_payment_status in ('Completed','Refunded') "; + $search_sql .= " AND pn.pn_datetime BETWEEN '$from 00:00:00' AND '$to 23:59:59' "; + if ( ! empty($currency)) { + $search_sql .= " AND pn_mc_currency = '$currency' "; + } + $this->search = $search_sql; + $this->orderby = ""; + return $this->get_list(); + } + } diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 29fb67d0..0d8a07ce 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -1,4 +1,4 @@ -<link href="/min?f=/css/destination.css" rel="stylesheet"> +<link href="http://www.mycht.cn/min?f=/css/destination.css" rel="stylesheet"> <script type="text/javascript"> $(document).ready(function() { $('#datepicker').datepicker({ @@ -10,8 +10,70 @@ } }); $(".ui-datepicker").css('width', '15.7em'); + var dateFormat = "yy-mm-dd", + from = $( "#from_date" ) + .datepicker({ + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + to.datepicker( "option", "minDate", getDate( this ) ); + }), + to = $( "#to_date" ).datepicker({ + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + from.datepicker( "option", "maxDate", getDate( this ) ); + }); + + function getDate( element ) { + var date; + try { + date = $.datepicker.parseDate( dateFormat, element.value ); + } catch( error ) { + date = null; + } + return date; + } }); </script> +<style type="text/css"> +.export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;position: absolute;top: 0;left: 17%;} +</style> +<div class="export_form_area "> + <form class="form-inline " method="post" id="search_list" action="/webht.php/apps/paypal/index/export_list/"> + <div class="form-group "> + <label for="from_date" class="">Date From</label> + <input type="text" class="form-control" id="from_date" name="from_date" required> + </div> + <div class="form-group "> + <label for="to_date" class="">To</label> + <input type="text" class="form-control" id="to_date" name="to_date" required> + </div> + <div class="form-group "> + <label for="currency" class="">Currency</label> + <select class="form-control" id="currency" name="currency"> + <option value="">All</option> + <option value="CNY">CNY</option> + <option value="USD">USD</option> + <option value="EUR">EUR</option> + <option value="CAD">CAD</option> + <option value="AUD">AUD</option> + <option value="GBP">GBP</option> + <option value="NZD">NZD</option> + <option value="SGD">SGD</option> + <option value="CHF">CHF</option> + </select> + </div> + <button type="submit" class="btn btn-primary">Export</button> + </form> +</div> + <div class="container-fluid"> <div class="row"> @@ -60,9 +122,9 @@ <li class="col-sm-7 "><strong>主题</strong></li> <li class="col-sm-4"><strong>客人邮箱</strong></li> <li class="col-sm-4 "><strong>交易号</strong></li> - <li class="col-sm-3 "><strong>收款(北京)时间</strong></li> - <li class="col-sm-3 "><strong>通知时间</strong></li> - <li class="col-sm-2 "><strong>通知状态</strong></li> + <li class="col-sm-3 "><strong>收款(北京)时间</strong></li> + <li class="col-sm-3 "><strong>通知时间</strong></li> + <li class="col-sm-2 "><strong>通知状态</strong></li> </a> </ul> <?php @@ -175,4 +237,4 @@ -</script> \ No newline at end of file +</script> diff --git a/webht/views/n-header.php b/webht/views/n-header.php index 02deb3e0..cb06b1ad 100644 --- a/webht/views/n-header.php +++ b/webht/views/n-header.php @@ -8,8 +8,8 @@ <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> <link href="/css/nav/nav.css?v=20150723" rel="stylesheet"> <link href="/css/webht/jquery-ui-1.10.0.custom.css" rel="stylesheet"> - <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> - <script src="/js/jquery-ui.min.js?v=1"></script> + <script src="http://www.mycht.cn/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> + <script src="http://www.mycht.cn/js/jquery-ui.min.js?v=1"></script> <!--[if lt IE 9]> <script src="/js/respond.min.js" type="text/javascript"></script> <![endif]--> @@ -20,7 +20,7 @@ <div class="container-fluid search_container nopadding"> <div class="navbar-header" style="float:none;"> <?php if(!$this->session->userdata('isapp')){ ?> - + <a class="navbar-brand text-muted" style="padding-top: 7px;padding-left: 30px;" href="<?php echo site_url('index/index'); ?>"> <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> @@ -45,8 +45,8 @@ </ul> </div> <div class="collapses navbar-collapses pull-right" id="bs-example-navbar-collapse-1"> - - + + </div> </div> -</nav> \ No newline at end of file +</nav> From a385f342ac93980cc9376e727fc33f6d2a79b45c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 2 Mar 2018 13:53:50 +0800 Subject: [PATCH 036/382] =?UTF-8?q?ipaylinks=20notes=E6=9F=A5=E7=9C=8B?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E8=AF=A6=E6=83=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/iPayLinks_list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 9ffe7de7..ce91c9c7 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -258,7 +258,7 @@ $.ajax({ type: "get", dataType: "json", - url: 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id + '/' + pn_invoice + '/' + noticeTime, + url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id , success: function(data, textStatus) { $('#modal_set_orderid_body').html(data); $('#modal_set_orderid').modal('show'); From 2805a12b461de610bea9db2dd053c10b1e9cb26b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 9 Mar 2018 10:53:37 +0800 Subject: [PATCH 037/382] =?UTF-8?q?paypal=20=E5=AE=9E=E6=94=B6=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E4=BB=A3=E5=8F=B7=E4=BD=BF=E7=94=A815002?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 72aaa8ec..11c0520d 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -783,7 +783,7 @@ class Index extends CI_Controller { $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 @@ -792,7 +792,7 @@ class Index extends CI_Controller { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); + $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15002'); } } //更新还没有填的客邮和交易号de收款记录(传统订单) From bbcd1aae2fc1973dfe178765dde15c52ddf10b5c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 16 Mar 2018 17:51:51 +0800 Subject: [PATCH 038/382] =?UTF-8?q?alipay=20=E4=BA=BA=E6=B0=91=E5=B8=81?= =?UTF-8?q?=E6=94=B6=E6=AC=BE,=20=E5=95=86=E5=8A=A1=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E7=BE=8E=E9=87=91=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 9 +++++++++ webht/third_party/pay/models/Alipay_model.php | 20 ++++++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 4b7aebe4..d04f01b6 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -292,6 +292,11 @@ class AlipayTradeService extends CI_Controller return $result; } + /*! + * 定时执行 + * 处理异步通知: 解析订单号, 邮件外联/客人; 插入付款记录 + * @author LYT <lyt@hainatravel.com> + */ public function send_alipay($pn_txn_id = false) { $data = array(); @@ -369,6 +374,7 @@ class AlipayTradeService extends CI_Controller //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->ALI_currencyCode))); + $USD_amount = $this->Alipay_model->get_USD($item->ALI_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; @@ -387,6 +393,7 @@ class AlipayTradeService extends CI_Controller $item->ALI_orderAmount, $item->ALI_completeTime, $currencyCode, + $USD_amount, $item->ALI_completeTime, $item->ALI_completeTime, $item->ALI_acquiringTime, @@ -698,4 +705,6 @@ var_dump($response->$responseNode); ); } + + } diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 48821bc3..70510309 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -157,7 +157,7 @@ class Alipay_model extends CI_Model { } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -173,6 +173,7 @@ class Alipay_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_Money ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -182,8 +183,8 @@ class Alipay_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -274,4 +275,17 @@ class Alipay_model extends CI_Model { $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); return $query; } + /*! + * 调用数据库函数,转换为美金 + */ + public function get_USD($amount, $currency='RMB') + { + $sql = "SELECT dbo.ConvertCurrencyToCurrency(?,?,?,?) as ssje"; + $query = $this->HT->query($sql, array(1, mb_strtolower($currency), 'usd', $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } } From e0acb71ee27d41211e1c90603a68365cdde1321f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 22 Mar 2018 11:21:24 +0800 Subject: [PATCH 039/382] =?UTF-8?q?paypal=20=E5=AE=9E=E6=94=B6=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E4=BB=A3=E5=8F=B7=E4=BD=BF=E7=94=A815002?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 11c0520d..7d1f3d8b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -789,10 +789,10 @@ class Index extends CI_Controller { $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 } } else { - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15010', mb_strtoupper($item->pn_mc_currency)); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15002'); + $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); } } //更新还没有填的客邮和交易号de收款记录(传统订单) From 4f6f96f0c5baa1cf71d969d98a714009959bb239 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 28 Mar 2018 11:24:37 +0800 Subject: [PATCH 040/382] =?UTF-8?q?ipaylinks=20=E5=AF=B9=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E4=B8=8B=E8=BD=BD,=20=E4=BF=9D=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Crypt/AES.php | 0 .../Crypt/Base.php | 0 .../Crypt/Blowfish.php | 0 .../Crypt/DES.php | 0 .../Crypt/Hash.php | 0 .../Crypt/RC2.php | 0 .../Crypt/RC4.php | 0 .../Crypt/RSA.php | 0 .../Crypt/Random.php | 0 .../Crypt/Rijndael.php | 0 .../Crypt/TripleDES.php | 0 .../Crypt/Twofish.php | 0 .../File/ANSI.php | 0 .../File/ASN1.php | 0 .../File/X509.php | 0 .../Math/BigInteger.php | 0 .../Net/SCP.php | 0 .../Net/SFTP.php | 0 .../Net/SFTP/Stream.php | 0 .../Net/SSH1.php | 0 .../Net/SSH2.php | 0 .../System/SSH/Agent.php | 0 .../System/SSH_Agent.php | 0 .../bootstrap.php | 0 .../download_files.php | 10 +- .../openssl.cnf | 0 webht/third_party/pay/config/paypal.php | 25 ++ .../pay/controllers/iPayLinksService.php | 14 +- webht/third_party/pay/controllers/report.php | 315 ++++++++++++++++++ webht/third_party/pay/models/Report_model.php | 61 ++++ 30 files changed, 418 insertions(+), 7 deletions(-) rename {ipaylinks_statement => download_statement}/Crypt/AES.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Base.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Blowfish.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/DES.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Hash.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/RC2.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/RC4.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/RSA.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Random.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Rijndael.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/TripleDES.php (100%) rename {ipaylinks_statement => download_statement}/Crypt/Twofish.php (100%) rename {ipaylinks_statement => download_statement}/File/ANSI.php (100%) rename {ipaylinks_statement => download_statement}/File/ASN1.php (100%) rename {ipaylinks_statement => download_statement}/File/X509.php (100%) rename {ipaylinks_statement => download_statement}/Math/BigInteger.php (100%) rename {ipaylinks_statement => download_statement}/Net/SCP.php (100%) rename {ipaylinks_statement => download_statement}/Net/SFTP.php (100%) rename {ipaylinks_statement => download_statement}/Net/SFTP/Stream.php (100%) rename {ipaylinks_statement => download_statement}/Net/SSH1.php (100%) rename {ipaylinks_statement => download_statement}/Net/SSH2.php (100%) rename {ipaylinks_statement => download_statement}/System/SSH/Agent.php (100%) rename {ipaylinks_statement => download_statement}/System/SSH_Agent.php (100%) rename {ipaylinks_statement => download_statement}/bootstrap.php (100%) rename {ipaylinks_statement => download_statement}/download_files.php (59%) rename {ipaylinks_statement => download_statement}/openssl.cnf (100%) create mode 100644 webht/third_party/pay/config/paypal.php create mode 100644 webht/third_party/pay/controllers/report.php create mode 100644 webht/third_party/pay/models/Report_model.php diff --git a/ipaylinks_statement/Crypt/AES.php b/download_statement/Crypt/AES.php similarity index 100% rename from ipaylinks_statement/Crypt/AES.php rename to download_statement/Crypt/AES.php diff --git a/ipaylinks_statement/Crypt/Base.php b/download_statement/Crypt/Base.php similarity index 100% rename from ipaylinks_statement/Crypt/Base.php rename to download_statement/Crypt/Base.php diff --git a/ipaylinks_statement/Crypt/Blowfish.php b/download_statement/Crypt/Blowfish.php similarity index 100% rename from ipaylinks_statement/Crypt/Blowfish.php rename to download_statement/Crypt/Blowfish.php diff --git a/ipaylinks_statement/Crypt/DES.php b/download_statement/Crypt/DES.php similarity index 100% rename from ipaylinks_statement/Crypt/DES.php rename to download_statement/Crypt/DES.php diff --git a/ipaylinks_statement/Crypt/Hash.php b/download_statement/Crypt/Hash.php similarity index 100% rename from ipaylinks_statement/Crypt/Hash.php rename to download_statement/Crypt/Hash.php diff --git a/ipaylinks_statement/Crypt/RC2.php b/download_statement/Crypt/RC2.php similarity index 100% rename from ipaylinks_statement/Crypt/RC2.php rename to download_statement/Crypt/RC2.php diff --git a/ipaylinks_statement/Crypt/RC4.php b/download_statement/Crypt/RC4.php similarity index 100% rename from ipaylinks_statement/Crypt/RC4.php rename to download_statement/Crypt/RC4.php diff --git a/ipaylinks_statement/Crypt/RSA.php b/download_statement/Crypt/RSA.php similarity index 100% rename from ipaylinks_statement/Crypt/RSA.php rename to download_statement/Crypt/RSA.php diff --git a/ipaylinks_statement/Crypt/Random.php b/download_statement/Crypt/Random.php similarity index 100% rename from ipaylinks_statement/Crypt/Random.php rename to download_statement/Crypt/Random.php diff --git a/ipaylinks_statement/Crypt/Rijndael.php b/download_statement/Crypt/Rijndael.php similarity index 100% rename from ipaylinks_statement/Crypt/Rijndael.php rename to download_statement/Crypt/Rijndael.php diff --git a/ipaylinks_statement/Crypt/TripleDES.php b/download_statement/Crypt/TripleDES.php similarity index 100% rename from ipaylinks_statement/Crypt/TripleDES.php rename to download_statement/Crypt/TripleDES.php diff --git a/ipaylinks_statement/Crypt/Twofish.php b/download_statement/Crypt/Twofish.php similarity index 100% rename from ipaylinks_statement/Crypt/Twofish.php rename to download_statement/Crypt/Twofish.php diff --git a/ipaylinks_statement/File/ANSI.php b/download_statement/File/ANSI.php similarity index 100% rename from ipaylinks_statement/File/ANSI.php rename to download_statement/File/ANSI.php diff --git a/ipaylinks_statement/File/ASN1.php b/download_statement/File/ASN1.php similarity index 100% rename from ipaylinks_statement/File/ASN1.php rename to download_statement/File/ASN1.php diff --git a/ipaylinks_statement/File/X509.php b/download_statement/File/X509.php similarity index 100% rename from ipaylinks_statement/File/X509.php rename to download_statement/File/X509.php diff --git a/ipaylinks_statement/Math/BigInteger.php b/download_statement/Math/BigInteger.php similarity index 100% rename from ipaylinks_statement/Math/BigInteger.php rename to download_statement/Math/BigInteger.php diff --git a/ipaylinks_statement/Net/SCP.php b/download_statement/Net/SCP.php similarity index 100% rename from ipaylinks_statement/Net/SCP.php rename to download_statement/Net/SCP.php diff --git a/ipaylinks_statement/Net/SFTP.php b/download_statement/Net/SFTP.php similarity index 100% rename from ipaylinks_statement/Net/SFTP.php rename to download_statement/Net/SFTP.php diff --git a/ipaylinks_statement/Net/SFTP/Stream.php b/download_statement/Net/SFTP/Stream.php similarity index 100% rename from ipaylinks_statement/Net/SFTP/Stream.php rename to download_statement/Net/SFTP/Stream.php diff --git a/ipaylinks_statement/Net/SSH1.php b/download_statement/Net/SSH1.php similarity index 100% rename from ipaylinks_statement/Net/SSH1.php rename to download_statement/Net/SSH1.php diff --git a/ipaylinks_statement/Net/SSH2.php b/download_statement/Net/SSH2.php similarity index 100% rename from ipaylinks_statement/Net/SSH2.php rename to download_statement/Net/SSH2.php diff --git a/ipaylinks_statement/System/SSH/Agent.php b/download_statement/System/SSH/Agent.php similarity index 100% rename from ipaylinks_statement/System/SSH/Agent.php rename to download_statement/System/SSH/Agent.php diff --git a/ipaylinks_statement/System/SSH_Agent.php b/download_statement/System/SSH_Agent.php similarity index 100% rename from ipaylinks_statement/System/SSH_Agent.php rename to download_statement/System/SSH_Agent.php diff --git a/ipaylinks_statement/bootstrap.php b/download_statement/bootstrap.php similarity index 100% rename from ipaylinks_statement/bootstrap.php rename to download_statement/bootstrap.php diff --git a/ipaylinks_statement/download_files.php b/download_statement/download_files.php similarity index 59% rename from ipaylinks_statement/download_files.php rename to download_statement/download_files.php index f93850de..69a3f9ef 100644 --- a/ipaylinks_statement/download_files.php +++ b/download_statement/download_files.php @@ -1,16 +1,18 @@ <?php include('Net/SFTP.php'); +set_time_limit(0); + $sftp = new Net_SFTP('106.14.1.181'); if (!$sftp->login('10000004000', 'YRATF0OtDaYa2Uhv6cWO8BV9FPBup5')) { exit('Login Failed'); } // 获取前一天的对账单 // target remote -$target_folder = str_replace("-", "/", date("/Y-m", strtotime("-1 day")) ); +$target_folder = str_replace("-", "/", date("Y-m", strtotime("-1 day")) ); $file_list = array_values(array_diff($sftp->nlist($target_folder), array(".",".."))); // target local -$target_local = "statement_files" . $target_folder; +$target_local = "statement_files/" . $target_folder; if ( ! is_dir($target_local)) { mkdir($target_local, 0777, true); } @@ -26,3 +28,7 @@ foreach ($new_files as $key => $new) { $new_cnt++; } echo "Copied new statements count: " . $new_cnt; + +// header("Location: http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/auto_update_statement?f=$target_folder&fjson=" . json_encode($new_files)); +// header("Location: http://www.mycht.cn/webht.php/apps/pay/report/ipaylinks_excel?f=$target_folder&fjson=" . json_encode($new_files)); +// header("Location: http://202.103.68.79:8083/webht.php/apps/pay/report/ipaylinks_excel?f=$target_folder&fjson=" . json_encode($new_files)); diff --git a/ipaylinks_statement/openssl.cnf b/download_statement/openssl.cnf similarity index 100% rename from ipaylinks_statement/openssl.cnf rename to download_statement/openssl.cnf diff --git a/webht/third_party/pay/config/paypal.php b/webht/third_party/pay/config/paypal.php new file mode 100644 index 00000000..70dcceaa --- /dev/null +++ b/webht/third_party/pay/config/paypal.php @@ -0,0 +1,25 @@ +<?php +// ycc sanbox +// $config['client_id'] = "AVfErlDftQcNj22239jNQmTV-J-rLqBdNf3HZO0-McmElUDxadiF8vAQdeXmZAnB_nKy06ZwFazs1kKU"; +// $config['secret'] = "EJUmlpxrNHkm3Kv4xBd1Qm2_kLGAmAcS8hbYKarYGAvQrDaJT-HrPgx_AEXL12-mt_3EM2KqM_E2eJtt"; +// lyt sandbox +// $config['client_id'] = "AcMk2gic4iPAILnAuJnTQ4ndyz3k35APxNrqtqtG8-stjj7LykAkdPwmMG_AFvopDJCCt0Z-LQawoL9f"; +// $config['secret'] = "EBPs37WgdYMLtrTTRv6usynF4eT-xGuk42VmvjePKxsQU6PfIk9aKe0zF8yIEo02vqP6oqkLWMdtJnU8"; +// ycc live +$config['client_id'] = "Af8wR2_0NnDo3hf8axMkI-5TFd_UccjP4fZzsKz7136pBe6pj69QQIodqYAOjKr0wE-gpAE7Ilo4i_eh"; +$config['secret'] = "EMp7oGhy8wX8pvJHC2Ey0_hnAxl2Oh559mSrbcnAqO526BhgxDR0gauTwYjY99DD7OBw0zeo4CIBWEfx"; + +$config['locale'] = "en_US"; +$config['currency'] = "USD"; + +$config['token_url'] = "https://api.paypal.com/v1/oauth2/token"; +$config['web_profiles_url'] = "https://api.paypal.com/v1/payment-experience/web-profiles/"; +$config['webhooks_url'] = "https://api.paypal.com/v1/notifications/webhooks"; +$config['payment_url'] = "https://api.paypal.com/v1/payments/payment"; +$config['sale_url'] = "https://api.paypal.com/v1/payments/sale"; +$config['activities_url'] = "https://api.paypal.com/v1/activities/activities"; + +$config['return_url'] = "https://www.chinahighlights.com"; +$config['cancel_url'] = "https://www.chinahighlights.com"; + +$config['notify_url'] = "https://www.mycht.cn/webht.php/apps/paypal/index/paypal_note"; diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 16855b9f..c36d6051 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -263,11 +263,12 @@ class IPayLinksService extends CI_Controller $this->query_info_arr["orderId"] = $orderid; $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); - $this->query_info_arr["mode"] = 2; + $this->query_info_arr["mode"] = 1; $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); - echo $resp; + // echo $resp; + var_export($resp); return; } @@ -1056,11 +1057,14 @@ class IPayLinksService extends CI_Controller public function auto_update_statement() { - $target_folder = date("Y-m", strtotime("-1 day")); - $target_folder = str_replace("-", "\\", $target_folder); + set_time_limit(0); + // $target_folder = date("Y-m", strtotime("-1 day")); + // $target_folder = str_replace("-", "\\", $target_folder); $today_time = strtotime(date('Ymd000000')); // 解析excel - $statement_folder = FCPATH.'ipaylinks_statement\statement_files\\' . $target_folder; + $target_folder = $this->input->get_post("f"); + $files = json_decode($this->input->get_post("fjson")); + $statement_folder = FCPATH.'download_statement\statement_files\\' . $target_folder; if ( ! is_dir($statement_folder)) { return; } diff --git a/webht/third_party/pay/controllers/report.php b/webht/third_party/pay/controllers/report.php new file mode 100644 index 00000000..98ed7b3b --- /dev/null +++ b/webht/third_party/pay/controllers/report.php @@ -0,0 +1,315 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class Report extends CI_Controller +{ + public $gatewayUrl; + + // cht + public function __construct(){ + parent::__construct(); + $this->config->load('paypal'); + $this->load->helper('payment_helper'); + $this->load->model('Report_model'); + } + + /*! + * 差集: 对账单 > HT收款记录 + * @author LYT <lyt@hainatravel.com> + * @date 2018-03-26 + * @param POST 时间区间 + */ + public function unstore_statement($begin_m=NULL, $end_m=NULL) + { + } + + /*! + * 转换字符集编码 + * @param $data + * @param $targetCharset + * @return string + */ + protected function characet($data, $targetCharset) { + if (!empty($data)) { + $fileType = "UTF-8"; + if (strcasecmp($fileType, $targetCharset) != 0) { + $data = mb_convert_encoding($data, $targetCharset, $fileType); + // $data = iconv($fileType, $targetCharset.'//IGNORE', $data); + } + } + return $data; + } + + /*! + * 检验非空 + * @author LYT <lyt@hainatravel.com> + * @date 2017-08-17 + * @param [type] $value [description] + * @return boolean true-空;false-非空 + */ + protected function checkEmpty($value) { + if (!isset($value)) + return true; + if ($value === null) + return true; + if (trim($value) === "") + return true; + + return false; + } + + protected function create_guid() { + return strtolower(md5(uniqid(mt_rand(), true))); + } + + /*! + * 解析ipaylinks对账单excel, 存入数据库 + * @author LYT <lyt@hainatravel.com> + * @date 2018-03-26 + * @param POST f={target_folder}&fjson={files_list_JSON} + */ + public function ipaylinks_excel() + { + $this->load->model('IPayLinks_model'); + set_time_limit(0); + // 解析excel + $target_folder = $this->input->get_post("f"); + $files = json_decode($this->input->get_post("fjson")); + log_message('error','ipaylinks excel POST: ' . $target_folder . $this->input->get_post("fjson")); + $statement_folder = FCPATH.'download_statement\statement_files\\' . $target_folder; + if ( ! is_dir($statement_folder)) { + return; + } + $files = $files ? $files : array_values(array_diff(scandir($statement_folder), array('.', '..'))); + if (empty($files)) { + echo "none excel."; + return; + } + $settle_cnt = 0; + $update_cnt = 0; + $file_path_output = ""; + bcscale(4); + foreach ($files as $k => $fe) { + $file_path = $statement_folder . '\\' . $fe; + if ( ! file_exists($file_path)) { + continue; + } + $settlement_record = $this->read_ipaylinks_excel($file_path); + if (empty($settlement_record)) { + continue; + } + foreach ($settlement_record as $settle) { + $orderid_info = analysis_orderid(trim($settle['orderid'])); + $orderid_info = json_decode($orderid_info); + if ( ! empty($orderid_info)) { + if (strcasecmp($orderid_info->ordertype, "B") === 0) { + $old_info = $this->IPayLinks_model->get_money_b(trim($settle['pn_invoice'])); + } else if (strcasecmp($orderid_info->ordertype, "T") === 0){ + $old_info = $this->IPayLinks_model->get_money_t(trim($settle['pn_invoice'])); + } + } + $warrant["PR_AccreditNo"] = trim($settle['pn_invoice']); + $warrant["PR_payType"] = 15018; + $warrant["PR_entryCurrency"] = trim($settle['entry_currency']); + $warrant["PR_entryAmount"] = bcadd(floatval($settle['entry_security']), floatval($settle['entry_basic'])); + $warrant["PR_COLI_SN"] = !empty($old_info) ? $old_info[0]->GAI_COLI_SN : NULL; + $warrant["PR_currency"] = trim($settle['currency']); + $warrant["PR_amount"] = trim($settle['order_amount']); + $warrant["PR_orderType"] = $orderid_info ? $orderid_info->ordertype : NULL; + $warrant["PR_fee"] = bcadd(trim($settle['service_fee']), trim($settle['transaction_fee'])); + $warrant["PR_paymentTime"] = trim($settle['complete_date']); + $warrant["PR_dealType"] = trim($settle['data_type']); + $warrant["PR_orderId"] = trim($settle['orderid']); + $warrant["PR_rate"] = trim($settle['settlement_rate']); + $warrant["PR_status"] = ""; + $warrant["PR_buyerName"] = ""; + $warrant["PR_buyerEmail"] = ""; + $this->Report_model->new_report($warrant); + $warrant = NULL; + $update_cnt++; + } + $settlement_record = null; // reset + $settle_cnt++; + $file_path_output .= "\r\n" . $file_path; + } + $result = "read ipaylinks reports result: " . date('Y-m-d H:i:s') . " ------ \r\n"; + $result .= "Found $settle_cnt Excels; Store $update_cnt records;" . $file_path_output; + log_message('error', $result); + echo $result; + return; + } + + public function read_ipaylinks_excel($filePath) + { + $tarr1=array(); + $this->load->library('PHPExcel'); + $PHPExcel = new PHPExcel(); + /**默认用excel2007读取excel,若格式不对,则用之前的版本进行读取*/ + $PHPReader = new PHPExcel_Reader_Excel2007(); + if(!$PHPReader->canRead($filePath)){ + $PHPReader = new PHPExcel_Reader_Excel5(); + if(!$PHPReader->canRead($filePath)){ + echo 'no Excel'; + return ; + } + } + $PHPExcel = $PHPReader->load($filePath); + /**读取excel文件中的第一个工作表*/ + $currentSheet = $PHPExcel->getSheet(0); + + /**取得最大的列号*/ + $allColumn = $currentSheet->getHighestColumn(); + + /**取得一共有多少行*/ + $allRow = $currentSheet->getHighestRow(); + $col_titles = $this->ipaylinks_col_title(); + /**从第二行开始输出,因为excel表中第一行为列名*/ + for($currentRow = 2;$currentRow <= $allRow;$currentRow++){ + $row_tmp = array(); + /**从第A列开始输出*/ + for($currentColumn= 'A';$currentColumn<= "N"; $currentColumn++){ + /**ord()将字符转为十进制数*/ + $val = trim($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue()); + $col_mean = $col_titles[$currentColumn]; + if($col_mean == 'data_type' && in_array($val, $this->noStore_dealType()) ) // strcasecmp('清算', $val) !== 0 + { + break; + } + if ($col_mean == 'orderid' && strcasecmp('-', $val) === 0) { + break; + } + $row_tmp[$col_mean] = $val; + } + if (isset($row_tmp['settlement_amount'])) { + $tarr1[] = $row_tmp; + } + } + return $tarr1; + } + public function ipaylinks_col_title() + { + return array( + "A" => "complete_date", + "B" => "pn_invoice", + "C" => "orderid", + "D" => "data_type", + "E" => "currency", + "F" => "order_amount", + "G" => "settlement_rate", + "H" => "settlement_amount", + "I" => "service_fee", + "J" => "transaction_fee", + "K" => "mark_memo", + "L" => "entry_currency", + "M" => "entry_security", + "N" => "entry_basic" + ); + } + public function noStore_dealType() + { + return array( + "归还保证金" + ,"记账" + ,"冻结" + ,"解冻" + ,"提现" + ,"提现手续费" + ); + } + + public function paypal_get_token() + { + $header = array( + "Accept: application/json", + "Accept-Language: en_US", + ); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HTTPHEADER, $header); + curl_setopt($ch, CURLOPT_URL, $this->config->item('token_url')); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_SSLVERSION, 6); + + $clientId = $this->config->item('client_id'); + $secret = $this->config->item('secret'); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_USERPWD, $clientId . ":" . $secret); + curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials"); + + $reponse = curl_exec($ch); + + if (curl_errno($ch)) { + log_message('error', "paypal token curl error code: ".curl_error($ch)); + } else { + $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (200 !== $httpStatusCode) { + log_message('error', "paypal token Request html Status Code: ".$httpStatusCode); + } + } + curl_close($ch); + + return json_decode($reponse); + } + + public function paypal_get_payment($payment_id) + { + // $url = $this->config->item("payment_url") . "/" . $payment_id; + // $url = $this->config->item("sale_url") . "/" . $payment_id; + $url = $this->config->item("activities_url") . "?page_size=50&sort_by=create_time&sort_order=desc&start_time=2018-03-25T11:00:00Z&end_time=2018-03-28T11:00:00Z"; + $c = $this->call_paypal($url); + var_dump($c); + return $c; + } + + public function call_paypal($url, $body = false) + { + $token_info = $this->paypal_get_token();var_dump($token_info); + // todo if no token + $access_token = $token_info->access_token; + $token_type = $token_info->token_type; + $header = array( + "Content-Type:application/json", + "Authorization: $token_type $access_token" + ); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_HTTPHEADER, $header); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + // curl_setopt($ch, CURLOPT_SSLVERSION, 6); + // CURL_SSLVERSION_TLSv1_2 Available since PHP 5.5.19 and 5.6.3 + + $param_str = ""; + if (is_array($body) && 0 < count($body)) { + $param_str = $this->toJSON($body); + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $param_str); + } + + $reponse = curl_exec($ch); + + if (curl_errno($ch)) { + log_message('error', "paypal curl REST API error code: " . curl_error($ch) . "; post: ".$param_str); + } else { + $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (200 !== $httpStatusCode) { + log_message('error', "paypal REST API Request html Status Code: ".$httpStatusCode); + } + } + curl_close($ch); + + return json_decode($reponse); + } + public function toJSON($arr, $options = 0) + { + if (version_compare(phpversion(), '5.4.0', '>=') === true) { + return json_encode($arr, $options | 64); + } + return str_replace('\\/', '/', json_encode($arr, $options)); // ~ php 5.3 + } + +} diff --git a/webht/third_party/pay/models/Report_model.php b/webht/third_party/pay/models/Report_model.php new file mode 100644 index 00000000..6f221bfa --- /dev/null +++ b/webht/third_party/pay/models/Report_model.php @@ -0,0 +1,61 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class Report_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->INFO = $this->load->database('INFO', TRUE); + } + + /** 插入对账单记录 */ + public function new_report($warrant_arr = array()) + { + $sql = "INSERT INTO PaymentReports + ( + PR_payType + ,PR_orderType + ,PR_COLI_SN + ,PR_orderId + ,PR_dealType + ,PR_AccreditNo + ,PR_currency + ,PR_amount + ,PR_rate + ,PR_entryCurrency + ,PR_entryAmount + ,PR_fee + ,PR_status + ,PR_buyerName + ,PR_buyerEmail + ,PR_paymentTime + ,PR_time + ) + VALUES + (?,?,?,?,N?,?,?,?,?,?,?,?,N?,N?,N?,? + ,GETDATE() + )"; + $query = $this->INFO->query($sql,array( + $warrant_arr["PR_payType"] + ,$warrant_arr["PR_orderType"] + ,$warrant_arr["PR_COLI_SN"] + ,$warrant_arr["PR_orderId"] + ,$warrant_arr["PR_dealType"] + ,$warrant_arr["PR_AccreditNo"] + ,$warrant_arr["PR_currency"] + ,$warrant_arr["PR_amount"] + ,$warrant_arr["PR_rate"] + ,$warrant_arr["PR_entryCurrency"] + ,$warrant_arr["PR_entryAmount"] + ,$warrant_arr["PR_fee"] + ,$warrant_arr["PR_status"] + ,$warrant_arr["PR_buyerName"] + ,$warrant_arr["PR_buyerEmail"] + ,$warrant_arr["PR_paymentTime"] + )); + return $query; + } + +} From 8a6b4ba1d85210529db02f8835edd69f3758a643 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 28 Mar 2018 12:43:28 +0800 Subject: [PATCH 041/382] =?UTF-8?q?ipaylinks=20=E5=AF=B9=E8=B4=A6=E5=8D=95?= =?UTF-8?q?excel?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/report.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/webht/third_party/pay/controllers/report.php b/webht/third_party/pay/controllers/report.php index 98ed7b3b..95d8df37 100644 --- a/webht/third_party/pay/controllers/report.php +++ b/webht/third_party/pay/controllers/report.php @@ -92,6 +92,9 @@ class Report extends CI_Controller $file_path_output = ""; bcscale(4); foreach ($files as $k => $fe) { + if ( ! in_array(strrchr($fe, '.'), array(".xlsx", ".xls"))) { + continue; + } $file_path = $statement_folder . '\\' . $fe; if ( ! file_exists($file_path)) { continue; From 3d293d802a63e52c8979ea81e859ba64e376b48a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 28 Mar 2018 18:31:54 +0800 Subject: [PATCH 042/382] =?UTF-8?q?ipaylinks=20excel=E5=AF=BC=E5=87=BA?= =?UTF-8?q?=E6=B2=A1=E6=9C=89=E4=BA=A4=E6=98=93=E5=8F=B7=E7=9A=84;=20HT?= =?UTF-8?q?=E4=B8=AD=E6=9F=A5=E8=AF=A2=E4=B8=8D=E5=88=B0=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/report.php | 97 ++++++++++++++++++- webht/third_party/pay/models/Report_model.php | 72 ++++++++++++++ 2 files changed, 168 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/report.php b/webht/third_party/pay/controllers/report.php index 95d8df37..6464075c 100644 --- a/webht/third_party/pay/controllers/report.php +++ b/webht/third_party/pay/controllers/report.php @@ -16,13 +16,108 @@ class Report extends CI_Controller } /*! - * 差集: 对账单 > HT收款记录 + * 差集: * @author LYT <lyt@hainatravel.com> * @date 2018-03-26 * @param POST 时间区间 */ public function unstore_statement($begin_m=NULL, $end_m=NULL) { + /*! 对账单 > HT收款记录 */ + $ret = $this->Report_model->ipaylinks_abnormal_in_HT(); + $no_dealId = $this->Report_model->HT_no_dealId(); + if (empty($ret) && empty($no_dealId)) { + echo "Not Found records."; + return; + } + $this->load->library('PHPExcel'); + $objPHPExcel = new PHPExcel(); + $objPHPExcel->setActiveSheetIndex(0); + //set width + $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); + $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15); + $objPHPExcel->getActiveSheet()->getColumnDimension('k')->setWidth(30); + $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20); + // 对齐 + $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + $objPHPExcel->getActiveSheet()->getStyle('G')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + $objPHPExcel->getActiveSheet()->getStyle('I')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + $objPHPExcel->getActiveSheet()->getStyle('J')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + + /** HT中没有找到相应交易号的记录, 对账单中存在 */ + $objPHPExcel->getActiveSheet() + ->SetCellValue('A1', 'HT中没有找到相应交易号的记录, 对账单中存在'); + // 表标题行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A2', '#') + ->SetCellValue('B2', '渠道') + ->SetCellValue('C2', '对账类型') + ->SetCellValue('D2', '订单号') + ->SetCellValue('E2', '申请币种') + ->SetCellValue('F2', '申请金额') + ->SetCellValue('G2', '清算汇率') + ->SetCellValue('H2', '入账币种') + ->SetCellValue('I2', '入账金额') + ->SetCellValue('J2', '手续费') + ->SetCellValue('K2', '交易号') + ->SetCellValue('L2', '交易日期') + ->SetCellValue('M2', '备注'); + $rowCount = 3; + foreach ($ret as $key => $row) { + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, ($rowCount-1)) + ->setCellValueExplicit('B'.$rowCount, "iPaylinks",PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('C'.$rowCount, $row->PR_dealType,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('D'.$rowCount, $row->PR_orderId,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('E'.$rowCount, $row->PR_currency,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('F'.$rowCount, number_format($row->PR_amount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('G'.$rowCount, number_format($row->PR_rate, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('H'.$rowCount, $row->PR_entryCurrency,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('I'.$rowCount, number_format($row->PR_entryAmount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('J'.$rowCount, number_format($row->PR_fee, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('K'.$rowCount, $row->PR_AccreditNo,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('L'.$rowCount, $row->PR_paymentTime); + $rowCount++; + } + $rowCount++; // 隔一行 + + /** HT手动录入的 */ + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, 'HT系统中缺少交易号的,手动录入的') + ->SetCellValue('M'.$rowCount, '备注'); + $rowCount++; + foreach ($no_dealId as $key2 => $row2) { + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, ($key2+1)) + ->setCellValueExplicit('B'.$rowCount, "iPaylinks",PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('C'.$rowCount, "",PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('D'.$rowCount, $row2->COLI_ID,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('E'.$rowCount, $row2->GAI_SQJECurrency,PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('F'.$rowCount, number_format($row2->GAI_SQJE, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('G'.$rowCount, number_format($row2->PR_rate, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('H'.$rowCount, $row2->PR_entryCurrency,PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('I'.$rowCount, number_format($row2->PR_entryAmount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('J'.$rowCount, number_format($row2->PR_fee, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + // ->setCellValueExplicit('K'.$rowCount, $row2->PR_AccreditNo,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('L'.$rowCount, $row2->GAI_AccountDate) + ->SetCellValue('M'.$rowCount, $row2->GAI_Memo); + $rowCount++; + } + + $filename = "export_ipaylinks_abnormal_" . date('Y-m-d'); + header('Content-Type: application/vnd.ms-excel'); + header('Content-Disposition: attachment;filename="' . $filename . '.xls"'); + header('Cache-Control: max-age=0'); + $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); + $objWriter->save('php://output'); } /*! diff --git a/webht/third_party/pay/models/Report_model.php b/webht/third_party/pay/models/Report_model.php index 6f221bfa..30efa3ad 100644 --- a/webht/third_party/pay/models/Report_model.php +++ b/webht/third_party/pay/models/Report_model.php @@ -58,4 +58,76 @@ class Report_model extends CI_Model { return $query; } + /*! + * 在ipaylinks对账单中, 未找到对应的HT订单记录 + * * 金额不相等(包括退款后金额不等) + * * HT中没有自动录入的收款记录, 收款记录被删除或没有成功录入(需要查询问题) + * @author LYT <lyt@hainatravel.com> + * @date 2018-03-28 + * @return [type] [description] + */ + public function ipaylinks_abnormal_in_HT() + { + $sql = "SELECT PR.* + FROM [InfoManager].[dbo].[PaymentReports] pr + WHERE pr.PR_dealType='清算' and PR_payType='15018' + EXCEPT + SELECT PR.* + FROM [InfoManager].[dbo].[PaymentReports] pr + INNER JOIN Tourmanager.dbo.BIZ_GroupAccountInfo bgai ON bgai.GAI_COLI_ID=pr.PR_orderId + AND pr.PR_dealType='清算' + INNER JOIN Tourmanager.dbo.BIZ_ConfirmLineInfo bcoli ON bcoli.COLI_SN=bgai.GAI_COLI_SN + AND bcoli.COLI_Department = 16 WHERE PR_amount=bgai.GAI_SQJE and PR_payType='15018' + AND GAI_SQJECurrency=PR_currency + EXCEPT + SELECT PR.* + FROM Tourmanager.dbo.GroupAccountInfo gai + INNER JOIN Tourmanager.dbo.ConfirmLineInfo coli ON coli.COLI_SN=gai.GAI_COLI_SN + AND coli.COLI_Department <> 16 + INNER JOIN [InfoManager].[dbo].[PaymentReports] pr ON gai.GAI_AccreditNo=pr.PR_AccreditNo WHERE pr.PR_dealType='清算' + AND PR_amount = gai.GAI_SQJE and PR_payType='15018' + EXCEPT + SELECT PR.* + FROM Tourmanager.dbo.BIZ_GroupAccountInfo bgai + INNER JOIN Tourmanager.dbo.BIZ_ConfirmLineInfo bcoli ON bcoli.COLI_SN=bgai.GAI_COLI_SN + AND bcoli.COLI_Department <> 16 + INNER JOIN [InfoManager].[dbo].[PaymentReports] pr ON bgai.GAI_AccreditNo=pr.PR_AccreditNo WHERE pr.PR_dealType='清算' + AND PR_amount = bgai.GAI_SQJE and PR_payType='15018' + ORDER BY PR_paymentTime asc "; + $query = $this->INFO->query($sql); + return $query->result(); + } + + public function HT_no_dealId() + { + $sql = "SELECT GAI_Type,Bgai1.GAI_SQJECurrency,GAI_SQJE, + Bgai1.GAI_Memo , + '商务--B' AS orderType, + bcoli.COLI_SN, + bcoli.COLI_ID AS COLI_ID, + Bgai1.GAI_AccountDate + FROM Tourmanager.dbo.BIZ_GroupAccountInfo Bgai1 + INNER JOIN Tourmanager.dbo.BIZ_ConfirmLineInfo bcoli ON bgai1.GAI_COLI_SN=bcoli.COLI_SN + WHERE Bgai1.GAI_Type IN ('15018') + AND Bgai1.GAI_AccreditNo IS NULL + AND Bgai1.GAI_SQJE > 0 + AND bcoli.COLI_Department <> 16 + UNION + SELECT GAI_Type,gai1.GAI_SQJECurrency,GAI_SQJE, + gai1.GAI_Memo , + '传统--T' AS orderType, + coli.COLI_SN, + coli.COLI_ID AS COLI_ID, + gai1.GAI_AccountDate + FROM Tourmanager.dbo.GroupAccountInfo gai1 + INNER JOIN Tourmanager.dbo.ConfirmLineInfo coli ON gai1.GAI_COLI_SN=coli.COLI_SN + WHERE gai1.GAI_Type IN ('15018') + AND gai1.GAI_AccreditNo IS NULL + AND gai1.GAI_SQJE > 0 + AND coli.COLI_Department <> 16 + ORDER BY GAI_AccountDate "; + $query = $this->INFO->query($sql); + return $query->result(); + } + } From 523b773bba1759d968c0f82dfce21f6a6596cb9b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 29 Mar 2018 16:42:12 +0800 Subject: [PATCH 043/382] =?UTF-8?q?paypal=20=E5=AF=B9=E8=B4=A6=E5=8D=95?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E4=BF=9D=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + webht/third_party/pay/config/paypal.php | 7 +- .../pay/controllers/iPayLinksService.php | 1 + webht/third_party/pay/controllers/report.php | 121 ++++++++++++++++-- 4 files changed, 119 insertions(+), 11 deletions(-) diff --git a/.gitignore b/.gitignore index a8e80dfb..c9c1fc39 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ /kcfinder/cache/* */cache/* */statement_files/* +*/paypal_activities/* diff --git a/webht/third_party/pay/config/paypal.php b/webht/third_party/pay/config/paypal.php index 70dcceaa..335d05d8 100644 --- a/webht/third_party/pay/config/paypal.php +++ b/webht/third_party/pay/config/paypal.php @@ -15,9 +15,10 @@ $config['currency'] = "USD"; $config['token_url'] = "https://api.paypal.com/v1/oauth2/token"; $config['web_profiles_url'] = "https://api.paypal.com/v1/payment-experience/web-profiles/"; $config['webhooks_url'] = "https://api.paypal.com/v1/notifications/webhooks"; -$config['payment_url'] = "https://api.paypal.com/v1/payments/payment"; -$config['sale_url'] = "https://api.paypal.com/v1/payments/sale"; -$config['activities_url'] = "https://api.paypal.com/v1/activities/activities"; +$config['payment_url'] = "https://api.paypal.com/v1/payments/payment/"; +$config['sale_url'] = "https://api.paypal.com/v1/payments/sale/"; +// $config['activities_url'] = "https://api.paypal.com/v1/activities/activities"; +// $config['reporting_url'] = "https://api.paypal.com/v1/reporting/transactions"; $config['return_url'] = "https://www.chinahighlights.com"; $config['cancel_url'] = "https://www.chinahighlights.com"; diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index c36d6051..14ce9fcf 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -596,6 +596,7 @@ class IPayLinksService extends CI_Controller $resp_arr = $resp; } else { $resp_arr = $this->input->post(); + log_message('error','iPayLinks asyn notify: ' . $this->input->post("orderId")); } $asyns_resp = $this->verify_sign($resp_arr); // 未得到结果 diff --git a/webht/third_party/pay/controllers/report.php b/webht/third_party/pay/controllers/report.php index 6464075c..2a99cc1b 100644 --- a/webht/third_party/pay/controllers/report.php +++ b/webht/third_party/pay/controllers/report.php @@ -271,7 +271,7 @@ class Report extends CI_Controller /**ord()将字符转为十进制数*/ $val = trim($currentSheet->getCellByColumnAndRow(ord($currentColumn) - 65,$currentRow)->getValue()); $col_mean = $col_titles[$currentColumn]; - if($col_mean == 'data_type' && in_array($val, $this->noStore_dealType()) ) // strcasecmp('清算', $val) !== 0 + if($col_mean == 'data_type' && in_array($val, $this->ipaylinks_noStore_dealType()) ) // strcasecmp('清算', $val) !== 0 { break; } @@ -305,7 +305,7 @@ class Report extends CI_Controller "N" => "entry_basic" ); } - public function noStore_dealType() + public function ipaylinks_noStore_dealType() { return array( "归还保证金" @@ -317,6 +317,112 @@ class Report extends CI_Controller ); } + public function paypal_excel() + { + // $this->load->model('IPayLinks_model'); + set_time_limit(0); + // 解析excel + $target_folder = $this->input->get_post("f"); + $files = json_decode($this->input->get_post("fjson")); + log_message('error','paypal excel POST: ' . $target_folder . $this->input->get_post("fjson")); + $statement_folder = FCPATH.'download_statement\paypal_activities\\' . $target_folder; + if ( ! is_dir($statement_folder)) { + return; + } + $files = $files ? $files : array_values(array_diff(scandir($statement_folder), array('.', '..'))); + if (empty($files)) { + echo "none excel."; + return; + } + $settle_cnt = 0; + $update_cnt = 0; + $file_path_output = ""; + bcscale(4); + foreach ($files as $k => $fe) { + if ( ! in_array(strrchr($fe, '.'), array(".xlsx", ".xls"))) { + continue; + } + $file_path = $statement_folder . '\\' . $fe; + if ( ! file_exists($file_path)) { + continue; + } + $settlement_record = $this->paypal_read_excel($file_path); + if (empty($settlement_record)) { + continue; + } + var_dump($settlement_record); + foreach ($settlement_record as $settle) { + $orderid_info = analysis_orderid(trim($settle['Invoice Number'])); // todo + $orderid_info = json_decode($orderid_info); + if ( ! empty($orderid_info)) { + if (strcasecmp($orderid_info->ordertype, "B") === 0) { + // $old_info = $this->IPayLinks_model->get_money_b(trim($settle['Transaction ID'])); + } else if (strcasecmp($orderid_info->ordertype, "T") === 0){ + // $old_info = $this->IPayLinks_model->get_money_t(trim($settle['Transaction ID'])); + } + } + $warrant["PR_AccreditNo"] = trim($settle['Transaction ID']); + $warrant["PR_payType"] = 15002; + $warrant["PR_entryCurrency"] = trim($settle['Currency']); + $warrant["PR_entryAmount"] = number_format(trim($settle['Net']), 2, ".", ""); + $warrant["PR_COLI_SN"] = !empty($old_info) ? $old_info[0]->GAI_COLI_SN : NULL; + $warrant["PR_currency"] = trim($settle['Currency']); + $warrant["PR_amount"] = number_format(trim($settle['Gross']), 2, ".", ""); + $warrant["PR_orderType"] = $orderid_info ? $orderid_info->ordertype : NULL; + $warrant["PR_fee"] = number_format(trim($settle['Fee']), 2, ".", ""); + $warrant["PR_paymentTime"] = trim($settle['Date']) . " " . trim($settle['Time']); + $warrant["PR_dealType"] = trim($settle['Type']); + $warrant["PR_orderId"] = trim($settle['Invoice Number']); // todo + $warrant["PR_rate"] = "1.00"; + $warrant["PR_status"] = trim($settle['Status']); + $warrant["PR_buyerName"] = trim($settle['Name']); + $warrant["PR_buyerEmail"] = trim($settle['From Email Address']); + $this->Report_model->new_report($warrant); + $warrant = NULL; + $update_cnt++; + } + $settlement_record = NULL; + } + echo $update_cnt; + } + + + public function paypal_read_excel($filePath) + { + $tarr1=array(); + $this->load->library('PHPExcel'); + $PHPExcel = new PHPExcel(); + $PHPReader = new PHPExcel_Reader_Excel2007(); + if(!$PHPReader->canRead($filePath)){ + $PHPReader = new PHPExcel_Reader_Excel5(); + if(!$PHPReader->canRead($filePath)){ + echo 'no Excel'; + return ; + } + } + $PHPExcel = $PHPReader->load($filePath); + /**读取excel文件中的第一个工作表*/ + $currentSheet = $PHPExcel->getSheet(0); + + foreach($currentSheet->getRowIterator() as $key1 => $row) + { + $row_tmp = array(); + foreach($row->getCellIterator() as $key => $cell) + { + if ($key1 === 1) { + $col_titles[] = $cell->getCalculatedValue(); + } elseif ($key === 1) { + $row_tmp[$col_titles[$key]] = PHPExcel_Style_NumberFormat::toFormattedString($cell->getCalculatedValue(), 'H:i:s'); + } else { + $row_tmp[$col_titles[$key]] = $cell->getCalculatedValue(); + } + } + $row_tmp ? $tarr1[] = $row_tmp : NULL; + } + + return $tarr1; + } + public function paypal_get_token() { $header = array( @@ -352,19 +458,18 @@ class Report extends CI_Controller return json_decode($reponse); } - public function paypal_get_payment($payment_id) + public function paypal_get_payment($payment_id=NULL) { - // $url = $this->config->item("payment_url") . "/" . $payment_id; - // $url = $this->config->item("sale_url") . "/" . $payment_id; - $url = $this->config->item("activities_url") . "?page_size=50&sort_by=create_time&sort_order=desc&start_time=2018-03-25T11:00:00Z&end_time=2018-03-28T11:00:00Z"; + $url = $this->config->item("payment_url") . "?start_time=2018-03-28T11:00:00Z&end_time=2018-03-30T11:00:00Z"; + // $url = $this->config->item("sale_url") . $payment_id; $c = $this->call_paypal($url); - var_dump($c); + echo (json_encode($c)); return $c; } public function call_paypal($url, $body = false) { - $token_info = $this->paypal_get_token();var_dump($token_info); + $token_info = $this->paypal_get_token(); // todo if no token $access_token = $token_info->access_token; $token_type = $token_info->token_type; From 1f583d2f3d78942f86b63d3317b0bdc043dd7c0a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 16 Apr 2018 18:13:51 +0800 Subject: [PATCH 044/382] =?UTF-8?q?trippest=20=E8=AE=A2=E5=8D=95=E5=90=8C?= =?UTF-8?q?=E6=AD=A5:=20=E8=8E=B7=E5=8F=96=E5=9B=BE=E5=85=B0=E6=9C=B5?= =?UTF-8?q?=E7=B3=BB=E7=BB=9F=E8=AE=A2=E5=8D=95=E5=AD=98=E5=85=A5HT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/.htaccess | 1 + .../trippestOrderSync/config/autoload.php | 116 ++ .../trippestOrderSync/config/config.php | 364 ++++ .../trippestOrderSync/config/constants.php | 41 + .../trippestOrderSync/config/database.php | 53 + .../trippestOrderSync/config/doctypes.php | 15 + .../config/foreign_chars.php | 64 + .../trippestOrderSync/config/hooks.php | 16 + .../trippestOrderSync/config/index.html | 10 + .../trippestOrderSync/config/migration.php | 41 + .../trippestOrderSync/config/mimes.php | 106 ++ .../trippestOrderSync/config/profiler.php | 17 + .../trippestOrderSync/config/routes.php | 46 + .../trippestOrderSync/config/smileys.php | 66 + .../trippestOrderSync/config/user_agents.php | 178 ++ .../controllers/TulanduoApi.php | 499 ++++++ .../trippestOrderSync/controllers/index.html | 10 + .../trippestOrderSync/controllers/welcome.php | 27 + .../helpers/array_helper.php | 92 + .../trippestOrderSync/helpers/index.html | 10 + .../third_party/trippestOrderSync/index.html | 10 + .../trippestOrderSync/libraries/index.html | 10 + .../trippestOrderSync/logs/index.html | 10 + .../trippestOrderSync/logs/log-2018-03-22.php | 2 + .../trippestOrderSync/logs/log-2018-03-30.php | 118 ++ .../trippestOrderSync/logs/log-2018-04-02.php | 106 ++ .../trippestOrderSync/logs/log-2018-04-03.php | 676 +++++++ .../trippestOrderSync/logs/log-2018-04-04.php | 260 +++ .../trippestOrderSync/logs/log-2018-04-08.php | 163 ++ .../trippestOrderSync/logs/log-2018-04-09.php | 201 +++ .../trippestOrderSync/logs/log-2018-04-10.php | 2 + .../trippestOrderSync/logs/log-2018-04-13.php | 76 + .../trippestOrderSync/logs/log-2018-04-15.php | 72 + .../trippestOrderSync/logs/log-2018-04-16.php | 81 + ...uo_addOrUpdateRouteOrderContentBuilder.php | 334 ++++ .../models/TuLanDuo_queryContentBuilder.php | 131 ++ .../trippestOrderSync/models/index.html | 10 + .../trippestOrderSync/models/orders_model.php | 1546 +++++++++++++++++ .../trippestOrderSync/views/index.html | 10 + .../views/welcome_message.php | 88 + 40 files changed, 5678 insertions(+) create mode 100644 webht/third_party/trippestOrderSync/.htaccess create mode 100644 webht/third_party/trippestOrderSync/config/autoload.php create mode 100644 webht/third_party/trippestOrderSync/config/config.php create mode 100644 webht/third_party/trippestOrderSync/config/constants.php create mode 100644 webht/third_party/trippestOrderSync/config/database.php create mode 100644 webht/third_party/trippestOrderSync/config/doctypes.php create mode 100644 webht/third_party/trippestOrderSync/config/foreign_chars.php create mode 100644 webht/third_party/trippestOrderSync/config/hooks.php create mode 100644 webht/third_party/trippestOrderSync/config/index.html create mode 100644 webht/third_party/trippestOrderSync/config/migration.php create mode 100644 webht/third_party/trippestOrderSync/config/mimes.php create mode 100644 webht/third_party/trippestOrderSync/config/profiler.php create mode 100644 webht/third_party/trippestOrderSync/config/routes.php create mode 100644 webht/third_party/trippestOrderSync/config/smileys.php create mode 100644 webht/third_party/trippestOrderSync/config/user_agents.php create mode 100644 webht/third_party/trippestOrderSync/controllers/TulanduoApi.php create mode 100644 webht/third_party/trippestOrderSync/controllers/index.html create mode 100644 webht/third_party/trippestOrderSync/controllers/welcome.php create mode 100644 webht/third_party/trippestOrderSync/helpers/array_helper.php create mode 100644 webht/third_party/trippestOrderSync/helpers/index.html create mode 100644 webht/third_party/trippestOrderSync/index.html create mode 100644 webht/third_party/trippestOrderSync/libraries/index.html create mode 100644 webht/third_party/trippestOrderSync/logs/index.html create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-03-22.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-03-30.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-02.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-03.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-04.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-08.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-09.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-10.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-13.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-15.php create mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-16.php create mode 100644 webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php create mode 100644 webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php create mode 100644 webht/third_party/trippestOrderSync/models/index.html create mode 100644 webht/third_party/trippestOrderSync/models/orders_model.php create mode 100644 webht/third_party/trippestOrderSync/views/index.html create mode 100644 webht/third_party/trippestOrderSync/views/welcome_message.php diff --git a/webht/third_party/trippestOrderSync/.htaccess b/webht/third_party/trippestOrderSync/.htaccess new file mode 100644 index 00000000..14249c50 --- /dev/null +++ b/webht/third_party/trippestOrderSync/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/autoload.php b/webht/third_party/trippestOrderSync/config/autoload.php new file mode 100644 index 00000000..53129c9c --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/autoload.php @@ -0,0 +1,116 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| AUTO-LOADER +| ------------------------------------------------------------------- +| This file specifies which systems should be loaded by default. +| +| In order to keep the framework as light-weight as possible only the +| absolute minimal resources are loaded by default. For example, +| the database is not connected to automatically since no assumption +| is made regarding whether you intend to use it. This file lets +| you globally define which systems you would like loaded with every +| request. +| +| ------------------------------------------------------------------- +| Instructions +| ------------------------------------------------------------------- +| +| These are the things you can load automatically: +| +| 1. Packages +| 2. Libraries +| 3. Helper files +| 4. Custom config files +| 5. Language files +| 6. Models +| +*/ + +/* +| ------------------------------------------------------------------- +| Auto-load Packges +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); +| +*/ + +$autoload['packages'] = array(); + + +/* +| ------------------------------------------------------------------- +| Auto-load Libraries +| ------------------------------------------------------------------- +| These are the classes located in the system/libraries folder +| or in your application/libraries folder. +| +| Prototype: +| +| $autoload['libraries'] = array('database', 'session', 'xmlrpc'); +*/ + +$autoload['libraries'] = array(); + + +/* +| ------------------------------------------------------------------- +| Auto-load Helper Files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['helper'] = array('url', 'file'); +*/ + +$autoload['helper'] = array(); + + +/* +| ------------------------------------------------------------------- +| Auto-load Config files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['config'] = array('config1', 'config2'); +| +| NOTE: This item is intended for use ONLY if you have created custom +| config files. Otherwise, leave it blank. +| +*/ + +$autoload['config'] = array(); + + +/* +| ------------------------------------------------------------------- +| Auto-load Language files +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['language'] = array('lang1', 'lang2'); +| +| NOTE: Do not include the "_lang" part of your file. For example +| "codeigniter_lang.php" would be referenced as array('codeigniter'); +| +*/ + +$autoload['language'] = array(); + + +/* +| ------------------------------------------------------------------- +| Auto-load Models +| ------------------------------------------------------------------- +| Prototype: +| +| $autoload['model'] = array('model1', 'model2'); +| +*/ + +$autoload['model'] = array(); + + +/* End of file autoload.php */ +/* Location: ./application/config/autoload.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/config.php b/webht/third_party/trippestOrderSync/config/config.php new file mode 100644 index 00000000..d7ea3540 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/config.php @@ -0,0 +1,364 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +/* +|-------------------------------------------------------------------------- +| Base Site URL +|-------------------------------------------------------------------------- +| +| URL to your CodeIgniter root. Typically this will be your base URL, +| WITH a trailing slash: +| +| http://example.com/ +| +| If this is not set then CodeIgniter will try to guess the protocol, domain +| and path to your installation. However, you should always configure this +| explicitly and never rely on auto-guessing, especially in production +| environments. +| +*/ +$config['base_url'] = ''; + +/* +|-------------------------------------------------------------------------- +| Index File +|-------------------------------------------------------------------------- +| +| Typically this will be your index.php file, unless you've renamed it to +| something else. If you are using mod_rewrite to remove the page set this +| variable so that it is blank. +| +*/ +$config['index_page'] = 'index.php'; + +/* +|-------------------------------------------------------------------------- +| URI PROTOCOL +|-------------------------------------------------------------------------- +| +| This item determines which server global should be used to retrieve the +| URI string. The default setting of 'AUTO' works for most servers. +| If your links do not seem to work, try one of the other delicious flavors: +| +| 'AUTO' Default - auto detects +| 'PATH_INFO' Uses the PATH_INFO +| 'QUERY_STRING' Uses the QUERY_STRING +| 'REQUEST_URI' Uses the REQUEST_URI +| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO +| +*/ +$config['uri_protocol'] = 'PATH_INFO'; + +/* +|-------------------------------------------------------------------------- +| URL suffix +|-------------------------------------------------------------------------- +| +| This option allows you to add a suffix to all URLs generated by CodeIgniter. +| For more information please see the user guide: +| +| http://codeigniter.com/user_guide/general/urls.html +*/ + +$config['url_suffix'] = ''; + +/* +|-------------------------------------------------------------------------- +| Default Language +|-------------------------------------------------------------------------- +| +| This determines which set of language files should be used. Make sure +| there is an available translation if you intend to use something other +| than english. +| +*/ +$config['language'] = 'english'; + +/* +|-------------------------------------------------------------------------- +| Default Character Set +|-------------------------------------------------------------------------- +| +| This determines which character set is used by default in various methods +| that require a character set to be provided. +| +*/ +$config['charset'] = 'UTF-8'; + +/* +|-------------------------------------------------------------------------- +| Enable/Disable System Hooks +|-------------------------------------------------------------------------- +| +| If you would like to use the 'hooks' feature you must enable it by +| setting this variable to TRUE (boolean). See the user guide for details. +| +*/ +$config['enable_hooks'] = FALSE; + + +/* +|-------------------------------------------------------------------------- +| Class Extension Prefix +|-------------------------------------------------------------------------- +| +| This item allows you to set the filename/classname prefix when extending +| native libraries. For more information please see the user guide: +| +| http://codeigniter.com/user_guide/general/core_classes.html +| http://codeigniter.com/user_guide/general/creating_libraries.html +| +*/ +$config['subclass_prefix'] = 'MY_'; + + +/* +|-------------------------------------------------------------------------- +| Allowed URL Characters +|-------------------------------------------------------------------------- +| +| This lets you specify with a regular expression which characters are permitted +| within your URLs. When someone tries to submit a URL with disallowed +| characters they will get a warning message. +| +| As a security measure you are STRONGLY encouraged to restrict URLs to +| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- +| +| Leave blank to allow all characters -- but only if you are insane. +| +| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! +| +*/ +$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; + + +/* +|-------------------------------------------------------------------------- +| Enable Query Strings +|-------------------------------------------------------------------------- +| +| By default CodeIgniter uses search-engine friendly segment based URLs: +| example.com/who/what/where/ +| +| By default CodeIgniter enables access to the $_GET array. If for some +| reason you would like to disable it, set 'allow_get_array' to FALSE. +| +| You can optionally enable standard query string based URLs: +| example.com?who=me&what=something&where=here +| +| Options are: TRUE or FALSE (boolean) +| +| The other items let you set the query string 'words' that will +| invoke your controllers and its functions: +| example.com/index.php?c=controller&m=function +| +| Please note that some of the helpers won't work as expected when +| this feature is enabled, since CodeIgniter is designed primarily to +| use segment based URLs. +| +*/ +$config['allow_get_array'] = TRUE; +$config['enable_query_strings'] = FALSE; +$config['controller_trigger'] = 'c'; +$config['function_trigger'] = 'm'; +$config['directory_trigger'] = 'd'; // experimental not currently in use + +/* +|-------------------------------------------------------------------------- +| Error Logging Threshold +|-------------------------------------------------------------------------- +| +| If you have enabled error logging, you can set an error threshold to +| determine what gets logged. Threshold options are: +| You can enable error logging by setting a threshold over zero. The +| threshold determines what gets logged. Threshold options are: +| +| 0 = Disables logging, Error logging TURNED OFF +| 1 = Error Messages (including PHP errors) +| 2 = Debug Messages +| 3 = Informational Messages +| 4 = All Messages +| +| For a live site you'll usually only enable Errors (1) to be logged otherwise +| your log files will fill up very fast. +| +*/ +$config['log_threshold'] = 1; + +/* +|-------------------------------------------------------------------------- +| Error Logging Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| application/logs/ folder. Use a full server path with trailing slash. +| +*/ +$config['log_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Date Format for Logs +|-------------------------------------------------------------------------- +| +| Each item that is logged has an associated date. You can use PHP date +| codes to set your own date formatting +| +*/ +$config['log_date_format'] = 'Y-m-d H:i:s'; + +/* +|-------------------------------------------------------------------------- +| Cache Directory Path +|-------------------------------------------------------------------------- +| +| Leave this BLANK unless you would like to set something other than the default +| system/cache/ folder. Use a full server path with trailing slash. +| +*/ +$config['cache_path'] = ''; + +/* +|-------------------------------------------------------------------------- +| Encryption Key +|-------------------------------------------------------------------------- +| +| If you use the Encryption class or the Session class you +| MUST set an encryption key. See the user guide for info. +| +*/ +$config['encryption_key'] = ''; + +/* +|-------------------------------------------------------------------------- +| Session Variables +|-------------------------------------------------------------------------- +| +| 'sess_cookie_name' = the name you want for the cookie +| 'sess_expiration' = the number of SECONDS you want the session to last. +| by default sessions last 7200 seconds (two hours). Set to zero for no expiration. +| 'sess_expire_on_close' = Whether to cause the session to expire automatically +| when the browser window is closed +| 'sess_encrypt_cookie' = Whether to encrypt the cookie +| 'sess_use_database' = Whether to save the session data to a database +| 'sess_table_name' = The name of the session database table +| 'sess_match_ip' = Whether to match the user's IP address when reading the session data +| 'sess_match_useragent' = Whether to match the User Agent when reading the session data +| 'sess_time_to_update' = how many seconds between CI refreshing Session Information +| +*/ +$config['sess_cookie_name'] = 'ci_session'; +$config['sess_expiration'] = 7200; +$config['sess_expire_on_close'] = FALSE; +$config['sess_encrypt_cookie'] = FALSE; +$config['sess_use_database'] = FALSE; +$config['sess_table_name'] = 'ci_sessions'; +$config['sess_match_ip'] = FALSE; +$config['sess_match_useragent'] = TRUE; +$config['sess_time_to_update'] = 300; + +/* +|-------------------------------------------------------------------------- +| Cookie Related Variables +|-------------------------------------------------------------------------- +| +| 'cookie_prefix' = Set a prefix if you need to avoid collisions +| 'cookie_domain' = Set to .your-domain.com for site-wide cookies +| 'cookie_path' = Typically will be a forward slash +| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists. +| +*/ +$config['cookie_prefix'] = ""; +$config['cookie_domain'] = ""; +$config['cookie_path'] = "/"; +$config['cookie_secure'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Global XSS Filtering +|-------------------------------------------------------------------------- +| +| Determines whether the XSS filter is always active when GET, POST or +| COOKIE data is encountered +| +*/ +$config['global_xss_filtering'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Cross Site Request Forgery +|-------------------------------------------------------------------------- +| Enables a CSRF cookie token to be set. When set to TRUE, token will be +| checked on a submitted form. If you are accepting user data, it is strongly +| recommended CSRF protection be enabled. +| +| 'csrf_token_name' = The token name +| 'csrf_cookie_name' = The cookie name +| 'csrf_expire' = The number in seconds the token should expire. +*/ +$config['csrf_protection'] = FALSE; +$config['csrf_token_name'] = 'csrf_test_name'; +$config['csrf_cookie_name'] = 'csrf_cookie_name'; +$config['csrf_expire'] = 7200; + +/* +|-------------------------------------------------------------------------- +| Output Compression +|-------------------------------------------------------------------------- +| +| Enables Gzip output compression for faster page loads. When enabled, +| the output class will test whether your server supports Gzip. +| Even if it does, however, not all browsers support compression +| so enable only if you are reasonably sure your visitors can handle it. +| +| VERY IMPORTANT: If you are getting a blank page when compression is enabled it +| means you are prematurely outputting something to your browser. It could +| even be a line of whitespace at the end of one of your scripts. For +| compression to work, nothing can be sent before the output buffer is called +| by the output class. Do not 'echo' any values with compression enabled. +| +*/ +$config['compress_output'] = FALSE; + +/* +|-------------------------------------------------------------------------- +| Master Time Reference +|-------------------------------------------------------------------------- +| +| Options are 'local' or 'gmt'. This pref tells the system whether to use +| your server's local time as the master 'now' reference, or convert it to +| GMT. See the 'date helper' page of the user guide for information +| regarding date handling. +| +*/ +$config['time_reference'] = 'local'; + + +/* +|-------------------------------------------------------------------------- +| Rewrite PHP Short Tags +|-------------------------------------------------------------------------- +| +| If your PHP installation does not have short tag support enabled CI +| can rewrite the tags on-the-fly, enabling you to utilize that syntax +| in your view files. Options are TRUE or FALSE (boolean) +| +*/ +$config['rewrite_short_tags'] = FALSE; + + +/* +|-------------------------------------------------------------------------- +| Reverse Proxy IPs +|-------------------------------------------------------------------------- +| +| If your server is behind a reverse proxy, you must whitelist the proxy IP +| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR +| header in order to properly identify the visitor's IP address. +| Comma-delimited, e.g. '10.0.1.200,10.0.1.201' +| +*/ +$config['proxy_ips'] = ''; + + +/* End of file config.php */ +/* Location: ./application/config/config.php */ diff --git a/webht/third_party/trippestOrderSync/config/constants.php b/webht/third_party/trippestOrderSync/config/constants.php new file mode 100644 index 00000000..4a879d36 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/constants.php @@ -0,0 +1,41 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +/* +|-------------------------------------------------------------------------- +| File and Directory Modes +|-------------------------------------------------------------------------- +| +| These prefs are used when checking and setting modes when working +| with the file system. The defaults are fine on servers with proper +| security, but you may wish (or even need) to change the values in +| certain environments (Apache running a separate process for each +| user, PHP under CGI with Apache suEXEC, etc.). Octal values should +| always be used to set the mode correctly. +| +*/ +define('FILE_READ_MODE', 0644); +define('FILE_WRITE_MODE', 0666); +define('DIR_READ_MODE', 0755); +define('DIR_WRITE_MODE', 0777); + +/* +|-------------------------------------------------------------------------- +| File Stream Modes +|-------------------------------------------------------------------------- +| +| These modes are used when working with fopen()/popen() +| +*/ + +define('FOPEN_READ', 'rb'); +define('FOPEN_READ_WRITE', 'r+b'); +define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care +define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care +define('FOPEN_WRITE_CREATE', 'ab'); +define('FOPEN_READ_WRITE_CREATE', 'a+b'); +define('FOPEN_WRITE_CREATE_STRICT', 'xb'); +define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); + + +/* End of file constants.php */ +/* Location: ./application/config/constants.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/database.php b/webht/third_party/trippestOrderSync/config/database.php new file mode 100644 index 00000000..70f54273 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/database.php @@ -0,0 +1,53 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| DATABASE CONNECTIVITY SETTINGS +| ------------------------------------------------------------------- +| This file will contain the settings needed to access your database. +| +| For complete instructions please consult the 'Database Connection' +| page of the User Guide. +| +| ------------------------------------------------------------------- +| EXPLANATION OF VARIABLES +| ------------------------------------------------------------------- +| +| ['hostname'] The hostname of your database server. +| ['username'] The username used to connect to the database +| ['password'] The password used to connect to the database +| ['database'] The name of the database you want to connect to +| ['dbdriver'] The database type. ie: mysql. Currently supported: + mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 +| ['dbprefix'] You can add an optional prefix, which will be added +| to the table name when using the Active Record class +| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection +| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. +| ['cache_on'] TRUE/FALSE - Enables/disables query caching +| ['cachedir'] The path to the folder where cache files should be stored +| ['char_set'] The character set used in communicating with the database +| ['dbcollat'] The character collation used in communicating with the database +| NOTE: For MySQL and MySQLi databases, this setting is only used +| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 +| (and in table creation queries made with DB Forge). +| There is an incompatibility in PHP with mysql_real_escape_string() which +| can make your site vulnerable to SQL injection if you are using a +| multi-byte character set and are running versions lower than these. +| Sites using Latin-1 or UTF-8 database character set and collation are unaffected. +| ['swap_pre'] A default table prefix that should be swapped with the dbprefix +| ['autoinit'] Whether or not to automatically initialize the database. +| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections +| - good for ensuring strict SQL while developing +| +| The $active_group variable lets you choose which connection group to +| make active. By default there is only one group (the 'default' group). +| +| The $active_record variables lets you determine whether or not to load +| the active record class +*/ +$active_group = 'HT'; +$active_record = TRUE; + +require 'c:/database_conn.php'; + +/* End of file database.php */ +/* Location: ./application/config/database.php */ diff --git a/webht/third_party/trippestOrderSync/config/doctypes.php b/webht/third_party/trippestOrderSync/config/doctypes.php new file mode 100644 index 00000000..f7e1d19a --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/doctypes.php @@ -0,0 +1,15 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +$_doctypes = array( + 'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">', + 'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', + 'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', + 'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">', + 'html5' => '<!DOCTYPE html>', + 'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', + 'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">', + 'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">' + ); + +/* End of file doctypes.php */ +/* Location: ./application/config/doctypes.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/foreign_chars.php b/webht/third_party/trippestOrderSync/config/foreign_chars.php new file mode 100644 index 00000000..14b0d737 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/foreign_chars.php @@ -0,0 +1,64 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| Foreign Characters +| ------------------------------------------------------------------- +| This file contains an array of foreign characters for transliteration +| conversion used by the Text helper +| +*/ +$foreign_characters = array( + '/ä|æ|ǽ/' => 'ae', + '/ö|œ/' => 'oe', + '/ü/' => 'ue', + '/Ä/' => 'Ae', + '/Ü/' => 'Ue', + '/Ö/' => 'Oe', + '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', + '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', + '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', + '/ç|ć|ĉ|ċ|č/' => 'c', + '/Ð|Ď|Đ/' => 'D', + '/ð|ď|đ/' => 'd', + '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', + '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', + '/Ĝ|Ğ|Ġ|Ģ/' => 'G', + '/ĝ|ğ|ġ|ģ/' => 'g', + '/Ĥ|Ħ/' => 'H', + '/ĥ|ħ/' => 'h', + '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', + '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', + '/Ĵ/' => 'J', + '/ĵ/' => 'j', + '/Ķ/' => 'K', + '/ķ/' => 'k', + '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', + '/ĺ|ļ|ľ|ŀ|ł/' => 'l', + '/Ñ|Ń|Ņ|Ň/' => 'N', + '/ñ|ń|ņ|ň|ʼn/' => 'n', + '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', + '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', + '/Ŕ|Ŗ|Ř/' => 'R', + '/ŕ|ŗ|ř/' => 'r', + '/Ś|Ŝ|Ş|Š/' => 'S', + '/ś|ŝ|ş|š|ſ/' => 's', + '/Ţ|Ť|Ŧ/' => 'T', + '/ţ|ť|ŧ/' => 't', + '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', + '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', + '/Ý|Ÿ|Ŷ/' => 'Y', + '/ý|ÿ|ŷ/' => 'y', + '/Ŵ/' => 'W', + '/ŵ/' => 'w', + '/Ź|Ż|Ž/' => 'Z', + '/ź|ż|ž/' => 'z', + '/Æ|Ǽ/' => 'AE', + '/ß/'=> 'ss', + '/IJ/' => 'IJ', + '/ij/' => 'ij', + '/Œ/' => 'OE', + '/ƒ/' => 'f' +); + +/* End of file foreign_chars.php */ +/* Location: ./application/config/foreign_chars.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/hooks.php b/webht/third_party/trippestOrderSync/config/hooks.php new file mode 100644 index 00000000..a4ad2be6 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/hooks.php @@ -0,0 +1,16 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------------- +| Hooks +| ------------------------------------------------------------------------- +| This file lets you define "hooks" to extend CI without hacking the core +| files. Please see the user guide for info: +| +| http://codeigniter.com/user_guide/general/hooks.html +| +*/ + + + +/* End of file hooks.php */ +/* Location: ./application/config/hooks.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/index.html b/webht/third_party/trippestOrderSync/config/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/migration.php b/webht/third_party/trippestOrderSync/config/migration.php new file mode 100644 index 00000000..df42a3ca --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/migration.php @@ -0,0 +1,41 @@ +<?php defined('BASEPATH') OR exit('No direct script access allowed'); +/* +|-------------------------------------------------------------------------- +| Enable/Disable Migrations +|-------------------------------------------------------------------------- +| +| Migrations are disabled by default but should be enabled +| whenever you intend to do a schema migration. +| +*/ +$config['migration_enabled'] = FALSE; + + +/* +|-------------------------------------------------------------------------- +| Migrations version +|-------------------------------------------------------------------------- +| +| This is used to set migration version that the file system should be on. +| If you run $this->migration->latest() this is the version that schema will +| be upgraded / downgraded to. +| +*/ +$config['migration_version'] = 0; + + +/* +|-------------------------------------------------------------------------- +| Migrations Path +|-------------------------------------------------------------------------- +| +| Path to your migrations folder. +| Typically, it will be within your application path. +| Also, writing permission is required within the migrations path. +| +*/ +$config['migration_path'] = APPPATH . 'migrations/'; + + +/* End of file migration.php */ +/* Location: ./application/config/migration.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/mimes.php b/webht/third_party/trippestOrderSync/config/mimes.php new file mode 100644 index 00000000..100f7d44 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/mimes.php @@ -0,0 +1,106 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| MIME TYPES +| ------------------------------------------------------------------- +| This file contains an array of mime types. It is used by the +| Upload class to help identify allowed file types. +| +*/ + +$mimes = array( 'hqx' => 'application/mac-binhex40', + 'cpt' => 'application/mac-compactpro', + 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'), + 'bin' => 'application/macbinary', + 'dms' => 'application/octet-stream', + 'lha' => 'application/octet-stream', + 'lzh' => 'application/octet-stream', + 'exe' => array('application/octet-stream', 'application/x-msdownload'), + 'class' => 'application/octet-stream', + 'psd' => 'application/x-photoshop', + 'so' => 'application/octet-stream', + 'sea' => 'application/octet-stream', + 'dll' => 'application/octet-stream', + 'oda' => 'application/oda', + 'pdf' => array('application/pdf', 'application/x-download'), + 'ai' => 'application/postscript', + 'eps' => 'application/postscript', + 'ps' => 'application/postscript', + 'smi' => 'application/smil', + 'smil' => 'application/smil', + 'mif' => 'application/vnd.mif', + 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'), + 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'), + 'wbxml' => 'application/wbxml', + 'wmlc' => 'application/wmlc', + 'dcr' => 'application/x-director', + 'dir' => 'application/x-director', + 'dxr' => 'application/x-director', + 'dvi' => 'application/x-dvi', + 'gtar' => 'application/x-gtar', + 'gz' => 'application/x-gzip', + 'php' => 'application/x-httpd-php', + 'php4' => 'application/x-httpd-php', + 'php3' => 'application/x-httpd-php', + 'phtml' => 'application/x-httpd-php', + 'phps' => 'application/x-httpd-php-source', + 'js' => 'application/x-javascript', + 'swf' => 'application/x-shockwave-flash', + 'sit' => 'application/x-stuffit', + 'tar' => 'application/x-tar', + 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'), + 'xhtml' => 'application/xhtml+xml', + 'xht' => 'application/xhtml+xml', + 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'), + 'mid' => 'audio/midi', + 'midi' => 'audio/midi', + 'mpga' => 'audio/mpeg', + 'mp2' => 'audio/mpeg', + 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'), + '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' => array('audio/x-wav', 'audio/wave', 'audio/wav'), + 'bmp' => array('image/bmp', 'image/x-windows-bmp'), + 'gif' => 'image/gif', + 'jpeg' => array('image/jpeg', 'image/pjpeg'), + 'jpg' => array('image/jpeg', 'image/pjpeg'), + 'jpe' => array('image/jpeg', 'image/pjpeg'), + 'png' => array('image/png', 'image/x-png'), + 'tiff' => 'image/tiff', + 'tif' => 'image/tiff', + 'css' => 'text/css', + 'html' => 'text/html', + 'htm' => 'text/html', + 'shtml' => 'text/html', + 'txt' => 'text/plain', + 'text' => 'text/plain', + 'log' => array('text/plain', 'text/x-log'), + 'rtx' => 'text/richtext', + 'rtf' => 'text/rtf', + 'xml' => 'text/xml', + 'xsl' => 'text/xml', + 'mpeg' => 'video/mpeg', + 'mpg' => 'video/mpeg', + 'mpe' => 'video/mpeg', + 'qt' => 'video/quicktime', + 'mov' => 'video/quicktime', + 'avi' => 'video/x-msvideo', + 'movie' => 'video/x-sgi-movie', + 'doc' => 'application/msword', + 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'), + 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'), + 'word' => array('application/msword', 'application/octet-stream'), + 'xl' => 'application/excel', + 'eml' => 'message/rfc822', + 'json' => array('application/json', 'text/json') + ); + + +/* End of file mimes.php */ +/* Location: ./application/config/mimes.php */ diff --git a/webht/third_party/trippestOrderSync/config/profiler.php b/webht/third_party/trippestOrderSync/config/profiler.php new file mode 100644 index 00000000..f8a5b1a1 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/profiler.php @@ -0,0 +1,17 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------------- +| Profiler Sections +| ------------------------------------------------------------------------- +| This file lets you determine whether or not various sections of Profiler +| data are displayed when the Profiler is enabled. +| Please see the user guide for info: +| +| http://codeigniter.com/user_guide/general/profiling.html +| +*/ + + + +/* End of file profiler.php */ +/* Location: ./application/config/profiler.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/routes.php b/webht/third_party/trippestOrderSync/config/routes.php new file mode 100644 index 00000000..5f9a5834 --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/routes.php @@ -0,0 +1,46 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------------- +| URI ROUTING +| ------------------------------------------------------------------------- +| This file lets you re-map URI requests to specific controller functions. +| +| Typically there is a one-to-one relationship between a URL string +| and its corresponding controller class/method. The segments in a +| URL normally follow this pattern: +| +| example.com/class/method/id/ +| +| In some instances, however, you may want to remap this relationship +| so that a different class/function is called than the one +| corresponding to the URL. +| +| Please see the user guide for complete details: +| +| http://codeigniter.com/user_guide/general/routing.html +| +| ------------------------------------------------------------------------- +| RESERVED ROUTES +| ------------------------------------------------------------------------- +| +| There area two reserved routes: +| +| $route['default_controller'] = 'welcome'; +| +| This route indicates which controller class should be loaded if the +| URI contains no data. In the above example, the "welcome" class +| would be loaded. +| +| $route['404_override'] = 'errors/page_missing'; +| +| This route will tell the Router what URI segments to use if those provided +| in the URL cannot be matched to a valid route. +| +*/ + +$route['default_controller'] = "welcome"; +$route['404_override'] = ''; + + +/* End of file routes.php */ +/* Location: ./application/config/routes.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/smileys.php b/webht/third_party/trippestOrderSync/config/smileys.php new file mode 100644 index 00000000..25d28b2c --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/smileys.php @@ -0,0 +1,66 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| SMILEYS +| ------------------------------------------------------------------- +| This file contains an array of smileys for use with the emoticon helper. +| Individual images can be used to replace multiple simileys. For example: +| :-) and :) use the same image replacement. +| +| Please see user guide for more info: +| http://codeigniter.com/user_guide/helpers/smiley_helper.html +| +*/ + +$smileys = array( + +// smiley image name width height alt + + ':-)' => array('grin.gif', '19', '19', 'grin'), + ':lol:' => array('lol.gif', '19', '19', 'LOL'), + ':cheese:' => array('cheese.gif', '19', '19', 'cheese'), + ':)' => array('smile.gif', '19', '19', 'smile'), + ';-)' => array('wink.gif', '19', '19', 'wink'), + ';)' => array('wink.gif', '19', '19', 'wink'), + ':smirk:' => array('smirk.gif', '19', '19', 'smirk'), + ':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'), + ':-S' => array('confused.gif', '19', '19', 'confused'), + ':wow:' => array('surprise.gif', '19', '19', 'surprised'), + ':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'), + ':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'), + '%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'), + ';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'), + ':P' => array('raspberry.gif', '19', '19', 'raspberry'), + ':blank:' => array('blank.gif', '19', '19', 'blank stare'), + ':long:' => array('longface.gif', '19', '19', 'long face'), + ':ohh:' => array('ohh.gif', '19', '19', 'ohh'), + ':grrr:' => array('grrr.gif', '19', '19', 'grrr'), + ':gulp:' => array('gulp.gif', '19', '19', 'gulp'), + '8-/' => array('ohoh.gif', '19', '19', 'oh oh'), + ':down:' => array('downer.gif', '19', '19', 'downer'), + ':red:' => array('embarrassed.gif', '19', '19', 'red face'), + ':sick:' => array('sick.gif', '19', '19', 'sick'), + ':shut:' => array('shuteye.gif', '19', '19', 'shut eye'), + ':-/' => array('hmm.gif', '19', '19', 'hmmm'), + '>:(' => array('mad.gif', '19', '19', 'mad'), + ':mad:' => array('mad.gif', '19', '19', 'mad'), + '>:-(' => array('angry.gif', '19', '19', 'angry'), + ':angry:' => array('angry.gif', '19', '19', 'angry'), + ':zip:' => array('zip.gif', '19', '19', 'zipper'), + ':kiss:' => array('kiss.gif', '19', '19', 'kiss'), + ':ahhh:' => array('shock.gif', '19', '19', 'shock'), + ':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'), + ':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'), + ':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'), + ':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'), + ':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'), + ':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'), + ':vampire:' => array('vampire.gif', '19', '19', 'vampire'), + ':snake:' => array('snake.gif', '19', '19', 'snake'), + ':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'), + ':question:' => array('question.gif', '19', '19', 'question') // no comma after last item + + ); + +/* End of file smileys.php */ +/* Location: ./application/config/smileys.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/user_agents.php b/webht/third_party/trippestOrderSync/config/user_agents.php new file mode 100644 index 00000000..e2d3c3af --- /dev/null +++ b/webht/third_party/trippestOrderSync/config/user_agents.php @@ -0,0 +1,178 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +/* +| ------------------------------------------------------------------- +| USER AGENT TYPES +| ------------------------------------------------------------------- +| This file contains four arrays of user agent data. It is used by the +| User Agent Class to help identify browser, platform, robot, and +| mobile device data. The array keys are used to identify the device +| and the array values are used to set the actual name of the item. +| +*/ + +$platforms = array ( + 'windows nt 6.0' => 'Windows Longhorn', + 'windows nt 5.2' => 'Windows 2003', + 'windows nt 5.0' => 'Windows 2000', + 'windows nt 5.1' => 'Windows XP', + 'windows nt 4.0' => 'Windows NT 4.0', + 'winnt4.0' => 'Windows NT 4.0', + 'winnt 4.0' => 'Windows NT', + 'winnt' => 'Windows NT', + 'windows 98' => 'Windows 98', + 'win98' => 'Windows 98', + 'windows 95' => 'Windows 95', + 'win95' => 'Windows 95', + 'windows' => 'Unknown Windows OS', + 'os x' => 'Mac OS X', + 'ppc mac' => 'Power PC Mac', + 'freebsd' => 'FreeBSD', + 'ppc' => 'Macintosh', + 'linux' => 'Linux', + 'debian' => 'Debian', + 'sunos' => 'Sun Solaris', + 'beos' => 'BeOS', + 'apachebench' => 'ApacheBench', + 'aix' => 'AIX', + 'irix' => 'Irix', + 'osf' => 'DEC OSF', + 'hp-ux' => 'HP-UX', + 'netbsd' => 'NetBSD', + 'bsdi' => 'BSDi', + 'openbsd' => 'OpenBSD', + 'gnu' => 'GNU/Linux', + 'unix' => 'Unknown Unix OS' + ); + + +// The order of this array should NOT be changed. Many browsers return +// multiple browser types so we want to identify the sub-type first. +$browsers = array( + 'Flock' => 'Flock', + 'Chrome' => 'Chrome', + 'Opera' => 'Opera', + 'MSIE' => 'Internet Explorer', + 'Internet Explorer' => 'Internet Explorer', + 'Shiira' => 'Shiira', + 'Firefox' => 'Firefox', + 'Chimera' => 'Chimera', + 'Phoenix' => 'Phoenix', + 'Firebird' => 'Firebird', + 'Camino' => 'Camino', + 'Netscape' => 'Netscape', + 'OmniWeb' => 'OmniWeb', + 'Safari' => 'Safari', + 'Mozilla' => 'Mozilla', + 'Konqueror' => 'Konqueror', + 'icab' => 'iCab', + 'Lynx' => 'Lynx', + 'Links' => 'Links', + 'hotjava' => 'HotJava', + 'amaya' => 'Amaya', + 'IBrowse' => 'IBrowse' + ); + +$mobiles = array( + // legacy array, old values commented out + 'mobileexplorer' => 'Mobile Explorer', +// 'openwave' => 'Open Wave', +// 'opera mini' => 'Opera Mini', +// 'operamini' => 'Opera Mini', +// 'elaine' => 'Palm', + 'palmsource' => 'Palm', +// 'digital paths' => 'Palm', +// 'avantgo' => 'Avantgo', +// 'xiino' => 'Xiino', + 'palmscape' => 'Palmscape', +// 'nokia' => 'Nokia', +// 'ericsson' => 'Ericsson', +// 'blackberry' => 'BlackBerry', +// 'motorola' => 'Motorola' + + // Phones and Manufacturers + 'motorola' => "Motorola", + 'nokia' => "Nokia", + 'palm' => "Palm", + 'iphone' => "Apple iPhone", + 'ipad' => "iPad", + 'ipod' => "Apple iPod Touch", + 'sony' => "Sony Ericsson", + 'ericsson' => "Sony Ericsson", + 'blackberry' => "BlackBerry", + 'cocoon' => "O2 Cocoon", + 'blazer' => "Treo", + 'lg' => "LG", + 'amoi' => "Amoi", + 'xda' => "XDA", + 'mda' => "MDA", + 'vario' => "Vario", + 'htc' => "HTC", + 'samsung' => "Samsung", + 'sharp' => "Sharp", + 'sie-' => "Siemens", + 'alcatel' => "Alcatel", + 'benq' => "BenQ", + 'ipaq' => "HP iPaq", + 'mot-' => "Motorola", + 'playstation portable' => "PlayStation Portable", + 'hiptop' => "Danger Hiptop", + 'nec-' => "NEC", + 'panasonic' => "Panasonic", + 'philips' => "Philips", + 'sagem' => "Sagem", + 'sanyo' => "Sanyo", + 'spv' => "SPV", + 'zte' => "ZTE", + 'sendo' => "Sendo", + + // Operating Systems + 'symbian' => "Symbian", + 'SymbianOS' => "SymbianOS", + 'elaine' => "Palm", + 'palm' => "Palm", + 'series60' => "Symbian S60", + 'windows ce' => "Windows CE", + + // Browsers + 'obigo' => "Obigo", + 'netfront' => "Netfront Browser", + 'openwave' => "Openwave Browser", + 'mobilexplorer' => "Mobile Explorer", + 'operamini' => "Opera Mini", + 'opera mini' => "Opera Mini", + + // Other + 'digital paths' => "Digital Paths", + 'avantgo' => "AvantGo", + 'xiino' => "Xiino", + 'novarra' => "Novarra Transcoder", + 'vodafone' => "Vodafone", + 'docomo' => "NTT DoCoMo", + 'o2' => "O2", + + // Fallback + 'mobile' => "Generic Mobile", + 'wireless' => "Generic Mobile", + 'j2me' => "Generic Mobile", + 'midp' => "Generic Mobile", + 'cldc' => "Generic Mobile", + 'up.link' => "Generic Mobile", + 'up.browser' => "Generic Mobile", + 'smartphone' => "Generic Mobile", + 'cellphone' => "Generic Mobile" + ); + +// There are hundreds of bots but these are the most common. +$robots = array( + 'googlebot' => 'Googlebot', + 'msnbot' => 'MSNBot', + 'slurp' => 'Inktomi Slurp', + 'yahoo' => 'Yahoo', + 'askjeeves' => 'AskJeeves', + 'fastcrawler' => 'FastCrawler', + 'infoseek' => 'InfoSeek Robot 1.0', + 'lycos' => 'Lycos' + ); + +/* End of file user_agents.php */ +/* Location: ./application/config/user_agents.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php new file mode 100644 index 00000000..f52b050f --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -0,0 +1,499 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class TulanduoApi extends CI_Controller +{ + public $special_route = array( + "BJSIC-42" => "'BJSIC-41','BJSIC-42'" + ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" + ); + public $special_route_name = array( + "BJSIC-42" => "北京精品两日游(目的地)" + ,"BJSIC-43" => "北京精品三日游(目的地)" + ); + public $city_info = array( + "北京分公司" => array( + "PlanVEI_SN" => 1343, + "COLI_sourcetype" => 32090, + "routeType" => "北京目的地线路", + "GRI_after" => "BJ" + ), + "西安分公司" => array( + "PlanVEI_SN" => 30548, + "COLI_sourcetype" => 32116, + "routeType" => "西安目的地线路", + "GRI_after" => "XA" + ), + "上海分公司" => array( + "PlanVEI_SN" => 29188, + "COLI_sourcetype" => 32112, + "routeType" => "上海目的地线路", + "GRI_after" => "SH" + ) + ); + + + // test + // public $list_url = "http://djdebug.ltsoftware.net:19919/action/api/searchRouteOrder/"; + // public $detail_url = "http://djdebug.ltsoftware.net:19919/action/api/detailRouteOrder/"; + public $neworder_url = "http://djdebug.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/"; + // Live + public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; + public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; + // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; + + // 发送到图兰朵系统接口的参数jsonParams + public $params; + + public function __construct(){ + parent::__construct(); + $this->load->model('Orders_model'); + $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); + $this->load->helper('array'); + + // $this->output->enable_profiler(TRUE); + + $this->params = new stdClass(); + /** test */ + // $this->userId = "358"; + // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + /** Live */ + // 目的地 + $this->userId = "1134"; + $this->key = "73d180d05d425fd192e1c5b3097e75ff"; + // 桂林海纳国旅 + // $this->userId = "18"; + // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + } + + public function get_orderlist() + { + $this->tld_order->setUserId($this->userId) + ->setKey($this->key) + ->setPageSize(20) + ->setPageIndex(1) + ->setStartTravelDate("2018-04-19") + ->setEndTravelDate("2018-04-19") + // ->setStartOrderDate("2018-04-13") + // ->setEndOrderDate("2018-04-13") + ; + $resp = $this->excute_curl($this->list_url, $this->tld_order); + $resp_arr = json_decode($resp, true); + if ($resp_arr['status'] !== 1) { + log_message('error','TulanduoApi get_orderlist failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . json_encode($this->params)); + return; + } + $all_list = $resp_arr["responseData"]["orders"]; + $order_to_HT = array_map( + function($ele){ + if ( ! in_array($ele['agcName'], array("D目的地桂林组")) ) { + return $ele; + } + },$resp_arr["responseData"]["orders"]); + for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) { + $this->tld_order->setPageIndex($pi); + $f_resp = $this->excute_curl($this->list_url, $this->tld_order); + $f_resp_arr = json_decode($f_resp, true); + if ($resp_arr['status'] !== 1) { + log_message('error','TulanduoApi get_orderlist failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . json_encode($this->params)); + continue; + } + $f_order_to_HT = array_map( + function($ele){ + if ( ! in_array($ele['agcName'], array("D目的地桂林组")) ) { + return $ele; + } + },$f_resp_arr["responseData"]["orders"]); + $order_to_HT = array_filter(array_merge($order_to_HT, $f_order_to_HT)); + $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); + } + foreach ($all_list as $k => $vo) { + $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 + // get order detail + // $this->tld_order->setOrderId($vo["orderId"]); + // $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + // $detail_jsonResp = json_decode($detail_resp); + // if ($detail_jsonResp->status !== 1) { + // log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . json_encode($this->params)); + // return; + // } + $PAG_Code = $pag_sub = null; + preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); + if (empty($temp_array) && isset($this->pag_no_tmp()[$vo['routeName']])) { + // 旧的数据没有线路代号 + $PAG_Code = $pag_sub = $this->pag_no_tmp()[$vo['routeName']]; + $split_code = explode("-", $PAG_Code); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else { + log_message('error','未识别的线路名称 ' . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); + $PAG_Code = $pag_sub = null; + $split_code = explode("-", $temp_array[0]); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } + $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); + $COLD_MemoText = json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); + + $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = null; + if (in_array($vo['agcName'], array("D目的地桂林组"))) { + $tmp_groupCode = explode("-", $vo['agcOrderNo']); + $real_groupCode = $tmp_groupCode[0] . "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $real_groupCode = mb_ereg_replace('(\s| )', '', $real_groupCode); + // set BIZ_COLI_SN, GRI_SN at Orders_model + $this->Orders_model->get_SN_by_groupCode($real_groupCode); + } + /** insert HT */ + if ($this->Orders_model->BIZ_COLI_SN === null) { + // BIZ_Guest + $this->Orders_model->GUT_LastName = $vo['customerName']; + // $this->Orders_model->GUT_Passport = $detail_jsonResp->orderDetail->customers[0]->documentNo; + $this->Orders_model->biz_guest_save(); + // BIZ_ConfirmLineInfo + $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; + $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); + $this->Orders_model->BIZ_COLI_ApplyDate = $vo['orderDate']; + $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$vo['operationDep']]) ? 32090 : $this->city_info[$vo['operationDep']]['COLI_sourcetype']; + $this->Orders_model->BIZ_COLI_State = $vo['orderStatus']==1 ? 7 : 4;; + $this->Orders_model->BIZ_COLI_servicetype = 'D'; + $this->Orders_model->BIZ_COLI_ConfirmType = 52001; + $this->Orders_model->BIZ_COLI_Memo = ""; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName'];//. $allDetails_to_HT; + $this->Orders_model->BIZ_COLI_GroupCode = $vo['agcOrderNo'] ? $vo['agcOrderNo'] : ''; + // $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; + $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; + $coli_sn[] = $this->Orders_model->biz_confirm_save(); + // BIZ_ConfirmLineDetail + $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->COLD_ServiceType = "D"; + $this->Orders_model->COLD_ServiceSN = $serviceSN; + $this->Orders_model->COLD_ServiceSN2 = $pag_sub; + $this->Orders_model->COLD_StartDate = $vo['travelDate']; + $this->Orders_model->COLD_EndDate = $vo['leaveDate']; + $this->Orders_model->COLD_PersonNum = $vo['adultNum']; + $this->Orders_model->COLD_ChildNum = $vo['childNum']; + $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认(已收款) // 4 下计划未确认(已收款) + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; + // $this->Orders_model->COLD_Memo = isset($detail_jsonResp->orderDetail->orderRemark) ? $detail_jsonResp->orderDetail->orderRemark : ''; + $this->Orders_model->COLD_MemoText = $COLD_MemoText; + $this->Orders_model->biz_confirm_detail_save(); + } + // biz_groupcombineinfo + $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; + $this->Orders_model->GCI_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; + $this->Orders_model->GCI_FromAgc = $vo['agcName']; + $this->Orders_model->GCI_groupType = $vo['orderType']; + $this->Orders_model->GCI_travelDate = $vo['travelDate']; + $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; + $this->Orders_model->GCI_createTime = $vo['orderDate']; + $this->Orders_model->biz_groupcombineinfo_save(); + } + return; + } + + public function update_HT_order_operation($coli_sn=null) + { + if ($coli_sn !== null) { + $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); + } else { + $startDate = date('Y-m-d'); + $endDate = date('Y-m-d', strtotime("+1 days")); + // $endDate = date('Y-m-d', strtotime("+4 days")); + $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); + } + foreach ($to_update_list as $key => $order) { + $this->tld_order->setOrderId($order->GCI_VendorOrderId) + ->setUserId($this->userId) + ->setKey($this->key); + $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + $detail_jsonResp = json_decode($detail_resp); + if ($detail_jsonResp->status !== 1) { + log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . json_encode($this->params)); + return; + } + $allDetails_to_HT = "日程: "; + foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { + $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; + } + /** HT 开始 */ + // GRoupInfo todo 写入报错 + if ($order->COLI_GRI_SN == null) { + $travelDate = new DateTime($detail_jsonResp->orderDetail->travelDate); + $leaveDate = new DateTime($detail_jsonResp->orderDetail->leaveDate); + $date_diff = $travelDate->diff($leaveDate); + $this->Orders_model->BIZ_COLI_SN = $order->GCI_COLI_SN; + + $this->Orders_model->GRI_No = $detail_jsonResp->orderDetail->agcOrderNo; + $this->Orders_model->GRI_OrderType = 227002; // 商务 + $this->Orders_model->GRI_Name = ""; + $this->Orders_model->GRI_PersonNum = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; + $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); + $this->Orders_model->GRI_IsCancel = 0; + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->groupinfo_save(); + // update COLI + $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN; + $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_No; + $this->Orders_model->update_confirmLineInfo(); + } + // BIZ_BookPeople + foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { + $this->Orders_model->BPE_FirstName = $vd->name; + $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; + $this->Orders_model->BPE_Passport = $vd->documentNo; + $bpe_sn[] = $this->Orders_model->biz_book_people_save(); + // BIZ_BookPeopleList + $this->Orders_model->biz_bookpeople_List_save($order->COLD_SN, $this->Orders_model->BPE_SN); + } + // BIZ_PackageOrderInfo + $this->Orders_model->POI_COLD_SN = $order->COLD_SN; + $this->Orders_model->POI_Time = $detail_jsonResp->orderDetail->travelDate; + $this->Orders_model->POI_Hotel = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation; + $this->Orders_model->POI_HotelAddress = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationAddress; + $this->Orders_model->POI_HotelPhone = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationTelNo; + $this->Orders_model->POI_EndTime = $detail_jsonResp->orderDetail->leaveDate; + $this->Orders_model->POI_QuotationType = 1; // 1 报价 2 网络支付价 3 促销价 + $this->Orders_model->biz_packageorder_save(); + // BIZ_GroupCombineOperationDetail + // 门票 + if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations) && + empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "sceneryOperations")) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { + $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_operationType = "sceneryOperations"; + $this->Orders_model->GCOD_subType = $vso->type; + $this->Orders_model->GCOD_title = $vso->name; + $this->Orders_model->GCOD_startDate = $vso->useDate; + $this->Orders_model->GCOD_endDate = $vso->useDate; + $this->Orders_model->GCOD_useNum = $vso->useNum; + $this->Orders_model->GCOD_sumMoney = $vso->sumMoney; + $this->Orders_model->GCOD_remark = $vso->remark; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = null; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } + // 用房 + // 用餐 + if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) && + empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "restraurantOperations"))) { + foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { + $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_operationType = "restraurantOperations"; + $this->Orders_model->GCOD_subType = $vro->type; + $this->Orders_model->GCOD_title = $vro->name; + $this->Orders_model->GCOD_startDate = $vro->useDate; + $this->Orders_model->GCOD_endDate = $vro->useDate; + $this->Orders_model->GCOD_useNum = $vro->useNum; + $this->Orders_model->GCOD_sumMoney = $vro->sumMoney; + $this->Orders_model->GCOD_standard = $vro->standard; + $this->Orders_model->GCOD_remark = $vro->remark; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = null; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } + // 用车 + if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) && + empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "touristCarOperations"))) { + foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { + $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_operationType = "touristCarOperations"; + $this->Orders_model->GCOD_subType = $vco->type; + $this->Orders_model->GCOD_title = $vco->name; + $this->Orders_model->GCOD_dutyName = $vco->driver; + $this->Orders_model->GCOD_dutyTel = $vco->driverTel; + $this->Orders_model->GCOD_startDate = $vco->startDate; + $this->Orders_model->GCOD_endDate = $vco->endDate; + $this->Orders_model->GCOD_sumMoney = $vco->sumMoney; + $this->Orders_model->GCOD_carLicense = $vco->carLicense; + $this->Orders_model->GCOD_useNum = 1; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_remark = $vco->remark; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } + // 导游服务 + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) && + empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "guiderOperations"))) { + foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { + $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_operationType = "guiderOperations"; + $this->Orders_model->GCOD_subType = ""; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = $vgo->name; + $this->Orders_model->GCOD_dutyTel = $vgo->mobelPhone; + $this->Orders_model->GCOD_dutyPhoto = isset($vgo->guiderPhoto) ? $vgo->guiderPhoto : ''; + $this->Orders_model->GCOD_startDate = $vgo->startDate; + $this->Orders_model->GCOD_endDate = $vgo->endDate; + $this->Orders_model->GCOD_sumMoney = $vgo->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vgo->remark; + $this->Orders_model->GCOD_useNum = 1; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } + } // end foreach order + echo "Got order from 图兰朵, count: " . count($to_update_list); + } + + public function order_push($COLI_ID='170809390') // test + {exit(); + /** test */ + $this->userId = "358"; + $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); + $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID); + if(empty($orderinfo)) {return;} + $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ; + $guestlist = $this->Orders_model->get_guestlist($COLD_SN_str); + $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str); + $routeName = $this->special_route_name[$scheduleDetails[0]->PAG_Code] ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; + if ($this->special_route[$scheduleDetails[0]->PAG_Code]) { + $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); + } + $travelFees = $this->Orders_model->get_paymentDetails($COLI_ID); + bcscale(4); + $this->tldOrderBuilder->setUserId($this->userId) + ->setKey($this->key) + ->setOrderType(1) + ->setRouteName($routeName) + ->setRouteType("北京目的地线路") // todo + ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode) + ->setAdultNum($orderinfo[0]->COLD_PersonNum) + ->setChildNum($orderinfo[0]->COLD_ChildNum) + ->setDestination("北京") // todo + ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) + ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)); + foreach ($guestlist as $key => $vg) { + $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) + ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) + ->setCustomersDocumentType($key, "Passport No.") + ->setCustomersDocumentNo($key, $vg->BPE_Passport) + ->setCustomersOtherInfo($key, ""); + } + foreach ($scheduleDetails as $ks => $vs) { + $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title) + ->setScheduleDetailsTitle($ks, $vs->PAG2_Name) + // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($ks, 0 ) + ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0) ) + ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0)); + } + foreach ($travelFees as $kf => $vf) { + $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") + ->setTravelFeesMoney($kf, $vf->GAI_SQJE) + ->setTravelFeesNum($kf, 1) + ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE)) + ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) + ->setTravelFeesRemark($kf, $vf->GAI_Memo); + } + $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; + $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; + $this->Orders_model->GCI_VendorOrderId = json_decode($rsp)->responseData->orderId; + $this->Orders_model->biz_groupcombineinfo_save(); + return; + } + + protected function excute_curl($url, $content_builder) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Accept: application/json" + )); + + // $params_str = ($this->characet(json_encode($this->params), "UTF-8")); + $params_str = $content_builder->getBizContent(); + $postBody = array('jsonParams' => $params_str, "notHander" => 1); + + if (is_string($params_str) && 0 < mb_strlen($params_str)) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); + } + + $reponse = curl_exec($ch); + $eval_resp = json_decode($reponse); + +log_message('error', " curl postBodyString: ".json_encode($postBody)); + if (curl_errno($ch) || $eval_resp->status == 0) { + log_message('error', "curl error code: ".curl_error($ch) . $eval_resp->errMsg . "; curl postBodyString: ".json_encode($postBody)); + } else { + $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (200 !== $httpStatusCode) { + log_message('error', "Request html Status Code: ".$httpStatusCode."; curl postBodyString: ".json_encode($postBody)); + } + } + curl_close($ch); + return $reponse; + } + + + /*! + * 转换字符集编码 + * @param $data + * @param $targetCharset + * @return string + */ + protected function characet($data, $targetCharset) { + if (!empty($data)) { + $fileType = "UTF-8"; + if (strcasecmp($fileType, $targetCharset) != 0) { + $data = mb_convert_encoding($data, $targetCharset, $fileType); + // $data = iconv($fileType, $targetCharset.'//IGNORE', $data); + } + } + return $data; + } + + public function pag_no_tmp($routeName='') + { + return array( + "故宫深度一日游(目的地)" => "BJSIC-44" + ,"故宫深度游拼团(目的地)" => "BJSIC-44" + ,"北京精品一日游(目的地)" => "BJSIC-41" + ,"北京精品两日游(目的地)" => "BJSIC-42" + ,"北京精品三日游(目的地)" => "BJSIC-43" + ,"北京精品游D2(目的地)" => "BJSIC-42" + ,"北京精品游D3(目的地)" => "BJSIC-43" + ,"北京单租车服务(目的地)" => "BJALC-209" + ,"北京市内-天津新港大车接送(目的地)" => "BJSIC-16" + ,"天津新港-北京市内大车接送(目的地)" => "BJSIC-16" + ,"箭扣-慕田峪徒步一日游(目的地)" => "BJSIC-45" + ,"箭扣-慕田峪长城徒步拼团(目的地)" => "BJSIC-45" + ,"司马台西-金山岭徒步一日游(目的地)" => "BJSIC-46" + ,"司马台西-金山岭长城徒步拼团(目的地)" => "BJSIC-46" + ,"慕田峪半日游拼团(目的地)" => "BJSIC-47" + ,"古北口长城徒步一日游(目的地)" => "BJSIC-48" + ,"半日游广场故宫拼团(目的地)" => "BJSIC-41" + // ,=> + ,"西安精品一日游(目的地)" => "XASIC-41" + ,"西安精品两日游(目的地)" => "XASIC-42" + ,"西安单租车服务(目的地)" => "XASIC-17" + ,"西安单租车接送服务(目的地)" => "XASIC-17" + ,"西安兵马俑精品一日游(目的地)" => "XASIC-41" + ,"西安兵马俑精品半日游(目的地)" => "XASIC-15" + ,"西安汉阳陵市内精品一日游(目的地)" => "XASIC-42" + // ,=> + ,"上海精品一日游(目的地)" => "SHSIC-41" + ,"上海市内精品一日游(目的地)" => "SHSIC-42" + ,"周庄锦溪精品一日游(目的地)" => "SHSIC-43" + ,"上海单租车(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" + ); + } +} diff --git a/webht/third_party/trippestOrderSync/controllers/index.html b/webht/third_party/trippestOrderSync/controllers/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/controllers/welcome.php b/webht/third_party/trippestOrderSync/controllers/welcome.php new file mode 100644 index 00000000..21bef43d --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/welcome.php @@ -0,0 +1,27 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +class Welcome extends CI_Controller { + + /** + * Index Page for this controller. + * + * Maps to the following URL + * http://example.com/index.php/welcome + * - or - + * http://example.com/index.php/welcome/index + * - or - + * Since this controller is set as the default controller in + * config/routes.php, it's displayed at http://example.com/ + * + * So any other public methods not prefixed with an underscore will + * map to /index.php/welcome/<method_name> + * @see http://codeigniter.com/user_guide/general/urls.html + */ + public function index() + { + $this->load->view('welcome_message'); + } +} + +/* End of file welcome.php */ +/* Location: ./application/controllers/welcome.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php new file mode 100644 index 00000000..1dd8320d --- /dev/null +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -0,0 +1,92 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +function array_unique_fb($array2D) +{ + foreach ($array2D as $v) + { + $v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串 + $temp[] = $v; + } + $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组 + foreach ($temp as $k => $v) + { + $temp[$k] = explode(",",$v); //再将拆开的数组重新组装 + } + return $temp; +} + +function my_array_unique($array, $keep_key_assoc = false) +{ + $duplicate_keys = array(); + $tmp = array(); + + foreach ($array as $key=>$val) + { + // convert objects to arrays, in_array() does not support objects + if (is_object($val)) + $val = (array)$val; + + if (!in_array($val, $tmp)) + $tmp[] = $val; + else + $duplicate_keys[] = $key; + } + + foreach ($duplicate_keys as $key) + unset($array[$key]); + + return $keep_key_assoc ? $array : array_values($array); +} + +//根据URL获取月份 +function getaqiMonth($url){ + $monArr = array('January','February','March','April','May','June','July','August','September','October','November','December'); + $monObj = array( + 'January' => '01', + 'February' => '02', + 'March' => '03', + 'April' => '04', + 'May' => '05' , + 'June' => '06', + 'July' => '07', + 'August' => '08', + 'September' => '09', + 'October' => '10', + 'November' => '11', + 'December' => '12'); + $urlarr = explode("/",$url); + $tmp = $urlarr[(count($urlarr)-1)]; + $tmp = ucfirst(str_ireplace('.htm','',$tmp)); + //$d=strtotime("00:01am ".$tmp." 15 2015"); + if(in_array($tmp,$monArr)){ + return $monObj[$tmp]; + }else{ + return false; + } +} +/* + * 把数组元素组合为字符串 + * $container:用来包含元素的符号 + * $se:分隔符 + * $arr:需要重新组合的数组 + * 例如:$arr=['aaaa','bbbb']; + * my_implode("'",",",$arr);得到 + * 'aaaa','bbbb' + */ +function my_implode($container,$se,$arr) +{ + $str = ""; + if ($arr != '') { + $str = ""; + $tcount = count($arr); + $tcountInt = 0; + foreach ($arr as $i) { + $tcountInt++; + if ($tcount == $tcountInt) { + $str .= $container . $i . $container; + } else { + $str .= $container . $i . $container . $se; + } + } + } + return $str; +} diff --git a/webht/third_party/trippestOrderSync/helpers/index.html b/webht/third_party/trippestOrderSync/helpers/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/helpers/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/index.html b/webht/third_party/trippestOrderSync/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/libraries/index.html b/webht/third_party/trippestOrderSync/libraries/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/libraries/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/logs/index.html b/webht/third_party/trippestOrderSync/logs/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php b/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php new file mode 100644 index 00000000..ebca2fb8 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php @@ -0,0 +1,2 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php b/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php new file mode 100644 index 00000000..47b639be --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php @@ -0,0 +1,118 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-03-30 16:18:22 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]在将 nvarchar 值 'HT080828004' 转换成数据类型 int 时失败。 @:SELECT coli.COLI_ID, + coli.COLI_Department, + cold.COLD_ServiceSN, + cold.COLD_ServiceSN2, + cold.COLD_ServiceCity, + * + FROM BIZ_ConfirmLineInfo coli + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE coli.COLI_ID=170809474 + ORDER BY COLI_ApplyDate DESC +ERROR - 2018-03-30 16:29:57 --> Severity: Warning --> Missing argument 1 for Orders_model::get_guestlist(), called in D:\workspace\trippest\application\controllers\TulanduoApi.php on line 38 and defined D:\workspace\trippest\application\models\orders_model.php 47 +ERROR - 2018-03-30 16:29:57 --> Severity: Notice --> Undefined variable: COLD_SN_str D:\workspace\trippest\application\models\orders_model.php 52 +ERROR - 2018-03-30 16:29:57 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:31:50 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:32:25 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:33:17 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:33:51 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:34:07 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:35:09 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:35:26 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN () +ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 +ERROR - 2018-03-30 16:58:10 --> Severity: 4096 --> Object of class TulanduoApi could not be converted to string D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Object of class TulanduoApi to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Undefined variable: Object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 +ERROR - 2018-03-30 16:58:41 --> Severity: 4096 --> Object of class TulanduoApi could not be converted to string D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Object of class TulanduoApi to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Undefined variable: Object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 +ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 +ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:02:44 --> Severity: Notice --> Undefined property: stdClass::$orderData D:\workspace\trippest\application\controllers\TulanduoApi.php 73 +ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:23:17 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 86 +ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php new file mode 100644 index 00000000..7e38da29 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php @@ -0,0 +1,106 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:40:45 --> curl error code: 出游时间[travelDate]格式有误!; curl postBodyString: {"jsonParams":"{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"orderType\":2,\"routeName\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38\",\"routeType\":\"\\u5317\\u4eac\\u76ee\\u7684\\u5730\\u7ebf\\u8def\",\"agcOrderNo\":\"CHBJ171223-BWM170809474\",\"adultNum\":2,\"childNum\":0,\"destination\":\"\\u5317\\u4eac\",\"travelDate\":\"2017-12-23 00:00:00\",\"leavedDate\":\"2017-12-23 08:00:00\",\"customers\":[{\"name\":\"SHINTAKU\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"523429066\",\"otherInfo\":\"\\u6027\\u522b\"},{\"name\":\"PROMSIRI\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"461694068\",\"otherInfo\":\"\\u6027\\u522b\"}],\"scheduleDetails\":[{\"content\":\"7:30 - 11:00\\uff1a \\u9152\\u5e97\\u63a5\\u5ba2\\u4eba\\uff0c\\u6e38\\u89c8\\u9890\\u548c\\u56ed\\uff1b\\r\\n11:20 \\u2013 11:40\\uff1a\\u53c2\\u89c2\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\uff1b\\r\\n12:00 - 13:00\\uff1a \\u5728\\u5927\\u7897\\u5c45\\u5348\\u9910\\uff1b\\r\\n13:30 - 14:10\\uff1a \\u6e38\\u89c8\\u666f\\u5c71\\u516c\\u56ed\\uff1b\\r\\n14:30 - 16:10\\uff1a \\u6e38\\u89c8\\u5929\\u575b\\uff1b\\r\\n16:30 - 17:30\\uff1a\\u9001\\u9152\\u5e97\\u3002\",\"title\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38 \\uff08\\u7b2c\\u4e8c\\u5929\\uff0c\\u9890\\u548c\\u56ed\\u3001\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\u3001\\u5348\\u9910\\u3001\\u666f\\u5c71\\u3001\\u5929\\u575b\\uff09\",\"breakFirst\":0,\"lunch\":1,\"dinner\":0}]}}","notHander":"1"} +ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:42:51 --> curl error code: 出游时间[travelDate]格式有误!; curl postBodyString: {"jsonParams":"{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"orderType\":2,\"routeName\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38\",\"routeType\":\"\\u5317\\u4eac\\u76ee\\u7684\\u5730\\u7ebf\\u8def\",\"agcOrderNo\":\"CHBJ171223-BWM170809474\",\"adultNum\":2,\"childNum\":0,\"destination\":\"\\u5317\\u4eac\",\"travelDate\":\" 00:00:00\",\"leavedDate\":\" 08:00:00\",\"customers\":[{\"name\":\"SHINTAKU\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"523429066\",\"otherInfo\":\"\\u6027\\u522b\"},{\"name\":\"PROMSIRI\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"461694068\",\"otherInfo\":\"\\u6027\\u522b\"}],\"scheduleDetails\":[{\"content\":\"7:30 - 11:00\\uff1a \\u9152\\u5e97\\u63a5\\u5ba2\\u4eba\\uff0c\\u6e38\\u89c8\\u9890\\u548c\\u56ed\\uff1b\\r\\n11:20 \\u2013 11:40\\uff1a\\u53c2\\u89c2\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\uff1b\\r\\n12:00 - 13:00\\uff1a \\u5728\\u5927\\u7897\\u5c45\\u5348\\u9910\\uff1b\\r\\n13:30 - 14:10\\uff1a \\u6e38\\u89c8\\u666f\\u5c71\\u516c\\u56ed\\uff1b\\r\\n14:30 - 16:10\\uff1a \\u6e38\\u89c8\\u5929\\u575b\\uff1b\\r\\n16:30 - 17:30\\uff1a\\u9001\\u9152\\u5e97\\u3002\",\"title\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38 \\uff08\\u7b2c\\u4e8c\\u5929\\uff0c\\u9890\\u548c\\u56ed\\u3001\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\u3001\\u5348\\u9910\\u3001\\u666f\\u5c71\\u3001\\u5929\\u575b\\uff09\",\"breakFirst\":0,\"lunch\":1,\"dinner\":0}]}}","notHander":"1"} +ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php new file mode 100644 index 00000000..67a4bf46 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php @@ -0,0 +1,676 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:16 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 42 +ERROR - 2018-04-03 13:55:16 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 43 +ERROR - 2018-04-03 13:55:16 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} +ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:44 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 43 +ERROR - 2018-04-03 13:55:44 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 44 +ERROR - 2018-04-03 13:55:44 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} +ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:05 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 44 +ERROR - 2018-04-03 13:56:05 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 45 +ERROR - 2018-04-03 13:56:05 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} +ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:10:41 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:11:02 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:11:02 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT COLI_GroupCode + FROM BIZ_ConfirmLineInfo coli + WHERE coli.COLI_GroupCode IN () +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:00 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:12:00 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 47 +ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:47 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:20:55 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 +ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:15 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 +ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:59 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 +ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:47:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:48:49 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:12 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:53 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:51:12 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:52:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:18 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:55:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:56:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:57:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:58:33 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:58:33 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 60 +ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:15 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:34 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 15:00:15 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:22 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:44:34 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:03:05 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_OriginalText +) +VALUES +( + '180403006', + NULL, + 2, + NULL, + NULL, + 0, + NULL, + NULL, + NULL, + NNULL, + '', + 'D', + 32090, + 52001, + 9, + 30, + '15227461856300', + '62001', + '北京精品两日游(目的地) +', + NULL, + N +ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:04:46 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_OriginalText +) +VALUES +( + '180403012', + NULL, + 2, + NULL, + NULL, + 0, + NULL, + NULL, + '北京精品两日游(目的地) +', + NNULL, + '', + 'D', + 32090, + 52001, + 9, + 30, + '15227462867070', + '62001', + '北京精品两日游(目的地) +', + NULL, + N +ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:06:04 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_OriginalText +) +VALUES +( + '180403018', + NULL, + 2, + NULL, + NULL, + 0, + NULL, + NULL, + '北京精品两日游(目的地) +', + N'', + '', + 'D', + 32090, + 52001, + 9, + 30, + '15227463643910', + '62001', + '北京精品两日游(目的地) +', + NULL, + N +ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:07:11 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_OriginalText +) +VALUES +( + '180403024', + NULL, + 2, + NULL, + NULL, + 0, + NULL, + NULL, + '北京精品两日游(目的地) +', + N'', + '', + 'D', + 32090, + 52001, + 9, + 30, + '15227464314580', + '62001', + '北京精品两日游(目的地) +', + NULL, + N +ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:18:27 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_OriginalText +) +VALUES +( + '180403030', + NULL, + 2, + NULL, + NULL, + NULL, + 0, + NULL, + NULL, + N'北京精品两日游(目的地) +', + '', + '', + 'D', + 32090, + 52001, + 9, + 30, + '15227471078350', + '62001', + '北京精品两日游(目的地) +', + NNULL +) +ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 +ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 +ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php new file mode 100644 index 00000000..2edf3a47 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php @@ -0,0 +1,260 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 +ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:13:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:45:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:45:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:45:57 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,GRI_OrderType) + VALUES (NNULL,NNULL,NULL,NULL,0,NULL) +ERROR - 2018-04-04 10:47:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:47:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:47:02 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,GRI_OrderType) + VALUES (NNULL,NNULL,NULL,NULL,0,NULL) +ERROR - 2018-04-04 10:47:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:47:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:47:52 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]不能将值 NULL 插入列 'DeleteFlag',表 'tourmanager.dbo.GRoupInfo';列不允许有 Null 值。INSERT 失败。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,GRI_OrderType) + VALUES (N'CHBJ170823-BHX170809390-1',N'CHBJ170823-BHX170809390-1',2,1,0,227002) +ERROR - 2018-04-04 10:49:16 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:49:16 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:49:16 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]INSERT 语句中列的数目大于 VALUES 子句中指定的值的数目。VALUES 子句中值的数目必须与 INSERT 语句中指定的列的数目匹配。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N'CHBJ170823-BHX170809390-1',N'CHBJ170823-BHX170809390-1',2,1,0,0) +ERROR - 2018-04-04 10:49:55 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:49:55 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:49:55 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'CHBJ170823' 无效。 @:select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No=CHBJ170823-BHX170809390-1 +ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined property: TulanduoApi::$GRI_SN D:\workspace\trippest\application\controllers\TulanduoApi.php 73 +ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:54:24 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:54:24 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:55:37 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:55:37 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:56:28 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:56:28 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:59:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:59:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:00:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:00:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:07:14 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:07:14 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:09:25 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:09:25 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 57 +ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 59 +ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 73 +ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 57 +ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 59 +ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 73 +ERROR - 2018-04-04 11:16:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined variable: ss D:\workspace\trippest\application\controllers\TulanduoApi.php 82 +ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:13:56 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:13:56 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined variable: today_obj D:\workspace\trippest\application\controllers\TulanduoApi.php 61 +ERROR - 2018-04-04 15:18:00 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:18:00 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:39 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:18:39 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:28:48 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:28:48 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:31:05 --> tag475000826 +ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:32:32 --> tag475000827 +ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:35:21 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]拒绝了对对象 'BIZ_GUEST' (数据库 'Tourmanager',架构 'dbo')的 INSERT 权限。 @:INSERT INTO BIZ_Guest + ( + GUT_FirstName, + GUT_LastName, + GUT_Title, + GUT_Email, + GUT_Email2, + GUT_NationalityID, + GUT_Passport, + GUT_TEL, + GUT_MoveTel, + GUT_AddCode, + GUT_CreateDate + ) +VALUES + ( + N'', + N'Ms. Dana Schwanz', + NULL, + NULL, + NULL, + NULL, + '471756661', + NULL, + NULL, + '15228309213330', + GETDATE() + ) +ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 +ERROR - 2018-04-04 16:43:35 --> tag475000828 +ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php new file mode 100644 index 00000000..e6e505fb --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php @@ -0,0 +1,163 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-08 15:57:06 --> array ( + 0 => 'T180405-BHJ180331588-D2', + 1 => 'T180405-BHJ180331588-D1', + 2 => 'T180412-BHJ180331474', + 3 => 'CHBJ180411-BHJ180331354 ', + 4 => 'CHBJ180416-BHJ180331486', + 5 => 'CHBJ180417-BHJ180331025M (BR-648698597)', + 6 => 'CHBJ180526-BHJ180331450', + 7 => 'CHBJ180405-BHJ180401102', + 8 => 'CHBJ180502-BTM180402019M(BR-648875768 )', + 9 => 'CHBJ180420-BTM180402025M(BR-648943709)', + 10 => 'T180403-BTM180402037M(GYG32384328)', + 11 => 'CHBJ180404-BTM180402102', + 12 => 'CHBJ180405-BTM180402420', + 13 => 'CHBJ180408-BTM180403001M(BR-649017533)', + 14 => 'CHBJ180411-BTM180403025M(BR-649019688)', + 15 => 'CHBJ180404-BTM180402918', + 16 => 'CHBJ180421-BTM180403031M(BR-648429882)', + 17 => 'CHBJ180407-BTM180403049M(BR-649133991)', + 18 => 'CHBJ180427-BTM180402690', + 19 => 'CHBJ180622-BTM180403037M(BR-649040809)', +) +ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_Guest + ( + GUT_FirstName, + GUT_LastName, + GUT_Title, + GUT_Email, + GUT_Email2, + GUT_NationalityID, + GUT_Passport, + GUT_TEL, + GUT_MoveTel, + GUT_AddCode, + GUT_CreateDate + ) +VALUES + ( + N'', + N'LAI TIEN CHIN ', + NULL, + NULL, + NULL, + NULL, + 'A34204892', + NULL, + NULL, + '15231742268330', + GETDATE() + ) +ERROR - 2018-04-08 15:57:06 --> INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N'T180405-BHJ180331588-D2',N'T180405-BHJ180331588-D2',3,1,0,0,227002) +ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_ConfirmLineInfo +( + COLI_ID, + COLI_GUT_SN, + COLI_Area, + COLI_ApplyDate, + COLI_Price, + COLI_Cost, + COLI_Currency, + COLI_TrueCardRate, + COLI_AgencyID, + COLI_OrderDetailText, + COLI_SenderIP, + COLI_WebCode, + COLI_servicetype, + COLI_sourcetype, + COLI_ConfirmType, + COLI_State, + COLI_Department, + COLI_AddCode, + COLI_OrderSource, + COLI_Memo, + COLI_GRI_SN, + COLI_GroupCode, + COLI_OriginalText +) +VALUES +( + '180408012', + NULL, + 2, + '2018-04-01', + NULL, + NULL, + 0, + NULL, + NULL, + N'来自图兰朵系统同步测试 16136西安汉阳陵市内精品一日游(目的地)', + '', + '', + 'D', + 32090, + 52001, + 7, + 30, + '15231742269430', + '62001', + '来自图兰朵系统同步测试 16136西安汉阳陵市内精品一日游(目的地)', + NULL, + N'T180405-BHJ180331588-D2', + N'' +) +ERROR - 2018-04-08 15:57:06 --> tag +ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_ConfirmLineDetail +( + COLD_COLI_SN, + COLD_ServiceType, + COLD_StartDate, + COLD_EndDate, + COLD_TotalCost, + COLD_TotalPrice, + COLD_Count, + COLD_PersonNum, + COLD_ChildNum, + COLD_BabyNum, + cold_state, + DeleteFlag, + COLD_DeliveryCharge, + COLD_AddCode, + COLD_PlanVEI_SN, + COLD_SPFS, + COLD_Memo, + COLD_ServiceSN +) +VALUES +( + NULL, + 'D', + '2018-04-05', + '2018-04-05', + NULL, + NULL, + NULL, + 3, + 0, + NULL, + 7, + 0, + 0, + '15231742269670', + NULL, + NULL, + '西安汉阳陵市内精品一日游(目的地)', + NULL +) +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php new file mode 100644 index 00000000..f2cedb62 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php @@ -0,0 +1,201 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-09 13:50:17 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startOrderDate\":\"2018-04-01\",\"endOrderDate\":\"2018-04-08\"}","notHander":"1"} +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 +ERROR - 2018-04-09 13:50:17 --> ids array ( + 0 => 16136, + 1 => 16137, + 2 => 16139, + 3 => 16140, + 4 => 16141, + 5 => 16142, + 6 => 16143, + 7 => 16152, + 8 => 16158, + 9 => 16160, + 10 => 16161, + 11 => 16164, + 12 => 16188, + 13 => 16189, + 14 => 16190, + 15 => 16192, + 16 => 16199, + 17 => 16200, + 18 => 16201, + 19 => 16202, +) +ERROR - 2018-04-09 13:50:18 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startOrderDate\":\"2018-04-01\",\"endOrderDate\":\"2018-04-08\",\"orderId\":16136}","notHander":"1"} +ERROR - 2018-04-09 13:50:18 --> orderId 16136 +ERROR - 2018-04-09 13:50:18 --> 2018-04-05: 汉阳陵+市内 +用车安排: 西安-瑞风张涛师傅车队; 7座(9座大通)司机: 王师傅(15529080993); [3新加坡,汉阳陵一日游,雁塔假日] +带团导游: 西安王辉Rosa; (13519169439); +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-08\"}","notHander":"1"} +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:51:14 --> ids array ( + 0 => 12433, + 1 => 13087, + 2 => 13144, + 3 => 13284, + 4 => 13386, + 5 => 13458, + 6 => 13466, + 7 => 13608, + 8 => 13622, + 9 => 13667, + 10 => 13679, + 11 => 13765, + 12 => 13783, + 13 => 13875, + 14 => 13921, + 15 => 13937, + 16 => 13938, + 17 => 13964, + 18 => 14041, + 19 => 14042, +) +ERROR - 2018-04-09 13:51:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-08\",\"orderId\":12433}","notHander":"1"} +ERROR - 2018-04-09 13:51:14 --> orderId 12433 +ERROR - 2018-04-09 13:51:14 --> 2018-04-05: 北京精品一日游 +用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品两日游;6人;北京新世界酒店 /北京朝阳悠唐皇冠假日酒店/北京金茂万丽酒店] +带团导游: 北京况怡Tiger; (13693050013); +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 13:54:02 --> 2018-04-08: 北京精品一日游 +2018-04-09: 北京精品两日游(D2) +2018-04-10: 北京精品三日游(D3) +用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品三日游;4人;北京内蒙古大厦 /北京希尔顿逸林酒店 ] +带团导游: 北京孙玲玲Linda(13521990227); +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:00:48 --> 日程: 2018-04-08: 北京精品一日游; 2018-04-09: 北京精品两日游(D2); 2018-04-10: 北京精品三日游(D3); +用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品三日游;4人;北京内蒙古大厦 /北京希尔顿逸林酒店 ] +带团导游: 北京孙玲玲Linda(13521990227); +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 +ERROR - 2018-04-09 14:03:16 --> Severity: Notice --> Undefined property: stdClass::$guiderOperations D:\workspace\trippest\application\controllers\TulanduoApi.php 116 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> Invalid argument supplied for foreach() D:\workspace\trippest\application\controllers\TulanduoApi.php 116 +ERROR - 2018-04-09 14:03:16 --> 日程: 2018-04-01: 单租车接机; +用车安排: 凯美瑞车队-宋师傅13811026411; 5座轿车(京BZ1864/black/5seats/car)司机: Mr.WANG/JianYU 王建宇(13161343885); [单租车接机;2人;北京金隅喜来登酒店;接DL0129(Arr1950@T2);] +带团导游: +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php new file mode 100644 index 00000000..ebca2fb8 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php @@ -0,0 +1,2 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php new file mode 100644 index 00000000..0d476b64 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php @@ -0,0 +1,76 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-13 16:51:57 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:51:59 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:52:00 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:52:01 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:52:02 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} +ERROR - 2018-04-13 16:52:02 --> GRI +ERROR - 2018-04-13 16:52:02 --> COLI475000834 +ERROR - 2018-04-13 16:52:02 --> COLD490000931 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:23 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:54:24 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:54:24 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:54:25 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:54:25 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} +ERROR - 2018-04-13 16:54:25 --> in gri +ERROR - 2018-04-13 16:54:25 --> GRI +ERROR - 2018-04-13 16:54:25 --> COLI475000835 +ERROR - 2018-04-13 16:54:25 --> COLD490000932 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:06 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:56:06 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:56:07 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:56:07 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:56:08 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} +ERROR - 2018-04-13 16:56:08 --> in gri +ERROR - 2018-04-13 16:56:08 --> GRI +ERROR - 2018-04-13 16:56:08 --> COLI475000836 +ERROR - 2018-04-13 16:56:08 --> COLD490000933 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:12 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:57:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:57:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:57:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 16:57:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} +ERROR - 2018-04-13 16:57:14 --> in gri +ERROR - 2018-04-13 16:57:14 --> GRI +ERROR - 2018-04-13 16:57:14 --> COLI475000837 +ERROR - 2018-04-13 16:57:14 --> COLD490000934 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:12 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 17:01:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 17:01:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 17:01:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} +ERROR - 2018-04-13 17:01:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} +ERROR - 2018-04-13 17:01:14 --> in gri +ERROR - 2018-04-13 17:01:14 --> GRI31 +ERROR - 2018-04-13 17:01:14 --> COLI475000838 +ERROR - 2018-04-13 17:01:14 --> COLD490000935 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 +ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php new file mode 100644 index 00000000..af2866f7 --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php @@ -0,0 +1,72 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-15 14:37:11 --> curl postBodyString: { + "jsonParams": "{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"travelFees\":[{\"type\":\"团款\",\"money\":\"756.00\",\"num\":1,\"unit\":\"6.4795\",\"sumMoney\":\"4898.57\",\"remark\":\"交易号(自动录入):17T02847CV281080D\"}],\"replaceCollections\":[],\"replacePays\":[],\"scheduleDetails\":[],\"customers\":[{\"name\":\"ZERVOS JOANNE\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"511460159\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE PETER\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"495326176\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE JOHN\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"526333245\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE BILL\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"480595859\",\"otherInfo\":\"\"}],\"orderType\":1,\"routeName\":\"北京精品两日游(目的地)\",\"routeType\":\"北京目的地线路\",\"agcOrderNo\":\"CHBJ170823-BHX170809390\",\"adultNum\":2,\"childNum\":0,\"destination\":\"北京\",\"travelDate\":\"2017-08-23\",\"leavedDate\":\"2017-08-23\"}}", + "notHander": "1" +} +ERROR - 2018-04-15 16:25:26 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} +ERROR - 2018-04-15 16:25:26 --> TulanduoApi get_orderlist failed. Msg:; Request: {} +ERROR - 2018-04-15 16:25:52 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} +ERROR - 2018-04-15 16:25:52 --> TulanduoApi get_orderlist failed. Msg:; Request: {} +ERROR - 2018-04-15 16:26:47 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} +ERROR - 2018-04-15 16:26:47 --> TulanduoApi get_orderlist failed. Msg:; Request: {} +ERROR - 2018-04-15 16:27:04 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} +ERROR - 2018-04-15 16:27:04 --> in gri +ERROR - 2018-04-15 16:27:04 --> Severity: Notice --> Undefined variable: allDetails_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 184 +ERROR - 2018-04-15 16:27:04 --> COLI_ID 180415156 +ERROR - 2018-04-15 16:30:31 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:30:31 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:30:31 --> in gri +ERROR - 2018-04-15 16:30:31 --> COLI_ID 180415162 +ERROR - 2018-04-15 16:33:09 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:33:10 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:33:10 --> in gri +ERROR - 2018-04-15 16:33:10 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]在 SET 子句中多次指定了列名 'COLD_Memo'。在同一 SET 子句中不得为一个列分配多个值。请修改 SET 子句,以确保一个列仅更新一次。如果 SET 子句更新了某视图的多列,那么列名 'COLD_Memo' 可能会在该视图定义中出现两次。 @:INSERT INTO BIZ_ConfirmLineDetail +( + COLD_COLI_SN, + COLD_ServiceType, + COLD_StartDate, + COLD_EndDate, + COLD_TotalCost, + COLD_TotalPrice, + COLD_Count, + COLD_PersonNum, + COLD_ChildNum, + COLD_BabyNum, + cold_state, + DeleteFlag, + COLD_DeliveryCharge, + COLD_AddCode, + COLD_PlanVEI_SN, + COLD_SPFS, + COLD_Memo, + COLD_Memo, + COLD_ServiceSN +) +VALUES +( + 475000866, + 'D', + '2018-04-12', + '2018-04-13', + NULL, + NULL, + NULL, + 1, + 0, + NULL, + 7, + 0, + 0, + '15237811903740', + 1343, + NULL, + NULL, + '{"Pick up":"7:20 \/ \u5317\u4eac\u4e3d\u82d1\u516c\u5bd3 Lee Garden Service Apartment Beijing","Drop off":"\u5317\u4eac\u4e3d\u82d1\u516c\u5bd3 Lee Garden Service Apartment Beijing"}', + NULL +) +ERROR - 2018-04-15 16:33:10 --> Severity: Warning --> Cannot modify header information - headers already sent by (output started at D:\workspace\trippest\application\controllers\TulanduoApi.php:84) D:\workspace\system\core\Common.php 439 +ERROR - 2018-04-15 16:33:30 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:33:30 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} +ERROR - 2018-04-15 16:33:30 --> in gri +ERROR - 2018-04-15 16:33:31 --> COLI_ID 180415174 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php new file mode 100644 index 00000000..67435b5b --- /dev/null +++ b/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php @@ -0,0 +1,81 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> + +ERROR - 2018-04-16 17:16:36 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13634\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:16:36 --> order 475000954 +ERROR - 2018-04-16 17:16:36 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:IF EXISTS( + SELECT TOP 1 1 + FROM BIZ_ConfirmLineInfo + WHERE COLI_SN=475000954 AND COLI_GRI_SN is NULL + ) + INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N'T180417-BTM180122007M(BR-640151641)',N'',2,1,0,0,227002) +ERROR - 2018-04-16 17:21:20 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13634\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:21:20 --> order 475000954 +ERROR - 2018-04-16 17:21:20 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:IF EXISTS( + SELECT TOP 1 1 + FROM BIZ_ConfirmLineInfo + WHERE COLI_SN=475000954 AND COLI_GRI_SN is NULL + ) + INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N'T180417-BTM180122007M(BR-640151641)',N'',2,1,0,0,227002) +ERROR - 2018-04-16 17:28:21 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-17\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} +ERROR - 2018-04-16 17:28:22 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-17\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} +ERROR - 2018-04-16 17:28:22 --> gci 108 +ERROR - 2018-04-16 17:30:19 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:30:19 --> order 475001062 +ERROR - 2018-04-16 17:30:19 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'N475001062' 无效。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N475001062,N'中华游180413-LILY170824015-CHXAD1','',1,1,0,0) +ERROR - 2018-04-16 17:30:39 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:30:39 --> order 475001062 +ERROR - 2018-04-16 17:30:39 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N'中华游180413-LILY170824015-CHXAD1',N'',1,1,0,0,227002) +ERROR - 2018-04-16 17:46:18 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:46:18 --> order 475001062 +ERROR - 2018-04-16 17:46:19 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'coli' 附近有语法错误。 @:UPDATE BIZ_ConfirmLineInfo coli SET + COLI_GRI_SN=183489, + COLI_GroupCode='中华游180413-LILY170824015-CHXAD1' + WHERE COLI_SN=475001062 + +ERROR - 2018-04-16 17:47:56 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 17:47:56 --> order 475001062 +ERROR - 2018-04-16 17:49:47 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-18\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} +ERROR - 2018-04-16 17:49:48 --> gci 108 +ERROR - 2018-04-16 17:53:34 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-19\",\"endTravelDate\":\"2018-04-19\"}","notHander":"1"} +ERROR - 2018-04-16 17:53:35 --> gci 109 +ERROR - 2018-04-16 18:02:29 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 18:02:30 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 18:02:30 --> Severity: Notice --> Undefined property: stdClass::$touristCarOperations D:\workspace\trippest\application\controllers\TulanduoApi.php 224 +ERROR - 2018-04-16 18:02:30 --> Severity: Warning --> Invalid argument supplied for foreach() D:\workspace\trippest\application\controllers\TulanduoApi.php 224 +ERROR - 2018-04-16 18:02:30 --> Severity: Notice --> Undefined property: TulanduoApi::$query D:\workspace\system\core\Model.php 51 +ERROR - 2018-04-16 18:04:40 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 18:04:40 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 18:05:08 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} +ERROR - 2018-04-16 18:05:09 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} diff --git a/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php b/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php new file mode 100644 index 00000000..f95cfd38 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php @@ -0,0 +1,334 @@ +<?php + + +class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model +{ + + private $userId; + private $Key; + + private $bizContentarr = array(); + private $bizContent = NULL; + + private $orderData=array(); + private $orderId; //”Integer”//订单ID,不为空代表修改 + private $modifyLogInfo; //”String”//修改的日志记录信息.如果是修改订单的状态,这里传输修改简报 + private $orderType; //”Integer” //订单类型 1=独立成团,2=散客团 + private $routeName; //”String”//行程名称 + private $routeType; //”String”//线路类型 + private $agcOrderNo; //”String”//组团社团号,团号格式 yyyy-mm-dd-cc(**)后面中括号号的对应团号的其他表达信息 + private $adultNum; //”Integer”//大人数量 + private $childNum; //”Integer”//小孩数量 + private $guiderNum; //”Integer”//领队数量 + private $guiderInfo; //”String”//领队信息 + private $toTraffic; //”String”//抵达交通 + private $backTraffic; //”String”//返回交通 + private $roomStandard; //”String”//用房标准 + private $orderRemark; //”String”//订单备注 + private $routeStandard; //”String”//行程接待标准 + private $destination; //”目的地名称”//目的地城市名称 + private $travelDate; //”String”//出游时间yyyy-mm-dd + private $leavedDate; //”String”//离团时间 yyyy-mm-dd + + // private $orderData['travelFees']=array(); //团款明细 + // [{ + // type:”String”//团款类型 + // money:”Double”//单价 + // num:”Double”//数量 + // unit:”Double”//单位 + // sumMoney:”Double//总金额” + // remark:”String”//备注 + // }] + // private $orderData['replaceCollections']=array(); //代收明细 + // [{ + // type:“String”//代收类型 + // money:”Double”//金额 + // remark:”String”//备注 + // }] + // private $orderData['replacePays']=array(); //代付明细 + // [{ + // type:“String”//代付类型 + // money:”Double”//金额 + // remark:”String”//备注 + // }] + // private $orderData['scheduleDetails']=array(); //行程详细,数组类型,按照第一天往后有序排列 + // [{ + // title:”String”//行程标题 + // content:”String”//行程内容 + // traffic:”String”//交通号 + // accommodation:”String”//住宿 + // breakFirst:”Integer”//是否包含早餐 【1=包含 0=不含】 + // dinner:”Integer”//是否包含中餐 【1=包含 0=不含】 + // lunch:”Integer”//是否包含晚餐 【1=包含 0=不含】 + // }] + // private $orderData['customers']=array(); //游客信息 + // [{ + // name:”String”//名字 + // peopleType:”String”//类型 【成人,小孩,婴儿,老人,学生…】 + // document Type:”String”//证件类型【护照,身份证,户口,驾驶证….】 + // documentNo:”String”//证件号 + // phoneNo:”String”//手机号 + // otherInfo:”String”//其他信息 + // }] + + function __construct() { + parent::__construct(); + $this->orderData['travelFees'] = array(); //团款明细 + $this->orderData['replaceCollections'] = array(); //代收明细 + $this->orderData['replacePays'] = array(); //代付明细 + $this->orderData['scheduleDetails'] = array(); //行程详细,数组类型,按照第一天往后有序排列 + $this->orderData['customers'] = array(); //游客信息 + } + + public function getBizContent() + { + if(!empty($this->orderData)){ + $this->bizContentarr['orderData'] = $this->orderData; + $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + } + return $this->bizContent; + } + + public function setUserId($userId) + { + $this->userId = $userId; + $this->bizContentarr['userId'] = $userId; + return $this; + } + public function setKey($Key) + { + $this->key = $Key; + $this->bizContentarr['key'] = $Key; + return $this; + } + /** 订单基本信息 */ + public function setOrderId($orderId) + { + $this->orderData['orderId'] = $orderId; + return $this; + } + public function setModifyLogInfo($modifyLogInfo) + { + $this->orderData['modifyLogInfo'] = $modifyLogInfo; + return $this; + } + public function setOrderType($orderType) + { + $this->orderData['orderType'] = $orderType; + return $this; + } + public function setRouteName($routeName) + { + $this->orderData['routeName'] = $routeName; + return $this; + } + public function setRouteType($routeType) + { + $this->orderData['routeType'] = $routeType; + return $this; + } + public function setAgcOrderNo($agcOrderNo) + { + $this->orderData['agcOrderNo'] = $agcOrderNo; + return $this; + } + public function setAdultNum($adultNum) + { + $this->orderData['adultNum'] = $adultNum; + return $this; + } + public function setChildNum($childNum) + { + $this->orderData['childNum'] = $childNum; + return $this; + } + public function setGuiderNum($guiderNum) + { + $this->orderData['guiderNum'] = $guiderNum; + return $this; + } + public function setGuiderInfo($guiderInfo) + { + $this->orderData['guiderInfo'] = $guiderInfo; + return $this; + } + public function setToTraffic($toTraffic) + { + $this->orderData['toTraffic'] = $toTraffic; + return $this; + } + public function setBackTraffic($backTraffic) + { + $this->orderData['backTraffic'] = $backTraffic; + return $this; + } + public function setRoomStandard($roomStandard) + { + $this->orderData['roomStandard'] = $roomStandard; + return $this; + } + public function setOrderRemark($orderRemark) + { + $this->orderData['orderRemark'] = $orderRemark; + return $this; + } + public function setRouteStandard($routeStandard) + { + $this->orderData['routeStandard'] = $routeStandard; + return $this; + } + public function setDestination($destination) + { + $this->orderData['destination'] = $destination; + return $this; + } + public function setTravelDate($travelDate) + { + $this->orderData['travelDate'] = $travelDate; + return $this; + } + public function setLeavedDate($leavedDate) + { + $this->orderData['leavedDate'] = $leavedDate; + return $this; + } + + /** 团款数组 */ + public function setTravelFeesType($index, $type) + { + $this->orderData['travelFees'][$index]['type'] = $type; + return $this; + } + public function setTravelFeesMoney($index, $money) + { + $this->orderData['travelFees'][$index]['money'] = $money; + return $this; + } + public function setTravelFeesNum($index, $num) + { + $this->orderData['travelFees'][$index]['num'] = $num; + return $this; + } + public function setTravelFeesUnit($index, $unit) + { + $this->orderData['travelFees'][$index]['unit'] = $unit; + return $this; + } + public function setTravelFeesSumMoney($index, $sumMoney) + { + $this->orderData['travelFees'][$index]['sumMoney'] = $sumMoney; + return $this; + } + public function setTravelFeesRemark($index, $remark) + { + $this->orderData['travelFees'][$index]['remark'] = $remark; + return $this; + } + + /** 代付数组 */ + public function setReplacePaysType($index, $type) + { + $this->orderData['replacePays'][$index]['type'] = $type; + return $this; + } + public function setReplacePaysMoney($index, $money) + { + $this->orderData['replacePays'][$index]['money'] = $money; + return $this; + } + public function setReplacePaysRemark($index, $remark) + { + $this->orderData['replacePays'][$index]['remark'] = $remark; + return $this; + } + + /** 代收数组 */ + public function setReplaceCollectionsType($index, $type) + { + $this->orderData['replaceCollections'][$index]['type'] = $type; + return $this; + } + public function setReplaceCollectionsMoney($index, $money) + { + $this->orderData['replaceCollections'][$index]['money'] = $money; + return $this; + } + public function setReplaceCollectionsRemark($index, $remark) + { + $this->orderData['replaceCollections'][$index]['remark'] = $remark; + return $this; + } + + /** 行程详细数组 */ + public function setScheduleDetailsTitle($index, $title) + { + $this->orderData['scheduleDetails'][$index]['title'] = $title; + return $this; + } + public function setScheduleDetailsContent($index, $content) + { + $this->orderData['scheduleDetails'][$index]['content'] = $content; + return $this; + } + public function setScheduleDetailsTraffic($index, $traffic) + { + $this->orderData['scheduleDetails'][$index]['traffic'] = $traffic; + return $this; + } + public function setScheduleDetailsAccommodation($index, $accommodation) + { + $this->orderData['scheduleDetails'][$index]['accommodation'] = $accommodation; + return $this; + } + public function setScheduleDetailsBreakFirst($index, $breakFirst) + { + $this->orderData['scheduleDetails'][$index]['breakFirst'] = $breakFirst; + return $this; + } + public function setScheduleDetailsDinner($index, $dinner) + { + $this->orderData['scheduleDetails'][$index]['dinner'] = $dinner; + return $this; + } + public function setScheduleDetailsLunch($index, $lunch) + { + $this->orderData['scheduleDetails'][$index]['lunch'] = $lunch; + return $this; + } + + /** 游客信息数组 */ + public function setCustomersName($index, $name) + { + $this->orderData['customers'][$index]['name'] = $name; + return $this; + } + public function setCustomersPeopleType($index, $peopleType) + { + $this->orderData['customers'][$index]['peopleType'] = $peopleType; + return $this; + } + public function setCustomersDocumentType($index, $documentType) + { + $this->orderData['customers'][$index]['documentType'] = $documentType; + return $this; + } + public function setCustomersDocumentNo($index, $documentNo) + { + $this->orderData['customers'][$index]['documentNo'] = $documentNo; + return $this; + } + public function setCustomersPhoneNo($index, $phoneNo) + { + $this->orderData['customers'][$index]['phoneNo'] = $phoneNo; + return $this; + } + public function setCustomersOtherInfo($index, $otherInfo) + { + $this->orderData['customers'][$index]['otherInfo'] = $otherInfo; + return $this; + } + + +} + +?> diff --git a/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php new file mode 100644 index 00000000..7ffc4956 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php @@ -0,0 +1,131 @@ +<?php +/*! + * 图兰朵系统对接: + * 查询接口业务参数 + * @author LYT <lyt@hainatravel.com> + * @date 2018-03-31 + */ +class TuLanDuo_queryContentBuilder extends CI_Model +{ + private $userId; + private $Key; + + private $pageSize=20; //”Integer”//每页数量 每页最多返回50行 + private $pageIndex=1; //”Integer”//页码。第几页数据 + private $orderType; //”Integer”//订单类型,1=独立成团,2=散客团 【精准查询】 + private $orderStatus; //”Integer”//订单状态 1=已确认,0=待确认 + private $startTravelDate; //”String”//当前出游时间之后 【精准查询】 + private $endTravelDate; //”String”//当前出游时间之前 【精准查询】 + private $startOrderDate; //”String”//当前预定时间之后 【精准查询】 + private $endOrderDate; //”String”//当前预定时间之前 【精准查询】 + private $agcOrderNo; //”String”//组团社团号 【模糊查询】 + private $adultNum; //”Integer”//大人数量 【精准查询】 + private $childNum; //”Integer”//小孩数量 【精准查询】 + private $customerName; //”String”//订单游客名单 【模糊查询】 + private $routeName; //”String”//行程名称 。 【模糊查询】 + private $operationDep; //”String”//操作部门 , 【精准查询】 + + private $orderId; //”Integer”//订单ID + + private $bizContentarr = array(); + + private $bizContent = NULL; + + public function getBizContent() + { + if(!empty($this->bizContentarr)){ + $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + } + return $this->bizContent; + } + + public function setUserId($userId) + { + $this->userId = $userId; + $this->bizContentarr['userId'] = $userId; + return $this; + } + public function setKey($Key) + { + $this->key = $Key; + $this->bizContentarr['key'] = $Key; + return $this; + } + + public function getPageSize() + { + return $this->pageSize; + } + public function setPageSize($pageSize) + { + $this->pageSize = $pageSize; + $this->bizContentarr['pageSize'] = $pageSize; + return $this; + } + public function getPageIndex() + { + return $this->pageIndex; + } + public function setPageIndex($pageIndex) + { + $this->pageIndex = $pageIndex; + $this->bizContentarr['pageIndex'] = $pageIndex; + return $this; + } + + public function getStartTravelDate() + { + return $this->startTravelDate; + } + public function setStartTravelDate($startTravelDate) + { + $this->startTravelDate = $startTravelDate; + $this->bizContentarr['startTravelDate'] = $startTravelDate; + return $this; + } + public function getEndTravelDate() + { + return $this->endTravelDate; + } + public function setEndTravelDate($endTravelDate) + { + $this->endTravelDate = $endTravelDate; + $this->bizContentarr['endTravelDate'] = $endTravelDate; + return $this; + } + + public function getStartOrderDate() + { + return $this->startOrderDate; + } + public function setStartOrderDate($startOrderDate) + { + $this->startOrderDate = $startOrderDate; + $this->bizContentarr['startOrderDate'] = $startOrderDate; + return $this; + } + public function getEndOrderDate() + { + return $this->endOrderDate; + } + public function setEndOrderDate($endOrderDate) + { + $this->endOrderDate = $endOrderDate; + $this->bizContentarr['endOrderDate'] = $endOrderDate; + return $this; + } + + public function getOrderId() + { + return $this->orderId; + } + public function setOrderId($orderId) + { + $this->orderId = $orderId; + $this->bizContentarr['orderId'] = $orderId; + return $this; + } + // 其他还没用到先不写了... +} + +?> diff --git a/webht/third_party/trippestOrderSync/models/index.html b/webht/third_party/trippestOrderSync/models/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php new file mode 100644 index 00000000..d2b78bd0 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -0,0 +1,1546 @@ +<?php + +class Orders_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + //读取默认配置 + $this->COLI_WebCode = $this->config->item('Site_Code'); + $this->COLI_Area = $this->config->item('Site_Area'); + $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); + $this->COLI_department = $this->config->item('Site_Department'); + $this->COLI_Currency = $this->config->item('Site_Currency'); + $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); + $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); + $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); + $this->COLI_OrderStartDate = null; + $this->COLI_Keywords = NULL; + switch ($this->check_device()) { + case 'mobile': + $this->COLI_OrderSource = '62003'; + break; + case 'tablet': + $this->COLI_OrderSource = '62002'; + break; + default: + $this->COLI_OrderSource = '62001'; + } + } + + public function get_orderinfo_detail($COLI_ID) + { + $sql = "SELECT coli.COLI_ID, + coli.COLI_Department, + cold.COLD_ServiceSN, + cold.COLD_ServiceSN2, + cold.COLD_ServiceCity, + * + FROM BIZ_ConfirmLineInfo coli + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE coli.COLI_ID='$COLI_ID' + ORDER BY COLI_ApplyDate DESC"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_guestlist($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_scheduleDetails($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN + AND (PAG2_LGC = 2) + WHERE COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_packageDetails($pag_code_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + WHERE pag.PAG_Code IN ($pag_code_str) + order by pag.PAG_Code "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_paymentDetails($COLI_ID) + { + $sql = "SELECT * + FROM BIZ_GroupAccountInfo bgai + INNER JOIN BIZ_ConfirmLineInfo coli ON bgai.GAI_COLI_SN=coli.COLI_SN + WHERE coli_ID = '$COLI_ID'"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_groupCodeList($GroupCodeList_str) + { + $sql = "SELECT GRI_No + FROM GRoupInfo gri + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No IN ($GroupCodeList_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_packageSN($pag_code) + { + $sql = "SELECT top 1 PAG2_SN + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + "; + $query = $this->HT->query($sql); + if ($query->row()) { + return $query->row()->PAG2_SN; + } + return NULL; + } + public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) + { + $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, gci.* + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE 1=1 "; + if ($coli_sn !== 0) { + $sql .= " and gci.GCI_COLI_SN='$coli_sn' "; + } + if ($startDate !== NULL) { + // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; + } + $query = $this->HT->query($sql); + return $query->result(); + } + + public $GRI_SN=0; // 团号 + public $GRI_No; // 团号 + public $GRI_OrderType; // 订单类型 + public $GRI_Name; // 团名 + public $GRI_PersonNum; // 人数 + public $GRI_Days; // 行程天数 + public $GRI_IsCancel=0; + public $GRI_DeleteFlag=0; + /** 团信息 */ + public function groupinfo_save() + { + $sql = "INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N?,N?,?,?,?,?,?)"; + $query = $this->HT->query($sql, array( + $this->GRI_No, + $this->GRI_Name, + $this->GRI_PersonNum, + $this->GRI_Days, + $this->GRI_IsCancel, + $this->GRI_DeleteFlag, + $this->GRI_OrderType + )); + $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); + return $this->GRI_SN; + } + + public $GCI_SN; + public $GCI_combineNo=''; // 拼团团号 + public $GCI_COLI_SN; // 订单key + public $GCI_VendorOrderId; // 地接社系统订单id + public $GCI_FromAgc; // 组团社来源 + public $GCI_groupType; // 组团社来源 + public $GCI_travelDate; + public $GCI_leaveDate; + public $GCI_createTime; + /** 目的地订单 拼团信息 */ + public function biz_groupcombineinfo_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupCombineInfo + WHERE GCI_VendorOrderId = ? + ) + INSERT INTO BIZ_GroupCombineInfo + (GCI_combineNo + ,GCI_COLI_SN + ,GCI_VendorOrderId + ,GCI_FromAgc + ,GCI_groupType + ,GCI_travelDate + ,GCI_leaveDate + ,GCI_createTime) + VALUES + (N? + ,? + ,? + ,N? + ,? + ,? + ,? + ,?) + "; + $query = $this->HT->query($sql, array( + $this->GCI_VendorOrderId + // ,$this->GCI_COLI_SN + ,$this->GCI_combineNo + ,$this->GCI_COLI_SN + ,$this->GCI_VendorOrderId + ,$this->GCI_FromAgc + ,$this->GCI_groupType + ,$this->GCI_travelDate + ,$this->GCI_leaveDate + ,$this->GCI_createTime + )); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + return $this->GCI_SN; + } + public function combineoperation_exist($combineNo='', $operation="") + { + if( ! $combineNo) { return false; } + $sql = "SELECT TOP 1 GCOD_GCI_combineNo + FROM BIZ_GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; + $query = $this->HT->query($sql, array( + $combineNo,$operation + )); + return $query->result(); + } + public $GCOD_SN; + public $GCOD_GCI_combineNo = ''; + public $GCOD_operationType = ''; + public $GCOD_subType = ''; + public $GCOD_title = ''; + public $GCOD_dutyName = ''; + public $GCOD_dutyTel; + public $GCOD_dutyPhoto; + public $GCOD_startDate; + public $GCOD_endDate; + public $GCOD_useNum=1; + public $GCOD_sumMoney; + public $GCOD_standard = ''; + public $GCOD_carLicense = ''; + public $GCOD_remark = ''; + public $GCOD_creatTime; + public function biz_groupcombineoperationdetail_save() + { + // IF NOT EXISTS( + // SELECT TOP 1 1 + // FROM BIZ_GroupCombineOperationDetail + // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? + // ) + $sql = "INSERT INTO BIZ_GroupCombineOperationDetail + (GCOD_GCI_combineNo + ,GCOD_operationType + ,GCOD_subType + ,GCOD_title + ,GCOD_dutyName + ,GCOD_dutyTel + ,GCOD_dutyPhoto + ,GCOD_startDate + ,GCOD_endDate + ,GCOD_useNum + ,GCOD_sumMoney + ,GCOD_standard + ,GCOD_carLicense + ,GCOD_remark + ,GCOD_creatTime) + VALUES + (N? + ,N? + ,N? + ,N? + ,N? + ,? + ,? + ,? + ,? + ,? + ,? + ,N? + ,N? + ,N? + ,GETDATE()) + "; + $query = $this->HT->query($sql, array( + $this->GCOD_GCI_combineNo + ,$this->GCOD_operationType + // ,$this->GCOD_GCI_combineNo + // ,$this->GCOD_operationType + ,$this->GCOD_subType + ,$this->GCOD_title + ,$this->GCOD_dutyName + ,$this->GCOD_dutyTel + ,$this->GCOD_dutyPhoto + ,$this->GCOD_startDate + ,$this->GCOD_endDate + ,$this->GCOD_useNum + ,$this->GCOD_sumMoney + ,$this->GCOD_standard + ,$this->GCOD_carLicense + ,$this->GCOD_remark + )); + return $query; + } + + + + var $GUT_SN; + var $GUT_FirstName; //联系人 + var $GUT_LastName = ""; //联系人 + var $GUT_Title; //称谓 + var $GUT_Email; //主email + var $GUT_Email2; //备用email + var $GUT_NationalityID; //国家 + var $GUT_Passport; //护照 + var $GUT_TEL; //座机 + var $GUT_MoveTel; //手机 + + /** + * 商务联系人表入库 + * + * @return int GUT_SN 插入id + */ + + function biz_guest_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_Guest \n" + . " ( \n" + . " GUT_FirstName, \n" + . " GUT_LastName, \n" + . " GUT_Title, \n" + . " GUT_Email, \n" + . " GUT_Email2, \n" + . " GUT_NationalityID, \n" + . " GUT_Passport, \n" + . " GUT_TEL, \n" + . " GUT_MoveTel, \n" + . " GUT_AddCode, \n" + . " GUT_CreateDate \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " GETDATE() \n" + . " )"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), + mb_convert_encoding($this->GUT_LastName, 'UTF-8'), + $this->GUT_Title, + $this->GUT_Email, + $this->GUT_Email2, + $this->GUT_NationalityID, + mb_convert_encoding($this->GUT_Passport, 'UTF-8'), + $this->GUT_TEL, + $this->GUT_MoveTel, $AddCode + )); + $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); + return $this->GUT_SN; + } + + public function get_SN_by_groupCode($code) + { + $sql = "SELECT top 1 COLI_SN,GRI_SN + FROM BIZ_ConfirmLineInfo coli + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No LIKE '$code%'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->GRI_SN; + return $query->row(); + } + return NULL; + } + + var $BIZ_COLI_SN; + var $BIZ_COLI_ID; + var $BIZ_COLI_GUT_SN; //联系人id + var $BIZ_COLI_Area; //市场 + var $BIZ_COLI_ApplyDate = ''; //提交日期 + var $BIZ_COLI_Price; //订单总价 + var $BIZ_COLI_Cost; //总成本 + var $BIZ_COLI_Currency; //币种 + var $BIZ_COLI_TrueCardRate; //信用卡手续费 + var $BIZ_COLI_SenderIP = ''; //客人ip + var $BIZ_COLI_WebCode = ''; //站点code + var $BIZ_COLI_servicetype; //订单来源类型 + var $BIZ_COLI_sourcetype; //预定类型 + var $BIZ_COLI_AgencyID; + var $BIZ_COLI_ConfirmType; //提交方式 + var $BIZ_COLI_OrderDetailText; + var $BIZ_COLI_OriginalText=''; + var $BIZ_COLI_Memo; + var $BIZ_COLI_GRI_SN; + var $BIZ_COLI_GroupCode=''; + var $BIZ_COLI_State; + + /** + * 商务订单主表入库 + * @return int BIZ_COLI_ID 插入id + */ + function biz_confirm_save() { + // if (empty($this->BIZ_COLI_WebCode)) { + $this->BIZ_COLI_WebCode = '';// 来源图兰朵 + // } + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" + . "( \n" + . " COLI_ID, \n" + . " COLI_GUT_SN, \n" + . " COLI_Area, \n" + . " COLI_ApplyDate, \n" + . " COLI_Price, \n" + . " COLI_Cost, \n" + . " COLI_Currency, \n" + . " COLI_TrueCardRate, \n" + . " COLI_AgencyID, \n" + . " COLI_OrderDetailText, \n" + . " COLI_SenderIP, \n" + . " COLI_WebCode, \n" + . " COLI_servicetype, \n" + . " COLI_sourcetype, \n" + . " COLI_ConfirmType, \n" + . " COLI_State, \n" + . " COLI_Department, \n" + . " COLI_AddCode, \n" + . " COLI_OrderSource, \n" + . " COLI_Memo, \n" + . " COLI_GRI_SN, \n" + . " COLI_GroupCode, \n" + . " COLI_OriginalText \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " N? \n" + . ")"; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_ID, + $this->BIZ_COLI_GUT_SN, + 2, + // $this->config->item('Site_Area'), + //date("Y-m-d H:i:s"), + $this->BIZ_COLI_ApplyDate, + $this->BIZ_COLI_Price, + $this->BIZ_COLI_Cost, + $this->config->item('Site_Currency'), + $this->BIZ_COLI_TrueCardRate, + $this->BIZ_COLI_AgencyID, + $this->BIZ_COLI_OrderDetailText, + $this->BIZ_COLI_SenderIP, + $this->BIZ_COLI_WebCode, + $this->BIZ_COLI_servicetype, + $this->BIZ_COLI_sourcetype, + $this->BIZ_COLI_ConfirmType, + $this->BIZ_COLI_State, + 30,// $this->config->item('Site_Department'), + $AddCode, + $this->COLI_OrderSource, + $this->BIZ_COLI_Memo, + $this->BIZ_COLI_GRI_SN, + $this->BIZ_COLI_GroupCode, + $this->BIZ_COLI_OriginalText + )); + $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); + return $this->BIZ_COLI_SN; + } + + public function update_confirmLineInfo() + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET + COLI_GRI_SN=?, + COLI_GroupCode=? + WHERE COLI_SN=? + "; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_GRI_SN + ,$this->BIZ_COLI_GroupCode + ,$this->BIZ_COLI_SN + )); + return $this->query; + } + + var $COLD_SN; + var $COLD_COLI_SN; // 订单主表sn + var $COLD_ServiceType; // 服务类型 + var $COLD_StartDate; // 产品的服务的开始日期 + var $COLD_EndDate; // 产品的服务的结束日期 + var $COLD_TotalCost; // 总成本 + var $COLD_TotalPrice; // 总报价 + var $COLD_Count; // 产品数量 + var $COLD_PersonNum; // 成人数 + var $COLD_ChildNum; // 小孩数 + var $COLD_BabyNum; // 婴儿数 + var $cold_state; // 状态 + var $DeleteFlag; // 删除标志 + var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY + var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 + var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 + var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID + var $COLD_Memo = NULL; + var $COLD_MemoText = NULL; + + /** + * 商务订单子(详细)表入库 + * + * @return int 插入id + */ + + function biz_confirm_detail_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" + . "( \n" + . " COLD_COLI_SN, \n" + . " COLD_ServiceType, \n" + . " COLD_StartDate, \n" + . " COLD_EndDate, \n" + . " COLD_TotalCost, \n" + . " COLD_TotalPrice, \n" + . " COLD_Count, \n" + . " COLD_PersonNum, \n" + . " COLD_ChildNum, \n" + . " COLD_BabyNum, \n" + . " cold_state, \n" + . " DeleteFlag, \n" + . " COLD_DeliveryCharge, \n" + . " COLD_AddCode, \n" + . " COLD_PlanVEI_SN, \n" + . " COLD_SPFS, \n" + . " COLD_Memo, \n" + . " COLD_MemoText, \n" + . " COLD_ServiceSN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->COLD_COLI_SN, + $this->COLD_ServiceType, + $this->COLD_StartDate, + $this->COLD_EndDate, + $this->COLD_TotalCost, + $this->COLD_TotalPrice, + $this->COLD_Count, + $this->COLD_PersonNum, + $this->COLD_ChildNum, + $this->COLD_BabyNum, + $this->cold_state, + $this->DeleteFlag, + $this->COLD_DeliveryCharge, + $AddCode, + $this->COLD_PlanVEI_SN, + $this->COLD_SPFS, + $this->COLD_Memo, + $this->COLD_MemoText, + $this->COLD_ServiceSN) + ); + //查出最近插入的id + $HT2 = $this->load->database('HT', true); + $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); + return $this->COLD_SN; + } + + var $BIZ_COLL_COLI_SN; + var $BIZ_COLL_type; + var $BIZ_COLL_COLI_Field; + var $BIZ_COLL_COLI_value; + var $BIZ_COLL_OPI_SN; + + function biz_confirm_line_log_save() + { + $sql = "INSERT INTO BIZ_ConfirmLineLog ( + COLL_COLI_SN, + COLL_LogTime, + COLL_type, + COLL_COLI_Field, + COLL_COLI_value, + COLL_OPI_SN + ) VALUES (?,GETDATE(),?,?,?,?) "; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, + $this->BIZ_COLL_type, + $this->BIZ_COLL_COLI_Field, + $this->BIZ_COLL_COLI_value, + $this->BIZ_COLL_OPI_SN) + ); + return $query; + } + + var $POI_SN; + var $POI_COLD_SN; + var $POI_FlightsNo = ''; + var $POI_AirPort = ''; + var $POI_Time; + var $POI_Hotel = ''; + var $POI_HotelAddress = ''; + var $POI_HotelPhone = ''; + var $POI_HotelCheckInName = ''; + var $POI_HotelCheckIn = ''; + var $POI_HotelCheckOut = ''; + var $POI_EndTime = ''; + var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 + /** 包价线路订单入库 */ + public function biz_packageorder_save() + { + $sql = "INSERT INTO BIZ_PackageOrderInfo + (POI_COLD_SN + ,POI_FlightsNo + ,POI_AirPort + ,POI_Time + ,POI_Hotel + ,POI_QuotationType + ,POI_HotelAddress + ,POI_HotelPhone + ,POI_HotelCheckInName + ,POI_HotelCheckIn + ,POI_HotelCheckOut + ,POI_EndTime) + VALUES + (? + ,? + ,N? + ,? + ,N? + ,? + ,N? + ,N? + ,N? + ,N? + ,N? + ,N?) + "; + $query = $this->HT->query($sql, array( + $this->POI_COLD_SN + ,$this->POI_FlightsNo + ,$this->POI_AirPort + ,$this->POI_Time + ,$this->POI_Hotel + ,$this->POI_QuotationType + ,$this->POI_HotelAddress + ,$this->POI_HotelPhone + ,$this->POI_HotelCheckInName + ,$this->POI_HotelCheckIn + ,$this->POI_HotelCheckOut + ,$this->POI_EndTime + )); + $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); + return $this->POI_SN; + } + + var $FOI_SN; + var $FOI_COLD_SN; // 订单子表sn + var $Aircompany; // 航空公司编码 + var $FlightsNo; // 航班号 + var $Cabin; // 舱位 + var $DepartAirport; // 出发机场 + var $ArrivalAirport; // 抵达机场 + var $DepartureCity; // 出发城市 + var $DepartureTime; // 出发日期 + var $ArrivalCity; // 抵达城市 + var $Arrivaltime; // 抵达时间 + var $DepartureDate; // 出发时间 + var $adultCost; // 成人成本 + var $childCost; // 小孩成倍 + var $babyCost; // 婴儿成本 + var $adultPrice; // 成人报价 + var $childPrice; // 小孩报价 + var $babyPrice; // 婴儿报价 + var $Stopover; // + var $PriceY; // Y仓价格 + var $price_low; // 最低价格 + var $FOI_Mile; // 里程 + var $TicketAddress; // 寄送地址 + var $FOI_CostTime = ''; // 运行时间 + var $Aircraft = ''; // 12306座位编号 + var $FOI_ServiceFee_adult = NULL; // 成人服务费 + var $FOI_ServiceFee_child = NULL; // 儿童服务费 + var $FOI_DeliveryFee = NULL; // 寄票费 + var $FOI_SelectedSeat = ""; // 选座 + + /** + * + * 商务机票订单入库 + * + */ + + function biz_flight_order_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" + . "( \n" + . " FOI_COLD_SN, \n" + . " Aircompany, \n" + . " FlightsNo, \n" + . " Cabin, \n" + . " DepartAirport, \n" + . " ArrivalAirport, \n" + . " DepartureCity, \n" + . " DepartureTime, \n" + . " ArrivalCity, \n" + . " Arrivaltime, \n" + . " DepartureDate, \n" + . " adultCost, \n" + . " childCost, \n" + . " babyCost, \n" + . " adultPrice, \n" + . " childPrice, \n" + . " babyPrice, \n" + . " Stopover, \n" + . " PriceY, \n" + . " price_low, \n" + . " FOI_Mile, \n" + . " TicketAddress, \n" + . " FOI_CostTime, \n" + . " FOI_AddCode, \n" + . " Aircraft, \n" + . " FOI_ServiceFee_adult, \n" + . " FOI_ServiceFee_child, \n" + . " FOI_SelectedSeat, \n" + . " FOI_DeliveryFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->FOI_COLD_SN, + $this->Aircompany, + $this->FlightsNo, + $this->Cabin, + $this->DepartAirport, + $this->ArrivalAirport, + $this->DepartureCity, + $this->DepartureTime, + $this->ArrivalCity, + $this->Arrivaltime, + $this->DepartureDate, + $this->adultCost, + $this->childCost, + $this->babyCost, + $this->adultPrice, + $this->childPrice, + $this->babyPrice, + $this->Stopover, + $this->PriceY, + $this->price_low, + $this->FOI_Mile, + $this->TicketAddress, + $this->FOI_CostTime, + $AddCode, + $this->Aircraft, + $this->FOI_ServiceFee_adult, + $this->FOI_ServiceFee_child, + $this->FOI_SelectedSeat, + $this->FOI_DeliveryFee + )); + $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); + return $this->FOI_SN; + } + + var $BPE_SN; + var $BPE_FirstName; //客人 + var $BPE_MiddleName; //客人 + var $BPE_LastName; //客人 + var $BPE_GuestType; //客人类型 + var $BPE_Passport; //护照 + var $BPE_imageSrc = NULL; //护照图片 + var $BPE_Nationality; //国籍 + var $BPE_SEX; //性别 + var $BPE_BirthDate; //生日 + var $BPE_PassportType = "Passport No."; //护照类型 + + /** + * + * 商务订单参团客人入库 + * + */ + + function biz_book_people_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_BookPeople \n" + . "( \n" + . " BPE_FirstName, \n" + . " BPE_MiddleName, \n" + . " BPE_LastName, \n" + . " BPE_GuestType, \n" + . " BPE_Passport, \n" + . " BPE_imageSrc, \n" + . " BPE_Nationality, \n" + . " BPE_SEX, \n" + . " BPE_BirthDate, \n" + . " BPE_PassportType, \n" + . " BPE_AddCode \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " N?, \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), + mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), + mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, + mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, + $this->BPE_Nationality, + $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); + $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); + return $this->BPE_SN; + } + + /** + * 参团人关联 + * + * @param int 商务子表sn + * @param int 参团客人sn + */ + function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { + $sql = "INSERT INTO BIZ_BookPeopleList \n" + . "( \n" + . " BPL_COLD_SN, \n" + . " BPL_BPE_SN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ? \n" + . ")"; + // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); + } + + /* + * 生成订单号 + * 根据系统时间生成,精确到0.0001微秒 + */ + + function MakeOrderNumber() { + return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); + } + + /** + * 生成商务订单号 + */ + function biz_make_order_number() { + /* + $date = date('ymd',time()); + $sql = "SELECT MAX( \n" + . " CONVERT( \n" + . " INT, \n" + . " CASE \n" + . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" + . " ELSE RIGHT(COLI_ID, 3) \n" + . " END \n" + . " ) \n" + . " ) AS SN \n" + . "FROM dbo.BIZ_ConfirmLineInfo \n" + . "WHERE (LEFT(COLI_ID, 6) = ?)"; + $query = $this->HT->query($sql,array($date)); + $id = $query->row()->SN; + if (is_null($id)||empty($id)) + { + $id = 0; + } + $ids = $date.(sprintf('%03d',(int)$id+1)); + return $ids; + */ + //call $conn + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + } else { + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->ccid); + } + } + + /** + * + * 更新订单状态(商务订单) + * + */ + public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { + //更新订单 + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; + $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); + $this->insert_acc_info($order_id); + return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); + } + + /** + * + * 更新火车订单购票截图 + * + */ + public function update_train_order_pic($order_pic_id) { + //更新订单 + $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; + //$query = $this->HT->query($sql); + + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, $sql); + + return $stmt; + } + + /** + * + * 插入收款记录 + * + */ + public function insert_acc_info($order_id) { + //获取订单 + $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + $order_info = $query->row(); + //插入记录 + $sql = "INSERT INTO BIZ_GroupAccountInfo \n" + . " ( \n" + . " GAI_COLI_SN, \n" + . " GAI_COLI_ID, \n" + . " GAI_Type, \n" + . " GAI_SQJE, \n" + . " GAI_SQDate, \n" + . " GAI_SSJE, \n" + . " GAI_SQJECurrency, \n" + . " GAI_SSDate, \n" + . " GAI_CusName, \n" + . " GAI_CusEmail, \n" + . " GAI_Memo \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . " )"; + $query = $this->HT->query($sql, array($order_info->COLI_SN, + $order_info->COLI_ID, + $order_info->COLI_PayManner, + $order_info->COLI_Price, + date('Y-m-d H:i:s'), + $order_info->COLI_Price, + $this->config->item('Site_Currency'), + date('Y-m-d H:i:s'), + "", "", " ")); + } + + function GetNationalityID($nationalityName) { + if (!$nationalityName) { + return 0; + } + if (is_numeric($nationalityName)) { + return $nationalityName; + } else { + $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_Country = ? "; + $query = $this->HT->query($sql, array($nationalityName)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_COI_SN; + } else { + return 0; + } + } + } + + function GetNationalityName($nationalityID) { + if (!is_numeric($nationalityID)) { + return $nationalityID; + } else { + $sql = "SELECT TOP 1 ci2.COI2_Country \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_LGC = 2 \n" + . " AND ci2.COI2_COI_SN = ? "; + $query = $this->HT->query($sql, array($nationalityID)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_Country; + } else { + return $nationalityID; + } + } + } + + /** + * + * 获取商务订单信息 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_flight_order_by_id($order_id) { + $sql = "SELECT DISTINCT cli.COLI_ID, \n" + . " cli.COLI_Price, \n" + . " bg.GUT_FirstName, \n" + . " bg.GUT_LastName, \n" + . " bg.GUT_Email, \n" + . " bg.GUT_Email2, \n" + . " bpe.BPE_SN, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_Passport, \n" + . " cld.COLD_Count, \n" + . " foi.FlightsNo, \n" + . " foi.DepartureDate, \n" + . " foi.DepartureTime, \n" + . " foi.ArrivalTime, \n" + . " cli.COLI_PayManner, \n" + . " cli.COLI_State, \n" + . " cli.COLI_sourcetype, \n" + . " foi.Cabin, \n" + . " foi.DepartAirport, \n" + . " foi.ArrivalAirport, \n" + . " cld.COLD_SN, \n" + . " foi.DepartureCity, \n" + . " foi.ArrivalCity, \n" + . " bg.GUT_TEL, \n" + . " bg.GUT_NationalityID, \n" + . " cli.COLI_OrderDetailText, \n" + . " bpe.BPE_imageSrc, \n" + . " cli.COLI_Cost, \n" + . " cld.COLD_TotalPrice, \n" + . " cld.COLD_TotalCost \n" + . "FROM BIZ_ConfirmLineInfo cli \n" + . " INNER JOIN BIZ_ConfirmLineDetail cld \n" + . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" + . " INNER JOIN BIZ_GUEST bg \n" + . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" + . " INNER JOIN BIZ_BookPeople bpe \n" + . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" + . " INNER JOIN BIZ_FlightsOrderInfo foi \n" + . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" + . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; + + $query = $this->HT->query($sql, array($order_id)); + return $query->result(); + } + + /** + * + * 获取机票订单乘员列表 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_bpe_list_by_id($order_id) { + $sql = "SELECT DISTINCT bpe.BPE_SN, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_Passport \n" + . "FROM BIZ_BookPeople bpe \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" + . " INNER JOIN BIZ_ConfirmLineDetail cold \n" + . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" + . " INNER JOIN BIZ_ConfirmLineInfo coli \n" + . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" + . "WHERE coli.COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); + return $query->result(); + } + + /** + * + * 获取机票电子票号 + * @param array bpe_sn 乘客sn数组 + * @return mixed 机票票号 + * + */ + public function get_ticket_no($bpe_sn) { + if (is_array($bpe_sn)) { + $instr = join(',', $bpe_sn); + } elseif (is_string($bpe_sn)) { + $instr = $bpe_sn; + } else { + $instr = 0; + } + $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" + . " ftn.FTN_TicketNo, \n" + . " ftn.FTN_GuestNo \n" + . "FROM BIZ_FlightsTicketNo ftn \n" + . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /* + * 发送邮件 + */ + + function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { + $sql = "INSERT INTO Email_AutomaticSend \n" + . " ( \n" + . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" + . " M_FromName, M_State \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" + . " ) "; + $query = $this->HT->query($sql, + array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) + ); + return $query; + } + + /** + * wifi预订入库(目前仅CHT使用) + * + * @return int 插入id + */ + var $WOI_COLD_SN; + var $WOI_Device; //设备(智能手机、pad) + var $WOI_DeviceCount; //设备数量 + var $WOI_UsersCount; //使用人数 + var $WOI_Package; //Wi-Fi套餐 + var $WOI_PackageCount; //套餐数量 + var $WOI_DeliverDate; //起租日期 + var $WOI_DeliverCity; //起租城市 + var $WOI_DeliverAddr; //起租地址 + var $WOI_ReturnDate; //归还日期 + var $WOI_ReturnCity; //归还城市 + var $WOI_ReturnAddr; //归还地址 + var $WOI_OtherService; //其他服务 + var $WOI_GroupNo; //团号 + var $WOI_ExpressNo; //快递单号 + + public function biz_wifi_info_save() { + $sql = "INSERT INTO BIZ_WifiOrderInfo \n" + . "( \n" + . " WOI_COLD_SN, \n" + . " WOI_Device, \n" + . " WOI_DeviceCount, \n" + . " WOI_UsersCount, \n" + . " WOI_Package, \n" + . " WOI_PackageCount, \n" + . " WOI_DeliverDate, \n" + . " WOI_DeliverCity, \n" + . " WOI_DeliverAddr, \n" + . " WOI_ReturnDate, \n" + . " WOI_ReturnCity, \n" + . " WOI_ReturnAddr, \n" + . " WOI_OtherService, \n" + . " WOI_GroupNo, \n" + . " WOI_ExpressNo \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->WOI_COLD_SN, + $this->WOI_Device, + $this->WOI_DeviceCount, + $this->WOI_UsersCount, + $this->WOI_Package, + $this->WOI_PackageCount, + $this->WOI_DeliverDate, + $this->WOI_DeliverCity, + $this->WOI_DeliverAddr, + $this->WOI_ReturnDate, + $this->WOI_ReturnCity, + $this->WOI_ReturnAddr, + $this->WOI_OtherService, + $this->WOI_GroupNo, + $this->WOI_ExpressNo + )); + } + + /** + * 酒店预订入库 + * + * @return int 插入id + */ + var $HOI_COLD_SN; //必选 + var $HOI_NoSmoking = null; //无烟房 + var $HOI_EarlyTime = null; //最早确认时间,已不用 + var $HOI_LastTime = null; //最晚确认时间,已不用 + var $HOI_Room_NO = null; //房号 + var $HOI_ExtraNum = 0; //加床 + var $HOI_RoomTypeName = null; //房型 + var $HOI_BreakNum = null; //早餐人数 + var $HOI_PriceType = null; //价格类型 + var $HOI_BreakType = null; //早餐类型 + var $HOI_RoomRates = null; + var $HOI_ExtrabedRates = null; + var $HOI_TaxFee = null; + + public function biz_hotel_order_save() { + /* ASP版本 + sql="select * from BIZ_HotelOrderInfo where 1=2" + rs2.open sql,conn,3,3,1 + rs2.addnew + rs2("HOI_COLD_SN")=COLD_SN + rs2("HOI_ExtraNum") = extrabed + if clng(Smoking)<2 then + rs2("HOI_NoSmoking")=Smoking + end if + rs2("HOI_EarlyTime")=earlydate + rs2("HOI_LastTime")="" + rs2.update + rs2.close + */ + $sql = "INSERT INTO BIZ_HotelOrderInfo \n" + . "( \n" + . " HOI_COLD_SN, \n" + . " HOI_NoSmoking, \n" + . " HOI_EarlyTime, \n" + . " HOI_LastTime, \n" + . " HOI_Room_NO, \n" + . " HOI_ExtraNum, \n" + . " HOI_RoomTypeName, \n" + . " HOI_BreakNum, \n" + . " HOI_PriceType, \n" + . " HOI_BreakType, \n" + . " HOI_RoomRates, \n" + . " HOI_ExtrabedRates, \n" + . " HOI_TaxFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->HOI_COLD_SN, + $this->HOI_NoSmoking, + $this->HOI_EarlyTime, + $this->HOI_LastTime, + $this->HOI_Room_NO, + $this->HOI_ExtraNum, + $this->HOI_RoomTypeName, + $this->HOI_BreakNum, + $this->HOI_PriceType, + $this->HOI_BreakType, + $this->HOI_RoomRates, + $this->HOI_ExtrabedRates, + $this->HOI_TaxFee + )); + } + + /** + * + * 返回成行订单 + * 条件1:订单类型 + * 天剑2:网站来源 + * + */ + public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { + if ($biz) { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" + . "FROM BIZ_ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } else { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" + . "FROM ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } + $this->sql = $this->HT->queries; + return $query->result(); + } + + //传统订单支付之后,插入新的订单信息 + public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { + //获取订单 + $order_info_sql = " + SELECT confirmlineinfotmp.COLI_OrderPrice, + memberinfotmp.MEI_FirstName, + memberinfotmp.MEI_LastName, + memberinfotmp.MEI_Mail + FROM memberinfotmp + INNER JOIN customerlisttmp + ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn + INNER JOIN confirmlineinfotmp + ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn + WHERE (customerlisttmp.cul_coli_sn = ? )"; + $query = $this->HT->query($order_info_sql, array($coli_sn)); + $order_info = $query->row(); + + //插入记录 + $sql = "INSERT INTO GroupAccountInfoTmp + ( + GAI_COLI_SN, + GAI_SQJE, + GAI_SQDate, + GAI_CusName, + GAI_CusEmail, + GAI_SQJECurrency, + GAI_Type, + LastEditTime, + GAI_GRI_SN, + GAI_State, + DeleteFlag + ) + VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + $query = $this->HT->query($sql, array($coli_sn, + $order_info->COLI_OrderPrice, + date('Y-m-d H:i:s'), + $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, + $order_info->MEI_Mail, + $this->config->item('Site_Currency'), + $pay_manner, + date('Y-m-d H:i:s'), + $gri_sn, + $state, + $deleteflag + ) + ); + } + + //来源终端 tablet mobile desktop + public function check_device() { + if (isset($_SERVER['HTTP_USER_AGENT'])) { + $ua = $_SERVER['HTTP_USER_AGENT']; + } else { + $ua = ''; + } + ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com + ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. + ## Price will be $2 + $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) + $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent + $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) + + if (!function_exists('androidTablet')) { + + function androidTablet($ua) { //Find out if it is a tablet + if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent + if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) + return true; + } + } + } + + } + $androidTablet = androidTablet($ua); //Do androidTablet function + $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent + + if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) + return 'tablet'; + } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet + return 'mobile'; + } else { //If it's not a mobile device + return 'desktop'; + } + } + + public function ip_limit($ip = "0.0.0.0") + { + if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { + return TRUE; + } + $sql = "SELECT COUNT(1) cnt + FROM ConfirmLineInfoTmp + WHERE 1=1 + AND COLI_SenderIP = ? + AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; + $query = $this->HT->query($sql, array($ip)); + $ret = $query->row(); + if ($ret->cnt > 50) { + return FALSE; + } else { + return TRUE; + } + } + + +} diff --git a/webht/third_party/trippestOrderSync/views/index.html b/webht/third_party/trippestOrderSync/views/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/views/welcome_message.php b/webht/third_party/trippestOrderSync/views/welcome_message.php new file mode 100644 index 00000000..0bf5a8d2 --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/welcome_message.php @@ -0,0 +1,88 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Welcome to CodeIgniter</title> + + <style type="text/css"> + + ::selection{ background-color: #E13300; color: white; } + ::moz-selection{ background-color: #E13300; color: white; } + ::webkit-selection{ background-color: #E13300; color: white; } + + body { + background-color: #fff; + margin: 40px; + font: 13px/20px normal Helvetica, Arial, sans-serif; + color: #4F5155; + } + + a { + color: #003399; + background-color: transparent; + font-weight: normal; + } + + h1 { + color: #444; + background-color: transparent; + border-bottom: 1px solid #D0D0D0; + font-size: 19px; + font-weight: normal; + margin: 0 0 14px 0; + padding: 14px 15px 10px 15px; + } + + code { + font-family: Consolas, Monaco, Courier New, Courier, monospace; + font-size: 12px; + background-color: #f9f9f9; + border: 1px solid #D0D0D0; + color: #002166; + display: block; + margin: 14px 0 14px 0; + padding: 12px 10px 12px 10px; + } + + #body{ + margin: 0 15px 0 15px; + } + + p.footer{ + text-align: right; + font-size: 11px; + border-top: 1px solid #D0D0D0; + line-height: 32px; + padding: 0 10px 0 10px; + margin: 20px 0 0 0; + } + + #container{ + margin: 10px; + border: 1px solid #D0D0D0; + -webkit-box-shadow: 0 0 8px #D0D0D0; + } + </style> +</head> +<body> + +<div id="container"> + <h1>Welcome to CodeIgniter!</h1> + + <div id="body"> + <p>The page you are looking at is being generated dynamically by CodeIgniter.</p> + + <p>If you would like to edit this page you'll find it located at:</p> + <code>application/views/welcome_message.php</code> + + <p>The corresponding controller for this page is found at:</p> + <code>application/controllers/welcome.php</code> + + <p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p> + </div> + + <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p> +</div> + +</body> +</html> \ No newline at end of file From 4d4abd5ecccb7baa805263b37c2d139a32627d3c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 16 Apr 2018 18:22:45 +0800 Subject: [PATCH 045/382] =?UTF-8?q?trippest=20=E8=BE=93=E5=87=BA=E6=96=87?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index f52b050f..3205a081 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -193,6 +193,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GCI_createTime = $vo['orderDate']; $this->Orders_model->biz_groupcombineinfo_save(); } + echo "Got order list from 图兰朵. count: " . $resp_arr["responseData"]["totalRows"]; return; } @@ -347,6 +348,7 @@ class TulanduoApi extends CI_Controller } } // end foreach order echo "Got order from 图兰朵, count: " . count($to_update_list); + return; } public function order_push($COLI_ID='170809390') // test From 4b22574baf959611e8a3c81d82ca6fa56242072d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 17 Apr 2018 13:46:15 +0800 Subject: [PATCH 046/382] =?UTF-8?q?trippest=20=E5=AD=98=E5=85=A5HT;=20?= =?UTF-8?q?=E5=8F=91=E9=80=81=E6=8C=87=E5=AE=9A=E8=AE=A2=E5=8D=95=E5=8F=B7?= =?UTF-8?q?=E8=AE=A1=E5=88=92;=20todo:=20=E5=AD=98=E5=85=A5HT=E4=BE=9B?= =?UTF-8?q?=E5=BA=94=E5=95=86=E8=AE=A1=E5=88=92=E7=9B=B8=E5=85=B3=E8=A1=A8?= =?UTF-8?q?;=20=E6=95=B4=E7=90=86model=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/config/config.php | 4 +- .../trippestOrderSync/config/autoload.php | 116 -- .../trippestOrderSync/config/config.php | 364 ---- .../trippestOrderSync/config/constants.php | 41 - .../trippestOrderSync/config/database.php | 53 - .../trippestOrderSync/config/doctypes.php | 15 - .../config/foreign_chars.php | 64 - .../trippestOrderSync/config/hooks.php | 16 - .../trippestOrderSync/config/index.html | 10 - .../trippestOrderSync/config/migration.php | 41 - .../trippestOrderSync/config/mimes.php | 106 -- .../trippestOrderSync/config/profiler.php | 17 - .../trippestOrderSync/config/routes.php | 46 - .../trippestOrderSync/config/smileys.php | 66 - .../trippestOrderSync/config/user_agents.php | 178 -- .../controllers/TulanduoApi.php | 139 +- .../trippestOrderSync/logs/index.html | 10 - .../trippestOrderSync/logs/log-2018-03-22.php | 2 - .../trippestOrderSync/logs/log-2018-03-30.php | 118 -- .../trippestOrderSync/logs/log-2018-04-02.php | 106 -- .../trippestOrderSync/logs/log-2018-04-03.php | 676 ------- .../trippestOrderSync/logs/log-2018-04-04.php | 260 --- .../trippestOrderSync/logs/log-2018-04-08.php | 163 -- .../trippestOrderSync/logs/log-2018-04-09.php | 201 --- .../trippestOrderSync/logs/log-2018-04-10.php | 2 - .../trippestOrderSync/logs/log-2018-04-13.php | 76 - .../trippestOrderSync/logs/log-2018-04-15.php | 72 - .../trippestOrderSync/logs/log-2018-04-16.php | 81 - .../trippestOrderSync/models/order_insert.php | 1562 +++++++++++++++++ .../trippestOrderSync/models/order_update.php | 1499 ++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 22 +- 31 files changed, 3163 insertions(+), 2963 deletions(-) delete mode 100644 webht/third_party/trippestOrderSync/config/autoload.php delete mode 100644 webht/third_party/trippestOrderSync/config/config.php delete mode 100644 webht/third_party/trippestOrderSync/config/constants.php delete mode 100644 webht/third_party/trippestOrderSync/config/database.php delete mode 100644 webht/third_party/trippestOrderSync/config/doctypes.php delete mode 100644 webht/third_party/trippestOrderSync/config/foreign_chars.php delete mode 100644 webht/third_party/trippestOrderSync/config/hooks.php delete mode 100644 webht/third_party/trippestOrderSync/config/index.html delete mode 100644 webht/third_party/trippestOrderSync/config/migration.php delete mode 100644 webht/third_party/trippestOrderSync/config/mimes.php delete mode 100644 webht/third_party/trippestOrderSync/config/profiler.php delete mode 100644 webht/third_party/trippestOrderSync/config/routes.php delete mode 100644 webht/third_party/trippestOrderSync/config/smileys.php delete mode 100644 webht/third_party/trippestOrderSync/config/user_agents.php delete mode 100644 webht/third_party/trippestOrderSync/logs/index.html delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-03-22.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-03-30.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-02.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-03.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-04.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-08.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-09.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-10.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-13.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-15.php delete mode 100644 webht/third_party/trippestOrderSync/logs/log-2018-04-16.php create mode 100644 webht/third_party/trippestOrderSync/models/order_insert.php create mode 100644 webht/third_party/trippestOrderSync/models/order_update.php diff --git a/webht/config/config.php b/webht/config/config.php index c3620ebb..ea305f7b 100644 --- a/webht/config/config.php +++ b/webht/config/config.php @@ -180,7 +180,7 @@ $config['directory_trigger'] = 'd'; // experimental not currently in use | your log files will fill up very fast. | */ -$config['log_threshold'] = 0; +$config['log_threshold'] = 1; /* |-------------------------------------------------------------------------- @@ -377,4 +377,4 @@ $config['site'] = array( 'mbj' => array('site_code' => 'mbj', 'site_id' => 98, 'site_lgc' => '1', 'site_url' => 'http://www.mybeijingchina.com'), 'ct' => array('site_code' => 'ct', 'site_id' => 1000, 'site_lgc' => '104', 'site_url' => 'http://www.chinatravel.com'), 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'http://www.diychinatours.com') -); \ No newline at end of file +); diff --git a/webht/third_party/trippestOrderSync/config/autoload.php b/webht/third_party/trippestOrderSync/config/autoload.php deleted file mode 100644 index 53129c9c..00000000 --- a/webht/third_party/trippestOrderSync/config/autoload.php +++ /dev/null @@ -1,116 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| AUTO-LOADER -| ------------------------------------------------------------------- -| This file specifies which systems should be loaded by default. -| -| In order to keep the framework as light-weight as possible only the -| absolute minimal resources are loaded by default. For example, -| the database is not connected to automatically since no assumption -| is made regarding whether you intend to use it. This file lets -| you globally define which systems you would like loaded with every -| request. -| -| ------------------------------------------------------------------- -| Instructions -| ------------------------------------------------------------------- -| -| These are the things you can load automatically: -| -| 1. Packages -| 2. Libraries -| 3. Helper files -| 4. Custom config files -| 5. Language files -| 6. Models -| -*/ - -/* -| ------------------------------------------------------------------- -| Auto-load Packges -| ------------------------------------------------------------------- -| Prototype: -| -| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); -| -*/ - -$autoload['packages'] = array(); - - -/* -| ------------------------------------------------------------------- -| Auto-load Libraries -| ------------------------------------------------------------------- -| These are the classes located in the system/libraries folder -| or in your application/libraries folder. -| -| Prototype: -| -| $autoload['libraries'] = array('database', 'session', 'xmlrpc'); -*/ - -$autoload['libraries'] = array(); - - -/* -| ------------------------------------------------------------------- -| Auto-load Helper Files -| ------------------------------------------------------------------- -| Prototype: -| -| $autoload['helper'] = array('url', 'file'); -*/ - -$autoload['helper'] = array(); - - -/* -| ------------------------------------------------------------------- -| Auto-load Config files -| ------------------------------------------------------------------- -| Prototype: -| -| $autoload['config'] = array('config1', 'config2'); -| -| NOTE: This item is intended for use ONLY if you have created custom -| config files. Otherwise, leave it blank. -| -*/ - -$autoload['config'] = array(); - - -/* -| ------------------------------------------------------------------- -| Auto-load Language files -| ------------------------------------------------------------------- -| Prototype: -| -| $autoload['language'] = array('lang1', 'lang2'); -| -| NOTE: Do not include the "_lang" part of your file. For example -| "codeigniter_lang.php" would be referenced as array('codeigniter'); -| -*/ - -$autoload['language'] = array(); - - -/* -| ------------------------------------------------------------------- -| Auto-load Models -| ------------------------------------------------------------------- -| Prototype: -| -| $autoload['model'] = array('model1', 'model2'); -| -*/ - -$autoload['model'] = array(); - - -/* End of file autoload.php */ -/* Location: ./application/config/autoload.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/config.php b/webht/third_party/trippestOrderSync/config/config.php deleted file mode 100644 index d7ea3540..00000000 --- a/webht/third_party/trippestOrderSync/config/config.php +++ /dev/null @@ -1,364 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); - -/* -|-------------------------------------------------------------------------- -| Base Site URL -|-------------------------------------------------------------------------- -| -| URL to your CodeIgniter root. Typically this will be your base URL, -| WITH a trailing slash: -| -| http://example.com/ -| -| If this is not set then CodeIgniter will try to guess the protocol, domain -| and path to your installation. However, you should always configure this -| explicitly and never rely on auto-guessing, especially in production -| environments. -| -*/ -$config['base_url'] = ''; - -/* -|-------------------------------------------------------------------------- -| Index File -|-------------------------------------------------------------------------- -| -| Typically this will be your index.php file, unless you've renamed it to -| something else. If you are using mod_rewrite to remove the page set this -| variable so that it is blank. -| -*/ -$config['index_page'] = 'index.php'; - -/* -|-------------------------------------------------------------------------- -| URI PROTOCOL -|-------------------------------------------------------------------------- -| -| This item determines which server global should be used to retrieve the -| URI string. The default setting of 'AUTO' works for most servers. -| If your links do not seem to work, try one of the other delicious flavors: -| -| 'AUTO' Default - auto detects -| 'PATH_INFO' Uses the PATH_INFO -| 'QUERY_STRING' Uses the QUERY_STRING -| 'REQUEST_URI' Uses the REQUEST_URI -| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO -| -*/ -$config['uri_protocol'] = 'PATH_INFO'; - -/* -|-------------------------------------------------------------------------- -| URL suffix -|-------------------------------------------------------------------------- -| -| This option allows you to add a suffix to all URLs generated by CodeIgniter. -| For more information please see the user guide: -| -| http://codeigniter.com/user_guide/general/urls.html -*/ - -$config['url_suffix'] = ''; - -/* -|-------------------------------------------------------------------------- -| Default Language -|-------------------------------------------------------------------------- -| -| This determines which set of language files should be used. Make sure -| there is an available translation if you intend to use something other -| than english. -| -*/ -$config['language'] = 'english'; - -/* -|-------------------------------------------------------------------------- -| Default Character Set -|-------------------------------------------------------------------------- -| -| This determines which character set is used by default in various methods -| that require a character set to be provided. -| -*/ -$config['charset'] = 'UTF-8'; - -/* -|-------------------------------------------------------------------------- -| Enable/Disable System Hooks -|-------------------------------------------------------------------------- -| -| If you would like to use the 'hooks' feature you must enable it by -| setting this variable to TRUE (boolean). See the user guide for details. -| -*/ -$config['enable_hooks'] = FALSE; - - -/* -|-------------------------------------------------------------------------- -| Class Extension Prefix -|-------------------------------------------------------------------------- -| -| This item allows you to set the filename/classname prefix when extending -| native libraries. For more information please see the user guide: -| -| http://codeigniter.com/user_guide/general/core_classes.html -| http://codeigniter.com/user_guide/general/creating_libraries.html -| -*/ -$config['subclass_prefix'] = 'MY_'; - - -/* -|-------------------------------------------------------------------------- -| Allowed URL Characters -|-------------------------------------------------------------------------- -| -| This lets you specify with a regular expression which characters are permitted -| within your URLs. When someone tries to submit a URL with disallowed -| characters they will get a warning message. -| -| As a security measure you are STRONGLY encouraged to restrict URLs to -| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_- -| -| Leave blank to allow all characters -- but only if you are insane. -| -| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!! -| -*/ -$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; - - -/* -|-------------------------------------------------------------------------- -| Enable Query Strings -|-------------------------------------------------------------------------- -| -| By default CodeIgniter uses search-engine friendly segment based URLs: -| example.com/who/what/where/ -| -| By default CodeIgniter enables access to the $_GET array. If for some -| reason you would like to disable it, set 'allow_get_array' to FALSE. -| -| You can optionally enable standard query string based URLs: -| example.com?who=me&what=something&where=here -| -| Options are: TRUE or FALSE (boolean) -| -| The other items let you set the query string 'words' that will -| invoke your controllers and its functions: -| example.com/index.php?c=controller&m=function -| -| Please note that some of the helpers won't work as expected when -| this feature is enabled, since CodeIgniter is designed primarily to -| use segment based URLs. -| -*/ -$config['allow_get_array'] = TRUE; -$config['enable_query_strings'] = FALSE; -$config['controller_trigger'] = 'c'; -$config['function_trigger'] = 'm'; -$config['directory_trigger'] = 'd'; // experimental not currently in use - -/* -|-------------------------------------------------------------------------- -| Error Logging Threshold -|-------------------------------------------------------------------------- -| -| If you have enabled error logging, you can set an error threshold to -| determine what gets logged. Threshold options are: -| You can enable error logging by setting a threshold over zero. The -| threshold determines what gets logged. Threshold options are: -| -| 0 = Disables logging, Error logging TURNED OFF -| 1 = Error Messages (including PHP errors) -| 2 = Debug Messages -| 3 = Informational Messages -| 4 = All Messages -| -| For a live site you'll usually only enable Errors (1) to be logged otherwise -| your log files will fill up very fast. -| -*/ -$config['log_threshold'] = 1; - -/* -|-------------------------------------------------------------------------- -| Error Logging Directory Path -|-------------------------------------------------------------------------- -| -| Leave this BLANK unless you would like to set something other than the default -| application/logs/ folder. Use a full server path with trailing slash. -| -*/ -$config['log_path'] = ''; - -/* -|-------------------------------------------------------------------------- -| Date Format for Logs -|-------------------------------------------------------------------------- -| -| Each item that is logged has an associated date. You can use PHP date -| codes to set your own date formatting -| -*/ -$config['log_date_format'] = 'Y-m-d H:i:s'; - -/* -|-------------------------------------------------------------------------- -| Cache Directory Path -|-------------------------------------------------------------------------- -| -| Leave this BLANK unless you would like to set something other than the default -| system/cache/ folder. Use a full server path with trailing slash. -| -*/ -$config['cache_path'] = ''; - -/* -|-------------------------------------------------------------------------- -| Encryption Key -|-------------------------------------------------------------------------- -| -| If you use the Encryption class or the Session class you -| MUST set an encryption key. See the user guide for info. -| -*/ -$config['encryption_key'] = ''; - -/* -|-------------------------------------------------------------------------- -| Session Variables -|-------------------------------------------------------------------------- -| -| 'sess_cookie_name' = the name you want for the cookie -| 'sess_expiration' = the number of SECONDS you want the session to last. -| by default sessions last 7200 seconds (two hours). Set to zero for no expiration. -| 'sess_expire_on_close' = Whether to cause the session to expire automatically -| when the browser window is closed -| 'sess_encrypt_cookie' = Whether to encrypt the cookie -| 'sess_use_database' = Whether to save the session data to a database -| 'sess_table_name' = The name of the session database table -| 'sess_match_ip' = Whether to match the user's IP address when reading the session data -| 'sess_match_useragent' = Whether to match the User Agent when reading the session data -| 'sess_time_to_update' = how many seconds between CI refreshing Session Information -| -*/ -$config['sess_cookie_name'] = 'ci_session'; -$config['sess_expiration'] = 7200; -$config['sess_expire_on_close'] = FALSE; -$config['sess_encrypt_cookie'] = FALSE; -$config['sess_use_database'] = FALSE; -$config['sess_table_name'] = 'ci_sessions'; -$config['sess_match_ip'] = FALSE; -$config['sess_match_useragent'] = TRUE; -$config['sess_time_to_update'] = 300; - -/* -|-------------------------------------------------------------------------- -| Cookie Related Variables -|-------------------------------------------------------------------------- -| -| 'cookie_prefix' = Set a prefix if you need to avoid collisions -| 'cookie_domain' = Set to .your-domain.com for site-wide cookies -| 'cookie_path' = Typically will be a forward slash -| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists. -| -*/ -$config['cookie_prefix'] = ""; -$config['cookie_domain'] = ""; -$config['cookie_path'] = "/"; -$config['cookie_secure'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| Global XSS Filtering -|-------------------------------------------------------------------------- -| -| Determines whether the XSS filter is always active when GET, POST or -| COOKIE data is encountered -| -*/ -$config['global_xss_filtering'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| Cross Site Request Forgery -|-------------------------------------------------------------------------- -| Enables a CSRF cookie token to be set. When set to TRUE, token will be -| checked on a submitted form. If you are accepting user data, it is strongly -| recommended CSRF protection be enabled. -| -| 'csrf_token_name' = The token name -| 'csrf_cookie_name' = The cookie name -| 'csrf_expire' = The number in seconds the token should expire. -*/ -$config['csrf_protection'] = FALSE; -$config['csrf_token_name'] = 'csrf_test_name'; -$config['csrf_cookie_name'] = 'csrf_cookie_name'; -$config['csrf_expire'] = 7200; - -/* -|-------------------------------------------------------------------------- -| Output Compression -|-------------------------------------------------------------------------- -| -| Enables Gzip output compression for faster page loads. When enabled, -| the output class will test whether your server supports Gzip. -| Even if it does, however, not all browsers support compression -| so enable only if you are reasonably sure your visitors can handle it. -| -| VERY IMPORTANT: If you are getting a blank page when compression is enabled it -| means you are prematurely outputting something to your browser. It could -| even be a line of whitespace at the end of one of your scripts. For -| compression to work, nothing can be sent before the output buffer is called -| by the output class. Do not 'echo' any values with compression enabled. -| -*/ -$config['compress_output'] = FALSE; - -/* -|-------------------------------------------------------------------------- -| Master Time Reference -|-------------------------------------------------------------------------- -| -| Options are 'local' or 'gmt'. This pref tells the system whether to use -| your server's local time as the master 'now' reference, or convert it to -| GMT. See the 'date helper' page of the user guide for information -| regarding date handling. -| -*/ -$config['time_reference'] = 'local'; - - -/* -|-------------------------------------------------------------------------- -| Rewrite PHP Short Tags -|-------------------------------------------------------------------------- -| -| If your PHP installation does not have short tag support enabled CI -| can rewrite the tags on-the-fly, enabling you to utilize that syntax -| in your view files. Options are TRUE or FALSE (boolean) -| -*/ -$config['rewrite_short_tags'] = FALSE; - - -/* -|-------------------------------------------------------------------------- -| Reverse Proxy IPs -|-------------------------------------------------------------------------- -| -| If your server is behind a reverse proxy, you must whitelist the proxy IP -| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR -| header in order to properly identify the visitor's IP address. -| Comma-delimited, e.g. '10.0.1.200,10.0.1.201' -| -*/ -$config['proxy_ips'] = ''; - - -/* End of file config.php */ -/* Location: ./application/config/config.php */ diff --git a/webht/third_party/trippestOrderSync/config/constants.php b/webht/third_party/trippestOrderSync/config/constants.php deleted file mode 100644 index 4a879d36..00000000 --- a/webht/third_party/trippestOrderSync/config/constants.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); - -/* -|-------------------------------------------------------------------------- -| File and Directory Modes -|-------------------------------------------------------------------------- -| -| These prefs are used when checking and setting modes when working -| with the file system. The defaults are fine on servers with proper -| security, but you may wish (or even need) to change the values in -| certain environments (Apache running a separate process for each -| user, PHP under CGI with Apache suEXEC, etc.). Octal values should -| always be used to set the mode correctly. -| -*/ -define('FILE_READ_MODE', 0644); -define('FILE_WRITE_MODE', 0666); -define('DIR_READ_MODE', 0755); -define('DIR_WRITE_MODE', 0777); - -/* -|-------------------------------------------------------------------------- -| File Stream Modes -|-------------------------------------------------------------------------- -| -| These modes are used when working with fopen()/popen() -| -*/ - -define('FOPEN_READ', 'rb'); -define('FOPEN_READ_WRITE', 'r+b'); -define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care -define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care -define('FOPEN_WRITE_CREATE', 'ab'); -define('FOPEN_READ_WRITE_CREATE', 'a+b'); -define('FOPEN_WRITE_CREATE_STRICT', 'xb'); -define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b'); - - -/* End of file constants.php */ -/* Location: ./application/config/constants.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/database.php b/webht/third_party/trippestOrderSync/config/database.php deleted file mode 100644 index 70f54273..00000000 --- a/webht/third_party/trippestOrderSync/config/database.php +++ /dev/null @@ -1,53 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| DATABASE CONNECTIVITY SETTINGS -| ------------------------------------------------------------------- -| This file will contain the settings needed to access your database. -| -| For complete instructions please consult the 'Database Connection' -| page of the User Guide. -| -| ------------------------------------------------------------------- -| EXPLANATION OF VARIABLES -| ------------------------------------------------------------------- -| -| ['hostname'] The hostname of your database server. -| ['username'] The username used to connect to the database -| ['password'] The password used to connect to the database -| ['database'] The name of the database you want to connect to -| ['dbdriver'] The database type. ie: mysql. Currently supported: - mysql, mysqli, postgre, odbc, mssql, sqlite, oci8 -| ['dbprefix'] You can add an optional prefix, which will be added -| to the table name when using the Active Record class -| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection -| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed. -| ['cache_on'] TRUE/FALSE - Enables/disables query caching -| ['cachedir'] The path to the folder where cache files should be stored -| ['char_set'] The character set used in communicating with the database -| ['dbcollat'] The character collation used in communicating with the database -| NOTE: For MySQL and MySQLi databases, this setting is only used -| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7 -| (and in table creation queries made with DB Forge). -| There is an incompatibility in PHP with mysql_real_escape_string() which -| can make your site vulnerable to SQL injection if you are using a -| multi-byte character set and are running versions lower than these. -| Sites using Latin-1 or UTF-8 database character set and collation are unaffected. -| ['swap_pre'] A default table prefix that should be swapped with the dbprefix -| ['autoinit'] Whether or not to automatically initialize the database. -| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections -| - good for ensuring strict SQL while developing -| -| The $active_group variable lets you choose which connection group to -| make active. By default there is only one group (the 'default' group). -| -| The $active_record variables lets you determine whether or not to load -| the active record class -*/ -$active_group = 'HT'; -$active_record = TRUE; - -require 'c:/database_conn.php'; - -/* End of file database.php */ -/* Location: ./application/config/database.php */ diff --git a/webht/third_party/trippestOrderSync/config/doctypes.php b/webht/third_party/trippestOrderSync/config/doctypes.php deleted file mode 100644 index f7e1d19a..00000000 --- a/webht/third_party/trippestOrderSync/config/doctypes.php +++ /dev/null @@ -1,15 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); - -$_doctypes = array( - 'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">', - 'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">', - 'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">', - 'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">', - 'html5' => '<!DOCTYPE html>', - 'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">', - 'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">', - 'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">' - ); - -/* End of file doctypes.php */ -/* Location: ./application/config/doctypes.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/foreign_chars.php b/webht/third_party/trippestOrderSync/config/foreign_chars.php deleted file mode 100644 index 14b0d737..00000000 --- a/webht/third_party/trippestOrderSync/config/foreign_chars.php +++ /dev/null @@ -1,64 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| Foreign Characters -| ------------------------------------------------------------------- -| This file contains an array of foreign characters for transliteration -| conversion used by the Text helper -| -*/ -$foreign_characters = array( - '/ä|æ|ǽ/' => 'ae', - '/ö|œ/' => 'oe', - '/ü/' => 'ue', - '/Ä/' => 'Ae', - '/Ü/' => 'Ue', - '/Ö/' => 'Oe', - '/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A', - '/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a', - '/Ç|Ć|Ĉ|Ċ|Č/' => 'C', - '/ç|ć|ĉ|ċ|č/' => 'c', - '/Ð|Ď|Đ/' => 'D', - '/ð|ď|đ/' => 'd', - '/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E', - '/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e', - '/Ĝ|Ğ|Ġ|Ģ/' => 'G', - '/ĝ|ğ|ġ|ģ/' => 'g', - '/Ĥ|Ħ/' => 'H', - '/ĥ|ħ/' => 'h', - '/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I', - '/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i', - '/Ĵ/' => 'J', - '/ĵ/' => 'j', - '/Ķ/' => 'K', - '/ķ/' => 'k', - '/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L', - '/ĺ|ļ|ľ|ŀ|ł/' => 'l', - '/Ñ|Ń|Ņ|Ň/' => 'N', - '/ñ|ń|ņ|ň|ʼn/' => 'n', - '/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O', - '/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o', - '/Ŕ|Ŗ|Ř/' => 'R', - '/ŕ|ŗ|ř/' => 'r', - '/Ś|Ŝ|Ş|Š/' => 'S', - '/ś|ŝ|ş|š|ſ/' => 's', - '/Ţ|Ť|Ŧ/' => 'T', - '/ţ|ť|ŧ/' => 't', - '/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U', - '/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u', - '/Ý|Ÿ|Ŷ/' => 'Y', - '/ý|ÿ|ŷ/' => 'y', - '/Ŵ/' => 'W', - '/ŵ/' => 'w', - '/Ź|Ż|Ž/' => 'Z', - '/ź|ż|ž/' => 'z', - '/Æ|Ǽ/' => 'AE', - '/ß/'=> 'ss', - '/IJ/' => 'IJ', - '/ij/' => 'ij', - '/Œ/' => 'OE', - '/ƒ/' => 'f' -); - -/* End of file foreign_chars.php */ -/* Location: ./application/config/foreign_chars.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/hooks.php b/webht/third_party/trippestOrderSync/config/hooks.php deleted file mode 100644 index a4ad2be6..00000000 --- a/webht/third_party/trippestOrderSync/config/hooks.php +++ /dev/null @@ -1,16 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------------- -| Hooks -| ------------------------------------------------------------------------- -| This file lets you define "hooks" to extend CI without hacking the core -| files. Please see the user guide for info: -| -| http://codeigniter.com/user_guide/general/hooks.html -| -*/ - - - -/* End of file hooks.php */ -/* Location: ./application/config/hooks.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/index.html b/webht/third_party/trippestOrderSync/config/index.html deleted file mode 100644 index c942a79c..00000000 --- a/webht/third_party/trippestOrderSync/config/index.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<head> - <title>403 Forbidden</title> -</head> -<body> - -<p>Directory access is forbidden.</p> - -</body> -</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/migration.php b/webht/third_party/trippestOrderSync/config/migration.php deleted file mode 100644 index df42a3ca..00000000 --- a/webht/third_party/trippestOrderSync/config/migration.php +++ /dev/null @@ -1,41 +0,0 @@ -<?php defined('BASEPATH') OR exit('No direct script access allowed'); -/* -|-------------------------------------------------------------------------- -| Enable/Disable Migrations -|-------------------------------------------------------------------------- -| -| Migrations are disabled by default but should be enabled -| whenever you intend to do a schema migration. -| -*/ -$config['migration_enabled'] = FALSE; - - -/* -|-------------------------------------------------------------------------- -| Migrations version -|-------------------------------------------------------------------------- -| -| This is used to set migration version that the file system should be on. -| If you run $this->migration->latest() this is the version that schema will -| be upgraded / downgraded to. -| -*/ -$config['migration_version'] = 0; - - -/* -|-------------------------------------------------------------------------- -| Migrations Path -|-------------------------------------------------------------------------- -| -| Path to your migrations folder. -| Typically, it will be within your application path. -| Also, writing permission is required within the migrations path. -| -*/ -$config['migration_path'] = APPPATH . 'migrations/'; - - -/* End of file migration.php */ -/* Location: ./application/config/migration.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/mimes.php b/webht/third_party/trippestOrderSync/config/mimes.php deleted file mode 100644 index 100f7d44..00000000 --- a/webht/third_party/trippestOrderSync/config/mimes.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| MIME TYPES -| ------------------------------------------------------------------- -| This file contains an array of mime types. It is used by the -| Upload class to help identify allowed file types. -| -*/ - -$mimes = array( 'hqx' => 'application/mac-binhex40', - 'cpt' => 'application/mac-compactpro', - 'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'), - 'bin' => 'application/macbinary', - 'dms' => 'application/octet-stream', - 'lha' => 'application/octet-stream', - 'lzh' => 'application/octet-stream', - 'exe' => array('application/octet-stream', 'application/x-msdownload'), - 'class' => 'application/octet-stream', - 'psd' => 'application/x-photoshop', - 'so' => 'application/octet-stream', - 'sea' => 'application/octet-stream', - 'dll' => 'application/octet-stream', - 'oda' => 'application/oda', - 'pdf' => array('application/pdf', 'application/x-download'), - 'ai' => 'application/postscript', - 'eps' => 'application/postscript', - 'ps' => 'application/postscript', - 'smi' => 'application/smil', - 'smil' => 'application/smil', - 'mif' => 'application/vnd.mif', - 'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'), - 'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'), - 'wbxml' => 'application/wbxml', - 'wmlc' => 'application/wmlc', - 'dcr' => 'application/x-director', - 'dir' => 'application/x-director', - 'dxr' => 'application/x-director', - 'dvi' => 'application/x-dvi', - 'gtar' => 'application/x-gtar', - 'gz' => 'application/x-gzip', - 'php' => 'application/x-httpd-php', - 'php4' => 'application/x-httpd-php', - 'php3' => 'application/x-httpd-php', - 'phtml' => 'application/x-httpd-php', - 'phps' => 'application/x-httpd-php-source', - 'js' => 'application/x-javascript', - 'swf' => 'application/x-shockwave-flash', - 'sit' => 'application/x-stuffit', - 'tar' => 'application/x-tar', - 'tgz' => array('application/x-tar', 'application/x-gzip-compressed'), - 'xhtml' => 'application/xhtml+xml', - 'xht' => 'application/xhtml+xml', - 'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'), - 'mid' => 'audio/midi', - 'midi' => 'audio/midi', - 'mpga' => 'audio/mpeg', - 'mp2' => 'audio/mpeg', - 'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'), - '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' => array('audio/x-wav', 'audio/wave', 'audio/wav'), - 'bmp' => array('image/bmp', 'image/x-windows-bmp'), - 'gif' => 'image/gif', - 'jpeg' => array('image/jpeg', 'image/pjpeg'), - 'jpg' => array('image/jpeg', 'image/pjpeg'), - 'jpe' => array('image/jpeg', 'image/pjpeg'), - 'png' => array('image/png', 'image/x-png'), - 'tiff' => 'image/tiff', - 'tif' => 'image/tiff', - 'css' => 'text/css', - 'html' => 'text/html', - 'htm' => 'text/html', - 'shtml' => 'text/html', - 'txt' => 'text/plain', - 'text' => 'text/plain', - 'log' => array('text/plain', 'text/x-log'), - 'rtx' => 'text/richtext', - 'rtf' => 'text/rtf', - 'xml' => 'text/xml', - 'xsl' => 'text/xml', - 'mpeg' => 'video/mpeg', - 'mpg' => 'video/mpeg', - 'mpe' => 'video/mpeg', - 'qt' => 'video/quicktime', - 'mov' => 'video/quicktime', - 'avi' => 'video/x-msvideo', - 'movie' => 'video/x-sgi-movie', - 'doc' => 'application/msword', - 'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'), - 'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'), - 'word' => array('application/msword', 'application/octet-stream'), - 'xl' => 'application/excel', - 'eml' => 'message/rfc822', - 'json' => array('application/json', 'text/json') - ); - - -/* End of file mimes.php */ -/* Location: ./application/config/mimes.php */ diff --git a/webht/third_party/trippestOrderSync/config/profiler.php b/webht/third_party/trippestOrderSync/config/profiler.php deleted file mode 100644 index f8a5b1a1..00000000 --- a/webht/third_party/trippestOrderSync/config/profiler.php +++ /dev/null @@ -1,17 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------------- -| Profiler Sections -| ------------------------------------------------------------------------- -| This file lets you determine whether or not various sections of Profiler -| data are displayed when the Profiler is enabled. -| Please see the user guide for info: -| -| http://codeigniter.com/user_guide/general/profiling.html -| -*/ - - - -/* End of file profiler.php */ -/* Location: ./application/config/profiler.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/routes.php b/webht/third_party/trippestOrderSync/config/routes.php deleted file mode 100644 index 5f9a5834..00000000 --- a/webht/third_party/trippestOrderSync/config/routes.php +++ /dev/null @@ -1,46 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------------- -| URI ROUTING -| ------------------------------------------------------------------------- -| This file lets you re-map URI requests to specific controller functions. -| -| Typically there is a one-to-one relationship between a URL string -| and its corresponding controller class/method. The segments in a -| URL normally follow this pattern: -| -| example.com/class/method/id/ -| -| In some instances, however, you may want to remap this relationship -| so that a different class/function is called than the one -| corresponding to the URL. -| -| Please see the user guide for complete details: -| -| http://codeigniter.com/user_guide/general/routing.html -| -| ------------------------------------------------------------------------- -| RESERVED ROUTES -| ------------------------------------------------------------------------- -| -| There area two reserved routes: -| -| $route['default_controller'] = 'welcome'; -| -| This route indicates which controller class should be loaded if the -| URI contains no data. In the above example, the "welcome" class -| would be loaded. -| -| $route['404_override'] = 'errors/page_missing'; -| -| This route will tell the Router what URI segments to use if those provided -| in the URL cannot be matched to a valid route. -| -*/ - -$route['default_controller'] = "welcome"; -$route['404_override'] = ''; - - -/* End of file routes.php */ -/* Location: ./application/config/routes.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/smileys.php b/webht/third_party/trippestOrderSync/config/smileys.php deleted file mode 100644 index 25d28b2c..00000000 --- a/webht/third_party/trippestOrderSync/config/smileys.php +++ /dev/null @@ -1,66 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| SMILEYS -| ------------------------------------------------------------------- -| This file contains an array of smileys for use with the emoticon helper. -| Individual images can be used to replace multiple simileys. For example: -| :-) and :) use the same image replacement. -| -| Please see user guide for more info: -| http://codeigniter.com/user_guide/helpers/smiley_helper.html -| -*/ - -$smileys = array( - -// smiley image name width height alt - - ':-)' => array('grin.gif', '19', '19', 'grin'), - ':lol:' => array('lol.gif', '19', '19', 'LOL'), - ':cheese:' => array('cheese.gif', '19', '19', 'cheese'), - ':)' => array('smile.gif', '19', '19', 'smile'), - ';-)' => array('wink.gif', '19', '19', 'wink'), - ';)' => array('wink.gif', '19', '19', 'wink'), - ':smirk:' => array('smirk.gif', '19', '19', 'smirk'), - ':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'), - ':-S' => array('confused.gif', '19', '19', 'confused'), - ':wow:' => array('surprise.gif', '19', '19', 'surprised'), - ':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'), - ':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'), - '%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'), - ';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'), - ':P' => array('raspberry.gif', '19', '19', 'raspberry'), - ':blank:' => array('blank.gif', '19', '19', 'blank stare'), - ':long:' => array('longface.gif', '19', '19', 'long face'), - ':ohh:' => array('ohh.gif', '19', '19', 'ohh'), - ':grrr:' => array('grrr.gif', '19', '19', 'grrr'), - ':gulp:' => array('gulp.gif', '19', '19', 'gulp'), - '8-/' => array('ohoh.gif', '19', '19', 'oh oh'), - ':down:' => array('downer.gif', '19', '19', 'downer'), - ':red:' => array('embarrassed.gif', '19', '19', 'red face'), - ':sick:' => array('sick.gif', '19', '19', 'sick'), - ':shut:' => array('shuteye.gif', '19', '19', 'shut eye'), - ':-/' => array('hmm.gif', '19', '19', 'hmmm'), - '>:(' => array('mad.gif', '19', '19', 'mad'), - ':mad:' => array('mad.gif', '19', '19', 'mad'), - '>:-(' => array('angry.gif', '19', '19', 'angry'), - ':angry:' => array('angry.gif', '19', '19', 'angry'), - ':zip:' => array('zip.gif', '19', '19', 'zipper'), - ':kiss:' => array('kiss.gif', '19', '19', 'kiss'), - ':ahhh:' => array('shock.gif', '19', '19', 'shock'), - ':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'), - ':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'), - ':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'), - ':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'), - ':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'), - ':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'), - ':vampire:' => array('vampire.gif', '19', '19', 'vampire'), - ':snake:' => array('snake.gif', '19', '19', 'snake'), - ':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'), - ':question:' => array('question.gif', '19', '19', 'question') // no comma after last item - - ); - -/* End of file smileys.php */ -/* Location: ./application/config/smileys.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/config/user_agents.php b/webht/third_party/trippestOrderSync/config/user_agents.php deleted file mode 100644 index e2d3c3af..00000000 --- a/webht/third_party/trippestOrderSync/config/user_agents.php +++ /dev/null @@ -1,178 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); -/* -| ------------------------------------------------------------------- -| USER AGENT TYPES -| ------------------------------------------------------------------- -| This file contains four arrays of user agent data. It is used by the -| User Agent Class to help identify browser, platform, robot, and -| mobile device data. The array keys are used to identify the device -| and the array values are used to set the actual name of the item. -| -*/ - -$platforms = array ( - 'windows nt 6.0' => 'Windows Longhorn', - 'windows nt 5.2' => 'Windows 2003', - 'windows nt 5.0' => 'Windows 2000', - 'windows nt 5.1' => 'Windows XP', - 'windows nt 4.0' => 'Windows NT 4.0', - 'winnt4.0' => 'Windows NT 4.0', - 'winnt 4.0' => 'Windows NT', - 'winnt' => 'Windows NT', - 'windows 98' => 'Windows 98', - 'win98' => 'Windows 98', - 'windows 95' => 'Windows 95', - 'win95' => 'Windows 95', - 'windows' => 'Unknown Windows OS', - 'os x' => 'Mac OS X', - 'ppc mac' => 'Power PC Mac', - 'freebsd' => 'FreeBSD', - 'ppc' => 'Macintosh', - 'linux' => 'Linux', - 'debian' => 'Debian', - 'sunos' => 'Sun Solaris', - 'beos' => 'BeOS', - 'apachebench' => 'ApacheBench', - 'aix' => 'AIX', - 'irix' => 'Irix', - 'osf' => 'DEC OSF', - 'hp-ux' => 'HP-UX', - 'netbsd' => 'NetBSD', - 'bsdi' => 'BSDi', - 'openbsd' => 'OpenBSD', - 'gnu' => 'GNU/Linux', - 'unix' => 'Unknown Unix OS' - ); - - -// The order of this array should NOT be changed. Many browsers return -// multiple browser types so we want to identify the sub-type first. -$browsers = array( - 'Flock' => 'Flock', - 'Chrome' => 'Chrome', - 'Opera' => 'Opera', - 'MSIE' => 'Internet Explorer', - 'Internet Explorer' => 'Internet Explorer', - 'Shiira' => 'Shiira', - 'Firefox' => 'Firefox', - 'Chimera' => 'Chimera', - 'Phoenix' => 'Phoenix', - 'Firebird' => 'Firebird', - 'Camino' => 'Camino', - 'Netscape' => 'Netscape', - 'OmniWeb' => 'OmniWeb', - 'Safari' => 'Safari', - 'Mozilla' => 'Mozilla', - 'Konqueror' => 'Konqueror', - 'icab' => 'iCab', - 'Lynx' => 'Lynx', - 'Links' => 'Links', - 'hotjava' => 'HotJava', - 'amaya' => 'Amaya', - 'IBrowse' => 'IBrowse' - ); - -$mobiles = array( - // legacy array, old values commented out - 'mobileexplorer' => 'Mobile Explorer', -// 'openwave' => 'Open Wave', -// 'opera mini' => 'Opera Mini', -// 'operamini' => 'Opera Mini', -// 'elaine' => 'Palm', - 'palmsource' => 'Palm', -// 'digital paths' => 'Palm', -// 'avantgo' => 'Avantgo', -// 'xiino' => 'Xiino', - 'palmscape' => 'Palmscape', -// 'nokia' => 'Nokia', -// 'ericsson' => 'Ericsson', -// 'blackberry' => 'BlackBerry', -// 'motorola' => 'Motorola' - - // Phones and Manufacturers - 'motorola' => "Motorola", - 'nokia' => "Nokia", - 'palm' => "Palm", - 'iphone' => "Apple iPhone", - 'ipad' => "iPad", - 'ipod' => "Apple iPod Touch", - 'sony' => "Sony Ericsson", - 'ericsson' => "Sony Ericsson", - 'blackberry' => "BlackBerry", - 'cocoon' => "O2 Cocoon", - 'blazer' => "Treo", - 'lg' => "LG", - 'amoi' => "Amoi", - 'xda' => "XDA", - 'mda' => "MDA", - 'vario' => "Vario", - 'htc' => "HTC", - 'samsung' => "Samsung", - 'sharp' => "Sharp", - 'sie-' => "Siemens", - 'alcatel' => "Alcatel", - 'benq' => "BenQ", - 'ipaq' => "HP iPaq", - 'mot-' => "Motorola", - 'playstation portable' => "PlayStation Portable", - 'hiptop' => "Danger Hiptop", - 'nec-' => "NEC", - 'panasonic' => "Panasonic", - 'philips' => "Philips", - 'sagem' => "Sagem", - 'sanyo' => "Sanyo", - 'spv' => "SPV", - 'zte' => "ZTE", - 'sendo' => "Sendo", - - // Operating Systems - 'symbian' => "Symbian", - 'SymbianOS' => "SymbianOS", - 'elaine' => "Palm", - 'palm' => "Palm", - 'series60' => "Symbian S60", - 'windows ce' => "Windows CE", - - // Browsers - 'obigo' => "Obigo", - 'netfront' => "Netfront Browser", - 'openwave' => "Openwave Browser", - 'mobilexplorer' => "Mobile Explorer", - 'operamini' => "Opera Mini", - 'opera mini' => "Opera Mini", - - // Other - 'digital paths' => "Digital Paths", - 'avantgo' => "AvantGo", - 'xiino' => "Xiino", - 'novarra' => "Novarra Transcoder", - 'vodafone' => "Vodafone", - 'docomo' => "NTT DoCoMo", - 'o2' => "O2", - - // Fallback - 'mobile' => "Generic Mobile", - 'wireless' => "Generic Mobile", - 'j2me' => "Generic Mobile", - 'midp' => "Generic Mobile", - 'cldc' => "Generic Mobile", - 'up.link' => "Generic Mobile", - 'up.browser' => "Generic Mobile", - 'smartphone' => "Generic Mobile", - 'cellphone' => "Generic Mobile" - ); - -// There are hundreds of bots but these are the most common. -$robots = array( - 'googlebot' => 'Googlebot', - 'msnbot' => 'MSNBot', - 'slurp' => 'Inktomi Slurp', - 'yahoo' => 'Yahoo', - 'askjeeves' => 'AskJeeves', - 'fastcrawler' => 'FastCrawler', - 'infoseek' => 'InfoSeek Robot 1.0', - 'lycos' => 'Lycos' - ); - -/* End of file user_agents.php */ -/* Location: ./application/config/user_agents.php */ \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 3205a081..c74aad8d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -36,9 +36,9 @@ class TulanduoApi extends CI_Controller // test - // public $list_url = "http://djdebug.ltsoftware.net:19919/action/api/searchRouteOrder/"; - // public $detail_url = "http://djdebug.ltsoftware.net:19919/action/api/detailRouteOrder/"; - public $neworder_url = "http://djdebug.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/"; + // public $list_url = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/"; + // public $detail_url = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/"; + public $neworder_url = "http://dj.ltsoftware.net:9901/action/api/addOrUpdateRouteOrder/"; // Live public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; @@ -109,6 +109,7 @@ class TulanduoApi extends CI_Controller $order_to_HT = array_filter(array_merge($order_to_HT, $f_order_to_HT)); $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); } + $cnt = 0; foreach ($all_list as $k => $vo) { $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 // get order detail @@ -137,8 +138,9 @@ class TulanduoApi extends CI_Controller $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); $COLD_MemoText = json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); - $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = null; - if (in_array($vo['agcName'], array("D目的地桂林组"))) { + $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; + $this->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 + if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $tmp_groupCode = explode("-", $vo['agcOrderNo']); $real_groupCode = $tmp_groupCode[0] . "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; @@ -148,25 +150,36 @@ class TulanduoApi extends CI_Controller } /** insert HT */ if ($this->Orders_model->BIZ_COLI_SN === null) { - // BIZ_Guest + /** BIZ_Guest */ $this->Orders_model->GUT_LastName = $vo['customerName']; - // $this->Orders_model->GUT_Passport = $detail_jsonResp->orderDetail->customers[0]->documentNo; $this->Orders_model->biz_guest_save(); - // BIZ_ConfirmLineInfo + /** GRoupInfo */ + $travelDate = new DateTime($vo['travelDate']); + $leaveDate = new DateTime($vo['leaveDate']); + $date_diff = $travelDate->diff($leaveDate); + $this->Orders_model->GRI_No = $vo['agcOrderNo']; + $this->Orders_model->GRI_OrderType = 227002; // 商务 + $this->Orders_model->GRI_Name = ""; + $this->Orders_model->GRI_PersonNum = $vo['adultNum']+$vo['childNum']; + $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); + $this->Orders_model->GRI_IsCancel = 0; + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->groupinfo_save(); + /*BIZ_ConfirmLineInfo*/ + $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; + $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_No : ""; $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); $this->Orders_model->BIZ_COLI_ApplyDate = $vo['orderDate']; $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$vo['operationDep']]) ? 32090 : $this->city_info[$vo['operationDep']]['COLI_sourcetype']; - $this->Orders_model->BIZ_COLI_State = $vo['orderStatus']==1 ? 7 : 4;; + $this->Orders_model->BIZ_COLI_State = $vo['orderStatus'] == 1 ? 7 : 4; $this->Orders_model->BIZ_COLI_servicetype = 'D'; $this->Orders_model->BIZ_COLI_ConfirmType = 52001; $this->Orders_model->BIZ_COLI_Memo = ""; - $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName'];//. $allDetails_to_HT; - $this->Orders_model->BIZ_COLI_GroupCode = $vo['agcOrderNo'] ? $vo['agcOrderNo'] : ''; - // $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $coli_sn[] = $this->Orders_model->biz_confirm_save(); - // BIZ_ConfirmLineDetail + /*BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; $this->Orders_model->COLD_ServiceType = "D"; $this->Orders_model->COLD_ServiceSN = $serviceSN; @@ -178,32 +191,36 @@ class TulanduoApi extends CI_Controller $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认(已收款) // 4 下计划未确认(已收款) $this->Orders_model->DeleteFlag = 0; $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; - // $this->Orders_model->COLD_Memo = isset($detail_jsonResp->orderDetail->orderRemark) ? $detail_jsonResp->orderDetail->orderRemark : ''; $this->Orders_model->COLD_MemoText = $COLD_MemoText; $this->Orders_model->biz_confirm_detail_save(); + $cnt++; + } + if ($this->Orders_model->GCI_SN === null) { + /*biz_groupcombineinfo*/ + $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; + $this->Orders_model->GCI_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; + $this->Orders_model->GCI_FromAgc = $vo['agcName']; + $this->Orders_model->GCI_groupType = $vo['orderType']; + $this->Orders_model->GCI_travelDate = $vo['travelDate']; + $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; + $this->Orders_model->GCI_createTime = $vo['orderDate']; + $this->Orders_model->biz_groupcombineinfo_save(); } - // biz_groupcombineinfo - $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; - $this->Orders_model->GCI_COLI_SN = $this->Orders_model->BIZ_COLI_SN; - $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; - $this->Orders_model->GCI_FromAgc = $vo['agcName']; - $this->Orders_model->GCI_groupType = $vo['orderType']; - $this->Orders_model->GCI_travelDate = $vo['travelDate']; - $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; - $this->Orders_model->GCI_createTime = $vo['orderDate']; - $this->Orders_model->biz_groupcombineinfo_save(); } - echo "Got order list from 图兰朵. count: " . $resp_arr["responseData"]["totalRows"]; + echo "Got order list from 图兰朵. count: " . $resp_arr["responseData"]["totalRows"] . "\r\n"; + echo "Insert COLI : " . $cnt . "\r\n"; return; } public function update_HT_order_operation($coli_sn=null) { + $this->load->model('Orders_update'); if ($coli_sn !== null) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); } else { $startDate = date('Y-m-d'); - $endDate = date('Y-m-d', strtotime("+1 days")); + $endDate = date('Y-m-d', strtotime("+1 days")); // test // $endDate = date('Y-m-d', strtotime("+4 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); } @@ -222,27 +239,25 @@ class TulanduoApi extends CI_Controller $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; } /** HT 开始 */ - // GRoupInfo todo 写入报错 - if ($order->COLI_GRI_SN == null) { - $travelDate = new DateTime($detail_jsonResp->orderDetail->travelDate); - $leaveDate = new DateTime($detail_jsonResp->orderDetail->leaveDate); - $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->BIZ_COLI_SN = $order->GCI_COLI_SN; - - $this->Orders_model->GRI_No = $detail_jsonResp->orderDetail->agcOrderNo; - $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = ""; - $this->Orders_model->GRI_PersonNum = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; - $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); - $this->Orders_model->GRI_IsCancel = 0; - $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->groupinfo_save(); - // update COLI - $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN; - $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_No; - $this->Orders_model->update_confirmLineInfo(); - } - // BIZ_BookPeople + /** UPDATE */ + /** BIZ_ConfirmLineInfo */ + $this->Orders_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; + $coli_update_column = array( + "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark + ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" // 调度信息加上以便在HT界面上显示 todo + ); + $this->Orders_update->biz_confirmlineinfo_update($coli_update_column); + /** BIZ_ConfirmLineDetail */ // nothing to update + /** biz_groupcombineinfo */ + $this->Orders_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; + $gci_update_column = array( + "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo + ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate + ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate + ); + $this->Orders_update->biz_groupcombineinfo_update($gci_update_column); + /** INSERT */ + /*BIZ_BookPeople*/ foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { $this->Orders_model->BPE_FirstName = $vd->name; $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; @@ -251,7 +266,7 @@ class TulanduoApi extends CI_Controller // BIZ_BookPeopleList $this->Orders_model->biz_bookpeople_List_save($order->COLD_SN, $this->Orders_model->BPE_SN); } - // BIZ_PackageOrderInfo + /*BIZ_PackageOrderInfo*/ $this->Orders_model->POI_COLD_SN = $order->COLD_SN; $this->Orders_model->POI_Time = $detail_jsonResp->orderDetail->travelDate; $this->Orders_model->POI_Hotel = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation; @@ -260,7 +275,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->POI_EndTime = $detail_jsonResp->orderDetail->leaveDate; $this->Orders_model->POI_QuotationType = 1; // 1 报价 2 网络支付价 3 促销价 $this->Orders_model->biz_packageorder_save(); - // BIZ_GroupCombineOperationDetail + /*BIZ_GroupCombineOperationDetail*/ // 门票 if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations) && empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "sceneryOperations")) ) { @@ -352,7 +367,8 @@ class TulanduoApi extends CI_Controller } public function order_push($COLI_ID='170809390') // test - {exit(); + { + // exit(); /** test */ $this->userId = "358"; $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -362,15 +378,15 @@ class TulanduoApi extends CI_Controller $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ; $guestlist = $this->Orders_model->get_guestlist($COLD_SN_str); $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str); - $routeName = $this->special_route_name[$scheduleDetails[0]->PAG_Code] ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; - if ($this->special_route[$scheduleDetails[0]->PAG_Code]) { + $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; + if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); } $travelFees = $this->Orders_model->get_paymentDetails($COLI_ID); bcscale(4); $this->tldOrderBuilder->setUserId($this->userId) ->setKey($this->key) - ->setOrderType(1) + ->setOrderType(2) // todo ->setRouteName($routeName) ->setRouteType("北京目的地线路") // todo ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode) @@ -382,9 +398,9 @@ class TulanduoApi extends CI_Controller foreach ($guestlist as $key => $vg) { $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) - ->setCustomersDocumentType($key, "Passport No.") + ->setCustomersDocumentType($key, "护照") // Passport No. ->setCustomersDocumentNo($key, $vg->BPE_Passport) - ->setCustomersOtherInfo($key, ""); + ->setCustomersOtherInfo($key, $this->Orders_model->GetNationalityName($orderinfo[0]->GUT_NationalityID)); } foreach ($scheduleDetails as $ks => $vs) { $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title) @@ -403,10 +419,15 @@ class TulanduoApi extends CI_Controller ->setTravelFeesRemark($kf, $vf->GAI_Memo); } $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; - $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; - $this->Orders_model->GCI_VendorOrderId = json_decode($rsp)->responseData->orderId; - $this->Orders_model->biz_groupcombineinfo_save(); + /** BIZ_GroupCombineInfo */ + if (json_decode($resp)->status == 1) { +log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); + $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; + $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; + $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; + $this->Orders_model->GCI_FromAgc = ""; + $this->Orders_model->biz_groupcombineinfo_save(); + } return; } diff --git a/webht/third_party/trippestOrderSync/logs/index.html b/webht/third_party/trippestOrderSync/logs/index.html deleted file mode 100644 index c942a79c..00000000 --- a/webht/third_party/trippestOrderSync/logs/index.html +++ /dev/null @@ -1,10 +0,0 @@ -<html> -<head> - <title>403 Forbidden</title> -</head> -<body> - -<p>Directory access is forbidden.</p> - -</body> -</html> \ No newline at end of file diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php b/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php deleted file mode 100644 index ebca2fb8..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-03-22.php +++ /dev/null @@ -1,2 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php b/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php deleted file mode 100644 index 47b639be..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-03-30.php +++ /dev/null @@ -1,118 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-03-30 16:18:22 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]在将 nvarchar 值 'HT080828004' 转换成数据类型 int 时失败。 @:SELECT coli.COLI_ID, - coli.COLI_Department, - cold.COLD_ServiceSN, - cold.COLD_ServiceSN2, - cold.COLD_ServiceCity, - * - FROM BIZ_ConfirmLineInfo coli - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE coli.COLI_ID=170809474 - ORDER BY COLI_ApplyDate DESC -ERROR - 2018-03-30 16:29:57 --> Severity: Warning --> Missing argument 1 for Orders_model::get_guestlist(), called in D:\workspace\trippest\application\controllers\TulanduoApi.php on line 38 and defined D:\workspace\trippest\application\models\orders_model.php 47 -ERROR - 2018-03-30 16:29:57 --> Severity: Notice --> Undefined variable: COLD_SN_str D:\workspace\trippest\application\models\orders_model.php 52 -ERROR - 2018-03-30 16:29:57 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:31:50 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:32:25 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:33:17 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:33:51 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:34:07 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:35:09 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:35:26 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN () -ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:35:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:36:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:38:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:44:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 -ERROR - 2018-03-30 16:58:10 --> Severity: 4096 --> Object of class TulanduoApi could not be converted to string D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Object of class TulanduoApi to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Undefined variable: Object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:10 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 -ERROR - 2018-03-30 16:58:41 --> Severity: 4096 --> Object of class TulanduoApi could not be converted to string D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Object of class TulanduoApi to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Undefined variable: Object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:41 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 65 -ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 71 -ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:58:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 16:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:01:27 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:02:44 --> Severity: Notice --> Undefined property: stdClass::$orderData D:\workspace\trippest\application\controllers\TulanduoApi.php 73 -ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:02:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:03:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:09:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:21:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:23:17 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 86 -ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:24:50 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:26:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:27:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-03-30 17:28:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php deleted file mode 100644 index 7e38da29..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-02.php +++ /dev/null @@ -1,106 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> Creating default object from empty value D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:17:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:21:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 09:22:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:30:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:40:45 --> curl error code: 出游时间[travelDate]格式有误!; curl postBodyString: {"jsonParams":"{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"orderType\":2,\"routeName\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38\",\"routeType\":\"\\u5317\\u4eac\\u76ee\\u7684\\u5730\\u7ebf\\u8def\",\"agcOrderNo\":\"CHBJ171223-BWM170809474\",\"adultNum\":2,\"childNum\":0,\"destination\":\"\\u5317\\u4eac\",\"travelDate\":\"2017-12-23 00:00:00\",\"leavedDate\":\"2017-12-23 08:00:00\",\"customers\":[{\"name\":\"SHINTAKU\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"523429066\",\"otherInfo\":\"\\u6027\\u522b\"},{\"name\":\"PROMSIRI\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"461694068\",\"otherInfo\":\"\\u6027\\u522b\"}],\"scheduleDetails\":[{\"content\":\"7:30 - 11:00\\uff1a \\u9152\\u5e97\\u63a5\\u5ba2\\u4eba\\uff0c\\u6e38\\u89c8\\u9890\\u548c\\u56ed\\uff1b\\r\\n11:20 \\u2013 11:40\\uff1a\\u53c2\\u89c2\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\uff1b\\r\\n12:00 - 13:00\\uff1a \\u5728\\u5927\\u7897\\u5c45\\u5348\\u9910\\uff1b\\r\\n13:30 - 14:10\\uff1a \\u6e38\\u89c8\\u666f\\u5c71\\u516c\\u56ed\\uff1b\\r\\n14:30 - 16:10\\uff1a \\u6e38\\u89c8\\u5929\\u575b\\uff1b\\r\\n16:30 - 17:30\\uff1a\\u9001\\u9152\\u5e97\\u3002\",\"title\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38 \\uff08\\u7b2c\\u4e8c\\u5929\\uff0c\\u9890\\u548c\\u56ed\\u3001\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\u3001\\u5348\\u9910\\u3001\\u666f\\u5c71\\u3001\\u5929\\u575b\\uff09\",\"breakFirst\":0,\"lunch\":1,\"dinner\":0}]}}","notHander":"1"} -ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:40:45 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:42:51 --> curl error code: 出游时间[travelDate]格式有误!; curl postBodyString: {"jsonParams":"{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"orderType\":2,\"routeName\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38\",\"routeType\":\"\\u5317\\u4eac\\u76ee\\u7684\\u5730\\u7ebf\\u8def\",\"agcOrderNo\":\"CHBJ171223-BWM170809474\",\"adultNum\":2,\"childNum\":0,\"destination\":\"\\u5317\\u4eac\",\"travelDate\":\" 00:00:00\",\"leavedDate\":\" 08:00:00\",\"customers\":[{\"name\":\"SHINTAKU\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"523429066\",\"otherInfo\":\"\\u6027\\u522b\"},{\"name\":\"PROMSIRI\",\"peopleType\":1,\"documentType\":\"\\u62a4\\u7167\",\"documenNo\":\"461694068\",\"otherInfo\":\"\\u6027\\u522b\"}],\"scheduleDetails\":[{\"content\":\"7:30 - 11:00\\uff1a \\u9152\\u5e97\\u63a5\\u5ba2\\u4eba\\uff0c\\u6e38\\u89c8\\u9890\\u548c\\u56ed\\uff1b\\r\\n11:20 \\u2013 11:40\\uff1a\\u53c2\\u89c2\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\uff1b\\r\\n12:00 - 13:00\\uff1a \\u5728\\u5927\\u7897\\u5c45\\u5348\\u9910\\uff1b\\r\\n13:30 - 14:10\\uff1a \\u6e38\\u89c8\\u666f\\u5c71\\u516c\\u56ed\\uff1b\\r\\n14:30 - 16:10\\uff1a \\u6e38\\u89c8\\u5929\\u575b\\uff1b\\r\\n16:30 - 17:30\\uff1a\\u9001\\u9152\\u5e97\\u3002\",\"title\":\"(\\u5317\\u4eac\\u56fe\\u5170\\u6735)\\u5317\\u4eac\\u7cbe\\u54c1\\u4e24\\u65e5\\u6e38 \\uff08\\u7b2c\\u4e8c\\u5929\\uff0c\\u9890\\u548c\\u56ed\\u3001\\u9e1f\\u5de2\\u6c34\\u7acb\\u65b9\\u5916\\u89c2\\u3001\\u5348\\u9910\\u3001\\u666f\\u5c71\\u3001\\u5929\\u575b\\uff09\",\"breakFirst\":0,\"lunch\":1,\"dinner\":0}]}}","notHander":"1"} -ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:42:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:43:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 10:48:46 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:08:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:16:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:50:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:52:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:53:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:55:20 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:56:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 11:59:51 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 12:09:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:01:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 16:03:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:55:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 17:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-02 18:13:17 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php deleted file mode 100644 index 67a4bf46..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-03.php +++ /dev/null @@ -1,676 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 12:03:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:16 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 42 -ERROR - 2018-04-03 13:55:16 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 43 -ERROR - 2018-04-03 13:55:16 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} -ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:44 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 43 -ERROR - 2018-04-03 13:55:44 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 44 -ERROR - 2018-04-03 13:55:44 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} -ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:55:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:05 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 44 -ERROR - 2018-04-03 13:56:05 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 45 -ERROR - 2018-04-03 13:56:05 --> get_orderlist failed. Msg:; Request: {"userId":"358","key":"a08f26ddc5b1bd4c8e5eafcac28fc1ec","startOrderDate":"2018-04-01","endOrderDate":"2018-04-04"} -ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:56:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 13:58:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:10:41 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:11:02 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:11:02 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]')' 附近有语法错误。 @:SELECT COLI_GroupCode - FROM BIZ_ConfirmLineInfo coli - WHERE coli.COLI_GroupCode IN () -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> array_map(): Argument #2 should be an array D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:11:30 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:00 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:12:00 --> Severity: Notice --> Trying to get property of non-object D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:00 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 47 -ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:47 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:12:47 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:31 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:14:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:15:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:20:55 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 -ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:20:55 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:15 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 -ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:59 --> Severity: Notice --> Undefined offset: 0 D:\workspace\trippest\application\controllers\TulanduoApi.php 52 -ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:21:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:42 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Notice --> Array to string conversion D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:28:43 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> Missing argument 2 for TulanduoApi::{closure}() D:\workspace\trippest\application\controllers\TulanduoApi.php 53 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: k D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:32:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Notice --> Undefined variable: GroupCode_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> array_keys() expects parameter 1 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> in_array() expects parameter 2 to be array, null given D:\workspace\trippest\application\controllers\TulanduoApi.php 54 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:33:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:47:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:47:23 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:48:49 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:48:49 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:12 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:53 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:49:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:51:12 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:51:12 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:52:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:52:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:18 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:54:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:55:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:55:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:56:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:56:29 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:57:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:57:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:58:33 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:58:33 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 60 -ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:58:33 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:15 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:34 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 14:59:53 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 15:00:15 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 15:00:15 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:22 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:43:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:44:34 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 16:44:34 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:03:05 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:03:05 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_OriginalText -) -VALUES -( - '180403006', - NULL, - 2, - NULL, - NULL, - 0, - NULL, - NULL, - NULL, - NNULL, - '', - 'D', - 32090, - 52001, - 9, - 30, - '15227461856300', - '62001', - '北京精品两日游(目的地) -', - NULL, - N -ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:04:46 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:04:46 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_OriginalText -) -VALUES -( - '180403012', - NULL, - 2, - NULL, - NULL, - 0, - NULL, - NULL, - '北京精品两日游(目的地) -', - NNULL, - '', - 'D', - 32090, - 52001, - 9, - 30, - '15227462867070', - '62001', - '北京精品两日游(目的地) -', - NULL, - N -ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:06:04 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:06:04 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_OriginalText -) -VALUES -( - '180403018', - NULL, - 2, - NULL, - NULL, - 0, - NULL, - NULL, - '北京精品两日游(目的地) -', - N'', - '', - 'D', - 32090, - 52001, - 9, - 30, - '15227463643910', - '62001', - '北京精品两日游(目的地) -', - NULL, - N -ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:07:11 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:07:11 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'N' 附近有语法错误。 @:INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_OriginalText -) -VALUES -( - '180403024', - NULL, - 2, - NULL, - NULL, - 0, - NULL, - NULL, - '北京精品两日游(目的地) -', - N'', - '', - 'D', - 32090, - 52001, - 9, - 30, - '15227464314580', - '62001', - '北京精品两日游(目的地) -', - NULL, - N -ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:18:27 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:18:27 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_OriginalText -) -VALUES -( - '180403030', - NULL, - 2, - NULL, - NULL, - NULL, - 0, - NULL, - NULL, - N'北京精品两日游(目的地) -', - '', - '', - 'D', - 32090, - 52001, - 9, - 30, - '15227471078350', - '62001', - '北京精品两日游(目的地) -', - NNULL -) -ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:18:57 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:18:58 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:18:58 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 62 -ERROR - 2018-04-03 17:20:32 --> Severity: Notice --> Undefined index: orderRemark D:\workspace\trippest\application\controllers\TulanduoApi.php 63 -ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-03 17:20:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php deleted file mode 100644 index 2edf3a47..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-04.php +++ /dev/null @@ -1,260 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-04 09:12:13 --> Severity: Notice --> Undefined index: orderTime D:\workspace\trippest\application\controllers\TulanduoApi.php 58 -ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:12:13 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:13:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 09:13:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:45:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:45:57 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:45:57 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,GRI_OrderType) - VALUES (NNULL,NNULL,NULL,NULL,0,NULL) -ERROR - 2018-04-04 10:47:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:47:02 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:47:02 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'NNULL' 无效。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,GRI_OrderType) - VALUES (NNULL,NNULL,NULL,NULL,0,NULL) -ERROR - 2018-04-04 10:47:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:47:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:47:52 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]不能将值 NULL 插入列 'DeleteFlag',表 'tourmanager.dbo.GRoupInfo';列不允许有 Null 值。INSERT 失败。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,GRI_OrderType) - VALUES (N'CHBJ170823-BHX170809390-1',N'CHBJ170823-BHX170809390-1',2,1,0,227002) -ERROR - 2018-04-04 10:49:16 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:49:16 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:49:16 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]INSERT 语句中列的数目大于 VALUES 子句中指定的值的数目。VALUES 子句中值的数目必须与 INSERT 语句中指定的列的数目匹配。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N'CHBJ170823-BHX170809390-1',N'CHBJ170823-BHX170809390-1',2,1,0,0) -ERROR - 2018-04-04 10:49:55 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:49:55 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:49:55 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'CHBJ170823' 无效。 @:select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No=CHBJ170823-BHX170809390-1 -ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:50:41 --> Severity: Notice --> Undefined property: TulanduoApi::$GRI_SN D:\workspace\trippest\application\controllers\TulanduoApi.php 73 -ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:50:41 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:54:24 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:54:24 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:54:24 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:55:37 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:55:37 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:55:37 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:56:28 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:56:28 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:56:28 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:59:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:59:03 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 10:59:03 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:00:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:00:10 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:00:10 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:07:14 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:07:14 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:07:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:09:25 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:09:25 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:09:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 57 -ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 59 -ERROR - 2018-04-04 11:12:44 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 73 -ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:12:44 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 57 -ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 59 -ERROR - 2018-04-04 11:16:06 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 73 -ERROR - 2018-04-04 11:16:06 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 11:16:52 --> Severity: Notice --> Undefined variable: ss D:\workspace\trippest\application\controllers\TulanduoApi.php 82 -ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 11:16:52 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:12:26 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:12:26 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:13:56 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:13:56 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:13:56 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:17:23 --> Severity: Notice --> Undefined variable: today_obj D:\workspace\trippest\application\controllers\TulanduoApi.php 61 -ERROR - 2018-04-04 15:18:00 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:18:00 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:01 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:39 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:18:39 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:18:39 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:28:48 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:28:48 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 15:28:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:29 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:54 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:27:59 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:31:05 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:31:05 --> tag475000826 -ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:31:05 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:32:32 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:32:32 --> tag475000827 -ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:32:32 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:35:21 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:35:21 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]拒绝了对对象 'BIZ_GUEST' (数据库 'Tourmanager',架构 'dbo')的 INSERT 权限。 @:INSERT INTO BIZ_Guest - ( - GUT_FirstName, - GUT_LastName, - GUT_Title, - GUT_Email, - GUT_Email2, - GUT_NationalityID, - GUT_Passport, - GUT_TEL, - GUT_MoveTel, - GUT_AddCode, - GUT_CreateDate - ) -VALUES - ( - N'', - N'Ms. Dana Schwanz', - NULL, - NULL, - NULL, - NULL, - '471756661', - NULL, - NULL, - '15228309213330', - GETDATE() - ) -ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:43:35 --> Severity: Notice --> Undefined index: agcOrderNo D:\workspace\trippest\application\controllers\TulanduoApi.php 48 -ERROR - 2018-04-04 16:43:35 --> tag475000828 -ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-04 16:43:35 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php deleted file mode 100644 index e6e505fb..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-08.php +++ /dev/null @@ -1,163 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-08 15:57:06 --> array ( - 0 => 'T180405-BHJ180331588-D2', - 1 => 'T180405-BHJ180331588-D1', - 2 => 'T180412-BHJ180331474', - 3 => 'CHBJ180411-BHJ180331354 ', - 4 => 'CHBJ180416-BHJ180331486', - 5 => 'CHBJ180417-BHJ180331025M (BR-648698597)', - 6 => 'CHBJ180526-BHJ180331450', - 7 => 'CHBJ180405-BHJ180401102', - 8 => 'CHBJ180502-BTM180402019M(BR-648875768 )', - 9 => 'CHBJ180420-BTM180402025M(BR-648943709)', - 10 => 'T180403-BTM180402037M(GYG32384328)', - 11 => 'CHBJ180404-BTM180402102', - 12 => 'CHBJ180405-BTM180402420', - 13 => 'CHBJ180408-BTM180403001M(BR-649017533)', - 14 => 'CHBJ180411-BTM180403025M(BR-649019688)', - 15 => 'CHBJ180404-BTM180402918', - 16 => 'CHBJ180421-BTM180403031M(BR-648429882)', - 17 => 'CHBJ180407-BTM180403049M(BR-649133991)', - 18 => 'CHBJ180427-BTM180402690', - 19 => 'CHBJ180622-BTM180403037M(BR-649040809)', -) -ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_Guest - ( - GUT_FirstName, - GUT_LastName, - GUT_Title, - GUT_Email, - GUT_Email2, - GUT_NationalityID, - GUT_Passport, - GUT_TEL, - GUT_MoveTel, - GUT_AddCode, - GUT_CreateDate - ) -VALUES - ( - N'', - N'LAI TIEN CHIN ', - NULL, - NULL, - NULL, - NULL, - 'A34204892', - NULL, - NULL, - '15231742268330', - GETDATE() - ) -ERROR - 2018-04-08 15:57:06 --> INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N'T180405-BHJ180331588-D2',N'T180405-BHJ180331588-D2',3,1,0,0,227002) -ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_ConfirmLineInfo -( - COLI_ID, - COLI_GUT_SN, - COLI_Area, - COLI_ApplyDate, - COLI_Price, - COLI_Cost, - COLI_Currency, - COLI_TrueCardRate, - COLI_AgencyID, - COLI_OrderDetailText, - COLI_SenderIP, - COLI_WebCode, - COLI_servicetype, - COLI_sourcetype, - COLI_ConfirmType, - COLI_State, - COLI_Department, - COLI_AddCode, - COLI_OrderSource, - COLI_Memo, - COLI_GRI_SN, - COLI_GroupCode, - COLI_OriginalText -) -VALUES -( - '180408012', - NULL, - 2, - '2018-04-01', - NULL, - NULL, - 0, - NULL, - NULL, - N'来自图兰朵系统同步测试 16136西安汉阳陵市内精品一日游(目的地)', - '', - '', - 'D', - 32090, - 52001, - 7, - 30, - '15231742269430', - '62001', - '来自图兰朵系统同步测试 16136西安汉阳陵市内精品一日游(目的地)', - NULL, - N'T180405-BHJ180331588-D2', - N'' -) -ERROR - 2018-04-08 15:57:06 --> tag -ERROR - 2018-04-08 15:57:06 --> INSERT INTO BIZ_ConfirmLineDetail -( - COLD_COLI_SN, - COLD_ServiceType, - COLD_StartDate, - COLD_EndDate, - COLD_TotalCost, - COLD_TotalPrice, - COLD_Count, - COLD_PersonNum, - COLD_ChildNum, - COLD_BabyNum, - cold_state, - DeleteFlag, - COLD_DeliveryCharge, - COLD_AddCode, - COLD_PlanVEI_SN, - COLD_SPFS, - COLD_Memo, - COLD_ServiceSN -) -VALUES -( - NULL, - 'D', - '2018-04-05', - '2018-04-05', - NULL, - NULL, - NULL, - 3, - 0, - NULL, - 7, - 0, - 0, - '15231742269670', - NULL, - NULL, - '西安汉阳陵市内精品一日游(目的地)', - NULL -) -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-08 15:57:07 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php deleted file mode 100644 index f2cedb62..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-09.php +++ /dev/null @@ -1,201 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-09 13:50:17 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startOrderDate\":\"2018-04-01\",\"endOrderDate\":\"2018-04-08\"}","notHander":"1"} -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 85 -ERROR - 2018-04-09 13:50:17 --> ids array ( - 0 => 16136, - 1 => 16137, - 2 => 16139, - 3 => 16140, - 4 => 16141, - 5 => 16142, - 6 => 16143, - 7 => 16152, - 8 => 16158, - 9 => 16160, - 10 => 16161, - 11 => 16164, - 12 => 16188, - 13 => 16189, - 14 => 16190, - 15 => 16192, - 16 => 16199, - 17 => 16200, - 18 => 16201, - 19 => 16202, -) -ERROR - 2018-04-09 13:50:18 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startOrderDate\":\"2018-04-01\",\"endOrderDate\":\"2018-04-08\",\"orderId\":16136}","notHander":"1"} -ERROR - 2018-04-09 13:50:18 --> orderId 16136 -ERROR - 2018-04-09 13:50:18 --> 2018-04-05: 汉阳陵+市内 -用车安排: 西安-瑞风张涛师傅车队; 7座(9座大通)司机: 王师傅(15529080993); [3新加坡,汉阳陵一日游,雁塔假日] -带团导游: 西安王辉Rosa; (13519169439); -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:50:18 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-08\"}","notHander":"1"} -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:51:14 --> ids array ( - 0 => 12433, - 1 => 13087, - 2 => 13144, - 3 => 13284, - 4 => 13386, - 5 => 13458, - 6 => 13466, - 7 => 13608, - 8 => 13622, - 9 => 13667, - 10 => 13679, - 11 => 13765, - 12 => 13783, - 13 => 13875, - 14 => 13921, - 15 => 13937, - 16 => 13938, - 17 => 13964, - 18 => 14041, - 19 => 14042, -) -ERROR - 2018-04-09 13:51:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-08\",\"orderId\":12433}","notHander":"1"} -ERROR - 2018-04-09 13:51:14 --> orderId 12433 -ERROR - 2018-04-09 13:51:14 --> 2018-04-05: 北京精品一日游 -用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品两日游;6人;北京新世界酒店 /北京朝阳悠唐皇冠假日酒店/北京金茂万丽酒店] -带团导游: 北京况怡Tiger; (13693050013); -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:51:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:00 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 13:54:02 --> 2018-04-08: 北京精品一日游 -2018-04-09: 北京精品两日游(D2) -2018-04-10: 北京精品三日游(D3) -用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品三日游;4人;北京内蒙古大厦 /北京希尔顿逸林酒店 ] -带团导游: 北京孙玲玲Linda(13521990227); -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 13:54:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:47 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:00:48 --> 日程: 2018-04-08: 北京精品一日游; 2018-04-09: 北京精品两日游(D2); 2018-04-10: 北京精品三日游(D3); -用车安排: 北京-王会生13051277931(奔面系列); 奔面(*)司机: A-TBC(*); [精品三日游;4人;北京内蒙古大厦 /北京希尔顿逸林酒店 ] -带团导游: 北京孙玲玲Linda(13521990227); -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:00:48 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:14 --> Severity: Notice --> Undefined index: agcName D:\workspace\trippest\application\controllers\TulanduoApi.php 87 -ERROR - 2018-04-09 14:03:16 --> Severity: Notice --> Undefined property: stdClass::$guiderOperations D:\workspace\trippest\application\controllers\TulanduoApi.php 116 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> Invalid argument supplied for foreach() D:\workspace\trippest\application\controllers\TulanduoApi.php 116 -ERROR - 2018-04-09 14:03:16 --> 日程: 2018-04-01: 单租车接机; -用车安排: 凯美瑞车队-宋师傅13811026411; 5座轿车(京BZ1864/black/5seats/car)司机: Mr.WANG/JianYU 王建宇(13161343885); [单租车接机;2人;北京金隅喜来登酒店;接DL0129(Arr1950@T2);] -带团导游: -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-09 14:03:16 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php deleted file mode 100644 index ebca2fb8..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-10.php +++ /dev/null @@ -1,2 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php deleted file mode 100644 index 0d476b64..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-13.php +++ /dev/null @@ -1,76 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-13 16:51:57 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:51:59 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:52:00 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:52:01 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:52:02 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} -ERROR - 2018-04-13 16:52:02 --> GRI -ERROR - 2018-04-13 16:52:02 --> COLI475000834 -ERROR - 2018-04-13 16:52:02 --> COLD490000931 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:52:02 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:23 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:54:24 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:54:24 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:54:25 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:54:25 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} -ERROR - 2018-04-13 16:54:25 --> in gri -ERROR - 2018-04-13 16:54:25 --> GRI -ERROR - 2018-04-13 16:54:25 --> COLI475000835 -ERROR - 2018-04-13 16:54:25 --> COLD490000932 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:54:25 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:06 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:56:06 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:56:07 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:56:07 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:56:08 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} -ERROR - 2018-04-13 16:56:08 --> in gri -ERROR - 2018-04-13 16:56:08 --> GRI -ERROR - 2018-04-13 16:56:08 --> COLI475000836 -ERROR - 2018-04-13 16:56:08 --> COLD490000933 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:56:08 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:12 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:57:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:57:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:57:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 16:57:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} -ERROR - 2018-04-13 16:57:14 --> in gri -ERROR - 2018-04-13 16:57:14 --> GRI -ERROR - 2018-04-13 16:57:14 --> COLI475000837 -ERROR - 2018-04-13 16:57:14 --> COLD490000934 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 16:57:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:12 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 17:01:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 17:01:13 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":3,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 17:01:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\"}","notHander":"1"} -ERROR - 2018-04-13 17:01:14 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":4,\"startTravelDate\":\"2018-04-01\",\"endTravelDate\":\"2018-04-03\",\"orderId\":13458}","notHander":"1"} -ERROR - 2018-04-13 17:01:14 --> in gri -ERROR - 2018-04-13 17:01:14 --> GRI31 -ERROR - 2018-04-13 17:01:14 --> COLI475000838 -ERROR - 2018-04-13 17:01:14 --> COLD490000935 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, array given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 -ERROR - 2018-04-13 17:01:14 --> Severity: Warning --> get_class() expects parameter 1 to be object, string given D:\workspace\system\libraries\Profiler.php 166 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php deleted file mode 100644 index af2866f7..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-15.php +++ /dev/null @@ -1,72 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-15 14:37:11 --> curl postBodyString: { - "jsonParams": "{\"userId\":\"358\",\"key\":\"a08f26ddc5b1bd4c8e5eafcac28fc1ec\",\"orderData\":{\"travelFees\":[{\"type\":\"团款\",\"money\":\"756.00\",\"num\":1,\"unit\":\"6.4795\",\"sumMoney\":\"4898.57\",\"remark\":\"交易号(自动录入):17T02847CV281080D\"}],\"replaceCollections\":[],\"replacePays\":[],\"scheduleDetails\":[],\"customers\":[{\"name\":\"ZERVOS JOANNE\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"511460159\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE PETER\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"495326176\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE JOHN\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"526333245\",\"otherInfo\":\"\"},{\"name\":\"MAGUIRE BILL\",\"peopleType\":\"成人\",\"documentType\":\"Passport No.\",\"documentNo\":\"480595859\",\"otherInfo\":\"\"}],\"orderType\":1,\"routeName\":\"北京精品两日游(目的地)\",\"routeType\":\"北京目的地线路\",\"agcOrderNo\":\"CHBJ170823-BHX170809390\",\"adultNum\":2,\"childNum\":0,\"destination\":\"北京\",\"travelDate\":\"2017-08-23\",\"leavedDate\":\"2017-08-23\"}}", - "notHander": "1" -} -ERROR - 2018-04-15 16:25:26 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} -ERROR - 2018-04-15 16:25:26 --> TulanduoApi get_orderlist failed. Msg:; Request: {} -ERROR - 2018-04-15 16:25:52 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} -ERROR - 2018-04-15 16:25:52 --> TulanduoApi get_orderlist failed. Msg:; Request: {} -ERROR - 2018-04-15 16:26:47 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} -ERROR - 2018-04-15 16:26:47 --> TulanduoApi get_orderlist failed. Msg:; Request: {} -ERROR - 2018-04-15 16:27:04 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-10\",\"endTravelDate\":\"2018-04-10\"}","notHander":"1"} -ERROR - 2018-04-15 16:27:04 --> in gri -ERROR - 2018-04-15 16:27:04 --> Severity: Notice --> Undefined variable: allDetails_to_HT D:\workspace\trippest\application\controllers\TulanduoApi.php 184 -ERROR - 2018-04-15 16:27:04 --> COLI_ID 180415156 -ERROR - 2018-04-15 16:30:31 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:30:31 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:30:31 --> in gri -ERROR - 2018-04-15 16:30:31 --> COLI_ID 180415162 -ERROR - 2018-04-15 16:33:09 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:33:10 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:33:10 --> in gri -ERROR - 2018-04-15 16:33:10 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]在 SET 子句中多次指定了列名 'COLD_Memo'。在同一 SET 子句中不得为一个列分配多个值。请修改 SET 子句,以确保一个列仅更新一次。如果 SET 子句更新了某视图的多列,那么列名 'COLD_Memo' 可能会在该视图定义中出现两次。 @:INSERT INTO BIZ_ConfirmLineDetail -( - COLD_COLI_SN, - COLD_ServiceType, - COLD_StartDate, - COLD_EndDate, - COLD_TotalCost, - COLD_TotalPrice, - COLD_Count, - COLD_PersonNum, - COLD_ChildNum, - COLD_BabyNum, - cold_state, - DeleteFlag, - COLD_DeliveryCharge, - COLD_AddCode, - COLD_PlanVEI_SN, - COLD_SPFS, - COLD_Memo, - COLD_Memo, - COLD_ServiceSN -) -VALUES -( - 475000866, - 'D', - '2018-04-12', - '2018-04-13', - NULL, - NULL, - NULL, - 1, - 0, - NULL, - 7, - 0, - 0, - '15237811903740', - 1343, - NULL, - NULL, - '{"Pick up":"7:20 \/ \u5317\u4eac\u4e3d\u82d1\u516c\u5bd3 Lee Garden Service Apartment Beijing","Drop off":"\u5317\u4eac\u4e3d\u82d1\u516c\u5bd3 Lee Garden Service Apartment Beijing"}', - NULL -) -ERROR - 2018-04-15 16:33:10 --> Severity: Warning --> Cannot modify header information - headers already sent by (output started at D:\workspace\trippest\application\controllers\TulanduoApi.php:84) D:\workspace\system\core\Common.php 439 -ERROR - 2018-04-15 16:33:30 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:33:30 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-12\",\"endTravelDate\":\"2018-04-12\"}","notHander":"1"} -ERROR - 2018-04-15 16:33:30 --> in gri -ERROR - 2018-04-15 16:33:31 --> COLI_ID 180415174 diff --git a/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php b/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php deleted file mode 100644 index 67435b5b..00000000 --- a/webht/third_party/trippestOrderSync/logs/log-2018-04-16.php +++ /dev/null @@ -1,81 +0,0 @@ -<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> - -ERROR - 2018-04-16 17:16:36 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13634\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:16:36 --> order 475000954 -ERROR - 2018-04-16 17:16:36 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:IF EXISTS( - SELECT TOP 1 1 - FROM BIZ_ConfirmLineInfo - WHERE COLI_SN=475000954 AND COLI_GRI_SN is NULL - ) - INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N'T180417-BTM180122007M(BR-640151641)',N'',2,1,0,0,227002) -ERROR - 2018-04-16 17:21:20 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13634\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:21:20 --> order 475000954 -ERROR - 2018-04-16 17:21:20 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:IF EXISTS( - SELECT TOP 1 1 - FROM BIZ_ConfirmLineInfo - WHERE COLI_SN=475000954 AND COLI_GRI_SN is NULL - ) - INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N'T180417-BTM180122007M(BR-640151641)',N'',2,1,0,0,227002) -ERROR - 2018-04-16 17:28:21 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-17\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} -ERROR - 2018-04-16 17:28:22 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":2,\"startTravelDate\":\"2018-04-17\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} -ERROR - 2018-04-16 17:28:22 --> gci 108 -ERROR - 2018-04-16 17:30:19 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:30:19 --> order 475001062 -ERROR - 2018-04-16 17:30:19 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]列名 'N475001062' 无效。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N475001062,N'中华游180413-LILY170824015-CHXAD1','',1,1,0,0) -ERROR - 2018-04-16 17:30:39 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:30:39 --> order 475001062 -ERROR - 2018-04-16 17:30:39 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]违反了 PRIMARY KEY 约束 'PK_GRoupInfo'。不能在对象 'dbo.GRoupInfo' 中插入重复键。 @:INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N'中华游180413-LILY170824015-CHXAD1',N'',1,1,0,0,227002) -ERROR - 2018-04-16 17:46:18 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:46:18 --> order 475001062 -ERROR - 2018-04-16 17:46:19 --> Query error: [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]'coli' 附近有语法错误。 @:UPDATE BIZ_ConfirmLineInfo coli SET - COLI_GRI_SN=183489, - COLI_GroupCode='中华游180413-LILY170824015-CHXAD1' - WHERE COLI_SN=475001062 - -ERROR - 2018-04-16 17:47:56 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 17:47:56 --> order 475001062 -ERROR - 2018-04-16 17:49:47 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-18\",\"endTravelDate\":\"2018-04-18\"}","notHander":"1"} -ERROR - 2018-04-16 17:49:48 --> gci 108 -ERROR - 2018-04-16 17:53:34 --> curl postBodyString: {"jsonParams":"{\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\",\"pageSize\":20,\"pageIndex\":1,\"startTravelDate\":\"2018-04-19\",\"endTravelDate\":\"2018-04-19\"}","notHander":"1"} -ERROR - 2018-04-16 17:53:35 --> gci 109 -ERROR - 2018-04-16 18:02:29 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 18:02:30 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 18:02:30 --> Severity: Notice --> Undefined property: stdClass::$touristCarOperations D:\workspace\trippest\application\controllers\TulanduoApi.php 224 -ERROR - 2018-04-16 18:02:30 --> Severity: Warning --> Invalid argument supplied for foreach() D:\workspace\trippest\application\controllers\TulanduoApi.php 224 -ERROR - 2018-04-16 18:02:30 --> Severity: Notice --> Undefined property: TulanduoApi::$query D:\workspace\system\core\Model.php 51 -ERROR - 2018-04-16 18:04:40 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 18:04:40 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 18:05:08 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"10192\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} -ERROR - 2018-04-16 18:05:09 --> curl postBodyString: {"jsonParams":"{\"orderId\":\"13145\",\"userId\":\"1134\",\"key\":\"73d180d05d425fd192e1c5b3097e75ff\"}","notHander":"1"} diff --git a/webht/third_party/trippestOrderSync/models/order_insert.php b/webht/third_party/trippestOrderSync/models/order_insert.php new file mode 100644 index 00000000..1b8eb596 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/order_insert.php @@ -0,0 +1,1562 @@ +<?php + +class Orders_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + //读取默认配置 + $this->COLI_WebCode = $this->config->item('Site_Code'); + $this->COLI_Area = $this->config->item('Site_Area'); + $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); + $this->COLI_department = $this->config->item('Site_Department'); + $this->COLI_Currency = $this->config->item('Site_Currency'); + $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); + $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); + $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); + $this->COLI_OrderStartDate = null; + $this->COLI_Keywords = NULL; + switch ($this->check_device()) { + case 'mobile': + $this->COLI_OrderSource = '62003'; + break; + case 'tablet': + $this->COLI_OrderSource = '62002'; + break; + default: + $this->COLI_OrderSource = '62001'; + } + } + + public function get_orderinfo_detail($COLI_ID) + { + $sql = "SELECT coli.COLI_ID, + coli.COLI_Department, + cold.COLD_ServiceSN, + cold.COLD_ServiceSN2, + cold.COLD_ServiceCity, + * + FROM BIZ_ConfirmLineInfo coli + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE coli.COLI_ID='$COLI_ID' + ORDER BY COLI_ApplyDate DESC"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_guestlist($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_scheduleDetails($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN + AND (PAG2_LGC = 2) + WHERE COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_packageDetails($pag_code_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + WHERE pag.PAG_Code IN ($pag_code_str) + order by pag.PAG_Code "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_paymentDetails($COLI_ID) + { + $sql = "SELECT * + FROM BIZ_GroupAccountInfo bgai + INNER JOIN BIZ_ConfirmLineInfo coli ON bgai.GAI_COLI_SN=coli.COLI_SN + WHERE coli_ID = '$COLI_ID'"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_groupCodeList($GroupCodeList_str) + { + $sql = "SELECT GRI_No + FROM GRoupInfo gri + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No IN ($GroupCodeList_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_packageSN($pag_code) + { + $sql = "SELECT top 1 PAG2_SN + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + "; + $query = $this->HT->query($sql); + if ($query->row()) { + return $query->row()->PAG2_SN; + } + return NULL; + } + public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) + { + $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, gci.* + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE 1=1 "; + if ($coli_sn !== 0) { + $sql .= " and gci.GCI_COLI_SN='$coli_sn' "; + } + if ($startDate !== NULL) { + // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; + } + $query = $this->HT->query($sql); + return $query->result(); + } + + public $GRI_SN=0; // 团号 + public $GRI_No; // 团号 + public $GRI_OrderType; // 订单类型 + public $GRI_Name; // 团名 + public $GRI_PersonNum; // 人数 + public $GRI_Days; // 行程天数 + public $GRI_IsCancel=0; + public $GRI_DeleteFlag=0; + /** 团信息 */ + public function groupinfo_save() + { + $sql = "INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N?,N?,?,?,?,?,?)"; + $query = $this->HT->query($sql, array( + $this->GRI_No, + $this->GRI_Name, + $this->GRI_PersonNum, + $this->GRI_Days, + $this->GRI_IsCancel, + $this->GRI_DeleteFlag, + $this->GRI_OrderType + )); + $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); + return $this->GRI_SN; + } + + public $GCI_SN; + public $GCI_combineNo=''; // 拼团团号 + public $GCI_COLI_SN; // 订单key + public $GCI_VendorOrderId; // 地接社系统订单id + public $GCI_FromAgc; // 组团社来源 + public $GCI_groupType; // 组团社来源 + public $GCI_travelDate; + public $GCI_leaveDate; + public $GCI_createTime; + /** 目的地订单 拼团信息 */ + public function biz_groupcombineinfo_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupCombineInfo + WHERE GCI_VendorOrderId = ? + ) + INSERT INTO BIZ_GroupCombineInfo + (GCI_combineNo + ,GCI_COLI_SN + ,GCI_VendorOrderId + ,GCI_FromAgc + ,GCI_groupType + ,GCI_travelDate + ,GCI_leaveDate + ,GCI_createTime) + VALUES + (N? + ,? + ,? + ,N? + ,? + ,? + ,? + ,?) + "; + $query = $this->HT->query($sql, array( + $this->GCI_VendorOrderId + // ,$this->GCI_COLI_SN + ,$this->GCI_combineNo + ,$this->GCI_COLI_SN + ,$this->GCI_VendorOrderId + ,$this->GCI_FromAgc + ,$this->GCI_groupType + ,$this->GCI_travelDate + ,$this->GCI_leaveDate + ,$this->GCI_createTime + )); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + return $this->GCI_SN; + } + public function combineoperation_exist($combineNo='', $operation="") + { + if( ! $combineNo) { return false; } + $sql = "SELECT TOP 1 GCOD_GCI_combineNo + FROM BIZ_GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; + $query = $this->HT->query($sql, array( + $combineNo,$operation + )); + return $query->result(); + } + public $GCOD_SN; + public $GCOD_GCI_combineNo = ''; + public $GCOD_operationType = ''; + public $GCOD_subType = ''; + public $GCOD_title = ''; + public $GCOD_dutyName = ''; + public $GCOD_dutyTel; + public $GCOD_dutyPhoto; + public $GCOD_startDate; + public $GCOD_endDate; + public $GCOD_useNum=1; + public $GCOD_sumMoney; + public $GCOD_standard = ''; + public $GCOD_carLicense = ''; + public $GCOD_remark = ''; + public $GCOD_creatTime; + public function biz_groupcombineoperationdetail_save() + { + // IF NOT EXISTS( + // SELECT TOP 1 1 + // FROM BIZ_GroupCombineOperationDetail + // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? + // ) + $sql = "INSERT INTO BIZ_GroupCombineOperationDetail + (GCOD_GCI_combineNo + ,GCOD_operationType + ,GCOD_subType + ,GCOD_title + ,GCOD_dutyName + ,GCOD_dutyTel + ,GCOD_dutyPhoto + ,GCOD_startDate + ,GCOD_endDate + ,GCOD_useNum + ,GCOD_sumMoney + ,GCOD_standard + ,GCOD_carLicense + ,GCOD_remark + ,GCOD_creatTime) + VALUES + (N? + ,N? + ,N? + ,N? + ,N? + ,? + ,? + ,? + ,? + ,? + ,? + ,N? + ,N? + ,N? + ,GETDATE()) + "; + $query = $this->HT->query($sql, array( + $this->GCOD_GCI_combineNo + ,$this->GCOD_operationType + // ,$this->GCOD_GCI_combineNo + // ,$this->GCOD_operationType + ,$this->GCOD_subType + ,$this->GCOD_title + ,$this->GCOD_dutyName + ,$this->GCOD_dutyTel + ,$this->GCOD_dutyPhoto + ,$this->GCOD_startDate + ,$this->GCOD_endDate + ,$this->GCOD_useNum + ,$this->GCOD_sumMoney + ,$this->GCOD_standard + ,$this->GCOD_carLicense + ,$this->GCOD_remark + )); + return $query; + } + + + + var $GUT_SN; + var $GUT_FirstName; //联系人 + var $GUT_LastName = ""; //联系人 + var $GUT_Title; //称谓 + var $GUT_Email; //主email + var $GUT_Email2; //备用email + var $GUT_NationalityID; //国家 + var $GUT_Passport; //护照 + var $GUT_TEL; //座机 + var $GUT_MoveTel; //手机 + + /** + * 商务联系人表入库 + * + * @return int GUT_SN 插入id + */ + + function biz_guest_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_Guest \n" + . " ( \n" + . " GUT_FirstName, \n" + . " GUT_LastName, \n" + . " GUT_Title, \n" + . " GUT_Email, \n" + . " GUT_Email2, \n" + . " GUT_NationalityID, \n" + . " GUT_Passport, \n" + . " GUT_TEL, \n" + . " GUT_MoveTel, \n" + . " GUT_AddCode, \n" + . " GUT_CreateDate \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " GETDATE() \n" + . " )"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), + mb_convert_encoding($this->GUT_LastName, 'UTF-8'), + $this->GUT_Title, + $this->GUT_Email, + $this->GUT_Email2, + $this->GUT_NationalityID, + mb_convert_encoding($this->GUT_Passport, 'UTF-8'), + $this->GUT_TEL, + $this->GUT_MoveTel, $AddCode + )); + $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); + return $this->GUT_SN; + } + + public function get_SN_by_vendorOrderId($vendorOrderId) + { + $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->COLI_GRI_SN; + $this->GCI_SN = $query->row()->GCI_SN; + return $query->row(); + } + return NULL; + } + + public function get_SN_by_groupCode($code) + { + $sql = "SELECT top 1 COLI_SN,GRI_SN + FROM BIZ_ConfirmLineInfo coli + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No LIKE '$code%'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->GRI_SN; + return $query->row(); + } + return NULL; + } + + var $BIZ_COLI_SN; + var $BIZ_COLI_ID; + var $BIZ_COLI_GUT_SN; //联系人id + var $BIZ_COLI_Area; //市场 + var $BIZ_COLI_ApplyDate = ''; //提交日期 + var $BIZ_COLI_Price; //订单总价 + var $BIZ_COLI_Cost; //总成本 + var $BIZ_COLI_Currency; //币种 + var $BIZ_COLI_TrueCardRate; //信用卡手续费 + var $BIZ_COLI_SenderIP = ''; //客人ip + var $BIZ_COLI_WebCode = ''; //站点code + var $BIZ_COLI_servicetype; //订单来源类型 + var $BIZ_COLI_sourcetype; //预定类型 + var $BIZ_COLI_AgencyID; + var $BIZ_COLI_ConfirmType; //提交方式 + var $BIZ_COLI_OrderDetailText; + var $BIZ_COLI_OriginalText=''; + var $BIZ_COLI_Memo; + var $BIZ_COLI_GRI_SN; + var $BIZ_COLI_GroupCode=''; + var $BIZ_COLI_State; + + /** + * 商务订单主表入库 + * @return int BIZ_COLI_ID 插入id + */ + function biz_confirm_save() { + // if (empty($this->BIZ_COLI_WebCode)) { + $this->BIZ_COLI_WebCode = '';// 来源图兰朵 + // } + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" + . "( \n" + . " COLI_ID, \n" + . " COLI_GUT_SN, \n" + . " COLI_Area, \n" + . " COLI_ApplyDate, \n" + . " COLI_Price, \n" + . " COLI_Cost, \n" + . " COLI_Currency, \n" + . " COLI_TrueCardRate, \n" + . " COLI_AgencyID, \n" + . " COLI_OrderDetailText, \n" + . " COLI_SenderIP, \n" + . " COLI_WebCode, \n" + . " COLI_servicetype, \n" + . " COLI_sourcetype, \n" + . " COLI_ConfirmType, \n" + . " COLI_State, \n" + . " COLI_Department, \n" + . " COLI_AddCode, \n" + . " COLI_OrderSource, \n" + . " COLI_Memo, \n" + . " COLI_GRI_SN, \n" + . " COLI_GroupCode, \n" + . " COLI_OriginalText \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " N? \n" + . ")"; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_ID, + $this->BIZ_COLI_GUT_SN, + 2, + // $this->config->item('Site_Area'), + //date("Y-m-d H:i:s"), + $this->BIZ_COLI_ApplyDate, + $this->BIZ_COLI_Price, + $this->BIZ_COLI_Cost, + $this->config->item('Site_Currency'), + $this->BIZ_COLI_TrueCardRate, + $this->BIZ_COLI_AgencyID, + $this->BIZ_COLI_OrderDetailText, + $this->BIZ_COLI_SenderIP, + $this->BIZ_COLI_WebCode, + $this->BIZ_COLI_servicetype, + $this->BIZ_COLI_sourcetype, + $this->BIZ_COLI_ConfirmType, + $this->BIZ_COLI_State, + 30,// $this->config->item('Site_Department'), + $AddCode, + $this->COLI_OrderSource, + $this->BIZ_COLI_Memo, + $this->BIZ_COLI_GRI_SN, + $this->BIZ_COLI_GroupCode, + $this->BIZ_COLI_OriginalText + )); + $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); + return $this->BIZ_COLI_SN; + } + + public function update_confirmLineInfo() + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET + COLI_GRI_SN=?, + COLI_GroupCode=? + WHERE COLI_SN=? + "; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_GRI_SN + ,$this->BIZ_COLI_GroupCode + ,$this->BIZ_COLI_SN + )); + return $this->query; + } + + var $COLD_SN; + var $COLD_COLI_SN; // 订单主表sn + var $COLD_ServiceType; // 服务类型 + var $COLD_StartDate; // 产品的服务的开始日期 + var $COLD_EndDate; // 产品的服务的结束日期 + var $COLD_TotalCost; // 总成本 + var $COLD_TotalPrice; // 总报价 + var $COLD_Count; // 产品数量 + var $COLD_PersonNum; // 成人数 + var $COLD_ChildNum; // 小孩数 + var $COLD_BabyNum; // 婴儿数 + var $cold_state; // 状态 + var $DeleteFlag; // 删除标志 + var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY + var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 + var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 + var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID + var $COLD_Memo = NULL; + var $COLD_MemoText = NULL; + + /** + * 商务订单子(详细)表入库 + * + * @return int 插入id + */ + + function biz_confirm_detail_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" + . "( \n" + . " COLD_COLI_SN, \n" + . " COLD_ServiceType, \n" + . " COLD_StartDate, \n" + . " COLD_EndDate, \n" + . " COLD_TotalCost, \n" + . " COLD_TotalPrice, \n" + . " COLD_Count, \n" + . " COLD_PersonNum, \n" + . " COLD_ChildNum, \n" + . " COLD_BabyNum, \n" + . " cold_state, \n" + . " DeleteFlag, \n" + . " COLD_DeliveryCharge, \n" + . " COLD_AddCode, \n" + . " COLD_PlanVEI_SN, \n" + . " COLD_SPFS, \n" + . " COLD_Memo, \n" + . " COLD_MemoText, \n" + . " COLD_ServiceSN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->COLD_COLI_SN, + $this->COLD_ServiceType, + $this->COLD_StartDate, + $this->COLD_EndDate, + $this->COLD_TotalCost, + $this->COLD_TotalPrice, + $this->COLD_Count, + $this->COLD_PersonNum, + $this->COLD_ChildNum, + $this->COLD_BabyNum, + $this->cold_state, + $this->DeleteFlag, + $this->COLD_DeliveryCharge, + $AddCode, + $this->COLD_PlanVEI_SN, + $this->COLD_SPFS, + $this->COLD_Memo, + $this->COLD_MemoText, + $this->COLD_ServiceSN) + ); + //查出最近插入的id + $HT2 = $this->load->database('HT', true); + $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); + return $this->COLD_SN; + } + + var $BIZ_COLL_COLI_SN; + var $BIZ_COLL_type; + var $BIZ_COLL_COLI_Field; + var $BIZ_COLL_COLI_value; + var $BIZ_COLL_OPI_SN; + + function biz_confirm_line_log_save() + { + $sql = "INSERT INTO BIZ_ConfirmLineLog ( + COLL_COLI_SN, + COLL_LogTime, + COLL_type, + COLL_COLI_Field, + COLL_COLI_value, + COLL_OPI_SN + ) VALUES (?,GETDATE(),?,?,?,?) "; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, + $this->BIZ_COLL_type, + $this->BIZ_COLL_COLI_Field, + $this->BIZ_COLL_COLI_value, + $this->BIZ_COLL_OPI_SN) + ); + return $query; + } + + var $POI_SN; + var $POI_COLD_SN; + var $POI_FlightsNo = ''; + var $POI_AirPort = ''; + var $POI_Time; + var $POI_Hotel = ''; + var $POI_HotelAddress = ''; + var $POI_HotelPhone = ''; + var $POI_HotelCheckInName = ''; + var $POI_HotelCheckIn = ''; + var $POI_HotelCheckOut = ''; + var $POI_EndTime = ''; + var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 + /** 包价线路订单入库 */ + public function biz_packageorder_save() + { + $sql = "INSERT INTO BIZ_PackageOrderInfo + (POI_COLD_SN + ,POI_FlightsNo + ,POI_AirPort + ,POI_Time + ,POI_Hotel + ,POI_QuotationType + ,POI_HotelAddress + ,POI_HotelPhone + ,POI_HotelCheckInName + ,POI_HotelCheckIn + ,POI_HotelCheckOut + ,POI_EndTime) + VALUES + (? + ,? + ,N? + ,? + ,N? + ,? + ,N? + ,N? + ,N? + ,N? + ,N? + ,N?) + "; + $query = $this->HT->query($sql, array( + $this->POI_COLD_SN + ,$this->POI_FlightsNo + ,$this->POI_AirPort + ,$this->POI_Time + ,$this->POI_Hotel + ,$this->POI_QuotationType + ,$this->POI_HotelAddress + ,$this->POI_HotelPhone + ,$this->POI_HotelCheckInName + ,$this->POI_HotelCheckIn + ,$this->POI_HotelCheckOut + ,$this->POI_EndTime + )); + $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); + return $this->POI_SN; + } + + var $FOI_SN; + var $FOI_COLD_SN; // 订单子表sn + var $Aircompany; // 航空公司编码 + var $FlightsNo; // 航班号 + var $Cabin; // 舱位 + var $DepartAirport; // 出发机场 + var $ArrivalAirport; // 抵达机场 + var $DepartureCity; // 出发城市 + var $DepartureTime; // 出发日期 + var $ArrivalCity; // 抵达城市 + var $Arrivaltime; // 抵达时间 + var $DepartureDate; // 出发时间 + var $adultCost; // 成人成本 + var $childCost; // 小孩成倍 + var $babyCost; // 婴儿成本 + var $adultPrice; // 成人报价 + var $childPrice; // 小孩报价 + var $babyPrice; // 婴儿报价 + var $Stopover; // + var $PriceY; // Y仓价格 + var $price_low; // 最低价格 + var $FOI_Mile; // 里程 + var $TicketAddress; // 寄送地址 + var $FOI_CostTime = ''; // 运行时间 + var $Aircraft = ''; // 12306座位编号 + var $FOI_ServiceFee_adult = NULL; // 成人服务费 + var $FOI_ServiceFee_child = NULL; // 儿童服务费 + var $FOI_DeliveryFee = NULL; // 寄票费 + var $FOI_SelectedSeat = ""; // 选座 + + /** + * + * 商务机票订单入库 + * + */ + + function biz_flight_order_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" + . "( \n" + . " FOI_COLD_SN, \n" + . " Aircompany, \n" + . " FlightsNo, \n" + . " Cabin, \n" + . " DepartAirport, \n" + . " ArrivalAirport, \n" + . " DepartureCity, \n" + . " DepartureTime, \n" + . " ArrivalCity, \n" + . " Arrivaltime, \n" + . " DepartureDate, \n" + . " adultCost, \n" + . " childCost, \n" + . " babyCost, \n" + . " adultPrice, \n" + . " childPrice, \n" + . " babyPrice, \n" + . " Stopover, \n" + . " PriceY, \n" + . " price_low, \n" + . " FOI_Mile, \n" + . " TicketAddress, \n" + . " FOI_CostTime, \n" + . " FOI_AddCode, \n" + . " Aircraft, \n" + . " FOI_ServiceFee_adult, \n" + . " FOI_ServiceFee_child, \n" + . " FOI_SelectedSeat, \n" + . " FOI_DeliveryFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->FOI_COLD_SN, + $this->Aircompany, + $this->FlightsNo, + $this->Cabin, + $this->DepartAirport, + $this->ArrivalAirport, + $this->DepartureCity, + $this->DepartureTime, + $this->ArrivalCity, + $this->Arrivaltime, + $this->DepartureDate, + $this->adultCost, + $this->childCost, + $this->babyCost, + $this->adultPrice, + $this->childPrice, + $this->babyPrice, + $this->Stopover, + $this->PriceY, + $this->price_low, + $this->FOI_Mile, + $this->TicketAddress, + $this->FOI_CostTime, + $AddCode, + $this->Aircraft, + $this->FOI_ServiceFee_adult, + $this->FOI_ServiceFee_child, + $this->FOI_SelectedSeat, + $this->FOI_DeliveryFee + )); + $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); + return $this->FOI_SN; + } + + var $BPE_SN; + var $BPE_FirstName; //客人 + var $BPE_MiddleName; //客人 + var $BPE_LastName; //客人 + var $BPE_GuestType; //客人类型 + var $BPE_Passport; //护照 + var $BPE_imageSrc = NULL; //护照图片 + var $BPE_Nationality; //国籍 + var $BPE_SEX; //性别 + var $BPE_BirthDate; //生日 + var $BPE_PassportType = "Passport No."; //护照类型 + + /** + * + * 商务订单参团客人入库 + * + */ + + function biz_book_people_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_BookPeople \n" + . "( \n" + . " BPE_FirstName, \n" + . " BPE_MiddleName, \n" + . " BPE_LastName, \n" + . " BPE_GuestType, \n" + . " BPE_Passport, \n" + . " BPE_imageSrc, \n" + . " BPE_Nationality, \n" + . " BPE_SEX, \n" + . " BPE_BirthDate, \n" + . " BPE_PassportType, \n" + . " BPE_AddCode \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " N?, \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), + mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), + mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, + mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, + $this->BPE_Nationality, + $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); + $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); + return $this->BPE_SN; + } + + /** + * 参团人关联 + * + * @param int 商务子表sn + * @param int 参团客人sn + */ + function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { + $sql = "INSERT INTO BIZ_BookPeopleList \n" + . "( \n" + . " BPL_COLD_SN, \n" + . " BPL_BPE_SN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ? \n" + . ")"; + // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); + } + + /* + * 生成订单号 + * 根据系统时间生成,精确到0.0001微秒 + */ + + function MakeOrderNumber() { + return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); + } + + /** + * 生成商务订单号 + */ + function biz_make_order_number() { + /* + $date = date('ymd',time()); + $sql = "SELECT MAX( \n" + . " CONVERT( \n" + . " INT, \n" + . " CASE \n" + . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" + . " ELSE RIGHT(COLI_ID, 3) \n" + . " END \n" + . " ) \n" + . " ) AS SN \n" + . "FROM dbo.BIZ_ConfirmLineInfo \n" + . "WHERE (LEFT(COLI_ID, 6) = ?)"; + $query = $this->HT->query($sql,array($date)); + $id = $query->row()->SN; + if (is_null($id)||empty($id)) + { + $id = 0; + } + $ids = $date.(sprintf('%03d',(int)$id+1)); + return $ids; + */ + //call $conn + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + } else { + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->ccid); + } + } + + /** + * + * 更新订单状态(商务订单) + * + */ + public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { + //更新订单 + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; + $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); + $this->insert_acc_info($order_id); + return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); + } + + /** + * + * 更新火车订单购票截图 + * + */ + public function update_train_order_pic($order_pic_id) { + //更新订单 + $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; + //$query = $this->HT->query($sql); + + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, $sql); + + return $stmt; + } + + /** + * + * 插入收款记录 + * + */ + public function insert_acc_info($order_id) { + //获取订单 + $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + $order_info = $query->row(); + //插入记录 + $sql = "INSERT INTO BIZ_GroupAccountInfo \n" + . " ( \n" + . " GAI_COLI_SN, \n" + . " GAI_COLI_ID, \n" + . " GAI_Type, \n" + . " GAI_SQJE, \n" + . " GAI_SQDate, \n" + . " GAI_SSJE, \n" + . " GAI_SQJECurrency, \n" + . " GAI_SSDate, \n" + . " GAI_CusName, \n" + . " GAI_CusEmail, \n" + . " GAI_Memo \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . " )"; + $query = $this->HT->query($sql, array($order_info->COLI_SN, + $order_info->COLI_ID, + $order_info->COLI_PayManner, + $order_info->COLI_Price, + date('Y-m-d H:i:s'), + $order_info->COLI_Price, + $this->config->item('Site_Currency'), + date('Y-m-d H:i:s'), + "", "", " ")); + } + + function GetNationalityID($nationalityName) { + if (!$nationalityName) { + return 0; + } + if (is_numeric($nationalityName)) { + return $nationalityName; + } else { + $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_Country = ? "; + $query = $this->HT->query($sql, array($nationalityName)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_COI_SN; + } else { + return 0; + } + } + } + + function GetNationalityName($nationalityID) { + if (!is_numeric($nationalityID)) { + return $nationalityID; + } else { + $sql = "SELECT TOP 1 ci2.COI2_Country \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_LGC = 2 \n" + . " AND ci2.COI2_COI_SN = ? "; + $query = $this->HT->query($sql, array($nationalityID)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_Country; + } else { + return $nationalityID; + } + } + } + + /** + * + * 获取商务订单信息 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_flight_order_by_id($order_id) { + $sql = "SELECT DISTINCT cli.COLI_ID, \n" + . " cli.COLI_Price, \n" + . " bg.GUT_FirstName, \n" + . " bg.GUT_LastName, \n" + . " bg.GUT_Email, \n" + . " bg.GUT_Email2, \n" + . " bpe.BPE_SN, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_Passport, \n" + . " cld.COLD_Count, \n" + . " foi.FlightsNo, \n" + . " foi.DepartureDate, \n" + . " foi.DepartureTime, \n" + . " foi.ArrivalTime, \n" + . " cli.COLI_PayManner, \n" + . " cli.COLI_State, \n" + . " cli.COLI_sourcetype, \n" + . " foi.Cabin, \n" + . " foi.DepartAirport, \n" + . " foi.ArrivalAirport, \n" + . " cld.COLD_SN, \n" + . " foi.DepartureCity, \n" + . " foi.ArrivalCity, \n" + . " bg.GUT_TEL, \n" + . " bg.GUT_NationalityID, \n" + . " cli.COLI_OrderDetailText, \n" + . " bpe.BPE_imageSrc, \n" + . " cli.COLI_Cost, \n" + . " cld.COLD_TotalPrice, \n" + . " cld.COLD_TotalCost \n" + . "FROM BIZ_ConfirmLineInfo cli \n" + . " INNER JOIN BIZ_ConfirmLineDetail cld \n" + . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" + . " INNER JOIN BIZ_GUEST bg \n" + . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" + . " INNER JOIN BIZ_BookPeople bpe \n" + . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" + . " INNER JOIN BIZ_FlightsOrderInfo foi \n" + . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" + . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; + + $query = $this->HT->query($sql, array($order_id)); + return $query->result(); + } + + /** + * + * 获取机票订单乘员列表 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_bpe_list_by_id($order_id) { + $sql = "SELECT DISTINCT bpe.BPE_SN, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_Passport \n" + . "FROM BIZ_BookPeople bpe \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" + . " INNER JOIN BIZ_ConfirmLineDetail cold \n" + . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" + . " INNER JOIN BIZ_ConfirmLineInfo coli \n" + . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" + . "WHERE coli.COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); + return $query->result(); + } + + /** + * + * 获取机票电子票号 + * @param array bpe_sn 乘客sn数组 + * @return mixed 机票票号 + * + */ + public function get_ticket_no($bpe_sn) { + if (is_array($bpe_sn)) { + $instr = join(',', $bpe_sn); + } elseif (is_string($bpe_sn)) { + $instr = $bpe_sn; + } else { + $instr = 0; + } + $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" + . " ftn.FTN_TicketNo, \n" + . " ftn.FTN_GuestNo \n" + . "FROM BIZ_FlightsTicketNo ftn \n" + . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /* + * 发送邮件 + */ + + function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { + $sql = "INSERT INTO Email_AutomaticSend \n" + . " ( \n" + . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" + . " M_FromName, M_State \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" + . " ) "; + $query = $this->HT->query($sql, + array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) + ); + return $query; + } + + /** + * wifi预订入库(目前仅CHT使用) + * + * @return int 插入id + */ + var $WOI_COLD_SN; + var $WOI_Device; //设备(智能手机、pad) + var $WOI_DeviceCount; //设备数量 + var $WOI_UsersCount; //使用人数 + var $WOI_Package; //Wi-Fi套餐 + var $WOI_PackageCount; //套餐数量 + var $WOI_DeliverDate; //起租日期 + var $WOI_DeliverCity; //起租城市 + var $WOI_DeliverAddr; //起租地址 + var $WOI_ReturnDate; //归还日期 + var $WOI_ReturnCity; //归还城市 + var $WOI_ReturnAddr; //归还地址 + var $WOI_OtherService; //其他服务 + var $WOI_GroupNo; //团号 + var $WOI_ExpressNo; //快递单号 + + public function biz_wifi_info_save() { + $sql = "INSERT INTO BIZ_WifiOrderInfo \n" + . "( \n" + . " WOI_COLD_SN, \n" + . " WOI_Device, \n" + . " WOI_DeviceCount, \n" + . " WOI_UsersCount, \n" + . " WOI_Package, \n" + . " WOI_PackageCount, \n" + . " WOI_DeliverDate, \n" + . " WOI_DeliverCity, \n" + . " WOI_DeliverAddr, \n" + . " WOI_ReturnDate, \n" + . " WOI_ReturnCity, \n" + . " WOI_ReturnAddr, \n" + . " WOI_OtherService, \n" + . " WOI_GroupNo, \n" + . " WOI_ExpressNo \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->WOI_COLD_SN, + $this->WOI_Device, + $this->WOI_DeviceCount, + $this->WOI_UsersCount, + $this->WOI_Package, + $this->WOI_PackageCount, + $this->WOI_DeliverDate, + $this->WOI_DeliverCity, + $this->WOI_DeliverAddr, + $this->WOI_ReturnDate, + $this->WOI_ReturnCity, + $this->WOI_ReturnAddr, + $this->WOI_OtherService, + $this->WOI_GroupNo, + $this->WOI_ExpressNo + )); + } + + /** + * 酒店预订入库 + * + * @return int 插入id + */ + var $HOI_COLD_SN; //必选 + var $HOI_NoSmoking = null; //无烟房 + var $HOI_EarlyTime = null; //最早确认时间,已不用 + var $HOI_LastTime = null; //最晚确认时间,已不用 + var $HOI_Room_NO = null; //房号 + var $HOI_ExtraNum = 0; //加床 + var $HOI_RoomTypeName = null; //房型 + var $HOI_BreakNum = null; //早餐人数 + var $HOI_PriceType = null; //价格类型 + var $HOI_BreakType = null; //早餐类型 + var $HOI_RoomRates = null; + var $HOI_ExtrabedRates = null; + var $HOI_TaxFee = null; + + public function biz_hotel_order_save() { + /* ASP版本 + sql="select * from BIZ_HotelOrderInfo where 1=2" + rs2.open sql,conn,3,3,1 + rs2.addnew + rs2("HOI_COLD_SN")=COLD_SN + rs2("HOI_ExtraNum") = extrabed + if clng(Smoking)<2 then + rs2("HOI_NoSmoking")=Smoking + end if + rs2("HOI_EarlyTime")=earlydate + rs2("HOI_LastTime")="" + rs2.update + rs2.close + */ + $sql = "INSERT INTO BIZ_HotelOrderInfo \n" + . "( \n" + . " HOI_COLD_SN, \n" + . " HOI_NoSmoking, \n" + . " HOI_EarlyTime, \n" + . " HOI_LastTime, \n" + . " HOI_Room_NO, \n" + . " HOI_ExtraNum, \n" + . " HOI_RoomTypeName, \n" + . " HOI_BreakNum, \n" + . " HOI_PriceType, \n" + . " HOI_BreakType, \n" + . " HOI_RoomRates, \n" + . " HOI_ExtrabedRates, \n" + . " HOI_TaxFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->HOI_COLD_SN, + $this->HOI_NoSmoking, + $this->HOI_EarlyTime, + $this->HOI_LastTime, + $this->HOI_Room_NO, + $this->HOI_ExtraNum, + $this->HOI_RoomTypeName, + $this->HOI_BreakNum, + $this->HOI_PriceType, + $this->HOI_BreakType, + $this->HOI_RoomRates, + $this->HOI_ExtrabedRates, + $this->HOI_TaxFee + )); + } + + /** + * + * 返回成行订单 + * 条件1:订单类型 + * 天剑2:网站来源 + * + */ + public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { + if ($biz) { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" + . "FROM BIZ_ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } else { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" + . "FROM ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } + $this->sql = $this->HT->queries; + return $query->result(); + } + + //传统订单支付之后,插入新的订单信息 + public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { + //获取订单 + $order_info_sql = " + SELECT confirmlineinfotmp.COLI_OrderPrice, + memberinfotmp.MEI_FirstName, + memberinfotmp.MEI_LastName, + memberinfotmp.MEI_Mail + FROM memberinfotmp + INNER JOIN customerlisttmp + ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn + INNER JOIN confirmlineinfotmp + ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn + WHERE (customerlisttmp.cul_coli_sn = ? )"; + $query = $this->HT->query($order_info_sql, array($coli_sn)); + $order_info = $query->row(); + + //插入记录 + $sql = "INSERT INTO GroupAccountInfoTmp + ( + GAI_COLI_SN, + GAI_SQJE, + GAI_SQDate, + GAI_CusName, + GAI_CusEmail, + GAI_SQJECurrency, + GAI_Type, + LastEditTime, + GAI_GRI_SN, + GAI_State, + DeleteFlag + ) + VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + $query = $this->HT->query($sql, array($coli_sn, + $order_info->COLI_OrderPrice, + date('Y-m-d H:i:s'), + $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, + $order_info->MEI_Mail, + $this->config->item('Site_Currency'), + $pay_manner, + date('Y-m-d H:i:s'), + $gri_sn, + $state, + $deleteflag + ) + ); + } + + //来源终端 tablet mobile desktop + public function check_device() { + if (isset($_SERVER['HTTP_USER_AGENT'])) { + $ua = $_SERVER['HTTP_USER_AGENT']; + } else { + $ua = ''; + } + ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com + ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. + ## Price will be $2 + $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) + $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent + $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) + + if (!function_exists('androidTablet')) { + + function androidTablet($ua) { //Find out if it is a tablet + if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent + if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) + return true; + } + } + } + + } + $androidTablet = androidTablet($ua); //Do androidTablet function + $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent + + if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) + return 'tablet'; + } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet + return 'mobile'; + } else { //If it's not a mobile device + return 'desktop'; + } + } + + public function ip_limit($ip = "0.0.0.0") + { + if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { + return TRUE; + } + $sql = "SELECT COUNT(1) cnt + FROM ConfirmLineInfoTmp + WHERE 1=1 + AND COLI_SenderIP = ? + AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; + $query = $this->HT->query($sql, array($ip)); + $ret = $query->row(); + if ($ret->cnt > 50) { + return FALSE; + } else { + return TRUE; + } + } + + +} diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php new file mode 100644 index 00000000..4eaef337 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -0,0 +1,1499 @@ +<?php + +class Orders_update extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + //读取默认配置 + $this->COLI_WebCode = $this->config->item('Site_Code'); + $this->COLI_Area = $this->config->item('Site_Area'); + $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); + $this->COLI_department = $this->config->item('Site_Department'); + $this->COLI_Currency = $this->config->item('Site_Currency'); + $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); + $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); + $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); + $this->COLI_OrderStartDate = null; + $this->COLI_Keywords = NULL; + switch ($this->check_device()) { + case 'mobile': + $this->COLI_OrderSource = '62003'; + break; + case 'tablet': + $this->COLI_OrderSource = '62002'; + break; + default: + $this->COLI_OrderSource = '62001'; + } + } + + public $coli_where_update = ""; + public function biz_confirmlineinfo_update($column_data) + { + if ($this->coli_where_update == "" || empty($column_data)) { + return false; + } + $update_str = $this->HT->update_string('BIZ_ConfirmLineInfo', $column_data, $this->coli_where_update); + $update_exc = $this->HT->query($update_str); + return $update_exc; + } + + public $cold_where_update = ""; + public function biz_confirmlinedetail_update($column_data) + { + if ($this->cold_where_update == "" || empty($column_data)) { + return false; + } + $update_str = $this->HT->update_string('BIZ_ConfirmLineDetail', $column_data, $this->cold_where_update); + $update_exc = $this->HT->query($update_str); + return $update_exc; + } + + public $gci_where_update = ""; + public function biz_groupcombineinfo_update($column_data) + { + if ($this->gci_where_update == "" || empty($column_data)) { + return false; + } + $update_str = $this->HT->update_string('BIZ_GroupCombineInfo', $column_data, $this->gci_where_update); + $update_exc = $this->HT->query($update_str); + return $update_exc; + } + + + + + public $GRI_SN=0; // 团号 + public $GRI_No; // 团号 + public $GRI_OrderType; // 订单类型 + public $GRI_Name; // 团名 + public $GRI_PersonNum; // 人数 + public $GRI_Days; // 行程天数 + public $GRI_IsCancel=0; + public $GRI_DeleteFlag=0; + /** 团信息 */ + public function groupinfo_save() + { + $sql = "INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OrderType) + VALUES (N?,N?,?,?,?,?,?)"; + $query = $this->HT->query($sql, array( + $this->GRI_No, + $this->GRI_Name, + $this->GRI_PersonNum, + $this->GRI_Days, + $this->GRI_IsCancel, + $this->GRI_DeleteFlag, + $this->GRI_OrderType + )); + $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); + return $this->GRI_SN; + } + + public $GCI_SN; + public $GCI_combineNo=''; // 拼团团号 + public $GCI_COLI_SN; // 订单key + public $GCI_VendorOrderId; // 地接社系统订单id + public $GCI_FromAgc; // 组团社来源 + public $GCI_groupType; // 组团社来源 + public $GCI_travelDate; + public $GCI_leaveDate; + public $GCI_createTime; + /** 目的地订单 拼团信息 */ + public function biz_groupcombineinfo_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupCombineInfo + WHERE GCI_VendorOrderId = ? + ) + INSERT INTO BIZ_GroupCombineInfo + (GCI_combineNo + ,GCI_COLI_SN + ,GCI_VendorOrderId + ,GCI_FromAgc + ,GCI_groupType + ,GCI_travelDate + ,GCI_leaveDate + ,GCI_createTime) + VALUES + (N? + ,? + ,? + ,N? + ,? + ,? + ,? + ,?) + "; + $query = $this->HT->query($sql, array( + $this->GCI_VendorOrderId + // ,$this->GCI_COLI_SN + ,$this->GCI_combineNo + ,$this->GCI_COLI_SN + ,$this->GCI_VendorOrderId + ,$this->GCI_FromAgc + ,$this->GCI_groupType + ,$this->GCI_travelDate + ,$this->GCI_leaveDate + ,$this->GCI_createTime + )); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + return $this->GCI_SN; + } + public function combineoperation_exist($combineNo='', $operation="") + { + if( ! $combineNo) { return false; } + $sql = "SELECT TOP 1 GCOD_GCI_combineNo + FROM BIZ_GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; + $query = $this->HT->query($sql, array( + $combineNo,$operation + )); + return $query->result(); + } + public $GCOD_SN; + public $GCOD_GCI_combineNo = ''; + public $GCOD_operationType = ''; + public $GCOD_subType = ''; + public $GCOD_title = ''; + public $GCOD_dutyName = ''; + public $GCOD_dutyTel; + public $GCOD_dutyPhoto; + public $GCOD_startDate; + public $GCOD_endDate; + public $GCOD_useNum=1; + public $GCOD_sumMoney; + public $GCOD_standard = ''; + public $GCOD_carLicense = ''; + public $GCOD_remark = ''; + public $GCOD_creatTime; + public function biz_groupcombineoperationdetail_save() + { + // IF NOT EXISTS( + // SELECT TOP 1 1 + // FROM BIZ_GroupCombineOperationDetail + // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? + // ) + $sql = "INSERT INTO BIZ_GroupCombineOperationDetail + (GCOD_GCI_combineNo + ,GCOD_operationType + ,GCOD_subType + ,GCOD_title + ,GCOD_dutyName + ,GCOD_dutyTel + ,GCOD_dutyPhoto + ,GCOD_startDate + ,GCOD_endDate + ,GCOD_useNum + ,GCOD_sumMoney + ,GCOD_standard + ,GCOD_carLicense + ,GCOD_remark + ,GCOD_creatTime) + VALUES + (N? + ,N? + ,N? + ,N? + ,N? + ,? + ,? + ,? + ,? + ,? + ,? + ,N? + ,N? + ,N? + ,GETDATE()) + "; + $query = $this->HT->query($sql, array( + $this->GCOD_GCI_combineNo + ,$this->GCOD_operationType + // ,$this->GCOD_GCI_combineNo + // ,$this->GCOD_operationType + ,$this->GCOD_subType + ,$this->GCOD_title + ,$this->GCOD_dutyName + ,$this->GCOD_dutyTel + ,$this->GCOD_dutyPhoto + ,$this->GCOD_startDate + ,$this->GCOD_endDate + ,$this->GCOD_useNum + ,$this->GCOD_sumMoney + ,$this->GCOD_standard + ,$this->GCOD_carLicense + ,$this->GCOD_remark + )); + return $query; + } + + + + var $GUT_SN; + var $GUT_FirstName; //联系人 + var $GUT_LastName = ""; //联系人 + var $GUT_Title; //称谓 + var $GUT_Email; //主email + var $GUT_Email2; //备用email + var $GUT_NationalityID; //国家 + var $GUT_Passport; //护照 + var $GUT_TEL; //座机 + var $GUT_MoveTel; //手机 + + /** + * 商务联系人表入库 + * + * @return int GUT_SN 插入id + */ + + function biz_guest_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_Guest \n" + . " ( \n" + . " GUT_FirstName, \n" + . " GUT_LastName, \n" + . " GUT_Title, \n" + . " GUT_Email, \n" + . " GUT_Email2, \n" + . " GUT_NationalityID, \n" + . " GUT_Passport, \n" + . " GUT_TEL, \n" + . " GUT_MoveTel, \n" + . " GUT_AddCode, \n" + . " GUT_CreateDate \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " GETDATE() \n" + . " )"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), + mb_convert_encoding($this->GUT_LastName, 'UTF-8'), + $this->GUT_Title, + $this->GUT_Email, + $this->GUT_Email2, + $this->GUT_NationalityID, + mb_convert_encoding($this->GUT_Passport, 'UTF-8'), + $this->GUT_TEL, + $this->GUT_MoveTel, $AddCode + )); + $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); + return $this->GUT_SN; + } + + public function get_SN_by_vendorOrderId($vendorOrderId) + { + $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->COLI_GRI_SN; + $this->GCI_SN = $query->row()->GCI_SN; + return $query->row(); + } + return NULL; + } + + public function get_SN_by_groupCode($code) + { + $sql = "SELECT top 1 COLI_SN,GRI_SN + FROM BIZ_ConfirmLineInfo coli + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No LIKE '$code%'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->GRI_SN; + return $query->row(); + } + return NULL; + } + + var $BIZ_COLI_SN; + var $BIZ_COLI_ID; + var $BIZ_COLI_GUT_SN; //联系人id + var $BIZ_COLI_Area; //市场 + var $BIZ_COLI_ApplyDate = ''; //提交日期 + var $BIZ_COLI_Price; //订单总价 + var $BIZ_COLI_Cost; //总成本 + var $BIZ_COLI_Currency; //币种 + var $BIZ_COLI_TrueCardRate; //信用卡手续费 + var $BIZ_COLI_SenderIP = ''; //客人ip + var $BIZ_COLI_WebCode = ''; //站点code + var $BIZ_COLI_servicetype; //订单来源类型 + var $BIZ_COLI_sourcetype; //预定类型 + var $BIZ_COLI_AgencyID; + var $BIZ_COLI_ConfirmType; //提交方式 + var $BIZ_COLI_OrderDetailText; + var $BIZ_COLI_OriginalText=''; + var $BIZ_COLI_Memo; + var $BIZ_COLI_GRI_SN; + var $BIZ_COLI_GroupCode=''; + var $BIZ_COLI_State; + + /** + * 商务订单主表入库 + * @return int BIZ_COLI_ID 插入id + */ + function biz_confirm_save() { + // if (empty($this->BIZ_COLI_WebCode)) { + $this->BIZ_COLI_WebCode = '';// 来源图兰朵 + // } + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" + . "( \n" + . " COLI_ID, \n" + . " COLI_GUT_SN, \n" + . " COLI_Area, \n" + . " COLI_ApplyDate, \n" + . " COLI_Price, \n" + . " COLI_Cost, \n" + . " COLI_Currency, \n" + . " COLI_TrueCardRate, \n" + . " COLI_AgencyID, \n" + . " COLI_OrderDetailText, \n" + . " COLI_SenderIP, \n" + . " COLI_WebCode, \n" + . " COLI_servicetype, \n" + . " COLI_sourcetype, \n" + . " COLI_ConfirmType, \n" + . " COLI_State, \n" + . " COLI_Department, \n" + . " COLI_AddCode, \n" + . " COLI_OrderSource, \n" + . " COLI_Memo, \n" + . " COLI_GRI_SN, \n" + . " COLI_GroupCode, \n" + . " COLI_OriginalText \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " N? \n" + . ")"; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_ID, + $this->BIZ_COLI_GUT_SN, + 2, + // $this->config->item('Site_Area'), + //date("Y-m-d H:i:s"), + $this->BIZ_COLI_ApplyDate, + $this->BIZ_COLI_Price, + $this->BIZ_COLI_Cost, + $this->config->item('Site_Currency'), + $this->BIZ_COLI_TrueCardRate, + $this->BIZ_COLI_AgencyID, + $this->BIZ_COLI_OrderDetailText, + $this->BIZ_COLI_SenderIP, + $this->BIZ_COLI_WebCode, + $this->BIZ_COLI_servicetype, + $this->BIZ_COLI_sourcetype, + $this->BIZ_COLI_ConfirmType, + $this->BIZ_COLI_State, + 30,// $this->config->item('Site_Department'), + $AddCode, + $this->COLI_OrderSource, + $this->BIZ_COLI_Memo, + $this->BIZ_COLI_GRI_SN, + $this->BIZ_COLI_GroupCode, + $this->BIZ_COLI_OriginalText + )); + $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); + return $this->BIZ_COLI_SN; + } + + public function update_confirmLineInfo() + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET + COLI_GRI_SN=?, + COLI_GroupCode=? + WHERE COLI_SN=? + "; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_GRI_SN + ,$this->BIZ_COLI_GroupCode + ,$this->BIZ_COLI_SN + )); + return $this->query; + } + + var $COLD_SN; + var $COLD_COLI_SN; // 订单主表sn + var $COLD_ServiceType; // 服务类型 + var $COLD_StartDate; // 产品的服务的开始日期 + var $COLD_EndDate; // 产品的服务的结束日期 + var $COLD_TotalCost; // 总成本 + var $COLD_TotalPrice; // 总报价 + var $COLD_Count; // 产品数量 + var $COLD_PersonNum; // 成人数 + var $COLD_ChildNum; // 小孩数 + var $COLD_BabyNum; // 婴儿数 + var $cold_state; // 状态 + var $DeleteFlag; // 删除标志 + var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY + var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 + var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 + var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID + var $COLD_Memo = NULL; + var $COLD_MemoText = NULL; + + /** + * 商务订单子(详细)表入库 + * + * @return int 插入id + */ + + function biz_confirm_detail_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" + . "( \n" + . " COLD_COLI_SN, \n" + . " COLD_ServiceType, \n" + . " COLD_StartDate, \n" + . " COLD_EndDate, \n" + . " COLD_TotalCost, \n" + . " COLD_TotalPrice, \n" + . " COLD_Count, \n" + . " COLD_PersonNum, \n" + . " COLD_ChildNum, \n" + . " COLD_BabyNum, \n" + . " cold_state, \n" + . " DeleteFlag, \n" + . " COLD_DeliveryCharge, \n" + . " COLD_AddCode, \n" + . " COLD_PlanVEI_SN, \n" + . " COLD_SPFS, \n" + . " COLD_Memo, \n" + . " COLD_MemoText, \n" + . " COLD_ServiceSN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->COLD_COLI_SN, + $this->COLD_ServiceType, + $this->COLD_StartDate, + $this->COLD_EndDate, + $this->COLD_TotalCost, + $this->COLD_TotalPrice, + $this->COLD_Count, + $this->COLD_PersonNum, + $this->COLD_ChildNum, + $this->COLD_BabyNum, + $this->cold_state, + $this->DeleteFlag, + $this->COLD_DeliveryCharge, + $AddCode, + $this->COLD_PlanVEI_SN, + $this->COLD_SPFS, + $this->COLD_Memo, + $this->COLD_MemoText, + $this->COLD_ServiceSN) + ); + //查出最近插入的id + $HT2 = $this->load->database('HT', true); + $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); + return $this->COLD_SN; + } + + var $BIZ_COLL_COLI_SN; + var $BIZ_COLL_type; + var $BIZ_COLL_COLI_Field; + var $BIZ_COLL_COLI_value; + var $BIZ_COLL_OPI_SN; + + function biz_confirm_line_log_save() + { + $sql = "INSERT INTO BIZ_ConfirmLineLog ( + COLL_COLI_SN, + COLL_LogTime, + COLL_type, + COLL_COLI_Field, + COLL_COLI_value, + COLL_OPI_SN + ) VALUES (?,GETDATE(),?,?,?,?) "; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, + $this->BIZ_COLL_type, + $this->BIZ_COLL_COLI_Field, + $this->BIZ_COLL_COLI_value, + $this->BIZ_COLL_OPI_SN) + ); + return $query; + } + + var $POI_SN; + var $POI_COLD_SN; + var $POI_FlightsNo = ''; + var $POI_AirPort = ''; + var $POI_Time; + var $POI_Hotel = ''; + var $POI_HotelAddress = ''; + var $POI_HotelPhone = ''; + var $POI_HotelCheckInName = ''; + var $POI_HotelCheckIn = ''; + var $POI_HotelCheckOut = ''; + var $POI_EndTime = ''; + var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 + /** 包价线路订单入库 */ + public function biz_packageorder_save() + { + $sql = "INSERT INTO BIZ_PackageOrderInfo + (POI_COLD_SN + ,POI_FlightsNo + ,POI_AirPort + ,POI_Time + ,POI_Hotel + ,POI_QuotationType + ,POI_HotelAddress + ,POI_HotelPhone + ,POI_HotelCheckInName + ,POI_HotelCheckIn + ,POI_HotelCheckOut + ,POI_EndTime) + VALUES + (? + ,? + ,N? + ,? + ,N? + ,? + ,N? + ,N? + ,N? + ,N? + ,N? + ,N?) + "; + $query = $this->HT->query($sql, array( + $this->POI_COLD_SN + ,$this->POI_FlightsNo + ,$this->POI_AirPort + ,$this->POI_Time + ,$this->POI_Hotel + ,$this->POI_QuotationType + ,$this->POI_HotelAddress + ,$this->POI_HotelPhone + ,$this->POI_HotelCheckInName + ,$this->POI_HotelCheckIn + ,$this->POI_HotelCheckOut + ,$this->POI_EndTime + )); + $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); + return $this->POI_SN; + } + + var $FOI_SN; + var $FOI_COLD_SN; // 订单子表sn + var $Aircompany; // 航空公司编码 + var $FlightsNo; // 航班号 + var $Cabin; // 舱位 + var $DepartAirport; // 出发机场 + var $ArrivalAirport; // 抵达机场 + var $DepartureCity; // 出发城市 + var $DepartureTime; // 出发日期 + var $ArrivalCity; // 抵达城市 + var $Arrivaltime; // 抵达时间 + var $DepartureDate; // 出发时间 + var $adultCost; // 成人成本 + var $childCost; // 小孩成倍 + var $babyCost; // 婴儿成本 + var $adultPrice; // 成人报价 + var $childPrice; // 小孩报价 + var $babyPrice; // 婴儿报价 + var $Stopover; // + var $PriceY; // Y仓价格 + var $price_low; // 最低价格 + var $FOI_Mile; // 里程 + var $TicketAddress; // 寄送地址 + var $FOI_CostTime = ''; // 运行时间 + var $Aircraft = ''; // 12306座位编号 + var $FOI_ServiceFee_adult = NULL; // 成人服务费 + var $FOI_ServiceFee_child = NULL; // 儿童服务费 + var $FOI_DeliveryFee = NULL; // 寄票费 + var $FOI_SelectedSeat = ""; // 选座 + + /** + * + * 商务机票订单入库 + * + */ + + function biz_flight_order_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" + . "( \n" + . " FOI_COLD_SN, \n" + . " Aircompany, \n" + . " FlightsNo, \n" + . " Cabin, \n" + . " DepartAirport, \n" + . " ArrivalAirport, \n" + . " DepartureCity, \n" + . " DepartureTime, \n" + . " ArrivalCity, \n" + . " Arrivaltime, \n" + . " DepartureDate, \n" + . " adultCost, \n" + . " childCost, \n" + . " babyCost, \n" + . " adultPrice, \n" + . " childPrice, \n" + . " babyPrice, \n" + . " Stopover, \n" + . " PriceY, \n" + . " price_low, \n" + . " FOI_Mile, \n" + . " TicketAddress, \n" + . " FOI_CostTime, \n" + . " FOI_AddCode, \n" + . " Aircraft, \n" + . " FOI_ServiceFee_adult, \n" + . " FOI_ServiceFee_child, \n" + . " FOI_SelectedSeat, \n" + . " FOI_DeliveryFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->FOI_COLD_SN, + $this->Aircompany, + $this->FlightsNo, + $this->Cabin, + $this->DepartAirport, + $this->ArrivalAirport, + $this->DepartureCity, + $this->DepartureTime, + $this->ArrivalCity, + $this->Arrivaltime, + $this->DepartureDate, + $this->adultCost, + $this->childCost, + $this->babyCost, + $this->adultPrice, + $this->childPrice, + $this->babyPrice, + $this->Stopover, + $this->PriceY, + $this->price_low, + $this->FOI_Mile, + $this->TicketAddress, + $this->FOI_CostTime, + $AddCode, + $this->Aircraft, + $this->FOI_ServiceFee_adult, + $this->FOI_ServiceFee_child, + $this->FOI_SelectedSeat, + $this->FOI_DeliveryFee + )); + $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); + return $this->FOI_SN; + } + + var $BPE_SN; + var $BPE_FirstName; //客人 + var $BPE_MiddleName; //客人 + var $BPE_LastName; //客人 + var $BPE_GuestType; //客人类型 + var $BPE_Passport; //护照 + var $BPE_imageSrc = NULL; //护照图片 + var $BPE_Nationality; //国籍 + var $BPE_SEX; //性别 + var $BPE_BirthDate; //生日 + var $BPE_PassportType = "Passport No."; //护照类型 + + /** + * + * 商务订单参团客人入库 + * + */ + + function biz_book_people_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_BookPeople \n" + . "( \n" + . " BPE_FirstName, \n" + . " BPE_MiddleName, \n" + . " BPE_LastName, \n" + . " BPE_GuestType, \n" + . " BPE_Passport, \n" + . " BPE_imageSrc, \n" + . " BPE_Nationality, \n" + . " BPE_SEX, \n" + . " BPE_BirthDate, \n" + . " BPE_PassportType, \n" + . " BPE_AddCode \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " N?, \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), + mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), + mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, + mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, + $this->BPE_Nationality, + $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); + $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); + return $this->BPE_SN; + } + + /** + * 参团人关联 + * + * @param int 商务子表sn + * @param int 参团客人sn + */ + function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { + $sql = "INSERT INTO BIZ_BookPeopleList \n" + . "( \n" + . " BPL_COLD_SN, \n" + . " BPL_BPE_SN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ? \n" + . ")"; + // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); + } + + /* + * 生成订单号 + * 根据系统时间生成,精确到0.0001微秒 + */ + + function MakeOrderNumber() { + return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); + } + + /** + * 生成商务订单号 + */ + function biz_make_order_number() { + /* + $date = date('ymd',time()); + $sql = "SELECT MAX( \n" + . " CONVERT( \n" + . " INT, \n" + . " CASE \n" + . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" + . " ELSE RIGHT(COLI_ID, 3) \n" + . " END \n" + . " ) \n" + . " ) AS SN \n" + . "FROM dbo.BIZ_ConfirmLineInfo \n" + . "WHERE (LEFT(COLI_ID, 6) = ?)"; + $query = $this->HT->query($sql,array($date)); + $id = $query->row()->SN; + if (is_null($id)||empty($id)) + { + $id = 0; + } + $ids = $date.(sprintf('%03d',(int)$id+1)); + return $ids; + */ + //call $conn + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + } else { + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->ccid); + } + } + + /** + * + * 更新订单状态(商务订单) + * + */ + public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { + //更新订单 + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; + $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); + $this->insert_acc_info($order_id); + return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); + } + + /** + * + * 更新火车订单购票截图 + * + */ + public function update_train_order_pic($order_pic_id) { + //更新订单 + $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; + //$query = $this->HT->query($sql); + + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, $sql); + + return $stmt; + } + + /** + * + * 插入收款记录 + * + */ + public function insert_acc_info($order_id) { + //获取订单 + $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + $order_info = $query->row(); + //插入记录 + $sql = "INSERT INTO BIZ_GroupAccountInfo \n" + . " ( \n" + . " GAI_COLI_SN, \n" + . " GAI_COLI_ID, \n" + . " GAI_Type, \n" + . " GAI_SQJE, \n" + . " GAI_SQDate, \n" + . " GAI_SSJE, \n" + . " GAI_SQJECurrency, \n" + . " GAI_SSDate, \n" + . " GAI_CusName, \n" + . " GAI_CusEmail, \n" + . " GAI_Memo \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . " )"; + $query = $this->HT->query($sql, array($order_info->COLI_SN, + $order_info->COLI_ID, + $order_info->COLI_PayManner, + $order_info->COLI_Price, + date('Y-m-d H:i:s'), + $order_info->COLI_Price, + $this->config->item('Site_Currency'), + date('Y-m-d H:i:s'), + "", "", " ")); + } + + function GetNationalityID($nationalityName) { + if (!$nationalityName) { + return 0; + } + if (is_numeric($nationalityName)) { + return $nationalityName; + } else { + $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_Country = ? "; + $query = $this->HT->query($sql, array($nationalityName)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_COI_SN; + } else { + return 0; + } + } + } + + function GetNationalityName($nationalityID) { + if (!is_numeric($nationalityID)) { + return $nationalityID; + } else { + $sql = "SELECT TOP 1 ci2.COI2_Country \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_LGC = 2 \n" + . " AND ci2.COI2_COI_SN = ? "; + $query = $this->HT->query($sql, array($nationalityID)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_Country; + } else { + return $nationalityID; + } + } + } + + /** + * + * 获取商务订单信息 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_flight_order_by_id($order_id) { + $sql = "SELECT DISTINCT cli.COLI_ID, \n" + . " cli.COLI_Price, \n" + . " bg.GUT_FirstName, \n" + . " bg.GUT_LastName, \n" + . " bg.GUT_Email, \n" + . " bg.GUT_Email2, \n" + . " bpe.BPE_SN, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_Passport, \n" + . " cld.COLD_Count, \n" + . " foi.FlightsNo, \n" + . " foi.DepartureDate, \n" + . " foi.DepartureTime, \n" + . " foi.ArrivalTime, \n" + . " cli.COLI_PayManner, \n" + . " cli.COLI_State, \n" + . " cli.COLI_sourcetype, \n" + . " foi.Cabin, \n" + . " foi.DepartAirport, \n" + . " foi.ArrivalAirport, \n" + . " cld.COLD_SN, \n" + . " foi.DepartureCity, \n" + . " foi.ArrivalCity, \n" + . " bg.GUT_TEL, \n" + . " bg.GUT_NationalityID, \n" + . " cli.COLI_OrderDetailText, \n" + . " bpe.BPE_imageSrc, \n" + . " cli.COLI_Cost, \n" + . " cld.COLD_TotalPrice, \n" + . " cld.COLD_TotalCost \n" + . "FROM BIZ_ConfirmLineInfo cli \n" + . " INNER JOIN BIZ_ConfirmLineDetail cld \n" + . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" + . " INNER JOIN BIZ_GUEST bg \n" + . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" + . " INNER JOIN BIZ_BookPeople bpe \n" + . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" + . " INNER JOIN BIZ_FlightsOrderInfo foi \n" + . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" + . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; + + $query = $this->HT->query($sql, array($order_id)); + return $query->result(); + } + + /** + * + * 获取机票订单乘员列表 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_bpe_list_by_id($order_id) { + $sql = "SELECT DISTINCT bpe.BPE_SN, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_Passport \n" + . "FROM BIZ_BookPeople bpe \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" + . " INNER JOIN BIZ_ConfirmLineDetail cold \n" + . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" + . " INNER JOIN BIZ_ConfirmLineInfo coli \n" + . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" + . "WHERE coli.COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); + return $query->result(); + } + + /** + * + * 获取机票电子票号 + * @param array bpe_sn 乘客sn数组 + * @return mixed 机票票号 + * + */ + public function get_ticket_no($bpe_sn) { + if (is_array($bpe_sn)) { + $instr = join(',', $bpe_sn); + } elseif (is_string($bpe_sn)) { + $instr = $bpe_sn; + } else { + $instr = 0; + } + $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" + . " ftn.FTN_TicketNo, \n" + . " ftn.FTN_GuestNo \n" + . "FROM BIZ_FlightsTicketNo ftn \n" + . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /* + * 发送邮件 + */ + + function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { + $sql = "INSERT INTO Email_AutomaticSend \n" + . " ( \n" + . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" + . " M_FromName, M_State \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" + . " ) "; + $query = $this->HT->query($sql, + array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) + ); + return $query; + } + + /** + * wifi预订入库(目前仅CHT使用) + * + * @return int 插入id + */ + var $WOI_COLD_SN; + var $WOI_Device; //设备(智能手机、pad) + var $WOI_DeviceCount; //设备数量 + var $WOI_UsersCount; //使用人数 + var $WOI_Package; //Wi-Fi套餐 + var $WOI_PackageCount; //套餐数量 + var $WOI_DeliverDate; //起租日期 + var $WOI_DeliverCity; //起租城市 + var $WOI_DeliverAddr; //起租地址 + var $WOI_ReturnDate; //归还日期 + var $WOI_ReturnCity; //归还城市 + var $WOI_ReturnAddr; //归还地址 + var $WOI_OtherService; //其他服务 + var $WOI_GroupNo; //团号 + var $WOI_ExpressNo; //快递单号 + + public function biz_wifi_info_save() { + $sql = "INSERT INTO BIZ_WifiOrderInfo \n" + . "( \n" + . " WOI_COLD_SN, \n" + . " WOI_Device, \n" + . " WOI_DeviceCount, \n" + . " WOI_UsersCount, \n" + . " WOI_Package, \n" + . " WOI_PackageCount, \n" + . " WOI_DeliverDate, \n" + . " WOI_DeliverCity, \n" + . " WOI_DeliverAddr, \n" + . " WOI_ReturnDate, \n" + . " WOI_ReturnCity, \n" + . " WOI_ReturnAddr, \n" + . " WOI_OtherService, \n" + . " WOI_GroupNo, \n" + . " WOI_ExpressNo \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->WOI_COLD_SN, + $this->WOI_Device, + $this->WOI_DeviceCount, + $this->WOI_UsersCount, + $this->WOI_Package, + $this->WOI_PackageCount, + $this->WOI_DeliverDate, + $this->WOI_DeliverCity, + $this->WOI_DeliverAddr, + $this->WOI_ReturnDate, + $this->WOI_ReturnCity, + $this->WOI_ReturnAddr, + $this->WOI_OtherService, + $this->WOI_GroupNo, + $this->WOI_ExpressNo + )); + } + + /** + * 酒店预订入库 + * + * @return int 插入id + */ + var $HOI_COLD_SN; //必选 + var $HOI_NoSmoking = null; //无烟房 + var $HOI_EarlyTime = null; //最早确认时间,已不用 + var $HOI_LastTime = null; //最晚确认时间,已不用 + var $HOI_Room_NO = null; //房号 + var $HOI_ExtraNum = 0; //加床 + var $HOI_RoomTypeName = null; //房型 + var $HOI_BreakNum = null; //早餐人数 + var $HOI_PriceType = null; //价格类型 + var $HOI_BreakType = null; //早餐类型 + var $HOI_RoomRates = null; + var $HOI_ExtrabedRates = null; + var $HOI_TaxFee = null; + + public function biz_hotel_order_save() { + /* ASP版本 + sql="select * from BIZ_HotelOrderInfo where 1=2" + rs2.open sql,conn,3,3,1 + rs2.addnew + rs2("HOI_COLD_SN")=COLD_SN + rs2("HOI_ExtraNum") = extrabed + if clng(Smoking)<2 then + rs2("HOI_NoSmoking")=Smoking + end if + rs2("HOI_EarlyTime")=earlydate + rs2("HOI_LastTime")="" + rs2.update + rs2.close + */ + $sql = "INSERT INTO BIZ_HotelOrderInfo \n" + . "( \n" + . " HOI_COLD_SN, \n" + . " HOI_NoSmoking, \n" + . " HOI_EarlyTime, \n" + . " HOI_LastTime, \n" + . " HOI_Room_NO, \n" + . " HOI_ExtraNum, \n" + . " HOI_RoomTypeName, \n" + . " HOI_BreakNum, \n" + . " HOI_PriceType, \n" + . " HOI_BreakType, \n" + . " HOI_RoomRates, \n" + . " HOI_ExtrabedRates, \n" + . " HOI_TaxFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->HOI_COLD_SN, + $this->HOI_NoSmoking, + $this->HOI_EarlyTime, + $this->HOI_LastTime, + $this->HOI_Room_NO, + $this->HOI_ExtraNum, + $this->HOI_RoomTypeName, + $this->HOI_BreakNum, + $this->HOI_PriceType, + $this->HOI_BreakType, + $this->HOI_RoomRates, + $this->HOI_ExtrabedRates, + $this->HOI_TaxFee + )); + } + + /** + * + * 返回成行订单 + * 条件1:订单类型 + * 天剑2:网站来源 + * + */ + public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { + if ($biz) { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" + . "FROM BIZ_ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } else { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" + . "FROM ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } + $this->sql = $this->HT->queries; + return $query->result(); + } + + //传统订单支付之后,插入新的订单信息 + public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { + //获取订单 + $order_info_sql = " + SELECT confirmlineinfotmp.COLI_OrderPrice, + memberinfotmp.MEI_FirstName, + memberinfotmp.MEI_LastName, + memberinfotmp.MEI_Mail + FROM memberinfotmp + INNER JOIN customerlisttmp + ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn + INNER JOIN confirmlineinfotmp + ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn + WHERE (customerlisttmp.cul_coli_sn = ? )"; + $query = $this->HT->query($order_info_sql, array($coli_sn)); + $order_info = $query->row(); + + //插入记录 + $sql = "INSERT INTO GroupAccountInfoTmp + ( + GAI_COLI_SN, + GAI_SQJE, + GAI_SQDate, + GAI_CusName, + GAI_CusEmail, + GAI_SQJECurrency, + GAI_Type, + LastEditTime, + GAI_GRI_SN, + GAI_State, + DeleteFlag + ) + VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + $query = $this->HT->query($sql, array($coli_sn, + $order_info->COLI_OrderPrice, + date('Y-m-d H:i:s'), + $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, + $order_info->MEI_Mail, + $this->config->item('Site_Currency'), + $pay_manner, + date('Y-m-d H:i:s'), + $gri_sn, + $state, + $deleteflag + ) + ); + } + + //来源终端 tablet mobile desktop + public function check_device() { + if (isset($_SERVER['HTTP_USER_AGENT'])) { + $ua = $_SERVER['HTTP_USER_AGENT']; + } else { + $ua = ''; + } + ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com + ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. + ## Price will be $2 + $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) + $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent + $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) + + if (!function_exists('androidTablet')) { + + function androidTablet($ua) { //Find out if it is a tablet + if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent + if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) + return true; + } + } + } + + } + $androidTablet = androidTablet($ua); //Do androidTablet function + $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent + + if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) + return 'tablet'; + } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet + return 'mobile'; + } else { //If it's not a mobile device + return 'desktop'; + } + } + + public function ip_limit($ip = "0.0.0.0") + { + if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { + return TRUE; + } + $sql = "SELECT COUNT(1) cnt + FROM ConfirmLineInfoTmp + WHERE 1=1 + AND COLI_SenderIP = ? + AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; + $query = $this->HT->query($sql, array($ip)); + $ret = $query->row(); + if ($ret->cnt > 50) { + return FALSE; + } else { + return TRUE; + } + } + + +} diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index d2b78bd0..b582c746 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -30,14 +30,16 @@ class Orders_model extends CI_Model { public function get_orderinfo_detail($COLI_ID) { - $sql = "SELECT coli.COLI_ID, + $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_Department, cold.COLD_ServiceSN, cold.COLD_ServiceSN2, cold.COLD_ServiceCity, + gut.GUT_NationalityID, * FROM BIZ_ConfirmLineInfo coli INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + LEFT JOIN BIZ_GUEST gut ON gut.GUT_SN=coli.COLI_GUT_SN WHERE coli.COLI_ID='$COLI_ID' ORDER BY COLI_ApplyDate DESC"; $query = $this->HT->query($sql); @@ -112,7 +114,7 @@ class Orders_model extends CI_Model { } public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, gci.* + $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* FROM BIZ_GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN @@ -364,6 +366,22 @@ class Orders_model extends CI_Model { return $this->GUT_SN; } + public function get_SN_by_vendorOrderId($vendorOrderId) + { + $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->COLI_GRI_SN; + $this->GCI_SN = $query->row()->GCI_SN; + return $query->row(); + } + return NULL; + } + public function get_SN_by_groupCode($code) { $sql = "SELECT top 1 COLI_SN,GRI_SN From 462cfa20b90d3b7b6d9c0da82fafe427f75174ed Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 23 Apr 2018 15:56:50 +0800 Subject: [PATCH 047/382] =?UTF-8?q?trippest=20=E5=AD=98=E5=85=A5HT?= =?UTF-8?q?=E4=BE=9B=E5=BA=94=E5=95=86=E8=AE=A1=E5=88=92=E7=9B=B8=E5=85=B3?= =?UTF-8?q?=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 44 +++++++------ .../trippestOrderSync/models/order_insert.php | 62 ++++++++++++++++++- .../trippestOrderSync/models/orders_model.php | 19 ++++++ 3 files changed, 104 insertions(+), 21 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index c74aad8d..0a4feca3 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -50,6 +50,7 @@ class TulanduoApi extends CI_Controller public function __construct(){ parent::__construct(); $this->load->model('Orders_model'); + $this->load->model('Order_insert'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); $this->load->helper('array'); @@ -74,15 +75,15 @@ class TulanduoApi extends CI_Controller ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) - ->setStartTravelDate("2018-04-19") - ->setEndTravelDate("2018-04-19") + ->setStartTravelDate("2018-04-18") + ->setEndTravelDate("2018-04-18") // ->setStartOrderDate("2018-04-13") // ->setEndOrderDate("2018-04-13") ; $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); if ($resp_arr['status'] !== 1) { - log_message('error','TulanduoApi get_orderlist failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . json_encode($this->params)); + log_message('error','TulanduoApi get_orderlist failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); return; } $all_list = $resp_arr["responseData"]["orders"]; @@ -97,7 +98,7 @@ class TulanduoApi extends CI_Controller $f_resp = $this->excute_curl($this->list_url, $this->tld_order); $f_resp_arr = json_decode($f_resp, true); if ($resp_arr['status'] !== 1) { - log_message('error','TulanduoApi get_orderlist failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . json_encode($this->params)); + log_message('error','TulanduoApi get_orderlist failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); continue; } $f_order_to_HT = array_map( @@ -112,14 +113,6 @@ class TulanduoApi extends CI_Controller $cnt = 0; foreach ($all_list as $k => $vo) { $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 - // get order detail - // $this->tld_order->setOrderId($vo["orderId"]); - // $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); - // $detail_jsonResp = json_decode($detail_resp); - // if ($detail_jsonResp->status !== 1) { - // log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . json_encode($this->params)); - // return; - // } $PAG_Code = $pag_sub = null; preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); if (empty($temp_array) && isset($this->pag_no_tmp()[$vo['routeName']])) { @@ -139,7 +132,7 @@ class TulanduoApi extends CI_Controller $COLD_MemoText = json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; - $this->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 + $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $tmp_groupCode = explode("-", $vo['agcOrderNo']); $real_groupCode = $tmp_groupCode[0] . "-"; @@ -165,7 +158,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GRI_IsCancel = 0; $this->Orders_model->DeleteFlag = 0; $this->Orders_model->groupinfo_save(); - /*BIZ_ConfirmLineInfo*/ + /**BIZ_ConfirmLineInfo*/ $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_No : ""; $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; @@ -179,7 +172,8 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $coli_sn[] = $this->Orders_model->biz_confirm_save(); - /*BIZ_ConfirmLineDetail*/ +log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); + /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; $this->Orders_model->COLD_ServiceType = "D"; $this->Orders_model->COLD_ServiceSN = $serviceSN; @@ -193,6 +187,20 @@ class TulanduoApi extends CI_Controller $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; $this->Orders_model->COLD_MemoText = $COLD_MemoText; $this->Orders_model->biz_confirm_detail_save(); + /** VendorArrangeState */ + $vendor_contact = $this->Orders_model->get_vendorContact($this->Orders_model->COLD_PlanVEI_SN); + $this->Order_insert->VAS_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; + $this->Order_insert->VAS_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; + $this->Order_insert->VAS_IsSendSucceed = 1; + $this->Order_insert->VAS_IsConfirm = $vo['orderStatus']; + $this->Order_insert->VAS_IsCancel = 0; + $this->Order_insert->VAS_SendTime = $vo['orderDate']; + $this->Order_insert->VAS_ConfirmTime = $vo['orderStatus'] == 1 ? $vo['orderDate'] : null; + $this->Order_insert->VAS_LMI_SN = !empty($vendor_contact) ? $vendor_contact->LMI_SN : null; + $this->Order_insert->VAS_FaxNo = !empty($vendor_contact) ? $vendor_contact->LMI_AutoFax : null; + $this->Order_insert->VAS_VendorEmail = !empty($vendor_contact) ? $vendor_contact->LMI_ListMail : null; + $this->Order_insert->vendorarrangestate_save(); + $cnt++; } if ($this->Orders_model->GCI_SN === null) { @@ -231,7 +239,7 @@ class TulanduoApi extends CI_Controller $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); $detail_jsonResp = json_decode($detail_resp); if ($detail_jsonResp->status !== 1) { - log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . json_encode($this->params)); + log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); return; } $allDetails_to_HT = "日程: "; @@ -297,7 +305,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineoperationdetail_save(); } } - // 用房 + // 用房 ... // 用餐 if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) && empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "restraurantOperations"))) { @@ -389,7 +397,7 @@ class TulanduoApi extends CI_Controller ->setOrderType(2) // todo ->setRouteName($routeName) ->setRouteType("北京目的地线路") // todo - ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode) + ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode) // todo 加上 -BJ,-SH, -XA ->setAdultNum($orderinfo[0]->COLD_PersonNum) ->setChildNum($orderinfo[0]->COLD_ChildNum) ->setDestination("北京") // todo diff --git a/webht/third_party/trippestOrderSync/models/order_insert.php b/webht/third_party/trippestOrderSync/models/order_insert.php index 1b8eb596..7978adaf 100644 --- a/webht/third_party/trippestOrderSync/models/order_insert.php +++ b/webht/third_party/trippestOrderSync/models/order_insert.php @@ -1,6 +1,6 @@ <?php -class Orders_model extends CI_Model { +class Order_insert extends CI_Model { function __construct() { parent::__construct(); @@ -127,6 +127,63 @@ class Orders_model extends CI_Model { return $query->result(); } + public $VAS_GRI_SN; + public $VAS_VEI_SN; + public $VAS_IsSendSucceed; + public $VAS_IsConfirm; + public $VAS_SendTime; + public $VAS_ConfirmTime; + public $VAS_IsCancel; + public $VAS_LMI_SN; + public $VAS_FaxNo; + public $VAS_VendorEmail; + public function vendorarrangestate_save() + { + $sql = "INSERT INTO VendorArrangeState + (VAS_GRI_SN + ,VAS_VEI_SN + ,VAS_IsSendSucceed + ,VAS_IsConfirm + ,VAS_SendTime + ,VAS_ConfirmTime + ,VAS_IsCancel + ,VAS_LMI_SN + ,VAS_FaxNo + ,VAS_VendorEmail + ,Creator + ,LastEditTime + ,DeleteFlag + ) VALUES + (? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,0 + ,GETDATE() + ,0 + )"; + $query = $this->HT->query($sql, array( + $this->VAS_GRI_SN + ,$this->VAS_VEI_SN + ,$this->VAS_IsSendSucceed + ,$this->VAS_IsConfirm + ,$this->VAS_SendTime + ,$this->VAS_ConfirmTime + ,$this->VAS_IsCancel + ,$this->VAS_LMI_SN + ,$this->VAS_FaxNo + ,$this->VAS_VendorEmail + )); + return $query; + } + + /** 团信息 */ public $GRI_SN=0; // 团号 public $GRI_No; // 团号 public $GRI_OrderType; // 订单类型 @@ -135,7 +192,6 @@ class Orders_model extends CI_Model { public $GRI_Days; // 行程天数 public $GRI_IsCancel=0; public $GRI_DeleteFlag=0; - /** 团信息 */ public function groupinfo_save() { $sql = "INSERT INTO GRoupInfo @@ -160,6 +216,7 @@ class Orders_model extends CI_Model { return $this->GRI_SN; } + /** 目的地订单 拼团信息 */ public $GCI_SN; public $GCI_combineNo=''; // 拼团团号 public $GCI_COLI_SN; // 订单key @@ -169,7 +226,6 @@ class Orders_model extends CI_Model { public $GCI_travelDate; public $GCI_leaveDate; public $GCI_createTime; - /** 目的地订单 拼团信息 */ public function biz_groupcombineinfo_save() { $sql = "IF NOT EXISTS( diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index b582c746..f553ba29 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -397,6 +397,25 @@ class Orders_model extends CI_Model { return NULL; } + /*! + * 获取地接社接受计划的人员信息 + * @param $vendorID 地接社ID + */ + public function get_vendorContact($vendorID) + { + $sql = "SELECT top 1 lmi2.LMI2_Name, + lmi.LMI_SN, + lmi.LMI_AutoFax, + lmi.LMI_Telephone, + lmi.LMI_Mobile, + lmi.LMI_ListMail + FROM LinkmanInfo lmi + INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN + WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; + $query = $this->HT->query($sql); + return $query->row(); + } + var $BIZ_COLI_SN; var $BIZ_COLI_ID; var $BIZ_COLI_GUT_SN; //联系人id From 772d0ec774ae14b58ea6aee2c2c8021880a293f7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 23 Apr 2018 16:55:24 +0800 Subject: [PATCH 048/382] =?UTF-8?q?trippest=20=E5=A2=9E=E5=8A=A0COLD=5Fser?= =?UTF-8?q?viceCity?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 15 ++++++------ .../trippestOrderSync/models/order_update.php | 2 +- .../trippestOrderSync/models/orders_model.php | 24 +++++++++++++++---- 3 files changed, 28 insertions(+), 13 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 0a4feca3..8e812c1d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -176,8 +176,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; $this->Orders_model->COLD_ServiceType = "D"; - $this->Orders_model->COLD_ServiceSN = $serviceSN; + $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_SN; $this->Orders_model->COLD_ServiceSN2 = $pag_sub; + $this->Orders_model->COLD_ServiceCity = $serviceSN->PAG_CII_SN; $this->Orders_model->COLD_StartDate = $vo['travelDate']; $this->Orders_model->COLD_EndDate = $vo['leaveDate']; $this->Orders_model->COLD_PersonNum = $vo['adultNum']; @@ -223,7 +224,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); public function update_HT_order_operation($coli_sn=null) { - $this->load->model('Orders_update'); + $this->load->model('Order_update'); if ($coli_sn !== null) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); } else { @@ -249,21 +250,21 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /** HT 开始 */ /** UPDATE */ /** BIZ_ConfirmLineInfo */ - $this->Orders_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; + $this->Order_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; $coli_update_column = array( "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" // 调度信息加上以便在HT界面上显示 todo ); - $this->Orders_update->biz_confirmlineinfo_update($coli_update_column); + $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update /** biz_groupcombineinfo */ - $this->Orders_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; + $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; $gci_update_column = array( - "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo + "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate ); - $this->Orders_update->biz_groupcombineinfo_update($gci_update_column); + $this->Order_update->biz_groupcombineinfo_update($gci_update_column); /** INSERT */ /*BIZ_BookPeople*/ foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 4eaef337..bfb53783 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -1,6 +1,6 @@ <?php -class Orders_update extends CI_Model { +class Order_update extends CI_Model { function __construct() { parent::__construct(); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index f553ba29..c436aa2d 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -101,17 +101,23 @@ class Orders_model extends CI_Model { public function get_packageSN($pag_code) { - $sql = "SELECT top 1 PAG2_SN + $sql = "SELECT top 1 PAG2_SN,PAG_CII_SN FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 "; $query = $this->HT->query($sql); if ($query->row()) { - return $query->row()->PAG2_SN; + return $query->row(); } return NULL; } + /*! + * 需要更新调度信息的订单 + * @param integer $coli_sn [description] + * @param [type] $startDate [description] + * @param [type] $endDate [description] + */ public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) { $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* @@ -123,7 +129,7 @@ class Orders_model extends CI_Model { $sql .= " and gci.GCI_COLI_SN='$coli_sn' "; } if ($startDate !== NULL) { - // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; + // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test } $query = $this->HT->query($sql); return $query->result(); @@ -563,6 +569,8 @@ class Orders_model extends CI_Model { var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID + var $COLD_ServiceSN2 = NULL; + var $COLD_ServiceCity = NULL; var $COLD_Memo = NULL; var $COLD_MemoText = NULL; @@ -595,7 +603,9 @@ class Orders_model extends CI_Model { . " COLD_SPFS, \n" . " COLD_Memo, \n" . " COLD_MemoText, \n" - . " COLD_ServiceSN \n" + . " COLD_ServiceSN, \n" + . " COLD_ServiceSN2, \n" + . " COLD_ServiceCity \n" . ") \n" . "VALUES \n" . "( \n" @@ -616,6 +626,8 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " ?, \n" + . " ?, \n" + . " ?, \n" . " ?, \n" . " ? \n" . ")"; @@ -639,7 +651,9 @@ class Orders_model extends CI_Model { $this->COLD_SPFS, $this->COLD_Memo, $this->COLD_MemoText, - $this->COLD_ServiceSN) + $this->COLD_ServiceSN, + $this->COLD_ServiceSN2, + $this->COLD_ServiceCity) ); //查出最近插入的id $HT2 = $this->load->database('HT', true); From bcd90a5faae9626614be6f8fe53fb00b93fefefc Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Apr 2018 11:08:18 +0800 Subject: [PATCH 049/382] =?UTF-8?q?trippest=20=E4=BF=AE=E6=AD=A3=E7=BA=BF?= =?UTF-8?q?=E8=B7=AF=E4=BB=A3=E5=8F=B7;=E5=8F=91=E9=80=81=E8=AE=A2?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 32 +- .../trippestOrderSync/models/order_update.php | 906 ------------------ .../trippestOrderSync/models/orders_model.php | 14 +- 3 files changed, 31 insertions(+), 921 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 8e812c1d..82bc2734 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -176,7 +176,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; $this->Orders_model->COLD_ServiceType = "D"; - $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_SN; + $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_PAG_SN; $this->Orders_model->COLD_ServiceSN2 = $pag_sub; $this->Orders_model->COLD_ServiceCity = $serviceSN->PAG_CII_SN; $this->Orders_model->COLD_StartDate = $vo['travelDate']; @@ -247,13 +247,17 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; } + $allDetails_to_HT .= "导游: "; + foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { + $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; + } /** HT 开始 */ /** UPDATE */ /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; $coli_update_column = array( - "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark - ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" // 调度信息加上以便在HT界面上显示 todo + "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark + ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT // 调度信息加上以便在HT界面上显示 todo ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update @@ -388,6 +392,10 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $guestlist = $this->Orders_model->get_guestlist($COLD_SN_str); $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str); $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; + // 子线路 + if ($scheduleDetails[0]->PAGS_CN_Title) { + $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]"; + } if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); } @@ -397,13 +405,14 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); ->setKey($this->key) ->setOrderType(2) // todo ->setRouteName($routeName) - ->setRouteType("北京目的地线路") // todo - ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode) // todo 加上 -BJ,-SH, -XA + ->setRouteType($scheduleDetails[0]->CII2_Name . "目的地线路") + ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->CII2_Name) ->setAdultNum($orderinfo[0]->COLD_PersonNum) ->setChildNum($orderinfo[0]->COLD_ChildNum) - ->setDestination("北京") // todo + ->setDestination($scheduleDetails[0]->CII2_Name) ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) - ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)); + ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)) + ->setOrderRemark($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText); // todo 抵离交通 foreach ($guestlist as $key => $vg) { $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) @@ -416,10 +425,10 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); ->setScheduleDetailsTitle($ks, $vs->PAG2_Name) // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) ->setScheduleDetailsBreakFirst($ks, 0 ) - ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0) ) - ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0)); + ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0) ) + ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0)); } - foreach ($travelFees as $kf => $vf) { + foreach ($travelFees as $kf => $vf) { // todo 发生退款或多笔收款 $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") ->setTravelFeesMoney($kf, $vf->GAI_SQJE) ->setTravelFeesNum($kf, 1) @@ -434,9 +443,10 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; - $this->Orders_model->GCI_FromAgc = ""; + $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; $this->Orders_model->biz_groupcombineinfo_save(); } + echo "Order Push done."; return; } diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index bfb53783..420448b1 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -64,90 +64,6 @@ class Order_update extends CI_Model { - public $GRI_SN=0; // 团号 - public $GRI_No; // 团号 - public $GRI_OrderType; // 订单类型 - public $GRI_Name; // 团名 - public $GRI_PersonNum; // 人数 - public $GRI_Days; // 行程天数 - public $GRI_IsCancel=0; - public $GRI_DeleteFlag=0; - /** 团信息 */ - public function groupinfo_save() - { - $sql = "INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N?,N?,?,?,?,?,?)"; - $query = $this->HT->query($sql, array( - $this->GRI_No, - $this->GRI_Name, - $this->GRI_PersonNum, - $this->GRI_Days, - $this->GRI_IsCancel, - $this->GRI_DeleteFlag, - $this->GRI_OrderType - )); - $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); - return $this->GRI_SN; - } - - public $GCI_SN; - public $GCI_combineNo=''; // 拼团团号 - public $GCI_COLI_SN; // 订单key - public $GCI_VendorOrderId; // 地接社系统订单id - public $GCI_FromAgc; // 组团社来源 - public $GCI_groupType; // 组团社来源 - public $GCI_travelDate; - public $GCI_leaveDate; - public $GCI_createTime; - /** 目的地订单 拼团信息 */ - public function biz_groupcombineinfo_save() - { - $sql = "IF NOT EXISTS( - SELECT TOP 1 1 - FROM BIZ_GroupCombineInfo - WHERE GCI_VendorOrderId = ? - ) - INSERT INTO BIZ_GroupCombineInfo - (GCI_combineNo - ,GCI_COLI_SN - ,GCI_VendorOrderId - ,GCI_FromAgc - ,GCI_groupType - ,GCI_travelDate - ,GCI_leaveDate - ,GCI_createTime) - VALUES - (N? - ,? - ,? - ,N? - ,? - ,? - ,? - ,?) - "; - $query = $this->HT->query($sql, array( - $this->GCI_VendorOrderId - // ,$this->GCI_COLI_SN - ,$this->GCI_combineNo - ,$this->GCI_COLI_SN - ,$this->GCI_VendorOrderId - ,$this->GCI_FromAgc - ,$this->GCI_groupType - ,$this->GCI_travelDate - ,$this->GCI_leaveDate - ,$this->GCI_createTime - )); - $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); - return $this->GCI_SN; - } public function combineoperation_exist($combineNo='', $operation="") { if( ! $combineNo) { return false; } @@ -159,147 +75,6 @@ class Order_update extends CI_Model { )); return $query->result(); } - public $GCOD_SN; - public $GCOD_GCI_combineNo = ''; - public $GCOD_operationType = ''; - public $GCOD_subType = ''; - public $GCOD_title = ''; - public $GCOD_dutyName = ''; - public $GCOD_dutyTel; - public $GCOD_dutyPhoto; - public $GCOD_startDate; - public $GCOD_endDate; - public $GCOD_useNum=1; - public $GCOD_sumMoney; - public $GCOD_standard = ''; - public $GCOD_carLicense = ''; - public $GCOD_remark = ''; - public $GCOD_creatTime; - public function biz_groupcombineoperationdetail_save() - { - // IF NOT EXISTS( - // SELECT TOP 1 1 - // FROM BIZ_GroupCombineOperationDetail - // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? - // ) - $sql = "INSERT INTO BIZ_GroupCombineOperationDetail - (GCOD_GCI_combineNo - ,GCOD_operationType - ,GCOD_subType - ,GCOD_title - ,GCOD_dutyName - ,GCOD_dutyTel - ,GCOD_dutyPhoto - ,GCOD_startDate - ,GCOD_endDate - ,GCOD_useNum - ,GCOD_sumMoney - ,GCOD_standard - ,GCOD_carLicense - ,GCOD_remark - ,GCOD_creatTime) - VALUES - (N? - ,N? - ,N? - ,N? - ,N? - ,? - ,? - ,? - ,? - ,? - ,? - ,N? - ,N? - ,N? - ,GETDATE()) - "; - $query = $this->HT->query($sql, array( - $this->GCOD_GCI_combineNo - ,$this->GCOD_operationType - // ,$this->GCOD_GCI_combineNo - // ,$this->GCOD_operationType - ,$this->GCOD_subType - ,$this->GCOD_title - ,$this->GCOD_dutyName - ,$this->GCOD_dutyTel - ,$this->GCOD_dutyPhoto - ,$this->GCOD_startDate - ,$this->GCOD_endDate - ,$this->GCOD_useNum - ,$this->GCOD_sumMoney - ,$this->GCOD_standard - ,$this->GCOD_carLicense - ,$this->GCOD_remark - )); - return $query; - } - - - - var $GUT_SN; - var $GUT_FirstName; //联系人 - var $GUT_LastName = ""; //联系人 - var $GUT_Title; //称谓 - var $GUT_Email; //主email - var $GUT_Email2; //备用email - var $GUT_NationalityID; //国家 - var $GUT_Passport; //护照 - var $GUT_TEL; //座机 - var $GUT_MoveTel; //手机 - - /** - * 商务联系人表入库 - * - * @return int GUT_SN 插入id - */ - - function biz_guest_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_Guest \n" - . " ( \n" - . " GUT_FirstName, \n" - . " GUT_LastName, \n" - . " GUT_Title, \n" - . " GUT_Email, \n" - . " GUT_Email2, \n" - . " GUT_NationalityID, \n" - . " GUT_Passport, \n" - . " GUT_TEL, \n" - . " GUT_MoveTel, \n" - . " GUT_AddCode, \n" - . " GUT_CreateDate \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " N?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " GETDATE() \n" - . " )"; - $query = $this->HT->query($sql, array( - mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), - mb_convert_encoding($this->GUT_LastName, 'UTF-8'), - $this->GUT_Title, - $this->GUT_Email, - $this->GUT_Email2, - $this->GUT_NationalityID, - mb_convert_encoding($this->GUT_Passport, 'UTF-8'), - $this->GUT_TEL, - $this->GUT_MoveTel, $AddCode - )); - $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); - return $this->GUT_SN; - } public function get_SN_by_vendorOrderId($vendorOrderId) { @@ -332,121 +107,6 @@ class Order_update extends CI_Model { return NULL; } - var $BIZ_COLI_SN; - var $BIZ_COLI_ID; - var $BIZ_COLI_GUT_SN; //联系人id - var $BIZ_COLI_Area; //市场 - var $BIZ_COLI_ApplyDate = ''; //提交日期 - var $BIZ_COLI_Price; //订单总价 - var $BIZ_COLI_Cost; //总成本 - var $BIZ_COLI_Currency; //币种 - var $BIZ_COLI_TrueCardRate; //信用卡手续费 - var $BIZ_COLI_SenderIP = ''; //客人ip - var $BIZ_COLI_WebCode = ''; //站点code - var $BIZ_COLI_servicetype; //订单来源类型 - var $BIZ_COLI_sourcetype; //预定类型 - var $BIZ_COLI_AgencyID; - var $BIZ_COLI_ConfirmType; //提交方式 - var $BIZ_COLI_OrderDetailText; - var $BIZ_COLI_OriginalText=''; - var $BIZ_COLI_Memo; - var $BIZ_COLI_GRI_SN; - var $BIZ_COLI_GroupCode=''; - var $BIZ_COLI_State; - - /** - * 商务订单主表入库 - * @return int BIZ_COLI_ID 插入id - */ - function biz_confirm_save() { - // if (empty($this->BIZ_COLI_WebCode)) { - $this->BIZ_COLI_WebCode = '';// 来源图兰朵 - // } - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" - . "( \n" - . " COLI_ID, \n" - . " COLI_GUT_SN, \n" - . " COLI_Area, \n" - . " COLI_ApplyDate, \n" - . " COLI_Price, \n" - . " COLI_Cost, \n" - . " COLI_Currency, \n" - . " COLI_TrueCardRate, \n" - . " COLI_AgencyID, \n" - . " COLI_OrderDetailText, \n" - . " COLI_SenderIP, \n" - . " COLI_WebCode, \n" - . " COLI_servicetype, \n" - . " COLI_sourcetype, \n" - . " COLI_ConfirmType, \n" - . " COLI_State, \n" - . " COLI_Department, \n" - . " COLI_AddCode, \n" - . " COLI_OrderSource, \n" - . " COLI_Memo, \n" - . " COLI_GRI_SN, \n" - . " COLI_GroupCode, \n" - . " COLI_OriginalText \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " N?, \n" - . " N? \n" - . ")"; - $query = $this->HT->query($sql, array( - $this->BIZ_COLI_ID, - $this->BIZ_COLI_GUT_SN, - 2, - // $this->config->item('Site_Area'), - //date("Y-m-d H:i:s"), - $this->BIZ_COLI_ApplyDate, - $this->BIZ_COLI_Price, - $this->BIZ_COLI_Cost, - $this->config->item('Site_Currency'), - $this->BIZ_COLI_TrueCardRate, - $this->BIZ_COLI_AgencyID, - $this->BIZ_COLI_OrderDetailText, - $this->BIZ_COLI_SenderIP, - $this->BIZ_COLI_WebCode, - $this->BIZ_COLI_servicetype, - $this->BIZ_COLI_sourcetype, - $this->BIZ_COLI_ConfirmType, - $this->BIZ_COLI_State, - 30,// $this->config->item('Site_Department'), - $AddCode, - $this->COLI_OrderSource, - $this->BIZ_COLI_Memo, - $this->BIZ_COLI_GRI_SN, - $this->BIZ_COLI_GroupCode, - $this->BIZ_COLI_OriginalText - )); - $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); - return $this->BIZ_COLI_SN; - } - public function update_confirmLineInfo() { $sql = "UPDATE BIZ_ConfirmLineInfo SET @@ -462,412 +122,6 @@ class Order_update extends CI_Model { return $this->query; } - var $COLD_SN; - var $COLD_COLI_SN; // 订单主表sn - var $COLD_ServiceType; // 服务类型 - var $COLD_StartDate; // 产品的服务的开始日期 - var $COLD_EndDate; // 产品的服务的结束日期 - var $COLD_TotalCost; // 总成本 - var $COLD_TotalPrice; // 总报价 - var $COLD_Count; // 产品数量 - var $COLD_PersonNum; // 成人数 - var $COLD_ChildNum; // 小孩数 - var $COLD_BabyNum; // 婴儿数 - var $cold_state; // 状态 - var $DeleteFlag; // 删除标志 - var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY - var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 - var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 - var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID - var $COLD_Memo = NULL; - var $COLD_MemoText = NULL; - - /** - * 商务订单子(详细)表入库 - * - * @return int 插入id - */ - - function biz_confirm_detail_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" - . "( \n" - . " COLD_COLI_SN, \n" - . " COLD_ServiceType, \n" - . " COLD_StartDate, \n" - . " COLD_EndDate, \n" - . " COLD_TotalCost, \n" - . " COLD_TotalPrice, \n" - . " COLD_Count, \n" - . " COLD_PersonNum, \n" - . " COLD_ChildNum, \n" - . " COLD_BabyNum, \n" - . " cold_state, \n" - . " DeleteFlag, \n" - . " COLD_DeliveryCharge, \n" - . " COLD_AddCode, \n" - . " COLD_PlanVEI_SN, \n" - . " COLD_SPFS, \n" - . " COLD_Memo, \n" - . " COLD_MemoText, \n" - . " COLD_ServiceSN \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array( - $this->COLD_COLI_SN, - $this->COLD_ServiceType, - $this->COLD_StartDate, - $this->COLD_EndDate, - $this->COLD_TotalCost, - $this->COLD_TotalPrice, - $this->COLD_Count, - $this->COLD_PersonNum, - $this->COLD_ChildNum, - $this->COLD_BabyNum, - $this->cold_state, - $this->DeleteFlag, - $this->COLD_DeliveryCharge, - $AddCode, - $this->COLD_PlanVEI_SN, - $this->COLD_SPFS, - $this->COLD_Memo, - $this->COLD_MemoText, - $this->COLD_ServiceSN) - ); - //查出最近插入的id - $HT2 = $this->load->database('HT', true); - $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); - return $this->COLD_SN; - } - - var $BIZ_COLL_COLI_SN; - var $BIZ_COLL_type; - var $BIZ_COLL_COLI_Field; - var $BIZ_COLL_COLI_value; - var $BIZ_COLL_OPI_SN; - - function biz_confirm_line_log_save() - { - $sql = "INSERT INTO BIZ_ConfirmLineLog ( - COLL_COLI_SN, - COLL_LogTime, - COLL_type, - COLL_COLI_Field, - COLL_COLI_value, - COLL_OPI_SN - ) VALUES (?,GETDATE(),?,?,?,?) "; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, - $this->BIZ_COLL_type, - $this->BIZ_COLL_COLI_Field, - $this->BIZ_COLL_COLI_value, - $this->BIZ_COLL_OPI_SN) - ); - return $query; - } - - var $POI_SN; - var $POI_COLD_SN; - var $POI_FlightsNo = ''; - var $POI_AirPort = ''; - var $POI_Time; - var $POI_Hotel = ''; - var $POI_HotelAddress = ''; - var $POI_HotelPhone = ''; - var $POI_HotelCheckInName = ''; - var $POI_HotelCheckIn = ''; - var $POI_HotelCheckOut = ''; - var $POI_EndTime = ''; - var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 - /** 包价线路订单入库 */ - public function biz_packageorder_save() - { - $sql = "INSERT INTO BIZ_PackageOrderInfo - (POI_COLD_SN - ,POI_FlightsNo - ,POI_AirPort - ,POI_Time - ,POI_Hotel - ,POI_QuotationType - ,POI_HotelAddress - ,POI_HotelPhone - ,POI_HotelCheckInName - ,POI_HotelCheckIn - ,POI_HotelCheckOut - ,POI_EndTime) - VALUES - (? - ,? - ,N? - ,? - ,N? - ,? - ,N? - ,N? - ,N? - ,N? - ,N? - ,N?) - "; - $query = $this->HT->query($sql, array( - $this->POI_COLD_SN - ,$this->POI_FlightsNo - ,$this->POI_AirPort - ,$this->POI_Time - ,$this->POI_Hotel - ,$this->POI_QuotationType - ,$this->POI_HotelAddress - ,$this->POI_HotelPhone - ,$this->POI_HotelCheckInName - ,$this->POI_HotelCheckIn - ,$this->POI_HotelCheckOut - ,$this->POI_EndTime - )); - $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); - return $this->POI_SN; - } - - var $FOI_SN; - var $FOI_COLD_SN; // 订单子表sn - var $Aircompany; // 航空公司编码 - var $FlightsNo; // 航班号 - var $Cabin; // 舱位 - var $DepartAirport; // 出发机场 - var $ArrivalAirport; // 抵达机场 - var $DepartureCity; // 出发城市 - var $DepartureTime; // 出发日期 - var $ArrivalCity; // 抵达城市 - var $Arrivaltime; // 抵达时间 - var $DepartureDate; // 出发时间 - var $adultCost; // 成人成本 - var $childCost; // 小孩成倍 - var $babyCost; // 婴儿成本 - var $adultPrice; // 成人报价 - var $childPrice; // 小孩报价 - var $babyPrice; // 婴儿报价 - var $Stopover; // - var $PriceY; // Y仓价格 - var $price_low; // 最低价格 - var $FOI_Mile; // 里程 - var $TicketAddress; // 寄送地址 - var $FOI_CostTime = ''; // 运行时间 - var $Aircraft = ''; // 12306座位编号 - var $FOI_ServiceFee_adult = NULL; // 成人服务费 - var $FOI_ServiceFee_child = NULL; // 儿童服务费 - var $FOI_DeliveryFee = NULL; // 寄票费 - var $FOI_SelectedSeat = ""; // 选座 - - /** - * - * 商务机票订单入库 - * - */ - - function biz_flight_order_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" - . "( \n" - . " FOI_COLD_SN, \n" - . " Aircompany, \n" - . " FlightsNo, \n" - . " Cabin, \n" - . " DepartAirport, \n" - . " ArrivalAirport, \n" - . " DepartureCity, \n" - . " DepartureTime, \n" - . " ArrivalCity, \n" - . " Arrivaltime, \n" - . " DepartureDate, \n" - . " adultCost, \n" - . " childCost, \n" - . " babyCost, \n" - . " adultPrice, \n" - . " childPrice, \n" - . " babyPrice, \n" - . " Stopover, \n" - . " PriceY, \n" - . " price_low, \n" - . " FOI_Mile, \n" - . " TicketAddress, \n" - . " FOI_CostTime, \n" - . " FOI_AddCode, \n" - . " Aircraft, \n" - . " FOI_ServiceFee_adult, \n" - . " FOI_ServiceFee_child, \n" - . " FOI_SelectedSeat, \n" - . " FOI_DeliveryFee \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->FOI_COLD_SN, - $this->Aircompany, - $this->FlightsNo, - $this->Cabin, - $this->DepartAirport, - $this->ArrivalAirport, - $this->DepartureCity, - $this->DepartureTime, - $this->ArrivalCity, - $this->Arrivaltime, - $this->DepartureDate, - $this->adultCost, - $this->childCost, - $this->babyCost, - $this->adultPrice, - $this->childPrice, - $this->babyPrice, - $this->Stopover, - $this->PriceY, - $this->price_low, - $this->FOI_Mile, - $this->TicketAddress, - $this->FOI_CostTime, - $AddCode, - $this->Aircraft, - $this->FOI_ServiceFee_adult, - $this->FOI_ServiceFee_child, - $this->FOI_SelectedSeat, - $this->FOI_DeliveryFee - )); - $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); - return $this->FOI_SN; - } - - var $BPE_SN; - var $BPE_FirstName; //客人 - var $BPE_MiddleName; //客人 - var $BPE_LastName; //客人 - var $BPE_GuestType; //客人类型 - var $BPE_Passport; //护照 - var $BPE_imageSrc = NULL; //护照图片 - var $BPE_Nationality; //国籍 - var $BPE_SEX; //性别 - var $BPE_BirthDate; //生日 - var $BPE_PassportType = "Passport No."; //护照类型 - - /** - * - * 商务订单参团客人入库 - * - */ - - function biz_book_people_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_BookPeople \n" - . "( \n" - . " BPE_FirstName, \n" - . " BPE_MiddleName, \n" - . " BPE_LastName, \n" - . " BPE_GuestType, \n" - . " BPE_Passport, \n" - . " BPE_imageSrc, \n" - . " BPE_Nationality, \n" - . " BPE_SEX, \n" - . " BPE_BirthDate, \n" - . " BPE_PassportType, \n" - . " BPE_AddCode \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " N?, \n" - . " N?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $query = $this->HT->query($sql, array( - mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), - mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), - mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, - mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, - $this->BPE_Nationality, - $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); - $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); - return $this->BPE_SN; - } - - /** - * 参团人关联 - * - * @param int 商务子表sn - * @param int 参团客人sn - */ - function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { - $sql = "INSERT INTO BIZ_BookPeopleList \n" - . "( \n" - . " BPL_COLD_SN, \n" - . " BPL_BPE_SN \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ? \n" - . ")"; - // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); - } - /* * 生成订单号 * 根据系统时间生成,精确到0.0001微秒 @@ -1192,166 +446,6 @@ class Order_update extends CI_Model { return $query; } - /** - * wifi预订入库(目前仅CHT使用) - * - * @return int 插入id - */ - var $WOI_COLD_SN; - var $WOI_Device; //设备(智能手机、pad) - var $WOI_DeviceCount; //设备数量 - var $WOI_UsersCount; //使用人数 - var $WOI_Package; //Wi-Fi套餐 - var $WOI_PackageCount; //套餐数量 - var $WOI_DeliverDate; //起租日期 - var $WOI_DeliverCity; //起租城市 - var $WOI_DeliverAddr; //起租地址 - var $WOI_ReturnDate; //归还日期 - var $WOI_ReturnCity; //归还城市 - var $WOI_ReturnAddr; //归还地址 - var $WOI_OtherService; //其他服务 - var $WOI_GroupNo; //团号 - var $WOI_ExpressNo; //快递单号 - - public function biz_wifi_info_save() { - $sql = "INSERT INTO BIZ_WifiOrderInfo \n" - . "( \n" - . " WOI_COLD_SN, \n" - . " WOI_Device, \n" - . " WOI_DeviceCount, \n" - . " WOI_UsersCount, \n" - . " WOI_Package, \n" - . " WOI_PackageCount, \n" - . " WOI_DeliverDate, \n" - . " WOI_DeliverCity, \n" - . " WOI_DeliverAddr, \n" - . " WOI_ReturnDate, \n" - . " WOI_ReturnCity, \n" - . " WOI_ReturnAddr, \n" - . " WOI_OtherService, \n" - . " WOI_GroupNo, \n" - . " WOI_ExpressNo \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->WOI_COLD_SN, - $this->WOI_Device, - $this->WOI_DeviceCount, - $this->WOI_UsersCount, - $this->WOI_Package, - $this->WOI_PackageCount, - $this->WOI_DeliverDate, - $this->WOI_DeliverCity, - $this->WOI_DeliverAddr, - $this->WOI_ReturnDate, - $this->WOI_ReturnCity, - $this->WOI_ReturnAddr, - $this->WOI_OtherService, - $this->WOI_GroupNo, - $this->WOI_ExpressNo - )); - } - - /** - * 酒店预订入库 - * - * @return int 插入id - */ - var $HOI_COLD_SN; //必选 - var $HOI_NoSmoking = null; //无烟房 - var $HOI_EarlyTime = null; //最早确认时间,已不用 - var $HOI_LastTime = null; //最晚确认时间,已不用 - var $HOI_Room_NO = null; //房号 - var $HOI_ExtraNum = 0; //加床 - var $HOI_RoomTypeName = null; //房型 - var $HOI_BreakNum = null; //早餐人数 - var $HOI_PriceType = null; //价格类型 - var $HOI_BreakType = null; //早餐类型 - var $HOI_RoomRates = null; - var $HOI_ExtrabedRates = null; - var $HOI_TaxFee = null; - - public function biz_hotel_order_save() { - /* ASP版本 - sql="select * from BIZ_HotelOrderInfo where 1=2" - rs2.open sql,conn,3,3,1 - rs2.addnew - rs2("HOI_COLD_SN")=COLD_SN - rs2("HOI_ExtraNum") = extrabed - if clng(Smoking)<2 then - rs2("HOI_NoSmoking")=Smoking - end if - rs2("HOI_EarlyTime")=earlydate - rs2("HOI_LastTime")="" - rs2.update - rs2.close - */ - $sql = "INSERT INTO BIZ_HotelOrderInfo \n" - . "( \n" - . " HOI_COLD_SN, \n" - . " HOI_NoSmoking, \n" - . " HOI_EarlyTime, \n" - . " HOI_LastTime, \n" - . " HOI_Room_NO, \n" - . " HOI_ExtraNum, \n" - . " HOI_RoomTypeName, \n" - . " HOI_BreakNum, \n" - . " HOI_PriceType, \n" - . " HOI_BreakType, \n" - . " HOI_RoomRates, \n" - . " HOI_ExtrabedRates, \n" - . " HOI_TaxFee \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array( - $this->HOI_COLD_SN, - $this->HOI_NoSmoking, - $this->HOI_EarlyTime, - $this->HOI_LastTime, - $this->HOI_Room_NO, - $this->HOI_ExtraNum, - $this->HOI_RoomTypeName, - $this->HOI_BreakNum, - $this->HOI_PriceType, - $this->HOI_BreakType, - $this->HOI_RoomRates, - $this->HOI_ExtrabedRates, - $this->HOI_TaxFee - )); - } /** * diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index c436aa2d..e5e9e577 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -56,23 +56,29 @@ class Orders_model extends CI_Model { return $query->result(); } + /*! + * 获取行程详情 + */ + /** 根据订号 */ public function get_scheduleDetails($COLD_SN_str) { $sql = "SELECT * FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN - AND (PAG2_LGC = 2) + INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN AND (PAG2_LGC = 2) + left join BIZ_PackageInfoSub pis on pis.PAGS_PAG_SN=pag.PAG_SN and PAGS_LGC=1 and cold.COLD_ServiceSN2=PAGS_SN WHERE COLD_SN IN ($COLD_SN_str)"; $query = $this->HT->query($sql); return $query->result(); } - + /** 根据线路代号 */ public function get_packageDetails($pag_code_str) { $sql = "SELECT * FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 WHERE pag.PAG_Code IN ($pag_code_str) order by pag.PAG_Code "; $query = $this->HT->query($sql); @@ -101,7 +107,7 @@ class Orders_model extends CI_Model { public function get_packageSN($pag_code) { - $sql = "SELECT top 1 PAG2_SN,PAG_CII_SN + $sql = "SELECT top 1 PAG2_SN,PAG_CII_SN,PAG2_PAG_SN FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 From eaedc2bfcfdacac107a5cacb9fbe766b6a1f73c8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Apr 2018 13:30:50 +0800 Subject: [PATCH 050/382] =?UTF-8?q?trippest=20=E6=95=B4=E7=90=86model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 32 +- .../trippestOrderSync/models/order_insert.php | 1618 ----------------- .../trippestOrderSync/models/order_update.php | 457 ----- .../trippestOrderSync/models/orders_model.php | 56 + 4 files changed, 71 insertions(+), 2092 deletions(-) delete mode 100644 webht/third_party/trippestOrderSync/models/order_insert.php diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 82bc2734..c2eae1c7 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -50,7 +50,6 @@ class TulanduoApi extends CI_Controller public function __construct(){ parent::__construct(); $this->load->model('Orders_model'); - $this->load->model('Order_insert'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); $this->load->helper('array'); @@ -75,8 +74,8 @@ class TulanduoApi extends CI_Controller ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) - ->setStartTravelDate("2018-04-18") - ->setEndTravelDate("2018-04-18") + ->setStartTravelDate("2018-04-19") // test + ->setEndTravelDate("2018-04-19") // ->setStartOrderDate("2018-04-13") // ->setEndOrderDate("2018-04-13") ; @@ -117,7 +116,7 @@ class TulanduoApi extends CI_Controller preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); if (empty($temp_array) && isset($this->pag_no_tmp()[$vo['routeName']])) { // 旧的数据没有线路代号 - $PAG_Code = $pag_sub = $this->pag_no_tmp()[$vo['routeName']]; + $PAG_Code = $this->pag_no_tmp()[$vo['routeName']]; $split_code = explode("-", $PAG_Code); $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; @@ -190,17 +189,17 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->biz_confirm_detail_save(); /** VendorArrangeState */ $vendor_contact = $this->Orders_model->get_vendorContact($this->Orders_model->COLD_PlanVEI_SN); - $this->Order_insert->VAS_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; - $this->Order_insert->VAS_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; - $this->Order_insert->VAS_IsSendSucceed = 1; - $this->Order_insert->VAS_IsConfirm = $vo['orderStatus']; - $this->Order_insert->VAS_IsCancel = 0; - $this->Order_insert->VAS_SendTime = $vo['orderDate']; - $this->Order_insert->VAS_ConfirmTime = $vo['orderStatus'] == 1 ? $vo['orderDate'] : null; - $this->Order_insert->VAS_LMI_SN = !empty($vendor_contact) ? $vendor_contact->LMI_SN : null; - $this->Order_insert->VAS_FaxNo = !empty($vendor_contact) ? $vendor_contact->LMI_AutoFax : null; - $this->Order_insert->VAS_VendorEmail = !empty($vendor_contact) ? $vendor_contact->LMI_ListMail : null; - $this->Order_insert->vendorarrangestate_save(); + $this->Orders_model->VAS_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; + $this->Orders_model->VAS_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; + $this->Orders_model->VAS_IsSendSucceed = 1; + $this->Orders_model->VAS_IsConfirm = $vo['orderStatus']; + $this->Orders_model->VAS_IsCancel = 0; + $this->Orders_model->VAS_SendTime = $vo['orderDate']; + $this->Orders_model->VAS_ConfirmTime = $vo['orderStatus'] == 1 ? $vo['orderDate'] : null; + $this->Orders_model->VAS_LMI_SN = !empty($vendor_contact) ? $vendor_contact->LMI_SN : null; + $this->Orders_model->VAS_FaxNo = !empty($vendor_contact) ? $vendor_contact->LMI_AutoFax : null; + $this->Orders_model->VAS_VendorEmail = !empty($vendor_contact) ? $vendor_contact->LMI_ListMail : null; + $this->Orders_model->vendorarrangestate_save(); $cnt++; } @@ -257,7 +256,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Order_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; $coli_update_column = array( "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark - ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT // 调度信息加上以便在HT界面上显示 todo + ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update @@ -472,7 +471,6 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $reponse = curl_exec($ch); $eval_resp = json_decode($reponse); -log_message('error', " curl postBodyString: ".json_encode($postBody)); if (curl_errno($ch) || $eval_resp->status == 0) { log_message('error', "curl error code: ".curl_error($ch) . $eval_resp->errMsg . "; curl postBodyString: ".json_encode($postBody)); } else { diff --git a/webht/third_party/trippestOrderSync/models/order_insert.php b/webht/third_party/trippestOrderSync/models/order_insert.php deleted file mode 100644 index 7978adaf..00000000 --- a/webht/third_party/trippestOrderSync/models/order_insert.php +++ /dev/null @@ -1,1618 +0,0 @@ -<?php - -class Order_insert extends CI_Model { - - function __construct() { - parent::__construct(); - $this->HT = $this->load->database('HT', TRUE); - //读取默认配置 - $this->COLI_WebCode = $this->config->item('Site_Code'); - $this->COLI_Area = $this->config->item('Site_Area'); - $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); - $this->COLI_department = $this->config->item('Site_Department'); - $this->COLI_Currency = $this->config->item('Site_Currency'); - $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); - $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); - $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); - $this->COLI_OrderStartDate = null; - $this->COLI_Keywords = NULL; - switch ($this->check_device()) { - case 'mobile': - $this->COLI_OrderSource = '62003'; - break; - case 'tablet': - $this->COLI_OrderSource = '62002'; - break; - default: - $this->COLI_OrderSource = '62001'; - } - } - - public function get_orderinfo_detail($COLI_ID) - { - $sql = "SELECT coli.COLI_ID, - coli.COLI_Department, - cold.COLD_ServiceSN, - cold.COLD_ServiceSN2, - cold.COLD_ServiceCity, - * - FROM BIZ_ConfirmLineInfo coli - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE coli.COLI_ID='$COLI_ID' - ORDER BY COLI_ApplyDate DESC"; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_guestlist($COLD_SN_str) - { - $sql = "SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN ($COLD_SN_str)"; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_scheduleDetails($COLD_SN_str) - { - $sql = "SELECT * - FROM BIZ_PackageInfo2 pag2 - INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN - AND (PAG2_LGC = 2) - WHERE COLD_SN IN ($COLD_SN_str)"; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_packageDetails($pag_code_str) - { - $sql = "SELECT * - FROM BIZ_PackageInfo2 pag2 - INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 - WHERE pag.PAG_Code IN ($pag_code_str) - order by pag.PAG_Code "; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_paymentDetails($COLI_ID) - { - $sql = "SELECT * - FROM BIZ_GroupAccountInfo bgai - INNER JOIN BIZ_ConfirmLineInfo coli ON bgai.GAI_COLI_SN=coli.COLI_SN - WHERE coli_ID = '$COLI_ID'"; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_groupCodeList($GroupCodeList_str) - { - $sql = "SELECT GRI_No - FROM GRoupInfo gri - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No IN ($GroupCodeList_str)"; - $query = $this->HT->query($sql); - return $query->result(); - } - - public function get_packageSN($pag_code) - { - $sql = "SELECT top 1 PAG2_SN - FROM BIZ_PackageInfo2 pag2 - INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN - WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 - "; - $query = $this->HT->query($sql); - if ($query->row()) { - return $query->row()->PAG2_SN; - } - return NULL; - } - public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) - { - $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, gci.* - FROM BIZ_GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE 1=1 "; - if ($coli_sn !== 0) { - $sql .= " and gci.GCI_COLI_SN='$coli_sn' "; - } - if ($startDate !== NULL) { - // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; - } - $query = $this->HT->query($sql); - return $query->result(); - } - - public $VAS_GRI_SN; - public $VAS_VEI_SN; - public $VAS_IsSendSucceed; - public $VAS_IsConfirm; - public $VAS_SendTime; - public $VAS_ConfirmTime; - public $VAS_IsCancel; - public $VAS_LMI_SN; - public $VAS_FaxNo; - public $VAS_VendorEmail; - public function vendorarrangestate_save() - { - $sql = "INSERT INTO VendorArrangeState - (VAS_GRI_SN - ,VAS_VEI_SN - ,VAS_IsSendSucceed - ,VAS_IsConfirm - ,VAS_SendTime - ,VAS_ConfirmTime - ,VAS_IsCancel - ,VAS_LMI_SN - ,VAS_FaxNo - ,VAS_VendorEmail - ,Creator - ,LastEditTime - ,DeleteFlag - ) VALUES - (? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,0 - ,GETDATE() - ,0 - )"; - $query = $this->HT->query($sql, array( - $this->VAS_GRI_SN - ,$this->VAS_VEI_SN - ,$this->VAS_IsSendSucceed - ,$this->VAS_IsConfirm - ,$this->VAS_SendTime - ,$this->VAS_ConfirmTime - ,$this->VAS_IsCancel - ,$this->VAS_LMI_SN - ,$this->VAS_FaxNo - ,$this->VAS_VendorEmail - )); - return $query; - } - - /** 团信息 */ - public $GRI_SN=0; // 团号 - public $GRI_No; // 团号 - public $GRI_OrderType; // 订单类型 - public $GRI_Name; // 团名 - public $GRI_PersonNum; // 人数 - public $GRI_Days; // 行程天数 - public $GRI_IsCancel=0; - public $GRI_DeleteFlag=0; - public function groupinfo_save() - { - $sql = "INSERT INTO GRoupInfo - (GRI_No - ,GRI_Name - ,GRI_PersonNum - ,GRI_Days - ,GRI_IsCancel - ,DeleteFlag - ,GRI_OrderType) - VALUES (N?,N?,?,?,?,?,?)"; - $query = $this->HT->query($sql, array( - $this->GRI_No, - $this->GRI_Name, - $this->GRI_PersonNum, - $this->GRI_Days, - $this->GRI_IsCancel, - $this->GRI_DeleteFlag, - $this->GRI_OrderType - )); - $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); - return $this->GRI_SN; - } - - /** 目的地订单 拼团信息 */ - public $GCI_SN; - public $GCI_combineNo=''; // 拼团团号 - public $GCI_COLI_SN; // 订单key - public $GCI_VendorOrderId; // 地接社系统订单id - public $GCI_FromAgc; // 组团社来源 - public $GCI_groupType; // 组团社来源 - public $GCI_travelDate; - public $GCI_leaveDate; - public $GCI_createTime; - public function biz_groupcombineinfo_save() - { - $sql = "IF NOT EXISTS( - SELECT TOP 1 1 - FROM BIZ_GroupCombineInfo - WHERE GCI_VendorOrderId = ? - ) - INSERT INTO BIZ_GroupCombineInfo - (GCI_combineNo - ,GCI_COLI_SN - ,GCI_VendorOrderId - ,GCI_FromAgc - ,GCI_groupType - ,GCI_travelDate - ,GCI_leaveDate - ,GCI_createTime) - VALUES - (N? - ,? - ,? - ,N? - ,? - ,? - ,? - ,?) - "; - $query = $this->HT->query($sql, array( - $this->GCI_VendorOrderId - // ,$this->GCI_COLI_SN - ,$this->GCI_combineNo - ,$this->GCI_COLI_SN - ,$this->GCI_VendorOrderId - ,$this->GCI_FromAgc - ,$this->GCI_groupType - ,$this->GCI_travelDate - ,$this->GCI_leaveDate - ,$this->GCI_createTime - )); - $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); - return $this->GCI_SN; - } - public function combineoperation_exist($combineNo='', $operation="") - { - if( ! $combineNo) { return false; } - $sql = "SELECT TOP 1 GCOD_GCI_combineNo - FROM BIZ_GroupCombineOperationDetail - WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; - $query = $this->HT->query($sql, array( - $combineNo,$operation - )); - return $query->result(); - } - public $GCOD_SN; - public $GCOD_GCI_combineNo = ''; - public $GCOD_operationType = ''; - public $GCOD_subType = ''; - public $GCOD_title = ''; - public $GCOD_dutyName = ''; - public $GCOD_dutyTel; - public $GCOD_dutyPhoto; - public $GCOD_startDate; - public $GCOD_endDate; - public $GCOD_useNum=1; - public $GCOD_sumMoney; - public $GCOD_standard = ''; - public $GCOD_carLicense = ''; - public $GCOD_remark = ''; - public $GCOD_creatTime; - public function biz_groupcombineoperationdetail_save() - { - // IF NOT EXISTS( - // SELECT TOP 1 1 - // FROM BIZ_GroupCombineOperationDetail - // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? - // ) - $sql = "INSERT INTO BIZ_GroupCombineOperationDetail - (GCOD_GCI_combineNo - ,GCOD_operationType - ,GCOD_subType - ,GCOD_title - ,GCOD_dutyName - ,GCOD_dutyTel - ,GCOD_dutyPhoto - ,GCOD_startDate - ,GCOD_endDate - ,GCOD_useNum - ,GCOD_sumMoney - ,GCOD_standard - ,GCOD_carLicense - ,GCOD_remark - ,GCOD_creatTime) - VALUES - (N? - ,N? - ,N? - ,N? - ,N? - ,? - ,? - ,? - ,? - ,? - ,? - ,N? - ,N? - ,N? - ,GETDATE()) - "; - $query = $this->HT->query($sql, array( - $this->GCOD_GCI_combineNo - ,$this->GCOD_operationType - // ,$this->GCOD_GCI_combineNo - // ,$this->GCOD_operationType - ,$this->GCOD_subType - ,$this->GCOD_title - ,$this->GCOD_dutyName - ,$this->GCOD_dutyTel - ,$this->GCOD_dutyPhoto - ,$this->GCOD_startDate - ,$this->GCOD_endDate - ,$this->GCOD_useNum - ,$this->GCOD_sumMoney - ,$this->GCOD_standard - ,$this->GCOD_carLicense - ,$this->GCOD_remark - )); - return $query; - } - - - - var $GUT_SN; - var $GUT_FirstName; //联系人 - var $GUT_LastName = ""; //联系人 - var $GUT_Title; //称谓 - var $GUT_Email; //主email - var $GUT_Email2; //备用email - var $GUT_NationalityID; //国家 - var $GUT_Passport; //护照 - var $GUT_TEL; //座机 - var $GUT_MoveTel; //手机 - - /** - * 商务联系人表入库 - * - * @return int GUT_SN 插入id - */ - - function biz_guest_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_Guest \n" - . " ( \n" - . " GUT_FirstName, \n" - . " GUT_LastName, \n" - . " GUT_Title, \n" - . " GUT_Email, \n" - . " GUT_Email2, \n" - . " GUT_NationalityID, \n" - . " GUT_Passport, \n" - . " GUT_TEL, \n" - . " GUT_MoveTel, \n" - . " GUT_AddCode, \n" - . " GUT_CreateDate \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " N?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " GETDATE() \n" - . " )"; - $query = $this->HT->query($sql, array( - mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), - mb_convert_encoding($this->GUT_LastName, 'UTF-8'), - $this->GUT_Title, - $this->GUT_Email, - $this->GUT_Email2, - $this->GUT_NationalityID, - mb_convert_encoding($this->GUT_Passport, 'UTF-8'), - $this->GUT_TEL, - $this->GUT_MoveTel, $AddCode - )); - $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); - return $this->GUT_SN; - } - - public function get_SN_by_vendorOrderId($vendorOrderId) - { - $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN - FROM BIZ_GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN - WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; - $query = $this->HT->query($sql); - if ($query->row()) { - $this->BIZ_COLI_SN = $query->row()->COLI_SN; - $this->GRI_SN = $query->row()->COLI_GRI_SN; - $this->GCI_SN = $query->row()->GCI_SN; - return $query->row(); - } - return NULL; - } - - public function get_SN_by_groupCode($code) - { - $sql = "SELECT top 1 COLI_SN,GRI_SN - FROM BIZ_ConfirmLineInfo coli - LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '$code%'"; - $query = $this->HT->query($sql); - if ($query->row()) { - $this->BIZ_COLI_SN = $query->row()->COLI_SN; - $this->GRI_SN = $query->row()->GRI_SN; - return $query->row(); - } - return NULL; - } - - var $BIZ_COLI_SN; - var $BIZ_COLI_ID; - var $BIZ_COLI_GUT_SN; //联系人id - var $BIZ_COLI_Area; //市场 - var $BIZ_COLI_ApplyDate = ''; //提交日期 - var $BIZ_COLI_Price; //订单总价 - var $BIZ_COLI_Cost; //总成本 - var $BIZ_COLI_Currency; //币种 - var $BIZ_COLI_TrueCardRate; //信用卡手续费 - var $BIZ_COLI_SenderIP = ''; //客人ip - var $BIZ_COLI_WebCode = ''; //站点code - var $BIZ_COLI_servicetype; //订单来源类型 - var $BIZ_COLI_sourcetype; //预定类型 - var $BIZ_COLI_AgencyID; - var $BIZ_COLI_ConfirmType; //提交方式 - var $BIZ_COLI_OrderDetailText; - var $BIZ_COLI_OriginalText=''; - var $BIZ_COLI_Memo; - var $BIZ_COLI_GRI_SN; - var $BIZ_COLI_GroupCode=''; - var $BIZ_COLI_State; - - /** - * 商务订单主表入库 - * @return int BIZ_COLI_ID 插入id - */ - function biz_confirm_save() { - // if (empty($this->BIZ_COLI_WebCode)) { - $this->BIZ_COLI_WebCode = '';// 来源图兰朵 - // } - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" - . "( \n" - . " COLI_ID, \n" - . " COLI_GUT_SN, \n" - . " COLI_Area, \n" - . " COLI_ApplyDate, \n" - . " COLI_Price, \n" - . " COLI_Cost, \n" - . " COLI_Currency, \n" - . " COLI_TrueCardRate, \n" - . " COLI_AgencyID, \n" - . " COLI_OrderDetailText, \n" - . " COLI_SenderIP, \n" - . " COLI_WebCode, \n" - . " COLI_servicetype, \n" - . " COLI_sourcetype, \n" - . " COLI_ConfirmType, \n" - . " COLI_State, \n" - . " COLI_Department, \n" - . " COLI_AddCode, \n" - . " COLI_OrderSource, \n" - . " COLI_Memo, \n" - . " COLI_GRI_SN, \n" - . " COLI_GroupCode, \n" - . " COLI_OriginalText \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " N?, \n" - . " N? \n" - . ")"; - $query = $this->HT->query($sql, array( - $this->BIZ_COLI_ID, - $this->BIZ_COLI_GUT_SN, - 2, - // $this->config->item('Site_Area'), - //date("Y-m-d H:i:s"), - $this->BIZ_COLI_ApplyDate, - $this->BIZ_COLI_Price, - $this->BIZ_COLI_Cost, - $this->config->item('Site_Currency'), - $this->BIZ_COLI_TrueCardRate, - $this->BIZ_COLI_AgencyID, - $this->BIZ_COLI_OrderDetailText, - $this->BIZ_COLI_SenderIP, - $this->BIZ_COLI_WebCode, - $this->BIZ_COLI_servicetype, - $this->BIZ_COLI_sourcetype, - $this->BIZ_COLI_ConfirmType, - $this->BIZ_COLI_State, - 30,// $this->config->item('Site_Department'), - $AddCode, - $this->COLI_OrderSource, - $this->BIZ_COLI_Memo, - $this->BIZ_COLI_GRI_SN, - $this->BIZ_COLI_GroupCode, - $this->BIZ_COLI_OriginalText - )); - $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); - return $this->BIZ_COLI_SN; - } - - public function update_confirmLineInfo() - { - $sql = "UPDATE BIZ_ConfirmLineInfo SET - COLI_GRI_SN=?, - COLI_GroupCode=? - WHERE COLI_SN=? - "; - $query = $this->HT->query($sql, array( - $this->BIZ_COLI_GRI_SN - ,$this->BIZ_COLI_GroupCode - ,$this->BIZ_COLI_SN - )); - return $this->query; - } - - var $COLD_SN; - var $COLD_COLI_SN; // 订单主表sn - var $COLD_ServiceType; // 服务类型 - var $COLD_StartDate; // 产品的服务的开始日期 - var $COLD_EndDate; // 产品的服务的结束日期 - var $COLD_TotalCost; // 总成本 - var $COLD_TotalPrice; // 总报价 - var $COLD_Count; // 产品数量 - var $COLD_PersonNum; // 成人数 - var $COLD_ChildNum; // 小孩数 - var $COLD_BabyNum; // 婴儿数 - var $cold_state; // 状态 - var $DeleteFlag; // 删除标志 - var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY - var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 - var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 - var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID - var $COLD_Memo = NULL; - var $COLD_MemoText = NULL; - - /** - * 商务订单子(详细)表入库 - * - * @return int 插入id - */ - - function biz_confirm_detail_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" - . "( \n" - . " COLD_COLI_SN, \n" - . " COLD_ServiceType, \n" - . " COLD_StartDate, \n" - . " COLD_EndDate, \n" - . " COLD_TotalCost, \n" - . " COLD_TotalPrice, \n" - . " COLD_Count, \n" - . " COLD_PersonNum, \n" - . " COLD_ChildNum, \n" - . " COLD_BabyNum, \n" - . " cold_state, \n" - . " DeleteFlag, \n" - . " COLD_DeliveryCharge, \n" - . " COLD_AddCode, \n" - . " COLD_PlanVEI_SN, \n" - . " COLD_SPFS, \n" - . " COLD_Memo, \n" - . " COLD_MemoText, \n" - . " COLD_ServiceSN \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array( - $this->COLD_COLI_SN, - $this->COLD_ServiceType, - $this->COLD_StartDate, - $this->COLD_EndDate, - $this->COLD_TotalCost, - $this->COLD_TotalPrice, - $this->COLD_Count, - $this->COLD_PersonNum, - $this->COLD_ChildNum, - $this->COLD_BabyNum, - $this->cold_state, - $this->DeleteFlag, - $this->COLD_DeliveryCharge, - $AddCode, - $this->COLD_PlanVEI_SN, - $this->COLD_SPFS, - $this->COLD_Memo, - $this->COLD_MemoText, - $this->COLD_ServiceSN) - ); - //查出最近插入的id - $HT2 = $this->load->database('HT', true); - $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); - return $this->COLD_SN; - } - - var $BIZ_COLL_COLI_SN; - var $BIZ_COLL_type; - var $BIZ_COLL_COLI_Field; - var $BIZ_COLL_COLI_value; - var $BIZ_COLL_OPI_SN; - - function biz_confirm_line_log_save() - { - $sql = "INSERT INTO BIZ_ConfirmLineLog ( - COLL_COLI_SN, - COLL_LogTime, - COLL_type, - COLL_COLI_Field, - COLL_COLI_value, - COLL_OPI_SN - ) VALUES (?,GETDATE(),?,?,?,?) "; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, - $this->BIZ_COLL_type, - $this->BIZ_COLL_COLI_Field, - $this->BIZ_COLL_COLI_value, - $this->BIZ_COLL_OPI_SN) - ); - return $query; - } - - var $POI_SN; - var $POI_COLD_SN; - var $POI_FlightsNo = ''; - var $POI_AirPort = ''; - var $POI_Time; - var $POI_Hotel = ''; - var $POI_HotelAddress = ''; - var $POI_HotelPhone = ''; - var $POI_HotelCheckInName = ''; - var $POI_HotelCheckIn = ''; - var $POI_HotelCheckOut = ''; - var $POI_EndTime = ''; - var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 - /** 包价线路订单入库 */ - public function biz_packageorder_save() - { - $sql = "INSERT INTO BIZ_PackageOrderInfo - (POI_COLD_SN - ,POI_FlightsNo - ,POI_AirPort - ,POI_Time - ,POI_Hotel - ,POI_QuotationType - ,POI_HotelAddress - ,POI_HotelPhone - ,POI_HotelCheckInName - ,POI_HotelCheckIn - ,POI_HotelCheckOut - ,POI_EndTime) - VALUES - (? - ,? - ,N? - ,? - ,N? - ,? - ,N? - ,N? - ,N? - ,N? - ,N? - ,N?) - "; - $query = $this->HT->query($sql, array( - $this->POI_COLD_SN - ,$this->POI_FlightsNo - ,$this->POI_AirPort - ,$this->POI_Time - ,$this->POI_Hotel - ,$this->POI_QuotationType - ,$this->POI_HotelAddress - ,$this->POI_HotelPhone - ,$this->POI_HotelCheckInName - ,$this->POI_HotelCheckIn - ,$this->POI_HotelCheckOut - ,$this->POI_EndTime - )); - $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); - return $this->POI_SN; - } - - var $FOI_SN; - var $FOI_COLD_SN; // 订单子表sn - var $Aircompany; // 航空公司编码 - var $FlightsNo; // 航班号 - var $Cabin; // 舱位 - var $DepartAirport; // 出发机场 - var $ArrivalAirport; // 抵达机场 - var $DepartureCity; // 出发城市 - var $DepartureTime; // 出发日期 - var $ArrivalCity; // 抵达城市 - var $Arrivaltime; // 抵达时间 - var $DepartureDate; // 出发时间 - var $adultCost; // 成人成本 - var $childCost; // 小孩成倍 - var $babyCost; // 婴儿成本 - var $adultPrice; // 成人报价 - var $childPrice; // 小孩报价 - var $babyPrice; // 婴儿报价 - var $Stopover; // - var $PriceY; // Y仓价格 - var $price_low; // 最低价格 - var $FOI_Mile; // 里程 - var $TicketAddress; // 寄送地址 - var $FOI_CostTime = ''; // 运行时间 - var $Aircraft = ''; // 12306座位编号 - var $FOI_ServiceFee_adult = NULL; // 成人服务费 - var $FOI_ServiceFee_child = NULL; // 儿童服务费 - var $FOI_DeliveryFee = NULL; // 寄票费 - var $FOI_SelectedSeat = ""; // 选座 - - /** - * - * 商务机票订单入库 - * - */ - - function biz_flight_order_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" - . "( \n" - . " FOI_COLD_SN, \n" - . " Aircompany, \n" - . " FlightsNo, \n" - . " Cabin, \n" - . " DepartAirport, \n" - . " ArrivalAirport, \n" - . " DepartureCity, \n" - . " DepartureTime, \n" - . " ArrivalCity, \n" - . " Arrivaltime, \n" - . " DepartureDate, \n" - . " adultCost, \n" - . " childCost, \n" - . " babyCost, \n" - . " adultPrice, \n" - . " childPrice, \n" - . " babyPrice, \n" - . " Stopover, \n" - . " PriceY, \n" - . " price_low, \n" - . " FOI_Mile, \n" - . " TicketAddress, \n" - . " FOI_CostTime, \n" - . " FOI_AddCode, \n" - . " Aircraft, \n" - . " FOI_ServiceFee_adult, \n" - . " FOI_ServiceFee_child, \n" - . " FOI_SelectedSeat, \n" - . " FOI_DeliveryFee \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->FOI_COLD_SN, - $this->Aircompany, - $this->FlightsNo, - $this->Cabin, - $this->DepartAirport, - $this->ArrivalAirport, - $this->DepartureCity, - $this->DepartureTime, - $this->ArrivalCity, - $this->Arrivaltime, - $this->DepartureDate, - $this->adultCost, - $this->childCost, - $this->babyCost, - $this->adultPrice, - $this->childPrice, - $this->babyPrice, - $this->Stopover, - $this->PriceY, - $this->price_low, - $this->FOI_Mile, - $this->TicketAddress, - $this->FOI_CostTime, - $AddCode, - $this->Aircraft, - $this->FOI_ServiceFee_adult, - $this->FOI_ServiceFee_child, - $this->FOI_SelectedSeat, - $this->FOI_DeliveryFee - )); - $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); - return $this->FOI_SN; - } - - var $BPE_SN; - var $BPE_FirstName; //客人 - var $BPE_MiddleName; //客人 - var $BPE_LastName; //客人 - var $BPE_GuestType; //客人类型 - var $BPE_Passport; //护照 - var $BPE_imageSrc = NULL; //护照图片 - var $BPE_Nationality; //国籍 - var $BPE_SEX; //性别 - var $BPE_BirthDate; //生日 - var $BPE_PassportType = "Passport No."; //护照类型 - - /** - * - * 商务订单参团客人入库 - * - */ - - function biz_book_people_save() { - //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 - $AddCode = $this->MakeOrderNumber(); - $sql = "INSERT INTO BIZ_BookPeople \n" - . "( \n" - . " BPE_FirstName, \n" - . " BPE_MiddleName, \n" - . " BPE_LastName, \n" - . " BPE_GuestType, \n" - . " BPE_Passport, \n" - . " BPE_imageSrc, \n" - . " BPE_Nationality, \n" - . " BPE_SEX, \n" - . " BPE_BirthDate, \n" - . " BPE_PassportType, \n" - . " BPE_AddCode \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " N?, \n" - . " N?, \n" - . " N?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $query = $this->HT->query($sql, array( - mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), - mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), - mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, - mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, - $this->BPE_Nationality, - $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); - $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); - return $this->BPE_SN; - } - - /** - * 参团人关联 - * - * @param int 商务子表sn - * @param int 参团客人sn - */ - function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { - $sql = "INSERT INTO BIZ_BookPeopleList \n" - . "( \n" - . " BPL_COLD_SN, \n" - . " BPL_BPE_SN \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ? \n" - . ")"; - // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); - } - - /* - * 生成订单号 - * 根据系统时间生成,精确到0.0001微秒 - */ - - function MakeOrderNumber() { - return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); - } - - /** - * 生成商务订单号 - */ - function biz_make_order_number() { - /* - $date = date('ymd',time()); - $sql = "SELECT MAX( \n" - . " CONVERT( \n" - . " INT, \n" - . " CASE \n" - . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" - . " ELSE RIGHT(COLI_ID, 3) \n" - . " END \n" - . " ) \n" - . " ) AS SN \n" - . "FROM dbo.BIZ_ConfirmLineInfo \n" - . "WHERE (LEFT(COLI_ID, 6) = ?)"; - $query = $this->HT->query($sql,array($date)); - $id = $query->row()->SN; - if (is_null($id)||empty($id)) - { - $id = 0; - } - $ids = $date.(sprintf('%03d',(int)$id+1)); - return $ids; - */ - //call $conn - include('c:/database_conn.php'); - $connection = array( - 'UID' => $db['HT']['username'], - 'PWD' => $db['HT']['password'], - 'Database' => 'tourmanager', - 'ConnectionPooling' => 1, - 'CharacterSet' => 'utf-8', - 'ReturnDatesAsStrings' => 1 - ); - $conn = sqlsrv_connect($db['HT']['hostname'], $connection); - $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); - if ($stmt === false) { - echo "Error in executing statement 3.\n"; - die(print_r(sqlsrv_errors(), true)); - } else { - //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 - //如果结果集为空就移到下一个 - while (sqlsrv_has_rows($stmt) !== TRUE) { - sqlsrv_next_result($stmt); - } - - $result_object = array(); - while ($row = sqlsrv_fetch_object($stmt)) { - $result_object[] = $row; - } - - sqlsrv_free_stmt($stmt); - sqlsrv_close($conn); - - return($result_object[0]->ccid); - } - } - - /** - * - * 更新订单状态(商务订单) - * - */ - public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { - //更新订单 - $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; - $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); - $this->insert_acc_info($order_id); - return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); - } - - /** - * - * 更新火车订单购票截图 - * - */ - public function update_train_order_pic($order_pic_id) { - //更新订单 - $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; - //$query = $this->HT->query($sql); - - include('c:/database_conn.php'); - $connection = array( - 'UID' => $db['HT']['username'], - 'PWD' => $db['HT']['password'], - 'Database' => 'tourmanager', - 'ConnectionPooling' => 1, - 'CharacterSet' => 'utf-8', - 'ReturnDatesAsStrings' => 1 - ); - $conn = sqlsrv_connect($db['HT']['hostname'], $connection); - $stmt = sqlsrv_query($conn, $sql); - - return $stmt; - } - - /** - * - * 插入收款记录 - * - */ - public function insert_acc_info($order_id) { - //获取订单 - $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; - $query = $this->HT->query($sql, array($order_id)); - $order_info = $query->row(); - //插入记录 - $sql = "INSERT INTO BIZ_GroupAccountInfo \n" - . " ( \n" - . " GAI_COLI_SN, \n" - . " GAI_COLI_ID, \n" - . " GAI_Type, \n" - . " GAI_SQJE, \n" - . " GAI_SQDate, \n" - . " GAI_SSJE, \n" - . " GAI_SQJECurrency, \n" - . " GAI_SSDate, \n" - . " GAI_CusName, \n" - . " GAI_CusEmail, \n" - . " GAI_Memo \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . " )"; - $query = $this->HT->query($sql, array($order_info->COLI_SN, - $order_info->COLI_ID, - $order_info->COLI_PayManner, - $order_info->COLI_Price, - date('Y-m-d H:i:s'), - $order_info->COLI_Price, - $this->config->item('Site_Currency'), - date('Y-m-d H:i:s'), - "", "", " ")); - } - - function GetNationalityID($nationalityName) { - if (!$nationalityName) { - return 0; - } - if (is_numeric($nationalityName)) { - return $nationalityName; - } else { - $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" - . "FROM COuntryInfo2 ci2 \n" - . "WHERE ci2.COI2_Country = ? "; - $query = $this->HT->query($sql, array($nationalityName)); - if ($query->result()) { - $row = $query->row(); - return $row->COI2_COI_SN; - } else { - return 0; - } - } - } - - function GetNationalityName($nationalityID) { - if (!is_numeric($nationalityID)) { - return $nationalityID; - } else { - $sql = "SELECT TOP 1 ci2.COI2_Country \n" - . "FROM COuntryInfo2 ci2 \n" - . "WHERE ci2.COI2_LGC = 2 \n" - . " AND ci2.COI2_COI_SN = ? "; - $query = $this->HT->query($sql, array($nationalityID)); - if ($query->result()) { - $row = $query->row(); - return $row->COI2_Country; - } else { - return $nationalityID; - } - } - } - - /** - * - * 获取商务订单信息 - * @param string $order_id 订单id - * @return mixed 订单信息 - * - */ - public function get_flight_order_by_id($order_id) { - $sql = "SELECT DISTINCT cli.COLI_ID, \n" - . " cli.COLI_Price, \n" - . " bg.GUT_FirstName, \n" - . " bg.GUT_LastName, \n" - . " bg.GUT_Email, \n" - . " bg.GUT_Email2, \n" - . " bpe.BPE_SN, \n" - . " bpe.BPE_GuestType, \n" - . " bpe.BPE_FirstName, \n" - . " bpe.BPE_MiddleName, \n" - . " bpe.BPE_LastName, \n" - . " bpe.BPE_GuestType, \n" - . " bpe.BPE_Passport, \n" - . " cld.COLD_Count, \n" - . " foi.FlightsNo, \n" - . " foi.DepartureDate, \n" - . " foi.DepartureTime, \n" - . " foi.ArrivalTime, \n" - . " cli.COLI_PayManner, \n" - . " cli.COLI_State, \n" - . " cli.COLI_sourcetype, \n" - . " foi.Cabin, \n" - . " foi.DepartAirport, \n" - . " foi.ArrivalAirport, \n" - . " cld.COLD_SN, \n" - . " foi.DepartureCity, \n" - . " foi.ArrivalCity, \n" - . " bg.GUT_TEL, \n" - . " bg.GUT_NationalityID, \n" - . " cli.COLI_OrderDetailText, \n" - . " bpe.BPE_imageSrc, \n" - . " cli.COLI_Cost, \n" - . " cld.COLD_TotalPrice, \n" - . " cld.COLD_TotalCost \n" - . "FROM BIZ_ConfirmLineInfo cli \n" - . " INNER JOIN BIZ_ConfirmLineDetail cld \n" - . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" - . " INNER JOIN BIZ_GUEST bg \n" - . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" - . " INNER JOIN BIZ_BookPeopleList bpl \n" - . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" - . " INNER JOIN BIZ_BookPeople bpe \n" - . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" - . " INNER JOIN BIZ_FlightsOrderInfo foi \n" - . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" - . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; - - $query = $this->HT->query($sql, array($order_id)); - return $query->result(); - } - - /** - * - * 获取机票订单乘员列表 - * @param string $order_id 订单id - * @return mixed 订单信息 - * - */ - public function get_bpe_list_by_id($order_id) { - $sql = "SELECT DISTINCT bpe.BPE_SN, \n" - . " bpe.BPE_FirstName, \n" - . " bpe.BPE_MiddleName, \n" - . " bpe.BPE_LastName, \n" - . " bpe.BPE_Passport \n" - . "FROM BIZ_BookPeople bpe \n" - . " INNER JOIN BIZ_BookPeopleList bpl \n" - . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" - . " INNER JOIN BIZ_ConfirmLineDetail cold \n" - . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" - . " INNER JOIN BIZ_ConfirmLineInfo coli \n" - . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" - . "WHERE coli.COLI_ID = ?"; - $query = $this->HT->query($sql, array($order_id)); - //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); - return $query->result(); - } - - /** - * - * 获取机票电子票号 - * @param array bpe_sn 乘客sn数组 - * @return mixed 机票票号 - * - */ - public function get_ticket_no($bpe_sn) { - if (is_array($bpe_sn)) { - $instr = join(',', $bpe_sn); - } elseif (is_string($bpe_sn)) { - $instr = $bpe_sn; - } else { - $instr = 0; - } - $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" - . " ftn.FTN_TicketNo, \n" - . " ftn.FTN_GuestNo \n" - . "FROM BIZ_FlightsTicketNo ftn \n" - . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; - $query = $this->HT->query($sql); - return $query->result(); - } - - /* - * 发送邮件 - */ - - function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { - $sql = "INSERT INTO Email_AutomaticSend \n" - . " ( \n" - . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" - . " M_FromName, M_State \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" - . " ) "; - $query = $this->HT->query($sql, - array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) - ); - return $query; - } - - /** - * wifi预订入库(目前仅CHT使用) - * - * @return int 插入id - */ - var $WOI_COLD_SN; - var $WOI_Device; //设备(智能手机、pad) - var $WOI_DeviceCount; //设备数量 - var $WOI_UsersCount; //使用人数 - var $WOI_Package; //Wi-Fi套餐 - var $WOI_PackageCount; //套餐数量 - var $WOI_DeliverDate; //起租日期 - var $WOI_DeliverCity; //起租城市 - var $WOI_DeliverAddr; //起租地址 - var $WOI_ReturnDate; //归还日期 - var $WOI_ReturnCity; //归还城市 - var $WOI_ReturnAddr; //归还地址 - var $WOI_OtherService; //其他服务 - var $WOI_GroupNo; //团号 - var $WOI_ExpressNo; //快递单号 - - public function biz_wifi_info_save() { - $sql = "INSERT INTO BIZ_WifiOrderInfo \n" - . "( \n" - . " WOI_COLD_SN, \n" - . " WOI_Device, \n" - . " WOI_DeviceCount, \n" - . " WOI_UsersCount, \n" - . " WOI_Package, \n" - . " WOI_PackageCount, \n" - . " WOI_DeliverDate, \n" - . " WOI_DeliverCity, \n" - . " WOI_DeliverAddr, \n" - . " WOI_ReturnDate, \n" - . " WOI_ReturnCity, \n" - . " WOI_ReturnAddr, \n" - . " WOI_OtherService, \n" - . " WOI_GroupNo, \n" - . " WOI_ExpressNo \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array($this->WOI_COLD_SN, - $this->WOI_Device, - $this->WOI_DeviceCount, - $this->WOI_UsersCount, - $this->WOI_Package, - $this->WOI_PackageCount, - $this->WOI_DeliverDate, - $this->WOI_DeliverCity, - $this->WOI_DeliverAddr, - $this->WOI_ReturnDate, - $this->WOI_ReturnCity, - $this->WOI_ReturnAddr, - $this->WOI_OtherService, - $this->WOI_GroupNo, - $this->WOI_ExpressNo - )); - } - - /** - * 酒店预订入库 - * - * @return int 插入id - */ - var $HOI_COLD_SN; //必选 - var $HOI_NoSmoking = null; //无烟房 - var $HOI_EarlyTime = null; //最早确认时间,已不用 - var $HOI_LastTime = null; //最晚确认时间,已不用 - var $HOI_Room_NO = null; //房号 - var $HOI_ExtraNum = 0; //加床 - var $HOI_RoomTypeName = null; //房型 - var $HOI_BreakNum = null; //早餐人数 - var $HOI_PriceType = null; //价格类型 - var $HOI_BreakType = null; //早餐类型 - var $HOI_RoomRates = null; - var $HOI_ExtrabedRates = null; - var $HOI_TaxFee = null; - - public function biz_hotel_order_save() { - /* ASP版本 - sql="select * from BIZ_HotelOrderInfo where 1=2" - rs2.open sql,conn,3,3,1 - rs2.addnew - rs2("HOI_COLD_SN")=COLD_SN - rs2("HOI_ExtraNum") = extrabed - if clng(Smoking)<2 then - rs2("HOI_NoSmoking")=Smoking - end if - rs2("HOI_EarlyTime")=earlydate - rs2("HOI_LastTime")="" - rs2.update - rs2.close - */ - $sql = "INSERT INTO BIZ_HotelOrderInfo \n" - . "( \n" - . " HOI_COLD_SN, \n" - . " HOI_NoSmoking, \n" - . " HOI_EarlyTime, \n" - . " HOI_LastTime, \n" - . " HOI_Room_NO, \n" - . " HOI_ExtraNum, \n" - . " HOI_RoomTypeName, \n" - . " HOI_BreakNum, \n" - . " HOI_PriceType, \n" - . " HOI_BreakType, \n" - . " HOI_RoomRates, \n" - . " HOI_ExtrabedRates, \n" - . " HOI_TaxFee \n" - . ") \n" - . "VALUES \n" - . "( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . ")"; - $HT1 = $this->load->database('HT', true); - $query = $HT1->query($sql, array( - $this->HOI_COLD_SN, - $this->HOI_NoSmoking, - $this->HOI_EarlyTime, - $this->HOI_LastTime, - $this->HOI_Room_NO, - $this->HOI_ExtraNum, - $this->HOI_RoomTypeName, - $this->HOI_BreakNum, - $this->HOI_PriceType, - $this->HOI_BreakType, - $this->HOI_RoomRates, - $this->HOI_ExtrabedRates, - $this->HOI_TaxFee - )); - } - - /** - * - * 返回成行订单 - * 条件1:订单类型 - * 天剑2:网站来源 - * - */ - public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { - if ($biz) { - $sql = "SELECT TOP 200 c.COLI_WebCode, \n" - . " c.COLI_ID, \n" - . " c.COLI_ConfirmDate, \n" - . " c.COLI_ApplyDate, \n" - . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" - . "FROM BIZ_ConfirmLineInfo c \n" - . "WHERE c.COLI_sourcetype = ? \n" - . " AND c.COLI_WebCode = ? \n" - . "ORDER BY \n" - . " c.COLI_SN DESC"; - $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); - } else { - $sql = "SELECT TOP 200 c.COLI_WebCode, \n" - . " c.COLI_ID, \n" - . " c.COLI_ConfirmDate, \n" - . " c.COLI_ApplyDate, \n" - . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" - . "FROM ConfirmLineInfo c \n" - . "WHERE c.COLI_sourcetype = ? \n" - . " AND c.COLI_WebCode = ? \n" - . "ORDER BY \n" - . " c.COLI_SN DESC"; - $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); - } - $this->sql = $this->HT->queries; - return $query->result(); - } - - //传统订单支付之后,插入新的订单信息 - public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { - //获取订单 - $order_info_sql = " - SELECT confirmlineinfotmp.COLI_OrderPrice, - memberinfotmp.MEI_FirstName, - memberinfotmp.MEI_LastName, - memberinfotmp.MEI_Mail - FROM memberinfotmp - INNER JOIN customerlisttmp - ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn - INNER JOIN confirmlineinfotmp - ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn - WHERE (customerlisttmp.cul_coli_sn = ? )"; - $query = $this->HT->query($order_info_sql, array($coli_sn)); - $order_info = $query->row(); - - //插入记录 - $sql = "INSERT INTO GroupAccountInfoTmp - ( - GAI_COLI_SN, - GAI_SQJE, - GAI_SQDate, - GAI_CusName, - GAI_CusEmail, - GAI_SQJECurrency, - GAI_Type, - LastEditTime, - GAI_GRI_SN, - GAI_State, - DeleteFlag - ) - VALUES (?,?,?,?,?,?,?,?,?,?,?)"; - - $query = $this->HT->query($sql, array($coli_sn, - $order_info->COLI_OrderPrice, - date('Y-m-d H:i:s'), - $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, - $order_info->MEI_Mail, - $this->config->item('Site_Currency'), - $pay_manner, - date('Y-m-d H:i:s'), - $gri_sn, - $state, - $deleteflag - ) - ); - } - - //来源终端 tablet mobile desktop - public function check_device() { - if (isset($_SERVER['HTTP_USER_AGENT'])) { - $ua = $_SERVER['HTTP_USER_AGENT']; - } else { - $ua = ''; - } - ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com - ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. - ## Price will be $2 - $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) - $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent - $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) - - if (!function_exists('androidTablet')) { - - function androidTablet($ua) { //Find out if it is a tablet - if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent - if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) - return true; - } - } - } - - } - $androidTablet = androidTablet($ua); //Do androidTablet function - $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent - - if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) - return 'tablet'; - } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet - return 'mobile'; - } else { //If it's not a mobile device - return 'desktop'; - } - } - - public function ip_limit($ip = "0.0.0.0") - { - if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { - return TRUE; - } - $sql = "SELECT COUNT(1) cnt - FROM ConfirmLineInfoTmp - WHERE 1=1 - AND COLI_SenderIP = ? - AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; - $query = $this->HT->query($sql, array($ip)); - $ret = $query->row(); - if ($ret->cnt > 50) { - return FALSE; - } else { - return TRUE; - } - } - - -} diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 420448b1..e8e0d7b8 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -16,16 +16,6 @@ class Order_update extends CI_Model { $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); $this->COLI_OrderStartDate = null; $this->COLI_Keywords = NULL; - switch ($this->check_device()) { - case 'mobile': - $this->COLI_OrderSource = '62003'; - break; - case 'tablet': - $this->COLI_OrderSource = '62002'; - break; - default: - $this->COLI_OrderSource = '62001'; - } } public $coli_where_update = ""; @@ -61,9 +51,6 @@ class Order_update extends CI_Model { return $update_exc; } - - - public function combineoperation_exist($combineNo='', $operation="") { if( ! $combineNo) { return false; } @@ -76,37 +63,6 @@ class Order_update extends CI_Model { return $query->result(); } - public function get_SN_by_vendorOrderId($vendorOrderId) - { - $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN - FROM BIZ_GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN - WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; - $query = $this->HT->query($sql); - if ($query->row()) { - $this->BIZ_COLI_SN = $query->row()->COLI_SN; - $this->GRI_SN = $query->row()->COLI_GRI_SN; - $this->GCI_SN = $query->row()->GCI_SN; - return $query->row(); - } - return NULL; - } - - public function get_SN_by_groupCode($code) - { - $sql = "SELECT top 1 COLI_SN,GRI_SN - FROM BIZ_ConfirmLineInfo coli - LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '$code%'"; - $query = $this->HT->query($sql); - if ($query->row()) { - $this->BIZ_COLI_SN = $query->row()->COLI_SN; - $this->GRI_SN = $query->row()->GRI_SN; - return $query->row(); - } - return NULL; - } - public function update_confirmLineInfo() { $sql = "UPDATE BIZ_ConfirmLineInfo SET @@ -122,75 +78,6 @@ class Order_update extends CI_Model { return $this->query; } - /* - * 生成订单号 - * 根据系统时间生成,精确到0.0001微秒 - */ - - function MakeOrderNumber() { - return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); - } - - /** - * 生成商务订单号 - */ - function biz_make_order_number() { - /* - $date = date('ymd',time()); - $sql = "SELECT MAX( \n" - . " CONVERT( \n" - . " INT, \n" - . " CASE \n" - . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" - . " ELSE RIGHT(COLI_ID, 3) \n" - . " END \n" - . " ) \n" - . " ) AS SN \n" - . "FROM dbo.BIZ_ConfirmLineInfo \n" - . "WHERE (LEFT(COLI_ID, 6) = ?)"; - $query = $this->HT->query($sql,array($date)); - $id = $query->row()->SN; - if (is_null($id)||empty($id)) - { - $id = 0; - } - $ids = $date.(sprintf('%03d',(int)$id+1)); - return $ids; - */ - //call $conn - include('c:/database_conn.php'); - $connection = array( - 'UID' => $db['HT']['username'], - 'PWD' => $db['HT']['password'], - 'Database' => 'tourmanager', - 'ConnectionPooling' => 1, - 'CharacterSet' => 'utf-8', - 'ReturnDatesAsStrings' => 1 - ); - $conn = sqlsrv_connect($db['HT']['hostname'], $connection); - $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); - if ($stmt === false) { - echo "Error in executing statement 3.\n"; - die(print_r(sqlsrv_errors(), true)); - } else { - //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 - //如果结果集为空就移到下一个 - while (sqlsrv_has_rows($stmt) !== TRUE) { - sqlsrv_next_result($stmt); - } - - $result_object = array(); - while ($row = sqlsrv_fetch_object($stmt)) { - $result_object[] = $row; - } - - sqlsrv_free_stmt($stmt); - sqlsrv_close($conn); - - return($result_object[0]->ccid); - } - } - /** * * 更新订单状态(商务订单) @@ -229,206 +116,6 @@ class Order_update extends CI_Model { return $stmt; } - /** - * - * 插入收款记录 - * - */ - public function insert_acc_info($order_id) { - //获取订单 - $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; - $query = $this->HT->query($sql, array($order_id)); - $order_info = $query->row(); - //插入记录 - $sql = "INSERT INTO BIZ_GroupAccountInfo \n" - . " ( \n" - . " GAI_COLI_SN, \n" - . " GAI_COLI_ID, \n" - . " GAI_Type, \n" - . " GAI_SQJE, \n" - . " GAI_SQDate, \n" - . " GAI_SSJE, \n" - . " GAI_SQJECurrency, \n" - . " GAI_SSDate, \n" - . " GAI_CusName, \n" - . " GAI_CusEmail, \n" - . " GAI_Memo \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ? \n" - . " )"; - $query = $this->HT->query($sql, array($order_info->COLI_SN, - $order_info->COLI_ID, - $order_info->COLI_PayManner, - $order_info->COLI_Price, - date('Y-m-d H:i:s'), - $order_info->COLI_Price, - $this->config->item('Site_Currency'), - date('Y-m-d H:i:s'), - "", "", " ")); - } - - function GetNationalityID($nationalityName) { - if (!$nationalityName) { - return 0; - } - if (is_numeric($nationalityName)) { - return $nationalityName; - } else { - $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" - . "FROM COuntryInfo2 ci2 \n" - . "WHERE ci2.COI2_Country = ? "; - $query = $this->HT->query($sql, array($nationalityName)); - if ($query->result()) { - $row = $query->row(); - return $row->COI2_COI_SN; - } else { - return 0; - } - } - } - - function GetNationalityName($nationalityID) { - if (!is_numeric($nationalityID)) { - return $nationalityID; - } else { - $sql = "SELECT TOP 1 ci2.COI2_Country \n" - . "FROM COuntryInfo2 ci2 \n" - . "WHERE ci2.COI2_LGC = 2 \n" - . " AND ci2.COI2_COI_SN = ? "; - $query = $this->HT->query($sql, array($nationalityID)); - if ($query->result()) { - $row = $query->row(); - return $row->COI2_Country; - } else { - return $nationalityID; - } - } - } - - /** - * - * 获取商务订单信息 - * @param string $order_id 订单id - * @return mixed 订单信息 - * - */ - public function get_flight_order_by_id($order_id) { - $sql = "SELECT DISTINCT cli.COLI_ID, \n" - . " cli.COLI_Price, \n" - . " bg.GUT_FirstName, \n" - . " bg.GUT_LastName, \n" - . " bg.GUT_Email, \n" - . " bg.GUT_Email2, \n" - . " bpe.BPE_SN, \n" - . " bpe.BPE_GuestType, \n" - . " bpe.BPE_FirstName, \n" - . " bpe.BPE_MiddleName, \n" - . " bpe.BPE_LastName, \n" - . " bpe.BPE_GuestType, \n" - . " bpe.BPE_Passport, \n" - . " cld.COLD_Count, \n" - . " foi.FlightsNo, \n" - . " foi.DepartureDate, \n" - . " foi.DepartureTime, \n" - . " foi.ArrivalTime, \n" - . " cli.COLI_PayManner, \n" - . " cli.COLI_State, \n" - . " cli.COLI_sourcetype, \n" - . " foi.Cabin, \n" - . " foi.DepartAirport, \n" - . " foi.ArrivalAirport, \n" - . " cld.COLD_SN, \n" - . " foi.DepartureCity, \n" - . " foi.ArrivalCity, \n" - . " bg.GUT_TEL, \n" - . " bg.GUT_NationalityID, \n" - . " cli.COLI_OrderDetailText, \n" - . " bpe.BPE_imageSrc, \n" - . " cli.COLI_Cost, \n" - . " cld.COLD_TotalPrice, \n" - . " cld.COLD_TotalCost \n" - . "FROM BIZ_ConfirmLineInfo cli \n" - . " INNER JOIN BIZ_ConfirmLineDetail cld \n" - . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" - . " INNER JOIN BIZ_GUEST bg \n" - . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" - . " INNER JOIN BIZ_BookPeopleList bpl \n" - . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" - . " INNER JOIN BIZ_BookPeople bpe \n" - . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" - . " INNER JOIN BIZ_FlightsOrderInfo foi \n" - . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" - . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; - - $query = $this->HT->query($sql, array($order_id)); - return $query->result(); - } - - /** - * - * 获取机票订单乘员列表 - * @param string $order_id 订单id - * @return mixed 订单信息 - * - */ - public function get_bpe_list_by_id($order_id) { - $sql = "SELECT DISTINCT bpe.BPE_SN, \n" - . " bpe.BPE_FirstName, \n" - . " bpe.BPE_MiddleName, \n" - . " bpe.BPE_LastName, \n" - . " bpe.BPE_Passport \n" - . "FROM BIZ_BookPeople bpe \n" - . " INNER JOIN BIZ_BookPeopleList bpl \n" - . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" - . " INNER JOIN BIZ_ConfirmLineDetail cold \n" - . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" - . " INNER JOIN BIZ_ConfirmLineInfo coli \n" - . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" - . "WHERE coli.COLI_ID = ?"; - $query = $this->HT->query($sql, array($order_id)); - //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); - return $query->result(); - } - - /** - * - * 获取机票电子票号 - * @param array bpe_sn 乘客sn数组 - * @return mixed 机票票号 - * - */ - public function get_ticket_no($bpe_sn) { - if (is_array($bpe_sn)) { - $instr = join(',', $bpe_sn); - } elseif (is_string($bpe_sn)) { - $instr = $bpe_sn; - } else { - $instr = 0; - } - $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" - . " ftn.FTN_TicketNo, \n" - . " ftn.FTN_GuestNo \n" - . "FROM BIZ_FlightsTicketNo ftn \n" - . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; - $query = $this->HT->query($sql); - return $query->result(); - } - - /* - * 发送邮件 - */ function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { $sql = "INSERT INTO Email_AutomaticSend \n" @@ -446,148 +133,4 @@ class Order_update extends CI_Model { return $query; } - - /** - * - * 返回成行订单 - * 条件1:订单类型 - * 天剑2:网站来源 - * - */ - public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { - if ($biz) { - $sql = "SELECT TOP 200 c.COLI_WebCode, \n" - . " c.COLI_ID, \n" - . " c.COLI_ConfirmDate, \n" - . " c.COLI_ApplyDate, \n" - . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" - . "FROM BIZ_ConfirmLineInfo c \n" - . "WHERE c.COLI_sourcetype = ? \n" - . " AND c.COLI_WebCode = ? \n" - . "ORDER BY \n" - . " c.COLI_SN DESC"; - $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); - } else { - $sql = "SELECT TOP 200 c.COLI_WebCode, \n" - . " c.COLI_ID, \n" - . " c.COLI_ConfirmDate, \n" - . " c.COLI_ApplyDate, \n" - . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" - . "FROM ConfirmLineInfo c \n" - . "WHERE c.COLI_sourcetype = ? \n" - . " AND c.COLI_WebCode = ? \n" - . "ORDER BY \n" - . " c.COLI_SN DESC"; - $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); - } - $this->sql = $this->HT->queries; - return $query->result(); - } - - //传统订单支付之后,插入新的订单信息 - public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { - //获取订单 - $order_info_sql = " - SELECT confirmlineinfotmp.COLI_OrderPrice, - memberinfotmp.MEI_FirstName, - memberinfotmp.MEI_LastName, - memberinfotmp.MEI_Mail - FROM memberinfotmp - INNER JOIN customerlisttmp - ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn - INNER JOIN confirmlineinfotmp - ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn - WHERE (customerlisttmp.cul_coli_sn = ? )"; - $query = $this->HT->query($order_info_sql, array($coli_sn)); - $order_info = $query->row(); - - //插入记录 - $sql = "INSERT INTO GroupAccountInfoTmp - ( - GAI_COLI_SN, - GAI_SQJE, - GAI_SQDate, - GAI_CusName, - GAI_CusEmail, - GAI_SQJECurrency, - GAI_Type, - LastEditTime, - GAI_GRI_SN, - GAI_State, - DeleteFlag - ) - VALUES (?,?,?,?,?,?,?,?,?,?,?)"; - - $query = $this->HT->query($sql, array($coli_sn, - $order_info->COLI_OrderPrice, - date('Y-m-d H:i:s'), - $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, - $order_info->MEI_Mail, - $this->config->item('Site_Currency'), - $pay_manner, - date('Y-m-d H:i:s'), - $gri_sn, - $state, - $deleteflag - ) - ); - } - - //来源终端 tablet mobile desktop - public function check_device() { - if (isset($_SERVER['HTTP_USER_AGENT'])) { - $ua = $_SERVER['HTTP_USER_AGENT']; - } else { - $ua = ''; - } - ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com - ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. - ## Price will be $2 - $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) - $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent - $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) - - if (!function_exists('androidTablet')) { - - function androidTablet($ua) { //Find out if it is a tablet - if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent - if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) - return true; - } - } - } - - } - $androidTablet = androidTablet($ua); //Do androidTablet function - $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent - - if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) - return 'tablet'; - } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet - return 'mobile'; - } else { //If it's not a mobile device - return 'desktop'; - } - } - - public function ip_limit($ip = "0.0.0.0") - { - if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { - return TRUE; - } - $sql = "SELECT COUNT(1) cnt - FROM ConfirmLineInfoTmp - WHERE 1=1 - AND COLI_SenderIP = ? - AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; - $query = $this->HT->query($sql, array($ip)); - $ret = $query->row(); - if ($ret->cnt > 50) { - return FALSE; - } else { - return TRUE; - } - } - - } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e5e9e577..ed30abad 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -141,6 +141,62 @@ class Orders_model extends CI_Model { return $query->result(); } + public $VAS_GRI_SN; + public $VAS_VEI_SN; + public $VAS_IsSendSucceed; + public $VAS_IsConfirm; + public $VAS_SendTime; + public $VAS_ConfirmTime; + public $VAS_IsCancel; + public $VAS_LMI_SN; + public $VAS_FaxNo; + public $VAS_VendorEmail; + public function vendorarrangestate_save() + { + $sql = "INSERT INTO VendorArrangeState + (VAS_GRI_SN + ,VAS_VEI_SN + ,VAS_IsSendSucceed + ,VAS_IsConfirm + ,VAS_SendTime + ,VAS_ConfirmTime + ,VAS_IsCancel + ,VAS_LMI_SN + ,VAS_FaxNo + ,VAS_VendorEmail + ,Creator + ,LastEditTime + ,DeleteFlag + ) VALUES + (? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,? + ,0 + ,GETDATE() + ,0 + )"; + $query = $this->HT->query($sql, array( + $this->VAS_GRI_SN + ,$this->VAS_VEI_SN + ,$this->VAS_IsSendSucceed + ,$this->VAS_IsConfirm + ,$this->VAS_SendTime + ,$this->VAS_ConfirmTime + ,$this->VAS_IsCancel + ,$this->VAS_LMI_SN + ,$this->VAS_FaxNo + ,$this->VAS_VendorEmail + )); + return $query; + } + public $GRI_SN=0; // 团号 public $GRI_No; // 团号 public $GRI_OrderType; // 订单类型 From 5ae2ca53c8275522a1cda8cc45d16aa28460917d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Apr 2018 13:54:36 +0800 Subject: [PATCH 051/382] =?UTF-8?q?trippest=20=E5=A2=9E=E5=8A=A0=E5=8C=97?= =?UTF-8?q?=E4=BA=AC=E4=B8=A4/=E4=B8=89=E6=97=A5=E6=B8=B8,=E8=A5=BF?= =?UTF-8?q?=E5=AE=89=E4=B8=A4=E6=97=A5=E6=B8=B8=E7=9A=84=E7=89=B9=E6=AE=8A?= =?UTF-8?q?=E5=A4=84=E7=90=86;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index c2eae1c7..5ada8b9e 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -8,29 +8,28 @@ class TulanduoApi extends CI_Controller public $special_route = array( "BJSIC-42" => "'BJSIC-41','BJSIC-42'" ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" + ,"XASIC-42" => "'XASIC-41','XASIC-42'" ); public $special_route_name = array( - "BJSIC-42" => "北京精品两日游(目的地)" - ,"BJSIC-43" => "北京精品三日游(目的地)" + "BJSIC-42" => "北京精品两日游(目的地BJSIC-42)" + ,"BJSIC-43" => "北京精品三日游(目的地BJSIC-43)" + ,"XASIC-42" => "西安精品两日游(目的地XASIC-42)" ); public $city_info = array( "北京分公司" => array( - "PlanVEI_SN" => 1343, - "COLI_sourcetype" => 32090, - "routeType" => "北京目的地线路", - "GRI_after" => "BJ" + "PlanVEI_SN" => 1343 + ,"COLI_sourcetype" => 32090 + ,"routeType" => "北京目的地线路" ), "西安分公司" => array( - "PlanVEI_SN" => 30548, - "COLI_sourcetype" => 32116, - "routeType" => "西安目的地线路", - "GRI_after" => "XA" + "PlanVEI_SN" => 30548 + ,"COLI_sourcetype" => 32116 + ,"routeType" => "西安目的地线路" ), "上海分公司" => array( - "PlanVEI_SN" => 29188, - "COLI_sourcetype" => 32112, - "routeType" => "上海目的地线路", - "GRI_after" => "SH" + "PlanVEI_SN" => 29188 + ,"COLI_sourcetype" => 32112 + ,"routeType" => "上海目的地线路" ) ); @@ -45,7 +44,7 @@ class TulanduoApi extends CI_Controller // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; // 发送到图兰朵系统接口的参数jsonParams - public $params; + // public $params; public function __construct(){ parent::__construct(); @@ -55,7 +54,7 @@ class TulanduoApi extends CI_Controller // $this->output->enable_profiler(TRUE); - $this->params = new stdClass(); + // $this->params = new stdClass(); /** test */ // $this->userId = "358"; // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -127,6 +126,7 @@ class TulanduoApi extends CI_Controller $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; } + $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); $COLD_MemoText = json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); From c3d1d34e3c3f955933fd2364c8b6e189256baf9e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Apr 2018 16:31:12 +0800 Subject: [PATCH 052/382] =?UTF-8?q?trippest=20=E4=BF=AE=E5=A4=8D=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E4=B8=8E=E8=AE=A2=E5=8D=95=E6=9C=AA=E5=85=B3=E8=81=94?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 15 ++++++++------- ...LanDuo_addOrUpdateRouteOrderContentBuilder.php | 2 +- .../models/TuLanDuo_queryContentBuilder.php | 2 +- .../trippestOrderSync/models/orders_model.php | 2 +- 4 files changed, 11 insertions(+), 10 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 5ada8b9e..9a1c6b59 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -109,18 +109,19 @@ class TulanduoApi extends CI_Controller $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); } $cnt = 0; + $pag_no_tmp = $this->pag_no_tmp(); foreach ($all_list as $k => $vo) { $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 $PAG_Code = $pag_sub = null; preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); - if (empty($temp_array) && isset($this->pag_no_tmp()[$vo['routeName']])) { + if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { // 旧的数据没有线路代号 - $PAG_Code = $this->pag_no_tmp()[$vo['routeName']]; + log_message('error','未识别的线路名称 ' . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); + $PAG_Code = $pag_no_tmp[$vo['routeName']]; $split_code = explode("-", $PAG_Code); $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; } else { - log_message('error','未识别的线路名称 ' . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); $PAG_Code = $pag_sub = null; $split_code = explode("-", $temp_array[0]); $PAG_Code = $split_code[0] . "-" . $split_code[1]; @@ -290,7 +291,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /*BIZ_GroupCombineOperationDetail*/ // 门票 if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations) && - empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "sceneryOperations")) ) { + ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "sceneryOperations")) === array() ) { foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; $this->Orders_model->GCOD_operationType = "sceneryOperations"; @@ -312,7 +313,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); // 用房 ... // 用餐 if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) && - empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "restraurantOperations"))) { + ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "restraurantOperations")) === array() ) { foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; $this->Orders_model->GCOD_operationType = "restraurantOperations"; @@ -333,7 +334,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } // 用车 if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) && - empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "touristCarOperations"))) { + ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "touristCarOperations")) === array() ) { foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; $this->Orders_model->GCOD_operationType = "touristCarOperations"; @@ -354,7 +355,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } // 导游服务 if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) && - empty($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "guiderOperations"))) { + ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "guiderOperations")) === array() ) { foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; $this->Orders_model->GCOD_operationType = "guiderOperations"; diff --git a/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php b/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php index f95cfd38..66f28198 100644 --- a/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php +++ b/webht/third_party/trippestOrderSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php @@ -84,7 +84,7 @@ class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model { if(!empty($this->orderData)){ $this->bizContentarr['orderData'] = $this->orderData; - $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + $this->bizContent = json_encode($this->bizContentarr); } return $this->bizContent; } diff --git a/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php index 7ffc4956..153a3e9b 100644 --- a/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php +++ b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php @@ -34,7 +34,7 @@ class TuLanDuo_queryContentBuilder extends CI_Model public function getBizContent() { if(!empty($this->bizContentarr)){ - $this->bizContent = json_encode($this->bizContentarr,JSON_UNESCAPED_UNICODE); + $this->bizContent = json_encode($this->bizContentarr); } return $this->bizContent; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index ed30abad..482062aa 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1025,7 +1025,7 @@ class Orders_model extends CI_Model { . " ?, \n" . " ? \n" . ")"; - // $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); + $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); } /* From 0c820a56549de4b9e906fa7a6082acdf50ce3eb9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Apr 2018 17:13:39 +0800 Subject: [PATCH 053/382] =?UTF-8?q?trippest=20=E4=BF=AE=E6=AD=A3=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=AE=A2=E4=BA=BA=E9=97=AE=E9=A2=98;=20=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=8C=85=E4=BB=B7=E4=BF=A1=E6=81=AF=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=BD=95=E5=85=A5=E9=97=AE=E9=A2=98;=20todo:=20=E6=9B=B4?= =?UTF-8?q?=E6=96=B0=E8=B0=83=E5=BA=A6=E4=BF=A1=E6=81=AF;=E7=94=9F?= =?UTF-8?q?=E6=88=90=E5=9B=A2=E5=90=8D=E6=93=8D=E4=BD=9C;=E7=94=9F?= =?UTF-8?q?=E6=88=90=E9=A2=84=E5=AE=9A=E4=BC=A0=E7=9C=9F=E6=93=8D=E4=BD=9C?= =?UTF-8?q?...:?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 16 ++++++++------- .../trippestOrderSync/models/order_update.php | 2 +- .../trippestOrderSync/models/orders_model.php | 20 +++++++++++++++++-- 3 files changed, 28 insertions(+), 10 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 9a1c6b59..21204a28 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -271,13 +271,15 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); /** INSERT */ /*BIZ_BookPeople*/ - foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { - $this->Orders_model->BPE_FirstName = $vd->name; - $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; - $this->Orders_model->BPE_Passport = $vd->documentNo; - $bpe_sn[] = $this->Orders_model->biz_book_people_save(); - // BIZ_BookPeopleList - $this->Orders_model->biz_bookpeople_List_save($order->COLD_SN, $this->Orders_model->BPE_SN); + if ($this->Orders_model->bookpeople_exist($order->COLD_SN) === array()) { + foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { + $this->Orders_model->BPE_FirstName = $vd->name; + $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; + $this->Orders_model->BPE_Passport = $vd->documentNo; + $bpe_sn[] = $this->Orders_model->biz_book_people_save(); + // BIZ_BookPeopleList + $this->Orders_model->biz_bookpeople_List_save($order->COLD_SN, $this->Orders_model->BPE_SN); + } } /*BIZ_PackageOrderInfo*/ $this->Orders_model->POI_COLD_SN = $order->COLD_SN; diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index e8e0d7b8..c454a86c 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -53,7 +53,7 @@ class Order_update extends CI_Model { public function combineoperation_exist($combineNo='', $operation="") { - if( ! $combineNo) { return false; } + if( ! $combineNo) { return array(); } $sql = "SELECT TOP 1 GCOD_GCI_combineNo FROM BIZ_GroupCombineOperationDetail WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 482062aa..c412c806 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -283,7 +283,7 @@ class Orders_model extends CI_Model { } public function combineoperation_exist($combineNo='', $operation="") { - if( ! $combineNo) { return false; } + if( ! $combineNo) { return array(); } $sql = "SELECT TOP 1 GCOD_GCI_combineNo FROM BIZ_GroupCombineOperationDetail WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; @@ -765,7 +765,12 @@ class Orders_model extends CI_Model { /** 包价线路订单入库 */ public function biz_packageorder_save() { - $sql = "INSERT INTO BIZ_PackageOrderInfo + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_PackageOrderInfo + WHERE POI_COLD_SN = ? + ) + INSERT INTO BIZ_PackageOrderInfo (POI_COLD_SN ,POI_FlightsNo ,POI_AirPort @@ -794,6 +799,7 @@ class Orders_model extends CI_Model { "; $query = $this->HT->query($sql, array( $this->POI_COLD_SN + ,$this->POI_COLD_SN ,$this->POI_FlightsNo ,$this->POI_AirPort ,$this->POI_Time @@ -948,6 +954,16 @@ class Orders_model extends CI_Model { return $this->FOI_SN; } + public function bookpeople_exist($cold_sn) + { + if( ! $cold_sn) { return array(); } + $sql = "SELECT top 1 * + FROM BIZ_BookPeopleList BPL + WHERE BPL_COLD_SN=? "; + $query = $this->HT->query($sql, array($cold_sn)); + return $query->result(); + } + var $BPE_SN; var $BPE_FirstName; //客人 var $BPE_MiddleName; //客人 From b0bc0bc7a9d38c75b10cb2d6dd7f0bf70fb56ffc Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 10:29:53 +0800 Subject: [PATCH 054/382] =?UTF-8?q?trippest=20=E5=9B=A2=E5=8F=B7=E8=A2=AB?= =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E4=BA=86=E4=B8=AD=E6=96=87=E7=A9=BA=E6=A0=BC?= =?UTF-8?q?=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 21204a28..d5b009fd 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -133,6 +133,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 + mb_regex_encoding("UTF-8"); if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $tmp_groupCode = explode("-", $vo['agcOrderNo']); $real_groupCode = $tmp_groupCode[0] . "-"; From 362c718416f8f378adae37e77f5acc6a9da67c5d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 11:21:33 +0800 Subject: [PATCH 055/382] =?UTF-8?q?trippest=20json=5Fencode=20=E4=B8=AD?= =?UTF-8?q?=E6=96=87=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 5 +++-- .../trippestOrderSync/helpers/array_helper.php | 18 ++++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 1 + 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index d5b009fd..b038519d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -48,9 +48,9 @@ class TulanduoApi extends CI_Controller public function __construct(){ parent::__construct(); + $this->load->helper('array'); $this->load->model('Orders_model'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); - $this->load->helper('array'); // $this->output->enable_profiler(TRUE); @@ -129,7 +129,7 @@ class TulanduoApi extends CI_Controller } $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); - $COLD_MemoText = json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); + $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 @@ -540,4 +540,5 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"上海单租车(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" ); } + } diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 1dd8320d..006ff0bf 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -90,3 +90,21 @@ function my_implode($container,$se,$arr) } return $str; } +/*! + * json_encode($a, JSON_UNESCAPED_UNICODE ) + * for PHP Version < 5.4 + */ +function raw_json_encode($input, $flags = 0) { + $fails = implode('|', array_filter(array( + '\\\\', + $flags & JSON_HEX_TAG ? 'u003[CE]' : '', + $flags & JSON_HEX_AMP ? 'u0026' : '', + $flags & JSON_HEX_APOS ? 'u0027' : '', + $flags & JSON_HEX_QUOT ? 'u0022' : '', + ))); + $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/"; + $callback = function ($m) { + return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8'); + }; + return preg_replace_callback($pattern, $callback, json_encode($input, $flags)); +} diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index c412c806..54f68579 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1672,4 +1672,5 @@ class Orders_model extends CI_Model { } + } From 0fd19df71a469b766181003fefda5fdb691428d2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 13:54:45 +0800 Subject: [PATCH 056/382] =?UTF-8?q?trippest=20=E7=94=9F=E6=88=90=E9=A2=84?= =?UTF-8?q?=E5=AE=9A=E4=BC=A0=E7=9C=9F=E6=93=8D=E4=BD=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 23 ++---- .../trippestOrderSync/models/orders_model.php | 73 ++++--------------- 2 files changed, 20 insertions(+), 76 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index b038519d..8652f49e 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -73,8 +73,8 @@ class TulanduoApi extends CI_Controller ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) - ->setStartTravelDate("2018-04-19") // test - ->setEndTravelDate("2018-04-19") + ->setStartTravelDate("2018-04-20") // test + ->setEndTravelDate("2018-04-20") // ->setStartOrderDate("2018-04-13") // ->setEndOrderDate("2018-04-13") ; @@ -189,26 +189,17 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; $this->Orders_model->COLD_MemoText = $COLD_MemoText; $this->Orders_model->biz_confirm_detail_save(); - /** VendorArrangeState */ - $vendor_contact = $this->Orders_model->get_vendorContact($this->Orders_model->COLD_PlanVEI_SN); - $this->Orders_model->VAS_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; - $this->Orders_model->VAS_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; - $this->Orders_model->VAS_IsSendSucceed = 1; - $this->Orders_model->VAS_IsConfirm = $vo['orderStatus']; - $this->Orders_model->VAS_IsCancel = 0; - $this->Orders_model->VAS_SendTime = $vo['orderDate']; - $this->Orders_model->VAS_ConfirmTime = $vo['orderStatus'] == 1 ? $vo['orderDate'] : null; - $this->Orders_model->VAS_LMI_SN = !empty($vendor_contact) ? $vendor_contact->LMI_SN : null; - $this->Orders_model->VAS_FaxNo = !empty($vendor_contact) ? $vendor_contact->LMI_AutoFax : null; - $this->Orders_model->VAS_VendorEmail = !empty($vendor_contact) ? $vendor_contact->LMI_ListMail : null; - $this->Orders_model->vendorarrangestate_save(); + /** SP_BIZ_Arrange */ + if ($this->Orders_model->GRI_SN) { + $this->Orders_model->sp_biz_arrange(); + } $cnt++; } if ($this->Orders_model->GCI_SN === null) { /*biz_groupcombineinfo*/ $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; - $this->Orders_model->GCI_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->GCI_GRI_SN = $this->Orders_model->GRI_SN; $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; $this->Orders_model->GCI_FromAgc = $vo['agcName']; $this->Orders_model->GCI_groupType = $vo['orderType']; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 54f68579..6c8772f3 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -128,11 +128,11 @@ class Orders_model extends CI_Model { { $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* FROM BIZ_GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN WHERE 1=1 "; if ($coli_sn !== 0) { - $sql .= " and gci.GCI_COLI_SN='$coli_sn' "; + $sql .= " and coli.COLI_SN='$coli_sn' "; } if ($startDate !== NULL) { // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test @@ -141,60 +141,14 @@ class Orders_model extends CI_Model { return $query->result(); } - public $VAS_GRI_SN; - public $VAS_VEI_SN; - public $VAS_IsSendSucceed; - public $VAS_IsConfirm; - public $VAS_SendTime; - public $VAS_ConfirmTime; - public $VAS_IsCancel; - public $VAS_LMI_SN; - public $VAS_FaxNo; - public $VAS_VendorEmail; - public function vendorarrangestate_save() + /*! + * 生成预定传真 + */ + public function sp_biz_arrange() { - $sql = "INSERT INTO VendorArrangeState - (VAS_GRI_SN - ,VAS_VEI_SN - ,VAS_IsSendSucceed - ,VAS_IsConfirm - ,VAS_SendTime - ,VAS_ConfirmTime - ,VAS_IsCancel - ,VAS_LMI_SN - ,VAS_FaxNo - ,VAS_VendorEmail - ,Creator - ,LastEditTime - ,DeleteFlag - ) VALUES - (? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,? - ,0 - ,GETDATE() - ,0 - )"; - $query = $this->HT->query($sql, array( - $this->VAS_GRI_SN - ,$this->VAS_VEI_SN - ,$this->VAS_IsSendSucceed - ,$this->VAS_IsConfirm - ,$this->VAS_SendTime - ,$this->VAS_ConfirmTime - ,$this->VAS_IsCancel - ,$this->VAS_LMI_SN - ,$this->VAS_FaxNo - ,$this->VAS_VendorEmail - )); - return $query; + $sql = "SP_BIZ_Arrange ?"; + $query = $this->HT->query($sql, array($this->GRI_SN)); + return $query->result(); } public $GRI_SN=0; // 团号 @@ -232,7 +186,7 @@ class Orders_model extends CI_Model { public $GCI_SN; public $GCI_combineNo=''; // 拼团团号 - public $GCI_COLI_SN; // 订单key + public $GCI_GRI_SN; // 团key public $GCI_VendorOrderId; // 地接社系统订单id public $GCI_FromAgc; // 组团社来源 public $GCI_groupType; // 组团社来源 @@ -249,7 +203,7 @@ class Orders_model extends CI_Model { ) INSERT INTO BIZ_GroupCombineInfo (GCI_combineNo - ,GCI_COLI_SN + ,GCI_GRI_SN ,GCI_VendorOrderId ,GCI_FromAgc ,GCI_groupType @@ -268,9 +222,8 @@ class Orders_model extends CI_Model { "; $query = $this->HT->query($sql, array( $this->GCI_VendorOrderId - // ,$this->GCI_COLI_SN ,$this->GCI_combineNo - ,$this->GCI_COLI_SN + ,$this->GCI_GRI_SN ,$this->GCI_VendorOrderId ,$this->GCI_FromAgc ,$this->GCI_groupType @@ -438,7 +391,7 @@ class Orders_model extends CI_Model { { $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN FROM BIZ_GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_SN=gci.GCI_COLI_SN + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; $query = $this->HT->query($sql); if ($query->row()) { From 5561afaa2815355fdd8b8214565cc1a9c2d743a9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 14:37:56 +0800 Subject: [PATCH 057/382] =?UTF-8?q?trippest=20=E4=BF=AE=E6=94=B9=E6=8B=BC?= =?UTF-8?q?=E5=9B=A2=E4=BF=A1=E6=81=AF=E8=A1=A8=E7=9A=84=E5=A4=96=E9=94=AE?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 8 ++++++-- .../third_party/trippestOrderSync/models/orders_model.php | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 8652f49e..da233e28 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -373,7 +373,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); return; } - public function order_push($COLI_ID='170809390') // test + public function order_push($COLI_ID=0) // test { // exit(); /** test */ @@ -444,6 +444,11 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return; } + public function order_change() + { + # code... + } + protected function excute_curl($url, $content_builder) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); @@ -454,7 +459,6 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); "Accept: application/json" )); - // $params_str = ($this->characet(json_encode($this->params), "UTF-8")); $params_str = $content_builder->getBizContent(); $postBody = array('jsonParams' => $params_str, "notHander" => 1); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 6c8772f3..7c76fb90 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -199,7 +199,7 @@ class Orders_model extends CI_Model { $sql = "IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupCombineInfo - WHERE GCI_VendorOrderId = ? + WHERE GCI_VendorOrderId = ? and GCI_GRI_SN=? ) INSERT INTO BIZ_GroupCombineInfo (GCI_combineNo @@ -222,6 +222,7 @@ class Orders_model extends CI_Model { "; $query = $this->HT->query($sql, array( $this->GCI_VendorOrderId + ,$this->GCI_GRI_SN ,$this->GCI_combineNo ,$this->GCI_GRI_SN ,$this->GCI_VendorOrderId From dc949c201e5661dfde2918a0405000fef3285feb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 16:34:16 +0800 Subject: [PATCH 058/382] =?UTF-8?q?trippest=20=E5=9B=A2=E4=BF=A1=E6=81=AF,?= =?UTF-8?q?=20=E5=9B=A2=E5=90=8D=E5=A2=9E=E5=8A=A0=E7=BB=84=E5=9B=A2?= =?UTF-8?q?=E7=A4=BE=E5=90=8D=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 27 ++++++++++--------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index da233e28..46d63c22 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -110,6 +110,7 @@ class TulanduoApi extends CI_Controller } $cnt = 0; $pag_no_tmp = $this->pag_no_tmp(); + mb_regex_encoding("UTF-8"); foreach ($all_list as $k => $vo) { $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 $PAG_Code = $pag_sub = null; @@ -133,7 +134,6 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 - mb_regex_encoding("UTF-8"); if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $tmp_groupCode = explode("-", $vo['agcOrderNo']); $real_groupCode = $tmp_groupCode[0] . "-"; @@ -153,7 +153,7 @@ class TulanduoApi extends CI_Controller $date_diff = $travelDate->diff($leaveDate); $this->Orders_model->GRI_No = $vo['agcOrderNo']; $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = ""; + $this->Orders_model->GRI_Name = $vo["agcName"] . $vo['agcOrderNo']; $this->Orders_model->GRI_PersonNum = $vo['adultNum']+$vo['childNum']; $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); $this->Orders_model->GRI_IsCancel = 0; @@ -235,21 +235,22 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); return; } - $allDetails_to_HT = "日程: "; - foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { - $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; - } - $allDetails_to_HT .= "导游: "; - foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { - $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; - } + // $allDetails_to_HT = ""; + // $allDetails_to_HT .= "日程: "; + // foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { + // $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; + // } + // $allDetails_to_HT .= "导游: "; + // foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { + // $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; + // } /** HT 开始 */ /** UPDATE */ /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; $coli_update_column = array( - "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark - ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT + "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n" + // ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT . "\r\n" ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update @@ -376,7 +377,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); public function order_push($COLI_ID=0) // test { // exit(); - /** test */ + /** 目的地 test */ $this->userId = "358"; $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); From 02598df751f1e219e05a0a566ae1559085fc0182 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 25 Apr 2018 17:32:29 +0800 Subject: [PATCH 059/382] =?UTF-8?q?ipaylinks=20=E6=9F=A5=E8=AF=A2=E8=AE=B0?= =?UTF-8?q?=E5=BD=95=E5=92=8C=E5=AF=BC=E5=87=BA=E6=8C=89=E9=92=AE=E5=86=B2?= =?UTF-8?q?=E7=AA=81=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/iPayLinks_list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index ce91c9c7..17123daa 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -52,7 +52,7 @@ <div class="export_form_area "> - <form class="form-inline " method="post" id="search_list" action="/webht.php/apps/pay/ipaylinksservice/export_list/"> + <form class="form-inline " method="post" id="search_list2" action="/webht.php/apps/pay/ipaylinksservice/export_list/"> <div class="form-group "> <label for="from_date" class="">Date From</label> <input type="text" class="form-control" id="from_date" name="from_date" required> From 7b39d44c89d175d738b0d749ae8ce4d04d19d63a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Apr 2018 14:52:24 +0800 Subject: [PATCH 060/382] =?UTF-8?q?trippest=20=E5=9C=B0=E6=8E=A5=E8=AE=A1?= =?UTF-8?q?=E5=88=92=20-=20=E7=8A=B6=E6=80=81=E5=8F=98=E6=9B=B4=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5=20todo=20=E9=AA=8C=E8=AF=81=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E8=B4=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 61 +++++++++++++--- .../trippestOrderSync/models/order_update.php | 73 ++++++------------- .../trippestOrderSync/models/orders_model.php | 33 +++++++++ 3 files changed, 105 insertions(+), 62 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 46d63c22..57b76c9d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -135,10 +135,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { - $tmp_groupCode = explode("-", $vo['agcOrderNo']); - $real_groupCode = $tmp_groupCode[0] . "-"; - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; - $real_groupCode = mb_ereg_replace('(\s| )', '', $real_groupCode); + $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode); } @@ -189,10 +186,12 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; $this->Orders_model->COLD_MemoText = $COLD_MemoText; $this->Orders_model->biz_confirm_detail_save(); - /** SP_BIZ_Arrange */ - if ($this->Orders_model->GRI_SN) { - $this->Orders_model->sp_biz_arrange(); - } + /** SP_BIZ_Arrange + * 这里是其他社的订单, 不写这个操作 + */ + // if ($this->Orders_model->GRI_SN) { + // $this->Orders_model->sp_biz_arrange(); + // } $cnt++; } @@ -441,13 +440,56 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; $this->Orders_model->biz_groupcombineinfo_save(); } + // email 供应商 todo echo "Order Push done."; return; } + /*! + * 订单状态变更,调度变更 + * (地接社调用, 并邮件通知外联) + */ public function order_change() { - # code... + $this->load->model('Order_update'); + $ret['status'] = -1; + $ret['errMsg'] = "未知错误"; + $input = $this->input->post(); + // todo 验证userID + $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId']); + if (empty($vas_info) && ! empty($input['agcOrderNo'])) { + $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode); + } + if (empty($vas_info)) { + $ret['errMsg'] = "未找到订单."; + } else { + $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $input['orderRemark']); + $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; + $coli_update_column = array( + "COLI_State" => 7 + ); + $update_coli = $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + if ($update_vas === TRUE) { + $ret['status'] = 1; + $ret['errMsg'] = ""; + } + } + if ($ret['status'] !== 1) { + log_message('error','图兰朵确认上报失败. POST RAW: ' . json_encode($input) . "; Result: " . json_encode($ret)); + } + // todo email 外联 + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + + public function analysis_groupCode($groupCode) + { + mb_regex_encoding("UTF-8"); + $tmp_groupCode = explode("-", $groupCode); + $real_groupCode = $tmp_groupCode[0] . "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $real_groupCode = mb_ereg_replace('(\s| )', '', $real_groupCode); + return $real_groupCode; } protected function excute_curl($url, $content_builder) { @@ -483,7 +525,6 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $reponse; } - /*! * 转换字符集编码 * @param $data diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index c454a86c..29b1b7f9 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -40,7 +40,12 @@ class Order_update extends CI_Model { return $update_exc; } - public $gci_where_update = ""; + /*! + * 更新拼团信息 + * @date 2018-04-26 + * @param array $column_data 需要更新的列数据数组 + */ + public $gci_where_update = ""; // where 条件 public function biz_groupcombineinfo_update($column_data) { if ($this->gci_where_update == "" || empty($column_data)) { @@ -51,6 +56,11 @@ class Order_update extends CI_Model { return $update_exc; } + /*! + * 拼团的调度信息是否已存在 + * @param string $combineNo 拼团团号 + * @param string $operation 调度类型 + */ public function combineoperation_exist($combineNo='', $operation="") { if( ! $combineNo) { return array(); } @@ -63,60 +73,19 @@ class Order_update extends CI_Model { return $query->result(); } - public function update_confirmLineInfo() - { - $sql = "UPDATE BIZ_ConfirmLineInfo SET - COLI_GRI_SN=?, - COLI_GroupCode=? - WHERE COLI_SN=? - "; - $query = $this->HT->query($sql, array( - $this->BIZ_COLI_GRI_SN - ,$this->BIZ_COLI_GroupCode - ,$this->BIZ_COLI_SN - )); - return $this->query; - } - - /** - * - * 更新订单状态(商务订单) - * + /*! + * 地接计划状态变更 + * @param [type] $vas_sn [description] + * @param string $confirminfo [description] */ - public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { - //更新订单 - $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; - $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); - $this->insert_acc_info($order_id); - return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); - } - - /** - * - * 更新火车订单购票截图 - * - */ - public function update_train_order_pic($order_pic_id) { - //更新订单 - $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; - //$query = $this->HT->query($sql); - - include('c:/database_conn.php'); - $connection = array( - 'UID' => $db['HT']['username'], - 'PWD' => $db['HT']['password'], - 'Database' => 'tourmanager', - 'ConnectionPooling' => 1, - 'CharacterSet' => 'utf-8', - 'ReturnDatesAsStrings' => 1 - ); - $conn = sqlsrv_connect($db['HT']['hostname'], $connection); - $stmt = sqlsrv_query($conn, $sql); - - return $stmt; + public function vendorStatus_update($vas_sn, $confirminfo="") + { + $sql = "UPDATE VendorArrangeState set VAS_IsConfirm=1,VAS_ConfirmInfo=?+CHAR(10)+VAS_ConfirmInfo + WHERE VAS_SN=?"; + $query = $this->HT->query($sql, array($confirminfo, $vas_sn)); + return $query; } - function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { $sql = "INSERT INTO Email_AutomaticSend \n" . " ( \n" diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 7c76fb90..67a7672a 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -141,6 +141,39 @@ class Orders_model extends CI_Model { return $query->result(); } + /*! + * 获取团计划信息的记录 - 根据地接社订单id + * 计划变更和订单状态确认时使用 + * @param integer $vendorOrderId 图兰朵地接社系统的订单id + */ + public function get_vendorarrangestate_byVendor($vendorOrderId) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM BIZ_GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON gci.GCI_GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + WHERE gci.GCI_VendorOrderId=?"; + $query = $this->HT->query($sql, array($vendorOrderId)); + return $query->result(); + } + /*! + * 获取团计划信息的记录 - 根据组团社团号 + * 计划变更和订单状态确认时使用 + * @param integer $groupCode 图兰朵地接社系统的订单id + */ + public function get_vendorarrangestate_byGroup($groupCode) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM GRoupInfo gri + INNER JOIN BIZ_ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + WHERE gri.GRI_No LIKE '$groupCode%'"; + $query = $this->HT->query($sql); + return $query->result(); + } + /*! * 生成预定传真 */ From 098b97d4924eb7d8b3657f062685b91fb8f48c25 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Apr 2018 14:50:58 +0800 Subject: [PATCH 061/382] =?UTF-8?q?trippest=20=E5=9C=B0=E6=8E=A5=E8=AE=A1?= =?UTF-8?q?=E5=88=92=20-=20=E7=8A=B6=E6=80=81=E5=8F=98=E6=9B=B4=E4=B8=8A?= =?UTF-8?q?=E6=8A=A5,=20=E6=9B=B4=E6=96=B0=E7=A1=AE=E8=AE=A4=E4=BF=A1?= =?UTF-8?q?=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 13 +++++--- .../trippestOrderSync/models/order_update.php | 33 ++++++++----------- .../trippestOrderSync/models/orders_model.php | 14 ++++---- 3 files changed, 29 insertions(+), 31 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 57b76c9d..d6a77a74 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -456,15 +456,20 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $ret['errMsg'] = "未知错误"; $input = $this->input->post(); // todo 验证userID - $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId']); + // $vendorID = $input['userId']; + $vendorID = 29188;//29188 1343; // test + $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); - $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); } if (empty($vas_info)) { $ret['errMsg'] = "未找到订单."; } else { - $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $input['orderRemark']); + $vendor_manager = $this->Orders_model->get_vendorContact($vendorID); + $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime']; + $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo; + $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo); $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; $coli_update_column = array( "COLI_State" => 7 @@ -476,7 +481,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); } } if ($ret['status'] !== 1) { - log_message('error','图兰朵确认上报失败. POST RAW: ' . json_encode($input) . "; Result: " . json_encode($ret)); + log_message('error','图兰朵确认上报失败. POST RAW: ' . raw_json_encode($input) . "; Result: " . raw_json_encode($ret)); } // todo email 外联 return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 29b1b7f9..4e61eda7 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -78,28 +78,21 @@ class Order_update extends CI_Model { * @param [type] $vas_sn [description] * @param string $confirminfo [description] */ - public function vendorStatus_update($vas_sn, $confirminfo="") + public function vendorStatus_update($vas_sn, $lmi_sn, $confirminfo="") { - $sql = "UPDATE VendorArrangeState set VAS_IsConfirm=1,VAS_ConfirmInfo=?+CHAR(10)+VAS_ConfirmInfo + $sql = "UPDATE VendorArrangeState + SET VAS_IsConfirm=1 + ,VAS_ConfirmInfo=? + ,VAS_ConfirmTime=getdate() + ,VAS_ConfirmSN=? WHERE VAS_SN=?"; - $query = $this->HT->query($sql, array($confirminfo, $vas_sn)); - return $query; - } - - function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { - $sql = "INSERT INTO Email_AutomaticSend \n" - . " ( \n" - . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" - . " M_FromName, M_State \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" - . " ) "; - $query = $this->HT->query($sql, - array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) - ); - return $query; + $query = $this->HT->query($sql, array($confirminfo, $lmi_sn, $vas_sn)); + // affected_rows() doesn't work with the 'sqlsrv' driver in CI2 + // The solution: Upgrade to the latest CodeIgniter 3.0.x version + $ssql = "SELECT 1 as 'exist' from VendorArrangeState where VAS_IsConfirm=1 and VAS_SN=? "; + $squery = $this->HT->query($ssql, array($vas_sn)); + $ret = $squery->result(); + return !empty($ret); } } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 67a7672a..5cca3c03 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -146,15 +146,15 @@ class Orders_model extends CI_Model { * 计划变更和订单状态确认时使用 * @param integer $vendorOrderId 图兰朵地接社系统的订单id */ - public function get_vendorarrangestate_byVendor($vendorOrderId) + public function get_vendorarrangestate_byVendor($vendorOrderId, $vei_sn) { $sql = "SELECT coli.COLI_ID, coli.COLI_SN, vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN FROM BIZ_GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON gci.GCI_GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN - WHERE gci.GCI_VendorOrderId=?"; - $query = $this->HT->query($sql, array($vendorOrderId)); + WHERE gci.GCI_VendorOrderId=? and vas.VAS_VEI_SN=? "; + $query = $this->HT->query($sql, array($vendorOrderId, $vei_sn)); return $query->result(); } /*! @@ -162,15 +162,15 @@ class Orders_model extends CI_Model { * 计划变更和订单状态确认时使用 * @param integer $groupCode 图兰朵地接社系统的订单id */ - public function get_vendorarrangestate_byGroup($groupCode) + public function get_vendorarrangestate_byGroup($groupCode, $vei_sn) { $sql = "SELECT coli.COLI_ID, coli.COLI_SN, vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN FROM GRoupInfo gri INNER JOIN BIZ_ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN - WHERE gri.GRI_No LIKE '$groupCode%'"; - $query = $this->HT->query($sql); + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '$groupCode%'"; + $query = $this->HT->query($sql, array($vei_sn)); return $query->result(); } @@ -465,7 +465,7 @@ class Orders_model extends CI_Model { lmi.LMI_Mobile, lmi.LMI_ListMail FROM LinkmanInfo lmi - INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN + INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN AND lmi2.LMI2_LGC=2 WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; $query = $this->HT->query($sql); return $query->row(); From c50f3eb20302ff44d256b845f1ebe7870586ae20 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Apr 2018 16:56:02 +0800 Subject: [PATCH 062/382] =?UTF-8?q?trippest=20=E5=9C=B0=E6=8E=A5=E7=A1=AE?= =?UTF-8?q?=E8=AE=A4=E5=90=8E=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5=E5=A4=96?= =?UTF-8?q?=E8=81=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 18 +++++++-- .../trippestOrderSync/models/orders_model.php | 40 +++++++++++-------- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index d6a77a74..600d616f 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -456,8 +456,8 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $ret['errMsg'] = "未知错误"; $input = $this->input->post(); // todo 验证userID - // $vendorID = $input['userId']; - $vendorID = 29188;//29188 1343; // test + $vendorID = $input['userId']; + // $vendorID = 29188;//29188 1343; // test $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); @@ -483,7 +483,19 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); if ($ret['status'] !== 1) { log_message('error','图兰朵确认上报失败. POST RAW: ' . raw_json_encode($input) . "; Result: " . raw_json_encode($ret)); } - // todo email 外联 + $sender_name = "中华游供应商合作平台"; + $sender_mail = "info@chinahighlights.net"; + $from_name = $vendor_manager->LMI2_Name; + $from_mail = $vendor_manager->LMI_ListMail; + $to_name = $vas_info[0]->OPI_Name; + $to_mail = $vas_info[0]->OPI_Email; + $subject = $input['agcOrderNo'] . "团已确认: " . $vendor_manager->VEI2_CompanyBN; + $mail_body = $vendor_manager->VEI2_CompanyBN . "对团" . $input['agcOrderNo'] . "的计划在" . $input['orderTime'] . "已确认。\r\n"; + $mail_body .= "确认说明:" . $input['orderRemark'] . "\r\n"; + $mail_body .= "确认人:$vendor_manager->LMI2_Name $vendor_manager->LMI_ListMail 固定电话: $vendor_manager->LMI_Telephone 移动电话:$vendor_manager->LMI_Mobile\r\n"; + $mail_body .= "变更内容: " . $vas_info[0]->VAS_ChangeText . "\r\n"; + $this->Orders_model->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name); + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5cca3c03..15ea7c69 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -148,11 +148,12 @@ class Orders_model extends CI_Model { */ public function get_vendorarrangestate_byVendor($vendorOrderId, $vei_sn) { - $sql = "SELECT coli.COLI_ID, coli.COLI_SN, + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN FROM BIZ_GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON gci.GCI_GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID WHERE gci.GCI_VendorOrderId=? and vas.VAS_VEI_SN=? "; $query = $this->HT->query($sql, array($vendorOrderId, $vei_sn)); return $query->result(); @@ -164,11 +165,12 @@ class Orders_model extends CI_Model { */ public function get_vendorarrangestate_byGroup($groupCode, $vei_sn) { - $sql = "SELECT coli.COLI_ID, coli.COLI_SN, + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN FROM GRoupInfo gri INNER JOIN BIZ_ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '$groupCode%'"; $query = $this->HT->query($sql, array($vei_sn)); return $query->result(); @@ -464,8 +466,10 @@ class Orders_model extends CI_Model { lmi.LMI_Telephone, lmi.LMI_Mobile, lmi.LMI_ListMail + ,vei2.VEI2_CompanyBN FROM LinkmanInfo lmi INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN AND lmi2.LMI2_LGC=2 + INNER JOIN VEndorInfo2 vei2 ON vei2.VEI2_VEI_SN=LMI_VEI_SN AND VEI2_LGC=2 WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; $query = $this->HT->query($sql); return $query->row(); @@ -1338,20 +1342,24 @@ class Orders_model extends CI_Model { /* * 发送邮件 */ - - function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { - $sql = "INSERT INTO Email_AutomaticSend \n" - . " ( \n" - . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" - . " M_FromName, M_State \n" - . " ) \n" - . "VALUES \n" - . " ( \n" - . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" - . " ) "; - $query = $this->HT->query($sql, - array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, $this->config->item('Site_Code'), $this->config->item('Site_SenderName')) - ); + public function save_automail($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $frominfo = 'vendorConfirm msg', $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $M_Web = 'vendorConfirm msg') { + $sql = "INSERT INTO + Email_AutomaticSend ( + M_SenderName, + M_SenderEmail, + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, + M_FromName, + M_ServiceSN, + M_State, + M_AddTime + ) VALUES (N?, N?, N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; + $query = $this->HT->query($sql, array($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); return $query; } From 3acce1e1dea24955bbc1eb4c546971e8f5975aa0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sat, 28 Apr 2018 13:41:30 +0800 Subject: [PATCH 063/382] =?UTF-8?q?trippest=20=E5=9B=A2=E6=AC=BE=E5=BD=95?= =?UTF-8?q?=E5=85=A5=E5=9C=B0=E6=8E=A5=E4=BB=A3=E6=94=B6,=E8=B0=83?= =?UTF-8?q?=E5=BA=A6=E4=BF=A1=E6=81=AF=E6=9B=B4=E6=96=B0,=E8=B0=83?= =?UTF-8?q?=E5=BA=A6=E4=BF=A1=E6=81=AF=E6=98=BE=E7=A4=BA=E5=88=B0=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E4=BF=A1=E6=81=AF=E4=B8=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 144 ++++++++++++++---- .../trippestOrderSync/models/order_update.php | 17 --- .../trippestOrderSync/models/orders_model.php | 113 +++++++------- 3 files changed, 165 insertions(+), 109 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 600d616f..96220ea5 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -44,7 +44,6 @@ class TulanduoApi extends CI_Controller // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; // 发送到图兰朵系统接口的参数jsonParams - // public $params; public function __construct(){ parent::__construct(); @@ -54,7 +53,6 @@ class TulanduoApi extends CI_Controller // $this->output->enable_profiler(TRUE); - // $this->params = new stdClass(); /** test */ // $this->userId = "358"; // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -65,6 +63,7 @@ class TulanduoApi extends CI_Controller // 桂林海纳国旅 // $this->userId = "18"; // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + mb_regex_encoding("UTF-8"); } public function get_orderlist() @@ -73,8 +72,8 @@ class TulanduoApi extends CI_Controller ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) - ->setStartTravelDate("2018-04-20") // test - ->setEndTravelDate("2018-04-20") + ->setStartTravelDate("2018-04-21") // test + ->setEndTravelDate("2018-04-21") // ->setStartOrderDate("2018-04-13") // ->setEndOrderDate("2018-04-13") ; @@ -111,7 +110,12 @@ class TulanduoApi extends CI_Controller $cnt = 0; $pag_no_tmp = $this->pag_no_tmp(); mb_regex_encoding("UTF-8"); + $unique_order = array(); foreach ($all_list as $k => $vo) { + if (in_array($vo['orderId'], $unique_order)) { + continue; + } + $unique_order[] = $vo['orderId']; $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 $PAG_Code = $pag_sub = null; preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); @@ -181,7 +185,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->COLD_EndDate = $vo['leaveDate']; $this->Orders_model->COLD_PersonNum = $vo['adultNum']; $this->Orders_model->COLD_ChildNum = $vo['childNum']; - $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认(已收款) // 4 下计划未确认(已收款) + $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认 // 4 下计划未确认 $this->Orders_model->DeleteFlag = 0; $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; $this->Orders_model->COLD_MemoText = $COLD_MemoText; @@ -213,18 +217,25 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); return; } - public function update_HT_order_operation($coli_sn=null) + public function insert_HT_order_operation($coli_sn=null) { $this->load->model('Order_update'); if ($coli_sn !== null) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); } else { - $startDate = date('Y-m-d'); - $endDate = date('Y-m-d', strtotime("+1 days")); // test + $startDate = ('2018-04-21'); + $endDate = ('2018-04-22'); // test + // $startDate = date('Y-m-d'); // $endDate = date('Y-m-d', strtotime("+4 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); } + $unique_orderGroupCombine = array(); + $unique_order = array(); foreach ($to_update_list as $key => $order) { + if (in_array($order->GCI_VendorOrderId, $unique_order)) { + continue; + } + $unique_order[] = $order->GCI_VendorOrderId; $this->tld_order->setOrderId($order->GCI_VendorOrderId) ->setUserId($this->userId) ->setKey($this->key); @@ -234,22 +245,33 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); return; } - // $allDetails_to_HT = ""; - // $allDetails_to_HT .= "日程: "; - // foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { - // $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; - // } - // $allDetails_to_HT .= "导游: "; - // foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { - // $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; - // } + $allDetails_to_HT = ""; + $allDetails_to_HT .= "\r\n日程: "; + foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { + $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; + } + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { + $allDetails_to_HT .= "\r\n导游: "; + foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { + $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; + } + } + if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) ) { + $allDetails_to_HT .= "\r\n用车: "; + foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vtc) { + $allDetails_to_HT .= $vtc->name .": " . $vtc->driver." (". $vtc->driverTel . ") "; + $allDetails_to_HT .= "[". $vtc->remark . "]; "; + } + } /** HT 开始 */ /** UPDATE */ /** BIZ_ConfirmLineInfo */ - $this->Order_update->coli_where_update = " COLI_SN=" . $order->GCI_COLI_SN; + $this->Order_update->coli_where_update = " COLI_SN=" . $order->COLI_SN; + $old_memo = mb_strstr($order->COLI_Memo, "orderRemark", true) ? mb_strstr($order->COLI_Memo, "orderRemark", true) : $order->COLI_Memo; + $old_detail = mb_strstr($order->COLI_OrderDetailText, "operations", true) ? mb_strstr($order->COLI_OrderDetailText, "operations", true) : $order->COLI_OrderDetailText; $coli_update_column = array( - "COLI_Memo" => $order->COLI_Memo . "\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n" - // ,"COLI_OrderDetailText" => $order->COLI_OrderDetailText . "\r\n" . $allDetails_to_HT . "\r\n" + "COLI_Memo" => $old_memo . "orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n" + ,"COLI_OrderDetailText" => $old_detail . "operations\r\n" . $allDetails_to_HT . "\r\n" ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update @@ -282,12 +304,73 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->POI_EndTime = $detail_jsonResp->orderDetail->leaveDate; $this->Orders_model->POI_QuotationType = 1; // 1 报价 2 网络支付价 3 促销价 $this->Orders_model->biz_packageorder_save(); + /** BIZ_GroupAccountInfo */ + // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 + $paytype = 15006; // 地接代收 + $pay_currency = 'RMB'; + // 删除旧的录入 + $this->Orders_model->biz_groupaccountinfo_cut($order->COLI_SN, $paytype); + if (isset($detail_jsonResp->orderDetail->travelFees) && $order->GCI_FromAgc != "D目的地桂林组") { + foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { + if ($vtf->reviewStatus == 0) { // 未审核的 + continue; + } + $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; + $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; + $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Type = $paytype; + $this->Orders_model->GAI_SQJE = $vtf->sumMoney; + $this->Orders_model->GAI_SQJECurrency = $pay_currency; + $this->Orders_model->GAI_Memo = $vtf->type . ", " . $vtf->remark; + $this->Orders_model->biz_groupaccountinfo_save(); + } + } + // 代收 + if (isset($detail_jsonResp->orderDetail->replaceCollections)) { + foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { + if ($vrc->reviewStatus == 0) { + continue; + } + $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; + $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; + $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Type = $paytype; + $this->Orders_model->GAI_SQJE = $vrc->money; + $this->Orders_model->GAI_SQJECurrency = $pay_currency; + $this->Orders_model->GAI_Memo = $vrc->type . ", " . $vrc->remark; + $this->Orders_model->biz_groupaccountinfo_save(); + } + } + // 代付 + if (isset($detail_jsonResp->orderDetail->replacePays)) { + foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { + if ($vrp->reviewStatus == 0) { + continue; + } + $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; + $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; + $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Type = $paytype; + $this->Orders_model->GAI_SQJE = "-" . $vrp->money; + $this->Orders_model->GAI_SQJECurrency = $pay_currency; + $this->Orders_model->GAI_Memo = $vrp->type . ", " . $vrp->remark; + $this->Orders_model->biz_groupaccountinfo_save(); + } + } /*BIZ_GroupCombineOperationDetail*/ + if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { + continue; + } + if (in_array($detail_jsonResp->orderDetail->groupOrderNo, $unique_orderGroupCombine)) { + continue; + } + $unique_orderGroupCombine[] = $detail_jsonResp->orderDetail->groupOrderNo; + // 删除旧的录入 + $this->Orders_model->biz_groupcombineoperationdetail_cut($detail_jsonResp->orderDetail->groupOrderNo); // 门票 - if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations) && - ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "sceneryOperations")) === array() ) { + if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { - $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; $this->Orders_model->GCOD_operationType = "sceneryOperations"; $this->Orders_model->GCOD_subType = $vso->type; $this->Orders_model->GCOD_title = $vso->name; @@ -306,10 +389,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } // 用房 ... // 用餐 - if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) && - ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "restraurantOperations")) === array() ) { + if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { - $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; $this->Orders_model->GCOD_operationType = "restraurantOperations"; $this->Orders_model->GCOD_subType = $vro->type; $this->Orders_model->GCOD_title = $vro->name; @@ -327,10 +409,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } } // 用车 - if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) && - ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "touristCarOperations")) === array() ) { + if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { - $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; $this->Orders_model->GCOD_operationType = "touristCarOperations"; $this->Orders_model->GCOD_subType = $vco->type; $this->Orders_model->GCOD_title = $vco->name; @@ -348,10 +429,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } } // 导游服务 - if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) && - ($this->Orders_model->combineoperation_exist($detail_jsonResp->orderDetail->groupOrderNo, "guiderOperations")) === array() ) { + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { - $this->Orders_model->GCOD_GCI_combineNo = isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : ""; + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; $this->Orders_model->GCOD_operationType = "guiderOperations"; $this->Orders_model->GCOD_subType = ""; $this->Orders_model->GCOD_title = ""; diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 4e61eda7..8c4a307a 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -56,23 +56,6 @@ class Order_update extends CI_Model { return $update_exc; } - /*! - * 拼团的调度信息是否已存在 - * @param string $combineNo 拼团团号 - * @param string $operation 调度类型 - */ - public function combineoperation_exist($combineNo='', $operation="") - { - if( ! $combineNo) { return array(); } - $sql = "SELECT TOP 1 GCOD_GCI_combineNo - FROM BIZ_GroupCombineOperationDetail - WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; - $query = $this->HT->query($sql, array( - $combineNo,$operation - )); - return $query->result(); - } - /*! * 地接计划状态变更 * @param [type] $vas_sn [description] diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 15ea7c69..f3427470 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -126,7 +126,7 @@ class Orders_model extends CI_Model { */ public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 1000 coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* + $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* FROM BIZ_GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN @@ -135,7 +135,7 @@ class Orders_model extends CI_Model { $sql .= " and coli.COLI_SN='$coli_sn' "; } if ($startDate !== NULL) { - // $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test + $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test } $query = $this->HT->query($sql); return $query->result(); @@ -270,6 +270,16 @@ class Orders_model extends CI_Model { $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); return $this->GCI_SN; } + + public function biz_groupcombineoperationdetail_cut($combineNo) + { + $sql = "DELETE + FROM BIZ_GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N?"; + $query = $this->HT->query($sql, array($combineNo)); + return $query; + } + public function combineoperation_exist($combineNo='', $operation="") { if( ! $combineNo) { return array(); } @@ -945,6 +955,11 @@ class Orders_model extends CI_Model { return $this->FOI_SN; } + /*! + * 查询是否已经写入过客人列表 + * @date 2018-04-28 + * @param [type] $cold_sn 订单字表key + */ public function bookpeople_exist($cold_sn) { if( ! $cold_sn) { return array(); } @@ -1104,42 +1119,20 @@ class Orders_model extends CI_Model { } } - /** - * - * 更新订单状态(商务订单) - * - */ - public function update_biz_order($order_id, $pay_manager, $source_type, $state, $text = '') { - //更新订单 - $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner=?,COLI_sourcetype=?,COLI_State=?,COLI_OrderDetailText=COLI_OrderDetailText+? WHERE COLI_ID=?"; - $query = $this->HT->query($sql, array($pay_manager, $source_type, $state, $text, $order_id . '')); - $this->insert_acc_info($order_id); - return '是否执行:' . print_r($query, true) . ' sql:' . $sql . ' 参数:' . print_r(array($pay_manager, $source_type, $state, $text, $order_id . ''), true); - } - - /** - * - * 更新火车订单购票截图 - * + /*! + * 删除收款记录以更新 + * @date 2018-04-28 + * @param [type] $coli_sn 订单key + * @param [type] $paytype 付款方式 */ - public function update_train_order_pic($order_pic_id) { - //更新订单 - $sql = "exec dbo.SP_BIZ_GroupFinanceList_Insert '" . $order_pic_id . "'"; - //$query = $this->HT->query($sql); - - include('c:/database_conn.php'); - $connection = array( - 'UID' => $db['HT']['username'], - 'PWD' => $db['HT']['password'], - 'Database' => 'tourmanager', - 'ConnectionPooling' => 1, - 'CharacterSet' => 'utf-8', - 'ReturnDatesAsStrings' => 1 - ); - $conn = sqlsrv_connect($db['HT']['hostname'], $connection); - $stmt = sqlsrv_query($conn, $sql); - - return $stmt; + public function biz_groupaccountinfo_cut($coli_sn, $paytype) + { + $sql = "UPDATE BIZ_GroupAccountInfo + SET DeleteFlag=1 + WHERE GAI_COLI_SN=? + AND GAI_Type=?"; + $query = $this->HT->query($sql, array($coli_sn, $paytype)); + return $query; } /** @@ -1147,24 +1140,25 @@ class Orders_model extends CI_Model { * 插入收款记录 * */ - public function insert_acc_info($order_id) { - //获取订单 - $sql = "Select Top 1 COLI_SN,COLI_ID,COLI_PayManner,COLI_Price From BIZ_ConfirmLineInfo Where COLI_ID = ?"; - $query = $this->HT->query($sql, array($order_id)); - $order_info = $query->row(); - //插入记录 - $sql = "INSERT INTO BIZ_GroupAccountInfo \n" + public $GAI_COLI_SN; + public $GAI_GRI_SN; + public $GAI_COLI_ID; + public $GAI_Type; + public $GAI_SQJE; + public $GAI_SQDate; + public $GAI_SQJECurrency; + public $GAI_Memo=""; + public function biz_groupaccountinfo_save() + { + $sql = "INSERT INTO BIZ_GroupAccountInfo \n" . " ( \n" . " GAI_COLI_SN, \n" + . " GAI_GRI_SN, \n" . " GAI_COLI_ID, \n" . " GAI_Type, \n" . " GAI_SQJE, \n" . " GAI_SQDate, \n" - . " GAI_SSJE, \n" . " GAI_SQJECurrency, \n" - . " GAI_SSDate, \n" - . " GAI_CusName, \n" - . " GAI_CusEmail, \n" . " GAI_Memo \n" . " ) \n" . "VALUES \n" @@ -1176,20 +1170,19 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " ?, \n" - . " ?, \n" - . " ?, \n" - . " ?, \n" . " ? \n" . " )"; - $query = $this->HT->query($sql, array($order_info->COLI_SN, - $order_info->COLI_ID, - $order_info->COLI_PayManner, - $order_info->COLI_Price, - date('Y-m-d H:i:s'), - $order_info->COLI_Price, - $this->config->item('Site_Currency'), - date('Y-m-d H:i:s'), - "", "", " ")); + $query = $this->HT->query($sql, array( + $this->GAI_COLI_SN + ,$this->GAI_GRI_SN + ,$this->GAI_COLI_ID + ,$this->GAI_Type + ,$this->GAI_SQJE + ,$this->GAI_SQDate + ,$this->GAI_SQJECurrency + ,$this->GAI_Memo + )); + return $query; } function GetNationalityID($nationalityName) { From 3526c9ce834ce2b91f94a2ae3090cc466b4900d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sat, 28 Apr 2018 17:59:01 +0800 Subject: [PATCH 064/382] =?UTF-8?q?trippest=20=E5=9B=BE=E5=85=B0=E6=9C=B5?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E7=8A=B6=E6=80=81=E4=B8=8A=E6=8A=A5,=20?= =?UTF-8?q?=E9=AA=8C=E8=AF=81=E8=BA=AB=E4=BB=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 96220ea5..560b3bc4 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -33,6 +33,10 @@ class TulanduoApi extends CI_Controller ) ); + // userId key + // 1343 2e47c3721e3ff6e816fe6b928d7acc7d + // 29188 95c3b0d958a79a1216e651df182b3cb4 + // 30548 9db75a2dc17156eb122364295804b7a2 // test // public $list_url = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/"; @@ -535,8 +539,12 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $ret['status'] = -1; $ret['errMsg'] = "未知错误"; $input = $this->input->post(); - // todo 验证userID $vendorID = $input['userId']; + $validate = $this->calc_key($vendorID, $input['key']); + if ($validate !== TRUE) { + $ret['errMsg'] = "身份验证失败."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } // $vendorID = 29188;//29188 1343; // test $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { @@ -675,4 +683,11 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ); } + public function calc_key($userId, $key) + { + $default = "b825e39422a54875a95752fc7ed6f5d2"; + $ret = md5(hash("sha256", $userId.$default)); + return $ret===$key; + } + } From 4347c580620224e79c587df713ea4c40303c3dda Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 2 May 2018 14:09:35 +0800 Subject: [PATCH 065/382] =?UTF-8?q?trippest=20=E5=9B=A2=E6=AC=BE=E7=9B=B4?= =?UTF-8?q?=E6=8E=A5=E6=8C=89=E7=85=A7=E6=8E=A5=E5=8F=A3=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E7=9A=84=E5=86=99=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 560b3bc4..88fcbb2d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -316,9 +316,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Orders_model->biz_groupaccountinfo_cut($order->COLI_SN, $paytype); if (isset($detail_jsonResp->orderDetail->travelFees) && $order->GCI_FromAgc != "D目的地桂林组") { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { - if ($vtf->reviewStatus == 0) { // 未审核的 - continue; - } + // if ($vtf->reviewStatus == 0) { // 未审核的 + // continue; + // } $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; @@ -332,9 +332,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); // 代收 if (isset($detail_jsonResp->orderDetail->replaceCollections)) { foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { - if ($vrc->reviewStatus == 0) { - continue; - } + // if ($vrc->reviewStatus == 0) { + // continue; + // } $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; @@ -348,9 +348,9 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); // 代付 if (isset($detail_jsonResp->orderDetail->replacePays)) { foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { - if ($vrp->reviewStatus == 0) { - continue; - } + // if ($vrp->reviewStatus == 0) { + // continue; + // } $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; From 0b0277a4daa2cb83b1e428d5636d36c67837644b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 2 May 2018 16:51:28 +0800 Subject: [PATCH 066/382] =?UTF-8?q?trippest=20=E4=BC=A0=E7=BB=9F=E5=9B=A2?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=9B=9E=E6=89=A7;=20=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E7=9A=84=E5=9B=A2=E6=9B=B4=E6=96=B0=E5=88=B0HT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 81 ++++++++++++++++--- .../trippestOrderSync/models/orders_model.php | 23 +++++- 2 files changed, 90 insertions(+), 14 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 88fcbb2d..59b436b2 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -70,6 +70,10 @@ class TulanduoApi extends CI_Controller mb_regex_encoding("UTF-8"); } + /*! + * 获取订单列表 + * @date 2018-05-02 + */ public function get_orderlist() { $this->tld_order->setUserId($this->userId) @@ -221,6 +225,11 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); return; } + /*! + * 更新订单的详情;[客人列表, 团费, 调度信息] + * @date 2018-05-02 + * @param [type] $coli_sn HT系统的订单key + */ public function insert_HT_order_operation($coli_sn=null) { $this->load->model('Order_update'); @@ -245,9 +254,18 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); ->setKey($this->key); $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); $detail_jsonResp = json_decode($detail_resp); + // 判断取消 if ($detail_jsonResp->status !== 1) { log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); - return; + if ($detail_jsonResp->errMsg == "未查询到对应的订单") { + $this->order_cancel($order->COLI_ID); + } + continue; + } + // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 + if ($order->GCI_FromAgc != "D目的地桂林组" && mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { + $this->order_cancel($order->COLI_ID); + continue; } $allDetails_to_HT = ""; $allDetails_to_HT .= "\r\n日程: "; @@ -362,7 +380,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); } } /*BIZ_GroupCombineOperationDetail*/ - if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { + if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { // 没有拼团团号 continue; } if (in_array($detail_jsonResp->orderDetail->groupOrderNo, $unique_orderGroupCombine)) { @@ -457,7 +475,28 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); return; } - public function order_push($COLI_ID=0) // test + /*! + * 取消团 + * @date 2018-05-02 + * @param string $COLI_ID HT系统订单号 + */ + public function order_cancel($COLI_ID="") + { + /** UPDATE HT */ + /** BIZ_ConfirmLineInfo */ + $this->Order_update->coli_where_update = " COLI_ID=" . $COLI_ID; + $coli_update_column = array( + "COLI_State" => 40 + ); + return $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + } + + /*! + * 发送预订计划到地接系统 + * @date 2018-05-02 + * @param string $COLI_ID HT系统订单号 + */ + public function order_push($COLI_ID="") // test { // exit(); /** 目的地 test */ @@ -546,23 +585,34 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } // $vendorID = 29188;//29188 1343; // test - $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); - if (empty($vas_info) && ! empty($input['agcOrderNo'])) { + $vas_info = array(); + if ($input['agcName'] == 'D目的地桂林组') { + $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); + if (empty($vas_info) && ! empty($input['agcOrderNo'])) { + $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); + } + } elseif ($input['agcName'] == '桂林海纳国旅') { $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); - $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID); } + if (empty($vas_info)) { $ret['errMsg'] = "未找到订单."; } else { $vendor_manager = $this->Orders_model->get_vendorContact($vendorID); + /** VendorArrangeState */ $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime']; $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo; $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo); - $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; - $coli_update_column = array( - "COLI_State" => 7 - ); - $update_coli = $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + if ($input['agcName'] == 'D目的地桂林组') { // 传统团的不需要更新订单主表 + /** BIZ_confirmlineinfo */ + $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; + $coli_update_column = array( + "COLI_State" => 7 + ); + $update_coli = $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + } if ($update_vas === TRUE) { $ret['status'] = 1; $ret['errMsg'] = ""; @@ -587,10 +637,17 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } + /*! + * 目的地项目组的订单计划的团号分析 + * 去除添加的后缀, 只保留前两部分: XXXXXX-YYYYYYYYYYYY + * @date 2018-05-02 + * @param [type] $groupCode 从地接系统获取到的团号 + */ public function analysis_groupCode($groupCode) { mb_regex_encoding("UTF-8"); - $tmp_groupCode = explode("-", $groupCode); + preg_match('^[\w\-]+^', $this->characet($groupCode, "UTF-8"), $temp_array); + $tmp_groupCode = explode("-", $temp_array[0]); $real_groupCode = $tmp_groupCode[0] . "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; $real_groupCode = mb_ereg_replace('(\s| )', '', $real_groupCode); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index f3427470..5c23f390 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -159,9 +159,10 @@ class Orders_model extends CI_Model { return $query->result(); } /*! - * 获取团计划信息的记录 - 根据组团社团号 + * 获取团计划信息的记录 - 根据组团社团号 - 商务订单 * 计划变更和订单状态确认时使用 - * @param integer $groupCode 图兰朵地接社系统的订单id + * @param string $groupCode 团号 + * @param integer $vei_sn HT系统中供应商key */ public function get_vendorarrangestate_byGroup($groupCode, $vei_sn) { @@ -175,6 +176,24 @@ class Orders_model extends CI_Model { $query = $this->HT->query($sql, array($vei_sn)); return $query->result(); } + /*! + * 获取团计划信息的记录 - 根据组团社团号 - 传统订单 + * 计划变更和订单状态确认时使用 + * @param string $groupCode 团号 + * @param integer $vei_sn HT系统中供应商key + */ + public function get_vendorarrangestate_byGroup_T($groupCode, $vei_sn) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM GRoupInfo gri + INNER JOIN ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '$groupCode%'"; + $query = $this->HT->query($sql, array($vei_sn)); + return $query->result(); + } /*! * 生成预定传真 From 2cf4cc9c6ce138e11da69712c9a91666a89fb9f0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 4 May 2018 10:30:46 +0800 Subject: [PATCH 067/382] =?UTF-8?q?trippest=20=E4=BF=AE=E6=AD=A3=E5=88=86?= =?UTF-8?q?=E6=9E=90=E5=9B=A2=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 10 +++++----- .../trippestOrderSync/models/orders_model.php | 6 +++--- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 59b436b2..508afa42 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -124,9 +124,9 @@ class TulanduoApi extends CI_Controller continue; } $unique_order[] = $vo['orderId']; - $vo['agcOrderNo'] = mb_ereg_replace('(\s| )', '', $vo['agcOrderNo']); // 去掉中文的全角空格 + $vo['agcOrderNo'] = mb_ereg_replace('( )', '', trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $PAG_Code = $pag_sub = null; - preg_match('^[a-zA-Z]+\-[0-9\-]+^', $this->characet($vo['routeName'], "UTF-8"), $temp_array); + preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { // 旧的数据没有线路代号 log_message('error','未识别的线路名称 ' . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); @@ -646,11 +646,11 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); public function analysis_groupCode($groupCode) { mb_regex_encoding("UTF-8"); - preg_match('^[\w\-]+^', $this->characet($groupCode, "UTF-8"), $temp_array); - $tmp_groupCode = explode("-", $temp_array[0]); + preg_match('/[\w\s\-]+/', $this->characet($groupCode, "UTF-8"), $temp_array); + $tmp_groupCode = explode("-", trim(strrchr($temp_array[0], " "))); $real_groupCode = $tmp_groupCode[0] . "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; - $real_groupCode = mb_ereg_replace('(\s| )', '', $real_groupCode); + $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); return $real_groupCode; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5c23f390..221970b9 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -172,7 +172,7 @@ class Orders_model extends CI_Model { INNER JOIN BIZ_ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID - WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '$groupCode%'"; + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '%$groupCode%'"; $query = $this->HT->query($sql, array($vei_sn)); return $query->result(); } @@ -190,7 +190,7 @@ class Orders_model extends CI_Model { INNER JOIN ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID - WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '$groupCode%'"; + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '%$groupCode%'"; $query = $this->HT->query($sql, array($vei_sn)); return $query->result(); } @@ -473,7 +473,7 @@ class Orders_model extends CI_Model { $sql = "SELECT top 1 COLI_SN,GRI_SN FROM BIZ_ConfirmLineInfo coli LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '$code%'"; + WHERE gri.GRI_No LIKE '%$code%'"; $query = $this->HT->query($sql); if ($query->row()) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; From 5c1f3664beab6d890901183cd7857b37f21ce720 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 8 May 2018 15:28:41 +0800 Subject: [PATCH 068/382] =?UTF-8?q?trippest=20=E5=88=A0=E9=99=A4=E6=B5=8B?= =?UTF-8?q?=E8=AF=95;=E6=95=B0=E6=8D=AE=E5=BA=93=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E4=BC=A0=E7=BB=9F=E5=9B=A2=E5=8F=AF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 35 ++++++++++------ .../trippestOrderSync/models/order_update.php | 2 +- .../trippestOrderSync/models/orders_model.php | 42 ++++++++++++------- 3 files changed, 51 insertions(+), 28 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 508afa42..ac6f3bfb 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -76,14 +76,16 @@ class TulanduoApi extends CI_Controller */ public function get_orderlist() { + $startOrderDate = date('Y-m-d', strtotime("-2 days")); + $endOrderDate = date('Y-m-d'); $this->tld_order->setUserId($this->userId) ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) - ->setStartTravelDate("2018-04-21") // test - ->setEndTravelDate("2018-04-21") - // ->setStartOrderDate("2018-04-13") - // ->setEndOrderDate("2018-04-13") + // ->setStartTravelDate("2018-04-21") // test + // ->setEndTravelDate("2018-04-21") + ->setStartOrderDate($startOrderDate) + ->setEndOrderDate($endOrderDate) ; $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); @@ -124,6 +126,8 @@ class TulanduoApi extends CI_Controller continue; } $unique_order[] = $vo['orderId']; + $this->Orders_model->BIZ_COLI_SN = null; + $this->Orders_model->GRI_SN = null; $vo['agcOrderNo'] = mb_ereg_replace('( )', '', trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $PAG_Code = $pag_sub = null; preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); @@ -145,7 +149,8 @@ class TulanduoApi extends CI_Controller $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; - $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId']); // 查询订单是否已经录入过 + $tmpv = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; + $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model @@ -182,7 +187,6 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $coli_sn[] = $this->Orders_model->biz_confirm_save(); -log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; $this->Orders_model->COLD_ServiceType = "D"; @@ -211,6 +215,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); /*biz_groupcombineinfo*/ $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; $this->Orders_model->GCI_GRI_SN = $this->Orders_model->GRI_SN; + $this->Orders_model->GCI_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; $this->Orders_model->GCI_FromAgc = $vo['agcName']; $this->Orders_model->GCI_groupType = $vo['orderType']; @@ -236,10 +241,10 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); if ($coli_sn !== null) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); } else { - $startDate = ('2018-04-21'); - $endDate = ('2018-04-22'); // test - // $startDate = date('Y-m-d'); - // $endDate = date('Y-m-d', strtotime("+4 days")); + // $startDate = ('2018-04-21'); + // $endDate = ('2018-04-22'); // test + $startDate = date('Y-m-d'); + $endDate = date('Y-m-d', strtotime("+4 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); } $unique_orderGroupCombine = array(); @@ -301,6 +306,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; $gci_update_column = array( "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo + ,"GCI_VEI_SN" => $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate ); @@ -393,6 +399,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; + $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; $this->Orders_model->GCOD_operationType = "sceneryOperations"; $this->Orders_model->GCOD_subType = $vso->type; $this->Orders_model->GCOD_title = $vso->name; @@ -414,6 +421,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; $this->Orders_model->GCOD_operationType = "restraurantOperations"; $this->Orders_model->GCOD_subType = $vro->type; $this->Orders_model->GCOD_title = $vro->name; @@ -434,6 +442,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; $this->Orders_model->GCOD_operationType = "touristCarOperations"; $this->Orders_model->GCOD_subType = $vco->type; $this->Orders_model->GCOD_title = $vco->name; @@ -454,6 +463,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; $this->Orders_model->GCOD_operationType = "guiderOperations"; $this->Orders_model->GCOD_subType = ""; $this->Orders_model->GCOD_title = ""; @@ -498,7 +508,7 @@ log_message('error','new coli ' . $this->Orders_model->BIZ_COLI_ID); */ public function order_push($COLI_ID="") // test { - // exit(); + exit(); /** 目的地 test */ $this->userId = "358"; $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -647,7 +657,8 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); { mb_regex_encoding("UTF-8"); preg_match('/[\w\s\-]+/', $this->characet($groupCode, "UTF-8"), $temp_array); - $tmp_groupCode = explode("-", trim(strrchr($temp_array[0], " "))); + $temp_array[0] = strrchr($temp_array[0], " ") ? strrchr($temp_array[0], " ") : $temp_array[0]; + $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0] . "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 8c4a307a..7c2b17f0 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -51,7 +51,7 @@ class Order_update extends CI_Model { if ($this->gci_where_update == "" || empty($column_data)) { return false; } - $update_str = $this->HT->update_string('BIZ_GroupCombineInfo', $column_data, $this->gci_where_update); + $update_str = $this->HT->update_string('GroupCombineInfo', $column_data, $this->gci_where_update); $update_exc = $this->HT->query($update_str); return $update_exc; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 221970b9..5ac7bba3 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -127,7 +127,7 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) { $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* - FROM BIZ_GroupCombineInfo gci + FROM GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN WHERE 1=1 "; @@ -150,12 +150,12 @@ class Orders_model extends CI_Model { { $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN - FROM BIZ_GroupCombineInfo gci + FROM GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON gci.GCI_GRI_SN=coli.COLI_GRI_SN INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID - WHERE gci.GCI_VendorOrderId=? and vas.VAS_VEI_SN=? "; - $query = $this->HT->query($sql, array($vendorOrderId, $vei_sn)); + WHERE gci.GCI_VendorOrderId=? and vas.VAS_VEI_SN=? and gci.GCI_VEI_SN=? "; + $query = $this->HT->query($sql, array($vendorOrderId, $vei_sn, $vei_sn)); return $query->result(); } /*! @@ -239,6 +239,7 @@ class Orders_model extends CI_Model { } public $GCI_SN; + public $GCI_VEI_SN; public $GCI_combineNo=''; // 拼团团号 public $GCI_GRI_SN; // 团key public $GCI_VendorOrderId; // 地接社系统订单id @@ -252,12 +253,13 @@ class Orders_model extends CI_Model { { $sql = "IF NOT EXISTS( SELECT TOP 1 1 - FROM BIZ_GroupCombineInfo - WHERE GCI_VendorOrderId = ? and GCI_GRI_SN=? + FROM GroupCombineInfo + WHERE GCI_VendorOrderId = ? and GCI_GRI_SN=? and GCI_VEI_SN=? ) - INSERT INTO BIZ_GroupCombineInfo + INSERT INTO GroupCombineInfo (GCI_combineNo ,GCI_GRI_SN + ,GCI_VEI_SN ,GCI_VendorOrderId ,GCI_FromAgc ,GCI_groupType @@ -268,6 +270,7 @@ class Orders_model extends CI_Model { (N? ,? ,? + ,? ,N? ,? ,? @@ -277,8 +280,10 @@ class Orders_model extends CI_Model { $query = $this->HT->query($sql, array( $this->GCI_VendorOrderId ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN ,$this->GCI_combineNo ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN ,$this->GCI_VendorOrderId ,$this->GCI_FromAgc ,$this->GCI_groupType @@ -286,24 +291,27 @@ class Orders_model extends CI_Model { ,$this->GCI_leaveDate ,$this->GCI_createTime )); - $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM BIZ_GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); return $this->GCI_SN; } public function biz_groupcombineoperationdetail_cut($combineNo) { $sql = "DELETE - FROM BIZ_GroupCombineOperationDetail + FROM GroupCombineOperationDetail WHERE GCOD_GCI_combineNo = N?"; $query = $this->HT->query($sql, array($combineNo)); return $query; } + /*! + * 暂时没用 + */ public function combineoperation_exist($combineNo='', $operation="") { if( ! $combineNo) { return array(); } $sql = "SELECT TOP 1 GCOD_GCI_combineNo - FROM BIZ_GroupCombineOperationDetail + FROM GroupCombineOperationDetail WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; $query = $this->HT->query($sql, array( $combineNo,$operation @@ -311,6 +319,7 @@ class Orders_model extends CI_Model { return $query->result(); } public $GCOD_SN; + public $GCOD_VEI_SN; public $GCOD_GCI_combineNo = ''; public $GCOD_operationType = ''; public $GCOD_subType = ''; @@ -330,11 +339,12 @@ class Orders_model extends CI_Model { { // IF NOT EXISTS( // SELECT TOP 1 1 - // FROM BIZ_GroupCombineOperationDetail + // FROM GroupCombineOperationDetail // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? // ) - $sql = "INSERT INTO BIZ_GroupCombineOperationDetail + $sql = "INSERT INTO GroupCombineOperationDetail (GCOD_GCI_combineNo + ,GCOD_VEI_SN ,GCOD_operationType ,GCOD_subType ,GCOD_title @@ -351,6 +361,7 @@ class Orders_model extends CI_Model { ,GCOD_creatTime) VALUES (N? + ,? ,N? ,N? ,N? @@ -368,6 +379,7 @@ class Orders_model extends CI_Model { "; $query = $this->HT->query($sql, array( $this->GCOD_GCI_combineNo + ,$this->GCOD_VEI_SN ,$this->GCOD_operationType // ,$this->GCOD_GCI_combineNo // ,$this->GCOD_operationType @@ -452,12 +464,12 @@ class Orders_model extends CI_Model { return $this->GUT_SN; } - public function get_SN_by_vendorOrderId($vendorOrderId) + public function get_SN_by_vendorOrderId($vendorOrderId, $vendorID) { $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN - FROM BIZ_GroupCombineInfo gci + FROM GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN - WHERE gci.GCI_VendorOrderId='$vendorOrderId'"; + WHERE gci.GCI_VendorOrderId='$vendorOrderId' and GCI_VEI_SN='$vendorID'"; $query = $this->HT->query($sql); if ($query->row()) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; From 3dd74efcd5b36407e6969041a61f1e53f3456873 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 8 May 2018 16:50:33 +0800 Subject: [PATCH 069/382] =?UTF-8?q?trippest=20=E5=9B=A2=E5=90=8D=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 31 ++++++++++--------- .../trippestOrderSync/models/orders_model.php | 4 +-- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index ac6f3bfb..f71c0893 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -76,6 +76,7 @@ class TulanduoApi extends CI_Controller */ public function get_orderlist() { + log_message('error','get_orderlist From TuLanDuo ' ); $startOrderDate = date('Y-m-d', strtotime("-2 days")); $endOrderDate = date('Y-m-d'); $this->tld_order->setUserId($this->userId) @@ -149,12 +150,12 @@ class TulanduoApi extends CI_Controller $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; - $tmpv = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; + $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model - $this->Orders_model->get_SN_by_groupCode($real_groupCode); + $this->Orders_model->get_SN_by_groupCode($real_groupCode, mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 19)); } /** insert HT */ if ($this->Orders_model->BIZ_COLI_SN === null) { @@ -165,9 +166,9 @@ class TulanduoApi extends CI_Controller $travelDate = new DateTime($vo['travelDate']); $leaveDate = new DateTime($vo['leaveDate']); $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->GRI_No = $vo['agcOrderNo']; + $this->Orders_model->GRI_No = mb_substr($vo['agcOrderNo'], 0, 19); $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = $vo["agcName"] . $vo['agcOrderNo']; + $this->Orders_model->GRI_Name = mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 19); $this->Orders_model->GRI_PersonNum = $vo['adultNum']+$vo['childNum']; $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); $this->Orders_model->GRI_IsCancel = 0; @@ -184,7 +185,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_servicetype = 'D'; $this->Orders_model->BIZ_COLI_ConfirmType = 52001; $this->Orders_model->BIZ_COLI_Memo = ""; - $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName']; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName'] . "; 团名: " . $vo['agcOrderNo']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $coli_sn[] = $this->Orders_model->biz_confirm_save(); /**BIZ_ConfirmLineDetail*/ @@ -199,7 +200,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->COLD_ChildNum = $vo['childNum']; $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认 // 4 下计划未确认 $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->COLD_PlanVEI_SN = empty($this->city_info[$vo['operationDep']]) ? 1343 : $this->city_info[$vo['operationDep']]['PlanVEI_SN']; + $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->COLD_MemoText = $COLD_MemoText; $this->Orders_model->biz_confirm_detail_save(); /** SP_BIZ_Arrange @@ -237,6 +238,7 @@ class TulanduoApi extends CI_Controller */ public function insert_HT_order_operation($coli_sn=null) { + log_message('error','get_order_operation From TuLanDuo '); $this->load->model('Order_update'); if ($coli_sn !== null) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); @@ -294,8 +296,8 @@ class TulanduoApi extends CI_Controller /** UPDATE */ /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $order->COLI_SN; - $old_memo = mb_strstr($order->COLI_Memo, "orderRemark", true) ? mb_strstr($order->COLI_Memo, "orderRemark", true) : $order->COLI_Memo; - $old_detail = mb_strstr($order->COLI_OrderDetailText, "operations", true) ? mb_strstr($order->COLI_OrderDetailText, "operations", true) : $order->COLI_OrderDetailText; + $old_memo = mb_strstr($order->COLI_Memo, "orderRemark", true)!==false ? mb_strstr($order->COLI_Memo, "orderRemark", true) : $order->COLI_Memo; + $old_detail = mb_strstr($order->COLI_OrderDetailText, "operations", true)!==false ? mb_strstr($order->COLI_OrderDetailText, "operations", true) : $order->COLI_OrderDetailText; $coli_update_column = array( "COLI_Memo" => $old_memo . "orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n" ,"COLI_OrderDetailText" => $old_detail . "operations\r\n" . $allDetails_to_HT . "\r\n" @@ -304,9 +306,10 @@ class TulanduoApi extends CI_Controller /** BIZ_ConfirmLineDetail */ // nothing to update /** biz_groupcombineinfo */ $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; + $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; $gci_update_column = array( "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo - ,"GCI_VEI_SN" => $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] + ,"GCI_VEI_SN" => $vei_SN ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate ); @@ -399,7 +402,7 @@ class TulanduoApi extends CI_Controller if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; - $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "sceneryOperations"; $this->Orders_model->GCOD_subType = $vso->type; $this->Orders_model->GCOD_title = $vso->name; @@ -421,7 +424,7 @@ class TulanduoApi extends CI_Controller if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "restraurantOperations"; $this->Orders_model->GCOD_subType = $vro->type; $this->Orders_model->GCOD_title = $vro->name; @@ -442,7 +445,7 @@ class TulanduoApi extends CI_Controller if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "touristCarOperations"; $this->Orders_model->GCOD_subType = $vco->type; $this->Orders_model->GCOD_title = $vco->name; @@ -463,7 +466,7 @@ class TulanduoApi extends CI_Controller if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN']; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "guiderOperations"; $this->Orders_model->GCOD_subType = ""; $this->Orders_model->GCOD_title = ""; @@ -660,7 +663,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $temp_array[0] = strrchr($temp_array[0], " ") ? strrchr($temp_array[0], " ") : $temp_array[0]; $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0] . "-"; - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true) ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); return $real_groupCode; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5ac7bba3..dfed8def 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -480,12 +480,12 @@ class Orders_model extends CI_Model { return NULL; } - public function get_SN_by_groupCode($code) + public function get_SN_by_groupCode($code, $NoName) { $sql = "SELECT top 1 COLI_SN,GRI_SN FROM BIZ_ConfirmLineInfo coli LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '%$code%'"; + WHERE gri.GRI_No LIKE '%$code%' and gri.GRI_No like '%$NoName%' "; $query = $this->HT->query($sql); if ($query->row()) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; From 70c4d90f41e823615f9cead4872818a902a64883 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 9 May 2018 16:07:46 +0800 Subject: [PATCH 070/382] =?UTF-8?q?trippest=20=E5=9B=A2=E5=90=8D=E7=9A=84?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 11 ++++++----- .../trippestOrderSync/models/orders_model.php | 2 +- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index f71c0893..aa4302cd 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -155,7 +155,7 @@ class TulanduoApi extends CI_Controller if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model - $this->Orders_model->get_SN_by_groupCode($real_groupCode, mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 19)); + $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); } /** insert HT */ if ($this->Orders_model->BIZ_COLI_SN === null) { @@ -166,9 +166,9 @@ class TulanduoApi extends CI_Controller $travelDate = new DateTime($vo['travelDate']); $leaveDate = new DateTime($vo['leaveDate']); $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->GRI_No = mb_substr($vo['agcOrderNo'], 0, 19); + $this->Orders_model->GRI_No = mb_substr($vo['agcOrderNo'], 0, 49); $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 19); + $this->Orders_model->GRI_Name = mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 49); $this->Orders_model->GRI_PersonNum = $vo['adultNum']+$vo['childNum']; $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); $this->Orders_model->GRI_IsCancel = 0; @@ -222,7 +222,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GCI_groupType = $vo['orderType']; $this->Orders_model->GCI_travelDate = $vo['travelDate']; $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; - $this->Orders_model->GCI_createTime = $vo['orderDate']; + $this->Orders_model->GCI_createTime = date('Y-m-d H:i:s'); $this->Orders_model->biz_groupcombineinfo_save(); } } @@ -308,10 +308,11 @@ class TulanduoApi extends CI_Controller $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; $gci_update_column = array( - "GCI_combineNo" => $detail_jsonResp->orderDetail->groupOrderNo + "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null ,"GCI_VEI_SN" => $vei_SN ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate + ,"GCI_createTime" => date('Y-m-d H:i:s') ); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); /** INSERT */ diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index dfed8def..e6b88da4 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -485,7 +485,7 @@ class Orders_model extends CI_Model { $sql = "SELECT top 1 COLI_SN,GRI_SN FROM BIZ_ConfirmLineInfo coli LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '%$code%' and gri.GRI_No like '%$NoName%' "; + WHERE gri.GRI_No LIKE '%$code%' and gri.GRI_Name like '%$NoName%' "; $query = $this->HT->query($sql); if ($query->row()) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; From 8b9e2609b52e977781d9d0cb5310a6372551597c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 9 May 2018 16:41:28 +0800 Subject: [PATCH 071/382] =?UTF-8?q?trippest=20=E8=AE=A2=E5=8D=95=E7=8A=B6?= =?UTF-8?q?=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/models/orders_model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e6b88da4..e70a1cb4 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -130,7 +130,7 @@ class Orders_model extends CI_Model { FROM GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE 1=1 "; + WHERE 1=1 and coli.COLI_State NOT IN ('30','40','50')"; if ($coli_sn !== 0) { $sql .= " and coli.COLI_SN='$coli_sn' "; } From 3c343a0ac4daac3b70a01940e6bc38f3a3140603 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 9 May 2018 17:02:08 +0800 Subject: [PATCH 072/382] =?UTF-8?q?trippest=20=E6=B3=A8=E9=87=8A=20todo:?= =?UTF-8?q?=20=E8=8E=B7=E5=8F=96=E8=B0=83=E5=BA=A6=E8=AF=A6=E6=83=85?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=E6=AF=8F=E6=AC=A1=E6=9B=B4=E6=96=B0=E4=B8=80?= =?UTF-8?q?=E4=B8=AA,=E4=B8=8D=E8=A6=81=E4=B8=80=E6=AC=A1=E5=BE=AA?= =?UTF-8?q?=E7=8E=AF=E5=A4=9A=E4=B8=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 4 ++-- webht/third_party/trippestOrderSync/models/orders_model.php | 6 +++++- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index aa4302cd..a8202780 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -226,7 +226,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineinfo_save(); } } - echo "Got order list from 图兰朵. count: " . $resp_arr["responseData"]["totalRows"] . "\r\n"; + echo "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . "\r\n"; echo "Insert COLI : " . $cnt . "\r\n"; return; } @@ -485,7 +485,7 @@ class TulanduoApi extends CI_Controller } } } // end foreach order - echo "Got order from 图兰朵, count: " . count($to_update_list); + echo "Got order from TuLanDuo, count: " . count($to_update_list); return; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e70a1cb4..f553bfb2 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1,5 +1,9 @@ <?php +/*! + * 这里操作的都是商务表, 传统订单的表不在这里 + */ + class Orders_model extends CI_Model { function __construct() { @@ -119,7 +123,7 @@ class Orders_model extends CI_Model { return NULL; } /*! - * 需要更新调度信息的订单 + * 需要更新调度信息的订单 -- 商务表 * @param integer $coli_sn [description] * @param [type] $startDate [description] * @param [type] $endDate [description] From be3aa99296f231a7d242233fc8123b7357157803 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 9 May 2018 17:46:14 +0800 Subject: [PATCH 073/382] =?UTF-8?q?trippest=20trippest=E8=B4=A6=E6=88=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 15 ++++++++------- .../trippestOrderSync/models/orders_model.php | 1 - 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index a8202780..4c5e2156 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -97,7 +97,7 @@ class TulanduoApi extends CI_Controller $all_list = $resp_arr["responseData"]["orders"]; $order_to_HT = array_map( function($ele){ - if ( ! in_array($ele['agcName'], array("D目的地桂林组")) ) { + if ( ! in_array($ele['agcName'], array("D目的地桂林组", "Trippest")) ) { return $ele; } },$resp_arr["responseData"]["orders"]); @@ -111,7 +111,7 @@ class TulanduoApi extends CI_Controller } $f_order_to_HT = array_map( function($ele){ - if ( ! in_array($ele['agcName'], array("D目的地桂林组")) ) { + if ( ! in_array($ele['agcName'], array("D目的地桂林组", "Trippest")) ) { return $ele; } },$f_resp_arr["responseData"]["orders"]); @@ -152,7 +152,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 - if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组"))) { + if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); @@ -270,7 +270,7 @@ class TulanduoApi extends CI_Controller continue; } // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 - if ($order->GCI_FromAgc != "D目的地桂林组" && mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { + if ( ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) && mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { $this->order_cancel($order->COLI_ID); continue; } @@ -342,7 +342,7 @@ class TulanduoApi extends CI_Controller $pay_currency = 'RMB'; // 删除旧的录入 $this->Orders_model->biz_groupaccountinfo_cut($order->COLI_SN, $paytype); - if (isset($detail_jsonResp->orderDetail->travelFees) && $order->GCI_FromAgc != "D目的地桂林组") { + if (isset($detail_jsonResp->orderDetail->travelFees) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { // if ($vtf->reviewStatus == 0) { // 未审核的 // continue; @@ -600,7 +600,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); } // $vendorID = 29188;//29188 1343; // test $vas_info = array(); - if ($input['agcName'] == 'D目的地桂林组') { + if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); @@ -619,7 +619,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime']; $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo; $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo); - if ($input['agcName'] == 'D目的地桂林组') { // 传统团的不需要更新订单主表 + if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { // 传统团的不需要更新订单主表 /** BIZ_confirmlineinfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; $coli_update_column = array( @@ -762,4 +762,5 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $ret===$key; } + } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index f553bfb2..37656449 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1695,5 +1695,4 @@ class Orders_model extends CI_Model { } - } From 2a17a7058494119c9fd87d4cc384355ba8f80910 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 9 May 2018 17:54:27 +0800 Subject: [PATCH 074/382] =?UTF-8?q?trippest=20=E6=8B=BC=E5=9B=A2=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E4=BE=9B=E5=BA=94=E5=95=86=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/TulanduoApi.php | 2 +- webht/third_party/trippestOrderSync/models/orders_model.php | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4c5e2156..4ade8e3d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -306,7 +306,7 @@ class TulanduoApi extends CI_Controller /** BIZ_ConfirmLineDetail */ // nothing to update /** biz_groupcombineinfo */ $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; - $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; + $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : $order->COLD_PlanVEI_SN; $gci_update_column = array( "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null ,"GCI_VEI_SN" => $vei_SN diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 37656449..5e0c6a8d 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -130,7 +130,8 @@ class Orders_model extends CI_Model { */ public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, gci.* + $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, + cold.COLD_PlanVEI_SN, gci.* FROM GroupCombineInfo gci INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN From 2a2d7dc741490c1dd613336c186e92a394c207bb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 10 May 2018 11:14:49 +0800 Subject: [PATCH 075/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5=E5=88=B0?= =?UTF-8?q?=E7=9A=84=E8=AE=A2=E5=8D=95=E7=BB=91=E5=AE=9A=E5=88=B0=E7=9B=AE?= =?UTF-8?q?=E7=9A=84=E5=9C=B0=E8=B4=A6=E6=88=B7:=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E8=B4=A6=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 12 +++++++++-- .../trippestOrderSync/models/orders_model.php | 20 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4ade8e3d..1c6f21a1 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -187,6 +187,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_Memo = ""; $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName'] . "; 团名: " . $vo['agcOrderNo']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; + $this->Orders_model->BIZ_COLI_OPI_ID = 435; $coli_sn[] = $this->Orders_model->biz_confirm_save(); /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; @@ -297,10 +298,12 @@ class TulanduoApi extends CI_Controller /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $order->COLI_SN; $old_memo = mb_strstr($order->COLI_Memo, "orderRemark", true)!==false ? mb_strstr($order->COLI_Memo, "orderRemark", true) : $order->COLI_Memo; + $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; $old_detail = mb_strstr($order->COLI_OrderDetailText, "operations", true)!==false ? mb_strstr($order->COLI_OrderDetailText, "operations", true) : $order->COLI_OrderDetailText; + $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; $coli_update_column = array( - "COLI_Memo" => $old_memo . "orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n" - ,"COLI_OrderDetailText" => $old_detail . "operations\r\n" . $allDetails_to_HT . "\r\n" + "COLI_Memo" => $new_memo + ,"COLI_OrderDetailText" => $new_detail ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update @@ -762,5 +765,10 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $ret===$key; } + public function call_do() + { + $this->Orders_model->test(); + } + } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5e0c6a8d..5c2ed72b 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -542,6 +542,7 @@ class Orders_model extends CI_Model { var $BIZ_COLI_GRI_SN; var $BIZ_COLI_GroupCode=''; var $BIZ_COLI_State; + var $BIZ_COLI_OPI_ID; /** * 商务订单主表入库 @@ -576,6 +577,7 @@ class Orders_model extends CI_Model { . " COLI_OrderSource, \n" . " COLI_Memo, \n" . " COLI_GRI_SN, \n" + . " COLI_OPI_ID, \n" . " COLI_GroupCode, \n" . " COLI_OriginalText \n" . ") \n" @@ -602,6 +604,7 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " ?, \n" + . " ?, \n" . " N?, \n" . " N? \n" . ")"; @@ -629,6 +632,7 @@ class Orders_model extends CI_Model { $this->COLI_OrderSource, $this->BIZ_COLI_Memo, $this->BIZ_COLI_GRI_SN, + $this->BIZ_COLI_OPI_ID, $this->BIZ_COLI_GroupCode, $this->BIZ_COLI_OriginalText )); @@ -1695,5 +1699,21 @@ class Orders_model extends CI_Model { } } + public function test() + { + return NULL; + // 绑定之前同步的为"订单同步账号" + $sql = "UPDATE BIZ_ConfirmLineInfo + SET COLI_OPI_ID=435 + WHERE COLI_SN IN + (SELECT COLI_SN + FROM groupcombineinfo gci + INNER JOIN GRoupInfo gri ON gci.GCI_GRI_SN=gri.GRI_SN + INNER JOIN BIZ_ConfirmLineInfo coli ON GRI_SN=coli.COLI_GRI_SN + AND coli.COLI_OPI_ID IS NULL + )"; + $query = $this->HT->query($sql); + } + } From 5081bf09219bbd9ec313e5efeea7cdac2791718c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 10 May 2018 11:46:40 +0800 Subject: [PATCH 076/382] =?UTF-8?q?trippest=20=E6=8B=BC=E5=9B=A2=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E4=BE=9B=E5=BA=94=E5=95=86=E8=B4=A6=E5=8F=B7=E4=B8=BA?= =?UTF-8?q?null=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/models/orders_model.php | 28 +++++++++++-------- 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5c2ed72b..41f64b11 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -487,14 +487,16 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,GRI_SN + $sql = "SELECT top 1 COLI_SN,GRI_SN,cold.COLD_PlanVEI_SN FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN WHERE gri.GRI_No LIKE '%$code%' and gri.GRI_Name like '%$NoName%' "; $query = $this->HT->query($sql); if ($query->row()) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; $this->GRI_SN = $query->row()->GRI_SN; + $this->COLD_PlanVEI_SN = $query->row()->COLD_PlanVEI_SN; return $query->row(); } return NULL; @@ -1701,17 +1703,19 @@ class Orders_model extends CI_Model { public function test() { - return NULL; - // 绑定之前同步的为"订单同步账号" - $sql = "UPDATE BIZ_ConfirmLineInfo - SET COLI_OPI_ID=435 - WHERE COLI_SN IN - (SELECT COLI_SN - FROM groupcombineinfo gci - INNER JOIN GRoupInfo gri ON gci.GCI_GRI_SN=gri.GRI_SN - INNER JOIN BIZ_ConfirmLineInfo coli ON GRI_SN=coli.COLI_GRI_SN - AND coli.COLI_OPI_ID IS NULL - )"; + // return NULL; + $sql = "UPDATE groupcombineinfo +SET [GCI_VEI_SN]=1343 +WHERE gci_vei_sn IS NULL + AND gci_sn IN + (SELECT gci.[GCI_SN] + FROM groupcombineinfo gci + INNER JOIN GRoupInfo gri ON gci.GCI_GRI_SN=gri.GRI_SN + INNER JOIN BIZ_ConfirmLineInfo coli ON GRI_SN=coli.COLI_GRI_SN +INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=COLI_SN + WHERE 1=1 +AND gci.gci_vei_sn IS NULL + AND COLD_PlanVEI_SN=1343)"; $query = $this->HT->query($sql); } From 685484f82218ab52f3c3fe706eb91fcfa67682cc Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 11 May 2018 15:04:23 +0800 Subject: [PATCH 077/382] =?UTF-8?q?trippest=20=E5=90=84=E6=B8=A0=E9=81=93?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E7=9A=84=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 104 ++++++++++++------ .../trippestOrderSync/models/orders_model.php | 34 +++--- 2 files changed, 88 insertions(+), 50 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 1c6f21a1..d09227a1 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -227,6 +227,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineinfo_save(); } } + log_message('error',"Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . " Insert COLI : " . $cnt); echo "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . "\r\n"; echo "Insert COLI : " . $cnt . "\r\n"; return; @@ -239,6 +240,9 @@ class TulanduoApi extends CI_Controller */ public function insert_HT_order_operation($coli_sn=null) { + // if ($coli_sn == null) { + // return null; + // } log_message('error','get_order_operation From TuLanDuo '); $this->load->model('Order_update'); if ($coli_sn !== null) { @@ -247,11 +251,12 @@ class TulanduoApi extends CI_Controller // $startDate = ('2018-04-21'); // $endDate = ('2018-04-22'); // test $startDate = date('Y-m-d'); - $endDate = date('Y-m-d', strtotime("+4 days")); + $endDate = date('Y-m-d', strtotime("+7 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); } $unique_orderGroupCombine = array(); $unique_order = array(); + $cnt = 0; foreach ($to_update_list as $key => $order) { if (in_array($order->GCI_VendorOrderId, $unique_order)) { continue; @@ -295,43 +300,64 @@ class TulanduoApi extends CI_Controller } /** HT 开始 */ /** UPDATE */ - /** BIZ_ConfirmLineInfo */ - $this->Order_update->coli_where_update = " COLI_SN=" . $order->COLI_SN; - $old_memo = mb_strstr($order->COLI_Memo, "orderRemark", true)!==false ? mb_strstr($order->COLI_Memo, "orderRemark", true) : $order->COLI_Memo; - $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; - $old_detail = mb_strstr($order->COLI_OrderDetailText, "operations", true)!==false ? mb_strstr($order->COLI_OrderDetailText, "operations", true) : $order->COLI_OrderDetailText; - $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; - $coli_update_column = array( - "COLI_Memo" => $new_memo - ,"COLI_OrderDetailText" => $new_detail - ); - $this->Order_update->biz_confirmlineinfo_update($coli_update_column); - /** BIZ_ConfirmLineDetail */ // nothing to update - /** biz_groupcombineinfo */ - $this->Order_update->gci_where_update = " GCI_SN=" . $order->GCI_SN; + $cnt++; $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : $order->COLD_PlanVEI_SN; + $getInfo_byGroupCode = null; + if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { + $real_groupCode = $this->analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); + } + $groupSN = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->GRI_SN : $order->COLI_GRI_SN; + $coli_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_SN : $order->COLI_SN; + $coli_id = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; + $coli_memo = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; + $coli_orderdetailtext = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; + $cold_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; + // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 + if ($getInfo_byGroupCode === null) { + } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { + log_message('error','原订单' . $order->COLI_ID); + $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; + $this->order_cancel($order->COLI_ID); + } + /** biz_groupcombineinfo */ + $this->Order_update->gci_where_update = " GCI_VEI_SN=$vei_SN and GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; $gci_update_column = array( "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null ,"GCI_VEI_SN" => $vei_SN + ,"GCI_GRI_SN" => $groupSN ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate ,"GCI_createTime" => date('Y-m-d H:i:s') ); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); + /** BIZ_ConfirmLineInfo */ + $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn; + $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo; + $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; + $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; + $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; + $coli_update_column = array( + "COLI_Memo" => $new_memo + ,"COLI_OrderDetailText" => $new_detail + ,"COLI_State" => 7 + ); + $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + /** BIZ_ConfirmLineDetail */ // nothing to update /** INSERT */ /*BIZ_BookPeople*/ - if ($this->Orders_model->bookpeople_exist($order->COLD_SN) === array()) { + if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { $this->Orders_model->BPE_FirstName = $vd->name; $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; $this->Orders_model->BPE_Passport = $vd->documentNo; $bpe_sn[] = $this->Orders_model->biz_book_people_save(); // BIZ_BookPeopleList - $this->Orders_model->biz_bookpeople_List_save($order->COLD_SN, $this->Orders_model->BPE_SN); + $this->Orders_model->biz_bookpeople_List_save($cold_sn, $this->Orders_model->BPE_SN); } } /*BIZ_PackageOrderInfo*/ - $this->Orders_model->POI_COLD_SN = $order->COLD_SN; + $this->Orders_model->POI_COLD_SN = $cold_sn; $this->Orders_model->POI_Time = $detail_jsonResp->orderDetail->travelDate; $this->Orders_model->POI_Hotel = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation; $this->Orders_model->POI_HotelAddress = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationAddress; @@ -343,20 +369,24 @@ class TulanduoApi extends CI_Controller // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 $paytype = 15006; // 地接代收 $pay_currency = 'RMB'; + $auto_text = "dataAutoEnter "; // 删除旧的录入 - $this->Orders_model->biz_groupaccountinfo_cut($order->COLI_SN, $paytype); + $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); if (isset($detail_jsonResp->orderDetail->travelFees) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { // if ($vtf->reviewStatus == 0) { // 未审核的 // continue; // } - $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; - $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; - $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Operator = 435; + $this->Orders_model->GAI_COLI_SN = $coli_sn; + $this->Orders_model->GAI_GRI_SN = $groupSN; + $this->Orders_model->GAI_COLI_ID = $coli_id; $this->Orders_model->GAI_Type = $paytype; $this->Orders_model->GAI_SQJE = $vtf->sumMoney; $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_Memo = $vtf->type . ", " . $vtf->remark; + $this->Orders_model->GAI_SSJE = $vtf->sumMoney; + $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); + $this->Orders_model->GAI_Memo = $auto_text . "团款" . $vtf->type . ", " . $vtf->remark; $this->Orders_model->biz_groupaccountinfo_save(); } } @@ -366,13 +396,16 @@ class TulanduoApi extends CI_Controller // if ($vrc->reviewStatus == 0) { // continue; // } - $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; - $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; - $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Operator = 435; + $this->Orders_model->GAI_COLI_SN = $coli_sn; + $this->Orders_model->GAI_GRI_SN = $groupSN; + $this->Orders_model->GAI_COLI_ID = $coli_id; $this->Orders_model->GAI_Type = $paytype; $this->Orders_model->GAI_SQJE = $vrc->money; $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_Memo = $vrc->type . ", " . $vrc->remark; + $this->Orders_model->GAI_SSJE = $vrc->money; + $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); + $this->Orders_model->GAI_Memo = $auto_text . "代收" . $vrc->type . ", " . $vrc->remark; $this->Orders_model->biz_groupaccountinfo_save(); } } @@ -382,13 +415,16 @@ class TulanduoApi extends CI_Controller // if ($vrp->reviewStatus == 0) { // continue; // } - $this->Orders_model->GAI_COLI_SN = $order->COLI_SN; - $this->Orders_model->GAI_GRI_SN = $order->COLI_GRI_SN; - $this->Orders_model->GAI_COLI_ID = $order->COLI_ID; + $this->Orders_model->GAI_Operator = 435; + $this->Orders_model->GAI_COLI_SN = $coli_sn; + $this->Orders_model->GAI_GRI_SN = $groupSN; + $this->Orders_model->GAI_COLI_ID = $coli_id; $this->Orders_model->GAI_Type = $paytype; $this->Orders_model->GAI_SQJE = "-" . $vrp->money; $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_Memo = $vrp->type . ", " . $vrp->remark; + $this->Orders_model->GAI_SSJE = $vrp->money; + $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); + $this->Orders_model->GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; $this->Orders_model->biz_groupaccountinfo_save(); } } @@ -488,7 +524,8 @@ class TulanduoApi extends CI_Controller } } } // end foreach order - echo "Got order from TuLanDuo, count: " . count($to_update_list); + log_message('error',"Got order operations from TuLanDuo, count: " . count($cnt)); + echo "Got order operations from TuLanDuo, count: " . count($cnt); return; } @@ -499,9 +536,10 @@ class TulanduoApi extends CI_Controller */ public function order_cancel($COLI_ID="") { + log_message('error','修改为不成行 order_cancel' . $COLI_ID); /** UPDATE HT */ /** BIZ_ConfirmLineInfo */ - $this->Order_update->coli_where_update = " COLI_ID=" . $COLI_ID; + $this->Order_update->coli_where_update = " COLI_ID='" . $COLI_ID . "'"; $coli_update_column = array( "COLI_State" => 40 ); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 41f64b11..d820499f 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -487,7 +487,7 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,GRI_SN,cold.COLD_PlanVEI_SN + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN @@ -1169,10 +1169,8 @@ class Orders_model extends CI_Model { */ public function biz_groupaccountinfo_cut($coli_sn, $paytype) { - $sql = "UPDATE BIZ_GroupAccountInfo - SET DeleteFlag=1 - WHERE GAI_COLI_SN=? - AND GAI_Type=?"; + $sql = "DELETE from BIZ_GroupAccountInfo + WHERE GAI_COLI_SN=? AND GAI_Type=? AND GAI_Operator = 435"; $query = $this->HT->query($sql, array($coli_sn, $paytype)); return $query; } @@ -1189,6 +1187,9 @@ class Orders_model extends CI_Model { public $GAI_SQJE; public $GAI_SQDate; public $GAI_SQJECurrency; + public $GAI_SSJE; + public $GAI_SSDate; + public $GAI_Operator; public $GAI_Memo=""; public function biz_groupaccountinfo_save() { @@ -1201,6 +1202,9 @@ class Orders_model extends CI_Model { . " GAI_SQJE, \n" . " GAI_SQDate, \n" . " GAI_SQJECurrency, \n" + . " GAI_SSJE, \n" + . " GAI_SSDate, \n" + . " GAI_Operator, \n" . " GAI_Memo \n" . " ) \n" . "VALUES \n" @@ -1212,6 +1216,9 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" . " ? \n" . " )"; $query = $this->HT->query($sql, array( @@ -1222,6 +1229,9 @@ class Orders_model extends CI_Model { ,$this->GAI_SQJE ,$this->GAI_SQDate ,$this->GAI_SQJECurrency + ,$this->GAI_SSJE + ,$this->GAI_SSDate + ,$this->GAI_Operator ,$this->GAI_Memo )); return $query; @@ -1704,18 +1714,8 @@ class Orders_model extends CI_Model { public function test() { // return NULL; - $sql = "UPDATE groupcombineinfo -SET [GCI_VEI_SN]=1343 -WHERE gci_vei_sn IS NULL - AND gci_sn IN - (SELECT gci.[GCI_SN] - FROM groupcombineinfo gci - INNER JOIN GRoupInfo gri ON gci.GCI_GRI_SN=gri.GRI_SN - INNER JOIN BIZ_ConfirmLineInfo coli ON GRI_SN=coli.COLI_GRI_SN -INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=COLI_SN - WHERE 1=1 -AND gci.gci_vei_sn IS NULL - AND COLD_PlanVEI_SN=1343)"; + $sql = " + "; $query = $this->HT->query($sql); } From 7fbfe35f05cd0ff1b6da059fae98372dcb4580cb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 14 May 2018 09:39:41 +0800 Subject: [PATCH 078/382] =?UTF-8?q?trippest=20=E7=9B=AE=E7=9A=84=E5=9C=B0?= =?UTF-8?q?=E6=94=B6=E7=9A=84=E5=8D=95=E7=BA=BF=E4=B8=8D=E5=A4=84=E7=90=86?= =?UTF-8?q?=E5=9B=A2=E6=AC=BE,=20=E9=81=BF=E5=85=8D=E5=92=8C=E5=A4=96?= =?UTF-8?q?=E8=81=94=E9=87=8D=E5=A4=8D=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index d09227a1..4f102250 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -359,7 +359,7 @@ class TulanduoApi extends CI_Controller /*BIZ_PackageOrderInfo*/ $this->Orders_model->POI_COLD_SN = $cold_sn; $this->Orders_model->POI_Time = $detail_jsonResp->orderDetail->travelDate; - $this->Orders_model->POI_Hotel = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation; + $this->Orders_model->POI_Hotel = isset($detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation) ? $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodation : ''; $this->Orders_model->POI_HotelAddress = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationAddress; $this->Orders_model->POI_HotelPhone = $detail_jsonResp->orderDetail->scheduleDetails[0]->accommodationTelNo; $this->Orders_model->POI_EndTime = $detail_jsonResp->orderDetail->leaveDate; @@ -390,8 +390,9 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupaccountinfo_save(); } } + // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. todo // 代收 - if (isset($detail_jsonResp->orderDetail->replaceCollections)) { + if (isset($detail_jsonResp->orderDetail->replaceCollections) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { // if ($vrc->reviewStatus == 0) { // continue; @@ -410,7 +411,7 @@ class TulanduoApi extends CI_Controller } } // 代付 - if (isset($detail_jsonResp->orderDetail->replacePays)) { + if (isset($detail_jsonResp->orderDetail->replacePays) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { // if ($vrp->reviewStatus == 0) { // continue; From d0080c1bb51c471a818bf16f10818c57e61e6c19 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 18 May 2018 11:29:02 +0800 Subject: [PATCH 079/382] =?UTF-8?q?trippest=20=E4=B8=8D=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=8E=9F=E6=9C=89=E7=9A=84=E8=AE=A2=E5=8D=95=E7=8A=B6=E6=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 7 ++++--- .../third_party/trippestOrderSync/models/orders_model.php | 2 +- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4f102250..ed1b4bd3 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -181,7 +181,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); $this->Orders_model->BIZ_COLI_ApplyDate = $vo['orderDate']; $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$vo['operationDep']]) ? 32090 : $this->city_info[$vo['operationDep']]['COLI_sourcetype']; - $this->Orders_model->BIZ_COLI_State = $vo['orderStatus'] == 1 ? 7 : 4; + $this->Orders_model->BIZ_COLI_State = 7; $this->Orders_model->BIZ_COLI_servicetype = 'D'; $this->Orders_model->BIZ_COLI_ConfirmType = 52001; $this->Orders_model->BIZ_COLI_Memo = ""; @@ -312,6 +312,7 @@ class TulanduoApi extends CI_Controller $coli_id = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; $coli_memo = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; $coli_orderdetailtext = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; + $coli_state = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_State : 7; $cold_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { @@ -338,9 +339,9 @@ class TulanduoApi extends CI_Controller $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; $coli_update_column = array( - "COLI_Memo" => $new_memo + "COLI_Memo" => $new_memo ,"COLI_OrderDetailText" => $new_detail - ,"COLI_State" => 7 + ,"COLI_State" => $coli_state ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index d820499f..a527e4f6 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -487,7 +487,7 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN From cde718aa69907befb05fb6de70c325ff1164d7b7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 28 May 2018 14:37:01 +0800 Subject: [PATCH 080/382] =?UTF-8?q?paypal=20=E6=9A=82=E6=97=B6=E6=8E=A5?= =?UTF-8?q?=E6=94=B6trippest=E7=9A=84paypal=20IPN,=20=E7=94=B1=E4=BA=8Etou?= =?UTF-8?q?rMaster=E7=9A=84=E6=8F=92=E4=BB=B6bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 7d1f3d8b..c4365398 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -633,6 +633,10 @@ class Index extends CI_Controller { $ordertype = 'B'; } } + // 2018.05.28 for Trippest, tourMaster的订单号是01开头 + if (substr($note_invoice_string[0], 0, 2) == '01') { + $ordertype = 'TP'; + } //手机订单、机票订单都没有加标示,在这里帮加上,暂时的,今后还是要在网前设置好 if ($ordertype == 'N' && isset($note_invoice_string[0])) { @@ -759,6 +763,12 @@ class Index extends CI_Controller { $orderid_info = json_decode($orderid_info); $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + // for trippest tourMaster 2018.05.28 + if ($orderid_info->ordertype == 'TP') { + $this->trippest_note($orderid_info, $item); + continue; + } + //查不到订单信息 if (empty($advisor_info)) { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); @@ -809,12 +819,14 @@ class Index extends CI_Controller { $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + //没有外联信息表示订单未分配 if (empty($opi_email) || empty($opi_firstname)) { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); continue; } + //添加邮件发送记录 //给外联发送通知邮件 $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; @@ -825,7 +837,7 @@ class Index extends CI_Controller { $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; $M_RelatedInfo = $item->pn_sn; $M_AddTime = $item->pn_payment_date; - $M_State = 0; //设置已经发送,测试专用 + $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); //添加邮件发送记录 end @@ -834,6 +846,25 @@ class Index extends CI_Controller { //echo 'done!'; } + public function trippest_note($orderid_info, $paypal_msg) + { + $opi_firstname = "David"; + $opi_email = "david@trippest.com"; + $orderid_info->orderid = $orderid_info->orderid . "#" . substr($orderid_info->orderid, 10); + + $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; + $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo; + $M_RelatedInfo = $paypal_msg->pn_sn; + $M_AddTime = $paypal_msg->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + $this->Note_model->update_send($paypal_msg->pn_txn_id, 'send'); + } + //所有记录列表 public function note_list() { $data = array(); From ae6069dba1c98473edf4360477cb9245be772ac6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 30 May 2018 11:01:23 +0800 Subject: [PATCH 081/382] =?UTF-8?q?trippest=20=E5=A2=9E=E5=8A=A0=E6=8C=89?= =?UTF-8?q?=E5=87=BA=E5=9B=A2=E6=97=B6=E9=97=B4=E8=8E=B7=E5=8F=96=E5=88=97?= =?UTF-8?q?=E8=A1=A8,=20=E9=81=BF=E5=85=8D=E6=8B=BC=E5=9B=A2=E5=86=85?= =?UTF-8?q?=E9=A2=84=E5=AE=9A=E6=97=B6=E9=97=B4=E5=B7=AE=E5=BE=88=E5=A4=9A?= =?UTF-8?q?=E5=AF=BC=E8=87=B4=E6=BC=8F=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 20 ++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index ed1b4bd3..916796fb 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -76,18 +76,24 @@ class TulanduoApi extends CI_Controller */ public function get_orderlist() { - log_message('error','get_orderlist From TuLanDuo ' ); $startOrderDate = date('Y-m-d', strtotime("-2 days")); $endOrderDate = date('Y-m-d'); + $startTravelDate = date('Y-m-d'); + $endTravelDate = date('Y-m-d', strtotime("+2 days")); $this->tld_order->setUserId($this->userId) ->setKey($this->key) ->setPageSize(20) - ->setPageIndex(1) - // ->setStartTravelDate("2018-04-21") // test - // ->setEndTravelDate("2018-04-21") - ->setStartOrderDate($startOrderDate) - ->setEndOrderDate($endOrderDate) - ; + ->setPageIndex(1) ; + $get_type = rand(0, 1); // 需要按预定时间和出发时间, 避免有漏的 + if ($get_type === 0) { + log_message('error','get_orderlist From TuLanDuo By travel Date' ); + $this->tld_order->setStartTravelDate($startTravelDate) + ->setEndTravelDate($endTravelDate) ; + } else { + log_message('error','get_orderlist From TuLanDuo By order Date' ); + $this->tld_order->setStartOrderDate($startOrderDate) + ->setEndOrderDate($endOrderDate) ; + } $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); if ($resp_arr['status'] !== 1) { From f580801657ee57e167e0b1869a151de5d763128d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 4 Jun 2018 10:22:58 +0800 Subject: [PATCH 082/382] =?UTF-8?q?trippest=20=E5=A2=9E=E5=8A=A0<=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E6=94=AF=E5=87=BA>,<=E5=85=B6=E4=BB=96=E6=94=B6?= =?UTF-8?q?=E5=85=A5>;=20todo:=20=E4=B9=8B=E5=89=8D=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=9A=84=E8=AE=A2=E5=8D=95=E9=9C=80=E8=A6=81=E8=A1=A5=E5=85=A8?= =?UTF-8?q?=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 916796fb..849ab040 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -531,6 +531,48 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineoperationdetail_save(); } } + // 其他支出 + if (isset($detail_jsonResp->orderDetail->operationDetails->otherCosts) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->otherCosts as $voc) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "otherCosts"; + $this->Orders_model->GCOD_subType = $voc->type; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = ""; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $voc->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $voc->remark; + $this->Orders_model->GCOD_useNum = $voc->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } + // 其他收入 + if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "otherReceives"; + $this->Orders_model->GCOD_subType = $vor->type; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = ""; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $vor->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vor->remark; + $this->Orders_model->GCOD_useNum = $vor->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } } // end foreach order log_message('error',"Got order operations from TuLanDuo, count: " . count($cnt)); echo "Got order operations from TuLanDuo, count: " . count($cnt); From 444588878ec7679bbfd5cb8a3d15fa637cca8a1c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 5 Jun 2018 11:10:20 +0800 Subject: [PATCH 083/382] =?UTF-8?q?trippest=20=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E8=AE=A2=E5=8D=95=E4=BF=A1=E6=81=AFAPI?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 79 ++++++++++++++++ .../controllers/detail_for_client.md | 94 +++++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 36 +++++++ 3 files changed, 209 insertions(+) create mode 100644 webht/third_party/trippestOrderSync/controllers/api.php create mode 100644 webht/third_party/trippestOrderSync/controllers/detail_for_client.md diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php new file mode 100644 index 00000000..095062c7 --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -0,0 +1,79 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Api extends CI_Controller { + + public function __construct(){ + parent::__construct(); + $this->load->helper('array'); + $this->load->model('Orders_model'); + mb_regex_encoding("UTF-8"); + } + + public function index() + { + $this->operation_detail(); + } + + public function operation_detail($find=null) + { + ($find===null) ? $find = $this->input->get_post('q') : null; + $order_obj = $this->Orders_model->get_operation_detail_for_client($find); + if ($order_obj['order_info'] == null) { + $order_obj['status'] = 0; + $order_obj['msg'] = "Not Found."; + return $this->output->set_content_type('application/json')->set_output(json_encode($order_obj)); + } + $order_obj['status'] = 1; + $order_obj['msg'] = ""; + // 英文名没有 + if ($order_obj['operator_info']->OPI_FirstName == null + || $order_obj['operator_info']->OPI2_Name == null ) { + $order_obj['operator_info']->OPI_FirstName = $order_obj['operator_info']->OPI2_Name + = ucfirst(strstr($order_obj['operator_info']->OPI_Email, "@", true)); + } + // 领队名字 + $order_obj['order_info']->leader_name = trim($order_obj['order_info']->GUT_FirstName . " " . $order_obj['order_info']->GUT_LastName); + // 团人数 + $order_obj['order_info']->personNum_text = $order_obj['order_info']->COLD_PersonNum + $order_obj['order_info']->COLD_ChildNum; + $order_obj['order_info']->personNum_text .= " (" . $order_obj['order_info']->COLD_PersonNum . " Adult(s)"; + if ($order_obj['order_info']->COLD_ChildNum > 0) { + $order_obj['order_info']->personNum_text .= " " . $order_obj['order_info']->COLD_ChildNum . " Child(ren)"; + } + $order_obj['order_info']->personNum_text .= ")" ; + // 出团时间 + $out_datetime = strtotime($order_obj['order_info']->COLD_StartDate); + $order_obj['order_info']->dateWeek_text = date('D', $out_datetime); + $order_obj['order_info']->dateDay_text = date('d', $out_datetime); + $order_obj['order_info']->dateMonth_text = date('M', $out_datetime); + $order_obj['order_info']->dateYear_text = date('Y', $out_datetime); + // 接送信息 + $order_obj['order_info']->pick_up = ""; + $order_obj['order_info']->drop_off = ""; + if ($order_obj['order_info']->COLD_MemoText != null && json_decode($order_obj['order_info']->COLD_MemoText) != null) { + $decode_MemoText = json_decode($order_obj['order_info']->COLD_MemoText, true); + $order_obj['order_info']->pick_up = $decode_MemoText['Pick up']; + $order_obj['order_info']->drop_off = $decode_MemoText['Drop off']; + } else { + $memo_text_tmp = trim(strstr($order_obj['order_info']->COLD_MemoText, "Pick Up From:")); + $order_obj['order_info']->pick_up = trim(strstr($memo_text_tmp, "Drop Off:", true)); + $order_obj['order_info']->drop_off = trim(strstr($memo_text_tmp, "Drop Off:")); + } + // 司机, 导游 + if ( ! empty($order_obj['operation_info'])) { + foreach ($order_obj['operation_info'] as $key => $value) { + $order_obj['operation_info'][$value->GCOD_operationType] = $value; + } + unset($order_obj['operation_info'][0]); + unset($order_obj['operation_info'][1]); + } + // unset($order_obj['order_info']->COLD_MemoText); + unset($order_obj['order_info']->GUT_FirstName); + unset($order_obj['order_info']->GUT_LastName); + return $this->output->set_content_type('application/json')->set_output(json_encode($order_obj)); + } + +} + +/* End of file api.php */ +/* Location: ./third_party/trippestOrderSync/controllers/api.php */ diff --git a/webht/third_party/trippestOrderSync/controllers/detail_for_client.md b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md new file mode 100644 index 00000000..318f5540 --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md @@ -0,0 +1,94 @@ +## 客人查询目的地订单信息API + +#### POST / GET +> `http://www.mycht.cn/webht.php/apps/trippestOrderSync/Api/operation_detail` + +参数| 类型 | 示例 +--- | --- | --- +q | string | 180601019 + +#### RETURN JSON + +```json +{ + "status": 1, // 查询结果; 1-成功; 0-失败 + "msg": "", // 失败信息: Not Found. + "order_info": { + "GCI_SN": 619, + "GCI_VendorOrderId": "18586", + "GCI_combineNo": "S-2018-06-03[25]", + "COLI_SN": 435010334, + "COLI_ID": "180601019", + "COLD_SN": 450021160, + "COLI_GroupCode": "中华游180603-Micky170713021-CHBJ", // 团号 + "COLI_OPI_ID": 435, + "COLD_ServiceSN": 4243, + "COLD_PersonNum": 1, // 成人数量 + "COLD_ChildNum": 0, // 小孩数量 + "COLD_StartDate": "2018-06-03 00:00:00", // 行程日期 + "PAG2_Name": "One-Day Beijing Highlights Mini Group Tour", // 行程名字 + // 酒店相关 + "POI_Hotel": "北京海航大厦万豪酒店", + "POI_HotelAddress": "No.26 Jia Xiaoyun Road, Chaoyang District, Beijing, China北京 朝阳区 霄云路甲26号 ", + "POI_HotelPhone": "010-59278888", + + "leader_name": "Jorge Latorre Alagon", // 领队 + "personNum_text": "1 (1 Adult(s))", // 人数 输出可读 + // 日期 输出可读 + "dateWeek_text": "Sun", + "dateDay_text": "03", + "dateMonth_text": "Jun", + "dateYear_text": "2018", + "pick_up": "北京海航大厦万豪酒店 Beijing Marriott Hotel Northeast", + "drop_off": "北京海航大厦万豪酒店 Beijing Marriott Hotel Northeast" + }, + "operator_info": { // Travel Advisor 信息 + "OPI_SN": 161, + "OPI_Name": "黄俊峻", + "OPI_FirstName": "Niko", + "OPI_MoveTelephone": "18807734970", + "OPI_Email": "niko@chinahighlights.com", + "OPI2_Name": "Niko Huang" // 英文名 + }, + "operation_info": { + "touristCarOperations": { // 车辆,司机信息 + "GCOD_SN": 127883, + "GCOD_VEI_SN": 1343, + "GCOD_GCI_combineNo": "S-2018-06-03[25]", + "GCOD_operationType": "touristCarOperations", + "GCOD_subType": "7座", // 车辆类型 + "GCOD_title": "上海秦健", // 车队,公司 + "GCOD_dutyName": "Mr Qin 秦师傅", // 司机姓名 + "GCOD_dutyTel": "17765106848", // 司机联系电话 + "GCOD_dutyPhoto": null, // 司机头像 + "GCOD_startDate": "2018-06-03", + "GCOD_endDate": "2018-06-03", + "GCOD_useNum": 1, + "GCOD_sumMoney": "800", + "GCOD_standard": "", + "GCOD_carLicense": "沪AZJ228", // 车辆牌照 + "GCOD_remark": "精品一日游;3人;北京瑞吉酒店/北京海航大厦万豪酒店 ", + "GCOD_creatTime": "2018-06-03 23:59:00" + }, + "guiderOperations": { // 导游信息, 单接送的订单没有这个对象 + "GCOD_SN": 127884, + "GCOD_VEI_SN": 1343, + "GCOD_GCI_combineNo": "S-2018-06-03[25]", + "GCOD_operationType": "guiderOperations", + "GCOD_subType": "", + "GCOD_title": "", + "GCOD_dutyName": "北京张豹勋William", // 导游姓名 + "GCOD_dutyTel": "18810790590", // 导游联系电话 + "GCOD_dutyPhoto": "http://djb3c.ltsoftware...", // 导游头像 + "GCOD_startDate": "2018-06-03", + "GCOD_endDate": "2018-06-03", + "GCOD_useNum": 1, + "GCOD_sumMoney": "300", + "GCOD_standard": "", + "GCOD_carLicense": "", + "GCOD_remark": "", + "GCOD_creatTime": "2018-06-03 23:59:00" + } + } +} +``` diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index a527e4f6..03552b3d 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1237,6 +1237,42 @@ class Orders_model extends CI_Model { return $query; } + function get_operation_detail_for_client($COLI_ID) + { + $ret['order_info'] = NULL; + $order_info_sql = "SELECT TOP 1 + GCI_SN,GCI_VendorOrderId,GCI_combineNo + ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID + ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,cold.COLD_MemoText + ,pag2.PAG2_Name + ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone + ,GUT_FirstName,GUT_LastName + FROM BIZ_ConfirmLineInfo coli + inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN + inner join BIZ_ConfirmLineDetail cold on COLD_COLI_SN=COLI_SN + inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN + inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN + inner join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 + where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' "; + // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + $order_info_query = $this->HT->query($order_info_sql); + if ($order_info_query->num_rows() > 0) { + $ret['order_info'] = $order_info_query->row(); + $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name + from OperatorInfo opi + left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1 + where OPI_SN=" . $ret['order_info']->COLI_OPI_ID; + $ret['operator_info'] = $this->HT->query($operator_sql)->row(); + $operation_sql = "SELECT gcod.* + from GroupCombineOperationDetail gcod + where GCOD_GCI_combineNo=? + and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + $operation_info = $this->HT->query($operation_sql, array($ret['order_info']->GCI_combineNo)); + $ret['operation_info'] = $operation_info->result(); + } + return $ret; + } + function GetNationalityID($nationalityName) { if (!$nationalityName) { return 0; From f2f903fb99675c95080a3a856ce75778c4932690 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 5 Jun 2018 16:59:28 +0800 Subject: [PATCH 084/382] =?UTF-8?q?trippest=20=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E6=8E=A5=E5=8F=A3,=20=E5=9F=9F=E6=9D=83=E9=99=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/api.php | 5 +++++ webht/third_party/trippestOrderSync/models/orders_model.php | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 095062c7..f7992766 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -17,6 +17,11 @@ class Api extends CI_Controller { public function operation_detail($find=null) { + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); ($find===null) ? $find = $this->input->get_post('q') : null; $order_obj = $this->Orders_model->get_operation_detail_for_client($find); if ($order_obj['order_info'] == null) { diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 03552b3d..eab87029 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1253,7 +1253,8 @@ class Orders_model extends CI_Model { inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN inner join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 - where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' "; + where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%'"; // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' $order_info_query = $this->HT->query($order_info_sql); if ($order_info_query->num_rows() > 0) { From cbddbe18918e836daa64a13653a33e7726071ee7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 21 Jun 2018 11:06:44 +0800 Subject: [PATCH 085/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=81=AB=E8=BD=A6?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E8=AE=A2=E5=8D=95=E6=94=B6=E6=AC=BE=E5=90=8E?= =?UTF-8?q?,=20=E8=AE=A2=E5=8D=95=E7=8A=B6=E6=80=81=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E4=B8=BA13-=E6=96=B0=E8=AE=A2=E5=8D=95=E5=B7=B2=E6=94=AF?= =?UTF-8?q?=E4=BB=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 6 ++++++ .../pay/controllers/iPayLinksService.php | 8 ++++++-- webht/third_party/pay/models/Alipay_model.php | 15 +++++++++++++-- webht/third_party/pay/models/IPayLinks_model.php | 4 ++-- webht/third_party/paypal/controllers/index.php | 8 ++++++-- webht/third_party/paypal/models/paypal_model.php | 4 ++-- 6 files changed, 35 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index d04f01b6..72afdff1 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -402,6 +402,12 @@ class AlipayTradeService extends CI_Controller $item->ALI_dealId, $ht_memo ); + if ($advisor_info->COLI_Department == 10) { + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->Alipay_model->update_paymanner($GAI_COLI_SN); + // 把订单状态设置为13-新订单已支付 + $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); + } } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 14ce9fcf..da3f5b65 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -417,8 +417,12 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); + if ($advisor_info->COLI_Department == 10) { + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); + // 把订单状态设置为13-新订单已支付 + $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); + } } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 70510309..64b46a60 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -18,7 +18,7 @@ class Alipay_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -60,7 +60,7 @@ class Alipay_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -288,4 +288,15 @@ class Alipay_model extends CI_Model { } return 0; } + + /*! + * 更新订单主表付款方式,防止没访问thankyou-train.asp + * @author LYT <lyt@hainatravel.com> + */ + public function update_paymanner($COLI_SN, $paymanner = '15015') + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = ? WHERE COLI_SN=? "; + $query = $this->HT->query($sql, array($paymanner, $COLI_SN)); + return $query; + } } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 214407b0..b53568fa 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -18,7 +18,7 @@ class IPayLinks_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -60,7 +60,7 @@ class IPayLinks_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index c4365398..83bf9e3b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -801,8 +801,12 @@ class Index extends CI_Controller { } else { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); + if ($advisor_info->COLI_Department == 10) { + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); + // 把订单状态设置为13-新订单已支付 + $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); + } } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index af3f95b5..09695d8b 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,7 +19,7 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -61,7 +61,7 @@ class Paypal_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); From b6c9cab656d431d89e090afbd3f0c2fff5c454d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 5 Jul 2018 10:27:44 +0800 Subject: [PATCH 086/382] =?UTF-8?q?=E5=95=86=E5=8A=A1=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=BB=E8=A1=A8=E7=9A=84=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 4 ++-- webht/third_party/pay/controllers/iPayLinksService.php | 4 ++-- webht/third_party/paypal/controllers/index.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 72afdff1..f5a38bdc 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -402,9 +402,9 @@ class AlipayTradeService extends CI_Controller $item->ALI_dealId, $ht_memo ); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->Alipay_model->update_paymanner($GAI_COLI_SN); if ($advisor_info->COLI_Department == 10) { - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Alipay_model->update_paymanner($GAI_COLI_SN); // 把订单状态设置为13-新订单已支付 $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); } diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index da3f5b65..7979b89d 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -417,9 +417,9 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); if ($advisor_info->COLI_Department == 10) { - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); // 把订单状态设置为13-新订单已支付 $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 83bf9e3b..fe5f02ee 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -801,9 +801,9 @@ class Index extends CI_Controller { } else { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); if ($advisor_info->COLI_Department == 10) { - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); // 把订单状态设置为13-新订单已支付 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); } From 27bee3fa08bb65c150b9348b59622defa92a6238 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 6 Jul 2018 16:32:45 +0800 Subject: [PATCH 087/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=AE=A2=E4=BA=BA?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E8=AE=A2=E5=8D=95=E6=8E=A5=E5=8F=A3,=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E6=94=AF=E6=8C=81=E8=AE=A2=E5=8D=95=E4=B8=8B?= =?UTF-8?q?=E9=A2=84=E5=AE=9A=E4=BA=86=E5=A4=9A=E4=B8=AA=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?.=20=20=E6=9C=AA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 2 +- .../trippestOrderSync/controllers/api.php | 139 ++++++++++++------ .../trippestOrderSync/models/orders_model.php | 46 ++++-- 3 files changed, 123 insertions(+), 64 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 849ab040..ab00e002 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -256,7 +256,7 @@ class TulanduoApi extends CI_Controller } else { // $startDate = ('2018-04-21'); // $endDate = ('2018-04-22'); // test - $startDate = date('Y-m-d'); + $startDate = date('Y-m-d', strtotime("-3 days")); $endDate = date('Y-m-d', strtotime("+7 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); } diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index f7992766..14a801a5 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -23,59 +23,104 @@ class Api extends CI_Controller { header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); header('Access-Control-Allow-Credentials:true'); ($find===null) ? $find = $this->input->get_post('q') : null; - $order_obj = $this->Orders_model->get_operation_detail_for_client($find); - if ($order_obj['order_info'] == null) { - $order_obj['status'] = 0; - $order_obj['msg'] = "Not Found."; - return $this->output->set_content_type('application/json')->set_output(json_encode($order_obj)); - } - $order_obj['status'] = 1; - $order_obj['msg'] = ""; - // 英文名没有 - if ($order_obj['operator_info']->OPI_FirstName == null - || $order_obj['operator_info']->OPI2_Name == null ) { - $order_obj['operator_info']->OPI_FirstName = $order_obj['operator_info']->OPI2_Name - = ucfirst(strstr($order_obj['operator_info']->OPI_Email, "@", true)); + $order_project = $this->Orders_model->get_package_order($find); + if ($order_project == null) { + $ret['status'] = 0; + $ret['msg'] = "Not Found."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } + $ret['status'] = 1; + $ret['msg'] = ""; + $ret['group_number'] = $order_project[0]->COLI_GroupCode; // 领队名字 - $order_obj['order_info']->leader_name = trim($order_obj['order_info']->GUT_FirstName . " " . $order_obj['order_info']->GUT_LastName); - // 团人数 - $order_obj['order_info']->personNum_text = $order_obj['order_info']->COLD_PersonNum + $order_obj['order_info']->COLD_ChildNum; - $order_obj['order_info']->personNum_text .= " (" . $order_obj['order_info']->COLD_PersonNum . " Adult(s)"; - if ($order_obj['order_info']->COLD_ChildNum > 0) { - $order_obj['order_info']->personNum_text .= " " . $order_obj['order_info']->COLD_ChildNum . " Child(ren)"; - } - $order_obj['order_info']->personNum_text .= ")" ; - // 出团时间 - $out_datetime = strtotime($order_obj['order_info']->COLD_StartDate); - $order_obj['order_info']->dateWeek_text = date('D', $out_datetime); - $order_obj['order_info']->dateDay_text = date('d', $out_datetime); - $order_obj['order_info']->dateMonth_text = date('M', $out_datetime); - $order_obj['order_info']->dateYear_text = date('Y', $out_datetime); - // 接送信息 - $order_obj['order_info']->pick_up = ""; - $order_obj['order_info']->drop_off = ""; - if ($order_obj['order_info']->COLD_MemoText != null && json_decode($order_obj['order_info']->COLD_MemoText) != null) { - $decode_MemoText = json_decode($order_obj['order_info']->COLD_MemoText, true); - $order_obj['order_info']->pick_up = $decode_MemoText['Pick up']; - $order_obj['order_info']->drop_off = $decode_MemoText['Drop off']; - } else { - $memo_text_tmp = trim(strstr($order_obj['order_info']->COLD_MemoText, "Pick Up From:")); - $order_obj['order_info']->pick_up = trim(strstr($memo_text_tmp, "Drop Off:", true)); - $order_obj['order_info']->drop_off = trim(strstr($memo_text_tmp, "Drop Off:")); + $ret['leader_name'] = trim($order_project[0]->GUT_FirstName . " " . $order_project[0]->GUT_LastName); + $ret['package'] = null; + foreach ($order_project as $kd => $poi) { + $tmp = array(); + // 行程人数 + $tmp['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; + $tmp['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; + if ($poi->COLD_ChildNum > 0) { + $tmp['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; + } + $tmp['personNum_text'] .= ")" ; + // 人数 + $tmp['adult_number'] = $order_project[0]->COLD_PersonNum; + $tmp['kid_number'] = $order_project[0]->COLD_ChildNum; + // 出团时间 + $tmp['start_date'] = $poi->COLD_StartDate; + $tmp['end_date'] = $poi->COLD_EndDate; + $tmp['tour_name'] = $poi->PAG2_Name; + $out_datetime = strtotime($poi->COLD_StartDate); + $tmp['dateWeek_text'] = date('D', $out_datetime); + $tmp['dateDay_text'] = date('d', $out_datetime); + $tmp['dateMonth_text'] = date('M', $out_datetime); + $tmp['dateYear_text'] = date('Y', $out_datetime); + // 接送信息 + $tmp['pick_up'] = ""; + $tmp['drop_off'] = ""; + $decode_MemoText = $memo_text_tmp = ""; + if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { + $decode_MemoText = json_decode($poi->COLD_MemoText, true); + $tmp['pick_up'] = $decode_MemoText['Pick up']; + $tmp['drop_off'] = $decode_MemoText['Drop off']; + } else { + $memo_text_tmp = trim(strstr($poi->COLD_MemoText, "Pick Up From:")); + $tmp['pick_up'] = trim(strstr($memo_text_tmp, "Drop Off:", true)); + $tmp['drop_off'] = trim(strstr($memo_text_tmp, "Drop Off:")); + } + // 酒店 + $tmp['hotel_name'] = $poi->POI_Hotel; + $tmp['hotel_address'] = $poi->POI_HotelAddress; + $tmp['hotel_tel'] = $poi->POI_HotelPhone; + // 航班/车次 + $tmp['flights_no'] = $poi->POI_FlightsNo; + $tmp['flights_airport'] = $poi->POI_AirPort; + + $ret['package'][] = $tmp; } +log_message('error',$order_project[0]->GCI_combineNo); + $operation = $this->Orders_model->get_operation($order_project[0]->GCI_combineNo); // 司机, 导游 - if ( ! empty($order_obj['operation_info'])) { - foreach ($order_obj['operation_info'] as $key => $value) { - $order_obj['operation_info'][$value->GCOD_operationType] = $value; + if ( ! empty($operation)) { + foreach ($operation as $key => $value) { + if ($value->GCOD_operationType === 'touristCarOperations') { + $tmp_car = array(); + $tmp_car['car_type'] = $value->GCOD_subType; + $tmp_car['car_company'] = $value->GCOD_title; + $tmp_car['car_license'] = $value->GCOD_carLicense; + $tmp_car['driver_name'] = $value->GCOD_dutyName; + $tmp_car['driver_tel'] = $value->GCOD_dutyTel; + $tmp_car['driver_pic'] = $value->GCOD_dutyPhoto; + $tmp_car['car_remark'] = $value->GCOD_remark; + $tmp_car['using_startdate'] = $value->GCOD_startDate; + $tmp_car['using_enddate'] = $value->GCOD_endDate; + $ret['cardriver'][] = $tmp_car; + } + else if ($value->GCOD_operationType === 'guiderOperations') { + $tmp_g = array(); + $tmp_g['guide_name'] = $value->GCOD_dutyName; + $tmp_g['guide_tel'] = $value->GCOD_dutyTel; + $tmp_g['guide_pic'] = $value->GCOD_dutyPhoto; + $tmp_g['guide_remark'] = $value->GCOD_remark; + $tmp_g['using_startdate'] = $value->GCOD_startDate; + $tmp_g['using_enddate'] = $value->GCOD_endDate; + $ret['tourguide'][] = $tmp_g; + } + } + } + $operator = $this->Orders_model->get_operator($order_project[0]->COLI_OPI_ID); + if ( ! empty($operator)) { + $ret['operator']['chinese_name'] = $operator->OPI_Name; + $ret['operator']['mobile'] = $operator->OPI_MoveTelephone; + $ret['operator']['email'] = $operator->OPI_Email; + $ret['operator']['english_name'] = $operator->OPI2_Name; + // 英文名没有 + if ($operator->OPI_FirstName == null || $operator->OPI2_Name == null ) { + $ret['operator']['english_name'] = ucfirst(strstr($operator->OPI_Email, "@", true)); } - unset($order_obj['operation_info'][0]); - unset($order_obj['operation_info'][1]); } - // unset($order_obj['order_info']->COLD_MemoText); - unset($order_obj['order_info']->GUT_FirstName); - unset($order_obj['order_info']->GUT_LastName); - return $this->output->set_content_type('application/json')->set_output(json_encode($order_obj)); + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index eab87029..d14b0929 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1237,15 +1237,15 @@ class Orders_model extends CI_Model { return $query; } - function get_operation_detail_for_client($COLI_ID) + function get_package_order($COLI_ID) { - $ret['order_info'] = NULL; - $order_info_sql = "SELECT TOP 1 + $order_info_sql = "SELECT GCI_SN,GCI_VendorOrderId,GCI_combineNo ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID - ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,cold.COLD_MemoText + ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText ,pag2.PAG2_Name ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone + ,poi.POI_AirPort,poi.POI_FlightsNo ,GUT_FirstName,GUT_LastName FROM BIZ_ConfirmLineInfo coli inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN @@ -1257,23 +1257,37 @@ class Orders_model extends CI_Model { OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%'"; // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' $order_info_query = $this->HT->query($order_info_sql); + $ret = $order_info_query->result(); if ($order_info_query->num_rows() > 0) { - $ret['order_info'] = $order_info_query->row(); - $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name - from OperatorInfo opi - left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1 - where OPI_SN=" . $ret['order_info']->COLI_OPI_ID; - $ret['operator_info'] = $this->HT->query($operator_sql)->row(); - $operation_sql = "SELECT gcod.* - from GroupCombineOperationDetail gcod - where GCOD_GCI_combineNo=? - and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; - $operation_info = $this->HT->query($operation_sql, array($ret['order_info']->GCI_combineNo)); - $ret['operation_info'] = $operation_info->result(); + // $operation_sql = "SELECT gcod.* + // from GroupCombineOperationDetail gcod + // where GCOD_GCI_combineNo=? + // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); + // $ret['operation_info'] = $operation_info->result(); } return $ret; } + function get_operator($OPI_SN) + { + $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name + from OperatorInfo opi + left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1 + where OPI_SN=" . $OPI_SN . " AND OPI_SN<>435"; + return $this->HT->query($operator_sql)->row(); + } + + function get_operation($combineNo) + { + $operation_sql = "SELECT gcod.* + from GroupCombineOperationDetail gcod + where GCOD_GCI_combineNo=? + and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + $operation_info = $this->HT->query($operation_sql, array($combineNo)); + return $operation_info->result(); + } + function GetNationalityID($nationalityName) { if (!$nationalityName) { return 0; From 8f349c7183c9ce1c30279379fe7a6cb791ae0cd0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 9 Jul 2018 10:43:57 +0800 Subject: [PATCH 088/382] =?UTF-8?q?paypal=20=E6=96=B0=E7=89=88=E6=9C=AC?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E4=BF=A1=E6=81=AF=E7=9A=84=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E5=AD=97=E6=AE=B5=E5=9C=A8transaction=5Fsubject?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index fe5f02ee..3aab75e2 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -556,7 +556,7 @@ class Index extends CI_Controller { $pn_txn_id = $this->input->post('txn_id'); $pn_invoice = $this->input->post('invoice'); - empty($pn_invoice) ? $pn_invoice = '' : false; + empty($pn_invoice) ? $pn_invoice = $this->input->post('transaction_subject') : false; $pn_custom = $this->input->post('custom'); empty($pn_custom) ? $pn_custom = '' : false; From ddf9c709c656ebaf64f9a9ec306d62c7d22bbff6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 12 Jul 2018 09:12:52 +0800 Subject: [PATCH 089/382] =?UTF-8?q?COLD=E5=92=8CGCI=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E4=B8=8D=E4=B8=80=E8=87=B4=E7=9A=84=E6=83=85=E5=86=B5?= =?UTF-8?q?,=E6=9B=B4=E6=96=B0=E4=BB=85=E5=8C=B9=E9=85=8DVendorOrderId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index ab00e002..4ee412a2 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -223,7 +223,7 @@ class TulanduoApi extends CI_Controller /*biz_groupcombineinfo*/ $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; $this->Orders_model->GCI_GRI_SN = $this->Orders_model->GRI_SN; - $this->Orders_model->GCI_VEI_SN = $this->Orders_model->COLD_PlanVEI_SN; + $this->Orders_model->GCI_VEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; $this->Orders_model->GCI_FromAgc = $vo['agcName']; $this->Orders_model->GCI_groupType = $vo['orderType']; @@ -328,7 +328,8 @@ class TulanduoApi extends CI_Controller $this->order_cancel($order->COLI_ID); } /** biz_groupcombineinfo */ - $this->Order_update->gci_where_update = " GCI_VEI_SN=$vei_SN and GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; + // $this->Order_update->gci_where_update = " GCI_VEI_SN=$vei_SN and GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; + $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; $gci_update_column = array( "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null ,"GCI_VEI_SN" => $vei_SN From cec778e335c06fe084b09777a041718dd4bd7915 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 12 Jul 2018 09:19:19 +0800 Subject: [PATCH 090/382] =?UTF-8?q?paypal=20=E5=A2=9E=E5=8A=A0=E5=86=99?= =?UTF-8?q?=E5=85=A5=E4=BB=98=E6=AC=BE=E4=BA=BA=E5=90=8D=E5=AD=97=E5=88=B0?= =?UTF-8?q?HT?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 3aab75e2..4cfb5f40 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -557,6 +557,7 @@ class Index extends CI_Controller { $pn_invoice = $this->input->post('invoice'); empty($pn_invoice) ? $pn_invoice = $this->input->post('transaction_subject') : false; + empty($pn_invoice) ? $pn_invoice = '' : false; $pn_custom = $this->input->post('custom'); empty($pn_custom) ? $pn_custom = '' : false; @@ -814,7 +815,7 @@ class Index extends CI_Controller { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); - $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); } From 3906f1636b84ff095a0800e1fa876635408d4665 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 12 Jul 2018 17:41:27 +0800 Subject: [PATCH 091/382] =?UTF-8?q?memo=20=E9=99=90=E5=88=B6400=E5=AD=97?= =?UTF-8?q?=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4ee412a2..4cff577f 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -346,7 +346,7 @@ class TulanduoApi extends CI_Controller $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; $coli_update_column = array( - "COLI_Memo" => $new_memo + "COLI_Memo" => substr($new_memo, 0, 400) ,"COLI_OrderDetailText" => $new_detail ,"COLI_State" => $coli_state ); From decdd795b242e7ab09b41d1b4743c7657444783a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sun, 15 Jul 2018 12:05:11 +0800 Subject: [PATCH 092/382] =?UTF-8?q?ipaylinks=20=E6=9F=A5=E8=AF=A2=E6=9C=AA?= =?UTF-8?q?=E5=85=A5=E5=BA=93=E7=9A=84=E8=AE=A2=E5=8D=95=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 1 - .../pay/controllers/iPayLinksService.php | 34 +++++++++++-------- .../pay/models/IPayLinks_model.php | 2 +- .../pay/views/alipay_note_setting.php | 2 +- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index f5a38bdc..78cc680b 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -369,7 +369,6 @@ class AlipayTradeService extends CI_Controller $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); continue; } - //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 7979b89d..b29d61d9 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -257,18 +257,24 @@ class IPayLinksService extends CI_Controller return; } - public function query_pay($orderid,$day_offset = 3) + public function query_pay($day_offset = 3, $orderid=NULL) { $this->query_info_arr["queryOrderId"] = $this->create_guid(); $this->query_info_arr["orderId"] = $orderid; $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); - $this->query_info_arr["mode"] = 1; + $this->query_info_arr["mode"] = 2; $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); - // echo $resp; - var_export($resp); + $resp_obj = simplexml_load_string($resp); + foreach ($resp_obj->details->detail as $key => $query_order) { + $order = new stdClass(); + $order->check = true; + $order->data = $query_order; + $this->ipaylinks_notice($order); + } + // $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); return; } @@ -335,7 +341,7 @@ class IPayLinksService extends CI_Controller foreach ($data['unsend_list'] as $item) { //已经发送的不处理,防止重复发送 - if ($item->IPL_sent == 'send') { + if ($item->IPL_sent == 'send' && empty($pn_txn_id)) { continue; } @@ -346,7 +352,7 @@ class IPayLinksService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->IPL_resultCode), "0000")) { + if (strcmp(trim($item->IPL_resultCode), "0000") && empty($pn_txn_id)) { $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } @@ -384,7 +390,6 @@ class IPayLinksService extends CI_Controller $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } - //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { @@ -417,12 +422,14 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); - // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); if ($advisor_info->COLI_Department == 10) { // 把订单状态设置为13-新订单已支付 $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); } + // 更新订单主表付款方式,防止没访问thankyou-train.asp + if (empty($advisor_info->COLI_PayManner)) { + $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); + } } } //更新还没有填的客邮和交易号de收款记录(传统订单) @@ -476,9 +483,8 @@ class IPayLinksService extends CI_Controller $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights'; // lang $remark_info = json_decode($item->IPL_memo); - $remark_info = json_decode($remark_info->remark); - $ln = $remark_info->ln; - $ln = $ln ? $ln : "en"; + (isset($remark_info->remark)) ? $remark_info = json_decode($remark_info->remark) : NULL; + $ln = (isset($remark_info->ln)) ? $remark_info->ln : "en"; $this->lang->load('ipl_common',$ln); $this->lang->load('ipl_buyer_email',$ln); $item->text = $this->lang->language; @@ -597,12 +603,12 @@ class IPayLinksService extends CI_Controller public function ipaylinks_notice($resp=NULL) { if ($resp !== NULL) { - $resp_arr = $resp; + $asyns_resp = $resp_arr = $resp; } else { $resp_arr = $this->input->post(); log_message('error','iPayLinks asyn notify: ' . $this->input->post("orderId")); + $asyns_resp = $this->verify_sign($resp_arr); } - $asyns_resp = $this->verify_sign($resp_arr); // 未得到结果 if (empty($asyns_resp->data->orderId)) { echo "200"; diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index b53568fa..49c3be6d 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -18,7 +18,7 @@ class IPayLinks_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); diff --git a/webht/third_party/pay/views/alipay_note_setting.php b/webht/third_party/pay/views/alipay_note_setting.php index 90332bba..e1bcc4bb 100644 --- a/webht/third_party/pay/views/alipay_note_setting.php +++ b/webht/third_party/pay/views/alipay_note_setting.php @@ -1,4 +1,4 @@ -<form action="http://www.mycht.cn/webht.php/apps/pay/iPayLinksService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> +<form action="http://www.mycht.cn/webht.php/apps/pay/AlipayTradeService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> <dl class="dl-horizontal"> <dt>交易号</dt> From 4fc71a482758ccbce123ea0f573bbc442bb7b89d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sun, 15 Jul 2018 13:15:00 +0800 Subject: [PATCH 093/382] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=95=86=E6=97=85?= =?UTF-8?q?=E7=9A=84=E4=B8=BB=E8=A1=A8=E4=BB=98=E6=AC=BE=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 4 +++- webht/third_party/pay/models/Alipay_model.php | 2 +- webht/third_party/paypal/models/paypal_model.php | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 78cc680b..e0cd7ccf 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -402,7 +402,9 @@ class AlipayTradeService extends CI_Controller $ht_memo ); // 更新订单主表付款方式,防止没访问thankyou-train.asp - $this->Alipay_model->update_paymanner($GAI_COLI_SN); + if (empty($advisor_info->COLI_PayManner)) { + $this->Alipay_model->update_paymanner($GAI_COLI_SN); + } if ($advisor_info->COLI_Department == 10) { // 把订单状态设置为13-新订单已支付 $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 64b46a60..97600764 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -18,7 +18,7 @@ class Alipay_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 09695d8b..73101e6a 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,7 +19,7 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); From 66b199af39e83fa10e6d4a4a7ae2787b939f855c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 17 Jul 2018 10:04:49 +0800 Subject: [PATCH 094/382] =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E5=88=97=E8=A1=A8,=20=E5=BD=95=E5=85=A5=E6=9C=AA=E6=8E=A5?= =?UTF-8?q?=E6=94=B6=E7=9A=84=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index b29d61d9..d8820bc3 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -341,7 +341,7 @@ class IPayLinksService extends CI_Controller foreach ($data['unsend_list'] as $item) { //已经发送的不处理,防止重复发送 - if ($item->IPL_sent == 'send' && empty($pn_txn_id)) { + if ($item->IPL_sent == 'send') { continue; } @@ -352,8 +352,8 @@ class IPayLinksService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->IPL_resultCode), "0000") && empty($pn_txn_id)) { - $this->Note_model->update_send($item->IPL_dealId, 'send'); + if (strcmp(trim($item->IPL_resultCode), "0000") !== 0 && strcmp(trim($item->IPL_stateCode), "2") !== 0) { + $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); continue; } @@ -637,7 +637,7 @@ class IPayLinksService extends CI_Controller ,strval($asyns_resp->data->currencyCode) ,strval(bcdiv(floatval($asyns_resp->data->orderAmount), 100)) ,NULL - ,NULL + ,isset($asyns_resp->data->stateCode) ? $asyns_resp->data->stateCode : NULL ,strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->acquiringTime))) ,strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->completeTime))) ,json_encode($asyns_resp->data) From ae36fe72e94e0ff39f3d432c2edfa70294d4aeb6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 18 Jul 2018 10:50:25 +0800 Subject: [PATCH 095/382] =?UTF-8?q?=E7=9B=AE=E7=9A=84=E5=9C=B0=E5=8D=95?= =?UTF-8?q?=E5=9B=A2=E8=B4=A2=E5=8A=A1=E8=A1=A8=E7=9A=84=E8=AE=A1=E7=AE=97?= =?UTF-8?q?,=20=E7=9B=B8=E5=90=8C=E4=BA=A7=E5=93=81=E7=BC=96=E5=8F=B7,=20?= =?UTF-8?q?=E5=85=81=E8=AE=B8=E6=8B=BC=E5=9B=A2=E4=BA=A7=E5=93=81=E7=BC=96?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 88 +++++++++++++++++++ .../models/orderFinance_model.php | 11 +++ 2 files changed, 99 insertions(+) create mode 100644 webht/third_party/trippestOrderSync/controllers/order_finance.php create mode 100644 webht/third_party/trippestOrderSync/models/orderFinance_model.php diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php new file mode 100644 index 00000000..41d20332 --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -0,0 +1,88 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Order_finance extends CI_Controller { + + public function index() + { + + } + + /*! + * 单团财务表计算 + * @date 2018-07-18 + * @param integer $coli_sn 订单主表key + * @return [type] [description] + */ + public function single_order_report($coli_sn=0) + { + + } + + /*! + * 最基本的订单 + * * 仅含有一个产品 + * @example 180712534 + * @date 2018-07-18 + * @param integer $coli_sn 订单主表key + * @return [type] [description] + */ + public function basic($coli_sn=0) + { + # code... + } + + /*! + * 获取相同的产品编号 + * @date 2018-07-18 + * @param string $tour_code 产品编号 + * @return array 含相同产品的数组 + */ + public function get_equaltour($tour_code="") + { + $equal_tour = null; + $all_equals = $this->equal_tours(); + foreach ($all_equals as $key => $equal) { + if (in_array($tour_code, $equal)) { + $equal_tour = $equal; + break; + } + } + return $equal_tour; + } + /** 产品编号不同实际是同一产品 */ + public function equal_tours() + { + return array( + array("SHSIC-31", "SHSIC-41"), + array("SHSIC-32", "SHSIC-42"), + array("SHSIC-33", "SHSIC-43"), + array("SHSIC-34", "SHSIC-44") + ); + } + + public function get_allowed_combine($tour_code="") + { + $allowed = null; + $all_allowed = $this->allowed_combine(); + foreach ($all_allowed as $key => $va) { + if (in_array($tour_code, $va)) { + $allowed = $va; + break; + } + } + return $allowed; + } + /** 不同产品但部分行程相同所以允许拼团 */ + public function allowed_combine() + { + return array( + array("XASIC-15", "XASIC-41"), + array("BJSIC-47", "BJSIC-41") + ); + } + +} + +/* End of file order_finance.php */ +/* Location: ./webht/third_party/trippestOrderSync/controllers/order_finance.php */ diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php new file mode 100644 index 00000000..ee63d527 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -0,0 +1,11 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class OrderFinance_model extends CI_Model { + + + +} + +/* End of file orderFinance_model.php */ +/* Location: ./webht/third_party/trippestOrderSync/models/orderFinance_model.php */ From dff41407cebbf89ed5d8623354c60f69363d3dbe Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 19 Jul 2018 09:45:20 +0800 Subject: [PATCH 096/382] =?UTF-8?q?PVT=E6=88=90=E6=9C=AC=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 116 +++++++++++++----- .../models/orderFinance_model.php | 84 +++++++++++++ 2 files changed, 170 insertions(+), 30 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 41d20332..5ba0bd0d 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -3,6 +3,29 @@ defined('BASEPATH') OR exit('No direct script access allowed'); class Order_finance extends CI_Controller { + /*! + * 基本流程 + * * 获取拼团类别: PVT? + * * 获取拼团总人数, 价格人等 + * * 分别计算每次拼团成本 + * * * 写入report_tour + * * 所有产品总成本 + * * * 写入report_order + * END + */ + /*! + * GCI_groupType + * 1 - PVT + * 2 - combine + */ + + public function __construct(){ + parent::__construct(); + $this->load->helper('array'); + $this->load->model('OrderFinance_model'); + mb_regex_encoding("UTF-8"); + } + public function index() { @@ -12,55 +35,82 @@ class Order_finance extends CI_Controller { * 单团财务表计算 * @date 2018-07-18 * @param integer $coli_sn 订单主表key - * @return [type] [description] + * @return [type] [description] */ public function single_order_report($coli_sn=0) { - + $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); + $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); + // $this->output->set_content_type('application/json')->set_output(json_encode($combineNo_arr)); + // $this->output->set_content_type('application/json')->set_output(json_encode($group_type_arr)); + foreach ($combineNo_arr as $kc => $vc) { + if ($vc->GCI_groupType == 1) { + $pvt_cost = $this->pvt_basic($vc->GCI_combineNo); + } else if ($vc->GCI_groupType == 2) { + $combine_cost = $this->combine_basic($vc->GCI_combineNo); + } + } + return; } /*! - * 最基本的订单 + * 基本拼团 * * 仅含有一个产品 * @example 180712534 * @date 2018-07-18 - * @param integer $coli_sn 订单主表key - * @return [type] [description] + * @param string $combineNo + * @return [type] [description] */ - public function basic($coli_sn=0) + public function combine_basic($combineNo="") { # code... } /*! - * 获取相同的产品编号 + * pvt计算 + * @example 180515061M * @date 2018-07-18 - * @param string $tour_code 产品编号 - * @return array 含相同产品的数组 */ - public function get_equaltour($tour_code="") + public function pvt_basic($combineNo="", $coli_sn=0) { - $equal_tour = null; - $all_equals = $this->equal_tours(); - foreach ($all_equals as $key => $equal) { - if (in_array($tour_code, $equal)) { - $equal_tour = $equal; - break; - } + $ret = new stdClass(); + $ret->tour = array(); + $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo); + if (empty($all_orders)) { + return null; } - return $equal_tour; - } - /** 产品编号不同实际是同一产品 */ - public function equal_tours() - { - return array( - array("SHSIC-31", "SHSIC-41"), - array("SHSIC-32", "SHSIC-42"), - array("SHSIC-33", "SHSIC-43"), - array("SHSIC-34", "SHSIC-44") - ); + // 预定的产品数 + $ret->tour_count = count(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $all_orders))); + $ret->person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); + bcscale(2); + $tour_s = new stdClass(); + $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); + $tour_s->startdate = $all_orders[0]->COLD_StartDate; + // $tour_s->person_grade = ($all_orders[0]->COLD_PersonNum + $all_orders[0]->COLD_ChildNum ); + $tour_s->cost_category = $combine_cost->cost_category; + $tour_s->cost_sum = $combine_cost->cost_sum; + $tour_s->person_cost = bcdiv($tour_s->cost_sum, $ret->person_num); + $tour_s->comment = "按PVT,共" . $ret->person_num . "人";// 150 + $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); + $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); + $tour_s->PAG_Code = substr(implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))), 0, 50) ; // TODO 限制50 + $tour_s->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 + $tour_s->pag_name = substr(implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)), 0, 200) ; // TODO 限制200 + $ret->tour[0] = $tour_s; + if ( $ret->tour_count > 1 ) { + } else { + } + $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); + $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + return; } + /*! + * 获取允许拼团的数组 + * @date 2018-07-18 + * @param string $tour_code 产品编号 + * @return array 含允许拼团产品编号的数组 + */ public function get_allowed_combine($tour_code="") { $allowed = null; @@ -73,12 +123,18 @@ class Order_finance extends CI_Controller { } return $allowed; } - /** 不同产品但部分行程相同所以允许拼团 */ + /** 允许拼团的不同编号产品 */ public function allowed_combine() { return array( + // * 不同产品但部分行程相同所以允许拼团 * array("XASIC-15", "XASIC-41"), - array("BJSIC-47", "BJSIC-41") + array("BJSIC-47", "BJSIC-41"), + // * 产品编号不同实际是同一产品 * + array("SHSIC-31", "SHSIC-41"), + array("SHSIC-32", "SHSIC-42"), + array("SHSIC-33", "SHSIC-43"), + array("SHSIC-34", "SHSIC-44") ); } diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index ee63d527..b2bba4a7 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -2,8 +2,92 @@ defined('BASEPATH') OR exit('No direct script access allowed'); class OrderFinance_model extends CI_Model { + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + /** 订单的所有拼团号 */ + public function get_order_combineNo($coli_sn=0) + { + $sql = "SELECT gci.GCI_combineNo,gci.GCI_groupType + from GroupCombineInfo gci + inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN + where coli.COLI_SN=$coli_sn + group by gci.GCI_combineNo,gci.GCI_groupType"; + return $this->HT->query($sql)->result(); + } + /** 拼团号下的所有订单 */ + public function get_all_combine_order($combineNo="") + { + $sql = "SELECT gci.GCI_combineNo,gci.GCI_VendorOrderId + ,COLI_SN,coli_ID--,COLI_ApplyDate,COLI_GroupCode + ,COLD_SN,cold.COLD_ServiceSN--,COLD_EndDate + ,PAG_Code ,pag_sub.PAGS_CN_Title, cold.COLD_StartDate,PAG_DefaultVEI_SN + ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate + --,PAG_Title + from GroupCombineInfo gci + inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN + left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN + left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2 + where gci.GCI_combineNo =? + order by GCI_combineNo,cold.COLD_StartDate"; + return $this->HT->query($sql, array($combineNo))->result(); + } + + /** 拼团的成本明细,总成本信息 */ + public function get_combine_sumMoney($combineNo="") + { + $ret = new stdClass(); + $sql = "SELECT GCOD_operationType,GCOD_subType,SUM(cast(gcod.GCOD_sumMoney as float)) cost + from GroupCombineOperationDetail gcod + where gcod.GCOD_GCI_combineNo =? + group by GCOD_GCI_combineNo,GCOD_operationType,GCOD_subType"; + $ret->cost_detail = $this->HT->query($sql, array($combineNo))->result(); + $ret->cost_sum = array_sum(array_map(function ($ele){return $ele->cost;}, $ret->cost_detail)); + + $ret->cost_category = array(); + $ret->cost_category['water'] = 0; + $ret->cost_category['guide_meal'] = 0; + $ret->cost_category['otherCosts'] = 0; + $ret->cost_category['guiderOperations'] = 0; + $ret->cost_category['touristCarOperations'] = 0; + $ret->cost_category['sceneryOperations'] = 0; + foreach ($ret->cost_detail as $key => $value) { + if ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='客人水费') { + $ret->cost_category['water'] += $value->cost; + continue; + } elseif ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='餐补(司陪)') { + $ret->cost_category['guide_meal'] += $value->cost; + continue; + } + $ret->cost_category[$value->GCOD_operationType] += $value->cost; + } + return $ret; + } + + /** 获取订单总人数 */ + public function get_order_person_num($coli_sn=0) + { + $sql = "SELECT BPL_BPE_SN + from BIZ_ConfirmLineDetail cold + inner join BIZ_BookPeopleList bpl on bpl.BPL_COLD_SN=cold.COLD_SN + where cold.COLD_COLI_SN=$coli_sn + group by bpl.BPL_BPE_SN"; + return $this->HT->query($sql)->num_rows(); + } + + /** 获取产品信息:产品名称,供应商等 */ + public function get_pag_info($PAG_SN_str="") + { + $sql = "SELECT pag.PAG_SN,PAG_Code,PAG_DefaultVEI_SN,PAG_Title,vei2.VEI2_CompanyBN + from BIZ_PackageInfo pag + inner join VEndorInfo2 vei2 on VEI2_VEI_SN=PAG_DefaultVEI_SN and VEI2_LGC=2 + where PAG_SN in ($PAG_SN_str) "; + return $this->HT->query($sql)->result(); + } } From 3d515c05325e1d76f0a22407e9771e5269bc7c1f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 19 Jul 2018 10:54:25 +0800 Subject: [PATCH 097/382] =?UTF-8?q?=E6=8C=87=E5=AE=9A=E4=BA=A4=E6=98=93?= =?UTF-8?q?=E5=8F=B7=E7=89=B9=E6=AE=8A=E5=A4=84=E7=90=86,=20=E5=85=81?= =?UTF-8?q?=E8=AE=B8=E7=BB=A7=E7=BB=AD=E5=8F=91=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 4cfb5f40..e7f4b9be 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -715,7 +715,7 @@ class Index extends CI_Controller { foreach ($data['unsend_list'] as $item) { //已经发送的不处理,防止重复发送 - if ($item->pn_send == 'send') { + if ($item->pn_send == 'send' && empty($pn_txn_id)) { continue; } From 87a3de22cfac0371e4b48912e6b10768c0e714d3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 19 Jul 2018 18:01:58 +0800 Subject: [PATCH 098/382] =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E8=AE=B0=E5=BD=95:=20=E6=98=BE=E7=A4=BA=E4=BB=98=E6=AC=BE?= =?UTF-8?q?=E4=BA=BA=E5=90=8D=E5=AD=97=20,=E4=BB=98=E6=AC=BE=E4=BA=BA?= =?UTF-8?q?=E9=82=AE=E7=AE=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 13 ++++++++----- webht/third_party/paypal/controllers/index.php | 13 ++++++++----- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index d8820bc3..c7ad49ba 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -1235,6 +1235,7 @@ class IPayLinksService extends CI_Controller $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); // 对齐 $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); @@ -1244,8 +1245,9 @@ class IPayLinksService extends CI_Controller ->SetCellValue('B1', '团号') ->SetCellValue('C1', '金额') ->SetCellValue('D1', '付款人') - ->SetCellValue('E1', '交易号') - ->SetCellValue('F1', '收单时间'); + ->SetCellValue('E1', '付款人邮箱') + ->SetCellValue('F1', '交易号') + ->SetCellValue('G1', '收单时间'); $currency_sum = array(); bcscale(2); $rowCount = 2; @@ -1258,9 +1260,10 @@ class IPayLinksService extends CI_Controller ->SetCellValue('A'.$rowCount, ($rowCount-1)) ->setCellValueExplicit('B'.$rowCount, $row->IPL_orderId,PHPExcel_Cell_DataType::TYPE_STRING) ->setCellValueExplicit('C'.$rowCount, trim($row->IPL_currencyCode) . number_format($row->IPL_orderAmount, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('D'.$rowCount, $payer) - ->setCellValueExplicit('E'.$rowCount, $row->IPL_dealId,PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('F'.$rowCount, $row->IPL_acquiringTime); + ->SetCellValue('D'.$rowCount, $row->IPL_payerName) + ->SetCellValue('E'.$rowCount, $row->IPL_payerEmail) + ->setCellValueExplicit('F'.$rowCount, $row->IPL_dealId,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('G'.$rowCount, $row->IPL_acquiringTime); $payer = ""; $rowCount++; } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index e7f4b9be..6c466f89 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -980,6 +980,7 @@ class Index extends CI_Controller { $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); // 对齐 $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); @@ -989,8 +990,9 @@ class Index extends CI_Controller { ->SetCellValue('B1', '团号') ->SetCellValue('C1', '金额') ->SetCellValue('D1', '付款人') - ->SetCellValue('E1', '交易号') - ->SetCellValue('F1', '收单时间'); + ->SetCellValue('E1', '付款人邮箱') + ->SetCellValue('F1', '交易号') + ->SetCellValue('G1', '收单时间'); $currency_sum = array(); bcscale(2); $rowCount = 2; @@ -1004,9 +1006,10 @@ class Index extends CI_Controller { ->SetCellValue('A'.$rowCount, ($rowCount-1)) ->setCellValueExplicit('B'.$rowCount, $orderid,PHPExcel_Cell_DataType::TYPE_STRING) ->setCellValueExplicit('C'.$rowCount, trim($row->pn_mc_currency) . number_format($row->pn_mc_gross, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('D'.$rowCount, $payer) - ->setCellValueExplicit('E'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('F'.$rowCount, $row->pn_datetime); + ->SetCellValue('D'.$rowCount, $row->pn_payer) + ->SetCellValue('E'.$rowCount, $row->pn_payer_email) + ->setCellValueExplicit('F'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('G'.$rowCount, $row->pn_datetime); $payer = $orderid = ""; $rowCount++; } From 027e4632a39c6062ddaf30d511f1d9baf48aa785 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 20 Jul 2018 09:19:51 +0800 Subject: [PATCH 099/382] =?UTF-8?q?=E4=BC=98=E5=85=88=E5=88=97=E5=87=BA?= =?UTF-8?q?=E5=8F=91=E9=80=81=E5=A4=B1=E8=B4=A5=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 2 +- webht/third_party/paypal/models/note_model.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 0f30a40c..9bc19894 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -42,7 +42,7 @@ class Note_model extends CI_Model { public function search_date($date) { $this->init(); - $search_sql = " AND pn.IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' "; + $search_sql = " AND (pn.IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; $this->search = $search_sql; $this->orderby=" ORDER BY CASE pn.IPL_sent WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.IPL_sn DESC "; return $this->get_list(); diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index d5f6c022..71835876 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -45,7 +45,7 @@ class Note_model extends CI_Model { public function search_date($date) { $this->init(); - $search_sql = " AND pn.pn_datetime BETWEEN '$date 00:00:00' AND '$date 23:59:59' "; + $search_sql = " AND (pn.pn_datetime BETWEEN '$date 00:00:00' AND '$date 23:59:59' OR pn_send<>'send') "; $this->search = $search_sql; $this->orderby=" ORDER BY CASE pn.pn_send WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.pn_sn DESC "; return $this->get_list(); From b65f771cf7b216f14c67e39aa09dc22c06a3ff0b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 20 Jul 2018 16:25:57 +0800 Subject: [PATCH 100/382] =?UTF-8?q?ipaylinks=20=E8=AE=A2=E5=8D=95=E5=8F=B7?= =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=A4=B1=E8=B4=A5=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/iPayLinks_list.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 17123daa..2c19a7d3 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -258,7 +258,7 @@ $.ajax({ type: "get", dataType: "json", - url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id , + url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id + '/' + pn_invoice, success: function(data, textStatus) { $('#modal_set_orderid_body').html(data); $('#modal_set_orderid').modal('show'); From f1667a48c3b7132f364fec96e617e1f3e343eb4f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 23 Jul 2018 14:54:50 +0800 Subject: [PATCH 101/382] =?UTF-8?q?ipaylinks=20MPS=E9=80=80=E6=AC=BE?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=BC=82=E6=AD=A5=E9=80=9A=E7=9F=A5;?= =?UTF-8?q?=E7=9B=AE=E5=89=8D=E4=BD=BF=E7=94=A8=E7=9A=84=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E6=98=AF=E4=BB=98=E6=AC=BE=E6=97=B6=E7=9A=84?= =?UTF-8?q?=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index c7ad49ba..29505740 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -347,7 +347,7 @@ class IPayLinksService extends CI_Controller //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->IPL_payType == 'refund') { - $this->Note_model->update_send($item->IPL_dealId, 'send'); + // $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } @@ -611,23 +611,35 @@ class IPayLinksService extends CI_Controller } // 未得到结果 if (empty($asyns_resp->data->orderId)) { - echo "200"; return; } // dealId $dealId = trim($asyns_resp->data->dealId) ; $tmp_deal = $dealId ? $dealId : $this->create_guid(); // payer info - $payer_info = json_decode($asyns_resp->data->remark); - $payer_name = $payer_info->n; - $payer_email = $payer_info->e; + if (isset($asyns_resp->data->remark)) { + $payer_info = json_decode($asyns_resp->data->remark); + $payer_name = $payer_info->n; + $payer_email = $payer_info->e; + } - if (true === $this->if_note_exists($dealId)) { - echo "200"; + bcscale(2); + /** 退款成功 */ + if (isset($asyns_resp->data->refundOrderId) && strcmp($asyns_resp->data->resultCode, '2') == 0) { + $this->Note_model->save_refund( + strval($asyns_resp->data->dealId) + , strval($asyns_resp->data->orderId) + , strval("-" . bcdiv(floatval($asyns_resp->data->refundAmount), 100)) + , strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->refundTime))) + , strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->completeTime))) + , $asyns_resp->data->resultCode + , "0000" + , json_encode($asyns_resp->data) + , "refund" + ); return; } - bcscale(2); // 支付成功 // 查询支付结果;入库处理 if ( ! empty($dealId)) { @@ -650,7 +662,6 @@ class IPayLinksService extends CI_Controller $query = $this->query_pay_result($asyns_resp->data); } // 返回状态码200 - echo "200"; return; } From c8c4e0ffa358b4ca911d36c4d3d8df5aff513e99 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 23 Jul 2018 15:39:12 +0800 Subject: [PATCH 102/382] =?UTF-8?q?=E4=BF=AE=E6=AD=A3=E4=B8=80=E4=B8=AA?= =?UTF-8?q?=E4=BA=A4=E6=98=93=E9=80=9A=E7=9F=A5=E6=9C=89=E8=AF=AF=E7=9A=84?= =?UTF-8?q?=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 18 +++++++++--------- .../third_party/pay/models/IPayLinks_model.php | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 29505740..11737233 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -263,18 +263,18 @@ class IPayLinksService extends CI_Controller $this->query_info_arr["orderId"] = $orderid; $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); - $this->query_info_arr["mode"] = 2; + $this->query_info_arr["mode"] = 1; $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); $resp_obj = simplexml_load_string($resp); - foreach ($resp_obj->details->detail as $key => $query_order) { - $order = new stdClass(); - $order->check = true; - $order->data = $query_order; - $this->ipaylinks_notice($order); - } - // $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); + // foreach ($resp_obj->details->detail as $key => $query_order) { + // $order = new stdClass(); + // $order->check = true; + // $order->data = $query_order; + // $this->ipaylinks_notice($order); + // } + $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); return; } @@ -341,7 +341,7 @@ class IPayLinksService extends CI_Controller foreach ($data['unsend_list'] as $item) { //已经发送的不处理,防止重复发送 - if ($item->IPL_sent == 'send') { + if ($item->IPL_sent == 'send' && empty($pn_txn_id)) { continue; } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 49c3be6d..56096204 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -164,7 +164,7 @@ class IPayLinks_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN From 02d03a9f8d1c85a534bcdb67c8db5b1d2d868cc2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 24 Jul 2018 14:19:40 +0800 Subject: [PATCH 103/382] =?UTF-8?q?=E6=8B=BC=E5=9B=A2=E6=88=90=E6=9C=AC?= =?UTF-8?q?=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 95 ++++++++++++++++--- .../models/orderFinance_model.php | 1 + 2 files changed, 81 insertions(+), 15 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 5ba0bd0d..89d6cda0 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -39,31 +39,96 @@ class Order_finance extends CI_Controller { */ public function single_order_report($coli_sn=0) { + $ret = new stdClass(); + $ret->combine_cost = array(); $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($group_type_arr)); foreach ($combineNo_arr as $kc => $vc) { if ($vc->GCI_groupType == 1) { - $pvt_cost = $this->pvt_basic($vc->GCI_combineNo); + $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo); } else if ($vc->GCI_groupType == 2) { - $combine_cost = $this->combine_basic($vc->GCI_combineNo); + $ret->combine_cost[] = $this->combine_basic($vc->GCI_combineNo, $coli_sn); } } + $this->output->set_content_type('application/json')->set_output(json_encode($ret)); return; } /*! - * 基本拼团 - * * 仅含有一个产品 - * @example 180712534 + * 拼团计算 + * @example 180426360,180516007U * @date 2018-07-18 * @param string $combineNo * @return [type] [description] */ - public function combine_basic($combineNo="") + public function combine_basic($combineNo="", $coli_sn=0) { - # code... + $ret = new stdClass(); + $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo); + if (empty($all_orders)) { + return null; + } +// $ret->s = $all_orders; + $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); + $all_pag = array_unique($all_pags); +// $ret->c = $all_pag; + $combine_pag_arr = array(); + if (count($all_pag) > 1) { + // 多个产品, 找出拼团产品号 + $rid_code = array(); + $value_count = array_count_values($all_pags); + foreach ($all_pag as $kp => $vp) { + $tmp = null; + $tmp = $this->get_allowed_combine($vp); +// $ret->b = array_diff($tmp, $all_pag); + if (empty(array_diff($tmp, $all_pag))) { + $combine_pag_arr[] = $tmp; + } +// $ret->e = $value_count; + if($value_count[$vp] > 1) { + $rid_code[] = $vp; + } + } +// $ret->d = $rid_code; + if ( ! empty($rid_code)) { + $combine_pag_arr[] = $rid_code; + } + } else { + // 单个产品 + $combine_pag_arr[] = ($all_pag); + } + bcscale(2); + $ret->combine_pags = my_array_unique($combine_pag_arr); + $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品 +// $ret->q = my_array_unique($combine_pag_arr); + $ret->tour_count = $ret->person_num = 0; + $ret->PAG_Code = ""; + $ret->order_cost = array(); + foreach ($all_orders as $ko => $vo) { + if (in_array($vo->PAG_Code, $ret->combine_pags)) { + // $ret->tour_count++; + $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $ret->startdate = $vo->COLD_StartDate; + $tour_s = new stdClass(); + if ($vo->COLI_SN == $coli_sn) { + $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $ret->order_cost[] = $tour_s; + } + } + } + $ret->PAG_Code = implode(",", $ret->combine_pags); + $ret->comment = "拼团" . $combineNo . ", 按" . $ret->person_num . "人等"; + $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); + $ret->cost_category = $combine_cost->cost_category; + $ret->cost_sum = $combine_cost->cost_sum; + $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num); + foreach ($ret->order_cost as $kc => $voc) { + $ret->order_cost[$kc]->order_cost_sum = bcmul($voc->person_num, $ret->person_cost); + } + return $ret; + // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); } /*! @@ -90,19 +155,19 @@ class Order_finance extends CI_Controller { $tour_s->cost_category = $combine_cost->cost_category; $tour_s->cost_sum = $combine_cost->cost_sum; $tour_s->person_cost = bcdiv($tour_s->cost_sum, $ret->person_num); - $tour_s->comment = "按PVT,共" . $ret->person_num . "人";// 150 + $tour_s->comment = "PVT,共" . $ret->person_num . "人";// 150 $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); - $tour_s->PAG_Code = substr(implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))), 0, 50) ; // TODO 限制50 + $tour_s->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); // TODO 限制50 $tour_s->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 - $tour_s->pag_name = substr(implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)), 0, 200) ; // TODO 限制200 + $tour_s->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') $ret->tour[0] = $tour_s; - if ( $ret->tour_count > 1 ) { - } else { - } + // if ( $ret->tour_count > 1 ) { + // } else { + // } $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); - $this->output->set_content_type('application/json')->set_output(json_encode($ret)); - return; + return $ret; + // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); } /*! diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index b2bba4a7..c4942dea 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -55,6 +55,7 @@ class OrderFinance_model extends CI_Model { $ret->cost_category['guiderOperations'] = 0; $ret->cost_category['touristCarOperations'] = 0; $ret->cost_category['sceneryOperations'] = 0; + $ret->cost_category['restraurantOperations'] = 0; foreach ($ret->cost_detail as $key => $value) { if ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='客人水费') { $ret->cost_category['water'] += $value->cost; From 63148e1f82321d979a359b8e0a2e534287c773c3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Jul 2018 09:27:53 +0800 Subject: [PATCH 104/382] =?UTF-8?q?=E6=8B=BC=E5=9B=A2=E6=88=90=E6=9C=AC?= =?UTF-8?q?=E8=AE=A1=E7=AE=97:=20+=E6=8B=86=E5=88=86=E6=8B=BC,=E6=B7=B7?= =?UTF-8?q?=E5=90=88=E6=8B=BC,=E8=AE=A2=E5=8D=95=E5=A4=9A=E4=BA=A7?= =?UTF-8?q?=E5=93=81=E5=8D=95=E6=8B=BC=3D=E6=95=B4=E5=9B=A2pvt....?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 154 +++++++++++++----- .../models/orderFinance_model.php | 14 +- 2 files changed, 127 insertions(+), 41 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 89d6cda0..401fd2a6 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -24,6 +24,7 @@ class Order_finance extends CI_Controller { $this->load->helper('array'); $this->load->model('OrderFinance_model'); mb_regex_encoding("UTF-8"); + bcscale(4); } public function index() @@ -45,11 +46,16 @@ class Order_finance extends CI_Controller { $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($group_type_arr)); + $processed_code = array(); foreach ($combineNo_arr as $kc => $vc) { if ($vc->GCI_groupType == 1) { - $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo); + $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); } else if ($vc->GCI_groupType == 2) { - $ret->combine_cost[] = $this->combine_basic($vc->GCI_combineNo, $coli_sn); + // 这里不排除产品编号是否已处理, 因为重复的情况比较多 + $tmp_cost = $this->combine_basic($vc->GCI_combineNo, $coli_sn); + $processed_code = array_merge($processed_code, $tmp_cost->combine_pags); + $ret->combine_cost[] = $tmp_cost; + $tmp_cost = null; } } $this->output->set_content_type('application/json')->set_output(json_encode($ret)); @@ -70,54 +76,105 @@ class Order_finance extends CI_Controller { if (empty($all_orders)) { return null; } + $ret->coli_sn = $coli_sn; // $ret->s = $all_orders; $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); $all_pag = array_unique($all_pags); -// $ret->c = $all_pag; $combine_pag_arr = array(); + $pvt_code = $this->forbidden_combine(); if (count($all_pag) > 1) { // 多个产品, 找出拼团产品号 - $rid_code = array(); - $value_count = array_count_values($all_pags); + // 先处理拆分拼团的产品, 补全产品号 + $allowed_spread = $this->spread_code(); + $extra_code_cold = array(); + $all_orders_arr = json_decode(json_encode($all_orders), true); // 避免foreach object 改变自身 + foreach ($all_orders_arr as $ka => $va) { + $extra_arr = array(); + if (isset($allowed_spread[$va['PAG_Code']])) { + foreach ($allowed_spread[$va['PAG_Code']] as $ks => $vs) { + $tmp_extra = new stdClass(); + $tmp_extra = (object) $va; + $tmp_extra->real_code = $tmp_extra->PAG_Code; + $tmp_extra->real_pag_sn = $tmp_extra->COLD_ServiceSN; + $tmp_extra->PAG_Code = $vs; + $tmp_extra->COLD_ServiceSN = null; + $extra_arr[] = $tmp_extra; + } + } + $extra_code_cold = array_merge($extra_code_cold, $extra_arr); + } + // 避免覆盖key + foreach ($extra_code_cold as $ke => $ve) { + $all_orders[] = $ve; + } + // 重新计算重复次数 + $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); + // 重复的产品号; 可混拼的产品 + $repeat_code = array(); + $code_count = array_count_values($all_pags); foreach ($all_pag as $kp => $vp) { + if (in_array($vp, $pvt_code)) { + continue; + } $tmp = null; $tmp = $this->get_allowed_combine($vp); -// $ret->b = array_diff($tmp, $all_pag); - if (empty(array_diff($tmp, $all_pag))) { - $combine_pag_arr[] = $tmp; + $this_allowed = ($tmp === null) ? null : array_diff($tmp, $all_pag); // diff((31,41), (31,41,47)) ==> () + if (empty($this_allowed) && $tmp !== null) { + $combine_pag_arr[] = $tmp; // push (31,41) } -// $ret->e = $value_count; - if($value_count[$vp] > 1) { - $rid_code[] = $vp; + // 重复的产品即为拼团 + if($code_count[$vp] > 1) { + $repeat_code[] = $vp; } } -// $ret->d = $rid_code; - if ( ! empty($rid_code)) { - $combine_pag_arr[] = $rid_code; + if ( ! empty($repeat_code)) { + $combine_pag_arr[] = $repeat_code; } } else { // 单个产品 $combine_pag_arr[] = ($all_pag); } - bcscale(2); + // 预定多产品, 但是只有部分发了计划 + // 预定多产品, 拼团只有一个订单, 相当于整团PVT + if (empty($combine_pag_arr)) { + // $combine_pag_arr[] = array_diff($all_pag, $pvt_code); // 此处排除PVT租车产品 + $combine_pag_arr[] = $all_pag; + } +// $ret->s = $all_pags; +// $ret->q = $combine_pag_arr; $ret->combine_pags = my_array_unique($combine_pag_arr); $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品 // $ret->q = my_array_unique($combine_pag_arr); - $ret->tour_count = $ret->person_num = 0; + $ret->person_num = 0; $ret->PAG_Code = ""; $ret->order_cost = array(); + $pag_sns = array(); + $unique_coli = array(); foreach ($all_orders as $ko => $vo) { if (in_array($vo->PAG_Code, $ret->combine_pags)) { - // $ret->tour_count++; - $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $pag_sns[] = $vo->COLD_ServiceSN; + // 整团单拼时, 避免重复计算人数 + // 订单人数不重复计 + if ( ! in_array($vo->PAG_Code, $pvt_code) && ! in_array($vo->COLI_SN, $unique_coli)) { + $unique_coli[] = $vo->COLI_SN; + $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum; + } $ret->startdate = $vo->COLD_StartDate; $tour_s = new stdClass(); if ($vo->COLI_SN == $coli_sn) { $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $tour_s->PAG_code = $vo->PAG_Code; + $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; + $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; $ret->order_cost[] = $tour_s; + $ret->coli_id = $vo->coli_ID; } } } + $this_order_real_pag_sns = array_map(function($ele) {return $ele->real_pag_sn;}, $ret->order_cost); + $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', array_unique(array_filter($this_order_real_pag_sns)))); // $pag_sns + $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 + $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') $ret->PAG_Code = implode(",", $ret->combine_pags); $ret->comment = "拼团" . $combineNo . ", 按" . $ret->person_num . "人等"; $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); @@ -136,36 +193,34 @@ class Order_finance extends CI_Controller { * @example 180515061M * @date 2018-07-18 */ - public function pvt_basic($combineNo="", $coli_sn=0) + public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array()) { $ret = new stdClass(); - $ret->tour = array(); - $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo); + // $ret->tour = array(); + $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code); if (empty($all_orders)) { return null; } + $ret->coli_sn = $coli_sn; + $ret->coli_id = $all_orders[0]->coli_ID; // 预定的产品数 $ret->tour_count = count(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $all_orders))); $ret->person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); - bcscale(2); - $tour_s = new stdClass(); + // $tour_s = new stdClass(); $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); - $tour_s->startdate = $all_orders[0]->COLD_StartDate; - // $tour_s->person_grade = ($all_orders[0]->COLD_PersonNum + $all_orders[0]->COLD_ChildNum ); - $tour_s->cost_category = $combine_cost->cost_category; - $tour_s->cost_sum = $combine_cost->cost_sum; - $tour_s->person_cost = bcdiv($tour_s->cost_sum, $ret->person_num); - $tour_s->comment = "PVT,共" . $ret->person_num . "人";// 150 + $ret->startdate = $all_orders[0]->COLD_StartDate; + $ret->person_grade = ($all_orders[0]->COLD_PersonNum + $all_orders[0]->COLD_ChildNum ); + $ret->cost_category = $combine_cost->cost_category; + $ret->cost_sum = $combine_cost->cost_sum; + $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num); + $ret->comment = "PVT,共" . $ret->person_num . "人";// 150 $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); - $tour_s->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); // TODO 限制50 - $tour_s->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 - $tour_s->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') - $ret->tour[0] = $tour_s; - // if ( $ret->tour_count > 1 ) { - // } else { - // } - $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); + $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); // TODO 限制50 + $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 + $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') + // $ret->tour[0] = $tour_s; + // $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); return $ret; // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); } @@ -188,7 +243,7 @@ class Order_finance extends CI_Controller { } return $allowed; } - /** 允许拼团的不同编号产品 */ + /** 允许混合拼团的不同编号产品 */ public function allowed_combine() { return array( @@ -203,6 +258,29 @@ class Order_finance extends CI_Controller { ); } + /** 允许拆分再拼团的产品编号 */ + public function spread_code() + { + return array( + "XASIC-42" => array("XASIC-41"), + "BJSIC-42" => array("BJSIC-41"), + "BJSIC-43" => array("BJSIC-41","BJSIC-42"), + "SHSIC-42" => array("SHSIC-41"), + "SHSIC-43" => array("SHSIC-41","SHSIC-42") + ); + } + + /** 肯定是PVT */ + public function forbidden_combine() + { + return array( + "BJALC-209", + "BJSIC-16", + "SHSIC-45", + "XASIC-16" + ); + } + } /* End of file order_finance.php */ diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index c4942dea..a52ed890 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -4,6 +4,7 @@ defined('BASEPATH') OR exit('No direct script access allowed'); class OrderFinance_model extends CI_Model { function __construct() { parent::__construct(); + $this->load->helper('array'); $this->HT = $this->load->database('HT', TRUE); } @@ -14,13 +15,18 @@ class OrderFinance_model extends CI_Model { from GroupCombineInfo gci inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN where coli.COLI_SN=$coli_sn - group by gci.GCI_combineNo,gci.GCI_groupType"; + group by gci.GCI_combineNo,gci.GCI_groupType + order by gci.GCI_groupType desc"; return $this->HT->query($sql)->result(); } - /** 拼团号下的所有订单 */ - public function get_all_combine_order($combineNo="") + /** + * 拼团号下的所有订单 + * * 仅包价线路产品 + */ + public function get_all_combine_order($combineNo="", $processed_code=array()) { + $processed_sql = empty($processed_code) ? "" : " and PAG_Code not in (" . my_implode("'",",",$processed_code) . ") "; $sql = "SELECT gci.GCI_combineNo,gci.GCI_VendorOrderId ,COLI_SN,coli_ID--,COLI_ApplyDate,COLI_GroupCode ,COLD_SN,cold.COLD_ServiceSN--,COLD_EndDate @@ -30,9 +36,11 @@ class OrderFinance_model extends CI_Model { from GroupCombineInfo gci inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN + and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2 where gci.GCI_combineNo =? + $processed_sql order by GCI_combineNo,cold.COLD_StartDate"; return $this->HT->query($sql, array($combineNo))->result(); } From 5cdef0d34ff136f49d23f301650c22d755d4f524 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Jul 2018 09:51:07 +0800 Subject: [PATCH 105/382] =?UTF-8?q?ipaylinks=20=E4=B8=8D=E5=A4=84=E7=90=86?= =?UTF-8?q?=E6=8E=A5=E6=94=B6=E5=88=B0=E7=9A=84=E5=A4=B1=E8=B4=A5=E7=9A=84?= =?UTF-8?q?=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 3 ++- webht/third_party/pay/models/note_model.php | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 11737233..c3f82ea6 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -501,7 +501,8 @@ class IPayLinksService extends CI_Controller } // 批量结果 if (empty($pn_txn_id)) { - echo "done. recorde count:".$int; + echo "count:" . count($data['unsend_list']); + echo "\r\ndone. recorde count:".$int; } return; } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 9bc19894..aa2ba7f1 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -143,6 +143,7 @@ class Note_model extends CI_Model { ,pn.IPL_payerEmail FROM IPayLinksLog pn WHERE 1=1 + AND IPL_stateCode<>3 "; $this->send ? $sql.=$this->send : false; $this->search ? $sql.=$this->search : false; From 4c9fb41945e768ec1b042269fd07ccf1a437534f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Jul 2018 16:52:46 +0800 Subject: [PATCH 106/382] =?UTF-8?q?ipaylinks=20=E5=A4=9A=E6=AC=A1=E4=BB=98?= =?UTF-8?q?=E6=AC=BE=E5=A4=B1=E8=B4=A5=E5=90=8E=E6=88=90=E5=8A=9F=E7=9A=84?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E9=80=9A=E7=9F=A5=E6=9C=AA=E6=88=90=E5=8A=9F?= =?UTF-8?q?,=E9=80=80=E6=AC=BE=E4=B8=8D=E5=A4=84=E7=90=86,=E4=BA=A4?= =?UTF-8?q?=E6=98=93=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 37 +++++--- webht/third_party/pay/models/note_model.php | 91 +++++++++---------- 2 files changed, 71 insertions(+), 57 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index c3f82ea6..f0738e8c 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -257,13 +257,14 @@ class IPayLinksService extends CI_Controller return; } - public function query_pay($day_offset = 3, $orderid=NULL) + public function query_pay($day_offset = 1, $orderid=NULL) { $this->query_info_arr["queryOrderId"] = $this->create_guid(); $this->query_info_arr["orderId"] = $orderid; - $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); - $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); - $this->query_info_arr["mode"] = 1; + // $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); + // $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); + $this->query_info_arr["mode"] = 1; + // $this->query_info_arr["type"] = $day_offset; // 1-支付;2-退款 $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); @@ -610,10 +611,11 @@ class IPayLinksService extends CI_Controller log_message('error','iPayLinks asyn notify: ' . $this->input->post("orderId")); $asyns_resp = $this->verify_sign($resp_arr); } + log_message('error','iPayLinks asyn notify body: ' . json_encode($asyns_resp->data)); // 未得到结果 - if (empty($asyns_resp->data->orderId)) { - return; - } + // if (empty($asyns_resp->data->orderId)) { + // return; + // } // dealId $dealId = trim($asyns_resp->data->dealId) ; $tmp_deal = $dealId ? $dealId : $this->create_guid(); @@ -634,7 +636,7 @@ class IPayLinksService extends CI_Controller , strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->refundTime))) , strval(date('Y-m-d H:i:s',strtotime($asyns_resp->data->completeTime))) , $asyns_resp->data->resultCode - , "0000" + , null , json_encode($asyns_resp->data) , "refund" ); @@ -643,7 +645,7 @@ class IPayLinksService extends CI_Controller // 支付成功 // 查询支付结果;入库处理 - if ( ! empty($dealId)) { + // if ( ! empty($dealId)) { $this->Note_model->save_ipl( strval($tmp_deal) ,strval($asyns_resp->data->orderId) @@ -661,7 +663,7 @@ class IPayLinksService extends CI_Controller ,strval($payer_email) ); $query = $this->query_pay_result($asyns_resp->data); - } + // } // 返回状态码200 return; } @@ -1009,7 +1011,7 @@ class IPayLinksService extends CI_Controller , strval(date('Y-m-d H:i:s',strtotime($refund->refundTime))) , strval(date('Y-m-d H:i:s',strtotime($refund->completeTime))) , $refund->stateCode - , "0000" + , ($refund->stateCode==2) ? "0000" : null , json_encode($refund) , "refund" ); @@ -1297,4 +1299,17 @@ class IPayLinksService extends CI_Controller $objWriter->save('php://output'); } + public function sign_fun() + { + $req = $this->input->post(); + $str = $this->generate_sign($req); + return $this->output->set_content_type('application/json')->set_output(json_encode(array("str" => $str))); + } + + public function test() + { + $this->Note_model->test(); + return ; + } + } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index aa2ba7f1..2fbc4f94 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -5,12 +5,12 @@ if (!defined('BASEPATH')) class Note_model extends CI_Model { - var $topnum = false; - var $orderby = false; - var $send = false; - var $search = false; - var $dealId = false; - var $payment_status = false; + var $topnum = null; + var $orderby = null; + var $send = null; + var $search = null; + var $dealId = null; + var $payment_status = null; function __construct() { parent::__construct(); @@ -18,12 +18,12 @@ class Note_model extends CI_Model { } public function init() { - $this->topnum = false; - $this->send = false; - $this->search = false; - $this->payment_status = false; - $this->dealId = false; - $this->orderby = ' ORDER BY pn.IPL_sn DESC '; + $this->topnum = null; + $this->send = null; + $this->search = null; + $this->payment_status = null; + $this->dealId = null; + $this->orderby = ' ORDER BY IPL_sn DESC '; } public function unsend($topnum = 2) { @@ -42,16 +42,16 @@ class Note_model extends CI_Model { public function search_date($date) { $this->init(); - $search_sql = " AND (pn.IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; + $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; $this->search = $search_sql; - $this->orderby=" ORDER BY CASE pn.IPL_sent WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.IPL_sn DESC "; + $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC "; return $this->get_list(); } public function note($txn_id){ $this->init(); $this->topnum=1; - $this->dealId=" AND pn.IPL_dealId=".$this->INFO->escape($txn_id); + $this->dealId=" AND IPL_dealId=".$this->INFO->escape($txn_id); return $this->get_list(); } @@ -59,7 +59,7 @@ class Note_model extends CI_Model { { $this->init(); $this->topnum=1; - $this->dealId=" AND pn.IPL_orderId=".$this->INFO->escape($orderid)." AND pn.IPL_noticeTime=".$this->INFO->escape($notice_time); + $this->dealId=" AND IPL_orderId=".$this->INFO->escape($orderid)." AND IPL_noticeTime=".$this->INFO->escape($notice_time); return $this->get_list(); } @@ -69,9 +69,9 @@ class Note_model extends CI_Model { $search_sql = ''; $search_key = trim($search_key); if (!empty($search_key)) { - $search_sql.=" AND ( pn.IPL_dealId = '$search_key' - OR pn.IPL_orderId like '%$search_key%' - OR pn.IPL_memo like '%$search_key%' )"; + $search_sql.=" AND ( IPL_dealId = '$search_key' + OR IPL_orderId like '%$search_key%' + OR IPL_memo like '%$search_key%' )"; } $this->search = $search_sql; return $this->get_list(); @@ -81,7 +81,7 @@ class Note_model extends CI_Model { { $this->init(); $this->topnum = 1; - $this->search = " AND pn.IPL_dealId = '".$dealId."' "; + $this->search = " AND IPL_dealId = '".$dealId."' "; return $this->get_list(); } @@ -124,31 +124,23 @@ class Note_model extends CI_Model { public function get_list() { $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT "; $sql .= " - pn.IPL_sn - ,pn.IPL_dealId - ,pn.IPL_orderId - ,pn.IPL_currencyCode - ,pn.IPL_orderAmount - ,pn.IPL_payAmount - ,pn.IPL_stateCode - ,pn.IPL_resultCode - ,pn.IPL_resultMsg - ,pn.IPL_acquiringTime - ,pn.IPL_completeTime - ,pn.IPL_memo - ,pn.IPL_sent - ,pn.IPL_payType - ,pn.IPL_noticeTime - ,pn.IPL_payerName - ,pn.IPL_payerEmail + pn.* FROM IPayLinksLog pn WHERE 1=1 - AND IPL_stateCode<>3 - "; - $this->send ? $sql.=$this->send : false; - $this->search ? $sql.=$this->search : false; - $this->dealId ? $sql.=$this->dealId : false; - $this->orderby ? $sql.=$this->orderby : false; + and pn.IPL_payType='pay' + and (pn.IPL_stateCode=2 or pn.IPL_resultCode='0000') + $this->send + $this->search + $this->dealId + UNION ALL + select * from InfoManager.dbo.IPayLinksLog ipl2 + where 1=1 + and ipl2.IPL_payType='refund' + and ipl2.IPL_stateCode=2 + $this->search + $this->dealId + $this->orderby + "; $query = $this->INFO->query($sql); if ($this->topnum === 1) { if ($query->num_rows() > 0) { @@ -197,7 +189,7 @@ class Note_model extends CI_Model { $sql = "IF NOT EXISTS( SELECT TOP 1 1 FROM IPayLinksLog - WHERE IPL_dealId = ? + WHERE IPL_dealId = ? AND IPL_payType='refund' ) INSERT INTO IPayLinksLog ( @@ -277,8 +269,8 @@ class Note_model extends CI_Model { public function date_range($from, $to, $currency=NULL) { $this->init(); - $search_sql = " AND pn.IPL_resultCode='0000' "; - $search_sql .= " AND pn.IPL_acquiringTime BETWEEN '$from 00:00:00' AND '$to 23:59:59' "; + $search_sql = " AND IPL_resultCode='0000' "; + $search_sql .= " AND IPL_acquiringTime BETWEEN '$from 00:00:00' AND '$to 23:59:59' "; if ( ! empty($currency)) { $search_sql .= " AND IPL_currencyCode = '$currency' "; } @@ -287,4 +279,11 @@ class Note_model extends CI_Model { return $this->get_list(); } + public function test() + { + $sql = " "; + $this->INFO->query($sql); + return; + } + } From 07b0d4cacaa0d526f0e375c82a7fa959668b1ef0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Jul 2018 16:58:30 +0800 Subject: [PATCH 107/382] =?UTF-8?q?ipaylinks=20=E6=8E=92=E5=BA=8F,?= =?UTF-8?q?=E6=9C=AA=E5=8F=91=E9=80=81>=E5=A4=B1=E8=B4=A5>=E6=88=90?= =?UTF-8?q?=E5=8A=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 2fbc4f94..19ee668b 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -23,7 +23,7 @@ class Note_model extends CI_Model { $this->search = null; $this->payment_status = null; $this->dealId = null; - $this->orderby = ' ORDER BY IPL_sn DESC '; + $this->orderby = ' ORDER BY IPL_sent DESC ,IPL_sn DESC '; } public function unsend($topnum = 2) { From 8b439fe8ee0af3f8bc0e1b35da0b09d1c63bf96c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 26 Jul 2018 18:11:17 +0800 Subject: [PATCH 108/382] =?UTF-8?q?ipaylinks=20=E6=9F=A5=E8=AF=A2=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index f0738e8c..addba6cf 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -257,15 +257,28 @@ class IPayLinksService extends CI_Controller return; } - public function query_pay($day_offset = 1, $orderid=NULL) + public function query_pay($orderid=NULL) { $this->query_info_arr["queryOrderId"] = $this->create_guid(); $this->query_info_arr["orderId"] = $orderid; - // $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); - // $this->query_info_arr["endTime"] = date('YmdHis',strtotime("+$day_offset days")); $this->query_info_arr["mode"] = 1; // $this->query_info_arr["type"] = $day_offset; // 1-支付;2-退款 + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); + $resp = $this->curl($this->queryUrl,$this->query_info_arr); + $resp_obj = simplexml_load_string($resp); + $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); + return; + } + + public function query_pay_list($day_offset = 3) + { + $this->query_info_arr["queryOrderId"] = $this->create_guid(); + $this->query_info_arr["beginTime"] = date('YmdHis',strtotime("-$day_offset days")); + $this->query_info_arr["endTime"] = date('YmdHis235959'); + $this->query_info_arr["mode"] = 2; + $this->query_info_arr["type"] = 1; // 1-支付;2-退款 + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); $resp_obj = simplexml_load_string($resp); From 7e0e2d60fffeb495c84288d7ca86804bb9629d32 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Jul 2018 12:36:01 +0800 Subject: [PATCH 109/382] =?UTF-8?q?ipaylinks=20=E5=88=97=E8=A1=A8top?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 19ee668b..65be8ea2 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -122,8 +122,9 @@ class Note_model extends CI_Model { } public function get_list() { - $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT "; - $sql .= " + // $this->topnum ? $sql = "SELECT TOP " . $this->topnum : $sql = "SELECT "; + $this->topnum ? $top_sql = " TOP " . $this->topnum : $top_sql = " "; + $sql = "SELECT $top_sql pn.* FROM IPayLinksLog pn WHERE 1=1 @@ -133,14 +134,16 @@ class Note_model extends CI_Model { $this->search $this->dealId UNION ALL - select * from InfoManager.dbo.IPayLinksLog ipl2 + select $top_sql * from InfoManager.dbo.IPayLinksLog ipl2 where 1=1 and ipl2.IPL_payType='refund' and ipl2.IPL_stateCode=2 + $this->send $this->search $this->dealId $this->orderby "; + $query = $this->INFO->query($sql); if ($this->topnum === 1) { if ($query->num_rows() > 0) { From 895c42941023ce4ee9c80a1218dbbc1e6448139c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Jul 2018 12:43:29 +0800 Subject: [PATCH 110/382] =?UTF-8?q?ipaylinks=20=E4=B8=8B=E8=BD=BD=E5=AF=B9?= =?UTF-8?q?=E8=B4=A6=E5=8D=95,=20=E5=AD=98=E5=85=A5=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=BA=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- download_statement/download_files.php | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/download_statement/download_files.php b/download_statement/download_files.php index 69a3f9ef..7e9c48a4 100644 --- a/download_statement/download_files.php +++ b/download_statement/download_files.php @@ -7,10 +7,23 @@ $sftp = new Net_SFTP('106.14.1.181'); if (!$sftp->login('10000004000', 'YRATF0OtDaYa2Uhv6cWO8BV9FPBup5')) { exit('Login Failed'); } -// 获取前一天的对账单 // target remote -$target_folder = str_replace("-", "/", date("Y-m", strtotime("-1 day")) ); +$target_folder = null; +$targer_day = null; +// 获取前一天的对账单 +$target_folder = str_replace("-", "/", date("Y-m", strtotime("-1 day")) ); // 2018/07 +if (isset($_GET['f'])) { + $target_folder = $_GET['f']; // f=2018/06 f=2018/07/23 + $target_set = explode('/', $target_folder); + if (isset($target_set[2])) { + $target_folder = $target_set[0] . "/" . $target_set[1]; + $targer_day = $target_set[2]; + } +} $file_list = array_values(array_diff($sftp->nlist($target_folder), array(".",".."))); +if ($targer_day !== null) { + $file_list = array($target_set[0] . $target_set[1] . $target_set[2] . ".xlsx"); +} // target local $target_local = "statement_files/" . $target_folder; if ( ! is_dir($target_local)) { @@ -24,11 +37,15 @@ $new_files = array_values(array_diff($file_list, $local_files)); $new_cnt = 0; foreach ($new_files as $key => $new) { $file_path = $target_folder . "/" . $new; + echo $file_path, " ", $target_local . "/" . $new; + echo "<br>"; $sftp->get($file_path, $target_local . "/" . $new); $new_cnt++; } echo "Copied new statements count: " . $new_cnt; +echo "<br> new_files ", json_encode($new_files); +echo "<br> file_list ", json_encode($file_list); // header("Location: http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/auto_update_statement?f=$target_folder&fjson=" . json_encode($new_files)); -// header("Location: http://www.mycht.cn/webht.php/apps/pay/report/ipaylinks_excel?f=$target_folder&fjson=" . json_encode($new_files)); +header("Location: http://www.mycht.cn/webht.php/apps/pay/report/ipaylinks_excel?f=$target_folder&fjson=" . json_encode($new_files)); // header("Location: http://202.103.68.79:8083/webht.php/apps/pay/report/ipaylinks_excel?f=$target_folder&fjson=" . json_encode($new_files)); From 31b064474d877ddee28c7d5801a47d8a8a64a709 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Jul 2018 15:05:32 +0800 Subject: [PATCH 111/382] =?UTF-8?q?ipaylinks=20=E6=9F=A5=E8=AF=A2=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E9=80=9A=E7=9F=A5=E8=AE=B0=E5=BD=95,=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E4=BD=BF=E7=94=A8IPL=E8=A1=A8=E7=9A=84key=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=20=E5=8E=9F=E5=9B=A0:=20ipaylinks=202018-07-23?= =?UTF-8?q?=E5=8D=87=E7=BA=A7=E7=B3=BB=E7=BB=9F=E5=90=8E=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=BE=97=E5=88=B0=E7=9A=84=E4=BA=A4=E6=98=93=E5=8F=B7=E4=B8=8D?= =?UTF-8?q?=E5=87=86=E7=A1=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 4 ++-- webht/third_party/pay/models/note_model.php | 3 ++- webht/third_party/pay/views/iPayLinks_list.php | 6 +++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index addba6cf..bf9f2b2b 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -900,11 +900,11 @@ class IPayLinksService extends CI_Controller } //获取note详情,以便后续修改各项数据 - public function note_modal($pn_txn_id = false, $pn_invoice = false ,$notice_time = false) { + public function note_modal($pn_txn_id = false, $pn_invoice = false, $pn_id = null) { $data = array(); $data['IPL_orderId'] = $pn_invoice; if (!empty($pn_txn_id)) { - $data['note'] = $this->Note_model->note($pn_txn_id); + $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); if (!empty($data['note'])) { if (!empty($pn_invoice)) { $orderid_info = $this->analysis_orderid($pn_invoice); diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 65be8ea2..6bdf5fcf 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -48,10 +48,11 @@ class Note_model extends CI_Model { return $this->get_list(); } - public function note($txn_id){ + public function note($txn_id, $pn_id=null){ $this->init(); $this->topnum=1; $this->dealId=" AND IPL_dealId=".$this->INFO->escape($txn_id); + $this->dealId .= ($pn_id===null) ? " " : " AND IPL_sn=" . $pn_id; return $this->get_list(); } diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 2c19a7d3..8b3b3a45 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -166,7 +166,7 @@ $class_css = 'btn-danger'; $show_send = $item->IPL_sent; } - ?><a href="javascript:void(0);" title="<?php echo $item->IPL_resultMsg; ?>" onclick="show_order_modal('<?php echo $item->IPL_dealId; ?>', '<?php echo $item->IPL_orderId; ?>','<?php echo $item->IPL_noticeTime; ?>','<?php echo $item->IPL_orderId; ?>')" class="btn btn-sm <?php echo $class_css; ?>"><?php echo $show_send; ?></a> + ?><a href="javascript:void(0);" title="<?php echo $item->IPL_resultMsg; ?>" onclick="show_order_modal('<?php echo $item->IPL_dealId; ?>', '<?php echo $item->IPL_orderId; ?>','<?php echo $item->IPL_noticeTime; ?>','<?php echo $item->IPL_orderId; ?>', '<?php echo $item->IPL_sn; ?>')" class="btn btn-sm <?php echo $class_css; ?>"><?php echo $show_send; ?></a> </li> </ul> @@ -253,12 +253,12 @@ return date; } }); - function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order) { + function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order, pn_id) { if (pn_txn_id) { $.ajax({ type: "get", dataType: "json", - url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id + '/' + pn_invoice, + url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id + '/' + pn_invoice + '/' + pn_id, success: function(data, textStatus) { $('#modal_set_orderid_body').html(data); $('#modal_set_orderid').modal('show'); From 74ba9fe96f326a30f0d81f0dd452833798eae5ab Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Jul 2018 15:48:45 +0800 Subject: [PATCH 112/382] =?UTF-8?q?ipaylinks=20=E5=8F=91=E9=80=81=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E4=BB=A5=E5=BC=82=E6=AD=A5=E9=80=9A=E7=9F=A5=E7=9A=84?= =?UTF-8?q?resultCode=E4=B8=BA=E5=87=86=20=E5=8E=9F=E5=9B=A0:=20ipaylinks?= =?UTF-8?q?=E9=80=BB=E8=BE=91=E4=BF=AE=E6=94=B9=E4=B8=BA=E6=94=AF=E4=BB=98?= =?UTF-8?q?=E7=BB=93=E6=9E=9C=E4=B8=8E=E5=95=86=E6=88=B7=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=8F=B7=E4=B8=80=E4=B8=80=E5=AF=B9=E5=BA=94,=20=E5=87=BA?= =?UTF-8?q?=E7=8E=B0=E4=BA=86=E4=B8=80=E4=B8=AA=E4=BA=A4=E6=98=93=E5=8F=B7?= =?UTF-8?q?=E5=90=8C=E6=97=B6=E5=87=BA=E7=8E=B0stateCode=3D2,resultCode!?= =?UTF-8?q?=3D'0000',=E6=89=80=E4=BB=A5=E8=BF=99=E9=87=8C=E4=B8=8D?= =?UTF-8?q?=E5=8C=B9=E9=85=8DstateCode=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index bf9f2b2b..115b51f1 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -366,7 +366,7 @@ class IPayLinksService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->IPL_resultCode), "0000") !== 0 && strcmp(trim($item->IPL_stateCode), "2") !== 0) { + if (strcmp(trim($item->IPL_resultCode), "0000") !== 0 ) { $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); continue; } From 7052a9c3ddd06629d6f4df1481fe26fe6bda4a2b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 27 Jul 2018 16:43:29 +0800 Subject: [PATCH 113/382] =?UTF-8?q?ipaylinks=20=E8=8E=B7=E5=8F=96=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E5=BD=95=E5=85=A5=E7=8A=B6=E6=80=81=20[=E6=B5=8B?= =?UTF-8?q?=E8=AF=95]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 16 + webht/third_party/pay/models/note_model.php | 72 ++++ .../third_party/pay/views/iPayLinks_list2.php | 336 ++++++++++++++++++ 3 files changed, 424 insertions(+) create mode 100644 webht/third_party/pay/views/iPayLinks_list2.php diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 115b51f1..d787b765 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -76,6 +76,22 @@ class IPayLinksService extends CI_Controller return; } + public function note_list2() + { + $data = array(); + $data["paytext"] = $this->payment_status(); + $data["keywords"] = $this->input->get_post("keywords"); + $data["date"] = $this->input->get_post("date"); + empty($data['date']) ? $data['date'] = date('Y-m-d') : false; + if (!empty($data['keywords'])) { + $data['notelist'] = $this->Note_model->search_key2($data['keywords']); + } else { + $data['notelist'] = $this->Note_model->search_date2($data['date']); + } + $this->load->view("iPayLinks_list2",$data); + return; + } + //失败记录列表 public function note_faillist() { $data = array(); diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 6bdf5fcf..fb6bb8f0 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -47,6 +47,13 @@ class Note_model extends CI_Model { $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC "; return $this->get_list(); } + public function search_date2($date) { + $this->init(); + $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; + $this->search = $search_sql; + $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC "; + return $this->get_list_with_order(); + } public function note($txn_id, $pn_id=null){ $this->init(); @@ -77,6 +84,19 @@ class Note_model extends CI_Model { $this->search = $search_sql; return $this->get_list(); } + public function search_key2($search_key) { + $this->init(); + $this->topnum = 300; //限制最大数量,防止查询单词过短 + $search_sql = ''; + $search_key = trim($search_key); + if (!empty($search_key)) { + $search_sql.=" AND ( IPL_dealId = '$search_key' + OR IPL_orderId like '%$search_key%' + OR IPL_memo like '%$search_key%' )"; + } + $this->search = $search_sql; + return $this->get_list_with_order(); + } public function note_exists($dealId) { @@ -158,6 +178,58 @@ class Note_model extends CI_Model { } } + /*! + * 查询异步通知记录 + * isRecord + * * 9999 已录入到订单收款记录表GAI; + * * 99999 APP组的收款记录, 由他们手动处理 + * * 10000 已忽略的退款记录; 关闭检测是否记录[已忽略] + * * 1 未录入到订单GAI + * @date 2018-07-27 + * @return [type] [description] + */ + public function get_list_with_order() + { + $sql = "SELECT + -- gai.GAI_SN, + -- gaib.GAI_SN, + -- COLI.COLI_ID, + case + when IPL_payType='pay' and (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 + when IPL_payType='pay' and coli.COLI_ID is not null then 99999 + when IPL_payType<>'pay' then 10000 + when IPL_sent=' closeRecord' then 10000 + else 1 + end isRecord, + ipl.* + from InfoManager.dbo.IPayLinksLog ipl + left join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on coli.COLI_ID=ipl.IPL_orderId and coli.COLI_Department=16 + left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 and ipl.IPL_payType='pay' + left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' + where 1=1 + and ( ipl.IPL_stateCode=2 or ipl.IPL_resultCode='0000') + and ( + 1=1 + $this->send + $this->search + $this->dealId + -- AND (IPL_noticeTime BETWEEN '2018-07-27 00:00:00' AND '2018-07-27 23:59:59' or IPL_sent<>'send') + or ((ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))=0 and IPL_payType='pay' and COLI.COLI_ID is null) + ) + order by isRecord asc,ipl.IPL_sent desc,IPL_sn desc"; + $query = $this->INFO->query($sql); + if ($this->topnum === 1) { + if ($query->num_rows() > 0) { + $row = $query->row(); + return $row; + } else { + return FALSE; + } + } else { + return $query->result(); + } + } + public function update_send($pn_txn_id, $pn_send) { $sql = " UPDATE IPayLinksLog diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php new file mode 100644 index 00000000..36c5a1e1 --- /dev/null +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -0,0 +1,336 @@ +<?php +/*! +* 查询支付记录 +* @author LYT <lyt@hainatravel.com> +* @date 2017-09-06 +*/ +?> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <title>iPayLinks Notes - China Highlights</title> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <meta name="referrer" content="always"> + <link href="//data.chinahighlights.com/css/min.php?f=/public/css/global.min.css,/css/ui.core.css,/css/ui.datepicker.css,/css/ui.theme.css,/css/calendar.css&amp;v=20170811" rel="stylesheet" type="text/css" /> + <style type="text/css" media="screen and (max-width:767px)"> + .pay_form .form-group{padding-left: 0!important;padding-right: 0!important;} + .pay_form .result_info{padding-top: 5px!important;} + </style> + <style type="text/css"> + p{margin-bottom: 8.5px;} + a{text-decoration: none;} + .text_padding {padding: 10px ;} + .btn_margin {margin-top: 5px;} + .navbar-header h1{display: inline-block;margin-left: 30px;margin-right: 30px;} + .pageTitle{margin-left: 300px;} + .pageTitle h1{color: #fff;border:none;font-size: 30px;} + .mobileTitle h1{color: #fff;border:none;font-size: 20px;} + .pay_form{padding: 30px 15px 15px 15px ;box-shadow: 0 0 10px #999;background: #fff;border-radius: 5px; } + .pay_form .form-group{padding-left: 50px;padding-right: 50px;} + .pay_form .control-label{text-align: left;} + .pay_form .result_info{padding-top: 25px;} + .pay_form .btn-danger{background: #a31022;} + .pay_footer{padding: 30px 0 10px;font-size: 12px;} + .line{border-bottom: 1px solid #cacaca;margin-left: 20px!important;margin-right: 20px!important;} + .btn{text-decoration: none;font-size: 14px;} + .mail_list {margin: 0;padding: 8px 15px;border-bottom: 1px solid #ccc;overflow: hidden; } + /*.input-group{border: 1px solid #ccc;}*/ + .input-group-btn{border: 1px solid #ccc;padding: 5px;} + .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} + .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;} + </style> + </head> + <body> + <div id="wrapper" class="chkVisible print-none"> + <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> + <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + <h1>iPayLinks Notes</h1> + + <div class="export_form_area "> + + <form class="form-inline " method="post" id="search_list2" action="/webht.php/apps/pay/ipaylinksservice/export_list/"> + <div class="form-group "> + <label for="from_date" class="">Date From</label> + <input type="text" class="form-control" id="from_date" name="from_date" required> + </div> + <div class="form-group "> + <label for="to_date" class="">To</label> + <input type="text" class="form-control" id="to_date" name="to_date" required> + </div> + <div class="form-group "> + <label for="currency" class="">Currency</label> + <select class="form-control" id="currency" name="currency"> + <option value="">All</option> + <option value="CNY">CNY</option> + <option value="USD">USD</option> + <option value="EUR">EUR</option> + <option value="CAD">CAD</option> + <option value="AUD">AUD</option> + <option value="GBP">GBP</option> + </select> + </div> + <button type="submit" class="btn btn-primary">Export</button> + </form> + + </div> + </div> + </div> + <div id="content"> + <div class="container-fluid marginTop"> + <div class="row"> + <!-- left --> + <div class="col-md-4 col-xs-24 print-none"> + <div class="row"> + <form method="post" id="search_list" action="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list/"> + <div class="input-group"> + <input type="text" name="keywords" value="<?php echo isset($search_key) ? $search_key : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> + <span class="input-group-addon search-btn" onclick="$('#search_list').submit();"></span> + </div> + <div id="datepicker"></div> + </form> + </div> + <p class="btn-lg"></p> + <ul class="list-unstyled hidden-xs links"> + <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list">&gt;全部收款邮件</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_faillist" >&gt;错误通知列表</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/batch_send_note" target="_blank">&gt;手动处理通知</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="http://share.chtcdn.com/info.php/sendmail/send_mail" target="_blank">&gt;发送邮件</a></li> + <li class="btn-lg"></li> + </ul> + <div class="well well-sm" > + <h4>通知状态:</h4> + <p>1.send 表示通知正确发送给外联</p> + <p>2.unsend 表示通知在等待处理,5~10分钟系统处理一遍</p> + <p>3.sendfail 状态的需要手工设置正确的订单号</p> + <p>4.Pending 还未到账,需要人工检查,确认支付或者取消,需要手工关闭此通知</p> + <p>5.Denied 银行拒付,需要手工关闭此通知</p> + </div> + </div> + <!-- end left --> + <div class=" pay_form_div col-sm-20 col-xs-24" style="min-height:1024px;border-left:1px solid #ddd;"> + <ul class="row mail_list hidden-xs"> + <a href="javascript:void(0);" style="cursor:default;color:#000;"> + <li class="col-sm-1 "><strong>#</strong></li> + <li class="col-sm-5 "><strong>主题</strong></li> + <li class="col-sm-5 "><strong>付款人</strong></li> + <li class="col-sm-4 "><strong>交易号</strong></li> + <li class="col-sm-3 "><strong>收单时间</strong></li> + <li class="col-sm-3 print-none"><strong>通知时间</strong></li> + <li class="col-sm-3 print-none"><strong>状态[通知/记录]</strong></li> + </a> + </ul> + <?php + foreach ($notelist as $key => $item) { + ?> + <ul class="row mail_list"> + + <li class="col-sm-1 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo ($key + 1); ?></li> + <li class="col-sm-5 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"> + <?php if ($item->IPL_dealId) { ?> + <a class="seen" target="_blank" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/receipt/<?php echo $item->IPL_dealId; ?>"> + <?php } else {?> + <a class="seen" target="_blank" href="#"> + <?php } ?> + <?php echo $item->IPL_orderId . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode ; ?> + </a></li> + + <li class="col-sm-5 nopadding-L" style="overflow:hidden;word-break: break-all;"> + <?php if ($item->IPL_payType == 'refund') { + echo "退款"; + } else { + echo $item->IPL_payerName . "<br>" . $item->IPL_payerEmail; + } ?> + </li> + + <li class="col-sm-4 nopadding-L" style="overflow:hidden;word-break: break-all;"><?php echo $item->IPL_dealId; ?></li> + + <li class="col-sm-3 nopadding-L" style="overflow:hidden;word-break: break-all;"><?php echo $item->IPL_acquiringTime; ?></li> + <li class="col-sm-3 nopadding-L print-none" ><?php echo $item->IPL_noticeTime; ?></li> + <li class="col-sm-3 print-none" > + <?php + $show_send = ''; + $class_css = ''; + if ($item->IPL_sent == 'send') { + $show_send = $item->IPL_sent; + } else if (strcmp(trim($item->IPL_stateCode), "2") && $item->IPL_stateCode != NULL) { + $class_css = 'btn-danger'; + $show_send = $paytext[intval(trim($item->IPL_stateCode))]; + } else { + $class_css = 'btn-danger'; + $show_send = $item->IPL_sent; + } + ?> + <a href="javascript:void(0);" title="<?php echo $item->IPL_resultMsg; ?>" onclick="show_order_modal('<?php echo $item->IPL_dealId; ?>', '<?php echo $item->IPL_orderId; ?>','<?php echo $item->IPL_noticeTime; ?>','<?php echo $item->IPL_orderId; ?>', '<?php echo $item->IPL_sn; ?>')" class="btn btn-sm <?php echo $class_css; ?>"><?php echo $show_send; ?></a> + <br> + <?php + $isRecord = ''; + $record_class = 'text_padding text-primary'; + if ($item->isRecord == '10000') { + $isRecord = '已忽略'; + } elseif ($item->isRecord == '99999') { + $isRecord = 'APP组处理'; + } elseif ($item->isRecord == '9999') { + $isRecord = '已录入'; + } else { + $isRecord = '未记录'; + $record_class = ' btn btn-sm btn_margin btn-danger '; + } + ?> + <a href="javascript:void(0);" onclick="" class="<?php echo $record_class; ?>"><?php echo $isRecord; ?></a> + </li> + </ul> + + <?php } ?> + </div> + <!-- </div> --> + <div class="pay_footer text-right print-none"> + <p>© 1998 China Highlights. + <a href="https://www.chinahighlights.com/privacy.htm" rel="nofollow">Privacy Statement</a> + </p> + </div> + </div> + </div> + </div> + <div id="main" class="container"> + </div> + + <!-- 手动设置订单号 --> + <div class="modal" id="modal_set_orderid" tabindex="-1" role="dialog" aria-labelledby="orderidModalLabel"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="orderidModalLabel">订单号修正操作</h4> + </div> + <div class="modal-body" id="modal_set_orderid_body"> + ... + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-primary pull-left" onclick="close_note();" >关闭此订单通知</button> + <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> + <button type="button" class="btn btn-primary" onclick="submit_order_modal();">保存并发送通知</button> + </div> + </div> + </div> + </div> + + </body> + <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js&v=20170811" type="text/javascript"></script> + <script type="text/javascript"> + jQuery.browser={};(function(){jQuery.browser.msie=false; jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})(); + </script> + <script src="//data.chinahighlights.com/js/min.php?f=/public/js/bootstrap.min.js,/js/jquery.form.min.js,/js/ui.core.js,/js/ui.datepicker.js,/js/jquery.ui.widget.min.js&v=20170811" type="text/javascript"></script> + <script language="javascript"> + $(document).ready(function() { + $('#datepicker').datepicker({ + defaultDate: '<?php echo $date; ?>', + dateFormat: 'yy-mm-dd', + onSelect: function(dateText) { + window.location.href = 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list?date=' + dateText; + } + }); + $(".ui-datepicker").css('width', '15.7em'); + + var dateFormat = "yy-mm-dd", + from = $( "#from_date" ) + .datepicker({ + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + to.datepicker( "option", "minDate", getDate( this ) ); + }), + to = $( "#to_date" ).datepicker({ + dateFormat: dateFormat, + changeMonth: true, + changeYear: true, + numberOfMonths: 1 + }) + .on( "change", function() { + from.datepicker( "option", "maxDate", getDate( this ) ); + }); + + function getDate( element ) { + var date; + try { + date = $.datepicker.parseDate( dateFormat, element.value ); + } catch( error ) { + date = null; + } + + return date; + } + }); + function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order, pn_id) { + if (pn_txn_id) { + $.ajax({ + type: "get", + dataType: "json", + url: '/webht.php/apps/pay/ipaylinksservice/note_modal/' + pn_txn_id + '/' + pn_invoice + '/' + pn_id, + success: function(data, textStatus) { + $('#modal_set_orderid_body').html(data); + $('#modal_set_orderid').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYCC...'); + } + }); + } else { + $.ajax({ + type: "get", + dataType: "json", + url: '/webht.php/apps/pay/ipaylinksservice/note_order_modal/' + old_order + '/' + pn_invoice + '/' + noticeTime, + success: function(data, textStatus) { + $('#modal_set_orderid_body').html(data); + $('#modal_set_orderid').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYCC...'); + } + }); + } + } + + function close_note() { + var pn_txn_id = $('#pn_txn_id').val(); + if (confirm('是否关闭此通知: ' + pn_txn_id)) { + $.ajax({ + type: "get", + dataType: "json", + url: 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/close_note/' + pn_txn_id, + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYCC...'); + } + }); + } + } + + function submit_order_modal() { + $('#form_modal_orderid').ajaxSubmit({ + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYCC...'); + }, + dataType: 'json', + timeout: 30000 + }); + return false; + } + </script> +</html> From 628148737408c59a8abc08504bce980ca408fe70 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 30 Jul 2018 09:35:16 +0800 Subject: [PATCH 114/382] =?UTF-8?q?ipaylinks=20=E5=88=97=E8=A1=A8=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 4 ++-- webht/third_party/pay/views/iPayLinks_list2.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index fb6bb8f0..ce206ad6 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -150,7 +150,7 @@ class Note_model extends CI_Model { FROM IPayLinksLog pn WHERE 1=1 and pn.IPL_payType='pay' - and (pn.IPL_stateCode=2 or pn.IPL_resultCode='0000') + and (pn.IPL_resultCode='0000') $this->send $this->search $this->dealId @@ -207,7 +207,7 @@ class Note_model extends CI_Model { left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 and ipl.IPL_payType='pay' left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' where 1=1 - and ( ipl.IPL_stateCode=2 or ipl.IPL_resultCode='0000') + and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') ) and ( 1=1 $this->send diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index 36c5a1e1..2b5dac34 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -182,7 +182,7 @@ $isRecord = '已录入'; } else { $isRecord = '未记录'; - $record_class = ' btn btn-sm btn_margin btn-danger '; + $record_class = ' btn btn-sm btn_margin btn-warning '; } ?> <a href="javascript:void(0);" onclick="" class="<?php echo $record_class; ?>"><?php echo $isRecord; ?></a> From ac00813dac054aa104f1ce5ade59e179d2325841 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 2 Aug 2018 09:37:49 +0800 Subject: [PATCH 115/382] =?UTF-8?q?trippest=20=E7=94=9F=E6=88=90=E5=8D=95?= =?UTF-8?q?=E5=9B=A2=E8=B4=A2=E5=8A=A1=E8=A1=A8;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 1 + .../controllers/order_finance.php | 203 ++++++++++++- .../models/orderFinance_model.php | 277 +++++++++++++++++- 3 files changed, 464 insertions(+), 17 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4cff577f..533fc820 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -76,6 +76,7 @@ class TulanduoApi extends CI_Controller */ public function get_orderlist() { + $order_number = $this->input->get_post("orderNum"); $startOrderDate = date('Y-m-d', strtotime("-2 days")); $endOrderDate = date('Y-m-d'); $startTravelDate = date('Y-m-d'); diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 401fd2a6..375a62b0 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -9,6 +9,7 @@ class Order_finance extends CI_Controller { * * 获取拼团总人数, 价格人等 * * 分别计算每次拼团成本 * * * 写入report_tour + * * 写入核算管理CK_GroupInfo * * 所有产品总成本 * * * 写入report_order * END @@ -32,22 +33,81 @@ class Order_finance extends CI_Controller { } + public function single_order_report($coli_sn=0) + { + $order_info = $this->OrderFinance_model->get_order_info($coli_sn); + if (empty($order_info)) { + return; + } + $report_order_exists = $this->OrderFinance_model->get_report_order($order_info->ordernumber); + if ( ! empty($report_order_exists)) { + return $this->output->set_content_type('application/json')->set_output(json_encode($report_order_exists)); + } + return $this->generate_report($order_info); + } + /*! * 单团财务表计算 * @date 2018-07-18 * @param integer $coli_sn 订单主表key - * @return [type] [description] + * 基本流程: + * * 获取拼团类别: PVT, 拼团 + * * 获取拼团总人数, 价格人等 + * * 分别计算每次拼团成本 + * * * 写入report_tour + * * 所有产品总成本 + * * * 写入核算管理CK_GroupInfo + * * * 写入单团财务表report_order + * END */ - public function single_order_report($coli_sn=0) + public function generate_report($order_info=array()) { + $coli_sn = $order_info->COLI_SN; + /** 单团财务表 */ + $report_order = array(); + $report_order['OrderYJLR'] = 0; //预计利润 + $report_order['basemoney'] = 0; // 总成本 + $report_order['money'] = 0; // 总收入, 实收金额 + $report_order['profitmoney'] = 0; // 利润 + $report_order['adultnumber'] = 0; + $report_order['childnumber'] = 0; + $report_order['babynumber'] = 0; + $report_order['ordernumber'] = $order_info->ordernumber; + $report_order['TuanName'] = $order_info->TuanName; + $report_order['operater'] = $order_info->operater; + $report_order['Agenter'] = $order_info->Agenter; + $report_order['ChinaName'] = $order_info->ChinaName; + $report_order['country'] = $order_info->country; + $report_order['reservedate'] = $order_info->reservedate; + $report_order['guesttype'] = $order_info->guesttype; + $report_order['RO_GRI_SN'] = $report_order['RO_CGI_SN'] = $order_info->GRI_SN; + // $report_order['basemoney'] = $order_info->basemoney; // 总成本 + // $report_order['OrderPrice'] = $order_info->OrderPrice; // 总报价 + /** 订单支付信息 */ + $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn); + $report_order['paymodenew'] = 0; + $report_order['money'] = $order_payment->SSmoney; + $report_order['RO_PayDescribe'] = $order_payment->payTypeDesc; + $report_order['paydate'] = $order_payment->patDate; + $report_order['OrderPrice'] = $report_order['money']; + /** 订单人数 */ + $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); + $report_order['adultnumber'] = $person_num->adult_num; + $report_order['childnumber'] = $person_num->child_num; + $ret = new stdClass(); + /** 图兰朵产品: 取拼团实际成本 */ $ret->combine_cost = array(); $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); +// $ret->x = $combineNo_arr; $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($combineNo_arr)); // $this->output->set_content_type('application/json')->set_output(json_encode($group_type_arr)); - $processed_code = array(); + $processed_code = array(); // 已处理的产品编号 foreach ($combineNo_arr as $kc => $vc) { + if (empty($vc->GCI_combineNo)) { + continue; + } if ($vc->GCI_groupType == 1) { $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); } else if ($vc->GCI_groupType == 2) { @@ -58,6 +118,115 @@ class Order_finance extends CI_Controller { $tmp_cost = null; } } + /** 保存图兰朵包价线路产品的成本到report_tour */ + // TODO + // pvt + $report_tour_pvt = array(); + if ( ! empty($ret->pvt)) { + $report_tour_pvt['ordernumber'] = $ret->pvt->coli_id; + $report_tour_pvt['tourCode'] = $ret->pvt->PAG_Code; + $report_tour_pvt['tourname'] = $ret->pvt->pag_name; + $report_tour_pvt['tourtime'] = $ret->pvt->startdate; + $report_tour_pvt['tourRSd'] = $ret->pvt->adult_num; + $report_tour_pvt['tourRSx'] = $ret->pvt->child_num; + $report_tour_pvt['tourCostRsd'] = $ret->pvt->person_cost; + $report_tour_pvt['tourCostRSx'] = $ret->pvt->person_cost; + $report_tour_pvt['tourcost'] = $ret->pvt->cost_sum; + $report_tour_pvt['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($ret->pvt->totalPrice); + $report_tour_pvt['tourProfit'] = ($report_tour_pvt['tourPrice']>0) ? bcsub($report_tour_pvt['tourPrice'], $report_tour_pvt['tourcost']) : 0; + $report_tour_pvt['tourProvide'] = $ret->pvt->vendor_name; + $report_tour_pvt['tourBZ'] = $ret->pvt->comment; + $report_tour_pvt['orderstats'] = 0; + // 成本详情 + $report_tour_pvt['RPT_Car'] = $ret->pvt->cost_category['touristCarOperations']; + $report_tour_pvt['RPT_Meal'] = $ret->pvt->cost_category['restraurantOperations']; + $report_tour_pvt['RPT_Ticket'] = $ret->pvt->cost_category['sceneryOperations']; + $report_tour_pvt['RPT_Service'] = $ret->pvt->cost_category['guiderOperations']; + $report_tour_pvt['RPT_MealGrants'] = $ret->pvt->cost_category['guide_meal']; + $report_tour_pvt['RPT_Water'] = $ret->pvt->cost_category['water']; + $report_tour_pvt['RPT_Other'] = $ret->pvt->cost_category['otherCosts']; + $report_tour_pvt['RPT_Total'] = $ret->pvt->cost_sum; + $report_tour_pvt['RPT_PersonGrade'] = $ret->pvt->person_grade; + $ret->report_tour[] = $report_tour_pvt; + // 计算订单总成本 + $report_order['basemoney'] = bcadd($report_order['basemoney'], $report_tour_pvt['tourcost']); + } + // 拼团 + if ( ! empty($ret->combine_cost)) { + foreach ($ret->combine_cost as $kcc => $cost) { + $cost_c = array(); + $cost_c['ordernumber'] = $cost->coli_id; + $cost_c['tourCode'] = implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))); + $cost_c['tourname'] = $cost->pag_name; + $cost_c['tourtime'] = $cost->startdate; + $cost_c['tourRSd'] = $cost->order_cost[0]->adult_num; + $cost_c['tourRSx'] = $cost->order_cost[0]->child_num; + $cost_c['tourCostRsd'] = $cost->person_cost; + $cost_c['tourCostRSx'] = $cost->person_cost; + $cost_c['tourcost'] = $cost->order_cost[0]->order_cost_sum; + $cost_c_price = 0; + foreach ($cost->order_cost as $koc => $coc) { + if ($coc->PAG_code === $coc->real_code) { + $cost_c_price = bcadd($cost_c_price, $coc->totalPrice); + } + } + $cost_c['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($cost_c_price); + $cost_c['tourProfit'] = ($cost_c['tourPrice']>0) ? bcsub($cost_c['tourPrice'], $cost_c['tourcost']) : 0; + $cost_c['tourProvide'] = $cost->vendor_name; + $cost_c['tourBZ'] = $cost->comment; + $cost_c['orderstats'] = 0; + // 成本详情 + $cost_c['RPT_Car'] = $cost->cost_category['touristCarOperations']; + $cost_c['RPT_Meal'] = $cost->cost_category['restraurantOperations']; + $cost_c['RPT_Ticket'] = $cost->cost_category['sceneryOperations']; + $cost_c['RPT_Service'] = $cost->cost_category['guiderOperations']; + $cost_c['RPT_MealGrants'] = $cost->cost_category['guide_meal']; + $cost_c['RPT_Water'] = $cost->cost_category['water']; + $cost_c['RPT_Other'] = $cost->cost_category['otherCosts']; + $cost_c['RPT_Total'] = $cost->cost_sum; + $cost_c['RPT_PersonGrade'] = $cost->person_num; + $ret->report_tour[] = $cost_c; + // 计算订单总成本 + $report_order['basemoney'] = bcadd($report_order['basemoney'], $cost_c['tourcost']); + } + } + /** 非图兰朵供应商的包价线路产品 */ + $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); + if ( ! empty($other_tour)) { + $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); + foreach ($ret->others as $kro => $vro) { + // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); + // test + $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->COLD_TotalCost); + } + } + /** 火车票预定 */ + $train_detail = $this->OrderFinance_model->get_order_detail($coli_sn, '2'); + if( ! empty($train_detail)) { + $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn); + foreach ($ret->train as $krt => $vrt) { + // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); + // test + $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); + } + } + /** 酒店预订 */ + $hotel_detail = $this->OrderFinance_model->get_order_detail($coli_sn, 'A'); + if ( ! empty($hotel_detail)) { + $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn); + foreach ($ret->hotel as $krh => $vrh) { + // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost); + // test + $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->COLD_TotalCost); + } + } + // 订单利润 + $report_order['profitmoney'] = $report_order['OrderYJLR'] = bcsub($report_order['money'], $report_order['basemoney']); + $report_order['builddate'] = date('Y-m-d H:i:s'); + $report_order['xh'] = $this->OrderFinance_model->get_report_order_xh(); //序号 + $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order); + // 核算管理 + // 更新report_order RO_CGI_SN $this->output->set_content_type('application/json')->set_output(json_encode($ret)); return; } @@ -67,7 +236,6 @@ class Order_finance extends CI_Controller { * @example 180426360,180516007U * @date 2018-07-18 * @param string $combineNo - * @return [type] [description] */ public function combine_basic($combineNo="", $coli_sn=0) { @@ -77,8 +245,7 @@ class Order_finance extends CI_Controller { return null; } $ret->coli_sn = $coli_sn; -// $ret->s = $all_orders; - $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); + $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); $all_pag = array_unique($all_pags); $combine_pag_arr = array(); $pvt_code = $this->forbidden_combine(); @@ -103,12 +270,13 @@ class Order_finance extends CI_Controller { } $extra_code_cold = array_merge($extra_code_cold, $extra_arr); } - // 避免覆盖key + // 不直接merge,避免覆盖key foreach ($extra_code_cold as $ke => $ve) { $all_orders[] = $ve; } // 重新计算重复次数 - $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); + $all_pags = array_filter(array_map(function($ele){ return $ele->PAG_Code;}, $all_orders)); +// $ret->s = $all_pags; // 重复的产品号; 可混拼的产品 $repeat_code = array(); $code_count = array_count_values($all_pags); @@ -140,11 +308,8 @@ class Order_finance extends CI_Controller { // $combine_pag_arr[] = array_diff($all_pag, $pvt_code); // 此处排除PVT租车产品 $combine_pag_arr[] = $all_pag; } -// $ret->s = $all_pags; -// $ret->q = $combine_pag_arr; $ret->combine_pags = my_array_unique($combine_pag_arr); $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品 -// $ret->q = my_array_unique($combine_pag_arr); $ret->person_num = 0; $ret->PAG_Code = ""; $ret->order_cost = array(); @@ -162,10 +327,14 @@ class Order_finance extends CI_Controller { $ret->startdate = $vo->COLD_StartDate; $tour_s = new stdClass(); if ($vo->COLI_SN == $coli_sn) { + $tour_s->COLD_SN = $vo->COLD_SN; $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $tour_s->adult_num = $vo->COLD_PersonNum; + $tour_s->child_num = $vo->COLD_ChildNum; $tour_s->PAG_code = $vo->PAG_Code; $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; + $tour_s->totalPrice = $vo->COLD_TotalPrice; $ret->order_cost[] = $tour_s; $ret->coli_id = $vo->coli_ID; } @@ -203,9 +372,17 @@ class Order_finance extends CI_Controller { } $ret->coli_sn = $coli_sn; $ret->coli_id = $all_orders[0]->coli_ID; + // 总报价 + $ret->totalPrice = 0; + foreach ($all_orders as $kal => $val) { + $ret->totalPrice = bcadd($ret->totalPrice, $val->COLD_TotalPrice); + } // 预定的产品数 $ret->tour_count = count(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $all_orders))); - $ret->person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); + $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); + $ret->person_num = $person_num->person_num; + $ret->adult_num = $person_num->adult_num; + $ret->child_num = $person_num->child_num; // $tour_s = new stdClass(); $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); $ret->startdate = $all_orders[0]->COLD_StartDate; @@ -213,7 +390,7 @@ class Order_finance extends CI_Controller { $ret->cost_category = $combine_cost->cost_category; $ret->cost_sum = $combine_cost->cost_sum; $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num); - $ret->comment = "PVT,共" . $ret->person_num . "人";// 150 + $ret->comment = "PVT,共" . $ret->person_num . "人次";// 150 $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); // TODO 限制50 diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index a52ed890..3c6dc195 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -6,6 +6,48 @@ class OrderFinance_model extends CI_Model { parent::__construct(); $this->load->helper('array'); $this->HT = $this->load->database('HT', TRUE); + bcscale(4); + } + + public function get_order_info($coli_sn=0) + { + $sql = "SELECT + coli.COLI_SN,coli.COLI_ID as ordernumber, + coli.COLI_WebCode as Agenter, + coli.COLI_ApplyDate as reservedate + ,coli.COLI_Cost as basemoney + ,coli.COLI_Price*6.77 OrderPrice + -- ,dbo.ConvertToRMB('USD',ISNULL(coli.COLI_Price,0)) OrderPrice + ,gri.GRI_SN ,gri.GRI_No as TuanName + ,opi.OPI_Name as ChinaName,opi.OPI_SN as operater,opi.OPI_DEI_SN + -- ,GETDATE() as builddate + ,gut.GUT_NationalityID,COI2_Country as country + ,( + select top 1 BPE_GuestType + from BIZ_ConfirmLineDetail + inner join BIZ_BookPeopleList on BPL_COLD_SN=COLD_SN + inner join BIZ_BookPeople on BPE_SN=BPL_BPE_SN + where COLD_COLI_SN=coli.COLI_SN + ) as guesttype + from BIZ_ConfirmLineInfo coli + inner join GRoupInfo gri on coli.COLI_GRI_SN=gri.GRI_SN and gri.DeleteFlag=0 + inner join OperatorInfo opi on opi.OPI_SN=coli.COLI_OPI_ID + left join BIZ_GUEST gut on gut.GUT_SN=coli.COLI_GUT_SN + left join CountryInfo2 on COI2_COI_SN=gut.GUT_NationalityID and COI2_LGC=2 + where coli.COLI_SN=$coli_sn "; + return $this->HT->query($sql)->row(); + } + + public function get_order_detail($coli_sn=0, $service_type='D', $tulanduo=null) + { + $vei_sql = ($tulanduo===null) ? "" : " AND COLD_PlanVEI_SN NOT IN (1343,29188,30548,30016) "; + $sql = "SELECT * from + BIZ_ConfirmLineDetail cold + where isnull(cold.DeleteFlag,0)=0 and COLD_ServiceType=? + and COLD_COLI_SN=$coli_sn + $vei_sql + "; + return $this->HT->query($sql, array($service_type))->result(); } /** 订单的所有拼团号 */ @@ -31,7 +73,7 @@ class OrderFinance_model extends CI_Model { ,COLI_SN,coli_ID--,COLI_ApplyDate,COLI_GroupCode ,COLD_SN,cold.COLD_ServiceSN--,COLD_EndDate ,PAG_Code ,pag_sub.PAGS_CN_Title, cold.COLD_StartDate,PAG_DefaultVEI_SN - ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate + ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate, cold.COLD_TotalPrice --,PAG_Title from GroupCombineInfo gci inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN @@ -80,12 +122,19 @@ class OrderFinance_model extends CI_Model { /** 获取订单总人数 */ public function get_order_person_num($coli_sn=0) { - $sql = "SELECT BPL_BPE_SN + $ret = new stdClass(); + $sql = "SELECT BPL_BPE_SN,bp.BPE_GuestType from BIZ_ConfirmLineDetail cold inner join BIZ_BookPeopleList bpl on bpl.BPL_COLD_SN=cold.COLD_SN + inner join biz_bookpeople bp on bp.BPE_SN=bpl.BPL_BPE_SN where cold.COLD_COLI_SN=$coli_sn - group by bpl.BPL_BPE_SN"; - return $this->HT->query($sql)->num_rows(); + group by bpl.BPL_BPE_SN,bp.BPE_GuestType"; + $query = $this->HT->query($sql); + $ret->person_num = $query->num_rows(); + $guest_type_cnt = array_count_values(array_map(function($ele) { return $ele->BPE_GuestType; }, $query->result())); + $ret->adult_num = $guest_type_cnt['1']; + $ret->child_num = $ret->person_num-$ret->adult_num; + return $ret; } /** 获取产品信息:产品名称,供应商等 */ @@ -98,6 +147,226 @@ class OrderFinance_model extends CI_Model { return $this->HT->query($sql)->result(); } + public function get_order_payment($coli_sn=0) + { + $ret = new stdClass(); + $sql = "SELECT gai.GAI_SSDate,gai.GAI_SSJE,gai.GAI_Type + from BIZ_GroupAccountInfo gai + where gai.GAI_COLI_SN=$coli_sn and gai.DeleteFlag=0"; + $payment = $this->HT->query($sql)->result(); + $ret->SSmoney = 0; + $ret->patDate = ""; + $ret->payType = ""; + $ret->payTypeDesc = ""; + if ( ! empty($payment)) { + foreach ($payment as $kp => $vp) { + $ret->SSmoney = bcadd($ret->SSmoney, $vp->GAI_SSJE); + } + $ret->patDate = $payment[0]->GAI_SSDate; + $ret->payType = $payment[0]->GAI_Type; + $ret->payTypeDesc = $this->HT + ->query("SELECT SYC2_CodeDiscribe + FROM V_System_Code + WHERE SYC_Type=15 AND LGC_LGC=2 + AND SYC_SN=? + ", array($ret->payType)) + ->row()->SYC2_CodeDiscribe; + } + return $ret; + } + + /** 图兰朵包价线路产品 */ + public function insert_report_tour_tulanduo($report_tour_arr=array()) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + foreach ($report_tour_arr as $krt => $vrt) { + $this->HT2->insert('tourmanager.dbo.Report_Tour', $vrt); + } + return TRUE; + } + + /** 火车票 */ + public function insert_report_train($coli_sn=0) + { + // INSERT INTO report_Train( + // OrderNumber, + // TrainNo, + // DepartureCity, + // ArrivalCity, + // DepartureDate, + // PassengerNo, + // adultPrice, + // TotalCost, + // TotalPrice, + // TrainProvide, + // TrainBZ, + // orderstats) + $sql = "SELECT + dbo.BIZ_ConfirmLineInfo.COLI_ID, + FlightsNo, + DepartureCity, + ArrivalCity, + left(convert(varchar,DepartureDate,120),10) as DepartureDate1, + isnull(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0) as PersonNum, + adultcost, + COLD_TotalCost as TotalCost, + COLD_TotalPrice*6.77 as TotalPrice, --test + VEI2_CompanyBN, + ' ' as TrainBZ, -- test + -- case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, + 0 as stat + from BIZ_ConfirmLineDetail + inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN + inner join BIZ_FlightsOrderInfo on FOI_COLD_SN = COLD_SN + left join VEndorInfo2 on COLD_PlanVEI_SN = VEI2_VEI_SN and VEI2_LGC = 2 + where COLD_COLI_SN = $coli_sn + and isnull(BIZ_ConfirmLineDetail.DeleteFlag,0)=0 + and COLD_ServiceType = '2' "; + return $this->HT->query($sql)->result(); + // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->row(); + } + + /** 酒店 */ + public function insert_report_hotel($coli_sn=0) + { + // INSERT INTO report_room( ordernumber, hotelName, cityName, hotelStar, roomtype, starttime, endtime, roomnumber, ExtraBedNumber, jianyeshu, jianyecost, ExtraBedCost, ExtraBedPrice, roomcost, roomprice, roomprofit, roomprovide, roombz, orderstats) + $sql = " + SELECT coli_id, + v2.VEI2_CompanyBN AS HotelName, + cityinfo2.CII2_Name AS cityname, + (SELECT SGC_ServiceGrade + FROM servicegradecode2 + WHERE SGC2_LGC=2 + AND SGC2_SGC_SN=Isnull(VEI_Grade,-1)) AS HStar, + (SELECT ROT2_TypeName + FROM roomtype2 + WHERE ROT2_ROT_SN=ISNULL(COLD_ServiceSN2,-1) + AND ROT2_LGC=1) AS RoomType, + left(convert(varchar,COLD_StartDate,120),10) AS COLD_StartDate, + left(convert(varchar,COLD_EndDate,120),10) AS COLD_EndDate, + COLD_Count, + isnull(HOI_ExtraNum,0) AS HOI_ExtraNum, + COLD_DayCount=DATEDIFF(DAY,COLD_StartDate,COLD_EndDate), + COLD_TotalCost, -- test + -- COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)), + 0 as ExtraBedCost, + 0 as ExtraBedPrice, + COLD_TotalCost, + COLD_TotalPrice*6.77 as COLD_TotalPrice, + (COLD_TotalPrice/1.03*6.77)-COLD_TotalCost as roomprofit, + VendorInfo2.VEI2_CompanyBN AS PlantVEI, + COLD_Describe, + 0 as stat + FROM BIZ_ConfirmLineDetail + INNER JOIN BIZ_ConfirmLineInfo ON COLD_COLI_SN=COLI_SN + LEFT JOIN BIZ_HotelOrderInfo ON HOI_COLD_SN = COLD_SN + LEFT JOIN VEndorInfo2 ON COLD_PlanVEI_SN = VEI2_VEI_SN AND VEI2_LGC = 2 + LEFT JOIN Vendorinfo2 AS V2 ON COLD_ServiceSN = V2.VEI2_VEI_SN AND V2.VEI2_LGC = 2 + LEFT JOIN VendorInfo ON COLD_ServiceSN = VEI_SN + LEFT JOIN cityinfo2 ON vendorinfo.VEI_CII_Name=cityinfo2.CII2_CII_SN AND cityinfo2.CII2_LGC=2 + WHERE COLD_COLI_SN = $coli_sn + AND BIZ_ConfirmLineDetail.DeleteFlag = 0 + AND COLD_ServiceType = 'A' + "; + return $this->HT->query($sql)->result(); + // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); + } + + /** 非图兰朵供应商的包价线路产品 */ + public function insert_report_tour_others($coli_sn=0) + { + // INSERT INTO report_tour( + // ordernumber, + // tourCode, + // tourname, + // tourtime, + // tourRSd, + // tourRSx, + // tourCostRsd, + // tourCostRSx, + // tourcost, + // tourPrice, + // tourProfit, + // tourProvide, + // tourBZ, + // orderstats) + $sql = "SELECT + dbo.BIZ_ConfirmLineInfo.COLI_ID, + dbo.BIZ_PackageInfo.PAG_Code, + dbo.BIZ_PackageInfo.PAG_Title, + SUBSTRING(CONVERT(varchar,dbo.BIZ_ConfirmLineDetail.COLD_StartDate, 120), 1, 10) AS COLD_StartDate, + dbo.BIZ_ConfirmLineDetail.COLD_PersonNum, + dbo.BIZ_ConfirmLineDetail.COLD_ChildNum, + --@AdultCost, + (select top 1 PKP_AdultCost + from BIZ_PackagePrice + where PKP_PAG_SN=COLD_ServiceSN + and PKP_VEI_SN=COLD_PlanVEI_SN + and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) + and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) + ORDER BY PKP_PriceGrade + ) as AdultCost, + --@ChildCost, + (select top 1 PKP_ChildCost + from BIZ_PackagePrice + where PKP_PAG_SN=COLD_ServiceSN + and PKP_VEI_SN=COLD_PlanVEI_SN + and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) + and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) + ORDER BY PKP_PriceGrade + ) as ChildCost, + dbo.BIZ_ConfirmLineDetail.COLD_TotalCost, + -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) COLD_TotalPrice, + -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as COLD_Profit, + dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77 COLD_TotalPrice, + (dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as COLD_Profit, + isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.') as VEI2_CompanyN, + SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as COLD_Describe1, + 0 as stat + FROM dbo.BIZ_ConfirmLineDetail + inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN + LEFT OUTER JOIN dbo.VEndorInfo2 ON dbo.VEndorInfo2.VEI2_VEI_SN = dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN AND dbo.VEndorInfo2.VEI2_LGC = 2 + INNER JOIN dbo.BIZ_PackageInfo ON dbo.BIZ_ConfirmLineDetail.COLD_ServiceSN = dbo.BIZ_PackageInfo.PAG_SN + WHERE (dbo.BIZ_ConfirmLineDetail.COLD_ServiceType='D') + AND (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0) + AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) + and dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN not in (1343,29188,30548,30016) "; + return $this->HT->query($sql)->result(); + // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_tour inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); + // $this->HT->query($sql); + return TRUE; + } + + public function insert_report_order($report_order_arr=array()) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + $this->HT2->insert('tourmanager.dbo.report_order', $report_order_arr); + return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber=? order by orderID desc",array($report_order_arr['ordernumber']))->row(); + // return TRUE; + } + + public function get_report_order($coli_id=0) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' order by orderID desc")->row(); + } + + public function convert_to_RMB($money=0, $fromCurrency='USD') + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + // [dbo].[ConvertToRMB](@TargetCurrency varchar(6), @SourceMoney decimal(18,5)) + return $this->HT2->query("SELECT tourmanager.dbo.[ConvertToRMB]('$fromCurrency',$money) as rmb ")->row()->rmb; + } + + public function get_report_order_xh() + { + return $this->HT->query("SELECT MAX(xh)+1 as newxh from report_order")->row()->newxh; + } + } /* End of file orderFinance_model.php */ From 403f42a34f5d0c7465fb2d23ed7e701ff8116f95 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 2 Aug 2018 10:08:05 +0800 Subject: [PATCH 116/382] =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=9B=BE=E5=85=B0?= =?UTF-8?q?=E6=9C=B5=E8=AE=A2=E5=8D=95=20=E4=BF=AE=E6=94=B9=E5=8F=82?= =?UTF-8?q?=E6=95=B0,=E6=8C=87=E5=AE=9A=E6=9F=A5=E8=AF=A2=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 28 ++++++++++++------- .../models/TuLanDuo_queryContentBuilder.php | 11 ++++++++ 2 files changed, 29 insertions(+), 10 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 533fc820..f5834f7c 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -74,9 +74,9 @@ class TulanduoApi extends CI_Controller * 获取订单列表 * @date 2018-05-02 */ - public function get_orderlist() + public function get_orderlist($order_number=null) { - $order_number = $this->input->get_post("orderNum"); + // $order_number = $this->input->get_post("orderNo"); $startOrderDate = date('Y-m-d', strtotime("-2 days")); $endOrderDate = date('Y-m-d'); $startTravelDate = date('Y-m-d'); @@ -85,15 +85,19 @@ class TulanduoApi extends CI_Controller ->setKey($this->key) ->setPageSize(20) ->setPageIndex(1) ; - $get_type = rand(0, 1); // 需要按预定时间和出发时间, 避免有漏的 - if ($get_type === 0) { - log_message('error','get_orderlist From TuLanDuo By travel Date' ); - $this->tld_order->setStartTravelDate($startTravelDate) - ->setEndTravelDate($endTravelDate) ; + if ( ! empty($order_number)) { + $this->tld_order->setAgcOrderNo($order_number); } else { - log_message('error','get_orderlist From TuLanDuo By order Date' ); - $this->tld_order->setStartOrderDate($startOrderDate) - ->setEndOrderDate($endOrderDate) ; + $get_type = rand(0, 1); // 需要按预定时间和出发时间, 避免有漏的 + if ($get_type === 0) { + log_message('error','get_orderlist From TuLanDuo By travel Date' ); + $this->tld_order->setStartTravelDate($startTravelDate) + ->setEndTravelDate($endTravelDate) ; + } else { + log_message('error','get_orderlist From TuLanDuo By order Date' ); + $this->tld_order->setStartOrderDate($startOrderDate) + ->setEndOrderDate($endOrderDate) ; + } } $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); @@ -101,6 +105,10 @@ class TulanduoApi extends CI_Controller log_message('error','TulanduoApi get_orderlist failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); return; } + if ($resp_arr["responseData"]["totalRows"] == 0) { + log_message('error','TulanduoApi get_orderlist 0. '); + return; + } $all_list = $resp_arr["responseData"]["orders"]; $order_to_HT = array_map( function($ele){ diff --git a/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php index 153a3e9b..22ea575e 100644 --- a/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php +++ b/webht/third_party/trippestOrderSync/models/TuLanDuo_queryContentBuilder.php @@ -125,6 +125,17 @@ class TuLanDuo_queryContentBuilder extends CI_Model $this->bizContentarr['orderId'] = $orderId; return $this; } + + public function getAgcOrderNo() + { + return $this->agcOrderNo; + } + public function setAgcOrderNo($agcOrderNo) + { + $this->agcOrderNo = $agcOrderNo; + $this->bizContentarr['agcOrderNo'] = $agcOrderNo; + return $this; + } // 其他还没用到先不写了... } From 8783f8797277af354236b0d42c291e09d433dd26 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 2 Aug 2018 10:39:30 +0800 Subject: [PATCH 117/382] =?UTF-8?q?=E5=9B=BE=E5=85=B0=E6=9C=B5=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E8=AE=A2=E5=8D=95,=E7=9B=B4=E6=8E=A5=E5=86=99?= =?UTF-8?q?=E5=85=A5=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/TulanduoApi.php | 3 ++- .../trippestOrderSync/controllers/order_finance.php | 2 +- webht/third_party/trippestOrderSync/models/orders_model.php | 4 ++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index f5834f7c..adb2322a 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -200,9 +200,10 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_servicetype = 'D'; $this->Orders_model->BIZ_COLI_ConfirmType = 52001; $this->Orders_model->BIZ_COLI_Memo = ""; - $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步测试" . $vo["orderId"] . ";线路:" . $vo['routeName'] . "; 团名: " . $vo['agcOrderNo']; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $vo["orderId"] . ";线路:" . $vo['routeName'] . "; 团名: " . $vo['agcOrderNo']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $this->Orders_model->BIZ_COLI_OPI_ID = 435; + $this->Orders_model->BIZ_COLI_PayManner = 15006; $coli_sn[] = $this->Orders_model->biz_confirm_save(); /**BIZ_ConfirmLineDetail*/ $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 375a62b0..a3c1eff9 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -226,7 +226,7 @@ class Order_finance extends CI_Controller { $report_order['xh'] = $this->OrderFinance_model->get_report_order_xh(); //序号 $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order); // 核算管理 - // 更新report_order RO_CGI_SN + $this->output->set_content_type('application/json')->set_output(json_encode($ret)); return; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index d14b0929..c047b885 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -543,6 +543,7 @@ class Orders_model extends CI_Model { var $BIZ_COLI_Memo; var $BIZ_COLI_GRI_SN; var $BIZ_COLI_GroupCode=''; + var $BIZ_COLI_PayManner; var $BIZ_COLI_State; var $BIZ_COLI_OPI_ID; @@ -581,6 +582,7 @@ class Orders_model extends CI_Model { . " COLI_GRI_SN, \n" . " COLI_OPI_ID, \n" . " COLI_GroupCode, \n" + . " COLI_PayManner, \n" . " COLI_OriginalText \n" . ") \n" . "VALUES \n" @@ -608,6 +610,7 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " N?, \n" + . " ?, \n" . " N? \n" . ")"; $query = $this->HT->query($sql, array( @@ -636,6 +639,7 @@ class Orders_model extends CI_Model { $this->BIZ_COLI_GRI_SN, $this->BIZ_COLI_OPI_ID, $this->BIZ_COLI_GroupCode, + $this->BIZ_COLI_PayManner, $this->BIZ_COLI_OriginalText )); $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); From 969c8514e6015a61edb0f1583a75cfa5fb111d71 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 2 Aug 2018 12:00:35 +0800 Subject: [PATCH 118/382] =?UTF-8?q?=E9=87=8D=E6=96=B0=E7=94=9F=E6=88=90?= =?UTF-8?q?=E5=88=99=E6=9B=B4=E6=96=B0;=20=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 20 +- .../models/orderFinance_model.php | 176 +++++++++++++++++- 2 files changed, 182 insertions(+), 14 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index a3c1eff9..80be305b 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -9,7 +9,6 @@ class Order_finance extends CI_Controller { * * 获取拼团总人数, 价格人等 * * 分别计算每次拼团成本 * * * 写入report_tour - * * 写入核算管理CK_GroupInfo * * 所有产品总成本 * * * 写入report_order * END @@ -46,6 +45,11 @@ class Order_finance extends CI_Controller { return $this->generate_report($order_info); } + public function regenerate_report($coli_sn=0) + { + return $this->generate_report($order_info, TRUE); + } + /*! * 单团财务表计算 * @date 2018-07-18 @@ -60,7 +64,7 @@ class Order_finance extends CI_Controller { * * * 写入单团财务表report_order * END */ - public function generate_report($order_info=array()) + public function generate_report($order_info=array(), $update_flag=false) { $coli_sn = $order_info->COLI_SN; /** 单团财务表 */ @@ -190,10 +194,13 @@ class Order_finance extends CI_Controller { $report_order['basemoney'] = bcadd($report_order['basemoney'], $cost_c['tourcost']); } } + /** 开始写入数据库 */ + /** 图兰朵供应商 */ + $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour, $update_flag); /** 非图兰朵供应商的包价线路产品 */ $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); if ( ! empty($other_tour)) { - $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); + $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn, $update_flag); foreach ($ret->others as $kro => $vro) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); // test @@ -203,7 +210,7 @@ class Order_finance extends CI_Controller { /** 火车票预定 */ $train_detail = $this->OrderFinance_model->get_order_detail($coli_sn, '2'); if( ! empty($train_detail)) { - $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn); + $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn, $update_flag); foreach ($ret->train as $krt => $vrt) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); // test @@ -213,7 +220,7 @@ class Order_finance extends CI_Controller { /** 酒店预订 */ $hotel_detail = $this->OrderFinance_model->get_order_detail($coli_sn, 'A'); if ( ! empty($hotel_detail)) { - $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn); + $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn, $update_flag); foreach ($ret->hotel as $krh => $vrh) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost); // test @@ -224,8 +231,7 @@ class Order_finance extends CI_Controller { $report_order['profitmoney'] = $report_order['OrderYJLR'] = bcsub($report_order['money'], $report_order['basemoney']); $report_order['builddate'] = date('Y-m-d H:i:s'); $report_order['xh'] = $this->OrderFinance_model->get_report_order_xh(); //序号 - $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order); - // 核算管理 + $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order, $update_flag); $this->output->set_content_type('application/json')->set_output(json_encode($ret)); return; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 3c6dc195..20535459 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -176,18 +176,27 @@ class OrderFinance_model extends CI_Model { } /** 图兰朵包价线路产品 */ - public function insert_report_tour_tulanduo($report_tour_arr=array()) + public function insert_report_tour_tulanduo($report_tour_arr=array(), $update_flag=false) { $this->HT2 = $this->load->database('INFO', TRUE); // test foreach ($report_tour_arr as $krt => $vrt) { - $this->HT2->insert('tourmanager.dbo.Report_Tour', $vrt); + if ($update_flag === TRUE) { + $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "'"; + $update_sql = $this->HT2->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); + $this->HT2->query($update_sql); + } else { + $this->HT2->insert('tourmanager.dbo.Report_Tour', $vrt); + } } return TRUE; } /** 火车票 */ - public function insert_report_train($coli_sn=0) + public function insert_report_train($coli_sn=0, $update_flag=false) { + if ($update_flag === TRUE) { + return $this->update_report_train($coli_sn); + } // INSERT INTO report_Train( // OrderNumber, // TrainNo, @@ -225,10 +234,46 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test return $this->HT->query($sql)->result(); // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->row(); } + public function update_report_train($coli_sn=0) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + $update_data = $this->get_train_cost($coli_sn); + $where = " OrderNumber='" . $update_data->OrderNumber . "' AND TrainNo='" . $update_data->TrainNo . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_Train', $update_data, $where); + return $this->HT2->query($update_sql); + } + public function get_train_cost($coli_sn=0) + { + $sql = "SELECT + dbo.BIZ_ConfirmLineInfo.COLI_ID OrderNumber, + FlightsNo TrainNo, + DepartureCity, + ArrivalCity, + left(convert(varchar,DepartureDate,120),10) as DepartureDate, + isnull(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0) as PassengerNo, + adultcost adultPrice, + COLD_TotalCost as TotalCost, + COLD_TotalPrice*6.77 as TotalPrice, --test + VEI2_CompanyBN TrainProvide, + ' ' as TrainBZ, -- test + -- case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, + 0 as orderstats + from BIZ_ConfirmLineDetail + inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN + inner join BIZ_FlightsOrderInfo on FOI_COLD_SN = COLD_SN + left join VEndorInfo2 on COLD_PlanVEI_SN = VEI2_VEI_SN and VEI2_LGC = 2 + where COLD_COLI_SN = $coli_sn + and isnull(BIZ_ConfirmLineDetail.DeleteFlag,0)=0 + and COLD_ServiceType = '2' "; + return $this->HT->query($sql)->row(); + } /** 酒店 */ - public function insert_report_hotel($coli_sn=0) + public function insert_report_hotel($coli_sn=0, $update_flag=false) { + if ($update_flag === TRUE) { + return $this->update_report_hotel($coli_sn); + } // INSERT INTO report_room( ordernumber, hotelName, cityName, hotelStar, roomtype, starttime, endtime, roomnumber, ExtraBedNumber, jianyeshu, jianyecost, ExtraBedCost, ExtraBedPrice, roomcost, roomprice, roomprofit, roomprovide, roombz, orderstats) $sql = " SELECT coli_id, @@ -271,10 +316,63 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test return $this->HT->query($sql)->result(); // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); } + public function update_report_hotel($coli_sn) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + $update_data = $this->get_hotel_cost($coli_sn); + $where = " ordernumber='" . $update_data->ordernumber . "' AND hotelName='" . $update_data->hotelName . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_room', $update_data, $where); + return $this->HT2->query($update_sql); + } + public function get_hotel_cost($coli_sn) + { + $sql = " + SELECT coli_id ordernumber, + v2.VEI2_CompanyBN AS hotelName, + cityinfo2.CII2_Name AS cityName, + (SELECT SGC_ServiceGrade + FROM servicegradecode2 + WHERE SGC2_LGC=2 + AND SGC2_SGC_SN=Isnull(VEI_Grade,-1)) AS hotelStar, + (SELECT ROT2_TypeName + FROM roomtype2 + WHERE ROT2_ROT_SN=ISNULL(COLD_ServiceSN2,-1) + AND ROT2_LGC=1) AS roomtype, + left(convert(varchar,COLD_StartDate,120),10) AS starttime, + left(convert(varchar,COLD_EndDate,120),10) AS endtime, + COLD_Count roomnumber, + isnull(HOI_ExtraNum,0) AS ExtraBedNumber, + COLD_DayCount=DATEDIFF(DAY,COLD_StartDate,COLD_EndDate) as jianyeshu, + COLD_TotalCost jianyecost, -- test + -- COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)) as jianyecost, + 0 as ExtraBedCost, + 0 as ExtraBedPrice, + COLD_TotalCost roomcost, + COLD_TotalPrice*6.77 as roomprice, + (COLD_TotalPrice/1.03*6.77)-COLD_TotalCost as roomprofit, + VendorInfo2.VEI2_CompanyBN AS roomprovide, + COLD_Describe roombz, + 0 as orderstats + FROM BIZ_ConfirmLineDetail + INNER JOIN BIZ_ConfirmLineInfo ON COLD_COLI_SN=COLI_SN + LEFT JOIN BIZ_HotelOrderInfo ON HOI_COLD_SN = COLD_SN + LEFT JOIN VEndorInfo2 ON COLD_PlanVEI_SN = VEI2_VEI_SN AND VEI2_LGC = 2 + LEFT JOIN Vendorinfo2 AS V2 ON COLD_ServiceSN = V2.VEI2_VEI_SN AND V2.VEI2_LGC = 2 + LEFT JOIN VendorInfo ON COLD_ServiceSN = VEI_SN + LEFT JOIN cityinfo2 ON vendorinfo.VEI_CII_Name=cityinfo2.CII2_CII_SN AND cityinfo2.CII2_LGC=2 + WHERE COLD_COLI_SN = $coli_sn + AND BIZ_ConfirmLineDetail.DeleteFlag = 0 + AND COLD_ServiceType = 'A' + "; + return $this->HT->query($sql)->row(); + } /** 非图兰朵供应商的包价线路产品 */ - public function insert_report_tour_others($coli_sn=0) + public function insert_report_tour_others($coli_sn=0, $update_flag=false) { + if ($update_flag === TRUE) { + return $this->update_report_tour_others($coli_sn); + } // INSERT INTO report_tour( // ordernumber, // tourCode, @@ -338,14 +436,78 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test return $this->HT->query($sql)->result(); // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_tour inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); // $this->HT->query($sql); + return TRUE; } + public function update_report_tour_others($coli_sn) + { +$this->HT2 = $this->load->database('INFO', TRUE); // test + $update_data = $this->get_report_tour_others_cost($coli_sn); + $where = " ordernumber='" . $update_data->ordernumber . "' AND tourCode='" . $update_data->tourCode . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_tour', $update_data, $where); + return $this->HT2->query($update_sql); + } + public function get_report_tour_others_cost($coli_sn=0) + { + $sql = "SELECT + dbo.BIZ_ConfirmLineInfo.COLI_ID ordernumber, + dbo.BIZ_PackageInfo.PAG_Code tourCode, + dbo.BIZ_PackageInfo.PAG_Title tourname, + SUBSTRING(CONVERT(varchar,dbo.BIZ_ConfirmLineDetail.COLD_StartDate, 120), 1, 10) AS tourtime, + dbo.BIZ_ConfirmLineDetail.COLD_PersonNum tourRSd, + dbo.BIZ_ConfirmLineDetail.COLD_ChildNum tourRSx, + --@AdultCost, + (select top 1 PKP_AdultCost + from BIZ_PackagePrice + where PKP_PAG_SN=COLD_ServiceSN + and PKP_VEI_SN=COLD_PlanVEI_SN + and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) + and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) + ORDER BY PKP_PriceGrade + ) as tourCostRsd, + --@ChildCost, + (select top 1 PKP_ChildCost + from BIZ_PackagePrice + where PKP_PAG_SN=COLD_ServiceSN + and PKP_VEI_SN=COLD_PlanVEI_SN + and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) + and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) + and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) + ORDER BY PKP_PriceGrade + ) as tourCostRSx, + dbo.BIZ_ConfirmLineDetail.COLD_TotalCost tourcost, + -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) tourPrice, + -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, + dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77 tourPrice, + (dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, + isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.') as tourProvide, + SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as tourBZ, + 0 as orderstats + FROM dbo.BIZ_ConfirmLineDetail + inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN + LEFT OUTER JOIN dbo.VEndorInfo2 ON dbo.VEndorInfo2.VEI2_VEI_SN = dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN AND dbo.VEndorInfo2.VEI2_LGC = 2 + INNER JOIN dbo.BIZ_PackageInfo ON dbo.BIZ_ConfirmLineDetail.COLD_ServiceSN = dbo.BIZ_PackageInfo.PAG_SN + WHERE (dbo.BIZ_ConfirmLineDetail.COLD_ServiceType='D') + AND (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0) + AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) + and dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN not in (1343,29188,30548,30016) "; + return $this->HT->query($sql)->row(); + } - public function insert_report_order($report_order_arr=array()) + public function insert_report_order($report_order_arr=array(), $update_flag=false) { $this->HT2 = $this->load->database('INFO', TRUE); // test + if ($update_flag === TRUE) { + $where = " ordernumber='" . $report_order_arr['ordernumber'] . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_order', $report_order_arr, $where); + $this->HT2->query($update_sql); + } $this->HT2->insert('tourmanager.dbo.report_order', $report_order_arr); - return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber=? order by orderID desc",array($report_order_arr['ordernumber']))->row(); + return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber=? order by orderID desc", + array($report_order_arr['ordernumber']))->row(); // return TRUE; } From 70333b9905d4dba6e6df8bff8809fdf83392ab5b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 2 Aug 2018 16:27:42 +0800 Subject: [PATCH 119/382] =?UTF-8?q?ipaylinks=20=E5=A2=9E=E5=8A=A0=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E6=98=AF=E5=90=A6=E5=B7=B2=E5=BD=95=E5=85=A5=E8=AE=A2?= =?UTF-8?q?=E5=8D=95,=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E7=A7=BB?= =?UTF-8?q?=E4=BA=A4=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 116 +++++++++++++++--- .../pay/models/IPayLinks_model.php | 17 ++- webht/third_party/pay/models/note_model.php | 20 +-- webht/third_party/pay/views/gai_setting.php | 38 ++++++ .../third_party/pay/views/iPayLinks_list.php | 2 + .../third_party/pay/views/iPayLinks_list2.php | 75 ++++++++++- webht/third_party/pay/views/note_setting.php | 4 +- 7 files changed, 239 insertions(+), 33 deletions(-) create mode 100644 webht/third_party/pay/views/gai_setting.php diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index d787b765..6db9d8b6 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -60,7 +60,7 @@ class IPayLinksService extends CI_Controller $this->note_list(); } - public function note_list() + public function note_list2() { $data = array(); $data["paytext"] = $this->payment_status(); @@ -76,7 +76,7 @@ class IPayLinksService extends CI_Controller return; } - public function note_list2() + public function note_list() { $data = array(); $data["paytext"] = $this->payment_status(); @@ -507,23 +507,25 @@ class IPayLinksService extends CI_Controller $M_State = 0; $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note'); // 2.给客人发邮件,通知账单 - $toName2 = !empty($item->IPL_payerName) ? $item->IPL_payerName : ''; - $toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : ''; - // Zac170919039_T(订单号) / 996.00USD / iPayLinks - $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights'; - // lang - $remark_info = json_decode($item->IPL_memo); - (isset($remark_info->remark)) ? $remark_info = json_decode($remark_info->remark) : NULL; - $ln = (isset($remark_info->ln)) ? $remark_info->ln : "en"; - $this->lang->load('ipl_common',$ln); - $this->lang->load('ipl_buyer_email',$ln); - $item->text = $this->lang->language; - // # lang end - $body2 = $this->load->view('receipt_buyer', $item, true); - $M_RelatedInfo2 = $item->IPL_sn; - $M_AddTime2 = $item->IPL_completeTime; - $M_State2 = 0; - $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'China Highlights Has Received Your Payment'); + if (empty($pn_txn_id)) { + $toName2 = !empty($item->IPL_payerName) ? $item->IPL_payerName : ''; + $toEmail2 = !empty($item->IPL_payerEmail) ? $item->IPL_payerEmail : ''; + // Zac170919039_T(订单号) / 996.00USD / iPayLinks + $subject2 = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $item->IPL_currencyCode . ' / China Highlights'; + // lang + $remark_info = json_decode($item->IPL_memo); + (isset($remark_info->remark)) ? $remark_info = json_decode($remark_info->remark) : NULL; + $ln = (isset($remark_info->ln)) ? $remark_info->ln : "en"; + $this->lang->load('ipl_common',$ln); + $this->lang->load('ipl_buyer_email',$ln); + $item->text = $this->lang->language; + // # lang end + $body2 = $this->load->view('receipt_buyer', $item, true); + $M_RelatedInfo2 = $item->IPL_sn; + $M_AddTime2 = $item->IPL_completeTime; + $M_State2 = 0; + $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName2, $toEmail2, $subject2, $body2, $M_RelatedInfo2, $M_State2, $M_AddTime2, 'China Highlights Has Received Your Payment'); + } // ---- 添加邮件发送记录 end $this->Note_model->update_send($item->IPL_dealId, 'send'); @@ -915,6 +917,82 @@ class IPayLinksService extends CI_Controller ); } + public function gai_modal($pn_txn_id=null, $pn_invoice=null, $pn_id = null, $neworder=null) + { + $data = array(); + $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); + $orderid_info = $this->analysis_orderid($pn_invoice); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->IPayLinks_model->get_money_t($pn_txn_id); + } elseif ($orderid_info->ordertype === 'B') { + $data['gai_info'] = $this->IPayLinks_model->get_money_b($pn_txn_id); + } + } + $data['old_order'] = $pn_invoice; + $data['new_order'] = $neworder; + $data['order_info'] = null; + if ($neworder !== null) { + $neworder_id = $this->analysis_orderid($neworder); + $neworder_id = json_decode($neworder_id); + if ( ! empty($neworder_id)) { + $data['order_info'] = $this->IPayLinks_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype); + } + } + echo json_encode($this->load->view('gai_setting', $data, true)); + } + + public function gai_modal_save() + { + $data = array(); + $pn_txn_id = $this->input->post('pn_txn_id'); + $pn_id = $this->input->post('pn_id'); + $neworder = $this->input->post('pn_invoice'); + + $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); + $orderid_info = $this->analysis_orderid($data['note'][0]->IPL_orderId); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->IPayLinks_model->get_money_t($pn_txn_id); + $this->IPayLinks_model->delete_money_t($pn_txn_id); + } elseif ($orderid_info->ordertype === 'B') { + $data['gai_info'] = $this->IPayLinks_model->get_money_b($pn_txn_id); + $this->IPayLinks_model->delete_money_b($pn_txn_id); + } + } + + if (!empty($pn_txn_id) && !empty($neworder)) { + $orderid_info = $this->analysis_orderid($neworder); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + if (!empty($advisor_info)) { + $this->Note_model->set_invoice($pn_txn_id, $neworder); + $this->batch_send_note($pn_txn_id); + echo json_encode('修改成功!'); + return true; + } + } + } + echo json_encode('没找到数据!'); + return; + } + + public function closeGai($pn_txn_id) + { + $data = array(); + $data['note'] = $this->Note_model->note($pn_txn_id); + if (!empty($data['note'])) { + $this->Note_model->update_send($pn_txn_id, 'closeRecord'); + echo json_encode('该收款记录已经忽略!'); + return true; + } + echo json_encode('没找到数据!'); + return; + } + //获取note详情,以便后续修改各项数据 public function note_modal($pn_txn_id = false, $pn_invoice = false, $pn_id = null) { $data = array(); diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 56096204..ff8af136 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -311,7 +311,7 @@ class IPayLinks_model extends CI_Model { public function get_money_t($pn_invoice) { $sql = "SELECT GroupAccountInfo.* from GroupAccountInfo - where GAI_Type='15018' and GAI_AccreditNo=? + where GAI_Type='15018' and DeleteFlag=0 and GAI_AccreditNo=? "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -321,7 +321,7 @@ class IPayLinks_model extends CI_Model { public function get_money_b($pn_invoice) { $sql = "SELECT BIZ_GroupAccountInfo.* from BIZ_GroupAccountInfo - where GAI_Type='15018' and GAI_AccreditNo=? + where GAI_Type='15018' and DeleteFlag=0 and GAI_AccreditNo=? "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -340,4 +340,17 @@ class IPayLinks_model extends CI_Model { $query = $this->HT->query($sql, array($entry_sum_RMB, $pn_invoice)); return $query; } + /** 删除收款记录 */ + public function delete_money_t($deadId) + { + $sql = "UPDATE GroupAccountInfo SET DeleteFlag=1 WHERE GAI_Type='15018' and GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } + public function delete_money_b($deadId) + { + $sql = "UPDATE BIZ_GroupAccountInfo SET DeleteFlag=1 WHERE GAI_Type='15018' and GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index ce206ad6..ba7942ca 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -9,6 +9,7 @@ class Note_model extends CI_Model { var $orderby = null; var $send = null; var $search = null; + var $date = null; var $dealId = null; var $payment_status = null; @@ -21,6 +22,7 @@ class Note_model extends CI_Model { $this->topnum = null; $this->send = null; $this->search = null; + $this->date = null; $this->payment_status = null; $this->dealId = null; $this->orderby = ' ORDER BY IPL_sent DESC ,IPL_sn DESC '; @@ -42,15 +44,16 @@ class Note_model extends CI_Model { public function search_date($date) { $this->init(); - $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; + $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ) "; $this->search = $search_sql; + $this->send = " AND (IPL_sent<>'closeRecord') "; $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC "; return $this->get_list(); } public function search_date2($date) { $this->init(); - $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' or IPL_sent<>'send') "; - $this->search = $search_sql; + $search_sql = " AND (IPL_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' ) "; + $this->date = $search_sql; $this->orderby=" ORDER BY IPL_sent DESC ,IPL_sn DESC "; return $this->get_list_with_order(); } @@ -198,7 +201,7 @@ class Note_model extends CI_Model { when IPL_payType='pay' and (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 when IPL_payType='pay' and coli.COLI_ID is not null then 99999 when IPL_payType<>'pay' then 10000 - when IPL_sent=' closeRecord' then 10000 + when IPL_sent='closeRecord' then 10000 else 1 end isRecord, ipl.* @@ -208,13 +211,14 @@ class Note_model extends CI_Model { left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' where 1=1 and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') ) + $this->send + $this->search + $this->dealId and ( 1=1 - $this->send - $this->search - $this->dealId + $this->date -- AND (IPL_noticeTime BETWEEN '2018-07-27 00:00:00' AND '2018-07-27 23:59:59' or IPL_sent<>'send') - or ((ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))=0 and IPL_payType='pay' and COLI.COLI_ID is null) + or ((ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))=0 and IPL_payType='pay' AND (IPL_sent<>'closeRecord') and COLI.COLI_ID is null) ) order by isRecord asc,ipl.IPL_sent desc,IPL_sn desc"; $query = $this->INFO->query($sql); diff --git a/webht/third_party/pay/views/gai_setting.php b/webht/third_party/pay/views/gai_setting.php new file mode 100644 index 00000000..355d3b2e --- /dev/null +++ b/webht/third_party/pay/views/gai_setting.php @@ -0,0 +1,38 @@ +<form action="http://www.mycht.cn/webht.php/apps/pay/iPayLinksService/gai_modal_save" method="post" id="form_modal_orderid" name="form_modal_gai"> + <?php if ( ! empty($gai_info)) { ?> + <p>已录入订单 <?php echo!empty($old_order) ? $old_order : ""; ?></p> + <table class="table table-hover table-bordered"> + <thead> + <th>申请金额/币种</th> + <th>实收金额</th> + </thead> + <tr> + <td><?php echo $gai_info[0]->GAI_SQJE; ?>&nbsp;<?php echo $gai_info[0]->GAI_SQJECurrency; ?></td> + <td><?php echo $gai_info[0]->GAI_SSJE; ?>&nbsp;CNY</td> + </tr> + </table> + <p>撤回以上订单收款记录, 并转移到订单: </p> + <?php } ?> + <div class="input-group"> + <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo $new_order; ?>" placeholder="输入订单号" > + <span class="input-group-addon search-btn" onclick="show_gai_modal('<?php echo $note->IPL_dealId; ?>','<?php echo $note->IPL_orderId; ?>','<?php echo $note->IPL_sn; ?>', $('#pn_invoice').val())"></span> + </div> + <label class="text-danger">订单号形如: 160414408_B , B商务订单,JJ160321052_T,T传统订单,请务必加上后缀</label> + <div>订单详细内容: </div> + <p> + <?php + if (!empty($order_info)) { + echo "COLI_SN => $order_info->COLI_SN<br/>"; + echo "COLI_ID => $order_info->COLI_ID<br/>"; + echo "OPI_Email => $order_info->OPI_Email<br/>"; + echo "OPI_Name => $order_info->OPI_Name<br/>"; + echo!empty($order_info->COLI_GroupCode) ? "COLI_GroupCode => $order_info->COLI_GroupCode<br/>" : false; + echo!empty($order_info->COLI_OrderDetailText) ? "COLI_OrderDetailText => $order_info->COLI_OrderDetailText\n" : false; + } else { + echo '找不到目标订单内容'; + } + ?> + </p> + <input type="hidden" name="pn_txn_id" id="pn_txn_id" value="<?php echo $note->IPL_dealId; ?>" /> + <input type="hidden" name="pn_id" id="pn_id" value="<?php echo $note->IPL_sn; ?>" /> +</form> diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index 8b3b3a45..b97c0a80 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -159,6 +159,8 @@ $class_css = ''; if ($item->IPL_sent == 'send') { $show_send = $item->IPL_sent; + } else if ($item->IPL_sent == 'closeRecord') { + $show_send = "已忽略"; } else if (strcmp(trim($item->IPL_stateCode), "2") && $item->IPL_stateCode != NULL) { $class_css = 'btn-danger'; $show_send = $paytext[intval(trim($item->IPL_stateCode))]; diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index 2b5dac34..9e7dddf3 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -42,6 +42,7 @@ .input-group-btn{border: 1px solid #ccc;padding: 5px;} .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;} + #modal_set_gai .btn{color: #333;font-weight: 700;} </style> </head> <body> @@ -161,6 +162,8 @@ $class_css = ''; if ($item->IPL_sent == 'send') { $show_send = $item->IPL_sent; + } else if ($item->IPL_sent == 'closeRecord') { + $show_send = "已忽略"; } else if (strcmp(trim($item->IPL_stateCode), "2") && $item->IPL_stateCode != NULL) { $class_css = 'btn-danger'; $show_send = $paytext[intval(trim($item->IPL_stateCode))]; @@ -185,7 +188,11 @@ $record_class = ' btn btn-sm btn_margin btn-warning '; } ?> - <a href="javascript:void(0);" onclick="" class="<?php echo $record_class; ?>"><?php echo $isRecord; ?></a> + <a href="javascript:void(0);" class="<?php echo $record_class; ?>" + onclick="show_gai_modal('<?php echo $item->IPL_dealId; ?>', '<?php echo $item->IPL_orderId; ?>','<?php echo $item->IPL_sn; ?>')" + > + <?php echo $isRecord; ?> + </a> </li> </ul> @@ -223,6 +230,27 @@ </div> </div> + <!-- 收款记录详情 --> + <div class="modal" id="modal_set_gai" tabindex="-1" role="dialog" aria-labelledby="gaiModalLabel"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"> + <span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="gaiModalLabel">收款记录修正操作</h4> + </div> + <div class="modal-body" id="modal_set_gai_body"> + ... + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-warning pull-left" onclick="close_gai()" >忽略此条收款</button> + <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> + <button type="button" class="btn btn-warning" onclick="submit_gai_modal()">保存</button> + </div> + </div> + </div> + </div> + </body> <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js&v=20170811" type="text/javascript"></script> <script type="text/javascript"> @@ -272,6 +300,51 @@ return date; } }); + function show_gai_modal(pn_txn_id, pn_invoice, pn_id, new_order) { + var url = '/webht.php/apps/pay/ipaylinksservice/gai_modal/' + pn_txn_id + '/' + pn_invoice + '/' + pn_id; + if (new_order) url += '/' + new_order; + $.ajax({ + type: "get", + dataType: "json", + url: url, + success: function(data, textStatus) { + $('#modal_set_gai_body').html(data); + $('#modal_set_gai').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }); + } + function close_gai() { + var pn_txn_id = $('#pn_txn_id').val(); + if (confirm('是否忽略此记录: ' + pn_txn_id)) { + $.ajax({ + type: "get", + dataType: "json", + url: 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/closeGai/' + pn_txn_id, + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }); + } + } + function submit_gai_modal() { + $('#form_modal_gai').ajaxSubmit({ + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + }, + dataType: 'json', + timeout: 30000 + }); + return false; + } function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order, pn_id) { if (pn_txn_id) { $.ajax({ diff --git a/webht/third_party/pay/views/note_setting.php b/webht/third_party/pay/views/note_setting.php index 47280d28..400e6952 100644 --- a/webht/third_party/pay/views/note_setting.php +++ b/webht/third_party/pay/views/note_setting.php @@ -13,13 +13,12 @@ <dd><?php echo $note->IPL_acquiringTime; ?></dd> </dl> - <dl class="dl-horizontal"> <dt>订单号</dt> <dd> <div class="input-group"> <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo!empty($IPL_orderId) ? $IPL_orderId : $note->IPL_orderId; ?>"> - <span class="input-group-addon search-btn" onclick="show_order_modal('<?php echo $note->IPL_dealId; ?>', $('#pn_invoice').val(),'<?php echo $note->IPL_noticeTime; ?>','<?php echo $note->IPL_orderId; ?>')"></span> + <span class="input-group-addon search-btn" onclick="show_order_modal('<?php echo $note->IPL_dealId; ?>', $('#pn_invoice').val(),'<?php echo $note->IPL_noticeTime; ?>','<?php echo $note->IPL_orderId; ?>','<?php echo $note->IPL_sn; ?>')"></span> </div> <label class="text-danger">订单号形如: 160414408_B , B商务订单,JJ160321052_T,T传统订单,请务必加上后缀</label> </dd> @@ -28,7 +27,6 @@ <dl class="dl-horizontal"> <dt>订单详细内容</dt> <dd> - <?php if (!empty($order_info)) { echo "COLI_SN => $order_info->COLI_SN<br/>"; From c5f3f3a1649bcefac6e18888e30a6c17f531a92f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 3 Aug 2018 09:30:59 +0800 Subject: [PATCH 120/382] =?UTF-8?q?=E7=94=9F=E6=88=90paypal=E9=93=BE?= =?UTF-8?q?=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/payment.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/paypal/controllers/payment.php b/webht/third_party/paypal/controllers/payment.php index 9b5eb06a..cd08e942 100644 --- a/webht/third_party/paypal/controllers/payment.php +++ b/webht/third_party/paypal/controllers/payment.php @@ -5,7 +5,7 @@ if (!defined('BASEPATH')) class Payment extends CI_Controller { - public function __construct() + public function __construct() { parent::__construct(); $this->permission->is_admin(false); @@ -16,7 +16,7 @@ class Payment extends CI_Controller $data=array(); if ($this->input->post('price')) { //文字链接 - $paylink='https://www.chinahighlightstravel.com/payment/payment-center.asp?'. + $paylink='https://www.chinahighlights.com/securepayment/?'. 'Site_Language='.$this->input->post('lan').'&'. 'Site_CurrencyType='.$this->input->post('currency').'&'. 'Site_ACD=100-200-300&'. @@ -36,4 +36,4 @@ class Payment extends CI_Controller $this->load->view('n-footer'); } -} \ No newline at end of file +} From 2a78c413bcec75905c4b65bd2afc8888018eadb3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 3 Aug 2018 09:38:30 +0800 Subject: [PATCH 121/382] =?UTF-8?q?=E7=94=9F=E6=88=90paypal=E9=93=BE?= =?UTF-8?q?=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/controllers/payment.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/controllers/payment.php b/application/controllers/payment.php index 82a594ed..03d89f0d 100644 --- a/application/controllers/payment.php +++ b/application/controllers/payment.php @@ -17,7 +17,7 @@ class Payment extends CI_Controller $data=array(); if ($this->input->post('price')) { $data['payurl']=' - <a href="https://www.chinahighlightstravel.com/payment/payment-center.asp?'. + <a href="https://www.chinahighlights.com/securepayment/?'. 'Site_Language=en_us&'. 'Site_CurrencyType=USD&'. 'Site_ACD=100-200-300&'. From 5ab9632f897ba2a90c9b5dd3298d14c933d35268 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 3 Aug 2018 14:37:29 +0800 Subject: [PATCH 122/382] =?UTF-8?q?paypal=20=E6=9F=A5=E7=9C=8B=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E6=98=AF=E5=90=A6=E5=B7=B2=E5=BD=95=E5=85=A5=E8=AE=A2?= =?UTF-8?q?=E5=8D=95;+=E6=94=B6=E6=AC=BE=E8=BD=AC=E7=A7=BB=E5=88=B0?= =?UTF-8?q?=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/gai_setting.php | 2 +- .../third_party/paypal/controllers/index.php | 75 ++++++++++++++++ .../third_party/paypal/models/note_model.php | 6 +- .../paypal/models/paypal_model.php | 33 +++++++ .../third_party/paypal/views/gai_setting.php | 41 +++++++++ webht/third_party/paypal/views/note_list.php | 85 ++++++++++++++++++- 6 files changed, 235 insertions(+), 7 deletions(-) create mode 100644 webht/third_party/paypal/views/gai_setting.php diff --git a/webht/third_party/pay/views/gai_setting.php b/webht/third_party/pay/views/gai_setting.php index 355d3b2e..70be2c9b 100644 --- a/webht/third_party/pay/views/gai_setting.php +++ b/webht/third_party/pay/views/gai_setting.php @@ -1,4 +1,4 @@ -<form action="http://www.mycht.cn/webht.php/apps/pay/iPayLinksService/gai_modal_save" method="post" id="form_modal_orderid" name="form_modal_gai"> +<form action="http://www.mycht.cn/webht.php/apps/pay/iPayLinksService/gai_modal_save" method="post" id="form_modal_gai" name="form_modal_gai"> <?php if ( ! empty($gai_info)) { ?> <p>已录入订单 <?php echo!empty($old_order) ? $old_order : ""; ?></p> <table class="table table-hover table-bordered"> diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 6c466f89..472e3bec 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1031,4 +1031,79 @@ class Index extends CI_Controller { $objWriter->save('php://output'); } + /** 查看收款记录的是否已录入到订单 */ + public function gai_modal($pn_txn_id=null, $pn_id = null, $neworder=null) + { + $data = array(); + $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); + $orderid_info = $this->analysis_orderid($data['note']->pn_invoice); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id); + } elseif ($orderid_info->ordertype === 'B') { + $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id); + } + } + $data['old_order'] = $data['note']->pn_invoice; + $data['new_order'] = $neworder; + $data['order_info'] = null; + if ($neworder !== null) { + $neworder_id = $this->analysis_orderid($neworder); + $neworder_id = json_decode($neworder_id); + if ( ! empty($neworder_id)) { + $data['order_info'] = $this->Paypal_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype); + } + } + echo json_encode($this->load->view('gai_setting', $data, true)); + } + public function gai_modal_save() + { + $data = array(); + $pn_txn_id = $this->input->post('pn_txn_id'); + $pn_id = $this->input->post('pn_id'); + $neworder = $this->input->post('pn_invoice'); + + $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); + $orderid_info = $this->analysis_orderid($data['note']->pn_invoice); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id); + $this->Paypal_model->delete_money_t($pn_txn_id); + } elseif ($orderid_info->ordertype === 'B') { + $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id); + $this->Paypal_model->delete_money_b($pn_txn_id); + } + } + + if (!empty($pn_txn_id) && !empty($neworder)) { + $orderid_info = $this->analysis_orderid($neworder); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + if (!empty($advisor_info)) { + $this->Note_model->set_invoice($pn_txn_id, $neworder); + $this->send_note($pn_txn_id); + echo json_encode('修改成功!'); + return true; + } + } + } + echo json_encode('没找到数据!'); + return; + } + public function closeGai($pn_txn_id) + { + $data = array(); + $data['note'] = $this->Note_model->note($pn_txn_id); + if (!empty($data['note'])) { + $this->Note_model->update_send($pn_txn_id, 'closeRecord'); + echo json_encode('该收款记录已经忽略!'); + return true; + } + echo json_encode('没找到数据!'); + return; + } + } diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index 71835876..8aff1673 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -45,16 +45,17 @@ class Note_model extends CI_Model { public function search_date($date) { $this->init(); - $search_sql = " AND (pn.pn_datetime BETWEEN '$date 00:00:00' AND '$date 23:59:59' OR pn_send<>'send') "; + $search_sql = " AND (pn.pn_datetime BETWEEN '$date 00:00:00' AND '$date 23:59:59' OR pn_send not in ('send','closeRecord')) "; $this->search = $search_sql; $this->orderby=" ORDER BY CASE pn.pn_send WHEN 'sendfail' THEN 1 ELSE 2 END ,pn.pn_sn DESC "; return $this->get_list(); } - public function note($pn_txn_id){ + public function note($pn_txn_id, $pn_sn=NULL){ $this->init(); $this->topnum=1; $this->pn_txn_id=" AND pn.pn_txn_id=".$this->HT->escape($pn_txn_id); + $this->pn_txn_id .= ($pn_sn===NULL) ? "" : " AND pn.pn_sn=".$this->HT->escape($pn_sn); return $this->get_list(); } @@ -118,6 +119,7 @@ class Note_model extends CI_Model { $this->search ? $sql.=$this->search : false; $this->pn_txn_id ? $sql.=$this->pn_txn_id : false; $this->orderby ? $sql.=$this->orderby : false; +// log_message('error',$sql); $query = $this->HT->query($sql); //print_r($this->HT->queries); if ($this->topnum === 1) { diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 73101e6a..b2d116bb 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -521,4 +521,37 @@ class Paypal_model extends CI_Model { $query = $this->HT->query($sql, array($paymanner, $COLI_SN)); return $query; } + //根据交易号获取收款记录(传统订单) + public function get_money_t($pn_invoice) { + $sql = "SELECT GroupAccountInfo.* + from GroupAccountInfo + where DeleteFlag=0 and GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + //根据交易号获取收款记录(商务订单) + public function get_money_b($pn_invoice) { + $sql = "SELECT BIZ_GroupAccountInfo.* + from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + /** 删除收款记录 */ + public function delete_money_t($deadId) + { + $sql = "UPDATE GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } + public function delete_money_b($deadId) + { + $sql = "UPDATE BIZ_GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } } diff --git a/webht/third_party/paypal/views/gai_setting.php b/webht/third_party/paypal/views/gai_setting.php new file mode 100644 index 00000000..e11d0137 --- /dev/null +++ b/webht/third_party/paypal/views/gai_setting.php @@ -0,0 +1,41 @@ +<form action="/webht.php/apps/paypal/index/gai_modal_save" method="post" id="form_modal_gai" name="form_modal_gai"> + <?php if ( ! empty($gai_info)) { ?> + <p>已录入订单 <?php echo!empty($old_order) ? $old_order : ""; ?></p> + <table class="table table-hover table-bordered"> + <thead> + <th>申请金额/币种</th> + <th>实收金额</th> + </thead> + <tr> + <td><?php echo $gai_info[0]->GAI_SQJE; ?>&nbsp;<?php echo $gai_info[0]->GAI_SQJECurrency; ?></td> + <td><?php echo $gai_info[0]->GAI_SSJE; ?>&nbsp;CNY</td> + </tr> + </table> + <p>撤回以上订单收款记录, 并转移到订单: </p> + <?php } else { ?> + <p>未自动录入到订单 </p> + <?php } ?> + <div class="input-group"> + <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo $new_order; ?>" placeholder="输入订单号" > + <span class="input-group-addon search-btn" style="cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;width: auto;height: auto;" + onclick="show_gai_modal('<?php echo $note->pn_txn_id; ?>','<?php echo $note->pn_sn; ?>', $('#pn_invoice').val())" ></span> + </div> + <label class="text-danger">订单号形如: 160414408_B , B商务订单,JJ160321052_T,T传统订单,请务必加上后缀</label> + <div>订单详细内容: </div> + <p> + <?php // + if (!empty($order_info)) { + echo "COLI_SN => $order_info->COLI_SN<br/>"; + echo "COLI_ID => $order_info->COLI_ID<br/>"; + echo "OPI_Email => $order_info->OPI_Email<br/>"; + echo "OPI_Name => $order_info->OPI_Name<br/>"; + echo!empty($order_info->COLI_GroupCode) ? "COLI_GroupCode => $order_info->COLI_GroupCode<br/>" : false; + echo!empty($order_info->COLI_OrderDetailText) ? "COLI_OrderDetailText => $order_info->COLI_OrderDetailText\n" : false; + } else { + echo '找不到目标订单内容'; + } + ?> + </p> + <input type="hidden" name="pn_txn_id" id="pn_txn_id" value="<?php echo $note->pn_txn_id; ?>" /> + <input type="hidden" name="pn_id" id="pn_id" value="<?php echo $note->pn_sn; ?>" /> +</form> diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 0d8a07ce..69e711d3 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -41,6 +41,7 @@ return date; } }); + </script> <style type="text/css"> .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;position: absolute;top: 0;left: 17%;} @@ -123,8 +124,8 @@ <li class="col-sm-4"><strong>客人邮箱</strong></li> <li class="col-sm-4 "><strong>交易号</strong></li> <li class="col-sm-3 "><strong>收款(北京)时间</strong></li> - <li class="col-sm-3 "><strong>通知时间</strong></li> - <li class="col-sm-2 "><strong>通知状态</strong></li> + <li class="col-sm-2 "><strong>通知时间</strong></li> + <li class="col-sm-3 "><strong>通知状态</strong></li> </a> </ul> <?php @@ -142,13 +143,16 @@ <li class="col-sm-4 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo $item->pn_txn_id; ?></li> <li class="col-sm-3 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo date('Y-m-d H:i:s', strtotime($item->pn_payment_date) + 3600 * 8); ?></li> - <li class="col-sm-3 nopadding-L" ><?php echo $item->pn_datetime; ?></li> - <li class="col-sm-2" > + <li class="col-sm-2 nopadding-L" ><?php echo $item->pn_datetime; ?></li> + <li class="col-sm-3" > <?php $show_send = ''; $class_css = ''; + $show_record = '查看录入状态'; if ($item->pn_send == 'send') { $show_send = $item->pn_send; + } elseif ($item->pn_send == 'closeRecord') { + $show_send = $show_record = '已忽略'; } else if ($item->pn_payment_status == 'Completed') { $class_css = 'btn-danger'; $show_send = $item->pn_send; @@ -157,6 +161,12 @@ $show_send = $item->pn_payment_status; } ?><a href="javascript:void(0);" onclick="show_order_modal('<?php echo $item->pn_txn_id; ?>', '')" class="btn btn-sm <?php echo $class_css; ?>"><?php echo $show_send; ?></a> + <br> + <a href="javascript:void(0);" class="text_padding text-primary" style="padding: 10px;" + onclick="show_gai_modal('<?php echo $item->pn_txn_id; ?>','<?php echo $item->pn_sn; ?>')" + > + <?php echo $show_record; ?> + </a> </li> </ul> @@ -186,6 +196,27 @@ </div> </div> +<!-- 收款记录详情 --> +<div class="modal" id="modal_set_gai" tabindex="-1" role="dialog" aria-labelledby="gaiModalLabel"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"> + <span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="gaiModalLabel">收款记录修正操作</h4> + </div> + <div class="modal-body" id="modal_set_gai_body"> + ... + </div> + <div class="modal-footer" style="color: #333;font-weight: 700;"> + <button type="button" class="btn btn-warning pull-left" onclick="close_gai()" >忽略此条收款</button> + <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> + <button type="button" class="btn btn-warning" onclick="submit_gai_modal()">保存</button> + </div> + </div> + </div> +</div> + <script type="text/javascript"> function show_order_modal(pn_txn_id, pn_invoice) { @@ -234,6 +265,52 @@ return false; } + function show_gai_modal(pn_txn_id, pn_id, new_order) { + $('#modal_set_gai').modal('show'); + var url = '/webht.php/apps/paypal/index/gai_modal/' + pn_txn_id + '/' + pn_id; + if (new_order) url += '/' + new_order; + $.ajax({ + type: "get", + dataType: "json", + url: url, + success: function(data, textStatus) { + $('#modal_set_gai_body').html(data); + $('#modal_set_gai').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }); + } + function close_gai() { + var pn_txn_id = $('#pn_txn_id').val(); + if (confirm('是否忽略此记录: ' + pn_txn_id)) { + $.ajax({ + type: "get", + dataType: "json", + url: '/webht.php/apps/paypal/index/closeGai/' + pn_txn_id, + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }); + } + } + function submit_gai_modal() {debugger + $('#form_modal_gai').ajaxSubmit({ + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + }, + dataType: 'json', + timeout: 30000 + }); + return false; + } From 3abe72fe5714f417562d0bff6aab8264e31c3dd9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 6 Aug 2018 14:55:45 +0800 Subject: [PATCH 123/382] =?UTF-8?q?trippest=20=E5=8D=95=E5=9B=A2=E8=B4=A2?= =?UTF-8?q?=E5=8A=A1=E8=A1=A8;+=E5=88=A4=E6=96=AD=E7=81=AB=E8=BD=A6?= =?UTF-8?q?=E7=A5=A8,=E9=85=92=E5=BA=97,=E5=8C=85=E4=BB=B7=E7=BA=BF?= =?UTF-8?q?=E8=B7=AF=E6=98=AF=E5=90=A6=E5=B7=B2=E7=94=9F=E6=88=90=E9=A1=B9?= =?UTF-8?q?=E7=9B=AE=E6=8A=A5=E8=A1=A8,=E6=98=AF=E5=88=99=E6=9B=B4?= =?UTF-8?q?=E6=96=B0,=E5=90=A6=E5=88=99=E6=96=B0=E5=A2=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 17 +- .../models/orderFinance_model.php | 259 +++++------------- 2 files changed, 79 insertions(+), 197 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 80be305b..fbd7aab6 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -45,11 +45,6 @@ class Order_finance extends CI_Controller { return $this->generate_report($order_info); } - public function regenerate_report($coli_sn=0) - { - return $this->generate_report($order_info, TRUE); - } - /*! * 单团财务表计算 * @date 2018-07-18 @@ -64,7 +59,7 @@ class Order_finance extends CI_Controller { * * * 写入单团财务表report_order * END */ - public function generate_report($order_info=array(), $update_flag=false) + public function generate_report($order_info=array()) { $coli_sn = $order_info->COLI_SN; /** 单团财务表 */ @@ -196,11 +191,11 @@ class Order_finance extends CI_Controller { } /** 开始写入数据库 */ /** 图兰朵供应商 */ - $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour, $update_flag); + $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour); /** 非图兰朵供应商的包价线路产品 */ $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); if ( ! empty($other_tour)) { - $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn, $update_flag); + $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); foreach ($ret->others as $kro => $vro) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); // test @@ -210,7 +205,7 @@ class Order_finance extends CI_Controller { /** 火车票预定 */ $train_detail = $this->OrderFinance_model->get_order_detail($coli_sn, '2'); if( ! empty($train_detail)) { - $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn, $update_flag); + $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn); foreach ($ret->train as $krt => $vrt) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); // test @@ -220,7 +215,7 @@ class Order_finance extends CI_Controller { /** 酒店预订 */ $hotel_detail = $this->OrderFinance_model->get_order_detail($coli_sn, 'A'); if ( ! empty($hotel_detail)) { - $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn, $update_flag); + $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn); foreach ($ret->hotel as $krh => $vrh) { // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost); // test @@ -231,7 +226,7 @@ class Order_finance extends CI_Controller { $report_order['profitmoney'] = $report_order['OrderYJLR'] = bcsub($report_order['money'], $report_order['basemoney']); $report_order['builddate'] = date('Y-m-d H:i:s'); $report_order['xh'] = $this->OrderFinance_model->get_report_order_xh(); //序号 - $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order, $update_flag); + $ret->report_order = $this->OrderFinance_model->insert_report_order($report_order, $coli_sn, $report_order['RO_GRI_SN']); $this->output->set_content_type('application/json')->set_output(json_encode($ret)); return; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 20535459..ed6672b9 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -175,12 +175,38 @@ class OrderFinance_model extends CI_Model { return $ret; } + /** 判断各种项目的报表是否已存在 */ + public function report_tour_exists($coli_id=null, $tourCode=null) + { + $sql = "SELECT top 1 ordernumber from report_tour where ordernumber=? and tourCode=?"; + $num_rows = $this->HT->query($sql, array($coli_id, $tourCode))->num_rows(); + return $num_rows>0; + } + public function report_train_exists($coli_id=null, $TrainNo=null) + { + $sql = "SELECT top 1 OrderNumber from report_Train where OrderNumber=? and TrainNo=?"; + $num_rows = $this->HT->query($sql, array($coli_id, $TrainNo))->num_rows(); + return $num_rows>0; + } + public function report_room_exists($coli_id=null, $hotelName=null) + { + $sql = "SELECT top 1 ordernumber from report_room where ordernumber=? and hotelName=?"; + $num_rows = $this->HT->query($sql, array($coli_id, $hotelName))->num_rows(); + return $num_rows>0; + } + public function report_order_exists($coli_id=null, $gri_sn=null) + { + $sql = "SELECT top 1 ordernumber from report_order where ordernumber=? and ro_gri_sn=?"; + $num_rows = $this->HT->query($sql, array($coli_id, $gri_sn))->num_rows(); + return $num_rows>0; + } + /** 图兰朵包价线路产品 */ - public function insert_report_tour_tulanduo($report_tour_arr=array(), $update_flag=false) + public function insert_report_tour_tulanduo($report_tour_arr=array()) { $this->HT2 = $this->load->database('INFO', TRUE); // test foreach ($report_tour_arr as $krt => $vrt) { - if ($update_flag === TRUE) { + if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode']) === TRUE) { $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "'"; $update_sql = $this->HT2->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); $this->HT2->query($update_sql); @@ -192,55 +218,20 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test } /** 火车票 */ - public function insert_report_train($coli_sn=0, $update_flag=false) - { - if ($update_flag === TRUE) { - return $this->update_report_train($coli_sn); - } - // INSERT INTO report_Train( - // OrderNumber, - // TrainNo, - // DepartureCity, - // ArrivalCity, - // DepartureDate, - // PassengerNo, - // adultPrice, - // TotalCost, - // TotalPrice, - // TrainProvide, - // TrainBZ, - // orderstats) - $sql = "SELECT - dbo.BIZ_ConfirmLineInfo.COLI_ID, - FlightsNo, - DepartureCity, - ArrivalCity, - left(convert(varchar,DepartureDate,120),10) as DepartureDate1, - isnull(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0) as PersonNum, - adultcost, - COLD_TotalCost as TotalCost, - COLD_TotalPrice*6.77 as TotalPrice, --test - VEI2_CompanyBN, - ' ' as TrainBZ, -- test - -- case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, - 0 as stat - from BIZ_ConfirmLineDetail - inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN - inner join BIZ_FlightsOrderInfo on FOI_COLD_SN = COLD_SN - left join VEndorInfo2 on COLD_PlanVEI_SN = VEI2_VEI_SN and VEI2_LGC = 2 - where COLD_COLI_SN = $coli_sn - and isnull(BIZ_ConfirmLineDetail.DeleteFlag,0)=0 - and COLD_ServiceType = '2' "; - return $this->HT->query($sql)->result(); - // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->row(); - } - public function update_report_train($coli_sn=0) + public function insert_report_train($coli_sn=0) { $this->HT2 = $this->load->database('INFO', TRUE); // test - $update_data = $this->get_train_cost($coli_sn); - $where = " OrderNumber='" . $update_data->OrderNumber . "' AND TrainNo='" . $update_data->TrainNo . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_Train', $update_data, $where); - return $this->HT2->query($update_sql); + $train_cost = $this->get_train_cost($coli_sn); + foreach ($train_cost as $ktc => $vtc) { + if ($this->report_train_exists($vtc->OrderNumber, $vtc->TrainNo) === TRUE) { + $where = " OrderNumber='" . $vtc->OrderNumber . "' AND TrainNo='" . $vtc->TrainNo . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE), $where); + $this->HT2->query($update_sql); + } else { + $this->HT2->insert('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE)); + } + } + return $this->HT2->query("SELECT * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->result(); } public function get_train_cost($coli_sn=0) { @@ -265,64 +256,24 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test where COLD_COLI_SN = $coli_sn and isnull(BIZ_ConfirmLineDetail.DeleteFlag,0)=0 and COLD_ServiceType = '2' "; - return $this->HT->query($sql)->row(); + return $this->HT->query($sql)->result(); } /** 酒店 */ - public function insert_report_hotel($coli_sn=0, $update_flag=false) - { - if ($update_flag === TRUE) { - return $this->update_report_hotel($coli_sn); - } - // INSERT INTO report_room( ordernumber, hotelName, cityName, hotelStar, roomtype, starttime, endtime, roomnumber, ExtraBedNumber, jianyeshu, jianyecost, ExtraBedCost, ExtraBedPrice, roomcost, roomprice, roomprofit, roomprovide, roombz, orderstats) - $sql = " - SELECT coli_id, - v2.VEI2_CompanyBN AS HotelName, - cityinfo2.CII2_Name AS cityname, - (SELECT SGC_ServiceGrade - FROM servicegradecode2 - WHERE SGC2_LGC=2 - AND SGC2_SGC_SN=Isnull(VEI_Grade,-1)) AS HStar, - (SELECT ROT2_TypeName - FROM roomtype2 - WHERE ROT2_ROT_SN=ISNULL(COLD_ServiceSN2,-1) - AND ROT2_LGC=1) AS RoomType, - left(convert(varchar,COLD_StartDate,120),10) AS COLD_StartDate, - left(convert(varchar,COLD_EndDate,120),10) AS COLD_EndDate, - COLD_Count, - isnull(HOI_ExtraNum,0) AS HOI_ExtraNum, - COLD_DayCount=DATEDIFF(DAY,COLD_StartDate,COLD_EndDate), - COLD_TotalCost, -- test - -- COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)), - 0 as ExtraBedCost, - 0 as ExtraBedPrice, - COLD_TotalCost, - COLD_TotalPrice*6.77 as COLD_TotalPrice, - (COLD_TotalPrice/1.03*6.77)-COLD_TotalCost as roomprofit, - VendorInfo2.VEI2_CompanyBN AS PlantVEI, - COLD_Describe, - 0 as stat - FROM BIZ_ConfirmLineDetail - INNER JOIN BIZ_ConfirmLineInfo ON COLD_COLI_SN=COLI_SN - LEFT JOIN BIZ_HotelOrderInfo ON HOI_COLD_SN = COLD_SN - LEFT JOIN VEndorInfo2 ON COLD_PlanVEI_SN = VEI2_VEI_SN AND VEI2_LGC = 2 - LEFT JOIN Vendorinfo2 AS V2 ON COLD_ServiceSN = V2.VEI2_VEI_SN AND V2.VEI2_LGC = 2 - LEFT JOIN VendorInfo ON COLD_ServiceSN = VEI_SN - LEFT JOIN cityinfo2 ON vendorinfo.VEI_CII_Name=cityinfo2.CII2_CII_SN AND cityinfo2.CII2_LGC=2 - WHERE COLD_COLI_SN = $coli_sn - AND BIZ_ConfirmLineDetail.DeleteFlag = 0 - AND COLD_ServiceType = 'A' - "; - return $this->HT->query($sql)->result(); - // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); - } - public function update_report_hotel($coli_sn) + public function insert_report_hotel($coli_sn=0) { $this->HT2 = $this->load->database('INFO', TRUE); // test - $update_data = $this->get_hotel_cost($coli_sn); - $where = " ordernumber='" . $update_data->ordernumber . "' AND hotelName='" . $update_data->hotelName . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_room', $update_data, $where); - return $this->HT2->query($update_sql); + $hotel_cost = $this->get_hotel_cost($coli_sn); + foreach ($hotel_cost as $khc => $vhc) { + if ($this->report_room_exists($vhc->ordernumber, $vhc->hotelName) === TRUE) { + $where = " ordernumber='" . $vhc->ordernumber . "' AND hotelName='" . $vhc->hotelName . "' "; + $update_sql = $this->HT2->update_string('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE), $where); + $this->HT2->query($update_sql); + } else { + $this->HT2->insert('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE)); + } + } + return $this->HT2->query("SELECT * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result(); } public function get_hotel_cost($coli_sn) { @@ -364,88 +315,24 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test AND BIZ_ConfirmLineDetail.DeleteFlag = 0 AND COLD_ServiceType = 'A' "; - return $this->HT->query($sql)->row(); + return $this->HT->query($sql)->result(); } /** 非图兰朵供应商的包价线路产品 */ - public function insert_report_tour_others($coli_sn=0, $update_flag=false) + public function insert_report_tour_others($coli_sn=0) { - if ($update_flag === TRUE) { - return $this->update_report_tour_others($coli_sn); - } - // INSERT INTO report_tour( - // ordernumber, - // tourCode, - // tourname, - // tourtime, - // tourRSd, - // tourRSx, - // tourCostRsd, - // tourCostRSx, - // tourcost, - // tourPrice, - // tourProfit, - // tourProvide, - // tourBZ, - // orderstats) - $sql = "SELECT - dbo.BIZ_ConfirmLineInfo.COLI_ID, - dbo.BIZ_PackageInfo.PAG_Code, - dbo.BIZ_PackageInfo.PAG_Title, - SUBSTRING(CONVERT(varchar,dbo.BIZ_ConfirmLineDetail.COLD_StartDate, 120), 1, 10) AS COLD_StartDate, - dbo.BIZ_ConfirmLineDetail.COLD_PersonNum, - dbo.BIZ_ConfirmLineDetail.COLD_ChildNum, - --@AdultCost, - (select top 1 PKP_AdultCost - from BIZ_PackagePrice - where PKP_PAG_SN=COLD_ServiceSN - and PKP_VEI_SN=COLD_PlanVEI_SN - and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) - and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) - and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) - and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) - ORDER BY PKP_PriceGrade - ) as AdultCost, - --@ChildCost, - (select top 1 PKP_ChildCost - from BIZ_PackagePrice - where PKP_PAG_SN=COLD_ServiceSN - and PKP_VEI_SN=COLD_PlanVEI_SN - and PKP_PersonStart<=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) - and PKP_PersonStop >=isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0) - and PKP_ValidDate <= CONVERT(varchar(100),COLD_StartDate,23) - and PKP_InvalidDate >= CONVERT(varchar(100),COLD_StartDate,23) - ORDER BY PKP_PriceGrade - ) as ChildCost, - dbo.BIZ_ConfirmLineDetail.COLD_TotalCost, - -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) COLD_TotalPrice, - -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as COLD_Profit, - dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77 COLD_TotalPrice, - (dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as COLD_Profit, - isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.') as VEI2_CompanyN, - SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as COLD_Describe1, - 0 as stat - FROM dbo.BIZ_ConfirmLineDetail - inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN - LEFT OUTER JOIN dbo.VEndorInfo2 ON dbo.VEndorInfo2.VEI2_VEI_SN = dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN AND dbo.VEndorInfo2.VEI2_LGC = 2 - INNER JOIN dbo.BIZ_PackageInfo ON dbo.BIZ_ConfirmLineDetail.COLD_ServiceSN = dbo.BIZ_PackageInfo.PAG_SN - WHERE (dbo.BIZ_ConfirmLineDetail.COLD_ServiceType='D') - AND (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0) - AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) - and dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN not in (1343,29188,30548,30016) "; - return $this->HT->query($sql)->result(); - // return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_tour inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->row(); - // $this->HT->query($sql); + $other_tour_cost = $this->get_report_tour_others_cost($coli_sn); + foreach ($other_tour_cost as $kotc => $votc) { + if ($this->report_tour_exists($votc->ordernumber, $votc->tourCode) === TRUE) { + $where = " ordernumber='" . $votc->ordernumber . "' AND tourCode='" . $votc->tourCode . "'"; + $update_sql = $this->HT2->update_string('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE), $where); + $this->HT2->query($update_sql); + } else { + $this->HT2->insert('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE)); + } - return TRUE; - } - public function update_report_tour_others($coli_sn) - { -$this->HT2 = $this->load->database('INFO', TRUE); // test - $update_data = $this->get_report_tour_others_cost($coli_sn); - $where = " ordernumber='" . $update_data->ordernumber . "' AND tourCode='" . $update_data->tourCode . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_tour', $update_data, $where); - return $this->HT2->query($update_sql); + } + return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_tour inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result(); } public function get_report_tour_others_cost($coli_sn=0) { @@ -494,21 +381,21 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test AND (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0) AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) and dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN not in (1343,29188,30548,30016) "; - return $this->HT->query($sql)->row(); + return $this->HT->query($sql)->result(); } - public function insert_report_order($report_order_arr=array(), $update_flag=false) + /** 单团财务表 */ + public function insert_report_order($report_order_arr=array(), $coli_sn=0, $gri_sn=0) { $this->HT2 = $this->load->database('INFO', TRUE); // test - if ($update_flag === TRUE) { + if ( $this->report_order_exists($coli_sn, $gri_sn) === TRUE ) { $where = " ordernumber='" . $report_order_arr['ordernumber'] . "' "; $update_sql = $this->HT2->update_string('tourmanager.dbo.report_order', $report_order_arr, $where); $this->HT2->query($update_sql); + } else { + $this->HT2->insert('tourmanager.dbo.report_order', $report_order_arr); } - $this->HT2->insert('tourmanager.dbo.report_order', $report_order_arr); - return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber=? order by orderID desc", - array($report_order_arr['ordernumber']))->row(); - // return TRUE; + return $this->get_report_order($report_order_arr['ordernumber']); } public function get_report_order($coli_id=0) From e0fec29a67c0df16a0011a6c2a8a3fe43a90f92e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 Aug 2018 11:16:09 +0800 Subject: [PATCH 124/382] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=BA=93=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E7=B1=BB=E5=9E=8B,=E9=95=BF=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 31 +++++++++---------- .../models/orderFinance_model.php | 14 ++++----- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index fbd7aab6..e5d07047 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -72,9 +72,9 @@ class Order_finance extends CI_Controller { $report_order['childnumber'] = 0; $report_order['babynumber'] = 0; $report_order['ordernumber'] = $order_info->ordernumber; - $report_order['TuanName'] = $order_info->TuanName; + $report_order['TuanName'] = mb_substr($order_info->TuanName, 0, 50); $report_order['operater'] = $order_info->operater; - $report_order['Agenter'] = $order_info->Agenter; + $report_order['Agenter'] = mb_substr($order_info->Agenter,0,10); $report_order['ChinaName'] = $order_info->ChinaName; $report_order['country'] = $order_info->country; $report_order['reservedate'] = $order_info->reservedate; @@ -118,13 +118,12 @@ class Order_finance extends CI_Controller { } } /** 保存图兰朵包价线路产品的成本到report_tour */ - // TODO // pvt $report_tour_pvt = array(); if ( ! empty($ret->pvt)) { $report_tour_pvt['ordernumber'] = $ret->pvt->coli_id; - $report_tour_pvt['tourCode'] = $ret->pvt->PAG_Code; - $report_tour_pvt['tourname'] = $ret->pvt->pag_name; + $report_tour_pvt['tourCode'] = mb_substr($ret->pvt->PAG_Code, 0, 50); + $report_tour_pvt['tourname'] = mb_substr($ret->pvt->pag_name, 0, 200); $report_tour_pvt['tourtime'] = $ret->pvt->startdate; $report_tour_pvt['tourRSd'] = $ret->pvt->adult_num; $report_tour_pvt['tourRSx'] = $ret->pvt->child_num; @@ -133,8 +132,8 @@ class Order_finance extends CI_Controller { $report_tour_pvt['tourcost'] = $ret->pvt->cost_sum; $report_tour_pvt['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($ret->pvt->totalPrice); $report_tour_pvt['tourProfit'] = ($report_tour_pvt['tourPrice']>0) ? bcsub($report_tour_pvt['tourPrice'], $report_tour_pvt['tourcost']) : 0; - $report_tour_pvt['tourProvide'] = $ret->pvt->vendor_name; - $report_tour_pvt['tourBZ'] = $ret->pvt->comment; + $report_tour_pvt['tourProvide'] = mb_substr($ret->pvt->vendor_name, 0, 50); + $report_tour_pvt['tourBZ'] = mb_substr($ret->pvt->comment, 0, 150); $report_tour_pvt['orderstats'] = 0; // 成本详情 $report_tour_pvt['RPT_Car'] = $ret->pvt->cost_category['touristCarOperations']; @@ -155,8 +154,8 @@ class Order_finance extends CI_Controller { foreach ($ret->combine_cost as $kcc => $cost) { $cost_c = array(); $cost_c['ordernumber'] = $cost->coli_id; - $cost_c['tourCode'] = implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))); - $cost_c['tourname'] = $cost->pag_name; + $cost_c['tourCode'] = mb_substr(implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))), 0, 50); + $cost_c['tourname'] = mb_substr($cost->pag_name, 0, 200) ; $cost_c['tourtime'] = $cost->startdate; $cost_c['tourRSd'] = $cost->order_cost[0]->adult_num; $cost_c['tourRSx'] = $cost->order_cost[0]->child_num; @@ -171,8 +170,8 @@ class Order_finance extends CI_Controller { } $cost_c['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($cost_c_price); $cost_c['tourProfit'] = ($cost_c['tourPrice']>0) ? bcsub($cost_c['tourPrice'], $cost_c['tourcost']) : 0; - $cost_c['tourProvide'] = $cost->vendor_name; - $cost_c['tourBZ'] = $cost->comment; + $cost_c['tourProvide'] = mb_substr($cost->vendor_name, 0, 50); + $cost_c['tourBZ'] = mb_substr($cost->comment, 0, 150); $cost_c['orderstats'] = 0; // 成本详情 $cost_c['RPT_Car'] = $cost->cost_category['touristCarOperations']; @@ -343,8 +342,8 @@ class Order_finance extends CI_Controller { } $this_order_real_pag_sns = array_map(function($ele) {return $ele->real_pag_sn;}, $ret->order_cost); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', array_unique(array_filter($this_order_real_pag_sns)))); // $pag_sns - $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 - $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') + $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; + $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; $ret->PAG_Code = implode(",", $ret->combine_pags); $ret->comment = "拼团" . $combineNo . ", 按" . $ret->person_num . "人等"; $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); @@ -394,9 +393,9 @@ class Order_finance extends CI_Controller { $ret->comment = "PVT,共" . $ret->person_num . "人次";// 150 $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); - $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); // TODO 限制50 - $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; // 50 - $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // TODO 限制200 用mb_substr('UTF-8') + $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); + $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; + $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; // $ret->tour[0] = $tour_s; // $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); return $ret; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index ed6672b9..f95fcb82 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -245,7 +245,7 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test adultcost adultPrice, COLD_TotalCost as TotalCost, COLD_TotalPrice*6.77 as TotalPrice, --test - VEI2_CompanyBN TrainProvide, + SUBSTRING(VEI2_CompanyBN,1,50) TrainProvide, ' ' as TrainBZ, -- test -- case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, 0 as orderstats @@ -279,13 +279,13 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test { $sql = " SELECT coli_id ordernumber, - v2.VEI2_CompanyBN AS hotelName, + SUBSTRING(v2.VEI2_CompanyBN,1,50) AS hotelName, cityinfo2.CII2_Name AS cityName, (SELECT SGC_ServiceGrade FROM servicegradecode2 WHERE SGC2_LGC=2 AND SGC2_SGC_SN=Isnull(VEI_Grade,-1)) AS hotelStar, - (SELECT ROT2_TypeName + (SELECT SUBSTRING(ROT2_TypeName,1,100) as ROT2_TypeName FROM roomtype2 WHERE ROT2_ROT_SN=ISNULL(COLD_ServiceSN2,-1) AND ROT2_LGC=1) AS roomtype, @@ -301,8 +301,8 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test COLD_TotalCost roomcost, COLD_TotalPrice*6.77 as roomprice, (COLD_TotalPrice/1.03*6.77)-COLD_TotalCost as roomprofit, - VendorInfo2.VEI2_CompanyBN AS roomprovide, - COLD_Describe roombz, + SUBSTRING(VendorInfo2.VEI2_CompanyBN,1,50) AS roomprovide, + SUBSTRING(COLD_Describe,1,150) roombz, 0 as orderstats FROM BIZ_ConfirmLineDetail INNER JOIN BIZ_ConfirmLineInfo ON COLD_COLI_SN=COLI_SN @@ -339,7 +339,7 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test $sql = "SELECT dbo.BIZ_ConfirmLineInfo.COLI_ID ordernumber, dbo.BIZ_PackageInfo.PAG_Code tourCode, - dbo.BIZ_PackageInfo.PAG_Title tourname, + SUBSTRING(dbo.BIZ_PackageInfo.PAG_Title,1,200) tourname, SUBSTRING(CONVERT(varchar,dbo.BIZ_ConfirmLineDetail.COLD_StartDate, 120), 1, 10) AS tourtime, dbo.BIZ_ConfirmLineDetail.COLD_PersonNum tourRSd, dbo.BIZ_ConfirmLineDetail.COLD_ChildNum tourRSx, @@ -370,7 +370,7 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77 tourPrice, (dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, - isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.') as tourProvide, + SUBSTRING(isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.'),1,50) as tourProvide, SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as tourBZ, 0 as orderstats FROM dbo.BIZ_ConfirmLineDetail From 816bca37bc5e760a8e6331492978684ce3a2523f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 Aug 2018 12:02:32 +0800 Subject: [PATCH 125/382] =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../models/orderFinance_model.php | 66 ++++++++----------- 1 file changed, 27 insertions(+), 39 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index f95fcb82..bbd89829 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -16,11 +16,9 @@ class OrderFinance_model extends CI_Model { coli.COLI_WebCode as Agenter, coli.COLI_ApplyDate as reservedate ,coli.COLI_Cost as basemoney - ,coli.COLI_Price*6.77 OrderPrice - -- ,dbo.ConvertToRMB('USD',ISNULL(coli.COLI_Price,0)) OrderPrice + ,dbo.ConvertToRMB('USD',ISNULL(coli.COLI_Price,0)) OrderPrice ,gri.GRI_SN ,gri.GRI_No as TuanName ,opi.OPI_Name as ChinaName,opi.OPI_SN as operater,opi.OPI_DEI_SN - -- ,GETDATE() as builddate ,gut.GUT_NationalityID,COI2_Country as country ,( select top 1 BPE_GuestType @@ -204,14 +202,13 @@ class OrderFinance_model extends CI_Model { /** 图兰朵包价线路产品 */ public function insert_report_tour_tulanduo($report_tour_arr=array()) { -$this->HT2 = $this->load->database('INFO', TRUE); // test foreach ($report_tour_arr as $krt => $vrt) { if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode']) === TRUE) { $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "'"; - $update_sql = $this->HT2->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); - $this->HT2->query($update_sql); + $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); + $this->HT->query($update_sql); } else { - $this->HT2->insert('tourmanager.dbo.Report_Tour', $vrt); + $this->HT->insert('tourmanager.dbo.Report_Tour', $vrt); } } return TRUE; @@ -220,18 +217,17 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test /** 火车票 */ public function insert_report_train($coli_sn=0) { -$this->HT2 = $this->load->database('INFO', TRUE); // test $train_cost = $this->get_train_cost($coli_sn); foreach ($train_cost as $ktc => $vtc) { if ($this->report_train_exists($vtc->OrderNumber, $vtc->TrainNo) === TRUE) { $where = " OrderNumber='" . $vtc->OrderNumber . "' AND TrainNo='" . $vtc->TrainNo . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE), $where); - $this->HT2->query($update_sql); + $update_sql = $this->HT->update_string('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE), $where); + $this->HT->query($update_sql); } else { - $this->HT2->insert('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE)); + $this->HT->insert('tourmanager.dbo.report_Train', json_decode(json_encode($vtc), TRUE)); } } - return $this->HT2->query("SELECT * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->result(); + return $this->HT->query("SELECT * from tourmanager.dbo.report_Train inner join BIZ_ConfirmLineInfo on COLI_ID=OrderNumber WHERE COLI_SN=$coli_sn order by OrderID desc")->result(); } public function get_train_cost($coli_sn=0) { @@ -244,10 +240,9 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test isnull(COLD_PersonNum,0)+ISNULL(COLD_ChildNum,0) as PassengerNo, adultcost adultPrice, COLD_TotalCost as TotalCost, - COLD_TotalPrice*6.77 as TotalPrice, --test + dbo.ConvertToRMB('USD',COLD_TotalPrice) as TotalPrice, SUBSTRING(VEI2_CompanyBN,1,50) TrainProvide, - ' ' as TrainBZ, -- test - -- case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, + case when dbo.GetBIZTrainVEIDebt(COLD_SN)='YES' then '挂账' else ' ' end as TrainBZ, 0 as orderstats from BIZ_ConfirmLineDetail inner join BIZ_ConfirmLineInfo on COLI_SN=COLD_COLI_SN @@ -262,18 +257,17 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test /** 酒店 */ public function insert_report_hotel($coli_sn=0) { -$this->HT2 = $this->load->database('INFO', TRUE); // test $hotel_cost = $this->get_hotel_cost($coli_sn); foreach ($hotel_cost as $khc => $vhc) { if ($this->report_room_exists($vhc->ordernumber, $vhc->hotelName) === TRUE) { $where = " ordernumber='" . $vhc->ordernumber . "' AND hotelName='" . $vhc->hotelName . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE), $where); - $this->HT2->query($update_sql); + $update_sql = $this->HT->update_string('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE), $where); + $this->HT->query($update_sql); } else { - $this->HT2->insert('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE)); + $this->HT->insert('tourmanager.dbo.report_room', json_decode(json_encode($vhc), TRUE)); } } - return $this->HT2->query("SELECT * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result(); + return $this->HT->query("SELECT * from tourmanager.dbo.report_room inner join BIZ_ConfirmLineInfo on COLI_ID=ordernumber WHERE COLI_SN=$coli_sn order by orderId desc")->result(); } public function get_hotel_cost($coli_sn) { @@ -294,13 +288,12 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test COLD_Count roomnumber, isnull(HOI_ExtraNum,0) AS ExtraBedNumber, COLD_DayCount=DATEDIFF(DAY,COLD_StartDate,COLD_EndDate) as jianyeshu, - COLD_TotalCost jianyecost, -- test - -- COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)) as jianyecost, + COLD_TotalCost*1.0/dbo.ZeroToOne(DATEDIFF(DAY,COLD_StartDate,COLD_EndDate)) as jianyecost, 0 as ExtraBedCost, 0 as ExtraBedPrice, COLD_TotalCost roomcost, - COLD_TotalPrice*6.77 as roomprice, - (COLD_TotalPrice/1.03*6.77)-COLD_TotalCost as roomprofit, + dbo.ConvertToRMB('USD',COLD_TotalPrice) as roomprice, + dbo.ConvertToRMB('USD',(COLD_TotalPrice/1.03))-COLD_TotalCost as roomprofit, SUBSTRING(VendorInfo2.VEI2_CompanyBN,1,50) AS roomprovide, SUBSTRING(COLD_Describe,1,150) roombz, 0 as orderstats @@ -325,10 +318,10 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test foreach ($other_tour_cost as $kotc => $votc) { if ($this->report_tour_exists($votc->ordernumber, $votc->tourCode) === TRUE) { $where = " ordernumber='" . $votc->ordernumber . "' AND tourCode='" . $votc->tourCode . "'"; - $update_sql = $this->HT2->update_string('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE), $where); - $this->HT2->query($update_sql); + $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE), $where); + $this->HT->query($update_sql); } else { - $this->HT2->insert('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE)); + $this->HT->insert('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE)); } } @@ -366,10 +359,8 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test ORDER BY PKP_PriceGrade ) as tourCostRSx, dbo.BIZ_ConfirmLineDetail.COLD_TotalCost tourcost, - -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) tourPrice, - -- dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, - dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77 tourPrice, - (dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice*6.77)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, + dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice) tourPrice, + dbo.ConvertToRMB('USD',dbo.BIZ_ConfirmLineDetail.COLD_TotalPrice)-dbo.BIZ_ConfirmLineDetail.COLD_TotalCost as tourProfit, SUBSTRING(isnull(dbo.VEndorInfo2.VEI2_CompanyBN,'.'),1,50) as tourProvide, SUBSTRING(dbo.BIZ_ConfirmLineDetail.COLD_Describe,1,70) as tourBZ, 0 as orderstats @@ -387,28 +378,25 @@ $this->HT2 = $this->load->database('INFO', TRUE); // test /** 单团财务表 */ public function insert_report_order($report_order_arr=array(), $coli_sn=0, $gri_sn=0) { -$this->HT2 = $this->load->database('INFO', TRUE); // test if ( $this->report_order_exists($coli_sn, $gri_sn) === TRUE ) { $where = " ordernumber='" . $report_order_arr['ordernumber'] . "' "; - $update_sql = $this->HT2->update_string('tourmanager.dbo.report_order', $report_order_arr, $where); - $this->HT2->query($update_sql); + $update_sql = $this->HT->update_string('tourmanager.dbo.report_order', $report_order_arr, $where); + $this->HT->query($update_sql); } else { - $this->HT2->insert('tourmanager.dbo.report_order', $report_order_arr); + $this->HT->insert('tourmanager.dbo.report_order', $report_order_arr); } return $this->get_report_order($report_order_arr['ordernumber']); } public function get_report_order($coli_id=0) { -$this->HT2 = $this->load->database('INFO', TRUE); // test - return $this->HT2->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' order by orderID desc")->row(); + return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' order by orderID desc")->row(); } public function convert_to_RMB($money=0, $fromCurrency='USD') { -$this->HT2 = $this->load->database('INFO', TRUE); // test // [dbo].[ConvertToRMB](@TargetCurrency varchar(6), @SourceMoney decimal(18,5)) - return $this->HT2->query("SELECT tourmanager.dbo.[ConvertToRMB]('$fromCurrency',$money) as rmb ")->row()->rmb; + return $this->HT->query("SELECT tourmanager.dbo.[ConvertToRMB]('$fromCurrency',$money) as rmb ")->row()->rmb; } public function get_report_order_xh() From 79ed5ac9644d1ae1e3d22a20ddadc5a626b56b0a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 Aug 2018 15:41:04 +0800 Subject: [PATCH 126/382] =?UTF-8?q?trippest=E5=8D=95=E5=9B=A2=E8=B4=A2?= =?UTF-8?q?=E5=8A=A1=E8=A1=A8:=20=E9=83=A8=E5=88=86=E6=B8=A0=E9=81=93?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=9C=AA=E5=BE=97=E5=88=B0=E5=AE=A2=E4=BA=BA?= =?UTF-8?q?=E5=90=8D=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 9 ++++++--- .../models/orderFinance_model.php | 16 ++++++++++++---- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index e5d07047..c33e796f 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -71,6 +71,7 @@ class Order_finance extends CI_Controller { $report_order['adultnumber'] = 0; $report_order['childnumber'] = 0; $report_order['babynumber'] = 0; + $report_order['orderstats'] = 1; $report_order['ordernumber'] = $order_info->ordernumber; $report_order['TuanName'] = mb_substr($order_info->TuanName, 0, 50); $report_order['operater'] = $order_info->operater; @@ -78,7 +79,7 @@ class Order_finance extends CI_Controller { $report_order['ChinaName'] = $order_info->ChinaName; $report_order['country'] = $order_info->country; $report_order['reservedate'] = $order_info->reservedate; - $report_order['guesttype'] = $order_info->guesttype; + $report_order['guesttype'] = ($order_info->guesttype===null) ? 1 : $order_info->guesttype; $report_order['RO_GRI_SN'] = $report_order['RO_CGI_SN'] = $order_info->GRI_SN; // $report_order['basemoney'] = $order_info->basemoney; // 总成本 // $report_order['OrderPrice'] = $order_info->OrderPrice; // 总报价 @@ -96,7 +97,7 @@ class Order_finance extends CI_Controller { $ret = new stdClass(); /** 图兰朵产品: 取拼团实际成本 */ - $ret->combine_cost = array(); + $ret->combine_cost = $ret->report_tour = array(); $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); // $ret->x = $combineNo_arr; $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); @@ -190,7 +191,9 @@ class Order_finance extends CI_Controller { } /** 开始写入数据库 */ /** 图兰朵供应商 */ - $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour); + if ( ! empty($ret->report_tour)) { + $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour); + } /** 非图兰朵供应商的包价线路产品 */ $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); if ( ! empty($other_tour)) { diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index bbd89829..4f17b59d 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -130,7 +130,14 @@ class OrderFinance_model extends CI_Model { $query = $this->HT->query($sql); $ret->person_num = $query->num_rows(); $guest_type_cnt = array_count_values(array_map(function($ele) { return $ele->BPE_GuestType; }, $query->result())); - $ret->adult_num = $guest_type_cnt['1']; + if ($ret->person_num === 0) { + $sql2 = "SELECT COLD_PersonNum,COLD_ChildNum,isnull(COLD_BabyNum,0) COLD_BabyNum from BIZ_ConfirmLineDetail where COLD_COLI_SN=$coli_sn "; + $num_q = $this->HT->query($sql2)->row(); + $ret->person_num = $num_q->COLD_PersonNum + $num_q->COLD_ChildNum + $num_q->COLD_BabyNum; + $ret->adult_num = $num_q->COLD_PersonNum; + } else { + $ret->adult_num = $guest_type_cnt['1']; + } $ret->child_num = $ret->person_num-$ret->adult_num; return $ret; } @@ -194,7 +201,7 @@ class OrderFinance_model extends CI_Model { } public function report_order_exists($coli_id=null, $gri_sn=null) { - $sql = "SELECT top 1 ordernumber from report_order where ordernumber=? and ro_gri_sn=?"; + $sql = "SELECT top 1 ordernumber from report_order where ordernumber=? and ro_gri_sn=? and orderstats=1"; $num_rows = $this->HT->query($sql, array($coli_id, $gri_sn))->num_rows(); return $num_rows>0; } @@ -378,7 +385,8 @@ class OrderFinance_model extends CI_Model { /** 单团财务表 */ public function insert_report_order($report_order_arr=array(), $coli_sn=0, $gri_sn=0) { - if ( $this->report_order_exists($coli_sn, $gri_sn) === TRUE ) { + $this->HT->query("DELETE from Report_Order where ordernumber = '" . $report_order_arr['ordernumber'] . "' AND orderstats=0 "); + if ( $this->report_order_exists($report_order_arr['ordernumber'], $gri_sn) === TRUE ) { $where = " ordernumber='" . $report_order_arr['ordernumber'] . "' "; $update_sql = $this->HT->update_string('tourmanager.dbo.report_order', $report_order_arr, $where); $this->HT->query($update_sql); @@ -390,7 +398,7 @@ class OrderFinance_model extends CI_Model { public function get_report_order($coli_id=0) { - return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' order by orderID desc")->row(); + return $this->HT->query("SELECT top 1 * from tourmanager.dbo.report_order WHERE ordernumber='$coli_id' and orderstats=1 order by orderID desc")->row(); } public function convert_to_RMB($money=0, $fromCurrency='USD') From 9379f922d6fa9ef372ee03582ca81ab54b3215b1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 Aug 2018 17:46:27 +0800 Subject: [PATCH 127/382] =?UTF-8?q?trippest=20=E5=8D=95=E5=9B=A2=E8=B4=A2?= =?UTF-8?q?=E5=8A=A1=E8=A1=A8:=E4=BF=AE=E6=94=B9=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=80=BB=E4=BA=BA=E6=95=B0=E7=9A=84=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 23 ++++---------- .../models/orderFinance_model.php | 30 +++++++++++++++---- 2 files changed, 29 insertions(+), 24 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index c33e796f..976a9aab 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -71,6 +71,8 @@ class Order_finance extends CI_Controller { $report_order['adultnumber'] = 0; $report_order['childnumber'] = 0; $report_order['babynumber'] = 0; + $report_order['qtCost'] = 0; + $report_order['qtMoney'] = 0; $report_order['orderstats'] = 1; $report_order['ordernumber'] = $order_info->ordernumber; $report_order['TuanName'] = mb_substr($order_info->TuanName, 0, 50); @@ -99,10 +101,7 @@ class Order_finance extends CI_Controller { /** 图兰朵产品: 取拼团实际成本 */ $ret->combine_cost = $ret->report_tour = array(); $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); -// $ret->x = $combineNo_arr; $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); - // $this->output->set_content_type('application/json')->set_output(json_encode($combineNo_arr)); - // $this->output->set_content_type('application/json')->set_output(json_encode($group_type_arr)); $processed_code = array(); // 已处理的产品编号 foreach ($combineNo_arr as $kc => $vc) { if (empty($vc->GCI_combineNo)) { @@ -199,9 +198,7 @@ class Order_finance extends CI_Controller { if ( ! empty($other_tour)) { $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); foreach ($ret->others as $kro => $vro) { - // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); - // test - $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->COLD_TotalCost); + $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); } } /** 火车票预定 */ @@ -209,8 +206,6 @@ class Order_finance extends CI_Controller { if( ! empty($train_detail)) { $ret->train = $this->OrderFinance_model->insert_report_train($coli_sn); foreach ($ret->train as $krt => $vrt) { - // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); - // test $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrt->TotalCost); } } @@ -219,9 +214,7 @@ class Order_finance extends CI_Controller { if ( ! empty($hotel_detail)) { $ret->hotel = $this->OrderFinance_model->insert_report_hotel($coli_sn); foreach ($ret->hotel as $krh => $vrh) { - // $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost); - // test - $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->COLD_TotalCost); + $report_order['basemoney'] = bcadd($report_order['basemoney'], $vrh->roomcost); } } // 订单利润 @@ -279,7 +272,6 @@ class Order_finance extends CI_Controller { } // 重新计算重复次数 $all_pags = array_filter(array_map(function($ele){ return $ele->PAG_Code;}, $all_orders)); -// $ret->s = $all_pags; // 重复的产品号; 可混拼的产品 $repeat_code = array(); $code_count = array_count_values($all_pags); @@ -368,7 +360,6 @@ class Order_finance extends CI_Controller { public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array()) { $ret = new stdClass(); - // $ret->tour = array(); $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code); if (empty($all_orders)) { return null; @@ -386,23 +377,19 @@ class Order_finance extends CI_Controller { $ret->person_num = $person_num->person_num; $ret->adult_num = $person_num->adult_num; $ret->child_num = $person_num->child_num; - // $tour_s = new stdClass(); $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); $ret->startdate = $all_orders[0]->COLD_StartDate; $ret->person_grade = ($all_orders[0]->COLD_PersonNum + $all_orders[0]->COLD_ChildNum ); $ret->cost_category = $combine_cost->cost_category; $ret->cost_sum = $combine_cost->cost_sum; $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num); - $ret->comment = "PVT,共" . $ret->person_num . "人次";// 150 + $ret->comment = "PVT,共" . $ret->person_num . "人"; $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; - // $ret->tour[0] = $tour_s; - // $ret->order_cost = array_sum(array_map(function($ele) {return $ele->cost_sum;}, $ret->tour)); return $ret; - // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); } /*! diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 4f17b59d..fa630c7a 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -117,10 +117,24 @@ class OrderFinance_model extends CI_Model { return $ret; } - /** 获取订单总人数 */ + /** 子订单中人数最多的预定 */ + public function get_max_cold_person_num($coli_sn=0) + { + $sql = "SELECT + ISNULL(MAX(COLD_PersonNum+COLD_ChildNum+ISNULL(COLD_BabyNum,0)), 0) person_num + ,ISNULL(MAX(COLD_PersonNum), 0) adult_num + ,ISNULL(MAX(COLD_ChildNum+ISNULL(COLD_BabyNum,0)), 0) child_num + from BIZ_ConfirmLineDetail + where COLD_COLI_SN=$coli_sn " + $ret = $this->HT->query($sql)->row(); + return $ret; + } + + /** 订单人数 */ public function get_order_person_num($coli_sn=0) { $ret = new stdClass(); + // 从订单客人名单列表中取 $sql = "SELECT BPL_BPE_SN,bp.BPE_GuestType from BIZ_ConfirmLineDetail cold inner join BIZ_BookPeopleList bpl on bpl.BPL_COLD_SN=cold.COLD_SN @@ -130,12 +144,16 @@ class OrderFinance_model extends CI_Model { $query = $this->HT->query($sql); $ret->person_num = $query->num_rows(); $guest_type_cnt = array_count_values(array_map(function($ele) { return $ele->BPE_GuestType; }, $query->result())); - if ($ret->person_num === 0) { - $sql2 = "SELECT COLD_PersonNum,COLD_ChildNum,isnull(COLD_BabyNum,0) COLD_BabyNum from BIZ_ConfirmLineDetail where COLD_COLI_SN=$coli_sn "; - $num_q = $this->HT->query($sql2)->row(); - $ret->person_num = $num_q->COLD_PersonNum + $num_q->COLD_ChildNum + $num_q->COLD_BabyNum; - $ret->adult_num = $num_q->COLD_PersonNum; + // 从子订单的人数中取最大值 + $max_person = $this->get_max_cold_person_num($coli_sn); + if ($ret->person_num === 0 || $ret->person_num < $max_person->person_num) { + // 没有客人名单时, 客人名单小于子订单人数(如新港接送)时 + // 使用子订单结果 + $ret->person_num = $max_person->person_num; + $ret->adult_num = $max_person->adult_num; } else { + // 订单列表人数 >= 子订单最大人数, 如180606288 + // 使用客人名单总数 $ret->adult_num = $guest_type_cnt['1']; } $ret->child_num = $ret->person_num-$ret->adult_num; From 05c1d09e606a8e6cdeb3baa4bba4d017847ab5fe Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 Aug 2018 14:03:38 +0800 Subject: [PATCH 128/382] =?UTF-8?q?trippest=20=E6=9B=B4=E6=96=B0=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=9B=BE=E5=85=B0=E6=9C=B5=E8=AE=A2=E5=8D=95=E8=AE=A1?= =?UTF-8?q?=E5=88=92=E5=9C=B0=E6=8E=A5=E5=8F=96=E6=B6=88=E7=9B=B8=E5=85=B3?= =?UTF-8?q?;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 54 ++++++++++++++----- .../controllers/order_finance.php | 4 +- .../models/orderFinance_model.php | 4 +- .../trippestOrderSync/models/orders_model.php | 25 ++++++--- 4 files changed, 63 insertions(+), 24 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index adb2322a..96580b07 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -254,21 +254,23 @@ class TulanduoApi extends CI_Controller * @date 2018-05-02 * @param [type] $coli_sn HT系统的订单key */ - public function insert_HT_order_operation($coli_sn=null) + public function insert_HT_order_operation($coli_sn=null,$get_vendorID=null) { // if ($coli_sn == null) { // return null; // } log_message('error','get_order_operation From TuLanDuo '); $this->load->model('Order_update'); - if ($coli_sn !== null) { + if ($coli_sn !== null && $coli_sn != 0) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); + } elseif ($get_vendorID !== null) { + $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $get_vendorID); } else { // $startDate = ('2018-04-21'); // $endDate = ('2018-04-22'); // test $startDate = date('Y-m-d', strtotime("-3 days")); $endDate = date('Y-m-d', strtotime("+7 days")); - $to_update_list = $this->Orders_model->get_groupCombineInfo(0, $startDate, $endDate); + $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate); } $unique_orderGroupCombine = array(); $unique_order = array(); @@ -286,14 +288,20 @@ class TulanduoApi extends CI_Controller // 判断取消 if ($detail_jsonResp->status !== 1) { log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); - if ($detail_jsonResp->errMsg == "未查询到对应的订单") { - $this->order_cancel($order->COLI_ID); + if ( $detail_jsonResp->errMsg == "未查询到对应的订单") { + $this->plan_cancel($order->GCI_VendorOrderId); + if (intval($order->COLI_OPI_ID) === 435) { + $this->order_cancel($order->COLI_ID); + } } continue; } // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 - if ( ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) && mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { - $this->order_cancel($order->COLI_ID); + if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { + $this->plan_cancel($order->GCI_VendorOrderId); + if (intval($order->COLI_OPI_ID) === 435) { + $this->order_cancel($order->COLI_ID); + } continue; } $allDetails_to_HT = ""; @@ -328,16 +336,21 @@ class TulanduoApi extends CI_Controller $coli_id = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; $coli_memo = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; $coli_orderdetailtext = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; - $coli_state = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_State : 7; + $coli_state = $getInfo_byGroupCode!==null ? + (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? 7 : $getInfo_byGroupCode->COLI_State) + : 7; $cold_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { - log_message('error','原订单' . $order->COLI_ID); - $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; - $this->order_cancel($order->COLI_ID); + if ( $order->COLI_ID) { + $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; + if (intval($order->COLI_OPI_ID) === 435 ) { + $this->order_cancel($order->COLI_ID); + } + } } - /** biz_groupcombineinfo */ + /** groupcombineinfo */ // $this->Order_update->gci_where_update = " GCI_VEI_SN=$vei_SN and GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; $gci_update_column = array( @@ -597,7 +610,10 @@ class TulanduoApi extends CI_Controller */ public function order_cancel($COLI_ID="") { - log_message('error','修改为不成行 order_cancel' . $COLI_ID); + if ($COLI_ID == '') { + return false; + } + log_message('error','修改为不成行 order_cancel ' . $COLI_ID); /** UPDATE HT */ /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_ID='" . $COLI_ID . "'"; @@ -606,6 +622,16 @@ class TulanduoApi extends CI_Controller ); return $this->Order_update->biz_confirmlineinfo_update($coli_update_column); } + public function plan_cancel($vendorID=0) + { + /** groupcombineinfo */ + $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $vendorID . "'"; + $gci_update_column = array( + "GCI_combineNo" => 'cancel' + ,"GCI_createTime" => date('Y-m-d H:i:s') + ); + $this->Order_update->biz_groupcombineinfo_update($gci_update_column); + } /*! * 发送预订计划到地接系统 @@ -763,7 +789,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); { mb_regex_encoding("UTF-8"); preg_match('/[\w\s\-]+/', $this->characet($groupCode, "UTF-8"), $temp_array); - $temp_array[0] = strrchr($temp_array[0], " ") ? strrchr($temp_array[0], " ") : $temp_array[0]; + $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0] . "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 976a9aab..51082153 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -96,10 +96,10 @@ class Order_finance extends CI_Controller { $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); $report_order['adultnumber'] = $person_num->adult_num; $report_order['childnumber'] = $person_num->child_num; - $ret = new stdClass(); /** 图兰朵产品: 取拼团实际成本 */ - $ret->combine_cost = $ret->report_tour = array(); + $ret->combine_cost = array(); + $ret->report_tour = array(); $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); $processed_code = array(); // 已处理的产品编号 diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index fa630c7a..365a2d95 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -53,7 +53,7 @@ class OrderFinance_model extends CI_Model { { $sql = "SELECT gci.GCI_combineNo,gci.GCI_groupType from GroupCombineInfo gci - inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN + inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN and GCI_combineNo<>'cancel' where coli.COLI_SN=$coli_sn group by gci.GCI_combineNo,gci.GCI_groupType order by gci.GCI_groupType desc"; @@ -125,7 +125,7 @@ class OrderFinance_model extends CI_Model { ,ISNULL(MAX(COLD_PersonNum), 0) adult_num ,ISNULL(MAX(COLD_ChildNum+ISNULL(COLD_BabyNum,0)), 0) child_num from BIZ_ConfirmLineDetail - where COLD_COLI_SN=$coli_sn " + where COLD_COLI_SN=$coli_sn "; $ret = $this->HT->query($sql)->row(); return $ret; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index c047b885..0a44a0ce 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -128,20 +128,33 @@ class Orders_model extends CI_Model { * @param [type] $startDate [description] * @param [type] $endDate [description] */ - public function get_groupCombineInfo($coli_sn=0, $startDate=null, $endDate=NULL) + public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo, + $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, gci.* FROM GroupCombineInfo gci - INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE 1=1 and coli.COLI_State NOT IN ('30','40','50')"; + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') + LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE 1=1 "; if ($coli_sn !== 0) { $sql .= " and coli.COLI_SN='$coli_sn' "; } + if ($get_vendorID !== null) { + $sql .= " and GCI_VendorOrderId='$get_vendorID' "; + } if ($startDate !== NULL) { $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test } + $sql .= "UNION SELECT top 50 + coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + cold.COLD_PlanVEI_SN, gci.* + FROM GroupCombineInfo gci + left JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') + left JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE 1=1 + and (GCI_combineNo='' or GCI_combineNo is null) + and GCI_travelDate < GETDATE() + order by GCI_travelDate"; $query = $this->HT->query($sql); return $query->result(); } @@ -487,7 +500,7 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN From ad2106a438d5ac128fcba41f23bfcaf60ed39fb3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 Aug 2018 16:40:37 +0800 Subject: [PATCH 129/382] =?UTF-8?q?trippest=20=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E9=A1=B5=E9=9D=A2:=20=E6=8C=89=E8=A1=8C=E7=A8=8B?= =?UTF-8?q?=E6=97=A5=E6=9C=9F=E8=BF=94=E5=9B=9E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 115 +++++++------ .../controllers/detail_for_client.md | 157 +++++++++--------- .../trippestOrderSync/models/orders_model.php | 8 +- 3 files changed, 146 insertions(+), 134 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 14a801a5..7d2cada2 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -12,6 +12,8 @@ class Api extends CI_Controller { public function index() { + // echo "string"; + // return; $this->operation_detail(); } @@ -32,57 +34,14 @@ class Api extends CI_Controller { $ret['status'] = 1; $ret['msg'] = ""; $ret['group_number'] = $order_project[0]->COLI_GroupCode; - // 领队名字 - $ret['leader_name'] = trim($order_project[0]->GUT_FirstName . " " . $order_project[0]->GUT_LastName); - $ret['package'] = null; - foreach ($order_project as $kd => $poi) { - $tmp = array(); - // 行程人数 - $tmp['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; - $tmp['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; - if ($poi->COLD_ChildNum > 0) { - $tmp['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; - } - $tmp['personNum_text'] .= ")" ; - // 人数 - $tmp['adult_number'] = $order_project[0]->COLD_PersonNum; - $tmp['kid_number'] = $order_project[0]->COLD_ChildNum; - // 出团时间 - $tmp['start_date'] = $poi->COLD_StartDate; - $tmp['end_date'] = $poi->COLD_EndDate; - $tmp['tour_name'] = $poi->PAG2_Name; - $out_datetime = strtotime($poi->COLD_StartDate); - $tmp['dateWeek_text'] = date('D', $out_datetime); - $tmp['dateDay_text'] = date('d', $out_datetime); - $tmp['dateMonth_text'] = date('M', $out_datetime); - $tmp['dateYear_text'] = date('Y', $out_datetime); - // 接送信息 - $tmp['pick_up'] = ""; - $tmp['drop_off'] = ""; - $decode_MemoText = $memo_text_tmp = ""; - if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { - $decode_MemoText = json_decode($poi->COLD_MemoText, true); - $tmp['pick_up'] = $decode_MemoText['Pick up']; - $tmp['drop_off'] = $decode_MemoText['Drop off']; - } else { - $memo_text_tmp = trim(strstr($poi->COLD_MemoText, "Pick Up From:")); - $tmp['pick_up'] = trim(strstr($memo_text_tmp, "Drop Off:", true)); - $tmp['drop_off'] = trim(strstr($memo_text_tmp, "Drop Off:")); - } - // 酒店 - $tmp['hotel_name'] = $poi->POI_Hotel; - $tmp['hotel_address'] = $poi->POI_HotelAddress; - $tmp['hotel_tel'] = $poi->POI_HotelPhone; - // 航班/车次 - $tmp['flights_no'] = $poi->POI_FlightsNo; - $tmp['flights_airport'] = $poi->POI_AirPort; - - $ret['package'][] = $tmp; - } -log_message('error',$order_project[0]->GCI_combineNo); - $operation = $this->Orders_model->get_operation($order_project[0]->GCI_combineNo); + $all_combine_no = array_unique(array_map(function($ele) + { + return $ele->GCI_combineNo; + }, $order_project)); + $operation = $this->Orders_model->get_operation($all_combine_no); // 司机, 导游 if ( ! empty($operation)) { + // 按照实际安排的日期分组 foreach ($operation as $key => $value) { if ($value->GCOD_operationType === 'touristCarOperations') { $tmp_car = array(); @@ -95,7 +54,9 @@ log_message('error',$order_project[0]->GCI_combineNo); $tmp_car['car_remark'] = $value->GCOD_remark; $tmp_car['using_startdate'] = $value->GCOD_startDate; $tmp_car['using_enddate'] = $value->GCOD_endDate; - $ret['cardriver'][] = $tmp_car; + $ret['operation'][$value->GCOD_startDate]['cardriver'][] = $tmp_car; + // 出团时间 + $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; } else if ($value->GCOD_operationType === 'guiderOperations') { $tmp_g = array(); @@ -105,10 +66,62 @@ log_message('error',$order_project[0]->GCI_combineNo); $tmp_g['guide_remark'] = $value->GCOD_remark; $tmp_g['using_startdate'] = $value->GCOD_startDate; $tmp_g['using_enddate'] = $value->GCOD_endDate; - $ret['tourguide'][] = $tmp_g; + $ret['operation'][$value->GCOD_startDate]['tourguide'][] = $tmp_g; + // 出团时间 + $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; + } + } + // 加上行程 + foreach ($ret['operation'] as $kro => &$vro) { + $out_datetime = strtotime($vro['start_date']); + $vro['dateWeek_text'] = date('D', $out_datetime); + $vro['dateDay_text'] = date('d', $out_datetime); + $vro['dateMonth_text'] = date('M', $out_datetime); + $vro['dateYear_text'] = date('Y', $out_datetime); + foreach ($order_project as $kd => $poi_info) { + if (strcmp($vro['start_date'], substr($poi->COLD_StartDate, 0, 10) ) === 0) { + $poi = $poi_info; + } else { + $poi = $order_project[0]; + } + $vro['tour_name'] = $poi->PAG2_Name; + // 领队名字 + $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // 行程人数 + $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; + $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; + if ($poi->COLD_ChildNum > 0) { + $vro['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; + } + $vro['personNum_text'] .= ")" ; + // 人数 + $vro['adult_number'] = $order_project[0]->COLD_PersonNum; + $vro['kid_number'] = $order_project[0]->COLD_ChildNum; + // 酒店 + $vro['hotel_name'] = $poi->POI_Hotel; + $vro['hotel_address'] = $poi->POI_HotelAddress; + $vro['hotel_tel'] = $poi->POI_HotelPhone; + // 航班/车次 + $vro['flights_no'] = $poi->POI_FlightsNo; + $vro['flights_airport'] = $poi->POI_AirPort; + // 接送信息 + $vro['pick_up'] = ""; + $vro['drop_off'] = ""; + $decode_MemoText = $memo_text_tmp = ""; + if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { + $decode_MemoText = json_decode($poi->COLD_MemoText, true); + $vro['pick_up'] = $decode_MemoText['Pick up']; + $vro['drop_off'] = $decode_MemoText['Drop off']; + } else { + $memo_text_tmp = trim(strstr($poi->COLD_MemoText, "Pick Up From:")); + $vro['pick_up'] = trim(strstr($memo_text_tmp, "Drop Off:", true)); + $vro['drop_off'] = trim(strstr($memo_text_tmp, "Drop Off:")); + } } } + unset($vro); } + $ret['operation'] = array_values($ret['operation']); $operator = $this->Orders_model->get_operator($order_project[0]->COLI_OPI_ID); if ( ! empty($operator)) { $ret['operator']['chinese_name'] = $operator->OPI_Name; diff --git a/webht/third_party/trippestOrderSync/controllers/detail_for_client.md b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md index 318f5540..5363494b 100644 --- a/webht/third_party/trippestOrderSync/controllers/detail_for_client.md +++ b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md @@ -3,92 +3,89 @@ #### POST / GET > `http://www.mycht.cn/webht.php/apps/trippestOrderSync/Api/operation_detail` -参数| 类型 | 示例 ---- | --- | --- -q | string | 180601019 +参数| 类型 | 示例 | - +--- | --- | --- | --- +q | string | 180601019 | 渠道订单, 不返回外联信息 + | | 180524043M | 单接送+Day Tour,共4天 #### RETURN JSON ```json { - "status": 1, // 查询结果; 1-成功; 0-失败 - "msg": "", // 失败信息: Not Found. - "order_info": { - "GCI_SN": 619, - "GCI_VendorOrderId": "18586", - "GCI_combineNo": "S-2018-06-03[25]", - "COLI_SN": 435010334, - "COLI_ID": "180601019", - "COLD_SN": 450021160, - "COLI_GroupCode": "中华游180603-Micky170713021-CHBJ", // 团号 - "COLI_OPI_ID": 435, - "COLD_ServiceSN": 4243, - "COLD_PersonNum": 1, // 成人数量 - "COLD_ChildNum": 0, // 小孩数量 - "COLD_StartDate": "2018-06-03 00:00:00", // 行程日期 - "PAG2_Name": "One-Day Beijing Highlights Mini Group Tour", // 行程名字 - // 酒店相关 - "POI_Hotel": "北京海航大厦万豪酒店", - "POI_HotelAddress": "No.26 Jia Xiaoyun Road, Chaoyang District, Beijing, China北京 朝阳区 霄云路甲26号 ", - "POI_HotelPhone": "010-59278888", - - "leader_name": "Jorge Latorre Alagon", // 领队 - "personNum_text": "1 (1 Adult(s))", // 人数 输出可读 - // 日期 输出可读 - "dateWeek_text": "Sun", - "dateDay_text": "03", - "dateMonth_text": "Jun", - "dateYear_text": "2018", - "pick_up": "北京海航大厦万豪酒店 Beijing Marriott Hotel Northeast", - "drop_off": "北京海航大厦万豪酒店 Beijing Marriott Hotel Northeast" - }, - "operator_info": { // Travel Advisor 信息 - "OPI_SN": 161, - "OPI_Name": "黄俊峻", - "OPI_FirstName": "Niko", - "OPI_MoveTelephone": "18807734970", - "OPI_Email": "niko@chinahighlights.com", - "OPI2_Name": "Niko Huang" // 英文名 - }, - "operation_info": { - "touristCarOperations": { // 车辆,司机信息 - "GCOD_SN": 127883, - "GCOD_VEI_SN": 1343, - "GCOD_GCI_combineNo": "S-2018-06-03[25]", - "GCOD_operationType": "touristCarOperations", - "GCOD_subType": "7座", // 车辆类型 - "GCOD_title": "上海秦健", // 车队,公司 - "GCOD_dutyName": "Mr Qin 秦师傅", // 司机姓名 - "GCOD_dutyTel": "17765106848", // 司机联系电话 - "GCOD_dutyPhoto": null, // 司机头像 - "GCOD_startDate": "2018-06-03", - "GCOD_endDate": "2018-06-03", - "GCOD_useNum": 1, - "GCOD_sumMoney": "800", - "GCOD_standard": "", - "GCOD_carLicense": "沪AZJ228", // 车辆牌照 - "GCOD_remark": "精品一日游;3人;北京瑞吉酒店/北京海航大厦万豪酒店 ", - "GCOD_creatTime": "2018-06-03 23:59:00" - }, - "guiderOperations": { // 导游信息, 单接送的订单没有这个对象 - "GCOD_SN": 127884, - "GCOD_VEI_SN": 1343, - "GCOD_GCI_combineNo": "S-2018-06-03[25]", - "GCOD_operationType": "guiderOperations", - "GCOD_subType": "", - "GCOD_title": "", - "GCOD_dutyName": "北京张豹勋William", // 导游姓名 - "GCOD_dutyTel": "18810790590", // 导游联系电话 - "GCOD_dutyPhoto": "http://djb3c.ltsoftware...", // 导游头像 - "GCOD_startDate": "2018-06-03", - "GCOD_endDate": "2018-06-03", - "GCOD_useNum": 1, - "GCOD_sumMoney": "300", - "GCOD_standard": "", - "GCOD_carLicense": "", - "GCOD_remark": "", - "GCOD_creatTime": "2018-06-03 23:59:00" + "status": 1, // 查询结果; 1-成功; 0-失败 + "msg": "", // 失败信息: Not Found. + "group_number": "CHBJ180621-BHJ180619085M", // 团号 + // 团计划安排详情, 按日期顺序的多个对象 + "operation": [ + { + // 日期 输出可读 + "start_date": "2018-06-21", + "dateWeek_text": "Thu", + "dateDay_text": "21", + "dateMonth_text": "Jun", + "dateYear_text": "2018", + // 行程名字 + "tour_name": "One-way Private Transfer Between Beijing Airport/Train Station and Your Hotel (Driver Service Only)", // 行程名字 + "leader_name": "Sarah Carbis", // 领队 + "personNum_text": "1 (1 Adult(s))", // 人数 输出可读 + "adult_number": 10, // 成人数量 + "kid_number": 0, // 小孩数量 + // 酒店相关 + "hotel_name": "Capital Hotel", + "hotel_address": "", + "hotel_tel": "", + // 航班 + "flights_no": "LH720", + "flights_airport": "", + // 接送信息 + "pick_up": "", + "drop_off": "", + // 车辆安排详情 安排不同车分别接客人的订单示例: 180606288 + "cardriver": [ + { + "car_type": "丰田大马", // 车辆类型 + "car_company": "北京-王会生13051277931(奔面系列)", // 车队,公司 + "car_license": "京B06528/white/12 seats van", // 车辆牌照,车辆信息 + // 司机 + "driver_name": "Mr.Li 李胜利", + "driver_tel": "13522003813", + "driver_pic": null, + "car_remark": "单租车酒店接客人送大董烤鸭(金宝汇店);10人;北京首都大酒店 ", + "using_startdate": "2018-06-21", + "using_enddate": "2018-06-21" + }, + { + "car_type": "5座轿车", + "car_company": "凯美瑞车队-宋师傅13811026411", + "car_license": "*", + "driver_name": "a-TBC", + "driver_tel": "*", + "driver_pic": null, + "car_remark": "单租车接机;1人;首都大酒店;接LH720(Arr0830@T3);", + "using_startdate": "2018-06-21", + "using_enddate": "2018-06-21" + } + ], + // 导游安排, 单接送的订单没有这个对象 + "tourguide": [ + { + "guide_name": "北京徐宝宝Tom", // 导游姓名 + "guide_tel": "18511135908", // 导游联系电话 + "guide_pic": "", // 导游头像 + "guide_remark": "", + "using_startdate": "2018-07-09", + "using_enddate": "2018-07-10" + } + ], } + ], + // 外联信息 + // 如果是渠道订单则没有这个对象 + "operator": { + "chinese_name": "黄俊峻", + "mobile": "18807734970", + "email": "niko@trippest.com", + "english_name": "Niko Huang" } } ``` diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 0a44a0ce..e8292d47 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1265,7 +1265,7 @@ class Orders_model extends CI_Model { ,poi.POI_AirPort,poi.POI_FlightsNo ,GUT_FirstName,GUT_LastName FROM BIZ_ConfirmLineInfo coli - inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN + inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN --and GCI_combineNo<>'cancel' inner join BIZ_ConfirmLineDetail cold on COLD_COLI_SN=COLI_SN inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN @@ -1297,10 +1297,12 @@ class Orders_model extends CI_Model { function get_operation($combineNo) { + $combineNos = my_implode("'",",",$combineNo); $operation_sql = "SELECT gcod.* from GroupCombineOperationDetail gcod - where GCOD_GCI_combineNo=? - and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + where GCOD_GCI_combineNo in ($combineNos) + and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations') + order by GCOD_startDate"; $operation_info = $this->HT->query($operation_sql, array($combineNo)); return $operation_info->result(); } From 2ba03b44302fcaa55a80653346211e4ee079b357 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 9 Aug 2018 16:37:41 +0800 Subject: [PATCH 130/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=95=B0=E6=8D=AE=E5=A1=AB=E5=86=99=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E6=80=BB=E6=8A=A5=E4=BB=B7=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 18 ++++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 9 ++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 96580b07..7d777d49 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -68,6 +68,7 @@ class TulanduoApi extends CI_Controller // $this->userId = "18"; // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; mb_regex_encoding("UTF-8"); + bcscale(4); } /*! @@ -368,10 +369,27 @@ class TulanduoApi extends CI_Controller $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; + // 团款总金额 美元币种 + $travel_fee = 0; + $travel_fee_currency = 'RMB'; + if (isset($detail_jsonResp->orderDetail->travelFees) ) { + foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { + $travel_fee = bcadd($travel_fee, $vtf->sumMoney); + } + unset($vtf); + } + $travel_fee = $getInfo_byGroupCode!==null ? + (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee : $getInfo_byGroupCode->COLI_Price) + : $travel_fee; + $travel_fee_currency = $getInfo_byGroupCode!==null ? + (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee_currency : $getInfo_byGroupCode->COLI_CUrrency) + : $travel_fee_currency; $coli_update_column = array( "COLI_Memo" => substr($new_memo, 0, 400) ,"COLI_OrderDetailText" => $new_detail ,"COLI_State" => $coli_state + ,"COLI_Price" => $travel_fee + ,"COLI_CUrrency" => $travel_fee_currency ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e8292d47..8fa7dfcf 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -500,7 +500,7 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN @@ -1781,6 +1781,13 @@ class Orders_model extends CI_Model { } } + public function convert_RMB_to_currency($money=0, $toCurrency='USD') + { + return $this->HT + ->query("SELECT tourmanager.dbo.[ConvertCurrencyToCurrency](1,'RMB','$toCurrency',$money) as rmb ") + ->row()->rmb; + } + public function test() { // return NULL; From a239cc12e9fd62518359eb439d1225e288d334e3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 Aug 2018 11:34:23 +0800 Subject: [PATCH 131/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=20?= =?UTF-8?q?=E6=B5=B7=E7=BA=B3=E7=9A=84=E7=9B=B4=E6=8E=A5=E5=8F=96=E5=8E=9F?= =?UTF-8?q?=E6=9D=A5=E7=9A=84=E5=9B=A2GRI=5FSN?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 14 ++++-- .../trippestOrderSync/models/orders_model.php | 44 +++++++++++++------ 2 files changed, 41 insertions(+), 17 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 7d777d49..7f91f62e 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -167,6 +167,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; + // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); @@ -174,10 +175,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); } /** insert HT */ - if ($this->Orders_model->BIZ_COLI_SN === null) { - /** BIZ_Guest */ - $this->Orders_model->GUT_LastName = $vo['customerName']; - $this->Orders_model->biz_guest_save(); + if ($this->Orders_model->GRI_SN === null) { /** GRoupInfo */ $travelDate = new DateTime($vo['travelDate']); $leaveDate = new DateTime($vo['leaveDate']); @@ -189,7 +187,15 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); $this->Orders_model->GRI_IsCancel = 0; $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->GRI_OPI_ID = 435; + $this->Orders_model->GRI_operator = 435; + $this->Orders_model->GRI_Creator = 435; $this->Orders_model->groupinfo_save(); + } + if ($this->Orders_model->BIZ_COLI_SN === null) { + /** BIZ_Guest */ + $this->Orders_model->GUT_LastName = $vo['customerName']; + $this->Orders_model->biz_guest_save(); /**BIZ_ConfirmLineInfo*/ $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_No : ""; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 8fa7dfcf..eda06437 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -231,6 +231,10 @@ class Orders_model extends CI_Model { public $GRI_Days; // 行程天数 public $GRI_IsCancel=0; public $GRI_DeleteFlag=0; + public $GRI_OPI_ID=0; + public $GRI_operator=0; + public $GRI_Creator=0; + public $GRI_CreateDate=0; /** 团信息 */ public function groupinfo_save() { @@ -241,8 +245,12 @@ class Orders_model extends CI_Model { ,GRI_Days ,GRI_IsCancel ,DeleteFlag + ,GRI_OPI_ID + ,GRI_operator + ,GRI_Creator + ,GRI_CreateDate ,GRI_OrderType) - VALUES (N?,N?,?,?,?,?,?)"; + VALUES (N?,N?,?,?,?,?,?,?,?,GETDATE(),?)"; $query = $this->HT->query($sql, array( $this->GRI_No, $this->GRI_Name, @@ -250,6 +258,9 @@ class Orders_model extends CI_Model { $this->GRI_Days, $this->GRI_IsCancel, $this->GRI_DeleteFlag, + $this->GRI_OPI_ID, + $this->GRI_operator, + $this->GRI_Creator, $this->GRI_OrderType )); $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); @@ -500,19 +511,26 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $NoName) { - $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency - FROM BIZ_ConfirmLineInfo coli - inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN - LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - WHERE gri.GRI_No LIKE '%$code%' and gri.GRI_Name like '%$NoName%' "; - $query = $this->HT->query($sql); - if ($query->row()) { - $this->BIZ_COLI_SN = $query->row()->COLI_SN; - $this->GRI_SN = $query->row()->GRI_SN; - $this->COLD_PlanVEI_SN = $query->row()->COLD_PlanVEI_SN; - return $query->row(); + $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name + from GRoupInfo + where GRI_Name like '%$code%' "; + $gri_query = $this->HT->query($gri_sql); + if ($gri_query->num_rows() > 0) { + $this->GRI_SN = $gri_query->row()->GRI_SN; + $this->GRI_operator = $gri_query->row()->GRI_operator; + $coli_sql = "SELECT top 1 COLI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo, + coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + where COLI_GRI_SN=" . $this->GRI_SN; + $coli_query = $this->HT->query($coli_sql); + if ($coli_query->num_rows() > 0) { + $this->BIZ_COLI_SN = $coli_query->row()->COLI_SN; + $this->COLD_PlanVEI_SN = $coli_query->row()->COLD_PlanVEI_SN; } - return NULL; + return json_decode(json_encode(array_merge(json_decode(json_encode($gri_query->row()), true), json_decode(json_encode($coli_query->row()), true)))); + } + return NULL; } /*! From 9edf348ef1c7bfbbd12a3b50231122f995e551a0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 Aug 2018 13:45:53 +0800 Subject: [PATCH 132/382] =?UTF-8?q?trippest=20=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2:=20=E8=8E=B7=E5=8F=96=E6=B5=B7=E7=BA=B3=E4=BC=A0?= =?UTF-8?q?=E7=BB=9F=E5=9B=A2=E7=9A=84=E7=BB=84=E5=9B=A2=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 4 +-- .../trippestOrderSync/controllers/api.php | 13 ++++++-- .../controllers/detail_for_client.md | 2 +- .../helpers/array_helper.php | 33 +++++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 19 +++++++++-- 5 files changed, 63 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 7f91f62e..6afa0a6f 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -51,6 +51,8 @@ class TulanduoApi extends CI_Controller public function __construct(){ parent::__construct(); + mb_regex_encoding("UTF-8"); + bcscale(4); $this->load->helper('array'); $this->load->model('Orders_model'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); @@ -67,8 +69,6 @@ class TulanduoApi extends CI_Controller // 桂林海纳国旅 // $this->userId = "18"; // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; - mb_regex_encoding("UTF-8"); - bcscale(4); } /*! diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 7d2cada2..26ca2b25 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -5,9 +5,9 @@ class Api extends CI_Controller { public function __construct(){ parent::__construct(); + mb_regex_encoding("UTF-8"); $this->load->helper('array'); $this->load->model('Orders_model'); - mb_regex_encoding("UTF-8"); } public function index() @@ -38,6 +38,7 @@ class Api extends CI_Controller { { return $ele->GCI_combineNo; }, $order_project)); + $ret['operation'] = null; $operation = $this->Orders_model->get_operation($all_combine_no); // 司机, 导游 if ( ! empty($operation)) { @@ -122,7 +123,15 @@ class Api extends CI_Controller { unset($vro); } $ret['operation'] = array_values($ret['operation']); - $operator = $this->Orders_model->get_operator($order_project[0]->COLI_OPI_ID); + /** 外联信息 */ + $raw_opi_id = 0; + if (intval($order_project[0]->COLI_OPI_ID) === 435) { + $real_code = analysis_groupCode($ret['group_number']); + $raw_opi_id = $this->Orders_model->get_gri_opi_id($real_code); + } else { + $raw_opi_id = $order_project[0]->COLI_OPI_ID; + } + $operator = $this->Orders_model->get_operator($raw_opi_id); if ( ! empty($operator)) { $ret['operator']['chinese_name'] = $operator->OPI_Name; $ret['operator']['mobile'] = $operator->OPI_MoveTelephone; diff --git a/webht/third_party/trippestOrderSync/controllers/detail_for_client.md b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md index 5363494b..6882369c 100644 --- a/webht/third_party/trippestOrderSync/controllers/detail_for_client.md +++ b/webht/third_party/trippestOrderSync/controllers/detail_for_client.md @@ -5,7 +5,7 @@ 参数| 类型 | 示例 | - --- | --- | --- | --- -q | string | 180601019 | 渠道订单, 不返回外联信息 +q | string | 180807025 | 渠道订单, 不返回外联信息 | | 180524043M | 单接送+Day Tour,共4天 #### RETURN JSON diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 006ff0bf..2e9bf4f0 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -108,3 +108,36 @@ function raw_json_encode($input, $flags = 0) { }; return preg_replace_callback($pattern, $callback, json_encode($input, $flags)); } +/*! + * 目的地项目组的订单计划的团号分析 + * 去除添加的后缀, 只保留前两部分: XXXXXX-YYYYYYYYYYYY + * @date 2018-05-02 + * @param [type] $groupCode 从地接系统获取到的团号 + */ +function analysis_groupCode($groupCode) +{ + mb_regex_encoding("UTF-8"); + preg_match('/[\w\s\-]+/', characet($groupCode, "UTF-8"), $temp_array); + $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; + $tmp_groupCode = explode("-", trim($temp_array[0])); + $real_groupCode = $tmp_groupCode[0] . "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); + return $real_groupCode; +} +/*! + * 转换字符集编码 + * @param $data + * @param $targetCharset + * @return string + */ +function characet($data, $targetCharset) { + if (!empty($data)) { + $fileType = "UTF-8"; + if (strcasecmp($fileType, $targetCharset) != 0) { + $data = mb_convert_encoding($data, $targetCharset, $fileType); + // $data = iconv($fileType, $targetCharset.'//IGNORE', $data); + } + } + return $data; +} diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index eda06437..2d55e17e 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -518,10 +518,10 @@ class Orders_model extends CI_Model { if ($gri_query->num_rows() > 0) { $this->GRI_SN = $gri_query->row()->GRI_SN; $this->GRI_operator = $gri_query->row()->GRI_operator; - $coli_sql = "SELECT top 1 COLI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo, - coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + $coli_sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo, coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN where COLI_GRI_SN=" . $this->GRI_SN; $coli_query = $this->HT->query($coli_sql); if ($coli_query->num_rows() > 0) { @@ -533,6 +533,19 @@ class Orders_model extends CI_Model { return NULL; } + /** 获取海纳团的发团人 */ + public function get_gri_opi_id($code) + { + $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,isnull(GRI_operator,0) GRI_operator,GRI_No,GRI_Name + from GRoupInfo + where GRI_Name like '%$code%' "; + $gri_query = $this->HT->query($gri_sql); + if ($gri_query->num_rows() > 0) { + return $gri_query->row()->GRI_operator; + } + return 0; + } + /*! * 获取地接社接受计划的人员信息 * @param $vendorID 地接社ID @@ -1304,7 +1317,7 @@ class Orders_model extends CI_Model { return $ret; } - function get_operator($OPI_SN) + function get_operator($OPI_SN=0) { $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name from OperatorInfo opi From 6bce4aca18960c84723a801f0503ef6656df7c38 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 Aug 2018 15:17:03 +0800 Subject: [PATCH 133/382] =?UTF-8?q?trippest=20=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2:=20=E6=8E=A5=E9=80=81=E4=BF=A1=E6=81=AF=E4=BB=8E?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E8=AF=A6=E6=83=85orderDetailText=E4=B8=AD?= =?UTF-8?q?=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/api.php | 5 ++--- webht/third_party/trippestOrderSync/models/orders_model.php | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 26ca2b25..0f333e54 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -114,9 +114,8 @@ class Api extends CI_Controller { $vro['pick_up'] = $decode_MemoText['Pick up']; $vro['drop_off'] = $decode_MemoText['Drop off']; } else { - $memo_text_tmp = trim(strstr($poi->COLD_MemoText, "Pick Up From:")); - $vro['pick_up'] = trim(strstr($memo_text_tmp, "Drop Off:", true)); - $vro['drop_off'] = trim(strstr($memo_text_tmp, "Drop Off:")); + $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); + $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); } } } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 2d55e17e..6a9fbeb5 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1289,7 +1289,7 @@ class Orders_model extends CI_Model { { $order_info_sql = "SELECT GCI_SN,GCI_VendorOrderId,GCI_combineNo - ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID + ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText ,pag2.PAG2_Name ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone From ddf0319e2038ed4b1e7f714bf4c3cc48ad5900ae Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 Aug 2018 17:19:16 +0800 Subject: [PATCH 134/382] =?UTF-8?q?=E6=89=8B=E5=8A=A8=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E8=B0=83=E5=BA=A6=E5=B9=B6=E8=BE=93=E5=87=BA?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 12 ++++ .../trippestOrderSync/views/operation.php | 61 +++++++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 webht/third_party/trippestOrderSync/views/operation.php diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 6afa0a6f..4f600884 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -803,6 +803,18 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } + public function refresh_operation($coli_sn=0) + { + $this->load->model('OrderFinance_model', 'combine_model'); + // $this->insert_HT_order_operation($coli_sn); + echo "string"; + $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn); + foreach ($data['combineNo_arr'] as $kcn => $vcn) { + $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo); + } + $this->load->view('operation',$data); + } + /*! * 目的地项目组的订单计划的团号分析 * 去除添加的后缀, 只保留前两部分: XXXXXX-YYYYYYYYYYYY diff --git a/webht/third_party/trippestOrderSync/views/operation.php b/webht/third_party/trippestOrderSync/views/operation.php new file mode 100644 index 00000000..01570053 --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/operation.php @@ -0,0 +1,61 @@ +<!DOCTYPE html> +<html> + <head> + <meta http-equiv=Content-Type content="text/html; charset=utf-8"> + <title>operation</title> + <style type=text/css>* { margin:0; font-family: Verdana, Arial, Helvetica, sans-serif; }body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size:13px; color:#545454; right: auto; background-color: #FFFBF0;}img, ul, ul li { padding:0; margin:0; border:0; }#warp { border-top:8px solid #a31022!important; }#logo { border: none!important}#logo, #surveyContent { width:160mm; margin:5px auto; padding:5px; }h1 { margin:15px 0 10px 0; font-size:24px; border-bottom:1px solid #d9d9d9; color:#545454; }h2 { margin:15px 0 10px 0; font-size:20px; color:#545454; } h3{background-color: #ccc; font-size: 14px; font-weight: bold;margin:5px 0;padding: 10px 0;} .tableSurvey table td { padding:5px; }.tableSurvey table td strong { margin-top:8px; }.tableSurvey1 { border:1px solid #e1e1e1; }.tableSurvey1 th { border:1px solid #fff; height:30px; padding-right:10px; text-align:right; background:#f1f1f1; }.tableSurvey1 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.tableSurvey2 { border:1px solid #e1e1e1; }.tableSurvey2 th { border:1px solid #fff; padding:5px 10px; text-align:right; background:#f1f1f1; font-weight:normal; }.tableSurvey2 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.blue{ color:#0070C0} + </style> + </head> + <body> + <?php + $operation_type = array( + "guiderOperations" => "导服", + "otherCosts" => "其他", + "touristCarOperations" => "用车", + "sceneryOperations" => "门票", + "restraurantOperations" => "用餐" + ); + ?> + <div id=warp> + <div id=surveyContent> + <?php foreach ($combineNo_arr as $kcn => $vcn) { ?> + <h3 height=33 colspan=2 class=captd align=center> + <?php echo intval($vcn->GCI_groupType)===1 ? "PVT" : "拼团号" ?>&nbsp;&nbsp; + <?php echo $vcn->GCI_combineNo; ?> + </h3> + <table border=1 cellspacing=0 cellpadding=3 width=100%> + <tr> + <td colspan=2 bgcolor=#ECECEC> + <b>总成本: ¥&nbsp;<?php echo $vcn->cost->cost_sum; ?></b> + </td> + </tr> + <tr> + <td colspan=2 bgcolor=#ECECEC> + <b>成本明细: </b> + </td> + </tr> + <?php foreach ($vcn->cost->cost_detail as $kc => $vc) { ?> + <tr> + <td width=60% > + <p> + <?php echo $operation_type[$vc->GCOD_operationType]; ?> + <?php //echo $vc->GCOD_subType; + if ($vc->GCOD_subType) { + echo " - " . $vc->GCOD_subType; + } + ?> + </p> + </td> + <td width=40% align="right"> + <div> + <?php echo ($vc->cost); ?> + </div> + </td> + </tr> + <?php } ?> + </table> + <?php } ?> + </div> + </div> + </body> +</html> From 4d86c0dc25d16a8ac5631b22cbeb9b9d99746ddc Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 Aug 2018 10:41:46 +0800 Subject: [PATCH 135/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=E6=B5=B7?= =?UTF-8?q?=E7=BA=B3=E7=9A=84=E5=9B=A2=E4=BD=BF=E7=94=A8=E6=B5=B7=E7=BA=B3?= =?UTF-8?q?=E7=9A=84=E5=9B=A2=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 14 ++++++++------ .../trippestOrderSync/models/orders_model.php | 5 +++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4f600884..cb5be68c 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -165,11 +165,13 @@ class TulanduoApi extends CI_Controller $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); - $this->Orders_model->BIZ_COLI_SN = $this->Orders_model->GRI_SN = $this->Orders_model->GCI_SN = null; + $this->Orders_model->BIZ_COLI_SN = null; + $this->Orders_model->GRI_SN = null; + $this->Orders_model->GCI_SN = null; $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 - if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { + if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest", "桂林海纳国旅"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); @@ -203,7 +205,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); $this->Orders_model->BIZ_COLI_ApplyDate = $vo['orderDate']; $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$vo['operationDep']]) ? 32090 : $this->city_info[$vo['operationDep']]['COLI_sourcetype']; - $this->Orders_model->BIZ_COLI_State = 7; + $this->Orders_model->BIZ_COLI_State = 9; $this->Orders_model->BIZ_COLI_servicetype = 'D'; $this->Orders_model->BIZ_COLI_ConfirmType = 52001; $this->Orders_model->BIZ_COLI_Memo = ""; @@ -222,7 +224,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->COLD_EndDate = $vo['leaveDate']; $this->Orders_model->COLD_PersonNum = $vo['adultNum']; $this->Orders_model->COLD_ChildNum = $vo['childNum']; - $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 7 : 4; // 7已确认 // 4 下计划未确认 + $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 9 : 104; // 9订妥 // 104联络地接中 $this->Orders_model->DeleteFlag = 0; $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->COLD_MemoText = $COLD_MemoText; @@ -344,8 +346,8 @@ class TulanduoApi extends CI_Controller $coli_memo = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; $coli_orderdetailtext = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; $coli_state = $getInfo_byGroupCode!==null ? - (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? 7 : $getInfo_byGroupCode->COLI_State) - : 7; + (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? 9 : $getInfo_byGroupCode->COLI_State) + : 9; $cold_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 6a9fbeb5..0e23532c 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -152,9 +152,10 @@ class Orders_model extends CI_Model { left JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') left JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN WHERE 1=1 - and (GCI_combineNo='' or GCI_combineNo is null) - and GCI_travelDate < GETDATE() + and COLI_OPI_ID=435 and COLI_Price is null order by GCI_travelDate"; + // -- and (GCI_combineNo='' or GCI_combineNo is null) + // -- and GCI_travelDate < GETDATE() $query = $this->HT->query($sql); return $query->result(); } From 594109d75bf40aeba38494868b0a5f5284438e71 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 Aug 2018 13:25:26 +0800 Subject: [PATCH 136/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=E4=BF=AE?= =?UTF-8?q?=E6=AD=A3=E4=B8=80=E4=BA=9B=E5=88=A4=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 46 +++++++++++-------- .../trippestOrderSync/models/orders_model.php | 27 ++++++----- 2 files changed, 41 insertions(+), 32 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index cb5be68c..9118adc0 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -341,18 +341,18 @@ class TulanduoApi extends CI_Controller $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); } $groupSN = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->GRI_SN : $order->COLI_GRI_SN; - $coli_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_SN : $order->COLI_SN; - $coli_id = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; - $coli_memo = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; - $coli_orderdetailtext = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; - $coli_state = $getInfo_byGroupCode!==null ? + $coli_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_SN : $order->COLI_SN; + $coli_id = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; + $coli_memo = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; + $coli_orderdetailtext = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; + $coli_state = isset($getInfo_byGroupCode->COLI_SN) ? (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? 9 : $getInfo_byGroupCode->COLI_State) : 9; - $cold_sn = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; + $cold_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { - if ( $order->COLI_ID) { + if ( $order->COLI_ID && $order->COLI_ID != $getInfo_byGroupCode->COLI_ID) { $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; if (intval($order->COLI_OPI_ID) === 435 ) { $this->order_cancel($order->COLI_ID); @@ -386,10 +386,10 @@ class TulanduoApi extends CI_Controller } unset($vtf); } - $travel_fee = $getInfo_byGroupCode!==null ? + $travel_fee = isset($getInfo_byGroupCode->COLI_SN) ? (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee : $getInfo_byGroupCode->COLI_Price) : $travel_fee; - $travel_fee_currency = $getInfo_byGroupCode!==null ? + $travel_fee_currency = isset($getInfo_byGroupCode->COLI_SN) ? (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee_currency : $getInfo_byGroupCode->COLI_CUrrency) : $travel_fee_currency; $coli_update_column = array( @@ -401,16 +401,20 @@ class TulanduoApi extends CI_Controller ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update + // query latest order detail + $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { - foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { - $this->Orders_model->BPE_FirstName = $vd->name; - $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; - $this->Orders_model->BPE_Passport = $vd->documentNo; - $bpe_sn[] = $this->Orders_model->biz_book_people_save(); - // BIZ_BookPeopleList - $this->Orders_model->biz_bookpeople_List_save($cold_sn, $this->Orders_model->BPE_SN); + if (isset($detail_jsonResp->orderDetail->customers)) { + foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { + $this->Orders_model->BPE_FirstName = $vd->name; + $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; + $this->Orders_model->BPE_Passport = $vd->documentNo; + $bpe_sn[] = $this->Orders_model->biz_book_people_save(); + // BIZ_BookPeopleList + $this->Orders_model->biz_bookpeople_List_save($cold_sn, $this->Orders_model->BPE_SN); + } } } /*BIZ_PackageOrderInfo*/ @@ -429,7 +433,7 @@ class TulanduoApi extends CI_Controller $auto_text = "dataAutoEnter "; // 删除旧的录入 $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); - if (isset($detail_jsonResp->orderDetail->travelFees) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { + if (isset($detail_jsonResp->orderDetail->travelFees) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { // if ($vtf->reviewStatus == 0) { // 未审核的 // continue; @@ -449,7 +453,7 @@ class TulanduoApi extends CI_Controller } // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. todo // 代收 - if (isset($detail_jsonResp->orderDetail->replaceCollections) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { + if (isset($detail_jsonResp->orderDetail->replaceCollections) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { // if ($vrc->reviewStatus == 0) { // continue; @@ -468,7 +472,7 @@ class TulanduoApi extends CI_Controller } } // 代付 - if (isset($detail_jsonResp->orderDetail->replacePays) && ! in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest")) ) { + if (isset($detail_jsonResp->orderDetail->replacePays) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { // if ($vrp->reviewStatus == 0) { // continue; @@ -830,7 +834,9 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0] . "-"; - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + if (isset($tmp_groupCode[1])) { + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + } $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); return $real_groupCode; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 0e23532c..b74d9cbc 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -145,17 +145,18 @@ class Orders_model extends CI_Model { if ($startDate !== NULL) { $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test } - $sql .= "UNION SELECT top 50 - coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - cold.COLD_PlanVEI_SN, gci.* - FROM GroupCombineInfo gci - left JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') - left JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - WHERE 1=1 - and COLI_OPI_ID=435 and COLI_Price is null - order by GCI_travelDate"; - // -- and (GCI_combineNo='' or GCI_combineNo is null) - // -- and GCI_travelDate < GETDATE() + // $sql .= "UNION SELECT top 50 + // coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + // cold.COLD_PlanVEI_SN, gci.* + // FROM GroupCombineInfo gci + // left JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') + // left JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + // WHERE 1=1 + // and not exists ( + // select * from BIZ_GroupAccountInfo where GAI_COLI_SN=COLI_SN + // ) + // and COLI_OPI_ID=435 + // order by GCI_travelDate"; $query = $this->HT->query($sql); return $query->result(); } @@ -518,12 +519,14 @@ class Orders_model extends CI_Model { $gri_query = $this->HT->query($gri_sql); if ($gri_query->num_rows() > 0) { $this->GRI_SN = $gri_query->row()->GRI_SN; + $this->GRI_No = $gri_query->row()->GRI_No; $this->GRI_operator = $gri_query->row()->GRI_operator; $coli_sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo, coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - where COLI_GRI_SN=" . $this->GRI_SN; + where COLI_GroupCode like '%$code%' "; + // where COLI_GRI_SN=" . $this->GRI_SN; $coli_query = $this->HT->query($coli_sql); if ($coli_query->num_rows() > 0) { $this->BIZ_COLI_SN = $coli_query->row()->COLI_SN; From 0f75fff5a28d3277dca1b84d6e080d7ae18fc7c8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 Aug 2018 17:57:26 +0800 Subject: [PATCH 137/382] =?UTF-8?q?trippest=E5=90=8C=E6=AD=A5:=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=88=A4=E6=96=AD=E5=9B=A2=E5=8F=B7=E6=98=AF=E5=90=A6?= =?UTF-8?q?=E5=B7=B2=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 4 ++-- .../trippestOrderSync/models/orders_model.php | 14 ++++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 9118adc0..4ac131df 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -174,7 +174,7 @@ class TulanduoApi extends CI_Controller if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest", "桂林海纳国旅"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model - $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); + $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); } /** insert HT */ if ($this->Orders_model->GRI_SN === null) { @@ -338,7 +338,7 @@ class TulanduoApi extends CI_Controller $getInfo_byGroupCode = null; if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { $real_groupCode = $this->analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); - $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $real_groupCode); + $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $detail_jsonResp->orderDetail->orderId); } $groupSN = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->GRI_SN : $order->COLI_GRI_SN; $coli_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_SN : $order->COLI_SN; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index b74d9cbc..e8a53939 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -511,11 +511,16 @@ class Orders_model extends CI_Model { return NULL; } - public function get_SN_by_groupCode($code, $NoName) + public function get_SN_by_groupCode($code, $vendorOrderId=NULL) { + $vendorOrderId_sql = $vendorOrderId===null ? "" : " case when GCI_VendorOrderId=$vendorOrderId then 0 else 1 end asc, "; $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name from GRoupInfo - where GRI_Name like '%$code%' "; + left join GroupCombineInfo on GCI_GRI_SN=GRI_SN + where GRI_Name like '%$code%' + order by + $vendorOrderId_sql + GCI_GRI_SN desc,GCI_SN asc"; $gri_query = $this->HT->query($gri_sql); if ($gri_query->num_rows() > 0) { $this->GRI_SN = $gri_query->row()->GRI_SN; @@ -525,8 +530,8 @@ class Orders_model extends CI_Model { FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - where COLI_GroupCode like '%$code%' "; - // where COLI_GRI_SN=" . $this->GRI_SN; + where COLI_GRI_SN=" . $this->GRI_SN; + // where COLI_GroupCode like '%$code%' "; $coli_query = $this->HT->query($coli_sql); if ($coli_query->num_rows() > 0) { $this->BIZ_COLI_SN = $coli_query->row()->COLI_SN; @@ -1827,6 +1832,7 @@ class Orders_model extends CI_Model { { // return NULL; $sql = " + "; $query = $this->HT->query($sql); } From 958be04ca46e6a1cf13d07899bda5b32bf9ae38f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 Aug 2018 10:39:24 +0800 Subject: [PATCH 138/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=20?= =?UTF-8?q?=E6=B5=B7=E7=BA=B3=E5=9B=A2=E4=B8=8D=E8=83=BD=E7=9B=B4=E6=8E=A5?= =?UTF-8?q?=E5=85=B3=E8=81=94=E5=8E=9F=E5=A7=8B=E5=9B=A2=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 4 +- .../trippestOrderSync/models/orders_model.php | 40 +++++++------------ 2 files changed, 16 insertions(+), 28 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4ac131df..77b6c37d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -171,12 +171,11 @@ class TulanduoApi extends CI_Controller $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 - if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest", "桂林海纳国旅"))) { + if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); } - /** insert HT */ if ($this->Orders_model->GRI_SN === null) { /** GRoupInfo */ $travelDate = new DateTime($vo['travelDate']); @@ -194,6 +193,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GRI_Creator = 435; $this->Orders_model->groupinfo_save(); } + /** insert HT */ if ($this->Orders_model->BIZ_COLI_SN === null) { /** BIZ_Guest */ $this->Orders_model->GUT_LastName = $vo['customerName']; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e8a53939..f7d8d55c 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -513,31 +513,20 @@ class Orders_model extends CI_Model { public function get_SN_by_groupCode($code, $vendorOrderId=NULL) { - $vendorOrderId_sql = $vendorOrderId===null ? "" : " case when GCI_VendorOrderId=$vendorOrderId then 0 else 1 end asc, "; - $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name - from GRoupInfo - left join GroupCombineInfo on GCI_GRI_SN=GRI_SN - where GRI_Name like '%$code%' - order by - $vendorOrderId_sql - GCI_GRI_SN desc,GCI_SN asc"; - $gri_query = $this->HT->query($gri_sql); - if ($gri_query->num_rows() > 0) { - $this->GRI_SN = $gri_query->row()->GRI_SN; - $this->GRI_No = $gri_query->row()->GRI_No; - $this->GRI_operator = $gri_query->row()->GRI_operator; - $coli_sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo, coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency - FROM BIZ_ConfirmLineInfo coli - inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN - LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN - where COLI_GRI_SN=" . $this->GRI_SN; - // where COLI_GroupCode like '%$code%' "; - $coli_query = $this->HT->query($coli_sql); - if ($coli_query->num_rows() > 0) { - $this->BIZ_COLI_SN = $coli_query->row()->COLI_SN; - $this->COLD_PlanVEI_SN = $coli_query->row()->COLD_PlanVEI_SN; - } - return json_decode(json_encode(array_merge(json_decode(json_encode($gri_query->row()), true), json_decode(json_encode($coli_query->row()), true)))); + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + ,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name + FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 + WHERE gri.GRI_No LIKE '%$code%' "; // and gri.GRI_Name like '%$NoName%' + $query = $this->HT->query($sql); + if ($query->num_rows() > 0) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->GRI_SN; + $this->GRI_No = $query->row()->GRI_No; + $this->GRI_operator = $query->row()->GRI_operator; + $this->COLD_PlanVEI_SN = $query->row()->COLD_PlanVEI_SN; + return $query->row(); } return NULL; } @@ -1832,7 +1821,6 @@ class Orders_model extends CI_Model { { // return NULL; $sql = " - "; $query = $this->HT->query($sql); } From e9ba5ca5c53c89ff3d8fc3e7ebe32a8479878328 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 Aug 2018 14:20:24 +0800 Subject: [PATCH 139/382] =?UTF-8?q?trippespt=E5=90=8C=E6=AD=A5:=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=9B=A2=E5=8F=B7=E8=A7=A3=E6=9E=90;=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E8=AE=A2=E5=8D=95=E6=8B=86=E5=88=86=E4=B9=9F=E9=9C=80?= =?UTF-8?q?=E8=A6=81=E5=90=88=E5=B9=B6=E5=BD=95=E5=85=A5:=E6=9C=AA?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 28 +++---------------- .../helpers/array_helper.php | 13 +++++++-- 2 files changed, 15 insertions(+), 26 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 77b6c37d..72c24bd4 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -172,7 +172,7 @@ class TulanduoApi extends CI_Controller // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { - $real_groupCode = $this->analysis_groupCode($vo['agcOrderNo']); + $real_groupCode = analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); } @@ -337,7 +337,7 @@ class TulanduoApi extends CI_Controller $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : $order->COLD_PlanVEI_SN; $getInfo_byGroupCode = null; if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { - $real_groupCode = $this->analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $detail_jsonResp->orderDetail->orderId); } $groupSN = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->GRI_SN : $order->COLI_GRI_SN; @@ -761,11 +761,11 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { - $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); + $real_groupCode = analysis_groupCode($input['agcOrderNo']); $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); } } elseif ($input['agcName'] == '桂林海纳国旅') { - $real_groupCode = $this->analysis_groupCode($input['agcOrderNo']); + $real_groupCode = analysis_groupCode($input['agcOrderNo']); $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID); } @@ -821,26 +821,6 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); $this->load->view('operation',$data); } - /*! - * 目的地项目组的订单计划的团号分析 - * 去除添加的后缀, 只保留前两部分: XXXXXX-YYYYYYYYYYYY - * @date 2018-05-02 - * @param [type] $groupCode 从地接系统获取到的团号 - */ - public function analysis_groupCode($groupCode) - { - mb_regex_encoding("UTF-8"); - preg_match('/[\w\s\-]+/', $this->characet($groupCode, "UTF-8"), $temp_array); - $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; - $tmp_groupCode = explode("-", trim($temp_array[0])); - $real_groupCode = $tmp_groupCode[0] . "-"; - if (isset($tmp_groupCode[1])) { - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; - } - $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); - return $real_groupCode; - } - protected function excute_curl($url, $content_builder) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 2e9bf4f0..b1cf03e2 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -120,8 +120,17 @@ function analysis_groupCode($groupCode) preg_match('/[\w\s\-]+/', characet($groupCode, "UTF-8"), $temp_array); $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; $tmp_groupCode = explode("-", trim($temp_array[0])); - $real_groupCode = $tmp_groupCode[0] . "-"; - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $real_groupCode = $tmp_groupCode[0]; + if (isset($tmp_groupCode[1])) { + $real_groupCode .= "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + } + for ($i=2; $i < count($tmp_groupCode); $i++) { + if (strlen($tmp_groupCode[$i]) > 4) { + $real_groupCode .= "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[$i], "(", true)!==false ? mb_strstr($tmp_groupCode[$i], "(", true) : $tmp_groupCode[$i]; + } + } $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); return $real_groupCode; } From 5df369937fef515529771972379e0d5a92d42986 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 Aug 2018 15:16:31 +0800 Subject: [PATCH 140/382] =?UTF-8?q?trippest=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20?= =?UTF-8?q?=E5=9B=BE=E5=85=B0=E6=9C=B5=E6=9C=AA=E8=BF=94=E5=9B=9E=E8=B0=83?= =?UTF-8?q?=E5=BA=A6=E6=95=B0=E6=8D=AE=E6=97=B6=E6=8C=89=E7=85=A7=E6=97=A7?= =?UTF-8?q?=E6=96=B9=E6=B3=95=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/order_finance.php | 10 +++++++--- .../trippestOrderSync/models/orderFinance_model.php | 6 +++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 51082153..9865de38 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -65,7 +65,6 @@ class Order_finance extends CI_Controller { /** 单团财务表 */ $report_order = array(); $report_order['OrderYJLR'] = 0; //预计利润 - $report_order['basemoney'] = 0; // 总成本 $report_order['money'] = 0; // 总收入, 实收金额 $report_order['profitmoney'] = 0; // 利润 $report_order['adultnumber'] = 0; @@ -83,7 +82,7 @@ class Order_finance extends CI_Controller { $report_order['reservedate'] = $order_info->reservedate; $report_order['guesttype'] = ($order_info->guesttype===null) ? 1 : $order_info->guesttype; $report_order['RO_GRI_SN'] = $report_order['RO_CGI_SN'] = $order_info->GRI_SN; - // $report_order['basemoney'] = $order_info->basemoney; // 总成本 + $report_order['basemoney'] = $order_info->otherCost; // 总成本=SUM(COLD_TotalCOst)+COLI_OtherCost // $report_order['OrderPrice'] = $order_info->OrderPrice; // 总报价 /** 订单支付信息 */ $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn); @@ -118,9 +117,11 @@ class Order_finance extends CI_Controller { } } /** 保存图兰朵包价线路产品的成本到report_tour */ + $processed_cold_sn = array(); // pvt $report_tour_pvt = array(); if ( ! empty($ret->pvt)) { + $processed_cold_sn = array_merge($processed_cold_sn,$ret->pvt->cold_sn); $report_tour_pvt['ordernumber'] = $ret->pvt->coli_id; $report_tour_pvt['tourCode'] = mb_substr($ret->pvt->PAG_Code, 0, 50); $report_tour_pvt['tourname'] = mb_substr($ret->pvt->pag_name, 0, 200); @@ -167,6 +168,7 @@ class Order_finance extends CI_Controller { if ($coc->PAG_code === $coc->real_code) { $cost_c_price = bcadd($cost_c_price, $coc->totalPrice); } + $processed_cold_sn[] = $coc->COLD_SN; } $cost_c['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($cost_c_price); $cost_c['tourProfit'] = ($cost_c['tourPrice']>0) ? bcsub($cost_c['tourPrice'], $cost_c['tourcost']) : 0; @@ -188,6 +190,7 @@ class Order_finance extends CI_Controller { $report_order['basemoney'] = bcadd($report_order['basemoney'], $cost_c['tourcost']); } } + $ret->processed_cold_sn = array_unique($processed_cold_sn); /** 开始写入数据库 */ /** 图兰朵供应商 */ if ( ! empty($ret->report_tour)) { @@ -195,7 +198,7 @@ class Order_finance extends CI_Controller { } /** 非图兰朵供应商的包价线路产品 */ $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); - if ( ! empty($other_tour)) { + if ( ! empty($other_tour) || empty($ret->processed_cold_sn)) { $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); foreach ($ret->others as $kro => $vro) { $report_order['basemoney'] = bcadd($report_order['basemoney'], $vro->tourcost); @@ -366,6 +369,7 @@ class Order_finance extends CI_Controller { } $ret->coli_sn = $coli_sn; $ret->coli_id = $all_orders[0]->coli_ID; + $ret->cold_sn = array_unique(array_map(function($ele) {return $ele->COLD_SN;}, $all_orders)); // 总报价 $ret->totalPrice = 0; foreach ($all_orders as $kal => $val) { diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 365a2d95..d67c8a6f 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -16,6 +16,7 @@ class OrderFinance_model extends CI_Model { coli.COLI_WebCode as Agenter, coli.COLI_ApplyDate as reservedate ,coli.COLI_Cost as basemoney + ,ISNULL(coli.COLI_OtherCost,0) as otherCost ,dbo.ConvertToRMB('USD',ISNULL(coli.COLI_Price,0)) OrderPrice ,gri.GRI_SN ,gri.GRI_No as TuanName ,opi.OPI_Name as ChinaName,opi.OPI_SN as operater,opi.OPI_DEI_SN @@ -76,7 +77,7 @@ class OrderFinance_model extends CI_Model { from GroupCombineInfo gci inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN - and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 + and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 and COLD_PlanVEI_SN in (1343,29188,30548,30016) left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2 where gci.GCI_combineNo =? @@ -395,8 +396,7 @@ class OrderFinance_model extends CI_Model { INNER JOIN dbo.BIZ_PackageInfo ON dbo.BIZ_ConfirmLineDetail.COLD_ServiceSN = dbo.BIZ_PackageInfo.PAG_SN WHERE (dbo.BIZ_ConfirmLineDetail.COLD_ServiceType='D') AND (dbo.BIZ_ConfirmLineDetail.DeleteFlag = 0) - AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) - and dbo.BIZ_ConfirmLineDetail.COLD_PlanVEI_SN not in (1343,29188,30548,30016) "; + AND (dbo.BIZ_ConfirmLineDetail.COLD_COLI_SN=$coli_sn) "; return $this->HT->query($sql)->result(); } From e9e3906a4859d0555ce4d1a8e2bbb87fe7670823 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 Aug 2018 17:42:25 +0800 Subject: [PATCH 141/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E6=8C=89=E5=9B=A2=E5=8F=B7=E6=9F=A5=E8=AF=A2=E5=B7=B2?= =?UTF-8?q?=E5=BD=95=E5=85=A5=E7=9A=84=E8=AE=A2=E5=8D=95=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/models/orders_model.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index f7d8d55c..35e701c9 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -516,9 +516,10 @@ class Orders_model extends CI_Model { $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency ,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name FROM BIZ_ConfirmLineInfo coli - inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN and COLI_State not in (30,40,50) LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 - WHERE gri.GRI_No LIKE '%$code%' "; // and gri.GRI_Name like '%$NoName%' + WHERE gri.GRI_No LIKE '%$code%' + order by COLI_SN desc"; // and gri.GRI_Name like '%$NoName%' $query = $this->HT->query($sql); if ($query->num_rows() > 0) { $this->BIZ_COLI_SN = $query->row()->COLI_SN; From ae402a3db72e5f0e6d608c6e837613a10572c5da Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 Aug 2018 14:25:37 +0800 Subject: [PATCH 142/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=20?= =?UTF-8?q?=E6=9C=AA=E8=AF=86=E5=88=AB=E7=9A=84=E7=BA=BF=E8=B7=AF=E5=90=8D?= =?UTF-8?q?=E7=A7=B0=E4=BB=A3=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 72c24bd4..288a36e1 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -149,12 +149,12 @@ class TulanduoApi extends CI_Controller $PAG_Code = $pag_sub = null; preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { - // 旧的数据没有线路代号 - log_message('error','未识别的线路名称 ' . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); $PAG_Code = $pag_no_tmp[$vo['routeName']]; $split_code = explode("-", $PAG_Code); $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + // 旧的数据没有线路代号 + log_message('error',"未识别的线路名称 $PAG_Code" . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); } else { $PAG_Code = $pag_sub = null; $split_code = explode("-", $temp_array[0]); @@ -401,8 +401,6 @@ class TulanduoApi extends CI_Controller ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ // nothing to update - // query latest order detail - $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { @@ -431,6 +429,8 @@ class TulanduoApi extends CI_Controller $paytype = 15006; // 地接代收 $pay_currency = 'RMB'; $auto_text = "dataAutoEnter "; + // query latest order detail + $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); // 删除旧的录入 $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); if (isset($detail_jsonResp->orderDetail->travelFees) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { From 5cdb4fb787acdc4f983e15e2724867cf843fedc8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 Aug 2018 09:44:03 +0800 Subject: [PATCH 143/382] =?UTF-8?q?trippest=E5=90=8C=E6=AD=A5:=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E6=9B=B4=E6=96=B0=E7=9A=84=E6=9F=A5=E8=AF=A2=E6=97=B6?= =?UTF-8?q?=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 6 +++--- webht/third_party/trippestOrderSync/models/orders_model.php | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 288a36e1..0aaaaf0d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -154,7 +154,7 @@ class TulanduoApi extends CI_Controller $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; // 旧的数据没有线路代号 - log_message('error',"未识别的线路名称 $PAG_Code" . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); + log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); } else { $PAG_Code = $pag_sub = null; $split_code = explode("-", $temp_array[0]); @@ -277,8 +277,8 @@ class TulanduoApi extends CI_Controller } else { // $startDate = ('2018-04-21'); // $endDate = ('2018-04-22'); // test - $startDate = date('Y-m-d', strtotime("-3 days")); - $endDate = date('Y-m-d', strtotime("+7 days")); + $startDate = date('Y-m-d', strtotime("-4 days")); + $endDate = date('Y-m-d', strtotime("+2 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate); } $unique_orderGroupCombine = array(); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 35e701c9..308fa230 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -130,7 +130,7 @@ class Orders_model extends CI_Model { */ public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 1000 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + $sql = "SELECT top 10 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, gci.* FROM GroupCombineInfo gci LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') @@ -143,8 +143,9 @@ class Orders_model extends CI_Model { $sql .= " and GCI_VendorOrderId='$get_vendorID' "; } if ($startDate !== NULL) { - $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; // test + $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; } + $sql .= " order by GCI_createTime asc "; // $sql .= "UNION SELECT top 50 // coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, // cold.COLD_PlanVEI_SN, gci.* From 59132a3900eda7f9859c7559fcf4c94793a6ec75 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 Aug 2018 11:44:45 +0800 Subject: [PATCH 144/382] =?UTF-8?q?trippest=20=E8=B4=A2=E5=8A=A1=E8=A1=A8:?= =?UTF-8?q?=E5=85=B6=E4=BB=96=E6=94=B6=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/models/orderFinance_model.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index d67c8a6f..53777243 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -101,6 +101,7 @@ class OrderFinance_model extends CI_Model { $ret->cost_category['water'] = 0; $ret->cost_category['guide_meal'] = 0; $ret->cost_category['otherCosts'] = 0; + $ret->cost_category['otherReceives'] = 0; $ret->cost_category['guiderOperations'] = 0; $ret->cost_category['touristCarOperations'] = 0; $ret->cost_category['sceneryOperations'] = 0; From 50d137146db492ed5a23884ad7737849149c05a1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 Aug 2018 16:56:21 +0800 Subject: [PATCH 145/382] =?UTF-8?q?trippest=E5=90=8C=E6=AD=A5:=20=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E4=BB=A3=E6=94=B6=E6=95=B0=E6=8D=AE;=20=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E6=9F=A5=E8=AF=A2:=20fixed=20bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 15 +++++++++++++++ .../trippestOrderSync/controllers/api.php | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 0aaaaf0d..cdfd7f51 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -471,6 +471,21 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupaccountinfo_save(); } } + if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $koor => $voor) { + $this->Orders_model->GAI_Operator = 435; + $this->Orders_model->GAI_COLI_SN = $coli_sn; + $this->Orders_model->GAI_GRI_SN = $groupSN; + $this->Orders_model->GAI_COLI_ID = $coli_id; + $this->Orders_model->GAI_Type = $paytype; + $this->Orders_model->GAI_SQJE = $voor->sumMoney; + $this->Orders_model->GAI_SQJECurrency = $pay_currency; + $this->Orders_model->GAI_SSJE = $voor->sumMoney; + $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); + $this->Orders_model->GAI_Memo = $auto_text . "代收" . $voor->type . ", " . $voor->remark; + $this->Orders_model->biz_groupaccountinfo_save(); + } + } // 代付 if (isset($detail_jsonResp->orderDetail->replacePays) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 0f333e54..8962541f 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -80,7 +80,7 @@ class Api extends CI_Controller { $vro['dateMonth_text'] = date('M', $out_datetime); $vro['dateYear_text'] = date('Y', $out_datetime); foreach ($order_project as $kd => $poi_info) { - if (strcmp($vro['start_date'], substr($poi->COLD_StartDate, 0, 10) ) === 0) { + if (strcmp($vro['start_date'], substr($poi_info->COLD_StartDate, 0, 10) ) === 0) { $poi = $poi_info; } else { $poi = $order_project[0]; From 03d090061ccd73dca9618bfe2d64fc0f127d23ca Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 20 Aug 2018 17:22:09 +0800 Subject: [PATCH 146/382] =?UTF-8?q?trippest=20push:=E7=BA=BF=E8=B7=AF?= =?UTF-8?q?=E5=90=8D=E7=A7=B0=E5=90=8E=E9=9D=A2=E5=A2=9E=E5=8A=A0=E7=BA=BF?= =?UTF-8?q?=E8=B7=AF=E7=BC=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index cdfd7f51..ad975290 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -700,6 +700,7 @@ class TulanduoApi extends CI_Controller if ($scheduleDetails[0]->PAGS_CN_Title) { $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]"; } + $routeName .= " " . $scheduleDetails[0]->PAG_Code; if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); } From 70ae2400e252a36c19748fd041e7918022e62772 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 21 Aug 2018 11:11:22 +0800 Subject: [PATCH 147/382] =?UTF-8?q?trippest=20=E6=9F=A5=E8=AF=A2:=E5=AE=89?= =?UTF-8?q?=E6=8E=92=E4=B8=8E=E8=A1=8C=E7=A8=8B=E6=8C=89=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E5=AF=B9=E5=BA=94?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 71 ++++++++++--------- 1 file changed, 36 insertions(+), 35 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 8962541f..8a27d447 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -25,8 +25,9 @@ class Api extends CI_Controller { header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); header('Access-Control-Allow-Credentials:true'); ($find===null) ? $find = $this->input->get_post('q') : null; + $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); $order_project = $this->Orders_model->get_package_order($find); - if ($order_project == null) { + if ($find===null || $order_project == null) { $ret['status'] = 0; $ret['msg'] = "Not Found."; return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); @@ -79,45 +80,45 @@ class Api extends CI_Controller { $vro['dateDay_text'] = date('d', $out_datetime); $vro['dateMonth_text'] = date('M', $out_datetime); $vro['dateYear_text'] = date('Y', $out_datetime); + $poi = $order_project[0]; foreach ($order_project as $kd => $poi_info) { if (strcmp($vro['start_date'], substr($poi_info->COLD_StartDate, 0, 10) ) === 0) { $poi = $poi_info; - } else { - $poi = $order_project[0]; - } - $vro['tour_name'] = $poi->PAG2_Name; - // 领队名字 - $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); - // 行程人数 - $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; - $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; - if ($poi->COLD_ChildNum > 0) { - $vro['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; - } - $vro['personNum_text'] .= ")" ; - // 人数 - $vro['adult_number'] = $order_project[0]->COLD_PersonNum; - $vro['kid_number'] = $order_project[0]->COLD_ChildNum; - // 酒店 - $vro['hotel_name'] = $poi->POI_Hotel; - $vro['hotel_address'] = $poi->POI_HotelAddress; - $vro['hotel_tel'] = $poi->POI_HotelPhone; - // 航班/车次 - $vro['flights_no'] = $poi->POI_FlightsNo; - $vro['flights_airport'] = $poi->POI_AirPort; - // 接送信息 - $vro['pick_up'] = ""; - $vro['drop_off'] = ""; - $decode_MemoText = $memo_text_tmp = ""; - if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { - $decode_MemoText = json_decode($poi->COLD_MemoText, true); - $vro['pick_up'] = $decode_MemoText['Pick up']; - $vro['drop_off'] = $decode_MemoText['Drop off']; - } else { - $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); - $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); + break; } } + $vro['tour_name'] = $poi->PAG2_Name; + // 领队名字 + $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // 行程人数 + $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; + $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; + if ($poi->COLD_ChildNum > 0) { + $vro['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; + } + $vro['personNum_text'] .= ")" ; + // 人数 + $vro['adult_number'] = $order_project[0]->COLD_PersonNum; + $vro['kid_number'] = $order_project[0]->COLD_ChildNum; + // 酒店 + $vro['hotel_name'] = $poi->POI_Hotel; + $vro['hotel_address'] = $poi->POI_HotelAddress; + $vro['hotel_tel'] = $poi->POI_HotelPhone; + // 航班/车次 + $vro['flights_no'] = $poi->POI_FlightsNo; + $vro['flights_airport'] = $poi->POI_AirPort; + // 接送信息 + $vro['pick_up'] = ""; + $vro['drop_off'] = ""; + $decode_MemoText = $memo_text_tmp = ""; + if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { + $decode_MemoText = json_decode($poi->COLD_MemoText, true); + $vro['pick_up'] = $decode_MemoText['Pick up']; + $vro['drop_off'] = $decode_MemoText['Drop off']; + } else { + $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); + $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); + } } unset($vro); } From 8ec7808391727fa2d271138f923583654c3110a2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 21 Aug 2018 17:54:34 +0800 Subject: [PATCH 148/382] =?UTF-8?q?trippest=20=E5=90=8C=E6=AD=A5:=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E5=8E=86=E5=8F=B2=E6=95=B0=E6=8D=AE,=E6=9C=AA?= =?UTF-8?q?=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 71 +++++++++++++++++-- .../trippestOrderSync/models/orders_model.php | 12 ++++ 2 files changed, 77 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index ad975290..b2370792 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -56,9 +56,7 @@ class TulanduoApi extends CI_Controller $this->load->helper('array'); $this->load->model('Orders_model'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); - // $this->output->enable_profiler(TRUE); - /** test */ // $this->userId = "358"; // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -153,13 +151,13 @@ class TulanduoApi extends CI_Controller $split_code = explode("-", $PAG_Code); $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - // 旧的数据没有线路代号 - log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); - } else { + } else if ( ! empty($temp_array)) { $PAG_Code = $pag_sub = null; $split_code = explode("-", $temp_array[0]); $PAG_Code = $split_code[0] . "-" . $split_code[1]; isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else { + log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); } $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); @@ -400,7 +398,7 @@ class TulanduoApi extends CI_Controller ,"COLI_CUrrency" => $travel_fee_currency ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); - /** BIZ_ConfirmLineDetail */ // nothing to update + /** BIZ_ConfirmLineDetail */ /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { @@ -648,6 +646,63 @@ class TulanduoApi extends CI_Controller return; } + /*! + * 往前获取历史数据 + * @date 2018-08-21 + */ + public function get_history_order_list($oldest_date=null) + { + // $oldest_date===null ? $oldest_date = $this->Orders_model->get_oldest_offset() : null; + $oldest_date===null ? $oldest_date = '2018-05-10' : null; // test + $startTravelDate = date('Y-m-d', strtotime("-1 day", strtotime($oldest_date))); + $endTravelDate = $oldest_date; + $start_date = $this->input->get_post("start"); + $end_date = $this->input->get_post("end"); + $startTravelDate = $start_date ? $start_date : $startTravelDate; + $endTravelDate = $end_date ? $end_date : $endTravelDate; + $this->tld_order->setUserId($this->userId) + ->setKey($this->key) + ->setPageSize(20) + ->setPageIndex(1) + ->setStartTravelDate($startTravelDate) + ->setEndTravelDate($endTravelDate) ; + var_export($startTravelDate); + var_export($endTravelDate); + $resp = $this->excute_curl($this->list_url, $this->tld_order); + $resp_arr = json_decode($resp, true); + if (intval($resp_arr['status']) !== 1) { + log_message('error','TulanduoApi get_orderlist history failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + // return; + } + if ($resp_arr["responseData"]["totalRows"] == 0) { + log_message('error','TulanduoApi get_orderlist history 0. '); + // 继续往前滚日期 + $this->get_history_order_list($startTravelDate); + } + $all_list = $resp_arr["responseData"]["orders"]; + for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) { + $this->tld_order->setPageIndex($pi); + $f_resp = $this->excute_curl($this->list_url, $this->tld_order); + $f_resp_arr = json_decode($f_resp, true); + if ($resp_arr['status'] !== 1) { + log_message('error','TulanduoApi get_orderlist history failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + continue; + } + $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); + } + $all_vendor_order_id = array_column($all_list, 'orderId'); + $all_vendor_order_id_str = implode(',', $all_vendor_order_id); + $exists_ht = $this->Orders_model->get_exists_vendorOrderId($all_vendor_order_id_str); + $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); + $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); + var_export($to_insert); + if (empty($to_insert) || count($to_insert)==1) { + // 继续往前滚日期 + $this->get_history_order_list($startTravelDate); + } + exit(); + } + /*! * 取消团 * @date 2018-05-02 @@ -893,7 +948,9 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); "故宫深度一日游(目的地)" => "BJSIC-44" ,"故宫深度游拼团(目的地)" => "BJSIC-44" ,"北京精品一日游(目的地)" => "BJSIC-41" + ,"北京精品一日游(PVT)(目的地)" => "BJSIC-41" ,"北京精品两日游(目的地)" => "BJSIC-42" + ,"北京精品两日游(PVT)(目的地)" => "BJSIC-42" ,"北京精品三日游(目的地)" => "BJSIC-43" ,"北京精品游D2(目的地)" => "BJSIC-42" ,"北京精品游D3(目的地)" => "BJSIC-43" @@ -903,6 +960,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"箭扣-慕田峪徒步一日游(目的地)" => "BJSIC-45" ,"箭扣-慕田峪长城徒步拼团(目的地)" => "BJSIC-45" ,"司马台西-金山岭徒步一日游(目的地)" => "BJSIC-46" + ,"司马台西-金山岭徒步一日游(PVT)(目的地)" => "BJSIC-46" ,"司马台西-金山岭长城徒步拼团(目的地)" => "BJSIC-46" ,"慕田峪半日游拼团(目的地)" => "BJSIC-47" ,"古北口长城徒步一日游(目的地)" => "BJSIC-48" @@ -919,6 +977,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"上海精品一日游(目的地)" => "SHSIC-41" ,"上海市内精品一日游(目的地)" => "SHSIC-42" ,"周庄锦溪精品一日游(目的地)" => "SHSIC-43" + ,"苏州精品一日游(目的地)" => "SHSIC-44" ,"上海单租车(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" ); } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 308fa230..71515311 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -122,6 +122,18 @@ class Orders_model extends CI_Model { } return NULL; } + public function get_exists_vendorOrderId($vendorOrderIds="") + { + $sql = "SELECT GCI_VendorOrderId FROM GroupCombineInfo + WHERE GCI_VendorOrderId IN ($vendorOrderIds) "; + return $this->HT->query($sql)->result(); + } + public function get_oldest_offset() + { + $sql = "SELECT top 1 CAST(GCI_travelDate as DATE) old_date from GroupCombineInfo + order by GCI_travelDate asc"; + return $this->HT->query($sql)->row()->old_date; + } /*! * 需要更新调度信息的订单 -- 商务表 * @param integer $coli_sn [description] From 96899b40af8beeb2c4fe2706caf16ef82eee5413 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 22 Aug 2018 09:37:47 +0800 Subject: [PATCH 149/382] =?UTF-8?q?trippest=20=E6=9F=A5=E8=AF=A2:=20?= =?UTF-8?q?=E6=B7=B7=E6=8B=BC=E6=97=B6,=E7=9F=AD=E8=A1=8C=E7=A8=8B?= =?UTF-8?q?=E7=9A=84=E6=9F=A5=E8=AF=A2=E4=BB=85=E6=98=BE=E7=A4=BA=E5=85=B6?= =?UTF-8?q?=E5=BD=A2=E6=88=90=E6=97=A5=E6=9C=9F=E5=86=85=E7=9A=84=E8=B0=83?= =?UTF-8?q?=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 8a27d447..e196c767 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -87,6 +87,8 @@ class Api extends CI_Controller { break; } } + $vro['cold_date'] = $poi->COLD_StartDate; + $vro['cold_enddate'] = $poi->COLD_EndDate; $vro['tour_name'] = $poi->PAG2_Name; // 领队名字 $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); @@ -123,6 +125,17 @@ class Api extends CI_Controller { unset($vro); } $ret['operation'] = array_values($ret['operation']); + $ret_operation = array(); + foreach ($ret['operation'] as $ko => $vo) { + if (strtotime($vo['start_date']) >= strtotime($vo['cold_date']) + && strtotime($vo['start_date']) <= strtotime($vo['cold_enddate'])) { + unset($vo['cold_date']); + unset($vo['cold_enddate']); + $ret_operation[] = $vo; + continue; + } + } + $ret['operation'] = $ret_operation; /** 外联信息 */ $raw_opi_id = 0; if (intval($order_project[0]->COLI_OPI_ID) === 435) { From 8774adaf1fd55bcc5929481306608b262633cf78 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 22 Aug 2018 11:53:42 +0800 Subject: [PATCH 150/382] =?UTF-8?q?trippest=20=E6=9F=A5=E8=AF=A2:=E6=8E=A5?= =?UTF-8?q?=E9=80=81=E4=BF=A1=E6=81=AF=E8=A1=A5=E5=85=85,=20=E4=BB=8EHT?= =?UTF-8?q?=E5=AD=90=E8=AE=A2=E5=8D=95=E8=AF=BB=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 41 +++++++++++++++---- .../trippestOrderSync/models/orders_model.php | 21 ++++++---- 2 files changed, 45 insertions(+), 17 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index e196c767..668bdda4 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -74,19 +74,32 @@ class Api extends CI_Controller { } } // 加上行程 + $num_index = 0; foreach ($ret['operation'] as $kro => &$vro) { $out_datetime = strtotime($vro['start_date']); $vro['dateWeek_text'] = date('D', $out_datetime); $vro['dateDay_text'] = date('d', $out_datetime); $vro['dateMonth_text'] = date('M', $out_datetime); $vro['dateYear_text'] = date('Y', $out_datetime); - $poi = $order_project[0]; + $poi = new stdclass(); foreach ($order_project as $kd => $poi_info) { if (strcmp($vro['start_date'], substr($poi_info->COLD_StartDate, 0, 10) ) === 0) { - $poi = $poi_info; - break; + if (count((array)$poi)===0) { + $poi = $poi_info; + } else if ($poi->POI_Hotel == "") { + $poi->POI_Hotel = $poi_info->POI_Hotel; + $poi->POI_HotelAddress = $poi_info->POI_HotelAddress; + $poi->POI_HotelPhone = $poi_info->POI_HotelPhone; + // } else if ($poi->POI_FlightsNo == "") { + } else if ($poi_info->POI_FlightsNo != "" && $poi_info->COLD_SN != $poi->COLD_SN) { + $poi->POI_FlightsNo .= "; " . $poi_info->POI_FlightsNo; + // $poi->POI_AirPort .= "; " . $poi_info->POI_AirPort; + } } } + if (count((array)$poi)===0) { + $poi = $order_project[0]; + } $vro['cold_date'] = $poi->COLD_StartDate; $vro['cold_enddate'] = $poi->COLD_EndDate; $vro['tour_name'] = $poi->PAG2_Name; @@ -113,14 +126,26 @@ class Api extends CI_Controller { $vro['pick_up'] = ""; $vro['drop_off'] = ""; $decode_MemoText = $memo_text_tmp = ""; - if ($poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { - $decode_MemoText = json_decode($poi->COLD_MemoText, true); - $vro['pick_up'] = $decode_MemoText['Pick up']; - $vro['drop_off'] = $decode_MemoText['Drop off']; - } else { + if ($num_index == 0) { $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); } + // if ($vro['pick_up'] === "") { + if (strval($poi->PAGS_Direction) === '0') { + $vro['pick_up'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + $vro['drop_off'] .= $poi->POI_Hotel; + } else if (strval($poi->PAGS_Direction) === '1') { + $vro['pick_up'] .= $poi->POI_Hotel; + $vro['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + } else { // if ($poi->POI_FlightsNo != "") + $vro['pick_up'] .= $poi->POI_Hotel; + // $vro['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; // 结束后送机 + } + // } + // if ($vro['pick_up'] === "" && $poi->POI_FlightsNo == '') { + // $vro['pick_up'] = $vro['drop_off'] = $poi->POI_Hotel; + // } + $num_index++; } unset($vro); } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 71515311..579f3fb8 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1303,6 +1303,7 @@ class Orders_model extends CI_Model { GCI_SN,GCI_VendorOrderId,GCI_combineNo ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText + ,pags.PAGS_Direction,pags.PAGS_describ ,pag2.PAG2_Name ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone ,poi.POI_AirPort,poi.POI_FlightsNo @@ -1313,19 +1314,21 @@ class Orders_model extends CI_Model { inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN inner join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 + left join BIZ_PackageInfoSub pags on pags.PAGS_SN=cold.COLD_ServiceSN2 where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' - OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%'"; + OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + order by COLD_StartDate asc"; // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' $order_info_query = $this->HT->query($order_info_sql); $ret = $order_info_query->result(); - if ($order_info_query->num_rows() > 0) { - // $operation_sql = "SELECT gcod.* - // from GroupCombineOperationDetail gcod - // where GCOD_GCI_combineNo=? - // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; - // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); - // $ret['operation_info'] = $operation_info->result(); - } + // if ($order_info_query->num_rows() > 0) { + // $operation_sql = "SELECT gcod.* + // from GroupCombineOperationDetail gcod + // where GCOD_GCI_combineNo=? + // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); + // $ret['operation_info'] = $operation_info->result(); + // } return $ret; } From acb8fcafa9d33ad2e6a3d221d2fee04ac26279e1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 22 Aug 2018 13:55:54 +0800 Subject: [PATCH 151/382] =?UTF-8?q?trippest=20=E6=9F=A5=E8=AF=A2model?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 2 +- .../trippestOrderSync/models/orders_model.php | 69 --------------- .../trippestOrderSync/models/orders_query.php | 83 +++++++++++++++++++ 3 files changed, 84 insertions(+), 70 deletions(-) create mode 100644 webht/third_party/trippestOrderSync/models/orders_query.php diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 668bdda4..fa89eb5d 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -7,7 +7,7 @@ class Api extends CI_Controller { parent::__construct(); mb_regex_encoding("UTF-8"); $this->load->helper('array'); - $this->load->model('Orders_model'); + $this->load->model('Orders_query', 'Orders_model'); } public function index() diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 579f3fb8..43ecc465 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -545,19 +545,6 @@ class Orders_model extends CI_Model { return NULL; } - /** 获取海纳团的发团人 */ - public function get_gri_opi_id($code) - { - $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,isnull(GRI_operator,0) GRI_operator,GRI_No,GRI_Name - from GRoupInfo - where GRI_Name like '%$code%' "; - $gri_query = $this->HT->query($gri_sql); - if ($gri_query->num_rows() > 0) { - return $gri_query->row()->GRI_operator; - } - return 0; - } - /*! * 获取地接社接受计划的人员信息 * @param $vendorID 地接社ID @@ -1297,62 +1284,6 @@ class Orders_model extends CI_Model { return $query; } - function get_package_order($COLI_ID) - { - $order_info_sql = "SELECT - GCI_SN,GCI_VendorOrderId,GCI_combineNo - ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText - ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText - ,pags.PAGS_Direction,pags.PAGS_describ - ,pag2.PAG2_Name - ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone - ,poi.POI_AirPort,poi.POI_FlightsNo - ,GUT_FirstName,GUT_LastName - FROM BIZ_ConfirmLineInfo coli - inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN --and GCI_combineNo<>'cancel' - inner join BIZ_ConfirmLineDetail cold on COLD_COLI_SN=COLI_SN - inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN - inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN - inner join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 - left join BIZ_PackageInfoSub pags on pags.PAGS_SN=cold.COLD_ServiceSN2 - where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' - OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' - order by COLD_StartDate asc"; - // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' - $order_info_query = $this->HT->query($order_info_sql); - $ret = $order_info_query->result(); - // if ($order_info_query->num_rows() > 0) { - // $operation_sql = "SELECT gcod.* - // from GroupCombineOperationDetail gcod - // where GCOD_GCI_combineNo=? - // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; - // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); - // $ret['operation_info'] = $operation_info->result(); - // } - return $ret; - } - - function get_operator($OPI_SN=0) - { - $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name - from OperatorInfo opi - left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1 - where OPI_SN=" . $OPI_SN . " AND OPI_SN<>435"; - return $this->HT->query($operator_sql)->row(); - } - - function get_operation($combineNo) - { - $combineNos = my_implode("'",",",$combineNo); - $operation_sql = "SELECT gcod.* - from GroupCombineOperationDetail gcod - where GCOD_GCI_combineNo in ($combineNos) - and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations') - order by GCOD_startDate"; - $operation_info = $this->HT->query($operation_sql, array($combineNo)); - return $operation_info->result(); - } - function GetNationalityID($nationalityName) { if (!$nationalityName) { return 0; diff --git a/webht/third_party/trippestOrderSync/models/orders_query.php b/webht/third_party/trippestOrderSync/models/orders_query.php new file mode 100644 index 00000000..1da05a4e --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/orders_query.php @@ -0,0 +1,83 @@ +<?php + +/*! + * 查询 + */ + +class Orders_query extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + /** 获取海纳团的发团人 */ + public function get_gri_opi_id($code) + { + $gri_sql = "SELECT top 1 GRI_SN,GRI_OPI_ID,isnull(GRI_operator,0) GRI_operator,GRI_No,GRI_Name + from GRoupInfo + where GRI_Name like '%$code%' "; + $gri_query = $this->HT->query($gri_sql); + if ($gri_query->num_rows() > 0) { + return $gri_query->row()->GRI_operator; + } + return 0; + } + + function get_package_order($COLI_ID) + { + $order_info_sql = "SELECT + GCI_SN,GCI_VendorOrderId,GCI_combineNo + ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText + ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText + ,pags.PAGS_Direction,pags.PAGS_describ + ,pag2.PAG2_Name + ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone + ,poi.POI_AirPort,poi.POI_FlightsNo + ,GUT_FirstName,GUT_LastName + FROM BIZ_ConfirmLineInfo coli + inner join GroupCombineInfo on COLI_GRI_SN=GCI_GRI_SN --and GCI_combineNo<>'cancel' + inner join BIZ_ConfirmLineDetail cold on COLD_COLI_SN=COLI_SN + inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN + inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN + inner join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 + left join BIZ_PackageInfoSub pags on pags.PAGS_SN=cold.COLD_ServiceSN2 + where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + order by COLD_StartDate asc"; + // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + $order_info_query = $this->HT->query($order_info_sql); + $ret = $order_info_query->result(); + // if ($order_info_query->num_rows() > 0) { + // $operation_sql = "SELECT gcod.* + // from GroupCombineOperationDetail gcod + // where GCOD_GCI_combineNo=? + // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; + // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); + // $ret['operation_info'] = $operation_info->result(); + // } + return $ret; + } + + function get_operator($OPI_SN=0) + { + $operator_sql = "SELECT opi.OPI_SN,opi.OPI_Name,opi.OPI_FirstName,OPI_MoveTelephone,OPI_Email,opi2.OPI2_Name + from OperatorInfo opi + left join OperatorInfo2 opi2 on opi2.OPI2_OPI_SN=OPI_SN and opi2.OPI2_LGC=1 + where OPI_SN=" . $OPI_SN . " AND OPI_SN<>435"; + return $this->HT->query($operator_sql)->row(); + } + + function get_operation($combineNo) + { + $combineNos = my_implode("'",",",$combineNo); + $operation_sql = "SELECT gcod.* + from GroupCombineOperationDetail gcod + where GCOD_GCI_combineNo in ($combineNos) + and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations') + order by GCOD_startDate"; + $operation_info = $this->HT->query($operation_sql, array($combineNo)); + return $operation_info->result(); + } + +} From 02bc546e78d07ef5e22297676a61f1e9c43cb826 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 24 Aug 2018 15:39:10 +0800 Subject: [PATCH 152/382] =?UTF-8?q?=E9=87=8D=E6=96=B0=E5=86=99=E5=90=8C?= =?UTF-8?q?=E6=AD=A5,=E6=9C=AA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 197 ++++++++++++++++-- .../trippestOrderSync/controllers/api.php | 2 +- .../trippestOrderSync/models/order_update.php | 14 ++ .../trippestOrderSync/models/orders_model.php | 44 ++-- 4 files changed, 224 insertions(+), 33 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index b2370792..1320495c 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -169,7 +169,8 @@ class TulanduoApi extends CI_Controller $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 - if ($this->Orders_model->BIZ_COLI_SN === null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { + // if ($this->Orders_model->BIZ_COLI_SN===null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { + if ($this->Orders_model->BIZ_COLI_SN === null) { $real_groupCode = analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); @@ -263,9 +264,6 @@ class TulanduoApi extends CI_Controller */ public function insert_HT_order_operation($coli_sn=null,$get_vendorID=null) { - // if ($coli_sn == null) { - // return null; - // } log_message('error','get_order_operation From TuLanDuo '); $this->load->model('Order_update'); if ($coli_sn !== null && $coli_sn != 0) { @@ -303,6 +301,7 @@ class TulanduoApi extends CI_Controller } continue; } + $detail_jsonResp->orderDetail->agcOrderNo = mb_ereg_replace('( )', '', trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格 // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { $this->plan_cancel($order->GCI_VendorOrderId); @@ -330,17 +329,120 @@ class TulanduoApi extends CI_Controller } } /** HT 开始 */ - /** UPDATE */ $cnt++; $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : $order->COLD_PlanVEI_SN; $getInfo_byGroupCode = null; - if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { - $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); - $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $detail_jsonResp->orderDetail->orderId); + $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + if (intval($order->COLI_OPI_ID) === 435 ) { + $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + if ( empty($getInfo_byGroupCodeArr) ){ + $getInfo_byGroupCode = null; // 没有该团号的团信息 + } elseif (strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 + $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0]; // 渠道和目的地有重复操作的团 + } else { + foreach ($getInfo_byGroupCodeArr as $kg => $vg) { + if (mb_substr($vg->GRI_No, 0, 49) === $detail_jsonResp->orderDetail->agcOrderNo) { + // 地接拆分的团号,需要全部匹配; 否则为没有团信息 + $getInfo_byGroupCode = $vg; + break; + } + } + } + if ($getInfo_byGroupCode === null) { + $PAG_Code = $pag_sub = null; + preg_match('/[a-zA-Z]+\-[0-9\-]+/', characet($detail_jsonResp->orderDetail->routeName, "UTF-8"), $temp_array); + if (empty($temp_array) && isset($pag_no_tmp[$detail_jsonResp->orderDetail->routeName])) { + $PAG_Code = $pag_no_tmp[$detail_jsonResp->orderDetail->routeName]; + $split_code = explode("-", $PAG_Code); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else if ( ! empty($temp_array)) { + $PAG_Code = $pag_sub = null; + $split_code = explode("-", $temp_array[0]); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else { + log_message('error',"未识别的线路名称 $PAG_Code " . $detail_jsonResp->orderDetail->orderId . " " . $detail_jsonResp->orderDetail->routeName . var_export($temp_array, 1)); + } + $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; + $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); + $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic)); + /** INSERT GRoupInfo */ + $travelDate = new DateTime($detail_jsonResp->orderDetail->travelDate); + $leaveDate = new DateTime($detail_jsonResp->orderDetail->leaveDate); + $date_diff = $travelDate->diff($leaveDate); + $this->Orders_model->GRI_No = mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49); + $this->Orders_model->GRI_OrderType = 227002; // 商务 + $this->Orders_model->GRI_Name = mb_substr($detail_jsonResp->orderDetail->agcName . $detail_jsonResp->orderDetail->agcOrderNo, 0, 49); + $this->Orders_model->GRI_PersonNum = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; + $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); + $this->Orders_model->GRI_IsCancel = 0; + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->GRI_OPI_ID = 435; + $this->Orders_model->GRI_operator = 435; + $this->Orders_model->GRI_Creator = 435; + $groupSN = $this->Orders_model->groupinfo_save(); + /** BIZ_Guest */ + $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name; + $this->Orders_model->biz_guest_save(); + /** BIZ_ConfirmLineInfo*/ + $this->Orders_model->BIZ_COLI_GRI_SN = $groupSN; + $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_No; + $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; + $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); + $this->Orders_model->BIZ_COLI_ApplyDate = $detail_jsonResp->orderDetail->orderTime; + $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$detail_jsonResp->orderDetail->operationDep]) ? 32090 : $this->city_info[$detail_jsonResp->orderDetail->operationDep]['COLI_sourcetype']; + $this->Orders_model->BIZ_COLI_State = 9; + $this->Orders_model->BIZ_COLI_servicetype = 'D'; + $this->Orders_model->BIZ_COLI_ConfirmType = 52001; + $this->Orders_model->BIZ_COLI_Memo = ""; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $detail_jsonResp->orderDetail->orderId . ";线路:" . $detail_jsonResp->orderDetail->routeName . "; 团名: " . $detail_jsonResp->orderDetail->agcOrderNo; + $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; + $this->Orders_model->BIZ_COLI_OPI_ID = 435; + $this->Orders_model->BIZ_COLI_PayManner = 15006; + $coli_sn = $this->Orders_model->biz_confirm_save(); + $coli_id = $this->Orders_model->BIZ_COLI_ID; + /**BIZ_ConfirmLineDetail*/ + $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->COLD_ServiceType = "D"; + $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_PAG_SN; + $this->Orders_model->COLD_ServiceSN2 = $pag_sub; + $this->Orders_model->COLD_ServiceCity = $serviceSN->PAG_CII_SN; + $this->Orders_model->COLD_StartDate = $detail_jsonResp->orderDetail->travelDate; + $this->Orders_model->COLD_EndDate = $detail_jsonResp->orderDetail->leaveDate; + $this->Orders_model->COLD_PersonNum = $detail_jsonResp->orderDetail->adultNum; + $this->Orders_model->COLD_ChildNum = $detail_jsonResp->orderDetail->childNum; + $this->Orders_model->cold_state = 9 + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; + $this->Orders_model->COLD_MemoText = $COLD_MemoText; + $cold_sn = $this->Orders_model->biz_confirm_detail_save(); + } + $groupSN = $groupSN ? $groupSN : $getInfo_byGroupCode->GRI_SN; + $coli_sn = $coli_sn ? $coli_sn : $getInfo_byGroupCode->COLI_SN; + $coli_id = $coli_id ? $coli_id : $getInfo_byGroupCode->COLI_ID; + $coli_memo = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_Memo : ""; + $coli_orderdetailtext = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; + $coli_state = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_State : 9; + $cold_sn = $cold_sn ? $cold_sn : $getInfo_byGroupCode->COLD_SN; + } else { + // $getInfo_byGroupCode = null; + $getInfo_byGroupCode = $getInfo_byGroupCode[0]; + $groupSN = $order->COLI_GRI_SN; + $coli_sn = $order->COLI_SN; + $coli_id = $order->COLI_ID; + $coli_memo = $order->COLI_Memo; + $coli_orderdetailtext = $order->COLI_OrderDetailText; + $coli_state = $order->COLI_State; + $cold_sn = $order->COLD_SN; } - $groupSN = $getInfo_byGroupCode!==null ? $getInfo_byGroupCode->GRI_SN : $order->COLI_GRI_SN; - $coli_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_SN : $order->COLI_SN; - $coli_id = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_ID : $order->COLI_ID; + // if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { + // $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $detail_jsonResp->orderDetail->orderId); + // } + /** UPDATE */ + $groupSN = $groupSN ? $groupSN : $order->COLI_GRI_SN; + $coli_sn = $coli_sn ? $coli_sn : $order->COLI_SN; + $coli_id = $coli_id ? $coli_id : $order->COLI_ID; $coli_memo = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; $coli_orderdetailtext = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; $coli_state = isset($getInfo_byGroupCode->COLI_SN) ? @@ -349,12 +451,10 @@ class TulanduoApi extends CI_Controller $cold_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { - } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { + } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && intval($order->COLI_OPI_ID)===435) { if ( $order->COLI_ID && $order->COLI_ID != $getInfo_byGroupCode->COLI_ID) { $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; - if (intval($order->COLI_OPI_ID) === 435 ) { - $this->order_cancel($order->COLI_ID); - } + $this->order_cancel($order->COLI_ID); } } /** groupcombineinfo */ @@ -369,6 +469,15 @@ class TulanduoApi extends CI_Controller ,"GCI_createTime" => date('Y-m-d H:i:s') ); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); + /** GRoupInfo */ + if (intval($order->COLI_OPI_ID) === 435 ) { + $gri_update_column = array( + "GRI_No" => $detail_jsonResp->orderDetail->agcOrderNo + ,"GRI_Name" => $detail_jsonResp->orderDetail->agcOrderNo + ); + $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN; + $this->Order_update->biz_groupinfo_update($gci_update_column); + } /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn; $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo; @@ -396,9 +505,18 @@ class TulanduoApi extends CI_Controller ,"COLI_State" => $coli_state ,"COLI_Price" => $travel_fee ,"COLI_CUrrency" => $travel_fee_currency + ,"COLI_GroupCode" => $detail_jsonResp->orderDetail->agcOrderNo ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ + if (intval($order->COLI_OPI_ID) === 435) { + $cold_update_column = array( + "COLD_PersonNum" => $detail_jsonResp->orderDetail->adultNum + ,"COLD_ChildNum" => $detail_jsonResp->orderDetail->childNum + ); + $this->Order_update->cold_where_update = " COLD_SN=" . $getInfo_byGroupCode->COLD_SN; + $this->Order_update->biz_confirmlinedetail_update($cold_update_column); + } /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { @@ -652,6 +770,7 @@ class TulanduoApi extends CI_Controller */ public function get_history_order_list($oldest_date=null) { + $this->load->model('Tulanduo_sync_model', 'sync_model'); // $oldest_date===null ? $oldest_date = $this->Orders_model->get_oldest_offset() : null; $oldest_date===null ? $oldest_date = '2018-05-10' : null; // test $startTravelDate = date('Y-m-d', strtotime("-1 day", strtotime($oldest_date))); @@ -677,7 +796,7 @@ class TulanduoApi extends CI_Controller if ($resp_arr["responseData"]["totalRows"] == 0) { log_message('error','TulanduoApi get_orderlist history 0. '); // 继续往前滚日期 - $this->get_history_order_list($startTravelDate); + return $this->get_history_order_list($startTravelDate); } $all_list = $resp_arr["responseData"]["orders"]; for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) { @@ -695,10 +814,52 @@ class TulanduoApi extends CI_Controller $exists_ht = $this->Orders_model->get_exists_vendorOrderId($all_vendor_order_id_str); $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); - var_export($to_insert); if (empty($to_insert) || count($to_insert)==1) { // 继续往前滚日期 - $this->get_history_order_list($startTravelDate); + return $this->get_history_order_list($startTravelDate); + } + foreach ($all_list as $k => $vo) { + if ( ! in_array($value['orderId'], $to_insert)) { + continue; + } + $vo['agcOrderNo'] = mb_ereg_replace('( )', '', trim($vo['agcOrderNo'])); // 去掉中文的全角空格 + // 解析产品编号 + $PAG_Code = $pag_sub = null; + preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); + if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { + $PAG_Code = $pag_no_tmp[$vo['routeName']]; + $split_code = explode("-", $PAG_Code); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else if ( ! empty($temp_array)) { + $PAG_Code = $pag_sub = null; + $split_code = explode("-", $temp_array[0]); + $PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $pag_sub=$split_code[2] : null; + } else { + log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); + } + $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; + $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); + $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); + $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; + // if (in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { + $real_groupCode = analysis_groupCode($vo['agcOrderNo']); + // check BIZ_COLI_SN,GRI_SN + $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + // } + /** INSERT */ + /** biz_groupcombineinfo*/ + $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; + $this->Orders_model->GCI_GRI_SN = $this->sync_model->GRI_SN; + $this->Orders_model->GCI_VEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; + $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; + $this->Orders_model->GCI_FromAgc = $vo['agcName']; + $this->Orders_model->GCI_groupType = $vo['orderType']; + $this->Orders_model->GCI_travelDate = $vo['travelDate']; + $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; + $this->Orders_model->GCI_createTime = date('Y-m-d H:i:s'); + $this->Orders_model->biz_groupcombineinfo_save(); } exit(); } diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index fa89eb5d..1562f36b 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -39,7 +39,7 @@ class Api extends CI_Controller { { return $ele->GCI_combineNo; }, $order_project)); - $ret['operation'] = null; + $ret['operation'] = array(); $operation = $this->Orders_model->get_operation($all_combine_no); // 司机, 导游 if ( ! empty($operation)) { diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index 7c2b17f0..bff88fd2 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -56,6 +56,20 @@ class Order_update extends CI_Model { return $update_exc; } + /*! + * 更新团信息 + */ + public $gri_where_update = ""; // where 条件 + public function biz_groupinfo_update($column_data) + { + if ($this->gri_where_update == "" || empty($column_data)) { + return false; + } + $update_str = $this->HT->update_string('GroupInfo', $column_data, $this->gri_where_update); + $update_exc = $this->HT->query($update_str); + return $update_exc; + } + /*! * 地接计划状态变更 * @param [type] $vas_sn [description] diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 43ecc465..ae96731a 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -122,18 +122,7 @@ class Orders_model extends CI_Model { } return NULL; } - public function get_exists_vendorOrderId($vendorOrderIds="") - { - $sql = "SELECT GCI_VendorOrderId FROM GroupCombineInfo - WHERE GCI_VendorOrderId IN ($vendorOrderIds) "; - return $this->HT->query($sql)->result(); - } - public function get_oldest_offset() - { - $sql = "SELECT top 1 CAST(GCI_travelDate as DATE) old_date from GroupCombineInfo - order by GCI_travelDate asc"; - return $this->HT->query($sql)->row()->old_date; - } + /*! * 需要更新调度信息的订单 -- 商务表 * @param integer $coli_sn [description] @@ -145,7 +134,7 @@ class Orders_model extends CI_Model { $sql = "SELECT top 10 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, gci.* FROM GroupCombineInfo gci - LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN --and coli.COLI_State NOT IN ('30','40','50') LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN WHERE 1=1 "; if ($coli_sn !== 0) { @@ -524,13 +513,19 @@ class Orders_model extends CI_Model { return NULL; } + /*! + * 1. 获取列表时: 按团号查询团是否已存在, 避免渠道和目的地组同时操作 + * @param [type] $code [description] + * @param [type] $vendorOrderId [description] + */ public function get_SN_by_groupCode($code, $vendorOrderId=NULL) { $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency ,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name FROM BIZ_ConfirmLineInfo coli - inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN and COLI_State not in (30,40,50) + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN --and COLI_State not in (30,40,50) LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 + and gri.GRI_operator<>435 and gri.GRI_operator is not null WHERE gri.GRI_No LIKE '%$code%' order by COLI_SN desc"; // and gri.GRI_Name like '%$NoName%' $query = $this->HT->query($sql); @@ -545,6 +540,27 @@ class Orders_model extends CI_Model { return NULL; } + /*! + * 更新时: + * @date 2018-08-23 + * @param [type] $code [description] + */ + public function get_order_by_groupcode($code) + { + $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, + coli.COLI_OrderDetailText, + coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, + coli.COLI_Memo + FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 + WHERE gri.GRI_No LIKE '%$code%' + order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; + $query = $this->HT->query($sql); + return $query->result(); + } + /*! * 获取地接社接受计划的人员信息 * @param $vendorID 地接社ID From 7921462d1771e7a7495d850dab22b6076dc7172f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 24 Aug 2018 15:46:17 +0800 Subject: [PATCH 153/382] =?UTF-8?q?=E6=9F=A5=E8=AF=A2bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 8 ++ .../trippestOrderSync/controllers/api.php | 2 +- .../models/tulanduo_sync_model.php | 122 ++++++++++++++++++ 3 files changed, 131 insertions(+), 1 deletion(-) create mode 100644 webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index b2370792..788f903c 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -399,6 +399,14 @@ class TulanduoApi extends CI_Controller ); $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** BIZ_ConfirmLineDetail */ + if (isset($getInfo_byGroupCode->COLI_SN) && intval($getInfo_byGroupCode->COLI_OPI_ID)===435) { + $cold_update_column = array( + "COLD_PersonNum" => $detail_jsonResp->orderDetail->adultNum + ,"COLD_ChildNum" => $detail_jsonResp->orderDetail->childNum + ); + $this->Order_update->cold_where_update = " COLD_SN=" . $getInfo_byGroupCode->COLD_SN; + $this->Order_update->biz_confirmlinedetail_update($cold_update_column); + } /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index fa89eb5d..1562f36b 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -39,7 +39,7 @@ class Api extends CI_Controller { { return $ele->GCI_combineNo; }, $order_project)); - $ret['operation'] = null; + $ret['operation'] = array(); $operation = $this->Orders_model->get_operation($all_combine_no); // 司机, 导游 if ( ! empty($operation)) { diff --git a/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php new file mode 100644 index 00000000..92c51eea --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php @@ -0,0 +1,122 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Tulanduo_sync_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + //读取默认配置 + $this->COLI_WebCode = $this->config->item('Site_Code'); + $this->COLI_Area = $this->config->item('Site_Area'); + $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); + $this->COLI_department = $this->config->item('Site_Department'); + $this->COLI_Currency = $this->config->item('Site_Currency'); + $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); + $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); + $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); + $this->COLI_OrderStartDate = null; + $this->COLI_Keywords = NULL; + switch ($this->check_device()) { + case 'mobile': + $this->COLI_OrderSource = '62003'; + break; + case 'tablet': + $this->COLI_OrderSource = '62002'; + break; + default: + $this->COLI_OrderSource = '62001'; + } + } + + /*! + * 查询图兰朵订单id是否已存在 + * @param string $vendorOrderIds [description] + */ + public function get_exists_vendorOrderId($vendorOrderIds="") + { + $sql = "SELECT GCI_VendorOrderId FROM GroupCombineInfo + WHERE GCI_VendorOrderId IN ($vendorOrderIds) "; + return $this->HT->query($sql)->result(); + } + /*! + * 从图兰朵同步历史数据的日期偏移 + * 获取HT内图兰朵订单的最老出发日期 + */ + public function get_oldest_offset() + { + $sql = "SELECT top 1 CAST(GCI_travelDate as DATE) old_date from GroupCombineInfo + order by GCI_travelDate asc"; + return $this->HT->query($sql)->row()->old_date; + } + /*! + * 图兰朵订单在HT内的信息 + * @param [type] $code [description] + * @param [type] $vendorOrderId [description] + */ + public function get_vendorOrder_HTinfo($code, $vendorOrderId=NULL) + { + # code... + } + + public $GCI_SN; + public $GCI_VEI_SN; + public $GCI_combineNo=''; // 拼团团号 + public $GCI_GRI_SN; // 团key + public $GCI_VendorOrderId; // 地接社系统订单id + public $GCI_FromAgc; // 组团社来源 + public $GCI_groupType; // 组团社来源 + public $GCI_travelDate; + public $GCI_leaveDate; + public $GCI_createTime; + /** 目的地订单 拼团信息 */ + public function biz_groupcombineinfo_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM GroupCombineInfo + WHERE GCI_VendorOrderId = ? and GCI_GRI_SN=? and GCI_VEI_SN=? + ) + INSERT INTO GroupCombineInfo + (GCI_combineNo + ,GCI_GRI_SN + ,GCI_VEI_SN + ,GCI_VendorOrderId + ,GCI_FromAgc + ,GCI_groupType + ,GCI_travelDate + ,GCI_leaveDate + ,GCI_createTime) + VALUES + (N? + ,? + ,? + ,? + ,N? + ,? + ,? + ,? + ,?) + "; + $query = $this->HT->query($sql, array( + $this->GCI_VendorOrderId + ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN + ,$this->GCI_combineNo + ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN + ,$this->GCI_VendorOrderId + ,$this->GCI_FromAgc + ,$this->GCI_groupType + ,$this->GCI_travelDate + ,$this->GCI_leaveDate + ,$this->GCI_createTime + )); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + return $this->GCI_SN; + } + +} + +/* End of file tulanduo_sync_model.php */ +/* Location: ./webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php */ From 3f20da44085dabb188744da16ae22cc5d64ed7de Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 7 Sep 2018 11:36:00 +0800 Subject: [PATCH 154/382] =?UTF-8?q?trippest=E8=8E=B7=E5=8F=96=E5=8E=86?= =?UTF-8?q?=E5=8F=B2=E8=AE=A2=E5=8D=95;=20=E6=8E=92=E9=99=A4=E5=95=86?= =?UTF-8?q?=E6=97=85=E7=BB=84=E5=9B=A2=E5=8F=B7;=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=9C=AA=E8=AF=86=E5=88=AB=E4=BA=A7=E5=93=81;=E6=8B=86?= =?UTF-8?q?=E5=88=86=E5=9B=A2=E4=BF=AE=E6=94=B9=E5=9B=A2=E5=8F=B7=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 1093 ++++++++--------- .../helpers/array_helper.php | 9 +- .../trippestOrderSync/models/orders_model.php | 8 +- .../models/tulanduo_sync_model.php | 59 + 4 files changed, 590 insertions(+), 579 deletions(-) create mode 100644 webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 1320495c..938d1a7b 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -21,6 +21,11 @@ class TulanduoApi extends CI_Controller ,"COLI_sourcetype" => 32090 ,"routeType" => "北京目的地线路" ), + "总部" => array( + "PlanVEI_SN" => 1343 + ,"COLI_sourcetype" => 32090 + ,"routeType" => "北京目的地线路" + ), "西安分公司" => array( "PlanVEI_SN" => 30548 ,"COLI_sourcetype" => 32116 @@ -32,6 +37,7 @@ class TulanduoApi extends CI_Controller ,"routeType" => "上海目的地线路" ) ); + public $vendor_ids = array(1343,30548,29188); // userId key // 1343 2e47c3721e3ff6e816fe6b928d7acc7d @@ -75,7 +81,6 @@ class TulanduoApi extends CI_Controller */ public function get_orderlist($order_number=null) { - // $order_number = $this->input->get_post("orderNo"); $startOrderDate = date('Y-m-d', strtotime("-2 days")); $endOrderDate = date('Y-m-d'); $startTravelDate = date('Y-m-d'); @@ -89,11 +94,11 @@ class TulanduoApi extends CI_Controller } else { $get_type = rand(0, 1); // 需要按预定时间和出发时间, 避免有漏的 if ($get_type === 0) { - log_message('error','get_orderlist From TuLanDuo By travel Date' ); + log_message('error','Got order list From TuLanDuo By travel Date' ); $this->tld_order->setStartTravelDate($startTravelDate) ->setEndTravelDate($endTravelDate) ; } else { - log_message('error','get_orderlist From TuLanDuo By order Date' ); + log_message('error','Got order list From TuLanDuo By order Date' ); $this->tld_order->setStartOrderDate($startOrderDate) ->setEndOrderDate($endOrderDate) ; } @@ -101,35 +106,21 @@ class TulanduoApi extends CI_Controller $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); if ($resp_arr['status'] !== 1) { - log_message('error','TulanduoApi get_orderlist failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + log_message('error','TulanduoApi Got order list failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); return; } if ($resp_arr["responseData"]["totalRows"] == 0) { - log_message('error','TulanduoApi get_orderlist 0. '); return; } $all_list = $resp_arr["responseData"]["orders"]; - $order_to_HT = array_map( - function($ele){ - if ( ! in_array($ele['agcName'], array("D目的地桂林组", "Trippest")) ) { - return $ele; - } - },$resp_arr["responseData"]["orders"]); for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) { $this->tld_order->setPageIndex($pi); $f_resp = $this->excute_curl($this->list_url, $this->tld_order); $f_resp_arr = json_decode($f_resp, true); if ($resp_arr['status'] !== 1) { - log_message('error','TulanduoApi get_orderlist failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + log_message('error','TulanduoApi Got order list failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); continue; } - $f_order_to_HT = array_map( - function($ele){ - if ( ! in_array($ele['agcName'], array("D目的地桂林组", "Trippest")) ) { - return $ele; - } - },$f_resp_arr["responseData"]["orders"]); - $order_to_HT = array_filter(array_merge($order_to_HT, $f_order_to_HT)); $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); } $cnt = 0; @@ -141,27 +132,9 @@ class TulanduoApi extends CI_Controller continue; } $unique_order[] = $vo['orderId']; - $this->Orders_model->BIZ_COLI_SN = null; - $this->Orders_model->GRI_SN = null; - $vo['agcOrderNo'] = mb_ereg_replace('( )', '', trim($vo['agcOrderNo'])); // 去掉中文的全角空格 - $PAG_Code = $pag_sub = null; - preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); - if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { - $PAG_Code = $pag_no_tmp[$vo['routeName']]; - $split_code = explode("-", $PAG_Code); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else if ( ! empty($temp_array)) { - $PAG_Code = $pag_sub = null; - $split_code = explode("-", $temp_array[0]); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else { - log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); - } - $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; - $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); - $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); + // paypal 手续费订单没有团号 + $vo['agcOrderNo'] = isset($vo['agcOrderNo']) ? $vo['agcOrderNo'] : $vo['groupOrderNo']; + $vo['agcOrderNo'] = trim_groupCode(trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $this->Orders_model->BIZ_COLI_SN = null; $this->Orders_model->GRI_SN = null; @@ -169,7 +142,6 @@ class TulanduoApi extends CI_Controller $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 - // if ($this->Orders_model->BIZ_COLI_SN===null && in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { if ($this->Orders_model->BIZ_COLI_SN === null) { $real_groupCode = analysis_groupCode($vo['agcOrderNo']); // set BIZ_COLI_SN, GRI_SN at Orders_model @@ -177,94 +149,40 @@ class TulanduoApi extends CI_Controller } if ($this->Orders_model->GRI_SN === null) { /** GRoupInfo */ - $travelDate = new DateTime($vo['travelDate']); - $leaveDate = new DateTime($vo['leaveDate']); - $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->GRI_No = mb_substr($vo['agcOrderNo'], 0, 49); - $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = mb_substr($vo["agcName"] . $vo['agcOrderNo'], 0, 49); - $this->Orders_model->GRI_PersonNum = $vo['adultNum']+$vo['childNum']; - $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); - $this->Orders_model->GRI_IsCancel = 0; - $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->GRI_OPI_ID = 435; - $this->Orders_model->GRI_operator = 435; - $this->Orders_model->GRI_Creator = 435; - $this->Orders_model->groupinfo_save(); + $this->insert_gri($vo); } /** insert HT */ if ($this->Orders_model->BIZ_COLI_SN === null) { /** BIZ_Guest */ $this->Orders_model->GUT_LastName = $vo['customerName']; $this->Orders_model->biz_guest_save(); - /**BIZ_ConfirmLineInfo*/ - $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_SN : null; - $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_SN ? $this->Orders_model->GRI_No : ""; - $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; - $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); - $this->Orders_model->BIZ_COLI_ApplyDate = $vo['orderDate']; - $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$vo['operationDep']]) ? 32090 : $this->city_info[$vo['operationDep']]['COLI_sourcetype']; - $this->Orders_model->BIZ_COLI_State = 9; - $this->Orders_model->BIZ_COLI_servicetype = 'D'; - $this->Orders_model->BIZ_COLI_ConfirmType = 52001; - $this->Orders_model->BIZ_COLI_Memo = ""; - $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $vo["orderId"] . ";线路:" . $vo['routeName'] . "; 团名: " . $vo['agcOrderNo']; - $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; - $this->Orders_model->BIZ_COLI_OPI_ID = 435; - $this->Orders_model->BIZ_COLI_PayManner = 15006; - $coli_sn[] = $this->Orders_model->biz_confirm_save(); - /**BIZ_ConfirmLineDetail*/ - $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; - $this->Orders_model->COLD_ServiceType = "D"; - $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_PAG_SN; - $this->Orders_model->COLD_ServiceSN2 = $pag_sub; - $this->Orders_model->COLD_ServiceCity = $serviceSN->PAG_CII_SN; - $this->Orders_model->COLD_StartDate = $vo['travelDate']; - $this->Orders_model->COLD_EndDate = $vo['leaveDate']; - $this->Orders_model->COLD_PersonNum = $vo['adultNum']; - $this->Orders_model->COLD_ChildNum = $vo['childNum']; - $this->Orders_model->cold_state = $vo['orderStatus']==1 ? 9 : 104; // 9订妥 // 104联络地接中 - $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; - $this->Orders_model->COLD_MemoText = $COLD_MemoText; - $this->Orders_model->biz_confirm_detail_save(); - /** SP_BIZ_Arrange - * 这里是其他社的订单, 不写这个操作 - */ - // if ($this->Orders_model->GRI_SN) { - // $this->Orders_model->sp_biz_arrange(); - // } + /** BIZ_ConfirmLineInfo*/ + $this->insert_coli($vo); + /** BIZ_ConfirmLineDetail*/ + $this->insert_cold($vo); $cnt++; } if ($this->Orders_model->GCI_SN === null) { /*biz_groupcombineinfo*/ - $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; - $this->Orders_model->GCI_GRI_SN = $this->Orders_model->GRI_SN; - $this->Orders_model->GCI_VEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; - $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; - $this->Orders_model->GCI_FromAgc = $vo['agcName']; - $this->Orders_model->GCI_groupType = $vo['orderType']; - $this->Orders_model->GCI_travelDate = $vo['travelDate']; - $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; - $this->Orders_model->GCI_createTime = date('Y-m-d H:i:s'); - $this->Orders_model->biz_groupcombineinfo_save(); + $this->insert_gci($vo); } } - log_message('error',"Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . " Insert COLI : " . $cnt); - echo "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . "\r\n"; - echo "Insert COLI : " . $cnt . "\r\n"; + $output_text = "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . ". Insert COLI : " . $cnt; + log_message('error', $output_text); + echo $output_text; return; } /*! * 更新订单的详情;[客人列表, 团费, 调度信息] + * * 定时执行, 约5分钟一次, 每次更新一个订单 * @date 2018-05-02 * @param [type] $coli_sn HT系统的订单key */ public function insert_HT_order_operation($coli_sn=null,$get_vendorID=null) { - log_message('error','get_order_operation From TuLanDuo '); + // log_message('error','get_order_operation From TuLanDuo '); $this->load->model('Order_update'); if ($coli_sn !== null && $coli_sn != 0) { $to_update_list = $this->Orders_model->get_groupCombineInfo($coli_sn); @@ -277,246 +195,182 @@ class TulanduoApi extends CI_Controller $endDate = date('Y-m-d', strtotime("+2 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate); } - $unique_orderGroupCombine = array(); - $unique_order = array(); - $cnt = 0; - foreach ($to_update_list as $key => $order) { - if (in_array($order->GCI_VendorOrderId, $unique_order)) { - continue; - } - $unique_order[] = $order->GCI_VendorOrderId; - $this->tld_order->setOrderId($order->GCI_VendorOrderId) - ->setUserId($this->userId) - ->setKey($this->key); - $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); - $detail_jsonResp = json_decode($detail_resp); - // 判断取消 - if ($detail_jsonResp->status !== 1) { - log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); - if ( $detail_jsonResp->errMsg == "未查询到对应的订单") { - $this->plan_cancel($order->GCI_VendorOrderId); - if (intval($order->COLI_OPI_ID) === 435) { - $this->order_cancel($order->COLI_ID); - } - } - continue; - } - $detail_jsonResp->orderDetail->agcOrderNo = mb_ereg_replace('( )', '', trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格 - // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 - if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { + $unique_orderGroupCombine = array(); // 录入拼团调度时,避免重复 + $order = $to_update_list[0]; + $this->tld_order->setOrderId($order->GCI_VendorOrderId) + ->setUserId($this->userId) + ->setKey($this->key); + $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + $detail_jsonResp = json_decode($detail_resp); + // 判断取消 + if ($detail_jsonResp->status !== 1) { + log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); + if ( $detail_jsonResp->errMsg == "未查询到对应的订单") { $this->plan_cancel($order->GCI_VendorOrderId); if (intval($order->COLI_OPI_ID) === 435) { $this->order_cancel($order->COLI_ID); } - continue; } - $allDetails_to_HT = ""; - $allDetails_to_HT .= "\r\n日程: "; - foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { - $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; + if ($detail_jsonResp->errMsg == "您没有查看本订单的权限!") { + $this->plan_cancel($order->GCI_VendorOrderId, "forbidden"); } - if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { - $allDetails_to_HT .= "\r\n导游: "; - foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { - $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; - } + return; + } + $detail_jsonResp->orderDetail->agcOrderNo = trim_groupCode(trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格 + // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 + if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { + $this->plan_cancel($order->GCI_VendorOrderId); + if (intval($order->COLI_OPI_ID) === 435) { + $this->order_cancel($order->COLI_ID); } - if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) ) { - $allDetails_to_HT .= "\r\n用车: "; - foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vtc) { - $allDetails_to_HT .= $vtc->name .": " . $vtc->driver." (". $vtc->driverTel . ") "; - $allDetails_to_HT .= "[". $vtc->remark . "]; "; - } + return; + } + $allDetails_to_HT = ""; + $allDetails_to_HT .= "\r\n日程: "; + foreach ($detail_jsonResp->orderDetail->scheduleDetails as $vsd) { + $allDetails_to_HT .= $vsd->travelDate .": ". $vsd->title . "; "; + } + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { + $allDetails_to_HT .= "\r\n导游: "; + foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vg) { + $allDetails_to_HT .= $vg->name ." (". $vg->mobelPhone . "); "; } - /** HT 开始 */ - $cnt++; - $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : $order->COLD_PlanVEI_SN; - $getInfo_byGroupCode = null; - $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); - if (intval($order->COLI_OPI_ID) === 435 ) { - $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); - if ( empty($getInfo_byGroupCodeArr) ){ - $getInfo_byGroupCode = null; // 没有该团号的团信息 - } elseif (strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 - $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0]; // 渠道和目的地有重复操作的团 - } else { - foreach ($getInfo_byGroupCodeArr as $kg => $vg) { - if (mb_substr($vg->GRI_No, 0, 49) === $detail_jsonResp->orderDetail->agcOrderNo) { - // 地接拆分的团号,需要全部匹配; 否则为没有团信息 - $getInfo_byGroupCode = $vg; - break; - } - } - } - if ($getInfo_byGroupCode === null) { - $PAG_Code = $pag_sub = null; - preg_match('/[a-zA-Z]+\-[0-9\-]+/', characet($detail_jsonResp->orderDetail->routeName, "UTF-8"), $temp_array); - if (empty($temp_array) && isset($pag_no_tmp[$detail_jsonResp->orderDetail->routeName])) { - $PAG_Code = $pag_no_tmp[$detail_jsonResp->orderDetail->routeName]; - $split_code = explode("-", $PAG_Code); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else if ( ! empty($temp_array)) { - $PAG_Code = $pag_sub = null; - $split_code = explode("-", $temp_array[0]); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else { - log_message('error',"未识别的线路名称 $PAG_Code " . $detail_jsonResp->orderDetail->orderId . " " . $detail_jsonResp->orderDetail->routeName . var_export($temp_array, 1)); + } + if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations) ) { + $allDetails_to_HT .= "\r\n用车: "; + foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vtc) { + $allDetails_to_HT .= $vtc->name .": " . $vtc->driver." (". $vtc->driverTel . ") "; + $allDetails_to_HT .= "[". $vtc->remark . "]; "; + } + } + /** HT 开始 */ + $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; + $getInfo_byGroupCode = null; + $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + $duplicate = false; + // 由同步新增的订单 或 未找到团号关联 + if (intval($order->COLI_OPI_ID) === 435 || $order->COLI_ID === null) { + if ( empty($getInfo_byGroupCodeArr)){ + $getInfo_byGroupCode = null; // 没有该团号的团信息 + } elseif (strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 + $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0]; // 渠道和目的地有重复操作的团 + $duplicate = true; + } else { + foreach ($getInfo_byGroupCodeArr as $kg => $vg) { + if ($vg->GRI_No === mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49)) { + // 地接拆分的团号,需要全部匹配; 否则为没有团信息 + $getInfo_byGroupCode = $vg; + break; } - $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; - $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); - $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic)); - /** INSERT GRoupInfo */ - $travelDate = new DateTime($detail_jsonResp->orderDetail->travelDate); - $leaveDate = new DateTime($detail_jsonResp->orderDetail->leaveDate); - $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->GRI_No = mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49); - $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = mb_substr($detail_jsonResp->orderDetail->agcName . $detail_jsonResp->orderDetail->agcOrderNo, 0, 49); - $this->Orders_model->GRI_PersonNum = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; - $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); - $this->Orders_model->GRI_IsCancel = 0; - $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->GRI_OPI_ID = 435; - $this->Orders_model->GRI_operator = 435; - $this->Orders_model->GRI_Creator = 435; - $groupSN = $this->Orders_model->groupinfo_save(); - /** BIZ_Guest */ - $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name; - $this->Orders_model->biz_guest_save(); - /** BIZ_ConfirmLineInfo*/ - $this->Orders_model->BIZ_COLI_GRI_SN = $groupSN; - $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_No; - $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; - $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); - $this->Orders_model->BIZ_COLI_ApplyDate = $detail_jsonResp->orderDetail->orderTime; - $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$detail_jsonResp->orderDetail->operationDep]) ? 32090 : $this->city_info[$detail_jsonResp->orderDetail->operationDep]['COLI_sourcetype']; - $this->Orders_model->BIZ_COLI_State = 9; - $this->Orders_model->BIZ_COLI_servicetype = 'D'; - $this->Orders_model->BIZ_COLI_ConfirmType = 52001; - $this->Orders_model->BIZ_COLI_Memo = ""; - $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $detail_jsonResp->orderDetail->orderId . ";线路:" . $detail_jsonResp->orderDetail->routeName . "; 团名: " . $detail_jsonResp->orderDetail->agcOrderNo; - $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; - $this->Orders_model->BIZ_COLI_OPI_ID = 435; - $this->Orders_model->BIZ_COLI_PayManner = 15006; - $coli_sn = $this->Orders_model->biz_confirm_save(); - $coli_id = $this->Orders_model->BIZ_COLI_ID; - /**BIZ_ConfirmLineDetail*/ - $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; - $this->Orders_model->COLD_ServiceType = "D"; - $this->Orders_model->COLD_ServiceSN = $serviceSN->PAG2_PAG_SN; - $this->Orders_model->COLD_ServiceSN2 = $pag_sub; - $this->Orders_model->COLD_ServiceCity = $serviceSN->PAG_CII_SN; - $this->Orders_model->COLD_StartDate = $detail_jsonResp->orderDetail->travelDate; - $this->Orders_model->COLD_EndDate = $detail_jsonResp->orderDetail->leaveDate; - $this->Orders_model->COLD_PersonNum = $detail_jsonResp->orderDetail->adultNum; - $this->Orders_model->COLD_ChildNum = $detail_jsonResp->orderDetail->childNum; - $this->Orders_model->cold_state = 9 - $this->Orders_model->DeleteFlag = 0; - $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; - $this->Orders_model->COLD_MemoText = $COLD_MemoText; - $cold_sn = $this->Orders_model->biz_confirm_detail_save(); } - $groupSN = $groupSN ? $groupSN : $getInfo_byGroupCode->GRI_SN; - $coli_sn = $coli_sn ? $coli_sn : $getInfo_byGroupCode->COLI_SN; - $coli_id = $coli_id ? $coli_id : $getInfo_byGroupCode->COLI_ID; - $coli_memo = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_Memo : ""; - $coli_orderdetailtext = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; - $coli_state = ($getInfo_byGroupCode!==null) ? $getInfo_byGroupCode->COLI_State : 9; - $cold_sn = $cold_sn ? $cold_sn : $getInfo_byGroupCode->COLD_SN; - } else { - // $getInfo_byGroupCode = null; - $getInfo_byGroupCode = $getInfo_byGroupCode[0]; - $groupSN = $order->COLI_GRI_SN; - $coli_sn = $order->COLI_SN; - $coli_id = $order->COLI_ID; - $coli_memo = $order->COLI_Memo; - $coli_orderdetailtext = $order->COLI_OrderDetailText; - $coli_state = $order->COLI_State; - $cold_sn = $order->COLD_SN; } - // if (in_array($order->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { - // $getInfo_byGroupCode = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $detail_jsonResp->orderDetail->orderId); - // } - /** UPDATE */ - $groupSN = $groupSN ? $groupSN : $order->COLI_GRI_SN; - $coli_sn = $coli_sn ? $coli_sn : $order->COLI_SN; - $coli_id = $coli_id ? $coli_id : $order->COLI_ID; - $coli_memo = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_Memo : $order->COLI_Memo; - $coli_orderdetailtext = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLI_OrderDetailText : $order->COLI_OrderDetailText; - $coli_state = isset($getInfo_byGroupCode->COLI_SN) ? - (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? 9 : $getInfo_byGroupCode->COLI_State) - : 9; - $cold_sn = isset($getInfo_byGroupCode->COLI_SN) ? $getInfo_byGroupCode->COLD_SN : $order->COLD_SN; - // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 if ($getInfo_byGroupCode === null) { - } elseif ($getInfo_byGroupCode->GRI_SN != $order->COLI_GRI_SN && intval($order->COLI_OPI_ID)===435) { - if ( $order->COLI_ID && $order->COLI_ID != $getInfo_byGroupCode->COLI_ID) { - $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; - $this->order_cancel($order->COLI_ID); - } - } - /** groupcombineinfo */ - // $this->Order_update->gci_where_update = " GCI_VEI_SN=$vei_SN and GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; - $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "'"; - $gci_update_column = array( - "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null - ,"GCI_VEI_SN" => $vei_SN - ,"GCI_GRI_SN" => $groupSN - ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate - ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate - ,"GCI_createTime" => date('Y-m-d H:i:s') - ); - $this->Order_update->biz_groupcombineinfo_update($gci_update_column); - /** GRoupInfo */ - if (intval($order->COLI_OPI_ID) === 435 ) { - $gri_update_column = array( - "GRI_No" => $detail_jsonResp->orderDetail->agcOrderNo - ,"GRI_Name" => $detail_jsonResp->orderDetail->agcOrderNo - ); - $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN; - $this->Order_update->biz_groupinfo_update($gci_update_column); + /** INSERT */ + $order_detail_arr = (array)$detail_jsonResp->orderDetail; + /** GRoupInfo */ + $groupSN = $this->insert_gri($order_detail_arr); + /** BIZ_Guest */ + $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name; + $this->Orders_model->biz_guest_save(); + /** BIZ_ConfirmLineInfo*/ + $order_detail_arr['orderDate'] = $order_detail_arr['orderTime']; + $coli_sn = $this->insert_coli($order_detail_arr); + $coli_id = $this->Orders_model->BIZ_COLI_ID; + /**BIZ_ConfirmLineDetail*/ + $cold_sn = $this->insert_cold($order_detail_arr); } - /** BIZ_ConfirmLineInfo */ - $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn; - $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo; - $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; - $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; - $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; - // 团款总金额 美元币种 - $travel_fee = 0; - $travel_fee_currency = 'RMB'; - if (isset($detail_jsonResp->orderDetail->travelFees) ) { - foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { - $travel_fee = bcadd($travel_fee, $vtf->sumMoney); - } - unset($vtf); + $groupSN = isset($groupSN) ? $groupSN : $getInfo_byGroupCode->GRI_SN; + $coli_sn = isset($coli_sn) ? $coli_sn : $getInfo_byGroupCode->COLI_SN; + $coli_id = isset($coli_id) ? $coli_id : $getInfo_byGroupCode->COLI_ID; + $cold_sn = isset($cold_sn) ? $cold_sn : $getInfo_byGroupCode->COLD_SN; + $coli_opi_id = 435; + $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : ""; + $coli_state = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_State : 9; + $coli_orderdetailtext = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; + } else { + // 已找到的目的地发的计划 + // $getInfo_byGroupCode = $order; + $getInfo_byGroupCode = $getInfo_byGroupCode[0]; + $groupSN = $order->COLI_GRI_SN; + $coli_sn = $order->COLI_SN; + $coli_id = $order->COLI_ID; + $coli_memo = $order->COLI_Memo; + $coli_state = $order->COLI_State; + $cold_sn = $order->COLD_SN; // ???多个子订单 !!!仅用于435创建的订单的更新, 因此仅一个 + $coli_opi_id = $order->COLI_OPI_ID; + $coli_orderdetailtext = $order->COLI_OrderDetailText; + } + /** UPDATE */ + // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 + if ($duplicate === true) { + if ( $order->COLI_ID && $order->COLI_ID != $getInfo_byGroupCode->COLI_ID) { + $allDetails_to_HT .= "\r\n疑似重复,请更新订单状态:" . $order->COLI_ID; + $this->order_cancel($order->COLI_ID); } - $travel_fee = isset($getInfo_byGroupCode->COLI_SN) ? - (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee : $getInfo_byGroupCode->COLI_Price) - : $travel_fee; - $travel_fee_currency = isset($getInfo_byGroupCode->COLI_SN) ? - (intval($getInfo_byGroupCode->COLI_OPI_ID)===435 ? $travel_fee_currency : $getInfo_byGroupCode->COLI_CUrrency) - : $travel_fee_currency; - $coli_update_column = array( - "COLI_Memo" => substr($new_memo, 0, 400) - ,"COLI_OrderDetailText" => $new_detail - ,"COLI_State" => $coli_state - ,"COLI_Price" => $travel_fee - ,"COLI_CUrrency" => $travel_fee_currency - ,"COLI_GroupCode" => $detail_jsonResp->orderDetail->agcOrderNo + } + /** groupcombineinfo */ + $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "' and GCI_VEI_SN in (" . implode(',', $this->vendor_ids) . ")"; // 不明确指定供应商id,出现过不对应的情况 + $gci_update_column = array( + "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null + ,"GCI_VEI_SN" => $vei_SN + ,"GCI_GRI_SN" => $groupSN + ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate + ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate + ,"GCI_createTime" => date('Y-m-d H:i:s') + ); + $this->Order_update->biz_groupcombineinfo_update($gci_update_column); + /** GRoupInfo */ + if (intval($order->COLI_OPI_ID) === 435 ) { + $gri_update_column = array( + "GRI_No" => $detail_jsonResp->orderDetail->agcOrderNo + ,"GRI_Name" => $detail_jsonResp->orderDetail->agcOrderNo ); - $this->Order_update->biz_confirmlineinfo_update($coli_update_column); - /** BIZ_ConfirmLineDetail */ - if (intval($order->COLI_OPI_ID) === 435) { - $cold_update_column = array( - "COLD_PersonNum" => $detail_jsonResp->orderDetail->adultNum - ,"COLD_ChildNum" => $detail_jsonResp->orderDetail->childNum - ); - $this->Order_update->cold_where_update = " COLD_SN=" . $getInfo_byGroupCode->COLD_SN; - $this->Order_update->biz_confirmlinedetail_update($cold_update_column); + $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN; + $this->Order_update->biz_groupinfo_update($gri_update_column); + } + /** BIZ_ConfirmLineInfo */ + $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn; + $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo; + $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; + $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; + $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; + // 团款总金额 + $travel_fee = 0; + $travel_fee_currency = 'RMB'; + if (isset($detail_jsonResp->orderDetail->travelFees) ) { + foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { + $travel_fee = bcadd($travel_fee, $vtf->sumMoney); } + unset($vtf); + } + $travel_fee = intval($coli_opi_id)===435 ? $travel_fee : $getInfo_byGroupCode->COLI_Price; + $travel_fee_currency = intval($coli_opi_id)===435 ? $travel_fee_currency : $getInfo_byGroupCode->COLI_CUrrency; + $coli_update_column = array( + "COLI_Memo" => substr($new_memo, 0, 400) + ,"COLI_OrderDetailText" => $new_detail + ,"COLI_State" => $coli_state + ,"COLI_Price" => $travel_fee + ,"COLI_CUrrency" => $travel_fee_currency + ,"COLI_GroupCode" => mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49) + ); + $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + /** + * update BIZ_ConfirmLineDetail + * insert BIZ_BookPeople,BIZ_PackageOrderInfo + */ + if (intval($coli_opi_id) === 435) { + /** BIZ_ConfirmLineDetail */ + $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); + $cold_update_column = array( + "COLD_PersonNum" => $detail_jsonResp->orderDetail->adultNum + ,"COLD_ChildNum" => $detail_jsonResp->orderDetail->childNum + ,"COLD_ServiceSN" => $pag_info->serviceinfo->PAG2_PAG_SN + ,"COLD_ServiceSN2" => $pag_info->pag_sub + ,"COLD_ServiceCity" => $pag_info->serviceinfo->PAG_CII_SN + ); + $this->Order_update->cold_where_update = " COLD_SN=" . $cold_sn; + $this->Order_update->biz_confirmlinedetail_update($cold_update_column); /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { @@ -540,227 +394,185 @@ class TulanduoApi extends CI_Controller $this->Orders_model->POI_EndTime = $detail_jsonResp->orderDetail->leaveDate; $this->Orders_model->POI_QuotationType = 1; // 1 报价 2 网络支付价 3 促销价 $this->Orders_model->biz_packageorder_save(); - /** BIZ_GroupAccountInfo */ - // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 - $paytype = 15006; // 地接代收 - $pay_currency = 'RMB'; - $auto_text = "dataAutoEnter "; - // query latest order detail - $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); - // 删除旧的录入 - $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); - if (isset($detail_jsonResp->orderDetail->travelFees) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { + } + // query latest order detail + $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); + /** BIZ_GroupAccountInfo */ + // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 + $paytype = 15006; // 地接代收 + $pay_currency = 'RMB'; + $auto_text = "dataAutoEnter "; + // 删除旧的录入 + $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); + if (intval($latest_order_detail[0]->COLI_OPI_ID)===435) { + // 团款 + if (isset($detail_jsonResp->orderDetail->travelFees) ) { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { - // if ($vtf->reviewStatus == 0) { // 未审核的 - // continue; - // } - $this->Orders_model->GAI_Operator = 435; - $this->Orders_model->GAI_COLI_SN = $coli_sn; - $this->Orders_model->GAI_GRI_SN = $groupSN; - $this->Orders_model->GAI_COLI_ID = $coli_id; - $this->Orders_model->GAI_Type = $paytype; - $this->Orders_model->GAI_SQJE = $vtf->sumMoney; - $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_SSJE = $vtf->sumMoney; - $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); - $this->Orders_model->GAI_Memo = $auto_text . "团款" . $vtf->type . ", " . $vtf->remark; - $this->Orders_model->biz_groupaccountinfo_save(); + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vtf->sumMoney, $vtf->sumMoney, $auto_text . "代收" . $vtf->type . ", " . $vtf->remark); } } - // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. todo + // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. // 代收 - if (isset($detail_jsonResp->orderDetail->replaceCollections) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { + if (isset($detail_jsonResp->orderDetail->replaceCollections) ) { foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { - // if ($vrc->reviewStatus == 0) { - // continue; - // } - $this->Orders_model->GAI_Operator = 435; - $this->Orders_model->GAI_COLI_SN = $coli_sn; - $this->Orders_model->GAI_GRI_SN = $groupSN; - $this->Orders_model->GAI_COLI_ID = $coli_id; - $this->Orders_model->GAI_Type = $paytype; - $this->Orders_model->GAI_SQJE = $vrc->money; - $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_SSJE = $vrc->money; - $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); - $this->Orders_model->GAI_Memo = $auto_text . "代收" . $vrc->type . ", " . $vrc->remark; - $this->Orders_model->biz_groupaccountinfo_save(); + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vrc->money, $vrc->money, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark); } } - if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { + if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $koor => $voor) { - $this->Orders_model->GAI_Operator = 435; - $this->Orders_model->GAI_COLI_SN = $coli_sn; - $this->Orders_model->GAI_GRI_SN = $groupSN; - $this->Orders_model->GAI_COLI_ID = $coli_id; - $this->Orders_model->GAI_Type = $paytype; - $this->Orders_model->GAI_SQJE = $voor->sumMoney; - $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_SSJE = $voor->sumMoney; - $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); - $this->Orders_model->GAI_Memo = $auto_text . "代收" . $voor->type . ", " . $voor->remark; - $this->Orders_model->biz_groupaccountinfo_save(); + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $voor->sumMoney, $voor->sumMoney, $auto_text . "代收" . $voor->type . ", " . $voor->remark); } } // 代付 - if (isset($detail_jsonResp->orderDetail->replacePays) && intval($latest_order_detail[0]->COLI_OPI_ID===435) ) { + if (isset($detail_jsonResp->orderDetail->replacePays) ) { foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { - // if ($vrp->reviewStatus == 0) { - // continue; - // } - $this->Orders_model->GAI_Operator = 435; - $this->Orders_model->GAI_COLI_SN = $coli_sn; - $this->Orders_model->GAI_GRI_SN = $groupSN; - $this->Orders_model->GAI_COLI_ID = $coli_id; - $this->Orders_model->GAI_Type = $paytype; - $this->Orders_model->GAI_SQJE = "-" . $vrp->money; - $this->Orders_model->GAI_SQJECurrency = $pay_currency; - $this->Orders_model->GAI_SSJE = $vrp->money; - $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); - $this->Orders_model->GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; - $this->Orders_model->biz_groupaccountinfo_save(); + $GAI_SQJE = "-" . $vrp->money; + $GAI_SSJE = "-" . $vrp->money; + $GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $GAI_Memo); } } - /*BIZ_GroupCombineOperationDetail*/ - if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { // 没有拼团团号 - continue; - } - if (in_array($detail_jsonResp->orderDetail->groupOrderNo, $unique_orderGroupCombine)) { - continue; - } - $unique_orderGroupCombine[] = $detail_jsonResp->orderDetail->groupOrderNo; - // 删除旧的录入 - $this->Orders_model->biz_groupcombineoperationdetail_cut($detail_jsonResp->orderDetail->groupOrderNo); - // 门票 - if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { - foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "sceneryOperations"; - $this->Orders_model->GCOD_subType = $vso->type; - $this->Orders_model->GCOD_title = $vso->name; - $this->Orders_model->GCOD_startDate = $vso->useDate; - $this->Orders_model->GCOD_endDate = $vso->useDate; - $this->Orders_model->GCOD_useNum = $vso->useNum; - $this->Orders_model->GCOD_sumMoney = $vso->sumMoney; - $this->Orders_model->GCOD_remark = $vso->remark; - $this->Orders_model->GCOD_dutyName = ""; - $this->Orders_model->GCOD_dutyTel = null; - $this->Orders_model->GCOD_dutyPhoto = null; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + /*BIZ_GroupCombineOperationDetail*/ + if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { // 没有拼团团号 + continue; + } + if (in_array($detail_jsonResp->orderDetail->groupOrderNo, $unique_orderGroupCombine)) { + continue; + } + $unique_orderGroupCombine[] = $detail_jsonResp->orderDetail->groupOrderNo; + // 删除旧的录入 + $this->Orders_model->biz_groupcombineoperationdetail_cut($detail_jsonResp->orderDetail->groupOrderNo); + // 门票 + if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { + foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "sceneryOperations"; + $this->Orders_model->GCOD_subType = $vso->type; + $this->Orders_model->GCOD_title = $vso->name; + $this->Orders_model->GCOD_startDate = $vso->useDate; + $this->Orders_model->GCOD_endDate = $vso->useDate; + $this->Orders_model->GCOD_useNum = $vso->useNum; + $this->Orders_model->GCOD_sumMoney = $vso->sumMoney; + $this->Orders_model->GCOD_remark = $vso->remark; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = null; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - // 用房 ... - // 用餐 - if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { - foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "restraurantOperations"; - $this->Orders_model->GCOD_subType = $vro->type; - $this->Orders_model->GCOD_title = $vro->name; - $this->Orders_model->GCOD_startDate = $vro->useDate; - $this->Orders_model->GCOD_endDate = $vro->useDate; - $this->Orders_model->GCOD_useNum = $vro->useNum; - $this->Orders_model->GCOD_sumMoney = $vro->sumMoney; - $this->Orders_model->GCOD_standard = $vro->standard; - $this->Orders_model->GCOD_remark = $vro->remark; - $this->Orders_model->GCOD_dutyName = ""; - $this->Orders_model->GCOD_dutyTel = null; - $this->Orders_model->GCOD_dutyPhoto = null; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + // 用房 ... + // 用餐 + if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "restraurantOperations"; + $this->Orders_model->GCOD_subType = $vro->type; + $this->Orders_model->GCOD_title = $vro->name; + $this->Orders_model->GCOD_startDate = $vro->useDate; + $this->Orders_model->GCOD_endDate = $vro->useDate; + $this->Orders_model->GCOD_useNum = $vro->useNum; + $this->Orders_model->GCOD_sumMoney = $vro->sumMoney; + $this->Orders_model->GCOD_standard = $vro->standard; + $this->Orders_model->GCOD_remark = $vro->remark; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = null; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - // 用车 - if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { - foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "touristCarOperations"; - $this->Orders_model->GCOD_subType = $vco->type; - $this->Orders_model->GCOD_title = $vco->name; - $this->Orders_model->GCOD_dutyName = $vco->driver; - $this->Orders_model->GCOD_dutyTel = $vco->driverTel; - $this->Orders_model->GCOD_startDate = $vco->startDate; - $this->Orders_model->GCOD_endDate = $vco->endDate; - $this->Orders_model->GCOD_sumMoney = $vco->sumMoney; - $this->Orders_model->GCOD_carLicense = $vco->carLicense; - $this->Orders_model->GCOD_useNum = 1; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_dutyPhoto = null; - $this->Orders_model->GCOD_remark = $vco->remark; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + // 用车 + if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { + foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "touristCarOperations"; + $this->Orders_model->GCOD_subType = $vco->type; + $this->Orders_model->GCOD_title = $vco->name; + $this->Orders_model->GCOD_dutyName = $vco->driver; + $this->Orders_model->GCOD_dutyTel = $vco->driverTel; + $this->Orders_model->GCOD_startDate = $vco->startDate; + $this->Orders_model->GCOD_endDate = $vco->endDate; + $this->Orders_model->GCOD_sumMoney = $vco->sumMoney; + $this->Orders_model->GCOD_carLicense = $vco->carLicense; + $this->Orders_model->GCOD_useNum = 1; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_dutyPhoto = null; + $this->Orders_model->GCOD_remark = $vco->remark; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - // 导游服务 - if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { - foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "guiderOperations"; - $this->Orders_model->GCOD_subType = ""; - $this->Orders_model->GCOD_title = ""; - $this->Orders_model->GCOD_dutyName = $vgo->name; - $this->Orders_model->GCOD_dutyTel = $vgo->mobelPhone; - $this->Orders_model->GCOD_dutyPhoto = isset($vgo->guiderPhoto) ? $vgo->guiderPhoto : ''; - $this->Orders_model->GCOD_startDate = $vgo->startDate; - $this->Orders_model->GCOD_endDate = $vgo->endDate; - $this->Orders_model->GCOD_sumMoney = $vgo->sumMoney; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_remark = $vgo->remark; - $this->Orders_model->GCOD_useNum = 1; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + // 导游服务 + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "guiderOperations"; + $this->Orders_model->GCOD_subType = ""; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = $vgo->name; + $this->Orders_model->GCOD_dutyTel = $vgo->mobelPhone; + $this->Orders_model->GCOD_dutyPhoto = isset($vgo->guiderPhoto) ? $vgo->guiderPhoto : ''; + $this->Orders_model->GCOD_startDate = $vgo->startDate; + $this->Orders_model->GCOD_endDate = $vgo->endDate; + $this->Orders_model->GCOD_sumMoney = $vgo->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vgo->remark; + $this->Orders_model->GCOD_useNum = 1; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - // 其他支出 - if (isset($detail_jsonResp->orderDetail->operationDetails->otherCosts) ) { - foreach ($detail_jsonResp->orderDetail->operationDetails->otherCosts as $voc) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "otherCosts"; - $this->Orders_model->GCOD_subType = $voc->type; - $this->Orders_model->GCOD_title = ""; - $this->Orders_model->GCOD_dutyName = ""; - $this->Orders_model->GCOD_dutyTel = ""; - $this->Orders_model->GCOD_dutyPhoto = ''; - $this->Orders_model->GCOD_startDate = ""; - $this->Orders_model->GCOD_endDate = ""; - $this->Orders_model->GCOD_sumMoney = $voc->sumMoney; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_remark = $voc->remark; - $this->Orders_model->GCOD_useNum = $voc->useNum; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + // 其他支出 + if (isset($detail_jsonResp->orderDetail->operationDetails->otherCosts) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->otherCosts as $voc) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "otherCosts"; + $this->Orders_model->GCOD_subType = $voc->type; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = ""; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $voc->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $voc->remark; + $this->Orders_model->GCOD_useNum = $voc->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - // 其他收入 - if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { - foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "otherReceives"; - $this->Orders_model->GCOD_subType = $vor->type; - $this->Orders_model->GCOD_title = ""; - $this->Orders_model->GCOD_dutyName = ""; - $this->Orders_model->GCOD_dutyTel = ""; - $this->Orders_model->GCOD_dutyPhoto = ''; - $this->Orders_model->GCOD_startDate = ""; - $this->Orders_model->GCOD_endDate = ""; - $this->Orders_model->GCOD_sumMoney = $vor->sumMoney; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_remark = $vor->remark; - $this->Orders_model->GCOD_useNum = $vor->useNum; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } + } + // 其他收入 + if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { + foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "otherReceives"; + $this->Orders_model->GCOD_subType = $vor->type; + $this->Orders_model->GCOD_title = ""; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = ""; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $vor->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vor->remark; + $this->Orders_model->GCOD_useNum = $vor->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); } - } // end foreach order - log_message('error',"Got order operations from TuLanDuo, count: " . count($cnt)); - echo "Got order operations from TuLanDuo, count: " . count($cnt); + } + $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id; + log_message('error', $output_text); + echo $output_text; return; } @@ -768,11 +580,19 @@ class TulanduoApi extends CI_Controller * 往前获取历史数据 * @date 2018-08-21 */ + public $date_roll = 0; public function get_history_order_list($oldest_date=null) { + // 避免执行超时, 滚动3次之后结束 + if ($this->date_roll > 2) { + log_message('error', "Got order list from TuLanDuo. Roll end. " . $oldest_date); + return false; + } + $this->date_roll ++; $this->load->model('Tulanduo_sync_model', 'sync_model'); - // $oldest_date===null ? $oldest_date = $this->Orders_model->get_oldest_offset() : null; - $oldest_date===null ? $oldest_date = '2018-05-10' : null; // test + $oldest_date===null ? $oldest_date = $this->sync_model->get_oldest_offset() : null; + // $oldest_date===null ? $oldest_date = '2018-05-10' : null; // test + // $oldest_date===null ? $oldest_date = '2018-04-28' : null; // test $startTravelDate = date('Y-m-d', strtotime("-1 day", strtotime($oldest_date))); $endTravelDate = $oldest_date; $start_date = $this->input->get_post("start"); @@ -785,8 +605,6 @@ class TulanduoApi extends CI_Controller ->setPageIndex(1) ->setStartTravelDate($startTravelDate) ->setEndTravelDate($endTravelDate) ; - var_export($startTravelDate); - var_export($endTravelDate); $resp = $this->excute_curl($this->list_url, $this->tld_order); $resp_arr = json_decode($resp, true); if (intval($resp_arr['status']) !== 1) { @@ -811,57 +629,169 @@ class TulanduoApi extends CI_Controller } $all_vendor_order_id = array_column($all_list, 'orderId'); $all_vendor_order_id_str = implode(',', $all_vendor_order_id); - $exists_ht = $this->Orders_model->get_exists_vendorOrderId($all_vendor_order_id_str); + $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str); $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); - if (empty($to_insert) || count($to_insert)==1) { + // if (empty($to_insert)) { + if (empty($to_insert) || count($to_insert)==1) { // test // 继续往前滚日期 return $this->get_history_order_list($startTravelDate); } + $cnt = 0; foreach ($all_list as $k => $vo) { - if ( ! in_array($value['orderId'], $to_insert)) { + if ( ! in_array($vo['orderId'], $to_insert)) { continue; } - $vo['agcOrderNo'] = mb_ereg_replace('( )', '', trim($vo['agcOrderNo'])); // 去掉中文的全角空格 - // 解析产品编号 - $PAG_Code = $pag_sub = null; - preg_match('/[a-zA-Z]+\-[0-9\-]+/', $this->characet($vo['routeName'], "UTF-8"), $temp_array); - if (empty($temp_array) && isset($pag_no_tmp[$vo['routeName']])) { - $PAG_Code = $pag_no_tmp[$vo['routeName']]; - $split_code = explode("-", $PAG_Code); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else if ( ! empty($temp_array)) { - $PAG_Code = $pag_sub = null; - $split_code = explode("-", $temp_array[0]); - $PAG_Code = $split_code[0] . "-" . $split_code[1]; - isset($split_code[2]) ? $pag_sub=$split_code[2] : null; - } else { - log_message('error',"未识别的线路名称 $PAG_Code " . $vo['orderId'] . " " . $vo['routeName'] . var_export($temp_array, 1)); - } - $PAG_Code = in_array($PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $PAG_Code; - $serviceSN = $this->Orders_model->get_packageSN($PAG_Code); - $COLD_MemoText = raw_json_encode(array("Pick up"=>$vo['toTraffic'], "Drop off"=>$vo['backTraffic'])); + $vo['agcOrderNo'] = trim_groupCode(trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; + $this->Orders_model->BIZ_COLI_SN = null; + $this->Orders_model->GRI_SN = null; // if (in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { $real_groupCode = analysis_groupCode($vo['agcOrderNo']); // check BIZ_COLI_SN,GRI_SN $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); // } /** INSERT */ - /** biz_groupcombineinfo*/ - $this->Orders_model->GCI_combineNo = isset($vo['groupOrderNo']) ? $vo['groupOrderNo'] : ''; - $this->Orders_model->GCI_GRI_SN = $this->sync_model->GRI_SN; - $this->Orders_model->GCI_VEI_SN = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; - $this->Orders_model->GCI_VendorOrderId = $vo['orderId']; - $this->Orders_model->GCI_FromAgc = $vo['agcName']; - $this->Orders_model->GCI_groupType = $vo['orderType']; - $this->Orders_model->GCI_travelDate = $vo['travelDate']; - $this->Orders_model->GCI_leaveDate = $vo['leaveDate']; - $this->Orders_model->GCI_createTime = date('Y-m-d H:i:s'); - $this->Orders_model->biz_groupcombineinfo_save(); + /** GRoupInfo */ + if ($this->Orders_model->GRI_SN === null) { + $this->insert_gri($vo); + } + if ($this->Orders_model->BIZ_COLI_SN === null) { + /** BIZ_Guest */ + $this->Orders_model->GUT_LastName = $vo['customerName']; + $this->Orders_model->biz_guest_save(); + /** BIZ_ConfirmLineInfo */ + $this->insert_coli($vo); + /** BIZ_ConfirmLineDetail */ + $this->insert_cold($vo); + $cnt++; + } + /** biz_groupcombineinfo */ + $this->insert_gci($vo); } - exit(); + $output_text = "Got order list from TuLanDuo (" . $startTravelDate . " ~ " . $endTravelDate . "). count: " . $resp_arr["responseData"]["totalRows"] . ". Insert COLI : " . $cnt; + log_message('error',$output_text); + echo $output_text; + return; + } + + public function insert_gai($coli_sn, $gri_sn, $coli_id, $paytype, $currency, $sqje, $ssje, $memo="") + { + $this->Orders_model->GAI_Operator = 435; + $this->Orders_model->GAI_COLI_SN = $coli_sn; + $this->Orders_model->GAI_GRI_SN = $gri_sn; + $this->Orders_model->GAI_COLI_ID = $coli_id; + $this->Orders_model->GAI_Type = $paytype; + $this->Orders_model->GAI_SQJE = $sqje; + $this->Orders_model->GAI_SQJECurrency = $currency; + $this->Orders_model->GAI_SSJE = $ssje; + $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); + $this->Orders_model->GAI_Memo = $memo; + return $this->Orders_model->biz_groupaccountinfo_save(); + } + + public function insert_cold($list_ele) + { + $COLD_MemoText = raw_json_encode(array("Pick up"=>$list_ele['toTraffic'], "Drop off"=>$list_ele['backTraffic'])); + $pag_info = $this->analysis_productcode($list_ele['routeName'], $list_ele['orderId']); + $this->Orders_model->COLD_COLI_SN = $this->Orders_model->BIZ_COLI_SN; + $this->Orders_model->COLD_ServiceType = "D"; + $this->Orders_model->COLD_ServiceSN = $pag_info->serviceinfo->PAG2_PAG_SN; + $this->Orders_model->COLD_ServiceSN2 = $pag_info->pag_sub; + $this->Orders_model->COLD_ServiceCity = $pag_info->serviceinfo->PAG_CII_SN; + $this->Orders_model->COLD_StartDate = $list_ele['travelDate']; + $this->Orders_model->COLD_EndDate = $list_ele['leaveDate']; + $this->Orders_model->COLD_PersonNum = $list_ele['adultNum']; + $this->Orders_model->COLD_ChildNum = $list_ele['childNum']; + $this->Orders_model->cold_state = $list_ele['orderStatus']==1 ? 9 : 104; // 9订妥 // 104联络地接中 + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->COLD_PlanVEI_SN = $this->city_info[$list_ele['operationDep']]['PlanVEI_SN'] ? $this->city_info[$list_ele['operationDep']]['PlanVEI_SN'] : 1343; + $this->Orders_model->COLD_MemoText = $COLD_MemoText; + return $this->Orders_model->biz_confirm_detail_save(); + } + + public function insert_coli($list_ele) + { + $this->Orders_model->BIZ_COLI_GRI_SN = $this->Orders_model->GRI_SN ; + $this->Orders_model->BIZ_COLI_GroupCode = $this->Orders_model->GRI_No ; + $this->Orders_model->BIZ_GUT_SN = $this->Orders_model->GUT_SN; + $this->Orders_model->BIZ_COLI_ID = $this->Orders_model->biz_make_order_number(); + $this->Orders_model->BIZ_COLI_ApplyDate = $list_ele['orderDate']; + $this->Orders_model->BIZ_COLI_sourcetype = empty($this->city_info[$list_ele['operationDep']]) ? 32090 : $this->city_info[$list_ele['operationDep']]['COLI_sourcetype']; + $this->Orders_model->BIZ_COLI_State = 9; + $this->Orders_model->BIZ_COLI_servicetype = 'D'; + $this->Orders_model->BIZ_COLI_ConfirmType = 52001; + $this->Orders_model->BIZ_COLI_Memo = ""; + $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $list_ele["orderId"] . ";线路:" . $list_ele['routeName'] . "; 团名: " . $list_ele['agcOrderNo']; + $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; + $this->Orders_model->BIZ_COLI_OPI_ID = 435; + $this->Orders_model->BIZ_COLI_PayManner = 15006; + return $this->Orders_model->biz_confirm_save(); + } + + public function insert_gri($list_ele) + { + $travelDate = new DateTime($list_ele['travelDate']); + $leaveDate = new DateTime($list_ele['leaveDate']); + $date_diff = $travelDate->diff($leaveDate); + $this->Orders_model->GRI_No = mb_substr($list_ele['agcOrderNo'], 0, 49); + $this->Orders_model->GRI_OrderType = 227002; // 商务 + $this->Orders_model->GRI_Name = mb_substr($list_ele['agcOrderNo'], 0, 49); + $this->Orders_model->GRI_PersonNum = $list_ele['adultNum']+$list_ele['childNum']; + $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); + $this->Orders_model->GRI_IsCancel = 0; + $this->Orders_model->DeleteFlag = 0; + $this->Orders_model->GRI_OPI_ID = 435; + $this->Orders_model->GRI_operator = 435; + $this->Orders_model->GRI_Creator = 435; + return $this->Orders_model->groupinfo_save(); + } + + public function insert_gci($list_ele) + { + $this->Orders_model->GCI_combineNo = isset($list_ele['groupOrderNo']) ? $list_ele['groupOrderNo'] : ''; + $this->Orders_model->GCI_GRI_SN = $this->Orders_model->GRI_SN; + $this->Orders_model->GCI_VEI_SN = $this->city_info[$list_ele['operationDep']]['PlanVEI_SN'] ? $this->city_info[$list_ele['operationDep']]['PlanVEI_SN'] : 1343; + $this->Orders_model->GCI_VendorOrderId = $list_ele['orderId']; + $this->Orders_model->GCI_FromAgc = $list_ele['agcName']; + $this->Orders_model->GCI_groupType = $list_ele['orderType']; + $this->Orders_model->GCI_travelDate = $list_ele['travelDate']; + $this->Orders_model->GCI_leaveDate = $list_ele['leaveDate']; + $this->Orders_model->GCI_createTime = date('Y-m-d H:i:s'); + return $this->Orders_model->biz_groupcombineinfo_save(); + } + + // 解析产品编号 + public function analysis_productcode($route_name, $vendor_orderid) + { + $ret = new stdClass(); + $ret->PAG_Code = null; + $ret->pag_sub = null; + $ret->serviceinfo = new stdClass(); + $pag_no_tmp = $this->pag_no_tmp(); + preg_match('/[a-zA-Z]+\-[0-9\-]+/', characet($route_name, "UTF-8"), $temp_array); + if (empty($temp_array) && isset($pag_no_tmp[$route_name])) { + $ret->PAG_Code = $pag_no_tmp[$route_name]; + $split_code = explode("-", $ret->PAG_Code); + $ret->PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $ret->pag_sub=$split_code[2] : null; + } else if ( ! empty($temp_array)) { + $ret->PAG_Code = null; + $ret->pag_sub = null; + $split_code = explode("-", $temp_array[0]); + $ret->PAG_Code = $split_code[0] . "-" . $split_code[1]; + isset($split_code[2]) ? $ret->pag_sub=$split_code[2] : null; + } else { + log_message('error',"UnKnown route name " . $ret->PAG_Code . " " . $vendor_orderid . " " . $route_name . var_export($temp_array, 1)); + $ret->serviceinfo->PAG2_SN = null; + $ret->serviceinfo->PAG_CII_SN = null; + $ret->serviceinfo->PAG2_PAG_SN = null; + } + $ret->PAG_Code = in_array($ret->PAG_Code, array("SHALC-6","SHALC-7","SHALC-8","SHALC-9")) ? "SHSIC-45" : $ret->PAG_Code; + if ($ret->PAG_Code) { + $ret->serviceinfo = $this->Orders_model->get_packageSN($ret->PAG_Code); + } + return $ret; } /*! @@ -874,7 +804,7 @@ class TulanduoApi extends CI_Controller if ($COLI_ID == '') { return false; } - log_message('error','修改为不成行 order_cancel ' . $COLI_ID); + log_message('error','update order_cancel ' . $COLI_ID); /** UPDATE HT */ /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_ID='" . $COLI_ID . "'"; @@ -883,12 +813,27 @@ class TulanduoApi extends CI_Controller ); return $this->Order_update->biz_confirmlineinfo_update($coli_update_column); } - public function plan_cancel($vendorID=0) + public function groupinfo_delete($gri_sn=0) + { + if ($gri_sn === 0) { + return false; + } + /** GRoupInfo */ + $this->Order_update->gri_where_update = " GRI_SN='" . $gri_sn . "'"; + $gri_update_column = array( + "DeleteFlag" => 1 + ); + return $this->Order_update->biz_groupinfo_update($gri_update_column); + } + public function plan_cancel($vendorID=0, $state="cancel") { + if ($vendorID === 0) { + return false; + } /** groupcombineinfo */ $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $vendorID . "'"; $gci_update_column = array( - "GCI_combineNo" => 'cancel' + "GCI_combineNo" => $state ,"GCI_createTime" => date('Y-m-d H:i:s') ); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); @@ -1124,6 +1069,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"司马台西-金山岭徒步一日游(PVT)(目的地)" => "BJSIC-46" ,"司马台西-金山岭长城徒步拼团(目的地)" => "BJSIC-46" ,"慕田峪半日游拼团(目的地)" => "BJSIC-47" + ,"慕田峪半日游PVT(目的地)" => "BJSIC-47" ,"古北口长城徒步一日游(目的地)" => "BJSIC-48" ,"半日游广场故宫拼团(目的地)" => "BJSIC-41" // ,=> @@ -1133,6 +1079,7 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"西安单租车接送服务(目的地)" => "XASIC-17" ,"西安兵马俑精品一日游(目的地)" => "XASIC-41" ,"西安兵马俑精品半日游(目的地)" => "XASIC-15" + ,"西安兵马俑精品半日游PVT(目的地)" => "XASIC-15" ,"西安汉阳陵市内精品一日游(目的地)" => "XASIC-42" // ,=> ,"上海精品一日游(目的地)" => "SHSIC-41" diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index b1cf03e2..8880682f 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -117,8 +117,9 @@ function raw_json_encode($input, $flags = 0) { function analysis_groupCode($groupCode) { mb_regex_encoding("UTF-8"); + $groupCode = trim_groupCode(trim($groupCode)); preg_match('/[\w\s\-]+/', characet($groupCode, "UTF-8"), $temp_array); - $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; + // $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0]; if (isset($tmp_groupCode[1])) { @@ -131,9 +132,13 @@ function analysis_groupCode($groupCode) $real_groupCode .= mb_strstr($tmp_groupCode[$i], "(", true)!==false ? mb_strstr($tmp_groupCode[$i], "(", true) : $tmp_groupCode[$i]; } } - $real_groupCode = mb_ereg_replace('( )', '', trim($real_groupCode)); + $real_groupCode = trim_groupCode(trim($real_groupCode)); return $real_groupCode; } +function trim_groupCode($groupCode) +{ + return mb_ereg_replace('( | | )', '', $groupCode); +} /*! * 转换字符集编码 * @param $data diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index ae96731a..9871d2be 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -131,7 +131,7 @@ class Orders_model extends CI_Model { */ public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) { - $sql = "SELECT top 10 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, gci.* FROM GroupCombineInfo gci LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN --and coli.COLI_State NOT IN ('30','40','50') @@ -267,7 +267,7 @@ class Orders_model extends CI_Model { $this->GRI_Creator, $this->GRI_OrderType )); - $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_No='" . $this->GRI_No . "'")->row('insert_id'); + $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_operator=435 AND GRI_No='" . $this->GRI_No . "'")->row('insert_id'); return $this->GRI_SN; } @@ -526,7 +526,7 @@ class Orders_model extends CI_Model { inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN --and COLI_State not in (30,40,50) LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 and gri.GRI_operator<>435 and gri.GRI_operator is not null - WHERE gri.GRI_No LIKE '%$code%' + WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' order by COLI_SN desc"; // and gri.GRI_Name like '%$NoName%' $query = $this->HT->query($sql); if ($query->num_rows() > 0) { @@ -555,7 +555,7 @@ class Orders_model extends CI_Model { FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 - WHERE gri.GRI_No LIKE '%$code%' + WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; $query = $this->HT->query($sql); return $query->result(); diff --git a/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php new file mode 100644 index 00000000..abcfb29a --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php @@ -0,0 +1,59 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Tulanduo_sync_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + /*! + * 查询图兰朵订单id是否已存在 + * @param string $vendorOrderIds [description] + */ + public function get_exists_vendorOrderId($vendorOrderIds="") + { + $sql = "SELECT GCI_VendorOrderId FROM GroupCombineInfo + WHERE GCI_VendorOrderId IN ($vendorOrderIds) "; + return $this->HT->query($sql)->result(); + } + /*! + * 从图兰朵同步历史数据的日期偏移 + * 获取HT内图兰朵订单的最老出发日期 + * * 由于获取列表时根据发团日期或得到更早时间的发团日期 + * * 因此这里取最早的10个, 找出不连续的为滚动日期的开始 + */ + public function get_oldest_offset() + { + $sql = "SELECT DISTINCT TOP 10 CAST(GCI_travelDate as DATE) old_date from GroupCombineInfo + order by old_date asc"; + $all_date = $this->HT->query($sql)->result(); + $all_date_arr = array_map(function($ele) + { + return $ele->old_date; + }, $all_date); + for ($i=count($all_date_arr)-1; $i > 0; $i--) { + $d1 = new DateTime($all_date_arr[$i]); + $d2 = new DateTime($all_date_arr[$i-1]); + $date_diff = $d2->diff($d1); + if (intval($date_diff->format('%R%a')) > 1) { + return $all_date_arr[$i]; + } + } + return $all_date_arr[0]; + } + /*! + * 图兰朵订单在HT内的信息 + * @param [type] $code [description] + * @param [type] $vendorOrderId [description] + */ + public function get_vendorOrder_HTinfo($code, $vendorOrderId=NULL) + { + # code... + } + +} + +/* End of file tulanduo_sync_model.php */ +/* Location: ./webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php */ From 0f94413dd2fe6684dcea9e404604670dd95e5a16 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 7 Sep 2018 14:23:07 +0800 Subject: [PATCH 155/382] =?UTF-8?q?=E6=9B=B4=E6=96=B0=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E4=B8=BB=E8=A1=A8:=20=E4=BB=85=E5=90=8C=E6=AD=A5=E7=9A=84?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=9B=B4=E6=96=B0=E6=94=B6=E6=AC=BE=E5=86=85?= =?UTF-8?q?=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 938d1a7b..82425233 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -344,16 +344,16 @@ class TulanduoApi extends CI_Controller } unset($vtf); } - $travel_fee = intval($coli_opi_id)===435 ? $travel_fee : $getInfo_byGroupCode->COLI_Price; - $travel_fee_currency = intval($coli_opi_id)===435 ? $travel_fee_currency : $getInfo_byGroupCode->COLI_CUrrency; $coli_update_column = array( "COLI_Memo" => substr($new_memo, 0, 400) ,"COLI_OrderDetailText" => $new_detail - ,"COLI_State" => $coli_state - ,"COLI_Price" => $travel_fee - ,"COLI_CUrrency" => $travel_fee_currency - ,"COLI_GroupCode" => mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49) ); + if (intval($coli_opi_id)===435) { + $coli_update_column["COLI_State"] = $coli_state; + $coli_update_column["COLI_Price"] = $travel_fee; + $coli_update_column["COLI_CUrrency"] = $travel_fee_currency; + $coli_update_column["COLI_GroupCode"] = mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49); + } $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** * update BIZ_ConfirmLineDetail From 4e206ba4594be38caac03b17034ce9861c1a6d75 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 7 Sep 2018 16:08:27 +0800 Subject: [PATCH 156/382] =?UTF-8?q?trippest=E5=90=8C=E6=AD=A5:=E6=89=8B?= =?UTF-8?q?=E7=BB=AD=E8=B4=B9=E8=AE=A2=E5=8D=95=E6=97=A0=E5=9B=A2=E5=8F=B7?= =?UTF-8?q?=E9=97=AE=E9=A2=98;=E6=9B=B4=E6=96=B0=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E7=9A=84=E8=B0=83=E5=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 22 +++++++---- .../trippestOrderSync/models/orders_model.php | 38 +++++++++++-------- 2 files changed, 37 insertions(+), 23 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 82425233..d023979a 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -133,7 +133,7 @@ class TulanduoApi extends CI_Controller } $unique_order[] = $vo['orderId']; // paypal 手续费订单没有团号 - $vo['agcOrderNo'] = isset($vo['agcOrderNo']) ? $vo['agcOrderNo'] : $vo['groupOrderNo']; + $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo']; $vo['agcOrderNo'] = trim_groupCode(trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $this->Orders_model->BIZ_COLI_SN = null; @@ -246,11 +246,14 @@ class TulanduoApi extends CI_Controller /** HT 开始 */ $vei_SN = $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] ? $this->city_info[$detail_jsonResp->orderDetail->operationDep]['PlanVEI_SN'] : 1343; $getInfo_byGroupCode = null; - $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); - $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + $getInfo_byGroupCodeArr = array(); + if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo != "") { + $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + } $duplicate = false; // 由同步新增的订单 或 未找到团号关联 - if (intval($order->COLI_OPI_ID) === 435 || $order->COLI_ID === null) { + if (intval($order->COLI_OPI_ID) === 435 || $order->COLI_ID === null || empty($getInfo_byGroupCodeArr)) { if ( empty($getInfo_byGroupCodeArr)){ $getInfo_byGroupCode = null; // 没有该团号的团信息 } elseif (strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 @@ -271,8 +274,11 @@ class TulanduoApi extends CI_Controller /** GRoupInfo */ $groupSN = $this->insert_gri($order_detail_arr); /** BIZ_Guest */ - $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name; - $this->Orders_model->biz_guest_save(); + $this->Orders_model->GUT_SN = null; + if (isset($detail_jsonResp->orderDetail->customers)) { + $this->Orders_model->GUT_LastName = $detail_jsonResp->orderDetail->customers[0]->name; + $this->Orders_model->biz_guest_save(); + } /** BIZ_ConfirmLineInfo*/ $order_detail_arr['orderDate'] = $order_detail_arr['orderTime']; $coli_sn = $this->insert_coli($order_detail_arr); @@ -646,11 +652,11 @@ class TulanduoApi extends CI_Controller $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->BIZ_COLI_SN = null; $this->Orders_model->GRI_SN = null; - // if (in_array($vo['agcName'], array("D目的地桂林组", "Trippest"))) { + if ( isset($vo['agcOrderNo']) && $vo['agcOrderNo'] != "") { $real_groupCode = analysis_groupCode($vo['agcOrderNo']); // check BIZ_COLI_SN,GRI_SN $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); - // } + } /** INSERT */ /** GRoupInfo */ if ($this->Orders_model->GRI_SN === null) { diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 9871d2be..78bfb4aa 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -132,7 +132,7 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) { $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - cold.COLD_PlanVEI_SN, gci.* + cold.COLD_PlanVEI_SN, gci.*,'0' as 'isHistory' FROM GroupCombineInfo gci LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN --and coli.COLI_State NOT IN ('30','40','50') LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN @@ -144,21 +144,29 @@ class Orders_model extends CI_Model { $sql .= " and GCI_VendorOrderId='$get_vendorID' "; } if ($startDate !== NULL) { - $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' "; + $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' and gci.GCI_createTime < '" . date('Y-m-d') . "' "; } - $sql .= " order by GCI_createTime asc "; - // $sql .= "UNION SELECT top 50 - // coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - // cold.COLD_PlanVEI_SN, gci.* - // FROM GroupCombineInfo gci - // left JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN and coli.COLI_State NOT IN ('30','40','50') - // left JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - // WHERE 1=1 - // and not exists ( - // select * from BIZ_GroupAccountInfo where GAI_COLI_SN=COLI_SN - // ) - // and COLI_OPI_ID=435 - // order by GCI_travelDate"; + // 近期的订单同步完成之后, 同步历史数据 + $sql .= " UNION ALL "; + $sql .= " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + cold.COLD_PlanVEI_SN, gci.*,'1' as 'isHistory' + from GroupCombineInfo gci + inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + where + GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') + and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + and GCI_combineNo not like '%取消%' + and not exists ( + select GCOD_SN from GroupCombineOperationDetail gcod where gcod.GCOD_GCI_combineNo=GCI_combineNo + ) + and 0 < ( + select sum(isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)+isnull(COLD_BabyNum,0)) person from BIZ_ConfirmLineInfo + inner join BIZ_ConfirmLineDetail on COLD_COLI_SN=COLI_SN + where COLI_GRI_SN=gri_sn + ) "; + $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; $query = $this->HT->query($sql); return $query->result(); } From f0cade4838b55fc6ee412d5fce1edceec0ffc150 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 7 Sep 2018 16:40:01 +0800 Subject: [PATCH 157/382] =?UTF-8?q?trippest=E5=90=8C=E6=AD=A5:=E4=B8=8D?= =?UTF-8?q?=E8=83=BD=E7=94=A8arrya=5Fcolumn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index d023979a..72b382f1 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -633,13 +633,12 @@ class TulanduoApi extends CI_Controller } $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); } - $all_vendor_order_id = array_column($all_list, 'orderId'); + $all_vendor_order_id = array_map(function($ele){ return $ele['orderId'];}, $all_list); $all_vendor_order_id_str = implode(',', $all_vendor_order_id); $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str); $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); - // if (empty($to_insert)) { - if (empty($to_insert) || count($to_insert)==1) { // test + if (empty($to_insert)) { // 继续往前滚日期 return $this->get_history_order_list($startTravelDate); } From e78d707c77769363da019839d6c0e81a2db291d6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 11 Oct 2018 15:58:23 +0800 Subject: [PATCH 158/382] =?UTF-8?q?=E5=8F=91=E9=80=81=E8=AE=A1=E5=88=92?= =?UTF-8?q?=E5=88=86=E6=94=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/.htaccess | 1 + .../controllers/TulanduoApi.php | 320 +++++++++++++++++ .../vendorPlanSync/controllers/index.php | 14 + .../vendorPlanSync/helpers/array_helper.php | 167 +++++++++ .../vendorPlanSync/helpers/index.html | 10 + webht/third_party/vendorPlanSync/index.html | 10 + .../vendorPlanSync/libraries/index.html | 10 + ...uo_addOrUpdateRouteOrderContentBuilder.php | 334 ++++++++++++++++++ .../models/TuLanDuo_queryContentBuilder.php | 142 ++++++++ .../vendorPlanSync/models/index.html | 10 + .../vendorPlanSync/views/index.html | 10 + .../vendorPlanSync/views/welcome_message.php | 88 +++++ 12 files changed, 1116 insertions(+) create mode 100644 webht/third_party/vendorPlanSync/.htaccess create mode 100644 webht/third_party/vendorPlanSync/controllers/TulanduoApi.php create mode 100644 webht/third_party/vendorPlanSync/controllers/index.php create mode 100644 webht/third_party/vendorPlanSync/helpers/array_helper.php create mode 100644 webht/third_party/vendorPlanSync/helpers/index.html create mode 100644 webht/third_party/vendorPlanSync/index.html create mode 100644 webht/third_party/vendorPlanSync/libraries/index.html create mode 100644 webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php create mode 100644 webht/third_party/vendorPlanSync/models/TuLanDuo_queryContentBuilder.php create mode 100644 webht/third_party/vendorPlanSync/models/index.html create mode 100644 webht/third_party/vendorPlanSync/views/index.html create mode 100644 webht/third_party/vendorPlanSync/views/welcome_message.php diff --git a/webht/third_party/vendorPlanSync/.htaccess b/webht/third_party/vendorPlanSync/.htaccess new file mode 100644 index 00000000..14249c50 --- /dev/null +++ b/webht/third_party/vendorPlanSync/.htaccess @@ -0,0 +1 @@ +Deny from all \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/controllers/TulanduoApi.php b/webht/third_party/vendorPlanSync/controllers/TulanduoApi.php new file mode 100644 index 00000000..baddabc4 --- /dev/null +++ b/webht/third_party/vendorPlanSync/controllers/TulanduoApi.php @@ -0,0 +1,320 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class TulanduoApi extends CI_Controller +{ + public $special_route = array( + "BJSIC-42" => "'BJSIC-41','BJSIC-42'" + ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" + ,"XASIC-42" => "'XASIC-41','XASIC-42'" + ); + public $special_route_name = array( + "BJSIC-42" => "北京精品两日游(目的地BJSIC-42)" + ,"BJSIC-43" => "北京精品三日游(目的地BJSIC-43)" + ,"XASIC-42" => "西安精品两日游(目的地XASIC-42)" + ); + public $city_info = array( + "北京分公司" => array( + "PlanVEI_SN" => 1343 + ,"COLI_sourcetype" => 32090 + ,"routeType" => "北京目的地线路" + ), + "总部" => array( + "PlanVEI_SN" => 1343 + ,"COLI_sourcetype" => 32090 + ,"routeType" => "北京目的地线路" + ), + "西安分公司" => array( + "PlanVEI_SN" => 30548 + ,"COLI_sourcetype" => 32116 + ,"routeType" => "西安目的地线路" + ), + "上海分公司" => array( + "PlanVEI_SN" => 29188 + ,"COLI_sourcetype" => 32112 + ,"routeType" => "上海目的地线路" + ) + ); + public $vendor_ids = array(1343,30548,29188); + + // userId key + // 1343 2e47c3721e3ff6e816fe6b928d7acc7d + // 29188 95c3b0d958a79a1216e651df182b3cb4 + // 30548 9db75a2dc17156eb122364295804b7a2 + + // test + // public $list_url = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/"; + // public $detail_url = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/"; + public $neworder_url = "http://dj.ltsoftware.net:9901/action/api/addOrUpdateRouteOrder/"; + // Live + public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; + public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; + // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; + + // 发送到图兰朵系统接口的参数jsonParams + + public function __construct(){ + parent::__construct(); + mb_regex_encoding("UTF-8"); + bcscale(4); + $this->load->helper('array'); + $this->load->model('Orders_model'); + $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); + // $this->output->enable_profiler(TRUE); + /** test */ + // $this->userId = "358"; + // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + /** Live */ + // 目的地 + $this->userId = "1134"; + $this->key = "73d180d05d425fd192e1c5b3097e75ff"; + // 桂林海纳国旅 + // $this->userId = "18"; + // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + } + + /*! + * 发送预订计划到地接系统 + * TODO read word into remark + * @date 2018-05-02 + * @param string $COLI_ID HT系统订单号 + */ + public function order_push($COLI_ID="") // test + { + // exit(); + /** 目的地 test */ + $this->userId = "358"; + $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); + $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID); + if(empty($orderinfo)) {return;} + $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ; + $guestlist = $this->Orders_model->get_guestlist($COLD_SN_str); + $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str); + $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; + // 子线路 + if ($scheduleDetails[0]->PAGS_CN_Title) { + $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]"; + } + $routeName .= " " . $scheduleDetails[0]->PAG_Code; + if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { + $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); + } + $travelFees = $this->Orders_model->get_paymentDetails($COLI_ID); + bcscale(4); + $this->tldOrderBuilder->setUserId($this->userId) + ->setKey($this->key) + ->setOrderType(2) // todo + ->setRouteName($routeName) + ->setRouteType($scheduleDetails[0]->CII2_Name . "目的地线路") + ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->CII2_Name) + ->setAdultNum($orderinfo[0]->COLD_PersonNum) + ->setChildNum($orderinfo[0]->COLD_ChildNum) + ->setDestination($scheduleDetails[0]->CII2_Name) + ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) + ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)) + ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)); // todo 抵离交通 + foreach ($guestlist as $key => $vg) { + $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) + ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) + ->setCustomersDocumentType($key, "护照") // Passport No. + ->setCustomersDocumentNo($key, $vg->BPE_Passport) + ->setCustomersOtherInfo($key, $this->Orders_model->GetNationalityName($orderinfo[0]->GUT_NationalityID)); + } + foreach ($scheduleDetails as $ks => $vs) { + $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title) + ->setScheduleDetailsTitle($ks, $vs->PAG2_Name) + // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($ks, 0 ) + ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0) ) + ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0)); + } + foreach ($travelFees as $kf => $vf) { // todo 发生退款或多笔收款 + $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") + ->setTravelFeesMoney($kf, $vf->GAI_SQJE) + ->setTravelFeesNum($kf, 1) + ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE)) + ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) + ->setTravelFeesRemark($kf, $vf->GAI_Memo); + } + var_dump(($this->tldOrderBuilder->getBizContent())); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + /** BIZ_GroupCombineInfo */ +// if (json_decode($resp)->status == 1) { +// log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); +// $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; +// $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; +// $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; +// $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; +// $this->Orders_model->biz_groupcombineinfo_save(); +// } + // email 供应商 todo + echo "Order Push done."; + return; + } + + /*! + * 订单状态变更,调度变更 + * (地接社调用, 并邮件通知外联) + */ + public function order_change() + { + $this->load->model('Order_update'); + $ret['status'] = -1; + $ret['errMsg'] = "未知错误"; + $input = $this->input->post(); + $vendorID = $input['userId']; + $validate = $this->calc_key($vendorID, $input['key']); + if ($validate !== TRUE) { + $ret['errMsg'] = "身份验证失败."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + // $vendorID = 29188;//29188 1343; // test + $vas_info = array(); + if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { + $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); + if (empty($vas_info) && ! empty($input['agcOrderNo'])) { + $real_groupCode = analysis_groupCode($input['agcOrderNo']); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); + } + } elseif ($input['agcName'] == '桂林海纳国旅') { + $real_groupCode = analysis_groupCode($input['agcOrderNo']); + $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID); + } + + if (empty($vas_info)) { + $ret['errMsg'] = "未找到订单."; + } else { + $vendor_manager = $this->Orders_model->get_vendorContact($vendorID); + /** VendorArrangeState */ + $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime']; + $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo; + $update_vas = $this->Order_update->vendorStatus_update($vas_info[0]->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo); + if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { // 传统团的不需要更新订单主表 + /** BIZ_confirmlineinfo */ + $this->Order_update->coli_where_update = " COLI_SN=" . $vas_info[0]->COLI_SN; + $coli_update_column = array( + "COLI_State" => 7 + ); + $update_coli = $this->Order_update->biz_confirmlineinfo_update($coli_update_column); + } + if ($update_vas === TRUE) { + $ret['status'] = 1; + $ret['errMsg'] = ""; + } + } + if ($ret['status'] !== 1) { + log_message('error','图兰朵确认上报失败. POST RAW: ' . raw_json_encode($input) . "; Result: " . raw_json_encode($ret)); + } + $sender_name = "中华游供应商合作平台"; + $sender_mail = "info@chinahighlights.net"; + $from_name = $vendor_manager->LMI2_Name; + $from_mail = $vendor_manager->LMI_ListMail; + $to_name = $vas_info[0]->OPI_Name; + $to_mail = $vas_info[0]->OPI_Email; + $subject = $input['agcOrderNo'] . "团已确认: " . $vendor_manager->VEI2_CompanyBN; + $mail_body = $vendor_manager->VEI2_CompanyBN . "对团" . $input['agcOrderNo'] . "的计划在" . $input['orderTime'] . "已确认。\r\n"; + $mail_body .= "确认说明:" . $input['orderRemark'] . "\r\n"; + $mail_body .= "确认人:$vendor_manager->LMI2_Name $vendor_manager->LMI_ListMail 固定电话: $vendor_manager->LMI_Telephone 移动电话:$vendor_manager->LMI_Mobile\r\n"; + $mail_body .= "变更内容: " . $vas_info[0]->VAS_ChangeText . "\r\n"; + $this->Orders_model->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name); + + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + + + protected function excute_curl($url, $content_builder) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Accept: application/json" + )); + + $params_str = $content_builder->getBizContent(); + $postBody = array('jsonParams' => $params_str, "notHander" => 1); + + if (is_string($params_str) && 0 < mb_strlen($params_str)) { + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); + } + + $reponse = curl_exec($ch); + $eval_resp = json_decode($reponse); + + if (curl_errno($ch) || $eval_resp->status == 0) { + log_message('error', "curl error code: ".curl_error($ch) . $eval_resp->errMsg . "; curl postBodyString: ".json_encode($postBody)); + } else { + $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (200 !== $httpStatusCode) { + log_message('error', "Request html Status Code: ".$httpStatusCode."; curl postBodyString: ".json_encode($postBody)); + } + } + curl_close($ch); + return $reponse; + } + + public function pag_no_tmp($routeName='') + { + return array( + "故宫深度一日游(目的地)" => "BJSIC-44" + ,"故宫深度游拼团(目的地)" => "BJSIC-44" + ,"北京精品一日游(目的地)" => "BJSIC-41" + ,"北京精品一日游(PVT)(目的地)" => "BJSIC-41" + ,"北京精品两日游(目的地)" => "BJSIC-42" + ,"北京精品两日游(PVT)(目的地)" => "BJSIC-42" + ,"北京精品三日游(目的地)" => "BJSIC-43" + ,"北京精品游D2(目的地)" => "BJSIC-42" + ,"北京精品游D3(目的地)" => "BJSIC-43" + ,"北京单租车服务(目的地)" => "BJALC-209" + ,"北京单租车接送(常规)" => "BJALC-209" + ,"北京单租车接送服务(目的地)" => "BJALC-209" + ,"北京市内-天津新港大车接送(目的地)" => "BJSIC-16" + ,"天津新港-北京市内大车接送(目的地)" => "BJSIC-16" + ,"箭扣-慕田峪徒步一日游(目的地)" => "BJSIC-45" + ,"箭扣-慕田峪徒步一日游(PVT)(目的地)" => "BJSIC-45" + ,"箭扣-慕田峪长城徒步拼团(目的地)" => "BJSIC-45" + ,"司马台西-金山岭徒步一日游(目的地)" => "BJSIC-46" + ,"司马台西-金山岭徒步一日游(PVT)(目的地)" => "BJSIC-46" + ,"司马台西-金山岭长城徒步拼团(目的地)" => "BJSIC-46" + ,"慕田峪半日游拼团(目的地)" => "BJSIC-47" + ,"慕田峪半日游PVT(目的地)" => "BJSIC-47" + ,"古北口长城徒步一日游(目的地)" => "BJSIC-48" + ,"古北口(目的地)" => "BJSIC-48" + ,"半日游广场故宫拼团(目的地)" => "BJSIC-41" + // ,=> + ,"西安精品一日游(目的地)" => "XASIC-41" + ,"西安精品一日游PVT(目的地)" => "XASIC-41" + ,"西安市内精品一日游(目的地)" => "XASIC-41" + ,"西安精品两日游(目的地)" => "XASIC-42" + ,"西安单租车服务(目的地)" => "XASIC-17" + ,"西安单租车接送服务(目的地)" => "XASIC-17" + ,"西安单租车接送服务" => "XASIC-17" + ,"西安兵马俑精品一日游(目的地)" => "XASIC-41" + ,"西安兵马俑精华一日游(目的地)" => "XASIC-41" + ,"西安兵马俑精品半日游(目的地)" => "XASIC-15" + ,"西安兵马俑精品半日游PVT(目的地)" => "XASIC-15" + ,"西安汉阳陵市内精品一日游(目的地)" => "XASIC-42" + // ,=> + ,"上海精品一日游(目的地)" => "SHSIC-41" + ,"上海精品游PVT线路(目的地)" => "SHSIC-41" + ,"上海市内精品一日游(目的地)" => "SHSIC-42" + ,"周庄锦溪精品一日游(目的地)" => "SHSIC-43" + ,"苏州精品一日游(目的地)" => "SHSIC-44" + ,"上海单租车(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" + ,"上海单租车接送服务(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" + ); + } + + public function calc_key($userId, $key) + { + $default = "b825e39422a54875a95752fc7ed6f5d2"; + $ret = md5(hash("sha256", $userId.$default)); + return $ret===$key; + } + +} diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php new file mode 100644 index 00000000..e189575c --- /dev/null +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -0,0 +1,14 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Index extends CI_Controller { + + public function index() + { + echo "string"; + } + +} + +/* End of file index.php */ +/* Location: ./third_party/vendorPlanSync/controllers/index.php */ diff --git a/webht/third_party/vendorPlanSync/helpers/array_helper.php b/webht/third_party/vendorPlanSync/helpers/array_helper.php new file mode 100644 index 00000000..f66c6d2b --- /dev/null +++ b/webht/third_party/vendorPlanSync/helpers/array_helper.php @@ -0,0 +1,167 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +function array_unique_fb($array2D) +{ + foreach ($array2D as $v) + { + $v = join(",",$v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串 + $temp[] = $v; + } + $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组 + foreach ($temp as $k => $v) + { + $temp[$k] = explode(",",$v); //再将拆开的数组重新组装 + } + return $temp; +} + +function my_array_unique($array, $keep_key_assoc = false) +{ + $duplicate_keys = array(); + $tmp = array(); + + foreach ($array as $key=>$val) + { + // convert objects to arrays, in_array() does not support objects + if (is_object($val)) + $val = (array)$val; + + if (!in_array($val, $tmp)) + $tmp[] = $val; + else + $duplicate_keys[] = $key; + } + + foreach ($duplicate_keys as $key) + unset($array[$key]); + + return $keep_key_assoc ? $array : array_values($array); +} + +//根据URL获取月份 +function getaqiMonth($url){ + $monArr = array('January','February','March','April','May','June','July','August','September','October','November','December'); + $monObj = array( + 'January' => '01', + 'February' => '02', + 'March' => '03', + 'April' => '04', + 'May' => '05' , + 'June' => '06', + 'July' => '07', + 'August' => '08', + 'September' => '09', + 'October' => '10', + 'November' => '11', + 'December' => '12'); + $urlarr = explode("/",$url); + $tmp = $urlarr[(count($urlarr)-1)]; + $tmp = ucfirst(str_ireplace('.htm','',$tmp)); + //$d=strtotime("00:01am ".$tmp." 15 2015"); + if(in_array($tmp,$monArr)){ + return $monObj[$tmp]; + }else{ + return false; + } +} +/* + * 把数组元素组合为字符串 + * $container:用来包含元素的符号 + * $se:分隔符 + * $arr:需要重新组合的数组 + * 例如:$arr=['aaaa','bbbb']; + * my_implode("'",",",$arr);得到 + * 'aaaa','bbbb' + */ +function my_implode($container,$se,$arr) +{ + $str = ""; + if ($arr != '') { + $str = ""; + $tcount = count($arr); + $tcountInt = 0; + foreach ($arr as $i) { + $tcountInt++; + if ($tcount == $tcountInt) { + $str .= $container . $i . $container; + } else { + $str .= $container . $i . $container . $se; + } + } + } + return $str; +} +/*! + * json_encode($a, JSON_UNESCAPED_UNICODE ) + * for PHP Version < 5.4 + */ +function raw_json_encode($input, $flags = 0) { + $fails = implode('|', array_filter(array( + '\\\\', + $flags & JSON_HEX_TAG ? 'u003[CE]' : '', + $flags & JSON_HEX_AMP ? 'u0026' : '', + $flags & JSON_HEX_APOS ? 'u0027' : '', + $flags & JSON_HEX_QUOT ? 'u0022' : '', + ))); + $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/"; + $callback = function ($m) { + return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8'); + }; + return preg_replace_callback($pattern, $callback, json_encode($input, $flags)); +} +/*! + * 目的地项目组的订单计划的团号分析 + * 去除添加的后缀, 只保留前两部分: XXXXXX-YYYYYYYYYYYY + * @date 2018-05-02 + * @param [type] $groupCode 从地接系统获取到的团号 + */ +function analysis_groupCode($groupCode) +{ + mb_regex_encoding("UTF-8"); + $groupCode = trim_str(trim($groupCode)); + preg_match('/[\w\s\-]+/', characet($groupCode, "UTF-8"), $temp_array); + // $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; + if (empty($temp_array)) { + return trim_str(trim($groupCode)); + } + $tmp_groupCode = explode("-", trim($temp_array[0])); + $real_groupCode = $tmp_groupCode[0]; + if (isset($tmp_groupCode[1])) { + $real_groupCode .= "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + } + for ($i=2; $i < count($tmp_groupCode); $i++) { + if (strlen($tmp_groupCode[$i]) > 4) { + $real_groupCode .= "-"; + $real_groupCode .= mb_strstr($tmp_groupCode[$i], "(", true)!==false ? mb_strstr($tmp_groupCode[$i], "(", true) : $tmp_groupCode[$i]; + } + } + $real_groupCode = trim_str(trim($real_groupCode)); + return $real_groupCode; +} +function trim_str($groupCode) +{ + return mb_ereg_replace('( | | )', '', $groupCode); +} +/*! + * 转换字符集编码 + * @param $data + * @param $targetCharset + * @return string + */ +function characet($data, $targetCharset) { + if (!empty($data)) { + $fileType = "UTF-8"; + if (strcasecmp($fileType, $targetCharset) != 0) { + $data = mb_convert_encoding($data, $targetCharset, $fileType); + // $data = iconv($fileType, $targetCharset.'//IGNORE', $data); + } + } + return $data; +} + +function real_phone_number($phone, $nation_code) +{ + $nation_str = "+" . $nation_code; + $cut_nation = str_replace($nation_str, "", $phone); + return mb_ereg_replace('[\D]', '', $cut_nation); +} diff --git a/webht/third_party/vendorPlanSync/helpers/index.html b/webht/third_party/vendorPlanSync/helpers/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/vendorPlanSync/helpers/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/index.html b/webht/third_party/vendorPlanSync/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/vendorPlanSync/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/libraries/index.html b/webht/third_party/vendorPlanSync/libraries/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/vendorPlanSync/libraries/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php new file mode 100644 index 00000000..66f28198 --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php @@ -0,0 +1,334 @@ +<?php + + +class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model +{ + + private $userId; + private $Key; + + private $bizContentarr = array(); + private $bizContent = NULL; + + private $orderData=array(); + private $orderId; //”Integer”//订单ID,不为空代表修改 + private $modifyLogInfo; //”String”//修改的日志记录信息.如果是修改订单的状态,这里传输修改简报 + private $orderType; //”Integer” //订单类型 1=独立成团,2=散客团 + private $routeName; //”String”//行程名称 + private $routeType; //”String”//线路类型 + private $agcOrderNo; //”String”//组团社团号,团号格式 yyyy-mm-dd-cc(**)后面中括号号的对应团号的其他表达信息 + private $adultNum; //”Integer”//大人数量 + private $childNum; //”Integer”//小孩数量 + private $guiderNum; //”Integer”//领队数量 + private $guiderInfo; //”String”//领队信息 + private $toTraffic; //”String”//抵达交通 + private $backTraffic; //”String”//返回交通 + private $roomStandard; //”String”//用房标准 + private $orderRemark; //”String”//订单备注 + private $routeStandard; //”String”//行程接待标准 + private $destination; //”目的地名称”//目的地城市名称 + private $travelDate; //”String”//出游时间yyyy-mm-dd + private $leavedDate; //”String”//离团时间 yyyy-mm-dd + + // private $orderData['travelFees']=array(); //团款明细 + // [{ + // type:”String”//团款类型 + // money:”Double”//单价 + // num:”Double”//数量 + // unit:”Double”//单位 + // sumMoney:”Double//总金额” + // remark:”String”//备注 + // }] + // private $orderData['replaceCollections']=array(); //代收明细 + // [{ + // type:“String”//代收类型 + // money:”Double”//金额 + // remark:”String”//备注 + // }] + // private $orderData['replacePays']=array(); //代付明细 + // [{ + // type:“String”//代付类型 + // money:”Double”//金额 + // remark:”String”//备注 + // }] + // private $orderData['scheduleDetails']=array(); //行程详细,数组类型,按照第一天往后有序排列 + // [{ + // title:”String”//行程标题 + // content:”String”//行程内容 + // traffic:”String”//交通号 + // accommodation:”String”//住宿 + // breakFirst:”Integer”//是否包含早餐 【1=包含 0=不含】 + // dinner:”Integer”//是否包含中餐 【1=包含 0=不含】 + // lunch:”Integer”//是否包含晚餐 【1=包含 0=不含】 + // }] + // private $orderData['customers']=array(); //游客信息 + // [{ + // name:”String”//名字 + // peopleType:”String”//类型 【成人,小孩,婴儿,老人,学生…】 + // document Type:”String”//证件类型【护照,身份证,户口,驾驶证….】 + // documentNo:”String”//证件号 + // phoneNo:”String”//手机号 + // otherInfo:”String”//其他信息 + // }] + + function __construct() { + parent::__construct(); + $this->orderData['travelFees'] = array(); //团款明细 + $this->orderData['replaceCollections'] = array(); //代收明细 + $this->orderData['replacePays'] = array(); //代付明细 + $this->orderData['scheduleDetails'] = array(); //行程详细,数组类型,按照第一天往后有序排列 + $this->orderData['customers'] = array(); //游客信息 + } + + public function getBizContent() + { + if(!empty($this->orderData)){ + $this->bizContentarr['orderData'] = $this->orderData; + $this->bizContent = json_encode($this->bizContentarr); + } + return $this->bizContent; + } + + public function setUserId($userId) + { + $this->userId = $userId; + $this->bizContentarr['userId'] = $userId; + return $this; + } + public function setKey($Key) + { + $this->key = $Key; + $this->bizContentarr['key'] = $Key; + return $this; + } + /** 订单基本信息 */ + public function setOrderId($orderId) + { + $this->orderData['orderId'] = $orderId; + return $this; + } + public function setModifyLogInfo($modifyLogInfo) + { + $this->orderData['modifyLogInfo'] = $modifyLogInfo; + return $this; + } + public function setOrderType($orderType) + { + $this->orderData['orderType'] = $orderType; + return $this; + } + public function setRouteName($routeName) + { + $this->orderData['routeName'] = $routeName; + return $this; + } + public function setRouteType($routeType) + { + $this->orderData['routeType'] = $routeType; + return $this; + } + public function setAgcOrderNo($agcOrderNo) + { + $this->orderData['agcOrderNo'] = $agcOrderNo; + return $this; + } + public function setAdultNum($adultNum) + { + $this->orderData['adultNum'] = $adultNum; + return $this; + } + public function setChildNum($childNum) + { + $this->orderData['childNum'] = $childNum; + return $this; + } + public function setGuiderNum($guiderNum) + { + $this->orderData['guiderNum'] = $guiderNum; + return $this; + } + public function setGuiderInfo($guiderInfo) + { + $this->orderData['guiderInfo'] = $guiderInfo; + return $this; + } + public function setToTraffic($toTraffic) + { + $this->orderData['toTraffic'] = $toTraffic; + return $this; + } + public function setBackTraffic($backTraffic) + { + $this->orderData['backTraffic'] = $backTraffic; + return $this; + } + public function setRoomStandard($roomStandard) + { + $this->orderData['roomStandard'] = $roomStandard; + return $this; + } + public function setOrderRemark($orderRemark) + { + $this->orderData['orderRemark'] = $orderRemark; + return $this; + } + public function setRouteStandard($routeStandard) + { + $this->orderData['routeStandard'] = $routeStandard; + return $this; + } + public function setDestination($destination) + { + $this->orderData['destination'] = $destination; + return $this; + } + public function setTravelDate($travelDate) + { + $this->orderData['travelDate'] = $travelDate; + return $this; + } + public function setLeavedDate($leavedDate) + { + $this->orderData['leavedDate'] = $leavedDate; + return $this; + } + + /** 团款数组 */ + public function setTravelFeesType($index, $type) + { + $this->orderData['travelFees'][$index]['type'] = $type; + return $this; + } + public function setTravelFeesMoney($index, $money) + { + $this->orderData['travelFees'][$index]['money'] = $money; + return $this; + } + public function setTravelFeesNum($index, $num) + { + $this->orderData['travelFees'][$index]['num'] = $num; + return $this; + } + public function setTravelFeesUnit($index, $unit) + { + $this->orderData['travelFees'][$index]['unit'] = $unit; + return $this; + } + public function setTravelFeesSumMoney($index, $sumMoney) + { + $this->orderData['travelFees'][$index]['sumMoney'] = $sumMoney; + return $this; + } + public function setTravelFeesRemark($index, $remark) + { + $this->orderData['travelFees'][$index]['remark'] = $remark; + return $this; + } + + /** 代付数组 */ + public function setReplacePaysType($index, $type) + { + $this->orderData['replacePays'][$index]['type'] = $type; + return $this; + } + public function setReplacePaysMoney($index, $money) + { + $this->orderData['replacePays'][$index]['money'] = $money; + return $this; + } + public function setReplacePaysRemark($index, $remark) + { + $this->orderData['replacePays'][$index]['remark'] = $remark; + return $this; + } + + /** 代收数组 */ + public function setReplaceCollectionsType($index, $type) + { + $this->orderData['replaceCollections'][$index]['type'] = $type; + return $this; + } + public function setReplaceCollectionsMoney($index, $money) + { + $this->orderData['replaceCollections'][$index]['money'] = $money; + return $this; + } + public function setReplaceCollectionsRemark($index, $remark) + { + $this->orderData['replaceCollections'][$index]['remark'] = $remark; + return $this; + } + + /** 行程详细数组 */ + public function setScheduleDetailsTitle($index, $title) + { + $this->orderData['scheduleDetails'][$index]['title'] = $title; + return $this; + } + public function setScheduleDetailsContent($index, $content) + { + $this->orderData['scheduleDetails'][$index]['content'] = $content; + return $this; + } + public function setScheduleDetailsTraffic($index, $traffic) + { + $this->orderData['scheduleDetails'][$index]['traffic'] = $traffic; + return $this; + } + public function setScheduleDetailsAccommodation($index, $accommodation) + { + $this->orderData['scheduleDetails'][$index]['accommodation'] = $accommodation; + return $this; + } + public function setScheduleDetailsBreakFirst($index, $breakFirst) + { + $this->orderData['scheduleDetails'][$index]['breakFirst'] = $breakFirst; + return $this; + } + public function setScheduleDetailsDinner($index, $dinner) + { + $this->orderData['scheduleDetails'][$index]['dinner'] = $dinner; + return $this; + } + public function setScheduleDetailsLunch($index, $lunch) + { + $this->orderData['scheduleDetails'][$index]['lunch'] = $lunch; + return $this; + } + + /** 游客信息数组 */ + public function setCustomersName($index, $name) + { + $this->orderData['customers'][$index]['name'] = $name; + return $this; + } + public function setCustomersPeopleType($index, $peopleType) + { + $this->orderData['customers'][$index]['peopleType'] = $peopleType; + return $this; + } + public function setCustomersDocumentType($index, $documentType) + { + $this->orderData['customers'][$index]['documentType'] = $documentType; + return $this; + } + public function setCustomersDocumentNo($index, $documentNo) + { + $this->orderData['customers'][$index]['documentNo'] = $documentNo; + return $this; + } + public function setCustomersPhoneNo($index, $phoneNo) + { + $this->orderData['customers'][$index]['phoneNo'] = $phoneNo; + return $this; + } + public function setCustomersOtherInfo($index, $otherInfo) + { + $this->orderData['customers'][$index]['otherInfo'] = $otherInfo; + return $this; + } + + +} + +?> diff --git a/webht/third_party/vendorPlanSync/models/TuLanDuo_queryContentBuilder.php b/webht/third_party/vendorPlanSync/models/TuLanDuo_queryContentBuilder.php new file mode 100644 index 00000000..22ea575e --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/TuLanDuo_queryContentBuilder.php @@ -0,0 +1,142 @@ +<?php +/*! + * 图兰朵系统对接: + * 查询接口业务参数 + * @author LYT <lyt@hainatravel.com> + * @date 2018-03-31 + */ +class TuLanDuo_queryContentBuilder extends CI_Model +{ + private $userId; + private $Key; + + private $pageSize=20; //”Integer”//每页数量 每页最多返回50行 + private $pageIndex=1; //”Integer”//页码。第几页数据 + private $orderType; //”Integer”//订单类型,1=独立成团,2=散客团 【精准查询】 + private $orderStatus; //”Integer”//订单状态 1=已确认,0=待确认 + private $startTravelDate; //”String”//当前出游时间之后 【精准查询】 + private $endTravelDate; //”String”//当前出游时间之前 【精准查询】 + private $startOrderDate; //”String”//当前预定时间之后 【精准查询】 + private $endOrderDate; //”String”//当前预定时间之前 【精准查询】 + private $agcOrderNo; //”String”//组团社团号 【模糊查询】 + private $adultNum; //”Integer”//大人数量 【精准查询】 + private $childNum; //”Integer”//小孩数量 【精准查询】 + private $customerName; //”String”//订单游客名单 【模糊查询】 + private $routeName; //”String”//行程名称 。 【模糊查询】 + private $operationDep; //”String”//操作部门 , 【精准查询】 + + private $orderId; //”Integer”//订单ID + + private $bizContentarr = array(); + + private $bizContent = NULL; + + public function getBizContent() + { + if(!empty($this->bizContentarr)){ + $this->bizContent = json_encode($this->bizContentarr); + } + return $this->bizContent; + } + + public function setUserId($userId) + { + $this->userId = $userId; + $this->bizContentarr['userId'] = $userId; + return $this; + } + public function setKey($Key) + { + $this->key = $Key; + $this->bizContentarr['key'] = $Key; + return $this; + } + + public function getPageSize() + { + return $this->pageSize; + } + public function setPageSize($pageSize) + { + $this->pageSize = $pageSize; + $this->bizContentarr['pageSize'] = $pageSize; + return $this; + } + public function getPageIndex() + { + return $this->pageIndex; + } + public function setPageIndex($pageIndex) + { + $this->pageIndex = $pageIndex; + $this->bizContentarr['pageIndex'] = $pageIndex; + return $this; + } + + public function getStartTravelDate() + { + return $this->startTravelDate; + } + public function setStartTravelDate($startTravelDate) + { + $this->startTravelDate = $startTravelDate; + $this->bizContentarr['startTravelDate'] = $startTravelDate; + return $this; + } + public function getEndTravelDate() + { + return $this->endTravelDate; + } + public function setEndTravelDate($endTravelDate) + { + $this->endTravelDate = $endTravelDate; + $this->bizContentarr['endTravelDate'] = $endTravelDate; + return $this; + } + + public function getStartOrderDate() + { + return $this->startOrderDate; + } + public function setStartOrderDate($startOrderDate) + { + $this->startOrderDate = $startOrderDate; + $this->bizContentarr['startOrderDate'] = $startOrderDate; + return $this; + } + public function getEndOrderDate() + { + return $this->endOrderDate; + } + public function setEndOrderDate($endOrderDate) + { + $this->endOrderDate = $endOrderDate; + $this->bizContentarr['endOrderDate'] = $endOrderDate; + return $this; + } + + public function getOrderId() + { + return $this->orderId; + } + public function setOrderId($orderId) + { + $this->orderId = $orderId; + $this->bizContentarr['orderId'] = $orderId; + return $this; + } + + public function getAgcOrderNo() + { + return $this->agcOrderNo; + } + public function setAgcOrderNo($agcOrderNo) + { + $this->agcOrderNo = $agcOrderNo; + $this->bizContentarr['agcOrderNo'] = $agcOrderNo; + return $this; + } + // 其他还没用到先不写了... +} + +?> diff --git a/webht/third_party/vendorPlanSync/models/index.html b/webht/third_party/vendorPlanSync/models/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/views/index.html b/webht/third_party/vendorPlanSync/views/index.html new file mode 100644 index 00000000..c942a79c --- /dev/null +++ b/webht/third_party/vendorPlanSync/views/index.html @@ -0,0 +1,10 @@ +<html> +<head> + <title>403 Forbidden</title> +</head> +<body> + +<p>Directory access is forbidden.</p> + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/vendorPlanSync/views/welcome_message.php b/webht/third_party/vendorPlanSync/views/welcome_message.php new file mode 100644 index 00000000..0bf5a8d2 --- /dev/null +++ b/webht/third_party/vendorPlanSync/views/welcome_message.php @@ -0,0 +1,88 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <title>Welcome to CodeIgniter</title> + + <style type="text/css"> + + ::selection{ background-color: #E13300; color: white; } + ::moz-selection{ background-color: #E13300; color: white; } + ::webkit-selection{ background-color: #E13300; color: white; } + + body { + background-color: #fff; + margin: 40px; + font: 13px/20px normal Helvetica, Arial, sans-serif; + color: #4F5155; + } + + a { + color: #003399; + background-color: transparent; + font-weight: normal; + } + + h1 { + color: #444; + background-color: transparent; + border-bottom: 1px solid #D0D0D0; + font-size: 19px; + font-weight: normal; + margin: 0 0 14px 0; + padding: 14px 15px 10px 15px; + } + + code { + font-family: Consolas, Monaco, Courier New, Courier, monospace; + font-size: 12px; + background-color: #f9f9f9; + border: 1px solid #D0D0D0; + color: #002166; + display: block; + margin: 14px 0 14px 0; + padding: 12px 10px 12px 10px; + } + + #body{ + margin: 0 15px 0 15px; + } + + p.footer{ + text-align: right; + font-size: 11px; + border-top: 1px solid #D0D0D0; + line-height: 32px; + padding: 0 10px 0 10px; + margin: 20px 0 0 0; + } + + #container{ + margin: 10px; + border: 1px solid #D0D0D0; + -webkit-box-shadow: 0 0 8px #D0D0D0; + } + </style> +</head> +<body> + +<div id="container"> + <h1>Welcome to CodeIgniter!</h1> + + <div id="body"> + <p>The page you are looking at is being generated dynamically by CodeIgniter.</p> + + <p>If you would like to edit this page you'll find it located at:</p> + <code>application/views/welcome_message.php</code> + + <p>The corresponding controller for this page is found at:</p> + <code>application/controllers/welcome.php</code> + + <p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p> + </div> + + <p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p> +</div> + +</body> +</html> \ No newline at end of file From 439de397311aacc80b021d08e8ec3c21868290d9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 11 Oct 2018 16:12:53 +0800 Subject: [PATCH 159/382] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=97=A5=E5=BF=97:?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0=E8=8E=B7=E5=8F=96=E5=8E=86=E5=8F=B2?= =?UTF-8?q?=E6=95=B0=E6=8D=AE[=E5=88=97=E8=A1=A8=E5=B7=B2=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E5=AE=8C=E6=AF=95];=20=E5=A2=9E=E5=8A=A0=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E5=8E=86=E5=8F=B2=E6=95=B0=E6=8D=AE=E7=9A=84=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E8=AF=A6=E6=83=85;=20=E4=BF=AE=E6=94=B9=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E6=97=B6=E9=97=B4=E7=9A=84=E8=A7=84=E5=88=99,=20?= =?UTF-8?q?=E6=AF=8F=E6=AC=A1=E4=BB=85=E5=90=8C=E6=AD=A5=E4=B8=80=E6=9D=A1?= =?UTF-8?q?;=20=E8=A1=A5=E5=85=85=E7=BC=BA=E5=B0=91=E7=9A=84=E4=BA=A7?= =?UTF-8?q?=E5=93=81=E7=BC=96=E5=8F=B7;=20=E5=AE=8C=E5=96=84tracking?= =?UTF-8?q?=E9=93=BE=E6=8E=A5=E6=95=B0=E6=8D=AE;=20=E8=B4=A2=E5=8A=A1?= =?UTF-8?q?=E8=A1=A8=E8=AE=A1=E7=AE=97:=E5=A2=9E=E5=8A=A0=E9=9D=9E?= =?UTF-8?q?=E5=B8=B8=E8=A7=84=E6=8B=BC=E5=9B=A2=E7=9A=84=E8=AE=A1=E7=AE=97?= =?UTF-8?q?;=E8=A7=A3=E5=86=B3=E4=B8=80=E4=B8=AA=E4=BA=A7=E5=93=81?= =?UTF-8?q?=E6=8B=BC=E5=A4=9A=E4=B8=AA=E5=9B=A2=E9=97=AE=E9=A2=98;?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=B7=B2=E4=B8=8B=E6=9E=B6=E4=BA=A7=E5=93=81?= =?UTF-8?q?=E8=AE=A1=E7=AE=97;=20=E5=A2=9E=E5=8A=A0=E7=9F=AD=E4=BF=A1?= =?UTF-8?q?=E9=80=9A=E7=9F=A5;=E7=9F=AD=E4=BF=A1=E5=8F=91=E9=80=81?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E6=9F=A5=E8=AF=A2;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 117 +++++---- .../trippestOrderSync/controllers/api.php | 16 +- .../controllers/order_finance.php | 16 +- .../controllers/send_operation.php | 174 +++++++++++++ .../helpers/array_helper.php | 18 +- .../models/orderFinance_model.php | 24 +- .../trippestOrderSync/models/orders_model.php | 32 +-- .../trippestOrderSync/models/orders_query.php | 3 +- .../models/send_operation_model.php | 135 ++++++++++ .../models/tulanduo_sync_model.php | 18 +- .../views/order_sms_list.php | 25 ++ .../trippestOrderSync/views/sms_log.php | 242 ++++++++++++++++++ 12 files changed, 736 insertions(+), 84 deletions(-) create mode 100644 webht/third_party/trippestOrderSync/controllers/send_operation.php create mode 100644 webht/third_party/trippestOrderSync/models/send_operation_model.php create mode 100644 webht/third_party/trippestOrderSync/views/order_sms_list.php create mode 100644 webht/third_party/trippestOrderSync/views/sms_log.php diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 72b382f1..b2054ddf 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -134,7 +134,7 @@ class TulanduoApi extends CI_Controller $unique_order[] = $vo['orderId']; // paypal 手续费订单没有团号 $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo']; - $vo['agcOrderNo'] = trim_groupCode(trim($vo['agcOrderNo'])); // 去掉中文的全角空格 + $vo['agcOrderNo'] = (trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $this->Orders_model->BIZ_COLI_SN = null; $this->Orders_model->GRI_SN = null; @@ -191,12 +191,16 @@ class TulanduoApi extends CI_Controller } else { // $startDate = ('2018-04-21'); // $endDate = ('2018-04-22'); // test - $startDate = date('Y-m-d', strtotime("-4 days")); + $startDate = date('Y-m-d'); $endDate = date('Y-m-d', strtotime("+2 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate); } + if (empty($to_update_list)) { + return false; + } $unique_orderGroupCombine = array(); // 录入拼团调度时,避免重复 $order = $to_update_list[0]; + log_message('error','vendorID ' . $order->GCI_VendorOrderId); $this->tld_order->setOrderId($order->GCI_VendorOrderId) ->setUserId($this->userId) ->setKey($this->key); @@ -216,7 +220,14 @@ class TulanduoApi extends CI_Controller } return; } - $detail_jsonResp->orderDetail->agcOrderNo = trim_groupCode(trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格 + if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo!="") { + } else { + $detail_jsonResp->orderDetail->agcOrderNo = $detail_jsonResp->orderDetail->groupOrderNo; + } + if (isset($detail_jsonResp->orderDetail->groupOrderNo)) { + $detail_jsonResp->orderDetail->groupOrderNo = (trim($detail_jsonResp->orderDetail->groupOrderNo)); + } + $detail_jsonResp->orderDetail->agcOrderNo = (trim($detail_jsonResp->orderDetail->agcOrderNo)); // 去掉中文的全角空格 // 目的地的团已经主动取消, 只有其他渠道的团需要更新状态 if (mb_strstr($detail_jsonResp->orderDetail->agcOrderNo, "取消") !== false) { $this->plan_cancel($order->GCI_VendorOrderId); @@ -256,12 +267,12 @@ class TulanduoApi extends CI_Controller if (intval($order->COLI_OPI_ID) === 435 || $order->COLI_ID === null || empty($getInfo_byGroupCodeArr)) { if ( empty($getInfo_byGroupCodeArr)){ $getInfo_byGroupCode = null; // 没有该团号的团信息 - } elseif (strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 + } elseif ($order->COLI_ID !== null && strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0]; // 渠道和目的地有重复操作的团 $duplicate = true; } else { foreach ($getInfo_byGroupCodeArr as $kg => $vg) { - if ($vg->GRI_No === mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49)) { + if ($vg->GRI_No === substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49)) { // 地接拆分的团号,需要全部匹配; 否则为没有团信息 $getInfo_byGroupCode = $vg; break; @@ -287,13 +298,14 @@ class TulanduoApi extends CI_Controller $cold_sn = $this->insert_cold($order_detail_arr); } $groupSN = isset($groupSN) ? $groupSN : $getInfo_byGroupCode->GRI_SN; - $coli_sn = isset($coli_sn) ? $coli_sn : $getInfo_byGroupCode->COLI_SN; + $coli_sn = isset($coli_sn)&&intval($coli_sn)!==0 ? $coli_sn : $getInfo_byGroupCode->COLI_SN; $coli_id = isset($coli_id) ? $coli_id : $getInfo_byGroupCode->COLI_ID; $cold_sn = isset($cold_sn) ? $cold_sn : $getInfo_byGroupCode->COLD_SN; $coli_opi_id = 435; $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : ""; - $coli_state = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_State : 9; + $coli_state = 9; $coli_orderdetailtext = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; + $cold_memotext = isset($cold_sn) ? $this->Orders_model->COLD_MemoText : $getInfo_byGroupCode->COLD_MemoText; } else { // 已找到的目的地发的计划 // $getInfo_byGroupCode = $order; @@ -306,6 +318,7 @@ class TulanduoApi extends CI_Controller $cold_sn = $order->COLD_SN; // ???多个子订单 !!!仅用于435创建的订单的更新, 因此仅一个 $coli_opi_id = $order->COLI_OPI_ID; $coli_orderdetailtext = $order->COLI_OrderDetailText; + $cold_memotext = $order->COLD_MemoText; } /** UPDATE */ // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 @@ -358,31 +371,37 @@ class TulanduoApi extends CI_Controller $coli_update_column["COLI_State"] = $coli_state; $coli_update_column["COLI_Price"] = $travel_fee; $coli_update_column["COLI_CUrrency"] = $travel_fee_currency; - $coli_update_column["COLI_GroupCode"] = mb_substr($detail_jsonResp->orderDetail->agcOrderNo, 0, 49); + $coli_update_column["COLI_GroupCode"] = substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49); } $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** * update BIZ_ConfirmLineDetail * insert BIZ_BookPeople,BIZ_PackageOrderInfo */ + /** BIZ_ConfirmLineDetail */ + $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); + $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic)); + $new_memotext = trim($cold_memotext)===""||(json_decode($cold_memotext)!==null&&!is_numeric(json_decode($cold_memotext))) ? $COLD_MemoText : $cold_memotext; + $cold_update_column = array( + "COLD_MemoText" => $new_memotext + ); + if (intval($coli_opi_id)===435) { + $cold_update_column['COLD_MemoText'] = $COLD_MemoText; + $cold_update_column['COLD_PersonNum'] = $detail_jsonResp->orderDetail->adultNum; + $cold_update_column["COLD_ChildNum"] = $detail_jsonResp->orderDetail->childNum; + $cold_update_column["COLD_ServiceSN"] = $pag_info->serviceinfo->PAG2_PAG_SN; + $cold_update_column["COLD_ServiceSN2"] = $pag_info->pag_sub; + $cold_update_column["COLD_ServiceCity"] = $pag_info->serviceinfo->PAG_CII_SN; + } + $this->Order_update->cold_where_update = " COLD_SN=" . $cold_sn; + $this->Order_update->biz_confirmlinedetail_update($cold_update_column); if (intval($coli_opi_id) === 435) { - /** BIZ_ConfirmLineDetail */ - $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); - $cold_update_column = array( - "COLD_PersonNum" => $detail_jsonResp->orderDetail->adultNum - ,"COLD_ChildNum" => $detail_jsonResp->orderDetail->childNum - ,"COLD_ServiceSN" => $pag_info->serviceinfo->PAG2_PAG_SN - ,"COLD_ServiceSN2" => $pag_info->pag_sub - ,"COLD_ServiceCity" => $pag_info->serviceinfo->PAG_CII_SN - ); - $this->Order_update->cold_where_update = " COLD_SN=" . $cold_sn; - $this->Order_update->biz_confirmlinedetail_update($cold_update_column); /** INSERT */ /*BIZ_BookPeople*/ if ($this->Orders_model->bookpeople_exist($cold_sn) === array()) { if (isset($detail_jsonResp->orderDetail->customers)) { foreach ($detail_jsonResp->orderDetail->customers as $kd => $vd) { - $this->Orders_model->BPE_FirstName = $vd->name; + $this->Orders_model->BPE_FirstName = substr($vd->name, 0, 40); $this->Orders_model->BPE_GuestType = $vd->peopleType=="成人" ? 1 : 2; $this->Orders_model->BPE_Passport = $vd->documentNo; $bpe_sn[] = $this->Orders_model->biz_book_people_save(); @@ -440,13 +459,7 @@ class TulanduoApi extends CI_Controller } } /*BIZ_GroupCombineOperationDetail*/ - if ( ! isset($detail_jsonResp->orderDetail->groupOrderNo)) { // 没有拼团团号 - continue; - } - if (in_array($detail_jsonResp->orderDetail->groupOrderNo, $unique_orderGroupCombine)) { - continue; - } - $unique_orderGroupCombine[] = $detail_jsonResp->orderDetail->groupOrderNo; + if ( isset($detail_jsonResp->orderDetail->groupOrderNo) ) { // 删除旧的录入 $this->Orders_model->biz_groupcombineoperationdetail_cut($detail_jsonResp->orderDetail->groupOrderNo); // 门票 @@ -501,7 +514,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GCOD_subType = $vco->type; $this->Orders_model->GCOD_title = $vco->name; $this->Orders_model->GCOD_dutyName = $vco->driver; - $this->Orders_model->GCOD_dutyTel = $vco->driverTel; + $this->Orders_model->GCOD_dutyTel = trim_str($vco->driverTel); $this->Orders_model->GCOD_startDate = $vco->startDate; $this->Orders_model->GCOD_endDate = $vco->endDate; $this->Orders_model->GCOD_sumMoney = $vco->sumMoney; @@ -522,7 +535,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GCOD_subType = ""; $this->Orders_model->GCOD_title = ""; $this->Orders_model->GCOD_dutyName = $vgo->name; - $this->Orders_model->GCOD_dutyTel = $vgo->mobelPhone; + $this->Orders_model->GCOD_dutyTel = trim_str($vgo->mobelPhone); $this->Orders_model->GCOD_dutyPhoto = isset($vgo->guiderPhoto) ? $vgo->guiderPhoto : ''; $this->Orders_model->GCOD_startDate = $vgo->startDate; $this->Orders_model->GCOD_endDate = $vgo->endDate; @@ -576,6 +589,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineoperationdetail_save(); } } + } $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id; log_message('error', $output_text); echo $output_text; @@ -589,6 +603,7 @@ class TulanduoApi extends CI_Controller public $date_roll = 0; public function get_history_order_list($oldest_date=null) { + return false; // 已全部结束 // 避免执行超时, 滚动3次之后结束 if ($this->date_roll > 2) { log_message('error', "Got order list from TuLanDuo. Roll end. " . $oldest_date); @@ -603,6 +618,8 @@ class TulanduoApi extends CI_Controller $endTravelDate = $oldest_date; $start_date = $this->input->get_post("start"); $end_date = $this->input->get_post("end"); + // $date_type = "travel"; + // $date_type = isset($this->input->get_post("end")) ? $this->input->get_post("end") : "travel"; $startTravelDate = $start_date ? $start_date : $startTravelDate; $endTravelDate = $end_date ? $end_date : $endTravelDate; $this->tld_order->setUserId($this->userId) @@ -635,6 +652,7 @@ class TulanduoApi extends CI_Controller } $all_vendor_order_id = array_map(function($ele){ return $ele['orderId'];}, $all_list); $all_vendor_order_id_str = implode(',', $all_vendor_order_id); + $exists_ht = $exists_ht_order_id = null; $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str); $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); @@ -647,7 +665,8 @@ class TulanduoApi extends CI_Controller if ( ! in_array($vo['orderId'], $to_insert)) { continue; } - $vo['agcOrderNo'] = trim_groupCode(trim($vo['agcOrderNo'])); // 去掉中文的全角空格 + $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo']; + $vo['agcOrderNo'] = (trim($vo['agcOrderNo'])); // 去掉中文的全角空格 $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; $this->Orders_model->BIZ_COLI_SN = null; $this->Orders_model->GRI_SN = null; @@ -739,9 +758,9 @@ class TulanduoApi extends CI_Controller $travelDate = new DateTime($list_ele['travelDate']); $leaveDate = new DateTime($list_ele['leaveDate']); $date_diff = $travelDate->diff($leaveDate); - $this->Orders_model->GRI_No = mb_substr($list_ele['agcOrderNo'], 0, 49); + $this->Orders_model->GRI_No = substr(trim_str($list_ele['agcOrderNo']), 0, 49); $this->Orders_model->GRI_OrderType = 227002; // 商务 - $this->Orders_model->GRI_Name = mb_substr($list_ele['agcOrderNo'], 0, 49); + $this->Orders_model->GRI_Name = substr(trim_str($list_ele['agcOrderNo']), 0, 49); $this->Orders_model->GRI_PersonNum = $list_ele['adultNum']+$list_ele['childNum']; $this->Orders_model->GRI_Days = intval($date_diff->format('%R%a')+1); $this->Orders_model->GRI_IsCancel = 0; @@ -846,12 +865,13 @@ class TulanduoApi extends CI_Controller /*! * 发送预订计划到地接系统 + * TODO read word into remark * @date 2018-05-02 * @param string $COLI_ID HT系统订单号 */ public function order_push($COLI_ID="") // test { - exit(); + // exit(); /** 目的地 test */ $this->userId = "358"; $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; @@ -883,7 +903,7 @@ class TulanduoApi extends CI_Controller ->setDestination($scheduleDetails[0]->CII2_Name) ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)) - ->setOrderRemark($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText); // todo 抵离交通 + ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)); // todo 抵离交通 foreach ($guestlist as $key => $vg) { $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) @@ -907,16 +927,17 @@ class TulanduoApi extends CI_Controller ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) ->setTravelFeesRemark($kf, $vf->GAI_Memo); } - $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + var_dump(($this->tldOrderBuilder->getBizContent())); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); /** BIZ_GroupCombineInfo */ - if (json_decode($resp)->status == 1) { -log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); - $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; - $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; - $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; - $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; - $this->Orders_model->biz_groupcombineinfo_save(); - } +// if (json_decode($resp)->status == 1) { +// log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); +// $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; +// $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; +// $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; +// $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; +// $this->Orders_model->biz_groupcombineinfo_save(); +// } // email 供应商 todo echo "Order Push done."; return; @@ -1066,9 +1087,12 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"北京精品游D2(目的地)" => "BJSIC-42" ,"北京精品游D3(目的地)" => "BJSIC-43" ,"北京单租车服务(目的地)" => "BJALC-209" + ,"北京单租车接送(常规)" => "BJALC-209" + ,"北京单租车接送服务(目的地)" => "BJALC-209" ,"北京市内-天津新港大车接送(目的地)" => "BJSIC-16" ,"天津新港-北京市内大车接送(目的地)" => "BJSIC-16" ,"箭扣-慕田峪徒步一日游(目的地)" => "BJSIC-45" + ,"箭扣-慕田峪徒步一日游(PVT)(目的地)" => "BJSIC-45" ,"箭扣-慕田峪长城徒步拼团(目的地)" => "BJSIC-45" ,"司马台西-金山岭徒步一日游(目的地)" => "BJSIC-46" ,"司马台西-金山岭徒步一日游(PVT)(目的地)" => "BJSIC-46" @@ -1076,22 +1100,29 @@ log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); ,"慕田峪半日游拼团(目的地)" => "BJSIC-47" ,"慕田峪半日游PVT(目的地)" => "BJSIC-47" ,"古北口长城徒步一日游(目的地)" => "BJSIC-48" + ,"古北口(目的地)" => "BJSIC-48" ,"半日游广场故宫拼团(目的地)" => "BJSIC-41" // ,=> ,"西安精品一日游(目的地)" => "XASIC-41" + ,"西安精品一日游PVT(目的地)" => "XASIC-41" + ,"西安市内精品一日游(目的地)" => "XASIC-41" ,"西安精品两日游(目的地)" => "XASIC-42" ,"西安单租车服务(目的地)" => "XASIC-17" ,"西安单租车接送服务(目的地)" => "XASIC-17" + ,"西安单租车接送服务" => "XASIC-17" ,"西安兵马俑精品一日游(目的地)" => "XASIC-41" + ,"西安兵马俑精华一日游(目的地)" => "XASIC-41" ,"西安兵马俑精品半日游(目的地)" => "XASIC-15" ,"西安兵马俑精品半日游PVT(目的地)" => "XASIC-15" ,"西安汉阳陵市内精品一日游(目的地)" => "XASIC-42" // ,=> ,"上海精品一日游(目的地)" => "SHSIC-41" + ,"上海精品游PVT线路(目的地)" => "SHSIC-41" ,"上海市内精品一日游(目的地)" => "SHSIC-42" ,"周庄锦溪精品一日游(目的地)" => "SHSIC-43" ,"苏州精品一日游(目的地)" => "SHSIC-44" ,"上海单租车(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" + ,"上海单租车接送服务(目的地)" => "SHSIC-45" //"SHALC-6,7,8,9" ); } diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 1562f36b..60b8d0b7 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -34,7 +34,7 @@ class Api extends CI_Controller { } $ret['status'] = 1; $ret['msg'] = ""; - $ret['group_number'] = $order_project[0]->COLI_GroupCode; + $ret['group_number'] = analysis_groupCode($order_project[0]->COLI_GroupCode); $all_combine_no = array_unique(array_map(function($ele) { return $ele->GCI_combineNo; @@ -126,11 +126,16 @@ class Api extends CI_Controller { $vro['pick_up'] = ""; $vro['drop_off'] = ""; $decode_MemoText = $memo_text_tmp = ""; - if ($num_index == 0) { + if ($vro['pick_up'] === "" && $poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { + $decode_MemoText = json_decode($poi->COLD_MemoText, true); + $vro['pick_up'] = $decode_MemoText['Pick up']; + $vro['drop_off'] = $decode_MemoText['Drop off']; + } + if ($vro['pick_up'] === "" && $num_index == 0) { $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); } - // if ($vro['pick_up'] === "") { + if ($vro['pick_up'] === "") { if (strval($poi->PAGS_Direction) === '0') { $vro['pick_up'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; $vro['drop_off'] .= $poi->POI_Hotel; @@ -141,10 +146,7 @@ class Api extends CI_Controller { $vro['pick_up'] .= $poi->POI_Hotel; // $vro['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; // 结束后送机 } - // } - // if ($vro['pick_up'] === "" && $poi->POI_FlightsNo == '') { - // $vro['pick_up'] = $vro['drop_off'] = $poi->POI_Hotel; - // } + } $num_index++; } unset($vro); diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 9865de38..cf49a170 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -54,8 +54,9 @@ class Order_finance extends CI_Controller { * * 获取拼团总人数, 价格人等 * * 分别计算每次拼团成本 * * * 写入report_tour + * * * 其他产品项目, report_train, report_hotel等 * * 所有产品总成本 - * * * 写入核算管理CK_GroupInfo + * * * [此处不做]写入核算管理CK_GroupInfo * * * 写入单团财务表report_order * END */ @@ -285,6 +286,7 @@ class Order_finance extends CI_Controller { $tmp = null; $tmp = $this->get_allowed_combine($vp); $this_allowed = ($tmp === null) ? null : array_diff($tmp, $all_pag); // diff((31,41), (31,41,47)) ==> () + // $this_allowed = ($tmp === null) ? null : array_diff($all_pag, $tmp); // diff((31,41), (31,41,47)) ==> () if (empty($this_allowed) && $tmp !== null) { $combine_pag_arr[] = $tmp; // push (31,41) } @@ -308,6 +310,13 @@ class Order_finance extends CI_Controller { } $ret->combine_pags = my_array_unique($combine_pag_arr); $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品 + // 一些不再常规混拼的团, 仅有一个拼团号的订单则加上该团 + foreach ($all_orders as $key => $value) { + if ($value->combine_cnt === 1) { + $ret->combine_pags[] = $value->PAG_Code; + } + } + $ret->combine_pags = array_values(array_unique($ret->combine_pags)); $ret->person_num = 0; $ret->PAG_Code = ""; $ret->order_cost = array(); @@ -330,7 +339,8 @@ class Order_finance extends CI_Controller { $tour_s->adult_num = $vo->COLD_PersonNum; $tour_s->child_num = $vo->COLD_ChildNum; $tour_s->PAG_code = $vo->PAG_Code; - $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; + // $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; + $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : $vo->PAG_Code; $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; $tour_s->totalPrice = $vo->COLD_TotalPrice; $ret->order_cost[] = $tour_s; @@ -351,8 +361,8 @@ class Order_finance extends CI_Controller { foreach ($ret->order_cost as $kc => $voc) { $ret->order_cost[$kc]->order_cost_sum = bcmul($voc->person_num, $ret->person_cost); } - return $ret; // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); + return $ret; } /*! diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php new file mode 100644 index 00000000..c4d9bc57 --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -0,0 +1,174 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Send_operation extends CI_Controller { + + public function __construct(){ + parent::__construct(); + mb_regex_encoding("UTF-8"); + bcscale(4); + $this->load->helper('array'); + $this->load->model('Send_operation_model', 'send_model'); + $this->send_url = 'https://www.mycht.cn/webht.php/apps/messagecenter/index/send_message/'; + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); + } + + public function index() + { + $this->sms_log(); + return; + } + + public function sms_log() + { + $date = $this->input->get_post("date"); + $date = $date ? $date : date('Y-m-d', strtotime("+1 day")); + $ready_order["date"] = $date; + $COLI_ID = $this->input->get_post("order_id"); + $ready_order["order_id"] = $COLI_ID; + $ready_order["list"] = $this->send_model->daytour_order_ready_for_send(trim($COLI_ID), $date, "no_send_state"); + $this->load->view('sms_log', $ready_order); + return; + } + + public function order_sms_list($COLI_SN) + { + $data['list'] = $this->send_model->order_sms_list($COLI_SN); + $list_table = $this->load->view('order_sms_list', $data, true); + $this->output->set_content_type('application/json')->set_output(json_encode($list_table)); + return; + } + + /*! + * 通过短信发送导游信息给预定了Day Tour的客人 + * * 每天9:00, 16:00 尝试发送 + * * 第二次发送之后仍然发送失败或没有调度信息, 反馈到Alex邮箱 + * * 这里只是Day Tour 订单, 不含单接送, 因此每个订单仅发送一次 + * @date 2018-09-25 + */ + public function daytour($COLI_ID="") + { + $now_h = date("H"); + $time_flag = ""; + if ($now_h < 9 || $now_h > 19) { + echo "Break time."; + return false; + } else if ($now_h >= 9 && $now_h < 16) { + $time_flag = "try1"; + } else { + $time_flag = "try2"; + } + $date = date('Y-m-d', strtotime("+1 day")); + if (trim($COLI_ID) !== "") { + $date = null; + $time_flag = "handle"; + } + $ready_order = $this->send_model->daytour_order_ready_for_send(trim($COLI_ID), $date, $time_flag); + if (empty($ready_order)) { + echo "Empty. "; + return false; + } + $order = $ready_order[0]; + if (strtotime($order->GCI_travelDate) < strtotime(date('Y-m-d')) ) { + echo "已过期"; + return; + } + $send_body = array( + "one" => trim($order->GUT_FirstName . " " . $order->GUT_LastName) + ,"two" => substr($order->GCI_travelDate, 0, 10) + ,"three" => $order->GCOD_dutyName + ,"four" => "+86 " . $order->GCOD_dutyTel + ,"phone" => real_phone_number($order->GUT_TEL, $order->GUT_POST) + ,"nation_code" => $order->GUT_POST + ); + $cb_db = array( + "TPSL_COLI_SN" => $order->COLI_SN + ,"TPSL_nationCode" => $send_body['nation_code'] + ,"TPSL_mobile" => $send_body['phone'] + ,"TPSL_msgType" => 'guide' + ,"TPSL_sendState" => 0 + ); + $ht_id = $this->send_model->insert_trippest_sms_log($cb_db); + $error_msg = ""; + $send_time = date("Y-m-d H:i:s"); + if ($order->GCOD_dutyName !== null) { + $send_cb = $this->excute_curl($this->send_url, $send_body); + $send_cb_obj = json_decode($send_cb); + $update_cb_db["TPSL_sendTime"] = $send_time; + $update_cb_db["TPSL_sendContent"] = json_encode($send_body); + $update_cb_db['TPSL_sendState'] = $send_cb_obj->result===0 ? 1 : 0; + $update_cb_db['TPSL_callbackJson'] = $send_cb; + $update_cb_db['TPSL_callbackTime'] = date("Y-m-d H:i:s"); + $update_where = " TPSL_SN=" . $ht_id; + $ht_id = $this->send_model->update_trippest_sms_log($update_where, $update_cb_db); + $send_cb_obj->errmsg!=="OK" ? $error_msg=$send_cb_obj->errmsg : null; + } + if ($time_flag === "try1") { + return; + } + if ($order->GCOD_dutyName === null || $error_msg !== "") { + // 没有调度或发送失败 + // to Alex + $operator_mailbody = "<p> Dear Alex: </p>" . + "<p>导游信息发送客人失败:<br /></p>" . + "<p>订单号:" . $order->COLI_ID ."</p>" . + "<p>发团时间:" . substr($order->GCI_travelDate, 0, 10) ."</p>" . + "<p>导游信息:" . $order->GCOD_dutyName . "(" . $order->GCOD_dutyTel . ")" ."</p>" . + "<p>导游更新时间:" . $order->GCI_createTime . " " . $order->GCOD_creatTime ."</p>" . + "<p>发送时间:" . $send_time ."</p>"; + if ($error_msg !== "") { + $operator_mailbody .= "<p>发送失败信息:" . $error_msg . "</p>"; + } + $operator_mailbody .= "<p><a href='https://www.trippest.com/track-your-trip/'>Tracking Link</a>.</p>"; + $operator_mailbody .= "<p> 此邮件由系统自动发送, 请勿回复.</p>"; + $this->send_model->SendMail( + "chinahighlights", + "webform@chinahighlights.net", + "YSL", + "alex@chinahighlights.net", // ysl email alex@chinahighlights.net + '#SMS send fail# ' . $order->COLI_ID, + $operator_mailbody); + } + echo "已发送"; + return; + } + + protected function excute_curl($url, $postBody) { + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_FAILONERROR, false); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); + curl_setopt($ch, CURLOPT_HTTPHEADER, array( + "Accept: application/json" + )); + + if (empty($postBody)) { + return false; + } + curl_setopt($ch, CURLOPT_POST, true); + curl_setopt($ch, CURLOPT_POSTFIELDS, $postBody); + + $reponse = curl_exec($ch); + // $eval_resp = json_decode($reponse); + + if (curl_errno($ch)) { + log_message('error', "curl error : ".curl_error($ch) . "; curl postBodyString: ".json_encode($postBody)); + } else { + $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); + if (200 !== $httpStatusCode) { + log_message('error', "curl response Status Code: ".$httpStatusCode."; curl postBodyString: ".json_encode($postBody)); + } + } + curl_close($ch); + return $reponse; + } + +} + +/* End of file send_operation.php */ +/* Location: ./webht/third_party/trippestOrderSync/controllers/send_operation.php */ diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 8880682f..f66c6d2b 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -117,9 +117,12 @@ function raw_json_encode($input, $flags = 0) { function analysis_groupCode($groupCode) { mb_regex_encoding("UTF-8"); - $groupCode = trim_groupCode(trim($groupCode)); + $groupCode = trim_str(trim($groupCode)); preg_match('/[\w\s\-]+/', characet($groupCode, "UTF-8"), $temp_array); // $temp_array[0] = strrchr($temp_array[0], " ") ? mb_strstr($temp_array[0], " ",true) : $temp_array[0]; + if (empty($temp_array)) { + return trim_str(trim($groupCode)); + } $tmp_groupCode = explode("-", trim($temp_array[0])); $real_groupCode = $tmp_groupCode[0]; if (isset($tmp_groupCode[1])) { @@ -132,12 +135,12 @@ function analysis_groupCode($groupCode) $real_groupCode .= mb_strstr($tmp_groupCode[$i], "(", true)!==false ? mb_strstr($tmp_groupCode[$i], "(", true) : $tmp_groupCode[$i]; } } - $real_groupCode = trim_groupCode(trim($real_groupCode)); + $real_groupCode = trim_str(trim($real_groupCode)); return $real_groupCode; } -function trim_groupCode($groupCode) +function trim_str($groupCode) { - return mb_ereg_replace('( | | )', '', $groupCode); + return mb_ereg_replace('( | | )', '', $groupCode); } /*! * 转换字符集编码 @@ -155,3 +158,10 @@ function characet($data, $targetCharset) { } return $data; } + +function real_phone_number($phone, $nation_code) +{ + $nation_str = "+" . $nation_code; + $cut_nation = str_replace($nation_str, "", $phone); + return mb_ereg_replace('[\D]', '', $cut_nation); +} diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 53777243..7f398f3e 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -64,6 +64,8 @@ class OrderFinance_model extends CI_Model { /** * 拼团号下的所有订单 * * 仅包价线路产品 + * * 2018-10-10 增加按COLD_PersonNum降序排序, 计算拼团人数时按多的算. + * 180217342 订单中2人参加两个项目拼同一个团但是人数不同 */ public function get_all_combine_order($combineNo="", $processed_code=array()) { @@ -74,15 +76,16 @@ class OrderFinance_model extends CI_Model { ,PAG_Code ,pag_sub.PAGS_CN_Title, cold.COLD_StartDate,PAG_DefaultVEI_SN ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate, cold.COLD_TotalPrice --,PAG_Title + ,(select count(1) from GroupCombineInfo where gci_gri_sn=coli_gri_sn) as combine_cnt from GroupCombineInfo gci - inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN + inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN and coli.COLI_State NOT IN (30,40,50) inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 and COLD_PlanVEI_SN in (1343,29188,30548,30016) left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2 where gci.GCI_combineNo =? $processed_sql - order by GCI_combineNo,cold.COLD_StartDate"; + order by GCI_combineNo asc,cold.COLD_StartDate asc,cold.COLD_PersonNum desc"; return $this->HT->query($sql, array($combineNo))->result(); } @@ -165,6 +168,9 @@ class OrderFinance_model extends CI_Model { /** 获取产品信息:产品名称,供应商等 */ public function get_pag_info($PAG_SN_str="") { + if ($PAG_SN_str=="") { + return array(); + } $sql = "SELECT pag.PAG_SN,PAG_Code,PAG_DefaultVEI_SN,PAG_Title,vei2.VEI2_CompanyBN from BIZ_PackageInfo pag inner join VEndorInfo2 vei2 on VEI2_VEI_SN=PAG_DefaultVEI_SN and VEI2_LGC=2 @@ -201,10 +207,10 @@ class OrderFinance_model extends CI_Model { } /** 判断各种项目的报表是否已存在 */ - public function report_tour_exists($coli_id=null, $tourCode=null) + public function report_tour_exists($coli_id=null, $tourCode=null, $tourBz=null) { - $sql = "SELECT top 1 ordernumber from report_tour where ordernumber=? and tourCode=?"; - $num_rows = $this->HT->query($sql, array($coli_id, $tourCode))->num_rows(); + $sql = "SELECT top 1 ordernumber from report_tour where ordernumber=? and tourCode=? and tourBz=? "; + $num_rows = $this->HT->query($sql, array($coli_id, $tourCode, $tourBz))->num_rows(); return $num_rows>0; } public function report_train_exists($coli_id=null, $TrainNo=null) @@ -230,8 +236,9 @@ class OrderFinance_model extends CI_Model { public function insert_report_tour_tulanduo($report_tour_arr=array()) { foreach ($report_tour_arr as $krt => $vrt) { - if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode']) === TRUE) { - $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "'"; + if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode'], $vrt['tourBZ']) === TRUE) { + $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "' "; + $where .= " AND tourBZ='" . $vrt['tourBZ'] . "' "; $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); $this->HT->query($update_sql); } else { @@ -343,8 +350,9 @@ class OrderFinance_model extends CI_Model { { $other_tour_cost = $this->get_report_tour_others_cost($coli_sn); foreach ($other_tour_cost as $kotc => $votc) { - if ($this->report_tour_exists($votc->ordernumber, $votc->tourCode) === TRUE) { + if ($this->report_tour_exists($votc->ordernumber, $votc->tourCode, $votc->tourBZ) === TRUE) { $where = " ordernumber='" . $votc->ordernumber . "' AND tourCode='" . $votc->tourCode . "'"; + $where .= " AND tourBZ='" . $votc->tourBZ . "' "; $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', json_decode(json_encode($votc), TRUE), $where); $this->HT->query($update_sql); } else { diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 78bfb4aa..be08730d 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -131,10 +131,14 @@ class Orders_model extends CI_Model { */ public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) { + $createTime_format = date('H')>12 ? 'Y-m-d 13:00:00' : 'Y-m-d 00:00:00'; $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - cold.COLD_PlanVEI_SN, gci.*,'0' as 'isHistory' + cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'0' as 'isHistory' FROM GroupCombineInfo gci - LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN --and coli.COLI_State NOT IN ('30','40','50') + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + --and coli.COLI_State NOT IN ('30','40','50') + and coli.COLI_State<>50 + and (select OPI_DEI_SN from OperatorInfo where OPI_SN=coli.COLI_OPI_ID)=30 LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN WHERE 1=1 "; if ($coli_sn !== 0) { @@ -144,28 +148,25 @@ class Orders_model extends CI_Model { $sql .= " and GCI_VendorOrderId='$get_vendorID' "; } if ($startDate !== NULL) { - $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' and gci.GCI_createTime < '" . date('Y-m-d') . "' "; + $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' + and gci.GCI_createTime < '" . date($createTime_format) . "' "; } // 近期的订单同步完成之后, 同步历史数据 $sql .= " UNION ALL "; $sql .= " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - cold.COLD_PlanVEI_SN, gci.*,'1' as 'isHistory' + cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' from GroupCombineInfo gci inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + and coli.COLI_State<>50 + and (select OPI_DEI_SN from OperatorInfo where OPI_SN=coli.COLI_OPI_ID)=30 LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + and gci.GCI_createTime < '" . date('Y-m-d') . "' and GCI_combineNo not like '%取消%' - and not exists ( - select GCOD_SN from GroupCombineOperationDetail gcod where gcod.GCOD_GCI_combineNo=GCI_combineNo - ) - and 0 < ( - select sum(isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)+isnull(COLD_BabyNum,0)) person from BIZ_ConfirmLineInfo - inner join BIZ_ConfirmLineDetail on COLD_COLI_SN=COLI_SN - where COLI_GRI_SN=gri_sn - ) "; + "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; $query = $this->HT->query($sql); return $query->result(); @@ -534,7 +535,7 @@ class Orders_model extends CI_Model { inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN --and COLI_State not in (30,40,50) LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 and gri.GRI_operator<>435 and gri.GRI_operator is not null - WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' + WHERE (select OPI_DEI_SN from OperatorInfo where OPI_SN=COLI_OPI_ID)=30 and gri.GRI_No LIKE '%$code%' order by COLI_SN desc"; // and gri.GRI_Name like '%$NoName%' $query = $this->HT->query($sql); if ($query->num_rows() > 0) { @@ -559,11 +560,12 @@ class Orders_model extends CI_Model { coli.COLI_OrderDetailText, coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, - coli.COLI_Memo + coli.COLI_Memo,cold.COLD_MemoText FROM BIZ_ConfirmLineInfo coli inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 - WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' + WHERE (select OPI_DEI_SN from OperatorInfo where OPI_SN=COLI_OPI_ID)=30 + and coli.COLI_State<>50 and gri.GRI_No LIKE '%$code%' order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; $query = $this->HT->query($sql); return $query->result(); diff --git a/webht/third_party/trippestOrderSync/models/orders_query.php b/webht/third_party/trippestOrderSync/models/orders_query.php index 1da05a4e..27c86be8 100644 --- a/webht/third_party/trippestOrderSync/models/orders_query.php +++ b/webht/third_party/trippestOrderSync/models/orders_query.php @@ -28,7 +28,7 @@ class Orders_query extends CI_Model { { $order_info_sql = "SELECT GCI_SN,GCI_VendorOrderId,GCI_combineNo - ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText + ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText,COLI_PriceMemo ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText ,pags.PAGS_Direction,pags.PAGS_describ ,pag2.PAG2_Name @@ -44,6 +44,7 @@ class Orders_query extends CI_Model { left join BIZ_PackageInfoSub pags on pags.PAGS_SN=cold.COLD_ServiceSN2 where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + OR COLI_PriceMemo like '%" . $this->HT->escape_like_str($COLI_ID) . "%' order by COLD_StartDate asc"; // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' $order_info_query = $this->HT->query($order_info_sql); diff --git a/webht/third_party/trippestOrderSync/models/send_operation_model.php b/webht/third_party/trippestOrderSync/models/send_operation_model.php new file mode 100644 index 00000000..976de4be --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/send_operation_model.php @@ -0,0 +1,135 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Send_operation_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + $this->info = $this->load->database('INFO', TRUE); + } + + public function daytour_order_ready_for_send($COLI_ID="", $date, $time_flag="no_send_state") + { + $today = date('Y-m-d 16:00:00'); + switch ($time_flag) { + case 'try1': + $send_state = " "; + break; + case 'try2': + $send_state = " and (TPSL_sendState=1 OR TPSL_logTime > '$today') "; + break; + case 'handle': + $send_state = " and (TPSL_sendState=1) "; + break; + + case '': + default: + $send_state = ""; + break; + } + $send_state_sql = " and not exists ( + select TPSL_SN from InfoManager.dbo.trippest_sms_log + where TPSL_COLI_SN=coli.COLI_SN + $send_state + ) "; + $top = " TOP 1 "; + $sms_state = ""; + if ($time_flag == "no_send_state") { + $send_state_sql = ""; + $top = ""; + $sms_state = " ,(select top 1 TPSL_sendState from InfoManager.dbo.trippest_sms_log + where TPSL_COLI_SN=coli.COLI_SN and TPSL_sendContent like '%'+GCOD_startDate+'%' + order by TPSL_sendState desc + ) as send_state"; + } + $search_sql = " AND GCI_travelDate ='$date' "; + if ($COLI_ID !== "") { + $search_sql = " AND COLI_ID='" . $COLI_ID . "'"; + } + $sql = "SELECT $top GroupCombineOperationDetail.GCOD_SN,COLI_SN,COLI_ID,COLI_groupCode + ,GUT_POST,GUT_TEL + ,PAG_ExtendType,PAG_Code + ,g.GUT_FirstName,g.GUT_LastName + ,gci.* + ,GCOD_startDate,GCOD_operationType,GCOD_dutyName,GCOD_dutyTel,GCOD_creatTime + $sms_state + FROM BIZ_ConfirmLineInfo coli + INNER JOIN BIZ_ConfirmLineDetail cold ON COLD_COLI_SN=COLI_SN + INNER JOIN BIZ_GUEST g ON g.GUT_SN=COLI_GUT_SN + and GUT_TEL is not null and GUT_TEL<>'' and GUT_POST<>'' + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=COLD_ServiceSN + LEFT JOIN GroupCombineInfo gci ON COLI_GRI_SN=GCI_GRI_SN + LEFT JOIN GroupCombineOperationDetail ON GCOD_GCI_combineNo=GCI_combineNo + AND GCOD_operationType='guiderOperations' + WHERE 1=1 + $search_sql + AND GCI_combineNo not IN ('cancel','forbidden') + AND '39009'<>PAG_ExtendType + $send_state_sql + ORDER BY GCI_travelDate, COLI_SN + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function insert_trippest_sms_log($column) + { + $this->info->insert("trippest_sms_log", $column); + return $this->info->insert_id(); + } + + public function update_trippest_sms_log($where, $column) + { + if ($where == "" || empty($column)) { + return false; + } + $update_str = $this->info->update_string('trippest_sms_log', $column, $where); + $update_exc = $this->info->query($update_str); + return $update_exc; + } + + /** 暂时不用了 */ + public function if_order_sent($COLI_SN, $msgType='guide') + { + $sql = "SELECT * + FROM [infomanager].[dbo].[trippest_sms_log] + where [TPSL_COLI_SN]=$COLI_SN + and [TPSL_sendState]=1 + and TPSL_msgType='$msgType' + "; + return $this->info->query($sql)->row(); + } + + /* + * 发送邮件 + */ + function SendMail($fromName, $fromEmail, $toName, $toEmail, $subject, $body) { + $sql = "INSERT INTO tourmanager.dbo.Email_AutomaticSend \n" + . " ( \n" + . " M_ReplyToName, M_ReplyToEmail, M_ToName, M_ToEmail, M_Title, M_Body, M_Web, \n" + . " M_FromName, M_State \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, ?, ?, ?, ?, N?, ?, ?, 0 \n" + . " ) "; + $query = $this->info->query($sql, + array(substr($fromName, 0, 127), $fromEmail, substr($toName, 0, 127), $toEmail, $subject, $body, 'trippest SMS send fail', 'chinahighlighgts') + ); + return $query; + } + + function order_sms_list($COLI_SN=0) + { + $sql = "SELECT * + FROM [infomanager].[dbo].[trippest_sms_log] + where [TPSL_COLI_SN]=$COLI_SN + order by TPSL_logTime "; + return $this->HT->query($sql)->result(); + } + +} + +/* End of file send_operation_model.php */ +/* Location: ./webht/third_party/trippestOrderSync/models/send_operation_model.php */ diff --git a/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php index f3108da4..0f6da1a5 100644 --- a/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php +++ b/webht/third_party/trippestOrderSync/models/tulanduo_sync_model.php @@ -26,6 +26,7 @@ class Tulanduo_sync_model extends CI_Model { */ public function get_oldest_offset() { + $ret_date = ""; $sql = "SELECT DISTINCT TOP 10 CAST(GCI_travelDate as DATE) old_date from GroupCombineInfo order by old_date asc"; $all_date = $this->HT->query($sql)->result(); @@ -37,11 +38,22 @@ class Tulanduo_sync_model extends CI_Model { $d1 = new DateTime($all_date_arr[$i]); $d2 = new DateTime($all_date_arr[$i-1]); $date_diff = $d2->diff($d1); - if (intval($date_diff->format('%R%a')) > 1) { - return $all_date_arr[$i]; + if (intval($date_diff->format('%R%a')) > 1 && !in_array($all_date_arr[$i], $this->empty_date()) ) { + $ret_date = $all_date_arr[$i]; + break; } } - return $all_date_arr[0]; + if ($ret_date==="") { + $ret_date = $all_date_arr[0]; + } + return $ret_date; + } + private function empty_date() + { + return array( + "2018-02-06" // 2018-02-05 没有团 + ,"2017-01-17" + ); } /*! * 图兰朵订单在HT内的信息 diff --git a/webht/third_party/trippestOrderSync/views/order_sms_list.php b/webht/third_party/trippestOrderSync/views/order_sms_list.php new file mode 100644 index 00000000..ab0b9788 --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/order_sms_list.php @@ -0,0 +1,25 @@ +<table class="table table-bordered table-hover"> + <thead> + <tr> + <th>发送时间</th> + <th>失败原因</th> + </tr> + </thead> + <tbody> + <?php + foreach ($list as $key => $value) { + $tmp_msg = null; + if ($value->TPSL_callbackJson == null) { + $tmp_msg = "无导游安排"; + } else { + $tmp_msg = json_decode($value->TPSL_callbackJson); + $tmp_msg = $tmp_msg->errmsg; + } + ?> + <tr> + <td> <?php echo $value->TPSL_logTime; ?> </td> + <td> <?php echo $tmp_msg; ?> </td> + </tr> + <?php } ?> + </tbody> +</table> diff --git a/webht/third_party/trippestOrderSync/views/sms_log.php b/webht/third_party/trippestOrderSync/views/sms_log.php new file mode 100644 index 00000000..3a597c80 --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/sms_log.php @@ -0,0 +1,242 @@ +<?php +/*! +* 查询短信发送记录 +* @author LYT <lyt@hainatravel.com> +* @date 2018-10-08 +*/ +?> +<!DOCTYPE html> +<html> + <head> + <meta charset="utf-8"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <title>Day Tour SMS Log - Trippest</title> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <meta name="referrer" content="always"> + <link href="//data.chinahighlights.com/css/min.php?f=/public/css/global.min.css&amp;v=20180811" rel="stylesheet" type="text/css" /> + <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> + <style type="text/css" media="screen and (max-width:767px)"> + .pay_form .form-group{padding-left: 0!important;padding-right: 0!important;} + .pay_form .result_info{padding-top: 5px!important;} + </style> + <style type="text/css"> + p{margin-bottom: 8.5px;} + a{text-decoration: none;} + .text_padding {padding: 10px ;} + .btn_margin {margin-top: 5px;} + .navbar-header h1{display: inline-block;margin-left: 30px;margin-right: 30px;} + .pageTitle{margin-left: 300px;} + .pageTitle h1{color: #fff;border:none;font-size: 30px;} + .mobileTitle h1{color: #fff;border:none;font-size: 20px;} + .pay_form{padding: 30px 15px 15px 15px ;box-shadow: 0 0 10px #999;background: #fff;border-radius: 5px; } + .pay_form .form-group{padding-left: 50px;padding-right: 50px;} + .pay_form .control-label{text-align: left;} + .pay_form .result_info{padding-top: 25px;} + .pay_form .btn-danger{background: #a31022;} + .pay_footer{padding: 30px 0 10px;font-size: 12px;} + .line{border-bottom: 1px solid #cacaca;margin-left: 20px!important;margin-right: 20px!important;} + .btn{text-decoration: none;font-size: 14px;} + .mail_list {margin: 0;padding: 8px 15px;border-bottom: 1px solid #ccc;overflow: hidden; } + /*.input-group{border: 1px solid #ccc;}*/ + .input-group-btn{border: 1px solid #ccc;padding: 5px;} + .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} + .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;} + #modal_set_gai .btn{color: #333;font-weight: 700;} + /*flatpickr:begin*/ + .flatpickr-calendar{background:transparent;opacity:0;display:none;text-align:center;visibility:hidden;padding:0;-webkit-animation:none;animation:none;direction:ltr;border:0;font-size:14px;line-height:24px;border-radius:5px;position:absolute;width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-touch-action:manipulation;touch-action:manipulation;background:#fff;-webkit-box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);}.flatpickr-calendar.open,.flatpickr-calendar.inline{opacity:1;max-height:640px;visibility:visible;}.flatpickr-calendar.open{display:inline-block;z-index:99999;}.flatpickr-calendar.animate.open{-webkit-animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);}.flatpickr-calendar.inline{display:block;position:relative;top:2px;}.flatpickr-calendar.static{position:absolute;top:calc(100% + 2px);}.flatpickr-calendar.static.open{z-index:999;display:block;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+1) .flatpickr-day.inRange:nth-child(7n+7){-webkit-box-shadow:none !important;box-shadow:none !important;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+2) .flatpickr-day.inRange:nth-child(7n+1){-webkit-box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-calendar .hasWeeks .dayContainer,.flatpickr-calendar .hasTime .dayContainer{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0;}.flatpickr-calendar .hasWeeks .dayContainer{border-left:0;}.flatpickr-calendar.showTimeInput.hasTime .flatpickr-time{height:40px;border-top:1px solid #e6e6e6;}.flatpickr-calendar.noCalendar.hasTime .flatpickr-time{height:auto;}.flatpickr-calendar:before,.flatpickr-calendar:after{position:absolute;display:block;pointer-events:none;border:solid transparent;content:'';height:0;width:0;left:22px;}.flatpickr-calendar.rightMost:before,.flatpickr-calendar.rightMost:after{left:auto;right:22px;}.flatpickr-calendar:before{border-width:5px;margin:0 -5px;}.flatpickr-calendar:after{border-width:4px;margin:0 -4px;}.flatpickr-calendar.arrowTop:before,.flatpickr-calendar.arrowTop:after{bottom:100%;}.flatpickr-calendar.arrowTop:before{border-bottom-color:#e6e6e6;}.flatpickr-calendar.arrowTop:after{border-bottom-color:#fff;}.flatpickr-calendar.arrowBottom:before,.flatpickr-calendar.arrowBottom:after{top:100%;}.flatpickr-calendar.arrowBottom:before{border-top-color:#e6e6e6;}.flatpickr-calendar.arrowBottom:after{border-top-color:#fff;}.flatpickr-calendar:focus{outline:0;}.flatpickr-wrapper{position:relative;display:inline-block;}.flatpickr-months{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-months .flatpickr-month{background:transparent;color:rgba(0,0,0,0.9);fill:rgba(0,0,0,0.9);height:28px;line-height:1;text-align:center;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;margin-bottom:5px;}.flatpickr-months .flatpickr-prev-month,.flatpickr-months .flatpickr-next-month{text-decoration:none;cursor:pointer;position:absolute;top:0px;line-height:16px;height:28px;padding:10px;z-index:3;}.flatpickr-months .flatpickr-prev-month.disabled,.flatpickr-months .flatpickr-next-month.disabled{display:none;}.flatpickr-months .flatpickr-prev-month i,.flatpickr-months .flatpickr-next-month i{position:relative;}.flatpickr-months .flatpickr-prev-month.flatpickr-prev-month,.flatpickr-months .flatpickr-next-month.flatpickr-prev-month{left:0;}.flatpickr-months .flatpickr-prev-month.flatpickr-next-month,.flatpickr-months .flatpickr-next-month.flatpickr-next-month{right:0;}.flatpickr-months .flatpickr-prev-month:hover,.flatpickr-months .flatpickr-next-month:hover{color:#959ea9;}.flatpickr-months .flatpickr-prev-month:hover svg,.flatpickr-months .flatpickr-next-month:hover svg{fill:#f64747;}.flatpickr-months .flatpickr-prev-month svg,.flatpickr-months .flatpickr-next-month svg{width:14px;height:14px;}.flatpickr-months .flatpickr-prev-month svg path,.flatpickr-months .flatpickr-next-month svg path{-webkit-transition:fill 0.1s;transition:fill 0.1s;fill:inherit;}.numInputWrapper{position:relative;height:auto;}.numInputWrapper input,.numInputWrapper span{display:inline-block;}.numInputWrapper input{width:100%;}.numInputWrapper input::-ms-clear{display:none;}.numInputWrapper span{position:absolute;right:0;width:14px;padding:0 4px 0 2px;height:50%;line-height:50%;opacity:0;cursor:pointer;border:1px solid rgba(57,57,57,0.15);-webkit-box-sizing:border-box;box-sizing:border-box;}.numInputWrapper span:hover{background:rgba(0,0,0,0.1);}.numInputWrapper span:active{background:rgba(0,0,0,0.2);}.numInputWrapper span:after{display:block;content:"";position:absolute;}.numInputWrapper span.arrowUp{top:-2px;left:50px;}.numInputWrapper span.arrowUp:after{border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:4px solid rgba(57,57,57,0.6);top:26%;}.numInputWrapper span.arrowDown{top:10px;left:50px;}.numInputWrapper span.arrowDown:after{border-left:4px solid transparent;border-right:4px solid transparent;border-top:4px solid rgba(57,57,57,0.6);top:40%;}.numInputWrapper span svg{width:inherit;height:auto;}.numInputWrapper span svg path{fill:rgba(0,0,0,0.5);}.numInputWrapper:hover{cursor:pointer;}.numInputWrapper:hover span{opacity:1;}.flatpickr-current-month{font-size:17px;line-height:inherit;font-weight:300;color:inherit;position:absolute;width:75%;left:12.5%;padding:6.16px 0 0 0;line-height:1;height:28px;display:inline-block;text-align:center;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);}.flatpickr-current-month span.cur-month{font-family:inherit;font-weight:700;color:inherit;display:inline-block;margin-left:0.5ch;padding:0;font-size:19px;color:#a31022;}.flatpickr-current-month span.cur-month:hover{cursor:pointer;}.flatpickr-current-month .numInputWrapper{width:6ch;width:7ch\0;display:inline-block;}.flatpickr-current-month .numInputWrapper span.arrowUp:after{border-bottom-color:rgba(0,0,0,0.9);}.flatpickr-current-month .numInputWrapper span.arrowDown:after{border-top-color:rgba(0,0,0,0.9);}.flatpickr-current-month input.cur-year{background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;color:inherit;cursor:text;padding:0 0 0 0.5ch;margin:0;display:inline-block;font-size:inherit;font-family:inherit;font-weight:300;line-height:inherit;height:auto;border:0;border-radius:0;vertical-align:initial;font-size:18px;}.flatpickr-current-month input.cur-year:focus{outline:0;}.flatpickr-current-month input.cur-year[disabled],.flatpickr-current-month input.cur-year[disabled]:hover{font-size:100%;color:rgba(0,0,0,0.5);background:transparent;pointer-events:none;}.flatpickr-weekdays{background:transparent;text-align:center;overflow:hidden;width:100%;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;height:28px;}.flatpickr-weekdays .flatpickr-weekdaycontainer{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}span.flatpickr-weekday{cursor:default;font-size:16px;background:transparent;color:rgba(0,0,0,0.54);line-height:1;margin:0;text-align:center;display:block;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}.dayContainer,.flatpickr-weeks{padding:1px 0 0 0;}.flatpickr-days{position:relative;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:start;-webkit-align-items:flex-start;-ms-flex-align:start;align-items:flex-start;width:307.875px;}.flatpickr-days:focus{outline:0;}.dayContainer{padding:0;outline:0;text-align:left;width:307.875px;min-width:307.875px;max-width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;display:inline-block;display:-ms-flexbox;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-wrap:wrap;-ms-flex-pack:justify;-webkit-justify-content:space-around;justify-content:space-around;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);opacity:1;}.dayContainer + .dayContainer{-webkit-box-shadow:-1px 0 0 #e6e6e6;box-shadow:-1px 0 0 #e6e6e6;}.flatpickr-day{background:none;border:1px solid transparent;border-radius:150px;-webkit-box-sizing:border-box;box-sizing:border-box;color:#a31022;cursor:pointer;font-weight:400;width:14.2857143%;-webkit-flex-basis:14.2857143%;-ms-flex-preferred-size:14.2857143%;flex-basis:14.2857143%;max-width:39px;height:39px;line-height:39px;margin:0;display:inline-block;position:relative;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;text-align:center;font-size:16px;}.flatpickr-day.inRange,.flatpickr-day.prevMonthDay.inRange,.flatpickr-day.nextMonthDay.inRange,.flatpickr-day.today.inRange,.flatpickr-day.prevMonthDay.today.inRange,.flatpickr-day.nextMonthDay.today.inRange,.flatpickr-day:hover,.flatpickr-day.prevMonthDay:hover,.flatpickr-day.nextMonthDay:hover,.flatpickr-day:focus,.flatpickr-day.prevMonthDay:focus,.flatpickr-day.nextMonthDay:focus{cursor:pointer;outline:0;background:#e6e6e6;border-color:#e6e6e6;}.flatpickr-day.today{border-color:#959ea9;}.flatpickr-day.today:hover,.flatpickr-day.today:focus{border-color:#959ea9;background:#959ea9;color:#fff;}.flatpickr-day.selected,.flatpickr-day.startRange,.flatpickr-day.endRange,.flatpickr-day.selected.inRange,.flatpickr-day.startRange.inRange,.flatpickr-day.endRange.inRange,.flatpickr-day.selected:focus,.flatpickr-day.startRange:focus,.flatpickr-day.endRange:focus,.flatpickr-day.selected:hover,.flatpickr-day.startRange:hover,.flatpickr-day.endRange:hover,.flatpickr-day.selected.prevMonthDay,.flatpickr-day.startRange.prevMonthDay,.flatpickr-day.endRange.prevMonthDay,.flatpickr-day.selected.nextMonthDay,.flatpickr-day.startRange.nextMonthDay,.flatpickr-day.endRange.nextMonthDay{background:#569ff7;-webkit-box-shadow:none;box-shadow:none;color:#fff;border-color:#569ff7;}.flatpickr-day.selected.startRange,.flatpickr-day.startRange.startRange,.flatpickr-day.endRange.startRange{border-radius:50px 0 0 50px;}.flatpickr-day.selected.endRange,.flatpickr-day.startRange.endRange,.flatpickr-day.endRange.endRange{border-radius:0 50px 50px 0;}.flatpickr-day.selected.startRange + .endRange,.flatpickr-day.startRange.startRange + .endRange,.flatpickr-day.endRange.startRange + .endRange{-webkit-box-shadow:-10px 0 0 #569ff7;box-shadow:-10px 0 0 #569ff7;}.flatpickr-day.selected.startRange.endRange,.flatpickr-day.startRange.startRange.endRange,.flatpickr-day.endRange.startRange.endRange{border-radius:50px;}.flatpickr-day.inRange{border-radius:0;-webkit-box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover,.flatpickr-day.prevMonthDay,.flatpickr-day.nextMonthDay,.flatpickr-day.notAllowed,.flatpickr-day.notAllowed.prevMonthDay,.flatpickr-day.notAllowed.nextMonthDay{color:#848080;background:transparent;border-color:transparent;cursor:default;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover{cursor:not-allowed;color:#d0d0d0;}.flatpickr-day.week.selected{border-radius:0;-webkit-box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;}.flatpickr-day.hidden{visibility:hidden;}.rangeMode .flatpickr-day{margin-top:1px;}.flatpickr-weekwrapper{display:inline-block;float:left;}.flatpickr-weekwrapper .flatpickr-weeks{padding:0 12px;-webkit-box-shadow:1px 0 0 #e6e6e6;box-shadow:1px 0 0 #e6e6e6;}.flatpickr-weekwrapper .flatpickr-weekday{float:none;width:100%;line-height:28px;}.flatpickr-weekwrapper span.flatpickr-day,.flatpickr-weekwrapper span.flatpickr-day:hover{display:block;width:100%;max-width:none;color:#9a9a9a;background:transparent;cursor:default;border:none;}.flatpickr-innerContainer{display:block;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;}.flatpickr-rContainer{display:inline-block;padding:0;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time{text-align:center;outline:0;display:block;height:0;line-height:40px;max-height:40px;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-time:after{content:"";display:table;clear:both;}.flatpickr-time .numInputWrapper{-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;width:40%;height:40px;float:left;}.flatpickr-time .numInputWrapper span.arrowUp:after{border-bottom-color:#4f4f4f;}.flatpickr-time .numInputWrapper span.arrowDown:after{border-top-color:#4f4f4f;}.flatpickr-time.hasSeconds .numInputWrapper{width:26%;}.flatpickr-time.time24hr .numInputWrapper{width:49%;}.flatpickr-time input{background:transparent;-webkit-box-shadow:none;box-shadow:none;border:0;border-radius:0;text-align:center;margin:0;padding:0;height:inherit;line-height:inherit;cursor:pointer;color:#4f4f4f;font-size:14px;position:relative;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time input.flatpickr-hour{font-weight:bold;}.flatpickr-time input.flatpickr-minute,.flatpickr-time input.flatpickr-second{font-weight:400;}.flatpickr-time input:focus{outline:0;border:0;}.flatpickr-time .flatpickr-time-separator,.flatpickr-time .flatpickr-am-pm{height:inherit;display:inline-block;float:left;line-height:inherit;color:#4f4f4f;font-weight:bold;width:2%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;}.flatpickr-time .flatpickr-am-pm{outline:0;width:18%;cursor:pointer;text-align:center;font-weight:400;}.flatpickr-time .flatpickr-am-pm:hover,.flatpickr-time .flatpickr-am-pm:focus{background:#f0f0f0;}.flatpickr-input[readonly]{cursor:pointer;}@-webkit-keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}}@keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}} + /*flatpickr:end*/ + </style> + </head> + <body> + <div id="wrapper" class="chkVisible print-none"> + <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> + <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + <h1>SMS Log</h1> + </div> + </div> + <div id="content"> + <div class="container-fluid marginTop"> + <div class="row"> + <!-- left --> + <div class="col-md-5 col-xs-24 print-none"> + <div class="row"> + <form method="post" id="search_list" action="/webht.php/apps/trippestOrderSync/send_operation/sms_log"> + <div class="input-group"> + <input type="text" name="order_id" value="<?php echo isset($order_id) ? $order_id : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> + <span class="input-group-addon search-btn" onclick="$('#search_list').submit();"></span> + </div> + <div id="datepicker" style="/*width: 100px;*/height: 30px;padding: 5px;">出团日期:</div> + </form> + </div> + <p class="btn-lg"></p> + </div> + <!-- end left --> + <div class=" pay_form_div col-sm-19 col-xs-24" style="min-height:1024px;border-left:1px solid #ddd;"> + <ul class="row mail_list hidden-xs"> + <a href="javascript:void(0);" style="cursor:default;color:#000;"> + <li class="col-sm-1 "><strong>#</strong></li> + <li class="col-sm-5 "><strong>团号</strong></li> + <li class="col-sm-2 "><strong>项目</strong></li> + <li class="col-sm-6 "><strong>地接安排</strong></li> + <li class="col-sm-3 "><strong>短信通知</strong></li> + <li class="col-sm-4 print-none"><strong>操作</strong></li> + </a> + </ul> + <?php + foreach ($list as $key => $item) { + ?> + <ul class="row mail_list"> + + <li class="col-sm-1 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo ($key + 1); ?></li> + <li class="col-sm-5 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"> + <?php echo $item->COLI_groupCode; ?> + </li> + + <li class="col-sm-2 nopadding-L" style="overflow:hidden;word-break: break-all;"> + <?php + echo $item->PAG_Code; + ?> + </li> + + <li class="col-sm-6 nopadding-L" style="overflow:hidden;word-break: break-all;" > + <?php echo $item->GCOD_startDate; ?> <br> + <?php echo $item->GCOD_dutyName; ?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $item->GCOD_dutyTel; ?> + </li> + + <li class="col-sm-3 nopadding-L" style="overflow:hidden;word-break: break-all;"> + <?php + if ($item->send_state == "1") { + echo "已发送"; // 查看短信内容 + } elseif ($item->send_state == "0") { + echo '<a href="javascript:void(0)" onclick="show_order_sms(' . $item->COLI_SN . ');" class="text-primary">查看失败信息</a>'; + } else { + echo "未发"; + } + ?> + </li> + <li class="col-sm-4 nopadding-L print-none" > + <a href="javascript:void(0)" onclick="refresh_gcod(<?php echo $item->COLI_SN; ?>)" class="text-primary">刷新地接安排</a> + <?php + if ($item->send_state == "1") { + } else { + echo ' | <a href="javascript:void(0)" onclick="handle_send(\'' . $item->COLI_ID . '\');" class="text-primary">重发</a>'; + } + ?> + + </li> + </ul> + + <?php } ?> + </div> + <!-- </div> --> + <div class="pay_footer text-right print-none clear " > + <p>© 1998 China Highlights. + <a href="https://www.chinahighlights.com/privacy.htm" rel="nofollow">Privacy Statement</a> + </p> + </div> + </div> + </div> + </div> + <div id="main" class="container"> + </div> + + <!-- 查看失败信息 --> + <div class="modal" id="modal_set_orderid" tabindex="-1" role="dialog" aria-labelledby="orderidModalLabel"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="orderidModalLabel">查看短信发送记录</h4> + </div> + <div class="modal-body" id="modal_set_orderid_body"> + ... + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> + </div> + </div> + </div> + </div> + + <div class="modal" role="dialog" id="loading"> + <img src="https://data.chinahighlights.com/pic/flight-loading.gif" class="center-block" style="margin-top: 50px;"> + </div> + + </body> + <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js&v=20170811" type="text/javascript"></script> + <script type="text/javascript"> + jQuery.browser={};(function(){jQuery.browser.msie=false; jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})(); + </script> + <script src="//data.chinahighlights.com/js/min.php?f=/public/js/bootstrap.min.js,/js/jquery.form.min.js,/js/flatpickr-4.4.4.min.js&v=20170811" type="text/javascript"></script> + <script language="javascript"> + $(document).ready(function() { + $("#datepicker").flatpickr({ + inline: true, + dateFormat: "Y-m-d", + defaultDate: "<?php echo $date; ?>", + onChange: function (selectedDates, dateStr, instance) { + window.location.href = '/webht.php/apps/trippestOrderSync/send_operation/sms_log?date=' + dateStr; + } + }); + }); + function show_order_sms(coli_sn) { + $.ajax({ + type: "get", + dataType: "json", + url: "/webht.php/apps/trippestOrderSync/send_operation/order_sms_list/" + coli_sn, + beforeSend: function () { + $('#loading').modal('show'); + }, + success: function(data, textStatus) { + $('#modal_set_orderid_body').html(data); + $('#modal_set_orderid').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }).done(function () { + $('#loading').modal('hide'); + }); + } + function refresh_gcod(coli_sn) { + $.ajax({ + type: "get", + // dataType: "json", + url: "http://www.mycht.cn/webht.php/apps/trippestOrderSync/TulanduoApi/insert_HT_order_operation/" + coli_sn, + beforeSend: function () { + $('#loading').modal('show'); + }, + success: function(data) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }).done(function () { + $('#loading').modal('hide'); + }); + } + function handle_send(coli_sn) { + $.ajax({ + type: "get", + // dataType: "json", + url: "/webht.php/apps/trippestOrderSync/send_operation/daytour/" + coli_sn, + beforeSend: function () { + $('#loading').modal('show'); + }, + success: function(data) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }).done(function () { + $('#loading').modal('hide'); + }); + } + </script> +</html> From c434f2ed998f152fe8bfd2c8a0eb723780e5ce48 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 11 Oct 2018 16:25:03 +0800 Subject: [PATCH 160/382] =?UTF-8?q?[+]=E6=94=B6=E6=AC=BE=E5=90=8E=E6=89=A7?= =?UTF-8?q?=E8=A1=8CHT=E4=BB=BB=E5=8A=A1;=20[+]=E4=BB=85=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E9=83=A8=E5=88=86=E7=8A=B6=E6=80=81=E7=9A=84=E5=95=86=E5=8A=A1?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=B8=BA13-=E6=96=B0=E8=AE=A2=E5=8D=95(?= =?UTF-8?q?=E5=B7=B2=E6=94=AF=E4=BB=98);=20=E5=85=B3=E9=97=ADipaylinks?= =?UTF-8?q?=E6=89=B9=E9=87=8F=E6=9F=A5=E8=AF=A2=E6=8E=A5=E5=8F=A3;=20?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E5=8C=B9=E9=85=8D=E5=88=B0?= =?UTF-8?q?=E5=A4=9A=E4=B8=AA=E8=AE=A2=E5=8D=95=E4=B8=8D=E5=A4=84=E7=90=86?= =?UTF-8?q?;=20=E6=94=AF=E6=8C=81=E6=89=8B=E5=B7=A5=E5=BD=95=E5=85=A5APP?= =?UTF-8?q?=E7=BB=84=E7=9A=84=E6=94=B6=E6=AC=BE;=20=E8=BD=AC=E7=A7=BB?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E6=97=B6=E5=8C=85=E6=8B=AC?= =?UTF-8?q?=E6=89=8B=E5=B7=A5=E5=BD=95=E5=85=A5=E4=BA=A4=E6=98=93=E5=8F=B7?= =?UTF-8?q?=E7=9A=84=E8=AE=B0=E5=BD=95;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/paypal.php | 7 +- .../pay/controllers/AlipayTradeService.php | 10 +-- .../pay/controllers/iPayLinksService.php | 80 +++++++++++++------ webht/third_party/pay/models/Alipay_model.php | 33 +++++--- .../pay/models/IPayLinks_model.php | 55 ++++++++----- webht/third_party/pay/views/gai_setting.php | 10 ++- webht/third_party/pay/views/note_setting.php | 1 + .../third_party/paypal/controllers/index.php | 60 +++++++++----- .../paypal/models/paypal_model.php | 43 ++++++---- webht/third_party/paypal/views/note_list.php | 1 - .../third_party/paypal/views/note_setting.php | 5 +- 11 files changed, 198 insertions(+), 107 deletions(-) diff --git a/webht/third_party/pay/config/paypal.php b/webht/third_party/pay/config/paypal.php index 335d05d8..70dcceaa 100644 --- a/webht/third_party/pay/config/paypal.php +++ b/webht/third_party/pay/config/paypal.php @@ -15,10 +15,9 @@ $config['currency'] = "USD"; $config['token_url'] = "https://api.paypal.com/v1/oauth2/token"; $config['web_profiles_url'] = "https://api.paypal.com/v1/payment-experience/web-profiles/"; $config['webhooks_url'] = "https://api.paypal.com/v1/notifications/webhooks"; -$config['payment_url'] = "https://api.paypal.com/v1/payments/payment/"; -$config['sale_url'] = "https://api.paypal.com/v1/payments/sale/"; -// $config['activities_url'] = "https://api.paypal.com/v1/activities/activities"; -// $config['reporting_url'] = "https://api.paypal.com/v1/reporting/transactions"; +$config['payment_url'] = "https://api.paypal.com/v1/payments/payment"; +$config['sale_url'] = "https://api.paypal.com/v1/payments/sale"; +$config['activities_url'] = "https://api.paypal.com/v1/activities/activities"; $config['return_url'] = "https://www.chinahighlights.com"; $config['cancel_url'] = "https://www.chinahighlights.com"; diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index e0cd7ccf..80b0d260 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -402,20 +402,16 @@ class AlipayTradeService extends CI_Controller $ht_memo ); // 更新订单主表付款方式,防止没访问thankyou-train.asp - if (empty($advisor_info->COLI_PayManner)) { - $this->Alipay_model->update_paymanner($GAI_COLI_SN); - } - if ($advisor_info->COLI_Department == 10) { + $this->Alipay_model->update_paymanner($GAI_COLI_SN); // 把订单状态设置为13-新订单已支付 $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); - } } } //更新还没有填的客邮和交易号de收款记录(传统订单) elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; - $this->Alipay_model->add_tour_account_info( + $gai_sn = $this->Alipay_model->add_tour_account_info( $GAI_COLI_SN, $item->ALI_orderAmount, $item->ALI_acquiringTime, @@ -430,6 +426,8 @@ class AlipayTradeService extends CI_Controller ); //添加汉特的订单提醒 $this->Alipay_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->ALI_currencyCode) . $item->ALI_orderAmount); + // 添加HT任务 + $this->Alipay_model->exec_addToTask($gai_sn); } } diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 6db9d8b6..07154dd8 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -286,6 +286,18 @@ class IPayLinksService extends CI_Controller $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); return; } + public function query_refund($refund_order_id) + { + $this->query_info_arr["queryOrderId"] = $this->create_guid(); + $this->query_info_arr["orderId"] = $refund_order_id; + $this->query_info_arr['mode'] = '1'; + $this->query_info_arr['type'] = '2'; + $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); + $resp = $this->curl($this->queryUrl,$this->query_info_arr); + $resp_obj = simplexml_load_string($resp); + $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); + return; + } public function query_pay_list($day_offset = 3) { @@ -432,9 +444,23 @@ class IPayLinksService extends CI_Controller //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - // $this->IPayLinks_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->IPL_dealId, $ht_memo); - // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 - // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + $this->IPayLinks_model->add_account_info_forAPP( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->IPL_orderAmount, + $item->IPL_completeTime, + mb_strtoupper($item->currencyCode), + $ssje, + $item->IPL_completeTime, + $item->IPL_completeTime, + $item->IPL_acquiringTime, + $item->IPL_payerName, + $item->IPL_payerEmail, + $item->IPL_dealId, + $ht_memo); + // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { + // //只修改APP组的订单状态,并且订单进度是我的订单 + // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); //把订单状态改为已付款 // } } else { $this->IPayLinks_model->add_account_info( @@ -452,10 +478,8 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); - if ($advisor_info->COLI_Department == 10) { // 把订单状态设置为13-新订单已支付 $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); - } // 更新订单主表付款方式,防止没访问thankyou-train.asp if (empty($advisor_info->COLI_PayManner)) { $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); @@ -466,7 +490,7 @@ class IPayLinksService extends CI_Controller elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; - $this->IPayLinks_model->add_tour_account_info( + $gai_sn = $this->IPayLinks_model->add_tour_account_info( $GAI_COLI_SN, $item->IPL_orderAmount, $item->IPL_acquiringTime, @@ -482,6 +506,8 @@ class IPayLinksService extends CI_Controller ); //添加汉特的订单提醒 $this->IPayLinks_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->IPL_currencyCode) . $item->IPL_orderAmount); + // 添加HT任务 + $this->IPayLinks_model->exec_addToTask($gai_sn); } } @@ -951,7 +977,7 @@ class IPayLinksService extends CI_Controller $neworder = $this->input->post('pn_invoice'); $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); - $orderid_info = $this->analysis_orderid($data['note'][0]->IPL_orderId); + $orderid_info = $this->analysis_orderid($data['note']->IPL_orderId); if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); if ($orderid_info->ordertype === 'T') { @@ -1056,25 +1082,26 @@ class IPayLinksService extends CI_Controller //修改订单名 public function note_modal_save() { - $data = array(); - - $pn_txn_id = $this->input->post('pn_txn_id'); - $pn_invoice = $this->input->post('pn_invoice'); - - if (!empty($pn_txn_id) && !empty($pn_invoice)) { - $orderid_info = $this->analysis_orderid($pn_invoice); - if (!empty($orderid_info)) { - $orderid_info = json_decode($orderid_info); - $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); - if (!empty($advisor_info)) { - $this->Note_model->set_invoice($pn_txn_id, $pn_invoice); - $this->batch_send_note($pn_txn_id); - echo json_encode('修改成功!'); - return true; - } - } - } - echo json_encode('没找到数据!'); + $this->gai_modal_save(); + // $data = array(); + + // $pn_txn_id = $this->input->post('pn_txn_id'); + // $pn_invoice = $this->input->post('pn_invoice'); + + // if (!empty($pn_txn_id) && !empty($pn_invoice)) { + // $orderid_info = $this->analysis_orderid($pn_invoice); + // if (!empty($orderid_info)) { + // $orderid_info = json_decode($orderid_info); + // $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + // if (!empty($advisor_info)) { + // $this->Note_model->set_invoice($pn_txn_id, $pn_invoice); + // $this->batch_send_note($pn_txn_id); + // echo json_encode('修改成功!'); + // return true; + // } + // } + // } + // echo json_encode('没找到数据!'); return; } @@ -1106,6 +1133,7 @@ class IPayLinksService extends CI_Controller */ public function get_refund_list($daylength=3) { + return false; // ipaylinks的批量查询接口已关闭 bcscale(2); $ret = array(); $list = $this->refund_list_info($daylength); diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 97600764..82deefb8 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -18,7 +18,7 @@ class Alipay_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class Alipay_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class Alipay_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class Alipay_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class Alipay_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -68,10 +68,14 @@ class Alipay_model extends CI_Model { } //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序,取最新的数据) - if (!empty($result)) { + if (!empty($result) && is_array($result) ) { //print_r($result[0]); //die(); - $result = $result[0]; + if (count($result) > 1) { + $result = array(); + } else { + $result = $result[0]; + } } return $result; @@ -119,7 +123,7 @@ class Alipay_model extends CI_Model { $sql = " UPDATE BIZ_ConfirmLineInfo SET COLI_State = ? - WHERE COLI_SN = ? + WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; @@ -217,7 +221,7 @@ class Alipay_model extends CI_Model { ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); - return $query; + return $insertid; } //更新线路提醒 @@ -299,4 +303,15 @@ class Alipay_model extends CI_Model { $query = $this->HT->query($sql, array($paymanner, $COLI_SN)); return $query; } + + /** JJH: 添加订单收款记录之后执行 */ + public function exec_addToTask($GAI_SN) + { + $sql = " if not exists ( + select top 1 1 from Sysautotask + where SAT_Type=1 and SAT_SourceSN=$GAI_SN + ) exec SP_AddToSystask 1," . $GAI_SN; + $query = $this->HT->query($sql); + return $query; + } } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index ff8af136..8ac260b2 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -18,7 +18,7 @@ class IPayLinks_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class IPayLinks_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class IPayLinks_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class IPayLinks_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class IPayLinks_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -68,10 +68,14 @@ class IPayLinks_model extends CI_Model { } //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序,取最新的数据) - if (!empty($result)) { + if (!empty($result) && is_array($result) ) { //print_r($result[0]); //die(); - $result = $result[0]; + if (count($result) > 1) { + $result = array(); // 找到多条匹配的订单记录时,不处理 + } else { + $result = $result[0]; + } } return $result; @@ -119,20 +123,20 @@ class IPayLinks_model extends CI_Model { $sql = " UPDATE BIZ_ConfirmLineInfo SET COLI_State = ? - WHERE COLI_SN = ? + WHERE COLI_SN = ? and COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; } //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 - public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_COLI_SN = ? AND GAI_SQJE=? + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN @@ -141,6 +145,7 @@ class IPayLinks_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -150,8 +155,8 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -197,7 +202,7 @@ class IPayLinks_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') AND DeleteFlag=0 ) INSERT INTO GroupAccountInfo ( GAI_COLI_SN @@ -218,7 +223,7 @@ class IPayLinks_model extends CI_Model { ) VALUES (?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); - return $query; + return $insertid; } //更新线路提醒 @@ -309,9 +314,11 @@ class IPayLinks_model extends CI_Model { //根据交易号获取收款记录(传统订单) public function get_money_t($pn_invoice) { - $sql = "SELECT GroupAccountInfo.* + $like = $this->HT->escape_like_str($pn_invoice); + $sql = "SELECT COLI_ID,GroupAccountInfo.* from GroupAccountInfo - where GAI_Type='15018' and DeleteFlag=0 and GAI_AccreditNo=? + inner join ConfirmLineInfo coli on COLI_SN=GAI_COLI_SN + where GAI_Type='15018' and GroupAccountInfo.DeleteFlag=0 and (GAI_AccreditNo=? or GAI_Memo like '%$like%') "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -319,9 +326,11 @@ class IPayLinks_model extends CI_Model { } //根据交易号获取收款记录(商务订单) public function get_money_b($pn_invoice) { - $sql = "SELECT BIZ_GroupAccountInfo.* + $like = $this->HT->escape_like_str($pn_invoice); + $sql = "SELECT COLI_ID,BIZ_GroupAccountInfo.* from BIZ_GroupAccountInfo - where GAI_Type='15018' and DeleteFlag=0 and GAI_AccreditNo=? + inner join BIZ_ConfirmLineInfo on COLI_SN=GAI_COLI_SN + where GAI_Type='15018' and BIZ_GroupAccountInfo.DeleteFlag=0 and (GAI_AccreditNo=? or GAI_Memo like '%$like%') "; $query = $this->HT->query($sql, array($pn_invoice)); $result = $query->result(); @@ -353,4 +362,14 @@ class IPayLinks_model extends CI_Model { $query = $this->HT->query($sql, array($deadId)); return $query; } + /** JJH: 添加订单收款记录之后执行 */ + public function exec_addToTask($GAI_SN) + { + $sql = " if not exists ( + select top 1 1 from Sysautotask + where SAT_Type=1 and SAT_SourceSN=$GAI_SN + ) exec SP_AddToSystask 1," . $GAI_SN; + $query = $this->HT->query($sql); + return $query; + } } diff --git a/webht/third_party/pay/views/gai_setting.php b/webht/third_party/pay/views/gai_setting.php index 70be2c9b..06808d0c 100644 --- a/webht/third_party/pay/views/gai_setting.php +++ b/webht/third_party/pay/views/gai_setting.php @@ -3,15 +3,19 @@ <p>已录入订单 <?php echo!empty($old_order) ? $old_order : ""; ?></p> <table class="table table-hover table-bordered"> <thead> + <th>订单号</th> <th>申请金额/币种</th> <th>实收金额</th> </thead> + <?php foreach ($gai_info as $key => $value) { ?> <tr> - <td><?php echo $gai_info[0]->GAI_SQJE; ?>&nbsp;<?php echo $gai_info[0]->GAI_SQJECurrency; ?></td> - <td><?php echo $gai_info[0]->GAI_SSJE; ?>&nbsp;CNY</td> + <td><?php echo $value->COLI_ID; ?></td> + <td><?php echo $value->GAI_SQJE; ?>&nbsp;<?php echo $value->GAI_SQJECurrency; ?></td> + <td><?php echo $value->GAI_SSJE; ?>&nbsp;CNY</td> </tr> + <?php } ?> </table> - <p>撤回以上订单收款记录, 并转移到订单: </p> + <p>撤回以上订单收款记录, 并转移到订单: (手动录入的不会撤回) </p> <?php } ?> <div class="input-group"> <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo $new_order; ?>" placeholder="输入订单号" > diff --git a/webht/third_party/pay/views/note_setting.php b/webht/third_party/pay/views/note_setting.php index 400e6952..973aef58 100644 --- a/webht/third_party/pay/views/note_setting.php +++ b/webht/third_party/pay/views/note_setting.php @@ -48,4 +48,5 @@ </dl> <input type="hidden" name="pn_txn_id" id="pn_txn_id" value="<?php echo $note->IPL_dealId; ?>" /> + <input type="hidden" name="pn_id" id="pn_id" value="<?php echo $note->IPL_sn; ?>" /> </form> diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 472e3bec..36724256 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -189,6 +189,21 @@ class Index extends CI_Controller { echo ('更新了' . ($result_count) . '条记录'); } + public function get_transactions_detail_by_paymentToken() + { + $token = $this->input->post("t"); + $base = $this->base(0); + // $post = "METHOD=GetTransactionDetails&VERSION=100.0&TRANSACTIONID=$token"; + // $post = "METHOD=GetExpressCheckoutDetails&VERSION=124.0&TOKEN=$token"; + + $token = str_replace(' ', 'T', $token) . 'Z'; + $post = "METHOD=TransactionSearch&VERSION=100.0&TRANSACTIONCLASS=ALL&STARTDATE=$token"; + + $detail = $this->call($base, $post); + var_dump($detail); + return; + } + //根据交易号获取交易详细信息 public function get_transactions_detail($redirect = 0) { //从数据库提取一条还没有更新交易详情的记录获取交易号 @@ -804,10 +819,8 @@ class Index extends CI_Controller { $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); - if ($advisor_info->COLI_Department == 10) { // 把订单状态设置为13-新订单已支付 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); - } } } //更新还没有填的客邮和交易号de收款记录(传统订单) @@ -815,9 +828,11 @@ class Index extends CI_Controller { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); - $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); + // 添加HT任务 + $this->Paypal_model->exec_addToTask($gai_sn); } } @@ -927,25 +942,26 @@ class Index extends CI_Controller { //修改订单名 public function note_modal_save() { - $data = array(); - - $pn_txn_id = $this->input->post('pn_txn_id'); - $pn_invoice = $this->input->post('pn_invoice'); - - if (!empty($pn_txn_id) && !empty($pn_invoice)) { - $orderid_info = $this->analysis_orderid($pn_invoice); - if (!empty($orderid_info)) { - $orderid_info = json_decode($orderid_info); - $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); - if (!empty($advisor_info)) { - $this->Note_model->set_invoice($pn_txn_id, $pn_invoice); - $this->send_note($pn_txn_id); - echo json_encode('修改成功!'); - return true; - } - } - } - echo json_encode('没找到数据!'); + $this->gai_modal_save(); + // $data = array(); + + // $pn_txn_id = $this->input->post('pn_txn_id'); + // $pn_invoice = $this->input->post('pn_invoice'); + + // if (!empty($pn_txn_id) && !empty($pn_invoice)) { + // $orderid_info = $this->analysis_orderid($pn_invoice); + // if (!empty($orderid_info)) { + // $orderid_info = json_decode($orderid_info); + // $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + // if (!empty($advisor_info)) { + // $this->Note_model->set_invoice($pn_txn_id, $pn_invoice); + // $this->send_note($pn_txn_id); + // echo json_encode('修改成功!'); + // return true; + // } + // } + // } + // echo json_encode('没找到数据!'); } //关闭note通知,用于手动处理通知后 diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index b2d116bb..f65a9675 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,7 +19,7 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -27,7 +27,7 @@ class Paypal_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -37,7 +37,7 @@ class Paypal_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -45,7 +45,7 @@ class Paypal_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 1 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -61,7 +61,7 @@ class Paypal_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 1 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -69,10 +69,14 @@ class Paypal_model extends CI_Model { } //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序,取最新的数据) - if (!empty($result)) { + if (!empty($result) && is_array($result) ) { //print_r($result[0]); //die(); - $result = $result[0]; + if (count($result) > 1) { + $result = array(); + } else { + $result = $result[0]; + } } return $result; @@ -120,7 +124,7 @@ class Paypal_model extends CI_Model { $sql = " UPDATE BIZ_ConfirmLineInfo SET COLI_State = ? - WHERE COLI_SN = ? + WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; @@ -133,7 +137,7 @@ class Paypal_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_COLI_SN = ? AND GAI_SQJE=? + WHERE GAI_COLI_SN = ? AND GAI_SQJE=? AND DeleteFlag=0 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN @@ -166,7 +170,7 @@ class Paypal_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') AND DeleteFlag=0 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN @@ -199,7 +203,7 @@ class Paypal_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM GroupAccountInfo - WHERE GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%' + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 ) INSERT INTO GroupAccountInfo ( GAI_COLI_SN @@ -220,7 +224,7 @@ class Paypal_model extends CI_Model { ) VALUES (?,15002,?,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); - return $query; + return $insertid; } //更新线路提醒 @@ -254,10 +258,6 @@ class Paypal_model extends CI_Model { return $query; } - public function note_list() { - - } - public function save_paypal_msg($pm_transaction_id, $pm_orderid, $pm_item_name, $pm_money, $pm_currency, $pm_payer, $pm_payer_email, $pm_payer_status, $pm_memo, $pm_payment_date, $pm_pay_type) { $sql = "INSERT INTO paypal_msg ( pm_transaction_id @@ -554,4 +554,15 @@ class Paypal_model extends CI_Model { $query = $this->HT->query($sql, array($deadId)); return $query; } + + /** JJH: 添加订单收款记录之后执行 */ + public function exec_addToTask($GAI_SN) + { + $sql = " if not exists ( + select top 1 1 from Sysautotask + where SAT_Type=1 and SAT_SourceSN=$GAI_SN + ) exec SP_AddToSystask 1," . $GAI_SN; + $query = $this->HT->query($sql); + return $query; + } } diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 69e711d3..ba5903c4 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -266,7 +266,6 @@ } function show_gai_modal(pn_txn_id, pn_id, new_order) { - $('#modal_set_gai').modal('show'); var url = '/webht.php/apps/paypal/index/gai_modal/' + pn_txn_id + '/' + pn_id; if (new_order) url += '/' + new_order; $.ajax({ diff --git a/webht/third_party/paypal/views/note_setting.php b/webht/third_party/paypal/views/note_setting.php index 1cf1a5a3..5138d92c 100644 --- a/webht/third_party/paypal/views/note_setting.php +++ b/webht/third_party/paypal/views/note_setting.php @@ -30,7 +30,7 @@ <dl class="dl-horizontal"> <dt>订单号</dt> - <dd> + <dd> <div class="input-group"> <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo!empty($pn_invoice) ? $pn_invoice : $note->pn_invoice; ?>"> <span class="input-group-btn"> @@ -66,4 +66,5 @@ </dl> <input type="hidden" name="pn_txn_id" id="pn_txn_id" value="<?php echo $note->pn_txn_id ?>" /> -</form> \ No newline at end of file + <input type="hidden" name="pn_id" id="pn_id" value="<?php echo $note->pn_sn; ?>" /> +</form> From ba182a014a9b7f804930d570228918144632085b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 11 Oct 2018 18:13:34 +0800 Subject: [PATCH 161/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8=E8=AE=A1?= =?UTF-8?q?=E7=AE=97:=20=E8=A7=A3=E6=9E=90=E4=BA=A7=E5=93=81=E7=BC=96?= =?UTF-8?q?=E5=8F=B7=E6=97=B6=E7=BB=9F=E4=B8=80=E5=A4=A7=E5=B0=8F=E5=86=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index cf49a170..8e9e6b4d 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -245,7 +245,7 @@ class Order_finance extends CI_Controller { return null; } $ret->coli_sn = $coli_sn; - $all_pags = array_map(function($ele){ return $ele->PAG_Code;}, $all_orders); + $all_pags = array_map(function($ele){ return mb_strtoupper($ele->PAG_Code);}, $all_orders); $all_pag = array_unique($all_pags); $combine_pag_arr = array(); $pvt_code = $this->forbidden_combine(); @@ -275,7 +275,7 @@ class Order_finance extends CI_Controller { $all_orders[] = $ve; } // 重新计算重复次数 - $all_pags = array_filter(array_map(function($ele){ return $ele->PAG_Code;}, $all_orders)); + $all_pags = array_filter(array_map(function($ele){ return mb_strtoupper($ele->PAG_Code);}, $all_orders)); // 重复的产品号; 可混拼的产品 $repeat_code = array(); $code_count = array_count_values($all_pags); @@ -284,7 +284,7 @@ class Order_finance extends CI_Controller { continue; } $tmp = null; - $tmp = $this->get_allowed_combine($vp); + $tmp = $this->get_allowed_combine(mb_strtoupper($vp)); $this_allowed = ($tmp === null) ? null : array_diff($tmp, $all_pag); // diff((31,41), (31,41,47)) ==> () // $this_allowed = ($tmp === null) ? null : array_diff($all_pag, $tmp); // diff((31,41), (31,41,47)) ==> () if (empty($this_allowed) && $tmp !== null) { @@ -310,10 +310,10 @@ class Order_finance extends CI_Controller { } $ret->combine_pags = my_array_unique($combine_pag_arr); $ret->combine_pags = $ret->combine_pags[0]; // 这里用0是因为一个拼团应该只有一组或一个产品 - // 一些不再常规混拼的团, 仅有一个拼团号的订单则加上该团 + // 一些不在常规混拼的团, 仅有一个拼团号的订单则加上该团 foreach ($all_orders as $key => $value) { if ($value->combine_cnt === 1) { - $ret->combine_pags[] = $value->PAG_Code; + $ret->combine_pags[] = mb_strtoupper($value->PAG_Code); } } $ret->combine_pags = array_values(array_unique($ret->combine_pags)); @@ -323,11 +323,11 @@ class Order_finance extends CI_Controller { $pag_sns = array(); $unique_coli = array(); foreach ($all_orders as $ko => $vo) { - if (in_array($vo->PAG_Code, $ret->combine_pags)) { + if (in_array(mb_strtoupper($vo->PAG_Code), $ret->combine_pags)) { $pag_sns[] = $vo->COLD_ServiceSN; // 整团单拼时, 避免重复计算人数 // 订单人数不重复计 - if ( ! in_array($vo->PAG_Code, $pvt_code) && ! in_array($vo->COLI_SN, $unique_coli)) { + if ( ! in_array(mb_strtoupper($vo->PAG_Code), $pvt_code) && ! in_array($vo->COLI_SN, $unique_coli)) { $unique_coli[] = $vo->COLI_SN; $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum; } @@ -338,9 +338,9 @@ class Order_finance extends CI_Controller { $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; $tour_s->adult_num = $vo->COLD_PersonNum; $tour_s->child_num = $vo->COLD_ChildNum; - $tour_s->PAG_code = $vo->PAG_Code; + $tour_s->PAG_code = mb_strtoupper($vo->PAG_Code); // $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; - $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : $vo->PAG_Code; + $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : mb_strtoupper($vo->PAG_Code); $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; $tour_s->totalPrice = $vo->COLD_TotalPrice; $ret->order_cost[] = $tour_s; @@ -386,7 +386,7 @@ class Order_finance extends CI_Controller { $ret->totalPrice = bcadd($ret->totalPrice, $val->COLD_TotalPrice); } // 预定的产品数 - $ret->tour_count = count(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $all_orders))); + $ret->tour_count = count(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $all_orders))); $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); $ret->person_num = $person_num->person_num; $ret->adult_num = $person_num->adult_num; @@ -400,7 +400,7 @@ class Order_finance extends CI_Controller { $ret->comment = "PVT,共" . $ret->person_num . "人"; $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); - $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->PAG_Code;}, $pags_info)))); + $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $pags_info)))); $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; return $ret; From d982e1ef1c13c21ac28728eae1717fc6e922b0e8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 12 Oct 2018 09:32:24 +0800 Subject: [PATCH 162/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E8=8E=B7=E5=8F=96=E5=BE=85=E5=90=8C=E6=AD=A5=E7=9A=84?= =?UTF-8?q?sql?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 3 ++ .../trippestOrderSync/models/orders_model.php | 52 +++++++++++++------ 2 files changed, 40 insertions(+), 15 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index b2054ddf..7f8b086a 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -194,6 +194,9 @@ class TulanduoApi extends CI_Controller $startDate = date('Y-m-d'); $endDate = date('Y-m-d', strtotime("+2 days")); $to_update_list = $this->Orders_model->get_groupCombineInfo(0, null, $startDate, $endDate); + if (empty($to_update_list)) { + $to_update_list = $this->Orders_model->get_groupCombineInfo_finance(); + } } if (empty($to_update_list)) { return false; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index be08730d..6fd1032c 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -152,26 +152,48 @@ class Orders_model extends CI_Model { and gci.GCI_createTime < '" . date($createTime_format) . "' "; } // 近期的订单同步完成之后, 同步历史数据 - $sql .= " UNION ALL "; - $sql .= " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, - cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' - from GroupCombineInfo gci - inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' - LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN - and coli.COLI_State<>50 - and (select OPI_DEI_SN from OperatorInfo where OPI_SN=coli.COLI_OPI_ID)=30 - LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN - where - GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' - and gci.GCI_createTime < '" . date('Y-m-d') . "' - and GCI_combineNo not like '%取消%' - "; + // 这个sql很慢, 导致锁表, 分开处理 + // $sql .= " UNION ALL "; + // $sql .= " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + // cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' + // from GroupCombineInfo gci + // inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' + // LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + // and coli.COLI_State<>50 + // and (select OPI_DEI_SN from OperatorInfo where OPI_SN=coli.COLI_OPI_ID)=30 + // LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + // where + // GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') + // and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + // and gci.GCI_createTime < '" . date('Y-m-d') . "' + // and GCI_combineNo not like '%取消%' + // "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; $query = $this->HT->query($sql); return $query->result(); } + public function get_groupCombineInfo_finance() + { + $sql = " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' + from GroupCombineInfo gci + inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + and coli.COLI_State<>50 + and (select OPI_DEI_SN from OperatorInfo where OPI_SN=coli.COLI_OPI_ID)=30 + LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + where + GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') + and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + and gci.GCI_createTime < '" . date('Y-m-d') . "' + and GCI_combineNo not like '%取消%' + "; + $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; + $query = $this->HT->query($sql); + return $query->result(); + } + /*! * 获取团计划信息的记录 - 根据地接社订单id * 计划变更和订单状态确认时使用 From 6a2de280c35ba7092c7f6d4782e1ced9de12fb8b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 12 Oct 2018 15:26:34 +0800 Subject: [PATCH 163/382] ... --- .../{TulanduoApi.php => Tulanduo.php} | 4 +- .../vendorPlanSync/controllers/index.php | 16 +- .../vendorPlanSync/models/orders_model.php | 1801 +++++++++++++++++ 3 files changed, 1817 insertions(+), 4 deletions(-) rename webht/third_party/vendorPlanSync/controllers/{TulanduoApi.php => Tulanduo.php} (99%) create mode 100644 webht/third_party/vendorPlanSync/models/orders_model.php diff --git a/webht/third_party/vendorPlanSync/controllers/TulanduoApi.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php similarity index 99% rename from webht/third_party/vendorPlanSync/controllers/TulanduoApi.php rename to webht/third_party/vendorPlanSync/controllers/Tulanduo.php index baddabc4..37d4f782 100644 --- a/webht/third_party/vendorPlanSync/controllers/TulanduoApi.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -3,7 +3,7 @@ if (!defined('BASEPATH')) exit('No direct script access allowed'); -class TulanduoApi extends CI_Controller +class Tulanduo extends CI_Controller { public $special_route = array( "BJSIC-42" => "'BJSIC-41','BJSIC-42'" @@ -53,8 +53,6 @@ class TulanduoApi extends CI_Controller public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; - // 发送到图兰朵系统接口的参数jsonParams - public function __construct(){ parent::__construct(); mb_regex_encoding("UTF-8"); diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index e189575c..3ffd8e9d 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -3,9 +3,23 @@ defined('BASEPATH') OR exit('No direct script access allowed'); class Index extends CI_Controller { + public function __construct(){ + parent::__construct(); + mb_regex_encoding("UTF-8"); + bcscale(4); + $this->load->helper('array'); + $this->load->model('Orders_model'); + } + public function index() { - echo "string"; + } + + public function push($COLI_ID) + { + $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID); + if(empty($orderinfo)) {return;} + return $this->output->set_content_type('application/json')->set_output(json_encode($orderinfo)); } } diff --git a/webht/third_party/vendorPlanSync/models/orders_model.php b/webht/third_party/vendorPlanSync/models/orders_model.php new file mode 100644 index 00000000..78bfb4aa --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/orders_model.php @@ -0,0 +1,1801 @@ +<?php + +/*! + * 这里操作的都是商务表, 传统订单的表不在这里 + */ + +class Orders_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + //读取默认配置 + $this->COLI_WebCode = $this->config->item('Site_Code'); + $this->COLI_Area = $this->config->item('Site_Area'); + $this->COLI_CustomerType = $this->config->item('Site_DepartmentID'); + $this->COLI_department = $this->config->item('Site_Department'); + $this->COLI_Currency = $this->config->item('Site_Currency'); + $this->COLI_InterestRate = $this->config->item('Site_InterestRate'); + $this->COLI_TrueCardRate = $this->config->item('Site_TrueCardRate'); + $this->COLI_TouristLGC = $this->config->item('Site_ServiceLGC'); + $this->COLI_OrderStartDate = null; + $this->COLI_Keywords = NULL; + switch ($this->check_device()) { + case 'mobile': + $this->COLI_OrderSource = '62003'; + break; + case 'tablet': + $this->COLI_OrderSource = '62002'; + break; + default: + $this->COLI_OrderSource = '62001'; + } + } + + public function get_orderinfo_detail($COLI_ID) + { + $sql = "SELECT top 1 coli.COLI_ID, + coli.COLI_Department, + cold.COLD_ServiceSN, + cold.COLD_ServiceSN2, + cold.COLD_ServiceCity, + gut.GUT_NationalityID, + * + FROM BIZ_ConfirmLineInfo coli + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + LEFT JOIN BIZ_GUEST gut ON gut.GUT_SN=coli.COLI_GUT_SN + WHERE coli.COLI_ID='$COLI_ID' + ORDER BY COLI_ApplyDate DESC"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_guestlist($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /*! + * 获取行程详情 + */ + /** 根据订号 */ + public function get_scheduleDetails($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN AND (PAG2_LGC = 2) + left join BIZ_PackageInfoSub pis on pis.PAGS_PAG_SN=pag.PAG_SN and PAGS_LGC=1 and cold.COLD_ServiceSN2=PAGS_SN + WHERE COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + /** 根据线路代号 */ + public function get_packageDetails($pag_code_str) + { + $sql = "SELECT * + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 + WHERE pag.PAG_Code IN ($pag_code_str) + order by pag.PAG_Code "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_paymentDetails($COLI_ID) + { + $sql = "SELECT * + FROM BIZ_GroupAccountInfo bgai + INNER JOIN BIZ_ConfirmLineInfo coli ON bgai.GAI_COLI_SN=coli.COLI_SN + WHERE coli_ID = '$COLI_ID'"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_groupCodeList($GroupCodeList_str) + { + $sql = "SELECT GRI_No + FROM GRoupInfo gri + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gri.GRI_SN + WHERE gri.GRI_No IN ($GroupCodeList_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_packageSN($pag_code) + { + $sql = "SELECT top 1 PAG2_SN,PAG_CII_SN,PAG2_PAG_SN + FROM BIZ_PackageInfo2 pag2 + INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN + WHERE pag.PAG_Code = '$pag_code' and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 + "; + $query = $this->HT->query($sql); + if ($query->row()) { + return $query->row(); + } + return NULL; + } + + /*! + * 需要更新调度信息的订单 -- 商务表 + * @param integer $coli_sn [description] + * @param [type] $startDate [description] + * @param [type] $endDate [description] + */ + public function get_groupCombineInfo($coli_sn=0, $get_vendorID=null, $startDate=null, $endDate=NULL) + { + $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + cold.COLD_PlanVEI_SN, gci.*,'0' as 'isHistory' + FROM GroupCombineInfo gci + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN --and coli.COLI_State NOT IN ('30','40','50') + LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + WHERE 1=1 "; + if ($coli_sn !== 0) { + $sql .= " and coli.COLI_SN='$coli_sn' "; + } + if ($get_vendorID !== null) { + $sql .= " and GCI_VendorOrderId='$get_vendorID' "; + } + if ($startDate !== NULL) { + $sql .= " and gci.GCI_travelDate between '$startDate' and '$endDate' and gci.GCI_createTime < '" . date('Y-m-d') . "' "; + } + // 近期的订单同步完成之后, 同步历史数据 + $sql .= " UNION ALL "; + $sql .= " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, + cold.COLD_PlanVEI_SN, gci.*,'1' as 'isHistory' + from GroupCombineInfo gci + inner join GRoupInfo on GRI_SN=GCI_GRI_SN and GRI_No<>'' + LEFT JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + where + GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') + and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + and GCI_combineNo not like '%取消%' + and not exists ( + select GCOD_SN from GroupCombineOperationDetail gcod where gcod.GCOD_GCI_combineNo=GCI_combineNo + ) + and 0 < ( + select sum(isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)+isnull(COLD_BabyNum,0)) person from BIZ_ConfirmLineInfo + inner join BIZ_ConfirmLineDetail on COLD_COLI_SN=COLI_SN + where COLI_GRI_SN=gri_sn + ) "; + $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; + $query = $this->HT->query($sql); + return $query->result(); + } + + /*! + * 获取团计划信息的记录 - 根据地接社订单id + * 计划变更和订单状态确认时使用 + * @param integer $vendorOrderId 图兰朵地接社系统的订单id + */ + public function get_vendorarrangestate_byVendor($vendorOrderId, $vei_sn) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON gci.GCI_GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID + WHERE gci.GCI_VendorOrderId=? and vas.VAS_VEI_SN=? and gci.GCI_VEI_SN=? "; + $query = $this->HT->query($sql, array($vendorOrderId, $vei_sn, $vei_sn)); + return $query->result(); + } + /*! + * 获取团计划信息的记录 - 根据组团社团号 - 商务订单 + * 计划变更和订单状态确认时使用 + * @param string $groupCode 团号 + * @param integer $vei_sn HT系统中供应商key + */ + public function get_vendorarrangestate_byGroup($groupCode, $vei_sn) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM GRoupInfo gri + INNER JOIN BIZ_ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '%$groupCode%'"; + $query = $this->HT->query($sql, array($vei_sn)); + return $query->result(); + } + /*! + * 获取团计划信息的记录 - 根据组团社团号 - 传统订单 + * 计划变更和订单状态确认时使用 + * @param string $groupCode 团号 + * @param integer $vei_sn HT系统中供应商key + */ + public function get_vendorarrangestate_byGroup_T($groupCode, $vei_sn) + { + $sql = "SELECT coli.COLI_ID, coli.COLI_SN,opi.OPI_Email,opi.OPI_Name, + vas.VAS_ChangeText, vas.VAS_ConfirmInfo, vas.VAS_SN + FROM GRoupInfo gri + INNER JOIN ConfirmLineInfo coli ON gri.GRI_SN=coli.COLI_GRI_SN + INNER JOIN VendorArrangeState vas ON vas.VAS_GRI_SN=coli.COLI_GRI_SN + LEFT JOIN OperatorInfo opi ON opi.OPI_SN=coli.COLI_OPI_ID + WHERE vas.VAS_VEI_SN=? and gri.GRI_No LIKE '%$groupCode%'"; + $query = $this->HT->query($sql, array($vei_sn)); + return $query->result(); + } + + /*! + * 生成预定传真 + */ + public function sp_biz_arrange() + { + $sql = "SP_BIZ_Arrange ?"; + $query = $this->HT->query($sql, array($this->GRI_SN)); + return $query->result(); + } + + public $GRI_SN=0; // 团号 + public $GRI_No; // 团号 + public $GRI_OrderType; // 订单类型 + public $GRI_Name; // 团名 + public $GRI_PersonNum; // 人数 + public $GRI_Days; // 行程天数 + public $GRI_IsCancel=0; + public $GRI_DeleteFlag=0; + public $GRI_OPI_ID=0; + public $GRI_operator=0; + public $GRI_Creator=0; + public $GRI_CreateDate=0; + /** 团信息 */ + public function groupinfo_save() + { + $sql = "INSERT INTO GRoupInfo + (GRI_No + ,GRI_Name + ,GRI_PersonNum + ,GRI_Days + ,GRI_IsCancel + ,DeleteFlag + ,GRI_OPI_ID + ,GRI_operator + ,GRI_Creator + ,GRI_CreateDate + ,GRI_OrderType) + VALUES (N?,N?,?,?,?,?,?,?,?,GETDATE(),?)"; + $query = $this->HT->query($sql, array( + $this->GRI_No, + $this->GRI_Name, + $this->GRI_PersonNum, + $this->GRI_Days, + $this->GRI_IsCancel, + $this->GRI_DeleteFlag, + $this->GRI_OPI_ID, + $this->GRI_operator, + $this->GRI_Creator, + $this->GRI_OrderType + )); + $this->GRI_SN = $this->HT->query("select MAX(GRI_SN) as insert_id FROM GRoupInfo WHERE GRI_operator=435 AND GRI_No='" . $this->GRI_No . "'")->row('insert_id'); + return $this->GRI_SN; + } + + public $GCI_SN; + public $GCI_VEI_SN; + public $GCI_combineNo=''; // 拼团团号 + public $GCI_GRI_SN; // 团key + public $GCI_VendorOrderId; // 地接社系统订单id + public $GCI_FromAgc; // 组团社来源 + public $GCI_groupType; // 组团社来源 + public $GCI_travelDate; + public $GCI_leaveDate; + public $GCI_createTime; + /** 目的地订单 拼团信息 */ + public function biz_groupcombineinfo_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM GroupCombineInfo + WHERE GCI_VendorOrderId = ? and GCI_GRI_SN=? and GCI_VEI_SN=? + ) + INSERT INTO GroupCombineInfo + (GCI_combineNo + ,GCI_GRI_SN + ,GCI_VEI_SN + ,GCI_VendorOrderId + ,GCI_FromAgc + ,GCI_groupType + ,GCI_travelDate + ,GCI_leaveDate + ,GCI_createTime) + VALUES + (N? + ,? + ,? + ,? + ,N? + ,? + ,? + ,? + ,?) + "; + $query = $this->HT->query($sql, array( + $this->GCI_VendorOrderId + ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN + ,$this->GCI_combineNo + ,$this->GCI_GRI_SN + ,$this->GCI_VEI_SN + ,$this->GCI_VendorOrderId + ,$this->GCI_FromAgc + ,$this->GCI_groupType + ,$this->GCI_travelDate + ,$this->GCI_leaveDate + ,$this->GCI_createTime + )); + $this->GCI_SN = $this->HT->query("select MAX(GCI_SN) as insert_id FROM GroupCombineInfo WHERE GCI_combineNo='" . $this->GCI_combineNo . "'")->row('insert_id'); + return $this->GCI_SN; + } + + public function biz_groupcombineoperationdetail_cut($combineNo) + { + $sql = "DELETE + FROM GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N?"; + $query = $this->HT->query($sql, array($combineNo)); + return $query; + } + + /*! + * 暂时没用 + */ + public function combineoperation_exist($combineNo='', $operation="") + { + if( ! $combineNo) { return array(); } + $sql = "SELECT TOP 1 GCOD_GCI_combineNo + FROM GroupCombineOperationDetail + WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=?"; + $query = $this->HT->query($sql, array( + $combineNo,$operation + )); + return $query->result(); + } + public $GCOD_SN; + public $GCOD_VEI_SN; + public $GCOD_GCI_combineNo = ''; + public $GCOD_operationType = ''; + public $GCOD_subType = ''; + public $GCOD_title = ''; + public $GCOD_dutyName = ''; + public $GCOD_dutyTel; + public $GCOD_dutyPhoto; + public $GCOD_startDate; + public $GCOD_endDate; + public $GCOD_useNum=1; + public $GCOD_sumMoney; + public $GCOD_standard = ''; + public $GCOD_carLicense = ''; + public $GCOD_remark = ''; + public $GCOD_creatTime; + public function biz_groupcombineoperationdetail_save() + { + // IF NOT EXISTS( + // SELECT TOP 1 1 + // FROM GroupCombineOperationDetail + // WHERE GCOD_GCI_combineNo = N? and GCOD_operationType=N? + // ) + $sql = "INSERT INTO GroupCombineOperationDetail + (GCOD_GCI_combineNo + ,GCOD_VEI_SN + ,GCOD_operationType + ,GCOD_subType + ,GCOD_title + ,GCOD_dutyName + ,GCOD_dutyTel + ,GCOD_dutyPhoto + ,GCOD_startDate + ,GCOD_endDate + ,GCOD_useNum + ,GCOD_sumMoney + ,GCOD_standard + ,GCOD_carLicense + ,GCOD_remark + ,GCOD_creatTime) + VALUES + (N? + ,? + ,N? + ,N? + ,N? + ,N? + ,? + ,? + ,? + ,? + ,? + ,? + ,N? + ,N? + ,N? + ,GETDATE()) + "; + $query = $this->HT->query($sql, array( + $this->GCOD_GCI_combineNo + ,$this->GCOD_VEI_SN + ,$this->GCOD_operationType + // ,$this->GCOD_GCI_combineNo + // ,$this->GCOD_operationType + ,$this->GCOD_subType + ,$this->GCOD_title + ,$this->GCOD_dutyName + ,$this->GCOD_dutyTel + ,$this->GCOD_dutyPhoto + ,$this->GCOD_startDate + ,$this->GCOD_endDate + ,$this->GCOD_useNum + ,$this->GCOD_sumMoney + ,$this->GCOD_standard + ,$this->GCOD_carLicense + ,$this->GCOD_remark + )); + return $query; + } + + + + var $GUT_SN; + var $GUT_FirstName; //联系人 + var $GUT_LastName = ""; //联系人 + var $GUT_Title; //称谓 + var $GUT_Email; //主email + var $GUT_Email2; //备用email + var $GUT_NationalityID; //国家 + var $GUT_Passport; //护照 + var $GUT_TEL; //座机 + var $GUT_MoveTel; //手机 + + /** + * 商务联系人表入库 + * + * @return int GUT_SN 插入id + */ + + function biz_guest_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_Guest \n" + . " ( \n" + . " GUT_FirstName, \n" + . " GUT_LastName, \n" + . " GUT_Title, \n" + . " GUT_Email, \n" + . " GUT_Email2, \n" + . " GUT_NationalityID, \n" + . " GUT_Passport, \n" + . " GUT_TEL, \n" + . " GUT_MoveTel, \n" + . " GUT_AddCode, \n" + . " GUT_CreateDate \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " GETDATE() \n" + . " )"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->GUT_FirstName, 'UTF-8'), + mb_convert_encoding($this->GUT_LastName, 'UTF-8'), + $this->GUT_Title, + $this->GUT_Email, + $this->GUT_Email2, + $this->GUT_NationalityID, + mb_convert_encoding($this->GUT_Passport, 'UTF-8'), + $this->GUT_TEL, + $this->GUT_MoveTel, $AddCode + )); + $this->GUT_SN = $this->HT->query('select MAX(GUT_SN) as insert_id FROM BIZ_Guest WHERE GUT_AddCode=' . $AddCode)->row('insert_id'); + return $this->GUT_SN; + } + + public function get_SN_by_vendorOrderId($vendorOrderId, $vendorID) + { + $sql = "SELECT TOP 1 coli.COLI_GRI_SN,coli.COLI_SN,gci.GCI_SN + FROM GroupCombineInfo gci + INNER JOIN BIZ_ConfirmLineInfo coli ON coli.COLI_GRI_SN=gci.GCI_GRI_SN + WHERE gci.GCI_VendorOrderId='$vendorOrderId' and GCI_VEI_SN='$vendorID'"; + $query = $this->HT->query($sql); + if ($query->row()) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->COLI_GRI_SN; + $this->GCI_SN = $query->row()->GCI_SN; + return $query->row(); + } + return NULL; + } + + /*! + * 1. 获取列表时: 按团号查询团是否已存在, 避免渠道和目的地组同时操作 + * @param [type] $code [description] + * @param [type] $vendorOrderId [description] + */ + public function get_SN_by_groupCode($code, $vendorOrderId=NULL) + { + $sql = "SELECT top 1 COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID,coli.COLI_Memo,coli.COLI_OrderDetailText,coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + ,GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name + FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN --and COLI_State not in (30,40,50) + LEFT JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 + and gri.GRI_operator<>435 and gri.GRI_operator is not null + WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' + order by COLI_SN desc"; // and gri.GRI_Name like '%$NoName%' + $query = $this->HT->query($sql); + if ($query->num_rows() > 0) { + $this->BIZ_COLI_SN = $query->row()->COLI_SN; + $this->GRI_SN = $query->row()->GRI_SN; + $this->GRI_No = $query->row()->GRI_No; + $this->GRI_operator = $query->row()->GRI_operator; + $this->COLD_PlanVEI_SN = $query->row()->COLD_PlanVEI_SN; + return $query->row(); + } + return NULL; + } + + /*! + * 更新时: + * @date 2018-08-23 + * @param [type] $code [description] + */ + public function get_order_by_groupcode($code) + { + $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, + coli.COLI_OrderDetailText, + coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency + GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, + coli.COLI_Memo + FROM BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN + left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 + WHERE coli.COLI_Department=30 and gri.GRI_No LIKE '%$code%' + order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /*! + * 获取地接社接受计划的人员信息 + * @param $vendorID 地接社ID + */ + public function get_vendorContact($vendorID) + { + $sql = "SELECT top 1 lmi2.LMI2_Name, + lmi.LMI_SN, + lmi.LMI_AutoFax, + lmi.LMI_Telephone, + lmi.LMI_Mobile, + lmi.LMI_ListMail + ,vei2.VEI2_CompanyBN + FROM LinkmanInfo lmi + INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN AND lmi2.LMI2_LGC=2 + INNER JOIN VEndorInfo2 vei2 ON vei2.VEI2_VEI_SN=LMI_VEI_SN AND VEI2_LGC=2 + WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; + $query = $this->HT->query($sql); + return $query->row(); + } + + var $BIZ_COLI_SN; + var $BIZ_COLI_ID; + var $BIZ_COLI_GUT_SN; //联系人id + var $BIZ_COLI_Area; //市场 + var $BIZ_COLI_ApplyDate = ''; //提交日期 + var $BIZ_COLI_Price; //订单总价 + var $BIZ_COLI_Cost; //总成本 + var $BIZ_COLI_Currency; //币种 + var $BIZ_COLI_TrueCardRate; //信用卡手续费 + var $BIZ_COLI_SenderIP = ''; //客人ip + var $BIZ_COLI_WebCode = ''; //站点code + var $BIZ_COLI_servicetype; //订单来源类型 + var $BIZ_COLI_sourcetype; //预定类型 + var $BIZ_COLI_AgencyID; + var $BIZ_COLI_ConfirmType; //提交方式 + var $BIZ_COLI_OrderDetailText; + var $BIZ_COLI_OriginalText=''; + var $BIZ_COLI_Memo; + var $BIZ_COLI_GRI_SN; + var $BIZ_COLI_GroupCode=''; + var $BIZ_COLI_PayManner; + var $BIZ_COLI_State; + var $BIZ_COLI_OPI_ID; + + /** + * 商务订单主表入库 + * @return int BIZ_COLI_ID 插入id + */ + function biz_confirm_save() { + // if (empty($this->BIZ_COLI_WebCode)) { + $this->BIZ_COLI_WebCode = '';// 来源图兰朵 + // } + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineInfo \n" + . "( \n" + . " COLI_ID, \n" + . " COLI_GUT_SN, \n" + . " COLI_Area, \n" + . " COLI_ApplyDate, \n" + . " COLI_Price, \n" + . " COLI_Cost, \n" + . " COLI_Currency, \n" + . " COLI_TrueCardRate, \n" + . " COLI_AgencyID, \n" + . " COLI_OrderDetailText, \n" + . " COLI_SenderIP, \n" + . " COLI_WebCode, \n" + . " COLI_servicetype, \n" + . " COLI_sourcetype, \n" + . " COLI_ConfirmType, \n" + . " COLI_State, \n" + . " COLI_Department, \n" + . " COLI_AddCode, \n" + . " COLI_OrderSource, \n" + . " COLI_Memo, \n" + . " COLI_GRI_SN, \n" + . " COLI_OPI_ID, \n" + . " COLI_GroupCode, \n" + . " COLI_PayManner, \n" + . " COLI_OriginalText \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " N?, \n" + . " ?, \n" + . " N? \n" + . ")"; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_ID, + $this->BIZ_COLI_GUT_SN, + 2, + // $this->config->item('Site_Area'), + //date("Y-m-d H:i:s"), + $this->BIZ_COLI_ApplyDate, + $this->BIZ_COLI_Price, + $this->BIZ_COLI_Cost, + $this->config->item('Site_Currency'), + $this->BIZ_COLI_TrueCardRate, + $this->BIZ_COLI_AgencyID, + $this->BIZ_COLI_OrderDetailText, + $this->BIZ_COLI_SenderIP, + $this->BIZ_COLI_WebCode, + $this->BIZ_COLI_servicetype, + $this->BIZ_COLI_sourcetype, + $this->BIZ_COLI_ConfirmType, + $this->BIZ_COLI_State, + 30,// $this->config->item('Site_Department'), + $AddCode, + $this->COLI_OrderSource, + $this->BIZ_COLI_Memo, + $this->BIZ_COLI_GRI_SN, + $this->BIZ_COLI_OPI_ID, + $this->BIZ_COLI_GroupCode, + $this->BIZ_COLI_PayManner, + $this->BIZ_COLI_OriginalText + )); + $this->BIZ_COLI_SN = $this->HT->query('select MAX(COLI_SN) as insert_id FROM BIZ_ConfirmLineInfo WHERE COLI_AddCode=' . $AddCode)->row('insert_id'); + return $this->BIZ_COLI_SN; + } + + public function update_confirmLineInfo() + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET + COLI_GRI_SN=?, + COLI_GroupCode=? + WHERE COLI_SN=? + "; + $query = $this->HT->query($sql, array( + $this->BIZ_COLI_GRI_SN + ,$this->BIZ_COLI_GroupCode + ,$this->BIZ_COLI_SN + )); + return $this->query; + } + + var $COLD_SN; + var $COLD_COLI_SN; // 订单主表sn + var $COLD_ServiceType; // 服务类型 + var $COLD_StartDate; // 产品的服务的开始日期 + var $COLD_EndDate; // 产品的服务的结束日期 + var $COLD_TotalCost; // 总成本 + var $COLD_TotalPrice; // 总报价 + var $COLD_Count; // 产品数量 + var $COLD_PersonNum; // 成人数 + var $COLD_ChildNum; // 小孩数 + var $COLD_BabyNum; // 婴儿数 + var $cold_state; // 状态 + var $DeleteFlag; // 删除标志 + var $COLD_DeliveryCharge = 0; //服务费 + 快递费用 CNY + var $COLD_PlanVEI_SN = NULL; // 默认供应商 628-火车桂林国旅 + var $COLD_SPFS = NULL; // 快递方式:1自取 2酒店 3指定地址 + var $COLD_ServiceSN = NULL; // 产品ID 除机票外 其它自基础产品库各产品ID + var $COLD_ServiceSN2 = NULL; + var $COLD_ServiceCity = NULL; + var $COLD_Memo = NULL; + var $COLD_MemoText = NULL; + + /** + * 商务订单子(详细)表入库 + * + * @return int 插入id + */ + + function biz_confirm_detail_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_ConfirmLineDetail \n" + . "( \n" + . " COLD_COLI_SN, \n" + . " COLD_ServiceType, \n" + . " COLD_StartDate, \n" + . " COLD_EndDate, \n" + . " COLD_TotalCost, \n" + . " COLD_TotalPrice, \n" + . " COLD_Count, \n" + . " COLD_PersonNum, \n" + . " COLD_ChildNum, \n" + . " COLD_BabyNum, \n" + . " cold_state, \n" + . " DeleteFlag, \n" + . " COLD_DeliveryCharge, \n" + . " COLD_AddCode, \n" + . " COLD_PlanVEI_SN, \n" + . " COLD_SPFS, \n" + . " COLD_Memo, \n" + . " COLD_MemoText, \n" + . " COLD_ServiceSN, \n" + . " COLD_ServiceSN2, \n" + . " COLD_ServiceCity \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->COLD_COLI_SN, + $this->COLD_ServiceType, + $this->COLD_StartDate, + $this->COLD_EndDate, + $this->COLD_TotalCost, + $this->COLD_TotalPrice, + $this->COLD_Count, + $this->COLD_PersonNum, + $this->COLD_ChildNum, + $this->COLD_BabyNum, + $this->cold_state, + $this->DeleteFlag, + $this->COLD_DeliveryCharge, + $AddCode, + $this->COLD_PlanVEI_SN, + $this->COLD_SPFS, + $this->COLD_Memo, + $this->COLD_MemoText, + $this->COLD_ServiceSN, + $this->COLD_ServiceSN2, + $this->COLD_ServiceCity) + ); + //查出最近插入的id + $HT2 = $this->load->database('HT', true); + $this->COLD_SN = $HT2->query('select MAX(COLD_SN) as insert_id FROM BIZ_ConfirmLineDetail WHERE COLD_AddCode=' . $AddCode)->row('insert_id'); + return $this->COLD_SN; + } + + var $BIZ_COLL_COLI_SN; + var $BIZ_COLL_type; + var $BIZ_COLL_COLI_Field; + var $BIZ_COLL_COLI_value; + var $BIZ_COLL_OPI_SN; + + function biz_confirm_line_log_save() + { + $sql = "INSERT INTO BIZ_ConfirmLineLog ( + COLL_COLI_SN, + COLL_LogTime, + COLL_type, + COLL_COLI_Field, + COLL_COLI_value, + COLL_OPI_SN + ) VALUES (?,GETDATE(),?,?,?,?) "; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->BIZ_COLL_COLI_SN, + $this->BIZ_COLL_type, + $this->BIZ_COLL_COLI_Field, + $this->BIZ_COLL_COLI_value, + $this->BIZ_COLL_OPI_SN) + ); + return $query; + } + + var $POI_SN; + var $POI_COLD_SN; + var $POI_FlightsNo = ''; + var $POI_AirPort = ''; + var $POI_Time; + var $POI_Hotel = ''; + var $POI_HotelAddress = ''; + var $POI_HotelPhone = ''; + var $POI_HotelCheckInName = ''; + var $POI_HotelCheckIn = ''; + var $POI_HotelCheckOut = ''; + var $POI_EndTime = ''; + var $POI_QuotationType; // 1 报价 2 网络支付价 3 促销价 + /** 包价线路订单入库 */ + public function biz_packageorder_save() + { + $sql = "IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_PackageOrderInfo + WHERE POI_COLD_SN = ? + ) + INSERT INTO BIZ_PackageOrderInfo + (POI_COLD_SN + ,POI_FlightsNo + ,POI_AirPort + ,POI_Time + ,POI_Hotel + ,POI_QuotationType + ,POI_HotelAddress + ,POI_HotelPhone + ,POI_HotelCheckInName + ,POI_HotelCheckIn + ,POI_HotelCheckOut + ,POI_EndTime) + VALUES + (? + ,? + ,N? + ,? + ,N? + ,? + ,N? + ,N? + ,N? + ,N? + ,N? + ,N?) + "; + $query = $this->HT->query($sql, array( + $this->POI_COLD_SN + ,$this->POI_COLD_SN + ,$this->POI_FlightsNo + ,$this->POI_AirPort + ,$this->POI_Time + ,$this->POI_Hotel + ,$this->POI_QuotationType + ,$this->POI_HotelAddress + ,$this->POI_HotelPhone + ,$this->POI_HotelCheckInName + ,$this->POI_HotelCheckIn + ,$this->POI_HotelCheckOut + ,$this->POI_EndTime + )); + $this->POI_SN = $this->HT->query('select MAX(POI_SN) as insert_id FROM BIZ_PackageOrderInfo WHERE POI_COLD_SN=' . $this->POI_COLD_SN)->row('insert_id'); + return $this->POI_SN; + } + + var $FOI_SN; + var $FOI_COLD_SN; // 订单子表sn + var $Aircompany; // 航空公司编码 + var $FlightsNo; // 航班号 + var $Cabin; // 舱位 + var $DepartAirport; // 出发机场 + var $ArrivalAirport; // 抵达机场 + var $DepartureCity; // 出发城市 + var $DepartureTime; // 出发日期 + var $ArrivalCity; // 抵达城市 + var $Arrivaltime; // 抵达时间 + var $DepartureDate; // 出发时间 + var $adultCost; // 成人成本 + var $childCost; // 小孩成倍 + var $babyCost; // 婴儿成本 + var $adultPrice; // 成人报价 + var $childPrice; // 小孩报价 + var $babyPrice; // 婴儿报价 + var $Stopover; // + var $PriceY; // Y仓价格 + var $price_low; // 最低价格 + var $FOI_Mile; // 里程 + var $TicketAddress; // 寄送地址 + var $FOI_CostTime = ''; // 运行时间 + var $Aircraft = ''; // 12306座位编号 + var $FOI_ServiceFee_adult = NULL; // 成人服务费 + var $FOI_ServiceFee_child = NULL; // 儿童服务费 + var $FOI_DeliveryFee = NULL; // 寄票费 + var $FOI_SelectedSeat = ""; // 选座 + + /** + * + * 商务机票订单入库 + * + */ + + function biz_flight_order_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_FlightsOrderInfo \n" + . "( \n" + . " FOI_COLD_SN, \n" + . " Aircompany, \n" + . " FlightsNo, \n" + . " Cabin, \n" + . " DepartAirport, \n" + . " ArrivalAirport, \n" + . " DepartureCity, \n" + . " DepartureTime, \n" + . " ArrivalCity, \n" + . " Arrivaltime, \n" + . " DepartureDate, \n" + . " adultCost, \n" + . " childCost, \n" + . " babyCost, \n" + . " adultPrice, \n" + . " childPrice, \n" + . " babyPrice, \n" + . " Stopover, \n" + . " PriceY, \n" + . " price_low, \n" + . " FOI_Mile, \n" + . " TicketAddress, \n" + . " FOI_CostTime, \n" + . " FOI_AddCode, \n" + . " Aircraft, \n" + . " FOI_ServiceFee_adult, \n" + . " FOI_ServiceFee_child, \n" + . " FOI_SelectedSeat, \n" + . " FOI_DeliveryFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->FOI_COLD_SN, + $this->Aircompany, + $this->FlightsNo, + $this->Cabin, + $this->DepartAirport, + $this->ArrivalAirport, + $this->DepartureCity, + $this->DepartureTime, + $this->ArrivalCity, + $this->Arrivaltime, + $this->DepartureDate, + $this->adultCost, + $this->childCost, + $this->babyCost, + $this->adultPrice, + $this->childPrice, + $this->babyPrice, + $this->Stopover, + $this->PriceY, + $this->price_low, + $this->FOI_Mile, + $this->TicketAddress, + $this->FOI_CostTime, + $AddCode, + $this->Aircraft, + $this->FOI_ServiceFee_adult, + $this->FOI_ServiceFee_child, + $this->FOI_SelectedSeat, + $this->FOI_DeliveryFee + )); + $this->FOI_SN = $HT1->query('select MAX(FOI_SN) as insert_id FROM BIZ_FlightsOrderInfo WHERE FOI_AddCode=' . $AddCode)->row('insert_id'); + return $this->FOI_SN; + } + + /*! + * 查询是否已经写入过客人列表 + * @date 2018-04-28 + * @param [type] $cold_sn 订单字表key + */ + public function bookpeople_exist($cold_sn) + { + if( ! $cold_sn) { return array(); } + $sql = "SELECT top 1 * + FROM BIZ_BookPeopleList BPL + WHERE BPL_COLD_SN=? "; + $query = $this->HT->query($sql, array($cold_sn)); + return $query->result(); + } + + var $BPE_SN; + var $BPE_FirstName; //客人 + var $BPE_MiddleName; //客人 + var $BPE_LastName; //客人 + var $BPE_GuestType; //客人类型 + var $BPE_Passport; //护照 + var $BPE_imageSrc = NULL; //护照图片 + var $BPE_Nationality; //国籍 + var $BPE_SEX; //性别 + var $BPE_BirthDate; //生日 + var $BPE_PassportType = "Passport No."; //护照类型 + + /** + * + * 商务订单参团客人入库 + * + */ + + function biz_book_people_save() { + //生成一个号码,用于MAX函数来查询插入ID时避免获得其它线程插入的值 + $AddCode = $this->MakeOrderNumber(); + $sql = "INSERT INTO BIZ_BookPeople \n" + . "( \n" + . " BPE_FirstName, \n" + . " BPE_MiddleName, \n" + . " BPE_LastName, \n" + . " BPE_GuestType, \n" + . " BPE_Passport, \n" + . " BPE_imageSrc, \n" + . " BPE_Nationality, \n" + . " BPE_SEX, \n" + . " BPE_BirthDate, \n" + . " BPE_PassportType, \n" + . " BPE_AddCode \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " N?, \n" + . " N?, \n" + . " N?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $query = $this->HT->query($sql, array( + mb_convert_encoding($this->BPE_FirstName, 'UTF-8'), + mb_convert_encoding($this->BPE_MiddleName, 'UTF-8'), + mb_convert_encoding($this->BPE_LastName, 'UTF-8'), $this->BPE_GuestType, + mb_convert_encoding($this->BPE_Passport, 'UTF-8'), $this->BPE_imageSrc, + $this->BPE_Nationality, + $this->BPE_SEX, $this->BPE_BirthDate, $this->BPE_PassportType, $AddCode)); + $this->BPE_SN = $this->HT->query('select MAX(BPE_SN) as insert_id FROM BIZ_BookPeople WHERE BPE_AddCode=' . $AddCode)->row('insert_id'); + return $this->BPE_SN; + } + + /** + * 参团人关联 + * + * @param int 商务子表sn + * @param int 参团客人sn + */ + function biz_bookpeople_List_save($COLD_SN, $BPE_SN) { + $sql = "INSERT INTO BIZ_BookPeopleList \n" + . "( \n" + . " BPL_COLD_SN, \n" + . " BPL_BPE_SN \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ? \n" + . ")"; + $query = $this->HT->query($sql, array($COLD_SN, $BPE_SN)); + } + + /* + * 生成订单号 + * 根据系统时间生成,精确到0.0001微秒 + */ + + function MakeOrderNumber() { + return str_replace('.', '', sprintf('%11.4f', gettimeofday(TRUE))); + } + + /** + * 生成商务订单号 + */ + function biz_make_order_number() { + /* + $date = date('ymd',time()); + $sql = "SELECT MAX( \n" + . " CONVERT( \n" + . " INT, \n" + . " CASE \n" + . " WHEN ISNUMERIC(RIGHT(COLI_ID, 3)) = 0 THEN LEFT(RIGHT(COLI_ID, 4), 3) \n" + . " ELSE RIGHT(COLI_ID, 3) \n" + . " END \n" + . " ) \n" + . " ) AS SN \n" + . "FROM dbo.BIZ_ConfirmLineInfo \n" + . "WHERE (LEFT(COLI_ID, 6) = ?)"; + $query = $this->HT->query($sql,array($date)); + $id = $query->row()->SN; + if (is_null($id)||empty($id)) + { + $id = 0; + } + $ids = $date.(sprintf('%03d',(int)$id+1)); + return $ids; + */ + //call $conn + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "declare @ccid varchar(20);exec dbo.SP_GetBIZOrderNo @ccid out;select @ccid as ccid;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + } else { + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->ccid); + } + } + + /*! + * 删除收款记录以更新 + * @date 2018-04-28 + * @param [type] $coli_sn 订单key + * @param [type] $paytype 付款方式 + */ + public function biz_groupaccountinfo_cut($coli_sn, $paytype) + { + $sql = "DELETE from BIZ_GroupAccountInfo + WHERE GAI_COLI_SN=? AND GAI_Type=? AND GAI_Operator = 435"; + $query = $this->HT->query($sql, array($coli_sn, $paytype)); + return $query; + } + + /** + * + * 插入收款记录 + * + */ + public $GAI_COLI_SN; + public $GAI_GRI_SN; + public $GAI_COLI_ID; + public $GAI_Type; + public $GAI_SQJE; + public $GAI_SQDate; + public $GAI_SQJECurrency; + public $GAI_SSJE; + public $GAI_SSDate; + public $GAI_Operator; + public $GAI_Memo=""; + public function biz_groupaccountinfo_save() + { + $sql = "INSERT INTO BIZ_GroupAccountInfo \n" + . " ( \n" + . " GAI_COLI_SN, \n" + . " GAI_GRI_SN, \n" + . " GAI_COLI_ID, \n" + . " GAI_Type, \n" + . " GAI_SQJE, \n" + . " GAI_SQDate, \n" + . " GAI_SQJECurrency, \n" + . " GAI_SSJE, \n" + . " GAI_SSDate, \n" + . " GAI_Operator, \n" + . " GAI_Memo \n" + . " ) \n" + . "VALUES \n" + . " ( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . " )"; + $query = $this->HT->query($sql, array( + $this->GAI_COLI_SN + ,$this->GAI_GRI_SN + ,$this->GAI_COLI_ID + ,$this->GAI_Type + ,$this->GAI_SQJE + ,$this->GAI_SQDate + ,$this->GAI_SQJECurrency + ,$this->GAI_SSJE + ,$this->GAI_SSDate + ,$this->GAI_Operator + ,$this->GAI_Memo + )); + return $query; + } + + function GetNationalityID($nationalityName) { + if (!$nationalityName) { + return 0; + } + if (is_numeric($nationalityName)) { + return $nationalityName; + } else { + $sql = "SELECT TOP 1 ci2.COI2_COI_SN \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_Country = ? "; + $query = $this->HT->query($sql, array($nationalityName)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_COI_SN; + } else { + return 0; + } + } + } + + function GetNationalityName($nationalityID) { + if (!is_numeric($nationalityID)) { + return $nationalityID; + } else { + $sql = "SELECT TOP 1 ci2.COI2_Country \n" + . "FROM COuntryInfo2 ci2 \n" + . "WHERE ci2.COI2_LGC = 2 \n" + . " AND ci2.COI2_COI_SN = ? "; + $query = $this->HT->query($sql, array($nationalityID)); + if ($query->result()) { + $row = $query->row(); + return $row->COI2_Country; + } else { + return $nationalityID; + } + } + } + + /** + * + * 获取商务订单信息 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_flight_order_by_id($order_id) { + $sql = "SELECT DISTINCT cli.COLI_ID, \n" + . " cli.COLI_Price, \n" + . " bg.GUT_FirstName, \n" + . " bg.GUT_LastName, \n" + . " bg.GUT_Email, \n" + . " bg.GUT_Email2, \n" + . " bpe.BPE_SN, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_GuestType, \n" + . " bpe.BPE_Passport, \n" + . " cld.COLD_Count, \n" + . " foi.FlightsNo, \n" + . " foi.DepartureDate, \n" + . " foi.DepartureTime, \n" + . " foi.ArrivalTime, \n" + . " cli.COLI_PayManner, \n" + . " cli.COLI_State, \n" + . " cli.COLI_sourcetype, \n" + . " foi.Cabin, \n" + . " foi.DepartAirport, \n" + . " foi.ArrivalAirport, \n" + . " cld.COLD_SN, \n" + . " foi.DepartureCity, \n" + . " foi.ArrivalCity, \n" + . " bg.GUT_TEL, \n" + . " bg.GUT_NationalityID, \n" + . " cli.COLI_OrderDetailText, \n" + . " bpe.BPE_imageSrc, \n" + . " cli.COLI_Cost, \n" + . " cld.COLD_TotalPrice, \n" + . " cld.COLD_TotalCost \n" + . "FROM BIZ_ConfirmLineInfo cli \n" + . " INNER JOIN BIZ_ConfirmLineDetail cld \n" + . " ON cli.COLI_SN = cld.COLD_COLI_SN \n" + . " INNER JOIN BIZ_GUEST bg \n" + . " ON bg.GUT_SN = cli.COLI_GUT_SN \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpl.BPL_COLD_SN = cld.COLD_SN \n" + . " INNER JOIN BIZ_BookPeople bpe \n" + . " ON bpl.BPL_BPE_SN = bpe.BPE_SN \n" + . " INNER JOIN BIZ_FlightsOrderInfo foi \n" + . " ON foi.FOI_COLD_SN = cld.COLD_SN \n" + . "WHERE cli.COLI_ID = ? AND isnull(cld.deleteflag,0) = 0 "; + + $query = $this->HT->query($sql, array($order_id)); + return $query->result(); + } + + /** + * + * 获取机票订单乘员列表 + * @param string $order_id 订单id + * @return mixed 订单信息 + * + */ + public function get_bpe_list_by_id($order_id) { + $sql = "SELECT DISTINCT bpe.BPE_SN, \n" + . " bpe.BPE_FirstName, \n" + . " bpe.BPE_MiddleName, \n" + . " bpe.BPE_LastName, \n" + . " bpe.BPE_Passport \n" + . "FROM BIZ_BookPeople bpe \n" + . " INNER JOIN BIZ_BookPeopleList bpl \n" + . " ON bpe.BPE_SN = bpl.BPL_BPE_SN \n" + . " INNER JOIN BIZ_ConfirmLineDetail cold \n" + . " ON bpl.BPL_COLD_SN = cold.COLD_SN \n" + . " INNER JOIN BIZ_ConfirmLineInfo coli \n" + . " ON coli.COLI_SN = cold.COLD_COLI_SN \n" + . "WHERE coli.COLI_ID = ?"; + $query = $this->HT->query($sql, array($order_id)); + //echo('<!--'.$this->HT->compile_binds($sql,array($order_id)).'-->'); + return $query->result(); + } + + /** + * + * 获取机票电子票号 + * @param array bpe_sn 乘客sn数组 + * @return mixed 机票票号 + * + */ + public function get_ticket_no($bpe_sn) { + if (is_array($bpe_sn)) { + $instr = join(',', $bpe_sn); + } elseif (is_string($bpe_sn)) { + $instr = $bpe_sn; + } else { + $instr = 0; + } + $sql = "SELECT DISTINCT ftn.FTN_FilghtsNo, \n" + . " ftn.FTN_TicketNo, \n" + . " ftn.FTN_GuestNo \n" + . "FROM BIZ_FlightsTicketNo ftn \n" + . "WHERE ftn.FTN_GuestNo IN (" . $instr . ")"; + $query = $this->HT->query($sql); + return $query->result(); + } + + /* + * 发送邮件 + */ + public function save_automail($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $frominfo = 'vendorConfirm msg', $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $M_Web = 'vendorConfirm msg') { + $sql = "INSERT INTO + Email_AutomaticSend ( + M_SenderName, + M_SenderEmail, + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, + M_FromName, + M_ServiceSN, + M_State, + M_AddTime + ) VALUES (N?, N?, N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; + $query = $this->HT->query($sql, array($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); + return $query; + } + + /** + * wifi预订入库(目前仅CHT使用) + * + * @return int 插入id + */ + var $WOI_COLD_SN; + var $WOI_Device; //设备(智能手机、pad) + var $WOI_DeviceCount; //设备数量 + var $WOI_UsersCount; //使用人数 + var $WOI_Package; //Wi-Fi套餐 + var $WOI_PackageCount; //套餐数量 + var $WOI_DeliverDate; //起租日期 + var $WOI_DeliverCity; //起租城市 + var $WOI_DeliverAddr; //起租地址 + var $WOI_ReturnDate; //归还日期 + var $WOI_ReturnCity; //归还城市 + var $WOI_ReturnAddr; //归还地址 + var $WOI_OtherService; //其他服务 + var $WOI_GroupNo; //团号 + var $WOI_ExpressNo; //快递单号 + + public function biz_wifi_info_save() { + $sql = "INSERT INTO BIZ_WifiOrderInfo \n" + . "( \n" + . " WOI_COLD_SN, \n" + . " WOI_Device, \n" + . " WOI_DeviceCount, \n" + . " WOI_UsersCount, \n" + . " WOI_Package, \n" + . " WOI_PackageCount, \n" + . " WOI_DeliverDate, \n" + . " WOI_DeliverCity, \n" + . " WOI_DeliverAddr, \n" + . " WOI_ReturnDate, \n" + . " WOI_ReturnCity, \n" + . " WOI_ReturnAddr, \n" + . " WOI_OtherService, \n" + . " WOI_GroupNo, \n" + . " WOI_ExpressNo \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array($this->WOI_COLD_SN, + $this->WOI_Device, + $this->WOI_DeviceCount, + $this->WOI_UsersCount, + $this->WOI_Package, + $this->WOI_PackageCount, + $this->WOI_DeliverDate, + $this->WOI_DeliverCity, + $this->WOI_DeliverAddr, + $this->WOI_ReturnDate, + $this->WOI_ReturnCity, + $this->WOI_ReturnAddr, + $this->WOI_OtherService, + $this->WOI_GroupNo, + $this->WOI_ExpressNo + )); + } + + /** + * 酒店预订入库 + * + * @return int 插入id + */ + var $HOI_COLD_SN; //必选 + var $HOI_NoSmoking = null; //无烟房 + var $HOI_EarlyTime = null; //最早确认时间,已不用 + var $HOI_LastTime = null; //最晚确认时间,已不用 + var $HOI_Room_NO = null; //房号 + var $HOI_ExtraNum = 0; //加床 + var $HOI_RoomTypeName = null; //房型 + var $HOI_BreakNum = null; //早餐人数 + var $HOI_PriceType = null; //价格类型 + var $HOI_BreakType = null; //早餐类型 + var $HOI_RoomRates = null; + var $HOI_ExtrabedRates = null; + var $HOI_TaxFee = null; + + public function biz_hotel_order_save() { + /* ASP版本 + sql="select * from BIZ_HotelOrderInfo where 1=2" + rs2.open sql,conn,3,3,1 + rs2.addnew + rs2("HOI_COLD_SN")=COLD_SN + rs2("HOI_ExtraNum") = extrabed + if clng(Smoking)<2 then + rs2("HOI_NoSmoking")=Smoking + end if + rs2("HOI_EarlyTime")=earlydate + rs2("HOI_LastTime")="" + rs2.update + rs2.close + */ + $sql = "INSERT INTO BIZ_HotelOrderInfo \n" + . "( \n" + . " HOI_COLD_SN, \n" + . " HOI_NoSmoking, \n" + . " HOI_EarlyTime, \n" + . " HOI_LastTime, \n" + . " HOI_Room_NO, \n" + . " HOI_ExtraNum, \n" + . " HOI_RoomTypeName, \n" + . " HOI_BreakNum, \n" + . " HOI_PriceType, \n" + . " HOI_BreakType, \n" + . " HOI_RoomRates, \n" + . " HOI_ExtrabedRates, \n" + . " HOI_TaxFee \n" + . ") \n" + . "VALUES \n" + . "( \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ?, \n" + . " ? \n" + . ")"; + $HT1 = $this->load->database('HT', true); + $query = $HT1->query($sql, array( + $this->HOI_COLD_SN, + $this->HOI_NoSmoking, + $this->HOI_EarlyTime, + $this->HOI_LastTime, + $this->HOI_Room_NO, + $this->HOI_ExtraNum, + $this->HOI_RoomTypeName, + $this->HOI_BreakNum, + $this->HOI_PriceType, + $this->HOI_BreakType, + $this->HOI_RoomRates, + $this->HOI_ExtrabedRates, + $this->HOI_TaxFee + )); + } + + /** + * + * 返回成行订单 + * 条件1:订单类型 + * 天剑2:网站来源 + * + */ + public function get_order_info($COLI_sourcetype, $COLI_WebCode, $biz = true) { + if ($biz) { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " ISNULL(c.COLI_IsSuccess, 0) AS success \n" + . "FROM BIZ_ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } else { + $sql = "SELECT TOP 200 c.COLI_WebCode, \n" + . " c.COLI_ID, \n" + . " c.COLI_ConfirmDate, \n" + . " c.COLI_ApplyDate, \n" + . " CASE WHEN c.COLI_Sended = 5 THEN 1 ELSE 0 END AS success \n" + . "FROM ConfirmLineInfo c \n" + . "WHERE c.COLI_sourcetype = ? \n" + . " AND c.COLI_WebCode = ? \n" + . "ORDER BY \n" + . " c.COLI_SN DESC"; + $query = $this->HT->query($sql, array($COLI_sourcetype, $COLI_WebCode)); + } + $this->sql = $this->HT->queries; + return $query->result(); + } + + //传统订单支付之后,插入新的订单信息 + public function insert_daytrip_order($coli_sn, $pay_manner, $gri_sn, $state, $deleteflag) { + //获取订单 + $order_info_sql = " + SELECT confirmlineinfotmp.COLI_OrderPrice, + memberinfotmp.MEI_FirstName, + memberinfotmp.MEI_LastName, + memberinfotmp.MEI_Mail + FROM memberinfotmp + INNER JOIN customerlisttmp + ON memberinfotmp.mei_sn = customerlisttmp.cul_cui_sn + INNER JOIN confirmlineinfotmp + ON customerlisttmp.cul_coli_sn = confirmlineinfotmp.coli_sn + WHERE (customerlisttmp.cul_coli_sn = ? )"; + $query = $this->HT->query($order_info_sql, array($coli_sn)); + $order_info = $query->row(); + + //插入记录 + $sql = "INSERT INTO GroupAccountInfoTmp + ( + GAI_COLI_SN, + GAI_SQJE, + GAI_SQDate, + GAI_CusName, + GAI_CusEmail, + GAI_SQJECurrency, + GAI_Type, + LastEditTime, + GAI_GRI_SN, + GAI_State, + DeleteFlag + ) + VALUES (?,?,?,?,?,?,?,?,?,?,?)"; + + $query = $this->HT->query($sql, array($coli_sn, + $order_info->COLI_OrderPrice, + date('Y-m-d H:i:s'), + $order_info->MEI_FirstName . " " . $order_info->MEI_LastName, + $order_info->MEI_Mail, + $this->config->item('Site_Currency'), + $pay_manner, + date('Y-m-d H:i:s'), + $gri_sn, + $state, + $deleteflag + ) + ); + } + + //来源终端 tablet mobile desktop + public function check_device() { + if (isset($_SERVER['HTTP_USER_AGENT'])) { + $ua = $_SERVER['HTTP_USER_AGENT']; + } else { + $ua = ''; + } + ## This credit must stay intact (Unless you have a deal with @lukasmig or frimerlukas@gmail.com + ## Made by Lukas Frimer Tholander from Made In Osted Webdesign. + ## Price will be $2 + $iphone = strstr(strtolower($ua), 'mobile'); //Search for 'mobile' in user-agent (iPhone have that) + $android = strstr(strtolower($ua), 'android'); //Search for 'android' in user-agent + $windowsPhone = strstr(strtolower($ua), 'phone'); //Search for 'phone' in user-agent (Windows Phone uses that) + + if (!function_exists('androidTablet')) { + + function androidTablet($ua) { //Find out if it is a tablet + if (strstr(strtolower($ua), 'android')) { //Search for android in user-agent + if (!strstr(strtolower($ua), 'mobile')) { //If there is no ''mobile' in user-agent (Android have that on their phones, but not tablets) + return true; + } + } + } + + } + $androidTablet = androidTablet($ua); //Do androidTablet function + $ipad = strstr(strtolower($ua), 'ipad'); //Search for iPad in user-agent + + if ($androidTablet || $ipad) { //If it's a tablet (iPad / Android) + return 'tablet'; + } elseif ($iphone && !$ipad || $android && !$androidTablet || $windowsPhone) { //If it's a phone and NOT a tablet + return 'mobile'; + } else { //If it's not a mobile device + return 'desktop'; + } + } + + public function ip_limit($ip = "0.0.0.0") + { + if (strcmp($ip, "0.0.0.0") === 0 || empty($ip)) { + return TRUE; + } + $sql = "SELECT COUNT(1) cnt + FROM ConfirmLineInfoTmp + WHERE 1=1 + AND COLI_SenderIP = ? + AND DateDiff(dd,COLI_ApplyDate,getdate())=0"; + $query = $this->HT->query($sql, array($ip)); + $ret = $query->row(); + if ($ret->cnt > 50) { + return FALSE; + } else { + return TRUE; + } + } + + public function convert_RMB_to_currency($money=0, $toCurrency='USD') + { + return $this->HT + ->query("SELECT tourmanager.dbo.[ConvertCurrencyToCurrency](1,'RMB','$toCurrency',$money) as rmb ") + ->row()->rmb; + } + + public function test() + { + // return NULL; + $sql = " + "; + $query = $this->HT->query($sql); + } + + +} From c9f726b6003864dcdd9cde824476f0c4a1e87960 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 12 Oct 2018 16:40:21 +0800 Subject: [PATCH 164/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=BB=84=E8=A6=81?= =?UTF-8?q?=E4=BB=BB=E4=BD=95=E7=8A=B6=E6=80=81=E6=94=B6=E6=AC=BE=E5=90=8E?= =?UTF-8?q?=E9=83=BD=E6=94=B9=E4=B8=BA=E6=96=B0=E8=AE=A2=E5=8D=95(?= =?UTF-8?q?=E5=B7=B2=E6=94=AF=E4=BB=98)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Alipay_model.php | 18 ++++++++++++++---- .../third_party/pay/models/IPayLinks_model.php | 18 ++++++++++++++---- .../third_party/paypal/models/paypal_model.php | 18 ++++++++++++++---- 3 files changed, 42 insertions(+), 12 deletions(-) diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 82deefb8..00d3b82b 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -121,11 +121,21 @@ class Alipay_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 8ac260b2..91a15066 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -121,11 +121,21 @@ class IPayLinks_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? and COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index f65a9675..a6cb43bb 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -122,11 +122,21 @@ class Paypal_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } From b3ce832bb6ee680b4fefcef23e57a80861f0d9e7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 12 Oct 2018 16:47:45 +0800 Subject: [PATCH 165/382] =?UTF-8?q?=E8=BF=98=E6=98=AF=E5=85=88=E7=94=A8?= =?UTF-8?q?=E5=9B=9E=E5=8E=9F=E6=9D=A5=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Alipay_model.php | 18 ++++-------------- .../third_party/pay/models/IPayLinks_model.php | 18 ++++-------------- .../third_party/paypal/models/paypal_model.php | 18 ++++-------------- 3 files changed, 12 insertions(+), 42 deletions(-) diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 00d3b82b..82deefb8 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -121,21 +121,11 @@ class Alipay_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - IF EXISTS - ( SELECT OPI_DEI_SN - FROM OperatorInfo - INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID - WHERE COLI_SN=? AND OPI_DEI_SN=10 - ) - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? - WHERE COLI_SN=? - ELSE - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? WHERE COLI_SN=? - AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State = ? + WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 91a15066..8ac260b2 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -121,21 +121,11 @@ class IPayLinks_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - IF EXISTS - ( SELECT OPI_DEI_SN - FROM OperatorInfo - INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID - WHERE COLI_SN=? AND OPI_DEI_SN=10 - ) - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? - WHERE COLI_SN=? - ELSE - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? WHERE COLI_SN=? - AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State = ? + WHERE COLI_SN = ? and COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index a6cb43bb..f65a9675 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -122,21 +122,11 @@ class Paypal_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - IF EXISTS - ( SELECT OPI_DEI_SN - FROM OperatorInfo - INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID - WHERE COLI_SN=? AND OPI_DEI_SN=10 - ) - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? - WHERE COLI_SN=? - ELSE - UPDATE BIZ_ConfirmLineInfo - SET COLI_State=? WHERE COLI_SN=? - AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State = ? + WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_state, $coli_sn)); return $query; } From 5f5100cf6807af9607fd922cbfae794e993d59f9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 15 Oct 2018 16:06:23 +0800 Subject: [PATCH 166/382] =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/index.php | 7 +++-- ...{orders_model.php => BIZ_orders_model.php} | 2 +- .../vendorPlanSync/models/Group_model.php | 31 +++++++++++++++++++ 3 files changed, 37 insertions(+), 3 deletions(-) rename webht/third_party/vendorPlanSync/models/{orders_model.php => BIZ_orders_model.php} (99%) create mode 100644 webht/third_party/vendorPlanSync/models/Group_model.php diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 3ffd8e9d..b8a30420 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -8,16 +8,19 @@ class Index extends CI_Controller { mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); - $this->load->model('Orders_model'); + $this->load->model('BIZ_Orders_model'); + $this->load->model('Group_model'); } public function index() { + $vendor_plan = $this->Group_model->get_vendor_plan_info(214600, 1343); + return $this->output->set_content_type('application/json')->set_output(json_encode($vendor_plan)); } public function push($COLI_ID) { - $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID); + $orderinfo = $this->BIZ_Orders_model->get_orderinfo_detail($COLI_ID); if(empty($orderinfo)) {return;} return $this->output->set_content_type('application/json')->set_output(json_encode($orderinfo)); } diff --git a/webht/third_party/vendorPlanSync/models/orders_model.php b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php similarity index 99% rename from webht/third_party/vendorPlanSync/models/orders_model.php rename to webht/third_party/vendorPlanSync/models/BIZ_orders_model.php index 78bfb4aa..1162bdc2 100644 --- a/webht/third_party/vendorPlanSync/models/orders_model.php +++ b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php @@ -4,7 +4,7 @@ * 这里操作的都是商务表, 传统订单的表不在这里 */ -class Orders_model extends CI_Model { +class BIZ_Orders_model extends CI_Model { function __construct() { parent::__construct(); diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php new file mode 100644 index 00000000..601e026e --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -0,0 +1,31 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Group_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + public function get_vendor_plan_info($gri_sn, $vendor_id) + { + $sql = " SP_VendorPlan_GetPlanInfo $gri_sn, $vendor_id, 0 "; + return $this->HT->query($sql)->result(); + } + + public function get_guestlist($COLD_SN_str) + { + $sql = "SELECT * + FROM BIZ_BookPeopleList BPL + INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN + WHERE BPL_COLD_SN IN ($COLD_SN_str)"; + $query = $this->HT->query($sql); + return $query->result(); + } + + +} + +/* End of file Group_model.php */ +/* Location: ./third_party/vendorPlanSync/models/Group_model.php */ From 5a5c399cc367a6dba2d5a08e51ea866cff449c1c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 16 Oct 2018 14:22:35 +0800 Subject: [PATCH 167/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E7=9A=84=E5=9B=A2=E5=8F=B7=E8=A7=A3=E6=9E=90=E8=A7=84=E5=88=99?= =?UTF-8?q?,=20=E9=81=BF=E5=85=8D=E5=9B=BE=E5=85=B0=E6=9C=B5=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=9B=A2=E5=8F=B7=E5=AF=BC=E8=87=B4=E5=90=8C=E6=AD=A5?= =?UTF-8?q?=E4=BA=A7=E7=94=9F=E9=87=8D=E5=A4=8D=E8=AE=A2=E5=8D=95;=20?= =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8=E7=9A=84report=5Ftour=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 21 +++++++++++---- .../trippestOrderSync/controllers/api.php | 7 ++--- .../helpers/array_helper.php | 4 ++- .../models/orderFinance_model.php | 26 ++++++++++++++----- 4 files changed, 42 insertions(+), 16 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 7f8b086a..4986a4ee 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -143,9 +143,14 @@ class TulanduoApi extends CI_Controller // set GCI_SN $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 if ($this->Orders_model->BIZ_COLI_SN === null) { - $real_groupCode = analysis_groupCode($vo['agcOrderNo']); + $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']); + $real_groupCode = $real_groupCode_info["cut"]; // set BIZ_COLI_SN, GRI_SN at Orders_model - $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + if (empty($group_info)) { + $real_groupCode = $real_groupCode_info["all"]; + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + } } if ($this->Orders_model->GRI_SN === null) { /** GRoupInfo */ @@ -262,7 +267,8 @@ class TulanduoApi extends CI_Controller $getInfo_byGroupCode = null; $getInfo_byGroupCodeArr = array(); if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo != "") { - $real_groupCode = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $real_groupCode_info = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); + $real_groupCode = $real_groupCode_info['cut']; $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); } $duplicate = false; @@ -674,9 +680,14 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_SN = null; $this->Orders_model->GRI_SN = null; if ( isset($vo['agcOrderNo']) && $vo['agcOrderNo'] != "") { - $real_groupCode = analysis_groupCode($vo['agcOrderNo']); + $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']); + $real_groupCode = $real_groupCode_info["cut"]; // check BIZ_COLI_SN,GRI_SN - $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + if (empty($group_info)) { + $real_groupCode = $real_groupCode_info["all"]; + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + } } /** INSERT */ /** GRoupInfo */ diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 60b8d0b7..78f7311f 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -34,7 +34,8 @@ class Api extends CI_Controller { } $ret['status'] = 1; $ret['msg'] = ""; - $ret['group_number'] = analysis_groupCode($order_project[0]->COLI_GroupCode); + $group_number_info = analysis_groupCode($order_project[0]->COLI_GroupCode); + $ret['group_number'] = $group_number_info["cut"]; $all_combine_no = array_unique(array_map(function($ele) { return $ele->GCI_combineNo; @@ -166,8 +167,8 @@ class Api extends CI_Controller { /** 外联信息 */ $raw_opi_id = 0; if (intval($order_project[0]->COLI_OPI_ID) === 435) { - $real_code = analysis_groupCode($ret['group_number']); - $raw_opi_id = $this->Orders_model->get_gri_opi_id($real_code); + $real_code_info = analysis_groupCode($ret['group_number']); + $raw_opi_id = $this->Orders_model->get_gri_opi_id($real_code_info['cut']); } else { $raw_opi_id = $order_project[0]->COLI_OPI_ID; } diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index f66c6d2b..1d4fce17 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -129,6 +129,7 @@ function analysis_groupCode($groupCode) $real_groupCode .= "-"; $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; } + $ret["cut"] = trim_str(trim($real_groupCode)); for ($i=2; $i < count($tmp_groupCode); $i++) { if (strlen($tmp_groupCode[$i]) > 4) { $real_groupCode .= "-"; @@ -136,7 +137,8 @@ function analysis_groupCode($groupCode) } } $real_groupCode = trim_str(trim($real_groupCode)); - return $real_groupCode; + $ret["all"] = $real_groupCode; + return $ret; } function trim_str($groupCode) { diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 7f398f3e..6f6c0ffc 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -209,8 +209,14 @@ class OrderFinance_model extends CI_Model { /** 判断各种项目的报表是否已存在 */ public function report_tour_exists($coli_id=null, $tourCode=null, $tourBz=null) { - $sql = "SELECT top 1 ordernumber from report_tour where ordernumber=? and tourCode=? and tourBz=? "; - $num_rows = $this->HT->query($sql, array($coli_id, $tourCode, $tourBz))->num_rows(); + $sql = "SELECT top 10 ordernumber from report_tour where ordernumber=? and tourCode=? "; + if ($tourBz) { + $tourBz = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($tourBz, ",", true)); + $tourBz = str_replace("[", "[[]", $tourBz); + $sql .= " and (tourBz like '%" . $this->HT->escape_like_str($tourBz) . "%' + OR tourBz='') "; + } + $num_rows = $this->HT->query($sql, array($coli_id, $tourCode))->num_rows(); return $num_rows>0; } public function report_train_exists($coli_id=null, $TrainNo=null) @@ -236,14 +242,20 @@ class OrderFinance_model extends CI_Model { public function insert_report_tour_tulanduo($report_tour_arr=array()) { foreach ($report_tour_arr as $krt => $vrt) { + $tourBz_tmp = ""; if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode'], $vrt['tourBZ']) === TRUE) { $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "' "; - $where .= " AND tourBZ='" . $vrt['tourBZ'] . "' "; - $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); - $this->HT->query($update_sql); - } else { - $this->HT->insert('tourmanager.dbo.Report_Tour', $vrt); + $tourBz_tmp = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($vrt['tourBZ'], ",", true)); + $tourBz_tmp = str_replace("[", "[[]", $tourBz_tmp); + $where .= " AND (tourBZ like '%" . $this->HT->escape_like_str($tourBz_tmp) . "%' + OR tourBZ='') "; + $delete_sql = "DELETE FROM tourmanager.dbo.Report_Tour where " . $where; + // $update_sql = $this->HT->update_string('tourmanager.dbo.Report_Tour', $vrt, $where); + $this->HT->query($delete_sql); } + // else { + $this->HT->insert('tourmanager.dbo.Report_Tour', $vrt); + // } } return TRUE; } From 4073dc449c8f6ec3e5e6eb54a51436d0a62d0b5a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 17 Oct 2018 16:03:29 +0800 Subject: [PATCH 168/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E8=AE=A2=E5=8D=95=E4=B8=8D=E8=AE=B0=E5=BD=95=E4=BB=A3?= =?UTF-8?q?=E6=94=B6=E4=BB=A3=E4=BB=98=E6=95=B0=E6=8D=AE,=20=E4=B8=8D?= =?UTF-8?q?=E5=8F=82=E4=B8=8E=E5=88=A9=E6=B6=A6=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 26 ++++++++++--------- .../trippestOrderSync/models/orders_model.php | 4 +++ 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4986a4ee..a232d0fd 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -439,32 +439,33 @@ class TulanduoApi extends CI_Controller // 删除旧的录入 $this->Orders_model->biz_groupaccountinfo_cut($coli_sn, $paytype); if (intval($latest_order_detail[0]->COLI_OPI_ID)===435) { + $gai_vei_sn = $latest_order_detail[0]->COLD_PlanVEI_SN; // 团款 if (isset($detail_jsonResp->orderDetail->travelFees) ) { foreach ($detail_jsonResp->orderDetail->travelFees as $ktf => $vtf) { - $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vtf->sumMoney, $vtf->sumMoney, $auto_text . "代收" . $vtf->type . ", " . $vtf->remark); + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vtf->sumMoney, $vtf->sumMoney,$gai_vei_sn, $auto_text . "团款" . $vtf->type . ", " . $vtf->remark); } } // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. // 代收 if (isset($detail_jsonResp->orderDetail->replaceCollections) ) { - foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { - $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vrc->money, $vrc->money, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark); - } + // foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { + // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vrc->money, $vrc->money,$gai_vei_sn, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark); + // } } if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $koor => $voor) { - $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $voor->sumMoney, $voor->sumMoney, $auto_text . "代收" . $voor->type . ", " . $voor->remark); + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $voor->sumMoney, $voor->sumMoney, $gai_vei_sn, $auto_text . "其他收入" . $voor->type . ", " . $voor->remark); } } // 代付 if (isset($detail_jsonResp->orderDetail->replacePays) ) { - foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { - $GAI_SQJE = "-" . $vrp->money; - $GAI_SSJE = "-" . $vrp->money; - $GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; - $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $GAI_Memo); - } + // foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { + // $GAI_SQJE = "-" . $vrp->money; + // $GAI_SSJE = "-" . $vrp->money; + // $GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; + // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo); + // } } } /*BIZ_GroupCombineOperationDetail*/ @@ -713,7 +714,7 @@ class TulanduoApi extends CI_Controller return; } - public function insert_gai($coli_sn, $gri_sn, $coli_id, $paytype, $currency, $sqje, $ssje, $memo="") + public function insert_gai($coli_sn, $gri_sn, $coli_id, $paytype, $currency, $sqje, $ssje, $gai_vei_sn, $memo="") { $this->Orders_model->GAI_Operator = 435; $this->Orders_model->GAI_COLI_SN = $coli_sn; @@ -725,6 +726,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->GAI_SSJE = $ssje; $this->Orders_model->GAI_SSDate = date("Y-m-d H:i:s"); $this->Orders_model->GAI_Memo = $memo; + $this->Orders_model->GAI_VEI_SN = $gai_vei_sn; return $this->Orders_model->biz_groupaccountinfo_save(); } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 6fd1032c..c5df5ca1 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1285,6 +1285,7 @@ class Orders_model extends CI_Model { public $GAI_SSJE; public $GAI_SSDate; public $GAI_Operator; + public $GAI_VEI_SN; public $GAI_Memo=""; public function biz_groupaccountinfo_save() { @@ -1300,6 +1301,7 @@ class Orders_model extends CI_Model { . " GAI_SSJE, \n" . " GAI_SSDate, \n" . " GAI_Operator, \n" + . " GAI_VEI_SN, \n" . " GAI_Memo \n" . " ) \n" . "VALUES \n" @@ -1314,6 +1316,7 @@ class Orders_model extends CI_Model { . " ?, \n" . " ?, \n" . " ?, \n" + . " ?, \n" . " ? \n" . " )"; $query = $this->HT->query($sql, array( @@ -1327,6 +1330,7 @@ class Orders_model extends CI_Model { ,$this->GAI_SSJE ,$this->GAI_SSDate ,$this->GAI_Operator + ,$this->GAI_VEI_SN ,$this->GAI_Memo )); return $query; From ab361415e8fe8ed4f75e4f40dbf4d1934a3e44b2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 18 Oct 2018 10:36:06 +0800 Subject: [PATCH 169/382] =?UTF-8?q?tracking:=20=E5=8C=97=E4=BA=AC=E4=B8=A4?= =?UTF-8?q?/=E4=B8=89=E6=97=A5=E6=B8=B8=E4=BA=A7=E5=93=81=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E5=90=8D=E7=A7=B0=E4=BF=AE=E6=94=B9;=20=E6=98=BE?= =?UTF-8?q?=E7=A4=BA=E6=97=A5=E6=9C=9F=E8=8C=83=E5=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 18 +++++++-- .../trippestOrderSync/libraries/trippest.php | 38 +++++++++++++++++++ .../trippestOrderSync/models/orders_query.php | 1 + 3 files changed, 54 insertions(+), 3 deletions(-) create mode 100644 webht/third_party/trippestOrderSync/libraries/trippest.php diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 78f7311f..6b1dce76 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -7,6 +7,7 @@ class Api extends CI_Controller { parent::__construct(); mb_regex_encoding("UTF-8"); $this->load->helper('array'); + $this->load->library('trippest'); $this->load->model('Orders_query', 'Orders_model'); } @@ -60,6 +61,7 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['cardriver'][] = $tmp_car; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; + $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; } else if ($value->GCOD_operationType === 'guiderOperations') { $tmp_g = array(); @@ -72,19 +74,25 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['tourguide'][] = $tmp_g; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; + $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; } } // 加上行程 $num_index = 0; foreach ($ret['operation'] as $kro => &$vro) { + $vro['start_date_raw'] = $vro['start_date']; $out_datetime = strtotime($vro['start_date']); + $out_datetime2 = strtotime($vro['end_date']); $vro['dateWeek_text'] = date('D', $out_datetime); $vro['dateDay_text'] = date('d', $out_datetime); $vro['dateMonth_text'] = date('M', $out_datetime); $vro['dateYear_text'] = date('Y', $out_datetime); + if ($out_datetime !== $out_datetime2) { + $vro['start_date'] = $vro['start_date'] . " to " . $vro['end_date']; + } $poi = new stdclass(); foreach ($order_project as $kd => $poi_info) { - if (strcmp($vro['start_date'], substr($poi_info->COLD_StartDate, 0, 10) ) === 0) { + if (strcmp($vro['start_date_raw'], substr($poi_info->COLD_StartDate, 0, 10) ) === 0) { if (count((array)$poi)===0) { $poi = $poi_info; } else if ($poi->POI_Hotel == "") { @@ -104,6 +112,10 @@ class Api extends CI_Controller { $vro['cold_date'] = $poi->COLD_StartDate; $vro['cold_enddate'] = $poi->COLD_EndDate; $vro['tour_name'] = $poi->PAG2_Name; + $code_name = $this->trippest->tour_name(strtoupper($poi->pag_code)); + if ($code_name !== "") { + $vro['tour_name'] = $code_name; + } // 领队名字 $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); // 行程人数 @@ -155,8 +167,8 @@ class Api extends CI_Controller { $ret['operation'] = array_values($ret['operation']); $ret_operation = array(); foreach ($ret['operation'] as $ko => $vo) { - if (strtotime($vo['start_date']) >= strtotime($vo['cold_date']) - && strtotime($vo['start_date']) <= strtotime($vo['cold_enddate'])) { + if (strtotime($vo['start_date_raw']) >= strtotime($vo['cold_date']) + && strtotime($vo['start_date_raw']) <= strtotime($vo['cold_enddate'])) { unset($vo['cold_date']); unset($vo['cold_enddate']); $ret_operation[] = $vo; diff --git a/webht/third_party/trippestOrderSync/libraries/trippest.php b/webht/third_party/trippestOrderSync/libraries/trippest.php new file mode 100644 index 00000000..b53121b0 --- /dev/null +++ b/webht/third_party/trippestOrderSync/libraries/trippest.php @@ -0,0 +1,38 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Trippest +{ + protected $ci; + + public function __construct() + { + $this->ci =& get_instance(); + } + + public function tour_name($pag_code) + { + $name = ""; + switch ($pag_code) { + case 'BJSIC-41': + $name = "One Day Beijing Highlights Tour"; + break; + case 'BJSIC-42': + $name = "Two-Day Beijing Boutique Small Group Tour"; + break; + case 'BJSIC-43': + $name = "Three-Day Beijing Discovery Tour"; + break; + + default: + # code... + break; + } + return $name; + } + + +} + +/* End of file trippest.php */ +/* Location: ./third_party/trippestOrderSync/libraries/trippest.php */ diff --git a/webht/third_party/trippestOrderSync/models/orders_query.php b/webht/third_party/trippestOrderSync/models/orders_query.php index 27c86be8..9cb773f3 100644 --- a/webht/third_party/trippestOrderSync/models/orders_query.php +++ b/webht/third_party/trippestOrderSync/models/orders_query.php @@ -28,6 +28,7 @@ class Orders_query extends CI_Model { { $order_info_sql = "SELECT GCI_SN,GCI_VendorOrderId,GCI_combineNo + ,(select PAG_code from biz_packageinfo where pag_sn=COLD_ServiceSN) as pag_code ,COLI_SN,COLI_ID,COLD_SN,COLI_GroupCode,COLI_OPI_ID,COLI_OrderDetailText,COLI_PriceMemo ,COLD_ServiceSN,COLD_PersonNum,COLD_ChildNum,COLD_StartDate,COLD_EndDate,cold.COLD_MemoText ,pags.PAGS_Direction,pags.PAGS_describ From c33a710e765496c4d0a00a23ae2742e2cef274f9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Oct 2018 11:29:58 +0800 Subject: [PATCH 170/382] =?UTF-8?q?tracking:=20=E5=A2=9E=E5=8A=A0=E9=99=A4?= =?UTF-8?q?=E4=BA=86=E5=9B=BE=E5=85=B0=E6=9C=B5=E4=BB=A5=E5=A4=96=E7=9A=84?= =?UTF-8?q?=E8=B0=83=E5=BA=A6=E6=9F=A5=E8=AF=A2,=20=E7=9B=AE=E5=89=8D?= =?UTF-8?q?=E6=98=AF=E5=AF=BC=E6=B8=B8=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 138 +++++++++++++++++- .../trippestOrderSync/models/orders_query.php | 55 ++++++- 2 files changed, 180 insertions(+), 13 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 6b1dce76..f12e0184 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -9,6 +9,11 @@ class Api extends CI_Controller { $this->load->helper('array'); $this->load->library('trippest'); $this->load->model('Orders_query', 'Orders_model'); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); } public function index() @@ -20,11 +25,134 @@ class Api extends CI_Controller { public function operation_detail($find=null) { - header('Access-Control-Allow-Origin:*'); - header('Access-Control-Allow-Methods:POST, GET'); - header('Access-Control-Max-Age:0'); - header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); - header('Access-Control-Allow-Credentials:true'); + ($find===null) ? $find = $this->input->get_post('q') : null; + $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); + $order_plan = $this->Orders_model->get_order_vendorplan($find); + if ($find===null || $order_plan == null) { + $ret['status'] = 0; + $ret['msg'] = "Not Found."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + $ret['status'] = 1; + $ret['msg'] = ""; + $gri_sn = $order_plan[0]->VAS_GRI_SN; + $group_number_info = analysis_groupCode($order_plan[0]->COLI_GroupCode); + $ret['group_number'] = $group_number_info["cut"]; + $operation_info = $ht_tourguide = $this->tourguide_common($gri_sn); + if (empty($operation_info)) { + return $this->operation_detail_tulanduo($find); + } + $ret['operation'] = $operation_info; + /** 外联信息 */ + $raw_opi_id = 0; + if (intval($order_plan[0]->COLI_OPI_ID) === 435) { + $real_code_info = analysis_groupCode($ret['group_number']); + $raw_opi_id = $this->Orders_model->get_gri_opi_id($real_code_info['cut']); + } else { + $raw_opi_id = $order_plan[0]->COLI_OPI_ID; + } + $operator = $this->Orders_model->get_operator($raw_opi_id); + if ( ! empty($operator)) { + $ret['operator']['chinese_name'] = $operator->OPI_Name; + $ret['operator']['mobile'] = $operator->OPI_MoveTelephone; + $ret['operator']['email'] = $operator->OPI_Email; + $ret['operator']['english_name'] = $operator->OPI2_Name; + // 英文名没有 + if ($operator->OPI_FirstName == null || $operator->OPI2_Name == null ) { + $ret['operator']['english_name'] = ucfirst(strstr($operator->OPI_Email, "@", true)); + } + } + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + + public function tourguide_common($gri_sn) + { + $operation = array(); + $tourguide = $this->Orders_model->get_plan_tourguide($gri_sn); + if (empty($tourguide)) { + return null; + } + $order_detail = $this->Orders_model->get_order_detail($gri_sn); + foreach ($order_detail as $kd => $poi) { + $operation_tmp = array(); + $operation_tmp['start_date'] = substr($poi->COLD_StartDate, 0, 10); + $out_datetime = strtotime($poi->COLD_StartDate); + $out_datetime2 = strtotime($poi->COLD_EndDate); + $operation_tmp['dateWeek_text'] = date('D', $out_datetime); + $operation_tmp['dateDay_text'] = date('d', $out_datetime); + $operation_tmp['dateMonth_text'] = date('M', $out_datetime); + $operation_tmp['dateYear_text'] = date('Y', $out_datetime); + if ($out_datetime !== $out_datetime2) { + $operation_tmp['start_date'] = $poi->COLD_StartDate . " to " . $poi->COLD_EndDate; + } + $operation_tmp['tour_name'] = $poi->PAG2_Name; + $code_name = $this->trippest->tour_name(strtoupper($poi->pag_code)); + if ($code_name !== "") { + $operation_tmp['tour_name'] = $code_name; + } + // 领队名字 + $operation_tmp['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // 行程人数 + $operation_tmp['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; + $operation_tmp['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; + if ($poi->COLD_ChildNum > 0) { + $operation_tmp['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; + } + $operation_tmp['personNum_text'] .= ")" ; + // 人数 + $operation_tmp['adult_number'] = $poi->COLD_PersonNum; + $operation_tmp['kid_number'] = $poi->COLD_ChildNum; + // 酒店 + $operation_tmp['hotel_name'] = $poi->POI_Hotel; + $operation_tmp['hotel_address'] = $poi->POI_HotelAddress; + $operation_tmp['hotel_tel'] = $poi->POI_HotelPhone; + // 航班/车次 + $operation_tmp['flights_no'] = $poi->POI_FlightsNo; + $operation_tmp['flights_airport'] = $poi->POI_AirPort; + // 接送信息 + $operation_tmp['pick_up'] = ""; + $operation_tmp['drop_off'] = ""; + $decode_MemoText = $memo_text_tmp = ""; + $operation_tmp['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); + $operation_tmp['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); + if ($operation_tmp['pick_up'] === "") { + if (strval($poi->PAGS_Direction) === '0') { + $operation_tmp['pick_up'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + $operation_tmp['drop_off'] .= $poi->POI_Hotel; + } else if (strval($poi->PAGS_Direction) === '1') { + $operation_tmp['pick_up'] .= $poi->POI_Hotel; + $operation_tmp['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + } else { // if ($poi->POI_FlightsNo != "") + $operation_tmp['pick_up'] .= $poi->POI_Hotel; + // $operation_tmp['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; // 结束后送机 + } + } + $opd = new stdclass(); + foreach ($tourguide as $key => $tgi) { + if ($poi->COLD_PlanVEI_SN === $tgi->EOI_VEI_SN + // && strcmp($operation_tmp['start_date_raw'], substr($poi->COLD_StartDate, 0, 10) ) === 0 + ) { + $opd = $tgi; + } + } + if (empty($opd)) { + $opd = $tgi[0]; + } + $tourguide_tmp['guide_name'] = $opd->TGI2_Name; + $tourguide_tmp['guide_tel'] = $opd->TGI_Mobile; + $tourguide_tmp['guide_pic'] = ""; + // $tourguide_tmp['using_startdate'] = $opd->GCOD_startDate; + // $tourguide_tmp['using_enddate'] = $opd->GCOD_endDate; + $operation_tmp['tourguide'][] = $tourguide_tmp; + $tourguide_tmp = array(); + + $operation[] = $operation_tmp; + } + return $operation; + } + + public function operation_detail_tulanduo($find=null) + { ($find===null) ? $find = $this->input->get_post('q') : null; $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); $order_project = $this->Orders_model->get_package_order($find); diff --git a/webht/third_party/trippestOrderSync/models/orders_query.php b/webht/third_party/trippestOrderSync/models/orders_query.php index 9cb773f3..6d68b65f 100644 --- a/webht/third_party/trippestOrderSync/models/orders_query.php +++ b/webht/third_party/trippestOrderSync/models/orders_query.php @@ -24,6 +24,53 @@ class Orders_query extends CI_Model { return 0; } + public function get_order_vendorplan($COLI_ID) + { + $sql = "SELECT COLI_GroupCode,COLI_OPI_ID,vas.* + from BIZ_ConfirmLineInfo coli + left join VendorArrangeState vas on VAS_GRI_SN=COLI_GRI_SN + where COLI_GroupCode like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + OR COLI_PriceMemo like '%" . $this->HT->escape_like_str($COLI_ID) . "%' + "; + return $this->HT->query($sql)->result(); + } + + public function get_order_detail($GRI_SN) + { + $sql = "SELECT + pag2.PAG2_Name + ,(select PAG_code from biz_packageinfo where pag_sn=COLD_ServiceSN) as pag_code + ,pags.PAGS_Direction,pags.PAGS_describ + ,poi.POI_Hotel,poi.POI_HotelAddress,poi.POI_HotelPhone + ,poi.POI_AirPort,poi.POI_FlightsNo + ,GUT_FirstName,GUT_LastName + ,cold.*,coli.* + from BIZ_ConfirmLineDetail cold + inner join BIZ_ConfirmLineInfo coli on COLI_SN=COLD_COLI_SN and cold.DeleteFlag=0 + inner join BIZ_PackageOrderInfo poi on poi.POI_COLD_SN=COLD_SN + inner join BIZ_GUEST g on g.GUT_SN=COLI_GUT_SN + left join BIZ_PackageInfo2 pag2 on pag2.PAG2_PAG_SN=COLD_ServiceSN and pag2.PAG2_LGC=1 + left join BIZ_PackageInfoSub pags on pags.PAGS_SN=cold.COLD_ServiceSN2 + where COLI_GRI_SN=$GRI_SN + order by COLD_StartDate "; + return $this->HT->query($sql)->result(); + } + + public function get_plan_tourguide($GRI_SN) + { + $sql = "SELECT tgi_info.TGI_SN,tgi_info.TGI2_Name,tgi_info.TGI_Mobile + ,eoi.EOI_GetDate,eoi.EOI_Date,eoi.EOI_VEI_SN + from Eva_ObjectInfo eoi + left join + ( select TGI_SN,TGI_Mobile,TGI2_Name from TouristGuideInfo tgi + left join TouristGuideInfo2 tgi2 on TGI2_TGI_SN=TGI_SN and TGI2_LGC=1 + ) as tgi_info on tgi_info.TGI_SN=eoi.EOI_ObjSN + where eoi.EOI_Type=3 and EOI_gri_sn=$GRI_SN + order by eoi.EOI_GetDate "; + return $this->HT->query($sql)->result(); + } + function get_package_order($COLI_ID) { $order_info_sql = "SELECT @@ -50,14 +97,6 @@ class Orders_query extends CI_Model { // OR COLI_ID like '%" . $this->HT->escape_like_str($COLI_ID) . "%' $order_info_query = $this->HT->query($order_info_sql); $ret = $order_info_query->result(); - // if ($order_info_query->num_rows() > 0) { - // $operation_sql = "SELECT gcod.* - // from GroupCombineOperationDetail gcod - // where GCOD_GCI_combineNo=? - // and gcod.GCOD_operationType in ('touristCarOperations','guiderOperations')"; - // $operation_info = $this->HT->query($operation_sql, array($ret['order_info'][0]->GCI_combineNo)); - // $ret['operation_info'] = $operation_info->result(); - // } return $ret; } From 97adc456ec46b214db23f384cf1ea738a50c7951 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Oct 2018 15:08:20 +0800 Subject: [PATCH 171/382] =?UTF-8?q?SMS:=20=E5=A2=9E=E5=8A=A0=E5=9B=BE?= =?UTF-8?q?=E5=85=B0=E6=9C=B5=E4=BB=A5=E5=A4=96=E5=9C=B0=E6=8E=A5=E7=A4=BE?= =?UTF-8?q?=E7=9A=84=E5=AF=BC=E6=B8=B8=E5=AE=89=E6=8E=92,=20=E8=AF=BB?= =?UTF-8?q?=E5=8F=96HT,=20=E6=95=B0=E6=8D=AE=E6=98=AF=E5=9C=B0=E6=8E=A5?= =?UTF-8?q?=E7=A4=BE=E5=9C=A8=E4=BE=9B=E5=BA=94=E5=95=86=E5=B9=B3=E5=8F=B0?= =?UTF-8?q?=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/send_operation.php | 31 +++++++--- .../models/send_operation_model.php | 61 +++++++++++++------ .../trippestOrderSync/views/sms_log.php | 13 +++- 3 files changed, 74 insertions(+), 31 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php index c4d9bc57..b0200d4e 100644 --- a/webht/third_party/trippestOrderSync/controllers/send_operation.php +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -73,15 +73,26 @@ class Send_operation extends CI_Controller { return false; } $order = $ready_order[0]; - if (strtotime($order->GCI_travelDate) < strtotime(date('Y-m-d')) ) { + if (strtotime($order->COLD_StartDate) < strtotime(date('Y-m-d')) ) { echo "已过期"; return; } + $last_update = ""; + $guide_name = ""; + if ($order->gcod != null) { + $split_gcod = explode("@", $order->gcod); + $guide_name = $split_gcod[0]; + $guide_tel = $split_gcod[1]; + $last_update = $split_gcod[2] . " " . $split_gcod[3]; + } else { + $guide_name = strstr($order->eva, "@", true); + $guide_tel = substr(strstr($order->eva, "@"), 1); + } $send_body = array( - "one" => trim($order->GUT_FirstName . " " . $order->GUT_LastName) - ,"two" => substr($order->GCI_travelDate, 0, 10) - ,"three" => $order->GCOD_dutyName - ,"four" => "+86 " . $order->GCOD_dutyTel + "one" => trim($order->guest_name) + ,"two" => substr($order->COLD_StartDate, 0, 10) + ,"three" => $guide_name + ,"four" => "+86 " . $guide_tel ,"phone" => real_phone_number($order->GUT_TEL, $order->GUT_POST) ,"nation_code" => $order->GUT_POST ); @@ -95,7 +106,7 @@ class Send_operation extends CI_Controller { $ht_id = $this->send_model->insert_trippest_sms_log($cb_db); $error_msg = ""; $send_time = date("Y-m-d H:i:s"); - if ($order->GCOD_dutyName !== null) { + if ($guide_name != null) { $send_cb = $this->excute_curl($this->send_url, $send_body); $send_cb_obj = json_decode($send_cb); $update_cb_db["TPSL_sendTime"] = $send_time; @@ -110,15 +121,15 @@ class Send_operation extends CI_Controller { if ($time_flag === "try1") { return; } - if ($order->GCOD_dutyName === null || $error_msg !== "") { + if ($guide_name == null || $error_msg !== "") { // 没有调度或发送失败 // to Alex $operator_mailbody = "<p> Dear Alex: </p>" . "<p>导游信息发送客人失败:<br /></p>" . "<p>订单号:" . $order->COLI_ID ."</p>" . - "<p>发团时间:" . substr($order->GCI_travelDate, 0, 10) ."</p>" . - "<p>导游信息:" . $order->GCOD_dutyName . "(" . $order->GCOD_dutyTel . ")" ."</p>" . - "<p>导游更新时间:" . $order->GCI_createTime . " " . $order->GCOD_creatTime ."</p>" . + "<p>发团时间:" . substr($order->COLD_StartDate, 0, 10) ."</p>" . + "<p>导游信息:" . $guide_name . "(" . $guide_tel . ")" ."</p>" . + "<p>导游更新时间:" . $last_update ."</p>" . "<p>发送时间:" . $send_time ."</p>"; if ($error_msg !== "") { $operator_mailbody .= "<p>发送失败信息:" . $error_msg . "</p>"; diff --git a/webht/third_party/trippestOrderSync/models/send_operation_model.php b/webht/third_party/trippestOrderSync/models/send_operation_model.php index 976de4be..f91606bd 100644 --- a/webht/third_party/trippestOrderSync/models/send_operation_model.php +++ b/webht/third_party/trippestOrderSync/models/send_operation_model.php @@ -38,37 +38,62 @@ class Send_operation_model extends CI_Model { if ($time_flag == "no_send_state") { $send_state_sql = ""; $top = ""; - $sms_state = " ,(select top 1 TPSL_sendState from InfoManager.dbo.trippest_sms_log - where TPSL_COLI_SN=coli.COLI_SN and TPSL_sendContent like '%'+GCOD_startDate+'%' + $sms_state = " ,(SELECT top 1 TPSL_sendState from InfoManager.dbo.trippest_sms_log + where TPSL_COLI_SN=coli.COLI_SN + and TPSL_sendContent like '%'+CONVERT(VARCHAR(10),CONVERT(DATE, COLD_StartDate))+'%' order by TPSL_sendState desc ) as send_state"; } - $search_sql = " AND GCI_travelDate ='$date' "; + $search_sql = " AND COLD_StartDate ='$date' "; if ($COLI_ID !== "") { $search_sql = " AND COLI_ID='" . $COLI_ID . "'"; } - $sql = "SELECT $top GroupCombineOperationDetail.GCOD_SN,COLI_SN,COLI_ID,COLI_groupCode - ,GUT_POST,GUT_TEL - ,PAG_ExtendType,PAG_Code - ,g.GUT_FirstName,g.GUT_LastName - ,gci.* - ,GCOD_startDate,GCOD_operationType,GCOD_dutyName,GCOD_dutyTel,GCOD_creatTime - $sms_state - FROM BIZ_ConfirmLineInfo coli - INNER JOIN BIZ_ConfirmLineDetail cold ON COLD_COLI_SN=COLI_SN + $sql = "SELECT $top + COLI_GroupCode,COLI_SN,COLI_ID + $sms_state + ,GUT_POST,GUT_TEL + ,PAG_Code + ,g.GUT_FirstName+' '+g.GUT_LastName guest_name + ,( + select top 1 GCOD_dutyName+'@'+GCOD_dutyTel+'@'+convert(varchar(20),GCOD_creatTime)+'@'+convert(varchar(20),GCI_createTime) + from GroupCombineInfo + inner join GroupCombineOperationDetail on GCOD_GCI_combineNo=GCI_combineNo + AND GCI_combineNo not IN ('cancel','forbidden') + where GCI_GRI_SN=COLI_GRI_SN + AND GCOD_operationType='guiderOperations' + ) as gcod + ,( + select top 1 TGI2_Name+'@'+TGI_Mobile from Eva_ObjectInfo + left join + ( select TGI_SN,TGI_Mobile,TGI2_Name from TouristGuideInfo tgi + left join TouristGuideInfo2 tgi2 on TGI2_TGI_SN=TGI_SN and TGI2_LGC=1 + ) as tgi_info on tgi_info.TGI_SN=EOI_ObjSN + where EOI_GRI_SN=COLI_GRI_SN and EOI_Type=3 + ) as eva + ,COLD_StartDate + from BIZ_ConfirmLineInfo coli + inner join BIZ_ConfirmLineDetail cold on COLI_SN=COLD_COLI_SN INNER JOIN BIZ_GUEST g ON g.GUT_SN=COLI_GUT_SN and GUT_TEL is not null and GUT_TEL<>'' and GUT_POST<>'' INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=COLD_ServiceSN - LEFT JOIN GroupCombineInfo gci ON COLI_GRI_SN=GCI_GRI_SN - LEFT JOIN GroupCombineOperationDetail ON GCOD_GCI_combineNo=GCI_combineNo - AND GCOD_operationType='guiderOperations' WHERE 1=1 + and COLI_State not in (30,40,50) $search_sql - AND GCI_combineNo not IN ('cancel','forbidden') AND '39009'<>PAG_ExtendType $send_state_sql - ORDER BY GCI_travelDate, COLI_SN - "; + and (exists ( + select top 1 1 from GroupCombineInfo + inner join GroupCombineOperationDetail on GCOD_GCI_combineNo=GCI_combineNo + AND GCI_combineNo not IN ('cancel','forbidden') + where GCI_GRI_SN=COLI_GRI_SN + AND GCOD_operationType='guiderOperations' + ) + OR exists ( + select top 1 1 from Eva_ObjectInfo + where EOI_GRI_SN=COLI_GRI_SN and EOI_Type=3 + ) + ) + ORDER BY COLD_StartDate, COLI_SN"; $query = $this->HT->query($sql); return $query->result(); } diff --git a/webht/third_party/trippestOrderSync/views/sms_log.php b/webht/third_party/trippestOrderSync/views/sms_log.php index 3a597c80..08c17eeb 100644 --- a/webht/third_party/trippestOrderSync/views/sms_log.php +++ b/webht/third_party/trippestOrderSync/views/sms_log.php @@ -93,7 +93,7 @@ <li class="col-sm-1 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo ($key + 1); ?></li> <li class="col-sm-5 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"> - <?php echo $item->COLI_groupCode; ?> + <?php echo $item->COLI_GroupCode; ?> </li> <li class="col-sm-2 nopadding-L" style="overflow:hidden;word-break: break-all;"> @@ -103,8 +103,15 @@ </li> <li class="col-sm-6 nopadding-L" style="overflow:hidden;word-break: break-all;" > - <?php echo $item->GCOD_startDate; ?> <br> - <?php echo $item->GCOD_dutyName; ?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $item->GCOD_dutyTel; ?> + <?php echo substr($item->COLD_StartDate, 0, 10); ?> <br> + <?php + if ($item->gcod != null) { + $split_gcod = explode("@", $item->gcod); + echo $split_gcod[0] . " " . $split_gcod[1]; + } else if ($item->eva != null) { + echo str_replace("@", " ", $item->eva); + } + ?> </li> <li class="col-sm-3 nopadding-L" style="overflow:hidden;word-break: break-all;"> From 5d7cfb160e311ccbfa638e2460cb3f9cd73f4471 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Oct 2018 11:49:41 +0800 Subject: [PATCH 172/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E8=AE=A2=E5=8D=95=E4=B8=8D=E8=AE=B0=E5=BD=95=E4=BB=A3?= =?UTF-8?q?=E6=94=B6=E4=BB=A3=E4=BB=98=E6=95=B0=E6=8D=AE,=20=E4=B8=8D?= =?UTF-8?q?=E5=8F=82=E4=B8=8E=E5=88=A9=E6=B6=A6=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index a232d0fd..f625591e 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -310,9 +310,9 @@ class TulanduoApi extends CI_Controller $coli_sn = isset($coli_sn)&&intval($coli_sn)!==0 ? $coli_sn : $getInfo_byGroupCode->COLI_SN; $coli_id = isset($coli_id) ? $coli_id : $getInfo_byGroupCode->COLI_ID; $cold_sn = isset($cold_sn) ? $cold_sn : $getInfo_byGroupCode->COLD_SN; - $coli_opi_id = 435; - $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : ""; - $coli_state = 9; + $coli_opi_id = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OPI_ID : 435; + $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : ""; + $coli_state = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_State : 9; $coli_orderdetailtext = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; $cold_memotext = isset($cold_sn) ? $this->Orders_model->COLD_MemoText : $getInfo_byGroupCode->COLD_MemoText; } else { @@ -448,25 +448,27 @@ class TulanduoApi extends CI_Controller } // 目的地项目组的订单为了避免重复录入, 外联会沟通录入, 这里不写入. // 代收 - if (isset($detail_jsonResp->orderDetail->replaceCollections) ) { - // foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { - // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $vrc->money, $vrc->money,$gai_vei_sn, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark); - // } - } + // 此处代收是地接社角度的代收, 计算利润时需扣减还给地接社, 因此录入为负. + // 代付同理 + // if (isset($detail_jsonResp->orderDetail->replaceCollections) ) { + // foreach ($detail_jsonResp->orderDetail->replaceCollections as $krc => $vrc) { + // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, '-' . $vrc->money, '-' . $vrc->money,$gai_vei_sn, $auto_text . "代收" . $vrc->type . ", " . $vrc->remark); + // } + // } if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $koor => $voor) { $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $voor->sumMoney, $voor->sumMoney, $gai_vei_sn, $auto_text . "其他收入" . $voor->type . ", " . $voor->remark); } } // 代付 - if (isset($detail_jsonResp->orderDetail->replacePays) ) { - // foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { - // $GAI_SQJE = "-" . $vrp->money; - // $GAI_SSJE = "-" . $vrp->money; - // $GAI_Memo = $auto_text . $vrp->type . ", " . $vrp->remark; - // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo); - // } - } + // if (isset($detail_jsonResp->orderDetail->replacePays) ) { + // foreach ($detail_jsonResp->orderDetail->replacePays as $krp => $vrp) { + // $GAI_SQJE = $vrp->money; + // $GAI_SSJE = $vrp->money; + // $GAI_Memo = $auto_text . "代付" . $vrp->type . ", " . $vrp->remark; + // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo); + // } + // } } /*BIZ_GroupCombineOperationDetail*/ if ( isset($detail_jsonResp->orderDetail->groupOrderNo) ) { From 3abfd132409a015da5aed161584c2133c55cbbec Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Oct 2018 15:02:12 +0800 Subject: [PATCH 173/382] =?UTF-8?q?tracking:=20=E6=94=AF=E6=8C=81BR#XXXX?= =?UTF-8?q?=E7=AD=89=E6=A0=BC=E5=BC=8F=E7=9A=84=E8=BE=93=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/api.php | 10 ++++++---- .../trippestOrderSync/models/orders_query.php | 3 ++- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index f12e0184..d284dcda 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -27,6 +27,8 @@ class Api extends CI_Controller { { ($find===null) ? $find = $this->input->get_post('q') : null; $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); + preg_match('/[\d]+\-?[\w]*/', characet($find, "UTF-8"), $temp_array); + $find = $temp_array[0]; $order_plan = $this->Orders_model->get_order_vendorplan($find); if ($find===null || $order_plan == null) { $ret['status'] = 0; @@ -37,7 +39,7 @@ class Api extends CI_Controller { $ret['msg'] = ""; $gri_sn = $order_plan[0]->VAS_GRI_SN; $group_number_info = analysis_groupCode($order_plan[0]->COLI_GroupCode); - $ret['group_number'] = $group_number_info["cut"]; + $ret['group_number'] = $group_number_info["all"]; $operation_info = $ht_tourguide = $this->tourguide_common($gri_sn); if (empty($operation_info)) { return $this->operation_detail_tulanduo($find); @@ -153,8 +155,8 @@ class Api extends CI_Controller { public function operation_detail_tulanduo($find=null) { - ($find===null) ? $find = $this->input->get_post('q') : null; - $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); + // ($find===null) ? $find = $this->input->get_post('q') : null; + // $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); $order_project = $this->Orders_model->get_package_order($find); if ($find===null || $order_project == null) { $ret['status'] = 0; @@ -164,7 +166,7 @@ class Api extends CI_Controller { $ret['status'] = 1; $ret['msg'] = ""; $group_number_info = analysis_groupCode($order_project[0]->COLI_GroupCode); - $ret['group_number'] = $group_number_info["cut"]; + $ret['group_number'] = $group_number_info["all"]; $all_combine_no = array_unique(array_map(function($ele) { return $ele->GCI_combineNo; diff --git a/webht/third_party/trippestOrderSync/models/orders_query.php b/webht/third_party/trippestOrderSync/models/orders_query.php index 6d68b65f..ccd7140a 100644 --- a/webht/third_party/trippestOrderSync/models/orders_query.php +++ b/webht/third_party/trippestOrderSync/models/orders_query.php @@ -57,8 +57,9 @@ class Orders_query extends CI_Model { return $this->HT->query($sql)->result(); } - public function get_plan_tourguide($GRI_SN) + public function get_plan_tourguide($GRI_SN=0) { + $GRI_SN = $GRI_SN==NULL ? 0 : $GRI_SN; $sql = "SELECT tgi_info.TGI_SN,tgi_info.TGI2_Name,tgi_info.TGI_Mobile ,eoi.EOI_GetDate,eoi.EOI_Date,eoi.EOI_VEI_SN from Eva_ObjectInfo eoi From 9a3ac72ca1c4546e723eb64d42d495b2457f9cf6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Oct 2018 15:20:32 +0800 Subject: [PATCH 174/382] =?UTF-8?q?tracking:=20=E8=B0=83=E6=95=B4=E5=A4=9A?= =?UTF-8?q?=E6=97=A5=E8=A1=8C=E7=A8=8B=E5=AF=BC=E6=B8=B8=E6=88=96=E5=8F=B8?= =?UTF-8?q?=E6=9C=BA=E5=A4=9A=E5=AE=89=E6=8E=92=E7=9A=84=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index d284dcda..9357c565 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -191,7 +191,11 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['cardriver'][] = $tmp_car; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; - $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; + if ( ! $ret['operation'][$value->GCOD_startDate]['end_date'] + || strtotime($ret['operation'][$value->GCOD_startDate]['end_date']) > strtotime($value->GCOD_endDate) + ) { + $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; + } } else if ($value->GCOD_operationType === 'guiderOperations') { $tmp_g = array(); @@ -204,7 +208,11 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['tourguide'][] = $tmp_g; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; - $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; + if ( ! $ret['operation'][$value->GCOD_startDate]['end_date'] + || strtotime($ret['operation'][$value->GCOD_startDate]['end_date']) > strtotime($value->GCOD_endDate) + ) { + $ret['operation'][$value->GCOD_startDate]['end_date']= $value->GCOD_endDate; + } } } // 加上行程 From 410cd1313721ee08d4d06c4f1816ba7e41867e11 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Oct 2018 15:33:12 +0800 Subject: [PATCH 175/382] =?UTF-8?q?SMS:=20=E6=A8=A1=E6=9D=BF=E4=BF=AE?= =?UTF-8?q?=E6=94=B9(=E5=A2=9E=E5=8A=A0=E8=AE=A2=E5=8D=95=E5=8F=B7);?= =?UTF-8?q?=E5=9B=BD=E5=AE=B6=E5=8C=BA=E5=8F=B7=E4=BB=85=E6=95=B0=E5=AD=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/api.php | 2 -- .../trippestOrderSync/controllers/send_operation.php | 10 ++++++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 9357c565..738927d8 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -18,8 +18,6 @@ class Api extends CI_Controller { public function index() { - // echo "string"; - // return; $this->operation_detail(); } diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php index b0200d4e..b17e4c93 100644 --- a/webht/third_party/trippestOrderSync/controllers/send_operation.php +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -50,6 +50,11 @@ class Send_operation extends CI_Controller { * * 这里只是Day Tour 订单, 不含单接送, 因此每个订单仅发送一次 * @date 2018-09-25 */ + /*! + * 模板内容 + * 2018-10-22 + * 【桂林海纳国旅】Hi {1}, your guide on {2} is {3}, (local)mobile is {4}. He/she'll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No. {5} at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest! + */ public function daytour($COLI_ID="") { $now_h = date("H"); @@ -93,8 +98,9 @@ class Send_operation extends CI_Controller { ,"two" => substr($order->COLD_StartDate, 0, 10) ,"three" => $guide_name ,"four" => "+86 " . $guide_tel - ,"phone" => real_phone_number($order->GUT_TEL, $order->GUT_POST) - ,"nation_code" => $order->GUT_POST + ,"five" => $order->COLI_ID + ,"phone" => real_phone_number($order->GUT_TEL, mb_ereg_replace('[\D]', '', $order->GUT_POST)) + ,"nation_code" => mb_ereg_replace('[\D]', '', $order->GUT_POST) ); $cb_db = array( "TPSL_COLI_SN" => $order->COLI_SN From 0592fbfc3756d2bb830ff8ca4183aa939ec478d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 23 Oct 2018 10:24:16 +0800 Subject: [PATCH 176/382] =?UTF-8?q?=E8=AE=BE=E7=BD=AE=E6=88=90=E8=A1=8C?= =?UTF-8?q?=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index f625591e..d9d20b1d 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -377,6 +377,7 @@ class TulanduoApi extends CI_Controller ,"COLI_OrderDetailText" => $new_detail ); if (intval($coli_opi_id)===435) { + $coli_update_column["COLI_IsSuccess"] = 1; // 表示成行订单 $coli_update_column["COLI_State"] = $coli_state; $coli_update_column["COLI_Price"] = $travel_fee; $coli_update_column["COLI_CUrrency"] = $travel_fee_currency; @@ -852,6 +853,7 @@ class TulanduoApi extends CI_Controller $this->Order_update->coli_where_update = " COLI_ID='" . $COLI_ID . "'"; $coli_update_column = array( "COLI_State" => 40 + ,"COLI_IsSuccess" => NULL ); return $this->Order_update->biz_confirmlineinfo_update($coli_update_column); } From 917c4c649ec7b3f142ca6d0c15bec29083024f32 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 24 Oct 2018 10:10:00 +0800 Subject: [PATCH 177/382] tracking: end_date --- webht/third_party/trippestOrderSync/controllers/api.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 738927d8..bd3f12b1 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -189,7 +189,7 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['cardriver'][] = $tmp_car; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; - if ( ! $ret['operation'][$value->GCOD_startDate]['end_date'] + if ( ! isset($ret['operation'][$value->GCOD_startDate]['end_date']) || strtotime($ret['operation'][$value->GCOD_startDate]['end_date']) > strtotime($value->GCOD_endDate) ) { $ret['operation'][$value->GCOD_startDate]['end_date'] = $value->GCOD_endDate; @@ -206,7 +206,7 @@ class Api extends CI_Controller { $ret['operation'][$value->GCOD_startDate]['tourguide'][] = $tmp_g; // 出团时间 $ret['operation'][$value->GCOD_startDate]['start_date'] = $value->GCOD_startDate; - if ( ! $ret['operation'][$value->GCOD_startDate]['end_date'] + if ( ! isset($ret['operation'][$value->GCOD_startDate]['end_date']) || strtotime($ret['operation'][$value->GCOD_startDate]['end_date']) > strtotime($value->GCOD_endDate) ) { $ret['operation'][$value->GCOD_startDate]['end_date']= $value->GCOD_endDate; From 35e95ae11b15d7d97b14598a01751e66abc92d8f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 24 Oct 2018 14:07:11 +0800 Subject: [PATCH 178/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=BB=84=E8=AE=A2?= =?UTF-8?q?=E5=8D=95:=E4=BB=BB=E4=BD=95=E7=8A=B6=E6=80=81=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E5=90=8E=E9=83=BD=E4=BF=AE=E6=94=B9=E4=B8=BA=E6=96=B0?= =?UTF-8?q?=E8=AE=A2=E5=8D=95(=E5=B7=B2=E6=94=AF=E4=BB=98),=E9=87=8D?= =?UTF-8?q?=E5=A4=8D=E5=A4=84=E7=90=86=E9=80=9A=E7=9F=A5=E7=9A=84=E4=B8=8D?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 6 +++-- .../pay/controllers/iPayLinksService.php | 6 +++-- webht/third_party/pay/models/Alipay_model.php | 27 ++++++++++++++++--- .../pay/models/IPayLinks_model.php | 27 ++++++++++++++++--- .../third_party/paypal/controllers/index.php | 8 +++--- .../paypal/models/paypal_model.php | 27 ++++++++++++++++--- 6 files changed, 82 insertions(+), 19 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 80b0d260..eeab05f0 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -386,6 +386,10 @@ class AlipayTradeService extends CI_Controller // $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 // } } else { + // 把订单状态设置为13-新订单已支付 + if (false == $this->Alipay_model->if_biz_gai_exists($item->ALI_dealId) ) { + $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); + } $this->Alipay_model->add_account_info( $GAI_COLI_SN, $advisor_info->COLI_ID, @@ -403,8 +407,6 @@ class AlipayTradeService extends CI_Controller ); // 更新订单主表付款方式,防止没访问thankyou-train.asp $this->Alipay_model->update_paymanner($GAI_COLI_SN); - // 把订单状态设置为13-新订单已支付 - $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 07154dd8..079f41e8 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -463,6 +463,10 @@ class IPayLinksService extends CI_Controller // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); //把订单状态改为已付款 // } } else { + // 把订单状态设置为13-新订单已支付 + if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) { + $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); + } $this->IPayLinks_model->add_account_info( $GAI_COLI_SN, $advisor_info->COLI_ID, @@ -478,8 +482,6 @@ class IPayLinksService extends CI_Controller $item->IPL_dealId, $ht_memo ); - // 把订单状态设置为13-新订单已支付 - $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); // 更新订单主表付款方式,防止没访问thankyou-train.asp if (empty($advisor_info->COLI_PayManner)) { $this->IPayLinks_model->update_paymanner($GAI_COLI_SN); diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 82deefb8..4e7644bb 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -121,14 +121,33 @@ class Alipay_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } + public function if_biz_gai_exists($GAI_AccreditNo) + { + $sql = " SELECT TOP 1 1 FROM BIZ_GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') + AND DeleteFlag=0"; + $result = $this->HT->query($sql, array($GAI_AccreditNo)); + return ($result->num_rows() > 0); + } + //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 8ac260b2..ba7a4687 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -121,14 +121,33 @@ class IPayLinks_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? and COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } + public function if_biz_gai_exists($GAI_AccreditNo) + { + $sql = " SELECT TOP 1 1 FROM BIZ_GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') + AND DeleteFlag=0"; + $result = $this->HT->query($sql, array($GAI_AccreditNo)); + return ($result->num_rows() > 0); + } + //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 36724256..a4d95825 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -812,15 +812,17 @@ class Index extends CI_Controller { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 - $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); //把订单状态改为已付款 } } else { + // 把订单状态设置为13-新订单已支付 + if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { + $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); + } $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); - // 把订单状态设置为13-新订单已支付 - $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); } } //更新还没有填的客邮和交易号de收款记录(传统订单) diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index f65a9675..110d2e70 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -122,14 +122,33 @@ class Paypal_model extends CI_Model { //修改订单状态 public function update_biz_coli_state($coli_sn, $coli_state) { $sql = " - UPDATE BIZ_ConfirmLineInfo - SET COLI_State = ? - WHERE COLI_SN = ? AND COLI_State in (0,1,11,12,13,14,40,50,60,101,102,999) + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,11,12,13,14,40,50,60,101,102,999) "; - $query = $this->HT->query($sql, array($coli_state, $coli_sn)); + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); return $query; } + public function if_biz_gai_exists($GAI_AccreditNo) + { + $sql = " SELECT TOP 1 1 FROM BIZ_GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') + AND DeleteFlag=0"; + $result = $this->HT->query($sql, array($GAI_AccreditNo)); + return ($result->num_rows() > 0); + } + //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 From c3649cc2deaa8008ba9eda4415345050331a0a1e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 25 Oct 2018 09:48:38 +0800 Subject: [PATCH 179/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=E4=BF=AE=E6=94=B9?= =?UTF-8?q?=E5=9B=A2=E5=8F=B7=E8=A7=A3=E6=9E=90;=E5=88=B7=E6=96=B06?= =?UTF-8?q?=E6=9C=88=E4=BB=BD=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/helpers/array_helper.php | 4 +++- webht/third_party/trippestOrderSync/models/orders_model.php | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 1d4fce17..317f4231 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -127,7 +127,9 @@ function analysis_groupCode($groupCode) $real_groupCode = $tmp_groupCode[0]; if (isset($tmp_groupCode[1])) { $real_groupCode .= "-"; - $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + // $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $order_id = mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; + $order_id = mb_strstr($order_id, " ", true)!==false ? mb_strstr($order_id, " ", true) : $order_id; } $ret["cut"] = trim_str(trim($real_groupCode)); for ($i=2; $i < count($tmp_groupCode); $i++) { diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index c5df5ca1..5d42bdf2 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -185,8 +185,8 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' - and gci.GCI_createTime < '" . date('Y-m-d') . "' + and GCI_travelDate between '2018-06-01' and '2018-06-30 23:59:59' + and gci.GCI_createTime < '2018-10-24' and GCI_combineNo not like '%取消%' "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; From 7c9d92f71d47994e0f2c55de32003c831986ad63 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Oct 2018 11:47:24 +0800 Subject: [PATCH 180/382] test --- .../trippestOrderSync/models/orders_model.php | 2 +- .../third_party/vendorPlanSync/controllers/Tulanduo.php | 9 +++++++-- webht/third_party/vendorPlanSync/models/Group_model.php | 9 --------- 3 files changed, 8 insertions(+), 12 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5d42bdf2..1d181545 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -587,7 +587,7 @@ class Orders_model extends CI_Model { inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 WHERE (select OPI_DEI_SN from OperatorInfo where OPI_SN=COLI_OPI_ID)=30 - and coli.COLI_State<>50 and gri.GRI_No LIKE '%$code%' + and coli.COLI_State<>50 and coli.COLI_GroupCode LIKE '%$code%' order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; $query = $this->HT->query($sql); return $query->result(); diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 37d4f782..a56d7ca2 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -58,7 +58,7 @@ class Tulanduo extends CI_Controller mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); - $this->load->model('Orders_model'); + $this->load->model('BIZ_Orders_model', 'Orders_model'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); // $this->output->enable_profiler(TRUE); /** test */ @@ -73,13 +73,18 @@ class Tulanduo extends CI_Controller // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; } + public function order_push($gri_sn) + { + # code... + } + /*! * 发送预订计划到地接系统 * TODO read word into remark * @date 2018-05-02 * @param string $COLI_ID HT系统订单号 */ - public function order_push($COLI_ID="") // test + public function order_push2($COLI_ID="") // test { // exit(); /** 目的地 test */ diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 601e026e..56c9fe4a 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -14,15 +14,6 @@ class Group_model extends CI_Model { return $this->HT->query($sql)->result(); } - public function get_guestlist($COLD_SN_str) - { - $sql = "SELECT * - FROM BIZ_BookPeopleList BPL - INNER JOIN BIZ_BookPeople BPE ON BPL_BPE_SN=BPE_SN - WHERE BPL_COLD_SN IN ($COLD_SN_str)"; - $query = $this->HT->query($sql); - return $query->result(); - } } From f41a51817c533c9e41b5bb92bfc3c9db4f8d685d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Oct 2018 13:45:22 +0800 Subject: [PATCH 181/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=9B=A2=E5=8F=B7?= =?UTF-8?q?=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 45 +++++++++++++------ .../helpers/array_helper.php | 4 ++ .../trippestOrderSync/models/orders_model.php | 7 ++- 3 files changed, 38 insertions(+), 18 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index d9d20b1d..9b4bd23a 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -269,11 +269,18 @@ class TulanduoApi extends CI_Controller if (isset($detail_jsonResp->orderDetail->agcOrderNo) && $detail_jsonResp->orderDetail->agcOrderNo != "") { $real_groupCode_info = analysis_groupCode($detail_jsonResp->orderDetail->agcOrderNo); $real_groupCode = $real_groupCode_info['cut']; + if (strlen($real_groupCode) < 9) { + $real_groupCode = $real_groupCode_info['all']; + } $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); } $duplicate = false; // 由同步新增的订单 或 未找到团号关联 - if (intval($order->COLI_OPI_ID) === 435 || $order->COLI_ID === null || empty($getInfo_byGroupCodeArr)) { + if (intval($order->COLI_OPI_ID) === 435 + || intval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) === 435 + || $order->COLI_ID === null + || empty($getInfo_byGroupCodeArr) + ) { if ( empty($getInfo_byGroupCodeArr)){ $getInfo_byGroupCode = null; // 没有该团号的团信息 } elseif ($order->COLI_ID !== null && strval($getInfo_byGroupCodeArr[0]->COLI_OPI_ID) !== '435') { // 避免intval(null)=0 @@ -281,7 +288,7 @@ class TulanduoApi extends CI_Controller $duplicate = true; } else { foreach ($getInfo_byGroupCodeArr as $kg => $vg) { - if ($vg->GRI_No === substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49)) { + if ($vg->COLI_GroupCode === substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49)) { // 地接拆分的团号,需要全部匹配; 否则为没有团信息 $getInfo_byGroupCode = $vg; break; @@ -312,22 +319,22 @@ class TulanduoApi extends CI_Controller $cold_sn = isset($cold_sn) ? $cold_sn : $getInfo_byGroupCode->COLD_SN; $coli_opi_id = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OPI_ID : 435; $coli_memo = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_Memo : ""; - $coli_state = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_State : 9; + $coli_state = (intval($coli_opi_id) !== 435) ? $getInfo_byGroupCode->COLI_State : 9; $coli_orderdetailtext = ($getInfo_byGroupCode !== null) ? $getInfo_byGroupCode->COLI_OrderDetailText : ""; $cold_memotext = isset($cold_sn) ? $this->Orders_model->COLD_MemoText : $getInfo_byGroupCode->COLD_MemoText; } else { // 已找到的目的地发的计划 // $getInfo_byGroupCode = $order; - $getInfo_byGroupCode = $getInfo_byGroupCode[0]; - $groupSN = $order->COLI_GRI_SN; - $coli_sn = $order->COLI_SN; - $coli_id = $order->COLI_ID; - $coli_memo = $order->COLI_Memo; - $coli_state = $order->COLI_State; - $cold_sn = $order->COLD_SN; // ???多个子订单 !!!仅用于435创建的订单的更新, 因此仅一个 - $coli_opi_id = $order->COLI_OPI_ID; - $coli_orderdetailtext = $order->COLI_OrderDetailText; - $cold_memotext = $order->COLD_MemoText; + $getInfo_byGroupCode = $getInfo_byGroupCodeArr[0]; + $groupSN = $getInfo_byGroupCode->COLI_GRI_SN; + $coli_sn = $getInfo_byGroupCode->COLI_SN; + $coli_id = $getInfo_byGroupCode->COLI_ID; + $coli_memo = $getInfo_byGroupCode->COLI_Memo; + $coli_state = $getInfo_byGroupCode->COLI_State; + $cold_sn = $getInfo_byGroupCode->COLD_SN; // ???多个子订单 !!!仅用于435创建的订单的更新, 因此仅一个 + $coli_opi_id = $getInfo_byGroupCode->COLI_OPI_ID; + $coli_orderdetailtext = $getInfo_byGroupCode->COLI_OrderDetailText; + $cold_memotext = $getInfo_byGroupCode->COLD_MemoText; } /** UPDATE */ // HT 订单有重复时, 以图兰朵的团号为正确的订单, 原本已录入的设为无效 @@ -349,14 +356,24 @@ class TulanduoApi extends CI_Controller ); $this->Order_update->biz_groupcombineinfo_update($gci_update_column); /** GRoupInfo */ - if (intval($order->COLI_OPI_ID) === 435 ) { + $coli_groupcode_ht = analysis_groupCode($getInfo_byGroupCode->COLI_GroupCode); + $groupcode_ht = $coli_groupcode_ht['cut']; + if (intval($coli_opi_id) === 435 ) { $gri_update_column = array( "GRI_No" => $detail_jsonResp->orderDetail->agcOrderNo ,"GRI_Name" => $detail_jsonResp->orderDetail->agcOrderNo ); $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN; $this->Order_update->biz_groupinfo_update($gri_update_column); + } elseif (strlen($groupcode_ht) > 9 && strpos($getInfo_byGroupCode->GRI_Name, $groupcode_ht)===false) { + // $gri_update_column = array( + // "GRI_No" => $getInfo_byGroupCode->COLI_GroupCode + // ,"GRI_Name" => $getInfo_byGroupCode->COLI_GroupCode + // ); + // $this->Order_update->gri_where_update = " GRI_SN=" . $groupSN; + // $this->Order_update->biz_groupinfo_update($gri_update_column); } + /** BIZ_ConfirmLineInfo */ $this->Order_update->coli_where_update = " COLI_SN=" . $coli_sn; $old_memo = mb_strstr($coli_memo, " orderRemark", true)!==false ? mb_strstr($coli_memo, " orderRemark", true) : $coli_memo; diff --git a/webht/third_party/trippestOrderSync/helpers/array_helper.php b/webht/third_party/trippestOrderSync/helpers/array_helper.php index 317f4231..973fd36e 100644 --- a/webht/third_party/trippestOrderSync/helpers/array_helper.php +++ b/webht/third_party/trippestOrderSync/helpers/array_helper.php @@ -130,6 +130,7 @@ function analysis_groupCode($groupCode) // $real_groupCode .= mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; $order_id = mb_strstr($tmp_groupCode[1], "(", true)!==false ? mb_strstr($tmp_groupCode[1], "(", true) : $tmp_groupCode[1]; $order_id = mb_strstr($order_id, " ", true)!==false ? mb_strstr($order_id, " ", true) : $order_id; + $real_groupCode .= $order_id; } $ret["cut"] = trim_str(trim($real_groupCode)); for ($i=2; $i < count($tmp_groupCode); $i++) { @@ -140,6 +141,9 @@ function analysis_groupCode($groupCode) } $real_groupCode = trim_str(trim($real_groupCode)); $ret["all"] = $real_groupCode; + if (strlen($ret['all']) < 9 ) { + $ret['all'] = trim_str(trim($groupCode)); + } return $ret; } function trim_str($groupCode) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5d42bdf2..71692c0d 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -168,7 +168,7 @@ class Orders_model extends CI_Model { // and gci.GCI_createTime < '" . date('Y-m-d') . "' // and GCI_combineNo not like '%取消%' // "; - $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; + $sql .= " ORDER BY isHistory ASC,GCI_travelDate asc, GCI_createTime ASC "; $query = $this->HT->query($sql); return $query->result(); } @@ -186,7 +186,6 @@ class Orders_model extends CI_Model { where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') and GCI_travelDate between '2018-06-01' and '2018-06-30 23:59:59' - and gci.GCI_createTime < '2018-10-24' and GCI_combineNo not like '%取消%' "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; @@ -579,7 +578,7 @@ class Orders_model extends CI_Model { public function get_order_by_groupcode($code) { $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, - coli.COLI_OrderDetailText, + coli.COLI_OrderDetailText,coli.COLI_GroupCode,coli.COLI_GRI_SN, coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, coli.COLI_Memo,cold.COLD_MemoText @@ -587,7 +586,7 @@ class Orders_model extends CI_Model { inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=COLI_SN left JOIN GRoupInfo gri ON coli.COLI_GRI_SN=gri.GRI_SN and GRI_OrderType=227002 WHERE (select OPI_DEI_SN from OperatorInfo where OPI_SN=COLI_OPI_ID)=30 - and coli.COLI_State<>50 and gri.GRI_No LIKE '%$code%' + and coli.COLI_State<>50 and coli.COLI_GroupCode LIKE '%$code%' order by case COLI_OPI_ID when 435 then 1 else 0 end asc,COLI_SN desc"; $query = $this->HT->query($sql); return $query->result(); From 3e3e86102e591ab6da902538e08099c580c0c507 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Oct 2018 17:35:19 +0800 Subject: [PATCH 182/382] =?UTF-8?q?=E8=AE=A1=E5=88=92=E5=8F=91=E9=80=81?= =?UTF-8?q?=E5=9B=BE=E5=85=B0=E6=9C=B5:=20=E8=8E=B7=E5=8F=96=E5=BE=85?= =?UTF-8?q?=E5=8F=91=E9=80=81=E8=AE=A1=E5=88=92;=20=E7=9B=AE=E7=9A=84?= =?UTF-8?q?=E5=9C=B0=E8=AE=A1=E5=88=92=E8=AF=A6=E6=83=85=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=9E=84=E5=BB=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 77 ++++++++++++------- .../models/BIZ_orders_model.php | 12 +-- .../vendorPlanSync/models/Group_model.php | 22 ++++++ 3 files changed, 77 insertions(+), 34 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index a56d7ca2..67555667 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -58,64 +58,82 @@ class Tulanduo extends CI_Controller mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); - $this->load->model('BIZ_Orders_model', 'Orders_model'); + $this->load->model('Group_model'); + $this->load->model('BIZ_orders_model', 'BIZ_order'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); // $this->output->enable_profiler(TRUE); /** test */ - // $this->userId = "358"; - // $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + $this->userId = "358"; + $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; /** Live */ // 目的地 - $this->userId = "1134"; - $this->key = "73d180d05d425fd192e1c5b3097e75ff"; + // $this->userId = "1134"; + // $this->key = "73d180d05d425fd192e1c5b3097e75ff"; // 桂林海纳国旅 // $this->userId = "18"; // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; } - public function order_push($gri_sn) + public function order_push() { - # code... + $start_date = date('Y-m-d'); + $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); + $vei_sn_str = implode(",", $this->vendor_ids); + $ready_to_send = $this->Group_model->get_plan_not_received(1, $vei_sn_str, $start_date, $end_date); + $order = $ready_to_send[0]; + if (strval($order->GRI_OrderType) === "227002" && strval($order->department) === "30") { + // 目的地计划 + return $this->push_trippest($order->GRI_SN); + } + if (strval($order->GRI_OrderType) === "227002") { + // 商务 + } + if (strval($order->GRI_OrderType) === "227001") { + // 传统订单 + } + + return $this->output->set_content_type('application/json')->set_output(json_encode($order)); } /*! - * 发送预订计划到地接系统 - * TODO read word into remark + * 发送目的地项目组预订计划到图兰朵地接系统 * @date 2018-05-02 * @param string $COLI_ID HT系统订单号 */ - public function order_push2($COLI_ID="") // test + public function push_trippest($gri_sn=0) // test { // exit(); /** 目的地 test */ $this->userId = "358"; $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); - $orderinfo = $this->Orders_model->get_orderinfo_detail($COLI_ID); + $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn); if(empty($orderinfo)) {return;} + $COLI_ID = $orderinfo[0]->COLI_ID; $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ; - $guestlist = $this->Orders_model->get_guestlist($COLD_SN_str); - $scheduleDetails = $this->Orders_model->get_scheduleDetails($COLD_SN_str); + $guestlist = $this->BIZ_order->get_guestlist($COLD_SN_str); + $scheduleDetails = $this->BIZ_order->get_scheduleDetails($COLD_SN_str); $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; // 子线路 + // todo 子线路方向 if ($scheduleDetails[0]->PAGS_CN_Title) { $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]"; } $routeName .= " " . $scheduleDetails[0]->PAG_Code; if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { - $scheduleDetails = $this->Orders_model->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); + $scheduleDetails = $this->BIZ_order->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); } - $travelFees = $this->Orders_model->get_paymentDetails($COLI_ID); + $travelFees = $this->BIZ_order->get_paymentDetails($COLI_ID); bcscale(4); $this->tldOrderBuilder->setUserId($this->userId) ->setKey($this->key) ->setOrderType(2) // todo ->setRouteName($routeName) - ->setRouteType($scheduleDetails[0]->CII2_Name . "目的地线路") - ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->CII2_Name) + ->setRouteType($scheduleDetails[0]->city_chinese . "目的地线路") + ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->city_code) ->setAdultNum($orderinfo[0]->COLD_PersonNum) ->setChildNum($orderinfo[0]->COLD_ChildNum) - ->setDestination($scheduleDetails[0]->CII2_Name) + ->setDestination($scheduleDetails[0]->city_chinese) ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)) ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)); // todo 抵离交通 @@ -124,12 +142,13 @@ class Tulanduo extends CI_Controller ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) ->setCustomersDocumentType($key, "护照") // Passport No. ->setCustomersDocumentNo($key, $vg->BPE_Passport) - ->setCustomersOtherInfo($key, $this->Orders_model->GetNationalityName($orderinfo[0]->GUT_NationalityID)); + ->setCustomersOtherInfo($key, $this->BIZ_order->GetNationalityName($orderinfo[0]->GUT_NationalityID)); } foreach ($scheduleDetails as $ks => $vs) { $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title) ->setScheduleDetailsTitle($ks, $vs->PAG2_Name) // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) + // ->setScheduleDetailsTraffic($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) ->setScheduleDetailsBreakFirst($ks, 0 ) ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0) ) ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0)); @@ -147,11 +166,11 @@ class Tulanduo extends CI_Controller /** BIZ_GroupCombineInfo */ // if (json_decode($resp)->status == 1) { // log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); -// $this->Orders_model->GCI_COLI_SN = $orderinfo[0]->COLI_SN; -// $this->Orders_model->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; -// $this->Orders_model->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; -// $this->Orders_model->GCI_FromAgc = "D目的地桂林组"; -// $this->Orders_model->biz_groupcombineinfo_save(); +// $this->BIZ_order->GCI_COLI_SN = $orderinfo[0]->COLI_SN; +// $this->BIZ_order->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; +// $this->BIZ_order->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; +// $this->BIZ_order->GCI_FromAgc = "D目的地桂林组"; +// $this->BIZ_order->biz_groupcombineinfo_save(); // } // email 供应商 todo echo "Order Push done."; @@ -177,20 +196,20 @@ class Tulanduo extends CI_Controller // $vendorID = 29188;//29188 1343; // test $vas_info = array(); if (in_array($input['agcName'], array("D目的地桂林组", "Trippest"))) { - $vas_info = $this->Orders_model->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); + $vas_info = $this->BIZ_order->get_vendorarrangestate_byVendor($input['orderId'], $vendorID); if (empty($vas_info) && ! empty($input['agcOrderNo'])) { $real_groupCode = analysis_groupCode($input['agcOrderNo']); - $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); + $vas_info = $this->BIZ_order->get_vendorarrangestate_byGroup($real_groupCode, $vendorID); } } elseif ($input['agcName'] == '桂林海纳国旅') { $real_groupCode = analysis_groupCode($input['agcOrderNo']); - $vas_info = $this->Orders_model->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID); + $vas_info = $this->BIZ_order->get_vendorarrangestate_byGroup_T($real_groupCode, $vendorID); } if (empty($vas_info)) { $ret['errMsg'] = "未找到订单."; } else { - $vendor_manager = $this->Orders_model->get_vendorContact($vendorID); + $vendor_manager = $this->BIZ_order->get_vendorContact($vendorID); /** VendorArrangeState */ $VAS_ConfirmInfo = $input['orderRemark'] . "\r\n======确认人: " . $input['orderDuty'] . ", 确认时间: " . $input['orderTime']; $VAS_ConfirmInfo .= "\r\n" . $vas_info[0]->VAS_ConfirmInfo; @@ -222,7 +241,7 @@ class Tulanduo extends CI_Controller $mail_body .= "确认说明:" . $input['orderRemark'] . "\r\n"; $mail_body .= "确认人:$vendor_manager->LMI2_Name $vendor_manager->LMI_ListMail 固定电话: $vendor_manager->LMI_Telephone 移动电话:$vendor_manager->LMI_Mobile\r\n"; $mail_body .= "变更内容: " . $vas_info[0]->VAS_ChangeText . "\r\n"; - $this->Orders_model->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name); + $this->BIZ_order->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name); return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } diff --git a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php index 1162bdc2..433d17e6 100644 --- a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php +++ b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php @@ -32,7 +32,7 @@ class BIZ_Orders_model extends CI_Model { } } - public function get_orderinfo_detail($COLI_ID) + public function get_orderinfo_detail($gri_sn) { $sql = "SELECT top 1 coli.COLI_ID, coli.COLI_Department, @@ -42,9 +42,9 @@ class BIZ_Orders_model extends CI_Model { gut.GUT_NationalityID, * FROM BIZ_ConfirmLineInfo coli - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN + INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN and cold.DeleteFlag=0 LEFT JOIN BIZ_GUEST gut ON gut.GUT_SN=coli.COLI_GUT_SN - WHERE coli.COLI_ID='$COLI_ID' + WHERE coli.COLI_GRI_SN=$gri_sn ORDER BY COLI_ApplyDate DESC"; $query = $this->HT->query($sql); return $query->result(); @@ -66,10 +66,12 @@ class BIZ_Orders_model extends CI_Model { /** 根据订号 */ public function get_scheduleDetails($COLD_SN_str) { - $sql = "SELECT * + $sql = "SELECT + (select CII2_name from CItyInfo2 where CII2_CII_SN=PAG_CII_SN and CII2_LGC=2) as city_chinese, + (select CII_PKCode from CItyInfo where CII_SN=PAG_CII_SN) as city_code + ,* FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN - INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN AND (PAG2_LGC = 2) left join BIZ_PackageInfoSub pis on pis.PAGS_PAG_SN=pag.PAG_SN and PAGS_LGC=1 and cold.COLD_ServiceSN2=PAGS_SN WHERE COLD_SN IN ($COLD_SN_str)"; diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 56c9fe4a..2c6d4fa0 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -8,6 +8,26 @@ class Group_model extends CI_Model { $this->HT = $this->load->database('HT', TRUE); } + public function get_plan_not_received($top=1, $vei_sn_str, $start_date=null, $end_date=null) + { + $top_sql = $top>0 ? " TOP $top " : ""; + $sql = "SELECT $top_sql VAS_IsConfirm, VAS_SendVary, GRI_OrderType, GRI_SN, GRI_No, GRI_operator, + (select OPI_DEI_SN from OperatorInfo where OPI_SN=GRI_operator) as department, + vas.* + from VendorArrangeState vas + inner join Eva_ObjectInfo eoi on EOI_GRI_SN=VAS_GRI_SN and EOI_Type=1 and EOI_ObjSN=VAS_VEI_SN + inner join GRoupInfo gri on GRI_SN=VAS_GRI_SN + where 1=1 + and VAS_IsCancel=0 and VAS_Delete=0 and vas.DeleteFlag=0 + and VAS_IsSendSucceed=1 + and VAS_IsConfirm=0 + and EOI_GetDate between '$start_date' and '$end_date' + and VAS_VEI_SN in ($vei_sn_str) + and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) + order by EOI_GetDate asc, vas.VAS_IsConfirm asc "; + return $this->HT->query($sql)->result(); + } + public function get_vendor_plan_info($gri_sn, $vendor_id) { $sql = " SP_VendorPlan_GetPlanInfo $gri_sn, $vendor_id, 0 "; @@ -16,6 +36,8 @@ class Group_model extends CI_Model { + + } /* End of file Group_model.php */ From a0d09c67f5ab53f1eaf86c44e7d2266a272d11c3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 29 Oct 2018 09:32:03 +0800 Subject: [PATCH 183/382] =?UTF-8?q?201806=E6=9C=88=E6=88=90=E6=9C=AC?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=88=B7=E6=96=B0=E5=AE=8C=E6=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/models/orders_model.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 71692c0d..38a9de19 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -185,7 +185,8 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - and GCI_travelDate between '2018-06-01' and '2018-06-30 23:59:59' + and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' + and gci.GCI_createTime < '" . date('Y-m-d') . "' and GCI_combineNo not like '%取消%' "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; From a59c8b3d160fb0a31ad8608b53e1112263736409 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 30 Oct 2018 17:21:22 +0800 Subject: [PATCH 184/382] =?UTF-8?q?=E5=8F=91=E9=80=81=E8=AE=A1=E5=88=92:?= =?UTF-8?q?=20=E6=B5=8B=E8=AF=95=E5=8F=91=E9=80=81=E7=9B=AE=E7=9A=84?= =?UTF-8?q?=E5=9C=B0=E9=A1=B9=E7=9B=AE=E8=AE=A2=E5=8D=95;[=E6=9C=AA?= =?UTF-8?q?=E5=AE=8C=E6=88=90]=E5=8F=91=E9=80=81=E8=AE=B0=E5=BD=95,?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E7=9A=84=E5=AF=B9=E6=96=B9=E7=B3=BB=E7=BB=9F?= =?UTF-8?q?id;[=E6=9C=AA=E8=A7=A3=E5=86=B3]=E5=95=86=E5=8A=A1=E7=BB=84?= =?UTF-8?q?=E8=AE=A1=E5=88=92=E6=96=87=E6=A1=A3=E5=86=85=E5=AE=B9=E5=8F=98?= =?UTF-8?q?=E6=9B=B4=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 269 +++++++++++++----- .../vendorPlanSync/libraries/trippest.php | 63 ++++ .../models/BIZ_orders_model.php | 35 ++- .../vendorPlanSync/models/Group_model.php | 1 + ...uo_addOrUpdateRouteOrderContentBuilder.php | 7 + 5 files changed, 288 insertions(+), 87 deletions(-) create mode 100644 webht/third_party/vendorPlanSync/libraries/trippest.php diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 67555667..2c71b0f6 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -5,16 +5,16 @@ if (!defined('BASEPATH')) class Tulanduo extends CI_Controller { - public $special_route = array( - "BJSIC-42" => "'BJSIC-41','BJSIC-42'" - ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" - ,"XASIC-42" => "'XASIC-41','XASIC-42'" - ); - public $special_route_name = array( - "BJSIC-42" => "北京精品两日游(目的地BJSIC-42)" - ,"BJSIC-43" => "北京精品三日游(目的地BJSIC-43)" - ,"XASIC-42" => "西安精品两日游(目的地XASIC-42)" - ); + // public $special_route = array( + // "BJSIC-42" => "'BJSIC-41','BJSIC-42'" + // ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" + // ,"XASIC-42" => "'XASIC-41','XASIC-42'" + // ); + // public $special_route_name = array( + // "BJSIC-42" => "北京精品两日游(目的地BJSIC-42)" + // ,"BJSIC-43" => "北京精品三日游(目的地BJSIC-43)" + // ,"XASIC-42" => "西安精品两日游(目的地XASIC-42)" + // ); public $city_info = array( "北京分公司" => array( "PlanVEI_SN" => 1343 @@ -58,9 +58,10 @@ class Tulanduo extends CI_Controller mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); + $this->load->library('trippest'); $this->load->model('Group_model'); $this->load->model('BIZ_orders_model', 'BIZ_order'); - $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); + // $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); // $this->output->enable_profiler(TRUE); /** test */ $this->userId = "358"; @@ -74,22 +75,28 @@ class Tulanduo extends CI_Controller // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; } - public function order_push() + public function order_push($GRI_SN=null) { + if ($GRI_SN !== null) { + return $this->push_trippest($GRI_SN); + } $start_date = date('Y-m-d'); $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); $vei_sn_str = implode(",", $this->vendor_ids); $ready_to_send = $this->Group_model->get_plan_not_received(1, $vei_sn_str, $start_date, $end_date); + if (empty($ready_to_send)) { + return; + } $order = $ready_to_send[0]; + // 目的地计划 if (strval($order->GRI_OrderType) === "227002" && strval($order->department) === "30") { - // 目的地计划 return $this->push_trippest($order->GRI_SN); } + // 商务 if (strval($order->GRI_OrderType) === "227002") { - // 商务 } + // 传统订单 if (strval($order->GRI_OrderType) === "227001") { - // 传统订单 } return $this->output->set_content_type('application/json')->set_output(json_encode($order)); @@ -97,10 +104,10 @@ class Tulanduo extends CI_Controller /*! * 发送目的地项目组预订计划到图兰朵地接系统 + * 地接社未接受的或有变更的 * @date 2018-05-02 - * @param string $COLI_ID HT系统订单号 */ - public function push_trippest($gri_sn=0) // test + public function push_trippest($gri_sn=0) { // exit(); /** 目的地 test */ @@ -110,70 +117,178 @@ class Tulanduo extends CI_Controller $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn); if(empty($orderinfo)) {return;} $COLI_ID = $orderinfo[0]->COLI_ID; - $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $orderinfo )) ; - $guestlist = $this->BIZ_order->get_guestlist($COLD_SN_str); - $scheduleDetails = $this->BIZ_order->get_scheduleDetails($COLD_SN_str); - $routeName = isset($this->special_route_name[$scheduleDetails[0]->PAG_Code]) ? $this->special_route_name[$scheduleDetails[0]->PAG_Code] : $scheduleDetails[0]->PAG2_Name; - // 子线路 - // todo 子线路方向 - if ($scheduleDetails[0]->PAGS_CN_Title) { - $routeName .= "[" . $scheduleDetails[0]->PAGS_CN_Title . "]"; - } - $routeName .= " " . $scheduleDetails[0]->PAG_Code; - if (isset($this->special_route[$scheduleDetails[0]->PAG_Code])) { - $scheduleDetails = $this->BIZ_order->get_packageDetails($this->special_route[$scheduleDetails[0]->PAG_Code]); - } $travelFees = $this->BIZ_order->get_paymentDetails($COLI_ID); - bcscale(4); - $this->tldOrderBuilder->setUserId($this->userId) - ->setKey($this->key) - ->setOrderType(2) // todo - ->setRouteName($routeName) - ->setRouteType($scheduleDetails[0]->city_chinese . "目的地线路") - ->setAgcOrderNo($orderinfo[0]->COLI_GroupCode . "-" . $scheduleDetails[0]->city_code) - ->setAdultNum($orderinfo[0]->COLD_PersonNum) - ->setChildNum($orderinfo[0]->COLD_ChildNum) - ->setDestination($scheduleDetails[0]->city_chinese) - ->setTravelDate(strstr($orderinfo[0]->COLD_StartDate, " ", true)) - ->setLeavedDate(strstr($orderinfo[0]->COLD_EndDate, " ", true)) - ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)); // todo 抵离交通 - foreach ($guestlist as $key => $vg) { - $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName) - ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) - ->setCustomersDocumentType($key, "护照") // Passport No. - ->setCustomersDocumentNo($key, $vg->BPE_Passport) - ->setCustomersOtherInfo($key, $this->BIZ_order->GetNationalityName($orderinfo[0]->GUT_NationalityID)); - } - foreach ($scheduleDetails as $ks => $vs) { - $this->tldOrderBuilder->setScheduleDetailsContent($ks, $vs->PAG2_Title) - ->setScheduleDetailsTitle($ks, $vs->PAG2_Name) - // ->set_scheduleDetails($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) - // ->setScheduleDetailsTraffic($ks, "traffic", ($vs->PAG_Vehicle>60001 ? 1 : 0)) - ->setScheduleDetailsBreakFirst($ks, 0 ) - ->setScheduleDetailsDinner($ks, (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0) ) - ->setScheduleDetailsLunch($ks, (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0)); + $fill_order = array(); + $processed_date = array(); + $processed_cold = array(); + foreach ($orderinfo as $ko => $cold) { + if ( ! in_array($cold->COLD_SN, $processed_cold)) { + $processed_cold[] = $cold->COLD_SN; + $all_package = $this->trippest->tour_code($cold->pag_code); + $pag_info = $this->BIZ_order->get_packageDetails(my_implode("'",",",$all_package)); + $fill_order[$cold->pag_code]["cold"][] = $cold; + $fill_order[$cold->pag_code]["package_info"] = $pag_info; + } } - foreach ($travelFees as $kf => $vf) { // todo 发生退款或多笔收款 - $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") - ->setTravelFeesMoney($kf, $vf->GAI_SQJE) - ->setTravelFeesNum($kf, 1) - ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE)) - ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) - ->setTravelFeesRemark($kf, $vf->GAI_Memo); + // $fill_order = array_values($fill_order); + $i=0; + $take_apart = count($fill_order)>1 ? true : false; + foreach ($fill_order as $kf => $vf) { + $i++; + $this->tldOrderBuilder->resetBizContent(); + $order_type = intval($vf["package_info"][0]->PAG_ExtendType)===39009 ? 1 : 2; + $last_code = count($vf["package_info"])-1; + $last_date = count($vf["cold"])-1; + $routeName = $vf["package_info"][0]->PAG2_Name . $vf["cold"][0]->pag_code; + $end_date = strstr($vf["cold"][$last_date]->COLD_StartDate, " ", true); + if (isset($this->trippest->special_route[$vf["cold"][0]->pag_code])) { + $routeName = $this->trippest->special_route[$vf["cold"][0]->pag_code]["name"]; + $extra_day = $this->trippest->special_route[$vf["cold"][0]->pag_code]["day"]-1; + $end_date = date("Y-m-d", strtotime("+$extra_day day", strtotime($vf["cold"][0]->COLD_StartDate))); + } + $agcOrderNo = $vf["cold"][0]->COLI_GroupCode . "-" . $vf["package_info"][0]->city_code; + if ($take_apart===true) { + $agcOrderNo .= "-" . $i; + } + $order_remark = ""; + if (trim($vf['cold'][0]->GUT_TEL) != "") { + $order_remark = "预定人电话:" . trim($vf["cold"][0]->GUT_TEL); + } + $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $vf["cold"] )) ; + $guestlist = $this->BIZ_order->get_guestlist($COLD_SN_str); + $this->tldOrderBuilder->setUserId($this->userId) + ->setKey($this->key) + ->setOrderType($order_type) + ->setRouteName($routeName) + ->setRouteType($vf["package_info"][0]->city_chinese . "目的地线路") + ->setAgcOrderNo($agcOrderNo) + ->setAdultNum($vf["cold"][0]->COLD_PersonNum) + ->setChildNum($vf["cold"][0]->COLD_ChildNum) + ->setDestination($vf["package_info"][0]->city_chinese) + ->setTravelDate(strstr($vf["cold"][0]->COLD_StartDate, " ", true)) + ->setLeavedDate($end_date) + ->setOrderRemark($order_remark) + // ->setOrderRemark(trim($orderinfo[0]->COLI_Memo . "\r\n" . $orderinfo[0]->COLD_Memo . "\r\n" . $orderinfo[0]->COLD_MemoText)) + // todo 抵离交通 + // ->setToTraffic($toTraffic) + // ->setBackTraffic($backTraffic) + ; + foreach ($guestlist as $key => $vg) { + $this->tldOrderBuilder->setCustomersName($key, $vg->BPE_FirstName . " " . $vg->BPE_LastName ) + ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) + ->setCustomersDocumentType($key, "护照") // Passport No. + ->setCustomersDocumentNo($key, $vg->BPE_Passport) + ->setCustomersOtherInfo($key, $this->BIZ_order->GetNationalityName($orderinfo[0]->GUT_NationalityID)); + } + $scheduleDetails = $this->BIZ_order->get_scheduleDetails($COLD_SN_str); + $schedule_obj = array(); + foreach ($scheduleDetails as $ks => $vs) { + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['date'] = substr($vs->COLD_StartDate, 0, 10); + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['lunch'] = (in_array($vs->PAG_Meal, array('61002', '61004')) ? 1 : 0); + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['dinner'] = (in_array($vs->PAG_Meal, array('61003', '61004')) ? 1 : 0); + $this_content = $this_title = ""; + if ( ! isset($schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'])) { + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] = ""; + } + // 人数 + $this_content .= "\r\n人数:" . $vs->COLD_PersonNum . "大"; + ($vs->COLD_ChildNum>0) ? $this_content .= $vs->COLD_ChildNum . "小" : null; + ($vs->COLD_BabyNum>0) ? $this_content .= $vs->COLD_BabyNum . "婴" : null; + $this_content .= "\r\n客人:"; + $this_guest = ""; + foreach ($guestlist as $dkg => $dvg) { + if ($dvg->BPL_COLD_SN == $vs->COLD_SN) { + $this_guest .= "," . $dvg->BPE_FirstName . " " . $dvg->BPE_LastName; + } + } + $this_content .= substr($this_guest, 1); + // 酒店 + $hotels = $this->BIZ_order->get_package_order($vs->COLD_SN); + if (trim($hotels[0]->POI_HotelAddress) != "") { + $this_content .= "\r\n酒店地址:" . $hotels[0]->POI_HotelAddress; + } + if ($hotels[0]->POI_FlightsNo) { + $this_content .= "\r\n航/车次:" . $hotels[0]->POI_FlightsNo; + if ($hotels[0]->POI_FromCity || $hotels[0]->POI_ToCity) { + $this_content .= ", (" . $hotels[0]->POI_FromCity . "-" . $hotels[0]->POI_ToCity . ")"; + } + if ($hotels[0]->POI_Time || $hotels[0]->POI_EndTime) { + $this_content .= ", " . $hotels[0]->POI_Time . " " . $hotels[0]->POI_EndTime; + } + if ($hotels[0]->POI_AirPort) { + $this_content .= ", " . $hotels[0]->POI_AirPort; + } + } + $this_content .= "\r\n"; + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['accommodation'] = $hotels[0]->POI_Hotel; + // 补充行程 + $fill_date = array(); + if (isset($this->trippest->special_route[$vs->PAG_Code])) { + for ($j=0; $j < $this->trippest->special_route[$vs->PAG_Code]['day']; $j++) { + $e_day = date("Y-m-d", strtotime("+$j day", strtotime($vs->COLD_StartDate))); + if ( ! isset($schedule_obj[$e_day]['content'])) { + $schedule_obj[$e_day]['content'] = ""; + } + $schedule_obj[$e_day]['date'] = $e_day; + $fill_date[] = $e_day; + $schedule_obj[$e_day]['code'] = $this->trippest->special_route[$vs->PAG_Code]['code'][$j]; + $pag_detail = $this->BIZ_order->get_packageDetails("'" . $schedule_obj[$e_day]['code'] . "'"); + $schedule_obj[$e_day]['title'] = $pag_detail[0]->PAG2_Name; + $schedule_obj[$e_day]['lunch'] = (in_array($pag_detail[0]->PAG_Meal, array('61002', '61004')) ? 1 : 0); + $schedule_obj[$e_day]['dinner'] = (in_array($pag_detail[0]->PAG_Meal, array('61003', '61004')) ? 1 : 0); + $schedule_obj[$e_day]['content'] .= $schedule_obj[$e_day]['title'] . $this_content; + $schedule_obj[$e_day]['accommodation'] = $hotels[0]->POI_Hotel; + } + } + // 行程 + if ($vs->PAGS_CN_Title) { + $this_title .= "[" . $vs->PAGS_CN_Title . "]"; + } + if ($this_title == "") { + $this_title .= $vs->PAG2_Name; + } + // 补充的行程避免重复 + if ( ! in_array(substr($vs->COLD_StartDate, 0, 10), $fill_date)) { + $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] .= $this_title . $this_content; + } + } + foreach (array_values($schedule_obj) as $kso => $vso) { + $this->tldOrderBuilder->setScheduleDetailsTitle($kso, $vso['date']) + ->setScheduleDetailsContent($kso, $vso['content']) + ->setScheduleDetailsAccommodation($kso, $vso['accommodation']) + // ->setScheduleDetailsTraffic($kso, ($vso->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($kso, 0 ) + ->setScheduleDetailsDinner($kso, $vso['dinner'] ) + ->setScheduleDetailsLunch($kso, $vso['lunch']) + ; + } + // 拆分的订单团款录第一个 + if ($i===1) { + foreach ($travelFees as $kf => $vf) { + $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") + ->setTravelFeesMoney($kf, $vf->GAI_SQJE) + ->setTravelFeesNum($kf, 1) + ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE)) + ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) + ->setTravelFeesRemark($kf, $vf->GAI_Memo); + } + } + echo(($this->tldOrderBuilder->getBizContent()));return; + // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); + // var_dump(($this->tldOrderBuilder->getBizContent())); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + /** BIZ_GroupCombineInfo */ + // if (json_decode($resp)->status == 1) { + // log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); + // $this->BIZ_order->GCI_COLI_SN = $orderinfo[0]->COLI_SN; + // $this->BIZ_order->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; + // $this->BIZ_order->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; + // $this->BIZ_order->GCI_FromAgc = "D目的地桂林组"; + // $this->BIZ_order->biz_groupcombineinfo_save(); + // } } - var_dump(($this->tldOrderBuilder->getBizContent())); - // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - /** BIZ_GroupCombineInfo */ -// if (json_decode($resp)->status == 1) { -// log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); -// $this->BIZ_order->GCI_COLI_SN = $orderinfo[0]->COLI_SN; -// $this->BIZ_order->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; -// $this->BIZ_order->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; -// $this->BIZ_order->GCI_FromAgc = "D目的地桂林组"; -// $this->BIZ_order->biz_groupcombineinfo_save(); -// } // email 供应商 todo - echo "Order Push done."; + // echo "Order Push done."; return; } diff --git a/webht/third_party/vendorPlanSync/libraries/trippest.php b/webht/third_party/vendorPlanSync/libraries/trippest.php new file mode 100644 index 00000000..ebba5748 --- /dev/null +++ b/webht/third_party/vendorPlanSync/libraries/trippest.php @@ -0,0 +1,63 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Trippest +{ + protected $ci; + + public function __construct() + { + $this->ci =& get_instance(); + } + + public function tour_name($pag_code) + { + $name = ""; + switch ($pag_code) { + case 'BJSIC-41': + $name = "One Day Beijing Highlights Tour"; + break; + case 'BJSIC-42': + $name = "Two-Day Beijing Boutique Small Group Tour"; + break; + case 'BJSIC-43': + $name = "Three-Day Beijing Discovery Tour"; + break; + + default: + break; + } + return $name; + } + + public $special_route = array( + "BJSIC-42" => array( + "code" => array('BJSIC-41','BJSIC-42') + ,"name" => "北京精品两日游(目的地BJSIC-42)" + ,"day" => 2 + ) + ,"BJSIC-43" => array( + "code" => array('BJSIC-41','BJSIC-42','BJSIC-43') + ,"name" => "北京精品三日游(目的地BJSIC-43)" + ,"day" => 3 + ) + ,"XASIC-42" => array( + "code" => array('XASIC-41','XASIC-42') + ,"name" => "西安精品两日游(目的地XASIC-42)" + ,"day" => 2 + ) + ); + public function tour_code($pag_code) + { + $ret = array($pag_code); + if (isset($this->special_route[$pag_code])) { + $ret = $this->special_route[$pag_code]["code"]; + } + return $ret; + } + + +} + +/* End of file trippest.php */ +/* Location: ./third_party/vendorPlanSync/libraries/trippest.php */ diff --git a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php index 433d17e6..ee0f1611 100644 --- a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php +++ b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php @@ -34,9 +34,10 @@ class BIZ_Orders_model extends CI_Model { public function get_orderinfo_detail($gri_sn) { - $sql = "SELECT top 1 coli.COLI_ID, + $sql = "SELECT coli.COLI_ID, coli.COLI_Department, cold.COLD_ServiceSN, + (select PAG_Code from biz_packageinfo where PAG_SN=cold.COLD_ServiceSN) as pag_code, cold.COLD_ServiceSN2, cold.COLD_ServiceCity, gut.GUT_NationalityID, @@ -45,7 +46,7 @@ class BIZ_Orders_model extends CI_Model { INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN and cold.DeleteFlag=0 LEFT JOIN BIZ_GUEST gut ON gut.GUT_SN=coli.COLI_GUT_SN WHERE coli.COLI_GRI_SN=$gri_sn - ORDER BY COLI_ApplyDate DESC"; + ORDER BY COLD_StartDate ASC"; $query = $this->HT->query($sql); return $query->result(); } @@ -66,37 +67,51 @@ class BIZ_Orders_model extends CI_Model { /** 根据订号 */ public function get_scheduleDetails($COLD_SN_str) { - $sql = "SELECT + $sql = "SELECT COLD_StartDate, (select CII2_name from CItyInfo2 where CII2_CII_SN=PAG_CII_SN and CII2_LGC=2) as city_chinese, (select CII_PKCode from CItyInfo where CII_SN=PAG_CII_SN) as city_code ,* - FROM BIZ_PackageInfo2 pag2 - INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN - INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN AND (PAG2_LGC = 2) + FROM BIZ_ConfirmLineDetail cold + LEFT JOIN BIZ_PackageInfo2 pag2 ON cold.COLD_ServiceSN=pag2.PAG2_PAG_SN AND (PAG2_LGC = 2) + LEFT JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN left join BIZ_PackageInfoSub pis on pis.PAGS_PAG_SN=pag.PAG_SN and PAGS_LGC=1 and cold.COLD_ServiceSN2=PAGS_SN - WHERE COLD_SN IN ($COLD_SN_str)"; + WHERE COLD_SN IN ($COLD_SN_str) + ORDER BY cold.COLD_StartDate asc "; $query = $this->HT->query($sql); return $query->result(); } /** 根据线路代号 */ public function get_packageDetails($pag_code_str) { - $sql = "SELECT * + $sql = "SELECT *, + (select CII2_name from CItyInfo2 where CII2_CII_SN=PAG_CII_SN and CII2_LGC=2) as city_chinese, + (select CII_PKCode from CItyInfo where CII_SN=PAG_CII_SN) as city_code FROM BIZ_PackageInfo2 pag2 INNER JOIN BIZ_PackageInfo pag ON pag.PAG_SN=pag2.PAG2_PAG_SN and pag2.PAG2_LGC=2 and pag.PAG_DEI_SN=30 - INNER JOIN CItyInfo2 cii2 on CII2_CII_SN=PAG_CII_SN and CII2_LGC=2 WHERE pag.PAG_Code IN ($pag_code_str) order by pag.PAG_Code "; $query = $this->HT->query($sql); return $query->result(); } + /** 酒店信息 */ + public function get_package_order($COLD_SN_str) + { + $sql = "SELECT * + from BIZ_PackageOrderInfo poi + where poi.POI_COLD_SN IN ($COLD_SN_str)"; + return $this->HT->query($sql)->result(); + } + public function get_paymentDetails($COLI_ID) { $sql = "SELECT * FROM BIZ_GroupAccountInfo bgai INNER JOIN BIZ_ConfirmLineInfo coli ON bgai.GAI_COLI_SN=coli.COLI_SN - WHERE coli_ID = '$COLI_ID'"; + WHERE bgai.DeleteFlag=0 AND bgai.GAI_Type NOT IN (15006,15008,15017) + AND ISNULL(bgai.GAI_VEI_SN,0)<>1343 + AND bgai.GAI_SQJE > 0 + AND coli_ID = '$COLI_ID'"; $query = $this->HT->query($sql); return $query->result(); } diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 2c6d4fa0..3a602790 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -23,6 +23,7 @@ class Group_model extends CI_Model { and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' and VAS_VEI_SN in ($vei_sn_str) + and GRI_OrderType=227002 -- test and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) order by EOI_GetDate asc, vas.VAS_IsConfirm asc "; return $this->HT->query($sql)->result(); diff --git a/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php index 66f28198..277ed0b6 100644 --- a/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php +++ b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php @@ -89,6 +89,13 @@ class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model return $this->bizContent; } + public function resetBizContent() + { + $this->bizContentarr['orderData'] = $this->orderData = array(); + $this->bizContent = NULL; + return $this->getBizContent(); + } + public function setUserId($userId) { $this->userId = $userId; From 63d3c4f86f5b109486d93016a3f56e04dc2395e4 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 30 Oct 2018 17:26:53 +0800 Subject: [PATCH 185/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E7=9B=B8=E5=90=8C=E6=8B=BC=E5=9B=A2=E5=8F=B7?= =?UTF-8?q?=E7=9A=84report=5Ftour;=20Tracking:=E8=A7=A3=E5=86=B3warning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/api.php | 9 ++++++--- .../trippestOrderSync/models/orderFinance_model.php | 8 +++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index bd3f12b1..30abde5e 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -24,10 +24,13 @@ class Api extends CI_Controller { public function operation_detail($find=null) { ($find===null) ? $find = $this->input->get_post('q') : null; - $find = (mb_strlen($find)<9) ? null : $this->input->get_post('q'); + $find = (mb_strlen($find)<9) ? null : $find; preg_match('/[\d]+\-?[\w]*/', characet($find, "UTF-8"), $temp_array); - $find = $temp_array[0]; - $order_plan = $this->Orders_model->get_order_vendorplan($find); + $find = isset($temp_array[0]) ? $temp_array[0] : null; + $order_plan = null; + if ($find !== null) { + $order_plan = $this->Orders_model->get_order_vendorplan($find); + } if ($find===null || $order_plan == null) { $ret['status'] = 0; $ret['msg'] = "Not Found."; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 6f6c0ffc..fd3ebe2d 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -209,14 +209,16 @@ class OrderFinance_model extends CI_Model { /** 判断各种项目的报表是否已存在 */ public function report_tour_exists($coli_id=null, $tourCode=null, $tourBz=null) { - $sql = "SELECT top 10 ordernumber from report_tour where ordernumber=? and tourCode=? "; + $sql = "SELECT top 10 ordernumber from report_tour where ordernumber=? "; if ($tourBz) { $tourBz = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($tourBz, ",", true)); $tourBz = str_replace("[", "[[]", $tourBz); $sql .= " and (tourBz like '%" . $this->HT->escape_like_str($tourBz) . "%' OR tourBz='') "; + } else { + $sql .= " AND tourCode='" . $tourCode . "' "; } - $num_rows = $this->HT->query($sql, array($coli_id, $tourCode))->num_rows(); + $num_rows = $this->HT->query($sql, array($coli_id))->num_rows(); return $num_rows>0; } public function report_train_exists($coli_id=null, $TrainNo=null) @@ -244,7 +246,7 @@ class OrderFinance_model extends CI_Model { foreach ($report_tour_arr as $krt => $vrt) { $tourBz_tmp = ""; if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode'], $vrt['tourBZ']) === TRUE) { - $where = " ordernumber='" . $vrt['ordernumber'] . "' AND tourCode='" . $vrt['tourCode'] . "' "; + $where = " ordernumber='" . $vrt['ordernumber'] . "' "; //AND tourCode='" . $vrt['tourCode'] . "' "; $tourBz_tmp = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($vrt['tourBZ'], ",", true)); $tourBz_tmp = str_replace("[", "[[]", $tourBz_tmp); $where .= " AND (tourBZ like '%" . $this->HT->escape_like_str($tourBz_tmp) . "%' From 21aca8d35b0004c1289078d1e2ae12b16ae6f11d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 31 Oct 2018 11:06:35 +0800 Subject: [PATCH 186/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E4=BB=B7=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 18 +++++++++++++++++- .../trippestOrderSync/models/orders_model.php | 18 ++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 9b4bd23a..dba2088a 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -381,6 +381,7 @@ class TulanduoApi extends CI_Controller $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; // 团款总金额 + // 渠道实收 $travel_fee = 0; $travel_fee_currency = 'RMB'; if (isset($detail_jsonResp->orderDetail->travelFees) ) { @@ -389,6 +390,22 @@ class TulanduoApi extends CI_Controller } unset($vtf); } + // 渠道价 + $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); + $total_num = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; + $partner_price = $this->Orders_model->get_partner_price($pag_info->PAG_Code, $total_num, $detail_jsonResp->orderDetail->travelDate); + if ( ! empty($partner_price)) { + $travel_fee_currency = $partner_price->PKP_Currency ? $partner_price->PKP_Currency : "RMB"; + if (strval($partner_price->PKP_PriceType) === "1") { + // 每团 + $travel_fee = $partner_price->PKP_AdultCost; + } else { + // 每人 + $adult_price = bcmul($detail_jsonResp->orderDetail->adultNum, $partner_price->PKP_AdultCost); + $child_price = bcmul($detail_jsonResp->orderDetail->childNum, $partner_price->PKP_ChildCost); + $travel_fee = bcadd($adult_price, $child_price); + } + } $coli_update_column = array( "COLI_Memo" => substr($new_memo, 0, 400) ,"COLI_OrderDetailText" => $new_detail @@ -406,7 +423,6 @@ class TulanduoApi extends CI_Controller * insert BIZ_BookPeople,BIZ_PackageOrderInfo */ /** BIZ_ConfirmLineDetail */ - $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic)); $new_memotext = trim($cold_memotext)===""||(json_decode($cold_memotext)!==null&&!is_numeric(json_decode($cold_memotext))) ? $COLD_MemoText : $cold_memotext; $cold_update_column = array( diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 38a9de19..3c158fd1 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1754,6 +1754,24 @@ class Orders_model extends CI_Model { ); } + /** 获取产品的渠道价格 */ + public function get_partner_price($code="", $person_num=0, $price_date="") + { + $sql = "SELECT TOP 1 PKP_Currency, + PKP_PriceGrade,PKP_ValidDate,PKP_InvalidDate, + PKP_AdultCost,PKP_ChildCost,PKP_BabyCost, + PKP_PriceType --0每人 1每团 + ,p.* + from BIZ_PackageInfo pag + left join BIZ_PackagePrice p on p.PKP_PAG_SN=PAG_SN + where PAG_Code=? and PAG_DEI_SN=30 + and ? between PKP_PersonStart and PKP_PersonStop + and ? between PKP_ValidDate and PKP_InvalidDate + and PKP_VEI_SN in (1343,29188,30548) + order by p.Checked desc, PKP_PriceGrade asc,PKP_ValidDate desc"; // 重复日期的取新的 + return $this->HT->query($sql, array($code, $person_num, $price_date))->row(); + } + //来源终端 tablet mobile desktop public function check_device() { if (isset($_SERVER['HTTP_USER_AGENT'])) { From 3f872775f8f169f7dcd0d82b881a7bf58fb814fd Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 1 Nov 2018 17:23:15 +0800 Subject: [PATCH 187/382] =?UTF-8?q?=E7=9F=AD=E4=BF=A1=E5=86=85=E5=AE=B9?= =?UTF-8?q?=E4=BB=85=E8=AF=BB=E5=8F=96=E8=8B=B1=E6=96=87=E5=90=8D=E5=AD=97?= =?UTF-8?q?,=20=E4=B8=AD=E8=8B=B1=E6=96=87=E6=B7=B7=E5=90=88=E7=9A=84?= =?UTF-8?q?=E7=9F=AD=E4=BF=A1=E8=B4=B9=E5=A4=AA=E8=B4=B5=E4=BA=86!?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/send_operation.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php index b17e4c93..21a70ac1 100644 --- a/webht/third_party/trippestOrderSync/controllers/send_operation.php +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -93,6 +93,7 @@ class Send_operation extends CI_Controller { $guide_name = strstr($order->eva, "@", true); $guide_tel = substr(strstr($order->eva, "@"), 1); } + $guide_name = mb_ereg_replace('[^a-zA-Z]', '', $guide_name); $send_body = array( "one" => trim($order->guest_name) ,"two" => substr($order->COLD_StartDate, 0, 10) From 8fb8a607ecbaaf80395ea4fd40e36ed9404de501 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 8 Nov 2018 11:38:02 +0800 Subject: [PATCH 188/382] =?UTF-8?q?=E8=A1=A5=E7=A9=BA=E7=9A=84=E8=A1=8C?= =?UTF-8?q?=E7=A8=8B,=20=E6=8D=A2=E4=BA=86=E6=B5=8B=E8=AF=95=E8=B4=A6?= =?UTF-8?q?=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 20 ++++++ .../models/orderFinance_model.php | 3 + .../vendorPlanSync/controllers/Tulanduo.php | 72 +++++++++++++------ 3 files changed, 73 insertions(+), 22 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index dba2088a..a33cb823 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -635,6 +635,26 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineoperationdetail_save(); } } + if (isset($detail_jsonResp->orderDetail->operationDetails->trafficOperations)) { + foreach ($detail_jsonResp->orderDetail->operationDetails->trafficOperations as $vto) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "trafficOperations"; + $this->Orders_model->GCOD_subType = $vto->birthland . " " . $vto->destination; + $this->Orders_model->GCOD_title = $vto->trafficNo; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = $vto->useDate; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $vto->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vto->remark; + $this->Orders_model->GCOD_useNum = $vto->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } } $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id; log_message('error', $output_text); diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index fd3ebe2d..91a46b4e 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -116,6 +116,9 @@ class OrderFinance_model extends CI_Model { } elseif ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='餐补(司陪)') { $ret->cost_category['guide_meal'] += $value->cost; continue; + } elseif ($value->GCOD_operationType=='trafficOperations') { + $ret->cost_category['otherCosts'] += $value->cost; + continue; } $ret->cost_category[$value->GCOD_operationType] += $value->cost; } diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 2c71b0f6..63ade2fb 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -47,10 +47,10 @@ class Tulanduo extends CI_Controller // test // public $list_url = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/"; // public $detail_url = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/"; - public $neworder_url = "http://dj.ltsoftware.net:9901/action/api/addOrUpdateRouteOrder/"; + public $neworder_url = "http://ltdj.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/"; // Live - public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; - public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; + // public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; + // public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; public function __construct(){ @@ -63,9 +63,11 @@ class Tulanduo extends CI_Controller $this->load->model('BIZ_orders_model', 'BIZ_order'); // $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); // $this->output->enable_profiler(TRUE); - /** test */ - $this->userId = "358"; - $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + /** test + 902 key:f56541ff40e1afba444d831c5a666195 + */ + $this->userId = "902"; + $this->key = "f56541ff40e1afba444d831c5a666195"; /** Live */ // 目的地 // $this->userId = "1134"; @@ -111,8 +113,8 @@ class Tulanduo extends CI_Controller { // exit(); /** 目的地 test */ - $this->userId = "358"; - $this->key = "a08f26ddc5b1bd4c8e5eafcac28fc1ec"; + $this->userId = "902"; + $this->key = "f56541ff40e1afba444d831c5a666195"; $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn); if(empty($orderinfo)) {return;} @@ -252,15 +254,41 @@ class Tulanduo extends CI_Controller $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] .= $this_title . $this_content; } } - foreach (array_values($schedule_obj) as $kso => $vso) { - $this->tldOrderBuilder->setScheduleDetailsTitle($kso, $vso['date']) - ->setScheduleDetailsContent($kso, $vso['content']) - ->setScheduleDetailsAccommodation($kso, $vso['accommodation']) - // ->setScheduleDetailsTraffic($kso, ($vso->PAG_Vehicle>60001 ? 1 : 0)) - ->setScheduleDetailsBreakFirst($kso, 0 ) - ->setScheduleDetailsDinner($kso, $vso['dinner'] ) - ->setScheduleDetailsLunch($kso, $vso['lunch']) - ; + // 补全空的日期 + $first_date = strstr($vf["cold"][0]->COLD_StartDate, " ", true); + $date1 = new DateTime($first_date); + $date_end = new DateTime($end_date); + $date_diff = $date_end->diff($date1); + $d = ($date_diff->format("%d")); + $all_date = array(); + for ($j=0; $j < ($d+1); $j++) { + $all_date[] = date('Y-m-d', strtotime("+$j day", strtotime($first_date))); + } + $real_date = array_column(array_values($schedule_obj), 'date'); + foreach ($all_date as $kd => $vd) { + if ( ! in_array($vd, $real_date)) { + $this->tldOrderBuilder->setScheduleDetailsTitle($kd, $vd) + ->setScheduleDetailsContent($kd, "无") + ->setScheduleDetailsAccommodation($kd, "") + // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($kd, 0 ) + ->setScheduleDetailsDinner($kd, 0) + ->setScheduleDetailsLunch($kd, 0) + ; + continue; + } + foreach (array_values($schedule_obj) as $kso => $vso) { + if ($vd==$vso['date']) { + $this->tldOrderBuilder->setScheduleDetailsTitle($kd, $vso['date']) + ->setScheduleDetailsContent($kd, $vso['content']) + ->setScheduleDetailsAccommodation($kd, $vso['accommodation']) + // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($kd, 0 ) + ->setScheduleDetailsDinner($kd, $vso['dinner'] ) + ->setScheduleDetailsLunch($kd, $vso['lunch']) + ; + } + } } // 拆分的订单团款录第一个 if ($i===1) { @@ -273,10 +301,10 @@ class Tulanduo extends CI_Controller ->setTravelFeesRemark($kf, $vf->GAI_Memo); } } - echo(($this->tldOrderBuilder->getBizContent()));return; - // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); - // var_dump(($this->tldOrderBuilder->getBizContent())); - // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // echo(($this->tldOrderBuilder->getBizContent())); + $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); + $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + var_dump($resp); /** BIZ_GroupCombineInfo */ // if (json_decode($resp)->status == 1) { // log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); @@ -288,7 +316,7 @@ class Tulanduo extends CI_Controller // } } // email 供应商 todo - // echo "Order Push done."; + echo "Order Push done."; return; } From 885fa0a93a05cd1d69f7abdf0598a49d8b59c899 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 8 Nov 2018 11:40:35 +0800 Subject: [PATCH 189/382] =?UTF-8?q?=E4=BA=A4=E9=80=9A=E7=A5=A8=E6=88=90?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 20 +++++++++++++++++++ .../models/orderFinance_model.php | 3 +++ 2 files changed, 23 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index dba2088a..a33cb823 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -635,6 +635,26 @@ class TulanduoApi extends CI_Controller $this->Orders_model->biz_groupcombineoperationdetail_save(); } } + if (isset($detail_jsonResp->orderDetail->operationDetails->trafficOperations)) { + foreach ($detail_jsonResp->orderDetail->operationDetails->trafficOperations as $vto) { + $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_VEI_SN = $vei_SN; + $this->Orders_model->GCOD_operationType = "trafficOperations"; + $this->Orders_model->GCOD_subType = $vto->birthland . " " . $vto->destination; + $this->Orders_model->GCOD_title = $vto->trafficNo; + $this->Orders_model->GCOD_dutyName = ""; + $this->Orders_model->GCOD_dutyTel = ""; + $this->Orders_model->GCOD_dutyPhoto = ''; + $this->Orders_model->GCOD_startDate = $vto->useDate; + $this->Orders_model->GCOD_endDate = ""; + $this->Orders_model->GCOD_sumMoney = $vto->sumMoney; + $this->Orders_model->GCOD_carLicense = ""; + $this->Orders_model->GCOD_standard = ""; + $this->Orders_model->GCOD_remark = $vto->remark; + $this->Orders_model->GCOD_useNum = $vto->useNum; + $this->Orders_model->biz_groupcombineoperationdetail_save(); + } + } } $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id; log_message('error', $output_text); diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index fd3ebe2d..91a46b4e 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -116,6 +116,9 @@ class OrderFinance_model extends CI_Model { } elseif ($value->GCOD_operationType=='otherCosts' && $value->GCOD_subType=='餐补(司陪)') { $ret->cost_category['guide_meal'] += $value->cost; continue; + } elseif ($value->GCOD_operationType=='trafficOperations') { + $ret->cost_category['otherCosts'] += $value->cost; + continue; } $ret->cost_category[$value->GCOD_operationType] += $value->cost; } From 6e2b6080952a554d83904fe4b73b63121d0c2412 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 8 Nov 2018 14:18:31 +0800 Subject: [PATCH 190/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BA=A7=E7=94=9F?= =?UTF-8?q?=E7=9A=84=E8=AE=A2=E5=8D=95,=20=E4=BF=AE=E6=94=B9=E4=BA=86?= =?UTF-8?q?=E5=9B=A2=E5=8F=B7=E7=94=A8=E4=BE=9B=E5=BA=94=E5=95=86=E7=9A=84?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=8F=B7=E5=8C=B9=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 5 +++++ webht/third_party/trippestOrderSync/models/orders_model.php | 1 + 2 files changed, 6 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index a33cb823..89e945f1 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -288,6 +288,11 @@ class TulanduoApi extends CI_Controller $duplicate = true; } else { foreach ($getInfo_byGroupCodeArr as $kg => $vg) { + // 同步的订单, 修改了团号, 用地接社id匹配 + if(intval($order->COLI_OPI_ID)===435 && $order->GCI_VendorOrderId == $vg->gci) { + $getInfo_byGroupCode = $vg; + break; + } if ($vg->COLI_GroupCode === substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49)) { // 地接拆分的团号,需要全部匹配; 否则为没有团信息 $getInfo_byGroupCode = $vg; diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 3c158fd1..5bcce4e0 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -579,6 +579,7 @@ class Orders_model extends CI_Model { public function get_order_by_groupcode($code) { $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, + (select gci_vendororderId from groupcombineinfo where gci_gri_sn=coli_gri_sn) as gci, coli.COLI_OrderDetailText,coli.COLI_GroupCode,coli.COLI_GRI_SN, coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, From 787b879b6b5a89deafb5425d07407f65fc9a6876 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 8 Nov 2018 14:47:19 +0800 Subject: [PATCH 191/382] =?UTF-8?q?forbidden=20=E7=9A=84=E8=AE=BE=E4=B8=BA?= =?UTF-8?q?=E6=97=A0=E6=95=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/TulanduoApi.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 89e945f1..54a240c8 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -225,6 +225,9 @@ class TulanduoApi extends CI_Controller } if ($detail_jsonResp->errMsg == "您没有查看本订单的权限!") { $this->plan_cancel($order->GCI_VendorOrderId, "forbidden"); + if (intval($order->COLI_OPI_ID) === 435) { + $this->order_cancel($order->COLI_ID); + } } return; } From d22152908daddf02b72c14585d06aa24ecd4cf21 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 9 Nov 2018 14:00:51 +0800 Subject: [PATCH 192/382] =?UTF-8?q?=20=E4=BF=AE=E5=A4=8D=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E7=9A=84=E4=BE=9B=E5=BA=94=E5=95=86=E8=AE=A2=E5=8D=95id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 2 +- .../trippestOrderSync/models/orders_model.php | 7 +++++-- .../vendorPlanSync/controllers/Tulanduo.php | 12 +++++++----- .../vendorPlanSync/models/BIZ_orders_model.php | 1 + 4 files changed, 14 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 54a240c8..b3079415 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -275,7 +275,7 @@ class TulanduoApi extends CI_Controller if (strlen($real_groupCode) < 9) { $real_groupCode = $real_groupCode_info['all']; } - $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode, $order->GCI_VendorOrderId); } $duplicate = false; // 由同步新增的订单 或 未找到团号关联 diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5bcce4e0..edf910d0 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -576,10 +576,13 @@ class Orders_model extends CI_Model { * @date 2018-08-23 * @param [type] $code [description] */ - public function get_order_by_groupcode($code) + public function get_order_by_groupcode($code, $order_id=0) { $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, - (select gci_vendororderId from groupcombineinfo where gci_gri_sn=coli_gri_sn) as gci, + (select top 1 case gci_vendororderId when $order_id then gci_vendororderId else 0 end + from groupcombineinfo where gci_gri_sn=coli_gri_sn + order by case gci_vendororderId when $order_id then 0 else 1 end asc + ) as gci, coli.COLI_OrderDetailText,coli.COLI_GroupCode,coli.COLI_GRI_SN, coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 63ade2fb..588da49a 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -141,7 +141,7 @@ class Tulanduo extends CI_Controller $order_type = intval($vf["package_info"][0]->PAG_ExtendType)===39009 ? 1 : 2; $last_code = count($vf["package_info"])-1; $last_date = count($vf["cold"])-1; - $routeName = $vf["package_info"][0]->PAG2_Name . $vf["cold"][0]->pag_code; + $routeName = $vf["package_info"][0]->PAG2_Name . mb_strtoupper($vf["cold"][0]->pag_code); $end_date = strstr($vf["cold"][$last_date]->COLD_StartDate, " ", true); if (isset($this->trippest->special_route[$vf["cold"][0]->pag_code])) { $routeName = $this->trippest->special_route[$vf["cold"][0]->pag_code]["name"]; @@ -152,6 +152,7 @@ class Tulanduo extends CI_Controller if ($take_apart===true) { $agcOrderNo .= "-" . $i; } + $agcOrderNo .= "(" . $vf["cold"][0]->operator . ")"; $order_remark = ""; if (trim($vf['cold'][0]->GUT_TEL) != "") { $order_remark = "预定人电话:" . trim($vf["cold"][0]->GUT_TEL); @@ -301,10 +302,11 @@ class Tulanduo extends CI_Controller ->setTravelFeesRemark($kf, $vf->GAI_Memo); } } - // echo(($this->tldOrderBuilder->getBizContent())); - $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); - $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - var_dump($resp); + echo(($this->tldOrderBuilder->getBizContent())); + // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // var_dump($resp); + /** BIZ_GroupCombineInfo */ // if (json_decode($resp)->status == 1) { // log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); diff --git a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php index ee0f1611..e9426647 100644 --- a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php +++ b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php @@ -41,6 +41,7 @@ class BIZ_Orders_model extends CI_Model { cold.COLD_ServiceSN2, cold.COLD_ServiceCity, gut.GUT_NationalityID, + (select opi2_name from tourmanager.dbo.operatorinfo2 where opi2_opi_sn=coli_opi_id and opi2_lgc=2) as operator, * FROM BIZ_ConfirmLineInfo coli INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN and cold.DeleteFlag=0 From ef22aa7a90e282f826b087b8d4d9cc2fd29d7de8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 9 Nov 2018 14:04:50 +0800 Subject: [PATCH 193/382] =?UTF-8?q?=E6=A0=B7=E5=BC=8F=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/alipay_list.php | 27 +++++++++++++++++++ .../third_party/pay/views/iPayLinks_list2.php | 27 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php index 7bb47876..c55ceead 100644 --- a/webht/third_party/pay/views/alipay_list.php +++ b/webht/third_party/pay/views/alipay_list.php @@ -21,6 +21,33 @@ .pay_form .result_info{padding-top: 5px!important;} </style> <style type="text/css"> + .modal-open { overflow: hidden } + .modal { display: none; overflow: hidden; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1050; -webkit-overflow-scrolling: touch; outline: 0 } + .modal.fade .modal-dialog { -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); -webkit-transition: -webkit-transform .3s ease-out; -moz-transition: -moz-transform .3s ease-out; -o-transition: -o-transform .3s ease-out; transition: transform .3s ease-out } + .modal.in .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0) } + .modal-open .modal { overflow-x: hidden; overflow-y: auto } + .modal-dialog { position: relative; width: auto; margin: 10px } + .modal-content { position: relative; background-color: #fff; border: 1px solid #999; border: 1px solid rgba(0,0,0,.2); border-radius: 6px; -webkit-box-shadow: 0 3px 9px rgba(0,0,0,.5); box-shadow: 0 3px 9px rgba(0,0,0,.5); background-clip: padding-box; outline: 0 } + .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000 } + .modal-backdrop.fade { opacity: 0; filter: alpha(opacity=0) } + .modal-backdrop.in { opacity: .5; filter: alpha(opacity=50) } + .modal-header { padding: 15px; border-bottom: 1px solid #e5e5e5; min-height: 16.43px } + .modal-header .close { margin-top: -2px } + .modal-title { margin: 0; line-height: 1.428571429 } + .modal-body { position: relative; padding: 30px } + .modal-footer { padding: 30px; text-align: right; border-top: 1px solid #e5e5e5 } + .modal-footer .btn+.btn { margin-left: 5px; margin-bottom: 0 } + .modal-footer .btn-group .btn+.btn { margin-left: -1px } + .modal-footer .btn-block+.btn-block { margin-left: 0 } + .modal-scrollbar-measure { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll } + @media (min-width:768px) { + .modal-dialog { width: 600px; margin: 30px auto } + .modal-content { -webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5); box-shadow: 0 5px 15px rgba(0,0,0,.5) } + .modal-sm { width: 300px } + } + @media (min-width:992px) { + .modal-lg { width: 900px } + } p{margin-bottom: 8.5px;} a{text-decoration: none;} .navbar-header h1{display: inline-block;margin-left: 30px;} diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index 9e7dddf3..6e42ff6a 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -21,6 +21,33 @@ .pay_form .result_info{padding-top: 5px!important;} </style> <style type="text/css"> + .modal-open { overflow: hidden } + .modal { display: none; overflow: hidden; position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1050; -webkit-overflow-scrolling: touch; outline: 0 } + .modal.fade .modal-dialog { -webkit-transform: translate(0, -25%); -ms-transform: translate(0, -25%); -o-transform: translate(0, -25%); transform: translate(0, -25%); -webkit-transition: -webkit-transform .3s ease-out; -moz-transition: -moz-transform .3s ease-out; -o-transition: -o-transform .3s ease-out; transition: transform .3s ease-out } + .modal.in .modal-dialog { -webkit-transform: translate(0, 0); -ms-transform: translate(0, 0); -o-transform: translate(0, 0); transform: translate(0, 0) } + .modal-open .modal { overflow-x: hidden; overflow-y: auto } + .modal-dialog { position: relative; width: auto; margin: 10px } + .modal-content { position: relative; background-color: #fff; border: 1px solid #999; border: 1px solid rgba(0,0,0,.2); border-radius: 6px; -webkit-box-shadow: 0 3px 9px rgba(0,0,0,.5); box-shadow: 0 3px 9px rgba(0,0,0,.5); background-clip: padding-box; outline: 0 } + .modal-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 1040; background-color: #000 } + .modal-backdrop.fade { opacity: 0; filter: alpha(opacity=0) } + .modal-backdrop.in { opacity: .5; filter: alpha(opacity=50) } + .modal-header { padding: 15px; border-bottom: 1px solid #e5e5e5; min-height: 16.43px } + .modal-header .close { margin-top: -2px } + .modal-title { margin: 0; line-height: 1.428571429 } + .modal-body { position: relative; padding: 30px } + .modal-footer { padding: 30px; text-align: right; border-top: 1px solid #e5e5e5 } + .modal-footer .btn+.btn { margin-left: 5px; margin-bottom: 0 } + .modal-footer .btn-group .btn+.btn { margin-left: -1px } + .modal-footer .btn-block+.btn-block { margin-left: 0 } + .modal-scrollbar-measure { position: absolute; top: -9999px; width: 50px; height: 50px; overflow: scroll } + @media (min-width:768px) { + .modal-dialog { width: 600px; margin: 30px auto } + .modal-content { -webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5); box-shadow: 0 5px 15px rgba(0,0,0,.5) } + .modal-sm { width: 300px } + } + @media (min-width:992px) { + .modal-lg { width: 900px } + } p{margin-bottom: 8.5px;} a{text-decoration: none;} .text_padding {padding: 10px ;} From 16d2b5a6e4dca32f60fa4c883e451ae827f960c4 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 9 Nov 2018 14:31:41 +0800 Subject: [PATCH 194/382] =?UTF-8?q?=E6=9F=A5=E8=AF=A2:=20=E6=B2=A1?= =?UTF-8?q?=E6=9C=89=E8=B0=83=E5=BA=A6=E4=BE=9D=E7=84=B6=E8=BF=94=E5=9B=9E?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=BF=A1=E6=81=AF;=20=E5=90=8C=E6=AD=A5:=20?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E5=8C=B9=E9=85=8D=E7=9A=84=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E8=AE=A2=E5=8D=95id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 2 +- .../trippestOrderSync/controllers/api.php | 66 +++++++++++++++++++ .../trippestOrderSync/models/orders_model.php | 7 +- .../trippestOrderSync/views/sms_log.php | 3 +- 4 files changed, 74 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 54a240c8..b3079415 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -275,7 +275,7 @@ class TulanduoApi extends CI_Controller if (strlen($real_groupCode) < 9) { $real_groupCode = $real_groupCode_info['all']; } - $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode); + $getInfo_byGroupCodeArr = $this->Orders_model->get_order_by_groupcode($real_groupCode, $order->GCI_VendorOrderId); } $duplicate = false; // 由同步新增的订单 或 未找到团号关联 diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 30abde5e..9401ca01 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -302,6 +302,72 @@ class Api extends CI_Controller { $num_index++; } unset($vro); + } else { + foreach ($order_project as $kd => $poi) { + $vro = array(); + $vro['start_date_raw'] = $vro['start_date'] = substr($poi->COLD_StartDate, 0, 10); + $out_datetime = strtotime($poi->COLD_StartDate); + $out_datetime2 = strtotime($poi->COLD_EndDate); + $vro['dateWeek_text'] = date('D', $out_datetime); + $vro['dateDay_text'] = date('d', $out_datetime); + $vro['dateMonth_text'] = date('M', $out_datetime); + $vro['dateYear_text'] = date('Y', $out_datetime); + if ($out_datetime !== $out_datetime2) { + $vro['start_date'] = $poi->COLD_StartDate . " to " . $poi->COLD_EndDate; + } + $vro['cold_date'] = $poi->COLD_StartDate; + $vro['cold_enddate'] = $poi->COLD_EndDate; + $vro['tour_name'] = $poi->PAG2_Name; + $code_name = $this->trippest->tour_name(strtoupper($poi->pag_code)); + if ($code_name !== "") { + $vro['tour_name'] = $code_name; + } + // 领队名字 + $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // 行程人数 + $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; + $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; + if ($poi->COLD_ChildNum > 0) { + $vro['personNum_text'] .= " " . $poi->COLD_ChildNum . " Child(ren)"; + } + $vro['personNum_text'] .= ")" ; + // 人数 + $vro['adult_number'] = $order_project[0]->COLD_PersonNum; + $vro['kid_number'] = $order_project[0]->COLD_ChildNum; + // 酒店 + $vro['hotel_name'] = $poi->POI_Hotel; + $vro['hotel_address'] = $poi->POI_HotelAddress; + $vro['hotel_tel'] = $poi->POI_HotelPhone; + // 航班/车次 + $vro['flights_no'] = $poi->POI_FlightsNo; + $vro['flights_airport'] = $poi->POI_AirPort; + // 接送信息 + $vro['pick_up'] = ""; + $vro['drop_off'] = ""; + $decode_MemoText = $memo_text_tmp = ""; + if ($vro['pick_up'] === "" && $poi->COLD_MemoText != null && json_decode($poi->COLD_MemoText) != null) { + $decode_MemoText = json_decode($poi->COLD_MemoText, true); + $vro['pick_up'] = $decode_MemoText['Pick up']; + $vro['drop_off'] = $decode_MemoText['Drop off']; + } + if ($vro['pick_up'] === "" && $kd == 0) { + $vro['pick_up'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Pick Up From:"), "\n", true), 13)); + $vro['drop_off'] = trim(substr(strstr(strstr($poi->COLI_OrderDetailText, "Drop Off:"), "\n" , true), 9)); + } + if ($vro['pick_up'] === "") { + if (strval($poi->PAGS_Direction) === '0') { + $vro['pick_up'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + $vro['drop_off'] .= $poi->POI_Hotel; + } else if (strval($poi->PAGS_Direction) === '1') { + $vro['pick_up'] .= $poi->POI_Hotel; + $vro['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; + } else { // if ($poi->POI_FlightsNo != "") + $vro['pick_up'] .= $poi->POI_Hotel; + // $vro['drop_off'] .= $poi->POI_FlightsNo . " " . $poi->POI_AirPort; // 结束后送机 + } + } + $ret['operation'][] = $vro; + } } $ret['operation'] = array_values($ret['operation']); $ret_operation = array(); diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5bcce4e0..edf910d0 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -576,10 +576,13 @@ class Orders_model extends CI_Model { * @date 2018-08-23 * @param [type] $code [description] */ - public function get_order_by_groupcode($code) + public function get_order_by_groupcode($code, $order_id=0) { $sql = "SELECT COLI_SN,gri.GRI_SN,cold.COLD_PlanVEI_SN,cold.COLD_SN,coli.COLI_ID, - (select gci_vendororderId from groupcombineinfo where gci_gri_sn=coli_gri_sn) as gci, + (select top 1 case gci_vendororderId when $order_id then gci_vendororderId else 0 end + from groupcombineinfo where gci_gri_sn=coli_gri_sn + order by case gci_vendororderId when $order_id then 0 else 1 end asc + ) as gci, coli.COLI_OrderDetailText,coli.COLI_GroupCode,coli.COLI_GRI_SN, coli.COLI_State,coli.COLI_OPI_ID,coli.COLI_Price,coli.COLI_CUrrency GRI_OPI_ID,GRI_operator,GRI_No,GRI_Name, diff --git a/webht/third_party/trippestOrderSync/views/sms_log.php b/webht/third_party/trippestOrderSync/views/sms_log.php index 08c17eeb..0f36160c 100644 --- a/webht/third_party/trippestOrderSync/views/sms_log.php +++ b/webht/third_party/trippestOrderSync/views/sms_log.php @@ -15,13 +15,14 @@ <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> <meta content="yes" name="apple-mobile-web-app-capable"> <meta name="referrer" content="always"> - <link href="//data.chinahighlights.com/css/min.php?f=/public/css/global.min.css&amp;v=20180811" rel="stylesheet" type="text/css" /> + <link href="http://www.mycht.cn/css/webht/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> <style type="text/css" media="screen and (max-width:767px)"> .pay_form .form-group{padding-left: 0!important;padding-right: 0!important;} .pay_form .result_info{padding-top: 5px!important;} </style> <style type="text/css"> + li{list-style: none;} p{margin-bottom: 8.5px;} a{text-decoration: none;} .text_padding {padding: 10px ;} From 78535daf0f8749977d0618e92831d8ba5cd4ffa0 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 9 Nov 2018 17:23:30 +0800 Subject: [PATCH 195/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20?= =?UTF-8?q?=E6=B8=A0=E9=81=93=E8=AE=A2=E5=8D=95=E7=9A=84=E6=80=BB=E6=94=B6?= =?UTF-8?q?=E5=85=A5=E5=A1=AB=E6=B8=A0=E9=81=93=E4=BB=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/order_finance.php | 3 +++ .../trippestOrderSync/models/orderFinance_model.php | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 8e9e6b4d..5e355ee4 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -92,6 +92,9 @@ class Order_finance extends CI_Controller { $report_order['RO_PayDescribe'] = $order_payment->payTypeDesc; $report_order['paydate'] = $order_payment->patDate; $report_order['OrderPrice'] = $report_order['money']; + if (strval($order_info->operater) === '435') { + $report_order['money'] = $order_info->OrderPrice; + } /** 订单人数 */ $person_num = $this->OrderFinance_model->get_order_person_num($coli_sn); $report_order['adultnumber'] = $person_num->adult_num; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 91a46b4e..1c5d380c 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -17,7 +17,7 @@ class OrderFinance_model extends CI_Model { coli.COLI_ApplyDate as reservedate ,coli.COLI_Cost as basemoney ,ISNULL(coli.COLI_OtherCost,0) as otherCost - ,dbo.ConvertToRMB('USD',ISNULL(coli.COLI_Price,0)) OrderPrice + ,dbo.ConvertToRMB(ISNULL(coli.COLI_Currency,'USD'),ISNULL(coli.COLI_Price,0)) OrderPrice ,gri.GRI_SN ,gri.GRI_No as TuanName ,opi.OPI_Name as ChinaName,opi.OPI_SN as operater,opi.OPI_DEI_SN ,gut.GUT_NationalityID,COI2_Country as country From 05823df084b57751bd88aea25687a6034b993cb8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 12 Nov 2018 15:12:12 +0800 Subject: [PATCH 196/382] =?UTF-8?q?=E7=A9=BA=E7=9A=84=E6=97=A5=E6=9C=9F?= =?UTF-8?q?=E8=A1=8C=E7=A8=8B=E5=86=99=E6=97=A0;=20=E5=9B=A2=E6=AC=BE?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E5=86=99=E4=BA=BA=E6=B0=91=E5=B8=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/Tulanduo.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 588da49a..0d66b918 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -268,7 +268,7 @@ class Tulanduo extends CI_Controller $real_date = array_column(array_values($schedule_obj), 'date'); foreach ($all_date as $kd => $vd) { if ( ! in_array($vd, $real_date)) { - $this->tldOrderBuilder->setScheduleDetailsTitle($kd, $vd) + $this->tldOrderBuilder->setScheduleDetailsTitle($kd, "无") ->setScheduleDetailsContent($kd, "无") ->setScheduleDetailsAccommodation($kd, "") // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0)) @@ -295,9 +295,9 @@ class Tulanduo extends CI_Controller if ($i===1) { foreach ($travelFees as $kf => $vf) { $this->tldOrderBuilder->setTravelFeesType($kf, "Per Group") - ->setTravelFeesMoney($kf, $vf->GAI_SQJE) + ->setTravelFeesMoney($kf, $vf->GAI_SSJE) ->setTravelFeesNum($kf, 1) - ->setTravelFeesUnit($kf, bcdiv($vf->GAI_SSJE, $vf->GAI_SQJE)) + ->setTravelFeesUnit($kf, 1) ->setTravelFeesSumMoney($kf, $vf->GAI_SSJE) ->setTravelFeesRemark($kf, $vf->GAI_Memo); } From 7916d84dae2d1320e9513b527314618dd599ae82 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 12 Nov 2018 17:26:40 +0800 Subject: [PATCH 197/382] =?UTF-8?q?report=5Ftour=E7=9A=84tour=5Fname?= =?UTF-8?q?=E9=95=BF=E5=BA=A6;=20=E5=A4=9A=E6=97=A5=E6=B8=B8=E7=9A=84?= =?UTF-8?q?=E6=B8=A0=E9=81=93=E4=BB=B7=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 33 +++++++++----- .../controllers/order_finance.php | 4 +- .../trippestOrderSync/libraries/trippest.php | 43 +++++++++++++++++++ 3 files changed, 67 insertions(+), 13 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index b3079415..9c00ccbb 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -60,6 +60,7 @@ class TulanduoApi extends CI_Controller mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); + $this->load->library('trippest'); $this->load->model('Orders_model'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); // $this->output->enable_profiler(TRUE); @@ -399,20 +400,30 @@ class TulanduoApi extends CI_Controller unset($vtf); } // 渠道价 + $partner_fee = 0; + $partner_fee_currency = 'RMB'; $pag_info = $this->analysis_productcode($detail_jsonResp->orderDetail->routeName, $detail_jsonResp->orderDetail->orderId); $total_num = $detail_jsonResp->orderDetail->adultNum+$detail_jsonResp->orderDetail->childNum; - $partner_price = $this->Orders_model->get_partner_price($pag_info->PAG_Code, $total_num, $detail_jsonResp->orderDetail->travelDate); - if ( ! empty($partner_price)) { - $travel_fee_currency = $partner_price->PKP_Currency ? $partner_price->PKP_Currency : "RMB"; - if (strval($partner_price->PKP_PriceType) === "1") { - // 每团 - $travel_fee = $partner_price->PKP_AdultCost; - } else { - // 每人 - $adult_price = bcmul($detail_jsonResp->orderDetail->adultNum, $partner_price->PKP_AdultCost); - $child_price = bcmul($detail_jsonResp->orderDetail->childNum, $partner_price->PKP_ChildCost); - $travel_fee = bcadd($adult_price, $child_price); + $all_pag = $this->trippest->get_complex_pag(strtoupper($pag_info->PAG_Code)); + foreach ($all_pag as $kp => $vp) { + $partner_price = $this->Orders_model->get_partner_price(strtoupper($vp), $total_num, $detail_jsonResp->orderDetail->travelDate); + if ( ! empty($partner_price)) { + $partner_fee_currency = $partner_price->PKP_Currency ? $partner_price->PKP_Currency : "RMB"; + if (strval($partner_price->PKP_PriceType) === "1") { + // 每团 + $partner_fee += $partner_price->PKP_AdultCost; + } else { + // 每人 + $adult_price = bcmul($detail_jsonResp->orderDetail->adultNum, $partner_price->PKP_AdultCost); + $child_price = bcmul($detail_jsonResp->orderDetail->childNum, $partner_price->PKP_ChildCost); + $partner_fee += bcadd($adult_price, $child_price); + } } + $partner_price = null; + } + if ($partner_fee > 0) { + $travel_fee = $partner_fee; + $travel_fee_currency = $partner_fee_currency; } $coli_update_column = array( "COLI_Memo" => substr($new_memo, 0, 400) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 5e355ee4..f5033d91 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -128,7 +128,7 @@ class Order_finance extends CI_Controller { $processed_cold_sn = array_merge($processed_cold_sn,$ret->pvt->cold_sn); $report_tour_pvt['ordernumber'] = $ret->pvt->coli_id; $report_tour_pvt['tourCode'] = mb_substr($ret->pvt->PAG_Code, 0, 50); - $report_tour_pvt['tourname'] = mb_substr($ret->pvt->pag_name, 0, 200); + $report_tour_pvt['tourname'] = substr($ret->pvt->pag_name, 0, 200); $report_tour_pvt['tourtime'] = $ret->pvt->startdate; $report_tour_pvt['tourRSd'] = $ret->pvt->adult_num; $report_tour_pvt['tourRSx'] = $ret->pvt->child_num; @@ -160,7 +160,7 @@ class Order_finance extends CI_Controller { $cost_c = array(); $cost_c['ordernumber'] = $cost->coli_id; $cost_c['tourCode'] = mb_substr(implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))), 0, 50); - $cost_c['tourname'] = mb_substr($cost->pag_name, 0, 200) ; + $cost_c['tourname'] = substr($cost->pag_name, 0, 200) ; $cost_c['tourtime'] = $cost->startdate; $cost_c['tourRSd'] = $cost->order_cost[0]->adult_num; $cost_c['tourRSx'] = $cost->order_cost[0]->child_num; diff --git a/webht/third_party/trippestOrderSync/libraries/trippest.php b/webht/third_party/trippestOrderSync/libraries/trippest.php index b53121b0..e808b0b5 100644 --- a/webht/third_party/trippestOrderSync/libraries/trippest.php +++ b/webht/third_party/trippestOrderSync/libraries/trippest.php @@ -31,6 +31,49 @@ class Trippest return $name; } + public function complex_tour() + { + return array( + "BJSIC-41" => array( + "name1" => "One Day Beijing Highlights Tour" + ,"name2" => "北京精品一日游(目的地BJSIC-41)" + ,"tours" => array( + "BJSIC-41" + ) + ) + ,"BJSIC-42" => array( + "name1" => "Two-Day Beijing Boutique Small Group Tour" + ,"name2" => "北京精品两日游(目的地BJSIC-42)" + ,"tours" => array( + "BJSIC-41","BJSIC-42" + ) + ) + ,"BJSIC-43" => array( + "name1" => "Three-Day Beijing Discovery Tour" + ,"name2" => "北京精品三日游(目的地BJSIC-43)" + ,"tours" => array( + "BJSIC-41","BJSIC-42","BJSIC-43" + ) + ) + ,"XASIC-42" => array( + "name1" => " " + ,"name2" => " " + ,"tours" => array( + "XASIC-41","XASIC-42" + ) + ) + ); + } + + public function get_complex_pag($pag_code) + { + $all_set = $this->complex_tour(); + if (isset($all_set[$pag_code])) { + return $all_set[$pag_code]['tours']; + } + return array($pag_code); + } + } From 3cd70d74dc9b09c8e34494cc97770720500693b7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 13 Nov 2018 10:29:00 +0800 Subject: [PATCH 198/382] =?UTF-8?q?=E6=B8=A0=E9=81=93=E4=BB=B7=E5=A4=A7?= =?UTF-8?q?=E4=BA=8E=E5=AE=9E=E9=99=85=E6=94=B6=E5=85=A5=E6=97=B6,=20?= =?UTF-8?q?=E6=8A=A5=E4=BB=B7=E5=A1=AB=E6=B8=A0=E9=81=93=E4=BB=B7.?= =?UTF-8?q?=E5=8F=8D=E4=B9=8B,=E6=8C=89=E5=AE=9E=E9=99=85=E6=94=B6?= =?UTF-8?q?=E5=85=A5,=E5=8E=9F=E5=9B=A0:=E8=B6=85=E5=85=AC=E9=87=8C,?= =?UTF-8?q?=E5=8A=A0=E8=BF=94=E7=A8=8B=E7=AD=89=E6=83=85=E5=86=B5=E6=9C=AA?= =?UTF-8?q?=E5=9C=A8=E9=A2=84=E5=AE=9A=E4=B8=AD=E4=BD=93=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/controllers/TulanduoApi.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 9c00ccbb..e7537b44 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -421,7 +421,7 @@ class TulanduoApi extends CI_Controller } $partner_price = null; } - if ($partner_fee > 0) { + if ($partner_fee > 0 && $partner_fee >= $travel_fee) { $travel_fee = $partner_fee; $travel_fee_currency = $partner_fee_currency; } From 1828176e50bb872c032f73db70c904c567cfe32c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 13 Nov 2018 11:04:06 +0800 Subject: [PATCH 199/382] =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=88=B7=E6=96=B0?= =?UTF-8?q?=E8=B0=83=E5=BA=A6,=E6=88=90=E6=9C=AC=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index e7537b44..a6862973 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -1107,13 +1107,13 @@ class TulanduoApi extends CI_Controller public function refresh_operation($coli_sn=0) { $this->load->model('OrderFinance_model', 'combine_model'); - // $this->insert_HT_order_operation($coli_sn); - echo "string"; - $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn); - foreach ($data['combineNo_arr'] as $kcn => $vcn) { - $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo); - } - $this->load->view('operation',$data); + return $this->insert_HT_order_operation($coli_sn); + // echo "string"; + // $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn); + // foreach ($data['combineNo_arr'] as $kcn => $vcn) { + // $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo); + // } + // $this->load->view('operation',$data); } protected function excute_curl($url, $content_builder) { From 0c7fdc5c1878ec1d2ce791bf1a5b14b0669ff481 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 15 Nov 2018 15:09:50 +0800 Subject: [PATCH 200/382] =?UTF-8?q?=E5=8F=91=E9=80=81=E5=8F=98=E6=9B=B4;?= =?UTF-8?q?=20=E4=B8=8A=E6=8A=A5=E7=A1=AE=E8=AE=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 129 +++++++++++++----- .../vendorPlanSync/controllers/index.php | 97 +++++++++++++ .../vendorPlanSync/helpers/array_helper.php | 1 + .../vendorPlanSync/libraries/trippest.php | 2 + .../models/BIZ_orders_model.php | 3 +- .../vendorPlanSync/models/Group_model.php | 125 ++++++++++++++++- ...uo_addOrUpdateRouteOrderContentBuilder.php | 77 ++--------- 7 files changed, 331 insertions(+), 103 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 0d66b918..1ca50dbe 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -37,7 +37,7 @@ class Tulanduo extends CI_Controller ,"routeType" => "上海目的地线路" ) ); - public $vendor_ids = array(1343,30548,29188); + // public $vendor_ids = array(1343,30548,29188); // userId key // 1343 2e47c3721e3ff6e816fe6b928d7acc7d @@ -75,24 +75,22 @@ class Tulanduo extends CI_Controller // 桂林海纳国旅 // $this->userId = "18"; // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + $this->vendor_ids = $this->trippest->tulanduo_vei_sn; } - public function order_push($GRI_SN=null) + public function order_push($GRI_SN=0) { - if ($GRI_SN !== null) { - return $this->push_trippest($GRI_SN); - } $start_date = date('Y-m-d'); $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); $vei_sn_str = implode(",", $this->vendor_ids); - $ready_to_send = $this->Group_model->get_plan_not_received(1, $vei_sn_str, $start_date, $end_date); + $ready_to_send = $this->Group_model->get_plan_not_received(1, $vei_sn_str, $GRI_SN, $start_date, $end_date); if (empty($ready_to_send)) { return; } $order = $ready_to_send[0]; // 目的地计划 if (strval($order->GRI_OrderType) === "227002" && strval($order->department) === "30") { - return $this->push_trippest($order->GRI_SN); + return $this->push_trippest($order); } // 商务 if (strval($order->GRI_OrderType) === "227002") { @@ -101,35 +99,55 @@ class Tulanduo extends CI_Controller if (strval($order->GRI_OrderType) === "227001") { } - return $this->output->set_content_type('application/json')->set_output(json_encode($order)); + return $this->output->set_output("not trippest"); + // return $this->output->set_content_type('application/json')->set_output(json_encode($order)); } /*! * 发送目的地项目组预订计划到图兰朵地接系统 - * 地接社未接受的或有变更的 + * 地接社未接收的或有变更的 * @date 2018-05-02 */ - public function push_trippest($gri_sn=0) + public function push_trippest($vas=null) { // exit(); /** 目的地 test */ $this->userId = "902"; $this->key = "f56541ff40e1afba444d831c5a666195"; + + $gri_sn = $vas->GRI_SN; + $vas_sn = $vas->VAS_SN; + $vei_sn = $vas->VAS_VEI_SN; + $is_send_vary = $vas->VAS_SendVary; + $change_info = $vas->VAS_ChangeText; + if (trim($change_info) !== "") { + preg_match_all('/(.*)={6}(.*)(\d{4}\-\d{2}\-\d{2})/ismU', characet($change_info,'UTF-8'), $change_arr); + $change_info = $change_arr[0][0]; + } + $change_info = str_replace("\n", "<br>", $change_info); + $vei_sn_str = implode(",", $this->vendor_ids); $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); - $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn); + $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn, $vei_sn_str); if(empty($orderinfo)) {return;} $COLI_ID = $orderinfo[0]->COLI_ID; + $set_pvt = strval($orderinfo[0]->COLI_PVT); $travelFees = $this->BIZ_order->get_paymentDetails($COLI_ID); + // 按产品拆分 todo:按订单类型拆分? 单团/拼团 $fill_order = array(); $processed_date = array(); $processed_cold = array(); foreach ($orderinfo as $ko => $cold) { - if ( ! in_array($cold->COLD_SN, $processed_cold)) { + if ( ! in_array($cold->COLD_SN, $processed_cold) && $cold->pag_code != '') { $processed_cold[] = $cold->COLD_SN; $all_package = $this->trippest->tour_code($cold->pag_code); $pag_info = $this->BIZ_order->get_packageDetails(my_implode("'",",",$all_package)); - $fill_order[$cold->pag_code]["cold"][] = $cold; - $fill_order[$cold->pag_code]["package_info"] = $pag_info; + if ($set_pvt==='1') { + $fill_order[0]["cold"][] = $cold; + $fill_order[0]["package_info"] = $pag_info; + } else { + $fill_order[$cold->pag_code]["cold"][] = $cold; + $fill_order[$cold->pag_code]["package_info"] = $pag_info; + } } } // $fill_order = array_values($fill_order); @@ -141,8 +159,10 @@ class Tulanduo extends CI_Controller $order_type = intval($vf["package_info"][0]->PAG_ExtendType)===39009 ? 1 : 2; $last_code = count($vf["package_info"])-1; $last_date = count($vf["cold"])-1; - $routeName = $vf["package_info"][0]->PAG2_Name . mb_strtoupper($vf["cold"][0]->pag_code); - $end_date = strstr($vf["cold"][$last_date]->COLD_StartDate, " ", true); + $tour_code = mb_strtoupper($vf["cold"][0]->pag_code); + $routeName = $vf["package_info"][0]->PAG2_Name . "(" . mb_strtoupper($vf["cold"][0]->pag_code) . ")"; + $first_date = strstr($vf["cold"][0]->COLD_StartDate, " ", true); + $end_date = strstr($vf["cold"][$last_date]->COLD_EndDate, " ", true); if (isset($this->trippest->special_route[$vf["cold"][0]->pag_code])) { $routeName = $this->trippest->special_route[$vf["cold"][0]->pag_code]["name"]; $extra_day = $this->trippest->special_route[$vf["cold"][0]->pag_code]["day"]-1; @@ -181,7 +201,7 @@ class Tulanduo extends CI_Controller ->setCustomersPeopleType($key, ($vg->BPE_GuestType==1 ? "成人" : "儿童")) ->setCustomersDocumentType($key, "护照") // Passport No. ->setCustomersDocumentNo($key, $vg->BPE_Passport) - ->setCustomersOtherInfo($key, $this->BIZ_order->GetNationalityName($orderinfo[0]->GUT_NationalityID)); + ->setCustomersOtherInfo($key, $this->BIZ_order->GetNationalityName($vg->BPE_Nationality)); } $scheduleDetails = $this->BIZ_order->get_scheduleDetails($COLD_SN_str); $schedule_obj = array(); @@ -254,9 +274,20 @@ class Tulanduo extends CI_Controller if ( ! in_array(substr($vs->COLD_StartDate, 0, 10), $fill_date)) { $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]['content'] .= $this_title . $this_content; } + // 当前产品连续日期的补充 + $date_s = new DateTime(strstr($vs->COLD_StartDate, " ", TRUE)); + $date_e = new DateTime(strstr($vs->COLD_EndDate, " ", TRUE)); + $date_d = $date_e->diff($date_s); + $d_t = ($date_d->format("%d")); + if ($d_t > 0) { + for ($d_i=0; $d_i < ($d_t+1); $d_i++) { + $f_d = date('Y-m-d', strtotime("+$d_i day", strtotime(substr($vs->COLD_StartDate, 0, 10)))); + $schedule_obj[$f_d] = $schedule_obj[substr($vs->COLD_StartDate, 0, 10)]; + $schedule_obj[$f_d]['date'] = $f_d; + } + } } // 补全空的日期 - $first_date = strstr($vf["cold"][0]->COLD_StartDate, " ", true); $date1 = new DateTime($first_date); $date_end = new DateTime($end_date); $date_diff = $date_end->diff($date1); @@ -302,22 +333,55 @@ class Tulanduo extends CI_Controller ->setTravelFeesRemark($kf, $vf->GAI_Memo); } } - echo(($this->tldOrderBuilder->getBizContent())); + // 查询是否变更 + $sync_orderstate = 1; + $vps_sn = 0; + $vendor_orderid = 0; + if (intval($is_send_vary)===1) { + $vps = $this->Group_model->get_sync_info($vas_sn, $tour_code); + if ( ! empty($vps)) { + $vps_sn = $vps->VPS_SN; + $vendor_orderid = $vps->VPS_sync_id; + $sync_orderstate = 11; + $modifyLogInfo = "<br>$change_info<br>"; + // $modifyLogInfo = "<br><a href='https://www.trippest.com'>https://www.trippest.com</a><br>"; + $this->tldOrderBuilder->setOrderId($vendor_orderid) + ->setModifyLogInfo($modifyLogInfo) + ; + } + } else { + $this->tldOrderBuilder->clearModifyLogInfo(); + // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) + ; + } + // echo(($this->tldOrderBuilder->getBizContent())); // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); - // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); // var_dump($resp); - - /** BIZ_GroupCombineInfo */ - // if (json_decode($resp)->status == 1) { - // log_message('error','in GCI ' . json_decode($resp)->responseData->orderId); - // $this->BIZ_order->GCI_COLI_SN = $orderinfo[0]->COLI_SN; - // $this->BIZ_order->GCI_GRI_SN = $orderinfo[0]->COLI_GRI_SN; - // $this->BIZ_order->GCI_VendorOrderId = json_decode($resp)->responseData->orderId; - // $this->BIZ_order->GCI_FromAgc = "D目的地桂林组"; - // $this->BIZ_order->biz_groupcombineinfo_save(); - // } + $response = json_decode($resp); + if ($response->status == 1) { + /** VendorPlanSync */ + $sync_ret = array( + "VPS_VAS_SN" => $vas_sn + ,"VPS_GRI_SN" => $gri_sn + ,"VPS_VEI_SN" => $vei_sn + ,"VPS_startDate" => $first_date + ,"VPS_endDate" => $end_date + ,"VPS_tourCode" => $tour_code + ,"VPS_sync_id" => $response->responseData->orderId + ,"VPS_sync_orderType" => $order_type + ,"VPS_sync_orderState" => $sync_orderstate + ,"VPS_syncTime" => date('Y-m-d H:i:s') + ); + if ($vps_sn === 0) { + $sync_id = $this->Group_model->insert_VendorPlanSync($sync_ret); + } else { + $update = $this->Group_model->update_VendorPlanSync($vps_sn, $sync_ret); + } + /** VendorArrangeState VAS_IsReceive */ + $this->Group_model->set_plan_received($vas_sn); + } } - // email 供应商 todo echo "Order Push done."; return; } @@ -332,7 +396,7 @@ class Tulanduo extends CI_Controller $ret['status'] = -1; $ret['errMsg'] = "未知错误"; $input = $this->input->post(); - $vendorID = $input['userId']; + $vendorID = $input['openId']; $validate = $this->calc_key($vendorID, $input['key']); if ($validate !== TRUE) { $ret['errMsg'] = "身份验证失败."; @@ -484,4 +548,5 @@ class Tulanduo extends CI_Controller return $ret===$key; } + } diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index b8a30420..9ef50337 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -8,6 +8,7 @@ class Index extends CI_Controller { mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); + $this->load->library('trippest'); $this->load->model('BIZ_Orders_model'); $this->load->model('Group_model'); } @@ -25,6 +26,102 @@ class Index extends CI_Controller { return $this->output->set_content_type('application/json')->set_output(json_encode($orderinfo)); } + /** + * 接收地接社的信息上报 + * * 信息类型代码: + * * * 1000 已接收变更,未确认 + * * * 2000 已确认计划/变更 + * * * 3001 导游信息变更 + * * * 4001 已确认取消 + * * * 4002 订单已删除 + * @date 2018-11-14 + */ + public function uploadOperation() + { + $ret['status'] = -1; + $ret['errMsg'] = "未知错误"; + $input = $this->input->post(); + $vendorID = $input['openId']; + $validate = $this->calc_key($vendorID, $input['key']); + if ($validate !== TRUE) { + $ret['errMsg'] = "身份验证失败."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + $vendor_order_id = $input['orderId']; + $action_code = $input['operationTypeCode']; + switch ($action_code) { + case '1000': + # code... + break; + case '2000': + $ret = $this->plan_confirm($input); + break; + case '3001': + # code... + break; + case '4001': + # code... + break; + case '4002': + # code... + break; + + default: + # code... + break; + } + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + + public function plan_confirm($input) + { + $ret['status'] = -1; + $ret['errMsg'] = "未知用户"; + $vps = $this->Group_model->get_sync_info_by_vendororder($input['orderId']); + if (empty($vps)) { + $ret['errMsg'] = "未找到相应的订单."; + return $ret; + } + $vendor_manager = $this->Group_model->get_vendorContact($input['openId']); + /** VendorArrangeState */ + $VAS_ConfirmInfo = $input['operationRemark'] . "\r\n======确认人: " . $input['operator'] . ", 确认时间: " . $input['operateTime']; + $VAS_ConfirmInfo .= "\r\n" . $vps->VAS_ConfirmInfo; + $update_vas = $this->Group_model->set_plan_confirm($vps->VAS_SN, $vendor_manager->LMI_SN, $VAS_ConfirmInfo); + if ($update_vas === TRUE) { + $ret['status'] = 1; + $ret['errMsg'] = ""; + $sync_arr = array( + "VPS_sync_orderState" => 2 + ,"VPS_syncTime" => date('Y-m-d H:i:s') + ); + /** VendorPlanSync */ + $this->Group_model->update_VendorPlanSync($vps->VPS_SN, $sync_arr); + // 邮件外联 + $sender_name = "中华游供应商合作平台"; + $sender_mail = "info@chinahighlights.net"; + $from_name = $vendor_manager->LMI2_Name; + $from_mail = $vendor_manager->LMI_ListMail; + $to_name = $vps->OPI_Name; + $to_mail = $vps->OPI_Email; + $subject = $vps->GRI_Name . "团已确认: " . $vendor_manager->VEI2_CompanyBN; + $mail_body = $vendor_manager->VEI2_CompanyBN . "对团" . $vps->GRI_Name . "的计划在" . $input['operateTime'] . "已确认。<br>"; + $mail_body .= "确认说明:" . $input['operationRemark'] . "<br>"; + $mail_body .= "确认人:$vendor_manager->LMI2_Name $vendor_manager->LMI_ListMail 固定电话: $vendor_manager->LMI_Telephone 移动电话:$vendor_manager->LMI_Mobile<br>"; + $mail_body .= "变更内容: " . $vps->VAS_ChangeText . "<br>"; + $this->Group_model->save_automail($sender_name, $sender_mail, $from_name, $from_mail, $to_name, $to_mail, $subject, $mail_body, $sender_name); + } else { + log_message('error','图兰朵确认上报更新状态失败. POST RAW: ' . raw_json_encode($input) ); + } + return $ret; + } + + public function calc_key($userId, $key) + { + $default = "b825e39422a54875a95752fc7ed6f5d2"; + $ret = md5(hash("sha256", $userId.$default)); + return $ret===$key; + } + } /* End of file index.php */ diff --git a/webht/third_party/vendorPlanSync/helpers/array_helper.php b/webht/third_party/vendorPlanSync/helpers/array_helper.php index f66c6d2b..3d265013 100644 --- a/webht/third_party/vendorPlanSync/helpers/array_helper.php +++ b/webht/third_party/vendorPlanSync/helpers/array_helper.php @@ -165,3 +165,4 @@ function real_phone_number($phone, $nation_code) $cut_nation = str_replace($nation_str, "", $phone); return mb_ereg_replace('[\D]', '', $cut_nation); } + diff --git a/webht/third_party/vendorPlanSync/libraries/trippest.php b/webht/third_party/vendorPlanSync/libraries/trippest.php index ebba5748..dfc48fe6 100644 --- a/webht/third_party/vendorPlanSync/libraries/trippest.php +++ b/webht/third_party/vendorPlanSync/libraries/trippest.php @@ -10,6 +10,8 @@ class Trippest $this->ci =& get_instance(); } + public $tulanduo_vei_sn = array(1343,30548,29188); + public function tour_name($pag_code) { $name = ""; diff --git a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php index e9426647..bef796ca 100644 --- a/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php +++ b/webht/third_party/vendorPlanSync/models/BIZ_orders_model.php @@ -32,7 +32,7 @@ class BIZ_Orders_model extends CI_Model { } } - public function get_orderinfo_detail($gri_sn) + public function get_orderinfo_detail($gri_sn, $vei_sn_str) { $sql = "SELECT coli.COLI_ID, coli.COLI_Department, @@ -47,6 +47,7 @@ class BIZ_Orders_model extends CI_Model { INNER JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN and cold.DeleteFlag=0 LEFT JOIN BIZ_GUEST gut ON gut.GUT_SN=coli.COLI_GUT_SN WHERE coli.COLI_GRI_SN=$gri_sn + AND COLD_PlanVEI_SN in ($vei_sn_str) ORDER BY COLD_StartDate ASC"; $query = $this->HT->query($sql); return $query->result(); diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 3a602790..60a06d2b 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -8,24 +8,27 @@ class Group_model extends CI_Model { $this->HT = $this->load->database('HT', TRUE); } - public function get_plan_not_received($top=1, $vei_sn_str, $start_date=null, $end_date=null) + public function get_plan_not_received($top=1, $vei_sn_str, $gri_sn=0, $start_date=null, $end_date=null) { $top_sql = $top>0 ? " TOP $top " : ""; - $sql = "SELECT $top_sql VAS_IsConfirm, VAS_SendVary, GRI_OrderType, GRI_SN, GRI_No, GRI_operator, + $gri_sql = $gri_sn===0 ? "" : " and GRI_SN=$gri_sn "; + $sql = "SELECT $top_sql VAS_IsConfirm, VAS_SendVary, + GRI_OrderType, GRI_SN, GRI_No, GRI_operator, (select OPI_DEI_SN from OperatorInfo where OPI_SN=GRI_operator) as department, vas.* from VendorArrangeState vas inner join Eva_ObjectInfo eoi on EOI_GRI_SN=VAS_GRI_SN and EOI_Type=1 and EOI_ObjSN=VAS_VEI_SN inner join GRoupInfo gri on GRI_SN=VAS_GRI_SN - where 1=1 + where 1=1 "; + $sql .= $gri_sn!==0 ? $gri_sql : " and VAS_IsCancel=0 and VAS_Delete=0 and vas.DeleteFlag=0 and VAS_IsSendSucceed=1 and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' and VAS_VEI_SN in ($vei_sn_str) and GRI_OrderType=227002 -- test - and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) - order by EOI_GetDate asc, vas.VAS_IsConfirm asc "; + and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) "; + $sql .= " order by EOI_GetDate asc, vas.VAS_IsConfirm asc"; return $this->HT->query($sql)->result(); } @@ -35,9 +38,121 @@ class Group_model extends CI_Model { return $this->HT->query($sql)->result(); } + public function get_sync_info($vas, $tour_code="") + { + $sql = "SELECT * + from VendorPlanSync + where VPS_VAS_SN=? "; + $param_arr = array($vas); + if ($tour_code !== "") { + $sql .= " AND VPS_tourCode=? "; + $param_arr[] = $tour_code; + } + return $this->HT->query($sql, $param_arr)->row(); + } + public function get_sync_info_by_vendororder($vendor_order_id) + { + $sql = "SELECT + opi.OPI_DEI_SN as department, + * + from VendorPlanSync vps + inner join VendorArrangeState vas on vas.VAS_SN=vps.VPS_VAS_SN + inner join GRoupInfo gri on GRI_SN=vas.VAS_GRI_SN + left join OperatorInfo opi on opi.OPI_SN=GRI_operator + where VPS_sync_id=? "; + $param_arr = array($vendor_order_id); + return $this->HT->query($sql, $param_arr)->row(); + } + /*! + * 获取地接社接受计划的人员信息 + * @param $vendorID 地接社ID + */ + public function get_vendorContact($vendorID) + { + $sql = "SELECT top 1 lmi2.LMI2_Name, + lmi.LMI_SN, + lmi.LMI_AutoFax, + lmi.LMI_Telephone, + lmi.LMI_Mobile, + lmi.LMI_ListMail + ,vei2.VEI2_CompanyBN + FROM LinkmanInfo lmi + INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN AND lmi2.LMI2_LGC=2 + INNER JOIN VEndorInfo2 vei2 ON vei2.VEI2_VEI_SN=LMI_VEI_SN AND VEI2_LGC=2 + WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; + $query = $this->HT->query($sql); + return $query->row(); + } + public function set_plan_received($vas_sn=0) + { + $sql = "UPDATE VendorArrangeState set VAS_IsReceive=1,VAS_ReceiveTime=GETDATE() where VAS_SN=? "; + return $this->HT->query($sql, array($vas_sn)); + } + + /*! + * 地接计划状态变更 + * @param [type] $vas_sn [description] + * @param string $confirminfo [description] + */ + public function set_plan_confirm($vas_sn, $lmi_sn, $confirminfo="") + { + $sql = "UPDATE VendorArrangeState + SET VAS_IsConfirm=1 + ,VAS_ConfirmInfo=? + ,VAS_ConfirmTime=getdate() + ,VAS_ConfirmSN=? + WHERE VAS_SN=?"; + $query = $this->HT->query($sql, array($confirminfo, $lmi_sn, $vas_sn)); + // affected_rows() doesn't work with the 'sqlsrv' driver in CI2 + // The solution: Upgrade to the latest CodeIgniter 3.0.x version + $ssql = "SELECT 1 as 'exist' from VendorArrangeState where VAS_IsConfirm=1 and VAS_SN=? "; + $squery = $this->HT->query($ssql, array($vas_sn)); + $ret = $squery->result(); + return !empty($ret); + } + + public function insert_VendorPlanSync($sync_arr=array()) + { + $this->HT->insert('VendorPlanSync', $sync_arr); + return $this->HT->query("SELECT MAX(VPS_SN) VPS_SN from VendorPlanSync") + ->row()->VPS_SN; + } + + public function update_VendorPlanSync($vps, $sync_arr=array()) + { + $where = " VPS_SN=" . $vps; + $update_sql = $this->HT->update_string('VendorPlanSync', $sync_arr, $where); + return $this->HT->query($update_sql); + } + + + + /* + * 发送邮件 + */ + public function save_automail($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $frominfo = 'vendorConfirm msg', $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $M_Web = 'vendorConfirm msg') { + $sql = "INSERT INTO + Email_AutomaticSend ( + M_SenderName, + M_SenderEmail, + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, + M_FromName, + M_ServiceSN, + M_State, + M_AddTime + ) VALUES (N?, N?, N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; + $query = $this->HT->query($sql, array($M_SenderName, $M_SenderEmail, $fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); + return $query; + } } diff --git a/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php index 277ed0b6..93b9b595 100644 --- a/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php +++ b/webht/third_party/vendorPlanSync/models/TuLanDuo_addOrUpdateRouteOrderContentBuilder.php @@ -10,74 +10,16 @@ class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model private $bizContentarr = array(); private $bizContent = NULL; - private $orderData=array(); - private $orderId; //”Integer”//订单ID,不为空代表修改 - private $modifyLogInfo; //”String”//修改的日志记录信息.如果是修改订单的状态,这里传输修改简报 - private $orderType; //”Integer” //订单类型 1=独立成团,2=散客团 - private $routeName; //”String”//行程名称 - private $routeType; //”String”//线路类型 - private $agcOrderNo; //”String”//组团社团号,团号格式 yyyy-mm-dd-cc(**)后面中括号号的对应团号的其他表达信息 - private $adultNum; //”Integer”//大人数量 - private $childNum; //”Integer”//小孩数量 - private $guiderNum; //”Integer”//领队数量 - private $guiderInfo; //”String”//领队信息 - private $toTraffic; //”String”//抵达交通 - private $backTraffic; //”String”//返回交通 - private $roomStandard; //”String”//用房标准 - private $orderRemark; //”String”//订单备注 - private $routeStandard; //”String”//行程接待标准 - private $destination; //”目的地名称”//目的地城市名称 - private $travelDate; //”String”//出游时间yyyy-mm-dd - private $leavedDate; //”String”//离团时间 yyyy-mm-dd - - // private $orderData['travelFees']=array(); //团款明细 - // [{ - // type:”String”//团款类型 - // money:”Double”//单价 - // num:”Double”//数量 - // unit:”Double”//单位 - // sumMoney:”Double//总金额” - // remark:”String”//备注 - // }] - // private $orderData['replaceCollections']=array(); //代收明细 - // [{ - // type:“String”//代收类型 - // money:”Double”//金额 - // remark:”String”//备注 - // }] - // private $orderData['replacePays']=array(); //代付明细 - // [{ - // type:“String”//代付类型 - // money:”Double”//金额 - // remark:”String”//备注 - // }] - // private $orderData['scheduleDetails']=array(); //行程详细,数组类型,按照第一天往后有序排列 - // [{ - // title:”String”//行程标题 - // content:”String”//行程内容 - // traffic:”String”//交通号 - // accommodation:”String”//住宿 - // breakFirst:”Integer”//是否包含早餐 【1=包含 0=不含】 - // dinner:”Integer”//是否包含中餐 【1=包含 0=不含】 - // lunch:”Integer”//是否包含晚餐 【1=包含 0=不含】 - // }] - // private $orderData['customers']=array(); //游客信息 - // [{ - // name:”String”//名字 - // peopleType:”String”//类型 【成人,小孩,婴儿,老人,学生…】 - // document Type:”String”//证件类型【护照,身份证,户口,驾驶证….】 - // documentNo:”String”//证件号 - // phoneNo:”String”//手机号 - // otherInfo:”String”//其他信息 - // }] + private $orderData=array( + 'travelFees' => array() //团款明细 + ,'replaceCollections' => array() //代收明细 + ,'replacePays' => array() //代付明细 + ,'scheduleDetails' => array() //行程详细,数组类型,按照第一天往后有序排列 + ,'customers' => array() //游客信息 + ); function __construct() { parent::__construct(); - $this->orderData['travelFees'] = array(); //团款明细 - $this->orderData['replaceCollections'] = array(); //代收明细 - $this->orderData['replacePays'] = array(); //代付明细 - $this->orderData['scheduleDetails'] = array(); //行程详细,数组类型,按照第一天往后有序排列 - $this->orderData['customers'] = array(); //游客信息 } public function getBizContent() @@ -119,6 +61,11 @@ class TuLanDuo_addOrUpdateRouteOrderContentBuilder extends CI_Model $this->orderData['modifyLogInfo'] = $modifyLogInfo; return $this; } + public function clearModifyLogInfo() + { + $this->orderData['modifyLogInfo'] = ''; + return $this; + } public function setOrderType($orderType) { $this->orderData['orderType'] = $orderType; From a668669d8637a600325a22e6c833ed33da88100b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 16 Nov 2018 15:19:03 +0800 Subject: [PATCH 201/382] =?UTF-8?q?=E4=B8=8A=E6=8A=A5=E5=AF=BC=E6=B8=B8?= =?UTF-8?q?=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 168 ++++++++++++------ .../vendorPlanSync/controllers/index.php | 46 +++-- .../vendorPlanSync/models/Group_model.php | 81 ++++++++- 3 files changed, 219 insertions(+), 76 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 1ca50dbe..207d6852 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -5,39 +5,38 @@ if (!defined('BASEPATH')) class Tulanduo extends CI_Controller { - // public $special_route = array( - // "BJSIC-42" => "'BJSIC-41','BJSIC-42'" - // ,"BJSIC-43" => "'BJSIC-41','BJSIC-42','BJSIC-43'" - // ,"XASIC-42" => "'XASIC-41','XASIC-42'" - // ); - // public $special_route_name = array( - // "BJSIC-42" => "北京精品两日游(目的地BJSIC-42)" - // ,"BJSIC-43" => "北京精品三日游(目的地BJSIC-43)" - // ,"XASIC-42" => "西安精品两日游(目的地XASIC-42)" + /** Live */ + /** + 目的地 + $this->userId = "1134"; + $this->key = "73d180d05d425fd192e1c5b3097e75ff"; + 桂林海纳国旅 + $this->userId = "18"; + $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + */ + // private $send_host = array( + // "30" => array( + // "userId" => 1134 + // ,"key" => "73d180d05d425fd192e1c5b3097e75ff" + // ) + // ,"1" => array( + // "userId" => 18 + // ,"key" => "d05c25e6e6c5d4898161e0aaf700d9c7" + // ) // ); - public $city_info = array( - "北京分公司" => array( - "PlanVEI_SN" => 1343 - ,"COLI_sourcetype" => 32090 - ,"routeType" => "北京目的地线路" - ), - "总部" => array( - "PlanVEI_SN" => 1343 - ,"COLI_sourcetype" => 32090 - ,"routeType" => "北京目的地线路" - ), - "西安分公司" => array( - "PlanVEI_SN" => 30548 - ,"COLI_sourcetype" => 32116 - ,"routeType" => "西安目的地线路" - ), - "上海分公司" => array( - "PlanVEI_SN" => 29188 - ,"COLI_sourcetype" => 32112 - ,"routeType" => "上海目的地线路" + /** test + * 902 key:f56541ff40e1afba444d831c5a666195 + */ + private $send_host = array( + "30" => array( + "userId" => 902 + ,"key" => "f56541ff40e1afba444d831c5a666195" + ) + ,"1" => array( + "userId" => 902 + ,"key" => "f56541ff40e1afba444d831c5a666195" ) ); - // public $vendor_ids = array(1343,30548,29188); // userId key // 1343 2e47c3721e3ff6e816fe6b928d7acc7d @@ -49,8 +48,8 @@ class Tulanduo extends CI_Controller // public $detail_url = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/"; public $neworder_url = "http://ltdj.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/"; // Live - // public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; - // public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; + public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; + public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; public function __construct(){ @@ -61,20 +60,10 @@ class Tulanduo extends CI_Controller $this->load->library('trippest'); $this->load->model('Group_model'); $this->load->model('BIZ_orders_model', 'BIZ_order'); - // $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); + $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); + $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); // $this->output->enable_profiler(TRUE); - /** test - 902 key:f56541ff40e1afba444d831c5a666195 - */ - $this->userId = "902"; - $this->key = "f56541ff40e1afba444d831c5a666195"; - /** Live */ - // 目的地 - // $this->userId = "1134"; - // $this->key = "73d180d05d425fd192e1c5b3097e75ff"; - // 桂林海纳国旅 - // $this->userId = "18"; - // $this->key = "d05c25e6e6c5d4898161e0aaf700d9c7"; + $this->vendor_ids = $this->trippest->tulanduo_vei_sn; } @@ -112,8 +101,8 @@ class Tulanduo extends CI_Controller { // exit(); /** 目的地 test */ - $this->userId = "902"; - $this->key = "f56541ff40e1afba444d831c5a666195"; + $userId = $this->send_host["30"]["userId"]; + $userKey = $this->send_host["30"]["key"]; $gri_sn = $vas->GRI_SN; $vas_sn = $vas->VAS_SN; @@ -126,7 +115,6 @@ class Tulanduo extends CI_Controller } $change_info = str_replace("\n", "<br>", $change_info); $vei_sn_str = implode(",", $this->vendor_ids); - $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn, $vei_sn_str); if(empty($orderinfo)) {return;} $COLI_ID = $orderinfo[0]->COLI_ID; @@ -143,7 +131,7 @@ class Tulanduo extends CI_Controller $pag_info = $this->BIZ_order->get_packageDetails(my_implode("'",",",$all_package)); if ($set_pvt==='1') { $fill_order[0]["cold"][] = $cold; - $fill_order[0]["package_info"] = $pag_info; + $fill_order[0]["package_info"] = $pag_info; // todo ??? 这里是否丢失了产品 } else { $fill_order[$cold->pag_code]["cold"][] = $cold; $fill_order[$cold->pag_code]["package_info"] = $pag_info; @@ -159,7 +147,7 @@ class Tulanduo extends CI_Controller $order_type = intval($vf["package_info"][0]->PAG_ExtendType)===39009 ? 1 : 2; $last_code = count($vf["package_info"])-1; $last_date = count($vf["cold"])-1; - $tour_code = mb_strtoupper($vf["cold"][0]->pag_code); + $tour_code = ""; $routeName = $vf["package_info"][0]->PAG2_Name . "(" . mb_strtoupper($vf["cold"][0]->pag_code) . ")"; $first_date = strstr($vf["cold"][0]->COLD_StartDate, " ", true); $end_date = strstr($vf["cold"][$last_date]->COLD_EndDate, " ", true); @@ -171,6 +159,7 @@ class Tulanduo extends CI_Controller $agcOrderNo = $vf["cold"][0]->COLI_GroupCode . "-" . $vf["package_info"][0]->city_code; if ($take_apart===true) { $agcOrderNo .= "-" . $i; + $tour_code = mb_strtoupper($vf["cold"][0]->pag_code); } $agcOrderNo .= "(" . $vf["cold"][0]->operator . ")"; $order_remark = ""; @@ -179,8 +168,8 @@ class Tulanduo extends CI_Controller } $COLD_SN_str = implode(',', array_map( function($element){return $element->COLD_SN;}, $vf["cold"] )) ; $guestlist = $this->BIZ_order->get_guestlist($COLD_SN_str); - $this->tldOrderBuilder->setUserId($this->userId) - ->setKey($this->key) + $this->tldOrderBuilder->setUserId($userId) + ->setKey($userKey) ->setOrderType($order_type) ->setRouteName($routeName) ->setRouteType($vf["package_info"][0]->city_chinese . "目的地线路") @@ -341,7 +330,7 @@ class Tulanduo extends CI_Controller $vps = $this->Group_model->get_sync_info($vas_sn, $tour_code); if ( ! empty($vps)) { $vps_sn = $vps->VPS_SN; - $vendor_orderid = $vps->VPS_sync_id; + $vendor_orderid = $vps->VPS_externalId; $sync_orderstate = 11; $modifyLogInfo = "<br>$change_info<br>"; // $modifyLogInfo = "<br><a href='https://www.trippest.com'>https://www.trippest.com</a><br>"; @@ -368,10 +357,11 @@ class Tulanduo extends CI_Controller ,"VPS_startDate" => $first_date ,"VPS_endDate" => $end_date ,"VPS_tourCode" => $tour_code - ,"VPS_sync_id" => $response->responseData->orderId - ,"VPS_sync_orderType" => $order_type - ,"VPS_sync_orderState" => $sync_orderstate - ,"VPS_syncTime" => date('Y-m-d H:i:s') + ,"VPS_sendHost" => $userId + ,"VPS_externalId" => $response->responseData->orderId + ,"VPS_externalorderType" => $order_type + ,"VPS_externalorderState" => $sync_orderstate + ,"VPS_latestTime" => date('Y-m-d H:i:s') ); if ($vps_sn === 0) { $sync_id = $this->Group_model->insert_VendorPlanSync($sync_ret); @@ -386,6 +376,68 @@ class Tulanduo extends CI_Controller return; } + public function tourguide_update($input, $vps, $eva) + { + $ret['status'] = -1; + $ret['errMsg'] = "未知错误"; + $eva_g_sn = $eva[0]->has_tourguide; + if (strval($vps->department)==="30") { + $userId = $this->send_host["30"]['userId']; + $userKey = $this->send_host["30"]['key']; + } else { + $userId = $this->send_host["1"]['userId']; + $userKey = $this->send_host["1"]['key']; + } + $this->tld_order->setOrderId($vps->VPS_externalId) + ->setUserId($userId) + ->setKey($userKey); + $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + $detail_jsonResp = json_decode($detail_resp); + // 判断 + if ($detail_jsonResp->status !== 1) { + log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); + $ret['errMsg'] = "查询失败"; + return $ret; + } + // 导游信息 + $tourguige_name = ""; + $tourguide_mobile = null; + if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { + $tourguige_name = $detail_jsonResp->orderDetail->operationDetails->guiderOperations[0]->name; + $tourguide_mobile = real_phone_number($detail_jsonResp->orderDetail->operationDetails->guiderOperations[0]->mobelPhone, 86); + } + if ($tourguige_name === "") { + $ret['errMsg'] = "未查询到导游"; + return $ret; + } + preg_match_all('/[^\w\s\-]+/', characet($tourguige_name, "UTF-8"), $cn_name_arr); // 取中文 + $tourguige_name_cn = preg_replace('/^(上海|北京|西安)/', '', characet($cn_name_arr[0][0],'UTF-8')); + preg_match_all('/[a-zA-Z]+/', characet($tourguige_name, "UTF-8"), $en_name_arr); // 取英文 + $tourguige_name_en = characet($en_name_arr[0][0],'UTF-8'); + $ht_tourguide = $this->Group_model->search_tourguide($input['openId'], $tourguige_name_cn, $tourguige_name_en, $tourguide_mobile); + if (empty($ht_tourguide)) { + $ret['errMsg'] = "导游信息未录入"; + return $ret; + } + $eva_tgi_column = array( + "EOI_Type" => 3 + ,"EOI_GRI_SN" => $eva->EOI_GRI_SN + ,"EOI_VEI_SN" => $eva->EOI_ObjSN + ,"EOI_ObjSN" => $ht_tourguide->TGI_SN + ,"EOI_CII_SN" => $eva->EOI_CII_SN + ,"EOI_GetDate" => $eva->EOI_GetDate + ,"EOI_Date" => $eva->EOI_Date + ,"EOI_Cancel" => $eva->EOI_Cancel + ,"EOI_GroupType" => $eva->EOI_GroupType + ,"EOI_FillWorkers_SN" => 0 // todo + ,"EOI_FWks_LastEditTime" => date('Y-m-d H:i:s') + ); + $this->Group_model->set_plan_tourguide($eva_g_sn, $eva_tgi_column); + $ret['status'] = 1; + $ret['errMsg'] = ""; + return $ret; + } + /*! * 订单状态变更,调度变更 * (地接社调用, 并邮件通知外联) @@ -456,7 +508,7 @@ class Tulanduo extends CI_Controller } - protected function excute_curl($url, $content_builder) { + private function excute_curl($url, $content_builder) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_FAILONERROR, false); diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 9ef50337..82e4cb6a 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -47,6 +47,11 @@ class Index extends CI_Controller { $ret['errMsg'] = "身份验证失败."; return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } + $vps = $this->Group_model->get_sync_info_by_vendororder($input['orderId']); + if (empty($vps)) { + $ret['errMsg'] = "未找到相应的订单."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } $vendor_order_id = $input['orderId']; $action_code = $input['operationTypeCode']; switch ($action_code) { @@ -54,10 +59,10 @@ class Index extends CI_Controller { # code... break; case '2000': - $ret = $this->plan_confirm($input); + $ret = $this->plan_confirm($input, $vps); break; case '3001': - # code... + $ret = $this->fill_tourguide($input, $vps); break; case '4001': # code... @@ -73,15 +78,10 @@ class Index extends CI_Controller { return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } - public function plan_confirm($input) + public function plan_confirm($input, $vps) { $ret['status'] = -1; - $ret['errMsg'] = "未知用户"; - $vps = $this->Group_model->get_sync_info_by_vendororder($input['orderId']); - if (empty($vps)) { - $ret['errMsg'] = "未找到相应的订单."; - return $ret; - } + $ret['errMsg'] = ""; $vendor_manager = $this->Group_model->get_vendorContact($input['openId']); /** VendorArrangeState */ $VAS_ConfirmInfo = $input['operationRemark'] . "\r\n======确认人: " . $input['operator'] . ", 确认时间: " . $input['operateTime']; @@ -91,8 +91,8 @@ class Index extends CI_Controller { $ret['status'] = 1; $ret['errMsg'] = ""; $sync_arr = array( - "VPS_sync_orderState" => 2 - ,"VPS_syncTime" => date('Y-m-d H:i:s') + "VPS_externalorderState" => 2 + ,"VPS_latestTime" => date('Y-m-d H:i:s') ); /** VendorPlanSync */ $this->Group_model->update_VendorPlanSync($vps->VPS_SN, $sync_arr); @@ -115,6 +115,30 @@ class Index extends CI_Controller { return $ret; } + public function fill_tourguide($input, $vps) + { + $ret['status'] = -1; + $ret['errMsg'] = ""; + $eva = $this->Group_model->get_plan_eva($vps->VAS_SN); + if (empty($eva)) { + $ret['errMsg'] = "未找到相应的订单."; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } + if (intval($eva[0]->need_tourguide)===0) { + // 不需要设置导游 + $ret['status'] = 1; + $ret['errMsg'] = ""; + return $ret; + } + // 需要填写导游, 则根据不同的供应商调用相应的方法 + if (in_array($input['openId'], $this->trippest->tulanduo_vei_sn)) { + require_once('Tulanduo.php'); + $tulanduo_fun = new Tulanduo(); + return $tulanduo_fun->tourguide_update($input, $vps, $eva); + } + return $ret; + } + public function calc_key($userId, $key) { $default = "b825e39422a54875a95752fc7ed6f5d2"; diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 60a06d2b..d15a8f31 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -32,6 +32,22 @@ class Group_model extends CI_Model { return $this->HT->query($sql)->result(); } + public function get_plan_eva($vas) + { + $sql = "SELECT + isnull(eoi_v.EOI_SendEvaluation,0) as need_tourguide, + isnull(eoi_g.EOI_SN,0) as has_tourguide, + vas.*,eoi_v.* + from VendorArrangeState vas + inner join Eva_ObjectInfo eoi_v on EOI_GRI_SN=VAS_GRI_SN + and EOI_Type=1 and EOI_ObjSN=VAS_VEI_SN + left join Eva_ObjectInfo eoi_g on eoi_g.EOI_GRI_SN=VAS_GRI_SN + and eoi_g.EOI_Type=3 and eoi_g.EOI_VEI_SN=eoi_v.EOI_ObjSN + where VAS_SN=? + order by has_tourguide desc "; + return $this->HT->query($sql, array($vas))->result(); + } + public function get_vendor_plan_info($gri_sn, $vendor_id) { $sql = " SP_VendorPlan_GetPlanInfo $gri_sn, $vendor_id, 0 "; @@ -41,7 +57,7 @@ class Group_model extends CI_Model { public function get_sync_info($vas, $tour_code="") { $sql = "SELECT * - from VendorPlanSync + from VendorPlanSendout where VPS_VAS_SN=? "; $param_arr = array($vas); if ($tour_code !== "") { @@ -56,11 +72,11 @@ class Group_model extends CI_Model { $sql = "SELECT opi.OPI_DEI_SN as department, * - from VendorPlanSync vps + from VendorPlanSendout vps inner join VendorArrangeState vas on vas.VAS_SN=vps.VPS_VAS_SN inner join GRoupInfo gri on GRI_SN=vas.VAS_GRI_SN left join OperatorInfo opi on opi.OPI_SN=GRI_operator - where VPS_sync_id=? "; + where VPS_externalId=? "; $param_arr = array($vendor_order_id); return $this->HT->query($sql, $param_arr)->row(); } @@ -86,6 +102,57 @@ class Group_model extends CI_Model { return $query->row(); } + public function search_tourguide($vendor, $cn_name, $en_name=null, $mobile=null) + { + $param_arr = array($cn_name); + $en_sql = " "; + if (strval($en_name)!=="") { + $en_sql = " and tgi_en.TGI2_Name =? "; + $param_arr[] = $en_name; + } + $mobile_sql = " "; + if (strval($mobile)!=="") { + $mobile_sql = " or TGI_Mobile=? "; + $param_arr[] = $mobile; + } + $sql = "SELECT TGI_VEI_SN,TGI_Mobile, + tgi_cn.TGI2_Name cn_name, + tgi_en.TGI2_Name en_name, + TGI_SN + from TouristGuideInfo2 tgi_en + join TouristGuideInfo on TGI_SN=tgi_en.TGI2_TGI_SN and tgi_en.TGI2_LGC=1 + join TouristGuideInfo2 tgi_cn on TGI_SN=tgi_cn.TGI2_TGI_SN and tgi_cn.TGI2_LGC=2 + where ( + ( 1=1 + and tgi_cn.TGI2_Name like '%" . $this->HT->escape_like_str($cn_name) . "%' + $en_sql + ) + $mobile_sql + ) + and TGI_VEI_SN in ($vendor)"; + return $this->HT->query($sql, $param_arr)->row(); + } + + public function set_plan_tourguide($eva_g_sn=0, $column=array()) + { + if ($eva_g_sn===0) { + // 第一次设置导游 + $this->HT->insert("Eva_ObjectInfo", $column); + $eva_g_sn = $this->HT->query("SELECT MAX(EOI_SN) EOI_SN from Eva_ObjectInfo + where EOI_GRI_SN=? + and EOI_VEI_SN=? + and EOI_Type=3 + ", array($column['EOI_GRI_SN'], $column['EOI_VEI_SN'])) + ->row()->EOI_SN; + } else { + // 变更导游设置 + $update_where = " EOI_SN=".$eva_g_sn; + $update_sql = $this->HT->update_string("Eva_ObjectInfo", $column, $update_where); + $this->HT->query($update_sql); + } + return $eva_g_sn; + } + public function set_plan_received($vas_sn=0) { $sql = "UPDATE VendorArrangeState set VAS_IsReceive=1,VAS_ReceiveTime=GETDATE() where VAS_SN=? "; @@ -102,7 +169,7 @@ class Group_model extends CI_Model { $sql = "UPDATE VendorArrangeState SET VAS_IsConfirm=1 ,VAS_ConfirmInfo=? - ,VAS_ConfirmTime=getdate() + ,VAS_ConfirmTime=GETDATE() ,VAS_ConfirmSN=? WHERE VAS_SN=?"; $query = $this->HT->query($sql, array($confirminfo, $lmi_sn, $vas_sn)); @@ -116,15 +183,15 @@ class Group_model extends CI_Model { public function insert_VendorPlanSync($sync_arr=array()) { - $this->HT->insert('VendorPlanSync', $sync_arr); - return $this->HT->query("SELECT MAX(VPS_SN) VPS_SN from VendorPlanSync") + $this->HT->insert('VendorPlanSendout', $sync_arr); + return $this->HT->query("SELECT MAX(VPS_SN) VPS_SN from VendorPlanSendout") ->row()->VPS_SN; } public function update_VendorPlanSync($vps, $sync_arr=array()) { $where = " VPS_SN=" . $vps; - $update_sql = $this->HT->update_string('VendorPlanSync', $sync_arr, $where); + $update_sql = $this->HT->update_string('VendorPlanSendout', $sync_arr, $where); return $this->HT->query($update_sql); } From e36b73bbf821d28d104621a04579542a60809d70 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 16 Nov 2018 17:25:24 +0800 Subject: [PATCH 202/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20?= =?UTF-8?q?=E6=8B=BC=E5=9B=A2=E7=9A=84=E8=AE=A1=E7=AE=97=E4=B8=8D=E8=83=BD?= =?UTF-8?q?=E6=8E=92=E9=99=A4=E5=8F=AA=E8=83=BDpvt=E7=9A=84=E4=BA=A7?= =?UTF-8?q?=E5=93=81=E7=BC=96=E5=8F=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/order_finance.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index f5033d91..6c4345d6 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -111,6 +111,8 @@ class Order_finance extends CI_Controller { continue; } if ($vc->GCI_groupType == 1) { + // 除去只能PVT的. 避免预定接送*1+tour*1, tour拼团只有一个订单, 被视为整团pvt,漏算接送成本 + $processed_code = array_diff($processed_code, $this->forbidden_combine()); $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); } else if ($vc->GCI_groupType == 2) { // 这里不排除产品编号是否已处理, 因为重复的情况比较多 From 67003cdb8c9e4159e0350ac2a5bd17d584283891 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 20 Nov 2018 10:03:22 +0800 Subject: [PATCH 203/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:=E5=85=B6?= =?UTF-8?q?=E4=BB=96=E6=94=B6=E5=85=A5=E8=AE=A1=E5=85=A5=E6=94=B6=E5=85=A5?= =?UTF-8?q?,=E8=80=8C=E4=B8=8D=E6=98=AF=E6=88=90=E6=9C=AC;=E6=8E=A5?= =?UTF-8?q?=E9=80=81=E4=BF=A1=E6=81=AF=E5=8F=96=E5=9B=BE=E5=85=B0=E6=9C=B5?= =?UTF-8?q?=E7=9A=84=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 42 +++++++++---------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index a6862973..811968b7 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -445,7 +445,7 @@ class TulanduoApi extends CI_Controller $COLD_MemoText = raw_json_encode(array("Pick up"=>$detail_jsonResp->orderDetail->toTraffic, "Drop off"=>$detail_jsonResp->orderDetail->backTraffic)); $new_memotext = trim($cold_memotext)===""||(json_decode($cold_memotext)!==null&&!is_numeric(json_decode($cold_memotext))) ? $COLD_MemoText : $cold_memotext; $cold_update_column = array( - "COLD_MemoText" => $new_memotext + "COLD_MemoText" => $COLD_MemoText ); if (intval($coli_opi_id)===435) { $cold_update_column['COLD_MemoText'] = $COLD_MemoText; @@ -634,26 +634,26 @@ class TulanduoApi extends CI_Controller } } // 其他收入 - if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { - foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; - $this->Orders_model->GCOD_VEI_SN = $vei_SN; - $this->Orders_model->GCOD_operationType = "otherReceives"; - $this->Orders_model->GCOD_subType = $vor->type; - $this->Orders_model->GCOD_title = ""; - $this->Orders_model->GCOD_dutyName = ""; - $this->Orders_model->GCOD_dutyTel = ""; - $this->Orders_model->GCOD_dutyPhoto = ''; - $this->Orders_model->GCOD_startDate = ""; - $this->Orders_model->GCOD_endDate = ""; - $this->Orders_model->GCOD_sumMoney = $vor->sumMoney; - $this->Orders_model->GCOD_carLicense = ""; - $this->Orders_model->GCOD_standard = ""; - $this->Orders_model->GCOD_remark = $vor->remark; - $this->Orders_model->GCOD_useNum = $vor->useNum; - $this->Orders_model->biz_groupcombineoperationdetail_save(); - } - } + // if (isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) ) { + // foreach ($detail_jsonResp->orderDetail->operationDetails->otherReceives as $vor) { + // $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + // $this->Orders_model->GCOD_VEI_SN = $vei_SN; + // $this->Orders_model->GCOD_operationType = "otherReceives"; + // $this->Orders_model->GCOD_subType = $vor->type; + // $this->Orders_model->GCOD_title = ""; + // $this->Orders_model->GCOD_dutyName = ""; + // $this->Orders_model->GCOD_dutyTel = ""; + // $this->Orders_model->GCOD_dutyPhoto = ''; + // $this->Orders_model->GCOD_startDate = ""; + // $this->Orders_model->GCOD_endDate = ""; + // $this->Orders_model->GCOD_sumMoney = $vor->sumMoney; + // $this->Orders_model->GCOD_carLicense = ""; + // $this->Orders_model->GCOD_standard = ""; + // $this->Orders_model->GCOD_remark = $vor->remark; + // $this->Orders_model->GCOD_useNum = $vor->useNum; + // $this->Orders_model->biz_groupcombineoperationdetail_save(); + // } + // } if (isset($detail_jsonResp->orderDetail->operationDetails->trafficOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->trafficOperations as $vto) { $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; From 372be829c519c66abab2e067220ce4c6c80a6a0a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 20 Nov 2018 11:55:33 +0800 Subject: [PATCH 204/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E9=80=81?= =?UTF-8?q?=E8=AE=A1=E5=88=92=E7=9A=84=E5=85=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 22 ++++--------- .../vendorPlanSync/controllers/index.php | 31 +++++++++++++------ .../vendorPlanSync/libraries/vendor.php | 24 ++++++++++++++ .../vendorPlanSync/models/Group_model.php | 4 +-- 4 files changed, 54 insertions(+), 27 deletions(-) create mode 100644 webht/third_party/vendorPlanSync/libraries/vendor.php diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 207d6852..ca706f63 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -67,16 +67,8 @@ class Tulanduo extends CI_Controller $this->vendor_ids = $this->trippest->tulanduo_vei_sn; } - public function order_push($GRI_SN=0) + public function order_push($order=null) { - $start_date = date('Y-m-d'); - $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); - $vei_sn_str = implode(",", $this->vendor_ids); - $ready_to_send = $this->Group_model->get_plan_not_received(1, $vei_sn_str, $GRI_SN, $start_date, $end_date); - if (empty($ready_to_send)) { - return; - } - $order = $ready_to_send[0]; // 目的地计划 if (strval($order->GRI_OrderType) === "227002" && strval($order->department) === "30") { return $this->push_trippest($order); @@ -88,8 +80,7 @@ class Tulanduo extends CI_Controller if (strval($order->GRI_OrderType) === "227001") { } - return $this->output->set_output("not trippest"); - // return $this->output->set_content_type('application/json')->set_output(json_encode($order)); + return "[Tulanduo>order_push] No function match. "; } /*! @@ -99,8 +90,8 @@ class Tulanduo extends CI_Controller */ public function push_trippest($vas=null) { - // exit(); - /** 目的地 test */ + return "[Tulanduo>push_trippest] Done. "; + /** 目的地 */ $userId = $this->send_host["30"]["userId"]; $userKey = $this->send_host["30"]["key"]; @@ -116,7 +107,7 @@ class Tulanduo extends CI_Controller $change_info = str_replace("\n", "<br>", $change_info); $vei_sn_str = implode(",", $this->vendor_ids); $orderinfo = $this->BIZ_order->get_orderinfo_detail($gri_sn, $vei_sn_str); - if(empty($orderinfo)) {return;} + if(empty($orderinfo)) {return "[Tulanduo>push_trippest] Not found order detail. ";} $COLI_ID = $orderinfo[0]->COLI_ID; $set_pvt = strval($orderinfo[0]->COLI_PVT); $travelFees = $this->BIZ_order->get_paymentDetails($COLI_ID); @@ -372,8 +363,7 @@ class Tulanduo extends CI_Controller $this->Group_model->set_plan_received($vas_sn); } } - echo "Order Push done."; - return; + return "Order Push done. "; } public function tourguide_update($input, $vps, $eva) diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 82e4cb6a..92071230 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -8,7 +8,7 @@ class Index extends CI_Controller { mb_regex_encoding("UTF-8"); bcscale(4); $this->load->helper('array'); - $this->load->library('trippest'); + $this->load->library('vendor'); $this->load->model('BIZ_Orders_model'); $this->load->model('Group_model'); } @@ -19,11 +19,23 @@ class Index extends CI_Controller { return $this->output->set_content_type('application/json')->set_output(json_encode($vendor_plan)); } - public function push($COLI_ID) + public function push($GRI_SN=0) { - $orderinfo = $this->BIZ_Orders_model->get_orderinfo_detail($COLI_ID); - if(empty($orderinfo)) {return;} - return $this->output->set_content_type('application/json')->set_output(json_encode($orderinfo)); + $start_date = date('Y-m-d'); + $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); + $ready_to_send = $this->Group_model->get_plan_not_received(1, $GRI_SN, $start_date, $end_date); + if (empty($ready_to_send)) { + return $this->output->set_output("empty"); + } + $order = $ready_to_send[0]; + if (isset($this->vendor->vendor_fun[strval($order->VAS_VEI_SN)])) { + $controller_name = $this->vendor->vendor_fun[strval($order->VAS_VEI_SN)]; + require_once($controller_name . ".php"); + $vendor_class = new $controller_name(); + $call_fun = $vendor_class->order_push($order); + return $this->output->set_output($call_fun . $order->GRI_SN); + } + return $this->output->set_output("Not found vendor function. " . $order->GRI_SN); } /** @@ -131,10 +143,11 @@ class Index extends CI_Controller { return $ret; } // 需要填写导游, 则根据不同的供应商调用相应的方法 - if (in_array($input['openId'], $this->trippest->tulanduo_vei_sn)) { - require_once('Tulanduo.php'); - $tulanduo_fun = new Tulanduo(); - return $tulanduo_fun->tourguide_update($input, $vps, $eva); + if (isset($this->vendor->vendor_fun[strval($input['openId'])])) { + $controller_name = $this->vendor->vendor_fun[strval($input['openId'])]; + require_once($controller_name . '.php'); + $vendor_class = new $controller_name(); + return $vendor_class->tourguide_update($input, $vps, $eva); } return $ret; } diff --git a/webht/third_party/vendorPlanSync/libraries/vendor.php b/webht/third_party/vendorPlanSync/libraries/vendor.php new file mode 100644 index 00000000..935e0ba8 --- /dev/null +++ b/webht/third_party/vendorPlanSync/libraries/vendor.php @@ -0,0 +1,24 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Vendor +{ + protected $ci; + + public function __construct() + { + $this->ci =& get_instance(); + } + + public $vendor_fun = array( + "1343" => "Tulanduo" + ,"29188" => "Tulanduo" + ,"30548" => "Tulanduo" + ); + + + +} + +/* End of file vendor.php */ +/* Location: ./third_party/vendorPlanSync/libraries/vendor.php */ diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index d15a8f31..e7aa68c1 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -8,7 +8,7 @@ class Group_model extends CI_Model { $this->HT = $this->load->database('HT', TRUE); } - public function get_plan_not_received($top=1, $vei_sn_str, $gri_sn=0, $start_date=null, $end_date=null) + public function get_plan_not_received($top=1, $gri_sn=0, $start_date=null, $end_date=null) { $top_sql = $top>0 ? " TOP $top " : ""; $gri_sql = $gri_sn===0 ? "" : " and GRI_SN=$gri_sn "; @@ -25,7 +25,7 @@ class Group_model extends CI_Model { and VAS_IsSendSucceed=1 and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' - and VAS_VEI_SN in ($vei_sn_str) + -- and VAS_VEI_SN in (29188, 1343, 30548) -- test and GRI_OrderType=227002 -- test and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) "; $sql .= " order by EOI_GetDate asc, vas.VAS_IsConfirm asc"; From 974ab904bb8c8d21b966d09826cb75e030921f98 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 20 Nov 2018 16:31:58 +0800 Subject: [PATCH 205/382] =?UTF-8?q?=E8=BD=AC=E7=A7=BB=E6=94=B6=E6=AC=BE:?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=E5=8E=9F=E6=9D=A5=E7=9A=84=E5=AE=9E=E6=94=B6?= =?UTF-8?q?=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 18 ++++++++++----- .../third_party/paypal/controllers/index.php | 22 ++++++++++++------- 2 files changed, 27 insertions(+), 13 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 079f41e8..a939b143 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -361,7 +361,7 @@ class IPayLinksService extends CI_Controller * @date 2017-08-29 * @param string $orderid 订单号 */ - public function batch_send_note($pn_txn_id = false) + public function batch_send_note($pn_txn_id = false, $old_ssje=NULL) { $data = array(); $int = 0; @@ -437,6 +437,7 @@ class IPayLinksService extends CI_Controller if (!empty($orderid_info)) { $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->IPL_currencyCode))); $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode); + $ssje = $old_ssje===NULL ? $ssje : $old_ssje; //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; @@ -460,7 +461,7 @@ class IPayLinksService extends CI_Controller $ht_memo); // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { // //只修改APP组的订单状态,并且订单进度是我的订单 - // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); //把订单状态改为已付款 + // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 // } } else { // 把订单状态设置为13-新订单已支付 @@ -974,6 +975,7 @@ class IPayLinksService extends CI_Controller public function gai_modal_save() { $data = array(); + $old_ssje = NULL; $pn_txn_id = $this->input->post('pn_txn_id'); $pn_id = $this->input->post('pn_id'); $neworder = $this->input->post('pn_invoice'); @@ -984,10 +986,16 @@ class IPayLinksService extends CI_Controller $orderid_info = json_decode($orderid_info); if ($orderid_info->ordertype === 'T') { $data['gai_info'] = $this->IPayLinks_model->get_money_t($pn_txn_id); - $this->IPayLinks_model->delete_money_t($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->IPayLinks_model->delete_money_t($pn_txn_id); + } } elseif ($orderid_info->ordertype === 'B') { $data['gai_info'] = $this->IPayLinks_model->get_money_b($pn_txn_id); - $this->IPayLinks_model->delete_money_b($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->IPayLinks_model->delete_money_b($pn_txn_id); + } } } @@ -998,7 +1006,7 @@ class IPayLinksService extends CI_Controller $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); if (!empty($advisor_info)) { $this->Note_model->set_invoice($pn_txn_id, $neworder); - $this->batch_send_note($pn_txn_id); + $this->batch_send_note($pn_txn_id, $old_ssje); echo json_encode('修改成功!'); return true; } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index a4d95825..87c17ead 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -708,7 +708,7 @@ class Index extends CI_Controller { */ //找到没有发送的记录 - public function send_note($pn_txn_id = false) { + public function send_note($pn_txn_id = false, $old_ssje=NULL) { $data = array(); //优先处理指定的交易号,用于修正交易号直接发送通知 @@ -803,23 +803,23 @@ class Index extends CI_Controller { //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); + $ssje = $old_ssje===NULL ? $ssje : $old_ssje; //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 - $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); //把订单状态改为已付款 + $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); } - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); @@ -829,7 +829,6 @@ class Index extends CI_Controller { elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已支付 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); @@ -1078,6 +1077,7 @@ class Index extends CI_Controller { public function gai_modal_save() { $data = array(); + $old_ssje = NULL; $pn_txn_id = $this->input->post('pn_txn_id'); $pn_id = $this->input->post('pn_id'); $neworder = $this->input->post('pn_invoice'); @@ -1088,10 +1088,16 @@ class Index extends CI_Controller { $orderid_info = json_decode($orderid_info); if ($orderid_info->ordertype === 'T') { $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id); - $this->Paypal_model->delete_money_t($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->Paypal_model->delete_money_t($pn_txn_id); + } } elseif ($orderid_info->ordertype === 'B') { $data['gai_info'] = $this->Paypal_model->get_money_b($pn_txn_id); - $this->Paypal_model->delete_money_b($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->Paypal_model->delete_money_b($pn_txn_id); + } } } @@ -1102,7 +1108,7 @@ class Index extends CI_Controller { $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); if (!empty($advisor_info)) { $this->Note_model->set_invoice($pn_txn_id, $neworder); - $this->send_note($pn_txn_id); + $this->send_note($pn_txn_id, $old_ssje); echo json_encode('修改成功!'); return true; } From d5e067ea6295f4e6e266228b251bff7a6a27cfcc Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 23 Nov 2018 11:14:14 +0800 Subject: [PATCH 206/382] =?UTF-8?q?=E7=BA=BF=E8=B7=AF=E8=AE=A2=E5=8D=95:?= =?UTF-8?q?=E5=AE=A2=E4=BA=BA=E4=BF=A1=E6=81=AF=E5=88=97=E8=A1=A8;?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=9F=8E=E5=B8=82;=E8=A1=8C=E7=A8=8B?= =?UTF-8?q?=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 55 ++++++++++++++++++- .../vendorPlanSync/helpers/array_helper.php | 17 ++++++ .../vendorPlanSync/models/Group_model.php | 52 +++++++++++++++++- 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index ca706f63..dafb11ad 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -78,19 +78,70 @@ class Tulanduo extends CI_Controller } // 传统订单 if (strval($order->GRI_OrderType) === "227001") { + return $this->push_tour($order); } return "[Tulanduo>order_push] No function match. "; } + /*! + * 发送线路订单计划 + * @date 2018-11-22 + */ + public function push_tour($vas=null) + { + $userId = $this->send_host["1"]["userId"]; + $userKey = $this->send_host["1"]["key"]; + $gri_sn = $vas->GRI_SN; + $vas_sn = $vas->VAS_SN; + $vei_sn = $vas->VAS_VEI_SN; + $is_send_vary = $vas->VAS_SendVary; + $change_info = $vas->VAS_ChangeText; + if (trim($change_info) !== "") { + preg_match_all('/(.*)={6}(.*)(\d{4}\-\d{2}\-\d{2})/ismU', characet($change_info,'UTF-8'), $change_arr); + $change_info = $change_arr[0][0]; + } + $change_info = str_replace("\n", "<br>", $change_info); + $agcOrderNo = $vas->GRI_Name; + // $grd_info = $this->Group_model->get_vendor_plan_info($gri_sn, $vei_sn); + // $all_day_no = array_map(function($ele){return $ele->GRD_DayNo;}, $grd_info); + $routeType = "桂林海纳国旅"; // todo + $arrange_info = $this->Group_model->get_arrange_info($gri_sn, $vei_sn); + $routeName = "中华游" . $arrange_info[0]->tocity . "常规线路"; // todo + $last_date = count($arrange_info)-1; + $end_date = strstr($arrange_info[$last_date]->ACI_OrderDate, " ", true); + $this->tldOrderBuilder->setUserId($userId) + ->setKey($userKey) + ->setOrderType(1) + ->setRouteName($routeName) + ->setRouteType($routeType) + ->setAgcOrderNo($agcOrderNo) + ->setAdultNum(intval($arrange_info[0]->ACI_PersonNum)) + ->setChildNum(intval(bcadd($arrange_info[0]->ACI_ChildNum, $arrange_info[0]->ACI_BabyNum))) + ->setDestination($arrange_info[0]->tocity) + ->setTravelDate(strstr($arrange_info[0]->ACI_OrderDate, " ", true)) + ->setLeavedDate($end_date) + // ->setOrderRemark($order_remark) + ; + $guestlist = $this->Group_model->get_customer_list($gri_sn); // todo orders_model + foreach ($guestlist as $key => $vg) { + $this->tldOrderBuilder->setCustomersName($key, $vg->MemberName ) + ->setCustomersPeopleType($key, (calc_age_type($vg->BirthDay)==1 ? "成人" : "儿童")) + ->setCustomersDocumentType($key, "护照") // Passport No. + ->setCustomersDocumentNo($key, $vg->PassportNo) + ->setCustomersOtherInfo($key, $vg->Country); + } + return $this->tldOrderBuilder->getBizContent(); + } + /*! * 发送目的地项目组预订计划到图兰朵地接系统 * 地接社未接收的或有变更的 - * @date 2018-05-02 + * @date 2018-10-26 */ public function push_trippest($vas=null) { - return "[Tulanduo>push_trippest] Done. "; + return "[Tulanduo>push_trippest] Done. "; // test /** 目的地 */ $userId = $this->send_host["30"]["userId"]; $userKey = $this->send_host["30"]["key"]; diff --git a/webht/third_party/vendorPlanSync/helpers/array_helper.php b/webht/third_party/vendorPlanSync/helpers/array_helper.php index 3d265013..1fb1f504 100644 --- a/webht/third_party/vendorPlanSync/helpers/array_helper.php +++ b/webht/third_party/vendorPlanSync/helpers/array_helper.php @@ -166,3 +166,20 @@ function real_phone_number($phone, $nation_code) return mb_ereg_replace('[\D]', '', $cut_nation); } +function calc_age($birthday) +{ + $now = new DateTime(); + $birth = new DateTime(strstr($birthday, " ", TRUE)); + $date_d = $now->diff($birth); + $d_t = ($date_d->format("%y")); + return $d_t; +} + +function calc_age_type($birthday) +{ + $age = calc_age($birthday); + if ($age > 17) { + return 1; + } + return 2; +} diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index e7aa68c1..5b480627 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -13,7 +13,7 @@ class Group_model extends CI_Model { $top_sql = $top>0 ? " TOP $top " : ""; $gri_sql = $gri_sn===0 ? "" : " and GRI_SN=$gri_sn "; $sql = "SELECT $top_sql VAS_IsConfirm, VAS_SendVary, - GRI_OrderType, GRI_SN, GRI_No, GRI_operator, + GRI_OrderType, GRI_SN, GRI_No, GRI_operator,GRI_Name, (select OPI_DEI_SN from OperatorInfo where OPI_SN=GRI_operator) as department, vas.* from VendorArrangeState vas @@ -26,7 +26,7 @@ class Group_model extends CI_Model { and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' -- and VAS_VEI_SN in (29188, 1343, 30548) -- test - and GRI_OrderType=227002 -- test + -- and GRI_OrderType=227002 -- test and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) "; $sql .= " order by EOI_GetDate asc, vas.VAS_IsConfirm asc"; return $this->HT->query($sql)->result(); @@ -54,6 +54,54 @@ class Group_model extends CI_Model { return $this->HT->query($sql)->result(); } + public function get_arrange_info($gri_sn, $vendor_id) + { + $param_arr = array($gri_sn, $vendor_id); + $sql = "SELECT + (select CII2_Name from CItyInfo2 + where CII2_CII_SN=ACI_FromCity and CII2_LGC=2) as fromcity, + (select CII2_Name from CItyInfo2 + where CII2_CII_SN=ACI_ToCity and CII2_LGC=2) as tocity, + * + from ArrangeConfirmInfo aci + where 1=1 + and aci.ACI_GRI_SN=? + and aci.ACI_VEI_SN=? + order by ACI_DayNo,ACI_SNInOneDay "; + return $this->HT->query($sql, $param_arr)->result(); + } + + public function get_customer_list($gri_sn) + { + $sql = "SELECT ( + SELECT (isnull(MEI_LastName,'') +' / '+ isnull(MEI_FirstName,'')) CustomerName + from MemberInfo + where MEI_SN=CUL_CUI_SN + ) as MemberName, + (select MEI_BirthDay from MemberInfo where MEI_SN=CUL_CUI_SN) as BirthDay, + ISNULL((select SYC2_CodeDiscribe + from V_System_Code + where LGC_LGC=2 + and SYC_SN=( + select top 1 MEI_Gender from MemberInfo + where MEI_SN=CUL_CUI_SN)),'' + ) Gender, + (select COI2_Country from V_Country_Info + where LGC_LGC = 2 + and COI_SN in (select MEI_Country from MemberInfo where MEI_SN=CUL_CUI_SN) + ) as Country, + (select MEI_PassportNo from MemberInfo where MEI_SN=CUL_CUI_SN) PassportNo, + (select MEI_PassportValidDate from MemberInfo where MEI_SN=CUL_CUI_SN) PassportValidDate + -- ,(select dbo.GetSysCodeName(MEI_Occupation,2) from MemberInfo where MEI_SN=CUL_CUI_SN) as Occupation + from CustomerList + where isnull(CUL_IsAgent,0)=0 + and isnull(CUL_IsEmergency,0)=0 + and isnull(CUL_IsTJR,0)=0 + and CUL_COLI_SN in (select COLI_SN from ConfirmLineInfo where COLI_GRI_SN=?) + order by CUL_Order"; + return $this->HT->query($sql, array($gri_sn))->result(); + } + public function get_sync_info($vas, $tour_code="") { $sql = "SELECT * From fc8b72bd702185721f4330904b4dd7f495f8580b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 27 Nov 2018 17:01:23 +0800 Subject: [PATCH 207/382] =?UTF-8?q?=E7=BA=BF=E8=B7=AF=E8=AE=A2=E5=8D=95:?= =?UTF-8?q?=E8=A1=A5=E5=85=A8=E7=A9=BA=E8=A1=8C=E7=A8=8B=E7=9A=84=E6=97=A5?= =?UTF-8?q?=E6=9C=9F=EF=BC=9B=E8=A1=8C=E7=A8=8B=E6=8E=A5=E5=BE=85=E6=A0=87?= =?UTF-8?q?=E5=87=86=E3=80=81=E8=A6=81=E6=B1=82=EF=BC=9B=E9=85=92=E5=BA=97?= =?UTF-8?q?=E8=A6=81=E6=B1=82=EF=BC=9B=E6=88=90=E4=BA=BA/=E5=84=BF?= =?UTF-8?q?=E7=AB=A5=E8=AE=A1=E7=AE=97=E4=BF=AE=E6=AD=A3=E6=AD=A3=EF=BC=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 69 ++++++++++++-- .../vendorPlanSync/helpers/array_helper.php | 9 +- .../vendorPlanSync/models/Group_model.php | 93 ++++++++++++------- .../vendorPlanSync/models/orders_model.php | 45 +++++++++ 4 files changed, 169 insertions(+), 47 deletions(-) create mode 100644 webht/third_party/vendorPlanSync/models/orders_model.php diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index dafb11ad..22124efc 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -59,6 +59,7 @@ class Tulanduo extends CI_Controller $this->load->helper('array'); $this->load->library('trippest'); $this->load->model('Group_model'); + $this->load->model('orders_model'); $this->load->model('BIZ_orders_model', 'BIZ_order'); $this->load->model('TuLanDuo_queryContentBuilder', 'tld_order'); $this->load->model('TuLanDuo_addOrUpdateRouteOrderContentBuilder', 'tldOrderBuilder'); @@ -103,13 +104,15 @@ class Tulanduo extends CI_Controller } $change_info = str_replace("\n", "<br>", $change_info); $agcOrderNo = $vas->GRI_Name; - // $grd_info = $this->Group_model->get_vendor_plan_info($gri_sn, $vei_sn); - // $all_day_no = array_map(function($ele){return $ele->GRD_DayNo;}, $grd_info); + $grd_info = $this->Group_model->get_vendor_plan_info($gri_sn, $vei_sn); + $all_day_no = array_map(function($ele){return $ele->GRD_DayNo;}, $grd_info); $routeType = "桂林海纳国旅"; // todo $arrange_info = $this->Group_model->get_arrange_info($gri_sn, $vei_sn); - $routeName = "中华游" . $arrange_info[0]->tocity . "常规线路"; // todo - $last_date = count($arrange_info)-1; - $end_date = strstr($arrange_info[$last_date]->ACI_OrderDate, " ", true); + $routeName = "中华游" . $arrange_info[0]->tocity . "线路"; // todo + $first_date = $grd_info[0]->day_no_raw; + $last_date = count($grd_info)-1; + $end_date = $grd_info[$last_date]->day_no_raw; + $request_info = $this->Group_model->get_plan_request($gri_sn); $this->tldOrderBuilder->setUserId($userId) ->setKey($userKey) ->setOrderType(1) @@ -119,11 +122,13 @@ class Tulanduo extends CI_Controller ->setAdultNum(intval($arrange_info[0]->ACI_PersonNum)) ->setChildNum(intval(bcadd($arrange_info[0]->ACI_ChildNum, $arrange_info[0]->ACI_BabyNum))) ->setDestination($arrange_info[0]->tocity) - ->setTravelDate(strstr($arrange_info[0]->ACI_OrderDate, " ", true)) + ->setTravelDate($first_date) ->setLeavedDate($end_date) - // ->setOrderRemark($order_remark) + // ->setOrderRemark($order_remark) // 订单备注 + ->setRoomStandard($request_info->GCI_HotelRequest) // 住房标准 + ->setRouteStandard($request_info->GCI_Request) // 行程服务标准 ; - $guestlist = $this->Group_model->get_customer_list($gri_sn); // todo orders_model + $guestlist = $this->orders_model->get_customer_list($gri_sn); foreach ($guestlist as $key => $vg) { $this->tldOrderBuilder->setCustomersName($key, $vg->MemberName ) ->setCustomersPeopleType($key, (calc_age_type($vg->BirthDay)==1 ? "成人" : "儿童")) @@ -131,7 +136,55 @@ class Tulanduo extends CI_Controller ->setCustomersDocumentNo($key, $vg->PassportNo) ->setCustomersOtherInfo($key, $vg->Country); } + $travel_fee = 0; + foreach ($arrange_info as $kaci => $vaci) { + $travel_fee = bcadd($travel_fee, $vaci->ACI_Amount); + } + $this->tldOrderBuilder->setTravelFeesType(0, "Per Group") + ->setTravelFeesMoney(0, $travel_fee) + ->setTravelFeesNum(0, 1) + ->setTravelFeesUnit(0, 1) + ->setTravelFeesSumMoney(0, $travel_fee) + ->setTravelFeesRemark(0, ""); + // 补全空的日期,行车为空 + $date1 = new DateTime($first_date); + $date_end = new DateTime($end_date); + $date_diff = $date_end->diff($date1); + $d = ($date_diff->format("%d")); + $all_date = array(); + for ($j=0; $j < ($d+1); $j++) { + $all_date[] = date('Y-m-d', strtotime("+$j day", strtotime($first_date))); + } + $real_date = array_map(function ($ele){return $ele->day_no_raw;}, $grd_info); + foreach ($all_date as $kd => $vd) { + if ( ! in_array($vd, $real_date)) { + $this->tldOrderBuilder->setScheduleDetailsTitle($kd, "无") + ->setScheduleDetailsContent($kd, "无") + ->setScheduleDetailsAccommodation($kd, "") + // ->setScheduleDetailsTraffic($kd, ($vso->PAG_Vehicle>60001 ? 1 : 0)) + ->setScheduleDetailsBreakFirst($kd, 0 ) + ->setScheduleDetailsDinner($kd, 0) + ->setScheduleDetailsLunch($kd, 0) + ; + continue; + } + foreach ($grd_info as $kgrd => $vgrd) { + if ($vd==$vgrd->day_no_raw) { + $this->tldOrderBuilder->setScheduleDetailsTitle($kd, $vgrd->GRD_OrderDate) + ->setScheduleDetailsContent($kd, $vgrd->GRD_Landscape) + ->setScheduleDetailsAccommodation($kd, $vgrd->GRD_Hotel) + ->setScheduleDetailsTraffic($kd, ($vgrd->GRD_Traffic)) + ->setScheduleDetailsBreakFirst($kd, 0 ) + ->setScheduleDetailsDinner($kd, (trim($vgrd->GRD_Meal_S)==="" ? 0 : 1 )) + ->setScheduleDetailsLunch($kd, (trim($vgrd->GRD_Meal_L)==="" ? 0 : 1 )) + ; + } + } + } return $this->tldOrderBuilder->getBizContent(); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // $response = json_decode($resp); + // return $resp; } /*! diff --git a/webht/third_party/vendorPlanSync/helpers/array_helper.php b/webht/third_party/vendorPlanSync/helpers/array_helper.php index 1fb1f504..2f6ec50f 100644 --- a/webht/third_party/vendorPlanSync/helpers/array_helper.php +++ b/webht/third_party/vendorPlanSync/helpers/array_helper.php @@ -177,9 +177,12 @@ function calc_age($birthday) function calc_age_type($birthday) { - $age = calc_age($birthday); - if ($age > 17) { + if (trim(strval($birthday))==="") { return 1; } - return 2; + $age = calc_age($birthday); + if ($age < 18) { + return 2; + } + return 1; } diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 5b480627..2ddce070 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -50,13 +50,64 @@ class Group_model extends CI_Model { public function get_vendor_plan_info($gri_sn, $vendor_id) { - $sql = " SP_VendorPlan_GetPlanInfo $gri_sn, $vendor_id, 0 "; - return $this->HT->query($sql)->result(); + // SET NOCOUNT ON 才能这样调用, 否则需要遍历结果集 + // $sql = " Tourmanager.dbo.SP_VendorPlan_GetPlanInfo ?, ?, 0 "; + // $grd_info = $this->HT->query($sql, array($gri_sn, $vendor_id))->result(); + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "EXEC Tourmanager.dbo.SP_VendorPlan_GetPlanInfo $gri_sn, $vendor_id, 0 "); + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + $grd_info = $result_object; + $all_day_no = array_map(function($ele){return $ele->GRD_DayNo;}, $grd_info); + $day_no_str = implode(",", $all_day_no); + $all_aci = $this->get_arrange_info($gri_sn, 0, $day_no_str); + foreach ($grd_info as $kgrd => &$vgrd) { + foreach ($all_aci as $kaci => $vaci) { + if ($vgrd->GRD_DayNo == $vaci->ACI_DayNo) { + $vgrd->day_no_raw = strstr($vaci->ACI_OrderDate, " ", true); + break; + } + } + } + return $grd_info; + } + + public function get_plan_request($gri_sn) + { + $sql = "SELECT * from GroupChangeInfo + where GCI_GRI_SN=? + order by LastEditTime desc + ,case when GCI_Order IS null then 999 else GCI_Order end desc"; + return $this->HT->query($sql, array($gri_sn))->row(); } - public function get_arrange_info($gri_sn, $vendor_id) + public function get_arrange_info($gri_sn, $vendor_id=0, $day_no="") { - $param_arr = array($gri_sn, $vendor_id); + $param_arr = array($gri_sn); + $vendor_sql = ""; + if ($vendor_id !== 0) { + $vendor_sql = " AND aci.ACI_VEI_SN=? "; + $param_arr[] = $vendor_id; + } + $day_no_sql = ($day_no !== "") ? " AND aci.ACI_DayNo IN ($day_no) " : ""; $sql = "SELECT (select CII2_Name from CItyInfo2 where CII2_CII_SN=ACI_FromCity and CII2_LGC=2) as fromcity, @@ -66,42 +117,12 @@ class Group_model extends CI_Model { from ArrangeConfirmInfo aci where 1=1 and aci.ACI_GRI_SN=? - and aci.ACI_VEI_SN=? + $vendor_sql + $day_no_sql order by ACI_DayNo,ACI_SNInOneDay "; return $this->HT->query($sql, $param_arr)->result(); } - public function get_customer_list($gri_sn) - { - $sql = "SELECT ( - SELECT (isnull(MEI_LastName,'') +' / '+ isnull(MEI_FirstName,'')) CustomerName - from MemberInfo - where MEI_SN=CUL_CUI_SN - ) as MemberName, - (select MEI_BirthDay from MemberInfo where MEI_SN=CUL_CUI_SN) as BirthDay, - ISNULL((select SYC2_CodeDiscribe - from V_System_Code - where LGC_LGC=2 - and SYC_SN=( - select top 1 MEI_Gender from MemberInfo - where MEI_SN=CUL_CUI_SN)),'' - ) Gender, - (select COI2_Country from V_Country_Info - where LGC_LGC = 2 - and COI_SN in (select MEI_Country from MemberInfo where MEI_SN=CUL_CUI_SN) - ) as Country, - (select MEI_PassportNo from MemberInfo where MEI_SN=CUL_CUI_SN) PassportNo, - (select MEI_PassportValidDate from MemberInfo where MEI_SN=CUL_CUI_SN) PassportValidDate - -- ,(select dbo.GetSysCodeName(MEI_Occupation,2) from MemberInfo where MEI_SN=CUL_CUI_SN) as Occupation - from CustomerList - where isnull(CUL_IsAgent,0)=0 - and isnull(CUL_IsEmergency,0)=0 - and isnull(CUL_IsTJR,0)=0 - and CUL_COLI_SN in (select COLI_SN from ConfirmLineInfo where COLI_GRI_SN=?) - order by CUL_Order"; - return $this->HT->query($sql, array($gri_sn))->result(); - } - public function get_sync_info($vas, $tour_code="") { $sql = "SELECT * diff --git a/webht/third_party/vendorPlanSync/models/orders_model.php b/webht/third_party/vendorPlanSync/models/orders_model.php new file mode 100644 index 00000000..ebbcac11 --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/orders_model.php @@ -0,0 +1,45 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Orders_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + public function get_customer_list($gri_sn) + { + $sql = "SELECT ( + SELECT (isnull(MEI_LastName,'') +' / '+ isnull(MEI_FirstName,'')) CustomerName + from MemberInfo + where MEI_SN=CUL_CUI_SN + ) as MemberName, + (select MEI_BirthDay from MemberInfo where MEI_SN=CUL_CUI_SN) as BirthDay, + ISNULL((select SYC2_CodeDiscribe + from V_System_Code + where LGC_LGC=2 + and SYC_SN=( + select top 1 MEI_Gender from MemberInfo + where MEI_SN=CUL_CUI_SN)),'' + ) Gender, + (select COI2_Country from V_Country_Info + where LGC_LGC = 2 + and COI_SN in (select MEI_Country from MemberInfo where MEI_SN=CUL_CUI_SN) + ) as Country, + (select MEI_PassportNo from MemberInfo where MEI_SN=CUL_CUI_SN) PassportNo, + (select MEI_PassportValidDate from MemberInfo where MEI_SN=CUL_CUI_SN) PassportValidDate + -- ,(select dbo.GetSysCodeName(MEI_Occupation,2) from MemberInfo where MEI_SN=CUL_CUI_SN) as Occupation + from CustomerList + where isnull(CUL_IsAgent,0)=0 + and isnull(CUL_IsEmergency,0)=0 + and isnull(CUL_IsTJR,0)=0 + and CUL_COLI_SN in (select COLI_SN from ConfirmLineInfo where COLI_GRI_SN=?) + order by CUL_Order"; + return $this->HT->query($sql, array($gri_sn))->result(); + } + +} + +/* End of file orders_model.php */ +/* Location: ./third_party/vendorPlanSync/models/orders_model.php */ From dd400c60e26e521e9a4249fc03242d89d03252a5 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 27 Nov 2018 17:10:00 +0800 Subject: [PATCH 208/382] =?UTF-8?q?=E7=BA=BF=E8=B7=AF=E8=AE=A2=E5=8D=95:?= =?UTF-8?q?=20=E5=A2=9E=E5=8A=A0=E5=A4=96=E8=81=94=E5=90=8D=E5=AD=97,=20?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E5=9F=8E=E5=B8=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/Tulanduo.php | 7 ++++--- webht/third_party/vendorPlanSync/models/Group_model.php | 3 +++ 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 22124efc..747649a7 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -103,12 +103,13 @@ class Tulanduo extends CI_Controller $change_info = $change_arr[0][0]; } $change_info = str_replace("\n", "<br>", $change_info); - $agcOrderNo = $vas->GRI_Name; $grd_info = $this->Group_model->get_vendor_plan_info($gri_sn, $vei_sn); $all_day_no = array_map(function($ele){return $ele->GRD_DayNo;}, $grd_info); - $routeType = "桂林海纳国旅"; // todo + $routeType = "桂林海纳国旅"; // todo 线路类型 $arrange_info = $this->Group_model->get_arrange_info($gri_sn, $vei_sn); - $routeName = "中华游" . $arrange_info[0]->tocity . "线路"; // todo + $routeName = "中华游" . $arrange_info[0]->tocity . "线路"; // todo 线路名称 + $agcOrderNo = $vas->GRI_Name . "-" . $arrange_info[0]->citycode; + $agcOrderNo .= "(" . $vas->operator . ")"; $first_date = $grd_info[0]->day_no_raw; $last_date = count($grd_info)-1; $end_date = $grd_info[$last_date]->day_no_raw; diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 2ddce070..dc8d46f7 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -15,6 +15,7 @@ class Group_model extends CI_Model { $sql = "SELECT $top_sql VAS_IsConfirm, VAS_SendVary, GRI_OrderType, GRI_SN, GRI_No, GRI_operator,GRI_Name, (select OPI_DEI_SN from OperatorInfo where OPI_SN=GRI_operator) as department, + (select OPI2_Name from OperatorInfo2 where OPI2_OPI_SN=GRI_operator and OPI2_LGC=2) as operator, vas.* from VendorArrangeState vas inner join Eva_ObjectInfo eoi on EOI_GRI_SN=VAS_GRI_SN and EOI_Type=1 and EOI_ObjSN=VAS_VEI_SN @@ -113,6 +114,8 @@ class Group_model extends CI_Model { where CII2_CII_SN=ACI_FromCity and CII2_LGC=2) as fromcity, (select CII2_Name from CItyInfo2 where CII2_CII_SN=ACI_ToCity and CII2_LGC=2) as tocity, + (select CII_PKCode from CItyInfo + where CII_SN=ACI_ToCity ) as citycode, * from ArrangeConfirmInfo aci where 1=1 From 1bd077bf526f6c2d14c67f59eb6a9da56dccfc7b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 29 Nov 2018 18:09:37 +0800 Subject: [PATCH 209/382] =?UTF-8?q?=E8=B0=83=E6=95=B4=E5=8F=91=E9=80=81/?= =?UTF-8?q?=E4=B8=8A=E6=8A=A5=E7=9B=B8=E5=85=B3=E7=8A=B6=E6=80=81;=20?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=B0=83=E7=94=A8=E8=B4=A6=E6=88=B7=E9=AA=8C?= =?UTF-8?q?=E8=AF=81;=20=E5=AF=BC=E6=B8=B8=E4=B8=8A=E6=8A=A5=E5=90=8E?= =?UTF-8?q?=E5=BD=95=E5=85=A5=E6=98=AF=E5=90=A6=E6=88=90=E5=8A=9F=E7=8A=B6?= =?UTF-8?q?=E6=80=81;=20=E5=A2=9E=E5=8A=A0=E6=B5=8B=E8=AF=95=E5=85=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + .../vendorPlanSync/controllers/Tulanduo.php | 53 +++++++++++++---- .../vendorPlanSync/controllers/index.php | 34 +++++++++-- .../vendorPlanSync/models/Group_model.php | 2 +- .../vendorPlanSync/models/UserAuth_model.php | 58 +++++++++++++++++++ 5 files changed, 130 insertions(+), 19 deletions(-) create mode 100644 webht/third_party/vendorPlanSync/models/UserAuth_model.php diff --git a/.gitignore b/.gitignore index 4954fc1d..f4ff3920 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,5 @@ /author/document/* */statement_files/* */paypal_activities/* +test122.php +/test122/* diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 747649a7..dbaa9ba3 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -182,6 +182,28 @@ class Tulanduo extends CI_Controller } } } + // 查询是否变更 + $sync_orderstate = 1; + $vps_sn = 0; + $vendor_orderid = 0; + $modifyLogInfo = "<br>$change_info<br>"; + if (intval($is_send_vary)===1) { + $vps = $this->Group_model->get_sync_info($vas_sn); + if ( ! empty($vps)) { + $vps_sn = $vps->VPS_SN; + $vendor_orderid = $vps->VPS_externalId; + $sync_orderstate = 11; + // $modifyLogInfo = "<br><a href='https://www.trippest.com'>https://www.trippest.com</a><br>"; + $this->tldOrderBuilder->setOrderId($vendor_orderid) + ->setModifyLogInfo($modifyLogInfo) + ; + } + } else { + $this->tldOrderBuilder->clearModifyLogInfo(); + // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) + ; + } + return $this->tldOrderBuilder->getBizContent(); // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); // $response = json_decode($resp); @@ -195,7 +217,7 @@ class Tulanduo extends CI_Controller */ public function push_trippest($vas=null) { - return "[Tulanduo>push_trippest] Done. "; // test + // return "[Tulanduo>push_trippest] Done. "; // test /** 目的地 */ $userId = $this->send_host["30"]["userId"]; $userKey = $this->send_host["30"]["key"]; @@ -419,7 +441,7 @@ class Tulanduo extends CI_Controller } } // 查询是否变更 - $sync_orderstate = 1; + $sync_orderstate = 10; $vps_sn = 0; $vendor_orderid = 0; if (intval($is_send_vary)===1) { @@ -441,8 +463,9 @@ class Tulanduo extends CI_Controller } // echo(($this->tldOrderBuilder->getBizContent())); // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); - $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); // var_dump($resp); + $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test $response = json_decode($resp); if ($response->status == 1) { /** VendorPlanSync */ @@ -474,6 +497,7 @@ class Tulanduo extends CI_Controller public function tourguide_update($input, $vps, $eva) { $ret['status'] = -1; + $ret['err'] = 100; $ret['errMsg'] = "未知错误"; $eva_g_sn = $eva[0]->has_tourguide; if (strval($vps->department)==="30") { @@ -486,12 +510,14 @@ class Tulanduo extends CI_Controller $this->tld_order->setOrderId($vps->VPS_externalId) ->setUserId($userId) ->setKey($userKey); - $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + // $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + $detail_resp = '{"status":1,"errMsg":"","orderDetail":{"orderId":' . rand(1000,9999) . ',"operationDetails": {"guiderOperations":[{"name":"北京翟梦琪Susie","mobelPhone":"18801326155","startDate":"2017-04-25","endDate":"2017-04-25","sumMoney":400,"remark":"","guiderPhoto":"http://djb3c.ltsoftware.net:9921/projects/djb3c//uploadImages/guider/1526898234415.png"}]}}}'; // test $detail_jsonResp = json_decode($detail_resp); // 判断 if ($detail_jsonResp->status !== 1) { log_message('error','TulanduoApi get_orderdetail failed. Msg:' . $detail_jsonResp->errMsg . "; Request: " . $this->tld_order->getBizContent()); - $ret['errMsg'] = "查询失败"; + $ret['err'] = 100; // 获取详情失败 + $ret['errMsg'] = "获取详情失败"; return $ret; } // 导游信息 @@ -502,6 +528,7 @@ class Tulanduo extends CI_Controller $tourguide_mobile = real_phone_number($detail_jsonResp->orderDetail->operationDetails->guiderOperations[0]->mobelPhone, 86); } if ($tourguige_name === "") { + $ret['err'] = 102; // 未查询到导游 $ret['errMsg'] = "未查询到导游"; return $ret; } @@ -511,24 +538,26 @@ class Tulanduo extends CI_Controller $tourguige_name_en = characet($en_name_arr[0][0],'UTF-8'); $ht_tourguide = $this->Group_model->search_tourguide($input['openId'], $tourguige_name_cn, $tourguige_name_en, $tourguide_mobile); if (empty($ht_tourguide)) { + $ret['err'] = 200; // 导游信息未录入 $ret['errMsg'] = "导游信息未录入"; return $ret; } $eva_tgi_column = array( "EOI_Type" => 3 - ,"EOI_GRI_SN" => $eva->EOI_GRI_SN - ,"EOI_VEI_SN" => $eva->EOI_ObjSN + ,"EOI_GRI_SN" => $eva[0]->EOI_GRI_SN + ,"EOI_VEI_SN" => $eva[0]->EOI_ObjSN ,"EOI_ObjSN" => $ht_tourguide->TGI_SN - ,"EOI_CII_SN" => $eva->EOI_CII_SN - ,"EOI_GetDate" => $eva->EOI_GetDate - ,"EOI_Date" => $eva->EOI_Date - ,"EOI_Cancel" => $eva->EOI_Cancel - ,"EOI_GroupType" => $eva->EOI_GroupType + ,"EOI_CII_SN" => $eva[0]->EOI_CII_SN + ,"EOI_GetDate" => $eva[0]->EOI_GetDate + ,"EOI_Date" => $eva[0]->EOI_Date + ,"EOI_Cancel" => $eva[0]->EOI_Cancel + ,"EOI_GroupType" => $eva[0]->EOI_GroupType ,"EOI_FillWorkers_SN" => 0 // todo ,"EOI_FWks_LastEditTime" => date('Y-m-d H:i:s') ); $this->Group_model->set_plan_tourguide($eva_g_sn, $eva_tgi_column); $ret['status'] = 1; + $ret['err'] = 0; $ret['errMsg'] = ""; return $ret; } diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 92071230..2b6f1035 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -9,8 +9,18 @@ class Index extends CI_Controller { bcscale(4); $this->load->helper('array'); $this->load->library('vendor'); - $this->load->model('BIZ_Orders_model'); + $this->load->model('UserAuth_model'); $this->load->model('Group_model'); + $this->load->model('BIZ_Orders_model'); + + $opend_id = $this->input->post('openId'); + $opend_key = $this->input->post('key'); + $match = $this->UserAuth_model->if_user_key($open_id, $open_key, 11, 1); + if ($match !== TRUE) { + $ret['status'] = -1; + $ret['errMsg'] = "用户验证失败"; + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } } public function index() @@ -77,10 +87,10 @@ class Index extends CI_Controller { $ret = $this->fill_tourguide($input, $vps); break; case '4001': - # code... - break; case '4002': - # code... + $ret['status'] = 1; + $ret['errMsg'] = ""; + log_message('error','上报确认取消. ' . json_encode($input)); break; default: @@ -103,7 +113,7 @@ class Index extends CI_Controller { $ret['status'] = 1; $ret['errMsg'] = ""; $sync_arr = array( - "VPS_externalorderState" => 2 + "VPS_externalorderState" => 20 ,"VPS_latestTime" => date('Y-m-d H:i:s') ); /** VendorPlanSync */ @@ -147,7 +157,19 @@ class Index extends CI_Controller { $controller_name = $this->vendor->vendor_fun[strval($input['openId'])]; require_once($controller_name . '.php'); $vendor_class = new $controller_name(); - return $vendor_class->tourguide_update($input, $vps, $eva); + $ret = $vendor_class->tourguide_update($input, $vps, $eva); + $err_code = $ret['err']; + unset($ret['err']); // 不返回给接收方 + $sync_ret = array( + "VPS_latestTime" => date('Y-m-d H:i:s') + ); + if ($err_code === 0) { + // 录入成功 + $sync_ret['VPS_externalorderState'] = 31; + } else { + $sync_ret['VPS_externalorderState'] = 32; + } + $this->Group_model->update_VendorPlanSync($vps->VPS_SN, $sync_ret); } return $ret; } diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index dc8d46f7..457ff90b 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -176,7 +176,7 @@ class Group_model extends CI_Model { public function search_tourguide($vendor, $cn_name, $en_name=null, $mobile=null) { - $param_arr = array($cn_name); + $param_arr = array(); $en_sql = " "; if (strval($en_name)!=="") { $en_sql = " and tgi_en.TGI2_Name =? "; diff --git a/webht/third_party/vendorPlanSync/models/UserAuth_model.php b/webht/third_party/vendorPlanSync/models/UserAuth_model.php new file mode 100644 index 00000000..87cf9569 --- /dev/null +++ b/webht/third_party/vendorPlanSync/models/UserAuth_model.php @@ -0,0 +1,58 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class UserAuth_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + /*! + * TPA_Direction + * 1 外部调用我社系统 + * 2 我社调用外部系统 + * + * TPA_AccountType + * - 1* 外部调用我社系统 + * - 11 地接社 + * - 2* 我社调用外部系统 + * - 21 所属小组 + * + */ + + public function get_user_key($account_id, $account_type, $direction) + { + $sql = "SELECT * + FROM [Tourmanager].[dbo].[ThirdPartyAuth] + where TPA_Direction=? + and TPA_AccountType=? + and TPA_AccountID=? + order by TPA_ExpiredTime desc "; + return $this->HT->query($sql, array($direction, $account_type, $account_id))->row(); + } + + /*! + * 验证openID,openKey是否有效 + * @date 2018-11-29 + * @param int $open_id + * @param string $open_key + * @param integer $direction 默认是1-外部调用 + * @return boolean + */ + public function if_user_key($open_id, $open_key, $account_type, $direction=1) + { + $sql = "SELECT tpa_sn + FROM [Tourmanager].[dbo].[ThirdPartyAuth] + where tpa_direction=? + and TPA_AccountType=? + and tpa_openid=? + and tpa_openkey=? + "; + return ($this->HT->query($sql, array($direction, $account_type, $open_id, $open_key))->num_rows() > 0); + } + +} + +/* End of file UserAuth_model.php */ +/* Location: ./third_party/vendorPlanSync/models/UserAuth_model.php */ From 0e77b42fc5a29f573fc8adf7371c5debc536a6e1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 11:03:04 +0800 Subject: [PATCH 210/382] =?UTF-8?q?=E6=8E=A5=E5=8F=A3=E8=B0=83=E7=94=A8?= =?UTF-8?q?=E8=B4=A6=E6=88=B7=E9=AA=8C=E8=AF=81;=20=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E8=BF=94=E5=9B=9E=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 34 +++++++++++++++---- .../vendorPlanSync/controllers/index.php | 33 ++++++++++-------- .../vendorPlanSync/models/UserAuth_model.php | 24 +++++-------- 3 files changed, 56 insertions(+), 35 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index dbaa9ba3..0ff6e7a6 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -114,9 +114,10 @@ class Tulanduo extends CI_Controller $last_date = count($grd_info)-1; $end_date = $grd_info[$last_date]->day_no_raw; $request_info = $this->Group_model->get_plan_request($gri_sn); + $order_type = 1; $this->tldOrderBuilder->setUserId($userId) ->setKey($userKey) - ->setOrderType(1) + ->setOrderType($order_type) ->setRouteName($routeName) ->setRouteType($routeType) ->setAgcOrderNo($agcOrderNo) @@ -183,7 +184,7 @@ class Tulanduo extends CI_Controller } } // 查询是否变更 - $sync_orderstate = 1; + $sync_orderstate = 10; $vps_sn = 0; $vendor_orderid = 0; $modifyLogInfo = "<br>$change_info<br>"; @@ -203,11 +204,32 @@ class Tulanduo extends CI_Controller // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; } - - return $this->tldOrderBuilder->getBizContent(); // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - // $response = json_decode($resp); - // return $resp; + $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test + $response = json_decode($resp); + if ($response->status == 1) { + /** VendorPlanSync */ + $sync_ret = array( + "VPS_VAS_SN" => $vas_sn + ,"VPS_GRI_SN" => $gri_sn + ,"VPS_VEI_SN" => $vei_sn + ,"VPS_startDate" => $first_date + ,"VPS_endDate" => $end_date + ,"VPS_sendHost" => $userId + ,"VPS_externalId" => $response->responseData->orderId + ,"VPS_externalorderType" => $order_type + ,"VPS_externalorderState" => $sync_orderstate + ,"VPS_latestTime" => date('Y-m-d H:i:s') + ); + if ($vps_sn === 0) { + $sync_id = $this->Group_model->insert_VendorPlanSync($sync_ret); + } else { + $update = $this->Group_model->update_VendorPlanSync($vps_sn, $sync_ret); + } + /** VendorArrangeState VAS_IsReceive */ + $this->Group_model->set_plan_received($vas_sn); + } + return $this->tldOrderBuilder->getBizContent() . "Order Push done. "; } /*! diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 2b6f1035..61a00740 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -13,16 +13,13 @@ class Index extends CI_Controller { $this->load->model('Group_model'); $this->load->model('BIZ_Orders_model'); - $opend_id = $this->input->post('openId'); - $opend_key = $this->input->post('key'); - $match = $this->UserAuth_model->if_user_key($open_id, $open_key, 11, 1); - if ($match !== TRUE) { - $ret['status'] = -1; - $ret['errMsg'] = "用户验证失败"; - return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); - } } + /*! + * TODO + * 请求的openID和订单的VEI_SN不相等 + */ + public function index() { $vendor_plan = $this->Group_model->get_vendor_plan_info(214600, 1343); @@ -48,6 +45,14 @@ class Index extends CI_Controller { return $this->output->set_output("Not found vendor function. " . $order->GRI_SN); } + public function verify_user() + { + $open_id = $this->input->post('openId'); + $open_key = $this->input->post('key'); + $match = $this->UserAuth_model->if_user_key($open_id, $open_key, 1); + return $match; + } + /** * 接收地接社的信息上报 * * 信息类型代码: @@ -62,13 +67,13 @@ class Index extends CI_Controller { { $ret['status'] = -1; $ret['errMsg'] = "未知错误"; - $input = $this->input->post(); - $vendorID = $input['openId']; - $validate = $this->calc_key($vendorID, $input['key']); - if ($validate !== TRUE) { - $ret['errMsg'] = "身份验证失败."; + $user_verify = $this->verify_user(); + if ($user_verify !== TRUE) { + $ret['errMsg'] = '用户验证失败'; return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } + $input = $this->input->post(); + $vendorID = $input['openId']; $vps = $this->Group_model->get_sync_info_by_vendororder($input['orderId']); if (empty($vps)) { $ret['errMsg'] = "未找到相应的订单."; @@ -178,7 +183,7 @@ class Index extends CI_Controller { { $default = "b825e39422a54875a95752fc7ed6f5d2"; $ret = md5(hash("sha256", $userId.$default)); - return $ret===$key; + return $ret; } } diff --git a/webht/third_party/vendorPlanSync/models/UserAuth_model.php b/webht/third_party/vendorPlanSync/models/UserAuth_model.php index 87cf9569..3e92c037 100644 --- a/webht/third_party/vendorPlanSync/models/UserAuth_model.php +++ b/webht/third_party/vendorPlanSync/models/UserAuth_model.php @@ -9,27 +9,21 @@ class UserAuth_model extends CI_Model { } /*! - * TPA_Direction - * 1 外部调用我社系统 - * 2 我社调用外部系统 * * TPA_AccountType - * - 1* 外部调用我社系统 - * - 11 地接社 - * - 2* 我社调用外部系统 - * - 21 所属小组 + * - 1 地接社 * */ - public function get_user_key($account_id, $account_type, $direction) + public function get_user_key($account_id, $account_type) { $sql = "SELECT * FROM [Tourmanager].[dbo].[ThirdPartyAuth] - where TPA_Direction=? + where 1=1 and TPA_AccountType=? and TPA_AccountID=? order by TPA_ExpiredTime desc "; - return $this->HT->query($sql, array($direction, $account_type, $account_id))->row(); + return $this->HT->query($sql, array($account_type, $account_id))->row(); } /*! @@ -40,16 +34,16 @@ class UserAuth_model extends CI_Model { * @param integer $direction 默认是1-外部调用 * @return boolean */ - public function if_user_key($open_id, $open_key, $account_type, $direction=1) + public function if_user_key($open_id, $open_key, $account_type) { $sql = "SELECT tpa_sn FROM [Tourmanager].[dbo].[ThirdPartyAuth] - where tpa_direction=? + where 1=1 and TPA_AccountType=? - and tpa_openid=? - and tpa_openkey=? + and TPA_OpenId=? + and TPA_OpenKey=? "; - return ($this->HT->query($sql, array($direction, $account_type, $open_id, $open_key))->num_rows() > 0); + return ($this->HT->query($sql, array($account_type, $open_id, $open_key))->num_rows() > 0); } } From a69d3c05e69a0b6ef5e113ade18e0b14ebd0ecbd Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 11:27:07 +0800 Subject: [PATCH 211/382] =?UTF-8?q?=E7=9F=AD=E4=BF=A1=E5=8F=91=E9=80=81?= =?UTF-8?q?=E6=97=A5=E5=BF=97=E5=A2=9E=E5=8A=A0=E6=98=BE=E7=A4=BA=E6=8E=A5?= =?UTF-8?q?=E6=94=B6=E5=8F=B7=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/views/order_sms_list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/trippestOrderSync/views/order_sms_list.php b/webht/third_party/trippestOrderSync/views/order_sms_list.php index ab0b9788..a3078675 100644 --- a/webht/third_party/trippestOrderSync/views/order_sms_list.php +++ b/webht/third_party/trippestOrderSync/views/order_sms_list.php @@ -2,6 +2,7 @@ <thead> <tr> <th>发送时间</th> + <th>接收号码</th> <th>失败原因</th> </tr> </thead> @@ -18,6 +19,7 @@ ?> <tr> <td> <?php echo $value->TPSL_logTime; ?> </td> + <td> <?php echo "+$value->TPSL_nationCode $value->TPSL_mobile"; ?> </td> <td> <?php echo $tmp_msg; ?> </td> </tr> <?php } ?> From 21510ce5058418653f880fa6f7634d3485f2b8a3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 11:34:10 +0800 Subject: [PATCH 212/382] =?UTF-8?q?=E5=8E=86=E5=8F=B2=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E7=9A=84=E6=88=90=E6=9C=AC=E8=AF=A6=E6=83=85=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=AE=8C=E6=AF=95;=20=E8=B4=A2=E5=8A=A1=E8=A1=A8=E6=89=80?= =?UTF-8?q?=E9=9C=80=E6=88=90=E6=9C=AC=E7=9A=84=E5=90=8C=E6=AD=A5=E7=AD=96?= =?UTF-8?q?=E7=95=A5=E5=BE=85=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/models/orders_model.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index edf910d0..b5522e5b 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -175,6 +175,7 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo_finance() { + return array(); // 历史数据已获取完毕, 财务数据的获取方法待定 2018-11-30 $sql = " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' from GroupCombineInfo gci @@ -188,6 +189,14 @@ class Orders_model extends CI_Model { and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' and gci.GCI_createTime < '" . date('Y-m-d') . "' and GCI_combineNo not like '%取消%' + and not exists ( + select GCOD_SN from GroupCombineOperationDetail gcod where gcod.GCOD_GCI_combineNo=GCI_combineNo + ) + and 0 < ( + select sum(isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)+isnull(COLD_BabyNum,0)) person from BIZ_ConfirmLineInfo + inner join BIZ_ConfirmLineDetail on COLD_COLI_SN=COLI_SN + where COLI_GRI_SN=gri_sn + ) "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; $query = $this->HT->query($sql); From 52b7373b77343128b93462b76471adbb2040eff1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 11:38:39 +0800 Subject: [PATCH 213/382] =?UTF-8?q?=E8=A1=A5=E5=85=85=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/index.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 61a00740..e695410b 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -17,7 +17,8 @@ class Index extends CI_Controller { /*! * TODO - * 请求的openID和订单的VEI_SN不相等 + * * 请求的openID和订单的VEI_SN不相等 + * * 使用供应商平台登陆账号获取接口的key */ public function index() From 91f58074fd3943b34f876bbf1aba0fec406d0237 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 14:29:31 +0800 Subject: [PATCH 214/382] =?UTF-8?q?=E5=AF=BC=E6=B8=B8=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E5=A1=AB=E5=86=99=E4=BA=BA=E5=A1=AB=E5=85=A5=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86=E9=BB=98=E8=AE=A4=E8=81=94=E7=B3=BB=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 23 ++++++++++--------- .../vendorPlanSync/models/Group_model.php | 10 ++++++++ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 0ff6e7a6..179e391d 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -24,17 +24,17 @@ class Tulanduo extends CI_Controller // ,"key" => "d05c25e6e6c5d4898161e0aaf700d9c7" // ) // ); - /** test - * 902 key:f56541ff40e1afba444d831c5a666195 + /** + * test */ private $send_host = array( "30" => array( - "userId" => 902 - ,"key" => "f56541ff40e1afba444d831c5a666195" + "userId" => 512 + ,"key" => "4d9bde5ce79d6093e4a98bebbd3892c2" ) ,"1" => array( - "userId" => 902 - ,"key" => "f56541ff40e1afba444d831c5a666195" + "userId" => 512 + ,"key" => "4d9bde5ce79d6093e4a98bebbd3892c2" ) ); @@ -44,12 +44,12 @@ class Tulanduo extends CI_Controller // 30548 9db75a2dc17156eb122364295804b7a2 // test - // public $list_url = "http://dj.ltsoftware.net:9901/action/api/searchRouteOrder/"; - // public $detail_url = "http://dj.ltsoftware.net:9901/action/api/detailRouteOrder/"; + public $list_url = "http://ltdj.ltsoftware.net:19919/action/api/searchRouteOrder/"; + public $detail_url = "http://ltdj.ltsoftware.net:19919/action/api/detailRouteOrder/"; public $neworder_url = "http://ltdj.ltsoftware.net:19919/action/api/addOrUpdateRouteOrder/"; // Live - public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; - public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; + // public $list_url = "http://djb3c.ltsoftware.net:9921/action/api/searchRouteOrder/"; + // public $detail_url = "http://djb3c.ltsoftware.net:9921/action/api/detailRouteOrder/"; // public $neworder_url = "http://djb3c.ltsoftware.net:9921/action/api/addOrUpdateRouteOrder/"; public function __construct(){ @@ -564,6 +564,7 @@ class Tulanduo extends CI_Controller $ret['errMsg'] = "导游信息未录入"; return $ret; } + $vendor_contactor = $this->Group_model->get_vendor_contactor($eva[0]->EOI_ObjSN); $eva_tgi_column = array( "EOI_Type" => 3 ,"EOI_GRI_SN" => $eva[0]->EOI_GRI_SN @@ -574,7 +575,7 @@ class Tulanduo extends CI_Controller ,"EOI_Date" => $eva[0]->EOI_Date ,"EOI_Cancel" => $eva[0]->EOI_Cancel ,"EOI_GroupType" => $eva[0]->EOI_GroupType - ,"EOI_FillWorkers_SN" => 0 // todo + ,"EOI_FillWorkers_SN" => $vendor_contactor->LMI_SN ,"EOI_FWks_LastEditTime" => date('Y-m-d H:i:s') ); $this->Group_model->set_plan_tourguide($eva_g_sn, $eva_tgi_column); diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 457ff90b..2261bab3 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -205,6 +205,16 @@ class Group_model extends CI_Model { return $this->HT->query($sql, $param_arr)->row(); } + public function get_vendor_contactor($vendor_id) + { + $sql = "SELECT * + from V_Link_Man_Info vlmi + where vlmi.LMI_VEI_SN=? + and vlmi.LMI_DefaultContactor='Yes' + and vlmi.LGC_LGC=2"; + return $this->HT->query($sql, array($vendor_id))->row(); + } + public function set_plan_tourguide($eva_g_sn=0, $column=array()) { if ($eva_g_sn===0) { From a72f811525c3f4627bfc0dc759bbf74aeaec5d9a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 15:12:33 +0800 Subject: [PATCH 215/382] =?UTF-8?q?=E5=88=A0=E4=BA=86=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E7=9A=84=E8=8E=B7=E5=8F=96=E4=BE=9B=E5=BA=94=E5=95=86=E8=81=94?= =?UTF-8?q?=E7=B3=BB=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 22 +++++------ .../vendorPlanSync/models/Group_model.php | 37 +++++++------------ 2 files changed, 23 insertions(+), 36 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 179e391d..fb83e350 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -204,8 +204,8 @@ class Tulanduo extends CI_Controller // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; } - // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test + $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test $response = json_decode($resp); if ($response->status == 1) { /** VendorPlanSync */ @@ -229,7 +229,8 @@ class Tulanduo extends CI_Controller /** VendorArrangeState VAS_IsReceive */ $this->Group_model->set_plan_received($vas_sn); } - return $this->tldOrderBuilder->getBizContent() . "Order Push done. "; + // return $this->tldOrderBuilder->getBizContent() . "[Tulanduo>push_tour] Done. "; + return "[Tulanduo>push_tour] Done. "; } /*! @@ -483,11 +484,8 @@ class Tulanduo extends CI_Controller // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; } - // echo(($this->tldOrderBuilder->getBizContent())); - // $this->output->set_content_type('application/json')->set_output($this->tldOrderBuilder->getBizContent()); - // $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); - // var_dump($resp); - $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test + $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); + // $resp = '{"status":1,"errMsg":"","responseData":{"orderId":' . rand(1000,9999) . '}}'; // test $response = json_decode($resp); if ($response->status == 1) { /** VendorPlanSync */ @@ -513,7 +511,7 @@ class Tulanduo extends CI_Controller $this->Group_model->set_plan_received($vas_sn); } } - return "Order Push done. "; + return "[Tulanduo>push_trippest] Done. "; } public function tourguide_update($input, $vps, $eva) @@ -532,8 +530,8 @@ class Tulanduo extends CI_Controller $this->tld_order->setOrderId($vps->VPS_externalId) ->setUserId($userId) ->setKey($userKey); - // $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); - $detail_resp = '{"status":1,"errMsg":"","orderDetail":{"orderId":' . rand(1000,9999) . ',"operationDetails": {"guiderOperations":[{"name":"北京翟梦琪Susie","mobelPhone":"18801326155","startDate":"2017-04-25","endDate":"2017-04-25","sumMoney":400,"remark":"","guiderPhoto":"http://djb3c.ltsoftware.net:9921/projects/djb3c//uploadImages/guider/1526898234415.png"}]}}}'; // test + $detail_resp = $this->excute_curl($this->detail_url, $this->tld_order); + // $detail_resp = '{"status":1,"errMsg":"","orderDetail":{"orderId":' . rand(1000,9999) . ',"operationDetails": {"guiderOperations":[{"name":"北京翟梦琪Susie","mobelPhone":"18801326155","startDate":"2017-04-25","endDate":"2017-04-25","sumMoney":400,"remark":"","guiderPhoto":"http://djb3c.ltsoftware.net:9921/projects/djb3c//uploadImages/guider/1526898234415.png"}]}}}'; // test $detail_jsonResp = json_decode($detail_resp); // 判断 if ($detail_jsonResp->status !== 1) { @@ -564,7 +562,7 @@ class Tulanduo extends CI_Controller $ret['errMsg'] = "导游信息未录入"; return $ret; } - $vendor_contactor = $this->Group_model->get_vendor_contactor($eva[0]->EOI_ObjSN); + $vendor_contactor = $this->Group_model->get_vendorContact($eva[0]->EOI_ObjSN); $eva_tgi_column = array( "EOI_Type" => 3 ,"EOI_GRI_SN" => $eva[0]->EOI_GRI_SN diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 2261bab3..45d3d5a3 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -155,22 +155,21 @@ class Group_model extends CI_Model { /*! * 获取地接社接受计划的人员信息 - * @param $vendorID 地接社ID + * @param $vendor_id 地接社ID */ - public function get_vendorContact($vendorID) + public function get_vendorContact($vendor_id) { - $sql = "SELECT top 1 lmi2.LMI2_Name, - lmi.LMI_SN, - lmi.LMI_AutoFax, - lmi.LMI_Telephone, - lmi.LMI_Mobile, - lmi.LMI_ListMail - ,vei2.VEI2_CompanyBN - FROM LinkmanInfo lmi - INNER JOIN LinkManInfo2 lmi2 ON lmi2.LMI2_LMI_SN=lmi.LMI_SN AND lmi2.LMI2_LGC=2 - INNER JOIN VEndorInfo2 vei2 ON vei2.VEI2_VEI_SN=LMI_VEI_SN AND VEI2_LGC=2 - WHERE LMI_Receiver='Yes' AND LMI_VEI_SN=$vendorID"; - $query = $this->HT->query($sql); + $sql = "SELECT + lmi.LMI2_Name,lmi.LMI_SN,lmi.LMI_AutoFax + ,lmi.LMI_Telephone,lmi.LMI_Mobile,lmi.LMI_ListMail + ,vei2.VEI2_CompanyBN + from V_Link_Man_Info lmi + left join VEndorInfo2 vei2 on VEI2_VEI_SN=lmi.LMI_VEI_SN + and VEI2_LGC=2 + where lmi.LMI_VEI_SN=? + and lmi.LMI_DefaultContactor='Yes' + and lmi.LGC_LGC=2"; + $query = $this->HT->query($sql, array($vendor_id)); return $query->row(); } @@ -205,16 +204,6 @@ class Group_model extends CI_Model { return $this->HT->query($sql, $param_arr)->row(); } - public function get_vendor_contactor($vendor_id) - { - $sql = "SELECT * - from V_Link_Man_Info vlmi - where vlmi.LMI_VEI_SN=? - and vlmi.LMI_DefaultContactor='Yes' - and vlmi.LGC_LGC=2"; - return $this->HT->query($sql, array($vendor_id))->row(); - } - public function set_plan_tourguide($eva_g_sn=0, $column=array()) { if ($eva_g_sn===0) { From 3f00ccb2d9ca5e41eb0b766f4e59c464052ae31a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 15:31:03 +0800 Subject: [PATCH 216/382] =?UTF-8?q?=E8=AE=B0=E5=BD=95=E6=B5=8B=E8=AF=95?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/index.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index e695410b..507ec818 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -66,6 +66,8 @@ class Index extends CI_Controller { */ public function uploadOperation() { + $input = $this->input->post(); + log_message('error',"Call [Tulanduo>uploadOperation]: " . json_encode($input)); $ret['status'] = -1; $ret['errMsg'] = "未知错误"; $user_verify = $this->verify_user(); @@ -73,7 +75,6 @@ class Index extends CI_Controller { $ret['errMsg'] = '用户验证失败'; return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); } - $input = $this->input->post(); $vendorID = $input['openId']; $vps = $this->Group_model->get_sync_info_by_vendororder($input['orderId']); if (empty($vps)) { From 8f863696f9999aba63b879b3817fffc02755c6bb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 30 Nov 2018 16:12:41 +0800 Subject: [PATCH 217/382] =?UTF-8?q?=E5=8F=91=E9=80=81=E6=96=B0=E8=AE=A1?= =?UTF-8?q?=E5=88=92:+=E8=AE=A1=E5=88=92=E8=AF=A6=E6=83=85=E9=A1=B5?= =?UTF-8?q?=E9=9D=A2,=20=E5=90=AB=E4=B8=8B=E8=BD=BD=E6=96=87=E4=BB=B6;(?= =?UTF-8?q?=E6=8E=A5=E6=94=B6=E6=8E=A5=E5=8F=A3=E6=9C=AA=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E5=85=B6=E4=BB=96=E4=BF=A1=E6=81=AF=E5=BD=95=E5=85=A5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/vendorPlanSync/controllers/Tulanduo.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index fb83e350..6657890e 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -200,8 +200,10 @@ class Tulanduo extends CI_Controller ; } } else { + $plan_detail_page = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; + $modifyLogInfo = "<br>计划下载:<a href='$plan_detail_page'>$plan_detail_page</a><br>"; $this->tldOrderBuilder->clearModifyLogInfo(); - // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) + $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; } $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); @@ -474,14 +476,15 @@ class Tulanduo extends CI_Controller $vendor_orderid = $vps->VPS_externalId; $sync_orderstate = 11; $modifyLogInfo = "<br>$change_info<br>"; - // $modifyLogInfo = "<br><a href='https://www.trippest.com'>https://www.trippest.com</a><br>"; $this->tldOrderBuilder->setOrderId($vendor_orderid) ->setModifyLogInfo($modifyLogInfo) ; } } else { + $plan_detail_page = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; + $modifyLogInfo = "<br>计划下载:<a href='$plan_detail_page'>$plan_detail_page</a><br>"; $this->tldOrderBuilder->clearModifyLogInfo(); - // $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) + $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; } $resp = $this->excute_curl($this->neworder_url, $this->tldOrderBuilder); From adbfbc0a3722d52811a2145456714994530d58ee Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 3 Dec 2018 15:19:13 +0800 Subject: [PATCH 218/382] =?UTF-8?q?=E5=8F=98=E6=9B=B4=E4=BF=A1=E6=81=AF?= =?UTF-8?q?=E6=AF=8F=E6=AC=A1=E5=8A=A0=E4=B8=8A=E4=B8=8B=E8=BD=BD=E9=93=BE?= =?UTF-8?q?=E6=8E=A5,=E6=96=B0=E8=AE=A2=E5=8D=95=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BC=80=E6=94=BE=E5=85=B6=E4=BB=96=E4=BF=A1=E6=81=AF=E5=AD=97?= =?UTF-8?q?=E6=AE=B5=E5=90=8E=E5=88=A0=E9=99=A4;=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=AD=9B=E9=80=89=E4=BB=85=E6=9F=A5=E8=AF=A2=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=8F=91=E9=80=81=E7=9A=84=E4=BE=9B=E5=BA=94?= =?UTF-8?q?=E5=95=86id;=20=E5=95=86=E5=8A=A1=E8=AE=A2=E5=8D=95=E6=9A=82?= =?UTF-8?q?=E6=97=B6=E7=94=A8=E4=BC=A0=E7=BB=9F=E8=AE=A2=E5=8D=95=E6=96=B9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../vendorPlanSync/controllers/Tulanduo.php | 16 +++++++++------- .../vendorPlanSync/controllers/index.php | 9 +++++---- .../vendorPlanSync/libraries/vendor.php | 2 ++ .../vendorPlanSync/models/Group_model.php | 5 +++-- 4 files changed, 19 insertions(+), 13 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 6657890e..0bbdc502 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -76,6 +76,7 @@ class Tulanduo extends CI_Controller } // 商务 if (strval($order->GRI_OrderType) === "227002") { + return $this->push_tour($order); } // 传统订单 if (strval($order->GRI_OrderType) === "227001") { @@ -187,21 +188,21 @@ class Tulanduo extends CI_Controller $sync_orderstate = 10; $vps_sn = 0; $vendor_orderid = 0; - $modifyLogInfo = "<br>$change_info<br>"; + $plan_detail_page_url = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; + $plan_detail_page = "<br>计划下载:<a href='$plan_detail_page_url'>$plan_detail_page_url</a><br>"; if (intval($is_send_vary)===1) { $vps = $this->Group_model->get_sync_info($vas_sn); if ( ! empty($vps)) { $vps_sn = $vps->VPS_SN; $vendor_orderid = $vps->VPS_externalId; $sync_orderstate = 11; - // $modifyLogInfo = "<br><a href='https://www.trippest.com'>https://www.trippest.com</a><br>"; + $modifyLogInfo = "$plan_detail_page<br>$change_info<br>"; $this->tldOrderBuilder->setOrderId($vendor_orderid) ->setModifyLogInfo($modifyLogInfo) ; } } else { - $plan_detail_page = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; - $modifyLogInfo = "<br>计划下载:<a href='$plan_detail_page'>$plan_detail_page</a><br>"; + $modifyLogInfo = $plan_detail_page; $this->tldOrderBuilder->clearModifyLogInfo(); $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; @@ -469,20 +470,21 @@ class Tulanduo extends CI_Controller $sync_orderstate = 10; $vps_sn = 0; $vendor_orderid = 0; + $plan_detail_page_url = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; + $plan_detail_page = "<br>计划下载:<a href='$plan_detail_page_url'>$plan_detail_page_url</a><br>"; if (intval($is_send_vary)===1) { $vps = $this->Group_model->get_sync_info($vas_sn, $tour_code); if ( ! empty($vps)) { $vps_sn = $vps->VPS_SN; $vendor_orderid = $vps->VPS_externalId; $sync_orderstate = 11; - $modifyLogInfo = "<br>$change_info<br>"; + $modifyLogInfo = "$plan_detail_page<br>$change_info<br>"; $this->tldOrderBuilder->setOrderId($vendor_orderid) ->setModifyLogInfo($modifyLogInfo) ; } } else { - $plan_detail_page = "http://p.mycht.cn/Cooperate/Plan_Detail.aspx?GSN=" . $gri_sn; - $modifyLogInfo = "<br>计划下载:<a href='$plan_detail_page'>$plan_detail_page</a><br>"; + $modifyLogInfo = $plan_detail_page; $this->tldOrderBuilder->clearModifyLogInfo(); $this->tldOrderBuilder->setModifyLogInfo($modifyLogInfo) ; diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 507ec818..ca5f618e 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -23,15 +23,15 @@ class Index extends CI_Controller { public function index() { - $vendor_plan = $this->Group_model->get_vendor_plan_info(214600, 1343); - return $this->output->set_content_type('application/json')->set_output(json_encode($vendor_plan)); + $auto_vendor_str = implode(",", $this->vendor->auto_vendor); + return $this->push(0, $auto_vendor_str); } - public function push($GRI_SN=0) + public function push($GRI_SN=0, $vendor_str=null) { $start_date = date('Y-m-d'); $end_date = date('Y-m-d 23:59:59', strtotime("+2 months")); - $ready_to_send = $this->Group_model->get_plan_not_received(1, $GRI_SN, $start_date, $end_date); + $ready_to_send = $this->Group_model->get_plan_not_received(1, $GRI_SN, $vendor_str, $start_date, $end_date); if (empty($ready_to_send)) { return $this->output->set_output("empty"); } @@ -41,6 +41,7 @@ class Index extends CI_Controller { require_once($controller_name . ".php"); $vendor_class = new $controller_name(); $call_fun = $vendor_class->order_push($order); + log_message('error',"Call [$controller_name>order_push] " . $order->GRI_SN); return $this->output->set_output($call_fun . $order->GRI_SN); } return $this->output->set_output("Not found vendor function. " . $order->GRI_SN); diff --git a/webht/third_party/vendorPlanSync/libraries/vendor.php b/webht/third_party/vendorPlanSync/libraries/vendor.php index 935e0ba8..ac8a0ddb 100644 --- a/webht/third_party/vendorPlanSync/libraries/vendor.php +++ b/webht/third_party/vendorPlanSync/libraries/vendor.php @@ -10,6 +10,8 @@ class Vendor $this->ci =& get_instance(); } + public $auto_vendor = array(1343,29188,30548); + public $vendor_fun = array( "1343" => "Tulanduo" ,"29188" => "Tulanduo" diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 45d3d5a3..5001fcb6 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -8,7 +8,7 @@ class Group_model extends CI_Model { $this->HT = $this->load->database('HT', TRUE); } - public function get_plan_not_received($top=1, $gri_sn=0, $start_date=null, $end_date=null) + public function get_plan_not_received($top=1, $gri_sn=0, $vendor_str=null, $start_date=null, $end_date=null) { $top_sql = $top>0 ? " TOP $top " : ""; $gri_sql = $gri_sn===0 ? "" : " and GRI_SN=$gri_sn "; @@ -26,10 +26,11 @@ class Group_model extends CI_Model { and VAS_IsSendSucceed=1 and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' - -- and VAS_VEI_SN in (29188, 1343, 30548) -- test + and VAS_VEI_SN in ($vendor_str) -- and GRI_OrderType=227002 -- test and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) "; $sql .= " order by EOI_GetDate asc, vas.VAS_IsConfirm asc"; +// log_message('error',$sql); return $this->HT->query($sql)->result(); } From b2b3959aee8bf8cddfe14e56b223ca8f3f305bb3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 5 Dec 2018 17:02:55 +0800 Subject: [PATCH 219/382] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E6=95=B0=E6=8D=AE:?= =?UTF-8?q?=20=E5=8F=91=E9=80=81=E7=9B=AE=E7=9A=84=E5=9C=B0=E7=BB=84?= =?UTF-8?q?=E8=AE=A1=E5=88=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/models/Group_model.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/vendorPlanSync/models/Group_model.php b/webht/third_party/vendorPlanSync/models/Group_model.php index 5001fcb6..e17b8b5e 100644 --- a/webht/third_party/vendorPlanSync/models/Group_model.php +++ b/webht/third_party/vendorPlanSync/models/Group_model.php @@ -27,7 +27,8 @@ class Group_model extends CI_Model { and VAS_IsConfirm=0 and EOI_GetDate between '$start_date' and '$end_date' and VAS_VEI_SN in ($vendor_str) - -- and GRI_OrderType=227002 -- test + and GRI_operator in (161,443,61) -- test + and GRI_OrderType=227002 -- test and (VAS_IsReceive=0 or (VAS_SendTime > ISNULL(VAS_ReceiveTime,0))) "; $sql .= " order by EOI_GetDate asc, vas.VAS_IsConfirm asc"; // log_message('error',$sql); From 3609054e49954603eabbd185b9adf122d50da981 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 6 Dec 2018 14:02:17 +0800 Subject: [PATCH 220/382] =?UTF-8?q?=E5=88=B7=E6=96=B0201808=E7=9A=84?= =?UTF-8?q?=E6=88=90=E6=9C=AC=E6=95=B0=E6=8D=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 2 ++ .../trippestOrderSync/models/orders_model.php | 12 ++---------- 2 files changed, 4 insertions(+), 10 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 811968b7..36811535 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -1197,6 +1197,7 @@ class TulanduoApi extends CI_Controller // ,=> ,"西安精品一日游(目的地)" => "XASIC-41" ,"西安精品一日游PVT(目的地)" => "XASIC-41" + ,"西安市内精华一日游(目的地)" => "XASIC-41" ,"西安市内精品一日游(目的地)" => "XASIC-41" ,"西安精品两日游(目的地)" => "XASIC-42" ,"西安单租车服务(目的地)" => "XASIC-17" @@ -1205,6 +1206,7 @@ class TulanduoApi extends CI_Controller ,"西安兵马俑精品一日游(目的地)" => "XASIC-41" ,"西安兵马俑精华一日游(目的地)" => "XASIC-41" ,"西安兵马俑精品半日游(目的地)" => "XASIC-15" + ,"西安兵马俑精华半日游(目的地)" => "XASIC-15" ,"西安兵马俑精品半日游PVT(目的地)" => "XASIC-15" ,"西安汉阳陵市内精品一日游(目的地)" => "XASIC-42" // ,=> diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index b5522e5b..4c11c095 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -186,17 +186,9 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - and GCI_leaveDate < '" . date('Y-m-d', strtotime("-7 days")) . "' - and gci.GCI_createTime < '" . date('Y-m-d') . "' +and GCI_travelDate between '2018-08-01' and '2018-08-31 23:59:59' +and gci.GCI_createTime < '2018-12-06 14:00:00' and GCI_combineNo not like '%取消%' - and not exists ( - select GCOD_SN from GroupCombineOperationDetail gcod where gcod.GCOD_GCI_combineNo=GCI_combineNo - ) - and 0 < ( - select sum(isnull(COLD_PersonNum,0)+isnull(COLD_ChildNum,0)+isnull(COLD_BabyNum,0)) person from BIZ_ConfirmLineInfo - inner join BIZ_ConfirmLineDetail on COLD_COLI_SN=COLI_SN - where COLI_GRI_SN=gri_sn - ) "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; $query = $this->HT->query($sql); From 283a45fe4ba4326595c505083d4ed9b63521b927 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 6 Dec 2018 16:28:00 +0800 Subject: [PATCH 221/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=8F=91=E9=80=81?= =?UTF-8?q?=E8=AE=B0=E5=BD=95=E7=9A=84=E5=AD=97=E6=AE=B5,=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E6=9B=B4=E6=96=B0=E6=97=B6=E9=97=B4[=E5=9C=B0?= =?UTF-8?q?=E6=8E=A5=E7=A4=BE=E4=B8=8A=E6=8A=A5=E4=BF=A1=E6=81=AF=E7=9A=84?= =?UTF-8?q?=E6=97=B6=E9=97=B4],=20=E9=A2=84=E7=95=99=E7=BB=99=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E5=8F=96=E6=B6=88=E6=98=AF=E5=90=A6=E7=A1=AE=E8=AE=A4?= =?UTF-8?q?=E6=97=B6=E7=94=A8(=E7=94=B1=E4=BA=8E=E5=9B=BE=E5=85=B0?= =?UTF-8?q?=E6=9C=B5=E5=9C=B0=E6=8E=A5=E7=B3=BB=E7=BB=9F=E7=9A=84=E8=AE=A1?= =?UTF-8?q?=E5=88=92=E6=B2=A1=E6=9C=89=E5=8F=96=E6=B6=88=E7=9A=84=E7=8A=B6?= =?UTF-8?q?=E6=80=81,=E6=97=A0=E6=B3=95=E4=B8=8A=E6=8A=A5),=20=E5=8C=BA?= =?UTF-8?q?=E5=88=86=E4=BA=8E=E5=8F=91=E9=80=81=E6=97=B6=E9=97=B4;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/Tulanduo.php | 4 ++-- webht/third_party/vendorPlanSync/controllers/index.php | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php index 0bbdc502..330f6b24 100644 --- a/webht/third_party/vendorPlanSync/controllers/Tulanduo.php +++ b/webht/third_party/vendorPlanSync/controllers/Tulanduo.php @@ -222,7 +222,7 @@ class Tulanduo extends CI_Controller ,"VPS_externalId" => $response->responseData->orderId ,"VPS_externalorderType" => $order_type ,"VPS_externalorderState" => $sync_orderstate - ,"VPS_latestTime" => date('Y-m-d H:i:s') + ,"VPS_sendTime" => date('Y-m-d H:i:s') ); if ($vps_sn === 0) { $sync_id = $this->Group_model->insert_VendorPlanSync($sync_ret); @@ -505,7 +505,7 @@ class Tulanduo extends CI_Controller ,"VPS_externalId" => $response->responseData->orderId ,"VPS_externalorderType" => $order_type ,"VPS_externalorderState" => $sync_orderstate - ,"VPS_latestTime" => date('Y-m-d H:i:s') + ,"VPS_sendTime" => date('Y-m-d H:i:s') ); if ($vps_sn === 0) { $sync_id = $this->Group_model->insert_VendorPlanSync($sync_ret); diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index ca5f618e..24fe5510 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -122,7 +122,7 @@ class Index extends CI_Controller { $ret['errMsg'] = ""; $sync_arr = array( "VPS_externalorderState" => 20 - ,"VPS_latestTime" => date('Y-m-d H:i:s') + ,"VPS_updateTime" => date('Y-m-d H:i:s') ); /** VendorPlanSync */ $this->Group_model->update_VendorPlanSync($vps->VPS_SN, $sync_arr); @@ -169,7 +169,7 @@ class Index extends CI_Controller { $err_code = $ret['err']; unset($ret['err']); // 不返回给接收方 $sync_ret = array( - "VPS_latestTime" => date('Y-m-d H:i:s') + "VPS_updateTime" => date('Y-m-d H:i:s') ); if ($err_code === 0) { // 录入成功 From 7cb7e4a7a8ee7c7e54fa494c946534da41ef8e5f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 6 Dec 2018 16:50:19 +0800 Subject: [PATCH 222/382] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=8F=91=E9=80=81?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E7=9A=84=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/vendorPlanSync/controllers/index.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/webht/third_party/vendorPlanSync/controllers/index.php b/webht/third_party/vendorPlanSync/controllers/index.php index 24fe5510..95f4d734 100644 --- a/webht/third_party/vendorPlanSync/controllers/index.php +++ b/webht/third_party/vendorPlanSync/controllers/index.php @@ -63,6 +63,14 @@ class Index extends CI_Controller { * * * 3001 导游信息变更 * * * 4001 已确认取消 * * * 4002 订单已删除 + * * 计划发送/更新状态 + * * * 未确认: + * * * 10 已接收计划 + * * * 11 已接收变更 + * * * 上报信息: + * * * 20 已上报确认 + * * * 31 已录入上报导游 + * * * 32 未录入上报导游 * @date 2018-11-14 */ public function uploadOperation() From de226cf324ac7127b770b41270375cd5603a655a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 18 Dec 2018 10:10:49 +0800 Subject: [PATCH 223/382] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=95=86=E5=8A=A1?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E7=9A=84=E6=93=8D=E4=BD=9C=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 2 ++ .../pay/controllers/iPayLinksService.php | 2 ++ webht/third_party/pay/models/Alipay_model.php | 14 ++++++++++++++ webht/third_party/pay/models/IPayLinks_model.php | 14 ++++++++++++++ webht/third_party/paypal/controllers/index.php | 2 ++ webht/third_party/paypal/models/paypal_model.php | 14 ++++++++++++++ 6 files changed, 48 insertions(+) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index eeab05f0..fe8190b5 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -384,11 +384,13 @@ class AlipayTradeService extends CI_Controller // $this->Alipay_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->ALI_dealId, $ht_memo); // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 // $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + // $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); // } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->Alipay_model->if_biz_gai_exists($item->ALI_dealId) ) { $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 13); + $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'BS13'); } $this->Alipay_model->add_account_info( $GAI_COLI_SN, diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index a939b143..e3e7ebeb 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -462,11 +462,13 @@ class IPayLinksService extends CI_Controller // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { // //只修改APP组的订单状态,并且订单进度是我的订单 // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + // $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); // } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) { $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 13); + $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS13'); } $this->IPayLinks_model->add_account_info( $GAI_COLI_SN, diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 4e7644bb..1d17f7c0 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -333,4 +333,18 @@ class Alipay_model extends CI_Model { $query = $this->HT->query($sql); return $query; } + + /** 写入商务订单操作记录 */ + public function insert_biz_order_log($coli_sn, $log_info) + { + $db_column = array( + "BOL_COLI_SN" => $coli_sn + ,"BOL_OPI_SN" => 0 + ,"BOL_OPType" => $log_info + ,"BOL_OPTime" => date('Y-m-d H:i:s') + ,"BOL_Creator" => 0 + ,"BOL_CreateTime" => date('Y-m-d H:i:s') + ); + return $this->HT->insert("BIZ_OrderOperationLog", $db_column); + } } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index ba7a4687..de3fb567 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -391,4 +391,18 @@ class IPayLinks_model extends CI_Model { $query = $this->HT->query($sql); return $query; } + + /** 写入商务订单操作记录 */ + public function insert_biz_order_log($coli_sn, $log_info) + { + $db_column = array( + "BOL_COLI_SN" => $coli_sn + ,"BOL_OPI_SN" => 0 + ,"BOL_OPType" => $log_info + ,"BOL_OPTime" => date('Y-m-d H:i:s') + ,"BOL_Creator" => 0 + ,"BOL_CreateTime" => date('Y-m-d H:i:s') + ); + return $this->HT->insert("BIZ_OrderOperationLog", $db_column); + } } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 87c17ead..adf0ac0b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -814,11 +814,13 @@ class Index extends CI_Controller { $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); + $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'BS13'); } $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 110d2e70..781db229 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -584,4 +584,18 @@ class Paypal_model extends CI_Model { $query = $this->HT->query($sql); return $query; } + + /** 写入商务订单操作记录 */ + public function insert_biz_order_log($coli_sn, $log_info) + { + $db_column = array( + "BOL_COLI_SN" => $coli_sn + ,"BOL_OPI_SN" => 0 + ,"BOL_OPType" => $log_info + ,"BOL_OPTime" => date('Y-m-d H:i:s') + ,"BOL_Creator" => 0 + ,"BOL_CreateTime" => date('Y-m-d H:i:s') + ); + return $this->HT->insert("BIZ_OrderOperationLog", $db_column); + } } From 5ffc136abc5cc16522b1da3be28d97e2ec635bc1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 18 Dec 2018 14:45:56 +0800 Subject: [PATCH 224/382] =?UTF-8?q?=E5=8D=95=E5=9B=A2=E8=B4=A2=E5=8A=A1?= =?UTF-8?q?=E8=A1=A8:=20=E5=A2=9E=E5=8A=A0=E4=B8=80=E4=B8=AA=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=8B=86=E5=88=86=E4=B8=BA=E5=A4=9A=E5=9C=B0PVT?= =?UTF-8?q?=E7=9A=84=E6=83=85=E5=86=B5=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 12 +-- .../controllers/order_finance.php | 83 ++++++++++++------- .../models/orderFinance_model.php | 1 + 3 files changed, 58 insertions(+), 38 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 36811535..279af95f 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -1107,13 +1107,13 @@ class TulanduoApi extends CI_Controller public function refresh_operation($coli_sn=0) { $this->load->model('OrderFinance_model', 'combine_model'); - return $this->insert_HT_order_operation($coli_sn); + // return $this->insert_HT_order_operation($coli_sn); // echo "string"; - // $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn); - // foreach ($data['combineNo_arr'] as $kcn => $vcn) { - // $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo); - // } - // $this->load->view('operation',$data); + $data['combineNo_arr'] = $this->combine_model->get_order_combineNo($coli_sn); + foreach ($data['combineNo_arr'] as $kcn => $vcn) { + $data['combineNo_arr'][$kcn]->cost = $this->combine_model->get_combine_sumMoney($vcn->GCI_combineNo); + } + $this->load->view('operation',$data); } protected function excute_curl($url, $content_builder) { diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 6c4345d6..0e3b410d 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -113,7 +113,8 @@ class Order_finance extends CI_Controller { if ($vc->GCI_groupType == 1) { // 除去只能PVT的. 避免预定接送*1+tour*1, tour拼团只有一个订单, 被视为整团pvt,漏算接送成本 $processed_code = array_diff($processed_code, $this->forbidden_combine()); - $ret->pvt = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); + $ret->pvt[] = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); + $processed_code = array_merge($processed_code, $pvt_cost->processed_code); // 多地pvt时需要区分 } else if ($vc->GCI_groupType == 2) { // 这里不排除产品编号是否已处理, 因为重复的情况比较多 $tmp_cost = $this->combine_basic($vc->GCI_combineNo, $coli_sn); @@ -127,34 +128,37 @@ class Order_finance extends CI_Controller { // pvt $report_tour_pvt = array(); if ( ! empty($ret->pvt)) { - $processed_cold_sn = array_merge($processed_cold_sn,$ret->pvt->cold_sn); - $report_tour_pvt['ordernumber'] = $ret->pvt->coli_id; - $report_tour_pvt['tourCode'] = mb_substr($ret->pvt->PAG_Code, 0, 50); - $report_tour_pvt['tourname'] = substr($ret->pvt->pag_name, 0, 200); - $report_tour_pvt['tourtime'] = $ret->pvt->startdate; - $report_tour_pvt['tourRSd'] = $ret->pvt->adult_num; - $report_tour_pvt['tourRSx'] = $ret->pvt->child_num; - $report_tour_pvt['tourCostRsd'] = $ret->pvt->person_cost; - $report_tour_pvt['tourCostRSx'] = $ret->pvt->person_cost; - $report_tour_pvt['tourcost'] = $ret->pvt->cost_sum; - $report_tour_pvt['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($ret->pvt->totalPrice); - $report_tour_pvt['tourProfit'] = ($report_tour_pvt['tourPrice']>0) ? bcsub($report_tour_pvt['tourPrice'], $report_tour_pvt['tourcost']) : 0; - $report_tour_pvt['tourProvide'] = mb_substr($ret->pvt->vendor_name, 0, 50); - $report_tour_pvt['tourBZ'] = mb_substr($ret->pvt->comment, 0, 150); - $report_tour_pvt['orderstats'] = 0; - // 成本详情 - $report_tour_pvt['RPT_Car'] = $ret->pvt->cost_category['touristCarOperations']; - $report_tour_pvt['RPT_Meal'] = $ret->pvt->cost_category['restraurantOperations']; - $report_tour_pvt['RPT_Ticket'] = $ret->pvt->cost_category['sceneryOperations']; - $report_tour_pvt['RPT_Service'] = $ret->pvt->cost_category['guiderOperations']; - $report_tour_pvt['RPT_MealGrants'] = $ret->pvt->cost_category['guide_meal']; - $report_tour_pvt['RPT_Water'] = $ret->pvt->cost_category['water']; - $report_tour_pvt['RPT_Other'] = $ret->pvt->cost_category['otherCosts']; - $report_tour_pvt['RPT_Total'] = $ret->pvt->cost_sum; - $report_tour_pvt['RPT_PersonGrade'] = $ret->pvt->person_grade; - $ret->report_tour[] = $report_tour_pvt; - // 计算订单总成本 - $report_order['basemoney'] = bcadd($report_order['basemoney'], $report_tour_pvt['tourcost']); + foreach ($ret->pvt as $kpvt => $cpvt) { + $processed_cold_sn = array_merge($processed_cold_sn,$cpvt->cold_sn); + $report_tour_pvt = array(); + $report_tour_pvt['ordernumber'] = $cpvt->coli_id; + $report_tour_pvt['tourCode'] = mb_substr($cpvt->PAG_Code, 0, 50); + $report_tour_pvt['tourname'] = substr($cpvt->pag_name, 0, 200); + $report_tour_pvt['tourtime'] = $cpvt->startdate; + $report_tour_pvt['tourRSd'] = $cpvt->adult_num; + $report_tour_pvt['tourRSx'] = $cpvt->child_num; + $report_tour_pvt['tourCostRsd'] = $cpvt->person_cost; + $report_tour_pvt['tourCostRSx'] = $cpvt->person_cost; + $report_tour_pvt['tourcost'] = $cpvt->cost_sum; + $report_tour_pvt['tourPrice'] = $this->OrderFinance_model->convert_to_RMB($cpvt->totalPrice); + $report_tour_pvt['tourProfit'] = ($report_tour_pvt['tourPrice']>0) ? bcsub($report_tour_pvt['tourPrice'], $report_tour_pvt['tourcost']) : 0; + $report_tour_pvt['tourProvide'] = mb_substr($cpvt->vendor_name, 0, 50); + $report_tour_pvt['tourBZ'] = mb_substr($cpvt->comment, 0, 150); + $report_tour_pvt['orderstats'] = 0; + // 成本详情 + $report_tour_pvt['RPT_Car'] = $cpvt->cost_category['touristCarOperations']; + $report_tour_pvt['RPT_Meal'] = $cpvt->cost_category['restraurantOperations']; + $report_tour_pvt['RPT_Ticket'] = $cpvt->cost_category['sceneryOperations']; + $report_tour_pvt['RPT_Service'] = $cpvt->cost_category['guiderOperations']; + $report_tour_pvt['RPT_MealGrants'] = $cpvt->cost_category['guide_meal']; + $report_tour_pvt['RPT_Water'] = $cpvt->cost_category['water']; + $report_tour_pvt['RPT_Other'] = $cpvt->cost_category['otherCosts']; + $report_tour_pvt['RPT_Total'] = $cpvt->cost_sum; + $report_tour_pvt['RPT_PersonGrade'] = $cpvt->person_grade; + $ret->report_tour[] = $report_tour_pvt; + // 计算订单总成本 + $report_order['basemoney'] = bcadd($report_order['basemoney'], $report_tour_pvt['tourcost']); + } } // 拼团 if ( ! empty($ret->combine_cost)) { @@ -378,10 +382,25 @@ class Order_finance extends CI_Controller { public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array()) { $ret = new stdClass(); - $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code); - if (empty($all_orders)) { + $all_orders_raw = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code); + if (empty($all_orders_raw)) { return null; } + $all_orders = $all_orders_raw; + // 取出供应商id, 有多个供应商时, 说明拆分为多个pvt + // 多地PVT + $all_vei_cnt = count(array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw))); + $ret->processed_code = array(); + if ($all_vei_cnt > 1) { + $all_vei = array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw)); + $all_orders = array(); + foreach ($all_orders_raw as $kor => $vor) { + if ($vor->COLD_PlanVEI_SN === $all_orders_raw[0]->COLD_PlanVEI_SN) { + $all_orders[] = $vor; + $ret->processed_code[] = $vor->PAG_Code; + } + } + } $ret->coli_sn = $coli_sn; $ret->coli_id = $all_orders[0]->coli_ID; $ret->cold_sn = array_unique(array_map(function($ele) {return $ele->COLD_SN;}, $all_orders)); @@ -402,7 +421,7 @@ class Order_finance extends CI_Controller { $ret->cost_category = $combine_cost->cost_category; $ret->cost_sum = $combine_cost->cost_sum; $ret->person_cost = bcdiv($ret->cost_sum, $ret->person_num); - $ret->comment = "PVT,共" . $ret->person_num . "人"; + $ret->comment = "PVT[" . $combineNo . "],共" . $ret->person_num . "人"; $pag_sns = array_values(array_unique(array_map(function($ele) {return $ele->COLD_ServiceSN;}, $all_orders))); $pags_info = $this->OrderFinance_model->get_pag_info(implode(',', $pag_sns)); $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $pags_info)))); diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 1c5d380c..01826145 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -73,6 +73,7 @@ class OrderFinance_model extends CI_Model { $sql = "SELECT gci.GCI_combineNo,gci.GCI_VendorOrderId ,COLI_SN,coli_ID--,COLI_ApplyDate,COLI_GroupCode ,COLD_SN,cold.COLD_ServiceSN--,COLD_EndDate + ,cold.COLD_PlanVEI_SN ,PAG_Code ,pag_sub.PAGS_CN_Title, cold.COLD_StartDate,PAG_DefaultVEI_SN ,COLD_PersonNum ,COLD_ChildNum , cold.COLD_StartDate,COLD_EndDate, cold.COLD_TotalPrice --,PAG_Title From 6e5e3fc8891fa71e81167b38378754720c9e3957 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 21 Dec 2018 16:04:50 +0800 Subject: [PATCH 225/382] =?UTF-8?q?=E5=9C=B0=E6=8E=A5=E6=9C=AA=E8=AE=B0?= =?UTF-8?q?=E5=9B=A2=E6=AC=BE=E7=9A=84,=20=E8=A1=A5=E5=85=85=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=3D0,=20=E9=81=BF=E5=85=8D=E6=B2=A1=E6=9C=89=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E6=97=A5=E6=9C=9F,=E5=AF=BC=E8=87=B4=E6=97=A0?= =?UTF-8?q?=E6=B3=95=E4=BF=9D=E5=AD=98=E8=B4=A2=E5=8A=A1=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/TulanduoApi.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 279af95f..50d28f5c 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -522,6 +522,10 @@ class TulanduoApi extends CI_Controller // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo); // } // } + if ( ! isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) + && ! isset($detail_jsonResp->orderDetail->travelFees) ) { + $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, 0, 0, $gai_vei_sn, $auto_text ); + } } /*BIZ_GroupCombineOperationDetail*/ if ( isset($detail_jsonResp->orderDetail->groupOrderNo) ) { From 99bc15d2aedd7fe81e5635ff4c58e0ce513465a9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 24 Dec 2018 14:28:00 +0800 Subject: [PATCH 226/382] =?UTF-8?q?APP=E7=9A=84=E8=87=AA=E5=8A=A8=E5=87=BA?= =?UTF-8?q?=E7=A5=A8=E8=AE=A2=E5=8D=95=E5=8F=B7,=20=E5=85=81=E8=AE=B8?= =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index adf0ac0b..63d44159 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -751,7 +751,12 @@ class Index extends CI_Controller { } //检测是否是APP订单,默认不处理 - if ((strpos($item->pn_memo, 'China Train Booking') !== false) || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false)) { //APP自动出票的订单不需要处理 + if ( + ( (strpos($item->pn_memo, 'China Train Booking') !== false) + || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) + ) + && empty($pn_txn_id) + ) { //APP自动出票的订单不需要处理 $this->Note_model->update_send($item->pn_txn_id, 'send'); continue; } @@ -795,7 +800,7 @@ class Index extends CI_Controller { $this->Note_model->set_invoice($item->pn_txn_id, $orderid_info->orderid . '_' . $orderid_info->ordertype); //检测是否是APP订单,默认不处理 - if ($orderid_info->ordertype == 'A') { //APP自动出票的订单不需要处理 + if ($orderid_info->ordertype == 'A' ) { //APP自动出票的订单不需要处理 $this->Note_model->update_send($item->pn_txn_id, 'send'); continue; } From 8158cab00a9f563e105cac0f5a6ec4bb845782fd Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sat, 29 Dec 2018 16:48:12 +0800 Subject: [PATCH 227/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:+=E5=8D=95?= =?UTF-8?q?=E4=B8=AA=E4=BA=A7=E5=93=81=E9=87=8D=E5=A4=8D=E6=8B=BC=E6=88=96?= =?UTF-8?q?=E6=97=A2=E6=8B=BC=E5=8F=88PVT=E7=9A=84=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 29 ++++++++++++++----- .../models/orderFinance_model.php | 8 +++++ 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 0e3b410d..52ac2aac 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -100,6 +100,7 @@ class Order_finance extends CI_Controller { $report_order['adultnumber'] = $person_num->adult_num; $report_order['childnumber'] = $person_num->child_num; $ret = new stdClass(); + $ret->pvt = array(); /** 图兰朵产品: 取拼团实际成本 */ $ret->combine_cost = array(); $ret->report_tour = array(); @@ -113,12 +114,19 @@ class Order_finance extends CI_Controller { if ($vc->GCI_groupType == 1) { // 除去只能PVT的. 避免预定接送*1+tour*1, tour拼团只有一个订单, 被视为整团pvt,漏算接送成本 $processed_code = array_diff($processed_code, $this->forbidden_combine()); - $ret->pvt[] = $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); - $processed_code = array_merge($processed_code, $pvt_cost->processed_code); // 多地pvt时需要区分 + $pvt_cost = $this->pvt_basic($vc->GCI_combineNo, $coli_sn, $processed_code); + if ($pvt_cost !== null) { + $ret->pvt[] = $pvt_cost; + } + if (isset($pvt_cost->processed_code) && $order_info->pag_cnt > 1) { // 单个产品可能重复,既拼又PVT + $processed_code = array_merge($processed_code, $pvt_cost->processed_code); // 多地pvt时需要区分 + } } else if ($vc->GCI_groupType == 2) { - // 这里不排除产品编号是否已处理, 因为重复的情况比较多 + // 这里不排除产品编号是否已处理, 因为重复的情况比较多. 如T180917-BHJ180716001M $tmp_cost = $this->combine_basic($vc->GCI_combineNo, $coli_sn); - $processed_code = array_merge($processed_code, $tmp_cost->combine_pags); + if ($order_info->pag_cnt > 1) { // 单个产品可能重复,既拼又PVT + $processed_code = array_merge($processed_code, $tmp_cost->combine_pags); + } $ret->combine_cost[] = $tmp_cost; $tmp_cost = null; } @@ -246,7 +254,7 @@ class Order_finance extends CI_Controller { * @date 2018-07-18 * @param string $combineNo */ - public function combine_basic($combineNo="", $coli_sn=0) + public function combine_basic($combineNo="", $coli_sn=0, $debug=false) { $ret = new stdClass(); $all_orders = $this->OrderFinance_model->get_all_combine_order($combineNo); @@ -370,7 +378,9 @@ class Order_finance extends CI_Controller { foreach ($ret->order_cost as $kc => $voc) { $ret->order_cost[$kc]->order_cost_sum = bcmul($voc->person_num, $ret->person_cost); } - // return $this->output->set_content_type('application/json')->set_output(json_encode($ret, JSON_UNESCAPED_UNICODE)); + if ($debug!=false) { + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } return $ret; } @@ -379,9 +389,10 @@ class Order_finance extends CI_Controller { * @example 180515061M * @date 2018-07-18 */ - public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array()) + public function pvt_basic($combineNo="", $coli_sn=0, $processed_code=array(), $debug=false) { $ret = new stdClass(); + $ret->processed_code = array(); $all_orders_raw = $this->OrderFinance_model->get_all_combine_order($combineNo, $processed_code); if (empty($all_orders_raw)) { return null; @@ -390,7 +401,6 @@ class Order_finance extends CI_Controller { // 取出供应商id, 有多个供应商时, 说明拆分为多个pvt // 多地PVT $all_vei_cnt = count(array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw))); - $ret->processed_code = array(); if ($all_vei_cnt > 1) { $all_vei = array_unique(array_map(function($ele) {return mb_strtoupper($ele->COLD_PlanVEI_SN);}, $all_orders_raw)); $all_orders = array(); @@ -427,6 +437,9 @@ class Order_finance extends CI_Controller { $ret->PAG_Code = implode(",", array_values(array_unique(array_map(function($ele) {return mb_strtoupper($ele->PAG_Code);}, $pags_info)))); $ret->vendor_name = implode(",", array_values(array_unique(array_map(function($ele) {return $ele->VEI2_CompanyBN;}, $pags_info)))) ; $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; + if ($debug!=false) { + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } return $ret; } diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 01826145..f2965b6b 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -28,6 +28,14 @@ class OrderFinance_model extends CI_Model { inner join BIZ_BookPeople on BPE_SN=BPL_BPE_SN where COLD_COLI_SN=coli.COLI_SN ) as guesttype + ,( + select COUNT(0) + from BIZ_ConfirmLineDetail + where COLD_COLI_SN=coli.COLI_SN + and isnull(DeleteFlag,0)=0 + and COLD_ServiceType='D' + and COLD_PlanVEI_SN in (1343,29188,30548,30016) + ) as pag_cnt from BIZ_ConfirmLineInfo coli inner join GRoupInfo gri on coli.COLI_GRI_SN=gri.GRI_SN and gri.DeleteFlag=0 inner join OperatorInfo opi on opi.OPI_SN=coli.COLI_OPI_ID From 8ca3999c652422822f71cc63ec6ff79d94bb3e97 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 2 Jan 2019 11:08:33 +0800 Subject: [PATCH 228/382] =?UTF-8?q?=E7=9F=AD=E4=BF=A1:=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E9=87=8D=E5=8F=91=E7=AD=96=E7=95=A5:=20=E7=AC=AC?= =?UTF-8?q?=E4=B8=80=E6=AC=A1=E5=8F=91=E9=80=81=E5=A4=B1=E8=B4=A5=E5=90=8E?= =?UTF-8?q?=E9=80=9A=E7=9F=A5=E4=BB=A5=E4=BE=BF=E4=BF=AE=E6=94=B9,?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E5=8E=9F=E5=9B=A0=E6=98=AF=E6=89=8B=E6=9C=BA?= =?UTF-8?q?=E5=8F=B7=E9=94=99=E8=AF=AF=E4=B8=94=E9=87=8D=E5=8F=91=E6=97=B6?= =?UTF-8?q?=E6=9C=AA=E5=8F=98=E6=9B=B4=E6=89=8B=E6=9C=BA=E5=8F=B7=E5=88=99?= =?UTF-8?q?=E4=B8=8D=E5=8F=91=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/send_operation.php | 67 ++++++++++++------- 1 file changed, 43 insertions(+), 24 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php index 21a70ac1..548da41e 100644 --- a/webht/third_party/trippestOrderSync/controllers/send_operation.php +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -82,6 +82,23 @@ class Send_operation extends CI_Controller { echo "已过期"; return; } + $has_send = false; + $send_history = $this->send_model->order_sms_list($order->COLI_SN); + if ( ! empty($send_history)) { + $has_send = true; + $new_number = mb_ereg_replace('[\D]', '', $order->GUT_POST) . real_phone_number($order->GUT_TEL, mb_ereg_replace('[\D]', '', $order->GUT_POST)); + $last_send = end($send_history); + $last_send_number = $last_send->TPSL_nationCode . $last_send->TPSL_mobile; + $last_send_cb = json_decode($last_send->TPSL_callbackJson); + if ($last_send_cb->result == 1016 && $new_number == $last_send_number) { + // 更新时间, 以免一直重复在这个订单 + $update_cb_db['TPSL_logTime'] = date("Y-m-d H:i:s"); + $update_where = " TPSL_SN=" . $last_send->TPSL_SN; + $ht_id = $this->send_model->update_trippest_sms_log($update_where, $update_cb_db); + echo "手机号错误且未变更"; + return; + } + } $last_update = ""; $guide_name = ""; if ($order->gcod != null) { @@ -125,31 +142,33 @@ class Send_operation extends CI_Controller { $ht_id = $this->send_model->update_trippest_sms_log($update_where, $update_cb_db); $send_cb_obj->errmsg!=="OK" ? $error_msg=$send_cb_obj->errmsg : null; } - if ($time_flag === "try1") { - return; - } - if ($guide_name == null || $error_msg !== "") { - // 没有调度或发送失败 - // to Alex - $operator_mailbody = "<p> Dear Alex: </p>" . - "<p>导游信息发送客人失败:<br /></p>" . - "<p>订单号:" . $order->COLI_ID ."</p>" . - "<p>发团时间:" . substr($order->COLD_StartDate, 0, 10) ."</p>" . - "<p>导游信息:" . $guide_name . "(" . $guide_tel . ")" ."</p>" . - "<p>导游更新时间:" . $last_update ."</p>" . - "<p>发送时间:" . $send_time ."</p>"; - if ($error_msg !== "") { - $operator_mailbody .= "<p>发送失败信息:" . $error_msg . "</p>"; + // if ($time_flag === "try1") { + // return; + // } + if ($has_send == false) { + if ($guide_name == null || $error_msg !== "") { + // 没有调度或发送失败 + // to Alex + $operator_mailbody = "<p> Dear Alex: </p>" . + "<p>导游信息发送客人失败:<br /></p>" . + "<p>订单号:" . $order->COLI_ID ."</p>" . + "<p>发团时间:" . substr($order->COLD_StartDate, 0, 10) ."</p>" . + "<p>导游信息:" . $guide_name . "(" . $guide_tel . ")" ."</p>" . + "<p>导游更新时间:" . $last_update ."</p>" . + "<p>发送时间:" . $send_time ."</p>"; + if ($error_msg !== "") { + $operator_mailbody .= "<p>发送失败信息:" . $error_msg . "</p>"; + } + $operator_mailbody .= "<p><a href='https://www.trippest.com/track-your-trip/'>Tracking Link</a>.</p>"; + $operator_mailbody .= "<p> 此邮件由系统自动发送, 请勿回复.</p>"; + $this->send_model->SendMail( + "chinahighlights", + "webform@chinahighlights.net", + "YSL", + "alex@chinahighlights.net", // ysl email alex@chinahighlights.net + '#SMS send fail# ' . $order->COLI_ID, + $operator_mailbody); } - $operator_mailbody .= "<p><a href='https://www.trippest.com/track-your-trip/'>Tracking Link</a>.</p>"; - $operator_mailbody .= "<p> 此邮件由系统自动发送, 请勿回复.</p>"; - $this->send_model->SendMail( - "chinahighlights", - "webform@chinahighlights.net", - "YSL", - "alex@chinahighlights.net", // ysl email alex@chinahighlights.net - '#SMS send fail# ' . $order->COLI_ID, - $operator_mailbody); } echo "已发送"; return; From 5c3b1bfde17cfae7bfd3b88bb009686a4d58a5f2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 3 Jan 2019 11:14:36 +0800 Subject: [PATCH 229/382] =?UTF-8?q?=E5=88=97=E8=A1=A8=E6=96=B9=E6=B3=95,?= =?UTF-8?q?=20=E8=BE=93=E5=87=BA=E6=96=B0=E5=A2=9E=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E7=9A=84id?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 50d28f5c..ec87afeb 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -125,6 +125,7 @@ class TulanduoApi extends CI_Controller $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); } $cnt = 0; + $order_id_str = ""; $pag_no_tmp = $this->pag_no_tmp(); mb_regex_encoding("UTF-8"); $unique_order = array(); @@ -172,9 +173,12 @@ class TulanduoApi extends CI_Controller if ($this->Orders_model->GCI_SN === null) { /*biz_groupcombineinfo*/ $this->insert_gci($vo); + + $order_id_str .= ", " . $vo["orderId"]; } } $output_text = "Got order list from TuLanDuo. count: " . $resp_arr["responseData"]["totalRows"] . ". Insert COLI : " . $cnt; + $output_text .= "; " . $order_id_str; log_message('error', $output_text); echo $output_text; return; @@ -522,6 +526,7 @@ class TulanduoApi extends CI_Controller // $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, $GAI_SQJE, $GAI_SSJE, $gai_vei_sn, $GAI_Memo); // } // } + // 没有收款记录, 则写入一条=0, 以免财务表无法保存 if ( ! isset($detail_jsonResp->orderDetail->operationDetails->otherReceives) && ! isset($detail_jsonResp->orderDetail->travelFees) ) { $this->insert_gai($coli_sn, $groupSN, $coli_id, $paytype, $pay_currency, 0, 0, $gai_vei_sn, $auto_text ); From e2a0ccdb7da43a6387dd2b2ccface00eadc5dc8d Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 4 Jan 2019 14:44:19 +0800 Subject: [PATCH 230/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E8=B0=83?= =?UTF-8?q?=E5=BA=A6=E6=98=8E=E7=BB=86=E8=A1=A8=E7=9A=84=E6=8B=BC=E5=9B=A2?= =?UTF-8?q?=E5=8F=B7=E5=AD=97=E6=AE=B5=E4=B8=8E=E6=8B=BC=E5=9B=A2=E8=A1=A8?= =?UTF-8?q?=E7=9A=84=E6=8B=BC=E5=9B=A2=E5=8F=B7=E5=AD=97=E6=AE=B5,?= =?UTF-8?q?=E7=BB=9F=E4=B8=80=E5=8E=BB=E9=99=A4=E4=B8=AD=E6=96=87=E7=9A=84?= =?UTF-8?q?=E7=A9=BA=E6=A0=BC;=20=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20=E9=87=8D?= =?UTF-8?q?=E6=96=B0=E7=94=9F=E6=88=90=E6=97=B6=E5=88=A0=E9=99=A4=E6=97=A7?= =?UTF-8?q?=E7=9A=84=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 86 +++++++++++++++++-- .../models/orderFinance_model.php | 10 ++- 2 files changed, 86 insertions(+), 10 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index ec87afeb..95502145 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -360,7 +360,7 @@ class TulanduoApi extends CI_Controller /** groupcombineinfo */ $this->Order_update->gci_where_update = " GCI_VendorOrderId='" . $detail_jsonResp->orderDetail->orderId . "' and GCI_VEI_SN in (" . implode(',', $this->vendor_ids) . ")"; // 不明确指定供应商id,出现过不对应的情况 $gci_update_column = array( - "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? $detail_jsonResp->orderDetail->groupOrderNo : null + "GCI_combineNo" => isset($detail_jsonResp->orderDetail->groupOrderNo) ? trim_str($detail_jsonResp->orderDetail->groupOrderNo) : null ,"GCI_VEI_SN" => $vei_SN ,"GCI_GRI_SN" => $groupSN ,"GCI_travelDate" => $detail_jsonResp->orderDetail->travelDate @@ -535,11 +535,11 @@ class TulanduoApi extends CI_Controller /*BIZ_GroupCombineOperationDetail*/ if ( isset($detail_jsonResp->orderDetail->groupOrderNo) ) { // 删除旧的录入 - $this->Orders_model->biz_groupcombineoperationdetail_cut($detail_jsonResp->orderDetail->groupOrderNo); + $this->Orders_model->biz_groupcombineoperationdetail_cut(trim_str($detail_jsonResp->orderDetail->groupOrderNo)); // 门票 if (isset($detail_jsonResp->orderDetail->operationDetails->sceneryOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->sceneryOperations as $ks => $vso) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo); $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "sceneryOperations"; $this->Orders_model->GCOD_subType = $vso->type; @@ -561,7 +561,7 @@ class TulanduoApi extends CI_Controller // 用餐 if (isset($detail_jsonResp->orderDetail->operationDetails->restraurantOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->restraurantOperations as $vro) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ; $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "restraurantOperations"; $this->Orders_model->GCOD_subType = $vro->type; @@ -582,7 +582,7 @@ class TulanduoApi extends CI_Controller // 用车 if (isset($detail_jsonResp->orderDetail->operationDetails->touristCarOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->touristCarOperations as $vco) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ; $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "touristCarOperations"; $this->Orders_model->GCOD_subType = $vco->type; @@ -603,7 +603,7 @@ class TulanduoApi extends CI_Controller // 导游服务 if (isset($detail_jsonResp->orderDetail->operationDetails->guiderOperations) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->guiderOperations as $vgo) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ; $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "guiderOperations"; $this->Orders_model->GCOD_subType = ""; @@ -624,7 +624,7 @@ class TulanduoApi extends CI_Controller // 其他支出 if (isset($detail_jsonResp->orderDetail->operationDetails->otherCosts) ) { foreach ($detail_jsonResp->orderDetail->operationDetails->otherCosts as $voc) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ; $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "otherCosts"; $this->Orders_model->GCOD_subType = $voc->type; @@ -665,7 +665,7 @@ class TulanduoApi extends CI_Controller // } if (isset($detail_jsonResp->orderDetail->operationDetails->trafficOperations)) { foreach ($detail_jsonResp->orderDetail->operationDetails->trafficOperations as $vto) { - $this->Orders_model->GCOD_GCI_combineNo = $detail_jsonResp->orderDetail->groupOrderNo ; + $this->Orders_model->GCOD_GCI_combineNo = trim_str($detail_jsonResp->orderDetail->groupOrderNo) ; $this->Orders_model->GCOD_VEI_SN = $vei_SN; $this->Orders_model->GCOD_operationType = "trafficOperations"; $this->Orders_model->GCOD_subType = $vto->birthland . " " . $vto->destination; @@ -690,6 +690,76 @@ class TulanduoApi extends CI_Controller return; } + public function order_complement() + { + // $start_date = $this->input->get_post("start_date"); + // $end_date = $this->input->get_post("end_date"); + $group_code = $this->input->get_post("group_code"); + /** + * 解析输入字段, 可能为拼团号或原始团号 + * * 拼团号: 直接解析为发团时间, 按发团时间查询列表 + * * 原始团号: 按团号查询 + */ + $start_date = NULL; $end_date = NULL; + $order_list = $this->new_order_to_ht("travel", $start_date, $end_date, $group_code); + } + + public function new_order_to_ht($date_type="travel", $start_date=NULL, $end_date=NULL, $group_code=NULL) + { + $ret = array(); + $ret['data'] = array(); + $ret['msg'] = ""; + $this->tld_order->setUserId($this->userId) + ->setKey($this->key) + ->setPageSize(50) + ->setPageIndex(1); + if ( ! empty($group_code)) { + $this->tld_order->setAgcOrderNo($group_code); + } else { + if ($date_type === "travel") { + $this->tld_order->setStartTravelDate($start_date) + ->setEndTravelDate($end_date) ; + } else { + $this->tld_order->setStartOrderDate($start_date) + ->setEndOrderDate($end_date) ; + } + } + $resp = $this->excute_curl($this->list_url, $this->tld_order); + $resp_arr = json_decode($resp, true); + if (intval($resp_arr['status']) !== 1) { + log_message('error','TulanduoApi order_list failed. Msg:' . $resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + $ret['msg'] = "failed"; + return $ret; + } + if ($resp_arr["responseData"]["totalRows"] == 0) { + $ret['msg'] = "total0"; + return $ret; + } + $all_list = $resp_arr["responseData"]["orders"]; + for($pi=2; $pi <= $resp_arr['responseData']['pageCount']; $pi++) { + $this->tld_order->setPageIndex($pi); + $f_resp = $this->excute_curl($this->list_url, $this->tld_order); + $f_resp_arr = json_decode($f_resp, true); + if ($resp_arr['status'] !== 1) { + log_message('error','TulanduoApi order_list failed. Msg:' . $f_resp_arr['errMsg'] . "; Request: " . ($this->tld_order->getBizContent())); + $ret['msg'] = "failed"; + continue; + } + $all_list = array_merge($all_list, $f_resp_arr["responseData"]["orders"]); + } + $all_vendor_order_id = array_map(function($ele){ return $ele['orderId'];}, $all_list); + $all_vendor_order_id_str = implode(',', $all_vendor_order_id); + $exists_ht = $exists_ht_order_id = null; + $exists_ht = $this->sync_model->get_exists_vendorOrderId($all_vendor_order_id_str); + $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); + $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); + if (empty($to_insert)) { + $ret['msg'] = "empty"; + } + $ret['data'] = $to_insert; + return $ret; + } + /*! * 往前获取历史数据 * @date 2018-08-21 diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index f2965b6b..3f189017 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -223,7 +223,10 @@ class OrderFinance_model extends CI_Model { { $sql = "SELECT top 10 ordernumber from report_tour where ordernumber=? "; if ($tourBz) { - $tourBz = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($tourBz, ",", true)); + $tourBz = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]$', '', strstr($tourBz, ",", true)); + if (stripos($tourBz, "pvt") === false) { + $tourBz = str_replace("]", "", $tourBz); + } $tourBz = str_replace("[", "[[]", $tourBz); $sql .= " and (tourBz like '%" . $this->HT->escape_like_str($tourBz) . "%' OR tourBz='') "; @@ -259,7 +262,10 @@ class OrderFinance_model extends CI_Model { $tourBz_tmp = ""; if ($this->report_tour_exists($vrt['ordernumber'], $vrt['tourCode'], $vrt['tourBZ']) === TRUE) { $where = " ordernumber='" . $vrt['ordernumber'] . "' "; //AND tourCode='" . $vrt['tourCode'] . "' "; - $tourBz_tmp = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]', '', strstr($vrt['tourBZ'], ",", true)); + $tourBz_tmp = mb_ereg_replace('[^a-zA-Z0-9\-\[\]]$', '', strstr($vrt['tourBZ'], ",", true)); + if (stripos($tourBz_tmp, "pvt") === false) { + $tourBz_tmp = str_replace("]", "", $tourBz_tmp); + } $tourBz_tmp = str_replace("[", "[[]", $tourBz_tmp); $where .= " AND (tourBZ like '%" . $this->HT->escape_like_str($tourBz_tmp) . "%' OR tourBZ='') "; From ae61f52b122d0f223b24e586d348dad195289b93 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 7 Jan 2019 17:15:44 +0800 Subject: [PATCH 231/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=20=E8=8E=B7?= =?UTF-8?q?=E5=8F=96=E5=9B=BE=E5=85=B0=E6=9C=B5=E4=BF=AE=E6=AD=A3=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E7=BA=BF=E8=B7=AF=E7=B1=BB=E5=9E=8B=E5=90=8E=E8=A1=A5?= =?UTF-8?q?=E5=85=85=E7=9A=84=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/TulanduoApi.php | 67 +++++++++++++++++-- 1 file changed, 61 insertions(+), 6 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 95502145..1015f5ab 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -692,20 +692,31 @@ class TulanduoApi extends CI_Controller public function order_complement() { - // $start_date = $this->input->get_post("start_date"); - // $end_date = $this->input->get_post("end_date"); + $start_date = NULL; $end_date = NULL; $group_code = $this->input->get_post("group_code"); /** * 解析输入字段, 可能为拼团号或原始团号 * * 拼团号: 直接解析为发团时间, 按发团时间查询列表 * * 原始团号: 按团号查询 */ - $start_date = NULL; $end_date = NULL; + preg_match_all('/\d{4}\-\d{1,2}\-\d{2}/i', $group_code, $matchs_arr); + if ( ! empty($matchs_arr[0])) { + $start_date = $matchs_arr[0][0]; + $end_date = $matchs_arr[0][0]; + $group_code = NULL; + } $order_list = $this->new_order_to_ht("travel", $start_date, $end_date, $group_code); + if ( ! empty($order_list['data'])) { + foreach ($order_list['data'] as $key => $order) { + $this->insert_HT_order_operation(NULL, $order); + } + } + return $this->output->set_content_type('application/json')->set_output(json_encode($order_list)); } public function new_order_to_ht($date_type="travel", $start_date=NULL, $end_date=NULL, $group_code=NULL) { + $this->load->model('Tulanduo_sync_model', 'sync_model'); $ret = array(); $ret['data'] = array(); $ret['msg'] = ""; @@ -731,8 +742,9 @@ class TulanduoApi extends CI_Controller $ret['msg'] = "failed"; return $ret; } + // return $this->tld_order->getBizContent(); if ($resp_arr["responseData"]["totalRows"] == 0) { - $ret['msg'] = "total0"; + $ret['msg'] = "notFound"; return $ret; } $all_list = $resp_arr["responseData"]["orders"]; @@ -754,9 +766,52 @@ class TulanduoApi extends CI_Controller $exists_ht_order_id = array_map(function($ele){ return intval($ele->GCI_VendorOrderId);}, $exists_ht); $to_insert = array_diff($all_vendor_order_id, $exists_ht_order_id); if (empty($to_insert)) { - $ret['msg'] = "empty"; + $ret['msg'] = "synced"; + } + foreach ($all_list as $k => $vo) { + if ( ! in_array($vo['orderId'], $to_insert)) { + continue; + } + // paypal 手续费订单没有团号 + $vo['agcOrderNo'] = (isset($vo['agcOrderNo'])&&$vo['agcOrderNo']!="") ? $vo['agcOrderNo'] : $vo['groupOrderNo']; + $vo['agcOrderNo'] = (trim_str($vo['agcOrderNo'])); // 去掉中文的全角空格 + + $this->Orders_model->BIZ_COLI_SN = null; + $this->Orders_model->GRI_SN = null; + $this->Orders_model->GCI_SN = null; + $tmpv = $this->city_info[$vo['operationDep']]['PlanVEI_SN'] ? $this->city_info[$vo['operationDep']]['PlanVEI_SN'] : 1343; + // set GCI_SN + $this->Orders_model->get_SN_by_vendorOrderId($vo['orderId'], $tmpv); // 查询订单是否已经录入过 + if ($this->Orders_model->BIZ_COLI_SN === null) { + $real_groupCode_info = analysis_groupCode($vo['agcOrderNo']); + $real_groupCode = $real_groupCode_info["cut"]; + // set BIZ_COLI_SN, GRI_SN at Orders_model + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + if (empty($group_info)) { + $real_groupCode = $real_groupCode_info["all"]; + $group_info = $this->Orders_model->get_SN_by_groupCode($real_groupCode, $vo['orderId']); + } + } + if ($this->Orders_model->GRI_SN === null) { + /** GRoupInfo */ + $this->insert_gri($vo); + } + /** insert HT */ + if ($this->Orders_model->BIZ_COLI_SN === null) { + /** BIZ_Guest */ + $this->Orders_model->GUT_LastName = $vo['customerName']; + $this->Orders_model->biz_guest_save(); + /** BIZ_ConfirmLineInfo*/ + $this->insert_coli($vo); + /** BIZ_ConfirmLineDetail*/ + $this->insert_cold($vo); + } + if ($this->Orders_model->GCI_SN === null) { + /*biz_groupcombineinfo*/ + $this->insert_gci($vo); + } } - $ret['data'] = $to_insert; + $ret['data'] = array_values($to_insert); return $ret; } From 1233e312b8b6843d75dc5fbb74efc76edb2e280e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 10 Jan 2019 16:51:47 +0800 Subject: [PATCH 232/382] =?UTF-8?q?fixed=20=E8=B4=A2=E5=8A=A1=E8=A1=A8?= =?UTF-8?q?=E5=A4=9A=E5=9C=B0=E5=8D=95=E4=BA=A7=E5=93=81=E6=8B=BC=E5=9B=A2?= =?UTF-8?q?=E9=9D=9EPVT=E6=97=B6=E4=BA=A7=E5=93=81=E6=88=90=E6=9C=AC?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E9=87=8D=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/models/orderFinance_model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index 3f189017..c8d67668 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -89,7 +89,7 @@ class OrderFinance_model extends CI_Model { from GroupCombineInfo gci inner join BIZ_ConfirmLineInfo coli on gci.GCI_GRI_SN=COLI_GRI_SN and coli.COLI_State NOT IN (30,40,50) inner join BIZ_ConfirmLineDetail cold on cold.COLD_COLI_SN=coli.COLI_SN - and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 and COLD_PlanVEI_SN in (1343,29188,30548,30016) + and cold.COLD_ServiceType='D' and cold.DeleteFlag=0 and COLD_PlanVEI_SN = GCI_VEI_SN left join BIZ_PackageInfo pag on PAG_SN=COLD_ServiceSN left join BIZ_PackageInfoSub pag_sub on pag_sub.PAGS_SN=COLD_ServiceSN2 where gci.GCI_combineNo =? From 65172fa43fe7cfb3244567aed83dc97fc9b86fc4 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 10 Jan 2019 18:04:48 +0800 Subject: [PATCH 233/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8:=20?= =?UTF-8?q?=E4=BA=A7=E5=93=81=E5=A4=87=E6=B3=A8=E5=A2=9E=E5=8A=A0=E6=8A=A5?= =?UTF-8?q?=E4=BB=B7/=E5=9B=A2=E6=AC=BE(RMB)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 22 +++++++++++++++++++ .../models/orderFinance_model.php | 7 ++++-- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 52ac2aac..3fd1717e 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -262,6 +262,16 @@ class Order_finance extends CI_Controller { return null; } $ret->coli_sn = $coli_sn; + $payment_currency = "USD"; + $currency_rate = 1; + $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn, TRUE); + foreach ($order_payment as $kp => $vp) { + if ($vp->GAI_SQJE > 0) { + $payment_currency = trim($vp->GAI_SQJECurrency); + $currency_rate = bcdiv($vp->GAI_SSJE, $vp->GAI_SQJE); + break; + } + } $all_pags = array_map(function($ele){ return mb_strtoupper($ele->PAG_Code);}, $all_orders); $all_pag = array_unique($all_pags); $combine_pag_arr = array(); @@ -337,6 +347,7 @@ class Order_finance extends CI_Controller { $ret->person_num = 0; $ret->PAG_Code = ""; $ret->order_cost = array(); + $ret->totalPrice_RMB = 0; $pag_sns = array(); $unique_coli = array(); foreach ($all_orders as $ko => $vo) { @@ -363,6 +374,16 @@ class Order_finance extends CI_Controller { $ret->order_cost[] = $tour_s; $ret->coli_id = $vo->coli_ID; } + // 预定产品的团款转换人民币, 写入财务表产品的备注 + // 补充的产品不算 + if ( ! isset($vo->real_pag_sn) && $vo->COLI_SN == $coli_sn) { + $vo->COLD_TotalPrice = $vo->COLD_TotalPrice===NULL ? 0 : $vo->COLD_TotalPrice; + if ($payment_currency == "USD" ) { + $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, bcmul($vo->COLD_TotalPrice, $currency_rate)); + } else { + $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, $this->OrderFinance_model->convert_to_RMB($vo->COLD_TotalPrice, 'USD')); + } + } } } $this_order_real_pag_sns = array_map(function($ele) {return $ele->real_pag_sn;}, $ret->order_cost); @@ -371,6 +392,7 @@ class Order_finance extends CI_Controller { $ret->pag_name = implode(";\r\n", array_map(function($ele) {return $ele->PAG_Title;}, $pags_info)) ; $ret->PAG_Code = implode(",", $ret->combine_pags); $ret->comment = "拼团" . $combineNo . ", 按" . $ret->person_num . "人等"; + $ret->comment .= $ret->totalPrice_RMB>0 ? (", 报价RMB " . $ret->totalPrice_RMB) : ""; $combine_cost = $this->OrderFinance_model->get_combine_sumMoney($combineNo); $ret->cost_category = $combine_cost->cost_category; $ret->cost_sum = $combine_cost->cost_sum; diff --git a/webht/third_party/trippestOrderSync/models/orderFinance_model.php b/webht/third_party/trippestOrderSync/models/orderFinance_model.php index c8d67668..e1ddd1e7 100644 --- a/webht/third_party/trippestOrderSync/models/orderFinance_model.php +++ b/webht/third_party/trippestOrderSync/models/orderFinance_model.php @@ -190,13 +190,16 @@ class OrderFinance_model extends CI_Model { return $this->HT->query($sql)->result(); } - public function get_order_payment($coli_sn=0) + public function get_order_payment($coli_sn=0, $detail=false) { $ret = new stdClass(); - $sql = "SELECT gai.GAI_SSDate,gai.GAI_SSJE,gai.GAI_Type + $sql = "SELECT gai.GAI_SSDate,gai.GAI_SQJE,gai.GAI_SSJE,gai.GAI_Type,gai.GAI_SQJECurrency from BIZ_GroupAccountInfo gai where gai.GAI_COLI_SN=$coli_sn and gai.DeleteFlag=0"; $payment = $this->HT->query($sql)->result(); + if ($detail === TRUE) { + return $payment; + } $ret->SSmoney = 0; $ret->patDate = ""; $ret->payType = ""; From 23b5243652b10983841b3cb78c502615f543dfc2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 11 Jan 2019 14:40:43 +0800 Subject: [PATCH 234/382] =?UTF-8?q?=E7=94=9F=E6=88=90=E8=B4=A2=E5=8A=A1?= =?UTF-8?q?=E8=A1=A8:=20=E6=89=B9=E9=87=8F=E5=92=8C=E5=8D=95=E4=B8=AA?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E5=88=86=E5=BC=80=E8=B0=83=E7=94=A8,=20?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E9=87=8D=E6=96=B0=E7=94=9F=E6=88=90=E6=97=B6?= =?UTF-8?q?=E5=8F=96=E6=9C=80=E6=96=B0=E7=9A=84=E6=88=90=E6=9C=AC=E6=98=8E?= =?UTF-8?q?=E7=BB=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/order_finance.php | 84 ++++++++++++------- 1 file changed, 52 insertions(+), 32 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 3fd1717e..508e73c3 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -32,6 +32,9 @@ class Order_finance extends CI_Controller { } + // 重新生成账单 + // HT批量按钮调用 + // 仅读取成本信息计算 public function single_order_report($coli_sn=0) { $order_info = $this->OrderFinance_model->get_order_info($coli_sn); @@ -45,6 +48,18 @@ class Order_finance extends CI_Controller { return $this->generate_report($order_info); } + // 重新生成账单 + // HT单团财务表页面调用, 先刷新一次成本 + public function single_order_report_refresh($coli_sn=0) + { + // 刷新成本 + $controller_name = "TulanduoApi"; + require_once($controller_name . '.php'); + $vendor_class = new $controller_name(); + $ret = $vendor_class->insert_HT_order_operation($coli_sn); + $this->single_order_report($coli_sn); + } + /*! * 单团财务表计算 * @date 2018-07-18 @@ -261,15 +276,17 @@ class Order_finance extends CI_Controller { if (empty($all_orders)) { return null; } - $ret->coli_sn = $coli_sn; - $payment_currency = "USD"; - $currency_rate = 1; - $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn, TRUE); - foreach ($order_payment as $kp => $vp) { - if ($vp->GAI_SQJE > 0) { - $payment_currency = trim($vp->GAI_SQJECurrency); - $currency_rate = bcdiv($vp->GAI_SSJE, $vp->GAI_SQJE); - break; + if ($coli_sn !== NULL) { + $ret->coli_sn = $coli_sn; + $payment_currency = "USD"; + $currency_rate = 1; + $order_payment = $this->OrderFinance_model->get_order_payment($coli_sn, TRUE); + foreach ($order_payment as $kp => $vp) { + if ($vp->GAI_SQJE > 0) { + $payment_currency = trim($vp->GAI_SQJECurrency); + $currency_rate = bcdiv($vp->GAI_SSJE, $vp->GAI_SQJE); + break; + } } } $all_pags = array_map(function($ele){ return mb_strtoupper($ele->PAG_Code);}, $all_orders); @@ -355,33 +372,36 @@ class Order_finance extends CI_Controller { $pag_sns[] = $vo->COLD_ServiceSN; // 整团单拼时, 避免重复计算人数 // 订单人数不重复计 + // 总人等 if ( ! in_array(mb_strtoupper($vo->PAG_Code), $pvt_code) && ! in_array($vo->COLI_SN, $unique_coli)) { $unique_coli[] = $vo->COLI_SN; $ret->person_num += $vo->COLD_PersonNum + $vo->COLD_ChildNum; } $ret->startdate = $vo->COLD_StartDate; - $tour_s = new stdClass(); - if ($vo->COLI_SN == $coli_sn) { - $tour_s->COLD_SN = $vo->COLD_SN; - $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; - $tour_s->adult_num = $vo->COLD_PersonNum; - $tour_s->child_num = $vo->COLD_ChildNum; - $tour_s->PAG_code = mb_strtoupper($vo->PAG_Code); - // $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; - $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : mb_strtoupper($vo->PAG_Code); - $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; - $tour_s->totalPrice = $vo->COLD_TotalPrice; - $ret->order_cost[] = $tour_s; - $ret->coli_id = $vo->coli_ID; - } - // 预定产品的团款转换人民币, 写入财务表产品的备注 - // 补充的产品不算 - if ( ! isset($vo->real_pag_sn) && $vo->COLI_SN == $coli_sn) { - $vo->COLD_TotalPrice = $vo->COLD_TotalPrice===NULL ? 0 : $vo->COLD_TotalPrice; - if ($payment_currency == "USD" ) { - $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, bcmul($vo->COLD_TotalPrice, $currency_rate)); - } else { - $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, $this->OrderFinance_model->convert_to_RMB($vo->COLD_TotalPrice, 'USD')); + if ($coli_sn !== NULL) { + $tour_s = new stdClass(); + if ($vo->COLI_SN == $coli_sn) { + $tour_s->COLD_SN = $vo->COLD_SN; + $tour_s->person_num = $vo->COLD_PersonNum + $vo->COLD_ChildNum; + $tour_s->adult_num = $vo->COLD_PersonNum; + $tour_s->child_num = $vo->COLD_ChildNum; + $tour_s->PAG_code = mb_strtoupper($vo->PAG_Code); + // $tour_s->real_code = isset($vo->real_code) ? $vo->real_code : $vo->PAG_Code; + $tour_s->real_code = isset($vo->real_code)&&in_array($vo->real_code, $ret->combine_pags) ? $vo->real_code : mb_strtoupper($vo->PAG_Code); + $tour_s->real_pag_sn = isset($vo->real_pag_sn) ? $vo->real_pag_sn : $vo->COLD_ServiceSN; + $tour_s->totalPrice = $vo->COLD_TotalPrice; + $ret->order_cost[] = $tour_s; + $ret->coli_id = $vo->coli_ID; + } + // 预定产品的团款转换人民币, 写入财务表产品的备注 + // 补充的产品不算 + if ( ! isset($vo->real_pag_sn) && $vo->COLI_SN == $coli_sn) { + $vo->COLD_TotalPrice = $vo->COLD_TotalPrice===NULL ? 0 : $vo->COLD_TotalPrice; + if ($payment_currency == "USD" ) { + $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, bcmul($vo->COLD_TotalPrice, $currency_rate)); + } else { + $ret->totalPrice_RMB = bcadd($ret->totalPrice_RMB, $this->OrderFinance_model->convert_to_RMB($vo->COLD_TotalPrice, 'USD')); + } } } } @@ -515,7 +535,7 @@ class Order_finance extends CI_Controller { { return array( "BJALC-209", - "BJSIC-16", + // "BJSIC-16", "SHSIC-45", "XASIC-16" ); From 5852cd8aa42c5a87340dabf710f1f48603d85501 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 11 Jan 2019 16:38:14 +0800 Subject: [PATCH 235/382] =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=88=90=E6=9C=AC,=20=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E6=89=8B=E5=8A=A8=E5=88=B7=E6=96=B0=E6=95=B0=E6=8D=AE.=20?= =?UTF-8?q?=E5=9C=A8=E8=B4=A2=E5=8A=A1=E8=A1=A8=E4=B8=AD=E9=87=8D=E6=96=B0?= =?UTF-8?q?=E7=94=9F=E6=88=90=E5=8F=AF=E5=86=8D=E6=AC=A1=E5=88=B7=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/models/orders_model.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 4c11c095..5b7bf210 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -175,7 +175,9 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo_finance() { - return array(); // 历史数据已获取完毕, 财务数据的获取方法待定 2018-11-30 + // return array(); // 历史数据已获取完毕 + $to_update_cost_date = date("Y-M-d", strtotime("-7 days")); + $last_update_time = date("Y-m-d 00:00:00"); $sql = " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' from GroupCombineInfo gci @@ -186,8 +188,12 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') -and GCI_travelDate between '2018-08-01' and '2018-08-31 23:59:59' -and gci.GCI_createTime < '2018-12-06 14:00:00' + -- 7天前的订单 + and gci.gci_leaveDate = '$to_update_cost_date' + -- 今天更新一次 + and gci.GCI_createTime < '$last_update_time' +-- and GCI_travelDate between '2018-08-01' and '2018-08-31 23:59:59' +-- and gci.GCI_createTime < '2018-12-06 14:00:00' and GCI_combineNo not like '%取消%' "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; From b9a07068d2de5d9dc5d534f463bf6e331d4d375a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 14 Jan 2019 11:31:50 +0800 Subject: [PATCH 236/382] =?UTF-8?q?=E8=87=AA=E5=8A=A8=E6=9B=B4=E6=96=B0?= =?UTF-8?q?=E6=88=90=E6=9C=AC:=20=E6=94=B9=E4=B8=BA45=E5=A4=A9=E5=89=8D,?= =?UTF-8?q?=E5=B7=B2=E4=BF=9D=E5=AD=98=E8=B4=A6=E5=8D=95=E7=9A=84=E6=8E=92?= =?UTF-8?q?=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/models/orders_model.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index 5b7bf210..decb3435 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -176,7 +176,7 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo_finance() { // return array(); // 历史数据已获取完毕 - $to_update_cost_date = date("Y-M-d", strtotime("-7 days")); + $to_update_cost_date = date("Y-m-d", strtotime("-45 days")); $last_update_time = date("Y-m-d 00:00:00"); $sql = " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' @@ -188,10 +188,14 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - -- 7天前的订单 + -- 45天前的订单 and gci.gci_leaveDate = '$to_update_cost_date' -- 今天更新一次 and gci.GCI_createTime < '$last_update_time' + -- 已生成账单的不再自动同步 + and NOT exists ( + select 1 from report_order where ordernumber=COLI_ID and orderstats=1 + ) -- and GCI_travelDate between '2018-08-01' and '2018-08-31 23:59:59' -- and gci.GCI_createTime < '2018-12-06 14:00:00' and GCI_combineNo not like '%取消%' From 6703a19d7c4a6ef7fbbcbdbc9ae34f8f8a960867 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 18 Jan 2019 13:47:07 +0800 Subject: [PATCH 237/382] =?UTF-8?q?ipaylinks=20APP=E7=BB=84=E7=9A=84?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E6=94=B6=E5=88=B0=E6=8E=A8=E9=80=81=E4=B9=9F?= =?UTF-8?q?=E4=B8=80=E6=A0=B7=E5=BD=95=E5=85=A5.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index e3e7ebeb..685a5a42 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -428,10 +428,10 @@ class IPayLinksService extends CI_Controller $this->Note_model->set_invoice($item->IPL_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype); //检测是否是APP订单,默认不处理 - if ($orderid_info->ordertype == 'A') { //APP自动出票的订单不需要处理 - $this->Note_model->update_send($item->IPL_dealId, 'send'); - continue; - } + // if ($orderid_info->ordertype == 'A') { //APP自动出票的订单不需要处理 + // $this->Note_model->update_send($item->IPL_dealId, 'send'); + // continue; + // } //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { @@ -459,11 +459,11 @@ class IPayLinksService extends CI_Controller $item->IPL_payerEmail, $item->IPL_dealId, $ht_memo); - // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { - // //只修改APP组的订单状态,并且订单进度是我的订单 - // $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 - // $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); - // } + if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { + //只修改APP组的订单状态,并且订单进度是我的订单 + $this->IPayLinks_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); + } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) { From 9a60bfd96aa0b56af61777622d812fc9d1f5c245 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 30 Jan 2019 15:11:58 +0800 Subject: [PATCH 238/382] =?UTF-8?q?=E6=B3=A8=E9=87=8A;=E5=BE=85=E8=A7=A3?= =?UTF-8?q?=E5=86=B3:=E5=9B=BE=E5=85=B0=E6=9C=B5=E5=8F=96=E6=B6=88?= =?UTF-8?q?=E6=9C=AA=E9=80=80=E6=AC=BE=E5=9B=A2=E7=9A=84=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/order_finance.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 508e73c3..e49ba595 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -229,7 +229,10 @@ class Order_finance extends CI_Controller { if ( ! empty($ret->report_tour)) { $this->OrderFinance_model->insert_report_tour_tulanduo($ret->report_tour); } - /** 非图兰朵供应商的包价线路产品 */ + /** + * 非图兰朵供应商的包价线路产品 + * 是图兰朵供应商, 但已取消且未退款 + */ $other_tour = $this->OrderFinance_model->get_order_detail($coli_sn, 'D', false); if ( ! empty($other_tour) || empty($ret->processed_cold_sn)) { $ret->others = $this->OrderFinance_model->insert_report_tour_others($coli_sn); From d53d6fc45b6525315384a4666a2cac6602ff4949 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 30 Jan 2019 17:00:29 +0800 Subject: [PATCH 239/382] =?UTF-8?q?=E6=B3=A8=E9=87=8A;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/order_finance.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index e49ba595..1afd6f89 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -119,7 +119,7 @@ class Order_finance extends CI_Controller { /** 图兰朵产品: 取拼团实际成本 */ $ret->combine_cost = array(); $ret->report_tour = array(); - $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); + $combineNo_arr = $this->OrderFinance_model->get_order_combineNo($coli_sn); // 拼团,PVT按顺序处理 $group_type_arr = array_unique(array_map(function($ele){return $ele->GCI_groupType;}, $combineNo_arr)); $processed_code = array(); // 已处理的产品编号 foreach ($combineNo_arr as $kc => $vc) { From d97c5552c0b389bfeeee69bf0130663cf1af0897 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 31 Jan 2019 14:28:31 +0800 Subject: [PATCH 240/382] =?UTF-8?q?Alipay=20=E5=A2=9E=E5=8A=A0=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E5=AE=9D=E9=80=80=E6=AC=BE=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 64 +++++++++++++------ 1 file changed, 45 insertions(+), 19 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index fe8190b5..7e117de7 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -99,29 +99,55 @@ class AlipayTradeService extends CI_Controller echo "failed"; return; } - if (true === $this->if_note_exists($asyns_resp->data->trade_no)) { + if ( isset($asyns_resp->data->refund_fee) && true === $this->if_note_exists($asyns_resp->data->out_biz_no) ) { + echo "success"; + return; + } else if ( ! isset($asyns_resp->data->refund_fee) && true === $this->if_note_exists($asyns_resp->data->trade_no)) { echo "success"; return; } + $notify_type = "pay"; + if (isset($asyns_resp->data->refund_fee)) { + $notify_type = "refund"; + } $code = isset($asyns_resp->data->code) ? strval($asyns_resp->data->code) : NULL ; $buyer = isset($asyns_resp->data->buyer_logon_id) ? strval($asyns_resp->data->buyer_logon_id) : NULL ; - if (strcmp(strval($asyns_resp->data->trade_status), "TRADE_SUCCESS") == 0) { - $this->Alipay_note_model->save_alipay( - strval($asyns_resp->data->trade_no) - ,strval($asyns_resp->data->out_trade_no) - ,"CNY" - ,strval($asyns_resp->data->total_amount) - ,NULL - ,NULL - ,strval($asyns_resp->data->gmt_create) - ,strval($asyns_resp->data->gmt_payment) - ,json_encode($asyns_resp->data) - ,strval("pay") - ,$code - ,strval($asyns_resp->data->trade_status) - ,NULL - ,$buyer - ); + if (strcmp(trim(strval($asyns_resp->data->trade_status)), "TRADE_SUCCESS") == 0) { + if ($notify_type === "pay") { + $this->Alipay_note_model->save_alipay( + strval($asyns_resp->data->trade_no) + ,strval($asyns_resp->data->out_trade_no) + ,"CNY" + ,strval($asyns_resp->data->total_amount) + ,NULL + ,NULL + ,strval($asyns_resp->data->gmt_create) + ,strval($asyns_resp->data->gmt_payment) + ,json_encode($asyns_resp->data) + ,$notify_type + ,$code + ,strval($asyns_resp->data->trade_status) + ,NULL + ,$buyer + ); + } else if ($notify_type == "refund") { + $this->Alipay_note_model->save_alipay( + strval($asyns_resp->data->out_biz_no) + ,strval($asyns_resp->data->out_trade_no) + ,"CNY" + ,"-" . strval($asyns_resp->data->refund_fee) + ,NULL + ,NULL + ,strval($asyns_resp->data->gmt_refund) + ,strval($asyns_resp->data->notify_time) + ,json_encode($asyns_resp->data) + ,$notify_type + ,$code + ,strval($asyns_resp->data->trade_status) + ,NULL + ,$buyer + ); + } // 查询payer // $this->AlipayTradeQueryContentBuilder->setTradeNo($asyns_resp->data->trade_no); // if ($asyns_resp->data->out_trade_no) { @@ -325,7 +351,7 @@ class AlipayTradeService extends CI_Controller } //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 - if ($item->ALI_payType == 'Refunded') { + if ($item->ALI_payType == 'refund') { $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); continue; } From 42060e66662f6a73bc7a26ca099f91508822aae6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 31 Jan 2019 16:37:37 +0800 Subject: [PATCH 241/382] =?UTF-8?q?ipaylinks=20=E9=80=80=E6=AC=BE=E6=8E=A8?= =?UTF-8?q?=E9=80=81=E4=B8=8D=E6=9F=A5=E8=AF=A2stateCode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 685a5a42..f1f5bff1 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -724,7 +724,9 @@ class IPayLinksService extends CI_Controller ,strval($payer_name) ,strval($payer_email) ); - $query = $this->query_pay_result($asyns_resp->data); + if (strval($asyns_resp->data->resultCode) === "0000") { + $query = $this->query_pay_result($asyns_resp->data); + } // } // 返回状态码200 return; From a5e47bc21ea6f1fea2acddc7c756bf8ff675af16 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 1 Feb 2019 14:13:28 +0800 Subject: [PATCH 242/382] =?UTF-8?q?Alipay=20=E6=8E=A8=E9=80=81=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=8F=AA=E8=83=BD=E8=BE=93=E5=87=BA=E6=8C=87=E5=AE=9A?= =?UTF-8?q?=E5=AD=97=E7=AC=A6=E4=B8=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 7e117de7..26021d00 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -92,6 +92,7 @@ class AlipayTradeService extends CI_Controller */ public function alipay_notice() { + error_reporting(0); $resp_arr = $this->input->post(); $asyns_resp = $this->check($resp_arr); // 未得到结果 From 586e56b5a8027402079a3d1c0edc1057c037b79c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 20 Feb 2019 11:03:31 +0800 Subject: [PATCH 243/382] =?UTF-8?q?Alipay=20=E8=AE=A1=E7=AE=97=E5=AE=9E?= =?UTF-8?q?=E6=94=B6=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 3 ++ webht/third_party/pay/models/Alipay_model.php | 28 ++++++++++++++++--- 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 26021d00..431ea289 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -400,6 +400,7 @@ class AlipayTradeService extends CI_Controller //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->ALI_currencyCode))); + $ssje = $this->Alipay_model->get_ssje($item->ALI_orderAmount, $currencyCode); $USD_amount = $this->Alipay_model->get_USD($item->ALI_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { @@ -426,6 +427,7 @@ class AlipayTradeService extends CI_Controller $item->ALI_completeTime, $currencyCode, $USD_amount, + $ssje, $item->ALI_completeTime, $item->ALI_completeTime, $item->ALI_acquiringTime, @@ -447,6 +449,7 @@ class AlipayTradeService extends CI_Controller $item->ALI_orderAmount, $item->ALI_acquiringTime, $currencyCode, + $ssje, $item->ALI_completeTime, $item->ALI_completeTime, $item->ALI_acquiringTime, diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 1d17f7c0..1019bdf1 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -180,7 +180,7 @@ class Alipay_model extends CI_Model { } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -197,6 +197,7 @@ class Alipay_model extends CI_Model { ,GAI_SQDate ,GAI_SQJECurrency ,GAI_Money + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -207,13 +208,13 @@ class Alipay_model extends CI_Model { ,GAI_State ,DeleteFlag ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } //添加收款记录(传统订单) - public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_tour_account_info($GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -228,6 +229,7 @@ class Alipay_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -238,7 +240,7 @@ class Alipay_model extends CI_Model { ,GAI_State ,DeleteFlag ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $insertid; } @@ -347,4 +349,22 @@ class Alipay_model extends CI_Model { ); return $this->HT->insert("BIZ_OrderOperationLog", $db_column); } + + /*! + * 调用数据库函数,生成实收金额 + * @author LYT <lyt@hainatravel.com> + * @date 2017-11-03 + * @param decimal(18,3) $amount + * @param varchar(6) $currency + */ + public function get_ssje($amount, $currency='RMB', $code='15015') + { + $sql = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje"; + $query = $this->HT->query($sql,array($code, $currency, $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } } From d08b32a8d5303767fd1f17140d1d08ec76765578 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 21 Feb 2019 09:30:13 +0800 Subject: [PATCH 244/382] =?UTF-8?q?Alipay=20=E5=AE=9E=E6=94=B6=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Alipay_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 1019bdf1..03e7977f 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -207,7 +207,7 @@ class Alipay_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; @@ -239,7 +239,7 @@ class Alipay_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $insertid; From c8f0abfc6cea53d8eca2cdfb6e95178d9433a0c3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 27 Feb 2019 15:45:35 +0800 Subject: [PATCH 245/382] =?UTF-8?q?paypal=20=E5=AF=BC=E5=87=BA=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95:=E5=A2=9E=E5=8A=A0=E8=AE=B0?= =?UTF-8?q?=E4=BD=8F=E6=AF=8F=E6=AC=A1=E5=AF=BC=E5=87=BA=E7=9A=84=E6=9C=80?= =?UTF-8?q?=E5=90=8E=E4=B8=80=E6=9D=A1,=E6=8C=87=E5=AE=9A=E6=80=BB?= =?UTF-8?q?=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 99 ++++++++++++-- .../third_party/paypal/models/note_model.php | 26 +++- webht/third_party/paypal/views/note_list.php | 121 ++++++++++++++---- 3 files changed, 207 insertions(+), 39 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 63d44159..d2adc6f4 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -907,6 +907,11 @@ class Index extends CI_Controller { $data['notelist'] = $this->Note_model->search_date($data['date']); } + /** + * 导出记录用的记录节点 + */ + $data['record_flags'] = $this->Note_model->list_export_record(); + $this->load->view('n-header', $data); $this->load->view('note_list'); $this->load->view('n-footer'); @@ -989,11 +994,80 @@ class Index extends CI_Controller { $from_date = $this->input->post("from_date"); $to_date = $this->input->post("to_date"); $currency = $this->input->post("currency"); - $export_list = $this->Note_model->date_range($from_date, $to_date, $currency); + $amount = $this->input->post("set_amount"); + $last_record = $this->input->post("date_history"); + if (empty($amount)) { + $export_list = $this->Note_model->date_range($from_date, $to_date, $currency); + } else { + $allmost_day = intval(ceil($amount/10000)); + if ( ! in_array($currency, array('CNY','USD'))) { + $allmost_day = 30; + } + $last_sn = null; + if ( ! empty($last_record)) { + $last_sn = strstr($last_record, '@', TRUE); + $from_date = substr(strstr($last_record, '@'),1); + } + $all_list = $this->target_amount_recursive($currency, $amount, 0, $from_date, $allmost_day, array(), $last_sn); + $export_list = $all_list['list']; + } if ($export_list == false) { echo "Not found any records for export."; return false; } + // 记录这次导出的最后一条 + if (isset($all_list['last_flag']) && ! empty($all_list['last_flag'])) { + $insert_db = array( + "TEL_transactionType" => 15002 + ,"TEL_transactionNoticeId" => $all_list['last_flag']->pn_sn + ,"TEL_transactionId" => $all_list['last_flag']->pn_txn_id + ,"TEL_transactionDate" => $all_list['last_flag']->pn_datetime + ,"TEL_transactionAmount" => $all_list['last_flag']->pn_mc_gross + ,"TEL_transactionCurrency" => $all_list['last_flag']->pn_mc_currency + ,"TEL_orderId" => $all_list['last_flag']->pn_invoice + ,"TEL_exportAmount" => $all_list['last_flag']->pn_mc_gross + ,"TEL_exportDate" => date('Y-m-d H:i:s') + ); + $this->Note_model->export_record($insert_db); + } + + $this->save_excel($export_list); + } + + /*! + * 递归查询收款记录, 直到总金额>=目标总金额 + * @date 2019-02-27 + */ + public function target_amount_recursive($currency, $target_amount, $now_amount, $from_date,$days=10,$list=array(), $last_sn=null, $last_flag=null) + { + $to_date = date('Y-m-d', strtotime("+$days days", strtotime($from_date))); + $former_list = $this->Note_model->date_range($from_date, $to_date, $currency, $last_sn); + $list_index = 0; + $last_sn = $last_sn===null ? 0 : $last_sn; + $last_flag = $last_flag===null ? null : $last_flag; + while ($now_amount < $target_amount && isset($former_list[$list_index])) { + $list[] = $former_list[$list_index]; + $now_amount = bcadd($now_amount, $former_list[$list_index]->pn_mc_gross); + $last_sn = $former_list[$list_index]->pn_sn; + $last_flag = $former_list[$list_index]; + $list_index++; + } + $ret = array( + "last_flag" => $last_flag, + "list" => $list + ); + if (empty($former_list)) { + return $ret; + } + if ($now_amount < $target_amount) { + return $this->target_amount_recursive($currency, $target_amount, $now_amount, $to_date, 10, $list, $last_sn, $last_flag); + } else { + return $ret; + } + } + + public function save_excel($export_list) + { $this->load->library('PHPExcel'); $objPHPExcel = new PHPExcel(); $objPHPExcel->setActiveSheetIndex(0); @@ -1005,18 +1079,21 @@ class Index extends CI_Controller { $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30); $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20); $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); + $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20); // 对齐 $objPHPExcel->getActiveSheet()->getStyle('B')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); $objPHPExcel->getActiveSheet()->getStyle('C')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); // 表标题行 $objPHPExcel->getActiveSheet() ->SetCellValue('A1', '#') ->SetCellValue('B1', '团号') ->SetCellValue('C1', '金额') - ->SetCellValue('D1', '付款人') - ->SetCellValue('E1', '付款人邮箱') - ->SetCellValue('F1', '交易号') - ->SetCellValue('G1', '收单时间'); + ->SetCellValue('D1', '币种') + ->SetCellValue('E1', '付款人') + ->SetCellValue('F1', '付款人邮箱') + ->SetCellValue('G1', '交易号') + ->SetCellValue('H1', '收单时间'); $currency_sum = array(); bcscale(2); $rowCount = 2; @@ -1028,12 +1105,14 @@ class Index extends CI_Controller { $orderid = $row->pn_invoice ? $row->pn_invoice : $row->pn_item_number; $objPHPExcel->getActiveSheet() ->SetCellValue('A'.$rowCount, ($rowCount-1)) + // ->SetCellValue('A'.$rowCount, $row->pn_sn) ->setCellValueExplicit('B'.$rowCount, $orderid,PHPExcel_Cell_DataType::TYPE_STRING) - ->setCellValueExplicit('C'.$rowCount, trim($row->pn_mc_currency) . number_format($row->pn_mc_gross, 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('D'.$rowCount, $row->pn_payer) - ->SetCellValue('E'.$rowCount, $row->pn_payer_email) - ->setCellValueExplicit('F'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING) - ->SetCellValue('G'.$rowCount, $row->pn_datetime); + ->setCellValue('C'.$rowCount, number_format($row->pn_mc_gross, 2, ".", "")) + ->setCellValueExplicit('D'.$rowCount, trim($row->pn_mc_currency) ,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('E'.$rowCount, $row->pn_payer) + ->SetCellValue('F'.$rowCount, $row->pn_payer_email) + ->setCellValueExplicit('G'.$rowCount, $row->pn_txn_id,PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('H'.$rowCount, $row->pn_datetime); $payer = $orderid = ""; $rowCount++; } diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index 8aff1673..04938ef1 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -153,7 +153,7 @@ class Note_model extends CI_Model { return $this->HT->query($sql, array($pn_invoice, $pn_txn_id)); } - public function date_range($from, $to, $currency=NULL) + public function date_range($from, $to, $currency=NULL, $pn_sn=NULL) { $this->init(); $search_sql = " AND pn_payment_status in ('Completed','Refunded') "; @@ -161,9 +161,31 @@ class Note_model extends CI_Model { if ( ! empty($currency)) { $search_sql .= " AND pn_mc_currency = '$currency' "; } + if ( ! empty($pn_sn)) { + $search_sql .= " AND pn_sn > $pn_sn "; + } $this->search = $search_sql; - $this->orderby = ""; + $this->orderby = " order by pn.pn_sn asc"; return $this->get_list(); } + + /** + * export note + */ + public function export_record($db) + { + $this->info = $this->load->database('INFO', TRUE); + $this->info->insert('Transaction_Export_Log', $db); + } + + public function list_export_record() + { + $this->info = $this->load->database('INFO', TRUE); + $sql = "SELECT TOP 10 * + FROM [InfoManager].[dbo].[Transaction_Export_Log] + order by TEL_SN desc"; + return $this->info->query($sql)->result(); + } + } diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index ba5903c4..daf4266a 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -1,6 +1,7 @@ <link href="http://www.mycht.cn/min?f=/css/destination.css" rel="stylesheet"> <script type="text/javascript"> $(document).ready(function() { + // $('.trigger_export_btn').trigger('click');// test $('#datepicker').datepicker({ defaultDate: '<?php echo $date; ?>', dateFormat: 'yy-mm-dd', @@ -44,37 +45,88 @@ </script> <style type="text/css"> -.export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;position: absolute;top: 0;left: 17%;} +.export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;/*position: absolute;top: 0;left: 17%;*/} +.trigger_export_btn{position: absolute;top: 0;left: 17%;} </style> -<div class="export_form_area "> - <form class="form-inline " method="post" id="search_list" action="/webht.php/apps/paypal/index/export_list/"> - <div class="form-group "> - <label for="from_date" class="">Date From</label> - <input type="text" class="form-control" id="from_date" name="from_date" required> - </div> - <div class="form-group "> - <label for="to_date" class="">To</label> - <input type="text" class="form-control" id="to_date" name="to_date" required> - </div> - <div class="form-group "> - <label for="currency" class="">Currency</label> - <select class="form-control" id="currency" name="currency"> - <option value="">All</option> - <option value="CNY">CNY</option> - <option value="USD">USD</option> - <option value="EUR">EUR</option> - <option value="CAD">CAD</option> - <option value="AUD">AUD</option> - <option value="GBP">GBP</option> - <option value="NZD">NZD</option> - <option value="SGD">SGD</option> - <option value="CHF">CHF</option> - </select> +<!-- Button trigger modal --> +<button type="button" class="btn btn-primary trigger_export_btn" data-toggle="modal" data-target="#exampleModal"> + 导出收款记录 &gt; +</button> +<!-- Modal --> +<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title" id="exampleModalLabel">导出 Paypal 记录</h5> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"> + <span aria-hidden="true">&times;</span> + </button> + </div> + <div class="modal-body"> + <form class="form-horizontal" role="form" method="post" id="search_list" action="/webht.php/apps/paypal/index/export_list/"> + <div class="form-group row"> + <label for="from_date" class="col-md-4">使用上次</label> + <div class="col-md-16"> + <select class="form-control" id="date_history" name="date_history" onchange="set_start_date(this)"> + <option value="">选择一个开始记录</option> + <?php + foreach ($record_flags as $kf => $vf) { +echo "<option value=\"$vf->TEL_transactionNoticeId@" . strstr($vf->TEL_transactionDate, " ", true) . "\">" . substr($vf->TEL_transactionDate,0,16) . ' / '. $vf->TEL_orderId . ' / '. $vf->TEL_transactionAmount . ' / '. $vf->TEL_transactionCurrency . "</option>"; + } + ?> + </select> + </div> + </div> + <div class="form-group row"> + <label for="from_date" class="col-md-4">Date From</label> + <div class="col-md-16"> + <input type="text" class="form-control col-md-8" id="from_date" name="from_date" placeholder="开始日期" required> + </div> + </div> + <div class="form-group row"> + <label for="to_date" class="col-md-4">To</label> + <div class="col-md-16"> + <input type="text" class="form-control" id="to_date" name="to_date" placeholder="结束日期" required> + </div> + </div> + <div class="form-group row"> + <label for="currency" class="col-md-4">Currency</label> + <div class="col-md-16"> + <select class="form-control" id="currency" name="currency" required> + <option value="">所有币种</option> + <option value="CNY">CNY</option> + <option value="USD">USD</option> + <option value="EUR">EUR</option> + <option value="CAD">CAD</option> + <option value="AUD">AUD</option> + <option value="GBP">GBP</option> + <option value="NZD">NZD</option> + <option value="SGD">SGD</option> + <option value="CHF">CHF</option> + </select> + </div> + </div> + <div class="form-group row"> + <label for="set_amount" class="col-md-4">总金额(元)</label> + <div class="col-md-16"> + <input type="number" class="form-control" id="set_amount" name="set_amount" placeholder="总金额"> + </div> + </div> + <div class="form-group"> + <div class="col-sm-24 "> + <button type="submit" class="btn btn-primary center-block">导出</button> + </div> + </div> + </form> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button> + </div> + </div> </div> - <button type="submit" class="btn btn-primary">Export</button> - </form> </div> + <div class="container-fluid"> <div class="row"> @@ -219,6 +271,21 @@ <script type="text/javascript"> + function set_start_date(select) { + if (select.value=='') { + $("#from_date").datepicker( "option", "disabled", false ); + $('#from_date').prop("readonly",false); + $('#to_date').prop("readonly",false).parents('.form-group').show(); + $("#to_date").datepicker( "option", "disabled", false ); + } else { + var this_date = select.value.split('@')[1]; + $('#from_date').val(this_date).prop("readonly",true); + $("#from_date" ).datepicker( "option", "disabled", true ); + $('#to_date').prop("readonly",true).parents('.form-group').hide(); + $("#to_date" ).datepicker( "option", "disabled", true ); + } + } + function show_order_modal(pn_txn_id, pn_invoice) { $.ajax({ type: "get", From bc43f8d1e8f056039ab6920124e9f5fa0f31ff60 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 28 Feb 2019 16:41:39 +0800 Subject: [PATCH 246/382] =?UTF-8?q?paypal=20=E6=8C=89=E9=87=91=E9=A2=9D?= =?UTF-8?q?=E5=AF=BC=E5=87=BA=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95,?= =?UTF-8?q?=E9=87=91=E9=A2=9D=E5=BF=85=E5=A1=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/views/note_list.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index daf4266a..0a957caa 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -283,6 +283,7 @@ echo "<option value=\"$vf->TEL_transactionNoticeId@" . strstr($vf->TEL_transacti $("#from_date" ).datepicker( "option", "disabled", true ); $('#to_date').prop("readonly",true).parents('.form-group').hide(); $("#to_date" ).datepicker( "option", "disabled", true ); + $("#set_amount").prop("required", true); } } From e0399f409ba5429f3abdd757b6c29437c90a46e2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 1 Mar 2019 15:42:56 +0800 Subject: [PATCH 247/382] =?UTF-8?q?paypal=20=E5=AF=BC=E5=87=BA=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E6=80=BB=E9=87=91=E9=A2=9D=E7=9A=84=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E8=AE=B0=E5=BD=95.=20=E8=87=AA=E5=8A=A8=E8=AE=A1=E7=AE=97,?= =?UTF-8?q?=E5=AE=8C=E5=85=A8=E5=8C=B9=E9=85=8D=E7=9B=AE=E6=A0=87=E9=87=91?= =?UTF-8?q?=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 34 ++++++++++++++++--- .../third_party/paypal/models/note_model.php | 7 ++-- webht/third_party/paypal/views/note_list.php | 19 +++++++++-- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index d2adc6f4..ec3f6458 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -10,6 +10,7 @@ class Index extends CI_Controller { // $this->output->enable_profiler(TRUE); $this->load->model('Paypal_model'); $this->load->model('Note_model'); + bcscale(2); } public function index() { @@ -1004,12 +1005,28 @@ class Index extends CI_Controller { $allmost_day = 30; } $last_sn = null; + $last_notice_sn = null; + $last_notice_record = array(); if ( ! empty($last_record)) { - $last_sn = strstr($last_record, '@', TRUE); - $from_date = substr(strstr($last_record, '@'),1); + $selection_text = explode("@", $last_record); + $last_sn = $selection_text[0]; + $last_notice_record = $this->Note_model->list_export_record($last_sn); + if ( ! empty($last_notice_record[0])) { + $last_notice_sn = $last_notice_record[0]->TEL_transactionNoticeId; + // 查询导出记录时包含上次导出的最后一条. + // 因此目标金额设为本次的目标+上次已导出的部分 + // 得到结果集之后会把本次的第一条的金额重新计算,即减去上次已导出金额.下述<!$> + $amount = bcadd($amount, $last_notice_record[0]->TEL_exportAmount); + $from_date = strstr($last_notice_record[0]->TEL_transactionDate, " ", TRUE); + $currency = $last_notice_record[0]->TEL_transactionCurrency; + } } - $all_list = $this->target_amount_recursive($currency, $amount, 0, $from_date, $allmost_day, array(), $last_sn); + $all_list = $this->target_amount_recursive($currency, $amount, 0, $from_date, $allmost_day, array(), $last_notice_sn); $export_list = $all_list['list']; + // <!$>修改导出的第一条记录, 金额改为剩余金额<!$> + if ( ! empty($last_notice_record[0]) && $last_notice_record[0]->TEL_transactionNoticeId==$export_list[0]->pn_sn) { + $export_list[0]->pn_mc_gross = bcsub($last_notice_record[0]->TEL_transactionAmount, $last_notice_record[0]->TEL_exportAmount); + } } if ($export_list == false) { echo "Not found any records for export."; @@ -1017,6 +1034,8 @@ class Index extends CI_Controller { } // 记录这次导出的最后一条 if (isset($all_list['last_flag']) && ! empty($all_list['last_flag'])) { + $balance_diff = bcsub($all_list['now_amount'], $amount); + $last_record_export = bcsub($all_list['last_flag']->pn_mc_gross, $balance_diff); $insert_db = array( "TEL_transactionType" => 15002 ,"TEL_transactionNoticeId" => $all_list['last_flag']->pn_sn @@ -1025,10 +1044,14 @@ class Index extends CI_Controller { ,"TEL_transactionAmount" => $all_list['last_flag']->pn_mc_gross ,"TEL_transactionCurrency" => $all_list['last_flag']->pn_mc_currency ,"TEL_orderId" => $all_list['last_flag']->pn_invoice - ,"TEL_exportAmount" => $all_list['last_flag']->pn_mc_gross + ,"TEL_exportAmount" => $last_record_export ,"TEL_exportDate" => date('Y-m-d H:i:s') ); $this->Note_model->export_record($insert_db); + // 修改导出的最后一条 + array_pop($export_list); + $all_list['last_flag']->pn_mc_gross = $last_record_export; + array_push($export_list, $all_list['last_flag']); } $this->save_excel($export_list); @@ -1054,7 +1077,8 @@ class Index extends CI_Controller { } $ret = array( "last_flag" => $last_flag, - "list" => $list + "list" => $list, + "now_amount" => $now_amount ); if (empty($former_list)) { return $ret; diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index 04938ef1..43662870 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -162,7 +162,7 @@ class Note_model extends CI_Model { $search_sql .= " AND pn_mc_currency = '$currency' "; } if ( ! empty($pn_sn)) { - $search_sql .= " AND pn_sn > $pn_sn "; + $search_sql .= " AND pn_sn >= $pn_sn "; } $this->search = $search_sql; $this->orderby = " order by pn.pn_sn asc"; @@ -179,11 +179,14 @@ class Note_model extends CI_Model { $this->info->insert('Transaction_Export_Log', $db); } - public function list_export_record() + public function list_export_record($sn=0) { $this->info = $this->load->database('INFO', TRUE); + $search_sql = $sn===0 ? "" : " and TEL_SN=$sn "; $sql = "SELECT TOP 10 * FROM [InfoManager].[dbo].[Transaction_Export_Log] + WHERE 1=1 + $search_sql order by TEL_SN desc"; return $this->info->query($sql)->result(); } diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 0a957caa..d8c83858 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -47,6 +47,7 @@ <style type="text/css"> .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;/*position: absolute;top: 0;left: 17%;*/} .trigger_export_btn{position: absolute;top: 0;left: 17%;} +.modal-dialog{width: 1024px;} </style> <!-- Button trigger modal --> <button type="button" class="btn btn-primary trigger_export_btn" data-toggle="modal" data-target="#exampleModal"> @@ -71,7 +72,12 @@ <option value="">选择一个开始记录</option> <?php foreach ($record_flags as $kf => $vf) { -echo "<option value=\"$vf->TEL_transactionNoticeId@" . strstr($vf->TEL_transactionDate, " ", true) . "\">" . substr($vf->TEL_transactionDate,0,16) . ' / '. $vf->TEL_orderId . ' / '. $vf->TEL_transactionAmount . ' / '. $vf->TEL_transactionCurrency . "</option>"; +echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true) . "@" . $vf->TEL_transactionCurrency . "\">" + . " [" . strstr($vf->TEL_exportDate, " ", true) . "] " + . $vf->TEL_transactionCurrency . " " . $vf->TEL_transactionAmount . ' - '. $vf->TEL_exportAmount + . " / " . $vf->TEL_orderId . ' / ' + . substr($vf->TEL_transactionDate,0,16) + . "</option>"; } ?> </select> @@ -109,7 +115,7 @@ echo "<option value=\"$vf->TEL_transactionNoticeId@" . strstr($vf->TEL_transacti <div class="form-group row"> <label for="set_amount" class="col-md-4">总金额(元)</label> <div class="col-md-16"> - <input type="number" class="form-control" id="set_amount" name="set_amount" placeholder="总金额"> + <input type="number" class="form-control" id="set_amount" name="set_amount" placeholder="总金额" onkeyup="set_target_amount(this)"> </div> </div> <div class="form-group"> @@ -284,6 +290,15 @@ echo "<option value=\"$vf->TEL_transactionNoticeId@" . strstr($vf->TEL_transacti $('#to_date').prop("readonly",true).parents('.form-group').hide(); $("#to_date" ).datepicker( "option", "disabled", true ); $("#set_amount").prop("required", true); + $("#currency option[value='" + select.value.split('@')[2] + "']").prop("selected", true); + $("#currency").prop("disabled", true); + } + } + + function set_target_amount(obj) { + if (parseFloat(obj.value) > 0) { + $('#to_date').prop("readonly",true).parents('.form-group').hide(); + $("#to_date" ).datepicker( "option", "disabled", true ); } } From e3d3ba3a5239e37443b05d48fdbe7ef1daf7d656 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 1 Mar 2019 15:50:22 +0800 Subject: [PATCH 248/382] =?UTF-8?q?paypal=20=E5=AF=BC=E5=87=BA=E8=A1=A8?= =?UTF-8?q?=E5=8D=95=E7=9A=84=E5=BF=85=E5=A1=AB=E9=A1=B9=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/views/note_list.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index d8c83858..ca271a36 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -299,6 +299,9 @@ echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true if (parseFloat(obj.value) > 0) { $('#to_date').prop("readonly",true).parents('.form-group').hide(); $("#to_date" ).datepicker( "option", "disabled", true ); + } else { + $('#to_date').prop("readonly",false).parents('.form-group').show(); + $("#to_date").datepicker( "option", "disabled", false ); } } From 2168b91ffc46f8e0ed825d8f7774e2a15f91014a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 1 Mar 2019 16:06:18 +0800 Subject: [PATCH 249/382] fixed notice --- webht/third_party/paypal/views/note_list.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index ca271a36..70dcc979 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -71,6 +71,7 @@ <select class="form-control" id="date_history" name="date_history" onchange="set_start_date(this)"> <option value="">选择一个开始记录</option> <?php + if ( ! empty($record_flags)) { foreach ($record_flags as $kf => $vf) { echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true) . "@" . $vf->TEL_transactionCurrency . "\">" . " [" . strstr($vf->TEL_exportDate, " ", true) . "] " @@ -79,6 +80,7 @@ echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true . substr($vf->TEL_transactionDate,0,16) . "</option>"; } + } ?> </select> </div> From 08844a835b7c7675774c1777faa423e32179e8c9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 5 Mar 2019 10:15:10 +0800 Subject: [PATCH 250/382] =?UTF-8?q?Trippest=20=E8=B4=A6=E5=8D=95=E7=BB=93?= =?UTF-8?q?=E7=AE=97,=E6=9C=AA=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/vendor_money.php | 92 +++++++++++ .../trippestOrderSync/libraries/trippest.php | 26 +++ .../models/vendor_money_model.php | 126 ++++++++++++++ .../trippestOrderSync/views/flatpickr.css.php | 5 + .../views/vendor_money_sum.php | 154 ++++++++++++++++++ 5 files changed, 403 insertions(+) create mode 100644 webht/third_party/trippestOrderSync/controllers/vendor_money.php create mode 100644 webht/third_party/trippestOrderSync/models/vendor_money_model.php create mode 100644 webht/third_party/trippestOrderSync/views/flatpickr.css.php create mode 100644 webht/third_party/trippestOrderSync/views/vendor_money_sum.php diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php new file mode 100644 index 00000000..f08b332a --- /dev/null +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -0,0 +1,92 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Vendor_money extends CI_Controller { + + public function __construct(){ + parent::__construct(); + $this->load->library('trippest'); + $this->load->helper('array'); + $this->load->model('Vendor_money_model', 'money_model'); + mb_regex_encoding("UTF-8"); + bcscale(4); + } + + public function index() + { + } + + public function settlement() + { + // $start_date = $this->input->post("start_date"); + // $end_date = $this->input->post("end_date"); + // if ($end_date == null) { + // $end_date = date("Y-m-d H:i:s", strtotime("+1 month", strtotime($start_date))-1); + // } + // $vendors = $this->input->post("vendors"); + // test + $start_date = "2018-10-01"; + $end_date = "2018-10-31 23:59:59"; + $vendors = "1343,29188"; + // end test + $vendor_sourcetype = $this->trippest->vendor_sourcetype(); + $result = array( + "trippest_order_vendor_money" => array() + ,"transfer_sum" => 0 + ); + /** 团款 */ + foreach (explode(",", $vendors) as $key => $vendor) { + $sourcetype = $vendor_sourcetype[strval($vendor)]["sourcetype"]; + $opi_summoney = $this->money_model->checked_group_list($vendor, $sourcetype, $start_date, $end_date); + $ret = array( + "trippest" => + array( + "trippest_sum" => 0, + "vendor_sum" => 0 + ), + "vendor" => + array( + "trippest_sum" => 0, + "vendor_sum" => 0, + "transfer_sum" => 0, + "trippest_order_vendor_money" => null + ) + ); + // 按照海纳的算法 + foreach ($opi_summoney as $key => $opi_money) { + if (floatval($opi_money['vendor_sum']) > 0) { + $ret["trippest"]['vendor_sum'] = bcadd(floatval($ret["trippest"]['vendor_sum']), floatval($opi_money['vendor_sum'])) ; + } + if (floatval($opi_money['trippest_sum']) > 0) { + $ret["trippest"]['trippest_sum'] = bcadd(floatval($ret["trippest"]['trippest_sum']), floatval($opi_money['trippest_sum'])) ; + } + } + // 按照图兰朵算法: Trippest自营订单的代收算在海纳收款 + foreach ($opi_summoney as $kv => $opi_money_v) { + if (strval($opi_money_v['COLI_OPI_ID']) === '435') { + $ret["vendor"]['vendor_sum'] = bcadd(floatval($ret["vendor"]['vendor_sum']), floatval($opi_money_v['vendor_sum'])) ; + } else { + $ret["vendor"]['trippest_sum'] = bcadd(floatval($ret["vendor"]['trippest_sum']), floatval($opi_money_v['trippest_sum'])) ; + $ret["vendor"]['trippest_sum'] = bcadd(floatval($ret["vendor"]['trippest_sum']), floatval($opi_money_v['vendor_sum'])) ; + } + } + $ret["vendor"]["transfer_sum"] = bcsub($ret["vendor"]['vendor_sum'], $ret["trippest"]['vendor_sum']); + if ($ret["vendor"]["transfer_sum"] != 0) { + $result['transfer_sum'] = bcadd($result['transfer_sum'], $ret["vendor"]["transfer_sum"]); + $result['trippest_order_vendor_money'] = array_merge($result['trippest_order_vendor_money'], $this->money_model->trippest_order_with_vendormoney($vendor, $sourcetype, $start_date, $end_date)); + } + + $result["money"][strval($vendor)] = $ret; + $result["money"][strval($vendor)]["vendor_code"] = $vendor; + $result["money"][strval($vendor)]["vendor_name"] = $vendor_sourcetype[strval($vendor)]["vendor_name"]; + } + /** 成本 */ + // return $this->output->set_content_type('application/json')->set_output(json_encode($result)); + $this->load->view('vendor_money_sum', $result); + return ; + } + +} + +/* End of file vendor_money.php */ +/* Location: ./third_party/trippestOrderSync/controllers/vendor_money.php */ diff --git a/webht/third_party/trippestOrderSync/libraries/trippest.php b/webht/third_party/trippestOrderSync/libraries/trippest.php index e808b0b5..808089b4 100644 --- a/webht/third_party/trippestOrderSync/libraries/trippest.php +++ b/webht/third_party/trippestOrderSync/libraries/trippest.php @@ -74,6 +74,32 @@ class Trippest return array($pag_code); } + public function vendor_sourcetype() + { + return array( + // 北京图兰朵 + "1343" => array( + "sourcetype" => "32090" + ,"vendor_name" => "北京图兰朵" + ) + // 上海图兰朵 + ,"29188" => array( + "sourcetype" => "32112" + ,"vendor_name" => "上海图兰朵" + ) + // 西安图兰朵 + ,"30548" => array( + "sourcetype" => "32116" + ,"vendor_name" => "西安图兰朵" + ) + // 桂林地接 + ,"628" => array( + "sourcetype" => "32122" + ,"vendor_name" => "桂林地接" + ) + ); + } + } diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php new file mode 100644 index 00000000..94692648 --- /dev/null +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -0,0 +1,126 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Vendor_money_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->load->helper('array'); + $this->HT = $this->load->database('HT', TRUE); + bcscale(4); + } + + public function checked_group_list($vendor, $sourcetype, $start_date, $end_date) + { + $sql = "SELECT sum_opi.COLI_OPI_ID,sum(sum_opi.海纳收款) as trippest_sum,sum(sum_opi.地接社收款) as vendor_sum + from ( + SELECT + (select isnull(SUM(COLD_TotalPrice),0) from BIZ_ConfirmLineDetail cold + where cold.COLD_COLI_SN=cgi_group.COLI_SN + and COLD_ServiceType='D' + and COLD_PlanVEI_SN=$vendor + )*cgi_group.汇率 as cold_price_RMB, + * + from ( + select + COLI_SN, + (select COUNT(0) from BIZ_ConfirmLineDetail + where COLD_COLI_SN=COLI_SN + and COLD_ServiceType='D' + ) as service_cnt, + COLI.COLI_sourcetype, + COLI.COLI_Price, + coli.COLI_Currency, + case when coli.COLI_Price <> 0 then + convert(decimal(10,2),round((select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_COLI_SN=COLI_SN + )/isnull(COLI.COLI_Price,1),2)) + else 0 end as 汇率, + (select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_COLI_SN=COLI_SN + ) as 总收款, + (select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_COLI_SN=COLI_SN + and GAI_Type not in (15017,15008,15006) + ) as 海纳收款, + (select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_COLI_SN=COLI_SN + and GAI_Type in (15017,15008,15006) + ) as 地接社收款 + ,coli.COLI_OPI_ID + + from CK_GroupInfo cgi + inner join GRoupInfo gri on CGI_GRI_SN=GRI_SN + inner join BIZ_ConfirmLineInfo coli on COLI_GRI_SN=GRI_SN + where 1=1 + and CGI_ArriveDate between '$start_date' and '$end_date' + and exists ( + select 1 from OperatorInfo where OPI_DEI_SN=30 and OPI_SN=CGI_OPI_SN + ) + and CGI_Checked=1 + and GRI_OrderType=227002 + + and COLI_sourcetype=$sourcetype + ) as cgi_group + ) as sum_opi + group by sum_opi.COLI_OPI_ID + order by case sum_opi.COLI_OPI_ID when '435' then 0 else 1 end "; + $query = $this->HT->query($sql); + $opi_sum_money = $query->result_array(); + return $opi_sum_money; + } + + // Trippest自营订单,含地接代收的 + public function trippest_order_with_vendormoney($vendor, $sourcetype, $start_date, $end_date) + { + $sql = "SELECT COLI_SN,coli_id,COLI_GroupCode, + convert(date,cgi.CGI_ArriveDate) CGI_ArriveDate, + COLI.COLI_sourcetype, COLI.COLI_Price, coli.COLI_Currency, + (SELECT isnull(SUM(GAI_SSJE),0) + FROM BIZ_GroupAccountInfo + WHERE DeleteFlag=0 + AND GAI_COLI_SN=COLI_SN + AND GAI_Type IN (15017, + 15008, + 15006)) AS vendor_sum , + coli.COLI_OPI_ID + FROM CK_GroupInfo cgi + INNER JOIN GRoupInfo gri ON CGI_GRI_SN=GRI_SN + INNER JOIN BIZ_ConfirmLineInfo coli ON COLI_GRI_SN=GRI_SN + WHERE 1=1 + AND CGI_ArriveDate BETWEEN '$start_date' AND '$end_date' + AND EXISTS + (SELECT 1 + FROM OperatorInfo + WHERE OPI_DEI_SN=30 + AND OPI_SN=CGI_OPI_SN) + AND CGI_Checked=1 + AND GRI_OrderType=227002 + AND COLI_sourcetype=$sourcetype + AND COLI_OPI_ID <> 435 + AND exists ( + select 1 from BIZ_ConfirmLineDetail where COLD_COLI_SN=COLI_SN and COLD_PlanVEI_SN=$vendor + ) + AND exists( + SELECT 1 + FROM BIZ_GroupAccountInfo + WHERE DeleteFlag=0 + AND GAI_COLI_SN=COLI_SN + AND GAI_SSJE>0 + AND GAI_Type IN (15017, + 15008, + 15006) + ) + ORDER BY cgi.CGI_ArriveDate "; + $query = $this->HT->query($sql); +// log_message('error',$sql); +// log_message('error',var_export($query->result_array(), 1)); + return $query->result_array(); + } + + + +} + +/* End of file vendor_money.php */ +/* Location: ./third_party/trippestOrderSync/models/vendor_money.php */ diff --git a/webht/third_party/trippestOrderSync/views/flatpickr.css.php b/webht/third_party/trippestOrderSync/views/flatpickr.css.php new file mode 100644 index 00000000..ed39226c --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/flatpickr.css.php @@ -0,0 +1,5 @@ +<style type="text/css"> + /*flatpickr:begin*/ + .flatpickr-calendar{background:transparent;opacity:0;display:none;text-align:center;visibility:hidden;padding:0;-webkit-animation:none;animation:none;direction:ltr;border:0;font-size:14px;line-height:24px;border-radius:5px;position:absolute;width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-touch-action:manipulation;touch-action:manipulation;background:#fff;-webkit-box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);}.flatpickr-calendar.open,.flatpickr-calendar.inline{opacity:1;max-height:640px;visibility:visible;}.flatpickr-calendar.open{display:inline-block;z-index:99999;}.flatpickr-calendar.animate.open{-webkit-animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);}.flatpickr-calendar.inline{display:block;position:relative;top:2px;}.flatpickr-calendar.static{position:absolute;top:calc(100% + 2px);}.flatpickr-calendar.static.open{z-index:999;display:block;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+1) .flatpickr-day.inRange:nth-child(7n+7){-webkit-box-shadow:none !important;box-shadow:none !important;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+2) .flatpickr-day.inRange:nth-child(7n+1){-webkit-box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-calendar .hasWeeks .dayContainer,.flatpickr-calendar .hasTime .dayContainer{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0;}.flatpickr-calendar .hasWeeks .dayContainer{border-left:0;}.flatpickr-calendar.showTimeInput.hasTime .flatpickr-time{height:40px;border-top:1px solid #e6e6e6;}.flatpickr-calendar.noCalendar.hasTime .flatpickr-time{height:auto;}.flatpickr-calendar:before,.flatpickr-calendar:after{position:absolute;display:block;pointer-events:none;border:solid transparent;content:'';height:0;width:0;left:22px;}.flatpickr-calendar.rightMost:before,.flatpickr-calendar.rightMost:after{left:auto;right:22px;}.flatpickr-calendar:before{border-width:5px;margin:0 -5px;}.flatpickr-calendar:after{border-width:4px;margin:0 -4px;}.flatpickr-calendar.arrowTop:before,.flatpickr-calendar.arrowTop:after{bottom:100%;}.flatpickr-calendar.arrowTop:before{border-bottom-color:#e6e6e6;}.flatpickr-calendar.arrowTop:after{border-bottom-color:#fff;}.flatpickr-calendar.arrowBottom:before,.flatpickr-calendar.arrowBottom:after{top:100%;}.flatpickr-calendar.arrowBottom:before{border-top-color:#e6e6e6;}.flatpickr-calendar.arrowBottom:after{border-top-color:#fff;}.flatpickr-calendar:focus{outline:0;}.flatpickr-wrapper{position:relative;display:inline-block;}.flatpickr-months{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-months .flatpickr-month{background:transparent;color:rgba(0,0,0,0.9);fill:rgba(0,0,0,0.9);height:28px;line-height:1;text-align:center;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;margin-bottom:5px;}.flatpickr-months .flatpickr-prev-month,.flatpickr-months .flatpickr-next-month{text-decoration:none;cursor:pointer;position:absolute;top:0px;line-height:16px;height:28px;padding:10px;z-index:3;}.flatpickr-months .flatpickr-prev-month.disabled,.flatpickr-months .flatpickr-next-month.disabled{display:none;}.flatpickr-months .flatpickr-prev-month i,.flatpickr-months .flatpickr-next-month i{position:relative;}.flatpickr-months .flatpickr-prev-month.flatpickr-prev-month,.flatpickr-months .flatpickr-next-month.flatpickr-prev-month{left:0;}.flatpickr-months .flatpickr-prev-month.flatpickr-next-month,.flatpickr-months .flatpickr-next-month.flatpickr-next-month{right:0;}.flatpickr-months .flatpickr-prev-month:hover,.flatpickr-months .flatpickr-next-month:hover{color:#959ea9;}.flatpickr-months .flatpickr-prev-month:hover svg,.flatpickr-months .flatpickr-next-month:hover svg{fill:#f64747;}.flatpickr-months .flatpickr-prev-month svg,.flatpickr-months .flatpickr-next-month svg{width:14px;height:14px;}.flatpickr-months .flatpickr-prev-month svg path,.flatpickr-months .flatpickr-next-month svg path{-webkit-transition:fill 0.1s;transition:fill 0.1s;fill:inherit;}.numInputWrapper{position:relative;height:auto;}.numInputWrapper input,.numInputWrapper span{display:inline-block;}.numInputWrapper input{width:100%;}.numInputWrapper input::-ms-clear{display:none;}.numInputWrapper span{position:absolute;right:0;width:14px;padding:0 4px 0 2px;height:50%;line-height:50%;opacity:0;cursor:pointer;border:1px solid rgba(57,57,57,0.15);-webkit-box-sizing:border-box;box-sizing:border-box;}.numInputWrapper span:hover{background:rgba(0,0,0,0.1);}.numInputWrapper span:active{background:rgba(0,0,0,0.2);}.numInputWrapper span:after{display:block;content:"";position:absolute;}.numInputWrapper span.arrowUp{top:-2px;left:50px;}.numInputWrapper span.arrowUp:after{border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:4px solid rgba(57,57,57,0.6);top:26%;}.numInputWrapper span.arrowDown{top:10px;left:50px;}.numInputWrapper span.arrowDown:after{border-left:4px solid transparent;border-right:4px solid transparent;border-top:4px solid rgba(57,57,57,0.6);top:40%;}.numInputWrapper span svg{width:inherit;height:auto;}.numInputWrapper span svg path{fill:rgba(0,0,0,0.5);}.numInputWrapper:hover{cursor:pointer;}.numInputWrapper:hover span{opacity:1;}.flatpickr-current-month{font-size:17px;line-height:inherit;font-weight:300;color:inherit;position:absolute;width:75%;left:12.5%;padding:6.16px 0 0 0;line-height:1;height:28px;display:inline-block;text-align:center;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);}.flatpickr-current-month span.cur-month{font-family:inherit;font-weight:700;color:inherit;display:inline-block;margin-left:0.5ch;padding:0;font-size:19px;color:#a31022;}.flatpickr-current-month span.cur-month:hover{cursor:pointer;}.flatpickr-current-month .numInputWrapper{width:6ch;width:7ch\0;display:inline-block;}.flatpickr-current-month .numInputWrapper span.arrowUp:after{border-bottom-color:rgba(0,0,0,0.9);}.flatpickr-current-month .numInputWrapper span.arrowDown:after{border-top-color:rgba(0,0,0,0.9);}.flatpickr-current-month input.cur-year{background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;color:inherit;cursor:text;padding:0 0 0 0.5ch;margin:0;display:inline-block;font-size:inherit;font-family:inherit;font-weight:300;line-height:inherit;height:auto;border:0;border-radius:0;vertical-align:initial;font-size:18px;}.flatpickr-current-month input.cur-year:focus{outline:0;}.flatpickr-current-month input.cur-year[disabled],.flatpickr-current-month input.cur-year[disabled]:hover{font-size:100%;color:rgba(0,0,0,0.5);background:transparent;pointer-events:none;}.flatpickr-weekdays{background:transparent;text-align:center;overflow:hidden;width:100%;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;height:28px;}.flatpickr-weekdays .flatpickr-weekdaycontainer{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}span.flatpickr-weekday{cursor:default;font-size:16px;background:transparent;color:rgba(0,0,0,0.54);line-height:1;margin:0;text-align:center;display:block;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}.dayContainer,.flatpickr-weeks{padding:1px 0 0 0;}.flatpickr-days{position:relative;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:start;-webkit-align-items:flex-start;-ms-flex-align:start;align-items:flex-start;width:307.875px;}.flatpickr-days:focus{outline:0;}.dayContainer{padding:0;outline:0;text-align:left;width:307.875px;min-width:307.875px;max-width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;display:inline-block;display:-ms-flexbox;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-wrap:wrap;-ms-flex-pack:justify;-webkit-justify-content:space-around;justify-content:space-around;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);opacity:1;}.dayContainer + .dayContainer{-webkit-box-shadow:-1px 0 0 #e6e6e6;box-shadow:-1px 0 0 #e6e6e6;}.flatpickr-day{background:none;border:1px solid transparent;border-radius:150px;-webkit-box-sizing:border-box;box-sizing:border-box;color:#a31022;cursor:pointer;font-weight:400;width:14.2857143%;-webkit-flex-basis:14.2857143%;-ms-flex-preferred-size:14.2857143%;flex-basis:14.2857143%;max-width:39px;height:39px;line-height:39px;margin:0;display:inline-block;position:relative;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;text-align:center;font-size:16px;}.flatpickr-day.inRange,.flatpickr-day.prevMonthDay.inRange,.flatpickr-day.nextMonthDay.inRange,.flatpickr-day.today.inRange,.flatpickr-day.prevMonthDay.today.inRange,.flatpickr-day.nextMonthDay.today.inRange,.flatpickr-day:hover,.flatpickr-day.prevMonthDay:hover,.flatpickr-day.nextMonthDay:hover,.flatpickr-day:focus,.flatpickr-day.prevMonthDay:focus,.flatpickr-day.nextMonthDay:focus{cursor:pointer;outline:0;background:#e6e6e6;border-color:#e6e6e6;}.flatpickr-day.today{border-color:#959ea9;}.flatpickr-day.today:hover,.flatpickr-day.today:focus{border-color:#959ea9;background:#959ea9;color:#fff;}.flatpickr-day.selected,.flatpickr-day.startRange,.flatpickr-day.endRange,.flatpickr-day.selected.inRange,.flatpickr-day.startRange.inRange,.flatpickr-day.endRange.inRange,.flatpickr-day.selected:focus,.flatpickr-day.startRange:focus,.flatpickr-day.endRange:focus,.flatpickr-day.selected:hover,.flatpickr-day.startRange:hover,.flatpickr-day.endRange:hover,.flatpickr-day.selected.prevMonthDay,.flatpickr-day.startRange.prevMonthDay,.flatpickr-day.endRange.prevMonthDay,.flatpickr-day.selected.nextMonthDay,.flatpickr-day.startRange.nextMonthDay,.flatpickr-day.endRange.nextMonthDay{background:#569ff7;-webkit-box-shadow:none;box-shadow:none;color:#fff;border-color:#569ff7;}.flatpickr-day.selected.startRange,.flatpickr-day.startRange.startRange,.flatpickr-day.endRange.startRange{border-radius:50px 0 0 50px;}.flatpickr-day.selected.endRange,.flatpickr-day.startRange.endRange,.flatpickr-day.endRange.endRange{border-radius:0 50px 50px 0;}.flatpickr-day.selected.startRange + .endRange,.flatpickr-day.startRange.startRange + .endRange,.flatpickr-day.endRange.startRange + .endRange{-webkit-box-shadow:-10px 0 0 #569ff7;box-shadow:-10px 0 0 #569ff7;}.flatpickr-day.selected.startRange.endRange,.flatpickr-day.startRange.startRange.endRange,.flatpickr-day.endRange.startRange.endRange{border-radius:50px;}.flatpickr-day.inRange{border-radius:0;-webkit-box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover,.flatpickr-day.prevMonthDay,.flatpickr-day.nextMonthDay,.flatpickr-day.notAllowed,.flatpickr-day.notAllowed.prevMonthDay,.flatpickr-day.notAllowed.nextMonthDay{color:#848080;background:transparent;border-color:transparent;cursor:default;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover{cursor:not-allowed;color:#d0d0d0;}.flatpickr-day.week.selected{border-radius:0;-webkit-box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;}.flatpickr-day.hidden{visibility:hidden;}.rangeMode .flatpickr-day{margin-top:1px;}.flatpickr-weekwrapper{display:inline-block;float:left;}.flatpickr-weekwrapper .flatpickr-weeks{padding:0 12px;-webkit-box-shadow:1px 0 0 #e6e6e6;box-shadow:1px 0 0 #e6e6e6;}.flatpickr-weekwrapper .flatpickr-weekday{float:none;width:100%;line-height:28px;}.flatpickr-weekwrapper span.flatpickr-day,.flatpickr-weekwrapper span.flatpickr-day:hover{display:block;width:100%;max-width:none;color:#9a9a9a;background:transparent;cursor:default;border:none;}.flatpickr-innerContainer{display:block;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;}.flatpickr-rContainer{display:inline-block;padding:0;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time{text-align:center;outline:0;display:block;height:0;line-height:40px;max-height:40px;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-time:after{content:"";display:table;clear:both;}.flatpickr-time .numInputWrapper{-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;width:40%;height:40px;float:left;}.flatpickr-time .numInputWrapper span.arrowUp:after{border-bottom-color:#4f4f4f;}.flatpickr-time .numInputWrapper span.arrowDown:after{border-top-color:#4f4f4f;}.flatpickr-time.hasSeconds .numInputWrapper{width:26%;}.flatpickr-time.time24hr .numInputWrapper{width:49%;}.flatpickr-time input{background:transparent;-webkit-box-shadow:none;box-shadow:none;border:0;border-radius:0;text-align:center;margin:0;padding:0;height:inherit;line-height:inherit;cursor:pointer;color:#4f4f4f;font-size:14px;position:relative;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time input.flatpickr-hour{font-weight:bold;}.flatpickr-time input.flatpickr-minute,.flatpickr-time input.flatpickr-second{font-weight:400;}.flatpickr-time input:focus{outline:0;border:0;}.flatpickr-time .flatpickr-time-separator,.flatpickr-time .flatpickr-am-pm{height:inherit;display:inline-block;float:left;line-height:inherit;color:#4f4f4f;font-weight:bold;width:2%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;}.flatpickr-time .flatpickr-am-pm{outline:0;width:18%;cursor:pointer;text-align:center;font-weight:400;}.flatpickr-time .flatpickr-am-pm:hover,.flatpickr-time .flatpickr-am-pm:focus{background:#f0f0f0;}.flatpickr-input[readonly]{cursor:pointer;}@-webkit-keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}}@keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}} + /*flatpickr:end*/ + </style> diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php new file mode 100644 index 00000000..c5868696 --- /dev/null +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -0,0 +1,154 @@ +<?php +/** + * 账单结算 + */ +?> +<!DOCTYPE html> +<html> +<head> + <title>Trippest账单结算</title> + <meta charset="utf-8"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <meta name="referrer" content="always"> + <link href="http://www.mycht.cn/css/webht/bootstrap.min.css" rel="stylesheet" type="text/css" /> + <link href="http://www.mycht.cn/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css" /> + <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> --> + <?php // include 'flatpickr.css.php'; ?> + <style type="text/css"> + form{border-bottom: 1px solid #ccc;} + .navbar-header h1{display: inline-block;margin-left: 30px;margin-right: 30px;} + label {display: inline-block;max-width: none;margin-bottom: 5px;font-weight: bold; } + .form-check-label{font-weight: normal; margin-left: 5px;} + </style> +</head> +<body> + <div id="wrapper" class="chkVisible print-none"> + <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> + <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + <h1>Trippest账单结算</h1> + </div> + </div> + <div class="container-fluid"> + <p></p> + <form action="" method="POST" role="form"> + <div class="form-group row"> + <label for="" class="col-md-2">地接社</label> + <div class=""> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="1343">北京图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="29188">上海图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="30548">西安图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="628">桂林地接</label> + </div> + </div> + <div class="form-group row"> + <label for="" class="col-md-2">发团日期</label> + <div class="col-md-3"> + <input type="text" class="form-control" id="" placeholder="开始日期" required> + </div> + <div class="col-md-3"> + <input type="text" class="form-control" id="" placeholder="结束日期"> + </div> + <button type="submit" class="btn btn-primary">Submit</button> + </div> + </form> + <p></p> + <table class="table table-bordered table-hover"> + <thead> + <tr> + <th rowspan="2">目的地</th> + <th colspan="2">总营收</th> + <th colspan="2">总成本</th> + <th rowspan="2">利润</th> + <th rowspan="2">海纳利润</th> + <th rowspan="2">地接利润</th> + <th rowspan="2">海纳应付地接</th> + </tr> + <tr> + <th >海纳代收</th> + <th >地接代收</th> + <th rowspan="2">海纳成本</th> + <th rowspan="2">地接成本</th> + </tr> + </thead> + <tbody> + <?php if ( ! empty($money)) { + foreach ($money as $kt => $trippest) { + ?> + <tr> + <td><?php echo $trippest['vendor_name'] ?></td> + <td><?php echo $trippest['trippest']['trippest_sum'] ?></td> + <td><?php echo $trippest['trippest']['vendor_sum'] ?></td> + <td></td> + <td></td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <?php } + } ?> + </tbody> + </table> + <table class="table table-bordered table-hover"> + <thead> + <tr> + <th rowspan="2">目的地</th> + <th colspan="2">总营收</th> + <th colspan="2">总成本</th> + <th rowspan="2">利润</th> + <th rowspan="2">海纳利润</th> + <th rowspan="2">地接利润</th> + <th rowspan="2">海纳应付地接</th> + </tr> + <tr> + <th >海纳代收</th> + <th >地接代收</th> + <th rowspan="2">海纳成本</th> + <th rowspan="2">地接成本</th> + </tr> + </thead> + <tbody> + <?php if ( ! empty($money)) { + foreach ($money as $kv => $vendor) { + ?> + <tr> + <td><?php echo $vendor['vendor_name'] ?></td> + <td><?php echo $vendor['vendor']['trippest_sum'] ?></td> + <td><?php echo $vendor['vendor']['vendor_sum'] ?></td> + <td></td> + <td></td> + <td></td> + <td></td> + <td></td> + <td></td> + </tr> + <?php } + } ?> + <?php if ( ! empty($trippest_order_vendor_money)) { + ?> + <tr> + <th colspan="2">团号</th> + <th colspan="7">应扣除地接收款: 总计 <?php echo $transfer_sum ?></th> + </tr> + <?php foreach ($trippest_order_vendor_money as $ko => $order) { + ?> + <tr> + <td colspan="2"><?php echo $order['COLI_GroupCode'] ?></td> + <td colspan="7"><?php echo $order["vendor_sum"] ?></td> + </tr> + <?php } } ?> + </tbody> + </table> + </div> +</body> +<script src="/js/jquery.min.js&v=20170811" type="text/javascript"></script> +<script src="/js/bootstrap.min.js" type="text/javascript"></script> +<script src="/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script> +<script src="/js/jquery.form.min.js" type="text/javascript"></script> + +</html> From e14d7c2fa9699335f5bcf82c5b8ed335c45f59d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 5 Mar 2019 10:25:08 +0800 Subject: [PATCH 251/382] =?UTF-8?q?Alipay,Paypal,iPaylinks=20APP=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E6=94=B6=E6=AC=BE=E5=BD=95=E5=85=A5,=E7=9B=B8?= =?UTF-8?q?=E5=90=8C=E9=87=91=E9=A2=9D=E8=BF=98=E8=A6=81=E6=A3=80=E6=B5=8B?= =?UTF-8?q?=E4=BB=98=E6=AC=BE=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Alipay_model.php | 2 +- webht/third_party/pay/models/IPayLinks_model.php | 2 +- webht/third_party/paypal/models/paypal_model.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 03e7977f..e8de4b02 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -155,7 +155,7 @@ class Alipay_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_COLI_SN = ? AND GAI_SQJE=? + WHERE GAI_COLI_SN = ? AND GAI_SQJE=? and GAI_Type=15015 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index de3fb567..1ba2db80 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -155,7 +155,7 @@ class IPayLinks_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 and GAI_Type=15018 ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 781db229..edf08fe2 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -156,7 +156,7 @@ class Paypal_model extends CI_Model { IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_GroupAccountInfo - WHERE GAI_COLI_SN = ? AND GAI_SQJE=? AND DeleteFlag=0 + WHERE GAI_COLI_SN = ? AND GAI_SQJE=? AND DeleteFlag=0 AND GAI_Type='15010' ) INSERT INTO BIZ_GroupAccountInfo ( GAI_COLI_SN From e867d57e5632a12333cfd7d25857c13e7fc1d1c6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 6 Mar 2019 09:29:06 +0800 Subject: [PATCH 252/382] =?UTF-8?q?Trippest=20=E8=B4=A6=E5=8D=95=E7=BB=93?= =?UTF-8?q?=E7=AE=97=E6=B1=87=E6=80=BB=E8=A1=A8=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/vendor_money.php | 108 +++++++++++--- .../trippestOrderSync/libraries/trippest.php | 4 + .../models/vendor_money_model.php | 27 +++- .../views/vendor_money_sum.php | 141 +++++++++++------- 4 files changed, 210 insertions(+), 70 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index f08b332a..72c85bdf 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -9,33 +9,61 @@ class Vendor_money extends CI_Controller { $this->load->helper('array'); $this->load->model('Vendor_money_model', 'money_model'); mb_regex_encoding("UTF-8"); - bcscale(4); + bcscale(2); } - public function index() + public function settlement() { + $data['default_date1'] = date('Y-m-01', strtotime("last month")); + $data['default_date2'] = date('Y-m-d', mktime(0,0,0,date('m'),1,date('Y'))-1); + $this->load->view('vendor_money_sum', $data); } - public function settlement() + public function index() { - // $start_date = $this->input->post("start_date"); - // $end_date = $this->input->post("end_date"); - // if ($end_date == null) { - // $end_date = date("Y-m-d H:i:s", strtotime("+1 month", strtotime($start_date))-1); - // } - // $vendors = $this->input->post("vendors"); - // test - $start_date = "2018-10-01"; - $end_date = "2018-10-31 23:59:59"; - $vendors = "1343,29188"; - // end test + $date_range = $this->input->post("date_range"); + preg_match_all('/\d{4}\-\d{2}\-\d{2}/', $date_range, $date_range_arr); + if (empty($date_range_arr[0])) { + return $this->settlement(); + } + $start_date = $date_range_arr[0][0]; + $end_date =$date_range_arr[0][1]; + if ($end_date == null) { + $end_date = date("Y-m-d H:i:s", strtotime("+1 month", strtotime($start_date))-1); + } + $vendors = $this->input->post("vendors"); $vendor_sourcetype = $this->trippest->vendor_sourcetype(); $result = array( - "trippest_order_vendor_money" => array() + "default_date1" => $start_date + ,"default_date2" => $end_date + ,"trippest_order_vendor_money" => array() ,"transfer_sum" => 0 + /** 列总计 */ + ,"col_sum" => array( + "trippest" => array( + "sum_trippest_cost" => 0 + ,"sum_vendor_cost" => 0 + ,"sum_trippest_sum" => 0 + ,"sum_vendor_sum" => 0 + ,"sum_profit" => 0 + ,"sum_trippest_profit" => 0 + ,"sum_vendor_profit" => 0 + ,"sum_payout" => 0 + ), + "vendor" => array( + "sum_trippest_cost" => 0 + ,"sum_vendor_cost" => 0 + ,"sum_trippest_sum" => 0 + ,"sum_vendor_sum" => 0 + ,"sum_profit" => 0 + ,"sum_trippest_profit" => 0 + ,"sum_vendor_profit" => 0 + ,"sum_payout" => 0 + ) + ) ); /** 团款 */ - foreach (explode(",", $vendors) as $key => $vendor) { + foreach ($vendors as $key => $vendor) { $sourcetype = $vendor_sourcetype[strval($vendor)]["sourcetype"]; $opi_summoney = $this->money_model->checked_group_list($vendor, $sourcetype, $start_date, $end_date); $ret = array( @@ -48,8 +76,7 @@ class Vendor_money extends CI_Controller { array( "trippest_sum" => 0, "vendor_sum" => 0, - "transfer_sum" => 0, - "trippest_order_vendor_money" => null + "transfer_sum" => 0 ) ); // 按照海纳的算法 @@ -79,8 +106,53 @@ class Vendor_money extends CI_Controller { $result["money"][strval($vendor)] = $ret; $result["money"][strval($vendor)]["vendor_code"] = $vendor; $result["money"][strval($vendor)]["vendor_name"] = $vendor_sourcetype[strval($vendor)]["vendor_name"]; + /** 团款合计 */ + $result['col_sum']['trippest']['sum_trippest_sum'] = bcadd($result['col_sum']['trippest']['sum_trippest_sum'], $ret["trippest"]['trippest_sum']); + $result['col_sum']['trippest']['sum_vendor_sum'] = bcadd($result['col_sum']['trippest']['sum_vendor_sum'], $ret["trippest"]['vendor_sum']); + $result['col_sum']['vendor']['sum_trippest_sum'] = bcadd($result['col_sum']['vendor']['sum_trippest_sum'], $ret["vendor"]['trippest_sum']); + $result['col_sum']['vendor']['sum_vendor_sum'] = bcadd($result['col_sum']['vendor']['sum_vendor_sum'], $ret["vendor"]['vendor_sum']); } /** 成本 */ + $vendors_cost = $this->money_model->vendor_cost(implode(',', $vendors), $start_date, $end_date); + foreach ($result['money'] as $km => &$vm) { + $vm['vendor_cost'] = $vm['trippest_cost'] = 0; + foreach ($vendors_cost as $kvc => $vvc) { + if (strval($vm['vendor_code']) === strval($vvc['vendor_code'])) { + $vm['vendor_cost'] = $vvc['vendor_cost']; + } + } + // 成本总计 + $result['col_sum']['trippest']['sum_trippest_cost'] = $result['col_sum']['vendor']['sum_trippest_cost'] = bcadd($result['col_sum']['trippest']['sum_trippest_cost'], $vm['trippest_cost']); + $result['col_sum']['trippest']['sum_vendor_cost'] = $result['col_sum']['vendor']['sum_vendor_cost'] = bcadd($result['col_sum']['trippest']['sum_vendor_cost'], $vm['vendor_cost']); + } + foreach ($result['money'] as $kmi => &$vmi) { + /** 利润 */ + $vmi['trippest']['total_profit'] = bcsub( + bcadd($vmi['trippest']['trippest_sum'], $vmi['trippest']['vendor_sum']), + bcadd($vmi['trippest_cost'], $vmi['vendor_cost'])); + $vmi['vendor']['total_profit'] = bcsub( + bcadd($vmi['vendor']['trippest_sum'], $vmi['vendor']['vendor_sum']), + bcadd($vmi['trippest_cost'], $vmi['vendor_cost'])); + /** 利润分成 */ + $vmi['trippest']['vendor_profit'] = bcmul($vmi['trippest']['total_profit'], $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]); + $vmi['trippest']['trippest_profit'] = bcmul($vmi['trippest']['total_profit'], bcsub(1, $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]) ); + $vmi['vendor']['vendor_profit'] = bcmul($vmi['vendor']['total_profit'], $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]); + $vmi['vendor']['trippest_profit'] = bcmul($vmi['vendor']['total_profit'], bcsub(1, $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]) ); + /** Trippest应付地接 */ + $vmi['trippest']['payout'] = bcsub(bcadd($vmi['vendor_cost'], $vmi['trippest']['vendor_profit'] ), $vmi['trippest']['vendor_sum']); + $vmi['vendor']['payout'] = bcsub(bcadd($vmi['vendor_cost'], $vmi['vendor']['vendor_profit'] ), $vmi['vendor']['vendor_sum']); + + /** 利润总计 */ + $result['col_sum']['trippest']['sum_profit'] = bcadd($result['col_sum']['trippest']['sum_profit'], $vmi['trippest']['total_profit']); + $result['col_sum']['trippest']['sum_trippest_profit'] = bcadd($result['col_sum']['trippest']['sum_trippest_profit'], $vmi['trippest']['trippest_profit']); + $result['col_sum']['trippest']['sum_vendor_profit'] = bcadd($result['col_sum']['trippest']['sum_vendor_profit'], $vmi['trippest']['vendor_profit']); + $result['col_sum']['vendor']['sum_profit'] = bcadd($result['col_sum']['vendor']['sum_profit'], $vmi['vendor']['total_profit']); + $result['col_sum']['vendor']['sum_trippest_profit'] = bcadd($result['col_sum']['vendor']['sum_trippest_profit'], $vmi['vendor']['trippest_profit']); + $result['col_sum']['vendor']['sum_vendor_profit'] = bcadd($result['col_sum']['vendor']['sum_vendor_profit'], $vmi['vendor']['vendor_profit']); + /** 应付总计 */ + $result['col_sum']['trippest']['sum_payout'] = bcadd($result['col_sum']['trippest']['sum_payout'], $vmi['trippest']['payout']); + $result['col_sum']['vendor']['sum_payout'] = bcadd($result['col_sum']['vendor']['sum_payout'], $vmi['vendor']['payout']); + } // return $this->output->set_content_type('application/json')->set_output(json_encode($result)); $this->load->view('vendor_money_sum', $result); return ; diff --git a/webht/third_party/trippestOrderSync/libraries/trippest.php b/webht/third_party/trippestOrderSync/libraries/trippest.php index 808089b4..d52ed3dd 100644 --- a/webht/third_party/trippestOrderSync/libraries/trippest.php +++ b/webht/third_party/trippestOrderSync/libraries/trippest.php @@ -81,21 +81,25 @@ class Trippest "1343" => array( "sourcetype" => "32090" ,"vendor_name" => "北京图兰朵" + ,"profit_rate" => 0.4 ) // 上海图兰朵 ,"29188" => array( "sourcetype" => "32112" ,"vendor_name" => "上海图兰朵" + ,"profit_rate" => 0.4 ) // 西安图兰朵 ,"30548" => array( "sourcetype" => "32116" ,"vendor_name" => "西安图兰朵" + ,"profit_rate" => 0.4 ) // 桂林地接 ,"628" => array( "sourcetype" => "32122" ,"vendor_name" => "桂林地接" + ,"profit_rate" => 0.4 ) ); } diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php index 94692648..9345ac0d 100644 --- a/webht/third_party/trippestOrderSync/models/vendor_money_model.php +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -113,11 +113,34 @@ class Vendor_money_model extends CI_Model { ) ORDER BY cgi.CGI_ArriveDate "; $query = $this->HT->query($sql); -// log_message('error',$sql); -// log_message('error',var_export($query->result_array(), 1)); return $query->result_array(); } + public function vendor_cost($vendor_str, $start_date, $end_date) + { + $sql = "SELECT group_cost.GCI_VEI_SN vendor_code, + SUM(group_cost.cost) vendor_cost + FROM + (SELECT DISTINCT gci.GCI_combineNo, + (SELECT SUM(CONVERT(float, gcod.GCOD_sumMoney)) + FROM GroupCombineOperationDetail gcod + WHERE gcod.GCOD_GCI_combineNo=GCI_combineNo + AND gcod.GCOD_operationType <> 'otherReceives' ) AS cost , + GCI_VEI_SN + FROM GroupCombineInfo gci + WHERE 1=1 + AND GCI_VEI_SN IN ($vendor_str) + AND EXISTS + ( SELECT 1 + FROM CK_GroupInfo + WHERE CGI_Checked=1 + AND CGI_GRI_SN=GCI_GRI_SN + AND CGI_ArriveDate BETWEEN '$start_date' AND '$end_date') + ) AS group_cost + GROUP BY group_cost.GCI_VEI_SN"; + $query = $this->HT->query($sql); + return $query->result_array(); + } } diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php index c5868696..651da1d7 100644 --- a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -6,7 +6,7 @@ <!DOCTYPE html> <html> <head> - <title>Trippest账单结算</title> + <title>Trippest &amp; 地接账单结算</title> <meta charset="utf-8"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> @@ -15,13 +15,17 @@ <meta name="referrer" content="always"> <link href="http://www.mycht.cn/css/webht/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="http://www.mycht.cn/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css" /> - <!-- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> --> - <?php // include 'flatpickr.css.php'; ?> + <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css"> + <!-- <?php // include 'flatpickr.css.php'; ?> --> <style type="text/css"> form{border-bottom: 1px solid #ccc;} .navbar-header h1{display: inline-block;margin-left: 30px;margin-right: 30px;} label {display: inline-block;max-width: none;margin-bottom: 5px;font-weight: bold; } .form-check-label{font-weight: normal; margin-left: 5px;} + thead th {text-align: center;} + tbody td {text-align: right;} + .text-left {text-align: left;} + .text-bold {font-weight: bold;} </style> </head> <body> @@ -30,30 +34,30 @@ <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> - <h1>Trippest账单结算</h1> + <h1>Trippest &amp; 地接账单结算</h1> </div> </div> <div class="container-fluid"> <p></p> - <form action="" method="POST" role="form"> + <form action="/webht.php/apps/trippestordersync/vendor_money/index" method="POST" role="form"> <div class="form-group row"> <label for="" class="col-md-2">地接社</label> <div class=""> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="1343">北京图兰朵</label> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="29188">上海图兰朵</label> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="30548">西安图兰朵</label> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="628">桂林地接</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="1343" checked>北京图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="29188" checked>上海图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="30548" checked>西安图兰朵</label> + <!-- <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="628">桂林地接</label> --> </div> </div> <div class="form-group row"> <label for="" class="col-md-2">发团日期</label> - <div class="col-md-3"> - <input type="text" class="form-control" id="" placeholder="开始日期" required> + <div class="col-md-6"> + <input type="text" class="form-control" name="date_range" id="date_range" placeholder="选择日期范围" required> </div> <div class="col-md-3"> - <input type="text" class="form-control" id="" placeholder="结束日期"> + <!-- <input type="text" class="form-control" id="end_date" placeholder="结束日期"> --> + <button type="submit" class="btn btn-primary">Submit</button> </div> - <button type="submit" class="btn btn-primary">Submit</button> </div> </form> <p></p> @@ -63,16 +67,16 @@ <th rowspan="2">目的地</th> <th colspan="2">总营收</th> <th colspan="2">总成本</th> - <th rowspan="2">利润</th> - <th rowspan="2">海纳利润</th> - <th rowspan="2">地接利润</th> - <th rowspan="2">海纳应付地接</th> + <th rowspan="2">⑤利润</th> + <th rowspan="2">⑥海纳利润</th> + <th rowspan="2">⑦地接利润</th> + <th rowspan="2">⑧海纳应付地接</th> </tr> <tr> - <th >海纳代收</th> - <th >地接代收</th> - <th rowspan="2">海纳成本</th> - <th rowspan="2">地接成本</th> + <th >①海纳代收</th> + <th >②地接代收</th> + <th rowspan="2">③海纳成本</th> + <th rowspan="2">④地接成本</th> </tr> </thead> <tbody> @@ -80,36 +84,51 @@ foreach ($money as $kt => $trippest) { ?> <tr> - <td><?php echo $trippest['vendor_name'] ?></td> + <td class="text-left"><?php echo $trippest['vendor_name'] ?></td> <td><?php echo $trippest['trippest']['trippest_sum'] ?></td> <td><?php echo $trippest['trippest']['vendor_sum'] ?></td> - <td></td> - <td></td> - <td></td> - <td></td> - <td></td> - <td></td> + <td><?php echo $trippest['trippest_cost'] ?></td> + <td><?php echo $trippest['vendor_cost'] ?></td> + <td><?php echo $trippest['trippest']['total_profit'] ?></td> + <td><?php echo $trippest['trippest']['trippest_profit'] ?></td> + <td><?php echo $trippest['trippest']['vendor_profit'] ?></td> + <td><?php echo $trippest['trippest']['payout'] ?></td> </tr> <?php } } ?> + <?php if ( ! empty($col_sum)) { + ?> + <tr class="text-bold"> + <td class="text-left">合计</td> + <td><?php echo $col_sum['trippest']['sum_trippest_sum'] ?></td> + <td><?php echo $col_sum['trippest']['sum_vendor_sum'] ?></td> + <td><?php echo $col_sum['trippest']['sum_trippest_cost'] ?></td> + <td><?php echo $col_sum['trippest']['sum_vendor_cost'] ?></td> + <td><?php echo $col_sum['trippest']['sum_profit'] ?></td> + <td><?php echo $col_sum['trippest']['sum_trippest_profit'] ?></td> + <td><?php echo $col_sum['trippest']['sum_vendor_profit'] ?></td> + <td><?php echo $col_sum['trippest']['sum_payout'] ?></td> + </tr> + <?php } ?> </tbody> </table> + <p>旧的算法, 需扣除Trippest自营订单的地接代收款项:</p> <table class="table table-bordered table-hover"> <thead> <tr> <th rowspan="2">目的地</th> <th colspan="2">总营收</th> <th colspan="2">总成本</th> - <th rowspan="2">利润</th> - <th rowspan="2">海纳利润</th> - <th rowspan="2">地接利润</th> - <th rowspan="2">海纳应付地接</th> + <th rowspan="2">⑤利润</th> + <th rowspan="2">⑥海纳利润</th> + <th rowspan="2">⑦地接利润</th> + <th rowspan="2">⑧海纳应付地接</th> </tr> <tr> - <th >海纳代收</th> - <th >地接代收</th> - <th rowspan="2">海纳成本</th> - <th rowspan="2">地接成本</th> + <th >①海纳代收</th> + <th >②地接代收</th> + <th rowspan="2">③海纳成本</th> + <th rowspan="2">④地接成本</th> </tr> </thead> <tbody> @@ -117,38 +136,60 @@ foreach ($money as $kv => $vendor) { ?> <tr> - <td><?php echo $vendor['vendor_name'] ?></td> + <td class="text-left"><?php echo $vendor['vendor_name'] ?></td> <td><?php echo $vendor['vendor']['trippest_sum'] ?></td> <td><?php echo $vendor['vendor']['vendor_sum'] ?></td> - <td></td> - <td></td> - <td></td> - <td></td> - <td></td> - <td></td> + <td><?php echo $vendor['trippest_cost'] ?></td> + <td><?php echo $vendor['vendor_cost'] ?></td> + <td><?php echo $vendor['vendor']['total_profit'] ?></td> + <td><?php echo $vendor['vendor']['trippest_profit'] ?></td> + <td><?php echo $vendor['vendor']['vendor_profit'] ?></td> + <td><?php echo $vendor['vendor']['payout'] ?></td> </tr> <?php } } ?> + <?php if ( ! empty($col_sum)) { + ?> + <tr class="text-bold"> + <td class="text-left">合计</td> + <td><?php echo $col_sum['vendor']['sum_trippest_sum'] ?></td> + <td><?php echo $col_sum['vendor']['sum_vendor_sum'] ?></td> + <td><?php echo $col_sum['vendor']['sum_trippest_cost'] ?></td> + <td><?php echo $col_sum['vendor']['sum_vendor_cost'] ?></td> + <td><?php echo $col_sum['vendor']['sum_profit'] ?></td> + <td><?php echo $col_sum['vendor']['sum_trippest_profit'] ?></td> + <td><?php echo $col_sum['vendor']['sum_vendor_profit'] ?></td> + <td><?php echo $col_sum['vendor']['sum_payout'] ?></td> + </tr> + <?php } ?> <?php if ( ! empty($trippest_order_vendor_money)) { ?> - <tr> + <tr class="text-bold"> <th colspan="2">团号</th> <th colspan="7">应扣除地接收款: 总计 <?php echo $transfer_sum ?></th> </tr> <?php foreach ($trippest_order_vendor_money as $ko => $order) { ?> <tr> - <td colspan="2"><?php echo $order['COLI_GroupCode'] ?></td> - <td colspan="7"><?php echo $order["vendor_sum"] ?></td> + <td colspan="2" class="text-left"><?php echo $order['COLI_GroupCode'] ?></td> + <td colspan="7" class="text-left"><?php echo $order["vendor_sum"] ?></td> </tr> <?php } } ?> </tbody> </table> </div> </body> -<script src="/js/jquery.min.js&v=20170811" type="text/javascript"></script> +<script src="/js/jquery.min.js" type="text/javascript"></script> <script src="/js/bootstrap.min.js" type="text/javascript"></script> -<script src="/js/bootstrap-datetimepicker.min.js" type="text/javascript"></script> -<script src="/js/jquery.form.min.js" type="text/javascript"></script> - +<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script> +<script type="text/javascript"> + $(document).ready(function() { + $("#date_range").flatpickr({ + dateFormat: 'Y-m-d' + ,mode: 'range' + ,allowInput: true + ,defaultDate:['<?php echo $default_date1 ?>', '<?php echo $default_date2 ?>'] + }); + }) +</script> </html> From 2b568e740a1b4719c6fcc55225a3dbd59552b248 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 6 Mar 2019 10:28:14 +0800 Subject: [PATCH 253/382] =?UTF-8?q?Trippest=20=E8=B4=A6=E5=8D=95=E8=AE=A1?= =?UTF-8?q?=E7=AE=97=E6=B1=87=E6=80=BB=E8=A1=A8=E6=A0=BC:=20=E5=9C=B0?= =?UTF-8?q?=E6=8E=A5=E9=80=89=E6=8B=A9=E8=BE=93=E5=87=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/vendor_money.php | 3 +++ .../trippestOrderSync/libraries/trippest.php | 10 +++++----- .../trippestOrderSync/views/vendor_money_sum.php | 6 +++--- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index 72c85bdf..eb7b2164 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -16,6 +16,8 @@ class Vendor_money extends CI_Controller { { $data['default_date1'] = date('Y-m-01', strtotime("last month")); $data['default_date2'] = date('Y-m-d', mktime(0,0,0,date('m'),1,date('Y'))-1); + $vendor_sourcetype = $this->trippest->vendor_sourcetype(); + $data['default_vendor'] = array_keys($vendor_sourcetype); $this->load->view('vendor_money_sum', $data); } @@ -36,6 +38,7 @@ class Vendor_money extends CI_Controller { $result = array( "default_date1" => $start_date ,"default_date2" => $end_date + ,"default_vendor" => $vendors ,"trippest_order_vendor_money" => array() ,"transfer_sum" => 0 /** 列总计 */ diff --git a/webht/third_party/trippestOrderSync/libraries/trippest.php b/webht/third_party/trippestOrderSync/libraries/trippest.php index d52ed3dd..220f243a 100644 --- a/webht/third_party/trippestOrderSync/libraries/trippest.php +++ b/webht/third_party/trippestOrderSync/libraries/trippest.php @@ -96,11 +96,11 @@ class Trippest ,"profit_rate" => 0.4 ) // 桂林地接 - ,"628" => array( - "sourcetype" => "32122" - ,"vendor_name" => "桂林地接" - ,"profit_rate" => 0.4 - ) + // ,"628" => array( + // "sourcetype" => "32122" + // ,"vendor_name" => "桂林地接" + // ,"profit_rate" => 0.4 + // ) ); } diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php index 651da1d7..711d1439 100644 --- a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -43,9 +43,9 @@ <div class="form-group row"> <label for="" class="col-md-2">地接社</label> <div class=""> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="1343" checked>北京图兰朵</label> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="29188" checked>上海图兰朵</label> - <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="30548" checked>西安图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="1343" <?php if(in_array(1343, $default_vendor)) { ?>checked<?php } ?> >北京图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="29188" <?php if(in_array(29188, $default_vendor)) { ?>checked<?php } ?>>上海图兰朵</label> + <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="30548" <?php if(in_array(30548, $default_vendor)) { ?>checked<?php } ?>>西安图兰朵</label> <!-- <label class="form-check-label"><input type="checkbox" class="" name="vendors[]" id="" value="628">桂林地接</label> --> </div> </div> From fae01a2a0eafe7a671502341c2d3516e2cd21995 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 6 Mar 2019 15:04:28 +0800 Subject: [PATCH 254/382] =?UTF-8?q?Trippest=20=E8=B4=A6=E5=8D=95=E7=BB=93?= =?UTF-8?q?=E7=AE=97=E8=A1=A8=E6=A0=BC:=E5=88=97=E5=87=BA=E9=9D=9E?= =?UTF-8?q?=E5=8C=85=E4=BB=B7=E4=BA=A7=E5=93=81=E4=B8=94=E9=9D=9E=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E4=BE=9B=E5=BA=94=E5=95=86=E6=8E=A5=E5=BE=85=E7=9A=84?= =?UTF-8?q?=E6=8A=A5=E4=BB=B7=E6=80=BB=E9=A2=9D,=20=E4=B8=8D=E8=AE=A1?= =?UTF-8?q?=E5=85=A5=E8=AE=A1=E7=AE=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/vendor_money.php | 22 ++++++++++--- .../models/vendor_money_model.php | 13 +++++--- .../views/vendor_money_sum.php | 33 ++++++++++++++++--- 3 files changed, 54 insertions(+), 14 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index eb7b2164..52a2df32 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -15,7 +15,7 @@ class Vendor_money extends CI_Controller { public function settlement() { $data['default_date1'] = date('Y-m-01', strtotime("last month")); - $data['default_date2'] = date('Y-m-d', mktime(0,0,0,date('m'),1,date('Y'))-1); + $data['default_date2'] = date('Y-m-d H:i:s', mktime(0,0,0,date('m'),1,date('Y'))-1); $vendor_sourcetype = $this->trippest->vendor_sourcetype(); $data['default_vendor'] = array_keys($vendor_sourcetype); $this->load->view('vendor_money_sum', $data); @@ -29,7 +29,7 @@ class Vendor_money extends CI_Controller { return $this->settlement(); } $start_date = $date_range_arr[0][0]; - $end_date =$date_range_arr[0][1]; + $end_date =$date_range_arr[0][1] . " 23:59:59"; if ($end_date == null) { $end_date = date("Y-m-d H:i:s", strtotime("+1 month", strtotime($start_date))-1); } @@ -52,6 +52,7 @@ class Vendor_money extends CI_Controller { ,"sum_trippest_profit" => 0 ,"sum_vendor_profit" => 0 ,"sum_payout" => 0 + ,"sum_other" => 0 ), "vendor" => array( "sum_trippest_cost" => 0 @@ -62,24 +63,27 @@ class Vendor_money extends CI_Controller { ,"sum_trippest_profit" => 0 ,"sum_vendor_profit" => 0 ,"sum_payout" => 0 + ,"sum_other" => 0 ) ) ); /** 团款 */ foreach ($vendors as $key => $vendor) { $sourcetype = $vendor_sourcetype[strval($vendor)]["sourcetype"]; - $opi_summoney = $this->money_model->checked_group_list($vendor, $sourcetype, $start_date, $end_date); + $opi_summoney = $this->money_model->checked_group_list($vendor, $sourcetype, $start_date, $end_date, implode(',', $vendors)); $ret = array( "trippest" => array( "trippest_sum" => 0, - "vendor_sum" => 0 + "vendor_sum" => 0, + "other_sum" => 0 ), "vendor" => array( "trippest_sum" => 0, "vendor_sum" => 0, - "transfer_sum" => 0 + "transfer_sum" => 0, + "other_sum" => 0 ) ); // 按照海纳的算法 @@ -90,6 +94,8 @@ class Vendor_money extends CI_Controller { if (floatval($opi_money['trippest_sum']) > 0) { $ret["trippest"]['trippest_sum'] = bcadd(floatval($ret["trippest"]['trippest_sum']), floatval($opi_money['trippest_sum'])) ; } + $ret['trippest']['other_sum'] = bcadd($ret['trippest']['other_sum'], $opi_money['other_price_sum']); + $ret["trippest"]['trippest_sum'] = bcsub($ret["trippest"]['trippest_sum'], $opi_money['other_price_sum']); } // 按照图兰朵算法: Trippest自营订单的代收算在海纳收款 foreach ($opi_summoney as $kv => $opi_money_v) { @@ -99,6 +105,8 @@ class Vendor_money extends CI_Controller { $ret["vendor"]['trippest_sum'] = bcadd(floatval($ret["vendor"]['trippest_sum']), floatval($opi_money_v['trippest_sum'])) ; $ret["vendor"]['trippest_sum'] = bcadd(floatval($ret["vendor"]['trippest_sum']), floatval($opi_money_v['vendor_sum'])) ; } + $ret['vendor']['other_sum'] = bcadd($ret['vendor']['other_sum'], $opi_money_v['other_price_sum']); + $ret["vendor"]['trippest_sum'] = bcsub($ret["vendor"]['trippest_sum'], $opi_money_v['other_price_sum']); } $ret["vendor"]["transfer_sum"] = bcsub($ret["vendor"]['vendor_sum'], $ret["trippest"]['vendor_sum']); if ($ret["vendor"]["transfer_sum"] != 0) { @@ -112,8 +120,11 @@ class Vendor_money extends CI_Controller { /** 团款合计 */ $result['col_sum']['trippest']['sum_trippest_sum'] = bcadd($result['col_sum']['trippest']['sum_trippest_sum'], $ret["trippest"]['trippest_sum']); $result['col_sum']['trippest']['sum_vendor_sum'] = bcadd($result['col_sum']['trippest']['sum_vendor_sum'], $ret["trippest"]['vendor_sum']); + $result['col_sum']['trippest']['sum_other'] = bcadd($result['col_sum']['trippest']['sum_other'], $ret['trippest']['other_sum']); + $result['col_sum']['vendor']['sum_trippest_sum'] = bcadd($result['col_sum']['vendor']['sum_trippest_sum'], $ret["vendor"]['trippest_sum']); $result['col_sum']['vendor']['sum_vendor_sum'] = bcadd($result['col_sum']['vendor']['sum_vendor_sum'], $ret["vendor"]['vendor_sum']); + $result['col_sum']['vendor']['sum_other'] = bcadd($result['col_sum']['vendor']['sum_other'], $ret['vendor']['other_sum']); } /** 成本 */ $vendors_cost = $this->money_model->vendor_cost(implode(',', $vendors), $start_date, $end_date); @@ -149,6 +160,7 @@ class Vendor_money extends CI_Controller { $result['col_sum']['trippest']['sum_profit'] = bcadd($result['col_sum']['trippest']['sum_profit'], $vmi['trippest']['total_profit']); $result['col_sum']['trippest']['sum_trippest_profit'] = bcadd($result['col_sum']['trippest']['sum_trippest_profit'], $vmi['trippest']['trippest_profit']); $result['col_sum']['trippest']['sum_vendor_profit'] = bcadd($result['col_sum']['trippest']['sum_vendor_profit'], $vmi['trippest']['vendor_profit']); + $result['col_sum']['vendor']['sum_profit'] = bcadd($result['col_sum']['vendor']['sum_profit'], $vmi['vendor']['total_profit']); $result['col_sum']['vendor']['sum_trippest_profit'] = bcadd($result['col_sum']['vendor']['sum_trippest_profit'], $vmi['vendor']['trippest_profit']); $result['col_sum']['vendor']['sum_vendor_profit'] = bcadd($result['col_sum']['vendor']['sum_vendor_profit'], $vmi['vendor']['vendor_profit']); diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php index 9345ac0d..689984dc 100644 --- a/webht/third_party/trippestOrderSync/models/vendor_money_model.php +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -10,16 +10,18 @@ class Vendor_money_model extends CI_Model { bcscale(4); } - public function checked_group_list($vendor, $sourcetype, $start_date, $end_date) + public function checked_group_list($vendor, $sourcetype, $start_date, $end_date, $all_vendor) { - $sql = "SELECT sum_opi.COLI_OPI_ID,sum(sum_opi.海纳收款) as trippest_sum,sum(sum_opi.地接社收款) as vendor_sum + $sql = "SELECT sum_opi.COLI_OPI_ID,sum(sum_opi.海纳收款) as trippest_sum,sum(sum_opi.地接社收款) as vendor_sum, + sum(sum_opi.other_price_RMB) as other_price_sum from ( SELECT (select isnull(SUM(COLD_TotalPrice),0) from BIZ_ConfirmLineDetail cold where cold.COLD_COLI_SN=cgi_group.COLI_SN - and COLD_ServiceType='D' - and COLD_PlanVEI_SN=$vendor - )*cgi_group.汇率 as cold_price_RMB, + and COLD_ServiceType <> 'D' + and COLD_PlanVEI_SN NOT IN ($all_vendor) + and cold.DeleteFlag=0 + )*cgi_group.汇率 as other_price_RMB, * from ( select @@ -27,6 +29,7 @@ class Vendor_money_model extends CI_Model { (select COUNT(0) from BIZ_ConfirmLineDetail where COLD_COLI_SN=COLI_SN and COLD_ServiceType='D' + and DeleteFlag=0 ) as service_cnt, COLI.COLI_sourcetype, COLI.COLI_Price, diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php index 711d1439..23df7e61 100644 --- a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -24,7 +24,9 @@ .form-check-label{font-weight: normal; margin-left: 5px;} thead th {text-align: center;} tbody td {text-align: right;} + .bg-grey {background-color: #f5f5f5;} .text-left {text-align: left;} + .text-right {text-align: right;} .text-bold {font-weight: bold;} </style> </head> @@ -94,12 +96,24 @@ <td><?php echo $trippest['trippest']['vendor_profit'] ?></td> <td><?php echo $trippest['trippest']['payout'] ?></td> </tr> - <?php } - } ?> + <?php + if ($trippest['trippest']['other_sum'] > 0) { + ?> + <tr class="bg-grey"> + <td >非包价产品的收款 <br></td> + <td ><?php echo $trippest['trippest']['other_sum'] ?></td> + <td colspan="7"></td> + </tr> + <?php + } + ?> + <?php + } + } ?> <?php if ( ! empty($col_sum)) { ?> <tr class="text-bold"> - <td class="text-left">合计</td> + <td class="text-left">合计(仅包价产品)</td> <td><?php echo $col_sum['trippest']['sum_trippest_sum'] ?></td> <td><?php echo $col_sum['trippest']['sum_vendor_sum'] ?></td> <td><?php echo $col_sum['trippest']['sum_trippest_cost'] ?></td> @@ -146,12 +160,23 @@ <td><?php echo $vendor['vendor']['vendor_profit'] ?></td> <td><?php echo $vendor['vendor']['payout'] ?></td> </tr> + <?php + if ($vendor['vendor']['other_sum'] > 0) { + ?> + <tr class="bg-grey"> + <td >非包价产品的收款 <br></td> + <td ><?php echo $vendor['vendor']['other_sum'] ?></td> + <td colspan="7"></td> + </tr> + <?php + } + ?> <?php } } ?> <?php if ( ! empty($col_sum)) { ?> <tr class="text-bold"> - <td class="text-left">合计</td> + <td class="text-left">合计(仅包价产品)</td> <td><?php echo $col_sum['vendor']['sum_trippest_sum'] ?></td> <td><?php echo $col_sum['vendor']['sum_vendor_sum'] ?></td> <td><?php echo $col_sum['vendor']['sum_trippest_cost'] ?></td> From d5955d129919c282c1a83090075b4fcab8c37601 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 6 Mar 2019 16:32:50 +0800 Subject: [PATCH 255/382] =?UTF-8?q?=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95?= =?UTF-8?q?=E9=A1=B5=E9=9D=A2=E4=BB=A5=E5=8F=8A=E7=9B=B8=E5=85=B3=E7=9A=84?= =?UTF-8?q?=E5=8A=9F=E8=83=BD=E9=A1=B9=E5=A2=9E=E5=8A=A0=E8=A6=81=E6=B1=82?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=AE=BE=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 3 +++ webht/third_party/pay/controllers/iPayLinksService.php | 5 +++++ webht/third_party/pay/views/alipay_list.php | 6 ++++++ webht/third_party/pay/views/iPayLinks_list.php | 9 ++++++++- webht/third_party/pay/views/iPayLinks_list2.php | 9 ++++++++- webht/third_party/paypal/controllers/index.php | 4 ++++ 6 files changed, 34 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 431ea289..808c6b0c 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -616,6 +616,7 @@ var_dump($response->$responseNode); public function note_list() { + $this->permission->is_admin(true); $data = array(); $data["paytext"] = $this->payment_status(); $data["keywords"] = $this->input->get_post("keywords"); @@ -631,6 +632,7 @@ var_dump($response->$responseNode); } //失败记录列表 public function note_faillist() { + $this->permission->is_admin(true); $data = array(); $data["paytext"] = $this->payment_status(); //有关键词则不限制日期 @@ -652,6 +654,7 @@ var_dump($response->$responseNode); //获取note详情,以便后续修改各项数据 public function note_modal($pn_txn_id = false, $pn_invoice = false ,$notice_time = false) { + $this->permission->is_admin(true); $data = array(); $data['IPL_orderId'] = $pn_invoice; if (!empty($pn_txn_id)) { diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index f1f5bff1..c953e061 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -62,6 +62,7 @@ class IPayLinksService extends CI_Controller public function note_list2() { + $this->permission->is_admin(true); $data = array(); $data["paytext"] = $this->payment_status(); $data["keywords"] = $this->input->get_post("keywords"); @@ -78,6 +79,7 @@ class IPayLinksService extends CI_Controller public function note_list() { + $this->permission->is_admin(true); $data = array(); $data["paytext"] = $this->payment_status(); $data["keywords"] = $this->input->get_post("keywords"); @@ -94,6 +96,7 @@ class IPayLinksService extends CI_Controller //失败记录列表 public function note_faillist() { + $this->permission->is_admin(true); $data = array(); $data["paytext"] = $this->payment_status(); //有关键词则不限制日期 @@ -952,6 +955,7 @@ class IPayLinksService extends CI_Controller public function gai_modal($pn_txn_id=null, $pn_invoice=null, $pn_id = null, $neworder=null) { + $this->permission->is_admin(true); $data = array(); $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); $orderid_info = $this->analysis_orderid($pn_invoice); @@ -1035,6 +1039,7 @@ class IPayLinksService extends CI_Controller //获取note详情,以便后续修改各项数据 public function note_modal($pn_txn_id = false, $pn_invoice = false, $pn_id = null) { + $this->permission->is_admin(true); $data = array(); $data['IPL_orderId'] = $pn_invoice; if (!empty($pn_txn_id)) { diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php index c55ceead..d3a9c1ad 100644 --- a/webht/third_party/pay/views/alipay_list.php +++ b/webht/third_party/pay/views/alipay_list.php @@ -76,6 +76,12 @@ </a> <h1>Alipay Notes</h1> <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> </ul> </div> </div> diff --git a/webht/third_party/pay/views/iPayLinks_list.php b/webht/third_party/pay/views/iPayLinks_list.php index b97c0a80..bd101cac 100644 --- a/webht/third_party/pay/views/iPayLinks_list.php +++ b/webht/third_party/pay/views/iPayLinks_list.php @@ -75,9 +75,16 @@ </div> <button type="submit" class="btn btn-primary">Export</button> </form> - </div> </div> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> + </ul> </div> <div id="content"> <div class="container-fluid marginTop"> diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index 6e42ff6a..0a981772 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -105,8 +105,15 @@ </div> <button type="submit" class="btn btn-primary">Export</button> </form> - </div> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> + </ul> </div> </div> <div id="content"> diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index ec3f6458..92000511 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -896,6 +896,7 @@ class Index extends CI_Controller { //所有记录列表 public function note_list() { + $this->permission->is_admin(true); $data = array(); //有关键词则不限制日期 $data['search_key'] = $this->input->post('search_key'); @@ -920,6 +921,7 @@ class Index extends CI_Controller { //所有记录列表 public function note_faillist() { + $this->permission->is_admin(true); $data = array(); //有关键词则不限制日期 $data['search_key'] = $this->input->post('search_key'); @@ -933,6 +935,7 @@ class Index extends CI_Controller { //获取note详情,修改各项数据 public function note_modal($pn_txn_id, $pn_invoice = false) { + $this->permission->is_admin(true); $data = array(); $data['pn_invoice'] = $pn_invoice; if (!empty($pn_txn_id)) { @@ -1161,6 +1164,7 @@ class Index extends CI_Controller { /** 查看收款记录的是否已录入到订单 */ public function gai_modal($pn_txn_id=null, $pn_id = null, $neworder=null) { + $this->permission->is_admin(true); $data = array(); $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); $orderid_info = $this->analysis_orderid($data['note']->pn_invoice); From bcfd3b3fcc0364c9cb4ccfa9de088c3f936c78a6 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 6 Mar 2019 16:41:28 +0800 Subject: [PATCH 256/382] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=A6=81=E6=B1=82?= =?UTF-8?q?=E7=99=BB=E5=BD=95=E8=AE=BE=E7=BD=AE,=20=E4=BD=BF=E7=94=A8HT?= =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E7=99=BB=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/send_operation.php | 1 + .../trippestOrderSync/controllers/vendor_money.php | 1 + webht/third_party/trippestOrderSync/views/sms_log.php | 8 ++++++++ .../trippestOrderSync/views/vendor_money_sum.php | 8 ++++++++ 4 files changed, 18 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/send_operation.php b/webht/third_party/trippestOrderSync/controllers/send_operation.php index 548da41e..1e209562 100644 --- a/webht/third_party/trippestOrderSync/controllers/send_operation.php +++ b/webht/third_party/trippestOrderSync/controllers/send_operation.php @@ -25,6 +25,7 @@ class Send_operation extends CI_Controller { public function sms_log() { + $this->permission->is_admin(true); $date = $this->input->get_post("date"); $date = $date ? $date : date('Y-m-d', strtotime("+1 day")); $ready_order["date"] = $date; diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index 52a2df32..9aa2cf22 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -23,6 +23,7 @@ class Vendor_money extends CI_Controller { public function index() { + $this->permission->is_admin(true); $date_range = $this->input->post("date_range"); preg_match_all('/\d{4}\-\d{2}\-\d{2}/', $date_range, $date_range_arr); if (empty($date_range_arr[0])) { diff --git a/webht/third_party/trippestOrderSync/views/sms_log.php b/webht/third_party/trippestOrderSync/views/sms_log.php index 0f36160c..f991bce2 100644 --- a/webht/third_party/trippestOrderSync/views/sms_log.php +++ b/webht/third_party/trippestOrderSync/views/sms_log.php @@ -57,6 +57,14 @@ <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>SMS Log</h1> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> + </ul> </div> </div> <div id="content"> diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php index 23df7e61..18aefdfe 100644 --- a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -37,6 +37,14 @@ <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>Trippest &amp; 地接账单结算</h1> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> + </ul> </div> </div> <div class="container-fluid"> From c3bd8247b1d557851f9711a3784eda391701b55e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 13 Mar 2019 13:28:24 +0800 Subject: [PATCH 257/382] paypal note log --- webht/third_party/paypal/controllers/index.php | 3 +++ 1 file changed, 3 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 92000511..5d6ce854 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -570,6 +570,7 @@ class Index extends CI_Controller { //存储paypal发送的消息 public function paypal_note() { $pn_txn_id = $this->input->post('txn_id'); + log_message('error','paypal-note: ' . $pn_txn_id); $pn_invoice = $this->input->post('invoice'); empty($pn_invoice) ? $pn_invoice = $this->input->post('transaction_subject') : false; @@ -602,10 +603,12 @@ class Index extends CI_Controller { //把PDT时间转成GMT时间 $pn_payment_date = gmdate('Y-m-d H:i:s', strtotime($pn_payment_date)); $this->Note_model->save_paypal_note($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo); + log_message('error','paypal-note-succeed ' . $pn_txn_id . ' # ' . $pn_invoice); echo 'ok'; } else { echo 'no'; } + return ; } //解析出订单号 From a6371459f78c94894c5fc0540da79ae6869fa9ea Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 13 Mar 2019 14:39:10 +0800 Subject: [PATCH 258/382] =?UTF-8?q?Trippest=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E4=BF=A1=E6=81=AF=E9=A1=B5=E9=9D=A2:=E9=9A=90?= =?UTF-8?q?=E8=97=8F=E5=AE=A2=E4=BA=BA=E5=85=A8=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index 9401ca01..bf58bf84 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -94,7 +94,9 @@ class Api extends CI_Controller { $operation_tmp['tour_name'] = $code_name; } // 领队名字 - $operation_tmp['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // $operation_tmp['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + $operation_tmp['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $operation_tmp['leader_name'] = trim($operation_tmp['leader_name']); // 行程人数 $operation_tmp['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; $operation_tmp['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; @@ -256,7 +258,9 @@ class Api extends CI_Controller { $vro['tour_name'] = $code_name; } // 领队名字 - $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // $vro['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + $vro['leader_name'] = substr_replace($poi->GUT_FirstName, str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2), 1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $vro['leader_name'] = trim($vro['leader_name']); // 行程人数 $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; @@ -323,7 +327,9 @@ class Api extends CI_Controller { $vro['tour_name'] = $code_name; } // 领队名字 - $vro['leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + // $vro['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); + $vro['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $vro['leader_name'] = trim($vro['leader_name']); // 行程人数 $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; $vro['personNum_text'] .= " (" . $poi->COLD_PersonNum . " Adult(s)"; From fc97b0a1c55a45eb1024300fe2226928996d5b6c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 13 Mar 2019 14:59:00 +0800 Subject: [PATCH 259/382] =?UTF-8?q?Trippest=E5=AE=A2=E4=BA=BA=E6=9F=A5?= =?UTF-8?q?=E8=AF=A2=E4=BF=A1=E6=81=AF=E9=A1=B5=E9=9D=A2:=E9=9A=90?= =?UTF-8?q?=E8=97=8F=E5=AE=A2=E4=BA=BA=E5=85=A8=E5=90=8D;=20*=E7=9A=84?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E6=AC=A1=E6=95=B0bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/api.php | 29 ++++++++++++++++--- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/api.php b/webht/third_party/trippestOrderSync/controllers/api.php index bf58bf84..f235f9a6 100644 --- a/webht/third_party/trippestOrderSync/controllers/api.php +++ b/webht/third_party/trippestOrderSync/controllers/api.php @@ -1,6 +1,6 @@ <?php defined('BASEPATH') OR exit('No direct script access allowed'); - +error_reporting(0); class Api extends CI_Controller { public function __construct(){ @@ -95,7 +95,14 @@ class Api extends CI_Controller { } // 领队名字 // $operation_tmp['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); - $operation_tmp['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $replace_cnt1 = $replace_cnt2 = 0; + if (mb_strlen($poi->GUT_FirstName, 'UTF-8') > 2) { + $replace_cnt1 = mb_strlen($poi->GUT_FirstName, 'UTF-8')-2; + } + if (mb_strlen($poi->GUT_LastName, 'UTF-8') > 2) { + $replace_cnt2 = mb_strlen($poi->GUT_LastName, 'UTF-8')-2; + } + $operation_tmp['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', $replace_cnt1),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', $replace_cnt2),1,-1); $operation_tmp['leader_name'] = trim($operation_tmp['leader_name']); // 行程人数 $operation_tmp['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; @@ -259,7 +266,14 @@ class Api extends CI_Controller { } // 领队名字 // $vro['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); - $vro['leader_name'] = substr_replace($poi->GUT_FirstName, str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2), 1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $replace_cnt1 = $replace_cnt2 = 0; + if (mb_strlen($poi->GUT_FirstName, 'UTF-8') > 2) { + $replace_cnt1 = mb_strlen($poi->GUT_FirstName, 'UTF-8')-2; + } + if (mb_strlen($poi->GUT_LastName, 'UTF-8') > 2) { + $replace_cnt2 = mb_strlen($poi->GUT_LastName, 'UTF-8')-2; + } + $vro['leader_name'] = substr_replace($poi->GUT_FirstName, str_repeat('*', $replace_cnt1), 1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', $replace_cnt2),1,-1); $vro['leader_name'] = trim($vro['leader_name']); // 行程人数 $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; @@ -328,7 +342,14 @@ class Api extends CI_Controller { } // 领队名字 // $vro['full_leader_name'] = trim($poi->GUT_FirstName . " " . $poi->GUT_LastName); - $vro['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', mb_strlen($poi->GUT_FirstName, 'UTF-8')-2),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', mb_strlen($poi->GUT_LastName, 'UTF-8')-2),1,-1); + $replace_cnt1 = $replace_cnt2 = 0; + if (mb_strlen($poi->GUT_FirstName, 'UTF-8') > 2) { + $replace_cnt1 = mb_strlen($poi->GUT_FirstName, 'UTF-8')-2; + } + if (mb_strlen($poi->GUT_LastName, 'UTF-8') > 2) { + $replace_cnt2 = mb_strlen($poi->GUT_LastName, 'UTF-8')-2; + } + $vro['leader_name'] = substr_replace($poi->GUT_FirstName,str_repeat('*', $replace_cnt1),1,-1) . " " . substr_replace($poi->GUT_LastName,str_repeat('*', $replace_cnt2),1,-1); $vro['leader_name'] = trim($vro['leader_name']); // 行程人数 $vro['personNum_text'] = $poi->COLD_PersonNum + $poi->COLD_ChildNum; From 4f60ce712416af68e148d4cef7796742ede05fa4 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 14 Mar 2019 11:05:21 +0800 Subject: [PATCH 260/382] =?UTF-8?q?paypal=20=E8=BF=94=E5=9B=9E=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 5d6ce854..1619f82e 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -604,9 +604,9 @@ class Index extends CI_Controller { $pn_payment_date = gmdate('Y-m-d H:i:s', strtotime($pn_payment_date)); $this->Note_model->save_paypal_note($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo); log_message('error','paypal-note-succeed ' . $pn_txn_id . ' # ' . $pn_invoice); - echo 'ok'; + // echo 'ok'; } else { - echo 'no'; + // echo 'no'; } return ; } From fea962dd9502f5cf8cbc76fd54510197a3f069c1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 18 Mar 2019 09:37:46 +0800 Subject: [PATCH 261/382] =?UTF-8?q?paypal=20note=20item=5Fname=E9=95=BF?= =?UTF-8?q?=E5=BA=A6250?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/models/note_model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index 43662870..c534e41f 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -89,7 +89,7 @@ class Note_model extends CI_Model { ?,N?,N?,?,N?,N?,?,?,N?,N?,?, N?, GETDATE(),'unsend' ) "; - $query = $this->HT->query($sql, array($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, $pn_item_name, $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo)); + $query = $this->HT->query($sql, array($pn_txn_id, $pn_invoice, $pn_custom, $pn_mc_gross, mb_substr($pn_item_name, 0, 250) , $pn_item_number, $pn_mc_currency, $pn_payment_status, $pn_payer, $pn_payer_email, $pn_payment_date, $pn_memo)); $insertid = $this->HT->last_id('paypal_note'); return $query; } From 4ba07604663e431b281084a0f8f851df4c4a0313 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 20 Mar 2019 10:38:07 +0800 Subject: [PATCH 262/382] sql bug --- webht/third_party/trippestOrderSync/models/orders_model.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index decb3435..a25828f3 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1783,7 +1783,7 @@ class Orders_model extends CI_Model { and ? between PKP_PersonStart and PKP_PersonStop and ? between PKP_ValidDate and PKP_InvalidDate and PKP_VEI_SN in (1343,29188,30548) - order by p.Checked desc, PKP_PriceGrade asc,PKP_ValidDate desc"; // 重复日期的取新的 + order by p.Checked desc, p.PKP_PriceGrade asc,p.PKP_ValidDate desc"; // 重复日期的取新的 return $this->HT->query($sql, array($code, $person_num, $price_date))->row(); } From c87204653d7ed42b150d7d9f0f405903f1872800 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 25 Mar 2019 11:53:52 +0800 Subject: [PATCH 263/382] =?UTF-8?q?paypal=20=E8=AE=A2=E5=8D=95=E5=8F=B7?= =?UTF-8?q?=E5=8C=B9=E9=85=8D=E5=A4=9A=E6=9D=A1=E8=AE=B0=E5=BD=95=E6=97=B6?= =?UTF-8?q?,=E9=9C=80=E6=89=8B=E5=8A=A8=E8=AF=B7=E6=B1=82=E5=BD=95?= =?UTF-8?q?=E5=85=A5,=E5=BD=95=E5=85=A5=E6=9C=80=E4=BD=B3=E5=8C=B9?= =?UTF-8?q?=E9=85=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 5 +++-- webht/third_party/paypal/models/paypal_model.php | 8 ++++++-- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 1619f82e..545a94be 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -786,7 +786,8 @@ class Index extends CI_Controller { //根据订单号查找外联信息 $orderid_info = json_decode($orderid_info); - $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + $handpick = empty($pn_txn_id) ? false : TRUE; + $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); // for trippest tourMaster 2018.05.28 if ($orderid_info->ordertype == 'TP') { @@ -1222,7 +1223,7 @@ class Index extends CI_Controller { $orderid_info = $this->analysis_orderid($neworder); if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); - $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, TRUE); if (!empty($advisor_info)) { $this->Note_model->set_invoice($pn_txn_id, $neworder); $this->send_note($pn_txn_id, $old_ssje); diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index edf08fe2..5ee4b9ad 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -14,7 +14,7 @@ class Paypal_model extends CI_Model { } //根据订单号获取外联邮箱 - public function get_order($COLI_ID, $orderinfo = false, $ordertype = 'N') { + public function get_order($COLI_ID, $orderinfo = false, $ordertype = 'N', $handpick=false) { $result = ''; $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T @@ -29,9 +29,13 @@ class Paypal_model extends CI_Model { if (empty($result) && ($ordertype == 'T')) { $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN - where COLI_ID like '%$COLI_ID'"; + where COLI_ID like '%$COLI_ID' + order by CHARINDEX('$COLI_ID', COLI_ID) "; $query = $this->HT->query($sql); $result = $query->result(); + if ($handpick === TRUE) { + $result = array($result[0]); + } } //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 From f90b0691af58e810021f2772d14d242388e24f8b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 27 Mar 2019 17:16:50 +0800 Subject: [PATCH 264/382] =?UTF-8?q?Trippest=20=E5=9C=B0=E6=8E=A5=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E6=95=B4=E7=90=86[=E6=9C=AA=E5=AE=8C]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../models/vendor_money_model.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php index 689984dc..d5a983b4 100644 --- a/webht/third_party/trippestOrderSync/models/vendor_money_model.php +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -1,6 +1,8 @@ <?php defined('BASEPATH') OR exit('No direct script access allowed'); +define('PAY_OTHER','15017,15008,15006'); + class Vendor_money_model extends CI_Model { function __construct() { @@ -44,11 +46,11 @@ class Vendor_money_model extends CI_Model { ) as 总收款, (select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo where DeleteFlag=0 and GAI_COLI_SN=COLI_SN - and GAI_Type not in (15017,15008,15006) + and GAI_Type not in (" . PAY_OTHER . ") ) as 海纳收款, (select isnull(SUM(GAI_SSJE),0) from BIZ_GroupAccountInfo where DeleteFlag=0 and GAI_COLI_SN=COLI_SN - and GAI_Type in (15017,15008,15006) + and GAI_Type in (" . PAY_OTHER . ") ) as 地接社收款 ,coli.COLI_OPI_ID @@ -83,9 +85,7 @@ class Vendor_money_model extends CI_Model { FROM BIZ_GroupAccountInfo WHERE DeleteFlag=0 AND GAI_COLI_SN=COLI_SN - AND GAI_Type IN (15017, - 15008, - 15006)) AS vendor_sum , + AND GAI_Type IN (" . PAY_OTHER . ")) AS vendor_sum , coli.COLI_OPI_ID FROM CK_GroupInfo cgi INNER JOIN GRoupInfo gri ON CGI_GRI_SN=GRI_SN @@ -110,9 +110,7 @@ class Vendor_money_model extends CI_Model { WHERE DeleteFlag=0 AND GAI_COLI_SN=COLI_SN AND GAI_SSJE>0 - AND GAI_Type IN (15017, - 15008, - 15006) + AND GAI_Type IN (" . PAY_OTHER . ") ) ORDER BY cgi.CGI_ArriveDate "; $query = $this->HT->query($sql); From 69876c28511e5a7ebfaea3f8ced6e5c2db903671 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 28 Mar 2019 09:58:12 +0800 Subject: [PATCH 265/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:COLD=5FPlanVEI=5FSN?= =?UTF-8?q?=E5=8F=98=E6=9B=B4=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 1 + .../trippestOrderSync/controllers/order_finance.php | 13 ++++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 1015f5ab..766b31f3 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -458,6 +458,7 @@ class TulanduoApi extends CI_Controller $cold_update_column["COLD_ServiceSN"] = $pag_info->serviceinfo->PAG2_PAG_SN; $cold_update_column["COLD_ServiceSN2"] = $pag_info->pag_sub; $cold_update_column["COLD_ServiceCity"] = $pag_info->serviceinfo->PAG_CII_SN; + $cold_update_column["COLD_PlanVEI_SN"] = $vei_SN; } $this->Order_update->cold_where_update = " COLD_SN=" . $cold_sn; $this->Order_update->biz_confirmlinedetail_update($cold_update_column); diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 1afd6f89..123dd5a2 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -35,7 +35,7 @@ class Order_finance extends CI_Controller { // 重新生成账单 // HT批量按钮调用 // 仅读取成本信息计算 - public function single_order_report($coli_sn=0) + public function single_order_report($coli_sn=0, $debug=false) { $order_info = $this->OrderFinance_model->get_order_info($coli_sn); if (empty($order_info)) { @@ -45,19 +45,19 @@ class Order_finance extends CI_Controller { if ( ! empty($report_order_exists)) { return $this->output->set_content_type('application/json')->set_output(json_encode($report_order_exists)); } - return $this->generate_report($order_info); + return $this->generate_report($order_info, $debug); } // 重新生成账单 // HT单团财务表页面调用, 先刷新一次成本 - public function single_order_report_refresh($coli_sn=0) + public function single_order_report_refresh($coli_sn=0, $debug=false) { // 刷新成本 $controller_name = "TulanduoApi"; require_once($controller_name . '.php'); $vendor_class = new $controller_name(); $ret = $vendor_class->insert_HT_order_operation($coli_sn); - $this->single_order_report($coli_sn); + $this->single_order_report($coli_sn, $debug); } /*! @@ -75,7 +75,7 @@ class Order_finance extends CI_Controller { * * * 写入单团财务表report_order * END */ - public function generate_report($order_info=array()) + public function generate_report($order_info=array(), $debug=false) { $coli_sn = $order_info->COLI_SN; /** 单团财务表 */ @@ -224,6 +224,9 @@ class Order_finance extends CI_Controller { } } $ret->processed_cold_sn = array_unique($processed_cold_sn); + if ($debug !== false) { + return $this->output->set_content_type('application/json')->set_output(json_encode($ret)); + } /** 开始写入数据库 */ /** 图兰朵供应商 */ if ( ! empty($ret->report_tour)) { From 6798355886b3b7297d5ba424c8587eb3100325be Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 28 Mar 2019 10:10:58 +0800 Subject: [PATCH 266/382] =?UTF-8?q?=E8=B4=A2=E5=8A=A1=E8=A1=A8=20debug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/order_finance.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index 123dd5a2..ee9bac2f 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -42,7 +42,7 @@ class Order_finance extends CI_Controller { return; } $report_order_exists = $this->OrderFinance_model->get_report_order($order_info->ordernumber); - if ( ! empty($report_order_exists)) { + if ( ! empty($report_order_exists) && $debug===false) { return $this->output->set_content_type('application/json')->set_output(json_encode($report_order_exists)); } return $this->generate_report($order_info, $debug); From 0e8277b1367cc1b207aa212081df935fdba462dd Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 29 Mar 2019 15:18:04 +0800 Subject: [PATCH 267/382] =?UTF-8?q?Trippest=E7=BB=93=E7=AE=97:=E9=9D=9E?= =?UTF-8?q?=E5=8C=85=E4=BB=B7=E4=BA=A7=E5=93=81=E6=80=BB=E9=A2=9D=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E8=AE=A1=E7=AE=97=E5=BD=93=E5=89=8D=E6=8C=87=E5=AE=9A?= =?UTF-8?q?=E4=BE=9B=E5=BA=94=E5=95=86,=E5=B9=B6=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=88=90=E6=9C=AC=E8=AE=A1=E7=AE=97;=20=E6=B8=A0=E9=81=93?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E6=94=B9=E4=B8=BA=E5=9C=B0=E6=8E=A5=E7=A4=BE?= =?UTF-8?q?=E6=94=B6=E6=AC=BE15020;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 2 +- .../trippestOrderSync/controllers/vendor_money.php | 4 ++++ .../trippestOrderSync/models/vendor_money_model.php | 11 +++++++++-- .../trippestOrderSync/views/vendor_money_sum.php | 12 ++++++++++-- 4 files changed, 24 insertions(+), 5 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 766b31f3..4f3e4f9e 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -491,7 +491,7 @@ class TulanduoApi extends CI_Controller $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); /** BIZ_GroupAccountInfo */ // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 - $paytype = 15006; // 地接代收 + $paytype = 15020; // 地接代收 $pay_currency = 'RMB'; $auto_text = "dataAutoEnter "; // 删除旧的录入 diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index 9aa2cf22..8fe4fd59 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -77,6 +77,7 @@ class Vendor_money extends CI_Controller { array( "trippest_sum" => 0, "vendor_sum" => 0, + "other_sum_cost" => 0, "other_sum" => 0 ), "vendor" => @@ -84,6 +85,7 @@ class Vendor_money extends CI_Controller { "trippest_sum" => 0, "vendor_sum" => 0, "transfer_sum" => 0, + "other_sum_cost" => 0, "other_sum" => 0 ) ); @@ -96,6 +98,7 @@ class Vendor_money extends CI_Controller { $ret["trippest"]['trippest_sum'] = bcadd(floatval($ret["trippest"]['trippest_sum']), floatval($opi_money['trippest_sum'])) ; } $ret['trippest']['other_sum'] = bcadd($ret['trippest']['other_sum'], $opi_money['other_price_sum']); + $ret['trippest']['other_sum_cost'] = bcadd($ret['trippest']['other_sum_cost'], $opi_money['other_cost_sum']); $ret["trippest"]['trippest_sum'] = bcsub($ret["trippest"]['trippest_sum'], $opi_money['other_price_sum']); } // 按照图兰朵算法: Trippest自营订单的代收算在海纳收款 @@ -107,6 +110,7 @@ class Vendor_money extends CI_Controller { $ret["vendor"]['trippest_sum'] = bcadd(floatval($ret["vendor"]['trippest_sum']), floatval($opi_money_v['vendor_sum'])) ; } $ret['vendor']['other_sum'] = bcadd($ret['vendor']['other_sum'], $opi_money_v['other_price_sum']); + $ret['vendor']['other_sum_cost'] = bcadd($ret['vendor']['other_sum_cost'], $opi_money_v['other_cost_sum']); $ret["vendor"]['trippest_sum'] = bcsub($ret["vendor"]['trippest_sum'], $opi_money_v['other_price_sum']); } $ret["vendor"]["transfer_sum"] = bcsub($ret["vendor"]['vendor_sum'], $ret["trippest"]['vendor_sum']); diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php index d5a983b4..3b3ec4de 100644 --- a/webht/third_party/trippestOrderSync/models/vendor_money_model.php +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -1,7 +1,7 @@ <?php defined('BASEPATH') OR exit('No direct script access allowed'); -define('PAY_OTHER','15017,15008,15006'); +define('PAY_OTHER','15017,15008,15006,15020'); class Vendor_money_model extends CI_Model { @@ -16,14 +16,21 @@ class Vendor_money_model extends CI_Model { { $sql = "SELECT sum_opi.COLI_OPI_ID,sum(sum_opi.海纳收款) as trippest_sum,sum(sum_opi.地接社收款) as vendor_sum, sum(sum_opi.other_price_RMB) as other_price_sum + , sum(sum_opi.other_cost_RMB) as other_cost_sum from ( SELECT (select isnull(SUM(COLD_TotalPrice),0) from BIZ_ConfirmLineDetail cold where cold.COLD_COLI_SN=cgi_group.COLI_SN and COLD_ServiceType <> 'D' - and COLD_PlanVEI_SN NOT IN ($all_vendor) + and COLD_PlanVEI_SN IN ($all_vendor) and cold.DeleteFlag=0 )*cgi_group.汇率 as other_price_RMB, + (select isnull(SUM(COLD_TotalCost),0) from BIZ_ConfirmLineDetail cold + where cold.COLD_COLI_SN=cgi_group.COLI_SN + and COLD_ServiceType <> 'D' + and COLD_PlanVEI_SN IN ($all_vendor) + and cold.DeleteFlag=0 + ) as other_cost_RMB, * from ( select diff --git a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php index 18aefdfe..76876eb1 100644 --- a/webht/third_party/trippestOrderSync/views/vendor_money_sum.php +++ b/webht/third_party/trippestOrderSync/views/vendor_money_sum.php @@ -110,7 +110,11 @@ <tr class="bg-grey"> <td >非包价产品的收款 <br></td> <td ><?php echo $trippest['trippest']['other_sum'] ?></td> - <td colspan="7"></td> + <td ></td> + <td ></td> + <td ><?php echo $trippest['trippest']['other_sum_cost'] ?></td> + <td ></td> + <td colspan="4"></td> </tr> <?php } @@ -174,7 +178,11 @@ <tr class="bg-grey"> <td >非包价产品的收款 <br></td> <td ><?php echo $vendor['vendor']['other_sum'] ?></td> - <td colspan="7"></td> + <td ></td> + <td ></td> + <td ><?php echo $vendor['vendor']['other_sum_cost'] ?></td> + <td ></td> + <td colspan="4"></td> </tr> <?php } From 1bc784330217ab14cf48de5f70d08a022e399159 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 29 Mar 2019 16:30:07 +0800 Subject: [PATCH 268/382] =?UTF-8?q?Trippest=E7=BB=93=E7=AE=97:=E6=80=BB?= =?UTF-8?q?=E9=A2=9D/=E6=88=90=E6=9C=AC=E5=8A=A0=E4=B8=8A=E9=9D=9E?= =?UTF-8?q?=E5=8C=85=E4=BB=B7=E4=BA=A7=E5=93=81=E9=87=91=E9=A2=9D,=20?= =?UTF-8?q?=E9=87=8D=E6=96=B0=E8=AE=A1=E7=AE=97=E5=88=A9=E6=B6=A6=E5=92=8C?= =?UTF-8?q?=E5=88=86=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/vendor_money.php | 20 ++++++++++++------- .../models/vendor_money_model.php | 2 +- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/vendor_money.php b/webht/third_party/trippestOrderSync/controllers/vendor_money.php index 8fe4fd59..9f7bbc41 100644 --- a/webht/third_party/trippestOrderSync/controllers/vendor_money.php +++ b/webht/third_party/trippestOrderSync/controllers/vendor_money.php @@ -123,11 +123,15 @@ class Vendor_money extends CI_Controller { $result["money"][strval($vendor)]["vendor_code"] = $vendor; $result["money"][strval($vendor)]["vendor_name"] = $vendor_sourcetype[strval($vendor)]["vendor_name"]; /** 团款合计 */ - $result['col_sum']['trippest']['sum_trippest_sum'] = bcadd($result['col_sum']['trippest']['sum_trippest_sum'], $ret["trippest"]['trippest_sum']); + $result['col_sum']['trippest']['sum_trippest_sum'] = bcadd( + bcadd($result['col_sum']['trippest']['sum_trippest_sum'], $ret["trippest"]['trippest_sum']) + ,$ret['trippest']['other_sum']); $result['col_sum']['trippest']['sum_vendor_sum'] = bcadd($result['col_sum']['trippest']['sum_vendor_sum'], $ret["trippest"]['vendor_sum']); $result['col_sum']['trippest']['sum_other'] = bcadd($result['col_sum']['trippest']['sum_other'], $ret['trippest']['other_sum']); - $result['col_sum']['vendor']['sum_trippest_sum'] = bcadd($result['col_sum']['vendor']['sum_trippest_sum'], $ret["vendor"]['trippest_sum']); + $result['col_sum']['vendor']['sum_trippest_sum'] = bcadd( + bcadd($result['col_sum']['vendor']['sum_trippest_sum'], $ret["vendor"]['trippest_sum']) + ,$ret['vendor']['other_sum']); $result['col_sum']['vendor']['sum_vendor_sum'] = bcadd($result['col_sum']['vendor']['sum_vendor_sum'], $ret["vendor"]['vendor_sum']); $result['col_sum']['vendor']['sum_other'] = bcadd($result['col_sum']['vendor']['sum_other'], $ret['vendor']['other_sum']); } @@ -142,16 +146,18 @@ class Vendor_money extends CI_Controller { } // 成本总计 $result['col_sum']['trippest']['sum_trippest_cost'] = $result['col_sum']['vendor']['sum_trippest_cost'] = bcadd($result['col_sum']['trippest']['sum_trippest_cost'], $vm['trippest_cost']); - $result['col_sum']['trippest']['sum_vendor_cost'] = $result['col_sum']['vendor']['sum_vendor_cost'] = bcadd($result['col_sum']['trippest']['sum_vendor_cost'], $vm['vendor_cost']); + $result['col_sum']['trippest']['sum_vendor_cost'] = $result['col_sum']['vendor']['sum_vendor_cost'] = bcadd( + bcadd($result['col_sum']['trippest']['sum_vendor_cost'], $vm['vendor_cost']) + ,$vm['trippest']['other_sum_cost']); } foreach ($result['money'] as $kmi => &$vmi) { /** 利润 */ $vmi['trippest']['total_profit'] = bcsub( - bcadd($vmi['trippest']['trippest_sum'], $vmi['trippest']['vendor_sum']), - bcadd($vmi['trippest_cost'], $vmi['vendor_cost'])); + bcadd(bcadd($vmi['trippest']['trippest_sum'], $vmi['trippest']['vendor_sum']),$vmi['trippest']['other_sum']), + bcadd(bcadd($vmi['trippest_cost'], $vmi['vendor_cost']),$vmi['trippest']['other_sum_cost'])); $vmi['vendor']['total_profit'] = bcsub( - bcadd($vmi['vendor']['trippest_sum'], $vmi['vendor']['vendor_sum']), - bcadd($vmi['trippest_cost'], $vmi['vendor_cost'])); + bcadd(bcadd($vmi['vendor']['trippest_sum'], $vmi['vendor']['vendor_sum']),$vmi['vendor']['other_sum']), + bcadd(bcadd($vmi['trippest_cost'], $vmi['vendor_cost']),$vmi['vendor']['other_sum_cost'])); /** 利润分成 */ $vmi['trippest']['vendor_profit'] = bcmul($vmi['trippest']['total_profit'], $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]); $vmi['trippest']['trippest_profit'] = bcmul($vmi['trippest']['total_profit'], bcsub(1, $vendor_sourcetype[strval($vmi['vendor_code'])]["profit_rate"]) ); diff --git a/webht/third_party/trippestOrderSync/models/vendor_money_model.php b/webht/third_party/trippestOrderSync/models/vendor_money_model.php index 3b3ec4de..374b9c8e 100644 --- a/webht/third_party/trippestOrderSync/models/vendor_money_model.php +++ b/webht/third_party/trippestOrderSync/models/vendor_money_model.php @@ -119,7 +119,7 @@ class Vendor_money_model extends CI_Model { AND GAI_SSJE>0 AND GAI_Type IN (" . PAY_OTHER . ") ) - ORDER BY cgi.CGI_ArriveDate "; + ORDER BY vendor_sum "; $query = $this->HT->query($sql); return $query->result_array(); } From 9de1b5ae24babca5a69ff21c623d78a1aa079f05 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 1 Apr 2019 09:46:31 +0800 Subject: [PATCH 269/382] =?UTF-8?q?Trippest=E5=90=8C=E6=AD=A5:=E6=94=AF?= =?UTF-8?q?=E4=BB=98=E6=96=B9=E5=BC=8F=E4=BD=BF=E7=94=A8=E5=9C=B0=E6=8E=A5?= =?UTF-8?q?=E7=A4=BE=E6=94=B6=E6=AC=BE;=E4=BF=AE=E6=AD=A3=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=9D=A5=E6=BA=90=E7=B1=BB=E5=9E=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4f3e4f9e..4dd918a5 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -3,6 +3,8 @@ if (!defined('BASEPATH')) exit('No direct script access allowed'); +define('PAY_TO_AGENCY',15020); + class TulanduoApi extends CI_Controller { public $special_route = array( @@ -439,6 +441,7 @@ class TulanduoApi extends CI_Controller $coli_update_column["COLI_Price"] = $travel_fee; $coli_update_column["COLI_CUrrency"] = $travel_fee_currency; $coli_update_column["COLI_GroupCode"] = substr(trim_str($detail_jsonResp->orderDetail->agcOrderNo), 0, 49); + $coli_update_column["COLI_sourcetype"] = empty($this->city_info[$detail_jsonResp->orderDetail->operationDep]) ? 32090 : $this->city_info[$detail_jsonResp->orderDetail->operationDep]['COLI_sourcetype']; } $this->Order_update->biz_confirmlineinfo_update($coli_update_column); /** @@ -491,7 +494,7 @@ class TulanduoApi extends CI_Controller $latest_order_detail = $this->Orders_model->get_orderinfo_detail($coli_id); /** BIZ_GroupAccountInfo */ // 团款, 只有其他社的订单, 目的地项目组的团款已经直接收入海纳账户 - $paytype = 15020; // 地接代收 + $paytype = PAY_TO_AGENCY; // 地接代收 $pay_currency = 'RMB'; $auto_text = "dataAutoEnter "; // 删除旧的录入 @@ -975,7 +978,7 @@ class TulanduoApi extends CI_Controller $this->Orders_model->BIZ_COLI_OrderDetailText = "来自图兰朵系统同步" . $list_ele["orderId"] . ";线路:" . $list_ele['routeName'] . "; 团名: " . $list_ele['agcOrderNo']; $this->Orders_model->BIZ_COLI_GUT_SN = $this->Orders_model->BIZ_GUT_SN ? $this->Orders_model->BIZ_GUT_SN : null; $this->Orders_model->BIZ_COLI_OPI_ID = 435; - $this->Orders_model->BIZ_COLI_PayManner = 15006; + $this->Orders_model->BIZ_COLI_PayManner = PAY_TO_AGENCY; return $this->Orders_model->biz_confirm_save(); } From 06d74423ff88cde54a7ac63faa69b6a2f8051b39 Mon Sep 17 00:00:00 2001 From: LiaoYijun <lyj@hainatravel.com> Date: Wed, 10 Apr 2019 13:49:18 +0800 Subject: [PATCH 270/382] =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=AE=A2=E4=BA=BA?= =?UTF-8?q?=E5=A1=AB=E6=8A=A4=E7=85=A7=E4=BF=A1=E6=81=AF=E7=9A=84=E5=86=85?= =?UTF-8?q?=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/order/views/confirm_order.php | 2 +- application/third_party/order/views/mailtext.php | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/application/third_party/order/views/confirm_order.php b/application/third_party/order/views/confirm_order.php index a916af4c..05a815f3 100644 --- a/application/third_party/order/views/confirm_order.php +++ b/application/third_party/order/views/confirm_order.php @@ -731,7 +731,7 @@ }); - $("#btn-add-personinfo-box").click(); + // $("#btn-add-personinfo-box").click(); //日期初始化 diff --git a/application/third_party/order/views/mailtext.php b/application/third_party/order/views/mailtext.php index fc6b27eb..2a1a8114 100644 --- a/application/third_party/order/views/mailtext.php +++ b/application/third_party/order/views/mailtext.php @@ -25,7 +25,6 @@ <h3>Contact Information</h3> <p style="margin:0;">Land line:<?php if (isset($postdata['landline'])) echo $postdata['landline']; ?></p> <p style="margin:0;">Mobile:<?php if (isset($postdata['mobile'])) echo $postdata['mobile']; ?></p> -<p style="margin:0;">Home Address:<?php if (isset($MEI_Street)) echo $MEI_Street; ?></p> <h4 class="text-red" style="box-sizing:border-box;font-family:'Helvetica Neue', Helvetica, Arial, sans-serif;font-weight:500;line-height:1.1;color:#AA2E2D;margin-top:10px;margin-bottom:15px;font-size:24px;padding:12px 0 12px 0;border-bottom:1px solid #dddddd;border-top:1px solid #dddddd;white-space:normal;background-color:#FFFFFF;"> Flight Information From ad9e5581caa8e71864561f90f0641c354410da10 Mon Sep 17 00:00:00 2001 From: LMR <59361885@qq.com> Date: Fri, 12 Apr 2019 11:10:42 +0800 Subject: [PATCH 271/382] rm --- application/controllers/gaapi.php | 69 +++++++++---------- .../sylvan-box-234910-357cb59e6bf0.json | 12 ---- 2 files changed, 34 insertions(+), 47 deletions(-) delete mode 100644 application/controllers/gaapi_json/sylvan-box-234910-357cb59e6bf0.json diff --git a/application/controllers/gaapi.php b/application/controllers/gaapi.php index 33003782..2027f22f 100644 --- a/application/controllers/gaapi.php +++ b/application/controllers/gaapi.php @@ -16,7 +16,7 @@ class Gaapi extends CI_Controller public function user_track() { - $cid = $this->input->get_post('cid'); + $cid = $this->input->get_post('cid'); $analytics = $this->initializeAnalytics(); $response = $this->getReport($analytics, $cid); $this->printResults($response); @@ -24,17 +24,17 @@ class Gaapi extends CI_Controller /** - * Initializes an Analytics Reporting API V4 service object. - * - * @return An authorized Analytics Reporting API V4 service object. - */ + * Initializes an Analytics Reporting API V4 service object. + * + * @return An authorized Analytics Reporting API V4 service object. + */ function initializeAnalytics() { // Use the developers console and download your service account // credentials in JSON format. Place them in this directory or // change the key file location if necessary. - $KEY_FILE_LOCATION = __DIR__ . '/gaapi_json/sylvan-box-234910-357cb59e6bf0.json'; + $KEY_FILE_LOCATION = 'c:/gaapi_json/sylvan-box-234910-357cb59e6bf0.json'; // Create and configure a new client object. $client = new Google_Client(); @@ -48,14 +48,14 @@ class Gaapi extends CI_Controller /** - * Queries the Analytics Reporting API V4. - * - * @param service An authorized Analytics Reporting API V4 service object. - * @return The Analytics Reporting API V4 response. - */ + * Queries the Analytics Reporting API V4. + * + * @param service An authorized Analytics Reporting API V4 service object. + * @return The Analytics Reporting API V4 response. + */ function getReport($analytics, $cid_no) { - //die($cid); + //die($cid); // Replace with your view ID, for example XXXX. $VIEW_ID = "68484932"; @@ -77,24 +77,24 @@ class Gaapi extends CI_Controller $cid->setName("ga:dimension1"); $hitTime = new Google_Service_AnalyticsReporting_Dimension(); $hitTime->setName("ga:dimension3"); - $ip = new Google_Service_AnalyticsReporting_Dimension(); + $ip = new Google_Service_AnalyticsReporting_Dimension(); $ip->setName("ga:dimension3"); - // Create Dimension Filter 1 + // Create Dimension Filter 1 $cidFilter = new Google_Service_AnalyticsReporting_DimensionFilter(); $cidFilter->setDimensionName("ga:dimension1"); $cidFilter->setOperator('EXACT'); $cidFilter->setExpressions($cid_no); - - // Create the DimensionFilterClauses + + // Create the DimensionFilterClauses $dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause(); $dimensionFilterClause->setFilters(array($cidFilter)); - // OrderBy maybe some bugs - $order = new Google_Service_AnalyticsReporting_OrderBy; - $order->setFieldName("ga:dimension3"); - $order->setOrderType("VALUE"); - $order->setSortOrder("DESCENDING"); + // OrderBy maybe some bugs + $order = new Google_Service_AnalyticsReporting_OrderBy; + $order->setFieldName("ga:dimension3"); + $order->setOrderType("VALUE"); + $order->setSortOrder("DESCENDING"); // Create the ReportRequest object. $request = new Google_Service_AnalyticsReporting_ReportRequest(); @@ -102,8 +102,8 @@ class Gaapi extends CI_Controller $request->setDateRanges($dateRange); $request->setMetrics(array($pv)); $request->setDimensions(array($pageUrl, $cid, $hitTime)); - $request->setDimensionFilterClauses(array($dimensionFilterClause)); - $request->setOrderBys(array($order)); + $request->setDimensionFilterClauses(array($dimensionFilterClause)); + $request->setOrderBys(array($order)); $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); $body->setReportRequests(array($request)); @@ -118,26 +118,26 @@ class Gaapi extends CI_Controller */ function printResults($reports) { - $alais_array = array( - "ga:dimension1" => "cid", - "ga:dimension3" => "hitTime", - "ga:pagePath" => "path" - ); - $rs_array = array(); + $alais_array = array( + "ga:dimension1" => "cid", + "ga:dimension3" => "hitTime", + "ga:pagePath" => "path" + ); + $rs_array = array(); for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) { $report = $reports[$reportIndex]; $header = $report->getColumnHeader(); $dimensionHeaders = $header->getDimensions(); $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); $rows = $report->getData()->getRows(); - $rs_row = array(); + $rs_row = array(); for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { $row = $rows[$rowIndex]; $dimensions = $row->getDimensions(); $metrics = $row->getMetrics(); for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { //print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); - $rs_row[$alais_array[$dimensionHeaders[$i]]] = $dimensions[$i]; + $rs_row[$alais_array[$dimensionHeaders[$i]]] = $dimensions[$i]; } for ($j = 0; $j < count($metrics); $j++) { @@ -145,14 +145,13 @@ class Gaapi extends CI_Controller for ($k = 0; $k < count($values); $k++) { $entry = $metricHeaders[$k]; //print($entry->getName() . ": " . $values[$k] . "\n"); - $rs_row[$entry->getName()] = $values[$k]; + $rs_row[$entry->getName()] = $values[$k]; } } - array_push($rs_array, $rs_row); + array_push($rs_array, $rs_row); } } - echo(json_encode($rs_array)); + echo (json_encode($rs_array)); } - } //end of gaapi diff --git a/application/controllers/gaapi_json/sylvan-box-234910-357cb59e6bf0.json b/application/controllers/gaapi_json/sylvan-box-234910-357cb59e6bf0.json deleted file mode 100644 index 1cd817fc..00000000 --- a/application/controllers/gaapi_json/sylvan-box-234910-357cb59e6bf0.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "type": "service_account", - "project_id": "sylvan-box-234910", - "private_key_id": "357cb59e6bf066231fe9d421a1cada76b6af29ef", - "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDSNl/aj3hQf6bf\naPBHuGTLemiUl2OborE8MNvl5brhJMncTSslS1Q5CQRPk4K6nW1gAq2/gQ5KZ7Sd\nh9gdtWzIDoUS1DBDaZiPB8vVN6YOjIWpRSylIXTewQ6YYuw9kt7vW0orfDSsaWrE\nc2Yb5YN+6GTxVBjFEb19IYg5/8zfmvaUCOinDwO+F8mh6fCS9FyhiN5omKD+ixiQ\nYFIo1CM1SCpT3eH67JIF+hzuGAVWhF7YmdNTBdfrM0/1PBM8HRry0jD1VaDeyv+e\n4lTnPCtvUgc5SJOaLv/UR06X1FpIYikK0RHJ04fTslQxu7hTLqbhg/7d/+aj95K0\nAwaGERvdAgMBAAECggEAAOQZHFdoDVxwlSJEqeNyIDZh+GIfmnYQAUFhMKkOsPCc\nw9rtTxrNRxace0fd2sXtVkF8pp5dWTasmmIMPGNt+dLR7pP/z4Of2o9ZQcJR1vCp\nZc195rz/EL+AmGgLgZXg/5lxGhyDKhJ9vpORNt/FPiFALyOueJ/wslEnkZfwDANv\n0C+uIv2L3g0mrgTqXVwU/dVdYi9UK7hhn0YMgtlbdpxRHV0cIiilb23Cyy0QsFXN\n2MsoHPQWf+72nE+5jNnysXcR8AjAthzOvP/jIcqqBguid1w9F3goH4adLTa1aPIL\ndNGI/z9mwuqGQg5C78ZfmZMb3YIRwV4nmUia7kzrowKBgQDr2h14VyEGAypCjo+r\nXRvDti55PY+jKUnUzbseJca7Z1Z2snvGXWgkoasZc8ozsQjoH7wJJnRoJOGnAJdF\ntyZxtJV5W0pefB6Pfqy6k5MlJJhMy6lGpkQo96iPOBqfowHa1r/S55USHjQAMXG2\nKrX6oq1IWmEmFYMFZnQo7+SPqwKBgQDkK4rnCbirwHC0Z6eXkbk0Fb8KrS0huq3C\nupaoBtwkfkyISBzcXx6Bup/Gg7czSxvY6U/Bg93WtTzzJwVuqKSqcTUrwW4rAmrh\nZNEYjJc5YLKK1xXVOEeisMIsWCEpF8JHvyrCRsoBCOVRbQROFqz9IOSGrplw1Rq6\ntuPp2fsalwKBgQDgbfabG/X9vadKHFSUUY5pBwRkNHNpZJGwIXEMeBALJoN9gcwM\nb7f5G6owFyHzXGRIVmJdJq2gqG/dtc889NJtYtTV3UwAawW9sGH3TRS5RIB0m1xi\nMTcs8LYCSvXysG/EaZOxwtL0oa8D/AjjuvLeJEzWS8KkNdYunlas2dJZ7wKBgEAO\nlWV9jjHxyfJr81oTGDquLD80FSqV/ThhJ/CuVFmOd6//BtM7hRYIrdiOm/0zhfLk\ntXZvrfUcVqsw9k513BzZwYKyQFqkyBrVMfrBZac/JYDjF4cP0NS06R6H829U8z8v\nRTLbqtSVicPNZlsB9Ljv5hiFpiBOQ73NoLjDcMKrAoGAC+mrH9aOBeQuikQllpWJ\naZ7XoDdZcmh3j+o7OZWHAP3mpQ6q6/1iPW4lhG/q6l+syjsYRmQuzYICtSJ6xQlC\nM+AYPjD+O6sW3MWGz469cqrym8o+Bm24emxJNvilo/U/N2Yif2gUGWgw8qXLEGsu\nUedwiH6aWGBFnlVuPz6CZ6s=\n-----END PRIVATE KEY-----\n", - "client_email": "gaapi-904@sylvan-box-234910.iam.gserviceaccount.com", - "client_id": "112785767675412711830", - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://oauth2.googleapis.com/token", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/gaapi-904%40sylvan-box-234910.iam.gserviceaccount.com" -} From 3badd8277244c9724d38729ac664ce5eccd4522d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=B9=E8=AF=9A=E8=AF=9A?= <ycc@hainatravel.com> Date: Fri, 12 Apr 2019 11:17:07 +0800 Subject: [PATCH 272/382] =?UTF-8?q?CT=E7=9A=84AMP=E6=A8=A1=E6=9D=BF?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../htmlcompressor/views/amp-template/ct.php | 23 +++---------------- 1 file changed, 3 insertions(+), 20 deletions(-) diff --git a/application/third_party/htmlcompressor/views/amp-template/ct.php b/application/third_party/htmlcompressor/views/amp-template/ct.php index c5048912..338379ef 100644 --- a/application/third_party/htmlcompressor/views/amp-template/ct.php +++ b/application/third_party/htmlcompressor/views/amp-template/ct.php @@ -49,23 +49,6 @@ footer p { margin-bottom:0.5rem;} #crumbNav a:hover { color: #a31022; text-decoration: none } /* from font awesome */ @font-face{font-family:FontAwesome;src:url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.eot?v=4.7.0);src:url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.eot?#iefix&v=4.7.0) format('embedded-opentype'),url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.woff2?v=4.7.0) format('woff2'),url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.woff?v=4.7.0) format('woff'),url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.ttf?v=4.7.0) format('truetype'),url(https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular) format('svg');font-weight:400;font-style:normal}.fa{display:inline-block;font:normal normal normal 14px/1 FontAwesome;font-size:inherit;text-rendering:auto;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.fa-facebook-square:before{content:"\f082"}.fa-facebook-f:before,.fa-facebook:before{content:"\f09a"}.fa-pinterest:before{content:"\f0d2"}.fa-pinterest-square:before{content:"\f0d3"}.fa-caret-down:before{content:"\f0d7"}.fa-caret-up:before{content:"\f0d8"}.fa-caret-left:before{content:"\f0d9"}.fa-caret-right:before{content:"\f0da"}.fa-instagram:before{content:"\f16d"}.fa-flickr:before{content:"\f16e"}.fa-tripadvisor:before{content:"\f262"}.fa-500px:before{content:"\f26e"}.fa-angle-down:before{content:"\f107"}.fa-square-o:before{content:"\f096"}.fa-angle-left:before{content:"\f104"}.fa-angle-right:before{content:"\f105"} -.fa-facebook-square:before { content: "\f082" } -.fa-facebook-f:before, .fa-facebook:before { content: "\f09a" } -.fa-twitter:before { content: "\f099" } -.fa-pinterest:before { content: "\f0d2" } -.fa-pinterest-square:before { content: "\f0d3" } -.fa-caret-down:before { content: "\f0d7" } -.fa-caret-up:before { content: "\f0d8" } -.fa-caret-left:before { content: "\f0d9" } -.fa-caret-right:before { content: "\f0da" } -.fa-instagram:before { content: "\f16d" } -.fa-flickr:before { content: "\f16e" } -.fa-tripadvisor:before { content: "\f262" } -.fa-500px:before { content: "\f26e" } -.fa-angle-down:before { content: "\f107" } -.fa-square-o:before { content: "\f096" } -.fa-angle-left:before { content: "\f104" } -.fa-angle-right:before { content: "\f105" } .fa-navicon:before,.fa-reorder:before,.fa-bars:before { content: "\f0c9"; color:#333; margin:0.32rem 0 0 1rem; } .fa-google-plus::before { content: "\f0d5";} /* sidebar style */ @@ -134,9 +117,9 @@ html{font-size:16px} <section> <h3 class="ampstart-nav-link amphtml-accordion-header"><a class="ampstart-nav-link" href="/china-tours/">China Tours</a> <i class="fa fa-angle-right" aria-hidden="true"></i></h3> <ul class="ampstart-dropdown-items list-reset "> - <li><a href="/china-tours/ct-1.htm">Classic China Tour from $1,419</a></li> - <li><a href="/china-tours/ct-2.htm">The History and Nature of China from $1,999</a></li> - <li><a href="/china-tours/ct-3.htm">China Adventure Journey from $2149</a></li> + <li><a href="/china-tours/ct-1.htm">Classic China Tour</a></li> + <li><a href="/china-tours/ct-2.htm">The History and Nature of China</a></li> + <li><a href="/china-tours/ct-3.htm">China Adventure Journey</a></li> <li><a href="/china-tours/theme/china-panda-tours/">Panda Tours</a></li> <li><a href="/china-tours/top-10-china-tours.htm"> See All Top 10 China Tours</a></li> </ul> From 4ea5eb7147f1732f2a3fc2f28a01e3586a252b68 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 15 Apr 2019 10:51:32 +0800 Subject: [PATCH 273/382] =?UTF-8?q?alipay=20=E5=A2=9E=E5=8A=A0=E4=BA=A4?= =?UTF-8?q?=E6=98=93=E5=8F=B7=E6=9F=A5=E8=AF=A2=E6=B2=A1=E6=9C=89=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E9=80=9A=E7=9F=A5=E7=9A=84=E6=94=B6=E6=AC=BE(?= =?UTF-8?q?=E6=9D=A5=E8=87=AA=E6=94=B6=E9=92=B1=E7=A0=81)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 44 ++++++++++++++----- .../pay/models/Alipay_note_model.php | 3 +- webht/third_party/pay/views/alipay_list.php | 9 +++- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 808c6b0c..2c414461 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -509,29 +509,24 @@ class AlipayTradeService extends CI_Controller $request = new AlipayTradeQueryRequest(); $request->setBizContent ( $biz_content ); - $response = $this->aopclientRequestExecute ($request,true); + $response = $this->aopclientRequestExecute ($request); $response = $response->alipay_trade_query_response; return $response; } - public function query_pay($dealId,$orderId=NULL) + public function query_pay($dealId=NULL,$orderId=NULL) { + if ($dealId === NULL) { + $dealId = $this->input->get_post('dealid'); + $dealId = trim($dealId); + } $this->AlipayTradeQueryContentBuilder->setTradeNo($dealId); if ($orderId) { $this->AlipayTradeQueryContentBuilder->setOutTradeNo($orderId); } $response = $this->Query($this->AlipayTradeQueryContentBuilder); - if ( strcmp(trim($response->code), "10000")) { - log_message('error',"Alipay query failed! error code:".$response->code."; result Msg: ".$response->msg.'; orderId:'.$response->out_trade_no.'; dealId:'.$response->trade_no."; "); - } - $html = '<table>'; - foreach ($response as $key => $value) { - $html .= "<tr><td>$key</td><td>$value</td>"; - } - $html .= '</table>'; - echo $html; - return; + return $response; } /*! @@ -624,6 +619,30 @@ var_dump($response->$responseNode); empty($data['date']) ? $data['date'] = date('Y-m-d') : false; if (!empty($data['keywords'])) { $data['notelist'] = $this->Alipay_note_model->search_key($data['keywords']); + /** 手动查询通过收钱码的收款, 必须输入交易号 */ + if (empty($data['notelist'])) { + $query_pay = $this->query_pay($data["keywords"]); + if ( ! empty($query_pay) && strval($query_pay->code)==="10000" && strval($query_pay->trade_status)==="TRADE_SUCCESS") { + $pay_type = $query_pay->total_amount>0 ? "pay" : "refund"; + $new_record = $this->Alipay_note_model->save_alipay( + strval($query_pay->trade_no) + ,strval($query_pay->out_trade_no) + ,"CNY" + ,strval($query_pay->total_amount) + ,NULL + ,NULL + ,strval($query_pay->send_pay_date) + ,strval($query_pay->send_pay_date) + ,json_encode($query_pay) + ,$pay_type + ,NULL + ,strval($query_pay->trade_status) + ,NULL + ,strval($query_pay->buyer_logon_id) + ); + $data['notelist'][] = $new_record; + } + } } else { $data['notelist'] = $this->Alipay_note_model->search_date($data['date']); } @@ -743,6 +762,7 @@ var_dump($response->$responseNode); return array( "WAIT_BUYER_PAY" => "Pending", "TRADE_SUCCESS" => "Payment success", + "TRADE_CLOSED" => "Payment closed", "TRADE_FINISHED" => "Payment success" ); } diff --git a/webht/third_party/pay/models/Alipay_note_model.php b/webht/third_party/pay/models/Alipay_note_model.php index 15294ba7..cafe422b 100644 --- a/webht/third_party/pay/models/Alipay_note_model.php +++ b/webht/third_party/pay/models/Alipay_note_model.php @@ -118,7 +118,8 @@ class Alipay_note_model extends CI_Model { ,$ALI_payerEmail )); $insertid = $this->INFO->last_id('AlipayLog'); - return $query; + $ret = "SELECT TOP 1 * FROM AlipayLog WHERE ALI_dealId='$ALI_dealId' ORDER BY ALI_sn DESC "; + return $this->INFO->query($ret)->row(); } public function get_list() { diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php index d3a9c1ad..afe0d5c2 100644 --- a/webht/third_party/pay/views/alipay_list.php +++ b/webht/third_party/pay/views/alipay_list.php @@ -66,6 +66,7 @@ /*.input-group{border: 1px solid #ccc;}*/ .input-group-btn{border: 1px solid #ccc;padding: 5px;} .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} + .center-block{display: block;margin: 0 auto;} </style> </head> <body> @@ -75,6 +76,7 @@ <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>Alipay Notes</h1> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> @@ -164,7 +166,8 @@ $show_send = $item->ALI_sent; } else if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")) { $class_css = 'btn-danger'; - $show_send = $paytext[intval(trim($item->ALI_resultMsg))]; + // $show_send = $paytext[intval(trim($item->ALI_resultMsg))]; + $show_send = strstr($item->ALI_resultMsg, "_"); } else { $class_css = 'btn-danger'; $show_send = $item->ALI_sent; @@ -206,6 +209,9 @@ </div> </div> </div> + <div class="modal" role="dialog" id="loading"> + <img src="https://data.chinahighlights.com/pic/flight-loading.gif" class="center-block" style="margin-top: 50px;"> + </div> </body> <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js&v=20170811" type="text/javascript"></script> @@ -224,6 +230,7 @@ }); $(".ui-datepicker").css('width', '15.7em'); + }); function show_order_modal(pn_txn_id, pn_invoice,noticeTime,old_order) { if (pn_txn_id) { From 6384c575806c9b8027b189e7a90d4b805c5880f5 Mon Sep 17 00:00:00 2001 From: LMR <59361885@qq.com> Date: Tue, 16 Apr 2019 13:58:53 +0800 Subject: [PATCH 274/382] =?UTF-8?q?google=20ga=E8=AE=A4=E8=AF=81=E8=BF=81?= =?UTF-8?q?=E7=A7=BB=E5=88=B0=E6=95=B0=E6=8D=AE=E4=B8=AD=E5=BF=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/controllers/gaapi.php | 157 ------------------------------ 1 file changed, 157 deletions(-) delete mode 100644 application/controllers/gaapi.php diff --git a/application/controllers/gaapi.php b/application/controllers/gaapi.php deleted file mode 100644 index 2027f22f..00000000 --- a/application/controllers/gaapi.php +++ /dev/null @@ -1,157 +0,0 @@ -<?php -if (!defined('BASEPATH')) - exit('No direct script access allowed'); - -class Gaapi extends CI_Controller -{ - - function __construct() - { - parent::__construct(); - $this->permission->is_admin(); - $this->site_code = $this->config->item('site_code'); - //ga verder - $this->load->library('MY_Composer'); - } - - public function user_track() - { - $cid = $this->input->get_post('cid'); - $analytics = $this->initializeAnalytics(); - $response = $this->getReport($analytics, $cid); - $this->printResults($response); - } - - - /** - * Initializes an Analytics Reporting API V4 service object. - * - * @return An authorized Analytics Reporting API V4 service object. - */ - function initializeAnalytics() - { - - // Use the developers console and download your service account - // credentials in JSON format. Place them in this directory or - // change the key file location if necessary. - $KEY_FILE_LOCATION = 'c:/gaapi_json/sylvan-box-234910-357cb59e6bf0.json'; - - // Create and configure a new client object. - $client = new Google_Client(); - $client->setApplicationName("User Tracker"); - $client->setAuthConfig($KEY_FILE_LOCATION); - $client->setScopes(['https://www.googleapis.com/auth/analytics.readonly']); - $analytics = new Google_Service_AnalyticsReporting($client); - - return $analytics; - } - - - /** - * Queries the Analytics Reporting API V4. - * - * @param service An authorized Analytics Reporting API V4 service object. - * @return The Analytics Reporting API V4 response. - */ - function getReport($analytics, $cid_no) - { - //die($cid); - - // Replace with your view ID, for example XXXX. - $VIEW_ID = "68484932"; - - // Create the DateRange object. - $dateRange = new Google_Service_AnalyticsReporting_DateRange(); - $dateRange->setStartDate("30daysAgo"); - $dateRange->setEndDate("today"); - - // Create the Metrics object. - $pv = new Google_Service_AnalyticsReporting_Metric(); - $pv->setExpression("ga:pageviews"); - $pv->setAlias("pageviews"); - - //Create the dimensions - $pageUrl = new Google_Service_AnalyticsReporting_Dimension(); - $pageUrl->setName("ga:pagePath"); - $cid = new Google_Service_AnalyticsReporting_Dimension(); - $cid->setName("ga:dimension1"); - $hitTime = new Google_Service_AnalyticsReporting_Dimension(); - $hitTime->setName("ga:dimension3"); - $ip = new Google_Service_AnalyticsReporting_Dimension(); - $ip->setName("ga:dimension3"); - - // Create Dimension Filter 1 - $cidFilter = new Google_Service_AnalyticsReporting_DimensionFilter(); - $cidFilter->setDimensionName("ga:dimension1"); - $cidFilter->setOperator('EXACT'); - $cidFilter->setExpressions($cid_no); - - // Create the DimensionFilterClauses - $dimensionFilterClause = new Google_Service_AnalyticsReporting_DimensionFilterClause(); - $dimensionFilterClause->setFilters(array($cidFilter)); - - // OrderBy maybe some bugs - $order = new Google_Service_AnalyticsReporting_OrderBy; - $order->setFieldName("ga:dimension3"); - $order->setOrderType("VALUE"); - $order->setSortOrder("DESCENDING"); - - // Create the ReportRequest object. - $request = new Google_Service_AnalyticsReporting_ReportRequest(); - $request->setViewId($VIEW_ID); - $request->setDateRanges($dateRange); - $request->setMetrics(array($pv)); - $request->setDimensions(array($pageUrl, $cid, $hitTime)); - $request->setDimensionFilterClauses(array($dimensionFilterClause)); - $request->setOrderBys(array($order)); - - $body = new Google_Service_AnalyticsReporting_GetReportsRequest(); - $body->setReportRequests(array($request)); - return $analytics->reports->batchGet($body); - } - - - /** - * Parses and prints the Analytics Reporting API V4 response. - * - * @param An Analytics Reporting API V4 response. - */ - function printResults($reports) - { - $alais_array = array( - "ga:dimension1" => "cid", - "ga:dimension3" => "hitTime", - "ga:pagePath" => "path" - ); - $rs_array = array(); - for ($reportIndex = 0; $reportIndex < count($reports); $reportIndex++) { - $report = $reports[$reportIndex]; - $header = $report->getColumnHeader(); - $dimensionHeaders = $header->getDimensions(); - $metricHeaders = $header->getMetricHeader()->getMetricHeaderEntries(); - $rows = $report->getData()->getRows(); - $rs_row = array(); - for ($rowIndex = 0; $rowIndex < count($rows); $rowIndex++) { - $row = $rows[$rowIndex]; - $dimensions = $row->getDimensions(); - $metrics = $row->getMetrics(); - for ($i = 0; $i < count($dimensionHeaders) && $i < count($dimensions); $i++) { - //print($dimensionHeaders[$i] . ": " . $dimensions[$i] . "\n"); - $rs_row[$alais_array[$dimensionHeaders[$i]]] = $dimensions[$i]; - } - - for ($j = 0; $j < count($metrics); $j++) { - $values = $metrics[$j]->getValues(); - for ($k = 0; $k < count($values); $k++) { - $entry = $metricHeaders[$k]; - //print($entry->getName() . ": " . $values[$k] . "\n"); - $rs_row[$entry->getName()] = $values[$k]; - } - } - array_push($rs_array, $rs_row); - } - } - echo (json_encode($rs_array)); - } -} -//end of gaapi From 43e9c8a68ef015b1ae5de0f9397a9d3880a7027e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 17 Apr 2019 15:12:46 +0800 Subject: [PATCH 275/382] =?UTF-8?q?wxpay=20=E5=BC=82=E6=AD=A5=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=A4=84=E7=90=86:=E6=8E=A5=E6=94=B6=E6=8E=A8?= =?UTF-8?q?=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/wxpay.php | 25 +++ .../pay/controllers/WxpayService.php | 160 ++++++++++++++++++ .../pay/helpers/payment_helper.php | 40 +++++ .../models/Online_payment_account_model.php | 27 +++ .../pay/models/Online_payment_note_model.php | 31 ++++ webht/third_party/pay/views/alipay_list.php | 2 +- 6 files changed, 284 insertions(+), 1 deletion(-) create mode 100644 webht/third_party/pay/config/wxpay.php create mode 100644 webht/third_party/pay/controllers/WxpayService.php create mode 100644 webht/third_party/pay/models/Online_payment_account_model.php create mode 100644 webht/third_party/pay/models/Online_payment_note_model.php diff --git a/webht/third_party/pay/config/wxpay.php b/webht/third_party/pay/config/wxpay.php new file mode 100644 index 00000000..b4752bff --- /dev/null +++ b/webht/third_party/pay/config/wxpay.php @@ -0,0 +1,25 @@ +<?php +$config["sign_type"] = "HMAC-SHA256"; +$config["trade_type"] = "NATIVE"; +$config["notify_url"] = ""; +$config["currency"] = "CNY"; +$config["currency_unit"] = 100; +$config["method_code"] = 15016; +/*! + * 各账号的设置 + */ +// test +$config['test']["app_id"] = "wx426b3015555a46be"; +$config['test']["mch_id"] = "1900009851"; +$config['test']["key"] = "8934e7d15453e97507ef794cf7b0519d"; +$config['test']["app_secret"] = "7813490da6f1265e4901ffb80afaa36f"; +// Trippest +$config['trippest']["app_id"] = ""; +$config['trippest']["mch_id"] = ""; +$config['trippest']["key"] = ""; +$config['trippest']["app_secret"] = ""; +// ChinaHighlights = China train booking +$config['cht']["app_id"] = ""; +$config['cht']["mch_id"] = ""; +$config['cht']["key"] = ""; +$config['cht']["app_secret"] = ""; diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php new file mode 100644 index 00000000..d6f7ce6b --- /dev/null +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -0,0 +1,160 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +global $__WX_SITE_NAME__; + +class WxpayService extends CI_Controller { + + protected $wx_site_config; + + public function __construct(){ + parent::__construct(); + bcscale(2); + $this->load->helper('payment'); + $this->config->load('wxpay', true); + $this->load->model('Online_payment_note_model', 'note_model'); + $this->load->model('Online_payment_account_model', 'account_model'); + } + + public function index() + { + + } + + public function notify($site='cht') + { +log_message('error','notify begin ----'); + $response['return_code'] = 'FAIL'; + $response['return_msg'] = ''; + $GLOBALS['__WX_SITE_NAME__'] = $site; + $this->wx_site_config = $this->config->item($GLOBALS['__WX_SITE_NAME__'], 'wxpay'); + if (!isset($GLOBALS['HTTP_RAW_POST_DATA'])) { + # 如果没有数据,直接返回失败 + return $this->response_to_wx($response); + } + //获取通知的数据 + $xml = $GLOBALS['HTTP_RAW_POST_DATA']; + $xml_arr = from_xml($xml); +// log_message('error',var_export($xml_arr, 1)); + if ($this->check_sign($xml_arr) !== true) { + return $this->response_to_wx($response); + } + // 入库保存异步通知 + if ( strval($xml_arr['result_code']) !== "SUCCESS" ) { + $response['return_code'] = 'SUCCESS'; + $response['return_msg'] = 'OK'; + } else { + $xml_arr['total_fee'] = bcdiv($xml_arr['total_fee'], $this->config->item('currency_unit', 'wxpay')); + $ssje = $this->account_model->get_ssje($xml_arr['total_fee'], $xml_arr['fee_type'], $this->config->item('currency_unit', 'wxpay')); + $save_column = array(); + $save_column['OPN_transactionId'] = $xml_arr['transaction_id']; + $save_column['OPN_orderId'] = $xml_arr['out_trade_no']; + $save_column['OPN_rawOrderId'] = $xml_arr['out_trade_no']; + $save_column['OPN_invoiceId'] = $xml_arr['out_trade_no']; + $save_column['OPN_subject'] = $xml_arr['attach']; + $save_column['OPN_currency'] = $xml_arr['fee_type']; + $save_column['OPN_orderAmount'] = $xml_arr['total_fee']; + $save_column['OPN_payAmount'] = $xml_arr['total_fee']; + $save_column['OPn_transactionResult'] = 'completed'; + $save_column['OPN_resultCode'] = $xml_arr['result_code']; + $save_column['OPN_resultMsg'] = isset($xml_arr['return_msg']) ? $xml_arr['return_msg'] : $xml_arr['result_code']; + $save_column['OPN_errCode'] = isset($xml_arr['err_code']) ? $xml_arr['err_code'] : NULL; + $save_column['OPN_errMsg'] = isset($xml_arr['err_code_des']) ? $xml_arr['err_code_des'] : NULL; + $save_column['OPN_acquiringTime'] = date('Y-m-d H:i:s',strtotime($xml_arr['time_end'])); + $save_column['OPN_completeTime'] = date('Y-m-d H:i:s',strtotime($xml_arr['time_end'])); + $save_column['OPN_remark'] = $xml_arr['attach']; + $save_column['OPN_payerLogId'] = $xml_arr['openid']; + $save_column['OPN_payerStatus'] = $xml_arr['is_subscribe']==='Y' ? "subscribed" : NULL; + $save_column['OPN_fundSource'] = $xml_arr['bank_type']; + $save_column['OPN_entryAmountCNY'] = floatval($ssje); + $save_column['OPN_rawContent'] = json_encode($xml_arr); + $save_column['OPN_noticeTime'] = date('Y-m-d H:i:s'); + // $save_column['OPN_noticeType'] = intval($xml_arr['total_fee'])>0 ? 'pay' : 'refund'; + $save_column['OPN_noticeType'] = 'pay'; + $save_column['OPN_noticeSendStatus'] = 'unsend'; + $save_column['OPN_noticeSendTime'] = NULL; + $save_column['OPN_accountMethod'] = $this->config->item('method_code', 'wxpay'); + if ( $this->note_model->insert_note($save_column) ) { + $response['return_code'] = 'SUCCESS'; + $response['return_msg'] = 'OK'; + } + } + return $this->response_to_wx($response); + } + + public function response_to_wx($response_arr) + { + $response_body = to_xml($response_arr); +// log_message('error',var_export($response_body, 1)); + echo $response_body; + # exit(); // end + } + + public function send_notify() + { + // $save_column['OPN_accountType'] = $xml_arr['']; + // $save_column['OPN_accountStatus'] = $xml_arr['']; + // $save_column['OPN_accountTime'] = $xml_arr['']; + } + + public function check_sign($xml_arr) + { + if ( ! array_key_exists('sign', $xml_arr)) { + log_message('error','Wxpay notify error: no sign.'); + return false; + } + if ($this->make_sign($xml_arr) !== $xml_arr['sign']) { + log_message('error','Wxpay notify error: sign.'); + return false; + } + if ($this->wx_site_config['app_id'] !== $xml_arr['appid']) { + log_message('error','Wxpay notify error: appid.'); + return false; + } + if ($this->wx_site_config['mch_id'] !== $xml_arr['mch_id']) { + log_message('error','Wxpay notify error: mch_id.'); + return false; + } + return true; + } + + public function make_sign($xml_arr, $needSignType = false) + { + //签名步骤一:按字典序排序参数 + ksort($xml_arr); + $string = $this->to_url_params($xml_arr); + //签名步骤二:在string后加入KEY + $string = $string . "&key=" . $this->wx_site_config['key']; + //签名步骤三:MD5加密或者HMAC-SHA256 + if(strlen($xml_arr['sign']) <= 32){ + //如果签名小于等于32个,则使用md5验证 + $string = md5($string); + } else { + //是用sha256校验 + $string = hash_hmac("sha256", $string , $this->wx_site_config['key']); + } + //签名步骤四:所有字符转为大写 + $result = strtoupper($string); +log_message('error',$result); + return $result; + } + + /** + * 格式化参数格式化成url参数 + */ + public function to_url_params($xml_arr) + { + $buff = ""; + foreach ($xml_arr as $k => $v) + { + if($k != "sign" && $v != "" && !is_array($v)){ + $buff .= $k . "=" . $v . "&"; + } + } + + $buff = trim($buff, "&"); + return $buff; + } + +} + diff --git a/webht/third_party/pay/helpers/payment_helper.php b/webht/third_party/pay/helpers/payment_helper.php index 3ec1e8cc..53ceac5e 100644 --- a/webht/third_party/pay/helpers/payment_helper.php +++ b/webht/third_party/pay/helpers/payment_helper.php @@ -180,3 +180,43 @@ function analysis_orderid($note_invoice_string) { } return json_encode(array('orderid' => $pm_orderid, 'ordertype' => $ordertype)); } +/** + * 输出xml字符 + * @throws WxPayException +**/ +function to_xml($arr) +{ + if(!is_array($arr) || count($arr) <= 0) + { + return false; + } + + $xml = "<xml>"; + foreach ($arr as $key=>$val) + { + if (is_numeric($val)){ + $xml.="<".$key.">".$val."</".$key.">"; + }else{ + $xml.="<".$key."><![CDATA[".$val."]]></".$key.">"; + } + } + $xml.="</xml>"; + return $xml; +} + +/** + * 将xml转为array + * @param string $xml + * @throws WxPayException + */ +function from_xml($xml) +{ + if(!$xml){ + return false; + } + //将XML转为array + //禁止引用外部xml实体 + libxml_disable_entity_loader(true); + return json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true); +} + diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php new file mode 100644 index 00000000..3c19ea87 --- /dev/null +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -0,0 +1,27 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Online_payment_account_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + /*! + * 调用数据库函数,生成实收金额 + * @author LYT <lyt@hainatravel.com> + */ + public function get_ssje($amount, $currency='USD', $code) + { + $sql = "SELECT dbo.GetSSJEFromSQJE(?, ?, ?) as ssje"; + $query = $this->HT->query($sql,array($code, $currency, $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return NULL; + } + +} + diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php new file mode 100644 index 00000000..2c721c52 --- /dev/null +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -0,0 +1,31 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class Online_payment_note_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->info = $this->load->database('INFO', TRUE); + } + + public function insert_note($column) + { + if ($column === null) { + return false; + } + $this->info->insert('OnlinePaymentNote', $column); + $ret = "SELECT TOP 1 * FROM OnlinePaymentNote WHERE OPN_transactionId=? ORDER BY OPN_SN DESC "; + return $this->info->query($ret, array($column['OPN_transactionId']))->row(); + } + + public function update_note($where, $column) + { + $update_str = $this->info->update_string('OnlinePaymentNote', $column, $where); + $this->info->query($update_str); + return TRUE; + } + + + +} + diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php index afe0d5c2..faceb099 100644 --- a/webht/third_party/pay/views/alipay_list.php +++ b/webht/third_party/pay/views/alipay_list.php @@ -95,7 +95,7 @@ <div class="row"> <form method="post" id="search_list" action="/webht.php/apps/pay/AlipayTradeService/note_list/"> <div class="input-group"> - <input type="text" name="keywords" value="<?php echo isset($search_key) ? $search_key : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> + <input type="text" name="keywords" value="<?php echo isset($search_key) ? $search_key : ''; ?>" class="form-control" placeholder="订单号/交易号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> <span class="input-group-addon search-btn" onclick="$('#search_list').submit();"></span> </div> <div id="datepicker"></div> From 4decfcfae7768118860b4d4b6f466fde651a8236 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 17 Apr 2019 17:37:03 +0800 Subject: [PATCH 276/382] =?UTF-8?q?=E5=A4=84=E7=90=86=E6=94=B6=E5=88=B0?= =?UTF-8?q?=E7=9A=84=E6=94=B6=E6=AC=BE=E6=8E=A8=E9=80=81,=E5=B0=86?= =?UTF-8?q?=E5=90=84=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F=E7=9A=84=E5=A4=84?= =?UTF-8?q?=E7=90=86=E6=96=B9=E6=B3=95=E5=90=88=E5=B9=B6.=2020%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/PaymentService.php | 43 +++++++++++++++ .../pay/controllers/WxpayService.php | 9 +--- .../pay/models/Online_payment_note_model.php | 53 +++++++++++++++++++ 3 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 webht/third_party/pay/controllers/PaymentService.php diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php new file mode 100644 index 00000000..72dbf507 --- /dev/null +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -0,0 +1,43 @@ +<?php +defined('BASEPATH') OR exit('No direct script access allowed'); + +class PaymentService extends CI_Controller { + + public function __construct(){ + parent::__construct(); + bcscale(2); + $this->load->helper('payment'); + // $this->config->load('wxpay', true); + $this->load->model('Online_payment_note_model', 'note_model'); + $this->load->model('Online_payment_account_model', 'account_model'); + } + + public function index() + { + + } + + public function send_notify($payment_method=NULL, $transactionId=NULL) + { + // $save_column['OPN_accountType'] = $xml_arr['']; + // $save_column['OPN_accountStatus'] = $xml_arr['']; + // $save_column['OPN_accountTime'] = $xml_arr['']; + $data = array(); + $int = 0; + + //优先处理指定的交易号,用于修正交易号直接发送通知 + if ( ! empty($transactionId)) { + $data['unsend_list'] = $this->note_model->get_note($payment_method, $transactionId); + } + // 待处理的 + if (empty($data['unsend_list'])) { + $data['unsend_list'] = $this->note_model->unsend_note($payment_method, 10); + } + //没有未处理的数据再查找处理失败的数据 + if (empty($data['unsend_list'])) { + $data['unsend_list'] = $this->note_model->sendfail_note($payment_method, 20); + } + } + +} + diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php index d6f7ce6b..2ee2daa0 100644 --- a/webht/third_party/pay/controllers/WxpayService.php +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -90,13 +90,6 @@ log_message('error','notify begin ----'); # exit(); // end } - public function send_notify() - { - // $save_column['OPN_accountType'] = $xml_arr['']; - // $save_column['OPN_accountStatus'] = $xml_arr['']; - // $save_column['OPN_accountTime'] = $xml_arr['']; - } - public function check_sign($xml_arr) { if ( ! array_key_exists('sign', $xml_arr)) { @@ -135,7 +128,7 @@ log_message('error','notify begin ----'); } //签名步骤四:所有字符转为大写 $result = strtoupper($string); -log_message('error',$result); +// log_message('error',$result); return $result; } diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php index 2c721c52..86f4a9cc 100644 --- a/webht/third_party/pay/models/Online_payment_note_model.php +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -25,6 +25,59 @@ class Online_payment_note_model extends CI_Model { return TRUE; } + public $topnum = false; + public $orderby = false; + public $send = false; + public $search = false; + public $transactionId = false; + public $payment_status = false; + public function init_query() { + $this->topnum = false; + $this->send = false; + $this->search = false; + $this->payment_status = false; + $this->transactionId = false; + $this->orderby = ' ORDER BY OPN_SN DESC '; + } + + public function query_note() + { + $top_sql = $this->topnum ? (" TOP " . $this->topnum) : ""; + $sql .= "SELECT $top_sql opn.* + FROM [InfoManager].[dbo].[OnlinePaymentNote] opn + WHERE 1=1 "; + $this->send ? $sql.=$this->send : false; + $this->search ? $sql.=$this->search : false; + $this->transactionId ? $sql.=$this->transactionId : false; + $this->orderby ? $sql.=$this->orderby : false; + $query = $this->INFO->query($sql); + return $query->result(); + } + + public function get_note($payment_method=NULL, $transactionId=null) + { + $this->init_query(); + $this->topnum=1; + $this->transactionId = " AND opn.OPN_transactionId=" . $this->INFO->escape($transactionId); + return $this->query_note(); + } + + public function unsend_note($payment_method=NULL, $num=2) + { + $this->init_query(); + $this->topnum = $num; + $this->send = " AND (OPN_noticeSendStatus='unsend' OR OPN_noticeSendStatus='' OR OPN_noticeSendStatus IS NULL) "; + return $this->query_note(); + } + + public function sendfail_note($payment_method=NULL, $num=2) + { + $this->init_query(); + $this->topnum = $num; + $this->send = " AND OPN_noticeSendStatus='sendfail' "; + return $this->query_note(); + } + } From df00c0823daf3b81e7c0790ed3040fa960bded15 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 18 Apr 2019 11:54:40 +0800 Subject: [PATCH 277/382] =?UTF-8?q?=E5=BC=82=E6=AD=A5=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E5=85=A5=E5=8F=A3=E5=8F=AA=E8=83=BD=E8=BE=93=E5=87=BA=E6=8C=87?= =?UTF-8?q?=E5=AE=9A=E5=AD=97=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/WxpayService.php | 1 + 1 file changed, 1 insertion(+) diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php index 2ee2daa0..e073dbd1 100644 --- a/webht/third_party/pay/controllers/WxpayService.php +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -23,6 +23,7 @@ class WxpayService extends CI_Controller { public function notify($site='cht') { + error_reporting(0); log_message('error','notify begin ----'); $response['return_code'] = 'FAIL'; $response['return_msg'] = ''; From 34d402bf8371802745c272164f9f62db6d173531 Mon Sep 17 00:00:00 2001 From: LiaoYijun <lyj@hainatravel.com> Date: Fri, 19 Apr 2019 11:40:57 +0800 Subject: [PATCH 278/382] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20LYJ=20=E4=B8=BA?= =?UTF-8?q?=E8=B6=85=E7=BA=A7=E7=AE=A1=E7=90=86=E5=91=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/config/config.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/config/config.php b/application/config/config.php index 82fb443e..684dda6a 100644 --- a/application/config/config.php +++ b/application/config/config.php @@ -660,7 +660,7 @@ $config['media_image_url_remote2'] = 'http://116.251.217.48:3581/upload'; //是否开启权限控制 $config['check_access'] = TRUE; //权限管理超级管理 -$config['access_super_manage'] = array('ycc', 'lmr'); +$config['access_super_manage'] = array('ycc', 'lmr', 'lyj'); //编辑器预览样式路径 $config['css_source_cht'] = '<link href="https://data.chinahighlights.com/css/min.php?f=/public/css/global.min.css,/css/festival-detail.css" rel="stylesheet">'; From d1b78f0c62a61add390bcfe0484dfb3e37eb7b2b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 13:23:30 +0800 Subject: [PATCH 279/382] =?UTF-8?q?Trippest=E7=AB=99=E7=82=B9=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=87=AA=E5=8A=A8=E5=BD=95=E5=85=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 128 +++++++++++++++++- .../paypal/models/paypal_model.php | 9 +- 2 files changed, 134 insertions(+), 3 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 545a94be..2dacf8a9 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -755,6 +755,7 @@ class Index extends CI_Controller { } //检测是否是APP订单,默认不处理 + // && $item->pn_payment_status !== 'Refunded' if ( ( (strpos($item->pn_memo, 'China Train Booking') !== false) || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) @@ -879,12 +880,135 @@ class Index extends CI_Controller { //echo 'done!'; } + public function send_refund($item) + { + // 找到原始收款交易的订单 + $parent_note = $this->note_modal->note($item->parent_txn_id); + if (empty($parent_note)) { + return false; + } + //订单号 + $orderid_info = $this->analysis_orderid($parent_note->pn_invoice); + + //找不到订单号,设置为发送失败标示 + if (empty($orderid_info)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); + return false; + } + + // for trippest tourMaster 2018.05.28 + if ($orderid_info->ordertype == 'TP') { + $this->trippest_note($orderid_info, $item); + return false; + } + + //根据订单号查找外联信息 + $orderid_info = json_decode($orderid_info); + $handpick = empty($pn_txn_id) ? false : TRUE; + $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); + + //查不到订单信息 + if (empty($advisor_info)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); + return false; + } + + //更新正确的订单信息到记录中,以这个为主 + $this->Note_model->set_invoice($item->pn_txn_id, $orderid_info->orderid . '_' . $orderid_info->ordertype); + + //添加支付信息入库 + //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 + if (!empty($orderid_info)) { + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); + $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + //更新还没有填的客邮和交易号de收款记录(商务订单) + if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { + $ht_memo = '退款交易号(自动录入):' . $item->pn_txn_id . "\n. "; + $ht_memo .= '原收款交易号(自动录入):' . $item->parent_txn_id; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } else { + // 把订单状态设置为13-新订单已支付 + if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { + $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } + $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + } + } + //更新还没有填的客邮和交易号de收款记录(传统订单) + elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { + $ht_memo = '退款交易号(自动录入):' . $item->pn_txn_id . "\n. "; + $ht_memo .= '原收款交易号(自动录入):' . $item->parent_txn_id; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + //添加汉特的订单提醒 + $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); + // 添加HT任务 // todo 是否还需要 + $this->Paypal_model->exec_addToTask($gai_sn); + } + } + + + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); + return false; + } + + //添加邮件发送记录 + //给外联发送通知邮件 + $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; + $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $M_RelatedInfo = $item->pn_sn; + $M_AddTime = $item->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + //添加邮件发送记录 end + + return $this->Note_model->update_send($item->pn_txn_id, 'send'); + } + public function trippest_note($orderid_info, $paypal_msg) { + $tp_orderid = "#" . substr($orderid_info->orderid, 10); + // 获取HT订单号 + $ht_tp_order = $this->Paypal_model->get_trippest_order($tp_orderid); + if (empty($ht_tp_order)) { + return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail'); + } + //更新正确的订单信息到记录中,以这个为主 + $this->Note_model->set_invoice($item->pn_txn_id, $ht_tp_order->COLI_ID . '_B'); + $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); + $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; + $this->Paypal_model->add_account_info( + $ht_tp_order->COLI_SN, + $ht_tp_order->COLI_ID, + $item->pn_mc_gross, + $item->pn_payment_date, + mb_strtoupper($item->pn_mc_currency), + $ssje, + $item->pn_payment_date, + $item->pn_payment_date, + $item->pn_payment_date, + '', + $item->pn_payer_email, + $item->pn_txn_id, + $ht_memo + ); + $opi_firstname = "David"; $opi_email = "david@trippest.com"; - $orderid_info->orderid = $orderid_info->orderid . "#" . substr($orderid_info->orderid, 10); - + $orderid_info->orderid = $orderid_info->orderid . "#" . $tp_orderid; $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; $toName = !empty($opi_firstname) ? $opi_firstname : ''; diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 5ee4b9ad..c32c7a05 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -212,7 +212,7 @@ class Paypal_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15010,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,?,15002,?,?,?,?,?,?,?,?,?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; @@ -602,4 +602,11 @@ class Paypal_model extends CI_Model { ); return $this->HT->insert("BIZ_OrderOperationLog", $db_column); } + + public function get_trippest_order($tp_order) + { + $sql = "SELECT top 1 * from BIZ_ConfirmLineInfo + WHERE COLI_PriceMemo=? "; + return $this->HT->query($sql, array($tp_order))->row(); + } } From c25105bba8251977c3fc95d11a47863e3826f9d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 16:52:32 +0800 Subject: [PATCH 280/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E5=A4=84=E7=90=8630%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 2dacf8a9..e6ba1bd4 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -714,6 +714,7 @@ class Index extends CI_Controller { //找到没有发送的记录 public function send_note($pn_txn_id = false, $old_ssje=NULL) { $data = array(); + $handpick = empty($pn_txn_id) ? false : TRUE; //优先处理指定的交易号,用于修正交易号直接发送通知 if (!empty($pn_txn_id)) { @@ -880,7 +881,7 @@ class Index extends CI_Controller { //echo 'done!'; } - public function send_refund($item) + public function send_refund($item, $handpick, $old_ssje=NULL) { // 找到原始收款交易的订单 $parent_note = $this->note_modal->note($item->parent_txn_id); @@ -904,7 +905,6 @@ class Index extends CI_Controller { //根据订单号查找外联信息 $orderid_info = json_decode($orderid_info); - $handpick = empty($pn_txn_id) ? false : TRUE; $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); //查不到订单信息 @@ -931,7 +931,6 @@ class Index extends CI_Controller { $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } else { - // 把订单状态设置为13-新订单已支付 if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } @@ -946,8 +945,6 @@ class Index extends CI_Controller { $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 $this->Paypal_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . mb_strtoupper($item->pn_mc_currency) . $item->pn_mc_gross); - // 添加HT任务 // todo 是否还需要 - $this->Paypal_model->exec_addToTask($gai_sn); } } @@ -973,8 +970,10 @@ class Index extends CI_Controller { $M_AddTime = $item->pn_payment_date; $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + // TODO 通知财务, 如果已做账 //添加邮件发送记录 end + return $this->Note_model->update_send($item->pn_txn_id, 'send'); } From 6ce3c4b338838f1f429f1e5b56a065c51dd5b0df Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 16:55:23 +0800 Subject: [PATCH 281/382] =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 2c414461..d9f4cf39 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -621,7 +621,9 @@ var_dump($response->$responseNode); $data['notelist'] = $this->Alipay_note_model->search_key($data['keywords']); /** 手动查询通过收钱码的收款, 必须输入交易号 */ if (empty($data['notelist'])) { + log_message('error','Alipay query ' . $data["keywords"]); $query_pay = $this->query_pay($data["keywords"]); + log_message('error','Alipay query result ' . var_export($query_pay, 1)); if ( ! empty($query_pay) && strval($query_pay->code)==="10000" && strval($query_pay->trade_status)==="TRADE_SUCCESS") { $pay_type = $query_pay->total_amount>0 ? "pay" : "refund"; $new_record = $this->Alipay_note_model->save_alipay( From fafa1ad0177e8ecfe59243cc7874a374988f0134 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 17:05:34 +0800 Subject: [PATCH 282/382] =?UTF-8?q?Alipay=20=E7=8A=B6=E6=80=81:=E4=BA=A4?= =?UTF-8?q?=E6=98=93=E7=BB=93=E6=9D=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index d9f4cf39..277c4e4f 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -113,7 +113,8 @@ class AlipayTradeService extends CI_Controller } $code = isset($asyns_resp->data->code) ? strval($asyns_resp->data->code) : NULL ; $buyer = isset($asyns_resp->data->buyer_logon_id) ? strval($asyns_resp->data->buyer_logon_id) : NULL ; - if (strcmp(trim(strval($asyns_resp->data->trade_status)), "TRADE_SUCCESS") == 0) { + if (strcmp(trim(strval($asyns_resp->data->trade_status)), "TRADE_SUCCESS") == 0 + || strcmp(trim(strval($asyns_resp->data->trade_status)), "TRADE_FINISHED") == 0) { if ($notify_type === "pay") { $this->Alipay_note_model->save_alipay( strval($asyns_resp->data->trade_no) @@ -624,7 +625,8 @@ var_dump($response->$responseNode); log_message('error','Alipay query ' . $data["keywords"]); $query_pay = $this->query_pay($data["keywords"]); log_message('error','Alipay query result ' . var_export($query_pay, 1)); - if ( ! empty($query_pay) && strval($query_pay->code)==="10000" && strval($query_pay->trade_status)==="TRADE_SUCCESS") { + if ( ! empty($query_pay) && strval($query_pay->code)==="10000" + && in_array(strval($query_pay->trade_status), array("TRADE_SUCCESS", "TRADE_FINISHED")) ) { $pay_type = $query_pay->total_amount>0 ? "pay" : "refund"; $new_record = $this->Alipay_note_model->save_alipay( strval($query_pay->trade_no) From 0f955f66b6a2f609411227e4c9af5e995aec7a79 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 17:30:41 +0800 Subject: [PATCH 283/382] =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 277c4e4f..a03e682d 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -622,9 +622,7 @@ var_dump($response->$responseNode); $data['notelist'] = $this->Alipay_note_model->search_key($data['keywords']); /** 手动查询通过收钱码的收款, 必须输入交易号 */ if (empty($data['notelist'])) { - log_message('error','Alipay query ' . $data["keywords"]); $query_pay = $this->query_pay($data["keywords"]); - log_message('error','Alipay query result ' . var_export($query_pay, 1)); if ( ! empty($query_pay) && strval($query_pay->code)==="10000" && in_array(strval($query_pay->trade_status), array("TRADE_SUCCESS", "TRADE_FINISHED")) ) { $pay_type = $query_pay->total_amount>0 ? "pay" : "refund"; From 8ca66f997f8134f9e5e38549ae009d7d9463480a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 19 Apr 2019 17:52:02 +0800 Subject: [PATCH 284/382] =?UTF-8?q?Alipay=20=E7=8A=B6=E6=80=81:=E4=BA=A4?= =?UTF-8?q?=E6=98=93=E7=BB=93=E6=9D=9F=20=E8=87=AA=E5=8A=A8=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index a03e682d..709e64bf 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -359,7 +359,8 @@ class AlipayTradeService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")) { + if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS") + || strcmp(trim($item->ALI_resultMsg), "TRADE_FINISHED")) { $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); continue; } From 51a7f9ef470875ca7d3344ac1689fb66dfb99b23 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Apr 2019 10:04:54 +0800 Subject: [PATCH 285/382] =?UTF-8?q?wxpay=20=E4=BF=AE=E6=94=B9=E8=AF=BB?= =?UTF-8?q?=E5=8F=96post=E6=95=B0=E6=8D=AE=E7=9A=84=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/WxpayService.php | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php index e073dbd1..5f7f8e74 100644 --- a/webht/third_party/pay/controllers/WxpayService.php +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -29,12 +29,14 @@ log_message('error','notify begin ----'); $response['return_msg'] = ''; $GLOBALS['__WX_SITE_NAME__'] = $site; $this->wx_site_config = $this->config->item($GLOBALS['__WX_SITE_NAME__'], 'wxpay'); - if (!isset($GLOBALS['HTTP_RAW_POST_DATA'])) { + $raw_post_data = file_get_contents('php://input'); +// log_message('error',var_export($raw_post_data, 1)); + if (empty($raw_post_data) ){ # 如果没有数据,直接返回失败 return $this->response_to_wx($response); } //获取通知的数据 - $xml = $GLOBALS['HTTP_RAW_POST_DATA']; + $xml = $raw_post_data; $xml_arr = from_xml($xml); // log_message('error',var_export($xml_arr, 1)); if ($this->check_sign($xml_arr) !== true) { From a06156b1cb0757f556b9653b2a6fbd39abf15593 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 22 Apr 2019 10:27:50 +0800 Subject: [PATCH 286/382] =?UTF-8?q?paypal=20Trippest=E7=AB=99=E7=9A=84?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E8=87=AA=E5=8A=A8=E5=BD=95=E5=85=A5=E8=AE=A2?= =?UTF-8?q?=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index e6ba1bd4..b844043f 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -986,22 +986,22 @@ class Index extends CI_Controller { return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail'); } //更新正确的订单信息到记录中,以这个为主 - $this->Note_model->set_invoice($item->pn_txn_id, $ht_tp_order->COLI_ID . '_B'); - $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); - $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; + $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_B'); + $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); + $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; $this->Paypal_model->add_account_info( $ht_tp_order->COLI_SN, $ht_tp_order->COLI_ID, - $item->pn_mc_gross, - $item->pn_payment_date, - mb_strtoupper($item->pn_mc_currency), + $paypal_msg->pn_mc_gross, + $paypal_msg->pn_payment_date, + mb_strtoupper($paypal_msg->pn_mc_currency), $ssje, - $item->pn_payment_date, - $item->pn_payment_date, - $item->pn_payment_date, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, '', - $item->pn_payer_email, - $item->pn_txn_id, + $paypal_msg->pn_payer_email, + $paypal_msg->pn_txn_id, $ht_memo ); From b8d580e40c880eff63ce0ce75feb2556b26ae95e Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 22 Apr 2019 10:52:08 +0800 Subject: [PATCH 287/382] =?UTF-8?q?=E5=BE=B7=E8=AF=AD=E7=AB=99=E5=9C=A8?= =?UTF-8?q?=E9=9D=99=E6=80=81=E5=8C=96=E6=9B=B4=E6=96=B0=E6=97=B6=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E4=B8=80=E4=B8=AA=E6=A0=87=E8=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/views/bootstrap3/information_edit.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/views/bootstrap3/information_edit.php b/application/views/bootstrap3/information_edit.php index a2bf64f4..904c5b19 100644 --- a/application/views/bootstrap3/information_edit.php +++ b/application/views/bootstrap3/information_edit.php @@ -336,7 +336,7 @@ } //德语站点跳转测试页面 function goto_gmtest_page() { - var site_url = 'http://gm.test/gm.php/information/detail/?static_html_url='; + var site_url = 'http://gm.test/gm.php/information/detail/?cache=false&static_html_url='; $('#goto_test_page_button').attr("href", site_url + $('#ic_url').val()); return true; } From a93320bca0d040d9e0c1965bbe158a47c72b0751 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 23 Apr 2019 10:09:48 +0800 Subject: [PATCH 288/382] =?UTF-8?q?paypal=20Trippest=E7=9A=84=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=87=AA=E5=8A=A8=E5=BD=95=E5=85=A5=E8=AE=A2=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 48 ++++++++++++------- .../paypal/models/paypal_model.php | 8 ++-- 2 files changed, 36 insertions(+), 20 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index b844043f..dcc4b8ea 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -647,7 +647,9 @@ class Index extends CI_Controller { $ordertype = 'N'; if (isset($note_invoice_string[1])) { $ordertype_temp = trim($note_invoice_string[1]); - if (substr($ordertype_temp, 0, 1) == 'T') { + if (substr($ordertype_temp, 0, 2) == 'TP') { + $ordertype = 'TP'; + } elseif (substr($ordertype_temp, 0, 1) == 'T') { $ordertype = 'T'; } elseif (substr($ordertype_temp, 0, 1) == 'B') { $ordertype = 'B'; @@ -979,14 +981,21 @@ class Index extends CI_Controller { public function trippest_note($orderid_info, $paypal_msg) { - $tp_orderid = "#" . substr($orderid_info->orderid, 10); + $tp_orderid = ''; + $real_orderid = $orderid_info->orderid; + if (substr($orderid_info->orderid, 0, 2) == '01') { + $tp_orderid = "#" . substr($orderid_info->orderid, 10); + $real_orderid = ''; + } // 获取HT订单号 - $ht_tp_order = $this->Paypal_model->get_trippest_order($tp_orderid); + $ht_tp_order = $this->Paypal_model->get_trippest_order($tp_orderid, $real_orderid); if (empty($ht_tp_order)) { return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail'); } + $tp_orderid = $ht_tp_order->COLI_PriceMemo; + $real_orderid = $ht_tp_order->COLI_ID; //更新正确的订单信息到记录中,以这个为主 - $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_B'); + $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_TP'); $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; $this->Paypal_model->add_account_info( @@ -1004,20 +1013,25 @@ class Index extends CI_Controller { $paypal_msg->pn_txn_id, $ht_memo ); + if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) { + $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); + $this->Paypal_model->insert_biz_order_log($ht_tp_order->COLI_SN, 'BS13'); + $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15002'); + + $opi_firstname = "David"; + $opi_email = "david@trippest.com"; + $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; + $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $real_orderid . $tp_orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo; + $M_RelatedInfo = $paypal_msg->pn_sn; + $M_AddTime = $paypal_msg->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + } - $opi_firstname = "David"; - $opi_email = "david@trippest.com"; - $orderid_info->orderid = $orderid_info->orderid . "#" . $tp_orderid; - $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; - $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; - $toName = !empty($opi_firstname) ? $opi_firstname : ''; - $toEmail = !empty($opi_email) ? $opi_email : ''; - $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo; - $M_RelatedInfo = $paypal_msg->pn_sn; - $M_AddTime = $paypal_msg->pn_payment_date; - $M_State = 0; - $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); $this->Note_model->update_send($paypal_msg->pn_txn_id, 'send'); } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index c32c7a05..df8808e5 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -603,10 +603,12 @@ class Paypal_model extends CI_Model { return $this->HT->insert("BIZ_OrderOperationLog", $db_column); } - public function get_trippest_order($tp_order) + public function get_trippest_order($tp_order='', $real_orderid='') { $sql = "SELECT top 1 * from BIZ_ConfirmLineInfo - WHERE COLI_PriceMemo=? "; - return $this->HT->query($sql, array($tp_order))->row(); + WHERE 1=1 "; + $tp_order ? $sql.=" and COLI_PriceMemo=$tp_order " : ""; + $real_orderid ? $sql.=" and COLI_ID=$real_orderid " : ""; + return $this->HT->query($sql)->row(); } } From ab26a780cd58d92c97b9181295872aec335f5dc8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 24 Apr 2019 10:53:50 +0800 Subject: [PATCH 289/382] =?UTF-8?q?paypal=20Trippest=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E7=9A=84=E7=8B=AC=E7=AB=8B=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 38 +++++++++++-------- 1 file changed, 22 insertions(+), 16 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index dcc4b8ea..6b77fd14 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -998,25 +998,10 @@ class Index extends CI_Controller { $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_TP'); $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; - $this->Paypal_model->add_account_info( - $ht_tp_order->COLI_SN, - $ht_tp_order->COLI_ID, - $paypal_msg->pn_mc_gross, - $paypal_msg->pn_payment_date, - mb_strtoupper($paypal_msg->pn_mc_currency), - $ssje, - $paypal_msg->pn_payment_date, - $paypal_msg->pn_payment_date, - $paypal_msg->pn_payment_date, - '', - $paypal_msg->pn_payer_email, - $paypal_msg->pn_txn_id, - $ht_memo - ); if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) { $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); $this->Paypal_model->insert_biz_order_log($ht_tp_order->COLI_SN, 'BS13'); - $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15002'); + $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15010'); $opi_firstname = "David"; $opi_email = "david@trippest.com"; @@ -1031,6 +1016,21 @@ class Index extends CI_Controller { $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); } + $this->Paypal_model->add_account_info( + $ht_tp_order->COLI_SN, + $ht_tp_order->COLI_ID, + $paypal_msg->pn_mc_gross, + $paypal_msg->pn_payment_date, + mb_strtoupper($paypal_msg->pn_mc_currency), + $ssje, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, + '', + $paypal_msg->pn_payer_email, + $paypal_msg->pn_txn_id, + $ht_memo + ); $this->Note_model->update_send($paypal_msg->pn_txn_id, 'send'); } @@ -1341,6 +1341,9 @@ class Index extends CI_Controller { $orderid_info = $this->analysis_orderid($data['note']->pn_invoice); if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'TP') { + $orderid_info->ordertype = 'B'; + } if ($orderid_info->ordertype === 'T') { $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id); if ( ! empty($data['gai_info'])) { @@ -1360,6 +1363,9 @@ class Index extends CI_Controller { $orderid_info = $this->analysis_orderid($neworder); if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'TP') { + $orderid_info->ordertype = 'B'; + } $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, TRUE); if (!empty($advisor_info)) { $this->Note_model->set_invoice($pn_txn_id, $neworder); From 43b9bf720534b21dacc03eaaa7de2a1bdadbdff1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 24 Apr 2019 11:01:05 +0800 Subject: [PATCH 290/382] =?UTF-8?q?wxpay=20=E6=94=B6=E6=AC=BE=E5=BC=82?= =?UTF-8?q?=E6=AD=A5=E9=80=9A=E7=9F=A5=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/paypal.php | 2 + .../pay/controllers/PaymentService.php | 244 +++++++++++++++- .../pay/helpers/payment_helper.php | 8 +- .../models/Online_payment_account_model.php | 270 ++++++++++++++++++ .../pay/models/Online_payment_note_model.php | 35 ++- 5 files changed, 540 insertions(+), 19 deletions(-) diff --git a/webht/third_party/pay/config/paypal.php b/webht/third_party/pay/config/paypal.php index 70dcceaa..f0a6743a 100644 --- a/webht/third_party/pay/config/paypal.php +++ b/webht/third_party/pay/config/paypal.php @@ -1,4 +1,6 @@ <?php + +$config["method_code"] = 15002; // ycc sanbox // $config['client_id'] = "AVfErlDftQcNj22239jNQmTV-J-rLqBdNf3HZO0-McmElUDxadiF8vAQdeXmZAnB_nKy06ZwFazs1kKU"; // $config['secret'] = "EJUmlpxrNHkm3Kv4xBd1Qm2_kLGAmAcS8hbYKarYGAvQrDaJT-HrPgx_AEXL12-mt_3EM2KqM_E2eJtt"; diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index 72dbf507..c01d4a43 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -1,13 +1,16 @@ <?php defined('BASEPATH') OR exit('No direct script access allowed'); +// global $__PAYMENT_METHOD_CODE__; + class PaymentService extends CI_Controller { public function __construct(){ parent::__construct(); bcscale(2); $this->load->helper('payment'); - // $this->config->load('wxpay', true); + $this->config->load('wxpay', true); + $this->config->load('paypal', true); $this->load->model('Online_payment_note_model', 'note_model'); $this->load->model('Online_payment_account_model', 'account_model'); } @@ -17,26 +20,245 @@ class PaymentService extends CI_Controller { } - public function send_notify($payment_method=NULL, $transactionId=NULL) + public function send_notify($transaction_id=NULL, $old_ssje=NULL) { - // $save_column['OPN_accountType'] = $xml_arr['']; - // $save_column['OPN_accountStatus'] = $xml_arr['']; - // $save_column['OPN_accountTime'] = $xml_arr['']; +log_message('error','send_notify begin ----'); +// exit(); $data = array(); - $int = 0; - + $show_index = 0; //优先处理指定的交易号,用于修正交易号直接发送通知 - if ( ! empty($transactionId)) { - $data['unsend_list'] = $this->note_model->get_note($payment_method, $transactionId); + if ( ! empty($transaction_id)) { + $data['unsend_list'] = $this->note_model->get_note($transaction_id); } // 待处理的 if (empty($data['unsend_list'])) { - $data['unsend_list'] = $this->note_model->unsend_note($payment_method, 10); + $data['unsend_list'] = $this->note_model->unsend_note(10); } //没有未处理的数据再查找处理失败的数据 if (empty($data['unsend_list'])) { - $data['unsend_list'] = $this->note_model->sendfail_note($payment_method, 20); + $data['unsend_list'] = $this->note_model->sendfail_note(20); + } + // 开始处理 + foreach ($data['unsend_list'] as $key => $item) { + //显示处理记录 + if (empty($transaction_id)) { + echo ++$show_index . ' ' . $item->OPN_transactionId . '<br/>'; + } + // 只处理完成状态 + if ($item->OPN_transactionResult != 'completed') { + continue; + } + if ($item->OPN_noticeType == 'Refunded') { + // 退款处理 + continue ; + } + + // 提取订单号 + $orderid_info = analysis_orderid($item->OPN_orderId); // 先用已设置过的 + if (empty($orderid_info)) { + $orderid_info = $this->method_analysis_orderid($item->OPN_accountMethod, $item->OPN_rawContent); + if (empty($orderid_info)) { + $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'sendfail'); + continue; + } + } + $orderid_info = json_decode($orderid_info); + // TODO Trippest的订单号要特别查询 + // 填入提取到的订单号 + $this->note_model->set_invoice($item->OPN_SN, $orderid_info->orderid . '_' . $orderid_info->ordertype); + + // APP自动出票的收款 跳过 + if ($orderid_info->ordertype === 'A' && $item->OPN_noticeType === 'pay') { + $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'closed'); + continue; + } + + // 开始查找订单和录入 + $handpick = empty($transaction_id) ? false : true; + $advisor_info = $this->account_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); + $ssje = $this->account_model->get_ssje($item->OPN_orderAmount, $item->OPN_accountMethod, mb_strtoupper($item->OPN_currency)); + $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + $ht_memo = '交易号(自动录入):' . $item->OPN_transactionId; + if ( ! isset($advisor_info->ordertype)) { + // record fail + $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'sendfail'); + continue; + } + $COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + $update_note_column = array(); + if ($advisor_info->ordertype == 0) { + /* 商务订单 */ + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { + /* APP */ + $this->account_model->add_account_info_forAPP( + $COLI_SN, + $item->OPN_accountMethod, + $advisor_info->COLI_ID, + $item->OPN_orderAmount, + $item->OPN_completeTime, + mb_strtoupper($item->OPN_currency), + $ssje, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_payerName, + $item->OPN_payerEmail, + $item->OPN_transactionId, + $ht_memo + ); + if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { + //只修改APP组的订单状态,并且订单进度是我的订单 + $this->account_model->update_biz_coli_state($COLI_SN, 8); //把订单状态改为已付款 + $this->account_model->insert_biz_order_log($COLI_SN, 'BS8'); + } + } else { + /* 其他商务订单 */ + // 第一次录入收款记录时变更状态,记录日志 + if (false == $this->account_model->if_biz_gai_exists($item->OPN_transactionId) ) { + $this->account_model->update_biz_coli_state($COLI_SN, 13); + $this->account_model->insert_biz_order_log($COLI_SN, 'BS13'); + } + $this->account_model->add_account_info( + $COLI_SN, + $item->OPN_accountMethod, + $advisor_info->COLI_ID, + $item->OPN_orderAmount, + $item->OPN_completeTime, + mb_strtoupper($item->OPN_currency), + $ssje, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_payerName, + $item->OPN_payerEmail, + $item->OPN_transactionId, + $ht_memo + ); + // 更新订单主表付款方式,防止没访问thankyou-train.asp + $this->account_model->update_paymanner($COLI_SN, $item->OPN_accountMethod); + } + // 更新note + $update_note_column['OPN_accountType'] = 'B'; + $update_note_column['OPN_accountStatus'] = 'recorded'; + $update_note_column['OPN_accountTime'] = date('Y-m-d H:i:s'); + } elseif ($advisor_info->ordertype == 1) { + /* 传统 */ + $gai_sn = $this->account_model->add_tour_account_info( + $COLI_SN, + $item->OPN_accountMethod, + $item->OPN_orderAmount, + $item->OPN_completeTime, + mb_strtoupper($item->OPN_currency), + $ssje, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_completeTime, + $item->OPN_payerName, + $item->OPN_payerEmail, + $item->OPN_transactionId, + $ht_memo + ); + //添加汉特的订单提醒 + $this->account_model->update_coli_introduction($COLI_SN, '已支付 ' . mb_strtoupper($item->OPN_currency) . $item->OPN_orderAmount); + // 添加HT任务 + $this->account_model->exec_addToTask($gai_sn); + // 更新note + $update_note_column['OPN_accountType'] = 'B'; + $update_note_column['OPN_accountStatus'] = 'recorded'; + $update_note_column['OPN_accountTime'] = date('Y-m-d H:i:s'); + } + // 更新note + if ( ! empty($update_note_column)) { + $where = " OPN_SN=" . $item->OPN_SN; + $this->note_model->update_note($where, $update_note_column); + } + // 邮件外联 + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'sendfail'); + continue; + } + //添加邮件发送记录 + //给外联发送通知邮件 + $fromName = !empty($item->OPN_payerName) ? $item->OPN_payerName : ''; + $fromEmail = !empty($item->OPN_payerEmail) ? $item->OPN_payerEmail : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->OPN_orderAmount . $item->OPN_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $M_RelatedInfo = $item->OPN_SN; + $M_AddTime = $item->OPN_completeTime; + $M_State = 0; + $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'payment note', 'payment note'); + //添加邮件发送记录 end + + $this->note_model->update_send($item->OPN_SN, $item->pn_txn_id, 'send'); + + + } + return; + // return $this->output->set_content_type('application/json')->set_output(json_encode($data)); + } + + /** 支付方式参数对应的配置文件名 */ + public function method_name($name) + { + $config_name = 'paypal'; + switch ($name) { + case 'paypal': + $config_name = 'paypal'; + break; + case 'weixin': + $config_name = 'wxpay'; + break; + case 'ipaylinks': + $config_name = 'iPayLinks'; + break; + case 'alipay': + $config_name = 'alipay'; + break; + + default: + # code... + break; + } + return $config_name; + } + + private function method_analysis_orderid($name, $raw_content) + { + $content_obj = json_decode($raw_content); + $orderid_info = array(); + switch (strval($name)) { + case '15002': + case '15010': // paypal + $orderid_info = analysis_orderid($content_obj->invoice); + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->transaction_subject) : NULL; + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->custom) : NULL; + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->item_name) : NULL; + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->item_name1) : NULL; + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->item_number) : NULL; + empty($orderid_info) ? $orderid_info = analysis_orderid($content_obj->item_number1) : NULL; + break; + + case '15016': // wxpay + $orderid_info = analysis_orderid($content_obj->out_trade_no); + break; + + case '15018': // iPaylinks + break; + + case '15015': // alipay + break; + + + default: + # code... + break; } + return $orderid_info; } } diff --git a/webht/third_party/pay/helpers/payment_helper.php b/webht/third_party/pay/helpers/payment_helper.php index 53ceac5e..80dc5010 100644 --- a/webht/third_party/pay/helpers/payment_helper.php +++ b/webht/third_party/pay/helpers/payment_helper.php @@ -130,12 +130,18 @@ function analysis_orderid($note_invoice_string) { $ordertype = 'N'; if (isset($note_invoice_string[1])) { $ordertype_temp = trim($note_invoice_string[1]); - if (substr($ordertype_temp, 0, 1) == 'T') { + if (substr($ordertype_temp, 0, 2) == 'TP') { + $ordertype = 'TP'; + } elseif (substr($ordertype_temp, 0, 1) == 'T') { $ordertype = 'T'; } elseif (substr($ordertype_temp, 0, 1) == 'B') { $ordertype = 'B'; } } + // 2018.05.28 for Trippest, tourMaster的订单号是01开头 + if (substr($note_invoice_string[0], 0, 2) == '01') { + $ordertype = 'TP'; + } //手机订单、机票订单都没有加标示,在这里帮加上,暂时的,今后还是要在网前设置好 if ($ordertype == 'N' && isset($note_invoice_string[0])) { diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index 3c19ea87..3a42e20e 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -23,5 +23,275 @@ class Online_payment_account_model extends CI_Model { return NULL; } + //根据订单号获取外联邮箱 + public function get_order($COLI_ID, $orderinfo = false, $ordertype = 'N', $handpick=false) { + $result = ''; + $fieldsql = $orderinfo == false ? '' : " ,* "; + //先查商务订单B,APP订单A、再查传统订单T + if ($ordertype == 'B' || $ordertype == 'A') { + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_ID =?"; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 + if (empty($result) && ($ordertype == 'T')) { + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_ID like '%$COLI_ID' + order by CHARINDEX('$COLI_ID', COLI_ID) "; + $query = $this->HT->query($sql); + $result = $query->result(); + if ($handpick === TRUE) { + $result = array($result[0]); + } + } + + //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 + + if (empty($result) && ($ordertype == 'M')) { + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_AddCode =? "; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + + if (empty($result) && ($ordertype == 'M')) { + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where + EXISTS ( + SELECT TOP 1 1 + FROM ConfirmLineInfoTmp clit + WHERE clit.COLI_ID = ? + AND cli.COLI_AddCode = CAST(clit.COLI_SN AS VARCHAR(10)) + ) + "; + $query = $this->HT->query($sql, array($COLI_ID)); + $result = $query->result(); + } + + //订单号查询不到尝试使用团号查询 + if (empty($result) && $ordertype == 'B') { + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN + where COLI_GroupCode like '%-$COLI_ID%'"; + $query = $this->HT->query($sql); + $result = $query->result(); + } + //团号查询不到尝试使用客人邮箱查询(预订多次的老客户得按日期新旧排序,取最新的数据) + + if (!empty($result) && is_array($result) ) { + //print_r($result[0]); + //die(); + if (count($result) > 1) { + $result = array(); + } else { + $result = $result[0]; + } + } + + return $result; + } + + public function if_biz_gai_exists($GAI_AccreditNo) + { + $sql = " SELECT TOP 1 1 FROM BIZ_GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') + AND DeleteFlag=0"; + $result = $this->HT->query($sql, array($GAI_AccreditNo)); + return ($result->num_rows() > 0); + } + + //修改订单状态 + public function update_biz_coli_state($coli_sn, $coli_state) { + $sql = " + IF EXISTS + ( SELECT OPI_DEI_SN + FROM OperatorInfo + INNER JOIN BIZ_ConfirmLineInfo ON OPI_SN=COLI_OPI_ID + WHERE COLI_SN=? AND OPI_DEI_SN=10 + ) + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? + WHERE COLI_SN=? + ELSE + UPDATE BIZ_ConfirmLineInfo + SET COLI_State=? WHERE COLI_SN=? + AND COLI_State IN (0,1,9,11,12,13,14,40,50,60,101,102,999) + "; + $query = $this->HT->query($sql, array($coli_sn, $coli_state, $coli_sn, $coli_state, $coli_sn)); + return $query; + } + + /** 写入商务订单操作记录 */ + public function insert_biz_order_log($coli_sn, $log_info) + { + $db_column = array( + "BOL_COLI_SN" => $coli_sn + ,"BOL_OPI_SN" => 0 + ,"BOL_OPType" => $log_info + ,"BOL_OPTime" => date('Y-m-d H:i:s') + ,"BOL_Creator" => 0 + ,"BOL_CreateTime" => date('Y-m-d H:i:s') + ); + return $this->HT->insert("BIZ_OrderOperationLog", $db_column); + } + + /*! + * 更新订单主表付款方式,防止没访问thankyou-train.asp + * @author LYT <lyt@hainatravel.com> + * @date 2017-11-27 + */ + public function update_paymanner($COLI_SN, $paymanner = '15010') + { + $sql = "UPDATE BIZ_ConfirmLineInfo SET COLI_PayManner = ? WHERE COLI_SN=? "; + $query = $this->HT->query($sql, array($paymanner, $COLI_SN)); + return $query; + } + + //添加收款记录(商务订单) + public function add_account_info($GAI_COLI_SN, $payment_method, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + + IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') AND DeleteFlag=0 + ) + INSERT INTO BIZ_GroupAccountInfo ( + GAI_COLI_SN + ,GAI_COLI_ID + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSJE + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $payment_method, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); + return $query; + } + + //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 + public function add_account_info_forAPP($GAI_COLI_SN, $payment_method, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + IF NOT EXISTS( + SELECT TOP 1 1 + FROM BIZ_GroupAccountInfo + WHERE GAI_COLI_SN = ? AND GAI_SQJE=? AND DeleteFlag=0 AND GAI_Type=? + ) + INSERT INTO BIZ_GroupAccountInfo ( + GAI_COLI_SN + ,GAI_COLI_ID + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSJE + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $payment_method, $GAI_COLI_SN, $GAI_COLI_ID, $payment_method, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); + return $query; + } + + //添加收款记录(传统订单) + public function add_tour_account_info($GAI_COLI_SN, $payment_method, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + //先判断是否有这条数据 + $sql = " + + IF NOT EXISTS( + SELECT TOP 1 1 + FROM GroupAccountInfo + WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') and DeleteFlag=0 + ) + INSERT INTO GroupAccountInfo ( + GAI_COLI_SN + ,GAI_Type + ,GAI_SQJE + ,GAI_SQDate + ,GAI_SQJECurrency + ,GAI_SSJE + ,GAI_SSDate + ,GAI_AccountDate + ,GAI_SubmitDate + ,GAI_CusName + ,GAI_CusEmail + ,GAI_AccreditNo + ,GAI_Memo + ,GAI_State + ,DeleteFlag + ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $payment_method, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $insertid = $this->HT->last_id('GroupAccountInfo'); + return $insertid; + } + + //更新线路提醒 + public function update_coli_introduction($coli_sn, $msg) { + $sql = " + update ConfirmLineInfo + set COLI_Introduction=ISNULL(COLI_Introduction,'')+' '+? + where 1=1 + AND ISNULL(COLI_Introduction,'')='' + AND COLI_SN=? + "; + // isnull(COLI_Sended,0) in (0,1) 之前判断是新订单或者未分配状态才添加提示的,有些团是后面付款的,所以把限制取消掉 + $query = $this->HT->query($sql, array($msg, $coli_sn)); + return $query; + } + + /** JJH: 添加订单收款记录之后执行 */ + public function exec_addToTask($GAI_SN) + { + $sql = " if not exists ( + select top 1 1 from Sysautotask + where SAT_Type=1 and SAT_SourceSN=$GAI_SN + ) exec SP_AddToSystask 1," . $GAI_SN; + $query = $this->HT->query($sql); + return $query; + } + + public function save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo = '', $M_State = 0, $M_AddTime = '', $frominfo = 'paypal msg', $M_Web = 'paypal msg') { + $sql = "INSERT INTO + Email_AutomaticSend ( + M_ReplyToName, + M_ReplyToEmail, + M_ToName, + M_ToEmail, + M_Title, + M_Body, + M_Web, + M_FromName, + M_ServiceSN, + M_State, + M_AddTime + ) VALUES (N?, N?, N?, N?, N?, N?, ?, N?, ?,?,getdate()) "; + $query = $this->HT->query($sql, array($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_Web, $frominfo, $M_RelatedInfo, $M_State)); + return $query; + } + } diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php index 86f4a9cc..5d0205e3 100644 --- a/webht/third_party/pay/models/Online_payment_note_model.php +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -25,44 +25,65 @@ class Online_payment_note_model extends CI_Model { return TRUE; } + public function update_send($id, $transactionId, $send) + { + $column = array("OPN_noticeSendStatus" => $send, "OPN_noticeSendTime" => date('Y-m-d H:i:s')); + $where = " OPN_transactionId = '$transactionId' AND OPN_SN=" . $id; + return $this->update_note($where, $column); + } + + //设置订单号 + public function set_invoice($id, $pn_invoice) + { + $column = array("OPN_orderId" => $send); + $where = " OPN_SN=" . $id; + return $this->update_note($where, $column); + } + public $topnum = false; public $orderby = false; public $send = false; public $search = false; public $transactionId = false; public $payment_status = false; + // public $payment_method = false; + public function init_query() { $this->topnum = false; $this->send = false; $this->search = false; $this->payment_status = false; $this->transactionId = false; - $this->orderby = ' ORDER BY OPN_SN DESC '; + // if ($GLOBALS['__PAYMENT_METHOD_CODE__']) { + // $this->payment_method = ' AND opn.OPN_accountMethod = ' . $GLOBALS['__PAYMENT_METHOD_CODE__'] . ' '; + // } + $this->orderby = ' ORDER BY OPN_SN DESC '; } public function query_note() { $top_sql = $this->topnum ? (" TOP " . $this->topnum) : ""; - $sql .= "SELECT $top_sql opn.* + $sql = "SELECT $top_sql opn.* FROM [InfoManager].[dbo].[OnlinePaymentNote] opn WHERE 1=1 "; + // $this->payment_method ? $sql.=$this->payment_method : false; $this->send ? $sql.=$this->send : false; $this->search ? $sql.=$this->search : false; $this->transactionId ? $sql.=$this->transactionId : false; $this->orderby ? $sql.=$this->orderby : false; - $query = $this->INFO->query($sql); + $query = $this->info->query($sql); return $query->result(); } - public function get_note($payment_method=NULL, $transactionId=null) + public function get_note($transactionId) { $this->init_query(); $this->topnum=1; - $this->transactionId = " AND opn.OPN_transactionId=" . $this->INFO->escape($transactionId); + $this->transactionId = " AND opn.OPN_transactionId=" . $this->info->escape($transactionId); return $this->query_note(); } - public function unsend_note($payment_method=NULL, $num=2) + public function unsend_note($num=2) { $this->init_query(); $this->topnum = $num; @@ -70,7 +91,7 @@ class Online_payment_note_model extends CI_Model { return $this->query_note(); } - public function sendfail_note($payment_method=NULL, $num=2) + public function sendfail_note($num=2) { $this->init_query(); $this->topnum = $num; From 52839d2b9a700b472ccbf3a80c8272774871b20c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 24 Apr 2019 13:55:38 +0800 Subject: [PATCH 291/382] =?UTF-8?q?paypal=20Trippest=E7=AB=99=E7=9A=84?= =?UTF-8?q?=E6=94=B6=E6=AC=BE=E5=9C=A8=E6=9C=AA=E6=89=BE=E5=88=B0=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=97=B6=E5=85=88=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5?= =?UTF-8?q?,=E4=BB=A5=E9=98=B2=E6=AD=A2=E6=96=B0=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E9=82=AE=E4=BB=B6=E6=BC=8F=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 88 +++++++++++-------- 1 file changed, 51 insertions(+), 37 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 6b77fd14..95d898fa 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -981,6 +981,7 @@ class Index extends CI_Controller { public function trippest_note($orderid_info, $paypal_msg) { + $send_type = ''; $tp_orderid = ''; $real_orderid = $orderid_info->orderid; if (substr($orderid_info->orderid, 0, 2) == '01') { @@ -990,49 +991,62 @@ class Index extends CI_Controller { // 获取HT订单号 $ht_tp_order = $this->Paypal_model->get_trippest_order($tp_orderid, $real_orderid); if (empty($ht_tp_order)) { - return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail'); + /** + * 此处不直接退出是为了:在(邮件订单不能自动录入/未收到新订单邮件)时也能通知外联已收款,防止漏单 + * 本方法内-以下的非空判断同理: !empty($ht_tp_order) + * * 未找到订单先邮件通知: pn_send='', 继续排队等待录入. 直到匹配订单变更为send + */ + // return $this->Note_model->update_send($paypal_msg->pn_txn_id, 'sendfail'); + } else { + $tp_orderid = $ht_tp_order->COLI_PriceMemo; + $real_orderid = $ht_tp_order->COLI_ID; + //更新正确的订单信息到记录中,以这个为主 + $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_TP'); } - $tp_orderid = $ht_tp_order->COLI_PriceMemo; - $real_orderid = $ht_tp_order->COLI_ID; - //更新正确的订单信息到记录中,以这个为主 - $this->Note_model->set_invoice($paypal_msg->pn_txn_id, $ht_tp_order->COLI_ID . '_TP'); $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) { - $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); - $this->Paypal_model->insert_biz_order_log($ht_tp_order->COLI_SN, 'BS13'); - $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15010'); - - $opi_firstname = "David"; - $opi_email = "david@trippest.com"; - $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; - $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; - $toName = !empty($opi_firstname) ? $opi_firstname : ''; - $toEmail = !empty($opi_email) ? $opi_email : ''; - $subject = $real_orderid . $tp_orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo; - $M_RelatedInfo = $paypal_msg->pn_sn; - $M_AddTime = $paypal_msg->pn_payment_date; - $M_State = 0; - $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + if ( ! empty($ht_tp_order)) { + $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); + $this->Paypal_model->insert_biz_order_log($ht_tp_order->COLI_SN, 'BS13'); + $this->Paypal_model->update_paymanner($ht_tp_order->COLI_SN, '15010'); + } + if (trim($paypal_msg->pn_send)!='' && trim($paypal_msg->pn_send)!='send') { + $opi_firstname = "David"; + $opi_email = "david@trippest.com"; + $fromName = !empty($paypal_msg->pn_payer) ? $paypal_msg->pn_payer : ''; + $fromEmail = !empty($paypal_msg->pn_payer_email) ? $paypal_msg->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $real_orderid . $tp_orderid . '_' . $orderid_info->ordertype . ' / ' . $paypal_msg->pn_mc_gross . $paypal_msg->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $paypal_msg, true); //$paypal_msg->pn_memo; + $M_RelatedInfo = $paypal_msg->pn_sn; + $M_AddTime = $paypal_msg->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + empty($ht_tp_order) ? $send_type = "" : false ; // 未录订单先通知收款, 置为空继续排队 + } + } + if ( ! empty($ht_tp_order)) { + $this->Paypal_model->add_account_info( + $ht_tp_order->COLI_SN, + $ht_tp_order->COLI_ID, + $paypal_msg->pn_mc_gross, + $paypal_msg->pn_payment_date, + mb_strtoupper($paypal_msg->pn_mc_currency), + $ssje, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, + $paypal_msg->pn_payment_date, + '', + $paypal_msg->pn_payer_email, + $paypal_msg->pn_txn_id, + $ht_memo + ); + $send_type = "send"; } - $this->Paypal_model->add_account_info( - $ht_tp_order->COLI_SN, - $ht_tp_order->COLI_ID, - $paypal_msg->pn_mc_gross, - $paypal_msg->pn_payment_date, - mb_strtoupper($paypal_msg->pn_mc_currency), - $ssje, - $paypal_msg->pn_payment_date, - $paypal_msg->pn_payment_date, - $paypal_msg->pn_payment_date, - '', - $paypal_msg->pn_payer_email, - $paypal_msg->pn_txn_id, - $ht_memo - ); - $this->Note_model->update_send($paypal_msg->pn_txn_id, 'send'); + $this->Note_model->update_send($paypal_msg->pn_txn_id, $send_type); } //所有记录列表 From bca4b6640a67c7ac933478b4805fa5b007d64bb8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 25 Apr 2019 09:34:12 +0800 Subject: [PATCH 292/382] =?UTF-8?q?Alipay=20=E6=9F=A5=E8=AF=A2=E9=80=80?= =?UTF-8?q?=E6=AC=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 24 +++++++++++++++++-- .../models/AlipayTradeQueryContentBuilder.php | 15 ++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 709e64bf..1a64536b 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -531,6 +531,26 @@ class AlipayTradeService extends CI_Controller return $response; } + /*! + * 查询退款 + * @date 2019-04-24 + * @param [type] $dealId 必须, 退款交易号.out_biz_no + * @param [type] $trade_no 必须, 原收款交易号 + */ + public function query_refund($dealId=NULL,$trade_no=NULL) + { + $this->AlipayTradeQueryContentBuilder->setTradeNo($trade_no); + $this->AlipayTradeQueryContentBuilder->setOutRequestNo($dealId); + + $biz_content=$this->AlipayTradeQueryContentBuilder->getBizContent(); + $request = new AlipayTradeFastpayRefundQueryRequest(); + $request->setBizContent ( $biz_content ); + + $response = $this->aopclientRequestExecute ($request); + // $response = $response->alipay_trade_fastpay_refund_query_response; + return $this->output->set_content_type('application/json')->set_output(json_encode($response)); + } + /*! * 对账单 * 流程: @@ -546,8 +566,8 @@ class AlipayTradeService extends CI_Controller { $request = new AlipayDataDataserviceBillDownloadurlQueryRequest(); $request->setBizContent("{" . - "\"bill_type\":\"trade\"," . - "\"bill_date\":\"2017-09\"" . + "\"bill_type\":\"signcustomer\"," . + "\"bill_date\":\"2019-04-03\"" . "}"); $response = $this->aopclientRequestExecute ($request); // var_dump($response); diff --git a/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php b/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php index ed892a77..16dd1734 100644 --- a/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php +++ b/webht/third_party/pay/models/AlipayTradeQueryContentBuilder.php @@ -50,6 +50,21 @@ class AlipayTradeQueryContentBuilder extends CI_Model $this->outTradeNo = $outTradeNo; $this->bizContentarr['out_trade_no'] = $outTradeNo; } + + /** + * 查询退款 + */ + private $out_request_no; + public function getOutRequestNo() + { + return $this->out_request_no; + } + public function setOutRequestNo($outRequestNo) + { + $this->out_request_no = $outRequestNo; + $this->bizContentarr['out_request_no'] = $outRequestNo; + } + } ?> From 5e1274f69f9954df41286ceaa7e9ba341162d92c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 25 Apr 2019 09:56:54 +0800 Subject: [PATCH 293/382] =?UTF-8?q?Alipay=E6=94=B6=E6=AC=BE=E7=A0=81?= =?UTF-8?q?=E8=AE=A2=E5=8D=95=E4=B8=8D=E6=94=B6=E6=89=8B=E7=BB=AD=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 1a64536b..f9db3a3c 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -402,7 +402,10 @@ class AlipayTradeService extends CI_Controller //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 if (!empty($orderid_info)) { $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->ALI_currencyCode))); - $ssje = $this->Alipay_model->get_ssje($item->ALI_orderAmount, $currencyCode); + $ssje = $item->ALI_orderAmount; + if (intval($item->ALI_stateCode)!==1) { + $ssje = $this->Alipay_model->get_ssje($item->ALI_orderAmount, $currencyCode); + } $USD_amount = $this->Alipay_model->get_USD($item->ALI_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { @@ -653,7 +656,7 @@ var_dump($response->$responseNode); ,"CNY" ,strval($query_pay->total_amount) ,NULL - ,NULL + ,1 // 此处1表示通过收款码进来的, 不收手续费, 后续录入时分别处理 ,strval($query_pay->send_pay_date) ,strval($query_pay->send_pay_date) ,json_encode($query_pay) From 83460c7eea52d1e008e9c3a212535c896778efc9 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 25 Apr 2019 13:35:44 +0800 Subject: [PATCH 294/382] =?UTF-8?q?=E6=90=AC=E8=BF=81123=E4=B8=8A=E9=9D=A2?= =?UTF-8?q?=E7=9A=84=E4=BB=A3=E7=A0=81=E5=88=B0=E4=BF=A1=E6=81=AF=E5=B9=B3?= =?UTF-8?q?=E5=8F=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/config/config.php | 107 +++ .../trainsystem/config/constants.php | 4 + .../trainsystem/controllers/addorders.php | 676 ++++++++++++++++++ .../trainsystem/controllers/api.php | 342 +++++++++ .../trainsystem/controllers/callback.php | 320 +++++++++ .../trainsystem/controllers/check.php | 528 ++++++++++++++ .../trainsystem/controllers/orders.php | 18 + .../trainsystem/controllers/pages.php | 208 ++++++ .../trainsystem/controllers/returnorders.php | 153 ++++ .../trainsystem/helpers/train_helper.php | 89 +++ .../third_party/trainsystem/libraries/Des.php | 59 ++ .../trainsystem/models/BIZ_train_model.php | 492 +++++++++++++ .../trainsystem/models/sendmail_model.php | 157 ++++ .../trainsystem/models/train_system_model.php | 267 +++++++ .../trainsystem/views/addorders.php | 0 .../trainsystem/views/common/footer.php | 43 ++ .../trainsystem/views/common/header.php | 131 ++++ .../third_party/trainsystem/views/email.php | 33 + .../trainsystem/views/email_before.php | 48 ++ .../trainsystem/views/email_fault.php | 26 + .../third_party/trainsystem/views/export.php | 110 +++ .../third_party/trainsystem/views/footer.php | 43 ++ .../third_party/trainsystem/views/header.php | 156 ++++ .../trainsystem/views/homepage.php | 511 +++++++++++++ .../third_party/trainsystem/views/order.php | 64 ++ .../trainsystem/views/order_list.php | 101 +++ .../third_party/trainsystem/views/refund.php | 48 ++ .../views/train_transaction_excel.php | 178 +++++ 28 files changed, 4912 insertions(+) create mode 100644 application/third_party/trainsystem/config/config.php create mode 100644 application/third_party/trainsystem/config/constants.php create mode 100644 application/third_party/trainsystem/controllers/addorders.php create mode 100644 application/third_party/trainsystem/controllers/api.php create mode 100644 application/third_party/trainsystem/controllers/callback.php create mode 100644 application/third_party/trainsystem/controllers/check.php create mode 100644 application/third_party/trainsystem/controllers/orders.php create mode 100644 application/third_party/trainsystem/controllers/pages.php create mode 100644 application/third_party/trainsystem/controllers/returnorders.php create mode 100644 application/third_party/trainsystem/helpers/train_helper.php create mode 100644 application/third_party/trainsystem/libraries/Des.php create mode 100644 application/third_party/trainsystem/models/BIZ_train_model.php create mode 100644 application/third_party/trainsystem/models/sendmail_model.php create mode 100644 application/third_party/trainsystem/models/train_system_model.php create mode 100644 application/third_party/trainsystem/views/addorders.php create mode 100644 application/third_party/trainsystem/views/common/footer.php create mode 100644 application/third_party/trainsystem/views/common/header.php create mode 100644 application/third_party/trainsystem/views/email.php create mode 100644 application/third_party/trainsystem/views/email_before.php create mode 100644 application/third_party/trainsystem/views/email_fault.php create mode 100644 application/third_party/trainsystem/views/export.php create mode 100644 application/third_party/trainsystem/views/footer.php create mode 100644 application/third_party/trainsystem/views/header.php create mode 100644 application/third_party/trainsystem/views/homepage.php create mode 100644 application/third_party/trainsystem/views/order.php create mode 100644 application/third_party/trainsystem/views/order_list.php create mode 100644 application/third_party/trainsystem/views/refund.php create mode 100644 application/third_party/trainsystem/views/train_transaction_excel.php diff --git a/application/third_party/trainsystem/config/config.php b/application/third_party/trainsystem/config/config.php new file mode 100644 index 00000000..7e4ddb07 --- /dev/null +++ b/application/third_party/trainsystem/config/config.php @@ -0,0 +1,107 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +//途牛apiurl (测试) +//define("TUNIU_URL","218.94.82.118:13532"); +//define("TUNIU_KEY","Te56CBQmorzJGeYIIK"); + +//途牛apiurl (正式) +define("TUNIU_URL","https://open.tuniu.cn"); +define("TUNIU_KEY","AILvoDj8El7KCSMe25"); + +define("ORDERUSER","guilintravel"); +define("ORDERKEY","07f811fe29f04008a8fcc86e81c012b9"); + +//聚合火车订票API key +define("JUHE_TRAIN_API_KEY","79f03107b921ef31310bd40a1415c1cb"); + +//聚合火车订票---查询api +define("JUHE_TRAIN_CX_API","http://op.juhe.cn/trainTickets/ticketsAvailable"); + +//聚合火车订票---订票api +define("JUHE_TRAIN_DP_API","http://op.juhe.cn/trainTickets/submit"); + +//聚合火车订票---状态查询api +define("JUHE_TRAIN_STATUS_API","http://op.juhe.cn/trainTickets/orderStatus"); + +//聚合火车订票---取消订单api +define("JUHE_TRAIN_CANCEL_API","http://op.juhe.cn/trainTickets/cancel"); + +//聚合火车订票---请求出票,支付api +define("JUHE_TRAIN_PAY_API","http://op.juhe.cn/trainTickets/pay"); + +//聚合火车订票---线上退票api +define("JUHE_TRAIN_REFUND_API","http://op.juhe.cn/trainTickets/refund"); + +//聚合火车订票---导出记录api +define("JUHE_TRAIN_EXPORT_API","http://op.juhe.cn/trainTickets/exportAccountChange"); +//http://op.juhe.cn/trainTickets/exportAccountChange?key=79f03107b921ef31310bd40a1415c1cb&since=2016-10-01 00:00&before=2016-10-30 00:00 + + + +//订单状态说明 +$config["train_order_status_msg"]=array( + "0"=>"待处理", + "1"=>"失效订单", + "2"=>"待支付", + "3"=>"已支付,待出票", + "4"=>"出票成功", + "5"=>"出票失败", + "6"=>"线上退票处理中", + "7"=>"有乘客退票(改签)成功", + "8"=>"乘客退票失败", + "e"=>"数据错误,提交失败" + ); + +//座次配对 +$config["train_zw"]=array( + "O"=>"二等座", + "9"=>"商务座", + "P"=>"特等座", + "6"=>"高级软卧", + "M"=>"一等座", + "4"=>"软卧", + "2"=>"软座", + "3"=>"硬卧", + "1"=>"硬座", + "F"=>"动卧" + ); +//数据库座次配对,包厢硬卧(5),无座(WZ),聚合没有 +$config["db_train_zw"]=array( + "9"=>"9", + "P"=>"P", + "M"=>"M", + "7"=>"M", + "O"=>"O", + "8"=>"O", + "6"=>"6", + "A"=>"6", + "S"=>"4", + "4"=>"4", + "F"=>"F", + "3"=>"3", + "2"=>"2", + "1"=>"1" + ); +//票种配对 +$config["train_piaotype"]=array( + "1"=>"成人票", + "2"=>"儿童票", + "3"=>"学生票", + "4"=>"残军票" + ); + +//证件类型配对 +$config["train_passportty"]=array( + "B"=>"护照", + "1"=>"二代身份证", + "2"=>"一代身份证", + "C"=>"港澳通行证", + "G"=>"台湾通行证" + ); + +//黑名单用户 +$config['black_list'] = array('209582910','539152642','506157109','E66735489','E66735492','E80377215','G23001338','E95287649','345276546','PA4286015','G09382769','G26113116','G25996274','572309763','506620366','505897939','E71156367','E21961674','v716898','561669436','EL657289','533300106','482225223','514815909','592108236','370682199509218814','130924199003161572','410728199011287038','372324199503253215','ED6234008'); + +//设置session 2592000 +$config['sess_cookie_name'] = 'trainsystem'; +$config['sess_expiration'] = 2592000; \ No newline at end of file diff --git a/application/third_party/trainsystem/config/constants.php b/application/third_party/trainsystem/config/constants.php new file mode 100644 index 00000000..9d315fd5 --- /dev/null +++ b/application/third_party/trainsystem/config/constants.php @@ -0,0 +1,4 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + + +define("JUHE_API_KEY","123"); \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/addorders.php b/application/third_party/trainsystem/controllers/addorders.php new file mode 100644 index 00000000..f5ae9b28 --- /dev/null +++ b/application/third_party/trainsystem/controllers/addorders.php @@ -0,0 +1,676 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class addorders extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->model("BIZ_train_model"); + $this->load->model("train_system_model"); + $this->load->helper('train'); + $this->db_train_zw = $this->config->item('db_train_zw'); + $this->train_zw = $this->config->item('train_zw'); + $this->black_list = $this->config->item('black_list'); + $this->isauto = 0; + } + + public function index(){ + echo 'api manager'; + } + + //自动出票 + public function auto_pay_ticket(){ + //log_message('error','auto ticket'); + date_default_timezone_set('Asia/Shanghai'); + //判断账户余额,如果小于1000自动退出。 + $post_data = array("key"=>JUHE_TRAIN_API_KEY); + $back_data = GetPost_http("http://op.juhe.cn/trainTickets/balance.php",$post_data); + $price = json_decode($back_data)->result; + print_r('账户余额:'.$price); + if($price < 1000){ + exit('账户余额不足'); + } + //筛选出能自动出票的订单 + $auto_pool = $this->BIZ_train_model->auto_check_ticket(); + + //创建一个不允许自动出票的国际火车票数组 + $nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795'); + + //创建黑名单 + $black_list = $this->config->item('black_list'); + $string = ''; + foreach($auto_pool as $item){ + $this->isauto = 1; + $bpe_sn = ''; + $back_message = ''; + $cold_sn = $item->COLD_SN; + $coli_id = $item->coli_id; + $back_data = 1; + + $people_arr = $this->BIZ_train_model->biz_people($cold_sn); + $train_info = $this->BIZ_train_model->get_biz_foi($cold_sn); + + if($item->COLD_SPFS > 1){ + //寄送票 + $back_data = 0; + $back_message .= '-邮寄不自动出票'; + } + + //乘客人数大于5人不出票 + if(count($people_arr) > 5){ + $back_data = 0; + $back_message .= '-乘客人数大于5不自动出票'; + } + + //护照号如果在黑名单的就不自动出票 + foreach($people_arr as $people_info){ + if(in_array($people_info->BPE_Passport,$black_list)){ + $back_data = 0; + $back_message .= '-此用户为黑名单用户,不自动出票'; + } + + if(strlen($people_info->BPE_Passport) >= 18){ + $back_data = 0; + $back_message .= '-护照位数大于18不自动出票'; + } + + $bpe_sn .= $people_info->BPE_SN.','; + } + $bpe_sn = substr($bpe_sn,0,strlen($bpe_sn)-1); + + //单张票价不能大于1000人民币 + if($train_info[0]->adultcost > 1000){ + $back_data = 0; + $back_message .= '-单价大于1000不自动出票'; + } + + //如果为国际火车票就不出票 + if(in_array($train_info[0]->FlightsNo, $nation_train)){ + $back_data = 0; + $back_message .= '-国际火车票不自动出票'; + } + + //无座的订单不做出票 + if($train_info[0]->Aircraft == 'WZ'){ + $back_data = 0; + $back_message .= '-无座不自动出票'; + } + + //香港火车不自动出票 + if($train_info[0]->DepartAirport == 'XJA'){ + $back_data = 0; + $back_message .= '-香港火车不自动出票'; + } + + $DepartureDate = strtotime($train_info[0]->DepartureDate); + $time = time(); + $depart_diff = ($DepartureDate - $time) / 86400; + + if($train_info[0]->ArrivalAirport == 'XJA' && $train_info[0]->adultcost > 500 && $depart_diff > 5){ + $back_data = 0; + $back_message .= '-内地香港火车金额大于500超过五天不自动出票'; + } + //print_r($train_info); + + //如果刚好是第三十天的订单 + echo $item->COLI_State; + if(($item->COLI_State == '8' || $item->COLI_State == '63')){ + $this->isauto = 3; + $time_obj = $this->BIZ_train_model->get_saletime($train_info['0']->DepartAirport_cn); + //print_r($time_obj); + if(!empty($time_obj)){ + $saletime = strtotime($time_obj->TST_saletime); + //echo $saletime; + $sale_diff = (time() - $saletime) / 3600; + if($sale_diff > 1){ + $back_data = 0; + $back_message .= '-超过抢票时间'; + }else if($sale_diff <0){ + $back_data = 0; + $back_message .= '-未到抢票时间'; + } + } + } + + if($back_data == 0){ + $string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')'.$back_message.'</td></tr>'; + }else{ + //单个订单提交 + echo $cold_sn.'<br>'; + $this->booktickets($cold_sn,$bpe_sn,'','juhe'); + //$string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>'; + } + } + print_r('<table border="1">'.$string.'</table>'); + } + + //创建一个方法用于接收所有的出票请求 + public function booktickets($cold_sn=null,$bpe_sn=null,$selectseat=null,$type=null){ + if(empty($cold_sn) && empty($bpe_sn)){ + //接收子表订单号 + $cold_sn = $this->input->get_post('order'); + //接收客人表sn + $bpe_sn = $this->input->get_post("people"); + //接收选座字符串 + $selectseat = $this->input->get_post("selectseat"); + //接收出票接口 + $type = $this->input->get_post("type"); + } + //测试数据 + /*$cold_sn = '488121613'; + $bpe_sn = '473183645,473183646,473183647'; + $selectseat = ''; + $type = 'juhe';*/ + + if(!is_numeric($cold_sn)){ + $reback["mes"]="订单号是数字"; + echo json_encode($reback); + return false; + } + + if(empty($bpe_sn)){ + $reback["mes"]="请选择乘客"; + echo json_encode($reback); + return false; + } + + $data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn); + $data['people_list']=$this->BIZ_train_model->in_bpesn_people_info($bpe_sn); + + if($selectseat == ''){ + $selectseat = ''; + $train_select = $data['train']->FOI_SelectedSeat; + $obj = explode(',',$train_select); + foreach($obj as $value){ + $selectseat .= $value; + } + } + + if (empty($data['train'])) { + //显示错误,找不到车次 + $reback["mes"]="找不到车次"; + echo json_encode($reback); + return false; + } + + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $reback["mes"]="找不到乘客信息"; + echo json_encode($reback); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $reback["mes"]="乘客不能超过五个"; + echo json_encode($reback); + return false; + } + + switch ($type){ + case 'juhe': + $this->juheModel($data,$selectseat,$cold_sn); + break; + case 'tuniu': + $this->tuniuModel($data,$selectseat,$cold_sn); + break; + case 'ctrip': + $this->ctripModel($data,$selectseat,$cold_sn); + break; + } + } + + function juheModel($data=null,$selectseat=null,$cold_sn=null){ + $zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称 + + //进行提交字符串的拼接 + $passengers = ""; + foreach ($data['people_list'] as $key => $item) { + //乘客姓名 + $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName; + //将特殊字符转换为正常字符以便于出票 + $passengersename = chk_sp_name($passengersename); + //乘客类型 + switch ($item->BPE_GuestType) { + case 1: + $piaotype = 1; + $piaotypename = "成人票"; + break; + case 2: + $piaotype = 2; + $piaotypename = "儿童票"; + break; + default://外国人应该就两种票吧 + $piaotype = 1; + $piaotypename = "成人票"; + break; + } + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + switch ($item->BPE_SEX){ + case '100003': + $sex = 'F'; + break; + case '100001': + $sex = 'M'; + break; + } + + $passportseno = str_replace(' ','',$item->BPE_Passport); + + //添加一个判断护照号是否在黑名单 + if(in_array($passportseno,$this->black_list)){ + $reback["mes"] = "乘客为黑名单用户"; + echo json_encode($reback); + return false; + } + + if($passporttypeseid == 'G'){ + $passengers .= ',{"passengerid":' . (++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","gatValidDateEnd":"'.$item->BPE_PassExpdate.'","gatBornDate":"'.$item->BPE_BirthDate.'","sexCode":"'.$sex.'"}'; + }else{ + $passengers .= ',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; + } + + } + + $passengers .= "]"; + $passengers = substr($passengers, 1); + $passengers = "[" . $passengers; + if(empty($selectseat)){ + $post_data=array( + "key"=>JUHE_TRAIN_API_KEY, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + }else{ + $post_data=array( + "key"=>JUHE_TRAIN_API_KEY, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + } + + //发起请求 + $add_data = new stdClass(); + $back_json = GetPost_http('http://op.juhe.cn/trainTickets/submit',$post_data); + $back_data = json_decode($back_json); + + if(!$back_data->error_code){ + $add_data->ordernumber = $back_data->result->orderid; + $reback["status"] = 1; + $reback["order"] = $back_data->result->orderid; + $reback["mes"] = "订单提交成功,等待回调"; + }else{ + $add_data->ordernumber=null; + $reback["mes"] = $back_json; + $add_data->status = "e"; + } + + //本地订单入库 + $add_data->cold_sn = $cold_sn; + $add_data->returncode = $back_data->error_code; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = $data['train']->FlightsNo; + $add_data->fromstationame = $data['train']->DepartAirport_cn; + $add_data->fromstationcode = $data['train']->DepartAirport; + $add_data->tostationame = $data['train']->ArrivalAirport_cn; + $add_data->tostationcode = $data['train']->ArrivalAirport; + $add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate)); + $add_data->startime = date('H:i',strtotime($data['train']->DepartureTime)); + $add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime)); + $add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; + $add_data->channel = 'juhe'; + $add_data->isauto = $this->isauto; + + $this->train_system_model->add_orders($add_data); + echo json_encode($reback); + return false; + + } + + function tuniuModel($data,$selectseat,$cold_sn){ + $this->load->library('Des'); + $zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称 + + $passengers=""; + //$cold_sn = $cold_sn.'_'.time(); + + //拼接车次信息 + $tuniu_data = '{'; + $tuniu_data .= '"retailOrderId":"'.$cold_sn.'",'; + $tuniu_data .= '"cheCi": "'.$data['train']->FlightsNo.'", '; + $tuniu_data .= '"fromStationCode": "'.$data['train']->DepartAirport.'", '; + $tuniu_data .= '"fromStationName": "'.$data['train']->DepartAirport_cn.'", '; + $tuniu_data .= '"toStationCode": "'.$data['train']->ArrivalAirport.'", '; + $tuniu_data .= '"toStationName": "'.$data['train']->ArrivalAirport_cn.'", '; + $tuniu_data .= '"trainDate": "'.substr($data["train"]->DepartureDate, 0, 10).'", '; + $tuniu_data .= '"callBackUrl": "http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",'; + $tuniu_data .= '"hasSeat": true,'; + $tuniu_data .= '"contact": "陈宇超",'; + $tuniu_data .= '"phone": "18877381547",'; + $tuniu_data .= '"isChooseSeats": true,'; + $tuniu_data .= '"chooseSeats":"'.$selectseat.'",'; + + //循环乘客 + $passengers = ''; + foreach ($data['people_list'] as $key => $item) { + $passengers .= '{'; + $passengers .= '"passengerId":'.$key.','; + $passengers .= '"ticketNo":"null",'; + //乘客姓名 + $passengersename = str_replace(' ','',$item->BPE_FirstName) . str_replace(' ','',$item->BPE_MiddleName) . str_replace(' ','',$item->BPE_LastName); + //将特殊字符转换为正常字符以便于出票 + $passengersename = chk_sp_name($passengersename); + $passengers .= '"passengerName":"'.$passengersename.'",'; + $passportseno = str_replace(' ','',$item->BPE_Passport); + + $passengers .= '"passportNo":"'.$passportseno.'",'; + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + //乘客类型 + switch ($item->BPE_GuestType) { + case 1: + $piaotype = 1; + $piaotypename = "成人票"; + break; + case 2: + $piaotype = 2; + $piaotypename = "儿童票"; + break; + default://外国人应该就两种票吧 + $piaotype = 1; + $piaotypename = "成人票"; + break; + } + + $passengers .= '"passportTypeId":"'.$passporttypeseid.'",'; + $passengers .= '"passportTypeName":"'.$passporttypeseidname.'",'; + + //票类型 + $passengers .= '"piaoType":"'.$item->BPE_GuestType.'",'; + $passengers .= '"piaoTypeName":"'.$piaotypename.'",'; + + //座位类型piaoTypeName + $passengers .= '"zwCode":"'.$zwcode.'",'; + $passengers .= '"zwName":"'.$zwname.'",'; + + $passengers .= '"cxin":"null",'; + $passengers .= '"price":"'.$data['train']->adultcost.'",'; + $passengers .= '"reason": 0'; + $passengers .= '},'; + } + + $passengers = substr($passengers,0,strlen($passengers)-1); + $passengers = '['.$passengers.']'; + $tuniu_data .= '"passengers": '.$passengers.'}'; + + //print_r($tuniu_data); + + $crypt = new DES(); + $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.create_sign().'", + "timestamp": "'.date('Y-m-d H:i:s',time()).'", + "data": "'.$mstr.'" + }'; + + $url = TUNIU_URL.'/train/book'; + $book_back_json = GetPost_http($url,$post_data,'POST','json'); + $book_back_data = json_decode($book_back_json); + + $orderId = $book_back_data->data->orderId; + $retailOrderId = $book_back_data->data->retailOrderId; + + if($book_back_data->success == 1){ + $confirm_url = TUNIU_URL.'/train/confirm'; + $sign = create_sign(); + $time = date('Y-m-d H:i:s',time()); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": { + "retailOrderId":"'.$retailOrderId.'", + "orderId":"'.$orderId.'", + "callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/confirm" + } + }'; + //请求出票 + $confirm_back_json = GetPost_http($confirm_url,$post_data,'POST','json'); + $confirm_back_data = json_decode($confirm_back_json); + $reback["status"] = 1; + $reback["order"] = $orderId; + $reback["mes"] = "订单提交成功,等待回调"; + }else{ + $reback["mes"] = $confirm_back_json; + $add_data->status = "e"; + } + + //本地订单入库 + $add_data = new stdClass(); + $add_data->cold_sn = $retailOrderId; + $add_data->ordernumber = $orderId; + $add_data->returncode = $confirm_back_data->returnCode; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = $data['train']->FlightsNo; + $add_data->fromstationame = $data['train']->DepartAirport_cn; + $add_data->fromstationcode = $data['train']->DepartAirport; + $add_data->tostationame = $data['train']->ArrivalAirport_cn; + $add_data->tostationcode = $data['train']->ArrivalAirport; + $add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate)); + $add_data->startime = date('H:i',strtotime($data['train']->DepartureTime)); + $add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime)); + $add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; + $add_data->channel = 'tuniu'; + $add_data->isauto = 0; + + $this->train_system_model->add_orders($add_data); + echo json_encode($reback); + return false; + } + + function ctripModel($data,$selectseat,$cold_sn){ + $zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称 + $OrderNumber = ORDERUSER.time(); + //拼接发送的报文 + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.PartnerAddOrder'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.PartnerAddOrder'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->PartnerName = ORDERUSER; + $PostData['TrainOrderService']->Operation = ''; + $PostData['TrainOrderService']->OrderType = '电子'; + $PostData['TrainOrderService']->OrderTicketType = '0'; + $PostData['TrainOrderService']->OrderNumber = $OrderNumber; + $PostData['TrainOrderService']->ChannelName = ORDERUSER; + + $PostData['TrainOrderService']->Order->OrderTime = $time; + $PostData['TrainOrderService']->Order->OrderMedia = 'pc'; + $PostData['TrainOrderService']->Order->Insurance = 'N'; + $PostData['TrainOrderService']->Order->Invoice = 'N'; + $PostData['TrainOrderService']->Order->PrivateCustomization = '0'; + + $PostData['TrainOrderService']->Order->TicketItem->FromStationName = $data['train']->DepartAirport_cn; + $PostData['TrainOrderService']->Order->TicketItem->ToStationName = $data['train']->ArrivalAirport_cn; + $PostData['TrainOrderService']->Order->TicketItem->TicketTime = date('Y-m-d H:i:s',strtotime($data['train']->DepartureTime)); + $PostData['TrainOrderService']->Order->TicketItem->TrainNumber = $data['train']->FlightsNo; + $PostData['TrainOrderService']->Order->TicketItem->ArrivalDateTime = date('Y-m-d H:i:s',strtotime($data['train']->ArrivalTime)); + $PostData['TrainOrderService']->Order->TicketItem->TicketPrice = $data['train']->adultcost; + $PostData['TrainOrderService']->Order->TicketItem->TicketCount = count($data['people_list']); + + $AdultNum = 0; + $ChildNum = 0; + $Passport = ''; + foreach ($data['people_list'] as $PassagerInfo){ + //乘客类型 + switch ($PassagerInfo->BPE_GuestType) { + case 1: + $PiaoType = 1; + $PiaoTypeName = "成人票"; + $AdultNum++; + break; + case 2: + $PiaoType = 2; + $PiaoTypeName = "儿童票"; + $ChildNum++; + break; + default://外国人应该就两种票吧 + $PiaoType = 1; + $PiaoTypeName = "成人票"; + break; + } + + //证件类型 + switch ($PassagerInfo->BPE_PassportType){ + case 'Chinese ID': + $PassportTypeseId = "1"; + $PassportTypeseidName = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $PassportTypeseidName = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $PassportTypeseId = "G"; + $PassportTypeseidName = "台湾通行证"; + break; + default : + $PassportTypeseId = "B"; + $PassportTypeseidName = "护照"; + break; + } + //$Passport .= chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0|'; + + if($PiaoType == 1){ + $RelatioNme = chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName); + $Passport .= chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0|'; + }elseif($PiaoType == 2){ + $Passport .= $RelatioNme.','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0,'.chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).'|'; + } + + } + + $PostData['TrainOrderService']->Order->TicketItem->AuditTicketCount = $AdultNum; + $PostData['TrainOrderService']->Order->TicketItem->ChildTicketCount = $ChildNum; + $PostData['TrainOrderService']->Order->TicketItem->SeatName = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; + $PostData['TrainOrderService']->Order->TicketItem->SelectedSeat = $selectseat; + $PostData['TrainOrderService']->Order->TicketItem->AcceptSeat = ''; + $PostData['TrainOrderService']->Order->TicketItem->passport = substr($Passport,0,strlen($Passport)-1); + $PostData['TrainOrderService']->Order->TicketItem->OrderPrice = $data['train']->adultcost * $AdultNum + $data['train']->childcost * $ChildNum; + + $PostData['TrainOrderService']->Order->FrontSeatFlag = '0'; + + $PostData['TrainOrderService']->Order->User->UserID = ''; + $PostData['TrainOrderService']->Order->User->UserName = 'guilintravel'; + $PostData['TrainOrderService']->Order->User->userLoginName = 'guilintravel'; + $PostData['TrainOrderService']->Order->User->UserMobile = '18877381547'; + //print_r($PostData);die(); + //本地添加记录 + $add_data = new stdClass(); + $add_data->cold_sn = $cold_sn; + $add_data->ordernumber = $OrderNumber; + $add_data->returncode = ''; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = $data['train']->FlightsNo; + $add_data->fromstationame = $data['train']->DepartAirport_cn; + $add_data->fromstationcode = $data['train']->DepartAirport; + $add_data->tostationame = $data['train']->ArrivalAirport_cn; + $add_data->tostationcode = $data['train']->ArrivalAirport; + $add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate)); + $add_data->startime = date('H:i',strtotime($data['train']->DepartureTime)); + $add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime)); + $add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; + $add_data->channel = 'ctrip'; + $add_data->isauto = 0; + + + //存储到数据库 + $this->train_system_model->add_orders($add_data); + + $Url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerAddOrder'; + $ResponseJson = GetPost_http($Url,json_encode($PostData),'POST'); + $ResponseData = json_decode($ResponseJson); + + //echo '预定'; + //print_r($ResponseData); + + //预定请求成功后执行支付 + if($ResponseData->Status == 'SUCCESS'){ + //计算订单总价,进行支付 + $total_price = $AdultNum * $data['train']->adultcost + $ChildNum * $data['train']->childcost; + $this->payorders($OrderNumber,$total_price); + $reback["status"] = 1; + $reback["order"] = $OrderNumber; + $reback["mes"] = "订单提交成功,等待回调"; + }else{ + $reback["mes"] = $ResponseJson; + $add_data->status = "e"; + } + echo json_encode($reback); + } +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/api.php b/application/third_party/trainsystem/controllers/api.php new file mode 100644 index 00000000..7091dbfd --- /dev/null +++ b/application/third_party/trainsystem/controllers/api.php @@ -0,0 +1,342 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class api extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->helper('train'); + $this->load->model("BIZ_train_model"); + $this->load->model("train_system_model"); + $this->load->model("Sendmail_model"); + } + + public function index(){ + echo 'api manager'; + } + + //获取订单出票状态 + public function isbooktickets(){ + $cold_sn = $this->input->get('cold_sn'); + + $tickets_info = $this->train_system_model->get_tickets_info($cold_sn); + //print_r($tickets_info); + if(!empty($tickets_info)){ + $return_data = array(); + $i = 0; + foreach($tickets_info as $items){ + $return_data[$i]->cold_sn = (int) $items->ts_cold_sn; + $return_data[$i]->ordernumber = $items->ts_ordernumber; + $return_data[$i]->status = $items->tst_status; + $return_data[$i]->passengersename = $items->tst_realname; + $return_data[$i]->passportseno = $items->tst_numberid; + $i++; + } + print_r(json_encode($return_data)); + }else{ + return null; + } + + } + + //用于自动发送确认信 + public function send_confirmmail(){ + //log_message('error','auto sendmail'); + $mailarr = $this->BIZ_train_model->auto_sendmail(); + foreach($mailarr as $obj){ + $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($obj->ts_cold_sn); + $coli_id = $coli_id[0]->COLI_ID; + $juhe_order = $obj->ts_ordernumber; + $this->send_mail_to_guest($coli_id,$juhe_order); + } + } + + //发邮件给客人 + function send_mail_to_guest($coli_id,$jh_order){ + $info = $this->BIZ_train_model->get_user_info($jh_order); + $guest = $this->BIZ_train_model->get_guest_info($coli_id); + //print_r($guest); + $operator_info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $fromName = $operator_info[0]->Name; + $fromEmail = $operator_info[0]->OPI_Email; + $toName = $guest[0]->GUT_LastName.$guest[0]->GUT_FirstName; + $toEmail = $guest[0]->GUT_Email;// + $data['coli_id'] = $coli_id; + $data['toname'] = $toName; + $data['adult'] = $info->COLD_PersonNum; + $data['chlid'] = $info->COLD_ChildNum; + $data['baby'] = $info->COLD_BabyNum; + $data['price'] = $this->BIZ_train_model->get_paypal($coli_id); + $data['allpeople'] = $this->BIZ_train_model->biz_people($info->COLD_SN); + $data['train_info'] = $this->BIZ_train_model->get_biz_foi($info->COLD_SN); + $differtime = (strtotime($data['train_info'][0]->DepartureTime) - time()) / 3600; + $obj = $this->BIZ_train_model->get_biz_jol_info($info->COLD_SN,$jh_order); + $data['ordernumber'] = $obj->ts_elecnumber; + $status = $obj->ts_status; + $data['operator'] = $operator_info; + $data['emailarr'] = explode(';',$operator_info[0]->Email); + + $data['seatinfo'] = $obj->ts_seatsinfo; + + if($status == '4' && $differtime > 0){ + $subject = "Got payment and issued train ticket(s), Order No $coli_id"; + $body = $this->load->view('email',$data,true); + $this->send_mail_to_wl("订单:{$coli_id} 出票成功","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //发送邮件给客人 + $flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>1,"ts_m_sn"=>$flag)); + }else if($status == '1' && $differtime < 18 && $differtime > 0){ + $subject = "The train ticket(s) will be issued manually, Order No $coli_id"; + $body = $this->load->view('email_fault',$data,true); + $this->send_mail_to_wl("订单:{$coli_id} 出票失败","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //测试阶段,将失败邮件发送一份给操作外联。 + $flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$fromName,$fromEmail,$subject,$body); + //测试阶段,将失败邮件发送一份给操作外联。 + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>1,"ts_m_sn"=>$flag)); + }else{ + echo $jh_order.'不需要发邮件<br>'; + $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>2)); + $flag = false; + } + + } + + //发邮件给外联 + function send_mail_to_wl($subject,$body,$coli_id){ + $fromName = "cyc"; + $fromEmail = "cyc@hainatravel.com"; + //获取该订单的操作员的邮箱以及姓名 + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + } + + //导出账单api + public function export_excel(){ + set_time_limit(0); + //创建跟踪号 + $trackcode = $this->BIZ_train_model->getTrackingCode(); + $from_date = $this->input->post("from_date"); + $to_date = $this->input->post("to_date"); + $examine = $this->input->post("examine"); + //$operator=$this->input->post("operator"); + + $reback=array();//返回的数据 + $reback["from_date"] = $from_date; + $reback["to_date"] = $to_date; + $reback["examine"] = $examine; + $group = array(); + + if(!empty($from_date) && !empty($to_date)){ + $from_date = date("Y-m-d H:i",strtotime($from_date)); + $to_date = date("Y-m-d H:i",strtotime($to_date)); + $r = "";//聚合返回的数据 + $string_r = "";//输出 + $coli_id = ""; + $wl_name = ""; + $arr = array();//整合完成的数组,写进excel表的数据 + $url = JUHE_TRAIN_EXPORT_API;//请求的url + $url .= "?key=".JUHE_TRAIN_API_KEY; + $url .= "&since=".$from_date; + $url .= "&before=".$to_date; + $r = GetPost_http($url); + $r = explode("\n",$r); + //print_r($r); + //die(); + for($i=1;$i<count($r)-1;$i++){ + $r_info=explode(",",$r[$i]); + $juhe_order=substr($r_info[4], 1,strlen($r_info[4])-2); + $obj = $this->BIZ_train_model->jh_order_get_coli_id($juhe_order); + //print_r($obj); + if(!empty($obj)){ + $coli_id = $obj[0]->COLI_ID; + $coli_sn = $obj[0]->COLI_SN; + }else{ + echo $juhe_order; + } + + $this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode); + + /*if(empty($coli_sn) || empty($coli_sn)){ + print_r($juhe_order); + }*/ + + + /* + $flag = $this->BIZ_train_model->islink($coli_sn); + if($flag){ + $this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode); + }else{ + echo $coli_sn.'该订单还未关联财务表,不能导出账单。<br>'; + die(); + } + */ + //去掉数据两边的双引号 + $r_info[2]=substr($r_info[2], stripos($r_info[2],'"')+1,strrpos($r_info[2],'"')-1); + $r_info[1]=substr($r_info[1], stripos($r_info[1],'"')+1,strrpos($r_info[1],'"')-1); + $r_info[5]=substr($r_info[5], stripos($r_info[5],'"')+1,strrpos($r_info[5],'"')-1); + $r_info[6]="";//储存团名 + $r_info[7] = "";//储存外联名 + $r_info[8] = "";//储存coli_id + if($coli_id){ + $r_info[8] = $coli_id; + $gri_no=$this->BIZ_train_model->get_gri_no($r_info[8]);//团名 + $wl_name = $this->BIZ_train_model->get_operatorInfo($r_info[8]); + if($gri_no){ + $r_info[6] = $gri_no[0]->GRI_No; + } + if($wl_name){ + $r_info[7] = $wl_name[0]->OPI_Name; + } + } + + //$r_info[3]=mb_convert_encoding($r_info[3],"utf-8","gbk"); + + if(is_numeric(mb_strpos($r_info[3],"充值"))){ + if(is_numeric(mb_strpos($r_info[3],"扣款"))){ + $r_info[3]="票款(有充值)"; + } + if(is_numeric(mb_strpos($r_info[3],"扣手续费"))){ + $r_info[3]="手续费(有充值)"; + } + if(is_numeric(mb_strpos($r_info[3],"线上退票成功"))){ + $r_info[3]="退票费(有充值)"; + } + } + if(is_numeric(mb_strpos($r_info[3],"扣款"))){ + $r_info[3]="票款"; + } + if(is_numeric(mb_strpos($r_info[3],"扣手续费"))){ + $r_info[3]="手续费"; + } + if(is_numeric(mb_strpos($r_info[3],"线上退票成功"))){ + $r_info[3]="退票费"; + } + // $r_info[3]=mb_convert_encoding($r_info[3],"gbk","utf-8"); + $r_info['trackcode'] = $trackcode; + $arr[]=$r_info; + + /* + //根据外联的名字创建数组来存储对应外联的订单信息 + if(!empty($r_info[7])){ + if(!isset($group[$r_info[7]])){ + $group[$r_info[7]] = array(); + } + array_push($group[$r_info[7]],$r_info); + }*/ + + } + /* + //将存储好的分组重新循环出来。 + foreach($group as $item){ + foreach ($item as $value){ + array_push($arr,$value); + } + } + */ + //die(); + if(empty($examine)){ + header("Content-type:application/vnd.ms-excel;charset=utf-8"); + header("Content-Disposition:attachment;filename=juhe_train.xls"); + $string_r= $this->load->view("train_transaction_excel",array("arr"=>$arr),TRUE); + echo $string_r;die; + }else{ + krsort($arr);//数组倒序 + $reback["data"]=$arr; + } + + } + } + + //登录验证 + public function check_login(){ + $code = $this->input->get('code'); + $signature = getDingSignature(); + $urlencode_signature = urlencode($signature); + $personInfoUrl = 'https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature='.$urlencode_signature.'&timestamp='.time().'&accessKey=dingoaystremzlahfew1tb'; + $post_data = '{"tmp_auth_code":"'.$code.'"}'; + $returnJson = GetPost_http($personInfoUrl,$post_data,'json'); + $returnData = json_decode($returnJson); + + if(!empty($returnData->user_info)){ + //创建session + $this->session->set_userdata('dingname', $returnData->user_info->nick); + $this->session->set_userdata('dingunionid', $returnData->user_info->unionid); + redirect('http://www.mycht.cn/info.php/apps/trainsystem/pages/'); + }else{ + redirect('http://www.mycht.cn/info.php/apps/trainsystem/pages/login'); + } + } + + public function check_session(){ + print_r($this->session->userdata('dingunionid')); + } + + //订单同步到trainsystem + public function sync_orders(){ + die(); + //获取聚合订单 + $juhe_orders = $this->train_system_model->getallorders(); + + $add_data = new stdClass(); + foreach ($juhe_orders as $items){ + $add_data->ordernumber = $items->JOL_JuheOrder; + $add_data->cold_sn = $items->JOL_COLD_SN; + $add_data->status = $items->JOL_Status; + $add_data->returncode = ''; + $add_data->errormsg = $items->JOL_RebackMsg; + $add_data->checi = $items->JOL_TrainCode; + $add_data->fromstationame = $items->JOL_FromStation; + $add_data->fromstationcode = $items->JOL_FromStationCode; + $add_data->tostationame = $items->JOL_ToStation; + $add_data->tostationcode = $items->JOL_ToStationCode; + + $trains = json_decode($items->JOL_BackTxt); + //print_r($trains->passengers); + if(isset($trains->train_date)){ + $add_data->startdate = $trains->train_date; + }else{ + $add_data->startdate = ''; + } + + foreach ($trains->passengers as $passengers){ + //对订票乘客进行存储 + $data_passager->ordernumber = $items->JOL_JuheOrder; + $data_passager->realname = $passengers->passengersename; + $data_passager->identitytype = $passengers->passporttypeseidname; + $data_passager->numberid = $passengers->passportseno; + $data_passager->ticketype = $passengers->piaotypename; + $data_passager->ticketprice = $passengers->price; + $data_passager->seatype = $passengers->zwname; + $data_passager->seatdetail = $passengers->cxin; + $data_passager->status = $items->JOL_Status; + //print_r($data_passager); + $this->train_system_model->add_passagers($data_passager); + } + + $add_data->startime = ''; + $add_data->endtime = ''; + $add_data->runtime = ''; + + $add_data->channel = 'juhe'; + $add_data->isauto = $items->JOL_IsAuto; + $this->train_system_model->add_orders($add_data); + //print_r($add_data); + } + } + + public function update_order(){ + $juhe_orders = $this->train_system_model->getallorders(); + foreach ($juhe_orders as $tickets_info){ + $ordernumber = $tickets_info->JOL_JuheOrder; + $subtime = $tickets_info->JOL_SubTime; + $price = $tickets_info->JOL_Price; + $this->train_system_model->update_juheorder($ordernumber,$subtime,$price); + } + + } + +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/callback.php b/application/third_party/trainsystem/controllers/callback.php new file mode 100644 index 00000000..b6d36723 --- /dev/null +++ b/application/third_party/trainsystem/controllers/callback.php @@ -0,0 +1,320 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class callback extends CI_Controller{ + public function __construct(){ + parent::__construct(); + $this->load->helper('train'); + $this->load->model("train_system_model"); + $this->load->model("BIZ_train_model"); + } + + public function juhecallback(){ + $data_post = $this->input->post(); + if(empty($data_post)){ + header("HTTP/1.1 404 Not Found"); + exit('{"reason":"empty infos","status":"404"}'); + } + + //调试代码 + /*$test_post = '{"data":"{\"from_station_name\":\"\u6b66\u6c49\",\"from_station_code\":\"WHN\",\"to_station_name\":\"\u897f\u5b89\u5317\",\"to_station_code\":\"EAY\",\"train_date\":\"2019-04-13\",\"orderid\":\"JH155317715892154\",\"user_orderid\":\"488123754\",\"orderamount\":\"1363.50\",\"ordernumber\":\"E946949845\",\"checi\":\"G856\",\"msg\":\"\u51fa\u7968\u6210\u529f\",\"status\":\"4\",\"passengers\":[{\"passengerid\":1,\"passengersename\":\"VENOSLEONARDA\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"086925694\",\"price\":\"454.5\",\"zwcode\":\"O\",\"zwname\":\"\u4e8c\u7b49\u5ea7\",\"ticket_no\":\"E946949845102006A\",\"cxin\":\"02\u8f66\u53a2,06A\u5ea7\",\"reason\":0},{\"passengerid\":2,\"passengersename\":\"WAGENSTALLERSANDRA\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CF7NR17M7\",\"price\":\"454.5\",\"zwcode\":\"O\",\"zwname\":\"\u4e8c\u7b49\u5ea7\",\"ticket_no\":\"E946949845102006B\",\"cxin\":\"02\u8f66\u53a2,06B\u5ea7\",\"reason\":0},{\"passengerid\":3,\"passengersename\":\"WALDMANNSOPHIE\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CF26Y6FVK\",\"price\":\"454.5\",\"zwcode\":\"O\",\"zwname\":\"\u4e8c\u7b49\u5ea7\",\"ticket_no\":\"E946949845102006C\",\"cxin\":\"02\u8f66\u53a2,06C\u5ea7\",\"reason\":0}],\"refund_money\":null,\"sign\":\"f74013fa24115eeb9a807aa237054920\"}"}'; + + $data_post["data"] = json_decode($test_post)->data;*/ + + log_message('error','聚合回调:'.json_encode($data_post)); + $data = json_decode($data_post["data"]); + + $update_data = new StdClass(); + $update_data->OrderStatus = $data->status; + $update_data->ordernumber = $data->orderid; + $update_data->OrderTotleFee = $data->orderamount; + $update_data->seatsinfo = ''; + $update_data->TicketCheck = ''; + $update_data->bookcallback = ''; + $update_data->confirmcallback = ''; + $update_data->returncallback = ''; + $update_data->ElectronicOrderNumber = $data->ordernumber; + $update_data->reschedulecallback = ''; + $update_data->ErrorMsg = $data->msg; + + //如果返回2则发送出票请求 + if($data->status == "1"){ + $update_data->bookcallback = $data_post["data"]; + }elseif($data->status == "2"){ + $coach = array(); + $seats = array(); + $string = ''; + $passagers = $data->passengers; + foreach($passagers as $item){ + foreach(explode(',',$item->cxin) as $item_seat){ + if(strpos($item_seat,'车厢')){ + $item_seat = str_replace('车厢','',$item_seat); + array_push($coach,$item_seat); + }else{ + $find = array('座上铺','座中铺','座下铺','座'); + $replace = array(' upper',' middle',' lower',''); + $item_seat = str_replace($find,$replace,$item_seat); + array_push($seats,$item_seat); + } + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $data->orderid; + $data_passager->realname = $item->passengersename; + $data_passager->identitytype = $item->passporttypeseidname; + $data_passager->numberid = $item->passportseno; + $data_passager->ticketype = $item->piaotypename; + $data_passager->ticketprice = $item->price; + $data_passager->seatype = $item->zwname; + $data_passager->seatdetail = $item->cxin; + $data_passager->status = '4'; + $this->train_system_model->add_passagers($data_passager); + } + + //判断车厢是否唯一,如果不唯一的话,分成两个车厢 + if(count(array_unique($coach)) == 1){ + $onlycoach = array_unique($coach); + $string .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach) as $item_coach){ + $string .= 'Coach '.$item_coach.','; + } + } + + $string .= 'Seat '; + foreach($seats as $item_seat){ + $string .= $item_seat.','; + } + + $seatinfo = substr($string,0,strlen($string)-1); + $update_data->seatsinfo = $seatinfo; + + $post_data = array( + "key"=>JUHE_TRAIN_API_KEY, + "orderid"=>$data->orderid + ); + $back_json = GetPost_http(JUHE_TRAIN_PAY_API,$post_data); + $update_data->bookcallback = $data_post["data"]; + }elseif($data->status == "4"){ + $add_train_order_data->TOC_Memo = $data->orderid." 聚合出票"; + $add_train_order_data->TOC_COLD_SN = $data->user_orderid; + $add_train_order_data->TOC_TrainNumber = $data->checi; + $add_train_order_data->TOC_DepartureDate = $data->train_date; + $add_train_order_data->TOC_TicketCost = $data->orderamount; + $add_train_order_data->poundage = (count($data->passengers)*2)."";//手续费,每人两块,转换成字符串 + $add_train_order_data->FOI_TrainNetOrderNo = $data->ordernumber; + $this->BIZ_train_model->add_train_payment($add_train_order_data); + + $update_data->confirmcallback = $data_post["data"]; + $this->BIZ_train_model->update_cold_planvei_sn($data->user_orderid); + }elseif($data->status=="7"){ + //退票成功 写入TOC表 + $newtime = "";//记录最新操作时间 + $refund_passportseno = "";//退票人护照号 + $refund_money = "";//退票金额 + foreach ($data->passengers as $p) { + if(isset($p->returntickets)){ + $refund_passportseno = $p->refundTimeline[count($p->refundTimeline)-1]->detail->passportseno; + $refund_money = $p->refundTimeline[count($p->refundTimeline)-1]->detail->returnmoney; + //退票时还需要单独对对每个乘客存储回调信息 + $passpager_info = new stdClass(); + $passpager_info->returncallback = $data_post["data"]; + $passpager_info->status = '7'; + $passpager_info->ordernumber = $data->orderid; + $passpager_info->realname = $p->refundTimeline[count($p->refundTimeline)-1]->detail->passengername; + $passpager_info->numberid = $refund_passportseno; + print_r($passpager_info); + $this->train_system_model->update_passpager_info($passpager_info); + + //添加退款记录 + $add_train_order_data->TOC_COLD_SN = $data->user_orderid; + $add_train_order_data->TOC_Memo = $data->orderid." ".$refund_passportseno; + $add_train_order_data->ordernumber = $data->user_orderid; + $add_train_order_data->TOC_TrainNumber = $data->checi; + $add_train_order_data->TOC_DepartureDate = $data->train_date; + $add_train_order_data->TOC_TicketCost = -$refund_money; + $add_train_order_data->FOI_TrainNetOrderNo = null;//退票不用更新取票号,以此在模型里面判断是否为退票消息 + + $this->BIZ_train_model->add_train_payment($add_train_order_data); + }else{ + //有可能提交了退票或者还没有退票 + + } + } + + $update_data->returncallback = $data_post["data"]; + } + //print_r($update_data);die(); + //更新订单信息(出票系统) + $this->train_system_model->update_orders($update_data); + } + + public function ctripcallback(){ + $back_json = file_get_contents('php://input'); + log_message('error','携程回调信息:'.$back_json); + /*$back_json = '{"Authentication":{"ServiceName":"web.order.returnTicketNotice","PartnerName":"tieyou","TimeStamp":"2019-1-18 11:35:22","MessageIdentity":"93F2BA3253829E8FAD29B5DEB7646A59"},"TrainOrderService":{"contactName":{},"contactMobile":{},"OrderNumber":"guilintravel1547778269","refundTicket":{"childBillId":{},"orderId":"8360041214","eOrderNumber":"EB59937931","eOrderType":"1","seatNumber":"01D\u53f7","passport":"544712454","passportName":"YANGFRANCISCHENG","realName":"YANGFRANCISCHENG","status":"1","reason":"\u9000\u7968\u6210\u529f\uff0c\u9000\u6b3e\u91d1\u989d:218.50\u5143"}}}';*/ + $ctrip_backdata = json_decode($back_json); + //print_r($ctrip_backdata); + if(!empty($ctrip_backdata)){ + $update_data = new stdClass(); + $update_data->ServiceName = $ctrip_backdata->Authentication->ServiceName; + $update_data->ordernumber = ''; + $update_data->seatsinfo = ''; + $update_data->TicketCheck = ''; + $update_data->bookcallback = ''; + $update_data->confirmcallback = ''; + $update_data->returncallback = ''; + $update_data->OrderTotleFee = 0; + $update_data->ElectronicOrderNumber = ''; + $update_data->reschedulecallback = ''; + + if($update_data->ServiceName == 'web.order.notifyTicket'){ + $update_data->OrderStatus = '4'; + $update_data->ErrorMsg = '出票成功'; + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $update_data->OrderTotleFee = $ctrip_backdata->TrainOrderService->OrderInfo->OrderTotleFee; + $update_data->ElectronicOrderNumber = $ctrip_backdata->TrainOrderService->OrderInfo->ElectronicOrderNumber; + + //新添加检票口信息 + if(isset($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck)){ + if(!is_object($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck)){ + $update_data->TicketCheck = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck; + } + } + + //获取总票数,由于携程接口单人和多人返回的数据结构不一致 + $person_num = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketCount; + + //存储座位信息 转换为英文 + $coach_arr = array(); + $seats_arr = array(); + $data_passager = new stdClass(); + $string = ''; + $i = 0; + if($person_num > 1){ + foreach ($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo as $items){ + if(strpos($items->SeatNo,'车厢')){ + $coach = mb_substr($items->SeatNo,0,strpos($items->SeatNo,'车厢')); + array_push($coach_arr,$coach); + $seat = mb_substr($items->SeatNo,strpos($items->SeatNo,'车厢')+2,mb_strlen($items->SeatNo,'UTF8')); + $find = array('号'); + $replace = array(''); + $seat = str_replace($find,$replace,$seat); + array_push($seats_arr,$seat); + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $data_passager->realname = $items->PassengerName; + $data_passager->identitytype = $items->IdentityType; + $data_passager->numberid = $items->NumberID; + $data_passager->ticketype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketType; + $data_passager->ticketprice = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketPrice; + $data_passager->seatype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketSeat; + $data_passager->seatdetail = $items->SeatNo; + $this->train_system_model->add_passagers($data_passager); + $i++; + } + + }else{ + $seatinfo_html = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->SeatNo; + if(strpos($seatinfo_html,'车厢')){ + $coach = mb_substr($seatinfo_html,0,strpos($seatinfo_html,'车厢')); + array_push($coach_arr,$coach); + $seat = mb_substr($seatinfo_html,strpos($seatinfo_html,'车厢')+2,mb_strlen($seatinfo_html,'UTF8')); + $find = array('号'); + $replace = array(''); + $seat = str_replace($find,$replace,$seat); + array_push($seats_arr,$seat); + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $data_passager->realname = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->PassengerName; + $data_passager->identitytype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->IdentityType; + $data_passager->numberid = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->NumberID; + $data_passager->ticketype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketType; + $data_passager->ticketprice = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketPrice; + $data_passager->seatype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketSeat; + $data_passager->seatdetail = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->SeatNo; + $this->train_system_model->add_passagers($data_passager); + } + + if(count(array_unique($coach_arr)) == 1){ + $onlycoach = array_unique($coach_arr); + $update_data->seatsinfo .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach_arr) as $item_coach){ + $update_data->seatsinfo .= 'Coach '.$item_coach.','; + } + } + + $update_data->seatsinfo .= 'Seat '; + foreach($seats_arr as $item_seat){ + $update_data->seatsinfo .= $item_seat.','; + } + + $update_data->seatsinfo = substr($update_data->seatsinfo,0,strlen($update_data->seatsinfo)-1); + + $update_data->bookcallback = $back_json; + + //添加支付记录 + $add_train_payment_data->TOC_Memo = $update_data->ordernumber; + //根据订单号获取cold_sn + $order_info = $this->train_system_model->get_order_info($update_data->ordernumber); + $cold_sn = $order_info->ts_cold_sn; + $add_train_payment_data->TOC_COLD_SN = $cold_sn; + $add_train_payment_data->TOC_TrainNumber = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfo->OrderTicketCheci; + $add_train_payment_data->TOC_DepartureDate = date('Y-m-d',strtotime($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfo->OrderTicketYMD)); + $add_train_payment_data->TOC_TicketCost = $update_data->OrderTotleFee; + $add_train_payment_data->poundage = ($person_num*5)."";//手续费,每人五块,转换成字符串 + $add_train_payment_data->FOI_TrainNetOrderNo = $update_data->ElectronicOrderNumber; + //print_r($add_train_order_data);die(); + $this->BIZ_train_model->add_train_payment($add_train_payment_data); + //记录供应商(瀚特) + $this->BIZ_train_model->update_cold_planvei_sn($cold_sn); + }else if($update_data->ServiceName == 'web.order.notifyNoTicket'){ + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $update_data->OrderStatus = '1'; + $update_data->ErrorMsg = $ctrip_backdata->TrainOrderService->OrderInfo->NoTicketReasons; + $update_data->confirmcallback = $back_json; + }else if($update_data->ServiceName == 'web.order.returnTicketNotice'){ + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderNumber; + $update_data->OrderStatus = '7'; + $update_data->ErrorMsg = $ctrip_backdata->TrainOrderService->refundTicket->reason; + $update_data->returncallback = $back_json; + + //退票时还需要单独对对每个乘客存储回调信息 + $passpager_info = new stdClass(); + $passpager_info->returncallback = $back_json; + $passpager_info->status = '7'; + $passpager_info->ordernumber = $ctrip_backdata->TrainOrderService->OrderNumber; + $passpager_info->realname = $ctrip_backdata->TrainOrderService->refundTicket->realName; + $passpager_info->numberid = $ctrip_backdata->TrainOrderService->refundTicket->passport; + $this->train_system_model->update_passpager_info($passpager_info); + }else if($update_data->ServiceName == 'web.order.requestRefund'){ + $return_order = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $return_money = $ctrip_backdata->TrainOrderService->TotalRefundAmount; + + //根据订单号获取cold_sn + $order_info = $this->train_system_model->get_order_info($return_order); + $cold_sn = $order_info->ts_cold_sn; + //print_r($order_info); + + $add_train_payment_data->TOC_Memo = $return_order.'_'.$ctrip_backdata->TrainOrderService->OrderInfo->OrderTid; + $add_train_payment_data->TOC_COLD_SN = $cold_sn; + $add_train_payment_data->TOC_TrainNumber = $order_info->ts_checi; + $add_train_payment_data->TOC_DepartureDate = $order_info->ts_startdate; + $add_train_payment_data->TOC_TicketCost = -$ctrip_backdata->TrainOrderService->TotalRefundAmount; + $add_train_payment_data->FOI_TrainNetOrderNo=null; + //print_r($add_train_payment_data);die(); + $this->BIZ_train_model->add_train_payment($add_train_payment_data); + return false; + } + + //更新订单信息(出票系统) + $this->train_system_model->update_orders($update_data); + } + } +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/check.php b/application/third_party/trainsystem/controllers/check.php new file mode 100644 index 00000000..0344df4d --- /dev/null +++ b/application/third_party/trainsystem/controllers/check.php @@ -0,0 +1,528 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class check extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->model("BIZ_train_model"); + $this->load->model("train_system_model"); + $this->load->helper('train'); + $this->db_train_zw = $this->config->item('db_train_zw'); + $this->train_zw = $this->config->item('train_zw'); + $this->black_list = $this->config->item('black_list'); + $this->isauto = 0; + } + + public function index(){ + //$this->BIZ_train_model->delete_other(); + } + + //1903241050 + public function check_autotickets(){ + log_message('error','auto ticket'); + date_default_timezone_set('Asia/Shanghai'); + //判断账户余额,如果小于1000自动退出。 + $post_data = array("key"=>JUHE_TRAIN_API_KEY); + $back_data = GetPost_http("http://op.juhe.cn/trainTickets/balance.php",$post_data); + $price = json_decode($back_data)->result; + print_r('账户余额:'.$price); + if($price < 1000){ + exit('账户余额不足'); + } + //筛选出能自动出票的订单 + $auto_pool = $this->BIZ_train_model->auto_check_ticket(); + + //创建一个不允许自动出票的国际火车票数组 + $nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795'); + + //创建黑名单 + $black_list = $this->config->item('black_list'); + $string = ''; + + foreach($auto_pool as $item){ + $this->isauto = 1; + $bpe_sn = ''; + $back_message = ''; + $cold_sn = $item->COLD_SN; + $coli_id = $item->coli_id; + $back_data = 1; + + $people_arr = $this->BIZ_train_model->biz_people($cold_sn); + $train_info = $this->BIZ_train_model->get_biz_foi($cold_sn); + + if($item->COLD_SPFS > 1){ + //寄送票 + $back_data = 0; + $back_message .= '-邮寄不自动出票'; + } + + //乘客人数大于5人不出票 + if(count($people_arr) > 5){ + $back_data = 0; + $back_message .= '-乘客人数大于5不自动出票'; + } + + //护照号如果在黑名单的就不自动出票 + foreach($people_arr as $people_info){ + if(in_array($people_info->BPE_Passport,$black_list)){ + $back_data = 0; + $back_message .= '-此用户为黑名单用户,不自动出票'; + } + + if(strlen($people_info->BPE_Passport) >= 18){ + $back_data = 0; + $back_message .= '-护照位数大于18不自动出票'; + } + + $bpe_sn .= $people_info->BPE_SN.','; + } + $bpe_sn = substr($bpe_sn,0,strlen($bpe_sn)-1); + + //单张票价不能大于1000人民币 + if($train_info[0]->adultcost > 1000){ + $back_data = 0; + $back_message .= '-单价大于1000不自动出票'; + } + + //如果为国际火车票就不出票 + if(in_array($train_info[0]->FlightsNo, $nation_train)){ + $back_data = 0; + $back_message .= '-国际火车票不自动出票'; + } + + //无座的订单不做出票 + if($train_info[0]->Aircraft == 'WZ'){ + $back_data = 0; + $back_message .= '-无座不自动出票'; + } + + //香港火车不自动出票 + if($train_info[0]->DepartAirport == 'XJA'){ + $back_data = 0; + $back_message .= '-香港火车不自动出票'; + } + + $DepartureDate = strtotime($train_info[0]->DepartureDate); + $time = time(); + $depart_diff = ($DepartureDate - $time) / 86400; + + if($train_info[0]->ArrivalAirport == 'XJA' && $train_info[0]->adultcost > 500 && $depart_diff > 5){ + $back_data = 0; + $back_message .= '-内地香港火车金额大于500超过五天不自动出票'; + } + //print_r($train_info); + + //如果刚好是第三十天的订单 + if(($item->COLI_State == '8' || $item->COLI_State == '63')){ + $this->isauto = 3; + $time_obj = $this->BIZ_train_model->get_saletime($train_info['0']->DepartAirport_cn); + if(!empty($time_obj)){ + $saletime = strtotime(date('Y-m-d').' '.$time_obj->TST_saletime); + //echo $saletime; + $sale_diff = (time() - $saletime) / 3600; + echo $cold_sn.'_'.date('Y-m-d').' '.$time_obj->TST_saletime.'/'.$saletime.'<br>'; + if($sale_diff > 1){ + $back_data = 0; + $back_message .= '-超过抢票时间'; + }else if($sale_diff <0){ + $back_data = 0; + $back_message .= '-未到抢票时间'; + } + } + } + + if($back_data == 0){ + $string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.'/'.$this->isauto.')'.$back_message.'</td></tr>'; + }else{ + //单个订单提交 + echo $cold_sn.'<br>'; + //$this->booktickets($cold_sn,$bpe_sn,'','juhe'); + //$string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>'; + } + } + print_r('<table border="1">'.$string.'</table>'); + } + + //创建一个方法用于接收所有的出票请求 + public function booktickets($cold_sn=null,$bpe_sn=null,$selectseat=null,$type=null){ + if(empty($cold_sn) && empty($bpe_sn)){ + //接收子表订单号 + $cold_sn = $this->input->get_post('order'); + //接收客人表sn + $bpe_sn = $this->input->get_post("people"); + //接收选座字符串 + $selectseat = $this->input->get_post("selectseat"); + //接收出票接口 + $type = $this->input->get_post("type"); + } + //测试数据 + /*$cold_sn = '488121613'; + $bpe_sn = '473183645,473183646,473183647'; + $selectseat = ''; + $type = 'juhe';*/ + + if(!is_numeric($cold_sn)){ + $reback["mes"]="订单号是数字"; + echo json_encode($reback); + return false; + } + + if(empty($bpe_sn)){ + $reback["mes"]="请选择乘客"; + echo json_encode($reback); + return false; + } + + $data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn); + $data['people_list']=$this->BIZ_train_model->in_bpesn_people_info($bpe_sn); + + if($selectseat == ''){ + $selectseat = ''; + $train_select = $data['train']->FOI_SelectedSeat; + $obj = explode(',',$train_select); + foreach($obj as $value){ + $selectseat .= $value; + } + } + + if (empty($data['train'])) { + //显示错误,找不到车次 + $reback["mes"]="找不到车次"; + echo json_encode($reback); + return false; + } + + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $reback["mes"]="找不到乘客信息"; + echo json_encode($reback); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $reback["mes"]="乘客不能超过五个"; + echo json_encode($reback); + return false; + } + + switch ($type){ + case 'juhe': + $this->juheModel($data,$selectseat,$cold_sn); + break; + case 'tuniu': + $this->tuniuModel($data,$selectseat,$cold_sn); + break; + case 'ctrip': + $this->ctripModel($data,$selectseat,$cold_sn); + break; + } + } + + function juheModel($data=null,$selectseat=null,$cold_sn=null){ + $zwcode = $this->db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; //座位名称 + + //进行提交字符串的拼接 + $passengers = ""; + foreach ($data['people_list'] as $key => $item) { + //乘客姓名 + $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName; + //将特殊字符转换为正常字符以便于出票 + $passengersename = chk_sp_name($passengersename); + //乘客类型 + switch ($item->BPE_GuestType) { + case 1: + $piaotype = 1; + $piaotypename = "成人票"; + break; + case 2: + $piaotype = 2; + $piaotypename = "儿童票"; + break; + default://外国人应该就两种票吧 + $piaotype = 1; + $piaotypename = "成人票"; + break; + } + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + switch ($item->BPE_SEX){ + case '100003': + $sex = 'F'; + break; + case '100001': + $sex = 'M'; + break; + } + + $passportseno = str_replace(' ','',$item->BPE_Passport); + + //添加一个判断护照号是否在黑名单 + if(in_array($passportseno,$this->black_list)){ + $reback["mes"] = "乘客为黑名单用户"; + echo json_encode($reback); + return false; + } + + if($passporttypeseid == 'G'){ + $passengers .= ',{"passengerid":' . (++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","gatValidDateEnd":"'.$item->BPE_PassExpdate.'","gatBornDate":"'.$item->BPE_BirthDate.'","sexCode":"'.$sex.'"}'; + }else{ + $passengers .= ',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; + } + + } + + $passengers .= "]"; + $passengers = substr($passengers, 1); + $passengers = "[" . $passengers; + if(empty($selectseat)){ + $post_data=array( + "key"=>JUHE_TRAIN_API_KEY, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + }else{ + $post_data=array( + "key"=>JUHE_TRAIN_API_KEY, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + } + + //发起请求 + /*$add_data = new stdClass(); + $back_json = GetPost_http('http://op.juhe.cn/trainTickets/submit',$post_data); + $back_data = json_decode($back_json); + + if(!$back_data->error_code){ + $add_data->ordernumber = $back_data->result->orderid; + $reback["status"] = 1; + $reback["order"] = $back_data->result->orderid; + $reback["mes"] = "订单提交成功,等待回调"; + }else{ + $add_data->ordernumber=null; + $reback["mes"] = $back_json; + $add_data->status = "e"; + }*/ + + //本地订单入库 + $add_data->cold_sn = $cold_sn; + $add_data->returncode = $back_data->error_code; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = $data['train']->FlightsNo; + $add_data->fromstationame = $data['train']->DepartAirport_cn; + $add_data->fromstationcode = $data['train']->DepartAirport; + $add_data->tostationame = $data['train']->ArrivalAirport_cn; + $add_data->tostationcode = $data['train']->ArrivalAirport; + $add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate)); + $add_data->startime = date('H:i',strtotime($data['train']->DepartureTime)); + $add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime)); + $add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; + $add_data->channel = 'juhe'; + $add_data->isauto = $this->isauto; + print_r($add_data); + /*$this->train_system_model->add_orders($add_data); + echo json_encode($reback); + return false;*/ + + } + + public function test_add(){ + $add_data->cold_sn = '123123'; + $add_data->returncode = '123123'; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = 'G89'; + $add_data->fromstationame = '北京'; + $add_data->fromstationcode = 'BJP'; + $add_data->tostationame = '上海'; + $add_data->tostationcode = 'SHH'; + $add_data->startdate = '2019-02-09'; + $add_data->startime = '14:00'; + $add_data->endtime = '19:00'; + $add_data->runtime = '300'; + $add_data->channel = 'juhe'; + $add_data->isauto = 3; + print_r($add_data); + $this->train_system_model->add_orders($add_data); + } + + public function juhecallback(){ + /*$data_post = $this->input->post(); + if(empty($data_post)){ + header("HTTP/1.1 404 Not Found"); + exit('{"reason":"empty infos","status":"404"}'); + }*/ + + //调试代码 + $test_post = '{"data":"{\"from_station_name\":\"\u5317\u4eac\u5357\",\"from_station_code\":\"VNP\",\"to_station_name\":\"\u4e0a\u6d77\u8679\u6865\",\"to_station_code\":\"AOH\",\"train_date\":\"2019-05-08\",\"orderid\":\"JH155489661120411\",\"user_orderid\":\"488128168\",\"orderamount\":\"3496.00\",\"ordernumber\":\"EE79032518\",\"checi\":\"G43\",\"msg\":\"\u7ebf\u4e0a\u9000\u7968\u6210\u529f\",\"status\":\"7\",\"passengers\":[{\"passengerid\":1,\"passengersename\":\"WEISIGKOLIVER\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CAYLW9WTT\",\"price\":\"1748.0\",\"zwcode\":\"9\",\"zwname\":\"\u5546\u52a1\u5ea7\",\"ticket_no\":\"EE79032518103005A\",\"cxin\":\"03\u8f66\u53a2,05A\u5ea7\",\"reason\":0,\"refundTimeline\":[{\"time\":\"2019-04-11 11:46:10\",\"msg\":\"\u7ebf\u4e0a\u7533\u8bf7\u9000\u7968\"},{\"time\":\"2019-04-11 11:46:41\",\"msg\":\"\u7ebf\u4e0a\u9000\u7968\u6210\u529f\",\"detail\":{\"returnsuccess\":true,\"returnmoney\":\"1748\",\"returnfailid\":\"\",\"returnfailmsg\":\"\",\"returntype\":\"1\",\"ticket_no\":\"EE79032518103005A\",\"passengername\":\"WEISIGKOLIVER\",\"passporttypeseid\":\"B\",\"passportseno\":\"CAYLW9WTT\"}}],\"returntickets\":{\"returnsuccess\":true,\"returnmoney\":\"1748\",\"returntime\":\"2019-04-11 11:46:39\",\"returnfailid\":\"\",\"returnfailmsg\":\"\",\"returntype\":\"1\"}},{\"passengerid\":2,\"passengersename\":\"ALBERTSTEFANIECAROLINDOROTHEE\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CAYLM2751\",\"price\":\"1748.0\",\"zwcode\":\"9\",\"zwname\":\"\u5546\u52a1\u5ea7\",\"ticket_no\":\"EE79032518103005C\",\"cxin\":\"03\u8f66\u53a2,05C\u5ea7\",\"reason\":0,\"refundTimeline\":[{\"time\":\"2019-04-11 11:46:12\",\"msg\":\"\u7ebf\u4e0a\u7533\u8bf7\u9000\u7968\"}]}],\"refund_money\":\"1748.00\",\"sign\":\"f077215579ecd5c130d39b502c9bd055\"}"}'; + + $data_post["data"] = json_decode($test_post)->data; + + log_message('error','聚合回调:'.json_encode($data_post)); + $data = json_decode($data_post["data"]); + + $update_data = new StdClass(); + $update_data->OrderStatus = $data->status; + $update_data->ordernumber = $data->orderid; + $update_data->OrderTotleFee = $data->orderamount; + $update_data->seatsinfo = ''; + $update_data->TicketCheck = ''; + $update_data->bookcallback = ''; + $update_data->confirmcallback = ''; + $update_data->returncallback = ''; + $update_data->ElectronicOrderNumber = $data->ordernumber; + $update_data->reschedulecallback = ''; + $update_data->ErrorMsg = $data->msg; + + //如果返回2则发送出票请求 + if($data->status == "1"){ + $update_data->bookcallback = $data_post["data"]; + }elseif($data->status == "2"){ + $coach = array(); + $seats = array(); + $string = ''; + $passagers = $data->passengers; + foreach($passagers as $item){ + foreach(explode(',',$item->cxin) as $item_seat){ + if(strpos($item_seat,'车厢')){ + $item_seat = str_replace('车厢','',$item_seat); + array_push($coach,$item_seat); + }else{ + $find = array('座上铺','座中铺','座下铺','座'); + $replace = array(' upper',' middle',' lower',''); + $item_seat = str_replace($find,$replace,$item_seat); + array_push($seats,$item_seat); + } + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $data->orderid; + $data_passager->realname = $item->passengersename; + $data_passager->identitytype = $item->passporttypeseidname; + $data_passager->numberid = $item->passportseno; + $data_passager->ticketype = $item->piaotypename; + $data_passager->ticketprice = $item->price; + $data_passager->seatype = $item->zwname; + $data_passager->seatdetail = $item->cxin; + $data_passager->status = '4'; + $this->train_system_model->add_passagers($data_passager); + } + + //判断车厢是否唯一,如果不唯一的话,分成两个车厢 + if(count(array_unique($coach)) == 1){ + $onlycoach = array_unique($coach); + $string .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach) as $item_coach){ + $string .= 'Coach '.$item_coach.','; + } + } + + $string .= 'Seat '; + foreach($seats as $item_seat){ + $string .= $item_seat.','; + } + + $seatinfo = substr($string,0,strlen($string)-1); + $update_data->seatsinfo = $seatinfo; + + $post_data = array( + "key"=>JUHE_TRAIN_API_KEY, + "orderid"=>$data->orderid + ); + $back_json = GetPost_http(JUHE_TRAIN_PAY_API,$post_data); + $update_data->bookcallback = $data_post["data"]; + }elseif($data->status == "4"){ + $add_train_order_data->TOC_Memo = $data->orderid." 聚合出票"; + $add_train_order_data->TOC_COLD_SN = $data->user_orderid; + $add_train_order_data->TOC_TrainNumber = $data->checi; + $add_train_order_data->TOC_DepartureDate = $data->train_date; + $add_train_order_data->TOC_TicketCost = $data->orderamount; + $add_train_order_data->poundage = (count($data->passengers)*2)."";//手续费,每人两块,转换成字符串 + $add_train_order_data->FOI_TrainNetOrderNo = $data->ordernumber; + $this->BIZ_train_model->add_train_payment($add_train_order_data); + + $update_data->confirmcallback = $data_post["data"]; + $this->BIZ_train_model->update_cold_planvei_sn($data->user_orderid); + }elseif($data->status=="7"){ + //退票成功 写入TOC表 + $newtime = "";//记录最新操作时间 + $refund_passportseno = "";//退票人护照号 + $refund_money = "";//退票金额 + foreach ($data->passengers as $p) { + if(isset($p->returntickets)){ + $refund_passportseno = $p->refundTimeline[count($p->refundTimeline)-1]->detail->passportseno; + $refund_money = $p->refundTimeline[count($p->refundTimeline)-1]->detail->returnmoney; + //退票时还需要单独对对每个乘客存储回调信息 + $passpager_info = new stdClass(); + $passpager_info->returncallback = $data_post["data"]; + $passpager_info->status = '7'; + $passpager_info->ordernumber = $data->orderid; + $passpager_info->realname = $p->refundTimeline[count($p->refundTimeline)-1]->detail->passengername; + $passpager_info->numberid = $refund_passportseno; + print_r($passpager_info); + $this->train_system_model->update_passpager_info($passpager_info); + + //添加退款记录 + $add_train_order_data->TOC_COLD_SN = $data->user_orderid; + $add_train_order_data->TOC_Memo = $data->orderid." ".$refund_passportseno; + $add_train_order_data->ordernumber = $data->user_orderid; + $add_train_order_data->TOC_TrainNumber = $data->checi; + $add_train_order_data->TOC_DepartureDate = $data->train_date; + $add_train_order_data->TOC_TicketCost = -$refund_money; + $add_train_order_data->FOI_TrainNetOrderNo = null;//退票不用更新取票号,以此在模型里面判断是否为退票消息 + + $this->BIZ_train_model->add_train_payment($add_train_order_data); + }else{ + //有可能提交了退票或者还没有退票 + + } + } + + $update_data->returncallback = $data_post["data"]; + } + //print_r($update_data);die(); + //更新订单信息(出票系统) + $this->train_system_model->update_orders($update_data); + } + +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/orders.php b/application/third_party/trainsystem/controllers/orders.php new file mode 100644 index 00000000..51cde718 --- /dev/null +++ b/application/third_party/trainsystem/controllers/orders.php @@ -0,0 +1,18 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class orders extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + + } + + public function index(){ + echo 'orders manager'; + } + + + +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/pages.php b/application/third_party/trainsystem/controllers/pages.php new file mode 100644 index 00000000..77f0edca --- /dev/null +++ b/application/third_party/trainsystem/controllers/pages.php @@ -0,0 +1,208 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class pages extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->model("train_system_model"); + $this->load->model("BIZ_train_model"); + $this->load->helper('train'); + $this->order_status_msg = $this->config->item('train_order_status_msg'); + } + + public function index($coli_id = null){ + if($this->session->userdata('dingname') == '' && $this->session->userdata('dingunionid') == ''){ + dingLogin(); + } + if($coli_id == null){ + $cols_id = $this->input->post("ht_order"); + }else{ + $cols_id = $coli_id; + } + + $list=new StdClass; + if(!empty($cols_id)){ + $cold_sn = $this->BIZ_train_model->get_biz_cold($cols_id); + $list->wl = $this->BIZ_train_model->get_operatorInfo($cols_id); + $i=0; + $list->info=array(); + foreach ($cold_sn as $v) { + $list->info[$i] = new StdClass; + $list->info[$i]->people = $this->BIZ_train_model->biz_people($v->COLD_SN); + $list->info[$i]->train = $this->BIZ_train_model->get_biz_foi($v->COLD_SN); + $list->info[$i]->status = $this->BIZ_train_model->get_biz_jol($v->COLD_SN); + $i++; + } + $list->cols_id=$cols_id; + } + + //查询聚合余额 + $back_data = GetPost_http("http://op.juhe.cn/trainTickets/balance.php?key=79f03107b921ef31310bd40a1415c1cb"); + $back_data = json_decode($back_data); + if(!empty($back_data->result)){ + $list->balance = $back_data->result; + }else{ + $list->balance = "NULL"; + } + //print_r($list); + $this->load->view('common/header'); + $this->load->view('homepage',$list); + $this->load->view('common/footer'); + } + + //系统列表页面 + public function order_list(){ + if($this->session->userdata('dingname') == '' && $this->session->userdata('dingunionid') == ''){ + dingLogin(); + } + $page_size = 10; + $page = $this->input->get("page"); + $order = $this->input->get("order"); + $web_code = $this->input->get("web_code"); + $where = "1=1";//搜索条件 + $page_parameter = "";//返回的分页条件参数 + if(empty($page) or !is_numeric($page)){ + $page=0; + } + if(!empty($order)){ + $where = "BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR InfoManager.dbo.trainsystem.ts_ordernumber='{$order}'"; + //$where2 = "where BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR JOL_JuheOrder='{$order}'"; + $list["order"] = $order; + $page_parameter = "order=".$order; + } + if(!empty($web_code)){ + $where = "BIZ_ConfirmLineInfo.COLI_WebCode='{$web_code}'"; + $page_parameter = "web_code=".$web_code; + } + + //获取订单数据 + $data = $this->train_system_model->get_order($page_size,$page,$where); + //print_r($data);die(); + $list["data"]=$data->list; + + $this->load->library('pagination'); + + $config['base_url'] = site_url("/apps/trainsystem/pages/order_list?{$page_parameter}"); + $config['total_rows'] = $data->count; + $config['per_page'] = $page_size; + $config['page_query_string']=TRUE; + $config['query_string_segment']="page"; + $config['cur_tag_open'] = '<li class="active"><a href="#">'; + $config['cur_tag_close'] = '</a></li>'; + $config['first_tag_open']=$config['last_tag_open']=$config['next_tag_open']=$config['prev_tag_open']=$config['num_tag_open']="<li>"; + $config['first_tag_close']=$config['last_tag_close']=$config['next_tag_close']=$config['prev_tag_close']=$config['num_tag_close']="</li>"; + + $this->pagination->initialize($config); + + $list["page_link"]=$this->pagination->create_links(); + + foreach ($list["data"] as $key => $value) { + $value->info = $this->order_status_msg[$value->ts_status];//自定义说明信息; + } + + + $this->load->view('header'); + $this->load->view('order_list',$list); + $this->load->view('footer'); + } + + //订单详情页面 + public function order(){ + if($this->session->userdata('dingname') == '' && $this->session->userdata('dingunionid') == ''){ + dingLogin(); + } + $ordernumber = $order=$this->input->get("order"); + + if(empty($ordernumber)){ + exit('参数错误'); + } + + //根据订单号查询订单信息 + $data = array(); + $train_infos = $this->train_system_model->get_train_infos($ordernumber); + $passpager_detail = $this->train_system_model->get_passager_details($ordernumber); + + //构造详情数组 + $data['status'] = $train_infos->ts_status; + $data['ordernumber'] = $train_infos->ts_ordernumber; + $data['train_date'] = $train_infos->ts_startdate; + $data['checi'] = $train_infos->ts_checi; + $data['elecnumber'] = $train_infos->ts_elecnumber; + $data['from_station_name'] = $train_infos->ts_fromstationame; + $data['from_station_code'] = $train_infos->ts_fromstationcode; + $data['to_station_name'] = $train_infos->ts_tostationame; + $data['to_station_code'] = $train_infos->ts_tostationcode; + $data['start_time'] = $train_infos->ts_startime; + $data['arrive_time'] = $train_infos->ts_endtime; + $data['channel'] = $train_infos->ts_channel; + $data['msg'] = $train_infos->ts_errormsg; + $data['passengers'] = $passpager_detail; + + //聚合订单可以查询实时数据 + if($train_infos->ts_channel == 'juhe'){ + $post_data=array( + "key"=>"79f03107b921ef31310bd40a1415c1cb", + "orderid"=>$train_infos->ts_ordernumber + ); + $back_data = GetPost_http("http://op.juhe.cn/trainTickets/orderStatus",$post_data); + $data['train_date'] = ''; + $data['start_time'] = json_decode($back_data)->result->start_time; + $data['arrive_time'] = json_decode($back_data)->result->arrive_time; + } + + $this->load->view('bootstrap3/header'); + $this->load->view('order',$data); + $this->load->view('bootstrap3/footer'); + } + + //退票页面 + public function refund(){ + if($this->session->userdata('dingname') == '' && $this->session->userdata('dingunionid') == ''){ + dingLogin(); + } + $ordernumber = $order=$this->input->get("order"); + + if(empty($ordernumber)){ + exit('参数错误'); + } + + //根据订单号查询订单信息 + $data = array(); + $train_infos = $this->train_system_model->get_train_infos($ordernumber); + $passpager_detail = $this->train_system_model->get_passager_details($ordernumber); + + //构造详情数组 + $data['ordernumber'] = $train_infos->ts_ordernumber; + $data['cold_sn'] = $train_infos->ts_cold_sn; + $data['train_date'] = $train_infos->ts_startdate; + $data['checi'] = $train_infos->ts_checi; + $data['elecnumber'] = $train_infos->ts_elecnumber; + $data['from_station_name'] = $train_infos->ts_fromstationame; + $data['from_station_code'] = $train_infos->ts_fromstationcode; + $data['to_station_name'] = $train_infos->ts_tostationame; + $data['to_station_code'] = $train_infos->ts_tostationcode; + $data['start_time'] = $train_infos->ts_startime; + $data['arrive_time'] = $train_infos->ts_endtime; + $data['channel'] = $train_infos->ts_channel; + $data['msg'] = $train_infos->ts_errormsg; + $data['return_json'] = $train_infos->ts_returncallback; + $data['passengers'] = $passpager_detail; + + //print_r($data); + $this->load->view('header'); + $this->load->view('refund',$data); + $this->load->view('footer'); + + } + + public function export(){ + if($this->session->userdata('dingname') == '' && $this->session->userdata('dingunionid') == ''){ + dingLogin(); + } + $this->load->view('header'); + $this->load->view('export'); + $this->load->view('footer'); + } +} \ No newline at end of file diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php new file mode 100644 index 00000000..078bf373 --- /dev/null +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -0,0 +1,153 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class returnorders extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->helper('train'); + $this->load->model("train_system_model"); + $this->load->model("Sendmail_model"); + $this->load->model('BIZ_train_model'); + } + + public function index(){ + echo 'return tickets'; + } + + public function returntickets(){ + //第三方订单号(为了避免一个子订单乘客分开出票而产生错误) + $ordernumber = $this->input->get_post('ordernumber'); + //护照姓名 + $passportname = $this->input->get_post('passportname'); + //护照号 + $passportno = $this->input->get_post('passportno'); + + if(!$ordernumber || !$passportname || !$passportno){ + header("HTTP/1.1 404 Not Found"); + exit('{"reason":"传参错误","status":"404"}'); + } + + //网前提交的姓名没有做处理 + $passportname = chk_sp_name($passportname); + + $ticket_data = $this->train_system_model->ticketfrom($ordernumber); + $passenger_data = $this->train_system_model->get_passenger_info($ordernumber,$passportname,$passportno); + + $channel = $ticket_data->ts_channel; + + if(empty($passenger_data)){ + exit('乘客信息为空无法退票'); + } + + switch ($channel){ + case 'juhe': + $this->juheModel($ticket_data,$passenger_data); + break; + case 'ctrip': + $this->ctripModel($ticket_data,$passenger_data); + break; + } + } + + function juheModel($ticket_data,$data){ + $post_data = array( + "key"=>JUHE_TRAIN_API_KEY, + "orderid"=>$ticket_data->ts_ordernumber + ); + $back_json = GetPost_http(JUHE_TRAIN_STATUS_API,$post_data); + $back_detail_data = json_decode($back_json); + //print_r($back_data);die(); + foreach($back_detail_data->result->passengers as $items){ + if($items->passengersename == $data->tst_realname && $items->passportseno == $data->tst_numberid){ + $ticket_no = $items->ticket_no; + } + } + + //发起退票 + $post_data1 = array( + "key"=>JUHE_TRAIN_API_KEY, + "orderid"=>$ticket_data->ts_ordernumber, + "tickets"=>'[{"ticket_no":"'.$ticket_no.'","passengername":"'.$data->tst_realname.'","passporttypeseid":"'.strexchangeid($data->tst_ticketype).'","passportseno":"'.$data->tst_numberid.'"}]', + ); + //print_r($post_data1);die(); + $back_json = GetPost_http(JUHE_TRAIN_REFUND_API,$post_data1); + //print_r($post_data1); + + log_message('error','聚合退票:'.$ticket_data->ts_ordernumber.'|'.$back_json); + $back_data = json_decode($back_json); + + if($back_data->error_code == '0'){ + //退票成功后发送一封邮件 + $fromName = 'trainsystem'; + $fromEmail = 'cyc@hainatravel.com'; + $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn); + $coli_id = $coli_id['0']->COLI_ID; + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $subject = '退票请求'; + $body = $back_detail_data->result->ordernumber.' 提出退票,乘客:'.$data->tst_realname.', '.$back_detail_data->result->start_time.' '.$back_detail_data->result->checi; + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + echo '{"reason":"退票成功","status":"200"}'; + }else{ + header("HTTP/1.1 404 Not Found"); + echo '{"reason":"退票失败","status":"404"}'; + } + } + + function ctripModel($ticket_data,$passenger_data){ + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.ticketReturn'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.ticketReturn'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->contactName = '陈宇超'; + $PostData['TrainOrderService']->contactMobile = '18877381547'; + $PostData['TrainOrderService']->OrderNumber = $ticket_data->ts_ordernumber; + $PostData['TrainOrderService']->OperatorType = '0'; + $PostData['TrainOrderService']->TicketInfo = ''; + $PostData['TrainOrderService']->TicketInfo = array(); + + $i = 0; + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderNumber'] = $passenger_data->ts_elecnumber; + if($passenger_data->tst_ticketype == '儿童票'){ + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderType'] = '2'; + }else{ + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderType'] = '1'; + } + $PostData['TrainOrderService']->TicketInfo[$i]['seatNumber'] = $passenger_data->tst_seatdetail; + $PostData['TrainOrderService']->TicketInfo[$i]['passportName'] = $passenger_data->tst_realname; + $PostData['TrainOrderService']->TicketInfo[$i]['passport'] = $passenger_data->tst_numberid; + $PostData['TrainOrderService']->TicketInfo[$i]['realName'] = $passenger_data->tst_realname; + + //发起退票请求 + $Url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerReturnTicket'; + $ResponseJson = GetPost_http($Url,json_encode($PostData),'POST'); + $ResponseData = json_decode($ResponseJson); + + if($ResponseData->Status == 'SUCCESS'){ + $fromName = 'trainsystem'; + $fromEmail = 'cyc@hainatravel.com'; + $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn); + $coli_id = $coli_id['0']->COLI_ID; + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $subject = '退票请求'; + $body = '乘客:'.$data->tst_realname.' 对订单:'.$data->ts_ordernumber.'发起退票请求!!!'; + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + echo '{"reason":"退票成功","status":"200"}'; + }else{ + header("HTTP/1.1 404 Not Found"); + echo '{"reason":"退票失败","status":"404"}'; + } + } + + +} \ No newline at end of file diff --git a/application/third_party/trainsystem/helpers/train_helper.php b/application/third_party/trainsystem/helpers/train_helper.php new file mode 100644 index 00000000..d79db5e6 --- /dev/null +++ b/application/third_party/trainsystem/helpers/train_helper.php @@ -0,0 +1,89 @@ +<?php +//;ţӿڴǩ +function create_sign(){ + $time = date('Y-m-d H:i:s',time()); + $secretKey = 'qvHMJVywEQqsd4EneHQl'; + $id = 'retailId25'; + $timeStamp = 'timestamp'.$time; + $sign = $secretKey.$id.'apiKey'.TUNIU_KEY.$timeStamp.$secretKey; + return strtoupper(md5($sign)); +} + +//֤תid +function strexchangeid($name){ + if($name != ''){ + switch ($name){ + case '֤': + return '1'; + break; + case '': + return 'B'; + break; + case '̨֤ͨ': + return 'G'; + break; + case '۰֤ͨ': + return 'C'; + break; + default : + return 'B'; + break; + } + } +} + +//ַת +function chk_sp_name($name){ + $name = str_replace( + array('', '', '', '', '', '', '?', '', '', '', '', '', '?',' ','/',' ',','), + array('a', 'e', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N','','','',''), + $name + ); + return substr(strtoupper($name),0,30); + } + +// +function GetPost_http($url, $data = '',$format='') { + if(!isset($_SERVER['HTTP_USER_AGENT'])){ + $_SERVER['HTTP_USER_AGENT'] = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.2372.400 QQBrowser/9.5.10548.400'; + } + $curl = curl_init(); // һCURLỰ + curl_setopt($curl, CURLOPT_URL, $url); // Ҫʵĵַ + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // ֤֤Դļ + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // ֤мSSL㷨Ƿ + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // ģûʹõ + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // ʹԶת + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // ԶReferer + if (!empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // һPost + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Postύݰ + if($format == 'json'){ + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); + } + } + curl_setopt($curl, CURLOPT_TIMEOUT, 40); // óʱƷֹѭ + curl_setopt($curl, CURLOPT_TIMEOUT_MS, 40000); // óʱƷֹѭ + curl_setopt($curl, CURLOPT_HEADER, 0); // ʾصHeader + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // ȡϢļʽ + $tmpInfo = curl_exec($curl); // ִв + $errno = curl_errno($curl); + if ($errno !== 0) { + log_message('error', 'ctripost'.$errno.curl_error($curl)); + } + curl_close($curl); //رCURLỰ + return $tmpInfo; // +} + +function getDingSignature(){ + $timestamp = time(); + $signature = hash_hmac('sha256',$timestamp,'emCK5vYFJc-HtMNNgbyGpmbYaNyPkNXn_ayoFd6q2m6rpljhxBn2JQEx9gy8H6DQ',true); + $signature = base64_encode($signature); + return $signature; +} + +function dingLogin(){ + redirect('https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoaystremzlahfew1tb&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/info.php/apps/trainsystem/api/check_login'); +} + + +?> \ No newline at end of file diff --git a/application/third_party/trainsystem/libraries/Des.php b/application/third_party/trainsystem/libraries/Des.php new file mode 100644 index 00000000..b2ea6b5f --- /dev/null +++ b/application/third_party/trainsystem/libraries/Des.php @@ -0,0 +1,59 @@ +<?php +class Des +{ + + function encrypt($string,$key) + { + $size = mcrypt_get_block_size('des','ecb'); + //$string = mb_convert_encoding($string, 'GBK', 'UTF-8'); + $string = $this->pkcs5_pad($string, $size); + $td = mcrypt_module_open('des', '', 'ecb', ''); + $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); + @mcrypt_generic_init($td, $key, $iv); + $data = mcrypt_generic($td, $string); + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + $data = base64_encode($data); + return $data; + } + + function decrypt($string,$key) + { + $string = base64_decode($string); + $td = mcrypt_module_open('des', '', 'ecb', ''); + //使用MCRYPT_DES算法,cbc模式 + $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); + $ks = mcrypt_enc_get_key_size($td); + @mcrypt_generic_init($td, $key, $iv); + //初始处理 + $decrypted = mdecrypt_generic($td, $string); + //解密 + mcrypt_generic_deinit($td); + //结束 + mcrypt_module_close($td); + + $result = $this->pkcs5_unpad($decrypted); + //$result = mb_convert_encoding($result, 'UTF-8', 'GBK'); + return $result; + } + + function pkcs5_pad($text, $blocksize) + { + $pad = $blocksize - (strlen($text) % $blocksize); + return $text . str_repeat(chr($pad), $pad); + } + + function pkcs5_unpad($text) + { + $pad = ord($text{strlen($text) - 1}); + if ($pad > strlen($text)) { + return false; + } + if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { + return false; + } + return substr($text, 0, -1 * $pad); + } +} + +?> \ No newline at end of file diff --git a/application/third_party/trainsystem/models/BIZ_train_model.php b/application/third_party/trainsystem/models/BIZ_train_model.php new file mode 100644 index 00000000..bd392858 --- /dev/null +++ b/application/third_party/trainsystem/models/BIZ_train_model.php @@ -0,0 +1,492 @@ +<?php + +class BIZ_train_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + $this->INFO = $this->load->database('INFO', TRUE); + } + + //获取订单信息 + function biz_order_detail($cold_sn) { + $sql = " + SELECT TOP 1 bfoi.FOI_SN + ,bfoi.FOI_COLD_SN + ,bfoi.DepartAirport + ,bfoi.ArrivalAirport + ,bfoi.FlightsNo + ,bfoi.Aircraft + ,bfoi.DepartureDate + ,bfoi.FOI_SelectedSeat + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + and ISNULL(TRS_StationCN,'')<>'' + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + and ISNULL(TRS_StationCN,'')<>'' + ) AS ArrivalAirport_cn, + FOI_TrainNetOrderNo, + bfoi.adultcost, + bfoi.childcost, + ArrivalTime, + DepartureTime + FROM BIZ_FlightsOrderInfo bfoi + WHERE bfoi.FOI_COLD_SN = ? + "; + $query = $this->HT->query($sql, $cold_sn); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //传入一组BPE_SN获取乘客信息 + function in_bpesn_people_info($bpe_sn){ + $sql = " + SELECT bbp.BPE_SN + ,bbp.BPE_FirstName + ,bbp.BPE_MiddleName + ,bbp.BPE_LastName + ,bbp.BPE_GuestType + ,bbp.BPE_Passport + ,bbp.BPE_PassportType + ,bbp.BPE_SEX + ,bbp.BPE_BirthDate + ,bbp.BPE_PassExpdate + FROM BIZ_BookPeople bbp + WHERE BPE_SN in(".$bpe_sn.") + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + //传入主订单翰特订单号COLI_ID(161014006M),获取子订单中火车订单的COLD_SN + function get_biz_cold($cols_id) { + $sql = "SELECT COLD_SN + FROM BIZ_ConfirmLineDetail bcld + WHERE bcld.COLD_COLI_SN=( + SELECT COLI_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID=?) + AND bcld.DeleteFlag=0 AND bcld.COLD_ServiceType='2'"; + $query = $this->HT->query($sql, $cols_id); + return $query->result(); + } + + //传入子订单COLD_SN,获取子订单对应的乘客信息 + function biz_people($cold_sn) { + $sql = " + SELECT bbp.BPE_SN + ,bbp.BPE_FirstName + ,bbp.BPE_MiddleName + ,bbp.BPE_LastName + ,bbp.BPE_GuestType + ,bbp.BPE_Passport + ,bbp.BPE_PassportType + FROM BIZ_BookPeople bbp + WHERE EXISTS( + SELECT TOP 1 1 + FROM BIZ_BookPeopleList bbpl + WHERE bbpl.BPL_BPE_SN = bbp.BPE_SN + AND bbpl.BPL_COLD_SN = ? + ) + "; + $query = $this->HT->query($sql, $cold_sn); + return $query->result(); + } + + //传入COLD_SN,获取火车车次等信息 + function get_biz_foi($cold_sn) { + $sql = " + SELECT FOI_COLD_SN, + FlightsNo, + Cabin, + Aircraft, + DepartureCity, + DepartAirport, + ArrivalAirport, + ArrivalCity, + DepartureDate, + DepartureTime, + ArrivalTime, + adultcost, + FOI_SelectedSeat, + FOI_TrainNetOrderNo, + FOI_SaleDate, + ( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + ) AS ArrivalAirport_cn + FROM BIZ_FlightsOrderInfo + WHERE FOI_COLD_SN = ? + "; + $query = $this->HT->query($sql, $cold_sn); + return $query->result(); + } + + //传入COLD_SN,获取BIZ_JuheOrderList是否存在此子订单,用来判断是否提交过给聚合 + function get_biz_jol($cold_sn) { + $sql = "SELECT top 1 JOL_SN FROM BIZ_JuheOrderList WHERE JOL_COLD_SN= ?"; + $query = $this->HT->query($sql, $cold_sn); + if($query->num_rows() == 0){ + return true; + }else{ + return false; + } + } + + //传入COLI_ID,获取外联名 + function get_operatorInfo($cols_id) { + $sql = " + SELECT + Name, + OPI_Name, + case when OPI_SN=375 then OPI_EmailBak else OPI_Email end as OPI_Email, + tel, + Mobile, + Email + FROM OperatorInfo + left join agenter_user + on AU_OPI_SN = OPI_SN + WHERE OPI_SN = ( + SELECT COLI_OPI_ID + FROM BIZ_ConfirmLineInfo bcli + WHERE bcli.COLI_ID = ? + ) + and agenter in ('cht', 'train_vac', 'jp', 'train_it', 'vc', 'ru') + "; + $query = $this->HT->query($sql, $cols_id); + return $query->result(); + } + + //新增支付记录 + public function add_train_payment($data){ + //主表ID,下面两个地方用到,所以先筛选出来,不知道能不能通过合并提高效率 + $sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?"; + $query=$this->HT->query($sql,$data->TOC_COLD_SN); + $query=$query->result(); + $CCSN=$query[0]->COLD_COLI_SN; + //删除多余支付记录 + $sql = "delete from BIZ_TrainOrderCost where TOC_COLI_SN = '{$CCSN}' and TOC_TicketCost is null"; + $query=$this->HT->query($sql); + if(empty($data->FOI_TrainNetOrderNo)){ + //退票 + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_DepartureDate, + TOC_TicketCost, + TOC_WL + ) + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}))"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%","退票费 ".$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost)); + }else{ + //出票 + //BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号 + /* + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=? + WHERE + FOI_COLD_SN=? + */ + $sql="IF EXISTS( + select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo = '$data->FOI_TrainNetOrderNo')) + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN' + ELSE + IF NOT EXISTS(select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and FOI_TrainNetOrderNo LIKE '%$data->FOI_TrainNetOrderNo%') + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN'"; + + $this->HT->query($sql); + + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_DepartureDate, + TOC_TicketCost, + TOC_WL, + TOC_OtherCost + ) + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT isnull(COLI_OPI_ID,29) FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%",$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost,$data->TOC_Memo." 手续费",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->poundage)); + } + return $query; + } + + public function update_cold_planvei_sn($cold_sn){ + $sql = "update BIZ_ConfirmLineDetail set COLD_PlanVEI_SN=30427 where COLD_SN = ?"; + $query = $this->HT->query($sql,$cold_sn); + } + + //自动获取符合自动出票要求的订单的coli_sn + function auto_check_ticket(){ + $sql = "SELECT distinct top 20 COLD_SN ,coli_id,COLD_SPFS,COLI_State + FROM BIZ_ConfirmLineInfo bcli + inner join BIZ_ConfirmLineDetail bcld on COLD_COLI_SN=COLI_SN + LEFT JOIN BIZ_GroupAccountInfo bgai + ON bcli.COLI_SN = bgai.GAI_COLI_SN + WHERE bcli.COLI_ServiceType = '2' + AND bcli.COLI_State in ('11','13','8','63') + AND bcli.COLI_WebCode in ('cht', 'JP', 'train_it', 'VC', 'train_ru','GM-Train','SHT','CT') + AND (bcli.COLI_Price - bgai.GAI_SQJE) <= 20 + AND (bcli.COLI_Price - bgai.GAI_SQJE) >= 0 + AND bcli.DeleteFlag = 0 + AND bgai.DeleteFlag = 0 + AND bcld.DeleteFlag = 0 + --AND COLD_SPFS<=2 + AND NOT EXISTS ( + SELECT TOP 1 1 + FROM InfoManager.dbo.trainsystem + WHERE ts_cold_sn = COLD_SN + ) + and (((COLI_State<>8 and COLI_State<>63) and COLD_StartDate < CONVERT(varchar(100),GETDATE()+29,23)) or ((COLI_State=8 or COLI_State=63) and COLD_StartDate between CONVERT(varchar(100),GETDATE()+29,23) and CONVERT(varchar(100),GETDATE()+29,23)+' 23:59')) + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_saletime($station){ + $sql = 'select TST_saletime from TrainSaleTime where TST_station_cn = ?'; + $query = $this->HT->query($sql,$station); + return $query->row(); + } + + //筛选符合发送邮件的订单 + public function auto_sendmail(){ + $sql = "SELECT + ts_cold_sn, + ts_ordernumber, + ts_status, + ts_isauto + FROM + trainsystem + left join + Tourmanager.dbo.BIZ_ConfirmLineDetail bcld + on + bcld.COLD_SN = ts_cold_sn + left join + Tourmanager.dbo.BIZ_ConfirmLineInfo bcli + on + bcld.COLD_COLI_SN = bcli.COLI_SN + WHERE + ts_sendmail is null + AND + ts_isauto = 1 + AND + ts_status != '0' + AND + ts_status != 'e' + AND + ts_status != '2' + AND + bcli.COLI_WebCode = 'cht' + "; + $query = $this->INFO->query($sql); + return $query->result(); + } + + // 传入 cold_sn 获取订单号 + public function cold_sn_get_coli_id($cold_sn){ + $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo + WHERE COLI_SN = ( + SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN = ? + ) + "; + $query = $this->HT->query($sql,array($cold_sn)); + return $query->result(); + } + + //邮件使用 + function get_user_info($jh_order){ + $sql = "select + * + from + Tourmanager.dbo.BIZ_ConfirmLineDetail + where + COLD_SN = ( + select + top 1 ts_cold_sn + from + trainsystem + where + ts_ordernumber = ? + )"; + $query = $query = $this->INFO->query($sql, $jh_order); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //用于自动出票,传入主订单翰特订单号 COLI_ID ,获取客人的姓名和邮箱 + public function get_guest_info($COLI_ID){ + $sql = "SELECT GUT_FirstName,GUT_LastName,GUT_Email FROM BIZ_GUEST bg WHERE bg.GUT_SN = + ( SELECT COLI_GUT_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID = ?) + "; + $query = $this->HT->query($sql,$COLI_ID); + return $query->result(); + } + + //获取paypal付款记录 + function get_paypal($coli_id){ + $sql = "select top 1 GAI_SQJE from BIZ_GroupAccountInfo where GAI_COLI_ID = ?"; + $query = $query = $this->HT->query($sql, $coli_id); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //通过 JOL_JuheOrder 获取 BIZ_JuheOrderList 获取聚合订单详情 + public function get_biz_jol_info($cold_sn,$jol_jo){ + $sql = "SELECT top 1 + * + FROM trainsystem + WHERE ts_cold_sn = ? AND ts_ordernumber = ? + "; + $query = $this->INFO->query($sql,array($cold_sn,$jol_jo)); + return $query->row(); + } + + //获取跟踪号 + public function getTrackingCode(){ + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "exec dbo.SP_getTrackingCode;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + }else{ + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->TrackingCode); + } + } + + //接收聚合订单号,获取翰特订单号,即BIZ_ConfirmLineInfo的COLI_ID + function jh_order_get_coli_id($ordernumber){ + $sql="SELECT + COLI_ID,COLI_SN,COLI_OPI_ID + FROM + BIZ_ConfirmLineInfo bcli + WHERE + bcli.COLI_SN= + (SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail bcld WHERE bcld.COLD_SN= + (SELECT ts_cold_sn FROM InfoManager.dbo.trainsystem WHERE ts_ordernumber = ? and ts_channel = 'juhe')) + "; + $query = $this->HT->query($sql, $ordernumber); + return $query->result(); + } + + //跟踪号与订单关联 + public function linkTrackingCode($coli_sn,$TrackCode){ + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "exec dbo.SP_recordTrackingCode '$coli_sn', '$TrackCode'"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + }else{ + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + /* + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + */ + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + + } + } + + //通过COLI_ID获取团名 即 GroupInfo的GRI_No + function get_gri_no($coli_id){ + $sql="SELECT GRI_No FROM GroupInfo + WHERE GRI_SN=( + SELECT COLI_GRI_SN FROM BIZ_ConfirmLineInfo WHERE COLI_ID=? + ) + "; + $query = $this->HT->query($sql, $coli_id); + return $query->result(); + } + + //修改 + function update_biz_jol($where,$data){ + return $this->INFO->where($where)->update("trainsystem", $data); + } + + function delete_other(){ + $sql = "delete from trainsystem where ts_id = '860'"; + $query = $this->INFO->query($sql); + } +} diff --git a/application/third_party/trainsystem/models/sendmail_model.php b/application/third_party/trainsystem/models/sendmail_model.php new file mode 100644 index 00000000..98ec89bc --- /dev/null +++ b/application/third_party/trainsystem/models/sendmail_model.php @@ -0,0 +1,157 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + +class Sendmail_model extends CI_Model { + + function __construct() + { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + function SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body) + { + $time = date('Y-m-d H:i:s',time()); + if($this->validEmail($toEmail)) + { + $data = array( + "M_ReplyToName" => $fromName, //回复人 + "M_ReplyToEmail" => $fromEmail, //回复地址 + "M_ToName" => $toName, //收件人名 + "M_ToEmail" => $toEmail, //收件邮件地址 + "M_Title" => $subject, //主题 + "M_Body" => $body, //邮件正文 + "M_Web" => "CHT", //所属站点 + "M_FromName" => "Chinahighlights.com", //站点名称 + "M_State" => 0, + "M_AddTime" => $time + ); + $this->HT->insert('Email_AutomaticSend',$data); + $m_sn = $this->HT->insert_id('Email_AutomaticSend'); + return $m_sn; + }else{ + return FALSE; + } + } + + function SendMailToTabletest($fromName,$fromEmail,$toName,$toEmail,$subject,$body) + { + $time = date('Y-m-d H:i:s',time()); + if($this->validEmail($toEmail)) + { + $data = array( + "M_ReplyToName" => $fromName, //回复人 + "M_ReplyToEmail" => $fromEmail, //回复地址 + "M_ToName" => $toName, //收件人名 + "M_ToEmail" => $toEmail, //收件邮件地址 + "M_Title" => $subject, //主题 + "M_Body" => $body, //邮件正文 + "M_Web" => "CHT", //所属站点 + "M_FromName" => "Chinahighlights.com", //站点名称 + "M_State" => 0, + "M_AddTime" => $time, + ); + $this->HT->insert('Email_AutomaticSend',$data); + $m_sn = $this->HT->insert_id('Email_AutomaticSend'); + return $m_sn; + }else{ + return FALSE; + } + } + + + public function validEmail($email){ + $isValid = true; + $atIndex = strrpos($email, "@"); + if (is_bool($atIndex) && !$atIndex){ + $isValid = false; + }else{ + $domain = substr($email, $atIndex+1); + $local = substr($email, 0, $atIndex); + $localLen = strlen($local); + $domainLen = strlen($domain); + $domain = str_replace(' ','',$domain); + if ($localLen < 1 || $localLen > 64){ + // local part length exceeded + $isValid = false; + }else if ($domainLen < 1 || $domainLen > 255){ + // domain part length exceeded + $isValid = false; + }else if ($local[0] == '.' || $local[$localLen-1] == '.'){ + // local part starts or ends with '.' + $isValid = false; + }else if (preg_match('/\\.\\./', $local)){ + // local part has two consecutive dots + $isValid = false; + }else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){ + // character not valid in domain part + $isValid = false; + }else if (preg_match('/\\.\\./', $domain)){ + // domain part has two consecutive dots + $isValid = false; + }else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local))){ + // character not valid in local part unless + // local part is quoted + if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))){ + $isValid = false; + } + } + /* + 不检查是否有DNS解析 + if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ + // domain not found in DNS + $isValid = false; + } + */ + } + return $isValid; + } + + public function validEmailtest($email){ + $isValid = true; + $atIndex = strrpos($email, "@"); + if (is_bool($atIndex) && !$atIndex){ + $isValid = false; + }else{ + $domain = substr($email, $atIndex+1); + $local = substr($email, 0, $atIndex); + $localLen = strlen($local); + $domainLen = strlen($domain); + $domain = str_replace(' ','',$domain); + print_r(preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)); + if ($localLen < 1 || $localLen > 64){ + // local part length exceeded + $isValid = false; + }else if ($domainLen < 1 || $domainLen > 255){ + // domain part length exceeded + $isValid = false; + }else if ($local[0] == '.' || $local[$localLen-1] == '.'){ + // local part starts or ends with '.' + $isValid = false; + }else if (preg_match('/\\.\\./', $local)){ + // local part has two consecutive dots + $isValid = false; + }else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){ + // character not valid in domain part + $isValid = false; + }else if (preg_match('/\\.\\./', $domain)){ + // domain part has two consecutive dots + $isValid = false; + }else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local))){ + // character not valid in local part unless + // local part is quoted + if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))){ + $isValid = false; + } + } + /* + 不检查是否有DNS解析 + if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ + // domain not found in DNS + $isValid = false; + } + */ + } + return $isValid; + } + +} \ No newline at end of file diff --git a/application/third_party/trainsystem/models/train_system_model.php b/application/third_party/trainsystem/models/train_system_model.php new file mode 100644 index 00000000..9b84793a --- /dev/null +++ b/application/third_party/trainsystem/models/train_system_model.php @@ -0,0 +1,267 @@ +<?php + +class train_system_model extends CI_Model { + private $order="";//订单号 + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + $this->INFO = $this->load->database('INFO', TRUE); + } + + public function get_order($pagesize=2,$page=0,$where="1=1"){ + $data=new StdClass(); + //获取总条数 + $sql="SELECT COUNT(*) AS count FROM InfoManager.dbo.trainsystem + LEFT JOIN + BIZ_ConfirmLineInfo + ON + BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN = InfoManager.dbo.trainsystem.ts_cold_sn) + WHERE + {$where} + "; + $query = $this->HT->query($sql); + $count=$query->result(); + $data->count=$count[0]->count; + + $sql="SELECT TOP {$pagesize} InfoManager.dbo.trainsystem.ts_subtime, + InfoManager.dbo.trainsystem.ts_cold_sn, + InfoManager.dbo.trainsystem.ts_ordernumber, + InfoManager.dbo.trainsystem.ts_status, + InfoManager.dbo.trainsystem.ts_errormsg, + InfoManager.dbo.trainsystem.ts_fromstationame, + InfoManager.dbo.trainsystem.ts_tostationame, + InfoManager.dbo.trainsystem.ts_checi, + InfoManager.dbo.trainsystem.ts_orderamount, + InfoManager.dbo.trainsystem.ts_isauto, + InfoManager.dbo.trainsystem.ts_sendmail, + InfoManager.dbo.trainsystem.ts_m_sn, + InfoManager.dbo.trainsystem.ts_channel, + BIZ_ConfirmLineInfo.COLI_ID, + BIZ_ConfirmLineInfo.COLI_WebCode + FROM + InfoManager.dbo.trainsystem + LEFT JOIN + BIZ_ConfirmLineInfo + ON + BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN = InfoManager.dbo.trainsystem.ts_cold_sn) + WHERE + InfoManager.dbo.trainsystem.ts_id NOT IN( + SELECT + TOP {$page} ts_id + FROM + InfoManager.dbo.trainsystem + LEFT JOIN + BIZ_ConfirmLineInfo + ON + BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN = InfoManager.dbo.trainsystem.ts_cold_sn) + where {$where} + ORDER BY ts_subtime DESC) + AND + {$where} + ORDER BY InfoManager.dbo.trainsystem.ts_subtime DESC"; + + $query = $this->HT->query($sql); + $data->list=$query->result(); + return $data; + + } + + //获取指定订单信息 + public function get_passager_details($ordernumber){ + $sql = "select * from trainsystem_tickets where tst_ordernumber = '{$ordernumber}'"; + $query = $this->INFO->query($sql); + return $query->result(); + } + + //获取火车信息 + public function get_train_infos($ordernumber){ + $sql = "select * from trainsystem where ts_ordernumber = '{$ordernumber}'"; + $query = $this->INFO->query($sql); + return $query->row(); + } + + public function update_passpager_status($status,$passagerid){ + $sql = "update trainsystem_tickets set tst_status = '{$status}' where tst_id = '{$passagerid}'"; + $query = $this->INFO->query($sql); + } + + //添加订单 + function add_orders($data){ + $sql=" + INSERT INTO trainsystem( + ts_cold_sn, + ts_ordernumber, + ts_subtime, + ts_returncode, + ts_status, + ts_errormsg, + ts_fromstationame, + ts_fromstationcode, + ts_tostationame, + ts_tostationcode, + ts_startdate, + ts_startime, + ts_endtime, + ts_runtime, + ts_checi, + ts_channel, + ts_isauto + ) + VALUES( + '{$data->cold_sn}', + '{$data->ordernumber}', + getdate(), + '{$data->returncode}', + '{$data->status}', + '{$data->errormsg}', + '{$data->fromstationame}', + '{$data->fromstationcode}', + '{$data->tostationame}', + '{$data->tostationcode}', + '{$data->startdate}', + '{$data->startime}', + '{$data->endtime}', + '{$data->runtime}', + '{$data->checi}', + '{$data->channel}', + '{$data->isauto}' + ) + "; + //echo $sql; + $query = $this->INFO->query($sql); + } + + public function ticketfrom($ts_ordernumber){ + $sql = "select ts_channel,ts_cold_sn,ts_ordernumber from trainsystem where ts_ordernumber = ?"; + $query = $this->INFO->query($sql,array($ts_ordernumber)); + return $query->row(); + } + + public function get_passenger_info($ordernumber,$passportname,$passportno){ + $sql = "select * from trainsystem_tickets left join trainsystem on tst_ordernumber = ts_ordernumber where tst_realname = ? and tst_numberid = ? and tst_ordernumber = ?"; + $query = $this->INFO->query($sql,array($passportname,$passportno,$ordernumber)); + return $query->row(); + } + + function add_passagers($data){ + $sql = "IF EXISTS (select * from trainsystem_tickets where tst_ordernumber = '{$data->ordernumber}' and tst_numberid = '{$data->numberid}') + update + trainsystem_tickets + set + tst_identitytype = '{$data->identitytype}', + tst_numberid = '{$data->numberid}', + tst_ticketype = '{$data->ticketype}', + tst_ticketprice = '{$data->ticketprice}', + tst_seatstype = '{$data->seatype}', + tst_seatdetail = '{$data->seatdetail}', + tst_status = '{$data->status}' + where + tst_ordernumber = '{$data->ordernumber}' + and + tst_numberid = '{$data->numberid}' + else + INSERT INTO trainsystem_tickets ( + tst_ordernumber, + tst_status, + tst_realname, + tst_identitytype, + tst_numberid, + tst_ticketype, + tst_ticketprice, + tst_seatstype, + tst_seatdetail + )VALUES( + '{$data->ordernumber}', + '{$data->status}', + '{$data->realname}', + '{$data->identitytype}', + '{$data->numberid}', + '{$data->ticketype}', + '{$data->ticketprice}', + '{$data->seatype}', + '{$data->seatdetail}' + ) + "; + $query =$this->INFO->query($sql); + } + + public function update_orders($data){ + $where = ''; + if(!empty($data->bookcallback)){ + $where .= " + ts_seatsinfo = '{$data->seatsinfo}', + ts_checkdoor = '{$data->TicketCheck}', + ts_elecnumber = '{$data->ElectronicOrderNumber}', + ts_orderamount = '{$data->OrderTotleFee}', + ts_bookcallback = '{$data->bookcallback}',"; + }else if(!empty($data->confirmcallback)){ + $where .= "ts_confirmcallback = '{$data->confirmcallback}',"; + }else if(!empty($data->returncallback)){ + $where .= "ts_returncallback = '{$data->returncallback}',"; + }else if(!empty($data->reschedulecallback)){ + $where .= "ts_reschedulecallback = '{$data->reschedulecallback}',"; + } + $sql =" + update trainsystem + set + ts_status = '{$data->OrderStatus}', + ts_errormsg = '{$data->ErrorMsg}', + ".substr($where,0,strlen($where)-1)." + where + ts_ordernumber = '{$data->ordernumber}' + "; + //echo $sql;die(); + $query = $this->INFO->query($sql); + } + + //更新乘客表信息 + public function update_passpager_info($data){ + $sql = "update + trainsystem_tickets + set + tst_status = '{$data->status}', + tst_returncallback = '{$data->returncallback}', + tst_lasteditdate = getdate() + where + tst_ordernumber = '{$data->ordernumber}' + and + tst_realname = '{$data->realname}' + and + tst_numberid = '{$data->numberid}' + "; + $query = $this->INFO->query($sql); + } + + public function get_tickets_info($cold_sn){ + $sql = "select ts_cold_sn,ts_ordernumber,tst_realname,tst_numberid,tst_status from trainsystem left join trainsystem_tickets on ts_ordernumber = tst_ordernumber where ts_cold_sn = ? and ts_status = '4'"; + $query = $this->INFO->query($sql,array($cold_sn)); + //$sql = "select * from BIZ_JuheOrderList where JOL_COLD_SN = ? and jol_status = '4'"; + //$query = $this->HT->query($sql,array($cold_sn)); + return $query->result(); + } + + public function getallorders(){ + $sql = "select * from Tourmanager.dbo.BIZ_JuheOrderList where JOL_SubTime > '2019-03-01' and (JOL_Status = '4' or JOL_Status = '7')"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function update_juheorder($ordernumber,$subtime,$price){ + $sql = "update trainsystem set ts_subtime = ? , ts_orderamount = ? where ts_ordernumber = ?"; + $query = $this->INFO->query($sql,array($subtime,$price,$ordernumber)); + } + + //根据cold_sn 获取出票情况 + public function get_ticketinfos($cold_sn){ + $sql = "select * from trainsystem where ts_cold_sn = ? and ts_status = '4'"; + $query = $this->INFO->query($sql,array($cold_sn)); + return $query->row(); + } + + + public function test(){ + $sql = "delete from trainsystem where ts_cold_sn = '488121613_1552637689'"; + $query = $this->INFO->query($sql); + } +} \ No newline at end of file diff --git a/application/third_party/trainsystem/views/addorders.php b/application/third_party/trainsystem/views/addorders.php new file mode 100644 index 00000000..e69de29b diff --git a/application/third_party/trainsystem/views/common/footer.php b/application/third_party/trainsystem/views/common/footer.php new file mode 100644 index 00000000..b231b902 --- /dev/null +++ b/application/third_party/trainsystem/views/common/footer.php @@ -0,0 +1,43 @@ +<?php // 代码各服务器已经同步 2016.06.01 ycc ?> +<div class="container-fluid footer"> + <div class="row"> + <div class="col-xs-5"></div> + <div class="col-xs-17"> + <legend></legend> + <p class="muted pull-right"><strong>{elapsed_time}</strong> seconds , <strong>{memory_usage}</strong> memory ,技术支持:YCC 08987705</p> + </div> + <div class="col-xs-2"></div> + </div> +</div> + +<!-- 静态化更新窗口 --> +<div class="modal fade" id="cache_refresh_modal" tabindex="-1" role="dialog" data-backdrop="false"> + <div class="modal-dialog" role="document"> + <div class="modal-content" > + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> + <h3 style="margin:0;">静态化更新-系列站专用</h3> + </div> + <div class="modal-body"> + <label>需要更新的页面</label> + <input type="text" class="form-control" name="static_html_url" id="static_html_url" placeholder="如:http://www.voyageschine.com/shanghai-voyage/" /> + <input type="hidden" name="updatecdn_byhand" id="updatecdn_byhand" value=""> + <p class="text-danger" id="cache_refresh_modal_msg" name="cache_refresh_modal_msg"></p> + + </div> + <div class="modal-footer"> + <button class="btn" data-dismiss="modal">关闭</button> + <a class="btn btn-primary" href="javascript:void(0);" onclick="$('#updatecdn_byhand').val('1'); + updateCache($('#static_html_url').val(), 'cache_refresh_modal_msg');" >更新</a> + </div> + </div> + </div> +</div> +<!-- 静态化更新窗口 --> + + + + + +</body> +</html> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/common/header.php b/application/third_party/trainsystem/views/common/header.php new file mode 100644 index 00000000..57025d13 --- /dev/null +++ b/application/third_party/trainsystem/views/common/header.php @@ -0,0 +1,131 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>出票系统</title> + <link rel="stylesheet" href="/css/information-system3.css?v=201508112" type="text/css" /> + <script type="text/javascript" src="/min/?f=/js/information-system3.min.js,/js/common.js"></script> + <link rel="shortcut icon" href="/bootstrap/img/glyphicons_290_skull.png"> + </head> + + <body> + <nav class="navbar navbar-inverse"> + <div class="container-fluid"> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="/"><span class="glyphicon glyphicon-home text-white"></span></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url(''); ?>">信息管理</a></li> + <li><a href="<?php echo site_url('product') ?>">产品管理</a></li> + <li><a href="<?php echo site_url('author'); ?>">作者平台</a></li> + <li><a href="<?php echo site_url('keyworlds') ?>">关键词</a></li> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + 更多<b class="caret"></b> + </a> + <ul class="dropdown-menu"> + <li><a href="<?php echo site_url('seo') ?>">SEO管理</a></li> + <li> <a href="<?php echo site_url('thirdparty/public/infopayauthor') ?>">打赏统计</a></li> + <li> <a href="<?php echo site_url('thirdparty/form') ?>">表单管理</a></li> + <li><a href="<?php echo site_url('thirdparty/advertise') ?>">广告管理</a></li> + <li><a href="<?php echo site_url('setting') ?>">系统设置</a></li> + </ul> + </li> + </ul> + <form id="form_information_search" name="form_information_search" method="post" action="<?php echo $this->router->class == 'infoshare' ? site_url('infoshare/search/') : site_url('welcome/search/'); ?>" class="navbar-form navbar-left" > + <div class="input-group"> + <span class="input-group-addon"> + <input type="checkbox" title="全文搜索" name="all_text_search" id="all_text_search" value="true" > + </span> + <input type="text" class="form-control input-sm" name="keywords" id="keywords" value="<?php echo isset($keywords) ? $keywords : false; ?>" style="min-width:450px;"> + + <span class="input-group-btn"> + <button class="btn btn-default btn-sm" type="submit">搜索</button> + <a href="#" onclick="openKCFinder_fast();" class="btn btn-default btn-sm" title="快速上传图片" ><span class="glyphicon glyphicon-picture"></span></a> + <a href="#" title="静态化更新" class="btn btn-default btn-sm" data-toggle="modal" data-target="#cache_refresh_modal" ><span class="glyphicon glyphicon-repeat"></span></a> + </span> + </div> + </form> + <ul class="nav navbar-nav navbar-right"> + <?php + $all_unread_sms = get_all_unread_sms(); + $info_unread_sms = get_all_unread_sms('info'); + if (isset($information->ic_id)) + $current_msg = $information->ic_id; + if (isset($task->t_id)) + $current_msg = $task->t_id; + $total_count = $all_unread_sms['sms_count'] + $info_unread_sms['sms_count']; //计算未读消息总数 + $unread_sms_ic_id = 0; //用于设置所有收录消息为已读 + if ($total_count != 0) { + ?> + <!-- 如果当前页面存在未读消息,则消息数减一 --> + <?php + if (isset($current_msg) && isset($all_unread_sms['sms'][$current_msg])) { + $total_count = $total_count - count($all_unread_sms['sms'][$current_msg]); + unset($all_unread_sms['sms'][$current_msg]); + } + ?> + <?php + if (isset($current_msg) && isset($info_unread_sms['sms'][$current_msg])) { + $total_count = $total_count - count($info_unread_sms['sms'][$current_msg]); + unset($info_unread_sms['sms'][$current_msg]); + } + ?> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + <i class="icon-envelope icon-white pull-left" style="margin-top:3px;"></i> <span class="badge badge-important pull-right"><?php echo $total_count; ?></span> + </a> + <ul class="dropdown-menu"> + <!-- 信息平台的消息 --> + <?php if (isset($info_unread_sms['sms']) && !empty($info_unread_sms['sms'])) { ?> + <a style="padding-left:20px;" href="javascript:void(0);" onclick="set_allmsg_to_read($('#unreadinfomsg').val());">标记全部收录信息为已读</a> + <li class="divider"></li> + <?php foreach ($info_unread_sms['sms'] as $m) { ?> + <li><a href="<?php echo site_url('information/edit/' . $m[0]->is_id); ?>"><?php + $t_title = get_text_short($m[0]->t_title, 15); + echo '[' . $m[0]->ic_sitecode . '] ' . $t_title['content'] . ' (' . $m[0]->m_content . ')'; + ?></a></li> + <?php $unread_sms_ic_id.=',' . $m[0]->m_object_id; ?> + <?php } ?> + <li class="divider"></li> + <input type="hidden" name="unreadinfomsg" id="unreadinfomsg" value="<?php echo $unread_sms_ic_id; ?>"> + <?php } ?> + <!--作者平台的消息--> + <?php foreach ($all_unread_sms['sms'] as $am) { ?> + <li><a href="<?php echo site_url('author/edit_task/' . $am[0]->m_object_id); ?>"><?php + $t_title = get_text_short($am[0]->t_title, 15); + echo $t_title['content'] . ' (' . count($am) . ')'; + ?></a></li> + <?php } ?> + </ul> + </li> + <?php } ?> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + <?php + echo $this->config->item('site_code'); + echo ' -'; + $admin_info = $this->session->userdata('session_admin'); + echo $admin_info['OPI_Name']; + ?> + <b class="caret"></b> + </a> + <ul class="dropdown-menu"> + <?php foreach ($this->config->item('site') as $site_item) { ?> + <li> <a href="<?php echo site_url('login/change_site/' . $site_item['site_code']); ?>" ><?php echo $site_item['site_code'] ?></a></li> + <?php } ?> + <li><a href="<?php echo site_url('login/out'); ?>" >退出</a></li> + </ul> + </li> + </ul> + </div> + </div> + </nav> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/email.php b/application/third_party/trainsystem/views/email.php new file mode 100644 index 00000000..1fe9c49e --- /dev/null +++ b/application/third_party/trainsystem/views/email.php @@ -0,0 +1,33 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>China train ticket(s) confirmed, Booking Number <?php echo $coli_id;?></title><style>*{ font-family:Verdana, Geneva, sans-serif; color:#545454;}</style></head><body style="font-family:Verdana, Geneva, sans-serif; border-left:1px solid #d1d1d1; border-right:1px solid #d1d1d1;"><h1 style="font-size:20px; text-align:center;">China Highlights Booking Confirmation</h1><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Dear <?php echo $toname?>,</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Thank you for your payment of US$<?php echo $price->GAI_SQJE?> . The train tickets have already been issued. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> You can collect the paper ticket(s) from now on at any train station in mainland China.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><strong>Please note:</strong></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">1.Please present the <strong>original passport(s) of all the passenger(s)</strong> and the ticket pick-up number(s) <span style="color:#33F"><?php echo $ordernumber;?></span> at ticket collection counters. The counter will then issue your paper train ticket(s). </p> +<p>See the <a style="color:#33F" href="https://www.chinahighlights.com/travelguide/transportation/how-to-board-train.htm">video</a> about how to collect the ticket(s) in China. +</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please double check the train(s) information and passport information. Let us know AT ONCE if you see any mistakes below. We can try to cancel tickets to minimize your loss. A 20% cancellation fee is charged by China Railway.</p><table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;width: 293px;">Ticket collection sentences</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p>The bilingual note below might help you pick up tickets at the ticket collection counter more easily.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 1.Please show me which window for picking up the train ticket. 你好,请问哪个是取票窗?</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please issue the paper tickets for me. The following is the pick up number(s).请帮我出票,电子取票号如下.</p></td></tr></table> +<?php + $j = 0; + foreach($train_info as $item){ + echo '<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"> + <tr> + <th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Pick up number</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><span style="color:#33F">'.$item->FOI_TrainNetOrderNo.'</span></td>'; + echo '</tr><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Train No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->FlightsNo.'</td></tr><tr>'; + echo '<th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Departure</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->DepartureTime.' '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Arrival</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->ArrivalTime.' '.$item->ArrivalCity.' Station(in Chinese '.$item->ArrivalAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Class</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->Cabin.' ('.$seatinfo.')</td></tr></table>'; + } +?> +<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;">Passenger(s)</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p><?php + if($adult>0){echo $adult.' adult(s) ';} + if($chlid>0){echo $chlid.' chlid(s) ';} + if($baby>0){echo $baby.' baby(s) ';} + ?></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> <?php + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + ?></p></td></tr></table> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 3.On your departure day, please time your arrival at the station wisely. If you are going to collect your train ticket(s) on the departure day, allow enough time waiting in the queue of the ticket collection counter, for the security x-ray check of your luggage, and for the ticket check before entering the passenger lounge. Tickets will stop being issued 30 minutes prior to departure. We suggest you be at the station at least 1.5 hours ahead of the stated departure time. Please leave at least 2.5 hours during public holidays.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 4.If you’ve already collected your ticket before the departure day, we recommend that you be at the station at least 40 minutes ahead of time. Please be at the station at least 1.5 hours during a public holiday. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 5.Please don't throw your ticket(s) away because you'll need it to exit the station.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">6.If you cancel the ticket(s) at a train station yourself, the money will be refunded to our account. Please cancel the tickets before the train departure. And email us then we will refund you accordingly.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">7.<a style="color:#33F" href="https://www.chinahighlights.com/china-trains/booking-policy.htm">China Highlights train ticket booking policy </a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Should you have any questions about your train ticket bookings, please do not hesitate to contact me.</p> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Best Regards!</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><?php echo $operator[0]->Name?>, Travel Advisor</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Tel: <?php echo $operator[0]->tel;?> Mobile: <?php echo $operator[0]->Mobile;?> </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Fax: 86-773-2827424, 86-773-2885308 </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> E-mail: <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?>;</a><a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?>;</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">WeChat: CH_train<p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><a href="http://www.chinahighlights.com">www.chinahighlights.com</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> If you wish to share anything with my supervisor (Ms. ethel), please feel free to send your email to <a href="mailto:ethel@chinahighlights.net">ethel@chinahighlights.net</a>.</p></body></html> diff --git a/application/third_party/trainsystem/views/email_before.php b/application/third_party/trainsystem/views/email_before.php new file mode 100644 index 00000000..2a077a6c --- /dev/null +++ b/application/third_party/trainsystem/views/email_before.php @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>China Highlights Booking Confirmation</title><style>*{ font-family:Verdana, Geneva, sans-serif; color:#545454;}</style></head><body style="font-family:Verdana, Geneva, sans-serif; border-left:1px solid #d1d1d1; border-right:1px solid #d1d1d1;"><h1 style="font-size:20px; text-align:center;">China Highlights Booking Confirmation</h1><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Dear <?php echo $toname?>,</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Thanks for payment US$<?php echo $price->GAI_SQJE?> . The train tickets have already been issued. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> You can collect the paper ticket(s) from now at any train station in mainland China.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> The same passport that was used for booking should also be used for ticket collection. A renewed passport won't be acceptable even if the holder is the same person. The system does not allow us to change passport number or passenger name after issue ticket. Have to issue new ticket if wrong passport number or name.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Please collect your paper tickets from a ticket counter in the train station. Tickets will stop being printed 30 minutes prior to departure. On departure day, please time your arrival wisely. If you are going to collect your tickets on departure day, allow for time waiting in queue at the ticket-counter, for security checks and for ticket checks. We suggest you be at the station at least 1.5 hours ahead of the stated departure time.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">If you’ve already collected before the departure day, it is also wise to be at the station at least 40 minutes ahead. </p><table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;">Passenger(s)</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p><?php + if($adult>0){echo $adult.' adult(s) ';} + if($chlid>0){echo $chlid.' chlid(s) ';} + if($baby>0){echo $baby.' baby(s) ';} + ?></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> <?php + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + ?></p></td></tr></table> +<?php + $j = 0; + foreach($train_info as $item){ + echo '<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Train'.++$j.':</p>'; + echo '<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"> + <tr> + <th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Ticket Pick Up No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><span style="color:#33F">'.$item->FOI_TrainNetOrderNo.'</span></td>'; + echo '</tr><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Train No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->FlightsNo.'</td></tr><tr>'; + echo '<th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Departure</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->DepartureTime.' '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Arrival</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->ArrivalTime.' '.$item->ArrivalCity.' Station(in Chinese '.$item->ArrivalAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Class</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->Cabin.'</td></tr></table>'; + } +?> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Kindly note below:</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">1.Please present all passenger(s) original passport(s) and Ticket Pick Up No.<span style="color:#33F"><?php echo $item->FOI_TrainNetOrderNo?></span>at any ticket counters of any railway stations. They will then issue your paper train ticket(s). You can find more instruction of collecting tickets enclosure. +</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 2.You can show screenshot of the paper tickets to the railway station counter. It helps get paper tickets easily.</p> +<?php + foreach($train_info as $obj){ + echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">'; + echo '<tr style="background:#f0f0f0; color:#545454; font-weight:100; font-size:20px; ">'; + echo ' <th style="font-weight:100; font-size:18px; text-align:left;padding:8px 10px; border-top:3px solid #ad1818;">'.substr($obj->DepartureDate,0,10).'&nbsp;&nbsp;&nbsp;'.$obj->FlightsNo.'&nbsp;&nbsp;&nbsp;'.$obj->FOI_TrainNetOrderNo.'</th></tr><tr>'; + echo '<td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;"><p>'.$obj->DepartAirport_cn.'('.$obj->DepartureCity.')<span style=" font-size:12px;">'.$obj->DepartureTime.'</span> To '.$obj->ArrivalAirport_cn.'('.$obj->ArrivalCity.')<span style=" font-size:12px;">'.$obj->ArrivalTime.'</span></p></td></tr>'; + foreach($juhe_info->passengers as $people){ + echo '<tr><td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;">'; + echo '<p>'.$people->passengersename.'('.$people->piaotypename.') '; + echo $people->cxin.' 票价:¥'.$people->price.'</p>'; + echo '</td></tr>'; + } + echo '<tr><td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;"><p>出票成功</p></td></tr></table>'; + } +?> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 3. There is no further fee if collect train ticket(s) at the DEPARTURE station shown on your ticket(s). RMB 5 per ticket will be charged at the ticket counter at other stations. Return tickets are treated separately. E.g. if you have booked Beijing-Shanghai and Shanghai-Beijing ticket(s), and you collect them all at Beijing, you will be charged RMB 5 per ticket for the Shanghai-Beijing ticket(s), but if you pick up the return leg ticket(s) separately in Shanghai you will avoid the charge.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 4. Please keep your ticket(s) and don't throw your ticket(s) away once you've boarded your train, you'll need it to exit the station.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 5.Download railway station instructions, maps and tips at <a href="https://www.chinahighlights.com/china-trains/station-map.htm">https://www.chinahighlights.com/china-trains/station-map.htm</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">6.Terms & Conditions. <a href="https://www.chinahighlights.com/china-trains/booking-policy.htm">https://www.chinahighlights.com/china-trains/booking-policy.htm</a></p><p>&nbsp;</p> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Best Regards!</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><?php echo $operator[0]->Name?>, Travel Advisor</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Tel: <?php echo $operator[0]->tel;?> Mobile: <?php echo $operator[0]->Mobile;?> </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Fax: 86-773-2827424, 86-773-2885308 </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> E-mail: <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?>;</a><a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?>;</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><a href="http://www.chinahighlights.com">www.chinahighlights.com</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> If you wish to share anything with my supervisor (Ms. Alex Yang), please feel free to send your email to <a href="mailto:alex@chinahighlights.net">alex@chinahighlights.net</a>.</p></body></html> diff --git a/application/third_party/trainsystem/views/email_fault.php b/application/third_party/trainsystem/views/email_fault.php new file mode 100644 index 00000000..a059912b --- /dev/null +++ b/application/third_party/trainsystem/views/email_fault.php @@ -0,0 +1,26 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Dear <?php echo $toname?>,</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;"> Thank you for your booking (order number <?php echo $coli_id?>), we have received your payment of USD<?php echo $price->GAI_SQJE?>.&nbsp;</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;"> Due to the heavy traffic flow of data, the system failed to automatically issue your ticket(s).</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Your travel advisor will purchase your train ticket(s) manually. &nbsp;You will receive an email within half a working day (Our time now:&nbsp;<strong><?php echo date('H:i').' '.date('a');?></strong>, <?php echo date('D');?>,<?php echo date('F').' '.date('d').','.date('Y');?> GMT+8).Should you have any questions or concerns with regards to your train booking, please do not hesitate to contact me at <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?></a>;<a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?></a> or telephone <?php echo $operator[0]->tel;?>. </p> +<?php foreach($train_info as $item){ + echo '<table border="0" cellspacing="0" cellpadding="0" width="60%">'; + echo '<tr><th width="17%" style="font-family:Verdana, Geneva, sans-serif;font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Train No. </th>'; + echo '<td width="83%" style="font-family:Verdana, Geneva, sans-serif;font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->FlightsNo.'</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Departure </th>'; + echo '<td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->DepartureTime.', '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)&nbsp;</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Arrival </th><td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->ArrivalTime.', '.$item->ArrivalCity.'(in Chinese'. $item->ArrivalAirport_cn.'火车站)&nbsp; </td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Class </th><td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->Cabin.'</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Passenger(s) </th>'; + echo '<td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'; + if($adult>0){echo $adult.' adult(s)<br/> ';} + if($chlid>0){echo $chlid.' chlid(s)<br/> ';} + if($baby>0){echo $baby.' baby(s)<br/> ';} + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + echo '</tr></table>'; + echo '<p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Regards <br />'; + echo $operator[0]->Name.'<br/>Travel Advisor<br/>'; + echo 'Telephone:&nbsp;(Office)'.$operator[0]->tel.', M: '.$operator[0]->Mobile.','; + echo 'Email: <a href="mailto:'.$emailarr[0].'">'.$emailarr[0].'</a>;<a href="mailto:'.$emailarr[1].'">'.$emailarr[1].'</a>;&nbsp</p>'; + }?> +</body> +</html> diff --git a/application/third_party/trainsystem/views/export.php b/application/third_party/trainsystem/views/export.php new file mode 100644 index 00000000..1da65ee6 --- /dev/null +++ b/application/third_party/trainsystem/views/export.php @@ -0,0 +1,110 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">交易记录导出&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/ht_order_list');?>">订单列表>></a> </h3> + </div> + <div class="panel-body"> + <form style="width: 80%;" action="http://www.mycht.cn/info.php/apps/trainsystem/api/export_excel/" method="post"> + <input type="text" name="from_date" class="date" value="<?php echo empty($from_date)?"":$from_date;?>" autocomplete="off">至 + <input type="text" name="to_date" class="date" value="<?php echo empty($to_date)?"":$to_date;?>" autocomplete="off"> + 审核状态:<input type="checkbox" <?php echo empty($examine)?"":"checked";?> name="examine" />&nbsp;&nbsp;&nbsp; + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> Download</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;"> + <!-- <table class="table table-hover" > + <thead> + <tr><th>时间</th><th>信息</th><th>变化值</th><th>团名</th><th>外联</th></tr> + </thead> + <tbody> + + <tr data-id="161130252" title="Popover title" data-container="body" data-toggle="popover" data-placement="top" data-content="顶部的 Popover 中的一些内容"> + <td>2016-12-01 11:18:28</td> + <td> 票款(有充值)</td> + <td>-1106.00</td> + <td>R161228-BYW161130252</td> + <td>李毅文</td> + </tr> + + </tbody> + </table> --> + <div class="row <?php echo empty($examine)?"hidden":"";?>" style="width:90%;margin:0 auto;"> + <div class=""> + <table class="table table-hover" id="list_table"> + <thead> + <tr><th>时间</th><th>信息</th><th>变化值</th><th>团名</th><th>外联</th></tr> + </thead> + <tbody> + + <?php foreach ($data as $key => $value) {?> + <tr data-id="<?php echo $value[8];?>" title="Popover title" data-container="body" data-toggle="popover" data-placement="top" data-content="顶部的 Popover 中的一些内容"> + <td><?php echo $value[2];?></td><td><?php echo $value[3];?></td><td><?php echo $value[1];?></td><td><?php echo $value[6];?></td><td><?php echo $value[7];?></td> + </tr> + <?php }?> + + </tbody> + </table> + </div> + </div> + </div> + </div> + +</div> +<div class="popover fade top in" role="tooltip" id="popover" style="width:auto;max-width: 100% !important;top: 139.6px; left: 50%; display: none;"> + <div class="arrow"></div> + <h3 class="popover-title">我的支付</h3> + <div class="popover-content"> + <table class="table" id="my_pay_data"> + <thead> + <tr> + <td>序号</td><td>车次</td><td>出发日期</td><td>价格</td><td>备注</td> + </tr> + </thead> + <tbody> + + </tbody> + </table> + </div> +</div> +<script> + + $(".date").datepicker({ + 'format': 'yyyy-m-d', + 'autoclose': true + }); + $("body").click(function(){ + $("#popover").css("display","none"); + }); + $("#popover").click(function(e){ + e.stopPropagation();//阻止事件冒泡,防止点击这个div也被隐藏 + }); + var popover_top=0; + var tr=""; + $("#list_table>tbody>tr").click(function(e){ + e.stopPropagation(); + popover_top=$(this).offset().top-$("#popover").height(); + var this_id=$(this).attr("data-id"); + var THIS=$(this); + url="<?php echo site_url('apps/train/index/get_ht_my_pay?').'id=';?>"+this_id; + $.ajax({ + url:url, + beforeSend:function(data){ + + // $("#popover").css("top",popover_top); + // $("#popover").css("display","block"); + }, + success:function(data){ + tr=""; + if(data.status==1){ + $.each(data.datas,function(n,value){ + tr+="<tr><td>"+(n+1)+"</td><td>"+value["TOC_TrainNumber"]+"</td><td>"+value["TOC_DepartureDate"]+"</td><td>"+value["TOC_TicketCost"]+"</td><td>"+value["TOC_Memo"]+"</td></tr>"; + }); + } + $("#my_pay_data>tbody").html(tr); + popover_top=THIS.offset().top-$("#popover").height(); + $("#popover").css("top",popover_top); + $("#popover").css("display","block"); + }, + dataType: "json", + }); + }); +</script> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/footer.php b/application/third_party/trainsystem/views/footer.php new file mode 100644 index 00000000..b231b902 --- /dev/null +++ b/application/third_party/trainsystem/views/footer.php @@ -0,0 +1,43 @@ +<?php // 代码各服务器已经同步 2016.06.01 ycc ?> +<div class="container-fluid footer"> + <div class="row"> + <div class="col-xs-5"></div> + <div class="col-xs-17"> + <legend></legend> + <p class="muted pull-right"><strong>{elapsed_time}</strong> seconds , <strong>{memory_usage}</strong> memory ,技术支持:YCC 08987705</p> + </div> + <div class="col-xs-2"></div> + </div> +</div> + +<!-- 静态化更新窗口 --> +<div class="modal fade" id="cache_refresh_modal" tabindex="-1" role="dialog" data-backdrop="false"> + <div class="modal-dialog" role="document"> + <div class="modal-content" > + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> + <h3 style="margin:0;">静态化更新-系列站专用</h3> + </div> + <div class="modal-body"> + <label>需要更新的页面</label> + <input type="text" class="form-control" name="static_html_url" id="static_html_url" placeholder="如:http://www.voyageschine.com/shanghai-voyage/" /> + <input type="hidden" name="updatecdn_byhand" id="updatecdn_byhand" value=""> + <p class="text-danger" id="cache_refresh_modal_msg" name="cache_refresh_modal_msg"></p> + + </div> + <div class="modal-footer"> + <button class="btn" data-dismiss="modal">关闭</button> + <a class="btn btn-primary" href="javascript:void(0);" onclick="$('#updatecdn_byhand').val('1'); + updateCache($('#static_html_url').val(), 'cache_refresh_modal_msg');" >更新</a> + </div> + </div> + </div> +</div> +<!-- 静态化更新窗口 --> + + + + + +</body> +</html> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/header.php b/application/third_party/trainsystem/views/header.php new file mode 100644 index 00000000..42e3dff2 --- /dev/null +++ b/application/third_party/trainsystem/views/header.php @@ -0,0 +1,156 @@ +<?php // 代码各服务器已经同步 2016.06.01 ycc ?> +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>信息平台</title> + <link rel="stylesheet" href="/css/information-system3.css?v=201508112" type="text/css" /> + <script type="text/javascript" src="/min/?f=/js/information-system3.min.js,/js/common.js"></script> + <script type="text/javascript" src="/js/kindeditor/kindeditor.js?v=20160601"></script> + <link rel="shortcut icon" href="/bootstrap/img/glyphicons_290_skull.png"> + <script language="javascript"> + //快速图片上传 + function openKCFinder_fast() { + window.CallBack = oopenKCFinder_fast_callback; + window.open('/media/popselectpicture.php?site_code=<?php echo $this->config->item('site_code'); ?>&site_lgc=<?php echo $this->config->item('site_lgc'); ?>', 'kcfinder_textbox', 'status=0, toolbar=0, location=0, menubar=0, directories=0,resizable=1, scrollbars=0, width=800, height=600'); + } + + function oopenKCFinder_fast_callback(result) { + var site_image_url = '<?php echo $this->config->item('site_image_url') ?>'; + if (result != null && result.Pinfo[0]) { + $.modaldialog.success("图片地址:<br/>" + site_image_url + result.Pinfo[0].PUrl); + } + } + //标识所有信息未已读 + function set_allmsg_to_read(ic_ids) { + var url = '<?php echo site_url("author/set_msg_to_read"); ?>'; + $.post(url, {'msg_ids': ic_ids}, function(result) { + window.location.href = window.location.href; + }); + } + </script> + </head> + + <body> + + + <nav class="navbar navbar-inverse"> + <div class="container-fluid"> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-9" aria-expanded="false"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="/"><span class="glyphicon glyphicon-home text-white"></span></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url(''); ?>">信息管理</a></li> + <li><a href="<?php echo site_url('product') ?>">产品管理</a></li> + <li><a href="<?php echo site_url('author'); ?>">作者平台</a></li> + <li><a href="<?php echo site_url('keyworlds') ?>">关键词</a></li> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + 更多<b class="caret"></b> + </a> + <ul class="dropdown-menu"> + <li><a href="<?php echo site_url('seo') ?>">SEO管理</a></li> + <li> <a href="<?php echo site_url('thirdparty/public/infopayauthor') ?>">打赏统计</a></li> + <li> <a href="<?php echo site_url('thirdparty/form') ?>">表单管理</a></li> + <li><a href="<?php echo site_url('thirdparty/advertise') ?>">广告管理</a></li> + <li><a href="<?php echo site_url('setting') ?>">系统设置</a></li> + </ul> + </li> + </ul> + <form id="form_information_search" name="form_information_search" method="post" action="<?php echo $this->router->class == 'infoshare' ? site_url('infoshare/search/') : site_url('welcome/search/'); ?>" class="navbar-form navbar-left" > + <div class="input-group"> + <span class="input-group-addon"> + <input type="checkbox" title="全文搜索" name="all_text_search" id="all_text_search" value="true" > + </span> + <input type="text" class="form-control input-sm" name="keywords" id="keywords" value="<?php echo isset($keywords) ? $keywords : false; ?>" style="min-width:450px;"> + + <span class="input-group-btn"> + <button class="btn btn-default btn-sm" type="submit">搜索</button> + <a href="#" onclick="openKCFinder_fast();" class="btn btn-default btn-sm" title="快速上传图片" ><span class="glyphicon glyphicon-picture"></span></a> + <a href="#" title="静态化更新" class="btn btn-default btn-sm" data-toggle="modal" data-target="#cache_refresh_modal" ><span class="glyphicon glyphicon-repeat"></span></a> + </span> + </div> + </form> + <ul class="nav navbar-nav navbar-right"> + <?php + $all_unread_sms = get_all_unread_sms(); + $info_unread_sms = get_all_unread_sms('info'); + if (isset($information->ic_id)) + $current_msg = $information->ic_id; + if (isset($task->t_id)) + $current_msg = $task->t_id; + $total_count = $all_unread_sms['sms_count'] + $info_unread_sms['sms_count']; //计算未读消息总数 + $unread_sms_ic_id = 0; //用于设置所有收录消息为已读 + if ($total_count != 0) { + ?> + <!-- 如果当前页面存在未读消息,则消息数减一 --> + <?php + if (isset($current_msg) && isset($all_unread_sms['sms'][$current_msg])) { + $total_count = $total_count - count($all_unread_sms['sms'][$current_msg]); + unset($all_unread_sms['sms'][$current_msg]); + } + ?> + <?php + if (isset($current_msg) && isset($info_unread_sms['sms'][$current_msg])) { + $total_count = $total_count - count($info_unread_sms['sms'][$current_msg]); + unset($info_unread_sms['sms'][$current_msg]); + } + ?> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + <i class="icon-envelope icon-white pull-left" style="margin-top:3px;"></i> <span class="badge badge-important pull-right"><?php echo $total_count; ?></span> + </a> + <ul class="dropdown-menu"> + <!-- 信息平台的消息 --> + <?php if (isset($info_unread_sms['sms']) && !empty($info_unread_sms['sms'])) { ?> + <a style="padding-left:20px;" href="javascript:void(0);" onclick="set_allmsg_to_read($('#unreadinfomsg').val());">标记全部收录信息为已读</a> + <li class="divider"></li> + <?php foreach ($info_unread_sms['sms'] as $m) { ?> + <li><a href="<?php echo site_url('information/edit/' . $m[0]->is_id); ?>"><?php + $t_title = get_text_short($m[0]->t_title, 15); + echo '[' . $m[0]->ic_sitecode . '] ' . $t_title['content'] . ' (' . $m[0]->m_content . ')'; + ?></a></li> + <?php $unread_sms_ic_id.=',' . $m[0]->m_object_id; ?> + <?php } ?> + <li class="divider"></li> + <input type="hidden" name="unreadinfomsg" id="unreadinfomsg" value="<?php echo $unread_sms_ic_id; ?>"> + <?php } ?> + <!--作者平台的消息--> + <?php foreach ($all_unread_sms['sms'] as $am) { ?> + <li><a href="<?php echo site_url('author/edit_task/' . $am[0]->m_object_id); ?>"><?php + $t_title = get_text_short($am[0]->t_title, 15); + echo $t_title['content'] . ' (' . count($am) . ')'; + ?></a></li> + <?php } ?> + </ul> + </li> + <?php } ?> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown"> + <?php + echo $this->config->item('site_code'); + echo ' -'; + $admin_info = $this->session->userdata('session_admin'); + echo $admin_info['OPI_Name']; + ?> + <b class="caret"></b> + </a> + <ul class="dropdown-menu"> + <?php foreach ($this->config->item('site') as $site_item) { ?> + <li> <a href="<?php echo site_url('login/change_site/' . $site_item['site_code']); ?>" ><?php echo $site_item['site_code'] ?></a></li> + <?php } ?> + <li><a href="<?php echo site_url('login/out'); ?>" >退出</a></li> + </ul> + </li> + </ul> + </div> + </div> + </nav> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/homepage.php b/application/third_party/trainsystem/views/homepage.php new file mode 100644 index 00000000..832859b3 --- /dev/null +++ b/application/third_party/trainsystem/views/homepage.php @@ -0,0 +1,511 @@ +<style> +.clear {clear: both;} +.train-summary{ font-size:12px; margin-bottom:10px;} +.train-summary span{ color:#9a0918;} +a:link.seat-a{background-image:url(/css/images/train/a-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-a{background-image:url(/css/images/train/a-seath.jpg);} +.selected_seat-a{background-image:url(/css/images/train/a-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-b{background-image:url(/css/images/train/b-seat.jpg); background-repeat:no-repeat; text-decoration:none; width:55px; display:block; height:42px; float:left;} +a:hover.seat-b{background-image:url(/css/images/train/b-seath.jpg);} +.selected_seat-b{background-image:url(/css/images/train/b-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-c{background-image:url(/css/images/train/c-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-c{background-image:url(/css/images/train/c-seath.jpg);} +.selected_seat-c{background-image:url(/css/images/train/c-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-d{background-image:url(/css/images/train/d-seat.jpg); background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:hover.seat-d{background-image:url(/css/images/train/d-seath.jpg);} +.selected_seat-d{background-image:url(/css/images/train/d-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.seat-f{background-image:url(/css/images/train/f-seat.jpg); background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:hover.seat-f{background-image:url(/css/images/train/f-seath.jpg);} +.selected_seat-f{background-image:url(/css/images/train/f-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.sleep-a {background-image:url(/css/images/train/l-up.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-a { background-image:url(/css/images/train/l-upa.jpg); } +.selected_sleep-a { background-image:url(/css/images/train/l-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-b {background-image:url(/css/images/train/r-up.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-b { background-image:url(/css/images/train/r-upa.jpg); } +.selected_sleep-b { background-image:url(/css/images/train/r-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-c {background-image:url(/css/images/train/l-mid.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-c { background-image:url(/css/images/train/l-mida.jpg); } +.selected_sleep-c { background-image:url(/css/images/train/l-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-d {background-image:url(/css/images/train/r-mid.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-d { background-image:url(/css/images/train/r-mida.jpg); } +.selected_sleep-d { background-image:url(/css/images/train/r-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-e {background-image:url(/css/images/train/l-low.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-e { background-image:url(/css/images/train/l-lowa.jpg); } +.selected_sleep-e { background-image:url(/css/images/train/l-lowa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-f {background-image:url(/css/images/train/r-low.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-f { background-image:url(/css/images/train/r-lowa.jpg); } +.selected_sleep-f { background-image:url(/css/images/train/r-lowa.jpg)!important; width:104px; display:block; height:38px; float:left; } +</style> +<script> +$(function(){ + //var selected = $('.selectticket').find('.selected').length; + //$('.selected_People').html(selected); +}); + +function selseat(seat){ + var type = $(seat).attr('type'); + var total = $(seat).parent().parent().find('.train-summary .seat_TotalPeople').html(); + if(total>=5){ + total = 5; + $('.seat_TotalPeople').html(total); + } + var count = $(seat).parent().parent().find('.selected').length; + console.log('执行之前的数量'+count); + //处理选座事件 + + if($(seat).hasClass('selected_'+type)){ + $(seat).removeClass('selected'); + $(seat).removeClass('selected_'+type); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('减掉之后'+count); + }else{ + if(count >= total){ + alert('You already chose seats for all the passengers.'); + }else{ + $(seat).addClass('selected_'+type); + $(seat).addClass('selected'); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('增加之后'+count); + } + + } + +} +</script> +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/trainsystem/pages/order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/trainsystem/pages/export');?>">导出交易记录>></a> <span style="margin-left:200px;">版本:V2.0</span><span class="pull-right">聚合余额(RMB):<?php echo $balance;?></span></h3> + </div> + <div class="panel-body"> + <form style="width: 300px;float: left;" action="http://www.mycht.cn/info.php/apps/trainsystem/pages/index/" method="post"> + <input type="text" name="ht_order" value="<?php echo isset($cols_id)?$cols_id:""; ?>"> + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 获取信息</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;">外联:<span><?php if(!empty($wl)){echo $wl[0]->OPI_Name;}?></span></p> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">火车订单信息</h3> + </div> + <div class="panel-body"> + <?php if(!empty($info)):?> + <?php $num=1; foreach($info as $v):?> + <table class="table table-bordered table-hover" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">座位</th> + <th style="text-align:center;">出发城市</th> + <th style="text-align:center;">抵达城市</th> + <th style="text-align:center;">发车日期</th> + <th style="text-align:center;">发车时间</th> + <th style="text-align:center;">抵达时间</th> + <th style="text-align:center;">票价</th> + <th style="text-align:center;">是否提交过</th> + </tr> + </thead> + <tbody> + + <tr> + <td><?php echo $num++;?></td> + <td><?php echo $v->train[0]->FlightsNo;?></td> + <td><?php echo $v->train[0]->Cabin;?></td> + <td><?php echo $v->train[0]->DepartureCity;?></td> + <td><?php echo $v->train[0]->ArrivalCity;?></td> + <td><?php echo $v->train[0]->DepartureDate;?></td> + <td><?php echo $v->train[0]->DepartureTime;?></td> + <td><?php echo $v->train[0]->ArrivalTime;?></td> + <td><?php echo $v->train[0]->adultcost;?></td> + <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> + <!--<td><button type="button" class="btn btn-success pay_api" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>" title="超过五个乘客不可用" >快捷订票</button></td>--> + </tr> + <tr> + <td colspan="11"> + <table class="table table-condensed table-bordered"> + <thead> + <tr> + <th style="text-align:center;"><input class="check_people" type="checkbox" /></th> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">姓名</th> + <th style="text-align:center;">护照</th> + <th style="text-align:center;">年龄类型</th> + </tr> + </thead> + <tbody> + <?php foreach($v->people as $key=>$p): ?> + <tr> + <?php if ($key < 5){?> + <td><input name="" type="checkbox" checked="checked" value="<?php echo $p->BPE_SN;?>" num="<?php echo $key;?>"/></td> + <?php }else{ ?> + <td><input name="" type="checkbox" value="<?php echo $p->BPE_SN;?>" /></td> + <?php } ?> + <td><?php echo $key+1;?></td> + <td class="people_name"><?php echo $p->BPE_FirstName." ".$p->BPE_MiddleName." ".$p->BPE_LastName;?></td> + <td><?php echo $p->BPE_Passport;?></td> + <td><?php echo $p->BPE_GuestType==1?"成人":($p->BPE_GuestType==2?"儿童":"婴儿");?></td> + </tr> + <?php endforeach;?> + <tr style="text-align:;"> + <td colspan="11" class="selectticket"> + <?php + $traintype = substr($v->train[0]->FlightsNo,0,1); + $arr = array('C','D','G'); + $sel_count = 0; + if(in_array($traintype,$arr)){ + $selectseat = ''; + $train_select = $v->train[0]->FOI_SelectedSeat; + $a1=$b1=$c1=$d1=$f1=$a2=$b2=$c2=$d2=$f2=false; + if($train_select){ + $obj = explode(',',$train_select); + foreach($obj as $value){ + switch($value){ + case '1A': + $a1 = true; + $sel_count++; + break; + case '1B': + $b1 = true; + $sel_count++; + break; + case '1C': + $c1 = true; + $sel_count++; + break; + case '1D': + $d1 = true; + $sel_count++; + break; + case '1F': + $f1 = true; + $sel_count++; + break; + case '2A': + $a2 = true; + $sel_count++; + break; + case '2B': + $b2 = true; + $sel_count++; + break; + case '2C': + $c2 = true; + $sel_count++; + break; + case '2D': + $d2 = true; + $sel_count++; + break; + case '2F': + $f2 = true; + $sel_count++; + break; + } + } + } + $html = ''; + $html .= '<div class="train-summary">'.$v->train[0]->Cabin.' for '.$v->train[0]->FlightsNo.' <span>(<span class="selected_People">'.$sel_count.'</span> of <span class="seat_TotalPeople">'.count($v->people).'</span> Seats)</span></div>'; + $html .= '<div class="seatPick">'; + if($a1){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b1){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + } + + } + if($c1){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d1){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + } + + } + if($f1){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + $html .= '<div class="seatPick">'; + if($a2){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b2){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + } + + } + if($c2){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d2){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + } + + } + if($f2){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + + if($v->train[0]->Aircraft != 'F'){ + echo $html; + } + } + ?> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success checked_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">聚合订票</button> + </td> + <td colspan="4" class="biaoqian"><span class="back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success ctrip_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">携程订票</button> + </td> + <td colspan="4" class="biaoqian"><span class="ctrip_back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success grab_ticket" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">抢票</button> + </td> + <td colspan="4"> + <span class="grab_config"><a style="text-decoration:none;cursor:pointer;">点击打开配置清单</a></span> + <p class="grab_mes" style="color:red;line-height: 30px;"></p> + <table class="table table-condensed table-bordered grab_config_table hidden"> + <tbody> + <tr> + <td colspan="2"><span style="float:left">截止时间 : <input type="text" name="deadline" class="date"/> 示例:2018-03-22 17:00:00(必填)</span></td> + <td colspan="2"><span style="float:left">备选车次 : <input type="text" name="alternate_train"/> 示例:["k10","G10"]</span></td> + <td colspan="2"><span style="float:left">备选座位 : <input type="text" name="alternate_seat"/> 示例:["1","2"]</span></td> + </tr> + </tbody> + </table> + </td> + + </tr> + <tr id="back_<?php echo $v->train[0]->FOI_COLD_SN;?>" style="display:none;"> + <td colspan="5"> + 快捷订票处理结果:<span style="color:red;"></span> + </td> + </tr> + + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + <?php endforeach;endif;?> + </div> + </div> +</div> + +<script> + var url="<?php echo site_url('apps/train/index/submit_juhe_order?').'order=';?>"; + var order_ul="<?php echo site_url('apps/train/index/order?').'order=';?>";//订单详情页面 + + $(".pay_api").click(function(){ + // alert(url+$(this).attr("data-order")); + var THIS=$(this); + var order=$(this).attr("data-order"); + var selectseat = ''; + $(this).parent().parent().next().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + $.ajax({ + url:url+$(this).attr("data-order")+'&selectseat='+selectseat, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("快捷订票"); + if(data.status==1){ + THIS.parent().html("<a href='"+order_ul+data.order+"' target='_blank'>订单详情</a>"); + } + + $("#back_"+order+" span").html(data.mes); + $("#back_"+order).show(); + + }, + dataType: "json", + + }); + return false; + }); + + $(".check_people").click(function(){ + if($(this).is(":checked")){ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").attr("checked","checked"); + }else{ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").removeAttr("checked"); + } + }); + + //聚合出票 + $(".checked_pay").click(function(){ + var url2="<?php echo site_url('apps/trainsystem/addorders/booktickets?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + var selectseat = ''; + $(this).parent().parent().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + + people_sn=people_sn.substring(1); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat+"&type=juhe"; + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("聚合订票"); + var str = "<a href='http://www.mycht.cn/info.php/apps/trainsystem/pages/order?order="+data.order+"' target='_blank'>"+data.mes+"</a>"; + THIS.parent().parent().find(".back_mes").html(str); + + }, + dataType: "json", + + }); + + return false; + }); + + //携程出票 + $(".ctrip_pay").click(function(){ + var ctrip_url="<?php echo site_url('apps/trainsystem/addorders/booktickets?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + var selectseat = ''; + $(this).parent().parent().prev().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data')+','; + } + }); + selectseat=selectseat.substr(0,selectseat.length-1); + people_sn=people_sn.substring(1); + ctrip_url+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat+"&type=ctrip"; + + var THIS=$(this); + THIS.parent().parent().find(".ctrip_back_mes").html(" ");//清空提示 + $.ajax({ + url:ctrip_url, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("携程订票"); + var str = "<a href='http://www.mycht.cn/info.php/apps/trainsystem/pages/order?order="+data.order+"' target='_blank'>"+data.mes+"</a>"; + THIS.parent().parent().find(".ctrip_back_mes").html(str); + + }, + dataType: "json", + + }); + + return false; + }); + + //抢票清单 + $('.grab_config').click(function(){ + var table = $(this).next().next('.grab_config_table'); + if(table.hasClass('hidden')){ + table.removeClass('hidden'); + }else{ + table.addClass('hidden'); + } + }); + + //开始抢票 + $('.grab_ticket').click(function(){ + var url2="<?php echo site_url('apps/train/tuniu_train/grabTicketBook?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + people_sn=people_sn.substring(1); + // var coli_id = $('input[name="ht_order"]').val(); + var deadline = $(this).parent().next().find('.date').val(); + var alternate_train = $('input[name="alternate_train"]').val(); + var alternate_seat = $('input[name="alternate_seat"]').val(); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&deadline="+deadline+"&alternate_train="+alternate_train+"&alternate_seat="+alternate_seat; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("抢票"); + THIS.parent().next().find(".grab_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); +</script> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/order.php b/application/third_party/trainsystem/views/order.php new file mode 100644 index 00000000..10df6de3 --- /dev/null +++ b/application/third_party/trainsystem/views/order.php @@ -0,0 +1,64 @@ +<script type="text/javascript" src="https://data.chinahighlights.com/js/train/StationInfo.js"></script> +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary" style="width:60%;margin:0 auto;"> + <div class="panel-heading"> + <h3 class="panel-title"><?php echo $train_date;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $checi;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo isset($elecnumber)?$elecnumber:"";?></h3> + </div> + <div class="panel-body"> + <?php if((int)$status>1):?> + <p style="display:inline-block"><?php echo $from_station_name;?><span class="from_station_en"> </span><br><span class="start_time"></span></p><span class="glyphicon glyphicon-arrow-right"> </span><p style="display:inline-block"> <?php echo $to_station_name;?><span class="to_station_en"> </span><br><span class="arrive_time"></span></p> + <?php foreach ($passengers as $v):?> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p><?php echo @$v->tst_realname."({$v->tst_identitytype})&nbsp;&nbsp;&nbsp;&nbsp;{$v->tst_seatstype}&nbsp;&nbsp;{$v->tst_seatdetail}&nbsp;&nbsp;&nbsp;&nbsp;票价:¥{$v->tst_ticketprice}";?></p> + <?php endforeach;?> + <?php if((int)$status === 4):?> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p>出票成功</p> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p style="text-align:center;"><a href="refund?order=<?php echo $ordernumber?>" style="padding:5px 15px;" class="btn btn-warning btn-sm">前往退票 <span class="glyphicon glyphicon-forward"></span></a></p> + <?php endif;?> + + <?php if((int)$status === 6):?> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p>正在处理退票</p> + <p style="text-align:center;"><a href="refund?order=<?php echo $ordernumber?>" style="padding:5px 15px;" class="btn btn-warning btn-sm">查看详情 <span class="glyphicon glyphicon-forward"></span></a></p> + <?php endif;?> + + <?php if((int)$status === 7):?> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p><?php echo $msg;?></p> + <p style="text-align:center;"><a href="refund?order=<?php echo $ordernumber?>" style="padding:5px 15px;" class="btn btn-warning btn-sm">查看详情 <span class="glyphicon glyphicon-forward"></span></a></p> + <?php endif;?> + <?php else:?> + <p><?php echo $msg;?></p> + <?php endif;?> + </div> + </div> +</div> +<script> +var StationInfoArr = StationInfo.split("@"); +var StationNameArr = new Array(); +var code_name = new Array(); +var station_cn_en = new Array(); +var form_data = {}; +for (var i = 0; i < StationInfoArr.length; ++i) { + StationNameArr.push(StationInfoArr[i].split("|")); + code_name[StationNameArr[i][1]] = [StationNameArr[i][2]]; + station_cn_en[StationNameArr[i][3]] = StationNameArr[i][2]; +} +console.log(station_cn_en); +$(function(){ + var from_station_en = code_name['<?php echo $from_station_code?>']; + var to_station_en = code_name['<?php echo $to_station_code?>']; + var start_date = '<?php echo $train_date?>'; + var start_time = '<?php echo $start_time?>'; + var arrive_time = '<?php echo $arrive_time?>'; + + //console.log(code_name); + $('.from_station_en').html('('+from_station_en+') '); + $('.to_station_en').html('('+to_station_en+')'); + $('.start_time').html('('+start_date+' '+start_time+')'); + $('.arrive_time').html('('+start_date+' '+arrive_time+')'); +}); +</script> + diff --git a/application/third_party/trainsystem/views/order_list.php b/application/third_party/trainsystem/views/order_list.php new file mode 100644 index 00000000..28108f3a --- /dev/null +++ b/application/third_party/trainsystem/views/order_list.php @@ -0,0 +1,101 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">订单搜索</h3> + </div> + <div class="panel-body"> + <div class="row"> + <form style="" action="" method="get"> + <div class="col-md-6"> + <input class="form-control" type="text" placeholder="汉特订单号或聚合订单号" name="order" value="<?php echo !empty($order)?"$order":"";?>" autocomplete="off"> + </div> + <div class="col-md-4"> + <select class="form-control" name="web_code"> + <option value ="分站点查询,默认商旅" disabled="disabled" selected>分站点查询,默认全站</option> + <option value ="CHT">商旅</option> + <option value ="jp">日本</option> + <option value="train_vac">西班牙</option> + <option value="train_it">意大利</option> + <option value="train_ru">俄罗斯</option> + <option value="train_vc">法国</option> + </select> + </div> + <!--<div class="col-md-5"> + <input type="text" name="from_date" class="date" value="" class=""> + 至 + <input type="text" name="to_date" class="date" value=""> + </div>--> + <div class="col-md-5"> + <button type="submit" id="sub" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-search"></span> 搜索</button> + </div> + </form> + </div> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">订单列表</h3> + </div> + <div class="panel-body"> + <table class="table table-striped" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">汉特订单号(商家订单号)</th> + <th style="text-align:center;">聚合订单号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">出发</th> + <th style="text-align:center;">到达</th> + <th style="text-align:center;">状态</th> + <th style="text-align:center;">价格</th> + <th style="text-align:center;">提交时间</th> + <th style="text-align:center;">所属部门</th> + <th style="text-align:center;">渠道</th> + <th style="text-align:center;">出票方式</th> + <th style="text-align:center;">是否发送邮件</th> + <th style="text-align:center;">操作</th> + </tr> + </thead> + <tbody> + <?php $num=0; foreach($data as $v):?> + <tr> + <td><?php echo ++$num;?></td> + <td><?php echo $v->COLI_ID.'('.$v->ts_cold_sn.')';?></td> + <td><?php echo $v->ts_ordernumber;?></td> + <td><?php echo $v->ts_checi;?></td> + <td><?php echo $v->ts_fromstationame;?></td> + <td><?php echo $v->ts_tostationame;?></td> + <td><?php echo $v->info;?></td> + <td><?php echo $v->ts_orderamount;?></td> + <td><?php echo $v->ts_subtime;?></td> + <td><?php echo $v->COLI_WebCode;?></td> + <td><?php echo $v->ts_channel;?></td> + <?php + if($v->ts_isauto == 1){ + echo '<td>自动</td>'; + }elseif($v->ts_isauto == 0){ + echo '<td>手动</td>'; + }elseif($v->ts_isauto == 3){ + echo '<td>抢票</td>'; + } + ?> + <?php + if($v->ts_sendmail == 1){ + if($v->ts_m_sn){ + echo '<td><a target="_blank" href="http://www.mycht.cn/info.php/apps/train/index/get_mailinfo/'.$v->ts_m_sn.'">是</a></td>'; + }else{ + echo '<td>是</td>'; + } + }else{ + echo '<td>否</td>'; + } + ?> + <td><a target="_blank" href="order?order=<?php echo $v->ts_ordernumber;?>">详情</a></td> + </tr> + <?php endforeach;?> + </tbody> + </table> + <div style="text-align:right;"><ul class="pagination"><?php echo $page_link;?></ul></div> + </div> + </div> +</div> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/refund.php b/application/third_party/trainsystem/views/refund.php new file mode 100644 index 00000000..6eeeac99 --- /dev/null +++ b/application/third_party/trainsystem/views/refund.php @@ -0,0 +1,48 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary" style="width:60%;margin:0 auto;"> + <div class="panel-heading"> + <h3 class="panel-title"><?php echo $train_date;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $checi;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo isset($elecnumber)?$elecnumber:"";?></h3> + </div> + <div class="panel-body"> + <?php + foreach ($passengers as $items){ + echo '<p>'.$from_station_name.'<span class="glyphicon glyphicon-arrow-right"></span>'.$to_station_name.'</p>'; + echo '<p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p>'; + echo '<p>'.$items->tst_realname.'('.$items->tst_ticketype.')&nbsp;&nbsp;&nbsp;&nbsp;'.$items->tst_seatstype.'&nbsp;&nbsp;'.$items->tst_seatdetail.'&nbsp;&nbsp;&nbsp;&nbsp;票价:¥'.$items->tst_ticketprice.'</p>'; + if((int)$items->tst_status != 7){ + echo '<p>'; + echo '<a href="###" style="padding:5px 15px;" class="btn btn-warning btn-sm returnticket" name="'.$items->tst_realname.'" passid="'.$items->tst_numberid.'"><span class="glyphicon glyphicon-remove"></span>退票</a>'; + echo '</p>'; + }else{ + $info = json_decode($items->tst_returncallback); + echo '<p><table class="table table-bordered table-hover" style="text-align:center;"><tr><th colspan="2" style="text-align:center;">退票处理</th></tr>'; + echo '<tr><td>'.$items->tst_lasteditdate.'</td>'; + echo '<tr><td>'.$msg.'</td></tr></table></p>'; + } + }?> + </div> + </div> +</div> +<script> +$(function(){ + $('.returnticket').click(function(){ + var url = <?php echo "'http://www.mycht.cn/info.php/apps/trainsystem/returnorders/returntickets?ordernumber=$ordernumber'"?>; + var return_ticket = $(this); + name = $(this).attr('name'); + passid = $(this).attr('passid'); + url += '&passportname='+name+'&passportno='+passid; + //console.log(url);return false; + $.ajax({ + url:url, + success:function(json){ + alert('请求成功,正在处理退票...'); + return_ticket.html('退票成功'); + }, + error:function(json){ + alert('请求失败,请重新请求...'); + return_ticket.html('退票失败'); + } + }); + }); +}); +</script> \ No newline at end of file diff --git a/application/third_party/trainsystem/views/train_transaction_excel.php b/application/third_party/trainsystem/views/train_transaction_excel.php new file mode 100644 index 00000000..fd45ab3b --- /dev/null +++ b/application/third_party/trainsystem/views/train_transaction_excel.php @@ -0,0 +1,178 @@ +<?xml version="1.0" encoding="utf-8"?> +<?mso-application progid="Excel.Sheet"?> +<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:o="urn:schemas-microsoft-com:office:office" + xmlns:x="urn:schemas-microsoft-com:office:excel" + xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:html="http://www.w3.org/TR/REC-html40"> + <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> + <Author>c21</Author> + <LastAuthor>c21</LastAuthor> + <Created>2016-12-23T01:21:46Z</Created> + <LastSaved>2016-12-23T01:38:10Z</LastSaved> + <Version>12.00</Version> + </DocumentProperties> + <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> + <WindowHeight>9630</WindowHeight> + <WindowWidth>21555</WindowWidth> + <WindowTopX>0</WindowTopX> + <WindowTopY>90</WindowTopY> + <ProtectStructure>False</ProtectStructure> + <ProtectWindows>False</ProtectWindows> + </ExcelWorkbook> + <Styles> + <Style ss:ID="Default" ss:Name="Normal"> + <Alignment ss:Vertical="Center"/> + <Borders/> + <Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/> + <Interior/> + <NumberFormat/> + <Protection/> + </Style> + <Style ss:ID="m58993952"> + <Alignment ss:Horizontal="Right" ss:Vertical="Center" ss:WrapText="1"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="m58993972"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="20" + ss:Color="#000000" ss:Bold="1"/> + </Style> + <Style ss:ID="m58993992"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="s78"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + </Style> + <Style ss:ID="s79"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + <NumberFormat ss:Format="General Date"/> + </Style> + </Styles> + <Worksheet ss:Name="Sheet1"> + <?php $num=count($arr);?> + <Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="<?php echo $num+6;?>" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Column ss:AutoFitWidth="0" ss:Width="115.5"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="100.5"/> + <Column ss:AutoFitWidth="0" ss:Width="62.25"/> + <Column ss:AutoFitWidth="0" ss:Width="203.25"/> + <Row ss:AutoFitHeight="0"> + <Cell ss:MergeAcross="5" ss:MergeDown="1" ss:StyleID="m58993952"><Data + ss:Type="String">苏州新科兰德科技有限公司&#10;地址:苏州市园区启月街288号紫金东方307室&#10;联系电话:051262391880&#10;开户银行:浙商银行苏州分行&#10;公司名称:苏州新科兰德科技有限公司&#10;银行账号:3050020010120100129207&#10;跟踪号:<?php echo $arr[0]['trackcode'];?></Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="99.75"/> + <Row ss:AutoFitHeight="0" ss:Height="42"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993972"><Data ss:Type="String">桂林海纳国际旅行社有限公司火车票对账文件</Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s78"><Data ss:Type="String">时间</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">信息</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">购票人</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">团名</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">变化值</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">最新余额</Data></Cell> + </Row> + <?php for($i=$num-1;$i>=0;$i--){?> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s79"><Data ss:Type="String"><?php echo $arr[$i][2];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][3];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][7];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][6];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="Number"><?php echo $arr[$i][1];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="Number"><?php echo $arr[$i][5];?></Data></Cell> + </Row> + <?php }?> + <Row ss:AutoFitHeight="0" ss:Height="36"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993992"><Data ss:Type="String">苏州新科兰德科技有限公司©版权所有 苏ICP备14006450号-3 增值电信业务经营许可证:苏B2-20140496</Data></Cell> + </Row> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <Selected/> + <Panes> + <Pane> + <Number>3</Number> + <ActiveRow>4</ActiveRow> + <ActiveCol>4</ActiveCol> + </Pane> + </Panes> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet2"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet3"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> +</Workbook> From 72ab473a8b4d322e2a3dc49c52d2ca2ef77bc9e7 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Fri, 26 Apr 2019 09:31:45 +0800 Subject: [PATCH 295/382] =?UTF-8?q?=E5=B0=86=E5=80=BC=E7=8F=AD=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F=E5=92=8Cvalue=E7=B3=BB=E7=BB=9F=E3=80=82=E3=80=82?= =?UTF-8?q?=E4=BB=8E123=E6=90=AC=E8=BF=81=E5=88=B0144?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dingmail/controllers/index.php | 714 ++++++++++++++++++ .../dingmail/models/ding_value_model.php | 334 ++++++++ webht/third_party/dingmail/views/like.php | 212 ++++++ webht/third_party/dingmail/views/login.php | 63 ++ webht/third_party/dingmail/views/mail.php | 552 ++++++++++++++ .../dingmail/views/rank_person.php | 251 ++++++ webht/third_party/dingmail/views/user.php | 258 +++++++ .../workflow/controllers/index.php | 114 ++- .../workflow/models/workflow_model.php | 37 +- .../third_party/workflow/views/form/rota.php | 29 +- .../workflow/views/index/rata_list.php | 9 +- .../workflow/views/index/unverify.php | 68 +- .../workflow/views/index/user_manage.php | 124 ++- .../workflow/views/index/verify.php | 6 +- .../workflow/views/mail_tpl/rota.php | 4 + webht/third_party/workflow/views/w-left.php | 5 +- 16 files changed, 2724 insertions(+), 56 deletions(-) create mode 100644 webht/third_party/dingmail/controllers/index.php create mode 100644 webht/third_party/dingmail/models/ding_value_model.php create mode 100644 webht/third_party/dingmail/views/like.php create mode 100644 webht/third_party/dingmail/views/login.php create mode 100644 webht/third_party/dingmail/views/mail.php create mode 100644 webht/third_party/dingmail/views/rank_person.php create mode 100644 webht/third_party/dingmail/views/user.php diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php new file mode 100644 index 00000000..6b705811 --- /dev/null +++ b/webht/third_party/dingmail/controllers/index.php @@ -0,0 +1,714 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class Index extends CI_Controller { + + public function __construct() { + parent::__construct(); + $this->load->model('ding_value_model'); + } + + public function test_cookie(){ + //https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoagxeeheunc0p95eu8&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/webht.php/apps/dingmail/index/test_cookie + + } + + public function index($unionid = null,$type = null){ + if($this->session->userdata('dingding_user_info') === false){ + $this->session->set_userdata('unionid', $unionid); + $this->session->set_userdata('type',$type); + $this->load->view('login'); + }else{ + if($unionid != null && $type != null){ + $user_info = $this->session->userdata('dingding_user_info'); + $data['type'] = $type; + $data['user'] = $user_info->ddu_Name; + $data['user_unionid'] = $user_info->ddu_Unionid; + if($this->ding_value_model->get_dingding_user($unionid) == null){ + echo '该用户还未登录过,请告知他登录后才能对他点赞或拍砖!<br>'; + echo '有问题请联系:CYC!'; + exit; + } + $data['comment_name'] = $this->ding_value_model->get_dingding_user($unionid)->ddu_Name; + $data['comment_unionid'] = $unionid; + $data['content'] = $type; + $data['mail_identify'] = $this->ding_value_model->get_dingding_user($unionid)->ddu_Sn.'_'.time(); + $data['createtime'] = time(); + if($data['user'] == $data['comment_name']){ + echo '<script>alert("不能对自己点赞或拍砖!")</script>'; + $this->index($unionid); + }else{ + $obj = $this->ding_value_model->get_user_time($data['comment_unionid'],$data['user_unionid']); + $last_time = $obj->ddv_Createtime; + $time_diff = ($data['createtime'] - $last_time) / 3600; + if($time_diff > 3){ + $flag = $this->ding_value_model->add_value($data); + if(!$flag){ + exit($type.'失败'); + }else{ + redirect(site_url('apps/dingmail/index/index/'.$unionid)); + } + }else{ + echo '<script>alert("不能频繁对一个人点赞或拍砖!")</script>'; + $this->index($unionid); + } + } + }else{ + if($unionid == null){ + $unionid = $this->session->userdata('dingding_user_info')->ddu_Unionid; + } + $mdata['user'] = $this->ding_value_model->get_dingding_user($unionid); + $mdata['user_unionid'] = $unionid; + $mdata['like_count'] = $this->ding_value_model->count_like($unionid); + $mdata['unlike_count'] = $this->ding_value_model->count_unlike($unionid); + $mdata['whos_like'] = $this->ding_value_model->whos_like($unionid); + $mdata['whos_unlike'] = $this->ding_value_model->whos_unlike($unionid); + $mdata['all_comment'] = $this->ding_value_model->all_comment($unionid); + //print_r($this->session->userdata('dingding_user_info')); + $this->load->view('user',$mdata); + } + } + } + + //value邮件页面 + public function mail_index(){ + if($this->session->userdata('dingding_user_info') === false){ + $this->load->view('login'); + }else{ + //print_r($this->session->userdata('dingding_user_info')); + $this->load->view('mail'); + } + } + + //发送邮件 + public function send_mail(){ + if(!$this->input->post('emaillist')){ + echo -1; + return; + } + $user_info = $this->session->userdata('dingding_user_info'); + $data['mail_content'] = htmlspecialchars($this->input->post('emailcontent')); + $data['mail_fromuser'] = $user_info->ddu_Name; + $data['mail_subject'] = $this->input->post('mail_subject'); + $data['mail_touser'] = $this->input->post('emaillist'); + $data['mail_ccuser'] = $this->input->post('cs_emaillist'); + $data['mail_value_key'] = $this->input->post('whm_value_key'); + $data['mail_createtime'] = time(); + $data['mail_identify'] = $user_info->ddu_Sn . '_' . time(); + $ddm_id = $this->ding_value_model->add_mail($data); + //邮件所有人,如果是value邮件,则属于被value的人,如果不是,则属于发邮件的人 + if ($this->input->post('whum_value_user')) { + $value_user_array = explode(';', $this->input->post('whum_value_user')); + foreach ($value_user_array as $vu) { + if (!empty($vu)) { + $vudata['value_user_name'] = $vu; + $vudata['value_user_identify'] = $data['mail_identify']; + $vudata['value_user_createtime'] = $data['mail_createtime']; + $ddum_id = $this->ding_value_model->add_value_user($vudata); + } + } + } else { + $vudata['value_user_name'] = $user_info->ddu_Name; + $vudata['value_user_identify'] = $data['mail_identify']; + $vudata['value_user_createtime'] = $data['mail_createtime']; + $ddum_id = $this->ding_value_model->add_value_user($vudata); + } + + //收件人 + $tostring = ''; + $tolist_array = array(); + $nowlist_array = explode(';', $this->input->post('emaillist')); + foreach ($nowlist_array as $v) { + if($v != null){ + $tostring .= "'".$v."'".','; + } + } + $tostring = substr($tostring,0,-1); + if(!empty($tostring)){ + $tolist_array = $this->ding_value_model->all_email($tostring); + }else{ + $tolist_array = null; + } + + + //抄送 + $ccstring = ''; + $cclist_array = array(); + $ccmail_array = explode(';', $this->input->post('cs_emaillist')); + + foreach ($ccmail_array as $c) { + if($c != null){ + $ccstring .= "'".$c."'".','; + } + } + $ccstring = substr($ccstring,0,-1); + if(!empty($ccstring)){ + $cclist_array = $this->ding_value_model->all_email($ccstring); + }else{ + $cclist_array = null; + } + $mailheader = '<p style="font-size:20px">FROM:'.$user_info->ddu_Name.'</p><br>'; + $mailbody = '<div style="overflow:hidden"> + <a style="height:auto;text-decoration: none;" href="http://' . $_SERVER['HTTP_HOST'] . '/webht.php/apps/dingmail/index/like/' . $data['mail_identify'] . '/like" > + <img src="http://' . $_SERVER['HTTP_HOST'] . '/css/images/like.png" /> + </a> + <a style="height:auto;text-decoration: none;" href="http://' . $_SERVER['HTTP_HOST'] . '/webht.php/apps/dingmail/index/like/' . $data['mail_identify'] . '/unlike" > + <img src="http://' . $_SERVER['HTTP_HOST'] . '/css/images/unlike.png" /> + </a> + </div>'; + + $fromuser = $user_info->ddu_Name; + $subject = $this->input->post('mail_subject'); + + //是否为value邮件,如果不是value邮件,不在邮件下放置点赞按钮 + if($this->input->post('whum_value_user')){ + $body = $mailheader.$this->input->post('emailcontent').$mailbody; + }else{ + $body = $mailheader.$this->input->post('emailcontent'); + } + + if (!$this->do_sendmail($fromuser, $tolist_array, $cclist_array, $subject, $body)) { + $result = 0; //"邮件发送有误: " . $mail->ErrorInfo; + } else { + //是value邮件的话,默认发送人点赞 + if ($this->input->post('whum_value_user')) { + $obj = explode(';', $this->input->post('whum_value_user')); + foreach(array_filter($obj) as $value){ + $data['comment_name'] = $value; + $data['comment_unionid'] = $this->ding_value_model->get_dingding_unionid($data['comment_name'])->ddu_Unionid; + $data['type'] = 'like'; + $data['mail_identify'] = $data['mail_identify']; + $data['user'] = $user_info->ddu_Name; + $data['user_unionid'] = $user_info->ddu_Unionid; + $data['content'] = $this->ding_value_model->get_mail($data['mail_identify'])->ddm_Content; + $data['createtime'] = time(); + $whc_id = $this->ding_value_model->add_value($data); + } + } + $result = 1; + } + echo $result; + return; + } + + //执行邮件发送功能 + public function do_sendmail($fromuser, $tolist_array, $cclist_array, $subject, $mailbody) { + $this->load->library('Phpmailer_lib'); + $mail = new PHPMailer(); + $mail->IsSMTP(); + $mail->Host = 'smtp.mxhichina.com';//smtp.sendgrid.net + $mail->Port = 25; + $mail->SMTPAuth = true; + $mail->Username = 'admin@hainatravel.com'; + $mail->Password = "Hainatravel123";//Hainatravel1234 + $mail->SMTPSecure = 'tls'; + $mail->CharSet = "utf-8"; + $mail->Encoding = "base64"; + $mail->IsHTML(true); + + + $mail->FromName = $fromuser; //收件人昵称 + $mail->From = 'admin@hainatravel.com'; //发件人 + //$mail->setFrom('zm198311@yahoo.com.cn‍', $fromuser); + + if($tolist_array != null){ + foreach ($tolist_array as $v) { + $mail->AddAddress($v->ddu_Email); //收件人 + } + } + if($cclist_array != null){ + foreach ($cclist_array as $c) { + $mail->addCC($c->ddu_Email); //抄送 + } + } + + $mail->Subject = $subject; //邮件主题 + $mail->Body = $mailbody; //邮件内容 + + if (!$mail->Send()) { + $result = $mail->ErrorInfo; + echo "邮件发送有误: " . $mail->ErrorInfo; + } else { + $result = true; + } + return $result; + } + + //钉邮群体点赞功能 + public function like($identify = null,$type = null){ + if($this->session->userdata('dingding_user_info') === false){ + $this->session->set_userdata('identify',$identify); + $this->session->set_userdata('mail_type',$type); + $this->load->view('login'); + }else{ + $user_info = $this->session->userdata('dingding_user_info'); + if(!empty($user_info)){ + $data['user'] = $user_info->ddu_Name; + if(($type == 'like' || $type == 'unlike') && $identify){ + $data['type'] = $type; + $data['mail_identify'] = $identify; + $data['user_unionid'] = $user_info->ddu_Unionid; + $has_like = $this->ding_value_model->is_liked($data); + if(!$has_like){ + $data['createtime'] = time(); + $data['content'] = $this->ding_value_model->get_mail($data['mail_identify'])->ddm_Content; + $data['comment_name'] = 'value邮件'; + $data['comment_unionid'] = $this->ding_value_model->get_mail($identify)->ddm_Sn; + //对邮件点赞 + $whc_id = $this->ding_value_model->add_value($data); + } + //对value对象点赞 + $valuedata['type'] = $type; + $valuedata['mail_identify'] = $identify; + $valuedata['user'] = $user_info->ddu_Name; + $valuedata['user_unionid'] = $user_info->ddu_Unionid; + $valuedata['createtime'] = time(); + $valuedata['content'] = $this->ding_value_model->get_mail($identify)->ddm_Content; + $obj = $this->ding_value_model->get_value($identify,$valuedata['user_unionid']); + if(!empty($obj)){ + //这里没有判空 + foreach($obj as $value){ + + $valuedata['comment_name'] = $value->ddum_Name; + $valuedata['comment_unionid'] = $value->ddu_Unionid; + $obj = $this->ding_value_model->get_user_time($valuedata['comment_unionid'],$valuedata['user_unionid'],$identify); + if($obj){ + $last_time = $obj->ddv_Createtime; + }else{ + $last_time = 0; + } + $time_diff = ($valuedata['createtime'] - $last_time) / 3600; + if($time_diff > 100000){ + $flag = $this->ding_value_model->add_value($valuedata); + + if(!$flag){ + continue; + } + + }else{ + echo '<script>alert("你已经对这封邮件的value对象点过赞或拍砖了!")</script>'; + } + } + //sleep(3); + //redirect(site_url('apps/dingmail/index/like/'.$identify)); + } + + } + } + $tpldata['value_mail'] = $this->ding_value_model->get_mail($identify); + $tpldata['whos_like'] = $this->ding_value_model->value_whos_like($identify); + $tpldata['whos_unlike'] = $this->ding_value_model->value_whos_unlike($identify); + $this->load->view('like',$tpldata); + } + } + + //增加评论 + public function add_comment(){ + $data = array(); + if($this->input->post('hidden_name')){ + $data['user'] = '猜猜我是谁'; + $data['user_unionid'] = 'xxxxxxx'; + $data['type'] = 'hidden_comment'; + }else{ + $data['user'] = $this->session->userdata('dingding_user_info')->ddu_Name; + $data['user_unionid'] = $this->session->userdata('dingding_user_info')->ddu_Unionid; + $data['type'] = 'comment'; + } + + $data['comment_name'] = $this->input->post('user_name'); + $data['comment_unionid'] = $this->input->post('user_unionid'); + $data['content'] = str_replace(PHP_EOL, '', $this->input->post('comment')); + + $data['createtime'] = time(); + $data['mail_identify'] = $this->input->post('user_sn').'_'.$data['createtime']; + + $obj = $this->ding_value_model->get_last_comment($data['comment_name'],$data['comment_unionid']); + + if(empty($obj)){ + $time = 0; + }else{ + $time = $obj[0]->ddv_Createtime; + } + + $tolist_array = $this->ding_value_model->all_email("'".$data['comment_name']."'"); + $difftime = time() - $time; + if($difftime / 3600 > 24){ + $this->do_sendmail($data['user'], $tolist_array, null, '今天有人评论你了哟!', '快去看看吧:http://www.mycht.cn/webht.php/apps/dingmail/index/index/'.$data['comment_unionid']); + } + + $comment_id = $this->ding_value_model->add_value($data); + + echo $comment_id; + } + + public function test(){ + $this->ding_value_model->test(); + } + + //点赞排行榜 + public function rank_person() { + if($this->session->userdata('dingding_user_info') === false){ + $this->load->view('login'); + }else{ + $data = array(); + $user_info = $this->session->userdata('dingding_user_info'); + if (!empty($user_info)) { + $data['uname'] = $user_info->ddu_Name; + } + //$data['current_user'] = $current_user; + //周榜 + $monday = strtotime('this week'); + $sunday = strtotime('last day this week +7 day'); + $data['rank_week'] = $this->ding_value_model->get_person_rank($monday, $sunday); + + //月榜 + $from_date = strtotime(date('Y-m-01', time())); + $firstday = date('Y-m-01', time()); + $to_date = strtotime("$firstday +1 month -1 day"); + $data['rank_month'] = $this->ding_value_model->get_person_rank($from_date, $to_date); + //年榜 + $year_start = strtotime(date('Y-01-01', time())); + //echo strtotime(date('2017-12-31', time())); + + //$year_start = strtotime(date('2016-01-01')); + $year_end = strtotime(date('Y-12-31', time())); + //$year_end = strtotime(date('2016-12-31')); + $data['rank_year'] = $this->ding_value_model->get_person_rank($year_start, $year_end); + //总榜 + //$data['rank_all']=$this->Outlook_model->get_person_rank(); + //每条价值观对应获得最多的人 + /* ycc,暂时不需要了 + $rank=array(); + $value_array=array('team','chengxin','customer','discovery','system'); + foreach ($value_array as $value) { + $rank[$value]=$this->Outlook_model->value_key_rank($value); + for ($i=1; $i < 5; $i++) { + $value_key=$value.$i; + $rank[$value_key]=$this->Outlook_model->value_key_rank($value_key); + } + } + $data['rank']=$rank; + */ + $this->load->view('rank_person',$data); + } + } + + //钉钉扫码登录 + public function auth_login(){ + //获取code + $code = $_REQUEST['code']; + //请求access_token,并且打印出来 + $url = 'https://oapi.dingtalk.com/sns/gettoken?appid=dingoagxeeheunc0p95eu8&appsecret=R3fhIY1zWw5wJZNWeszXg0VNpxzU5i95T4tUuboTQBEWAaQyg3mGC-ssskeyt9DY'; + $access_token = json_decode($this->get_http($url,$data = '',$method = 'GET')); + //请求接口获取persistent_code + $url_info = 'https://oapi.dingtalk.com/sns/get_persistent_code?access_token='.$access_token->access_token; + $tmp_auth_code = '{"tmp_auth_code":"'.$code.'"}'; + $info = json_decode($this->get_http($url_info,$data = $tmp_auth_code,$method = 'POST')); + //请求sns_token + $url_sns = 'https://oapi.dingtalk.com/sns/get_sns_token?access_token='.$access_token->access_token; + $sns_code = '{"openid":"'.$info->openid.'","persistent_code":"'.$info->persistent_code.'"}'; + $sns_token = json_decode($this->get_http($url_sns,$sns_code,$method = 'POST')); + //获取个人信息 + $url_person = 'https://oapi.dingtalk.com/sns/getuserinfo?sns_token='.$sns_token->sns_token; + $person = json_decode($this->get_http($url_person,$data = '',$method = 'GET')); + $unionid = $person->user_info->unionid; + $username = $person->user_info->nick; + $check_login = $this->ding_value_model->get_dingding_user($unionid); + if(!$check_login){ + $data = $this->get_user_info($unionid); + $flag = $this->ding_value_model->add_dingding_user($data['ddu_Name'],$data['ddu_Unionid'],$data['ddu_Mobile'],$data['ddu_Email'],$data['ddu_Position'],$data['ddu_Avatar'],$data['ddu_Datetime']); + if(!$flag){ + exit('新增用户失败!'); + }else{ + $user_info = $this->ding_value_model->get_dingding_user($data['ddu_Unionid']); + $this->session->set_userdata('dingding_user_info',$user_info); + if($this->session->userdata('unionid') && $this->session->userdata('type')){ + redirect(site_url('apps/dingmail/index/index/'.$this->session->userdata('unionid').'/'.$this->session->userdata('type'))); + }elseif($this->session->userdata('identify') && $this->session->userdata('mail_type')){ + redirect(site_url('apps/dingmail/index/like/'.$this->session->userdata('identify').'/'.$this->session->userdata('mail_type'))); + }else{ + redirect(site_url('apps/dingmail/index/index/'.$user_info->ddu_Unionid)); + } + } + } + $now_time = time(); + if($check_login->ddu_Datetime == null){ + $check_login->ddu_Datetime = 0; + } + $last_time = $check_login->ddu_Datetime; + $time_diff = ($now_time - $last_time) / 86400; + if($time_diff > 30){ + $data= $this->get_user_info($unionid); + $this->ding_value_model->update_dingding_user($data['ddu_Name'],$data['ddu_Unionid'],$data['ddu_Mobile'],$data['ddu_Email'],$data['ddu_Position'],$data['ddu_Avatar'],$data['ddu_Datetime']); + $check_login = $this->ding_value_model->get_dingding_user($unionid); + } + $this->session->set_userdata('dingding_user_info', $check_login); + if($this->session->userdata('unionid') && $this->session->userdata('type')){ + redirect(site_url('apps/dingmail/index/index/'.$this->session->userdata('unionid').'/'.$this->session->userdata('type'))); + }elseif($this->session->userdata('identify') && $this->session->userdata('mail_type')){ + redirect(site_url('apps/dingmail/index/like/'.$this->session->userdata('identify').'/'.$this->session->userdata('mail_type'))); + }else{ + redirect(site_url('apps/dingmail/index/index/'.$check_login->ddu_Unionid)); + } + + } + + //通过钉钉获取用户详细信息 + public function get_user_info($unionid){ + //公司的access_token. + //unionid是通过扫码获取到 + //获取公司access_token,用access_token和unionid获取userid,利用userid获取成员详细信息。 + $url_access_token = 'https://oapi.dingtalk.com/gettoken?corpid=ding48bce8fd3957c96b&corpsecret=4I_TlkOUtWQ60tUYX_447WXM5mNX41q_Q03xtZJgvBOzMPzGbNKZZz_Bsv-0B9I1'; + $company_info = json_decode($this->get_http($url_access_token,$data='',$method='GET')); + $url_unionid = 'https://oapi.dingtalk.com/user/getUseridByUnionid?access_token='.$company_info->access_token.'&unionid='.$unionid; + $userid = json_decode($this->get_http($url_unionid,$data='',$method='GET')); + $url_userid = 'https://oapi.dingtalk.com/user/get?access_token='.$company_info->access_token.'&userid='.$userid->userid; + $person_details = json_decode($this->get_http($url_userid,$data='',$method='GET')); + $data['ddu_Name'] = $person_details->name; + $data['ddu_Unionid'] = $person_details->unionid; + $data['ddu_Mobile'] = $person_details->mobile; + $data['ddu_Email'] = $person_details->orgEmail; + $data['ddu_Position'] = $person_details->position; + $data['ddu_Avatar'] = $person_details->avatar; + $data['ddu_Datetime'] = time(); + return $data; + } + + //发送请求 + public function get_http($url, $data = '', $method = 'GET') { + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + if ($method == 'POST' && !empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); + } + curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $tmpInfo = curl_exec($curl); // 执行操作 + $errno = curl_errno($curl); + if ($errno !== 0) { + return false; + echo $errno . curl_error($curl); //记录错误日志 + } + curl_close($curl); //关闭CURL会话 + return $tmpInfo; //返回数据 + } + + //自动提示 + public function get_user_list(){ + $q = $this->input->get('q'); + $str_array = explode(';', $q); + $q = end($str_array); + if (!$q) + return; + + $showcount = 1; + $tmp = $this->ding_value_model->all_email(); + foreach ($tmp as $value) { + if ($showcount > 8) + break; + if (strstr($value->ddu_Name, $q)) { + echo $value->ddu_Name . ';' . "\n"; + $showcount++; + } + } + } + + //检测是否有value + public function check_value_user() { + $value_user_array = explode(';', $this->input->post('value_user')); + foreach ($value_user_array as $vu) { + if (!empty($vu)) { + $result = $this->ding_value_model->has_user($vu); + if (empty($result)) { + echo 0; + return; + } + } + } + echo 1; + return; + } + + //退出 + public function logout(){ + $this->session->unset_userdata('dingding_user_info'); + $this->session->unset_userdata('unionid'); + $this->session->unset_userdata('type'); + $this->session->unset_userdata('identify'); + $this->session->unset_userdata('mail_type'); + $this->input->set_cookie('userdata', '', ''); + redirect(site_url('apps/dingmail/index/index/')); + } + + public function valuemail_list(){ + header("Content-type:text/html;charset=utf-8"); + $data = $this->ding_value_model->get_valuemail_list(); + for($i=0;$i<count($data);$i++){ + echo '<h2>时间:'.date('y-m-d',$data[$i]->ddm_Createtime).'</h2><br>'; + echo '<h2>标题:</h2>'.$data[$i]->ddm_Subject.'<br>'; + echo '<h2>value邮件内容:</h2>'.htmlspecialchars_decode($data[$i]->ddm_Content).'<br>'; + echo '<hr/>'; + } + + } + + //查询那条value使用的次数最多 + public function count_valueitems(){ + //获取所有的item条目 + $obj = $this->ding_value_model->get_allvalueitems(); + //定义变量存储数据 + $data = array(); + $data['team1_cn'] = '心存谦卑,发现并欣赏他人的长处'; + $data['team2_cn'] = '人比事更重要,爱能包容一切过错'; + $data['team3_cn'] = '相信一群平凡的人,能组成一个不平凡的团队'; + $data['team4_cn'] = '人人平等,在爱里说诚实话'; + $data['team1_num'] = 0;$data['team2_num'] = 0;$data['team3_num'] = 0;$data['team4_num'] = 0; + + $data['chengxin1_cn'] = '行真善美,恨不义财'; + $data['chengxin2_cn'] = '诚实可信,说到做到,不隐藏真相'; + $data['chengxin3_cn'] = '做人一诺千金,做事全力以赴'; + $data['chengxin4_cn'] = '勇于承担责任使你更优秀'; + $data['chengxin1_num'] = 0;$data['chengxin2_num'] = 0;$data['chengxin3_num'] = 0;$data['chengxin4_num'] = 0; + + $data['customer1_cn'] = '穿客户的鞋,客户是我们最好的老师'; + $data['customer2_cn'] = '细节展现专业,多走一里路'; + $data['customer3_cn'] = '客户的独特性就是我们存在的理由'; + $data['customer4_cn'] = '不让一点瑕疵破坏客人一生中唯一的旅程,一眚能掩大德'; + $data['customer1_num'] = 0;$data['customer2_num'] = 0;$data['customer3_num'] = 0;$data['customer4_num'] = 0; + + $data['discovery1_cn'] = '好奇心,好头脑风暴'; + $data['discovery2_cn'] = '第一个行动的,失败了也光荣;行动太迟,正确的决策也可能变成错误'; + $data['discovery3_cn'] = '以往的成功经验未必是今天问题的解决方案'; + $data['discovery4_cn'] = 'Do Without,自己创造条件达到目标'; + $data['discovery1_num'] = 0;$data['discovery2_num'] = 0;$data['discovery3_num'] = 0;$data['discovery4_num'] = 0; + + foreach ($obj as $item){ + $items = explode(',',$item->ddm_value_key); + foreach($items as $value){ + if(!empty($value)){ + switch ($value){ + case 'team1': + $data['team1_num']++; + break; + case 'team2': + $data['team2_num']++; + break; + case 'team3': + $data['team3_num']++; + break; + case 'team4': + $data['team4_num']++; + break; + case 'chengxin1': + $data['chengxin1_num']++; + break; + case 'chengxin2': + $data['chengxin2_num']++; + break; + case 'chengxin3': + $data['chengxin3_num']++; + break; + case 'chengxin4': + $data['chengxin4_num']++; + break; + case 'customer1': + $data['customer1_num']++; + break; + case 'customer2': + $data['customer2_num']++; + break; + case 'customer3': + $data['customer3_num']++; + break; + case 'customer4': + $data['customer4_num']++; + break; + case 'discovery1': + $data['discovery1_num']++; + break; + case 'discovery2': + $data['discovery2_num']++; + break; + case 'discovery3': + $data['discovery3_num']++; + break; + case 'discovery4': + $data['discovery4_num']++; + break; + } + } + } + } + + //输出内容 + echo '使用条目:'.$data['team1_cn'].' | 使用次数:'.$data['team1_num'].'<br>'; + echo '使用条目:'.$data['team2_cn'].' | 使用次数:'.$data['team2_num'].'<br>'; + echo '使用条目:'.$data['team3_cn'].' | 使用次数:'.$data['team3_num'].'<br>'; + echo '使用条目:'.$data['team4_cn'].' | 使用次数:'.$data['team4_num'].'<br>'; + echo '使用条目:'.$data['chengxin1_cn'].' | 使用次数:'.$data['chengxin1_num'].'<br>'; + echo '使用条目:'.$data['chengxin2_cn'].' | 使用次数:'.$data['chengxin2_num'].'<br>'; + echo '使用条目:'.$data['chengxin3_cn'].' | 使用次数:'.$data['chengxin3_num'].'<br>'; + echo '使用条目:'.$data['chengxin4_cn'].' | 使用次数:'.$data['chengxin4_num'].'<br>'; + echo '使用条目:'.$data['customer1_cn'].' | 使用次数:'.$data['customer1_num'].'<br>'; + echo '使用条目:'.$data['customer2_cn'].' | 使用次数:'.$data['customer2_num'].'<br>'; + echo '使用条目:'.$data['customer3_cn'].' | 使用次数:'.$data['customer3_num'].'<br>'; + echo '使用条目:'.$data['customer4_cn'].' | 使用次数:'.$data['customer4_num'].'<br>'; + echo '使用条目:'.$data['discovery1_cn'].' | 使用次数:'.$data['discovery1_num'].'<br>'; + echo '使用条目:'.$data['discovery2_cn'].' | 使用次数:'.$data['discovery2_num'].'<br>'; + echo '使用条目:'.$data['discovery3_cn'].' | 使用次数:'.$data['discovery3_num'].'<br>'; + echo '使用条目:'.$data['discovery4_cn'].' | 使用次数:'.$data['discovery4_num'].'<br>'; + + } + + public function ajax_get_data(){ + header("Content-Type: text/html;charset=utf-8"); + $from_time = $this->input->get_post('from_time'); + $to_time = $this->input->get_post('to_time'); + $type = $this->input->get_post('type'); + + if($type == 'week'){ + $from_time = strtotime($from_time); + $to_time = strtotime($to_time); + }else if($type == 'month'){ + $firstday = $from_time; + $from_time = strtotime($from_time); + $to_time = strtotime("$firstday +1 month -1 day"); + }else if($type == 'year'){ + $from_time = strtotime($from_time); + $to_time = strtotime($to_time); + } + + $rank_data = $this->ding_value_model->get_person_rank($from_time, $to_time); + + $return_html = ''; + foreach($rank_data as $key=>$value){ + $return_html .= '<li class="col-xs-24 nopadding">'; + $num = $key+1; + $return_html .= '<span class="text-danger'.$num.'">No.'.$num.'</span> '; + $return_html .= '<span><a href="'.site_url('apps/dingmail/index/index/'.$value->ddv_Comment_Unionid).'">'.$value->ddv_Comment_Name.'</a></span>'; + $return_html .= '<span class="badge pull-right">'.$value->like_count.' like</span></li>'; + } + print_r($return_html); + } + + public function delete_value($sn=null){ + if(empty($sn)){ + exit('传参错误'); + }else{ + $this->ding_value_model->delete_value($sn); + } + + } +} + + +?> \ No newline at end of file diff --git a/webht/third_party/dingmail/models/ding_value_model.php b/webht/third_party/dingmail/models/ding_value_model.php new file mode 100644 index 00000000..cc656095 --- /dev/null +++ b/webht/third_party/dingmail/models/ding_value_model.php @@ -0,0 +1,334 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + + +class ding_value_model extends CI_Model { + + function __construct(){ + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + //扫码获取相应人的信息 + function get_dingding_user($unionid){ + $sql = "select + * + from + Dingding_User + where + ddu_Unionid = ?"; + $query = $this->HT->query($sql, array($unionid)); + if ($query->num_rows() > 0){ + $row = $query->row(); + return $row; + } + else{ + return FALSE; + } + } + + //根据姓名获取唯一unionid + public function get_dingding_unionid($name){ + $sql = "select ddu_Unionid from Dingding_User where ddu_Name = ?"; + $query = $this->HT->query($sql, array($name)); + if ($query->num_rows() > 0){ + $row = $query->row(); + return $row; + } + else{ + return FALSE; + } + } + + + //添加用户 + function add_dingding_user($name,$unionid,$mobile,$email,$position,$avatar,$time){ + $sql = "INSERT INTO Dingding_User (ddu_Name,ddu_Unionid,ddu_Mobile,ddu_Email,ddu_Position,ddu_Avatar,ddu_Datetime) VALUES (N?,?,?,?,N?,?,?)"; + $query = $this->HT->query($sql,array($name,$unionid,$mobile,$email,$position,$avatar,$time)); + if ($query){ + return TRUE; + }else{ + return FALSE; + } + } + + //添加value事件 + function add_value($data){ + $sql = "INSERT INTO Dingding_Value (ddv_Type,ddv_Name,ddv_User_Unionid,ddv_Comment_Name,ddv_Comment_Unionid,ddv_Content,ddv_Identify,ddv_Createtime) VALUES (?,N?,?,N?,?,N?,?,?)"; + $query = $this->HT->query($sql,array($data['type'],$data['user'],$data['user_unionid'],$data['comment_name'],$data['comment_unionid'],$data['content'],$data['mail_identify'],$data['createtime'])); + if($query){ + return TRUE; + }else{ + return FALSE; + } + } + + //统计like人数 + function count_like($unionid){ + $year_start = strtotime(date('Y-01-01', time())); + $year_end = strtotime(date('Y-12-31', time())); + $sql = "SELECT COUNT(*) AS count FROM Dingding_Value WHERE ddv_Comment_Unionid = ? AND ddv_Type = 'like' AND ddv_Type = 'like' and ddv_Createtime > '{$year_start}' and ddv_Createtime < '{$year_end}'"; + $query = $this->HT->query($sql,$unionid); + $row = $query->row(); + return $row; + } + + //获取like的人是那些 + function whos_like($unionid){ + $year_start = strtotime(date('Y-01-01', time())); + $year_end = strtotime(date('Y-12-31', time())); + $sql = "SELECT ddv_Name FROM Dingding_Value WHERE ddv_Comment_Unionid = ? AND ddv_Type = 'like' and ddv_Createtime > '{$year_start}' and ddv_Createtime < '{$year_end}' ORDER BY ddv_Sn DESC"; + $query = $this->HT->query($sql,$unionid); + $row = $query->result(); + return $row; + } + + //获取value点赞的人 + function value_whos_like($identify){ + $sql = "SELECT ddv_Name FROM Dingding_Value WHERE ddv_Identify = ? and ddv_Type = 'like' and ddv_Comment_Name = 'value邮件' ORDER BY ddv_Createtime DESC"; + $query = $this->HT->query($sql,$identify); + $row = $query->result(); + return $row; + } + + //获取value拍砖的人 + function value_whos_unlike($identify){ + $sql = "SELECT ddv_Name FROM Dingding_Value WHERE ddv_Identify = ? and ddv_Type = 'unlike' and ddv_Comment_Name = 'value邮件' ORDER BY ddv_Createtime DESC"; + $query = $this->HT->query($sql,$identify); + $row = $query->result(); + return $row; + } + + //根据Identify获取value邮件 + function get_mail($identify){ + $sql = "SELECT * FROM Dingding_Mail where ddm_Identify = ?"; + $query = $this->HT->query($sql, array($identify)); + if ($query->num_rows() > 0){ + $row = $query->row(); + return $row; + } + else{ + return FALSE; + } + } + + //根据Identify获取value邮件中value的人 + function get_value($identify,$user_unionid){ + $sql = "select * from Dingding_user_mail left join Dingding_User on(ddum_Name = ddu_Name) where ddum_Identify = ? and ddu_Unionid != '$user_unionid'"; + $query = $this->HT->query($sql, array($identify)); + if ($query->num_rows() > 0){ + $row = $query->result(); + return $row; + } + else{ + return FALSE; + } + } + + //统计unlike人数 + function count_unlike($unionid){ + $year_start = strtotime(date('Y-01-01', time())); + $year_end = strtotime(date('Y-12-31', time())); + $sql = "SELECT COUNT(*) AS count FROM Dingding_Value WHERE ddv_Comment_Unionid = ? AND ddv_Type = 'unlike' and ddv_Createtime > '{$year_start}' and ddv_Createtime < '{$year_end}'"; + $query = $this->HT->query($sql,$unionid); + $row = $query->row(); + return $row; + } + + //获取unlike的人是那些 + function whos_unlike($unionid){ + $year_start = strtotime(date('Y-01-01', time())); + $year_end = strtotime(date('Y-12-31', time())); + $sql = "SELECT ddv_Name FROM Dingding_Value WHERE ddv_Comment_Unionid = ? AND ddv_Type = 'unlike' and ddv_Createtime > '{$year_start}' and ddv_Createtime < '{$year_end}' ORDER BY ddv_Sn DESC"; + $query = $this->HT->query($sql,$unionid); + $row = $query->result(); + return $row; + } + + //获取所有点评了的人的列表 + function all_comment($unionid){ + $year_start = strtotime(date('Y-01-01', time())); + $year_end = strtotime(date('Y-12-31', time())); + $sql = "SELECT * + FROM Dingding_Value + left join Dingding_User on ddu_Unionid = ddv_User_Unionid + left join Dingding_Mail on ddv_Identify = ddm_Identify + where ddv_Comment_Unionid = '$unionid' + and ddv_Createtime > '{$year_start}' and ddv_Createtime < '{$year_end}' + ORDER BY ddv_Sn DESC"; + $query = $this->HT->query($sql,$unionid); + $row = $query->result(); + return $row; + } + /* + //获取所有点评了的人的列表 + function all_comment($unionid){ + $sql = "SELECT * FROM Dingding_Value WHERE ddv_Comment_Unionid = ? ORDER BY ddv_Sn DESC"; + $query = $this->HT->query($sql,$unionid); + $row = $query->result(); + return $row; + } + */ + //获取所有员工的姓名以及邮箱(钉钉邮箱) + function all_email($data = null){ + if($data){ + $where = "where ddu_Name in ($data)"; + }else{ + $where = ''; + } + $sql = "SELECT ddu_Name,ddu_Email FROM Dingding_User ".$where; + $query = $this->HT->query($sql); + $row = $query->result(); + return $row; + } + + //根据名字确定是否存在 + public function has_user($user_name){ + $sql="SELECT * FROM Dingding_User WHERE ddu_Name='$user_name' "; + $query = $this->HT->query($sql); + return $query->result(); + } + + //新增value邮件 + public function add_mail($data){ + $sql="INSERT INTO Dingding_Mail( + ddm_subject, + ddm_content, + ddm_touser, + ddm_ccuser, + ddm_fromuser, + ddm_value_key, + ddm_identify, + ddm_createtime + ) + VALUES (N?,N?,N?,N?,N?,?,?,?)"; + $this->HT->query($sql, array($data['mail_subject'],$data['mail_content'],$data['mail_touser'],$data['mail_ccuser'],$data['mail_fromuser'],$data['mail_value_key'],$data['mail_identify'],$data['mail_createtime'])); + return $this->HT->last_id('Dingding_Mail'); + } + + //新增value的名单 + public function add_value_user($data){ + $sql="INSERT INTO Dingding_User_Mail ( + ddum_name, + ddum_identify, + ddum_createtime) + VALUES (?,?,?)"; + $this->HT->query($sql, array($data['value_user_name'],$data['value_user_identify'],$data['value_user_createtime'])); + return $this->HT->last_id('webht_user_mail'); + } + + //检测是否已经点赞(仅用于value邮件点赞) + public function is_liked($data){ + $sql = "select * from Dingding_Value where ddv_Identify = ? and ddv_User_Unionid = ? and ddv_Comment_Name = 'value邮件'"; + $query = $this->HT->query($sql,array($data['mail_identify'],$data['user_unionid'])); + if($query->num_rows() >= 1){ + return true; + }else{ + return false; + } + } + + //获取用户最新一次被点赞的时间以及人 + public function get_user_time($unionid,$user_unionid,$identify=false){ + if($identify){ + $where = "and ddv_identify = '$identify'"; + }else{ + $where = ""; + } + $sql = "select ddv_Name,ddv_Createtime from Dingding_Value where ddv_Comment_Unionid = '$unionid' and ddv_User_Unionid = '$user_unionid'$where order by ddv_Createtime desc"; + $query = $this->HT->query($sql); + if($query){ + return $query->row(); + }else{ + return false; + } + } + + //获取最新一次被评论的时间 + public function get_last_comment($comment_name,$comment_unionid){ + $sql = "select + top 1 * + from + Dingding_Value + where + ddv_Comment_Name = '$comment_name' + and + ddv_Comment_Unionid = '$comment_unionid' + and + ddv_Type in ('comment','hidden_comment') + order by + ddv_Createtime desc"; + $query = $this->HT->query($sql); + $result=$query->result(); + return $result; + } + + + //获取点赞排行榜 + public function get_person_rank($from_date=false,$to_date=false){ + $datesql=""; + if ($from_date) { + $datesql=" AND ddv_Createtime BETWEEN '$from_date' AND '$to_date' "; + } + $sql="SELECT TOP 15 + ddv_Comment_Name, + ddv_Comment_Unionid, + COUNT(ddv_Comment_Name) as like_count + FROM Dingding_Value + WHERE ddv_Type='like' AND ddv_Comment_Name != 'value邮件' + $datesql + GROUP BY ddv_Comment_Name,ddv_Comment_Unionid + ORDER BY like_count DESC"; + + $query = $this->HT->query($sql); + $result=$query->result(); + return $result; + } + + //更新用户信息 + function update_dingding_user($name,$unionid,$mobile,$email,$position,$avatar,$time){ + $sql = "UPDATE Dingding_User SET + ddu_Name = '$name', + ddu_Mobile = '$mobile', + ddu_Email = '$email', + ddu_Position = '$position', + ddu_Avatar = '$avatar', + ddu_Datetime = '$time' + WHERE ddu_Unionid = '$unionid'"; + $query = $this->HT->query($sql); + if ($query){ + return true; + }else{ + return FALSE; + } + } + + //获取value邮件列表 + public function get_valuemail_list(){ + $year = strtotime(date('Y-01-01')); + $sql = "select * from Dingding_Mail where ddm_Createtime > '$year' order by ddm_Createtime desc "; + $query = $this->HT->query($sql); + return $query->result(); + + } + + //获取所有value邮件所用的价值观 + public function get_allvalueitems(){ + $sql = "select ddm_value_key from Dingding_Mail where ddm_value_key != ''"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function delete_value($sn){ + $sql = "DELETE FROM Dingding_Value WHERE ddv_Sn = '{$sn}'"; + $query = $this->HT->query($sql); + } + + public function test(){ + $sql = "delete from Dingding_Value where ddv_Sn = '9125'"; + $query = $this->HT->query($sql); + } + +} \ No newline at end of file diff --git a/webht/third_party/dingmail/views/like.php b/webht/third_party/dingmail/views/like.php new file mode 100644 index 00000000..fdde9754 --- /dev/null +++ b/webht/third_party/dingmail/views/like.php @@ -0,0 +1,212 @@ +<!DOCTYPE html> +<html lang="zh-cn"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>HT在线平台</title> + <!-- <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/webht/webht.css?v=1" rel="stylesheet">--> + <link href="/min?f=/css/webht/bootstrap.min.css,/css/webht/webht.css" rel="stylesheet"> + + + + <!--[if lt IE 9]> + <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> + <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> + <![endif]--> + <!-- + <script src="/js/jquery.min.js"></script> + <script src="/js/bootstrap.min.js"></script> + <script src="/js/webht.js?v=1"></script> + --> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js,/js/jquery.suggest.js"></script> + + + <link rel="shortcut icon" href="/css/images/webht.jpg"> +</head> +<body> +<nav class="navbar navbar-inverse navbar-red"> + <div class="container-fluid"> + <!-- Brand and toggle get grouped for better mobile display --> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="<?php echo site_url('');?>"><span class="icon-home"></span> 中华游在线</a> + <a class="navbar-brand visible-xs-block"><?php if(isset($navtitle)) echo $navtitle;?></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url('apps/dingmail/index/mail_index');?>">Value发送</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/index/'.$this->session->userdata('dingding_user_info')->ddu_Unionid);?>">个人中心</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/rank_person');?>">排行榜</a></li> + </ul> + </div> + </div><!-- /.container-fluid --> + </nav> + <div class="container" style="max-width:1200px;"> + <div class="row"> + <div class="col-xs-24 btn-lg"></div> + <div class="col-sm-7 col-xs-24 pull-right" style="font: 14px 'Arial','Microsoft YaHei';line-height:25px;"> + <div class="panel"> + <div class="panel-body"> + <legend> + <span class="text-primary glyphicon glyphicon-thumbs-up" style="font-size:20px;"></span> + <span style="font-size:15px;">他们都觉得很赞!</span> + </legend> + + <?php foreach ($whos_like as $l) { ?> + <span><?php echo $l->ddv_Name; ?>; </span> + <?php } ?> + <div class="clearfix"></div> + </div> + </div> + <div class="panel"> + <div class="panel-body"> + <legend> + <span class="text-danger glyphicon glyphicon-thumbs-down" style="font-size:20px;"></span> + <span style="font-size:15px;">他们拍砖了!</span> + </legend> + <?php foreach ($whos_unlike as $ul) { ?> + <span><?php echo $ul->ddv_Name; ?>; </span> + <?php } ?> + <div class="clearfix"></div> + </div> + </div> + + </div> + + <div class="col-sm-17 col-xs-24"> + <div class="col-xs-24" style="padding-bottom:30px;background:#fff;"> + <h3 style="font-size:20px;margin-bottom:30px;"><?php echo $value_mail->ddm_Subject;?></h3> + <div class="col-xs-24 nopadding"><?php echo htmlspecialchars_decode($value_mail->ddm_Content); ?></div> + <!-- + <div class="col-xs-24 nopadding"> + <a name="gotocomment" id="gotocomment" ></a> + <form id="from-add-comment" method="post" action="<?php echo site_url('apps/outlook/index/add_comment');?>" style="background:#f5f5f5;padding:0px 15px 15px 15px;margin-top:50px;"> + <div class="col-xs-24 btn-lg"></div> + <div class="col-xs-24 nopadding"> + <textarea class="form-control" rows="3" name="comment" id="comment-textarea"></textarea> + </div> + <div class="col-xs-24 btn-sm"></div> + <div class="col-xs-24 nopadding"> + <input type="hidden" name="whc_whm_identify" value="<?php echo $whc_whm_identify;?>"> + <button type="button" id="btn-add-comment" class="btn btn-danger pull-right">确 定</button> + </div> + <div class="clearfix"></div> + </form> + </div> + --> + </div> + <?php if (!empty($list)) { ?> + <div class="col-xs-24" style="margin-top:20px;margin-bottom:50px;padding-bottom:20px;font: 14px 'Arial','Microsoft YaHei';line-height:23px;background:#fff;"> + <?php foreach ($list as $key => $c) { ?> + <div class="col-xs-24" style="padding:12px 0 10px 0;"> + <p class="text-primary"><a href="<?php $usermail=explode('@', $c->whu_email);echo site_url('apps/outlook/index/space/'.$usermail[0]); ?>"><?php echo $c->whu_uname; ?></a>:</p> + <p><?php echo $c->whc_content; ?></p> + <p> + <span class="text-muted"><?php echo date('Y-m-d H:i:s',$c->whc_createtime); ?></span> + <span class="pull-right"><a href="#gotocomment" class="re_comment" data-uname="<?php echo $c->whu_uname; ?>">回复</a></span> + </p> + </div> + <legend class="col-xs-24"></legend> + <?php } ?> + </div> + <?php } ?> + + </div> + + </div> +</div> +<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-body"> + <div class="media"> + <div class="media-left"> + <div> + <span id="msgclass" class="glyphicon glyphicon-ok text-success" aria-hidden="true" style="font-size:85px;"> </span> + <a class="btn btn-sm btn-danger" onclick="ajax_link($(this));" href="javascript:void(0);" data-href="<?php echo site_url('apps/outlook/index/delete_comment/'.$whc_whm_identify.'/'.$type); ?>">撤销操作</a> + </div> + </div> + <div class="media-body" style="font-size:32px;"> + <div class="col-xs-24 btn-lg"><p></p></div> + <span id="msgbox" class="text-success">你已经成功的狠狠<?php if($type=='like'){echo '赞';}else{echo '踩';} ?>了TA一下!</span> + <p style="font-size:14px;color:#888;padding-left:5px;padding-top:18px;"><em class="text-danger" id="seconed_box">15</em> 秒钟内可以撤销刚才的操作</p> + </div> + </div> + </div> + </div> + </div> +</div> + +<script type="text/javascript"> + +var type="<?php echo $type;?>"; +var comment_url="<?php echo site_url('apps/outlook/index/like/'.$whc_whm_identify.'/comment');?>"; +if (type=='like' || type=='unlike') { + $('#myModal').modal('show'); + var timer=$("#seconed_box").text(); + if (timer>=0) { + setInterval(function(){ + var newtimer=--timer; + $("#seconed_box").text(newtimer); + },1000); + }; + setTimeout("$('#myModal').modal('hide')",15000); +}; + +$(".re_comment").click(function () { + $("textarea").text('@'+$(this).attr('data-uname')+' '); + $("textarea").focus(); +}); + +$("#btn-add-comment").click(function() { + if ($("#comment-textarea").val().replace(/(^\s*)|(\s*$)/g,'')=="") { + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + $("#msgbox").text('评论内容不能为空!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + },5000); + return false; + }; + var url = $("form#from-add-comment").attr('action'); + var data= $("form#from-add-comment").serialize(); + $.post(url,data,function(result){ + if (result) { + $("#msgclass").removeClass('glyphicon-remove text-danger'); + $("#msgclass").addClass('glyphicon-ok text-success'); + $("#msgbox").removeClass('text-danger'); + $("#msgbox").addClass('text-success'); + $("#msgbox").text('评论成功!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + location.href=comment_url; + },1500); + }else{ + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + $("#msgbox").text('评论发布失败!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + },5000); + } + }); +}); + +</script> + </body> +</html> \ No newline at end of file diff --git a/webht/third_party/dingmail/views/login.php b/webht/third_party/dingmail/views/login.php new file mode 100644 index 00000000..39421aa0 --- /dev/null +++ b/webht/third_party/dingmail/views/login.php @@ -0,0 +1,63 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta charset="utf-8"> + <title>value系统登录</title> + <link href="http://data.chtcdn.com/bootstrap/css/bootstrap.min.css" rel="stylesheet"> + <link rel="stylesheet" href="http://data.chtcdn.com/js/poshytip/tip-yellow/tip-yellow.css" type="text/css" /> + <link rel="stylesheet" href="http://data.chtcdn.com/js/modaldialog/css/jquery.modaldialog.css" type="text/css" /> + <link rel="stylesheet" href="http://data.chtcdn.com/js/kindeditor/themes/default/default.css" type="text/css" media="screen" /> + <script type="text/javascript" src="http://data.chtcdn.com/js/jquery.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/bootstrap/js/bootstrap.min.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/js/poshytip/jquery.poshytip.min.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/js/jquery.form.min.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/js/modaldialog/jquery.modaldialog.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/js/kindeditor/kindeditor-min.js"></script> + <script type="text/javascript" src="http://data.chtcdn.com/js/basic.js"></script> + <script src="https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js"></script> + <script type="text/javascript" src="/dinglogin/dingmail.js"></script> + <link rel="stylesheet" href="/dinglogin/dingding.css"> + <!-- + <link rel="stylesheet" href="/min/?f=/bootstrap/css/bootstrap.min.css,/js/poshytip/tip-yellow/tip-yellow.css,/js/modaldialog/css/jquery.modaldialog.css,/js/kindeditor/themes/default/default.css" type="text/css" /> + + <script type="text/javascript" src="/min/?f=/js/jquery.js,/bootstrap/js/bootstrap.min.js,/js/poshytip/jquery.poshytip.min.js,/js/jquery.form.min.js,/js/modaldialog/jquery.modaldialog.js,/js/kindeditor/kindeditor-min.js,/js/basic.js"></script> + + --> + + <link rel="shortcut icon" href="http://data.chtcdn.com/bootstrap/img/glyphicons_290_skull.png"> + </head> + + <body> + +<div class="row-fluid"> + <div class="span3"></div> + <div class="span6"> + <form action="<?php echo site_url('login/check') ?>" class="form-horizontal" name="form_login" id="form_login" method="post"> + <legend> + <p>Welcome</p> + <div class="login_header"> + <div class="login_type login_type_active">钉钉扫码登录</div> + <div class="login_type"><a href="https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoagxeeheunc0p95eu8&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/webht.php/apps/dingmail/index/auth_login">钉钉账号密码登录</a></div> + </div> + </legend> + <div class="ding_login"> + <div id="login_container"></div> + </div> + </form> + + <div class="alert alert-error"> + <h4>IE6 isn't allowed!</h4> + Please use Google Chrome, Firefox, Safair, or IE7+. + </div> + + </div> + <div class="span3"></div> + + +</div> + + + + </body> + +</html> diff --git a/webht/third_party/dingmail/views/mail.php b/webht/third_party/dingmail/views/mail.php new file mode 100644 index 00000000..cbcbdef3 --- /dev/null +++ b/webht/third_party/dingmail/views/mail.php @@ -0,0 +1,552 @@ +<!DOCTYPE html> +<html lang="zh-cn"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>HT在线平台</title> + <!-- <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/webht/webht.css?v=1" rel="stylesheet">--> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js,/js/jquery.suggest.js"></script> + <link href="/min?f=/css/webht/bootstrap.min.css,/css/webht/webht.css" rel="stylesheet"> + <link type="text/css" rel="stylesheet" href="/css/webht/jquery.suggest.css" /> + <script src="/js/TQEditor/TQEditor.js" type="text/javascript"></script> + <script type="text/javascript" src="/js/jquery.suggest.js"></script> + + + <!--[if lt IE 9]> + <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> + <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> + <![endif]--> + <!-- + <script src="/js/jquery.min.js"></script> + <script src="/js/bootstrap.min.js"></script> + <script src="/js/webht.js?v=1"></script> + --> + + + + <link rel="shortcut icon" href="/css/images/webht.jpg"> +</head> +<body> + <nav class="navbar navbar-inverse navbar-red"> + <div class="container-fluid"> + <!-- Brand and toggle get grouped for better mobile display --> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="<?php echo site_url('');?>"><span class="icon-home"></span> 中华游在线</a> + <a class="navbar-brand visible-xs-block"><?php if(isset($navtitle)) echo $navtitle;?></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url('apps/dingmail/index/mail_index');?>">Value发送</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/index/'.$this->session->userdata('dingding_user_info')->ddu_Unionid);?>">个人中心</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/rank_person');?>">排行榜</a></li> + </ul> + <ul class="nav navbar-nav navbar-right"> + <li><a href="<?php echo site_url('apps/dingmail/index/logout');?>">退出</a></li> + </ul> + </div> + </div><!-- /.container-fluid --> + </nav> + + <div class="container-fluid"> + <div class="row"> + <div class="col-xs-24" style="padding:15px; padding-right:30px;"> + <form id="form-send-mail" method="post" action="<?php echo site_url('apps/dingmail/index/send_mail');?>"> + <div class="media" style="overflow:visible;"> + <div class="media-left"> + <button type="button" id="btn-send-mail" class="media-object btn btn-default" style="width:80px;height:80px;" data-loading-text="正在发送" onclick="$(this).button('loading');"><span class="icon-newspaper" style="font-size:32px;"></span><br>发送(S)</button> + </div> + <div class="media-body" style="overflow:visible;"> + <div class="input-group" id="auto-complete"> + <span class="input-group-btn"> + <button class="btn btn-default" type="button" disabled="disabled">收件人(O)...</button> + </span> + <input type="text" class="form-control" id="emaillist" name="emaillist" value="G-海纳公告;"> + </div> + <div class="col-xs-24 btn-sm"></div> + <div class="form-group input-group" id="auto-complete2"> + <span class="input-group-btn"> + <button class="btn btn-default" type="button" disabled="disabled">抄 送(C)...</button> + </span> + <input type="text" class="form-control" id="cs_emaillist" name="cs_emaillist"> + </div> + </div> + </div> + <div class="form-group input-group"> + <div class="input-group-btn"> + <button type="button" class="btn btn-default" style="width:92px;" data-toggle="modal" data-target="#myModal" data-backdrop="static">价值观 <span class="caret"> </span></button> + <button type="button" class="btn btn-default" style="width:100px;cursor:default;background:#fff !important;" disabled="disabled">主 题</button> + </div> + <input type="text" class="form-control" name="mail_subject" id="mail-subject" autocomplete="off"> + </div> + <textarea class="form-control" id="emailcontent" rows="36" name="emailcontent"></textarea> + <input type="hidden" id="whm_value_key" name="whm_value_key"> + <input type="hidden" id="whum_value_user" name="whum_value_user"> + </form> + </div> + </div> +</div> + +<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> + <div class="modal-dialog modal-lg" style="margin-top:5px;"> + <div class="modal-content"> + <div class="modal-header"> + <div class="" id="auto-complete3"> + <input type="text" class="form-control" name="value_user" id="value_user" placeholder="value人员名单,输入名字,然后在下拉提示框里选择完整的名单"> + </div> + </div> + <div class="modal-body" style="padding-top:0;"> + <div class="col-xs-12" style="padding-left:0;"> + <h4>团队协作:</h4> + <div class="checkbox"> + <label> + <input class="team_checkbox" type="checkbox" data-checked="false" value="team1"> + 1.心存谦卑,发现并欣赏他人的长处 + </label> + </div> + <div class="checkbox"> + <label> + <input class="team_checkbox" type="checkbox" data-checked="false" value="team2"> + 2.人比事更重要,爱能包容一切过错 + </label> + </div> + <div class="checkbox"> + <label> + <input class="team_checkbox" type="checkbox" data-checked="false" value="team3"> + 3.相信一群平凡的人,能组成一个不平凡的团队 + </label> + </div> + <div class="checkbox"> + <label> + <input class="team_checkbox" type="checkbox" data-checked="false" value="team4"> + 4.人人平等,在爱里说诚实话 + </label> + </div> + </div> + <div class="col-xs-12"> + <h4>诚信负责:</h4> + <div class="checkbox"> + <label> + <input class="chengxin_checkbox" type="checkbox" data-checked="false" value="chengxin1"> + 1.行真善美,恨不义财 + </label> + </div> + <div class="checkbox"> + <label> + <input class="chengxin_checkbox" type="checkbox" data-checked="false" value="chengxin2"> + 2.诚实可信,说到做到,不隐藏真相 + </label> + </div> + <div class="checkbox"> + <label> + <input class="chengxin_checkbox" type="checkbox" data-checked="false" value="chengxin3"> + 3.做人一诺千金,做事全力以赴 + </label> + </div> + <div class="checkbox"> + <label> + <input class="chengxin_checkbox" type="checkbox" data-checked="false" value="chengxin4"> + 4.勇于承担责任使你更优秀 + </label> + </div> + </div> + <div class="col-xs-24 clearfix"></div> + <div class="col-xs-12" style="padding-left:0;"> + <h4>客户满意: </h4> + <div class="checkbox"> + <label> + <input class="customer_checkbox" type="checkbox" data-checked="false" value="customer1"> + 1.穿客户的鞋,客户是我们最好的老师 + </label> + </div> + <div class="checkbox"> + <label> + <input class="customer_checkbox" type="checkbox" data-checked="false" value="customer2"> + 2.细节展现专业,多走一里路 + </label> + </div> + <div class="checkbox"> + <label> + <input class="customer_checkbox" type="checkbox" data-checked="false" value="customer3"> + 3.客户的独特性就是我们存在的理由 + </label> + </div> + <div class="checkbox"> + <label> + <input class="customer_checkbox" type="checkbox" data-checked="false" value="customer4"> + 4.不让一点瑕疵破坏客人一生中唯一的旅程,一眚能掩大德 + </label> + </div> + </div> + <div class="col-xs-12"> + <h4>发现创新: </h4> + <div class="checkbox"> + <label> + <input class="discovery_checkbox" type="checkbox" data-checked="false" value="discovery1"> + 1.好奇心,好头脑风暴 + </label> + </div> + <div class="checkbox"> + <label> + <input class="discovery_checkbox" type="checkbox" data-checked="false" value="discovery2"> + 2.第一个行动的,失败了也光荣;行动太迟,正确的决策也可能变成错误 + </label> + </div> + <div class="checkbox"> + <label> + <input class="discovery_checkbox" type="checkbox" data-checked="false" value="discovery3"> + 3.以往的成功经验未必是今天问题的解决方案 + </label> + </div> + <div class="checkbox"> + <label> + <input class="discovery_checkbox" type="checkbox" data-checked="false" value="discovery4"> + 4.Do Without,自己创造条件达到目标 + </label> + </div> + </div> + <div class="col-xs-24" style="padding-left:0;"> + <h4>系统思维:</h4> + <div class="checkbox"> + <label> + <input class="system_checkbox" type="checkbox" data-checked="false" value="system1"> + 1.Why goes before How, 先明确目的和意义,再决定步骤和方法 + </label> + </div> + <div class="checkbox"> + <label> + <input class="system_checkbox" type="checkbox" data-checked="false" value="system2"> + 2.举一反三,不头痛医头、脚痛医脚,从根部解决问题 + </label> + </div> + <div class="checkbox"> + <label> + <input class="system_checkbox" type="checkbox" data-checked="false" value="system3"> + 3.让我们走过的弯路,成为他人成功的捷径;让我们走过的捷径,成为后人永远的祝福 + </label> + </div> + <div class="checkbox"> + <label> + <input class="system_checkbox" type="checkbox" data-checked="false" value="system4"> + 4.复杂的事情简单做,简单的事情认真重复做,重复的事情创造性地做,代码可以做的事情就不要人来做 + </label> + </div> + </div> + + <div class="col-xs-24" style="padding-left:0;"> + <h4> + <label> + <input type="checkbox" data-checked="false" value="special" id="special_checkbox" onclick="$('#special_value_input').toggle();"> + 其他价值观 + </label> + </h4> + <input class="form-control" id="special_value_input" name="special_text" style="display:none;"> + </div> + + <div class="clearfix"></div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-primary" id="btn-value">确 定</button> + <button type="button" class="btn btn-default" id="btn-value-remove" data-dismiss="modal" style="margin-left:5px;">取消</button> + </div> + </div> + </div> +</div> +<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-body"> + <div class="media"> + <div class="media-left"> + <div> + <span id="msgclass" class="glyphicon glyphicon-ok text-success" aria-hidden="true" style="font-size:85px;"> </span> + </div> + </div> + <div class="media-body" style="font-size:32px;"> + <div class="col-xs-24 btn-lg"><p></p></div> + <span id="msgbox" class="text-success">发送成功!</span> + </div> + </div> + </div> + </div> + </div> +</div> +<div class="modal fade" id="myModal-img" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="myModalLabel">插入图片</h4> + </div> + <div class="modal-body"> + <form action="<?php echo site_url('apps/outlook/index/upload_photos');?>" + method="post" + target="ifm1" + class="form-inline form_upload_photos" + enctype="multipart/form-data"> + <div class="col-xs-24 btn-lg"></div> + <div class="form-group"> + <label for="宽度">图片</label> + <input class="form-control" type="file" name="Profile_file" id="Profile_file" /> + </div> + <div class="col-xs-24 btn-lg"></div> + <div class="clearfix"></div> + <div class="form-group"> + <label for="宽度">宽度</label> + <input type="text" class="form-control" id="upload_photo_width" value="500"> + </div> + <div class="form-group"> + <label for="高度">高度</label> + <input type="text" class="form-control" id="upload_photo_height" value="auto"> + </div> + <div class="col-xs-24 btn-lg"></div> + <div class="clearfix"></div> + </form> + <div id="upload_status1"> + <iframe class="ifm1 hide" name="ifm1"></iframe> + </div> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-danger pull-right editor_img_upload">确 定</button> + </div> + </div> + </div> +</div> + +<script type="text/javascript" defer="true"> +var $img_modal=$('#myModal-img'); +var doname="<?php echo $_SERVER['HTTP_HOST']; ?>"; +var TQE=new tqEditor('emailcontent', + { + toolbar:['mode','paragraph','fontname','fontsize','forecolor','backcolor','bold','italic','underline','strikethrough','removeformat','|','justifyleft','justifycenter','justifyright','unorderedlist','orderedlist','iodent','outdent','indent','|','inserthorizontalrule','createlink','unlink','inserttable','|','insertimage','insertface'], + toolbarRight:['fullscreen'], + imageUploadUrl:'./upload.php', + linkUploadUrl:'./upload.php', + faceurl:'http://'+doname+'/js/TQEditor/face' + }); + +$(".editor_img_upload").click(function(){ + $(".form_upload_photos").submit(); + $img_modal.modal('hide'); +}); +function get_photo_url(text){ + var width=$("#upload_photo_width").val(); + var height=$("#upload_photo_height").val(); + var upload_html='<img src="'+text+'" width="'+width+'" height="'+height+'">'; + TQE.insertHtml(upload_html); +} + +$(document).ready(function() +{ + //自动提示 + var auto_complete_url="<?php echo site_url('apps/dingmail/index/get_user_list'); ?>"; + $("#emaillist").suggest(auto_complete_url,{ + container: '#auto-complete', + onSelect: function() {}, + selectClass: '', + matchClass: 'active', + resultsClass: 'list-unstyled' + }); + $("#cs_emaillist").suggest(auto_complete_url,{ + container: '#auto-complete2', + onSelect: function() {}, + selectClass: '', + matchClass: 'active', + resultsClass: 'list-unstyled' + }); + $("#value_user").suggest(auto_complete_url,{ + container: '#auto-complete3', + onSelect: function() {}, + selectClass: '', + matchClass: 'active', + resultsClass: 'list-unstyled' + }); + + $("input:checkbox").click(function() { + if ($(this).attr('data-checked')=="false") { + $(this).attr('data-checked','true'); + }else{ + $(this).attr('data-checked','false'); + } + }); + + $("#btn-value").click(function() { + if ($("#value_user").val()=='') { + alert('请输入要VALUE的人员名单!'); + return false; + }; + var checkurl="<?php echo site_url('apps/dingmail/index/check_value_user'); ?>"; + var flag=true; + var checkuserdata={"value_user":$("#value_user").val()}; + $.ajax({ + type:'post', + url:checkurl, + data:checkuserdata, + async:false, + success:function(response){ + if (response==0) { + flag=false; + } + }, + }); + + if (!flag) { + alert('输入的value人员名字不够完整,请从下拉提示框里选择名单!'); + return false; + }; + + var subject=''; + var whm_value_key=''; + var teamstr='[团队协作]:'; + var teamflag=false; + $(".team_checkbox").each(function(){ + if ($(this).attr('data-checked')=="true") { + teamstr+=$.trim($(this).parent("label").text())+';'; + whm_value_key+=$(this).val()+','; + teamflag=true; + } + }); + if(teamflag) subject+=teamstr; + + var chengxinstr='[诚信负责]:'; + var chengxinflag=false; + $(".chengxin_checkbox").each(function(){ + if ($(this).attr('data-checked')=="true") { + chengxinstr+=$.trim($(this).parent("label").text())+';'; + whm_value_key+=$(this).val()+','; + chengxinflag=true; + } + }); + if(chengxinflag) subject+=chengxinstr; + + var customerstr='[客户满意]:'; + var customerflag=false; + $(".customer_checkbox").each(function(){ + if ($(this).attr('data-checked')=="true") { + customerstr+=$.trim($(this).parent("label").text())+';'; + whm_value_key+=$(this).val()+','; + customerflag=true; + } + }); + if(customerflag) subject+=customerstr; + + var discoverystr='[发现创新]:'; + var discoveryflag=false; + $(".discovery_checkbox").each(function(){ + if ($(this).attr('data-checked')=="true") { + discoverystr+=$.trim($(this).parent("label").text())+';'; + whm_value_key+=$(this).val()+','; + discoveryflag=true; + } + }); + if(discoveryflag) subject+=discoverystr; + + var systemstr='[系统思维]:'; + var systemflag=false; + $(".system_checkbox").each(function(){ + if ($(this).attr('data-checked')=="true") { + systemstr+=$.trim($(this).parent("label").text())+';'; + whm_value_key+=$(this).val()+','; + systemflag=true; + } + }); + if(systemflag) subject+=systemstr; + + var specialstr='[其他价值观]:'; + var specialflag=false; + if ($("#special_checkbox").attr('data-checked')=="true") { + specialstr+=$("#special_value_input").val()+';'; + whm_value_key+=$("#special_checkbox").val()+','; + specialflag=true; + }; + if(specialflag) subject+=specialstr; + + if (whm_value_key=='') { + alert('请选择要VALUE的条目类型!'); + return false; + }; + + if($("#value_user").val()) subject=$("#value_user").val()+subject; + if (subject!=='') subject='values+'+subject; + $("#mail-subject").val(subject); + $("#whm_value_key").val(whm_value_key); + $("#whum_value_user").val($("#value_user").val()); + + $('#myModal').modal('hide'); +/* $("input:checkbox").attr('data-checked','false'); + $("input:checkbox").removeAttr("checked"); + $("#value_user").val(''); +*/ }); +//取消设置,所有选项清零 + $("#btn-value-remove").click(function () { + $("input:checkbox").attr('data-checked','false'); + $("input:checkbox").removeAttr("checked"); + $("#value_user").val(''); + }); + + $("#btn-send-mail").click(function () { + if ($("#emailcontent").val().replace(/(^\s*)|(\s*$)/g,'')=="") { + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + $("#msgbox").text('邮件内容不能为空!'); + $('#myModal2').modal('show'); + var that=$(this); + setTimeout(function() { + $('#myModal2').modal('hide'); + that.button('reset'); + },3000); + return false; + }; + var url = $("form#form-send-mail").attr('action'); + var data= $("form#form-send-mail").serialize(); + $.post(url,data,function(result){ + + if (result==1) { + $("#msgclass").removeClass('glyphicon-remove text-danger'); + $("#msgclass").addClass('glyphicon-ok text-success'); + $("#msgbox").removeClass('text-danger'); + $("#msgbox").addClass('text-success'); + $("#msgbox").text('发送成功!'); + $('#myModal2').modal('show'); + setTimeout(function() { + $('#myModal2').modal('hide'); + location.href=location.href; + },1500); + }else{ + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + if (result==-1) { + $("#msgbox").text('请输入收件人名字!'); + }else{ + $("#msgbox").text('发送失败!'); + /* + setTimeout(function() { + $('#myModal2').modal('hide'); + location.href=location.href; + },1500); + */ + } + $('#myModal2').modal('show'); + setTimeout(function() { + $('#myModal2').modal('hide'); + },5000); + } + + }); + }) +}); +</script> +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/dingmail/views/rank_person.php b/webht/third_party/dingmail/views/rank_person.php new file mode 100644 index 00000000..e1a89a0f --- /dev/null +++ b/webht/third_party/dingmail/views/rank_person.php @@ -0,0 +1,251 @@ +<!DOCTYPE html> +<html lang="zh-cn"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>HT在线平台</title> + <!-- <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/webht/webht.css?v=1" rel="stylesheet">--> + <link href="/min?f=/css/webht/bootstrap.min.css,/css/webht/webht.css" rel="stylesheet"> + + + + <!--[if lt IE 9]> + <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> + <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> + <![endif]--> + <!-- + <script src="/js/jquery.min.js"></script> + <script src="/js/bootstrap.min.js"></script> + <script src="/js/webht.js?v=1"></script> + --> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js,/js/jquery.suggest.js"></script> + <script src="/js/jquery-ui.min.js?v=1"></script> + + <link href="/css/webht/jquery-ui-1.10.0.custom.css" rel="stylesheet"> + + <link rel="shortcut icon" href="/css/images/webht.jpg"> +</head> +<body> + <nav class="navbar navbar-inverse navbar-red"> + <div class="container-fluid"> + <!-- Brand and toggle get grouped for better mobile display --> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="<?php echo site_url('');?>"><span class="icon-home"></span> 中华游在线</a> + <a class="navbar-brand visible-xs-block"><?php if(isset($navtitle)) echo $navtitle;?></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url('apps/dingmail/index/mail_index');?>">Value发送</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/index/'.$this->session->userdata('dingding_user_info')->ddu_Unionid);?>">个人中心</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/rank_person');?>">排行榜</a></li> + </ul> + <ul class="nav navbar-nav navbar-right"> + <li><a href="<?php echo site_url('apps/dingmail/index/logout');?>">退出</a></li> + </ul> + </div> + </div><!-- /.container-fluid --> + </nav> + +<div class="container"> + <div class="row"> + <div class="col-xs-24 btn-lg"></div> + <div class="col-xs-24"> + <h3>个人获赞排行榜</h3> + </div> + <div class="col-xs-8"> + <div class="col-xs-24 bg-white min-height-500"> + <div class="row" style="border-bottom:1px solid #e5e5e5;margin-bottom:20px;"> + <div class="col-xs-4"><p style="font-size:15px;color:#333;padding-top:8px;">周榜</p></div> + <div class="col-xs-10"><input class="form-control" placeholder="起始时间" id="from_time" value=""/></div> + <div class="col-xs-10"><input class="form-control" placeholder="截止时间" id="to_time" value=""/></div> + </div> + <ul class="nav rank_ul" id="week_data"> + <?php foreach ($rank_week as $key_rw => $rw) { ?> + <li class="col-xs-24 nopadding"> + <span class="text-danger<?php echo $key_rw+1; ?>">No.<?php echo $key_rw+1; ?></span> + <span> + <a href="<?php echo site_url('apps/dingmail/index/index/'.$rw->ddv_Comment_Unionid); ?>"> + <?php echo $rw->ddv_Comment_Name; ?> + </a> + </span> + <span class="badge pull-right"><?php echo $rw->like_count;?> like</span> + </li> + <?php } ?> + <?php if(empty($rank_week)) { ?><p>暂无数据</p><?php } ?> + </ul> + </div> + </div> + <div class="col-xs-8"> + <div class="col-xs-24 bg-white min-height-500"> + <div class="row" style="border-bottom:1px solid #e5e5e5;margin-bottom:20px;"> + <div class="col-xs-4"><p style="font-size:15px;color:#333;padding-top:8px;">月榜</p></div> + <div class="col-xs-10"> + <select class="form-control" id="month_time"> + <option select="selected" value="null">选择月份</option> + <option value="1">一月</option> + <option value="2">二月</option> + <option value="3">三月</option> + <option value="4">四月</option> + <option value="5">五月</option> + <option value="6">六月</option> + <option value="7">七月</option> + <option value="8">八月</option> + <option value="9">九月</option> + <option value="10">十月</option> + <option value="11">十一月</option> + <option value="12">十二月</option> + </select> + </div> + <div class="col-xs-10"> + <select class="form-control" id="month_year_time"> + <!--<option select="selected" value="null">选择年份</option>--> + <?php + for($i=2017; $i<=date('Y'); $i++){ + if($i == date('Y')){ + echo '<option value="'.$i.'" selected="selected">'.$i.'</option>'; + }else{ + echo '<option value="'.$i.'">'.$i.'</option>'; + } + } + ?> + </select> + </div> + </div> + <ul class="nav rank_ul" id="month_data"> + <?php foreach ($rank_month as $key_rm => $rm) { ?> + <li class="col-xs-24 nopadding"> + <span class="text-danger<?php echo $key_rm+1; ?>">No.<?php echo $key_rm+1; ?></span> + <span> + <a href="<?php echo site_url('apps/dingmail/index/index/'.$rm->ddv_Comment_Unionid); ?>"> + <?php echo $rm->ddv_Comment_Name; ?> + </a> + </span> + <span class="badge pull-right"><?php echo $rm->like_count;?> like</span> + </li> + <?php } ?> + <?php if(empty($rank_month)) { ?><p>暂无数据</p><?php } ?> + </ul> + </div> + </div> + <div class="col-xs-8"> + <div class="col-xs-24 bg-white min-height-500"> + <div class="row" style="border-bottom:1px solid #e5e5e5;margin-bottom:20px;"> + <div class="col-xs-6"><p style="font-size:15px;color:#333;padding-top:8px;">年榜</p></div> + <div class="col-xs-18"> + <select class="form-control" id="year_time"> + <?php + for($i=2017; $i<=date('Y'); $i++){ + if($i == date('Y')){ + echo '<option value="'.$i.'" selected="selected">'.$i.'</option>'; + }else{ + echo '<option value="'.$i.'">'.$i.'</option>'; + } + } + ?> + </select> + </div> + </div> + <ul class="nav rank_ul" id="year_data"> + <?php foreach ($rank_year as $key_ry => $ry) { ?> + <li class="col-xs-24 nopadding"> + <span class="text-danger<?php echo $key_ry+1; ?>">No.<?php echo $key_ry+1; ?></span> + <span> + <a href="<?php echo site_url('apps/dingmail/index/index/'.$ry->ddv_Comment_Unionid); ?>"> + <?php echo $ry->ddv_Comment_Name; ?> + </a> + </span> + <span class="badge pull-right"><?php echo $ry->like_count;?> like</span> + </li> + <?php } ?> + <?php if(empty($rank_year)) { ?><p>暂无数据</p><?php } ?> + </ul> + </div> + </div> + </div> + +</div> +</body> +<script> +$(function(){ + //日期选择 + $('#from_time,#to_time').datepicker({ + + }); + + //周榜触发事件 + var from_time = ''; + var to_time = ''; + var month_time = ''; + var year_time = ''; + var type = ''; + var month_year_time = ''; + $('#from_time,#to_time').change(function(){ + from_time = $('#from_time').val(); + to_time = $('#to_time').val(); + if(from_time != '' && to_time != ''){ + type = 'week'; + ajax_gethtml(from_time,to_time,type); + } + }); + + //月榜触发事件 + $('#month_time').change(function(){ + month_time = $('#month_time').val(); + month_year_time = $('#month_year_time').val(); + if(month_time != null){ + type = 'month'; + if(month_year_time == 'null'){ + var myDate = new Date(); + from_time = myDate.getFullYear()+'-'+month_time+'-01'; + }else{ + from_time = month_year_time+'-'+month_time+'-01'; + } + to_time = ''; + ajax_gethtml(from_time,to_time,type); + } + }); + + $('#month_year_time').change(function(){ + month_time = $('#month_time').val(); + month_year_time = $('#month_year_time').val(); + if(month_time != 'null'){ + type = 'month'; + from_time = month_year_time+'-'+month_time+'-01'; + to_time = ''; + ajax_gethtml(from_time,to_time,type); + } + }); + + + //年榜触发事件 + $('#year_time').change(function(){ + year_time = $('#year_time').val(); + if(year_time != null){ + type = 'year'; + from_time = year_time+'-01-01'; + to_time = year_time+'-12-31'; + ajax_gethtml(from_time,to_time,type); + } + }); +}); + +function ajax_gethtml(from_time,to_time,type){ + $.ajax({ + url:'http://www.mycht.cn/webht.php/apps/dingmail/index/ajax_get_data/?from_time='+from_time+'&to_time='+to_time+'&type='+type, + type:'get', + success:function(data){ + $('#'+type+'_data').html(data); + } + }); +} +</script> +</html> \ No newline at end of file diff --git a/webht/third_party/dingmail/views/user.php b/webht/third_party/dingmail/views/user.php new file mode 100644 index 00000000..3364dc35 --- /dev/null +++ b/webht/third_party/dingmail/views/user.php @@ -0,0 +1,258 @@ +<!DOCTYPE html> +<html lang="zh-cn"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>HT在线平台</title> + <!-- <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/webht/webht.css?v=1" rel="stylesheet">--> + <link href="/min?f=/css/webht/bootstrap.min.css,/css/webht/webht.css" rel="stylesheet"> + + + + <!--[if lt IE 9]> + <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> + <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> + <![endif]--> + <!-- + <script src="/js/jquery.min.js"></script> + <script src="/js/bootstrap.min.js"></script> + <script src="/js/webht.js?v=1"></script> + --> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js,/js/jquery.suggest.js"></script> + + + <link rel="shortcut icon" href="/css/images/webht.jpg"> +</head> +<body> + <nav class="navbar navbar-inverse navbar-red"> + <div class="container-fluid"> + <!-- Brand and toggle get grouped for better mobile display --> + <div class="navbar-header"> + <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> + <span class="sr-only">Toggle navigation</span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + <span class="icon-bar"></span> + </button> + <a class="navbar-brand" href="<?php echo site_url('');?>"><span class="icon-home"></span> 中华游在线</a> + <a class="navbar-brand visible-xs-block"><?php if(isset($navtitle)) echo $navtitle;?></a> + </div> + + <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> + <ul class="nav navbar-nav"> + <li><a href="<?php echo site_url('apps/dingmail/index/mail_index');?>">Value发送</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/index/'.$this->session->userdata('dingding_user_info')->ddu_Unionid);?>">个人中心</a></li> + <li><a href="<?php echo site_url('apps/dingmail/index/rank_person');?>">排行榜</a></li> + </ul> + <ul class="nav navbar-nav navbar-right"> + <li><a href="<?php echo site_url('apps/dingmail/index/logout');?>">退出</a></li> + </ul> + </div> + </div><!-- /.container-fluid --> + </nav> + + <div class="container" style="max-width:1200px;"> + <div class="row"> + <div class="col-sm-7 col-xs-24 pull-right" style="font: 14px 'Arial','Microsoft YaHei';line-height:25px;"> + <div class="panel" style="margin-top:15px;"> + <div class="panel-body nopadding"> + <div class="row"> + <div class="col-xs-10"> + <?php if(!empty($user->ddu_Avatar)){?> + <img class="img-responsive" src="<?php echo $user->ddu_Avatar?>"/> + <?php }else{?> + 请退出后再次扫码登录,将展示你的钉钉头像 + <?php }?> + </div> + <div class="col-xs-14"> + <p></p><h4 class="text-center strong"><?php echo $user->ddu_Name?></h4><p></p> + <div class="col-xs-12 text-center text-muted" style="border-left:1px solid #ddd;"> + <a href="<?php echo site_url('apps/dingmail/index/index/'.$user_unionid.'/like');?>"> + <strong><?php echo $like_count->count;?></strong><br> + <span>赞</span> + </a> + </div> + <div class="col-xs-12 text-center text-muted" style="border-left:1px solid #ddd;"> + <a href="<?php echo site_url('apps/dingmail/index/index/'.$user_unionid.'/unlike');?>"> + <strong><?php echo $unlike_count->count;?></strong><br> + <span>板砖</span> + </a> + </div> + <p></p> + <div class="col-xs-24 btn-sm"></div> + </div> + </div> + </div> + </div> + <div class="panel"> + <div class="panel-body"> + <legend> + <span class="text-primary glyphicon glyphicon-thumbs-up" style="font-size:20px;"></span> + <span style="font-size:15px;">他们都觉得很赞!</span> + </legend> + <?php foreach($whos_like as $obj){?> + <span><?php echo $obj->ddv_Name; ?>; </span> + <?php } ?> + <div class="clearfix"></div> + </div> + </div> + <div class="panel"> + <div class="panel-body"> + <legend> + <span class="text-danger glyphicon glyphicon-thumbs-down" style="font-size:20px;"></span> + <span style="font-size:15px;">他们拍砖了!</span> + </legend> + <?php foreach($whos_unlike as $obj){?> + <span><?php echo $obj->ddv_Name; ?>; </span> + <?php } ?> + <div class="clearfix"></div> + </div> + </div> + <?php if($this->session->userdata('dingding_user_info')->ddu_Name == $user->ddu_Name ){ ?> + <div class="panel"> + <div class="panel-body"> + <legend> + <span class="text-danger glyphicon glyphicon-leaf" style="font-size:20px;"></span> + <span style="font-size:15px;">个人邮件签名设置!</span> + </legend> + <div class="col-xs-24 nopadding" style="height:70px;background:none;"> + <a href="http://www.mycht.cn/webht.php/apps/dingmail/index/mail_index"> + <img src="http://www.mycht.cn/css/images/+valuemail.png"> + </a> + <a href="http://www.mycht.cn/webht.php/apps/dingmail/index/index/<?php echo $this->session->userdata('dingding_user_info')->ddu_Unionid?>/like"> + <img src="http://www.mycht.cn/css/images/+like.png"> + </a> + <a href="http://www.mycht.cn/webht.php/apps/dingmail/index/index/<?php echo $this->session->userdata('dingding_user_info')->ddu_Unionid?>/unlike"> + <img src="http://www.mycht.cn/css/images/+unlike.png"> + </a> + </div> + <div class="clearfix"> + <p>钉邮签名没有更新成功的同学请看这里:</p> + <p>拖动鼠标选中上方的三个按钮(在<span class="text-danger">按钮下方</span>鼠标左键三击试试),然后按下Ctrl+C键进行复制到自己的outlook签名里即可。</p><p>温馨提示:不能直接用鼠标右键功能进行复制</p> + </div> + </div> + </div> + <?php }else{ ?> + <div></div> + <?php }?> + </div> + <div class="col-sm-17 col-xs-24"> + <a name="gotocomment" id="gotocomment"></a> + <form id="from-add-comment" method="post" action="<?php echo site_url('apps/dingmail/index/add_comment');?>" style="background:#fff;padding:0 15px 15px 15px;margin-top:15px;"> + <div class="col-xs-24 btn-lg"></div> + <p class="col-xs-24 nopadding"><em class="text-primary strong">大家好,我是<?php echo $user->ddu_Name; ?>,欢迎留言......</em></p> + <div class="col-xs-24 nopadding"> + <textarea class="form-control" rows="3" name="comment" id="comment-textarea"></textarea> + </div> + <div class="col-xs-24 btn-sm"></div> + <div class="col-xs-24 nopadding"> + <input type="hidden" name="user_unionid" value="<?php echo $user_unionid;?>"> + <input type="hidden" name="user_sn" value="<?php echo $user->ddu_Sn;?>"> + <input type="hidden" name="user_name" value="<?php echo $user->ddu_Name;?>"> + <div class="pull-right"> + <label style="padding:0 10px 0 0"><input type="checkbox" name="hidden_name" value="hidden_name"/><span style="padding-left:10px">匿名发送</span></label> + <button type="button" id="btn-add-comment" class="btn btn-danger">确 定</button> + </div> + </div> + <div class="clearfix"></div> + </form> + + <div class="col-xs-24 nopadding" style="margin-top:20px;margin-bottom:50px;font: 14px 'Arial','Microsoft YaHei';line-height:23px;"> + <?php foreach($all_comment as $key=>$value){?> + <div class="col-xs-24" style="border-bottom:1px solid #ededed;padding:15px 20px;background:#fff;"> + <p class="text-primary"> + <?php if($value->ddu_Avatar){?> + <img style="width:30px;display:inline;border-radius:50%;margin-right:15px;" class="img-responsive" src="<?php echo $value->ddu_Avatar?>"/> + <?php }?> + <?php if($value->ddv_Type == 'hidden_comment'){ + echo $value->ddv_Name; + }else{?> + <a href="http://www.mycht.cn/webht.php/apps/dingmail/index/index/<?php echo $value->ddv_User_Unionid?>"><?php echo $value->ddv_Name?></a> + <?php }?> + </p> + <?php if($value->ddv_Content == 'like' || $value->ddv_Content == 'unlike' ){ ?> + <p>对你点了一个<?php echo $value->ddv_Content?></p> + <?php }else if($value->ddv_Type == 'comment' || $value->ddv_Type == 'hidden_comment'){?> + <p><?php echo $value->ddv_Content?></p> + <?php }else{ ?> + <p><?php echo $value->ddv_Type.'+1'.'<br>';echo $value->ddm_Subject; ?></p><a href="http://www.mycht.cn/webht.php/apps/dingmail/index/like/<?php echo $value->ddv_Identify?>/comment">查看更多</a> + <?php }?> + <p> + <span class="text-muted"><?php echo date('m-d-y H:i:s',$value->ddv_Createtime)?></span> + </p> + </div> + <?php } ?> + + </div> + + </div> + </div> + </div> + <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> + <div class="modal-dialog"> + <div class="modal-content"> + <div class="modal-body"> + <div class="media"> + <div class="media-left"> + <div> + <span id="msgclass" class="glyphicon glyphicon-ok text-success" aria-hidden="true" style="font-size:85px;"> </span> + </div> + </div> + <div class="media-body" style="font-size:32px;"> + <div class="col-xs-24 btn-lg"><p></p></div> + <span id="msgbox" class="text-success"></span> + </div> + </div> + </div> + </div> + </div> +</div> +</body> +<script> +var comment_url="<?php echo site_url('apps/dingmail/index/index/'.$user_unionid);?>"; + +$("#btn-add-comment").click(function() { + if ($("#comment-textarea").val().replace(/(^\s*)|(\s*$)/g,'')=="") { + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + $("#msgbox").text('评论内容不能为空!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + },5000); + return false; + }; + var url = $("form#from-add-comment").attr('action'); + var data= $("form#from-add-comment").serialize(); + console.log(data); + $.post(url,data,function(result){ + if (result) { + $("#msgclass").removeClass('glyphicon-remove text-danger'); + $("#msgclass").addClass('glyphicon-ok text-success'); + $("#msgbox").removeClass('text-danger'); + $("#msgbox").addClass('text-success'); + $("#msgbox").text('评论成功!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + location.href=comment_url; + },1500); + }else{ + $("#msgclass").removeClass('glyphicon-ok text-success'); + $("#msgclass").addClass('glyphicon-remove text-danger'); + $("#msgbox").removeClass('text-success'); + $("#msgbox").addClass('text-danger'); + $("#msgbox").text('评论发布失败!'); + $('#myModal').modal('show'); + setTimeout(function() { + $('#myModal').modal('hide'); + },5000); + } + }); +}); +</script> +</html> \ No newline at end of file diff --git a/webht/third_party/workflow/controllers/index.php b/webht/third_party/workflow/controllers/index.php index c37ca49a..0f209053 100644 --- a/webht/third_party/workflow/controllers/index.php +++ b/webht/third_party/workflow/controllers/index.php @@ -15,7 +15,11 @@ class Index extends CI_Controller $this->permission->is_admin(false); $this->load->model('workflow_model'); } - + + public function test(){ + $this->workflow_model->delete_test(); + } + //首页 public function index() { @@ -24,6 +28,7 @@ class Index extends CI_Controller } $data=array(); $typelist=$this->workflow_model->get_type_list('all'); + //print_r($typelist); $data['typelist']=array(); foreach ($typelist as $t) { $data['typelist'][$t->wt_parentid][]=$t; @@ -62,7 +67,12 @@ class Index extends CI_Controller //添加一个具体事务到数据库 public function do_add_work() - { + { + + $this->load->model('operator_model'); + $current_user=$this->input->post('wf_user'); + $tmp = $this->operator_model->get_user_by_name($current_user); + //判断是不是补填的值班记录 if ($this->input->post('mail_title')=='值班记录') { //本月和上个月的值班表(有可能本月初和上月尾是连着的假期) @@ -73,27 +83,32 @@ class Index extends CI_Controller $data['flow_data'][]=$this->workflow_model->get_work_flow_data($v->wf_sn); } //节假日列表 - $needdate_list=array(); + $needdate_list=$myrota=array(); foreach ($data['flow_data'] as $f) { foreach ($f as $d) { $wfd_key_arr=explode('_', $d->wfd_key); + //值班日期是周末的日期集合 if ($wfd_key_arr[0]=='weekend' && $d->wfd_value==1) { $wfd_key_arr[1]=strlen($wfd_key_arr[1])==7?substr($wfd_key_arr[1], 0,-1).'0'.substr($wfd_key_arr[1],-1):$wfd_key_arr[1]; $needdate_list[]=$wfd_key_arr[1]; } + //当前用户的值班日期集合 + $name_string=str_replace('惠毅', '惠毅;惠 毅', $d->wfd_value); + if (!empty($d->wfd_value) && stripos($name_string, $tmp['OPI_Name'])!==false && isset($wfd_key_arr[2]) && is_numeric($wfd_key_arr[2])) { + $need_date=strlen($wfd_key_arr[2])==7?substr($wfd_key_arr[2], 0,-1).'0'.substr($wfd_key_arr[2],-1):$wfd_key_arr[2]; + $myrota[]=date('Ymd',strtotime($need_date)); + } } } + $needdate_list=array_intersect($needdate_list,$myrota); $zhiban_date=date('Ymd',strtotime($this->input->post('wf_time'))); - if (!in_array($zhiban_date, $needdate_list)) { - echo json_encode(array('status'=>'no','msg'=>'请把左上角的日期改为你值班当天的日期')); - return true; + if (empty($needdate_list) or !in_array($zhiban_date, $needdate_list)) { + //echo json_encode(array('status'=>'no','msg'=>'值班日期与值班表不符,更换了值班的同学请更改值班表')); + //return true; } } //保存任务 - $this->load->model('operator_model'); - $current_user=$this->input->post('wf_user'); - $tmp = $this->operator_model->get_user_by_name($current_user); $wf_user=$tmp['OPI_SN']; $wf_time=strtotime($this->input->post('wf_time')); $group_admin=explode('@', $this->input->post('wf_wt_sn')); @@ -108,10 +123,13 @@ class Index extends CI_Controller if ($wfd_key=='emailcontent') { $wfd_value=htmlspecialchars($wfd_value); } - $col_val.="('".trim($wfd_key)."','".$wfd_value."',".$wfd_wf_sn."),"; + // $col_val.="('".trim($wfd_key)."','".$wfd_value."',".$wfd_wf_sn."),"; + $col_val.="('".trim($wfd_key)."','".chop($wfd_value)."',".$wfd_wf_sn."),";//csk 2016-9-22 去掉末尾的换行和空格 $mail_data[$wfd_key]=$wfd_value; $mail_data['flow_data'][$wfd_key]=$wfd_value; + $mail_data['flow_data'][$wfd_key]=chop($wfd_value);//csk 2016-9-22 去掉末尾的换行和空格 } + $apply_user=$this->input->post('apply_user'); if (empty($apply_user)) { $col_val.="('apply_user','".$current_user."',".$wfd_wf_sn."),"; @@ -123,7 +141,6 @@ class Index extends CI_Controller //添加审核人 $typeinfo=$this->workflow_model->get_type_list(0,$wf_wt_sn); $verify_tolist_array=$this->get_verify_admin_list($wfd_wf_sn,$group_admin[1],$typeinfo[0]->wt_linear); - //抄送邮件给指定人员 if ($wfd_wf_sn && $wfd_sn) { $data['userdata']=$this->session->userdata('admin_chtcdn'); @@ -177,6 +194,7 @@ class Index extends CI_Controller } $data['userdata']=$this->session->userdata('admin_chtcdn'); + //print_r($data['userdata']); //事务申请人信息 $userdata=$this->session->userdata('admin_chtcdn'); $flow=$this->workflow_model->get_work_list($userdata['OPI_SN'],$wv_status,$wf_sn); @@ -189,6 +207,7 @@ class Index extends CI_Controller $data[$d->wfd_key]=$d->wfd_value; $data['flow_data'][$d->wfd_key]=$d->wfd_value; } + //print_r($data); $form=$data['flow']->wt_form; $data['wf_sn']=$wf_sn; @@ -201,12 +220,16 @@ class Index extends CI_Controller //当前用户是否审核人员 0否 1是 $verify_user=$this->workflow_model->get_verify($wf_sn,0,false,50); $data['is_verify_user']=0; - foreach ($verify_user as $vu) { + // var_dump($data['userdata']);die; + if(!empty($data['userdata']['whu_uid'])){//csk2016-11-29 + foreach ($verify_user as $vu) { if ($data['userdata']['whu_uid']==$vu->wv_admin) { $data['is_verify_user']=1; break; } + } } + //用于做导航激活状态 $data['nav_type']=$nav_type; if ($nav_type=='userlist') { @@ -222,6 +245,7 @@ class Index extends CI_Controller } $data['wv_status']=$wv_status; $data['form']=$this->load->view("form/$form",$data,true); + //print_r($data); $this->load->view('n-header', $data); $this->load->view('w-nav'); $this->load->view('w-left'); @@ -313,7 +337,7 @@ class Index extends CI_Controller $namestrings=str_replace(';', ';', $namestrings); $namestrings=str_replace('(', '(', $namestrings); $namestrings=str_replace(')', ');', $namestrings); - $namestrings=str_replace('惠毅', '惠 毅', $namestrings); + //$namestrings=str_replace('惠毅', '惠 毅', $namestrings); $namestrings=str_replace("\n", ";", $namestrings); $namestrings=str_replace("\r", ";", $namestrings); $namestrings_arr=explode(';', $namestrings); @@ -336,9 +360,6 @@ class Index extends CI_Controller } if (isset($atd_sn_arr[0]->ATT_SN) && isset($epy_sn_arr[0]->EPY_ID)) { $jabtime=7; - if ($workdata[0]->OPI_Name=='周玲霞') { - $jabtime=3.5; - } //如果有自定义的考勤时间则使用自定义的数据 $kaoqin_time=$this->input->post('kaoqin_time')?$this->input->post('kaoqin_time'):''; $kaoqin_time=trim($kaoqin_time); @@ -467,6 +488,7 @@ class Index extends CI_Controller return $verify_tolist_array; } + // public function other_verify($wf_sn,$wv_status=0) { //获取当前值班名单 @@ -542,9 +564,9 @@ class Index extends CI_Controller array_multisort($datetemp3, SORT_ASC, $js_uname_list); $data['en_uname_list']=$en_uname_list; - $data['sw_uname_list']=$sw_uname_list; - $data['jd_uname_list']=$jd_uname_list; - $data['js_uname_list']=$js_uname_list; + $data['sw_uname_list']=array();//$sw_uname_list; + $data['jd_uname_list']=array();//$jd_uname_list; + $data['js_uname_list']=array();//$js_uname_list; $data['wf_sn']=$wf_sn; $data['nav_type']='rata_list'; @@ -624,6 +646,7 @@ class Index extends CI_Controller //分页 $page_flag=true; $list=$this->workflow_model->get_work_list($userdata['whu_uid'],$wv_status,false,$page_flag,false); + //print_r($list); $pages['total']=count($list);//数据总条数 $pages['pageSize']= 30;//每页展示数量 $pages['url'] = site_url("apps/workflow/index/unverify/$wv_status/");//页码链接 @@ -638,18 +661,34 @@ class Index extends CI_Controller } $datalist=$this->workflow_model->get_work_list_by_sn($task_id_str); $worklist=array(); + $wf_sn_str='0'; foreach ($datalist as $wlist) { $worklist[$wlist->wf_sn]=$wlist; + $wf_sn_str.=','.$wlist->wf_sn; } + $data['list']=$worklist; - + $flow_data=$this->workflow_model->get_work_flow_data($wf_sn_str); + + $f_datas=array(); + foreach ($flow_data as $k => $f) { + $f_datas[$f->wfd_wf_sn][$f->wfd_key]=$f->wfd_value; + } + $data['f_datas']=$f_datas; + $data['nav_type']='verify'; $data['left_nav']=$wv_status==0?'unverify':'verify'; $data['wv_status']=$wv_status; + //print_r($data); if ($wv_status==1) { $data['nav_type']='verifyed'; } - + // var_dump($data["list"]); + // foreach ($data["list"] as $key => $v) { + // echo $v->wf_status; + // echo $v->isverify; + // echo "<br>"; + // } $this->load->view('n-header', $data); $this->load->view('w-nav'); $this->load->view('w-left'); @@ -847,10 +886,11 @@ class Index extends CI_Controller $data['rolelist']=$this->workflow_model->get_department_list(2); //用户列表 $data['userlist']=$this->workflow_model->get_user_list(); + if ($whu_uid!==false) { $data['userinfo']=$this->workflow_model->get_user_list($whu_uid); - $data['userinfo']=$data['userinfo'][0]; - $data['userrole']=array_filter(explode(',', $data['userinfo']->role)); + $data['userinfo']=$data['userinfo'][0]; + $data['userrole']=array_filter(explode(',', $data['userinfo']->role)); } $this->load->view('n-header', $data); $this->load->view('w-nav'); @@ -863,6 +903,7 @@ class Index extends CI_Controller //员工资料更新 public function user_edit() { + $type=$this->input->post('type'); $whu_role=$this->input->post('userrole'); $whu_uname=$this->input->post('whu_uname'); $whu_email=$this->input->post('whu_email'); @@ -870,11 +911,19 @@ class Index extends CI_Controller $department=$this->input->post('department'); $role=!empty($whu_role)?implode(',',$this->input->post('userrole')):NULL; $whu_uid=$this->input->post('whu_uid'); - $result=$this->workflow_model->update_webuser($whu_uname,$whu_email,$whu_ip,$department,$role,$whu_uid); + if($type == 'add'){ + $result = $result=$this->workflow_model->add_webuser($whu_uname,$whu_email,$whu_ip,$department,$role,$whu_uid); + }else if($type == 'delete'){ + $result=$this->workflow_model->delete_webuser($whu_uname,$whu_uid); + + }else if($type == 'update'){ + $result=$this->workflow_model->update_webuser($whu_uname,$whu_email,$whu_ip,$department,$role,$whu_uid); + } + if ($result) { - echo json_encode(array('status'=>'ok','msg'=>'保存成功!')); + echo json_encode(array('status'=>'ok','msg'=>'操作成功!')); }else{ - echo json_encode(array('status'=>'no','msg'=>'保存失败!')); + echo json_encode(array('status'=>'no','msg'=>'操作失败!')); } } @@ -1001,8 +1050,8 @@ class Index extends CI_Controller //发送邮件 $mail_tpl='rota.php'; - $subject='电子商务部'.date('n',$wf_time).'月值班安排'; - $html='各位同事,<br>以下是电子商务部'.date('Y',$wf_time).'年'.date('n',$wf_time).'月值班安排,请大家<span style="color:red;">做好提醒</span>,按相关值班规定值班。<br>为方便统计加班小时数,请记得到<span style="color:red;">值班记录系统</span>填写值班记录,自行调班的同事请记得到<span style="color:red;">值班记录系统</span>里面更改。<br>谢谢!'; + $subject='海纳国旅'.date('n',$wf_time).'月值班安排'; + $html='各位同事,<br>以下是海纳国旅'.date('Y',$wf_time).'年'.date('n',$wf_time).'月值班安排,请大家<span style="color:red;">做好提醒</span>,按相关值班规定值班。<br>为方便统计加班小时数,请记得到<span style="color:red;">值班记录系统</span>填写值班记录,自行调班的同事请记得到<span style="color:red;">值班记录系统</span>里面更改。<br>谢谢!'; $mailbody=$html.'<br><br>'.$this->load->view("mail_tpl/$mail_tpl",$mail_data,true); //发送人信息 @@ -1032,13 +1081,16 @@ class Index extends CI_Controller if ($this->workflow_model->delete_wfd($wf_sn)) { $col_val=''; foreach ($this->input->post() as $wfd_key => $wfd_value) { - $col_val.="('".trim($wfd_key)."','".$wfd_value."',".$wf_sn."),"; + // $col_val.="('".trim($wfd_key)."','".$wfd_value."',".$wf_sn."),"; + + $col_val.="('".trim($wfd_key)."','".chop($wfd_value)."',".$wf_sn."),";//csk 2016-9-22 去掉末尾的换行和空格 } $apply_user=$this->input->post('apply_user'); if (empty($apply_user)) { $col_val.="('apply_user','".$current_user."',".$wf_sn."),"; } $col_val=substr($col_val, 0, -1); + $wfd_sn=$this->workflow_model->add_work_data($col_val); } @@ -1053,6 +1105,7 @@ class Index extends CI_Controller if ($this->session->userdata('verify_referer')) { $verify_referer_url=$this->session->userdata('verify_referer'); } + echo json_encode(array('status'=>'ok_go','msg'=>'更新成功!','url'=>$verify_referer_url)); } @@ -1413,5 +1466,6 @@ class Index extends CI_Controller } $this->load->view('index/print_text', $data); } - + + } diff --git a/webht/third_party/workflow/models/workflow_model.php b/webht/third_party/workflow/models/workflow_model.php index 3da7b4b6..da3c6732 100644 --- a/webht/third_party/workflow/models/workflow_model.php +++ b/webht/third_party/workflow/models/workflow_model.php @@ -100,7 +100,7 @@ class Workflow_model extends CI_Model { } public function get_work_list($wv_admin,$wv_status,$wf_sn=false,$page_flag=false,$wv_actived=-1) - { + {// $map=" AND wt_form!='rota.php' AND (wv_admin=258 or wv_admin='$wv_admin')"; if (!$wv_actived) { $map.=" AND wv_actived!=-1 "; @@ -117,7 +117,7 @@ class Workflow_model extends CI_Model { left join work_type on wf_wt_sn=wt_sn left join OperatorInfo on wf_user=OPI_SN WHERE wv_status=? $map - ORDER BY wf_time desc"; + ORDER BY wf_time desc"; $query = $this->HT->query($sql, array($wv_status)); $result=$query->result(); return $result; @@ -411,6 +411,34 @@ class Workflow_model extends CI_Model { $query = $this->HT->query($sql,array($whu_uname,$whu_email,$whu_ip,$department,$role,$whu_uid)); return $query; } + + public function add_webuser($whu_uname,$whu_email,$whu_ip,$department,$role) + { + $status = 1; + $sql="INSERT INTO webht_user + (whu_uname, + whu_email, + whu_ip, + whu_status, + department, + role) + VALUES + (?,?,?,?,?,?)"; + $query = $this->HT->query($sql,array($whu_uname,$whu_email,$whu_ip,$status,$department,$role)); + return $query; + } + + public function delete_webuser($whu_uname,$whu_uid) + { + $sql="DELETE FROM + webht_user + WHERE + whu_uname=? + and + whu_uid=?"; + $query = $this->HT->query($sql,array($whu_uname,$whu_uid)); + return $query; + } public function delete_wt($wt_sn,$wt_isdelete=1) { @@ -437,5 +465,10 @@ class Workflow_model extends CI_Model { $query=$this->HT->query($sql, array($wv_wf_sn)); return $query; } + + public function delete_test(){ + $sql = "delete from work_flow_data where wfd_key like '%201905%'"; + $query=$this->HT->query($sql); + } } \ No newline at end of file diff --git a/webht/third_party/workflow/views/form/rota.php b/webht/third_party/workflow/views/form/rota.php index 91ae4018..8d36ad27 100644 --- a/webht/third_party/workflow/views/form/rota.php +++ b/webht/third_party/workflow/views/form/rota.php @@ -5,7 +5,7 @@ <form class="form-add-watch col-xs-24 nopadding" method="post" style="" action="<?php echo site_url('apps/workflow/index/do_add_work'); ?>"> <?php - $year=isset($wf_time)?date('Y',strtotime($wf_time)):date('Y'); + $year=isset($wf_time)?date('Y',strtotime($wf_time)):date('Y',strtotime("+1 month")); $month=isset($wf_time)?date('m',strtotime($wf_time)):date('m',strtotime("+1 month")); $month_n=isset($wf_time)?date('n',strtotime($wf_time)):date('n',strtotime("+1 month")); $days=cal_days_in_month(CAL_GREGORIAN,$month,$year); @@ -39,20 +39,25 @@ <th width="120">CH销售</th> <th width="60">CT</th> <th width="60">商务</th> - <th width="60">德语</th> <th colspan="2">国际</th> <th width="80">技术</th> <th width="70">计调</th> + <th width="70">APP</th> + <th width="70">目的地</th> + <th width="70">亚洲事业部</th> </tr> <tr class="rotatable_bg"> <th colspan="2">值班时间</th> <th>12点-13点</th> <th colspan="2">9:30-12:00,13:00-17:00</th> - <th colspan="2">10:00-16:00</th> + <th colspan="1">10:00-16:00</th> <th width="60">到办公室</th> <th width="120">VPN</th> <th>技术远程值班</th> <th>无团电话值班</th> + <th>VPN(8:30-23:00)</th> + <th>VPN(8:30-23:00)</th> + <th>VPN(8:30-23:00)</th> </tr> <?php for ($i=1; $i <= $days; $i++) { ?> <?php @@ -63,17 +68,19 @@ $ch_uname=$flow_data['ch_uname_'.$ymd]; $ct_uname=$flow_data['ct_uname_'.$ymd]; $sw_uname=$flow_data['sw_uname_'.$ymd]; - $de_uname=$flow_data['de_uname_'.$ymd]; $eu_uname=$flow_data['eu_uname_'.$ymd]; $vpn_uname=$flow_data['vpn_uname_'.$ymd]; $js_uname=$flow_data['js_uname_'.$ymd]; $jd_uname=$flow_data['jd_uname_'.$ymd]; + $app_uname=isset($flow_data['app_uname_'.$ymd])?$flow_data['app_uname_'.$ymd]:''; + $trippest_uname=isset($flow_data['trippest_uname_'.$ymd])?$flow_data['trippest_uname_'.$ymd]:''; + $ah_uname=isset($flow_data['ah_uname_'.$ymd])?$flow_data['ah_uname_'.$ymd]:''; isset($flow_data['weekend_'.$ymd])? $weekend=$flow_data['weekend_'.$ymd]:$weekend=0; } ?> <tr class="rota_tr_box <?php if((!isset($wf_sn) && ($week_no==0 || $week_no==6)) || (isset($weekend) && $weekend==1)) echo 'rotatable_bg'; ?>"> <td> - <input class="<?php if($userdata['whu_isadmin']!=1) echo 'hidden'; ?>" type="checkbox" name="weekend_<?php echo $year.$month.$i;?>" value="1" <?php if(isset($weekend) && $weekend==1) echo 'checked'; ?>> + <input class="<?php if(@$userdata['whu_isadmin']!=1) echo 'hidden'; ?>" type="checkbox" name="weekend_<?php echo $year.$month.$i;?>" value="1" <?php if(isset($weekend) && $weekend==1) echo 'checked'; ?>> <?php echo $weekarray[$week_no]; ?> </td> <td><?php echo $month_n.'月'.$i."日"; ?></td> @@ -89,9 +96,6 @@ <td> <textarea title="双击我进行修改" class="form-control" name="sw_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($sw_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($sw_uname))echo $sw_uname; ?></textarea> </td> - <td> - <textarea title="双击我进行修改" class="form-control" name="de_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($de_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($de_uname))echo $de_uname; ?></textarea> - </td> <td> <textarea title="双击我进行修改" class="form-control" name="eu_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($eu_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($eu_uname))echo $eu_uname; ?></textarea> </td> @@ -104,6 +108,15 @@ <td> <textarea title="双击我进行修改" class="form-control" name="jd_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($jd_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($jd_uname))echo $jd_uname; ?></textarea> </td> + <td> + <textarea title="双击我进行修改" class="form-control" name="app_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($app_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($app_uname))echo $app_uname; ?></textarea> + </td> + <td> + <textarea title="双击我进行修改" class="form-control" name="trippest_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($trippest_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($trippest_uname))echo $trippest_uname; ?></textarea> + </td> + <td> + <textarea title="双击我进行修改" class="form-control" name="ah_uname_<?php echo $year.$month.$i;?>" <?php if(isset($wf_sn) && $userdata['whu_isadmin']!=1 && stripos($ah_uname, $userdata['OPI_Name'])===false) echo 'readonly';?>><?php if(isset($ah_uname))echo $ah_uname; ?></textarea> + </td> </tr> <?php } ?> </table> diff --git a/webht/third_party/workflow/views/index/rata_list.php b/webht/third_party/workflow/views/index/rata_list.php index f897cfee..37e506a3 100644 --- a/webht/third_party/workflow/views/index/rata_list.php +++ b/webht/third_party/workflow/views/index/rata_list.php @@ -5,7 +5,8 @@ <th>提交时间</th> <th>状态</th> <th>操作</th> - <th class="<?php $userdata=$this->session->userdata('admin_chtcdn'); if ($userdata['whu_isadmin']!=1) echo 'hidden'; ?>">其他</th> + <th>其他</th> + <?php $userdata=$this->session->userdata('admin_chtcdn'); ?> </tr> <?php foreach ($list as $key => $v) { ?> <tr> @@ -23,7 +24,11 @@ <a href="javascript:void(0);" class="ajax-link" data-href="<?php echo site_url('apps/workflow/index/dalete_work_flow/'.$v->wf_sn); ?>">删除</a> <?php } ?> </td> - <td class="<?php if ($userdata['whu_isadmin']!=1) echo 'hidden'; ?>"><a href="<?php echo site_url('apps/workflow/index/other_verify/'.$v->wf_sn.'/'.$v->wf_status); ?>">不用发邮件记录考勤的员工</a></td> + <td> + <?php if ($userdata['whu_isadmin']==1) { ?> + <a href="<?php echo site_url('apps/workflow/index/other_verify/'.$v->wf_sn); ?>">中午值班审核</a> + <?php } ?> + </td> </tr> <?php } ?> </tbody> diff --git a/webht/third_party/workflow/views/index/unverify.php b/webht/third_party/workflow/views/index/unverify.php index e37e0edc..98e05a90 100644 --- a/webht/third_party/workflow/views/index/unverify.php +++ b/webht/third_party/workflow/views/index/unverify.php @@ -6,9 +6,14 @@ <th>状态</th> <th>操作</th> </tr> - <?php foreach ($list as $key => $v) { ?> + <?php $i=1;foreach ($list as $key => $v) { ?> <tr> - <td class="hidden-xs" scope="row"><?php echo ($key+1); ?></td> + <td class="hidden-xs" scope="row"> + <?php if($left_nav && $left_nav!='userlist'){ ?> + <input type="checkbox" class="work_flow_item" data-key="<?php echo $i; ?>" data-wfsn="<?php echo $v->wf_sn; ?>" data-mailtitle="<?php echo $f_datas[$v->wf_sn]['mail_title']; ?>" data-kaoqintime="<?php if($v->wt_userdefined==1) echo isset($f_datas[$v->wf_sn]['rest_days'])?$f_datas[$v->wf_sn]['rest_days']*7+$f_datas[$v->wf_sn]['rest_days2']:''; ?>"> + <?php } ?> + <?php echo ($i++); ?> + </td> <td><?php echo $v->wt_name.'('.$v->OPI_Name.')'; ?></td> <td><?php echo date('Y-m-d H:i:s',$v->wf_time); ?></td> <td><?php $status=$v->wf_status==0? ($v->isverify!=1?'还没处理':'处理中'):'已审核';echo $status; ?></td> @@ -20,6 +25,15 @@ </td> </tr> <?php } ?> + <tr> + <td colspan="5"> + <label style="padding-right:20px;"><input type="checkbox" id="checkall_item"> 全选</label> + <?php $userdata=$this->session->userdata('admin_chtcdn'); if (isset($left_nav) && $left_nav=='unverify' && ($userdata['OPI_Name']=='侯敏' || $userdata['OPI_Name']=='王婷' )) { ?> + <a class="btn btn-default verify_all_item" href="javascript:void(0);" data-status="0" data-lastkey="0">批量审核</a> + <a class="btn btn-default verify_all_item" href="javascript:void(0);" data-status="1" data-lastkey="0">审核不通过</a> + <?php } ?> + </td> + </tr> </tbody> </table> @@ -29,4 +43,52 @@ <?php echo $pageinfo['htmls']; ?> </ul> </nav> -</div> \ No newline at end of file +</div> + +<script> + +$("#checkall_item").click(function(){ + if ($(this).attr("checked")) { + $(".work_flow_item").attr("checked",'checked'); + }else{ + $(".work_flow_item").removeAttr("checked"); + } +}); + +var selected_item=0; +$(".verify_all_item").click(function(event) { + $(this).text('正在处理,请耐心等待...'); + var $that=$(this); + + $(".work_flow_item").each(function(){ + if ($(this).attr("checked")) { + selected_item=$(this).attr('data-key'); + }; + }); + $that.attr("data-lastkey",selected_item); + + $(".work_flow_item").each(function(){ + if ($(this).attr("checked")) { + var wv_wf_sn=$(this).attr('data-wfsn'); + var wv_comment=''; + var mail_title=$(this).attr('data-mailtitle'); + var kaoqin_time=$(this).attr('data-kaoqintime'); + if (kaoqin_time=='') { + var data={"wv_wf_sn":wv_wf_sn,"wv_comment":wv_comment,"mail_title":mail_title}; + }else{ + var data={"wv_wf_sn":wv_wf_sn,"wv_comment":wv_comment,"mail_title":mail_title,"kaoqin_time":kaoqin_time}; + } + var wv_status=$that.attr('data-status'); + var url="<?php echo site_url('apps/workflow/index/do_verify'); ?>"+'/'+wv_status; + var $this=$(this); + $.post(url,data,function(res){ + if ($that.attr("data-lastkey")==$this.attr('data-key')) { + $that.text('已处理完成'); + }; + }); + }; + + }); +}); + +</script> \ No newline at end of file diff --git a/webht/third_party/workflow/views/index/user_manage.php b/webht/third_party/workflow/views/index/user_manage.php index e34bf2e7..4fde522d 100644 --- a/webht/third_party/workflow/views/index/user_manage.php +++ b/webht/third_party/workflow/views/index/user_manage.php @@ -20,7 +20,14 @@ <div class="col-xs-19"> <div class="col-xs-24 btn-lg"></div> <legend>员工资料编辑</legend> - <form class="form-horizontal form_user_edit" method="post" action="<?php echo site_url('apps/workflow/index/user_edit'); ?>"> + <ul class="nav nav-tabs" role="tablist" style="margin-bottom:40px"> + <li role="presentation" class="active"><a href="#add" aria-controls="add" role="tab" data-toggle="tab" onclick="location.href='<?php echo site_url('apps/workflow/index/user_manage')?>'">新增</a></li> + <li role="presentation"><a href="#delete" aria-controls="delete" role="tab" data-toggle="tab">删除</a></li> + <li role="presentation"><a href="#update" aria-controls="update" role="tab" data-toggle="tab">修改</a></li> + </ul> + <div class="tab-content"> + <div role="tabpanel" class="tab-pane active" id="add"> + <form class="form-horizontal form_user_add" method="post" action="<?php echo site_url('apps/workflow/index/user_edit'); ?>"> <div class="form-group"> <label class="col-sm-4 control-label">姓名</label> <div class="col-sm-10"> @@ -63,16 +70,117 @@ <div class="form-group"> <div class="btn-group col-sm-offset-4 col-xs-5"> <input type="hidden" name="whu_uid" value="<?php if(isset($userinfo)) echo $userinfo->whu_uid; ?>"> - <button type="button" class="btn btn-danger" onclick="ajaxSubmit('.form_user_edit');">保存</button> - <button class="btn dropdown-toggle btn-danger col-xs-5" data-toggle="dropdown"> - <span class="caret"></span> - </button> - <ul class="dropdown-menu"> - <li><a href="javascript:void(0);" onclick="alert('现在还不能删人')">删除</a></li> - </ul> + <input type="hidden" name="type" value="add"> + <button type="button" class="btn btn-danger" onclick="ajaxSubmit('.form_user_add');">保存</button> + </div> </div> </form> + </div> + <div role="tabpanel" class="tab-pane" id="delete"> + <form class="form-horizontal form_user_delete" method="post" action="<?php echo site_url('apps/workflow/index/user_edit'); ?>"> + <div class="form-group"> + <label class="col-sm-4 control-label">姓名</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_uname" value="<?php if(isset($userinfo)) echo $userinfo->whu_uname; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">Email</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_email" value="<?php if(isset($userinfo)) echo $userinfo->whu_email; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">IP地址</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_ip" value="<?php if(isset($userinfo)) echo $userinfo->whu_ip; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">事业部</label> + <div class="col-sm-10"> + <select class="form-control" name="department"> + <?php foreach ($typelist as $type) { ?> + <option value="<?php echo $type->wt_sn; ?>" <?php if(isset($userinfo) && $type->wt_sn==$userinfo->department) echo 'selected'; ?>><?php echo $type->wt_name; ?></option> + <?php } ?> + </select> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">职务</label> + <div class="col-sm-20"> + <div class="checkbox"> + <?php foreach ($rolelist as $role) { ?> + <label><input type="checkbox" name="userrole[]" value="<?php echo $role->wt_sn; ?>" <?php if(isset($userrole) && in_array($role->wt_sn, $userrole)) echo 'checked'; ?>> <?php echo $role->wt_name; ?></label> + <?php } ?> + </div> + </div> + </div> + + <div class="form-group"> + <div class="btn-group col-sm-offset-4 col-xs-5"> + <input type="hidden" name="whu_uid" value="<?php if(isset($userinfo)) echo $userinfo->whu_uid; ?>"> + <input type="hidden" name="type" value="delete"> + <button type="button" class="btn btn-danger" onclick="ajaxSubmit('.form_user_delete');">删除</button> + + </div> + </div> + </form></div> + <div role="tabpanel" class="tab-pane" id="update"> + <form class="form-horizontal form_user_update" method="post" action="<?php echo site_url('apps/workflow/index/user_edit'); ?>"> + <div class="form-group"> + <label class="col-sm-4 control-label">姓名</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_uname" value="<?php if(isset($userinfo)) echo $userinfo->whu_uname; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">Email</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_email" value="<?php if(isset($userinfo)) echo $userinfo->whu_email; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">IP地址</label> + <div class="col-sm-10"> + <input type="text" class="form-control" name="whu_ip" value="<?php if(isset($userinfo)) echo $userinfo->whu_ip; ?>"> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">事业部</label> + <div class="col-sm-10"> + <select class="form-control" name="department"> + <?php foreach ($typelist as $type) { ?> + <option value="<?php echo $type->wt_sn; ?>" <?php if(isset($userinfo) && $type->wt_sn==$userinfo->department) echo 'selected'; ?>><?php echo $type->wt_name; ?></option> + <?php } ?> + </select> + </div> + </div> + <div class="form-group"> + <label class="col-sm-4 control-label">职务</label> + <div class="col-sm-20"> + <div class="checkbox"> + <?php foreach ($rolelist as $role) { ?> + <label><input type="checkbox" name="userrole[]" value="<?php echo $role->wt_sn; ?>" <?php if(isset($userrole) && in_array($role->wt_sn, $userrole)) echo 'checked'; ?>> <?php echo $role->wt_name; ?></label> + <?php } ?> + </div> + </div> + </div> + + <div class="form-group"> + <div class="btn-group col-sm-offset-4 col-xs-5"> + <input type="hidden" name="whu_uid" value="<?php if(isset($userinfo)) echo $userinfo->whu_uid; ?>"> + <input type="hidden" name="type" value="update"> + <button type="button" class="btn btn-danger" onclick="ajaxSubmit('.form_user_update');">修改</button> + + </div> + </div> + </form> + </div> + </div> + + </div> </div> diff --git a/webht/third_party/workflow/views/index/verify.php b/webht/third_party/workflow/views/index/verify.php index 17024a14..cb3a6ee5 100644 --- a/webht/third_party/workflow/views/index/verify.php +++ b/webht/third_party/workflow/views/index/verify.php @@ -31,9 +31,11 @@ </form> <?php } ?> <div class="col-xs-24 btn-sm"></div> - <?php if (empty($verify_data) && ($nav_type=='userlist' || $nav_type=='rata_list')) { ?> + <?php if (empty($verify_data) && ($nav_type=='userlist' || $nav_type=='rata_list')) { + if($userdata['whu_isadmin'] == '1'){ + ?> <button type="button" class="btn btn-block btn-default" onclick="$('.form-add-watch').attr('action','<?php echo site_url('apps/workflow/index/update_work'); ?>');ajaxSubmit('.form-add-watch');">保存修改</button> - <?php } ?> + <?php } }?> <?php } ?> <?php if($userdata['whu_isadmin']==1 && $left_nav=='rata_list'){ ?> <button class="btn btn-block btn-default" onclick="$('.form-add-watch').attr('action','<?php echo site_url("apps/workflow/index/send_rota_mail"); ?>');ajaxSubmit('.form-add-watch');">发送邮件</button> diff --git a/webht/third_party/workflow/views/mail_tpl/rota.php b/webht/third_party/workflow/views/mail_tpl/rota.php index 9d92193a..83bbc015 100644 --- a/webht/third_party/workflow/views/mail_tpl/rota.php +++ b/webht/third_party/workflow/views/mail_tpl/rota.php @@ -23,6 +23,7 @@ table th,table td{padding: 5px;font-size: 12px;text-align: center;vertical-align <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" colspan="2">国际</th> <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="100">技术</th> <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="80">计调</th> + <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="80">APP</th> </tr> <tr class="rotatable_bg"> <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" height="35" colspan="2">值班时间</th> @@ -33,6 +34,7 @@ table th,table td{padding: 5px;font-size: 12px;text-align: center;vertical-align <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="150">VPN</th> <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="100">技术远程值班</th> <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="80">无团电话值班</th> + <th style="border-bottom:1px solid #aaa;border-left:1px solid #aaa;" width="80">VPN(8:30-23:00)</th> </tr> <?php for ($i=1; $i <= $days; $i++) { ?> <?php @@ -48,6 +50,7 @@ table th,table td{padding: 5px;font-size: 12px;text-align: center;vertical-align $vpn_uname=$flow_data['vpn_uname_'.$ymd]; $js_uname=$flow_data['js_uname_'.$ymd]; $jd_uname=$flow_data['jd_uname_'.$ymd]; + $app_uname=isset($flow_data['app_uname_'.$ymd])?$flow_data['app_uname_'.$ymd]:''; isset($flow_data['weekend_'.$ymd])? $weekend=$flow_data['weekend_'.$ymd]:$weekend=0; } ?> @@ -63,6 +66,7 @@ table th,table td{padding: 5px;font-size: 12px;text-align: center;vertical-align <td style="border-left:1px solid #aaa;border-bottom:1px solid #aaa;"></p><?php if(isset($vpn_uname))echo $vpn_uname;?></p></td> <td style="border-left:1px solid #aaa;border-bottom:1px solid #aaa;"></p><?php if(isset($js_uname))echo $js_uname; ?></p></td> <td style="border-left:1px solid #aaa;border-bottom:1px solid #aaa;"></p><?php if(isset($jd_uname))echo $jd_uname; ?></p></td> + <td style="border-left:1px solid #aaa;border-bottom:1px solid #aaa;"></p><?php if(isset($app_uname))echo $app_uname; ?></p></td> </tr> <?php } ?> </table> \ No newline at end of file diff --git a/webht/third_party/workflow/views/w-left.php b/webht/third_party/workflow/views/w-left.php index f54dc2be..e4a3ce23 100644 --- a/webht/third_party/workflow/views/w-left.php +++ b/webht/third_party/workflow/views/w-left.php @@ -8,7 +8,10 @@ <li><a class="hidden-xs <?php if(isset($left_nav) && $left_nav=='unverify') echo 'active';?>" href="<?php echo site_url('apps/workflow/index/unverify'); ?>"><span class="glyphicon glyphicon-edit"></span>待审核事务</a></li> <li><a class="hidden-xs <?php if(isset($left_nav) && $left_nav=='verify') echo 'active';?>" href="<?php echo site_url('apps/workflow/index/unverify/1'); ?>"><span class="glyphicon glyphicon-saved"></span>已审核事务</a></li> <li><a class="hidden-xs <?php if(isset($left_nav) && $left_nav=='rata_list') echo 'active';?>" href="<?php echo site_url('apps/workflow/index/rata_list'); ?>"><span class="glyphicon glyphicon-edit"></span>中华游值班表</a></li> - <?php $userdata=$this->session->userdata('admin_chtcdn'); if ($userdata['whu_isadmin']==1) { ?> + <?php + $userdata=$this->session->userdata('admin_chtcdn'); + if ( !empty($userdata['whu_isadmin']) && $userdata['whu_isadmin']==1) { + ?> <li><a class="hidden-xs <?php if(isset($left_nav) && $left_nav=='type_list') echo 'active';?>" href="<?php echo site_url('apps/workflow/index/work_type_list'); ?>"><span class="glyphicon glyphicon-th"></span>管理事务类型</a></li> <li><a class="load-modal hidden-xs" href="javascript:void(0);" data-href="<?php echo site_url('apps/workflow/index/add_work_type'); ?>" data-modal="bs-worktype-modal-lg"><span class="glyphicon glyphicon-plus"></span>添加事务类型</a></li> <li><a class="hidden-xs" href="<?php echo site_url('apps/workflow/index/add_partment_type'); ?>" ><span class="glyphicon glyphicon-plus"></span>事业部分组</a></li> From 21569e4da0657b69a8b0c2a8209a5fc525b4745c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Apr 2019 11:06:34 +0800 Subject: [PATCH 296/382] =?UTF-8?q?paypal=20Trippest=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E7=9A=84=E5=8F=91=E9=80=81=E7=8A=B6=E6=80=81=E6=94=B9=E5=88=B0?= =?UTF-8?q?=E5=92=8C=E5=A4=B1=E8=B4=A5=E4=B8=80=E8=B5=B7=E5=A4=84=E7=90=86?= =?UTF-8?q?,=E9=81=BF=E5=85=8D=E5=8D=A1=E4=BD=8F=E5=85=B6=E4=BB=96?= =?UTF-8?q?=E5=8F=91=E9=80=81=E5=A4=B1=E8=B4=A5=E7=9A=84=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/models/note_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/models/note_model.php b/webht/third_party/paypal/models/note_model.php index c534e41f..0cd9ecd4 100644 --- a/webht/third_party/paypal/models/note_model.php +++ b/webht/third_party/paypal/models/note_model.php @@ -31,14 +31,14 @@ class Note_model extends CI_Model { public function unsend($topnum = 2) { $this->init(); $this->topnum = $topnum; - $this->pn_send = " AND (pn_send='unsend' OR pn_send='' OR pn_send IS NULL) "; + $this->pn_send = " AND (pn_send='unsend' OR pn_send IS NULL) "; return $this->get_list(); } public function failnote($topnum = 2) { $this->init(); $this->topnum = $topnum; - $this->pn_send = " AND pn_send='sendfail' "; + $this->pn_send = " AND (pn_send='sendfail' OR pn_send='') "; //$this->orderby = ' ORDER BY pn.pn_sn ASC '; return $this->get_list(); } From 02b64c677e6356be984c73ba4c12ee6a11fcae10 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Apr 2019 11:07:57 +0800 Subject: [PATCH 297/382] =?UTF-8?q?Alipay=20=E4=BA=A4=E6=98=93=E7=BB=93?= =?UTF-8?q?=E6=9D=9F=E7=9A=84=E5=A4=84=E7=90=86bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index f9db3a3c..9800c519 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -348,7 +348,7 @@ class AlipayTradeService extends CI_Controller foreach ($data['unsend_list'] as $item) { //已经发送的不处理,防止重复发送 - if ($item->ALI_sent == 'send') { + if ($item->ALI_sent == 'send' && empty($pn_txn_id)) { continue; } @@ -359,8 +359,7 @@ class AlipayTradeService extends CI_Controller } //只处理完成状态,其他状态由陆燕处理 - if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS") - || strcmp(trim($item->ALI_resultMsg), "TRADE_FINISHED")) { + if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")!==0 && strcmp(trim($item->ALI_resultMsg), "TRADE_FINISHED")!==0 ) { $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); continue; } From 8538378b43f84d5b5609566f16f87c45fefc1030 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Apr 2019 11:09:05 +0800 Subject: [PATCH 298/382] =?UTF-8?q?wxpay=20=E8=87=AA=E5=8A=A8=E5=BD=95?= =?UTF-8?q?=E5=85=A5=E5=92=8C=E5=8F=91=E9=80=81=E6=8F=90=E9=86=92.=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8Dbug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/PaymentService.php | 18 +++++++++--------- .../pay/controllers/WxpayService.php | 2 +- .../pay/models/Online_payment_note_model.php | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index c01d4a43..0e39d8da 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -40,10 +40,6 @@ log_message('error','send_notify begin ----'); } // 开始处理 foreach ($data['unsend_list'] as $key => $item) { - //显示处理记录 - if (empty($transaction_id)) { - echo ++$show_index . ' ' . $item->OPN_transactionId . '<br/>'; - } // 只处理完成状态 if ($item->OPN_transactionResult != 'completed') { continue; @@ -76,17 +72,17 @@ log_message('error','send_notify begin ----'); // 开始查找订单和录入 $handpick = empty($transaction_id) ? false : true; $advisor_info = $this->account_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); - $ssje = $this->account_model->get_ssje($item->OPN_orderAmount, $item->OPN_accountMethod, mb_strtoupper($item->OPN_currency)); + $ssje = $this->account_model->get_ssje($item->OPN_orderAmount, mb_strtoupper($item->OPN_currency), $item->OPN_accountMethod); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; $ht_memo = '交易号(自动录入):' . $item->OPN_transactionId; - if ( ! isset($advisor_info->ordertype)) { + if ( empty($advisor_info)) { // record fail $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'sendfail'); continue; } $COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; $update_note_column = array(); - if ($advisor_info->ordertype == 0) { + if ($advisor_info->order_type == 0) { /* 商务订单 */ if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { /* APP */ @@ -141,7 +137,7 @@ log_message('error','send_notify begin ----'); $update_note_column['OPN_accountType'] = 'B'; $update_note_column['OPN_accountStatus'] = 'recorded'; $update_note_column['OPN_accountTime'] = date('Y-m-d H:i:s'); - } elseif ($advisor_info->ordertype == 1) { + } elseif ($advisor_info->order_type == 1) { /* 传统 */ $gai_sn = $this->account_model->add_tour_account_info( $COLI_SN, @@ -194,8 +190,12 @@ log_message('error','send_notify begin ----'); $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'payment note', 'payment note'); //添加邮件发送记录 end - $this->note_model->update_send($item->OPN_SN, $item->pn_txn_id, 'send'); + $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'send'); + //显示处理记录 + if (empty($transaction_id)) { + echo ++$show_index . ' ' . $item->OPN_transactionId . '<br/>'; + } } return; diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php index 5f7f8e74..1f39a0ed 100644 --- a/webht/third_party/pay/controllers/WxpayService.php +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -100,7 +100,7 @@ log_message('error','notify begin ----'); return false; } if ($this->make_sign($xml_arr) !== $xml_arr['sign']) { - log_message('error','Wxpay notify error: sign.'); + log_message('error','Wxpay notify error: sign.' . $this->make_sign($xml_arr)); return false; } if ($this->wx_site_config['app_id'] !== $xml_arr['appid']) { diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php index 5d0205e3..e4eefeea 100644 --- a/webht/third_party/pay/models/Online_payment_note_model.php +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -35,7 +35,7 @@ class Online_payment_note_model extends CI_Model { //设置订单号 public function set_invoice($id, $pn_invoice) { - $column = array("OPN_orderId" => $send); + $column = array("OPN_orderId" => $pn_invoice); $where = " OPN_SN=" . $id; return $this->update_note($where, $column); } From cf47bc32b911fd2c6cd3c5879a4e98443c9190b2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Apr 2019 12:02:10 +0800 Subject: [PATCH 299/382] =?UTF-8?q?paypal=20Trippest=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E7=9A=84=E5=BD=95=E5=85=A5=E7=8A=B6=E6=80=81=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 95d898fa..3c2bdb67 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1325,6 +1325,9 @@ class Index extends CI_Controller { $orderid_info = $this->analysis_orderid($data['note']->pn_invoice); if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'TP') { + $orderid_info->ordertype = 'B'; + } if ($orderid_info->ordertype === 'T') { $data['gai_info'] = $this->Paypal_model->get_money_t($pn_txn_id); } elseif ($orderid_info->ordertype === 'B') { @@ -1337,6 +1340,9 @@ class Index extends CI_Controller { if ($neworder !== null) { $neworder_id = $this->analysis_orderid($neworder); $neworder_id = json_decode($neworder_id); + if ($neworder_id->ordertype === 'TP') { + $neworder_id->ordertype = 'B'; + } if ( ! empty($neworder_id)) { $data['order_info'] = $this->Paypal_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype); } From 9cef2510b497e8c094ca1853bd0081bfa2802aeb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 26 Apr 2019 17:28:03 +0800 Subject: [PATCH 300/382] =?UTF-8?q?=E6=94=B6=E6=AC=BE:=E5=A4=96=E8=81=94?= =?UTF-8?q?=E9=82=AE=E4=BB=B6=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/PaymentService.php | 25 +++++++++++--- .../pay/models/Online_payment_note_model.php | 34 +++++++++---------- webht/third_party/pay/views/mail_advisor.php | 1 + 3 files changed, 39 insertions(+), 21 deletions(-) create mode 100644 webht/third_party/pay/views/mail_advisor.php diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index 0e39d8da..272a86be 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -20,6 +20,24 @@ class PaymentService extends CI_Controller { } + public function note_list() + { + $this->permission->is_admin(true); + $data = array(); + // $data["paytext"] = $this->payment_status(); + $data["method_name"] = $this->input->get_post("method_name"); + $data["keywords"] = $this->input->get_post("keywords"); + $data["date"] = $this->input->get_post("date"); + empty($data['date']) ? $data['date'] = date('Y-m-d') : false; + if (!empty($data['keywords'])) { + $data['notelist'] = $this->note_model->search_key($data['keywords']); + } else { + $data['notelist'] = $this->note_model->search_date($data['date']); + } + $this->load->view("iPayLinks_list",$data); + return; + } + public function send_notify($transaction_id=NULL, $old_ssje=NULL) { log_message('error','send_notify begin ----'); @@ -183,7 +201,7 @@ log_message('error','send_notify begin ----'); $toName = !empty($opi_firstname) ? $opi_firstname : ''; $toEmail = !empty($opi_email) ? $opi_email : ''; $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->OPN_orderAmount . $item->OPN_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $body = $this->load->view('mail_advisor', $item, true); //$item->pn_memo; $M_RelatedInfo = $item->OPN_SN; $M_AddTime = $item->OPN_completeTime; $M_State = 0; @@ -203,6 +221,7 @@ log_message('error','send_notify begin ----'); } /** 支付方式参数对应的配置文件名 */ + /** @Deprecated */ public function method_name($name) { $config_name = 'paypal'; @@ -246,14 +265,12 @@ log_message('error','send_notify begin ----'); case '15016': // wxpay $orderid_info = analysis_orderid($content_obj->out_trade_no); break; - + // TODO case '15018': // iPaylinks break; - case '15015': // alipay break; - default: # code... break; diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php index e4eefeea..7d5a9c4a 100644 --- a/webht/third_party/pay/models/Online_payment_note_model.php +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -40,6 +40,23 @@ class Online_payment_note_model extends CI_Model { return $this->update_note($where, $column); } + public function unsend_note($num=2) + { + $this->init_query(); + $this->topnum = $num; + $this->send = " AND (OPN_noticeSendStatus='unsend' OR OPN_noticeSendStatus='' OR OPN_noticeSendStatus IS NULL) "; + return $this->query_note(); + } + + public function sendfail_note($num=2) + { + $this->init_query(); + $this->topnum = $num; + $this->send = " AND OPN_noticeSendStatus='sendfail' "; + return $this->query_note(); + } + + public $topnum = false; public $orderby = false; public $send = false; @@ -83,23 +100,6 @@ class Online_payment_note_model extends CI_Model { return $this->query_note(); } - public function unsend_note($num=2) - { - $this->init_query(); - $this->topnum = $num; - $this->send = " AND (OPN_noticeSendStatus='unsend' OR OPN_noticeSendStatus='' OR OPN_noticeSendStatus IS NULL) "; - return $this->query_note(); - } - - public function sendfail_note($num=2) - { - $this->init_query(); - $this->topnum = $num; - $this->send = " AND OPN_noticeSendStatus='sendfail' "; - return $this->query_note(); - } - - } diff --git a/webht/third_party/pay/views/mail_advisor.php b/webht/third_party/pay/views/mail_advisor.php new file mode 100644 index 00000000..272340c6 --- /dev/null +++ b/webht/third_party/pay/views/mail_advisor.php @@ -0,0 +1 @@ +<html> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"></head> <body style="font-size: 12px;font-family: arial,helvetica,sans-serif;margin-top:0;margin-bottom:0;"> <div class=ppmail> <table align=center border=0 cellpadding=0 cellspacing=0 width=100%> <tbody> <tr valign=top> <td width=100%> <table align=center border=0 cellpadding=0 cellspacing=0 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;" width=100%> <tbody> <tr valign=top> <td> <?php $logo_path = ''; switch (strval($OPN_accountMethod)) { case '15002': case '15010': $logo_path = 'https://www.mycht.cn/css/images/paypal_logo.gif'; break; case '15018': $logo_path = 'https://www.ipaylinks.com/img/common/logo-en.png'; break; case '15016': $logo_path = 'https://www.mycht.cn/css/images/wepaylogo.png'; break; case '15015': $logo_path = 'https://data.chinahighlights.com/pic/alipay_logo.png'; break; default: break; } ?> <img src="<?php echo $logo_path; ?>" border=0 height=55 alt="payment logo"> </td> <td valign=middle align=right> <?php echo $OPN_completeTime;?> <br>Transaction ID:&nbsp;&nbsp; <?php echo $OPN_transactionId;?> </td> </tr> </tbody> </table> <div style="margin-top: 10px;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <span style="color:#333333 !important;font-weight:bold;font-family: arial,helvetica,sans-serif;">Hello Guilin China International Travel Service Co.,Ltd,</span> <br> <span style=font-size:14px;color:#C88039;font-weight:bold;text-decoration:none;>You received a payment of <?php echo $OPN_orderAmount;?> <?php echo $OPN_currency;?> </span> <br> <table cellpadding=5 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <tbody> <tr> <td valign=top> <span style=font-weight:bold;color:#333333;>Seller Protection-</span> <span style="color: #4c8f3a;"> </span> </td> <td> </td> </tr> </tbody> </table> <div style="margin-top:0px;border-bottom:1px solid #aaaaaa;"> </div> <table border=0 cellpadding=0 cellspacing=0 style="color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px; margin-bottom:5px;" width=98% align=left> <tbody> <tr> <td style=padding-top:5px; valign=top width=50% align=left> <span style=color:#333333;font-weight:bold;>Buyer</span> <br> <?php echo $OPN_payerName;?> <br> <?php echo $OPN_payerEmail;?> <br> </td> <td style=padding-top:5px; valign=top> </td> </tr> </tbody> </table> <table align=center border=0 cellpadding=0 cellspacing=0 style="clear:both;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;margin-top:5px;" width=100%> <tbody> <tr> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=330 align=left>Description</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=80 align=right>Amount</td> </tr> <tr> <td style=padding:10px; width=330 align=left> <?php echo $OPN_orderId;?> <br> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=80 align=right> <?php echo $OPN_orderAmount;?> <?php echo $OPN_currency;?> </td> </tr> </tbody> </table> </tr> </tbody> </table> </div> </body> </html> From aecdf6eddf986666a1db385e09c354687184741e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 29 Apr 2019 11:56:55 +0800 Subject: [PATCH 301/382] =?UTF-8?q?wxpay=20=E6=94=B6=E6=AC=BE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=A4=84=E7=90=86;=E6=94=B6=E6=AC=BE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5=E5=88=97=E8=A1=A8;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/PaymentService.php | 127 ++++++++++++++++-- .../models/Online_payment_account_model.php | 36 ++++- .../pay/models/Online_payment_note_model.php | 49 ++++++- 3 files changed, 200 insertions(+), 12 deletions(-) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index 272a86be..bf6180b6 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -1,8 +1,6 @@ <?php defined('BASEPATH') OR exit('No direct script access allowed'); -// global $__PAYMENT_METHOD_CODE__; - class PaymentService extends CI_Controller { public function __construct(){ @@ -17,7 +15,6 @@ class PaymentService extends CI_Controller { public function index() { - } public function note_list() @@ -34,19 +31,36 @@ class PaymentService extends CI_Controller { } else { $data['notelist'] = $this->note_model->search_date($data['date']); } - $this->load->view("iPayLinks_list",$data); + + /** + * 导出记录用的记录节点 + * TODO + */ + // $data['record_flags'] = $this->note_model->list_export_record(); + + $this->load->view("payment_list",$data); return; } - public function send_notify($transaction_id=NULL, $old_ssje=NULL) + public function note_faillist() + { + $this->permission->is_admin(true); + $data = array(); + $data['date'] = date('Y-m-d'); + $data['notelist'] = $this->note_model->failnote(100); + $this->load->view("payment_list",$data); + return; + } + + public function send_notify($opn_id=NULL, $old_ssje=NULL) { log_message('error','send_notify begin ----'); // exit(); $data = array(); $show_index = 0; //优先处理指定的交易号,用于修正交易号直接发送通知 - if ( ! empty($transaction_id)) { - $data['unsend_list'] = $this->note_model->get_note($transaction_id); + if ( ! empty($opn_id)) { + $data['unsend_list'] = $this->note_model->get_note($opn_id); } // 待处理的 if (empty($data['unsend_list'])) { @@ -88,7 +102,7 @@ log_message('error','send_notify begin ----'); } // 开始查找订单和录入 - $handpick = empty($transaction_id) ? false : true; + $handpick = empty($opn_id) ? false : true; $advisor_info = $this->account_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); $ssje = $this->account_model->get_ssje($item->OPN_orderAmount, mb_strtoupper($item->OPN_currency), $item->OPN_accountMethod); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; @@ -207,11 +221,12 @@ log_message('error','send_notify begin ----'); $M_State = 0; $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'payment note', 'payment note'); //添加邮件发送记录 end + // 2. 给客人发邮件,通知账单 todo ?? 是否需要 $this->note_model->update_send($item->OPN_SN, $item->OPN_transactionId, 'send'); //显示处理记录 - if (empty($transaction_id)) { + if (empty($opn_id)) { echo ++$show_index . ' ' . $item->OPN_transactionId . '<br/>'; } @@ -278,5 +293,99 @@ log_message('error','send_notify begin ----'); return $orderid_info; } + public function convert_send_status() + { + # code... + } + + public function gai_modal($pn_id = null, $neworder=null) + { + $this->permission->is_admin(true); + $data = array(); + $note = $this->note_model->get_note($pn_id); + $data['note'] = $note[0]; + $data['order_info'] = NULL; + $pn_invoice = $data['note']->OPN_orderId ? $data['note']->OPN_orderId : $data['note']->OPN_rawOrderId; + $pn_txn_id = $data['note']->OPN_transactionId; + $orderid_info = analysis_orderid($pn_invoice); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $data['order_info'] = $this->account_model->get_order($orderid_info->orderid, true, $orderid_info->ordertype); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->account_model->get_money_t($pn_txn_id); + } elseif ($orderid_info->ordertype === 'B' || $orderid_info->ordertype === 'TP') { + $data['gai_info'] = $this->account_model->get_money_b($pn_txn_id); + } + } + $data['old_order'] = $pn_invoice; + $data['new_order'] = $neworder; + if ($neworder !== null ) { + $neworder_id = analysis_orderid($neworder); + $neworder_id = json_decode($neworder_id); + if ( ! empty($neworder_id)) { + $data['order_info'] = $this->account_model->get_order($neworder_id->orderid, true, $neworder_id->ordertype); + } + } + echo json_encode($this->load->view('payment_gai_setting', $data, true)); + } + + public function gai_modal_save() + { + $data = array(); + $old_ssje = NULL; + $pn_txn_id = $this->input->post('pn_txn_id'); + $pn_id = $this->input->post('pn_id'); + $neworder = $this->input->post('pn_invoice'); + + $note = $this->note_model->get_note($pn_id); + $data['note'] = $note[0]; + $orderid_info = analysis_orderid($data['note']->OPN_orderId); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + if ($orderid_info->ordertype === 'T') { + $data['gai_info'] = $this->account_model->get_money_t($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->account_model->delete_money_t($pn_txn_id); + } + } elseif ($orderid_info->ordertype === 'B' || $orderid_info->ordertype === 'TP') { + $data['gai_info'] = $this->account_model->get_money_b($pn_txn_id); + if ( ! empty($data['gai_info'])) { + $old_ssje = $data['gai_info'][0]->GAI_SSJE; + $this->account_model->delete_money_b($pn_txn_id); + } + } + } + + if (!empty($pn_txn_id) && !empty($neworder)) { + $orderid_info = analysis_orderid($neworder); + if (!empty($orderid_info)) { + $orderid_info = json_decode($orderid_info); + $advisor_info = $this->account_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + if (!empty($advisor_info)) { + $this->note_model->set_invoice($data['note']->OPN_SN, $neworder); + $this->send_notify($data['note']->OPN_SN, $old_ssje); + echo json_encode('修改成功!'); + return true; + } + } + } + echo json_encode('没找到数据!'); + return; + } + + public function close_gai($opn_id) + { + $data = array(); + $data['note'] = $this->note_model->get_note($opn_id); + if (!empty($data['note'])) { + $this->note_model->update_send($opn_id, $data['note'][0]->OPN_transactionId, 'closed'); + echo json_encode('该收款记录已经忽略!'); + return true; + } + echo json_encode('没找到数据!'); + return; + } + } diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index 3a42e20e..91fc6fa0 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -28,7 +28,7 @@ class Online_payment_account_model extends CI_Model { $result = ''; $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T - if ($ordertype == 'B' || $ordertype == 'A') { + if ($ordertype == 'B' || $ordertype == 'A' || $ordertype == 'TP') { $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; @@ -152,6 +152,40 @@ class Online_payment_account_model extends CI_Model { return $query; } + //根据交易号获取收款记录(传统订单) + public function get_money_t($pn_invoice) { + $sql = "SELECT GroupAccountInfo.* + from GroupAccountInfo + where DeleteFlag=0 and GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + //根据交易号获取收款记录(商务订单) + public function get_money_b($pn_invoice) { + $sql = "SELECT BIZ_GroupAccountInfo.* + from BIZ_GroupAccountInfo + where DeleteFlag=0 and GAI_AccreditNo=? + "; + $query = $this->HT->query($sql, array($pn_invoice)); + $result = $query->result(); + return $result; + } + /** 删除收款记录 */ + public function delete_money_t($deadId) + { + $sql = "UPDATE GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } + public function delete_money_b($deadId) + { + $sql = "UPDATE BIZ_GroupAccountInfo SET DeleteFlag=1 WHERE GAI_AccreditNo=?"; + $query = $this->HT->query($sql, array($deadId)); + return $query; + } + //添加收款记录(商务订单) public function add_account_info($GAI_COLI_SN, $payment_method, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 diff --git a/webht/third_party/pay/models/Online_payment_note_model.php b/webht/third_party/pay/models/Online_payment_note_model.php index 7d5a9c4a..c17f0cb4 100644 --- a/webht/third_party/pay/models/Online_payment_note_model.php +++ b/webht/third_party/pay/models/Online_payment_note_model.php @@ -92,14 +92,59 @@ class Online_payment_note_model extends CI_Model { return $query->result(); } - public function get_note($transactionId) + public function get_note($opn_id) { $this->init_query(); $this->topnum=1; - $this->transactionId = " AND opn.OPN_transactionId=" . $this->info->escape($transactionId); + $this->search = " AND opn.OPN_SN=" . $this->info->escape($opn_id); return $this->query_note(); } + public function search_key($keyword) + { + $this->init_query(); + $this->topnum = 300; + $keyword = trim($keyword); + $search_sql = ""; + if ( ! empty($keyword)) { + $search_sql.=" AND ( OPN_transactionId = '$keyword' + OR OPN_orderId like '%$keyword%' + OR OPN_rawOrderId like '%$keyword%' )"; + } + $this->search = $search_sql; + return $this->query_note(); + } + + public function search_date($date) + { + $this->init_query(); + $this->search = " AND OPN_noticeTime BETWEEN '$date 00:00:00' AND '$date 23:59:59' "; + return $this->query_note(); + } + + public function failnote($topnum = 2) { + $this->init_query(); + $this->topnum = $topnum; + $this->send = " AND OPN_noticeSendStatus='sendfail' "; + return $this->query_note(); + } + + /*! + * 导出记录 + * @date 2019-04-28 + * @param integer $sn [description] + */ + public function list_export_record($sn=0) + { + $search_sql = $sn===0 ? "" : " and TEL_SN=$sn "; + $sql = "SELECT TOP 10 * + FROM [InfoManager].[dbo].[Transaction_Export_Log] + WHERE 1=1 + $search_sql + order by TEL_SN desc"; + return $this->info->query($sql)->result(); + } + } From ef7df5607005e47916b2fb63c316fc819d908b38 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 29 Apr 2019 13:30:54 +0800 Subject: [PATCH 302/382] =?UTF-8?q?wxpay=20=E6=96=B0=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/webht/flatpicker.min.css | 3 + js/flatpickr-4.4.4.min.js | 2 + .../pay/views/payment_gai_setting.php | 59 ++++ webht/third_party/pay/views/payment_list.php | 303 ++++++++++++++++++ 4 files changed, 367 insertions(+) create mode 100644 css/webht/flatpicker.min.css create mode 100644 js/flatpickr-4.4.4.min.js create mode 100644 webht/third_party/pay/views/payment_gai_setting.php create mode 100644 webht/third_party/pay/views/payment_list.php diff --git a/css/webht/flatpicker.min.css b/css/webht/flatpicker.min.css new file mode 100644 index 00000000..f513a963 --- /dev/null +++ b/css/webht/flatpicker.min.css @@ -0,0 +1,3 @@ +/*flatpickr:begin*/ +.flatpickr-calendar{background:transparent;opacity:0;display:none;text-align:center;visibility:hidden;padding:0;-webkit-animation:none;animation:none;direction:ltr;border:0;font-size:14px;line-height:24px;border-radius:5px;position:absolute;width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;-ms-touch-action:manipulation;touch-action:manipulation;background:#fff;-webkit-box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);box-shadow:1px 0 0 #e6e6e6,-1px 0 0 #e6e6e6,0 1px 0 #e6e6e6,0 -1px 0 #e6e6e6,0 3px 13px rgba(0,0,0,0.08);}.flatpickr-calendar.open,.flatpickr-calendar.inline{opacity:1;max-height:640px;visibility:visible;}.flatpickr-calendar.open{display:inline-block;z-index:99999;}.flatpickr-calendar.animate.open{-webkit-animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);animation:fpFadeInDown 300ms cubic-bezier(0.23,1,0.32,1);}.flatpickr-calendar.inline{display:block;position:relative;top:2px;}.flatpickr-calendar.static{position:absolute;top:calc(100% + 2px);}.flatpickr-calendar.static.open{z-index:999;display:block;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+1) .flatpickr-day.inRange:nth-child(7n+7){-webkit-box-shadow:none !important;box-shadow:none !important;}.flatpickr-calendar.multiMonth .flatpickr-days .dayContainer:nth-child(n+2) .flatpickr-day.inRange:nth-child(7n+1){-webkit-box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-2px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-calendar .hasWeeks .dayContainer,.flatpickr-calendar .hasTime .dayContainer{border-bottom:0;border-bottom-right-radius:0;border-bottom-left-radius:0;}.flatpickr-calendar .hasWeeks .dayContainer{border-left:0;}.flatpickr-calendar.showTimeInput.hasTime .flatpickr-time{height:40px;border-top:1px solid #e6e6e6;}.flatpickr-calendar.noCalendar.hasTime .flatpickr-time{height:auto;}.flatpickr-calendar:before,.flatpickr-calendar:after{position:absolute;display:block;pointer-events:none;border:solid transparent;content:'';height:0;width:0;left:22px;}.flatpickr-calendar.rightMost:before,.flatpickr-calendar.rightMost:after{left:auto;right:22px;}.flatpickr-calendar:before{border-width:5px;margin:0 -5px;}.flatpickr-calendar:after{border-width:4px;margin:0 -4px;}.flatpickr-calendar.arrowTop:before,.flatpickr-calendar.arrowTop:after{bottom:100%;}.flatpickr-calendar.arrowTop:before{border-bottom-color:#e6e6e6;}.flatpickr-calendar.arrowTop:after{border-bottom-color:#fff;}.flatpickr-calendar.arrowBottom:before,.flatpickr-calendar.arrowBottom:after{top:100%;}.flatpickr-calendar.arrowBottom:before{border-top-color:#e6e6e6;}.flatpickr-calendar.arrowBottom:after{border-top-color:#fff;}.flatpickr-calendar:focus{outline:0;}.flatpickr-wrapper{position:relative;display:inline-block;}.flatpickr-months{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-months .flatpickr-month{background:transparent;color:rgba(0,0,0,0.9);fill:rgba(0,0,0,0.9);height:28px;line-height:1;text-align:center;position:relative;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;overflow:hidden;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;margin-bottom:5px;}.flatpickr-months .flatpickr-prev-month,.flatpickr-months .flatpickr-next-month{text-decoration:none;cursor:pointer;position:absolute;top:0px;line-height:16px;height:28px;padding:10px;z-index:3;}.flatpickr-months .flatpickr-prev-month.disabled,.flatpickr-months .flatpickr-next-month.disabled{display:none;}.flatpickr-months .flatpickr-prev-month i,.flatpickr-months .flatpickr-next-month i{position:relative;}.flatpickr-months .flatpickr-prev-month.flatpickr-prev-month,.flatpickr-months .flatpickr-next-month.flatpickr-prev-month{left:0;}.flatpickr-months .flatpickr-prev-month.flatpickr-next-month,.flatpickr-months .flatpickr-next-month.flatpickr-next-month{right:0;}.flatpickr-months .flatpickr-prev-month:hover,.flatpickr-months .flatpickr-next-month:hover{color:#959ea9;}.flatpickr-months .flatpickr-prev-month:hover svg,.flatpickr-months .flatpickr-next-month:hover svg{fill:#f64747;}.flatpickr-months .flatpickr-prev-month svg,.flatpickr-months .flatpickr-next-month svg{width:14px;height:14px;}.flatpickr-months .flatpickr-prev-month svg path,.flatpickr-months .flatpickr-next-month svg path{-webkit-transition:fill 0.1s;transition:fill 0.1s;fill:inherit;}.numInputWrapper{position:relative;height:auto;}.numInputWrapper input,.numInputWrapper span{display:inline-block;}.numInputWrapper input{width:100%;}.numInputWrapper input::-ms-clear{display:none;}.numInputWrapper span{position:absolute;right:0;width:14px;padding:0 4px 0 2px;height:50%;line-height:50%;opacity:0;cursor:pointer;border:1px solid rgba(57,57,57,0.15);-webkit-box-sizing:border-box;box-sizing:border-box;}.numInputWrapper span:hover{background:rgba(0,0,0,0.1);}.numInputWrapper span:active{background:rgba(0,0,0,0.2);}.numInputWrapper span:after{display:block;content:"";position:absolute;}.numInputWrapper span.arrowUp{top:-2px;left:50px;}.numInputWrapper span.arrowUp:after{border-left:4px solid transparent;border-right:4px solid transparent;border-bottom:4px solid rgba(57,57,57,0.6);top:26%;}.numInputWrapper span.arrowDown{top:10px;left:50px;}.numInputWrapper span.arrowDown:after{border-left:4px solid transparent;border-right:4px solid transparent;border-top:4px solid rgba(57,57,57,0.6);top:40%;}.numInputWrapper span svg{width:inherit;height:auto;}.numInputWrapper span svg path{fill:rgba(0,0,0,0.5);}.numInputWrapper:hover{cursor:pointer;}.numInputWrapper:hover span{opacity:1;}.flatpickr-current-month{font-size:17px;line-height:inherit;font-weight:300;color:inherit;position:absolute;width:75%;left:12.5%;padding:6.16px 0 0 0;line-height:1;height:28px;display:inline-block;text-align:center;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);}.flatpickr-current-month span.cur-month{font-family:inherit;font-weight:700;color:inherit;display:inline-block;margin-left:0.5ch;padding:0;font-size:19px;color:#a31022;}.flatpickr-current-month span.cur-month:hover{cursor:pointer;}.flatpickr-current-month .numInputWrapper{width:6ch;width:7ch\0;display:inline-block;}.flatpickr-current-month .numInputWrapper span.arrowUp:after{border-bottom-color:rgba(0,0,0,0.9);}.flatpickr-current-month .numInputWrapper span.arrowDown:after{border-top-color:rgba(0,0,0,0.9);}.flatpickr-current-month input.cur-year{background:transparent;-webkit-box-sizing:border-box;box-sizing:border-box;color:inherit;cursor:text;padding:0 0 0 0.5ch;margin:0;display:inline-block;font-size:inherit;font-family:inherit;font-weight:300;line-height:inherit;height:auto;border:0;border-radius:0;vertical-align:initial;font-size:18px;}.flatpickr-current-month input.cur-year:focus{outline:0;}.flatpickr-current-month input.cur-year[disabled],.flatpickr-current-month input.cur-year[disabled]:hover{font-size:100%;color:rgba(0,0,0,0.5);background:transparent;pointer-events:none;}.flatpickr-weekdays{background:transparent;text-align:center;overflow:hidden;width:100%;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:center;-webkit-align-items:center;-ms-flex-align:center;align-items:center;height:28px;}.flatpickr-weekdays .flatpickr-weekdaycontainer{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}span.flatpickr-weekday{cursor:default;font-size:16px;background:transparent;color:rgba(0,0,0,0.54);line-height:1;margin:0;text-align:center;display:block;-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;}.dayContainer,.flatpickr-weeks{padding:1px 0 0 0;}.flatpickr-days{position:relative;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-align:start;-webkit-align-items:flex-start;-ms-flex-align:start;align-items:flex-start;width:307.875px;}.flatpickr-days:focus{outline:0;}.dayContainer{padding:0;outline:0;text-align:left;width:307.875px;min-width:307.875px;max-width:307.875px;-webkit-box-sizing:border-box;box-sizing:border-box;display:inline-block;display:-ms-flexbox;display:-webkit-box;display:-webkit-flex;display:flex;-webkit-flex-wrap:wrap;flex-wrap:wrap;-ms-flex-wrap:wrap;-ms-flex-pack:justify;-webkit-justify-content:space-around;justify-content:space-around;-webkit-transform:translate3d(0px,0px,0px);transform:translate3d(0px,0px,0px);opacity:1;}.dayContainer + .dayContainer{-webkit-box-shadow:-1px 0 0 #e6e6e6;box-shadow:-1px 0 0 #e6e6e6;}.flatpickr-day{background:none;border:1px solid transparent;border-radius:150px;-webkit-box-sizing:border-box;box-sizing:border-box;color:#a31022;cursor:pointer;font-weight:400;width:14.2857143%;-webkit-flex-basis:14.2857143%;-ms-flex-preferred-size:14.2857143%;flex-basis:14.2857143%;max-width:39px;height:39px;line-height:39px;margin:0;display:inline-block;position:relative;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;text-align:center;font-size:16px;}.flatpickr-day.inRange,.flatpickr-day.prevMonthDay.inRange,.flatpickr-day.nextMonthDay.inRange,.flatpickr-day.today.inRange,.flatpickr-day.prevMonthDay.today.inRange,.flatpickr-day.nextMonthDay.today.inRange,.flatpickr-day:hover,.flatpickr-day.prevMonthDay:hover,.flatpickr-day.nextMonthDay:hover,.flatpickr-day:focus,.flatpickr-day.prevMonthDay:focus,.flatpickr-day.nextMonthDay:focus{cursor:pointer;outline:0;background:#e6e6e6;border-color:#e6e6e6;}.flatpickr-day.today{border-color:#959ea9;}.flatpickr-day.today:hover,.flatpickr-day.today:focus{border-color:#959ea9;background:#959ea9;color:#fff;}.flatpickr-day.selected,.flatpickr-day.startRange,.flatpickr-day.endRange,.flatpickr-day.selected.inRange,.flatpickr-day.startRange.inRange,.flatpickr-day.endRange.inRange,.flatpickr-day.selected:focus,.flatpickr-day.startRange:focus,.flatpickr-day.endRange:focus,.flatpickr-day.selected:hover,.flatpickr-day.startRange:hover,.flatpickr-day.endRange:hover,.flatpickr-day.selected.prevMonthDay,.flatpickr-day.startRange.prevMonthDay,.flatpickr-day.endRange.prevMonthDay,.flatpickr-day.selected.nextMonthDay,.flatpickr-day.startRange.nextMonthDay,.flatpickr-day.endRange.nextMonthDay{background:#569ff7;-webkit-box-shadow:none;box-shadow:none;color:#fff;border-color:#569ff7;}.flatpickr-day.selected.startRange,.flatpickr-day.startRange.startRange,.flatpickr-day.endRange.startRange{border-radius:50px 0 0 50px;}.flatpickr-day.selected.endRange,.flatpickr-day.startRange.endRange,.flatpickr-day.endRange.endRange{border-radius:0 50px 50px 0;}.flatpickr-day.selected.startRange + .endRange,.flatpickr-day.startRange.startRange + .endRange,.flatpickr-day.endRange.startRange + .endRange{-webkit-box-shadow:-10px 0 0 #569ff7;box-shadow:-10px 0 0 #569ff7;}.flatpickr-day.selected.startRange.endRange,.flatpickr-day.startRange.startRange.endRange,.flatpickr-day.endRange.startRange.endRange{border-radius:50px;}.flatpickr-day.inRange{border-radius:0;-webkit-box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;box-shadow:-5px 0 0 #e6e6e6,5px 0 0 #e6e6e6;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover,.flatpickr-day.prevMonthDay,.flatpickr-day.nextMonthDay,.flatpickr-day.notAllowed,.flatpickr-day.notAllowed.prevMonthDay,.flatpickr-day.notAllowed.nextMonthDay{color:#848080;background:transparent;border-color:transparent;cursor:default;}.flatpickr-day.disabled,.flatpickr-day.disabled:hover{cursor:not-allowed;color:#d0d0d0;}.flatpickr-day.week.selected{border-radius:0;-webkit-box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;box-shadow:-5px 0 0 #569ff7,5px 0 0 #569ff7;}.flatpickr-day.hidden{visibility:hidden;}.rangeMode .flatpickr-day{margin-top:1px;}.flatpickr-weekwrapper{display:inline-block;float:left;}.flatpickr-weekwrapper .flatpickr-weeks{padding:0 12px;-webkit-box-shadow:1px 0 0 #e6e6e6;box-shadow:1px 0 0 #e6e6e6;}.flatpickr-weekwrapper .flatpickr-weekday{float:none;width:100%;line-height:28px;}.flatpickr-weekwrapper span.flatpickr-day,.flatpickr-weekwrapper span.flatpickr-day:hover{display:block;width:100%;max-width:none;color:#9a9a9a;background:transparent;cursor:default;border:none;}.flatpickr-innerContainer{display:block;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;}.flatpickr-rContainer{display:inline-block;padding:0;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time{text-align:center;outline:0;display:block;height:0;line-height:40px;max-height:40px;-webkit-box-sizing:border-box;box-sizing:border-box;overflow:hidden;display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;}.flatpickr-time:after{content:"";display:table;clear:both;}.flatpickr-time .numInputWrapper{-webkit-box-flex:1;-webkit-flex:1;-ms-flex:1;flex:1;width:40%;height:40px;float:left;}.flatpickr-time .numInputWrapper span.arrowUp:after{border-bottom-color:#4f4f4f;}.flatpickr-time .numInputWrapper span.arrowDown:after{border-top-color:#4f4f4f;}.flatpickr-time.hasSeconds .numInputWrapper{width:26%;}.flatpickr-time.time24hr .numInputWrapper{width:49%;}.flatpickr-time input{background:transparent;-webkit-box-shadow:none;box-shadow:none;border:0;border-radius:0;text-align:center;margin:0;padding:0;height:inherit;line-height:inherit;cursor:pointer;color:#4f4f4f;font-size:14px;position:relative;-webkit-box-sizing:border-box;box-sizing:border-box;}.flatpickr-time input.flatpickr-hour{font-weight:bold;}.flatpickr-time input.flatpickr-minute,.flatpickr-time input.flatpickr-second{font-weight:400;}.flatpickr-time input:focus{outline:0;border:0;}.flatpickr-time .flatpickr-time-separator,.flatpickr-time .flatpickr-am-pm{height:inherit;display:inline-block;float:left;line-height:inherit;color:#4f4f4f;font-weight:bold;width:2%;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;-webkit-align-self:center;-ms-flex-item-align:center;align-self:center;}.flatpickr-time .flatpickr-am-pm{outline:0;width:18%;cursor:pointer;text-align:center;font-weight:400;}.flatpickr-time .flatpickr-am-pm:hover,.flatpickr-time .flatpickr-am-pm:focus{background:#f0f0f0;}.flatpickr-input[readonly]{cursor:pointer;}@-webkit-keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}}@keyframes fpFadeInDown{from{opacity:0;-webkit-transform:translate3d(0,-20px,0);transform:translate3d(0,-20px,0);}to{opacity:1;-webkit-transform:translate3d(0,0,0);transform:translate3d(0,0,0);}} +/*flatpickr:end*/ diff --git a/js/flatpickr-4.4.4.min.js b/js/flatpickr-4.4.4.min.js new file mode 100644 index 00000000..b40382b2 --- /dev/null +++ b/js/flatpickr-4.4.4.min.js @@ -0,0 +1,2 @@ +/* flatpickr v4.4.4,, @license MIT */ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.flatpickr=t()}(this,function(){"use strict";var Z=function(e){return("0"+e).slice(-2)},Q=function(e){return!0===e?1:0};function X(n,a,i){var o;return void 0===i&&(i=!1),function(){var e=this,t=arguments;null!==o&&clearTimeout(o),o=window.setTimeout(function(){o=null,i||n.apply(e,t)},a),i&&!o&&n.apply(e,t)}}var ee=function(e){return e instanceof Array?e:[e]},e=function(){},te=function(e,t,n){return n.months[t?"shorthand":"longhand"][e]},D={D:e,F:function(e,t,n){e.setMonth(n.months.longhand.indexOf(t))},G:function(e,t){e.setHours(parseFloat(t))},H:function(e,t){e.setHours(parseFloat(t))},J:function(e,t){e.setDate(parseFloat(t))},K:function(e,t,n){e.setHours(e.getHours()%12+12*Q(new RegExp(n.amPM[1],"i").test(t)))},M:function(e,t,n){e.setMonth(n.months.shorthand.indexOf(t))},S:function(e,t){e.setSeconds(parseFloat(t))},U:function(e,t){return new Date(1e3*parseFloat(t))},W:function(e,t){var n=parseInt(t);return new Date(e.getFullYear(),0,2+7*(n-1),0,0,0,0)},Y:function(e,t){e.setFullYear(parseFloat(t))},Z:function(e,t){return new Date(t)},d:function(e,t){e.setDate(parseFloat(t))},h:function(e,t){e.setHours(parseFloat(t))},i:function(e,t){e.setMinutes(parseFloat(t))},j:function(e,t){e.setDate(parseFloat(t))},l:e,m:function(e,t){e.setMonth(parseFloat(t)-1)},n:function(e,t){e.setMonth(parseFloat(t)-1)},s:function(e,t){e.setSeconds(parseFloat(t))},w:e,y:function(e,t){e.setFullYear(2e3+parseFloat(t))}},ne={D:"(\\w+)",F:"(\\w+)",G:"(\\d\\d|\\d)",H:"(\\d\\d|\\d)",J:"(\\d\\d|\\d)\\w+",K:"",M:"(\\w+)",S:"(\\d\\d|\\d)",U:"(.+)",W:"(\\d\\d|\\d)",Y:"(\\d{4})",Z:"(.+)",d:"(\\d\\d|\\d)",h:"(\\d\\d|\\d)",i:"(\\d\\d|\\d)",j:"(\\d\\d|\\d)",l:"(\\w+)",m:"(\\d\\d|\\d)",n:"(\\d\\d|\\d)",s:"(\\d\\d|\\d)",w:"(\\d\\d|\\d)",y:"(\\d{2})"},c={Z:function(e){return e.toISOString()},D:function(e,t,n){return t.weekdays.shorthand[c.w(e,t,n)]},F:function(e,t,n){return te(c.n(e,t,n)-1,!1,t)},G:function(e,t,n){return Z(c.h(e,t,n))},H:function(e){return Z(e.getHours())},J:function(e,t){return void 0!==t.ordinal?e.getDate()+t.ordinal(e.getDate()):e.getDate()},K:function(e,t){return t.amPM[Q(11<e.getHours())]},M:function(e,t){return te(e.getMonth(),!0,t)},S:function(e){return Z(e.getSeconds())},U:function(e){return e.getTime()/1e3},W:function(e,t,n){return n.getWeek(e)},Y:function(e){return e.getFullYear()},d:function(e){return Z(e.getDate())},h:function(e){return e.getHours()%12?e.getHours()%12:12},i:function(e){return Z(e.getMinutes())},j:function(e){return e.getDate()},l:function(e,t){return t.weekdays.longhand[e.getDay()]},m:function(e){return Z(e.getMonth()+1)},n:function(e){return e.getMonth()+1},s:function(e){return e.getSeconds()},w:function(e){return e.getDay()},y:function(e){return String(e.getFullYear()).substring(2)}},ae={weekdays:{shorthand:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],longhand:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},months:{shorthand:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],longhand:["January","February","March","April","May","June","July","August","September","October","November","December"]},daysInMonth:[31,28,31,30,31,30,31,31,30,31,30,31],firstDayOfWeek:0,ordinal:function(e){var t=e%100;if(3<t&&t<21)return"th";switch(t%10){case 1:return"st";case 2:return"nd";case 3:return"rd";default:return"th"}},rangeSeparator:" to ",weekAbbreviation:"Wk",scrollTitle:"Scroll to increment",toggleTitle:"Click to toggle",amPM:["AM","PM"],yearAriaLabel:"Year"},ie=function(e){var t=e.config,o=void 0===t?b:t,n=e.l10n,r=void 0===n?ae:n;return function(a,e,t){if(void 0!==o.formatDate)return o.formatDate(a,e);var i=t||r;return e.split("").map(function(e,t,n){return c[e]&&"\\"!==n[t-1]?c[e](a,i,o):"\\"!==e?e:""}).join("")}},oe=function(e){var t=e.config,h=void 0===t?b:t,n=e.l10n,v=void 0===n?ae:n;return function(e,t,n){if(0===e||e){var a,i=e;if(e instanceof Date)a=new Date(e.getTime());else if("string"!=typeof e&&void 0!==e.toFixed)a=new Date(e);else if("string"==typeof e){var o=t||(h||b).dateFormat,r=String(e).trim();if("today"===r)a=new Date,n=!0;else if(/Z$/.test(r)||/GMT$/.test(r))a=new Date(e);else if(h&&h.parseDate)a=h.parseDate(e,o);else{a=h&&h.noCalendar?new Date((new Date).setHours(0,0,0,0)):new Date((new Date).getFullYear(),0,1,0,0,0,0);for(var c,l=[],d=0,s=0,u="";d<o.length;d++){var f=o[d],m="\\"===f,g="\\"===o[d-1]||m;if(ne[f]&&!g){u+=ne[f];var p=new RegExp(u).exec(e);p&&(c=!0)&&l["Y"!==f?"push":"unshift"]({fn:D[f],val:p[++s]})}else m||(u+=".");l.forEach(function(e){var t=e.fn,n=e.val;return a=t(a,n,v)||a})}a=c?a:void 0}}if(a instanceof Date)return!0===n&&a.setHours(0,0,0,0),a;h.errorHandler(new Error("Invalid date provided: "+i))}}};function re(e,t,n){return void 0===n&&(n=!0),!1!==n?new Date(e.getTime()).setHours(0,0,0,0)-new Date(t.getTime()).setHours(0,0,0,0):e.getTime()-t.getTime()}var ce=function(e,t,n){return e>Math.min(t,n)&&e<Math.max(t,n)},le={DAY:864e5},b={_disable:[],_enable:[],allowInput:!1,altFormat:"F j, Y",altInput:!1,altInputClass:"form-control input",animate:"object"==typeof window&&-1===window.navigator.userAgent.indexOf("MSIE"),ariaDateFormat:"F j, Y",clickOpens:!0,closeOnSelect:!0,conjunction:", ",dateFormat:"Y-m-d",defaultHour:12,defaultMinute:0,defaultSeconds:0,disable:[],disableMobile:!1,enable:[],enableSeconds:!1,enableTime:!1,errorHandler:function(e){return"undefined"!=typeof console&&console.warn(e)},getWeek:function(e){var t=new Date(e.getTime());t.setHours(0,0,0,0),t.setDate(t.getDate()+3-(t.getDay()+6)%7);var n=new Date(t.getFullYear(),0,4);return 1+Math.round(((t.getTime()-n.getTime())/864e5-3+(n.getDay()+6)%7)/7)},hourIncrement:1,ignoredFocusElements:[],inline:!1,locale:"default",minuteIncrement:5,mode:"single",nextArrow:"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",noCalendar:!1,now:new Date,onChange:[],onClose:[],onDayCreate:[],onDestroy:[],onKeyDown:[],onMonthChange:[],onOpen:[],onParseConfig:[],onReady:[],onValueUpdate:[],onYearChange:[],onPreCalendarPosition:[],plugins:[],position:"auto",positionElement:void 0,prevArrow:"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",shorthandCurrentMonth:!1,showMonths:1,static:!1,time_24hr:!1,weekNumbers:!1,wrap:!1};function de(e,t,n){if(!0===n)return e.classList.add(t);e.classList.remove(t)}function se(e,t,n){var a=window.document.createElement(e);return t=t||"",n=n||"",a.className=t,void 0!==n&&(a.textContent=n),a}function ue(e){for(;e.firstChild;)e.removeChild(e.firstChild)}function fe(e,t){var n=se("div","numInputWrapper"),a=se("input","numInput "+e),i=se("span","arrowUp"),o=se("span","arrowDown");if(a.type="text",a.pattern="\\d*",void 0!==t)for(var r in t)a.setAttribute(r,t[r]);return n.appendChild(a),n.appendChild(i),n.appendChild(o),n}"function"!=typeof Object.assign&&(Object.assign=function(n){if(!n)throw TypeError("Cannot convert undefined or null to object");for(var e=arguments.length,t=new Array(1<e?e-1:0),a=1;a<e;a++)t[a-1]=arguments[a];for(var i=function(t){t&&Object.keys(t).forEach(function(e){return n[e]=t[e]})},o=0;o<t.length;o++){i(t[o])}return n});var me=300;function r(s,u){var D={config:Object.assign({},ge.defaultConfig),l10n:ae};function f(e){return e.bind(D)}function t(){if(void 0!==D.daysContainer){D.calendarContainer.style.visibility="hidden",D.calendarContainer.style.display="block";var e=(D.days.offsetWidth+1)*D.config.showMonths;D.daysContainer.style.width=e+"px",D.calendarContainer.style.width=e+"px",void 0!==D.weekWrapper&&(D.calendarContainer.style.width=e+D.weekWrapper.offsetWidth+"px"),D.calendarContainer.style.removeProperty("visibility"),D.calendarContainer.style.removeProperty("display")}}function d(e){0!==D.selectedDates.length&&(!function(e){e.preventDefault();var t="keydown"===e.type,n=e.target;void 0!==D.amPM&&e.target===D.amPM&&(D.amPM.textContent=D.l10n.amPM[Q(D.amPM.textContent===D.l10n.amPM[0])]);var a=parseFloat(n.getAttribute("data-min")),i=parseFloat(n.getAttribute("data-max")),o=parseFloat(n.getAttribute("data-step")),r=parseInt(n.value,10),c=e.delta||(t?38===e.which?1:-1:0),l=r+o*c;if(void 0!==n.value&&2===n.value.length){var d=n===D.hourElement,s=n===D.minuteElement;l<a?(l=i+l+Q(!d)+(Q(d)&&Q(!D.amPM)),s&&h(void 0,-1,D.hourElement)):i<l&&(l=n===D.hourElement?l-i-Q(!D.amPM):a,s&&h(void 0,1,D.hourElement)),D.amPM&&d&&(1===o?l+r===23:Math.abs(l-r)>o)&&(D.amPM.textContent=D.l10n.amPM[Q(D.amPM.textContent===D.l10n.amPM[0])]),n.value=Z(l)}}(e),"input"!==e.type?(m(),G()):setTimeout(function(){m(),G()},me))}function m(){if(void 0!==D.hourElement&&void 0!==D.minuteElement){var e,t,n=(parseInt(D.hourElement.value.slice(-2),10)||0)%24,a=(parseInt(D.minuteElement.value,10)||0)%60,i=void 0!==D.secondElement?(parseInt(D.secondElement.value,10)||0)%60:0;void 0!==D.amPM&&(e=n,t=D.amPM.textContent,n=e%12+12*Q(t===D.l10n.amPM[1]));var o=void 0!==D.config.minTime||D.config.minDate&&D.minDateHasTime&&D.latestSelectedDateObj&&0===re(D.latestSelectedDateObj,D.config.minDate,!0);if(void 0!==D.config.maxTime||D.config.maxDate&&D.maxDateHasTime&&D.latestSelectedDateObj&&0===re(D.latestSelectedDateObj,D.config.maxDate,!0)){var r=void 0!==D.config.maxTime?D.config.maxTime:D.config.maxDate;(n=Math.min(n,r.getHours()))===r.getHours()&&(a=Math.min(a,r.getMinutes())),a===r.getMinutes()&&(i=Math.min(i,r.getSeconds()))}if(o){var c=void 0!==D.config.minTime?D.config.minTime:D.config.minDate;(n=Math.max(n,c.getHours()))===c.getHours()&&(a=Math.max(a,c.getMinutes())),a===c.getMinutes()&&(i=Math.max(i,c.getSeconds()))}l(n,a,i)}}function g(e){var t=e||D.latestSelectedDateObj;t&&l(t.getHours(),t.getMinutes(),t.getSeconds())}function l(e,t,n){void 0!==D.latestSelectedDateObj&&D.latestSelectedDateObj.setHours(e%24,t,n||0,0),D.hourElement&&D.minuteElement&&!D.isMobile&&(D.hourElement.value=Z(D.config.time_24hr?e:(12+e)%12+12*Q(e%12==0)),D.minuteElement.value=Z(t),void 0!==D.amPM&&(D.amPM.textContent=D.l10n.amPM[Q(12<=e)]),void 0!==D.secondElement&&(D.secondElement.value=Z(n)))}function n(e){var t=parseInt(e.target.value)+(e.delta||0);4!==t.toString().length&&"Enter"!==e.key||(e.target.blur(),/[^\d]/.test(t.toString())||S(t))}function o(t,n,a,i){return n instanceof Array?n.forEach(function(e){return o(t,e,a,i)}):t instanceof Array?t.forEach(function(e){return o(e,n,a,i)}):(t.addEventListener(n,a,i),void D._handlers.push({element:t,event:n,handler:a}))}function a(t){return function(e){1===e.which&&t(e)}}function p(){U("onChange")}function i(e){var t=void 0!==e?D.parseDate(e):D.latestSelectedDateObj||(D.config.minDate&&D.config.minDate>D.now?D.config.minDate:D.config.maxDate&&D.config.maxDate<D.now?D.config.maxDate:D.now);try{void 0!==t&&(D.currentYear=t.getFullYear(),D.currentMonth=t.getMonth())}catch(e){e.message="Invalid date supplied: "+t,D.config.errorHandler(e)}D.redraw()}function r(e){~e.target.className.indexOf("arrow")&&h(e,e.target.classList.contains("arrowUp")?1:-1)}function h(e,t,n){var a=e&&e.target,i=n||a&&a.parentNode&&a.parentNode.firstChild,o=q("increment");o.delta=t,i&&i.dispatchEvent(o)}function v(e,t,n,a){var i,o=P(t,!0),r=se("span","flatpickr-day "+e,t.getDate().toString());return r.dateObj=t,r.$i=a,r.setAttribute("aria-label",D.formatDate(t,D.config.ariaDateFormat)),-1===e.indexOf("hidden")&&0===re(t,D.now)&&((D.todayDateElem=r).classList.add("today"),r.setAttribute("aria-current","date")),o?(r.tabIndex=-1,$(t)&&(r.classList.add("selected"),D.selectedDateElem=r,"range"===D.config.mode&&(de(r,"startRange",D.selectedDates[0]&&0===re(t,D.selectedDates[0],!0)),de(r,"endRange",D.selectedDates[1]&&0===re(t,D.selectedDates[1],!0)),"nextMonthDay"===e&&r.classList.add("inRange")))):r.classList.add("disabled"),"range"===D.config.mode&&(i=t,!("range"!==D.config.mode||D.selectedDates.length<2)&&0<=re(i,D.selectedDates[0])&&re(i,D.selectedDates[1])<=0&&!$(t)&&r.classList.add("inRange")),D.weekNumbers&&1===D.config.showMonths&&"prevMonthDay"!==e&&n%7==1&&D.weekNumbers.insertAdjacentHTML("beforeend","<span class='flatpickr-day'>"+D.config.getWeek(t)+"</span>"),U("onDayCreate",r),r}function b(e){e.focus(),"range"===D.config.mode&&A(e)}function w(e){for(var t=0<e?0:D.config.showMonths-1,n=0<e?D.config.showMonths:-1,a=t;a!=n;a+=e)for(var i=D.daysContainer.children[a],o=0<e?0:i.children.length-1,r=0<e?i.children.length:-1,c=o;c!=r;c+=e){var l=i.children[c];if(-1===l.className.indexOf("hidden")&&P(l.dateObj))return l}}function M(e,t){var n=_(document.activeElement),a=void 0!==e?e:n?document.activeElement:void 0!==D.selectedDateElem&&_(D.selectedDateElem)?D.selectedDateElem:void 0!==D.todayDateElem&&_(D.todayDateElem)?D.todayDateElem:w(0<t?1:-1);return void 0===a?D._input.focus():n?void function(e,t){for(var n=-1===e.className.indexOf("Month")?e.dateObj.getMonth():D.currentMonth,a=0<t?D.config.showMonths:-1,i=0<t?1:-1,o=n-D.currentMonth;o!=a;o+=i)for(var r=D.daysContainer.children[o],c=n-D.currentMonth===o?e.$i+t:t<0?r.children.length-1:0,l=r.children.length,d=c;0<=d&&d<l&&d!=(0<t?l:-1);d+=i){var s=r.children[d];if(-1===s.className.indexOf("hidden")&&P(s.dateObj)&&Math.abs(e.$i-d)>=Math.abs(t))return b(s)}D.changeMonth(i),M(w(i),0)}(a,t):b(a)}function c(e,t){for(var n=(new Date(e,t,1).getDay()-D.l10n.firstDayOfWeek+7)%7,a=D.utils.getDaysInMonth((t-1+12)%12),i=D.utils.getDaysInMonth(t),o=window.document.createDocumentFragment(),r=1<D.config.showMonths,c=r?"prevMonthDay hidden":"prevMonthDay",l=r?"nextMonthDay hidden":"nextMonthDay",d=a+1-n,s=0;d<=a;d++,s++)o.appendChild(v(c,new Date(e,t-1,d),d,s));for(d=1;d<=i;d++,s++)o.appendChild(v("",new Date(e,t,d),d,s));for(var u=i+1;u<=42-n&&(1===D.config.showMonths||s%7!=0);u++,s++)o.appendChild(v(l,new Date(e,t+1,u%i),u,s));var f=se("div","dayContainer");return f.appendChild(o),f}function C(){if(void 0!==D.daysContainer){ue(D.daysContainer),D.weekNumbers&&ue(D.weekNumbers);for(var e=document.createDocumentFragment(),t=0;t<D.config.showMonths;t++){var n=new Date(D.currentYear,D.currentMonth,1);n.setMonth(D.currentMonth+t),e.appendChild(c(n.getFullYear(),n.getMonth()))}D.daysContainer.appendChild(e),D.days=D.daysContainer.firstChild}}function y(){var e=se("div","flatpickr-month"),t=window.document.createDocumentFragment(),n=se("span","cur-month");n.title=D.l10n.scrollTitle;var a=fe("cur-year",{tabindex:"-1"}),i=a.childNodes[0];i.title=D.l10n.scrollTitle,i.setAttribute("aria-label",D.l10n.yearAriaLabel),D.config.minDate&&i.setAttribute("data-min",D.config.minDate.getFullYear().toString()),D.config.maxDate&&(i.setAttribute("data-max",D.config.maxDate.getFullYear().toString()),i.disabled=!!D.config.minDate&&D.config.minDate.getFullYear()===D.config.maxDate.getFullYear());var o=se("div","flatpickr-current-month");return o.appendChild(n),o.appendChild(a),t.appendChild(o),e.appendChild(t),{container:e,yearElement:i,monthElement:n}}function x(){ue(D.monthNav),D.monthNav.appendChild(D.prevMonthNav);for(var e=D.config.showMonths;e--;){var t=y();D.yearElements.push(t.yearElement),D.monthElements.push(t.monthElement),D.monthNav.appendChild(t.container)}D.monthNav.appendChild(D.nextMonthNav)}function E(){D.weekdayContainer?ue(D.weekdayContainer):D.weekdayContainer=se("div","flatpickr-weekdays");for(var e=D.config.showMonths;e--;){var t=se("div","flatpickr-weekdaycontainer");D.weekdayContainer.appendChild(t)}return T(),D.weekdayContainer}function T(){var e=D.l10n.firstDayOfWeek,t=D.l10n.weekdays.shorthand.concat();0<e&&e<t.length&&(t=t.splice(e,t.length).concat(t.splice(0,e)));for(var n=D.config.showMonths;n--;)D.weekdayContainer.children[n].innerHTML="\n <span class=flatpickr-weekday>\n "+t.join("</span><span class=flatpickr-weekday>")+"\n </span>\n "}function k(e,t){void 0===t&&(t=!0);var n=t?e:e-D.currentMonth;n<0&&!0===D._hidePrevMonthArrow||0<n&&!0===D._hideNextMonthArrow||(D.currentMonth+=n,(D.currentMonth<0||11<D.currentMonth)&&(D.currentYear+=11<D.currentMonth?1:-1,D.currentMonth=(D.currentMonth+12)%12,U("onYearChange")),C(),U("onMonthChange"),z())}function I(e){return!(!D.config.appendTo||!D.config.appendTo.contains(e))||D.calendarContainer.contains(e)}function O(t){if(D.isOpen&&!D.config.inline){var e=I(t.target),n=t.target===D.input||t.target===D.altInput||D.element.contains(t.target)||t.path&&t.path.indexOf&&(~t.path.indexOf(D.input)||~t.path.indexOf(D.altInput)),a="blur"===t.type?n&&t.relatedTarget&&!I(t.relatedTarget):!n&&!e,i=!D.config.ignoredFocusElements.some(function(e){return e.contains(t.target)});a&&i&&(D.close(),"range"===D.config.mode&&1===D.selectedDates.length&&(D.clear(!1),D.redraw()))}}function S(e){if(!(!e||D.config.minDate&&e<D.config.minDate.getFullYear()||D.config.maxDate&&e>D.config.maxDate.getFullYear())){var t=e,n=D.currentYear!==t;D.currentYear=t||D.currentYear,D.config.maxDate&&D.currentYear===D.config.maxDate.getFullYear()?D.currentMonth=Math.min(D.config.maxDate.getMonth(),D.currentMonth):D.config.minDate&&D.currentYear===D.config.minDate.getFullYear()&&(D.currentMonth=Math.max(D.config.minDate.getMonth(),D.currentMonth)),n&&(D.redraw(),U("onYearChange"))}}function P(e,t){void 0===t&&(t=!0);var n=D.parseDate(e,void 0,t);if(D.config.minDate&&n&&re(n,D.config.minDate,void 0!==t?t:!D.minDateHasTime)<0||D.config.maxDate&&n&&0<re(n,D.config.maxDate,void 0!==t?t:!D.maxDateHasTime))return!1;if(0===D.config.enable.length&&0===D.config.disable.length)return!0;if(void 0===n)return!1;for(var a,i=0<D.config.enable.length,o=i?D.config.enable:D.config.disable,r=0;r<o.length;r++){if("function"==typeof(a=o[r])&&a(n))return i;if(a instanceof Date&&void 0!==n&&a.getTime()===n.getTime())return i;if("string"==typeof a&&void 0!==n){var c=D.parseDate(a,void 0,!0);return c&&c.getTime()===n.getTime()?i:!i}if("object"==typeof a&&void 0!==n&&a.from&&a.to&&n.getTime()>=a.from.getTime()&&n.getTime()<=a.to.getTime())return i}return!i}function _(e){return void 0!==D.daysContainer&&(-1===e.className.indexOf("hidden")&&D.daysContainer.contains(e))}function F(e){e.stopPropagation();var t=e.target===D._input,n=I(e.target),a=D.config.allowInput,i=D.isOpen&&(!a||!t),o=D.config.inline&&t&&!a;if(13===e.keyCode&&t){if(a)return D.setDate(D._input.value,!0,e.target===D.altInput?D.config.altFormat:D.config.dateFormat),e.target.blur();D.open()}else if(n||i||o){var r=!!D.timeContainer&&D.timeContainer.contains(e.target);switch(e.keyCode){case 13:r?G():R(e);break;case 27:e.preventDefault(),W();break;case 8:case 46:t&&!D.config.allowInput&&(e.preventDefault(),D.clear());break;case 37:case 39:if(r)D.hourElement&&D.hourElement.focus();else if(e.preventDefault(),void 0!==D.daysContainer&&!1===D.config.allowInput){var c=39===e.keyCode?1:-1;e.ctrlKey?(k(c),M(w(1),0)):M(void 0,c)}break;case 38:case 40:e.preventDefault();var l=40===e.keyCode?1:-1;D.daysContainer?e.ctrlKey?(S(D.currentYear-l),M(w(1),0)):r||M(void 0,7*l):D.config.enableTime&&(!r&&D.hourElement&&D.hourElement.focus(),d(e),D._debouncedChange());break;case 9:e.target===D.hourElement?(e.preventDefault(),D.minuteElement.select()):e.target===D.minuteElement&&(D.secondElement||D.amPM)?(e.preventDefault(),void 0!==D.secondElement?D.secondElement.focus():void 0!==D.amPM&&D.amPM.focus()):e.target===D.secondElement&&D.amPM&&(e.preventDefault(),D.amPM.focus())}switch(e.key){case D.l10n.amPM[0].charAt(0):case D.l10n.amPM[0].charAt(0).toLowerCase():void 0!==D.amPM&&e.target===D.amPM&&(D.amPM.textContent=D.l10n.amPM[0],m(),G());break;case D.l10n.amPM[1].charAt(0):case D.l10n.amPM[1].charAt(0).toLowerCase():void 0!==D.amPM&&e.target===D.amPM&&(D.amPM.textContent=D.l10n.amPM[1],m(),G())}U("onKeyDown",e)}}function A(o){if(1===D.selectedDates.length&&o.classList.contains("flatpickr-day")&&!o.classList.contains("disabled")){for(var r=o.dateObj.getTime(),c=D.parseDate(D.selectedDates[0],void 0,!0).getTime(),e=Math.min(r,D.selectedDates[0].getTime()),t=Math.max(r,D.selectedDates[0].getTime()),n=D.daysContainer.children,a=n[0].children[0].dateObj.getTime(),i=n[n.length-1].lastChild.dateObj.getTime(),l=!1,d=0,s=0,u=a;u<i;u+=le.DAY)P(new Date(u),!0)||(l=l||e<u&&u<t,u<c&&(!d||d<u)?d=u:c<u&&(!s||u<s)&&(s=u));for(var f=0;f<D.config.showMonths;f++)for(var m=D.daysContainer.children[f],g=D.daysContainer.children[f-1],p=function(e,t){var n=m.children[e],a=n.dateObj.getTime(),i=0<d&&a<d||0<s&&s<a;return i?(n.classList.add("notAllowed"),["inRange","startRange","endRange"].forEach(function(e){n.classList.remove(e)}),"continue"):l&&!i?"continue":(["startRange","inRange","endRange","notAllowed"].forEach(function(e){n.classList.remove(e)}),o.classList.add(r<D.selectedDates[0].getTime()?"startRange":"endRange"),void(!m.contains(o)&&0<f&&g&&g.lastChild.dateObj.getTime()>=a||(c<r&&a===c?n.classList.add("startRange"):r<c&&a===c&&n.classList.add("endRange"),d<=a&&(0===s||a<=s)&&ce(a,c,r)&&n.classList.add("inRange"))))},h=0,v=m.children.length;h<v;h++)p(h)}}function N(){!D.isOpen||D.config.static||D.config.inline||H()}function j(a){return function(e){var t=D.config["_"+a+"Date"]=D.parseDate(e,D.config.dateFormat),n=D.config["_"+("min"===a?"max":"min")+"Date"];void 0!==t&&(D["min"===a?"minDateHasTime":"maxDateHasTime"]=0<t.getHours()||0<t.getMinutes()||0<t.getSeconds()),D.selectedDates&&(D.selectedDates=D.selectedDates.filter(function(e){return P(e)}),D.selectedDates.length||"min"!==a||g(t),G()),D.daysContainer&&(L(),void 0!==t?D.currentYearElement[a]=t.getFullYear().toString():D.currentYearElement.removeAttribute(a),D.currentYearElement.disabled=!!n&&void 0!==t&&n.getFullYear()===t.getFullYear())}}function Y(){"object"!=typeof D.config.locale&&void 0===ge.l10ns[D.config.locale]&&D.config.errorHandler(new Error("flatpickr: invalid locale "+D.config.locale)),D.l10n=Object.assign({},ge.l10ns.default,"object"==typeof D.config.locale?D.config.locale:"default"!==D.config.locale?ge.l10ns[D.config.locale]:void 0),ne.K="("+D.l10n.amPM[0]+"|"+D.l10n.amPM[1]+"|"+D.l10n.amPM[0].toLowerCase()+"|"+D.l10n.amPM[1].toLowerCase()+")",D.formatDate=ie(D)}function H(e){if(void 0!==D.calendarContainer){U("onPreCalendarPosition");var t=e||D._positionElement,n=Array.prototype.reduce.call(D.calendarContainer.children,function(e,t){return e+t.offsetHeight},0),a=D.calendarContainer.offsetWidth,i=D.config.position,o=t.getBoundingClientRect(),r=window.innerHeight-o.bottom,c="above"===i||"below"!==i&&r<n&&o.top>n,l=window.pageYOffset+o.top+(c?-n-2:t.offsetHeight+2);if(de(D.calendarContainer,"arrowTop",!c),de(D.calendarContainer,"arrowBottom",c),!D.config.inline){var d=window.pageXOffset+o.left,s=window.document.body.offsetWidth-o.right,u=d+a>window.document.body.offsetWidth;de(D.calendarContainer,"rightMost",u),D.config.static||(D.calendarContainer.style.top=l+"px",u?(D.calendarContainer.style.left="auto",D.calendarContainer.style.right=s+"px"):(D.calendarContainer.style.left=d+"px",D.calendarContainer.style.right="auto"))}}}function L(){D.config.noCalendar||D.isMobile||(z(),C())}function W(){D._input.focus(),-1!==window.navigator.userAgent.indexOf("MSIE")||void 0!==navigator.msMaxTouchPoints?setTimeout(D.close,0):D.close()}function R(e){e.preventDefault(),e.stopPropagation();var t=function e(t,n){return n(t)?t:t.parentNode?e(t.parentNode,n):void 0}(e.target,function(e){return e.classList&&e.classList.contains("flatpickr-day")&&!e.classList.contains("disabled")&&!e.classList.contains("notAllowed")});if(void 0!==t){var n=t,a=D.latestSelectedDateObj=new Date(n.dateObj.getTime()),i=(a.getMonth()<D.currentMonth||a.getMonth()>D.currentMonth+D.config.showMonths-1)&&"range"!==D.config.mode;if(D.selectedDateElem=n,"single"===D.config.mode)D.selectedDates=[a];else if("multiple"===D.config.mode){var o=$(a);o?D.selectedDates.splice(parseInt(o),1):D.selectedDates.push(a)}else"range"===D.config.mode&&(2===D.selectedDates.length&&D.clear(!1),D.selectedDates.push(a),0!==re(a,D.selectedDates[0],!0)&&D.selectedDates.sort(function(e,t){return e.getTime()-t.getTime()}));if(m(),i){var r=D.currentYear!==a.getFullYear();D.currentYear=a.getFullYear(),D.currentMonth=a.getMonth(),r&&U("onYearChange"),U("onMonthChange")}if(z(),C(),D.config.minDate&&D.minDateHasTime&&D.config.enableTime&&0===re(a,D.config.minDate)&&g(D.config.minDate),G(),D.config.enableTime&&setTimeout(function(){return D.showTimeInput=!0},50),"range"===D.config.mode&&(1===D.selectedDates.length?A(n):z()),i||"range"===D.config.mode||1!==D.config.showMonths?D.selectedDateElem&&D.selectedDateElem.focus():b(n),void 0!==D.hourElement&&setTimeout(function(){return void 0!==D.hourElement&&D.hourElement.select()},451),D.config.closeOnSelect){var c="single"===D.config.mode&&!D.config.enableTime,l="range"===D.config.mode&&2===D.selectedDates.length&&!D.config.enableTime;(c||l)&&W()}p()}}D.parseDate=oe({config:D.config,l10n:D.l10n}),D._handlers=[],D._bind=o,D._setHoursFromDate=g,D.changeMonth=k,D.changeYear=S,D.clear=function(e){void 0===e&&(e=!0);D.input.value="",void 0!==D.altInput&&(D.altInput.value="");void 0!==D.mobileInput&&(D.mobileInput.value="");D.selectedDates=[],D.latestSelectedDateObj=void 0,!(D.showTimeInput=!1)===D.config.enableTime&&(void 0!==D.config.minDate?g(D.config.minDate):l(D.config.defaultHour,D.config.defaultMinute,D.config.defaultSeconds));D.redraw(),e&&U("onChange")},D.close=function(){D.isOpen=!1,D.isMobile||(D.calendarContainer.classList.remove("open"),D._input.classList.remove("active"));U("onClose")},D._createElement=se,D.destroy=function(){void 0!==D.config&&U("onDestroy");for(var e=D._handlers.length;e--;){var t=D._handlers[e];t.element.removeEventListener(t.event,t.handler)}D._handlers=[],D.mobileInput?(D.mobileInput.parentNode&&D.mobileInput.parentNode.removeChild(D.mobileInput),D.mobileInput=void 0):D.calendarContainer&&D.calendarContainer.parentNode&&D.calendarContainer.parentNode.removeChild(D.calendarContainer);D.altInput&&(D.input.type="text",D.altInput.parentNode&&D.altInput.parentNode.removeChild(D.altInput),delete D.altInput);D.input&&(D.input.type=D.input._type,D.input.classList.remove("flatpickr-input"),D.input.removeAttribute("readonly"),D.input.value="");["_showTimeInput","latestSelectedDateObj","_hideNextMonthArrow","_hidePrevMonthArrow","__hideNextMonthArrow","__hidePrevMonthArrow","isMobile","isOpen","selectedDateElem","minDateHasTime","maxDateHasTime","days","daysContainer","_input","_positionElement","innerContainer","rContainer","monthNav","todayDateElem","calendarContainer","weekdayContainer","prevMonthNav","nextMonthNav","currentMonthElement","currentYearElement","navigationCurrentMonth","selectedDateElem","config"].forEach(function(e){try{delete D[e]}catch(e){}})},D.isEnabled=P,D.jumpToDate=i,D.open=function(e,t){void 0===t&&(t=D._input);if(!0===D.isMobile)return e&&(e.preventDefault(),e.target&&e.target.blur()),setTimeout(function(){void 0!==D.mobileInput&&D.mobileInput.click()},0),void U("onOpen");if(D._input.disabled||D.config.inline)return;var n=D.isOpen;D.isOpen=!0,n||(D.calendarContainer.classList.add("open"),D._input.classList.add("active"),U("onOpen"),H(t));!0===D.config.enableTime&&!0===D.config.noCalendar&&(0===D.selectedDates.length&&(D.setDate(void 0!==D.config.minDate?new Date(D.config.minDate.getTime()):(new Date).setHours(D.config.defaultHour,D.config.defaultMinute,D.config.defaultSeconds,0),!1),m(),G()),setTimeout(function(){return D.hourElement.select()},50))},D.redraw=L,D.set=function(e,t){null!==e&&"object"==typeof e?Object.assign(D.config,e):(D.config[e]=t,void 0!==J[e]&&J[e].forEach(function(e){return e()}));D.redraw(),i()},D.setDate=function(e,t,n){void 0===t&&(t=!1);void 0===n&&(n=D.config.dateFormat);if(0!==e&&!e)return D.clear(t);K(e,n),D.showTimeInput=0<D.selectedDates.length,D.latestSelectedDateObj=D.selectedDates[0],D.redraw(),i(),g(),G(t),t&&U("onChange")},D.toggle=function(){if(D.isOpen)return D.close();D.open()};var J={locale:[Y,T],showMonths:[x,t,E]};function K(e,t){var n=[];if(e instanceof Array)n=e.map(function(e){return D.parseDate(e,t)});else if(e instanceof Date||"number"==typeof e)n=[D.parseDate(e,t)];else if("string"==typeof e)switch(D.config.mode){case"single":n=[D.parseDate(e,t)];break;case"multiple":n=e.split(D.config.conjunction).map(function(e){return D.parseDate(e,t)});break;case"range":n=e.split(D.l10n.rangeSeparator).map(function(e){return D.parseDate(e,t)})}else D.config.errorHandler(new Error("Invalid date supplied: "+JSON.stringify(e)));D.selectedDates=n.filter(function(e){return e instanceof Date&&P(e,!1)}),"range"===D.config.mode&&D.selectedDates.sort(function(e,t){return e.getTime()-t.getTime()})}function B(e){return e.map(function(e){return"string"==typeof e||"number"==typeof e||e instanceof Date?D.parseDate(e,void 0,!0):e&&"object"==typeof e&&e.from&&e.to?{from:D.parseDate(e.from,void 0),to:D.parseDate(e.to,void 0)}:e}).filter(function(e){return e})}function U(e,t){var n=D.config[e];if(void 0!==n&&0<n.length)for(var a=0;n[a]&&a<n.length;a++)n[a](D.selectedDates,D.input.value,D,t);"onChange"===e&&(D.input.dispatchEvent(q("change")),D.input.dispatchEvent(q("input")))}function q(e){var t=document.createEvent("Event");return t.initEvent(e,!0,!0),t}function $(e){for(var t=0;t<D.selectedDates.length;t++)if(0===re(D.selectedDates[t],e))return""+t;return!1}function z(){D.config.noCalendar||D.isMobile||!D.monthNav||(D.yearElements.forEach(function(e,t){var n=new Date(D.currentYear,D.currentMonth,1);n.setMonth(D.currentMonth+t),D.monthElements[t].textContent=te(n.getMonth(),D.config.shorthandCurrentMonth,D.l10n)+" ",e.value=n.getFullYear().toString()}),D._hidePrevMonthArrow=void 0!==D.config.minDate&&(D.currentYear===D.config.minDate.getFullYear()?D.currentMonth<=D.config.minDate.getMonth():D.currentYear<D.config.minDate.getFullYear()),D._hideNextMonthArrow=void 0!==D.config.maxDate&&(D.currentYear===D.config.maxDate.getFullYear()?D.currentMonth+1>D.config.maxDate.getMonth():D.currentYear>D.config.maxDate.getFullYear()))}function G(e){if(void 0===e&&(e=!0),0===D.selectedDates.length)return D.clear(e);void 0!==D.mobileInput&&D.mobileFormatStr&&(D.mobileInput.value=void 0!==D.latestSelectedDateObj?D.formatDate(D.latestSelectedDateObj,D.mobileFormatStr):"");var t="range"!==D.config.mode?D.config.conjunction:D.l10n.rangeSeparator;D.input.value=D.selectedDates.map(function(e){return D.formatDate(e,D.config.dateFormat)}).join(t),void 0!==D.altInput&&(D.altInput.value=D.selectedDates.map(function(e){return D.formatDate(e,D.config.altFormat)}).join(t)),!1!==e&&U("onValueUpdate")}function V(e){var t=D.prevMonthNav.contains(e.target),n=D.nextMonthNav.contains(e.target);t||n?k(t?-1:1):0<=D.yearElements.indexOf(e.target)?(e.preventDefault(),e.target.select()):e.target.classList.contains("arrowUp")?D.changeYear(D.currentYear+1):e.target.classList.contains("arrowDown")&&D.changeYear(D.currentYear-1)}return function(){D.element=D.input=s,D.isOpen=!1,function(){var e=["wrap","weekNumbers","allowInput","clickOpens","time_24hr","enableTime","noCalendar","altInput","shorthandCurrentMonth","inline","static","enableSeconds","disableMobile"],t=["onChange","onClose","onDayCreate","onDestroy","onKeyDown","onMonthChange","onOpen","onParseConfig","onReady","onValueUpdate","onYearChange","onPreCalendarPosition"],n=Object.assign({},u,JSON.parse(JSON.stringify(s.dataset||{}))),a={};D.config.parseDate=n.parseDate,D.config.formatDate=n.formatDate,Object.defineProperty(D.config,"enable",{get:function(){return D.config._enable},set:function(e){D.config._enable=B(e)}}),Object.defineProperty(D.config,"disable",{get:function(){return D.config._disable},set:function(e){D.config._disable=B(e)}}),!n.dateFormat&&n.enableTime&&(a.dateFormat=n.noCalendar?"H:i"+(n.enableSeconds?":S":""):ge.defaultConfig.dateFormat+" H:i"+(n.enableSeconds?":S":"")),n.altInput&&n.enableTime&&!n.altFormat&&(a.altFormat=n.noCalendar?"h:i"+(n.enableSeconds?":S K":" K"):ge.defaultConfig.altFormat+" h:i"+(n.enableSeconds?":S":"")+" K"),Object.defineProperty(D.config,"minDate",{get:function(){return D.config._minDate},set:j("min")}),Object.defineProperty(D.config,"maxDate",{get:function(){return D.config._maxDate},set:j("max")});var i=function(t){return function(e){D.config["min"===t?"_minTime":"_maxTime"]=D.parseDate(e,"H:i")}};Object.defineProperty(D.config,"minTime",{get:function(){return D.config._minTime},set:i("min")}),Object.defineProperty(D.config,"maxTime",{get:function(){return D.config._maxTime},set:i("max")}),Object.assign(D.config,a,n);for(var o=0;o<e.length;o++)D.config[e[o]]=!0===D.config[e[o]]||"true"===D.config[e[o]];for(var r=t.length;r--;)void 0!==D.config[t[r]]&&(D.config[t[r]]=ee(D.config[t[r]]||[]).map(f));"time"===D.config.mode&&(D.config.noCalendar=!0,D.config.enableTime=!0);for(var c=0;c<D.config.plugins.length;c++){var l=D.config.plugins[c](D)||{};for(var d in l)~t.indexOf(d)?D.config[d]=ee(l[d]).map(f).concat(D.config[d]):void 0===n[d]&&(D.config[d]=l[d])}D.isMobile=!D.config.disableMobile&&!D.config.inline&&"single"===D.config.mode&&!D.config.disable.length&&!D.config.enable.length&&!D.config.weekNumbers&&/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),U("onParseConfig")}(),Y(),function(){if(D.input=D.config.wrap?s.querySelector("[data-input]"):s,!D.input)return D.config.errorHandler(new Error("Invalid input element specified"));D.input._type=D.input.type,D.input.type="text",D.input.classList.add("flatpickr-input"),D._input=D.input,D.config.altInput&&(D.altInput=se(D.input.nodeName,D.input.className+" "+D.config.altInputClass),D._input=D.altInput,D.altInput.placeholder=D.input.placeholder,D.altInput.disabled=D.input.disabled,D.altInput.required=D.input.required,D.altInput.tabIndex=D.input.tabIndex,D.altInput.type="text",D.input.type="hidden",!D.config.static&&D.input.parentNode&&D.input.parentNode.insertBefore(D.altInput,D.input.nextSibling)),D.config.allowInput||D._input.setAttribute("readonly","readonly"),D._positionElement=D.config.positionElement||D._input}(),function(){D.selectedDates=[],D.now=D.parseDate(D.config.now)||new Date;var e=D.config.defaultDate||D.input.value;e&&K(e,D.config.dateFormat);var t=0<D.selectedDates.length?D.selectedDates[0]:D.config.minDate&&D.config.minDate.getTime()>D.now.getTime()?D.config.minDate:D.config.maxDate&&D.config.maxDate.getTime()<D.now.getTime()?D.config.maxDate:D.now;D.currentYear=t.getFullYear(),D.currentMonth=t.getMonth(),0<D.selectedDates.length&&(D.latestSelectedDateObj=D.selectedDates[0]),void 0!==D.config.minTime&&(D.config.minTime=D.parseDate(D.config.minTime,"H:i")),void 0!==D.config.maxTime&&(D.config.maxTime=D.parseDate(D.config.maxTime,"H:i")),D.minDateHasTime=!!D.config.minDate&&(0<D.config.minDate.getHours()||0<D.config.minDate.getMinutes()||0<D.config.minDate.getSeconds()),D.maxDateHasTime=!!D.config.maxDate&&(0<D.config.maxDate.getHours()||0<D.config.maxDate.getMinutes()||0<D.config.maxDate.getSeconds()),Object.defineProperty(D,"showTimeInput",{get:function(){return D._showTimeInput},set:function(e){D._showTimeInput=e,D.calendarContainer&&de(D.calendarContainer,"showTimeInput",e),D.isOpen&&H()}})}(),D.utils={getDaysInMonth:function(e,t){return void 0===e&&(e=D.currentMonth),void 0===t&&(t=D.currentYear),1===e&&(t%4==0&&t%100!=0||t%400==0)?29:D.l10n.daysInMonth[e]}},D.isMobile||function(){var e=window.document.createDocumentFragment();if(D.calendarContainer=se("div","flatpickr-calendar"),D.calendarContainer.tabIndex=-1,!D.config.noCalendar){if(e.appendChild((D.monthNav=se("div","flatpickr-months"),D.yearElements=[],D.monthElements=[],D.prevMonthNav=se("span","flatpickr-prev-month"),D.prevMonthNav.innerHTML=D.config.prevArrow,D.nextMonthNav=se("span","flatpickr-next-month"),D.nextMonthNav.innerHTML=D.config.nextArrow,x(),Object.defineProperty(D,"_hidePrevMonthArrow",{get:function(){return D.__hidePrevMonthArrow},set:function(e){D.__hidePrevMonthArrow!==e&&(de(D.prevMonthNav,"disabled",e),D.__hidePrevMonthArrow=e)}}),Object.defineProperty(D,"_hideNextMonthArrow",{get:function(){return D.__hideNextMonthArrow},set:function(e){D.__hideNextMonthArrow!==e&&(de(D.nextMonthNav,"disabled",e),D.__hideNextMonthArrow=e)}}),D.currentYearElement=D.yearElements[0],z(),D.monthNav)),D.innerContainer=se("div","flatpickr-innerContainer"),D.config.weekNumbers){var t=function(){D.calendarContainer.classList.add("hasWeeks");var e=se("div","flatpickr-weekwrapper");e.appendChild(se("span","flatpickr-weekday",D.l10n.weekAbbreviation));var t=se("div","flatpickr-weeks");return e.appendChild(t),{weekWrapper:e,weekNumbers:t}}(),n=t.weekWrapper,a=t.weekNumbers;D.innerContainer.appendChild(n),D.weekNumbers=a,D.weekWrapper=n}D.rContainer=se("div","flatpickr-rContainer"),D.rContainer.appendChild(E()),D.daysContainer||(D.daysContainer=se("div","flatpickr-days"),D.daysContainer.tabIndex=-1),C(),D.rContainer.appendChild(D.daysContainer),D.innerContainer.appendChild(D.rContainer),e.appendChild(D.innerContainer)}D.config.enableTime&&e.appendChild(function(){D.calendarContainer.classList.add("hasTime"),D.config.noCalendar&&D.calendarContainer.classList.add("noCalendar"),D.timeContainer=se("div","flatpickr-time"),D.timeContainer.tabIndex=-1;var e=se("span","flatpickr-time-separator",":"),t=fe("flatpickr-hour");D.hourElement=t.childNodes[0];var n=fe("flatpickr-minute");if(D.minuteElement=n.childNodes[0],D.hourElement.tabIndex=D.minuteElement.tabIndex=-1,D.hourElement.value=Z(D.latestSelectedDateObj?D.latestSelectedDateObj.getHours():D.config.time_24hr?D.config.defaultHour:function(e){switch(e%24){case 0:case 12:return 12;default:return e%12}}(D.config.defaultHour)),D.minuteElement.value=Z(D.latestSelectedDateObj?D.latestSelectedDateObj.getMinutes():D.config.defaultMinute),D.hourElement.setAttribute("data-step",D.config.hourIncrement.toString()),D.minuteElement.setAttribute("data-step",D.config.minuteIncrement.toString()),D.hourElement.setAttribute("data-min",D.config.time_24hr?"0":"1"),D.hourElement.setAttribute("data-max",D.config.time_24hr?"23":"12"),D.minuteElement.setAttribute("data-min","0"),D.minuteElement.setAttribute("data-max","59"),D.timeContainer.appendChild(t),D.timeContainer.appendChild(e),D.timeContainer.appendChild(n),D.config.time_24hr&&D.timeContainer.classList.add("time24hr"),D.config.enableSeconds){D.timeContainer.classList.add("hasSeconds");var a=fe("flatpickr-second");D.secondElement=a.childNodes[0],D.secondElement.value=Z(D.latestSelectedDateObj?D.latestSelectedDateObj.getSeconds():D.config.defaultSeconds),D.secondElement.setAttribute("data-step",D.minuteElement.getAttribute("data-step")),D.secondElement.setAttribute("data-min",D.minuteElement.getAttribute("data-min")),D.secondElement.setAttribute("data-max",D.minuteElement.getAttribute("data-max")),D.timeContainer.appendChild(se("span","flatpickr-time-separator",":")),D.timeContainer.appendChild(a)}return D.config.time_24hr||(D.amPM=se("span","flatpickr-am-pm",D.l10n.amPM[Q(11<(D.latestSelectedDateObj?D.hourElement.value:D.config.defaultHour))]),D.amPM.title=D.l10n.toggleTitle,D.amPM.tabIndex=-1,D.timeContainer.appendChild(D.amPM)),D.timeContainer}()),de(D.calendarContainer,"rangeMode","range"===D.config.mode),de(D.calendarContainer,"animate",!0===D.config.animate),de(D.calendarContainer,"multiMonth",1<D.config.showMonths),D.calendarContainer.appendChild(e);var i=void 0!==D.config.appendTo&&void 0!==D.config.appendTo.nodeType;if((D.config.inline||D.config.static)&&(D.calendarContainer.classList.add(D.config.inline?"inline":"static"),D.config.inline&&(!i&&D.element.parentNode?D.element.parentNode.insertBefore(D.calendarContainer,D._input.nextSibling):void 0!==D.config.appendTo&&D.config.appendTo.appendChild(D.calendarContainer)),D.config.static)){var o=se("div","flatpickr-wrapper");D.element.parentNode&&D.element.parentNode.insertBefore(o,D.element),o.appendChild(D.element),D.altInput&&o.appendChild(D.altInput),o.appendChild(D.calendarContainer)}D.config.static||D.config.inline||(void 0!==D.config.appendTo?D.config.appendTo:window.document.body).appendChild(D.calendarContainer)}(),function(){if(D.config.wrap&&["open","close","toggle","clear"].forEach(function(t){Array.prototype.forEach.call(D.element.querySelectorAll("[data-"+t+"]"),function(e){return o(e,"click",D[t])})}),D.isMobile)return function(){var e=D.config.enableTime?D.config.noCalendar?"time":"datetime-local":"date";D.mobileInput=se("input",D.input.className+" flatpickr-mobile"),D.mobileInput.step=D.input.getAttribute("step")||"any",D.mobileInput.tabIndex=1,D.mobileInput.type=e,D.mobileInput.disabled=D.input.disabled,D.mobileInput.required=D.input.required,D.mobileInput.placeholder=D.input.placeholder,D.mobileFormatStr="datetime-local"===e?"Y-m-d\\TH:i:S":"date"===e?"Y-m-d":"H:i:S",0<D.selectedDates.length&&(D.mobileInput.defaultValue=D.mobileInput.value=D.formatDate(D.selectedDates[0],D.mobileFormatStr)),D.config.minDate&&(D.mobileInput.min=D.formatDate(D.config.minDate,"Y-m-d")),D.config.maxDate&&(D.mobileInput.max=D.formatDate(D.config.maxDate,"Y-m-d")),D.input.type="hidden",void 0!==D.altInput&&(D.altInput.type="hidden");try{D.input.parentNode&&D.input.parentNode.insertBefore(D.mobileInput,D.input.nextSibling)}catch(e){}o(D.mobileInput,"change",function(e){D.setDate(e.target.value,!1,D.mobileFormatStr),U("onChange"),U("onClose")})}();var e=X(N,50);D._debouncedChange=X(p,me),D.daysContainer&&!/iPhone|iPad|iPod/i.test(navigator.userAgent)&&o(D.daysContainer,"mouseover",function(e){"range"===D.config.mode&&A(e.target)}),o(window.document.body,"keydown",F),D.config.static||o(D._input,"keydown",F),D.config.inline||D.config.static||o(window,"resize",e),void 0!==window.ontouchstart&&o(window.document,"touchstart",O),o(window.document,"mousedown",a(O)),o(window.document,"focus",O,{capture:!0}),!0===D.config.clickOpens&&(o(D._input,"focus",D.open),o(D._input,"mousedown",a(D.open))),void 0!==D.daysContainer&&(o(D.monthNav,"mousedown",a(V)),o(D.monthNav,["keyup","increment"],n),o(D.daysContainer,"mousedown",a(R))),void 0!==D.timeContainer&&void 0!==D.minuteElement&&void 0!==D.hourElement&&(o(D.timeContainer,["input","increment"],d),o(D.timeContainer,"mousedown",a(r)),o(D.timeContainer,["input","increment"],D._debouncedChange,{passive:!0}),o([D.hourElement,D.minuteElement],["focus","click"],function(e){return e.target.select()}),void 0!==D.secondElement&&o(D.secondElement,"focus",function(){return D.secondElement&&D.secondElement.select()}),void 0!==D.amPM&&o(D.amPM,"mousedown",a(function(e){d(e),p()})))}(),(D.selectedDates.length||D.config.noCalendar)&&(D.config.enableTime&&g(D.config.noCalendar?D.latestSelectedDateObj||D.config.minDate:void 0),G(!1)),t(),D.showTimeInput=0<D.selectedDates.length||D.config.noCalendar;var e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);!D.isMobile&&e&&H(),U("onReady")}(),D}function n(e,t){for(var n=Array.prototype.slice.call(e),a=[],i=0;i<n.length;i++){var o=n[i];try{if(null!==o.getAttribute("data-fp-omit"))continue;void 0!==o._flatpickr&&(o._flatpickr.destroy(),o._flatpickr=void 0),o._flatpickr=r(o,t||{}),a.push(o._flatpickr)}catch(e){console.error(e)}}return 1===a.length?a[0]:a}"undefined"!=typeof HTMLElement&&(HTMLCollection.prototype.flatpickr=NodeList.prototype.flatpickr=function(e){return n(this,e)},HTMLElement.prototype.flatpickr=function(e){return n([this],e)});var ge=function(e,t){return e instanceof NodeList?n(e,t):n("string"==typeof e?window.document.querySelectorAll(e):[e],t)};return ge.defaultConfig=b,ge.l10ns={en:Object.assign({},ae),default:Object.assign({},ae)},ge.localize=function(e){ge.l10ns.default=Object.assign({},ge.l10ns.default,e)},ge.setDefaults=function(e){ge.defaultConfig=Object.assign({},ge.defaultConfig,e)},ge.parseDate=oe({}),ge.formatDate=ie({}),ge.compareDates=re,"undefined"!=typeof jQuery&&(jQuery.fn.flatpickr=function(e){return n(this,e)}),Date.prototype.fp_incr=function(e){return new Date(this.getFullYear(),this.getMonth(),this.getDate()+("string"==typeof e?parseInt(e,10):e))},ge}); \ No newline at end of file diff --git a/webht/third_party/pay/views/payment_gai_setting.php b/webht/third_party/pay/views/payment_gai_setting.php new file mode 100644 index 00000000..097a3f7b --- /dev/null +++ b/webht/third_party/pay/views/payment_gai_setting.php @@ -0,0 +1,59 @@ +<form action="/webht.php/apps/pay/paymentService/gai_modal_save" method="post" id="form_modal_gai" name="form_modal_gai"> + <?php if ( ! empty($gai_info)) { ?> + <p>已录入订单 <?php echo!empty($old_order) ? $old_order : ""; ?></p> + <table class="table table-hover table-bordered"> + <thead> + <th>订单号</th> + <th>申请金额/币种</th> + <th>实收金额</th> + </thead> + <?php foreach ($gai_info as $key => $value) { ?> + <tr> + <td><?php echo $value->GAI_COLI_ID; ?></td> + <td><?php echo $value->GAI_SQJE; ?>&nbsp;<?php echo $value->GAI_SQJECurrency; ?></td> + <td><?php echo $value->GAI_SSJE; ?>&nbsp;CNY</td> + </tr> + <?php } ?> + </table> + <p>撤回以上订单收款记录, 并转移到订单: (手动录入的不会撤回) </p> + <?php } else { ?> + <dl class="dl-horizontal"> + <dt>交易号</dt> + <dd><?php echo $note->OPN_transactionId ?> ( <?php echo strtoupper($note->OPN_noticeType) . " " . $note->OPN_transactionResult; ?> )</dd> + </dl> + <dl class="dl-horizontal"> + <dt>付款金额</dt> + <dd><?php echo $note->OPN_currency . ' ' . $note->OPN_orderAmount ?></dd> + </dl> + <dl class="dl-horizontal"> + <dt>付款时间</dt> + <dd><?php echo $note->OPN_completeTime; ?></dd> + </dl> + <?php } ?> + <div class="input-group"> + <input type="text" class="form-control" id="pn_invoice" name="pn_invoice" value="<?php echo !empty($new_order) ? $new_order : $old_order; ?>" placeholder="输入订单号搜索匹配" > + <span class="input-group-addon search-btn" onclick="show_gai_modal('<?php echo $note->OPN_SN; ?>', $('#pn_invoice').val())"></span> + </div> + <label class="text-danger">订单号形如: 160414408_B , B商务订单,JJ160321052_T,T传统订单,请务必加上后缀</label> + <div>订单详细内容: </div> + <p> + <?php + if (!empty($order_info)) { + echo "COLI_SN => $order_info->COLI_SN<br/>"; + echo "COLI_ID => $order_info->COLI_ID<br/>"; + echo "OPI_Email => $order_info->OPI_Email<br/>"; + echo "OPI_Name => $order_info->OPI_Name<br/>"; + echo!empty($order_info->COLI_GroupCode) ? "COLI_GroupCode => $order_info->COLI_GroupCode<br/>" : false; + echo!empty($order_info->COLI_OrderDetailText) ? "COLI_OrderDetailText => $order_info->COLI_OrderDetailText\n" : false; + } else { + echo '找不到目标订单内容'; + } + ?> + </p> + <input type="hidden" name="pn_txn_id" id="pn_txn_id" value="<?php echo $note->OPN_transactionId; ?>" /> + <input type="hidden" name="pn_id" id="pn_id" value="<?php echo $note->OPN_SN; ?>" /> +</form> +<div class="dl-horizontal"> + <p><a href="javascript:void(0);" onclick="$('#note_original_data').toggle()" >原始数据</a></p> + <p> <span style="display: none;" id="note_original_data"><?php echo str_replace('","', '"<br/>"', $note->OPN_rawContent); ?></span></p> +</div> diff --git a/webht/third_party/pay/views/payment_list.php b/webht/third_party/pay/views/payment_list.php new file mode 100644 index 00000000..57310825 --- /dev/null +++ b/webht/third_party/pay/views/payment_list.php @@ -0,0 +1,303 @@ +<!DOCTYPE html> +<html> +<head> + <meta charset="utf-8"> + <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <meta name="referrer" content="always"> + <title>Payment List - China Highlights</title> + <script src="http://www.mycht.cn/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> + <link href="/css/webht/bootstrap.min.css" rel="stylesheet" type="text/css" /> + <link rel="stylesheet" href="/css/webht/flatpicker.min.css"> + <style type="text/css" media="screen and (max-width:767px)"></style> + <style type="text/css"> + .export_form_area{display: inline-block;padding: 6px;border: 1px solid #ccc;background-color: #ccc;/*position: absolute;top: 0;left: 17%;*/} + .trigger_export_btn{position: absolute;top: 0;left: 50%;} + .modal-dialog{width: 1024px;} + .navbar-header h1 {display: inline-block;margin-left: 30px;margin-right: 30px;} + .input-group-btn{border: 1px solid #ccc;padding: 5px;} + .search-btn{cursor: pointer; background: url(//data.chinahighlights.com/css/images/global/site-search-button.png) no-repeat center center;} + .input-check{width: 20px;height: 20px;} + label span{vertical-align: super;} + </style> +</head> +<body> + <!-- Button trigger modal --> + <!-- 先隐藏 --> + <button type="button" class="btn btn-primary trigger_export_btn hidden" data-toggle="modal" data-target="#exampleModal"> + 导出收款记录 &gt; + </button> + <!-- Modal --> + <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <h5 class="modal-title" id="exampleModalLabel">导出 Paypal 记录</h5> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"> + <span aria-hidden="true">&times;</span> + </button> + </div> + <div class="modal-body"> + <form class="form-horizontal" role="form" method="post" id="search_list" action="/webht.php/apps/paypal/index/export_list/"> + <div class="form-group row"> + <label for="from_date" class="col-md-4">使用上次</label> + <div class="col-md-16"> + <select class="form-control" id="date_history" name="date_history" onchange="set_start_date(this)"> + <option value="">选择一个开始记录</option> + <?php + if ( ! empty($record_flags)) { + foreach ($record_flags as $kf => $vf) { + echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true) . "@" . $vf->TEL_transactionCurrency . "\">" + . " [" . strstr($vf->TEL_exportDate, " ", true) . "] " + . $vf->TEL_transactionCurrency . " " . $vf->TEL_transactionAmount . ' - '. $vf->TEL_exportAmount + . " / " . $vf->TEL_orderId . ' / ' + . substr($vf->TEL_transactionDate,0,16) + . "</option>"; + } + } + ?> + </select> + </div> + </div> + <div class="form-group row"> + <label for="from_date" class="col-md-4">Date From</label> + <div class="col-md-16"> + <input type="text" class="form-control col-md-8" id="from_date" name="from_date" placeholder="开始日期" required> + </div> + </div> + <div class="form-group row"> + <label for="to_date" class="col-md-4">To</label> + <div class="col-md-16"> + <input type="text" class="form-control" id="to_date" name="to_date" placeholder="结束日期" required> + </div> + </div> + <div class="form-group row"> + <label for="currency" class="col-md-4">Currency</label> + <div class="col-md-16"> + <select class="form-control" id="currency" name="currency" required> + <option value="">所有币种</option> + <option value="CNY">CNY</option> + <option value="USD">USD</option> + <option value="EUR">EUR</option> + <option value="CAD">CAD</option> + <option value="AUD">AUD</option> + <option value="GBP">GBP</option> + <option value="NZD">NZD</option> + <option value="SGD">SGD</option> + <option value="CHF">CHF</option> + </select> + </div> + </div> + <div class="form-group row"> + <label for="set_amount" class="col-md-4">总金额(元)</label> + <div class="col-md-16"> + <input type="number" class="form-control" id="set_amount" name="set_amount" placeholder="总金额" onkeyup="set_target_amount(this)"> + </div> + </div> + <div class="form-group"> + <div class="col-sm-24 "> + <button type="submit" class="btn btn-primary center-block">导出</button> + </div> + </div> + </form> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button> + </div> + </div> + </div> + </div> + <div id="wrapper" class="chkVisible print-none"> + <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> + <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="https://www.mycht.cn/webht.php/index/index"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + <h1>Payment List</h1> + <label> + <input type="checkbox" name="" value="15016" checked readonly class="input-check"><span>微信</span> + </label> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> + <li class="dropdown"> + <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> + <ul class="dropdown-menu" role="menu"> + <li><a href="<?php echo site_url('login/logout'); ?>">退出</a></li> + </ul> + </li> + </ul> + </div> + </div> + <div class="" id="content"> + <div class="container-fluid marginTop"> + <div class="row"> + <!-- left --> + <div class="col-md-4 col-xs-24 print-none"> + <div class="row"> + <form method="post" id="search_note_list" action="/webht.php/apps/pay/paymentservice/note_list/"> + <div class="input-group"> + <input type="text" name="keywords" value="<?php echo isset($keywords) ? $keywords : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> + <span class="input-group-addon search-btn" onclick="$('#search_note_list').submit();"></span> + </div> + <div id="datepicker"></div> + </form> + </div> + <p class="btn-lg"></p> + <ul class="list-unstyled hidden-xs links"> + <li><a class="text-primary" href="/webht.php/apps/pay/paymentservice/note_list">&gt;全部收款邮件</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="/webht.php/apps/pay/paymentservice/note_faillist" >&gt;错误通知列表</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="/webht.php/apps/pay/paymentservice/send_notify" target="_blank">&gt;手动处理通知</a></li> + <li class="btn-sm"></li> + <li><a class="text-primary" href="http://share.chtcdn.com/info.php/sendmail/send_mail" target="_blank">&gt;发送邮件</a></li> + <li class="btn-lg"></li> + </ul> + <div class="well well-sm hidden-xs" > + <h4>通知状态:</h4> + <p>1.send 表示通知正确发送给外联</p> + <p>2.unsend 表示通知在等待处理,5~10分钟系统处理一遍</p> + <p>3.sendfail 状态的需要手工设置正确的订单号</p> + <p>4.Pending 还未到账,需要人工检查,确认支付或者取消,需要手工关闭此通知</p> + <p>5.Denied 银行拒付,需要手工关闭此通知</p> + </div> + </div> + <!-- left end --> + <div class=" pay_form_div col-sm-20 col-xs-24" style="min-height:1024px;border-left:1px solid #ddd;"> + <table class="table table-bordered table-hover"> + <thead> + <tr> + <th>#</th> + <th>主题</th> + <th>付款人</th> + <th>交易号</th> + <th>收单时间</th> + <th>通知时间</th> + <th>状态[通知/记录]</th> + </tr> + </thead> + <tbody> + <?php + foreach ($notelist as $key => $item) { + ?> + <tr> + <td><?php echo $key+1; ?></td> + <td><?php echo $item->OPN_orderId . ' / ' . $item->OPN_orderAmount . $item->OPN_currency; ?></td> + <td> + <?php + echo $item->OPN_payerEmail; + ?> + </td> + <td><?php echo $item->OPN_transactionId; ?></td> + <td><?php echo $item->OPN_acquiringTime; ?></td> + <td><?php echo $item->OPN_noticeTime; ?></td> + <td> + <?php + $send_text = '';$send_class=''; + if ($item->OPN_accountStatus !== 'recorded') { + $send_class = 'btn-danger'; + } + if ($item->OPN_noticeSendStatus !== 'send' ) { + $send_class = 'btn-danger'; + } + if ($item->OPN_noticeSendStatus === 'closed') { + $send_class = ''; + } + ?> + <?php if ($item->OPN_noticeType !== 'pay') { + echo '<span class=text-danger >' . strtoupper($item->OPN_noticeType) . '</span><br>'; + } ?> + <a href="javascript:void(0);" class="btn btn-sm <?php echo $send_class; ?>" onclick="show_gai_modal('<?php echo $item->OPN_SN; ?>')"> + <?php echo $item->OPN_noticeSendStatus .' / ' . $item->OPN_accountStatus; ?> + </a> + </td> + </tr> + <?php } ?> + </tbody> + </table> + </div> + <!-- right end --> + </div> + </div> + </div> + <!-- 收款记录详情 --> + <div class="modal" id="modal_set_gai" tabindex="-1" role="dialog" aria-labelledby="gaiModalLabel"> + <div class="modal-dialog" role="document"> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal" aria-label="Close"> + <span aria-hidden="true">&times;</span></button> + <h4 class="modal-title" id="gaiModalLabel">收款记录</h4> + </div> + <div class="modal-body" id="modal_set_gai_body"> + ... + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-warning pull-left" onclick="close_gai()" >忽略此条收款</button> + <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> + <button type="button" class="btn btn-warning" onclick="submit_gai_modal()">保存</button> + </div> + </div> + </div> + </div> +</body> +<script type="text/javascript" src="/js/flatpickr-4.4.4.min.js"></script> +<script type="text/javascript"> + $(document).ready(function() { + $("#datepicker").flatpickr({ + inline: true, + dateFormat: "Y-m-d", + defaultDate: "<?php echo $date; ?>", + onChange: function (selectedDates, dateStr, instance) { + window.location.href = '/webht.php/apps/pay/paymentservice/note_list?date=' + dateStr; + } + }); + }) + function show_gai_modal(pn_id, new_order) { + var url = '/webht.php/apps/pay/paymentservice/gai_modal/' + pn_id; + if (new_order) url += '/' + new_order; + $.ajax({ + type: "get", + dataType: "json", + url: url, + success: function(data, textStatus) { + $('#modal_set_gai_body').html(data); + $('#modal_set_gai').modal('show'); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYoyo...'); + } + }); + } + function close_gai() { + var pn_id = $('#pn_id').val(); + var pn_txn_id = $('#pn_txn_id').val(); + if (confirm('是否忽略此记录: ' + pn_txn_id)) { + $.ajax({ + type: "get", + dataType: "json", + url: '/webht.php/apps/pay/paymentservice/close_gai/' + pn_id, + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + } + }); + } + } + function submit_gai_modal() { + $('#form_modal_gai').ajaxSubmit({ + success: function(data, textStatus) { + alert(data); + }, + error: function(msg) { + alert('\u53d1\u751f\u9519\u8bef\uff0c\u8bf7\u8054\u7cfbYOYO...'); + }, + dataType: 'json', + timeout: 30000 + }); + return false; + } +</script> +</html> From 5a639a518fd479437c7d64404cadf511f06c9133 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 29 Apr 2019 16:15:12 +0800 Subject: [PATCH 303/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=87=BA=E7=A5=A8=E7=AB=99=E7=82=B9=E3=80=82=20=E4=BF=AE?= =?UTF-8?q?=E6=94=B9=E5=85=A5=E5=BA=93=E6=94=AF=E4=BB=98=E8=AE=B0=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/trainsystem/controllers/check.php | 2 +- .../third_party/trainsystem/models/BIZ_train_model.php | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/application/third_party/trainsystem/controllers/check.php b/application/third_party/trainsystem/controllers/check.php index 0344df4d..49f0d110 100644 --- a/application/third_party/trainsystem/controllers/check.php +++ b/application/third_party/trainsystem/controllers/check.php @@ -393,7 +393,7 @@ class check extends CI_Controller{ }*/ //调试代码 - $test_post = '{"data":"{\"from_station_name\":\"\u5317\u4eac\u5357\",\"from_station_code\":\"VNP\",\"to_station_name\":\"\u4e0a\u6d77\u8679\u6865\",\"to_station_code\":\"AOH\",\"train_date\":\"2019-05-08\",\"orderid\":\"JH155489661120411\",\"user_orderid\":\"488128168\",\"orderamount\":\"3496.00\",\"ordernumber\":\"EE79032518\",\"checi\":\"G43\",\"msg\":\"\u7ebf\u4e0a\u9000\u7968\u6210\u529f\",\"status\":\"7\",\"passengers\":[{\"passengerid\":1,\"passengersename\":\"WEISIGKOLIVER\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CAYLW9WTT\",\"price\":\"1748.0\",\"zwcode\":\"9\",\"zwname\":\"\u5546\u52a1\u5ea7\",\"ticket_no\":\"EE79032518103005A\",\"cxin\":\"03\u8f66\u53a2,05A\u5ea7\",\"reason\":0,\"refundTimeline\":[{\"time\":\"2019-04-11 11:46:10\",\"msg\":\"\u7ebf\u4e0a\u7533\u8bf7\u9000\u7968\"},{\"time\":\"2019-04-11 11:46:41\",\"msg\":\"\u7ebf\u4e0a\u9000\u7968\u6210\u529f\",\"detail\":{\"returnsuccess\":true,\"returnmoney\":\"1748\",\"returnfailid\":\"\",\"returnfailmsg\":\"\",\"returntype\":\"1\",\"ticket_no\":\"EE79032518103005A\",\"passengername\":\"WEISIGKOLIVER\",\"passporttypeseid\":\"B\",\"passportseno\":\"CAYLW9WTT\"}}],\"returntickets\":{\"returnsuccess\":true,\"returnmoney\":\"1748\",\"returntime\":\"2019-04-11 11:46:39\",\"returnfailid\":\"\",\"returnfailmsg\":\"\",\"returntype\":\"1\"}},{\"passengerid\":2,\"passengersename\":\"ALBERTSTEFANIECAROLINDOROTHEE\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"CAYLM2751\",\"price\":\"1748.0\",\"zwcode\":\"9\",\"zwname\":\"\u5546\u52a1\u5ea7\",\"ticket_no\":\"EE79032518103005C\",\"cxin\":\"03\u8f66\u53a2,05C\u5ea7\",\"reason\":0,\"refundTimeline\":[{\"time\":\"2019-04-11 11:46:12\",\"msg\":\"\u7ebf\u4e0a\u7533\u8bf7\u9000\u7968\"}]}],\"refund_money\":\"1748.00\",\"sign\":\"f077215579ecd5c130d39b502c9bd055\"}"}'; + $test_post = '{"data":"{\"from_station_name\":\"\u5e7f\u5dde\u5357\",\"from_station_code\":\"IZQ\",\"to_station_name\":\"\u9999\u6e2f\u897f\u4e5d\u9f99\",\"to_station_code\":\"XJA\",\"train_date\":\"2019-04-29\",\"orderid\":\"JH155651319519711\",\"user_orderid\":\"488132483\",\"orderamount\":\"374.00\",\"ordernumber\":\"E244376926\",\"checi\":\"G6537\",\"msg\":\"\u51fa\u7968\u6210\u529f\",\"status\":\"4\",\"passengers\":[{\"passengerid\":1,\"passengersename\":\"PRIETORAMOSJORGECLAUDIO\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"AAC408307\",\"price\":\"187.0\",\"zwcode\":\"O\",\"zwname\":\"\u4e8c\u7b49\u5ea7\",\"ticket_no\":\"E244376926111013D\",\"cxin\":\"11\u8f66\u53a2,13D\u5ea7\",\"reason\":0},{\"passengerid\":2,\"passengersename\":\"SALAZARNATALIAGISELA\",\"piaotype\":\"1\",\"piaotypename\":\"\u6210\u4eba\u7968\",\"passporttypeseid\":\"B\",\"passporttypeseidname\":\"\u62a4\u7167\",\"passportseno\":\"AAC419811\",\"price\":\"187.0\",\"zwcode\":\"O\",\"zwname\":\"\u4e8c\u7b49\u5ea7\",\"ticket_no\":\"E244376926111013F\",\"cxin\":\"11\u8f66\u53a2,13F\u5ea7\",\"reason\":0}],\"refund_money\":null,\"sign\":\"831c146e2ce223a5437ed78db0ec8c25\"}"}'; $data_post["data"] = json_decode($test_post)->data; diff --git a/application/third_party/trainsystem/models/BIZ_train_model.php b/application/third_party/trainsystem/models/BIZ_train_model.php index bd392858..d6401575 100644 --- a/application/third_party/trainsystem/models/BIZ_train_model.php +++ b/application/third_party/trainsystem/models/BIZ_train_model.php @@ -240,7 +240,7 @@ class BIZ_train_model extends CI_Model { TOC_WL, TOC_OtherCost ) - VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT isnull(COLI_OPI_ID,29) FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)"; + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT isnull(COLI_OPI_ID,29) FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT isnull(COLI_OPI_ID,29) FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)"; $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%",$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost,$data->TOC_Memo." 手续费",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->poundage)); } return $query; @@ -260,7 +260,7 @@ class BIZ_train_model extends CI_Model { ON bcli.COLI_SN = bgai.GAI_COLI_SN WHERE bcli.COLI_ServiceType = '2' AND bcli.COLI_State in ('11','13','8','63') - AND bcli.COLI_WebCode in ('cht', 'JP', 'train_it', 'VC', 'train_ru','GM-Train','SHT','CT') + AND bcli.COLI_WebCode in ('cht', 'JP', 'train_it', 'VC', 'train_ru','GM-Train','SHT','CT','WebMob-biz','WeChat-biz') AND (bcli.COLI_Price - bgai.GAI_SQJE) <= 20 AND (bcli.COLI_Price - bgai.GAI_SQJE) >= 0 AND bcli.DeleteFlag = 0 From 7b5ff8a08fa351e4ba323b2d4230518c2a7e72df Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 29 Apr 2019 17:05:00 +0800 Subject: [PATCH 304/382] =?UTF-8?q?=E7=9F=AD=E4=BF=A1=E5=8F=91=E9=80=81?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=92=8C=E8=AE=A2=E5=8D=95=E6=9D=A5=E6=BA=90?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E7=B3=BB=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ctrip/controllers/ctrip_train.php | 24 +++ .../tripadvisor_spider/config/config.php | 6 +- .../tripadvisor_spider/controllers/index.php | 158 ++++++++++++++- .../messagecenter/controllers/index.php | 183 ++++++++++++++++++ .../messagecenter/helpers/message_helper.php | 31 +++ .../messagecenter/views/message_index.php | 52 +++++ .../ordersfrom/controllers/index.php | 81 ++++++++ .../ordersfrom/models/ordersfrom_model.php | 45 +++++ .../ordersfrom/views/ah_orders.php | 62 ++++++ webht/third_party/ordersfrom/views/index.php | 120 ++++++++++++ 10 files changed, 760 insertions(+), 2 deletions(-) create mode 100644 webht/third_party/messagecenter/controllers/index.php create mode 100644 webht/third_party/messagecenter/helpers/message_helper.php create mode 100644 webht/third_party/messagecenter/views/message_index.php create mode 100644 webht/third_party/ordersfrom/controllers/index.php create mode 100644 webht/third_party/ordersfrom/models/ordersfrom_model.php create mode 100644 webht/third_party/ordersfrom/views/ah_orders.php create mode 100644 webht/third_party/ordersfrom/views/index.php diff --git a/application/third_party/ctrip/controllers/ctrip_train.php b/application/third_party/ctrip/controllers/ctrip_train.php index 7f818f37..1836268e 100644 --- a/application/third_party/ctrip/controllers/ctrip_train.php +++ b/application/third_party/ctrip/controllers/ctrip_train.php @@ -123,6 +123,12 @@ class ctrip_train extends CI_Controller{ $rwNum = $Seats->TicketLeft; } + if($Seats->SeatName == '一等双软下'){ + $ydrwPrice = $Seats->Price * 10; + $SeaType .= '"I":"'.$ydrwPrice.'","AI":"¥'.$Seats->Price.'",'; + $ydrwNum = $Seats->TicketLeft; + } + if($Seats->SeatName == '软座'){ $rzPrice = $Seats->Price * 10; $SeaType .= '"2":"'.$rzPrice.'","A2":"¥'.$Seats->Price.'",'; @@ -167,6 +173,12 @@ class ctrip_train extends CI_Controller{ $ywNum = $Seats->TicketLeft; } + if($Seats->SeatName == '二等双软下'){ + $errwPrice = $Seats->Price * 10; + $SeaType .= '"J":"'.$errwPrice.'","AJ":"¥'.$Seats->Price.'",'; + $errwNum = $Seats->TicketLeft; + } + if($Seats->SeatName == '动卧下'){ $SeaType .= '"F":"¥'.$Seats->Price.'",'; $dwNum = $Seats->TicketLeft; @@ -175,6 +187,7 @@ class ctrip_train extends CI_Controller{ $PriceStr = $SeaType.'"train_no":'.'"'.$TrainInfo->TrainNo.'"'; } + //对返回的数据进行容错处理 $gjrwNum = isset($gjrwNum) ? ticket_exchange($gjrwNum,$iseven) : ''; $rwNum = isset($rwNum) ? ticket_exchange($rwNum,$iseven) : ''; @@ -187,6 +200,17 @@ class ctrip_train extends CI_Controller{ $ydzNum = isset($ydzNum) ? ticket_exchange($ydzNum,$iseven) : ''; $swzNum = isset($swzNum) ? ticket_exchange($swzNum,$iseven) : ''; $dwNum = isset($dwNum) ? ticket_exchange($dwNum,$iseven) : ''; + $ydrwNum = isset($ydrwNum) ? ticket_exchange($ydrwNum,$iseven) : ''; + $errwNum = isset($errwNum) ? ticket_exchange($errwNum,$iseven) : ''; + + if($rwNum == '' && $ydrwNum != ''){ + $rwNum = $ydrwNum; + } + + if($ywNum == '' && $errwNum != ''){ + $ywNum = $errwNum; + } + $runMin = $TrainInfo->DurationMinutes % 60; $runHour = ($TrainInfo->DurationMinutes - $runMin) / 60; diff --git a/application/third_party/tripadvisor_spider/config/config.php b/application/third_party/tripadvisor_spider/config/config.php index b76a507d..022d61f8 100644 --- a/application/third_party/tripadvisor_spider/config/config.php +++ b/application/third_party/tripadvisor_spider/config/config.php @@ -17,7 +17,11 @@ $config['tripadvisor_website'] = array( 'Lijiang' => 'http://www.tripadvisor.com/Attraction_Review-g303783-d8464335-Reviews{PAGENUM}China_Highlights_Lijiang-Lijiang_Yunnan.html', 'Zhangjiajie' => 'http://www.tripadvisor.com/Attraction_Review-g494933-d8077695-Reviews{PAGENUM}China_Highlights_Zhangjiajie_Day_Tour-Zhangjiajie_Hunan.html', 'HongKong' => 'https://www.tripadvisor.com/Attraction_Review-g294217-d10243951-Reviews{PAGENUM}China_Highlights_Hong_Kong-Hong_Kong.html', - 'Panda' => 'https://www.tripadvisor.com/Attraction_Review-g297463-d11489225-Reviews{PAGENUM}China_Highlights-Chengdu_Sichuan.html' + 'Panda' => 'https://www.tripadvisor.com/Attraction_Review-g297463-d11489225-Reviews{PAGENUM}China_Highlights-Chengdu_Sichuan.html', + 'tp_Beijing' => 'https://www.tripadvisor.com/Attraction_Review-g294212-d4006739-Reviews-The_Trippest_Mini_Group_Tours-Beijing.html', + 'tp_Xian' => 'https://www.tripadvisor.com/Attraction_Review-g298557-d10999897-Reviews-Xi_an_Trippest_Mini_Group_Tours-Xi_an_Shaanxi.html', + 'tp_Shanghai' => 'https://www.tripadvisor.com/Attraction_Review-g308272-d6222868-Reviews-Shanghai_Trippest_Mini_Group_Tours-Shanghai.html', + 'tp_Guilin' => 'https://www.tripadvisor.com/Attraction_Review-g298556-d14121459-Reviews-Trippest_Mini_Group_Tours-Guilin_Guangxi.html' ); diff --git a/application/third_party/tripadvisor_spider/controllers/index.php b/application/third_party/tripadvisor_spider/controllers/index.php index e2dee812..6bc23ea5 100644 --- a/application/third_party/tripadvisor_spider/controllers/index.php +++ b/application/third_party/tripadvisor_spider/controllers/index.php @@ -11,6 +11,11 @@ class Index extends CI_Controller { public function __construct() { parent::__construct(); //$this->output->enable_profiler(TRUE); + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); $this->load->model('Tripadvisor_Review_model'); } @@ -186,5 +191,156 @@ class Index extends CI_Controller { } echo json_encode(array('group_result' => $this->load->view('find_group_result', $data, true), 'tr_content' => $data['ta_review']->tr_content)); } - + + //第三方数据导入 + public function third_party_input(){ + $this->load->view('bootstrap3/header'); + $this->load->view('third_party_input'); + $this->load->view('bootstrap3/footer'); + } + + function ensure_writable_dir($dir) { + if(!file_exists($dir)) { + mkdir($dir, 0766, true); + chmod($dir, 0766); + chmod($dir, 0777); + }else if(!is_writable($dir)) { + chmod($dir, 0766); + chmod($dir, 0777); + if(!is_writable($dir)) { + throw new FileSystemException("目录 $dir 不可写"); + } + } + } + + //第三方数据录入 + public function analysis_excel(){ + $filename = date('Y').date('m').date('d').date('h').date('i').date('s').'.'.explode('.',$_FILES['fileArray']['name'])[1]; + $tmp = $_FILES['fileArray']['tmp_name']; + $error = $_FILES['fileArray']['error']; + if($error > 0){ + header("HTTP/1.1 404 Not Found"); + echo '{"status":404,"message":'.$_FILES["fileArray"]["error"].'}'; + }else{ + $path = 'upload/'.date('Y').'/'.date('m').'/'; + $this->ensure_writable_dir($path); + if(move_uploaded_file($tmp,$path.$filename)){ + require_once "PHPExcel/IOFactory.php"; + $phpExcel = PHPExcel_IOFactory::load($path.$filename); + + //创建返回的数组 + $data = []; + foreach ($phpExcel->getSheetNames() as $key=>$destination){ + $data[$key] = new stdClass(); + $data[$key]->destination = $destination; + $data[$key]->list_name = array(); + $data[$key]->list_data = array(); + //循环获取每个表格的行/列数 + $row = $phpExcel->getActiveSheet()->getHighestRow(); + $column = $phpExcel->getActiveSheet()->getHighestColumn(); + $j = 0; + // 行数循环 + for ($i = 1; $i <= $row; $i++) { + // 列数循环 + for ($c = 'A'; $c <= $column; $c++) { + if($phpExcel->getActiveSheet($key)->getCell('A' . $i)->getValue() == ''){ + continue; + }else{ + if($i == 1){ + array_push($data[$key]->list_name,$phpExcel->getActiveSheet($key)->getCell($c . $i)->getValue()); + }else{ + $data[$key]->list_data[$j][] = $phpExcel->getActiveSheet($key)->getCell($c . $i)->getValue(); + } + + } + } + $j++; + } + } + //返回处理完后的json + print_r(json_encode($data)); + }else{ + header("HTTP/1.1 404 Not Found"); + echo '{"status":404,"message":"文件上传失败!","picname":""}'; + } + } + } + + public function get_destination_reviews($destination = null){ + $ta_website = $this->config->item('tripadvisor_website'); + + //根据传入的目的地简码获取TA的相应评论列表 + if(isset($ta_website[$destination])){ + $url = $ta_website[$destination]; + + //根据url获取页面内容 + $content = GET_HTTP($url); + + //进行页面解析 + $html_object = str_get_html($content); + + //获取第一页列表上的url + foreach ($html_object->find('.reviewSelector .quote a') as $a_info){ + $url = 'https://www.tripadvisor.com'.$a_info->href; + + } + } + } + + function get_reviews_detail(){ + set_time_limit(0); + $url = $this->input->get_post('url'); + $destination = $this->input->get_post('destination'); + + //$url = 'https://www.tripadvisor.com/ShowUserReviews-g294212-d4006739-r666168101-The_Trippest_Mini_Group_Tours-Beijing.html'; + $destination = 'tp_Beijing'; + + if($url != ''){ + $content = GET_HTTP($url); + $html_object = str_get_html($content); + + //做一个数组用于存储数据 + $detail_data = new stdClass(); + $detail_data->destination = $destination; + + //提取局部,不做整个页面的寻找元素,提升效率 + $meta_inner = $html_object->find('.meta_inner'); + + foreach($meta_inner as $detail_info){ + //获取评论者帐号 + foreach($detail_info->find('.info_text') as $review_name){ + $detail_data->review_name = $review_name->first_child()->innertext; + } + + //获取评论者ID + foreach($detail_info->find('.reviewSelector') as $review_id){ + $detail_data->review_id = str_replace('review_','',$review_id->id); + } + + //获取标题 + foreach($detail_info->find('#HEADING') as $title){ + $detail_data->title = $title->innertext; + } + + //获取星级 + foreach($detail_info->find('.ui_bubble_rating') as $star_nums){ + $detail_data->star_nums = str_replace('ui_bubble_rating ','',$star_nums->getAttribute('class')); + $detail_data->star_nums = str_replace(array('bubble_50','bubble_40','bubble_30','bubble_20'),array(5,4,3,2),$detail_data->star_nums); + } + + //获取评论内容 + foreach($detail_info->find('.partial_entry .fullText') as $content){ + $detail_data->content = $content->innertext; + } + + //获取评论时间 + foreach($detail_info->find('.prw_reviews_stay_date_hsx') as $review_date){ + $detail_data->review_date = str_replace('<span class="stay_date_label">Date of experience:</span> ','',$review_date->innertext); + } + } + + //拿到数据后进行入库 + print_r(json_encode($detail_data)); + } + } } diff --git a/webht/third_party/messagecenter/controllers/index.php b/webht/third_party/messagecenter/controllers/index.php new file mode 100644 index 00000000..2ac45867 --- /dev/null +++ b/webht/third_party/messagecenter/controllers/index.php @@ -0,0 +1,183 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class Index extends CI_Controller { + + public function __construct() { + parent::__construct(); + $this->load->helper('message'); + $this->key = '3d15821171548bf7d0a93afab66e797b'; + $this->sendsms = 'https://yun.tim.qq.com/v5/tlssmssvr/sendsms'; + } + + public function test(){ + echo phpinfo(); + /*try { + echo '1'; + } finally { + echo '2'; + }*/ + } + + public function index(){ + $this->load->view('n-header'); + $this->load->view('message_index'); + } + + //新建短信模板 + public function add_templete(){ + $templete = htmlspecialchars($this->input->post('templete')); + $title = $this->input->post('title'); + + if(empty($templete)){ + header("HTTP/1.1 404 Not Found"); + exit('{"status":"404","reason":"传参为空!"}'); + } + + if(empty($title)){ + $title = 'trippset'.rand(1,100); + } + + $random = rand(1000,9999); + $time = time(); + $sig = 'appkey='.$this->key.'&random='.$random.'&time='.$time; + $sig = hash("sha256", $sig); + + $post_str = '{ + "remark": "", + "sig": "'.$sig.'", + "text": "'.$templete.'", + "time": '.$time.', + "title": "'.$title.'", + "type": 1 + }'; + + $url = 'https://yun.tim.qq.com/v5/tlssmssvr/add_template?sdkappid=1400082793&random='.$random; + + $back_json = sms_post($url,$post_str,'POST'); + $back_data = json_decode($back_json); + print_r($back_data); + + } + + //查询短信模板状态 + public function search_templete_status(){ + $random = rand(1000,9999); + $time = time(); + $sig = 'appkey='.$this->key.'&random='.$random.'&time='.$time; + $sig = hash("sha256", $sig); + + $post_str = '{ + "sig": "'.$sig.'", + "time": '.$time.', + "tpl_page": { + "max": 10, + "offset": 0 + } + }'; + + $url = 'https://yun.tim.qq.com/v5/tlssmssvr/get_template?sdkappid=1400082793&random='.$random; + $back_json = sms_post($url,$post_str,'POST'); + $back_data = json_decode($back_json); + print_r($back_data); + } + + //短信模板更新 + public function update_templete($id,$title){ + $contents = "Hi {1}, your guide on {2} is {3}, (local)mobile is {4}. He/she'll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No. {5} at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest!"; + $random = rand(1000,9999); + $time = time(); + $sig = 'appkey='.$this->key.'&random='.$random.'&time='.$time; + $sig = hash("sha256", $sig); + + $post_str = '{ + "sig": "'.$sig.'", + "text": "'.$contents.'", + "time": '.$time.', + "title": "'.$title.'", + "tpl_id": '.$id.', + "type": 0 + }'; + + $url = 'https://yun.tim.qq.com/v5/tlssmssvr/mod_template?sdkappid=1400082793&random='.$random; + $back_json = sms_post($url,$post_str,'POST'); + $back_data = json_decode($back_json); + print_r($back_data); + } + + //删除模板 + public function delete_templete(){ + $random = rand(1000,9999); + $time = time(); + $sig = 'appkey='.$this->key.'&random='.$random.'&time='.$time; + $sig = hash("sha256", $sig); + + $post_str = '{ + "sig": "'.$sig.'", + "time": '.$time.', + "tpl_id": [ + 212919, + 213082 + ] + }'; + + $url = 'https://yun.tim.qq.com/v5/tlssmssvr/del_template?sdkappid=1400082793&random='.$random; + $back_json = sms_post($url,$post_str,'POST'); + $back_data = json_decode($back_json); + print_r($back_data); + } + + //发送短信 + public function send_message(){ + //接收参数 + //1-4为四个参数依次排序 字符格式不做限制 + $one = $this->input->post('one'); + $two = $this->input->post('two'); + $three = $this->input->post('three'); + $four = $this->input->post('four'); + $five = $this->input->post('five'); + //手机号 * 必填 + $phone = $this->input->post('phone'); + //区号 * 必填 + $nation_code = $this->input->post('nation_code'); + + if(empty($phone) || empty($nation_code)){ + header("HTTP/1.1 404 Not Found"); + exit('{"status":"404","reason":"传参为空!"}'); + } + + //构造发送短信的报文 + $random = rand(1000,9999); + $time = time(); + $sig = 'appkey='.$this->key.'&random='.$random.'&time='.$time.'&mobile='.$phone; + $sig = hash("sha256", $sig); + $mysign = '[ChinaHighlights]'; + + if($nation_code == 86){ + $mysign = '【桂林海纳国旅】'; + } + + $post_str = '{ + "ext": "", + "extend": "", + "msg": "Hi '.$one.', your guide on '.$two.' is '.$three.', (local) mobile is '.$four.'. He/she\'ll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No. '.$five.' at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest!", + "sig": "'.$sig.'", + "tel": { + "mobile": "'.$phone.'", + "nationcode": "'.$nation_code.'" + }, + "time": '.$time.', + "type": 0 + }'; + + $url = 'https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=1400082793&random='.$random; + $back_json = sms_post($url,$post_str,'POST'); + $back_data = json_decode($back_json); + print_r($back_json); + } + +} + + +?> \ No newline at end of file diff --git a/webht/third_party/messagecenter/helpers/message_helper.php b/webht/third_party/messagecenter/helpers/message_helper.php new file mode 100644 index 00000000..8634dd43 --- /dev/null +++ b/webht/third_party/messagecenter/helpers/message_helper.php @@ -0,0 +1,31 @@ +<?php + //发送请求函数 + function sms_post($url, $data = '', $method = 'GET') { + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 + //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + if ($method == 'POST' && !empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=UTF-8')); + } + curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $tmpInfo = curl_exec($curl); // 执行操作 + $errno = curl_errno($curl); + if ($errno !== 0) { + return false; + echo $errno . curl_error($curl); //记录错误日志 + } + curl_close($curl); //关闭CURL会话 + return $tmpInfo; //返回数据 + } + + function hello(){ + echo 'hello'; + } \ No newline at end of file diff --git a/webht/third_party/messagecenter/views/message_index.php b/webht/third_party/messagecenter/views/message_index.php new file mode 100644 index 00000000..4e70dfd4 --- /dev/null +++ b/webht/third_party/messagecenter/views/message_index.php @@ -0,0 +1,52 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel-heading"> + <ul class="nav nav-tabs"> + <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li> + <li role="presentation"><a href="#manager" aria-controls="manager" role="tab" data-toggle="tab">管理页面</a></li> + <li role="presentation"><a href="#sendsms" aria-controls="sendsms" role="tab" data-toggle="tab">发送短信页面</a></li> + </ul> + </div> + + <div class="tab-content" style="padding:0 30px"> + <div role="tabpanel" class="tab-pane active" id="home"> + <div class="text-center"> + <h1>短信发送中心</h1> + <p>版本1.0</p> + <p>可以正常添加模板,但是只有一个模板可以发送</p> + </div> + </div> + + <div role="tabpanel" class="tab-pane" id="manager"> + <form action="http://www.mycht.cn/webht.php/apps/messagecenter/index/add_templete" method="post" name="add_template"> + <p>模板示例:Hi {1}, your guide on {2} is {3}, (local)mobile is {4}. He/she'll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No. {5} at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest!</p> + <label for="addtemplate">输入模板:</label> + <textarea id="addtemplate" class="form-control" name="templete"></textarea> + <br> + <button type="submit" class="btn btn-default">添加模板</button> + </form> + </div> + + <div role="tabpanel" class="tab-pane" id="sendsms"> + <p>模板示例:Hi {1}, your guide on {2} is {3}, (local)mobile is {4}. He/she'll call you at the hotel, or leave a message tonight. You can find more info by inputting booking No {5} at https://www.trippest.com/track-your-trip. Wish you a wonderful day with Trippest!</p> + <form action="http://www.mycht.cn/webht.php/apps/messagecenter/index/send_message" method="post" name="add_template"> + <label for="addtemplate">输入信息:</label> + <br> + <label>区号:<input type="text" name="nation_code"></label> + <br> + <label>手机号:<input type="text" name="phone"></label> + <br> + <label>元素一:<input type="text" name="one"></label> + <br> + <label>元素二:<input type="text" name="two"></label> + <br> + <label>元素三:<input type="text" name="three"></label> + <br> + <label>元素四:<input type="text" name="four"></label> + <br> + <label>元素五:<input type="text" name="five"></label> + <br> + <button type="submit" class="btn btn-default">发送短信</button> + </form> + </div> + </div> +</div> \ No newline at end of file diff --git a/webht/third_party/ordersfrom/controllers/index.php b/webht/third_party/ordersfrom/controllers/index.php new file mode 100644 index 00000000..c70cb925 --- /dev/null +++ b/webht/third_party/ordersfrom/controllers/index.php @@ -0,0 +1,81 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class Index extends CI_Controller { + + public function __construct() { + parent::__construct(); + $this->load->model('ordersfrom_model'); + } + + public function index(){ + $data = array(); + $data['startime'] = $this->input->get_post('startime'); + $data['endtime'] = $this->input->get_post('endtime'); + $data['webcode'] = $this->input->get_post('webcode'); + $data['total_nums'] = 0; + + if($data['startime'] && $data['endtime'] && $data['webcode']){ + $all_orders = $this->ordersfrom_model->get_all_orders($data['startime'],$data['endtime'],$data['webcode']); + $data['total_nums'] = count($all_orders); + $data['orders'] = $this->group_order_arr($all_orders); + }else{ + $data['orders'] = null; + } + $this->load->view('index',$data); + } + + function group_order_arr($all_orders){ + $data = array(); + $num = 0; + foreach ($all_orders as $item){ + preg_match('/(https|http):[\/]{2}[a-z]+[.]{1}[a-z\d\-]+[.a-z\d-\/.htm]*/',$item->COLI_OrderDetailText,$matches); + if(!empty($matches[0])){ + if(isset($data[$matches[0]])){ + $data[$matches[0]]['num'] +=1; + array_push($data[$matches[0]]['order'],$item->coli_id); + }else{ + $data[$matches[0]] = array(); + $data[$matches[0]]['num'] = 1; + $data[$matches[0]]['order'] = array(); + array_push($data[$matches[0]]['order'],$item->coli_id); + } + } + } + + return $this->array_sort($data,'num','desc'); + } + + function array_sort($arr,$keys,$type='asc'){ + $keysvalue = $new_array = array(); + foreach ($arr as $k=>$v){ + $keysvalue[$k] = $v[$keys]; + } + if($type == 'asc'){ + asort($keysvalue); + }else{ + arsort($keysvalue); + } + reset($keysvalue); + foreach ($keysvalue as $k=>$v){ + $new_array[$k] = $arr[$k]; + } + return $new_array; + } + + public function count_ah_orders(){ + $data = array(); + $ah_product_obj = $this->ordersfrom_model->ah_productions(); + foreach($ah_product_obj as $item){ + $data[$item->cli_no] = array(); + $orders_arr = $this->ordersfrom_model->get_orders($item->cli_no); + $data[$item->cli_no] = $orders_arr; + } + $mdata['orders'] = $data; + $this->load->view('ah_orders',$mdata); + } +} + + +?> \ No newline at end of file diff --git a/webht/third_party/ordersfrom/models/ordersfrom_model.php b/webht/third_party/ordersfrom/models/ordersfrom_model.php new file mode 100644 index 00000000..e09daa1a --- /dev/null +++ b/webht/third_party/ordersfrom/models/ordersfrom_model.php @@ -0,0 +1,45 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + + +class ordersfrom_model extends CI_Model { + + function __construct(){ + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + public function get_all_orders($fromtime,$totime,$website){ + $sql = "select + COLI_OrderDetailText,coli_id + from + ConfirmLineInfo + where + COLI_WebCode = ? + and + COLI_ApplyDate > ? + and + COLI_ApplyDate < ? + and + DeleteFlag = 0 + and + COLI_OrderDetailText like '%https:%' + "; + $query = $this->HT->query($sql,array($website,$fromtime,$totime)); + return $query->result(); + } + + public function ah_productions(){ + $sql = "select cli_no from CustomerLineInfo WHERE CLI_DEI_SN = '28' AND DeleteFlag = '0'"; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_orders($productsn){ + $sql = "select COLI_ID from ConfirmLineInfo where COLI_WebCode = 'AH' and DeleteFlag = 0 and COLI_OrderDetailText like '%{$productsn}%'"; + $query = $this->HT->query($sql); + return $query->result(); + } +} \ No newline at end of file diff --git a/webht/third_party/ordersfrom/views/ah_orders.php b/webht/third_party/ordersfrom/views/ah_orders.php new file mode 100644 index 00000000..44959118 --- /dev/null +++ b/webht/third_party/ordersfrom/views/ah_orders.php @@ -0,0 +1,62 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>订单来源页面搜索</title> + <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/nav/nav.css?v=20150723" rel="stylesheet"> + <link href="/css/webht/jquery-ui-1.10.0.custom.css" rel="stylesheet"> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> + <script src="/js/jquery-ui.min.js?v=1"></script> +<!--[if lt IE 9]> +<script src="/js/respond.min.js" type="text/javascript"></script> +<![endif]--> + +</head> +<body> +<nav class="navbar navbar-inverses" style="margin-bottom:0;border-bottom:1px solid #ddd;"> + <div class="container-fluid search_container nopadding"> + <div class="navbar-header" style="float:none;"> + <a class="navbar-brand text-muted" style="padding-top: 7px;padding-left: 30px;" href="<?php echo site_url('index/index'); ?>"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + </div> + </div> +</nav> +<h1 class="text-center">AH订单统计(按线路代号)</h1> +<table class="table table-bordered"> + <tr> + <th>线路代号</th> + <th>订单数量</th> + <th>具体订单号</th> + </tr> + <?php + $table_body = ''; + //print_r($orders); + foreach ($orders as $key=>$items){ + $table_body .= '<tr>'; + $table_body .= '<td>'.$key.'</td>'; + $table_body .= '<td>'.count($items).'</td>'; + $table_body .= '<td class="order_detail">'; + $orders_num = 0; + foreach ($items as $value){ + $orders_num++; + if($orders_num == count($items)){ + $table_body .= $value->COLI_ID; + }else{ + $table_body .= $value->COLI_ID.'、'; + } + } + + $table_body .= '</td>'; + $table_body .= '</tr>'; + } + echo $table_body; + ?> +</table> + + +</body> +</html> \ No newline at end of file diff --git a/webht/third_party/ordersfrom/views/index.php b/webht/third_party/ordersfrom/views/index.php new file mode 100644 index 00000000..840358bd --- /dev/null +++ b/webht/third_party/ordersfrom/views/index.php @@ -0,0 +1,120 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1"> + <title>订单来源页面搜索</title> + <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> + <link href="/css/nav/nav.css?v=20150723" rel="stylesheet"> + <link href="/css/webht/jquery-ui-1.10.0.custom.css" rel="stylesheet"> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> + <script src="/js/jquery-ui.min.js?v=1"></script> +<!--[if lt IE 9]> +<script src="/js/respond.min.js" type="text/javascript"></script> +<![endif]--> + +</head> +<body> +<nav class="navbar navbar-inverses" style="margin-bottom:0;border-bottom:1px solid #ddd;"> + <div class="container-fluid search_container nopadding"> + <div class="navbar-header" style="float:none;"> + <a class="navbar-brand text-muted" style="padding-top: 7px;padding-left: 30px;" href="<?php echo site_url('index/index'); ?>"> + <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> + </a> + </div> + </div> +</nav> + +<div class="container"> + <h1 class="text-center">订单来源页面查询</h1> + <div class="content" style="margin-top:20px;"> + <form method="post" class="form-inline" action="http://www.mycht.cn/webht.php/apps/ordersfrom/index/"> + <div class="col-sm-8"> + <div class="form-group"> + <label for="startime">开始时间</label> + <input id="startime" name="startime" class="form-control" type="text" value="<?php echo empty($startime) ? '' :$startime;?>" autocomplete="off"/> + </div> + </div> + <div class="col-sm-8"> + <div class="form-group"> + <label for="endtime">结束时间</label> + <input id="endtime" name="endtime" class="form-control" type="text" value="<?php echo empty($endtime) ? '' :$endtime;?>" autocomplete="off"/> + </div> + </div> + <div class="col-sm-8"> + <div class="form-group"> + <label for="webcode">站点选择</label> + <select class="form-control" name="webcode" id="webcode"> + <option value="gm">GM</option> + <option value="cht">CH</option> + <option value="ah">AH</option> + <option value="CT">CT</option> + <option value="YZ">YZ</option> + <option value="SHT">SHT</option> + <option value="GL">GL</option> + <option value="MBJ">MBJ</option> + <option value="TBT">TBT</option> + </select> + </div> + <button id="ordersfrom" type="submit" class="btn btn-default">查询</button> + </div> + </form> + </div> +</div> + +<?php if(!empty($orders)){?> +<div class="orderscontent"> + <div> + <h3 class="text-center">统计分组结果</h3> + <p class="text-center">总订单数:<?php echo $total_nums;?></p> + </div> + <div class="table-responsive"> + <table class="table table-bordered"> + <tr> + <th>订单来源</th> + <th>订单数量</th> + <th>具体订单号</th> + </tr> + <?php + $table_body = ''; + foreach ($orders as $key=>$items){ + $table_body .= '<tr>'; + $table_body .= '<td>'.$key.'</td>'; + $table_body .= '<td>'.$items['num'].'</td>'; + $table_body .= '<td class="order_detail">'; + $orders_num = 0; + foreach ($items['order'] as $value){ + $orders_num++; + if($orders_num == count($items['order'])){ + $table_body .= $value; + }else{ + $table_body .= $value.'、'; + } + } + + $table_body .= '</td>'; + $table_body .= '</tr>'; + } + echo $table_body; + ?> + </table> + </div> +</div> +<?php }?> +<script> +$(function(){ + $('#startime,#endtime').datepicker({ + dateFormat: "yy-mm-dd", + changeMonth: true, + changeYear: true + }); + + //获取站点 + var sitecode = "<?php echo $webcode;?>"; + if(sitecode != ''){ + $('#webcode option[value='+sitecode+']').attr("selected","selected"); + } +}); +</script> +</html> \ No newline at end of file From 477fa683ed12d7728f0bc3102f1b0c878a1158ab Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 29 Apr 2019 17:09:54 +0800 Subject: [PATCH 305/382] =?UTF-8?q?=E4=BB=8E123=E6=90=AC=E8=BF=81=E7=9A=84?= =?UTF-8?q?=E5=AE=A2=E6=88=B7=E9=9C=80=E6=B1=82=E9=A1=B9=E7=9B=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/controllers/demandform.php | 167 ++++++++++++++++ webht/models/demandform_model.php | 119 +++++++++++ webht/views/demandform/index.php | 160 +++++++++++++++ webht/views/demandform/index1.php | 315 ++++++++++++++++++++++++++++++ webht/views/demandform/reply.php | 122 ++++++++++++ 5 files changed, 883 insertions(+) create mode 100644 webht/controllers/demandform.php create mode 100644 webht/models/demandform_model.php create mode 100644 webht/views/demandform/index.php create mode 100644 webht/views/demandform/index1.php create mode 100644 webht/views/demandform/reply.php diff --git a/webht/controllers/demandform.php b/webht/controllers/demandform.php new file mode 100644 index 00000000..3e5b94bf --- /dev/null +++ b/webht/controllers/demandform.php @@ -0,0 +1,167 @@ +<?php + +if (!defined('BASEPATH')) { + exit('No direct script access allowed'); +} + +class Demandform extends CI_Controller { + + function __construct() { + parent::__construct(); + $this->load->model('Demandform_model'); + } + + /*! + * @author LYT <lyt@hainatravel.com> + * @date 2018-01-23 + * @param [type] $coli_sn 订单主表的COLI_SN + * @param integer $form_id 默认值2是0.1版本固定的 + */ + public function index($coli_sn = null, $form_id = 2) + { + header("Cache-Control: no-store"); + + // 已填则返回成功 + $is_replied = $this->Demandform_model->get_reply($coli_sn); + + $form_id = intval(trim($form_id)); + $_raw_data = $this->Demandform_model->get_form_detail($form_id); + $part = array(); + foreach ($_raw_data->formdetail as $key => $fd) { + $tmp_a = array(); + $tmp_r = array(); + foreach ($_raw_data->answer as $ka => $a) { + if ($fd->FD_id === $a->A_FD_id) { + $tmp_a[] = $a; + } + } + if ( ! empty($is_replied)) { + foreach ($is_replied as $kr => $re) { + if ($re->FD_id === $fd->FD_id) { + $tmp_r[] = $re->CRD_content; + } + } + } + $fd->reply = $tmp_r; + $fd->answer = (object) $tmp_a; + // part set + $part["part1"]["title"] = "PART 1 -- Travel Preference"; + $part["part2"]["title"] = "PART 2"; + if (intval(trim($fd->FD_section)) === 1) { + $part["part1"]["data"][] = $fd; + } + if (intval(trim($fd->FD_section)) === 2) { + $part["part2"]["data"][] = $fd; + } + } + $_raw_data->part = $part; + unset($_raw_data->formdetail); + unset($_raw_data->answer); + $_raw_data->coli = $coli_sn; + + if ( ! empty($is_replied)) { + $this->load->view('demandform/thanks', $_raw_data); + return; + } + + $this->load->view('demandform/index', $_raw_data); + return; + } + + public function form_save() + { + $all_post = $this->input->post(); + + $ret["code"] = 1; + $ret["msg"] = ""; + // 已填则返回成功 -- todo + + $check_input = array(); + foreach ($all_post["q"] as $key => $value) { + if ($value["required"] == 1 && empty($value["answer"])) { + $ret["code"] = 0; + $ret["msg"][] = $key; + } + } + if ($ret["code"] == 0) { + return $this->output->set_content_type('text/plain')->set_output(json_encode($ret)); + } + // CD_CustomerReply + $this->Demandform_model->CR_COLI_sn = trim($this->input->post("coli_sn")); + $this->Demandform_model->CR_F_id = trim($this->input->post("fid")); + $d = $a = $c = ""; + foreach ($all_post["q"] as $key => $value) { + $split_answer = null; + $class_max = 0; + if (trim($value["ismain"]) != 1) { + continue; + } + $class_max = (count($value["answer"])-1); + $split_answer = explode("=_", $value["answer"][$class_max]); + if (trim($value["qclass"]) === 'D' && ! empty($split_answer)) { + $d = (isset($split_answer) ? $split_answer[1] : "?"); + } + if (trim($value["qclass"]) === 'A' && ! empty($split_answer)) { + $a = (isset($split_answer) ? $split_answer[1] : "?"); + } + if (trim($value["qclass"]) === 'C' && ! empty($split_answer)) { + $c = (isset($split_answer) ? $split_answer[1] : "?"); + } + } + $this->Demandform_model->CR_result = $d . $a . $c; + // CD_CustomerReplyDetail + $this->Demandform_model->CRD_CR_id = $this->Demandform_model->reply_save(); + $reply_detail = array(); + foreach ($all_post["q"] as $key => $value) { + if (empty($value["atext"]) && empty($value["answer"])) { + continue; + } + $this->Demandform_model->CRD_FD_id = $value["fdid"]; + $this->Demandform_model->CRD_result = null; + $this->Demandform_model->CRD_Answer = null; + $this->Demandform_model->CRD_content = null; + + if (isset($value["answer"])) { + foreach ($value["answer"] as $ka => $va) { + $split_answer = null; + $split_answer = explode("=_", trim($value["answer"][$ka])); + $this->Demandform_model->CRD_Answer = $split_answer[0]; + $this->Demandform_model->CRD_content = (!empty($split_answer) ? ($split_answer[2]) : ""); + if ( ! empty($value["qclass"]) && ! empty($split_answer)) { + $this->Demandform_model->CRD_result = (!empty($split_answer) ? $split_answer[1] : "?"); + } + // 这里是 选择题others选项的可填入项 + $this->Demandform_model->CRD_content .= (isset($value["atext"]) ? $value["atext"] : ""); + $this->Demandform_model->replydetail_save(); + } + } else { + // 这里是填空题的输入 + $this->Demandform_model->CRD_content = $value["atext"]; + $this->Demandform_model->replydetail_save(); + } + } + return $this->output->set_content_type('text/plain')->set_output(json_encode($ret)); + } + + public function view_reply($coli) + { + $reply = $this->Demandform_model->get_reply($coli); + $reply_arr = array(); + $reply_fd_arr = array(); + foreach ($reply as $key => $r) { + $class_key = trim($r->FD_class) ? trim($r->FD_class) : "normal"; + $reply_arr["CR_result"] = $r->CR_result; + $reply_arr[$class_key]["q" . $r->FD_id][] = $r; + } + $this->load->view('demandform/reply', $reply_arr); + } + + public function converet_answer($answer) + { + $ret = ord($answer)-64; + $ret = ($ret > 3) ? 3 : $ret; + return $ret; + } + + +} diff --git a/webht/models/demandform_model.php b/webht/models/demandform_model.php new file mode 100644 index 00000000..dd80ba58 --- /dev/null +++ b/webht/models/demandform_model.php @@ -0,0 +1,119 @@ +<?php + +class Demandform_model extends CI_Model { + + function __construct() + { + parent::__construct(); + $this->INFO = $this->load->database('INFO', TRUE); + } + + public function get_form_detail($form_id) + { + $ret = (object) array(); + $form_sql = "SELECT top 1 * FROM CD_form WHERE f_id=$form_id " ; + $f_query = $this->INFO->query($form_sql); + $ret->form = $f_query->row(); + + $formdetail_sql = "SELECT fd.* + FROM CD_formdetail fd + WHERE fd.FD_F_id=$form_id order by FD_sort asc" ; + $fd_query = $this->INFO->query($formdetail_sql); + $ret->formdetail = $fd_query->result(); + + $answer_sql = "SELECT a.* + FROM CD_formdetail fd + INNER JOIN CD_answer a ON a.A_FD_id=fd.FD_id + WHERE fd.FD_F_id=$form_id " ; + $a_query = $this->INFO->query($answer_sql); + $ret->answer = $a_query->result(); + + return $ret; + } + + // CD_CustomerReply + public $CR_COLI_sn; + public $CR_F_id; + public $CR_result; + + public function reply_save() + { + $rsql = "INSERT INTO CD_CustomerReply ( + CR_COLI_sn + ,CR_F_id + ,CR_replytime + ,CR_result) + VALUES + (? + ,? + ,GETDATE() + ,N?)"; + // log_message('error',$this->INFO->compile_binds($rsql, + $rquery = $this->INFO->query($rsql, + array($this->CR_COLI_sn, $this->CR_F_id, $this->CR_result)); + $cr_id_q = "SELECT TOP 1 CR_id + FROM CD_CustomerReply + WHERE CR_COLI_sn=? + ORDER BY CR_replytime DESC"; + $cr_query = $this->INFO->query($cr_id_q, array($this->CR_COLI_sn)); + $cr_id_r = $cr_query->row(); + return $cr_id_r->CR_id; + } + + // CD_CustomerReplyDetail + public $CRD_FD_id; + public $CRD_Answer; + public $CRD_content; + public $CRD_result; + public $CRD_CR_id; + + public function replydetail_save() + { + $rdsql = "INSERT INTO CD_CustomerReplyDetail + (CRD_CR_id + ,CRD_FD_id + ,CRD_Answer + ,CRD_content + ,CRD_result + ) + VALUES (?,?,?,N?,?) "; + // log_message('error',$this->INFO->compile_binds($rdsql, + $rdquery = $this->INFO->query($rdsql, + array( + $this->CRD_CR_id, + $this->CRD_FD_id, + $this->CRD_Answer, + $this->CRD_content, + $this->CRD_result + ) + ); + return $this->INFO->insert_id(); + } + + public function get_reply($coli) + { + $sql = "SELECT fd.FD_id, + fd.FD_F_id, + fd.FD_section, + cr.CR_replytime, + cr.CR_COLI_sn, + cr.CR_result, + fd.FD_class, + fd.FD_ismain, + crd.CRD_result, + fd.FD_question, + crd.CRD_content + FROM CD_CustomerReply cr + INNER JOIN CD_CustomerReplyDetail crd ON crd.CRD_CR_id=cr.CR_id + INNER JOIN CD_FormDetail fd ON CRD_FD_id=FD_id + WHERE CR_COLI_sn='$coli' + ORDER BY fd.FD_section ASC,fd.FD_sort ASC + "; + $query = $this->INFO->query($sql); + + return $query->result(); + } + + + +} diff --git a/webht/views/demandform/index.php b/webht/views/demandform/index.php new file mode 100644 index 00000000..2dfb008b --- /dev/null +++ b/webht/views/demandform/index.php @@ -0,0 +1,160 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <title>We Complete You</title> + <!-- <link href="https://data.chinahighlights.com/css/complete-trip.css" rel="stylesheet"> --> + <link href="http://202.103.68.221/css/complete-trip.css" rel="stylesheet"> + <style type="text/css" media="screen and (min-device-width:768px)"> + .modal-dialog {width: 600px;margin: 100px auto;} + .modal-content {-webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5);box-shadow: 0 5px 15px rgba(0,0,0,.5);} + </style> + <style type="text/css"> + .sendBtn{border: none;} + .text-danger{color: #a31022;} + .complete-tips{ border-bottom: 1px dashed #a31022;} + .hidden{display: none;} + .modal-open .modal {overflow-x: hidden;overflow-y: auto;} + .fade.in {opacity: 1;} + .modal {display: none;overflow: hidden;position: fixed;top: 0;right: 0;bottom: 0;left: 0;z-index: 1050;-webkit-overflow-scrolling: touch;outline: 0;} + .fade {opacity: 0;-webkit-transition: opacity .15s linear;-o-transition: opacity .15s linear;transition: opacity .15s linear;} + .modal.in .modal-dialog {-webkit-transform: translate(0, 0);-ms-transform: translate(0, 0);-o-transform: translate(0, 0);transform: translate(0, 0);} + .modal.fade .modal-dialog {-webkit-transform: translate(0, -25%);-ms-transform: translate(0, -25%);-o-transform: translate(0, -25%);transform: translate(0, -25%);-webkit-transition: -webkit-transform .3s ease-out;-moz-transition: -moz-transform .3s ease-out;-o-transition: -o-transform .3s ease-out;transition: transform .3s ease-out;} + .modal-content {position: relative;background-color: #fff;border: 1px solid #999;border: 1px solid rgba(0,0,0,.2);border-radius: 6px;-webkit-box-shadow: 0 3px 9px rgba(0,0,0,.5);box-shadow: 0 3px 9px rgba(0,0,0,.5);background-clip: padding-box;outline: 0;} + .modal-header {padding: 15px;border-bottom: 1px solid #e5e5e5;min-height: 16.43px;} + .modal-header .close {margin-top: -2px;} + button.close {padding: 0;cursor: pointer;background: 0 0;border: 0;-webkit-appearance: none;} + .close {float: right;font-size: 18px;font-weight: 700;line-height: 1;color: #000;text-shadow: 0 1px 0 #fff;opacity: .2;filter: alpha(opacity=20);} + h4.modal-title {margin: 0;line-height: 1.428571429;} + .modal-body {position: relative;padding: 30px;} + .modal-footer {padding: 30px;text-align: right;border-top: 1px solid #e5e5e5;} + .btn-default {color: #333;background-color: #fff;border-color: #ccc;} + .btn {display: inline-block;margin-bottom: 0;font-weight: 400;text-align: center;vertical-align: middle;touch-action: manipulation;cursor: pointer;background-image: none;border: 1px solid transparent;white-space: nowrap;padding: 6px 12px;font-size: 12px;line-height: 1.428571429;border-radius: 4px;-webkit-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;} + .modal-backdrop.in {opacity: .5;filter: alpha(opacity=50);} + .modal-backdrop.fade {opacity: 0;filter: alpha(opacity=0);} + .modal-backdrop {position: fixed;top: 0;right: 0;bottom: 0;left: 0;z-index: 1040;background-color: #000;} + sup{color: #a31022;font-size: 16px;vertical-align: baseline;top: -0.5em;} + </style> + <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js,/js/ChtPublic.js,/public/js/bootstrap.min.js"> + </script> + <script type="text/javascript"> + $(document).ready(function() { + $.ajax({ type: "get", url: "/secureforms/form_token" }).done(function(data) { $("form").append(data); }); + $("#btn").click(function() { + $.ajax({ + url:"/securedemandform/form_save", + // url:"/guide-use.php/demandform/form_save", + type:"POST", + dataType:"JSON", + data:$("#demandform").serialize(), + beforeSend:function(xhr) { + var flag; + $("#btn").text('Please wait...'); + }, + complete:function() { + $("#btn").text('Send to Simon'); + } + }).done(function(data) { + if (data.code == 0) { + $(".required-error").addClass("text-danger"); + $(".complete-tips").removeClass("hidden"); + } else { + $('#myModal').modal('show'); + $(".complete-tips").addClass("hidden"); + } + }) + }) + }); + </script> + </head> + <body> + <header> + <div id="header"> + <!-- <div class="logo"><img src="https://data.chinahighlights.com/pic/logo/logo-132x104.png"></div> --> + <div class="logo"><img src="http://202.103.68.79/pic/logo/logo-132x104.png"></div> + <span class="pageTitle"></span> + </div> + </header> + <div id="content"> + <form action="/guide-use.php/demandform/form_save" method="POST" target="hidden-frame" id="demandform" name="demandform"> + <?php echo __FORM_TOKEN__ ?> + <input type="hidden" name="coli_sn" value="<?=$coli?>"> + <input type="hidden" name="fid" value="<?=$form->F_id?>"> + <ul class="headList"> + <li><?php + $form_com = str_replace("\r\n", "<br>", $form->F_comment); + $form_com = str_replace("\n", "<br>", $form_com); + echo $form_com; + ?> + </li> + </ul> + + <?php foreach ($part as $key => $p) { ?> + <h2><?=$p["title"]?></h2> + <div><?php foreach ($p["data"] as $kf => $q) { ?> + <p class="<?php if($q->FD_required==1){ ?>required-error<?php } ?>"> + <strong><?php echo ($kf+1) ?>.</strong> <em><?php echo $q->FD_question ?> + <?php if($q->FD_required==1){ ?> + <sup>&lowast;</sup> + <?php } ?> + </em></p> + <input type="hidden" name="q[q<?=$q->FD_id?>][qclass]" value="<?=trim($q->FD_class)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][qtype]" value="<?=trim($q->FD_AnswerType)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][fdid]" value="<?=trim($q->FD_id)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][ismain]" value="<?=trim($q->FD_ismain)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][required]" value="<?=trim($q->FD_required)?>"> + <?php if (intval(trim($q->FD_AnswerType)) > 0) { // 选择题 + $answer_type = intval(trim($q->FD_AnswerType))==1 ? "radio" : "checkbox"; + ?> + <?php foreach ($q->answer as $ka => $an) { ?> + <label> + <input type="<?=$answer_type?>" name="q[q<?=$q->FD_id?>][answer][]" + value="<?=trim($an->A_number)?>=_<?=trim($q->FD_class) . trim($an->A_class)?>=_<?=$an->A_content?>" id="ra_<?=$q->FD_id?>_<?=$an->A_id?>"> + <?php if(trim($an->A_content) == '') { // 这里不要了 ?> + <!-- <input type="text" name="q[q<?=$q->FD_id?>][atext]" data-radioid="ra_<?=$q->FD_id?>_<?=$an->A_id?>" > --> + <?php } else {?> + <em><?php echo trim($an->A_content) ?></em> + <?php } ?> + </label> + <?php } ?> + <?php } else { // 填空?> + <textarea placeholder="<?=$q->FD_comment?>" name="q[q<?=$q->FD_id?>][atext]"></textarea> + <!-- <input type="text" name="q[q<?=$q->FD_id?>][atext]"> --> + <?php } ?> + <?php } ?> + </div> + <?php } ?> + + <p class="hidden complete-tips text-danger">Please complete the highlighted questions.</p> + <button type="submit" class="sendBtn"> + <a href="javascript:void(0)" id="btn"> + Send to Simon + </a> + </button> + </form> + </div> + + <!-- Modal --> + <div id="myModal" class="modal fade" role="dialog"> + <div class="modal-dialog"> + <!-- Modal content--> + <div class="modal-content"> + <div class="modal-header"> + <button type="button" class="close" data-dismiss="modal">&times;</button> + <h4 class="modal-title">Message</h4> + </div> + <div class="modal-body"> + <p>Thank you!</p> + </div> + <div class="modal-footer"> + <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> + </div> + </div> + </div> + </div> + + </body> +</html> diff --git a/webht/views/demandform/index1.php b/webht/views/demandform/index1.php new file mode 100644 index 00000000..07c122f9 --- /dev/null +++ b/webht/views/demandform/index1.php @@ -0,0 +1,315 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8"> + <title>Easy Planning from now!</title> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <meta name="referrer" content="always"> + <meta name="Description" content="Easy Planning from now! Telling us your preference." /> + <link type="text/css" rel="stylesheet" href="//data.chinahighlights.com/css/min.php?f=/public/css/global.min.css"> + <link rel="canonical" href="https://www.chinahighlights.com/contactus/"> + <script src="//data.chinahighlights.com/js/min.php?f=/js/jquery-1.8.2.min.js,/js/ChtPublic.js,/public/js/bootstrap.min.js"> + </script> + <script src="//data.chinahighlights.com/js/form-helper.js"> + </script> + <script type="text/javascript"> + $(document).ready(function() { + $.ajax({ type: "get", url: "/secureforms/form_token" }).done(function(data) { $("form").append(data); }); + $("#realname,#email,#additionalrequirements").focus(function() { + $(this).siblings(".requiredArea").remove(); + }); + }); + </script> + <script type="text/javascript"> + function judgeform() { + var rc,ec,cc; + if($('input[name="realname"]').val()==''){ + $('<div style="color: #a31022;" class="requiredArea">Please fill up your name.</div>').appendTo('#name_area'); + return false; + } + if($('input[name="email"]').val()==''){ + $('<div style="color: #a31022;" class="requiredArea">Wrong email address. Eg: service@chinahighlights.com.</div>').appendTo('#email_area'); + return false; + } else { + var emailPattern = /^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/; + if (!emailPattern.test($('#email').val())) { + $('<div style="color: #a31022;" class="requiredArea">Wrong email address. Eg: service@chinahighlights.com.</div>').appendTo('#email_area'); + return false; + } + } + if (document.getElementById("additionalrequirements").value == "") + { + $('<div style="color: #a31022;" class="requiredArea">Please tell us what kind of tour you want!</div>').appendTo('#text_area'); + return false; + } + return true; + } + </script> + <!--[if lte IE 9]> + <script src="/public/js/respond.min.js"> + </script> + <![endif]--> + </head> + <body> + <div id="wrapper"> + <div id="headerWrapper"> + <div id="header"> + <div class="container"> + <div class="row hidden-xs hidden-sm" id="headerLinkRight"> + <div class="col-lg-24"> + <ul class="list-inline pull-right"> + <li> + <a rel="nofollow" href="/contactus/">Contact us</a> + </li> + <li> + <a href="/aboutus/" rel="nofollow">About us</a> + </li> + </ul> + <div class="tollfree pull-right"> + <i class="fa fa-phone"> + </i> + <div class="currentNo"> + <strong>USA/CA:</strong>800-2682918 </div> + <div class="freePhone"> + <span> + <strong>AU:</strong> 1800-764678</span> + <span> + <strong>UK:</strong> 0800-0327753</span> + <span> + <strong>All:</strong> 86-773-2831999</span> + <span class="closeBlock"> + <img src="//data.chinahighlights.com/css/images/global/phone-close.png"> + </span> + </div> + </div> + </div> + </div> + </div><!--end of container --> + <div id="mainnav" class="nav navbar navbar-inverse" role="navigation"> + <div class="container"> + <div class="row"> + <div class="col-lg-3 col-sm-4 logobox hidden-xs"> + <a href="/"> + <img src="/pic/logo/logo-132x104.png" alt="logo" class="img-responsive"> + </a> + </div> + <div class="col-lg-21 col-sm-20 col-lg-offset-3 col-sm-offset-3"> + <div class="navbar-header"> + <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> + <span class="icon-bar"> + </span> + <span class="icon-bar"> + </span> + <span class="icon-bar"> + </span> + </button> + <div class="mobileLogo visible-xs">CHINA HIGHLIGHTS<sup>&reg;</sup> + </div> + <div class="navbar-brand visible-xs"> + <a rel="nofollow" href="/tour/create-my-trip.htm"> + <img src="/pic/tailor-mark.png" class="img-responsive" width="25"> + </a> + </div> + </div> + <div class="collapse navbar-collapse"> + <ul class="nav navbar-nav chNav"> + <li> + <a href="/">Home</a> + </li> + <li class="visible-xs"> + <a href="/tour/create-my-trip.htm">Create My Trip</a> + </li> + <li > + <a href="/tour/">China Tours</a> + <span class="withMenu" data-target="#china-tours"> + <a href="#">+</a> + </span> + </li> + <ul id="china-tours"> + <li> + <a href="/tour/top-china-tours/">Top 10 Tours</a> + </li> + <li> + <a href="/tour/china-panda-tours/">Panda Tours</a> + </li> + <li> + <a href="/tour/family-tours/">Family Tours</a> + </li> + <li> + <a href="/yangtzecruise/">Yangtze Cruise</a> + </li> + </ul> + <li class="non-mibile"> + <a href="/tour/create-my-trip.htm">Create My Trip</a> + </li> + <li > + <a href="/citytour/">Destinations</a> + <span class="withMenu" data-target="#destinations"> + <a href="#">+</a> + </span> + </li> + <ul id="destinations"> + <li> + <a href="/beijing/tours.htm">Beijing</a> + </li> + <li> + <a href="/guilin/tours.htm">Guilin</a> + </li> + <li> + <a href="/zhangjiajie/tours.htm">Zhangjiajie</a> + </li> + <li> + <a href="/huangshan/tours.htm">Huangshan</a> + </li> + <li> + <a href="/shanghai/tours.htm">Shanghai</a> + </li> + <li> + <a href="/xian/tours.htm">Xi'an</a> + </li> + <li> + <a href="/chengdu/tours.htm">Chengdu</a> + </li> + </ul> + <li > + <a href="/travelguide/">Travel Guide</a> + <span class="withMenu" data-target="#travel-guide"> + <a href="#">+</a> + </span> + </li> + <ul id="travel-guide"> + <li> + <a href="/travelguide/visa-application/">China Visas</a> + </li> + <li> + <a href="/beijing/">Beijing</a> + </li> + <li> + <a href="/greatwall/">The Great Wall of China</a> + </li> + <li> + <a href="/travelguide/china-top-10-attractions.htm">China’s Top 10 Attractions</a> + </li> + <li> + <a href="/giant-panda/">Giant Pandas</a> + </li> + <li> + <a href="/xian/terracotta-army/">The Terracotta Army</a> + </li> + <li> + <a href="/travelguide/top-highlights-of-china.htm">Best of China</a> + </li> + </ul> + <li > + <a href="/travelguide/culture/">Culture</a> + <span class="withMenu" data-target="#culture"> + <a href="#">+</a> + </span> + </li> + <ul id="culture"> + <li> + <a href="/travelguide/chinese-zodiac/">Chinese Zodiac</a> + </li> + <li> + <a href="/travelguide/special-report/chinese-new-year/">Chinese New Year</a> + </li> + <li> + <a href="/festivals/mid-autumn-festival.htm">Mid-autumn Festival</a> + </li> + <li> + <a href="/festivals/china-public-holiday.htm">Public Holiday Schedule</a> + </li> + </ul> + <li class="hidden-xs "> + <a href="/china-trains/">Trains</a> + </li> + <li> + <a href="/tour/asia-tours/">Asia Tours</a> + </li> + <li class="last"> + <a href="/daytrip/">Day Tours</a> + </li> + </ul> + </div> + </div> + </div> + </div> + <!--container--> + </div> + <!--end of mainnav --> + </div></div> + <!-- form --> + <div> + <h2>Easy Planning from now! The only thing you need to do is telling us your preference. Leave the rest to Us!</h2> + <form action="/guide-use.php/demandform/form_save" method="POST"> + <?php echo __FORM_TOKEN__ ?> + <input type="hidden" name="coli_sn" value="<?=$coli?>"> + <input type="hidden" name="fid" value="<?=$form->F_id?>"> + <div> + <?php foreach ($part as $key => $p) { ?> + <h3> <b><?=$p["title"]?></b></h3> + <p><?php foreach ($p["data"] as $kf => $q) { ?> + <p><?php echo ($kf+1) . "." . $q->FD_question ?></p> + <input type="hidden" name="q[q<?=$q->FD_id?>][qclass]" value="<?=trim($q->FD_class)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][qtype]" value="<?=trim($q->FD_AnswerType)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][fdid]" value="<?=trim($q->FD_id)?>"> + <input type="hidden" name="q[q<?=$q->FD_id?>][ismain]" value="<?=trim($q->FD_ismain)?>"> + <?php if (intval(trim($q->FD_AnswerType)) === 1) { ?> + <ol style="list-style-type: upper-alpha;margin-left: 50px;"> + <?php foreach ($q->answer as $ka => $an) { ?> + <li> + <label> + <input style="margin-left: -30px;margin-right: 15px;line-height: 21px;vertical-align: text-bottom;" type="radio" name="q[q<?=$q->FD_id?>][answer]" <?php if($q->FD_required==1){ ?> required <?php } ?> + value="<?=trim($an->A_number)?>=_<?=$an->A_content?>" id="ra_<?=$q->FD_id?>_<?=$an->A_id?>" > + <?php if(trim($an->A_content) == '') { ?> + <input type="text" name="q[q<?=$q->FD_id?>][atext]" data-radioid="ra_<?=$q->FD_id?>_<?=$an->A_id?>" > + <?php } else {?> + <?php echo trim($an->A_content) ?> + <?php } ?> + </label> + </li> + <?php } ?> + </ol> + <?php } else { ?> + <input type="text" name="q[q<?=$q->FD_id?>][atext]"> + <?php } ?> + <?php } ?></p> + <?php } ?> + </div> + <input type="submit" name="" value="submit"> + </form> + </div> + <!-- end form --> + <div id="footer"> + </div> + <!-- </div> + </div>--> + </div> + <script src="//data.chinahighlights.com/public/js/footer-html5.js"> + </script> + </body> +</html> +<script type="text/javascript"> + $(function() { + $("ol input:text").focus(function() { + var obj = $(this); + var target_id = obj.data("radioid"); + $("#"+target_id).prop("checked","checked"); + // var target_id_t = obj.data("texttarget"); + // $("#"+target_id_t).val("other answer"); + }) + // $("input:radio").change(function() { + // var obj = $(this); + // var target_id = obj.data("texttarget"); + // $("#"+target_id).val(obj.data("text")); + // var li_index = (obj.parents("li").index())+1; + // var li_alphabet = convert(li_index); + // }) + }) + function convert(num){ + return num <= 26 ? + String.fromCharCode(num + 64) : convert(~~((num - 1) / 26)) + convert(num % 26 || 26); + } +</script> diff --git a/webht/views/demandform/reply.php b/webht/views/demandform/reply.php new file mode 100644 index 00000000..f47388c5 --- /dev/null +++ b/webht/views/demandform/reply.php @@ -0,0 +1,122 @@ +<!doctype html> +<html> + <head> + <meta charset="utf-8"> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <meta content="width=device-width, initial-scale=1.0" name="viewport"> + <meta content="yes" name="apple-mobile-web-app-capable"> + <title>customer reply</title> + <style type="text/css" media="screen and (min-device-width:768px)"> + .modal-dialog {width: 600px;margin: 100px auto;} + .modal-content {-webkit-box-shadow: 0 5px 15px rgba(0,0,0,.5);box-shadow: 0 5px 15px rgba(0,0,0,.5);} + </style> + <style type="text/css"> + body{background-color: #f1f1f1;color: #555;font-size: 16px;font-family: 'Open Sans', sans-serif;} + #content{width: 1000px;display: block;margin-left: auto ;margin-right: auto ;} + </style> + </head> + <body> + <div id="content" style="padding: 20px;"> + <?php if (empty($D) || empty($A) || empty($C)) { ?> + <h3>未收到回复</h3> + <?php } else { ?> + <table border="1"> + <thead> + <tr> + <th width="10%">等级</th> + <th width="45%">关键问题</th> + <th width="45%">辅助信息</th> + </tr> + </thead> + <tbody> + <tr> + <td> + <?php echo $CR_result; ?> + </td> + <td> + <?php foreach ($D as $kc => $qa) { + if (intval($qa[0]->FD_ismain) == 1) { + echo $qa[0]->FD_question; + foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo ($answer->CRD_result) . "." . $answer->CRD_content; ?></p> + <?php } } } ?> + </td> + <td> + <?php foreach ($D as $kc => $qa) { + if (intval($qa[0]->FD_ismain) != 1) { ?> + <?php echo $qa[0]->FD_question; ?> + <?php foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo ($answer->CRD_result) . "." . $answer->CRD_content; ?></p> + <?php } } } ?> + </td> + </tr> + <tr> + <td> + <?php echo $CR_result; ?> + </td> + <td> + <?php foreach ($A as $kc => $qa) { + if (intval($qa[0]->FD_ismain) == 1) { + echo $qa[0]->FD_question; + foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo ($answer->CRD_result) . "." . $answer->CRD_content; ?></p> + <?php } } } ?> + </td> + <td> + <?php foreach ($A as $kc => $qa) { + if (intval($qa[0]->FD_ismain) != 1) { ?> + <?php echo $qa[0]->FD_question; ?> + <?php foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo ($answer->CRD_result) . "." . $answer->CRD_content; ?></p> + <?php } } } ?> + </td> + </tr> + <tr> + <td> + <?php echo $CR_result; ?> + </td> + <td> + <?php foreach ($C as $kc => $qa) { + if (intval($qa[0]->FD_ismain) == 1) { ?> + <?php echo $qa[0]->FD_question; + foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo ($answer->CRD_result) . "." . $answer->CRD_content; ?></p> + <?php } } ?> + <?php } ?> + </td> + <td> + <?php foreach ($C as $kc => $qa) { ?> + <?php if (intval($qa[0]->FD_ismain) != 1) { ?> + <?php echo $qa[0]->FD_question; ?> + <?php foreach ($qa as $ka => $answer) { ?> + <p style="color: #a31022;"><?php echo $answer->CRD_content; ?></p> + <?php } } ?> + <?php } ?> + </td> + </tr> + <tr> + <td colspan="3" style="text-align: center;font-weight: bold;"> + 其他信息 + </td> + </tr> + <?php foreach ($normal as $key => $qn) { ?> + <tr> + <!-- <td><?//=($key+1)?></td> --> + <td colspan="2"> + <?php echo $qn[0]->FD_question; ?> + </td> + <td> + <?php foreach ($qn as $ka => $na) { ?> + <p style="color: #a31022;"><?php echo $na->CRD_content; ?></p> + <?php } ?> + </td> + </tr> + <?php } ?> + </tbody> + </table> + <?php } ?> + + </div> + + </body> +</html> From a93d4308d1b68b1167d568ad5be6c549705f75c8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 30 Apr 2019 17:57:04 +0800 Subject: [PATCH 306/382] =?UTF-8?q?Trippest=E6=88=90=E6=9C=AC=E8=A1=A5?= =?UTF-8?q?=E5=85=85:=E5=A2=9E=E5=8A=A0report=5Ftour:RPT=5FCOLD=5FSN?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/order_finance.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index ee9bac2f..e4c06133 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -168,6 +168,7 @@ class Order_finance extends CI_Controller { $report_tour_pvt['tourProvide'] = mb_substr($cpvt->vendor_name, 0, 50); $report_tour_pvt['tourBZ'] = mb_substr($cpvt->comment, 0, 150); $report_tour_pvt['orderstats'] = 0; + $report_tour_pvt['RPT_COLD_SN'] = $cpvt->cold_sn[0]; // 成本详情 $report_tour_pvt['RPT_Car'] = $cpvt->cost_category['touristCarOperations']; $report_tour_pvt['RPT_Meal'] = $cpvt->cost_category['restraurantOperations']; @@ -196,6 +197,7 @@ class Order_finance extends CI_Controller { $cost_c['tourCostRsd'] = $cost->person_cost; $cost_c['tourCostRSx'] = $cost->person_cost; $cost_c['tourcost'] = $cost->order_cost[0]->order_cost_sum; + $cost_c['RPT_COLD_SN'] = $cost->order_cost[0]->COLD_SN; $cost_c_price = 0; foreach ($cost->order_cost as $koc => $coc) { if ($coc->PAG_code === $coc->real_code) { From fafede57fc923436da4e536a86d9a5cd9834fde5 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sun, 5 May 2019 14:44:59 +0800 Subject: [PATCH 307/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5:=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E7=BB=84=E5=9B=A2=E7=A4=BE=E9=94=99=E8=AF=AF=E7=9A=84=E5=A4=87?= =?UTF-8?q?=E6=B3=A8=E6=8F=90=E7=A4=BA;=20=E4=BF=AE=E6=AD=A3=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E7=9A=84=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B[=E5=9C=B0=E6=8E=A5=E4=BB=A3=E6=94=B6,=E5=9C=B0?= =?UTF-8?q?=E6=8E=A5=E7=A4=BE=E4=BB=A3=E6=94=B6]?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 8 +++++++- .../third_party/trippestOrderSync/models/order_update.php | 2 +- .../third_party/trippestOrderSync/models/orders_model.php | 4 ++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4dd918a5..4c4384e0 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -369,7 +369,7 @@ class TulanduoApi extends CI_Controller ,"GCI_leaveDate" => $detail_jsonResp->orderDetail->leaveDate ,"GCI_createTime" => date('Y-m-d H:i:s') ); - $this->Order_update->biz_groupcombineinfo_update($gci_update_column); + $gci_info = $this->Order_update->biz_groupcombineinfo_update($gci_update_column); /** GRoupInfo */ $coli_groupcode_ht = analysis_groupCode($getInfo_byGroupCode->COLI_GroupCode); $groupcode_ht = $coli_groupcode_ht['cut']; @@ -395,6 +395,12 @@ class TulanduoApi extends CI_Controller $new_memo = trim($detail_jsonResp->orderDetail->orderRemark)=="" ? $old_memo : $old_memo . " orderRemark\r\n" . $detail_jsonResp->orderDetail->orderRemark . "\r\n"; $old_detail = mb_strstr($coli_orderdetailtext, " operations", true)!==false ? mb_strstr($coli_orderdetailtext, " operations", true) : $coli_orderdetailtext; $new_detail = trim($allDetails_to_HT)=="" ? $old_detail : $old_detail . " operations\r\n" . $allDetails_to_HT . "\r\n"; + // 判断收款方并提示 + $finance_memo = ""; + if (intval($coli_opi_id) === 435 && in_array($gci_info->GCI_FromAgc, array("D目的地桂林组", "Trippest"))) { + $finance_memo .= "备注: 本订单组团社是渠道, 账单收款方应为地接社代收, 同步回来却是Trippest自营, 请注意核对.\r\n"; + $new_memo .= mb_strstr($new_memo, "orderRemark", true)!==false ? $finance_memo : ("orderRemark " . $finance_memo); + } // 团款总金额 // 渠道实收 $travel_fee = 0; diff --git a/webht/third_party/trippestOrderSync/models/order_update.php b/webht/third_party/trippestOrderSync/models/order_update.php index bff88fd2..8b0bd495 100644 --- a/webht/third_party/trippestOrderSync/models/order_update.php +++ b/webht/third_party/trippestOrderSync/models/order_update.php @@ -53,7 +53,7 @@ class Order_update extends CI_Model { } $update_str = $this->HT->update_string('GroupCombineInfo', $column_data, $this->gci_where_update); $update_exc = $this->HT->query($update_str); - return $update_exc; + return $this->HT->query("SELECT top 1 * from GroupCombineInfo WHERE " . $this->gci_where_update)->row(); } /*! diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index a25828f3..e241900c 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -1280,8 +1280,8 @@ class Orders_model extends CI_Model { public function biz_groupaccountinfo_cut($coli_sn, $paytype) { $sql = "DELETE from BIZ_GroupAccountInfo - WHERE GAI_COLI_SN=? AND GAI_Type=? AND GAI_Operator = 435"; - $query = $this->HT->query($sql, array($coli_sn, $paytype)); + WHERE GAI_COLI_SN=? AND GAI_Operator = 435"; // AND GAI_Type=?, $paytype + $query = $this->HT->query($sql, array($coli_sn)); return $query; } From 1173cc6c92f27fdf1459fa82f89c8e70c18db596 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sun, 5 May 2019 16:34:40 +0800 Subject: [PATCH 308/382] mark todo --- webht/third_party/paypal/controllers/index.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 3c2bdb67..0c5f15a6 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -883,6 +883,12 @@ class Index extends CI_Controller { //echo 'done!'; } + /*! + * 退款处理 + * @date 2019-05-05 + * TODO: + * * 退款的记录增加发送财务的状态 + */ public function send_refund($item, $handpick, $old_ssje=NULL) { // 找到原始收款交易的订单 @@ -972,6 +978,7 @@ class Index extends CI_Controller { $M_AddTime = $item->pn_payment_date; $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + // TODO 通知客人 // TODO 通知财务, 如果已做账 //添加邮件发送记录 end From d6d761bc4d486e900e059187052c8ce35316c31e Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 6 May 2019 11:33:58 +0800 Subject: [PATCH 309/382] =?UTF-8?q?alipay=20=E4=B8=B4=E6=97=B6=E5=A2=9E?= =?UTF-8?q?=E5=8A=A0=E8=B7=A8=E5=9F=9F,=20=E8=BF=81=E7=A7=BB144=E5=90=8E?= =?UTF-8?q?=E5=88=A0=E9=99=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 4 ++++ .../pay/controllers/WxpayService.php | 18 +++++++++--------- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 9800c519..af470043 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -78,6 +78,10 @@ class AlipayTradeService extends CI_Controller if(empty($this->gateway_url)||trim($this->gateway_url)==""){ log_message('error','Alipay ERROR gateway_url should not be NULL!'); } + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); } public function index() { diff --git a/webht/third_party/pay/controllers/WxpayService.php b/webht/third_party/pay/controllers/WxpayService.php index 1f39a0ed..145ecb49 100644 --- a/webht/third_party/pay/controllers/WxpayService.php +++ b/webht/third_party/pay/controllers/WxpayService.php @@ -139,18 +139,18 @@ log_message('error','notify begin ----'); * 格式化参数格式化成url参数 */ public function to_url_params($xml_arr) + { + $buff = ""; + foreach ($xml_arr as $k => $v) { - $buff = ""; - foreach ($xml_arr as $k => $v) - { - if($k != "sign" && $v != "" && !is_array($v)){ - $buff .= $k . "=" . $v . "&"; - } + if($k != "sign" && $v != "" && !is_array($v)){ + $buff .= $k . "=" . $v . "&"; } - - $buff = trim($buff, "&"); - return $buff; } + $buff = trim($buff, "&"); + return $buff; + } + } From 2665fcbdb941a5bbea6feff52d997b62c530808b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 6 May 2019 18:03:02 +0800 Subject: [PATCH 310/382] =?UTF-8?q?paypal=20=E9=80=80=E6=AC=BE:=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E9=82=AE=E4=BB=B6=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/config/config.php | 30 ++++++------ .../third_party/paypal/controllers/index.php | 31 ++++++++----- .../paypal/models/paypal_model.php | 18 ++++++-- .../third_party/paypal/views/refund_buyer.php | 46 +++++++++++++++++++ 4 files changed, 94 insertions(+), 31 deletions(-) create mode 100644 webht/third_party/paypal/views/refund_buyer.php diff --git a/webht/config/config.php b/webht/config/config.php index ea305f7b..31b9d963 100644 --- a/webht/config/config.php +++ b/webht/config/config.php @@ -362,19 +362,19 @@ $config['proxy_ips'] = ''; $config['site'] = array( - 'cht' => array('site_code' => 'cht', 'site_id' => 14, 'site_lgc' => '1', 'site_url' => 'http://www.chinahighlights.com'), - 'gm' => array('site_code' => 'gm', 'site_id' => 22, 'site_lgc' => '4', 'site_url' => 'http://www.chinarundreisen.com'), - 'vc' => array('site_code' => 'vc', 'site_id' => 30, 'site_lgc' => '5', 'site_url' => 'http://www.voyageschine.com'), - 'jp' => array('site_code' => 'jp', 'site_id' => 88, 'site_lgc' => '3', 'site_url' => 'http://www.arachina.com'), - 'vac' => array('site_code' => 'vac', 'site_id' => 95, 'site_lgc' => '6', 'site_url' => 'http://www.viaje-a-china.com'), - 'it' => array('site_code' => 'it', 'site_id' => 168, 'site_lgc' => '8', 'site_url' => 'http://www.viaggio-in-cina.it'), - 'ru' => array('site_code' => 'ru', 'site_id' => 102, 'site_lgc' => '7', 'site_url' => 'http://www.chinahighlights.ru'), - 'wt' => array('site_code' => 'wt', 'site_id' => 172, 'site_lgc' => '2', 'site_url' => 'http://www.iiiyooo.com'), - 'tbt' => array('site_code' => 'tbt', 'site_id' => 169, 'site_lgc' => '1', 'site_url' => 'http://www.tibettravel.info'), - 'sht' => array('site_code' => 'sht', 'site_id' => 96, 'site_lgc' => '1', 'site_url' => 'http://www.shanghaihighlights.com'), - 'yz' => array('site_code' => 'yz', 'site_id' => 89, 'site_lgc' => '1', 'site_url' => 'http://www.yangtzeriver.org'), - 'gl' => array('site_code' => 'gl', 'site_id' => 90, 'site_lgc' => '1', 'site_url' => 'http://www.guilinchina.net'), - 'mbj' => array('site_code' => 'mbj', 'site_id' => 98, 'site_lgc' => '1', 'site_url' => 'http://www.mybeijingchina.com'), - 'ct' => array('site_code' => 'ct', 'site_id' => 1000, 'site_lgc' => '104', 'site_url' => 'http://www.chinatravel.com'), - 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'http://www.diychinatours.com') + 'cht' => array('site_code' => 'cht', 'site_id' => 14, 'site_lgc' => '1', 'site_url' => 'https://www.chinahighlights.com'), + 'gm' => array('site_code' => 'gm', 'site_id' => 22, 'site_lgc' => '4', 'site_url' => 'https://www.chinarundreisen.com'), + 'vc' => array('site_code' => 'vc', 'site_id' => 30, 'site_lgc' => '5', 'site_url' => 'https://www.voyageschine.com'), + 'jp' => array('site_code' => 'jp', 'site_id' => 88, 'site_lgc' => '3', 'site_url' => 'https://www.arachina.com'), + 'vac' => array('site_code' => 'vac', 'site_id' => 95, 'site_lgc' => '6', 'site_url' => 'https://www.viaje-a-china.com'), + 'it' => array('site_code' => 'it', 'site_id' => 168, 'site_lgc' => '8', 'site_url' => 'https://www.viaggio-in-cina.it'), + 'ru' => array('site_code' => 'ru', 'site_id' => 102, 'site_lgc' => '7', 'site_url' => 'https://www.chinahighlights.ru'), + 'wt' => array('site_code' => 'wt', 'site_id' => 172, 'site_lgc' => '2', 'site_url' => 'https://www.iiiyooo.com'), + 'tbt' => array('site_code' => 'tbt', 'site_id' => 169, 'site_lgc' => '1', 'site_url' => 'https://www.tibettravel.info'), + 'sht' => array('site_code' => 'sht', 'site_id' => 96, 'site_lgc' => '1', 'site_url' => 'https://www.shanghaihighlights.com'), + 'yz' => array('site_code' => 'yz', 'site_id' => 89, 'site_lgc' => '1', 'site_url' => 'https://www.yangtzeriver.org'), + 'gl' => array('site_code' => 'gl', 'site_id' => 90, 'site_lgc' => '1', 'site_url' => 'https://www.guilinchina.net'), + 'mbj' => array('site_code' => 'mbj', 'site_id' => 98, 'site_lgc' => '1', 'site_url' => 'https://www.mybeijingchina.com'), + 'ct' => array('site_code' => 'ct', 'site_id' => 1000, 'site_lgc' => '104', 'site_url' => 'https://www.chinatravel.com'), + 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'https://www.diychinatours.com') ); diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 0c5f15a6..1cccf5db 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -747,8 +747,10 @@ class Index extends CI_Controller { } //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->pn_payment_status == 'Refunded') { - $this->Note_model->update_send($item->pn_txn_id, 'send'); + $this->send_refund($item, $handpick, $old_ssje); continue; + // $this->Note_model->update_send($item->pn_txn_id, 'send'); + // continue; } //只处理完成状态,其他状态由陆燕处理 @@ -892,7 +894,8 @@ class Index extends CI_Controller { public function send_refund($item, $handpick, $old_ssje=NULL) { // 找到原始收款交易的订单 - $parent_note = $this->note_modal->note($item->parent_txn_id); + $parent_txn_id = json_decode($item->pn_memo)->parent_txn_id; + $parent_note = $this->Note_model->note($parent_txn_id); if (empty($parent_note)) { return false; } @@ -904,7 +907,7 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); return false; } - + $orderid_info = json_decode($orderid_info); // for trippest tourMaster 2018.05.28 if ($orderid_info->ordertype == 'TP') { $this->trippest_note($orderid_info, $item); @@ -912,7 +915,6 @@ class Index extends CI_Controller { } //根据订单号查找外联信息 - $orderid_info = json_decode($orderid_info); $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); //查不到订单信息 @@ -931,24 +933,24 @@ class Index extends CI_Controller { $ssje = $old_ssje===NULL ? $ssje : $old_ssje; //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { - $ht_memo = '退款交易号(自动录入):' . $item->pn_txn_id . "\n. "; - $ht_memo .= '原收款交易号(自动录入):' . $item->parent_txn_id; + $ht_memo = '(自动录入)退款号:' . $item->pn_txn_id . "\n. "; + $ht_memo .= '原收款号:' . $parent_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } else { if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } - $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); } } //更新还没有填的客邮和交易号de收款记录(传统订单) elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { - $ht_memo = '退款交易号(自动录入):' . $item->pn_txn_id . "\n. "; - $ht_memo .= '原收款交易号(自动录入):' . $item->parent_txn_id; + $ht_memo = '(自动)退款号:' . $item->pn_txn_id . "\n. "; + $ht_memo .= '原交易号:' . $parent_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; $gai_sn = $this->Paypal_model->add_tour_account_info($GAI_COLI_SN, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); //添加汉特的订单提醒 @@ -965,7 +967,12 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); return false; } - + // TODO site_code + $site_info = $this->config->item('site'); + $site_info = $site_info['cht']; + $advisor_detail = $this->Paypal_model->get_advisor_detail($advisor_info->OPI_SN, $site_info['site_lgc']); + $item->advisor_detail = $advisor_detail; + $item->site = $site_info['site_url']; //添加邮件发送记录 //给外联发送通知邮件 $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; @@ -979,6 +986,8 @@ class Index extends CI_Controller { $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); // TODO 通知客人 + $this->load->view('refund_buyer', $item); + // TODO 通知财务, 如果已做账 //添加邮件发送记录 end diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index df8808e5..0e2da945 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,7 +19,7 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -27,7 +27,7 @@ class Paypal_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID' order by CHARINDEX('$COLI_ID', COLI_ID) "; @@ -41,7 +41,7 @@ class Paypal_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -49,7 +49,7 @@ class Paypal_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -65,7 +65,7 @@ class Paypal_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -611,4 +611,12 @@ class Paypal_model extends CI_Model { $real_orderid ? $sql.=" and COLI_ID=$real_orderid " : ""; return $this->HT->query($sql)->row(); } + + public function get_advisor_detail($OPI_SN, $lgc=1) + { + $sql = "SELECT OPI_SN,OPI_MoveTelephone,OPI_Telephone,OPI_Email,OPI2_Name,OPI2_FirstName,OPI2_LastName + FROM [Tourmanager].[dbo].[V_Operator_Info] + where OPI_SN=? and LGC_LGC=? "; + return $this->HT->query($sql, array($OPI_SN, $lgc))->row(); + } } diff --git a/webht/third_party/paypal/views/refund_buyer.php b/webht/third_party/paypal/views/refund_buyer.php new file mode 100644 index 00000000..4624db39 --- /dev/null +++ b/webht/third_party/paypal/views/refund_buyer.php @@ -0,0 +1,46 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns=http://www.w3.org/1999/xhtml> +<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title>Your Submission Was Successful! - China Highlights</title><style type=text/css>* { margin:0; font-family: Verdana, Arial, Helvetica, sans-serif; }body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size:13px; color:#545454; right: auto; }img, ul, ul li { padding:0; margin:0; border:0; }#warp { border-top:8px solid #a31022!important; }#logo { border: none!important}#logo, #surveyContent { width:210mm; margin:5px auto; padding:5px; }h1 { margin:15px 0 10px 0; font-size:24px; border-bottom:1px solid #d9d9d9; color:#545454; }h2 { margin:15px 0 10px 0; font-size:20px; color:#545454; }.tableSurvey table td { padding:5px; }.tableSurvey table td strong { margin-top:8px; }.tableSurvey1 { border:1px solid #e1e1e1; }.tableSurvey1 th { border:1px solid #fff; height:30px; padding-right:10px; text-align:right; background:#f1f1f1; }.tableSurvey1 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.tableSurvey2 { border:1px solid #e1e1e1; }.tableSurvey2 th { border:1px solid #fff; padding:5px 10px; text-align:right; background:#f1f1f1; font-weight:normal; }.tableSurvey2 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.blue{ color:#0070C0} +.text-bold {font-weight: bold;} +.text-right{text-align: right;} +.title-bold{font-weight: bold;background-color: #ddd;padding: 3px 0;} +</style></head> +<body> + <div id=warp> + <div id=surveyContent> + <?php $raw = json_decode($pn_memo); $c_gross = str_replace("-", "", $pn_mc_gross); ?> + <p>Dear <?php echo $pn_payer ?>,</p> + <br> + <p>China Highlights has refunded to your account today - <?php echo $c_gross ?><?php echo $pn_mc_currency ?>. The transaction to appear on your account may take up to 2-weeks.</p> + <br> + <p>Please find below details of your refund transaction:</p> + <br> + <p class="title-bold">Transaction details</p> + <p ><?php echo $raw->payment_date ?></p> + <p >Payment status: <?php echo $pn_payment_status ?></p> + <br> + <p class="title-bold">Payment details</p> + <p>Gross amount</p> + <p class="text-right"><?php echo $pn_mc_gross ?> <?php echo $pn_mc_currency ?></p> + <br> + <p class="title-bold">Invoice ID</p> + <p><?php echo $pn_invoice ?></p> + <br> + <p class="title-bold">Contact information</p> + <p ><?php echo $pn_payer ?></p> + <p ><?php echo $pn_payer_email ?></p> + <br> + <br> + <pre style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:13px;"> +Best Regards! + +<?php echo $advisor_detail->OPI2_Name ?>, Travel Advisor<br> +Tel: +86-773-<?php echo $advisor_detail->OPI_Telephone ?> Mobile: +86-<?php echo $advisor_detail->OPI_MoveTelephone ?><br> +E-mail: <?php echo $advisor_detail->OPI_Email ?><br> +<?php echo $site; ?><br> +Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China + </pre> + </div> + </div> +</body> +</html> From 6454733a9ab67603ef026053d8939d0b9deb3a64 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 7 May 2019 09:58:20 +0800 Subject: [PATCH 311/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E5=88=B0144=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E6=9B=B4=E6=96=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/models/BIZ_train_model.php | 2 +- .../tripadvisor_spider/controllers/index.php | 16 +++++++++------ .../dingmail/controllers/index.php | 18 +++-------------- .../dingmail/models/ding_value_model.php | 17 ++++++++++++++++ webht/third_party/dingmail/views/login.php | 20 +++++++++---------- .../dingmail/views/rank_person.php | 2 +- .../third_party/outlook/controllers/index.php | 18 ++++++++++------- .../outlook/models/outlook_model.php | 2 +- 8 files changed, 54 insertions(+), 41 deletions(-) diff --git a/application/third_party/trainsystem/models/BIZ_train_model.php b/application/third_party/trainsystem/models/BIZ_train_model.php index d6401575..0c4b8fea 100644 --- a/application/third_party/trainsystem/models/BIZ_train_model.php +++ b/application/third_party/trainsystem/models/BIZ_train_model.php @@ -253,7 +253,7 @@ class BIZ_train_model extends CI_Model { //自动获取符合自动出票要求的订单的coli_sn function auto_check_ticket(){ - $sql = "SELECT distinct top 20 COLD_SN ,coli_id,COLD_SPFS,COLI_State + $sql = "SELECT distinct top 30 COLD_SN ,coli_id,COLD_SPFS,COLI_State FROM BIZ_ConfirmLineInfo bcli inner join BIZ_ConfirmLineDetail bcld on COLD_COLI_SN=COLI_SN LEFT JOIN BIZ_GroupAccountInfo bgai diff --git a/application/third_party/tripadvisor_spider/controllers/index.php b/application/third_party/tripadvisor_spider/controllers/index.php index 6bc23ea5..6b7e266f 100644 --- a/application/third_party/tripadvisor_spider/controllers/index.php +++ b/application/third_party/tripadvisor_spider/controllers/index.php @@ -18,7 +18,7 @@ class Index extends CI_Controller { header('Access-Control-Allow-Credentials:true'); $this->load->model('Tripadvisor_Review_model'); } - + public function index($city = 'Beijing') { $this->permission->is_admin(); $data = array(); @@ -228,6 +228,7 @@ class Index extends CI_Controller { require_once "PHPExcel/IOFactory.php"; $phpExcel = PHPExcel_IOFactory::load($path.$filename); + //创建返回的数组 $data = []; foreach ($phpExcel->getSheetNames() as $key=>$destination){ @@ -236,20 +237,20 @@ class Index extends CI_Controller { $data[$key]->list_name = array(); $data[$key]->list_data = array(); //循环获取每个表格的行/列数 - $row = $phpExcel->getActiveSheet()->getHighestRow(); - $column = $phpExcel->getActiveSheet()->getHighestColumn(); + $row = $phpExcel->getSheet($key)->getHighestRow(); + $column = $phpExcel->getSheet($key)->getHighestColumn(); $j = 0; // 行数循环 for ($i = 1; $i <= $row; $i++) { // 列数循环 for ($c = 'A'; $c <= $column; $c++) { - if($phpExcel->getActiveSheet($key)->getCell('A' . $i)->getValue() == ''){ + if($phpExcel->getSheet($key)->getCell('A' . $i)->getValue() == ''){ continue; }else{ if($i == 1){ - array_push($data[$key]->list_name,$phpExcel->getActiveSheet($key)->getCell($c . $i)->getValue()); + array_push($data[$key]->list_name,$phpExcel->getSheet($key)->getCell($c . $i)->getValue()); }else{ - $data[$key]->list_data[$j][] = $phpExcel->getActiveSheet($key)->getCell($c . $i)->getValue(); + $data[$key]->list_data[$j][] = $phpExcel->getSheet($key)->getCell($c . $i)->getValue(); } } @@ -291,6 +292,7 @@ class Index extends CI_Controller { set_time_limit(0); $url = $this->input->get_post('url'); $destination = $this->input->get_post('destination'); + $html_num = $this->input->get_post('html_num'); //$url = 'https://www.tripadvisor.com/ShowUserReviews-g294212-d4006739-r666168101-The_Trippest_Mini_Group_Tours-Beijing.html'; $destination = 'tp_Beijing'; @@ -307,6 +309,8 @@ class Index extends CI_Controller { $meta_inner = $html_object->find('.meta_inner'); foreach($meta_inner as $detail_info){ + //记录该条记录的id + $detail_data->html_id = $html_num; //获取评论者帐号 foreach($detail_info->find('.info_text') as $review_name){ $detail_data->review_name = $review_name->first_child()->innertext; diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index 6b705811..7ee50452 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -375,21 +375,9 @@ class Index extends CI_Controller { $year_end = strtotime(date('Y-12-31', time())); //$year_end = strtotime(date('2016-12-31')); $data['rank_year'] = $this->ding_value_model->get_person_rank($year_start, $year_end); - //总榜 - //$data['rank_all']=$this->Outlook_model->get_person_rank(); - //每条价值观对应获得最多的人 - /* ycc,暂时不需要了 - $rank=array(); - $value_array=array('team','chengxin','customer','discovery','system'); - foreach ($value_array as $value) { - $rank[$value]=$this->Outlook_model->value_key_rank($value); - for ($i=1; $i < 5; $i++) { - $value_key=$value.$i; - $rank[$value_key]=$this->Outlook_model->value_key_rank($value_key); - } - } - $data['rank']=$rank; - */ + //获取全年点赞次数 + $data['click_like'] = $this->ding_value_model->get_click_liek($year_start, $year_end); + $this->load->view('rank_person',$data); } } diff --git a/webht/third_party/dingmail/models/ding_value_model.php b/webht/third_party/dingmail/models/ding_value_model.php index cc656095..72992758 100644 --- a/webht/third_party/dingmail/models/ding_value_model.php +++ b/webht/third_party/dingmail/models/ding_value_model.php @@ -287,6 +287,23 @@ class ding_value_model extends CI_Model { return $result; } + //获取全年参与点赞的次数 + public function get_click_liek($from_date=false,$to_date=false){ + $datesql=""; + if ($from_date) { + $datesql=" AND ddv_Createtime BETWEEN '$from_date' AND '$to_date' "; + } + $sql="SELECT COUNT(*) as like_count + FROM Dingding_Value + WHERE ddv_Type='like' AND ddv_Comment_Name != 'value邮件' + $datesql + "; + + $query = $this->HT->query($sql); + $result=$query->row(); + return $result; + } + //更新用户信息 function update_dingding_user($name,$unionid,$mobile,$email,$position,$avatar,$time){ $sql = "UPDATE Dingding_User SET diff --git a/webht/third_party/dingmail/views/login.php b/webht/third_party/dingmail/views/login.php index 39421aa0..6c38f003 100644 --- a/webht/third_party/dingmail/views/login.php +++ b/webht/third_party/dingmail/views/login.php @@ -4,16 +4,16 @@ <meta charset="utf-8"> <title>value系统登录</title> <link href="http://data.chtcdn.com/bootstrap/css/bootstrap.min.css" rel="stylesheet"> - <link rel="stylesheet" href="http://data.chtcdn.com/js/poshytip/tip-yellow/tip-yellow.css" type="text/css" /> - <link rel="stylesheet" href="http://data.chtcdn.com/js/modaldialog/css/jquery.modaldialog.css" type="text/css" /> - <link rel="stylesheet" href="http://data.chtcdn.com/js/kindeditor/themes/default/default.css" type="text/css" media="screen" /> - <script type="text/javascript" src="http://data.chtcdn.com/js/jquery.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/bootstrap/js/bootstrap.min.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/js/poshytip/jquery.poshytip.min.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/js/jquery.form.min.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/js/modaldialog/jquery.modaldialog.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/js/kindeditor/kindeditor-min.js"></script> - <script type="text/javascript" src="http://data.chtcdn.com/js/basic.js"></script> + <link rel="stylesheet" href="/js/poshytip/tip-yellow/tip-yellow.css" type="text/css" /> + <link rel="stylesheet" href="/js/modaldialog/css/jquery.modaldialog.css" type="text/css" /> + <link rel="stylesheet" href="/js/kindeditor/themes/default/default.css" type="text/css" media="screen" /> + <script type="text/javascript" src="/js/jquery.js"></script> + <script type="text/javascript" src="/js/bootstrap.min.js"></script> + <script type="text/javascript" src="/js/poshytip/jquery.poshytip.min.js"></script> + <script type="text/javascript" src="/js/jquery.form.min.js"></script> + <script type="text/javascript" src="/js/modaldialog/jquery.modaldialog.js"></script> + <script type="text/javascript" src="/js/kindeditor/kindeditor-min.js"></script> + <script type="text/javascript" src="/js/basic.js"></script> <script src="https://g.alicdn.com/dingding/dinglogin/0.0.2/ddLogin.js"></script> <script type="text/javascript" src="/dinglogin/dingmail.js"></script> <link rel="stylesheet" href="/dinglogin/dingding.css"> diff --git a/webht/third_party/dingmail/views/rank_person.php b/webht/third_party/dingmail/views/rank_person.php index e1a89a0f..398936e6 100644 --- a/webht/third_party/dingmail/views/rank_person.php +++ b/webht/third_party/dingmail/views/rank_person.php @@ -59,7 +59,7 @@ <div class="row"> <div class="col-xs-24 btn-lg"></div> <div class="col-xs-24"> - <h3>个人获赞排行榜</h3> + <h3>个人获赞排行榜 | 全年参与点赞次数:<?php echo $click_like->like_count?></h3> </div> <div class="col-xs-8"> <div class="col-xs-24 bg-white min-height-500"> diff --git a/webht/third_party/outlook/controllers/index.php b/webht/third_party/outlook/controllers/index.php index 5f6ef0a7..7372af94 100644 --- a/webht/third_party/outlook/controllers/index.php +++ b/webht/third_party/outlook/controllers/index.php @@ -175,7 +175,10 @@ class Index extends CI_Controller { $data['rank_month'] = $this->Outlook_model->get_person_rank($from_date, $to_date); //年榜 $year_start = strtotime(date('Y-01-01', time())); + //$year_start = strtotime(date('2016-01-01')); $year_end = strtotime(date('Y-12-31', time())); + //$year_end = strtotime(date('2016-12-31')); + $data['rank_year'] = $this->Outlook_model->get_person_rank($year_start, $year_end); //总榜 //$data['rank_all']=$this->Outlook_model->get_person_rank(); @@ -342,12 +345,12 @@ class Index extends CI_Controller { $tip_type = 'comment'; //等于comment时页面不弹出提示 $tpldata['list'] = $this->Outlook_model->get_comment_list($whc_whm_identify, 'comment', 'DESC'); - $tpldata['mail_text'] = $this->Outlook_model->get_mail_text($whc_whm_identify); + $tpldata['mail_text'] = $this->Outlook_model->get_mail_text($whc_whm_identify); $tpldata['userinfo'] = $this->Outlook_model->get_webhtuser_by_filed('whu_email', $whc_whm_identify . '@citsguilin.com', '*'); - + if ($current_user->whu_uid && $linktype != 'comment' && $tpldata['userinfo']->whu_uid != $current_user->whu_uid) { $like_count = $this->Outlook_model->get_comment_count($whc_whm_identify, $linktype, $current_user->whu_uid); - if ($like_count < 3) { + if ($like_count < 3) { $data['whc_type'] = $linktype; $data['whc_whm_identify'] = $whc_whm_identify; $data['whc_uid'] = $current_user->whu_uid; @@ -373,7 +376,7 @@ class Index extends CI_Controller { } $tpldata['list_count'] = $this->Outlook_model->get_space_comment($tpldata['userinfo']->whu_uname, $whc_whm_identify, 'comment', true); - $tpldata['like_list'] = $this->Outlook_model->get_space_comment($tpldata['userinfo']->whu_uname, $whc_whm_identify, 'like'); + $tpldata['like_list'] = $this->Outlook_model->get_space_comment($tpldata['userinfo']->whu_uname, $whc_whm_identify, 'like'); $tpldata['unlike_list'] = $this->Outlook_model->get_space_comment($tpldata['userinfo']->whu_uname, $whc_whm_identify, 'unlike'); $tpldata['type'] = $tip_type; $tpldata['current_user'] = $current_user; @@ -627,7 +630,6 @@ class Index extends CI_Controller { $fromemail = $fromuser->whu_email; $subject = $this->input->post('mail_subject'); $body = $this->input->post('emailcontent') . $mailbody; - if (!$this->do_sendmail($fromemail, $tolist_array, $cclist_array, $subject, $body)) { $result = 0; //"邮件发送有误: " . $mail->ErrorInfo; } else { @@ -659,7 +661,7 @@ class Index extends CI_Controller { $mail->CharSet = "utf-8"; $mail->Encoding = "base64"; $mail->IsHTML(true); - + $mail->From = $fromuser; //发件人 foreach ($tolist_array as $v) { $mail->AddAddress($v); //收件人 @@ -671,7 +673,8 @@ class Index extends CI_Controller { $mail->Body = $mailbody; //邮件内容 if (!$mail->Send()) { - $result = false; //"邮件发送有误: " . $mail->ErrorInfo; + //$result = false;// echo "邮件发送有误: " . $mail->ErrorInfo; + echo "邮件发送有误: " . $mail->ErrorInfo; } else { $result = true; } @@ -814,6 +817,7 @@ class Index extends CI_Controller { $whu_uname = $whu_uname[0]; $whu_ip = $this->input->post('whu_ip'); $result = $this->Outlook_model->verify_user($whu_uname, $whu_ip); + echo $result; } diff --git a/webht/third_party/outlook/models/outlook_model.php b/webht/third_party/outlook/models/outlook_model.php index 86e6d1e0..1c8b4f3e 100644 --- a/webht/third_party/outlook/models/outlook_model.php +++ b/webht/third_party/outlook/models/outlook_model.php @@ -281,7 +281,7 @@ class Outlook_model extends CI_Model { return '2'; }else{ $sql="UPDATE webht_user SET whu_ip = '$whu_ip',whu_status=1 WHERE whu_uname like '%$whu_uname%' "; - $result = $this->HT->query($sql); + $result = $this->HT->query($sql);//var_dump($this->HT->last_query()); return '1'; } } From 434dccc50ca09fa0b75dd5c95365820d77315201 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 May 2019 10:28:41 +0800 Subject: [PATCH 312/382] =?UTF-8?q?Alipay=E5=A2=9E=E5=8A=A0APP=E7=BB=84?= =?UTF-8?q?=E7=9A=84=E5=BD=95=E5=85=A5;=E4=BC=A0=E7=BB=9F=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E6=94=AF=E6=8C=81?= =?UTF-8?q?=E6=9B=B4=E6=96=B0=E5=AE=9E=E6=94=B6=E9=87=91=E9=A2=9D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 51 ++++++++++++------- webht/third_party/pay/models/Alipay_model.php | 11 ++-- 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index af470043..47db682f 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -417,11 +417,24 @@ class AlipayTradeService extends CI_Controller //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 - // $this->Alipay_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->ALI_dealId, $ht_memo); - // if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 - // $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 - // $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); - // } + $this->Alipay_model->add_account_info_forAPP( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->ALI_orderAmount, + $item->ALI_completeTime, + $currencyCode, + $ssje, + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_payerName, + $item->ALI_payerEmail, + $item->ALI_dealId, + $ht_memo); + if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 + $this->Alipay_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 + $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'BS8'); + } } else { // 把订单状态设置为13-新订单已支付 if (false == $this->Alipay_model->if_biz_gai_exists($item->ALI_dealId) ) { @@ -484,19 +497,21 @@ class AlipayTradeService extends CI_Controller //添加邮件发送记录 //给外联发送通知邮件 - $fromName = 'Alipay'; - $fromEmail = ''; - $toName = !empty($opi_firstname) ? $opi_firstname : ''; - $toEmail = !empty($opi_email) ? $opi_email : ''; - $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->ALI_orderAmount . $item->ALI_currencyCode . ' / ' . $fromName; - $body = $this->load->view('alipay_receipt_mail', $item, true); - $M_RelatedInfo = $item->ALI_sn; - $M_AddTime = $item->ALI_completeTime; - $M_State = 0; - $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'Alipay note'); - //添加邮件发送记录 end - - $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + if ($item->ALI_sent !== 'send') { + $fromName = 'Alipay'; + $fromEmail = ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->ALI_orderAmount . $item->ALI_currencyCode . ' / ' . $fromName; + $body = $this->load->view('alipay_receipt_mail', $item, true); + $M_RelatedInfo = $item->ALI_sn; + $M_AddTime = $item->ALI_completeTime; + $M_State = 0; + $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'Alipay note'); + //添加邮件发送记录 end + + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + } $int++; } // 批量结果 diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index e8de4b02..27be3647 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -149,7 +149,7 @@ class Alipay_model extends CI_Model { } //添加收款记录(商务订单),APP会自动增加记录,所以添加前根据金额来判断是否有重复记录 - public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info_forAPP($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " IF NOT EXISTS( @@ -164,6 +164,7 @@ class Alipay_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate ,GAI_SubmitDate @@ -173,8 +174,8 @@ class Alipay_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -239,7 +240,9 @@ class Alipay_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0) + ELSE + UPDATE GroupAccountInfo SET GAI_SSJE='$GAI_SSJE' WHERE GAI_AccreditNo='$GAI_AccreditNo' "; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $insertid; From cc7fc45dbaf55ade8fe05a3d73e8dceb5ed56cb9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 May 2019 14:43:15 +0800 Subject: [PATCH 313/382] =?UTF-8?q?paypal=20=E9=80=80=E6=AC=BE=E5=A4=84?= =?UTF-8?q?=E7=90=86,=E9=80=9A=E7=9F=A5=E5=AE=A2=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 1 + .../pay/views/alipay_receipt_mail.php | 2 +- .../third_party/paypal/controllers/index.php | 43 ++++++++++++++----- .../paypal/models/paypal_model.php | 17 ++++++++ webht/third_party/paypal/views/note_list.php | 2 +- 5 files changed, 53 insertions(+), 12 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 47db682f..cf9dce05 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -549,6 +549,7 @@ class AlipayTradeService extends CI_Controller $this->AlipayTradeQueryContentBuilder->setOutTradeNo($orderId); } $response = $this->Query($this->AlipayTradeQueryContentBuilder); + // return $this->output->set_content_type('application/json')->set_output(json_encode($response)); return $response; } diff --git a/webht/third_party/pay/views/alipay_receipt_mail.php b/webht/third_party/pay/views/alipay_receipt_mail.php index a2590081..76f30880 100644 --- a/webht/third_party/pay/views/alipay_receipt_mail.php +++ b/webht/third_party/pay/views/alipay_receipt_mail.php @@ -1 +1 @@ -<html> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"></head> <body style="font-size: 12px;font-family: arial,helvetica,sans-serif;margin-top:0;margin-bottom:0;"> <div class=ppmail> <table align=center border=0 cellpadding=0 cellspacing=0 width=100%> <tbody> <tr valign=top> <td width=100%> <table align=center border=0 cellpadding=0 cellspacing=0 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;" width=100%> <tbody> <tr valign=top> <td> <img src=https://data.chinahighlights.com/pic/alipay_logo.png border=0 alt="PayPal logo"> </td> <td valign=middle align=right> <?php echo $ALI_completeTime;?> <br>Transaction ID:<a target=new href=#> <?php echo $ALI_dealId;?> </a> </td> </tr> </tbody> </table> <div style="margin-top: 10px;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <span style="color:#333333 !important;font-weight:bold;font-family: arial,helvetica,sans-serif;">Hello Guilin China International Travel Service Co.,Ltd,</span> <br> <span style=font-size:14px;color:#C88039;font-weight:bold;text-decoration:none;>You received a payment of <?php echo $ALI_orderAmount;?> <?php echo $ALI_currencyCode;?> </span> <br> <table cellpadding=5 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <tbody> <tr> <td valign=top>Thanks for using iPayLinks.You can now ship any items.To see all the transaction details,log in to your iPayLinks account.<br>It may take a few moments for this transaction to appear in your account.<br> <span style=font-weight:bold;color:#333333;>Seller Protection-</span> <span style="color: #4c8f3a;"> </span> </td> <td> </td> </tr> </tbody> </table> <div style="margin-top:0px;border-bottom:1px solid #aaaaaa;"> </div> <table border=0 cellpadding=0 cellspacing=0 style="color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px; margin-bottom:5px;" width=98% align=left> <tbody> <tr> <td style=padding-top:5px; valign=top width=50% align=left> <span style=color:#333333;font-weight:bold;>Buyer</span> <br> <?php echo $ALI_payerName;?> <br> <?php echo $ALI_payerEmail;?> <br> </td> <td style=padding-top:5px; valign=top> </td> </tr> </tbody> </table> <table align=center border=0 cellpadding=0 cellspacing=0 style="clear:both;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;margin-top:5px;" width=100%> <tbody> <tr> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=330 align=left>Description</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=80 align=right>Amount</td> </tr> <tr> <td style=padding:10px; width=330 align=left> <?php echo $ALI_orderId;?> <br> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=80 align=right> <?php echo $ALI_orderAmount;?> <?php echo $ALI_currencyCode;?> </td> </tr> </tbody> </table> </tr> </tbody> </table> </div> </body> </html> +<html> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"></head> <body style="font-size: 12px;font-family: arial,helvetica,sans-serif;margin-top:0;margin-bottom:0;"> <div class=ppmail> <table align=center border=0 cellpadding=0 cellspacing=0 width=100%> <tbody> <tr valign=top> <td width=100%> <table align=center border=0 cellpadding=0 cellspacing=0 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;" width=100%> <tbody> <tr valign=top> <td> <img src=https://data.chinahighlights.com/pic/alipay_logo.png border=0 alt="PayPal logo"> </td> <td valign=middle align=right> <?php echo $ALI_completeTime;?> <br>Transaction ID:<a target=new href=#> <?php echo $ALI_dealId;?> </a> </td> </tr> </tbody> </table> <div style="margin-top: 10px;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <span style="color:#333333 !important;font-weight:bold;font-family: arial,helvetica,sans-serif;">Hello Guilin China International Travel Service Co.,Ltd,</span> <br> <span style=font-size:14px;color:#C88039;font-weight:bold;text-decoration:none;>You received a payment of <?php echo $ALI_orderAmount;?> <?php echo $ALI_currencyCode;?> </span> <br> <table cellpadding=5 style="color:#333333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;"> <tbody> <tr> <td valign=top>Thanks for using Alipay.You can now ship any items.To see all the transaction details,log in to your Alipay account.<br>It may take a few moments for this transaction to appear in your account.<br> <span style=font-weight:bold;color:#333333;>Seller Protection-</span> <span style="color: #4c8f3a;"> </span> </td> <td> </td> </tr> </tbody> </table> <div style="margin-top:0px;border-bottom:1px solid #aaaaaa;"> </div> <table border=0 cellpadding=0 cellspacing=0 style="color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px; margin-bottom:5px;" width=98% align=left> <tbody> <tr> <td style=padding-top:5px; valign=top width=50% align=left> <span style=color:#333333;font-weight:bold;>Buyer</span> <br> <?php echo $ALI_payerName;?> <br> <?php echo $ALI_payerEmail;?> <br> </td> <td style=padding-top:5px; valign=top> </td> </tr> </tbody> </table> <table align=center border=0 cellpadding=0 cellspacing=0 style="clear:both;color:#333 !important;font-family: arial,helvetica,sans-serif;font-size:12px;margin-top:5px;" width=100%> <tbody> <tr> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=330 align=left>Description</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=75 align=right>&nbsp;</td> <td style="border:1px solid #ccc;border-right:none;border-left:none;padding:5px 10px 5px 10px !important;color: #333333 !important;" width=80 align=right>Amount</td> </tr> <tr> <td style=padding:10px; width=330 align=left> <?php echo $ALI_orderId;?> <br> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=75 align=right> </td> <td style=padding:10px; width=80 align=right> <?php echo $ALI_orderAmount;?> <?php echo $ALI_currencyCode;?> </td> </tr> </tbody> </table> </tr> </tbody> </table> </div> </body> </html> diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 1cccf5db..a930c19a 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -897,6 +897,7 @@ class Index extends CI_Controller { $parent_txn_id = json_decode($item->pn_memo)->parent_txn_id; $parent_note = $this->Note_model->note($parent_txn_id); if (empty($parent_note)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); return false; } //订单号 @@ -947,7 +948,7 @@ class Index extends CI_Controller { $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); } } - //更新还没有填的客邮和交易号de收款记录(传统订单) + //更新还没有填的客邮和交易号的收款记录(传统订单) elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { $ht_memo = '(自动)退款号:' . $item->pn_txn_id . "\n. "; $ht_memo .= '原交易号:' . $parent_txn_id; @@ -958,7 +959,6 @@ class Index extends CI_Controller { } } - $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie @@ -967,9 +967,13 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); return false; } - // TODO site_code + + $web_code = $advisor_info->COLI_WebCode; $site_info = $this->config->item('site'); - $site_info = $site_info['cht']; + if ( ! isset($site_info[$web_code])) { + $web_code = 'cht'; + } + $site_info = $site_info[$web_code]; $advisor_detail = $this->Paypal_model->get_advisor_detail($advisor_info->OPI_SN, $site_info['site_lgc']); $item->advisor_detail = $advisor_detail; $item->site = $site_info['site_url']; @@ -980,19 +984,38 @@ class Index extends CI_Controller { $toName = !empty($opi_firstname) ? $opi_firstname : ''; $toEmail = !empty($opi_email) ? $opi_email : ''; $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $body = $this->load->view('mail_templete', $item, true); $M_RelatedInfo = $item->pn_sn; $M_AddTime = $item->pn_payment_date; $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); - // TODO 通知客人 - $this->load->view('refund_buyer', $item); - + // 通知客人, 客人邮箱 + $customer_detail = $this->Paypal_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype); + $c_fromName = $advisor_detail->OPI2_Name; + $c_fromEmail = $advisor_detail->OPI_Email; + $c_toName = $customer_detail->fullname; + $c_toEmail = $customer_detail->email; + $c_subject = $item->pn_mc_currency . " " . str_replace('-', '', $item->pn_mc_gross) . " Refunded to your account, booking number " . $item->pn_invoice; + $c_body = $this->load->view('refund_buyer', $item, true); + $c_M_RelatedInfo = $item->pn_sn; + $c_M_AddTime = $item->pn_payment_date; + $c_M_State = 0; + $this->Paypal_model->save_automail( + $c_fromName, + $c_fromEmail, + $c_toName, + $c_toEmail, + $c_subject, + $c_body, + $c_M_RelatedInfo, + $c_M_State, + $c_M_AddTime, + 'paypal refund receipt'); + $this->Note_model->update_send($item->pn_txn_id, 'send-customer'); // TODO 通知财务, 如果已做账 //添加邮件发送记录 end - - return $this->Note_model->update_send($item->pn_txn_id, 'send'); + return ; } public function trippest_note($orderid_info, $paypal_msg) diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 0e2da945..0684017d 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -619,4 +619,21 @@ class Paypal_model extends CI_Model { where OPI_SN=? and LGC_LGC=? "; return $this->HT->query($sql, array($OPI_SN, $lgc))->row(); } + + public function get_customer_detail($COLI_SN, $ordertype) + { + if ($ordertype === 'T') { + $sql = "SELECT mei.MEI_FirstName+' '+isnull(mei.MEI_MiddleName,'')+' '+isnull(mei.MEI_LastName,'') fullname, + mei.MEI_MailList email + FROM MEmberInfo mei + INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN and cul.CUL_IsLinkMan=1 + WHERE CUL_COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } else { + $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname,GUT_Email email from BIZ_GUEST g + INNER JOIN BIZ_ConfirmLineInfo coli on coli.COLI_GUT_SN=g.GUT_SN + WHERE COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } + } } diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 70dcc979..612750ed 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -209,7 +209,7 @@ echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true $show_send = ''; $class_css = ''; $show_record = '查看录入状态'; - if ($item->pn_send == 'send') { + if ($item->pn_send == 'send' || substr($item->pn_send, 0, 5) == "send-") { $show_send = $item->pn_send; } elseif ($item->pn_send == 'closeRecord') { $show_send = $show_record = '已忽略'; From 1ce0e268df6a6bd452ea5c71fa77d899101f9be8 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 7 May 2019 17:52:26 +0800 Subject: [PATCH 314/382] =?UTF-8?q?config=20=E5=A2=9E=E5=8A=A0Trippest?= =?UTF-8?q?=E7=AB=99=E7=82=B9;=E9=80=80=E6=AC=BE=E5=A4=84=E7=90=86?= =?UTF-8?q?=E7=9A=84=E5=AE=A2=E4=BA=BA=E9=82=AE=E4=BB=B6:+=E5=A4=96?= =?UTF-8?q?=E8=81=94=E7=9A=84=E7=AD=BE=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/config/config.php | 3 +- .../third_party/paypal/controllers/index.php | 104 ++++++++++-------- .../paypal/models/paypal_model.php | 28 ++++- .../third_party/paypal/views/refund_buyer.php | 8 +- 4 files changed, 85 insertions(+), 58 deletions(-) diff --git a/webht/config/config.php b/webht/config/config.php index 31b9d963..38dc5444 100644 --- a/webht/config/config.php +++ b/webht/config/config.php @@ -376,5 +376,6 @@ $config['site'] = array( 'gl' => array('site_code' => 'gl', 'site_id' => 90, 'site_lgc' => '1', 'site_url' => 'https://www.guilinchina.net'), 'mbj' => array('site_code' => 'mbj', 'site_id' => 98, 'site_lgc' => '1', 'site_url' => 'https://www.mybeijingchina.com'), 'ct' => array('site_code' => 'ct', 'site_id' => 1000, 'site_lgc' => '104', 'site_url' => 'https://www.chinatravel.com'), - 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'https://www.diychinatours.com') + 'dct' => array('site_code' => 'dct', 'site_id' => 99, 'site_lgc' => '1', 'site_url' => 'https://www.diychinatours.com'), + 'trippest' => array('site_code' => 'trippest', 'site_id' => 0, 'site_lgc' => '1', 'site_url' => 'https://www.trippest.com') ); diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index a930c19a..9569c86f 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -653,6 +653,8 @@ class Index extends CI_Controller { $ordertype = 'T'; } elseif (substr($ordertype_temp, 0, 1) == 'B') { $ordertype = 'B'; + } elseif (substr($ordertype_temp, 0, 1) == 'A') { + $ordertype = 'A'; } } // 2018.05.28 for Trippest, tourMaster的订单号是01开头 @@ -909,10 +911,9 @@ class Index extends CI_Controller { return false; } $orderid_info = json_decode($orderid_info); - // for trippest tourMaster 2018.05.28 - if ($orderid_info->ordertype == 'TP') { - $this->trippest_note($orderid_info, $item); - return false; + + if (in_array($orderid_info->ordertype, array('TP', 'A')) ) { + $orderid_info->ordertype = 'B'; } //根据订单号查找外联信息 @@ -968,52 +969,59 @@ class Index extends CI_Controller { return false; } - $web_code = $advisor_info->COLI_WebCode; - $site_info = $this->config->item('site'); - if ( ! isset($site_info[$web_code])) { - $web_code = 'cht'; - } - $site_info = $site_info[$web_code]; - $advisor_detail = $this->Paypal_model->get_advisor_detail($advisor_info->OPI_SN, $site_info['site_lgc']); - $item->advisor_detail = $advisor_detail; - $item->site = $site_info['site_url']; //添加邮件发送记录 - //给外联发送通知邮件 - $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; - $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; - $toName = !empty($opi_firstname) ? $opi_firstname : ''; - $toEmail = !empty($opi_email) ? $opi_email : ''; - $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $item, true); - $M_RelatedInfo = $item->pn_sn; - $M_AddTime = $item->pn_payment_date; - $M_State = 0; - $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); - // 通知客人, 客人邮箱 - $customer_detail = $this->Paypal_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype); - $c_fromName = $advisor_detail->OPI2_Name; - $c_fromEmail = $advisor_detail->OPI_Email; - $c_toName = $customer_detail->fullname; - $c_toEmail = $customer_detail->email; - $c_subject = $item->pn_mc_currency . " " . str_replace('-', '', $item->pn_mc_gross) . " Refunded to your account, booking number " . $item->pn_invoice; - $c_body = $this->load->view('refund_buyer', $item, true); - $c_M_RelatedInfo = $item->pn_sn; - $c_M_AddTime = $item->pn_payment_date; - $c_M_State = 0; - $this->Paypal_model->save_automail( - $c_fromName, - $c_fromEmail, - $c_toName, - $c_toEmail, - $c_subject, - $c_body, - $c_M_RelatedInfo, - $c_M_State, - $c_M_AddTime, - 'paypal refund receipt'); - $this->Note_model->update_send($item->pn_txn_id, 'send-customer'); - // TODO 通知财务, 如果已做账 + if ($item->pn_send !== 'send' && substr($item->pn_send, 0, 5) !== 'send-') { + // 客人邮件中的外联落款 + // $web_code = 'cht'; // 默认cht + $web_lgc = 1; + $web_code = strtolower($advisor_info->COLI_WebCode); + $site_info = $this->config->item('site'); + if (isset($site_info[$web_code])) { + $site_info = $site_info[$web_code]; + $item->site = $site_info['site_url']; + $web_lgc = $site_info['site_lgc']; + } + $advisor_detail = $this->Paypal_model->get_advisor_detail($advisor_info->COLI_SN, $advisor_info->OPI_SN, $web_lgc); + $item->advisor_detail = $advisor_detail; + + //给外联发送通知邮件 + $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; + $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $item, true); + $M_RelatedInfo = $item->pn_sn; + $M_AddTime = $item->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + // 通知客人, 客人邮箱 + $customer_detail = $this->Paypal_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype); + $c_fromName = $advisor_detail->fullname; + $opi_email_list = explode(";", $advisor_detail->email); // 解析外联的邮件 + $c_fromEmail = trim($opi_email_list[0]); + $c_toName = $customer_detail->fullname; + $c_toEmail = $customer_detail->email; + $c_subject = $item->pn_mc_currency . " " . str_replace('-', '', $item->pn_mc_gross) . " Refunded to your account, booking number " . $item->pn_invoice; + $c_body = $this->load->view('refund_buyer', $item, true); + $c_M_RelatedInfo = $item->pn_sn; + $c_M_AddTime = $item->pn_payment_date; + $c_M_State = 0; + $this->Paypal_model->save_automail( + $c_fromName, + $c_fromEmail, + $c_toName, + $c_toEmail, + $c_subject, + $c_body, + $c_M_RelatedInfo, + $c_M_State, + $c_M_AddTime, + 'paypal refund receipt'); + $this->Note_model->update_send($item->pn_txn_id, 'send-customer'); + } //添加邮件发送记录 end + // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 return ; } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 0684017d..0f8697f5 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -612,12 +612,30 @@ class Paypal_model extends CI_Model { return $this->HT->query($sql)->row(); } - public function get_advisor_detail($OPI_SN, $lgc=1) + public function get_advisor_detail($COLI_SN, $OPI_SN, $lgc=1) { - $sql = "SELECT OPI_SN,OPI_MoveTelephone,OPI_Telephone,OPI_Email,OPI2_Name,OPI2_FirstName,OPI2_LastName - FROM [Tourmanager].[dbo].[V_Operator_Info] - where OPI_SN=? and LGC_LGC=? "; - return $this->HT->query($sql, array($OPI_SN, $lgc))->row(); + $advisor_signature = $this->get_advisor_signature($COLI_SN); + if (empty($advisor_signature)) { + $sql = "SELECT OPI_SN, '+86-'+OPI_MoveTelephone mobile,'+86-773-'+OPI_Telephone tel,OPI_Email email,OPI2_Name fullname,OPI2_FirstName,OPI2_LastName + FROM [Tourmanager].[dbo].[V_Operator_Info] + where OPI_SN=? and LGC_LGC=? "; + $advisor_signature = $this->HT->query($sql, array($OPI_SN, $lgc))->row(); + } + return $advisor_signature; + } + public function get_advisor_signature($COLI_SN) + { + $sql = "SELECT top 1 dbo.agenter_user.Name fullname, dbo.agenter_user.tel, + dbo.agenter_user.Email email, dbo.agenter_user.mobile, OPI_DEI_SN, COLI_OPI_ID + FROM dbo.BIZ_ConfirmLineInfo + INNER JOIN dbo.agenter_user ON dbo.BIZ_ConfirmLineInfo.COLI_OPI_ID = dbo.agenter_user.AU_OPI_SN + AND + (dbo.BIZ_ConfirmLineInfo.COLI_WebCode = dbo.agenter_user.agenter + OR (COLI_WebCode in ('EXPCH','MESENLLA','traba','wayaway','guias') and agenter='VAC') + ) + LEFT JOIN OperatorInfo on COLI_OPI_ID = OPI_SN + WHERE (dbo.BIZ_ConfirmLineInfo.COLI_SN = ?)"; + return $this->HT->query($sql, array($COLI_SN))->row(); } public function get_customer_detail($COLI_SN, $ordertype) diff --git a/webht/third_party/paypal/views/refund_buyer.php b/webht/third_party/paypal/views/refund_buyer.php index 4624db39..a4b05563 100644 --- a/webht/third_party/paypal/views/refund_buyer.php +++ b/webht/third_party/paypal/views/refund_buyer.php @@ -34,10 +34,10 @@ <pre style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:13px;"> Best Regards! -<?php echo $advisor_detail->OPI2_Name ?>, Travel Advisor<br> -Tel: +86-773-<?php echo $advisor_detail->OPI_Telephone ?> Mobile: +86-<?php echo $advisor_detail->OPI_MoveTelephone ?><br> -E-mail: <?php echo $advisor_detail->OPI_Email ?><br> -<?php echo $site; ?><br> +<?php echo $advisor_detail->fullname ?>, Travel Advisor<br> +Tel: <?php echo $advisor_detail->tel ?> Mobile: <?php echo $advisor_detail->mobile ?><br> +E-mail: <?php echo $advisor_detail->email ?><br> +<?php if(isset($site)) { echo $site . '<br>'; } ?> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China </pre> </div> From 11f9e9967f1892c4af69bd37c0f2836abd460565 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 May 2019 10:02:17 +0800 Subject: [PATCH 315/382] =?UTF-8?q?paypal=20=E6=94=B6=E6=AC=BE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5:=E9=82=AE=E4=BB=B6=E4=B8=8D=E9=87=8D=E5=A4=8D?= =?UTF-8?q?=E5=8F=91;=20=E5=95=86=E6=97=85=E6=96=B0=E5=A2=9E=E7=9A=84CHTAP?= =?UTF-8?q?P-biz=E9=9C=80=E4=B8=8EAPP=E7=BB=84=E7=9A=84=E8=AE=A2=E5=8D=95?= =?UTF-8?q?=E5=8C=BA=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 9569c86f..08bd185b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -828,7 +828,7 @@ class Index extends CI_Controller { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 - if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") !== '-biz') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); if ($advisor_info->COLI_WebCode == 'CHTAPP' && $advisor_info->COLI_State == 11) { //只修改APP组的订单状态,并且订单进度是我的订单 $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 8); //把订单状态改为已付款 @@ -869,20 +869,21 @@ class Index extends CI_Controller { //添加邮件发送记录 - //给外联发送通知邮件 - $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; - $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; - $toName = !empty($opi_firstname) ? $opi_firstname : ''; - $toEmail = !empty($opi_email) ? $opi_email : ''; - $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; - $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; - $M_RelatedInfo = $item->pn_sn; - $M_AddTime = $item->pn_payment_date; - $M_State = 0; - $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); - //添加邮件发送记录 end - - $this->Note_model->update_send($item->pn_txn_id, 'send'); + if ($item->pn_send !== 'send') { + //给外联发送通知邮件 + $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; + $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; + $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $M_RelatedInfo = $item->pn_sn; + $M_AddTime = $item->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + //添加邮件发送记录 end + $this->Note_model->update_send($item->pn_txn_id, 'send'); + } } //echo 'done!'; } From 7d9d6fa57fdadc1f9f929063a3831bc484d6808b Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 8 May 2019 11:10:33 +0800 Subject: [PATCH 316/382] =?UTF-8?q?TA=E9=87=87=E9=9B=86=E5=92=8C=E7=9F=AD?= =?UTF-8?q?=E4=BF=A1=E8=AE=A1=E8=B4=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../controllers/PHPExcel.php | 1153 +++ .../controllers/PHPExcel/Autoloader.php | 81 + .../PHPExcel/CachedObjectStorage/APC.php | 290 + .../CachedObjectStorage/CacheBase.php | 368 + .../PHPExcel/CachedObjectStorage/DiscISAM.php | 208 + .../PHPExcel/CachedObjectStorage/ICache.php | 103 + .../PHPExcel/CachedObjectStorage/Igbinary.php | 149 + .../PHPExcel/CachedObjectStorage/Memcache.php | 308 + .../PHPExcel/CachedObjectStorage/Memory.php | 118 + .../CachedObjectStorage/MemoryGZip.php | 133 + .../CachedObjectStorage/MemorySerialized.php | 129 + .../PHPExcel/CachedObjectStorage/PHPTemp.php | 200 + .../PHPExcel/CachedObjectStorage/SQLite.php | 307 + .../PHPExcel/CachedObjectStorage/SQLite3.php | 346 + .../PHPExcel/CachedObjectStorage/Wincache.php | 289 + .../PHPExcel/CachedObjectStorageFactory.php | 231 + .../CalcEngine/CyclicReferenceStack.php | 94 + .../PHPExcel/CalcEngine/Logger.php | 151 + .../controllers/PHPExcel/Calculation.php | 4391 ++++++++++ .../PHPExcel/Calculation/Database.php | 676 ++ .../PHPExcel/Calculation/DateTime.php | 1553 ++++ .../PHPExcel/Calculation/Engineering.php | 2650 ++++++ .../PHPExcel/Calculation/Exception.php | 46 + .../PHPExcel/Calculation/ExceptionHandler.php | 45 + .../PHPExcel/Calculation/Financial.php | 2359 +++++ .../PHPExcel/Calculation/FormulaParser.php | 622 ++ .../PHPExcel/Calculation/FormulaToken.php | 176 + .../PHPExcel/Calculation/Function.php | 148 + .../PHPExcel/Calculation/Functions.php | 760 ++ .../PHPExcel/Calculation/Logical.php | 285 + .../PHPExcel/Calculation/LookupRef.php | 879 ++ .../PHPExcel/Calculation/MathTrig.php | 1459 ++++ .../PHPExcel/Calculation/Statistical.php | 3745 ++++++++ .../PHPExcel/Calculation/TextData.php | 651 ++ .../PHPExcel/Calculation/Token/Stack.php | 111 + .../PHPExcel/Calculation/functionlist.txt | 351 + .../controllers/PHPExcel/Cell.php | 1032 +++ .../PHPExcel/Cell/AdvancedValueBinder.php | 187 + .../controllers/PHPExcel/Cell/DataType.php | 115 + .../PHPExcel/Cell/DataValidation.php | 492 ++ .../PHPExcel/Cell/DefaultValueBinder.php | 102 + .../controllers/PHPExcel/Cell/Hyperlink.php | 124 + .../PHPExcel/Cell/IValueBinder.php | 47 + .../controllers/PHPExcel/Chart.php | 680 ++ .../controllers/PHPExcel/Chart/Axis.php | 561 ++ .../controllers/PHPExcel/Chart/DataSeries.php | 390 + .../PHPExcel/Chart/DataSeriesValues.php | 333 + .../controllers/PHPExcel/Chart/Exception.php | 46 + .../controllers/PHPExcel/Chart/GridLines.php | 472 + .../controllers/PHPExcel/Chart/Layout.php | 486 ++ .../controllers/PHPExcel/Chart/Legend.php | 170 + .../controllers/PHPExcel/Chart/PlotArea.php | 126 + .../controllers/PHPExcel/Chart/Properties.php | 363 + .../Chart/Renderer/PHP Charting Libraries.txt | 20 + .../PHPExcel/Chart/Renderer/jpgraph.php | 883 ++ .../controllers/PHPExcel/Chart/Title.php | 86 + .../controllers/PHPExcel/Comment.php | 338 + .../PHPExcel/DocumentProperties.php | 611 ++ .../controllers/PHPExcel/DocumentSecurity.php | 222 + .../controllers/PHPExcel/Exception.php | 54 + .../controllers/PHPExcel/HashTable.php | 204 + .../controllers/PHPExcel/Helper/HTML.php | 808 ++ .../controllers/PHPExcel/IComparable.php | 34 + .../controllers/PHPExcel/IOFactory.php | 289 + .../controllers/PHPExcel/NamedRange.php | 249 + .../controllers/PHPExcel/Reader/Abstract.php | 289 + .../controllers/PHPExcel/Reader/CSV.php | 406 + .../PHPExcel/Reader/DefaultReadFilter.php | 51 + .../PHPExcel/Reader/Excel2003XML.php | 801 ++ .../controllers/PHPExcel/Reader/Excel2007.php | 2051 +++++ .../PHPExcel/Reader/Excel2007/Chart.php | 520 ++ .../PHPExcel/Reader/Excel2007/Theme.php | 127 + .../controllers/PHPExcel/Reader/Excel5.php | 7594 +++++++++++++++++ .../PHPExcel/Reader/Excel5/Color.php | 32 + .../PHPExcel/Reader/Excel5/Color/BIFF5.php | 77 + .../PHPExcel/Reader/Excel5/Color/BIFF8.php | 77 + .../PHPExcel/Reader/Excel5/Color/BuiltIn.php | 31 + .../PHPExcel/Reader/Excel5/ErrorCode.php | 28 + .../PHPExcel/Reader/Excel5/Escher.php | 669 ++ .../PHPExcel/Reader/Excel5/MD5.php | 203 + .../PHPExcel/Reader/Excel5/RC4.php | 81 + .../PHPExcel/Reader/Excel5/Style/Border.php | 36 + .../Reader/Excel5/Style/FillPattern.php | 41 + .../controllers/PHPExcel/Reader/Exception.php | 46 + .../controllers/PHPExcel/Reader/Gnumeric.php | 850 ++ .../controllers/PHPExcel/Reader/HTML.php | 549 ++ .../PHPExcel/Reader/IReadFilter.php | 39 + .../controllers/PHPExcel/Reader/IReader.php | 46 + .../controllers/PHPExcel/Reader/OOCalc.php | 696 ++ .../controllers/PHPExcel/Reader/SYLK.php | 478 ++ .../controllers/PHPExcel/ReferenceHelper.php | 913 ++ .../controllers/PHPExcel/RichText.php | 191 + .../PHPExcel/RichText/ITextElement.php | 56 + .../controllers/PHPExcel/RichText/Run.php | 98 + .../PHPExcel/RichText/TextElement.php | 105 + .../controllers/PHPExcel/Settings.php | 389 + .../controllers/PHPExcel/Shared/CodePage.php | 156 + .../controllers/PHPExcel/Shared/Date.php | 418 + .../controllers/PHPExcel/Shared/Drawing.php | 270 + .../controllers/PHPExcel/Shared/Escher.php | 83 + .../PHPExcel/Shared/Escher/DgContainer.php | 75 + .../Escher/DgContainer/SpgrContainer.php | 102 + .../DgContainer/SpgrContainer/SpContainer.php | 388 + .../PHPExcel/Shared/Escher/DggContainer.php | 196 + .../Escher/DggContainer/BstoreContainer.php | 57 + .../DggContainer/BstoreContainer/BSE.php | 112 + .../DggContainer/BstoreContainer/BSE/Blip.php | 83 + .../controllers/PHPExcel/Shared/Excel5.php | 298 + .../controllers/PHPExcel/Shared/File.php | 180 + .../controllers/PHPExcel/Shared/Font.php | 741 ++ .../PHPExcel/Shared/JAMA/CHANGELOG.TXT | 16 + .../Shared/JAMA/CholeskyDecomposition.php | 148 + .../Shared/JAMA/EigenvalueDecomposition.php | 864 ++ .../PHPExcel/Shared/JAMA/LUDecomposition.php | 257 + .../PHPExcel/Shared/JAMA/Matrix.php | 1159 +++ .../PHPExcel/Shared/JAMA/QRDecomposition.php | 235 + .../JAMA/SingularValueDecomposition.php | 528 ++ .../PHPExcel/Shared/JAMA/utils/Error.php | 83 + .../PHPExcel/Shared/JAMA/utils/Maths.php | 44 + .../controllers/PHPExcel/Shared/OLE.php | 526 ++ .../Shared/OLE/ChainedBlockStream.php | 206 + .../controllers/PHPExcel/Shared/OLE/PPS.php | 230 + .../PHPExcel/Shared/OLE/PPS/File.php | 74 + .../PHPExcel/Shared/OLE/PPS/Root.php | 462 + .../controllers/PHPExcel/Shared/OLERead.php | 318 + .../PHPExcel/Shared/PCLZip/gnu-lgpl.txt | 504 ++ .../PHPExcel/Shared/PCLZip/pclzip.lib.php | 5173 +++++++++++ .../PHPExcel/Shared/PCLZip/readme.txt | 421 + .../PHPExcel/Shared/PasswordHasher.php | 67 + .../controllers/PHPExcel/Shared/String.php | 819 ++ .../controllers/PHPExcel/Shared/TimeZone.php | 144 + .../controllers/PHPExcel/Shared/XMLWriter.php | 124 + .../PHPExcel/Shared/ZipArchive.php | 163 + .../PHPExcel/Shared/ZipStreamWrapper.php | 200 + .../PHPExcel/Shared/trend/bestFitClass.php | 425 + .../Shared/trend/exponentialBestFitClass.php | 138 + .../Shared/trend/linearBestFitClass.php | 102 + .../Shared/trend/logarithmicBestFitClass.php | 110 + .../Shared/trend/polynomialBestFitClass.php | 222 + .../Shared/trend/powerBestFitClass.php | 138 + .../PHPExcel/Shared/trend/trendClass.php | 147 + .../controllers/PHPExcel/Style.php | 644 ++ .../controllers/PHPExcel/Style/Alignment.php | 464 + .../controllers/PHPExcel/Style/Border.php | 282 + .../controllers/PHPExcel/Style/Borders.php | 429 + .../controllers/PHPExcel/Style/Color.php | 443 + .../PHPExcel/Style/Conditional.php | 293 + .../controllers/PHPExcel/Style/Fill.php | 322 + .../controllers/PHPExcel/Style/Font.php | 543 ++ .../PHPExcel/Style/NumberFormat.php | 751 ++ .../controllers/PHPExcel/Style/Protection.php | 204 + .../controllers/PHPExcel/Style/Supervisor.php | 125 + .../controllers/PHPExcel/Worksheet.php | 2968 +++++++ .../PHPExcel/Worksheet/AutoFilter.php | 846 ++ .../PHPExcel/Worksheet/AutoFilter/Column.php | 405 + .../Worksheet/AutoFilter/Column/Rule.php | 468 + .../PHPExcel/Worksheet/BaseDrawing.php | 507 ++ .../PHPExcel/Worksheet/CellIterator.php | 88 + .../controllers/PHPExcel/Worksheet/Column.php | 86 + .../PHPExcel/Worksheet/ColumnCellIterator.php | 216 + .../PHPExcel/Worksheet/ColumnDimension.php | 132 + .../PHPExcel/Worksheet/ColumnIterator.php | 201 + .../PHPExcel/Worksheet/Dimension.php | 178 + .../PHPExcel/Worksheet/Drawing.php | 147 + .../PHPExcel/Worksheet/Drawing/Shadow.php | 296 + .../PHPExcel/Worksheet/HeaderFooter.php | 494 ++ .../Worksheet/HeaderFooterDrawing.php | 361 + .../PHPExcel/Worksheet/MemoryDrawing.php | 201 + .../PHPExcel/Worksheet/PageMargins.php | 233 + .../PHPExcel/Worksheet/PageSetup.php | 839 ++ .../PHPExcel/Worksheet/Protection.php | 581 ++ .../controllers/PHPExcel/Worksheet/Row.php | 86 + .../PHPExcel/Worksheet/RowCellIterator.php | 225 + .../PHPExcel/Worksheet/RowDimension.php | 132 + .../PHPExcel/Worksheet/RowIterator.php | 192 + .../PHPExcel/Worksheet/SheetView.php | 187 + .../PHPExcel/WorksheetIterator.php | 108 + .../controllers/PHPExcel/Writer/Abstract.php | 157 + .../controllers/PHPExcel/Writer/CSV.php | 352 + .../controllers/PHPExcel/Writer/Excel2007.php | 533 ++ .../PHPExcel/Writer/Excel2007/Chart.php | 1520 ++++ .../PHPExcel/Writer/Excel2007/Comments.php | 260 + .../Writer/Excel2007/ContentTypes.php | 240 + .../PHPExcel/Writer/Excel2007/DocProps.php | 262 + .../PHPExcel/Writer/Excel2007/Drawing.php | 589 ++ .../PHPExcel/Writer/Excel2007/Rels.php | 424 + .../PHPExcel/Writer/Excel2007/RelsRibbon.php | 67 + .../PHPExcel/Writer/Excel2007/RelsVBA.php | 63 + .../PHPExcel/Writer/Excel2007/StringTable.php | 313 + .../PHPExcel/Writer/Excel2007/Style.php | 696 ++ .../PHPExcel/Writer/Excel2007/Theme.php | 869 ++ .../PHPExcel/Writer/Excel2007/Workbook.php | 448 + .../PHPExcel/Writer/Excel2007/Worksheet.php | 1219 +++ .../PHPExcel/Writer/Excel2007/WriterPart.php | 75 + .../controllers/PHPExcel/Writer/Excel5.php | 904 ++ .../PHPExcel/Writer/Excel5/BIFFwriter.php | 246 + .../PHPExcel/Writer/Excel5/Escher.php | 523 ++ .../PHPExcel/Writer/Excel5/Font.php | 166 + .../PHPExcel/Writer/Excel5/Parser.php | 1531 ++++ .../PHPExcel/Writer/Excel5/Workbook.php | 1444 ++++ .../PHPExcel/Writer/Excel5/Worksheet.php | 4240 +++++++++ .../controllers/PHPExcel/Writer/Excel5/Xf.php | 557 ++ .../controllers/PHPExcel/Writer/Exception.php | 46 + .../controllers/PHPExcel/Writer/HTML.php | 1612 ++++ .../controllers/PHPExcel/Writer/IWriter.php | 37 + .../PHPExcel/Writer/OpenDocument.php | 190 + .../Writer/OpenDocument/Cell/Comment.php | 63 + .../PHPExcel/Writer/OpenDocument/Content.php | 272 + .../PHPExcel/Writer/OpenDocument/Meta.php | 95 + .../PHPExcel/Writer/OpenDocument/MetaInf.php | 87 + .../PHPExcel/Writer/OpenDocument/Mimetype.php | 41 + .../PHPExcel/Writer/OpenDocument/Settings.php | 76 + .../PHPExcel/Writer/OpenDocument/Styles.php | 92 + .../Writer/OpenDocument/Thumbnails.php | 41 + .../Writer/OpenDocument/WriterPart.php | 30 + .../controllers/PHPExcel/Writer/PDF.php | 89 + .../controllers/PHPExcel/Writer/PDF/Core.php | 355 + .../PHPExcel/Writer/PDF/DomPDF.php | 108 + .../controllers/PHPExcel/Writer/PDF/mPDF.php | 118 + .../controllers/PHPExcel/Writer/PDF/tcPDF.php | 123 + .../controllers/PHPExcel/locale/bg/config | 49 + .../controllers/PHPExcel/locale/cs/config | 47 + .../controllers/PHPExcel/locale/cs/functions | 438 + .../controllers/PHPExcel/locale/da/config | 48 + .../controllers/PHPExcel/locale/da/functions | 438 + .../controllers/PHPExcel/locale/de/config | 47 + .../controllers/PHPExcel/locale/de/functions | 438 + .../controllers/PHPExcel/locale/en/uk/config | 32 + .../controllers/PHPExcel/locale/es/config | 47 + .../controllers/PHPExcel/locale/es/functions | 438 + .../controllers/PHPExcel/locale/fi/config | 47 + .../controllers/PHPExcel/locale/fi/functions | 438 + .../controllers/PHPExcel/locale/fr/config | 47 + .../controllers/PHPExcel/locale/fr/functions | 438 + .../controllers/PHPExcel/locale/hu/config | 47 + .../controllers/PHPExcel/locale/hu/functions | 438 + .../controllers/PHPExcel/locale/it/config | 47 + .../controllers/PHPExcel/locale/it/functions | 438 + .../controllers/PHPExcel/locale/nl/config | 47 + .../controllers/PHPExcel/locale/nl/functions | 438 + .../controllers/PHPExcel/locale/no/config | 47 + .../controllers/PHPExcel/locale/no/functions | 438 + .../controllers/PHPExcel/locale/pl/config | 47 + .../controllers/PHPExcel/locale/pl/functions | 438 + .../controllers/PHPExcel/locale/pt/br/config | 47 + .../PHPExcel/locale/pt/br/functions | 408 + .../controllers/PHPExcel/locale/pt/config | 47 + .../controllers/PHPExcel/locale/pt/functions | 408 + .../controllers/PHPExcel/locale/ru/config | 47 + .../controllers/PHPExcel/locale/ru/functions | 438 + .../controllers/PHPExcel/locale/sv/config | 47 + .../controllers/PHPExcel/locale/sv/functions | 408 + .../controllers/PHPExcel/locale/tr/config | 47 + .../controllers/PHPExcel/locale/tr/functions | 438 + .../views/third_party_input.php | 157 + .../messagecenter/controllers/index.php | 53 +- .../models/messagecenter_model.php | 20 + .../messagecenter/views/message_index.php | 54 +- 258 files changed, 113741 insertions(+), 10 deletions(-) create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Autoloader.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/APC.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/CacheBase.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/DiscISAM.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/ICache.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Igbinary.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memcache.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memory.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemoryGZip.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemorySerialized.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/PHPTemp.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite3.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Wincache.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorageFactory.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/CyclicReferenceStack.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/Logger.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Database.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/DateTime.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Engineering.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Exception.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/ExceptionHandler.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Financial.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaParser.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaToken.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Function.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Functions.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Logical.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/LookupRef.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/MathTrig.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Statistical.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/TextData.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Token/Stack.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/functionlist.txt create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/AdvancedValueBinder.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataType.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataValidation.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DefaultValueBinder.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/Hyperlink.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/IValueBinder.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Axis.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeries.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeriesValues.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Exception.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/GridLines.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Layout.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Legend.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/PlotArea.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Properties.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/jpgraph.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Title.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Comment.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentProperties.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentSecurity.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Exception.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/HashTable.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Helper/HTML.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/IComparable.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/IOFactory.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/NamedRange.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Abstract.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/CSV.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/DefaultReadFilter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2003XML.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Chart.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Theme.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF5.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF8.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BuiltIn.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/ErrorCode.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Escher.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/MD5.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/RC4.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/Border.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/FillPattern.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Exception.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Gnumeric.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/HTML.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReadFilter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReader.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/OOCalc.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/SYLK.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/ReferenceHelper.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/ITextElement.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/Run.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/TextElement.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Settings.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/CodePage.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Date.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Drawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Excel5.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/File.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Font.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CHANGELOG.TXT create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CholeskyDecomposition.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/LUDecomposition.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/Matrix.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/QRDecomposition.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/SingularValueDecomposition.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Error.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Maths.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/ChainedBlockStream.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/File.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/Root.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLERead.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/gnu-lgpl.txt create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/pclzip.lib.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/readme.txt create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PasswordHasher.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/String.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/TimeZone.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/XMLWriter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipArchive.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipStreamWrapper.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/bestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/exponentialBestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/linearBestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/logarithmicBestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/polynomialBestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/powerBestFitClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/trendClass.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Alignment.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Border.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Borders.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Color.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Conditional.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Fill.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Font.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/NumberFormat.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Protection.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Supervisor.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column/Rule.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/BaseDrawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/CellIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Column.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnCellIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnDimension.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Dimension.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing/Shadow.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooterDrawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/MemoryDrawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageMargins.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageSetup.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Protection.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Row.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowCellIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowDimension.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/SheetView.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/WorksheetIterator.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Abstract.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/CSV.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Chart.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Comments.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/ContentTypes.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/DocProps.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Drawing.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Rels.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsRibbon.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsVBA.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/StringTable.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Style.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Theme.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Workbook.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Worksheet.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/WriterPart.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/BIFFwriter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Escher.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Font.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Parser.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Workbook.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Worksheet.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Xf.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Exception.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/HTML.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/IWriter.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Cell/Comment.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Content.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Meta.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/MetaInf.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Mimetype.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Settings.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Styles.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Thumbnails.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/WriterPart.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/Core.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/DomPDF.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/mPDF.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/tcPDF.php create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/bg/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/en/uk/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/functions create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/config create mode 100644 application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/functions create mode 100644 application/third_party/tripadvisor_spider/views/third_party_input.php create mode 100644 webht/third_party/messagecenter/models/messagecenter_model.php diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel.php new file mode 100644 index 00000000..b8dbe0ef --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel.php @@ -0,0 +1,1153 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel +{ + /** + * Unique ID + * + * @var string + */ + private $uniqueID; + + /** + * Document properties + * + * @var PHPExcel_DocumentProperties + */ + private $properties; + + /** + * Document security + * + * @var PHPExcel_DocumentSecurity + */ + private $security; + + /** + * Collection of Worksheet objects + * + * @var PHPExcel_Worksheet[] + */ + private $workSheetCollection = array(); + + /** + * Calculation Engine + * + * @var PHPExcel_Calculation + */ + private $calculationEngine; + + /** + * Active sheet index + * + * @var integer + */ + private $activeSheetIndex = 0; + + /** + * Named ranges + * + * @var PHPExcel_NamedRange[] + */ + private $namedRanges = array(); + + /** + * CellXf supervisor + * + * @var PHPExcel_Style + */ + private $cellXfSupervisor; + + /** + * CellXf collection + * + * @var PHPExcel_Style[] + */ + private $cellXfCollection = array(); + + /** + * CellStyleXf collection + * + * @var PHPExcel_Style[] + */ + private $cellStyleXfCollection = array(); + + /** + * hasMacros : this workbook have macros ? + * + * @var bool + */ + private $hasMacros = false; + + /** + * macrosCode : all macros code (the vbaProject.bin file, this include form, code, etc.), null if no macro + * + * @var binary + */ + private $macrosCode; + /** + * macrosCertificate : if macros are signed, contains vbaProjectSignature.bin file, null if not signed + * + * @var binary + */ + private $macrosCertificate; + + /** + * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI + * + * @var null|string + */ + private $ribbonXMLData; + + /** + * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements + * ignored if $ribbonXMLData is null + * + * @var null|array + */ + private $ribbonBinObjects; + + /** + * The workbook has macros ? + * + * @return boolean true if workbook has macros, false if not + */ + public function hasMacros() + { + return $this->hasMacros; + } + + /** + * Define if a workbook has macros + * + * @param boolean $hasMacros true|false + */ + public function setHasMacros($hasMacros = false) + { + $this->hasMacros = (bool) $hasMacros; + } + + /** + * Set the macros code + * + * @param string $MacrosCode string|null + */ + public function setMacrosCode($MacrosCode = null) + { + $this->macrosCode=$MacrosCode; + $this->setHasMacros(!is_null($MacrosCode)); + } + + /** + * Return the macros code + * + * @return string|null + */ + public function getMacrosCode() + { + return $this->macrosCode; + } + + /** + * Set the macros certificate + * + * @param string|null $Certificate + */ + public function setMacrosCertificate($Certificate = null) + { + $this->macrosCertificate=$Certificate; + } + + /** + * Is the project signed ? + * + * @return boolean true|false + */ + public function hasMacrosCertificate() + { + return !is_null($this->macrosCertificate); + } + + /** + * Return the macros certificate + * + * @return string|null + */ + public function getMacrosCertificate() + { + return $this->macrosCertificate; + } + + /** + * Remove all macros, certificate from spreadsheet + * + */ + public function discardMacros() + { + $this->hasMacros=false; + $this->macrosCode=null; + $this->macrosCertificate=null; + } + + /** + * set ribbon XML data + * + */ + public function setRibbonXMLData($Target = null, $XMLData = null) + { + if (!is_null($Target) && !is_null($XMLData)) { + $this->ribbonXMLData = array('target' => $Target, 'data' => $XMLData); + } else { + $this->ribbonXMLData = null; + } + } + + /** + * retrieve ribbon XML Data + * + * return string|null|array + */ + public function getRibbonXMLData($What = 'all') //we need some constants here... + { + $ReturnData = null; + $What = strtolower($What); + switch ($What){ + case 'all': + $ReturnData = $this->ribbonXMLData; + break; + case 'target': + case 'data': + if (is_array($this->ribbonXMLData) && array_key_exists($What, $this->ribbonXMLData)) { + $ReturnData = $this->ribbonXMLData[$What]; + } + break; + } + + return $ReturnData; + } + + /** + * store binaries ribbon objects (pictures) + * + */ + public function setRibbonBinObjects($BinObjectsNames = null, $BinObjectsData = null) + { + if (!is_null($BinObjectsNames) && !is_null($BinObjectsData)) { + $this->ribbonBinObjects = array('names' => $BinObjectsNames, 'data' => $BinObjectsData); + } else { + $this->ribbonBinObjects = null; + } + } + /** + * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function) + * + */ + private function getExtensionOnly($ThePath) + { + return pathinfo($ThePath, PATHINFO_EXTENSION); + } + + /** + * retrieve Binaries Ribbon Objects + * + */ + public function getRibbonBinObjects($What = 'all') + { + $ReturnData = null; + $What = strtolower($What); + switch($What) { + case 'all': + return $this->ribbonBinObjects; + break; + case 'names': + case 'data': + if (is_array($this->ribbonBinObjects) && array_key_exists($What, $this->ribbonBinObjects)) { + $ReturnData=$this->ribbonBinObjects[$What]; + } + break; + case 'types': + if (is_array($this->ribbonBinObjects) && + array_key_exists('data', $this->ribbonBinObjects) && is_array($this->ribbonBinObjects['data'])) { + $tmpTypes=array_keys($this->ribbonBinObjects['data']); + $ReturnData = array_unique(array_map(array($this, 'getExtensionOnly'), $tmpTypes)); + } else { + $ReturnData=array(); // the caller want an array... not null if empty + } + break; + } + return $ReturnData; + } + + /** + * This workbook have a custom UI ? + * + * @return boolean true|false + */ + public function hasRibbon() + { + return !is_null($this->ribbonXMLData); + } + + /** + * This workbook have additionnal object for the ribbon ? + * + * @return boolean true|false + */ + public function hasRibbonBinObjects() + { + return !is_null($this->ribbonBinObjects); + } + + /** + * Check if a sheet with a specified code name already exists + * + * @param string $pSheetCodeName Name of the worksheet to check + * @return boolean + */ + public function sheetCodeNameExists($pSheetCodeName) + { + return ($this->getSheetByCodeName($pSheetCodeName) !== null); + } + + /** + * Get sheet by code name. Warning : sheet don't have always a code name ! + * + * @param string $pName Sheet name + * @return PHPExcel_Worksheet + */ + public function getSheetByCodeName($pName = '') + { + $worksheetCount = count($this->workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + if ($this->workSheetCollection[$i]->getCodeName() == $pName) { + return $this->workSheetCollection[$i]; + } + } + + return null; + } + + /** + * Create a new PHPExcel with one Worksheet + */ + public function __construct() + { + $this->uniqueID = uniqid(); + $this->calculationEngine = new PHPExcel_Calculation($this); + + // Initialise worksheet collection and add one worksheet + $this->workSheetCollection = array(); + $this->workSheetCollection[] = new PHPExcel_Worksheet($this); + $this->activeSheetIndex = 0; + + // Create document properties + $this->properties = new PHPExcel_DocumentProperties(); + + // Create document security + $this->security = new PHPExcel_DocumentSecurity(); + + // Set named ranges + $this->namedRanges = array(); + + // Create the cellXf supervisor + $this->cellXfSupervisor = new PHPExcel_Style(true); + $this->cellXfSupervisor->bindParent($this); + + // Create the default style + $this->addCellXf(new PHPExcel_Style); + $this->addCellStyleXf(new PHPExcel_Style); + } + + /** + * Code to execute when this worksheet is unset() + * + */ + public function __destruct() + { + $this->calculationEngine = null; + $this->disconnectWorksheets(); + } + + /** + * Disconnect all worksheets from this PHPExcel workbook object, + * typically so that the PHPExcel object can be unset + * + */ + public function disconnectWorksheets() + { + $worksheet = null; + foreach ($this->workSheetCollection as $k => &$worksheet) { + $worksheet->disconnectCells(); + $this->workSheetCollection[$k] = null; + } + unset($worksheet); + $this->workSheetCollection = array(); + } + + /** + * Return the calculation engine for this worksheet + * + * @return PHPExcel_Calculation + */ + public function getCalculationEngine() + { + return $this->calculationEngine; + } // function getCellCacheController() + + /** + * Get properties + * + * @return PHPExcel_DocumentProperties + */ + public function getProperties() + { + return $this->properties; + } + + /** + * Set properties + * + * @param PHPExcel_DocumentProperties $pValue + */ + public function setProperties(PHPExcel_DocumentProperties $pValue) + { + $this->properties = $pValue; + } + + /** + * Get security + * + * @return PHPExcel_DocumentSecurity + */ + public function getSecurity() + { + return $this->security; + } + + /** + * Set security + * + * @param PHPExcel_DocumentSecurity $pValue + */ + public function setSecurity(PHPExcel_DocumentSecurity $pValue) + { + $this->security = $pValue; + } + + /** + * Get active sheet + * + * @return PHPExcel_Worksheet + * + * @throws PHPExcel_Exception + */ + public function getActiveSheet() + { + return $this->getSheet($this->activeSheetIndex); + } + + /** + * Create sheet and add it to this workbook + * + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function createSheet($iSheetIndex = null) + { + $newSheet = new PHPExcel_Worksheet($this); + $this->addSheet($newSheet, $iSheetIndex); + return $newSheet; + } + + /** + * Check if a sheet with a specified name already exists + * + * @param string $pSheetName Name of the worksheet to check + * @return boolean + */ + public function sheetNameExists($pSheetName) + { + return ($this->getSheetByName($pSheetName) !== null); + } + + /** + * Add sheet + * + * @param PHPExcel_Worksheet $pSheet + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function addSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) + { + if ($this->sheetNameExists($pSheet->getTitle())) { + throw new PHPExcel_Exception( + "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first." + ); + } + + if ($iSheetIndex === null) { + if ($this->activeSheetIndex < 0) { + $this->activeSheetIndex = 0; + } + $this->workSheetCollection[] = $pSheet; + } else { + // Insert the sheet at the requested index + array_splice( + $this->workSheetCollection, + $iSheetIndex, + 0, + array($pSheet) + ); + + // Adjust active sheet index if necessary + if ($this->activeSheetIndex >= $iSheetIndex) { + ++$this->activeSheetIndex; + } + } + + if ($pSheet->getParent() === null) { + $pSheet->rebindParent($this); + } + + return $pSheet; + } + + /** + * Remove sheet by index + * + * @param int $pIndex Active sheet index + * @throws PHPExcel_Exception + */ + public function removeSheetByIndex($pIndex = 0) + { + + $numSheets = count($this->workSheetCollection); + if ($pIndex > $numSheets - 1) { + throw new PHPExcel_Exception( + "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + ); + } else { + array_splice($this->workSheetCollection, $pIndex, 1); + } + // Adjust active sheet index if necessary + if (($this->activeSheetIndex >= $pIndex) && + ($pIndex > count($this->workSheetCollection) - 1)) { + --$this->activeSheetIndex; + } + + } + + /** + * Get sheet by index + * + * @param int $pIndex Sheet index + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function getSheet($pIndex = 0) + { + if (!isset($this->workSheetCollection[$pIndex])) { + $numSheets = $this->getSheetCount(); + throw new PHPExcel_Exception( + "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}." + ); + } + + return $this->workSheetCollection[$pIndex]; + } + + /** + * Get all sheets + * + * @return PHPExcel_Worksheet[] + */ + public function getAllSheets() + { + return $this->workSheetCollection; + } + + /** + * Get sheet by name + * + * @param string $pName Sheet name + * @return PHPExcel_Worksheet + */ + public function getSheetByName($pName = '') + { + $worksheetCount = count($this->workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + if ($this->workSheetCollection[$i]->getTitle() === $pName) { + return $this->workSheetCollection[$i]; + } + } + + return null; + } + + /** + * Get index for sheet + * + * @param PHPExcel_Worksheet $pSheet + * @return int Sheet index + * @throws PHPExcel_Exception + */ + public function getIndex(PHPExcel_Worksheet $pSheet) + { + foreach ($this->workSheetCollection as $key => $value) { + if ($value->getHashCode() == $pSheet->getHashCode()) { + return $key; + } + } + + throw new PHPExcel_Exception("Sheet does not exist."); + } + + /** + * Set index for sheet by sheet name. + * + * @param string $sheetName Sheet name to modify index for + * @param int $newIndex New index for the sheet + * @return int New sheet index + * @throws PHPExcel_Exception + */ + public function setIndexByName($sheetName, $newIndex) + { + $oldIndex = $this->getIndex($this->getSheetByName($sheetName)); + $pSheet = array_splice( + $this->workSheetCollection, + $oldIndex, + 1 + ); + array_splice( + $this->workSheetCollection, + $newIndex, + 0, + $pSheet + ); + return $newIndex; + } + + /** + * Get sheet count + * + * @return int + */ + public function getSheetCount() + { + return count($this->workSheetCollection); + } + + /** + * Get active sheet index + * + * @return int Active sheet index + */ + public function getActiveSheetIndex() + { + return $this->activeSheetIndex; + } + + /** + * Set active sheet index + * + * @param int $pIndex Active sheet index + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setActiveSheetIndex($pIndex = 0) + { + $numSheets = count($this->workSheetCollection); + + if ($pIndex > $numSheets - 1) { + throw new PHPExcel_Exception( + "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}." + ); + } else { + $this->activeSheetIndex = $pIndex; + } + return $this->getActiveSheet(); + } + + /** + * Set active sheet index by name + * + * @param string $pValue Sheet title + * @return PHPExcel_Worksheet + * @throws PHPExcel_Exception + */ + public function setActiveSheetIndexByName($pValue = '') + { + if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) { + $this->setActiveSheetIndex($this->getIndex($worksheet)); + return $worksheet; + } + + throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue); + } + + /** + * Get sheet names + * + * @return string[] + */ + public function getSheetNames() + { + $returnValue = array(); + $worksheetCount = $this->getSheetCount(); + for ($i = 0; $i < $worksheetCount; ++$i) { + $returnValue[] = $this->getSheet($i)->getTitle(); + } + + return $returnValue; + } + + /** + * Add external sheet + * + * @param PHPExcel_Worksheet $pSheet External sheet to add + * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null) + { + if ($this->sheetNameExists($pSheet->getTitle())) { + throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first."); + } + + // count how many cellXfs there are in this workbook currently, we will need this below + $countCellXfs = count($this->cellXfCollection); + + // copy all the shared cellXfs from the external workbook and append them to the current + foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) { + $this->addCellXf(clone $cellXf); + } + + // move sheet to this workbook + $pSheet->rebindParent($this); + + // update the cellXfs + foreach ($pSheet->getCellCollection(false) as $cellID) { + $cell = $pSheet->getCell($cellID); + $cell->setXfIndex($cell->getXfIndex() + $countCellXfs); + } + + return $this->addSheet($pSheet, $iSheetIndex); + } + + /** + * Get named ranges + * + * @return PHPExcel_NamedRange[] + */ + public function getNamedRanges() + { + return $this->namedRanges; + } + + /** + * Add named range + * + * @param PHPExcel_NamedRange $namedRange + * @return boolean + */ + public function addNamedRange(PHPExcel_NamedRange $namedRange) + { + if ($namedRange->getScope() == null) { + // global scope + $this->namedRanges[$namedRange->getName()] = $namedRange; + } else { + // local scope + $this->namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange; + } + return true; + } + + /** + * Get named range + * + * @param string $namedRange + * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope + * @return PHPExcel_NamedRange|null + */ + public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) + { + $returnValue = null; + + if ($namedRange != '' && ($namedRange !== null)) { + // first look for global defined name + if (isset($this->namedRanges[$namedRange])) { + $returnValue = $this->namedRanges[$namedRange]; + } + + // then look for local defined name (has priority over global defined name if both names exist) + if (($pSheet !== null) && isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { + $returnValue = $this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]; + } + } + + return $returnValue; + } + + /** + * Remove named range + * + * @param string $namedRange + * @param PHPExcel_Worksheet|null $pSheet Scope: use null for global scope. + * @return PHPExcel + */ + public function removeNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null) + { + if ($pSheet === null) { + if (isset($this->namedRanges[$namedRange])) { + unset($this->namedRanges[$namedRange]); + } + } else { + if (isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) { + unset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]); + } + } + return $this; + } + + /** + * Get worksheet iterator + * + * @return PHPExcel_WorksheetIterator + */ + public function getWorksheetIterator() + { + return new PHPExcel_WorksheetIterator($this); + } + + /** + * Copy workbook (!= clone!) + * + * @return PHPExcel + */ + public function copy() + { + $copied = clone $this; + + $worksheetCount = count($this->workSheetCollection); + for ($i = 0; $i < $worksheetCount; ++$i) { + $this->workSheetCollection[$i] = $this->workSheetCollection[$i]->copy(); + $this->workSheetCollection[$i]->rebindParent($this); + } + + return $copied; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + foreach ($this as $key => $val) { + if (is_object($val) || (is_array($val))) { + $this->{$key} = unserialize(serialize($val)); + } + } + } + + /** + * Get the workbook collection of cellXfs + * + * @return PHPExcel_Style[] + */ + public function getCellXfCollection() + { + return $this->cellXfCollection; + } + + /** + * Get cellXf by index + * + * @param int $pIndex + * @return PHPExcel_Style + */ + public function getCellXfByIndex($pIndex = 0) + { + return $this->cellXfCollection[$pIndex]; + } + + /** + * Get cellXf by hash code + * + * @param string $pValue + * @return PHPExcel_Style|boolean False if no match found + */ + public function getCellXfByHashCode($pValue = '') + { + foreach ($this->cellXfCollection as $cellXf) { + if ($cellXf->getHashCode() == $pValue) { + return $cellXf; + } + } + return false; + } + + /** + * Check if style exists in style collection + * + * @param PHPExcel_Style $pCellStyle + * @return boolean + */ + public function cellXfExists($pCellStyle = null) + { + return in_array($pCellStyle, $this->cellXfCollection, true); + } + + /** + * Get default style + * + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getDefaultStyle() + { + if (isset($this->cellXfCollection[0])) { + return $this->cellXfCollection[0]; + } + throw new PHPExcel_Exception('No default style found for this workbook'); + } + + /** + * Add a cellXf to the workbook + * + * @param PHPExcel_Style $style + */ + public function addCellXf(PHPExcel_Style $style) + { + $this->cellXfCollection[] = $style; + $style->setIndex(count($this->cellXfCollection) - 1); + } + + /** + * Remove cellXf by index. It is ensured that all cells get their xf index updated. + * + * @param integer $pIndex Index to cellXf + * @throws PHPExcel_Exception + */ + public function removeCellXfByIndex($pIndex = 0) + { + if ($pIndex > count($this->cellXfCollection) - 1) { + throw new PHPExcel_Exception("CellXf index is out of bounds."); + } else { + // first remove the cellXf + array_splice($this->cellXfCollection, $pIndex, 1); + + // then update cellXf indexes for cells + foreach ($this->workSheetCollection as $worksheet) { + foreach ($worksheet->getCellCollection(false) as $cellID) { + $cell = $worksheet->getCell($cellID); + $xfIndex = $cell->getXfIndex(); + if ($xfIndex > $pIndex) { + // decrease xf index by 1 + $cell->setXfIndex($xfIndex - 1); + } elseif ($xfIndex == $pIndex) { + // set to default xf index 0 + $cell->setXfIndex(0); + } + } + } + } + } + + /** + * Get the cellXf supervisor + * + * @return PHPExcel_Style + */ + public function getCellXfSupervisor() + { + return $this->cellXfSupervisor; + } + + /** + * Get the workbook collection of cellStyleXfs + * + * @return PHPExcel_Style[] + */ + public function getCellStyleXfCollection() + { + return $this->cellStyleXfCollection; + } + + /** + * Get cellStyleXf by index + * + * @param integer $pIndex Index to cellXf + * @return PHPExcel_Style + */ + public function getCellStyleXfByIndex($pIndex = 0) + { + return $this->cellStyleXfCollection[$pIndex]; + } + + /** + * Get cellStyleXf by hash code + * + * @param string $pValue + * @return PHPExcel_Style|boolean False if no match found + */ + public function getCellStyleXfByHashCode($pValue = '') + { + foreach ($this->cellStyleXfCollection as $cellStyleXf) { + if ($cellStyleXf->getHashCode() == $pValue) { + return $cellStyleXf; + } + } + return false; + } + + /** + * Add a cellStyleXf to the workbook + * + * @param PHPExcel_Style $pStyle + */ + public function addCellStyleXf(PHPExcel_Style $pStyle) + { + $this->cellStyleXfCollection[] = $pStyle; + $pStyle->setIndex(count($this->cellStyleXfCollection) - 1); + } + + /** + * Remove cellStyleXf by index + * + * @param integer $pIndex Index to cellXf + * @throws PHPExcel_Exception + */ + public function removeCellStyleXfByIndex($pIndex = 0) + { + if ($pIndex > count($this->cellStyleXfCollection) - 1) { + throw new PHPExcel_Exception("CellStyleXf index is out of bounds."); + } else { + array_splice($this->cellStyleXfCollection, $pIndex, 1); + } + } + + /** + * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells + * and columns in the workbook + */ + public function garbageCollect() + { + // how many references are there to each cellXf ? + $countReferencesCellXf = array(); + foreach ($this->cellXfCollection as $index => $cellXf) { + $countReferencesCellXf[$index] = 0; + } + + foreach ($this->getWorksheetIterator() as $sheet) { + // from cells + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + ++$countReferencesCellXf[$cell->getXfIndex()]; + } + + // from row dimensions + foreach ($sheet->getRowDimensions() as $rowDimension) { + if ($rowDimension->getXfIndex() !== null) { + ++$countReferencesCellXf[$rowDimension->getXfIndex()]; + } + } + + // from column dimensions + foreach ($sheet->getColumnDimensions() as $columnDimension) { + ++$countReferencesCellXf[$columnDimension->getXfIndex()]; + } + } + + // remove cellXfs without references and create mapping so we can update xfIndex + // for all cells and columns + $countNeededCellXfs = 0; + $map = array(); + foreach ($this->cellXfCollection as $index => $cellXf) { + if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf + ++$countNeededCellXfs; + } else { + unset($this->cellXfCollection[$index]); + } + $map[$index] = $countNeededCellXfs - 1; + } + $this->cellXfCollection = array_values($this->cellXfCollection); + + // update the index for all cellXfs + foreach ($this->cellXfCollection as $i => $cellXf) { + $cellXf->setIndex($i); + } + + // make sure there is always at least one cellXf (there should be) + if (empty($this->cellXfCollection)) { + $this->cellXfCollection[] = new PHPExcel_Style(); + } + + // update the xfIndex for all cells, row dimensions, column dimensions + foreach ($this->getWorksheetIterator() as $sheet) { + // for all cells + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + $cell->setXfIndex($map[$cell->getXfIndex()]); + } + + // for all row dimensions + foreach ($sheet->getRowDimensions() as $rowDimension) { + if ($rowDimension->getXfIndex() !== null) { + $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]); + } + } + + // for all column dimensions + foreach ($sheet->getColumnDimensions() as $columnDimension) { + $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]); + } + + // also do garbage collection for all the sheets + $sheet->garbageCollect(); + } + } + + /** + * Return the unique ID value assigned to this spreadsheet workbook + * + * @return string + */ + public function getID() + { + return $this->uniqueID; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Autoloader.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Autoloader.php new file mode 100644 index 00000000..c3b95a20 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Autoloader.php @@ -0,0 +1,81 @@ +<?php + +PHPExcel_Autoloader::register(); +// As we always try to run the autoloader before anything else, we can use it to do a few +// simple checks and initialisations +//PHPExcel_Shared_ZipStreamWrapper::register(); +// check mbstring.func_overload +if (ini_get('mbstring.func_overload') & 2) { + throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).'); +} +PHPExcel_Shared_String::buildCharacterSets(); + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Autoloader +{ + /** + * Register the Autoloader with SPL + * + */ + public static function register() + { + if (function_exists('__autoload')) { + // Register any existing autoloader function with SPL, so we don't get any clashes + spl_autoload_register('__autoload'); + } + // Register ourselves with SPL + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true); + } else { + return spl_autoload_register(array('PHPExcel_Autoloader', 'load')); + } + } + + /** + * Autoload a class identified by name + * + * @param string $pClassName Name of the object to load + */ + public static function load($pClassName) + { + if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) { + // Either already loaded, or not a PHPExcel class request + return false; + } + + $pClassFilePath = PHPEXCEL_ROOT . + str_replace('_', DIRECTORY_SEPARATOR, $pClassName) . + '.php'; + + if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) { + // Can't load + return false; + } + + require($pClassFilePath); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/APC.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/APC.php new file mode 100644 index 00000000..c74b07fe --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/APC.php @@ -0,0 +1,290 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_APC + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_APC extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Prefix used to uniquely identify cache data for this worksheet + * + * @access private + * @var string + */ + private $cachePrefix = null; + + /** + * Cache timeout + * + * @access private + * @var integer + */ + private $cacheTime = 600; + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @access private + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + if (!apc_store( + $this->cachePrefix . $this->currentObjectID . '.cache', + serialize($this->currentObject), + $this->cacheTime + )) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell ' . $this->currentObjectID . ' in APC'); + } + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @access public + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + $this->cellCache[$pCoord] = true; + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @access public + * @param string $pCoord Coordinate address of the cell to check + * @throws PHPExcel_Exception + * @return boolean + */ + public function isDataSet($pCoord) + { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in apc + $success = apc_fetch($this->cachePrefix.$pCoord.'.cache'); + if ($success === false) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); + } + return true; + } + return false; + } + + /** + * Get cell at a specific coordinate + * + * @access public + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (parent::isDataSet($pCoord)) { + $obj = apc_fetch($this->cachePrefix . $pCoord . '.cache'); + if ($obj === false) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache'); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @access public + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + // Delete the entry from APC + apc_delete($this->cachePrefix.$pCoord.'.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } + + /** + * Clone the cell collection + * + * @access public + * @param PHPExcel_Worksheet $parent The new worksheet + * @throws PHPExcel_Exception + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->getUniqueID(); + $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.'; + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + if ($cellID != $this->currentObjectID) { + $obj = apc_fetch($this->cachePrefix . $cellID . '.cache'); + if ($obj === false) { + // Entry no longer exists in APC, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception('Cell entry ' . $cellID . ' no longer exists in APC'); + } + if (!apc_store($newCachePrefix . $cellID . '.cache', $obj, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell ' . $cellID . ' in APC'); + } + } + } + $this->cachePrefix = $newCachePrefix; + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if ($this->currentObject !== null) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + + // Flush the APC cache + $this->__destruct(); + + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) + { + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if ($this->cachePrefix === null) { + $baseUnique = $this->getUniqueID(); + $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.'; + $this->cacheTime = $cacheTime; + + parent::__construct($parent); + } + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + apc_delete($this->cachePrefix . $cellID . '.cache'); + } + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!function_exists('apc_store')) { + return false; + } + if (apc_sma_info() === false) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/CacheBase.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/CacheBase.php new file mode 100644 index 00000000..9a12ec86 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/CacheBase.php @@ -0,0 +1,368 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_CacheBase + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_CachedObjectStorage_CacheBase +{ + /** + * Parent worksheet + * + * @var PHPExcel_Worksheet + */ + protected $parent; + + /** + * The currently active Cell + * + * @var PHPExcel_Cell + */ + protected $currentObject = null; + + /** + * Coordinate address of the currently active Cell + * + * @var string + */ + protected $currentObjectID = null; + + /** + * Flag indicating whether the currently active Cell requires saving + * + * @var boolean + */ + protected $currentCellIsDirty = true; + + /** + * An array of cells or cell pointers for the worksheet cells held in this cache, + * and indexed by their coordinate address within the worksheet + * + * @var array of mixed + */ + protected $cellCache = array(); + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + */ + public function __construct(PHPExcel_Worksheet $parent) + { + // Set our parent worksheet. + // This is maintained within the cache controller to facilitate re-attaching it to PHPExcel_Cell objects when + // they are woken from a serialized state + $this->parent = $parent; + } + + /** + * Return the parent worksheet for this cell collection + * + * @return PHPExcel_Worksheet + */ + public function getParent() + { + return $this->parent; + } + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return true; + } + // Check if the requested entry exists in the cache + return isset($this->cellCache[$pCoord]); + } + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) + { + if ($fromAddress === $this->currentObjectID) { + $this->currentObjectID = $toAddress; + } + $this->currentCellIsDirty = true; + if (isset($this->cellCache[$fromAddress])) { + $this->cellCache[$toAddress] = &$this->cellCache[$fromAddress]; + unset($this->cellCache[$fromAddress]); + } + + return true; + } + + /** + * Add or Update a cell in cache + * + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function updateCacheData(PHPExcel_Cell $cell) + { + return $this->addCacheData($cell->getCoordinate(), $cell); + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID && !is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObjectID = $this->currentObject = null; + } + + if (is_object($this->cellCache[$pCoord])) { + $this->cellCache[$pCoord]->detach(); + unset($this->cellCache[$pCoord]); + } + $this->currentCellIsDirty = false; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + return array_keys($this->cellCache); + } + + /** + * Sort the list of all cell addresses currently held in cache by row and column + * + * @return string[] + */ + public function getSortedCellList() + { + $sortKeys = array(); + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $column, $row); + $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord; + } + ksort($sortKeys); + + return array_values($sortKeys); + } + + /** + * Get highest worksheet column and highest row that have cell records + * + * @return array Highest column name and highest row number + */ + public function getHighestRowAndColumn() + { + // Lookup highest column and highest row + $col = array('A' => '1A'); + $row = array(1); + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $c, $r); + $row[$r] = $r; + $col[$c] = strlen($c).$c; + } + if (!empty($row)) { + // Determine highest column and row + $highestRow = max($row); + $highestColumn = substr(max($col), 1); + } + + return array( + 'row' => $highestRow, + 'column' => $highestColumn + ); + } + + /** + * Return the cell address of the currently active cell object + * + * @return string + */ + public function getCurrentAddress() + { + return $this->currentObjectID; + } + + /** + * Return the column address of the currently active cell object + * + * @return string + */ + public function getCurrentColumn() + { + sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); + return $column; + } + + /** + * Return the row address of the currently active cell object + * + * @return integer + */ + public function getCurrentRow() + { + sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row); + return (integer) $row; + } + + /** + * Get highest worksheet column + * + * @param string $row Return the highest column for the specified row, + * or the highest column of any row if no row number is passed + * @return string Highest column name + */ + public function getHighestColumn($row = null) + { + if ($row == null) { + $colRow = $this->getHighestRowAndColumn(); + return $colRow['column']; + } + + $columnList = array(1); + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $c, $r); + if ($r != $row) { + continue; + } + $columnList[] = PHPExcel_Cell::columnIndexFromString($c); + } + return PHPExcel_Cell::stringFromColumnIndex(max($columnList) - 1); + } + + /** + * Get highest worksheet row + * + * @param string $column Return the highest row for the specified column, + * or the highest row of any column if no column letter is passed + * @return int Highest row number + */ + public function getHighestRow($column = null) + { + if ($column == null) { + $colRow = $this->getHighestRowAndColumn(); + return $colRow['row']; + } + + $rowList = array(0); + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $c, $r); + if ($c != $column) { + continue; + } + $rowList[] = $r; + } + + return max($rowList); + } + + /** + * Generate a unique ID for cache referencing + * + * @return string Unique Reference + */ + protected function getUniqueID() + { + if (function_exists('posix_getpid')) { + $baseUnique = posix_getpid(); + } else { + $baseUnique = mt_rand(); + } + return uniqid($baseUnique, true); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + $this->currentCellIsDirty; + $this->storeData(); + + $this->parent = $parent; + if (($this->currentObject !== null) && (is_object($this->currentObject))) { + $this->currentObject->attach($this); + } + } // function copyCellCollection() + + /** + * Remove a row, deleting all cells in that row + * + * @param string $row Row number to remove + * @return void + */ + public function removeRow($row) + { + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $c, $r); + if ($r == $row) { + $this->deleteCacheData($coord); + } + } + } + + /** + * Remove a column, deleting all cells in that column + * + * @param string $column Column ID to remove + * @return void + */ + public function removeColumn($column) + { + foreach ($this->getCellList() as $coord) { + sscanf($coord, '%[A-Z]%d', $c, $r); + if ($c == $column) { + $this->deleteCacheData($coord); + } + } + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/DiscISAM.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/DiscISAM.php new file mode 100644 index 00000000..13bc0337 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/DiscISAM.php @@ -0,0 +1,208 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_DiscISAM + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_DiscISAM extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Name of the file for this cache + * + * @var string + */ + private $fileName = null; + + /** + * File handle for this cache file + * + * @var resource + */ + private $fileHandle = null; + + /** + * Directory/Folder where the cache file is located + * + * @var string + */ + private $cacheDirectory = null; + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + fseek($this->fileHandle, 0, SEEK_END); + + $this->cellCache[$this->currentObjectID] = array( + 'ptr' => ftell($this->fileHandle), + 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) + ); + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']); + $this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz'])); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->getUniqueID(); + $newFileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache'; + // Copy the existing cell cache file + copy($this->fileName, $newFileName); + $this->fileName = $newFileName; + // Open the copied cell cache file + $this->fileHandle = fopen($this->fileName, 'a+'); + } + + /** + * Clear the cell collection and disconnect from our parent + * + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) + { + $this->cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== null)) + ? $arguments['dir'] + : PHPExcel_Shared_File::sys_get_temp_dir(); + + parent::__construct($parent); + if (is_null($this->fileHandle)) { + $baseUnique = $this->getUniqueID(); + $this->fileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache'; + $this->fileHandle = fopen($this->fileName, 'a+'); + } + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + if (!is_null($this->fileHandle)) { + fclose($this->fileHandle); + unlink($this->fileName); + } + $this->fileHandle = null; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/ICache.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/ICache.php new file mode 100644 index 00000000..aafef6e9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/ICache.php @@ -0,0 +1,103 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_ICache + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_CachedObjectStorage_ICache +{ + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell); + + /** + * Add or Update a cell in cache + * + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function updateCacheData(PHPExcel_Cell $cell); + + /** + * Fetch a cell from cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to retrieve + * @return PHPExcel_Cell Cell that was found, or null if not found + * @throws PHPExcel_Exception + */ + public function getCacheData($pCoord); + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord); + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord); + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList(); + + /** + * Get the list of all cell addresses currently held in cache sorted by column and row + * + * @return string[] + */ + public function getSortedCellList(); + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent); + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable(); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Igbinary.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Igbinary.php new file mode 100644 index 00000000..5f3527b5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Igbinary.php @@ -0,0 +1,149 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_Igbinary + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_Igbinary extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $this->cellCache[$this->currentObjectID] = igbinary_serialize($this->currentObject); + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = igbinary_unserialize($this->cellCache[$pCoord]); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } // function getCacheData() + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } // function unsetWorksheetCells() + + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!function_exists('igbinary_serialize')) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memcache.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memcache.php new file mode 100644 index 00000000..07942cc3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memcache.php @@ -0,0 +1,308 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_Memcache + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_Memcache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Prefix used to uniquely identify cache data for this worksheet + * + * @var string + */ + private $cachePrefix = null; + + /** + * Cache timeout + * + * @var integer + */ + private $cacheTime = 600; + + /** + * Memcache interface + * + * @var resource + */ + private $memcache = null; + + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $obj = serialize($this->currentObject); + if (!$this->memcache->replace($this->cachePrefix . $this->currentObjectID . '.cache', $obj, null, $this->cacheTime)) { + if (!$this->memcache->add($this->cachePrefix . $this->currentObjectID . '.cache', $obj, null, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception("Failed to store cell {$this->currentObjectID} in MemCache"); + } + } + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } // function _storeData() + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + $this->cellCache[$pCoord] = true; + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } // function addCacheData() + + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + * @return boolean + */ + public function isDataSet($pCoord) + { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in Memcache + $success = $this->memcache->get($this->cachePrefix.$pCoord.'.cache'); + if ($success === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache'); + } + return true; + } + return false; + } + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (parent::isDataSet($pCoord)) { + $obj = $this->memcache->get($this->cachePrefix . $pCoord . '.cache'); + if ($obj === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception("Cell entry {$pCoord} no longer exists in MemCache"); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + // Delete the entry from Memcache + $this->memcache->delete($this->cachePrefix . $pCoord . '.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->getUniqueID(); + $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.'; + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + if ($cellID != $this->currentObjectID) { + $obj = $this->memcache->get($this->cachePrefix.$cellID.'.cache'); + if ($obj === false) { + // Entry no longer exists in Memcache, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception("Cell entry {$cellID} no longer exists in MemCache"); + } + if (!$this->memcache->add($newCachePrefix . $cellID . '.cache', $obj, null, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception("Failed to store cell {$cellID} in MemCache"); + } + } + } + $this->cachePrefix = $newCachePrefix; + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + + // Flush the Memcache cache + $this->__destruct(); + + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) + { + $memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost'; + $memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211; + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if (is_null($this->cachePrefix)) { + $baseUnique = $this->getUniqueID(); + $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.'; + + // Set a new Memcache object and connect to the Memcache server + $this->memcache = new Memcache(); + if (!$this->memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) { + throw new PHPExcel_Exception("Could not connect to MemCache server at {$memcacheServer}:{$memcachePort}"); + } + $this->cacheTime = $cacheTime; + + parent::__construct($parent); + } + } + + /** + * Memcache error handler + * + * @param string $host Memcache server + * @param integer $port Memcache port + * @throws PHPExcel_Exception + */ + public function failureCallback($host, $port) + { + throw new PHPExcel_Exception("memcache {$host}:{$port} failed"); + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + $this->memcache->delete($this->cachePrefix.$cellID . '.cache'); + } + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!function_exists('memcache_add')) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memory.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memory.php new file mode 100644 index 00000000..0e2ea0b0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Memory.php @@ -0,0 +1,118 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_Memory + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_Memory extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Dummy method callable from CacheBase, but unused by Memory cache + * + * @return void + */ + protected function storeData() + { + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + $this->cellCache[$pCoord] = $cell; + + // Set current entry to the new/updated entry + $this->currentObjectID = $pCoord; + + return $cell; + } + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + $this->currentObjectID = null; + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + + // Return requested entry + return $this->cellCache[$pCoord]; + } + + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + + $newCollection = array(); + foreach ($this->cellCache as $k => &$cell) { + $newCollection[$k] = clone $cell; + $newCollection[$k]->attach($this); + } + + $this->cellCache = $newCollection; + } + + /** + * Clear the cell collection and disconnect from our parent + * + */ + public function unsetWorksheetCells() + { + // Because cells are all stored as intact objects in memory, we need to detach each one from the parent + foreach ($this->cellCache as $k => &$cell) { + $cell->detach(); + $this->cellCache[$k] = null; + } + unset($cell); + + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemoryGZip.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemoryGZip.php new file mode 100644 index 00000000..c06ec714 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemoryGZip.php @@ -0,0 +1,133 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_MemoryGZip + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_MemoryGZip extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $this->cellCache[$this->currentObjectID] = gzdeflate(serialize($this->currentObject)); + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = unserialize(gzinflate($this->cellCache[$pCoord])); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemorySerialized.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemorySerialized.php new file mode 100644 index 00000000..13325149 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/MemorySerialized.php @@ -0,0 +1,129 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_MemorySerialized + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_MemorySerialized extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $this->cellCache[$this->currentObjectID] = serialize($this->currentObject); + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = unserialize($this->cellCache[$pCoord]); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/PHPTemp.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/PHPTemp.php new file mode 100644 index 00000000..43c78197 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/PHPTemp.php @@ -0,0 +1,200 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_PHPTemp + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_PHPTemp extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Name of the file for this cache + * + * @var string + */ + private $fileHandle = null; + + /** + * Memory limit to use before reverting to file cache + * + * @var integer + */ + private $memoryCacheSize = null; + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + fseek($this->fileHandle, 0, SEEK_END); + + $this->cellCache[$this->currentObjectID] = array( + 'ptr' => ftell($this->fileHandle), + 'sz' => fwrite($this->fileHandle, serialize($this->currentObject)) + ); + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + if (!isset($this->cellCache[$pCoord])) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']); + $this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz'])); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + // Open a new stream for the cell cache data + $newFileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+'); + // Copy the existing cell cache data to the new stream + fseek($this->fileHandle, 0); + while (!feof($this->fileHandle)) { + fwrite($newFileHandle, fread($this->fileHandle, 1024)); + } + $this->fileHandle = $newFileHandle; + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + + // Close down the php://temp file + $this->__destruct(); + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) + { + $this->memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB'; + + parent::__construct($parent); + if (is_null($this->fileHandle)) { + $this->fileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+'); + } + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + if (!is_null($this->fileHandle)) { + fclose($this->fileHandle); + } + $this->fileHandle = null; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite.php new file mode 100644 index 00000000..e7b50c5b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite.php @@ -0,0 +1,307 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_SQLite + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_SQLite extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Database table name + * + * @var string + */ + private $TableName = null; + + /** + * Database handle + * + * @var resource + */ + private $DBHandle = null; + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + if (!$this->DBHandle->queryExec("INSERT OR REPLACE INTO kvp_".$this->TableName." VALUES('".$this->currentObjectID."','".sqlite_escape_string(serialize($this->currentObject))."')")) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + $query = "SELECT value FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; + $cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC); + if ($cellResultSet === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } elseif ($cellResultSet->numRows() == 0) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + + $cellResult = $cellResultSet->fetchSingle(); + $this->currentObject = unserialize($cellResult); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Is a value set for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return true; + } + + // Check if the requested entry exists in the cache + $query = "SELECT id FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; + $cellResultSet = $this->DBHandle->query($query, SQLITE_ASSOC); + if ($cellResultSet === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } elseif ($cellResultSet->numRows() == 0) { + // Return null if requested entry doesn't exist in cache + return false; + } + return true; + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + $this->currentObject->detach(); + $this->currentObjectID = $this->currentObject = null; + } + + // Check if the requested entry exists in the cache + $query = "DELETE FROM kvp_".$this->TableName." WHERE id='".$pCoord."'"; + if (!$this->DBHandle->queryExec($query)) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + + $this->currentCellIsDirty = false; + } + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) + { + if ($fromAddress === $this->currentObjectID) { + $this->currentObjectID = $toAddress; + } + + $query = "DELETE FROM kvp_".$this->TableName." WHERE id='".$toAddress."'"; + $result = $this->DBHandle->exec($query); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + $query = "UPDATE kvp_".$this->TableName." SET id='".$toAddress."' WHERE id='".$fromAddress."'"; + $result = $this->DBHandle->exec($query); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + return true; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + $query = "SELECT id FROM kvp_".$this->TableName; + $cellIdsResult = $this->DBHandle->unbufferedQuery($query, SQLITE_ASSOC); + if ($cellIdsResult === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + + $cellKeys = array(); + foreach ($cellIdsResult as $row) { + $cellKeys[] = $row['id']; + } + + return $cellKeys; + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + $this->currentCellIsDirty; + $this->storeData(); + + // Get a new id for the new table name + $tableName = str_replace('.', '_', $this->getUniqueID()); + if (!$this->DBHandle->queryExec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_'.$this->TableName) + ) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + + // Copy the existing cell cache file + $this->TableName = $tableName; + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + */ + public function __construct(PHPExcel_Worksheet $parent) + { + parent::__construct($parent); + if (is_null($this->DBHandle)) { + $this->TableName = str_replace('.', '_', $this->getUniqueID()); + $_DBName = ':memory:'; + + $this->DBHandle = new SQLiteDatabase($_DBName); + if ($this->DBHandle === false) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + if (!$this->DBHandle->queryExec('CREATE TABLE kvp_'.$this->TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) { + throw new PHPExcel_Exception(sqlite_error_string($this->DBHandle->lastError())); + } + } + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + if (!is_null($this->DBHandle)) { + $this->DBHandle->queryExec('DROP TABLE kvp_'.$this->TableName); + } + $this->DBHandle = null; + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!function_exists('sqlite_open')) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite3.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite3.php new file mode 100644 index 00000000..27473d6c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/SQLite3.php @@ -0,0 +1,346 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_SQLite3 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_SQLite3 extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Database table name + * + * @var string + */ + private $TableName = null; + + /** + * Database handle + * + * @var resource + */ + private $DBHandle = null; + + /** + * Prepared statement for a SQLite3 select query + * + * @var SQLite3Stmt + */ + private $selectQuery; + + /** + * Prepared statement for a SQLite3 insert query + * + * @var SQLite3Stmt + */ + private $insertQuery; + + /** + * Prepared statement for a SQLite3 update query + * + * @var SQLite3Stmt + */ + private $updateQuery; + + /** + * Prepared statement for a SQLite3 delete query + * + * @var SQLite3Stmt + */ + private $deleteQuery; + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $this->insertQuery->bindValue('id', $this->currentObjectID, SQLITE3_TEXT); + $this->insertQuery->bindValue('data', serialize($this->currentObject), SQLITE3_BLOB); + $result = $this->insertQuery->execute(); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + $this->currentCellIsDirty = false; + } + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + $this->selectQuery->bindValue('id', $pCoord, SQLITE3_TEXT); + $cellResult = $this->selectQuery->execute(); + if ($cellResult === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + $cellData = $cellResult->fetchArray(SQLITE3_ASSOC); + if ($cellData === false) { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + + $this->currentObject = unserialize($cellData['value']); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + /** + * Is a value set for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return true; + } + + // Check if the requested entry exists in the cache + $this->selectQuery->bindValue('id', $pCoord, SQLITE3_TEXT); + $cellResult = $this->selectQuery->execute(); + if ($cellResult === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + $cellData = $cellResult->fetchArray(SQLITE3_ASSOC); + + return ($cellData === false) ? false : true; + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + $this->currentObject->detach(); + $this->currentObjectID = $this->currentObject = null; + } + + // Check if the requested entry exists in the cache + $this->deleteQuery->bindValue('id', $pCoord, SQLITE3_TEXT); + $result = $this->deleteQuery->execute(); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + $this->currentCellIsDirty = false; + } + + /** + * Move a cell object from one address to another + * + * @param string $fromAddress Current address of the cell to move + * @param string $toAddress Destination address of the cell to move + * @return boolean + */ + public function moveCell($fromAddress, $toAddress) + { + if ($fromAddress === $this->currentObjectID) { + $this->currentObjectID = $toAddress; + } + + $this->deleteQuery->bindValue('id', $toAddress, SQLITE3_TEXT); + $result = $this->deleteQuery->execute(); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + $this->updateQuery->bindValue('toid', $toAddress, SQLITE3_TEXT); + $this->updateQuery->bindValue('fromid', $fromAddress, SQLITE3_TEXT); + $result = $this->updateQuery->execute(); + if ($result === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + return true; + } + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + $query = "SELECT id FROM kvp_".$this->TableName; + $cellIdsResult = $this->DBHandle->query($query); + if ($cellIdsResult === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + $cellKeys = array(); + while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) { + $cellKeys[] = $row['id']; + } + + return $cellKeys; + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + $this->currentCellIsDirty; + $this->storeData(); + + // Get a new id for the new table name + $tableName = str_replace('.', '_', $this->getUniqueID()); + if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB) + AS SELECT * FROM kvp_'.$this->TableName) + ) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + + // Copy the existing cell cache file + $this->TableName = $tableName; + } + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + + // Close down the temporary cache file + $this->__destruct(); + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + */ + public function __construct(PHPExcel_Worksheet $parent) + { + parent::__construct($parent); + if (is_null($this->DBHandle)) { + $this->TableName = str_replace('.', '_', $this->getUniqueID()); + $_DBName = ':memory:'; + + $this->DBHandle = new SQLite3($_DBName); + if ($this->DBHandle === false) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$this->TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) { + throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg()); + } + } + + $this->selectQuery = $this->DBHandle->prepare("SELECT value FROM kvp_".$this->TableName." WHERE id = :id"); + $this->insertQuery = $this->DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->TableName." VALUES(:id,:data)"); + $this->updateQuery = $this->DBHandle->prepare("UPDATE kvp_".$this->TableName." SET id=:toId WHERE id=:fromId"); + $this->deleteQuery = $this->DBHandle->prepare("DELETE FROM kvp_".$this->TableName." WHERE id = :id"); + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + if (!is_null($this->DBHandle)) { + $this->DBHandle->exec('DROP TABLE kvp_'.$this->TableName); + $this->DBHandle->close(); + } + $this->DBHandle = null; + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!class_exists('SQLite3', false)) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Wincache.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Wincache.php new file mode 100644 index 00000000..1567874f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorage/Wincache.php @@ -0,0 +1,289 @@ +<?php + +/** + * PHPExcel_CachedObjectStorage_Wincache + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorage_Wincache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache +{ + /** + * Prefix used to uniquely identify cache data for this worksheet + * + * @var string + */ + private $cachePrefix = null; + + /** + * Cache timeout + * + * @var integer + */ + private $cacheTime = 600; + + + /** + * Store cell data in cache for the current cell object if it's "dirty", + * and the 'nullify' the current cell object + * + * @return void + * @throws PHPExcel_Exception + */ + protected function storeData() + { + if ($this->currentCellIsDirty && !empty($this->currentObjectID)) { + $this->currentObject->detach(); + + $obj = serialize($this->currentObject); + if (wincache_ucache_exists($this->cachePrefix.$this->currentObjectID.'.cache')) { + if (!wincache_ucache_set($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache'); + } + } else { + if (!wincache_ucache_add($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache'); + } + } + $this->currentCellIsDirty = false; + } + + $this->currentObjectID = $this->currentObject = null; + } + + /** + * Add or Update a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to update + * @param PHPExcel_Cell $cell Cell to update + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function addCacheData($pCoord, PHPExcel_Cell $cell) + { + if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) { + $this->storeData(); + } + $this->cellCache[$pCoord] = true; + + $this->currentObjectID = $pCoord; + $this->currentObject = $cell; + $this->currentCellIsDirty = true; + + return $cell; + } + + /** + * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell? + * + * @param string $pCoord Coordinate address of the cell to check + * @return boolean + */ + public function isDataSet($pCoord) + { + // Check if the requested entry is the current object, or exists in the cache + if (parent::isDataSet($pCoord)) { + if ($this->currentObjectID == $pCoord) { + return true; + } + // Check if the requested entry still exists in cache + $success = wincache_ucache_exists($this->cachePrefix.$pCoord.'.cache'); + if ($success === false) { + // Entry no longer exists in Wincache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); + } + return true; + } + return false; + } + + + /** + * Get cell at a specific coordinate + * + * @param string $pCoord Coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Cell Cell that was found, or null if not found + */ + public function getCacheData($pCoord) + { + if ($pCoord === $this->currentObjectID) { + return $this->currentObject; + } + $this->storeData(); + + // Check if the entry that has been requested actually exists + $obj = null; + if (parent::isDataSet($pCoord)) { + $success = false; + $obj = wincache_ucache_get($this->cachePrefix.$pCoord.'.cache', $success); + if ($success === false) { + // Entry no longer exists in WinCache, so clear it from the cache array + parent::deleteCacheData($pCoord); + throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache'); + } + } else { + // Return null if requested entry doesn't exist in cache + return null; + } + + // Set current entry to the requested entry + $this->currentObjectID = $pCoord; + $this->currentObject = unserialize($obj); + // Re-attach this as the cell's parent + $this->currentObject->attach($this); + + // Return requested entry + return $this->currentObject; + } + + + /** + * Get a list of all cell addresses currently held in cache + * + * @return string[] + */ + public function getCellList() + { + if ($this->currentObjectID !== null) { + $this->storeData(); + } + + return parent::getCellList(); + } + + /** + * Delete a cell in cache identified by coordinate address + * + * @param string $pCoord Coordinate address of the cell to delete + * @throws PHPExcel_Exception + */ + public function deleteCacheData($pCoord) + { + // Delete the entry from Wincache + wincache_ucache_delete($this->cachePrefix.$pCoord.'.cache'); + + // Delete the entry from our cell address array + parent::deleteCacheData($pCoord); + } + + /** + * Clone the cell collection + * + * @param PHPExcel_Worksheet $parent The new worksheet + * @return void + */ + public function copyCellCollection(PHPExcel_Worksheet $parent) + { + parent::copyCellCollection($parent); + // Get a new id for the new file name + $baseUnique = $this->getUniqueID(); + $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.'; + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + if ($cellID != $this->currentObjectID) { + $success = false; + $obj = wincache_ucache_get($this->cachePrefix.$cellID.'.cache', $success); + if ($success === false) { + // Entry no longer exists in WinCache, so clear it from the cache array + parent::deleteCacheData($cellID); + throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in Wincache'); + } + if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->cacheTime)) { + $this->__destruct(); + throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in Wincache'); + } + } + } + $this->cachePrefix = $newCachePrefix; + } + + + /** + * Clear the cell collection and disconnect from our parent + * + * @return void + */ + public function unsetWorksheetCells() + { + if (!is_null($this->currentObject)) { + $this->currentObject->detach(); + $this->currentObject = $this->currentObjectID = null; + } + + // Flush the WinCache cache + $this->__destruct(); + + $this->cellCache = array(); + + // detach ourself from the worksheet, so that it can then delete this object successfully + $this->parent = null; + } + + /** + * Initialise this new cell collection + * + * @param PHPExcel_Worksheet $parent The worksheet for this cell collection + * @param array of mixed $arguments Additional initialisation arguments + */ + public function __construct(PHPExcel_Worksheet $parent, $arguments) + { + $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600; + + if (is_null($this->cachePrefix)) { + $baseUnique = $this->getUniqueID(); + $this->cachePrefix = substr(md5($baseUnique), 0, 8).'.'; + $this->cacheTime = $cacheTime; + + parent::__construct($parent); + } + } + + /** + * Destroy this cell collection + */ + public function __destruct() + { + $cacheList = $this->getCellList(); + foreach ($cacheList as $cellID) { + wincache_ucache_delete($this->cachePrefix.$cellID.'.cache'); + } + } + + /** + * Identify whether the caching method is currently available + * Some methods are dependent on the availability of certain extensions being enabled in the PHP build + * + * @return boolean + */ + public static function cacheMethodIsAvailable() + { + if (!function_exists('wincache_ucache_add')) { + return false; + } + + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorageFactory.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorageFactory.php new file mode 100644 index 00000000..0a969786 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CachedObjectStorageFactory.php @@ -0,0 +1,231 @@ +<?php + +/** + * PHPExcel_CachedObjectStorageFactory + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_CachedObjectStorage + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CachedObjectStorageFactory +{ + const cache_in_memory = 'Memory'; + const cache_in_memory_gzip = 'MemoryGZip'; + const cache_in_memory_serialized = 'MemorySerialized'; + const cache_igbinary = 'Igbinary'; + const cache_to_discISAM = 'DiscISAM'; + const cache_to_apc = 'APC'; + const cache_to_memcache = 'Memcache'; + const cache_to_phpTemp = 'PHPTemp'; + const cache_to_wincache = 'Wincache'; + const cache_to_sqlite = 'SQLite'; + const cache_to_sqlite3 = 'SQLite3'; + + /** + * Name of the method used for cell cacheing + * + * @var string + */ + private static $cacheStorageMethod = null; + + /** + * Name of the class used for cell cacheing + * + * @var string + */ + private static $cacheStorageClass = null; + + /** + * List of all possible cache storage methods + * + * @var string[] + */ + private static $storageMethods = array( + self::cache_in_memory, + self::cache_in_memory_gzip, + self::cache_in_memory_serialized, + self::cache_igbinary, + self::cache_to_phpTemp, + self::cache_to_discISAM, + self::cache_to_apc, + self::cache_to_memcache, + self::cache_to_wincache, + self::cache_to_sqlite, + self::cache_to_sqlite3, + ); + + /** + * Default arguments for each cache storage method + * + * @var array of mixed array + */ + private static $storageMethodDefaultParameters = array( + self::cache_in_memory => array( + ), + self::cache_in_memory_gzip => array( + ), + self::cache_in_memory_serialized => array( + ), + self::cache_igbinary => array( + ), + self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB' + ), + self::cache_to_discISAM => array( 'dir' => null + ), + self::cache_to_apc => array( 'cacheTime' => 600 + ), + self::cache_to_memcache => array( 'memcacheServer' => 'localhost', + 'memcachePort' => 11211, + 'cacheTime' => 600 + ), + self::cache_to_wincache => array( 'cacheTime' => 600 + ), + self::cache_to_sqlite => array( + ), + self::cache_to_sqlite3 => array( + ), + ); + + /** + * Arguments for the active cache storage method + * + * @var array of mixed array + */ + private static $storageMethodParameters = array(); + + /** + * Return the current cache storage method + * + * @return string|null + **/ + public static function getCacheStorageMethod() + { + return self::$cacheStorageMethod; + } + + /** + * Return the current cache storage class + * + * @return PHPExcel_CachedObjectStorage_ICache|null + **/ + public static function getCacheStorageClass() + { + return self::$cacheStorageClass; + } + + /** + * Return the list of all possible cache storage methods + * + * @return string[] + **/ + public static function getAllCacheStorageMethods() + { + return self::$storageMethods; + } + + /** + * Return the list of all available cache storage methods + * + * @return string[] + **/ + public static function getCacheStorageMethods() + { + $activeMethods = array(); + foreach (self::$storageMethods as $storageMethod) { + $cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $storageMethod; + if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) { + $activeMethods[] = $storageMethod; + } + } + return $activeMethods; + } + + /** + * Identify the cache storage method to use + * + * @param string $method Name of the method to use for cell cacheing + * @param array of mixed $arguments Additional arguments to pass to the cell caching class + * when instantiating + * @return boolean + **/ + public static function initialize($method = self::cache_in_memory, $arguments = array()) + { + if (!in_array($method, self::$storageMethods)) { + return false; + } + + $cacheStorageClass = 'PHPExcel_CachedObjectStorage_'.$method; + if (!call_user_func(array( $cacheStorageClass, + 'cacheMethodIsAvailable'))) { + return false; + } + + self::$storageMethodParameters[$method] = self::$storageMethodDefaultParameters[$method]; + foreach ($arguments as $k => $v) { + if (array_key_exists($k, self::$storageMethodParameters[$method])) { + self::$storageMethodParameters[$method][$k] = $v; + } + } + + if (self::$cacheStorageMethod === null) { + self::$cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $method; + self::$cacheStorageMethod = $method; + } + return true; + } + + /** + * Initialise the cache storage + * + * @param PHPExcel_Worksheet $parent Enable cell caching for this worksheet + * @return PHPExcel_CachedObjectStorage_ICache + **/ + public static function getInstance(PHPExcel_Worksheet $parent) + { + $cacheMethodIsAvailable = true; + if (self::$cacheStorageMethod === null) { + $cacheMethodIsAvailable = self::initialize(); + } + + if ($cacheMethodIsAvailable) { + $instance = new self::$cacheStorageClass( + $parent, + self::$storageMethodParameters[self::$cacheStorageMethod] + ); + if ($instance !== null) { + return $instance; + } + } + + return false; + } + + /** + * Clear the cache storage + * + **/ + public static function finalize() + { + self::$cacheStorageMethod = null; + self::$cacheStorageClass = null; + self::$storageMethodParameters = array(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/CyclicReferenceStack.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/CyclicReferenceStack.php new file mode 100644 index 00000000..1072fc75 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/CyclicReferenceStack.php @@ -0,0 +1,94 @@ +<?php + +/** + * PHPExcel_CalcEngine_CyclicReferenceStack + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CalcEngine_CyclicReferenceStack +{ + /** + * The call stack for calculated cells + * + * @var mixed[] + */ + private $stack = array(); + + /** + * Return the number of entries on the stack + * + * @return integer + */ + public function count() + { + return count($this->stack); + } + + /** + * Push a new entry onto the stack + * + * @param mixed $value + */ + public function push($value) + { + $this->stack[$value] = $value; + } + + /** + * Pop the last entry from the stack + * + * @return mixed + */ + public function pop() + { + return array_pop($this->stack); + } + + /** + * Test to see if a specified entry exists on the stack + * + * @param mixed $value The value to test + */ + public function onStack($value) + { + return isset($this->stack[$value]); + } + + /** + * Clear the stack + */ + public function clear() + { + $this->stack = array(); + } + + /** + * Return an array of all entries on the stack + * + * @return mixed[] + */ + public function showStack() + { + return $this->stack; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/Logger.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/Logger.php new file mode 100644 index 00000000..c5ffe73e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/CalcEngine/Logger.php @@ -0,0 +1,151 @@ +<?php + +/** + * PHPExcel_CalcEngine_Logger + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_CalcEngine_Logger +{ + /** + * Flag to determine whether a debug log should be generated by the calculation engine + * If true, then a debug log will be generated + * If false, then a debug log will not be generated + * + * @var boolean + */ + private $writeDebugLog = false; + + /** + * Flag to determine whether a debug log should be echoed by the calculation engine + * If true, then a debug log will be echoed + * If false, then a debug log will not be echoed + * A debug log can only be echoed if it is generated + * + * @var boolean + */ + private $echoDebugLog = false; + + /** + * The debug log generated by the calculation engine + * + * @var string[] + */ + private $debugLog = array(); + + /** + * The calculation engine cell reference stack + * + * @var PHPExcel_CalcEngine_CyclicReferenceStack + */ + private $cellStack; + + /** + * Instantiate a Calculation engine logger + * + * @param PHPExcel_CalcEngine_CyclicReferenceStack $stack + */ + public function __construct(PHPExcel_CalcEngine_CyclicReferenceStack $stack) + { + $this->cellStack = $stack; + } + + /** + * Enable/Disable Calculation engine logging + * + * @param boolean $pValue + */ + public function setWriteDebugLog($pValue = false) + { + $this->writeDebugLog = $pValue; + } + + /** + * Return whether calculation engine logging is enabled or disabled + * + * @return boolean + */ + public function getWriteDebugLog() + { + return $this->writeDebugLog; + } + + /** + * Enable/Disable echoing of debug log information + * + * @param boolean $pValue + */ + public function setEchoDebugLog($pValue = false) + { + $this->echoDebugLog = $pValue; + } + + /** + * Return whether echoing of debug log information is enabled or disabled + * + * @return boolean + */ + public function getEchoDebugLog() + { + return $this->echoDebugLog; + } + + /** + * Write an entry to the calculation engine debug log + */ + public function writeDebugLog() + { + // Only write the debug log if logging is enabled + if ($this->writeDebugLog) { + $message = implode(func_get_args()); + $cellReference = implode(' -> ', $this->cellStack->showStack()); + if ($this->echoDebugLog) { + echo $cellReference, + ($this->cellStack->count() > 0 ? ' => ' : ''), + $message, + PHP_EOL; + } + $this->debugLog[] = $cellReference . + ($this->cellStack->count() > 0 ? ' => ' : '') . + $message; + } + } + + /** + * Clear the calculation engine debug log + */ + public function clearLog() + { + $this->debugLog = array(); + } + + /** + * Return the calculation engine debug log + * + * @return string[] + */ + public function getLog() + { + return $this->debugLog; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation.php new file mode 100644 index 00000000..20b1ec3f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation.php @@ -0,0 +1,4391 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +if (!defined('CALCULATION_REGEXP_CELLREF')) { + // Test for support of \P (multibyte options) in PCRE + if (defined('PREG_BAD_UTF8_ERROR')) { + // Cell reference (cell or range of cells, with or without a sheet reference) + define('CALCULATION_REGEXP_CELLREF', '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})'); + // Named Range of cells + define('CALCULATION_REGEXP_NAMEDRANGE', '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)'); + } else { + // Cell reference (cell or range of cells, with or without a sheet reference) + define('CALCULATION_REGEXP_CELLREF', '(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)'); + // Named Range of cells + define('CALCULATION_REGEXP_NAMEDRANGE', '(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)'); + } +} + +/** + * PHPExcel_Calculation (Multiton) + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation +{ + /** Constants */ + /** Regular Expressions */ + // Numeric operand + const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?'; + // String operand + const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"'; + // Opening bracket + const CALCULATION_REGEXP_OPENBRACE = '\('; + // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it) + const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\('; + // Cell reference (cell or range of cells, with or without a sheet reference) + const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF; + // Named Range of cells + const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE; + // Error + const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?'; + + + /** constants */ + const RETURN_ARRAY_AS_ERROR = 'error'; + const RETURN_ARRAY_AS_VALUE = 'value'; + const RETURN_ARRAY_AS_ARRAY = 'array'; + + private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE; + + + /** + * Instance of this class + * + * @access private + * @var PHPExcel_Calculation + */ + private static $instance; + + + /** + * Instance of the workbook this Calculation Engine is using + * + * @access private + * @var PHPExcel + */ + private $workbook; + + /** + * List of instances of the calculation engine that we've instantiated for individual workbooks + * + * @access private + * @var PHPExcel_Calculation[] + */ + private static $workbookSets; + + /** + * Calculation cache + * + * @access private + * @var array + */ + private $calculationCache = array (); + + + /** + * Calculation cache enabled + * + * @access private + * @var boolean + */ + private $calculationCacheEnabled = true; + + + /** + * List of operators that can be used within formulae + * The true/false value indicates whether it is a binary operator or a unary operator + * + * @access private + * @var array + */ + private static $operators = array( + '+' => true, '-' => true, '*' => true, '/' => true, + '^' => true, '&' => true, '%' => false, '~' => false, + '>' => true, '<' => true, '=' => true, '>=' => true, + '<=' => true, '<>' => true, '|' => true, ':' => true + ); + + /** + * List of binary operators (those that expect two operands) + * + * @access private + * @var array + */ + private static $binaryOperators = array( + '+' => true, '-' => true, '*' => true, '/' => true, + '^' => true, '&' => true, '>' => true, '<' => true, + '=' => true, '>=' => true, '<=' => true, '<>' => true, + '|' => true, ':' => true + ); + + /** + * The debug log generated by the calculation engine + * + * @access private + * @var PHPExcel_CalcEngine_Logger + * + */ + private $debugLog; + + /** + * Flag to determine how formula errors should be handled + * If true, then a user error will be triggered + * If false, then an exception will be thrown + * + * @access public + * @var boolean + * + */ + public $suppressFormulaErrors = false; + + /** + * Error message for any error that was raised/thrown by the calculation engine + * + * @access public + * @var string + * + */ + public $formulaError = null; + + /** + * An array of the nested cell references accessed by the calculation engine, used for the debug log + * + * @access private + * @var array of string + * + */ + private $cyclicReferenceStack; + + private $cellStack = array(); + + /** + * Current iteration counter for cyclic formulae + * If the value is 0 (or less) then cyclic formulae will throw an exception, + * otherwise they will iterate to the limit defined here before returning a result + * + * @var integer + * + */ + private $cyclicFormulaCounter = 1; + + private $cyclicFormulaCell = ''; + + /** + * Number of iterations for cyclic formulae + * + * @var integer + * + */ + public $cyclicFormulaCount = 1; + + /** + * Epsilon Precision used for comparisons in calculations + * + * @var float + * + */ + private $delta = 0.1e-12; + + + /** + * The current locale setting + * + * @var string + * + */ + private static $localeLanguage = 'en_us'; // US English (default locale) + + /** + * List of available locale settings + * Note that this is read for the locale subdirectory only when requested + * + * @var string[] + * + */ + private static $validLocaleLanguages = array( + 'en' // English (default language) + ); + + /** + * Locale-specific argument separator for function arguments + * + * @var string + * + */ + private static $localeArgumentSeparator = ','; + private static $localeFunctions = array(); + + /** + * Locale-specific translations for Excel constants (True, False and Null) + * + * @var string[] + * + */ + public static $localeBoolean = array( + 'TRUE' => 'TRUE', + 'FALSE' => 'FALSE', + 'NULL' => 'NULL' + ); + + /** + * Excel constant string translations to their PHP equivalents + * Constant conversion from text name/value to actual (datatyped) value + * + * @var string[] + * + */ + private static $excelConstants = array( + 'TRUE' => true, + 'FALSE' => false, + 'NULL' => null + ); + + // PHPExcel functions + private static $PHPExcelFunctions = array( + 'ABS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'abs', + 'argumentCount' => '1' + ), + 'ACCRINT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINT', + 'argumentCount' => '4-7' + ), + 'ACCRINTM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINTM', + 'argumentCount' => '3-5' + ), + 'ACOS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'acos', + 'argumentCount' => '1' + ), + 'ACOSH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'acosh', + 'argumentCount' => '1' + ), + 'ADDRESS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::CELL_ADDRESS', + 'argumentCount' => '2-5' + ), + 'AMORDEGRC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::AMORDEGRC', + 'argumentCount' => '6,7' + ), + 'AMORLINC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::AMORLINC', + 'argumentCount' => '6,7' + ), + 'AND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_AND', + 'argumentCount' => '1+' + ), + 'AREAS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ASC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ASIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'asin', + 'argumentCount' => '1' + ), + 'ASINH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'asinh', + 'argumentCount' => '1' + ), + 'ATAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'atan', + 'argumentCount' => '1' + ), + 'ATAN2' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ATAN2', + 'argumentCount' => '2' + ), + 'ATANH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'atanh', + 'argumentCount' => '1' + ), + 'AVEDEV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVEDEV', + 'argumentCount' => '1+' + ), + 'AVERAGE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGE', + 'argumentCount' => '1+' + ), + 'AVERAGEA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEA', + 'argumentCount' => '1+' + ), + 'AVERAGEIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEIF', + 'argumentCount' => '2,3' + ), + 'AVERAGEIFS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3+' + ), + 'BAHTTEXT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'BESSELI' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELI', + 'argumentCount' => '2' + ), + 'BESSELJ' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELJ', + 'argumentCount' => '2' + ), + 'BESSELK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELK', + 'argumentCount' => '2' + ), + 'BESSELY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELY', + 'argumentCount' => '2' + ), + 'BETADIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BETADIST', + 'argumentCount' => '3-5' + ), + 'BETAINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BETAINV', + 'argumentCount' => '3-5' + ), + 'BIN2DEC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTODEC', + 'argumentCount' => '1' + ), + 'BIN2HEX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOHEX', + 'argumentCount' => '1,2' + ), + 'BIN2OCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOOCT', + 'argumentCount' => '1,2' + ), + 'BINOMDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::BINOMDIST', + 'argumentCount' => '4' + ), + 'CEILING' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::CEILING', + 'argumentCount' => '2' + ), + 'CELL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1,2' + ), + 'CHAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::CHARACTER', + 'argumentCount' => '1' + ), + 'CHIDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIDIST', + 'argumentCount' => '2' + ), + 'CHIINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIINV', + 'argumentCount' => '2' + ), + 'CHITEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'CHOOSE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::CHOOSE', + 'argumentCount' => '2+' + ), + 'CLEAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMNONPRINTABLE', + 'argumentCount' => '1' + ), + 'CODE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::ASCIICODE', + 'argumentCount' => '1' + ), + 'COLUMN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMN', + 'argumentCount' => '-1', + 'passByReference' => array(true) + ), + 'COLUMNS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMNS', + 'argumentCount' => '1' + ), + 'COMBIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::COMBIN', + 'argumentCount' => '2' + ), + 'COMPLEX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::COMPLEX', + 'argumentCount' => '2,3' + ), + 'CONCATENATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::CONCATENATE', + 'argumentCount' => '1+' + ), + 'CONFIDENCE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CONFIDENCE', + 'argumentCount' => '3' + ), + 'CONVERT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::CONVERTUOM', + 'argumentCount' => '3' + ), + 'CORREL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL', + 'argumentCount' => '2' + ), + 'COS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'cos', + 'argumentCount' => '1' + ), + 'COSH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'cosh', + 'argumentCount' => '1' + ), + 'COUNT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNT', + 'argumentCount' => '1+' + ), + 'COUNTA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTA', + 'argumentCount' => '1+' + ), + 'COUNTBLANK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTBLANK', + 'argumentCount' => '1' + ), + 'COUNTIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTIF', + 'argumentCount' => '2' + ), + 'COUNTIFS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'COUPDAYBS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYBS', + 'argumentCount' => '3,4' + ), + 'COUPDAYS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYS', + 'argumentCount' => '3,4' + ), + 'COUPDAYSNC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYSNC', + 'argumentCount' => '3,4' + ), + 'COUPNCD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNCD', + 'argumentCount' => '3,4' + ), + 'COUPNUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNUM', + 'argumentCount' => '3,4' + ), + 'COUPPCD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::COUPPCD', + 'argumentCount' => '3,4' + ), + 'COVAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::COVAR', + 'argumentCount' => '2' + ), + 'CRITBINOM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CRITBINOM', + 'argumentCount' => '3' + ), + 'CUBEKPIMEMBER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEMEMBER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEMEMBERPROPERTY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBERANKEDMEMBER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBESET' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBESETCOUNT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUBEVALUE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '?' + ), + 'CUMIPMT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::CUMIPMT', + 'argumentCount' => '6' + ), + 'CUMPRINC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::CUMPRINC', + 'argumentCount' => '6' + ), + 'DATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATE', + 'argumentCount' => '3' + ), + 'DATEDIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEDIF', + 'argumentCount' => '2,3' + ), + 'DATEVALUE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEVALUE', + 'argumentCount' => '1' + ), + 'DAVERAGE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DAVERAGE', + 'argumentCount' => '3' + ), + 'DAY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFMONTH', + 'argumentCount' => '1' + ), + 'DAYS360' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYS360', + 'argumentCount' => '2,3' + ), + 'DB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DB', + 'argumentCount' => '4,5' + ), + 'DCOUNT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNT', + 'argumentCount' => '3' + ), + 'DCOUNTA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNTA', + 'argumentCount' => '3' + ), + 'DDB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DDB', + 'argumentCount' => '4,5' + ), + 'DEC2BIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOBIN', + 'argumentCount' => '1,2' + ), + 'DEC2HEX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOHEX', + 'argumentCount' => '1,2' + ), + 'DEC2OCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOOCT', + 'argumentCount' => '1,2' + ), + 'DEGREES' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'rad2deg', + 'argumentCount' => '1' + ), + 'DELTA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::DELTA', + 'argumentCount' => '1,2' + ), + 'DEVSQ' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::DEVSQ', + 'argumentCount' => '1+' + ), + 'DGET' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DGET', + 'argumentCount' => '3' + ), + 'DISC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DISC', + 'argumentCount' => '4,5' + ), + 'DMAX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DMAX', + 'argumentCount' => '3' + ), + 'DMIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DMIN', + 'argumentCount' => '3' + ), + 'DOLLAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::DOLLAR', + 'argumentCount' => '1,2' + ), + 'DOLLARDE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARDE', + 'argumentCount' => '2' + ), + 'DOLLARFR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARFR', + 'argumentCount' => '2' + ), + 'DPRODUCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DPRODUCT', + 'argumentCount' => '3' + ), + 'DSTDEV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEV', + 'argumentCount' => '3' + ), + 'DSTDEVP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEVP', + 'argumentCount' => '3' + ), + 'DSUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DSUM', + 'argumentCount' => '3' + ), + 'DURATION' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5,6' + ), + 'DVAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DVAR', + 'argumentCount' => '3' + ), + 'DVARP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE, + 'functionCall' => 'PHPExcel_Calculation_Database::DVARP', + 'argumentCount' => '3' + ), + 'EDATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::EDATE', + 'argumentCount' => '2' + ), + 'EFFECT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::EFFECT', + 'argumentCount' => '2' + ), + 'EOMONTH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::EOMONTH', + 'argumentCount' => '2' + ), + 'ERF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::ERF', + 'argumentCount' => '1,2' + ), + 'ERFC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::ERFC', + 'argumentCount' => '1' + ), + 'ERROR.TYPE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::ERROR_TYPE', + 'argumentCount' => '1' + ), + 'EVEN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::EVEN', + 'argumentCount' => '1' + ), + 'EXACT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'EXP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'exp', + 'argumentCount' => '1' + ), + 'EXPONDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::EXPONDIST', + 'argumentCount' => '3' + ), + 'FACT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACT', + 'argumentCount' => '1' + ), + 'FACTDOUBLE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACTDOUBLE', + 'argumentCount' => '1' + ), + 'FALSE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::FALSE', + 'argumentCount' => '0' + ), + 'FDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3' + ), + 'FIND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE', + 'argumentCount' => '2,3' + ), + 'FINDB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE', + 'argumentCount' => '2,3' + ), + 'FINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3' + ), + 'FISHER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHER', + 'argumentCount' => '1' + ), + 'FISHERINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHERINV', + 'argumentCount' => '1' + ), + 'FIXED' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::FIXEDFORMAT', + 'argumentCount' => '1-3' + ), + 'FLOOR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::FLOOR', + 'argumentCount' => '2' + ), + 'FORECAST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::FORECAST', + 'argumentCount' => '3' + ), + 'FREQUENCY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'FTEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'FV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::FV', + 'argumentCount' => '3-5' + ), + 'FVSCHEDULE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::FVSCHEDULE', + 'argumentCount' => '2' + ), + 'GAMMADIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMADIST', + 'argumentCount' => '4' + ), + 'GAMMAINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMAINV', + 'argumentCount' => '3' + ), + 'GAMMALN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMALN', + 'argumentCount' => '1' + ), + 'GCD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::GCD', + 'argumentCount' => '1+' + ), + 'GEOMEAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GEOMEAN', + 'argumentCount' => '1+' + ), + 'GESTEP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::GESTEP', + 'argumentCount' => '1,2' + ), + 'GETPIVOTDATA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2+' + ), + 'GROWTH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::GROWTH', + 'argumentCount' => '1-4' + ), + 'HARMEAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::HARMEAN', + 'argumentCount' => '1+' + ), + 'HEX2BIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOBIN', + 'argumentCount' => '1,2' + ), + 'HEX2DEC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTODEC', + 'argumentCount' => '1' + ), + 'HEX2OCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOOCT', + 'argumentCount' => '1,2' + ), + 'HLOOKUP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::HLOOKUP', + 'argumentCount' => '3,4' + ), + 'HOUR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::HOUROFDAY', + 'argumentCount' => '1' + ), + 'HYPERLINK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::HYPERLINK', + 'argumentCount' => '1,2', + 'passCellReference' => true + ), + 'HYPGEOMDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::HYPGEOMDIST', + 'argumentCount' => '4' + ), + 'IF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::STATEMENT_IF', + 'argumentCount' => '1-3' + ), + 'IFERROR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::IFERROR', + 'argumentCount' => '2' + ), + 'IMABS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMABS', + 'argumentCount' => '1' + ), + 'IMAGINARY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMAGINARY', + 'argumentCount' => '1' + ), + 'IMARGUMENT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMARGUMENT', + 'argumentCount' => '1' + ), + 'IMCONJUGATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCONJUGATE', + 'argumentCount' => '1' + ), + 'IMCOS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCOS', + 'argumentCount' => '1' + ), + 'IMDIV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMDIV', + 'argumentCount' => '2' + ), + 'IMEXP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMEXP', + 'argumentCount' => '1' + ), + 'IMLN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLN', + 'argumentCount' => '1' + ), + 'IMLOG10' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG10', + 'argumentCount' => '1' + ), + 'IMLOG2' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG2', + 'argumentCount' => '1' + ), + 'IMPOWER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPOWER', + 'argumentCount' => '2' + ), + 'IMPRODUCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPRODUCT', + 'argumentCount' => '1+' + ), + 'IMREAL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMREAL', + 'argumentCount' => '1' + ), + 'IMSIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSIN', + 'argumentCount' => '1' + ), + 'IMSQRT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSQRT', + 'argumentCount' => '1' + ), + 'IMSUB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUB', + 'argumentCount' => '2' + ), + 'IMSUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUM', + 'argumentCount' => '1+' + ), + 'INDEX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDEX', + 'argumentCount' => '1-4' + ), + 'INDIRECT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDIRECT', + 'argumentCount' => '1,2', + 'passCellReference' => true + ), + 'INFO' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'INT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::INT', + 'argumentCount' => '1' + ), + 'INTERCEPT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::INTERCEPT', + 'argumentCount' => '2' + ), + 'INTRATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::INTRATE', + 'argumentCount' => '4,5' + ), + 'IPMT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::IPMT', + 'argumentCount' => '4-6' + ), + 'IRR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::IRR', + 'argumentCount' => '1,2' + ), + 'ISBLANK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_BLANK', + 'argumentCount' => '1' + ), + 'ISERR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERR', + 'argumentCount' => '1' + ), + 'ISERROR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERROR', + 'argumentCount' => '1' + ), + 'ISEVEN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_EVEN', + 'argumentCount' => '1' + ), + 'ISLOGICAL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_LOGICAL', + 'argumentCount' => '1' + ), + 'ISNA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NA', + 'argumentCount' => '1' + ), + 'ISNONTEXT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NONTEXT', + 'argumentCount' => '1' + ), + 'ISNUMBER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NUMBER', + 'argumentCount' => '1' + ), + 'ISODD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ODD', + 'argumentCount' => '1' + ), + 'ISPMT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::ISPMT', + 'argumentCount' => '4' + ), + 'ISREF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'ISTEXT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::IS_TEXT', + 'argumentCount' => '1' + ), + 'JIS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'KURT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::KURT', + 'argumentCount' => '1+' + ), + 'LARGE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LARGE', + 'argumentCount' => '2' + ), + 'LCM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::LCM', + 'argumentCount' => '1+' + ), + 'LEFT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT', + 'argumentCount' => '1,2' + ), + 'LEFTB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT', + 'argumentCount' => '1,2' + ), + 'LEN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH', + 'argumentCount' => '1' + ), + 'LENB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH', + 'argumentCount' => '1' + ), + 'LINEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LINEST', + 'argumentCount' => '1-4' + ), + 'LN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'log', + 'argumentCount' => '1' + ), + 'LOG' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::LOG_BASE', + 'argumentCount' => '1,2' + ), + 'LOG10' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'log10', + 'argumentCount' => '1' + ), + 'LOGEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGEST', + 'argumentCount' => '1-4' + ), + 'LOGINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGINV', + 'argumentCount' => '3' + ), + 'LOGNORMDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGNORMDIST', + 'argumentCount' => '3' + ), + 'LOOKUP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::LOOKUP', + 'argumentCount' => '2,3' + ), + 'LOWER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::LOWERCASE', + 'argumentCount' => '1' + ), + 'MATCH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::MATCH', + 'argumentCount' => '2,3' + ), + 'MAX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAX', + 'argumentCount' => '1+' + ), + 'MAXA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXA', + 'argumentCount' => '1+' + ), + 'MAXIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXIF', + 'argumentCount' => '2+' + ), + 'MDETERM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MDETERM', + 'argumentCount' => '1' + ), + 'MDURATION' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5,6' + ), + 'MEDIAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MEDIAN', + 'argumentCount' => '1+' + ), + 'MEDIANIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2+' + ), + 'MID' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::MID', + 'argumentCount' => '3' + ), + 'MIDB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::MID', + 'argumentCount' => '3' + ), + 'MIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MIN', + 'argumentCount' => '1+' + ), + 'MINA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MINA', + 'argumentCount' => '1+' + ), + 'MINIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MINIF', + 'argumentCount' => '2+' + ), + 'MINUTE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::MINUTEOFHOUR', + 'argumentCount' => '1' + ), + 'MINVERSE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MINVERSE', + 'argumentCount' => '1' + ), + 'MIRR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::MIRR', + 'argumentCount' => '3' + ), + 'MMULT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MMULT', + 'argumentCount' => '2' + ), + 'MOD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MOD', + 'argumentCount' => '2' + ), + 'MODE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::MODE', + 'argumentCount' => '1+' + ), + 'MONTH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::MONTHOFYEAR', + 'argumentCount' => '1' + ), + 'MROUND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MROUND', + 'argumentCount' => '2' + ), + 'MULTINOMIAL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::MULTINOMIAL', + 'argumentCount' => '1+' + ), + 'N' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::N', + 'argumentCount' => '1' + ), + 'NA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::NA', + 'argumentCount' => '0' + ), + 'NEGBINOMDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NEGBINOMDIST', + 'argumentCount' => '3' + ), + 'NETWORKDAYS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::NETWORKDAYS', + 'argumentCount' => '2+' + ), + 'NOMINAL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NOMINAL', + 'argumentCount' => '2' + ), + 'NORMDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMDIST', + 'argumentCount' => '4' + ), + 'NORMINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMINV', + 'argumentCount' => '3' + ), + 'NORMSDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSDIST', + 'argumentCount' => '1' + ), + 'NORMSINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSINV', + 'argumentCount' => '1' + ), + 'NOT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::NOT', + 'argumentCount' => '1' + ), + 'NOW' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATETIMENOW', + 'argumentCount' => '0' + ), + 'NPER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NPER', + 'argumentCount' => '3-5' + ), + 'NPV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::NPV', + 'argumentCount' => '2+' + ), + 'OCT2BIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOBIN', + 'argumentCount' => '1,2' + ), + 'OCT2DEC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTODEC', + 'argumentCount' => '1' + ), + 'OCT2HEX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING, + 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOHEX', + 'argumentCount' => '1,2' + ), + 'ODD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ODD', + 'argumentCount' => '1' + ), + 'ODDFPRICE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '8,9' + ), + 'ODDFYIELD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '8,9' + ), + 'ODDLPRICE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '7,8' + ), + 'ODDLYIELD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '7,8' + ), + 'OFFSET' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::OFFSET', + 'argumentCount' => '3-5', + 'passCellReference' => true, + 'passByReference' => array(true) + ), + 'OR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_OR', + 'argumentCount' => '1+' + ), + 'PEARSON' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL', + 'argumentCount' => '2' + ), + 'PERCENTILE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTILE', + 'argumentCount' => '2' + ), + 'PERCENTRANK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTRANK', + 'argumentCount' => '2,3' + ), + 'PERMUT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::PERMUT', + 'argumentCount' => '2' + ), + 'PHONETIC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1' + ), + 'PI' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'pi', + 'argumentCount' => '0' + ), + 'PMT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PMT', + 'argumentCount' => '3-5' + ), + 'POISSON' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::POISSON', + 'argumentCount' => '3' + ), + 'POWER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::POWER', + 'argumentCount' => '2' + ), + 'PPMT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PPMT', + 'argumentCount' => '4-6' + ), + 'PRICE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICE', + 'argumentCount' => '6,7' + ), + 'PRICEDISC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEDISC', + 'argumentCount' => '4,5' + ), + 'PRICEMAT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEMAT', + 'argumentCount' => '5,6' + ), + 'PROB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '3,4' + ), + 'PRODUCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::PRODUCT', + 'argumentCount' => '1+' + ), + 'PROPER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::PROPERCASE', + 'argumentCount' => '1' + ), + 'PV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::PV', + 'argumentCount' => '3-5' + ), + 'QUARTILE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::QUARTILE', + 'argumentCount' => '2' + ), + 'QUOTIENT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::QUOTIENT', + 'argumentCount' => '2' + ), + 'RADIANS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'deg2rad', + 'argumentCount' => '1' + ), + 'RAND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND', + 'argumentCount' => '0' + ), + 'RANDBETWEEN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND', + 'argumentCount' => '2' + ), + 'RANK' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::RANK', + 'argumentCount' => '2,3' + ), + 'RATE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::RATE', + 'argumentCount' => '3-6' + ), + 'RECEIVED' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::RECEIVED', + 'argumentCount' => '4-5' + ), + 'REPLACE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE', + 'argumentCount' => '4' + ), + 'REPLACEB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE', + 'argumentCount' => '4' + ), + 'REPT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'str_repeat', + 'argumentCount' => '2' + ), + 'RIGHT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT', + 'argumentCount' => '1,2' + ), + 'RIGHTB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT', + 'argumentCount' => '1,2' + ), + 'ROMAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROMAN', + 'argumentCount' => '1,2' + ), + 'ROUND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'round', + 'argumentCount' => '2' + ), + 'ROUNDDOWN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDDOWN', + 'argumentCount' => '2' + ), + 'ROUNDUP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDUP', + 'argumentCount' => '2' + ), + 'ROW' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROW', + 'argumentCount' => '-1', + 'passByReference' => array(true) + ), + 'ROWS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROWS', + 'argumentCount' => '1' + ), + 'RSQ' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::RSQ', + 'argumentCount' => '2' + ), + 'RTD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '1+' + ), + 'SEARCH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE', + 'argumentCount' => '2,3' + ), + 'SEARCHB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE', + 'argumentCount' => '2,3' + ), + 'SECOND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::SECONDOFMINUTE', + 'argumentCount' => '1' + ), + 'SERIESSUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SERIESSUM', + 'argumentCount' => '4' + ), + 'SIGN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SIGN', + 'argumentCount' => '1' + ), + 'SIN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sin', + 'argumentCount' => '1' + ), + 'SINH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sinh', + 'argumentCount' => '1' + ), + 'SKEW' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SKEW', + 'argumentCount' => '1+' + ), + 'SLN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::SLN', + 'argumentCount' => '3' + ), + 'SLOPE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SLOPE', + 'argumentCount' => '2' + ), + 'SMALL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::SMALL', + 'argumentCount' => '2' + ), + 'SQRT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'sqrt', + 'argumentCount' => '1' + ), + 'SQRTPI' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SQRTPI', + 'argumentCount' => '1' + ), + 'STANDARDIZE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STANDARDIZE', + 'argumentCount' => '3' + ), + 'STDEV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEV', + 'argumentCount' => '1+' + ), + 'STDEVA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVA', + 'argumentCount' => '1+' + ), + 'STDEVP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVP', + 'argumentCount' => '1+' + ), + 'STDEVPA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVPA', + 'argumentCount' => '1+' + ), + 'STEYX' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::STEYX', + 'argumentCount' => '2' + ), + 'SUBSTITUTE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::SUBSTITUTE', + 'argumentCount' => '3,4' + ), + 'SUBTOTAL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUBTOTAL', + 'argumentCount' => '2+' + ), + 'SUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUM', + 'argumentCount' => '1+' + ), + 'SUMIF' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIF', + 'argumentCount' => '2,3' + ), + 'SUMIFS' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIFS', + 'argumentCount' => '3+' + ), + 'SUMPRODUCT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMPRODUCT', + 'argumentCount' => '1+' + ), + 'SUMSQ' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMSQ', + 'argumentCount' => '1+' + ), + 'SUMX2MY2' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2MY2', + 'argumentCount' => '2' + ), + 'SUMX2PY2' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2PY2', + 'argumentCount' => '2' + ), + 'SUMXMY2' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMXMY2', + 'argumentCount' => '2' + ), + 'SYD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::SYD', + 'argumentCount' => '4' + ), + 'T' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::RETURNSTRING', + 'argumentCount' => '1' + ), + 'TAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'tan', + 'argumentCount' => '1' + ), + 'TANH' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'tanh', + 'argumentCount' => '1' + ), + 'TBILLEQ' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLEQ', + 'argumentCount' => '3' + ), + 'TBILLPRICE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLPRICE', + 'argumentCount' => '3' + ), + 'TBILLYIELD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLYIELD', + 'argumentCount' => '3' + ), + 'TDIST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TDIST', + 'argumentCount' => '3' + ), + 'TEXT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TEXTFORMAT', + 'argumentCount' => '2' + ), + 'TIME' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::TIME', + 'argumentCount' => '3' + ), + 'TIMEVALUE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::TIMEVALUE', + 'argumentCount' => '1' + ), + 'TINV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TINV', + 'argumentCount' => '2' + ), + 'TODAY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DATENOW', + 'argumentCount' => '0' + ), + 'TRANSPOSE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::TRANSPOSE', + 'argumentCount' => '1' + ), + 'TREND' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TREND', + 'argumentCount' => '1-4' + ), + 'TRIM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMSPACES', + 'argumentCount' => '1' + ), + 'TRIMMEAN' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::TRIMMEAN', + 'argumentCount' => '2' + ), + 'TRUE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL, + 'functionCall' => 'PHPExcel_Calculation_Logical::TRUE', + 'argumentCount' => '0' + ), + 'TRUNC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG, + 'functionCall' => 'PHPExcel_Calculation_MathTrig::TRUNC', + 'argumentCount' => '1,2' + ), + 'TTEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '4' + ), + 'TYPE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::TYPE', + 'argumentCount' => '1' + ), + 'UPPER' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::UPPERCASE', + 'argumentCount' => '1' + ), + 'USDOLLAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '2' + ), + 'VALUE' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA, + 'functionCall' => 'PHPExcel_Calculation_TextData::VALUE', + 'argumentCount' => '1' + ), + 'VAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARFunc', + 'argumentCount' => '1+' + ), + 'VARA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARA', + 'argumentCount' => '1+' + ), + 'VARP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARP', + 'argumentCount' => '1+' + ), + 'VARPA' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::VARPA', + 'argumentCount' => '1+' + ), + 'VDB' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '5-7' + ), + 'VERSION' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION, + 'functionCall' => 'PHPExcel_Calculation_Functions::VERSION', + 'argumentCount' => '0' + ), + 'VLOOKUP' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE, + 'functionCall' => 'PHPExcel_Calculation_LookupRef::VLOOKUP', + 'argumentCount' => '3,4' + ), + 'WEEKDAY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFWEEK', + 'argumentCount' => '1,2' + ), + 'WEEKNUM' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::WEEKOFYEAR', + 'argumentCount' => '1,2' + ), + 'WEIBULL' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::WEIBULL', + 'argumentCount' => '4' + ), + 'WORKDAY' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::WORKDAY', + 'argumentCount' => '2+' + ), + 'XIRR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::XIRR', + 'argumentCount' => '2,3' + ), + 'XNPV' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::XNPV', + 'argumentCount' => '3' + ), + 'YEAR' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::YEAR', + 'argumentCount' => '1' + ), + 'YEARFRAC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME, + 'functionCall' => 'PHPExcel_Calculation_DateTime::YEARFRAC', + 'argumentCount' => '2,3' + ), + 'YIELD' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY', + 'argumentCount' => '6,7' + ), + 'YIELDDISC' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDDISC', + 'argumentCount' => '4,5' + ), + 'YIELDMAT' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL, + 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDMAT', + 'argumentCount' => '5,6' + ), + 'ZTEST' => array( + 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL, + 'functionCall' => 'PHPExcel_Calculation_Statistical::ZTEST', + 'argumentCount' => '2-3' + ) + ); + + // Internal functions used for special control purposes + private static $controlFunctions = array( + 'MKMATRIX' => array( + 'argumentCount' => '*', + 'functionCall' => 'self::mkMatrix' + ) + ); + + + public function __construct(PHPExcel $workbook = null) + { + $this->delta = 1 * pow(10, 0 - ini_get('precision')); + + $this->workbook = $workbook; + $this->cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack(); + $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->cyclicReferenceStack); + } + + + private static function loadLocales() + { + $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/'; + foreach (glob($localeFileDirectory.'/*', GLOB_ONLYDIR) as $filename) { + $filename = substr($filename, strlen($localeFileDirectory)+1); + if ($filename != 'en') { + self::$validLocaleLanguages[] = $filename; + } + } + } + + /** + * Get an instance of this class + * + * @access public + * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object, + * or NULL to create a standalone claculation engine + * @return PHPExcel_Calculation + */ + public static function getInstance(PHPExcel $workbook = null) + { + if ($workbook !== null) { + $instance = $workbook->getCalculationEngine(); + if (isset($instance)) { + return $instance; + } + } + + if (!isset(self::$instance) || (self::$instance === null)) { + self::$instance = new PHPExcel_Calculation(); + } + return self::$instance; + } + + /** + * Unset an instance of this class + * + * @access public + */ + public function __destruct() + { + $this->workbook = null; + } + + /** + * Flush the calculation cache for any existing instance of this class + * but only if a PHPExcel_Calculation instance exists + * + * @access public + * @return null + */ + public function flushInstance() + { + $this->clearCalculationCache(); + } + + + /** + * Get the debuglog for this claculation engine instance + * + * @access public + * @return PHPExcel_CalcEngine_Logger + */ + public function getDebugLog() + { + return $this->_debugLog; + } + + /** + * __clone implementation. Cloning should not be allowed in a Singleton! + * + * @access public + * @throws PHPExcel_Calculation_Exception + */ + final public function __clone() + { + throw new PHPExcel_Calculation_Exception('Cloning the calculation engine is not allowed!'); + } + + + /** + * Return the locale-specific translation of TRUE + * + * @access public + * @return string locale-specific translation of TRUE + */ + public static function getTRUE() + { + return self::$localeBoolean['TRUE']; + } + + /** + * Return the locale-specific translation of FALSE + * + * @access public + * @return string locale-specific translation of FALSE + */ + public static function getFALSE() + { + return self::$localeBoolean['FALSE']; + } + + /** + * Set the Array Return Type (Array or Value of first element in the array) + * + * @access public + * @param string $returnType Array return type + * @return boolean Success or failure + */ + public static function setArrayReturnType($returnType) + { + if (($returnType == self::RETURN_ARRAY_AS_VALUE) || + ($returnType == self::RETURN_ARRAY_AS_ERROR) || + ($returnType == self::RETURN_ARRAY_AS_ARRAY)) { + self::$returnArrayAsType = $returnType; + return true; + } + return false; + } + + + /** + * Return the Array Return Type (Array or Value of first element in the array) + * + * @access public + * @return string $returnType Array return type + */ + public static function getArrayReturnType() + { + return self::$returnArrayAsType; + } + + + /** + * Is calculation caching enabled? + * + * @access public + * @return boolean + */ + public function getCalculationCacheEnabled() + { + return $this->calculationCacheEnabled; + } + + /** + * Enable/disable calculation cache + * + * @access public + * @param boolean $pValue + */ + public function setCalculationCacheEnabled($pValue = true) + { + $this->calculationCacheEnabled = $pValue; + $this->clearCalculationCache(); + } + + + /** + * Enable calculation cache + */ + public function enableCalculationCache() + { + $this->setCalculationCacheEnabled(true); + } + + + /** + * Disable calculation cache + */ + public function disableCalculationCache() + { + $this->setCalculationCacheEnabled(false); + } + + + /** + * Clear calculation cache + */ + public function clearCalculationCache() + { + $this->calculationCache = array(); + } + + /** + * Clear calculation cache for a specified worksheet + * + * @param string $worksheetName + */ + public function clearCalculationCacheForWorksheet($worksheetName) + { + if (isset($this->calculationCache[$worksheetName])) { + unset($this->calculationCache[$worksheetName]); + } + } + + /** + * Rename calculation cache for a specified worksheet + * + * @param string $fromWorksheetName + * @param string $toWorksheetName + */ + public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName) + { + if (isset($this->calculationCache[$fromWorksheetName])) { + $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName]; + unset($this->calculationCache[$fromWorksheetName]); + } + } + + + /** + * Get the currently defined locale code + * + * @return string + */ + public function getLocale() + { + return self::$localeLanguage; + } + + + /** + * Set the locale code + * + * @param string $locale The locale to use for formula translation + * @return boolean + */ + public function setLocale($locale = 'en_us') + { + // Identify our locale and language + $language = $locale = strtolower($locale); + if (strpos($locale, '_') !== false) { + list($language) = explode('_', $locale); + } + + if (count(self::$validLocaleLanguages) == 1) { + self::loadLocales(); + } + // Test whether we have any language data for this language (any locale) + if (in_array($language, self::$validLocaleLanguages)) { + // initialise language/locale settings + self::$localeFunctions = array(); + self::$localeArgumentSeparator = ','; + self::$localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL'); + // Default is English, if user isn't requesting english, then read the necessary data from the locale files + if ($locale != 'en_us') { + // Search for a file with a list of function names for locale + $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'functions'; + if (!file_exists($functionNamesFile)) { + // If there isn't a locale specific function file, look for a language specific function file + $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions'; + if (!file_exists($functionNamesFile)) { + return false; + } + } + // Retrieve the list of locale or language specific function names + $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeFunctions as $localeFunction) { + list($localeFunction) = explode('##', $localeFunction); // Strip out comments + if (strpos($localeFunction, '=') !== false) { + list($fName, $lfName) = explode('=', $localeFunction); + $fName = trim($fName); + $lfName = trim($lfName); + if ((isset(self::$PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) { + self::$localeFunctions[$fName] = $lfName; + } + } + } + // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions + if (isset(self::$localeFunctions['TRUE'])) { + self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE']; + } + if (isset(self::$localeFunctions['FALSE'])) { + self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE']; + } + + $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'config'; + if (!file_exists($configFile)) { + $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config'; + } + if (file_exists($configFile)) { + $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); + foreach ($localeSettings as $localeSetting) { + list($localeSetting) = explode('##', $localeSetting); // Strip out comments + if (strpos($localeSetting, '=') !== false) { + list($settingName, $settingValue) = explode('=', $localeSetting); + $settingName = strtoupper(trim($settingName)); + switch ($settingName) { + case 'ARGUMENTSEPARATOR': + self::$localeArgumentSeparator = trim($settingValue); + break; + } + } + } + } + } + + self::$functionReplaceFromExcel = self::$functionReplaceToExcel = + self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null; + self::$localeLanguage = $locale; + return true; + } + return false; + } + + + + public static function translateSeparator($fromSeparator, $toSeparator, $formula, &$inBraces) + { + $strlen = mb_strlen($formula); + for ($i = 0; $i < $strlen; ++$i) { + $chr = mb_substr($formula, $i, 1); + switch ($chr) { + case '{': + $inBraces = true; + break; + case '}': + $inBraces = false; + break; + case $fromSeparator: + if (!$inBraces) { + $formula = mb_substr($formula, 0, $i).$toSeparator.mb_substr($formula, $i+1); + } + } + } + return $formula; + } + + private static function translateFormula($from, $to, $formula, $fromSeparator, $toSeparator) + { + // Convert any Excel function names to the required language + if (self::$localeLanguage !== 'en_us') { + $inBraces = false; + // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators + if (strpos($formula, '"') !== false) { + // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded + // the formula + $temp = explode('"', $formula); + $i = false; + foreach ($temp as &$value) { + // Only count/replace in alternating array entries + if ($i = !$i) { + $value = preg_replace($from, $to, $value); + $value = self::translateSeparator($fromSeparator, $toSeparator, $value, $inBraces); + } + } + unset($value); + // Then rebuild the formula string + $formula = implode('"', $temp); + } else { + // If there's no quoted strings, then we do a simple count/replace + $formula = preg_replace($from, $to, $formula); + $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inBraces); + } + } + + return $formula; + } + + private static $functionReplaceFromExcel = null; + private static $functionReplaceToLocale = null; + + public function _translateFormulaToLocale($formula) + { + if (self::$functionReplaceFromExcel === null) { + self::$functionReplaceFromExcel = array(); + foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui'; + } + foreach (array_keys(self::$localeBoolean) as $excelBoolean) { + self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + } + + } + + if (self::$functionReplaceToLocale === null) { + self::$functionReplaceToLocale = array(); + foreach (array_values(self::$localeFunctions) as $localeFunctionName) { + self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2'; + } + foreach (array_values(self::$localeBoolean) as $localeBoolean) { + self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2'; + } + } + + return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator); + } + + + private static $functionReplaceFromLocale = null; + private static $functionReplaceToExcel = null; + + public function _translateFormulaToEnglish($formula) + { + if (self::$functionReplaceFromLocale === null) { + self::$functionReplaceFromLocale = array(); + foreach (array_values(self::$localeFunctions) as $localeFunctionName) { + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui'; + } + foreach (array_values(self::$localeBoolean) as $excelBoolean) { + self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui'; + } + } + + if (self::$functionReplaceToExcel === null) { + self::$functionReplaceToExcel = array(); + foreach (array_keys(self::$localeFunctions) as $excelFunctionName) { + self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2'; + } + foreach (array_keys(self::$localeBoolean) as $excelBoolean) { + self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2'; + } + } + + return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ','); + } + + + public static function localeFunc($function) + { + if (self::$localeLanguage !== 'en_us') { + $functionName = trim($function, '('); + if (isset(self::$localeFunctions[$functionName])) { + $brace = ($functionName != $function); + $function = self::$localeFunctions[$functionName]; + if ($brace) { + $function .= '('; + } + } + } + return $function; + } + + + + + /** + * Wrap string values in quotes + * + * @param mixed $value + * @return mixed + */ + public static function wrapResult($value) + { + if (is_string($value)) { + // Error values cannot be "wrapped" + if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) { + // Return Excel errors "as is" + return $value; + } + // Return strings wrapped in quotes + return '"'.$value.'"'; + // Convert numeric errors to NaN error + } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return $value; + } + + + /** + * Remove quotes used as a wrapper to identify string values + * + * @param mixed $value + * @return mixed + */ + public static function unwrapResult($value) + { + if (is_string($value)) { + if ((isset($value{0})) && ($value{0} == '"') && (substr($value, -1) == '"')) { + return substr($value, 1, -1); + } + // Convert numeric errors to NaN error + } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $value; + } + + + + + /** + * Calculate cell value (using formula from a cell ID) + * Retained for backward compatibility + * + * @access public + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculate(PHPExcel_Cell $pCell = null) + { + try { + return $this->calculateCellValue($pCell); + } catch (PHPExcel_Exception $e) { + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + } + + + /** + * Calculate the value of a cell formula + * + * @access public + * @param PHPExcel_Cell $pCell Cell to calculate + * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculateCellValue(PHPExcel_Cell $pCell = null, $resetLog = true) + { + if ($pCell === null) { + return null; + } + + $returnArrayAsType = self::$returnArrayAsType; + if ($resetLog) { + // Initialise the logging settings if requested + $this->formulaError = null; + $this->_debugLog->clearLog(); + $this->cyclicReferenceStack->clear(); + $this->cyclicFormulaCounter = 1; + + self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY; + } + + // Execute the calculation for the cell formula + $this->cellStack[] = array( + 'sheet' => $pCell->getWorksheet()->getTitle(), + 'cell' => $pCell->getCoordinate(), + ); + try { + $result = self::unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell)); + $cellAddress = array_pop($this->cellStack); + $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); + } catch (PHPExcel_Exception $e) { + $cellAddress = array_pop($this->cellStack); + $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']); + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + + if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { + self::$returnArrayAsType = $returnArrayAsType; + $testResult = PHPExcel_Calculation_Functions::flattenArray($result); + if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) { + return PHPExcel_Calculation_Functions::VALUE(); + } + // If there's only a single cell in the array, then we allow it + if (count($testResult) != 1) { + // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it + $r = array_keys($result); + $r = array_shift($r); + if (!is_numeric($r)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_array($result[$r])) { + $c = array_keys($result[$r]); + $c = array_shift($c); + if (!is_numeric($c)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + } + $result = array_shift($testResult); + } + self::$returnArrayAsType = $returnArrayAsType; + + + if ($result === null) { + return 0; + } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $result; + } + + + /** + * Validate and parse a formula string + * + * @param string $formula Formula to parse + * @return array + * @throws PHPExcel_Calculation_Exception + */ + public function parseFormula($formula) + { + // Basic validation that this is indeed a formula + // We return an empty array if not + $formula = trim($formula); + if ((!isset($formula{0})) || ($formula{0} != '=')) { + return array(); + } + $formula = ltrim(substr($formula, 1)); + if (!isset($formula{0})) { + return array(); + } + + // Parse the formula and return the token stack + return $this->_parseFormula($formula); + } + + + /** + * Calculate the value of a formula + * + * @param string $formula Formula to parse + * @param string $cellID Address of the cell to calculate + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function calculateFormula($formula, $cellID = null, PHPExcel_Cell $pCell = null) + { + // Initialise the logging settings + $this->formulaError = null; + $this->_debugLog->clearLog(); + $this->cyclicReferenceStack->clear(); + + if ($this->workbook !== null && $cellID === null && $pCell === null) { + $cellID = 'A1'; + $pCell = $this->workbook->getActiveSheet()->getCell($cellID); + } else { + // Disable calculation cacheing because it only applies to cell calculations, not straight formulae + // But don't actually flush any cache + $resetCache = $this->getCalculationCacheEnabled(); + $this->calculationCacheEnabled = false; + } + + // Execute the calculation + try { + $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell)); + } catch (PHPExcel_Exception $e) { + throw new PHPExcel_Calculation_Exception($e->getMessage()); + } + + if ($this->workbook === null) { + // Reset calculation cacheing to its previous state + $this->calculationCacheEnabled = $resetCache; + } + + return $result; + } + + + public function getValueFromCache($cellReference, &$cellValue) + { + // Is calculation cacheing enabled? + // Is the value present in calculation cache? + $this->_debugLog->writeDebugLog('Testing cache value for cell ', $cellReference); + if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) { + $this->_debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache'); + // Return the cached result + $cellValue = $this->calculationCache[$cellReference]; + return true; + } + return false; + } + + public function saveValueToCache($cellReference, $cellValue) + { + if ($this->calculationCacheEnabled) { + $this->calculationCache[$cellReference] = $cellValue; + } + } + + /** + * Parse a cell formula and calculate its value + * + * @param string $formula The formula to parse and calculate + * @param string $cellID The ID (e.g. A3) of the cell that we are calculating + * @param PHPExcel_Cell $pCell Cell to calculate + * @return mixed + * @throws PHPExcel_Calculation_Exception + */ + public function _calculateFormulaValue($formula, $cellID = null, PHPExcel_Cell $pCell = null) + { + $cellValue = null; + + // Basic validation that this is indeed a formula + // We simply return the cell value if not + $formula = trim($formula); + if ($formula{0} != '=') { + return self::wrapResult($formula); + } + $formula = ltrim(substr($formula, 1)); + if (!isset($formula{0})) { + return self::wrapResult($formula); + } + + $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; + $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk"; + $wsCellReference = $wsTitle . '!' . $cellID; + + if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) { + return $cellValue; + } + + if (($wsTitle{0} !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) { + if ($this->cyclicFormulaCount <= 0) { + $this->cyclicFormulaCell = ''; + return $this->raiseFormulaError('Cyclic Reference in Formula'); + } elseif ($this->cyclicFormulaCell === $wsCellReference) { + ++$this->cyclicFormulaCounter; + if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { + $this->cyclicFormulaCell = ''; + return $cellValue; + } + } elseif ($this->cyclicFormulaCell == '') { + if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) { + return $cellValue; + } + $this->cyclicFormulaCell = $wsCellReference; + } + } + + // Parse the formula onto the token stack and calculate the value + $this->cyclicReferenceStack->push($wsCellReference); + $cellValue = $this->processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell); + $this->cyclicReferenceStack->pop(); + + // Save to calculation cache + if ($cellID !== null) { + $this->saveValueToCache($wsCellReference, $cellValue); + } + + // Return the calculated value + return $cellValue; + } + + + /** + * Ensure that paired matrix operands are both matrices and of the same size + * + * @param mixed &$operand1 First matrix operand + * @param mixed &$operand2 Second matrix operand + * @param integer $resize Flag indicating whether the matrices should be resized to match + * and (if so), whether the smaller dimension should grow or the + * larger should shrink. + * 0 = no resize + * 1 = shrink to fit + * 2 = extend to fit + */ + private static function checkMatrixOperands(&$operand1, &$operand2, $resize = 1) + { + // Examine each of the two operands, and turn them into an array if they aren't one already + // Note that this function should only be called if one or both of the operand is already an array + if (!is_array($operand1)) { + list($matrixRows, $matrixColumns) = self::getMatrixDimensions($operand2); + $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1)); + $resize = 0; + } elseif (!is_array($operand2)) { + list($matrixRows, $matrixColumns) = self::getMatrixDimensions($operand1); + $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2)); + $resize = 0; + } + + list($matrix1Rows, $matrix1Columns) = self::getMatrixDimensions($operand1); + list($matrix2Rows, $matrix2Columns) = self::getMatrixDimensions($operand2); + if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) { + $resize = 1; + } + + if ($resize == 2) { + // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger + self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); + } elseif ($resize == 1) { + // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller + self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); + } + return array( $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns); + } + + + /** + * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0 + * + * @param mixed &$matrix matrix operand + * @return array An array comprising the number of rows, and number of columns + */ + private static function getMatrixDimensions(&$matrix) + { + $matrixRows = count($matrix); + $matrixColumns = 0; + foreach ($matrix as $rowKey => $rowValue) { + $matrixColumns = max(count($rowValue), $matrixColumns); + if (!is_array($rowValue)) { + $matrix[$rowKey] = array($rowValue); + } else { + $matrix[$rowKey] = array_values($rowValue); + } + } + $matrix = array_values($matrix); + return array($matrixRows, $matrixColumns); + } + + + /** + * Ensure that paired matrix operands are both matrices of the same size + * + * @param mixed &$matrix1 First matrix operand + * @param mixed &$matrix2 Second matrix operand + * @param integer $matrix1Rows Row size of first matrix operand + * @param integer $matrix1Columns Column size of first matrix operand + * @param integer $matrix2Rows Row size of second matrix operand + * @param integer $matrix2Columns Column size of second matrix operand + */ + private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) + { + if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { + if ($matrix2Rows < $matrix1Rows) { + for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) { + unset($matrix1[$i]); + } + } + if ($matrix2Columns < $matrix1Columns) { + for ($i = 0; $i < $matrix1Rows; ++$i) { + for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { + unset($matrix1[$i][$j]); + } + } + } + } + + if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { + if ($matrix1Rows < $matrix2Rows) { + for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) { + unset($matrix2[$i]); + } + } + if ($matrix1Columns < $matrix2Columns) { + for ($i = 0; $i < $matrix2Rows; ++$i) { + for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { + unset($matrix2[$i][$j]); + } + } + } + } + } + + + /** + * Ensure that paired matrix operands are both matrices of the same size + * + * @param mixed &$matrix1 First matrix operand + * @param mixed &$matrix2 Second matrix operand + * @param integer $matrix1Rows Row size of first matrix operand + * @param integer $matrix1Columns Column size of first matrix operand + * @param integer $matrix2Rows Row size of second matrix operand + * @param integer $matrix2Columns Column size of second matrix operand + */ + private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns) + { + if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) { + if ($matrix2Columns < $matrix1Columns) { + for ($i = 0; $i < $matrix2Rows; ++$i) { + $x = $matrix2[$i][$matrix2Columns-1]; + for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) { + $matrix2[$i][$j] = $x; + } + } + } + if ($matrix2Rows < $matrix1Rows) { + $x = $matrix2[$matrix2Rows-1]; + for ($i = 0; $i < $matrix1Rows; ++$i) { + $matrix2[$i] = $x; + } + } + } + + if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) { + if ($matrix1Columns < $matrix2Columns) { + for ($i = 0; $i < $matrix1Rows; ++$i) { + $x = $matrix1[$i][$matrix1Columns-1]; + for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) { + $matrix1[$i][$j] = $x; + } + } + } + if ($matrix1Rows < $matrix2Rows) { + $x = $matrix1[$matrix1Rows-1]; + for ($i = 0; $i < $matrix2Rows; ++$i) { + $matrix1[$i] = $x; + } + } + } + } + + + /** + * Format details of an operand for display in the log (based on operand type) + * + * @param mixed $value First matrix operand + * @return mixed + */ + private function showValue($value) + { + if ($this->_debugLog->getWriteDebugLog()) { + $testArray = PHPExcel_Calculation_Functions::flattenArray($value); + if (count($testArray) == 1) { + $value = array_pop($testArray); + } + + if (is_array($value)) { + $returnMatrix = array(); + $pad = $rpad = ', '; + foreach ($value as $row) { + if (is_array($row)) { + $returnMatrix[] = implode($pad, array_map(array($this, 'showValue'), $row)); + $rpad = '; '; + } else { + $returnMatrix[] = $this->showValue($row); + } + } + return '{ '.implode($rpad, $returnMatrix).' }'; + } elseif (is_string($value) && (trim($value, '"') == $value)) { + return '"'.$value.'"'; + } elseif (is_bool($value)) { + return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; + } + } + return PHPExcel_Calculation_Functions::flattenSingleValue($value); + } + + + /** + * Format type and details of an operand for display in the log (based on operand type) + * + * @param mixed $value First matrix operand + * @return mixed + */ + private function showTypeDetails($value) + { + if ($this->_debugLog->getWriteDebugLog()) { + $testArray = PHPExcel_Calculation_Functions::flattenArray($value); + if (count($testArray) == 1) { + $value = array_pop($testArray); + } + + if ($value === null) { + return 'a NULL value'; + } elseif (is_float($value)) { + $typeString = 'a floating point number'; + } elseif (is_int($value)) { + $typeString = 'an integer number'; + } elseif (is_bool($value)) { + $typeString = 'a boolean'; + } elseif (is_array($value)) { + $typeString = 'a matrix'; + } else { + if ($value == '') { + return 'an empty string'; + } elseif ($value{0} == '#') { + return 'a '.$value.' error'; + } else { + $typeString = 'a string'; + } + } + return $typeString.' with a value of '.$this->showValue($value); + } + } + + + private function convertMatrixReferences($formula) + { + static $matrixReplaceFrom = array('{', ';', '}'); + static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))'); + + // Convert any Excel matrix references to the MKMATRIX() function + if (strpos($formula, '{') !== false) { + // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators + if (strpos($formula, '"') !== false) { + // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded + // the formula + $temp = explode('"', $formula); + // Open and Closed counts used for trapping mismatched braces in the formula + $openCount = $closeCount = 0; + $i = false; + foreach ($temp as &$value) { + // Only count/replace in alternating array entries + if ($i = !$i) { + $openCount += substr_count($value, '{'); + $closeCount += substr_count($value, '}'); + $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value); + } + } + unset($value); + // Then rebuild the formula string + $formula = implode('"', $temp); + } else { + // If there's no quoted strings, then we do a simple count/replace + $openCount = substr_count($formula, '{'); + $closeCount = substr_count($formula, '}'); + $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula); + } + // Trap for mismatched braces and trigger an appropriate error + if ($openCount < $closeCount) { + if ($openCount > 0) { + return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'"); + } else { + return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered"); + } + } elseif ($openCount > $closeCount) { + if ($closeCount > 0) { + return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'"); + } else { + return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered"); + } + } + } + + return $formula; + } + + + private static function mkMatrix() + { + return func_get_args(); + } + + + // Binary Operators + // These operators always work on two values + // Array key is the operator, the value indicates whether this is a left or right associative operator + private static $operatorAssociativity = array( + '^' => 0, // Exponentiation + '*' => 0, '/' => 0, // Multiplication and Division + '+' => 0, '-' => 0, // Addition and Subtraction + '&' => 0, // Concatenation + '|' => 0, ':' => 0, // Intersect and Range + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison + ); + + // Comparison (Boolean) Operators + // These operators work on two values, but always return a boolean result + private static $comparisonOperators = array('>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true); + + // Operator Precedence + // This list includes all valid operators, whether binary (including boolean) or unary (such as %) + // Array key is the operator, the value is its precedence + private static $operatorPrecedence = array( + ':' => 8, // Range + '|' => 7, // Intersect + '~' => 6, // Negation + '%' => 5, // Percentage + '^' => 4, // Exponentiation + '*' => 3, '/' => 3, // Multiplication and Division + '+' => 2, '-' => 2, // Addition and Subtraction + '&' => 1, // Concatenation + '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison + ); + + // Convert infix to postfix notation + private function _parseFormula($formula, PHPExcel_Cell $pCell = null) + { + if (($formula = $this->convertMatrixReferences(trim($formula))) === false) { + return false; + } + + // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet), + // so we store the parent worksheet so that we can re-attach it when necessary + $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null; + + $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION. + '|'.self::CALCULATION_REGEXP_CELLREF. + '|'.self::CALCULATION_REGEXP_NUMBER. + '|'.self::CALCULATION_REGEXP_STRING. + '|'.self::CALCULATION_REGEXP_OPENBRACE. + '|'.self::CALCULATION_REGEXP_NAMEDRANGE. + '|'.self::CALCULATION_REGEXP_ERROR. + ')/si'; + + // Start with initialisation + $index = 0; + $stack = new PHPExcel_Calculation_Token_Stack; + $output = array(); + $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a + // - is a negation or + is a positive operator rather than an operation + $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand + // should be null in a function call + // The guts of the lexical parser + // Loop through the formula extracting each operator and operand in turn + while (true) { +//echo 'Assessing Expression '.substr($formula, $index), PHP_EOL; + $opCharacter = $formula{$index}; // Get the first character of the value at the current index position +//echo 'Initial character of expression block is '.$opCharacter, PHP_EOL; + if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula{$index+1}]))) { + $opCharacter .= $formula{++$index}; +//echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL; + } + + // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand + $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match); +//echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').PHP_EOL; +//var_dump($match); + + if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus? +//echo 'Element is a Negation operator', PHP_EOL; + $stack->push('Unary Operator', '~'); // Put a negation on the stack + ++$index; // and drop the negation symbol + } elseif ($opCharacter == '%' && $expectingOperator) { +//echo 'Element is a Percentage operator', PHP_EOL; + $stack->push('Unary Operator', '%'); // Put a percentage on the stack + ++$index; + } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded? +//echo 'Element is a Positive number, not Plus operator', PHP_EOL; + ++$index; // Drop the redundant plus symbol + } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal + return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression + + } elseif ((isset(self::$operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack? +//echo 'Element with value '.$opCharacter.' is an Operator', PHP_EOL; + while ($stack->count() > 0 && + ($o2 = $stack->last()) && + isset(self::$operators[$o2['value']]) && + @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) { + $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output + } + $stack->push('Binary Operator', $opCharacter); // Finally put our current operator onto the stack + ++$index; + $expectingOperator = false; + + } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis? +//echo 'Element is a Closing bracket', PHP_EOL; + $expectingOperand = false; + while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + if ($o2 === null) { + return $this->raiseFormulaError('Formula Error: Unexpected closing brace ")"'); + } else { + $output[] = $o2; + } + } + $d = $stack->last(2); + if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function? + $functionName = $matches[1]; // Get the function name +//echo 'Closed Function is '.$functionName, PHP_EOL; + $d = $stack->pop(); + $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack) +//if ($argumentCount == 0) { +// echo 'With no arguments', PHP_EOL; +//} elseif ($argumentCount == 1) { +// echo 'With 1 argument', PHP_EOL; +//} else { +// echo 'With '.$argumentCount.' arguments', PHP_EOL; +//} + $output[] = $d; // Dump the argument count on the output + $output[] = $stack->pop(); // Pop the function and push onto the output + if (isset(self::$controlFunctions[$functionName])) { +//echo 'Built-in function '.$functionName, PHP_EOL; + $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount']; + $functionCall = self::$controlFunctions[$functionName]['functionCall']; + } elseif (isset(self::$PHPExcelFunctions[$functionName])) { +//echo 'PHPExcel function '.$functionName, PHP_EOL; + $expectedArgumentCount = self::$PHPExcelFunctions[$functionName]['argumentCount']; + $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall']; + } else { // did we somehow push a non-function on the stack? this should never happen + return $this->raiseFormulaError("Formula Error: Internal error, non-function on stack"); + } + // Check the argument count + $argumentCountError = false; + if (is_numeric($expectedArgumentCount)) { + if ($expectedArgumentCount < 0) { +//echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount), PHP_EOL; + if ($argumentCount > abs($expectedArgumentCount)) { + $argumentCountError = true; + $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount); + } + } else { +//echo '$expectedArgumentCount is numeric '.$expectedArgumentCount, PHP_EOL; + if ($argumentCount != $expectedArgumentCount) { + $argumentCountError = true; + $expectedArgumentCountString = $expectedArgumentCount; + } + } + } elseif ($expectedArgumentCount != '*') { + $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch); +//print_r($argMatch); +//echo PHP_EOL; + switch ($argMatch[2]) { + case '+': + if ($argumentCount < $argMatch[1]) { + $argumentCountError = true; + $expectedArgumentCountString = $argMatch[1].' or more '; + } + break; + case '-': + if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) { + $argumentCountError = true; + $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3]; + } + break; + case ',': + if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) { + $argumentCountError = true; + $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3]; + } + break; + } + } + if ($argumentCountError) { + return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected"); + } + } + ++$index; + + } elseif ($opCharacter == ',') { // Is this the separator for function arguments? +//echo 'Element is a Function argument separator', PHP_EOL; + while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last ( + if ($o2 === null) { + return $this->raiseFormulaError("Formula Error: Unexpected ,"); + } else { + $output[] = $o2; // pop the argument expression stuff and push onto the output + } + } + // If we've a comma when we're expecting an operand, then what we actually have is a null operand; + // so push a null onto the stack + if (($expectingOperand) || (!$expectingOperator)) { + $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); + } + // make sure there was a function + $d = $stack->last(2); + if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { + return $this->raiseFormulaError("Formula Error: Unexpected ,"); + } + $d = $stack->pop(); + $stack->push($d['type'], ++$d['value'], $d['reference']); // increment the argument count + $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again + $expectingOperator = false; + $expectingOperand = true; + ++$index; + + } elseif ($opCharacter == '(' && !$expectingOperator) { +// echo 'Element is an Opening Bracket<br />'; + $stack->push('Brace', '('); + ++$index; + + } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number? + $expectingOperator = true; + $expectingOperand = false; + $val = $match[1]; + $length = strlen($val); +// echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function<br />'; + + if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) { + $val = preg_replace('/\s/u', '', $val); +// echo 'Element '.$val.' is a Function<br />'; + if (isset(self::$PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function + $stack->push('Function', strtoupper($val)); + $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch); + if ($ax) { + $stack->push('Operand Count for Function '.strtoupper($val).')', 0); + $expectingOperator = true; + } else { + $stack->push('Operand Count for Function '.strtoupper($val).')', 1); + $expectingOperator = false; + } + $stack->push('Brace', '('); + } else { // it's a var w/ implicit multiplication + $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null); + } + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) { +// echo 'Element '.$val.' is a Cell reference<br />'; + // Watch for this case-change when modifying to allow cell references in different worksheets... + // Should only be applied to the actual cell column, not the worksheet name + + // If the last entry on the stack was a : operator, then we have a cell range reference + $testPrevOp = $stack->last(1); + if ($testPrevOp['value'] == ':') { + // If we have a worksheet reference, then we're playing with a 3D reference + if ($matches[2] == '') { + // Otherwise, we 'inherit' the worksheet reference from the start cell reference + // The start of the cell range reference should be the last entry in $output + $startCellRef = $output[count($output)-1]['value']; + preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches); + if ($startMatches[2] > '') { + $val = $startMatches[2].'!'.$val; + } + } else { + return $this->raiseFormulaError("3D Range references are not yet supported"); + } + } + + $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val); +// $expectingOperator = FALSE; + } else { // it's a variable, constant, string, number or boolean +// echo 'Element is a Variable, Constant, String, Number or Boolean<br />'; + // If the last entry on the stack was a : operator, then we may have a row or column range reference + $testPrevOp = $stack->last(1); + if ($testPrevOp['value'] == ':') { + $startRowColRef = $output[count($output)-1]['value']; + $rangeWS1 = ''; + if (strpos('!', $startRowColRef) !== false) { + list($rangeWS1, $startRowColRef) = explode('!', $startRowColRef); + } + if ($rangeWS1 != '') { + $rangeWS1 .= '!'; + } + $rangeWS2 = $rangeWS1; + if (strpos('!', $val) !== false) { + list($rangeWS2, $val) = explode('!', $val); + } + if ($rangeWS2 != '') { + $rangeWS2 .= '!'; + } + if ((is_integer($startRowColRef)) && (ctype_digit($val)) && + ($startRowColRef <= 1048576) && ($val <= 1048576)) { + // Row range + $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007 + $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef; + $val = $rangeWS2.$endRowColRef.$val; + } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) && + (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) { + // Column range + $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007 + $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1'; + $val = $rangeWS2.$val.$endRowColRef; + } + } + + $localeConstant = false; + if ($opCharacter == '"') { +// echo 'Element is a String<br />'; + // UnEscape any quotes within the string + $val = self::wrapResult(str_replace('""', '"', self::unwrapResult($val))); + } elseif (is_numeric($val)) { +// echo 'Element is a Number<br />'; + if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) { +// echo 'Casting '.$val.' to float<br />'; + $val = (float) $val; + } else { +// echo 'Casting '.$val.' to integer<br />'; + $val = (integer) $val; + } + } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) { + $excelConstant = trim(strtoupper($val)); +// echo 'Element '.$excelConstant.' is an Excel Constant<br />'; + $val = self::$excelConstants[$excelConstant]; + } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) { +// echo 'Element '.$localeConstant.' is an Excel Constant<br />'; + $val = self::$excelConstants[$localeConstant]; + } + $details = array('type' => 'Value', 'value' => $val, 'reference' => null); + if ($localeConstant) { + $details['localeValue'] = $localeConstant; + } + $output[] = $details; + } + $index += $length; + + } elseif ($opCharacter == '$') { // absolute row or column range + ++$index; + } elseif ($opCharacter == ')') { // miscellaneous error checking + if ($expectingOperand) { + $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null); + $expectingOperand = false; + $expectingOperator = true; + } else { + return $this->raiseFormulaError("Formula Error: Unexpected ')'"); + } + } elseif (isset(self::$operators[$opCharacter]) && !$expectingOperator) { + return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'"); + } else { // I don't even want to know what you did to get here + return $this->raiseFormulaError("Formula Error: An unexpected error occured"); + } + // Test for end of formula string + if ($index == strlen($formula)) { + // Did we end with an operator?. + // Only valid for the % unary operator + if ((isset(self::$operators[$opCharacter])) && ($opCharacter != '%')) { + return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands"); + } else { + break; + } + } + // Ignore white space + while (($formula{$index} == "\n") || ($formula{$index} == "\r")) { + ++$index; + } + if ($formula{$index} == ' ') { + while ($formula{$index} == ' ') { + ++$index; + } + // If we're expecting an operator, but only have a space between the previous and next operands (and both are + // Cell References) then we have an INTERSECTION operator +// echo 'Possible Intersect Operator<br />'; + if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) && + ($output[count($output)-1]['type'] == 'Cell Reference')) { +// echo 'Element is an Intersect Operator<br />'; + while ($stack->count() > 0 && + ($o2 = $stack->last()) && + isset(self::$operators[$o2['value']]) && + @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) { + $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output + } + $stack->push('Binary Operator', '|'); // Put an Intersect Operator on the stack + $expectingOperator = false; + } + } + } + + while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output + if ((is_array($op) && $op['value'] == '(') || ($op === '(')) { + return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced + } + $output[] = $op; + } + return $output; + } + + + private static function dataTestReference(&$operandData) + { + $operand = $operandData['value']; + if (($operandData['reference'] === null) && (is_array($operand))) { + $rKeys = array_keys($operand); + $rowKey = array_shift($rKeys); + $cKeys = array_keys(array_keys($operand[$rowKey])); + $colKey = array_shift($cKeys); + if (ctype_upper($colKey)) { + $operandData['reference'] = $colKey.$rowKey; + } + } + return $operand; + } + + // evaluate postfix notation + private function processTokenStack($tokens, $cellID = null, PHPExcel_Cell $pCell = null) + { + if ($tokens == false) { + return false; + } + + // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection), + // so we store the parent cell collection so that we can re-attach it when necessary + $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null; + $pCellParent = ($pCell !== null) ? $pCell->getParent() : null; + $stack = new PHPExcel_Calculation_Token_Stack; + + // Loop through each token in turn + foreach ($tokens as $tokenData) { +// print_r($tokenData); +// echo '<br />'; + $token = $tokenData['value']; +// echo '<b>Token is '.$token.'</b><br />'; + // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack + if (isset(self::$binaryOperators[$token])) { +// echo 'Token is a binary operator<br />'; + // We must have two operands, error if we don't + if (($operand2Data = $stack->pop()) === null) { + return $this->raiseFormulaError('Internal error - Operand value missing from stack'); + } + if (($operand1Data = $stack->pop()) === null) { + return $this->raiseFormulaError('Internal error - Operand value missing from stack'); + } + + $operand1 = self::dataTestReference($operand1Data); + $operand2 = self::dataTestReference($operand2Data); + + // Log what we're doing + if ($token == ':') { + $this->_debugLog->writeDebugLog('Evaluating Range ', $this->showValue($operand1Data['reference']), ' ', $token, ' ', $this->showValue($operand2Data['reference'])); + } else { + $this->_debugLog->writeDebugLog('Evaluating ', $this->showValue($operand1), ' ', $token, ' ', $this->showValue($operand2)); + } + + // Process the operation in the appropriate manner + switch ($token) { + // Comparison (Boolean) Operators + case '>': // Greater than + case '<': // Less than + case '>=': // Greater than or Equal to + case '<=': // Less than or Equal to + case '=': // Equality + case '<>': // Inequality + $this->executeBinaryComparisonOperation($cellID, $operand1, $operand2, $token, $stack); + break; + // Binary Operators + case ':': // Range + $sheet1 = $sheet2 = ''; + if (strpos($operand1Data['reference'], '!') !== false) { + list($sheet1, $operand1Data['reference']) = explode('!', $operand1Data['reference']); + } else { + $sheet1 = ($pCellParent !== null) ? $pCellWorksheet->getTitle() : ''; + } + if (strpos($operand2Data['reference'], '!') !== false) { + list($sheet2, $operand2Data['reference']) = explode('!', $operand2Data['reference']); + } else { + $sheet2 = $sheet1; + } + if ($sheet1 == $sheet2) { + if ($operand1Data['reference'] === null) { + if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) { + $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value']; + } elseif (trim($operand1Data['reference']) == '') { + $operand1Data['reference'] = $pCell->getCoordinate(); + } else { + $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow(); + } + } + if ($operand2Data['reference'] === null) { + if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) { + $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value']; + } elseif (trim($operand2Data['reference']) == '') { + $operand2Data['reference'] = $pCell->getCoordinate(); + } else { + $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow(); + } + } + + $oData = array_merge(explode(':', $operand1Data['reference']), explode(':', $operand2Data['reference'])); + $oCol = $oRow = array(); + foreach ($oData as $oDatum) { + $oCR = PHPExcel_Cell::coordinateFromString($oDatum); + $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1; + $oRow[] = $oCR[1]; + } + $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow); + if ($pCellParent !== null) { + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($sheet1), false); + } else { + return $this->raiseFormulaError('Unable to access Cell Reference'); + } + $stack->push('Cell Reference', $cellValue, $cellRef); + } else { + $stack->push('Error', PHPExcel_Calculation_Functions::REF(), null); + } + break; + case '+': // Addition + $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'plusEquals', $stack); + break; + case '-': // Subtraction + $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'minusEquals', $stack); + break; + case '*': // Multiplication + $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayTimesEquals', $stack); + break; + case '/': // Division + $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayRightDivide', $stack); + break; + case '^': // Exponential + $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'power', $stack); + break; + case '&': // Concatenation + // If either of the operands is a matrix, we need to treat them both as matrices + // (converting the other operand to a matrix if need be); then perform the required + // matrix operation + if (is_bool($operand1)) { + $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; + } + if (is_bool($operand2)) { + $operand2 = ($operand2) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE']; + } + if ((is_array($operand1)) || (is_array($operand2))) { + // Ensure that both operands are arrays/matrices + self::checkMatrixOperands($operand1, $operand2, 2); + try { + // Convert operand 1 from a PHP array to a matrix + $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1); + // Perform the required operation against the operand 1 matrix, passing in operand 2 + $matrixResult = $matrix->concat($operand2); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + } else { + $result = '"'.str_replace('""', '"', self::unwrapResult($operand1, '"').self::unwrapResult($operand2, '"')).'"'; + } + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $stack->push('Value', $result); + break; + case '|': // Intersect + $rowIntersect = array_intersect_key($operand1, $operand2); + $cellIntersect = $oCol = $oRow = array(); + foreach (array_keys($rowIntersect) as $row) { + $oRow[] = $row; + foreach ($rowIntersect[$row] as $col => $data) { + $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1; + $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]); + } + } + $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($cellIntersect)); + $stack->push('Value', $cellIntersect, $cellRef); + break; + } + + // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on + } elseif (($token === '~') || ($token === '%')) { +// echo 'Token is a unary operator<br />'; + if (($arg = $stack->pop()) === null) { + return $this->raiseFormulaError('Internal error - Operand value missing from stack'); + } + $arg = $arg['value']; + if ($token === '~') { +// echo 'Token is a negation operator<br />'; + $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->showValue($arg)); + $multiplier = -1; + } else { +// echo 'Token is a percentile operator<br />'; + $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->showValue($arg)); + $multiplier = 0.01; + } + if (is_array($arg)) { + self::checkMatrixOperands($arg, $multiplier, 2); + try { + $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg); + $matrixResult = $matrix1->arrayTimesEquals($multiplier); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + $stack->push('Value', $result); + } else { + $this->executeNumericBinaryOperation($cellID, $multiplier, $arg, '*', 'arrayTimesEquals', $stack); + } + + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) { + $cellRef = null; +// echo 'Element '.$token.' is a Cell reference<br />'; + if (isset($matches[8])) { +// echo 'Reference is a Range of cells<br />'; + if ($pCell === null) { +// We can't access the range, so return a REF error + $cellValue = PHPExcel_Calculation_Functions::REF(); + } else { + $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10]; + if ($matches[2] > '') { + $matches[2] = trim($matches[2], "\"'"); + if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { + // It's a Reference to an external workbook (not currently supported) + return $this->raiseFormulaError('Unable to access External Workbook'); + } + $matches[2] = trim($matches[2], "\"'"); +// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />'; + $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]); + if ($pCellParent !== null) { + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false); + } else { + return $this->raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); +// $cellRef = $matches[2].'!'.$cellRef; + } else { +// echo '$cellRef='.$cellRef.' in current worksheet<br />'; + $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet'); + if ($pCellParent !== null) { + $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); + } else { + return $this->raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->showTypeDetails($cellValue)); + } + } + } else { +// echo 'Reference is a single Cell<br />'; + if ($pCell === null) { +// We can't access the cell, so return a REF error + $cellValue = PHPExcel_Calculation_Functions::REF(); + } else { + $cellRef = $matches[6].$matches[7]; + if ($matches[2] > '') { + $matches[2] = trim($matches[2], "\"'"); + if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) { + // It's a Reference to an external workbook (not currently supported) + return $this->raiseFormulaError('Unable to access External Workbook'); + } +// echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />'; + $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]); + if ($pCellParent !== null) { + $cellSheet = $this->workbook->getSheetByName($matches[2]); + if ($cellSheet && $cellSheet->cellExists($cellRef)) { + $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false); + $pCell->attach($pCellParent); + } else { + $cellValue = null; + } + } else { + return $this->raiseFormulaError('Unable to access Cell Reference'); + } + $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue)); +// $cellRef = $matches[2].'!'.$cellRef; + } else { +// echo '$cellRef='.$cellRef.' in current worksheet<br />'; + $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet'); + if ($pCellParent->isDataSet($cellRef)) { + $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false); + $pCell->attach($pCellParent); + } else { + $cellValue = null; + } + $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->showTypeDetails($cellValue)); + } + } + } + $stack->push('Value', $cellValue, $cellRef); + + // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) { +// echo 'Token is a function<br />'; + $functionName = $matches[1]; + $argCount = $stack->pop(); + $argCount = $argCount['value']; + if ($functionName != 'MKMATRIX') { + $this->_debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's')); + } + if ((isset(self::$PHPExcelFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function + if (isset(self::$PHPExcelFunctions[$functionName])) { + $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$PHPExcelFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$PHPExcelFunctions[$functionName]['passCellReference']); + } elseif (isset(self::$controlFunctions[$functionName])) { + $functionCall = self::$controlFunctions[$functionName]['functionCall']; + $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']); + $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']); + } + // get the arguments for this function +// echo 'Function '.$functionName.' expects '.$argCount.' arguments<br />'; + $args = $argArrayVals = array(); + for ($i = 0; $i < $argCount; ++$i) { + $arg = $stack->pop(); + $a = $argCount - $i - 1; + if (($passByReference) && + (isset(self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) && + (self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) { + if ($arg['reference'] === null) { + $args[] = $cellID; + if ($functionName != 'MKMATRIX') { + $argArrayVals[] = $this->showValue($cellID); + } + } else { + $args[] = $arg['reference']; + if ($functionName != 'MKMATRIX') { + $argArrayVals[] = $this->showValue($arg['reference']); + } + } + } else { + $args[] = self::unwrapResult($arg['value']); + if ($functionName != 'MKMATRIX') { + $argArrayVals[] = $this->showValue($arg['value']); + } + } + } + // Reverse the order of the arguments + krsort($args); + if (($passByReference) && ($argCount == 0)) { + $args[] = $cellID; + $argArrayVals[] = $this->showValue($cellID); + } +// echo 'Arguments are: '; +// print_r($args); +// echo '<br />'; + if ($functionName != 'MKMATRIX') { + if ($this->_debugLog->getWriteDebugLog()) { + krsort($argArrayVals); + $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator.' ', PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )'); + } + } + // Process each argument in turn, building the return value as an array +// if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) { +// $operand1 = $args[1]; +// $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->showValue($operand1)); +// $result = array(); +// $row = 0; +// foreach($operand1 as $args) { +// if (is_array($args)) { +// foreach($args as $arg) { +// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($arg), ' )'); +// $r = call_user_func_array($functionCall, $arg); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r)); +// $result[$row][] = $r; +// } +// ++$row; +// } else { +// $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($args), ' )'); +// $r = call_user_func_array($functionCall, $args); +// $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r)); +// $result[] = $r; +// } +// } +// } else { + // Process the argument with the appropriate function call + if ($passCellReference) { + $args[] = $pCell; + } + if (strpos($functionCall, '::') !== false) { + $result = call_user_func_array(explode('::', $functionCall), $args); + } else { + foreach ($args as &$arg) { + $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg); + } + unset($arg); + $result = call_user_func_array($functionCall, $args); + } + if ($functionName != 'MKMATRIX') { + $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result)); + } + $stack->push('Value', self::wrapResult($result)); + } + + } else { + // if the token is a number, boolean, string or an Excel error, push it onto the stack + if (isset(self::$excelConstants[strtoupper($token)])) { + $excelConstant = strtoupper($token); +// echo 'Token is a PHPExcel constant: '.$excelConstant.'<br />'; + $stack->push('Constant Value', self::$excelConstants[$excelConstant]); + $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant])); + } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) { +// echo 'Token is a number, boolean, string, null or an Excel error<br />'; + $stack->push('Value', $token); + // if the token is a named range, push the named range name onto the stack + } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) { +// echo 'Token is a named range<br />'; + $namedRange = $matches[6]; +// echo 'Named Range is '.$namedRange.'<br />'; + $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange); + $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellWorksheet : null), false); + $pCell->attach($pCellParent); + $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->showTypeDetails($cellValue)); + $stack->push('Named Range', $cellValue, $namedRange); + } else { + return $this->raiseFormulaError("undefined variable '$token'"); + } + } + } + // when we're out of tokens, the stack should have a single element, the final result + if ($stack->count() != 1) { + return $this->raiseFormulaError("internal error"); + } + $output = $stack->pop(); + $output = $output['value']; + +// if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) { +// return array_shift(PHPExcel_Calculation_Functions::flattenArray($output)); +// } + return $output; + } + + + private function validateBinaryOperand($cellID, &$operand, &$stack) + { + if (is_array($operand)) { + if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) { + do { + $operand = array_pop($operand); + } while (is_array($operand)); + } + } + // Numbers, matrices and booleans can pass straight through, as they're already valid + if (is_string($operand)) { + // We only need special validations for the operand if it is a string + // Start by stripping off the quotation marks we use to identify true excel string values internally + if ($operand > '' && $operand{0} == '"') { + $operand = self::unwrapResult($operand); + } + // If the string is a numeric value, we treat it as a numeric, so no further testing + if (!is_numeric($operand)) { + // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations + if ($operand > '' && $operand{0} == '#') { + $stack->push('Value', $operand); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand)); + return false; + } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) { + // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations + $stack->push('Value', '#VALUE!'); + $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!')); + return false; + } + } + } + + // return a true if the value of the operand is one that we can use in normal binary operations + return true; + } + + + private function executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays = false) + { + // If we're dealing with matrix operations, we want a matrix result + if ((is_array($operand1)) || (is_array($operand2))) { + $result = array(); + if ((is_array($operand1)) && (!is_array($operand2))) { + foreach ($operand1 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2)); + $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } elseif ((!is_array($operand1)) && (is_array($operand2))) { + foreach ($operand2 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData)); + $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } else { + if (!$recursingArrays) { + self::checkMatrixOperands($operand1, $operand2, 2); + } + foreach ($operand1 as $x => $operandData) { + $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x])); + $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true); + $r = $stack->pop(); + $result[$x] = $r['value']; + } + } + // Log the result details + $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Array', $result); + return true; + } + + // Simple validate the two operands if they are string values + if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') { + $operand1 = self::unwrapResult($operand1); + } + if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') { + $operand2 = self::unwrapResult($operand2); + } + + // Use case insensitive comparaison if not OpenOffice mode + if (PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + if (is_string($operand1)) { + $operand1 = strtoupper($operand1); + } + if (is_string($operand2)) { + $operand2 = strtoupper($operand2); + } + } + + $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE; + + // execute the necessary operation + switch ($operation) { + // Greater than + case '>': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0; + } else { + $result = ($operand1 > $operand2); + } + break; + // Less than + case '<': + if ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0; + } else { + $result = ($operand1 < $operand2); + } + break; + // Equality + case '=': + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = (abs($operand1 - $operand2) < $this->delta); + } else { + $result = strcmp($operand1, $operand2) == 0; + } + break; + // Greater than or equal + case '>=': + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 > $operand2)); + } elseif ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0; + } else { + $result = strcmp($operand1, $operand2) >= 0; + } + break; + // Less than or equal + case '<=': + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 < $operand2)); + } elseif ($useLowercaseFirstComparison) { + $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0; + } else { + $result = strcmp($operand1, $operand2) <= 0; + } + break; + // Inequality + case '<>': + if (is_numeric($operand1) && is_numeric($operand2)) { + $result = (abs($operand1 - $operand2) > 1E-14); + } else { + $result = strcmp($operand1, $operand2) != 0; + } + break; + } + + // Log the result details + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Value', $result); + return true; + } + + /** + * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters + * @param string $str1 First string value for the comparison + * @param string $str2 Second string value for the comparison + * @return integer + */ + private function strcmpLowercaseFirst($str1, $str2) + { + $inversedStr1 = PHPExcel_Shared_String::StrCaseReverse($str1); + $inversedStr2 = PHPExcel_Shared_String::StrCaseReverse($str2); + + return strcmp($inversedStr1, $inversedStr2); + } + + private function executeNumericBinaryOperation($cellID, $operand1, $operand2, $operation, $matrixFunction, &$stack) + { + // Validate the two operands + if (!$this->validateBinaryOperand($cellID, $operand1, $stack)) { + return false; + } + if (!$this->validateBinaryOperand($cellID, $operand2, $stack)) { + return false; + } + + // If either of the operands is a matrix, we need to treat them both as matrices + // (converting the other operand to a matrix if need be); then perform the required + // matrix operation + if ((is_array($operand1)) || (is_array($operand2))) { + // Ensure that both operands are arrays/matrices of the same size + self::checkMatrixOperands($operand1, $operand2, 2); + + try { + // Convert operand 1 from a PHP array to a matrix + $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1); + // Perform the required operation against the operand 1 matrix, passing in operand 2 + $matrixResult = $matrix->$matrixFunction($operand2); + $result = $matrixResult->getArray(); + } catch (PHPExcel_Exception $ex) { + $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage()); + $result = '#VALUE!'; + } + } else { + if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) && + ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) || + (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) { + $result = PHPExcel_Calculation_Functions::VALUE(); + } else { + // If we're dealing with non-matrix operations, execute the necessary operation + switch ($operation) { + // Addition + case '+': + $result = $operand1 + $operand2; + break; + // Subtraction + case '-': + $result = $operand1 - $operand2; + break; + // Multiplication + case '*': + $result = $operand1 * $operand2; + break; + // Division + case '/': + if ($operand2 == 0) { + // Trap for Divide by Zero error + $stack->push('Value', '#DIV/0!'); + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails('#DIV/0!')); + return false; + } else { + $result = $operand1 / $operand2; + } + break; + // Power + case '^': + $result = pow($operand1, $operand2); + break; + } + } + } + + // Log the result details + $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result)); + // And push the result onto the stack + $stack->push('Value', $result); + return true; + } + + + // trigger an error, but nicely, if need be + protected function raiseFormulaError($errorMessage) + { + $this->formulaError = $errorMessage; + $this->cyclicReferenceStack->clear(); + if (!$this->suppressFormulaErrors) { + throw new PHPExcel_Calculation_Exception($errorMessage); + } + trigger_error($errorMessage, E_USER_ERROR); + } + + + /** + * Extract range values + * + * @param string &$pRange String based range representation + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param boolean $resetLog Flag indicating whether calculation log should be reset or not + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. + * @throws PHPExcel_Calculation_Exception + */ + public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true) + { + // Return value + $returnValue = array (); + +// echo 'extractCellRange('.$pRange.')', PHP_EOL; + if ($pSheet !== null) { + $pSheetName = $pSheet->getTitle(); +// echo 'Passed sheet name is '.$pSheetName.PHP_EOL; +// echo 'Range reference is '.$pRange.PHP_EOL; + if (strpos($pRange, '!') !== false) { +// echo '$pRange reference includes sheet reference', PHP_EOL; + list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); +// echo 'New sheet name is '.$pSheetName, PHP_EOL; +// echo 'Adjusted Range reference is '.$pRange, PHP_EOL; + $pSheet = $this->workbook->getSheetByName($pSheetName); + } + + // Extract range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); + $pRange = $pSheetName.'!'.$pRange; + if (!isset($aReferences[1])) { + // Single cell in range + sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow); + $cellValue = null; + if ($pSheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = null; + } + } else { + // Extract cell data for all cells in the range + foreach ($aReferences as $reference) { + // Extract range + sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow); + $cellValue = null; + if ($pSheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = null; + } + } + } + } + + return $returnValue; + } + + + /** + * Extract range values + * + * @param string &$pRange String based range representation + * @param PHPExcel_Worksheet $pSheet Worksheet + * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned. + * @param boolean $resetLog Flag indicating whether calculation log should be reset or not + * @throws PHPExcel_Calculation_Exception + */ + public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true) + { + // Return value + $returnValue = array (); + +// echo 'extractNamedRange('.$pRange.')<br />'; + if ($pSheet !== null) { + $pSheetName = $pSheet->getTitle(); +// echo 'Current sheet name is '.$pSheetName.'<br />'; +// echo 'Range reference is '.$pRange.'<br />'; + if (strpos($pRange, '!') !== false) { +// echo '$pRange reference includes sheet reference', PHP_EOL; + list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true); +// echo 'New sheet name is '.$pSheetName, PHP_EOL; +// echo 'Adjusted Range reference is '.$pRange, PHP_EOL; + $pSheet = $this->workbook->getSheetByName($pSheetName); + } + + // Named range? + $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet); + if ($namedRange !== null) { + $pSheet = $namedRange->getWorksheet(); +// echo 'Named Range '.$pRange.' ('; + $pRange = $namedRange->getRange(); + $splitRange = PHPExcel_Cell::splitRange($pRange); + // Convert row and column references + if (ctype_alpha($splitRange[0][0])) { + $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow(); + } elseif (ctype_digit($splitRange[0][0])) { + $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1]; + } +// echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'<br />'; + +// if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) { +// if (!$namedRange->getLocalOnly()) { +// $pSheet = $namedRange->getWorksheet(); +// } else { +// return $returnValue; +// } +// } + } else { + return PHPExcel_Calculation_Functions::REF(); + } + + // Extract range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); +// var_dump($aReferences); + if (!isset($aReferences[1])) { + // Single cell (or single column or row) in range + list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]); + $cellValue = null; + if ($pSheet->cellExists($aReferences[0])) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = null; + } + } else { + // Extract cell data for all cells in the range + foreach ($aReferences as $reference) { + // Extract range + list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($reference); +// echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'<br />'; + $cellValue = null; + if ($pSheet->cellExists($reference)) { + $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog); + } else { + $returnValue[$currentRow][$currentCol] = null; + } + } + } +// print_r($returnValue); +// echo '<br />'; + } + + return $returnValue; + } + + + /** + * Is a specific function implemented? + * + * @param string $pFunction Function Name + * @return boolean + */ + public function isImplemented($pFunction = '') + { + $pFunction = strtoupper($pFunction); + if (isset(self::$PHPExcelFunctions[$pFunction])) { + return (self::$PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY'); + } else { + return false; + } + } + + + /** + * Get a list of all implemented functions as an array of function objects + * + * @return array of PHPExcel_Calculation_Function + */ + public function listFunctions() + { + $returnValue = array(); + + foreach (self::$PHPExcelFunctions as $functionName => $function) { + if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { + $returnValue[$functionName] = new PHPExcel_Calculation_Function( + $function['category'], + $functionName, + $function['functionCall'] + ); + } + } + + return $returnValue; + } + + + /** + * Get a list of all Excel function names + * + * @return array + */ + public function listAllFunctionNames() + { + return array_keys(self::$PHPExcelFunctions); + } + + /** + * Get a list of implemented Excel function names + * + * @return array + */ + public function listFunctionNames() + { + $returnValue = array(); + foreach (self::$PHPExcelFunctions as $functionName => $function) { + if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') { + $returnValue[] = $functionName; + } + } + + return $returnValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Database.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Database.php new file mode 100644 index 00000000..b8d91cb6 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Database.php @@ -0,0 +1,676 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_Database + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Database +{ + /** + * fieldExtract + * + * Extracts the column ID to use for the data field. + * + * @access private + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param mixed $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @return string|NULL + * + */ + private static function fieldExtract($database, $field) + { + $field = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($field)); + $fieldNames = array_map('strtoupper', array_shift($database)); + + if (is_numeric($field)) { + $keys = array_keys($fieldNames); + return $keys[$field-1]; + } + $key = array_search($field, $fieldNames); + return ($key) ? $key : null; + } + + /** + * filter + * + * Parses the selection criteria, extracts the database rows that match those criteria, and + * returns that subset of rows. + * + * @access private + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return array of mixed + * + */ + private static function filter($database, $criteria) + { + $fieldNames = array_shift($database); + $criteriaNames = array_shift($criteria); + + // Convert the criteria into a set of AND/OR conditions with [:placeholders] + $testConditions = $testValues = array(); + $testConditionsCount = 0; + foreach ($criteriaNames as $key => $criteriaName) { + $testCondition = array(); + $testConditionCount = 0; + foreach ($criteria as $row => $criterion) { + if ($criterion[$key] > '') { + $testCondition[] = '[:'.$criteriaName.']'.PHPExcel_Calculation_Functions::ifCondition($criterion[$key]); + $testConditionCount++; + } + } + if ($testConditionCount > 1) { + $testConditions[] = 'OR(' . implode(',', $testCondition) . ')'; + $testConditionsCount++; + } elseif ($testConditionCount == 1) { + $testConditions[] = $testCondition[0]; + $testConditionsCount++; + } + } + + if ($testConditionsCount > 1) { + $testConditionSet = 'AND(' . implode(',', $testConditions) . ')'; + } elseif ($testConditionsCount == 1) { + $testConditionSet = $testConditions[0]; + } + + // Loop through each row of the database + foreach ($database as $dataRow => $dataValues) { + // Substitute actual values from the database row for our [:placeholders] + $testConditionList = $testConditionSet; + foreach ($criteriaNames as $key => $criteriaName) { + $k = array_search($criteriaName, $fieldNames); + if (isset($dataValues[$k])) { + $dataValue = $dataValues[$k]; + $dataValue = (is_string($dataValue)) ? PHPExcel_Calculation::wrapResult(strtoupper($dataValue)) : $dataValue; + $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList); + } + } + // evaluate the criteria against the row data + $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList); + // If the row failed to meet the criteria, remove it from the database + if (!$result) { + unset($database[$dataRow]); + } + } + + return $database; + } + + + private static function getFilteredColumn($database, $field, $criteria) + { + // reduce the database to a set of rows that match all the criteria + $database = self::filter($database, $criteria); + // extract an array of values for the requested column + $colData = array(); + foreach ($database as $row) { + $colData[] = $row[$field]; + } + + return $colData; + } + + /** + * DAVERAGE + * + * Averages the values in a column of a list or database that match conditions you specify. + * + * Excel Function: + * DAVERAGE(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DAVERAGE($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::AVERAGE( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DCOUNT + * + * Counts the cells that contain numbers in a column of a list or database that match conditions + * that you specify. + * + * Excel Function: + * DCOUNT(database,[field],criteria) + * + * Excel Function: + * DAVERAGE(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return integer + * + * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the + * database that match the criteria. + * + */ + public static function DCOUNT($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::COUNT( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DCOUNTA + * + * Counts the nonblank cells in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DCOUNTA(database,[field],criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return integer + * + * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the + * database that match the criteria. + * + */ + public static function DCOUNTA($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // reduce the database to a set of rows that match all the criteria + $database = self::filter($database, $criteria); + // extract an array of values for the requested column + $colData = array(); + foreach ($database as $row) { + $colData[] = $row[$field]; + } + + // Return + return PHPExcel_Calculation_Statistical::COUNTA( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DGET + * + * Extracts a single value from a column of a list or database that matches conditions that you + * specify. + * + * Excel Function: + * DGET(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return mixed + * + */ + public static function DGET($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + $colData = self::getFilteredColumn($database, $field, $criteria); + if (count($colData) > 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return $colData[0]; + } + + + /** + * DMAX + * + * Returns the largest number in a column of a list or database that matches conditions you that + * specify. + * + * Excel Function: + * DMAX(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DMAX($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::MAX( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DMIN + * + * Returns the smallest number in a column of a list or database that matches conditions you that + * specify. + * + * Excel Function: + * DMIN(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DMIN($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::MIN( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DPRODUCT + * + * Multiplies the values in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DPRODUCT(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DPRODUCT($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_MathTrig::PRODUCT( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DSTDEV + * + * Estimates the standard deviation of a population based on a sample by using the numbers in a + * column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSTDEV(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSTDEV($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::STDEV( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DSTDEVP + * + * Calculates the standard deviation of a population based on the entire population by using the + * numbers in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSTDEVP(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSTDEVP($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::STDEVP( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DSUM + * + * Adds the numbers in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DSUM(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DSUM($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_MathTrig::SUM( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DVAR + * + * Estimates the variance of a population based on a sample by using the numbers in a column + * of a list or database that match conditions that you specify. + * + * Excel Function: + * DVAR(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DVAR($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::VARFunc( + self::getFilteredColumn($database, $field, $criteria) + ); + } + + + /** + * DVARP + * + * Calculates the variance of a population based on the entire population by using the numbers + * in a column of a list or database that match conditions that you specify. + * + * Excel Function: + * DVARP(database,field,criteria) + * + * @access public + * @category Database Functions + * @param mixed[] $database The range of cells that makes up the list or database. + * A database is a list of related data in which rows of related + * information are records, and columns of data are fields. The + * first row of the list contains labels for each column. + * @param string|integer $field Indicates which column is used in the function. Enter the + * column label enclosed between double quotation marks, such as + * "Age" or "Yield," or a number (without quotation marks) that + * represents the position of the column within the list: 1 for + * the first column, 2 for the second column, and so on. + * @param mixed[] $criteria The range of cells that contains the conditions you specify. + * You can use any range for the criteria argument, as long as it + * includes at least one column label and at least one cell below + * the column label in which you specify a condition for the + * column. + * @return float + * + */ + public static function DVARP($database, $field, $criteria) + { + $field = self::fieldExtract($database, $field); + if (is_null($field)) { + return null; + } + + // Return + return PHPExcel_Calculation_Statistical::VARP( + self::getFilteredColumn($database, $field, $criteria) + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/DateTime.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/DateTime.php new file mode 100644 index 00000000..72f4c7a2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/DateTime.php @@ -0,0 +1,1553 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_DateTime + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_DateTime +{ + /** + * Identify if a year is a leap year or not + * + * @param integer $year The year to test + * @return boolean TRUE if the year is a leap year, otherwise FALSE + */ + public static function isLeapYear($year) + { + return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0)); + } + + + /** + * Return the number of days between two dates based on a 360 day calendar + * + * @param integer $startDay Day of month of the start date + * @param integer $startMonth Month of the start date + * @param integer $startYear Year of the start date + * @param integer $endDay Day of month of the start date + * @param integer $endMonth Month of the start date + * @param integer $endYear Year of the start date + * @param boolean $methodUS Whether to use the US method or the European method of calculation + * @return integer Number of days between the start date and the end date + */ + private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS) + { + if ($startDay == 31) { + --$startDay; + } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) { + $startDay = 30; + } + if ($endDay == 31) { + if ($methodUS && $startDay != 30) { + $endDay = 1; + if ($endMonth == 12) { + ++$endYear; + $endMonth = 1; + } else { + ++$endMonth; + } + } else { + $endDay = 30; + } + } + + return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360; + } + + + /** + * getDateValue + * + * @param string $dateValue + * @return mixed Excel date/time serial value, or string if error + */ + public static function getDateValue($dateValue) + { + if (!is_numeric($dateValue)) { + if ((is_string($dateValue)) && + (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) { + $dateValue = PHPExcel_Shared_Date::PHPToExcel($dateValue); + } else { + $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + $dateValue = self::DATEVALUE($dateValue); + PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType); + } + } + return $dateValue; + } + + + /** + * getTimeValue + * + * @param string $timeValue + * @return mixed Excel date/time serial value, or string if error + */ + private static function getTimeValue($timeValue) + { + $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + $timeValue = self::TIMEVALUE($timeValue); + PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType); + return $timeValue; + } + + + private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0) + { + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + $oMonth = (int) $PHPDateObject->format('m'); + $oYear = (int) $PHPDateObject->format('Y'); + + $adjustmentMonthsString = (string) $adjustmentMonths; + if ($adjustmentMonths > 0) { + $adjustmentMonthsString = '+'.$adjustmentMonths; + } + if ($adjustmentMonths != 0) { + $PHPDateObject->modify($adjustmentMonthsString.' months'); + } + $nMonth = (int) $PHPDateObject->format('m'); + $nYear = (int) $PHPDateObject->format('Y'); + + $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12); + if ($monthDiff != $adjustmentMonths) { + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-'.$adjustDays.' days'; + $PHPDateObject->modify($adjustDaysString); + } + return $PHPDateObject; + } + + + /** + * DATETIMENOW + * + * Returns the current date and time. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * NOW() + * + * @access public + * @category Date/Time Functions + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATETIMENOW() + { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $retValue = false; + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time()); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + $retValue = (integer) time(); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + $retValue = new DateTime(); + break; + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } + + + /** + * DATENOW + * + * Returns the current date. + * The NOW function is useful when you need to display the current date and time on a worksheet or + * calculate a value based on the current date and time, and have that value updated each time you + * open the worksheet. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * and time format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TODAY() + * + * @access public + * @category Date/Time Functions + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATENOW() + { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $retValue = false; + $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time())); + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + $retValue = (float) $excelDateTime; + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime); + break; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime); + break; + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } + + + /** + * DATE + * + * The DATE function returns a value that represents a particular date. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * DATE(year,month,day) + * + * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function. + * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted, + * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language. + * + * @access public + * @category Date/Time Functions + * @param integer $year The value of the year argument can include one to four digits. + * Excel interprets the year argument according to the configured + * date system: 1900 or 1904. + * If year is between 0 (zero) and 1899 (inclusive), Excel adds that + * value to 1900 to calculate the year. For example, DATE(108,1,2) + * returns January 2, 2008 (1900+108). + * If year is between 1900 and 9999 (inclusive), Excel uses that + * value as the year. For example, DATE(2008,1,2) returns January 2, + * 2008. + * If year is less than 0 or is 10000 or greater, Excel returns the + * #NUM! error value. + * @param integer $month A positive or negative integer representing the month of the year + * from 1 to 12 (January to December). + * If month is greater than 12, month adds that number of months to + * the first month in the year specified. For example, DATE(2008,14,2) + * returns the serial number representing February 2, 2009. + * If month is less than 1, month subtracts the magnitude of that + * number of months, plus 1, from the first month in the year + * specified. For example, DATE(2008,-3,2) returns the serial number + * representing September 2, 2007. + * @param integer $day A positive or negative integer representing the day of the month + * from 1 to 31. + * If day is greater than the number of days in the month specified, + * day adds that number of days to the first day in the month. For + * example, DATE(2008,1,35) returns the serial number representing + * February 4, 2008. + * If day is less than 1, day subtracts the magnitude that number of + * days, plus one, from the first day of the month specified. For + * example, DATE(2008,1,-15) returns the serial number representing + * December 16, 2007. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATE($year = 0, $month = 1, $day = 1) + { + $year = PHPExcel_Calculation_Functions::flattenSingleValue($year); + $month = PHPExcel_Calculation_Functions::flattenSingleValue($month); + $day = PHPExcel_Calculation_Functions::flattenSingleValue($day); + + if (($month !== null) && (!is_numeric($month))) { + $month = PHPExcel_Shared_Date::monthStringToNumber($month); + } + + if (($day !== null) && (!is_numeric($day))) { + $day = PHPExcel_Shared_Date::dayStringToNumber($day); + } + + $year = ($year !== null) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0; + $month = ($month !== null) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0; + $day = ($day !== null) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0; + if ((!is_numeric($year)) || + (!is_numeric($month)) || + (!is_numeric($day))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $year = (integer) $year; + $month = (integer) $month; + $day = (integer) $day; + + $baseYear = PHPExcel_Shared_Date::getExcelCalendar(); + // Validate parameters + if ($year < ($baseYear-1900)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (($year < $baseYear) && ($year >= ($baseYear-1900))) { + $year += 1900; + } + + if ($month < 1) { + // Handle year/month adjustment if month < 1 + --$month; + $year += ceil($month / 12) - 1; + $month = 13 - abs($month % 12); + } elseif ($month > 12) { + // Handle year/month adjustment if month > 12 + $year += floor($month / 12); + $month = ($month % 12); + } + + // Re-validate the year parameter after adjustments + if (($year < $baseYear) || ($year >= 10000)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day); + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue); + } + } + + + /** + * TIME + * + * The TIME function returns a value that represents a particular time. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TIME(hour,minute,second) + * + * @access public + * @category Date/Time Functions + * @param integer $hour A number from 0 (zero) to 32767 representing the hour. + * Any value greater than 23 will be divided by 24 and the remainder + * will be treated as the hour value. For example, TIME(27,0,0) = + * TIME(3,0,0) = .125 or 3:00 AM. + * @param integer $minute A number from 0 to 32767 representing the minute. + * Any value greater than 59 will be converted to hours and minutes. + * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM. + * @param integer $second A number from 0 to 32767 representing the second. + * Any value greater than 59 will be converted to hours, minutes, + * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148 + * or 12:33:20 AM + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function TIME($hour = 0, $minute = 0, $second = 0) + { + $hour = PHPExcel_Calculation_Functions::flattenSingleValue($hour); + $minute = PHPExcel_Calculation_Functions::flattenSingleValue($minute); + $second = PHPExcel_Calculation_Functions::flattenSingleValue($second); + + if ($hour == '') { + $hour = 0; + } + if ($minute == '') { + $minute = 0; + } + if ($second == '') { + $second = 0; + } + + if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $hour = (integer) $hour; + $minute = (integer) $minute; + $second = (integer) $second; + + if ($second < 0) { + $minute += floor($second / 60); + $second = 60 - abs($second % 60); + if ($second == 60) { + $second = 0; + } + } elseif ($second >= 60) { + $minute += floor($second / 60); + $second = $second % 60; + } + if ($minute < 0) { + $hour += floor($minute / 60); + $minute = 60 - abs($minute % 60); + if ($minute == 60) { + $minute = 0; + } + } elseif ($minute >= 60) { + $hour += floor($minute / 60); + $minute = $minute % 60; + } + + if ($hour > 23) { + $hour = $hour % 24; + } elseif ($hour < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + $date = 0; + $calendar = PHPExcel_Shared_Date::getExcelCalendar(); + if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) { + $date = 1; + } + return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600 + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + $dayAdjust = 0; + if ($hour < 0) { + $dayAdjust = floor($hour / 24); + $hour = 24 - abs($hour % 24); + if ($hour == 24) { + $hour = 0; + } + } elseif ($hour >= 24) { + $dayAdjust = floor($hour / 24); + $hour = $hour % 24; + } + $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second); + if ($dayAdjust != 0) { + $phpDateObject->modify($dayAdjust.' days'); + } + return $phpDateObject; + } + } + + + /** + * DATEVALUE + * + * Returns a value that represents a particular date. + * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp + * value. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * DATEVALUE(dateValue) + * + * @access public + * @category Date/Time Functions + * @param string $dateValue Text that represents a date in a Microsoft Excel date format. + * For example, "1/30/2008" or "30-Jan-2008" are text strings within + * quotation marks that represent dates. Using the default date + * system in Excel for Windows, date_text must represent a date from + * January 1, 1900, to December 31, 9999. Using the default date + * system in Excel for the Macintosh, date_text must represent a date + * from January 1, 1904, to December 31, 9999. DATEVALUE returns the + * #VALUE! error value if date_text is out of this range. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function DATEVALUE($dateValue = 1) + { + $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue), '"'); + // Strip any ordinals because they're allowed in Excel (English only) + $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue); + // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany) + $dateValue = str_replace(array('/', '.', '-', ' '), array(' ', ' ', ' ', ' '), $dateValue); + + $yearFound = false; + $t1 = explode(' ', $dateValue); + foreach ($t1 as &$t) { + if ((is_numeric($t)) && ($t > 31)) { + if ($yearFound) { + return PHPExcel_Calculation_Functions::VALUE(); + } else { + if ($t < 100) { + $t += 1900; + } + $yearFound = true; + } + } + } + if ((count($t1) == 1) && (strpos($t, ':') != false)) { + // We've been fed a time value without any date + return 0.0; + } elseif (count($t1) == 2) { + // We only have two parts of the date: either day/month or month/year + if ($yearFound) { + array_unshift($t1, 1); + } else { + array_push($t1, date('Y')); + } + } + unset($t); + $dateValue = implode(' ', $t1); + + $PHPDateArray = date_parse($dateValue); + if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { + $testVal1 = strtok($dateValue, '- '); + if ($testVal1 !== false) { + $testVal2 = strtok('- '); + if ($testVal2 !== false) { + $testVal3 = strtok('- '); + if ($testVal3 === false) { + $testVal3 = strftime('%Y'); + } + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3); + if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { + $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3); + if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + } + + if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { + // Execute function + if ($PHPDateArray['year'] == '') { + $PHPDateArray['year'] = strftime('%Y'); + } + if ($PHPDateArray['year'] < 1900) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if ($PHPDateArray['month'] == '') { + $PHPDateArray['month'] = strftime('%m'); + } + if ($PHPDateArray['day'] == '') { + $PHPDateArray['day'] = strftime('%d'); + } + $excelDateValue = floor( + PHPExcel_Shared_Date::FormattedPHPToExcel( + $PHPDateArray['year'], + $PHPDateArray['month'], + $PHPDateArray['day'], + $PHPDateArray['hour'], + $PHPDateArray['minute'], + $PHPDateArray['second'] + ) + ); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00'); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * TIMEVALUE + * + * Returns a value that represents a particular time. + * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp + * value. + * + * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time + * format of your regional settings. PHPExcel does not change cell formatting in this way. + * + * Excel Function: + * TIMEVALUE(timeValue) + * + * @access public + * @category Date/Time Functions + * @param string $timeValue A text string that represents a time in any one of the Microsoft + * Excel time formats; for example, "6:45 PM" and "18:45" text strings + * within quotation marks that represent time. + * Date information in time_text is ignored. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function TIMEVALUE($timeValue) + { + $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue), '"'); + $timeValue = str_replace(array('/', '.'), array('-', '-'), $timeValue); + + $PHPDateArray = date_parse($timeValue); + if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel( + $PHPDateArray['year'], + $PHPDateArray['month'], + $PHPDateArray['day'], + $PHPDateArray['hour'], + $PHPDateArray['minute'], + $PHPDateArray['second'] + ); + } else { + $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1; + } + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) $excelDateValue; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * DATEDIF + * + * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object + * or a standard date string + * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object + * or a standard date string + * @param string $unit + * @return integer Interval between the dates + */ + public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D') + { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit)); + + if (is_string($startDate = self::getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Validate parameters + if ($startDate >= $endDate) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $difference = $endDate - $startDate; + + $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate); + $startDays = $PHPStartDateObject->format('j'); + $startMonths = $PHPStartDateObject->format('n'); + $startYears = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + $endDays = $PHPEndDateObject->format('j'); + $endMonths = $PHPEndDateObject->format('n'); + $endYears = $PHPEndDateObject->format('Y'); + + $retVal = PHPExcel_Calculation_Functions::NaN(); + switch ($unit) { + case 'D': + $retVal = intval($difference); + break; + case 'M': + $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12); + // We're only interested in full months + if ($endDays < $startDays) { + --$retVal; + } + break; + case 'Y': + $retVal = intval($endYears - $startYears); + // We're only interested in full months + if ($endMonths < $startMonths) { + --$retVal; + } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) { + --$retVal; + } + break; + case 'MD': + if ($endDays < $startDays) { + $retVal = $endDays; + $PHPEndDateObject->modify('-'.$endDays.' days'); + $adjustDays = $PHPEndDateObject->format('j'); + if ($adjustDays > $startDays) { + $retVal += ($adjustDays - $startDays); + } + } else { + $retVal = $endDays - $startDays; + } + break; + case 'YM': + $retVal = intval($endMonths - $startMonths); + if ($retVal < 0) { + $retVal += 12; + } + // We're only interested in full months + if ($endDays < $startDays) { + --$retVal; + } + break; + case 'YD': + $retVal = intval($difference); + if ($endYears > $startYears) { + while ($endYears > $startYears) { + $PHPEndDateObject->modify('-1 year'); + $endYears = $PHPEndDateObject->format('Y'); + } + $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z'); + if ($retVal < 0) { + $retVal += 365; + } + } + break; + default: + $retVal = PHPExcel_Calculation_Functions::NaN(); + } + return $retVal; + } + + + /** + * DAYS360 + * + * Returns the number of days between two dates based on a 360-day year (twelve 30-day months), + * which is used in some accounting calculations. Use this function to help compute payments if + * your accounting system is based on twelve 30-day months. + * + * Excel Function: + * DAYS360(startDate,endDate[,method]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param boolean $method US or European Method + * FALSE or omitted: U.S. (NASD) method. If the starting date is + * the last day of a month, it becomes equal to the 30th of the + * same month. If the ending date is the last day of a month and + * the starting date is earlier than the 30th of a month, the + * ending date becomes equal to the 1st of the next month; + * otherwise the ending date becomes equal to the 30th of the + * same month. + * TRUE: European method. Starting dates and ending dates that + * occur on the 31st of a month become equal to the 30th of the + * same month. + * @return integer Number of days between start date and end date + */ + public static function DAYS360($startDate = 0, $endDate = 0, $method = false) + { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + + if (is_string($startDate = self::getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (!is_bool($method)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate); + $startDay = $PHPStartDateObject->format('j'); + $startMonth = $PHPStartDateObject->format('n'); + $startYear = $PHPStartDateObject->format('Y'); + + $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + $endDay = $PHPEndDateObject->format('j'); + $endMonth = $PHPEndDateObject->format('n'); + $endYear = $PHPEndDateObject->format('Y'); + + return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method); + } + + + /** + * YEARFRAC + * + * Calculates the fraction of the year represented by the number of whole days between two dates + * (the start_date and the end_date). + * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or + * obligations to assign to a specific term. + * + * Excel Function: + * YEARFRAC(startDate,endDate[,method]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param integer $method Method used for the calculation + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float fraction of the year + */ + public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0) + { + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + $method = PHPExcel_Calculation_Functions::flattenSingleValue($method); + + if (is_string($startDate = self::getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($endDate = self::getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) { + switch ($method) { + case 0: + return self::DAYS360($startDate, $endDate) / 360; + case 1: + $days = self::DATEDIF($startDate, $endDate); + $startYear = self::YEAR($startDate); + $endYear = self::YEAR($endDate); + $years = $endYear - $startYear + 1; + $leapDays = 0; + if ($years == 1) { + if (self::isLeapYear($endYear)) { + $startMonth = self::MONTHOFYEAR($startDate); + $endMonth = self::MONTHOFYEAR($endDate); + $endDay = self::DAYOFMONTH($endDate); + if (($startMonth < 3) || + (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) { + $leapDays += 1; + } + } + } else { + for ($year = $startYear; $year <= $endYear; ++$year) { + if ($year == $startYear) { + $startMonth = self::MONTHOFYEAR($startDate); + $startDay = self::DAYOFMONTH($startDate); + if ($startMonth < 3) { + $leapDays += (self::isLeapYear($year)) ? 1 : 0; + } + } elseif ($year == $endYear) { + $endMonth = self::MONTHOFYEAR($endDate); + $endDay = self::DAYOFMONTH($endDate); + if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) { + $leapDays += (self::isLeapYear($year)) ? 1 : 0; + } + } else { + $leapDays += (self::isLeapYear($year)) ? 1 : 0; + } + } + if ($years == 2) { + if (($leapDays == 0) && (self::isLeapYear($startYear)) && ($days > 365)) { + $leapDays = 1; + } elseif ($days < 366) { + $years = 1; + } + } + $leapDays /= $years; + } + return $days / (365 + $leapDays); + case 2: + return self::DATEDIF($startDate, $endDate) / 360; + case 3: + return self::DATEDIF($startDate, $endDate) / 365; + case 4: + return self::DAYS360($startDate, $endDate, true) / 360; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * NETWORKDAYS + * + * Returns the number of whole working days between start_date and end_date. Working days + * exclude weekends and any dates identified in holidays. + * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days + * worked during a specific term. + * + * Excel Function: + * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date + * timestamp (integer), PHP DateTime object, or a standard date + * strings that will be excluded from the working calendar, such + * as state and federal holidays and floating holidays. + * @return integer Interval between the dates + */ + public static function NETWORKDAYS($startDate, $endDate) + { + // Retrieve the mandatory start and end date that are referenced in the function definition + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate); + // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days + $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + array_shift($dateArgs); + array_shift($dateArgs); + + // Validate the start and end dates + if (is_string($startDate = $sDate = self::getDateValue($startDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $startDate = (float) floor($startDate); + if (is_string($endDate = $eDate = self::getDateValue($endDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $endDate = (float) floor($endDate); + + if ($sDate > $eDate) { + $startDate = $eDate; + $endDate = $sDate; + } + + // Execute function + $startDoW = 6 - self::DAYOFWEEK($startDate, 2); + if ($startDoW < 0) { + $startDoW = 0; + } + $endDoW = self::DAYOFWEEK($endDate, 2); + if ($endDoW >= 6) { + $endDoW = 0; + } + + $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5; + $partWeekDays = $endDoW + $startDoW; + if ($partWeekDays > 5) { + $partWeekDays -= 5; + } + + // Test any extra holiday parameters + $holidayCountedArray = array(); + foreach ($dateArgs as $holidayDate) { + if (is_string($holidayDate = self::getDateValue($holidayDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if ((self::DAYOFWEEK($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) { + --$partWeekDays; + $holidayCountedArray[] = $holidayDate; + } + } + } + + if ($sDate > $eDate) { + return 0 - ($wholeWeekDays + $partWeekDays); + } + return $wholeWeekDays + $partWeekDays; + } + + + /** + * WORKDAY + * + * Returns the date that is the indicated number of working days before or after a date (the + * starting date). Working days exclude weekends and any dates identified as holidays. + * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected + * delivery times, or the number of days of work performed. + * + * Excel Function: + * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]]) + * + * @access public + * @category Date/Time Functions + * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param integer $endDays The number of nonweekend and nonholiday days before or after + * startDate. A positive value for days yields a future date; a + * negative value yields a past date. + * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date + * timestamp (integer), PHP DateTime object, or a standard date + * strings that will be excluded from the working calendar, such + * as state and federal holidays and floating holidays. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function WORKDAY($startDate, $endDays) + { + // Retrieve the mandatory start date and days that are referenced in the function definition + $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate); + $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays); + // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days + $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + array_shift($dateArgs); + array_shift($dateArgs); + + if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $startDate = (float) floor($startDate); + $endDays = (int) floor($endDays); + // If endDays is 0, we always return startDate + if ($endDays == 0) { + return $startDate; + } + + $decrementing = ($endDays < 0) ? true : false; + + // Adjust the start date if it falls over a weekend + + $startDoW = self::DAYOFWEEK($startDate, 3); + if (self::DAYOFWEEK($startDate, 3) >= 5) { + $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW; + ($decrementing) ? $endDays++ : $endDays--; + } + + // Add endDays + $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5); + + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::DAYOFWEEK($endDate, 3); + if ($endDoW >= 5) { + $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW; + } + + // Test any extra holiday parameters + if (!empty($dateArgs)) { + $holidayCountedArray = $holidayDates = array(); + foreach ($dateArgs as $holidayDate) { + if (($holidayDate !== null) && (trim($holidayDate) > '')) { + if (is_string($holidayDate = self::getDateValue($holidayDate))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (self::DAYOFWEEK($holidayDate, 3) < 5) { + $holidayDates[] = $holidayDate; + } + } + } + if ($decrementing) { + rsort($holidayDates, SORT_NUMERIC); + } else { + sort($holidayDates, SORT_NUMERIC); + } + foreach ($holidayDates as $holidayDate) { + if ($decrementing) { + if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + --$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + } else { + if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) { + if (!in_array($holidayDate, $holidayCountedArray)) { + ++$endDate; + $holidayCountedArray[] = $holidayDate; + } + } + } + // Adjust the calculated end date if it falls over a weekend + $endDoW = self::DAYOFWEEK($endDate, 3); + if ($endDoW >= 5) { + $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW; + } + } + } + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) $endDate; + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return PHPExcel_Shared_Date::ExcelToPHPObject($endDate); + } + } + + + /** + * DAYOFMONTH + * + * Returns the day of the month, for a specified date. The day is given as an integer + * ranging from 1 to 31. + * + * Excel Function: + * DAY(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Day of the month + */ + public static function DAYOFMONTH($dateValue = 1) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if ($dateValue === null) { + $dateValue = 1; + } elseif (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue == 0.0) { + return 0; + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('j'); + } + + + /** + * DAYOFWEEK + * + * Returns the day of the week for a specified date. The day is given as an integer + * ranging from 0 to 7 (dependent on the requested style). + * + * Excel Function: + * WEEKDAY(dateValue[,style]) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $style A number that determines the type of return value + * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday). + * 2 Numbers 1 (Monday) through 7 (Sunday). + * 3 Numbers 0 (Monday) through 6 (Sunday). + * @return int Day of the week value + */ + public static function DAYOFWEEK($dateValue = 1, $style = 1) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $style = PHPExcel_Calculation_Functions::flattenSingleValue($style); + + if (!is_numeric($style)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif (($style < 1) || ($style > 3)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $style = floor($style); + + if ($dateValue === null) { + $dateValue = 1; + } elseif (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + $DoW = $PHPDateObject->format('w'); + + $firstDay = 1; + switch ($style) { + case 1: + ++$DoW; + break; + case 2: + if ($DoW == 0) { + $DoW = 7; + } + break; + case 3: + if ($DoW == 0) { + $DoW = 7; + } + $firstDay = 0; + --$DoW; + break; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) { + // Test for Excel's 1900 leap year, and introduce the error as required + if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) { + --$DoW; + if ($DoW < $firstDay) { + $DoW += 7; + } + } + } + + return (int) $DoW; + } + + + /** + * WEEKOFYEAR + * + * Returns the week of the year for a specified date. + * The WEEKNUM function considers the week containing January 1 to be the first week of the year. + * However, there is a European standard that defines the first week as the one with the majority + * of days (four or more) falling in the new year. This means that for years in which there are + * three days or less in the first week of January, the WEEKNUM function returns week numbers + * that are incorrect according to the European standard. + * + * Excel Function: + * WEEKNUM(dateValue[,style]) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param boolean $method Week begins on Sunday or Monday + * 1 or omitted Week begins on Sunday. + * 2 Week begins on Monday. + * @return int Week Number + */ + public static function WEEKOFYEAR($dateValue = 1, $method = 1) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $method = PHPExcel_Calculation_Functions::flattenSingleValue($method); + + if (!is_numeric($method)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif (($method < 1) || ($method > 2)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $method = floor($method); + + if ($dateValue === null) { + $dateValue = 1; + } elseif (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + $dayOfYear = $PHPDateObject->format('z'); + $dow = $PHPDateObject->format('w'); + $PHPDateObject->modify('-' . $dayOfYear . ' days'); + $dow = $PHPDateObject->format('w'); + $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7); + $dayOfYear -= $daysInFirstWeek; + $weekOfYear = ceil($dayOfYear / 7) + 1; + + return (int) $weekOfYear; + } + + + /** + * MONTHOFYEAR + * + * Returns the month of a date represented by a serial number. + * The month is given as an integer, ranging from 1 (January) to 12 (December). + * + * Excel Function: + * MONTH(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Month of the year + */ + public static function MONTHOFYEAR($dateValue = 1) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if ($dateValue === null) { + $dateValue = 1; + } elseif (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('n'); + } + + + /** + * YEAR + * + * Returns the year corresponding to a date. + * The year is returned as an integer in the range 1900-9999. + * + * Excel Function: + * YEAR(dateValue) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @return int Year + */ + public static function YEAR($dateValue = 1) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + + if ($dateValue === null) { + $dateValue = 1; + } elseif (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($dateValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Execute function + $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue); + + return (int) $PHPDateObject->format('Y'); + } + + + /** + * HOUROFDAY + * + * Returns the hour of a time value. + * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.). + * + * Excel Function: + * HOUR(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Hour + */ + public static function HOUROFDAY($timeValue = 0) + { + $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue, '/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue, 1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('G', $timeValue); + } + + + /** + * MINUTEOFHOUR + * + * Returns the minutes of a time value. + * The minute is given as an integer, ranging from 0 to 59. + * + * Excel Function: + * MINUTE(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Minute + */ + public static function MINUTEOFHOUR($timeValue = 0) + { + $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue, '/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue, 1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('i', $timeValue); + } + + + /** + * SECONDOFMINUTE + * + * Returns the seconds of a time value. + * The second is given as an integer in the range 0 (zero) to 59. + * + * Excel Function: + * SECOND(timeValue) + * + * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard time string + * @return int Second + */ + public static function SECONDOFMINUTE($timeValue = 0) + { + $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue); + + if (!is_numeric($timeValue)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $testVal = strtok($timeValue, '/-: '); + if (strlen($testVal) < strlen($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $timeValue = self::getTimeValue($timeValue); + if (is_string($timeValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + // Execute function + if ($timeValue >= 1) { + $timeValue = fmod($timeValue, 1); + } elseif ($timeValue < 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue); + + return (int) gmdate('s', $timeValue); + } + + + /** + * EDATE + * + * Returns the serial number that represents the date that is the indicated number of months + * before or after a specified date (the start_date). + * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month + * as the date of issue. + * + * Excel Function: + * EDATE(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function EDATE($dateValue = 1, $adjustmentMonths = 0) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths); + + if (!is_numeric($adjustmentMonths)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $adjustmentMonths = floor($adjustmentMonths); + + if (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject)); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return $PHPDateObject; + } + } + + + /** + * EOMONTH + * + * Returns the date value for the last day of the month that is the indicated number of months + * before or after start_date. + * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month. + * + * Excel Function: + * EOMONTH(dateValue,adjustmentMonths) + * + * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer), + * PHP DateTime object, or a standard date string + * @param int $adjustmentMonths The number of months before or after start_date. + * A positive value for months yields a future date; + * a negative value yields a past date. + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0) + { + $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue); + $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths); + + if (!is_numeric($adjustmentMonths)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $adjustmentMonths = floor($adjustmentMonths); + + if (is_string($dateValue = self::getDateValue($dateValue))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Execute function + $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths+1); + $adjustDays = (int) $PHPDateObject->format('d'); + $adjustDaysString = '-' . $adjustDays . ' days'; + $PHPDateObject->modify($adjustDaysString); + + switch (PHPExcel_Calculation_Functions::getReturnDateType()) { + case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL: + return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC: + return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject)); + case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT: + return $PHPDateObject; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Engineering.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Engineering.php new file mode 100644 index 00000000..75e27847 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Engineering.php @@ -0,0 +1,2650 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** EULER */ +define('EULER', 2.71828182845904523536); + +/** + * PHPExcel_Calculation_Engineering + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Engineering +{ + /** + * Details of the Units of measure that can be used in CONVERTUOM() + * + * @var mixed[] + */ + private static $conversionUnits = array( + 'g' => array('Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true), + 'sg' => array('Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false), + 'lbm' => array('Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false), + 'u' => array('Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true), + 'ozm' => array('Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false), + 'm' => array('Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true), + 'mi' => array('Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false), + 'Nmi' => array('Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false), + 'in' => array('Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false), + 'ft' => array('Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false), + 'yd' => array('Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false), + 'ang' => array('Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true), + 'Pica' => array('Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false), + 'yr' => array('Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false), + 'day' => array('Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false), + 'hr' => array('Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false), + 'mn' => array('Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false), + 'sec' => array('Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true), + 'Pa' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true), + 'p' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true), + 'atm' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true), + 'at' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true), + 'mmHg' => array('Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true), + 'N' => array('Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true), + 'dyn' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true), + 'dy' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true), + 'lbf' => array('Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false), + 'J' => array('Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true), + 'e' => array('Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true), + 'c' => array('Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true), + 'cal' => array('Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true), + 'eV' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true), + 'ev' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true), + 'HPh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false), + 'hh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false), + 'Wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true), + 'wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true), + 'flb' => array('Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false), + 'BTU' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false), + 'btu' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false), + 'HP' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false), + 'h' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false), + 'W' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true), + 'w' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true), + 'T' => array('Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true), + 'ga' => array('Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true), + 'C' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false), + 'cel' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false), + 'F' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false), + 'fah' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false), + 'K' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false), + 'kel' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false), + 'tsp' => array('Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false), + 'tbs' => array('Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false), + 'oz' => array('Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false), + 'cup' => array('Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false), + 'pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false), + 'us_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false), + 'uk_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false), + 'qt' => array('Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false), + 'gal' => array('Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false), + 'l' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true), + 'lt' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true), + ); + + /** + * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() + * + * @var mixed[] + */ + private static $conversionMultipliers = array( + 'Y' => array('multiplier' => 1E24, 'name' => 'yotta'), + 'Z' => array('multiplier' => 1E21, 'name' => 'zetta'), + 'E' => array('multiplier' => 1E18, 'name' => 'exa'), + 'P' => array('multiplier' => 1E15, 'name' => 'peta'), + 'T' => array('multiplier' => 1E12, 'name' => 'tera'), + 'G' => array('multiplier' => 1E9, 'name' => 'giga'), + 'M' => array('multiplier' => 1E6, 'name' => 'mega'), + 'k' => array('multiplier' => 1E3, 'name' => 'kilo'), + 'h' => array('multiplier' => 1E2, 'name' => 'hecto'), + 'e' => array('multiplier' => 1E1, 'name' => 'deka'), + 'd' => array('multiplier' => 1E-1, 'name' => 'deci'), + 'c' => array('multiplier' => 1E-2, 'name' => 'centi'), + 'm' => array('multiplier' => 1E-3, 'name' => 'milli'), + 'u' => array('multiplier' => 1E-6, 'name' => 'micro'), + 'n' => array('multiplier' => 1E-9, 'name' => 'nano'), + 'p' => array('multiplier' => 1E-12, 'name' => 'pico'), + 'f' => array('multiplier' => 1E-15, 'name' => 'femto'), + 'a' => array('multiplier' => 1E-18, 'name' => 'atto'), + 'z' => array('multiplier' => 1E-21, 'name' => 'zepto'), + 'y' => array('multiplier' => 1E-24, 'name' => 'yocto'), + ); + + /** + * Details of the Units of measure conversion factors, organised by group + * + * @var mixed[] + */ + private static $unitConversions = array( + 'Mass' => array( + 'g' => array( + 'g' => 1.0, + 'sg' => 6.85220500053478E-05, + 'lbm' => 2.20462291469134E-03, + 'u' => 6.02217000000000E+23, + 'ozm' => 3.52739718003627E-02, + ), + 'sg' => array( + 'g' => 1.45938424189287E+04, + 'sg' => 1.0, + 'lbm' => 3.21739194101647E+01, + 'u' => 8.78866000000000E+27, + 'ozm' => 5.14782785944229E+02, + ), + 'lbm' => array( + 'g' => 4.5359230974881148E+02, + 'sg' => 3.10810749306493E-02, + 'lbm' => 1.0, + 'u' => 2.73161000000000E+26, + 'ozm' => 1.60000023429410E+01, + ), + 'u' => array( + 'g' => 1.66053100460465E-24, + 'sg' => 1.13782988532950E-28, + 'lbm' => 3.66084470330684E-27, + 'u' => 1.0, + 'ozm' => 5.85735238300524E-26, + ), + 'ozm' => array( + 'g' => 2.83495152079732E+01, + 'sg' => 1.94256689870811E-03, + 'lbm' => 6.24999908478882E-02, + 'u' => 1.70725600000000E+25, + 'ozm' => 1.0, + ), + ), + 'Distance' => array( + 'm' => array( + 'm' => 1.0, + 'mi' => 6.21371192237334E-04, + 'Nmi' => 5.39956803455724E-04, + 'in' => 3.93700787401575E+01, + 'ft' => 3.28083989501312E+00, + 'yd' => 1.09361329797891E+00, + 'ang' => 1.00000000000000E+10, + 'Pica' => 2.83464566929116E+03, + ), + 'mi' => array( + 'm' => 1.60934400000000E+03, + 'mi' => 1.0, + 'Nmi' => 8.68976241900648E-01, + 'in' => 6.33600000000000E+04, + 'ft' => 5.28000000000000E+03, + 'yd' => 1.76000000000000E+03, + 'ang' => 1.60934400000000E+13, + 'Pica' => 4.56191999999971E+06, + ), + 'Nmi' => array( + 'm' => 1.85200000000000E+03, + 'mi' => 1.15077944802354E+00, + 'Nmi' => 1.0, + 'in' => 7.29133858267717E+04, + 'ft' => 6.07611548556430E+03, + 'yd' => 2.02537182785694E+03, + 'ang' => 1.85200000000000E+13, + 'Pica' => 5.24976377952723E+06, + ), + 'in' => array( + 'm' => 2.54000000000000E-02, + 'mi' => 1.57828282828283E-05, + 'Nmi' => 1.37149028077754E-05, + 'in' => 1.0, + 'ft' => 8.33333333333333E-02, + 'yd' => 2.77777777686643E-02, + 'ang' => 2.54000000000000E+08, + 'Pica' => 7.19999999999955E+01, + ), + 'ft' => array( + 'm' => 3.04800000000000E-01, + 'mi' => 1.89393939393939E-04, + 'Nmi' => 1.64578833693305E-04, + 'in' => 1.20000000000000E+01, + 'ft' => 1.0, + 'yd' => 3.33333333223972E-01, + 'ang' => 3.04800000000000E+09, + 'Pica' => 8.63999999999946E+02, + ), + 'yd' => array( + 'm' => 9.14400000300000E-01, + 'mi' => 5.68181818368230E-04, + 'Nmi' => 4.93736501241901E-04, + 'in' => 3.60000000118110E+01, + 'ft' => 3.00000000000000E+00, + 'yd' => 1.0, + 'ang' => 9.14400000300000E+09, + 'Pica' => 2.59200000085023E+03, + ), + 'ang' => array( + 'm' => 1.00000000000000E-10, + 'mi' => 6.21371192237334E-14, + 'Nmi' => 5.39956803455724E-14, + 'in' => 3.93700787401575E-09, + 'ft' => 3.28083989501312E-10, + 'yd' => 1.09361329797891E-10, + 'ang' => 1.0, + 'Pica' => 2.83464566929116E-07, + ), + 'Pica' => array( + 'm' => 3.52777777777800E-04, + 'mi' => 2.19205948372629E-07, + 'Nmi' => 1.90484761219114E-07, + 'in' => 1.38888888888898E-02, + 'ft' => 1.15740740740748E-03, + 'yd' => 3.85802469009251E-04, + 'ang' => 3.52777777777800E+06, + 'Pica' => 1.0, + ), + ), + 'Time' => array( + 'yr' => array( + 'yr' => 1.0, + 'day' => 365.25, + 'hr' => 8766.0, + 'mn' => 525960.0, + 'sec' => 31557600.0, + ), + 'day' => array( + 'yr' => 2.73785078713210E-03, + 'day' => 1.0, + 'hr' => 24.0, + 'mn' => 1440.0, + 'sec' => 86400.0, + ), + 'hr' => array( + 'yr' => 1.14077116130504E-04, + 'day' => 4.16666666666667E-02, + 'hr' => 1.0, + 'mn' => 60.0, + 'sec' => 3600.0, + ), + 'mn' => array( + 'yr' => 1.90128526884174E-06, + 'day' => 6.94444444444444E-04, + 'hr' => 1.66666666666667E-02, + 'mn' => 1.0, + 'sec' => 60.0, + ), + 'sec' => array( + 'yr' => 3.16880878140289E-08, + 'day' => 1.15740740740741E-05, + 'hr' => 2.77777777777778E-04, + 'mn' => 1.66666666666667E-02, + 'sec' => 1.0, + ), + ), + 'Pressure' => array( + 'Pa' => array( + 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923299998193E-06, + 'at' => 9.86923299998193E-06, + 'mmHg' => 7.50061707998627E-03, + ), + 'p' => array( + 'Pa' => 1.0, + 'p' => 1.0, + 'atm' => 9.86923299998193E-06, + 'at' => 9.86923299998193E-06, + 'mmHg' => 7.50061707998627E-03, + ), + 'atm' => array( + 'Pa' => 1.01324996583000E+05, + 'p' => 1.01324996583000E+05, + 'atm' => 1.0, + 'at' => 1.0, + 'mmHg' => 760.0, + ), + 'at' => array( + 'Pa' => 1.01324996583000E+05, + 'p' => 1.01324996583000E+05, + 'atm' => 1.0, + 'at' => 1.0, + 'mmHg' => 760.0, + ), + 'mmHg' => array( + 'Pa' => 1.33322363925000E+02, + 'p' => 1.33322363925000E+02, + 'atm' => 1.31578947368421E-03, + 'at' => 1.31578947368421E-03, + 'mmHg' => 1.0, + ), + ), + 'Force' => array( + 'N' => array( + 'N' => 1.0, + 'dyn' => 1.0E+5, + 'dy' => 1.0E+5, + 'lbf' => 2.24808923655339E-01, + ), + 'dyn' => array( + 'N' => 1.0E-5, + 'dyn' => 1.0, + 'dy' => 1.0, + 'lbf' => 2.24808923655339E-06, + ), + 'dy' => array( + 'N' => 1.0E-5, + 'dyn' => 1.0, + 'dy' => 1.0, + 'lbf' => 2.24808923655339E-06, + ), + 'lbf' => array( + 'N' => 4.448222, + 'dyn' => 4.448222E+5, + 'dy' => 4.448222E+5, + 'lbf' => 1.0, + ), + ), + 'Energy' => array( + 'J' => array( + 'J' => 1.0, + 'e' => 9.99999519343231E+06, + 'c' => 2.39006249473467E-01, + 'cal' => 2.38846190642017E-01, + 'eV' => 6.24145700000000E+18, + 'ev' => 6.24145700000000E+18, + 'HPh' => 3.72506430801000E-07, + 'hh' => 3.72506430801000E-07, + 'Wh' => 2.77777916238711E-04, + 'wh' => 2.77777916238711E-04, + 'flb' => 2.37304222192651E+01, + 'BTU' => 9.47815067349015E-04, + 'btu' => 9.47815067349015E-04, + ), + 'e' => array( + 'J' => 1.00000048065700E-07, + 'e' => 1.0, + 'c' => 2.39006364353494E-08, + 'cal' => 2.38846305445111E-08, + 'eV' => 6.24146000000000E+11, + 'ev' => 6.24146000000000E+11, + 'HPh' => 3.72506609848824E-14, + 'hh' => 3.72506609848824E-14, + 'Wh' => 2.77778049754611E-11, + 'wh' => 2.77778049754611E-11, + 'flb' => 2.37304336254586E-06, + 'BTU' => 9.47815522922962E-11, + 'btu' => 9.47815522922962E-11, + ), + 'c' => array( + 'J' => 4.18399101363672E+00, + 'e' => 4.18398900257312E+07, + 'c' => 1.0, + 'cal' => 9.99330315287563E-01, + 'eV' => 2.61142000000000E+19, + 'ev' => 2.61142000000000E+19, + 'HPh' => 1.55856355899327E-06, + 'hh' => 1.55856355899327E-06, + 'Wh' => 1.16222030532950E-03, + 'wh' => 1.16222030532950E-03, + 'flb' => 9.92878733152102E+01, + 'BTU' => 3.96564972437776E-03, + 'btu' => 3.96564972437776E-03, + ), + 'cal' => array( + 'J' => 4.18679484613929E+00, + 'e' => 4.18679283372801E+07, + 'c' => 1.00067013349059E+00, + 'cal' => 1.0, + 'eV' => 2.61317000000000E+19, + 'ev' => 2.61317000000000E+19, + 'HPh' => 1.55960800463137E-06, + 'hh' => 1.55960800463137E-06, + 'Wh' => 1.16299914807955E-03, + 'wh' => 1.16299914807955E-03, + 'flb' => 9.93544094443283E+01, + 'BTU' => 3.96830723907002E-03, + 'btu' => 3.96830723907002E-03, + ), + 'eV' => array( + 'J' => 1.60219000146921E-19, + 'e' => 1.60218923136574E-12, + 'c' => 3.82933423195043E-20, + 'cal' => 3.82676978535648E-20, + 'eV' => 1.0, + 'ev' => 1.0, + 'HPh' => 5.96826078912344E-26, + 'hh' => 5.96826078912344E-26, + 'Wh' => 4.45053000026614E-23, + 'wh' => 4.45053000026614E-23, + 'flb' => 3.80206452103492E-18, + 'BTU' => 1.51857982414846E-22, + 'btu' => 1.51857982414846E-22, + ), + 'ev' => array( + 'J' => 1.60219000146921E-19, + 'e' => 1.60218923136574E-12, + 'c' => 3.82933423195043E-20, + 'cal' => 3.82676978535648E-20, + 'eV' => 1.0, + 'ev' => 1.0, + 'HPh' => 5.96826078912344E-26, + 'hh' => 5.96826078912344E-26, + 'Wh' => 4.45053000026614E-23, + 'wh' => 4.45053000026614E-23, + 'flb' => 3.80206452103492E-18, + 'BTU' => 1.51857982414846E-22, + 'btu' => 1.51857982414846E-22, + ), + 'HPh' => array( + 'J' => 2.68451741316170E+06, + 'e' => 2.68451612283024E+13, + 'c' => 6.41616438565991E+05, + 'cal' => 6.41186757845835E+05, + 'eV' => 1.67553000000000E+25, + 'ev' => 1.67553000000000E+25, + 'HPh' => 1.0, + 'hh' => 1.0, + 'Wh' => 7.45699653134593E+02, + 'wh' => 7.45699653134593E+02, + 'flb' => 6.37047316692964E+07, + 'BTU' => 2.54442605275546E+03, + 'btu' => 2.54442605275546E+03, + ), + 'hh' => array( + 'J' => 2.68451741316170E+06, + 'e' => 2.68451612283024E+13, + 'c' => 6.41616438565991E+05, + 'cal' => 6.41186757845835E+05, + 'eV' => 1.67553000000000E+25, + 'ev' => 1.67553000000000E+25, + 'HPh' => 1.0, + 'hh' => 1.0, + 'Wh' => 7.45699653134593E+02, + 'wh' => 7.45699653134593E+02, + 'flb' => 6.37047316692964E+07, + 'BTU' => 2.54442605275546E+03, + 'btu' => 2.54442605275546E+03, + ), + 'Wh' => array( + 'J' => 3.59999820554720E+03, + 'e' => 3.59999647518369E+10, + 'c' => 8.60422069219046E+02, + 'cal' => 8.59845857713046E+02, + 'eV' => 2.24692340000000E+22, + 'ev' => 2.24692340000000E+22, + 'HPh' => 1.34102248243839E-03, + 'hh' => 1.34102248243839E-03, + 'Wh' => 1.0, + 'wh' => 1.0, + 'flb' => 8.54294774062316E+04, + 'BTU' => 3.41213254164705E+00, + 'btu' => 3.41213254164705E+00, + ), + 'wh' => array( + 'J' => 3.59999820554720E+03, + 'e' => 3.59999647518369E+10, + 'c' => 8.60422069219046E+02, + 'cal' => 8.59845857713046E+02, + 'eV' => 2.24692340000000E+22, + 'ev' => 2.24692340000000E+22, + 'HPh' => 1.34102248243839E-03, + 'hh' => 1.34102248243839E-03, + 'Wh' => 1.0, + 'wh' => 1.0, + 'flb' => 8.54294774062316E+04, + 'BTU' => 3.41213254164705E+00, + 'btu' => 3.41213254164705E+00, + ), + 'flb' => array( + 'J' => 4.21400003236424E-02, + 'e' => 4.21399800687660E+05, + 'c' => 1.00717234301644E-02, + 'cal' => 1.00649785509554E-02, + 'eV' => 2.63015000000000E+17, + 'ev' => 2.63015000000000E+17, + 'HPh' => 1.56974211145130E-08, + 'hh' => 1.56974211145130E-08, + 'Wh' => 1.17055614802000E-05, + 'wh' => 1.17055614802000E-05, + 'flb' => 1.0, + 'BTU' => 3.99409272448406E-05, + 'btu' => 3.99409272448406E-05, + ), + 'BTU' => array( + 'J' => 1.05505813786749E+03, + 'e' => 1.05505763074665E+10, + 'c' => 2.52165488508168E+02, + 'cal' => 2.51996617135510E+02, + 'eV' => 6.58510000000000E+21, + 'ev' => 6.58510000000000E+21, + 'HPh' => 3.93015941224568E-04, + 'hh' => 3.93015941224568E-04, + 'Wh' => 2.93071851047526E-01, + 'wh' => 2.93071851047526E-01, + 'flb' => 2.50369750774671E+04, + 'BTU' => 1.0, + 'btu' => 1.0, + ), + 'btu' => array( + 'J' => 1.05505813786749E+03, + 'e' => 1.05505763074665E+10, + 'c' => 2.52165488508168E+02, + 'cal' => 2.51996617135510E+02, + 'eV' => 6.58510000000000E+21, + 'ev' => 6.58510000000000E+21, + 'HPh' => 3.93015941224568E-04, + 'hh' => 3.93015941224568E-04, + 'Wh' => 2.93071851047526E-01, + 'wh' => 2.93071851047526E-01, + 'flb' => 2.50369750774671E+04, + 'BTU' => 1.0, + 'btu' => 1.0, + ), + ), + 'Power' => array( + 'HP' => array( + 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45701000000000E+02, + 'w' => 7.45701000000000E+02, + ), + 'h' => array( + 'HP' => 1.0, + 'h' => 1.0, + 'W' => 7.45701000000000E+02, + 'w' => 7.45701000000000E+02, + ), + 'W' => array( + 'HP' => 1.34102006031908E-03, + 'h' => 1.34102006031908E-03, + 'W' => 1.0, + 'w' => 1.0, + ), + 'w' => array( + 'HP' => 1.34102006031908E-03, + 'h' => 1.34102006031908E-03, + 'W' => 1.0, + 'w' => 1.0, + ), + ), + 'Magnetism' => array( + 'T' => array( + 'T' => 1.0, + 'ga' => 10000.0, + ), + 'ga' => array( + 'T' => 0.0001, + 'ga' => 1.0, + ), + ), + 'Liquid' => array( + 'tsp' => array( + 'tsp' => 1.0, + 'tbs' => 3.33333333333333E-01, + 'oz' => 1.66666666666667E-01, + 'cup' => 2.08333333333333E-02, + 'pt' => 1.04166666666667E-02, + 'us_pt' => 1.04166666666667E-02, + 'uk_pt' => 8.67558516821960E-03, + 'qt' => 5.20833333333333E-03, + 'gal' => 1.30208333333333E-03, + 'l' => 4.92999408400710E-03, + 'lt' => 4.92999408400710E-03, + ), + 'tbs' => array( + 'tsp' => 3.00000000000000E+00, + 'tbs' => 1.0, + 'oz' => 5.00000000000000E-01, + 'cup' => 6.25000000000000E-02, + 'pt' => 3.12500000000000E-02, + 'us_pt' => 3.12500000000000E-02, + 'uk_pt' => 2.60267555046588E-02, + 'qt' => 1.56250000000000E-02, + 'gal' => 3.90625000000000E-03, + 'l' => 1.47899822520213E-02, + 'lt' => 1.47899822520213E-02, + ), + 'oz' => array( + 'tsp' => 6.00000000000000E+00, + 'tbs' => 2.00000000000000E+00, + 'oz' => 1.0, + 'cup' => 1.25000000000000E-01, + 'pt' => 6.25000000000000E-02, + 'us_pt' => 6.25000000000000E-02, + 'uk_pt' => 5.20535110093176E-02, + 'qt' => 3.12500000000000E-02, + 'gal' => 7.81250000000000E-03, + 'l' => 2.95799645040426E-02, + 'lt' => 2.95799645040426E-02, + ), + 'cup' => array( + 'tsp' => 4.80000000000000E+01, + 'tbs' => 1.60000000000000E+01, + 'oz' => 8.00000000000000E+00, + 'cup' => 1.0, + 'pt' => 5.00000000000000E-01, + 'us_pt' => 5.00000000000000E-01, + 'uk_pt' => 4.16428088074541E-01, + 'qt' => 2.50000000000000E-01, + 'gal' => 6.25000000000000E-02, + 'l' => 2.36639716032341E-01, + 'lt' => 2.36639716032341E-01, + ), + 'pt' => array( + 'tsp' => 9.60000000000000E+01, + 'tbs' => 3.20000000000000E+01, + 'oz' => 1.60000000000000E+01, + 'cup' => 2.00000000000000E+00, + 'pt' => 1.0, + 'us_pt' => 1.0, + 'uk_pt' => 8.32856176149081E-01, + 'qt' => 5.00000000000000E-01, + 'gal' => 1.25000000000000E-01, + 'l' => 4.73279432064682E-01, + 'lt' => 4.73279432064682E-01, + ), + 'us_pt' => array( + 'tsp' => 9.60000000000000E+01, + 'tbs' => 3.20000000000000E+01, + 'oz' => 1.60000000000000E+01, + 'cup' => 2.00000000000000E+00, + 'pt' => 1.0, + 'us_pt' => 1.0, + 'uk_pt' => 8.32856176149081E-01, + 'qt' => 5.00000000000000E-01, + 'gal' => 1.25000000000000E-01, + 'l' => 4.73279432064682E-01, + 'lt' => 4.73279432064682E-01, + ), + 'uk_pt' => array( + 'tsp' => 1.15266000000000E+02, + 'tbs' => 3.84220000000000E+01, + 'oz' => 1.92110000000000E+01, + 'cup' => 2.40137500000000E+00, + 'pt' => 1.20068750000000E+00, + 'us_pt' => 1.20068750000000E+00, + 'uk_pt' => 1.0, + 'qt' => 6.00343750000000E-01, + 'gal' => 1.50085937500000E-01, + 'l' => 5.68260698087162E-01, + 'lt' => 5.68260698087162E-01, + ), + 'qt' => array( + 'tsp' => 1.92000000000000E+02, + 'tbs' => 6.40000000000000E+01, + 'oz' => 3.20000000000000E+01, + 'cup' => 4.00000000000000E+00, + 'pt' => 2.00000000000000E+00, + 'us_pt' => 2.00000000000000E+00, + 'uk_pt' => 1.66571235229816E+00, + 'qt' => 1.0, + 'gal' => 2.50000000000000E-01, + 'l' => 9.46558864129363E-01, + 'lt' => 9.46558864129363E-01, + ), + 'gal' => array( + 'tsp' => 7.68000000000000E+02, + 'tbs' => 2.56000000000000E+02, + 'oz' => 1.28000000000000E+02, + 'cup' => 1.60000000000000E+01, + 'pt' => 8.00000000000000E+00, + 'us_pt' => 8.00000000000000E+00, + 'uk_pt' => 6.66284940919265E+00, + 'qt' => 4.00000000000000E+00, + 'gal' => 1.0, + 'l' => 3.78623545651745E+00, + 'lt' => 3.78623545651745E+00, + ), + 'l' => array( + 'tsp' => 2.02840000000000E+02, + 'tbs' => 6.76133333333333E+01, + 'oz' => 3.38066666666667E+01, + 'cup' => 4.22583333333333E+00, + 'pt' => 2.11291666666667E+00, + 'us_pt' => 2.11291666666667E+00, + 'uk_pt' => 1.75975569552166E+00, + 'qt' => 1.05645833333333E+00, + 'gal' => 2.64114583333333E-01, + 'l' => 1.0, + 'lt' => 1.0, + ), + 'lt' => array( + 'tsp' => 2.02840000000000E+02, + 'tbs' => 6.76133333333333E+01, + 'oz' => 3.38066666666667E+01, + 'cup' => 4.22583333333333E+00, + 'pt' => 2.11291666666667E+00, + 'us_pt' => 2.11291666666667E+00, + 'uk_pt' => 1.75975569552166E+00, + 'qt' => 1.05645833333333E+00, + 'gal' => 2.64114583333333E-01, + 'l' => 1.0, + 'lt' => 1.0, + ), + ), + ); + + + /** + * parseComplex + * + * Parses a complex number into its real and imaginary parts, and an I or J suffix + * + * @param string $complexNumber The complex number + * @return string[] Indexed on "real", "imaginary" and "suffix" + */ + public static function parseComplex($complexNumber) + { + $workString = (string) $complexNumber; + + $realNumber = $imaginary = 0; + // Extract the suffix, if there is one + $suffix = substr($workString, -1); + if (!is_numeric($suffix)) { + $workString = substr($workString, 0, -1); + } else { + $suffix = ''; + } + + // Split the input into its Real and Imaginary components + $leadingSign = 0; + if (strlen($workString) > 0) { + $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0; + } + $power = ''; + $realNumber = strtok($workString, '+-'); + if (strtoupper(substr($realNumber, -1)) == 'E') { + $power = strtok('+-'); + ++$leadingSign; + } + + $realNumber = substr($workString, 0, strlen($realNumber)+strlen($power)+$leadingSign); + + if ($suffix != '') { + $imaginary = substr($workString, strlen($realNumber)); + + if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) { + $imaginary = $realNumber.'1'; + $realNumber = '0'; + } elseif ($imaginary == '') { + $imaginary = $realNumber; + $realNumber = '0'; + } elseif (($imaginary == '+') || ($imaginary == '-')) { + $imaginary .= '1'; + } + } + + return array( + 'real' => $realNumber, + 'imaginary' => $imaginary, + 'suffix' => $suffix + ); + } + + + /** + * Cleans the leading characters in a complex number string + * + * @param string $complexNumber The complex number to clean + * @return string The "cleaned" complex number + */ + private static function cleanComplex($complexNumber) + { + if ($complexNumber{0} == '+') { + $complexNumber = substr($complexNumber, 1); + } + if ($complexNumber{0} == '0') { + $complexNumber = substr($complexNumber, 1); + } + if ($complexNumber{0} == '.') { + $complexNumber = '0'.$complexNumber; + } + if ($complexNumber{0} == '+') { + $complexNumber = substr($complexNumber, 1); + } + return $complexNumber; + } + + /** + * Formats a number base string value with leading zeroes + * + * @param string $xVal The "number" to pad + * @param integer $places The length that we want to pad this value + * @return string The padded "number" + */ + private static function nbrConversionFormat($xVal, $places) + { + if (!is_null($places)) { + if (strlen($xVal) <= $places) { + return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10); + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + return substr($xVal, -10); + } + + /** + * BESSELI + * + * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated + * for purely imaginary arguments + * + * Excel Function: + * BESSELI(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELI returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. + * If ord is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELI returns the #VALUE! error value. + * If $ord < 0, BESSELI returns the #NUM! error value. + * @return float + * + */ + public static function BESSELI($x, $ord) + { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + $ord = floor($ord); + if ($ord < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (abs($x) <= 30) { + $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord); + $ordK = 1; + $fSqrX = ($x * $x) / 4; + do { + $fTerm *= $fSqrX; + $fTerm /= ($ordK * ($ordK + $ord)); + $fResult += $fTerm; + } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); + } else { + $f_2_PI = 2 * M_PI; + + $fXAbs = abs($x); + $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs); + if (($ord & 1) && ($x < 0)) { + $fResult = -$fResult; + } + } + return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * BESSELJ + * + * Returns the Bessel function + * + * Excel Function: + * BESSELJ(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELJ returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value. + * If $ord < 0, BESSELJ returns the #NUM! error value. + * @return float + * + */ + public static function BESSELJ($x, $ord) + { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + $ord = floor($ord); + if ($ord < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $fResult = 0; + if (abs($x) <= 30) { + $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord); + $ordK = 1; + $fSqrX = ($x * $x) / -4; + do { + $fTerm *= $fSqrX; + $fTerm /= ($ordK * ($ordK + $ord)); + $fResult += $fTerm; + } while ((abs($fTerm) > 1e-12) && (++$ordK < 100)); + } else { + $f_PI_DIV_2 = M_PI / 2; + $f_PI_DIV_4 = M_PI / 4; + + $fXAbs = abs($x); + $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4); + if (($ord & 1) && ($x < 0)) { + $fResult = -$fResult; + } + } + return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + private static function besselK0($fNum) + { + if ($fNum <= 2) { + $fNum2 = $fNum * 0.5; + $y = ($fNum2 * $fNum2); + $fRet = -log($fNum2) * self::BESSELI($fNum, 0) + + (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y * + (0.10750e-3 + $y * 0.74e-5)))))); + } else { + $y = 2 / $fNum; + $fRet = exp(-$fNum) / sqrt($fNum) * + (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y * + (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3)))))); + } + return $fRet; + } + + + private static function besselK1($fNum) + { + if ($fNum <= 2) { + $fNum2 = $fNum * 0.5; + $y = ($fNum2 * $fNum2); + $fRet = log($fNum2) * self::BESSELI($fNum, 1) + + (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y * + (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum; + } else { + $y = 2 / $fNum; + $fRet = exp(-$fNum) / sqrt($fNum) * + (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y * + (0.325614e-2 + $y * (-0.68245e-3))))))); + } + return $fRet; + } + + + /** + * BESSELK + * + * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated + * for purely imaginary arguments. + * + * Excel Function: + * BESSELK(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. + * If $ord < 0, BESSELK returns the #NUM! error value. + * @return float + * + */ + public static function BESSELK($x, $ord) + { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + if (($ord < 0) || ($x == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch (floor($ord)) { + case 0: + return self::besselK0($x); + case 1: + return self::besselK1($x); + default: + $fTox = 2 / $x; + $fBkm = self::besselK0($x); + $fBk = self::besselK1($x); + for ($n = 1; $n < $ord; ++$n) { + $fBkp = $fBkm + $n * $fTox * $fBk; + $fBkm = $fBk; + $fBk = $fBkp; + } + } + return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + private static function besselY0($fNum) + { + if ($fNum < 8.0) { + $y = ($fNum * $fNum); + $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733)))); + $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y)))); + $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum); + } else { + $z = 8.0 / $fNum; + $y = ($z * $z); + $xx = $fNum - 0.785398164; + $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6))); + $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7)))); + $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2); + } + return $fRet; + } + + + private static function besselY1($fNum) + { + if ($fNum < 8.0) { + $y = ($fNum * $fNum); + $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y * + (-0.4237922726e7 + $y * 0.8511937935e4))))); + $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y * + (0.1020426050e6 + $y * (0.3549632885e3 + $y))))); + $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum); + } else { + $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491); + } + return $fRet; + } + + + /** + * BESSELY + * + * Returns the Bessel function, which is also called the Weber function or the Neumann function. + * + * Excel Function: + * BESSELY(x,ord) + * + * @access public + * @category Engineering Functions + * @param float $x The value at which to evaluate the function. + * If x is nonnumeric, BESSELK returns the #VALUE! error value. + * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated. + * If $ord is nonnumeric, BESSELK returns the #VALUE! error value. + * If $ord < 0, BESSELK returns the #NUM! error value. + * + * @return float + */ + public static function BESSELY($x, $ord) + { + $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x); + $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord); + + if ((is_numeric($x)) && (is_numeric($ord))) { + if (($ord < 0) || ($x == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch (floor($ord)) { + case 0: + return self::besselY0($x); + case 1: + return self::besselY1($x); + default: + $fTox = 2 / $x; + $fBym = self::besselY0($x); + $fBy = self::besselY1($x); + for ($n = 1; $n < $ord; ++$n) { + $fByp = $n * $fTox * $fBy - $fBym; + $fBym = $fBy; + $fBy = $fByp; + } + } + return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * BINTODEC + * + * Return a binary value as decimal. + * + * Excel Function: + * BIN2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2DEC returns the #NUM! error value. + * @return string + */ + public static function BINTODEC($x) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + $x = substr($x, -9); + return '-'.(512-bindec($x)); + } + return bindec($x); + } + + + /** + * BINTOHEX + * + * Return a binary value as hex. + * + * Excel Function: + * BIN2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2HEX returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2HEX returns the #VALUE! error value. + * If places is negative, BIN2HEX returns the #NUM! error value. + * @return string + */ + public static function BINTOHEX($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + return str_repeat('F', 8).substr(strtoupper(dechex(bindec(substr($x, -9)))), -2); + } + $hexVal = (string) strtoupper(dechex(bindec($x))); + + return self::nbrConversionFormat($hexVal, $places); + } + + + /** + * BINTOOCT + * + * Return a binary value as octal. + * + * Excel Function: + * BIN2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The binary number (as a string) that you want to convert. The number + * cannot contain more than 10 characters (10 bits). The most significant + * bit of number is the sign bit. The remaining 9 bits are magnitude bits. + * Negative numbers are represented using two's-complement notation. + * If number is not a valid binary number, or if number contains more than + * 10 characters (10 bits), BIN2OCT returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the + * minimum number of characters necessary. Places is useful for padding the + * return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, BIN2OCT returns the #VALUE! error value. + * If places is negative, BIN2OCT returns the #NUM! error value. + * @return string + */ + public static function BINTOOCT($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $x = floor($x); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[01]/', $x, $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (strlen($x) > 10) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (strlen($x) == 10) { + // Two's Complement + return str_repeat('7', 7).substr(strtoupper(decoct(bindec(substr($x, -9)))), -3); + } + $octVal = (string) decoct(bindec($x)); + + return self::nbrConversionFormat($octVal, $places); + } + + + /** + * DECTOBIN + * + * Return a decimal value as binary. + * + * Excel Function: + * DEC2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * valid place values are ignored and DEC2BIN returns a 10-character + * (10-bit) binary number in which the most significant bit is the sign + * bit. The remaining 9 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error + * value. + * If number is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If DEC2BIN requires more than places characters, it returns the #NUM! + * error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2BIN returns the #VALUE! error value. + * If places is zero or negative, DEC2BIN returns the #NUM! error value. + * @return string + */ + public static function DECTOBIN($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = decbin($x); + if (strlen($r) == 32) { + // Two's Complement + $r = substr($r, -10); + } elseif (strlen($r) > 11) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::nbrConversionFormat($r, $places); + } + + + /** + * DECTOHEX + * + * Return a decimal value as hex. + * + * Excel Function: + * DEC2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2HEX returns a 10-character (40-bit) + * hexadecimal number in which the most significant bit is the sign + * bit. The remaining 39 bits are magnitude bits. Negative numbers + * are represented using two's-complement notation. + * If number < -549,755,813,888 or if number > 549,755,813,887, + * DEC2HEX returns the #NUM! error value. + * If number is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If DEC2HEX requires more than places characters, it returns the + * #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2HEX returns the #VALUE! error value. + * If places is zero or negative, DEC2HEX returns the #NUM! error value. + * @return string + */ + public static function DECTOHEX($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = strtoupper(dechex($x)); + if (strlen($r) == 8) { + // Two's Complement + $r = 'FF'.$r; + } + + return self::nbrConversionFormat($r, $places); + } + + + /** + * DECTOOCT + * + * Return an decimal value as octal. + * + * Excel Function: + * DEC2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The decimal integer you want to convert. If number is negative, + * places is ignored and DEC2OCT returns a 10-character (30-bit) + * octal number in which the most significant bit is the sign bit. + * The remaining 29 bits are magnitude bits. Negative numbers are + * represented using two's-complement notation. + * If number < -536,870,912 or if number > 536,870,911, DEC2OCT + * returns the #NUM! error value. + * If number is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If DEC2OCT requires more than places characters, it returns the + * #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses + * the minimum number of characters necessary. Places is useful for + * padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, DEC2OCT returns the #VALUE! error value. + * If places is zero or negative, DEC2OCT returns the #NUM! error value. + * @return string + */ + public static function DECTOOCT($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $x = (int) $x; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) floor($x); + $r = decoct($x); + if (strlen($r) == 11) { + // Two's Complement + $r = substr($r, -10); + } + + return self::nbrConversionFormat($r, $places); + } + + + /** + * HEXTOBIN + * + * Return a hex value as binary. + * + * Excel Function: + * HEX2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x the hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit (40th bit from the right). The remaining + * 9 bits are magnitude bits. Negative numbers are represented + * using two's-complement notation. + * If number is negative, HEX2BIN ignores places and returns a + * 10-character binary number. + * If number is negative, it cannot be less than FFFFFFFE00, and + * if number is positive, it cannot be greater than 1FF. + * If number is not a valid hexadecimal number, HEX2BIN returns + * the #NUM! error value. + * If HEX2BIN requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, + * HEX2BIN uses the minimum number of characters necessary. Places + * is useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2BIN returns the #VALUE! error value. + * If places is negative, HEX2BIN returns the #NUM! error value. + * @return string + */ + public static function HEXTOBIN($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $binVal = decbin(hexdec($x)); + + return substr(self::nbrConversionFormat($binVal, $places), -10); + } + + + /** + * HEXTODEC + * + * Return a hex value as decimal. + * + * Excel Function: + * HEX2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The hexadecimal number you want to convert. This number cannot + * contain more than 10 characters (40 bits). The most significant + * bit of number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is not a valid hexadecimal number, HEX2DEC returns the + * #NUM! error value. + * @return string + */ + public static function HEXTODEC($x) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return hexdec($x); + } + + + /** + * HEXTOOCT + * + * Return a hex value as octal. + * + * Excel Function: + * HEX2OCT(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The hexadecimal number you want to convert. Number cannot + * contain more than 10 characters. The most significant bit of + * number is the sign bit. The remaining 39 bits are magnitude + * bits. Negative numbers are represented using two's-complement + * notation. + * If number is negative, HEX2OCT ignores places and returns a + * 10-character octal number. + * If number is negative, it cannot be less than FFE0000000, and + * if number is positive, it cannot be greater than 1FFFFFFF. + * If number is not a valid hexadecimal number, HEX2OCT returns + * the #NUM! error value. + * If HEX2OCT requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, HEX2OCT + * uses the minimum number of characters necessary. Places is + * useful for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, HEX2OCT returns the #VALUE! error + * value. + * If places is negative, HEX2OCT returns the #NUM! error value. + * @return string + */ + public static function HEXTOOCT($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $octVal = decoct(hexdec($x)); + + return self::nbrConversionFormat($octVal, $places); + } // function HEXTOOCT() + + + /** + * OCTTOBIN + * + * Return an octal value as binary. + * + * Excel Function: + * OCT2BIN(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not + * contain more than 10 characters. The most significant + * bit of number is the sign bit. The remaining 29 bits + * are magnitude bits. Negative numbers are represented + * using two's-complement notation. + * If number is negative, OCT2BIN ignores places and returns + * a 10-character binary number. + * If number is negative, it cannot be less than 7777777000, + * and if number is positive, it cannot be greater than 777. + * If number is not a valid octal number, OCT2BIN returns + * the #NUM! error value. + * If OCT2BIN requires more than places characters, it + * returns the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, + * OCT2BIN uses the minimum number of characters necessary. + * Places is useful for padding the return value with + * leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2BIN returns the #VALUE! + * error value. + * If places is negative, OCT2BIN returns the #NUM! error + * value. + * @return string + */ + public static function OCTTOBIN($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $r = decbin(octdec($x)); + + return self::nbrConversionFormat($r, $places); + } + + + /** + * OCTTODEC + * + * Return an octal value as decimal. + * + * Excel Function: + * OCT2DEC(x) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is not a valid octal number, OCT2DEC returns the + * #NUM! error value. + * @return string + */ + public static function OCTTODEC($x) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return octdec($x); + } + + + /** + * OCTTOHEX + * + * Return an octal value as hex. + * + * Excel Function: + * OCT2HEX(x[,places]) + * + * @access public + * @category Engineering Functions + * @param string $x The octal number you want to convert. Number may not contain + * more than 10 octal characters (30 bits). The most significant + * bit of number is the sign bit. The remaining 29 bits are + * magnitude bits. Negative numbers are represented using + * two's-complement notation. + * If number is negative, OCT2HEX ignores places and returns a + * 10-character hexadecimal number. + * If number is not a valid octal number, OCT2HEX returns the + * #NUM! error value. + * If OCT2HEX requires more than places characters, it returns + * the #NUM! error value. + * @param integer $places The number of characters to use. If places is omitted, OCT2HEX + * uses the minimum number of characters necessary. Places is useful + * for padding the return value with leading 0s (zeros). + * If places is not an integer, it is truncated. + * If places is nonnumeric, OCT2HEX returns the #VALUE! error value. + * If places is negative, OCT2HEX returns the #NUM! error value. + * @return string + */ + public static function OCTTOHEX($x, $places = null) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $places = PHPExcel_Calculation_Functions::flattenSingleValue($places); + + if (is_bool($x)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $x = (string) $x; + if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $hexVal = strtoupper(dechex(octdec($x))); + + return self::nbrConversionFormat($hexVal, $places); + } + + + /** + * COMPLEX + * + * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj. + * + * Excel Function: + * COMPLEX(realNumber,imaginary[,places]) + * + * @access public + * @category Engineering Functions + * @param float $realNumber The real coefficient of the complex number. + * @param float $imaginary The imaginary coefficient of the complex number. + * @param string $suffix The suffix for the imaginary component of the complex number. + * If omitted, the suffix is assumed to be "i". + * @return string + */ + public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i') + { + $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber); + $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary); + $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix); + + if (((is_numeric($realNumber)) && (is_numeric($imaginary))) && + (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) { + $realNumber = (float) $realNumber; + $imaginary = (float) $imaginary; + + if ($suffix == '') { + $suffix = 'i'; + } + if ($realNumber == 0.0) { + if ($imaginary == 0.0) { + return (string) '0'; + } elseif ($imaginary == 1.0) { + return (string) $suffix; + } elseif ($imaginary == -1.0) { + return (string) '-'.$suffix; + } + return (string) $imaginary.$suffix; + } elseif ($imaginary == 0.0) { + return (string) $realNumber; + } elseif ($imaginary == 1.0) { + return (string) $realNumber.'+'.$suffix; + } elseif ($imaginary == -1.0) { + return (string) $realNumber.'-'.$suffix; + } + if ($imaginary > 0) { + $imaginary = (string) '+'.$imaginary; + } + return (string) $realNumber.$imaginary.$suffix; + } + + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * IMAGINARY + * + * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMAGINARY(complexNumber) + * + * @access public + * @category Engineering Functions + * @param string $complexNumber The complex number for which you want the imaginary + * coefficient. + * @return float + */ + public static function IMAGINARY($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + return $parsedComplex['imaginary']; + } + + + /** + * IMREAL + * + * Returns the real coefficient of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMREAL(complexNumber) + * + * @access public + * @category Engineering Functions + * @param string $complexNumber The complex number for which you want the real coefficient. + * @return float + */ + public static function IMREAL($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + return $parsedComplex['real']; + } + + + /** + * IMABS + * + * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMABS(complexNumber) + * + * @param string $complexNumber The complex number for which you want the absolute value. + * @return float + */ + public static function IMABS($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + return sqrt( + ($parsedComplex['real'] * $parsedComplex['real']) + + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']) + ); + } + + + /** + * IMARGUMENT + * + * Returns the argument theta of a complex number, i.e. the angle in radians from the real + * axis to the representation of the number in polar coordinates. + * + * Excel Function: + * IMARGUMENT(complexNumber) + * + * @param string $complexNumber The complex number for which you want the argument theta. + * @return float + */ + public static function IMARGUMENT($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if ($parsedComplex['real'] == 0.0) { + if ($parsedComplex['imaginary'] == 0.0) { + return 0.0; + } elseif ($parsedComplex['imaginary'] < 0.0) { + return M_PI / -2; + } else { + return M_PI / 2; + } + } elseif ($parsedComplex['real'] > 0.0) { + return atan($parsedComplex['imaginary'] / $parsedComplex['real']); + } elseif ($parsedComplex['imaginary'] < 0.0) { + return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real']))); + } else { + return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real'])); + } + } + + + /** + * IMCONJUGATE + * + * Returns the complex conjugate of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCONJUGATE(complexNumber) + * + * @param string $complexNumber The complex number for which you want the conjugate. + * @return string + */ + public static function IMCONJUGATE($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return $parsedComplex['real']; + } else { + return self::cleanComplex( + self::COMPLEX( + $parsedComplex['real'], + 0 - $parsedComplex['imaginary'], + $parsedComplex['suffix'] + ) + ); + } + } + + + /** + * IMCOS + * + * Returns the cosine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMCOS(complexNumber) + * + * @param string $complexNumber The complex number for which you want the cosine. + * @return string|float + */ + public static function IMCOS($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return cos($parsedComplex['real']); + } else { + return self::IMCONJUGATE( + self::COMPLEX( + cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']), + sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']), + $parsedComplex['suffix'] + ) + ); + } + } + + + /** + * IMSIN + * + * Returns the sine of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSIN(complexNumber) + * + * @param string $complexNumber The complex number for which you want the sine. + * @return string|float + */ + public static function IMSIN($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if ($parsedComplex['imaginary'] == 0.0) { + return sin($parsedComplex['real']); + } else { + return self::COMPLEX( + sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']), + cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']), + $parsedComplex['suffix'] + ); + } + } + + + /** + * IMSQRT + * + * Returns the square root of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMSQRT(complexNumber) + * + * @param string $complexNumber The complex number for which you want the square root. + * @return string + */ + public static function IMSQRT($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + $theta = self::IMARGUMENT($complexNumber); + $d1 = cos($theta / 2); + $d2 = sin($theta / 2); + $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']))); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($d1 * $r, $d2 * $r); + } else { + return self::COMPLEX($d1 * $r, $d2 * $r, $parsedComplex['suffix']); + } + } + + + /** + * IMLN + * + * Returns the natural logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLN(complexNumber) + * + * @param string $complexNumber The complex number for which you want the natural logarithm. + * @return string + */ + public static function IMLN($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']))); + $t = self::IMARGUMENT($complexNumber); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($logR, $t); + } else { + return self::COMPLEX($logR, $t, $parsedComplex['suffix']); + } + } + + + /** + * IMLOG10 + * + * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG10(complexNumber) + * + * @param string $complexNumber The complex number for which you want the common logarithm. + * @return string + */ + public static function IMLOG10($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return log10($parsedComplex['real']); + } + + return self::IMPRODUCT(log10(EULER), self::IMLN($complexNumber)); + } + + + /** + * IMLOG2 + * + * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMLOG2(complexNumber) + * + * @param string $complexNumber The complex number for which you want the base-2 logarithm. + * @return string + */ + public static function IMLOG2($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return log($parsedComplex['real'], 2); + } + + return self::IMPRODUCT(log(EULER, 2), self::IMLN($complexNumber)); + } + + + /** + * IMEXP + * + * Returns the exponential of a complex number in x + yi or x + yj text format. + * + * Excel Function: + * IMEXP(complexNumber) + * + * @param string $complexNumber The complex number for which you want the exponential. + * @return string + */ + public static function IMEXP($complexNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + + $parsedComplex = self::parseComplex($complexNumber); + + if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) { + return '1'; + } + + $e = exp($parsedComplex['real']); + $eX = $e * cos($parsedComplex['imaginary']); + $eY = $e * sin($parsedComplex['imaginary']); + + if ($parsedComplex['suffix'] == '') { + return self::COMPLEX($eX, $eY); + } else { + return self::COMPLEX($eX, $eY, $parsedComplex['suffix']); + } + } + + + /** + * IMPOWER + * + * Returns a complex number in x + yi or x + yj text format raised to a power. + * + * Excel Function: + * IMPOWER(complexNumber,realNumber) + * + * @param string $complexNumber The complex number you want to raise to a power. + * @param float $realNumber The power to which you want to raise the complex number. + * @return string + */ + public static function IMPOWER($complexNumber, $realNumber) + { + $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber); + $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber); + + if (!is_numeric($realNumber)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $parsedComplex = self::parseComplex($complexNumber); + + $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])); + $rPower = pow($r, $realNumber); + $theta = self::IMARGUMENT($complexNumber) * $realNumber; + if ($theta == 0) { + return 1; + } elseif ($parsedComplex['imaginary'] == 0.0) { + return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']); + } else { + return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']); + } + } + + + /** + * IMDIV + * + * Returns the quotient of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMDIV(complexDividend,complexDivisor) + * + * @param string $complexDividend The complex numerator or dividend. + * @param string $complexDivisor The complex denominator or divisor. + * @return string + */ + public static function IMDIV($complexDividend, $complexDivisor) + { + $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend); + $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor); + + $parsedComplexDividend = self::parseComplex($complexDividend); + $parsedComplexDivisor = self::parseComplex($complexDivisor); + + if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') && + ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) { + $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix']; + } + + $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']); + $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']); + $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']); + + $r = $d1 / $d3; + $i = $d2 / $d3; + + if ($i > 0.0) { + return self::cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']); + } elseif ($i < 0.0) { + return self::cleanComplex($r.$i.$parsedComplexDivisor['suffix']); + } else { + return $r; + } + } + + + /** + * IMSUB + * + * Returns the difference of two complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUB(complexNumber1,complexNumber2) + * + * @param string $complexNumber1 The complex number from which to subtract complexNumber2. + * @param string $complexNumber2 The complex number to subtract from complexNumber1. + * @return string + */ + public static function IMSUB($complexNumber1, $complexNumber2) + { + $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1); + $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2); + + $parsedComplex1 = self::parseComplex($complexNumber1); + $parsedComplex2 = self::parseComplex($complexNumber2); + + if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) && + ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) { + $parsedComplex1['suffix'] = $parsedComplex2['suffix']; + } + + $d1 = $parsedComplex1['real'] - $parsedComplex2['real']; + $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary']; + + return self::COMPLEX($d1, $d2, $parsedComplex1['suffix']); + } + + + /** + * IMSUM + * + * Returns the sum of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMSUM(complexNumber[,complexNumber[,...]]) + * + * @param string $complexNumber,... Series of complex numbers to add + * @return string + */ + public static function IMSUM() + { + // Return value + $returnValue = self::parseComplex('0'); + $activeSuffix = ''; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + $parsedComplex = self::parseComplex($arg); + + if ($activeSuffix == '') { + $activeSuffix = $parsedComplex['suffix']; + } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $returnValue['real'] += $parsedComplex['real']; + $returnValue['imaginary'] += $parsedComplex['imaginary']; + } + + if ($returnValue['imaginary'] == 0.0) { + $activeSuffix = ''; + } + return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix); + } + + + /** + * IMPRODUCT + * + * Returns the product of two or more complex numbers in x + yi or x + yj text format. + * + * Excel Function: + * IMPRODUCT(complexNumber[,complexNumber[,...]]) + * + * @param string $complexNumber,... Series of complex numbers to multiply + * @return string + */ + public static function IMPRODUCT() + { + // Return value + $returnValue = self::parseComplex('1'); + $activeSuffix = ''; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + $parsedComplex = self::parseComplex($arg); + + $workValue = $returnValue; + if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) { + $activeSuffix = $parsedComplex['suffix']; + } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) { + return PHPExcel_Calculation_Functions::NaN(); + } + $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']); + $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']); + } + + if ($returnValue['imaginary'] == 0.0) { + $activeSuffix = ''; + } + return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix); + } + + + /** + * DELTA + * + * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise. + * Use this function to filter a set of values. For example, by summing several DELTA + * functions you calculate the count of equal pairs. This function is also known as the + * Kronecker Delta function. + * + * Excel Function: + * DELTA(a[,b]) + * + * @param float $a The first number. + * @param float $b The second number. If omitted, b is assumed to be zero. + * @return int + */ + public static function DELTA($a, $b = 0) + { + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + return (int) ($a == $b); + } + + + /** + * GESTEP + * + * Excel Function: + * GESTEP(number[,step]) + * + * Returns 1 if number >= step; returns 0 (zero) otherwise + * Use this function to filter a set of values. For example, by summing several GESTEP + * functions you calculate the count of values that exceed a threshold. + * + * @param float $number The value to test against step. + * @param float $step The threshold value. + * If you omit a value for step, GESTEP uses zero. + * @return int + */ + public static function GESTEP($number, $step = 0) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $step = PHPExcel_Calculation_Functions::flattenSingleValue($step); + + return (int) ($number >= $step); + } + + + // + // Private method to calculate the erf value + // + private static $twoSqrtPi = 1.128379167095512574; + + public static function erfVal($x) + { + if (abs($x) > 2.2) { + return 1 - self::erfcVal($x); + } + $sum = $term = $x; + $xsqr = ($x * $x); + $j = 1; + do { + $term *= $xsqr / $j; + $sum -= $term / (2 * $j + 1); + ++$j; + $term *= $xsqr / $j; + $sum += $term / (2 * $j + 1); + ++$j; + if ($sum == 0.0) { + break; + } + } while (abs($term / $sum) > PRECISION); + return self::$twoSqrtPi * $sum; + } + + + /** + * ERF + * + * Returns the error function integrated between the lower and upper bound arguments. + * + * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments, + * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was + * improved, so that it can now calculate the function for both positive and negative ranges. + * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments. + * + * Excel Function: + * ERF(lower[,upper]) + * + * @param float $lower lower bound for integrating ERF + * @param float $upper upper bound for integrating ERF. + * If omitted, ERF integrates between zero and lower_limit + * @return float + */ + public static function ERF($lower, $upper = null) + { + $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower); + $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper); + + if (is_numeric($lower)) { + if (is_null($upper)) { + return self::erfVal($lower); + } + if (is_numeric($upper)) { + return self::erfVal($upper) - self::erfVal($lower); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + // + // Private method to calculate the erfc value + // + private static $oneSqrtPi = 0.564189583547756287; + + private static function erfcVal($x) + { + if (abs($x) < 2.2) { + return 1 - self::erfVal($x); + } + if ($x < 0) { + return 2 - self::ERFC(-$x); + } + $a = $n = 1; + $b = $c = $x; + $d = ($x * $x) + 0.5; + $q1 = $q2 = $b / $d; + $t = 0; + do { + $t = $a * $n + $b * $x; + $a = $b; + $b = $t; + $t = $c * $n + $d * $x; + $c = $d; + $d = $t; + $n += 0.5; + $q1 = $q2; + $q2 = $b / $d; + } while ((abs($q1 - $q2) / $q2) > PRECISION); + return self::$oneSqrtPi * exp(-$x * $x) * $q2; + } + + + /** + * ERFC + * + * Returns the complementary ERF function integrated between x and infinity + * + * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument, + * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was + * improved, so that it can now calculate the function for both positive and negative x values. + * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments. + * + * Excel Function: + * ERFC(x) + * + * @param float $x The lower bound for integrating ERFC + * @return float + */ + public static function ERFC($x) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + + if (is_numeric($x)) { + return self::erfcVal($x); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * getConversionGroups + * Returns a list of the different conversion groups for UOM conversions + * + * @return array + */ + public static function getConversionGroups() + { + $conversionGroups = array(); + foreach (self::$conversionUnits as $conversionUnit) { + $conversionGroups[] = $conversionUnit['Group']; + } + return array_merge(array_unique($conversionGroups)); + } + + + /** + * getConversionGroupUnits + * Returns an array of units of measure, for a specified conversion group, or for all groups + * + * @param string $group The group whose units of measure you want to retrieve + * @return array + */ + public static function getConversionGroupUnits($group = null) + { + $conversionGroups = array(); + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { + $conversionGroups[$conversionGroup['Group']][] = $conversionUnit; + } + } + return $conversionGroups; + } + + + /** + * getConversionGroupUnitDetails + * + * @param string $group The group whose units of measure you want to retrieve + * @return array + */ + public static function getConversionGroupUnitDetails($group = null) + { + $conversionGroups = array(); + foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) { + if ((is_null($group)) || ($conversionGroup['Group'] == $group)) { + $conversionGroups[$conversionGroup['Group']][] = array( + 'unit' => $conversionUnit, + 'description' => $conversionGroup['Unit Name'] + ); + } + } + return $conversionGroups; + } + + + /** + * getConversionMultipliers + * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM() + * + * @return array of mixed + */ + public static function getConversionMultipliers() + { + return self::$conversionMultipliers; + } + + + /** + * CONVERTUOM + * + * Converts a number from one measurement system to another. + * For example, CONVERT can translate a table of distances in miles to a table of distances + * in kilometers. + * + * Excel Function: + * CONVERT(value,fromUOM,toUOM) + * + * @param float $value The value in fromUOM to convert. + * @param string $fromUOM The units for value. + * @param string $toUOM The units for the result. + * + * @return float + */ + public static function CONVERTUOM($value, $fromUOM, $toUOM) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM); + $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM); + + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $fromMultiplier = 1.0; + if (isset(self::$conversionUnits[$fromUOM])) { + $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; + } else { + $fromMultiplier = substr($fromUOM, 0, 1); + $fromUOM = substr($fromUOM, 1); + if (isset(self::$conversionMultipliers[$fromMultiplier])) { + $fromMultiplier = self::$conversionMultipliers[$fromMultiplier]['multiplier']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + if ((isset(self::$conversionUnits[$fromUOM])) && (self::$conversionUnits[$fromUOM]['AllowPrefix'])) { + $unitGroup1 = self::$conversionUnits[$fromUOM]['Group']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + } + $value *= $fromMultiplier; + + $toMultiplier = 1.0; + if (isset(self::$conversionUnits[$toUOM])) { + $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; + } else { + $toMultiplier = substr($toUOM, 0, 1); + $toUOM = substr($toUOM, 1); + if (isset(self::$conversionMultipliers[$toMultiplier])) { + $toMultiplier = self::$conversionMultipliers[$toMultiplier]['multiplier']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + if ((isset(self::$conversionUnits[$toUOM])) && (self::$conversionUnits[$toUOM]['AllowPrefix'])) { + $unitGroup2 = self::$conversionUnits[$toUOM]['Group']; + } else { + return PHPExcel_Calculation_Functions::NA(); + } + } + if ($unitGroup1 != $unitGroup2) { + return PHPExcel_Calculation_Functions::NA(); + } + + if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) { + // We've already factored $fromMultiplier into the value, so we need + // to reverse it again + return $value / $fromMultiplier; + } elseif ($unitGroup1 == 'Temperature') { + if (($fromUOM == 'F') || ($fromUOM == 'fah')) { + if (($toUOM == 'F') || ($toUOM == 'fah')) { + return $value; + } else { + $value = (($value - 32) / 1.8); + if (($toUOM == 'K') || ($toUOM == 'kel')) { + $value += 273.15; + } + return $value; + } + } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) && + (($toUOM == 'K') || ($toUOM == 'kel'))) { + return $value; + } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) && + (($toUOM == 'C') || ($toUOM == 'cel'))) { + return $value; + } + if (($toUOM == 'F') || ($toUOM == 'fah')) { + if (($fromUOM == 'K') || ($fromUOM == 'kel')) { + $value -= 273.15; + } + return ($value * 1.8) + 32; + } + if (($toUOM == 'C') || ($toUOM == 'cel')) { + return $value - 273.15; + } + return $value + 273.15; + } + return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Exception.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Exception.php new file mode 100644 index 00000000..52d73fc4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Exception.php @@ -0,0 +1,46 @@ +<?php + +/** + * PHPExcel_Calculation_Exception + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Exception extends PHPExcel_Exception +{ + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/ExceptionHandler.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/ExceptionHandler.php new file mode 100644 index 00000000..4cb0a688 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/ExceptionHandler.php @@ -0,0 +1,45 @@ +<?php + +/** + * PHPExcel_Calculation_ExceptionHandler + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_ExceptionHandler +{ + /** + * Register errorhandler + */ + public function __construct() + { + set_error_handler(array('PHPExcel_Calculation_Exception', 'errorHandlerCallback'), E_ALL); + } + + /** + * Unregister errorhandler + */ + public function __destruct() + { + restore_error_handler(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Financial.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Financial.php new file mode 100644 index 00000000..fdf48940 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Financial.php @@ -0,0 +1,2359 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** FINANCIAL_MAX_ITERATIONS */ +define('FINANCIAL_MAX_ITERATIONS', 128); + +/** FINANCIAL_PRECISION */ +define('FINANCIAL_PRECISION', 1.0e-08); + +/** + * PHPExcel_Calculation_Financial + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Financial +{ + /** + * isLastDayOfMonth + * + * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month + * + * @param DateTime $testDate The date for testing + * @return boolean + */ + private static function isLastDayOfMonth($testDate) + { + return ($testDate->format('d') == $testDate->format('t')); + } + + + /** + * isFirstDayOfMonth + * + * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month + * + * @param DateTime $testDate The date for testing + * @return boolean + */ + private static function isFirstDayOfMonth($testDate) + { + return ($testDate->format('d') == 1); + } + + + private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next) + { + $months = 12 / $frequency; + + $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity); + $eom = self::isLastDayOfMonth($result); + + while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) { + $result->modify('-'.$months.' months'); + } + if ($next) { + $result->modify('+'.$months.' months'); + } + + if ($eom) { + $result->modify('-1 day'); + } + + return PHPExcel_Shared_Date::PHPToExcel($result); + } + + + private static function isValidFrequency($frequency) + { + if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) { + return true; + } + if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) && + (($frequency == 6) || ($frequency == 12))) { + return true; + } + return false; + } + + + /** + * daysPerYear + * + * Returns the number of days in a specified year, as defined by the "basis" value + * + * @param integer $year The year against which we're testing + * @param integer $basis The type of day count: + * 0 or omitted US (NASD) 360 + * 1 Actual (365 or 366 in a leap year) + * 2 360 + * 3 365 + * 4 European 360 + * @return integer + */ + private static function daysPerYear($year, $basis = 0) + { + switch ($basis) { + case 0: + case 2: + case 4: + $daysPerYear = 360; + break; + case 3: + $daysPerYear = 365; + break; + case 1: + $daysPerYear = (PHPExcel_Calculation_DateTime::isLeapYear($year)) ? 366 : 365; + break; + default: + return PHPExcel_Calculation_Functions::NaN(); + } + return $daysPerYear; + } + + + private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) + { + $pmt = self::PMT($rate, $nper, $pv, $fv, $type); + $capital = $pv; + for ($i = 1; $i<= $per; ++$i) { + $interest = ($type && $i == 1) ? 0 : -$capital * $rate; + $principal = $pmt - $interest; + $capital += $principal; + } + return array($interest, $principal); + } + + + /** + * ACCRINT + * + * Returns the accrued interest for a security that pays periodic interest. + * + * Excel Function: + * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed $issue The security's issue date. + * @param mixed $firstinterest The security's first interest date. + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date + * when the security is traded to the buyer. + * @param float $rate The security's annual coupon rate. + * @param float $par The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param integer $frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0) + { + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest); + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par); + $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($rate)) && (is_numeric($par))) { + $rate = (float) $rate; + $par = (float) $par; + if (($rate <= 0) || ($par <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + + return $par * $rate * $daysBetweenIssueAndSettlement; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * ACCRINTM + * + * Returns the accrued interest for a security that pays interest at maturity. + * + * Excel Function: + * ACCRINTM(issue,settlement,rate[,par[,basis]]) + * + * @access public + * @category Financial Functions + * @param mixed issue The security's issue date. + * @param mixed settlement The security's settlement (or maturity) date. + * @param float rate The security's annual coupon rate. + * @param float par The security's par value. + * If you omit par, ACCRINT uses $1,000. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0) + { + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par); + $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($rate)) && (is_numeric($par))) { + $rate = (float) $rate; + $par = (float) $par; + if (($rate <= 0) || ($par <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + return $par * $rate * $daysBetweenIssueAndSettlement; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * AMORDEGRC + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * The function is similar to AMORLINC, except that a depreciation coefficient is applied in + * the calculation depending on the life of the assets. + * This function will return the depreciation until the last period of the life of the assets + * or until the cumulated value of depreciation is greater than the cost of the assets minus + * the salvage value. + * + * Excel Function: + * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @access public + * @category Financial Functions + * @param float cost The cost of the asset. + * @param mixed purchased Date of the purchase of the asset. + * @param mixed firstPeriod Date of the end of the first period. + * @param mixed salvage The salvage value at the end of the life of the asset. + * @param float period The period. + * @param float rate Rate of depreciation. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased); + $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period)); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // The depreciation coefficients are: + // Life of assets (1/rate) Depreciation coefficient + // Less than 3 years 1 + // Between 3 and 4 years 1.5 + // Between 5 and 6 years 2 + // More than 6 years 2.5 + $fUsePer = 1.0 / $rate; + if ($fUsePer < 3.0) { + $amortiseCoeff = 1.0; + } elseif ($fUsePer < 5.0) { + $amortiseCoeff = 1.5; + } elseif ($fUsePer <= 6.0) { + $amortiseCoeff = 2.0; + } else { + $amortiseCoeff = 2.5; + } + + $rate *= $amortiseCoeff; + $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost, 0); + $cost -= $fNRate; + $fRest = $cost - $salvage; + + for ($n = 0; $n < $period; ++$n) { + $fNRate = round($rate * $cost, 0); + $fRest -= $fNRate; + + if ($fRest < 0.0) { + switch ($period - $n) { + case 0: + case 1: + return round($cost * 0.5, 0); + default: + return 0.0; + } + } + $cost -= $fNRate; + } + return $fNRate; + } + + + /** + * AMORLINC + * + * Returns the depreciation for each accounting period. + * This function is provided for the French accounting system. If an asset is purchased in + * the middle of the accounting period, the prorated depreciation is taken into account. + * + * Excel Function: + * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis]) + * + * @access public + * @category Financial Functions + * @param float cost The cost of the asset. + * @param mixed purchased Date of the purchase of the asset. + * @param mixed firstPeriod Date of the end of the first period. + * @param mixed salvage The salvage value at the end of the life of the asset. + * @param float period The period. + * @param float rate Rate of depreciation. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased); + $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + $fOneRate = $cost * $rate; + $fCostDelta = $cost - $salvage; + // Note, quirky variation for leap years on the YEARFRAC for this function + $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased); + $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis); + + if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::isLeapYear($purchasedYear))) { + $yearFrac *= 365 / 366; + } + + $f0Rate = $yearFrac * $rate * $cost; + $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate); + + if ($period == 0) { + return $f0Rate; + } elseif ($period <= $nNumOfFullPeriods) { + return $fOneRate; + } elseif ($period == ($nNumOfFullPeriods + 1)) { + return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate); + } else { + return 0.0; + } + } + + + /** + * COUPDAYBS + * + * Returns the number of days from the beginning of the coupon period to the settlement date. + * + * Excel Function: + * COUPDAYBS(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis); + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); + + return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear; + } + + + /** + * COUPDAYS + * + * Returns the number of days in the coupon period that contains the settlement date. + * + * Excel Function: + * COUPDAYS(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + switch ($basis) { + case 3: + // Actual/365 + return 365 / $frequency; + case 1: + // Actual/actual + if ($frequency == 1) { + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity), $basis); + return ($daysPerYear / $frequency); + } + $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + return ($next - $prev); + default: + // US (NASD) 30/360, Actual/360 or European 30/360 + return 360 / $frequency; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * COUPDAYSNC + * + * Returns the number of days from the settlement date to the next coupon date. + * + * Excel Function: + * COUPDAYSNC(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis); + $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + + return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear; + } + + + /** + * COUPNCD + * + * Returns the next coupon date after the settlement date. + * + * Excel Function: + * COUPNCD(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + } + + + /** + * COUPNUM + * + * Returns the number of coupons payable between the settlement date and maturity date, + * rounded up to the nearest whole coupon. + * + * Excel Function: + * COUPNUM(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return integer + */ + public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $settlement = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true); + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365; + + switch ($frequency) { + case 1: // annual payments + return ceil($daysBetweenSettlementAndMaturity / 360); + case 2: // half-yearly + return ceil($daysBetweenSettlementAndMaturity / 180); + case 4: // quarterly + return ceil($daysBetweenSettlementAndMaturity / 90); + case 6: // bimonthly + return ceil($daysBetweenSettlementAndMaturity / 60); + case 12: // monthly + return ceil($daysBetweenSettlementAndMaturity / 30); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * COUPPCD + * + * Returns the previous coupon date before the settlement date. + * + * Excel Function: + * COUPPCD(settlement,maturity,frequency[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed frequency the number of coupon payments per year. + * Valid frequency values are: + * 1 Annual + * 2 Semi-Annual + * 4 Quarterly + * If working in Gnumeric Mode, the following frequency options are + * also available + * 6 Bimonthly + * 12 Monthly + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object, + * depending on the value of the ReturnDateType flag + */ + public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false); + } + + + /** + * CUMIPMT + * + * Returns the cumulative interest paid on a loan between the start and end periods. + * + * Excel Function: + * CUMIPMT(rate,nper,pv,start,end[,type]) + * + * @access public + * @category Financial Functions + * @param float $rate The Interest rate + * @param integer $nper The total number of payment periods + * @param float $pv Present Value + * @param integer $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param integer $end The last period in the calculation. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start); + $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($start < 1 || $start > $end) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interest = 0; + for ($per = $start; $per <= $end; ++$per) { + $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type); + } + + return $interest; + } + + + /** + * CUMPRINC + * + * Returns the cumulative principal paid on a loan between the start and end periods. + * + * Excel Function: + * CUMPRINC(rate,nper,pv,start,end[,type]) + * + * @access public + * @category Financial Functions + * @param float $rate The Interest rate + * @param integer $nper The total number of payment periods + * @param float $pv Present Value + * @param integer $start The first period in the calculation. + * Payment periods are numbered beginning with 1. + * @param integer $end The last period in the calculation. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start); + $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($start < 1 || $start > $end) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $principal = 0; + for ($per = $start; $per <= $end; ++$per) { + $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type); + } + + return $principal; + } + + + /** + * DB + * + * Returns the depreciation of an asset for a specified period using the + * fixed-declining balance method. + * This form of depreciation is used if you want to get a higher depreciation value + * at the beginning of the depreciation (as opposed to linear depreciation). The + * depreciation value is reduced with every depreciation period by the depreciation + * already deducted from the initial cost. + * + * Excel Function: + * DB(cost,salvage,life,period[,month]) + * + * @access public + * @category Financial Functions + * @param float cost Initial cost of the asset. + * @param float salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param integer life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param integer period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param integer month Number of months in the first year. If month is omitted, + * it defaults to 12. + * @return float + */ + public static function DB($cost, $salvage, $life, $period, $month = 12) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $month = PHPExcel_Calculation_Functions::flattenSingleValue($month); + + // Validate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) { + $cost = (float) $cost; + $salvage = (float) $salvage; + $life = (int) $life; + $period = (int) $period; + $month = (int) $month; + if ($cost == 0) { + return 0.0; + } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + $previousDepreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + if ($per == 1) { + $depreciation = $cost * $fixedDepreciationRate * $month / 12; + } elseif ($per == ($life + 1)) { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12; + } else { + $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate; + } + $previousDepreciation += $depreciation; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $depreciation = round($depreciation, 2); + } + return $depreciation; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * DDB + * + * Returns the depreciation of an asset for a specified period using the + * double-declining balance method or some other method you specify. + * + * Excel Function: + * DDB(cost,salvage,life,period[,factor]) + * + * @access public + * @category Financial Functions + * @param float cost Initial cost of the asset. + * @param float salvage Value at the end of the depreciation. + * (Sometimes called the salvage value of the asset) + * @param integer life Number of periods over which the asset is depreciated. + * (Sometimes called the useful life of the asset) + * @param integer period The period for which you want to calculate the + * depreciation. Period must use the same units as life. + * @param float factor The rate at which the balance declines. + * If factor is omitted, it is assumed to be 2 (the + * double-declining balance method). + * @return float + */ + public static function DDB($cost, $salvage, $life, $period, $factor = 2.0) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor); + + // Validate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) { + $cost = (float) $cost; + $salvage = (float) $salvage; + $life = (int) $life; + $period = (int) $period; + $factor = (float) $factor; + if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // Set Fixed Depreciation Rate + $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life)); + $fixedDepreciationRate = round($fixedDepreciationRate, 3); + + // Loop through each period calculating the depreciation + $previousDepreciation = 0; + for ($per = 1; $per <= $period; ++$per) { + $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation)); + $previousDepreciation += $depreciation; + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + $depreciation = round($depreciation, 2); + } + return $depreciation; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * DISC + * + * Returns the discount rate for a security. + * + * Excel Function: + * DISC(settlement,maturity,price,redemption[,basis]) + * + * @access public + * @category Financial Functions + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue + * date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param integer price The security's price per $100 face value. + * @param integer redemption The security's redemption value per $100 face value. + * @param integer basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) { + $price = (float) $price; + $redemption = (float) $redemption; + $basis = (int) $basis; + if (($price <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * DOLLARDE + * + * Converts a dollar price expressed as an integer part and a fraction + * part into a dollar price expressed as a decimal number. + * Fractional dollar numbers are sometimes used for security prices. + * + * Excel Function: + * DOLLARDE(fractional_dollar,fraction) + * + * @access public + * @category Financial Functions + * @param float $fractional_dollar Fractional Dollar + * @param integer $fraction Fraction + * @return float + */ + public static function DOLLARDE($fractional_dollar = null, $fraction = 0) + { + $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar); + $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction); + + // Validate parameters + if (is_null($fractional_dollar) || $fraction < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($fraction == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $dollars = floor($fractional_dollar); + $cents = fmod($fractional_dollar, 1); + $cents /= $fraction; + $cents *= pow(10, ceil(log10($fraction))); + return $dollars + $cents; + } + + + /** + * DOLLARFR + * + * Converts a dollar price expressed as a decimal number into a dollar price + * expressed as a fraction. + * Fractional dollar numbers are sometimes used for security prices. + * + * Excel Function: + * DOLLARFR(decimal_dollar,fraction) + * + * @access public + * @category Financial Functions + * @param float $decimal_dollar Decimal Dollar + * @param integer $fraction Fraction + * @return float + */ + public static function DOLLARFR($decimal_dollar = null, $fraction = 0) + { + $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar); + $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction); + + // Validate parameters + if (is_null($decimal_dollar) || $fraction < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($fraction == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $dollars = floor($decimal_dollar); + $cents = fmod($decimal_dollar, 1); + $cents *= $fraction; + $cents *= pow(10, -ceil(log10($fraction))); + return $dollars + $cents; + } + + + /** + * EFFECT + * + * Returns the effective interest rate given the nominal rate and the number of + * compounding payments per year. + * + * Excel Function: + * EFFECT(nominal_rate,npery) + * + * @access public + * @category Financial Functions + * @param float $nominal_rate Nominal interest rate + * @param integer $npery Number of compounding payments per year + * @return float + */ + public static function EFFECT($nominal_rate = 0, $npery = 0) + { + $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate); + $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery); + + // Validate parameters + if ($nominal_rate <= 0 || $npery < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return pow((1 + $nominal_rate / $npery), $npery) - 1; + } + + + /** + * FV + * + * Returns the Future Value of a cash flow with constant payments and interest rate (annuities). + * + * Excel Function: + * FV(rate,nper,pmt[,pv[,type]]) + * + * @access public + * @category Financial Functions + * @param float $rate The interest rate per period + * @param int $nper Total number of payment periods in an annuity + * @param float $pmt The payment made each period: it cannot change over the + * life of the annuity. Typically, pmt contains principal + * and interest but no other fees or taxes. + * @param float $pv Present Value, or the lump-sum amount that a series of + * future payments is worth right now. + * @param integer $type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @return float + */ + public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate; + } + return -$pv - $pmt * $nper; + } + + + /** + * FVSCHEDULE + * + * Returns the future value of an initial principal after applying a series of compound interest rates. + * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate. + * + * Excel Function: + * FVSCHEDULE(principal,schedule) + * + * @param float $principal The present value. + * @param float[] $schedule An array of interest rates to apply. + * @return float + */ + public static function FVSCHEDULE($principal, $schedule) + { + $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal); + $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule); + + foreach ($schedule as $rate) { + $principal *= 1 + $rate; + } + + return $principal; + } + + + /** + * INTRATE + * + * Returns the interest rate for a fully invested security. + * + * Excel Function: + * INTRATE(settlement,maturity,investment,redemption[,basis]) + * + * @param mixed $settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed $maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param integer $investment The amount invested in the security. + * @param integer $redemption The amount to be received at maturity. + * @param integer $basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) { + $investment = (float) $investment; + $redemption = (float) $redemption; + $basis = (int) $basis; + if (($investment <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * IPMT + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * + * Excel Function: + * IPMT(rate,per,nper,pv[,fv][,type]) + * + * @param float $rate Interest rate per period + * @param int $per Period for which we want to find the interest + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($per <= 0 || $per > $nper) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[0]; + } + + /** + * IRR + * + * Returns the internal rate of return for a series of cash flows represented by the numbers in values. + * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur + * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received + * for an investment consisting of payments (negative values) and income (positive values) that occur at regular + * periods. + * + * Excel Function: + * IRR(values[,guess]) + * + * @param float[] $values An array or a reference to cells that contain numbers for which you want + * to calculate the internal rate of return. + * Values must contain at least one positive value and one negative value to + * calculate the internal rate of return. + * @param float $guess A number that you guess is close to the result of IRR + * @return float + */ + public static function IRR($values, $guess = 0.1) + { + if (!is_array($values)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess); + + // create an initial range, with a root somewhere between 0 and guess + $x1 = 0.0; + $x2 = $guess; + $f1 = self::NPV($x1, $values); + $f2 = self::NPV($x2, $values); + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + if (($f1 * $f2) < 0.0) { + break; + } + if (abs($f1) < abs($f2)) { + $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values); + } else { + $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values); + } + } + if (($f1 * $f2) > 0.0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $f = self::NPV($x1, $values); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::NPV($x_mid, $values); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) { + return $x_mid; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * ISPMT + * + * Returns the interest payment for an investment based on an interest rate and a constant payment schedule. + * + * Excel Function: + * =ISPMT(interest_rate, period, number_payments, PV) + * + * interest_rate is the interest rate for the investment + * + * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments. + * + * number_payments is the number of payments for the annuity + * + * PV is the loan amount or present value of the payments + */ + public static function ISPMT() + { + // Return value + $returnValue = 0; + + // Get the parameters + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $interestRate = array_shift($aArgs); + $period = array_shift($aArgs); + $numberPeriods = array_shift($aArgs); + $principleRemaining = array_shift($aArgs); + + // Calculate + $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0); + for ($i=0; $i <= $period; ++$i) { + $returnValue = $interestRate * $principleRemaining * -1; + $principleRemaining -= $principlePayment; + // principle needs to be 0 after the last payment, don't let floating point screw it up + if ($i == $numberPeriods) { + $returnValue = 0; + } + } + return($returnValue); + } + + + /** + * MIRR + * + * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both + * the cost of the investment and the interest received on reinvestment of cash. + * + * Excel Function: + * MIRR(values,finance_rate, reinvestment_rate) + * + * @param float[] $values An array or a reference to cells that contain a series of payments and + * income occurring at regular intervals. + * Payments are negative value, income is positive values. + * @param float $finance_rate The interest rate you pay on the money used in the cash flows + * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them + * @return float + */ + public static function MIRR($values, $finance_rate, $reinvestment_rate) + { + if (!is_array($values)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate); + $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate); + $n = count($values); + + $rr = 1.0 + $reinvestment_rate; + $fr = 1.0 + $finance_rate; + + $npv_pos = $npv_neg = 0.0; + foreach ($values as $i => $v) { + if ($v >= 0) { + $npv_pos += $v / pow($rr, $i); + } else { + $npv_neg += $v / pow($fr, $i); + } + } + + if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $mirr = pow((-$npv_pos * pow($rr, $n)) + / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0; + + return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE()); + } + + + /** + * NOMINAL + * + * Returns the nominal interest rate given the effective rate and the number of compounding payments per year. + * + * @param float $effect_rate Effective interest rate + * @param int $npery Number of compounding payments per year + * @return float + */ + public static function NOMINAL($effect_rate = 0, $npery = 0) + { + $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate); + $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery); + + // Validate parameters + if ($effect_rate <= 0 || $npery < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + return $npery * (pow($effect_rate + 1, 1 / $npery) - 1); + } + + + /** + * NPER + * + * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate. + * + * @param float $rate Interest rate per period + * @param int $pmt Periodic payment (annuity) + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + if ($pmt == 0 && $pv == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate); + } + if ($pmt == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (-$pv -$fv) / $pmt; + } + + /** + * NPV + * + * Returns the Net Present Value of a cash flow series given a discount rate. + * + * @return float + */ + public static function NPV() + { + // Return value + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $rate = array_shift($aArgs); + for ($i = 1; $i <= count($aArgs); ++$i) { + // Is it a numeric value? + if (is_numeric($aArgs[$i - 1])) { + $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i); + } + } + + // Return + return $returnValue; + } + + /** + * PMT + * + * Returns the constant payment (annuity) for a cash flow with a constant interest rate. + * + * @param float $rate Interest rate per period + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate); + } + return (-$pv - $fv) / $nper; + } + + + /** + * PPMT + * + * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate. + * + * @param float $rate Interest rate per period + * @param int $per Period for which we want to find the interest + * @param int $nper Number of periods + * @param float $pv Present Value + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per); + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($per <= 0 || $per > $nper) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Calculate + $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type); + return $interestAndPrincipal[1]; + } + + + public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield); + $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency); + $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (($settlement > $maturity) || + (!self::isValidFrequency($frequency)) || + (($basis < 0) || ($basis > 4))) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis); + $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis); + $n = self::COUPNUM($settlement, $maturity, $frequency, $basis); + $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis); + + $baseYF = 1.0 + ($yield / $frequency); + $rfp = 100 * ($rate / $frequency); + $de = $dsc / $e; + + $result = $redemption / pow($baseYF, (--$n + $de)); + for ($k = 0; $k <= $n; ++$k) { + $result += $rfp / (pow($baseYF, ($k + $de))); + } + $result -= $rfp * ($a / $e); + + return $result; + } + + + /** + * PRICEDISC + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int discount The security's discount rate. + * @param int redemption The security's redemption value per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount); + $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) { + if (($discount <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * PRICEMAT + * + * Returns the price per $100 face value of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed issue The security's issue date. + * @param int rate The security's interest rate at date of issue. + * @param int yield The security's annual yield. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($rate) && is_numeric($yield)) { + if (($rate <= 0) || ($yield <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) / + (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) - + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * PV + * + * Returns the Present Value of a cash flow with constant payments and interest rate (annuities). + * + * @param float $rate Interest rate per period + * @param int $nper Number of periods + * @param float $pmt Periodic payment (annuity) + * @param float $fv Future Value + * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period + * @return float + */ + public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = PHPExcel_Calculation_Functions::flattenSingleValue($type); + + // Validate parameters + if ($type != 0 && $type != 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // Calculate + if (!is_null($rate) && $rate != 0) { + return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper); + } + return -$fv - $pmt * $nper; + } + + + /** + * RATE + * + * Returns the interest rate per period of an annuity. + * RATE is calculated by iteration and can have zero or more solutions. + * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations, + * RATE returns the #NUM! error value. + * + * Excel Function: + * RATE(nper,pmt,pv[,fv[,type[,guess]]]) + * + * @access public + * @category Financial Functions + * @param float nper The total number of payment periods in an annuity. + * @param float pmt The payment made each period and cannot change over the life + * of the annuity. + * Typically, pmt includes principal and interest but no other + * fees or taxes. + * @param float pv The present value - the total amount that a series of future + * payments is worth now. + * @param float fv The future value, or a cash balance you want to attain after + * the last payment is made. If fv is omitted, it is assumed + * to be 0 (the future value of a loan, for example, is 0). + * @param integer type A number 0 or 1 and indicates when payments are due: + * 0 or omitted At the end of the period. + * 1 At the beginning of the period. + * @param float guess Your guess for what the rate will be. + * If you omit guess, it is assumed to be 10 percent. + * @return float + **/ + public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1) + { + $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper); + $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt); + $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv); + $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv); + $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type); + $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess); + + $rate = $guess; + if (abs($rate) < FINANCIAL_PRECISION) { + $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; + } else { + $f = exp($nper * log(1 + $rate)); + $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + } + $y0 = $pv + $pmt * $nper + $fv; + $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + + // find root by secant method + $i = $x0 = 0.0; + $x1 = $rate; + while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) { + $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0); + $x0 = $x1; + $x1 = $rate; + if (($nper * abs($pmt)) > ($pv - $fv)) { + $x1 = abs($x1); + } + if (abs($rate) < FINANCIAL_PRECISION) { + $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv; + } else { + $f = exp($nper * log(1 + $rate)); + $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv; + } + + $y0 = $y1; + $y1 = $y; + ++$i; + } + return $rate; + } + + + /** + * RECEIVED + * + * Returns the price per $100 face value of a discounted security. + * + * @param mixed settlement The security's settlement date. + * The security settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int investment The amount invested in the security. + * @param int discount The security's discount rate. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment); + $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) { + if (($investment <= 0) || ($discount <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + + return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SLN + * + * Returns the straight-line depreciation of an asset for one period + * + * @param cost Initial cost of the asset + * @param salvage Value at the end of the depreciation + * @param life Number of periods over which the asset is depreciated + * @return float + */ + public static function SLN($cost, $salvage, $life) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + + // Calculate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) { + if ($life < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return ($cost - $salvage) / $life; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SYD + * + * Returns the sum-of-years' digits depreciation of an asset for a specified period. + * + * @param cost Initial cost of the asset + * @param salvage Value at the end of the depreciation + * @param life Number of periods over which the asset is depreciated + * @param period Period + * @return float + */ + public static function SYD($cost, $salvage, $life, $period) + { + $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost); + $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage); + $life = PHPExcel_Calculation_Functions::flattenSingleValue($life); + $period = PHPExcel_Calculation_Functions::flattenSingleValue($period); + + // Calculate + if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) { + if (($life < 1) || ($period > $life)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * TBILLEQ + * + * Returns the bond-equivalent yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int discount The Treasury bill's discount rate. + * @return float + */ + public static function TBILLEQ($settlement, $maturity, $discount) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount); + + // Use TBILLPRICE for validation + $testValue = self::TBILLPRICE($settlement, $maturity, $discount); + if (is_string($testValue)) { + return $testValue; + } + + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement)); + } + + return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity); + } + + + /** + * TBILLPRICE + * + * Returns the yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int discount The Treasury bill's discount rate. + * @return float + */ + public static function TBILLPRICE($settlement, $maturity, $discount) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount); + + if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // Validate + if (is_numeric($discount)) { + if ($discount <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement)); + } + + if ($daysBetweenSettlementAndMaturity > 360) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360)); + if ($price <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return $price; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * TBILLYIELD + * + * Returns the yield for a Treasury bill. + * + * @param mixed settlement The Treasury bill's settlement date. + * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer. + * @param mixed maturity The Treasury bill's maturity date. + * The maturity date is the date when the Treasury bill expires. + * @param int price The Treasury bill's price per $100 face value. + * @return float + */ + public static function TBILLYIELD($settlement, $maturity, $price) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + + // Validate + if (is_numeric($price)) { + if ($price <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + ++$maturity; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360; + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + } else { + $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement)); + } + + if ($daysBetweenSettlementAndMaturity > 360) { + return PHPExcel_Calculation_Functions::NaN(); + } + + return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + public static function XIRR($values, $dates, $guess = 0.1) + { + if ((!is_array($values)) && (!is_array($dates))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $dates = PHPExcel_Calculation_Functions::flattenArray($dates); + $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess); + if (count($values) != count($dates)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + // create an initial range, with a root somewhere between 0 and guess + $x1 = 0.0; + $x2 = $guess; + $f1 = self::XNPV($x1, $values, $dates); + $f2 = self::XNPV($x2, $values, $dates); + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + if (($f1 * $f2) < 0.0) { + break; + } elseif (abs($f1) < abs($f2)) { + $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates); + } else { + $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates); + } + } + if (($f1 * $f2) > 0.0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $f = self::XNPV($x1, $values, $dates); + if ($f < 0.0) { + $rtb = $x1; + $dx = $x2 - $x1; + } else { + $rtb = $x2; + $dx = $x1 - $x2; + } + + for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) { + $dx *= 0.5; + $x_mid = $rtb + $dx; + $f_mid = self::XNPV($x_mid, $values, $dates); + if ($f_mid <= 0.0) { + $rtb = $x_mid; + } + if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) { + return $x_mid; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * XNPV + * + * Returns the net present value for a schedule of cash flows that is not necessarily periodic. + * To calculate the net present value for a series of cash flows that is periodic, use the NPV function. + * + * Excel Function: + * =XNPV(rate,values,dates) + * + * @param float $rate The discount rate to apply to the cash flows. + * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates. + * The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment. + * If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year. + * The series of values must contain at least one positive value and one negative value. + * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments. + * The first payment date indicates the beginning of the schedule of payments. + * All other dates must be later than this date, but they may occur in any order. + * @return float + */ + public static function XNPV($rate, $values, $dates) + { + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + if (!is_numeric($rate)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if ((!is_array($values)) || (!is_array($dates))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $values = PHPExcel_Calculation_Functions::flattenArray($values); + $dates = PHPExcel_Calculation_Functions::flattenArray($dates); + $valCount = count($values); + if ($valCount != count($dates)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((min($values) > 0) || (max($values) < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + $xnpv = 0.0; + for ($i = 0; $i < $valCount; ++$i) { + if (!is_numeric($values[$i])) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365); + } + return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * YIELDDISC + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param int price The security's price per $100 face value. + * @param int redemption The security's redemption value per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($price) && is_numeric($redemption)) { + if (($price <= 0) || ($redemption <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * YIELDMAT + * + * Returns the annual yield of a security that pays interest at maturity. + * + * @param mixed settlement The security's settlement date. + * The security's settlement date is the date after the issue date when the security is traded to the buyer. + * @param mixed maturity The security's maturity date. + * The maturity date is the date when the security expires. + * @param mixed issue The security's issue date. + * @param int rate The security's interest rate at date of issue. + * @param int price The security's price per $100 face value. + * @param int basis The type of day count to use. + * 0 or omitted US (NASD) 30/360 + * 1 Actual/actual + * 2 Actual/360 + * 3 Actual/365 + * 4 European 30/360 + * @return float + */ + public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0) + { + $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement); + $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity); + $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue); + $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate); + $price = PHPExcel_Calculation_Functions::flattenSingleValue($price); + $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis); + + // Validate + if (is_numeric($rate) && is_numeric($price)) { + if (($rate <= 0) || ($price <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis); + if (!is_numeric($daysPerYear)) { + return $daysPerYear; + } + $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis); + if (!is_numeric($daysBetweenIssueAndSettlement)) { + // return date error + return $daysBetweenIssueAndSettlement; + } + $daysBetweenIssueAndSettlement *= $daysPerYear; + $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis); + if (!is_numeric($daysBetweenIssueAndMaturity)) { + // return date error + return $daysBetweenIssueAndMaturity; + } + $daysBetweenIssueAndMaturity *= $daysPerYear; + $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis); + if (!is_numeric($daysBetweenSettlementAndMaturity)) { + // return date error + return $daysBetweenSettlementAndMaturity; + } + $daysBetweenSettlementAndMaturity *= $daysPerYear; + + return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) / + (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) * + ($daysPerYear / $daysBetweenSettlementAndMaturity); + } + return PHPExcel_Calculation_Functions::VALUE(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaParser.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaParser.php new file mode 100644 index 00000000..893f19e9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaParser.php @@ -0,0 +1,622 @@ +<?php + +/* +PARTLY BASED ON: + Copyright (c) 2007 E. W. Bachtal, Inc. + + 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. + + http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html + http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html +*/ + +/** + * PHPExcel_Calculation_FormulaParser + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +class PHPExcel_Calculation_FormulaParser +{ + /* Character constants */ + const QUOTE_DOUBLE = '"'; + const QUOTE_SINGLE = '\''; + const BRACKET_CLOSE = ']'; + const BRACKET_OPEN = '['; + const BRACE_OPEN = '{'; + const BRACE_CLOSE = '}'; + const PAREN_OPEN = '('; + const PAREN_CLOSE = ')'; + const SEMICOLON = ';'; + const WHITESPACE = ' '; + const COMMA = ','; + const ERROR_START = '#'; + + const OPERATORS_SN = "+-"; + const OPERATORS_INFIX = "+-*/^&=><"; + const OPERATORS_POSTFIX = "%"; + + /** + * Formula + * + * @var string + */ + private $formula; + + /** + * Tokens + * + * @var PHPExcel_Calculation_FormulaToken[] + */ + private $tokens = array(); + + /** + * Create a new PHPExcel_Calculation_FormulaParser + * + * @param string $pFormula Formula to parse + * @throws PHPExcel_Calculation_Exception + */ + public function __construct($pFormula = '') + { + // Check parameters + if (is_null($pFormula)) { + throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula"); + } + + // Initialise values + $this->formula = trim($pFormula); + // Parse! + $this->parseToTokens(); + } + + /** + * Get Formula + * + * @return string + */ + public function getFormula() + { + return $this->formula; + } + + /** + * Get Token + * + * @param int $pId Token id + * @return string + * @throws PHPExcel_Calculation_Exception + */ + public function getToken($pId = 0) + { + if (isset($this->tokens[$pId])) { + return $this->tokens[$pId]; + } else { + throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist."); + } + } + + /** + * Get Token count + * + * @return string + */ + public function getTokenCount() + { + return count($this->tokens); + } + + /** + * Get Tokens + * + * @return PHPExcel_Calculation_FormulaToken[] + */ + public function getTokens() + { + return $this->tokens; + } + + /** + * Parse to tokens + */ + private function parseToTokens() + { + // No attempt is made to verify formulas; assumes formulas are derived from Excel, where + // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions. + + // Check if the formula has a valid starting = + $formulaLength = strlen($this->formula); + if ($formulaLength < 2 || $this->formula{0} != '=') { + return; + } + + // Helper variables + $tokens1 = $tokens2 = $stack = array(); + $inString = $inPath = $inRange = $inError = false; + $token = $previousToken = $nextToken = null; + + $index = 1; + $value = ''; + + $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A"); + $COMPARATORS_MULTI = array(">=", "<=", "<>"); + + while ($index < $formulaLength) { + // state-dependent character evaluation (order is important) + + // double-quoted strings + // embeds are doubled + // end marks token + if ($inString) { + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) { + if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) { + $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE; + ++$index; + } else { + $inString = false; + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT); + $value = ""; + } + } else { + $value .= $this->formula{$index}; + } + ++$index; + continue; + } + + // single-quoted strings (links) + // embeds are double + // end does not mark a token + if ($inPath) { + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) { + if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) { + $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE; + ++$index; + } else { + $inPath = false; + } + } else { + $value .= $this->formula{$index}; + } + ++$index; + continue; + } + + // bracked strings (R1C1 range index or linked workbook name) + // no embeds (changed to "()" by Excel) + // end does not mark a token + if ($inRange) { + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) { + $inRange = false; + } + $value .= $this->formula{$index}; + ++$index; + continue; + } + + // error values + // end marks a token, determined from absolute list of values + if ($inError) { + $value .= $this->formula{$index}; + ++$index; + if (in_array($value, $ERRORS)) { + $inError = false; + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR); + $value = ""; + } + continue; + } + + // scientific notation check + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->formula{$index}) !== false) { + if (strlen($value) > 1) { + if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->formula{$index}) != 0) { + $value .= $this->formula{$index}; + ++$index; + continue; + } + } + } + + // independent character evaluation (order not important) + + // establish state-dependent character evaluations + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) { + if (strlen($value > 0)) { + // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inString = true; + ++$index; + continue; + } + + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) { + if (strlen($value) > 0) { + // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inPath = true; + ++$index; + continue; + } + + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) { + $inRange = true; + $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN; + ++$index; + continue; + } + + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) { + if (strlen($value) > 0) { + // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + $inError = true; + $value .= PHPExcel_Calculation_FormulaParser::ERROR_START; + ++$index; + continue; + } + + // mark start and end of arrays and array rows + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) { + if (strlen($value) > 0) { + // unexpected + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN); + $value = ""; + } + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + ++$index; + continue; + } + + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT); + $tokens1[] = $tmp; + + $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + + ++$index; + continue; + } + + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + ++$index; + continue; + } + + // trim white-space + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE); + ++$index; + while (($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) { + ++$index; + } + continue; + } + + // multi-character comparators + if (($index + 2) <= $formulaLength) { + if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + $index += 2; + continue; + } + } + + // standard infix operators + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->formula{$index}) !== false) { + if (strlen($value) > 0) { + $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX); + ++$index; + continue; + } + + // standard postfix operators (only one) + if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->formula{$index}) !== false) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX); + ++$index; + continue; + } + + // start subexpression or function + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) { + if (strlen($value) > 0) { + $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + $value = ""; + } else { + $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START); + $tokens1[] = $tmp; + $stack[] = clone $tmp; + } + ++$index; + continue; + } + + // function, subexpression, or array parameters, or operand unions + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $stack[] = $tmp; + + if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION); + } else { + $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT); + } + ++$index; + continue; + } + + // stop subexpression + if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) { + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + $value = ""; + } + + $tmp = array_pop($stack); + $tmp->setValue(""); + $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP); + $tokens1[] = $tmp; + + ++$index; + continue; + } + + // token accumulation + $value .= $this->formula{$index}; + ++$index; + } + + // dump remaining accumulation + if (strlen($value) > 0) { + $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND); + } + + // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections + $tokenCount = count($tokens1); + for ($i = 0; $i < $tokenCount; ++$i) { + $token = $tokens1[$i]; + if (isset($tokens1[$i - 1])) { + $previousToken = $tokens1[$i - 1]; + } else { + $previousToken = null; + } + if (isset($tokens1[$i + 1])) { + $nextToken = $tokens1[$i + 1]; + } else { + $nextToken = null; + } + + if (is_null($token)) { + continue; + } + + if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) { + $tokens2[] = $token; + continue; + } + + if (is_null($previousToken)) { + continue; + } + + if (! ( + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) ) { + continue; + } + + if (is_null($nextToken)) { + continue; + } + + if (! ( + (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) || + (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) || + ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND) + ) ) { + continue; + } + + $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION); + } + + // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators + // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names + $this->tokens = array(); + + $tokenCount = count($tokens2); + for ($i = 0; $i < $tokenCount; ++$i) { + $token = $tokens2[$i]; + if (isset($tokens2[$i - 1])) { + $previousToken = $tokens2[$i - 1]; + } else { + $previousToken = null; + } + if (isset($tokens2[$i + 1])) { + $nextToken = $tokens2[$i + 1]; + } else { + $nextToken = null; + } + + if (is_null($token)) { + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") { + if ($i == 0) { + $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX); + } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && + ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && + ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } else { + $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX); + } + + $this->tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") { + if ($i == 0) { + continue; + } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && + ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && + ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) || + ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } else { + continue; + } + + $this->tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && + $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + } elseif ($token->getValue() == "&") { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION); + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH); + } + + $this->tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND && + $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) { + if (!is_numeric($token->getValue())) { + if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL); + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE); + } + } else { + $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER); + } + + $this->tokens[] = $token; + continue; + } + + if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) { + if (strlen($token->getValue() > 0)) { + if (substr($token->getValue(), 0, 1) == "@") { + $token->setValue(substr($token->getValue(), 1)); + } + } + } + + $this->tokens[] = $token; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaToken.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaToken.php new file mode 100644 index 00000000..41c6e3d5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/FormulaToken.php @@ -0,0 +1,176 @@ +<?php + +/* +PARTLY BASED ON: + Copyright (c) 2007 E. W. Bachtal, Inc. + + 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. + + http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html + http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html +*/ + +/** + * PHPExcel_Calculation_FormulaToken + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +class PHPExcel_Calculation_FormulaToken +{ + /* Token types */ + const TOKEN_TYPE_NOOP = 'Noop'; + const TOKEN_TYPE_OPERAND = 'Operand'; + const TOKEN_TYPE_FUNCTION = 'Function'; + const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression'; + const TOKEN_TYPE_ARGUMENT = 'Argument'; + const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix'; + const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix'; + const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix'; + const TOKEN_TYPE_WHITESPACE = 'Whitespace'; + const TOKEN_TYPE_UNKNOWN = 'Unknown'; + + /* Token subtypes */ + const TOKEN_SUBTYPE_NOTHING = 'Nothing'; + const TOKEN_SUBTYPE_START = 'Start'; + const TOKEN_SUBTYPE_STOP = 'Stop'; + const TOKEN_SUBTYPE_TEXT = 'Text'; + const TOKEN_SUBTYPE_NUMBER = 'Number'; + const TOKEN_SUBTYPE_LOGICAL = 'Logical'; + const TOKEN_SUBTYPE_ERROR = 'Error'; + const TOKEN_SUBTYPE_RANGE = 'Range'; + const TOKEN_SUBTYPE_MATH = 'Math'; + const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation'; + const TOKEN_SUBTYPE_INTERSECTION = 'Intersection'; + const TOKEN_SUBTYPE_UNION = 'Union'; + + /** + * Value + * + * @var string + */ + private $value; + + /** + * Token Type (represented by TOKEN_TYPE_*) + * + * @var string + */ + private $tokenType; + + /** + * Token SubType (represented by TOKEN_SUBTYPE_*) + * + * @var string + */ + private $tokenSubType; + + /** + * Create a new PHPExcel_Calculation_FormulaToken + * + * @param string $pValue + * @param string $pTokenType Token type (represented by TOKEN_TYPE_*) + * @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*) + */ + public function __construct($pValue, $pTokenType = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN, $pTokenSubType = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) + { + // Initialise values + $this->value = $pValue; + $this->tokenType = $pTokenType; + $this->tokenSubType = $pTokenSubType; + } + + /** + * Get Value + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set Value + * + * @param string $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /** + * Get Token Type (represented by TOKEN_TYPE_*) + * + * @return string + */ + public function getTokenType() + { + return $this->tokenType; + } + + /** + * Set Token Type + * + * @param string $value + */ + public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN) + { + $this->tokenType = $value; + } + + /** + * Get Token SubType (represented by TOKEN_SUBTYPE_*) + * + * @return string + */ + public function getTokenSubType() + { + return $this->tokenSubType; + } + + /** + * Set Token SubType + * + * @param string $value + */ + public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) + { + $this->tokenSubType = $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Function.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Function.php new file mode 100644 index 00000000..d58cef25 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Function.php @@ -0,0 +1,148 @@ +<?php + +/** + * PHPExcel_Calculation_Function + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Function +{ + /* Function categories */ + const CATEGORY_CUBE = 'Cube'; + const CATEGORY_DATABASE = 'Database'; + const CATEGORY_DATE_AND_TIME = 'Date and Time'; + const CATEGORY_ENGINEERING = 'Engineering'; + const CATEGORY_FINANCIAL = 'Financial'; + const CATEGORY_INFORMATION = 'Information'; + const CATEGORY_LOGICAL = 'Logical'; + const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference'; + const CATEGORY_MATH_AND_TRIG = 'Math and Trig'; + const CATEGORY_STATISTICAL = 'Statistical'; + const CATEGORY_TEXT_AND_DATA = 'Text and Data'; + + /** + * Category (represented by CATEGORY_*) + * + * @var string + */ + private $category; + + /** + * Excel name + * + * @var string + */ + private $excelName; + + /** + * PHPExcel name + * + * @var string + */ + private $phpExcelName; + + /** + * Create a new PHPExcel_Calculation_Function + * + * @param string $pCategory Category (represented by CATEGORY_*) + * @param string $pExcelName Excel function name + * @param string $pPHPExcelName PHPExcel function mapping + * @throws PHPExcel_Calculation_Exception + */ + public function __construct($pCategory = null, $pExcelName = null, $pPHPExcelName = null) + { + if (($pCategory !== null) && ($pExcelName !== null) && ($pPHPExcelName !== null)) { + // Initialise values + $this->category = $pCategory; + $this->excelName = $pExcelName; + $this->phpExcelName = $pPHPExcelName; + } else { + throw new PHPExcel_Calculation_Exception("Invalid parameters passed."); + } + } + + /** + * Get Category (represented by CATEGORY_*) + * + * @return string + */ + public function getCategory() + { + return $this->category; + } + + /** + * Set Category (represented by CATEGORY_*) + * + * @param string $value + * @throws PHPExcel_Calculation_Exception + */ + public function setCategory($value = null) + { + if (!is_null($value)) { + $this->category = $value; + } else { + throw new PHPExcel_Calculation_Exception("Invalid parameter passed."); + } + } + + /** + * Get Excel name + * + * @return string + */ + public function getExcelName() + { + return $this->excelName; + } + + /** + * Set Excel name + * + * @param string $value + */ + public function setExcelName($value) + { + $this->excelName = $value; + } + + /** + * Get PHPExcel name + * + * @return string + */ + public function getPHPExcelName() + { + return $this->phpExcelName; + } + + /** + * Set PHPExcel name + * + * @param string $value + */ + public function setPHPExcelName($value) + { + $this->phpExcelName = $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Functions.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Functions.php new file mode 100644 index 00000000..5a1e5ee5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Functions.php @@ -0,0 +1,760 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + + +/** MAX_VALUE */ +define('MAX_VALUE', 1.2e308); + +/** 2 / PI */ +define('M_2DIVPI', 0.63661977236758134307553505349006); + +/** MAX_ITERATIONS */ +define('MAX_ITERATIONS', 256); + +/** PRECISION */ +define('PRECISION', 8.88E-016); + + +/** + * PHPExcel_Calculation_Functions + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Functions +{ + + /** constants */ + const COMPATIBILITY_EXCEL = 'Excel'; + const COMPATIBILITY_GNUMERIC = 'Gnumeric'; + const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc'; + + const RETURNDATE_PHP_NUMERIC = 'P'; + const RETURNDATE_PHP_OBJECT = 'O'; + const RETURNDATE_EXCEL = 'E'; + + + /** + * Compatibility mode to use for error checking and responses + * + * @access private + * @var string + */ + protected static $compatibilityMode = self::COMPATIBILITY_EXCEL; + + /** + * Data Type to use when returning date values + * + * @access private + * @var string + */ + protected static $returnDateType = self::RETURNDATE_EXCEL; + + /** + * List of error codes + * + * @access private + * @var array + */ + protected static $errorCodes = array( + 'null' => '#NULL!', + 'divisionbyzero' => '#DIV/0!', + 'value' => '#VALUE!', + 'reference' => '#REF!', + 'name' => '#NAME?', + 'num' => '#NUM!', + 'na' => '#N/A', + 'gettingdata' => '#GETTING_DATA' + ); + + + /** + * Set the Compatibility Mode + * + * @access public + * @category Function Configuration + * @param string $compatibilityMode Compatibility Mode + * Permitted values are: + * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel' + * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + * @return boolean (Success or Failure) + */ + public static function setCompatibilityMode($compatibilityMode) + { + if (($compatibilityMode == self::COMPATIBILITY_EXCEL) || + ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) || + ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) { + self::$compatibilityMode = $compatibilityMode; + return true; + } + return false; + } + + + /** + * Return the current Compatibility Mode + * + * @access public + * @category Function Configuration + * @return string Compatibility Mode + * Possible Return values are: + * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel' + * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric' + * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc' + */ + public static function getCompatibilityMode() + { + return self::$compatibilityMode; + } + + + /** + * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) + * + * @access public + * @category Function Configuration + * @param string $returnDateType Return Date Format + * Permitted values are: + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P' + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O' + * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E' + * @return boolean Success or failure + */ + public static function setReturnDateType($returnDateType) + { + if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) || + ($returnDateType == self::RETURNDATE_PHP_OBJECT) || + ($returnDateType == self::RETURNDATE_EXCEL)) { + self::$returnDateType = $returnDateType; + return true; + } + return false; + } + + + /** + * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object) + * + * @access public + * @category Function Configuration + * @return string Return Date Format + * Possible Return values are: + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P' + * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O' + * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E' + */ + public static function getReturnDateType() + { + return self::$returnDateType; + } + + + /** + * DUMMY + * + * @access public + * @category Error Returns + * @return string #Not Yet Implemented + */ + public static function DUMMY() + { + return '#Not Yet Implemented'; + } + + + /** + * DIV0 + * + * @access public + * @category Error Returns + * @return string #Not Yet Implemented + */ + public static function DIV0() + { + return self::$errorCodes['divisionbyzero']; + } + + + /** + * NA + * + * Excel Function: + * =NA() + * + * Returns the error value #N/A + * #N/A is the error value that means "no value is available." + * + * @access public + * @category Logical Functions + * @return string #N/A! + */ + public static function NA() + { + return self::$errorCodes['na']; + } + + + /** + * NaN + * + * Returns the error value #NUM! + * + * @access public + * @category Error Returns + * @return string #NUM! + */ + public static function NaN() + { + return self::$errorCodes['num']; + } + + + /** + * NAME + * + * Returns the error value #NAME? + * + * @access public + * @category Error Returns + * @return string #NAME? + */ + public static function NAME() + { + return self::$errorCodes['name']; + } + + + /** + * REF + * + * Returns the error value #REF! + * + * @access public + * @category Error Returns + * @return string #REF! + */ + public static function REF() + { + return self::$errorCodes['reference']; + } + + + /** + * NULL + * + * Returns the error value #NULL! + * + * @access public + * @category Error Returns + * @return string #NULL! + */ + public static function NULL() + { + return self::$errorCodes['null']; + } + + + /** + * VALUE + * + * Returns the error value #VALUE! + * + * @access public + * @category Error Returns + * @return string #VALUE! + */ + public static function VALUE() + { + return self::$errorCodes['value']; + } + + + public static function isMatrixValue($idx) + { + return ((substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0)); + } + + + public static function isValue($idx) + { + return (substr_count($idx, '.') == 0); + } + + + public static function isCellValue($idx) + { + return (substr_count($idx, '.') > 1); + } + + + public static function ifCondition($condition) + { + $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition); + if (!isset($condition{0})) { + $condition = '=""'; + } + if (!in_array($condition{0}, array('>', '<', '='))) { + if (!is_numeric($condition)) { + $condition = PHPExcel_Calculation::wrapResult(strtoupper($condition)); + } + return '=' . $condition; + } else { + preg_match('/([<>=]+)(.*)/', $condition, $matches); + list(, $operator, $operand) = $matches; + + if (!is_numeric($operand)) { + $operand = str_replace('"', '""', $operand); + $operand = PHPExcel_Calculation::wrapResult(strtoupper($operand)); + } + + return $operator.$operand; + } + } + + /** + * ERROR_TYPE + * + * @param mixed $value Value to check + * @return boolean + */ + public static function ERROR_TYPE($value = '') + { + $value = self::flattenSingleValue($value); + + $i = 1; + foreach (self::$errorCodes as $errorCode) { + if ($value === $errorCode) { + return $i; + } + ++$i; + } + return self::NA(); + } + + + /** + * IS_BLANK + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_BLANK($value = null) + { + if (!is_null($value)) { + $value = self::flattenSingleValue($value); + } + + return is_null($value); + } + + + /** + * IS_ERR + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ERR($value = '') + { + $value = self::flattenSingleValue($value); + + return self::IS_ERROR($value) && (!self::IS_NA($value)); + } + + + /** + * IS_ERROR + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ERROR($value = '') + { + $value = self::flattenSingleValue($value); + + if (!is_string($value)) { + return false; + } + return in_array($value, array_values(self::$errorCodes)); + } + + + /** + * IS_NA + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NA($value = '') + { + $value = self::flattenSingleValue($value); + + return ($value === self::NA()); + } + + + /** + * IS_EVEN + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_EVEN($value = null) + { + $value = self::flattenSingleValue($value); + + if ($value === null) { + return self::NAME(); + } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { + return self::VALUE(); + } + + return ($value % 2 == 0); + } + + + /** + * IS_ODD + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_ODD($value = null) + { + $value = self::flattenSingleValue($value); + + if ($value === null) { + return self::NAME(); + } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) { + return self::VALUE(); + } + + return (abs($value) % 2 == 1); + } + + + /** + * IS_NUMBER + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NUMBER($value = null) + { + $value = self::flattenSingleValue($value); + + if (is_string($value)) { + return false; + } + return is_numeric($value); + } + + + /** + * IS_LOGICAL + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_LOGICAL($value = null) + { + $value = self::flattenSingleValue($value); + + return is_bool($value); + } + + + /** + * IS_TEXT + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_TEXT($value = null) + { + $value = self::flattenSingleValue($value); + + return (is_string($value) && !self::IS_ERROR($value)); + } + + + /** + * IS_NONTEXT + * + * @param mixed $value Value to check + * @return boolean + */ + public static function IS_NONTEXT($value = null) + { + return !self::IS_TEXT($value); + } + + + /** + * VERSION + * + * @return string Version information + */ + public static function VERSION() + { + return 'PHPExcel ##VERSION##, ##DATE##'; + } + + + /** + * N + * + * Returns a value converted to a number + * + * @param value The value you want converted + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number That number + * A date The serial number of that date + * TRUE 1 + * FALSE 0 + * An error value The error value + * Anything else 0 + */ + public static function N($value = null) + { + while (is_array($value)) { + $value = array_shift($value); + } + + switch (gettype($value)) { + case 'double': + case 'float': + case 'integer': + return $value; + case 'boolean': + return (integer) $value; + case 'string': + // Errors + if ((strlen($value) > 0) && ($value{0} == '#')) { + return $value; + } + break; + } + return 0; + } + + + /** + * TYPE + * + * Returns a number that identifies the type of a value + * + * @param value The value you want tested + * @return number N converts values listed in the following table + * If value is or refers to N returns + * A number 1 + * Text 2 + * Logical Value 4 + * An error value 16 + * Array or Matrix 64 + */ + public static function TYPE($value = null) + { + $value = self::flattenArrayIndexed($value); + if (is_array($value) && (count($value) > 1)) { + end($value); + $a = key($value); + // Range of cells is an error + if (self::isCellValue($a)) { + return 16; + // Test for Matrix + } elseif (self::isMatrixValue($a)) { + return 64; + } + } elseif (empty($value)) { + // Empty Cell + return 1; + } + $value = self::flattenSingleValue($value); + + if (($value === null) || (is_float($value)) || (is_int($value))) { + return 1; + } elseif (is_bool($value)) { + return 4; + } elseif (is_array($value)) { + return 64; + } elseif (is_string($value)) { + // Errors + if ((strlen($value) > 0) && ($value{0} == '#')) { + return 16; + } + return 2; + } + return 0; + } + + + /** + * Convert a multi-dimensional array to a simple 1-dimensional array + * + * @param array $array Array to be flattened + * @return array Flattened array + */ + public static function flattenArray($array) + { + if (!is_array($array)) { + return (array) $array; + } + + $arrayValues = array(); + foreach ($array as $value) { + if (is_array($value)) { + foreach ($value as $val) { + if (is_array($val)) { + foreach ($val as $v) { + $arrayValues[] = $v; + } + } else { + $arrayValues[] = $val; + } + } + } else { + $arrayValues[] = $value; + } + } + + return $arrayValues; + } + + + /** + * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing + * + * @param array $array Array to be flattened + * @return array Flattened array + */ + public static function flattenArrayIndexed($array) + { + if (!is_array($array)) { + return (array) $array; + } + + $arrayValues = array(); + foreach ($array as $k1 => $value) { + if (is_array($value)) { + foreach ($value as $k2 => $val) { + if (is_array($val)) { + foreach ($val as $k3 => $v) { + $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v; + } + } else { + $arrayValues[$k1.'.'.$k2] = $val; + } + } + } else { + $arrayValues[$k1] = $value; + } + } + + return $arrayValues; + } + + + /** + * Convert an array to a single scalar value by extracting the first element + * + * @param mixed $value Array or scalar value + * @return mixed + */ + public static function flattenSingleValue($value = '') + { + while (is_array($value)) { + $value = array_pop($value); + } + + return $value; + } +} + + +// +// There are a few mathematical functions that aren't available on all versions of PHP for all platforms +// These functions aren't available in Windows implementations of PHP prior to version 5.3.0 +// So we test if they do exist for this version of PHP/operating platform; and if not we create them +// +if (!function_exists('acosh')) { + function acosh($x) + { + return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2)); + } // function acosh() +} + +if (!function_exists('asinh')) { + function asinh($x) + { + return log($x + sqrt(1 + $x * $x)); + } // function asinh() +} + +if (!function_exists('atanh')) { + function atanh($x) + { + return (log(1 + $x) - log(1 - $x)) / 2; + } // function atanh() +} + + +// +// Strangely, PHP doesn't have a mb_str_replace multibyte function +// As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set +// +if ((!function_exists('mb_str_replace')) && + (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) { + function mb_str_replace($search, $replace, $subject) + { + if (is_array($subject)) { + $ret = array(); + foreach ($subject as $key => $val) { + $ret[$key] = mb_str_replace($search, $replace, $val); + } + return $ret; + } + + foreach ((array) $search as $key => $s) { + if ($s == '' && $s !== 0) { + continue; + } + $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : ''); + $pos = mb_strpos($subject, $s, 0, 'UTF-8'); + while ($pos !== false) { + $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8'); + $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8'); + } + } + return $subject; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Logical.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Logical.php new file mode 100644 index 00000000..dd65f010 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Logical.php @@ -0,0 +1,285 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_Logical + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Logical +{ + /** + * TRUE + * + * Returns the boolean TRUE. + * + * Excel Function: + * =TRUE() + * + * @access public + * @category Logical Functions + * @return boolean True + */ + public static function TRUE() + { + return true; + } + + + /** + * FALSE + * + * Returns the boolean FALSE. + * + * Excel Function: + * =FALSE() + * + * @access public + * @category Logical Functions + * @return boolean False + */ + public static function FALSE() + { + return false; + } + + + /** + * LOGICAL_AND + * + * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE. + * + * Excel Function: + * =AND(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds + * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @access public + * @category Logical Functions + * @param mixed $arg,... Data values + * @return boolean The logical AND of the arguments. + */ + public static function LOGICAL_AND() + { + // Return value + $returnValue = true; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $argCount = -1; + foreach ($aArgs as $argCount => $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $returnValue = $returnValue && $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue = $returnValue && ($arg != 0); + } elseif (is_string($arg)) { + $arg = strtoupper($arg); + if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) { + $arg = true; + } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) { + $arg = false; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $returnValue = $returnValue && ($arg != 0); + } + } + + // Return + if ($argCount < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + return $returnValue; + } + + + /** + * LOGICAL_OR + * + * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE. + * + * Excel Function: + * =OR(logical1[,logical2[, ...]]) + * + * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays + * or references that contain logical values. + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds + * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @access public + * @category Logical Functions + * @param mixed $arg,... Data values + * @return boolean The logical OR of the arguments. + */ + public static function LOGICAL_OR() + { + // Return value + $returnValue = false; + + // Loop through the arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $argCount = -1; + foreach ($aArgs as $argCount => $arg) { + // Is it a boolean value? + if (is_bool($arg)) { + $returnValue = $returnValue || $arg; + } elseif ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue = $returnValue || ($arg != 0); + } elseif (is_string($arg)) { + $arg = strtoupper($arg); + if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) { + $arg = true; + } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) { + $arg = false; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $returnValue = $returnValue || ($arg != 0); + } + } + + // Return + if ($argCount < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + return $returnValue; + } + + + /** + * NOT + * + * Returns the boolean inverse of the argument. + * + * Excel Function: + * =NOT(logical) + * + * The argument must evaluate to a logical value such as TRUE or FALSE + * + * Boolean arguments are treated as True or False as appropriate + * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False + * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds + * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value + * + * @access public + * @category Logical Functions + * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE + * @return boolean The boolean inverse of the argument. + */ + public static function NOT($logical = false) + { + $logical = PHPExcel_Calculation_Functions::flattenSingleValue($logical); + if (is_string($logical)) { + $logical = strtoupper($logical); + if (($logical == 'TRUE') || ($logical == PHPExcel_Calculation::getTRUE())) { + return false; + } elseif (($logical == 'FALSE') || ($logical == PHPExcel_Calculation::getFALSE())) { + return true; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + return !$logical; + } + + /** + * STATEMENT_IF + * + * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE. + * + * Excel Function: + * =IF(condition[,returnIfTrue[,returnIfFalse]]) + * + * Condition is any value or expression that can be evaluated to TRUE or FALSE. + * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100, + * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE. + * This argument can use any comparison calculation operator. + * ReturnIfTrue is the value that is returned if condition evaluates to TRUE. + * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE, + * then the IF function returns the text "Within budget" + * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use + * the logical value TRUE for this argument. + * ReturnIfTrue can be another formula. + * ReturnIfFalse is the value that is returned if condition evaluates to FALSE. + * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE, + * then the IF function returns the text "Over budget". + * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned. + * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned. + * ReturnIfFalse can be another formula. + * + * @access public + * @category Logical Functions + * @param mixed $condition Condition to evaluate + * @param mixed $returnIfTrue Value to return when condition is true + * @param mixed $returnIfFalse Optional value to return when condition is false + * @return mixed The value of returnIfTrue or returnIfFalse determined by condition + */ + public static function STATEMENT_IF($condition = true, $returnIfTrue = 0, $returnIfFalse = false) + { + $condition = (is_null($condition)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition); + $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue); + $returnIfFalse = (is_null($returnIfFalse)) ? false : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse); + + return ($condition) ? $returnIfTrue : $returnIfFalse; + } + + + /** + * IFERROR + * + * Excel Function: + * =IFERROR(testValue,errorpart) + * + * @access public + * @category Logical Functions + * @param mixed $testValue Value to check, is also the value returned when no error + * @param mixed $errorpart Value to return when testValue is an error condition + * @return mixed The value of errorpart or testValue determined by error condition + */ + public static function IFERROR($testValue = '', $errorpart = '') + { + $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue); + $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart); + + return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/LookupRef.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/LookupRef.php new file mode 100644 index 00000000..1fe77902 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/LookupRef.php @@ -0,0 +1,879 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_LookupRef + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_LookupRef +{ + /** + * CELL_ADDRESS + * + * Creates a cell address as text, given specified row and column numbers. + * + * Excel Function: + * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText]) + * + * @param row Row number to use in the cell reference + * @param column Column number to use in the cell reference + * @param relativity Flag indicating the type of reference to return + * 1 or omitted Absolute + * 2 Absolute row; relative column + * 3 Relative row; absolute column + * 4 Relative + * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style. + * TRUE or omitted CELL_ADDRESS returns an A1-style reference + * FALSE CELL_ADDRESS returns an R1C1-style reference + * @param sheetText Optional Name of worksheet to use + * @return string + */ + public static function CELL_ADDRESS($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '') + { + $row = PHPExcel_Calculation_Functions::flattenSingleValue($row); + $column = PHPExcel_Calculation_Functions::flattenSingleValue($column); + $relativity = PHPExcel_Calculation_Functions::flattenSingleValue($relativity); + $sheetText = PHPExcel_Calculation_Functions::flattenSingleValue($sheetText); + + if (($row < 1) || ($column < 1)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if ($sheetText > '') { + if (strpos($sheetText, ' ') !== false) { + $sheetText = "'".$sheetText."'"; + } + $sheetText .='!'; + } + if ((!is_bool($referenceStyle)) || $referenceStyle) { + $rowRelative = $columnRelative = '$'; + $column = PHPExcel_Cell::stringFromColumnIndex($column-1); + if (($relativity == 2) || ($relativity == 4)) { + $columnRelative = ''; + } + if (($relativity == 3) || ($relativity == 4)) { + $rowRelative = ''; + } + return $sheetText.$columnRelative.$column.$rowRelative.$row; + } else { + if (($relativity == 2) || ($relativity == 4)) { + $column = '['.$column.']'; + } + if (($relativity == 3) || ($relativity == 4)) { + $row = '['.$row.']'; + } + return $sheetText.'R'.$row.'C'.$column; + } + } + + + /** + * COLUMN + * + * Returns the column number of the given cell reference + * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array. + * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the + * reference of the cell in which the COLUMN function appears; otherwise this function returns 0. + * + * Excel Function: + * =COLUMN([cellAddress]) + * + * @param cellAddress A reference to a range of cells for which you want the column numbers + * @return integer or array of integer + */ + public static function COLUMN($cellAddress = null) + { + if (is_null($cellAddress) || trim($cellAddress) === '') { + return 0; + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $columnKey => $value) { + $columnKey = preg_replace('/[^a-z]/i', '', $columnKey); + return (integer) PHPExcel_Cell::columnIndexFromString($columnKey); + } + } else { + if (strpos($cellAddress, '!') !== false) { + list($sheet, $cellAddress) = explode('!', $cellAddress); + } + if (strpos($cellAddress, ':') !== false) { + list($startAddress, $endAddress) = explode(':', $cellAddress); + $startAddress = preg_replace('/[^a-z]/i', '', $startAddress); + $endAddress = preg_replace('/[^a-z]/i', '', $endAddress); + $returnValue = array(); + do { + $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress); + } while ($startAddress++ != $endAddress); + return $returnValue; + } else { + $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress); + return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress); + } + } + } + + + /** + * COLUMNS + * + * Returns the number of columns in an array or reference. + * + * Excel Function: + * =COLUMNS(cellAddress) + * + * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns + * @return integer The number of columns in cellAddress + */ + public static function COLUMNS($cellAddress = null) + { + if (is_null($cellAddress) || $cellAddress === '') { + return 1; + } elseif (!is_array($cellAddress)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $rows; + } else { + return $columns; + } + } + + + /** + * ROW + * + * Returns the row number of the given cell reference + * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array. + * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the + * reference of the cell in which the ROW function appears; otherwise this function returns 0. + * + * Excel Function: + * =ROW([cellAddress]) + * + * @param cellAddress A reference to a range of cells for which you want the row numbers + * @return integer or array of integer + */ + public static function ROW($cellAddress = null) + { + if (is_null($cellAddress) || trim($cellAddress) === '') { + return 0; + } + + if (is_array($cellAddress)) { + foreach ($cellAddress as $columnKey => $rowValue) { + foreach ($rowValue as $rowKey => $cellValue) { + return (integer) preg_replace('/[^0-9]/i', '', $rowKey); + } + } + } else { + if (strpos($cellAddress, '!') !== false) { + list($sheet, $cellAddress) = explode('!', $cellAddress); + } + if (strpos($cellAddress, ':') !== false) { + list($startAddress, $endAddress) = explode(':', $cellAddress); + $startAddress = preg_replace('/[^0-9]/', '', $startAddress); + $endAddress = preg_replace('/[^0-9]/', '', $endAddress); + $returnValue = array(); + do { + $returnValue[][] = (integer) $startAddress; + } while ($startAddress++ != $endAddress); + return $returnValue; + } else { + list($cellAddress) = explode(':', $cellAddress); + return (integer) preg_replace('/[^0-9]/', '', $cellAddress); + } + } + } + + + /** + * ROWS + * + * Returns the number of rows in an array or reference. + * + * Excel Function: + * =ROWS(cellAddress) + * + * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows + * @return integer The number of rows in cellAddress + */ + public static function ROWS($cellAddress = null) + { + if (is_null($cellAddress) || $cellAddress === '') { + return 1; + } elseif (!is_array($cellAddress)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + reset($cellAddress); + $isMatrix = (is_numeric(key($cellAddress))); + list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress); + + if ($isMatrix) { + return $columns; + } else { + return $rows; + } + } + + + /** + * HYPERLINK + * + * Excel Function: + * =HYPERLINK(linkURL,displayName) + * + * @access public + * @category Logical Functions + * @param string $linkURL Value to check, is also the value returned when no error + * @param string $displayName Value to return when testValue is an error condition + * @param PHPExcel_Cell $pCell The cell to set the hyperlink in + * @return mixed The value of $displayName (or $linkURL if $displayName was blank) + */ + public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null) + { + $args = func_get_args(); + $pCell = array_pop($args); + + $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL); + $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName); + + if ((!is_object($pCell)) || (trim($linkURL) == '')) { + return PHPExcel_Calculation_Functions::REF(); + } + + if ((is_object($displayName)) || trim($displayName) == '') { + $displayName = $linkURL; + } + + $pCell->getHyperlink()->setUrl($linkURL); + $pCell->getHyperlink()->setTooltip($displayName); + + return $displayName; + } + + + /** + * INDIRECT + * + * Returns the reference specified by a text string. + * References are immediately evaluated to display their contents. + * + * Excel Function: + * =INDIRECT(cellAddress) + * + * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010 + * + * @param cellAddress $cellAddress The cell address of the current cell (containing this formula) + * @param PHPExcel_Cell $pCell The current cell (containing this formula) + * @return mixed The cells referenced by cellAddress + * + * @todo Support for the optional a1 parameter introduced in Excel 2010 + * + */ + public static function INDIRECT($cellAddress = null, PHPExcel_Cell $pCell = null) + { + $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress); + if (is_null($cellAddress) || $cellAddress === '') { + return PHPExcel_Calculation_Functions::REF(); + } + + $cellAddress1 = $cellAddress; + $cellAddress2 = null; + if (strpos($cellAddress, ':') !== false) { + list($cellAddress1, $cellAddress2) = explode(':', $cellAddress); + } + + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) || + ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) { + if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) { + return PHPExcel_Calculation_Functions::REF(); + } + + if (strpos($cellAddress, '!') !== false) { + list($sheetName, $cellAddress) = explode('!', $cellAddress); + $sheetName = trim($sheetName, "'"); + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false); + } + + if (strpos($cellAddress, '!') !== false) { + list($sheetName, $cellAddress) = explode('!', $cellAddress); + $sheetName = trim($sheetName, "'"); + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + } + + + /** + * OFFSET + * + * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells. + * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and + * the number of columns to be returned. + * + * Excel Function: + * =OFFSET(cellAddress, rows, cols, [height], [width]) + * + * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or + * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value. + * @param rows The number of rows, up or down, that you want the upper-left cell to refer to. + * Using 5 as the rows argument specifies that the upper-left cell in the reference is + * five rows below reference. Rows can be positive (which means below the starting reference) + * or negative (which means above the starting reference). + * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result + * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the + * reference is five columns to the right of reference. Cols can be positive (which means + * to the right of the starting reference) or negative (which means to the left of the + * starting reference). + * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number. + * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number. + * @return string A reference to a cell or range of cells + */ + public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null) + { + $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows); + $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns); + $height = PHPExcel_Calculation_Functions::flattenSingleValue($height); + $width = PHPExcel_Calculation_Functions::flattenSingleValue($width); + if ($cellAddress == null) { + return 0; + } + + $args = func_get_args(); + $pCell = array_pop($args); + if (!is_object($pCell)) { + return PHPExcel_Calculation_Functions::REF(); + } + + $sheetName = null; + if (strpos($cellAddress, "!")) { + list($sheetName, $cellAddress) = explode("!", $cellAddress); + $sheetName = trim($sheetName, "'"); + } + if (strpos($cellAddress, ":")) { + list($startCell, $endCell) = explode(":", $cellAddress); + } else { + $startCell = $endCell = $cellAddress; + } + list($startCellColumn, $startCellRow) = PHPExcel_Cell::coordinateFromString($startCell); + list($endCellColumn, $endCellRow) = PHPExcel_Cell::coordinateFromString($endCell); + + $startCellRow += $rows; + $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1; + $startCellColumn += $columns; + + if (($startCellRow <= 0) || ($startCellColumn < 0)) { + return PHPExcel_Calculation_Functions::REF(); + } + $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1; + if (($width != null) && (!is_object($width))) { + $endCellColumn = $startCellColumn + $width - 1; + } else { + $endCellColumn += $columns; + } + $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn); + + if (($height != null) && (!is_object($height))) { + $endCellRow = $startCellRow + $height - 1; + } else { + $endCellRow += $rows; + } + + if (($endCellRow <= 0) || ($endCellColumn < 0)) { + return PHPExcel_Calculation_Functions::REF(); + } + $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn); + + $cellAddress = $startCellColumn.$startCellRow; + if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) { + $cellAddress .= ':'.$endCellColumn.$endCellRow; + } + + if ($sheetName !== null) { + $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName); + } else { + $pSheet = $pCell->getWorksheet(); + } + + return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false); + } + + + /** + * CHOOSE + * + * Uses lookup_value to return a value from the list of value arguments. + * Use CHOOSE to select one of up to 254 values based on the lookup_value. + * + * Excel Function: + * =CHOOSE(index_num, value1, [value2], ...) + * + * @param index_num Specifies which value argument is selected. + * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number + * between 1 and 254. + * @param value1... Value1 is required, subsequent values are optional. + * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on + * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or + * text. + * @return mixed The selected value + */ + public static function CHOOSE() + { + $chooseArgs = func_get_args(); + $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs)); + $entryCount = count($chooseArgs) - 1; + + if (is_array($chosenEntry)) { + $chosenEntry = array_shift($chosenEntry); + } + if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) { + --$chosenEntry; + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + $chosenEntry = floor($chosenEntry); + if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_array($chooseArgs[$chosenEntry])) { + return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]); + } else { + return $chooseArgs[$chosenEntry]; + } + } + + + /** + * MATCH + * + * The MATCH function searches for a specified item in a range of cells + * + * Excel Function: + * =MATCH(lookup_value, lookup_array, [match_type]) + * + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered. + * @return integer The relative position of the found item + */ + public static function MATCH($lookup_value, $lookup_array, $match_type = 1) + { + $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array); + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type); + // MATCH is not case sensitive + $lookup_value = strtolower($lookup_value); + + // lookup_value type has to be number, text, or logical values + if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) { + return PHPExcel_Calculation_Functions::NA(); + } + + // match_type is 0, 1 or -1 + if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) { + return PHPExcel_Calculation_Functions::NA(); + } + + // lookup_array should not be empty + $lookupArraySize = count($lookup_array); + if ($lookupArraySize <= 0) { + return PHPExcel_Calculation_Functions::NA(); + } + + // lookup_array should contain only number, text, or logical values, or empty (null) cells + foreach ($lookup_array as $i => $lookupArrayValue) { + // check the type of the value + if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) && + (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) { + return PHPExcel_Calculation_Functions::NA(); + } + // convert strings to lowercase for case-insensitive testing + if (is_string($lookupArrayValue)) { + $lookup_array[$i] = strtolower($lookupArrayValue); + } + if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) { + $lookup_array = array_slice($lookup_array, 0, $i-1); + } + } + + // if match_type is 1 or -1, the list has to be ordered + if ($match_type == 1) { + asort($lookup_array); + $keySet = array_keys($lookup_array); + } elseif ($match_type == -1) { + arsort($lookup_array); + $keySet = array_keys($lookup_array); + } + + // ** + // find the match + // ** + foreach ($lookup_array as $i => $lookupArrayValue) { + if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) { + // exact match + return ++$i; + } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) { + $i = array_search($i, $keySet); + // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value + if ($i < 1) { + // 1st cell was already smaller than the lookup_value + break; + } else { + // the previous cell was the match + return $keySet[$i-1]+1; + } + } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) { + $i = array_search($i, $keySet); + // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value + if ($i < 1) { + // 1st cell was already bigger than the lookup_value + break; + } else { + // the previous cell was the match + return $keySet[$i-1]+1; + } + } + } + + // unsuccessful in finding a match, return #N/A error value + return PHPExcel_Calculation_Functions::NA(); + } + + + /** + * INDEX + * + * Uses an index to choose a value from a reference or array + * + * Excel Function: + * =INDEX(range_array, row_num, [column_num]) + * + * @param range_array A range of cells or an array constant + * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required. + * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required. + * @return mixed the value of a specified cell or array of cells + */ + public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0) + { + if (($rowNum < 0) || ($columnNum < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (!is_array($arrayValues)) { + return PHPExcel_Calculation_Functions::REF(); + } + + $rowKeys = array_keys($arrayValues); + $columnKeys = @array_keys($arrayValues[$rowKeys[0]]); + + if ($columnNum > count($columnKeys)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($columnNum == 0) { + if ($rowNum == 0) { + return $arrayValues; + } + $rowNum = $rowKeys[--$rowNum]; + $returnArray = array(); + foreach ($arrayValues as $arrayColumn) { + if (is_array($arrayColumn)) { + if (isset($arrayColumn[$rowNum])) { + $returnArray[] = $arrayColumn[$rowNum]; + } else { + return $arrayValues[$rowNum]; + } + } else { + return $arrayValues[$rowNum]; + } + } + return $returnArray; + } + $columnNum = $columnKeys[--$columnNum]; + if ($rowNum > count($rowKeys)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($rowNum == 0) { + return $arrayValues[$columnNum]; + } + $rowNum = $rowKeys[--$rowNum]; + + return $arrayValues[$rowNum][$columnNum]; + } + + + /** + * TRANSPOSE + * + * @param array $matrixData A matrix of values + * @return array + * + * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix. + */ + public static function TRANSPOSE($matrixData) + { + $returnMatrix = array(); + if (!is_array($matrixData)) { + $matrixData = array(array($matrixData)); + } + + $column = 0; + foreach ($matrixData as $matrixRow) { + $row = 0; + foreach ($matrixRow as $matrixCell) { + $returnMatrix[$row][$column] = $matrixCell; + ++$row; + } + ++$column; + } + return $returnMatrix; + } + + + private static function vlookupSort($a, $b) + { + reset($a); + $firstColumn = key($a); + if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) { + return 0; + } + return ($aLower < $bLower) ? -1 : 1; + } + + + /** + * VLOOKUP + * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1. + * @param not_exact_match Determines if you are looking for an exact match based on lookup_value. + * @return mixed The value of the found cell + */ + public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) + { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number); + $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match); + + // index_number must be greater than or equal to 1 + if ($index_number < 1) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // index_number must be less than or equal to the number of columns in lookup_array + if ((!is_array($lookup_array)) || (empty($lookup_array))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $f = array_keys($lookup_array); + $firstRow = array_pop($f); + if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $columnKeys = array_keys($lookup_array[$firstRow]); + $returnColumn = $columnKeys[--$index_number]; + $firstColumn = array_shift($columnKeys); + } + } + + if (!$not_exact_match) { + uasort($lookup_array, array('self', 'vlookupSort')); + } + + $rowNumber = $rowValue = false; + foreach ($lookup_array as $rowKey => $rowData) { + if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) || + (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) { + break; + } + $rowNumber = $rowKey; + $rowValue = $rowData[$firstColumn]; + } + + if ($rowNumber !== false) { + if ((!$not_exact_match) && ($rowValue != $lookup_value)) { + // if an exact match is required, we have what we need to return an appropriate response + return PHPExcel_Calculation_Functions::NA(); + } else { + // otherwise return the appropriate value + return $lookup_array[$rowNumber][$returnColumn]; + } + } + + return PHPExcel_Calculation_Functions::NA(); + } + + + /** + * HLOOKUP + * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_array The range of cells being searched + * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1. + * @param not_exact_match Determines if you are looking for an exact match based on lookup_value. + * @return mixed The value of the found cell + */ + public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true) + { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number); + $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match); + + // index_number must be greater than or equal to 1 + if ($index_number < 1) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + // index_number must be less than or equal to the number of columns in lookup_array + if ((!is_array($lookup_array)) || (empty($lookup_array))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $f = array_keys($lookup_array); + $firstRow = array_pop($f); + if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) { + return PHPExcel_Calculation_Functions::REF(); + } else { + $columnKeys = array_keys($lookup_array[$firstRow]); + $firstkey = $f[0] - 1; + $returnColumn = $firstkey + $index_number; + $firstColumn = array_shift($f); + } + } + + if (!$not_exact_match) { + $firstRowH = asort($lookup_array[$firstColumn]); + } + + $rowNumber = $rowValue = false; + foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) { + if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) || + (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) { + break; + } + $rowNumber = $rowKey; + $rowValue = $rowData; + } + + if ($rowNumber !== false) { + if ((!$not_exact_match) && ($rowValue != $lookup_value)) { + // if an exact match is required, we have what we need to return an appropriate response + return PHPExcel_Calculation_Functions::NA(); + } else { + // otherwise return the appropriate value + return $lookup_array[$returnColumn][$rowNumber]; + } + } + + return PHPExcel_Calculation_Functions::NA(); + } + + + /** + * LOOKUP + * The LOOKUP function searches for value either from a one-row or one-column range or from an array. + * @param lookup_value The value that you want to match in lookup_array + * @param lookup_vector The range of cells being searched + * @param result_vector The column from which the matching value must be returned + * @return mixed The value of the found cell + */ + public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null) + { + $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value); + + if (!is_array($lookup_vector)) { + return PHPExcel_Calculation_Functions::NA(); + } + $lookupRows = count($lookup_vector); + $l = array_keys($lookup_vector); + $l = array_shift($l); + $lookupColumns = count($lookup_vector[$l]); + if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) { + $lookup_vector = self::TRANSPOSE($lookup_vector); + $lookupRows = count($lookup_vector); + $l = array_keys($lookup_vector); + $lookupColumns = count($lookup_vector[array_shift($l)]); + } + + if (is_null($result_vector)) { + $result_vector = $lookup_vector; + } + $resultRows = count($result_vector); + $l = array_keys($result_vector); + $l = array_shift($l); + $resultColumns = count($result_vector[$l]); + if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) { + $result_vector = self::TRANSPOSE($result_vector); + $resultRows = count($result_vector); + $r = array_keys($result_vector); + $resultColumns = count($result_vector[array_shift($r)]); + } + + if ($lookupRows == 2) { + $result_vector = array_pop($lookup_vector); + $lookup_vector = array_shift($lookup_vector); + } + if ($lookupColumns != 2) { + foreach ($lookup_vector as &$value) { + if (is_array($value)) { + $k = array_keys($value); + $key1 = $key2 = array_shift($k); + $key2++; + $dataValue1 = $value[$key1]; + } else { + $key1 = 0; + $key2 = 1; + $dataValue1 = $value; + } + $dataValue2 = array_shift($result_vector); + if (is_array($dataValue2)) { + $dataValue2 = array_shift($dataValue2); + } + $value = array($key1 => $dataValue1, $key2 => $dataValue2); + } + unset($value); + } + + return self::VLOOKUP($lookup_value, $lookup_vector, 2); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/MathTrig.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/MathTrig.php new file mode 100644 index 00000000..894ba9cf --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/MathTrig.php @@ -0,0 +1,1459 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_MathTrig + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_MathTrig +{ + // + // Private method to return an array of the factors of the input value + // + private static function factors($value) + { + $startVal = floor(sqrt($value)); + + $factorArray = array(); + for ($i = $startVal; $i > 1; --$i) { + if (($value % $i) == 0) { + $factorArray = array_merge($factorArray, self::factors($value / $i)); + $factorArray = array_merge($factorArray, self::factors($i)); + if ($i <= sqrt($value)) { + break; + } + } + } + if (!empty($factorArray)) { + rsort($factorArray); + return $factorArray; + } else { + return array((integer) $value); + } + } + + + private static function romanCut($num, $n) + { + return ($num - ($num % $n ) ) / $n; + } + + + /** + * ATAN2 + * + * This function calculates the arc tangent of the two variables x and y. It is similar to + * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used + * to determine the quadrant of the result. + * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a + * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between + * -pi and pi, excluding -pi. + * + * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard + * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function. + * + * Excel Function: + * ATAN2(xCoordinate,yCoordinate) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $xCoordinate The x-coordinate of the point. + * @param float $yCoordinate The y-coordinate of the point. + * @return float The inverse tangent of the specified x- and y-coordinates. + */ + public static function ATAN2($xCoordinate = null, $yCoordinate = null) + { + $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate); + $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate); + + $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0; + $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0; + + if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) && + ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) { + $xCoordinate = (float) $xCoordinate; + $yCoordinate = (float) $yCoordinate; + + if (($xCoordinate == 0) && ($yCoordinate == 0)) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + return atan2($yCoordinate, $xCoordinate); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * CEILING + * + * Returns number rounded up, away from zero, to the nearest multiple of significance. + * For example, if you want to avoid using pennies in your prices and your product is + * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the + * nearest nickel. + * + * Excel Function: + * CEILING(number[,significance]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number The number you want to round. + * @param float $significance The multiple to which you want to round. + * @return float Rounded Number + */ + public static function CEILING($number, $significance = null) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + if ((is_null($significance)) && + (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) { + $significance = $number / abs($number); + } + + if ((is_numeric($number)) && (is_numeric($significance))) { + if (($number == 0.0 ) || ($significance == 0.0)) { + return 0.0; + } elseif (self::SIGN($number) == self::SIGN($significance)) { + return ceil($number / $significance) * $significance; + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * COMBIN + * + * Returns the number of combinations for a given number of items. Use COMBIN to + * determine the total possible number of groups for a given number of items. + * + * Excel Function: + * COMBIN(numObjs,numInSet) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param int $numObjs Number of different objects + * @param int $numInSet Number of objects in each combination + * @return int Number of combinations + */ + public static function COMBIN($numObjs, $numInSet) + { + $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs); + $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet); + + if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { + if ($numObjs < $numInSet) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif ($numInSet < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * EVEN + * + * Returns number rounded up to the nearest even integer. + * You can use this function for processing items that come in twos. For example, + * a packing crate accepts rows of one or two items. The crate is full when + * the number of items, rounded up to the nearest two, matches the crate's + * capacity. + * + * Excel Function: + * EVEN(number) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to round + * @return int Rounded Number + */ + public static function EVEN($number) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 0; + } elseif (is_bool($number)) { + $number = (int) $number; + } + + if (is_numeric($number)) { + $significance = 2 * self::SIGN($number); + return (int) self::CEILING($number, $significance); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FACT + * + * Returns the factorial of a number. + * The factorial of a number is equal to 1*2*3*...* number. + * + * Excel Function: + * FACT(factVal) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $factVal Factorial Value + * @return int Factorial + */ + public static function FACT($factVal) + { + $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal); + + if (is_numeric($factVal)) { + if ($factVal < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $factLoop = floor($factVal); + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + if ($factVal > $factLoop) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + } + return $factorial ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FACTDOUBLE + * + * Returns the double factorial of a number. + * + * Excel Function: + * FACTDOUBLE(factVal) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $factVal Factorial Value + * @return int Double Factorial + */ + public static function FACTDOUBLE($factVal) + { + $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal); + + if (is_numeric($factLoop)) { + $factLoop = floor($factLoop); + if ($factVal < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $factorial = 1; + while ($factLoop > 1) { + $factorial *= $factLoop--; + --$factLoop; + } + return $factorial ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FLOOR + * + * Rounds number down, toward zero, to the nearest multiple of significance. + * + * Excel Function: + * FLOOR(number[,significance]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to round + * @param float $significance Significance + * @return float Rounded Number + */ + public static function FLOOR($number, $significance = null) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + if ((is_null($significance)) && + (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) { + $significance = $number/abs($number); + } + + if ((is_numeric($number)) && (is_numeric($significance))) { + if ($significance == 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } elseif ($number == 0.0) { + return 0.0; + } elseif (self::SIGN($number) == self::SIGN($significance)) { + return floor($number / $significance) * $significance; + } else { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * GCD + * + * Returns the greatest common divisor of a series of numbers. + * The greatest common divisor is the largest integer that divides both + * number1 and number2 without a remainder. + * + * Excel Function: + * GCD(number1[,number2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return integer Greatest Common Divisor + */ + public static function GCD() + { + $returnValue = 1; + $allValuesFactors = array(); + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) { + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ($value == 0) { + continue; + } elseif ($value < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $myFactors = self::factors($value); + $myCountedFactors = array_count_values($myFactors); + $allValuesFactors[] = $myCountedFactors; + } + $allValuesCount = count($allValuesFactors); + if ($allValuesCount == 0) { + return 0; + } + + $mergedArray = $allValuesFactors[0]; + for ($i=1; $i < $allValuesCount; ++$i) { + $mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]); + } + $mergedArrayValues = count($mergedArray); + if ($mergedArrayValues == 0) { + return $returnValue; + } elseif ($mergedArrayValues > 1) { + foreach ($mergedArray as $mergedKey => $mergedValue) { + foreach ($allValuesFactors as $highestPowerTest) { + foreach ($highestPowerTest as $testKey => $testValue) { + if (($testKey == $mergedKey) && ($testValue < $mergedValue)) { + $mergedArray[$mergedKey] = $testValue; + $mergedValue = $testValue; + } + } + } + } + + $returnValue = 1; + foreach ($mergedArray as $key => $value) { + $returnValue *= pow($key, $value); + } + return $returnValue; + } else { + $keys = array_keys($mergedArray); + $key = $keys[0]; + $value = $mergedArray[$key]; + foreach ($allValuesFactors as $testValue) { + foreach ($testValue as $mergedKey => $mergedValue) { + if (($mergedKey == $key) && ($mergedValue < $value)) { + $value = $mergedValue; + } + } + } + return pow($key, $value); + } + } + + + /** + * INT + * + * Casts a floating point value to an integer + * + * Excel Function: + * INT(number) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number Number to cast to an integer + * @return integer Integer value + */ + public static function INT($number) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 0; + } elseif (is_bool($number)) { + return (int) $number; + } + if (is_numeric($number)) { + return (int) floor($number); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * LCM + * + * Returns the lowest common multiplier of a series of numbers + * The least common multiple is the smallest positive integer that is a multiple + * of all integer arguments number1, number2, and so on. Use LCM to add fractions + * with different denominators. + * + * Excel Function: + * LCM(number1[,number2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return int Lowest Common Multiplier + */ + public static function LCM() + { + $returnValue = 1; + $allPoweredFactors = array(); + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) { + if (!is_numeric($value)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if ($value == 0) { + return 0; + } elseif ($value < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $myFactors = self::factors(floor($value)); + $myCountedFactors = array_count_values($myFactors); + $myPoweredFactors = array(); + foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) { + $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower); + } + foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) { + if (array_key_exists($myPoweredValue, $allPoweredFactors)) { + if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } else { + $allPoweredFactors[$myPoweredValue] = $myPoweredFactor; + } + } + } + foreach ($allPoweredFactors as $allPoweredFactor) { + $returnValue *= (integer) $allPoweredFactor; + } + return $returnValue; + } + + + /** + * LOG_BASE + * + * Returns the logarithm of a number to a specified base. The default base is 10. + * + * Excel Function: + * LOG(number[,base]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param float $number The positive real number for which you want the logarithm + * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10. + * @return float + */ + public static function LOG_BASE($number = null, $base = 10) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base); + + if ((!is_numeric($base)) || (!is_numeric($number))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (($base <= 0) || ($number <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return log($number, $base); + } + + + /** + * MDETERM + * + * Returns the matrix determinant of an array. + * + * Excel Function: + * MDETERM(array) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param array $matrixValues A matrix of values + * @return float + */ + public static function MDETERM($matrixValues) + { + $matrixData = array(); + if (!is_array($matrixValues)) { + $matrixValues = array(array($matrixValues)); + } + + $row = $maxColumn = 0; + foreach ($matrixValues as $matrixRow) { + if (!is_array($matrixRow)) { + $matrixRow = array($matrixRow); + } + $column = 0; + foreach ($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixData[$column][$row] = $matrixCell; + ++$column; + } + if ($column > $maxColumn) { + $maxColumn = $column; + } + ++$row; + } + if ($row != $maxColumn) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + try { + $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData); + return $matrix->det(); + } catch (PHPExcel_Exception $ex) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + + /** + * MINVERSE + * + * Returns the inverse matrix for the matrix stored in an array. + * + * Excel Function: + * MINVERSE(array) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param array $matrixValues A matrix of values + * @return array + */ + public static function MINVERSE($matrixValues) + { + $matrixData = array(); + if (!is_array($matrixValues)) { + $matrixValues = array(array($matrixValues)); + } + + $row = $maxColumn = 0; + foreach ($matrixValues as $matrixRow) { + if (!is_array($matrixRow)) { + $matrixRow = array($matrixRow); + } + $column = 0; + foreach ($matrixRow as $matrixCell) { + if ((is_string($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixData[$column][$row] = $matrixCell; + ++$column; + } + if ($column > $maxColumn) { + $maxColumn = $column; + } + ++$row; + } + if ($row != $maxColumn) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + try { + $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData); + return $matrix->inverse()->getArray(); + } catch (PHPExcel_Exception $ex) { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + + /** + * MMULT + * + * @param array $matrixData1 A matrix of values + * @param array $matrixData2 A matrix of values + * @return array + */ + public static function MMULT($matrixData1, $matrixData2) + { + $matrixAData = $matrixBData = array(); + if (!is_array($matrixData1)) { + $matrixData1 = array(array($matrixData1)); + } + if (!is_array($matrixData2)) { + $matrixData2 = array(array($matrixData2)); + } + + try { + $rowA = 0; + foreach ($matrixData1 as $matrixRow) { + if (!is_array($matrixRow)) { + $matrixRow = array($matrixRow); + } + $columnA = 0; + foreach ($matrixRow as $matrixCell) { + if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixAData[$rowA][$columnA] = $matrixCell; + ++$columnA; + } + ++$rowA; + } + $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData); + $rowB = 0; + foreach ($matrixData2 as $matrixRow) { + if (!is_array($matrixRow)) { + $matrixRow = array($matrixRow); + } + $columnB = 0; + foreach ($matrixRow as $matrixCell) { + if ((!is_numeric($matrixCell)) || ($matrixCell === null)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $matrixBData[$rowB][$columnB] = $matrixCell; + ++$columnB; + } + ++$rowB; + } + $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData); + + if ($columnA != $rowB) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + return $matrixA->times($matrixB)->getArray(); + } catch (PHPExcel_Exception $ex) { + var_dump($ex->getMessage()); + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + + /** + * MOD + * + * @param int $a Dividend + * @param int $b Divisor + * @return int Remainder + */ + public static function MOD($a = 1, $b = 1) + { + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + if ($b == 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } elseif (($a < 0.0) && ($b > 0.0)) { + return $b - fmod(abs($a), $b); + } elseif (($a > 0.0) && ($b < 0.0)) { + return $b + fmod($a, abs($b)); + } + + return fmod($a, $b); + } + + + /** + * MROUND + * + * Rounds a number to the nearest multiple of a specified value + * + * @param float $number Number to round + * @param int $multiple Multiple to which you want to round $number + * @return float Rounded Number + */ + public static function MROUND($number, $multiple) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple); + + if ((is_numeric($number)) && (is_numeric($multiple))) { + if ($multiple == 0) { + return 0; + } + if ((self::SIGN($number)) == (self::SIGN($multiple))) { + $multiplier = 1 / $multiple; + return round($number * $multiplier) / $multiplier; + } + return PHPExcel_Calculation_Functions::NaN(); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * MULTINOMIAL + * + * Returns the ratio of the factorial of a sum of values to the product of factorials. + * + * @param array of mixed Data Series + * @return float + */ + public static function MULTINOMIAL() + { + $summer = 0; + $divisor = 1; + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if (is_numeric($arg)) { + if ($arg < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + $summer += floor($arg); + $divisor *= self::FACT($arg); + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + + // Return + if ($summer > 0) { + $summer = self::FACT($summer); + return $summer / $divisor; + } + return 0; + } + + + /** + * ODD + * + * Returns number rounded up to the nearest odd integer. + * + * @param float $number Number to round + * @return int Rounded Number + */ + public static function ODD($number) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_null($number)) { + return 1; + } elseif (is_bool($number)) { + return 1; + } elseif (is_numeric($number)) { + $significance = self::SIGN($number); + if ($significance == 0) { + return 1; + } + + $result = self::CEILING($number, $significance); + if ($result == self::EVEN($result)) { + $result += $significance; + } + + return (int) $result; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * POWER + * + * Computes x raised to the power y. + * + * @param float $x + * @param float $y + * @return float + */ + public static function POWER($x = 0, $y = 2) + { + $x = PHPExcel_Calculation_Functions::flattenSingleValue($x); + $y = PHPExcel_Calculation_Functions::flattenSingleValue($y); + + // Validate parameters + if ($x == 0.0 && $y == 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif ($x == 0.0 && $y < 0.0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + // Return + $result = pow($x, $y); + return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN(); + } + + + /** + * PRODUCT + * + * PRODUCT returns the product of all the values and cells referenced in the argument list. + * + * Excel Function: + * PRODUCT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function PRODUCT() + { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue *= $arg; + } + } + } + + // Return + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } + + + /** + * QUOTIENT + * + * QUOTIENT function returns the integer portion of a division. Numerator is the divided number + * and denominator is the divisor. + * + * Excel Function: + * QUOTIENT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function QUOTIENT() + { + // Return value + $returnValue = null; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = ($arg == 0) ? 0 : $arg; + } else { + if (($returnValue == 0) || ($arg == 0)) { + $returnValue = 0; + } else { + $returnValue /= $arg; + } + } + } + } + + // Return + return intval($returnValue); + } + + + /** + * RAND + * + * @param int $min Minimal value + * @param int $max Maximal value + * @return int Random number + */ + public static function RAND($min = 0, $max = 0) + { + $min = PHPExcel_Calculation_Functions::flattenSingleValue($min); + $max = PHPExcel_Calculation_Functions::flattenSingleValue($max); + + if ($min == 0 && $max == 0) { + return (mt_rand(0, 10000000)) / 10000000; + } else { + return mt_rand($min, $max); + } + } + + + public static function ROMAN($aValue, $style = 0) + { + $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue); + $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style); + if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $aValue = (integer) $aValue; + if ($aValue == 0) { + return ''; + } + + $mill = array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM'); + $cent = array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'); + $tens = array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'); + $ones = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'); + + $roman = ''; + while ($aValue > 5999) { + $roman .= 'M'; + $aValue -= 1000; + } + $m = self::romanCut($aValue, 1000); + $aValue %= 1000; + $c = self::romanCut($aValue, 100); + $aValue %= 100; + $t = self::romanCut($aValue, 10); + $aValue %= 10; + + return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue]; + } + + + /** + * ROUNDUP + * + * Rounds a number up to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * @return float Rounded Number + */ + public static function ROUNDUP($number, $digits) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + if ((is_numeric($number)) && (is_numeric($digits))) { + $significance = pow(10, (int) $digits); + if ($number < 0.0) { + return floor($number * $significance) / $significance; + } else { + return ceil($number * $significance) / $significance; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * ROUNDDOWN + * + * Rounds a number down to a specified number of decimal places + * + * @param float $number Number to round + * @param int $digits Number of digits to which you want to round $number + * @return float Rounded Number + */ + public static function ROUNDDOWN($number, $digits) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + if ((is_numeric($number)) && (is_numeric($digits))) { + $significance = pow(10, (int) $digits); + if ($number < 0.0) { + return ceil($number * $significance) / $significance; + } else { + return floor($number * $significance) / $significance; + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SERIESSUM + * + * Returns the sum of a power series + * + * @param float $x Input value to the power series + * @param float $n Initial power to which you want to raise $x + * @param float $m Step by which to increase $n for each term in the series + * @param array of mixed Data Series + * @return float + */ + public static function SERIESSUM() + { + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $x = array_shift($aArgs); + $n = array_shift($aArgs); + $m = array_shift($aArgs); + + if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) { + // Calculate + $i = 0; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += $arg * pow($x, $n + ($m * $i++)); + } else { + return PHPExcel_Calculation_Functions::VALUE(); + } + } + return $returnValue; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SIGN + * + * Determines the sign of a number. Returns 1 if the number is positive, zero (0) + * if the number is 0, and -1 if the number is negative. + * + * @param float $number Number to round + * @return int sign value + */ + public static function SIGN($number) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_bool($number)) { + return (int) $number; + } + if (is_numeric($number)) { + if ($number == 0.0) { + return 0; + } + return $number / abs($number); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SQRTPI + * + * Returns the square root of (number * pi). + * + * @param float $number Number + * @return float Square Root of Number * Pi + */ + public static function SQRTPI($number) + { + $number = PHPExcel_Calculation_Functions::flattenSingleValue($number); + + if (is_numeric($number)) { + if ($number < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return sqrt($number * M_PI) ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SUBTOTAL + * + * Returns a subtotal in a list or database. + * + * @param int the number 1 to 11 that specifies which function to + * use in calculating subtotals within a list. + * @param array of mixed Data Series + * @return float + */ + public static function SUBTOTAL() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $subtotal = array_shift($aArgs); + + if ((is_numeric($subtotal)) && (!is_string($subtotal))) { + switch ($subtotal) { + case 1: + return PHPExcel_Calculation_Statistical::AVERAGE($aArgs); + case 2: + return PHPExcel_Calculation_Statistical::COUNT($aArgs); + case 3: + return PHPExcel_Calculation_Statistical::COUNTA($aArgs); + case 4: + return PHPExcel_Calculation_Statistical::MAX($aArgs); + case 5: + return PHPExcel_Calculation_Statistical::MIN($aArgs); + case 6: + return self::PRODUCT($aArgs); + case 7: + return PHPExcel_Calculation_Statistical::STDEV($aArgs); + case 8: + return PHPExcel_Calculation_Statistical::STDEVP($aArgs); + case 9: + return self::SUM($aArgs); + case 10: + return PHPExcel_Calculation_Statistical::VARFunc($aArgs); + case 11: + return PHPExcel_Calculation_Statistical::VARP($aArgs); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SUM + * + * SUM computes the sum of all the values and cells referenced in the argument list. + * + * Excel Function: + * SUM(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUM() + { + $returnValue = 0; + + // Loop through the arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += $arg; + } + } + + return $returnValue; + } + + + /** + * SUMIF + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * SUMIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be summed. + * @return float + */ + public static function SUMIF($aArgs, $condition, $sumArgs = array()) + { + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { + $arg = str_replace('"', '""', $arg); + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + // Is it a value within our criteria + $returnValue += $sumArgs[$key]; + } + } + + return $returnValue; + } + + + /** + * SUMIFS + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * SUMIFS(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be summed. + * @return float + */ + public static function SUMIFS() { + $arrayList = func_get_args(); + + $sumArgs = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList)); + + while (count($arrayList) > 0) { + $aArgsArray[] = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList)); + $conditions[] = PHPExcel_Calculation_Functions::ifCondition(array_shift($arrayList)); + } + + // Loop through each set of arguments and conditions + foreach ($conditions as $index => $condition) { + $aArgs = $aArgsArray[$index]; + $wildcard = false; + if ((strpos($condition, '*') !== false) || (strpos($condition, '?') !== false)) { + // * and ? are wildcard characters. + // Use ~* and ~? for literal star and question mark + // Code logic doesn't yet handle escaping + $condition = trim(ltrim($condition, '=<>'), '"'); + $wildcard = true; + } + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if ($wildcard) { + if (!fnmatch($condition, $arg, FNM_CASEFOLD)) { + // Is it a value within our criteria + $sumArgs[$key] = 0.0; + } + } else { + if (!is_numeric($arg)) { + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + $testCondition = '='.$arg.$condition; + if (!PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + // Is it a value within our criteria + $sumArgs[$key] = 0.0; + } + } + } + } + + // Return + return array_sum($sumArgs); + } + + + /** + * SUMPRODUCT + * + * Excel Function: + * SUMPRODUCT(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUMPRODUCT() + { + $arrayList = func_get_args(); + + $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList)); + $wrkCellCount = count($wrkArray); + + for ($i=0; $i< $wrkCellCount; ++$i) { + if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) { + $wrkArray[$i] = 0; + } + } + + foreach ($arrayList as $matrixData) { + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData); + $count = count($array2); + if ($wrkCellCount != $count) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + foreach ($array2 as $i => $val) { + if ((!is_numeric($val)) || (is_string($val))) { + $val = 0; + } + $wrkArray[$i] *= $val; + } + } + + return array_sum($wrkArray); + } + + + /** + * SUMSQ + * + * SUMSQ returns the sum of the squares of the arguments + * + * Excel Function: + * SUMSQ(value1[,value2[, ...]]) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function SUMSQ() + { + $returnValue = 0; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $returnValue += ($arg * $arg); + } + } + + return $returnValue; + } + + + /** + * SUMX2MY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMX2MY2($matrixData1, $matrixData2) + { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count = min(count($array1), count($array2)); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]); + } + } + + return $result; + } + + + /** + * SUMX2PY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMX2PY2($matrixData1, $matrixData2) + { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count = min(count($array1), count($array2)); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]); + } + } + + return $result; + } + + + /** + * SUMXMY2 + * + * @param mixed[] $matrixData1 Matrix #1 + * @param mixed[] $matrixData2 Matrix #2 + * @return float + */ + public static function SUMXMY2($matrixData1, $matrixData2) + { + $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2); + $count = min(count($array1), count($array2)); + + $result = 0; + for ($i = 0; $i < $count; ++$i) { + if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) && + ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) { + $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]); + } + } + + return $result; + } + + + /** + * TRUNC + * + * Truncates value to the number of fractional digits by number_digits. + * + * @param float $value + * @param int $digits + * @return float Truncated value + */ + public static function TRUNC($value = 0, $digits = 0) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits); + + // Validate parameters + if ((!is_numeric($value)) || (!is_numeric($digits))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $digits = floor($digits); + + // Truncate + $adjust = pow(10, $digits); + + if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust), '0') < $adjust/10)) { + return $value; + } + + return (intval($value * $adjust)) / $adjust; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Statistical.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Statistical.php new file mode 100644 index 00000000..1a33610f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Statistical.php @@ -0,0 +1,3745 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/trendClass.php'; + + +/** LOG_GAMMA_X_MAX_VALUE */ +define('LOG_GAMMA_X_MAX_VALUE', 2.55e305); + +/** XMININ */ +define('XMININ', 2.23e-308); + +/** EPS */ +define('EPS', 2.22e-16); + +/** SQRT2PI */ +define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099); + +/** + * PHPExcel_Calculation_Statistical + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Statistical +{ + private static function checkTrendArrays(&$array1, &$array2) + { + if (!is_array($array1)) { + $array1 = array($array1); + } + if (!is_array($array2)) { + $array2 = array($array2); + } + + $array1 = PHPExcel_Calculation_Functions::flattenArray($array1); + $array2 = PHPExcel_Calculation_Functions::flattenArray($array2); + foreach ($array1 as $key => $value) { + if ((is_bool($value)) || (is_string($value)) || (is_null($value))) { + unset($array1[$key]); + unset($array2[$key]); + } + } + foreach ($array2 as $key => $value) { + if ((is_bool($value)) || (is_string($value)) || (is_null($value))) { + unset($array1[$key]); + unset($array2[$key]); + } + } + $array1 = array_merge($array1); + $array2 = array_merge($array2); + + return true; + } + + + /** + * Beta function. + * + * @author Jaco van Kooten + * + * @param p require p>0 + * @param q require q>0 + * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + */ + private static function beta($p, $q) + { + if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) { + return 0.0; + } else { + return exp(self::logBeta($p, $q)); + } + } + + + /** + * Incomplete beta function + * + * @author Jaco van Kooten + * @author Paul Meagher + * + * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992). + * @param x require 0<=x<=1 + * @param p require p>0 + * @param q require q>0 + * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow + */ + private static function incompleteBeta($x, $p, $q) + { + if ($x <= 0.0) { + return 0.0; + } elseif ($x >= 1.0) { + return 1.0; + } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) { + return 0.0; + } + $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x)); + if ($x < ($p + 1.0) / ($p + $q + 2.0)) { + return $beta_gam * self::betaFraction($x, $p, $q) / $p; + } else { + return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q); + } + } + + + // Function cache for logBeta function + private static $logBetaCacheP = 0.0; + private static $logBetaCacheQ = 0.0; + private static $logBetaCacheResult = 0.0; + + /** + * The natural logarithm of the beta function. + * + * @param p require p>0 + * @param q require q>0 + * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow + * @author Jaco van Kooten + */ + private static function logBeta($p, $q) + { + if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) { + self::$logBetaCacheP = $p; + self::$logBetaCacheQ = $q; + if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) { + self::$logBetaCacheResult = 0.0; + } else { + self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q); + } + } + return self::$logBetaCacheResult; + } + + + /** + * Evaluates of continued fraction part of incomplete beta function. + * Based on an idea from Numerical Recipes (W.H. Press et al, 1992). + * @author Jaco van Kooten + */ + private static function betaFraction($x, $p, $q) + { + $c = 1.0; + $sum_pq = $p + $q; + $p_plus = $p + 1.0; + $p_minus = $p - 1.0; + $h = 1.0 - $sum_pq * $x / $p_plus; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $frac = $h; + $m = 1; + $delta = 0.0; + while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION) { + $m2 = 2 * $m; + // even index for d + $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < XMININ) { + $c = XMININ; + } + $frac *= $h * $c; + // odd index for d + $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2)); + $h = 1.0 + $d * $h; + if (abs($h) < XMININ) { + $h = XMININ; + } + $h = 1.0 / $h; + $c = 1.0 + $d / $c; + if (abs($c) < XMININ) { + $c = XMININ; + } + $delta = $h * $c; + $frac *= $delta; + ++$m; + } + return $frac; + } + + + /** + * logGamma function + * + * @version 1.1 + * @author Jaco van Kooten + * + * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher. + * + * The natural logarithm of the gamma function. <br /> + * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br /> + * Applied Mathematics Division <br /> + * Argonne National Laboratory <br /> + * Argonne, IL 60439 <br /> + * <p> + * References: + * <ol> + * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural + * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li> + * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li> + * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li> + * </ol> + * </p> + * <p> + * From the original documentation: + * </p> + * <p> + * This routine calculates the LOG(GAMMA) function for a positive real argument X. + * Computation is based on an algorithm outlined in references 1 and 2. + * The program uses rational functions that theoretically approximate LOG(GAMMA) + * to at least 18 significant decimal digits. The approximation for X > 12 is from + * reference 3, while approximations for X < 12.0 are similar to those in reference + * 1, but are unpublished. The accuracy achieved depends on the arithmetic system, + * the compiler, the intrinsic functions, and proper selection of the + * machine-dependent constants. + * </p> + * <p> + * Error returns: <br /> + * The program returns the value XINF for X .LE. 0.0 or when overflow would occur. + * The computation is believed to be free of underflow and overflow. + * </p> + * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305 + */ + + // Function cache for logGamma + private static $logGammaCacheResult = 0.0; + private static $logGammaCacheX = 0.0; + + private static function logGamma($x) + { + // Log Gamma related constants + static $lg_d1 = -0.5772156649015328605195174; + static $lg_d2 = 0.4227843350984671393993777; + static $lg_d4 = 1.791759469228055000094023; + + static $lg_p1 = array( + 4.945235359296727046734888, + 201.8112620856775083915565, + 2290.838373831346393026739, + 11319.67205903380828685045, + 28557.24635671635335736389, + 38484.96228443793359990269, + 26377.48787624195437963534, + 7225.813979700288197698961 + ); + static $lg_p2 = array( + 4.974607845568932035012064, + 542.4138599891070494101986, + 15506.93864978364947665077, + 184793.2904445632425417223, + 1088204.76946882876749847, + 3338152.967987029735917223, + 5106661.678927352456275255, + 3074109.054850539556250927 + ); + static $lg_p4 = array( + 14745.02166059939948905062, + 2426813.369486704502836312, + 121475557.4045093227939592, + 2663432449.630976949898078, + 29403789566.34553899906876, + 170266573776.5398868392998, + 492612579337.743088758812, + 560625185622.3951465078242 + ); + static $lg_q1 = array( + 67.48212550303777196073036, + 1113.332393857199323513008, + 7738.757056935398733233834, + 27639.87074403340708898585, + 54993.10206226157329794414, + 61611.22180066002127833352, + 36351.27591501940507276287, + 8785.536302431013170870835 + ); + static $lg_q2 = array( + 183.0328399370592604055942, + 7765.049321445005871323047, + 133190.3827966074194402448, + 1136705.821321969608938755, + 5267964.117437946917577538, + 13467014.54311101692290052, + 17827365.30353274213975932, + 9533095.591844353613395747 + ); + static $lg_q4 = array( + 2690.530175870899333379843, + 639388.5654300092398984238, + 41355999.30241388052042842, + 1120872109.61614794137657, + 14886137286.78813811542398, + 101680358627.2438228077304, + 341747634550.7377132798597, + 446315818741.9713286462081 + ); + static $lg_c = array( + -0.001910444077728, + 8.4171387781295e-4, + -5.952379913043012e-4, + 7.93650793500350248e-4, + -0.002777777777777681622553, + 0.08333333333333333331554247, + 0.0057083835261 + ); + + // Rough estimate of the fourth root of logGamma_xBig + static $lg_frtbig = 2.25e76; + static $pnt68 = 0.6796875; + + + if ($x == self::$logGammaCacheX) { + return self::$logGammaCacheResult; + } + $y = $x; + if ($y > 0.0 && $y <= LOG_GAMMA_X_MAX_VALUE) { + if ($y <= EPS) { + $res = -log(y); + } elseif ($y <= 1.5) { + // --------------------- + // EPS .LT. X .LE. 1.5 + // --------------------- + if ($y < $pnt68) { + $corr = -log($y); + $xm1 = $y; + } else { + $corr = 0.0; + $xm1 = $y - 1.0; + } + if ($y <= 0.5 || $y >= $pnt68) { + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm1 + $lg_p1[$i]; + $xden = $xden * $xm1 + $lg_q1[$i]; + } + $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden)); + } else { + $xm2 = $y - 1.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + $lg_p2[$i]; + $xden = $xden * $xm2 + $lg_q2[$i]; + } + $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); + } + } elseif ($y <= 4.0) { + // --------------------- + // 1.5 .LT. X .LE. 4.0 + // --------------------- + $xm2 = $y - 2.0; + $xden = 1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm2 + $lg_p2[$i]; + $xden = $xden * $xm2 + $lg_q2[$i]; + } + $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden)); + } elseif ($y <= 12.0) { + // ---------------------- + // 4.0 .LT. X .LE. 12.0 + // ---------------------- + $xm4 = $y - 4.0; + $xden = -1.0; + $xnum = 0.0; + for ($i = 0; $i < 8; ++$i) { + $xnum = $xnum * $xm4 + $lg_p4[$i]; + $xden = $xden * $xm4 + $lg_q4[$i]; + } + $res = $lg_d4 + $xm4 * ($xnum / $xden); + } else { + // --------------------------------- + // Evaluate for argument .GE. 12.0 + // --------------------------------- + $res = 0.0; + if ($y <= $lg_frtbig) { + $res = $lg_c[6]; + $ysq = $y * $y; + for ($i = 0; $i < 6; ++$i) { + $res = $res / $ysq + $lg_c[$i]; + } + $res /= $y; + $corr = log($y); + $res = $res + log(SQRT2PI) - 0.5 * $corr; + $res += $y * ($corr - 1.0); + } + } + } else { + // -------------------------- + // Return for bad arguments + // -------------------------- + $res = MAX_VALUE; + } + // ------------------------------ + // Final adjustments and return + // ------------------------------ + self::$logGammaCacheX = $x; + self::$logGammaCacheResult = $res; + return $res; + } + + + // + // Private implementation of the incomplete Gamma function + // + private static function incompleteGamma($a, $x) + { + static $max = 32; + $summer = 0; + for ($n=0; $n<=$max; ++$n) { + $divisor = $a; + for ($i=1; $i<=$n; ++$i) { + $divisor *= ($a + $i); + } + $summer += (pow($x, $n) / $divisor); + } + return pow($x, $a) * exp(0-$x) * $summer; + } + + + // + // Private implementation of the Gamma function + // + private static function gamma($data) + { + if ($data == 0.0) { + return 0; + } + + static $p0 = 1.000000000190015; + static $p = array( + 1 => 76.18009172947146, + 2 => -86.50532032941677, + 3 => 24.01409824083091, + 4 => -1.231739572450155, + 5 => 1.208650973866179e-3, + 6 => -5.395239384953e-6 + ); + + $y = $x = $data; + $tmp = $x + 5.5; + $tmp -= ($x + 0.5) * log($tmp); + + $summer = $p0; + for ($j=1; $j<=6; ++$j) { + $summer += ($p[$j] / ++$y); + } + return exp(0 - $tmp + log(SQRT2PI * $summer / $x)); + } + + + /*************************************************************************** + * inverse_ncdf.php + * ------------------- + * begin : Friday, January 16, 2004 + * copyright : (C) 2004 Michael Nickerson + * email : nickersonm@yahoo.com + * + ***************************************************************************/ + private static function inverseNcdf($p) + { + // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to + // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as + // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html + // I have not checked the accuracy of this implementation. Be aware that PHP + // will truncate the coeficcients to 14 digits. + + // You have permission to use and distribute this function freely for + // whatever purpose you want, but please show common courtesy and give credit + // where credit is due. + + // Input paramater is $p - probability - where 0 < p < 1. + + // Coefficients in rational approximations + static $a = array( + 1 => -3.969683028665376e+01, + 2 => 2.209460984245205e+02, + 3 => -2.759285104469687e+02, + 4 => 1.383577518672690e+02, + 5 => -3.066479806614716e+01, + 6 => 2.506628277459239e+00 + ); + + static $b = array( + 1 => -5.447609879822406e+01, + 2 => 1.615858368580409e+02, + 3 => -1.556989798598866e+02, + 4 => 6.680131188771972e+01, + 5 => -1.328068155288572e+01 + ); + + static $c = array( + 1 => -7.784894002430293e-03, + 2 => -3.223964580411365e-01, + 3 => -2.400758277161838e+00, + 4 => -2.549732539343734e+00, + 5 => 4.374664141464968e+00, + 6 => 2.938163982698783e+00 + ); + + static $d = array( + 1 => 7.784695709041462e-03, + 2 => 3.224671290700398e-01, + 3 => 2.445134137142996e+00, + 4 => 3.754408661907416e+00 + ); + + // Define lower and upper region break-points. + $p_low = 0.02425; //Use lower region approx. below this + $p_high = 1 - $p_low; //Use upper region approx. above this + + if (0 < $p && $p < $p_low) { + // Rational approximation for lower region. + $q = sqrt(-2 * log($p)); + return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } elseif ($p_low <= $p && $p <= $p_high) { + // Rational approximation for central region. + $q = $p - 0.5; + $r = $q * $q; + return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q / + ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1); + } elseif ($p_high < $p && $p < 1) { + // Rational approximation for upper region. + $q = sqrt(-2 * log(1 - $p)); + return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) / + (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1); + } + // If 0 < p < 1, return a null value + return PHPExcel_Calculation_Functions::NULL(); + } + + + private static function inverseNcdf2($prob) + { + // Approximation of inverse standard normal CDF developed by + // B. Moro, "The Full Monte," Risk 8(2), Feb 1995, 57-58. + + $a1 = 2.50662823884; + $a2 = -18.61500062529; + $a3 = 41.39119773534; + $a4 = -25.44106049637; + + $b1 = -8.4735109309; + $b2 = 23.08336743743; + $b3 = -21.06224101826; + $b4 = 3.13082909833; + + $c1 = 0.337475482272615; + $c2 = 0.976169019091719; + $c3 = 0.160797971491821; + $c4 = 2.76438810333863E-02; + $c5 = 3.8405729373609E-03; + $c6 = 3.951896511919E-04; + $c7 = 3.21767881768E-05; + $c8 = 2.888167364E-07; + $c9 = 3.960315187E-07; + + $y = $prob - 0.5; + if (abs($y) < 0.42) { + $z = ($y * $y); + $z = $y * ((($a4 * $z + $a3) * $z + $a2) * $z + $a1) / (((($b4 * $z + $b3) * $z + $b2) * $z + $b1) * $z + 1); + } else { + if ($y > 0) { + $z = log(-log(1 - $prob)); + } else { + $z = log(-log($prob)); + } + $z = $c1 + $z * ($c2 + $z * ($c3 + $z * ($c4 + $z * ($c5 + $z * ($c6 + $z * ($c7 + $z * ($c8 + $z * $c9))))))); + if ($y < 0) { + $z = -$z; + } + } + return $z; + } // function inverseNcdf2() + + + private static function inverseNcdf3($p) + { + // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3. + // Produces the normal deviate Z corresponding to a given lower + // tail area of P; Z is accurate to about 1 part in 10**16. + // + // This is a PHP version of the original FORTRAN code that can + // be found at http://lib.stat.cmu.edu/apstat/ + $split1 = 0.425; + $split2 = 5; + $const1 = 0.180625; + $const2 = 1.6; + + // coefficients for p close to 0.5 + $a0 = 3.3871328727963666080; + $a1 = 1.3314166789178437745E+2; + $a2 = 1.9715909503065514427E+3; + $a3 = 1.3731693765509461125E+4; + $a4 = 4.5921953931549871457E+4; + $a5 = 6.7265770927008700853E+4; + $a6 = 3.3430575583588128105E+4; + $a7 = 2.5090809287301226727E+3; + + $b1 = 4.2313330701600911252E+1; + $b2 = 6.8718700749205790830E+2; + $b3 = 5.3941960214247511077E+3; + $b4 = 2.1213794301586595867E+4; + $b5 = 3.9307895800092710610E+4; + $b6 = 2.8729085735721942674E+4; + $b7 = 5.2264952788528545610E+3; + + // coefficients for p not close to 0, 0.5 or 1. + $c0 = 1.42343711074968357734; + $c1 = 4.63033784615654529590; + $c2 = 5.76949722146069140550; + $c3 = 3.64784832476320460504; + $c4 = 1.27045825245236838258; + $c5 = 2.41780725177450611770E-1; + $c6 = 2.27238449892691845833E-2; + $c7 = 7.74545014278341407640E-4; + + $d1 = 2.05319162663775882187; + $d2 = 1.67638483018380384940; + $d3 = 6.89767334985100004550E-1; + $d4 = 1.48103976427480074590E-1; + $d5 = 1.51986665636164571966E-2; + $d6 = 5.47593808499534494600E-4; + $d7 = 1.05075007164441684324E-9; + + // coefficients for p near 0 or 1. + $e0 = 6.65790464350110377720; + $e1 = 5.46378491116411436990; + $e2 = 1.78482653991729133580; + $e3 = 2.96560571828504891230E-1; + $e4 = 2.65321895265761230930E-2; + $e5 = 1.24266094738807843860E-3; + $e6 = 2.71155556874348757815E-5; + $e7 = 2.01033439929228813265E-7; + + $f1 = 5.99832206555887937690E-1; + $f2 = 1.36929880922735805310E-1; + $f3 = 1.48753612908506148525E-2; + $f4 = 7.86869131145613259100E-4; + $f5 = 1.84631831751005468180E-5; + $f6 = 1.42151175831644588870E-7; + $f7 = 2.04426310338993978564E-15; + + $q = $p - 0.5; + + // computation for p close to 0.5 + if (abs($q) <= split1) { + $R = $const1 - $q * $q; + $z = $q * ((((((($a7 * $R + $a6) * $R + $a5) * $R + $a4) * $R + $a3) * $R + $a2) * $R + $a1) * $R + $a0) / + ((((((($b7 * $R + $b6) * $R + $b5) * $R + $b4) * $R + $b3) * $R + $b2) * $R + $b1) * $R + 1); + } else { + if ($q < 0) { + $R = $p; + } else { + $R = 1 - $p; + } + $R = pow(-log($R), 2); + + // computation for p not close to 0, 0.5 or 1. + if ($R <= $split2) { + $R = $R - $const2; + $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) / + ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1); + } else { + // computation for p near 0 or 1. + $R = $R - $split2; + $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) / + ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1); + } + if ($q < 0) { + $z = -$z; + } + } + return $z; + } + + + /** + * AVEDEV + * + * Returns the average of the absolute deviations of data points from their mean. + * AVEDEV is a measure of the variability in a data set. + * + * Excel Function: + * AVEDEV(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVEDEV() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if ($aMean != PHPExcel_Calculation_Functions::DIV0()) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = abs($arg - $aMean); + } else { + $returnValue += abs($arg - $aMean); + } + ++$aCount; + } + } + + // Return + if ($aCount == 0) { + return PHPExcel_Calculation_Functions::DIV0(); + } + return $returnValue / $aCount; + } + return PHPExcel_Calculation_Functions::NaN(); + } + + + /** + * AVERAGE + * + * Returns the average (arithmetic mean) of the arguments + * + * Excel Function: + * AVERAGE(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVERAGE() + { + $returnValue = $aCount = 0; + + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue += $arg; + } + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return $returnValue / $aCount; + } else { + return PHPExcel_Calculation_Functions::DIV0(); + } + } + + + /** + * AVERAGEA + * + * Returns the average of its arguments, including numbers, text, and logical values + * + * Excel Function: + * AVERAGEA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function AVERAGEA() + { + $returnValue = null; + + $aCount = 0; + // Loop through arguments + foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = $arg; + } else { + $returnValue += $arg; + } + ++$aCount; + } + } + } + + if ($aCount > 0) { + return $returnValue / $aCount; + } else { + return PHPExcel_Calculation_Functions::DIV0(); + } + } + + + /** + * AVERAGEIF + * + * Returns the average value from a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * AVERAGEIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @param mixed[] $averageArgs Data values + * @return float + */ + public static function AVERAGEIF($aArgs, $condition, $averageArgs = array()) + { + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $averageArgs = PHPExcel_Calculation_Functions::flattenArray($averageArgs); + if (empty($averageArgs)) { + $averageArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::ifCondition($condition); + // Loop through arguments + $aCount = 0; + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + return $returnValue / $aCount; + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * BETADIST + * + * Returns the beta distribution. + * + * @param float $value Value at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @param boolean $cumulative + * @return float + * + */ + public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin); + $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax); + + if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { + if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + $value -= $rMin; + $value /= ($rMax - $rMin); + return self::incompleteBeta($value, $alpha, $beta); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * BETAINV + * + * Returns the inverse of the beta distribution. + * + * @param float $probability Probability at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @param float $rMin Minimum value + * @param float $rMax Maximum value + * @param boolean $cumulative + * @return float + * + */ + public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin); + $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax); + + if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) { + if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($rMin > $rMax) { + $tmp = $rMin; + $rMin = $rMax; + $rMax = $tmp; + } + $a = 0; + $b = 2; + + $i = 0; + while ((($b - $a) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + $guess = ($a + $b) / 2; + $result = self::BETADIST($guess, $alpha, $beta); + if (($result == $probability) || ($result == 0)) { + $b = $a; + } elseif ($result > $probability) { + $b = $guess; + } else { + $a = $guess; + } + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($rMin + $guess * ($rMax - $rMin), 12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * BINOMDIST + * + * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with + * a fixed number of tests or trials, when the outcomes of any trial are only success or failure, + * when trials are independent, and when the probability of success is constant throughout the + * experiment. For example, BINOMDIST can calculate the probability that two of the next three + * babies born are male. + * + * @param float $value Number of successes in trials + * @param float $trials Number of trials + * @param float $probability Probability of success on each trial + * @param boolean $cumulative + * @return float + * + * @todo Cumulative distribution function + * + */ + public static function BINOMDIST($value, $trials, $probability, $cumulative) + { + $value = floor(PHPExcel_Calculation_Functions::flattenSingleValue($value)); + $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + + if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) { + if (($value < 0) || ($value > $trials)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + $summer = 0; + for ($i = 0; $i <= $value; ++$i) { + $summer += PHPExcel_Calculation_MathTrig::COMBIN($trials, $i) * pow($probability, $i) * pow(1 - $probability, $trials - $i); + } + return $summer; + } else { + return PHPExcel_Calculation_MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value) ; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * CHIDIST + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $value Value for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function CHIDIST($value, $degrees) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($value)) && (is_numeric($degrees))) { + if ($degrees < 1) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($value < 0) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + return 1; + } + return PHPExcel_Calculation_Functions::NaN(); + } + return 1 - (self::incompleteGamma($degrees/2, $value/2) / self::gamma($degrees/2)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * CHIINV + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $probability Probability for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function CHIINV($probability, $degrees) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($probability)) && (is_numeric($degrees))) { + $xLo = 100; + $xHi = 0; + + $x = $xNew = 1; + $dx = 1; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::CHIDIST($x, $degrees); + $error = $result - $probability; + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($x, 12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * CONFIDENCE + * + * Returns the confidence interval for a population mean + * + * @param float $alpha + * @param float $stdDev Standard Deviation + * @param float $size + * @return float + * + */ + public static function CONFIDENCE($alpha, $stdDev, $size) + { + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + $size = floor(PHPExcel_Calculation_Functions::flattenSingleValue($size)); + + if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) { + if (($alpha <= 0) || ($alpha >= 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($stdDev <= 0) || ($size < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * CORREL + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function CORREL($yValues, $xValues = null) + { + if ((is_null($xValues)) || (!is_array($yValues)) || (!is_array($xValues))) { + return PHPExcel_Calculation_Functions::VALUE(); + } + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getCorrelation(); + } + + + /** + * COUNT + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * COUNT(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNT() + { + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + ++$returnValue; + } + } + + return $returnValue; + } + + + /** + * COUNTA + * + * Counts the number of cells that are not empty within the list of arguments + * + * Excel Function: + * COUNTA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNTA() + { + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric, boolean or string value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + ++$returnValue; + } + } + + return $returnValue; + } + + + /** + * COUNTBLANK + * + * Counts the number of empty cells within the list of arguments + * + * Excel Function: + * COUNTBLANK(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return int + */ + public static function COUNTBLANK() + { + $returnValue = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a blank cell? + if ((is_null($arg)) || ((is_string($arg)) && ($arg == ''))) { + ++$returnValue; + } + } + + return $returnValue; + } + + + /** + * COUNTIF + * + * Counts the number of cells that contain numbers within the list of arguments + * + * Excel Function: + * COUNTIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be counted. + * @return int + */ + public static function COUNTIF($aArgs, $condition) + { + $returnValue = 0; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $condition = PHPExcel_Calculation_Functions::ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $arg) { + if (!is_numeric($arg)) { + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + // Is it a value within our criteria + ++$returnValue; + } + } + + return $returnValue; + } + + + /** + * COVAR + * + * Returns covariance, the average of the products of deviations for each data point pair. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function COVAR($yValues, $xValues) + { + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getCovariance(); + } + + + /** + * CRITBINOM + * + * Returns the smallest value for which the cumulative binomial distribution is greater + * than or equal to a criterion value + * + * See http://support.microsoft.com/kb/828117/ for details of the algorithm used + * + * @param float $trials number of Bernoulli trials + * @param float $probability probability of a success on each trial + * @param float $alpha criterion value + * @return int + * + * @todo Warning. This implementation differs from the algorithm detailed on the MS + * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess + * This eliminates a potential endless loop error, but may have an adverse affect on the + * accuracy of the function (although all my tests have so far returned correct results). + * + */ + public static function CRITBINOM($trials, $probability, $alpha) + { + $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + + if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) { + if ($trials < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($alpha < 0) || ($alpha > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif ($alpha <= 0.5) { + $t = sqrt(log(1 / ($alpha * $alpha))); + $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t)); + } else { + $t = sqrt(log(1 / pow(1 - $alpha, 2))); + $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t); + } + $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability))); + if ($Guess < 0) { + $Guess = 0; + } elseif ($Guess > $trials) { + $Guess = $trials; + } + + $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0; + $EssentiallyZero = 10e-12; + + $m = floor($trials * $probability); + ++$TotalUnscaledProbability; + if ($m == $Guess) { + ++$UnscaledPGuess; + } + if ($m <= $Guess) { + ++$UnscaledCumPGuess; + } + + $PreviousValue = 1; + $Done = false; + $k = $m + 1; + while ((!$Done) && ($k <= $trials)) { + $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability)); + $TotalUnscaledProbability += $CurrentValue; + if ($k == $Guess) { + $UnscaledPGuess += $CurrentValue; + } + if ($k <= $Guess) { + $UnscaledCumPGuess += $CurrentValue; + } + if ($CurrentValue <= $EssentiallyZero) { + $Done = true; + } + $PreviousValue = $CurrentValue; + ++$k; + } + + $PreviousValue = 1; + $Done = false; + $k = $m - 1; + while ((!$Done) && ($k >= 0)) { + $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability); + $TotalUnscaledProbability += $CurrentValue; + if ($k == $Guess) { + $UnscaledPGuess += $CurrentValue; + } + if ($k <= $Guess) { + $UnscaledCumPGuess += $CurrentValue; + } + if ($CurrentValue <= $EssentiallyZero) { + $Done = true; + } + $PreviousValue = $CurrentValue; + --$k; + } + + $PGuess = $UnscaledPGuess / $TotalUnscaledProbability; + $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability; + +// $CumPGuessMinus1 = $CumPGuess - $PGuess; + $CumPGuessMinus1 = $CumPGuess - 1; + + while (true) { + if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) { + return $Guess; + } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) { + $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability); + $CumPGuessMinus1 = $CumPGuess; + $CumPGuess = $CumPGuess + $PGuessPlus1; + $PGuess = $PGuessPlus1; + ++$Guess; + } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) { + $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability; + $CumPGuess = $CumPGuessMinus1; + $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess; + $PGuess = $PGuessMinus1; + --$Guess; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * DEVSQ + * + * Returns the sum of squares of deviations of data points from their sample mean. + * + * Excel Function: + * DEVSQ(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function DEVSQ() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if ($aMean != PHPExcel_Calculation_Functions::DIV0()) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + // Is it a numeric value? + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || + (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean), 2); + } else { + $returnValue += pow(($arg - $aMean), 2); + } + ++$aCount; + } + } + + // Return + if (is_null($returnValue)) { + return PHPExcel_Calculation_Functions::NaN(); + } else { + return $returnValue; + } + } + return self::NA(); + } + + + /** + * EXPONDIST + * + * Returns the exponential distribution. Use EXPONDIST to model the time between events, + * such as how long an automated bank teller takes to deliver cash. For example, you can + * use EXPONDIST to determine the probability that the process takes at most 1 minute. + * + * @param float $value Value of the function + * @param float $lambda The parameter value + * @param boolean $cumulative + * @return float + */ + public static function EXPONDIST($value, $lambda, $cumulative) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $lambda = PHPExcel_Calculation_Functions::flattenSingleValue($lambda); + $cumulative = PHPExcel_Calculation_Functions::flattenSingleValue($cumulative); + + if ((is_numeric($value)) && (is_numeric($lambda))) { + if (($value < 0) || ($lambda < 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 1 - exp(0-$value*$lambda); + } else { + return $lambda * exp(0-$value*$lambda); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FISHER + * + * Returns the Fisher transformation at x. This transformation produces a function that + * is normally distributed rather than skewed. Use this function to perform hypothesis + * testing on the correlation coefficient. + * + * @param float $value + * @return float + */ + public static function FISHER($value) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + if (($value <= -1) || ($value >= 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return 0.5 * log((1+$value)/(1-$value)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FISHERINV + * + * Returns the inverse of the Fisher transformation. Use this transformation when + * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then + * FISHERINV(y) = x. + * + * @param float $value + * @return float + */ + public static function FISHERINV($value) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + return (exp(2 * $value) - 1) / (exp(2 * $value) + 1); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FORECAST + * + * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value. + * + * @param float Value of X for which we want to find Y + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function FORECAST($xValue, $yValues, $xValues) + { + $xValue = PHPExcel_Calculation_Functions::flattenSingleValue($xValue); + if (!is_numeric($xValue)) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getValueOfYForX($xValue); + } + + + /** + * GAMMADIST + * + * Returns the gamma distribution. + * + * @param float $value Value at which you want to evaluate the distribution + * @param float $a Parameter to the distribution + * @param float $b Parameter to the distribution + * @param boolean $cumulative + * @return float + * + */ + public static function GAMMADIST($value, $a, $b, $cumulative) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $a = PHPExcel_Calculation_Functions::flattenSingleValue($a); + $b = PHPExcel_Calculation_Functions::flattenSingleValue($b); + + if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) { + if (($value < 0) || ($a <= 0) || ($b <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return self::incompleteGamma($a, $value / $b) / self::gamma($a); + } else { + return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a-1) * exp(0-($value / $b)); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * GAMMAINV + * + * Returns the inverse of the beta distribution. + * + * @param float $probability Probability at which you want to evaluate the distribution + * @param float $alpha Parameter to the distribution + * @param float $beta Parameter to the distribution + * @return float + * + */ + public static function GAMMAINV($probability, $alpha, $beta) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + + if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) { + if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $xLo = 0; + $xHi = $alpha * $beta * 5; + + $x = $xNew = 1; + $error = $pdf = 0; + $dx = 1024; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability; + if ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + $pdf = self::GAMMADIST($x, $alpha, $beta, false); + // Avoid division by zero + if ($pdf != 0.0) { + $dx = $error / $pdf; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return $x; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * GAMMALN + * + * Returns the natural logarithm of the gamma function. + * + * @param float $value + * @return float + */ + public static function GAMMALN($value) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_numeric($value)) { + if ($value <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return log(self::gamma($value)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * GEOMEAN + * + * Returns the geometric mean of an array or range of positive data. For example, you + * can use GEOMEAN to calculate average growth rate given compound interest with + * variable rates. + * + * Excel Function: + * GEOMEAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function GEOMEAN() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $aMean = PHPExcel_Calculation_MathTrig::PRODUCT($aArgs); + if (is_numeric($aMean) && ($aMean > 0)) { + $aCount = self::COUNT($aArgs) ; + if (self::MIN($aArgs) > 0) { + return pow($aMean, (1 / $aCount)); + } + } + return PHPExcel_Calculation_Functions::NaN(); + } + + + /** + * GROWTH + * + * Returns values along a predicted emponential trend + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param array of mixed Values of X for which we want to find Y + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @return array of float + */ + public static function GROWTH($yValues, $xValues = array(), $newValues = array(), $const = true) + { + $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues); + $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues); + $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues); + $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + + $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitExponential->getXValues(); + } + + $returnArray = array(); + foreach ($newValues as $xValue) { + $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue); + } + + return $returnArray; + } + + + /** + * HARMEAN + * + * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the + * arithmetic mean of reciprocals. + * + * Excel Function: + * HARMEAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function HARMEAN() + { + // Return value + $returnValue = PHPExcel_Calculation_Functions::NA(); + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + if (self::MIN($aArgs) < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + $aCount = 0; + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ($arg <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (is_null($returnValue)) { + $returnValue = (1 / $arg); + } else { + $returnValue += (1 / $arg); + } + ++$aCount; + } + } + + // Return + if ($aCount > 0) { + return 1 / ($returnValue / $aCount); + } else { + return $returnValue; + } + } + + + /** + * HYPGEOMDIST + * + * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of + * sample successes, given the sample size, population successes, and population size. + * + * @param float $sampleSuccesses Number of successes in the sample + * @param float $sampleNumber Size of the sample + * @param float $populationSuccesses Number of successes in the population + * @param float $populationNumber Population size + * @return float + * + */ + public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber) + { + $sampleSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleSuccesses)); + $sampleNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleNumber)); + $populationSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationSuccesses)); + $populationNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationNumber)); + + if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) { + if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return PHPExcel_Calculation_MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) * + PHPExcel_Calculation_MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) / + PHPExcel_Calculation_MathTrig::COMBIN($populationNumber, $sampleNumber); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * INTERCEPT + * + * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function INTERCEPT($yValues, $xValues) + { + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getIntersect(); + } + + + /** + * KURT + * + * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness + * or flatness of a distribution compared with the normal distribution. Positive + * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a + * relatively flat distribution. + * + * @param array Data Series + * @return float + */ + public static function KURT() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $mean = self::AVERAGE($aArgs); + $stdDev = self::STDEV($aArgs); + + if ($stdDev > 0) { + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += pow((($arg - $mean) / $stdDev), 4); + ++$count; + } + } + } + + // Return + if ($count > 3) { + return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1, 2) / (($count-2) * ($count-3))); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * LARGE + * + * Returns the nth largest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * LARGE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Position (ordered from the largest) in the array or range of data to return + * @return float + * + */ + public static function LARGE() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = floor(array_pop($aArgs)); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $count = self::COUNT($mArgs); + $entry = floor(--$entry); + if (($entry < 0) || ($entry >= $count) || ($count == 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + rsort($mArgs); + return $mArgs[$entry]; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * LINEST + * + * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data, + * and then returns an array that describes the line. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param boolean A logical value specifying whether to return additional regression statistics. + * @return array + */ + public static function LINEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + $stats = (is_null($stats)) ? false : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats); + if (is_null($xValues)) { + $xValues = range(1, count(PHPExcel_Calculation_Functions::flattenArray($yValues))); + } + + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return 0; + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues, $const); + if ($stats) { + return array( + array( + $bestFitLinear->getSlope(), + $bestFitLinear->getSlopeSE(), + $bestFitLinear->getGoodnessOfFit(), + $bestFitLinear->getF(), + $bestFitLinear->getSSRegression(), + ), + array( + $bestFitLinear->getIntersect(), + $bestFitLinear->getIntersectSE(), + $bestFitLinear->getStdevOfResiduals(), + $bestFitLinear->getDFResiduals(), + $bestFitLinear->getSSResiduals() + ) + ); + } else { + return array( + $bestFitLinear->getSlope(), + $bestFitLinear->getIntersect() + ); + } + } + + + /** + * LOGEST + * + * Calculates an exponential curve that best fits the X and Y data series, + * and then returns an array that describes the line. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @param boolean A logical value specifying whether to return additional regression statistics. + * @return array + */ + public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false) + { + $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + $stats = (is_null($stats)) ? false : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats); + if (is_null($xValues)) { + $xValues = range(1, count(PHPExcel_Calculation_Functions::flattenArray($yValues))); + } + + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + foreach ($yValues as $value) { + if ($value <= 0.0) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return 1; + } + + $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL, $yValues, $xValues, $const); + if ($stats) { + return array( + array( + $bestFitExponential->getSlope(), + $bestFitExponential->getSlopeSE(), + $bestFitExponential->getGoodnessOfFit(), + $bestFitExponential->getF(), + $bestFitExponential->getSSRegression(), + ), + array( + $bestFitExponential->getIntersect(), + $bestFitExponential->getIntersectSE(), + $bestFitExponential->getStdevOfResiduals(), + $bestFitExponential->getDFResiduals(), + $bestFitExponential->getSSResiduals() + ) + ); + } else { + return array( + $bestFitExponential->getSlope(), + $bestFitExponential->getIntersect() + ); + } + } + + + /** + * LOGINV + * + * Returns the inverse of the normal cumulative distribution + * + * @param float $probability + * @param float $mean + * @param float $stdDev + * @return float + * + * @todo Try implementing P J Acklam's refinement algorithm for greater + * accuracy if I can get my head round the mathematics + * (as described at) http://home.online.no/~pjacklam/notes/invnorm/ + */ + public static function LOGINV($probability, $mean, $stdDev) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return exp($mean + $stdDev * self::NORMSINV($probability)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * LOGNORMDIST + * + * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed + * with parameters mean and standard_dev. + * + * @param float $value + * @param float $mean + * @param float $stdDev + * @return float + */ + public static function LOGNORMDIST($value, $mean, $stdDev) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($value <= 0) || ($stdDev <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::NORMSDIST((log($value) - $mean) / $stdDev); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * MAX + * + * MAX returns the value of the element of the values passed that has the highest value, + * with negative numbers considered smaller than positive numbers. + * + * Excel Function: + * MAX(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MAX() + { + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } + + + /** + * MAXA + * + * Returns the greatest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MAXA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MAXA() + { + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } + + + /** + * MAXIF + * + * Counts the maximum value within a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * MAXIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @return float + */ + public static function MAXIF($aArgs, $condition, $sumArgs = array()) + { + $returnValue = null; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg > $returnValue)) { + $returnValue = $arg; + } + } + } + + return $returnValue; + } + + /** + * MEDIAN + * + * Returns the median of the given numbers. The median is the number in the middle of a set of numbers. + * + * Excel Function: + * MEDIAN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MEDIAN() + { + $returnValue = PHPExcel_Calculation_Functions::NaN(); + + $mArgs = array(); + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs, SORT_NUMERIC); + $mValueCount = $mValueCount / 2; + if ($mValueCount == floor($mValueCount)) { + $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2; + } else { + $mValueCount = floor($mValueCount); + $returnValue = $mArgs[$mValueCount]; + } + } + + return $returnValue; + } + + + /** + * MIN + * + * MIN returns the value of the element of the values passed that has the smallest value, + * with negative numbers considered smaller than positive numbers. + * + * Excel Function: + * MIN(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MIN() + { + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } + + + /** + * MINA + * + * Returns the smallest value in a list of arguments, including numbers, text, and logical values + * + * Excel Function: + * MINA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MINA() + { + $returnValue = null; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + if (is_null($returnValue)) { + return 0; + } + return $returnValue; + } + + + /** + * MINIF + * + * Returns the minimum value within a range of cells that contain numbers within the list of arguments + * + * Excel Function: + * MINIF(value1[,value2[, ...]],condition) + * + * @access public + * @category Mathematical and Trigonometric Functions + * @param mixed $arg,... Data values + * @param string $condition The criteria that defines which cells will be checked. + * @return float + */ + public static function MINIF($aArgs, $condition, $sumArgs = array()) + { + $returnValue = null; + + $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs); + $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs); + if (empty($sumArgs)) { + $sumArgs = $aArgs; + } + $condition = PHPExcel_Calculation_Functions::ifCondition($condition); + // Loop through arguments + foreach ($aArgs as $key => $arg) { + if (!is_numeric($arg)) { + $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg)); + } + $testCondition = '='.$arg.$condition; + if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) { + if ((is_null($returnValue)) || ($arg < $returnValue)) { + $returnValue = $arg; + } + } + } + + return $returnValue; + } + + + // + // Special variant of array_count_values that isn't limited to strings and integers, + // but can work with floating point numbers as values + // + private static function modeCalc($data) + { + $frequencyArray = array(); + foreach ($data as $datum) { + $found = false; + foreach ($frequencyArray as $key => $value) { + if ((string) $value['value'] == (string) $datum) { + ++$frequencyArray[$key]['frequency']; + $found = true; + break; + } + } + if (!$found) { + $frequencyArray[] = array( + 'value' => $datum, + 'frequency' => 1 + ); + } + } + + foreach ($frequencyArray as $key => $value) { + $frequencyList[$key] = $value['frequency']; + $valueList[$key] = $value['value']; + } + array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray); + + if ($frequencyArray[0]['frequency'] == 1) { + return PHPExcel_Calculation_Functions::NA(); + } + return $frequencyArray[0]['value']; + } + + + /** + * MODE + * + * Returns the most frequently occurring, or repetitive, value in an array or range of data + * + * Excel Function: + * MODE(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function MODE() + { + $returnValue = PHPExcel_Calculation_Functions::NA(); + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + + if (!empty($mArgs)) { + return self::modeCalc($mArgs); + } + + return $returnValue; + } + + + /** + * NEGBINOMDIST + * + * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that + * there will be number_f failures before the number_s-th success, when the constant + * probability of a success is probability_s. This function is similar to the binomial + * distribution, except that the number of successes is fixed, and the number of trials is + * variable. Like the binomial, trials are assumed to be independent. + * + * @param float $failures Number of Failures + * @param float $successes Threshold number of Successes + * @param float $probability Probability of success on each trial + * @return float + * + */ + public static function NEGBINOMDIST($failures, $successes, $probability) + { + $failures = floor(PHPExcel_Calculation_Functions::flattenSingleValue($failures)); + $successes = floor(PHPExcel_Calculation_Functions::flattenSingleValue($successes)); + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + + if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) { + if (($failures < 0) || ($successes < 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } elseif (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) { + if (($failures + $successes - 1) <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + } + return (PHPExcel_Calculation_MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * (pow($probability, $successes)) * (pow(1 - $probability, $failures)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * NORMDIST + * + * Returns the normal distribution for the specified mean and standard deviation. This + * function has a very wide range of applications in statistics, including hypothesis + * testing. + * + * @param float $value + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @param boolean $cumulative + * @return float + * + */ + public static function NORMDIST($value, $mean, $stdDev, $cumulative) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if ($stdDev < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 0.5 * (1 + PHPExcel_Calculation_Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2)))); + } else { + return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean, 2) / (2 * ($stdDev * $stdDev)))); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * NORMINV + * + * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation. + * + * @param float $value + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @return float + * + */ + public static function NORMINV($probability, $mean, $stdDev) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if (($probability < 0) || ($probability > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ($stdDev < 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return (self::inverseNcdf($probability) * $stdDev) + $mean; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * NORMSDIST + * + * Returns the standard normal cumulative distribution function. The distribution has + * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a + * table of standard normal curve areas. + * + * @param float $value + * @return float + */ + public static function NORMSDIST($value) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + return self::NORMDIST($value, 0, 1, true); + } + + + /** + * NORMSINV + * + * Returns the inverse of the standard normal cumulative distribution + * + * @param float $value + * @return float + */ + public static function NORMSINV($value) + { + return self::NORMINV($value, 0, 1); + } + + + /** + * PERCENTILE + * + * Returns the nth percentile of values in a range.. + * + * Excel Function: + * PERCENTILE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param float $entry Percentile value in the range 0..1, inclusive. + * @return float + */ + public static function PERCENTILE() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + if (($entry < 0) || ($entry > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $mValueCount = count($mArgs); + if ($mValueCount > 0) { + sort($mArgs); + $count = self::COUNT($mArgs); + $index = $entry * ($count-1); + $iBase = floor($index); + if ($index == $iBase) { + return $mArgs[$index]; + } else { + $iNext = $iBase + 1; + $iProportion = $index - $iBase; + return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * PERCENTRANK + * + * Returns the rank of a value in a data set as a percentage of the data set. + * + * @param array of number An array of, or a reference to, a list of numbers. + * @param number The number whose rank you want to find. + * @param number The number of significant digits for the returned percentage value. + * @return float + */ + public static function PERCENTRANK($valueSet, $value, $significance = 3) + { + $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet); + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $significance = (is_null($significance)) ? 3 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($significance); + + foreach ($valueSet as $key => $valueEntry) { + if (!is_numeric($valueEntry)) { + unset($valueSet[$key]); + } + } + sort($valueSet, SORT_NUMERIC); + $valueCount = count($valueSet); + if ($valueCount == 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + + $valueAdjustor = $valueCount - 1; + if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) { + return PHPExcel_Calculation_Functions::NA(); + } + + $pos = array_search($value, $valueSet); + if ($pos === false) { + $pos = 0; + $testValue = $valueSet[0]; + while ($testValue < $value) { + $testValue = $valueSet[++$pos]; + } + --$pos; + $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos])); + } + + return round($pos / $valueAdjustor, $significance); + } + + + /** + * PERMUT + * + * Returns the number of permutations for a given number of objects that can be + * selected from number objects. A permutation is any set or subset of objects or + * events where internal order is significant. Permutations are different from + * combinations, for which the internal order is not significant. Use this function + * for lottery-style probability calculations. + * + * @param int $numObjs Number of different objects + * @param int $numInSet Number of objects in each permutation + * @return int Number of permutations + */ + public static function PERMUT($numObjs, $numInSet) + { + $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs); + $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet); + + if ((is_numeric($numObjs)) && (is_numeric($numInSet))) { + $numInSet = floor($numInSet); + if ($numObjs < $numInSet) { + return PHPExcel_Calculation_Functions::NaN(); + } + return round(PHPExcel_Calculation_MathTrig::FACT($numObjs) / PHPExcel_Calculation_MathTrig::FACT($numObjs - $numInSet)); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * POISSON + * + * Returns the Poisson distribution. A common application of the Poisson distribution + * is predicting the number of events over a specific time, such as the number of + * cars arriving at a toll plaza in 1 minute. + * + * @param float $value + * @param float $mean Mean Value + * @param boolean $cumulative + * @return float + * + */ + public static function POISSON($value, $mean, $cumulative) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + + if ((is_numeric($value)) && (is_numeric($mean))) { + if (($value < 0) || ($mean <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + $summer = 0; + for ($i = 0; $i <= floor($value); ++$i) { + $summer += pow($mean, $i) / PHPExcel_Calculation_MathTrig::FACT($i); + } + return exp(0-$mean) * $summer; + } else { + return (exp(0-$mean) * pow($mean, $value)) / PHPExcel_Calculation_MathTrig::FACT($value); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * QUARTILE + * + * Returns the quartile of a data set. + * + * Excel Function: + * QUARTILE(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Quartile value in the range 1..3, inclusive. + * @return float + */ + public static function QUARTILE() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = floor(array_pop($aArgs)); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $entry /= 4; + if (($entry < 0) || ($entry > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + return self::PERCENTILE($aArgs, $entry); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * RANK + * + * Returns the rank of a number in a list of numbers. + * + * @param number The number whose rank you want to find. + * @param array of number An array of, or a reference to, a list of numbers. + * @param mixed Order to sort the values in the value set + * @return float + */ + public static function RANK($value, $valueSet, $order = 0) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet); + $order = (is_null($order)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($order); + + foreach ($valueSet as $key => $valueEntry) { + if (!is_numeric($valueEntry)) { + unset($valueSet[$key]); + } + } + + if ($order == 0) { + rsort($valueSet, SORT_NUMERIC); + } else { + sort($valueSet, SORT_NUMERIC); + } + $pos = array_search($value, $valueSet); + if ($pos === false) { + return PHPExcel_Calculation_Functions::NA(); + } + + return ++$pos; + } + + + /** + * RSQ + * + * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function RSQ($yValues, $xValues) + { + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getGoodnessOfFit(); + } + + + /** + * SKEW + * + * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry + * of a distribution around its mean. Positive skewness indicates a distribution with an + * asymmetric tail extending toward more positive values. Negative skewness indicates a + * distribution with an asymmetric tail extending toward more negative values. + * + * @param array Data Series + * @return float + */ + public static function SKEW() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $mean = self::AVERAGE($aArgs); + $stdDev = self::STDEV($aArgs); + + $count = $summer = 0; + // Loop through arguments + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summer += pow((($arg - $mean) / $stdDev), 3); + ++$count; + } + } + } + + if ($count > 2) { + return $summer * ($count / (($count-1) * ($count-2))); + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * SLOPE + * + * Returns the slope of the linear regression line through data points in known_y's and known_x's. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function SLOPE($yValues, $xValues) + { + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getSlope(); + } + + + /** + * SMALL + * + * Returns the nth smallest value in a data set. You can use this function to + * select a value based on its relative standing. + * + * Excel Function: + * SMALL(value1[,value2[, ...]],entry) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param int $entry Position (ordered from the smallest) in the array or range of data to return + * @return float + */ + public static function SMALL() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $entry = array_pop($aArgs); + + if ((is_numeric($entry)) && (!is_string($entry))) { + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $count = self::COUNT($mArgs); + $entry = floor(--$entry); + if (($entry < 0) || ($entry >= $count) || ($count == 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + sort($mArgs); + return $mArgs[$entry]; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * STANDARDIZE + * + * Returns a normalized value from a distribution characterized by mean and standard_dev. + * + * @param float $value Value to normalize + * @param float $mean Mean Value + * @param float $stdDev Standard Deviation + * @return float Standardized value + */ + public static function STANDARDIZE($value, $mean, $stdDev) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean); + $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev); + + if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) { + if ($stdDev <= 0) { + return PHPExcel_Calculation_Functions::NaN(); + } + return ($value - $mean) / $stdDev ; + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * STDEV + * + * Estimates standard deviation based on a sample. The standard deviation is a measure of how + * widely values are dispersed from the average value (the mean). + * + * Excel Function: + * STDEV(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEV() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + // Return value + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if (!is_null($aMean)) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean), 2); + } else { + $returnValue += pow(($arg - $aMean), 2); + } + ++$aCount; + } + } + + // Return + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * STDEVA + * + * Estimates standard deviation based on a sample, including numbers, text, and logical values + * + * Excel Function: + * STDEVA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVA() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + $returnValue = null; + + $aMean = self::AVERAGEA($aArgs); + if (!is_null($aMean)) { + $aCount = -1; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean), 2); + } else { + $returnValue += pow(($arg - $aMean), 2); + } + ++$aCount; + } + } + } + + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * STDEVP + * + * Calculates standard deviation based on the entire population + * + * Excel Function: + * STDEVP(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVP() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + $returnValue = null; + + $aMean = self::AVERAGE($aArgs); + if (!is_null($aMean)) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean), 2); + } else { + $returnValue += pow(($arg - $aMean), 2); + } + ++$aCount; + } + } + + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * STDEVPA + * + * Calculates standard deviation based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * STDEVPA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function STDEVPA() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + + $returnValue = null; + + $aMean = self::AVERAGEA($aArgs); + if (!is_null($aMean)) { + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_bool($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + if (is_null($returnValue)) { + $returnValue = pow(($arg - $aMean), 2); + } else { + $returnValue += pow(($arg - $aMean), 2); + } + ++$aCount; + } + } + } + + if (($aCount > 0) && ($returnValue >= 0)) { + return sqrt($returnValue / $aCount); + } + } + return PHPExcel_Calculation_Functions::DIV0(); + } + + + /** + * STEYX + * + * Returns the standard error of the predicted y-value for each x in the regression. + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @return float + */ + public static function STEYX($yValues, $xValues) + { + if (!self::checkTrendArrays($yValues, $xValues)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $yValueCount = count($yValues); + $xValueCount = count($xValues); + + if (($yValueCount == 0) || ($yValueCount != $xValueCount)) { + return PHPExcel_Calculation_Functions::NA(); + } elseif ($yValueCount == 1) { + return PHPExcel_Calculation_Functions::DIV0(); + } + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues); + return $bestFitLinear->getStdevOfResiduals(); + } + + + /** + * TDIST + * + * Returns the probability of Student's T distribution. + * + * @param float $value Value for the function + * @param float $degrees degrees of freedom + * @param float $tails number of tails (1 or 2) + * @return float + */ + public static function TDIST($value, $degrees, $tails) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + $tails = floor(PHPExcel_Calculation_Functions::flattenSingleValue($tails)); + + if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) { + if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) { + return PHPExcel_Calculation_Functions::NaN(); + } + // tdist, which finds the probability that corresponds to a given value + // of t with k degrees of freedom. This algorithm is translated from a + // pascal function on p81 of "Statistical Computing in Pascal" by D + // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd: + // London). The above Pascal algorithm is itself a translation of the + // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer + // Laboratory as reported in (among other places) "Applied Statistics + // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis + // Horwood Ltd.; W. Sussex, England). + $tterm = $degrees; + $ttheta = atan2($value, sqrt($tterm)); + $tc = cos($ttheta); + $ts = sin($ttheta); + $tsum = 0; + + if (($degrees % 2) == 1) { + $ti = 3; + $tterm = $tc; + } else { + $ti = 2; + $tterm = 1; + } + + $tsum = $tterm; + while ($ti < $degrees) { + $tterm *= $tc * $tc * ($ti - 1) / $ti; + $tsum += $tterm; + $ti += 2; + } + $tsum *= $ts; + if (($degrees % 2) == 1) { + $tsum = M_2DIVPI * ($tsum + $ttheta); + } + $tValue = 0.5 * (1 + $tsum); + if ($tails == 1) { + return 1 - abs($tValue); + } else { + return 1 - abs((1 - $tValue) - $tValue); + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * TINV + * + * Returns the one-tailed probability of the chi-squared distribution. + * + * @param float $probability Probability for the function + * @param float $degrees degrees of freedom + * @return float + */ + public static function TINV($probability, $degrees) + { + $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability); + $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees)); + + if ((is_numeric($probability)) && (is_numeric($degrees))) { + $xLo = 100; + $xHi = 0; + + $x = $xNew = 1; + $dx = 1; + $i = 0; + + while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) { + // Apply Newton-Raphson step + $result = self::TDIST($x, $degrees, 2); + $error = $result - $probability; + if ($error == 0.0) { + $dx = 0; + } elseif ($error < 0.0) { + $xLo = $x; + } else { + $xHi = $x; + } + // Avoid division by zero + if ($result != 0.0) { + $dx = $error / $result; + $xNew = $x - $dx; + } + // If the NR fails to converge (which for example may be the + // case if the initial guess is too rough) we apply a bisection + // step to determine a more narrow interval around the root. + if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) { + $xNew = ($xLo + $xHi) / 2; + $dx = $xNew - $x; + } + $x = $xNew; + } + if ($i == MAX_ITERATIONS) { + return PHPExcel_Calculation_Functions::NA(); + } + return round($x, 12); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * TREND + * + * Returns values along a linear trend + * + * @param array of mixed Data Series Y + * @param array of mixed Data Series X + * @param array of mixed Values of X for which we want to find Y + * @param boolean A logical value specifying whether to force the intersect to equal 0. + * @return array of float + */ + public static function TREND($yValues, $xValues = array(), $newValues = array(), $const = true) + { + $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues); + $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues); + $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues); + $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const); + + $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues, $const); + if (empty($newValues)) { + $newValues = $bestFitLinear->getXValues(); + } + + $returnArray = array(); + foreach ($newValues as $xValue) { + $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue); + } + + return $returnArray; + } + + + /** + * TRIMMEAN + * + * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean + * taken by excluding a percentage of data points from the top and bottom tails + * of a data set. + * + * Excel Function: + * TRIMEAN(value1[,value2[, ...]], $discard) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @param float $discard Percentage to discard + * @return float + */ + public static function TRIMMEAN() + { + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + + // Calculate + $percent = array_pop($aArgs); + + if ((is_numeric($percent)) && (!is_string($percent))) { + if (($percent < 0) || ($percent > 1)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $mArgs = array(); + foreach ($aArgs as $arg) { + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $mArgs[] = $arg; + } + } + $discard = floor(self::COUNT($mArgs) * $percent / 2); + sort($mArgs); + for ($i=0; $i < $discard; ++$i) { + array_pop($mArgs); + array_shift($mArgs); + } + return self::AVERAGE($mArgs); + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * VARFunc + * + * Estimates variance based on a sample. + * + * Excel Function: + * VAR(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARFunc() + { + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $aCount = 0; + foreach ($aArgs as $arg) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + return $returnValue; + } + + + /** + * VARA + * + * Estimates variance based on a sample, including numbers, text, and logical values + * + * Excel Function: + * VARA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARA() + { + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && + (PHPExcel_Calculation_Functions::isValue($k))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ((is_string($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 1) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * ($aCount - 1)); + } + return $returnValue; + } + + + /** + * VARP + * + * Calculates variance based on the entire population + * + * Excel Function: + * VARP(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARP() + { + // Return value + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + $aCount = 0; + foreach ($aArgs as $arg) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } + // Is it a numeric value? + if ((is_numeric($arg)) && (!is_string($arg))) { + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * $aCount); + } + return $returnValue; + } + + + /** + * VARPA + * + * Calculates variance based on the entire population, including numbers, text, and logical values + * + * Excel Function: + * VARPA(value1[,value2[, ...]]) + * + * @access public + * @category Statistical Functions + * @param mixed $arg,... Data values + * @return float + */ + public static function VARPA() + { + $returnValue = PHPExcel_Calculation_Functions::DIV0(); + + $summerA = $summerB = 0; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()); + $aCount = 0; + foreach ($aArgs as $k => $arg) { + if ((is_string($arg)) && + (PHPExcel_Calculation_Functions::isValue($k))) { + return PHPExcel_Calculation_Functions::VALUE(); + } elseif ((is_string($arg)) && + (!PHPExcel_Calculation_Functions::isMatrixValue($k))) { + } else { + // Is it a numeric value? + if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) { + if (is_bool($arg)) { + $arg = (integer) $arg; + } elseif (is_string($arg)) { + $arg = 0; + } + $summerA += ($arg * $arg); + $summerB += $arg; + ++$aCount; + } + } + } + + if ($aCount > 0) { + $summerA *= $aCount; + $summerB *= $summerB; + $returnValue = ($summerA - $summerB) / ($aCount * $aCount); + } + return $returnValue; + } + + + /** + * WEIBULL + * + * Returns the Weibull distribution. Use this distribution in reliability + * analysis, such as calculating a device's mean time to failure. + * + * @param float $value + * @param float $alpha Alpha Parameter + * @param float $beta Beta Parameter + * @param boolean $cumulative + * @return float + * + */ + public static function WEIBULL($value, $alpha, $beta, $cumulative) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha); + $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta); + + if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta))) { + if (($value < 0) || ($alpha <= 0) || ($beta <= 0)) { + return PHPExcel_Calculation_Functions::NaN(); + } + if ((is_numeric($cumulative)) || (is_bool($cumulative))) { + if ($cumulative) { + return 1 - exp(0 - pow($value / $beta, $alpha)); + } else { + return ($alpha / pow($beta, $alpha)) * pow($value, $alpha - 1) * exp(0 - pow($value / $beta, $alpha)); + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * ZTEST + * + * Returns the Weibull distribution. Use this distribution in reliability + * analysis, such as calculating a device's mean time to failure. + * + * @param float $dataSet + * @param float $m0 Alpha Parameter + * @param float $sigma Beta Parameter + * @param boolean $cumulative + * @return float + * + */ + public static function ZTEST($dataSet, $m0, $sigma = null) + { + $dataSet = PHPExcel_Calculation_Functions::flattenArrayIndexed($dataSet); + $m0 = PHPExcel_Calculation_Functions::flattenSingleValue($m0); + $sigma = PHPExcel_Calculation_Functions::flattenSingleValue($sigma); + + if (is_null($sigma)) { + $sigma = self::STDEV($dataSet); + } + $n = count($dataSet); + + return 1 - self::NORMSDIST((self::AVERAGE($dataSet) - $m0) / ($sigma / SQRT($n))); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/TextData.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/TextData.php new file mode 100644 index 00000000..6461d060 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/TextData.php @@ -0,0 +1,651 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Calculation_TextData + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_TextData +{ + private static $invalidChars; + + private static function unicodeToOrd($c) + { + if (ord($c{0}) >=0 && ord($c{0}) <= 127) { + return ord($c{0}); + } elseif (ord($c{0}) >= 192 && ord($c{0}) <= 223) { + return (ord($c{0})-192)*64 + (ord($c{1})-128); + } elseif (ord($c{0}) >= 224 && ord($c{0}) <= 239) { + return (ord($c{0})-224)*4096 + (ord($c{1})-128)*64 + (ord($c{2})-128); + } elseif (ord($c{0}) >= 240 && ord($c{0}) <= 247) { + return (ord($c{0})-240)*262144 + (ord($c{1})-128)*4096 + (ord($c{2})-128)*64 + (ord($c{3})-128); + } elseif (ord($c{0}) >= 248 && ord($c{0}) <= 251) { + return (ord($c{0})-248)*16777216 + (ord($c{1})-128)*262144 + (ord($c{2})-128)*4096 + (ord($c{3})-128)*64 + (ord($c{4})-128); + } elseif (ord($c{0}) >= 252 && ord($c{0}) <= 253) { + return (ord($c{0})-252)*1073741824 + (ord($c{1})-128)*16777216 + (ord($c{2})-128)*262144 + (ord($c{3})-128)*4096 + (ord($c{4})-128)*64 + (ord($c{5})-128); + } elseif (ord($c{0}) >= 254 && ord($c{0}) <= 255) { + // error + return PHPExcel_Calculation_Functions::VALUE(); + } + return 0; + } + + /** + * CHARACTER + * + * @param string $character Value + * @return int + */ + public static function CHARACTER($character) + { + $character = PHPExcel_Calculation_Functions::flattenSingleValue($character); + + if ((!is_numeric($character)) || ($character < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (function_exists('mb_convert_encoding')) { + return mb_convert_encoding('&#'.intval($character).';', 'UTF-8', 'HTML-ENTITIES'); + } else { + return chr(intval($character)); + } + } + + + /** + * TRIMNONPRINTABLE + * + * @param mixed $stringValue Value to check + * @return string + */ + public static function TRIMNONPRINTABLE($stringValue = '') + { + $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue); + + if (is_bool($stringValue)) { + return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (self::$invalidChars == null) { + self::$invalidChars = range(chr(0), chr(31)); + } + + if (is_string($stringValue) || is_numeric($stringValue)) { + return str_replace(self::$invalidChars, '', trim($stringValue, "\x00..\x1F")); + } + return null; + } + + + /** + * TRIMSPACES + * + * @param mixed $stringValue Value to check + * @return string + */ + public static function TRIMSPACES($stringValue = '') + { + $stringValue = PHPExcel_Calculation_Functions::flattenSingleValue($stringValue); + if (is_bool($stringValue)) { + return ($stringValue) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (is_string($stringValue) || is_numeric($stringValue)) { + return trim(preg_replace('/ +/', ' ', trim($stringValue, ' ')), ' '); + } + return null; + } + + + /** + * ASCIICODE + * + * @param string $characters Value + * @return int + */ + public static function ASCIICODE($characters) + { + if (($characters === null) || ($characters === '')) { + return PHPExcel_Calculation_Functions::VALUE(); + } + $characters = PHPExcel_Calculation_Functions::flattenSingleValue($characters); + if (is_bool($characters)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $characters = (int) $characters; + } else { + $characters = ($characters) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + } + + $character = $characters; + if ((function_exists('mb_strlen')) && (function_exists('mb_substr'))) { + if (mb_strlen($characters, 'UTF-8') > 1) { + $character = mb_substr($characters, 0, 1, 'UTF-8'); + } + return self::unicodeToOrd($character); + } else { + if (strlen($characters) > 0) { + $character = substr($characters, 0, 1); + } + return ord($character); + } + } + + + /** + * CONCATENATE + * + * @return string + */ + public static function CONCATENATE() + { + $returnValue = ''; + + // Loop through arguments + $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args()); + foreach ($aArgs as $arg) { + if (is_bool($arg)) { + if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) { + $arg = (int) $arg; + } else { + $arg = ($arg) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + } + $returnValue .= $arg; + } + + return $returnValue; + } + + + /** + * DOLLAR + * + * This function converts a number to text using currency format, with the decimals rounded to the specified place. + * The format used is $#,##0.00_);($#,##0.00).. + * + * @param float $value The value to format + * @param int $decimals The number of digits to display to the right of the decimal point. + * If decimals is negative, number is rounded to the left of the decimal point. + * If you omit decimals, it is assumed to be 2 + * @return string + */ + public static function DOLLAR($value = 0, $decimals = 2) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $decimals = is_null($decimals) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($decimals); + + // Validate parameters + if (!is_numeric($value) || !is_numeric($decimals)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $decimals = floor($decimals); + + $mask = '$#,##0'; + if ($decimals > 0) { + $mask .= '.' . str_repeat('0', $decimals); + } else { + $round = pow(10, abs($decimals)); + if ($value < 0) { + $round = 0-$round; + } + $value = PHPExcel_Calculation_MathTrig::MROUND($value, $round); + } + + return PHPExcel_Style_NumberFormat::toFormattedString($value, $mask); + + } + + + /** + * SEARCHSENSITIVE + * + * @param string $needle The string to look for + * @param string $haystack The string in which to look + * @param int $offset Offset within $haystack + * @return string + */ + public static function SEARCHSENSITIVE($needle, $haystack, $offset = 1) + { + $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle); + $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack); + $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset); + + if (!is_bool($needle)) { + if (is_bool($haystack)) { + $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) { + if (PHPExcel_Shared_String::CountCharacters($needle) == 0) { + return $offset; + } + if (function_exists('mb_strpos')) { + $pos = mb_strpos($haystack, $needle, --$offset, 'UTF-8'); + } else { + $pos = strpos($haystack, $needle, --$offset); + } + if ($pos !== false) { + return ++$pos; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * SEARCHINSENSITIVE + * + * @param string $needle The string to look for + * @param string $haystack The string in which to look + * @param int $offset Offset within $haystack + * @return string + */ + public static function SEARCHINSENSITIVE($needle, $haystack, $offset = 1) + { + $needle = PHPExcel_Calculation_Functions::flattenSingleValue($needle); + $haystack = PHPExcel_Calculation_Functions::flattenSingleValue($haystack); + $offset = PHPExcel_Calculation_Functions::flattenSingleValue($offset); + + if (!is_bool($needle)) { + if (is_bool($haystack)) { + $haystack = ($haystack) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (($offset > 0) && (PHPExcel_Shared_String::CountCharacters($haystack) > $offset)) { + if (PHPExcel_Shared_String::CountCharacters($needle) == 0) { + return $offset; + } + if (function_exists('mb_stripos')) { + $pos = mb_stripos($haystack, $needle, --$offset, 'UTF-8'); + } else { + $pos = stripos($haystack, $needle, --$offset); + } + if ($pos !== false) { + return ++$pos; + } + } + } + return PHPExcel_Calculation_Functions::VALUE(); + } + + + /** + * FIXEDFORMAT + * + * @param mixed $value Value to check + * @param integer $decimals + * @param boolean $no_commas + * @return boolean + */ + public static function FIXEDFORMAT($value, $decimals = 2, $no_commas = false) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $decimals = PHPExcel_Calculation_Functions::flattenSingleValue($decimals); + $no_commas = PHPExcel_Calculation_Functions::flattenSingleValue($no_commas); + + // Validate parameters + if (!is_numeric($value) || !is_numeric($decimals)) { + return PHPExcel_Calculation_Functions::NaN(); + } + $decimals = floor($decimals); + + $valueResult = round($value, $decimals); + if ($decimals < 0) { + $decimals = 0; + } + if (!$no_commas) { + $valueResult = number_format($valueResult, $decimals); + } + + return (string) $valueResult; + } + + + /** + * LEFT + * + * @param string $value Value + * @param int $chars Number of characters + * @return string + */ + public static function LEFT($value = '', $chars = 1) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if ($chars < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_substr')) { + return mb_substr($value, 0, $chars, 'UTF-8'); + } else { + return substr($value, 0, $chars); + } + } + + + /** + * MID + * + * @param string $value Value + * @param int $start Start character + * @param int $chars Number of characters + * @return string + */ + public static function MID($value = '', $start = 1, $chars = null) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $start = PHPExcel_Calculation_Functions::flattenSingleValue($start); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if (($start < 1) || ($chars < 0)) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_substr')) { + return mb_substr($value, --$start, $chars, 'UTF-8'); + } else { + return substr($value, --$start, $chars); + } + } + + + /** + * RIGHT + * + * @param string $value Value + * @param int $chars Number of characters + * @return string + */ + public static function RIGHT($value = '', $chars = 1) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + + if ($chars < 0) { + return PHPExcel_Calculation_Functions::VALUE(); + } + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if ((function_exists('mb_substr')) && (function_exists('mb_strlen'))) { + return mb_substr($value, mb_strlen($value, 'UTF-8') - $chars, $chars, 'UTF-8'); + } else { + return substr($value, strlen($value) - $chars); + } + } + + + /** + * STRINGLENGTH + * + * @param string $value Value + * @return string + */ + public static function STRINGLENGTH($value = '') + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (is_bool($value)) { + $value = ($value) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + if (function_exists('mb_strlen')) { + return mb_strlen($value, 'UTF-8'); + } else { + return strlen($value); + } + } + + + /** + * LOWERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function LOWERCASE($mixedCaseString) + { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToLower($mixedCaseString); + } + + + /** + * UPPERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function UPPERCASE($mixedCaseString) + { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToUpper($mixedCaseString); + } + + + /** + * PROPERCASE + * + * Converts a string value to upper case. + * + * @param string $mixedCaseString + * @return string + */ + public static function PROPERCASE($mixedCaseString) + { + $mixedCaseString = PHPExcel_Calculation_Functions::flattenSingleValue($mixedCaseString); + + if (is_bool($mixedCaseString)) { + $mixedCaseString = ($mixedCaseString) ? PHPExcel_Calculation::getTRUE() : PHPExcel_Calculation::getFALSE(); + } + + return PHPExcel_Shared_String::StrToTitle($mixedCaseString); + } + + + /** + * REPLACE + * + * @param string $oldText String to modify + * @param int $start Start character + * @param int $chars Number of characters + * @param string $newText String to replace in defined position + * @return string + */ + public static function REPLACE($oldText = '', $start = 1, $chars = null, $newText) + { + $oldText = PHPExcel_Calculation_Functions::flattenSingleValue($oldText); + $start = PHPExcel_Calculation_Functions::flattenSingleValue($start); + $chars = PHPExcel_Calculation_Functions::flattenSingleValue($chars); + $newText = PHPExcel_Calculation_Functions::flattenSingleValue($newText); + + $left = self::LEFT($oldText, $start-1); + $right = self::RIGHT($oldText, self::STRINGLENGTH($oldText)-($start+$chars)+1); + + return $left.$newText.$right; + } + + + /** + * SUBSTITUTE + * + * @param string $text Value + * @param string $fromText From Value + * @param string $toText To Value + * @param integer $instance Instance Number + * @return string + */ + public static function SUBSTITUTE($text = '', $fromText = '', $toText = '', $instance = 0) + { + $text = PHPExcel_Calculation_Functions::flattenSingleValue($text); + $fromText = PHPExcel_Calculation_Functions::flattenSingleValue($fromText); + $toText = PHPExcel_Calculation_Functions::flattenSingleValue($toText); + $instance = floor(PHPExcel_Calculation_Functions::flattenSingleValue($instance)); + + if ($instance == 0) { + if (function_exists('mb_str_replace')) { + return mb_str_replace($fromText, $toText, $text); + } else { + return str_replace($fromText, $toText, $text); + } + } else { + $pos = -1; + while ($instance > 0) { + if (function_exists('mb_strpos')) { + $pos = mb_strpos($text, $fromText, $pos+1, 'UTF-8'); + } else { + $pos = strpos($text, $fromText, $pos+1); + } + if ($pos === false) { + break; + } + --$instance; + } + if ($pos !== false) { + if (function_exists('mb_strlen')) { + return self::REPLACE($text, ++$pos, mb_strlen($fromText, 'UTF-8'), $toText); + } else { + return self::REPLACE($text, ++$pos, strlen($fromText), $toText); + } + } + } + + return $text; + } + + + /** + * RETURNSTRING + * + * @param mixed $testValue Value to check + * @return boolean + */ + public static function RETURNSTRING($testValue = '') + { + $testValue = PHPExcel_Calculation_Functions::flattenSingleValue($testValue); + + if (is_string($testValue)) { + return $testValue; + } + return null; + } + + + /** + * TEXTFORMAT + * + * @param mixed $value Value to check + * @param string $format Format mask to use + * @return boolean + */ + public static function TEXTFORMAT($value, $format) + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + $format = PHPExcel_Calculation_Functions::flattenSingleValue($format); + + if ((is_string($value)) && (!is_numeric($value)) && PHPExcel_Shared_Date::isDateTimeFormatCode($format)) { + $value = PHPExcel_Calculation_DateTime::DATEVALUE($value); + } + + return (string) PHPExcel_Style_NumberFormat::toFormattedString($value, $format); + } + + /** + * VALUE + * + * @param mixed $value Value to check + * @return boolean + */ + public static function VALUE($value = '') + { + $value = PHPExcel_Calculation_Functions::flattenSingleValue($value); + + if (!is_numeric($value)) { + $numberValue = str_replace( + PHPExcel_Shared_String::getThousandsSeparator(), + '', + trim($value, " \t\n\r\0\x0B" . PHPExcel_Shared_String::getCurrencyCode()) + ); + if (is_numeric($numberValue)) { + return (float) $numberValue; + } + + $dateSetting = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + + if (strpos($value, ':') !== false) { + $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($value); + if ($timeValue !== PHPExcel_Calculation_Functions::VALUE()) { + PHPExcel_Calculation_Functions::setReturnDateType($dateSetting); + return $timeValue; + } + } + $dateValue = PHPExcel_Calculation_DateTime::DATEVALUE($value); + if ($dateValue !== PHPExcel_Calculation_Functions::VALUE()) { + PHPExcel_Calculation_Functions::setReturnDateType($dateSetting); + return $dateValue; + } + PHPExcel_Calculation_Functions::setReturnDateType($dateSetting); + + return PHPExcel_Calculation_Functions::VALUE(); + } + return (float) $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Token/Stack.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Token/Stack.php new file mode 100644 index 00000000..02ed5aaf --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/Token/Stack.php @@ -0,0 +1,111 @@ +<?php + +/** + * PHPExcel_Calculation_Token_Stack + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Calculation + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Calculation_Token_Stack +{ + /** + * The parser stack for formulae + * + * @var mixed[] + */ + private $stack = array(); + + /** + * Count of entries in the parser stack + * + * @var integer + */ + private $count = 0; + + /** + * Return the number of entries on the stack + * + * @return integer + */ + public function count() + { + return $this->count; + } + + /** + * Push a new entry onto the stack + * + * @param mixed $type + * @param mixed $value + * @param mixed $reference + */ + public function push($type, $value, $reference = null) + { + $this->stack[$this->count++] = array( + 'type' => $type, + 'value' => $value, + 'reference' => $reference + ); + if ($type == 'Function') { + $localeFunction = PHPExcel_Calculation::localeFunc($value); + if ($localeFunction != $value) { + $this->stack[($this->count - 1)]['localeValue'] = $localeFunction; + } + } + } + + /** + * Pop the last entry from the stack + * + * @return mixed + */ + public function pop() + { + if ($this->count > 0) { + return $this->stack[--$this->count]; + } + return null; + } + + /** + * Return an entry from the stack without removing it + * + * @param integer $n number indicating how far back in the stack we want to look + * @return mixed + */ + public function last($n = 1) + { + if ($this->count - $n < 0) { + return null; + } + return $this->stack[$this->count - $n]; + } + + /** + * Clear the stack + */ + public function clear() + { + $this->stack = array(); + $this->count = 0; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/functionlist.txt b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/functionlist.txt new file mode 100644 index 00000000..67dbd49c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Calculation/functionlist.txt @@ -0,0 +1,351 @@ +ABS +ACCRINT +ACCRINTM +ACOS +ACOSH +ADDRESS +AMORDEGRC +AMORLINC +AND +AREAS +ASC +ASIN +ASINH +ATAN +ATAN2 +ATANH +AVEDEV +AVERAGE +AVERAGEA +AVERAGEIF +AVERAGEIFS +BAHTTEXT +BESSELI +BESSELJ +BESSELK +BESSELY +BETADIST +BETAINV +BIN2DEC +BIN2HEX +BIN2OCT +BINOMDIST +CEILING +CELL +CHAR +CHIDIST +CHIINV +CHITEST +CHOOSE +CLEAN +CODE +COLUMN +COLUMNS +COMBIN +COMPLEX +CONCATENATE +CONFIDENCE +CONVERT +CORREL +COS +COSH +COUNT +COUNTA +COUNTBLANK +COUNTIF +COUNTIFS +COUPDAYBS +COUPDAYBS +COUPDAYSNC +COUPNCD +COUPNUM +COUPPCD +COVAR +CRITBINOM +CUBEKPIMEMBER +CUBEMEMBER +CUBEMEMBERPROPERTY +CUBERANKEDMEMBER +CUBESET +CUBESETCOUNT +CUBEVALUE +CUMIPMT +CUMPRINC +DATE +DATEDIF +DATEVALUE +DAVERAGE +DAY +DAYS360 +DB +DCOUNT +DCOUNTA +DDB +DEC2BIN +DEC2HEX +DEC2OCT +DEGREES +DELTA +DEVSQ +DGET +DISC +DMAX +DMIN +DOLLAR +DOLLARDE +DOLLARFR +DPRODUCT +DSTDEV +DSTDEVP +DSUM +DURATION +DVAR +DVARP +EDATE +EFFECT +EOMONTH +ERF +ERFC +ERROR.TYPE +EVEN +EXACT +EXP +EXPONDIST +FACT +FACTDOUBLE +FALSE +FDIST +FIND +FINDB +FINV +FISHER +FISHERINV +FIXED +FLOOR +FORECAST +FREQUENCY +FTEST +FV +FVSCHEDULE +GAMAMDIST +GAMMAINV +GAMMALN +GCD +GEOMEAN +GESTEP +GETPIVOTDATA +GROWTH +HARMEAN +HEX2BIN +HEX2OCT +HLOOKUP +HOUR +HYPERLINK +HYPGEOMDIST +IF +IFERROR +IMABS +IMAGINARY +IMARGUMENT +IMCONJUGATE +IMCOS +IMEXP +IMLN +IMLOG10 +IMLOG2 +IMPOWER +IMPRODUCT +IMREAL +IMSIN +IMSQRT +IMSUB +IMSUM +INDEX +INDIRECT +INFO +INT +INTERCEPT +INTRATE +IPMT +IRR +ISBLANK +ISERR +ISERROR +ISEVEN +ISLOGICAL +ISNA +ISNONTEXT +ISNUMBER +ISODD +ISPMT +ISREF +ISTEXT +JIS +KURT +LARGE +LCM +LEFT +LEFTB +LEN +LENB +LINEST +LN +LOG +LOG10 +LOGEST +LOGINV +LOGNORMDIST +LOOKUP +LOWER +MATCH +MAX +MAXA +MDETERM +MDURATION +MEDIAN +MID +MIDB +MIN +MINA +MINUTE +MINVERSE +MIRR +MMULT +MOD +MODE +MONTH +MROUND +MULTINOMIAL +N +NA +NEGBINOMDIST +NETWORKDAYS +NOMINAL +NORMDIST +NORMINV +NORMSDIST +NORMSINV +NOT +NOW +NPER +NPV +OCT2BIN +OCT2DEC +OCT2HEX +ODD +ODDFPRICE +ODDFYIELD +ODDLPRICE +ODDLYIELD +OFFSET +OR +PEARSON +PERCENTILE +PERCENTRANK +PERMUT +PHONETIC +PI +PMT +POISSON +POWER +PPMT +PRICE +PRICEDISC +PRICEMAT +PROB +PRODUCT +PROPER +PV +QUARTILE +QUOTIENT +RADIANS +RAND +RANDBETWEEN +RANK +RATE +RECEIVED +REPLACE +REPLACEB +REPT +RIGHT +RIGHTB +ROMAN +ROUND +ROUNDDOWN +ROUNDUP +ROW +ROWS +RSQ +RTD +SEARCH +SEARCHB +SECOND +SERIESSUM +SIGN +SIN +SINH +SKEW +SLN +SLOPE +SMALL +SQRT +SQRTPI +STANDARDIZE +STDEV +STDEVA +STDEVP +STDEVPA +STEYX +SUBSTITUTE +SUBTOTAL +SUM +SUMIF +SUMIFS +SUMPRODUCT +SUMSQ +SUMX2MY2 +SUMX2PY2 +SUMXMY2 +SYD +T +TAN +TANH +TBILLEQ +TBILLPRICE +TBILLYIELD +TDIST +TEXT +TIME +TIMEVALUE +TINV +TODAY +TRANSPOSE +TREND +TRIM +TRIMMEAN +TRUE +TRUNC +TTEST +TYPE +UPPER +USDOLLAR +VALUE +VAR +VARA +VARP +VARPA +VDB +VERSION +VLOOKUP +WEEKDAY +WEEKNUM +WEIBULL +WORKDAY +XIRR +XNPV +YEAR +YEARFRAC +YIELD +YIELDDISC +YIELDMAT +ZTEST diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell.php new file mode 100644 index 00000000..c99a3c8b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell.php @@ -0,0 +1,1032 @@ +<?php + +/** + * PHPExcel_Cell + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell +{ + /** + * Default range variable constant + * + * @var string + */ + const DEFAULT_RANGE = 'A1:A1'; + + /** + * Value binder to use + * + * @var PHPExcel_Cell_IValueBinder + */ + private static $valueBinder; + + /** + * Value of the cell + * + * @var mixed + */ + private $value; + + /** + * Calculated value of the cell (used for caching) + * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to + * create the original spreadsheet file. + * Note that this value is not guaranteed to reflect the actual calculated value because it is + * possible that auto-calculation was disabled in the original spreadsheet, and underlying data + * values used by the formula have changed since it was last calculated. + * + * @var mixed + */ + private $calculatedValue; + + /** + * Type of the cell data + * + * @var string + */ + private $dataType; + + /** + * Parent worksheet + * + * @var PHPExcel_CachedObjectStorage_CacheBase + */ + private $parent; + + /** + * Index to cellXf + * + * @var int + */ + private $xfIndex = 0; + + /** + * Attributes of the formula + * + */ + private $formulaAttributes; + + + /** + * Send notification to the cache controller + * + * @return void + **/ + public function notifyCacheController() + { + $this->parent->updateCacheData($this); + + return $this; + } + + public function detach() + { + $this->parent = null; + } + + public function attach(PHPExcel_CachedObjectStorage_CacheBase $parent) + { + $this->parent = $parent; + } + + + /** + * Create a new Cell + * + * @param mixed $pValue + * @param string $pDataType + * @param PHPExcel_Worksheet $pSheet + * @throws PHPExcel_Exception + */ + public function __construct($pValue = null, $pDataType = null, PHPExcel_Worksheet $pSheet = null) + { + // Initialise cell value + $this->value = $pValue; + + // Set worksheet cache + $this->parent = $pSheet->getCellCacheController(); + + // Set datatype? + if ($pDataType !== null) { + if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) { + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + } + $this->dataType = $pDataType; + } elseif (!self::getValueBinder()->bindValue($this, $pValue)) { + throw new PHPExcel_Exception("Value could not be bound to cell."); + } + } + + /** + * Get cell coordinate column + * + * @return string + */ + public function getColumn() + { + return $this->parent->getCurrentColumn(); + } + + /** + * Get cell coordinate row + * + * @return int + */ + public function getRow() + { + return $this->parent->getCurrentRow(); + } + + /** + * Get cell coordinate + * + * @return string + */ + public function getCoordinate() + { + return $this->parent->getCurrentAddress(); + } + + /** + * Get cell value + * + * @return mixed + */ + public function getValue() + { + return $this->value; + } + + /** + * Get cell value with formatting + * + * @return string + */ + public function getFormattedValue() + { + return (string) PHPExcel_Style_NumberFormat::toFormattedString( + $this->getCalculatedValue(), + $this->getStyle() + ->getNumberFormat()->getFormatCode() + ); + } + + /** + * Set cell value + * + * Sets the value for a cell, automatically determining the datatype using the value binder + * + * @param mixed $pValue Value + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setValue($pValue = null) + { + if (!self::getValueBinder()->bindValue($this, $pValue)) { + throw new PHPExcel_Exception("Value could not be bound to cell."); + } + return $this; + } + + /** + * Set the value for a cell, with the explicit data type passed to the method (bypassing any use of the value binder) + * + * @param mixed $pValue Value + * @param string $pDataType Explicit data type + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setValueExplicit($pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING) + { + // set the value according to data type + switch ($pDataType) { + case PHPExcel_Cell_DataType::TYPE_NULL: + $this->value = $pValue; + break; + case PHPExcel_Cell_DataType::TYPE_STRING2: + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + // no break + case PHPExcel_Cell_DataType::TYPE_STRING: + // Synonym for string + case PHPExcel_Cell_DataType::TYPE_INLINE: + // Rich text + $this->value = PHPExcel_Cell_DataType::checkString($pValue); + break; + case PHPExcel_Cell_DataType::TYPE_NUMERIC: + $this->value = (float) $pValue; + break; + case PHPExcel_Cell_DataType::TYPE_FORMULA: + $this->value = (string) $pValue; + break; + case PHPExcel_Cell_DataType::TYPE_BOOL: + $this->value = (bool) $pValue; + break; + case PHPExcel_Cell_DataType::TYPE_ERROR: + $this->value = PHPExcel_Cell_DataType::checkErrorCode($pValue); + break; + default: + throw new PHPExcel_Exception('Invalid datatype: ' . $pDataType); + break; + } + + // set the datatype + $this->dataType = $pDataType; + + return $this->notifyCacheController(); + } + + /** + * Get calculated cell value + * + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + * + * @param boolean $resetLog Whether the calculation engine logger should be reset or not + * @return mixed + * @throws PHPExcel_Exception + */ + public function getCalculatedValue($resetLog = true) + { +//echo 'Cell '.$this->getCoordinate().' value is a '.$this->dataType.' with a value of '.$this->getValue().PHP_EOL; + if ($this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA) { + try { +//echo 'Cell value for '.$this->getCoordinate().' is a formula: Calculating value'.PHP_EOL; + $result = PHPExcel_Calculation::getInstance( + $this->getWorksheet()->getParent() + )->calculateCellValue($this, $resetLog); +//echo $this->getCoordinate().' calculation result is '.$result.PHP_EOL; + // We don't yet handle array returns + if (is_array($result)) { + while (is_array($result)) { + $result = array_pop($result); + } + } + } catch (PHPExcel_Exception $ex) { + if (($ex->getMessage() === 'Unable to access External Workbook') && ($this->calculatedValue !== null)) { +//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->calculatedValue; // Fallback for calculations referencing external files. + } +//echo 'Calculation Exception: '.$ex->getMessage().PHP_EOL; + $result = '#N/A'; + throw new PHPExcel_Calculation_Exception( + $this->getWorksheet()->getTitle().'!'.$this->getCoordinate().' -> '.$ex->getMessage() + ); + } + + if ($result === '#Not Yet Implemented') { +//echo 'Returning fallback value of '.$this->calculatedValue.' for cell '.$this->getCoordinate().PHP_EOL; + return $this->calculatedValue; // Fallback if calculation engine does not support the formula. + } +//echo 'Returning calculated value of '.$result.' for cell '.$this->getCoordinate().PHP_EOL; + return $result; + } elseif ($this->value instanceof PHPExcel_RichText) { +// echo 'Cell value for '.$this->getCoordinate().' is rich text: Returning data value of '.$this->value.'<br />'; + return $this->value->getPlainText(); + } +// echo 'Cell value for '.$this->getCoordinate().' is not a formula: Returning data value of '.$this->value.'<br />'; + return $this->value; + } + + /** + * Set old calculated value (cached) + * + * @param mixed $pValue Value + * @return PHPExcel_Cell + */ + public function setCalculatedValue($pValue = null) + { + if ($pValue !== null) { + $this->calculatedValue = (is_numeric($pValue)) ? (float) $pValue : $pValue; + } + + return $this->notifyCacheController(); + } + + /** + * Get old calculated value (cached) + * This returns the value last calculated by MS Excel or whichever spreadsheet program was used to + * create the original spreadsheet file. + * Note that this value is not guaranteed to refelect the actual calculated value because it is + * possible that auto-calculation was disabled in the original spreadsheet, and underlying data + * values used by the formula have changed since it was last calculated. + * + * @return mixed + */ + public function getOldCalculatedValue() + { + return $this->calculatedValue; + } + + /** + * Get cell data type + * + * @return string + */ + public function getDataType() + { + return $this->dataType; + } + + /** + * Set cell data type + * + * @param string $pDataType + * @return PHPExcel_Cell + */ + public function setDataType($pDataType = PHPExcel_Cell_DataType::TYPE_STRING) + { + if ($pDataType == PHPExcel_Cell_DataType::TYPE_STRING2) { + $pDataType = PHPExcel_Cell_DataType::TYPE_STRING; + } + $this->dataType = $pDataType; + + return $this->notifyCacheController(); + } + + /** + * Identify if the cell contains a formula + * + * @return boolean + */ + public function isFormula() + { + return $this->dataType == PHPExcel_Cell_DataType::TYPE_FORMULA; + } + + /** + * Does this cell contain Data validation rules? + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function hasDataValidation() + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot check for data validation when cell is not bound to a worksheet'); + } + + return $this->getWorksheet()->dataValidationExists($this->getCoordinate()); + } + + /** + * Get Data validation rules + * + * @return PHPExcel_Cell_DataValidation + * @throws PHPExcel_Exception + */ + public function getDataValidation() + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot get data validation for cell that is not bound to a worksheet'); + } + + return $this->getWorksheet()->getDataValidation($this->getCoordinate()); + } + + /** + * Set Data validation rules + * + * @param PHPExcel_Cell_DataValidation $pDataValidation + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setDataValidation(PHPExcel_Cell_DataValidation $pDataValidation = null) + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot set data validation for cell that is not bound to a worksheet'); + } + + $this->getWorksheet()->setDataValidation($this->getCoordinate(), $pDataValidation); + + return $this->notifyCacheController(); + } + + /** + * Does this cell contain a Hyperlink? + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function hasHyperlink() + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot check for hyperlink when cell is not bound to a worksheet'); + } + + return $this->getWorksheet()->hyperlinkExists($this->getCoordinate()); + } + + /** + * Get Hyperlink + * + * @return PHPExcel_Cell_Hyperlink + * @throws PHPExcel_Exception + */ + public function getHyperlink() + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot get hyperlink for cell that is not bound to a worksheet'); + } + + return $this->getWorksheet()->getHyperlink($this->getCoordinate()); + } + + /** + * Set Hyperlink + * + * @param PHPExcel_Cell_Hyperlink $pHyperlink + * @return PHPExcel_Cell + * @throws PHPExcel_Exception + */ + public function setHyperlink(PHPExcel_Cell_Hyperlink $pHyperlink = null) + { + if (!isset($this->parent)) { + throw new PHPExcel_Exception('Cannot set hyperlink for cell that is not bound to a worksheet'); + } + + $this->getWorksheet()->setHyperlink($this->getCoordinate(), $pHyperlink); + + return $this->notifyCacheController(); + } + + /** + * Get parent worksheet + * + * @return PHPExcel_CachedObjectStorage_CacheBase + */ + public function getParent() + { + return $this->parent; + } + + /** + * Get parent worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() + { + return $this->parent->getParent(); + } + + /** + * Is this cell in a merge range + * + * @return boolean + */ + public function isInMergeRange() + { + return (boolean) $this->getMergeRange(); + } + + /** + * Is this cell the master (top left cell) in a merge range (that holds the actual data value) + * + * @return boolean + */ + public function isMergeRangeValueCell() + { + if ($mergeRange = $this->getMergeRange()) { + $mergeRange = PHPExcel_Cell::splitRange($mergeRange); + list($startCell) = $mergeRange[0]; + if ($this->getCoordinate() === $startCell) { + return true; + } + } + return false; + } + + /** + * If this cell is in a merge range, then return the range + * + * @return string + */ + public function getMergeRange() + { + foreach ($this->getWorksheet()->getMergeCells() as $mergeRange) { + if ($this->isInRange($mergeRange)) { + return $mergeRange; + } + } + return false; + } + + /** + * Get cell style + * + * @return PHPExcel_Style + */ + public function getStyle() + { + return $this->getWorksheet()->getStyle($this->getCoordinate()); + } + + /** + * Re-bind parent + * + * @param PHPExcel_Worksheet $parent + * @return PHPExcel_Cell + */ + public function rebindParent(PHPExcel_Worksheet $parent) + { + $this->parent = $parent->getCellCacheController(); + + return $this->notifyCacheController(); + } + + /** + * Is cell in a specific range? + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return boolean + */ + public function isInRange($pRange = 'A1:A1') + { + list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange); + + // Translate properties + $myColumn = self::columnIndexFromString($this->getColumn()); + $myRow = $this->getRow(); + + // Verify if cell is in range + return (($rangeStart[0] <= $myColumn) && ($rangeEnd[0] >= $myColumn) && + ($rangeStart[1] <= $myRow) && ($rangeEnd[1] >= $myRow) + ); + } + + /** + * Coordinate from string + * + * @param string $pCoordinateString + * @return array Array containing column and row (indexes 0 and 1) + * @throws PHPExcel_Exception + */ + public static function coordinateFromString($pCoordinateString = 'A1') + { + if (preg_match("/^([$]?[A-Z]{1,3})([$]?\d{1,7})$/", $pCoordinateString, $matches)) { + return array($matches[1],$matches[2]); + } elseif ((strpos($pCoordinateString, ':') !== false) || (strpos($pCoordinateString, ',') !== false)) { + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } elseif ($pCoordinateString == '') { + throw new PHPExcel_Exception('Cell coordinate can not be zero-length string'); + } + + throw new PHPExcel_Exception('Invalid cell coordinate '.$pCoordinateString); + } + + /** + * Make string row, column or cell coordinate absolute + * + * @param string $pCoordinateString e.g. 'A' or '1' or 'A1' + * Note that this value can be a row or column reference as well as a cell reference + * @return string Absolute coordinate e.g. '$A' or '$1' or '$A$1' + * @throws PHPExcel_Exception + */ + public static function absoluteReference($pCoordinateString = 'A1') + { + if (strpos($pCoordinateString, ':') === false && strpos($pCoordinateString, ',') === false) { + // Split out any worksheet name from the reference + $worksheet = ''; + $cellAddress = explode('!', $pCoordinateString); + if (count($cellAddress) > 1) { + list($worksheet, $pCoordinateString) = $cellAddress; + } + if ($worksheet > '') { + $worksheet .= '!'; + } + + // Create absolute coordinate + if (ctype_digit($pCoordinateString)) { + return $worksheet . '$' . $pCoordinateString; + } elseif (ctype_alpha($pCoordinateString)) { + return $worksheet . '$' . strtoupper($pCoordinateString); + } + return $worksheet . self::absoluteCoordinate($pCoordinateString); + } + + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } + + /** + * Make string coordinate absolute + * + * @param string $pCoordinateString e.g. 'A1' + * @return string Absolute coordinate e.g. '$A$1' + * @throws PHPExcel_Exception + */ + public static function absoluteCoordinate($pCoordinateString = 'A1') + { + if (strpos($pCoordinateString, ':') === false && strpos($pCoordinateString, ',') === false) { + // Split out any worksheet name from the coordinate + $worksheet = ''; + $cellAddress = explode('!', $pCoordinateString); + if (count($cellAddress) > 1) { + list($worksheet, $pCoordinateString) = $cellAddress; + } + if ($worksheet > '') { + $worksheet .= '!'; + } + + // Create absolute coordinate + list($column, $row) = self::coordinateFromString($pCoordinateString); + $column = ltrim($column, '$'); + $row = ltrim($row, '$'); + return $worksheet . '$' . $column . '$' . $row; + } + + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells'); + } + + /** + * Split range into coordinate strings + * + * @param string $pRange e.g. 'B4:D9' or 'B4:D9,H2:O11' or 'B4' + * @return array Array containg one or more arrays containing one or two coordinate strings + * e.g. array('B4','D9') or array(array('B4','D9'),array('H2','O11')) + * or array('B4') + */ + public static function splitRange($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if (empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + $exploded = explode(',', $pRange); + $counter = count($exploded); + for ($i = 0; $i < $counter; ++$i) { + $exploded[$i] = explode(':', $exploded[$i]); + } + return $exploded; + } + + /** + * Build range from coordinate strings + * + * @param array $pRange Array containg one or more arrays containing one or two coordinate strings + * @return string String representation of $pRange + * @throws PHPExcel_Exception + */ + public static function buildRange($pRange) + { + // Verify range + if (!is_array($pRange) || empty($pRange) || !is_array($pRange[0])) { + throw new PHPExcel_Exception('Range does not contain any information'); + } + + // Build range + $imploded = array(); + $counter = count($pRange); + for ($i = 0; $i < $counter; ++$i) { + $pRange[$i] = implode(':', $pRange[$i]); + } + $imploded = implode(',', $pRange); + + return $imploded; + } + + /** + * Calculate range boundaries + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range coordinates array(Start Cell, End Cell) + * where Start Cell and End Cell are arrays (Column Number, Row Number) + */ + public static function rangeBoundaries($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if (empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Extract range + if (strpos($pRange, ':') === false) { + $rangeA = $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + // Calculate range outer borders + $rangeStart = self::coordinateFromString($rangeA); + $rangeEnd = self::coordinateFromString($rangeB); + + // Translate column into index + $rangeStart[0] = self::columnIndexFromString($rangeStart[0]); + $rangeEnd[0] = self::columnIndexFromString($rangeEnd[0]); + + return array($rangeStart, $rangeEnd); + } + + /** + * Calculate range dimension + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range dimension (width, height) + */ + public static function rangeDimension($pRange = 'A1:A1') + { + // Calculate range outer borders + list($rangeStart, $rangeEnd) = self::rangeBoundaries($pRange); + + return array( ($rangeEnd[0] - $rangeStart[0] + 1), ($rangeEnd[1] - $rangeStart[1] + 1) ); + } + + /** + * Calculate range boundaries + * + * @param string $pRange Cell range (e.g. A1:A1) + * @return array Range coordinates array(Start Cell, End Cell) + * where Start Cell and End Cell are arrays (Column ID, Row Number) + */ + public static function getRangeBoundaries($pRange = 'A1:A1') + { + // Ensure $pRange is a valid range + if (empty($pRange)) { + $pRange = self::DEFAULT_RANGE; + } + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Extract range + if (strpos($pRange, ':') === false) { + $rangeA = $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + return array( self::coordinateFromString($rangeA), self::coordinateFromString($rangeB)); + } + + /** + * Column index from string + * + * @param string $pString + * @return int Column index (base 1 !!!) + */ + public static function columnIndexFromString($pString = 'A') + { + // Using a lookup cache adds a slight memory overhead, but boosts speed + // caching using a static within the method is faster than a class static, + // though it's additional memory overhead + static $_indexCache = array(); + + if (isset($_indexCache[$pString])) { + return $_indexCache[$pString]; + } + // It's surprising how costly the strtoupper() and ord() calls actually are, so we use a lookup array rather than use ord() + // and make it case insensitive to get rid of the strtoupper() as well. Because it's a static, there's no significant + // memory overhead either + static $_columnLookup = array( + 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, + 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26, + 'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7, 'h' => 8, 'i' => 9, 'j' => 10, 'k' => 11, 'l' => 12, 'm' => 13, + 'n' => 14, 'o' => 15, 'p' => 16, 'q' => 17, 'r' => 18, 's' => 19, 't' => 20, 'u' => 21, 'v' => 22, 'w' => 23, 'x' => 24, 'y' => 25, 'z' => 26 + ); + + // We also use the language construct isset() rather than the more costly strlen() function to match the length of $pString + // for improved performance + if (isset($pString{0})) { + if (!isset($pString{1})) { + $_indexCache[$pString] = $_columnLookup[$pString]; + return $_indexCache[$pString]; + } elseif (!isset($pString{2})) { + $_indexCache[$pString] = $_columnLookup[$pString{0}] * 26 + $_columnLookup[$pString{1}]; + return $_indexCache[$pString]; + } elseif (!isset($pString{3})) { + $_indexCache[$pString] = $_columnLookup[$pString{0}] * 676 + $_columnLookup[$pString{1}] * 26 + $_columnLookup[$pString{2}]; + return $_indexCache[$pString]; + } + } + throw new PHPExcel_Exception("Column string index can not be " . ((isset($pString{0})) ? "longer than 3 characters" : "empty")); + } + + /** + * String from columnindex + * + * @param int $pColumnIndex Column index (base 0 !!!) + * @return string + */ + public static function stringFromColumnIndex($pColumnIndex = 0) + { + // Using a lookup cache adds a slight memory overhead, but boosts speed + // caching using a static within the method is faster than a class static, + // though it's additional memory overhead + static $_indexCache = array(); + + if (!isset($_indexCache[$pColumnIndex])) { + // Determine column string + if ($pColumnIndex < 26) { + $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex); + } elseif ($pColumnIndex < 702) { + $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . + chr(65 + $pColumnIndex % 26); + } else { + $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . + chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . + chr(65 + $pColumnIndex % 26); + } + } + return $_indexCache[$pColumnIndex]; + } + + /** + * Extract all cell references in range + * + * @param string $pRange Range (e.g. A1 or A1:C10 or A1:E10 A20:E25) + * @return array Array containing single cell references + */ + public static function extractAllCellReferencesInRange($pRange = 'A1') + { + // Returnvalue + $returnValue = array(); + + // Explode spaces + $cellBlocks = explode(' ', str_replace('$', '', strtoupper($pRange))); + foreach ($cellBlocks as $cellBlock) { + // Single cell? + if (strpos($cellBlock, ':') === false && strpos($cellBlock, ',') === false) { + $returnValue[] = $cellBlock; + continue; + } + + // Range... + $ranges = self::splitRange($cellBlock); + foreach ($ranges as $range) { + // Single cell? + if (!isset($range[1])) { + $returnValue[] = $range[0]; + continue; + } + + // Range... + list($rangeStart, $rangeEnd) = $range; + sscanf($rangeStart, '%[A-Z]%d', $startCol, $startRow); + sscanf($rangeEnd, '%[A-Z]%d', $endCol, $endRow); + ++$endCol; + + // Current data + $currentCol = $startCol; + $currentRow = $startRow; + + // Loop cells + while ($currentCol != $endCol) { + while ($currentRow <= $endRow) { + $returnValue[] = $currentCol.$currentRow; + ++$currentRow; + } + ++$currentCol; + $currentRow = $startRow; + } + } + } + + // Sort the result by column and row + $sortKeys = array(); + foreach (array_unique($returnValue) as $coord) { + sscanf($coord, '%[A-Z]%d', $column, $row); + $sortKeys[sprintf('%3s%09d', $column, $row)] = $coord; + } + ksort($sortKeys); + + // Return value + return array_values($sortKeys); + } + + /** + * Compare 2 cells + * + * @param PHPExcel_Cell $a Cell a + * @param PHPExcel_Cell $b Cell b + * @return int Result of comparison (always -1 or 1, never zero!) + */ + public static function compareCells(PHPExcel_Cell $a, PHPExcel_Cell $b) + { + if ($a->getRow() < $b->getRow()) { + return -1; + } elseif ($a->getRow() > $b->getRow()) { + return 1; + } elseif (self::columnIndexFromString($a->getColumn()) < self::columnIndexFromString($b->getColumn())) { + return -1; + } else { + return 1; + } + } + + /** + * Get value binder to use + * + * @return PHPExcel_Cell_IValueBinder + */ + public static function getValueBinder() + { + if (self::$valueBinder === null) { + self::$valueBinder = new PHPExcel_Cell_DefaultValueBinder(); + } + + return self::$valueBinder; + } + + /** + * Set value binder to use + * + * @param PHPExcel_Cell_IValueBinder $binder + * @throws PHPExcel_Exception + */ + public static function setValueBinder(PHPExcel_Cell_IValueBinder $binder = null) + { + if ($binder === null) { + throw new PHPExcel_Exception("A PHPExcel_Cell_IValueBinder is required for PHPExcel to function correctly."); + } + + self::$valueBinder = $binder; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != 'parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + /** + * Get index to cellXf + * + * @return int + */ + public function getXfIndex() + { + return $this->xfIndex; + } + + /** + * Set index to cellXf + * + * @param int $pValue + * @return PHPExcel_Cell + */ + public function setXfIndex($pValue = 0) + { + $this->xfIndex = $pValue; + + return $this->notifyCacheController(); + } + + /** + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + */ + public function setFormulaAttributes($pAttributes) + { + $this->formulaAttributes = $pAttributes; + return $this; + } + + /** + * @deprecated Since version 1.7.8 for planned changes to cell for array formula handling + */ + public function getFormulaAttributes() + { + return $this->formulaAttributes; + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() + { + return (string) $this->getValue(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/AdvancedValueBinder.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/AdvancedValueBinder.php new file mode 100644 index 00000000..061d04eb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/AdvancedValueBinder.php @@ -0,0 +1,187 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Cell_AdvancedValueBinder + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell_AdvancedValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder +{ + /** + * Bind value to a cell + * + * @param PHPExcel_Cell $cell Cell to bind value to + * @param mixed $value Value to bind in cell + * @return boolean + */ + public function bindValue(PHPExcel_Cell $cell, $value = null) + { + // sanitize UTF-8 strings + if (is_string($value)) { + $value = PHPExcel_Shared_String::SanitizeUTF8($value); + } + + // Find out data type + $dataType = parent::dataTypeForValue($value); + + // Style logic - strings + if ($dataType === PHPExcel_Cell_DataType::TYPE_STRING && !$value instanceof PHPExcel_RichText) { + // Test for booleans using locale-setting + if ($value == PHPExcel_Calculation::getTRUE()) { + $cell->setValueExplicit(true, PHPExcel_Cell_DataType::TYPE_BOOL); + return true; + } elseif ($value == PHPExcel_Calculation::getFALSE()) { + $cell->setValueExplicit(false, PHPExcel_Cell_DataType::TYPE_BOOL); + return true; + } + + // Check for number in scientific format + if (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NUMBER.'$/', $value)) { + $cell->setValueExplicit((float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + return true; + } + + // Check for fraction + if (preg_match('/^([+-]?)\s*([0-9]+)\s?\/\s*([0-9]+)$/', $value, $matches)) { + // Convert value to number + $value = $matches[2] / $matches[3]; + if ($matches[1] == '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode('??/??'); + return true; + } elseif (preg_match('/^([+-]?)([0-9]*) +([0-9]*)\s?\/\s*([0-9]*)$/', $value, $matches)) { + // Convert value to number + $value = $matches[2] + ($matches[3] / $matches[4]); + if ($matches[1] == '-') { + $value = 0 - $value; + } + $cell->setValueExplicit((float) $value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode('# ??/??'); + return true; + } + + // Check for percentage + if (preg_match('/^\-?[0-9]*\.?[0-9]*\s?\%$/', $value)) { + // Convert value to number + $value = (float) str_replace('%', '', $value) / 100; + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00); + return true; + } + + // Check for currency + $currencyCode = PHPExcel_Shared_String::getCurrencyCode(); + $decimalSeparator = PHPExcel_Shared_String::getDecimalSeparator(); + $thousandsSeparator = PHPExcel_Shared_String::getThousandsSeparator(); + if (preg_match('/^'.preg_quote($currencyCode).' *(\d{1,3}('.preg_quote($thousandsSeparator).'\d{3})*|(\d+))('.preg_quote($decimalSeparator).'\d{2})?$/', $value)) { + // Convert value to number + $value = (float) trim(str_replace(array($currencyCode, $thousandsSeparator, $decimalSeparator), array('', '', '.'), $value)); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode( + str_replace('$', $currencyCode, PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE) + ); + return true; + } elseif (preg_match('/^\$ *(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/', $value)) { + // Convert value to number + $value = (float) trim(str_replace(array('$',','), '', $value)); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE); + return true; + } + + // Check for time without seconds e.g. '9:45', '09:45' + if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d$/', $value)) { + // Convert value to number + list($h, $m) = explode(':', $value); + $days = $h / 24 + $m / 1440; + $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3); + return true; + } + + // Check for time with seconds '9:45:59', '09:45:59' + if (preg_match('/^(\d|[0-1]\d|2[0-3]):[0-5]\d:[0-5]\d$/', $value)) { + // Convert value to number + list($h, $m, $s) = explode(':', $value); + $days = $h / 24 + $m / 1440 + $s / 86400; + // Convert value to number + $cell->setValueExplicit($days, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4); + return true; + } + + // Check for datetime, e.g. '2008-12-31', '2008-12-31 15:59', '2008-12-31 15:59:10' + if (($d = PHPExcel_Shared_Date::stringToExcel($value)) !== false) { + // Convert value to number + $cell->setValueExplicit($d, PHPExcel_Cell_DataType::TYPE_NUMERIC); + // Determine style. Either there is a time part or not. Look for ':' + if (strpos($value, ':') !== false) { + $formatCode = 'yyyy-mm-dd h:mm'; + } else { + $formatCode = 'yyyy-mm-dd'; + } + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getNumberFormat()->setFormatCode($formatCode); + return true; + } + + // Check for newline character "\n" + if (strpos($value, "\n") !== false) { + $value = PHPExcel_Shared_String::SanitizeUTF8($value); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); + // Set style + $cell->getWorksheet()->getStyle($cell->getCoordinate()) + ->getAlignment()->setWrapText(true); + return true; + } + } + + // Not bound yet? Use parent... + return parent::bindValue($cell, $value); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataType.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataType.php new file mode 100644 index 00000000..fc010e65 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataType.php @@ -0,0 +1,115 @@ +<?php + +/** + * PHPExcel_Cell_DataType + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell_DataType +{ + /* Data types */ + const TYPE_STRING2 = 'str'; + const TYPE_STRING = 's'; + const TYPE_FORMULA = 'f'; + const TYPE_NUMERIC = 'n'; + const TYPE_BOOL = 'b'; + const TYPE_NULL = 'null'; + const TYPE_INLINE = 'inlineStr'; + const TYPE_ERROR = 'e'; + + /** + * List of error codes + * + * @var array + */ + private static $errorCodes = array( + '#NULL!' => 0, + '#DIV/0!' => 1, + '#VALUE!' => 2, + '#REF!' => 3, + '#NAME?' => 4, + '#NUM!' => 5, + '#N/A' => 6 + ); + + /** + * Get list of error codes + * + * @return array + */ + public static function getErrorCodes() + { + return self::$errorCodes; + } + + /** + * DataType for value + * + * @deprecated Replaced by PHPExcel_Cell_IValueBinder infrastructure, will be removed in version 1.8.0 + * @param mixed $pValue + * @return string + */ + public static function dataTypeForValue($pValue = null) + { + return PHPExcel_Cell_DefaultValueBinder::dataTypeForValue($pValue); + } + + /** + * Check a string that it satisfies Excel requirements + * + * @param mixed Value to sanitize to an Excel string + * @return mixed Sanitized value + */ + public static function checkString($pValue = null) + { + if ($pValue instanceof PHPExcel_RichText) { + // TODO: Sanitize Rich-Text string (max. character count is 32,767) + return $pValue; + } + + // string must never be longer than 32,767 characters, truncate if necessary + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 32767); + + // we require that newline is represented as "\n" in core, not as "\r\n" or "\r" + $pValue = str_replace(array("\r\n", "\r"), "\n", $pValue); + + return $pValue; + } + + /** + * Check a value that it is a valid error code + * + * @param mixed Value to sanitize to an Excel error code + * @return string Sanitized value + */ + public static function checkErrorCode($pValue = null) + { + $pValue = (string) $pValue; + + if (!array_key_exists($pValue, self::$errorCodes)) { + $pValue = '#NULL!'; + } + + return $pValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataValidation.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataValidation.php new file mode 100644 index 00000000..9883633e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DataValidation.php @@ -0,0 +1,492 @@ +<?php + +/** + * PHPExcel_Cell_DataValidation + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell_DataValidation +{ + /* Data validation types */ + const TYPE_NONE = 'none'; + const TYPE_CUSTOM = 'custom'; + const TYPE_DATE = 'date'; + const TYPE_DECIMAL = 'decimal'; + const TYPE_LIST = 'list'; + const TYPE_TEXTLENGTH = 'textLength'; + const TYPE_TIME = 'time'; + const TYPE_WHOLE = 'whole'; + + /* Data validation error styles */ + const STYLE_STOP = 'stop'; + const STYLE_WARNING = 'warning'; + const STYLE_INFORMATION = 'information'; + + /* Data validation operators */ + const OPERATOR_BETWEEN = 'between'; + const OPERATOR_EQUAL = 'equal'; + const OPERATOR_GREATERTHAN = 'greaterThan'; + const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const OPERATOR_LESSTHAN = 'lessThan'; + const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; + const OPERATOR_NOTBETWEEN = 'notBetween'; + const OPERATOR_NOTEQUAL = 'notEqual'; + + /** + * Formula 1 + * + * @var string + */ + private $formula1; + + /** + * Formula 2 + * + * @var string + */ + private $formula2; + + /** + * Type + * + * @var string + */ + private $type = PHPExcel_Cell_DataValidation::TYPE_NONE; + + /** + * Error style + * + * @var string + */ + private $errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; + + /** + * Operator + * + * @var string + */ + private $operator; + + /** + * Allow Blank + * + * @var boolean + */ + private $allowBlank; + + /** + * Show DropDown + * + * @var boolean + */ + private $showDropDown; + + /** + * Show InputMessage + * + * @var boolean + */ + private $showInputMessage; + + /** + * Show ErrorMessage + * + * @var boolean + */ + private $showErrorMessage; + + /** + * Error title + * + * @var string + */ + private $errorTitle; + + /** + * Error + * + * @var string + */ + private $error; + + /** + * Prompt title + * + * @var string + */ + private $promptTitle; + + /** + * Prompt + * + * @var string + */ + private $prompt; + + /** + * Create a new PHPExcel_Cell_DataValidation + */ + public function __construct() + { + // Initialise member variables + $this->formula1 = ''; + $this->formula2 = ''; + $this->type = PHPExcel_Cell_DataValidation::TYPE_NONE; + $this->errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; + $this->operator = ''; + $this->allowBlank = false; + $this->showDropDown = false; + $this->showInputMessage = false; + $this->showErrorMessage = false; + $this->errorTitle = ''; + $this->error = ''; + $this->promptTitle = ''; + $this->prompt = ''; + } + + /** + * Get Formula 1 + * + * @return string + */ + public function getFormula1() + { + return $this->formula1; + } + + /** + * Set Formula 1 + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setFormula1($value = '') + { + $this->formula1 = $value; + return $this; + } + + /** + * Get Formula 2 + * + * @return string + */ + public function getFormula2() + { + return $this->formula2; + } + + /** + * Set Formula 2 + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setFormula2($value = '') + { + $this->formula2 = $value; + return $this; + } + + /** + * Get Type + * + * @return string + */ + public function getType() + { + return $this->type; + } + + /** + * Set Type + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setType($value = PHPExcel_Cell_DataValidation::TYPE_NONE) + { + $this->type = $value; + return $this; + } + + /** + * Get Error style + * + * @return string + */ + public function getErrorStyle() + { + return $this->errorStyle; + } + + /** + * Set Error style + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setErrorStyle($value = PHPExcel_Cell_DataValidation::STYLE_STOP) + { + $this->errorStyle = $value; + return $this; + } + + /** + * Get Operator + * + * @return string + */ + public function getOperator() + { + return $this->operator; + } + + /** + * Set Operator + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setOperator($value = '') + { + $this->operator = $value; + return $this; + } + + /** + * Get Allow Blank + * + * @return boolean + */ + public function getAllowBlank() + { + return $this->allowBlank; + } + + /** + * Set Allow Blank + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setAllowBlank($value = false) + { + $this->allowBlank = $value; + return $this; + } + + /** + * Get Show DropDown + * + * @return boolean + */ + public function getShowDropDown() + { + return $this->showDropDown; + } + + /** + * Set Show DropDown + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowDropDown($value = false) + { + $this->showDropDown = $value; + return $this; + } + + /** + * Get Show InputMessage + * + * @return boolean + */ + public function getShowInputMessage() + { + return $this->showInputMessage; + } + + /** + * Set Show InputMessage + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowInputMessage($value = false) + { + $this->showInputMessage = $value; + return $this; + } + + /** + * Get Show ErrorMessage + * + * @return boolean + */ + public function getShowErrorMessage() + { + return $this->showErrorMessage; + } + + /** + * Set Show ErrorMessage + * + * @param boolean $value + * @return PHPExcel_Cell_DataValidation + */ + public function setShowErrorMessage($value = false) + { + $this->showErrorMessage = $value; + return $this; + } + + /** + * Get Error title + * + * @return string + */ + public function getErrorTitle() + { + return $this->errorTitle; + } + + /** + * Set Error title + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setErrorTitle($value = '') + { + $this->errorTitle = $value; + return $this; + } + + /** + * Get Error + * + * @return string + */ + public function getError() + { + return $this->error; + } + + /** + * Set Error + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setError($value = '') + { + $this->error = $value; + return $this; + } + + /** + * Get Prompt title + * + * @return string + */ + public function getPromptTitle() + { + return $this->promptTitle; + } + + /** + * Set Prompt title + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setPromptTitle($value = '') + { + $this->promptTitle = $value; + return $this; + } + + /** + * Get Prompt + * + * @return string + */ + public function getPrompt() + { + return $this->prompt; + } + + /** + * Set Prompt + * + * @param string $value + * @return PHPExcel_Cell_DataValidation + */ + public function setPrompt($value = '') + { + $this->prompt = $value; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->formula1 . + $this->formula2 . + $this->type = PHPExcel_Cell_DataValidation::TYPE_NONE . + $this->errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP . + $this->operator . + ($this->allowBlank ? 't' : 'f') . + ($this->showDropDown ? 't' : 'f') . + ($this->showInputMessage ? 't' : 'f') . + ($this->showErrorMessage ? 't' : 'f') . + $this->errorTitle . + $this->error . + $this->promptTitle . + $this->prompt . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DefaultValueBinder.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DefaultValueBinder.php new file mode 100644 index 00000000..dc19e6c4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/DefaultValueBinder.php @@ -0,0 +1,102 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Cell_DefaultValueBinder + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder +{ + /** + * Bind value to a cell + * + * @param PHPExcel_Cell $cell Cell to bind value to + * @param mixed $value Value to bind in cell + * @return boolean + */ + public function bindValue(PHPExcel_Cell $cell, $value = null) + { + // sanitize UTF-8 strings + if (is_string($value)) { + $value = PHPExcel_Shared_String::SanitizeUTF8($value); + } elseif (is_object($value)) { + // Handle any objects that might be injected + if ($value instanceof DateTime) { + $value = $value->format('Y-m-d H:i:s'); + } elseif (!($value instanceof PHPExcel_RichText)) { + $value = (string) $value; + } + } + + // Set value explicit + $cell->setValueExplicit($value, self::dataTypeForValue($value)); + + // Done! + return true; + } + + /** + * DataType for value + * + * @param mixed $pValue + * @return string + */ + public static function dataTypeForValue($pValue = null) + { + // Match the value against a few data types + if ($pValue === null) { + return PHPExcel_Cell_DataType::TYPE_NULL; + } elseif ($pValue === '') { + return PHPExcel_Cell_DataType::TYPE_STRING; + } elseif ($pValue instanceof PHPExcel_RichText) { + return PHPExcel_Cell_DataType::TYPE_INLINE; + } elseif ($pValue{0} === '=' && strlen($pValue) > 1) { + return PHPExcel_Cell_DataType::TYPE_FORMULA; + } elseif (is_bool($pValue)) { + return PHPExcel_Cell_DataType::TYPE_BOOL; + } elseif (is_float($pValue) || is_int($pValue)) { + return PHPExcel_Cell_DataType::TYPE_NUMERIC; + } elseif (preg_match('/^[\+\-]?([0-9]+\\.?[0-9]*|[0-9]*\\.?[0-9]+)([Ee][\-\+]?[0-2]?\d{1,3})?$/', $pValue)) { + $tValue = ltrim($pValue, '+-'); + if (is_string($pValue) && $tValue{0} === '0' && strlen($tValue) > 1 && $tValue{1} !== '.') { + return PHPExcel_Cell_DataType::TYPE_STRING; + } elseif ((strpos($pValue, '.') === false) && ($pValue > PHP_INT_MAX)) { + return PHPExcel_Cell_DataType::TYPE_STRING; + } + return PHPExcel_Cell_DataType::TYPE_NUMERIC; + } elseif (is_string($pValue) && array_key_exists($pValue, PHPExcel_Cell_DataType::getErrorCodes())) { + return PHPExcel_Cell_DataType::TYPE_ERROR; + } + + return PHPExcel_Cell_DataType::TYPE_STRING; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/Hyperlink.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/Hyperlink.php new file mode 100644 index 00000000..daab54c8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/Hyperlink.php @@ -0,0 +1,124 @@ +<?php + +/** + * PHPExcel_Cell_Hyperlink + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Cell_Hyperlink +{ + /** + * URL to link the cell to + * + * @var string + */ + private $url; + + /** + * Tooltip to display on the hyperlink + * + * @var string + */ + private $tooltip; + + /** + * Create a new PHPExcel_Cell_Hyperlink + * + * @param string $pUrl Url to link the cell to + * @param string $pTooltip Tooltip to display on the hyperlink + */ + public function __construct($pUrl = '', $pTooltip = '') + { + // Initialise member variables + $this->url = $pUrl; + $this->tooltip = $pTooltip; + } + + /** + * Get URL + * + * @return string + */ + public function getUrl() + { + return $this->url; + } + + /** + * Set URL + * + * @param string $value + * @return PHPExcel_Cell_Hyperlink + */ + public function setUrl($value = '') + { + $this->url = $value; + return $this; + } + + /** + * Get tooltip + * + * @return string + */ + public function getTooltip() + { + return $this->tooltip; + } + + /** + * Set tooltip + * + * @param string $value + * @return PHPExcel_Cell_Hyperlink + */ + public function setTooltip($value = '') + { + $this->tooltip = $value; + return $this; + } + + /** + * Is this hyperlink internal? (to another worksheet) + * + * @return boolean + */ + public function isInternal() + { + return strpos($this->url, 'sheet://') !== false; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->url . + $this->tooltip . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/IValueBinder.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/IValueBinder.php new file mode 100644 index 00000000..de2d0ac0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Cell/IValueBinder.php @@ -0,0 +1,47 @@ +<?php + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Cell_IValueBinder + * + * @category PHPExcel + * @package PHPExcel_Cell + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +interface PHPExcel_Cell_IValueBinder +{ + /** + * Bind value to a cell + * + * @param PHPExcel_Cell $cell Cell to bind value to + * @param mixed $value Value to bind in cell + * @return boolean + */ + public function bindValue(PHPExcel_Cell $cell, $value = null); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart.php new file mode 100644 index 00000000..d7799935 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart.php @@ -0,0 +1,680 @@ +<?php + +/** + * PHPExcel_Chart + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart +{ + /** + * Chart Name + * + * @var string + */ + private $name = ''; + + /** + * Worksheet + * + * @var PHPExcel_Worksheet + */ + private $worksheet; + + /** + * Chart Title + * + * @var PHPExcel_Chart_Title + */ + private $title; + + /** + * Chart Legend + * + * @var PHPExcel_Chart_Legend + */ + private $legend; + + /** + * X-Axis Label + * + * @var PHPExcel_Chart_Title + */ + private $xAxisLabel; + + /** + * Y-Axis Label + * + * @var PHPExcel_Chart_Title + */ + private $yAxisLabel; + + /** + * Chart Plot Area + * + * @var PHPExcel_Chart_PlotArea + */ + private $plotArea; + + /** + * Plot Visible Only + * + * @var boolean + */ + private $plotVisibleOnly = true; + + /** + * Display Blanks as + * + * @var string + */ + private $displayBlanksAs = '0'; + + /** + * Chart Asix Y as + * + * @var PHPExcel_Chart_Axis + */ + private $yAxis; + + /** + * Chart Asix X as + * + * @var PHPExcel_Chart_Axis + */ + private $xAxis; + + /** + * Chart Major Gridlines as + * + * @var PHPExcel_Chart_GridLines + */ + private $majorGridlines; + + /** + * Chart Minor Gridlines as + * + * @var PHPExcel_Chart_GridLines + */ + private $minorGridlines; + + /** + * Top-Left Cell Position + * + * @var string + */ + private $topLeftCellRef = 'A1'; + + + /** + * Top-Left X-Offset + * + * @var integer + */ + private $topLeftXOffset = 0; + + + /** + * Top-Left Y-Offset + * + * @var integer + */ + private $topLeftYOffset = 0; + + + /** + * Bottom-Right Cell Position + * + * @var string + */ + private $bottomRightCellRef = 'A1'; + + + /** + * Bottom-Right X-Offset + * + * @var integer + */ + private $bottomRightXOffset = 10; + + + /** + * Bottom-Right Y-Offset + * + * @var integer + */ + private $bottomRightYOffset = 10; + + + /** + * Create a new PHPExcel_Chart + */ + public function __construct($name, PHPExcel_Chart_Title $title = null, PHPExcel_Chart_Legend $legend = null, PHPExcel_Chart_PlotArea $plotArea = null, $plotVisibleOnly = true, $displayBlanksAs = '0', PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, PHPExcel_Chart_Axis $xAxis = null, PHPExcel_Chart_Axis $yAxis = null, PHPExcel_Chart_GridLines $majorGridlines = null, PHPExcel_Chart_GridLines $minorGridlines = null) + { + $this->name = $name; + $this->title = $title; + $this->legend = $legend; + $this->xAxisLabel = $xAxisLabel; + $this->yAxisLabel = $yAxisLabel; + $this->plotArea = $plotArea; + $this->plotVisibleOnly = $plotVisibleOnly; + $this->displayBlanksAs = $displayBlanksAs; + $this->xAxis = $xAxis; + $this->yAxis = $yAxis; + $this->majorGridlines = $majorGridlines; + $this->minorGridlines = $minorGridlines; + } + + /** + * Get Name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Get Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() + { + return $this->worksheet; + } + + /** + * Set Worksheet + * + * @param PHPExcel_Worksheet $pValue + * @throws PHPExcel_Chart_Exception + * @return PHPExcel_Chart + */ + public function setWorksheet(PHPExcel_Worksheet $pValue = null) + { + $this->worksheet = $pValue; + + return $this; + } + + /** + * Get Title + * + * @return PHPExcel_Chart_Title + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Title + * + * @param PHPExcel_Chart_Title $title + * @return PHPExcel_Chart + */ + public function setTitle(PHPExcel_Chart_Title $title) + { + $this->title = $title; + + return $this; + } + + /** + * Get Legend + * + * @return PHPExcel_Chart_Legend + */ + public function getLegend() + { + return $this->legend; + } + + /** + * Set Legend + * + * @param PHPExcel_Chart_Legend $legend + * @return PHPExcel_Chart + */ + public function setLegend(PHPExcel_Chart_Legend $legend) + { + $this->legend = $legend; + + return $this; + } + + /** + * Get X-Axis Label + * + * @return PHPExcel_Chart_Title + */ + public function getXAxisLabel() + { + return $this->xAxisLabel; + } + + /** + * Set X-Axis Label + * + * @param PHPExcel_Chart_Title $label + * @return PHPExcel_Chart + */ + public function setXAxisLabel(PHPExcel_Chart_Title $label) + { + $this->xAxisLabel = $label; + + return $this; + } + + /** + * Get Y-Axis Label + * + * @return PHPExcel_Chart_Title + */ + public function getYAxisLabel() + { + return $this->yAxisLabel; + } + + /** + * Set Y-Axis Label + * + * @param PHPExcel_Chart_Title $label + * @return PHPExcel_Chart + */ + public function setYAxisLabel(PHPExcel_Chart_Title $label) + { + $this->yAxisLabel = $label; + + return $this; + } + + /** + * Get Plot Area + * + * @return PHPExcel_Chart_PlotArea + */ + public function getPlotArea() + { + return $this->plotArea; + } + + /** + * Get Plot Visible Only + * + * @return boolean + */ + public function getPlotVisibleOnly() + { + return $this->plotVisibleOnly; + } + + /** + * Set Plot Visible Only + * + * @param boolean $plotVisibleOnly + * @return PHPExcel_Chart + */ + public function setPlotVisibleOnly($plotVisibleOnly = true) + { + $this->plotVisibleOnly = $plotVisibleOnly; + + return $this; + } + + /** + * Get Display Blanks as + * + * @return string + */ + public function getDisplayBlanksAs() + { + return $this->displayBlanksAs; + } + + /** + * Set Display Blanks as + * + * @param string $displayBlanksAs + * @return PHPExcel_Chart + */ + public function setDisplayBlanksAs($displayBlanksAs = '0') + { + $this->displayBlanksAs = $displayBlanksAs; + } + + + /** + * Get yAxis + * + * @return PHPExcel_Chart_Axis + */ + public function getChartAxisY() + { + if ($this->yAxis !== null) { + return $this->yAxis; + } + + return new PHPExcel_Chart_Axis(); + } + + /** + * Get xAxis + * + * @return PHPExcel_Chart_Axis + */ + public function getChartAxisX() + { + if ($this->xAxis !== null) { + return $this->xAxis; + } + + return new PHPExcel_Chart_Axis(); + } + + /** + * Get Major Gridlines + * + * @return PHPExcel_Chart_GridLines + */ + public function getMajorGridlines() + { + if ($this->majorGridlines !== null) { + return $this->majorGridlines; + } + + return new PHPExcel_Chart_GridLines(); + } + + /** + * Get Minor Gridlines + * + * @return PHPExcel_Chart_GridLines + */ + public function getMinorGridlines() + { + if ($this->minorGridlines !== null) { + return $this->minorGridlines; + } + + return new PHPExcel_Chart_GridLines(); + } + + + /** + * Set the Top Left position for the chart + * + * @param string $cell + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setTopLeftPosition($cell, $xOffset = null, $yOffset = null) + { + $this->topLeftCellRef = $cell; + if (!is_null($xOffset)) { + $this->setTopLeftXOffset($xOffset); + } + if (!is_null($yOffset)) { + $this->setTopLeftYOffset($yOffset); + } + + return $this; + } + + /** + * Get the top left position of the chart + * + * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + */ + public function getTopLeftPosition() + { + return array( + 'cell' => $this->topLeftCellRef, + 'xOffset' => $this->topLeftXOffset, + 'yOffset' => $this->topLeftYOffset + ); + } + + /** + * Get the cell address where the top left of the chart is fixed + * + * @return string + */ + public function getTopLeftCell() + { + return $this->topLeftCellRef; + } + + /** + * Set the Top Left cell position for the chart + * + * @param string $cell + * @return PHPExcel_Chart + */ + public function setTopLeftCell($cell) + { + $this->topLeftCellRef = $cell; + + return $this; + } + + /** + * Set the offset position within the Top Left cell for the chart + * + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setTopLeftOffset($xOffset = null, $yOffset = null) + { + if (!is_null($xOffset)) { + $this->setTopLeftXOffset($xOffset); + } + if (!is_null($yOffset)) { + $this->setTopLeftYOffset($yOffset); + } + + return $this; + } + + /** + * Get the offset position within the Top Left cell for the chart + * + * @return integer[] + */ + public function getTopLeftOffset() + { + return array( + 'X' => $this->topLeftXOffset, + 'Y' => $this->topLeftYOffset + ); + } + + public function setTopLeftXOffset($xOffset) + { + $this->topLeftXOffset = $xOffset; + + return $this; + } + + public function getTopLeftXOffset() + { + return $this->topLeftXOffset; + } + + public function setTopLeftYOffset($yOffset) + { + $this->topLeftYOffset = $yOffset; + + return $this; + } + + public function getTopLeftYOffset() + { + return $this->topLeftYOffset; + } + + /** + * Set the Bottom Right position of the chart + * + * @param string $cell + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setBottomRightPosition($cell, $xOffset = null, $yOffset = null) + { + $this->bottomRightCellRef = $cell; + if (!is_null($xOffset)) { + $this->setBottomRightXOffset($xOffset); + } + if (!is_null($yOffset)) { + $this->setBottomRightYOffset($yOffset); + } + + return $this; + } + + /** + * Get the bottom right position of the chart + * + * @return array an associative array containing the cell address, X-Offset and Y-Offset from the top left of that cell + */ + public function getBottomRightPosition() + { + return array( + 'cell' => $this->bottomRightCellRef, + 'xOffset' => $this->bottomRightXOffset, + 'yOffset' => $this->bottomRightYOffset + ); + } + + public function setBottomRightCell($cell) + { + $this->bottomRightCellRef = $cell; + + return $this; + } + + /** + * Get the cell address where the bottom right of the chart is fixed + * + * @return string + */ + public function getBottomRightCell() + { + return $this->bottomRightCellRef; + } + + /** + * Set the offset position within the Bottom Right cell for the chart + * + * @param integer $xOffset + * @param integer $yOffset + * @return PHPExcel_Chart + */ + public function setBottomRightOffset($xOffset = null, $yOffset = null) + { + if (!is_null($xOffset)) { + $this->setBottomRightXOffset($xOffset); + } + if (!is_null($yOffset)) { + $this->setBottomRightYOffset($yOffset); + } + + return $this; + } + + /** + * Get the offset position within the Bottom Right cell for the chart + * + * @return integer[] + */ + public function getBottomRightOffset() + { + return array( + 'X' => $this->bottomRightXOffset, + 'Y' => $this->bottomRightYOffset + ); + } + + public function setBottomRightXOffset($xOffset) + { + $this->bottomRightXOffset = $xOffset; + + return $this; + } + + public function getBottomRightXOffset() + { + return $this->bottomRightXOffset; + } + + public function setBottomRightYOffset($yOffset) + { + $this->bottomRightYOffset = $yOffset; + + return $this; + } + + public function getBottomRightYOffset() + { + return $this->bottomRightYOffset; + } + + + public function refresh() + { + if ($this->worksheet !== null) { + $this->plotArea->refresh($this->worksheet); + } + } + + public function render($outputDestination = null) + { + $libraryName = PHPExcel_Settings::getChartRendererName(); + if (is_null($libraryName)) { + return false; + } + // Ensure that data series values are up-to-date before we render + $this->refresh(); + + $libraryPath = PHPExcel_Settings::getChartRendererPath(); + $includePath = str_replace('\\', '/', get_include_path()); + $rendererPath = str_replace('\\', '/', $libraryPath); + if (strpos($rendererPath, $includePath) === false) { + set_include_path(get_include_path() . PATH_SEPARATOR . $libraryPath); + } + + $rendererName = 'PHPExcel_Chart_Renderer_'.$libraryName; + $renderer = new $rendererName($this); + + if ($outputDestination == 'php://output') { + $outputDestination = null; + } + return $renderer->render($outputDestination); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Axis.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Axis.php new file mode 100644 index 00000000..9aeafc6a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Axis.php @@ -0,0 +1,561 @@ +<?php + +/** + * Created by PhpStorm. + * User: Wiktor Trzonkowski + * Date: 6/17/14 + * Time: 12:11 PM + */ + +class PHPExcel_Chart_Axis extends PHPExcel_Chart_Properties +{ + /** + * Axis Number + * + * @var array of mixed + */ + private $axisNumber = array( + 'format' => self::FORMAT_CODE_GENERAL, + 'source_linked' => 1 + ); + + /** + * Axis Options + * + * @var array of mixed + */ + private $axisOptions = array( + 'minimum' => null, + 'maximum' => null, + 'major_unit' => null, + 'minor_unit' => null, + 'orientation' => self::ORIENTATION_NORMAL, + 'minor_tick_mark' => self::TICK_MARK_NONE, + 'major_tick_mark' => self::TICK_MARK_NONE, + 'axis_labels' => self::AXIS_LABELS_NEXT_TO, + 'horizontal_crosses' => self::HORIZONTAL_CROSSES_AUTOZERO, + 'horizontal_crosses_value' => null + ); + + /** + * Fill Properties + * + * @var array of mixed + */ + private $fillProperties = array( + 'type' => self::EXCEL_COLOR_TYPE_ARGB, + 'value' => null, + 'alpha' => 0 + ); + + /** + * Line Properties + * + * @var array of mixed + */ + private $lineProperties = array( + 'type' => self::EXCEL_COLOR_TYPE_ARGB, + 'value' => null, + 'alpha' => 0 + ); + + /** + * Line Style Properties + * + * @var array of mixed + */ + private $lineStyleProperties = array( + 'width' => '9525', + 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, + 'dash' => self::LINE_STYLE_DASH_SOLID, + 'cap' => self::LINE_STYLE_CAP_FLAT, + 'join' => self::LINE_STYLE_JOIN_BEVEL, + 'arrow' => array( + 'head' => array( + 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, + 'size' => self::LINE_STYLE_ARROW_SIZE_5 + ), + 'end' => array( + 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, + 'size' => self::LINE_STYLE_ARROW_SIZE_8 + ), + ) + ); + + /** + * Shadow Properties + * + * @var array of mixed + */ + private $shadowProperties = array( + 'presets' => self::SHADOW_PRESETS_NOSHADOW, + 'effect' => null, + 'color' => array( + 'type' => self::EXCEL_COLOR_TYPE_STANDARD, + 'value' => 'black', + 'alpha' => 40, + ), + 'size' => array( + 'sx' => null, + 'sy' => null, + 'kx' => null + ), + 'blur' => null, + 'direction' => null, + 'distance' => null, + 'algn' => null, + 'rotWithShape' => null + ); + + /** + * Glow Properties + * + * @var array of mixed + */ + private $glowProperties = array( + 'size' => null, + 'color' => array( + 'type' => self::EXCEL_COLOR_TYPE_STANDARD, + 'value' => 'black', + 'alpha' => 40 + ) + ); + + /** + * Soft Edge Properties + * + * @var array of mixed + */ + private $softEdges = array( + 'size' => null + ); + + /** + * Get Series Data Type + * + * @return string + */ + public function setAxisNumberProperties($format_code) + { + $this->axisNumber['format'] = (string) $format_code; + $this->axisNumber['source_linked'] = 0; + } + + /** + * Get Axis Number Format Data Type + * + * @return string + */ + public function getAxisNumberFormat() + { + return $this->axisNumber['format']; + } + + /** + * Get Axis Number Source Linked + * + * @return string + */ + public function getAxisNumberSourceLinked() + { + return (string) $this->axisNumber['source_linked']; + } + + /** + * Set Axis Options Properties + * + * @param string $axis_labels + * @param string $horizontal_crosses_value + * @param string $horizontal_crosses + * @param string $axis_orientation + * @param string $major_tmt + * @param string $minor_tmt + * @param string $minimum + * @param string $maximum + * @param string $major_unit + * @param string $minor_unit + * + */ + public function setAxisOptionsProperties($axis_labels, $horizontal_crosses_value = null, $horizontal_crosses = null, $axis_orientation = null, $major_tmt = null, $minor_tmt = null, $minimum = null, $maximum = null, $major_unit = null, $minor_unit = null) + { + $this->axisOptions['axis_labels'] = (string) $axis_labels; + ($horizontal_crosses_value !== null) ? $this->axisOptions['horizontal_crosses_value'] = (string) $horizontal_crosses_value : null; + ($horizontal_crosses !== null) ? $this->axisOptions['horizontal_crosses'] = (string) $horizontal_crosses : null; + ($axis_orientation !== null) ? $this->axisOptions['orientation'] = (string) $axis_orientation : null; + ($major_tmt !== null) ? $this->axisOptions['major_tick_mark'] = (string) $major_tmt : null; + ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + ($minor_tmt !== null) ? $this->axisOptions['minor_tick_mark'] = (string) $minor_tmt : null; + ($minimum !== null) ? $this->axisOptions['minimum'] = (string) $minimum : null; + ($maximum !== null) ? $this->axisOptions['maximum'] = (string) $maximum : null; + ($major_unit !== null) ? $this->axisOptions['major_unit'] = (string) $major_unit : null; + ($minor_unit !== null) ? $this->axisOptions['minor_unit'] = (string) $minor_unit : null; + } + + /** + * Get Axis Options Property + * + * @param string $property + * + * @return string + */ + public function getAxisOptionsProperty($property) + { + return $this->axisOptions[$property]; + } + + /** + * Set Axis Orientation Property + * + * @param string $orientation + * + */ + public function setAxisOrientation($orientation) + { + $this->orientation = (string) $orientation; + } + + /** + * Set Fill Property + * + * @param string $color + * @param int $alpha + * @param string $type + * + */ + public function setFillParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) + { + $this->fillProperties = $this->setColorProperties($color, $alpha, $type); + } + + /** + * Set Line Property + * + * @param string $color + * @param int $alpha + * @param string $type + * + */ + public function setLineParameters($color, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_ARGB) + { + $this->lineProperties = $this->setColorProperties($color, $alpha, $type); + } + + /** + * Get Fill Property + * + * @param string $property + * + * @return string + */ + public function getFillProperty($property) + { + return $this->fillProperties[$property]; + } + + /** + * Get Line Property + * + * @param string $property + * + * @return string + */ + public function getLineProperty($property) + { + return $this->lineProperties[$property]; + } + + /** + * Set Line Style Properties + * + * @param float $line_width + * @param string $compound_type + * @param string $dash_type + * @param string $cap_type + * @param string $join_type + * @param string $head_arrow_type + * @param string $head_arrow_size + * @param string $end_arrow_type + * @param string $end_arrow_size + * + */ + public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) + { + (!is_null($line_width)) ? $this->lineStyleProperties['width'] = $this->getExcelPointsWidth((float) $line_width) : null; + (!is_null($compound_type)) ? $this->lineStyleProperties['compound'] = (string) $compound_type : null; + (!is_null($dash_type)) ? $this->lineStyleProperties['dash'] = (string) $dash_type : null; + (!is_null($cap_type)) ? $this->lineStyleProperties['cap'] = (string) $cap_type : null; + (!is_null($join_type)) ? $this->lineStyleProperties['join'] = (string) $join_type : null; + (!is_null($head_arrow_type)) ? $this->lineStyleProperties['arrow']['head']['type'] = (string) $head_arrow_type : null; + (!is_null($head_arrow_size)) ? $this->lineStyleProperties['arrow']['head']['size'] = (string) $head_arrow_size : null; + (!is_null($end_arrow_type)) ? $this->lineStyleProperties['arrow']['end']['type'] = (string) $end_arrow_type : null; + (!is_null($end_arrow_size)) ? $this->lineStyleProperties['arrow']['end']['size'] = (string) $end_arrow_size : null; + } + + /** + * Get Line Style Property + * + * @param array|string $elements + * + * @return string + */ + public function getLineStyleProperty($elements) + { + return $this->getArrayElementsValue($this->lineStyleProperties, $elements); + } + + /** + * Get Line Style Arrow Excel Width + * + * @param string $arrow + * + * @return string + */ + public function getLineStyleArrowWidth($arrow) + { + return $this->getLineStyleArrowSize($this->lineStyleProperties['arrow'][$arrow]['size'], 'w'); + } + + /** + * Get Line Style Arrow Excel Length + * + * @param string $arrow + * + * @return string + */ + public function getLineStyleArrowLength($arrow) + { + return $this->getLineStyleArrowSize($this->lineStyleProperties['arrow'][$arrow]['size'], 'len'); + } + + /** + * Set Shadow Properties + * + * @param int $shadow_presets + * @param string $sh_color_value + * @param string $sh_color_type + * @param string $sh_color_alpha + * @param float $sh_blur + * @param int $sh_angle + * @param float $sh_distance + * + */ + public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) + { + $this->setShadowPresetsProperties((int) $sh_presets) + ->setShadowColor( + is_null($sh_color_value) ? $this->shadowProperties['color']['value'] : $sh_color_value, + is_null($sh_color_alpha) ? (int) $this->shadowProperties['color']['alpha'] : $sh_color_alpha, + is_null($sh_color_type) ? $this->shadowProperties['color']['type'] : $sh_color_type + ) + ->setShadowBlur($sh_blur) + ->setShadowAngle($sh_angle) + ->setShadowDistance($sh_distance); + } + + /** + * Set Shadow Color + * + * @param int $shadow_presets + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowPresetsProperties($shadow_presets) + { + $this->shadowProperties['presets'] = $shadow_presets; + $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + + return $this; + } + + /** + * Set Shadow Properties from Maped Values + * + * @param array $properties_map + * @param * $reference + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + { + $base_reference = $reference; + foreach ($properties_map as $property_key => $property_val) { + if (is_array($property_val)) { + if ($reference === null) { + $reference = & $this->shadowProperties[$property_key]; + } else { + $reference = & $reference[$property_key]; + } + $this->setShadowProperiesMapValues($property_val, $reference); + } else { + if ($base_reference === null) { + $this->shadowProperties[$property_key] = $property_val; + } else { + $reference[$property_key] = $property_val; + } + } + } + + return $this; + } + + /** + * Set Shadow Color + * + * @param string $color + * @param int $alpha + * @param string $type + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowColor($color, $alpha, $type) + { + $this->shadowProperties['color'] = $this->setColorProperties($color, $alpha, $type); + + return $this; + } + + /** + * Set Shadow Blur + * + * @param float $blur + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowBlur($blur) + { + if ($blur !== null) { + $this->shadowProperties['blur'] = (string) $this->getExcelPointsWidth($blur); + } + + return $this; + } + + /** + * Set Shadow Angle + * + * @param int $angle + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowAngle($angle) + { + if ($angle !== null) { + $this->shadowProperties['direction'] = (string) $this->getExcelPointsAngle($angle); + } + + return $this; + } + + /** + * Set Shadow Distance + * + * @param float $distance + * + * @return PHPExcel_Chart_Axis + */ + private function setShadowDistance($distance) + { + if ($distance !== null) { + $this->shadowProperties['distance'] = (string) $this->getExcelPointsWidth($distance); + } + + return $this; + } + + /** + * Get Glow Property + * + * @param float $size + * @param string $color_value + * @param int $color_alpha + * @param string $color_type + */ + public function getShadowProperty($elements) + { + return $this->getArrayElementsValue($this->shadowProperties, $elements); + } + + /** + * Set Glow Properties + * + * @param float $size + * @param string $color_value + * @param int $color_alpha + * @param string $color_type + */ + public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) + { + $this->setGlowSize($size) + ->setGlowColor( + is_null($color_value) ? $this->glowProperties['color']['value'] : $color_value, + is_null($color_alpha) ? (int) $this->glowProperties['color']['alpha'] : $color_alpha, + is_null($color_type) ? $this->glowProperties['color']['type'] : $color_type + ); + } + + /** + * Get Glow Property + * + * @param array|string $property + * + * @return string + */ + public function getGlowProperty($property) + { + return $this->getArrayElementsValue($this->glowProperties, $property); + } + + /** + * Set Glow Color + * + * @param float $size + * + * @return PHPExcel_Chart_Axis + */ + private function setGlowSize($size) + { + if (!is_null($size)) { + $this->glowProperties['size'] = $this->getExcelPointsWidth($size); + } + + return $this; + } + + /** + * Set Glow Color + * + * @param string $color + * @param int $alpha + * @param string $type + * + * @return PHPExcel_Chart_Axis + */ + private function setGlowColor($color, $alpha, $type) + { + $this->glowProperties['color'] = $this->setColorProperties($color, $alpha, $type); + + return $this; + } + + /** + * Set Soft Edges Size + * + * @param float $size + */ + public function setSoftEdges($size) + { + if (!is_null($size)) { + $softEdges['size'] = (string) $this->getExcelPointsWidth($size); + } + } + + /** + * Get Soft Edges Size + * + * @return string + */ + public function getSoftEdgesSize() + { + return $this->softEdges['size']; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeries.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeries.php new file mode 100644 index 00000000..9ecd543a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeries.php @@ -0,0 +1,390 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Chart_DataSeries + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Chart_DataSeries +{ + const TYPE_BARCHART = 'barChart'; + const TYPE_BARCHART_3D = 'bar3DChart'; + const TYPE_LINECHART = 'lineChart'; + const TYPE_LINECHART_3D = 'line3DChart'; + const TYPE_AREACHART = 'areaChart'; + const TYPE_AREACHART_3D = 'area3DChart'; + const TYPE_PIECHART = 'pieChart'; + const TYPE_PIECHART_3D = 'pie3DChart'; + const TYPE_DOUGHTNUTCHART = 'doughnutChart'; + const TYPE_DONUTCHART = self::TYPE_DOUGHTNUTCHART; // Synonym + const TYPE_SCATTERCHART = 'scatterChart'; + const TYPE_SURFACECHART = 'surfaceChart'; + const TYPE_SURFACECHART_3D = 'surface3DChart'; + const TYPE_RADARCHART = 'radarChart'; + const TYPE_BUBBLECHART = 'bubbleChart'; + const TYPE_STOCKCHART = 'stockChart'; + const TYPE_CANDLECHART = self::TYPE_STOCKCHART; // Synonym + + const GROUPING_CLUSTERED = 'clustered'; + const GROUPING_STACKED = 'stacked'; + const GROUPING_PERCENT_STACKED = 'percentStacked'; + const GROUPING_STANDARD = 'standard'; + + const DIRECTION_BAR = 'bar'; + const DIRECTION_HORIZONTAL = self::DIRECTION_BAR; + const DIRECTION_COL = 'col'; + const DIRECTION_COLUMN = self::DIRECTION_COL; + const DIRECTION_VERTICAL = self::DIRECTION_COL; + + const STYLE_LINEMARKER = 'lineMarker'; + const STYLE_SMOOTHMARKER = 'smoothMarker'; + const STYLE_MARKER = 'marker'; + const STYLE_FILLED = 'filled'; + + + /** + * Series Plot Type + * + * @var string + */ + private $plotType; + + /** + * Plot Grouping Type + * + * @var boolean + */ + private $plotGrouping; + + /** + * Plot Direction + * + * @var boolean + */ + private $plotDirection; + + /** + * Plot Style + * + * @var string + */ + private $plotStyle; + + /** + * Order of plots in Series + * + * @var array of integer + */ + private $plotOrder = array(); + + /** + * Plot Label + * + * @var array of PHPExcel_Chart_DataSeriesValues + */ + private $plotLabel = array(); + + /** + * Plot Category + * + * @var array of PHPExcel_Chart_DataSeriesValues + */ + private $plotCategory = array(); + + /** + * Smooth Line + * + * @var string + */ + private $smoothLine; + + /** + * Plot Values + * + * @var array of PHPExcel_Chart_DataSeriesValues + */ + private $plotValues = array(); + + /** + * Create a new PHPExcel_Chart_DataSeries + */ + public function __construct($plotType = null, $plotGrouping = null, $plotOrder = array(), $plotLabel = array(), $plotCategory = array(), $plotValues = array(), $plotDirection = null, $smoothLine = null, $plotStyle = null) + { + $this->plotType = $plotType; + $this->plotGrouping = $plotGrouping; + $this->plotOrder = $plotOrder; + $keys = array_keys($plotValues); + $this->plotValues = $plotValues; + if ((count($plotLabel) == 0) || (is_null($plotLabel[$keys[0]]))) { + $plotLabel[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); + } + + $this->plotLabel = $plotLabel; + if ((count($plotCategory) == 0) || (is_null($plotCategory[$keys[0]]))) { + $plotCategory[$keys[0]] = new PHPExcel_Chart_DataSeriesValues(); + } + $this->plotCategory = $plotCategory; + $this->smoothLine = $smoothLine; + $this->plotStyle = $plotStyle; + + if (is_null($plotDirection)) { + $plotDirection = self::DIRECTION_COL; + } + $this->plotDirection = $plotDirection; + } + + /** + * Get Plot Type + * + * @return string + */ + public function getPlotType() + { + return $this->plotType; + } + + /** + * Set Plot Type + * + * @param string $plotType + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotType($plotType = '') + { + $this->plotType = $plotType; + return $this; + } + + /** + * Get Plot Grouping Type + * + * @return string + */ + public function getPlotGrouping() + { + return $this->plotGrouping; + } + + /** + * Set Plot Grouping Type + * + * @param string $groupingType + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotGrouping($groupingType = null) + { + $this->plotGrouping = $groupingType; + return $this; + } + + /** + * Get Plot Direction + * + * @return string + */ + public function getPlotDirection() + { + return $this->plotDirection; + } + + /** + * Set Plot Direction + * + * @param string $plotDirection + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotDirection($plotDirection = null) + { + $this->plotDirection = $plotDirection; + return $this; + } + + /** + * Get Plot Order + * + * @return string + */ + public function getPlotOrder() + { + return $this->plotOrder; + } + + /** + * Get Plot Labels + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotLabels() + { + return $this->plotLabel; + } + + /** + * Get Plot Label by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotLabelByIndex($index) + { + $keys = array_keys($this->plotLabel); + if (in_array($index, $keys)) { + return $this->plotLabel[$index]; + } elseif (isset($keys[$index])) { + return $this->plotLabel[$keys[$index]]; + } + return false; + } + + /** + * Get Plot Categories + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotCategories() + { + return $this->plotCategory; + } + + /** + * Get Plot Category by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotCategoryByIndex($index) + { + $keys = array_keys($this->plotCategory); + if (in_array($index, $keys)) { + return $this->plotCategory[$index]; + } elseif (isset($keys[$index])) { + return $this->plotCategory[$keys[$index]]; + } + return false; + } + + /** + * Get Plot Style + * + * @return string + */ + public function getPlotStyle() + { + return $this->plotStyle; + } + + /** + * Set Plot Style + * + * @param string $plotStyle + * @return PHPExcel_Chart_DataSeries + */ + public function setPlotStyle($plotStyle = null) + { + $this->plotStyle = $plotStyle; + return $this; + } + + /** + * Get Plot Values + * + * @return array of PHPExcel_Chart_DataSeriesValues + */ + public function getPlotValues() + { + return $this->plotValues; + } + + /** + * Get Plot Values by Index + * + * @return PHPExcel_Chart_DataSeriesValues + */ + public function getPlotValuesByIndex($index) + { + $keys = array_keys($this->plotValues); + if (in_array($index, $keys)) { + return $this->plotValues[$index]; + } elseif (isset($keys[$index])) { + return $this->plotValues[$keys[$index]]; + } + return false; + } + + /** + * Get Number of Plot Series + * + * @return integer + */ + public function getPlotSeriesCount() + { + return count($this->plotValues); + } + + /** + * Get Smooth Line + * + * @return boolean + */ + public function getSmoothLine() + { + return $this->smoothLine; + } + + /** + * Set Smooth Line + * + * @param boolean $smoothLine + * @return PHPExcel_Chart_DataSeries + */ + public function setSmoothLine($smoothLine = true) + { + $this->smoothLine = $smoothLine; + return $this; + } + + public function refresh(PHPExcel_Worksheet $worksheet) + { + foreach ($this->plotValues as $plotValues) { + if ($plotValues !== null) { + $plotValues->refresh($worksheet, true); + } + } + foreach ($this->plotLabel as $plotValues) { + if ($plotValues !== null) { + $plotValues->refresh($worksheet, true); + } + } + foreach ($this->plotCategory as $plotValues) { + if ($plotValues !== null) { + $plotValues->refresh($worksheet, false); + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeriesValues.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeriesValues.php new file mode 100644 index 00000000..ea57e52a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/DataSeriesValues.php @@ -0,0 +1,333 @@ +<?php + +/** + * PHPExcel_Chart_DataSeriesValues + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_DataSeriesValues +{ + + const DATASERIES_TYPE_STRING = 'String'; + const DATASERIES_TYPE_NUMBER = 'Number'; + + private static $dataTypeValues = array( + self::DATASERIES_TYPE_STRING, + self::DATASERIES_TYPE_NUMBER, + ); + + /** + * Series Data Type + * + * @var string + */ + private $dataType; + + /** + * Series Data Source + * + * @var string + */ + private $dataSource; + + /** + * Format Code + * + * @var string + */ + private $formatCode; + + /** + * Series Point Marker + * + * @var string + */ + private $pointMarker; + + /** + * Point Count (The number of datapoints in the dataseries) + * + * @var integer + */ + private $pointCount = 0; + + /** + * Data Values + * + * @var array of mixed + */ + private $dataValues = array(); + + /** + * Create a new PHPExcel_Chart_DataSeriesValues object + */ + public function __construct($dataType = self::DATASERIES_TYPE_NUMBER, $dataSource = null, $formatCode = null, $pointCount = 0, $dataValues = array(), $marker = null) + { + $this->setDataType($dataType); + $this->dataSource = $dataSource; + $this->formatCode = $formatCode; + $this->pointCount = $pointCount; + $this->dataValues = $dataValues; + $this->pointMarker = $marker; + } + + /** + * Get Series Data Type + * + * @return string + */ + public function getDataType() + { + return $this->dataType; + } + + /** + * Set Series Data Type + * + * @param string $dataType Datatype of this data series + * Typical values are: + * PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_STRING + * Normally used for axis point values + * PHPExcel_Chart_DataSeriesValues::DATASERIES_TYPE_NUMBER + * Normally used for chart data values + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataType($dataType = self::DATASERIES_TYPE_NUMBER) + { + if (!in_array($dataType, self::$dataTypeValues)) { + throw new PHPExcel_Chart_Exception('Invalid datatype for chart data series values'); + } + $this->dataType = $dataType; + + return $this; + } + + /** + * Get Series Data Source (formula) + * + * @return string + */ + public function getDataSource() + { + return $this->dataSource; + } + + /** + * Set Series Data Source (formula) + * + * @param string $dataSource + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataSource($dataSource = null, $refreshDataValues = true) + { + $this->dataSource = $dataSource; + + if ($refreshDataValues) { + // TO DO + } + + return $this; + } + + /** + * Get Point Marker + * + * @return string + */ + public function getPointMarker() + { + return $this->pointMarker; + } + + /** + * Set Point Marker + * + * @param string $marker + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setPointMarker($marker = null) + { + $this->pointMarker = $marker; + + return $this; + } + + /** + * Get Series Format Code + * + * @return string + */ + public function getFormatCode() + { + return $this->formatCode; + } + + /** + * Set Series Format Code + * + * @param string $formatCode + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setFormatCode($formatCode = null) + { + $this->formatCode = $formatCode; + + return $this; + } + + /** + * Get Series Point Count + * + * @return integer + */ + public function getPointCount() + { + return $this->pointCount; + } + + /** + * Identify if the Data Series is a multi-level or a simple series + * + * @return boolean + */ + public function isMultiLevelSeries() + { + if (count($this->dataValues) > 0) { + return is_array($this->dataValues[0]); + } + return null; + } + + /** + * Return the level count of a multi-level Data Series + * + * @return boolean + */ + public function multiLevelCount() + { + $levelCount = 0; + foreach ($this->dataValues as $dataValueSet) { + $levelCount = max($levelCount, count($dataValueSet)); + } + return $levelCount; + } + + /** + * Get Series Data Values + * + * @return array of mixed + */ + public function getDataValues() + { + return $this->dataValues; + } + + /** + * Get the first Series Data value + * + * @return mixed + */ + public function getDataValue() + { + $count = count($this->dataValues); + if ($count == 0) { + return null; + } elseif ($count == 1) { + return $this->dataValues[0]; + } + return $this->dataValues; + } + + /** + * Set Series Data Values + * + * @param array $dataValues + * @param boolean $refreshDataSource + * TRUE - refresh the value of dataSource based on the values of $dataValues + * FALSE - don't change the value of dataSource + * @return PHPExcel_Chart_DataSeriesValues + */ + public function setDataValues($dataValues = array(), $refreshDataSource = true) + { + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($dataValues); + $this->pointCount = count($dataValues); + + if ($refreshDataSource) { + // TO DO + } + + return $this; + } + + private function stripNulls($var) + { + return $var !== null; + } + + public function refresh(PHPExcel_Worksheet $worksheet, $flatten = true) + { + if ($this->dataSource !== null) { + $calcEngine = PHPExcel_Calculation::getInstance($worksheet->getParent()); + $newDataValues = PHPExcel_Calculation::unwrapResult( + $calcEngine->_calculateFormulaValue( + '='.$this->dataSource, + null, + $worksheet->getCell('A1') + ) + ); + if ($flatten) { + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + foreach ($this->dataValues as &$dataValue) { + if ((!empty($dataValue)) && ($dataValue[0] == '#')) { + $dataValue = 0.0; + } + } + unset($dataValue); + } else { + $cellRange = explode('!', $this->dataSource); + if (count($cellRange) > 1) { + list(, $cellRange) = $cellRange; + } + + $dimensions = PHPExcel_Cell::rangeDimension(str_replace('$', '', $cellRange)); + if (($dimensions[0] == 1) || ($dimensions[1] == 1)) { + $this->dataValues = PHPExcel_Calculation_Functions::flattenArray($newDataValues); + } else { + $newArray = array_values(array_shift($newDataValues)); + foreach ($newArray as $i => $newDataSet) { + $newArray[$i] = array($newDataSet); + } + + foreach ($newDataValues as $newDataSet) { + $i = 0; + foreach ($newDataSet as $newDataVal) { + array_unshift($newArray[$i++], $newDataVal); + } + } + $this->dataValues = $newArray; + } + } + $this->pointCount = count($this->dataValues); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Exception.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Exception.php new file mode 100644 index 00000000..e20dfa59 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Exception.php @@ -0,0 +1,46 @@ +<?php + +/** + * PHPExcel_Chart_Exception + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_Exception extends PHPExcel_Exception +{ + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/GridLines.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/GridLines.php new file mode 100644 index 00000000..898012eb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/GridLines.php @@ -0,0 +1,472 @@ +<?php + +/** + * Created by PhpStorm. + * User: Wiktor Trzonkowski + * Date: 7/2/14 + * Time: 2:36 PM + */ + +class PHPExcel_Chart_GridLines extends PHPExcel_Chart_Properties +{ + + /** + * Properties of Class: + * Object State (State for Minor Tick Mark) @var bool + * Line Properties @var array of mixed + * Shadow Properties @var array of mixed + * Glow Properties @var array of mixed + * Soft Properties @var array of mixed + * + */ + + private $objectState = false; + + private $lineProperties = array( + 'color' => array( + 'type' => self::EXCEL_COLOR_TYPE_STANDARD, + 'value' => null, + 'alpha' => 0 + ), + 'style' => array( + 'width' => '9525', + 'compound' => self::LINE_STYLE_COMPOUND_SIMPLE, + 'dash' => self::LINE_STYLE_DASH_SOLID, + 'cap' => self::LINE_STYLE_CAP_FLAT, + 'join' => self::LINE_STYLE_JOIN_BEVEL, + 'arrow' => array( + 'head' => array( + 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, + 'size' => self::LINE_STYLE_ARROW_SIZE_5 + ), + 'end' => array( + 'type' => self::LINE_STYLE_ARROW_TYPE_NOARROW, + 'size' => self::LINE_STYLE_ARROW_SIZE_8 + ), + ) + ) + ); + + private $shadowProperties = array( + 'presets' => self::SHADOW_PRESETS_NOSHADOW, + 'effect' => null, + 'color' => array( + 'type' => self::EXCEL_COLOR_TYPE_STANDARD, + 'value' => 'black', + 'alpha' => 85, + ), + 'size' => array( + 'sx' => null, + 'sy' => null, + 'kx' => null + ), + 'blur' => null, + 'direction' => null, + 'distance' => null, + 'algn' => null, + 'rotWithShape' => null + ); + + private $glowProperties = array( + 'size' => null, + 'color' => array( + 'type' => self::EXCEL_COLOR_TYPE_STANDARD, + 'value' => 'black', + 'alpha' => 40 + ) + ); + + private $softEdges = array( + 'size' => null + ); + + /** + * Get Object State + * + * @return bool + */ + + public function getObjectState() + { + return $this->objectState; + } + + /** + * Change Object State to True + * + * @return PHPExcel_Chart_GridLines + */ + + private function activateObject() + { + $this->objectState = true; + + return $this; + } + + /** + * Set Line Color Properties + * + * @param string $value + * @param int $alpha + * @param string $type + */ + + public function setLineColorProperties($value, $alpha = 0, $type = self::EXCEL_COLOR_TYPE_STANDARD) + { + $this->activateObject() + ->lineProperties['color'] = $this->setColorProperties( + $value, + $alpha, + $type + ); + } + + /** + * Set Line Color Properties + * + * @param float $line_width + * @param string $compound_type + * @param string $dash_type + * @param string $cap_type + * @param string $join_type + * @param string $head_arrow_type + * @param string $head_arrow_size + * @param string $end_arrow_type + * @param string $end_arrow_size + */ + + public function setLineStyleProperties($line_width = null, $compound_type = null, $dash_type = null, $cap_type = null, $join_type = null, $head_arrow_type = null, $head_arrow_size = null, $end_arrow_type = null, $end_arrow_size = null) + { + $this->activateObject(); + (!is_null($line_width)) + ? $this->lineProperties['style']['width'] = $this->getExcelPointsWidth((float) $line_width) + : null; + (!is_null($compound_type)) + ? $this->lineProperties['style']['compound'] = (string) $compound_type + : null; + (!is_null($dash_type)) + ? $this->lineProperties['style']['dash'] = (string) $dash_type + : null; + (!is_null($cap_type)) + ? $this->lineProperties['style']['cap'] = (string) $cap_type + : null; + (!is_null($join_type)) + ? $this->lineProperties['style']['join'] = (string) $join_type + : null; + (!is_null($head_arrow_type)) + ? $this->lineProperties['style']['arrow']['head']['type'] = (string) $head_arrow_type + : null; + (!is_null($head_arrow_size)) + ? $this->lineProperties['style']['arrow']['head']['size'] = (string) $head_arrow_size + : null; + (!is_null($end_arrow_type)) + ? $this->lineProperties['style']['arrow']['end']['type'] = (string) $end_arrow_type + : null; + (!is_null($end_arrow_size)) + ? $this->lineProperties['style']['arrow']['end']['size'] = (string) $end_arrow_size + : null; + } + + /** + * Get Line Color Property + * + * @param string $parameter + * + * @return string + */ + + public function getLineColorProperty($parameter) + { + return $this->lineProperties['color'][$parameter]; + } + + /** + * Get Line Style Property + * + * @param array|string $elements + * + * @return string + */ + + public function getLineStyleProperty($elements) + { + return $this->getArrayElementsValue($this->lineProperties['style'], $elements); + } + + /** + * Set Glow Properties + * + * @param float $size + * @param string $color_value + * @param int $color_alpha + * @param string $color_type + * + */ + + public function setGlowProperties($size, $color_value = null, $color_alpha = null, $color_type = null) + { + $this + ->activateObject() + ->setGlowSize($size) + ->setGlowColor($color_value, $color_alpha, $color_type); + } + + /** + * Get Glow Color Property + * + * @param string $property + * + * @return string + */ + + public function getGlowColor($property) + { + return $this->glowProperties['color'][$property]; + } + + /** + * Get Glow Size + * + * @return string + */ + + public function getGlowSize() + { + return $this->glowProperties['size']; + } + + /** + * Set Glow Size + * + * @param float $size + * + * @return PHPExcel_Chart_GridLines + */ + + private function setGlowSize($size) + { + $this->glowProperties['size'] = $this->getExcelPointsWidth((float) $size); + + return $this; + } + + /** + * Set Glow Color + * + * @param string $color + * @param int $alpha + * @param string $type + * + * @return PHPExcel_Chart_GridLines + */ + + private function setGlowColor($color, $alpha, $type) + { + if (!is_null($color)) { + $this->glowProperties['color']['value'] = (string) $color; + } + if (!is_null($alpha)) { + $this->glowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); + } + if (!is_null($type)) { + $this->glowProperties['color']['type'] = (string) $type; + } + + return $this; + } + + /** + * Get Line Style Arrow Parameters + * + * @param string $arrow_selector + * @param string $property_selector + * + * @return string + */ + + public function getLineStyleArrowParameters($arrow_selector, $property_selector) + { + return $this->getLineStyleArrowSize($this->lineProperties['style']['arrow'][$arrow_selector]['size'], $property_selector); + } + + /** + * Set Shadow Properties + * + * @param int $sh_presets + * @param string $sh_color_value + * @param string $sh_color_type + * @param int $sh_color_alpha + * @param string $sh_blur + * @param int $sh_angle + * @param float $sh_distance + * + */ + + public function setShadowProperties($sh_presets, $sh_color_value = null, $sh_color_type = null, $sh_color_alpha = null, $sh_blur = null, $sh_angle = null, $sh_distance = null) + { + $this->activateObject() + ->setShadowPresetsProperties((int) $sh_presets) + ->setShadowColor( + is_null($sh_color_value) ? $this->shadowProperties['color']['value'] : $sh_color_value, + is_null($sh_color_alpha) ? (int) $this->shadowProperties['color']['alpha'] : $this->getTrueAlpha($sh_color_alpha), + is_null($sh_color_type) ? $this->shadowProperties['color']['type'] : $sh_color_type + ) + ->setShadowBlur($sh_blur) + ->setShadowAngle($sh_angle) + ->setShadowDistance($sh_distance); + } + + /** + * Set Shadow Presets Properties + * + * @param int $shadow_presets + * + * @return PHPExcel_Chart_GridLines + */ + + private function setShadowPresetsProperties($shadow_presets) + { + $this->shadowProperties['presets'] = $shadow_presets; + $this->setShadowProperiesMapValues($this->getShadowPresetsMap($shadow_presets)); + + return $this; + } + + /** + * Set Shadow Properties Values + * + * @param array $properties_map + * @param * $reference + * + * @return PHPExcel_Chart_GridLines + */ + + private function setShadowProperiesMapValues(array $properties_map, &$reference = null) + { + $base_reference = $reference; + foreach ($properties_map as $property_key => $property_val) { + if (is_array($property_val)) { + if ($reference === null) { + $reference = & $this->shadowProperties[$property_key]; + } else { + $reference = & $reference[$property_key]; + } + $this->setShadowProperiesMapValues($property_val, $reference); + } else { + if ($base_reference === null) { + $this->shadowProperties[$property_key] = $property_val; + } else { + $reference[$property_key] = $property_val; + } + } + } + + return $this; + } + + /** + * Set Shadow Color + * + * @param string $color + * @param int $alpha + * @param string $type + * @return PHPExcel_Chart_GridLines + */ + private function setShadowColor($color, $alpha, $type) + { + if (!is_null($color)) { + $this->shadowProperties['color']['value'] = (string) $color; + } + if (!is_null($alpha)) { + $this->shadowProperties['color']['alpha'] = $this->getTrueAlpha((int) $alpha); + } + if (!is_null($type)) { + $this->shadowProperties['color']['type'] = (string) $type; + } + + return $this; + } + + /** + * Set Shadow Blur + * + * @param float $blur + * + * @return PHPExcel_Chart_GridLines + */ + private function setShadowBlur($blur) + { + if ($blur !== null) { + $this->shadowProperties['blur'] = (string) $this->getExcelPointsWidth($blur); + } + + return $this; + } + + /** + * Set Shadow Angle + * + * @param int $angle + * @return PHPExcel_Chart_GridLines + */ + + private function setShadowAngle($angle) + { + if ($angle !== null) { + $this->shadowProperties['direction'] = (string) $this->getExcelPointsAngle($angle); + } + + return $this; + } + + /** + * Set Shadow Distance + * + * @param float $distance + * @return PHPExcel_Chart_GridLines + */ + private function setShadowDistance($distance) + { + if ($distance !== null) { + $this->shadowProperties['distance'] = (string) $this->getExcelPointsWidth($distance); + } + + return $this; + } + + /** + * Get Shadow Property + * + * @param string $elements + * @param array $elements + * @return string + */ + public function getShadowProperty($elements) + { + return $this->getArrayElementsValue($this->shadowProperties, $elements); + } + + /** + * Set Soft Edges Size + * + * @param float $size + */ + public function setSoftEdgesSize($size) + { + if (!is_null($size)) { + $this->activateObject(); + $softEdges['size'] = (string) $this->getExcelPointsWidth($size); + } + } + + /** + * Get Soft Edges Size + * + * @return string + */ + public function getSoftEdgesSize() + { + return $this->softEdges['size']; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Layout.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Layout.php new file mode 100644 index 00000000..7fef0741 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Layout.php @@ -0,0 +1,486 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Chart_Layout + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Chart_Layout +{ + /** + * layoutTarget + * + * @var string + */ + private $layoutTarget; + + /** + * X Mode + * + * @var string + */ + private $xMode; + + /** + * Y Mode + * + * @var string + */ + private $yMode; + + /** + * X-Position + * + * @var float + */ + private $xPos; + + /** + * Y-Position + * + * @var float + */ + private $yPos; + + /** + * width + * + * @var float + */ + private $width; + + /** + * height + * + * @var float + */ + private $height; + + /** + * show legend key + * Specifies that legend keys should be shown in data labels + * + * @var boolean + */ + private $showLegendKey; + + /** + * show value + * Specifies that the value should be shown in a data label. + * + * @var boolean + */ + private $showVal; + + /** + * show category name + * Specifies that the category name should be shown in the data label. + * + * @var boolean + */ + private $showCatName; + + /** + * show data series name + * Specifies that the series name should be shown in the data label. + * + * @var boolean + */ + private $showSerName; + + /** + * show percentage + * Specifies that the percentage should be shown in the data label. + * + * @var boolean + */ + private $showPercent; + + /** + * show bubble size + * + * @var boolean + */ + private $showBubbleSize; + + /** + * show leader lines + * Specifies that leader lines should be shown for the data label. + * + * @var boolean + */ + private $showLeaderLines; + + + /** + * Create a new PHPExcel_Chart_Layout + */ + public function __construct($layout = array()) + { + if (isset($layout['layoutTarget'])) { + $this->layoutTarget = $layout['layoutTarget']; + } + if (isset($layout['xMode'])) { + $this->xMode = $layout['xMode']; + } + if (isset($layout['yMode'])) { + $this->yMode = $layout['yMode']; + } + if (isset($layout['x'])) { + $this->xPos = (float) $layout['x']; + } + if (isset($layout['y'])) { + $this->yPos = (float) $layout['y']; + } + if (isset($layout['w'])) { + $this->width = (float) $layout['w']; + } + if (isset($layout['h'])) { + $this->height = (float) $layout['h']; + } + } + + /** + * Get Layout Target + * + * @return string + */ + public function getLayoutTarget() + { + return $this->layoutTarget; + } + + /** + * Set Layout Target + * + * @param Layout Target $value + * @return PHPExcel_Chart_Layout + */ + public function setLayoutTarget($value) + { + $this->layoutTarget = $value; + return $this; + } + + /** + * Get X-Mode + * + * @return string + */ + public function getXMode() + { + return $this->xMode; + } + + /** + * Set X-Mode + * + * @param X-Mode $value + * @return PHPExcel_Chart_Layout + */ + public function setXMode($value) + { + $this->xMode = $value; + return $this; + } + + /** + * Get Y-Mode + * + * @return string + */ + public function getYMode() + { + return $this->yMode; + } + + /** + * Set Y-Mode + * + * @param Y-Mode $value + * @return PHPExcel_Chart_Layout + */ + public function setYMode($value) + { + $this->yMode = $value; + return $this; + } + + /** + * Get X-Position + * + * @return number + */ + public function getXPosition() + { + return $this->xPos; + } + + /** + * Set X-Position + * + * @param X-Position $value + * @return PHPExcel_Chart_Layout + */ + public function setXPosition($value) + { + $this->xPos = $value; + return $this; + } + + /** + * Get Y-Position + * + * @return number + */ + public function getYPosition() + { + return $this->yPos; + } + + /** + * Set Y-Position + * + * @param Y-Position $value + * @return PHPExcel_Chart_Layout + */ + public function setYPosition($value) + { + $this->yPos = $value; + return $this; + } + + /** + * Get Width + * + * @return number + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set Width + * + * @param Width $value + * @return PHPExcel_Chart_Layout + */ + public function setWidth($value) + { + $this->width = $value; + return $this; + } + + /** + * Get Height + * + * @return number + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set Height + * + * @param Height $value + * @return PHPExcel_Chart_Layout + */ + public function setHeight($value) + { + $this->height = $value; + return $this; + } + + + /** + * Get show legend key + * + * @return boolean + */ + public function getShowLegendKey() + { + return $this->showLegendKey; + } + + /** + * Set show legend key + * Specifies that legend keys should be shown in data labels. + * + * @param boolean $value Show legend key + * @return PHPExcel_Chart_Layout + */ + public function setShowLegendKey($value) + { + $this->showLegendKey = $value; + return $this; + } + + /** + * Get show value + * + * @return boolean + */ + public function getShowVal() + { + return $this->showVal; + } + + /** + * Set show val + * Specifies that the value should be shown in data labels. + * + * @param boolean $value Show val + * @return PHPExcel_Chart_Layout + */ + public function setShowVal($value) + { + $this->showVal = $value; + return $this; + } + + /** + * Get show category name + * + * @return boolean + */ + public function getShowCatName() + { + return $this->showCatName; + } + + /** + * Set show cat name + * Specifies that the category name should be shown in data labels. + * + * @param boolean $value Show cat name + * @return PHPExcel_Chart_Layout + */ + public function setShowCatName($value) + { + $this->showCatName = $value; + return $this; + } + + /** + * Get show data series name + * + * @return boolean + */ + public function getShowSerName() + { + return $this->showSerName; + } + + /** + * Set show ser name + * Specifies that the series name should be shown in data labels. + * + * @param boolean $value Show series name + * @return PHPExcel_Chart_Layout + */ + public function setShowSerName($value) + { + $this->showSerName = $value; + return $this; + } + + /** + * Get show percentage + * + * @return boolean + */ + public function getShowPercent() + { + return $this->showPercent; + } + + /** + * Set show percentage + * Specifies that the percentage should be shown in data labels. + * + * @param boolean $value Show percentage + * @return PHPExcel_Chart_Layout + */ + public function setShowPercent($value) + { + $this->showPercent = $value; + return $this; + } + + /** + * Get show bubble size + * + * @return boolean + */ + public function getShowBubbleSize() + { + return $this->showBubbleSize; + } + + /** + * Set show bubble size + * Specifies that the bubble size should be shown in data labels. + * + * @param boolean $value Show bubble size + * @return PHPExcel_Chart_Layout + */ + public function setShowBubbleSize($value) + { + $this->showBubbleSize = $value; + return $this; + } + + /** + * Get show leader lines + * + * @return boolean + */ + public function getShowLeaderLines() + { + return $this->showLeaderLines; + } + + /** + * Set show leader lines + * Specifies that leader lines should be shown in data labels. + * + * @param boolean $value Show leader lines + * @return PHPExcel_Chart_Layout + */ + public function setShowLeaderLines($value) + { + $this->showLeaderLines = $value; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Legend.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Legend.php new file mode 100644 index 00000000..e850eb59 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Legend.php @@ -0,0 +1,170 @@ +<?php + +/** + * PHPExcel_Chart_Legend + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_Legend +{ + /** Legend positions */ + const xlLegendPositionBottom = -4107; // Below the chart. + const xlLegendPositionCorner = 2; // In the upper right-hand corner of the chart border. + const xlLegendPositionCustom = -4161; // A custom position. + const xlLegendPositionLeft = -4131; // Left of the chart. + const xlLegendPositionRight = -4152; // Right of the chart. + const xlLegendPositionTop = -4160; // Above the chart. + + const POSITION_RIGHT = 'r'; + const POSITION_LEFT = 'l'; + const POSITION_BOTTOM = 'b'; + const POSITION_TOP = 't'; + const POSITION_TOPRIGHT = 'tr'; + + private static $positionXLref = array( + self::xlLegendPositionBottom => self::POSITION_BOTTOM, + self::xlLegendPositionCorner => self::POSITION_TOPRIGHT, + self::xlLegendPositionCustom => '??', + self::xlLegendPositionLeft => self::POSITION_LEFT, + self::xlLegendPositionRight => self::POSITION_RIGHT, + self::xlLegendPositionTop => self::POSITION_TOP + ); + + /** + * Legend position + * + * @var string + */ + private $position = self::POSITION_RIGHT; + + /** + * Allow overlay of other elements? + * + * @var boolean + */ + private $overlay = true; + + /** + * Legend Layout + * + * @var PHPExcel_Chart_Layout + */ + private $layout = null; + + + /** + * Create a new PHPExcel_Chart_Legend + */ + public function __construct($position = self::POSITION_RIGHT, PHPExcel_Chart_Layout $layout = null, $overlay = false) + { + $this->setPosition($position); + $this->layout = $layout; + $this->setOverlay($overlay); + } + + /** + * Get legend position as an excel string value + * + * @return string + */ + public function getPosition() + { + return $this->position; + } + + /** + * Get legend position using an excel string value + * + * @param string $position + */ + public function setPosition($position = self::POSITION_RIGHT) + { + if (!in_array($position, self::$positionXLref)) { + return false; + } + + $this->position = $position; + return true; + } + + /** + * Get legend position as an Excel internal numeric value + * + * @return number + */ + public function getPositionXL() + { + return array_search($this->position, self::$positionXLref); + } + + /** + * Set legend position using an Excel internal numeric value + * + * @param number $positionXL + */ + public function setPositionXL($positionXL = self::xlLegendPositionRight) + { + if (!array_key_exists($positionXL, self::$positionXLref)) { + return false; + } + + $this->position = self::$positionXLref[$positionXL]; + return true; + } + + /** + * Get allow overlay of other elements? + * + * @return boolean + */ + public function getOverlay() + { + return $this->overlay; + } + + /** + * Set allow overlay of other elements? + * + * @param boolean $overlay + * @return boolean + */ + public function setOverlay($overlay = false) + { + if (!is_bool($overlay)) { + return false; + } + + $this->overlay = $overlay; + return true; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() + { + return $this->layout; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/PlotArea.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/PlotArea.php new file mode 100644 index 00000000..551cc517 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/PlotArea.php @@ -0,0 +1,126 @@ +<?php + +/** + * PHPExcel_Chart_PlotArea + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_PlotArea +{ + /** + * PlotArea Layout + * + * @var PHPExcel_Chart_Layout + */ + private $layout = null; + + /** + * Plot Series + * + * @var array of PHPExcel_Chart_DataSeries + */ + private $plotSeries = array(); + + /** + * Create a new PHPExcel_Chart_PlotArea + */ + public function __construct(PHPExcel_Chart_Layout $layout = null, $plotSeries = array()) + { + $this->layout = $layout; + $this->plotSeries = $plotSeries; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() + { + return $this->layout; + } + + /** + * Get Number of Plot Groups + * + * @return array of PHPExcel_Chart_DataSeries + */ + public function getPlotGroupCount() + { + return count($this->plotSeries); + } + + /** + * Get Number of Plot Series + * + * @return integer + */ + public function getPlotSeriesCount() + { + $seriesCount = 0; + foreach ($this->plotSeries as $plot) { + $seriesCount += $plot->getPlotSeriesCount(); + } + return $seriesCount; + } + + /** + * Get Plot Series + * + * @return array of PHPExcel_Chart_DataSeries + */ + public function getPlotGroup() + { + return $this->plotSeries; + } + + /** + * Get Plot Series by Index + * + * @return PHPExcel_Chart_DataSeries + */ + public function getPlotGroupByIndex($index) + { + return $this->plotSeries[$index]; + } + + /** + * Set Plot Series + * + * @param [PHPExcel_Chart_DataSeries] + * @return PHPExcel_Chart_PlotArea + */ + public function setPlotSeries($plotSeries = array()) + { + $this->plotSeries = $plotSeries; + + return $this; + } + + public function refresh(PHPExcel_Worksheet $worksheet) + { + foreach ($this->plotSeries as $plotSeries) { + $plotSeries->refresh($worksheet); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Properties.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Properties.php new file mode 100644 index 00000000..9bb6e933 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Properties.php @@ -0,0 +1,363 @@ +<?php +/** + * Created by PhpStorm. + * User: nhw2h8s + * Date: 7/2/14 + * Time: 5:45 PM + */ + +abstract class PHPExcel_Chart_Properties +{ + const + EXCEL_COLOR_TYPE_STANDARD = 'prstClr', + EXCEL_COLOR_TYPE_SCHEME = 'schemeClr', + EXCEL_COLOR_TYPE_ARGB = 'srgbClr'; + + const + AXIS_LABELS_LOW = 'low', + AXIS_LABELS_HIGH = 'high', + AXIS_LABELS_NEXT_TO = 'nextTo', + AXIS_LABELS_NONE = 'none'; + + const + TICK_MARK_NONE = 'none', + TICK_MARK_INSIDE = 'in', + TICK_MARK_OUTSIDE = 'out', + TICK_MARK_CROSS = 'cross'; + + const + HORIZONTAL_CROSSES_AUTOZERO = 'autoZero', + HORIZONTAL_CROSSES_MAXIMUM = 'max'; + + const + FORMAT_CODE_GENERAL = 'General', + FORMAT_CODE_NUMBER = '#,##0.00', + FORMAT_CODE_CURRENCY = '$#,##0.00', + FORMAT_CODE_ACCOUNTING = '_($* #,##0.00_);_($* (#,##0.00);_($* "-"??_);_(@_)', + FORMAT_CODE_DATE = 'm/d/yyyy', + FORMAT_CODE_TIME = '[$-F400]h:mm:ss AM/PM', + FORMAT_CODE_PERCENTAGE = '0.00%', + FORMAT_CODE_FRACTION = '# ?/?', + FORMAT_CODE_SCIENTIFIC = '0.00E+00', + FORMAT_CODE_TEXT = '@', + FORMAT_CODE_SPECIAL = '00000'; + + const + ORIENTATION_NORMAL = 'minMax', + ORIENTATION_REVERSED = 'maxMin'; + + const + LINE_STYLE_COMPOUND_SIMPLE = 'sng', + LINE_STYLE_COMPOUND_DOUBLE = 'dbl', + LINE_STYLE_COMPOUND_THICKTHIN = 'thickThin', + LINE_STYLE_COMPOUND_THINTHICK = 'thinThick', + LINE_STYLE_COMPOUND_TRIPLE = 'tri', + + LINE_STYLE_DASH_SOLID = 'solid', + LINE_STYLE_DASH_ROUND_DOT = 'sysDot', + LINE_STYLE_DASH_SQUERE_DOT = 'sysDash', + LINE_STYPE_DASH_DASH = 'dash', + LINE_STYLE_DASH_DASH_DOT = 'dashDot', + LINE_STYLE_DASH_LONG_DASH = 'lgDash', + LINE_STYLE_DASH_LONG_DASH_DOT = 'lgDashDot', + LINE_STYLE_DASH_LONG_DASH_DOT_DOT = 'lgDashDotDot', + + LINE_STYLE_CAP_SQUARE = 'sq', + LINE_STYLE_CAP_ROUND = 'rnd', + LINE_STYLE_CAP_FLAT = 'flat', + + LINE_STYLE_JOIN_ROUND = 'bevel', + LINE_STYLE_JOIN_MITER = 'miter', + LINE_STYLE_JOIN_BEVEL = 'bevel', + + LINE_STYLE_ARROW_TYPE_NOARROW = null, + LINE_STYLE_ARROW_TYPE_ARROW = 'triangle', + LINE_STYLE_ARROW_TYPE_OPEN = 'arrow', + LINE_STYLE_ARROW_TYPE_STEALTH = 'stealth', + LINE_STYLE_ARROW_TYPE_DIAMOND = 'diamond', + LINE_STYLE_ARROW_TYPE_OVAL = 'oval', + + LINE_STYLE_ARROW_SIZE_1 = 1, + LINE_STYLE_ARROW_SIZE_2 = 2, + LINE_STYLE_ARROW_SIZE_3 = 3, + LINE_STYLE_ARROW_SIZE_4 = 4, + LINE_STYLE_ARROW_SIZE_5 = 5, + LINE_STYLE_ARROW_SIZE_6 = 6, + LINE_STYLE_ARROW_SIZE_7 = 7, + LINE_STYLE_ARROW_SIZE_8 = 8, + LINE_STYLE_ARROW_SIZE_9 = 9; + + const + SHADOW_PRESETS_NOSHADOW = null, + SHADOW_PRESETS_OUTER_BOTTTOM_RIGHT = 1, + SHADOW_PRESETS_OUTER_BOTTOM = 2, + SHADOW_PRESETS_OUTER_BOTTOM_LEFT = 3, + SHADOW_PRESETS_OUTER_RIGHT = 4, + SHADOW_PRESETS_OUTER_CENTER = 5, + SHADOW_PRESETS_OUTER_LEFT = 6, + SHADOW_PRESETS_OUTER_TOP_RIGHT = 7, + SHADOW_PRESETS_OUTER_TOP = 8, + SHADOW_PRESETS_OUTER_TOP_LEFT = 9, + SHADOW_PRESETS_INNER_BOTTTOM_RIGHT = 10, + SHADOW_PRESETS_INNER_BOTTOM = 11, + SHADOW_PRESETS_INNER_BOTTOM_LEFT = 12, + SHADOW_PRESETS_INNER_RIGHT = 13, + SHADOW_PRESETS_INNER_CENTER = 14, + SHADOW_PRESETS_INNER_LEFT = 15, + SHADOW_PRESETS_INNER_TOP_RIGHT = 16, + SHADOW_PRESETS_INNER_TOP = 17, + SHADOW_PRESETS_INNER_TOP_LEFT = 18, + SHADOW_PRESETS_PERSPECTIVE_BELOW = 19, + SHADOW_PRESETS_PERSPECTIVE_UPPER_RIGHT = 20, + SHADOW_PRESETS_PERSPECTIVE_UPPER_LEFT = 21, + SHADOW_PRESETS_PERSPECTIVE_LOWER_RIGHT = 22, + SHADOW_PRESETS_PERSPECTIVE_LOWER_LEFT = 23; + + protected function getExcelPointsWidth($width) + { + return $width * 12700; + } + + protected function getExcelPointsAngle($angle) + { + return $angle * 60000; + } + + protected function getTrueAlpha($alpha) + { + return (string) 100 - $alpha . '000'; + } + + protected function setColorProperties($color, $alpha, $type) + { + return array( + 'type' => (string) $type, + 'value' => (string) $color, + 'alpha' => (string) $this->getTrueAlpha($alpha) + ); + } + + protected function getLineStyleArrowSize($array_selector, $array_kay_selector) + { + $sizes = array( + 1 => array('w' => 'sm', 'len' => 'sm'), + 2 => array('w' => 'sm', 'len' => 'med'), + 3 => array('w' => 'sm', 'len' => 'lg'), + 4 => array('w' => 'med', 'len' => 'sm'), + 5 => array('w' => 'med', 'len' => 'med'), + 6 => array('w' => 'med', 'len' => 'lg'), + 7 => array('w' => 'lg', 'len' => 'sm'), + 8 => array('w' => 'lg', 'len' => 'med'), + 9 => array('w' => 'lg', 'len' => 'lg') + ); + + return $sizes[$array_selector][$array_kay_selector]; + } + + protected function getShadowPresetsMap($shadow_presets_option) + { + $presets_options = array( + //OUTER + 1 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '2700000', + 'algn' => 'tl', + 'rotWithShape' => '0' + ), + 2 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '5400000', + 'algn' => 't', + 'rotWithShape' => '0' + ), + 3 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '8100000', + 'algn' => 'tr', + 'rotWithShape' => '0' + ), + 4 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'algn' => 'l', + 'rotWithShape' => '0' + ), + 5 => array( + 'effect' => 'outerShdw', + 'size' => array( + 'sx' => '102000', + 'sy' => '102000' + ) + , + 'blur' => '63500', + 'distance' => '38100', + 'algn' => 'ctr', + 'rotWithShape' => '0' + ), + 6 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '10800000', + 'algn' => 'r', + 'rotWithShape' => '0' + ), + 7 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '18900000', + 'algn' => 'bl', + 'rotWithShape' => '0' + ), + 8 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '16200000', + 'rotWithShape' => '0' + ), + 9 => array( + 'effect' => 'outerShdw', + 'blur' => '50800', + 'distance' => '38100', + 'direction' => '13500000', + 'algn' => 'br', + 'rotWithShape' => '0' + ), + //INNER + 10 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '2700000', + ), + 11 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '5400000', + ), + 12 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '8100000', + ), + 13 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + ), + 14 => array( + 'effect' => 'innerShdw', + 'blur' => '114300', + ), + 15 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '10800000', + ), + 16 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '18900000', + ), + 17 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '16200000', + ), + 18 => array( + 'effect' => 'innerShdw', + 'blur' => '63500', + 'distance' => '50800', + 'direction' => '13500000', + ), + //perspective + 19 => array( + 'effect' => 'outerShdw', + 'blur' => '152400', + 'distance' => '317500', + 'size' => array( + 'sx' => '90000', + 'sy' => '-19000', + ), + 'direction' => '5400000', + 'rotWithShape' => '0', + ), + 20 => array( + 'effect' => 'outerShdw', + 'blur' => '76200', + 'direction' => '18900000', + 'size' => array( + 'sy' => '23000', + 'kx' => '-1200000', + ), + 'algn' => 'bl', + 'rotWithShape' => '0', + ), + 21 => array( + 'effect' => 'outerShdw', + 'blur' => '76200', + 'direction' => '13500000', + 'size' => array( + 'sy' => '23000', + 'kx' => '1200000', + ), + 'algn' => 'br', + 'rotWithShape' => '0', + ), + 22 => array( + 'effect' => 'outerShdw', + 'blur' => '76200', + 'distance' => '12700', + 'direction' => '2700000', + 'size' => array( + 'sy' => '-23000', + 'kx' => '-800400', + ), + 'algn' => 'bl', + 'rotWithShape' => '0', + ), + 23 => array( + 'effect' => 'outerShdw', + 'blur' => '76200', + 'distance' => '12700', + 'direction' => '8100000', + 'size' => array( + 'sy' => '-23000', + 'kx' => '800400', + ), + 'algn' => 'br', + 'rotWithShape' => '0', + ), + ); + + return $presets_options[$shadow_presets_option]; + } + + protected function getArrayElementsValue($properties, $elements) + { + $reference = & $properties; + if (!is_array($elements)) { + return $reference[$elements]; + } else { + foreach ($elements as $keys) { + $reference = & $reference[$keys]; + } + return $reference; + } + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt new file mode 100644 index 00000000..9334f684 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/PHP Charting Libraries.txt @@ -0,0 +1,20 @@ +ChartDirector + http://www.advsofteng.com/cdphp.html + +GraPHPite + http://graphpite.sourceforge.net/ + +JpGraph + http://www.aditus.nu/jpgraph/ + +LibChart + http://naku.dohcrew.com/libchart/pages/introduction/ + +pChart + http://pchart.sourceforge.net/ + +TeeChart + http://www.steema.com/products/teechart/overview.html + +PHPGraphLib + http://www.ebrueggeman.com/phpgraphlib \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/jpgraph.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/jpgraph.php new file mode 100644 index 00000000..b3d7396f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Renderer/jpgraph.php @@ -0,0 +1,883 @@ +<?php + +require_once(PHPExcel_Settings::getChartRendererPath().'/jpgraph.php'); + +/** + * PHPExcel_Chart_Renderer_jpgraph + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart_Renderer + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_Renderer_jpgraph +{ + private static $width = 640; + + private static $height = 480; + + private static $colourSet = array( + 'mediumpurple1', 'palegreen3', 'gold1', 'cadetblue1', + 'darkmagenta', 'coral', 'dodgerblue3', 'eggplant', + 'mediumblue', 'magenta', 'sandybrown', 'cyan', + 'firebrick1', 'forestgreen', 'deeppink4', 'darkolivegreen', + 'goldenrod2' + ); + + private static $markSet = array( + 'diamond' => MARK_DIAMOND, + 'square' => MARK_SQUARE, + 'triangle' => MARK_UTRIANGLE, + 'x' => MARK_X, + 'star' => MARK_STAR, + 'dot' => MARK_FILLEDCIRCLE, + 'dash' => MARK_DTRIANGLE, + 'circle' => MARK_CIRCLE, + 'plus' => MARK_CROSS + ); + + + private $chart; + + private $graph; + + private static $plotColour = 0; + + private static $plotMark = 0; + + + private function formatPointMarker($seriesPlot, $markerID) + { + $plotMarkKeys = array_keys(self::$markSet); + if (is_null($markerID)) { + // Use default plot marker (next marker in the series) + self::$plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); + } elseif ($markerID !== 'none') { + // Use specified plot marker (if it exists) + if (isset(self::$markSet[$markerID])) { + $seriesPlot->mark->SetType(self::$markSet[$markerID]); + } else { + // If the specified plot marker doesn't exist, use default plot marker (next marker in the series) + self::$plotMark %= count(self::$markSet); + $seriesPlot->mark->SetType(self::$markSet[$plotMarkKeys[self::$plotMark++]]); + } + } else { + // Hide plot marker + $seriesPlot->mark->Hide(); + } + $seriesPlot->mark->SetColor(self::$colourSet[self::$plotColour]); + $seriesPlot->mark->SetFillColor(self::$colourSet[self::$plotColour]); + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + + return $seriesPlot; + } + + + private function formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation = '') + { + $datasetLabelFormatCode = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getFormatCode(); + if (!is_null($datasetLabelFormatCode)) { + // Retrieve any label formatting code + $datasetLabelFormatCode = stripslashes($datasetLabelFormatCode); + } + + $testCurrentIndex = 0; + foreach ($datasetLabels as $i => $datasetLabel) { + if (is_array($datasetLabel)) { + if ($rotation == 'bar') { + $datasetLabels[$i] = implode(" ", $datasetLabel); + } else { + $datasetLabel = array_reverse($datasetLabel); + $datasetLabels[$i] = implode("\n", $datasetLabel); + } + } else { + // Format labels according to any formatting code + if (!is_null($datasetLabelFormatCode)) { + $datasetLabels[$i] = PHPExcel_Style_NumberFormat::toFormattedString($datasetLabel, $datasetLabelFormatCode); + } + } + ++$testCurrentIndex; + } + + return $datasetLabels; + } + + + private function percentageSumCalculation($groupID, $seriesCount) + { + // Adjust our values to a percentage value across all series in the group + for ($i = 0; $i < $seriesCount; ++$i) { + if ($i == 0) { + $sumValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + } else { + $nextValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + foreach ($nextValues as $k => $value) { + if (isset($sumValues[$k])) { + $sumValues[$k] += $value; + } else { + $sumValues[$k] = $value; + } + } + } + } + + return $sumValues; + } + + + private function percentageAdjustValues($dataValues, $sumValues) + { + foreach ($dataValues as $k => $dataValue) { + $dataValues[$k] = $dataValue / $sumValues[$k] * 100; + } + + return $dataValues; + } + + + private function getCaption($captionElement) + { + // Read any caption + $caption = (!is_null($captionElement)) ? $captionElement->getCaption() : null; + // Test if we have a title caption to display + if (!is_null($caption)) { + // If we do, it could be a plain string or an array + if (is_array($caption)) { + // Implode an array to a plain string + $caption = implode('', $caption); + } + } + return $caption; + } + + + private function renderTitle() + { + $title = $this->getCaption($this->chart->getTitle()); + if (!is_null($title)) { + $this->graph->title->Set($title); + } + } + + + private function renderLegend() + { + $legend = $this->chart->getLegend(); + if (!is_null($legend)) { + $legendPosition = $legend->getPosition(); + $legendOverlay = $legend->getOverlay(); + switch ($legendPosition) { + case 'r': + $this->graph->legend->SetPos(0.01, 0.5, 'right', 'center'); // right + $this->graph->legend->SetColumns(1); + break; + case 'l': + $this->graph->legend->SetPos(0.01, 0.5, 'left', 'center'); // left + $this->graph->legend->SetColumns(1); + break; + case 't': + $this->graph->legend->SetPos(0.5, 0.01, 'center', 'top'); // top + break; + case 'b': + $this->graph->legend->SetPos(0.5, 0.99, 'center', 'bottom'); // bottom + break; + default: + $this->graph->legend->SetPos(0.01, 0.01, 'right', 'top'); // top-right + $this->graph->legend->SetColumns(1); + break; + } + } else { + $this->graph->legend->Hide(); + } + } + + + private function renderCartesianPlotArea($type = 'textlin') + { + $this->graph = new Graph(self::$width, self::$height); + $this->graph->SetScale($type); + + $this->renderTitle(); + + // Rotate for bar rather than column chart + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotDirection(); + $reverse = ($rotation == 'bar') ? true : false; + + $xAxisLabel = $this->chart->getXAxisLabel(); + if (!is_null($xAxisLabel)) { + $title = $this->getCaption($xAxisLabel); + if (!is_null($title)) { + $this->graph->xaxis->SetTitle($title, 'center'); + $this->graph->xaxis->title->SetMargin(35); + if ($reverse) { + $this->graph->xaxis->title->SetAngle(90); + $this->graph->xaxis->title->SetMargin(90); + } + } + } + + $yAxisLabel = $this->chart->getYAxisLabel(); + if (!is_null($yAxisLabel)) { + $title = $this->getCaption($yAxisLabel); + if (!is_null($title)) { + $this->graph->yaxis->SetTitle($title, 'center'); + if ($reverse) { + $this->graph->yaxis->title->SetAngle(0); + $this->graph->yaxis->title->SetMargin(-55); + } + } + } + } + + + private function renderPiePlotArea($doughnut = false) + { + $this->graph = new PieGraph(self::$width, self::$height); + + $this->renderTitle(); + } + + + private function renderRadarPlotArea() + { + $this->graph = new RadarGraph(self::$width, self::$height); + $this->graph->SetScale('lin'); + + $this->renderTitle(); + } + + + private function renderPlotLine($groupID, $filled = false, $combination = false, $dimensions = '2d') + { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + if ($grouping == 'percentStacked') { + $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + $seriesPlot = new LinePlot($dataValues); + if ($combination) { + $seriesPlot->SetBarCenter(); + } + + if ($filled) { + $seriesPlot->SetFilled(true); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); + } else { + // Set the appropriate plot marker + $this->formatPointMarker($seriesPlot, $marker); + } + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + + if ($grouping == 'standard') { + $groupPlot = $seriesPlots; + } else { + $groupPlot = new AccLinePlot($seriesPlots); + } + $this->graph->Add($groupPlot); + } + + + private function renderPlotBar($groupID, $dimensions = '2d') + { + $rotation = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotDirection(); + // Rotate for bar rather than column chart + if (($groupID == 0) && ($rotation == 'bar')) { + $this->graph->Set90AndMargin(); + } + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount, $rotation); + // Rotate for bar rather than column chart + if ($rotation == 'bar') { + $datasetLabels = array_reverse($datasetLabels); + $this->graph->yaxis->SetPos('max'); + $this->graph->yaxis->SetLabelAlign('center', 'top'); + $this->graph->yaxis->SetLabelSide(SIDE_RIGHT); + } + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + if ($grouping == 'percentStacked') { + $sumValues = $this->percentageSumCalculation($groupID, $seriesCount); + } + + // Loop through each data series in turn + for ($j = 0; $j < $seriesCount; ++$j) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + if ($grouping == 'percentStacked') { + $dataValues = $this->percentageAdjustValues($dataValues, $sumValues); + } + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + // Reverse the $dataValues order for bar rather than column chart + if ($rotation == 'bar') { + $dataValues = array_reverse($dataValues); + } + $seriesPlot = new BarPlot($dataValues); + $seriesPlot->SetColor('black'); + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour++]); + if ($dimensions == '3d') { + $seriesPlot->SetShadow(); + } + if (!$this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)) { + $dataLabel = ''; + } else { + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($j)->getDataValue(); + } + $seriesPlot->SetLegend($dataLabel); + + $seriesPlots[] = $seriesPlot; + } + // Reverse the plot order for bar rather than column chart + if (($rotation == 'bar') && (!($grouping == 'percentStacked'))) { + $seriesPlots = array_reverse($seriesPlots); + } + + if ($grouping == 'clustered') { + $groupPlot = new GroupBarPlot($seriesPlots); + } elseif ($grouping == 'standard') { + $groupPlot = new GroupBarPlot($seriesPlots); + } else { + $groupPlot = new AccBarPlot($seriesPlots); + if ($dimensions == '3d') { + $groupPlot->SetShadow(); + } + } + + $this->graph->Add($groupPlot); + } + + + private function renderPlotScatter($groupID, $bubble) + { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $scatterStyle = $bubbleSize = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + foreach ($dataValuesY as $k => $dataValueY) { + $dataValuesY[$k] = $k; + } + + $seriesPlot = new ScatterPlot($dataValuesX, $dataValuesY); + if ($scatterStyle == 'lineMarker') { + $seriesPlot->SetLinkPoints(); + $seriesPlot->link->SetColor(self::$colourSet[self::$plotColour]); + } elseif ($scatterStyle == 'smoothMarker') { + $spline = new Spline($dataValuesY, $dataValuesX); + list($splineDataY, $splineDataX) = $spline->Get(count($dataValuesX) * self::$width / 20); + $lplot = new LinePlot($splineDataX, $splineDataY); + $lplot->SetColor(self::$colourSet[self::$plotColour]); + + $this->graph->Add($lplot); + } + + if ($bubble) { + $this->formatPointMarker($seriesPlot, 'dot'); + $seriesPlot->mark->SetColor('black'); + $seriesPlot->mark->SetSize($bubbleSize); + } else { + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + $this->formatPointMarker($seriesPlot, $marker); + } + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetLegend($dataLabel); + + $this->graph->Add($seriesPlot); + } + } + + + private function renderPlotRadar($groupID) + { + $radarStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + $marker = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getPointMarker(); + + $dataValues = array(); + foreach ($dataValuesY as $k => $dataValueY) { + $dataValues[$k] = implode(' ', array_reverse($dataValueY)); + } + $tmp = array_shift($dataValues); + $dataValues[] = $tmp; + $tmp = array_shift($dataValuesX); + $dataValuesX[] = $tmp; + + $this->graph->SetTitles(array_reverse($dataValues)); + + $seriesPlot = new RadarPlot(array_reverse($dataValuesX)); + + $dataLabel = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotLabelByIndex($i)->getDataValue(); + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + if ($radarStyle == 'filled') { + $seriesPlot->SetFillColor(self::$colourSet[self::$plotColour]); + } + $this->formatPointMarker($seriesPlot, $marker); + $seriesPlot->SetLegend($dataLabel); + + $this->graph->Add($seriesPlot); + } + } + + + private function renderPlotContour($groupID) + { + $contourStyle = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + + $dataValues = array(); + // Loop through each data series in turn + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesY = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex($i)->getDataValues(); + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($i)->getDataValues(); + + $dataValues[$i] = $dataValuesX; + } + $seriesPlot = new ContourPlot($dataValues); + + $this->graph->Add($seriesPlot); + } + + + private function renderPlotStock($groupID) + { + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $plotOrder = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotOrder(); + + $dataValues = array(); + // Loop through each data series in turn and build the plot arrays + foreach ($plotOrder as $i => $v) { + $dataValuesX = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($v)->getDataValues(); + foreach ($dataValuesX as $j => $dataValueX) { + $dataValues[$plotOrder[$i]][$j] = $dataValueX; + } + } + if (empty($dataValues)) { + return; + } + + $dataValuesPlot = array(); + // Flatten the plot arrays to a single dimensional array to work with jpgraph + for ($j = 0; $j < count($dataValues[0]); ++$j) { + for ($i = 0; $i < $seriesCount; ++$i) { + $dataValuesPlot[] = $dataValues[$i][$j]; + } + } + + // Set the x-axis labels + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + $this->graph->xaxis->SetTickLabels($datasetLabels); + } + + $seriesPlot = new StockPlot($dataValuesPlot); + $seriesPlot->SetWidth(20); + + $this->graph->Add($seriesPlot); + } + + + private function renderAreaChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotLine($i, true, false, $dimensions); + } + } + + + private function renderLineChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotLine($i, false, false, $dimensions); + } + } + + + private function renderBarChart($groupCount, $dimensions = '2d') + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotBar($i, $dimensions); + } + } + + + private function renderScatterChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea('linlin'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotScatter($i, false); + } + } + + + private function renderBubbleChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + + $this->renderCartesianPlotArea('linlin'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotScatter($i, true); + } + } + + + private function renderPieChart($groupCount, $dimensions = '2d', $doughnut = false, $multiplePlots = false) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie.php'); + if ($dimensions == '3d') { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_pie3d.php'); + } + + $this->renderPiePlotArea($doughnut); + + $iLimit = ($multiplePlots) ? $groupCount : 1; + for ($groupID = 0; $groupID < $iLimit; ++$groupID) { + $grouping = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotGrouping(); + $exploded = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotStyle(); + if ($groupID == 0) { + $labelCount = count($this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex(0)->getPointCount()); + if ($labelCount > 0) { + $datasetLabels = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotCategoryByIndex(0)->getDataValues(); + $datasetLabels = $this->formatDataSetLabels($groupID, $datasetLabels, $labelCount); + } + } + + $seriesCount = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotSeriesCount(); + $seriesPlots = array(); + // For pie charts, we only display the first series: doughnut charts generally display all series + $jLimit = ($multiplePlots) ? $seriesCount : 1; + // Loop through each data series in turn + for ($j = 0; $j < $jLimit; ++$j) { + $dataValues = $this->chart->getPlotArea()->getPlotGroupByIndex($groupID)->getPlotValuesByIndex($j)->getDataValues(); + + // Fill in any missing values in the $dataValues array + $testCurrentIndex = 0; + foreach ($dataValues as $k => $dataValue) { + while ($k != $testCurrentIndex) { + $dataValues[$testCurrentIndex] = null; + ++$testCurrentIndex; + } + ++$testCurrentIndex; + } + + if ($dimensions == '3d') { + $seriesPlot = new PiePlot3D($dataValues); + } else { + if ($doughnut) { + $seriesPlot = new PiePlotC($dataValues); + } else { + $seriesPlot = new PiePlot($dataValues); + } + } + + if ($multiplePlots) { + $seriesPlot->SetSize(($jLimit-$j) / ($jLimit * 4)); + } + + if ($doughnut) { + $seriesPlot->SetMidColor('white'); + } + + $seriesPlot->SetColor(self::$colourSet[self::$plotColour++]); + if (count($datasetLabels) > 0) { + $seriesPlot->SetLabels(array_fill(0, count($datasetLabels), '')); + } + if ($dimensions != '3d') { + $seriesPlot->SetGuideLines(false); + } + if ($j == 0) { + if ($exploded) { + $seriesPlot->ExplodeAll(); + } + $seriesPlot->SetLegends($datasetLabels); + } + + $this->graph->Add($seriesPlot); + } + } + } + + + private function renderRadarChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_radar.php'); + + $this->renderRadarPlotArea(); + + for ($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->renderPlotRadar($groupID); + } + } + + + private function renderStockChart($groupCount) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_stock.php'); + + $this->renderCartesianPlotArea('intint'); + + for ($groupID = 0; $groupID < $groupCount; ++$groupID) { + $this->renderPlotStock($groupID); + } + } + + + private function renderContourChart($groupCount, $dimensions) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_contour.php'); + + $this->renderCartesianPlotArea('intint'); + + for ($i = 0; $i < $groupCount; ++$i) { + $this->renderPlotContour($i); + } + } + + + private function renderCombinationChart($groupCount, $dimensions, $outputDestination) + { + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_bar.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_scatter.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_regstat.php'); + require_once(PHPExcel_Settings::getChartRendererPath().'jpgraph_line.php'); + + $this->renderCartesianPlotArea(); + + for ($i = 0; $i < $groupCount; ++$i) { + $dimensions = null; + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + switch ($chartType) { + case 'area3DChart': + $dimensions = '3d'; + // no break + case 'areaChart': + $this->renderPlotLine($i, true, true, $dimensions); + break; + case 'bar3DChart': + $dimensions = '3d'; + // no break + case 'barChart': + $this->renderPlotBar($i, $dimensions); + break; + case 'line3DChart': + $dimensions = '3d'; + // no break + case 'lineChart': + $this->renderPlotLine($i, false, true, $dimensions); + break; + case 'scatterChart': + $this->renderPlotScatter($i, false); + break; + case 'bubbleChart': + $this->renderPlotScatter($i, true); + break; + default: + $this->graph = null; + return false; + } + } + + $this->renderLegend(); + + $this->graph->Stroke($outputDestination); + return true; + } + + + public function render($outputDestination) + { + self::$plotColour = 0; + + $groupCount = $this->chart->getPlotArea()->getPlotGroupCount(); + + $dimensions = null; + if ($groupCount == 1) { + $chartType = $this->chart->getPlotArea()->getPlotGroupByIndex(0)->getPlotType(); + } else { + $chartTypes = array(); + for ($i = 0; $i < $groupCount; ++$i) { + $chartTypes[] = $this->chart->getPlotArea()->getPlotGroupByIndex($i)->getPlotType(); + } + $chartTypes = array_unique($chartTypes); + if (count($chartTypes) == 1) { + $chartType = array_pop($chartTypes); + } elseif (count($chartTypes) == 0) { + echo 'Chart is not yet implemented<br />'; + return false; + } else { + return $this->renderCombinationChart($groupCount, $dimensions, $outputDestination); + } + } + + switch ($chartType) { + case 'area3DChart': + $dimensions = '3d'; + // no break + case 'areaChart': + $this->renderAreaChart($groupCount, $dimensions); + break; + case 'bar3DChart': + $dimensions = '3d'; + // no break + case 'barChart': + $this->renderBarChart($groupCount, $dimensions); + break; + case 'line3DChart': + $dimensions = '3d'; + // no break + case 'lineChart': + $this->renderLineChart($groupCount, $dimensions); + break; + case 'pie3DChart': + $dimensions = '3d'; + // no break + case 'pieChart': + $this->renderPieChart($groupCount, $dimensions, false, false); + break; + case 'doughnut3DChart': + $dimensions = '3d'; + // no break + case 'doughnutChart': + $this->renderPieChart($groupCount, $dimensions, true, true); + break; + case 'scatterChart': + $this->renderScatterChart($groupCount); + break; + case 'bubbleChart': + $this->renderBubbleChart($groupCount); + break; + case 'radarChart': + $this->renderRadarChart($groupCount); + break; + case 'surface3DChart': + $dimensions = '3d'; + // no break + case 'surfaceChart': + $this->renderContourChart($groupCount, $dimensions); + break; + case 'stockChart': + $this->renderStockChart($groupCount, $dimensions); + break; + default: + echo $chartType.' is not yet implemented<br />'; + return false; + } + $this->renderLegend(); + + $this->graph->Stroke($outputDestination); + return true; + } + + + /** + * Create a new PHPExcel_Chart_Renderer_jpgraph + */ + public function __construct(PHPExcel_Chart $chart) + { + $this->graph = null; + $this->chart = $chart; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Title.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Title.php new file mode 100644 index 00000000..d8dc14f2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Chart/Title.php @@ -0,0 +1,86 @@ +<?php + +/** + * PHPExcel_Chart_Title + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Chart + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Chart_Title +{ + + /** + * Title Caption + * + * @var string + */ + private $caption = null; + + /** + * Title Layout + * + * @var PHPExcel_Chart_Layout + */ + private $layout = null; + + /** + * Create a new PHPExcel_Chart_Title + */ + public function __construct($caption = null, PHPExcel_Chart_Layout $layout = null) + { + $this->caption = $caption; + $this->layout = $layout; + } + + /** + * Get caption + * + * @return string + */ + public function getCaption() + { + return $this->caption; + } + + /** + * Set caption + * + * @param string $caption + * @return PHPExcel_Chart_Title + */ + public function setCaption($caption = null) + { + $this->caption = $caption; + + return $this; + } + + /** + * Get Layout + * + * @return PHPExcel_Chart_Layout + */ + public function getLayout() + { + return $this->layout; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Comment.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Comment.php new file mode 100644 index 00000000..d55363fd --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Comment.php @@ -0,0 +1,338 @@ +<?php + +/** + * PHPExcel_Comment + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Comment implements PHPExcel_IComparable +{ + /** + * Author + * + * @var string + */ + private $author; + + /** + * Rich text comment + * + * @var PHPExcel_RichText + */ + private $text; + + /** + * Comment width (CSS style, i.e. XXpx or YYpt) + * + * @var string + */ + private $width = '96pt'; + + /** + * Left margin (CSS style, i.e. XXpx or YYpt) + * + * @var string + */ + private $marginLeft = '59.25pt'; + + /** + * Top margin (CSS style, i.e. XXpx or YYpt) + * + * @var string + */ + private $marginTop = '1.5pt'; + + /** + * Visible + * + * @var boolean + */ + private $visible = false; + + /** + * Comment height (CSS style, i.e. XXpx or YYpt) + * + * @var string + */ + private $height = '55.5pt'; + + /** + * Comment fill color + * + * @var PHPExcel_Style_Color + */ + private $fillColor; + + /** + * Alignment + * + * @var string + */ + private $alignment; + + /** + * Create a new PHPExcel_Comment + * + * @throws PHPExcel_Exception + */ + public function __construct() + { + // Initialise variables + $this->author = 'Author'; + $this->text = new PHPExcel_RichText(); + $this->fillColor = new PHPExcel_Style_Color('FFFFFFE1'); + $this->alignment = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + } + + /** + * Get Author + * + * @return string + */ + public function getAuthor() + { + return $this->author; + } + + /** + * Set Author + * + * @param string $pValue + * @return PHPExcel_Comment + */ + public function setAuthor($pValue = '') + { + $this->author = $pValue; + return $this; + } + + /** + * Get Rich text comment + * + * @return PHPExcel_RichText + */ + public function getText() + { + return $this->text; + } + + /** + * Set Rich text comment + * + * @param PHPExcel_RichText $pValue + * @return PHPExcel_Comment + */ + public function setText(PHPExcel_RichText $pValue) + { + $this->text = $pValue; + return $this; + } + + /** + * Get comment width (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set comment width (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setWidth($value = '96pt') + { + $this->width = $value; + return $this; + } + + /** + * Get comment height (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set comment height (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setHeight($value = '55.5pt') + { + $this->height = $value; + return $this; + } + + /** + * Get left margin (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getMarginLeft() + { + return $this->marginLeft; + } + + /** + * Set left margin (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setMarginLeft($value = '59.25pt') + { + $this->marginLeft = $value; + return $this; + } + + /** + * Get top margin (CSS style, i.e. XXpx or YYpt) + * + * @return string + */ + public function getMarginTop() + { + return $this->marginTop; + } + + /** + * Set top margin (CSS style, i.e. XXpx or YYpt) + * + * @param string $value + * @return PHPExcel_Comment + */ + public function setMarginTop($value = '1.5pt') + { + $this->marginTop = $value; + return $this; + } + + /** + * Is the comment visible by default? + * + * @return boolean + */ + public function getVisible() + { + return $this->visible; + } + + /** + * Set comment default visibility + * + * @param boolean $value + * @return PHPExcel_Comment + */ + public function setVisible($value = false) + { + $this->visible = $value; + return $this; + } + + /** + * Get fill color + * + * @return PHPExcel_Style_Color + */ + public function getFillColor() + { + return $this->fillColor; + } + + /** + * Set Alignment + * + * @param string $pValue + * @return PHPExcel_Comment + */ + public function setAlignment($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) + { + $this->alignment = $pValue; + return $this; + } + + /** + * Get Alignment + * + * @return string + */ + public function getAlignment() + { + return $this->alignment; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->author . + $this->text->getHashCode() . + $this->width . + $this->height . + $this->marginLeft . + $this->marginTop . + ($this->visible ? 1 : 0) . + $this->fillColor->getHashCode() . + $this->alignment . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() + { + return $this->text->getPlainText(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentProperties.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentProperties.php new file mode 100644 index 00000000..2395ba98 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentProperties.php @@ -0,0 +1,611 @@ +<?php + +/** + * PHPExcel_DocumentProperties + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_DocumentProperties +{ + /** constants */ + const PROPERTY_TYPE_BOOLEAN = 'b'; + const PROPERTY_TYPE_INTEGER = 'i'; + const PROPERTY_TYPE_FLOAT = 'f'; + const PROPERTY_TYPE_DATE = 'd'; + const PROPERTY_TYPE_STRING = 's'; + const PROPERTY_TYPE_UNKNOWN = 'u'; + + /** + * Creator + * + * @var string + */ + private $creator = 'Unknown Creator'; + + /** + * LastModifiedBy + * + * @var string + */ + private $lastModifiedBy; + + /** + * Created + * + * @var datetime + */ + private $created; + + /** + * Modified + * + * @var datetime + */ + private $modified; + + /** + * Title + * + * @var string + */ + private $title = 'Untitled Spreadsheet'; + + /** + * Description + * + * @var string + */ + private $description = ''; + + /** + * Subject + * + * @var string + */ + private $subject = ''; + + /** + * Keywords + * + * @var string + */ + private $keywords = ''; + + /** + * Category + * + * @var string + */ + private $category = ''; + + /** + * Manager + * + * @var string + */ + private $manager = ''; + + /** + * Company + * + * @var string + */ + private $company = 'Microsoft Corporation'; + + /** + * Custom Properties + * + * @var string + */ + private $customProperties = array(); + + + /** + * Create a new PHPExcel_DocumentProperties + */ + public function __construct() + { + // Initialise values + $this->lastModifiedBy = $this->creator; + $this->created = time(); + $this->modified = time(); + } + + /** + * Get Creator + * + * @return string + */ + public function getCreator() + { + return $this->creator; + } + + /** + * Set Creator + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCreator($pValue = '') + { + $this->creator = $pValue; + return $this; + } + + /** + * Get Last Modified By + * + * @return string + */ + public function getLastModifiedBy() + { + return $this->lastModifiedBy; + } + + /** + * Set Last Modified By + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setLastModifiedBy($pValue = '') + { + $this->lastModifiedBy = $pValue; + return $this; + } + + /** + * Get Created + * + * @return datetime + */ + public function getCreated() + { + return $this->created; + } + + /** + * Set Created + * + * @param datetime $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCreated($pValue = null) + { + if ($pValue === null) { + $pValue = time(); + } elseif (is_string($pValue)) { + if (is_numeric($pValue)) { + $pValue = intval($pValue); + } else { + $pValue = strtotime($pValue); + } + } + + $this->created = $pValue; + return $this; + } + + /** + * Get Modified + * + * @return datetime + */ + public function getModified() + { + return $this->modified; + } + + /** + * Set Modified + * + * @param datetime $pValue + * @return PHPExcel_DocumentProperties + */ + public function setModified($pValue = null) + { + if ($pValue === null) { + $pValue = time(); + } elseif (is_string($pValue)) { + if (is_numeric($pValue)) { + $pValue = intval($pValue); + } else { + $pValue = strtotime($pValue); + } + } + + $this->modified = $pValue; + return $this; + } + + /** + * Get Title + * + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set Title + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setTitle($pValue = '') + { + $this->title = $pValue; + return $this; + } + + /** + * Get Description + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set Description + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setDescription($pValue = '') + { + $this->description = $pValue; + return $this; + } + + /** + * Get Subject + * + * @return string + */ + public function getSubject() + { + return $this->subject; + } + + /** + * Set Subject + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setSubject($pValue = '') + { + $this->subject = $pValue; + return $this; + } + + /** + * Get Keywords + * + * @return string + */ + public function getKeywords() + { + return $this->keywords; + } + + /** + * Set Keywords + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setKeywords($pValue = '') + { + $this->keywords = $pValue; + return $this; + } + + /** + * Get Category + * + * @return string + */ + public function getCategory() + { + return $this->category; + } + + /** + * Set Category + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCategory($pValue = '') + { + $this->category = $pValue; + return $this; + } + + /** + * Get Company + * + * @return string + */ + public function getCompany() + { + return $this->company; + } + + /** + * Set Company + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setCompany($pValue = '') + { + $this->company = $pValue; + return $this; + } + + /** + * Get Manager + * + * @return string + */ + public function getManager() + { + return $this->manager; + } + + /** + * Set Manager + * + * @param string $pValue + * @return PHPExcel_DocumentProperties + */ + public function setManager($pValue = '') + { + $this->manager = $pValue; + return $this; + } + + /** + * Get a List of Custom Property Names + * + * @return array of string + */ + public function getCustomProperties() + { + return array_keys($this->customProperties); + } + + /** + * Check if a Custom Property is defined + * + * @param string $propertyName + * @return boolean + */ + public function isCustomPropertySet($propertyName) + { + return isset($this->customProperties[$propertyName]); + } + + /** + * Get a Custom Property Value + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyValue($propertyName) + { + if (isset($this->customProperties[$propertyName])) { + return $this->customProperties[$propertyName]['value']; + } + + } + + /** + * Get a Custom Property Type + * + * @param string $propertyName + * @return string + */ + public function getCustomPropertyType($propertyName) + { + if (isset($this->customProperties[$propertyName])) { + return $this->customProperties[$propertyName]['type']; + } + + } + + /** + * Set a Custom Property + * + * @param string $propertyName + * @param mixed $propertyValue + * @param string $propertyType + * 'i' : Integer + * 'f' : Floating Point + * 's' : String + * 'd' : Date/Time + * 'b' : Boolean + * @return PHPExcel_DocumentProperties + */ + public function setCustomProperty($propertyName, $propertyValue = '', $propertyType = null) + { + if (($propertyType === null) || (!in_array($propertyType, array(self::PROPERTY_TYPE_INTEGER, + self::PROPERTY_TYPE_FLOAT, + self::PROPERTY_TYPE_STRING, + self::PROPERTY_TYPE_DATE, + self::PROPERTY_TYPE_BOOLEAN)))) { + if ($propertyValue === null) { + $propertyType = self::PROPERTY_TYPE_STRING; + } elseif (is_float($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_FLOAT; + } elseif (is_int($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_INTEGER; + } elseif (is_bool($propertyValue)) { + $propertyType = self::PROPERTY_TYPE_BOOLEAN; + } else { + $propertyType = self::PROPERTY_TYPE_STRING; + } + } + + $this->customProperties[$propertyName] = array( + 'value' => $propertyValue, + 'type' => $propertyType + ); + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } + + public static function convertProperty($propertyValue, $propertyType) + { + switch ($propertyType) { + case 'empty': // Empty + return ''; + break; + case 'null': // Null + return null; + break; + case 'i1': // 1-Byte Signed Integer + case 'i2': // 2-Byte Signed Integer + case 'i4': // 4-Byte Signed Integer + case 'i8': // 8-Byte Signed Integer + case 'int': // Integer + return (int) $propertyValue; + break; + case 'ui1': // 1-Byte Unsigned Integer + case 'ui2': // 2-Byte Unsigned Integer + case 'ui4': // 4-Byte Unsigned Integer + case 'ui8': // 8-Byte Unsigned Integer + case 'uint': // Unsigned Integer + return abs((int) $propertyValue); + break; + case 'r4': // 4-Byte Real Number + case 'r8': // 8-Byte Real Number + case 'decimal': // Decimal + return (float) $propertyValue; + break; + case 'lpstr': // LPSTR + case 'lpwstr': // LPWSTR + case 'bstr': // Basic String + return $propertyValue; + break; + case 'date': // Date and Time + case 'filetime': // File Time + return strtotime($propertyValue); + break; + case 'bool': // Boolean + return ($propertyValue == 'true') ? true : false; + break; + case 'cy': // Currency + case 'error': // Error Status Code + case 'vector': // Vector + case 'array': // Array + case 'blob': // Binary Blob + case 'oblob': // Binary Blob Object + case 'stream': // Binary Stream + case 'ostream': // Binary Stream Object + case 'storage': // Binary Storage + case 'ostorage': // Binary Storage Object + case 'vstream': // Binary Versioned Stream + case 'clsid': // Class ID + case 'cf': // Clipboard Data + return $propertyValue; + break; + } + return $propertyValue; + } + + public static function convertPropertyType($propertyType) + { + switch ($propertyType) { + case 'i1': // 1-Byte Signed Integer + case 'i2': // 2-Byte Signed Integer + case 'i4': // 4-Byte Signed Integer + case 'i8': // 8-Byte Signed Integer + case 'int': // Integer + case 'ui1': // 1-Byte Unsigned Integer + case 'ui2': // 2-Byte Unsigned Integer + case 'ui4': // 4-Byte Unsigned Integer + case 'ui8': // 8-Byte Unsigned Integer + case 'uint': // Unsigned Integer + return self::PROPERTY_TYPE_INTEGER; + break; + case 'r4': // 4-Byte Real Number + case 'r8': // 8-Byte Real Number + case 'decimal': // Decimal + return self::PROPERTY_TYPE_FLOAT; + break; + case 'empty': // Empty + case 'null': // Null + case 'lpstr': // LPSTR + case 'lpwstr': // LPWSTR + case 'bstr': // Basic String + return self::PROPERTY_TYPE_STRING; + break; + case 'date': // Date and Time + case 'filetime': // File Time + return self::PROPERTY_TYPE_DATE; + break; + case 'bool': // Boolean + return self::PROPERTY_TYPE_BOOLEAN; + break; + case 'cy': // Currency + case 'error': // Error Status Code + case 'vector': // Vector + case 'array': // Array + case 'blob': // Binary Blob + case 'oblob': // Binary Blob Object + case 'stream': // Binary Stream + case 'ostream': // Binary Stream Object + case 'storage': // Binary Storage + case 'ostorage': // Binary Storage Object + case 'vstream': // Binary Versioned Stream + case 'clsid': // Class ID + case 'cf': // Clipboard Data + return self::PROPERTY_TYPE_UNKNOWN; + break; + } + return self::PROPERTY_TYPE_UNKNOWN; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentSecurity.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentSecurity.php new file mode 100644 index 00000000..ecea0da1 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/DocumentSecurity.php @@ -0,0 +1,222 @@ +<?php + +/** + * PHPExcel_DocumentSecurity + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_DocumentSecurity +{ + /** + * LockRevision + * + * @var boolean + */ + private $lockRevision; + + /** + * LockStructure + * + * @var boolean + */ + private $lockStructure; + + /** + * LockWindows + * + * @var boolean + */ + private $lockWindows; + + /** + * RevisionsPassword + * + * @var string + */ + private $revisionsPassword; + + /** + * WorkbookPassword + * + * @var string + */ + private $workbookPassword; + + /** + * Create a new PHPExcel_DocumentSecurity + */ + public function __construct() + { + // Initialise values + $this->lockRevision = false; + $this->lockStructure = false; + $this->lockWindows = false; + $this->revisionsPassword = ''; + $this->workbookPassword = ''; + } + + /** + * Is some sort of document security enabled? + * + * @return boolean + */ + public function isSecurityEnabled() + { + return $this->lockRevision || + $this->lockStructure || + $this->lockWindows; + } + + /** + * Get LockRevision + * + * @return boolean + */ + public function getLockRevision() + { + return $this->lockRevision; + } + + /** + * Set LockRevision + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + public function setLockRevision($pValue = false) + { + $this->lockRevision = $pValue; + return $this; + } + + /** + * Get LockStructure + * + * @return boolean + */ + public function getLockStructure() + { + return $this->lockStructure; + } + + /** + * Set LockStructure + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + public function setLockStructure($pValue = false) + { + $this->lockStructure = $pValue; + return $this; + } + + /** + * Get LockWindows + * + * @return boolean + */ + public function getLockWindows() + { + return $this->lockWindows; + } + + /** + * Set LockWindows + * + * @param boolean $pValue + * @return PHPExcel_DocumentSecurity + */ + public function setLockWindows($pValue = false) + { + $this->lockWindows = $pValue; + return $this; + } + + /** + * Get RevisionsPassword (hashed) + * + * @return string + */ + public function getRevisionsPassword() + { + return $this->revisionsPassword; + } + + /** + * Set RevisionsPassword + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_DocumentSecurity + */ + public function setRevisionsPassword($pValue = '', $pAlreadyHashed = false) + { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->revisionsPassword = $pValue; + return $this; + } + + /** + * Get WorkbookPassword (hashed) + * + * @return string + */ + public function getWorkbookPassword() + { + return $this->workbookPassword; + } + + /** + * Set WorkbookPassword + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_DocumentSecurity + */ + public function setWorkbookPassword($pValue = '', $pAlreadyHashed = false) + { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->workbookPassword = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Exception.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Exception.php new file mode 100644 index 00000000..b27750ea --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Exception.php @@ -0,0 +1,54 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Exception + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Exception extends Exception +{ + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/HashTable.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/HashTable.php new file mode 100644 index 00000000..c21d18c3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/HashTable.php @@ -0,0 +1,204 @@ +<?php + +/** + * PHPExcel_HashTable + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_HashTable +{ + /** + * HashTable elements + * + * @var array + */ + protected $items = array(); + + /** + * HashTable key map + * + * @var array + */ + protected $keyMap = array(); + + /** + * Create a new PHPExcel_HashTable + * + * @param PHPExcel_IComparable[] $pSource Optional source array to create HashTable from + * @throws PHPExcel_Exception + */ + public function __construct($pSource = null) + { + if ($pSource !== null) { + // Create HashTable + $this->addFromSource($pSource); + } + } + + /** + * Add HashTable items from source + * + * @param PHPExcel_IComparable[] $pSource Source array to create HashTable from + * @throws PHPExcel_Exception + */ + public function addFromSource($pSource = null) + { + // Check if an array was passed + if ($pSource == null) { + return; + } elseif (!is_array($pSource)) { + throw new PHPExcel_Exception('Invalid array parameter passed.'); + } + + foreach ($pSource as $item) { + $this->add($item); + } + } + + /** + * Add HashTable item + * + * @param PHPExcel_IComparable $pSource Item to add + * @throws PHPExcel_Exception + */ + public function add(PHPExcel_IComparable $pSource = null) + { + $hash = $pSource->getHashCode(); + if (!isset($this->items[$hash])) { + $this->items[$hash] = $pSource; + $this->keyMap[count($this->items) - 1] = $hash; + } + } + + /** + * Remove HashTable item + * + * @param PHPExcel_IComparable $pSource Item to remove + * @throws PHPExcel_Exception + */ + public function remove(PHPExcel_IComparable $pSource = null) + { + $hash = $pSource->getHashCode(); + if (isset($this->items[$hash])) { + unset($this->items[$hash]); + + $deleteKey = -1; + foreach ($this->keyMap as $key => $value) { + if ($deleteKey >= 0) { + $this->keyMap[$key - 1] = $value; + } + + if ($value == $hash) { + $deleteKey = $key; + } + } + unset($this->keyMap[count($this->keyMap) - 1]); + } + } + + /** + * Clear HashTable + * + */ + public function clear() + { + $this->items = array(); + $this->keyMap = array(); + } + + /** + * Count + * + * @return int + */ + public function count() + { + return count($this->items); + } + + /** + * Get index for hash code + * + * @param string $pHashCode + * @return int Index + */ + public function getIndexForHashCode($pHashCode = '') + { + return array_search($pHashCode, $this->keyMap); + } + + /** + * Get by index + * + * @param int $pIndex + * @return PHPExcel_IComparable + * + */ + public function getByIndex($pIndex = 0) + { + if (isset($this->keyMap[$pIndex])) { + return $this->getByHashCode($this->keyMap[$pIndex]); + } + + return null; + } + + /** + * Get by hashcode + * + * @param string $pHashCode + * @return PHPExcel_IComparable + * + */ + public function getByHashCode($pHashCode = '') + { + if (isset($this->items[$pHashCode])) { + return $this->items[$pHashCode]; + } + + return null; + } + + /** + * HashTable to array + * + * @return PHPExcel_IComparable[] + */ + public function toArray() + { + return $this->items; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Helper/HTML.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Helper/HTML.php new file mode 100644 index 00000000..a78f11c1 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Helper/HTML.php @@ -0,0 +1,808 @@ +<?php + +class PHPExcel_Helper_HTML +{ + protected static $colourMap = array( + 'aliceblue' => 'f0f8ff', + 'antiquewhite' => 'faebd7', + 'antiquewhite1' => 'ffefdb', + 'antiquewhite2' => 'eedfcc', + 'antiquewhite3' => 'cdc0b0', + 'antiquewhite4' => '8b8378', + 'aqua' => '00ffff', + 'aquamarine1' => '7fffd4', + 'aquamarine2' => '76eec6', + 'aquamarine4' => '458b74', + 'azure1' => 'f0ffff', + 'azure2' => 'e0eeee', + 'azure3' => 'c1cdcd', + 'azure4' => '838b8b', + 'beige' => 'f5f5dc', + 'bisque1' => 'ffe4c4', + 'bisque2' => 'eed5b7', + 'bisque3' => 'cdb79e', + 'bisque4' => '8b7d6b', + 'black' => '000000', + 'blanchedalmond' => 'ffebcd', + 'blue' => '0000ff', + 'blue1' => '0000ff', + 'blue2' => '0000ee', + 'blue4' => '00008b', + 'blueviolet' => '8a2be2', + 'brown' => 'a52a2a', + 'brown1' => 'ff4040', + 'brown2' => 'ee3b3b', + 'brown3' => 'cd3333', + 'brown4' => '8b2323', + 'burlywood' => 'deb887', + 'burlywood1' => 'ffd39b', + 'burlywood2' => 'eec591', + 'burlywood3' => 'cdaa7d', + 'burlywood4' => '8b7355', + 'cadetblue' => '5f9ea0', + 'cadetblue1' => '98f5ff', + 'cadetblue2' => '8ee5ee', + 'cadetblue3' => '7ac5cd', + 'cadetblue4' => '53868b', + 'chartreuse1' => '7fff00', + 'chartreuse2' => '76ee00', + 'chartreuse3' => '66cd00', + 'chartreuse4' => '458b00', + 'chocolate' => 'd2691e', + 'chocolate1' => 'ff7f24', + 'chocolate2' => 'ee7621', + 'chocolate3' => 'cd661d', + 'coral' => 'ff7f50', + 'coral1' => 'ff7256', + 'coral2' => 'ee6a50', + 'coral3' => 'cd5b45', + 'coral4' => '8b3e2f', + 'cornflowerblue' => '6495ed', + 'cornsilk1' => 'fff8dc', + 'cornsilk2' => 'eee8cd', + 'cornsilk3' => 'cdc8b1', + 'cornsilk4' => '8b8878', + 'cyan1' => '00ffff', + 'cyan2' => '00eeee', + 'cyan3' => '00cdcd', + 'cyan4' => '008b8b', + 'darkgoldenrod' => 'b8860b', + 'darkgoldenrod1' => 'ffb90f', + 'darkgoldenrod2' => 'eead0e', + 'darkgoldenrod3' => 'cd950c', + 'darkgoldenrod4' => '8b6508', + 'darkgreen' => '006400', + 'darkkhaki' => 'bdb76b', + 'darkolivegreen' => '556b2f', + 'darkolivegreen1' => 'caff70', + 'darkolivegreen2' => 'bcee68', + 'darkolivegreen3' => 'a2cd5a', + 'darkolivegreen4' => '6e8b3d', + 'darkorange' => 'ff8c00', + 'darkorange1' => 'ff7f00', + 'darkorange2' => 'ee7600', + 'darkorange3' => 'cd6600', + 'darkorange4' => '8b4500', + 'darkorchid' => '9932cc', + 'darkorchid1' => 'bf3eff', + 'darkorchid2' => 'b23aee', + 'darkorchid3' => '9a32cd', + 'darkorchid4' => '68228b', + 'darksalmon' => 'e9967a', + 'darkseagreen' => '8fbc8f', + 'darkseagreen1' => 'c1ffc1', + 'darkseagreen2' => 'b4eeb4', + 'darkseagreen3' => '9bcd9b', + 'darkseagreen4' => '698b69', + 'darkslateblue' => '483d8b', + 'darkslategray' => '2f4f4f', + 'darkslategray1' => '97ffff', + 'darkslategray2' => '8deeee', + 'darkslategray3' => '79cdcd', + 'darkslategray4' => '528b8b', + 'darkturquoise' => '00ced1', + 'darkviolet' => '9400d3', + 'deeppink1' => 'ff1493', + 'deeppink2' => 'ee1289', + 'deeppink3' => 'cd1076', + 'deeppink4' => '8b0a50', + 'deepskyblue1' => '00bfff', + 'deepskyblue2' => '00b2ee', + 'deepskyblue3' => '009acd', + 'deepskyblue4' => '00688b', + 'dimgray' => '696969', + 'dodgerblue1' => '1e90ff', + 'dodgerblue2' => '1c86ee', + 'dodgerblue3' => '1874cd', + 'dodgerblue4' => '104e8b', + 'firebrick' => 'b22222', + 'firebrick1' => 'ff3030', + 'firebrick2' => 'ee2c2c', + 'firebrick3' => 'cd2626', + 'firebrick4' => '8b1a1a', + 'floralwhite' => 'fffaf0', + 'forestgreen' => '228b22', + 'fuchsia' => 'ff00ff', + 'gainsboro' => 'dcdcdc', + 'ghostwhite' => 'f8f8ff', + 'gold1' => 'ffd700', + 'gold2' => 'eec900', + 'gold3' => 'cdad00', + 'gold4' => '8b7500', + 'goldenrod' => 'daa520', + 'goldenrod1' => 'ffc125', + 'goldenrod2' => 'eeb422', + 'goldenrod3' => 'cd9b1d', + 'goldenrod4' => '8b6914', + 'gray' => 'bebebe', + 'gray1' => '030303', + 'gray10' => '1a1a1a', + 'gray11' => '1c1c1c', + 'gray12' => '1f1f1f', + 'gray13' => '212121', + 'gray14' => '242424', + 'gray15' => '262626', + 'gray16' => '292929', + 'gray17' => '2b2b2b', + 'gray18' => '2e2e2e', + 'gray19' => '303030', + 'gray2' => '050505', + 'gray20' => '333333', + 'gray21' => '363636', + 'gray22' => '383838', + 'gray23' => '3b3b3b', + 'gray24' => '3d3d3d', + 'gray25' => '404040', + 'gray26' => '424242', + 'gray27' => '454545', + 'gray28' => '474747', + 'gray29' => '4a4a4a', + 'gray3' => '080808', + 'gray30' => '4d4d4d', + 'gray31' => '4f4f4f', + 'gray32' => '525252', + 'gray33' => '545454', + 'gray34' => '575757', + 'gray35' => '595959', + 'gray36' => '5c5c5c', + 'gray37' => '5e5e5e', + 'gray38' => '616161', + 'gray39' => '636363', + 'gray4' => '0a0a0a', + 'gray40' => '666666', + 'gray41' => '696969', + 'gray42' => '6b6b6b', + 'gray43' => '6e6e6e', + 'gray44' => '707070', + 'gray45' => '737373', + 'gray46' => '757575', + 'gray47' => '787878', + 'gray48' => '7a7a7a', + 'gray49' => '7d7d7d', + 'gray5' => '0d0d0d', + 'gray50' => '7f7f7f', + 'gray51' => '828282', + 'gray52' => '858585', + 'gray53' => '878787', + 'gray54' => '8a8a8a', + 'gray55' => '8c8c8c', + 'gray56' => '8f8f8f', + 'gray57' => '919191', + 'gray58' => '949494', + 'gray59' => '969696', + 'gray6' => '0f0f0f', + 'gray60' => '999999', + 'gray61' => '9c9c9c', + 'gray62' => '9e9e9e', + 'gray63' => 'a1a1a1', + 'gray64' => 'a3a3a3', + 'gray65' => 'a6a6a6', + 'gray66' => 'a8a8a8', + 'gray67' => 'ababab', + 'gray68' => 'adadad', + 'gray69' => 'b0b0b0', + 'gray7' => '121212', + 'gray70' => 'b3b3b3', + 'gray71' => 'b5b5b5', + 'gray72' => 'b8b8b8', + 'gray73' => 'bababa', + 'gray74' => 'bdbdbd', + 'gray75' => 'bfbfbf', + 'gray76' => 'c2c2c2', + 'gray77' => 'c4c4c4', + 'gray78' => 'c7c7c7', + 'gray79' => 'c9c9c9', + 'gray8' => '141414', + 'gray80' => 'cccccc', + 'gray81' => 'cfcfcf', + 'gray82' => 'd1d1d1', + 'gray83' => 'd4d4d4', + 'gray84' => 'd6d6d6', + 'gray85' => 'd9d9d9', + 'gray86' => 'dbdbdb', + 'gray87' => 'dedede', + 'gray88' => 'e0e0e0', + 'gray89' => 'e3e3e3', + 'gray9' => '171717', + 'gray90' => 'e5e5e5', + 'gray91' => 'e8e8e8', + 'gray92' => 'ebebeb', + 'gray93' => 'ededed', + 'gray94' => 'f0f0f0', + 'gray95' => 'f2f2f2', + 'gray97' => 'f7f7f7', + 'gray98' => 'fafafa', + 'gray99' => 'fcfcfc', + 'green' => '00ff00', + 'green1' => '00ff00', + 'green2' => '00ee00', + 'green3' => '00cd00', + 'green4' => '008b00', + 'greenyellow' => 'adff2f', + 'honeydew1' => 'f0fff0', + 'honeydew2' => 'e0eee0', + 'honeydew3' => 'c1cdc1', + 'honeydew4' => '838b83', + 'hotpink' => 'ff69b4', + 'hotpink1' => 'ff6eb4', + 'hotpink2' => 'ee6aa7', + 'hotpink3' => 'cd6090', + 'hotpink4' => '8b3a62', + 'indianred' => 'cd5c5c', + 'indianred1' => 'ff6a6a', + 'indianred2' => 'ee6363', + 'indianred3' => 'cd5555', + 'indianred4' => '8b3a3a', + 'ivory1' => 'fffff0', + 'ivory2' => 'eeeee0', + 'ivory3' => 'cdcdc1', + 'ivory4' => '8b8b83', + 'khaki' => 'f0e68c', + 'khaki1' => 'fff68f', + 'khaki2' => 'eee685', + 'khaki3' => 'cdc673', + 'khaki4' => '8b864e', + 'lavender' => 'e6e6fa', + 'lavenderblush1' => 'fff0f5', + 'lavenderblush2' => 'eee0e5', + 'lavenderblush3' => 'cdc1c5', + 'lavenderblush4' => '8b8386', + 'lawngreen' => '7cfc00', + 'lemonchiffon1' => 'fffacd', + 'lemonchiffon2' => 'eee9bf', + 'lemonchiffon3' => 'cdc9a5', + 'lemonchiffon4' => '8b8970', + 'light' => 'eedd82', + 'lightblue' => 'add8e6', + 'lightblue1' => 'bfefff', + 'lightblue2' => 'b2dfee', + 'lightblue3' => '9ac0cd', + 'lightblue4' => '68838b', + 'lightcoral' => 'f08080', + 'lightcyan1' => 'e0ffff', + 'lightcyan2' => 'd1eeee', + 'lightcyan3' => 'b4cdcd', + 'lightcyan4' => '7a8b8b', + 'lightgoldenrod1' => 'ffec8b', + 'lightgoldenrod2' => 'eedc82', + 'lightgoldenrod3' => 'cdbe70', + 'lightgoldenrod4' => '8b814c', + 'lightgoldenrodyellow' => 'fafad2', + 'lightgray' => 'd3d3d3', + 'lightpink' => 'ffb6c1', + 'lightpink1' => 'ffaeb9', + 'lightpink2' => 'eea2ad', + 'lightpink3' => 'cd8c95', + 'lightpink4' => '8b5f65', + 'lightsalmon1' => 'ffa07a', + 'lightsalmon2' => 'ee9572', + 'lightsalmon3' => 'cd8162', + 'lightsalmon4' => '8b5742', + 'lightseagreen' => '20b2aa', + 'lightskyblue' => '87cefa', + 'lightskyblue1' => 'b0e2ff', + 'lightskyblue2' => 'a4d3ee', + 'lightskyblue3' => '8db6cd', + 'lightskyblue4' => '607b8b', + 'lightslateblue' => '8470ff', + 'lightslategray' => '778899', + 'lightsteelblue' => 'b0c4de', + 'lightsteelblue1' => 'cae1ff', + 'lightsteelblue2' => 'bcd2ee', + 'lightsteelblue3' => 'a2b5cd', + 'lightsteelblue4' => '6e7b8b', + 'lightyellow1' => 'ffffe0', + 'lightyellow2' => 'eeeed1', + 'lightyellow3' => 'cdcdb4', + 'lightyellow4' => '8b8b7a', + 'lime' => '00ff00', + 'limegreen' => '32cd32', + 'linen' => 'faf0e6', + 'magenta' => 'ff00ff', + 'magenta2' => 'ee00ee', + 'magenta3' => 'cd00cd', + 'magenta4' => '8b008b', + 'maroon' => 'b03060', + 'maroon1' => 'ff34b3', + 'maroon2' => 'ee30a7', + 'maroon3' => 'cd2990', + 'maroon4' => '8b1c62', + 'medium' => '66cdaa', + 'mediumaquamarine' => '66cdaa', + 'mediumblue' => '0000cd', + 'mediumorchid' => 'ba55d3', + 'mediumorchid1' => 'e066ff', + 'mediumorchid2' => 'd15fee', + 'mediumorchid3' => 'b452cd', + 'mediumorchid4' => '7a378b', + 'mediumpurple' => '9370db', + 'mediumpurple1' => 'ab82ff', + 'mediumpurple2' => '9f79ee', + 'mediumpurple3' => '8968cd', + 'mediumpurple4' => '5d478b', + 'mediumseagreen' => '3cb371', + 'mediumslateblue' => '7b68ee', + 'mediumspringgreen' => '00fa9a', + 'mediumturquoise' => '48d1cc', + 'mediumvioletred' => 'c71585', + 'midnightblue' => '191970', + 'mintcream' => 'f5fffa', + 'mistyrose1' => 'ffe4e1', + 'mistyrose2' => 'eed5d2', + 'mistyrose3' => 'cdb7b5', + 'mistyrose4' => '8b7d7b', + 'moccasin' => 'ffe4b5', + 'navajowhite1' => 'ffdead', + 'navajowhite2' => 'eecfa1', + 'navajowhite3' => 'cdb38b', + 'navajowhite4' => '8b795e', + 'navy' => '000080', + 'navyblue' => '000080', + 'oldlace' => 'fdf5e6', + 'olive' => '808000', + 'olivedrab' => '6b8e23', + 'olivedrab1' => 'c0ff3e', + 'olivedrab2' => 'b3ee3a', + 'olivedrab4' => '698b22', + 'orange' => 'ffa500', + 'orange1' => 'ffa500', + 'orange2' => 'ee9a00', + 'orange3' => 'cd8500', + 'orange4' => '8b5a00', + 'orangered1' => 'ff4500', + 'orangered2' => 'ee4000', + 'orangered3' => 'cd3700', + 'orangered4' => '8b2500', + 'orchid' => 'da70d6', + 'orchid1' => 'ff83fa', + 'orchid2' => 'ee7ae9', + 'orchid3' => 'cd69c9', + 'orchid4' => '8b4789', + 'pale' => 'db7093', + 'palegoldenrod' => 'eee8aa', + 'palegreen' => '98fb98', + 'palegreen1' => '9aff9a', + 'palegreen2' => '90ee90', + 'palegreen3' => '7ccd7c', + 'palegreen4' => '548b54', + 'paleturquoise' => 'afeeee', + 'paleturquoise1' => 'bbffff', + 'paleturquoise2' => 'aeeeee', + 'paleturquoise3' => '96cdcd', + 'paleturquoise4' => '668b8b', + 'palevioletred' => 'db7093', + 'palevioletred1' => 'ff82ab', + 'palevioletred2' => 'ee799f', + 'palevioletred3' => 'cd6889', + 'palevioletred4' => '8b475d', + 'papayawhip' => 'ffefd5', + 'peachpuff1' => 'ffdab9', + 'peachpuff2' => 'eecbad', + 'peachpuff3' => 'cdaf95', + 'peachpuff4' => '8b7765', + 'pink' => 'ffc0cb', + 'pink1' => 'ffb5c5', + 'pink2' => 'eea9b8', + 'pink3' => 'cd919e', + 'pink4' => '8b636c', + 'plum' => 'dda0dd', + 'plum1' => 'ffbbff', + 'plum2' => 'eeaeee', + 'plum3' => 'cd96cd', + 'plum4' => '8b668b', + 'powderblue' => 'b0e0e6', + 'purple' => 'a020f0', + 'rebeccapurple' => '663399', + 'purple1' => '9b30ff', + 'purple2' => '912cee', + 'purple3' => '7d26cd', + 'purple4' => '551a8b', + 'red' => 'ff0000', + 'red1' => 'ff0000', + 'red2' => 'ee0000', + 'red3' => 'cd0000', + 'red4' => '8b0000', + 'rosybrown' => 'bc8f8f', + 'rosybrown1' => 'ffc1c1', + 'rosybrown2' => 'eeb4b4', + 'rosybrown3' => 'cd9b9b', + 'rosybrown4' => '8b6969', + 'royalblue' => '4169e1', + 'royalblue1' => '4876ff', + 'royalblue2' => '436eee', + 'royalblue3' => '3a5fcd', + 'royalblue4' => '27408b', + 'saddlebrown' => '8b4513', + 'salmon' => 'fa8072', + 'salmon1' => 'ff8c69', + 'salmon2' => 'ee8262', + 'salmon3' => 'cd7054', + 'salmon4' => '8b4c39', + 'sandybrown' => 'f4a460', + 'seagreen1' => '54ff9f', + 'seagreen2' => '4eee94', + 'seagreen3' => '43cd80', + 'seagreen4' => '2e8b57', + 'seashell1' => 'fff5ee', + 'seashell2' => 'eee5de', + 'seashell3' => 'cdc5bf', + 'seashell4' => '8b8682', + 'sienna' => 'a0522d', + 'sienna1' => 'ff8247', + 'sienna2' => 'ee7942', + 'sienna3' => 'cd6839', + 'sienna4' => '8b4726', + 'silver' => 'c0c0c0', + 'skyblue' => '87ceeb', + 'skyblue1' => '87ceff', + 'skyblue2' => '7ec0ee', + 'skyblue3' => '6ca6cd', + 'skyblue4' => '4a708b', + 'slateblue' => '6a5acd', + 'slateblue1' => '836fff', + 'slateblue2' => '7a67ee', + 'slateblue3' => '6959cd', + 'slateblue4' => '473c8b', + 'slategray' => '708090', + 'slategray1' => 'c6e2ff', + 'slategray2' => 'b9d3ee', + 'slategray3' => '9fb6cd', + 'slategray4' => '6c7b8b', + 'snow1' => 'fffafa', + 'snow2' => 'eee9e9', + 'snow3' => 'cdc9c9', + 'snow4' => '8b8989', + 'springgreen1' => '00ff7f', + 'springgreen2' => '00ee76', + 'springgreen3' => '00cd66', + 'springgreen4' => '008b45', + 'steelblue' => '4682b4', + 'steelblue1' => '63b8ff', + 'steelblue2' => '5cacee', + 'steelblue3' => '4f94cd', + 'steelblue4' => '36648b', + 'tan' => 'd2b48c', + 'tan1' => 'ffa54f', + 'tan2' => 'ee9a49', + 'tan3' => 'cd853f', + 'tan4' => '8b5a2b', + 'teal' => '008080', + 'thistle' => 'd8bfd8', + 'thistle1' => 'ffe1ff', + 'thistle2' => 'eed2ee', + 'thistle3' => 'cdb5cd', + 'thistle4' => '8b7b8b', + 'tomato1' => 'ff6347', + 'tomato2' => 'ee5c42', + 'tomato3' => 'cd4f39', + 'tomato4' => '8b3626', + 'turquoise' => '40e0d0', + 'turquoise1' => '00f5ff', + 'turquoise2' => '00e5ee', + 'turquoise3' => '00c5cd', + 'turquoise4' => '00868b', + 'violet' => 'ee82ee', + 'violetred' => 'd02090', + 'violetred1' => 'ff3e96', + 'violetred2' => 'ee3a8c', + 'violetred3' => 'cd3278', + 'violetred4' => '8b2252', + 'wheat' => 'f5deb3', + 'wheat1' => 'ffe7ba', + 'wheat2' => 'eed8ae', + 'wheat3' => 'cdba96', + 'wheat4' => '8b7e66', + 'white' => 'ffffff', + 'whitesmoke' => 'f5f5f5', + 'yellow' => 'ffff00', + 'yellow1' => 'ffff00', + 'yellow2' => 'eeee00', + 'yellow3' => 'cdcd00', + 'yellow4' => '8b8b00', + 'yellowgreen' => '9acd32', + ); + + protected $face; + protected $size; + protected $color; + + protected $bold = false; + protected $italic = false; + protected $underline = false; + protected $superscript = false; + protected $subscript = false; + protected $strikethrough = false; + + protected $startTagCallbacks = array( + 'font' => 'startFontTag', + 'b' => 'startBoldTag', + 'strong' => 'startBoldTag', + 'i' => 'startItalicTag', + 'em' => 'startItalicTag', + 'u' => 'startUnderlineTag', + 'ins' => 'startUnderlineTag', + 'del' => 'startStrikethruTag', + 'sup' => 'startSuperscriptTag', + 'sub' => 'startSubscriptTag', + ); + + protected $endTagCallbacks = array( + 'font' => 'endFontTag', + 'b' => 'endBoldTag', + 'strong' => 'endBoldTag', + 'i' => 'endItalicTag', + 'em' => 'endItalicTag', + 'u' => 'endUnderlineTag', + 'ins' => 'endUnderlineTag', + 'del' => 'endStrikethruTag', + 'sup' => 'endSuperscriptTag', + 'sub' => 'endSubscriptTag', + 'br' => 'breakTag', + 'p' => 'breakTag', + 'h1' => 'breakTag', + 'h2' => 'breakTag', + 'h3' => 'breakTag', + 'h4' => 'breakTag', + 'h5' => 'breakTag', + 'h6' => 'breakTag', + ); + + protected $stack = array(); + + protected $stringData = ''; + + protected $richTextObject; + + protected function initialise() + { + $this->face = $this->size = $this->color = null; + $this->bold = $this->italic = $this->underline = $this->superscript = $this->subscript = $this->strikethrough = false; + + $this->stack = array(); + + $this->stringData = ''; + } + + public function toRichTextObject($html) + { + $this->initialise(); + + // Create a new DOM object + $dom = new \DOMDocument; + // Load the HTML file into the DOM object + // Note the use of error suppression, because typically this will be an html fragment, so not fully valid markup + $loaded = @$dom->loadHTML($html); + + // Discard excess white space + $dom->preserveWhiteSpace = false; + + $this->richTextObject = new PHPExcel_RichText();; + $this->parseElements($dom); + + // Clean any further spurious whitespace + $this->cleanWhitespace(); + + return $this->richTextObject; + } + + protected function cleanWhitespace() + { + foreach ($this->richTextObject->getRichTextElements() as $key => $element) { + $text = $element->getText(); + // Trim any leading spaces on the first run + if ($key == 0) { + $text = ltrim($text); + } + // Trim any spaces immediately after a line break + $text = preg_replace('/\n */mu', "\n", $text); + $element->setText($text); + } + } + + protected function buildTextRun() + { + $text = $this->stringData; + if (trim($text) === '') { + return; + } + + $richtextRun = $this->richTextObject->createTextRun($this->stringData); + if ($this->face) { + $richtextRun->getFont()->setName($this->face); + } + if ($this->size) { + $richtextRun->getFont()->setSize($this->size); + } + if ($this->color) { + $richtextRun->getFont()->setColor(new PHPExcel_Style_Color('ff' . $this->color)); + } + if ($this->bold) { + $richtextRun->getFont()->setBold(true); + } + if ($this->italic) { + $richtextRun->getFont()->setItalic(true); + } + if ($this->underline) { + $richtextRun->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } + if ($this->superscript) { + $richtextRun->getFont()->setSuperScript(true); + } + if ($this->subscript) { + $richtextRun->getFont()->setSubScript(true); + } + if ($this->strikethrough) { + $richtextRun->getFont()->setStrikethrough(true); + } + $this->stringData = ''; + } + + protected function rgbToColour($rgb) + { + preg_match_all('/\d+/', $rgb, $values); + foreach ($values[0] as &$value) { + $value = str_pad(dechex($value), 2, '0', STR_PAD_LEFT); + } + return implode($values[0]); + } + + protected function colourNameLookup($rgb) + { + return self::$colourMap[$rgb]; + } + + protected function startFontTag($tag) + { + foreach ($tag->attributes as $attribute) { + $attributeName = strtolower($attribute->name); + $attributeValue = $attribute->value; + + if ($attributeName == 'color') { + if (preg_match('/rgb\s*\(/', $attributeValue)) { + $this->$attributeName = $this->rgbToColour($attributeValue); + } elseif (strpos(trim($attributeValue), '#') === 0) { + $this->$attributeName = ltrim($attributeValue, '#'); + } else { + $this->$attributeName = $this->colourNameLookup($attributeValue); + } + } else { + $this->$attributeName = $attributeValue; + } + } + } + + protected function endFontTag() + { + $this->face = $this->size = $this->color = null; + } + + protected function startBoldTag() + { + $this->bold = true; + } + + protected function endBoldTag() + { + $this->bold = false; + } + + protected function startItalicTag() + { + $this->italic = true; + } + + protected function endItalicTag() + { + $this->italic = false; + } + + protected function startUnderlineTag() + { + $this->underline = true; + } + + protected function endUnderlineTag() + { + $this->underline = false; + } + + protected function startSubscriptTag() + { + $this->subscript = true; + } + + protected function endSubscriptTag() + { + $this->subscript = false; + } + + protected function startSuperscriptTag() + { + $this->superscript = true; + } + + protected function endSuperscriptTag() + { + $this->superscript = false; + } + + protected function startStrikethruTag() + { + $this->strikethrough = true; + } + + protected function endStrikethruTag() + { + $this->strikethrough = false; + } + + protected function breakTag() + { + $this->stringData .= "\n"; + } + + protected function parseTextNode(DOMText $textNode) + { + $domText = preg_replace( + '/\s+/u', + ' ', + str_replace(array("\r", "\n"), ' ', $textNode->nodeValue) + ); + $this->stringData .= $domText; + $this->buildTextRun(); + } + + protected function handleCallback($element, $callbackTag, $callbacks) + { + if (isset($callbacks[$callbackTag])) { + $elementHandler = $callbacks[$callbackTag]; + if (method_exists($this, $elementHandler)) { + call_user_func(array($this, $elementHandler), $element); + } + } + } + + protected function parseElementNode(DOMElement $element) + { + $callbackTag = strtolower($element->nodeName); + $this->stack[] = $callbackTag; + + $this->handleCallback($element, $callbackTag, $this->startTagCallbacks); + + $this->parseElements($element); + array_pop($this->stack); + + $this->handleCallback($element, $callbackTag, $this->endTagCallbacks); + } + + protected function parseElements(DOMNode $element) + { + foreach ($element->childNodes as $child) { + if ($child instanceof DOMText) { + $this->parseTextNode($child); + } elseif ($child instanceof DOMElement) { + $this->parseElementNode($child); + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/IComparable.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/IComparable.php new file mode 100644 index 00000000..6dc36a94 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/IComparable.php @@ -0,0 +1,34 @@ +<?php + +/** + * PHPExcel_IComparable + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_IComparable +{ + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode(); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/IOFactory.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/IOFactory.php new file mode 100644 index 00000000..3ecda177 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/IOFactory.php @@ -0,0 +1,289 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_IOFactory + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_IOFactory +{ + /** + * Search locations + * + * @var array + * @access private + * @static + */ + private static $searchLocations = array( + array( 'type' => 'IWriter', 'path' => 'PHPExcel/Writer/{0}.php', 'class' => 'PHPExcel_Writer_{0}' ), + array( 'type' => 'IReader', 'path' => 'PHPExcel/Reader/{0}.php', 'class' => 'PHPExcel_Reader_{0}' ) + ); + + /** + * Autoresolve classes + * + * @var array + * @access private + * @static + */ + private static $autoResolveClasses = array( + 'Excel2007', + 'Excel5', + 'Excel2003XML', + 'OOCalc', + 'SYLK', + 'Gnumeric', + 'HTML', + 'CSV', + ); + + /** + * Private constructor for PHPExcel_IOFactory + */ + private function __construct() + { + } + + /** + * Get search locations + * + * @static + * @access public + * @return array + */ + public static function getSearchLocations() + { + return self::$searchLocations; + } + + /** + * Set search locations + * + * @static + * @access public + * @param array $value + * @throws PHPExcel_Reader_Exception + */ + public static function setSearchLocations($value) + { + if (is_array($value)) { + self::$searchLocations = $value; + } else { + throw new PHPExcel_Reader_Exception('Invalid parameter passed.'); + } + } + + /** + * Add search location + * + * @static + * @access public + * @param string $type Example: IWriter + * @param string $location Example: PHPExcel/Writer/{0}.php + * @param string $classname Example: PHPExcel_Writer_{0} + */ + public static function addSearchLocation($type = '', $location = '', $classname = '') + { + self::$searchLocations[] = array( 'type' => $type, 'path' => $location, 'class' => $classname ); + } + + /** + * Create PHPExcel_Writer_IWriter + * + * @static + * @access public + * @param PHPExcel $phpExcel + * @param string $writerType Example: Excel2007 + * @return PHPExcel_Writer_IWriter + * @throws PHPExcel_Reader_Exception + */ + public static function createWriter(PHPExcel $phpExcel, $writerType = '') + { + // Search type + $searchType = 'IWriter'; + + // Include class + foreach (self::$searchLocations as $searchLocation) { + if ($searchLocation['type'] == $searchType) { + $className = str_replace('{0}', $writerType, $searchLocation['class']); + + $instance = new $className($phpExcel); + if ($instance !== null) { + return $instance; + } + } + } + + // Nothing found... + throw new PHPExcel_Reader_Exception("No $searchType found for type $writerType"); + } + + /** + * Create PHPExcel_Reader_IReader + * + * @static + * @access public + * @param string $readerType Example: Excel2007 + * @return PHPExcel_Reader_IReader + * @throws PHPExcel_Reader_Exception + */ + public static function createReader($readerType = '') + { + // Search type + $searchType = 'IReader'; + + // Include class + foreach (self::$searchLocations as $searchLocation) { + if ($searchLocation['type'] == $searchType) { + $className = str_replace('{0}', $readerType, $searchLocation['class']); + + $instance = new $className(); + if ($instance !== null) { + return $instance; + } + } + } + + // Nothing found... + throw new PHPExcel_Reader_Exception("No $searchType found for type $readerType"); + } + + /** + * Loads PHPExcel from file using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public static function load($pFilename) + { + $reader = self::createReaderForFile($pFilename); + return $reader->load($pFilename); + } + + /** + * Identify file type using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file to identify + * @return string + * @throws PHPExcel_Reader_Exception + */ + public static function identify($pFilename) + { + $reader = self::createReaderForFile($pFilename); + $className = get_class($reader); + $classType = explode('_', $className); + unset($reader); + return array_pop($classType); + } + + /** + * Create PHPExcel_Reader_IReader for file using automatic PHPExcel_Reader_IReader resolution + * + * @static + * @access public + * @param string $pFilename The name of the spreadsheet file + * @return PHPExcel_Reader_IReader + * @throws PHPExcel_Reader_Exception + */ + public static function createReaderForFile($pFilename) + { + // First, lucky guess by inspecting file extension + $pathinfo = pathinfo($pFilename); + + $extensionType = null; + if (isset($pathinfo['extension'])) { + switch (strtolower($pathinfo['extension'])) { + case 'xlsx': // Excel (OfficeOpenXML) Spreadsheet + case 'xlsm': // Excel (OfficeOpenXML) Macro Spreadsheet (macros will be discarded) + case 'xltx': // Excel (OfficeOpenXML) Template + case 'xltm': // Excel (OfficeOpenXML) Macro Template (macros will be discarded) + $extensionType = 'Excel2007'; + break; + case 'xls': // Excel (BIFF) Spreadsheet + case 'xlt': // Excel (BIFF) Template + $extensionType = 'Excel5'; + break; + case 'ods': // Open/Libre Offic Calc + case 'ots': // Open/Libre Offic Calc Template + $extensionType = 'OOCalc'; + break; + case 'slk': + $extensionType = 'SYLK'; + break; + case 'xml': // Excel 2003 SpreadSheetML + $extensionType = 'Excel2003XML'; + break; + case 'gnumeric': + $extensionType = 'Gnumeric'; + break; + case 'htm': + case 'html': + $extensionType = 'HTML'; + break; + case 'csv': + // Do nothing + // We must not try to use CSV reader since it loads + // all files including Excel files etc. + break; + default: + break; + } + + if ($extensionType !== null) { + $reader = self::createReader($extensionType); + // Let's see if we are lucky + if (isset($reader) && $reader->canRead($pFilename)) { + return $reader; + } + } + } + + // If we reach here then "lucky guess" didn't give any result + // Try walking through all the options in self::$autoResolveClasses + foreach (self::$autoResolveClasses as $autoResolveClass) { + // Ignore our original guess, we know that won't work + if ($autoResolveClass !== $extensionType) { + $reader = self::createReader($autoResolveClass); + if ($reader->canRead($pFilename)) { + return $reader; + } + } + } + + throw new PHPExcel_Reader_Exception('Unable to identify a reader for this file'); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/NamedRange.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/NamedRange.php new file mode 100644 index 00000000..2848db83 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/NamedRange.php @@ -0,0 +1,249 @@ +<?php + +/** + * PHPExcel_NamedRange + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_NamedRange +{ + /** + * Range name + * + * @var string + */ + private $name; + + /** + * Worksheet on which the named range can be resolved + * + * @var PHPExcel_Worksheet + */ + private $worksheet; + + /** + * Range of the referenced cells + * + * @var string + */ + private $range; + + /** + * Is the named range local? (i.e. can only be used on $this->worksheet) + * + * @var bool + */ + private $localOnly; + + /** + * Scope + * + * @var PHPExcel_Worksheet + */ + private $scope; + + /** + * Create a new NamedRange + * + * @param string $pName + * @param PHPExcel_Worksheet $pWorksheet + * @param string $pRange + * @param bool $pLocalOnly + * @param PHPExcel_Worksheet|null $pScope Scope. Only applies when $pLocalOnly = true. Null for global scope. + * @throws PHPExcel_Exception + */ + public function __construct($pName = null, PHPExcel_Worksheet $pWorksheet, $pRange = 'A1', $pLocalOnly = false, $pScope = null) + { + // Validate data + if (($pName === null) || ($pWorksheet === null) || ($pRange === null)) { + throw new PHPExcel_Exception('Parameters can not be null.'); + } + + // Set local members + $this->name = $pName; + $this->worksheet = $pWorksheet; + $this->range = $pRange; + $this->localOnly = $pLocalOnly; + $this->scope = ($pLocalOnly == true) ? (($pScope == null) ? $pWorksheet : $pScope) : null; + } + + /** + * Get name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set name + * + * @param string $value + * @return PHPExcel_NamedRange + */ + public function setName($value = null) + { + if ($value !== null) { + // Old title + $oldTitle = $this->name; + + // Re-attach + if ($this->worksheet !== null) { + $this->worksheet->getParent()->removeNamedRange($this->name, $this->worksheet); + } + $this->name = $value; + + if ($this->worksheet !== null) { + $this->worksheet->getParent()->addNamedRange($this); + } + + // New title + $newTitle = $this->name; + PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->worksheet->getParent(), $oldTitle, $newTitle); + } + return $this; + } + + /** + * Get worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() + { + return $this->worksheet; + } + + /** + * Set worksheet + * + * @param PHPExcel_Worksheet $value + * @return PHPExcel_NamedRange + */ + public function setWorksheet(PHPExcel_Worksheet $value = null) + { + if ($value !== null) { + $this->worksheet = $value; + } + return $this; + } + + /** + * Get range + * + * @return string + */ + public function getRange() + { + return $this->range; + } + + /** + * Set range + * + * @param string $value + * @return PHPExcel_NamedRange + */ + public function setRange($value = null) + { + if ($value !== null) { + $this->range = $value; + } + return $this; + } + + /** + * Get localOnly + * + * @return bool + */ + public function getLocalOnly() + { + return $this->localOnly; + } + + /** + * Set localOnly + * + * @param bool $value + * @return PHPExcel_NamedRange + */ + public function setLocalOnly($value = false) + { + $this->localOnly = $value; + $this->scope = $value ? $this->worksheet : null; + return $this; + } + + /** + * Get scope + * + * @return PHPExcel_Worksheet|null + */ + public function getScope() + { + return $this->scope; + } + + /** + * Set scope + * + * @param PHPExcel_Worksheet|null $value + * @return PHPExcel_NamedRange + */ + public function setScope(PHPExcel_Worksheet $value = null) + { + $this->scope = $value; + $this->localOnly = ($value == null) ? false : true; + return $this; + } + + /** + * Resolve a named range to a regular cell range + * + * @param string $pNamedRange Named range + * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope + * @return PHPExcel_NamedRange + */ + public static function resolveRange($pNamedRange = '', PHPExcel_Worksheet $pSheet) + { + return $pSheet->getParent()->getNamedRange($pNamedRange, $pSheet); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Abstract.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Abstract.php new file mode 100644 index 00000000..189c70a1 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Abstract.php @@ -0,0 +1,289 @@ +<?php + +/** + * PHPExcel_Reader_Abstract + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Read data only? + * Identifies whether the Reader should only read data values for cells, and ignore any formatting information; + * or whether it should read both data and formatting + * + * @var boolean + */ + protected $readDataOnly = false; + + /** + * Read empty cells? + * Identifies whether the Reader should read data values for cells all cells, or should ignore cells containing + * null value or empty string + * + * @var boolean + */ + protected $readEmptyCells = true; + + /** + * Read charts that are defined in the workbook? + * Identifies whether the Reader should read the definitions for any charts that exist in the workbook; + * + * @var boolean + */ + protected $includeCharts = false; + + /** + * Restrict which sheets should be loaded? + * This property holds an array of worksheet names to be loaded. If null, then all worksheets will be loaded. + * + * @var array of string + */ + protected $loadSheetsOnly; + + /** + * PHPExcel_Reader_IReadFilter instance + * + * @var PHPExcel_Reader_IReadFilter + */ + protected $readFilter; + + protected $fileHandle = null; + + + /** + * Read data only? + * If this is true, then the Reader will only read data values for cells, it will not read any formatting information. + * If false (the default) it will read data and formatting. + * + * @return boolean + */ + public function getReadDataOnly() + { + return $this->readDataOnly; + } + + /** + * Set read data only + * Set to true, to advise the Reader only to read data values for cells, and to ignore any formatting information. + * Set to false (the default) to advise the Reader to read both data and formatting for cells. + * + * @param boolean $pValue + * + * @return PHPExcel_Reader_IReader + */ + public function setReadDataOnly($pValue = false) + { + $this->readDataOnly = $pValue; + return $this; + } + + /** + * Read empty cells? + * If this is true (the default), then the Reader will read data values for all cells, irrespective of value. + * If false it will not read data for cells containing a null value or an empty string. + * + * @return boolean + */ + public function getReadEmptyCells() + { + return $this->readEmptyCells; + } + + /** + * Set read empty cells + * Set to true (the default) to advise the Reader read data values for all cells, irrespective of value. + * Set to false to advise the Reader to ignore cells containing a null value or an empty string. + * + * @param boolean $pValue + * + * @return PHPExcel_Reader_IReader + */ + public function setReadEmptyCells($pValue = true) + { + $this->readEmptyCells = $pValue; + return $this; + } + + /** + * Read charts in workbook? + * If this is true, then the Reader will include any charts that exist in the workbook. + * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. + * If false (the default) it will ignore any charts defined in the workbook file. + * + * @return boolean + */ + public function getIncludeCharts() + { + return $this->includeCharts; + } + + /** + * Set read charts in workbook + * Set to true, to advise the Reader to include any charts that exist in the workbook. + * Note that a ReadDataOnly value of false overrides, and charts won't be read regardless of the IncludeCharts value. + * Set to false (the default) to discard charts. + * + * @param boolean $pValue + * + * @return PHPExcel_Reader_IReader + */ + public function setIncludeCharts($pValue = false) + { + $this->includeCharts = (boolean) $pValue; + return $this; + } + + /** + * Get which sheets to load + * Returns either an array of worksheet names (the list of worksheets that should be loaded), or a null + * indicating that all worksheets in the workbook should be loaded. + * + * @return mixed + */ + public function getLoadSheetsOnly() + { + return $this->loadSheetsOnly; + } + + /** + * Set which sheets to load + * + * @param mixed $value + * This should be either an array of worksheet names to be loaded, or a string containing a single worksheet name. + * If NULL, then it tells the Reader to read all worksheets in the workbook + * + * @return PHPExcel_Reader_IReader + */ + public function setLoadSheetsOnly($value = null) + { + if ($value === null) { + return $this->setLoadAllSheets(); + } + + $this->loadSheetsOnly = is_array($value) ? $value : array($value); + return $this; + } + + /** + * Set all sheets to load + * Tells the Reader to load all worksheets from the workbook. + * + * @return PHPExcel_Reader_IReader + */ + public function setLoadAllSheets() + { + $this->loadSheetsOnly = null; + return $this; + } + + /** + * Read filter + * + * @return PHPExcel_Reader_IReadFilter + */ + public function getReadFilter() + { + return $this->readFilter; + } + + /** + * Set read filter + * + * @param PHPExcel_Reader_IReadFilter $pValue + * @return PHPExcel_Reader_IReader + */ + public function setReadFilter(PHPExcel_Reader_IReadFilter $pValue) + { + $this->readFilter = $pValue; + return $this; + } + + /** + * Open file for reading + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + * @return resource + */ + protected function openFile($pFilename) + { + // Check if file exists + if (!file_exists($pFilename) || !is_readable($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Open file + $this->fileHandle = fopen($pFilename, 'r'); + if ($this->fileHandle === false) { + throw new PHPExcel_Reader_Exception("Could not open file " . $pFilename . " for reading."); + } + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + try { + $this->openFile($pFilename); + } catch (Exception $e) { + return false; + } + + $readable = $this->isValidFormat(); + fclose($this->fileHandle); + return $readable; + } + + /** + * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks + * + * @param string $xml + * @throws PHPExcel_Reader_Exception + */ + public function securityScan($xml) + { + $pattern = '/\\0?' . implode('\\0?', str_split('<!DOCTYPE')) . '\\0?/'; + if (preg_match($pattern, $xml)) { + throw new PHPExcel_Reader_Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); + } + return $xml; + } + + /** + * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks + * + * @param string $filestream + * @throws PHPExcel_Reader_Exception + */ + public function securityScanFile($filestream) + { + return $this->securityScan(file_get_contents($filestream)); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/CSV.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/CSV.php new file mode 100644 index 00000000..21329dad --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/CSV.php @@ -0,0 +1,406 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_CSV + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_CSV extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Input encoding + * + * @access private + * @var string + */ + private $inputEncoding = 'UTF-8'; + + /** + * Delimiter + * + * @access private + * @var string + */ + private $delimiter = ','; + + /** + * Enclosure + * + * @access private + * @var string + */ + private $enclosure = '"'; + + /** + * Sheet index to read + * + * @access private + * @var int + */ + private $sheetIndex = 0; + + /** + * Load rows contiguously + * + * @access private + * @var int + */ + private $contiguous = false; + + /** + * Row counter for loading rows contiguously + * + * @var int + */ + private $contiguousRow = -1; + + + /** + * Create a new PHPExcel_Reader_CSV + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is a CSV file + * + * @return boolean + */ + protected function isValidFormat() + { + return true; + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'UTF-8') + { + $this->inputEncoding = $pValue; + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->inputEncoding; + } + + /** + * Move filepointer past any BOM marker + * + */ + protected function skipBOM() + { + rewind($this->fileHandle); + + switch ($this->inputEncoding) { + case 'UTF-8': + fgets($this->fileHandle, 4) == "\xEF\xBB\xBF" ? + fseek($this->fileHandle, 3) : fseek($this->fileHandle, 0); + break; + case 'UTF-16LE': + fgets($this->fileHandle, 3) == "\xFF\xFE" ? + fseek($this->fileHandle, 2) : fseek($this->fileHandle, 0); + break; + case 'UTF-16BE': + fgets($this->fileHandle, 3) == "\xFE\xFF" ? + fseek($this->fileHandle, 2) : fseek($this->fileHandle, 0); + break; + case 'UTF-32LE': + fgets($this->fileHandle, 5) == "\xFF\xFE\x00\x00" ? + fseek($this->fileHandle, 4) : fseek($this->fileHandle, 0); + break; + case 'UTF-32BE': + fgets($this->fileHandle, 5) == "\x00\x00\xFE\xFF" ? + fseek($this->fileHandle, 4) : fseek($this->fileHandle, 0); + break; + default: + break; + } + } + + /** + * Identify any separator that is explicitly set in the file + * + */ + protected function checkSeparator() + { + $line = fgets($this->fileHandle); + if ($line === false) { + return; + } + + if ((strlen(trim($line, "\r\n")) == 5) && (stripos($line, 'sep=') === 0)) { + $this->delimiter = substr($line, 4, 1); + return; + } + return $this->skipBOM(); + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Open file + $this->openFile($pFilename); + if (!$this->isValidFormat()) { + fclose($this->fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->fileHandle; + + // Skip BOM, if any + $this->skipBOM(); + $this->checkSeparator(); + + $escapeEnclosures = array( "\\" . $this->enclosure, $this->enclosure . $this->enclosure ); + + $worksheetInfo = array(); + $worksheetInfo[0]['worksheetName'] = 'Worksheet'; + $worksheetInfo[0]['lastColumnLetter'] = 'A'; + $worksheetInfo[0]['lastColumnIndex'] = 0; + $worksheetInfo[0]['totalRows'] = 0; + $worksheetInfo[0]['totalColumns'] = 0; + + // Loop through each line of the file in turn + while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure)) !== false) { + $worksheetInfo[0]['totalRows']++; + $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], count($rowData) - 1); + } + + $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); + $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; + + // Close file + fclose($fileHandle); + + return $worksheetInfo; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + $lineEnding = ini_get('auto_detect_line_endings'); + ini_set('auto_detect_line_endings', true); + + // Open file + $this->openFile($pFilename); + if (!$this->isValidFormat()) { + fclose($this->fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->fileHandle; + + // Skip BOM, if any + $this->skipBOM(); + $this->checkSeparator(); + + // Create new PHPExcel object + while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) { + $objPHPExcel->createSheet(); + } + $sheet = $objPHPExcel->setActiveSheetIndex($this->sheetIndex); + + $escapeEnclosures = array( "\\" . $this->enclosure, + $this->enclosure . $this->enclosure + ); + + // Set our starting row based on whether we're in contiguous mode or not + $currentRow = 1; + if ($this->contiguous) { + $currentRow = ($this->contiguousRow == -1) ? $sheet->getHighestRow(): $this->contiguousRow; + } + + // Loop through each line of the file in turn + while (($rowData = fgetcsv($fileHandle, 0, $this->delimiter, $this->enclosure)) !== false) { + $columnLetter = 'A'; + foreach ($rowData as $rowDatum) { + if ($rowDatum != '' && $this->readFilter->readCell($columnLetter, $currentRow)) { + // Unescape enclosures + $rowDatum = str_replace($escapeEnclosures, $this->enclosure, $rowDatum); + + // Convert encoding if necessary + if ($this->inputEncoding !== 'UTF-8') { + $rowDatum = PHPExcel_Shared_String::ConvertEncoding($rowDatum, 'UTF-8', $this->inputEncoding); + } + + // Set cell value + $sheet->getCell($columnLetter . $currentRow)->setValue($rowDatum); + } + ++$columnLetter; + } + ++$currentRow; + } + + // Close file + fclose($fileHandle); + + if ($this->contiguous) { + $this->contiguousRow = $currentRow; + } + + ini_set('auto_detect_line_endings', $lineEnding); + + // Return + return $objPHPExcel; + } + + /** + * Get delimiter + * + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * Set delimiter + * + * @param string $pValue Delimiter, defaults to , + * @return PHPExcel_Reader_CSV + */ + public function setDelimiter($pValue = ',') + { + $this->delimiter = $pValue; + return $this; + } + + /** + * Get enclosure + * + * @return string + */ + public function getEnclosure() + { + return $this->enclosure; + } + + /** + * Set enclosure + * + * @param string $pValue Enclosure, defaults to " + * @return PHPExcel_Reader_CSV + */ + public function setEnclosure($pValue = '"') + { + if ($pValue == '') { + $pValue = '"'; + } + $this->enclosure = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return integer + */ + public function getSheetIndex() + { + return $this->sheetIndex; + } + + /** + * Set sheet index + * + * @param integer $pValue Sheet index + * @return PHPExcel_Reader_CSV + */ + public function setSheetIndex($pValue = 0) + { + $this->sheetIndex = $pValue; + return $this; + } + + /** + * Set Contiguous + * + * @param boolean $contiguous + */ + public function setContiguous($contiguous = false) + { + $this->contiguous = (bool) $contiguous; + if (!$contiguous) { + $this->contiguousRow = -1; + } + + return $this; + } + + /** + * Get Contiguous + * + * @return boolean + */ + public function getContiguous() + { + return $this->contiguous; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/DefaultReadFilter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/DefaultReadFilter.php new file mode 100644 index 00000000..ea25f63c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/DefaultReadFilter.php @@ -0,0 +1,51 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_DefaultReadFilter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_DefaultReadFilter implements PHPExcel_Reader_IReadFilter +{ + /** + * Should this cell be read? + * + * @param $column Column address (as a string value like "A", or "IV") + * @param $row Row number + * @param $worksheetName Optional worksheet name + * @return boolean + */ + public function readCell($column, $row, $worksheetName = '') + { + return true; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2003XML.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2003XML.php new file mode 100644 index 00000000..c007f9bb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2003XML.php @@ -0,0 +1,801 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_Excel2003XML + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Excel2003XML extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Formats + * + * @var array + */ + protected $styles = array(); + + /** + * Character set used in the file + * + * @var string + */ + protected $charSet = 'UTF-8'; + + /** + * Create a new PHPExcel_Reader_Excel2003XML + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + + // Office xmlns:o="urn:schemas-microsoft-com:office:office" + // Excel xmlns:x="urn:schemas-microsoft-com:office:excel" + // XML Spreadsheet xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" + // Spreadsheet component xmlns:c="urn:schemas-microsoft-com:office:component:spreadsheet" + // XML schema xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" + // XML data type xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" + // MS-persist recordset xmlns:rs="urn:schemas-microsoft-com:rowset" + // Rowset xmlns:z="#RowsetSchema" + // + + $signature = array( + '<?xml version="1.0"', + '<?mso-application progid="Excel.Sheet"?>' + ); + + // Open file + $this->openFile($pFilename); + $fileHandle = $this->fileHandle; + + // Read sample data (first 2 KB will do) + $data = fread($fileHandle, 2048); + fclose($fileHandle); + + $valid = true; + foreach ($signature as $match) { + // every part of the signature must be present + if (strpos($data, $match) === false) { + $valid = false; + break; + } + } + + // Retrieve charset encoding + if (preg_match('/<?xml.*encoding=[\'"](.*?)[\'"].*?>/um', $data, $matches)) { + $this->charSet = strtoupper($matches[1]); + } +// echo 'Character Set is ', $this->charSet,'<br />'; + + return $valid; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + if (!$this->canRead($pFilename)) { + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + + $worksheetNames = array(); + + $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $xml_ss = $xml->children($namespaces['ss']); + foreach ($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + $worksheetNames[] = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet); + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $worksheetID = 1; + $xml_ss = $xml->children($namespaces['ss']); + foreach ($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + + $tmpInfo = array(); + $tmpInfo['worksheetName'] = ''; + $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['lastColumnIndex'] = 0; + $tmpInfo['totalRows'] = 0; + $tmpInfo['totalColumns'] = 0; + + if (isset($worksheet_ss['Name'])) { + $tmpInfo['worksheetName'] = (string) $worksheet_ss['Name']; + } else { + $tmpInfo['worksheetName'] = "Worksheet_{$worksheetID}"; + } + + if (isset($worksheet->Table->Row)) { + $rowIndex = 0; + + foreach ($worksheet->Table->Row as $rowData) { + $columnIndex = 0; + $rowHasData = false; + + foreach ($rowData->Cell as $cell) { + if (isset($cell->Data)) { + $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); + $rowHasData = true; + } + + ++$columnIndex; + } + + ++$rowIndex; + + if ($rowHasData) { + $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); + } + } + } + + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; + + $worksheetInfo[] = $tmpInfo; + ++$worksheetID; + } + + return $worksheetInfo; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + $objPHPExcel->removeSheetByIndex(0); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + protected static function identifyFixedStyleValue($styleList, &$styleAttributeValue) + { + $styleAttributeValue = strtolower($styleAttributeValue); + foreach ($styleList as $style) { + if ($styleAttributeValue == strtolower($style)) { + $styleAttributeValue = $style; + return true; + } + } + return false; + } + + /** + * pixel units to excel width units(units of 1/256th of a character width) + * @param pxs + * @return + */ + protected static function pixel2WidthUnits($pxs) + { + $UNIT_OFFSET_MAP = array(0, 36, 73, 109, 146, 182, 219); + + $widthUnits = 256 * ($pxs / 7); + $widthUnits += $UNIT_OFFSET_MAP[($pxs % 7)]; + return $widthUnits; + } + + /** + * excel width units(units of 1/256th of a character width) to pixel units + * @param widthUnits + * @return + */ + protected static function widthUnits2Pixel($widthUnits) + { + $pixels = ($widthUnits / 256) * 7; + $offsetWidthUnits = $widthUnits % 256; + $pixels += round($offsetWidthUnits / (256 / 7)); + return $pixels; + } + + protected static function hex2str($hex) + { + return chr(hexdec($hex[1])); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + $fromFormats = array('\-', '\ '); + $toFormats = array('-', ' '); + + $underlineStyles = array ( + PHPExcel_Style_Font::UNDERLINE_NONE, + PHPExcel_Style_Font::UNDERLINE_DOUBLE, + PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING, + PHPExcel_Style_Font::UNDERLINE_SINGLE, + PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING + ); + $verticalAlignmentStyles = array ( + PHPExcel_Style_Alignment::VERTICAL_BOTTOM, + PHPExcel_Style_Alignment::VERTICAL_TOP, + PHPExcel_Style_Alignment::VERTICAL_CENTER, + PHPExcel_Style_Alignment::VERTICAL_JUSTIFY + ); + $horizontalAlignmentStyles = array ( + PHPExcel_Style_Alignment::HORIZONTAL_GENERAL, + PHPExcel_Style_Alignment::HORIZONTAL_LEFT, + PHPExcel_Style_Alignment::HORIZONTAL_RIGHT, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS, + PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY + ); + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + if (!$this->canRead($pFilename)) { + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + + $xml = simplexml_load_string($this->securityScan(file_get_contents($pFilename)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespaces = $xml->getNamespaces(true); + + $docProps = $objPHPExcel->getProperties(); + if (isset($xml->DocumentProperties[0])) { + foreach ($xml->DocumentProperties[0] as $propertyName => $propertyValue) { + switch ($propertyName) { + case 'Title': + $docProps->setTitle(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Subject': + $docProps->setSubject(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Author': + $docProps->setCreator(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Created': + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + break; + case 'LastAuthor': + $docProps->setLastModifiedBy(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'LastSaved': + $lastSaveDate = strtotime($propertyValue); + $docProps->setModified($lastSaveDate); + break; + case 'Company': + $docProps->setCompany(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Category': + $docProps->setCategory(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Manager': + $docProps->setManager(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Keywords': + $docProps->setKeywords(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + case 'Description': + $docProps->setDescription(self::convertStringEncoding($propertyValue, $this->charSet)); + break; + } + } + } + if (isset($xml->CustomDocumentProperties)) { + foreach ($xml->CustomDocumentProperties[0] as $propertyName => $propertyValue) { + $propertyAttributes = $propertyValue->attributes($namespaces['dt']); + $propertyName = preg_replace_callback('/_x([0-9a-z]{4})_/', 'PHPExcel_Reader_Excel2003XML::hex2str', $propertyName); + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_UNKNOWN; + switch ((string) $propertyAttributes) { + case 'string': + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + $propertyValue = trim($propertyValue); + break; + case 'boolean': + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN; + $propertyValue = (bool) $propertyValue; + break; + case 'integer': + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_INTEGER; + $propertyValue = intval($propertyValue); + break; + case 'float': + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT; + $propertyValue = floatval($propertyValue); + break; + case 'dateTime.tz': + $propertyType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE; + $propertyValue = strtotime(trim($propertyValue)); + break; + } + $docProps->setCustomProperty($propertyName, $propertyValue, $propertyType); + } + } + + foreach ($xml->Styles[0] as $style) { + $style_ss = $style->attributes($namespaces['ss']); + $styleID = (string) $style_ss['ID']; +// echo 'Style ID = '.$styleID.'<br />'; + $this->styles[$styleID] = (isset($this->styles['Default'])) ? $this->styles['Default'] : array(); + foreach ($style as $styleType => $styleData) { + $styleAttributes = $styleData->attributes($namespaces['ss']); +// echo $styleType.'<br />'; + switch ($styleType) { + case 'Alignment': + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'Vertical': + if (self::identifyFixedStyleValue($verticalAlignmentStyles, $styleAttributeValue)) { + $this->styles[$styleID]['alignment']['vertical'] = $styleAttributeValue; + } + break; + case 'Horizontal': + if (self::identifyFixedStyleValue($horizontalAlignmentStyles, $styleAttributeValue)) { + $this->styles[$styleID]['alignment']['horizontal'] = $styleAttributeValue; + } + break; + case 'WrapText': + $this->styles[$styleID]['alignment']['wrap'] = true; + break; + } + } + break; + case 'Borders': + foreach ($styleData->Border as $borderStyle) { + $borderAttributes = $borderStyle->attributes($namespaces['ss']); + $thisBorder = array(); + foreach ($borderAttributes as $borderStyleKey => $borderStyleValue) { +// echo $borderStyleKey.' = '.$borderStyleValue.'<br />'; + switch ($borderStyleKey) { + case 'LineStyle': + $thisBorder['style'] = PHPExcel_Style_Border::BORDER_MEDIUM; +// $thisBorder['style'] = $borderStyleValue; + break; + case 'Weight': +// $thisBorder['style'] = $borderStyleValue; + break; + case 'Position': + $borderPosition = strtolower($borderStyleValue); + break; + case 'Color': + $borderColour = substr($borderStyleValue, 1); + $thisBorder['color']['rgb'] = $borderColour; + break; + } + } + if (!empty($thisBorder)) { + if (($borderPosition == 'left') || ($borderPosition == 'right') || ($borderPosition == 'top') || ($borderPosition == 'bottom')) { + $this->styles[$styleID]['borders'][$borderPosition] = $thisBorder; + } + } + } + break; + case 'Font': + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; + $styleAttributeValue = (string) $styleAttributeValue; + switch ($styleAttributeKey) { + case 'FontName': + $this->styles[$styleID]['font']['name'] = $styleAttributeValue; + break; + case 'Size': + $this->styles[$styleID]['font']['size'] = $styleAttributeValue; + break; + case 'Color': + $this->styles[$styleID]['font']['color']['rgb'] = substr($styleAttributeValue, 1); + break; + case 'Bold': + $this->styles[$styleID]['font']['bold'] = true; + break; + case 'Italic': + $this->styles[$styleID]['font']['italic'] = true; + break; + case 'Underline': + if (self::identifyFixedStyleValue($underlineStyles, $styleAttributeValue)) { + $this->styles[$styleID]['font']['underline'] = $styleAttributeValue; + } + break; + } + } + break; + case 'Interior': + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; + switch ($styleAttributeKey) { + case 'Color': + $this->styles[$styleID]['fill']['color']['rgb'] = substr($styleAttributeValue, 1); + break; + } + } + break; + case 'NumberFormat': + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; + $styleAttributeValue = str_replace($fromFormats, $toFormats, $styleAttributeValue); + switch ($styleAttributeValue) { + case 'Short Date': + $styleAttributeValue = 'dd/mm/yyyy'; + break; + } + if ($styleAttributeValue > '') { + $this->styles[$styleID]['numberformat']['code'] = $styleAttributeValue; + } + } + break; + case 'Protection': + foreach ($styleAttributes as $styleAttributeKey => $styleAttributeValue) { +// echo $styleAttributeKey.' = '.$styleAttributeValue.'<br />'; + } + break; + } + } +// print_r($this->styles[$styleID]); +// echo '<hr />'; + } +// echo '<hr />'; + + $worksheetID = 0; + $xml_ss = $xml->children($namespaces['ss']); + + foreach ($xml_ss->Worksheet as $worksheet) { + $worksheet_ss = $worksheet->attributes($namespaces['ss']); + + if ((isset($this->loadSheetsOnly)) && (isset($worksheet_ss['Name'])) && + (!in_array($worksheet_ss['Name'], $this->loadSheetsOnly))) { + continue; + } + +// echo '<h3>Worksheet: ', $worksheet_ss['Name'],'<h3>'; +// + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + if (isset($worksheet_ss['Name'])) { + $worksheetName = self::convertStringEncoding((string) $worksheet_ss['Name'], $this->charSet); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in + // formula cells... during the load, all formulae should be correct, and we're simply bringing + // the worksheet name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName, false); + } + + $columnID = 'A'; + if (isset($worksheet->Table->Column)) { + foreach ($worksheet->Table->Column as $columnData) { + $columnData_ss = $columnData->attributes($namespaces['ss']); + if (isset($columnData_ss['Index'])) { + $columnID = PHPExcel_Cell::stringFromColumnIndex($columnData_ss['Index']-1); + } + if (isset($columnData_ss['Width'])) { + $columnWidth = $columnData_ss['Width']; +// echo '<b>Setting column width for '.$columnID.' to '.$columnWidth.'</b><br />'; + $objPHPExcel->getActiveSheet()->getColumnDimension($columnID)->setWidth($columnWidth / 5.4); + } + ++$columnID; + } + } + + $rowID = 1; + if (isset($worksheet->Table->Row)) { + $additionalMergedCells = 0; + foreach ($worksheet->Table->Row as $rowData) { + $rowHasData = false; + $row_ss = $rowData->attributes($namespaces['ss']); + if (isset($row_ss['Index'])) { + $rowID = (integer) $row_ss['Index']; + } +// echo '<b>Row '.$rowID.'</b><br />'; + + $columnID = 'A'; + foreach ($rowData->Cell as $cell) { + $cell_ss = $cell->attributes($namespaces['ss']); + if (isset($cell_ss['Index'])) { + $columnID = PHPExcel_Cell::stringFromColumnIndex($cell_ss['Index']-1); + } + $cellRange = $columnID.$rowID; + + if ($this->getReadFilter() !== null) { + if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { + continue; + } + } + + if ((isset($cell_ss['MergeAcross'])) || (isset($cell_ss['MergeDown']))) { + $columnTo = $columnID; + if (isset($cell_ss['MergeAcross'])) { + $additionalMergedCells += (int)$cell_ss['MergeAcross']; + $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cell_ss['MergeAcross'] -1); + } + $rowTo = $rowID; + if (isset($cell_ss['MergeDown'])) { + $rowTo = $rowTo + $cell_ss['MergeDown']; + } + $cellRange .= ':'.$columnTo.$rowTo; + $objPHPExcel->getActiveSheet()->mergeCells($cellRange); + } + + $cellIsSet = $hasCalculatedValue = false; + $cellDataFormula = ''; + if (isset($cell_ss['Formula'])) { + $cellDataFormula = $cell_ss['Formula']; + // added this as a check for array formulas + if (isset($cell_ss['ArrayRange'])) { + $cellDataCSEFormula = $cell_ss['ArrayRange']; +// echo "found an array formula at ".$columnID.$rowID."<br />"; + } + $hasCalculatedValue = true; + } + if (isset($cell->Data)) { + $cellValue = $cellData = $cell->Data; + $type = PHPExcel_Cell_DataType::TYPE_NULL; + $cellData_ss = $cellData->attributes($namespaces['ss']); + if (isset($cellData_ss['Type'])) { + $cellDataType = $cellData_ss['Type']; + switch ($cellDataType) { + /* + const TYPE_STRING = 's'; + const TYPE_FORMULA = 'f'; + const TYPE_NUMERIC = 'n'; + const TYPE_BOOL = 'b'; + const TYPE_NULL = 'null'; + const TYPE_INLINE = 'inlineStr'; + const TYPE_ERROR = 'e'; + */ + case 'String': + $cellValue = self::convertStringEncoding($cellValue, $this->charSet); + $type = PHPExcel_Cell_DataType::TYPE_STRING; + break; + case 'Number': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $cellValue = (float) $cellValue; + if (floor($cellValue) == $cellValue) { + $cellValue = (integer) $cellValue; + } + break; + case 'Boolean': + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $cellValue = ($cellValue != 0); + break; + case 'DateTime': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $cellValue = PHPExcel_Shared_Date::PHPToExcel(strtotime($cellValue)); + break; + case 'Error': + $type = PHPExcel_Cell_DataType::TYPE_ERROR; + break; + } + } + + if ($hasCalculatedValue) { +// echo 'FORMULA<br />'; + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + $columnNumber = PHPExcel_Cell::columnIndexFromString($columnID); + if (substr($cellDataFormula, 0, 3) == 'of:') { + $cellDataFormula = substr($cellDataFormula, 3); +// echo 'Before: ', $cellDataFormula,'<br />'; + $temp = explode('"', $cellDataFormula); + $key = false; + foreach ($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + $value = str_replace(array('[.', '.', ']'), '', $value); + } + } + } else { + // Convert R1C1 style references to A1 style references (but only when not quoted) +// echo 'Before: ', $cellDataFormula,'<br />'; + $temp = explode('"', $cellDataFormula); + $key = false; + foreach ($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($key = !$key) { + preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER + PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach ($cellReferences as $cellReference) { + $rowReference = $cellReference[2][0]; + // Empty R reference is the current row + if ($rowReference == '') { + $rowReference = $rowID; + } + // Bracketed R references are relative to the current row + if ($rowReference{0} == '[') { + $rowReference = $rowID + trim($rowReference, '[]'); + } + $columnReference = $cellReference[4][0]; + // Empty C reference is the current column + if ($columnReference == '') { + $columnReference = $columnNumber; + } + // Bracketed C references are relative to the current column + if ($columnReference{0} == '[') { + $columnReference = $columnNumber + trim($columnReference, '[]'); + } + $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; + $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); + } + } + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"', $temp); +// echo 'After: ', $cellDataFormula,'<br />'; + } + +// echo 'Cell '.$columnID.$rowID.' is a '.$type.' with a value of '.(($hasCalculatedValue) ? $cellDataFormula : $cellValue).'<br />'; +// + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $cellValue), $type); + if ($hasCalculatedValue) { +// echo 'Formula result is '.$cellValue.'<br />'; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setCalculatedValue($cellValue); + } + $cellIsSet = $rowHasData = true; + } + + if (isset($cell->Comment)) { +// echo '<b>comment found</b><br />'; + $commentAttributes = $cell->Comment->attributes($namespaces['ss']); + $author = 'unknown'; + if (isset($commentAttributes->Author)) { + $author = (string)$commentAttributes->Author; +// echo 'Author: ', $author,'<br />'; + } + $node = $cell->Comment->Data->asXML(); +// $annotation = str_replace('html:','',substr($node,49,-10)); +// echo $annotation,'<br />'; + $annotation = strip_tags($node); +// echo 'Annotation: ', $annotation,'<br />'; + $objPHPExcel->getActiveSheet()->getComment($columnID.$rowID)->setAuthor(self::convertStringEncoding($author, $this->charSet))->setText($this->parseRichText($annotation)); + } + + if (($cellIsSet) && (isset($cell_ss['StyleID']))) { + $style = (string) $cell_ss['StyleID']; +// echo 'Cell style for '.$columnID.$rowID.' is '.$style.'<br />'; + if ((isset($this->styles[$style])) && (!empty($this->styles[$style]))) { +// echo 'Cell '.$columnID.$rowID.'<br />'; +// print_r($this->styles[$style]); +// echo '<br />'; + if (!$objPHPExcel->getActiveSheet()->cellExists($columnID.$rowID)) { + $objPHPExcel->getActiveSheet()->getCell($columnID.$rowID)->setValue(null); + } + $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($this->styles[$style]); + } + } + ++$columnID; + while ($additionalMergedCells > 0) { + ++$columnID; + $additionalMergedCells--; + } + } + + if ($rowHasData) { + if (isset($row_ss['StyleID'])) { + $rowStyle = $row_ss['StyleID']; + } + if (isset($row_ss['Height'])) { + $rowHeight = $row_ss['Height']; +// echo '<b>Setting row height to '.$rowHeight.'</b><br />'; + $objPHPExcel->getActiveSheet()->getRowDimension($rowID)->setRowHeight($rowHeight); + } + } + + ++$rowID; + } + } + ++$worksheetID; + } + + // Return + return $objPHPExcel; + } + + + protected static function convertStringEncoding($string, $charset) + { + if ($charset != 'UTF-8') { + return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', $charset); + } + return $string; + } + + + protected function parseRichText($is = '') + { + $value = new PHPExcel_RichText(); + + $value->createText(self::convertStringEncoding($is, $this->charSet)); + + return $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007.php new file mode 100644 index 00000000..1932df4b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007.php @@ -0,0 +1,2051 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_Excel2007 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Excel2007 extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * PHPExcel_ReferenceHelper instance + * + * @var PHPExcel_ReferenceHelper + */ + private $referenceHelper = null; + + /** + * PHPExcel_Reader_Excel2007_Theme instance + * + * @var PHPExcel_Reader_Excel2007_Theme + */ + private static $theme = null; + + /** + * Create a new PHPExcel_Reader_Excel2007 instance + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + $this->referenceHelper = PHPExcel_ReferenceHelper::getInstance(); + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + // Check if zip class exists +// if (!class_exists($zipClass, false)) { +// throw new PHPExcel_Reader_Exception($zipClass . " library is not enabled"); +// } + + $xl = false; + // Load file + $zip = new $zipClass; + if ($zip->open($pFilename) === true) { + // check if it is an OOXML archive + $rels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if ($rels !== false) { + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + if (basename($rel["Target"]) == 'workbook.xml') { + $xl = true; + } + break; + + } + } + } + $zip->close(); + } + + return $xl; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetNames = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // The files we're looking at here are small enough that simpleXML is more efficient than XMLReader + $rels = simplexml_load_string( + $this->securityScan($this->getFromZipArchive($zip, "_rels/.rels"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()) + ); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $xmlWorkbook = simplexml_load_string( + $this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}"), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()) + ); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + // Check if sheet should be skipped + $worksheetNames[] = (string) $eleSheet["name"]; + } + } + } + } + + $zip->close(); + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + $rels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + if ($rel["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument") { + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $worksheets = array(); + foreach ($relsWorkbook->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet") { + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + } + } + + $xmlWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if ($xmlWorkbook->sheets) { + $dir = dirname($rel["Target"]); + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + $tmpInfo = array( + 'worksheetName' => (string) $eleSheet["name"], + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + + $xml = new XMLReader(); + $res = $xml->xml($this->securityScanFile('zip://'.PHPExcel_Shared_File::realpath($pFilename).'#'."$dir/$fileWorksheet"), null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2, true); + + $currCells = 0; + while ($xml->read()) { + if ($xml->name == 'row' && $xml->nodeType == XMLReader::ELEMENT) { + $row = $xml->getAttribute('r'); + $tmpInfo['totalRows'] = $row; + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); + $currCells = 0; + } elseif ($xml->name == 'c' && $xml->nodeType == XMLReader::ELEMENT) { + $currCells++; + } + } + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); + $xml->close(); + + $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + + $worksheetInfo[] = $tmpInfo; + } + } + } + } + + $zip->close(); + + return $worksheetInfo; + } + + private static function castToBoolean($c) + { +// echo 'Initial Cast to Boolean', PHP_EOL; + $value = isset($c->v) ? (string) $c->v : null; + if ($value == '0') { + return false; + } elseif ($value == '1') { + return true; + } else { + return (bool)$c->v; + } + return $value; + } + + private static function castToError($c) + { +// echo 'Initial Cast to Error', PHP_EOL; + return isset($c->v) ? (string) $c->v : null; + } + + private static function castToString($c) + { +// echo 'Initial Cast to String, PHP_EOL; + return isset($c->v) ? (string) $c->v : null; + } + + private function castToFormula($c, $r, &$cellDataType, &$value, &$calculatedValue, &$sharedFormulas, $castBaseType) + { +// echo 'Formula', PHP_EOL; +// echo '$c->f is ', $c->f, PHP_EOL; + $cellDataType = 'f'; + $value = "={$c->f}"; + $calculatedValue = self::$castBaseType($c); + + // Shared formula? + if (isset($c->f['t']) && strtolower((string)$c->f['t']) == 'shared') { +// echo 'SHARED FORMULA', PHP_EOL; + $instance = (string)$c->f['si']; + +// echo 'Instance ID = ', $instance, PHP_EOL; +// +// echo 'Shared Formula Array:', PHP_EOL; +// print_r($sharedFormulas); + if (!isset($sharedFormulas[(string)$c->f['si']])) { +// echo 'SETTING NEW SHARED FORMULA', PHP_EOL; +// echo 'Master is ', $r, PHP_EOL; +// echo 'Formula is ', $value, PHP_EOL; + $sharedFormulas[$instance] = array('master' => $r, 'formula' => $value); +// echo 'New Shared Formula Array:', PHP_EOL; +// print_r($sharedFormulas); + } else { +// echo 'GETTING SHARED FORMULA', PHP_EOL; +// echo 'Master is ', $sharedFormulas[$instance]['master'], PHP_EOL; +// echo 'Formula is ', $sharedFormulas[$instance]['formula'], PHP_EOL; + $master = PHPExcel_Cell::coordinateFromString($sharedFormulas[$instance]['master']); + $current = PHPExcel_Cell::coordinateFromString($r); + + $difference = array(0, 0); + $difference[0] = PHPExcel_Cell::columnIndexFromString($current[0]) - PHPExcel_Cell::columnIndexFromString($master[0]); + $difference[1] = $current[1] - $master[1]; + + $value = $this->referenceHelper->updateFormulaReferences($sharedFormulas[$instance]['formula'], 'A1', $difference[0], $difference[1]); +// echo 'Adjusted Formula is ', $value, PHP_EOL; + } + } + } + + + private function getFromZipArchive($archive, $fileName = '') + { + // Root-relative paths + if (strpos($fileName, '//') !== false) { + $fileName = substr($fileName, strpos($fileName, '//') + 1); + } + $fileName = PHPExcel_Shared_File::realpath($fileName); + + // Sadly, some 3rd party xlsx generators don't use consistent case for filenaming + // so we need to load case-insensitively from the zip file + + // Apache POI fixes + $contents = $archive->getFromIndex( + $archive->locateName($fileName, ZIPARCHIVE::FL_NOCASE) + ); + if ($contents === false) { + $contents = $archive->getFromIndex( + $archive->locateName(substr($fileName, 1), ZIPARCHIVE::FL_NOCASE) + ); + } + + return $contents; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Initialisations + $excel = new PHPExcel; + $excel->removeSheetByIndex(0); + if (!$this->readDataOnly) { + $excel->removeCellStyleXfByIndex(0); // remove the default style + $excel->removeCellXfByIndex(0); // remove the default style + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + $zip->open($pFilename); + + // Read the theme first, because we need the colour scheme when reading the styles + $wbRels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "xl/_rels/workbook.xml.rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($wbRels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme": + $themeOrderArray = array('lt1', 'dk1', 'lt2', 'dk2'); + $themeOrderAdditional = count($themeOrderArray); + + $xmlTheme = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "xl/{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlTheme)) { + $xmlThemeName = $xmlTheme->attributes(); + $xmlTheme = $xmlTheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + $themeName = (string)$xmlThemeName['name']; + + $colourScheme = $xmlTheme->themeElements->clrScheme->attributes(); + $colourSchemeName = (string)$colourScheme['name']; + $colourScheme = $xmlTheme->themeElements->clrScheme->children("http://schemas.openxmlformats.org/drawingml/2006/main"); + + $themeColours = array(); + foreach ($colourScheme as $k => $xmlColour) { + $themePos = array_search($k, $themeOrderArray); + if ($themePos === false) { + $themePos = $themeOrderAdditional++; + } + if (isset($xmlColour->sysClr)) { + $xmlColourData = $xmlColour->sysClr->attributes(); + $themeColours[$themePos] = $xmlColourData['lastClr']; + } elseif (isset($xmlColour->srgbClr)) { + $xmlColourData = $xmlColour->srgbClr->attributes(); + $themeColours[$themePos] = $xmlColourData['val']; + } + } + self::$theme = new PHPExcel_Reader_Excel2007_Theme($themeName, $colourSchemeName, $themeColours); + } + break; + } + } + + $rels = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "_rels/.rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($rels->Relationship as $rel) { + switch ($rel["Type"]) { + case "http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties": + $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $xmlCore->registerXPathNamespace("dc", "http://purl.org/dc/elements/1.1/"); + $xmlCore->registerXPathNamespace("dcterms", "http://purl.org/dc/terms/"); + $xmlCore->registerXPathNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties"); + $docProps = $excel->getProperties(); + $docProps->setCreator((string) self::getArrayItem($xmlCore->xpath("dc:creator"))); + $docProps->setLastModifiedBy((string) self::getArrayItem($xmlCore->xpath("cp:lastModifiedBy"))); + $docProps->setCreated(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:created")))); //! respect xsi:type + $docProps->setModified(strtotime(self::getArrayItem($xmlCore->xpath("dcterms:modified")))); //! respect xsi:type + $docProps->setTitle((string) self::getArrayItem($xmlCore->xpath("dc:title"))); + $docProps->setDescription((string) self::getArrayItem($xmlCore->xpath("dc:description"))); + $docProps->setSubject((string) self::getArrayItem($xmlCore->xpath("dc:subject"))); + $docProps->setKeywords((string) self::getArrayItem($xmlCore->xpath("cp:keywords"))); + $docProps->setCategory((string) self::getArrayItem($xmlCore->xpath("cp:category"))); + } + break; + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties": + $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + if (isset($xmlCore->Company)) { + $docProps->setCompany((string) $xmlCore->Company); + } + if (isset($xmlCore->Manager)) { + $docProps->setManager((string) $xmlCore->Manager); + } + } + break; + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties": + $xmlCore = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if (is_object($xmlCore)) { + $docProps = $excel->getProperties(); + foreach ($xmlCore as $xmlProperty) { + $cellDataOfficeAttributes = $xmlProperty->attributes(); + if (isset($cellDataOfficeAttributes['name'])) { + $propertyName = (string) $cellDataOfficeAttributes['name']; + $cellDataOfficeChildren = $xmlProperty->children('http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + $attributeType = $cellDataOfficeChildren->getName(); + $attributeValue = (string) $cellDataOfficeChildren->{$attributeType}; + $attributeValue = PHPExcel_DocumentProperties::convertProperty($attributeValue, $attributeType); + $attributeType = PHPExcel_DocumentProperties::convertPropertyType($attributeType); + $docProps->setCustomProperty($propertyName, $attributeValue, $attributeType); + } + } + } + break; + //Ribbon + case "http://schemas.microsoft.com/office/2006/relationships/ui/extensibility": + $customUI = $rel['Target']; + if (!is_null($customUI)) { + $this->readRibbon($excel, $customUI, $zip); + } + break; + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument": + $dir = dirname($rel["Target"]); + $relsWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/_rels/" . basename($rel["Target"]) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $relsWorkbook->registerXPathNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships"); + + $sharedStrings = array(); + $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings']")); + $xmlStrings = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + if (isset($xmlStrings) && isset($xmlStrings->si)) { + foreach ($xmlStrings->si as $val) { + if (isset($val->t)) { + $sharedStrings[] = PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $val->t); + } elseif (isset($val->r)) { + $sharedStrings[] = $this->parseRichText($val); + } + } + } + + $worksheets = array(); + $macros = $customUI = null; + foreach ($relsWorkbook->Relationship as $ele) { + switch ($ele['Type']) { + case "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet": + $worksheets[(string) $ele["Id"]] = $ele["Target"]; + break; + // a vbaProject ? (: some macros) + case "http://schemas.microsoft.com/office/2006/relationships/vbaProject": + $macros = $ele["Target"]; + break; + } + } + + if (!is_null($macros)) { + $macrosCode = $this->getFromZipArchive($zip, 'xl/vbaProject.bin');//vbaProject.bin always in 'xl' dir and always named vbaProject.bin + if ($macrosCode !== false) { + $excel->setMacrosCode($macrosCode); + $excel->setHasMacros(true); + //short-circuit : not reading vbaProject.bin.rel to get Signature =>allways vbaProjectSignature.bin in 'xl' dir + $Certificate = $this->getFromZipArchive($zip, 'xl/vbaProjectSignature.bin'); + if ($Certificate !== false) { + $excel->setMacrosCertificate($Certificate); + } + } + } + $styles = array(); + $cellStyles = array(); + $xpath = self::getArrayItem($relsWorkbook->xpath("rel:Relationship[@Type='http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles']")); + $xmlStyles = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$xpath[Target]")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + $numFmts = null; + if ($xmlStyles && $xmlStyles->numFmts[0]) { + $numFmts = $xmlStyles->numFmts[0]; + } + if (isset($numFmts) && ($numFmts !== null)) { + $numFmts->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + } + if (!$this->readDataOnly && $xmlStyles) { + foreach ($xmlStyles->cellXfs->xf as $xf) { + $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + if ($xf["numFmtId"]) { + if (isset($numFmts)) { + $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } + } + + // We shouldn't override any of the built-in MS Excel values (values below id 164) + // But there's a lot of naughty homebrew xlsx writers that do use "reserved" id values that aren't actually used + // So we make allowance for them rather than lose formatting masks + if ((int)$xf["numFmtId"] < 164 && PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]) !== '') { + $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + $quotePrefix = false; + if (isset($xf["quotePrefix"])) { + $quotePrefix = (boolean) $xf["quotePrefix"]; + } + + $style = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $styles[] = $style; + + // add style to cellXf collection + $objStyle = new PHPExcel_Style; + self::readStyle($objStyle, $style); + $excel->addCellXf($objStyle); + } + + foreach ($xmlStyles->cellStyleXfs->xf as $xf) { + $numFmt = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + if ($numFmts && $xf["numFmtId"]) { + $tmpNumFmt = self::getArrayItem($numFmts->xpath("sml:numFmt[@numFmtId=$xf[numFmtId]]")); + if (isset($tmpNumFmt["formatCode"])) { + $numFmt = (string) $tmpNumFmt["formatCode"]; + } elseif ((int)$xf["numFmtId"] < 165) { + $numFmt = PHPExcel_Style_NumberFormat::builtInFormatCode((int)$xf["numFmtId"]); + } + } + + $cellStyle = (object) array( + "numFmt" => $numFmt, + "font" => $xmlStyles->fonts->font[intval($xf["fontId"])], + "fill" => $xmlStyles->fills->fill[intval($xf["fillId"])], + "border" => $xmlStyles->borders->border[intval($xf["borderId"])], + "alignment" => $xf->alignment, + "protection" => $xf->protection, + "quotePrefix" => $quotePrefix, + ); + $cellStyles[] = $cellStyle; + + // add style to cellStyleXf collection + $objStyle = new PHPExcel_Style; + self::readStyle($objStyle, $cellStyle); + $excel->addCellStyleXf($objStyle); + } + } + + $dxfs = array(); + if (!$this->readDataOnly && $xmlStyles) { + // Conditional Styles + if ($xmlStyles->dxfs) { + foreach ($xmlStyles->dxfs->dxf as $dxf) { + $style = new PHPExcel_Style(false, true); + self::readStyle($style, $dxf); + $dxfs[] = $style; + } + } + // Cell Styles + if ($xmlStyles->cellStyles) { + foreach ($xmlStyles->cellStyles->cellStyle as $cellStyle) { + if (intval($cellStyle['builtinId']) == 0) { + if (isset($cellStyles[intval($cellStyle['xfId'])])) { + // Set default style + $style = new PHPExcel_Style; + self::readStyle($style, $cellStyles[intval($cellStyle['xfId'])]); + + // normal style, currently not using it for anything + } + } + } + } + } + + $xmlWorkbook = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "{$rel['Target']}")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + // Set base date + if ($xmlWorkbook->workbookPr) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900); + if (isset($xmlWorkbook->workbookPr['date1904'])) { + if (self::boolean((string) $xmlWorkbook->workbookPr['date1904'])) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904); + } + } + } + + $sheetId = 0; // keep track of new sheet id in final workbook + $oldSheetId = -1; // keep track of old sheet id in final workbook + $countSkippedSheets = 0; // keep track of number of skipped sheets + $mapSheetId = array(); // mapping of sheet ids from old to new + + $charts = $chartDetails = array(); + + if ($xmlWorkbook->sheets) { + foreach ($xmlWorkbook->sheets->sheet as $eleSheet) { + ++$oldSheetId; + + // Check if sheet should be skipped + if (isset($this->loadSheetsOnly) && !in_array((string) $eleSheet["name"], $this->loadSheetsOnly)) { + ++$countSkippedSheets; + $mapSheetId[$oldSheetId] = null; + continue; + } + + // Map old sheet id in original workbook to new sheet id. + // They will differ if loadSheetsOnly() is being used + $mapSheetId[$oldSheetId] = $oldSheetId - $countSkippedSheets; + + // Load sheet + $docSheet = $excel->createSheet(); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet + // references in formula cells... during the load, all formulae should be correct, + // and we're simply bringing the worksheet name in line with the formula, not the + // reverse + $docSheet->setTitle((string) $eleSheet["name"], false); + $fileWorksheet = $worksheets[(string) self::getArrayItem($eleSheet->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $xmlSheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "$dir/$fileWorksheet")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + + $sharedFormulas = array(); + + if (isset($eleSheet["state"]) && (string) $eleSheet["state"] != '') { + $docSheet->setSheetState((string) $eleSheet["state"]); + } + + if (isset($xmlSheet->sheetViews) && isset($xmlSheet->sheetViews->sheetView)) { + if (isset($xmlSheet->sheetViews->sheetView['zoomScale'])) { + $docSheet->getSheetView()->setZoomScale(intval($xmlSheet->sheetViews->sheetView['zoomScale'])); + } + if (isset($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])) { + $docSheet->getSheetView()->setZoomScaleNormal(intval($xmlSheet->sheetViews->sheetView['zoomScaleNormal'])); + } + if (isset($xmlSheet->sheetViews->sheetView['view'])) { + $docSheet->getSheetView()->setView((string) $xmlSheet->sheetViews->sheetView['view']); + } + if (isset($xmlSheet->sheetViews->sheetView['showGridLines'])) { + $docSheet->setShowGridLines(self::boolean((string)$xmlSheet->sheetViews->sheetView['showGridLines'])); + } + if (isset($xmlSheet->sheetViews->sheetView['showRowColHeaders'])) { + $docSheet->setShowRowColHeaders(self::boolean((string)$xmlSheet->sheetViews->sheetView['showRowColHeaders'])); + } + if (isset($xmlSheet->sheetViews->sheetView['rightToLeft'])) { + $docSheet->setRightToLeft(self::boolean((string)$xmlSheet->sheetViews->sheetView['rightToLeft'])); + } + if (isset($xmlSheet->sheetViews->sheetView->pane)) { + if (isset($xmlSheet->sheetViews->sheetView->pane['topLeftCell'])) { + $docSheet->freezePane((string)$xmlSheet->sheetViews->sheetView->pane['topLeftCell']); + } else { + $xSplit = 0; + $ySplit = 0; + + if (isset($xmlSheet->sheetViews->sheetView->pane['xSplit'])) { + $xSplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['xSplit']); + } + + if (isset($xmlSheet->sheetViews->sheetView->pane['ySplit'])) { + $ySplit = 1 + intval($xmlSheet->sheetViews->sheetView->pane['ySplit']); + } + + $docSheet->freezePaneByColumnAndRow($xSplit, $ySplit); + } + } + + if (isset($xmlSheet->sheetViews->sheetView->selection)) { + if (isset($xmlSheet->sheetViews->sheetView->selection['sqref'])) { + $sqref = (string)$xmlSheet->sheetViews->sheetView->selection['sqref']; + $sqref = explode(' ', $sqref); + $sqref = $sqref[0]; + $docSheet->setSelectedCells($sqref); + } + } + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->tabColor)) { + if (isset($xmlSheet->sheetPr->tabColor['rgb'])) { + $docSheet->getTabColor()->setARGB((string)$xmlSheet->sheetPr->tabColor['rgb']); + } + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr['codeName'])) { + $docSheet->setCodeName((string) $xmlSheet->sheetPr['codeName']); + } + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->outlinePr)) { + if (isset($xmlSheet->sheetPr->outlinePr['summaryRight']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryRight'])) { + $docSheet->setShowSummaryRight(false); + } else { + $docSheet->setShowSummaryRight(true); + } + + if (isset($xmlSheet->sheetPr->outlinePr['summaryBelow']) && + !self::boolean((string) $xmlSheet->sheetPr->outlinePr['summaryBelow'])) { + $docSheet->setShowSummaryBelow(false); + } else { + $docSheet->setShowSummaryBelow(true); + } + } + + if (isset($xmlSheet->sheetPr) && isset($xmlSheet->sheetPr->pageSetUpPr)) { + if (isset($xmlSheet->sheetPr->pageSetUpPr['fitToPage']) && + !self::boolean((string) $xmlSheet->sheetPr->pageSetUpPr['fitToPage'])) { + $docSheet->getPageSetup()->setFitToPage(false); + } else { + $docSheet->getPageSetup()->setFitToPage(true); + } + } + + if (isset($xmlSheet->sheetFormatPr)) { + if (isset($xmlSheet->sheetFormatPr['customHeight']) && + self::boolean((string) $xmlSheet->sheetFormatPr['customHeight']) && + isset($xmlSheet->sheetFormatPr['defaultRowHeight'])) { + $docSheet->getDefaultRowDimension()->setRowHeight((float)$xmlSheet->sheetFormatPr['defaultRowHeight']); + } + if (isset($xmlSheet->sheetFormatPr['defaultColWidth'])) { + $docSheet->getDefaultColumnDimension()->setWidth((float)$xmlSheet->sheetFormatPr['defaultColWidth']); + } + if (isset($xmlSheet->sheetFormatPr['zeroHeight']) && + ((string)$xmlSheet->sheetFormatPr['zeroHeight'] == '1')) { + $docSheet->getDefaultRowDimension()->setZeroHeight(true); + } + } + + if (isset($xmlSheet->cols) && !$this->readDataOnly) { + foreach ($xmlSheet->cols->col as $col) { + for ($i = intval($col["min"]) - 1; $i < intval($col["max"]); ++$i) { + if ($col["style"] && !$this->readDataOnly) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setXfIndex(intval($col["style"])); + } + if (self::boolean($col["bestFit"])) { + //$docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setAutoSize(true); + } + if (self::boolean($col["hidden"])) { + // echo PHPExcel_Cell::stringFromColumnIndex($i), ': HIDDEN COLUMN',PHP_EOL; + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setVisible(false); + } + if (self::boolean($col["collapsed"])) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setCollapsed(true); + } + if ($col["outlineLevel"] > 0) { + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setOutlineLevel(intval($col["outlineLevel"])); + } + $docSheet->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($i))->setWidth(floatval($col["width"])); + + if (intval($col["max"]) == 16384) { + break; + } + } + } + } + + if (isset($xmlSheet->printOptions) && !$this->readDataOnly) { + if (self::boolean((string) $xmlSheet->printOptions['gridLinesSet'])) { + $docSheet->setShowGridlines(true); + } + if (self::boolean((string) $xmlSheet->printOptions['gridLines'])) { + $docSheet->setPrintGridlines(true); + } + if (self::boolean((string) $xmlSheet->printOptions['horizontalCentered'])) { + $docSheet->getPageSetup()->setHorizontalCentered(true); + } + if (self::boolean((string) $xmlSheet->printOptions['verticalCentered'])) { + $docSheet->getPageSetup()->setVerticalCentered(true); + } + } + + if ($xmlSheet && $xmlSheet->sheetData && $xmlSheet->sheetData->row) { + foreach ($xmlSheet->sheetData->row as $row) { + if ($row["ht"] && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setRowHeight(floatval($row["ht"])); + } + if (self::boolean($row["hidden"]) && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setVisible(false); + } + if (self::boolean($row["collapsed"])) { + $docSheet->getRowDimension(intval($row["r"]))->setCollapsed(true); + } + if ($row["outlineLevel"] > 0) { + $docSheet->getRowDimension(intval($row["r"]))->setOutlineLevel(intval($row["outlineLevel"])); + } + if ($row["s"] && !$this->readDataOnly) { + $docSheet->getRowDimension(intval($row["r"]))->setXfIndex(intval($row["s"])); + } + + foreach ($row->c as $c) { + $r = (string) $c["r"]; + $cellDataType = (string) $c["t"]; + $value = null; + $calculatedValue = null; + + // Read cell? + if ($this->getReadFilter() !== null) { + $coordinates = PHPExcel_Cell::coordinateFromString($r); + + if (!$this->getReadFilter()->readCell($coordinates[0], $coordinates[1], $docSheet->getTitle())) { + continue; + } + } + + // echo 'Reading cell ', $coordinates[0], $coordinates[1], PHP_EOL; + // print_r($c); + // echo PHP_EOL; + // echo 'Cell Data Type is ', $cellDataType, ': '; + // + // Read cell! + switch ($cellDataType) { + case "s": + // echo 'String', PHP_EOL; + if ((string)$c->v != '') { + $value = $sharedStrings[intval($c->v)]; + + if ($value instanceof PHPExcel_RichText) { + $value = clone $value; + } + } else { + $value = ''; + } + break; + case "b": + // echo 'Boolean', PHP_EOL; + if (!isset($c->f)) { + $value = self::castToBoolean($c); + } else { + // Formula + $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToBoolean'); + if (isset($c->f['t'])) { + $att = array(); + $att = $c->f; + $docSheet->getCell($r)->setFormulaAttributes($att); + } + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + break; + case "inlineStr": +// echo 'Inline String', PHP_EOL; + if (isset($c->f)) { + $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError'); + } else { + $value = $this->parseRichText($c->is); + } + break; + case "e": + // echo 'Error', PHP_EOL; + if (!isset($c->f)) { + $value = self::castToError($c); + } else { + // Formula + $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToError'); + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + break; + default: +// echo 'Default', PHP_EOL; + if (!isset($c->f)) { + // echo 'Not a Formula', PHP_EOL; + $value = self::castToString($c); + } else { + // echo 'Treat as Formula', PHP_EOL; + // Formula + $this->castToFormula($c, $r, $cellDataType, $value, $calculatedValue, $sharedFormulas, 'castToString'); + // echo '$calculatedValue = ', $calculatedValue, PHP_EOL; + } + break; + } + // echo 'Value is ', $value, PHP_EOL; + + // Check for numeric values + if (is_numeric($value) && $cellDataType != 's') { + if ($value == (int)$value) { + $value = (int)$value; + } elseif ($value == (float)$value) { + $value = (float)$value; + } elseif ($value == (double)$value) { + $value = (double)$value; + } + } + + // Rich text? + if ($value instanceof PHPExcel_RichText && $this->readDataOnly) { + $value = $value->getPlainText(); + } + + $cell = $docSheet->getCell($r); + // Assign value + if ($cellDataType != '') { + $cell->setValueExplicit($value, $cellDataType); + } else { + $cell->setValue($value); + } + if ($calculatedValue !== null) { + $cell->setCalculatedValue($calculatedValue); + } + + // Style information? + if ($c["s"] && !$this->readDataOnly) { + // no style index means 0, it seems + $cell->setXfIndex(isset($styles[intval($c["s"])]) ? + intval($c["s"]) : 0); + } + } + } + } + + $conditionals = array(); + if (!$this->readDataOnly && $xmlSheet && $xmlSheet->conditionalFormatting) { + foreach ($xmlSheet->conditionalFormatting as $conditional) { + foreach ($conditional->cfRule as $cfRule) { + if (((string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_NONE || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CELLIS || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT || (string)$cfRule["type"] == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) && isset($dxfs[intval($cfRule["dxfId"])])) { + $conditionals[(string) $conditional["sqref"]][intval($cfRule["priority"])] = $cfRule; + } + } + } + + foreach ($conditionals as $ref => $cfRules) { + ksort($cfRules); + $conditionalStyles = array(); + foreach ($cfRules as $cfRule) { + $objConditional = new PHPExcel_Style_Conditional(); + $objConditional->setConditionType((string)$cfRule["type"]); + $objConditional->setOperatorType((string)$cfRule["operator"]); + + if ((string)$cfRule["text"] != '') { + $objConditional->setText((string)$cfRule["text"]); + } + + if (count($cfRule->formula) > 1) { + foreach ($cfRule->formula as $formula) { + $objConditional->addCondition((string)$formula); + } + } else { + $objConditional->addCondition((string)$cfRule->formula); + } + $objConditional->setStyle(clone $dxfs[intval($cfRule["dxfId"])]); + $conditionalStyles[] = $objConditional; + } + + // Extract all cell references in $ref + $cellBlocks = explode(' ', str_replace('$', '', strtoupper($ref))); + foreach ($cellBlocks as $cellBlock) { + $docSheet->getStyle($cellBlock)->setConditionalStyles($conditionalStyles); + } + } + } + + $aKeys = array("sheet", "objects", "scenarios", "formatCells", "formatColumns", "formatRows", "insertColumns", "insertRows", "insertHyperlinks", "deleteColumns", "deleteRows", "selectLockedCells", "sort", "autoFilter", "pivotTables", "selectUnlockedCells"); + if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + foreach ($aKeys as $key) { + $method = "set" . ucfirst($key); + $docSheet->getProtection()->$method(self::boolean((string) $xmlSheet->sheetProtection[$key])); + } + } + + if (!$this->readDataOnly && $xmlSheet && $xmlSheet->sheetProtection) { + $docSheet->getProtection()->setPassword((string) $xmlSheet->sheetProtection["password"], true); + if ($xmlSheet->protectedRanges->protectedRange) { + foreach ($xmlSheet->protectedRanges->protectedRange as $protectedRange) { + $docSheet->protectCells((string) $protectedRange["sqref"], (string) $protectedRange["password"], true); + } + } + } + + if ($xmlSheet && $xmlSheet->autoFilter && !$this->readDataOnly) { + $autoFilterRange = (string) $xmlSheet->autoFilter["ref"]; + if (strpos($autoFilterRange, ':') !== false) { + $autoFilter = $docSheet->getAutoFilter(); + $autoFilter->setRange($autoFilterRange); + + foreach ($xmlSheet->autoFilter->filterColumn as $filterColumn) { + $column = $autoFilter->getColumnByOffset((integer) $filterColumn["colId"]); + // Check for standard filters + if ($filterColumn->filters) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER); + $filters = $filterColumn->filters; + if ((isset($filters["blank"])) && ($filters["blank"] == 1)) { + // Operator is undefined, but always treated as EQUAL + $column->createRule()->setRule(null, '')->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Standard filters are always an OR join, so no join rule needs to be set + // Entries can be either filter elements + foreach ($filters->filter as $filterRule) { + // Operator is undefined, but always treated as EQUAL + $column->createRule()->setRule(null, (string) $filterRule["val"])->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER); + } + // Or Date Group elements + foreach ($filters->dateGroupItem as $dateGroupItem) { + $column->createRule()->setRule( + // Operator is undefined, but always treated as EQUAL + null, + array( + 'year' => (string) $dateGroupItem["year"], + 'month' => (string) $dateGroupItem["month"], + 'day' => (string) $dateGroupItem["day"], + 'hour' => (string) $dateGroupItem["hour"], + 'minute' => (string) $dateGroupItem["minute"], + 'second' => (string) $dateGroupItem["second"], + ), + (string) $dateGroupItem["dateTimeGrouping"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP); + } + } + // Check for custom filters + if ($filterColumn->customFilters) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER); + $customFilters = $filterColumn->customFilters; + // Custom filters can an AND or an OR join; + // and there should only ever be one or two entries + if ((isset($customFilters["and"])) && ($customFilters["and"] == 1)) { + $column->setJoin(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); + } + foreach ($customFilters->customFilter as $filterRule) { + $column->createRule()->setRule( + (string) $filterRule["operator"], + (string) $filterRule["val"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_CUSTOMFILTER); + } + } + // Check for dynamic filters + if ($filterColumn->dynamicFilter) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER); + // We should only ever have one dynamic filter + foreach ($filterColumn->dynamicFilter as $filterRule) { + $column->createRule()->setRule( + // Operator is undefined, but always treated as EQUAL + null, + (string) $filterRule["val"], + (string) $filterRule["type"] + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER); + if (isset($filterRule["val"])) { + $column->setAttribute('val', (string) $filterRule["val"]); + } + if (isset($filterRule["maxVal"])) { + $column->setAttribute('maxVal', (string) $filterRule["maxVal"]); + } + } + } + // Check for dynamic filters + if ($filterColumn->top10) { + $column->setFilterType(PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER); + // We should only ever have one top10 filter + foreach ($filterColumn->top10 as $filterRule) { + $column->createRule()->setRule( + (((isset($filterRule["percent"])) && ($filterRule["percent"] == 1)) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE + ), + (string) $filterRule["val"], + (((isset($filterRule["top"])) && ($filterRule["top"] == 1)) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM + ) + ) + ->setRuleType(PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER); + } + } + } + } + } + + if ($xmlSheet && $xmlSheet->mergeCells && $xmlSheet->mergeCells->mergeCell && !$this->readDataOnly) { + foreach ($xmlSheet->mergeCells->mergeCell as $mergeCell) { + $mergeRef = (string) $mergeCell["ref"]; + if (strpos($mergeRef, ':') !== false) { + $docSheet->mergeCells((string) $mergeCell["ref"]); + } + } + } + + if ($xmlSheet && $xmlSheet->pageMargins && !$this->readDataOnly) { + $docPageMargins = $docSheet->getPageMargins(); + $docPageMargins->setLeft(floatval($xmlSheet->pageMargins["left"])); + $docPageMargins->setRight(floatval($xmlSheet->pageMargins["right"])); + $docPageMargins->setTop(floatval($xmlSheet->pageMargins["top"])); + $docPageMargins->setBottom(floatval($xmlSheet->pageMargins["bottom"])); + $docPageMargins->setHeader(floatval($xmlSheet->pageMargins["header"])); + $docPageMargins->setFooter(floatval($xmlSheet->pageMargins["footer"])); + } + + if ($xmlSheet && $xmlSheet->pageSetup && !$this->readDataOnly) { + $docPageSetup = $docSheet->getPageSetup(); + + if (isset($xmlSheet->pageSetup["orientation"])) { + $docPageSetup->setOrientation((string) $xmlSheet->pageSetup["orientation"]); + } + if (isset($xmlSheet->pageSetup["paperSize"])) { + $docPageSetup->setPaperSize(intval($xmlSheet->pageSetup["paperSize"])); + } + if (isset($xmlSheet->pageSetup["scale"])) { + $docPageSetup->setScale(intval($xmlSheet->pageSetup["scale"]), false); + } + if (isset($xmlSheet->pageSetup["fitToHeight"]) && intval($xmlSheet->pageSetup["fitToHeight"]) >= 0) { + $docPageSetup->setFitToHeight(intval($xmlSheet->pageSetup["fitToHeight"]), false); + } + if (isset($xmlSheet->pageSetup["fitToWidth"]) && intval($xmlSheet->pageSetup["fitToWidth"]) >= 0) { + $docPageSetup->setFitToWidth(intval($xmlSheet->pageSetup["fitToWidth"]), false); + } + if (isset($xmlSheet->pageSetup["firstPageNumber"]) && isset($xmlSheet->pageSetup["useFirstPageNumber"]) && + self::boolean((string) $xmlSheet->pageSetup["useFirstPageNumber"])) { + $docPageSetup->setFirstPageNumber(intval($xmlSheet->pageSetup["firstPageNumber"])); + } + } + + if ($xmlSheet && $xmlSheet->headerFooter && !$this->readDataOnly) { + $docHeaderFooter = $docSheet->getHeaderFooter(); + + if (isset($xmlSheet->headerFooter["differentOddEven"]) && + self::boolean((string)$xmlSheet->headerFooter["differentOddEven"])) { + $docHeaderFooter->setDifferentOddEven(true); + } else { + $docHeaderFooter->setDifferentOddEven(false); + } + if (isset($xmlSheet->headerFooter["differentFirst"]) && + self::boolean((string)$xmlSheet->headerFooter["differentFirst"])) { + $docHeaderFooter->setDifferentFirst(true); + } else { + $docHeaderFooter->setDifferentFirst(false); + } + if (isset($xmlSheet->headerFooter["scaleWithDoc"]) && + !self::boolean((string)$xmlSheet->headerFooter["scaleWithDoc"])) { + $docHeaderFooter->setScaleWithDocument(false); + } else { + $docHeaderFooter->setScaleWithDocument(true); + } + if (isset($xmlSheet->headerFooter["alignWithMargins"]) && + !self::boolean((string)$xmlSheet->headerFooter["alignWithMargins"])) { + $docHeaderFooter->setAlignWithMargins(false); + } else { + $docHeaderFooter->setAlignWithMargins(true); + } + + $docHeaderFooter->setOddHeader((string) $xmlSheet->headerFooter->oddHeader); + $docHeaderFooter->setOddFooter((string) $xmlSheet->headerFooter->oddFooter); + $docHeaderFooter->setEvenHeader((string) $xmlSheet->headerFooter->evenHeader); + $docHeaderFooter->setEvenFooter((string) $xmlSheet->headerFooter->evenFooter); + $docHeaderFooter->setFirstHeader((string) $xmlSheet->headerFooter->firstHeader); + $docHeaderFooter->setFirstFooter((string) $xmlSheet->headerFooter->firstFooter); + } + + if ($xmlSheet && $xmlSheet->rowBreaks && $xmlSheet->rowBreaks->brk && !$this->readDataOnly) { + foreach ($xmlSheet->rowBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak("A$brk[id]", PHPExcel_Worksheet::BREAK_ROW); + } + } + } + if ($xmlSheet && $xmlSheet->colBreaks && $xmlSheet->colBreaks->brk && !$this->readDataOnly) { + foreach ($xmlSheet->colBreaks->brk as $brk) { + if ($brk["man"]) { + $docSheet->setBreak(PHPExcel_Cell::stringFromColumnIndex((string) $brk["id"]) . "1", PHPExcel_Worksheet::BREAK_COLUMN); + } + } + } + + if ($xmlSheet && $xmlSheet->dataValidations && !$this->readDataOnly) { + foreach ($xmlSheet->dataValidations->dataValidation as $dataValidation) { + // Uppercase coordinate + $range = strtoupper($dataValidation["sqref"]); + $rangeSet = explode(' ', $range); + foreach ($rangeSet as $range) { + $stRange = $docSheet->shrinkRangeToFit($range); + + // Extract all cell references in $range + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($stRange) as $reference) { + // Create validation + $docValidation = $docSheet->getCell($reference)->getDataValidation(); + $docValidation->setType((string) $dataValidation["type"]); + $docValidation->setErrorStyle((string) $dataValidation["errorStyle"]); + $docValidation->setOperator((string) $dataValidation["operator"]); + $docValidation->setAllowBlank($dataValidation["allowBlank"] != 0); + $docValidation->setShowDropDown($dataValidation["showDropDown"] == 0); + $docValidation->setShowInputMessage($dataValidation["showInputMessage"] != 0); + $docValidation->setShowErrorMessage($dataValidation["showErrorMessage"] != 0); + $docValidation->setErrorTitle((string) $dataValidation["errorTitle"]); + $docValidation->setError((string) $dataValidation["error"]); + $docValidation->setPromptTitle((string) $dataValidation["promptTitle"]); + $docValidation->setPrompt((string) $dataValidation["prompt"]); + $docValidation->setFormula1((string) $dataValidation->formula1); + $docValidation->setFormula2((string) $dataValidation->formula2); + } + } + } + } + + // Add hyperlinks + $hyperlinks = array(); + if (!$this->readDataOnly) { + // Locate hyperlink relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink") { + $hyperlinks[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through hyperlinks + if ($xmlSheet && $xmlSheet->hyperlinks) { + foreach ($xmlSheet->hyperlinks->hyperlink as $hyperlink) { + // Link url + $linkRel = $hyperlink->attributes('http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($hyperlink['ref']) as $cellReference) { + $cell = $docSheet->getCell($cellReference); + if (isset($linkRel['id'])) { + $hyperlinkUrl = $hyperlinks[ (string)$linkRel['id'] ]; + if (isset($hyperlink['location'])) { + $hyperlinkUrl .= '#' . (string) $hyperlink['location']; + } + $cell->getHyperlink()->setUrl($hyperlinkUrl); + } elseif (isset($hyperlink['location'])) { + $cell->getHyperlink()->setUrl('sheet://' . (string)$hyperlink['location']); + } + + // Tooltip + if (isset($hyperlink['tooltip'])) { + $cell->getHyperlink()->setTooltip((string)$hyperlink['tooltip']); + } + } + } + } + } + + // Add comments + $comments = array(); + $vmlComments = array(); + if (!$this->readDataOnly) { + // Locate comment relations + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments") { + $comments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlComments[(string)$ele["Id"]] = (string)$ele["Target"]; + } + } + } + + // Loop through comments + foreach ($comments as $relName => $relPath) { + // Load comments file + $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $commentsFile = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + + // Utility variables + $authors = array(); + + // Loop through authors + foreach ($commentsFile->authors->author as $author) { + $authors[] = (string)$author; + } + + // Loop through contents + foreach ($commentsFile->commentList->comment as $comment) { + if (!empty($comment['authorId'])) { + $docSheet->getComment((string)$comment['ref'])->setAuthor($authors[(string)$comment['authorId']]); + } + $docSheet->getComment((string)$comment['ref'])->setText($this->parseRichText($comment->text)); + } + } + + // Loop through VML comments + foreach ($vmlComments as $relName => $relPath) { + // Load VML comments file + $relPath = PHPExcel_Shared_File::realpath(dirname("$dir/$fileWorksheet") . "/" . $relPath); + $vmlCommentsFile = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $relPath)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $vmlCommentsFile->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $shapes = $vmlCommentsFile->xpath('//v:shape'); + foreach ($shapes as $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + if (isset($shape['style'])) { + $style = (string)$shape['style']; + $fillColor = strtoupper(substr((string)$shape['fillcolor'], 1)); + $column = null; + $row = null; + + $clientData = $shape->xpath('.//x:ClientData'); + if (is_array($clientData) && !empty($clientData)) { + $clientData = $clientData[0]; + + if (isset($clientData['ObjectType']) && (string)$clientData['ObjectType'] == 'Note') { + $temp = $clientData->xpath('.//x:Row'); + if (is_array($temp)) { + $row = $temp[0]; + } + + $temp = $clientData->xpath('.//x:Column'); + if (is_array($temp)) { + $column = $temp[0]; + } + } + } + + if (($column !== null) && ($row !== null)) { + // Set comment properties + $comment = $docSheet->getCommentByColumnAndRow((string) $column, $row + 1); + $comment->getFillColor()->setRGB($fillColor); + + // Parse style + $styleArray = explode(';', str_replace(' ', '', $style)); + foreach ($styleArray as $stylePair) { + $stylePair = explode(':', $stylePair); + + if ($stylePair[0] == 'margin-left') { + $comment->setMarginLeft($stylePair[1]); + } + if ($stylePair[0] == 'margin-top') { + $comment->setMarginTop($stylePair[1]); + } + if ($stylePair[0] == 'width') { + $comment->setWidth($stylePair[1]); + } + if ($stylePair[0] == 'height') { + $comment->setHeight($stylePair[1]); + } + if ($stylePair[0] == 'visibility') { + $comment->setVisible($stylePair[1] == 'visible'); + } + } + } + } + } + } + + // Header/footer images + if ($xmlSheet && $xmlSheet->legacyDrawingHF && !$this->readDataOnly) { + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $vmlRelationship = ''; + + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing") { + $vmlRelationship = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]); + } + } + + if ($vmlRelationship != '') { + // Fetch linked images + $relsVML = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname($vmlRelationship) . '/_rels/' . basename($vmlRelationship) . '.rels')), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsVML->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $drawings[(string) $ele["Id"]] = self::dirAdd($vmlRelationship, $ele["Target"]); + } + } + + // Fetch VML document + $vmlDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $vmlRelationship)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $vmlDrawing->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + + $hfImages = array(); + + $shapes = $vmlDrawing->xpath('//v:shape'); + foreach ($shapes as $idx => $shape) { + $shape->registerXPathNamespace('v', 'urn:schemas-microsoft-com:vml'); + $imageData = $shape->xpath('//v:imagedata'); + $imageData = $imageData[$idx]; + + $imageData = $imageData->attributes('urn:schemas-microsoft-com:office:office'); + $style = self::toCSSArray((string)$shape['style']); + + $hfImages[ (string)$shape['id'] ] = new PHPExcel_Worksheet_HeaderFooterDrawing(); + if (isset($imageData['title'])) { + $hfImages[ (string)$shape['id'] ]->setName((string)$imageData['title']); + } + + $hfImages[ (string)$shape['id'] ]->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $drawings[(string)$imageData['relid']], false); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(false); + $hfImages[ (string)$shape['id'] ]->setWidth($style['width']); + $hfImages[ (string)$shape['id'] ]->setHeight($style['height']); + if (isset($style['margin-left'])) { + $hfImages[ (string)$shape['id'] ]->setOffsetX($style['margin-left']); + } + $hfImages[ (string)$shape['id'] ]->setOffsetY($style['margin-top']); + $hfImages[ (string)$shape['id'] ]->setResizeProportional(true); + } + + $docSheet->getHeaderFooter()->setImages($hfImages); + } + } + } + + } + + // TODO: Autoshapes from twoCellAnchors! + if ($zip->locateName(dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")) { + $relsWorksheet = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname("$dir/$fileWorksheet") . "/_rels/" . basename($fileWorksheet) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $drawings = array(); + foreach ($relsWorksheet->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing") { + $drawings[(string) $ele["Id"]] = self::dirAdd("$dir/$fileWorksheet", $ele["Target"]); + } + } + if ($xmlSheet->drawing && !$this->readDataOnly) { + foreach ($xmlSheet->drawing as $drawing) { + $fileDrawing = $drawings[(string) self::getArrayItem($drawing->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "id")]; + $relsDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, dirname($fileDrawing) . "/_rels/" . basename($fileDrawing) . ".rels")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); //~ http://schemas.openxmlformats.org/package/2006/relationships"); + $images = array(); + + if ($relsDrawing && $relsDrawing->Relationship) { + foreach ($relsDrawing->Relationship as $ele) { + if ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image") { + $images[(string) $ele["Id"]] = self::dirAdd($fileDrawing, $ele["Target"]); + } elseif ($ele["Type"] == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart") { + if ($this->includeCharts) { + $charts[self::dirAdd($fileDrawing, $ele["Target"])] = array( + 'id' => (string) $ele["Id"], + 'sheet' => $docSheet->getTitle() + ); + } + } + } + } + $xmlDrawing = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $fileDrawing)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions())->children("http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"); + + if ($xmlDrawing->oneCellAnchor) { + foreach ($xmlDrawing->oneCellAnchor as $oneCellAnchor) { + if ($oneCellAnchor->pic->blipFill) { + $blip = $oneCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $oneCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPExcel_Worksheet_Drawing; + $objDrawing->setName((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::getArrayItem($oneCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::getArrayItem($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy"))); + if ($xfrm) { + $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } else { + // ? Can charts be positioned with a oneCellAnchor ? + $coordinates = PHPExcel_Cell::stringFromColumnIndex((string) $oneCellAnchor->from->col) . ($oneCellAnchor->from->row + 1); + $offsetX = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->colOff); + $offsetY = PHPExcel_Shared_Drawing::EMUToPixels($oneCellAnchor->from->rowOff); + $width = PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cx")); + $height = PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($oneCellAnchor->ext->attributes(), "cy")); + } + } + } + if ($xmlDrawing->twoCellAnchor) { + foreach ($xmlDrawing->twoCellAnchor as $twoCellAnchor) { + if ($twoCellAnchor->pic->blipFill) { + $blip = $twoCellAnchor->pic->blipFill->children("http://schemas.openxmlformats.org/drawingml/2006/main")->blip; + $xfrm = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->xfrm; + $outerShdw = $twoCellAnchor->pic->spPr->children("http://schemas.openxmlformats.org/drawingml/2006/main")->effectLst->outerShdw; + $objDrawing = new PHPExcel_Worksheet_Drawing; + $objDrawing->setName((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "name")); + $objDrawing->setDescription((string) self::getArrayItem($twoCellAnchor->pic->nvPicPr->cNvPr->attributes(), "descr")); + $objDrawing->setPath("zip://".PHPExcel_Shared_File::realpath($pFilename)."#" . $images[(string) self::getArrayItem($blip->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"), "embed")], false); + $objDrawing->setCoordinates(PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1)); + $objDrawing->setOffsetX(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff)); + $objDrawing->setOffsetY(PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff)); + $objDrawing->setResizeProportional(false); + + if ($xfrm) { + $objDrawing->setWidth(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cx"))); + $objDrawing->setHeight(PHPExcel_Shared_Drawing::EMUToPixels(self::getArrayItem($xfrm->ext->attributes(), "cy"))); + $objDrawing->setRotation(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($xfrm->attributes(), "rot"))); + } + if ($outerShdw) { + $shadow = $objDrawing->getShadow(); + $shadow->setVisible(true); + $shadow->setBlurRadius(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "blurRad"))); + $shadow->setDistance(PHPExcel_Shared_Drawing::EMUTopixels(self::getArrayItem($outerShdw->attributes(), "dist"))); + $shadow->setDirection(PHPExcel_Shared_Drawing::angleToDegrees(self::getArrayItem($outerShdw->attributes(), "dir"))); + $shadow->setAlignment((string) self::getArrayItem($outerShdw->attributes(), "algn")); + $shadow->getColor()->setRGB(self::getArrayItem($outerShdw->srgbClr->attributes(), "val")); + $shadow->setAlpha(self::getArrayItem($outerShdw->srgbClr->alpha->attributes(), "val") / 1000); + } + $objDrawing->setWorksheet($docSheet); + } elseif (($this->includeCharts) && ($twoCellAnchor->graphicFrame)) { + $fromCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->from->col) . ($twoCellAnchor->from->row + 1); + $fromOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->colOff); + $fromOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->from->rowOff); + $toCoordinate = PHPExcel_Cell::stringFromColumnIndex((string) $twoCellAnchor->to->col) . ($twoCellAnchor->to->row + 1); + $toOffsetX = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->colOff); + $toOffsetY = PHPExcel_Shared_Drawing::EMUToPixels($twoCellAnchor->to->rowOff); + $graphic = $twoCellAnchor->graphicFrame->children("http://schemas.openxmlformats.org/drawingml/2006/main")->graphic; + $chartRef = $graphic->graphicData->children("http://schemas.openxmlformats.org/drawingml/2006/chart")->chart; + $thisChart = (string) $chartRef->attributes("http://schemas.openxmlformats.org/officeDocument/2006/relationships"); + + $chartDetails[$docSheet->getTitle().'!'.$thisChart] = array( + 'fromCoordinate' => $fromCoordinate, + 'fromOffsetX' => $fromOffsetX, + 'fromOffsetY' => $fromOffsetY, + 'toCoordinate' => $toCoordinate, + 'toOffsetX' => $toOffsetX, + 'toOffsetY' => $toOffsetY, + 'worksheetTitle' => $docSheet->getTitle() + ); + } + } + } + } + } + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange, '!')) !== false) { + $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '' && (string)$definedName['localSheetId'] == $sheetId) { + // Switch on type + switch ((string)$definedName['name']) { + case '_xlnm._FilterDatabase': + if ((string)$definedName['hidden'] !== '1') { + $extractedRange = explode(',', $extractedRange); + foreach ($extractedRange as $range) { + $autoFilterRange = $range; + if (strpos($autoFilterRange, ':') !== false) { + $docSheet->getAutoFilter()->setRange($autoFilterRange); + } + } + } + break; + case '_xlnm.Print_Titles': + // Split $extractedRange + $extractedRange = explode(',', $extractedRange); + + // Set print titles + foreach ($extractedRange as $range) { + $matches = array(); + $range = str_replace('$', '', $range); + + // check for repeating columns, e g. 'A:A' or 'A:D' + if (preg_match('/!?([A-Z]+)\:([A-Z]+)$/', $range, $matches)) { + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($matches[1], $matches[2])); + } elseif (preg_match('/!?(\d+)\:(\d+)$/', $range, $matches)) { + // check for repeating rows, e.g. '1:1' or '1:5' + $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($matches[1], $matches[2])); + } + } + break; + case '_xlnm.Print_Area': + $rangeSets = explode(',', $extractedRange); // FIXME: what if sheetname contains comma? + $newRangeSets = array(); + foreach ($rangeSets as $rangeSet) { + $range = explode('!', $rangeSet); // FIXME: what if sheetname contains exclamation mark? + $rangeSet = isset($range[1]) ? $range[1] : $range[0]; + if (strpos($rangeSet, ':') === false) { + $rangeSet = $rangeSet . ':' . $rangeSet; + } + $newRangeSets[] = str_replace('$', '', $rangeSet); + } + $docSheet->getPageSetup()->setPrintArea(implode(',', $newRangeSets)); + break; + + default: + break; + } + } + } + } + + // Next sheet id + ++$sheetId; + } + + // Loop through definedNames + if ($xmlWorkbook->definedNames) { + foreach ($xmlWorkbook->definedNames->definedName as $definedName) { + // Extract range + $extractedRange = (string)$definedName; + $extractedRange = preg_replace('/\'(\w+)\'\!/', '', $extractedRange); + if (($spos = strpos($extractedRange, '!')) !== false) { + $extractedRange = substr($extractedRange, 0, $spos).str_replace('$', '', substr($extractedRange, $spos)); + } else { + $extractedRange = str_replace('$', '', $extractedRange); + } + + // Valid range? + if (stripos((string)$definedName, '#REF!') !== false || $extractedRange == '') { + continue; + } + + // Some definedNames are only applicable if we are on the same sheet... + if ((string)$definedName['localSheetId'] != '') { + // Local defined name + // Switch on type + switch ((string)$definedName['name']) { + case '_xlnm._FilterDatabase': + case '_xlnm.Print_Titles': + case '_xlnm.Print_Area': + break; + default: + if ($mapSheetId[(integer) $definedName['localSheetId']] !== null) { + $range = explode('!', (string)$definedName); + if (count($range) == 2) { + $range[0] = str_replace("''", "'", $range[0]); + $range[0] = str_replace("'", "", $range[0]); + if ($worksheet = $docSheet->getParent()->getSheetByName($range[0])) { + $extractedRange = str_replace('$', '', $range[1]); + $scope = $docSheet->getParent()->getSheet($mapSheetId[(integer) $definedName['localSheetId']]); + $excel->addNamedRange(new PHPExcel_NamedRange((string)$definedName['name'], $worksheet, $extractedRange, true, $scope)); + } + } + } + break; + } + } elseif (!isset($definedName['localSheetId'])) { + // "Global" definedNames + $locatedSheet = null; + $extractedSheetName = ''; + if (strpos((string)$definedName, '!') !== false) { + // Extract sheet name + $extractedSheetName = PHPExcel_Worksheet::extractSheetTitle((string)$definedName, true); + $extractedSheetName = $extractedSheetName[0]; + + // Locate sheet + $locatedSheet = $excel->getSheetByName($extractedSheetName); + + // Modify range + $range = explode('!', $extractedRange); + $extractedRange = isset($range[1]) ? $range[1] : $range[0]; + } + + if ($locatedSheet !== null) { + $excel->addNamedRange(new PHPExcel_NamedRange((string)$definedName['name'], $locatedSheet, $extractedRange, false)); + } + } + } + } + } + + if ((!$this->readDataOnly) || (!empty($this->loadSheetsOnly))) { + // active sheet index + $activeTab = intval($xmlWorkbook->bookViews->workbookView["activeTab"]); // refers to old sheet index + + // keep active sheet index if sheet is still loaded, else first sheet is set as the active + if (isset($mapSheetId[$activeTab]) && $mapSheetId[$activeTab] !== null) { + $excel->setActiveSheetIndex($mapSheetId[$activeTab]); + } else { + if ($excel->getSheetCount() == 0) { + $excel->createSheet(); + } + $excel->setActiveSheetIndex(0); + } + } + break; + } + } + + if (!$this->readDataOnly) { + $contentTypes = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, "[Content_Types].xml")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + foreach ($contentTypes->Override as $contentType) { + switch ($contentType["ContentType"]) { + case "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": + if ($this->includeCharts) { + $chartEntryRef = ltrim($contentType['PartName'], '/'); + $chartElements = simplexml_load_string($this->securityScan($this->getFromZipArchive($zip, $chartEntryRef)), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $objChart = PHPExcel_Reader_Excel2007_Chart::readChart($chartElements, basename($chartEntryRef, '.xml')); + +// echo 'Chart ', $chartEntryRef, '<br />'; +// var_dump($charts[$chartEntryRef]); +// + if (isset($charts[$chartEntryRef])) { + $chartPositionRef = $charts[$chartEntryRef]['sheet'].'!'.$charts[$chartEntryRef]['id']; +// echo 'Position Ref ', $chartPositionRef, '<br />'; + if (isset($chartDetails[$chartPositionRef])) { +// var_dump($chartDetails[$chartPositionRef]); + + $excel->getSheetByName($charts[$chartEntryRef]['sheet'])->addChart($objChart); + $objChart->setWorksheet($excel->getSheetByName($charts[$chartEntryRef]['sheet'])); + $objChart->setTopLeftPosition($chartDetails[$chartPositionRef]['fromCoordinate'], $chartDetails[$chartPositionRef]['fromOffsetX'], $chartDetails[$chartPositionRef]['fromOffsetY']); + $objChart->setBottomRightPosition($chartDetails[$chartPositionRef]['toCoordinate'], $chartDetails[$chartPositionRef]['toOffsetX'], $chartDetails[$chartPositionRef]['toOffsetY']); + } + } + } + } + } + } + + $zip->close(); + + return $excel; + } + + private static function readColor($color, $background = false) + { + if (isset($color["rgb"])) { + return (string)$color["rgb"]; + } elseif (isset($color["indexed"])) { + return PHPExcel_Style_Color::indexedColor($color["indexed"]-7, $background)->getARGB(); + } elseif (isset($color["theme"])) { + if (self::$theme !== null) { + $returnColour = self::$theme->getColourByIndex((int)$color["theme"]); + if (isset($color["tint"])) { + $tintAdjust = (float) $color["tint"]; + $returnColour = PHPExcel_Style_Color::changeBrightness($returnColour, $tintAdjust); + } + return 'FF'.$returnColour; + } + } + + if ($background) { + return 'FFFFFFFF'; + } + return 'FF000000'; + } + + private static function readStyle($docStyle, $style) + { + // format code +// if (isset($style->numFmt)) { +// if (isset($style->numFmt['formatCode'])) { +// $docStyle->getNumberFormat()->setFormatCode((string) $style->numFmt['formatCode']); +// } else { + $docStyle->getNumberFormat()->setFormatCode($style->numFmt); +// } +// } + + // font + if (isset($style->font)) { + $docStyle->getFont()->setName((string) $style->font->name["val"]); + $docStyle->getFont()->setSize((string) $style->font->sz["val"]); + if (isset($style->font->b)) { + $docStyle->getFont()->setBold(!isset($style->font->b["val"]) || self::boolean((string) $style->font->b["val"])); + } + if (isset($style->font->i)) { + $docStyle->getFont()->setItalic(!isset($style->font->i["val"]) || self::boolean((string) $style->font->i["val"])); + } + if (isset($style->font->strike)) { + $docStyle->getFont()->setStrikethrough(!isset($style->font->strike["val"]) || self::boolean((string) $style->font->strike["val"])); + } + $docStyle->getFont()->getColor()->setARGB(self::readColor($style->font->color)); + + if (isset($style->font->u) && !isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } elseif (isset($style->font->u) && isset($style->font->u["val"])) { + $docStyle->getFont()->setUnderline((string)$style->font->u["val"]); + } + + if (isset($style->font->vertAlign) && isset($style->font->vertAlign["val"])) { + $vertAlign = strtolower((string)$style->font->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $docStyle->getFont()->setSuperScript(true); + } + if ($vertAlign == 'subscript') { + $docStyle->getFont()->setSubScript(true); + } + } + } + + // fill + if (isset($style->fill)) { + if ($style->fill->gradientFill) { + $gradientFill = $style->fill->gradientFill[0]; + if (!empty($gradientFill["type"])) { + $docStyle->getFill()->setFillType((string) $gradientFill["type"]); + } + $docStyle->getFill()->setRotation(floatval($gradientFill["degree"])); + $gradientFill->registerXPathNamespace("sml", "http://schemas.openxmlformats.org/spreadsheetml/2006/main"); + $docStyle->getFill()->getStartColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath("sml:stop[@position=0]"))->color)); + $docStyle->getFill()->getEndColor()->setARGB(self::readColor(self::getArrayItem($gradientFill->xpath("sml:stop[@position=1]"))->color)); + } elseif ($style->fill->patternFill) { + $patternType = (string)$style->fill->patternFill["patternType"] != '' ? (string)$style->fill->patternFill["patternType"] : 'solid'; + $docStyle->getFill()->setFillType($patternType); + if ($style->fill->patternFill->fgColor) { + $docStyle->getFill()->getStartColor()->setARGB(self::readColor($style->fill->patternFill->fgColor, true)); + } else { + $docStyle->getFill()->getStartColor()->setARGB('FF000000'); + } + if ($style->fill->patternFill->bgColor) { + $docStyle->getFill()->getEndColor()->setARGB(self::readColor($style->fill->patternFill->bgColor, true)); + } + } + } + + // border + if (isset($style->border)) { + $diagonalUp = self::boolean((string) $style->border["diagonalUp"]); + $diagonalDown = self::boolean((string) $style->border["diagonalDown"]); + if (!$diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE); + } elseif ($diagonalUp && !$diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP); + } elseif (!$diagonalUp && $diagonalDown) { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN); + } else { + $docStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH); + } + self::readBorder($docStyle->getBorders()->getLeft(), $style->border->left); + self::readBorder($docStyle->getBorders()->getRight(), $style->border->right); + self::readBorder($docStyle->getBorders()->getTop(), $style->border->top); + self::readBorder($docStyle->getBorders()->getBottom(), $style->border->bottom); + self::readBorder($docStyle->getBorders()->getDiagonal(), $style->border->diagonal); + } + + // alignment + if (isset($style->alignment)) { + $docStyle->getAlignment()->setHorizontal((string) $style->alignment["horizontal"]); + $docStyle->getAlignment()->setVertical((string) $style->alignment["vertical"]); + + $textRotation = 0; + if ((int)$style->alignment["textRotation"] <= 90) { + $textRotation = (int)$style->alignment["textRotation"]; + } elseif ((int)$style->alignment["textRotation"] > 90) { + $textRotation = 90 - (int)$style->alignment["textRotation"]; + } + + $docStyle->getAlignment()->setTextRotation(intval($textRotation)); + $docStyle->getAlignment()->setWrapText(self::boolean((string) $style->alignment["wrapText"])); + $docStyle->getAlignment()->setShrinkToFit(self::boolean((string) $style->alignment["shrinkToFit"])); + $docStyle->getAlignment()->setIndent(intval((string)$style->alignment["indent"]) > 0 ? intval((string)$style->alignment["indent"]) : 0); + $docStyle->getAlignment()->setReadorder(intval((string)$style->alignment["readingOrder"]) > 0 ? intval((string)$style->alignment["readingOrder"]) : 0); + } + + // protection + if (isset($style->protection)) { + if (isset($style->protection['locked'])) { + if (self::boolean((string) $style->protection['locked'])) { + $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setLocked(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + } + } + + if (isset($style->protection['hidden'])) { + if (self::boolean((string) $style->protection['hidden'])) { + $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_PROTECTED); + } else { + $docStyle->getProtection()->setHidden(PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + } + } + } + + // top-level style settings + if (isset($style->quotePrefix)) { + $docStyle->setQuotePrefix($style->quotePrefix); + } + } + + private static function readBorder($docBorder, $eleBorder) + { + if (isset($eleBorder["style"])) { + $docBorder->setBorderStyle((string) $eleBorder["style"]); + } + if (isset($eleBorder->color)) { + $docBorder->getColor()->setARGB(self::readColor($eleBorder->color)); + } + } + + private function parseRichText($is = null) + { + $value = new PHPExcel_RichText(); + + if (isset($is->t)) { + $value->createText(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $is->t)); + } else { + if (is_object($is->r)) { + foreach ($is->r as $run) { + if (!isset($run->rPr)) { + $objText = $value->createText(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $run->t)); + + } else { + $objText = $value->createTextRun(PHPExcel_Shared_String::ControlCharacterOOXML2PHP((string) $run->t)); + + if (isset($run->rPr->rFont["val"])) { + $objText->getFont()->setName((string) $run->rPr->rFont["val"]); + } + if (isset($run->rPr->sz["val"])) { + $objText->getFont()->setSize((string) $run->rPr->sz["val"]); + } + if (isset($run->rPr->color)) { + $objText->getFont()->setColor(new PHPExcel_Style_Color(self::readColor($run->rPr->color))); + } + if ((isset($run->rPr->b["val"]) && self::boolean((string) $run->rPr->b["val"])) || + (isset($run->rPr->b) && !isset($run->rPr->b["val"]))) { + $objText->getFont()->setBold(true); + } + if ((isset($run->rPr->i["val"]) && self::boolean((string) $run->rPr->i["val"])) || + (isset($run->rPr->i) && !isset($run->rPr->i["val"]))) { + $objText->getFont()->setItalic(true); + } + if (isset($run->rPr->vertAlign) && isset($run->rPr->vertAlign["val"])) { + $vertAlign = strtolower((string)$run->rPr->vertAlign["val"]); + if ($vertAlign == 'superscript') { + $objText->getFont()->setSuperScript(true); + } + if ($vertAlign == 'subscript') { + $objText->getFont()->setSubScript(true); + } + } + if (isset($run->rPr->u) && !isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } elseif (isset($run->rPr->u) && isset($run->rPr->u["val"])) { + $objText->getFont()->setUnderline((string)$run->rPr->u["val"]); + } + if ((isset($run->rPr->strike["val"]) && self::boolean((string) $run->rPr->strike["val"])) || + (isset($run->rPr->strike) && !isset($run->rPr->strike["val"]))) { + $objText->getFont()->setStrikethrough(true); + } + } + } + } + } + + return $value; + } + + private function readRibbon($excel, $customUITarget, $zip) + { + $baseDir = dirname($customUITarget); + $nameCustomUI = basename($customUITarget); + // get the xml file (ribbon) + $localRibbon = $this->getFromZipArchive($zip, $customUITarget); + $customUIImagesNames = array(); + $customUIImagesBinaries = array(); + // something like customUI/_rels/customUI.xml.rels + $pathRels = $baseDir . '/_rels/' . $nameCustomUI . '.rels'; + $dataRels = $this->getFromZipArchive($zip, $pathRels); + if ($dataRels) { + // exists and not empty if the ribbon have some pictures (other than internal MSO) + $UIRels = simplexml_load_string($this->securityScan($dataRels), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + if ($UIRels) { + // we need to save id and target to avoid parsing customUI.xml and "guess" if it's a pseudo callback who load the image + foreach ($UIRels->Relationship as $ele) { + if ($ele["Type"] == 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image') { + // an image ? + $customUIImagesNames[(string) $ele['Id']] = (string)$ele['Target']; + $customUIImagesBinaries[(string)$ele['Target']] = $this->getFromZipArchive($zip, $baseDir . '/' . (string) $ele['Target']); + } + } + } + } + if ($localRibbon) { + $excel->setRibbonXMLData($customUITarget, $localRibbon); + if (count($customUIImagesNames) > 0 && count($customUIImagesBinaries) > 0) { + $excel->setRibbonBinObjects($customUIImagesNames, $customUIImagesBinaries); + } else { + $excel->setRibbonBinObjects(null); + } + } else { + $excel->setRibbonXMLData(null); + $excel->setRibbonBinObjects(null); + } + } + + private static function getArrayItem($array, $key = 0) + { + return (isset($array[$key]) ? $array[$key] : null); + } + + private static function dirAdd($base, $add) + { + return preg_replace('~[^/]+/\.\./~', '', dirname($base) . "/$add"); + } + + private static function toCSSArray($style) + { + $style = str_replace(array("\r","\n"), "", $style); + + $temp = explode(';', $style); + $style = array(); + foreach ($temp as $item) { + $item = explode(':', $item); + + if (strpos($item[1], 'px') !== false) { + $item[1] = str_replace('px', '', $item[1]); + } + if (strpos($item[1], 'pt') !== false) { + $item[1] = str_replace('pt', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::fontSizeToPixels($item[1]); + } + if (strpos($item[1], 'in') !== false) { + $item[1] = str_replace('in', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::inchSizeToPixels($item[1]); + } + if (strpos($item[1], 'cm') !== false) { + $item[1] = str_replace('cm', '', $item[1]); + $item[1] = PHPExcel_Shared_Font::centimeterSizeToPixels($item[1]); + } + + $style[$item[0]] = $item[1]; + } + + return $style; + } + + private static function boolean($value = null) + { + if (is_object($value)) { + $value = (string) $value; + } + if (is_numeric($value)) { + return (bool) $value; + } + return ($value === 'true' || $value === 'TRUE'); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Chart.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Chart.php new file mode 100644 index 00000000..590bf2d8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Chart.php @@ -0,0 +1,520 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +/** + * PHPExcel_Reader_Excel2007_Chart + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Excel2007_Chart +{ + private static function getAttribute($component, $name, $format) + { + $attributes = $component->attributes(); + if (isset($attributes[$name])) { + if ($format == 'string') { + return (string) $attributes[$name]; + } elseif ($format == 'integer') { + return (integer) $attributes[$name]; + } elseif ($format == 'boolean') { + return (boolean) ($attributes[$name] === '0' || $attributes[$name] !== 'true') ? false : true; + } else { + return (float) $attributes[$name]; + } + } + return null; + } + + + private static function readColor($color, $background = false) + { + if (isset($color["rgb"])) { + return (string)$color["rgb"]; + } elseif (isset($color["indexed"])) { + return PHPExcel_Style_Color::indexedColor($color["indexed"]-7, $background)->getARGB(); + } + } + + public static function readChart($chartElements, $chartName) + { + $namespacesChartMeta = $chartElements->getNamespaces(true); + $chartElementsC = $chartElements->children($namespacesChartMeta['c']); + + $XaxisLabel = $YaxisLabel = $legend = $title = null; + $dispBlanksAs = $plotVisOnly = null; + + foreach ($chartElementsC as $chartElementKey => $chartElement) { + switch ($chartElementKey) { + case "chart": + foreach ($chartElement as $chartDetailsKey => $chartDetails) { + $chartDetailsC = $chartDetails->children($namespacesChartMeta['c']); + switch ($chartDetailsKey) { + case "plotArea": + $plotAreaLayout = $XaxisLable = $YaxisLable = null; + $plotSeries = $plotAttributes = array(); + foreach ($chartDetails as $chartDetailKey => $chartDetail) { + switch ($chartDetailKey) { + case "layout": + $plotAreaLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'plotArea'); + break; + case "catAx": + if (isset($chartDetail->title)) { + $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); + } + break; + case "dateAx": + if (isset($chartDetail->title)) { + $XaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); + } + break; + case "valAx": + if (isset($chartDetail->title)) { + $YaxisLabel = self::chartTitle($chartDetail->title->children($namespacesChartMeta['c']), $namespacesChartMeta, 'cat'); + } + break; + case "barChart": + case "bar3DChart": + $barDirection = self::getAttribute($chartDetail->barDir, 'val', 'string'); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotDirection($barDirection); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "lineChart": + case "line3DChart": + $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "areaChart": + case "area3DChart": + $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "doughnutChart": + case "pieChart": + case "pie3DChart": + $explosion = isset($chartDetail->ser->explosion); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotStyle($explosion); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "scatterChart": + $scatterStyle = self::getAttribute($chartDetail->scatterStyle, 'val', 'string'); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotStyle($scatterStyle); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "bubbleChart": + $bubbleScale = self::getAttribute($chartDetail->bubbleScale, 'val', 'integer'); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotStyle($bubbleScale); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "radarChart": + $radarStyle = self::getAttribute($chartDetail->radarStyle, 'val', 'string'); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotStyle($radarStyle); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "surfaceChart": + case "surface3DChart": + $wireFrame = self::getAttribute($chartDetail->wireframe, 'val', 'boolean'); + $plotSer = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotSer->setPlotStyle($wireFrame); + $plotSeries[] = $plotSer; + $plotAttributes = self::readChartAttributes($chartDetail); + break; + case "stockChart": + $plotSeries[] = self::chartDataSeries($chartDetail, $namespacesChartMeta, $chartDetailKey); + $plotAttributes = self::readChartAttributes($plotAreaLayout); + break; + } + } + if ($plotAreaLayout == null) { + $plotAreaLayout = new PHPExcel_Chart_Layout(); + } + $plotArea = new PHPExcel_Chart_PlotArea($plotAreaLayout, $plotSeries); + self::setChartAttributes($plotAreaLayout, $plotAttributes); + break; + case "plotVisOnly": + $plotVisOnly = self::getAttribute($chartDetails, 'val', 'string'); + break; + case "dispBlanksAs": + $dispBlanksAs = self::getAttribute($chartDetails, 'val', 'string'); + break; + case "title": + $title = self::chartTitle($chartDetails, $namespacesChartMeta, 'title'); + break; + case "legend": + $legendPos = 'r'; + $legendLayout = null; + $legendOverlay = false; + foreach ($chartDetails as $chartDetailKey => $chartDetail) { + switch ($chartDetailKey) { + case "legendPos": + $legendPos = self::getAttribute($chartDetail, 'val', 'string'); + break; + case "overlay": + $legendOverlay = self::getAttribute($chartDetail, 'val', 'boolean'); + break; + case "layout": + $legendLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta, 'legend'); + break; + } + } + $legend = new PHPExcel_Chart_Legend($legendPos, $legendLayout, $legendOverlay); + break; + } + } + } + } + $chart = new PHPExcel_Chart($chartName, $title, $legend, $plotArea, $plotVisOnly, $dispBlanksAs, $XaxisLabel, $YaxisLabel); + + return $chart; + } + + private static function chartTitle($titleDetails, $namespacesChartMeta, $type) + { + $caption = array(); + $titleLayout = null; + foreach ($titleDetails as $titleDetailKey => $chartDetail) { + switch ($titleDetailKey) { + case "tx": + $titleDetails = $chartDetail->rich->children($namespacesChartMeta['a']); + foreach ($titleDetails as $titleKey => $titleDetail) { + switch ($titleKey) { + case "p": + $titleDetailPart = $titleDetail->children($namespacesChartMeta['a']); + $caption[] = self::parseRichText($titleDetailPart); + } + } + break; + case "layout": + $titleLayout = self::chartLayoutDetails($chartDetail, $namespacesChartMeta); + break; + } + } + + return new PHPExcel_Chart_Title($caption, $titleLayout); + } + + private static function chartLayoutDetails($chartDetail, $namespacesChartMeta) + { + if (!isset($chartDetail->manualLayout)) { + return null; + } + $details = $chartDetail->manualLayout->children($namespacesChartMeta['c']); + if (is_null($details)) { + return null; + } + $layout = array(); + foreach ($details as $detailKey => $detail) { +// echo $detailKey, ' => ',self::getAttribute($detail, 'val', 'string'),PHP_EOL; + $layout[$detailKey] = self::getAttribute($detail, 'val', 'string'); + } + return new PHPExcel_Chart_Layout($layout); + } + + private static function chartDataSeries($chartDetail, $namespacesChartMeta, $plotType) + { + $multiSeriesType = null; + $smoothLine = false; + $seriesLabel = $seriesCategory = $seriesValues = $plotOrder = array(); + + $seriesDetailSet = $chartDetail->children($namespacesChartMeta['c']); + foreach ($seriesDetailSet as $seriesDetailKey => $seriesDetails) { + switch ($seriesDetailKey) { + case "grouping": + $multiSeriesType = self::getAttribute($chartDetail->grouping, 'val', 'string'); + break; + case "ser": + $marker = null; + foreach ($seriesDetails as $seriesKey => $seriesDetail) { + switch ($seriesKey) { + case "idx": + $seriesIndex = self::getAttribute($seriesDetail, 'val', 'integer'); + break; + case "order": + $seriesOrder = self::getAttribute($seriesDetail, 'val', 'integer'); + $plotOrder[$seriesIndex] = $seriesOrder; + break; + case "tx": + $seriesLabel[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); + break; + case "marker": + $marker = self::getAttribute($seriesDetail->symbol, 'val', 'string'); + break; + case "smooth": + $smoothLine = self::getAttribute($seriesDetail, 'val', 'boolean'); + break; + case "cat": + $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta); + break; + case "val": + $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); + break; + case "xVal": + $seriesCategory[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); + break; + case "yVal": + $seriesValues[$seriesIndex] = self::chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker); + break; + } + } + } + } + return new PHPExcel_Chart_DataSeries($plotType, $multiSeriesType, $plotOrder, $seriesLabel, $seriesCategory, $seriesValues, $smoothLine); + } + + + private static function chartDataSeriesValueSet($seriesDetail, $namespacesChartMeta, $marker = null, $smoothLine = false) + { + if (isset($seriesDetail->strRef)) { + $seriesSource = (string) $seriesDetail->strRef->f; + $seriesData = self::chartDataSeriesValues($seriesDetail->strRef->strCache->children($namespacesChartMeta['c']), 's'); + + return new PHPExcel_Chart_DataSeriesValues('String', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine); + } elseif (isset($seriesDetail->numRef)) { + $seriesSource = (string) $seriesDetail->numRef->f; + $seriesData = self::chartDataSeriesValues($seriesDetail->numRef->numCache->children($namespacesChartMeta['c'])); + + return new PHPExcel_Chart_DataSeriesValues('Number', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine); + } elseif (isset($seriesDetail->multiLvlStrRef)) { + $seriesSource = (string) $seriesDetail->multiLvlStrRef->f; + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlStrRef->multiLvlStrCache->children($namespacesChartMeta['c']), 's'); + $seriesData['pointCount'] = count($seriesData['dataValues']); + + return new PHPExcel_Chart_DataSeriesValues('String', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine); + } elseif (isset($seriesDetail->multiLvlNumRef)) { + $seriesSource = (string) $seriesDetail->multiLvlNumRef->f; + $seriesData = self::chartDataSeriesValuesMultiLevel($seriesDetail->multiLvlNumRef->multiLvlNumCache->children($namespacesChartMeta['c']), 's'); + $seriesData['pointCount'] = count($seriesData['dataValues']); + + return new PHPExcel_Chart_DataSeriesValues('String', $seriesSource, $seriesData['formatCode'], $seriesData['pointCount'], $seriesData['dataValues'], $marker, $smoothLine); + } + return null; + } + + + private static function chartDataSeriesValues($seriesValueSet, $dataType = 'n') + { + $seriesVal = array(); + $formatCode = ''; + $pointCount = 0; + + foreach ($seriesValueSet as $seriesValueIdx => $seriesValue) { + switch ($seriesValueIdx) { + case 'ptCount': + $pointCount = self::getAttribute($seriesValue, 'val', 'integer'); + break; + case 'formatCode': + $formatCode = (string) $seriesValue; + break; + case 'pt': + $pointVal = self::getAttribute($seriesValue, 'idx', 'integer'); + if ($dataType == 's') { + $seriesVal[$pointVal] = (string) $seriesValue->v; + } else { + $seriesVal[$pointVal] = (float) $seriesValue->v; + } + break; + } + } + + return array( + 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal + ); + } + + private static function chartDataSeriesValuesMultiLevel($seriesValueSet, $dataType = 'n') + { + $seriesVal = array(); + $formatCode = ''; + $pointCount = 0; + + foreach ($seriesValueSet->lvl as $seriesLevelIdx => $seriesLevel) { + foreach ($seriesLevel as $seriesValueIdx => $seriesValue) { + switch ($seriesValueIdx) { + case 'ptCount': + $pointCount = self::getAttribute($seriesValue, 'val', 'integer'); + break; + case 'formatCode': + $formatCode = (string) $seriesValue; + break; + case 'pt': + $pointVal = self::getAttribute($seriesValue, 'idx', 'integer'); + if ($dataType == 's') { + $seriesVal[$pointVal][] = (string) $seriesValue->v; + } else { + $seriesVal[$pointVal][] = (float) $seriesValue->v; + } + break; + } + } + } + + return array( + 'formatCode' => $formatCode, + 'pointCount' => $pointCount, + 'dataValues' => $seriesVal + ); + } + + private static function parseRichText($titleDetailPart = null) + { + $value = new PHPExcel_RichText(); + + foreach ($titleDetailPart as $titleDetailElementKey => $titleDetailElement) { + if (isset($titleDetailElement->t)) { + $objText = $value->createTextRun((string) $titleDetailElement->t); + } + if (isset($titleDetailElement->rPr)) { + if (isset($titleDetailElement->rPr->rFont["val"])) { + $objText->getFont()->setName((string) $titleDetailElement->rPr->rFont["val"]); + } + + $fontSize = (self::getAttribute($titleDetailElement->rPr, 'sz', 'integer')); + if (!is_null($fontSize)) { + $objText->getFont()->setSize(floor($fontSize / 100)); + } + + $fontColor = (self::getAttribute($titleDetailElement->rPr, 'color', 'string')); + if (!is_null($fontColor)) { + $objText->getFont()->setColor(new PHPExcel_Style_Color(self::readColor($fontColor))); + } + + $bold = self::getAttribute($titleDetailElement->rPr, 'b', 'boolean'); + if (!is_null($bold)) { + $objText->getFont()->setBold($bold); + } + + $italic = self::getAttribute($titleDetailElement->rPr, 'i', 'boolean'); + if (!is_null($italic)) { + $objText->getFont()->setItalic($italic); + } + + $baseline = self::getAttribute($titleDetailElement->rPr, 'baseline', 'integer'); + if (!is_null($baseline)) { + if ($baseline > 0) { + $objText->getFont()->setSuperScript(true); + } elseif ($baseline < 0) { + $objText->getFont()->setSubScript(true); + } + } + + $underscore = (self::getAttribute($titleDetailElement->rPr, 'u', 'string')); + if (!is_null($underscore)) { + if ($underscore == 'sng') { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + } elseif ($underscore == 'dbl') { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLE); + } else { + $objText->getFont()->setUnderline(PHPExcel_Style_Font::UNDERLINE_NONE); + } + } + + $strikethrough = (self::getAttribute($titleDetailElement->rPr, 's', 'string')); + if (!is_null($strikethrough)) { + if ($strikethrough == 'noStrike') { + $objText->getFont()->setStrikethrough(false); + } else { + $objText->getFont()->setStrikethrough(true); + } + } + } + } + + return $value; + } + + private static function readChartAttributes($chartDetail) + { + $plotAttributes = array(); + if (isset($chartDetail->dLbls)) { + if (isset($chartDetail->dLbls->howLegendKey)) { + $plotAttributes['showLegendKey'] = self::getAttribute($chartDetail->dLbls->showLegendKey, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showVal)) { + $plotAttributes['showVal'] = self::getAttribute($chartDetail->dLbls->showVal, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showCatName)) { + $plotAttributes['showCatName'] = self::getAttribute($chartDetail->dLbls->showCatName, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showSerName)) { + $plotAttributes['showSerName'] = self::getAttribute($chartDetail->dLbls->showSerName, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showPercent)) { + $plotAttributes['showPercent'] = self::getAttribute($chartDetail->dLbls->showPercent, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showBubbleSize)) { + $plotAttributes['showBubbleSize'] = self::getAttribute($chartDetail->dLbls->showBubbleSize, 'val', 'string'); + } + if (isset($chartDetail->dLbls->showLeaderLines)) { + $plotAttributes['showLeaderLines'] = self::getAttribute($chartDetail->dLbls->showLeaderLines, 'val', 'string'); + } + } + + return $plotAttributes; + } + + private static function setChartAttributes($plotArea, $plotAttributes) + { + foreach ($plotAttributes as $plotAttributeKey => $plotAttributeValue) { + switch ($plotAttributeKey) { + case 'showLegendKey': + $plotArea->setShowLegendKey($plotAttributeValue); + break; + case 'showVal': + $plotArea->setShowVal($plotAttributeValue); + break; + case 'showCatName': + $plotArea->setShowCatName($plotAttributeValue); + break; + case 'showSerName': + $plotArea->setShowSerName($plotAttributeValue); + break; + case 'showPercent': + $plotArea->setShowPercent($plotAttributeValue); + break; + case 'showBubbleSize': + $plotArea->setShowBubbleSize($plotAttributeValue); + break; + case 'showLeaderLines': + $plotArea->setShowLeaderLines($plotAttributeValue); + break; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Theme.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Theme.php new file mode 100644 index 00000000..134f4b60 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel2007/Theme.php @@ -0,0 +1,127 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Reader_Excel2007_Theme + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Reader_Excel2007_Theme +{ + /** + * Theme Name + * + * @var string + */ + private $themeName; + + /** + * Colour Scheme Name + * + * @var string + */ + private $colourSchemeName; + + /** + * Colour Map indexed by position + * + * @var array of string + */ + private $colourMapValues; + + + /** + * Colour Map + * + * @var array of string + */ + private $colourMap; + + + /** + * Create a new PHPExcel_Theme + * + */ + public function __construct($themeName, $colourSchemeName, $colourMap) + { + // Initialise values + $this->themeName = $themeName; + $this->colourSchemeName = $colourSchemeName; + $this->colourMap = $colourMap; + } + + /** + * Get Theme Name + * + * @return string + */ + public function getThemeName() + { + return $this->themeName; + } + + /** + * Get colour Scheme Name + * + * @return string + */ + public function getColourSchemeName() + { + return $this->colourSchemeName; + } + + /** + * Get colour Map Value by Position + * + * @return string + */ + public function getColourByIndex($index = 0) + { + if (isset($this->colourMap[$index])) { + return $this->colourMap[$index]; + } + return null; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != '_parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5.php new file mode 100644 index 00000000..62e971d2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5.php @@ -0,0 +1,7594 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_Excel5 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of ParseXL (used as the base for this class): +// -------------------------------------------------------------------------------- +// Adapted from Excel_Spreadsheet_Reader developed by users bizon153, +// trex005, and mmp11 (SourceForge.net) +// http://sourceforge.net/projects/phpexcelreader/ +// Primary changes made by canyoncasa (dvc) for ParseXL 1.00 ... +// Modelled moreso after Perl Excel Parse/Write modules +// Added Parse_Excel_Spreadsheet object +// Reads a whole worksheet or tab as row,column array or as +// associated hash of indexed rows and named column fields +// Added variables for worksheet (tab) indexes and names +// Added an object call for loading individual woorksheets +// Changed default indexing defaults to 0 based arrays +// Fixed date/time and percent formats +// Includes patches found at SourceForge... +// unicode patch by nobody +// unpack("d") machine depedency patch by matchy +// boundsheet utf16 patch by bjaenichen +// Renamed functions for shorter names +// General code cleanup and rigor, including <80 column width +// Included a testcase Excel file and PHP example calls +// Code works for PHP 5.x + +// Primary changes made by canyoncasa (dvc) for ParseXL 1.10 ... +// http://sourceforge.net/tracker/index.php?func=detail&aid=1466964&group_id=99160&atid=623334 +// Decoding of formula conditions, results, and tokens. +// Support for user-defined named cells added as an array "namedcells" +// Patch code for user-defined named cells supports single cells only. +// NOTE: this patch only works for BIFF8 as BIFF5-7 use a different +// external sheet reference structure +class PHPExcel_Reader_Excel5 extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + // ParseXL definitions + const XLS_BIFF8 = 0x0600; + const XLS_BIFF7 = 0x0500; + const XLS_WorkbookGlobals = 0x0005; + const XLS_Worksheet = 0x0010; + + // record identifiers + const XLS_TYPE_FORMULA = 0x0006; + const XLS_TYPE_EOF = 0x000a; + const XLS_TYPE_PROTECT = 0x0012; + const XLS_TYPE_OBJECTPROTECT = 0x0063; + const XLS_TYPE_SCENPROTECT = 0x00dd; + const XLS_TYPE_PASSWORD = 0x0013; + const XLS_TYPE_HEADER = 0x0014; + const XLS_TYPE_FOOTER = 0x0015; + const XLS_TYPE_EXTERNSHEET = 0x0017; + const XLS_TYPE_DEFINEDNAME = 0x0018; + const XLS_TYPE_VERTICALPAGEBREAKS = 0x001a; + const XLS_TYPE_HORIZONTALPAGEBREAKS = 0x001b; + const XLS_TYPE_NOTE = 0x001c; + const XLS_TYPE_SELECTION = 0x001d; + const XLS_TYPE_DATEMODE = 0x0022; + const XLS_TYPE_EXTERNNAME = 0x0023; + const XLS_TYPE_LEFTMARGIN = 0x0026; + const XLS_TYPE_RIGHTMARGIN = 0x0027; + const XLS_TYPE_TOPMARGIN = 0x0028; + const XLS_TYPE_BOTTOMMARGIN = 0x0029; + const XLS_TYPE_PRINTGRIDLINES = 0x002b; + const XLS_TYPE_FILEPASS = 0x002f; + const XLS_TYPE_FONT = 0x0031; + const XLS_TYPE_CONTINUE = 0x003c; + const XLS_TYPE_PANE = 0x0041; + const XLS_TYPE_CODEPAGE = 0x0042; + const XLS_TYPE_DEFCOLWIDTH = 0x0055; + const XLS_TYPE_OBJ = 0x005d; + const XLS_TYPE_COLINFO = 0x007d; + const XLS_TYPE_IMDATA = 0x007f; + const XLS_TYPE_SHEETPR = 0x0081; + const XLS_TYPE_HCENTER = 0x0083; + const XLS_TYPE_VCENTER = 0x0084; + const XLS_TYPE_SHEET = 0x0085; + const XLS_TYPE_PALETTE = 0x0092; + const XLS_TYPE_SCL = 0x00a0; + const XLS_TYPE_PAGESETUP = 0x00a1; + const XLS_TYPE_MULRK = 0x00bd; + const XLS_TYPE_MULBLANK = 0x00be; + const XLS_TYPE_DBCELL = 0x00d7; + const XLS_TYPE_XF = 0x00e0; + const XLS_TYPE_MERGEDCELLS = 0x00e5; + const XLS_TYPE_MSODRAWINGGROUP = 0x00eb; + const XLS_TYPE_MSODRAWING = 0x00ec; + const XLS_TYPE_SST = 0x00fc; + const XLS_TYPE_LABELSST = 0x00fd; + const XLS_TYPE_EXTSST = 0x00ff; + const XLS_TYPE_EXTERNALBOOK = 0x01ae; + const XLS_TYPE_DATAVALIDATIONS = 0x01b2; + const XLS_TYPE_TXO = 0x01b6; + const XLS_TYPE_HYPERLINK = 0x01b8; + const XLS_TYPE_DATAVALIDATION = 0x01be; + const XLS_TYPE_DIMENSION = 0x0200; + const XLS_TYPE_BLANK = 0x0201; + const XLS_TYPE_NUMBER = 0x0203; + const XLS_TYPE_LABEL = 0x0204; + const XLS_TYPE_BOOLERR = 0x0205; + const XLS_TYPE_STRING = 0x0207; + const XLS_TYPE_ROW = 0x0208; + const XLS_TYPE_INDEX = 0x020b; + const XLS_TYPE_ARRAY = 0x0221; + const XLS_TYPE_DEFAULTROWHEIGHT = 0x0225; + const XLS_TYPE_WINDOW2 = 0x023e; + const XLS_TYPE_RK = 0x027e; + const XLS_TYPE_STYLE = 0x0293; + const XLS_TYPE_FORMAT = 0x041e; + const XLS_TYPE_SHAREDFMLA = 0x04bc; + const XLS_TYPE_BOF = 0x0809; + const XLS_TYPE_SHEETPROTECTION = 0x0867; + const XLS_TYPE_RANGEPROTECTION = 0x0868; + const XLS_TYPE_SHEETLAYOUT = 0x0862; + const XLS_TYPE_XFEXT = 0x087d; + const XLS_TYPE_PAGELAYOUTVIEW = 0x088b; + const XLS_TYPE_UNKNOWN = 0xffff; + + // Encryption type + const MS_BIFF_CRYPTO_NONE = 0; + const MS_BIFF_CRYPTO_XOR = 1; + const MS_BIFF_CRYPTO_RC4 = 2; + + // Size of stream blocks when using RC4 encryption + const REKEY_BLOCK = 0x400; + + /** + * Summary Information stream data. + * + * @var string + */ + private $summaryInformation; + + /** + * Extended Summary Information stream data. + * + * @var string + */ + private $documentSummaryInformation; + + /** + * User-Defined Properties stream data. + * + * @var string + */ + private $userDefinedProperties; + + /** + * Workbook stream data. (Includes workbook globals substream as well as sheet substreams) + * + * @var string + */ + private $data; + + /** + * Size in bytes of $this->data + * + * @var int + */ + private $dataSize; + + /** + * Current position in stream + * + * @var integer + */ + private $pos; + + /** + * Workbook to be returned by the reader. + * + * @var PHPExcel + */ + private $phpExcel; + + /** + * Worksheet that is currently being built by the reader. + * + * @var PHPExcel_Worksheet + */ + private $phpSheet; + + /** + * BIFF version + * + * @var int + */ + private $version; + + /** + * Codepage set in the Excel file being read. Only important for BIFF5 (Excel 5.0 - Excel 95) + * For BIFF8 (Excel 97 - Excel 2003) this will always have the value 'UTF-16LE' + * + * @var string + */ + private $codepage; + + /** + * Shared formats + * + * @var array + */ + private $formats; + + /** + * Shared fonts + * + * @var array + */ + private $objFonts; + + /** + * Color palette + * + * @var array + */ + private $palette; + + /** + * Worksheets + * + * @var array + */ + private $sheets; + + /** + * External books + * + * @var array + */ + private $externalBooks; + + /** + * REF structures. Only applies to BIFF8. + * + * @var array + */ + private $ref; + + /** + * External names + * + * @var array + */ + private $externalNames; + + /** + * Defined names + * + * @var array + */ + private $definedname; + + /** + * Shared strings. Only applies to BIFF8. + * + * @var array + */ + private $sst; + + /** + * Panes are frozen? (in sheet currently being read). See WINDOW2 record. + * + * @var boolean + */ + private $frozen; + + /** + * Fit printout to number of pages? (in sheet currently being read). See SHEETPR record. + * + * @var boolean + */ + private $isFitToPages; + + /** + * Objects. One OBJ record contributes with one entry. + * + * @var array + */ + private $objs; + + /** + * Text Objects. One TXO record corresponds with one entry. + * + * @var array + */ + private $textObjects; + + /** + * Cell Annotations (BIFF8) + * + * @var array + */ + private $cellNotes; + + /** + * The combined MSODRAWINGGROUP data + * + * @var string + */ + private $drawingGroupData; + + /** + * The combined MSODRAWING data (per sheet) + * + * @var string + */ + private $drawingData; + + /** + * Keep track of XF index + * + * @var int + */ + private $xfIndex; + + /** + * Mapping of XF index (that is a cell XF) to final index in cellXf collection + * + * @var array + */ + private $mapCellXfIndex; + + /** + * Mapping of XF index (that is a style XF) to final index in cellStyleXf collection + * + * @var array + */ + private $mapCellStyleXfIndex; + + /** + * The shared formulas in a sheet. One SHAREDFMLA record contributes with one value. + * + * @var array + */ + private $sharedFormulas; + + /** + * The shared formula parts in a sheet. One FORMULA record contributes with one value if it + * refers to a shared formula. + * + * @var array + */ + private $sharedFormulaParts; + + /** + * The type of encryption in use + * + * @var int + */ + private $encryption = 0; + + /** + * The position in the stream after which contents are encrypted + * + * @var int + */ + private $encryptionStartPos = false; + + /** + * The current RC4 decryption object + * + * @var PHPExcel_Reader_Excel5_RC4 + */ + private $rc4Key = null; + + /** + * The position in the stream that the RC4 decryption object was left at + * + * @var int + */ + private $rc4Pos = 0; + + /** + * The current MD5 context state + * + * @var string + */ + private $md5Ctxt = null; + + /** + * Create a new PHPExcel_Reader_Excel5 instance + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + try { + // Use ParseXL for the hard work. + $ole = new PHPExcel_Shared_OLERead(); + + // get excel data + $res = $ole->read($pFilename); + return true; + } catch (PHPExcel_Exception $e) { + return false; + } + } + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetNames = array(); + + // Read the OLE file + $this->loadOLE($pFilename); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->dataSize = strlen($this->data); + + $this->pos = 0; + $this->sheets = array(); + + // Parse Workbook Global Substream + while ($this->pos < $this->dataSize) { + $code = self::getInt2d($this->data, $this->pos); + + switch ($code) { + case self::XLS_TYPE_BOF: + $this->readBof(); + break; + case self::XLS_TYPE_SHEET: + $this->readSheet(); + break; + case self::XLS_TYPE_EOF: + $this->readDefault(); + break 2; + default: + $this->readDefault(); + break; + } + } + + foreach ($this->sheets as $sheet) { + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module + continue; + } + + $worksheetNames[] = $sheet['name']; + } + + return $worksheetNames; + } + + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + // Read the OLE file + $this->loadOLE($pFilename); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->dataSize = strlen($this->data); + + // initialize + $this->pos = 0; + $this->sheets = array(); + + // Parse Workbook Global Substream + while ($this->pos < $this->dataSize) { + $code = self::getInt2d($this->data, $this->pos); + + switch ($code) { + case self::XLS_TYPE_BOF: + $this->readBof(); + break; + case self::XLS_TYPE_SHEET: + $this->readSheet(); + break; + case self::XLS_TYPE_EOF: + $this->readDefault(); + break 2; + default: + $this->readDefault(); + break; + } + } + + // Parse the individual sheets + foreach ($this->sheets as $sheet) { + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet + // 0x02: Chart + // 0x06: Visual Basic module + continue; + } + + $tmpInfo = array(); + $tmpInfo['worksheetName'] = $sheet['name']; + $tmpInfo['lastColumnLetter'] = 'A'; + $tmpInfo['lastColumnIndex'] = 0; + $tmpInfo['totalRows'] = 0; + $tmpInfo['totalColumns'] = 0; + + $this->pos = $sheet['offset']; + + while ($this->pos <= $this->dataSize - 4) { + $code = self::getInt2d($this->data, $this->pos); + + switch ($code) { + case self::XLS_TYPE_RK: + case self::XLS_TYPE_LABELSST: + case self::XLS_TYPE_NUMBER: + case self::XLS_TYPE_FORMULA: + case self::XLS_TYPE_BOOLERR: + case self::XLS_TYPE_LABEL: + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + $rowIndex = self::getInt2d($recordData, 0) + 1; + $columnIndex = self::getInt2d($recordData, 2); + + $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex); + $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex); + break; + case self::XLS_TYPE_BOF: + $this->readBof(); + break; + case self::XLS_TYPE_EOF: + $this->readDefault(); + break 2; + default: + $this->readDefault(); + break; + } + } + + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; + + $worksheetInfo[] = $tmpInfo; + } + + return $worksheetInfo; + } + + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Read the OLE file + $this->loadOLE($pFilename); + + // Initialisations + $this->phpExcel = new PHPExcel; + $this->phpExcel->removeSheetByIndex(0); // remove 1st sheet + if (!$this->readDataOnly) { + $this->phpExcel->removeCellStyleXfByIndex(0); // remove the default style + $this->phpExcel->removeCellXfByIndex(0); // remove the default style + } + + // Read the summary information stream (containing meta data) + $this->readSummaryInformation(); + + // Read the Additional document summary information stream (containing application-specific meta data) + $this->readDocumentSummaryInformation(); + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->dataSize = strlen($this->data); + + // initialize + $this->pos = 0; + $this->codepage = 'CP1252'; + $this->formats = array(); + $this->objFonts = array(); + $this->palette = array(); + $this->sheets = array(); + $this->externalBooks = array(); + $this->ref = array(); + $this->definedname = array(); + $this->sst = array(); + $this->drawingGroupData = ''; + $this->xfIndex = ''; + $this->mapCellXfIndex = array(); + $this->mapCellStyleXfIndex = array(); + + // Parse Workbook Global Substream + while ($this->pos < $this->dataSize) { + $code = self::getInt2d($this->data, $this->pos); + + switch ($code) { + case self::XLS_TYPE_BOF: + $this->readBof(); + break; + case self::XLS_TYPE_FILEPASS: + $this->readFilepass(); + break; + case self::XLS_TYPE_CODEPAGE: + $this->readCodepage(); + break; + case self::XLS_TYPE_DATEMODE: + $this->readDateMode(); + break; + case self::XLS_TYPE_FONT: + $this->readFont(); + break; + case self::XLS_TYPE_FORMAT: + $this->readFormat(); + break; + case self::XLS_TYPE_XF: + $this->readXf(); + break; + case self::XLS_TYPE_XFEXT: + $this->readXfExt(); + break; + case self::XLS_TYPE_STYLE: + $this->readStyle(); + break; + case self::XLS_TYPE_PALETTE: + $this->readPalette(); + break; + case self::XLS_TYPE_SHEET: + $this->readSheet(); + break; + case self::XLS_TYPE_EXTERNALBOOK: + $this->readExternalBook(); + break; + case self::XLS_TYPE_EXTERNNAME: + $this->readExternName(); + break; + case self::XLS_TYPE_EXTERNSHEET: + $this->readExternSheet(); + break; + case self::XLS_TYPE_DEFINEDNAME: + $this->readDefinedName(); + break; + case self::XLS_TYPE_MSODRAWINGGROUP: + $this->readMsoDrawingGroup(); + break; + case self::XLS_TYPE_SST: + $this->readSst(); + break; + case self::XLS_TYPE_EOF: + $this->readDefault(); + break 2; + default: + $this->readDefault(); + break; + } + } + + // Resolve indexed colors for font, fill, and border colors + // Cannot be resolved already in XF record, because PALETTE record comes afterwards + if (!$this->readDataOnly) { + foreach ($this->objFonts as $objFont) { + if (isset($objFont->colorIndex)) { + $color = PHPExcel_Reader_Excel5_Color::map($objFont->colorIndex, $this->palette, $this->version); + $objFont->getColor()->setRGB($color['rgb']); + } + } + + foreach ($this->phpExcel->getCellXfCollection() as $objStyle) { + // fill start and end color + $fill = $objStyle->getFill(); + + if (isset($fill->startcolorIndex)) { + $startColor = PHPExcel_Reader_Excel5_Color::map($fill->startcolorIndex, $this->palette, $this->version); + $fill->getStartColor()->setRGB($startColor['rgb']); + } + if (isset($fill->endcolorIndex)) { + $endColor = PHPExcel_Reader_Excel5_Color::map($fill->endcolorIndex, $this->palette, $this->version); + $fill->getEndColor()->setRGB($endColor['rgb']); + } + + // border colors + $top = $objStyle->getBorders()->getTop(); + $right = $objStyle->getBorders()->getRight(); + $bottom = $objStyle->getBorders()->getBottom(); + $left = $objStyle->getBorders()->getLeft(); + $diagonal = $objStyle->getBorders()->getDiagonal(); + + if (isset($top->colorIndex)) { + $borderTopColor = PHPExcel_Reader_Excel5_Color::map($top->colorIndex, $this->palette, $this->version); + $top->getColor()->setRGB($borderTopColor['rgb']); + } + if (isset($right->colorIndex)) { + $borderRightColor = PHPExcel_Reader_Excel5_Color::map($right->colorIndex, $this->palette, $this->version); + $right->getColor()->setRGB($borderRightColor['rgb']); + } + if (isset($bottom->colorIndex)) { + $borderBottomColor = PHPExcel_Reader_Excel5_Color::map($bottom->colorIndex, $this->palette, $this->version); + $bottom->getColor()->setRGB($borderBottomColor['rgb']); + } + if (isset($left->colorIndex)) { + $borderLeftColor = PHPExcel_Reader_Excel5_Color::map($left->colorIndex, $this->palette, $this->version); + $left->getColor()->setRGB($borderLeftColor['rgb']); + } + if (isset($diagonal->colorIndex)) { + $borderDiagonalColor = PHPExcel_Reader_Excel5_Color::map($diagonal->colorIndex, $this->palette, $this->version); + $diagonal->getColor()->setRGB($borderDiagonalColor['rgb']); + } + } + } + + // treat MSODRAWINGGROUP records, workbook-level Escher + if (!$this->readDataOnly && $this->drawingGroupData) { + $escherWorkbook = new PHPExcel_Shared_Escher(); + $reader = new PHPExcel_Reader_Excel5_Escher($escherWorkbook); + $escherWorkbook = $reader->load($this->drawingGroupData); + + // debug Escher stream + //$debug = new Debug_Escher(new PHPExcel_Shared_Escher()); + //$debug->load($this->drawingGroupData); + } + + // Parse the individual sheets + foreach ($this->sheets as $sheet) { + if ($sheet['sheetType'] != 0x00) { + // 0x00: Worksheet, 0x02: Chart, 0x06: Visual Basic module + continue; + } + + // check if sheet should be skipped + if (isset($this->loadSheetsOnly) && !in_array($sheet['name'], $this->loadSheetsOnly)) { + continue; + } + + // add sheet to PHPExcel object + $this->phpSheet = $this->phpExcel->createSheet(); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula + // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet + // name in line with the formula, not the reverse + $this->phpSheet->setTitle($sheet['name'], false); + $this->phpSheet->setSheetState($sheet['sheetState']); + + $this->pos = $sheet['offset']; + + // Initialize isFitToPages. May change after reading SHEETPR record. + $this->isFitToPages = false; + + // Initialize drawingData + $this->drawingData = ''; + + // Initialize objs + $this->objs = array(); + + // Initialize shared formula parts + $this->sharedFormulaParts = array(); + + // Initialize shared formulas + $this->sharedFormulas = array(); + + // Initialize text objs + $this->textObjects = array(); + + // Initialize cell annotations + $this->cellNotes = array(); + $this->textObjRef = -1; + + while ($this->pos <= $this->dataSize - 4) { + $code = self::getInt2d($this->data, $this->pos); + + switch ($code) { + case self::XLS_TYPE_BOF: + $this->readBof(); + break; + case self::XLS_TYPE_PRINTGRIDLINES: + $this->readPrintGridlines(); + break; + case self::XLS_TYPE_DEFAULTROWHEIGHT: + $this->readDefaultRowHeight(); + break; + case self::XLS_TYPE_SHEETPR: + $this->readSheetPr(); + break; + case self::XLS_TYPE_HORIZONTALPAGEBREAKS: + $this->readHorizontalPageBreaks(); + break; + case self::XLS_TYPE_VERTICALPAGEBREAKS: + $this->readVerticalPageBreaks(); + break; + case self::XLS_TYPE_HEADER: + $this->readHeader(); + break; + case self::XLS_TYPE_FOOTER: + $this->readFooter(); + break; + case self::XLS_TYPE_HCENTER: + $this->readHcenter(); + break; + case self::XLS_TYPE_VCENTER: + $this->readVcenter(); + break; + case self::XLS_TYPE_LEFTMARGIN: + $this->readLeftMargin(); + break; + case self::XLS_TYPE_RIGHTMARGIN: + $this->readRightMargin(); + break; + case self::XLS_TYPE_TOPMARGIN: + $this->readTopMargin(); + break; + case self::XLS_TYPE_BOTTOMMARGIN: + $this->readBottomMargin(); + break; + case self::XLS_TYPE_PAGESETUP: + $this->readPageSetup(); + break; + case self::XLS_TYPE_PROTECT: + $this->readProtect(); + break; + case self::XLS_TYPE_SCENPROTECT: + $this->readScenProtect(); + break; + case self::XLS_TYPE_OBJECTPROTECT: + $this->readObjectProtect(); + break; + case self::XLS_TYPE_PASSWORD: + $this->readPassword(); + break; + case self::XLS_TYPE_DEFCOLWIDTH: + $this->readDefColWidth(); + break; + case self::XLS_TYPE_COLINFO: + $this->readColInfo(); + break; + case self::XLS_TYPE_DIMENSION: + $this->readDefault(); + break; + case self::XLS_TYPE_ROW: + $this->readRow(); + break; + case self::XLS_TYPE_DBCELL: + $this->readDefault(); + break; + case self::XLS_TYPE_RK: + $this->readRk(); + break; + case self::XLS_TYPE_LABELSST: + $this->readLabelSst(); + break; + case self::XLS_TYPE_MULRK: + $this->readMulRk(); + break; + case self::XLS_TYPE_NUMBER: + $this->readNumber(); + break; + case self::XLS_TYPE_FORMULA: + $this->readFormula(); + break; + case self::XLS_TYPE_SHAREDFMLA: + $this->readSharedFmla(); + break; + case self::XLS_TYPE_BOOLERR: + $this->readBoolErr(); + break; + case self::XLS_TYPE_MULBLANK: + $this->readMulBlank(); + break; + case self::XLS_TYPE_LABEL: + $this->readLabel(); + break; + case self::XLS_TYPE_BLANK: + $this->readBlank(); + break; + case self::XLS_TYPE_MSODRAWING: + $this->readMsoDrawing(); + break; + case self::XLS_TYPE_OBJ: + $this->readObj(); + break; + case self::XLS_TYPE_WINDOW2: + $this->readWindow2(); + break; + case self::XLS_TYPE_PAGELAYOUTVIEW: + $this->readPageLayoutView(); + break; + case self::XLS_TYPE_SCL: + $this->readScl(); + break; + case self::XLS_TYPE_PANE: + $this->readPane(); + break; + case self::XLS_TYPE_SELECTION: + $this->readSelection(); + break; + case self::XLS_TYPE_MERGEDCELLS: + $this->readMergedCells(); + break; + case self::XLS_TYPE_HYPERLINK: + $this->readHyperLink(); + break; + case self::XLS_TYPE_DATAVALIDATIONS: + $this->readDataValidations(); + break; + case self::XLS_TYPE_DATAVALIDATION: + $this->readDataValidation(); + break; + case self::XLS_TYPE_SHEETLAYOUT: + $this->readSheetLayout(); + break; + case self::XLS_TYPE_SHEETPROTECTION: + $this->readSheetProtection(); + break; + case self::XLS_TYPE_RANGEPROTECTION: + $this->readRangeProtection(); + break; + case self::XLS_TYPE_NOTE: + $this->readNote(); + break; + //case self::XLS_TYPE_IMDATA: $this->readImData(); break; + case self::XLS_TYPE_TXO: + $this->readTextObject(); + break; + case self::XLS_TYPE_CONTINUE: + $this->readContinue(); + break; + case self::XLS_TYPE_EOF: + $this->readDefault(); + break 2; + default: + $this->readDefault(); + break; + } + + } + + // treat MSODRAWING records, sheet-level Escher + if (!$this->readDataOnly && $this->drawingData) { + $escherWorksheet = new PHPExcel_Shared_Escher(); + $reader = new PHPExcel_Reader_Excel5_Escher($escherWorksheet); + $escherWorksheet = $reader->load($this->drawingData); + + // debug Escher stream + //$debug = new Debug_Escher(new PHPExcel_Shared_Escher()); + //$debug->load($this->drawingData); + + // get all spContainers in one long array, so they can be mapped to OBJ records + $allSpContainers = $escherWorksheet->getDgContainer()->getSpgrContainer()->getAllSpContainers(); + } + + // treat OBJ records + foreach ($this->objs as $n => $obj) { +// echo '<hr /><b>Object</b> reference is ', $n,'<br />'; +// var_dump($obj); +// echo '<br />'; + + // the first shape container never has a corresponding OBJ record, hence $n + 1 + if (isset($allSpContainers[$n + 1]) && is_object($allSpContainers[$n + 1])) { + $spContainer = $allSpContainers[$n + 1]; + + // we skip all spContainers that are a part of a group shape since we cannot yet handle those + if ($spContainer->getNestingLevel() > 1) { + continue; + } + + // calculate the width and height of the shape + list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($spContainer->getStartCoordinates()); + list($endColumn, $endRow) = PHPExcel_Cell::coordinateFromString($spContainer->getEndCoordinates()); + + $startOffsetX = $spContainer->getStartOffsetX(); + $startOffsetY = $spContainer->getStartOffsetY(); + $endOffsetX = $spContainer->getEndOffsetX(); + $endOffsetY = $spContainer->getEndOffsetY(); + + $width = PHPExcel_Shared_Excel5::getDistanceX($this->phpSheet, $startColumn, $startOffsetX, $endColumn, $endOffsetX); + $height = PHPExcel_Shared_Excel5::getDistanceY($this->phpSheet, $startRow, $startOffsetY, $endRow, $endOffsetY); + + // calculate offsetX and offsetY of the shape + $offsetX = $startOffsetX * PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, $startColumn) / 1024; + $offsetY = $startOffsetY * PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $startRow) / 256; + + switch ($obj['otObjType']) { + case 0x19: + // Note +// echo 'Cell Annotation Object<br />'; +// echo 'Object ID is ', $obj['idObjID'],'<br />'; + if (isset($this->cellNotes[$obj['idObjID']])) { + $cellNote = $this->cellNotes[$obj['idObjID']]; + + if (isset($this->textObjects[$obj['idObjID']])) { + $textObject = $this->textObjects[$obj['idObjID']]; + $this->cellNotes[$obj['idObjID']]['objTextData'] = $textObject; + } + } + break; + case 0x08: +// echo 'Picture Object<br />'; + // picture + // get index to BSE entry (1-based) + $BSEindex = $spContainer->getOPT(0x0104); + $BSECollection = $escherWorkbook->getDggContainer()->getBstoreContainer()->getBSECollection(); + $BSE = $BSECollection[$BSEindex - 1]; + $blipType = $BSE->getBlipType(); + + // need check because some blip types are not supported by Escher reader such as EMF + if ($blip = $BSE->getBlip()) { + $ih = imagecreatefromstring($blip->getData()); + $drawing = new PHPExcel_Worksheet_MemoryDrawing(); + $drawing->setImageResource($ih); + + // width, height, offsetX, offsetY + $drawing->setResizeProportional(false); + $drawing->setWidth($width); + $drawing->setHeight($height); + $drawing->setOffsetX($offsetX); + $drawing->setOffsetY($offsetY); + + switch ($blipType) { + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG: + $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG); + $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_JPEG); + break; + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG: + $drawing->setRenderingFunction(PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG); + $drawing->setMimeType(PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_PNG); + break; + } + + $drawing->setWorksheet($this->phpSheet); + $drawing->setCoordinates($spContainer->getStartCoordinates()); + } + break; + default: + // other object type + break; + } + } + } + + // treat SHAREDFMLA records + if ($this->version == self::XLS_BIFF8) { + foreach ($this->sharedFormulaParts as $cell => $baseCell) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($cell); + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { + $formula = $this->getFormulaFromStructure($this->sharedFormulas[$baseCell], $cell); + $this->phpSheet->getCell($cell)->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + } + } + } + + if (!empty($this->cellNotes)) { + foreach ($this->cellNotes as $note => $noteDetails) { + if (!isset($noteDetails['objTextData'])) { + if (isset($this->textObjects[$note])) { + $textObject = $this->textObjects[$note]; + $noteDetails['objTextData'] = $textObject; + } else { + $noteDetails['objTextData']['text'] = ''; + } + } +// echo '<b>Cell annotation ', $note,'</b><br />'; +// var_dump($noteDetails); +// echo '<br />'; + $cellAddress = str_replace('$', '', $noteDetails['cellRef']); + $this->phpSheet->getComment($cellAddress)->setAuthor($noteDetails['author'])->setText($this->parseRichText($noteDetails['objTextData']['text'])); + } + } + } + + // add the named ranges (defined names) + foreach ($this->definedname as $definedName) { + if ($definedName['isBuiltInName']) { + switch ($definedName['name']) { + case pack('C', 0x06): + // print area + // in general, formula looks like this: Foo!$C$7:$J$66,Bar!$A$1:$IV$2 + $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? + + $extractedRanges = array(); + foreach ($ranges as $range) { + // $range should look like one of these + // Foo!$C$7:$J$66 + // Bar!$A$1:$IV$2 + $explodes = explode('!', $range); // FIXME: what if sheetname contains exclamation mark? + $sheetName = trim($explodes[0], "'"); + if (count($explodes) == 2) { + if (strpos($explodes[1], ':') === false) { + $explodes[1] = $explodes[1] . ':' . $explodes[1]; + } + $extractedRanges[] = str_replace('$', '', $explodes[1]); // C7:J66 + } + } + if ($docSheet = $this->phpExcel->getSheetByName($sheetName)) { + $docSheet->getPageSetup()->setPrintArea(implode(',', $extractedRanges)); // C7:J66,A1:IV2 + } + break; + case pack('C', 0x07): + // print titles (repeating rows) + // Assuming BIFF8, there are 3 cases + // 1. repeating rows + // formula looks like this: Sheet!$A$1:$IV$2 + // rows 1-2 repeat + // 2. repeating columns + // formula looks like this: Sheet!$A$1:$B$65536 + // columns A-B repeat + // 3. both repeating rows and repeating columns + // formula looks like this: Sheet!$A$1:$B$65536,Sheet!$A$1:$IV$2 + $ranges = explode(',', $definedName['formula']); // FIXME: what if sheetname contains comma? + foreach ($ranges as $range) { + // $range should look like this one of these + // Sheet!$A$1:$B$65536 + // Sheet!$A$1:$IV$2 + $explodes = explode('!', $range); + if (count($explodes) == 2) { + if ($docSheet = $this->phpExcel->getSheetByName($explodes[0])) { + $extractedRange = $explodes[1]; + $extractedRange = str_replace('$', '', $extractedRange); + + $coordinateStrings = explode(':', $extractedRange); + if (count($coordinateStrings) == 2) { + list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[0]); + list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($coordinateStrings[1]); + + if ($firstColumn == 'A' and $lastColumn == 'IV') { + // then we have repeating rows + $docSheet->getPageSetup()->setRowsToRepeatAtTop(array($firstRow, $lastRow)); + } elseif ($firstRow == 1 and $lastRow == 65536) { + // then we have repeating columns + $docSheet->getPageSetup()->setColumnsToRepeatAtLeft(array($firstColumn, $lastColumn)); + } + } + } + } + } + break; + } + } else { + // Extract range + $explodes = explode('!', $definedName['formula']); + + if (count($explodes) == 2) { + if (($docSheet = $this->phpExcel->getSheetByName($explodes[0])) || + ($docSheet = $this->phpExcel->getSheetByName(trim($explodes[0], "'")))) { + $extractedRange = $explodes[1]; + $extractedRange = str_replace('$', '', $extractedRange); + + $localOnly = ($definedName['scope'] == 0) ? false : true; + + $scope = ($definedName['scope'] == 0) ? null : $this->phpExcel->getSheetByName($this->sheets[$definedName['scope'] - 1]['name']); + + $this->phpExcel->addNamedRange(new PHPExcel_NamedRange((string)$definedName['name'], $docSheet, $extractedRange, $localOnly, $scope)); + } + } else { + // Named Value + // TODO Provide support for named values + } + } + } + $this->data = null; + + return $this->phpExcel; + } + + /** + * Read record data from stream, decrypting as required + * + * @param string $data Data stream to read from + * @param int $pos Position to start reading from + * @param int $length Record data length + * + * @return string Record data + */ + private function readRecordData($data, $pos, $len) + { + $data = substr($data, $pos, $len); + + // File not encrypted, or record before encryption start point + if ($this->encryption == self::MS_BIFF_CRYPTO_NONE || $pos < $this->encryptionStartPos) { + return $data; + } + + $recordData = ''; + if ($this->encryption == self::MS_BIFF_CRYPTO_RC4) { + $oldBlock = floor($this->rc4Pos / self::REKEY_BLOCK); + $block = floor($pos / self::REKEY_BLOCK); + $endBlock = floor(($pos + $len) / self::REKEY_BLOCK); + + // Spin an RC4 decryptor to the right spot. If we have a decryptor sitting + // at a point earlier in the current block, re-use it as we can save some time. + if ($block != $oldBlock || $pos < $this->rc4Pos || !$this->rc4Key) { + $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); + $step = $pos % self::REKEY_BLOCK; + } else { + $step = $pos - $this->rc4Pos; + } + $this->rc4Key->RC4(str_repeat("\0", $step)); + + // Decrypt record data (re-keying at the end of every block) + while ($block != $endBlock) { + $step = self::REKEY_BLOCK - ($pos % self::REKEY_BLOCK); + $recordData .= $this->rc4Key->RC4(substr($data, 0, $step)); + $data = substr($data, $step); + $pos += $step; + $len -= $step; + $block++; + $this->rc4Key = $this->makeKey($block, $this->md5Ctxt); + } + $recordData .= $this->rc4Key->RC4(substr($data, 0, $len)); + + // Keep track of the position of this decryptor. + // We'll try and re-use it later if we can to speed things up + $this->rc4Pos = $pos + $len; + } elseif ($this->encryption == self::MS_BIFF_CRYPTO_XOR) { + throw new PHPExcel_Reader_Exception('XOr encryption not supported'); + } + return $recordData; + } + + /** + * Use OLE reader to extract the relevant data streams from the OLE file + * + * @param string $pFilename + */ + private function loadOLE($pFilename) + { + // OLE reader + $ole = new PHPExcel_Shared_OLERead(); + // get excel data, + $res = $ole->read($pFilename); + // Get workbook data: workbook stream + sheet streams + $this->data = $ole->getStream($ole->wrkbook); + // Get summary information data + $this->summaryInformation = $ole->getStream($ole->summaryInformation); + // Get additional document summary information data + $this->documentSummaryInformation = $ole->getStream($ole->documentSummaryInformation); + // Get user-defined property data +// $this->userDefinedProperties = $ole->getUserDefinedProperties(); + } + + + /** + * Read summary information + */ + private function readSummaryInformation() + { + if (!isset($this->summaryInformation)) { + return; + } + + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + // offset: 2; size: 2; + // offset: 4; size: 2; OS version + // offset: 6; size: 2; OS indicator + // offset: 8; size: 16 + // offset: 24; size: 4; section count + $secCount = self::getInt4d($this->summaryInformation, 24); + + // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 + // offset: 44; size: 4 + $secOffset = self::getInt4d($this->summaryInformation, 44); + + // section header + // offset: $secOffset; size: 4; section length + $secLength = self::getInt4d($this->summaryInformation, $secOffset); + + // offset: $secOffset+4; size: 4; property count + $countProperties = self::getInt4d($this->summaryInformation, $secOffset+4); + + // initialize code page (used to resolve string values) + $codePage = 'CP1252'; + + // offset: ($secOffset+8); size: var + // loop through property decarations and properties + for ($i = 0; $i < $countProperties; ++$i) { + // offset: ($secOffset+8) + (8 * $i); size: 4; property ID + $id = self::getInt4d($this->summaryInformation, ($secOffset+8) + (8 * $i)); + + // Use value of property id as appropriate + // offset: ($secOffset+12) + (8 * $i); size: 4; offset from beginning of section (48) + $offset = self::getInt4d($this->summaryInformation, ($secOffset+12) + (8 * $i)); + + $type = self::getInt4d($this->summaryInformation, $secOffset + $offset); + + // initialize property value + $value = null; + + // extract property value based on property type + switch ($type) { + case 0x02: // 2 byte signed integer + $value = self::getInt2d($this->summaryInformation, $secOffset + 4 + $offset); + break; + case 0x03: // 4 byte signed integer + $value = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); + break; + case 0x13: // 4 byte unsigned integer + // not needed yet, fix later if necessary + break; + case 0x1E: // null-terminated string prepended by dword string length + $byteLength = self::getInt4d($this->summaryInformation, $secOffset + 4 + $offset); + $value = substr($this->summaryInformation, $secOffset + 8 + $offset, $byteLength); + $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage); + $value = rtrim($value); + break; + case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + // PHP-time + $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->summaryInformation, $secOffset + 4 + $offset, 8)); + break; + case 0x47: // Clipboard format + // not needed yet, fix later if necessary + break; + } + + switch ($id) { + case 0x01: // Code Page + $codePage = PHPExcel_Shared_CodePage::NumberToName($value); + break; + case 0x02: // Title + $this->phpExcel->getProperties()->setTitle($value); + break; + case 0x03: // Subject + $this->phpExcel->getProperties()->setSubject($value); + break; + case 0x04: // Author (Creator) + $this->phpExcel->getProperties()->setCreator($value); + break; + case 0x05: // Keywords + $this->phpExcel->getProperties()->setKeywords($value); + break; + case 0x06: // Comments (Description) + $this->phpExcel->getProperties()->setDescription($value); + break; + case 0x07: // Template + // Not supported by PHPExcel + break; + case 0x08: // Last Saved By (LastModifiedBy) + $this->phpExcel->getProperties()->setLastModifiedBy($value); + break; + case 0x09: // Revision + // Not supported by PHPExcel + break; + case 0x0A: // Total Editing Time + // Not supported by PHPExcel + break; + case 0x0B: // Last Printed + // Not supported by PHPExcel + break; + case 0x0C: // Created Date/Time + $this->phpExcel->getProperties()->setCreated($value); + break; + case 0x0D: // Modified Date/Time + $this->phpExcel->getProperties()->setModified($value); + break; + case 0x0E: // Number of Pages + // Not supported by PHPExcel + break; + case 0x0F: // Number of Words + // Not supported by PHPExcel + break; + case 0x10: // Number of Characters + // Not supported by PHPExcel + break; + case 0x11: // Thumbnail + // Not supported by PHPExcel + break; + case 0x12: // Name of creating application + // Not supported by PHPExcel + break; + case 0x13: // Security + // Not supported by PHPExcel + break; + } + } + } + + + /** + * Read additional document summary information + */ + private function readDocumentSummaryInformation() + { + if (!isset($this->documentSummaryInformation)) { + return; + } + + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + // offset: 2; size: 2; + // offset: 4; size: 2; OS version + // offset: 6; size: 2; OS indicator + // offset: 8; size: 16 + // offset: 24; size: 4; section count + $secCount = self::getInt4d($this->documentSummaryInformation, 24); +// echo '$secCount = ', $secCount,'<br />'; + + // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae + // offset: 44; size: 4; first section offset + $secOffset = self::getInt4d($this->documentSummaryInformation, 44); +// echo '$secOffset = ', $secOffset,'<br />'; + + // section header + // offset: $secOffset; size: 4; section length + $secLength = self::getInt4d($this->documentSummaryInformation, $secOffset); +// echo '$secLength = ', $secLength,'<br />'; + + // offset: $secOffset+4; size: 4; property count + $countProperties = self::getInt4d($this->documentSummaryInformation, $secOffset+4); +// echo '$countProperties = ', $countProperties,'<br />'; + + // initialize code page (used to resolve string values) + $codePage = 'CP1252'; + + // offset: ($secOffset+8); size: var + // loop through property decarations and properties + for ($i = 0; $i < $countProperties; ++$i) { +// echo 'Property ', $i,'<br />'; + // offset: ($secOffset+8) + (8 * $i); size: 4; property ID + $id = self::getInt4d($this->documentSummaryInformation, ($secOffset+8) + (8 * $i)); +// echo 'ID is ', $id,'<br />'; + + // Use value of property id as appropriate + // offset: 60 + 8 * $i; size: 4; offset from beginning of section (48) + $offset = self::getInt4d($this->documentSummaryInformation, ($secOffset+12) + (8 * $i)); + + $type = self::getInt4d($this->documentSummaryInformation, $secOffset + $offset); +// echo 'Type is ', $type,', '; + + // initialize property value + $value = null; + + // extract property value based on property type + switch ($type) { + case 0x02: // 2 byte signed integer + $value = self::getInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); + break; + case 0x03: // 4 byte signed integer + $value = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); + break; + case 0x0B: // Boolean + $value = self::getInt2d($this->documentSummaryInformation, $secOffset + 4 + $offset); + $value = ($value == 0 ? false : true); + break; + case 0x13: // 4 byte unsigned integer + // not needed yet, fix later if necessary + break; + case 0x1E: // null-terminated string prepended by dword string length + $byteLength = self::getInt4d($this->documentSummaryInformation, $secOffset + 4 + $offset); + $value = substr($this->documentSummaryInformation, $secOffset + 8 + $offset, $byteLength); + $value = PHPExcel_Shared_String::ConvertEncoding($value, 'UTF-8', $codePage); + $value = rtrim($value); + break; + case 0x40: // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + // PHP-Time + $value = PHPExcel_Shared_OLE::OLE2LocalDate(substr($this->documentSummaryInformation, $secOffset + 4 + $offset, 8)); + break; + case 0x47: // Clipboard format + // not needed yet, fix later if necessary + break; + } + + switch ($id) { + case 0x01: // Code Page + $codePage = PHPExcel_Shared_CodePage::NumberToName($value); + break; + case 0x02: // Category + $this->phpExcel->getProperties()->setCategory($value); + break; + case 0x03: // Presentation Target + // Not supported by PHPExcel + break; + case 0x04: // Bytes + // Not supported by PHPExcel + break; + case 0x05: // Lines + // Not supported by PHPExcel + break; + case 0x06: // Paragraphs + // Not supported by PHPExcel + break; + case 0x07: // Slides + // Not supported by PHPExcel + break; + case 0x08: // Notes + // Not supported by PHPExcel + break; + case 0x09: // Hidden Slides + // Not supported by PHPExcel + break; + case 0x0A: // MM Clips + // Not supported by PHPExcel + break; + case 0x0B: // Scale Crop + // Not supported by PHPExcel + break; + case 0x0C: // Heading Pairs + // Not supported by PHPExcel + break; + case 0x0D: // Titles of Parts + // Not supported by PHPExcel + break; + case 0x0E: // Manager + $this->phpExcel->getProperties()->setManager($value); + break; + case 0x0F: // Company + $this->phpExcel->getProperties()->setCompany($value); + break; + case 0x10: // Links up-to-date + // Not supported by PHPExcel + break; + } + } + } + + + /** + * Reads a general type of BIFF record. Does nothing except for moving stream pointer forward to next record. + */ + private function readDefault() + { + $length = self::getInt2d($this->data, $this->pos + 2); +// $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + } + + + /** + * The NOTE record specifies a comment associated with a particular cell. In Excel 95 (BIFF7) and earlier versions, + * this record stores a note (cell note). This feature was significantly enhanced in Excel 97. + */ + private function readNote() + { +// echo '<b>Read Cell Annotation</b><br />'; + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + $cellAddress = $this->readBIFF8CellAddress(substr($recordData, 0, 4)); + if ($this->version == self::XLS_BIFF8) { + $noteObjID = self::getInt2d($recordData, 6); + $noteAuthor = self::readUnicodeStringLong(substr($recordData, 8)); + $noteAuthor = $noteAuthor['value']; +// echo 'Note Address=', $cellAddress,'<br />'; +// echo 'Note Object ID=', $noteObjID,'<br />'; +// echo 'Note Author=', $noteAuthor,'<hr />'; +// + $this->cellNotes[$noteObjID] = array( + 'cellRef' => $cellAddress, + 'objectID' => $noteObjID, + 'author' => $noteAuthor + ); + } else { + $extension = false; + if ($cellAddress == '$B$65536') { + // If the address row is -1 and the column is 0, (which translates as $B$65536) then this is a continuation + // note from the previous cell annotation. We're not yet handling this, so annotations longer than the + // max 2048 bytes will probably throw a wobbly. + $row = self::getInt2d($recordData, 0); + $extension = true; + $cellAddress = array_pop(array_keys($this->phpSheet->getComments())); + } +// echo 'Note Address=', $cellAddress,'<br />'; + + $cellAddress = str_replace('$', '', $cellAddress); + $noteLength = self::getInt2d($recordData, 4); + $noteText = trim(substr($recordData, 6)); +// echo 'Note Length=', $noteLength,'<br />'; +// echo 'Note Text=', $noteText,'<br />'; + + if ($extension) { + // Concatenate this extension with the currently set comment for the cell + $comment = $this->phpSheet->getComment($cellAddress); + $commentText = $comment->getText()->getPlainText(); + $comment->setText($this->parseRichText($commentText.$noteText)); + } else { + // Set comment for the cell + $this->phpSheet->getComment($cellAddress)->setText($this->parseRichText($noteText)); +// ->setAuthor($author) + } + } + + } + + + /** + * The TEXT Object record contains the text associated with a cell annotation. + */ + private function readTextObject() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // recordData consists of an array of subrecords looking like this: + // grbit: 2 bytes; Option Flags + // rot: 2 bytes; rotation + // cchText: 2 bytes; length of the text (in the first continue record) + // cbRuns: 2 bytes; length of the formatting (in the second continue record) + // followed by the continuation records containing the actual text and formatting + $grbitOpts = self::getInt2d($recordData, 0); + $rot = self::getInt2d($recordData, 2); + $cchText = self::getInt2d($recordData, 10); + $cbRuns = self::getInt2d($recordData, 12); + $text = $this->getSplicedRecordData(); + + $this->textObjects[$this->textObjRef] = array( + 'text' => substr($text["recordData"], $text["spliceOffsets"][0]+1, $cchText), + 'format' => substr($text["recordData"], $text["spliceOffsets"][1], $cbRuns), + 'alignment' => $grbitOpts, + 'rotation' => $rot + ); + +// echo '<b>_readTextObject()</b><br />'; +// var_dump($this->textObjects[$this->textObjRef]); +// echo '<br />'; + } + + + /** + * Read BOF + */ + private function readBof() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = substr($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 2; size: 2; type of the following data + $substreamType = self::getInt2d($recordData, 2); + + switch ($substreamType) { + case self::XLS_WorkbookGlobals: + $version = self::getInt2d($recordData, 0); + if (($version != self::XLS_BIFF8) && ($version != self::XLS_BIFF7)) { + throw new PHPExcel_Reader_Exception('Cannot read this Excel file. Version is too old.'); + } + $this->version = $version; + break; + case self::XLS_Worksheet: + // do not use this version information for anything + // it is unreliable (OpenOffice doc, 5.8), use only version information from the global stream + break; + default: + // substream, e.g. chart + // just skip the entire substream + do { + $code = self::getInt2d($this->data, $this->pos); + $this->readDefault(); + } while ($code != self::XLS_TYPE_EOF && $this->pos < $this->dataSize); + break; + } + } + + + /** + * FILEPASS + * + * This record is part of the File Protection Block. It + * contains information about the read/write password of the + * file. All record contents following this record will be + * encrypted. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + * + * The decryption functions and objects used from here on in + * are based on the source of Spreadsheet-ParseExcel: + * http://search.cpan.org/~jmcnamara/Spreadsheet-ParseExcel/ + */ + private function readFilepass() + { + $length = self::getInt2d($this->data, $this->pos + 2); + + if ($length != 54) { + throw new PHPExcel_Reader_Exception('Unexpected file pass record length'); + } + + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->verifyPassword('VelvetSweatshop', substr($recordData, 6, 16), substr($recordData, 22, 16), substr($recordData, 38, 16), $this->md5Ctxt)) { + throw new PHPExcel_Reader_Exception('Decryption password incorrect'); + } + + $this->encryption = self::MS_BIFF_CRYPTO_RC4; + + // Decryption required from the record after next onwards + $this->encryptionStartPos = $this->pos + self::getInt2d($this->data, $this->pos + 2); + } + + /** + * Make an RC4 decryptor for the given block + * + * @var int $block Block for which to create decrypto + * @var string $valContext MD5 context state + * + * @return PHPExcel_Reader_Excel5_RC4 + */ + private function makeKey($block, $valContext) + { + $pwarray = str_repeat("\0", 64); + + for ($i = 0; $i < 5; $i++) { + $pwarray[$i] = $valContext[$i]; + } + + $pwarray[5] = chr($block & 0xff); + $pwarray[6] = chr(($block >> 8) & 0xff); + $pwarray[7] = chr(($block >> 16) & 0xff); + $pwarray[8] = chr(($block >> 24) & 0xff); + + $pwarray[9] = "\x80"; + $pwarray[56] = "\x48"; + + $md5 = new PHPExcel_Reader_Excel5_MD5(); + $md5->add($pwarray); + + $s = $md5->getContext(); + return new PHPExcel_Reader_Excel5_RC4($s); + } + + /** + * Verify RC4 file password + * + * @var string $password Password to check + * @var string $docid Document id + * @var string $salt_data Salt data + * @var string $hashedsalt_data Hashed salt data + * @var string &$valContext Set to the MD5 context of the value + * + * @return bool Success + */ + private function verifyPassword($password, $docid, $salt_data, $hashedsalt_data, &$valContext) + { + $pwarray = str_repeat("\0", 64); + + for ($i = 0; $i < strlen($password); $i++) { + $o = ord(substr($password, $i, 1)); + $pwarray[2 * $i] = chr($o & 0xff); + $pwarray[2 * $i + 1] = chr(($o >> 8) & 0xff); + } + $pwarray[2 * $i] = chr(0x80); + $pwarray[56] = chr(($i << 4) & 0xff); + + $md5 = new PHPExcel_Reader_Excel5_MD5(); + $md5->add($pwarray); + + $mdContext1 = $md5->getContext(); + + $offset = 0; + $keyoffset = 0; + $tocopy = 5; + + $md5->reset(); + + while ($offset != 16) { + if ((64 - $offset) < 5) { + $tocopy = 64 - $offset; + } + for ($i = 0; $i <= $tocopy; $i++) { + $pwarray[$offset + $i] = $mdContext1[$keyoffset + $i]; + } + $offset += $tocopy; + + if ($offset == 64) { + $md5->add($pwarray); + $keyoffset = $tocopy; + $tocopy = 5 - $tocopy; + $offset = 0; + continue; + } + + $keyoffset = 0; + $tocopy = 5; + for ($i = 0; $i < 16; $i++) { + $pwarray[$offset + $i] = $docid[$i]; + } + $offset += 16; + } + + $pwarray[16] = "\x80"; + for ($i = 0; $i < 47; $i++) { + $pwarray[17 + $i] = "\0"; + } + $pwarray[56] = "\x80"; + $pwarray[57] = "\x0a"; + + $md5->add($pwarray); + $valContext = $md5->getContext(); + + $key = $this->makeKey(0, $valContext); + + $salt = $key->RC4($salt_data); + $hashedsalt = $key->RC4($hashedsalt_data); + + $salt .= "\x80" . str_repeat("\0", 47); + $salt[56] = "\x80"; + + $md5->reset(); + $md5->add($salt); + $mdContext2 = $md5->getContext(); + + return $mdContext2 == $hashedsalt; + } + + /** + * CODEPAGE + * + * This record stores the text encoding used to write byte + * strings, stored as MS Windows code page identifier. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readCodepage() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; code page identifier + $codepage = self::getInt2d($recordData, 0); + + $this->codepage = PHPExcel_Shared_CodePage::NumberToName($codepage); + } + + + /** + * DATEMODE + * + * This record specifies the base date for displaying date + * values. All dates are stored as count of days past this + * base date. In BIFF2-BIFF4 this record is part of the + * Calculation Settings Block. In BIFF5-BIFF8 it is + * stored in the Workbook Globals Substream. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readDateMode() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; 0 = base 1900, 1 = base 1904 + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900); + if (ord($recordData{0}) == 1) { + PHPExcel_Shared_Date::setExcelCalendar(PHPExcel_Shared_Date::CALENDAR_MAC_1904); + } + } + + + /** + * Read a FONT record + */ + private function readFont() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + $objFont = new PHPExcel_Style_Font(); + + // offset: 0; size: 2; height of the font (in twips = 1/20 of a point) + $size = self::getInt2d($recordData, 0); + $objFont->setSize($size / 20); + + // offset: 2; size: 2; option flags + // bit: 0; mask 0x0001; bold (redundant in BIFF5-BIFF8) + // bit: 1; mask 0x0002; italic + $isItalic = (0x0002 & self::getInt2d($recordData, 2)) >> 1; + if ($isItalic) { + $objFont->setItalic(true); + } + + // bit: 2; mask 0x0004; underlined (redundant in BIFF5-BIFF8) + // bit: 3; mask 0x0008; strike + $isStrike = (0x0008 & self::getInt2d($recordData, 2)) >> 3; + if ($isStrike) { + $objFont->setStrikethrough(true); + } + + // offset: 4; size: 2; colour index + $colorIndex = self::getInt2d($recordData, 4); + $objFont->colorIndex = $colorIndex; + + // offset: 6; size: 2; font weight + $weight = self::getInt2d($recordData, 6); + switch ($weight) { + case 0x02BC: + $objFont->setBold(true); + break; + } + + // offset: 8; size: 2; escapement type + $escapement = self::getInt2d($recordData, 8); + switch ($escapement) { + case 0x0001: + $objFont->setSuperScript(true); + break; + case 0x0002: + $objFont->setSubScript(true); + break; + } + + // offset: 10; size: 1; underline type + $underlineType = ord($recordData{10}); + switch ($underlineType) { + case 0x00: + break; // no underline + case 0x01: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLE); + break; + case 0x02: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLE); + break; + case 0x21: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING); + break; + case 0x22: + $objFont->setUnderline(PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING); + break; + } + + // offset: 11; size: 1; font family + // offset: 12; size: 1; character set + // offset: 13; size: 1; not used + // offset: 14; size: var; font name + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringShort(substr($recordData, 14)); + } else { + $string = $this->readByteStringShort(substr($recordData, 14)); + } + $objFont->setName($string['value']); + + $this->objFonts[] = $objFont; + } + } + + + /** + * FORMAT + * + * This record contains information about a number format. + * All FORMAT records occur together in a sequential list. + * + * In BIFF2-BIFF4 other records referencing a FORMAT record + * contain a zero-based index into this list. From BIFF5 on + * the FORMAT record contains the index itself that will be + * used by other records. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readFormat() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + $indexCode = self::getInt2d($recordData, 0); + + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringLong(substr($recordData, 2)); + } else { + // BIFF7 + $string = $this->readByteStringShort(substr($recordData, 2)); + } + + $formatString = $string['value']; + $this->formats[$indexCode] = $formatString; + } + } + + + /** + * XF - Extended Format + * + * This record contains formatting information for cells, rows, columns or styles. + * According to http://support.microsoft.com/kb/147732 there are always at least 15 cell style XF + * and 1 cell XF. + * Inspection of Excel files generated by MS Office Excel shows that XF records 0-14 are cell style XF + * and XF record 15 is a cell XF + * We only read the first cell style XF and skip the remaining cell style XF records + * We read all cell XF records. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readXf() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + $objStyle = new PHPExcel_Style(); + + if (!$this->readDataOnly) { + // offset: 0; size: 2; Index to FONT record + if (self::getInt2d($recordData, 0) < 4) { + $fontIndex = self::getInt2d($recordData, 0); + } else { + // this has to do with that index 4 is omitted in all BIFF versions for some strange reason + // check the OpenOffice documentation of the FONT record + $fontIndex = self::getInt2d($recordData, 0) - 1; + } + $objStyle->setFont($this->objFonts[$fontIndex]); + + // offset: 2; size: 2; Index to FORMAT record + $numberFormatIndex = self::getInt2d($recordData, 2); + if (isset($this->formats[$numberFormatIndex])) { + // then we have user-defined format code + $numberformat = array('code' => $this->formats[$numberFormatIndex]); + } elseif (($code = PHPExcel_Style_NumberFormat::builtInFormatCode($numberFormatIndex)) !== '') { + // then we have built-in format code + $numberformat = array('code' => $code); + } else { + // we set the general format code + $numberformat = array('code' => 'General'); + } + $objStyle->getNumberFormat()->setFormatCode($numberformat['code']); + + // offset: 4; size: 2; XF type, cell protection, and parent style XF + // bit 2-0; mask 0x0007; XF_TYPE_PROT + $xfTypeProt = self::getInt2d($recordData, 4); + // bit 0; mask 0x01; 1 = cell is locked + $isLocked = (0x01 & $xfTypeProt) >> 0; + $objStyle->getProtection()->setLocked($isLocked ? PHPExcel_Style_Protection::PROTECTION_INHERIT : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + + // bit 1; mask 0x02; 1 = Formula is hidden + $isHidden = (0x02 & $xfTypeProt) >> 1; + $objStyle->getProtection()->setHidden($isHidden ? PHPExcel_Style_Protection::PROTECTION_PROTECTED : PHPExcel_Style_Protection::PROTECTION_UNPROTECTED); + + // bit 2; mask 0x04; 0 = Cell XF, 1 = Cell Style XF + $isCellStyleXf = (0x04 & $xfTypeProt) >> 2; + + // offset: 6; size: 1; Alignment and text break + // bit 2-0, mask 0x07; horizontal alignment + $horAlign = (0x07 & ord($recordData{6})) >> 0; + switch ($horAlign) { + case 0: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_GENERAL); + break; + case 1: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT); + break; + case 2: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER); + break; + case 3: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + break; + case 4: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_FILL); + break; + case 5: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY); + break; + case 6: + $objStyle->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS); + break; + } + // bit 3, mask 0x08; wrap text + $wrapText = (0x08 & ord($recordData{6})) >> 3; + switch ($wrapText) { + case 0: + $objStyle->getAlignment()->setWrapText(false); + break; + case 1: + $objStyle->getAlignment()->setWrapText(true); + break; + } + // bit 6-4, mask 0x70; vertical alignment + $vertAlign = (0x70 & ord($recordData{6})) >> 4; + switch ($vertAlign) { + case 0: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_TOP); + break; + case 1: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER); + break; + case 2: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_BOTTOM); + break; + case 3: + $objStyle->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_JUSTIFY); + break; + } + + if ($this->version == self::XLS_BIFF8) { + // offset: 7; size: 1; XF_ROTATION: Text rotation angle + $angle = ord($recordData{7}); + $rotation = 0; + if ($angle <= 90) { + $rotation = $angle; + } elseif ($angle <= 180) { + $rotation = 90 - $angle; + } elseif ($angle == 255) { + $rotation = -165; + } + $objStyle->getAlignment()->setTextRotation($rotation); + + // offset: 8; size: 1; Indentation, shrink to cell size, and text direction + // bit: 3-0; mask: 0x0F; indent level + $indent = (0x0F & ord($recordData{8})) >> 0; + $objStyle->getAlignment()->setIndent($indent); + + // bit: 4; mask: 0x10; 1 = shrink content to fit into cell + $shrinkToFit = (0x10 & ord($recordData{8})) >> 4; + switch ($shrinkToFit) { + case 0: + $objStyle->getAlignment()->setShrinkToFit(false); + break; + case 1: + $objStyle->getAlignment()->setShrinkToFit(true); + break; + } + + // offset: 9; size: 1; Flags used for attribute groups + + // offset: 10; size: 4; Cell border lines and background area + // bit: 3-0; mask: 0x0000000F; left style + if ($bordersLeftStyle = PHPExcel_Reader_Excel5_Style_Border::lookup((0x0000000F & self::getInt4d($recordData, 10)) >> 0)) { + $objStyle->getBorders()->getLeft()->setBorderStyle($bordersLeftStyle); + } + // bit: 7-4; mask: 0x000000F0; right style + if ($bordersRightStyle = PHPExcel_Reader_Excel5_Style_Border::lookup((0x000000F0 & self::getInt4d($recordData, 10)) >> 4)) { + $objStyle->getBorders()->getRight()->setBorderStyle($bordersRightStyle); + } + // bit: 11-8; mask: 0x00000F00; top style + if ($bordersTopStyle = PHPExcel_Reader_Excel5_Style_Border::lookup((0x00000F00 & self::getInt4d($recordData, 10)) >> 8)) { + $objStyle->getBorders()->getTop()->setBorderStyle($bordersTopStyle); + } + // bit: 15-12; mask: 0x0000F000; bottom style + if ($bordersBottomStyle = PHPExcel_Reader_Excel5_Style_Border::lookup((0x0000F000 & self::getInt4d($recordData, 10)) >> 12)) { + $objStyle->getBorders()->getBottom()->setBorderStyle($bordersBottomStyle); + } + // bit: 22-16; mask: 0x007F0000; left color + $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & self::getInt4d($recordData, 10)) >> 16; + + // bit: 29-23; mask: 0x3F800000; right color + $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & self::getInt4d($recordData, 10)) >> 23; + + // bit: 30; mask: 0x40000000; 1 = diagonal line from top left to right bottom + $diagonalDown = (0x40000000 & self::getInt4d($recordData, 10)) >> 30 ? true : false; + + // bit: 31; mask: 0x80000000; 1 = diagonal line from bottom left to top right + $diagonalUp = (0x80000000 & self::getInt4d($recordData, 10)) >> 31 ? true : false; + + if ($diagonalUp == false && $diagonalDown == false) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_NONE); + } elseif ($diagonalUp == true && $diagonalDown == false) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_UP); + } elseif ($diagonalUp == false && $diagonalDown == true) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_DOWN); + } elseif ($diagonalUp == true && $diagonalDown == true) { + $objStyle->getBorders()->setDiagonalDirection(PHPExcel_Style_Borders::DIAGONAL_BOTH); + } + + // offset: 14; size: 4; + // bit: 6-0; mask: 0x0000007F; top color + $objStyle->getBorders()->getTop()->colorIndex = (0x0000007F & self::getInt4d($recordData, 14)) >> 0; + + // bit: 13-7; mask: 0x00003F80; bottom color + $objStyle->getBorders()->getBottom()->colorIndex = (0x00003F80 & self::getInt4d($recordData, 14)) >> 7; + + // bit: 20-14; mask: 0x001FC000; diagonal color + $objStyle->getBorders()->getDiagonal()->colorIndex = (0x001FC000 & self::getInt4d($recordData, 14)) >> 14; + + // bit: 24-21; mask: 0x01E00000; diagonal style + if ($bordersDiagonalStyle = PHPExcel_Reader_Excel5_Style_Border::lookup((0x01E00000 & self::getInt4d($recordData, 14)) >> 21)) { + $objStyle->getBorders()->getDiagonal()->setBorderStyle($bordersDiagonalStyle); + } + + // bit: 31-26; mask: 0xFC000000 fill pattern + if ($fillType = PHPExcel_Reader_Excel5_Style_FillPattern::lookup((0xFC000000 & self::getInt4d($recordData, 14)) >> 26)) { + $objStyle->getFill()->setFillType($fillType); + } + // offset: 18; size: 2; pattern and background colour + // bit: 6-0; mask: 0x007F; color index for pattern color + $objStyle->getFill()->startcolorIndex = (0x007F & self::getInt2d($recordData, 18)) >> 0; + + // bit: 13-7; mask: 0x3F80; color index for pattern background + $objStyle->getFill()->endcolorIndex = (0x3F80 & self::getInt2d($recordData, 18)) >> 7; + } else { + // BIFF5 + + // offset: 7; size: 1; Text orientation and flags + $orientationAndFlags = ord($recordData{7}); + + // bit: 1-0; mask: 0x03; XF_ORIENTATION: Text orientation + $xfOrientation = (0x03 & $orientationAndFlags) >> 0; + switch ($xfOrientation) { + case 0: + $objStyle->getAlignment()->setTextRotation(0); + break; + case 1: + $objStyle->getAlignment()->setTextRotation(-165); + break; + case 2: + $objStyle->getAlignment()->setTextRotation(90); + break; + case 3: + $objStyle->getAlignment()->setTextRotation(-90); + break; + } + + // offset: 8; size: 4; cell border lines and background area + $borderAndBackground = self::getInt4d($recordData, 8); + + // bit: 6-0; mask: 0x0000007F; color index for pattern color + $objStyle->getFill()->startcolorIndex = (0x0000007F & $borderAndBackground) >> 0; + + // bit: 13-7; mask: 0x00003F80; color index for pattern background + $objStyle->getFill()->endcolorIndex = (0x00003F80 & $borderAndBackground) >> 7; + + // bit: 21-16; mask: 0x003F0000; fill pattern + $objStyle->getFill()->setFillType(PHPExcel_Reader_Excel5_Style_FillPattern::lookup((0x003F0000 & $borderAndBackground) >> 16)); + + // bit: 24-22; mask: 0x01C00000; bottom line style + $objStyle->getBorders()->getBottom()->setBorderStyle(PHPExcel_Reader_Excel5_Style_Border::lookup((0x01C00000 & $borderAndBackground) >> 22)); + + // bit: 31-25; mask: 0xFE000000; bottom line color + $objStyle->getBorders()->getBottom()->colorIndex = (0xFE000000 & $borderAndBackground) >> 25; + + // offset: 12; size: 4; cell border lines + $borderLines = self::getInt4d($recordData, 12); + + // bit: 2-0; mask: 0x00000007; top line style + $objStyle->getBorders()->getTop()->setBorderStyle(PHPExcel_Reader_Excel5_Style_Border::lookup((0x00000007 & $borderLines) >> 0)); + + // bit: 5-3; mask: 0x00000038; left line style + $objStyle->getBorders()->getLeft()->setBorderStyle(PHPExcel_Reader_Excel5_Style_Border::lookup((0x00000038 & $borderLines) >> 3)); + + // bit: 8-6; mask: 0x000001C0; right line style + $objStyle->getBorders()->getRight()->setBorderStyle(PHPExcel_Reader_Excel5_Style_Border::lookup((0x000001C0 & $borderLines) >> 6)); + + // bit: 15-9; mask: 0x0000FE00; top line color index + $objStyle->getBorders()->getTop()->colorIndex = (0x0000FE00 & $borderLines) >> 9; + + // bit: 22-16; mask: 0x007F0000; left line color index + $objStyle->getBorders()->getLeft()->colorIndex = (0x007F0000 & $borderLines) >> 16; + + // bit: 29-23; mask: 0x3F800000; right line color index + $objStyle->getBorders()->getRight()->colorIndex = (0x3F800000 & $borderLines) >> 23; + } + + // add cellStyleXf or cellXf and update mapping + if ($isCellStyleXf) { + // we only read one style XF record which is always the first + if ($this->xfIndex == 0) { + $this->phpExcel->addCellStyleXf($objStyle); + $this->mapCellStyleXfIndex[$this->xfIndex] = 0; + } + } else { + // we read all cell XF records + $this->phpExcel->addCellXf($objStyle); + $this->mapCellXfIndex[$this->xfIndex] = count($this->phpExcel->getCellXfCollection()) - 1; + } + + // update XF index for when we read next record + ++$this->xfIndex; + } + } + + + /** + * + */ + private function readXfExt() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; 0x087D = repeated header + + // offset: 2; size: 2 + + // offset: 4; size: 8; not used + + // offset: 12; size: 2; record version + + // offset: 14; size: 2; index to XF record which this record modifies + $ixfe = self::getInt2d($recordData, 14); + + // offset: 16; size: 2; not used + + // offset: 18; size: 2; number of extension properties that follow + $cexts = self::getInt2d($recordData, 18); + + // start reading the actual extension data + $offset = 20; + while ($offset < $length) { + // extension type + $extType = self::getInt2d($recordData, $offset); + + // extension length + $cb = self::getInt2d($recordData, $offset + 2); + + // extension data + $extData = substr($recordData, $offset + 4, $cb); + + switch ($extType) { + case 4: // fill start color + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $fill = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); + $fill->getStartColor()->setRGB($rgb); + unset($fill->startcolorIndex); // normal color index does not apply, discard + } + } + break; + case 5: // fill end color + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $fill = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFill(); + $fill->getEndColor()->setRGB($rgb); + unset($fill->endcolorIndex); // normal color index does not apply, discard + } + } + break; + case 7: // border color top + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $top = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getTop(); + $top->getColor()->setRGB($rgb); + unset($top->colorIndex); // normal color index does not apply, discard + } + } + break; + case 8: // border color bottom + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $bottom = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getBottom(); + $bottom->getColor()->setRGB($rgb); + unset($bottom->colorIndex); // normal color index does not apply, discard + } + } + break; + case 9: // border color left + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $left = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getLeft(); + $left->getColor()->setRGB($rgb); + unset($left->colorIndex); // normal color index does not apply, discard + } + } + break; + case 10: // border color right + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $right = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getRight(); + $right->getColor()->setRGB($rgb); + unset($right->colorIndex); // normal color index does not apply, discard + } + } + break; + case 11: // border color diagonal + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $diagonal = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getBorders()->getDiagonal(); + $diagonal->getColor()->setRGB($rgb); + unset($diagonal->colorIndex); // normal color index does not apply, discard + } + } + break; + case 13: // font color + $xclfType = self::getInt2d($extData, 0); // color type + $xclrValue = substr($extData, 4, 4); // color value (value based on color type) + + if ($xclfType == 2) { + $rgb = sprintf('%02X%02X%02X', ord($xclrValue{0}), ord($xclrValue{1}), ord($xclrValue{2})); + + // modify the relevant style property + if (isset($this->mapCellXfIndex[$ixfe])) { + $font = $this->phpExcel->getCellXfByIndex($this->mapCellXfIndex[$ixfe])->getFont(); + $font->getColor()->setRGB($rgb); + unset($font->colorIndex); // normal color index does not apply, discard + } + } + break; + } + + $offset += $cb; + } + } + + } + + + /** + * Read STYLE record + */ + private function readStyle() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; index to XF record and flag for built-in style + $ixfe = self::getInt2d($recordData, 0); + + // bit: 11-0; mask 0x0FFF; index to XF record + $xfIndex = (0x0FFF & $ixfe) >> 0; + + // bit: 15; mask 0x8000; 0 = user-defined style, 1 = built-in style + $isBuiltIn = (bool) ((0x8000 & $ixfe) >> 15); + + if ($isBuiltIn) { + // offset: 2; size: 1; identifier for built-in style + $builtInId = ord($recordData{2}); + + switch ($builtInId) { + case 0x00: + // currently, we are not using this for anything + break; + default: + break; + } + } else { + // user-defined; not supported by PHPExcel + } + } + } + + + /** + * Read PALETTE record + */ + private function readPalette() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; number of following colors + $nm = self::getInt2d($recordData, 0); + + // list of RGB colors + for ($i = 0; $i < $nm; ++$i) { + $rgb = substr($recordData, 2 + 4 * $i, 4); + $this->palette[] = self::readRGB($rgb); + } + } + } + + + /** + * SHEET + * + * This record is located in the Workbook Globals + * Substream and represents a sheet inside the workbook. + * One SHEET record is written for each sheet. It stores the + * sheet name and a stream offset to the BOF record of the + * respective Sheet Substream within the Workbook Stream. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readSheet() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // offset: 0; size: 4; absolute stream position of the BOF record of the sheet + // NOTE: not encrypted + $rec_offset = self::getInt4d($this->data, $this->pos + 4); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 4; size: 1; sheet state + switch (ord($recordData{4})) { + case 0x00: + $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; + break; + case 0x01: + $sheetState = PHPExcel_Worksheet::SHEETSTATE_HIDDEN; + break; + case 0x02: + $sheetState = PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN; + break; + default: + $sheetState = PHPExcel_Worksheet::SHEETSTATE_VISIBLE; + break; + } + + // offset: 5; size: 1; sheet type + $sheetType = ord($recordData{5}); + + // offset: 6; size: var; sheet name + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringShort(substr($recordData, 6)); + $rec_name = $string['value']; + } elseif ($this->version == self::XLS_BIFF7) { + $string = $this->readByteStringShort(substr($recordData, 6)); + $rec_name = $string['value']; + } + + $this->sheets[] = array( + 'name' => $rec_name, + 'offset' => $rec_offset, + 'sheetState' => $sheetState, + 'sheetType' => $sheetType, + ); + } + + + /** + * Read EXTERNALBOOK record + */ + private function readExternalBook() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset within record data + $offset = 0; + + // there are 4 types of records + if (strlen($recordData) > 4) { + // external reference + // offset: 0; size: 2; number of sheet names ($nm) + $nm = self::getInt2d($recordData, 0); + $offset += 2; + + // offset: 2; size: var; encoded URL without sheet name (Unicode string, 16-bit length) + $encodedUrlString = self::readUnicodeStringLong(substr($recordData, 2)); + $offset += $encodedUrlString['size']; + + // offset: var; size: var; list of $nm sheet names (Unicode strings, 16-bit length) + $externalSheetNames = array(); + for ($i = 0; $i < $nm; ++$i) { + $externalSheetNameString = self::readUnicodeStringLong(substr($recordData, $offset)); + $externalSheetNames[] = $externalSheetNameString['value']; + $offset += $externalSheetNameString['size']; + } + + // store the record data + $this->externalBooks[] = array( + 'type' => 'external', + 'encodedUrl' => $encodedUrlString['value'], + 'externalSheetNames' => $externalSheetNames, + ); + } elseif (substr($recordData, 2, 2) == pack('CC', 0x01, 0x04)) { + // internal reference + // offset: 0; size: 2; number of sheet in this document + // offset: 2; size: 2; 0x01 0x04 + $this->externalBooks[] = array( + 'type' => 'internal', + ); + } elseif (substr($recordData, 0, 4) == pack('vCC', 0x0001, 0x01, 0x3A)) { + // add-in function + // offset: 0; size: 2; 0x0001 + $this->externalBooks[] = array( + 'type' => 'addInFunction', + ); + } elseif (substr($recordData, 0, 2) == pack('v', 0x0000)) { + // DDE links, OLE links + // offset: 0; size: 2; 0x0000 + // offset: 2; size: var; encoded source document name + $this->externalBooks[] = array( + 'type' => 'DDEorOLE', + ); + } + } + + + /** + * Read EXTERNNAME record. + */ + private function readExternName() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // external sheet references provided for named cells + if ($this->version == self::XLS_BIFF8) { + // offset: 0; size: 2; options + $options = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; + + // offset: 4; size: 2; not used + + // offset: 6; size: var + $nameString = self::readUnicodeStringShort(substr($recordData, 6)); + + // offset: var; size: var; formula data + $offset = 6 + $nameString['size']; + $formula = $this->getFormulaFromStructure(substr($recordData, $offset)); + + $this->externalNames[] = array( + 'name' => $nameString['value'], + 'formula' => $formula, + ); + } + } + + + /** + * Read EXTERNSHEET record + */ + private function readExternSheet() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // external sheet references provided for named cells + if ($this->version == self::XLS_BIFF8) { + // offset: 0; size: 2; number of following ref structures + $nm = self::getInt2d($recordData, 0); + for ($i = 0; $i < $nm; ++$i) { + $this->ref[] = array( + // offset: 2 + 6 * $i; index to EXTERNALBOOK record + 'externalBookIndex' => self::getInt2d($recordData, 2 + 6 * $i), + // offset: 4 + 6 * $i; index to first sheet in EXTERNALBOOK record + 'firstSheetIndex' => self::getInt2d($recordData, 4 + 6 * $i), + // offset: 6 + 6 * $i; index to last sheet in EXTERNALBOOK record + 'lastSheetIndex' => self::getInt2d($recordData, 6 + 6 * $i), + ); + } + } + } + + + /** + * DEFINEDNAME + * + * This record is part of a Link Table. It contains the name + * and the token array of an internal defined name. Token + * arrays of defined names contain tokens with aberrant + * token classes. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readDefinedName() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8) { + // retrieves named cells + + // offset: 0; size: 2; option flags + $opts = self::getInt2d($recordData, 0); + + // bit: 5; mask: 0x0020; 0 = user-defined name, 1 = built-in-name + $isBuiltInName = (0x0020 & $opts) >> 5; + + // offset: 2; size: 1; keyboard shortcut + + // offset: 3; size: 1; length of the name (character count) + $nlen = ord($recordData{3}); + + // offset: 4; size: 2; size of the formula data (it can happen that this is zero) + // note: there can also be additional data, this is not included in $flen + $flen = self::getInt2d($recordData, 4); + + // offset: 8; size: 2; 0=Global name, otherwise index to sheet (1-based) + $scope = self::getInt2d($recordData, 8); + + // offset: 14; size: var; Name (Unicode string without length field) + $string = self::readUnicodeString(substr($recordData, 14), $nlen); + + // offset: var; size: $flen; formula data + $offset = 14 + $string['size']; + $formulaStructure = pack('v', $flen) . substr($recordData, $offset); + + try { + $formula = $this->getFormulaFromStructure($formulaStructure); + } catch (PHPExcel_Exception $e) { + $formula = ''; + } + + $this->definedname[] = array( + 'isBuiltInName' => $isBuiltInName, + 'name' => $string['value'], + 'formula' => $formula, + 'scope' => $scope, + ); + } + } + + + /** + * Read MSODRAWINGGROUP record + */ + private function readMsoDrawingGroup() + { + $length = self::getInt2d($this->data, $this->pos + 2); + + // get spliced record data + $splicedRecordData = $this->getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + $this->drawingGroupData .= $recordData; + } + + + /** + * SST - Shared String Table + * + * This record contains a list of all strings used anywhere + * in the workbook. Each string occurs only once. The + * workbook uses indexes into the list to reference the + * strings. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + **/ + private function readSst() + { + // offset within (spliced) record data + $pos = 0; + + // get spliced record data + $splicedRecordData = $this->getSplicedRecordData(); + + $recordData = $splicedRecordData['recordData']; + $spliceOffsets = $splicedRecordData['spliceOffsets']; + + // offset: 0; size: 4; total number of strings in the workbook + $pos += 4; + + // offset: 4; size: 4; number of following strings ($nm) + $nm = self::getInt4d($recordData, 4); + $pos += 4; + + // loop through the Unicode strings (16-bit length) + for ($i = 0; $i < $nm; ++$i) { + // number of characters in the Unicode string + $numChars = self::getInt2d($recordData, $pos); + $pos += 2; + + // option flags + $optionFlags = ord($recordData{$pos}); + ++$pos; + + // bit: 0; mask: 0x01; 0 = compressed; 1 = uncompressed + $isCompressed = (($optionFlags & 0x01) == 0) ; + + // bit: 2; mask: 0x02; 0 = ordinary; 1 = Asian phonetic + $hasAsian = (($optionFlags & 0x04) != 0); + + // bit: 3; mask: 0x03; 0 = ordinary; 1 = Rich-Text + $hasRichText = (($optionFlags & 0x08) != 0); + + if ($hasRichText) { + // number of Rich-Text formatting runs + $formattingRuns = self::getInt2d($recordData, $pos); + $pos += 2; + } + + if ($hasAsian) { + // size of Asian phonetic setting + $extendedRunLength = self::getInt4d($recordData, $pos); + $pos += 4; + } + + // expected byte length of character array if not split + $len = ($isCompressed) ? $numChars : $numChars * 2; + + // look up limit position + foreach ($spliceOffsets as $spliceOffset) { + // it can happen that the string is empty, therefore we need + // <= and not just < + if ($pos <= $spliceOffset) { + $limitpos = $spliceOffset; + break; + } + } + + if ($pos + $len <= $limitpos) { + // character array is not split between records + + $retstr = substr($recordData, $pos, $len); + $pos += $len; + } else { + // character array is split between records + + // first part of character array + $retstr = substr($recordData, $pos, $limitpos - $pos); + + $bytesRead = $limitpos - $pos; + + // remaining characters in Unicode string + $charsLeft = $numChars - (($isCompressed) ? $bytesRead : ($bytesRead / 2)); + + $pos = $limitpos; + + // keep reading the characters + while ($charsLeft > 0) { + // look up next limit position, in case the string span more than one continue record + foreach ($spliceOffsets as $spliceOffset) { + if ($pos < $spliceOffset) { + $limitpos = $spliceOffset; + break; + } + } + + // repeated option flags + // OpenOffice.org documentation 5.21 + $option = ord($recordData{$pos}); + ++$pos; + + if ($isCompressed && ($option == 0)) { + // 1st fragment compressed + // this fragment compressed + $len = min($charsLeft, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len; + $isCompressed = true; + } elseif (!$isCompressed && ($option != 0)) { + // 1st fragment uncompressed + // this fragment uncompressed + $len = min($charsLeft * 2, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len / 2; + $isCompressed = false; + } elseif (!$isCompressed && ($option == 0)) { + // 1st fragment uncompressed + // this fragment compressed + $len = min($charsLeft, $limitpos - $pos); + for ($j = 0; $j < $len; ++$j) { + $retstr .= $recordData{$pos + $j} . chr(0); + } + $charsLeft -= $len; + $isCompressed = false; + } else { + // 1st fragment compressed + // this fragment uncompressed + $newstr = ''; + for ($j = 0; $j < strlen($retstr); ++$j) { + $newstr .= $retstr[$j] . chr(0); + } + $retstr = $newstr; + $len = min($charsLeft * 2, $limitpos - $pos); + $retstr .= substr($recordData, $pos, $len); + $charsLeft -= $len / 2; + $isCompressed = false; + } + + $pos += $len; + } + } + + // convert to UTF-8 + $retstr = self::encodeUTF16($retstr, $isCompressed); + + // read additional Rich-Text information, if any + $fmtRuns = array(); + if ($hasRichText) { + // list of formatting runs + for ($j = 0; $j < $formattingRuns; ++$j) { + // first formatted character; zero-based + $charPos = self::getInt2d($recordData, $pos + $j * 4); + + // index to font record + $fontIndex = self::getInt2d($recordData, $pos + 2 + $j * 4); + + $fmtRuns[] = array( + 'charPos' => $charPos, + 'fontIndex' => $fontIndex, + ); + } + $pos += 4 * $formattingRuns; + } + + // read additional Asian phonetics information, if any + if ($hasAsian) { + // For Asian phonetic settings, we skip the extended string data + $pos += $extendedRunLength; + } + + // store the shared sting + $this->sst[] = array( + 'value' => $retstr, + 'fmtRuns' => $fmtRuns, + ); + } + + // getSplicedRecordData() takes care of moving current position in data stream + } + + + /** + * Read PRINTGRIDLINES record + */ + private function readPrintGridlines() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { + // offset: 0; size: 2; 0 = do not print sheet grid lines; 1 = print sheet gridlines + $printGridlines = (bool) self::getInt2d($recordData, 0); + $this->phpSheet->setPrintGridlines($printGridlines); + } + } + + + /** + * Read DEFAULTROWHEIGHT record + */ + private function readDefaultRowHeight() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; option flags + // offset: 2; size: 2; default height for unused rows, (twips 1/20 point) + $height = self::getInt2d($recordData, 2); + $this->phpSheet->getDefaultRowDimension()->setRowHeight($height / 20); + } + + + /** + * Read SHEETPR record + */ + private function readSheetPr() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2 + + // bit: 6; mask: 0x0040; 0 = outline buttons above outline group + $isSummaryBelow = (0x0040 & self::getInt2d($recordData, 0)) >> 6; + $this->phpSheet->setShowSummaryBelow($isSummaryBelow); + + // bit: 7; mask: 0x0080; 0 = outline buttons left of outline group + $isSummaryRight = (0x0080 & self::getInt2d($recordData, 0)) >> 7; + $this->phpSheet->setShowSummaryRight($isSummaryRight); + + // bit: 8; mask: 0x100; 0 = scale printout in percent, 1 = fit printout to number of pages + // this corresponds to radio button setting in page setup dialog in Excel + $this->isFitToPages = (bool) ((0x0100 & self::getInt2d($recordData, 0)) >> 8); + } + + + /** + * Read HORIZONTALPAGEBREAKS record + */ + private function readHorizontalPageBreaks() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { + // offset: 0; size: 2; number of the following row index structures + $nm = self::getInt2d($recordData, 0); + + // offset: 2; size: 6 * $nm; list of $nm row index structures + for ($i = 0; $i < $nm; ++$i) { + $r = self::getInt2d($recordData, 2 + 6 * $i); + $cf = self::getInt2d($recordData, 2 + 6 * $i + 2); + $cl = self::getInt2d($recordData, 2 + 6 * $i + 4); + + // not sure why two column indexes are necessary? + $this->phpSheet->setBreakByColumnAndRow($cf, $r, PHPExcel_Worksheet::BREAK_ROW); + } + } + } + + + /** + * Read VERTICALPAGEBREAKS record + */ + private function readVerticalPageBreaks() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { + // offset: 0; size: 2; number of the following column index structures + $nm = self::getInt2d($recordData, 0); + + // offset: 2; size: 6 * $nm; list of $nm row index structures + for ($i = 0; $i < $nm; ++$i) { + $c = self::getInt2d($recordData, 2 + 6 * $i); + $rf = self::getInt2d($recordData, 2 + 6 * $i + 2); + $rl = self::getInt2d($recordData, 2 + 6 * $i + 4); + + // not sure why two row indexes are necessary? + $this->phpSheet->setBreakByColumnAndRow($c, $rf, PHPExcel_Worksheet::BREAK_COLUMN); + } + } + } + + + /** + * Read HEADER record + */ + private function readHeader() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: var + // realized that $recordData can be empty even when record exists + if ($recordData) { + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringLong($recordData); + } else { + $string = $this->readByteStringShort($recordData); + } + + $this->phpSheet->getHeaderFooter()->setOddHeader($string['value']); + $this->phpSheet->getHeaderFooter()->setEvenHeader($string['value']); + } + } + } + + + /** + * Read FOOTER record + */ + private function readFooter() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: var + // realized that $recordData can be empty even when record exists + if ($recordData) { + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringLong($recordData); + } else { + $string = $this->readByteStringShort($recordData); + } + $this->phpSheet->getHeaderFooter()->setOddFooter($string['value']); + $this->phpSheet->getHeaderFooter()->setEvenFooter($string['value']); + } + } + } + + + /** + * Read HCENTER record + */ + private function readHcenter() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; 0 = print sheet left aligned, 1 = print sheet centered horizontally + $isHorizontalCentered = (bool) self::getInt2d($recordData, 0); + + $this->phpSheet->getPageSetup()->setHorizontalCentered($isHorizontalCentered); + } + } + + + /** + * Read VCENTER record + */ + private function readVcenter() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; 0 = print sheet aligned at top page border, 1 = print sheet vertically centered + $isVerticalCentered = (bool) self::getInt2d($recordData, 0); + + $this->phpSheet->getPageSetup()->setVerticalCentered($isVerticalCentered); + } + } + + + /** + * Read LEFTMARGIN record + */ + private function readLeftMargin() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 8 + $this->phpSheet->getPageMargins()->setLeft(self::extractNumber($recordData)); + } + } + + + /** + * Read RIGHTMARGIN record + */ + private function readRightMargin() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 8 + $this->phpSheet->getPageMargins()->setRight(self::extractNumber($recordData)); + } + } + + + /** + * Read TOPMARGIN record + */ + private function readTopMargin() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 8 + $this->phpSheet->getPageMargins()->setTop(self::extractNumber($recordData)); + } + } + + + /** + * Read BOTTOMMARGIN record + */ + private function readBottomMargin() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 8 + $this->phpSheet->getPageMargins()->setBottom(self::extractNumber($recordData)); + } + } + + + /** + * Read PAGESETUP record + */ + private function readPageSetup() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; paper size + $paperSize = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; scaling factor + $scale = self::getInt2d($recordData, 2); + + // offset: 6; size: 2; fit worksheet width to this number of pages, 0 = use as many as needed + $fitToWidth = self::getInt2d($recordData, 6); + + // offset: 8; size: 2; fit worksheet height to this number of pages, 0 = use as many as needed + $fitToHeight = self::getInt2d($recordData, 8); + + // offset: 10; size: 2; option flags + + // bit: 1; mask: 0x0002; 0=landscape, 1=portrait + $isPortrait = (0x0002 & self::getInt2d($recordData, 10)) >> 1; + + // bit: 2; mask: 0x0004; 1= paper size, scaling factor, paper orient. not init + // when this bit is set, do not use flags for those properties + $isNotInit = (0x0004 & self::getInt2d($recordData, 10)) >> 2; + + if (!$isNotInit) { + $this->phpSheet->getPageSetup()->setPaperSize($paperSize); + switch ($isPortrait) { + case 0: + $this->phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE); + break; + case 1: + $this->phpSheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT); + break; + } + + $this->phpSheet->getPageSetup()->setScale($scale, false); + $this->phpSheet->getPageSetup()->setFitToPage((bool) $this->isFitToPages); + $this->phpSheet->getPageSetup()->setFitToWidth($fitToWidth, false); + $this->phpSheet->getPageSetup()->setFitToHeight($fitToHeight, false); + } + + // offset: 16; size: 8; header margin (IEEE 754 floating-point value) + $marginHeader = self::extractNumber(substr($recordData, 16, 8)); + $this->phpSheet->getPageMargins()->setHeader($marginHeader); + + // offset: 24; size: 8; footer margin (IEEE 754 floating-point value) + $marginFooter = self::extractNumber(substr($recordData, 24, 8)); + $this->phpSheet->getPageMargins()->setFooter($marginFooter); + } + } + + + /** + * PROTECT - Sheet protection (BIFF2 through BIFF8) + * if this record is omitted, then it also means no sheet protection + */ + private function readProtect() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit 0, mask 0x01; 1 = sheet is protected + $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; + $this->phpSheet->getProtection()->setSheet((bool)$bool); + } + + + /** + * SCENPROTECT + */ + private function readScenProtect() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit: 0, mask 0x01; 1 = scenarios are protected + $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; + + $this->phpSheet->getProtection()->setScenarios((bool)$bool); + } + + + /** + * OBJECTPROTECT + */ + private function readObjectProtect() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 2; + + // bit: 0, mask 0x01; 1 = objects are protected + $bool = (0x01 & self::getInt2d($recordData, 0)) >> 0; + + $this->phpSheet->getProtection()->setObjects((bool)$bool); + } + + + /** + * PASSWORD - Sheet protection (hashed) password (BIFF2 through BIFF8) + */ + private function readPassword() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; 16-bit hash value of password + $password = strtoupper(dechex(self::getInt2d($recordData, 0))); // the hashed password + $this->phpSheet->getProtection()->setPassword($password, true); + } + } + + + /** + * Read DEFCOLWIDTH record + */ + private function readDefColWidth() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; default column width + $width = self::getInt2d($recordData, 0); + if ($width != 8) { + $this->phpSheet->getDefaultColumnDimension()->setWidth($width); + } + } + + + /** + * Read COLINFO record + */ + private function readColInfo() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; index to first column in range + $fc = self::getInt2d($recordData, 0); // first column index + + // offset: 2; size: 2; index to last column in range + $lc = self::getInt2d($recordData, 2); // first column index + + // offset: 4; size: 2; width of the column in 1/256 of the width of the zero character + $width = self::getInt2d($recordData, 4); + + // offset: 6; size: 2; index to XF record for default column formatting + $xfIndex = self::getInt2d($recordData, 6); + + // offset: 8; size: 2; option flags + // bit: 0; mask: 0x0001; 1= columns are hidden + $isHidden = (0x0001 & self::getInt2d($recordData, 8)) >> 0; + + // bit: 10-8; mask: 0x0700; outline level of the columns (0 = no outline) + $level = (0x0700 & self::getInt2d($recordData, 8)) >> 8; + + // bit: 12; mask: 0x1000; 1 = collapsed + $isCollapsed = (0x1000 & self::getInt2d($recordData, 8)) >> 12; + + // offset: 10; size: 2; not used + + for ($i = $fc; $i <= $lc; ++$i) { + if ($lc == 255 || $lc == 256) { + $this->phpSheet->getDefaultColumnDimension()->setWidth($width / 256); + break; + } + $this->phpSheet->getColumnDimensionByColumn($i)->setWidth($width / 256); + $this->phpSheet->getColumnDimensionByColumn($i)->setVisible(!$isHidden); + $this->phpSheet->getColumnDimensionByColumn($i)->setOutlineLevel($level); + $this->phpSheet->getColumnDimensionByColumn($i)->setCollapsed($isCollapsed); + $this->phpSheet->getColumnDimensionByColumn($i)->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * ROW + * + * This record contains the properties of a single row in a + * sheet. Rows and cells in a sheet are divided into blocks + * of 32 rows. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readRow() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; index of this row + $r = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to column of the first cell which is described by a cell record + + // offset: 4; size: 2; index to column of the last cell which is described by a cell record, increased by 1 + + // offset: 6; size: 2; + + // bit: 14-0; mask: 0x7FFF; height of the row, in twips = 1/20 of a point + $height = (0x7FFF & self::getInt2d($recordData, 6)) >> 0; + + // bit: 15: mask: 0x8000; 0 = row has custom height; 1= row has default height + $useDefaultHeight = (0x8000 & self::getInt2d($recordData, 6)) >> 15; + + if (!$useDefaultHeight) { + $this->phpSheet->getRowDimension($r + 1)->setRowHeight($height / 20); + } + + // offset: 8; size: 2; not used + + // offset: 10; size: 2; not used in BIFF5-BIFF8 + + // offset: 12; size: 4; option flags and default row formatting + + // bit: 2-0: mask: 0x00000007; outline level of the row + $level = (0x00000007 & self::getInt4d($recordData, 12)) >> 0; + $this->phpSheet->getRowDimension($r + 1)->setOutlineLevel($level); + + // bit: 4; mask: 0x00000010; 1 = outline group start or ends here... and is collapsed + $isCollapsed = (0x00000010 & self::getInt4d($recordData, 12)) >> 4; + $this->phpSheet->getRowDimension($r + 1)->setCollapsed($isCollapsed); + + // bit: 5; mask: 0x00000020; 1 = row is hidden + $isHidden = (0x00000020 & self::getInt4d($recordData, 12)) >> 5; + $this->phpSheet->getRowDimension($r + 1)->setVisible(!$isHidden); + + // bit: 7; mask: 0x00000080; 1 = row has explicit format + $hasExplicitFormat = (0x00000080 & self::getInt4d($recordData, 12)) >> 7; + + // bit: 27-16; mask: 0x0FFF0000; only applies when hasExplicitFormat = 1; index to XF record + $xfIndex = (0x0FFF0000 & self::getInt4d($recordData, 12)) >> 16; + + if ($hasExplicitFormat) { + $this->phpSheet->getRowDimension($r + 1)->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read RK record + * This record represents a cell that contains an RK value + * (encoded integer or floating-point value). If a + * floating-point value cannot be encoded to an RK value, + * a NUMBER record will be written. This record replaces the + * record INTEGER written in BIFF2. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readRk() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::getInt2d($recordData, 4); + + // offset: 6; size: 4; RK value + $rknum = self::getInt4d($recordData, 6); + $numValue = self::getIEEE754($rknum); + + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + if (!$this->readDataOnly) { + // add style information + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + + // add cell + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + } + + + /** + * Read LABELSST record + * This record represents a cell that contains a string. It + * replaces the LABEL record and RSTRING record used in + * BIFF2-BIFF5. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readLabelSst() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + $emptyCell = true; + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::getInt2d($recordData, 4); + + // offset: 6; size: 4; index to SST record + $index = self::getInt4d($recordData, 6); + + // add cell + if (($fmtRuns = $this->sst[$index]['fmtRuns']) && !$this->readDataOnly) { + // then we should treat as rich text + $richText = new PHPExcel_RichText(); + $charPos = 0; + $sstCount = count($this->sst[$index]['fmtRuns']); + for ($i = 0; $i <= $sstCount; ++$i) { + if (isset($fmtRuns[$i])) { + $text = PHPExcel_Shared_String::Substring($this->sst[$index]['value'], $charPos, $fmtRuns[$i]['charPos'] - $charPos); + $charPos = $fmtRuns[$i]['charPos']; + } else { + $text = PHPExcel_Shared_String::Substring($this->sst[$index]['value'], $charPos, PHPExcel_Shared_String::CountCharacters($this->sst[$index]['value'])); + } + + if (PHPExcel_Shared_String::CountCharacters($text) > 0) { + if ($i == 0) { // first text run, no style + $richText->createText($text); + } else { + $textRun = $richText->createTextRun($text); + if (isset($fmtRuns[$i - 1])) { + if ($fmtRuns[$i - 1]['fontIndex'] < 4) { + $fontIndex = $fmtRuns[$i - 1]['fontIndex']; + } else { + // this has to do with that index 4 is omitted in all BIFF versions for some strange reason + // check the OpenOffice documentation of the FONT record + $fontIndex = $fmtRuns[$i - 1]['fontIndex'] - 1; + } + $textRun->setFont(clone $this->objFonts[$fontIndex]); + } + } + } + } + if ($this->readEmptyCells || trim($richText->getPlainText()) !== '') { + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($richText, PHPExcel_Cell_DataType::TYPE_STRING); + $emptyCell = false; + } + } else { + if ($this->readEmptyCells || trim($this->sst[$index]['value']) !== '') { + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($this->sst[$index]['value'], PHPExcel_Cell_DataType::TYPE_STRING); + $emptyCell = false; + } + } + + if (!$this->readDataOnly && !$emptyCell) { + // add style information + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read MULRK record + * This record represents a cell range containing RK value + * cells. All cells are located in the same row. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readMulRk() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to first column + $colFirst = self::getInt2d($recordData, 2); + + // offset: var; size: 2; index to last column + $colLast = self::getInt2d($recordData, $length - 2); + $columns = $colLast - $colFirst + 1; + + // offset within record data + $offset = 4; + + for ($i = 0; $i < $columns; ++$i) { + $columnString = PHPExcel_Cell::stringFromColumnIndex($colFirst + $i); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: var; size: 2; index to XF record + $xfIndex = self::getInt2d($recordData, $offset); + + // offset: var; size: 4; RK value + $numValue = self::getIEEE754(self::getInt4d($recordData, $offset + 2)); + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + if (!$this->readDataOnly) { + // add style + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + + // add cell value + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + + $offset += 6; + } + } + + + /** + * Read NUMBER record + * This record represents a cell that contains a + * floating-point value. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readNumber() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size 2; index to column + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset 4; size: 2; index to XF record + $xfIndex = self::getInt2d($recordData, 4); + + $numValue = self::extractNumber(substr($recordData, 6, 8)); + + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + if (!$this->readDataOnly) { + // add cell style + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + + // add cell value + $cell->setValueExplicit($numValue, PHPExcel_Cell_DataType::TYPE_NUMERIC); + } + } + + + /** + * Read FORMULA record + perhaps a following STRING record if formula result is a string + * This record contains the token array and the result of a + * formula cell. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readFormula() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; col index + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // offset: 20: size: variable; formula structure + $formulaStructure = substr($recordData, 20); + + // offset: 14: size: 2; option flags, recalculate always, recalculate on open etc. + $options = self::getInt2d($recordData, 14); + + // bit: 0; mask: 0x0001; 1 = recalculate always + // bit: 1; mask: 0x0002; 1 = calculate on open + // bit: 2; mask: 0x0008; 1 = part of a shared formula + $isPartOfSharedFormula = (bool) (0x0008 & $options); + + // WARNING: + // We can apparently not rely on $isPartOfSharedFormula. Even when $isPartOfSharedFormula = true + // the formula data may be ordinary formula data, therefore we need to check + // explicitly for the tExp token (0x01) + $isPartOfSharedFormula = $isPartOfSharedFormula && ord($formulaStructure{2}) == 0x01; + + if ($isPartOfSharedFormula) { + // part of shared formula which means there will be a formula with a tExp token and nothing else + // get the base cell, grab tExp token + $baseRow = self::getInt2d($formulaStructure, 3); + $baseCol = self::getInt2d($formulaStructure, 5); + $this->_baseCell = PHPExcel_Cell::stringFromColumnIndex($baseCol). ($baseRow + 1); + } + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + if ($isPartOfSharedFormula) { + // formula is added to this cell after the sheet has been read + $this->sharedFormulaParts[$columnString . ($row + 1)] = $this->_baseCell; + } + + // offset: 16: size: 4; not used + + // offset: 4; size: 2; XF index + $xfIndex = self::getInt2d($recordData, 4); + + // offset: 6; size: 8; result of the formula + if ((ord($recordData{6}) == 0) && (ord($recordData{12}) == 255) && (ord($recordData{13}) == 255)) { + // String formula. Result follows in appended STRING record + $dataType = PHPExcel_Cell_DataType::TYPE_STRING; + + // read possible SHAREDFMLA record + $code = self::getInt2d($this->data, $this->pos); + if ($code == self::XLS_TYPE_SHAREDFMLA) { + $this->readSharedFmla(); + } + + // read STRING record + $value = $this->readString(); + } elseif ((ord($recordData{6}) == 1) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + // Boolean formula. Result is in +2; 0=false, 1=true + $dataType = PHPExcel_Cell_DataType::TYPE_BOOL; + $value = (bool) ord($recordData{8}); + } elseif ((ord($recordData{6}) == 2) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + // Error formula. Error code is in +2 + $dataType = PHPExcel_Cell_DataType::TYPE_ERROR; + $value = PHPExcel_Reader_Excel5_ErrorCode::lookup(ord($recordData{8})); + } elseif ((ord($recordData{6}) == 3) + && (ord($recordData{12}) == 255) + && (ord($recordData{13}) == 255)) { + // Formula result is a null string + $dataType = PHPExcel_Cell_DataType::TYPE_NULL; + $value = ''; + } else { + // forumla result is a number, first 14 bytes like _NUMBER record + $dataType = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $value = self::extractNumber(substr($recordData, 6, 8)); + } + + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + if (!$this->readDataOnly) { + // add cell style + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + + // store the formula + if (!$isPartOfSharedFormula) { + // not part of shared formula + // add cell value. If we can read formula, populate with formula, otherwise just used cached value + try { + if ($this->version != self::XLS_BIFF8) { + throw new PHPExcel_Reader_Exception('Not BIFF8. Can only read BIFF8 formulas'); + } + $formula = $this->getFormulaFromStructure($formulaStructure); // get formula in human language + $cell->setValueExplicit('=' . $formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + + } catch (PHPExcel_Exception $e) { + $cell->setValueExplicit($value, $dataType); + } + } else { + if ($this->version == self::XLS_BIFF8) { + // do nothing at this point, formula id added later in the code + } else { + $cell->setValueExplicit($value, $dataType); + } + } + + // store the cached calculated value + $cell->setCalculatedValue($value); + } + } + + + /** + * Read a SHAREDFMLA record. This function just stores the binary shared formula in the reader, + * which usually contains relative references. + * These will be used to construct the formula in each shared formula part after the sheet is read. + */ + private function readSharedFmla() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0, size: 6; cell range address of the area used by the shared formula, not used for anything + $cellRange = substr($recordData, 0, 6); + $cellRange = $this->readBIFF5CellRangeAddressFixed($cellRange); // note: even BIFF8 uses BIFF5 syntax + + // offset: 6, size: 1; not used + + // offset: 7, size: 1; number of existing FORMULA records for this shared formula + $no = ord($recordData{7}); + + // offset: 8, size: var; Binary token array of the shared formula + $formula = substr($recordData, 8); + + // at this point we only store the shared formula for later use + $this->sharedFormulas[$this->_baseCell] = $formula; + } + + + /** + * Read a STRING record from current stream position and advance the stream pointer to next record + * This record is used for storing result from FORMULA record when it is a string, and + * it occurs directly after the FORMULA record + * + * @return string The string contents as UTF-8 + */ + private function readString() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringLong($recordData); + $value = $string['value']; + } else { + $string = $this->readByteStringLong($recordData); + $value = $string['value']; + } + + return $value; + } + + + /** + * Read BOOLERR record + * This record represents a Boolean value or error value + * cell. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readBoolErr() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; column index + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: 4; size: 2; index to XF record + $xfIndex = self::getInt2d($recordData, 4); + + // offset: 6; size: 1; the boolean value or error value + $boolErr = ord($recordData{6}); + + // offset: 7; size: 1; 0=boolean; 1=error + $isError = ord($recordData{7}); + + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + switch ($isError) { + case 0: // boolean + $value = (bool) $boolErr; + + // add cell value + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_BOOL); + break; + case 1: // error type + $value = PHPExcel_Reader_Excel5_ErrorCode::lookup($boolErr); + + // add cell value + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_ERROR); + break; + } + + if (!$this->readDataOnly) { + // add cell style + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read MULBLANK record + * This record represents a cell range of empty cells. All + * cells are located in the same row + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readMulBlank() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to first column + $fc = self::getInt2d($recordData, 2); + + // offset: 4; size: 2 x nc; list of indexes to XF records + // add style information + if (!$this->readDataOnly && $this->readEmptyCells) { + for ($i = 0; $i < $length / 2 - 3; ++$i) { + $columnString = PHPExcel_Cell::stringFromColumnIndex($fc + $i); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + $xfIndex = self::getInt2d($recordData, 4 + 2 * $i); + $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + // offset: 6; size 2; index to last column (not needed) + } + + + /** + * Read LABEL record + * This record represents a cell that contains a string. In + * BIFF8 it is usually replaced by the LABELSST record. + * Excel still uses this record, if it copies unformatted + * text cells to the clipboard. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readLabel() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; index to row + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to column + $column = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: 4; size: 2; XF index + $xfIndex = self::getInt2d($recordData, 4); + + // add cell value + // todo: what if string is very long? continue record + if ($this->version == self::XLS_BIFF8) { + $string = self::readUnicodeStringLong(substr($recordData, 6)); + $value = $string['value']; + } else { + $string = $this->readByteStringLong(substr($recordData, 6)); + $value = $string['value']; + } + if ($this->readEmptyCells || trim($value) !== '') { + $cell = $this->phpSheet->getCell($columnString . ($row + 1)); + $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_STRING); + + if (!$this->readDataOnly) { + // add cell style + $cell->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + } + + + /** + * Read BLANK record + */ + private function readBlank() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; row index + $row = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; col index + $col = self::getInt2d($recordData, 2); + $columnString = PHPExcel_Cell::stringFromColumnIndex($col); + + // Read cell? + if (($this->getReadFilter() !== null) && $this->getReadFilter()->readCell($columnString, $row + 1, $this->phpSheet->getTitle())) { + // offset: 4; size: 2; XF index + $xfIndex = self::getInt2d($recordData, 4); + + // add style information + if (!$this->readDataOnly && $this->readEmptyCells) { + $this->phpSheet->getCell($columnString . ($row + 1))->setXfIndex($this->mapCellXfIndex[$xfIndex]); + } + } + } + + + /** + * Read MSODRAWING record + */ + private function readMsoDrawing() + { + $length = self::getInt2d($this->data, $this->pos + 2); + + // get spliced record data + $splicedRecordData = $this->getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + $this->drawingData .= $recordData; + } + + + /** + * Read OBJ record + */ + private function readObj() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly || $this->version != self::XLS_BIFF8) { + return; + } + + // recordData consists of an array of subrecords looking like this: + // ft: 2 bytes; ftCmo type (0x15) + // cb: 2 bytes; size in bytes of ftCmo data + // ot: 2 bytes; Object Type + // id: 2 bytes; Object id number + // grbit: 2 bytes; Option Flags + // data: var; subrecord data + + // for now, we are just interested in the second subrecord containing the object type + $ftCmoType = self::getInt2d($recordData, 0); + $cbCmoSize = self::getInt2d($recordData, 2); + $otObjType = self::getInt2d($recordData, 4); + $idObjID = self::getInt2d($recordData, 6); + $grbitOpts = self::getInt2d($recordData, 6); + + $this->objs[] = array( + 'ftCmoType' => $ftCmoType, + 'cbCmoSize' => $cbCmoSize, + 'otObjType' => $otObjType, + 'idObjID' => $idObjID, + 'grbitOpts' => $grbitOpts + ); + $this->textObjRef = $idObjID; + +// echo '<b>_readObj()</b><br />'; +// var_dump(end($this->objs)); +// echo '<br />'; + } + + + /** + * Read WINDOW2 record + */ + private function readWindow2() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; option flags + $options = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; index to first visible row + $firstVisibleRow = self::getInt2d($recordData, 2); + + // offset: 4; size: 2; index to first visible colum + $firstVisibleColumn = self::getInt2d($recordData, 4); + if ($this->version === self::XLS_BIFF8) { + // offset: 8; size: 2; not used + // offset: 10; size: 2; cached magnification factor in page break preview (in percent); 0 = Default (60%) + // offset: 12; size: 2; cached magnification factor in normal view (in percent); 0 = Default (100%) + // offset: 14; size: 4; not used + $zoomscaleInPageBreakPreview = self::getInt2d($recordData, 10); + if ($zoomscaleInPageBreakPreview === 0) { + $zoomscaleInPageBreakPreview = 60; + } + $zoomscaleInNormalView = self::getInt2d($recordData, 12); + if ($zoomscaleInNormalView === 0) { + $zoomscaleInNormalView = 100; + } + } + + // bit: 1; mask: 0x0002; 0 = do not show gridlines, 1 = show gridlines + $showGridlines = (bool) ((0x0002 & $options) >> 1); + $this->phpSheet->setShowGridlines($showGridlines); + + // bit: 2; mask: 0x0004; 0 = do not show headers, 1 = show headers + $showRowColHeaders = (bool) ((0x0004 & $options) >> 2); + $this->phpSheet->setShowRowColHeaders($showRowColHeaders); + + // bit: 3; mask: 0x0008; 0 = panes are not frozen, 1 = panes are frozen + $this->frozen = (bool) ((0x0008 & $options) >> 3); + + // bit: 6; mask: 0x0040; 0 = columns from left to right, 1 = columns from right to left + $this->phpSheet->setRightToLeft((bool)((0x0040 & $options) >> 6)); + + // bit: 10; mask: 0x0400; 0 = sheet not active, 1 = sheet active + $isActive = (bool) ((0x0400 & $options) >> 10); + if ($isActive) { + $this->phpExcel->setActiveSheetIndex($this->phpExcel->getIndex($this->phpSheet)); + } + + // bit: 11; mask: 0x0800; 0 = normal view, 1 = page break view + $isPageBreakPreview = (bool) ((0x0800 & $options) >> 11); + + //FIXME: set $firstVisibleRow and $firstVisibleColumn + + if ($this->phpSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT) { + //NOTE: this setting is inferior to page layout view(Excel2007-) + $view = $isPageBreakPreview ? PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW : PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL; + $this->phpSheet->getSheetView()->setView($view); + if ($this->version === self::XLS_BIFF8) { + $zoomScale = $isPageBreakPreview ? $zoomscaleInPageBreakPreview : $zoomscaleInNormalView; + $this->phpSheet->getSheetView()->setZoomScale($zoomScale); + $this->phpSheet->getSheetView()->setZoomScaleNormal($zoomscaleInNormalView); + } + } + } + + /** + * Read PLV Record(Created by Excel2007 or upper) + */ + private function readPageLayoutView() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + //var_dump(unpack("vrt/vgrbitFrt/V2reserved/vwScalePLV/vgrbit", $recordData)); + + // offset: 0; size: 2; rt + //->ignore + $rt = self::getInt2d($recordData, 0); + // offset: 2; size: 2; grbitfr + //->ignore + $grbitFrt = self::getInt2d($recordData, 2); + // offset: 4; size: 8; reserved + //->ignore + + // offset: 12; size 2; zoom scale + $wScalePLV = self::getInt2d($recordData, 12); + // offset: 14; size 2; grbit + $grbit = self::getInt2d($recordData, 14); + + // decomprise grbit + $fPageLayoutView = $grbit & 0x01; + $fRulerVisible = ($grbit >> 1) & 0x01; //no support + $fWhitespaceHidden = ($grbit >> 3) & 0x01; //no support + + if ($fPageLayoutView === 1) { + $this->phpSheet->getSheetView()->setView(PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT); + $this->phpSheet->getSheetView()->setZoomScale($wScalePLV); //set by Excel2007 only if SHEETVIEW_PAGE_LAYOUT + } + //otherwise, we cannot know whether SHEETVIEW_PAGE_LAYOUT or SHEETVIEW_PAGE_BREAK_PREVIEW. + } + + /** + * Read SCL record + */ + private function readScl() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // offset: 0; size: 2; numerator of the view magnification + $numerator = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; numerator of the view magnification + $denumerator = self::getInt2d($recordData, 2); + + // set the zoom scale (in percent) + $this->phpSheet->getSheetView()->setZoomScale($numerator * 100 / $denumerator); + } + + + /** + * Read PANE record + */ + private function readPane() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; position of vertical split + $px = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; position of horizontal split + $py = self::getInt2d($recordData, 2); + + if ($this->frozen) { + // frozen panes + $this->phpSheet->freezePane(PHPExcel_Cell::stringFromColumnIndex($px) . ($py + 1)); + } else { + // unfrozen panes; split windows; not supported by PHPExcel core + } + } + } + + + /** + * Read SELECTION record. There is one such record for each pane in the sheet. + */ + private function readSelection() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 1; pane identifier + $paneId = ord($recordData{0}); + + // offset: 1; size: 2; index to row of the active cell + $r = self::getInt2d($recordData, 1); + + // offset: 3; size: 2; index to column of the active cell + $c = self::getInt2d($recordData, 3); + + // offset: 5; size: 2; index into the following cell range list to the + // entry that contains the active cell + $index = self::getInt2d($recordData, 5); + + // offset: 7; size: var; cell range address list containing all selected cell ranges + $data = substr($recordData, 7); + $cellRangeAddressList = $this->readBIFF5CellRangeAddressList($data); // note: also BIFF8 uses BIFF5 syntax + + $selectedCells = $cellRangeAddressList['cellRangeAddresses'][0]; + + // first row '1' + last row '16384' indicates that full column is selected (apparently also in BIFF8!) + if (preg_match('/^([A-Z]+1\:[A-Z]+)16384$/', $selectedCells)) { + $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)16384$/', '${1}1048576', $selectedCells); + } + + // first row '1' + last row '65536' indicates that full column is selected + if (preg_match('/^([A-Z]+1\:[A-Z]+)65536$/', $selectedCells)) { + $selectedCells = preg_replace('/^([A-Z]+1\:[A-Z]+)65536$/', '${1}1048576', $selectedCells); + } + + // first column 'A' + last column 'IV' indicates that full row is selected + if (preg_match('/^(A[0-9]+\:)IV([0-9]+)$/', $selectedCells)) { + $selectedCells = preg_replace('/^(A[0-9]+\:)IV([0-9]+)$/', '${1}XFD${2}', $selectedCells); + } + + $this->phpSheet->setSelectedCells($selectedCells); + } + } + + + private function includeCellRangeFiltered($cellRangeAddress) + { + $includeCellRange = true; + if ($this->getReadFilter() !== null) { + $includeCellRange = false; + $rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($cellRangeAddress); + $rangeBoundaries[1][0]++; + for ($row = $rangeBoundaries[0][1]; $row <= $rangeBoundaries[1][1]; $row++) { + for ($column = $rangeBoundaries[0][0]; $column != $rangeBoundaries[1][0]; $column++) { + if ($this->getReadFilter()->readCell($column, $row, $this->phpSheet->getTitle())) { + $includeCellRange = true; + break 2; + } + } + } + } + return $includeCellRange; + } + + + /** + * MERGEDCELLS + * + * This record contains the addresses of merged cell ranges + * in the current sheet. + * + * -- "OpenOffice.org's Documentation of the Microsoft + * Excel File Format" + */ + private function readMergedCells() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->version == self::XLS_BIFF8 && !$this->readDataOnly) { + $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($recordData); + foreach ($cellRangeAddressList['cellRangeAddresses'] as $cellRangeAddress) { + if ((strpos($cellRangeAddress, ':') !== false) && + ($this->includeCellRangeFiltered($cellRangeAddress))) { + $this->phpSheet->mergeCells($cellRangeAddress); + } + } + } + } + + + /** + * Read HYPERLINK record + */ + private function readHyperLink() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer forward to next record + $this->pos += 4 + $length; + + if (!$this->readDataOnly) { + // offset: 0; size: 8; cell range address of all cells containing this hyperlink + try { + $cellRange = $this->readBIFF8CellRangeAddressFixed($recordData, 0, 8); + } catch (PHPExcel_Exception $e) { + return; + } + + // offset: 8, size: 16; GUID of StdLink + + // offset: 24, size: 4; unknown value + + // offset: 28, size: 4; option flags + // bit: 0; mask: 0x00000001; 0 = no link or extant, 1 = file link or URL + $isFileLinkOrUrl = (0x00000001 & self::getInt2d($recordData, 28)) >> 0; + + // bit: 1; mask: 0x00000002; 0 = relative path, 1 = absolute path or URL + $isAbsPathOrUrl = (0x00000001 & self::getInt2d($recordData, 28)) >> 1; + + // bit: 2 (and 4); mask: 0x00000014; 0 = no description + $hasDesc = (0x00000014 & self::getInt2d($recordData, 28)) >> 2; + + // bit: 3; mask: 0x00000008; 0 = no text, 1 = has text + $hasText = (0x00000008 & self::getInt2d($recordData, 28)) >> 3; + + // bit: 7; mask: 0x00000080; 0 = no target frame, 1 = has target frame + $hasFrame = (0x00000080 & self::getInt2d($recordData, 28)) >> 7; + + // bit: 8; mask: 0x00000100; 0 = file link or URL, 1 = UNC path (inc. server name) + $isUNC = (0x00000100 & self::getInt2d($recordData, 28)) >> 8; + + // offset within record data + $offset = 32; + + if ($hasDesc) { + // offset: 32; size: var; character count of description text + $dl = self::getInt4d($recordData, 32); + // offset: 36; size: var; character array of description text, no Unicode string header, always 16-bit characters, zero terminated + $desc = self::encodeUTF16(substr($recordData, 36, 2 * ($dl - 1)), false); + $offset += 4 + 2 * $dl; + } + if ($hasFrame) { + $fl = self::getInt4d($recordData, $offset); + $offset += 4 + 2 * $fl; + } + + // detect type of hyperlink (there are 4 types) + $hyperlinkType = null; + + if ($isUNC) { + $hyperlinkType = 'UNC'; + } elseif (!$isFileLinkOrUrl) { + $hyperlinkType = 'workbook'; + } elseif (ord($recordData{$offset}) == 0x03) { + $hyperlinkType = 'local'; + } elseif (ord($recordData{$offset}) == 0xE0) { + $hyperlinkType = 'URL'; + } + + switch ($hyperlinkType) { + case 'URL': + // section 5.58.2: Hyperlink containing a URL + // e.g. http://example.org/index.php + + // offset: var; size: 16; GUID of URL Moniker + $offset += 16; + // offset: var; size: 4; size (in bytes) of character array of the URL including trailing zero word + $us = self::getInt4d($recordData, $offset); + $offset += 4; + // offset: var; size: $us; character array of the URL, no Unicode string header, always 16-bit characters, zero-terminated + $url = self::encodeUTF16(substr($recordData, $offset, $us - 2), false); + $nullOffset = strpos($url, 0x00); + if ($nullOffset) { + $url = substr($url, 0, $nullOffset); + } + $url .= $hasText ? '#' : ''; + $offset += $us; + break; + case 'local': + // section 5.58.3: Hyperlink to local file + // examples: + // mydoc.txt + // ../../somedoc.xls#Sheet!A1 + + // offset: var; size: 16; GUI of File Moniker + $offset += 16; + + // offset: var; size: 2; directory up-level count. + $upLevelCount = self::getInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 4; character count of the shortened file path and name, including trailing zero word + $sl = self::getInt4d($recordData, $offset); + $offset += 4; + + // offset: var; size: sl; character array of the shortened file path and name in 8.3-DOS-format (compressed Unicode string) + $shortenedFilePath = substr($recordData, $offset, $sl); + $shortenedFilePath = self::encodeUTF16($shortenedFilePath, true); + $shortenedFilePath = substr($shortenedFilePath, 0, -1); // remove trailing zero + + $offset += $sl; + + // offset: var; size: 24; unknown sequence + $offset += 24; + + // extended file path + // offset: var; size: 4; size of the following file link field including string lenth mark + $sz = self::getInt4d($recordData, $offset); + $offset += 4; + + // only present if $sz > 0 + if ($sz > 0) { + // offset: var; size: 4; size of the character array of the extended file path and name + $xl = self::getInt4d($recordData, $offset); + $offset += 4; + + // offset: var; size 2; unknown + $offset += 2; + + // offset: var; size $xl; character array of the extended file path and name. + $extendedFilePath = substr($recordData, $offset, $xl); + $extendedFilePath = self::encodeUTF16($extendedFilePath, false); + $offset += $xl; + } + + // construct the path + $url = str_repeat('..\\', $upLevelCount); + $url .= ($sz > 0) ? $extendedFilePath : $shortenedFilePath; // use extended path if available + $url .= $hasText ? '#' : ''; + + break; + case 'UNC': + // section 5.58.4: Hyperlink to a File with UNC (Universal Naming Convention) Path + // todo: implement + return; + case 'workbook': + // section 5.58.5: Hyperlink to the Current Workbook + // e.g. Sheet2!B1:C2, stored in text mark field + $url = 'sheet://'; + break; + default: + return; + } + + if ($hasText) { + // offset: var; size: 4; character count of text mark including trailing zero word + $tl = self::getInt4d($recordData, $offset); + $offset += 4; + // offset: var; size: var; character array of the text mark without the # sign, no Unicode header, always 16-bit characters, zero-terminated + $text = self::encodeUTF16(substr($recordData, $offset, 2 * ($tl - 1)), false); + $url .= $text; + } + + // apply the hyperlink to all the relevant cells + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cellRange) as $coordinate) { + $this->phpSheet->getCell($coordinate)->getHyperLink()->setUrl($url); + } + } + } + + + /** + * Read DATAVALIDATIONS record + */ + private function readDataValidations() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer forward to next record + $this->pos += 4 + $length; + } + + + /** + * Read DATAVALIDATION record + */ + private function readDataValidation() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer forward to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 4; Options + $options = self::getInt4d($recordData, 0); + + // bit: 0-3; mask: 0x0000000F; type + $type = (0x0000000F & $options) >> 0; + switch ($type) { + case 0x00: + $type = PHPExcel_Cell_DataValidation::TYPE_NONE; + break; + case 0x01: + $type = PHPExcel_Cell_DataValidation::TYPE_WHOLE; + break; + case 0x02: + $type = PHPExcel_Cell_DataValidation::TYPE_DECIMAL; + break; + case 0x03: + $type = PHPExcel_Cell_DataValidation::TYPE_LIST; + break; + case 0x04: + $type = PHPExcel_Cell_DataValidation::TYPE_DATE; + break; + case 0x05: + $type = PHPExcel_Cell_DataValidation::TYPE_TIME; + break; + case 0x06: + $type = PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH; + break; + case 0x07: + $type = PHPExcel_Cell_DataValidation::TYPE_CUSTOM; + break; + } + + // bit: 4-6; mask: 0x00000070; error type + $errorStyle = (0x00000070 & $options) >> 4; + switch ($errorStyle) { + case 0x00: + $errorStyle = PHPExcel_Cell_DataValidation::STYLE_STOP; + break; + case 0x01: + $errorStyle = PHPExcel_Cell_DataValidation::STYLE_WARNING; + break; + case 0x02: + $errorStyle = PHPExcel_Cell_DataValidation::STYLE_INFORMATION; + break; + } + + // bit: 7; mask: 0x00000080; 1= formula is explicit (only applies to list) + // I have only seen cases where this is 1 + $explicitFormula = (0x00000080 & $options) >> 7; + + // bit: 8; mask: 0x00000100; 1= empty cells allowed + $allowBlank = (0x00000100 & $options) >> 8; + + // bit: 9; mask: 0x00000200; 1= suppress drop down arrow in list type validity + $suppressDropDown = (0x00000200 & $options) >> 9; + + // bit: 18; mask: 0x00040000; 1= show prompt box if cell selected + $showInputMessage = (0x00040000 & $options) >> 18; + + // bit: 19; mask: 0x00080000; 1= show error box if invalid values entered + $showErrorMessage = (0x00080000 & $options) >> 19; + + // bit: 20-23; mask: 0x00F00000; condition operator + $operator = (0x00F00000 & $options) >> 20; + switch ($operator) { + case 0x00: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN; + break; + case 0x01: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN; + break; + case 0x02: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_EQUAL; + break; + case 0x03: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL; + break; + case 0x04: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN; + break; + case 0x05: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN; + break; + case 0x06: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL; + break; + case 0x07: + $operator = PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL; + break; + } + + // offset: 4; size: var; title of the prompt box + $offset = 4; + $string = self::readUnicodeStringLong(substr($recordData, $offset)); + $promptTitle = $string['value'] !== chr(0) ? $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; title of the error box + $string = self::readUnicodeStringLong(substr($recordData, $offset)); + $errorTitle = $string['value'] !== chr(0) ? $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; text of the prompt box + $string = self::readUnicodeStringLong(substr($recordData, $offset)); + $prompt = $string['value'] !== chr(0) ? $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: var; text of the error box + $string = self::readUnicodeStringLong(substr($recordData, $offset)); + $error = $string['value'] !== chr(0) ? $string['value'] : ''; + $offset += $string['size']; + + // offset: var; size: 2; size of the formula data for the first condition + $sz1 = self::getInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 2; not used + $offset += 2; + + // offset: var; size: $sz1; formula data for first condition (without size field) + $formula1 = substr($recordData, $offset, $sz1); + $formula1 = pack('v', $sz1) . $formula1; // prepend the length + try { + $formula1 = $this->getFormulaFromStructure($formula1); + + // in list type validity, null characters are used as item separators + if ($type == PHPExcel_Cell_DataValidation::TYPE_LIST) { + $formula1 = str_replace(chr(0), ',', $formula1); + } + } catch (PHPExcel_Exception $e) { + return; + } + $offset += $sz1; + + // offset: var; size: 2; size of the formula data for the first condition + $sz2 = self::getInt2d($recordData, $offset); + $offset += 2; + + // offset: var; size: 2; not used + $offset += 2; + + // offset: var; size: $sz2; formula data for second condition (without size field) + $formula2 = substr($recordData, $offset, $sz2); + $formula2 = pack('v', $sz2) . $formula2; // prepend the length + try { + $formula2 = $this->getFormulaFromStructure($formula2); + } catch (PHPExcel_Exception $e) { + return; + } + $offset += $sz2; + + // offset: var; size: var; cell range address list with + $cellRangeAddressList = $this->readBIFF8CellRangeAddressList(substr($recordData, $offset)); + $cellRangeAddresses = $cellRangeAddressList['cellRangeAddresses']; + + foreach ($cellRangeAddresses as $cellRange) { + $stRange = $this->phpSheet->shrinkRangeToFit($cellRange); + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($stRange) as $coordinate) { + $objValidation = $this->phpSheet->getCell($coordinate)->getDataValidation(); + $objValidation->setType($type); + $objValidation->setErrorStyle($errorStyle); + $objValidation->setAllowBlank((bool)$allowBlank); + $objValidation->setShowInputMessage((bool)$showInputMessage); + $objValidation->setShowErrorMessage((bool)$showErrorMessage); + $objValidation->setShowDropDown(!$suppressDropDown); + $objValidation->setOperator($operator); + $objValidation->setErrorTitle($errorTitle); + $objValidation->setError($error); + $objValidation->setPromptTitle($promptTitle); + $objValidation->setPrompt($prompt); + $objValidation->setFormula1($formula1); + $objValidation->setFormula2($formula2); + } + } + } + + /** + * Read SHEETLAYOUT record. Stores sheet tab color information. + */ + private function readSheetLayout() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // local pointer in record data + $offset = 0; + + if (!$this->readDataOnly) { + // offset: 0; size: 2; repeated record identifier 0x0862 + + // offset: 2; size: 10; not used + + // offset: 12; size: 4; size of record data + // Excel 2003 uses size of 0x14 (documented), Excel 2007 uses size of 0x28 (not documented?) + $sz = self::getInt4d($recordData, 12); + + switch ($sz) { + case 0x14: + // offset: 16; size: 2; color index for sheet tab + $colorIndex = self::getInt2d($recordData, 16); + $color = PHPExcel_Reader_Excel5_Color::map($colorIndex, $this->palette, $this->version); + $this->phpSheet->getTabColor()->setRGB($color['rgb']); + break; + case 0x28: + // TODO: Investigate structure for .xls SHEETLAYOUT record as saved by MS Office Excel 2007 + return; + break; + } + } + } + + + /** + * Read SHEETPROTECTION record (FEATHEADR) + */ + private function readSheetProtection() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + if ($this->readDataOnly) { + return; + } + + // offset: 0; size: 2; repeated record header + + // offset: 2; size: 2; FRT cell reference flag (=0 currently) + + // offset: 4; size: 8; Currently not used and set to 0 + + // offset: 12; size: 2; Shared feature type index (2=Enhanced Protetion, 4=SmartTag) + $isf = self::getInt2d($recordData, 12); + if ($isf != 2) { + return; + } + + // offset: 14; size: 1; =1 since this is a feat header + + // offset: 15; size: 4; size of rgbHdrSData + + // rgbHdrSData, assume "Enhanced Protection" + // offset: 19; size: 2; option flags + $options = self::getInt2d($recordData, 19); + + // bit: 0; mask 0x0001; 1 = user may edit objects, 0 = users must not edit objects + $bool = (0x0001 & $options) >> 0; + $this->phpSheet->getProtection()->setObjects(!$bool); + + // bit: 1; mask 0x0002; edit scenarios + $bool = (0x0002 & $options) >> 1; + $this->phpSheet->getProtection()->setScenarios(!$bool); + + // bit: 2; mask 0x0004; format cells + $bool = (0x0004 & $options) >> 2; + $this->phpSheet->getProtection()->setFormatCells(!$bool); + + // bit: 3; mask 0x0008; format columns + $bool = (0x0008 & $options) >> 3; + $this->phpSheet->getProtection()->setFormatColumns(!$bool); + + // bit: 4; mask 0x0010; format rows + $bool = (0x0010 & $options) >> 4; + $this->phpSheet->getProtection()->setFormatRows(!$bool); + + // bit: 5; mask 0x0020; insert columns + $bool = (0x0020 & $options) >> 5; + $this->phpSheet->getProtection()->setInsertColumns(!$bool); + + // bit: 6; mask 0x0040; insert rows + $bool = (0x0040 & $options) >> 6; + $this->phpSheet->getProtection()->setInsertRows(!$bool); + + // bit: 7; mask 0x0080; insert hyperlinks + $bool = (0x0080 & $options) >> 7; + $this->phpSheet->getProtection()->setInsertHyperlinks(!$bool); + + // bit: 8; mask 0x0100; delete columns + $bool = (0x0100 & $options) >> 8; + $this->phpSheet->getProtection()->setDeleteColumns(!$bool); + + // bit: 9; mask 0x0200; delete rows + $bool = (0x0200 & $options) >> 9; + $this->phpSheet->getProtection()->setDeleteRows(!$bool); + + // bit: 10; mask 0x0400; select locked cells + $bool = (0x0400 & $options) >> 10; + $this->phpSheet->getProtection()->setSelectLockedCells(!$bool); + + // bit: 11; mask 0x0800; sort cell range + $bool = (0x0800 & $options) >> 11; + $this->phpSheet->getProtection()->setSort(!$bool); + + // bit: 12; mask 0x1000; auto filter + $bool = (0x1000 & $options) >> 12; + $this->phpSheet->getProtection()->setAutoFilter(!$bool); + + // bit: 13; mask 0x2000; pivot tables + $bool = (0x2000 & $options) >> 13; + $this->phpSheet->getProtection()->setPivotTables(!$bool); + + // bit: 14; mask 0x4000; select unlocked cells + $bool = (0x4000 & $options) >> 14; + $this->phpSheet->getProtection()->setSelectUnlockedCells(!$bool); + + // offset: 21; size: 2; not used + } + + + /** + * Read RANGEPROTECTION record + * Reading of this record is based on Microsoft Office Excel 97-2000 Binary File Format Specification, + * where it is referred to as FEAT record + */ + private function readRangeProtection() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // move stream pointer to next record + $this->pos += 4 + $length; + + // local pointer in record data + $offset = 0; + + if (!$this->readDataOnly) { + $offset += 12; + + // offset: 12; size: 2; shared feature type, 2 = enhanced protection, 4 = smart tag + $isf = self::getInt2d($recordData, 12); + if ($isf != 2) { + // we only read FEAT records of type 2 + return; + } + $offset += 2; + + $offset += 5; + + // offset: 19; size: 2; count of ref ranges this feature is on + $cref = self::getInt2d($recordData, 19); + $offset += 2; + + $offset += 6; + + // offset: 27; size: 8 * $cref; list of cell ranges (like in hyperlink record) + $cellRanges = array(); + for ($i = 0; $i < $cref; ++$i) { + try { + $cellRange = $this->readBIFF8CellRangeAddressFixed(substr($recordData, 27 + 8 * $i, 8)); + } catch (PHPExcel_Exception $e) { + return; + } + $cellRanges[] = $cellRange; + $offset += 8; + } + + // offset: var; size: var; variable length of feature specific data + $rgbFeat = substr($recordData, $offset); + $offset += 4; + + // offset: var; size: 4; the encrypted password (only 16-bit although field is 32-bit) + $wPassword = self::getInt4d($recordData, $offset); + $offset += 4; + + // Apply range protection to sheet + if ($cellRanges) { + $this->phpSheet->protectCells(implode(' ', $cellRanges), strtoupper(dechex($wPassword)), true); + } + } + } + + + /** + * Read IMDATA record + */ + private function readImData() + { + $length = self::getInt2d($this->data, $this->pos + 2); + + // get spliced record data + $splicedRecordData = $this->getSplicedRecordData(); + $recordData = $splicedRecordData['recordData']; + + // UNDER CONSTRUCTION + + // offset: 0; size: 2; image format + $cf = self::getInt2d($recordData, 0); + + // offset: 2; size: 2; environment from which the file was written + $env = self::getInt2d($recordData, 2); + + // offset: 4; size: 4; length of the image data + $lcb = self::getInt4d($recordData, 4); + + // offset: 8; size: var; image data + $iData = substr($recordData, 8); + + switch ($cf) { + case 0x09: // Windows bitmap format + // BITMAPCOREINFO + // 1. BITMAPCOREHEADER + // offset: 0; size: 4; bcSize, Specifies the number of bytes required by the structure + $bcSize = self::getInt4d($iData, 0); + // var_dump($bcSize); + + // offset: 4; size: 2; bcWidth, specifies the width of the bitmap, in pixels + $bcWidth = self::getInt2d($iData, 4); + // var_dump($bcWidth); + + // offset: 6; size: 2; bcHeight, specifies the height of the bitmap, in pixels. + $bcHeight = self::getInt2d($iData, 6); + // var_dump($bcHeight); + $ih = imagecreatetruecolor($bcWidth, $bcHeight); + + // offset: 8; size: 2; bcPlanes, specifies the number of planes for the target device. This value must be 1 + + // offset: 10; size: 2; bcBitCount specifies the number of bits-per-pixel. This value must be 1, 4, 8, or 24 + $bcBitCount = self::getInt2d($iData, 10); + // var_dump($bcBitCount); + + $rgbString = substr($iData, 12); + $rgbTriples = array(); + while (strlen($rgbString) > 0) { + $rgbTriples[] = unpack('Cb/Cg/Cr', $rgbString); + $rgbString = substr($rgbString, 3); + } + $x = 0; + $y = 0; + foreach ($rgbTriples as $i => $rgbTriple) { + $color = imagecolorallocate($ih, $rgbTriple['r'], $rgbTriple['g'], $rgbTriple['b']); + imagesetpixel($ih, $x, $bcHeight - 1 - $y, $color); + $x = ($x + 1) % $bcWidth; + $y = $y + floor(($x + 1) / $bcWidth); + } + //imagepng($ih, 'image.png'); + + $drawing = new PHPExcel_Worksheet_Drawing(); + $drawing->setPath($filename); + $drawing->setWorksheet($this->phpSheet); + break; + case 0x02: // Windows metafile or Macintosh PICT format + case 0x0e: // native format + default: + break; + } + + // getSplicedRecordData() takes care of moving current position in data stream + } + + + /** + * Read a free CONTINUE record. Free CONTINUE record may be a camouflaged MSODRAWING record + * When MSODRAWING data on a sheet exceeds 8224 bytes, CONTINUE records are used instead. Undocumented. + * In this case, we must treat the CONTINUE record as a MSODRAWING record + */ + private function readContinue() + { + $length = self::getInt2d($this->data, $this->pos + 2); + $recordData = $this->readRecordData($this->data, $this->pos + 4, $length); + + // check if we are reading drawing data + // this is in case a free CONTINUE record occurs in other circumstances we are unaware of + if ($this->drawingData == '') { + // move stream pointer to next record + $this->pos += 4 + $length; + + return; + } + + // check if record data is at least 4 bytes long, otherwise there is no chance this is MSODRAWING data + if ($length < 4) { + // move stream pointer to next record + $this->pos += 4 + $length; + + return; + } + + // dirty check to see if CONTINUE record could be a camouflaged MSODRAWING record + // look inside CONTINUE record to see if it looks like a part of an Escher stream + // we know that Escher stream may be split at least at + // 0xF003 MsofbtSpgrContainer + // 0xF004 MsofbtSpContainer + // 0xF00D MsofbtClientTextbox + $validSplitPoints = array(0xF003, 0xF004, 0xF00D); // add identifiers if we find more + + $splitPoint = self::getInt2d($recordData, 2); + if (in_array($splitPoint, $validSplitPoints)) { + // get spliced record data (and move pointer to next record) + $splicedRecordData = $this->getSplicedRecordData(); + $this->drawingData .= $splicedRecordData['recordData']; + + return; + } + + // move stream pointer to next record + $this->pos += 4 + $length; + } + + + /** + * Reads a record from current position in data stream and continues reading data as long as CONTINUE + * records are found. Splices the record data pieces and returns the combined string as if record data + * is in one piece. + * Moves to next current position in data stream to start of next record different from a CONtINUE record + * + * @return array + */ + private function getSplicedRecordData() + { + $data = ''; + $spliceOffsets = array(); + + $i = 0; + $spliceOffsets[0] = 0; + + do { + ++$i; + + // offset: 0; size: 2; identifier + $identifier = self::getInt2d($this->data, $this->pos); + // offset: 2; size: 2; length + $length = self::getInt2d($this->data, $this->pos + 2); + $data .= $this->readRecordData($this->data, $this->pos + 4, $length); + + $spliceOffsets[$i] = $spliceOffsets[$i - 1] + $length; + + $this->pos += 4 + $length; + $nextIdentifier = self::getInt2d($this->data, $this->pos); + } while ($nextIdentifier == self::XLS_TYPE_CONTINUE); + + $splicedData = array( + 'recordData' => $data, + 'spliceOffsets' => $spliceOffsets, + ); + + return $splicedData; + + } + + + /** + * Convert formula structure into human readable Excel formula like 'A3+A5*5' + * + * @param string $formulaStructure The complete binary data for the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function getFormulaFromStructure($formulaStructure, $baseCell = 'A1') + { + // offset: 0; size: 2; size of the following formula data + $sz = self::getInt2d($formulaStructure, 0); + + // offset: 2; size: sz + $formulaData = substr($formulaStructure, 2, $sz); + + // for debug: dump the formula data + //echo '<xmp>'; + //echo 'size: ' . $sz . "\n"; + //echo 'the entire formula data: '; + //Debug::dump($formulaData); + //echo "\n----\n"; + + // offset: 2 + sz; size: variable (optional) + if (strlen($formulaStructure) > 2 + $sz) { + $additionalData = substr($formulaStructure, 2 + $sz); + + // for debug: dump the additional data + //echo 'the entire additional data: '; + //Debug::dump($additionalData); + //echo "\n----\n"; + } else { + $additionalData = ''; + } + + return $this->getFormulaFromData($formulaData, $additionalData, $baseCell); + } + + + /** + * Take formula data and additional data for formula and return human readable formula + * + * @param string $formulaData The binary data for the formula itself + * @param string $additionalData Additional binary data going with the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function getFormulaFromData($formulaData, $additionalData = '', $baseCell = 'A1') + { + // start parsing the formula data + $tokens = array(); + + while (strlen($formulaData) > 0 and $token = $this->getNextToken($formulaData, $baseCell)) { + $tokens[] = $token; + $formulaData = substr($formulaData, $token['size']); + + // for debug: dump the token + //var_dump($token); + } + + $formulaString = $this->createFormulaFromTokens($tokens, $additionalData); + + return $formulaString; + } + + + /** + * Take array of tokens together with additional data for formula and return human readable formula + * + * @param array $tokens + * @param array $additionalData Additional binary data going with the formula + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string Human readable formula + */ + private function createFormulaFromTokens($tokens, $additionalData) + { + // empty formula? + if (empty($tokens)) { + return ''; + } + + $formulaStrings = array(); + foreach ($tokens as $token) { + // initialize spaces + $space0 = isset($space0) ? $space0 : ''; // spaces before next token, not tParen + $space1 = isset($space1) ? $space1 : ''; // carriage returns before next token, not tParen + $space2 = isset($space2) ? $space2 : ''; // spaces before opening parenthesis + $space3 = isset($space3) ? $space3 : ''; // carriage returns before opening parenthesis + $space4 = isset($space4) ? $space4 : ''; // spaces before closing parenthesis + $space5 = isset($space5) ? $space5 : ''; // carriage returns before closing parenthesis + + switch ($token['name']) { + case 'tAdd': // addition + case 'tConcat': // addition + case 'tDiv': // division + case 'tEQ': // equality + case 'tGE': // greater than or equal + case 'tGT': // greater than + case 'tIsect': // intersection + case 'tLE': // less than or equal + case 'tList': // less than or equal + case 'tLT': // less than + case 'tMul': // multiplication + case 'tNE': // multiplication + case 'tPower': // power + case 'tRange': // range + case 'tSub': // subtraction + $op2 = array_pop($formulaStrings); + $op1 = array_pop($formulaStrings); + $formulaStrings[] = "$op1$space1$space0{$token['data']}$op2"; + unset($space0, $space1); + break; + case 'tUplus': // unary plus + case 'tUminus': // unary minus + $op = array_pop($formulaStrings); + $formulaStrings[] = "$space1$space0{$token['data']}$op"; + unset($space0, $space1); + break; + case 'tPercent': // percent sign + $op = array_pop($formulaStrings); + $formulaStrings[] = "$op$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + case 'tAttrVolatile': // indicates volatile function + case 'tAttrIf': + case 'tAttrSkip': + case 'tAttrChoose': + // token is only important for Excel formula evaluator + // do nothing + break; + case 'tAttrSpace': // space / carriage return + // space will be used when next token arrives, do not alter formulaString stack + switch ($token['data']['spacetype']) { + case 'type0': + $space0 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type1': + $space1 = str_repeat("\n", $token['data']['spacecount']); + break; + case 'type2': + $space2 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type3': + $space3 = str_repeat("\n", $token['data']['spacecount']); + break; + case 'type4': + $space4 = str_repeat(' ', $token['data']['spacecount']); + break; + case 'type5': + $space5 = str_repeat("\n", $token['data']['spacecount']); + break; + } + break; + case 'tAttrSum': // SUM function with one parameter + $op = array_pop($formulaStrings); + $formulaStrings[] = "{$space1}{$space0}SUM($op)"; + unset($space0, $space1); + break; + case 'tFunc': // function with fixed number of arguments + case 'tFuncV': // function with variable number of arguments + if ($token['data']['function'] != '') { + // normal function + $ops = array(); // array of operators + for ($i = 0; $i < $token['data']['args']; ++$i) { + $ops[] = array_pop($formulaStrings); + } + $ops = array_reverse($ops); + $formulaStrings[] = "$space1$space0{$token['data']['function']}(" . implode(',', $ops) . ")"; + unset($space0, $space1); + } else { + // add-in function + $ops = array(); // array of operators + for ($i = 0; $i < $token['data']['args'] - 1; ++$i) { + $ops[] = array_pop($formulaStrings); + } + $ops = array_reverse($ops); + $function = array_pop($formulaStrings); + $formulaStrings[] = "$space1$space0$function(" . implode(',', $ops) . ")"; + unset($space0, $space1); + } + break; + case 'tParen': // parenthesis + $expression = array_pop($formulaStrings); + $formulaStrings[] = "$space3$space2($expression$space5$space4)"; + unset($space2, $space3, $space4, $space5); + break; + case 'tArray': // array constant + $constantArray = self::readBIFF8ConstantArray($additionalData); + $formulaStrings[] = $space1 . $space0 . $constantArray['value']; + $additionalData = substr($additionalData, $constantArray['size']); // bite of chunk of additional data + unset($space0, $space1); + break; + case 'tMemArea': + // bite off chunk of additional data + $cellRangeAddressList = $this->readBIFF8CellRangeAddressList($additionalData); + $additionalData = substr($additionalData, $cellRangeAddressList['size']); + $formulaStrings[] = "$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + case 'tArea': // cell range address + case 'tBool': // boolean + case 'tErr': // error code + case 'tInt': // integer + case 'tMemErr': + case 'tMemFunc': + case 'tMissArg': + case 'tName': + case 'tNameX': + case 'tNum': // number + case 'tRef': // single cell reference + case 'tRef3d': // 3d cell reference + case 'tArea3d': // 3d cell range reference + case 'tRefN': + case 'tAreaN': + case 'tStr': // string + $formulaStrings[] = "$space1$space0{$token['data']}"; + unset($space0, $space1); + break; + } + } + $formulaString = $formulaStrings[0]; + + // for debug: dump the human readable formula + //echo '----' . "\n"; + //echo 'Formula: ' . $formulaString; + + return $formulaString; + } + + + /** + * Fetch next token from binary formula data + * + * @param string Formula data + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return array + * @throws PHPExcel_Reader_Exception + */ + private function getNextToken($formulaData, $baseCell = 'A1') + { + // offset: 0; size: 1; token id + $id = ord($formulaData[0]); // token id + $name = false; // initialize token name + + switch ($id) { + case 0x03: + $name = 'tAdd'; + $size = 1; + $data = '+'; + break; + case 0x04: + $name = 'tSub'; + $size = 1; + $data = '-'; + break; + case 0x05: + $name = 'tMul'; + $size = 1; + $data = '*'; + break; + case 0x06: + $name = 'tDiv'; + $size = 1; + $data = '/'; + break; + case 0x07: + $name = 'tPower'; + $size = 1; + $data = '^'; + break; + case 0x08: + $name = 'tConcat'; + $size = 1; + $data = '&'; + break; + case 0x09: + $name = 'tLT'; + $size = 1; + $data = '<'; + break; + case 0x0A: + $name = 'tLE'; + $size = 1; + $data = '<='; + break; + case 0x0B: + $name = 'tEQ'; + $size = 1; + $data = '='; + break; + case 0x0C: + $name = 'tGE'; + $size = 1; + $data = '>='; + break; + case 0x0D: + $name = 'tGT'; + $size = 1; + $data = '>'; + break; + case 0x0E: + $name = 'tNE'; + $size = 1; + $data = '<>'; + break; + case 0x0F: + $name = 'tIsect'; + $size = 1; + $data = ' '; + break; + case 0x10: + $name = 'tList'; + $size = 1; + $data = ','; + break; + case 0x11: + $name = 'tRange'; + $size = 1; + $data = ':'; + break; + case 0x12: + $name = 'tUplus'; + $size = 1; + $data = '+'; + break; + case 0x13: + $name = 'tUminus'; + $size = 1; + $data = '-'; + break; + case 0x14: + $name = 'tPercent'; + $size = 1; + $data = '%'; + break; + case 0x15: // parenthesis + $name = 'tParen'; + $size = 1; + $data = null; + break; + case 0x16: // missing argument + $name = 'tMissArg'; + $size = 1; + $data = ''; + break; + case 0x17: // string + $name = 'tStr'; + // offset: 1; size: var; Unicode string, 8-bit string length + $string = self::readUnicodeStringShort(substr($formulaData, 1)); + $size = 1 + $string['size']; + $data = self::UTF8toExcelDoubleQuoted($string['value']); + break; + case 0x19: // Special attribute + // offset: 1; size: 1; attribute type flags: + switch (ord($formulaData[1])) { + case 0x01: + $name = 'tAttrVolatile'; + $size = 4; + $data = null; + break; + case 0x02: + $name = 'tAttrIf'; + $size = 4; + $data = null; + break; + case 0x04: + $name = 'tAttrChoose'; + // offset: 2; size: 2; number of choices in the CHOOSE function ($nc, number of parameters decreased by 1) + $nc = self::getInt2d($formulaData, 2); + // offset: 4; size: 2 * $nc + // offset: 4 + 2 * $nc; size: 2 + $size = 2 * $nc + 6; + $data = null; + break; + case 0x08: + $name = 'tAttrSkip'; + $size = 4; + $data = null; + break; + case 0x10: + $name = 'tAttrSum'; + $size = 4; + $data = null; + break; + case 0x40: + case 0x41: + $name = 'tAttrSpace'; + $size = 4; + // offset: 2; size: 2; space type and position + switch (ord($formulaData[2])) { + case 0x00: + $spacetype = 'type0'; + break; + case 0x01: + $spacetype = 'type1'; + break; + case 0x02: + $spacetype = 'type2'; + break; + case 0x03: + $spacetype = 'type3'; + break; + case 0x04: + $spacetype = 'type4'; + break; + case 0x05: + $spacetype = 'type5'; + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized space type in tAttrSpace token'); + break; + } + // offset: 3; size: 1; number of inserted spaces/carriage returns + $spacecount = ord($formulaData[3]); + + $data = array('spacetype' => $spacetype, 'spacecount' => $spacecount); + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized attribute flag in tAttr token'); + break; + } + break; + case 0x1C: // error code + // offset: 1; size: 1; error code + $name = 'tErr'; + $size = 2; + $data = PHPExcel_Reader_Excel5_ErrorCode::lookup(ord($formulaData[1])); + break; + case 0x1D: // boolean + // offset: 1; size: 1; 0 = false, 1 = true; + $name = 'tBool'; + $size = 2; + $data = ord($formulaData[1]) ? 'TRUE' : 'FALSE'; + break; + case 0x1E: // integer + // offset: 1; size: 2; unsigned 16-bit integer + $name = 'tInt'; + $size = 3; + $data = self::getInt2d($formulaData, 1); + break; + case 0x1F: // number + // offset: 1; size: 8; + $name = 'tNum'; + $size = 9; + $data = self::extractNumber(substr($formulaData, 1)); + $data = str_replace(',', '.', (string)$data); // in case non-English locale + break; + case 0x20: // array constant + case 0x40: + case 0x60: + // offset: 1; size: 7; not used + $name = 'tArray'; + $size = 8; + $data = null; + break; + case 0x21: // function with fixed number of arguments + case 0x41: + case 0x61: + $name = 'tFunc'; + $size = 3; + // offset: 1; size: 2; index to built-in sheet function + switch (self::getInt2d($formulaData, 1)) { + case 2: + $function = 'ISNA'; + $args = 1; + break; + case 3: + $function = 'ISERROR'; + $args = 1; + break; + case 10: + $function = 'NA'; + $args = 0; + break; + case 15: + $function = 'SIN'; + $args = 1; + break; + case 16: + $function = 'COS'; + $args = 1; + break; + case 17: + $function = 'TAN'; + $args = 1; + break; + case 18: + $function = 'ATAN'; + $args = 1; + break; + case 19: + $function = 'PI'; + $args = 0; + break; + case 20: + $function = 'SQRT'; + $args = 1; + break; + case 21: + $function = 'EXP'; + $args = 1; + break; + case 22: + $function = 'LN'; + $args = 1; + break; + case 23: + $function = 'LOG10'; + $args = 1; + break; + case 24: + $function = 'ABS'; + $args = 1; + break; + case 25: + $function = 'INT'; + $args = 1; + break; + case 26: + $function = 'SIGN'; + $args = 1; + break; + case 27: + $function = 'ROUND'; + $args = 2; + break; + case 30: + $function = 'REPT'; + $args = 2; + break; + case 31: + $function = 'MID'; + $args = 3; + break; + case 32: + $function = 'LEN'; + $args = 1; + break; + case 33: + $function = 'VALUE'; + $args = 1; + break; + case 34: + $function = 'TRUE'; + $args = 0; + break; + case 35: + $function = 'FALSE'; + $args = 0; + break; + case 38: + $function = 'NOT'; + $args = 1; + break; + case 39: + $function = 'MOD'; + $args = 2; + break; + case 40: + $function = 'DCOUNT'; + $args = 3; + break; + case 41: + $function = 'DSUM'; + $args = 3; + break; + case 42: + $function = 'DAVERAGE'; + $args = 3; + break; + case 43: + $function = 'DMIN'; + $args = 3; + break; + case 44: + $function = 'DMAX'; + $args = 3; + break; + case 45: + $function = 'DSTDEV'; + $args = 3; + break; + case 48: + $function = 'TEXT'; + $args = 2; + break; + case 61: + $function = 'MIRR'; + $args = 3; + break; + case 63: + $function = 'RAND'; + $args = 0; + break; + case 65: + $function = 'DATE'; + $args = 3; + break; + case 66: + $function = 'TIME'; + $args = 3; + break; + case 67: + $function = 'DAY'; + $args = 1; + break; + case 68: + $function = 'MONTH'; + $args = 1; + break; + case 69: + $function = 'YEAR'; + $args = 1; + break; + case 71: + $function = 'HOUR'; + $args = 1; + break; + case 72: + $function = 'MINUTE'; + $args = 1; + break; + case 73: + $function = 'SECOND'; + $args = 1; + break; + case 74: + $function = 'NOW'; + $args = 0; + break; + case 75: + $function = 'AREAS'; + $args = 1; + break; + case 76: + $function = 'ROWS'; + $args = 1; + break; + case 77: + $function = 'COLUMNS'; + $args = 1; + break; + case 83: + $function = 'TRANSPOSE'; + $args = 1; + break; + case 86: + $function = 'TYPE'; + $args = 1; + break; + case 97: + $function = 'ATAN2'; + $args = 2; + break; + case 98: + $function = 'ASIN'; + $args = 1; + break; + case 99: + $function = 'ACOS'; + $args = 1; + break; + case 105: + $function = 'ISREF'; + $args = 1; + break; + case 111: + $function = 'CHAR'; + $args = 1; + break; + case 112: + $function = 'LOWER'; + $args = 1; + break; + case 113: + $function = 'UPPER'; + $args = 1; + break; + case 114: + $function = 'PROPER'; + $args = 1; + break; + case 117: + $function = 'EXACT'; + $args = 2; + break; + case 118: + $function = 'TRIM'; + $args = 1; + break; + case 119: + $function = 'REPLACE'; + $args = 4; + break; + case 121: + $function = 'CODE'; + $args = 1; + break; + case 126: + $function = 'ISERR'; + $args = 1; + break; + case 127: + $function = 'ISTEXT'; + $args = 1; + break; + case 128: + $function = 'ISNUMBER'; + $args = 1; + break; + case 129: + $function = 'ISBLANK'; + $args = 1; + break; + case 130: + $function = 'T'; + $args = 1; + break; + case 131: + $function = 'N'; + $args = 1; + break; + case 140: + $function = 'DATEVALUE'; + $args = 1; + break; + case 141: + $function = 'TIMEVALUE'; + $args = 1; + break; + case 142: + $function = 'SLN'; + $args = 3; + break; + case 143: + $function = 'SYD'; + $args = 4; + break; + case 162: + $function = 'CLEAN'; + $args = 1; + break; + case 163: + $function = 'MDETERM'; + $args = 1; + break; + case 164: + $function = 'MINVERSE'; + $args = 1; + break; + case 165: + $function = 'MMULT'; + $args = 2; + break; + case 184: + $function = 'FACT'; + $args = 1; + break; + case 189: + $function = 'DPRODUCT'; + $args = 3; + break; + case 190: + $function = 'ISNONTEXT'; + $args = 1; + break; + case 195: + $function = 'DSTDEVP'; + $args = 3; + break; + case 196: + $function = 'DVARP'; + $args = 3; + break; + case 198: + $function = 'ISLOGICAL'; + $args = 1; + break; + case 199: + $function = 'DCOUNTA'; + $args = 3; + break; + case 207: + $function = 'REPLACEB'; + $args = 4; + break; + case 210: + $function = 'MIDB'; + $args = 3; + break; + case 211: + $function = 'LENB'; + $args = 1; + break; + case 212: + $function = 'ROUNDUP'; + $args = 2; + break; + case 213: + $function = 'ROUNDDOWN'; + $args = 2; + break; + case 214: + $function = 'ASC'; + $args = 1; + break; + case 215: + $function = 'DBCS'; + $args = 1; + break; + case 221: + $function = 'TODAY'; + $args = 0; + break; + case 229: + $function = 'SINH'; + $args = 1; + break; + case 230: + $function = 'COSH'; + $args = 1; + break; + case 231: + $function = 'TANH'; + $args = 1; + break; + case 232: + $function = 'ASINH'; + $args = 1; + break; + case 233: + $function = 'ACOSH'; + $args = 1; + break; + case 234: + $function = 'ATANH'; + $args = 1; + break; + case 235: + $function = 'DGET'; + $args = 3; + break; + case 244: + $function = 'INFO'; + $args = 1; + break; + case 252: + $function = 'FREQUENCY'; + $args = 2; + break; + case 261: + $function = 'ERROR.TYPE'; + $args = 1; + break; + case 271: + $function = 'GAMMALN'; + $args = 1; + break; + case 273: + $function = 'BINOMDIST'; + $args = 4; + break; + case 274: + $function = 'CHIDIST'; + $args = 2; + break; + case 275: + $function = 'CHIINV'; + $args = 2; + break; + case 276: + $function = 'COMBIN'; + $args = 2; + break; + case 277: + $function = 'CONFIDENCE'; + $args = 3; + break; + case 278: + $function = 'CRITBINOM'; + $args = 3; + break; + case 279: + $function = 'EVEN'; + $args = 1; + break; + case 280: + $function = 'EXPONDIST'; + $args = 3; + break; + case 281: + $function = 'FDIST'; + $args = 3; + break; + case 282: + $function = 'FINV'; + $args = 3; + break; + case 283: + $function = 'FISHER'; + $args = 1; + break; + case 284: + $function = 'FISHERINV'; + $args = 1; + break; + case 285: + $function = 'FLOOR'; + $args = 2; + break; + case 286: + $function = 'GAMMADIST'; + $args = 4; + break; + case 287: + $function = 'GAMMAINV'; + $args = 3; + break; + case 288: + $function = 'CEILING'; + $args = 2; + break; + case 289: + $function = 'HYPGEOMDIST'; + $args = 4; + break; + case 290: + $function = 'LOGNORMDIST'; + $args = 3; + break; + case 291: + $function = 'LOGINV'; + $args = 3; + break; + case 292: + $function = 'NEGBINOMDIST'; + $args = 3; + break; + case 293: + $function = 'NORMDIST'; + $args = 4; + break; + case 294: + $function = 'NORMSDIST'; + $args = 1; + break; + case 295: + $function = 'NORMINV'; + $args = 3; + break; + case 296: + $function = 'NORMSINV'; + $args = 1; + break; + case 297: + $function = 'STANDARDIZE'; + $args = 3; + break; + case 298: + $function = 'ODD'; + $args = 1; + break; + case 299: + $function = 'PERMUT'; + $args = 2; + break; + case 300: + $function = 'POISSON'; + $args = 3; + break; + case 301: + $function = 'TDIST'; + $args = 3; + break; + case 302: + $function = 'WEIBULL'; + $args = 4; + break; + case 303: + $function = 'SUMXMY2'; + $args = 2; + break; + case 304: + $function = 'SUMX2MY2'; + $args = 2; + break; + case 305: + $function = 'SUMX2PY2'; + $args = 2; + break; + case 306: + $function = 'CHITEST'; + $args = 2; + break; + case 307: + $function = 'CORREL'; + $args = 2; + break; + case 308: + $function = 'COVAR'; + $args = 2; + break; + case 309: + $function = 'FORECAST'; + $args = 3; + break; + case 310: + $function = 'FTEST'; + $args = 2; + break; + case 311: + $function = 'INTERCEPT'; + $args = 2; + break; + case 312: + $function = 'PEARSON'; + $args = 2; + break; + case 313: + $function = 'RSQ'; + $args = 2; + break; + case 314: + $function = 'STEYX'; + $args = 2; + break; + case 315: + $function = 'SLOPE'; + $args = 2; + break; + case 316: + $function = 'TTEST'; + $args = 4; + break; + case 325: + $function = 'LARGE'; + $args = 2; + break; + case 326: + $function = 'SMALL'; + $args = 2; + break; + case 327: + $function = 'QUARTILE'; + $args = 2; + break; + case 328: + $function = 'PERCENTILE'; + $args = 2; + break; + case 331: + $function = 'TRIMMEAN'; + $args = 2; + break; + case 332: + $function = 'TINV'; + $args = 2; + break; + case 337: + $function = 'POWER'; + $args = 2; + break; + case 342: + $function = 'RADIANS'; + $args = 1; + break; + case 343: + $function = 'DEGREES'; + $args = 1; + break; + case 346: + $function = 'COUNTIF'; + $args = 2; + break; + case 347: + $function = 'COUNTBLANK'; + $args = 1; + break; + case 350: + $function = 'ISPMT'; + $args = 4; + break; + case 351: + $function = 'DATEDIF'; + $args = 3; + break; + case 352: + $function = 'DATESTRING'; + $args = 1; + break; + case 353: + $function = 'NUMBERSTRING'; + $args = 2; + break; + case 360: + $function = 'PHONETIC'; + $args = 1; + break; + case 368: + $function = 'BAHTTEXT'; + $args = 1; + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized function in formula'); + break; + } + $data = array('function' => $function, 'args' => $args); + break; + case 0x22: // function with variable number of arguments + case 0x42: + case 0x62: + $name = 'tFuncV'; + $size = 4; + // offset: 1; size: 1; number of arguments + $args = ord($formulaData[1]); + // offset: 2: size: 2; index to built-in sheet function + $index = self::getInt2d($formulaData, 2); + switch ($index) { + case 0: + $function = 'COUNT'; + break; + case 1: + $function = 'IF'; + break; + case 4: + $function = 'SUM'; + break; + case 5: + $function = 'AVERAGE'; + break; + case 6: + $function = 'MIN'; + break; + case 7: + $function = 'MAX'; + break; + case 8: + $function = 'ROW'; + break; + case 9: + $function = 'COLUMN'; + break; + case 11: + $function = 'NPV'; + break; + case 12: + $function = 'STDEV'; + break; + case 13: + $function = 'DOLLAR'; + break; + case 14: + $function = 'FIXED'; + break; + case 28: + $function = 'LOOKUP'; + break; + case 29: + $function = 'INDEX'; + break; + case 36: + $function = 'AND'; + break; + case 37: + $function = 'OR'; + break; + case 46: + $function = 'VAR'; + break; + case 49: + $function = 'LINEST'; + break; + case 50: + $function = 'TREND'; + break; + case 51: + $function = 'LOGEST'; + break; + case 52: + $function = 'GROWTH'; + break; + case 56: + $function = 'PV'; + break; + case 57: + $function = 'FV'; + break; + case 58: + $function = 'NPER'; + break; + case 59: + $function = 'PMT'; + break; + case 60: + $function = 'RATE'; + break; + case 62: + $function = 'IRR'; + break; + case 64: + $function = 'MATCH'; + break; + case 70: + $function = 'WEEKDAY'; + break; + case 78: + $function = 'OFFSET'; + break; + case 82: + $function = 'SEARCH'; + break; + case 100: + $function = 'CHOOSE'; + break; + case 101: + $function = 'HLOOKUP'; + break; + case 102: + $function = 'VLOOKUP'; + break; + case 109: + $function = 'LOG'; + break; + case 115: + $function = 'LEFT'; + break; + case 116: + $function = 'RIGHT'; + break; + case 120: + $function = 'SUBSTITUTE'; + break; + case 124: + $function = 'FIND'; + break; + case 125: + $function = 'CELL'; + break; + case 144: + $function = 'DDB'; + break; + case 148: + $function = 'INDIRECT'; + break; + case 167: + $function = 'IPMT'; + break; + case 168: + $function = 'PPMT'; + break; + case 169: + $function = 'COUNTA'; + break; + case 183: + $function = 'PRODUCT'; + break; + case 193: + $function = 'STDEVP'; + break; + case 194: + $function = 'VARP'; + break; + case 197: + $function = 'TRUNC'; + break; + case 204: + $function = 'USDOLLAR'; + break; + case 205: + $function = 'FINDB'; + break; + case 206: + $function = 'SEARCHB'; + break; + case 208: + $function = 'LEFTB'; + break; + case 209: + $function = 'RIGHTB'; + break; + case 216: + $function = 'RANK'; + break; + case 219: + $function = 'ADDRESS'; + break; + case 220: + $function = 'DAYS360'; + break; + case 222: + $function = 'VDB'; + break; + case 227: + $function = 'MEDIAN'; + break; + case 228: + $function = 'SUMPRODUCT'; + break; + case 247: + $function = 'DB'; + break; + case 255: + $function = ''; + break; + case 269: + $function = 'AVEDEV'; + break; + case 270: + $function = 'BETADIST'; + break; + case 272: + $function = 'BETAINV'; + break; + case 317: + $function = 'PROB'; + break; + case 318: + $function = 'DEVSQ'; + break; + case 319: + $function = 'GEOMEAN'; + break; + case 320: + $function = 'HARMEAN'; + break; + case 321: + $function = 'SUMSQ'; + break; + case 322: + $function = 'KURT'; + break; + case 323: + $function = 'SKEW'; + break; + case 324: + $function = 'ZTEST'; + break; + case 329: + $function = 'PERCENTRANK'; + break; + case 330: + $function = 'MODE'; + break; + case 336: + $function = 'CONCATENATE'; + break; + case 344: + $function = 'SUBTOTAL'; + break; + case 345: + $function = 'SUMIF'; + break; + case 354: + $function = 'ROMAN'; + break; + case 358: + $function = 'GETPIVOTDATA'; + break; + case 359: + $function = 'HYPERLINK'; + break; + case 361: + $function = 'AVERAGEA'; + break; + case 362: + $function = 'MAXA'; + break; + case 363: + $function = 'MINA'; + break; + case 364: + $function = 'STDEVPA'; + break; + case 365: + $function = 'VARPA'; + break; + case 366: + $function = 'STDEVA'; + break; + case 367: + $function = 'VARA'; + break; + default: + throw new PHPExcel_Reader_Exception('Unrecognized function in formula'); + break; + } + $data = array('function' => $function, 'args' => $args); + break; + case 0x23: // index to defined name + case 0x43: + case 0x63: + $name = 'tName'; + $size = 5; + // offset: 1; size: 2; one-based index to definedname record + $definedNameIndex = self::getInt2d($formulaData, 1) - 1; + // offset: 2; size: 2; not used + $data = $this->definedname[$definedNameIndex]['name']; + break; + case 0x24: // single cell reference e.g. A5 + case 0x44: + case 0x64: + $name = 'tRef'; + $size = 5; + $data = $this->readBIFF8CellAddress(substr($formulaData, 1, 4)); + break; + case 0x25: // cell range reference to cells in the same sheet (2d) + case 0x45: + case 0x65: + $name = 'tArea'; + $size = 9; + $data = $this->readBIFF8CellRangeAddress(substr($formulaData, 1, 8)); + break; + case 0x26: // Constant reference sub-expression + case 0x46: + case 0x66: + $name = 'tMemArea'; + // offset: 1; size: 4; not used + // offset: 5; size: 2; size of the following subexpression + $subSize = self::getInt2d($formulaData, 5); + $size = 7 + $subSize; + $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); + break; + case 0x27: // Deleted constant reference sub-expression + case 0x47: + case 0x67: + $name = 'tMemErr'; + // offset: 1; size: 4; not used + // offset: 5; size: 2; size of the following subexpression + $subSize = self::getInt2d($formulaData, 5); + $size = 7 + $subSize; + $data = $this->getFormulaFromData(substr($formulaData, 7, $subSize)); + break; + case 0x29: // Variable reference sub-expression + case 0x49: + case 0x69: + $name = 'tMemFunc'; + // offset: 1; size: 2; size of the following sub-expression + $subSize = self::getInt2d($formulaData, 1); + $size = 3 + $subSize; + $data = $this->getFormulaFromData(substr($formulaData, 3, $subSize)); + break; + case 0x2C: // Relative 2d cell reference reference, used in shared formulas and some other places + case 0x4C: + case 0x6C: + $name = 'tRefN'; + $size = 5; + $data = $this->readBIFF8CellAddressB(substr($formulaData, 1, 4), $baseCell); + break; + case 0x2D: // Relative 2d range reference + case 0x4D: + case 0x6D: + $name = 'tAreaN'; + $size = 9; + $data = $this->readBIFF8CellRangeAddressB(substr($formulaData, 1, 8), $baseCell); + break; + case 0x39: // External name + case 0x59: + case 0x79: + $name = 'tNameX'; + $size = 7; + // offset: 1; size: 2; index to REF entry in EXTERNSHEET record + // offset: 3; size: 2; one-based index to DEFINEDNAME or EXTERNNAME record + $index = self::getInt2d($formulaData, 3); + // assume index is to EXTERNNAME record + $data = $this->externalNames[$index - 1]['name']; + // offset: 5; size: 2; not used + break; + case 0x3A: // 3d reference to cell + case 0x5A: + case 0x7A: + $name = 'tRef3d'; + $size = 7; + + try { + // offset: 1; size: 2; index to REF entry + $sheetRange = $this->readSheetRangeByRefIndex(self::getInt2d($formulaData, 1)); + // offset: 3; size: 4; cell address + $cellAddress = $this->readBIFF8CellAddress(substr($formulaData, 3, 4)); + + $data = "$sheetRange!$cellAddress"; + } catch (PHPExcel_Exception $e) { + // deleted sheet reference + $data = '#REF!'; + } + break; + case 0x3B: // 3d reference to cell range + case 0x5B: + case 0x7B: + $name = 'tArea3d'; + $size = 11; + + try { + // offset: 1; size: 2; index to REF entry + $sheetRange = $this->readSheetRangeByRefIndex(self::getInt2d($formulaData, 1)); + // offset: 3; size: 8; cell address + $cellRangeAddress = $this->readBIFF8CellRangeAddress(substr($formulaData, 3, 8)); + + $data = "$sheetRange!$cellRangeAddress"; + } catch (PHPExcel_Exception $e) { + // deleted sheet reference + $data = '#REF!'; + } + break; + // Unknown cases // don't know how to deal with + default: + throw new PHPExcel_Reader_Exception('Unrecognized token ' . sprintf('%02X', $id) . ' in formula'); + break; + } + + return array( + 'id' => $id, + 'name' => $name, + 'size' => $size, + 'data' => $data, + ); + } + + + /** + * Reads a cell address in BIFF8 e.g. 'A2' or '$A$2' + * section 3.3.4 + * + * @param string $cellAddressStructure + * @return string + */ + private function readBIFF8CellAddress($cellAddressStructure) + { + // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) + $row = self::getInt2d($cellAddressStructure, 0) + 1; + + // offset: 2; size: 2; index to column or column offset + relative flags + // bit: 7-0; mask 0x00FF; column index + $column = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::getInt2d($cellAddressStructure, 2)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($cellAddressStructure, 2))) { + $column = '$' . $column; + } + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($cellAddressStructure, 2))) { + $row = '$' . $row; + } + + return $column . $row; + } + + + /** + * Reads a cell address in BIFF8 for shared formulas. Uses positive and negative values for row and column + * to indicate offsets from a base cell + * section 3.3.4 + * + * @param string $cellAddressStructure + * @param string $baseCell Base cell, only needed when formula contains tRefN tokens, e.g. with shared formulas + * @return string + */ + private function readBIFF8CellAddressB($cellAddressStructure, $baseCell = 'A1') + { + list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell); + $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1; + + // offset: 0; size: 2; index to row (0... 65535) (or offset (-32768... 32767)) + $rowIndex = self::getInt2d($cellAddressStructure, 0); + $row = self::getInt2d($cellAddressStructure, 0) + 1; + + // offset: 2; size: 2; index to column or column offset + relative flags + // bit: 7-0; mask 0x00FF; column index + $colIndex = 0x00FF & self::getInt2d($cellAddressStructure, 2); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($cellAddressStructure, 2))) { + $column = PHPExcel_Cell::stringFromColumnIndex($colIndex); + $column = '$' . $column; + } else { + $colIndex = ($colIndex <= 127) ? $colIndex : $colIndex - 256; + $column = PHPExcel_Cell::stringFromColumnIndex($baseCol + $colIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($cellAddressStructure, 2))) { + $row = '$' . $row; + } else { + $rowIndex = ($rowIndex <= 32767) ? $rowIndex : $rowIndex - 65536; + $row = $baseRow + $rowIndex; + } + + return $column . $row; + } + + + /** + * Reads a cell range address in BIFF5 e.g. 'A2:B6' or 'A1' + * always fixed range + * section 2.5.14 + * + * @param string $subData + * @return string + * @throws PHPExcel_Reader_Exception + */ + private function readBIFF5CellRangeAddressFixed($subData) + { + // offset: 0; size: 2; index to first row + $fr = self::getInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row + $lr = self::getInt2d($subData, 2) + 1; + + // offset: 4; size: 1; index to first column + $fc = ord($subData{4}); + + // offset: 5; size: 1; index to last column + $lc = ord($subData{5}); + + // check values + if ($fr > $lr || $fc > $lc) { + throw new PHPExcel_Reader_Exception('Not a cell range address'); + } + + // column index to letter + $fc = PHPExcel_Cell::stringFromColumnIndex($fc); + $lc = PHPExcel_Cell::stringFromColumnIndex($lc); + + if ($fr == $lr and $fc == $lc) { + return "$fc$fr"; + } + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 e.g. 'A2:B6' or 'A1' + * always fixed range + * section 2.5.14 + * + * @param string $subData + * @return string + * @throws PHPExcel_Reader_Exception + */ + private function readBIFF8CellRangeAddressFixed($subData) + { + // offset: 0; size: 2; index to first row + $fr = self::getInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row + $lr = self::getInt2d($subData, 2) + 1; + + // offset: 4; size: 2; index to first column + $fc = self::getInt2d($subData, 4); + + // offset: 6; size: 2; index to last column + $lc = self::getInt2d($subData, 6); + + // check values + if ($fr > $lr || $fc > $lc) { + throw new PHPExcel_Reader_Exception('Not a cell range address'); + } + + // column index to letter + $fc = PHPExcel_Cell::stringFromColumnIndex($fc); + $lc = PHPExcel_Cell::stringFromColumnIndex($lc); + + if ($fr == $lr and $fc == $lc) { + return "$fc$fr"; + } + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 e.g. 'A2:B6' or '$A$2:$B$6' + * there are flags indicating whether column/row index is relative + * section 3.3.4 + * + * @param string $subData + * @return string + */ + private function readBIFF8CellRangeAddress($subData) + { + // todo: if cell range is just a single cell, should this funciton + // not just return e.g. 'A1' and not 'A1:A1' ? + + // offset: 0; size: 2; index to first row (0... 65535) (or offset (-32768... 32767)) + $fr = self::getInt2d($subData, 0) + 1; + + // offset: 2; size: 2; index to last row (0... 65535) (or offset (-32768... 32767)) + $lr = self::getInt2d($subData, 2) + 1; + + // offset: 4; size: 2; index to first column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $fc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::getInt2d($subData, 4)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($subData, 4))) { + $fc = '$' . $fc; + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($subData, 4))) { + $fr = '$' . $fr; + } + + // offset: 6; size: 2; index to last column or column offset + relative flags + + // bit: 7-0; mask 0x00FF; column index + $lc = PHPExcel_Cell::stringFromColumnIndex(0x00FF & self::getInt2d($subData, 6)); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($subData, 6))) { + $lc = '$' . $lc; + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($subData, 6))) { + $lr = '$' . $lr; + } + + return "$fc$fr:$lc$lr"; + } + + + /** + * Reads a cell range address in BIFF8 for shared formulas. Uses positive and negative values for row and column + * to indicate offsets from a base cell + * section 3.3.4 + * + * @param string $subData + * @param string $baseCell Base cell + * @return string Cell range address + */ + private function readBIFF8CellRangeAddressB($subData, $baseCell = 'A1') + { + list($baseCol, $baseRow) = PHPExcel_Cell::coordinateFromString($baseCell); + $baseCol = PHPExcel_Cell::columnIndexFromString($baseCol) - 1; + + // TODO: if cell range is just a single cell, should this funciton + // not just return e.g. 'A1' and not 'A1:A1' ? + + // offset: 0; size: 2; first row + $frIndex = self::getInt2d($subData, 0); // adjust below + + // offset: 2; size: 2; relative index to first row (0... 65535) should be treated as offset (-32768... 32767) + $lrIndex = self::getInt2d($subData, 2); // adjust below + + // offset: 4; size: 2; first column with relative/absolute flags + + // bit: 7-0; mask 0x00FF; column index + $fcIndex = 0x00FF & self::getInt2d($subData, 4); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($subData, 4))) { + // absolute column index + $fc = PHPExcel_Cell::stringFromColumnIndex($fcIndex); + $fc = '$' . $fc; + } else { + // column offset + $fcIndex = ($fcIndex <= 127) ? $fcIndex : $fcIndex - 256; + $fc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $fcIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($subData, 4))) { + // absolute row index + $fr = $frIndex + 1; + $fr = '$' . $fr; + } else { + // row offset + $frIndex = ($frIndex <= 32767) ? $frIndex : $frIndex - 65536; + $fr = $baseRow + $frIndex; + } + + // offset: 6; size: 2; last column with relative/absolute flags + + // bit: 7-0; mask 0x00FF; column index + $lcIndex = 0x00FF & self::getInt2d($subData, 6); + $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256; + $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex); + + // bit: 14; mask 0x4000; (1 = relative column index, 0 = absolute column index) + if (!(0x4000 & self::getInt2d($subData, 6))) { + // absolute column index + $lc = PHPExcel_Cell::stringFromColumnIndex($lcIndex); + $lc = '$' . $lc; + } else { + // column offset + $lcIndex = ($lcIndex <= 127) ? $lcIndex : $lcIndex - 256; + $lc = PHPExcel_Cell::stringFromColumnIndex($baseCol + $lcIndex); + } + + // bit: 15; mask 0x8000; (1 = relative row index, 0 = absolute row index) + if (!(0x8000 & self::getInt2d($subData, 6))) { + // absolute row index + $lr = $lrIndex + 1; + $lr = '$' . $lr; + } else { + // row offset + $lrIndex = ($lrIndex <= 32767) ? $lrIndex : $lrIndex - 65536; + $lr = $baseRow + $lrIndex; + } + + return "$fc$fr:$lc$lr"; + } + + + /** + * Read BIFF8 cell range address list + * section 2.5.15 + * + * @param string $subData + * @return array + */ + private function readBIFF8CellRangeAddressList($subData) + { + $cellRangeAddresses = array(); + + // offset: 0; size: 2; number of the following cell range addresses + $nm = self::getInt2d($subData, 0); + + $offset = 2; + // offset: 2; size: 8 * $nm; list of $nm (fixed) cell range addresses + for ($i = 0; $i < $nm; ++$i) { + $cellRangeAddresses[] = $this->readBIFF8CellRangeAddressFixed(substr($subData, $offset, 8)); + $offset += 8; + } + + return array( + 'size' => 2 + 8 * $nm, + 'cellRangeAddresses' => $cellRangeAddresses, + ); + } + + + /** + * Read BIFF5 cell range address list + * section 2.5.15 + * + * @param string $subData + * @return array + */ + private function readBIFF5CellRangeAddressList($subData) + { + $cellRangeAddresses = array(); + + // offset: 0; size: 2; number of the following cell range addresses + $nm = self::getInt2d($subData, 0); + + $offset = 2; + // offset: 2; size: 6 * $nm; list of $nm (fixed) cell range addresses + for ($i = 0; $i < $nm; ++$i) { + $cellRangeAddresses[] = $this->readBIFF5CellRangeAddressFixed(substr($subData, $offset, 6)); + $offset += 6; + } + + return array( + 'size' => 2 + 6 * $nm, + 'cellRangeAddresses' => $cellRangeAddresses, + ); + } + + + /** + * Get a sheet range like Sheet1:Sheet3 from REF index + * Note: If there is only one sheet in the range, one gets e.g Sheet1 + * It can also happen that the REF structure uses the -1 (FFFF) code to indicate deleted sheets, + * in which case an PHPExcel_Reader_Exception is thrown + * + * @param int $index + * @return string|false + * @throws PHPExcel_Reader_Exception + */ + private function readSheetRangeByRefIndex($index) + { + if (isset($this->ref[$index])) { + $type = $this->externalBooks[$this->ref[$index]['externalBookIndex']]['type']; + + switch ($type) { + case 'internal': + // check if we have a deleted 3d reference + if ($this->ref[$index]['firstSheetIndex'] == 0xFFFF or $this->ref[$index]['lastSheetIndex'] == 0xFFFF) { + throw new PHPExcel_Reader_Exception('Deleted sheet reference'); + } + + // we have normal sheet range (collapsed or uncollapsed) + $firstSheetName = $this->sheets[$this->ref[$index]['firstSheetIndex']]['name']; + $lastSheetName = $this->sheets[$this->ref[$index]['lastSheetIndex']]['name']; + + if ($firstSheetName == $lastSheetName) { + // collapsed sheet range + $sheetRange = $firstSheetName; + } else { + $sheetRange = "$firstSheetName:$lastSheetName"; + } + + // escape the single-quotes + $sheetRange = str_replace("'", "''", $sheetRange); + + // if there are special characters, we need to enclose the range in single-quotes + // todo: check if we have identified the whole set of special characters + // it seems that the following characters are not accepted for sheet names + // and we may assume that they are not present: []*/:\? + if (preg_match("/[ !\"@#£$%&{()}<>=+'|^,;-]/", $sheetRange)) { + $sheetRange = "'$sheetRange'"; + } + + return $sheetRange; + break; + default: + // TODO: external sheet support + throw new PHPExcel_Reader_Exception('Excel5 reader only supports internal sheets in fomulas'); + break; + } + } + return false; + } + + + /** + * read BIFF8 constant value array from array data + * returns e.g. array('value' => '{1,2;3,4}', 'size' => 40} + * section 2.5.8 + * + * @param string $arrayData + * @return array + */ + private static function readBIFF8ConstantArray($arrayData) + { + // offset: 0; size: 1; number of columns decreased by 1 + $nc = ord($arrayData[0]); + + // offset: 1; size: 2; number of rows decreased by 1 + $nr = self::getInt2d($arrayData, 1); + $size = 3; // initialize + $arrayData = substr($arrayData, 3); + + // offset: 3; size: var; list of ($nc + 1) * ($nr + 1) constant values + $matrixChunks = array(); + for ($r = 1; $r <= $nr + 1; ++$r) { + $items = array(); + for ($c = 1; $c <= $nc + 1; ++$c) { + $constant = self::readBIFF8Constant($arrayData); + $items[] = $constant['value']; + $arrayData = substr($arrayData, $constant['size']); + $size += $constant['size']; + } + $matrixChunks[] = implode(',', $items); // looks like e.g. '1,"hello"' + } + $matrix = '{' . implode(';', $matrixChunks) . '}'; + + return array( + 'value' => $matrix, + 'size' => $size, + ); + } + + + /** + * read BIFF8 constant value which may be 'Empty Value', 'Number', 'String Value', 'Boolean Value', 'Error Value' + * section 2.5.7 + * returns e.g. array('value' => '5', 'size' => 9) + * + * @param string $valueData + * @return array + */ + private static function readBIFF8Constant($valueData) + { + // offset: 0; size: 1; identifier for type of constant + $identifier = ord($valueData[0]); + + switch ($identifier) { + case 0x00: // empty constant (what is this?) + $value = ''; + $size = 9; + break; + case 0x01: // number + // offset: 1; size: 8; IEEE 754 floating-point value + $value = self::extractNumber(substr($valueData, 1, 8)); + $size = 9; + break; + case 0x02: // string value + // offset: 1; size: var; Unicode string, 16-bit string length + $string = self::readUnicodeStringLong(substr($valueData, 1)); + $value = '"' . $string['value'] . '"'; + $size = 1 + $string['size']; + break; + case 0x04: // boolean + // offset: 1; size: 1; 0 = FALSE, 1 = TRUE + if (ord($valueData[1])) { + $value = 'TRUE'; + } else { + $value = 'FALSE'; + } + $size = 9; + break; + case 0x10: // error code + // offset: 1; size: 1; error code + $value = PHPExcel_Reader_Excel5_ErrorCode::lookup(ord($valueData[1])); + $size = 9; + break; + } + return array( + 'value' => $value, + 'size' => $size, + ); + } + + + /** + * Extract RGB color + * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.4 + * + * @param string $rgb Encoded RGB value (4 bytes) + * @return array + */ + private static function readRGB($rgb) + { + // offset: 0; size 1; Red component + $r = ord($rgb{0}); + + // offset: 1; size: 1; Green component + $g = ord($rgb{1}); + + // offset: 2; size: 1; Blue component + $b = ord($rgb{2}); + + // HEX notation, e.g. 'FF00FC' + $rgb = sprintf('%02X%02X%02X', $r, $g, $b); + + return array('rgb' => $rgb); + } + + + /** + * Read byte string (8-bit string length) + * OpenOffice documentation: 2.5.2 + * + * @param string $subData + * @return array + */ + private function readByteStringShort($subData) + { + // offset: 0; size: 1; length of the string (character count) + $ln = ord($subData[0]); + + // offset: 1: size: var; character array (8-bit characters) + $value = $this->decodeCodepage(substr($subData, 1, $ln)); + + return array( + 'value' => $value, + 'size' => 1 + $ln, // size in bytes of data structure + ); + } + + + /** + * Read byte string (16-bit string length) + * OpenOffice documentation: 2.5.2 + * + * @param string $subData + * @return array + */ + private function readByteStringLong($subData) + { + // offset: 0; size: 2; length of the string (character count) + $ln = self::getInt2d($subData, 0); + + // offset: 2: size: var; character array (8-bit characters) + $value = $this->decodeCodepage(substr($subData, 2)); + + //return $string; + return array( + 'value' => $value, + 'size' => 2 + $ln, // size in bytes of data structure + ); + } + + + /** + * Extracts an Excel Unicode short string (8-bit string length) + * OpenOffice documentation: 2.5.3 + * function will automatically find out where the Unicode string ends. + * + * @param string $subData + * @return array + */ + private static function readUnicodeStringShort($subData) + { + $value = ''; + + // offset: 0: size: 1; length of the string (character count) + $characterCount = ord($subData[0]); + + $string = self::readUnicodeString(substr($subData, 1), $characterCount); + + // add 1 for the string length + $string['size'] += 1; + + return $string; + } + + + /** + * Extracts an Excel Unicode long string (16-bit string length) + * OpenOffice documentation: 2.5.3 + * this function is under construction, needs to support rich text, and Asian phonetic settings + * + * @param string $subData + * @return array + */ + private static function readUnicodeStringLong($subData) + { + $value = ''; + + // offset: 0: size: 2; length of the string (character count) + $characterCount = self::getInt2d($subData, 0); + + $string = self::readUnicodeString(substr($subData, 2), $characterCount); + + // add 2 for the string length + $string['size'] += 2; + + return $string; + } + + + /** + * Read Unicode string with no string length field, but with known character count + * this function is under construction, needs to support rich text, and Asian phonetic settings + * OpenOffice.org's Documentation of the Microsoft Excel File Format, section 2.5.3 + * + * @param string $subData + * @param int $characterCount + * @return array + */ + private static function readUnicodeString($subData, $characterCount) + { + $value = ''; + + // offset: 0: size: 1; option flags + // bit: 0; mask: 0x01; character compression (0 = compressed 8-bit, 1 = uncompressed 16-bit) + $isCompressed = !((0x01 & ord($subData[0])) >> 0); + + // bit: 2; mask: 0x04; Asian phonetic settings + $hasAsian = (0x04) & ord($subData[0]) >> 2; + + // bit: 3; mask: 0x08; Rich-Text settings + $hasRichText = (0x08) & ord($subData[0]) >> 3; + + // offset: 1: size: var; character array + // this offset assumes richtext and Asian phonetic settings are off which is generally wrong + // needs to be fixed + $value = self::encodeUTF16(substr($subData, 1, $isCompressed ? $characterCount : 2 * $characterCount), $isCompressed); + + return array( + 'value' => $value, + 'size' => $isCompressed ? 1 + $characterCount : 1 + 2 * $characterCount, // the size in bytes including the option flags + ); + } + + + /** + * Convert UTF-8 string to string surounded by double quotes. Used for explicit string tokens in formulas. + * Example: hello"world --> "hello""world" + * + * @param string $value UTF-8 encoded string + * @return string + */ + private static function UTF8toExcelDoubleQuoted($value) + { + return '"' . str_replace('"', '""', $value) . '"'; + } + + + /** + * Reads first 8 bytes of a string and return IEEE 754 float + * + * @param string $data Binary string that is at least 8 bytes long + * @return float + */ + private static function extractNumber($data) + { + $rknumhigh = self::getInt4d($data, 4); + $rknumlow = self::getInt4d($data, 0); + $sign = ($rknumhigh & 0x80000000) >> 31; + $exp = (($rknumhigh & 0x7ff00000) >> 20) - 1023; + $mantissa = (0x100000 | ($rknumhigh & 0x000fffff)); + $mantissalow1 = ($rknumlow & 0x80000000) >> 31; + $mantissalow2 = ($rknumlow & 0x7fffffff); + $value = $mantissa / pow(2, (20 - $exp)); + + if ($mantissalow1 != 0) { + $value += 1 / pow(2, (21 - $exp)); + } + + $value += $mantissalow2 / pow(2, (52 - $exp)); + if ($sign) { + $value *= -1; + } + + return $value; + } + + + private static function getIEEE754($rknum) + { + if (($rknum & 0x02) != 0) { + $value = $rknum >> 2; + } else { + // changes by mmp, info on IEEE754 encoding from + // research.microsoft.com/~hollasch/cgindex/coding/ieeefloat.html + // The RK format calls for using only the most significant 30 bits + // of the 64 bit floating point value. The other 34 bits are assumed + // to be 0 so we use the upper 30 bits of $rknum as follows... + $sign = ($rknum & 0x80000000) >> 31; + $exp = ($rknum & 0x7ff00000) >> 20; + $mantissa = (0x100000 | ($rknum & 0x000ffffc)); + $value = $mantissa / pow(2, (20- ($exp - 1023))); + if ($sign) { + $value = -1 * $value; + } + //end of changes by mmp + } + if (($rknum & 0x01) != 0) { + $value /= 100; + } + return $value; + } + + + /** + * Get UTF-8 string from (compressed or uncompressed) UTF-16 string + * + * @param string $string + * @param bool $compressed + * @return string + */ + private static function encodeUTF16($string, $compressed = '') + { + if ($compressed) { + $string = self::uncompressByteString($string); + } + + return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', 'UTF-16LE'); + } + + /** + * Convert UTF-16 string in compressed notation to uncompressed form. Only used for BIFF8. + * + * @param string $string + * @return string + */ + private static function uncompressByteString($string) + { + $uncompressedString = ''; + $strLen = strlen($string); + for ($i = 0; $i < $strLen; ++$i) { + $uncompressedString .= $string[$i] . "\0"; + } + + return $uncompressedString; + } + + /** + * Convert string to UTF-8. Only used for BIFF5. + * + * @param string $string + * @return string + */ + private function decodeCodepage($string) + { + return PHPExcel_Shared_String::ConvertEncoding($string, 'UTF-8', $this->codepage); + } + + /** + * Read 16-bit unsigned integer + * + * @param string $data + * @param int $pos + * @return int + */ + public static function getInt2d($data, $pos) + { + return ord($data[$pos]) | (ord($data[$pos+1]) << 8); + } + + /** + * Read 32-bit signed integer + * + * @param string $data + * @param int $pos + * @return int + */ + public static function getInt4d($data, $pos) + { + // FIX: represent numbers correctly on 64-bit system + // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 + // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems + $_or_24 = ord($data[$pos + 3]); + if ($_or_24 >= 128) { + // negative number + $_ord_24 = -abs((256 - $_or_24) << 24); + } else { + $_ord_24 = ($_or_24 & 127) << 24; + } + return ord($data[$pos]) | (ord($data[$pos+1]) << 8) | (ord($data[$pos+2]) << 16) | $_ord_24; + } + + private function parseRichText($is = '') + { + $value = new PHPExcel_RichText(); + $value->createText($is); + + return $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color.php new file mode 100644 index 00000000..1801df5e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color.php @@ -0,0 +1,32 @@ +<?php + +class PHPExcel_Reader_Excel5_Color +{ + /** + * Read color + * + * @param int $color Indexed color + * @param array $palette Color palette + * @return array RGB color value, example: array('rgb' => 'FF0000') + */ + public static function map($color, $palette, $version) + { + if ($color <= 0x07 || $color >= 0x40) { + // special built-in color + return PHPExcel_Reader_Excel5_Color_BuiltIn::lookup($color); + } elseif (isset($palette) && isset($palette[$color - 8])) { + // palette color, color index 0x08 maps to pallete index 0 + return $palette[$color - 8]; + } else { + // default color table + if ($version == PHPExcel_Reader_Excel5::XLS_BIFF8) { + return PHPExcel_Reader_Excel5_Color_BIFF8::lookup($color); + } else { + // BIFF5 + return PHPExcel_Reader_Excel5_Color_BIFF5::lookup($color); + } + } + + return $color; + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF5.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF5.php new file mode 100644 index 00000000..159c27fc --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF5.php @@ -0,0 +1,77 @@ +<?php + +class PHPExcel_Reader_Excel5_Color_BIFF5 +{ + protected static $map = array( + 0x08 => '000000', + 0x09 => 'FFFFFF', + 0x0A => 'FF0000', + 0x0B => '00FF00', + 0x0C => '0000FF', + 0x0D => 'FFFF00', + 0x0E => 'FF00FF', + 0x0F => '00FFFF', + 0x10 => '800000', + 0x11 => '008000', + 0x12 => '000080', + 0x13 => '808000', + 0x14 => '800080', + 0x15 => '008080', + 0x16 => 'C0C0C0', + 0x17 => '808080', + 0x18 => '8080FF', + 0x19 => '802060', + 0x1A => 'FFFFC0', + 0x1B => 'A0E0F0', + 0x1C => '600080', + 0x1D => 'FF8080', + 0x1E => '0080C0', + 0x1F => 'C0C0FF', + 0x20 => '000080', + 0x21 => 'FF00FF', + 0x22 => 'FFFF00', + 0x23 => '00FFFF', + 0x24 => '800080', + 0x25 => '800000', + 0x26 => '008080', + 0x27 => '0000FF', + 0x28 => '00CFFF', + 0x29 => '69FFFF', + 0x2A => 'E0FFE0', + 0x2B => 'FFFF80', + 0x2C => 'A6CAF0', + 0x2D => 'DD9CB3', + 0x2E => 'B38FEE', + 0x2F => 'E3E3E3', + 0x30 => '2A6FF9', + 0x31 => '3FB8CD', + 0x32 => '488436', + 0x33 => '958C41', + 0x34 => '8E5E42', + 0x35 => 'A0627A', + 0x36 => '624FAC', + 0x37 => '969696', + 0x38 => '1D2FBE', + 0x39 => '286676', + 0x3A => '004500', + 0x3B => '453E01', + 0x3C => '6A2813', + 0x3D => '85396A', + 0x3E => '4A3285', + 0x3F => '424242', + ); + + /** + * Map color array from BIFF5 built-in color index + * + * @param int $color + * @return array + */ + public static function lookup($color) + { + if (isset(self::$map[$color])) { + return array('rgb' => self::$map[$color]); + } + return array('rgb' => '000000'); + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF8.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF8.php new file mode 100644 index 00000000..4d3f2d0a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BIFF8.php @@ -0,0 +1,77 @@ +<?php + +class PHPExcel_Reader_Excel5_Color_BIFF8 +{ + protected static $map = array( + 0x08 => '000000', + 0x09 => 'FFFFFF', + 0x0A => 'FF0000', + 0x0B => '00FF00', + 0x0C => '0000FF', + 0x0D => 'FFFF00', + 0x0E => 'FF00FF', + 0x0F => '00FFFF', + 0x10 => '800000', + 0x11 => '008000', + 0x12 => '000080', + 0x13 => '808000', + 0x14 => '800080', + 0x15 => '008080', + 0x16 => 'C0C0C0', + 0x17 => '808080', + 0x18 => '9999FF', + 0x19 => '993366', + 0x1A => 'FFFFCC', + 0x1B => 'CCFFFF', + 0x1C => '660066', + 0x1D => 'FF8080', + 0x1E => '0066CC', + 0x1F => 'CCCCFF', + 0x20 => '000080', + 0x21 => 'FF00FF', + 0x22 => 'FFFF00', + 0x23 => '00FFFF', + 0x24 => '800080', + 0x25 => '800000', + 0x26 => '008080', + 0x27 => '0000FF', + 0x28 => '00CCFF', + 0x29 => 'CCFFFF', + 0x2A => 'CCFFCC', + 0x2B => 'FFFF99', + 0x2C => '99CCFF', + 0x2D => 'FF99CC', + 0x2E => 'CC99FF', + 0x2F => 'FFCC99', + 0x30 => '3366FF', + 0x31 => '33CCCC', + 0x32 => '99CC00', + 0x33 => 'FFCC00', + 0x34 => 'FF9900', + 0x35 => 'FF6600', + 0x36 => '666699', + 0x37 => '969696', + 0x38 => '003366', + 0x39 => '339966', + 0x3A => '003300', + 0x3B => '333300', + 0x3C => '993300', + 0x3D => '993366', + 0x3E => '333399', + 0x3F => '333333', + ); + + /** + * Map color array from BIFF8 built-in color index + * + * @param int $color + * @return array + */ + public static function lookup($color) + { + if (isset(self::$map[$color])) { + return array('rgb' => self::$map[$color]); + } + return array('rgb' => '000000'); + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BuiltIn.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BuiltIn.php new file mode 100644 index 00000000..a5b7e59b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Color/BuiltIn.php @@ -0,0 +1,31 @@ +<?php + +class PHPExcel_Reader_Excel5_Color_BuiltIn +{ + protected static $map = array( + 0x00 => '000000', + 0x01 => 'FFFFFF', + 0x02 => 'FF0000', + 0x03 => '00FF00', + 0x04 => '0000FF', + 0x05 => 'FFFF00', + 0x06 => 'FF00FF', + 0x07 => '00FFFF', + 0x40 => '000000', // system window text color + 0x41 => 'FFFFFF', // system window background color + ); + + /** + * Map built-in color to RGB value + * + * @param int $color Indexed color + * @return array + */ + public static function lookup($color) + { + if (isset(self::$map[$color])) { + return array('rgb' => self::$map[$color]); + } + return array('rgb' => '000000'); + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/ErrorCode.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/ErrorCode.php new file mode 100644 index 00000000..f1d1cb6d --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/ErrorCode.php @@ -0,0 +1,28 @@ +<?php + +class PHPExcel_Reader_Excel5_ErrorCode +{ + protected static $map = array( + 0x00 => '#NULL!', + 0x07 => '#DIV/0!', + 0x0F => '#VALUE!', + 0x17 => '#REF!', + 0x1D => '#NAME?', + 0x24 => '#NUM!', + 0x2A => '#N/A', + ); + + /** + * Map error code, e.g. '#N/A' + * + * @param int $code + * @return string + */ + public static function lookup($code) + { + if (isset(self::$map[$code])) { + return self::$map[$code]; + } + return false; + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Escher.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Escher.php new file mode 100644 index 00000000..2b99e222 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Escher.php @@ -0,0 +1,669 @@ +<?php + +/** + * PHPExcel_Reader_Excel5_Escher + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Excel5_Escher +{ + const DGGCONTAINER = 0xF000; + const BSTORECONTAINER = 0xF001; + const DGCONTAINER = 0xF002; + const SPGRCONTAINER = 0xF003; + const SPCONTAINER = 0xF004; + const DGG = 0xF006; + const BSE = 0xF007; + const DG = 0xF008; + const SPGR = 0xF009; + const SP = 0xF00A; + const OPT = 0xF00B; + const CLIENTTEXTBOX = 0xF00D; + const CLIENTANCHOR = 0xF010; + const CLIENTDATA = 0xF011; + const BLIPJPEG = 0xF01D; + const BLIPPNG = 0xF01E; + const SPLITMENUCOLORS = 0xF11E; + const TERTIARYOPT = 0xF122; + + /** + * Escher stream data (binary) + * + * @var string + */ + private $data; + + /** + * Size in bytes of the Escher stream data + * + * @var int + */ + private $dataSize; + + /** + * Current position of stream pointer in Escher stream data + * + * @var int + */ + private $pos; + + /** + * The object to be returned by the reader. Modified during load. + * + * @var mixed + */ + private $object; + + /** + * Create a new PHPExcel_Reader_Excel5_Escher instance + * + * @param mixed $object + */ + public function __construct($object) + { + $this->object = $object; + } + + /** + * Load Escher stream data. May be a partial Escher stream. + * + * @param string $data + */ + public function load($data) + { + $this->data = $data; + + // total byte size of Excel data (workbook global substream + sheet substreams) + $this->dataSize = strlen($this->data); + + $this->pos = 0; + + // Parse Escher stream + while ($this->pos < $this->dataSize) { + // offset: 2; size: 2: Record Type + $fbt = PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos + 2); + + switch ($fbt) { + case self::DGGCONTAINER: + $this->readDggContainer(); + break; + case self::DGG: + $this->readDgg(); + break; + case self::BSTORECONTAINER: + $this->readBstoreContainer(); + break; + case self::BSE: + $this->readBSE(); + break; + case self::BLIPJPEG: + $this->readBlipJPEG(); + break; + case self::BLIPPNG: + $this->readBlipPNG(); + break; + case self::OPT: + $this->readOPT(); + break; + case self::TERTIARYOPT: + $this->readTertiaryOPT(); + break; + case self::SPLITMENUCOLORS: + $this->readSplitMenuColors(); + break; + case self::DGCONTAINER: + $this->readDgContainer(); + break; + case self::DG: + $this->readDg(); + break; + case self::SPGRCONTAINER: + $this->readSpgrContainer(); + break; + case self::SPCONTAINER: + $this->readSpContainer(); + break; + case self::SPGR: + $this->readSpgr(); + break; + case self::SP: + $this->readSp(); + break; + case self::CLIENTTEXTBOX: + $this->readClientTextbox(); + break; + case self::CLIENTANCHOR: + $this->readClientAnchor(); + break; + case self::CLIENTDATA: + $this->readClientData(); + break; + default: + $this->readDefault(); + break; + } + } + + return $this->object; + } + + /** + * Read a generic record + */ + private function readDefault() + { + // offset 0; size: 2; recVer and recInstance + $verInstance = PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos); + + // offset: 2; size: 2: Record Type + $fbt = PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos + 2); + + // bit: 0-3; mask: 0x000F; recVer + $recVer = (0x000F & $verInstance) >> 0; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read DggContainer record (Drawing Group Container) + */ + private function readDggContainer() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // record is a container, read contents + $dggContainer = new PHPExcel_Shared_Escher_DggContainer(); + $this->object->setDggContainer($dggContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($dggContainer); + $reader->load($recordData); + } + + /** + * Read Dgg record (Drawing Group) + */ + private function readDgg() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read BstoreContainer record (Blip Store Container) + */ + private function readBstoreContainer() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // record is a container, read contents + $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer(); + $this->object->setBstoreContainer($bstoreContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($bstoreContainer); + $reader->load($recordData); + } + + /** + * Read BSE record + */ + private function readBSE() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // add BSE to BstoreContainer + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $this->object->addBSE($BSE); + + $BSE->setBLIPType($recInstance); + + // offset: 0; size: 1; btWin32 (MSOBLIPTYPE) + $btWin32 = ord($recordData[0]); + + // offset: 1; size: 1; btWin32 (MSOBLIPTYPE) + $btMacOS = ord($recordData[1]); + + // offset: 2; size: 16; MD4 digest + $rgbUid = substr($recordData, 2, 16); + + // offset: 18; size: 2; tag + $tag = PHPExcel_Reader_Excel5::getInt2d($recordData, 18); + + // offset: 20; size: 4; size of BLIP in bytes + $size = PHPExcel_Reader_Excel5::getInt4d($recordData, 20); + + // offset: 24; size: 4; number of references to this BLIP + $cRef = PHPExcel_Reader_Excel5::getInt4d($recordData, 24); + + // offset: 28; size: 4; MSOFO file offset + $foDelay = PHPExcel_Reader_Excel5::getInt4d($recordData, 28); + + // offset: 32; size: 1; unused1 + $unused1 = ord($recordData{32}); + + // offset: 33; size: 1; size of nameData in bytes (including null terminator) + $cbName = ord($recordData{33}); + + // offset: 34; size: 1; unused2 + $unused2 = ord($recordData{34}); + + // offset: 35; size: 1; unused3 + $unused3 = ord($recordData{35}); + + // offset: 36; size: $cbName; nameData + $nameData = substr($recordData, 36, $cbName); + + // offset: 36 + $cbName, size: var; the BLIP data + $blipData = substr($recordData, 36 + $cbName); + + // record is a container, read contents + $reader = new PHPExcel_Reader_Excel5_Escher($BSE); + $reader->load($blipData); + } + + /** + * Read BlipJPEG record. Holds raw JPEG image data + */ + private function readBlipJPEG() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + $pos = 0; + + // offset: 0; size: 16; rgbUid1 (MD4 digest of) + $rgbUid1 = substr($recordData, 0, 16); + $pos += 16; + + // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 + if (in_array($recInstance, array(0x046B, 0x06E3))) { + $rgbUid2 = substr($recordData, 16, 16); + $pos += 16; + } + + // offset: var; size: 1; tag + $tag = ord($recordData{$pos}); + $pos += 1; + + // offset: var; size: var; the raw image data + $data = substr($recordData, $pos); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($data); + + $this->object->setBlip($blip); + } + + /** + * Read BlipPNG record. Holds raw PNG image data + */ + private function readBlipPNG() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + $pos = 0; + + // offset: 0; size: 16; rgbUid1 (MD4 digest of) + $rgbUid1 = substr($recordData, 0, 16); + $pos += 16; + + // offset: 16; size: 16; rgbUid2 (MD4 digest), only if $recInstance = 0x46B or 0x6E3 + if ($recInstance == 0x06E1) { + $rgbUid2 = substr($recordData, 16, 16); + $pos += 16; + } + + // offset: var; size: 1; tag + $tag = ord($recordData{$pos}); + $pos += 1; + + // offset: var; size: var; the raw image data + $data = substr($recordData, $pos); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($data); + + $this->object->setBlip($blip); + } + + /** + * Read OPT record. This record may occur within DggContainer record or SpContainer + */ + private function readOPT() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + $this->readOfficeArtRGFOPTE($recordData, $recInstance); + } + + /** + * Read TertiaryOPT record + */ + private function readTertiaryOPT() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read SplitMenuColors record + */ + private function readSplitMenuColors() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read DgContainer record (Drawing Container) + */ + private function readDgContainer() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // record is a container, read contents + $dgContainer = new PHPExcel_Shared_Escher_DgContainer(); + $this->object->setDgContainer($dgContainer); + $reader = new PHPExcel_Reader_Excel5_Escher($dgContainer); + $escher = $reader->load($recordData); + } + + /** + * Read Dg record (Drawing) + */ + private function readDg() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read SpgrContainer record (Shape Group Container) + */ + private function readSpgrContainer() + { + // context is either context DgContainer or SpgrContainer + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // record is a container, read contents + $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer(); + + if ($this->object instanceof PHPExcel_Shared_Escher_DgContainer) { + // DgContainer + $this->object->setSpgrContainer($spgrContainer); + } else { + // SpgrContainer + $this->object->addChild($spgrContainer); + } + + $reader = new PHPExcel_Reader_Excel5_Escher($spgrContainer); + $escher = $reader->load($recordData); + } + + /** + * Read SpContainer record (Shape Container) + */ + private function readSpContainer() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // add spContainer to spgrContainer + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + $this->object->addChild($spContainer); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // record is a container, read contents + $reader = new PHPExcel_Reader_Excel5_Escher($spContainer); + $escher = $reader->load($recordData); + } + + /** + * Read Spgr record (Shape Group) + */ + private function readSpgr() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read Sp record (Shape) + */ + private function readSp() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read ClientTextbox record + */ + private function readClientTextbox() + { + // offset: 0; size: 2; recVer and recInstance + + // bit: 4-15; mask: 0xFFF0; recInstance + $recInstance = (0xFFF0 & PHPExcel_Reader_Excel5::getInt2d($this->data, $this->pos)) >> 4; + + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read ClientAnchor record. This record holds information about where the shape is anchored in worksheet + */ + private function readClientAnchor() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + + // offset: 2; size: 2; upper-left corner column index (0-based) + $c1 = PHPExcel_Reader_Excel5::getInt2d($recordData, 2); + + // offset: 4; size: 2; upper-left corner horizontal offset in 1/1024 of column width + $startOffsetX = PHPExcel_Reader_Excel5::getInt2d($recordData, 4); + + // offset: 6; size: 2; upper-left corner row index (0-based) + $r1 = PHPExcel_Reader_Excel5::getInt2d($recordData, 6); + + // offset: 8; size: 2; upper-left corner vertical offset in 1/256 of row height + $startOffsetY = PHPExcel_Reader_Excel5::getInt2d($recordData, 8); + + // offset: 10; size: 2; bottom-right corner column index (0-based) + $c2 = PHPExcel_Reader_Excel5::getInt2d($recordData, 10); + + // offset: 12; size: 2; bottom-right corner horizontal offset in 1/1024 of column width + $endOffsetX = PHPExcel_Reader_Excel5::getInt2d($recordData, 12); + + // offset: 14; size: 2; bottom-right corner row index (0-based) + $r2 = PHPExcel_Reader_Excel5::getInt2d($recordData, 14); + + // offset: 16; size: 2; bottom-right corner vertical offset in 1/256 of row height + $endOffsetY = PHPExcel_Reader_Excel5::getInt2d($recordData, 16); + + // set the start coordinates + $this->object->setStartCoordinates(PHPExcel_Cell::stringFromColumnIndex($c1) . ($r1 + 1)); + + // set the start offsetX + $this->object->setStartOffsetX($startOffsetX); + + // set the start offsetY + $this->object->setStartOffsetY($startOffsetY); + + // set the end coordinates + $this->object->setEndCoordinates(PHPExcel_Cell::stringFromColumnIndex($c2) . ($r2 + 1)); + + // set the end offsetX + $this->object->setEndOffsetX($endOffsetX); + + // set the end offsetY + $this->object->setEndOffsetY($endOffsetY); + } + + /** + * Read ClientData record + */ + private function readClientData() + { + $length = PHPExcel_Reader_Excel5::getInt4d($this->data, $this->pos + 4); + $recordData = substr($this->data, $this->pos + 8, $length); + + // move stream pointer to next record + $this->pos += 8 + $length; + } + + /** + * Read OfficeArtRGFOPTE table of property-value pairs + * + * @param string $data Binary data + * @param int $n Number of properties + */ + private function readOfficeArtRGFOPTE($data, $n) + { + $splicedComplexData = substr($data, 6 * $n); + + // loop through property-value pairs + for ($i = 0; $i < $n; ++$i) { + // read 6 bytes at a time + $fopte = substr($data, 6 * $i, 6); + + // offset: 0; size: 2; opid + $opid = PHPExcel_Reader_Excel5::getInt2d($fopte, 0); + + // bit: 0-13; mask: 0x3FFF; opid.opid + $opidOpid = (0x3FFF & $opid) >> 0; + + // bit: 14; mask 0x4000; 1 = value in op field is BLIP identifier + $opidFBid = (0x4000 & $opid) >> 14; + + // bit: 15; mask 0x8000; 1 = this is a complex property, op field specifies size of complex data + $opidFComplex = (0x8000 & $opid) >> 15; + + // offset: 2; size: 4; the value for this property + $op = PHPExcel_Reader_Excel5::getInt4d($fopte, 2); + + if ($opidFComplex) { + $complexData = substr($splicedComplexData, 0, $op); + $splicedComplexData = substr($splicedComplexData, $op); + + // we store string value with complex data + $value = $complexData; + } else { + // we store integer value + $value = $op; + } + + $this->object->setOPT($opidOpid, $value); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/MD5.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/MD5.php new file mode 100644 index 00000000..f14ea946 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/MD5.php @@ -0,0 +1,203 @@ +<?php + +/** + * PHPExcel_Reader_Excel5_MD5 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Excel5_MD5 +{ + // Context + private $a; + private $b; + private $c; + private $d; + + /** + * MD5 stream constructor + */ + public function __construct() + { + $this->reset(); + } + + /** + * Reset the MD5 stream context + */ + public function reset() + { + $this->a = 0x67452301; + $this->b = 0xEFCDAB89; + $this->c = 0x98BADCFE; + $this->d = 0x10325476; + } + + /** + * Get MD5 stream context + * + * @return string + */ + public function getContext() + { + $s = ''; + foreach (array('a', 'b', 'c', 'd') as $i) { + $v = $this->{$i}; + $s .= chr($v & 0xff); + $s .= chr(($v >> 8) & 0xff); + $s .= chr(($v >> 16) & 0xff); + $s .= chr(($v >> 24) & 0xff); + } + + return $s; + } + + /** + * Add data to context + * + * @param string $data Data to add + */ + public function add($data) + { + $words = array_values(unpack('V16', $data)); + + $A = $this->a; + $B = $this->b; + $C = $this->c; + $D = $this->d; + + $F = array('PHPExcel_Reader_Excel5_MD5','f'); + $G = array('PHPExcel_Reader_Excel5_MD5','g'); + $H = array('PHPExcel_Reader_Excel5_MD5','h'); + $I = array('PHPExcel_Reader_Excel5_MD5','i'); + + /* ROUND 1 */ + self::step($F, $A, $B, $C, $D, $words[0], 7, 0xd76aa478); + self::step($F, $D, $A, $B, $C, $words[1], 12, 0xe8c7b756); + self::step($F, $C, $D, $A, $B, $words[2], 17, 0x242070db); + self::step($F, $B, $C, $D, $A, $words[3], 22, 0xc1bdceee); + self::step($F, $A, $B, $C, $D, $words[4], 7, 0xf57c0faf); + self::step($F, $D, $A, $B, $C, $words[5], 12, 0x4787c62a); + self::step($F, $C, $D, $A, $B, $words[6], 17, 0xa8304613); + self::step($F, $B, $C, $D, $A, $words[7], 22, 0xfd469501); + self::step($F, $A, $B, $C, $D, $words[8], 7, 0x698098d8); + self::step($F, $D, $A, $B, $C, $words[9], 12, 0x8b44f7af); + self::step($F, $C, $D, $A, $B, $words[10], 17, 0xffff5bb1); + self::step($F, $B, $C, $D, $A, $words[11], 22, 0x895cd7be); + self::step($F, $A, $B, $C, $D, $words[12], 7, 0x6b901122); + self::step($F, $D, $A, $B, $C, $words[13], 12, 0xfd987193); + self::step($F, $C, $D, $A, $B, $words[14], 17, 0xa679438e); + self::step($F, $B, $C, $D, $A, $words[15], 22, 0x49b40821); + + /* ROUND 2 */ + self::step($G, $A, $B, $C, $D, $words[1], 5, 0xf61e2562); + self::step($G, $D, $A, $B, $C, $words[6], 9, 0xc040b340); + self::step($G, $C, $D, $A, $B, $words[11], 14, 0x265e5a51); + self::step($G, $B, $C, $D, $A, $words[0], 20, 0xe9b6c7aa); + self::step($G, $A, $B, $C, $D, $words[5], 5, 0xd62f105d); + self::step($G, $D, $A, $B, $C, $words[10], 9, 0x02441453); + self::step($G, $C, $D, $A, $B, $words[15], 14, 0xd8a1e681); + self::step($G, $B, $C, $D, $A, $words[4], 20, 0xe7d3fbc8); + self::step($G, $A, $B, $C, $D, $words[9], 5, 0x21e1cde6); + self::step($G, $D, $A, $B, $C, $words[14], 9, 0xc33707d6); + self::step($G, $C, $D, $A, $B, $words[3], 14, 0xf4d50d87); + self::step($G, $B, $C, $D, $A, $words[8], 20, 0x455a14ed); + self::step($G, $A, $B, $C, $D, $words[13], 5, 0xa9e3e905); + self::step($G, $D, $A, $B, $C, $words[2], 9, 0xfcefa3f8); + self::step($G, $C, $D, $A, $B, $words[7], 14, 0x676f02d9); + self::step($G, $B, $C, $D, $A, $words[12], 20, 0x8d2a4c8a); + + /* ROUND 3 */ + self::step($H, $A, $B, $C, $D, $words[5], 4, 0xfffa3942); + self::step($H, $D, $A, $B, $C, $words[8], 11, 0x8771f681); + self::step($H, $C, $D, $A, $B, $words[11], 16, 0x6d9d6122); + self::step($H, $B, $C, $D, $A, $words[14], 23, 0xfde5380c); + self::step($H, $A, $B, $C, $D, $words[1], 4, 0xa4beea44); + self::step($H, $D, $A, $B, $C, $words[4], 11, 0x4bdecfa9); + self::step($H, $C, $D, $A, $B, $words[7], 16, 0xf6bb4b60); + self::step($H, $B, $C, $D, $A, $words[10], 23, 0xbebfbc70); + self::step($H, $A, $B, $C, $D, $words[13], 4, 0x289b7ec6); + self::step($H, $D, $A, $B, $C, $words[0], 11, 0xeaa127fa); + self::step($H, $C, $D, $A, $B, $words[3], 16, 0xd4ef3085); + self::step($H, $B, $C, $D, $A, $words[6], 23, 0x04881d05); + self::step($H, $A, $B, $C, $D, $words[9], 4, 0xd9d4d039); + self::step($H, $D, $A, $B, $C, $words[12], 11, 0xe6db99e5); + self::step($H, $C, $D, $A, $B, $words[15], 16, 0x1fa27cf8); + self::step($H, $B, $C, $D, $A, $words[2], 23, 0xc4ac5665); + + /* ROUND 4 */ + self::step($I, $A, $B, $C, $D, $words[0], 6, 0xf4292244); + self::step($I, $D, $A, $B, $C, $words[7], 10, 0x432aff97); + self::step($I, $C, $D, $A, $B, $words[14], 15, 0xab9423a7); + self::step($I, $B, $C, $D, $A, $words[5], 21, 0xfc93a039); + self::step($I, $A, $B, $C, $D, $words[12], 6, 0x655b59c3); + self::step($I, $D, $A, $B, $C, $words[3], 10, 0x8f0ccc92); + self::step($I, $C, $D, $A, $B, $words[10], 15, 0xffeff47d); + self::step($I, $B, $C, $D, $A, $words[1], 21, 0x85845dd1); + self::step($I, $A, $B, $C, $D, $words[8], 6, 0x6fa87e4f); + self::step($I, $D, $A, $B, $C, $words[15], 10, 0xfe2ce6e0); + self::step($I, $C, $D, $A, $B, $words[6], 15, 0xa3014314); + self::step($I, $B, $C, $D, $A, $words[13], 21, 0x4e0811a1); + self::step($I, $A, $B, $C, $D, $words[4], 6, 0xf7537e82); + self::step($I, $D, $A, $B, $C, $words[11], 10, 0xbd3af235); + self::step($I, $C, $D, $A, $B, $words[2], 15, 0x2ad7d2bb); + self::step($I, $B, $C, $D, $A, $words[9], 21, 0xeb86d391); + + $this->a = ($this->a + $A) & 0xffffffff; + $this->b = ($this->b + $B) & 0xffffffff; + $this->c = ($this->c + $C) & 0xffffffff; + $this->d = ($this->d + $D) & 0xffffffff; + } + + private static function f($X, $Y, $Z) + { + return (($X & $Y) | ((~ $X) & $Z)); // X AND Y OR NOT X AND Z + } + + private static function g($X, $Y, $Z) + { + return (($X & $Z) | ($Y & (~ $Z))); // X AND Z OR Y AND NOT Z + } + + private static function h($X, $Y, $Z) + { + return ($X ^ $Y ^ $Z); // X XOR Y XOR Z + } + + private static function i($X, $Y, $Z) + { + return ($Y ^ ($X | (~ $Z))) ; // Y XOR (X OR NOT Z) + } + + private static function step($func, &$A, $B, $C, $D, $M, $s, $t) + { + $A = ($A + call_user_func($func, $B, $C, $D) + $M + $t) & 0xffffffff; + $A = self::rotate($A, $s); + $A = ($B + $A) & 0xffffffff; + } + + private static function rotate($decimal, $bits) + { + $binary = str_pad(decbin($decimal), 32, "0", STR_PAD_LEFT); + return bindec(substr($binary, $bits).substr($binary, 0, $bits)); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/RC4.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/RC4.php new file mode 100644 index 00000000..5640539c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/RC4.php @@ -0,0 +1,81 @@ +<?php + +/** + * PHPExcel_Reader_Excel5_RC4 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Excel5_RC4 +{ + // Context + protected $s = array(); + protected $i = 0; + protected $j = 0; + + /** + * RC4 stream decryption/encryption constrcutor + * + * @param string $key Encryption key/passphrase + */ + public function __construct($key) + { + $len = strlen($key); + + for ($this->i = 0; $this->i < 256; $this->i++) { + $this->s[$this->i] = $this->i; + } + + $this->j = 0; + for ($this->i = 0; $this->i < 256; $this->i++) { + $this->j = ($this->j + $this->s[$this->i] + ord($key[$this->i % $len])) % 256; + $t = $this->s[$this->i]; + $this->s[$this->i] = $this->s[$this->j]; + $this->s[$this->j] = $t; + } + $this->i = $this->j = 0; + } + + /** + * Symmetric decryption/encryption function + * + * @param string $data Data to encrypt/decrypt + * + * @return string + */ + public function RC4($data) + { + $len = strlen($data); + for ($c = 0; $c < $len; $c++) { + $this->i = ($this->i + 1) % 256; + $this->j = ($this->j + $this->s[$this->i]) % 256; + $t = $this->s[$this->i]; + $this->s[$this->i] = $this->s[$this->j]; + $this->s[$this->j] = $t; + + $t = ($this->s[$this->i] + $this->s[$this->j]) % 256; + + $data[$c] = chr(ord($data[$c]) ^ $this->s[$t]); + } + return $data; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/Border.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/Border.php new file mode 100644 index 00000000..fb45b9d5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/Border.php @@ -0,0 +1,36 @@ +<?php + +class PHPExcel_Reader_Excel5_Style_Border +{ + protected static $map = array( + 0x00 => PHPExcel_Style_Border::BORDER_NONE, + 0x01 => PHPExcel_Style_Border::BORDER_THIN, + 0x02 => PHPExcel_Style_Border::BORDER_MEDIUM, + 0x03 => PHPExcel_Style_Border::BORDER_DASHED, + 0x04 => PHPExcel_Style_Border::BORDER_DOTTED, + 0x05 => PHPExcel_Style_Border::BORDER_THICK, + 0x06 => PHPExcel_Style_Border::BORDER_DOUBLE, + 0x07 => PHPExcel_Style_Border::BORDER_HAIR, + 0x08 => PHPExcel_Style_Border::BORDER_MEDIUMDASHED, + 0x09 => PHPExcel_Style_Border::BORDER_DASHDOT, + 0x0A => PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT, + 0x0B => PHPExcel_Style_Border::BORDER_DASHDOTDOT, + 0x0C => PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT, + 0x0D => PHPExcel_Style_Border::BORDER_SLANTDASHDOT, + ); + + /** + * Map border style + * OpenOffice documentation: 2.5.11 + * + * @param int $index + * @return string + */ + public static function lookup($index) + { + if (isset(self::$map[$index])) { + return self::$map[$index]; + } + return PHPExcel_Style_Border::BORDER_NONE; + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/FillPattern.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/FillPattern.php new file mode 100644 index 00000000..c92d19a6 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Excel5/Style/FillPattern.php @@ -0,0 +1,41 @@ +<?php + +class PHPExcel_Reader_Excel5_Style_FillPattern +{ + protected static $map = array( + 0x00 => PHPExcel_Style_Fill::FILL_NONE, + 0x01 => PHPExcel_Style_Fill::FILL_SOLID, + 0x02 => PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY, + 0x03 => PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY, + 0x04 => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY, + 0x05 => PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL, + 0x06 => PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL, + 0x07 => PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN, + 0x08 => PHPExcel_Style_Fill::FILL_PATTERN_DARKUP, + 0x09 => PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID, + 0x0A => PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS, + 0x0B => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL, + 0x0C => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL, + 0x0D => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN, + 0x0E => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP, + 0x0F => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID, + 0x10 => PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS, + 0x11 => PHPExcel_Style_Fill::FILL_PATTERN_GRAY125, + 0x12 => PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625, + ); + + /** + * Get fill pattern from index + * OpenOffice documentation: 2.5.12 + * + * @param int $index + * @return string + */ + public static function lookup($index) + { + if (isset(self::$map[$index])) { + return self::$map[$index]; + } + return PHPExcel_Style_Fill::FILL_NONE; + } +} \ No newline at end of file diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Exception.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Exception.php new file mode 100644 index 00000000..48b3f825 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Exception.php @@ -0,0 +1,46 @@ +<?php + +/** + * PHPExcel_Reader_Exception + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Exception extends PHPExcel_Exception +{ + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Gnumeric.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Gnumeric.php new file mode 100644 index 00000000..913e52bc --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/Gnumeric.php @@ -0,0 +1,850 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_Gnumeric + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_Gnumeric extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Formats + * + * @var array + */ + private $styles = array(); + + /** + * Shared Expressions + * + * @var array + */ + private $expressions = array(); + + private $referenceHelper = null; + + /** + * Create a new PHPExcel_Reader_Gnumeric + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + $this->referenceHelper = PHPExcel_ReferenceHelper::getInstance(); + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + // Check if gzlib functions are available + if (!function_exists('gzread')) { + throw new PHPExcel_Reader_Exception("gzlib library is not enabled"); + } + + // Read signature data (first 3 bytes) + $fh = fopen($pFilename, 'r'); + $data = fread($fh, 2); + fclose($fh); + + if ($data != chr(0x1F).chr(0x8B)) { + return false; + } + + return true; + } + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $xml = new XMLReader(); + $xml->xml($this->securityScanFile('compress.zlib://'.realpath($pFilename)), null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2, true); + + $worksheetNames = array(); + while ($xml->read()) { + if ($xml->name == 'gnm:SheetName' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $worksheetNames[] = (string) $xml->value; + } elseif ($xml->name == 'gnm:Sheets') { + // break out of the loop once we've got our sheet names rather than parse the entire file + break; + } + } + + return $worksheetNames; + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $xml = new XMLReader(); + $xml->xml($this->securityScanFile('compress.zlib://'.realpath($pFilename)), null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2, true); + + $worksheetInfo = array(); + while ($xml->read()) { + if ($xml->name == 'gnm:Sheet' && $xml->nodeType == XMLReader::ELEMENT) { + $tmpInfo = array( + 'worksheetName' => '', + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + while ($xml->read()) { + if ($xml->name == 'gnm:Name' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['worksheetName'] = (string) $xml->value; + } elseif ($xml->name == 'gnm:MaxCol' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['lastColumnIndex'] = (int) $xml->value; + $tmpInfo['totalColumns'] = (int) $xml->value + 1; + } elseif ($xml->name == 'gnm:MaxRow' && $xml->nodeType == XMLReader::ELEMENT) { + $xml->read(); // Move onto the value node + $tmpInfo['totalRows'] = (int) $xml->value + 1; + break; + } + } + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $worksheetInfo[] = $tmpInfo; + } + } + + return $worksheetInfo; + } + + private function gzfileGetContents($filename) + { + $file = @gzopen($filename, 'rb'); + if ($file !== false) { + $data = ''; + while (!gzeof($file)) { + $data .= gzread($file, 1024); + } + gzclose($file); + } + return $data; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + $gFileData = $this->gzfileGetContents($pFilename); + +// echo '<pre>'; +// echo htmlentities($gFileData,ENT_QUOTES,'UTF-8'); +// echo '</pre><hr />'; +// + $xml = simplexml_load_string($this->securityScan($gFileData), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesMeta = $xml->getNamespaces(true); + +// var_dump($namespacesMeta); +// + $gnmXML = $xml->children($namespacesMeta['gnm']); + + $docProps = $objPHPExcel->getProperties(); + // Document Properties are held differently, depending on the version of Gnumeric + if (isset($namespacesMeta['office'])) { + $officeXML = $xml->children($namespacesMeta['office']); + $officeDocXML = $officeXML->{'document-meta'}; + $officeDocMetaXML = $officeDocXML->meta; + + foreach ($officeDocMetaXML as $officePropertyData) { + $officePropertyDC = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); + } + foreach ($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'title': + $docProps->setTitle(trim($propertyValue)); + break; + case 'subject': + $docProps->setSubject(trim($propertyValue)); + break; + case 'creator': + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'date': + $creationDate = strtotime(trim($propertyValue)); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'description': + $docProps->setDescription(trim($propertyValue)); + break; + } + } + $officePropertyMeta = array(); + if (isset($namespacesMeta['meta'])) { + $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); + } + foreach ($officePropertyMeta as $propertyName => $propertyValue) { + $attributes = $propertyValue->attributes($namespacesMeta['meta']); + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'keyword': + $docProps->setKeywords(trim($propertyValue)); + break; + case 'initial-creator': + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'creation-date': + $creationDate = strtotime(trim($propertyValue)); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'user-defined': + list(, $attrName) = explode(':', $attributes['name']); + switch ($attrName) { + case 'publisher': + $docProps->setCompany(trim($propertyValue)); + break; + case 'category': + $docProps->setCategory(trim($propertyValue)); + break; + case 'manager': + $docProps->setManager(trim($propertyValue)); + break; + } + break; + } + } + } + } elseif (isset($gnmXML->Summary)) { + foreach ($gnmXML->Summary->Item as $summaryItem) { + $propertyName = $summaryItem->name; + $propertyValue = $summaryItem->{'val-string'}; + switch ($propertyName) { + case 'title': + $docProps->setTitle(trim($propertyValue)); + break; + case 'comments': + $docProps->setDescription(trim($propertyValue)); + break; + case 'keywords': + $docProps->setKeywords(trim($propertyValue)); + break; + case 'category': + $docProps->setCategory(trim($propertyValue)); + break; + case 'manager': + $docProps->setManager(trim($propertyValue)); + break; + case 'author': + $docProps->setCreator(trim($propertyValue)); + $docProps->setLastModifiedBy(trim($propertyValue)); + break; + case 'company': + $docProps->setCompany(trim($propertyValue)); + break; + } + } + } + + $worksheetID = 0; + foreach ($gnmXML->Sheets->Sheet as $sheet) { + $worksheetName = (string) $sheet->Name; +// echo '<b>Worksheet: ', $worksheetName,'</b><br />'; + if ((isset($this->loadSheetsOnly)) && (!in_array($worksheetName, $this->loadSheetsOnly))) { + continue; + } + + $maxRow = $maxCol = 0; + + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in formula + // cells... during the load, all formulae should be correct, and we're simply bringing the worksheet + // name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName, false); + + if ((!$this->readDataOnly) && (isset($sheet->PrintInformation))) { + if (isset($sheet->PrintInformation->Margins)) { + foreach ($sheet->PrintInformation->Margins->children('gnm', true) as $key => $margin) { + $marginAttributes = $margin->attributes(); + $marginSize = 72 / 100; // Default + switch ($marginAttributes['PrefUnit']) { + case 'mm': + $marginSize = intval($marginAttributes['Points']) / 100; + break; + } + switch ($key) { + case 'top': + $objPHPExcel->getActiveSheet()->getPageMargins()->setTop($marginSize); + break; + case 'bottom': + $objPHPExcel->getActiveSheet()->getPageMargins()->setBottom($marginSize); + break; + case 'left': + $objPHPExcel->getActiveSheet()->getPageMargins()->setLeft($marginSize); + break; + case 'right': + $objPHPExcel->getActiveSheet()->getPageMargins()->setRight($marginSize); + break; + case 'header': + $objPHPExcel->getActiveSheet()->getPageMargins()->setHeader($marginSize); + break; + case 'footer': + $objPHPExcel->getActiveSheet()->getPageMargins()->setFooter($marginSize); + break; + } + } + } + } + + foreach ($sheet->Cells->Cell as $cell) { + $cellAttributes = $cell->attributes(); + $row = (int) $cellAttributes->Row + 1; + $column = (int) $cellAttributes->Col; + + if ($row > $maxRow) { + $maxRow = $row; + } + if ($column > $maxCol) { + $maxCol = $column; + } + + $column = PHPExcel_Cell::stringFromColumnIndex($column); + + // Read cell? + if ($this->getReadFilter() !== null) { + if (!$this->getReadFilter()->readCell($column, $row, $worksheetName)) { + continue; + } + } + + $ValueType = $cellAttributes->ValueType; + $ExprID = (string) $cellAttributes->ExprID; +// echo 'Cell ', $column, $row,'<br />'; +// echo 'Type is ', $ValueType,'<br />'; +// echo 'Value is ', $cell,'<br />'; + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + if ($ExprID > '') { + if (((string) $cell) > '') { + $this->expressions[$ExprID] = array( + 'column' => $cellAttributes->Col, + 'row' => $cellAttributes->Row, + 'formula' => (string) $cell + ); +// echo 'NEW EXPRESSION ', $ExprID,'<br />'; + } else { + $expression = $this->expressions[$ExprID]; + + $cell = $this->referenceHelper->updateFormulaReferences( + $expression['formula'], + 'A1', + $cellAttributes->Col - $expression['column'], + $cellAttributes->Row - $expression['row'], + $worksheetName + ); +// echo 'SHARED EXPRESSION ', $ExprID,'<br />'; +// echo 'New Value is ', $cell,'<br />'; + } + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; + } else { + switch ($ValueType) { + case '10': // NULL + $type = PHPExcel_Cell_DataType::TYPE_NULL; + break; + case '20': // Boolean + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $cell = ($cell == 'TRUE') ? true: false; + break; + case '30': // Integer + $cell = intval($cell); + // Excel 2007+ doesn't differentiate between integer and float, so set the value and dropthru to the next (numeric) case + case '40': // Float + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + break; + case '50': // Error + $type = PHPExcel_Cell_DataType::TYPE_ERROR; + break; + case '60': // String + $type = PHPExcel_Cell_DataType::TYPE_STRING; + break; + case '70': // Cell Range + case '80': // Array + } + } + $objPHPExcel->getActiveSheet()->getCell($column.$row)->setValueExplicit($cell, $type); + } + + if ((!$this->readDataOnly) && (isset($sheet->Objects))) { + foreach ($sheet->Objects->children('gnm', true) as $key => $comment) { + $commentAttributes = $comment->attributes(); + // Only comment objects are handled at the moment + if ($commentAttributes->Text) { + $objPHPExcel->getActiveSheet()->getComment((string)$commentAttributes->ObjectBound)->setAuthor((string)$commentAttributes->Author)->setText($this->parseRichText((string)$commentAttributes->Text)); + } + } + } +// echo '$maxCol=', $maxCol,'; $maxRow=', $maxRow,'<br />'; +// + foreach ($sheet->Styles->StyleRegion as $styleRegion) { + $styleAttributes = $styleRegion->attributes(); + if (($styleAttributes['startRow'] <= $maxRow) && + ($styleAttributes['startCol'] <= $maxCol)) { + $startColumn = PHPExcel_Cell::stringFromColumnIndex((int) $styleAttributes['startCol']); + $startRow = $styleAttributes['startRow'] + 1; + + $endColumn = ($styleAttributes['endCol'] > $maxCol) ? $maxCol : (int) $styleAttributes['endCol']; + $endColumn = PHPExcel_Cell::stringFromColumnIndex($endColumn); + $endRow = ($styleAttributes['endRow'] > $maxRow) ? $maxRow : $styleAttributes['endRow']; + $endRow += 1; + $cellRange = $startColumn.$startRow.':'.$endColumn.$endRow; +// echo $cellRange,'<br />'; + + $styleAttributes = $styleRegion->Style->attributes(); +// var_dump($styleAttributes); +// echo '<br />'; + + // We still set the number format mask for date/time values, even if readDataOnly is true + if ((!$this->readDataOnly) || + (PHPExcel_Shared_Date::isDateTimeFormatCode((string) $styleAttributes['Format']))) { + $styleArray = array(); + $styleArray['numberformat']['code'] = (string) $styleAttributes['Format']; + // If readDataOnly is false, we set all formatting information + if (!$this->readDataOnly) { + switch ($styleAttributes['HAlign']) { + case '1': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + break; + case '2': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_LEFT; + break; + case '4': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_RIGHT; + break; + case '8': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER; + break; + case '16': + case '64': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS; + break; + case '32': + $styleArray['alignment']['horizontal'] = PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY; + break; + } + + switch ($styleAttributes['VAlign']) { + case '1': + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_TOP; + break; + case '2': + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + break; + case '4': + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_CENTER; + break; + case '8': + $styleArray['alignment']['vertical'] = PHPExcel_Style_Alignment::VERTICAL_JUSTIFY; + break; + } + + $styleArray['alignment']['wrap'] = ($styleAttributes['WrapText'] == '1') ? true : false; + $styleArray['alignment']['shrinkToFit'] = ($styleAttributes['ShrinkToFit'] == '1') ? true : false; + $styleArray['alignment']['indent'] = (intval($styleAttributes["Indent"]) > 0) ? $styleAttributes["indent"] : 0; + + $RGB = self::parseGnumericColour($styleAttributes["Fore"]); + $styleArray['font']['color']['rgb'] = $RGB; + $RGB = self::parseGnumericColour($styleAttributes["Back"]); + $shade = $styleAttributes["Shade"]; + if (($RGB != '000000') || ($shade != '0')) { + $styleArray['fill']['color']['rgb'] = $styleArray['fill']['startcolor']['rgb'] = $RGB; + $RGB2 = self::parseGnumericColour($styleAttributes["PatternColor"]); + $styleArray['fill']['endcolor']['rgb'] = $RGB2; + switch ($shade) { + case '1': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_SOLID; + break; + case '2': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR; + break; + case '3': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_GRADIENT_PATH; + break; + case '4': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN; + break; + case '5': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY; + break; + case '6': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID; + break; + case '7': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL; + break; + case '8': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS; + break; + case '9': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKUP; + break; + case '10': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL; + break; + case '11': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625; + break; + case '12': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_GRAY125; + break; + case '13': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN; + break; + case '14': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY; + break; + case '15': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID; + break; + case '16': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL; + break; + case '17': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS; + break; + case '18': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP; + break; + case '19': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL; + break; + case '20': + $styleArray['fill']['type'] = PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY; + break; + } + } + + $fontAttributes = $styleRegion->Style->Font->attributes(); +// var_dump($fontAttributes); +// echo '<br />'; + $styleArray['font']['name'] = (string) $styleRegion->Style->Font; + $styleArray['font']['size'] = intval($fontAttributes['Unit']); + $styleArray['font']['bold'] = ($fontAttributes['Bold'] == '1') ? true : false; + $styleArray['font']['italic'] = ($fontAttributes['Italic'] == '1') ? true : false; + $styleArray['font']['strike'] = ($fontAttributes['StrikeThrough'] == '1') ? true : false; + switch ($fontAttributes['Underline']) { + case '1': + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLE; + break; + case '2': + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLE; + break; + case '3': + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING; + break; + case '4': + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING; + break; + default: + $styleArray['font']['underline'] = PHPExcel_Style_Font::UNDERLINE_NONE; + break; + } + switch ($fontAttributes['Script']) { + case '1': + $styleArray['font']['superScript'] = true; + break; + case '-1': + $styleArray['font']['subScript'] = true; + break; + } + + if (isset($styleRegion->Style->StyleBorder)) { + if (isset($styleRegion->Style->StyleBorder->Top)) { + $styleArray['borders']['top'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Top->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Bottom)) { + $styleArray['borders']['bottom'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Bottom->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Left)) { + $styleArray['borders']['left'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Left->attributes()); + } + if (isset($styleRegion->Style->StyleBorder->Right)) { + $styleArray['borders']['right'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Right->attributes()); + } + if ((isset($styleRegion->Style->StyleBorder->Diagonal)) && (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}))) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_BOTH; + } elseif (isset($styleRegion->Style->StyleBorder->Diagonal)) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->Diagonal->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_UP; + } elseif (isset($styleRegion->Style->StyleBorder->{'Rev-Diagonal'})) { + $styleArray['borders']['diagonal'] = self::parseBorderAttributes($styleRegion->Style->StyleBorder->{'Rev-Diagonal'}->attributes()); + $styleArray['borders']['diagonaldirection'] = PHPExcel_Style_Borders::DIAGONAL_DOWN; + } + } + if (isset($styleRegion->Style->HyperLink)) { + // TO DO + $hyperlink = $styleRegion->Style->HyperLink->attributes(); + } + } +// var_dump($styleArray); +// echo '<br />'; + $objPHPExcel->getActiveSheet()->getStyle($cellRange)->applyFromArray($styleArray); + } + } + } + + if ((!$this->readDataOnly) && (isset($sheet->Cols))) { + // Column Widths + $columnAttributes = $sheet->Cols->attributes(); + $defaultWidth = $columnAttributes['DefaultSizePts'] / 5.4; + $c = 0; + foreach ($sheet->Cols->ColInfo as $columnOverride) { + $columnAttributes = $columnOverride->attributes(); + $column = $columnAttributes['No']; + $columnWidth = $columnAttributes['Unit'] / 5.4; + $hidden = ((isset($columnAttributes['Hidden'])) && ($columnAttributes['Hidden'] == '1')) ? true : false; + $columnCount = (isset($columnAttributes['Count'])) ? $columnAttributes['Count'] : 1; + while ($c < $column) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); + ++$c; + } + while (($c < ($column+$columnCount)) && ($c <= $maxCol)) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($columnWidth); + if ($hidden) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setVisible(false); + } + ++$c; + } + } + while ($c <= $maxCol) { + $objPHPExcel->getActiveSheet()->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($c))->setWidth($defaultWidth); + ++$c; + } + } + + if ((!$this->readDataOnly) && (isset($sheet->Rows))) { + // Row Heights + $rowAttributes = $sheet->Rows->attributes(); + $defaultHeight = $rowAttributes['DefaultSizePts']; + $r = 0; + + foreach ($sheet->Rows->RowInfo as $rowOverride) { + $rowAttributes = $rowOverride->attributes(); + $row = $rowAttributes['No']; + $rowHeight = $rowAttributes['Unit']; + $hidden = ((isset($rowAttributes['Hidden'])) && ($rowAttributes['Hidden'] == '1')) ? true : false; + $rowCount = (isset($rowAttributes['Count'])) ? $rowAttributes['Count'] : 1; + while ($r < $row) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + } + while (($r < ($row+$rowCount)) && ($r < $maxRow)) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($rowHeight); + if ($hidden) { + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setVisible(false); + } + } + } + while ($r < $maxRow) { + ++$r; + $objPHPExcel->getActiveSheet()->getRowDimension($r)->setRowHeight($defaultHeight); + } + } + + // Handle Merged Cells in this worksheet + if (isset($sheet->MergedRegions)) { + foreach ($sheet->MergedRegions->Merge as $mergeCells) { + if (strpos($mergeCells, ':') !== false) { + $objPHPExcel->getActiveSheet()->mergeCells($mergeCells); + } + } + } + + $worksheetID++; + } + + // Loop through definedNames (global named ranges) + if (isset($gnmXML->Names)) { + foreach ($gnmXML->Names->Name as $namedRange) { + $name = (string) $namedRange->name; + $range = (string) $namedRange->value; + if (stripos($range, '#REF!') !== false) { + continue; + } + + $range = explode('!', $range); + $range[0] = trim($range[0], "'"); + if ($worksheet = $objPHPExcel->getSheetByName($range[0])) { + $extractedRange = str_replace('$', '', $range[1]); + $objPHPExcel->addNamedRange(new PHPExcel_NamedRange($name, $worksheet, $extractedRange)); + } + } + } + + // Return + return $objPHPExcel; + } + + private static function parseBorderAttributes($borderAttributes) + { + $styleArray = array(); + if (isset($borderAttributes["Color"])) { + $styleArray['color']['rgb'] = self::parseGnumericColour($borderAttributes["Color"]); + } + + switch ($borderAttributes["Style"]) { + case '0': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_NONE; + break; + case '1': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case '2': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUM; + break; + case '3': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_SLANTDASHDOT; + break; + case '4': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHED; + break; + case '5': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_THICK; + break; + case '6': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DOUBLE; + break; + case '7': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DOTTED; + break; + case '8': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHED; + break; + case '9': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHDOT; + break; + case '10': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT; + break; + case '11': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_DASHDOTDOT; + break; + case '12': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT; + break; + case '13': + $styleArray['style'] = PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT; + break; + } + return $styleArray; + } + + private function parseRichText($is = '') + { + $value = new PHPExcel_RichText(); + $value->createText($is); + + return $value; + } + + private static function parseGnumericColour($gnmColour) + { + list($gnmR, $gnmG, $gnmB) = explode(':', $gnmColour); + $gnmR = substr(str_pad($gnmR, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmG = substr(str_pad($gnmG, 4, '0', STR_PAD_RIGHT), 0, 2); + $gnmB = substr(str_pad($gnmB, 4, '0', STR_PAD_RIGHT), 0, 2); + return $gnmR . $gnmG . $gnmB; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/HTML.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/HTML.php new file mode 100644 index 00000000..ac762a4f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/HTML.php @@ -0,0 +1,549 @@ +<?php + +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_HTML + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +/** PHPExcel root directory */ +class PHPExcel_Reader_HTML extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + + /** + * Input encoding + * + * @var string + */ + protected $inputEncoding = 'ANSI'; + + /** + * Sheet index to read + * + * @var int + */ + protected $sheetIndex = 0; + + /** + * Formats + * + * @var array + */ + protected $formats = array( + 'h1' => array( + 'font' => array( + 'bold' => true, + 'size' => 24, + ), + ), // Bold, 24pt + 'h2' => array( + 'font' => array( + 'bold' => true, + 'size' => 18, + ), + ), // Bold, 18pt + 'h3' => array( + 'font' => array( + 'bold' => true, + 'size' => 13.5, + ), + ), // Bold, 13.5pt + 'h4' => array( + 'font' => array( + 'bold' => true, + 'size' => 12, + ), + ), // Bold, 12pt + 'h5' => array( + 'font' => array( + 'bold' => true, + 'size' => 10, + ), + ), // Bold, 10pt + 'h6' => array( + 'font' => array( + 'bold' => true, + 'size' => 7.5, + ), + ), // Bold, 7.5pt + 'a' => array( + 'font' => array( + 'underline' => true, + 'color' => array( + 'argb' => PHPExcel_Style_Color::COLOR_BLUE, + ), + ), + ), // Blue underlined + 'hr' => array( + 'borders' => array( + 'bottom' => array( + 'style' => PHPExcel_Style_Border::BORDER_THIN, + 'color' => array( + PHPExcel_Style_Color::COLOR_BLACK, + ), + ), + ), + ), // Bottom border + ); + + protected $rowspan = array(); + + /** + * Create a new PHPExcel_Reader_HTML + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is an HTML file + * + * @return boolean + */ + protected function isValidFormat() + { + // Reading 2048 bytes should be enough to validate that the format is HTML + $data = fread($this->fileHandle, 2048); + if ((strpos($data, '<') !== false) && + (strlen($data) !== strlen(strip_tags($data)))) { + return true; + } + + return false; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'ANSI') + { + $this->inputEncoding = $pValue; + + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->inputEncoding; + } + + // Data Array used for testing only, should write to PHPExcel object on completion of tests + protected $dataArray = array(); + protected $tableLevel = 0; + protected $nestedColumn = array('A'); + + protected function setTableStartColumn($column) + { + if ($this->tableLevel == 0) { + $column = 'A'; + } + ++$this->tableLevel; + $this->nestedColumn[$this->tableLevel] = $column; + + return $this->nestedColumn[$this->tableLevel]; + } + + protected function getTableStartColumn() + { + return $this->nestedColumn[$this->tableLevel]; + } + + protected function releaseTableStartColumn() + { + --$this->tableLevel; + + return array_pop($this->nestedColumn); + } + + protected function flushCell($sheet, $column, $row, &$cellContent) + { + if (is_string($cellContent)) { + // Simple String content + if (trim($cellContent) > '') { + // Only actually write it if there's content in the string +// echo 'FLUSH CELL: ' , $column , $row , ' => ' , $cellContent , '<br />'; + // Write to worksheet to be done here... + // ... we return the cell so we can mess about with styles more easily + $sheet->setCellValue($column . $row, $cellContent, true); + $this->dataArray[$row][$column] = $cellContent; + } + } else { + // We have a Rich Text run + // TODO + $this->dataArray[$row][$column] = 'RICH TEXT: ' . $cellContent; + } + $cellContent = (string) ''; + } + + protected function processDomElement(DOMNode $element, $sheet, &$row, &$column, &$cellContent, $format = null) + { + foreach ($element->childNodes as $child) { + if ($child instanceof DOMText) { + $domText = preg_replace('/\s+/u', ' ', trim($child->nodeValue)); + if (is_string($cellContent)) { + // simply append the text if the cell content is a plain text string + $cellContent .= $domText; + } else { + // but if we have a rich text run instead, we need to append it correctly + // TODO + } + } elseif ($child instanceof DOMElement) { +// echo '<b>DOM ELEMENT: </b>' , strtoupper($child->nodeName) , '<br />'; + + $attributeArray = array(); + foreach ($child->attributes as $attribute) { +// echo '<b>ATTRIBUTE: </b>' , $attribute->name , ' => ' , $attribute->value , '<br />'; + $attributeArray[$attribute->name] = $attribute->value; + } + + switch ($child->nodeName) { + case 'meta': + foreach ($attributeArray as $attributeName => $attributeValue) { + switch ($attributeName) { + case 'content': + // TODO + // Extract character set, so we can convert to UTF-8 if required + break; + } + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + break; + case 'title': + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + $sheet->setTitle($cellContent); + $cellContent = ''; + break; + case 'span': + case 'div': + case 'font': + case 'i': + case 'em': + case 'strong': + case 'b': +// echo 'STYLING, SPAN OR DIV<br />'; + if ($cellContent > '') { + $cellContent .= ' '; + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + if ($cellContent > '') { + $cellContent .= ' '; + } +// echo 'END OF STYLING, SPAN OR DIV<br />'; + break; + case 'hr': + $this->flushCell($sheet, $column, $row, $cellContent); + ++$row; + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } else { + $cellContent = '----------'; + $this->flushCell($sheet, $column, $row, $cellContent); + } + ++$row; + // Add a break after a horizontal rule, simply by allowing the code to dropthru + case 'br': + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; + } else { + // Otherwise flush our existing content and move the row cursor on + $this->flushCell($sheet, $column, $row, $cellContent); + ++$row; + } +// echo 'HARD LINE BREAK: ' , '<br />'; + break; + case 'a': +// echo 'START OF HYPERLINK: ' , '<br />'; + foreach ($attributeArray as $attributeName => $attributeValue) { + switch ($attributeName) { + case 'href': +// echo 'Link to ' , $attributeValue , '<br />'; + $sheet->getCell($column . $row)->getHyperlink()->setUrl($attributeValue); + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } + break; + } + } + $cellContent .= ' '; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF HYPERLINK:' , '<br />'; + break; + case 'h1': + case 'h2': + case 'h3': + case 'h4': + case 'h5': + case 'h6': + case 'ol': + case 'ul': + case 'p': + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; +// echo 'LIST ENTRY: ' , '<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + } else { + if ($cellContent > '') { + $this->flushCell($sheet, $column, $row, $cellContent); + $row++; + } +// echo 'START OF PARAGRAPH: ' , '<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF PARAGRAPH:' , '<br />'; + $this->flushCell($sheet, $column, $row, $cellContent); + + if (isset($this->formats[$child->nodeName])) { + $sheet->getStyle($column . $row)->applyFromArray($this->formats[$child->nodeName]); + } + + $row++; + $column = 'A'; + } + break; + case 'li': + if ($this->tableLevel > 0) { + // If we're inside a table, replace with a \n + $cellContent .= "\n"; +// echo 'LIST ENTRY: ' , '<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + } else { + if ($cellContent > '') { + $this->flushCell($sheet, $column, $row, $cellContent); + } + ++$row; +// echo 'LIST ENTRY: ' , '<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF LIST ENTRY:' , '<br />'; + $this->flushCell($sheet, $column, $row, $cellContent); + $column = 'A'; + } + break; + case 'table': + $this->flushCell($sheet, $column, $row, $cellContent); + $column = $this->setTableStartColumn($column); +// echo 'START OF TABLE LEVEL ' , $this->tableLevel , '<br />'; + if ($this->tableLevel > 1) { + --$row; + } + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF TABLE LEVEL ' , $this->tableLevel , '<br />'; + $column = $this->releaseTableStartColumn(); + if ($this->tableLevel > 1) { + ++$column; + } else { + ++$row; + } + break; + case 'thead': + case 'tbody': + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + break; + case 'tr': + $column = $this->getTableStartColumn(); + $cellContent = ''; +// echo 'START OF TABLE ' , $this->tableLevel , ' ROW<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + ++$row; +// echo 'END OF TABLE ' , $this->tableLevel , ' ROW<br />'; + break; + case 'th': + case 'td': +// echo 'START OF TABLE ' , $this->tableLevel , ' CELL<br />'; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); +// echo 'END OF TABLE ' , $this->tableLevel , ' CELL<br />'; + + while (isset($this->rowspan[$column . $row])) { + ++$column; + } + + $this->flushCell($sheet, $column, $row, $cellContent); + +// if (isset($attributeArray['style']) && !empty($attributeArray['style'])) { +// $styleAry = $this->getPhpExcelStyleArray($attributeArray['style']); +// +// if (!empty($styleAry)) { +// $sheet->getStyle($column . $row)->applyFromArray($styleAry); +// } +// } + + if (isset($attributeArray['rowspan']) && isset($attributeArray['colspan'])) { + //create merging rowspan and colspan + $columnTo = $column; + for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { + ++$columnTo; + } + $range = $column . $row . ':' . $columnTo . ($row + $attributeArray['rowspan'] - 1); + foreach (\PHPExcel_Cell::extractAllCellReferencesInRange($range) as $value) { + $this->rowspan[$value] = true; + } + $sheet->mergeCells($range); + $column = $columnTo; + } elseif (isset($attributeArray['rowspan'])) { + //create merging rowspan + $range = $column . $row . ':' . $column . ($row + $attributeArray['rowspan'] - 1); + foreach (\PHPExcel_Cell::extractAllCellReferencesInRange($range) as $value) { + $this->rowspan[$value] = true; + } + $sheet->mergeCells($range); + } elseif (isset($attributeArray['colspan'])) { + //create merging colspan + $columnTo = $column; + for ($i = 0; $i < $attributeArray['colspan'] - 1; $i++) { + ++$columnTo; + } + $sheet->mergeCells($column . $row . ':' . $columnTo . $row); + $column = $columnTo; + } + ++$column; + break; + case 'body': + $row = 1; + $column = 'A'; + $content = ''; + $this->tableLevel = 0; + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + break; + default: + $this->processDomElement($child, $sheet, $row, $column, $cellContent); + } + } + } + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Open file to validate + $this->openFile($pFilename); + if (!$this->isValidFormat()) { + fclose($this->fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid HTML file."); + } + // Close after validating + fclose($this->fileHandle); + + // Create new PHPExcel + while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) { + $objPHPExcel->createSheet(); + } + $objPHPExcel->setActiveSheetIndex($this->sheetIndex); + + // Create a new DOM object + $dom = new domDocument; + // Reload the HTML file into the DOM object + $loaded = $dom->loadHTML(mb_convert_encoding($this->securityScanFile($pFilename), 'HTML-ENTITIES', 'UTF-8')); + if ($loaded === false) { + throw new PHPExcel_Reader_Exception('Failed to load ' . $pFilename . ' as a DOM Document'); + } + + // Discard white space + $dom->preserveWhiteSpace = false; + + $row = 0; + $column = 'A'; + $content = ''; + $this->processDomElement($dom, $objPHPExcel->getActiveSheet(), $row, $column, $content); + + // Return + return $objPHPExcel; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() + { + return $this->sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Reader_HTML + */ + public function setSheetIndex($pValue = 0) + { + $this->sheetIndex = $pValue; + + return $this; + } + + /** + * Scan theXML for use of <!ENTITY to prevent XXE/XEE attacks + * + * @param string $xml + * @throws PHPExcel_Reader_Exception + */ + public function securityScan($xml) + { + $pattern = '/\\0?' . implode('\\0?', str_split('<!ENTITY')) . '\\0?/'; + if (preg_match($pattern, $xml)) { + throw new PHPExcel_Reader_Exception('Detected use of ENTITY in XML, spreadsheet file load() aborted to prevent XXE/XEE attacks'); + } + return $xml; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReadFilter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReadFilter.php new file mode 100644 index 00000000..f7c852d9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReadFilter.php @@ -0,0 +1,39 @@ +<?php + +/** + * PHPExcel_Reader_IReadFilter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_Reader_IReadFilter +{ + /** + * Should this cell be read? + * + * @param $column Column address (as a string value like "A", or "IV") + * @param $row Row number + * @param $worksheetName Optional worksheet name + * @return boolean + */ + public function readCell($column, $row, $worksheetName = ''); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReader.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReader.php new file mode 100644 index 00000000..90345464 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/IReader.php @@ -0,0 +1,46 @@ +<?php + +/** + * PHPExcel_Reader_IReader + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_Reader_IReader +{ + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + */ + public function canRead($pFilename); + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/OOCalc.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/OOCalc.php new file mode 100644 index 00000000..a889d957 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/OOCalc.php @@ -0,0 +1,696 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_OOCalc + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_OOCalc extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Formats + * + * @var array + */ + private $styles = array(); + + /** + * Create a new PHPExcel_Reader_OOCalc + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Can the current PHPExcel_Reader_IReader read the file? + * + * @param string $pFilename + * @return boolean + * @throws PHPExcel_Reader_Exception + */ + public function canRead($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + // Check if zip class exists +// if (!class_exists($zipClass, false)) { +// throw new PHPExcel_Reader_Exception($zipClass . " library is not enabled"); +// } + + $mimeType = 'UNKNOWN'; + // Load file + $zip = new $zipClass; + if ($zip->open($pFilename) === true) { + // check if it is an OOXML archive + $stat = $zip->statName('mimetype'); + if ($stat && ($stat['size'] <= 255)) { + $mimeType = $zip->getFromName($stat['name']); + } elseif ($stat = $zip->statName('META-INF/manifest.xml')) { + $xml = simplexml_load_string($this->securityScan($zip->getFromName('META-INF/manifest.xml')), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesContent = $xml->getNamespaces(true); + if (isset($namespacesContent['manifest'])) { + $manifest = $xml->children($namespacesContent['manifest']); + foreach ($manifest as $manifestDataSet) { + $manifestAttributes = $manifestDataSet->attributes($namespacesContent['manifest']); + if ($manifestAttributes->{'full-path'} == '/') { + $mimeType = (string) $manifestAttributes->{'media-type'}; + break; + } + } + } + } + + $zip->close(); + + return ($mimeType === 'application/vnd.oasis.opendocument.spreadsheet'); + } + + return false; + } + + + /** + * Reads names of the worksheets from a file, without parsing the whole file to a PHPExcel object + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetNames($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + + $worksheetNames = array(); + + $xml = new XMLReader(); + $res = $xml->xml($this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2, true); + + // Step into the first level of content of the XML + $xml->read(); + while ($xml->read()) { + // Quickly jump through to the office:body node + while ($xml->name !== 'office:body') { + if ($xml->isEmptyElement) { + $xml->read(); + } else { + $xml->next(); + } + } + // Now read each node until we find our first table:table node + while ($xml->read()) { + if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + // Loop through each table:table node reading the table:name attribute for each worksheet name + do { + $worksheetNames[] = $xml->getAttribute('table:name'); + $xml->next(); + } while ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT); + } + } + } + + return $worksheetNames; + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $worksheetInfo = array(); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + + $xml = new XMLReader(); + $res = $xml->xml($this->securityScanFile('zip://'.realpath($pFilename).'#content.xml'), null, PHPExcel_Settings::getLibXmlLoaderOptions()); + $xml->setParserProperty(2, true); + + // Step into the first level of content of the XML + $xml->read(); + while ($xml->read()) { + // Quickly jump through to the office:body node + while ($xml->name !== 'office:body') { + if ($xml->isEmptyElement) { + $xml->read(); + } else { + $xml->next(); + } + } + // Now read each node until we find our first table:table node + while ($xml->read()) { + if ($xml->name == 'table:table' && $xml->nodeType == XMLReader::ELEMENT) { + $worksheetNames[] = $xml->getAttribute('table:name'); + + $tmpInfo = array( + 'worksheetName' => $xml->getAttribute('table:name'), + 'lastColumnLetter' => 'A', + 'lastColumnIndex' => 0, + 'totalRows' => 0, + 'totalColumns' => 0, + ); + + // Loop through each child node of the table:table element reading + $currCells = 0; + do { + $xml->read(); + if ($xml->name == 'table:table-row' && $xml->nodeType == XMLReader::ELEMENT) { + $rowspan = $xml->getAttribute('table:number-rows-repeated'); + $rowspan = empty($rowspan) ? 1 : $rowspan; + $tmpInfo['totalRows'] += $rowspan; + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); + $currCells = 0; + // Step into the row + $xml->read(); + do { + if ($xml->name == 'table:table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + if (!$xml->isEmptyElement) { + $currCells++; + $xml->next(); + } else { + $xml->read(); + } + } elseif ($xml->name == 'table:covered-table-cell' && $xml->nodeType == XMLReader::ELEMENT) { + $mergeSize = $xml->getAttribute('table:number-columns-repeated'); + $currCells += $mergeSize; + $xml->read(); + } + } while ($xml->name != 'table:table-row'); + } + } while ($xml->name != 'table:table'); + + $tmpInfo['totalColumns'] = max($tmpInfo['totalColumns'], $currCells); + $tmpInfo['lastColumnIndex'] = $tmpInfo['totalColumns'] - 1; + $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); + $worksheetInfo[] = $tmpInfo; + } + } + +// foreach ($workbookData->table as $worksheetDataSet) { +// $worksheetData = $worksheetDataSet->children($namespacesContent['table']); +// $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']); +// +// $rowIndex = 0; +// foreach ($worksheetData as $key => $rowData) { +// switch ($key) { +// case 'table-row' : +// $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']); +// $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? +// $rowDataTableAttributes['number-rows-repeated'] : 1; +// $columnIndex = 0; +// +// foreach ($rowData as $key => $cellData) { +// $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']); +// $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? +// $cellDataTableAttributes['number-columns-repeated'] : 1; +// $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']); +// if (isset($cellDataOfficeAttributes['value-type'])) { +// $tmpInfo['lastColumnIndex'] = max($tmpInfo['lastColumnIndex'], $columnIndex + $colRepeats - 1); +// $tmpInfo['totalRows'] = max($tmpInfo['totalRows'], $rowIndex + $rowRepeats); +// } +// $columnIndex += $colRepeats; +// } +// $rowIndex += $rowRepeats; +// break; +// } +// } +// +// $tmpInfo['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($tmpInfo['lastColumnIndex']); +// $tmpInfo['totalColumns'] = $tmpInfo['lastColumnIndex'] + 1; +// +// } +// } + } + + return $worksheetInfo; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + private static function identifyFixedStyleValue($styleList, &$styleAttributeValue) + { + $styleAttributeValue = strtolower($styleAttributeValue); + foreach ($styleList as $style) { + if ($styleAttributeValue == strtolower($style)) { + $styleAttributeValue = $style; + return true; + } + } + return false; + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Check if file exists + if (!file_exists($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist."); + } + + $timezoneObj = new DateTimeZone('Europe/London'); + $GMT = new DateTimeZone('UTC'); + + $zipClass = PHPExcel_Settings::getZipClass(); + + $zip = new $zipClass; + if (!$zip->open($pFilename)) { + throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file."); + } + +// echo '<h1>Meta Information</h1>'; + $xml = simplexml_load_string($this->securityScan($zip->getFromName("meta.xml")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesMeta = $xml->getNamespaces(true); +// echo '<pre>'; +// print_r($namespacesMeta); +// echo '</pre><hr />'; + + $docProps = $objPHPExcel->getProperties(); + $officeProperty = $xml->children($namespacesMeta['office']); + foreach ($officeProperty as $officePropertyData) { + $officePropertyDC = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyDC = $officePropertyData->children($namespacesMeta['dc']); + } + foreach ($officePropertyDC as $propertyName => $propertyValue) { + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'title': + $docProps->setTitle($propertyValue); + break; + case 'subject': + $docProps->setSubject($propertyValue); + break; + case 'creator': + $docProps->setCreator($propertyValue); + $docProps->setLastModifiedBy($propertyValue); + break; + case 'date': + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + $docProps->setModified($creationDate); + break; + case 'description': + $docProps->setDescription($propertyValue); + break; + } + } + $officePropertyMeta = array(); + if (isset($namespacesMeta['dc'])) { + $officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']); + } + foreach ($officePropertyMeta as $propertyName => $propertyValue) { + $propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']); + $propertyValue = (string) $propertyValue; + switch ($propertyName) { + case 'initial-creator': + $docProps->setCreator($propertyValue); + break; + case 'keyword': + $docProps->setKeywords($propertyValue); + break; + case 'creation-date': + $creationDate = strtotime($propertyValue); + $docProps->setCreated($creationDate); + break; + case 'user-defined': + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + foreach ($propertyValueAttributes as $key => $value) { + if ($key == 'name') { + $propertyValueName = (string) $value; + } elseif ($key == 'value-type') { + switch ($value) { + case 'date': + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'date'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE; + break; + case 'boolean': + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'bool'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN; + break; + case 'float': + $propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue, 'r4'); + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT; + break; + default: + $propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING; + } + } + } + $docProps->setCustomProperty($propertyValueName, $propertyValue, $propertyValueType); + break; + } + } + } + + +// echo '<h1>Workbook Content</h1>'; + $xml = simplexml_load_string($this->securityScan($zip->getFromName("content.xml")), 'SimpleXMLElement', PHPExcel_Settings::getLibXmlLoaderOptions()); + $namespacesContent = $xml->getNamespaces(true); +// echo '<pre>'; +// print_r($namespacesContent); +// echo '</pre><hr />'; + + $workbook = $xml->children($namespacesContent['office']); + foreach ($workbook->body->spreadsheet as $workbookData) { + $workbookData = $workbookData->children($namespacesContent['table']); + $worksheetID = 0; + foreach ($workbookData->table as $worksheetDataSet) { + $worksheetData = $worksheetDataSet->children($namespacesContent['table']); +// print_r($worksheetData); +// echo '<br />'; + $worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']); +// print_r($worksheetDataAttributes); +// echo '<br />'; + if ((isset($this->loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) && + (!in_array($worksheetDataAttributes['name'], $this->loadSheetsOnly))) { + continue; + } + +// echo '<h2>Worksheet '.$worksheetDataAttributes['name'].'</h2>'; + // Create new Worksheet + $objPHPExcel->createSheet(); + $objPHPExcel->setActiveSheetIndex($worksheetID); + if (isset($worksheetDataAttributes['name'])) { + $worksheetName = (string) $worksheetDataAttributes['name']; + // Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in + // formula cells... during the load, all formulae should be correct, and we're simply + // bringing the worksheet name in line with the formula, not the reverse + $objPHPExcel->getActiveSheet()->setTitle($worksheetName, false); + } + + $rowID = 1; + foreach ($worksheetData as $key => $rowData) { +// echo '<b>'.$key.'</b><br />'; + switch ($key) { + case 'table-header-rows': + foreach ($rowData as $key => $cellData) { + $rowData = $cellData; + break; + } + case 'table-row': + $rowDataTableAttributes = $rowData->attributes($namespacesContent['table']); + $rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ? $rowDataTableAttributes['number-rows-repeated'] : 1; + $columnID = 'A'; + foreach ($rowData as $key => $cellData) { + if ($this->getReadFilter() !== null) { + if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) { + continue; + } + } + +// echo '<b>'.$columnID.$rowID.'</b><br />'; + $cellDataText = (isset($namespacesContent['text'])) ? $cellData->children($namespacesContent['text']) : ''; + $cellDataOffice = $cellData->children($namespacesContent['office']); + $cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']); + $cellDataTableAttributes = $cellData->attributes($namespacesContent['table']); + +// echo 'Office Attributes: '; +// print_r($cellDataOfficeAttributes); +// echo '<br />Table Attributes: '; +// print_r($cellDataTableAttributes); +// echo '<br />Cell Data Text'; +// print_r($cellDataText); +// echo '<br />'; +// + $type = $formatting = $hyperlink = null; + $hasCalculatedValue = false; + $cellDataFormula = ''; + if (isset($cellDataTableAttributes['formula'])) { + $cellDataFormula = $cellDataTableAttributes['formula']; + $hasCalculatedValue = true; + } + + if (isset($cellDataOffice->annotation)) { +// echo 'Cell has comment<br />'; + $annotationText = $cellDataOffice->annotation->children($namespacesContent['text']); + $textArray = array(); + foreach ($annotationText as $t) { + if (isset($t->span)) { + foreach ($t->span as $text) { + $textArray[] = (string)$text; + } + } else { + $textArray[] = (string) $t; + } + } + $text = implode("\n", $textArray); +// echo $text, '<br />'; + $objPHPExcel->getActiveSheet()->getComment($columnID.$rowID)->setText($this->parseRichText($text)); +// ->setAuthor( $author ) + } + + if (isset($cellDataText->p)) { + // Consolidate if there are multiple p records (maybe with spans as well) + $dataArray = array(); + // Text can have multiple text:p and within those, multiple text:span. + // text:p newlines, but text:span does not. + // Also, here we assume there is no text data is span fields are specified, since + // we have no way of knowing proper positioning anyway. + foreach ($cellDataText->p as $pData) { + if (isset($pData->span)) { + // span sections do not newline, so we just create one large string here + $spanSection = ""; + foreach ($pData->span as $spanData) { + $spanSection .= $spanData; + } + array_push($dataArray, $spanSection); + } else { + array_push($dataArray, $pData); + } + } + $allCellDataText = implode($dataArray, "\n"); + +// echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'<br />'; + switch ($cellDataOfficeAttributes['value-type']) { + case 'string': + $type = PHPExcel_Cell_DataType::TYPE_STRING; + $dataValue = $allCellDataText; + if (isset($dataValue->a)) { + $dataValue = $dataValue->a; + $cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']); + $hyperlink = $cellXLinkAttributes['href']; + } + break; + case 'boolean': + $type = PHPExcel_Cell_DataType::TYPE_BOOL; + $dataValue = ($allCellDataText == 'TRUE') ? true : false; + break; + case 'percentage': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + $dataValue = (integer) $dataValue; + } + $formatting = PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00; + break; + case 'currency': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + $dataValue = (integer) $dataValue; + } + $formatting = PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE; + break; + case 'float': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = (float) $cellDataOfficeAttributes['value']; + if (floor($dataValue) == $dataValue) { + if ($dataValue == (integer) $dataValue) { + $dataValue = (integer) $dataValue; + } else { + $dataValue = (float) $dataValue; + } + } + break; + case 'date': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT); + $dateObj->setTimeZone($timezoneObj); + list($year, $month, $day, $hour, $minute, $second) = explode(' ', $dateObj->format('Y m d H i s')); + $dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day, $hour, $minute, $second); + if ($dataValue != floor($dataValue)) { + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15.' '.PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4; + } else { + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15; + } + break; + case 'time': + $type = PHPExcel_Cell_DataType::TYPE_NUMERIC; + $dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 '.implode(':', sscanf($cellDataOfficeAttributes['time-value'], 'PT%dH%dM%dS')))); + $formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4; + break; + } +// echo 'Data value is '.$dataValue.'<br />'; +// if ($hyperlink !== null) { +// echo 'Hyperlink is '.$hyperlink.'<br />'; +// } + } else { + $type = PHPExcel_Cell_DataType::TYPE_NULL; + $dataValue = null; + } + + if ($hasCalculatedValue) { + $type = PHPExcel_Cell_DataType::TYPE_FORMULA; +// echo 'Formula: ', $cellDataFormula, PHP_EOL; + $cellDataFormula = substr($cellDataFormula, strpos($cellDataFormula, ':=')+1); + $temp = explode('"', $cellDataFormula); + $tKey = false; + foreach ($temp as &$value) { + // Only replace in alternate array entries (i.e. non-quoted blocks) + if ($tKey = !$tKey) { + $value = preg_replace('/\[([^\.]+)\.([^\.]+):\.([^\.]+)\]/Ui', '$1!$2:$3', $value); // Cell range reference in another sheet + $value = preg_replace('/\[([^\.]+)\.([^\.]+)\]/Ui', '$1!$2', $value); // Cell reference in another sheet + $value = preg_replace('/\[\.([^\.]+):\.([^\.]+)\]/Ui', '$1:$2', $value); // Cell range reference + $value = preg_replace('/\[\.([^\.]+)\]/Ui', '$1', $value); // Simple cell reference + $value = PHPExcel_Calculation::translateSeparator(';', ',', $value, $inBraces); + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"', $temp); +// echo 'Adjusted Formula: ', $cellDataFormula, PHP_EOL; + } + + $colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ? $cellDataTableAttributes['number-columns-repeated'] : 1; + if ($type !== null) { + for ($i = 0; $i < $colRepeats; ++$i) { + if ($i > 0) { + ++$columnID; + } + if ($type !== PHPExcel_Cell_DataType::TYPE_NULL) { + for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) { + $rID = $rowID + $rowAdjust; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue), $type); + if ($hasCalculatedValue) { +// echo 'Forumla result is '.$dataValue.'<br />'; + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setCalculatedValue($dataValue); + } + if ($formatting !== null) { + $objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode($formatting); + } else { + $objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL); + } + if ($hyperlink !== null) { + $objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->getHyperlink()->setUrl($hyperlink); + } + } + } + } + } + + // Merged cells + if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) { + if (($type !== PHPExcel_Cell_DataType::TYPE_NULL) || (!$this->readDataOnly)) { + $columnTo = $columnID; + if (isset($cellDataTableAttributes['number-columns-spanned'])) { + $columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] -2); + } + $rowTo = $rowID; + if (isset($cellDataTableAttributes['number-rows-spanned'])) { + $rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1; + } + $cellRange = $columnID.$rowID.':'.$columnTo.$rowTo; + $objPHPExcel->getActiveSheet()->mergeCells($cellRange); + } + } + + ++$columnID; + } + $rowID += $rowRepeats; + break; + } + } + ++$worksheetID; + } + } + + // Return + return $objPHPExcel; + } + + private function parseRichText($is = '') + { + $value = new PHPExcel_RichText(); + + $value->createText($is); + + return $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/SYLK.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/SYLK.php new file mode 100644 index 00000000..eb7ef1af --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Reader/SYLK.php @@ -0,0 +1,478 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Reader_SYLK + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Reader + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Reader_SYLK extends PHPExcel_Reader_Abstract implements PHPExcel_Reader_IReader +{ + /** + * Input encoding + * + * @var string + */ + private $inputEncoding = 'ANSI'; + + /** + * Sheet index to read + * + * @var int + */ + private $sheetIndex = 0; + + /** + * Formats + * + * @var array + */ + private $formats = array(); + + /** + * Format Count + * + * @var int + */ + private $format = 0; + + /** + * Create a new PHPExcel_Reader_SYLK + */ + public function __construct() + { + $this->readFilter = new PHPExcel_Reader_DefaultReadFilter(); + } + + /** + * Validate that the current file is a SYLK file + * + * @return boolean + */ + protected function isValidFormat() + { + // Read sample data (first 2 KB will do) + $data = fread($this->fileHandle, 2048); + + // Count delimiters in file + $delimiterCount = substr_count($data, ';'); + if ($delimiterCount < 1) { + return false; + } + + // Analyze first line looking for ID; signature + $lines = explode("\n", $data); + if (substr($lines[0], 0, 4) != 'ID;P') { + return false; + } + + return true; + } + + /** + * Set input encoding + * + * @param string $pValue Input encoding + */ + public function setInputEncoding($pValue = 'ANSI') + { + $this->inputEncoding = $pValue; + return $this; + } + + /** + * Get input encoding + * + * @return string + */ + public function getInputEncoding() + { + return $this->inputEncoding; + } + + /** + * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) + * + * @param string $pFilename + * @throws PHPExcel_Reader_Exception + */ + public function listWorksheetInfo($pFilename) + { + // Open file + $this->openFile($pFilename); + if (!$this->isValidFormat()) { + fclose($this->fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->fileHandle; + rewind($fileHandle); + + $worksheetInfo = array(); + $worksheetInfo[0]['worksheetName'] = 'Worksheet'; + $worksheetInfo[0]['lastColumnLetter'] = 'A'; + $worksheetInfo[0]['lastColumnIndex'] = 0; + $worksheetInfo[0]['totalRows'] = 0; + $worksheetInfo[0]['totalColumns'] = 0; + + // Loop through file + $rowData = array(); + + // loop through one row (line) at a time in the file + $rowIndex = 0; + while (($rowData = fgets($fileHandle)) !== false) { + $columnIndex = 0; + + // convert SYLK encoded $rowData to UTF-8 + $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); + + // explode each row at semicolons while taking into account that literal semicolon (;) + // is escaped like this (;;) + $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); + + $dataType = array_shift($rowData); + if ($dataType == 'C') { + // Read cell value data + foreach ($rowData as $rowDatum) { + switch ($rowDatum{0}) { + case 'C': + case 'X': + $columnIndex = substr($rowDatum, 1) - 1; + break; + case 'R': + case 'Y': + $rowIndex = substr($rowDatum, 1); + break; + } + + $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); + $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); + } + } + } + + $worksheetInfo[0]['lastColumnLetter'] = PHPExcel_Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); + $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; + + // Close file + fclose($fileHandle); + + return $worksheetInfo; + } + + /** + * Loads PHPExcel from file + * + * @param string $pFilename + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function load($pFilename) + { + // Create new PHPExcel + $objPHPExcel = new PHPExcel(); + + // Load into this instance + return $this->loadIntoExisting($pFilename, $objPHPExcel); + } + + /** + * Loads PHPExcel from file into PHPExcel instance + * + * @param string $pFilename + * @param PHPExcel $objPHPExcel + * @return PHPExcel + * @throws PHPExcel_Reader_Exception + */ + public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel) + { + // Open file + $this->openFile($pFilename); + if (!$this->isValidFormat()) { + fclose($this->fileHandle); + throw new PHPExcel_Reader_Exception($pFilename . " is an Invalid Spreadsheet file."); + } + $fileHandle = $this->fileHandle; + rewind($fileHandle); + + // Create new PHPExcel + while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) { + $objPHPExcel->createSheet(); + } + $objPHPExcel->setActiveSheetIndex($this->sheetIndex); + + $fromFormats = array('\-', '\ '); + $toFormats = array('-', ' '); + + // Loop through file + $rowData = array(); + $column = $row = ''; + + // loop through one row (line) at a time in the file + while (($rowData = fgets($fileHandle)) !== false) { + // convert SYLK encoded $rowData to UTF-8 + $rowData = PHPExcel_Shared_String::SYLKtoUTF8($rowData); + + // explode each row at semicolons while taking into account that literal semicolon (;) + // is escaped like this (;;) + $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); + + $dataType = array_shift($rowData); + // Read shared styles + if ($dataType == 'P') { + $formatArray = array(); + foreach ($rowData as $rowDatum) { + switch ($rowDatum{0}) { + case 'P': + $formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); + break; + case 'E': + case 'F': + $formatArray['font']['name'] = substr($rowDatum, 1); + break; + case 'L': + $formatArray['font']['size'] = substr($rowDatum, 1); + break; + case 'S': + $styleSettings = substr($rowDatum, 1); + for ($i=0; $i<strlen($styleSettings); ++$i) { + switch ($styleSettings{$i}) { + case 'I': + $formatArray['font']['italic'] = true; + break; + case 'D': + $formatArray['font']['bold'] = true; + break; + case 'T': + $formatArray['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'B': + $formatArray['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'L': + $formatArray['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'R': + $formatArray['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + } + } + break; + } + } + $this->formats['P'.$this->format++] = $formatArray; + // Read cell value data + } elseif ($dataType == 'C') { + $hasCalculatedValue = false; + $cellData = $cellDataFormula = ''; + foreach ($rowData as $rowDatum) { + switch ($rowDatum{0}) { + case 'C': + case 'X': + $column = substr($rowDatum, 1); + break; + case 'R': + case 'Y': + $row = substr($rowDatum, 1); + break; + case 'K': + $cellData = substr($rowDatum, 1); + break; + case 'E': + $cellDataFormula = '='.substr($rowDatum, 1); + // Convert R1C1 style references to A1 style references (but only when not quoted) + $temp = explode('"', $cellDataFormula); + $key = false; + foreach ($temp as &$value) { + // Only count/replace in alternate array entries + if ($key = !$key) { + preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE); + // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way + // through the formula from left to right. Reversing means that we work right to left.through + // the formula + $cellReferences = array_reverse($cellReferences); + // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, + // then modify the formula to use that new reference + foreach ($cellReferences as $cellReference) { + $rowReference = $cellReference[2][0]; + // Empty R reference is the current row + if ($rowReference == '') { + $rowReference = $row; + } + // Bracketed R references are relative to the current row + if ($rowReference{0} == '[') { + $rowReference = $row + trim($rowReference, '[]'); + } + $columnReference = $cellReference[4][0]; + // Empty C reference is the current column + if ($columnReference == '') { + $columnReference = $column; + } + // Bracketed C references are relative to the current column + if ($columnReference{0} == '[') { + $columnReference = $column + trim($columnReference, '[]'); + } + $A1CellReference = PHPExcel_Cell::stringFromColumnIndex($columnReference-1).$rowReference; + + $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); + } + } + } + unset($value); + // Then rebuild the formula string + $cellDataFormula = implode('"', $temp); + $hasCalculatedValue = true; + break; + } + } + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + $cellData = PHPExcel_Calculation::unwrapResult($cellData); + + // Set cell value + $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); + if ($hasCalculatedValue) { + $cellData = PHPExcel_Calculation::unwrapResult($cellData); + $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); + } + // Read cell formatting + } elseif ($dataType == 'F') { + $formatStyle = $columnWidth = $styleSettings = ''; + $styleData = array(); + foreach ($rowData as $rowDatum) { + switch ($rowDatum{0}) { + case 'C': + case 'X': + $column = substr($rowDatum, 1); + break; + case 'R': + case 'Y': + $row = substr($rowDatum, 1); + break; + case 'P': + $formatStyle = $rowDatum; + break; + case 'W': + list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1)); + break; + case 'S': + $styleSettings = substr($rowDatum, 1); + for ($i=0; $i<strlen($styleSettings); ++$i) { + switch ($styleSettings{$i}) { + case 'I': + $styleData['font']['italic'] = true; + break; + case 'D': + $styleData['font']['bold'] = true; + break; + case 'T': + $styleData['borders']['top']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'B': + $styleData['borders']['bottom']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'L': + $styleData['borders']['left']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + case 'R': + $styleData['borders']['right']['style'] = PHPExcel_Style_Border::BORDER_THIN; + break; + } + } + break; + } + } + if (($formatStyle > '') && ($column > '') && ($row > '')) { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + if (isset($this->formats[$formatStyle])) { + $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]); + } + } + if ((!empty($styleData)) && ($column > '') && ($row > '')) { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($column-1); + $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); + } + if ($columnWidth > '') { + if ($startCol == $endCol) { + $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); + } else { + $startCol = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $endCol = PHPExcel_Cell::stringFromColumnIndex($endCol-1); + $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); + do { + $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); + } while ($startCol != $endCol); + } + } + } else { + foreach ($rowData as $rowDatum) { + switch ($rowDatum{0}) { + case 'C': + case 'X': + $column = substr($rowDatum, 1); + break; + case 'R': + case 'Y': + $row = substr($rowDatum, 1); + break; + } + } + } + } + + // Close file + fclose($fileHandle); + + // Return + return $objPHPExcel; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() + { + return $this->sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Reader_SYLK + */ + public function setSheetIndex($pValue = 0) + { + $this->sheetIndex = $pValue; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/ReferenceHelper.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/ReferenceHelper.php new file mode 100644 index 00000000..7d7de93b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/ReferenceHelper.php @@ -0,0 +1,913 @@ +<?php + +/** + * PHPExcel_ReferenceHelper (Singleton) + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_ReferenceHelper +{ + /** Constants */ + /** Regular Expressions */ + const REFHELPER_REGEXP_CELLREF = '((\w*|\'[^!]*\')!)?(?<![:a-z\$])(\$?[a-z]{1,3}\$?\d+)(?=[^:!\d\'])'; + const REFHELPER_REGEXP_CELLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}\$?\d+):(\$?[a-z]{1,3}\$?\d+)'; + const REFHELPER_REGEXP_ROWRANGE = '((\w*|\'[^!]*\')!)?(\$?\d+):(\$?\d+)'; + const REFHELPER_REGEXP_COLRANGE = '((\w*|\'[^!]*\')!)?(\$?[a-z]{1,3}):(\$?[a-z]{1,3})'; + + /** + * Instance of this class + * + * @var PHPExcel_ReferenceHelper + */ + private static $instance; + + /** + * Get an instance of this class + * + * @return PHPExcel_ReferenceHelper + */ + public static function getInstance() + { + if (!isset(self::$instance) || (self::$instance === null)) { + self::$instance = new PHPExcel_ReferenceHelper(); + } + + return self::$instance; + } + + /** + * Create a new PHPExcel_ReferenceHelper + */ + protected function __construct() + { + } + + /** + * Compare two column addresses + * Intended for use as a Callback function for sorting column addresses by column + * + * @param string $a First column to test (e.g. 'AA') + * @param string $b Second column to test (e.g. 'Z') + * @return integer + */ + public static function columnSort($a, $b) + { + return strcasecmp(strlen($a) . $a, strlen($b) . $b); + } + + /** + * Compare two column addresses + * Intended for use as a Callback function for reverse sorting column addresses by column + * + * @param string $a First column to test (e.g. 'AA') + * @param string $b Second column to test (e.g. 'Z') + * @return integer + */ + public static function columnReverseSort($a, $b) + { + return 1 - strcasecmp(strlen($a) . $a, strlen($b) . $b); + } + + /** + * Compare two cell addresses + * Intended for use as a Callback function for sorting cell addresses by column and row + * + * @param string $a First cell to test (e.g. 'AA1') + * @param string $b Second cell to test (e.g. 'Z1') + * @return integer + */ + public static function cellSort($a, $b) + { + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); + + if ($ar == $br) { + return strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); + } + return ($ar < $br) ? -1 : 1; + } + + /** + * Compare two cell addresses + * Intended for use as a Callback function for sorting cell addresses by column and row + * + * @param string $a First cell to test (e.g. 'AA1') + * @param string $b Second cell to test (e.g. 'Z1') + * @return integer + */ + public static function cellReverseSort($a, $b) + { + sscanf($a, '%[A-Z]%d', $ac, $ar); + sscanf($b, '%[A-Z]%d', $bc, $br); + + if ($ar == $br) { + return 1 - strcasecmp(strlen($ac) . $ac, strlen($bc) . $bc); + } + return ($ar < $br) ? 1 : -1; + } + + /** + * Test whether a cell address falls within a defined range of cells + * + * @param string $cellAddress Address of the cell we're testing + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @return boolean + */ + private static function cellAddressInDeleteRange($cellAddress, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols) + { + list($cellColumn, $cellRow) = PHPExcel_Cell::coordinateFromString($cellAddress); + $cellColumnIndex = PHPExcel_Cell::columnIndexFromString($cellColumn); + // Is cell within the range of rows/columns if we're deleting + if ($pNumRows < 0 && + ($cellRow >= ($beforeRow + $pNumRows)) && + ($cellRow < $beforeRow)) { + return true; + } elseif ($pNumCols < 0 && + ($cellColumnIndex >= ($beforeColumnIndex + $pNumCols)) && + ($cellColumnIndex < $beforeColumnIndex)) { + return true; + } + return false; + } + + /** + * Update page breaks when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustPageBreaks(PHPExcel_Worksheet $pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aBreaks = $pSheet->getBreaks(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aBreaks, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aBreaks, array('PHPExcel_ReferenceHelper','cellSort')); + + foreach ($aBreaks as $key => $value) { + if (self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + // If we're deleting, then clear any defined breaks that are within the range + // of rows/columns that we're deleting + $pSheet->setBreak($key, PHPExcel_Worksheet::BREAK_NONE); + } else { + // Otherwise update any affected breaks by inserting a new break at the appropriate point + // and removing the old affected break + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setBreak($newReference, $value) + ->setBreak($key, PHPExcel_Worksheet::BREAK_NONE); + } + } + } + } + + /** + * Update cell comments when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aComments = $pSheet->getComments(); + $aNewComments = array(); // the new array of all comments + + foreach ($aComments as $key => &$value) { + // Any comments inside a deleted range will be ignored + if (!self::cellAddressInDeleteRange($key, $beforeRow, $pNumRows, $beforeColumnIndex, $pNumCols)) { + // Otherwise build a new array of comments indexed by the adjusted cell reference + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $aNewComments[$newReference] = $value; + } + } + // Replace the comments array with the new set of comments + $pSheet->setComments($aNewComments); + } + + /** + * Update hyperlinks when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aHyperlinkCollection = $pSheet->getHyperlinkCollection(); + ($pNumCols > 0 || $pNumRows > 0) ? uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : uksort($aHyperlinkCollection, array('PHPExcel_ReferenceHelper','cellSort')); + + foreach ($aHyperlinkCollection as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setHyperlink($newReference, $value); + $pSheet->setHyperlink($key, null); + } + } + } + + /** + * Update data validations when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aDataValidationCollection = $pSheet->getDataValidationCollection(); + ($pNumCols > 0 || $pNumRows > 0) ? uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellReverseSort')) : uksort($aDataValidationCollection, array('PHPExcel_ReferenceHelper','cellSort')); + + foreach ($aDataValidationCollection as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->setDataValidation($newReference, $value); + $pSheet->setDataValidation($key, null); + } + } + } + + /** + * Update merged cells when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aMergeCells = $pSheet->getMergeCells(); + $aNewMergeCells = array(); // the new array of all merge cells + foreach ($aMergeCells as $key => &$value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + $aNewMergeCells[$newReference] = $newReference; + } + $pSheet->setMergeCells($aNewMergeCells); // replace the merge cells array + } + + /** + * Update protected cells when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aProtectedCells = $pSheet->getProtectedCells(); + ($pNumCols > 0 || $pNumRows > 0) ? + uksort($aProtectedCells, array('PHPExcel_ReferenceHelper','cellReverseSort')) : + uksort($aProtectedCells, array('PHPExcel_ReferenceHelper','cellSort')); + foreach ($aProtectedCells as $key => $value) { + $newReference = $this->updateCellReference($key, $pBefore, $pNumCols, $pNumRows); + if ($key != $newReference) { + $pSheet->protectCells($newReference, $value, true); + $pSheet->unprotectCells($key); + } + } + } + + /** + * Update column dimensions when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aColumnDimensions = array_reverse($pSheet->getColumnDimensions(), true); + if (!empty($aColumnDimensions)) { + foreach ($aColumnDimensions as $objColumnDimension) { + $newReference = $this->updateCellReference($objColumnDimension->getColumnIndex() . '1', $pBefore, $pNumCols, $pNumRows); + list($newReference) = PHPExcel_Cell::coordinateFromString($newReference); + if ($objColumnDimension->getColumnIndex() != $newReference) { + $objColumnDimension->setColumnIndex($newReference); + } + } + $pSheet->refreshColumnDimensions(); + } + } + + /** + * Update row dimensions when inserting/deleting rows/columns + * + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @param string $pBefore Insert/Delete before this cell address (e.g. 'A1') + * @param integer $beforeColumnIndex Index number of the column we're inserting/deleting before + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $beforeRow Number of the row we're inserting/deleting before + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + */ + protected function adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows) + { + $aRowDimensions = array_reverse($pSheet->getRowDimensions(), true); + if (!empty($aRowDimensions)) { + foreach ($aRowDimensions as $objRowDimension) { + $newReference = $this->updateCellReference('A' . $objRowDimension->getRowIndex(), $pBefore, $pNumCols, $pNumRows); + list(, $newReference) = PHPExcel_Cell::coordinateFromString($newReference); + if ($objRowDimension->getRowIndex() != $newReference) { + $objRowDimension->setRowIndex($newReference); + } + } + $pSheet->refreshRowDimensions(); + + $copyDimension = $pSheet->getRowDimension($beforeRow - 1); + for ($i = $beforeRow; $i <= $beforeRow - 1 + $pNumRows; ++$i) { + $newDimension = $pSheet->getRowDimension($i); + $newDimension->setRowHeight($copyDimension->getRowHeight()); + $newDimension->setVisible($copyDimension->getVisible()); + $newDimension->setOutlineLevel($copyDimension->getOutlineLevel()); + $newDimension->setCollapsed($copyDimension->getCollapsed()); + } + } + } + + /** + * Insert a new column or row, updating all possible related data + * + * @param string $pBefore Insert before this cell address (e.g. 'A1') + * @param integer $pNumCols Number of columns to insert/delete (negative values indicate deletion) + * @param integer $pNumRows Number of rows to insert/delete (negative values indicate deletion) + * @param PHPExcel_Worksheet $pSheet The worksheet that we're editing + * @throws PHPExcel_Exception + */ + public function insertNewBefore($pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, PHPExcel_Worksheet $pSheet = null) + { + $remove = ($pNumCols < 0 || $pNumRows < 0); + $aCellCollection = $pSheet->getCellCollection(); + + // Get coordinates of $pBefore + $beforeColumn = 'A'; + $beforeRow = 1; + list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore); + $beforeColumnIndex = PHPExcel_Cell::columnIndexFromString($beforeColumn); + + // Clear cells if we are removing columns or rows + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); + + // 1. Clear column strips if we are removing columns + if ($pNumCols < 0 && $beforeColumnIndex - 2 + $pNumCols > 0) { + for ($i = 1; $i <= $highestRow - 1; ++$i) { + for ($j = $beforeColumnIndex - 1 + $pNumCols; $j <= $beforeColumnIndex - 2; ++$j) { + $coordinate = PHPExcel_Cell::stringFromColumnIndex($j) . $i; + $pSheet->removeConditionalStyles($coordinate); + if ($pSheet->cellExists($coordinate)) { + $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL); + $pSheet->getCell($coordinate)->setXfIndex(0); + } + } + } + } + + // 2. Clear row strips if we are removing rows + if ($pNumRows < 0 && $beforeRow - 1 + $pNumRows > 0) { + for ($i = $beforeColumnIndex - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) { + for ($j = $beforeRow + $pNumRows; $j <= $beforeRow - 1; ++$j) { + $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . $j; + $pSheet->removeConditionalStyles($coordinate); + if ($pSheet->cellExists($coordinate)) { + $pSheet->getCell($coordinate)->setValueExplicit('', PHPExcel_Cell_DataType::TYPE_NULL); + $pSheet->getCell($coordinate)->setXfIndex(0); + } + } + } + } + + // Loop through cells, bottom-up, and change cell coordinates + if ($remove) { + // It's faster to reverse and pop than to use unshift, especially with large cell collections + $aCellCollection = array_reverse($aCellCollection); + } + while ($cellID = array_pop($aCellCollection)) { + $cell = $pSheet->getCell($cellID); + $cellIndex = PHPExcel_Cell::columnIndexFromString($cell->getColumn()); + + if ($cellIndex-1 + $pNumCols < 0) { + continue; + } + + // New coordinates + $newCoordinates = PHPExcel_Cell::stringFromColumnIndex($cellIndex-1 + $pNumCols) . ($cell->getRow() + $pNumRows); + + // Should the cell be updated? Move value and cellXf index from one cell to another. + if (($cellIndex >= $beforeColumnIndex) && ($cell->getRow() >= $beforeRow)) { + // Update cell styles + $pSheet->getCell($newCoordinates)->setXfIndex($cell->getXfIndex()); + + // Insert this cell at its new location + if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { + // Formula should be adjusted + $pSheet->getCell($newCoordinates) + ->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + } else { + // Formula should not be adjusted + $pSheet->getCell($newCoordinates)->setValue($cell->getValue()); + } + + // Clear the original cell + $pSheet->getCellCacheController()->deleteCacheData($cellID); + } else { + /* We don't need to update styles for rows/columns before our insertion position, + but we do still need to adjust any formulae in those cells */ + if ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA) { + // Formula should be adjusted + $cell->setValue($this->updateFormulaReferences($cell->getValue(), $pBefore, $pNumCols, $pNumRows, $pSheet->getTitle())); + } + + } + } + + // Duplicate styles for the newly inserted cells + $highestColumn = $pSheet->getHighestColumn(); + $highestRow = $pSheet->getHighestRow(); + + if ($pNumCols > 0 && $beforeColumnIndex - 2 > 0) { + for ($i = $beforeRow; $i <= $highestRow - 1; ++$i) { + // Style + $coordinate = PHPExcel_Cell::stringFromColumnIndex($beforeColumnIndex - 2) . $i; + if ($pSheet->cellExists($coordinate)) { + $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? + $pSheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeColumnIndex - 1; $j <= $beforeColumnIndex - 2 + $pNumCols; ++$j) { + $pSheet->getCellByColumnAndRow($j, $i)->setXfIndex($xfIndex); + if ($conditionalStyles) { + $cloned = array(); + foreach ($conditionalStyles as $conditionalStyle) { + $cloned[] = clone $conditionalStyle; + } + $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($j) . $i, $cloned); + } + } + } + + } + } + + if ($pNumRows > 0 && $beforeRow - 1 > 0) { + for ($i = $beforeColumnIndex - 1; $i <= PHPExcel_Cell::columnIndexFromString($highestColumn) - 1; ++$i) { + // Style + $coordinate = PHPExcel_Cell::stringFromColumnIndex($i) . ($beforeRow - 1); + if ($pSheet->cellExists($coordinate)) { + $xfIndex = $pSheet->getCell($coordinate)->getXfIndex(); + $conditionalStyles = $pSheet->conditionalStylesExists($coordinate) ? + $pSheet->getConditionalStyles($coordinate) : false; + for ($j = $beforeRow; $j <= $beforeRow - 1 + $pNumRows; ++$j) { + $pSheet->getCell(PHPExcel_Cell::stringFromColumnIndex($i) . $j)->setXfIndex($xfIndex); + if ($conditionalStyles) { + $cloned = array(); + foreach ($conditionalStyles as $conditionalStyle) { + $cloned[] = clone $conditionalStyle; + } + $pSheet->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($i) . $j, $cloned); + } + } + } + } + } + + // Update worksheet: column dimensions + $this->adjustColumnDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: row dimensions + $this->adjustRowDimensions($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: page breaks + $this->adjustPageBreaks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: comments + $this->adjustComments($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: hyperlinks + $this->adjustHyperlinks($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: data validations + $this->adjustDataValidations($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: merge cells + $this->adjustMergeCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: protected cells + $this->adjustProtectedCells($pSheet, $pBefore, $beforeColumnIndex, $pNumCols, $beforeRow, $pNumRows); + + // Update worksheet: autofilter + $autoFilter = $pSheet->getAutoFilter(); + $autoFilterRange = $autoFilter->getRange(); + if (!empty($autoFilterRange)) { + if ($pNumCols != 0) { + $autoFilterColumns = array_keys($autoFilter->getColumns()); + if (count($autoFilterColumns) > 0) { + sscanf($pBefore, '%[A-Z]%d', $column, $row); + $columnIndex = PHPExcel_Cell::columnIndexFromString($column); + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($autoFilterRange); + if ($columnIndex <= $rangeEnd[0]) { + if ($pNumCols < 0) { + // If we're actually deleting any columns that fall within the autofilter range, + // then we delete any rules for those columns + $deleteColumn = $columnIndex + $pNumCols - 1; + $deleteCount = abs($pNumCols); + for ($i = 1; $i <= $deleteCount; ++$i) { + if (in_array(PHPExcel_Cell::stringFromColumnIndex($deleteColumn), $autoFilterColumns)) { + $autoFilter->clearColumn(PHPExcel_Cell::stringFromColumnIndex($deleteColumn)); + } + ++$deleteColumn; + } + } + $startCol = ($columnIndex > $rangeStart[0]) ? $columnIndex : $rangeStart[0]; + + // Shuffle columns in autofilter range + if ($pNumCols > 0) { + // For insert, we shuffle from end to beginning to avoid overwriting + $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]); + + $startColRef = $startCol; + $endColRef = $rangeEnd[0]; + $toColRef = $rangeEnd[0]+$pNumCols; + + do { + $autoFilter->shiftColumn(PHPExcel_Cell::stringFromColumnIndex($endColRef-1), PHPExcel_Cell::stringFromColumnIndex($toColRef-1)); + --$endColRef; + --$toColRef; + } while ($startColRef <= $endColRef); + } else { + // For delete, we shuffle from beginning to end to avoid overwriting + $startColID = PHPExcel_Cell::stringFromColumnIndex($startCol-1); + $toColID = PHPExcel_Cell::stringFromColumnIndex($startCol+$pNumCols-1); + $endColID = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]); + do { + $autoFilter->shiftColumn($startColID, $toColID); + ++$startColID; + ++$toColID; + } while ($startColID != $endColID); + } + } + } + } + $pSheet->setAutoFilter($this->updateCellReference($autoFilterRange, $pBefore, $pNumCols, $pNumRows)); + } + + // Update worksheet: freeze pane + if ($pSheet->getFreezePane() != '') { + $pSheet->freezePane($this->updateCellReference($pSheet->getFreezePane(), $pBefore, $pNumCols, $pNumRows)); + } + + // Page setup + if ($pSheet->getPageSetup()->isPrintAreaSet()) { + $pSheet->getPageSetup()->setPrintArea($this->updateCellReference($pSheet->getPageSetup()->getPrintArea(), $pBefore, $pNumCols, $pNumRows)); + } + + // Update worksheet: drawings + $aDrawings = $pSheet->getDrawingCollection(); + foreach ($aDrawings as $objDrawing) { + $newReference = $this->updateCellReference($objDrawing->getCoordinates(), $pBefore, $pNumCols, $pNumRows); + if ($objDrawing->getCoordinates() != $newReference) { + $objDrawing->setCoordinates($newReference); + } + } + + // Update workbook: named ranges + if (count($pSheet->getParent()->getNamedRanges()) > 0) { + foreach ($pSheet->getParent()->getNamedRanges() as $namedRange) { + if ($namedRange->getWorksheet()->getHashCode() == $pSheet->getHashCode()) { + $namedRange->setRange($this->updateCellReference($namedRange->getRange(), $pBefore, $pNumCols, $pNumRows)); + } + } + } + + // Garbage collect + $pSheet->garbageCollect(); + } + + /** + * Update references within formulas + * + * @param string $pFormula Formula to update + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to insert + * @param int $pNumRows Number of rows to insert + * @param string $sheetName Worksheet name/title + * @return string Updated formula + * @throws PHPExcel_Exception + */ + public function updateFormulaReferences($pFormula = '', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0, $sheetName = '') + { + // Update cell references in the formula + $formulaBlocks = explode('"', $pFormula); + $i = false; + foreach ($formulaBlocks as &$formulaBlock) { + // Ignore blocks that were enclosed in quotes (alternating entries in the $formulaBlocks array after the explode) + if ($i = !$i) { + $adjustCount = 0; + $newCellTokens = $cellTokens = array(); + // Search for row ranges (e.g. 'Sheet1'!3:5 or 3:5) with or without $ absolutes (e.g. $3:5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_ROWRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach ($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = substr($this->updateCellReference('$A'.$match[3], $pBefore, $pNumCols, $pNumRows), 2); + $modified4 = substr($this->updateCellReference('$A'.$match[4], $pBefore, $pNumCols, $pNumRows), 2); + + if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { + if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = 100000; + $row = 10000000 + trim($match[3], '$'); + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<!\d\$\!)'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + // Search for column ranges (e.g. 'Sheet1'!C:E or C:E) with or without $ absolutes (e.g. $C:E) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_COLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach ($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = substr($this->updateCellReference($match[3].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + $modified4 = substr($this->updateCellReference($match[4].'$1', $pBefore, $pNumCols, $pNumRows), 0, -2); + + if ($match[3].':'.$match[4] !== $modified3.':'.$modified4) { + if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($match[3], '$')) + 100000; + $row = 10000000; + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?![A-Z])/i'; + ++$adjustCount; + } + } + } + } + // Search for cell ranges (e.g. 'Sheet1'!A3:C5 or A3:C5) with or without $ absolutes (e.g. $A1:C$5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLRANGE.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + if ($matchCount > 0) { + foreach ($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3].':'.$match[4]; + $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); + $modified4 = $this->updateCellReference($match[4], $pBefore, $pNumCols, $pNumRows); + + if ($match[3].$match[4] !== $modified3.$modified4) { + if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3.':'.$modified4; + list($column, $row) = PHPExcel_Cell::coordinateFromString($match[3]); + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($column, '$')) + 100000; + $row = trim($row, '$') + 10000000; + $cellIndex = $column.$row; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z]\$\!)'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + // Search for cell references (e.g. 'Sheet1'!A3 or C5) with or without $ absolutes (e.g. $A1 or C$5) + $matchCount = preg_match_all('/'.self::REFHELPER_REGEXP_CELLREF.'/i', ' '.$formulaBlock.' ', $matches, PREG_SET_ORDER); + + if ($matchCount > 0) { + foreach ($matches as $match) { + $fromString = ($match[2] > '') ? $match[2].'!' : ''; + $fromString .= $match[3]; + + $modified3 = $this->updateCellReference($match[3], $pBefore, $pNumCols, $pNumRows); + if ($match[3] !== $modified3) { + if (($match[2] == '') || (trim($match[2], "'") == $sheetName)) { + $toString = ($match[2] > '') ? $match[2].'!' : ''; + $toString .= $modified3; + list($column, $row) = PHPExcel_Cell::coordinateFromString($match[3]); + // Max worksheet size is 1,048,576 rows by 16,384 columns in Excel 2007, so our adjustments need to be at least one digit more + $column = PHPExcel_Cell::columnIndexFromString(trim($column, '$')) + 100000; + $row = trim($row, '$') + 10000000; + $cellIndex = $row . $column; + + $newCellTokens[$cellIndex] = preg_quote($toString); + $cellTokens[$cellIndex] = '/(?<![A-Z\$\!])'.preg_quote($fromString).'(?!\d)/i'; + ++$adjustCount; + } + } + } + } + if ($adjustCount > 0) { + if ($pNumCols > 0 || $pNumRows > 0) { + krsort($cellTokens); + krsort($newCellTokens); + } else { + ksort($cellTokens); + ksort($newCellTokens); + } // Update cell references in the formula + $formulaBlock = str_replace('\\', '', preg_replace($cellTokens, $newCellTokens, $formulaBlock)); + } + } + } + unset($formulaBlock); + + // Then rebuild the formula string + return implode('"', $formulaBlocks); + } + + /** + * Update cell reference + * + * @param string $pCellRange Cell range + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell range + * @throws PHPExcel_Exception + */ + public function updateCellReference($pCellRange = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { + // Is it in another worksheet? Will not have to update anything. + if (strpos($pCellRange, "!") !== false) { + return $pCellRange; + // Is it a range or a single cell? + } elseif (strpos($pCellRange, ':') === false && strpos($pCellRange, ',') === false) { + // Single cell + return $this->updateSingleCellReference($pCellRange, $pBefore, $pNumCols, $pNumRows); + } elseif (strpos($pCellRange, ':') !== false || strpos($pCellRange, ',') !== false) { + // Range + return $this->updateCellRange($pCellRange, $pBefore, $pNumCols, $pNumRows); + } else { + // Return original + return $pCellRange; + } + } + + /** + * Update named formulas (i.e. containing worksheet references / named ranges) + * + * @param PHPExcel $pPhpExcel Object to update + * @param string $oldName Old name (name to replace) + * @param string $newName New name + */ + public function updateNamedFormulas(PHPExcel $pPhpExcel, $oldName = '', $newName = '') + { + if ($oldName == '') { + return; + } + + foreach ($pPhpExcel->getWorksheetIterator() as $sheet) { + foreach ($sheet->getCellCollection(false) as $cellID) { + $cell = $sheet->getCell($cellID); + if (($cell !== null) && ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_FORMULA)) { + $formula = $cell->getValue(); + if (strpos($formula, $oldName) !== false) { + $formula = str_replace("'" . $oldName . "'!", "'" . $newName . "'!", $formula); + $formula = str_replace($oldName . "!", $newName . "!", $formula); + $cell->setValueExplicit($formula, PHPExcel_Cell_DataType::TYPE_FORMULA); + } + } + } + } + } + + /** + * Update cell range + * + * @param string $pCellRange Cell range (e.g. 'B2:D4', 'B:C' or '2:3') + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell range + * @throws PHPExcel_Exception + */ + private function updateCellRange($pCellRange = 'A1:A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { + if (strpos($pCellRange, ':') !== false || strpos($pCellRange, ',') !== false) { + // Update range + $range = PHPExcel_Cell::splitRange($pCellRange); + $ic = count($range); + for ($i = 0; $i < $ic; ++$i) { + $jc = count($range[$i]); + for ($j = 0; $j < $jc; ++$j) { + if (ctype_alpha($range[$i][$j])) { + $r = PHPExcel_Cell::coordinateFromString($this->updateSingleCellReference($range[$i][$j].'1', $pBefore, $pNumCols, $pNumRows)); + $range[$i][$j] = $r[0]; + } elseif (ctype_digit($range[$i][$j])) { + $r = PHPExcel_Cell::coordinateFromString($this->updateSingleCellReference('A'.$range[$i][$j], $pBefore, $pNumCols, $pNumRows)); + $range[$i][$j] = $r[1]; + } else { + $range[$i][$j] = $this->updateSingleCellReference($range[$i][$j], $pBefore, $pNumCols, $pNumRows); + } + } + } + + // Recreate range string + return PHPExcel_Cell::buildRange($range); + } else { + throw new PHPExcel_Exception("Only cell ranges may be passed to this method."); + } + } + + /** + * Update single cell reference + * + * @param string $pCellReference Single cell reference + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to increment + * @param int $pNumRows Number of rows to increment + * @return string Updated cell reference + * @throws PHPExcel_Exception + */ + private function updateSingleCellReference($pCellReference = 'A1', $pBefore = 'A1', $pNumCols = 0, $pNumRows = 0) + { + if (strpos($pCellReference, ':') === false && strpos($pCellReference, ',') === false) { + // Get coordinates of $pBefore + list($beforeColumn, $beforeRow) = PHPExcel_Cell::coordinateFromString($pBefore); + + // Get coordinates of $pCellReference + list($newColumn, $newRow) = PHPExcel_Cell::coordinateFromString($pCellReference); + + // Verify which parts should be updated + $updateColumn = (($newColumn{0} != '$') && ($beforeColumn{0} != '$') && (PHPExcel_Cell::columnIndexFromString($newColumn) >= PHPExcel_Cell::columnIndexFromString($beforeColumn))); + $updateRow = (($newRow{0} != '$') && ($beforeRow{0} != '$') && $newRow >= $beforeRow); + + // Create new column reference + if ($updateColumn) { + $newColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($newColumn) - 1 + $pNumCols); + } + + // Create new row reference + if ($updateRow) { + $newRow = $newRow + $pNumRows; + } + + // Return new reference + return $newColumn . $newRow; + } else { + throw new PHPExcel_Exception("Only single cell references may be passed to this method."); + } + } + + /** + * __clone implementation. Cloning should not be allowed in a Singleton! + * + * @throws PHPExcel_Exception + */ + final public function __clone() + { + throw new PHPExcel_Exception("Cloning a Singleton is not allowed!"); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText.php new file mode 100644 index 00000000..74a3534a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText.php @@ -0,0 +1,191 @@ +<?php + +/** + * PHPExcel_RichText + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_RichText implements PHPExcel_IComparable +{ + /** + * Rich text elements + * + * @var PHPExcel_RichText_ITextElement[] + */ + private $richTextElements; + + /** + * Create a new PHPExcel_RichText instance + * + * @param PHPExcel_Cell $pCell + * @throws PHPExcel_Exception + */ + public function __construct(PHPExcel_Cell $pCell = null) + { + // Initialise variables + $this->richTextElements = array(); + + // Rich-Text string attached to cell? + if ($pCell !== null) { + // Add cell text and style + if ($pCell->getValue() != "") { + $objRun = new PHPExcel_RichText_Run($pCell->getValue()); + $objRun->setFont(clone $pCell->getParent()->getStyle($pCell->getCoordinate())->getFont()); + $this->addText($objRun); + } + + // Set parent value + $pCell->setValueExplicit($this, PHPExcel_Cell_DataType::TYPE_STRING); + } + } + + /** + * Add text + * + * @param PHPExcel_RichText_ITextElement $pText Rich text element + * @throws PHPExcel_Exception + * @return PHPExcel_RichText + */ + public function addText(PHPExcel_RichText_ITextElement $pText = null) + { + $this->richTextElements[] = $pText; + return $this; + } + + /** + * Create text + * + * @param string $pText Text + * @return PHPExcel_RichText_TextElement + * @throws PHPExcel_Exception + */ + public function createText($pText = '') + { + $objText = new PHPExcel_RichText_TextElement($pText); + $this->addText($objText); + return $objText; + } + + /** + * Create text run + * + * @param string $pText Text + * @return PHPExcel_RichText_Run + * @throws PHPExcel_Exception + */ + public function createTextRun($pText = '') + { + $objText = new PHPExcel_RichText_Run($pText); + $this->addText($objText); + return $objText; + } + + /** + * Get plain text + * + * @return string + */ + public function getPlainText() + { + // Return value + $returnValue = ''; + + // Loop through all PHPExcel_RichText_ITextElement + foreach ($this->richTextElements as $text) { + $returnValue .= $text->getText(); + } + + // Return + return $returnValue; + } + + /** + * Convert to string + * + * @return string + */ + public function __toString() + { + return $this->getPlainText(); + } + + /** + * Get Rich Text elements + * + * @return PHPExcel_RichText_ITextElement[] + */ + public function getRichTextElements() + { + return $this->richTextElements; + } + + /** + * Set Rich Text elements + * + * @param PHPExcel_RichText_ITextElement[] $pElements Array of elements + * @throws PHPExcel_Exception + * @return PHPExcel_RichText + */ + public function setRichTextElements($pElements = null) + { + if (is_array($pElements)) { + $this->richTextElements = $pElements; + } else { + throw new PHPExcel_Exception("Invalid PHPExcel_RichText_ITextElement[] array passed."); + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + $hashElements = ''; + foreach ($this->richTextElements as $element) { + $hashElements .= $element->getHashCode(); + } + + return md5( + $hashElements . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/ITextElement.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/ITextElement.php new file mode 100644 index 00000000..5db34320 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/ITextElement.php @@ -0,0 +1,56 @@ +<?php + +/** + * PHPExcel_RichText_ITextElement + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_RichText_ITextElement +{ + /** + * Get text + * + * @return string Text + */ + public function getText(); + + /** + * Set text + * + * @param $pText string Text + * @return PHPExcel_RichText_ITextElement + */ + public function setText($pText = ''); + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont(); + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode(); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/Run.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/Run.php new file mode 100644 index 00000000..5737bb0d --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/Run.php @@ -0,0 +1,98 @@ +<?php + +/** + * PHPExcel_RichText_Run + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_RichText_Run extends PHPExcel_RichText_TextElement implements PHPExcel_RichText_ITextElement +{ + /** + * Font + * + * @var PHPExcel_Style_Font + */ + private $font; + + /** + * Create a new PHPExcel_RichText_Run instance + * + * @param string $pText Text + */ + public function __construct($pText = '') + { + // Initialise variables + $this->setText($pText); + $this->font = new PHPExcel_Style_Font(); + } + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont() + { + return $this->font; + } + + /** + * Set font + * + * @param PHPExcel_Style_Font $pFont Font + * @throws PHPExcel_Exception + * @return PHPExcel_RichText_ITextElement + */ + public function setFont(PHPExcel_Style_Font $pFont = null) + { + $this->font = $pFont; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->getText() . + $this->font->getHashCode() . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/TextElement.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/TextElement.php new file mode 100644 index 00000000..f86e7031 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/RichText/TextElement.php @@ -0,0 +1,105 @@ +<?php + +/** + * PHPExcel_RichText_TextElement + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_RichText + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_RichText_TextElement implements PHPExcel_RichText_ITextElement +{ + /** + * Text + * + * @var string + */ + private $text; + + /** + * Create a new PHPExcel_RichText_TextElement instance + * + * @param string $pText Text + */ + public function __construct($pText = '') + { + // Initialise variables + $this->text = $pText; + } + + /** + * Get text + * + * @return string Text + */ + public function getText() + { + return $this->text; + } + + /** + * Set text + * + * @param $pText string Text + * @return PHPExcel_RichText_ITextElement + */ + public function setText($pText = '') + { + $this->text = $pText; + return $this; + } + + /** + * Get font + * + * @return PHPExcel_Style_Font + */ + public function getFont() + { + return null; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->text . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Settings.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Settings.php new file mode 100644 index 00000000..dcbc89fc --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Settings.php @@ -0,0 +1,389 @@ +<?php + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + +/** + * PHPExcel_Settings + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Settings + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Settings +{ + /** constants */ + /** Available Zip library classes */ + const PCLZIP = 'PHPExcel_Shared_ZipArchive'; + const ZIPARCHIVE = 'ZipArchive'; + + /** Optional Chart Rendering libraries */ + const CHART_RENDERER_JPGRAPH = 'jpgraph'; + + /** Optional PDF Rendering libraries */ + const PDF_RENDERER_TCPDF = 'tcPDF'; + const PDF_RENDERER_DOMPDF = 'DomPDF'; + const PDF_RENDERER_MPDF = 'mPDF'; + + + private static $chartRenderers = array( + self::CHART_RENDERER_JPGRAPH, + ); + + private static $pdfRenderers = array( + self::PDF_RENDERER_TCPDF, + self::PDF_RENDERER_DOMPDF, + self::PDF_RENDERER_MPDF, + ); + + + /** + * Name of the class used for Zip file management + * e.g. + * ZipArchive + * + * @var string + */ + private static $zipClass = self::ZIPARCHIVE; + + + /** + * Name of the external Library used for rendering charts + * e.g. + * jpgraph + * + * @var string + */ + private static $chartRendererName; + + /** + * Directory Path to the external Library used for rendering charts + * + * @var string + */ + private static $chartRendererPath; + + + /** + * Name of the external Library used for rendering PDF files + * e.g. + * mPDF + * + * @var string + */ + private static $pdfRendererName; + + /** + * Directory Path to the external Library used for rendering PDF files + * + * @var string + */ + private static $pdfRendererPath; + + /** + * Default options for libxml loader + * + * @var int + */ + private static $libXmlLoaderOptions = null; + + /** + * Set the Zip handler Class that PHPExcel should use for Zip file management (PCLZip or ZipArchive) + * + * @param string $zipClass The Zip handler class that PHPExcel should use for Zip file management + * e.g. PHPExcel_Settings::PCLZip or PHPExcel_Settings::ZipArchive + * @return boolean Success or failure + */ + public static function setZipClass($zipClass) + { + if (($zipClass === self::PCLZIP) || + ($zipClass === self::ZIPARCHIVE)) { + self::$zipClass = $zipClass; + return true; + } + return false; + } + + + /** + * Return the name of the Zip handler Class that PHPExcel is configured to use (PCLZip or ZipArchive) + * or Zip file management + * + * @return string Name of the Zip handler Class that PHPExcel is configured to use + * for Zip file management + * e.g. PHPExcel_Settings::PCLZip or PHPExcel_Settings::ZipArchive + */ + public static function getZipClass() + { + return self::$zipClass; + } + + + /** + * Return the name of the method that is currently configured for cell cacheing + * + * @return string Name of the cacheing method + */ + public static function getCacheStorageMethod() + { + return PHPExcel_CachedObjectStorageFactory::getCacheStorageMethod(); + } + + + /** + * Return the name of the class that is currently being used for cell cacheing + * + * @return string Name of the class currently being used for cacheing + */ + public static function getCacheStorageClass() + { + return PHPExcel_CachedObjectStorageFactory::getCacheStorageClass(); + } + + + /** + * Set the method that should be used for cell cacheing + * + * @param string $method Name of the cacheing method + * @param array $arguments Optional configuration arguments for the cacheing method + * @return boolean Success or failure + */ + public static function setCacheStorageMethod($method = PHPExcel_CachedObjectStorageFactory::cache_in_memory, $arguments = array()) + { + return PHPExcel_CachedObjectStorageFactory::initialize($method, $arguments); + } + + + /** + * Set the locale code to use for formula translations and any special formatting + * + * @param string $locale The locale code to use (e.g. "fr" or "pt_br" or "en_uk") + * @return boolean Success or failure + */ + public static function setLocale($locale = 'en_us') + { + return PHPExcel_Calculation::getInstance()->setLocale($locale); + } + + + /** + * Set details of the external library that PHPExcel should use for rendering charts + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + * @param string $libraryBaseDir Directory path to the library's base folder + * + * @return boolean Success or failure + */ + public static function setChartRenderer($libraryName, $libraryBaseDir) + { + if (!self::setChartRendererName($libraryName)) { + return false; + } + return self::setChartRendererPath($libraryBaseDir); + } + + + /** + * Identify to PHPExcel the external library to use for rendering charts + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + * + * @return boolean Success or failure + */ + public static function setChartRendererName($libraryName) + { + if (!in_array($libraryName, self::$chartRenderers)) { + return false; + } + self::$chartRendererName = $libraryName; + + return true; + } + + + /** + * Tell PHPExcel where to find the external library to use for rendering charts + * + * @param string $libraryBaseDir Directory path to the library's base folder + * @return boolean Success or failure + */ + public static function setChartRendererPath($libraryBaseDir) + { + if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) { + return false; + } + self::$chartRendererPath = $libraryBaseDir; + + return true; + } + + + /** + * Return the Chart Rendering Library that PHPExcel is currently configured to use (e.g. jpgraph) + * + * @return string|NULL Internal reference name of the Chart Rendering Library that PHPExcel is + * currently configured to use + * e.g. PHPExcel_Settings::CHART_RENDERER_JPGRAPH + */ + public static function getChartRendererName() + { + return self::$chartRendererName; + } + + + /** + * Return the directory path to the Chart Rendering Library that PHPExcel is currently configured to use + * + * @return string|NULL Directory Path to the Chart Rendering Library that PHPExcel is + * currently configured to use + */ + public static function getChartRendererPath() + { + return self::$chartRendererPath; + } + + + /** + * Set details of the external library that PHPExcel should use for rendering PDF files + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + * @param string $libraryBaseDir Directory path to the library's base folder + * + * @return boolean Success or failure + */ + public static function setPdfRenderer($libraryName, $libraryBaseDir) + { + if (!self::setPdfRendererName($libraryName)) { + return false; + } + return self::setPdfRendererPath($libraryBaseDir); + } + + + /** + * Identify to PHPExcel the external library to use for rendering PDF files + * + * @param string $libraryName Internal reference name of the library + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + * + * @return boolean Success or failure + */ + public static function setPdfRendererName($libraryName) + { + if (!in_array($libraryName, self::$pdfRenderers)) { + return false; + } + self::$pdfRendererName = $libraryName; + + return true; + } + + + /** + * Tell PHPExcel where to find the external library to use for rendering PDF files + * + * @param string $libraryBaseDir Directory path to the library's base folder + * @return boolean Success or failure + */ + public static function setPdfRendererPath($libraryBaseDir) + { + if ((file_exists($libraryBaseDir) === false) || (is_readable($libraryBaseDir) === false)) { + return false; + } + self::$pdfRendererPath = $libraryBaseDir; + + return true; + } + + + /** + * Return the PDF Rendering Library that PHPExcel is currently configured to use (e.g. dompdf) + * + * @return string|NULL Internal reference name of the PDF Rendering Library that PHPExcel is + * currently configured to use + * e.g. PHPExcel_Settings::PDF_RENDERER_TCPDF, + * PHPExcel_Settings::PDF_RENDERER_DOMPDF + * or PHPExcel_Settings::PDF_RENDERER_MPDF + */ + public static function getPdfRendererName() + { + return self::$pdfRendererName; + } + + /** + * Return the directory path to the PDF Rendering Library that PHPExcel is currently configured to use + * + * @return string|NULL Directory Path to the PDF Rendering Library that PHPExcel is + * currently configured to use + */ + public static function getPdfRendererPath() + { + return self::$pdfRendererPath; + } + + /** + * Set options for libxml loader + * + * @param int $options Options for libxml loader + */ + public static function setLibXmlLoaderOptions($options = null) + { + if (is_null($options) && defined('LIBXML_DTDLOAD')) { + $options = LIBXML_DTDLOAD | LIBXML_DTDATTR; + } + if (version_compare(PHP_VERSION, '5.2.11') >= 0) { + @libxml_disable_entity_loader((bool) $options); + } + self::$libXmlLoaderOptions = $options; + } + + /** + * Get defined options for libxml loader. + * Defaults to LIBXML_DTDLOAD | LIBXML_DTDATTR when not set explicitly. + * + * @return int Default options for libxml loader + */ + public static function getLibXmlLoaderOptions() + { + if (is_null(self::$libXmlLoaderOptions) && defined('LIBXML_DTDLOAD')) { + self::setLibXmlLoaderOptions(LIBXML_DTDLOAD | LIBXML_DTDATTR); + } elseif (is_null(self::$libXmlLoaderOptions)) { + self::$libXmlLoaderOptions = true; + } + if (version_compare(PHP_VERSION, '5.2.11') >= 0) { + @libxml_disable_entity_loader((bool) self::$libXmlLoaderOptions); + } + return self::$libXmlLoaderOptions; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/CodePage.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/CodePage.php new file mode 100644 index 00000000..b3e440e2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/CodePage.php @@ -0,0 +1,156 @@ +<?php + +/** + * PHPExcel_Shared_CodePage + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_CodePage +{ + /** + * Convert Microsoft Code Page Identifier to Code Page Name which iconv + * and mbstring understands + * + * @param integer $codePage Microsoft Code Page Indentifier + * @return string Code Page Name + * @throws PHPExcel_Exception + */ + public static function NumberToName($codePage = 1252) + { + switch ($codePage) { + case 367: + return 'ASCII'; // ASCII + case 437: + return 'CP437'; // OEM US + case 720: + throw new PHPExcel_Exception('Code page 720 not supported.'); // OEM Arabic + case 737: + return 'CP737'; // OEM Greek + case 775: + return 'CP775'; // OEM Baltic + case 850: + return 'CP850'; // OEM Latin I + case 852: + return 'CP852'; // OEM Latin II (Central European) + case 855: + return 'CP855'; // OEM Cyrillic + case 857: + return 'CP857'; // OEM Turkish + case 858: + return 'CP858'; // OEM Multilingual Latin I with Euro + case 860: + return 'CP860'; // OEM Portugese + case 861: + return 'CP861'; // OEM Icelandic + case 862: + return 'CP862'; // OEM Hebrew + case 863: + return 'CP863'; // OEM Canadian (French) + case 864: + return 'CP864'; // OEM Arabic + case 865: + return 'CP865'; // OEM Nordic + case 866: + return 'CP866'; // OEM Cyrillic (Russian) + case 869: + return 'CP869'; // OEM Greek (Modern) + case 874: + return 'CP874'; // ANSI Thai + case 932: + return 'CP932'; // ANSI Japanese Shift-JIS + case 936: + return 'CP936'; // ANSI Chinese Simplified GBK + case 949: + return 'CP949'; // ANSI Korean (Wansung) + case 950: + return 'CP950'; // ANSI Chinese Traditional BIG5 + case 1200: + return 'UTF-16LE'; // UTF-16 (BIFF8) + case 1250: + return 'CP1250'; // ANSI Latin II (Central European) + case 1251: + return 'CP1251'; // ANSI Cyrillic + case 0: + // CodePage is not always correctly set when the xls file was saved by Apple's Numbers program + case 1252: + return 'CP1252'; // ANSI Latin I (BIFF4-BIFF7) + case 1253: + return 'CP1253'; // ANSI Greek + case 1254: + return 'CP1254'; // ANSI Turkish + case 1255: + return 'CP1255'; // ANSI Hebrew + case 1256: + return 'CP1256'; // ANSI Arabic + case 1257: + return 'CP1257'; // ANSI Baltic + case 1258: + return 'CP1258'; // ANSI Vietnamese + case 1361: + return 'CP1361'; // ANSI Korean (Johab) + case 10000: + return 'MAC'; // Apple Roman + case 10001: + return 'CP932'; // Macintosh Japanese + case 10002: + return 'CP950'; // Macintosh Chinese Traditional + case 10003: + return 'CP1361'; // Macintosh Korean + case 10004: + return 'MACARABIC'; // Apple Arabic + case 10005: + return 'MACHEBREW'; // Apple Hebrew + case 10006: + return 'MACGREEK'; // Macintosh Greek + case 10007: + return 'MACCYRILLIC'; // Macintosh Cyrillic + case 10008: + return 'CP936'; // Macintosh - Simplified Chinese (GB 2312) + case 10010: + return 'MACROMANIA'; // Macintosh Romania + case 10017: + return 'MACUKRAINE'; // Macintosh Ukraine + case 10021: + return 'MACTHAI'; // Macintosh Thai + case 10029: + return 'MACCENTRALEUROPE'; // Macintosh Central Europe + case 10079: + return 'MACICELAND'; // Macintosh Icelandic + case 10081: + return 'MACTURKISH'; // Macintosh Turkish + case 10082: + return 'MACCROATIAN'; // Macintosh Croatian + case 21010: + return 'UTF-16LE'; // UTF-16 (BIFF8) This isn't correct, but some Excel writer libraries erroneously use Codepage 21010 for UTF-16LE + case 32768: + return 'MAC'; // Apple Roman + case 32769: + throw new PHPExcel_Exception('Code page 32769 not supported.'); // ANSI Latin I (BIFF2-BIFF3) + case 65000: + return 'UTF-7'; // Unicode (UTF-7) + case 65001: + return 'UTF-8'; // Unicode (UTF-8) + } + throw new PHPExcel_Exception('Unknown codepage: ' . $codePage); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Date.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Date.php new file mode 100644 index 00000000..b00a39a3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Date.php @@ -0,0 +1,418 @@ +<?php + +/** + * PHPExcel_Shared_Date + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Date +{ + /** constants */ + const CALENDAR_WINDOWS_1900 = 1900; // Base date of 1st Jan 1900 = 1.0 + const CALENDAR_MAC_1904 = 1904; // Base date of 2nd Jan 1904 = 1.0 + + /* + * Names of the months of the year, indexed by shortname + * Planned usage for locale settings + * + * @public + * @var string[] + */ + public static $monthNames = array( + 'Jan' => 'January', + 'Feb' => 'February', + 'Mar' => 'March', + 'Apr' => 'April', + 'May' => 'May', + 'Jun' => 'June', + 'Jul' => 'July', + 'Aug' => 'August', + 'Sep' => 'September', + 'Oct' => 'October', + 'Nov' => 'November', + 'Dec' => 'December', + ); + + /* + * Names of the months of the year, indexed by shortname + * Planned usage for locale settings + * + * @public + * @var string[] + */ + public static $numberSuffixes = array( + 'st', + 'nd', + 'rd', + 'th', + ); + + /* + * Base calendar year to use for calculations + * + * @private + * @var int + */ + protected static $excelBaseDate = self::CALENDAR_WINDOWS_1900; + + /** + * Set the Excel calendar (Windows 1900 or Mac 1904) + * + * @param integer $baseDate Excel base date (1900 or 1904) + * @return boolean Success or failure + */ + public static function setExcelCalendar($baseDate) + { + if (($baseDate == self::CALENDAR_WINDOWS_1900) || + ($baseDate == self::CALENDAR_MAC_1904)) { + self::$excelBaseDate = $baseDate; + return true; + } + return false; + } + + + /** + * Return the Excel calendar (Windows 1900 or Mac 1904) + * + * @return integer Excel base date (1900 or 1904) + */ + public static function getExcelCalendar() + { + return self::$excelBaseDate; + } + + + /** + * Convert a date from Excel to PHP + * + * @param integer $dateValue Excel date/time value + * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as + * a UST timestamp, or adjusted to UST + * @param string $timezone The timezone for finding the adjustment from UST + * @return integer PHP serialized date/time + */ + public static function ExcelToPHP($dateValue = 0, $adjustToTimezone = false, $timezone = null) + { + if (self::$excelBaseDate == self::CALENDAR_WINDOWS_1900) { + $myexcelBaseDate = 25569; + // Adjust for the spurious 29-Feb-1900 (Day 60) + if ($dateValue < 60) { + --$myexcelBaseDate; + } + } else { + $myexcelBaseDate = 24107; + } + + // Perform conversion + if ($dateValue >= 1) { + $utcDays = $dateValue - $myexcelBaseDate; + $returnValue = round($utcDays * 86400); + if (($returnValue <= PHP_INT_MAX) && ($returnValue >= -PHP_INT_MAX)) { + $returnValue = (integer) $returnValue; + } + } else { + $hours = round($dateValue * 24); + $mins = round($dateValue * 1440) - round($hours * 60); + $secs = round($dateValue * 86400) - round($hours * 3600) - round($mins * 60); + $returnValue = (integer) gmmktime($hours, $mins, $secs); + } + + $timezoneAdjustment = ($adjustToTimezone) ? + PHPExcel_Shared_TimeZone::getTimezoneAdjustment($timezone, $returnValue) : + 0; + + return $returnValue + $timezoneAdjustment; + } + + + /** + * Convert a date from Excel to a PHP Date/Time object + * + * @param integer $dateValue Excel date/time value + * @return DateTime PHP date/time object + */ + public static function ExcelToPHPObject($dateValue = 0) + { + $dateTime = self::ExcelToPHP($dateValue); + $days = floor($dateTime / 86400); + $time = round((($dateTime / 86400) - $days) * 86400); + $hours = round($time / 3600); + $minutes = round($time / 60) - ($hours * 60); + $seconds = round($time) - ($hours * 3600) - ($minutes * 60); + + $dateObj = date_create('1-Jan-1970+'.$days.' days'); + $dateObj->setTime($hours, $minutes, $seconds); + + return $dateObj; + } + + + /** + * Convert a date from PHP to Excel + * + * @param mixed $dateValue PHP serialized date/time or date object + * @param boolean $adjustToTimezone Flag indicating whether $dateValue should be treated as + * a UST timestamp, or adjusted to UST + * @param string $timezone The timezone for finding the adjustment from UST + * @return mixed Excel date/time value + * or boolean FALSE on failure + */ + public static function PHPToExcel($dateValue = 0, $adjustToTimezone = false, $timezone = null) + { + $saveTimeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + + $timezoneAdjustment = ($adjustToTimezone) ? + PHPExcel_Shared_TimeZone::getTimezoneAdjustment($timezone ? $timezone : $saveTimeZone, $dateValue) : + 0; + + $retValue = false; + if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) { + $dateValue->add(new DateInterval('PT' . $timezoneAdjustment . 'S')); + $retValue = self::FormattedPHPToExcel($dateValue->format('Y'), $dateValue->format('m'), $dateValue->format('d'), $dateValue->format('H'), $dateValue->format('i'), $dateValue->format('s')); + } elseif (is_numeric($dateValue)) { + $dateValue += $timezoneAdjustment; + $retValue = self::FormattedPHPToExcel(date('Y', $dateValue), date('m', $dateValue), date('d', $dateValue), date('H', $dateValue), date('i', $dateValue), date('s', $dateValue)); + } elseif (is_string($dateValue)) { + $retValue = self::stringToExcel($dateValue); + } + date_default_timezone_set($saveTimeZone); + + return $retValue; + } + + + /** + * FormattedPHPToExcel + * + * @param integer $year + * @param integer $month + * @param integer $day + * @param integer $hours + * @param integer $minutes + * @param integer $seconds + * @return integer Excel date/time value + */ + public static function FormattedPHPToExcel($year, $month, $day, $hours = 0, $minutes = 0, $seconds = 0) + { + if (self::$excelBaseDate == self::CALENDAR_WINDOWS_1900) { + // + // Fudge factor for the erroneous fact that the year 1900 is treated as a Leap Year in MS Excel + // This affects every date following 28th February 1900 + // + $excel1900isLeapYear = true; + if (($year == 1900) && ($month <= 2)) { + $excel1900isLeapYear = false; + } + $myexcelBaseDate = 2415020; + } else { + $myexcelBaseDate = 2416481; + $excel1900isLeapYear = false; + } + + // Julian base date Adjustment + if ($month > 2) { + $month -= 3; + } else { + $month += 9; + --$year; + } + + // Calculate the Julian Date, then subtract the Excel base date (JD 2415020 = 31-Dec-1899 Giving Excel Date of 0) + $century = substr($year, 0, 2); + $decade = substr($year, 2, 2); + $excelDate = floor((146097 * $century) / 4) + floor((1461 * $decade) / 4) + floor((153 * $month + 2) / 5) + $day + 1721119 - $myexcelBaseDate + $excel1900isLeapYear; + + $excelTime = (($hours * 3600) + ($minutes * 60) + $seconds) / 86400; + + return (float) $excelDate + $excelTime; + } + + + /** + * Is a given cell a date/time? + * + * @param PHPExcel_Cell $pCell + * @return boolean + */ + public static function isDateTime(PHPExcel_Cell $pCell) + { + return self::isDateTimeFormat( + $pCell->getWorksheet()->getStyle( + $pCell->getCoordinate() + )->getNumberFormat() + ); + } + + + /** + * Is a given number format a date/time? + * + * @param PHPExcel_Style_NumberFormat $pFormat + * @return boolean + */ + public static function isDateTimeFormat(PHPExcel_Style_NumberFormat $pFormat) + { + return self::isDateTimeFormatCode($pFormat->getFormatCode()); + } + + + private static $possibleDateFormatCharacters = 'eymdHs'; + + /** + * Is a given number format code a date/time? + * + * @param string $pFormatCode + * @return boolean + */ + public static function isDateTimeFormatCode($pFormatCode = '') + { + if (strtolower($pFormatCode) === strtolower(PHPExcel_Style_NumberFormat::FORMAT_GENERAL)) { + // "General" contains an epoch letter 'e', so we trap for it explicitly here (case-insensitive check) + return false; + } + if (preg_match('/[0#]E[+-]0/i', $pFormatCode)) { + // Scientific format + return false; + } + + // Switch on formatcode + switch ($pFormatCode) { + // Explicitly defined date formats + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDD2: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DDMMYYYY: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYSLASH: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMYMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DMMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_MYMINUS: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_DATETIME: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME1: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME2: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME3: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME5: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME6: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME7: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME8: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX14: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX16: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX17: + case PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22: + return true; + } + + // Typically number, currency or accounting (or occasionally fraction) formats + if ((substr($pFormatCode, 0, 1) == '_') || (substr($pFormatCode, 0, 2) == '0 ')) { + return false; + } + // Try checking for any of the date formatting characters that don't appear within square braces + if (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i', $pFormatCode)) { + // We might also have a format mask containing quoted strings... + // we don't want to test for any of our characters within the quoted blocks + if (strpos($pFormatCode, '"') !== false) { + $segMatcher = false; + foreach (explode('"', $pFormatCode) as $subVal) { + // Only test in alternate array entries (the non-quoted blocks) + if (($segMatcher = !$segMatcher) && + (preg_match('/(^|\])[^\[]*['.self::$possibleDateFormatCharacters.']/i', $subVal))) { + return true; + } + } + return false; + } + return true; + } + + // No date... + return false; + } + + + /** + * Convert a date/time string to Excel time + * + * @param string $dateValue Examples: '2009-12-31', '2009-12-31 15:59', '2009-12-31 15:59:10' + * @return float|FALSE Excel date/time serial value + */ + public static function stringToExcel($dateValue = '') + { + if (strlen($dateValue) < 2) { + return false; + } + if (!preg_match('/^(\d{1,4}[ \.\/\-][A-Z]{3,9}([ \.\/\-]\d{1,4})?|[A-Z]{3,9}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?|\d{1,4}[ \.\/\-]\d{1,4}([ \.\/\-]\d{1,4})?)( \d{1,2}:\d{1,2}(:\d{1,2})?)?$/iu', $dateValue)) { + return false; + } + + $dateValueNew = PHPExcel_Calculation_DateTime::DATEVALUE($dateValue); + + if ($dateValueNew === PHPExcel_Calculation_Functions::VALUE()) { + return false; + } + + if (strpos($dateValue, ':') !== false) { + $timeValue = PHPExcel_Calculation_DateTime::TIMEVALUE($dateValue); + if ($timeValue === PHPExcel_Calculation_Functions::VALUE()) { + return false; + } + $dateValueNew += $timeValue; + } + return $dateValueNew; + } + + /** + * Converts a month name (either a long or a short name) to a month number + * + * @param string $month Month name or abbreviation + * @return integer|string Month number (1 - 12), or the original string argument if it isn't a valid month name + */ + public static function monthStringToNumber($month) + { + $monthIndex = 1; + foreach (self::$monthNames as $shortMonthName => $longMonthName) { + if (($month === $longMonthName) || ($month === $shortMonthName)) { + return $monthIndex; + } + ++$monthIndex; + } + return $month; + } + + /** + * Strips an ordinal froma numeric value + * + * @param string $day Day number with an ordinal + * @return integer|string The integer value with any ordinal stripped, or the original string argument if it isn't a valid numeric + */ + public static function dayStringToNumber($day) + { + $strippedDayValue = (str_replace(self::$numberSuffixes, '', $day)); + if (is_numeric($strippedDayValue)) { + return (integer) $strippedDayValue; + } + return $day; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Drawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Drawing.php new file mode 100644 index 00000000..3e027b4a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Drawing.php @@ -0,0 +1,270 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Shared_Drawing + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Drawing +{ + /** + * Convert pixels to EMU + * + * @param int $pValue Value in pixels + * @return int Value in EMU + */ + public static function pixelsToEMU($pValue = 0) + { + return round($pValue * 9525); + } + + /** + * Convert EMU to pixels + * + * @param int $pValue Value in EMU + * @return int Value in pixels + */ + public static function EMUToPixels($pValue = 0) + { + if ($pValue != 0) { + return round($pValue / 9525); + } else { + return 0; + } + } + + /** + * Convert pixels to column width. Exact algorithm not known. + * By inspection of a real Excel file using Calibri 11, one finds 1000px ~ 142.85546875 + * This gives a conversion factor of 7. Also, we assume that pixels and font size are proportional. + * + * @param int $pValue Value in pixels + * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook + * @return int Value in cell dimension + */ + public static function pixelsToCellDimension($pValue = 0, PHPExcel_Style_Font $pDefaultFont) + { + // Font name and size + $name = $pDefaultFont->getName(); + $size = $pDefaultFont->getSize(); + + if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { + // Exact width can be determined + $colWidth = $pValue * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width'] / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px']; + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $colWidth = $pValue * 11 * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / $size; + } + + return $colWidth; + } + + /** + * Convert column width from (intrinsic) Excel units to pixels + * + * @param float $pValue Value in cell dimension + * @param PHPExcel_Style_Font $pDefaultFont Default font of the workbook + * @return int Value in pixels + */ + public static function cellDimensionToPixels($pValue = 0, PHPExcel_Style_Font $pDefaultFont) + { + // Font name and size + $name = $pDefaultFont->getName(); + $size = $pDefaultFont->getSize(); + + if (isset(PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size])) { + // Exact width can be determined + $colWidth = $pValue * PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['px'] / PHPExcel_Shared_Font::$defaultColumnWidths[$name][$size]['width']; + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $colWidth = $pValue * $size * PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['px'] / PHPExcel_Shared_Font::$defaultColumnWidths['Calibri'][11]['width'] / 11; + } + + // Round pixels to closest integer + $colWidth = (int) round($colWidth); + + return $colWidth; + } + + /** + * Convert pixels to points + * + * @param int $pValue Value in pixels + * @return int Value in points + */ + public static function pixelsToPoints($pValue = 0) + { + return $pValue * 0.67777777; + } + + /** + * Convert points to pixels + * + * @param int $pValue Value in points + * @return int Value in pixels + */ + public static function pointsToPixels($pValue = 0) + { + if ($pValue != 0) { + return (int) ceil($pValue * 1.333333333); + } else { + return 0; + } + } + + /** + * Convert degrees to angle + * + * @param int $pValue Degrees + * @return int Angle + */ + public static function degreesToAngle($pValue = 0) + { + return (int)round($pValue * 60000); + } + + /** + * Convert angle to degrees + * + * @param int $pValue Angle + * @return int Degrees + */ + public static function angleToDegrees($pValue = 0) + { + if ($pValue != 0) { + return round($pValue / 60000); + } else { + return 0; + } + } + + /** + * Create a new image from file. By alexander at alexauto dot nl + * + * @link http://www.php.net/manual/en/function.imagecreatefromwbmp.php#86214 + * @param string $filename Path to Windows DIB (BMP) image + * @return resource + */ + public static function imagecreatefrombmp($p_sFile) + { + // Load the image into a string + $file = fopen($p_sFile, "rb"); + $read = fread($file, 10); + while (!feof($file) && ($read<>"")) { + $read .= fread($file, 1024); + } + + $temp = unpack("H*", $read); + $hex = $temp[1]; + $header = substr($hex, 0, 108); + + // Process the header + // Structure: http://www.fastgraph.com/help/bmp_header_format.html + if (substr($header, 0, 4)=="424d") { + // Cut it in parts of 2 bytes + $header_parts = str_split($header, 2); + + // Get the width 4 bytes + $width = hexdec($header_parts[19].$header_parts[18]); + + // Get the height 4 bytes + $height = hexdec($header_parts[23].$header_parts[22]); + + // Unset the header params + unset($header_parts); + } + + // Define starting X and Y + $x = 0; + $y = 1; + + // Create newimage + $image = imagecreatetruecolor($width, $height); + + // Grab the body from the image + $body = substr($hex, 108); + + // Calculate if padding at the end-line is needed + // Divided by two to keep overview. + // 1 byte = 2 HEX-chars + $body_size = (strlen($body)/2); + $header_size = ($width*$height); + + // Use end-line padding? Only when needed + $usePadding = ($body_size>($header_size*3)+4); + + // Using a for-loop with index-calculation instaid of str_split to avoid large memory consumption + // Calculate the next DWORD-position in the body + for ($i = 0; $i < $body_size; $i += 3) { + // Calculate line-ending and padding + if ($x >= $width) { + // If padding needed, ignore image-padding + // Shift i to the ending of the current 32-bit-block + if ($usePadding) { + $i += $width%4; + } + + // Reset horizontal position + $x = 0; + + // Raise the height-position (bottom-up) + $y++; + + // Reached the image-height? Break the for-loop + if ($y > $height) { + break; + } + } + + // Calculation of the RGB-pixel (defined as BGR in image-data) + // Define $i_pos as absolute position in the body + $i_pos = $i * 2; + $r = hexdec($body[$i_pos+4].$body[$i_pos+5]); + $g = hexdec($body[$i_pos+2].$body[$i_pos+3]); + $b = hexdec($body[$i_pos].$body[$i_pos+1]); + + // Calculate and draw the pixel + $color = imagecolorallocate($image, $r, $g, $b); + imagesetpixel($image, $x, $height-$y, $color); + + // Raise the horizontal position + $x++; + } + + // Unset the body / free the memory + unset($body); + + // Return image-object + return $image; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher.php new file mode 100644 index 00000000..1aedb9d2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher.php @@ -0,0 +1,83 @@ +<?php + +/** + * PHPExcel_Shared_Escher + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher +{ + /** + * Drawing Group Container + * + * @var PHPExcel_Shared_Escher_DggContainer + */ + private $dggContainer; + + /** + * Drawing Container + * + * @var PHPExcel_Shared_Escher_DgContainer + */ + private $dgContainer; + + /** + * Get Drawing Group Container + * + * @return PHPExcel_Shared_Escher_DgContainer + */ + public function getDggContainer() + { + return $this->dggContainer; + } + + /** + * Set Drawing Group Container + * + * @param PHPExcel_Shared_Escher_DggContainer $dggContainer + */ + public function setDggContainer($dggContainer) + { + return $this->dggContainer = $dggContainer; + } + + /** + * Get Drawing Container + * + * @return PHPExcel_Shared_Escher_DgContainer + */ + public function getDgContainer() + { + return $this->dgContainer; + } + + /** + * Set Drawing Container + * + * @param PHPExcel_Shared_Escher_DgContainer $dgContainer + */ + public function setDgContainer($dgContainer) + { + return $this->dgContainer = $dgContainer; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer.php new file mode 100644 index 00000000..739cd902 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer.php @@ -0,0 +1,75 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DgContainer + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DgContainer +{ + /** + * Drawing index, 1-based. + * + * @var int + */ + private $dgId; + + /** + * Last shape index in this drawing + * + * @var int + */ + private $lastSpId; + + private $spgrContainer = null; + + public function getDgId() + { + return $this->dgId; + } + + public function setDgId($value) + { + $this->dgId = $value; + } + + public function getLastSpId() + { + return $this->lastSpId; + } + + public function setLastSpId($value) + { + $this->lastSpId = $value; + } + + public function getSpgrContainer() + { + return $this->spgrContainer; + } + + public function setSpgrContainer($spgrContainer) + { + return $this->spgrContainer = $spgrContainer; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php new file mode 100644 index 00000000..49e7d685 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer.php @@ -0,0 +1,102 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DgContainer_SpgrContainer + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DgContainer_SpgrContainer +{ + /** + * Parent Shape Group Container + * + * @var PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + private $parent; + + /** + * Shape Container collection + * + * @var array + */ + private $children = array(); + + /** + * Set parent Shape Group Container + * + * @param PHPExcel_Shared_Escher_DgContainer_SpgrContainer $parent + */ + public function setParent($parent) + { + $this->parent = $parent; + } + + /** + * Get the parent Shape Group Container if any + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer|null + */ + public function getParent() + { + return $this->parent; + } + + /** + * Add a child. This will be either spgrContainer or spContainer + * + * @param mixed $child + */ + public function addChild($child) + { + $this->children[] = $child; + $child->setParent($this); + } + + /** + * Get collection of Shape Containers + */ + public function getChildren() + { + return $this->children; + } + + /** + * Recursively get all spContainers within this spgrContainer + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer[] + */ + public function getAllSpContainers() + { + $allSpContainers = array(); + + foreach ($this->children as $child) { + if ($child instanceof PHPExcel_Shared_Escher_DgContainer_SpgrContainer) { + $allSpContainers = array_merge($allSpContainers, $child->getAllSpContainers()); + } else { + $allSpContainers[] = $child; + } + } + + return $allSpContainers; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php new file mode 100644 index 00000000..a1f1a460 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DgContainer/SpgrContainer/SpContainer.php @@ -0,0 +1,388 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer +{ + /** + * Parent Shape Group Container + * + * @var PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + private $parent; + + /** + * Is this a group shape? + * + * @var boolean + */ + private $spgr = false; + + /** + * Shape type + * + * @var int + */ + private $spType; + + /** + * Shape flag + * + * @var int + */ + private $spFlag; + + /** + * Shape index (usually group shape has index 0, and the rest: 1,2,3...) + * + * @var boolean + */ + private $spId; + + /** + * Array of options + * + * @var array + */ + private $OPT; + + /** + * Cell coordinates of upper-left corner of shape, e.g. 'A1' + * + * @var string + */ + private $startCoordinates; + + /** + * Horizontal offset of upper-left corner of shape measured in 1/1024 of column width + * + * @var int + */ + private $startOffsetX; + + /** + * Vertical offset of upper-left corner of shape measured in 1/256 of row height + * + * @var int + */ + private $startOffsetY; + + /** + * Cell coordinates of bottom-right corner of shape, e.g. 'B2' + * + * @var string + */ + private $endCoordinates; + + /** + * Horizontal offset of bottom-right corner of shape measured in 1/1024 of column width + * + * @var int + */ + private $endOffsetX; + + /** + * Vertical offset of bottom-right corner of shape measured in 1/256 of row height + * + * @var int + */ + private $endOffsetY; + + /** + * Set parent Shape Group Container + * + * @param PHPExcel_Shared_Escher_DgContainer_SpgrContainer $parent + */ + public function setParent($parent) + { + $this->parent = $parent; + } + + /** + * Get the parent Shape Group Container + * + * @return PHPExcel_Shared_Escher_DgContainer_SpgrContainer + */ + public function getParent() + { + return $this->parent; + } + + /** + * Set whether this is a group shape + * + * @param boolean $value + */ + public function setSpgr($value = false) + { + $this->spgr = $value; + } + + /** + * Get whether this is a group shape + * + * @return boolean + */ + public function getSpgr() + { + return $this->spgr; + } + + /** + * Set the shape type + * + * @param int $value + */ + public function setSpType($value) + { + $this->spType = $value; + } + + /** + * Get the shape type + * + * @return int + */ + public function getSpType() + { + return $this->spType; + } + + /** + * Set the shape flag + * + * @param int $value + */ + public function setSpFlag($value) + { + $this->spFlag = $value; + } + + /** + * Get the shape flag + * + * @return int + */ + public function getSpFlag() + { + return $this->spFlag; + } + + /** + * Set the shape index + * + * @param int $value + */ + public function setSpId($value) + { + $this->spId = $value; + } + + /** + * Get the shape index + * + * @return int + */ + public function getSpId() + { + return $this->spId; + } + + /** + * Set an option for the Shape Group Container + * + * @param int $property The number specifies the option + * @param mixed $value + */ + public function setOPT($property, $value) + { + $this->OPT[$property] = $value; + } + + /** + * Get an option for the Shape Group Container + * + * @param int $property The number specifies the option + * @return mixed + */ + public function getOPT($property) + { + if (isset($this->OPT[$property])) { + return $this->OPT[$property]; + } + return null; + } + + /** + * Get the collection of options + * + * @return array + */ + public function getOPTCollection() + { + return $this->OPT; + } + + /** + * Set cell coordinates of upper-left corner of shape + * + * @param string $value + */ + public function setStartCoordinates($value = 'A1') + { + $this->startCoordinates = $value; + } + + /** + * Get cell coordinates of upper-left corner of shape + * + * @return string + */ + public function getStartCoordinates() + { + return $this->startCoordinates; + } + + /** + * Set offset in x-direction of upper-left corner of shape measured in 1/1024 of column width + * + * @param int $startOffsetX + */ + public function setStartOffsetX($startOffsetX = 0) + { + $this->startOffsetX = $startOffsetX; + } + + /** + * Get offset in x-direction of upper-left corner of shape measured in 1/1024 of column width + * + * @return int + */ + public function getStartOffsetX() + { + return $this->startOffsetX; + } + + /** + * Set offset in y-direction of upper-left corner of shape measured in 1/256 of row height + * + * @param int $startOffsetY + */ + public function setStartOffsetY($startOffsetY = 0) + { + $this->startOffsetY = $startOffsetY; + } + + /** + * Get offset in y-direction of upper-left corner of shape measured in 1/256 of row height + * + * @return int + */ + public function getStartOffsetY() + { + return $this->startOffsetY; + } + + /** + * Set cell coordinates of bottom-right corner of shape + * + * @param string $value + */ + public function setEndCoordinates($value = 'A1') + { + $this->endCoordinates = $value; + } + + /** + * Get cell coordinates of bottom-right corner of shape + * + * @return string + */ + public function getEndCoordinates() + { + return $this->endCoordinates; + } + + /** + * Set offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width + * + * @param int $startOffsetX + */ + public function setEndOffsetX($endOffsetX = 0) + { + $this->endOffsetX = $endOffsetX; + } + + /** + * Get offset in x-direction of bottom-right corner of shape measured in 1/1024 of column width + * + * @return int + */ + public function getEndOffsetX() + { + return $this->endOffsetX; + } + + /** + * Set offset in y-direction of bottom-right corner of shape measured in 1/256 of row height + * + * @param int $endOffsetY + */ + public function setEndOffsetY($endOffsetY = 0) + { + $this->endOffsetY = $endOffsetY; + } + + /** + * Get offset in y-direction of bottom-right corner of shape measured in 1/256 of row height + * + * @return int + */ + public function getEndOffsetY() + { + return $this->endOffsetY; + } + + /** + * Get the nesting level of this spContainer. This is the number of spgrContainers between this spContainer and + * the dgContainer. A value of 1 = immediately within first spgrContainer + * Higher nesting level occurs if and only if spContainer is part of a shape group + * + * @return int Nesting level + */ + public function getNestingLevel() + { + $nestingLevel = 0; + + $parent = $this->getParent(); + while ($parent instanceof PHPExcel_Shared_Escher_DgContainer_SpgrContainer) { + ++$nestingLevel; + $parent = $parent->getParent(); + } + + return $nestingLevel; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer.php new file mode 100644 index 00000000..b116b1bd --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer.php @@ -0,0 +1,196 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DggContainer + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DggContainer +{ + /** + * Maximum shape index of all shapes in all drawings increased by one + * + * @var int + */ + private $spIdMax; + + /** + * Total number of drawings saved + * + * @var int + */ + private $cDgSaved; + + /** + * Total number of shapes saved (including group shapes) + * + * @var int + */ + private $cSpSaved; + + /** + * BLIP Store Container + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + private $bstoreContainer; + + /** + * Array of options for the drawing group + * + * @var array + */ + private $OPT = array(); + + /** + * Array of identifier clusters containg information about the maximum shape identifiers + * + * @var array + */ + private $IDCLs = array(); + + /** + * Get maximum shape index of all shapes in all drawings (plus one) + * + * @return int + */ + public function getSpIdMax() + { + return $this->spIdMax; + } + + /** + * Set maximum shape index of all shapes in all drawings (plus one) + * + * @param int + */ + public function setSpIdMax($value) + { + $this->spIdMax = $value; + } + + /** + * Get total number of drawings saved + * + * @return int + */ + public function getCDgSaved() + { + return $this->cDgSaved; + } + + /** + * Set total number of drawings saved + * + * @param int + */ + public function setCDgSaved($value) + { + $this->cDgSaved = $value; + } + + /** + * Get total number of shapes saved (including group shapes) + * + * @return int + */ + public function getCSpSaved() + { + return $this->cSpSaved; + } + + /** + * Set total number of shapes saved (including group shapes) + * + * @param int + */ + public function setCSpSaved($value) + { + $this->cSpSaved = $value; + } + + /** + * Get BLIP Store Container + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + public function getBstoreContainer() + { + return $this->bstoreContainer; + } + + /** + * Set BLIP Store Container + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer $bstoreContainer + */ + public function setBstoreContainer($bstoreContainer) + { + $this->bstoreContainer = $bstoreContainer; + } + + /** + * Set an option for the drawing group + * + * @param int $property The number specifies the option + * @param mixed $value + */ + public function setOPT($property, $value) + { + $this->OPT[$property] = $value; + } + + /** + * Get an option for the drawing group + * + * @param int $property The number specifies the option + * @return mixed + */ + public function getOPT($property) + { + if (isset($this->OPT[$property])) { + return $this->OPT[$property]; + } + return null; + } + + /** + * Get identifier clusters + * + * @return array + */ + public function getIDCLs() + { + return $this->IDCLs; + } + + /** + * Set identifier clusters. array(<drawingId> => <max shape id>, ...) + * + * @param array $pValue + */ + public function setIDCLs($pValue) + { + $this->IDCLs = $pValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php new file mode 100644 index 00000000..1af2432b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer.php @@ -0,0 +1,57 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer +{ + /** + * BLIP Store Entries. Each of them holds one BLIP (Big Large Image or Picture) + * + * @var array + */ + private $BSECollection = array(); + + /** + * Add a BLIP Store Entry + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $BSE + */ + public function addBSE($BSE) + { + $this->BSECollection[] = $BSE; + $BSE->setParent($this); + } + + /** + * Get the collection of BLIP Store Entries + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE[] + */ + public function getBSECollection() + { + return $this->BSECollection; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php new file mode 100644 index 00000000..d17e91e1 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE.php @@ -0,0 +1,112 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE +{ + const BLIPTYPE_ERROR = 0x00; + const BLIPTYPE_UNKNOWN = 0x01; + const BLIPTYPE_EMF = 0x02; + const BLIPTYPE_WMF = 0x03; + const BLIPTYPE_PICT = 0x04; + const BLIPTYPE_JPEG = 0x05; + const BLIPTYPE_PNG = 0x06; + const BLIPTYPE_DIB = 0x07; + const BLIPTYPE_TIFF = 0x11; + const BLIPTYPE_CMYKJPEG = 0x12; + + /** + * The parent BLIP Store Entry Container + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer + */ + private $parent; + + /** + * The BLIP (Big Large Image or Picture) + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + */ + private $blip; + + /** + * The BLIP type + * + * @var int + */ + private $blipType; + + /** + * Set parent BLIP Store Entry Container + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer $parent + */ + public function setParent($parent) + { + $this->parent = $parent; + } + + /** + * Get the BLIP + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + */ + public function getBlip() + { + return $this->blip; + } + + /** + * Set the BLIP + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip $blip + */ + public function setBlip($blip) + { + $this->blip = $blip; + $blip->setParent($this); + } + + /** + * Get the BLIP type + * + * @return int + */ + public function getBlipType() + { + return $this->blipType; + } + + /** + * Set the BLIP type + * + * @param int + */ + public function setBlipType($blipType) + { + $this->blipType = $blipType; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php new file mode 100644 index 00000000..3bcbbbe2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Escher/DggContainer/BstoreContainer/BSE/Blip.php @@ -0,0 +1,83 @@ +<?php + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Escher + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip +{ + /** + * The parent BSE + * + * @var PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE + */ + private $parent; + + /** + * Raw image data + * + * @var string + */ + private $data; + + /** + * Get the raw image data + * + * @return string + */ + public function getData() + { + return $this->data; + } + + /** + * Set the raw image data + * + * @param string + */ + public function setData($data) + { + $this->data = $data; + } + + /** + * Set parent BSE + * + * @param PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $parent + */ + public function setParent($parent) + { + $this->parent = $parent; + } + + /** + * Get parent BSE + * + * @return PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE $parent + */ + public function getParent() + { + return $this->parent; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Excel5.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Excel5.php new file mode 100644 index 00000000..c3ff209f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Excel5.php @@ -0,0 +1,298 @@ +<?php + +/** + * PHPExcel_Shared_Excel5 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_Excel5 +{ + /** + * Get the width of a column in pixels. We use the relationship y = ceil(7x) where + * x is the width in intrinsic Excel units (measuring width in number of normal characters) + * This holds for Arial 10 + * + * @param PHPExcel_Worksheet $sheet The sheet + * @param string $col The column + * @return integer The width in pixels + */ + public static function sizeCol($sheet, $col = 'A') + { + // default font of the workbook + $font = $sheet->getParent()->getDefaultStyle()->getFont(); + + $columnDimensions = $sheet->getColumnDimensions(); + + // first find the true column width in pixels (uncollapsed and unhidden) + if (isset($columnDimensions[$col]) and $columnDimensions[$col]->getWidth() != -1) { + // then we have column dimension with explicit width + $columnDimension = $columnDimensions[$col]; + $width = $columnDimension->getWidth(); + $pixelWidth = PHPExcel_Shared_Drawing::cellDimensionToPixels($width, $font); + } elseif ($sheet->getDefaultColumnDimension()->getWidth() != -1) { + // then we have default column dimension with explicit width + $defaultColumnDimension = $sheet->getDefaultColumnDimension(); + $width = $defaultColumnDimension->getWidth(); + $pixelWidth = PHPExcel_Shared_Drawing::cellDimensionToPixels($width, $font); + } else { + // we don't even have any default column dimension. Width depends on default font + $pixelWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($font, true); + } + + // now find the effective column width in pixels + if (isset($columnDimensions[$col]) and !$columnDimensions[$col]->getVisible()) { + $effectivePixelWidth = 0; + } else { + $effectivePixelWidth = $pixelWidth; + } + + return $effectivePixelWidth; + } + + /** + * Convert the height of a cell from user's units to pixels. By interpolation + * the relationship is: y = 4/3x. If the height hasn't been set by the user we + * use the default value. If the row is hidden we use a value of zero. + * + * @param PHPExcel_Worksheet $sheet The sheet + * @param integer $row The row index (1-based) + * @return integer The width in pixels + */ + public static function sizeRow($sheet, $row = 1) + { + // default font of the workbook + $font = $sheet->getParent()->getDefaultStyle()->getFont(); + + $rowDimensions = $sheet->getRowDimensions(); + + // first find the true row height in pixels (uncollapsed and unhidden) + if (isset($rowDimensions[$row]) and $rowDimensions[$row]->getRowHeight() != -1) { + // then we have a row dimension + $rowDimension = $rowDimensions[$row]; + $rowHeight = $rowDimension->getRowHeight(); + $pixelRowHeight = (int) ceil(4 * $rowHeight / 3); // here we assume Arial 10 + } elseif ($sheet->getDefaultRowDimension()->getRowHeight() != -1) { + // then we have a default row dimension with explicit height + $defaultRowDimension = $sheet->getDefaultRowDimension(); + $rowHeight = $defaultRowDimension->getRowHeight(); + $pixelRowHeight = PHPExcel_Shared_Drawing::pointsToPixels($rowHeight); + } else { + // we don't even have any default row dimension. Height depends on default font + $pointRowHeight = PHPExcel_Shared_Font::getDefaultRowHeightByFont($font); + $pixelRowHeight = PHPExcel_Shared_Font::fontSizeToPixels($pointRowHeight); + } + + // now find the effective row height in pixels + if (isset($rowDimensions[$row]) and !$rowDimensions[$row]->getVisible()) { + $effectivePixelRowHeight = 0; + } else { + $effectivePixelRowHeight = $pixelRowHeight; + } + + return $effectivePixelRowHeight; + } + + /** + * Get the horizontal distance in pixels between two anchors + * The distanceX is found as sum of all the spanning columns widths minus correction for the two offsets + * + * @param PHPExcel_Worksheet $sheet + * @param string $startColumn + * @param integer $startOffsetX Offset within start cell measured in 1/1024 of the cell width + * @param string $endColumn + * @param integer $endOffsetX Offset within end cell measured in 1/1024 of the cell width + * @return integer Horizontal measured in pixels + */ + public static function getDistanceX(PHPExcel_Worksheet $sheet, $startColumn = 'A', $startOffsetX = 0, $endColumn = 'A', $endOffsetX = 0) + { + $distanceX = 0; + + // add the widths of the spanning columns + $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1; // 1-based + $endColumnIndex = PHPExcel_Cell::columnIndexFromString($endColumn) - 1; // 1-based + for ($i = $startColumnIndex; $i <= $endColumnIndex; ++$i) { + $distanceX += self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($i)); + } + + // correct for offsetX in startcell + $distanceX -= (int) floor(self::sizeCol($sheet, $startColumn) * $startOffsetX / 1024); + + // correct for offsetX in endcell + $distanceX -= (int) floor(self::sizeCol($sheet, $endColumn) * (1 - $endOffsetX / 1024)); + + return $distanceX; + } + + /** + * Get the vertical distance in pixels between two anchors + * The distanceY is found as sum of all the spanning rows minus two offsets + * + * @param PHPExcel_Worksheet $sheet + * @param integer $startRow (1-based) + * @param integer $startOffsetY Offset within start cell measured in 1/256 of the cell height + * @param integer $endRow (1-based) + * @param integer $endOffsetY Offset within end cell measured in 1/256 of the cell height + * @return integer Vertical distance measured in pixels + */ + public static function getDistanceY(PHPExcel_Worksheet $sheet, $startRow = 1, $startOffsetY = 0, $endRow = 1, $endOffsetY = 0) + { + $distanceY = 0; + + // add the widths of the spanning rows + for ($row = $startRow; $row <= $endRow; ++$row) { + $distanceY += self::sizeRow($sheet, $row); + } + + // correct for offsetX in startcell + $distanceY -= (int) floor(self::sizeRow($sheet, $startRow) * $startOffsetY / 256); + + // correct for offsetX in endcell + $distanceY -= (int) floor(self::sizeRow($sheet, $endRow) * (1 - $endOffsetY / 256)); + + return $distanceY; + } + + /** + * Convert 1-cell anchor coordinates to 2-cell anchor coordinates + * This function is ported from PEAR Spreadsheet_Writer_Excel with small modifications + * + * Calculate the vertices that define the position of the image as required by + * the OBJ record. + * + * +------------+------------+ + * | A | B | + * +-----+------------+------------+ + * | |(x1,y1) | | + * | 1 |(A1)._______|______ | + * | | | | | + * | | | | | + * +-----+----| BITMAP |-----+ + * | | | | | + * | 2 | |______________. | + * | | | (B2)| + * | | | (x2,y2)| + * +---- +------------+------------+ + * + * Example of a bitmap that covers some of the area from cell A1 to cell B2. + * + * Based on the width and height of the bitmap we need to calculate 8 vars: + * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. + * The width and height of the cells are also variable and have to be taken into + * account. + * The values of $col_start and $row_start are passed in from the calling + * function. The values of $col_end and $row_end are calculated by subtracting + * the width and height of the bitmap from the width and height of the + * underlying cells. + * The vertices are expressed as a percentage of the underlying cell width as + * follows (rhs values are in pixels): + * + * x1 = X / W *1024 + * y1 = Y / H *256 + * x2 = (X-1) / W *1024 + * y2 = (Y-1) / H *256 + * + * Where: X is distance from the left side of the underlying cell + * Y is distance from the top of the underlying cell + * W is the width of the cell + * H is the height of the cell + * + * @param PHPExcel_Worksheet $sheet + * @param string $coordinates E.g. 'A1' + * @param integer $offsetX Horizontal offset in pixels + * @param integer $offsetY Vertical offset in pixels + * @param integer $width Width in pixels + * @param integer $height Height in pixels + * @return array + */ + public static function oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height) + { + list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinates); + $col_start = PHPExcel_Cell::columnIndexFromString($column) - 1; + $row_start = $row - 1; + + $x1 = $offsetX; + $y1 = $offsetY; + + // Initialise end cell to the same as the start cell + $col_end = $col_start; // Col containing lower right corner of object + $row_end = $row_start; // Row containing bottom right corner of object + + // Zero the specified offset if greater than the cell dimensions + if ($x1 >= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) { + $x1 = 0; + } + if ($y1 >= self::sizeRow($sheet, $row_start + 1)) { + $y1 = 0; + } + + $width = $width + $x1 -1; + $height = $height + $y1 -1; + + // Subtract the underlying cell widths to find the end cell of the image + while ($width >= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) { + $width -= self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)); + ++$col_end; + } + + // Subtract the underlying cell heights to find the end cell of the image + while ($height >= self::sizeRow($sheet, $row_end + 1)) { + $height -= self::sizeRow($sheet, $row_end + 1); + ++$row_end; + } + + // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell + // with zero height or width. + if (self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) { + return; + } + if (self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) { + return; + } + if (self::sizeRow($sheet, $row_start + 1) == 0) { + return; + } + if (self::sizeRow($sheet, $row_end + 1) == 0) { + return; + } + + // Convert the pixel values to the percentage value expected by Excel + $x1 = $x1 / self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / self::sizeRow($sheet, $row_start + 1) * 256; + $x2 = ($width + 1) / self::sizeCol($sheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = ($height + 1) / self::sizeRow($sheet, $row_end + 1) * 256; // Distance to bottom of object + + $startCoordinates = PHPExcel_Cell::stringFromColumnIndex($col_start) . ($row_start + 1); + $endCoordinates = PHPExcel_Cell::stringFromColumnIndex($col_end) . ($row_end + 1); + + $twoAnchor = array( + 'startCoordinates' => $startCoordinates, + 'startOffsetX' => $x1, + 'startOffsetY' => $y1, + 'endCoordinates' => $endCoordinates, + 'endOffsetX' => $x2, + 'endOffsetY' => $y2, + ); + + return $twoAnchor; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/File.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/File.php new file mode 100644 index 00000000..a62df759 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/File.php @@ -0,0 +1,180 @@ +<?php + +/** + * PHPExcel_Shared_File + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_File +{ + /* + * Use Temp or File Upload Temp for temporary files + * + * @protected + * @var boolean + */ + protected static $useUploadTempDirectory = false; + + + /** + * Set the flag indicating whether the File Upload Temp directory should be used for temporary files + * + * @param boolean $useUploadTempDir Use File Upload Temporary directory (true or false) + */ + public static function setUseUploadTempDirectory($useUploadTempDir = false) + { + self::$useUploadTempDirectory = (boolean) $useUploadTempDir; + } + + + /** + * Get the flag indicating whether the File Upload Temp directory should be used for temporary files + * + * @return boolean Use File Upload Temporary directory (true or false) + */ + public static function getUseUploadTempDirectory() + { + return self::$useUploadTempDirectory; + } + + + /** + * Verify if a file exists + * + * @param string $pFilename Filename + * @return bool + */ + public static function file_exists($pFilename) + { + // Sick construction, but it seems that + // file_exists returns strange values when + // doing the original file_exists on ZIP archives... + if (strtolower(substr($pFilename, 0, 3)) == 'zip') { + // Open ZIP file and verify if the file exists + $zipFile = substr($pFilename, 6, strpos($pFilename, '#') - 6); + $archiveFile = substr($pFilename, strpos($pFilename, '#') + 1); + + $zip = new ZipArchive(); + if ($zip->open($zipFile) === true) { + $returnValue = ($zip->getFromName($archiveFile) !== false); + $zip->close(); + return $returnValue; + } else { + return false; + } + } else { + // Regular file_exists + return file_exists($pFilename); + } + } + + /** + * Returns canonicalized absolute pathname, also for ZIP archives + * + * @param string $pFilename + * @return string + */ + public static function realpath($pFilename) + { + // Returnvalue + $returnValue = ''; + + // Try using realpath() + if (file_exists($pFilename)) { + $returnValue = realpath($pFilename); + } + + // Found something? + if ($returnValue == '' || ($returnValue === null)) { + $pathArray = explode('/', $pFilename); + while (in_array('..', $pathArray) && $pathArray[0] != '..') { + for ($i = 0; $i < count($pathArray); ++$i) { + if ($pathArray[$i] == '..' && $i > 0) { + unset($pathArray[$i]); + unset($pathArray[$i - 1]); + break; + } + } + } + $returnValue = implode('/', $pathArray); + } + + // Return + return $returnValue; + } + + /** + * Get the systems temporary directory. + * + * @return string + */ + public static function sys_get_temp_dir() + { + if (self::$useUploadTempDirectory) { + // use upload-directory when defined to allow running on environments having very restricted + // open_basedir configs + if (ini_get('upload_tmp_dir') !== false) { + if ($temp = ini_get('upload_tmp_dir')) { + if (file_exists($temp)) { + return realpath($temp); + } + } + } + } + + // sys_get_temp_dir is only available since PHP 5.2.1 + // http://php.net/manual/en/function.sys-get-temp-dir.php#94119 + if (!function_exists('sys_get_temp_dir')) { + if ($temp = getenv('TMP')) { + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } + } + if ($temp = getenv('TEMP')) { + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } + } + if ($temp = getenv('TMPDIR')) { + if ((!empty($temp)) && (file_exists($temp))) { + return realpath($temp); + } + } + + // trick for creating a file in system's temporary dir + // without knowing the path of the system's temporary dir + $temp = tempnam(__FILE__, ''); + if (file_exists($temp)) { + unlink($temp); + return realpath(dirname($temp)); + } + + return null; + } + + // use ordinary built-in PHP function + // There should be no problem with the 5.2.4 Suhosin realpath() bug, because this line should only + // be called if we're running 5.2.1 or earlier + return realpath(sys_get_temp_dir()); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Font.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Font.php new file mode 100644 index 00000000..7efb3c96 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/Font.php @@ -0,0 +1,741 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Shared_Font + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_Font +{ + /* Methods for resolving autosize value */ + const AUTOSIZE_METHOD_APPROX = 'approx'; + const AUTOSIZE_METHOD_EXACT = 'exact'; + + private static $autoSizeMethods = array( + self::AUTOSIZE_METHOD_APPROX, + self::AUTOSIZE_METHOD_EXACT, + ); + + /** Character set codes used by BIFF5-8 in Font records */ + const CHARSET_ANSI_LATIN = 0x00; + const CHARSET_SYSTEM_DEFAULT = 0x01; + const CHARSET_SYMBOL = 0x02; + const CHARSET_APPLE_ROMAN = 0x4D; + const CHARSET_ANSI_JAPANESE_SHIFTJIS = 0x80; + const CHARSET_ANSI_KOREAN_HANGUL = 0x81; + const CHARSET_ANSI_KOREAN_JOHAB = 0x82; + const CHARSET_ANSI_CHINESE_SIMIPLIFIED = 0x86; // gb2312 + const CHARSET_ANSI_CHINESE_TRADITIONAL = 0x88; // big5 + const CHARSET_ANSI_GREEK = 0xA1; + const CHARSET_ANSI_TURKISH = 0xA2; + const CHARSET_ANSI_VIETNAMESE = 0xA3; + const CHARSET_ANSI_HEBREW = 0xB1; + const CHARSET_ANSI_ARABIC = 0xB2; + const CHARSET_ANSI_BALTIC = 0xBA; + const CHARSET_ANSI_CYRILLIC = 0xCC; + const CHARSET_ANSI_THAI = 0xDD; + const CHARSET_ANSI_LATIN_II = 0xEE; + const CHARSET_OEM_LATIN_I = 0xFF; + + // XXX: Constants created! + /** Font filenames */ + const ARIAL = 'arial.ttf'; + const ARIAL_BOLD = 'arialbd.ttf'; + const ARIAL_ITALIC = 'ariali.ttf'; + const ARIAL_BOLD_ITALIC = 'arialbi.ttf'; + + const CALIBRI = 'CALIBRI.TTF'; + const CALIBRI_BOLD = 'CALIBRIB.TTF'; + const CALIBRI_ITALIC = 'CALIBRII.TTF'; + const CALIBRI_BOLD_ITALIC = 'CALIBRIZ.TTF'; + + const COMIC_SANS_MS = 'comic.ttf'; + const COMIC_SANS_MS_BOLD = 'comicbd.ttf'; + + const COURIER_NEW = 'cour.ttf'; + const COURIER_NEW_BOLD = 'courbd.ttf'; + const COURIER_NEW_ITALIC = 'couri.ttf'; + const COURIER_NEW_BOLD_ITALIC = 'courbi.ttf'; + + const GEORGIA = 'georgia.ttf'; + const GEORGIA_BOLD = 'georgiab.ttf'; + const GEORGIA_ITALIC = 'georgiai.ttf'; + const GEORGIA_BOLD_ITALIC = 'georgiaz.ttf'; + + const IMPACT = 'impact.ttf'; + + const LIBERATION_SANS = 'LiberationSans-Regular.ttf'; + const LIBERATION_SANS_BOLD = 'LiberationSans-Bold.ttf'; + const LIBERATION_SANS_ITALIC = 'LiberationSans-Italic.ttf'; + const LIBERATION_SANS_BOLD_ITALIC = 'LiberationSans-BoldItalic.ttf'; + + const LUCIDA_CONSOLE = 'lucon.ttf'; + const LUCIDA_SANS_UNICODE = 'l_10646.ttf'; + + const MICROSOFT_SANS_SERIF = 'micross.ttf'; + + const PALATINO_LINOTYPE = 'pala.ttf'; + const PALATINO_LINOTYPE_BOLD = 'palab.ttf'; + const PALATINO_LINOTYPE_ITALIC = 'palai.ttf'; + const PALATINO_LINOTYPE_BOLD_ITALIC = 'palabi.ttf'; + + const SYMBOL = 'symbol.ttf'; + + const TAHOMA = 'tahoma.ttf'; + const TAHOMA_BOLD = 'tahomabd.ttf'; + + const TIMES_NEW_ROMAN = 'times.ttf'; + const TIMES_NEW_ROMAN_BOLD = 'timesbd.ttf'; + const TIMES_NEW_ROMAN_ITALIC = 'timesi.ttf'; + const TIMES_NEW_ROMAN_BOLD_ITALIC = 'timesbi.ttf'; + + const TREBUCHET_MS = 'trebuc.ttf'; + const TREBUCHET_MS_BOLD = 'trebucbd.ttf'; + const TREBUCHET_MS_ITALIC = 'trebucit.ttf'; + const TREBUCHET_MS_BOLD_ITALIC = 'trebucbi.ttf'; + + const VERDANA = 'verdana.ttf'; + const VERDANA_BOLD = 'verdanab.ttf'; + const VERDANA_ITALIC = 'verdanai.ttf'; + const VERDANA_BOLD_ITALIC = 'verdanaz.ttf'; + + /** + * AutoSize method + * + * @var string + */ + private static $autoSizeMethod = self::AUTOSIZE_METHOD_APPROX; + + /** + * Path to folder containing TrueType font .ttf files + * + * @var string + */ + private static $trueTypeFontPath = null; + + /** + * How wide is a default column for a given default font and size? + * Empirical data found by inspecting real Excel files and reading off the pixel width + * in Microsoft Office Excel 2007. + * + * @var array + */ + public static $defaultColumnWidths = array( + 'Arial' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 56, 'width' => 9.33203125), + 9 => array('px' => 64, 'width' => 9.14062500), + 10 => array('px' => 64, 'width' => 9.14062500), + ), + 'Calibri' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 56, 'width' => 9.33203125), + 9 => array('px' => 56, 'width' => 9.33203125), + 10 => array('px' => 64, 'width' => 9.14062500), + 11 => array('px' => 64, 'width' => 9.14062500), + ), + 'Verdana' => array( + 1 => array('px' => 24, 'width' => 12.00000000), + 2 => array('px' => 24, 'width' => 12.00000000), + 3 => array('px' => 32, 'width' => 10.66406250), + 4 => array('px' => 32, 'width' => 10.66406250), + 5 => array('px' => 40, 'width' => 10.00000000), + 6 => array('px' => 48, 'width' => 9.59765625), + 7 => array('px' => 48, 'width' => 9.59765625), + 8 => array('px' => 64, 'width' => 9.14062500), + 9 => array('px' => 72, 'width' => 9.00000000), + 10 => array('px' => 72, 'width' => 9.00000000), + ), + ); + + /** + * Set autoSize method + * + * @param string $pValue + * @return boolean Success or failure + */ + public static function setAutoSizeMethod($pValue = self::AUTOSIZE_METHOD_APPROX) + { + if (!in_array($pValue, self::$autoSizeMethods)) { + return false; + } + self::$autoSizeMethod = $pValue; + + return true; + } + + /** + * Get autoSize method + * + * @return string + */ + public static function getAutoSizeMethod() + { + return self::$autoSizeMethod; + } + + /** + * Set the path to the folder containing .ttf files. There should be a trailing slash. + * Typical locations on variout some platforms: + * <ul> + * <li>C:/Windows/Fonts/</li> + * <li>/usr/share/fonts/truetype/</li> + * <li>~/.fonts/</li> + * </ul> + * + * @param string $pValue + */ + public static function setTrueTypeFontPath($pValue = '') + { + self::$trueTypeFontPath = $pValue; + } + + /** + * Get the path to the folder containing .ttf files. + * + * @return string + */ + public static function getTrueTypeFontPath() + { + return self::$trueTypeFontPath; + } + + /** + * Calculate an (approximate) OpenXML column width, based on font size and text contained + * + * @param PHPExcel_Style_Font $font Font object + * @param PHPExcel_RichText|string $cellText Text to calculate width + * @param integer $rotation Rotation angle + * @param PHPExcel_Style_Font|NULL $defaultFont Font object + * @return integer Column width + */ + public static function calculateColumnWidth(PHPExcel_Style_Font $font, $cellText = '', $rotation = 0, PHPExcel_Style_Font $defaultFont = null) + { + // If it is rich text, use plain text + if ($cellText instanceof PHPExcel_RichText) { + $cellText = $cellText->getPlainText(); + } + + // Special case if there are one or more newline characters ("\n") + if (strpos($cellText, "\n") !== false) { + $lineTexts = explode("\n", $cellText); + $lineWidths = array(); + foreach ($lineTexts as $lineText) { + $lineWidths[] = self::calculateColumnWidth($font, $lineText, $rotation = 0, $defaultFont); + } + return max($lineWidths); // width of longest line in cell + } + + // Try to get the exact text width in pixels + $approximate = self::$autoSizeMethod == self::AUTOSIZE_METHOD_APPROX; + if (!$approximate) { + $columnWidthAdjust = ceil(self::getTextWidthPixelsExact('n', $font, 0) * 1.07); + try { + // Width of text in pixels excl. padding + // and addition because Excel adds some padding, just use approx width of 'n' glyph + $columnWidth = self::getTextWidthPixelsExact($cellText, $font, $rotation) + $columnWidthAdjust; + } catch (PHPExcel_Exception $e) { + $approximate = true; + } + } + + if ($approximate) { + $columnWidthAdjust = self::getTextWidthPixelsApprox('n', $font, 0); + // Width of text in pixels excl. padding, approximation + // and addition because Excel adds some padding, just use approx width of 'n' glyph + $columnWidth = self::getTextWidthPixelsApprox($cellText, $font, $rotation) + $columnWidthAdjust; + } + + // Convert from pixel width to column width + $columnWidth = PHPExcel_Shared_Drawing::pixelsToCellDimension($columnWidth, $defaultFont); + + // Return + return round($columnWidth, 6); + } + + /** + * Get GD text width in pixels for a string of text in a certain font at a certain rotation angle + * + * @param string $text + * @param PHPExcel_Style_Font + * @param int $rotation + * @return int + * @throws PHPExcel_Exception + */ + public static function getTextWidthPixelsExact($text, PHPExcel_Style_Font $font, $rotation = 0) + { + if (!function_exists('imagettfbbox')) { + throw new PHPExcel_Exception('GD library needs to be enabled'); + } + + // font size should really be supplied in pixels in GD2, + // but since GD2 seems to assume 72dpi, pixels and points are the same + $fontFile = self::getTrueTypeFontFileFromFont($font); + $textBox = imagettfbbox($font->getSize(), $rotation, $fontFile, $text); + + // Get corners positions + $lowerLeftCornerX = $textBox[0]; +// $lowerLeftCornerY = $textBox[1]; + $lowerRightCornerX = $textBox[2]; +// $lowerRightCornerY = $textBox[3]; + $upperRightCornerX = $textBox[4]; +// $upperRightCornerY = $textBox[5]; + $upperLeftCornerX = $textBox[6]; +// $upperLeftCornerY = $textBox[7]; + + // Consider the rotation when calculating the width + $textWidth = max($lowerRightCornerX - $upperLeftCornerX, $upperRightCornerX - $lowerLeftCornerX); + + return $textWidth; + } + + /** + * Get approximate width in pixels for a string of text in a certain font at a certain rotation angle + * + * @param string $columnText + * @param PHPExcel_Style_Font $font + * @param int $rotation + * @return int Text width in pixels (no padding added) + */ + public static function getTextWidthPixelsApprox($columnText, PHPExcel_Style_Font $font = null, $rotation = 0) + { + $fontName = $font->getName(); + $fontSize = $font->getSize(); + + // Calculate column width in pixels. We assume fixed glyph width. Result varies with font name and size. + switch ($fontName) { + case 'Calibri': + // value 8.26 was found via interpolation by inspecting real Excel files with Calibri 11 font. + $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; + + case 'Arial': + // value 7 was found via interpolation by inspecting real Excel files with Arial 10 font. +// $columnWidth = (int) (7 * PHPExcel_Shared_String::CountCharacters($columnText)); + // value 8 was set because of experience in different exports at Arial 10 font. + $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; + + case 'Verdana': + // value 8 was found via interpolation by inspecting real Excel files with Verdana 10 font. + $columnWidth = (int) (8 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 10; // extrapolate from font size + break; + + default: + // just assume Calibri + $columnWidth = (int) (8.26 * PHPExcel_Shared_String::CountCharacters($columnText)); + $columnWidth = $columnWidth * $fontSize / 11; // extrapolate from font size + break; + } + + // Calculate approximate rotated column width + if ($rotation !== 0) { + if ($rotation == -165) { + // stacked text + $columnWidth = 4; // approximation + } else { + // rotated text + $columnWidth = $columnWidth * cos(deg2rad($rotation)) + + $fontSize * abs(sin(deg2rad($rotation))) / 5; // approximation + } + } + + // pixel width is an integer + return (int) $columnWidth; + } + + /** + * Calculate an (approximate) pixel size, based on a font points size + * + * @param int $fontSizeInPoints Font size (in points) + * @return int Font size (in pixels) + */ + public static function fontSizeToPixels($fontSizeInPoints = 11) + { + return (int) ((4 / 3) * $fontSizeInPoints); + } + + /** + * Calculate an (approximate) pixel size, based on inch size + * + * @param int $sizeInInch Font size (in inch) + * @return int Size (in pixels) + */ + public static function inchSizeToPixels($sizeInInch = 1) + { + return ($sizeInInch * 96); + } + + /** + * Calculate an (approximate) pixel size, based on centimeter size + * + * @param int $sizeInCm Font size (in centimeters) + * @return int Size (in pixels) + */ + public static function centimeterSizeToPixels($sizeInCm = 1) + { + return ($sizeInCm * 37.795275591); + } + + /** + * Returns the font path given the font + * + * @param PHPExcel_Style_Font + * @return string Path to TrueType font file + */ + public static function getTrueTypeFontFileFromFont($font) + { + if (!file_exists(self::$trueTypeFontPath) || !is_dir(self::$trueTypeFontPath)) { + throw new PHPExcel_Exception('Valid directory to TrueType Font files not specified'); + } + + $name = $font->getName(); + $bold = $font->getBold(); + $italic = $font->getItalic(); + + // Check if we can map font to true type font file + switch ($name) { + case 'Arial': + $fontFile = ( + $bold ? ($italic ? self::ARIAL_BOLD_ITALIC : self::ARIAL_BOLD) + : ($italic ? self::ARIAL_ITALIC : self::ARIAL) + ); + break; + case 'Calibri': + $fontFile = ( + $bold ? ($italic ? self::CALIBRI_BOLD_ITALIC : self::CALIBRI_BOLD) + : ($italic ? self::CALIBRI_ITALIC : self::CALIBRI) + ); + break; + case 'Courier New': + $fontFile = ( + $bold ? ($italic ? self::COURIER_NEW_BOLD_ITALIC : self::COURIER_NEW_BOLD) + : ($italic ? self::COURIER_NEW_ITALIC : self::COURIER_NEW) + ); + break; + case 'Comic Sans MS': + $fontFile = ( + $bold ? self::COMIC_SANS_MS_BOLD : self::COMIC_SANS_MS + ); + break; + case 'Georgia': + $fontFile = ( + $bold ? ($italic ? self::GEORGIA_BOLD_ITALIC : self::GEORGIA_BOLD) + : ($italic ? self::GEORGIA_ITALIC : self::GEORGIA) + ); + break; + case 'Impact': + $fontFile = self::IMPACT; + break; + case 'Liberation Sans': + $fontFile = ( + $bold ? ($italic ? self::LIBERATION_SANS_BOLD_ITALIC : self::LIBERATION_SANS_BOLD) + : ($italic ? self::LIBERATION_SANS_ITALIC : self::LIBERATION_SANS) + ); + break; + case 'Lucida Console': + $fontFile = self::LUCIDA_CONSOLE; + break; + case 'Lucida Sans Unicode': + $fontFile = self::LUCIDA_SANS_UNICODE; + break; + case 'Microsoft Sans Serif': + $fontFile = self::MICROSOFT_SANS_SERIF; + break; + case 'Palatino Linotype': + $fontFile = ( + $bold ? ($italic ? self::PALATINO_LINOTYPE_BOLD_ITALIC : self::PALATINO_LINOTYPE_BOLD) + : ($italic ? self::PALATINO_LINOTYPE_ITALIC : self::PALATINO_LINOTYPE) + ); + break; + case 'Symbol': + $fontFile = self::SYMBOL; + break; + case 'Tahoma': + $fontFile = ( + $bold ? self::TAHOMA_BOLD : self::TAHOMA + ); + break; + case 'Times New Roman': + $fontFile = ( + $bold ? ($italic ? self::TIMES_NEW_ROMAN_BOLD_ITALIC : self::TIMES_NEW_ROMAN_BOLD) + : ($italic ? self::TIMES_NEW_ROMAN_ITALIC : self::TIMES_NEW_ROMAN) + ); + break; + case 'Trebuchet MS': + $fontFile = ( + $bold ? ($italic ? self::TREBUCHET_MS_BOLD_ITALIC : self::TREBUCHET_MS_BOLD) + : ($italic ? self::TREBUCHET_MS_ITALIC : self::TREBUCHET_MS) + ); + break; + case 'Verdana': + $fontFile = ( + $bold ? ($italic ? self::VERDANA_BOLD_ITALIC : self::VERDANA_BOLD) + : ($italic ? self::VERDANA_ITALIC : self::VERDANA) + ); + break; + default: + throw new PHPExcel_Exception('Unknown font name "'. $name .'". Cannot map to TrueType font file'); + break; + } + + $fontFile = self::$trueTypeFontPath . $fontFile; + + // Check if file actually exists + if (!file_exists($fontFile)) { + throw new PHPExcel_Exception('TrueType Font file not found'); + } + + return $fontFile; + } + + /** + * Returns the associated charset for the font name. + * + * @param string $name Font name + * @return int Character set code + */ + public static function getCharsetFromFontName($name) + { + switch ($name) { + // Add more cases. Check FONT records in real Excel files. + case 'EucrosiaUPC': + return self::CHARSET_ANSI_THAI; + case 'Wingdings': + return self::CHARSET_SYMBOL; + case 'Wingdings 2': + return self::CHARSET_SYMBOL; + case 'Wingdings 3': + return self::CHARSET_SYMBOL; + default: + return self::CHARSET_ANSI_LATIN; + } + } + + /** + * Get the effective column width for columns without a column dimension or column with width -1 + * For example, for Calibri 11 this is 9.140625 (64 px) + * + * @param PHPExcel_Style_Font $font The workbooks default font + * @param boolean $pPixels true = return column width in pixels, false = return in OOXML units + * @return mixed Column width + */ + public static function getDefaultColumnWidthByFont(PHPExcel_Style_Font $font, $pPixels = false) + { + if (isset(self::$defaultColumnWidths[$font->getName()][$font->getSize()])) { + // Exact width can be determined + $columnWidth = $pPixels ? + self::$defaultColumnWidths[$font->getName()][$font->getSize()]['px'] + : self::$defaultColumnWidths[$font->getName()][$font->getSize()]['width']; + + } else { + // We don't have data for this particular font and size, use approximation by + // extrapolating from Calibri 11 + $columnWidth = $pPixels ? + self::$defaultColumnWidths['Calibri'][11]['px'] + : self::$defaultColumnWidths['Calibri'][11]['width']; + $columnWidth = $columnWidth * $font->getSize() / 11; + + // Round pixels to closest integer + if ($pPixels) { + $columnWidth = (int) round($columnWidth); + } + } + + return $columnWidth; + } + + /** + * Get the effective row height for rows without a row dimension or rows with height -1 + * For example, for Calibri 11 this is 15 points + * + * @param PHPExcel_Style_Font $font The workbooks default font + * @return float Row height in points + */ + public static function getDefaultRowHeightByFont(PHPExcel_Style_Font $font) + { + switch ($font->getName()) { + case 'Arial': + switch ($font->getSize()) { + case 10: + // inspection of Arial 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + case 9: + // inspection of Arial 9 workbook says 12.00pt ~16px + $rowHeight = 12; + break; + case 8: + // inspection of Arial 8 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + case 7: + // inspection of Arial 7 workbook says 9.00pt ~12px + $rowHeight = 9; + break; + case 6: + case 5: + // inspection of Arial 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + case 4: + // inspection of Arial 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + case 3: + // inspection of Arial 3 workbook says 6.00pt ~8px + $rowHeight = 6; + break; + case 2: + case 1: + // inspection of Arial 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + default: + // use Arial 10 workbook as an approximation, extrapolation + $rowHeight = 12.75 * $font->getSize() / 10; + break; + } + break; + + case 'Calibri': + switch ($font->getSize()) { + case 11: + // inspection of Calibri 11 workbook says 15.00pt ~20px + $rowHeight = 15; + break; + case 10: + // inspection of Calibri 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + case 9: + // inspection of Calibri 9 workbook says 12.00pt ~16px + $rowHeight = 12; + break; + case 8: + // inspection of Calibri 8 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + case 7: + // inspection of Calibri 7 workbook says 9.00pt ~12px + $rowHeight = 9; + break; + case 6: + case 5: + // inspection of Calibri 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + case 4: + // inspection of Calibri 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + case 3: + // inspection of Calibri 3 workbook says 6.00pt ~8px + $rowHeight = 6.00; + break; + case 2: + case 1: + // inspection of Calibri 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + default: + // use Calibri 11 workbook as an approximation, extrapolation + $rowHeight = 15 * $font->getSize() / 11; + break; + } + break; + + case 'Verdana': + switch ($font->getSize()) { + case 10: + // inspection of Verdana 10 workbook says 12.75pt ~17px + $rowHeight = 12.75; + break; + case 9: + // inspection of Verdana 9 workbook says 11.25pt ~15px + $rowHeight = 11.25; + break; + case 8: + // inspection of Verdana 8 workbook says 10.50pt ~14px + $rowHeight = 10.50; + break; + case 7: + // inspection of Verdana 7 workbook says 9.00pt ~12px + $rowHeight = 9.00; + break; + case 6: + case 5: + // inspection of Verdana 5,6 workbook says 8.25pt ~11px + $rowHeight = 8.25; + break; + case 4: + // inspection of Verdana 4 workbook says 6.75pt ~9px + $rowHeight = 6.75; + break; + case 3: + // inspection of Verdana 3 workbook says 6.00pt ~8px + $rowHeight = 6; + break; + case 2: + case 1: + // inspection of Verdana 1,2 workbook says 5.25pt ~7px + $rowHeight = 5.25; + break; + default: + // use Verdana 10 workbook as an approximation, extrapolation + $rowHeight = 12.75 * $font->getSize() / 10; + break; + } + break; + default: + // just use Calibri as an approximation + $rowHeight = 15 * $font->getSize() / 11; + break; + } + + return $rowHeight; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CHANGELOG.TXT b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CHANGELOG.TXT new file mode 100644 index 00000000..1c18a5da --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CHANGELOG.TXT @@ -0,0 +1,16 @@ +Mar 1, 2005 11:15 AST by PM + ++ For consistency, renamed Math.php to Maths.java, utils to util, + tests to test, docs to doc - + ++ Removed conditional logic from top of Matrix class. + ++ Switched to using hypo function in Maths.php for all php-hypot calls. + NOTE TO SELF: Need to make sure that all decompositions have been + switched over to using the bundled hypo. + +Feb 25, 2005 at 10:00 AST by PM + ++ Recommend using simpler Error.php instead of JAMA_Error.php but + can be persuaded otherwise. + diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CholeskyDecomposition.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CholeskyDecomposition.php new file mode 100644 index 00000000..d68109b3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/CholeskyDecomposition.php @@ -0,0 +1,148 @@ +<?php +/** + * @package JAMA + * + * Cholesky decomposition class + * + * For a symmetric, positive definite matrix A, the Cholesky decomposition + * is an lower triangular matrix L so that A = L*L'. + * + * If the matrix is not symmetric or positive definite, the constructor + * returns a partial decomposition and sets an internal flag that may + * be queried by the isSPD() method. + * + * @author Paul Meagher + * @author Michael Bommarito + * @version 1.2 + */ +class CholeskyDecomposition +{ + /** + * Decomposition storage + * @var array + * @access private + */ + private $L = array(); + + /** + * Matrix row and column dimension + * @var int + * @access private + */ + private $m; + + /** + * Symmetric positive definite flag + * @var boolean + * @access private + */ + private $isspd = true; + + /** + * CholeskyDecomposition + * + * Class constructor - decomposes symmetric positive definite matrix + * @param mixed Matrix square symmetric positive definite matrix + */ + public function __construct($A = null) + { + if ($A instanceof Matrix) { + $this->L = $A->getArray(); + $this->m = $A->getRowDimension(); + + for ($i = 0; $i < $this->m; ++$i) { + for ($j = $i; $j < $this->m; ++$j) { + for ($sum = $this->L[$i][$j], $k = $i - 1; $k >= 0; --$k) { + $sum -= $this->L[$i][$k] * $this->L[$j][$k]; + } + if ($i == $j) { + if ($sum >= 0) { + $this->L[$i][$i] = sqrt($sum); + } else { + $this->isspd = false; + } + } else { + if ($this->L[$i][$i] != 0) { + $this->L[$j][$i] = $sum / $this->L[$i][$i]; + } + } + } + + for ($k = $i+1; $k < $this->m; ++$k) { + $this->L[$i][$k] = 0.0; + } + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION)); + } + } // function __construct() + + /** + * Is the matrix symmetric and positive definite? + * + * @return boolean + */ + public function isSPD() + { + return $this->isspd; + } // function isSPD() + + /** + * getL + * + * Return triangular factor. + * @return Matrix Lower triangular matrix + */ + public function getL() + { + return new Matrix($this->L); + } // function getL() + + /** + * Solve A*X = B + * + * @param $B Row-equal matrix + * @return Matrix L * L' * X = B + */ + public function solve($B = null) + { + if ($B instanceof Matrix) { + if ($B->getRowDimension() == $this->m) { + if ($this->isspd) { + $X = $B->getArrayCopy(); + $nx = $B->getColumnDimension(); + + for ($k = 0; $k < $this->m; ++$k) { + for ($i = $k + 1; $i < $this->m; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->L[$i][$k]; + } + } + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->L[$k][$k]; + } + } + + for ($k = $this->m - 1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->L[$k][$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j] * $this->L[$k][$i]; + } + } + } + + return new Matrix($X, $this->m, $nx); + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixSPDException)); + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MATRIX_DIMENSION_EXCEPTION)); + } + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION)); + } + } // function solve() +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php new file mode 100644 index 00000000..d4ae3979 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/EigenvalueDecomposition.php @@ -0,0 +1,864 @@ +<?php +/** + * @package JAMA + * + * Class to obtain eigenvalues and eigenvectors of a real matrix. + * + * If A is symmetric, then A = V*D*V' where the eigenvalue matrix D + * is diagonal and the eigenvector matrix V is orthogonal (i.e. + * A = V.times(D.times(V.transpose())) and V.times(V.transpose()) + * equals the identity matrix). + * + * If A is not symmetric, then the eigenvalue matrix D is block diagonal + * with the real eigenvalues in 1-by-1 blocks and any complex eigenvalues, + * lambda + i*mu, in 2-by-2 blocks, [lambda, mu; -mu, lambda]. The + * columns of V represent the eigenvectors in the sense that A*V = V*D, + * i.e. A.times(V) equals V.times(D). The matrix V may be badly + * conditioned, or even singular, so the validity of the equation + * A = V*D*inverse(V) depends upon V.cond(). + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class EigenvalueDecomposition +{ + /** + * Row and column dimension (square matrix). + * @var int + */ + private $n; + + /** + * Internal symmetry flag. + * @var int + */ + private $issymmetric; + + /** + * Arrays for internal storage of eigenvalues. + * @var array + */ + private $d = array(); + private $e = array(); + + /** + * Array for internal storage of eigenvectors. + * @var array + */ + private $V = array(); + + /** + * Array for internal storage of nonsymmetric Hessenberg form. + * @var array + */ + private $H = array(); + + /** + * Working storage for nonsymmetric algorithm. + * @var array + */ + private $ort; + + /** + * Used for complex scalar division. + * @var float + */ + private $cdivr; + private $cdivi; + + /** + * Symmetric Householder reduction to tridiagonal form. + * + * @access private + */ + private function tred2() + { + // This is derived from the Algol procedures tred2 by + // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + // Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + // Fortran subroutine in EISPACK. + $this->d = $this->V[$this->n-1]; + // Householder reduction to tridiagonal form. + for ($i = $this->n-1; $i > 0; --$i) { + $i_ = $i -1; + // Scale to avoid under/overflow. + $h = $scale = 0.0; + $scale += array_sum(array_map(abs, $this->d)); + if ($scale == 0.0) { + $this->e[$i] = $this->d[$i_]; + $this->d = array_slice($this->V[$i_], 0, $i_); + for ($j = 0; $j < $i; ++$j) { + $this->V[$j][$i] = $this->V[$i][$j] = 0.0; + } + } else { + // Generate Householder vector. + for ($k = 0; $k < $i; ++$k) { + $this->d[$k] /= $scale; + $h += pow($this->d[$k], 2); + } + $f = $this->d[$i_]; + $g = sqrt($h); + if ($f > 0) { + $g = -$g; + } + $this->e[$i] = $scale * $g; + $h = $h - $f * $g; + $this->d[$i_] = $f - $g; + for ($j = 0; $j < $i; ++$j) { + $this->e[$j] = 0.0; + } + // Apply similarity transformation to remaining columns. + for ($j = 0; $j < $i; ++$j) { + $f = $this->d[$j]; + $this->V[$j][$i] = $f; + $g = $this->e[$j] + $this->V[$j][$j] * $f; + for ($k = $j+1; $k <= $i_; ++$k) { + $g += $this->V[$k][$j] * $this->d[$k]; + $this->e[$k] += $this->V[$k][$j] * $f; + } + $this->e[$j] = $g; + } + $f = 0.0; + for ($j = 0; $j < $i; ++$j) { + $this->e[$j] /= $h; + $f += $this->e[$j] * $this->d[$j]; + } + $hh = $f / (2 * $h); + for ($j=0; $j < $i; ++$j) { + $this->e[$j] -= $hh * $this->d[$j]; + } + for ($j = 0; $j < $i; ++$j) { + $f = $this->d[$j]; + $g = $this->e[$j]; + for ($k = $j; $k <= $i_; ++$k) { + $this->V[$k][$j] -= ($f * $this->e[$k] + $g * $this->d[$k]); + } + $this->d[$j] = $this->V[$i-1][$j]; + $this->V[$i][$j] = 0.0; + } + } + $this->d[$i] = $h; + } + + // Accumulate transformations. + for ($i = 0; $i < $this->n-1; ++$i) { + $this->V[$this->n-1][$i] = $this->V[$i][$i]; + $this->V[$i][$i] = 1.0; + $h = $this->d[$i+1]; + if ($h != 0.0) { + for ($k = 0; $k <= $i; ++$k) { + $this->d[$k] = $this->V[$k][$i+1] / $h; + } + for ($j = 0; $j <= $i; ++$j) { + $g = 0.0; + for ($k = 0; $k <= $i; ++$k) { + $g += $this->V[$k][$i+1] * $this->V[$k][$j]; + } + for ($k = 0; $k <= $i; ++$k) { + $this->V[$k][$j] -= $g * $this->d[$k]; + } + } + } + for ($k = 0; $k <= $i; ++$k) { + $this->V[$k][$i+1] = 0.0; + } + } + + $this->d = $this->V[$this->n-1]; + $this->V[$this->n-1] = array_fill(0, $j, 0.0); + $this->V[$this->n-1][$this->n-1] = 1.0; + $this->e[0] = 0.0; + } + + /** + * Symmetric tridiagonal QL algorithm. + * + * This is derived from the Algol procedures tql2, by + * Bowdler, Martin, Reinsch, and Wilkinson, Handbook for + * Auto. Comp., Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutine in EISPACK. + * + * @access private + */ + private function tql2() + { + for ($i = 1; $i < $this->n; ++$i) { + $this->e[$i-1] = $this->e[$i]; + } + $this->e[$this->n-1] = 0.0; + $f = 0.0; + $tst1 = 0.0; + $eps = pow(2.0, -52.0); + + for ($l = 0; $l < $this->n; ++$l) { + // Find small subdiagonal element + $tst1 = max($tst1, abs($this->d[$l]) + abs($this->e[$l])); + $m = $l; + while ($m < $this->n) { + if (abs($this->e[$m]) <= $eps * $tst1) { + break; + } + ++$m; + } + // If m == l, $this->d[l] is an eigenvalue, + // otherwise, iterate. + if ($m > $l) { + $iter = 0; + do { + // Could check iteration count here. + $iter += 1; + // Compute implicit shift + $g = $this->d[$l]; + $p = ($this->d[$l+1] - $g) / (2.0 * $this->e[$l]); + $r = hypo($p, 1.0); + if ($p < 0) { + $r *= -1; + } + $this->d[$l] = $this->e[$l] / ($p + $r); + $this->d[$l+1] = $this->e[$l] * ($p + $r); + $dl1 = $this->d[$l+1]; + $h = $g - $this->d[$l]; + for ($i = $l + 2; $i < $this->n; ++$i) { + $this->d[$i] -= $h; + } + $f += $h; + // Implicit QL transformation. + $p = $this->d[$m]; + $c = 1.0; + $c2 = $c3 = $c; + $el1 = $this->e[$l + 1]; + $s = $s2 = 0.0; + for ($i = $m-1; $i >= $l; --$i) { + $c3 = $c2; + $c2 = $c; + $s2 = $s; + $g = $c * $this->e[$i]; + $h = $c * $p; + $r = hypo($p, $this->e[$i]); + $this->e[$i+1] = $s * $r; + $s = $this->e[$i] / $r; + $c = $p / $r; + $p = $c * $this->d[$i] - $s * $g; + $this->d[$i+1] = $h + $s * ($c * $g + $s * $this->d[$i]); + // Accumulate transformation. + for ($k = 0; $k < $this->n; ++$k) { + $h = $this->V[$k][$i+1]; + $this->V[$k][$i+1] = $s * $this->V[$k][$i] + $c * $h; + $this->V[$k][$i] = $c * $this->V[$k][$i] - $s * $h; + } + } + $p = -$s * $s2 * $c3 * $el1 * $this->e[$l] / $dl1; + $this->e[$l] = $s * $p; + $this->d[$l] = $c * $p; + // Check for convergence. + } while (abs($this->e[$l]) > $eps * $tst1); + } + $this->d[$l] = $this->d[$l] + $f; + $this->e[$l] = 0.0; + } + + // Sort eigenvalues and corresponding vectors. + for ($i = 0; $i < $this->n - 1; ++$i) { + $k = $i; + $p = $this->d[$i]; + for ($j = $i+1; $j < $this->n; ++$j) { + if ($this->d[$j] < $p) { + $k = $j; + $p = $this->d[$j]; + } + } + if ($k != $i) { + $this->d[$k] = $this->d[$i]; + $this->d[$i] = $p; + for ($j = 0; $j < $this->n; ++$j) { + $p = $this->V[$j][$i]; + $this->V[$j][$i] = $this->V[$j][$k]; + $this->V[$j][$k] = $p; + } + } + } + } + + /** + * Nonsymmetric reduction to Hessenberg form. + * + * This is derived from the Algol procedures orthes and ortran, + * by Martin and Wilkinson, Handbook for Auto. Comp., + * Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutines in EISPACK. + * + * @access private + */ + private function orthes() + { + $low = 0; + $high = $this->n-1; + + for ($m = $low+1; $m <= $high-1; ++$m) { + // Scale column. + $scale = 0.0; + for ($i = $m; $i <= $high; ++$i) { + $scale = $scale + abs($this->H[$i][$m-1]); + } + if ($scale != 0.0) { + // Compute Householder transformation. + $h = 0.0; + for ($i = $high; $i >= $m; --$i) { + $this->ort[$i] = $this->H[$i][$m-1] / $scale; + $h += $this->ort[$i] * $this->ort[$i]; + } + $g = sqrt($h); + if ($this->ort[$m] > 0) { + $g *= -1; + } + $h -= $this->ort[$m] * $g; + $this->ort[$m] -= $g; + // Apply Householder similarity transformation + // H = (I -u * u' / h) * H * (I -u * u') / h) + for ($j = $m; $j < $this->n; ++$j) { + $f = 0.0; + for ($i = $high; $i >= $m; --$i) { + $f += $this->ort[$i] * $this->H[$i][$j]; + } + $f /= $h; + for ($i = $m; $i <= $high; ++$i) { + $this->H[$i][$j] -= $f * $this->ort[$i]; + } + } + for ($i = 0; $i <= $high; ++$i) { + $f = 0.0; + for ($j = $high; $j >= $m; --$j) { + $f += $this->ort[$j] * $this->H[$i][$j]; + } + $f = $f / $h; + for ($j = $m; $j <= $high; ++$j) { + $this->H[$i][$j] -= $f * $this->ort[$j]; + } + } + $this->ort[$m] = $scale * $this->ort[$m]; + $this->H[$m][$m-1] = $scale * $g; + } + } + + // Accumulate transformations (Algol's ortran). + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->V[$i][$j] = ($i == $j ? 1.0 : 0.0); + } + } + for ($m = $high-1; $m >= $low+1; --$m) { + if ($this->H[$m][$m-1] != 0.0) { + for ($i = $m+1; $i <= $high; ++$i) { + $this->ort[$i] = $this->H[$i][$m-1]; + } + for ($j = $m; $j <= $high; ++$j) { + $g = 0.0; + for ($i = $m; $i <= $high; ++$i) { + $g += $this->ort[$i] * $this->V[$i][$j]; + } + // Double division avoids possible underflow + $g = ($g / $this->ort[$m]) / $this->H[$m][$m-1]; + for ($i = $m; $i <= $high; ++$i) { + $this->V[$i][$j] += $g * $this->ort[$i]; + } + } + } + } + } + + /** + * Performs complex division. + * + * @access private + */ + private function cdiv($xr, $xi, $yr, $yi) + { + if (abs($yr) > abs($yi)) { + $r = $yi / $yr; + $d = $yr + $r * $yi; + $this->cdivr = ($xr + $r * $xi) / $d; + $this->cdivi = ($xi - $r * $xr) / $d; + } else { + $r = $yr / $yi; + $d = $yi + $r * $yr; + $this->cdivr = ($r * $xr + $xi) / $d; + $this->cdivi = ($r * $xi - $xr) / $d; + } + } + + /** + * Nonsymmetric reduction from Hessenberg to real Schur form. + * + * Code is derived from the Algol procedure hqr2, + * by Martin and Wilkinson, Handbook for Auto. Comp., + * Vol.ii-Linear Algebra, and the corresponding + * Fortran subroutine in EISPACK. + * + * @access private + */ + private function hqr2() + { + // Initialize + $nn = $this->n; + $n = $nn - 1; + $low = 0; + $high = $nn - 1; + $eps = pow(2.0, -52.0); + $exshift = 0.0; + $p = $q = $r = $s = $z = 0; + // Store roots isolated by balanc and compute matrix norm + $norm = 0.0; + + for ($i = 0; $i < $nn; ++$i) { + if (($i < $low) or ($i > $high)) { + $this->d[$i] = $this->H[$i][$i]; + $this->e[$i] = 0.0; + } + for ($j = max($i-1, 0); $j < $nn; ++$j) { + $norm = $norm + abs($this->H[$i][$j]); + } + } + + // Outer loop over eigenvalue index + $iter = 0; + while ($n >= $low) { + // Look for single small sub-diagonal element + $l = $n; + while ($l > $low) { + $s = abs($this->H[$l-1][$l-1]) + abs($this->H[$l][$l]); + if ($s == 0.0) { + $s = $norm; + } + if (abs($this->H[$l][$l-1]) < $eps * $s) { + break; + } + --$l; + } + // Check for convergence + // One root found + if ($l == $n) { + $this->H[$n][$n] = $this->H[$n][$n] + $exshift; + $this->d[$n] = $this->H[$n][$n]; + $this->e[$n] = 0.0; + --$n; + $iter = 0; + // Two roots found + } elseif ($l == $n-1) { + $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; + $p = ($this->H[$n-1][$n-1] - $this->H[$n][$n]) / 2.0; + $q = $p * $p + $w; + $z = sqrt(abs($q)); + $this->H[$n][$n] = $this->H[$n][$n] + $exshift; + $this->H[$n-1][$n-1] = $this->H[$n-1][$n-1] + $exshift; + $x = $this->H[$n][$n]; + // Real pair + if ($q >= 0) { + if ($p >= 0) { + $z = $p + $z; + } else { + $z = $p - $z; + } + $this->d[$n-1] = $x + $z; + $this->d[$n] = $this->d[$n-1]; + if ($z != 0.0) { + $this->d[$n] = $x - $w / $z; + } + $this->e[$n-1] = 0.0; + $this->e[$n] = 0.0; + $x = $this->H[$n][$n-1]; + $s = abs($x) + abs($z); + $p = $x / $s; + $q = $z / $s; + $r = sqrt($p * $p + $q * $q); + $p = $p / $r; + $q = $q / $r; + // Row modification + for ($j = $n-1; $j < $nn; ++$j) { + $z = $this->H[$n-1][$j]; + $this->H[$n-1][$j] = $q * $z + $p * $this->H[$n][$j]; + $this->H[$n][$j] = $q * $this->H[$n][$j] - $p * $z; + } + // Column modification + for ($i = 0; $i <= $n; ++$i) { + $z = $this->H[$i][$n-1]; + $this->H[$i][$n-1] = $q * $z + $p * $this->H[$i][$n]; + $this->H[$i][$n] = $q * $this->H[$i][$n] - $p * $z; + } + // Accumulate transformations + for ($i = $low; $i <= $high; ++$i) { + $z = $this->V[$i][$n-1]; + $this->V[$i][$n-1] = $q * $z + $p * $this->V[$i][$n]; + $this->V[$i][$n] = $q * $this->V[$i][$n] - $p * $z; + } + // Complex pair + } else { + $this->d[$n-1] = $x + $p; + $this->d[$n] = $x + $p; + $this->e[$n-1] = $z; + $this->e[$n] = -$z; + } + $n = $n - 2; + $iter = 0; + // No convergence yet + } else { + // Form shift + $x = $this->H[$n][$n]; + $y = 0.0; + $w = 0.0; + if ($l < $n) { + $y = $this->H[$n-1][$n-1]; + $w = $this->H[$n][$n-1] * $this->H[$n-1][$n]; + } + // Wilkinson's original ad hoc shift + if ($iter == 10) { + $exshift += $x; + for ($i = $low; $i <= $n; ++$i) { + $this->H[$i][$i] -= $x; + } + $s = abs($this->H[$n][$n-1]) + abs($this->H[$n-1][$n-2]); + $x = $y = 0.75 * $s; + $w = -0.4375 * $s * $s; + } + // MATLAB's new ad hoc shift + if ($iter == 30) { + $s = ($y - $x) / 2.0; + $s = $s * $s + $w; + if ($s > 0) { + $s = sqrt($s); + if ($y < $x) { + $s = -$s; + } + $s = $x - $w / (($y - $x) / 2.0 + $s); + for ($i = $low; $i <= $n; ++$i) { + $this->H[$i][$i] -= $s; + } + $exshift += $s; + $x = $y = $w = 0.964; + } + } + // Could check iteration count here. + $iter = $iter + 1; + // Look for two consecutive small sub-diagonal elements + $m = $n - 2; + while ($m >= $l) { + $z = $this->H[$m][$m]; + $r = $x - $z; + $s = $y - $z; + $p = ($r * $s - $w) / $this->H[$m+1][$m] + $this->H[$m][$m+1]; + $q = $this->H[$m+1][$m+1] - $z - $r - $s; + $r = $this->H[$m+2][$m+1]; + $s = abs($p) + abs($q) + abs($r); + $p = $p / $s; + $q = $q / $s; + $r = $r / $s; + if ($m == $l) { + break; + } + if (abs($this->H[$m][$m-1]) * (abs($q) + abs($r)) < + $eps * (abs($p) * (abs($this->H[$m-1][$m-1]) + abs($z) + abs($this->H[$m+1][$m+1])))) { + break; + } + --$m; + } + for ($i = $m + 2; $i <= $n; ++$i) { + $this->H[$i][$i-2] = 0.0; + if ($i > $m+2) { + $this->H[$i][$i-3] = 0.0; + } + } + // Double QR step involving rows l:n and columns m:n + for ($k = $m; $k <= $n-1; ++$k) { + $notlast = ($k != $n-1); + if ($k != $m) { + $p = $this->H[$k][$k-1]; + $q = $this->H[$k+1][$k-1]; + $r = ($notlast ? $this->H[$k+2][$k-1] : 0.0); + $x = abs($p) + abs($q) + abs($r); + if ($x != 0.0) { + $p = $p / $x; + $q = $q / $x; + $r = $r / $x; + } + } + if ($x == 0.0) { + break; + } + $s = sqrt($p * $p + $q * $q + $r * $r); + if ($p < 0) { + $s = -$s; + } + if ($s != 0) { + if ($k != $m) { + $this->H[$k][$k-1] = -$s * $x; + } elseif ($l != $m) { + $this->H[$k][$k-1] = -$this->H[$k][$k-1]; + } + $p = $p + $s; + $x = $p / $s; + $y = $q / $s; + $z = $r / $s; + $q = $q / $p; + $r = $r / $p; + // Row modification + for ($j = $k; $j < $nn; ++$j) { + $p = $this->H[$k][$j] + $q * $this->H[$k+1][$j]; + if ($notlast) { + $p = $p + $r * $this->H[$k+2][$j]; + $this->H[$k+2][$j] = $this->H[$k+2][$j] - $p * $z; + } + $this->H[$k][$j] = $this->H[$k][$j] - $p * $x; + $this->H[$k+1][$j] = $this->H[$k+1][$j] - $p * $y; + } + // Column modification + for ($i = 0; $i <= min($n, $k+3); ++$i) { + $p = $x * $this->H[$i][$k] + $y * $this->H[$i][$k+1]; + if ($notlast) { + $p = $p + $z * $this->H[$i][$k+2]; + $this->H[$i][$k+2] = $this->H[$i][$k+2] - $p * $r; + } + $this->H[$i][$k] = $this->H[$i][$k] - $p; + $this->H[$i][$k+1] = $this->H[$i][$k+1] - $p * $q; + } + // Accumulate transformations + for ($i = $low; $i <= $high; ++$i) { + $p = $x * $this->V[$i][$k] + $y * $this->V[$i][$k+1]; + if ($notlast) { + $p = $p + $z * $this->V[$i][$k+2]; + $this->V[$i][$k+2] = $this->V[$i][$k+2] - $p * $r; + } + $this->V[$i][$k] = $this->V[$i][$k] - $p; + $this->V[$i][$k+1] = $this->V[$i][$k+1] - $p * $q; + } + } // ($s != 0) + } // k loop + } // check convergence + } // while ($n >= $low) + + // Backsubstitute to find vectors of upper triangular form + if ($norm == 0.0) { + return; + } + + for ($n = $nn-1; $n >= 0; --$n) { + $p = $this->d[$n]; + $q = $this->e[$n]; + // Real vector + if ($q == 0) { + $l = $n; + $this->H[$n][$n] = 1.0; + for ($i = $n-1; $i >= 0; --$i) { + $w = $this->H[$i][$i] - $p; + $r = 0.0; + for ($j = $l; $j <= $n; ++$j) { + $r = $r + $this->H[$i][$j] * $this->H[$j][$n]; + } + if ($this->e[$i] < 0.0) { + $z = $w; + $s = $r; + } else { + $l = $i; + if ($this->e[$i] == 0.0) { + if ($w != 0.0) { + $this->H[$i][$n] = -$r / $w; + } else { + $this->H[$i][$n] = -$r / ($eps * $norm); + } + // Solve real equations + } else { + $x = $this->H[$i][$i+1]; + $y = $this->H[$i+1][$i]; + $q = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i]; + $t = ($x * $s - $z * $r) / $q; + $this->H[$i][$n] = $t; + if (abs($x) > abs($z)) { + $this->H[$i+1][$n] = (-$r - $w * $t) / $x; + } else { + $this->H[$i+1][$n] = (-$s - $y * $t) / $z; + } + } + // Overflow control + $t = abs($this->H[$i][$n]); + if (($eps * $t) * $t > 1) { + for ($j = $i; $j <= $n; ++$j) { + $this->H[$j][$n] = $this->H[$j][$n] / $t; + } + } + } + } + // Complex vector + } elseif ($q < 0) { + $l = $n-1; + // Last vector component imaginary so matrix is triangular + if (abs($this->H[$n][$n-1]) > abs($this->H[$n-1][$n])) { + $this->H[$n-1][$n-1] = $q / $this->H[$n][$n-1]; + $this->H[$n-1][$n] = -($this->H[$n][$n] - $p) / $this->H[$n][$n-1]; + } else { + $this->cdiv(0.0, -$this->H[$n-1][$n], $this->H[$n-1][$n-1] - $p, $q); + $this->H[$n-1][$n-1] = $this->cdivr; + $this->H[$n-1][$n] = $this->cdivi; + } + $this->H[$n][$n-1] = 0.0; + $this->H[$n][$n] = 1.0; + for ($i = $n-2; $i >= 0; --$i) { + // double ra,sa,vr,vi; + $ra = 0.0; + $sa = 0.0; + for ($j = $l; $j <= $n; ++$j) { + $ra = $ra + $this->H[$i][$j] * $this->H[$j][$n-1]; + $sa = $sa + $this->H[$i][$j] * $this->H[$j][$n]; + } + $w = $this->H[$i][$i] - $p; + if ($this->e[$i] < 0.0) { + $z = $w; + $r = $ra; + $s = $sa; + } else { + $l = $i; + if ($this->e[$i] == 0) { + $this->cdiv(-$ra, -$sa, $w, $q); + $this->H[$i][$n-1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; + } else { + // Solve complex equations + $x = $this->H[$i][$i+1]; + $y = $this->H[$i+1][$i]; + $vr = ($this->d[$i] - $p) * ($this->d[$i] - $p) + $this->e[$i] * $this->e[$i] - $q * $q; + $vi = ($this->d[$i] - $p) * 2.0 * $q; + if ($vr == 0.0 & $vi == 0.0) { + $vr = $eps * $norm * (abs($w) + abs($q) + abs($x) + abs($y) + abs($z)); + } + $this->cdiv($x * $r - $z * $ra + $q * $sa, $x * $s - $z * $sa - $q * $ra, $vr, $vi); + $this->H[$i][$n-1] = $this->cdivr; + $this->H[$i][$n] = $this->cdivi; + if (abs($x) > (abs($z) + abs($q))) { + $this->H[$i+1][$n-1] = (-$ra - $w * $this->H[$i][$n-1] + $q * $this->H[$i][$n]) / $x; + $this->H[$i+1][$n] = (-$sa - $w * $this->H[$i][$n] - $q * $this->H[$i][$n-1]) / $x; + } else { + $this->cdiv(-$r - $y * $this->H[$i][$n-1], -$s - $y * $this->H[$i][$n], $z, $q); + $this->H[$i+1][$n-1] = $this->cdivr; + $this->H[$i+1][$n] = $this->cdivi; + } + } + // Overflow control + $t = max(abs($this->H[$i][$n-1]), abs($this->H[$i][$n])); + if (($eps * $t) * $t > 1) { + for ($j = $i; $j <= $n; ++$j) { + $this->H[$j][$n-1] = $this->H[$j][$n-1] / $t; + $this->H[$j][$n] = $this->H[$j][$n] / $t; + } + } + } // end else + } // end for + } // end else for complex case + } // end for + + // Vectors of isolated roots + for ($i = 0; $i < $nn; ++$i) { + if ($i < $low | $i > $high) { + for ($j = $i; $j < $nn; ++$j) { + $this->V[$i][$j] = $this->H[$i][$j]; + } + } + } + + // Back transformation to get eigenvectors of original matrix + for ($j = $nn-1; $j >= $low; --$j) { + for ($i = $low; $i <= $high; ++$i) { + $z = 0.0; + for ($k = $low; $k <= min($j, $high); ++$k) { + $z = $z + $this->V[$i][$k] * $this->H[$k][$j]; + } + $this->V[$i][$j] = $z; + } + } + } // end hqr2 + + /** + * Constructor: Check for symmetry, then construct the eigenvalue decomposition + * + * @access public + * @param A Square matrix + * @return Structure to access D and V. + */ + public function __construct($Arg) + { + $this->A = $Arg->getArray(); + $this->n = $Arg->getColumnDimension(); + + $issymmetric = true; + for ($j = 0; ($j < $this->n) & $issymmetric; ++$j) { + for ($i = 0; ($i < $this->n) & $issymmetric; ++$i) { + $issymmetric = ($this->A[$i][$j] == $this->A[$j][$i]); + } + } + + if ($issymmetric) { + $this->V = $this->A; + // Tridiagonalize. + $this->tred2(); + // Diagonalize. + $this->tql2(); + } else { + $this->H = $this->A; + $this->ort = array(); + // Reduce to Hessenberg form. + $this->orthes(); + // Reduce Hessenberg to real Schur form. + $this->hqr2(); + } + } + + /** + * Return the eigenvector matrix + * + * @access public + * @return V + */ + public function getV() + { + return new Matrix($this->V, $this->n, $this->n); + } + + /** + * Return the real parts of the eigenvalues + * + * @access public + * @return real(diag(D)) + */ + public function getRealEigenvalues() + { + return $this->d; + } + + /** + * Return the imaginary parts of the eigenvalues + * + * @access public + * @return imag(diag(D)) + */ + public function getImagEigenvalues() + { + return $this->e; + } + + /** + * Return the block diagonal eigenvalue matrix + * + * @access public + * @return D + */ + public function getD() + { + for ($i = 0; $i < $this->n; ++$i) { + $D[$i] = array_fill(0, $this->n, 0.0); + $D[$i][$i] = $this->d[$i]; + if ($this->e[$i] == 0) { + continue; + } + $o = ($this->e[$i] > 0) ? $i + 1 : $i - 1; + $D[$i][$o] = $this->e[$i]; + } + return new Matrix($D); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/LUDecomposition.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/LUDecomposition.php new file mode 100644 index 00000000..2505d922 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/LUDecomposition.php @@ -0,0 +1,257 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the LU decomposition is an m-by-n + * unit lower triangular matrix L, an n-by-n upper triangular matrix U, + * and a permutation vector piv of length m so that A(piv,:) = L*U. + * If m < n, then L is m-by-m and U is m-by-n. + * + * The LU decompostion with pivoting always exists, even if the matrix is + * singular, so the constructor will never fail. The primary use of the + * LU decomposition is in the solution of square systems of simultaneous + * linear equations. This will fail if isNonsingular() returns false. + * + * @author Paul Meagher + * @author Bartosz Matosiuk + * @author Michael Bommarito + * @version 1.1 + * @license PHP v3.0 + */ +class PHPExcel_Shared_JAMA_LUDecomposition +{ + const MATRIX_SINGULAR_EXCEPTION = "Can only perform operation on singular matrix."; + const MATRIX_SQUARE_EXCEPTION = "Mismatched Row dimension"; + + /** + * Decomposition storage + * @var array + */ + private $LU = array(); + + /** + * Row dimension. + * @var int + */ + private $m; + + /** + * Column dimension. + * @var int + */ + private $n; + + /** + * Pivot sign. + * @var int + */ + private $pivsign; + + /** + * Internal storage of pivot vector. + * @var array + */ + private $piv = array(); + + /** + * LU Decomposition constructor. + * + * @param $A Rectangular matrix + * @return Structure to access L, U and piv. + */ + public function __construct($A) + { + if ($A instanceof PHPExcel_Shared_JAMA_Matrix) { + // Use a "left-looking", dot-product, Crout/Doolittle algorithm. + $this->LU = $A->getArray(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + for ($i = 0; $i < $this->m; ++$i) { + $this->piv[$i] = $i; + } + $this->pivsign = 1; + $LUrowi = $LUcolj = array(); + + // Outer loop. + for ($j = 0; $j < $this->n; ++$j) { + // Make a copy of the j-th column to localize references. + for ($i = 0; $i < $this->m; ++$i) { + $LUcolj[$i] = &$this->LU[$i][$j]; + } + // Apply previous transformations. + for ($i = 0; $i < $this->m; ++$i) { + $LUrowi = $this->LU[$i]; + // Most of the time is spent in the following dot product. + $kmax = min($i, $j); + $s = 0.0; + for ($k = 0; $k < $kmax; ++$k) { + $s += $LUrowi[$k] * $LUcolj[$k]; + } + $LUrowi[$j] = $LUcolj[$i] -= $s; + } + // Find pivot and exchange if necessary. + $p = $j; + for ($i = $j+1; $i < $this->m; ++$i) { + if (abs($LUcolj[$i]) > abs($LUcolj[$p])) { + $p = $i; + } + } + if ($p != $j) { + for ($k = 0; $k < $this->n; ++$k) { + $t = $this->LU[$p][$k]; + $this->LU[$p][$k] = $this->LU[$j][$k]; + $this->LU[$j][$k] = $t; + } + $k = $this->piv[$p]; + $this->piv[$p] = $this->piv[$j]; + $this->piv[$j] = $k; + $this->pivsign = $this->pivsign * -1; + } + // Compute multipliers. + if (($j < $this->m) && ($this->LU[$j][$j] != 0.0)) { + for ($i = $j+1; $i < $this->m; ++$i) { + $this->LU[$i][$j] /= $this->LU[$j][$j]; + } + } + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ARGUMENT_TYPE_EXCEPTION); + } + } // function __construct() + + /** + * Get lower triangular factor. + * + * @return array Lower triangular factor + */ + public function getL() + { + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i > $j) { + $L[$i][$j] = $this->LU[$i][$j]; + } elseif ($i == $j) { + $L[$i][$j] = 1.0; + } else { + $L[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($L); + } // function getL() + + /** + * Get upper triangular factor. + * + * @return array Upper triangular factor + */ + public function getU() + { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i <= $j) { + $U[$i][$j] = $this->LU[$i][$j]; + } else { + $U[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($U); + } // function getU() + + /** + * Return pivot permutation vector. + * + * @return array Pivot vector + */ + public function getPivot() + { + return $this->piv; + } // function getPivot() + + /** + * Alias for getPivot + * + * @see getPivot + */ + public function getDoublePivot() + { + return $this->getPivot(); + } // function getDoublePivot() + + /** + * Is the matrix nonsingular? + * + * @return true if U, and hence A, is nonsingular. + */ + public function isNonsingular() + { + for ($j = 0; $j < $this->n; ++$j) { + if ($this->LU[$j][$j] == 0) { + return false; + } + } + return true; + } // function isNonsingular() + + /** + * Count determinants + * + * @return array d matrix deterninat + */ + public function det() + { + if ($this->m == $this->n) { + $d = $this->pivsign; + for ($j = 0; $j < $this->n; ++$j) { + $d *= $this->LU[$j][$j]; + } + return $d; + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MATRIX_DIMENSION_EXCEPTION); + } + } // function det() + + /** + * Solve A*X = B + * + * @param $B A Matrix with as many rows as A and any number of columns. + * @return X so that L*U*X = B(piv,:) + * @PHPExcel_Calculation_Exception IllegalArgumentException Matrix row dimensions must agree. + * @PHPExcel_Calculation_Exception RuntimeException Matrix is singular. + */ + public function solve($B) + { + if ($B->getRowDimension() == $this->m) { + if ($this->isNonsingular()) { + // Copy right hand side with pivoting + $nx = $B->getColumnDimension(); + $X = $B->getMatrix($this->piv, 0, $nx-1); + // Solve L*Y = B(piv,:) + for ($k = 0; $k < $this->n; ++$k) { + for ($i = $k+1; $i < $this->n; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k]; + } + } + } + // Solve U*X = Y; + for ($k = $this->n-1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$k][$j] /= $this->LU[$k][$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X->A[$i][$j] -= $X->A[$k][$j] * $this->LU[$i][$k]; + } + } + } + return $X; + } else { + throw new PHPExcel_Calculation_Exception(self::MATRIX_SINGULAR_EXCEPTION); + } + } else { + throw new PHPExcel_Calculation_Exception(self::MATRIX_SQUARE_EXCEPTION); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/Matrix.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/Matrix.php new file mode 100644 index 00000000..82fb0fb2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/Matrix.php @@ -0,0 +1,1159 @@ +<?php +/** + * @package JAMA + */ + +/** PHPExcel root directory */ +if (!defined('PHPEXCEL_ROOT')) { + /** + * @ignore + */ + define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../../'); + require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php'); +} + + +/* + * Matrix class + * + * @author Paul Meagher + * @author Michael Bommarito + * @author Lukasz Karapuda + * @author Bartek Matosiuk + * @version 1.8 + * @license PHP v3.0 + * @see http://math.nist.gov/javanumerics/jama/ + */ +class PHPExcel_Shared_JAMA_Matrix +{ + const POLYMORPHIC_ARGUMENT_EXCEPTION = "Invalid argument pattern for polymorphic function."; + const ARGUMENT_TYPE_EXCEPTION = "Invalid argument type."; + const ARGUMENT_BOUNDS_EXCEPTION = "Invalid argument range."; + const MATRIX_DIMENSION_EXCEPTION = "Matrix dimensions are not equal."; + const ARRAY_LENGTH_EXCEPTION = "Array length must be a multiple of m."; + + /** + * Matrix storage + * + * @var array + * @access public + */ + public $A = array(); + + /** + * Matrix row dimension + * + * @var int + * @access private + */ + private $m; + + /** + * Matrix column dimension + * + * @var int + * @access private + */ + private $n; + + /** + * Polymorphic constructor + * + * As PHP has no support for polymorphic constructors, we hack our own sort of polymorphism using func_num_args, func_get_arg, and gettype. In essence, we're just implementing a simple RTTI filter and calling the appropriate constructor. + */ + public function __construct() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + //Rectangular matrix - m x n initialized from 2D array + case 'array': + $this->m = count($args[0]); + $this->n = count($args[0][0]); + $this->A = $args[0]; + break; + //Square matrix - n x n + case 'integer': + $this->m = $args[0]; + $this->n = $args[0]; + $this->A = array_fill(0, $this->m, array_fill(0, $this->n, 0)); + break; + //Rectangular matrix - m x n + case 'integer,integer': + $this->m = $args[0]; + $this->n = $args[1]; + $this->A = array_fill(0, $this->m, array_fill(0, $this->n, 0)); + break; + //Rectangular matrix - m x n initialized from packed array + case 'array,integer': + $this->m = $args[1]; + if ($this->m != 0) { + $this->n = count($args[0]) / $this->m; + } else { + $this->n = 0; + } + if (($this->m * $this->n) == count($args[0])) { + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $args[0][$i + $j * $this->m]; + } + } + } else { + throw new PHPExcel_Calculation_Exception(self::ARRAY_LENGTH_EXCEPTION); + } + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * getArray + * + * @return array Matrix array + */ + public function getArray() + { + return $this->A; + } + + /** + * getRowDimension + * + * @return int Row dimension + */ + public function getRowDimension() + { + return $this->m; + } + + /** + * getColumnDimension + * + * @return int Column dimension + */ + public function getColumnDimension() + { + return $this->n; + } + + /** + * get + * + * Get the i,j-th element of the matrix. + * @param int $i Row position + * @param int $j Column position + * @return mixed Element (int/float/double) + */ + public function get($i = null, $j = null) + { + return $this->A[$i][$j]; + } + + /** + * getMatrix + * + * Get a submatrix + * @param int $i0 Initial row index + * @param int $iF Final row index + * @param int $j0 Initial column index + * @param int $jF Final column index + * @return Matrix Submatrix + */ + public function getMatrix() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + //A($i0...; $j0...) + case 'integer,integer': + list($i0, $j0) = $args; + if ($i0 >= 0) { + $m = $this->m - $i0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if ($j0 >= 0) { + $n = $this->n - $j0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for ($i = $i0; $i < $this->m; ++$i) { + for ($j = $j0; $j < $this->n; ++$j) { + $R->set($i, $j, $this->A[$i][$j]); + } + } + return $R; + break; + //A($i0...$iF; $j0...$jF) + case 'integer,integer,integer,integer': + list($i0, $iF, $j0, $jF) = $args; + if (($iF > $i0) && ($this->m >= $iF) && ($i0 >= 0)) { + $m = $iF - $i0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if (($jF > $j0) && ($this->n >= $jF) && ($j0 >= 0)) { + $n = $jF - $j0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m+1, $n+1); + for ($i = $i0; $i <= $iF; ++$i) { + for ($j = $j0; $j <= $jF; ++$j) { + $R->set($i - $i0, $j - $j0, $this->A[$i][$j]); + } + } + return $R; + break; + //$R = array of row indices; $C = array of column indices + case 'array,array': + list($RL, $CL) = $args; + if (count($RL) > 0) { + $m = count($RL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if (count($CL) > 0) { + $n = count($CL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for ($i = 0; $i < $m; ++$i) { + for ($j = 0; $j < $n; ++$j) { + $R->set($i - $i0, $j - $j0, $this->A[$RL[$i]][$CL[$j]]); + } + } + return $R; + break; + //$RL = array of row indices; $CL = array of column indices + case 'array,array': + list($RL, $CL) = $args; + if (count($RL) > 0) { + $m = count($RL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if (count($CL) > 0) { + $n = count($CL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for ($i = 0; $i < $m; ++$i) { + for ($j = 0; $j < $n; ++$j) { + $R->set($i, $j, $this->A[$RL[$i]][$CL[$j]]); + } + } + return $R; + break; + //A($i0...$iF); $CL = array of column indices + case 'integer,integer,array': + list($i0, $iF, $CL) = $args; + if (($iF > $i0) && ($this->m >= $iF) && ($i0 >= 0)) { + $m = $iF - $i0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if (count($CL) > 0) { + $n = count($CL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for ($i = $i0; $i < $iF; ++$i) { + for ($j = 0; $j < $n; ++$j) { + $R->set($i - $i0, $j, $this->A[$RL[$i]][$j]); + } + } + return $R; + break; + //$RL = array of row indices + case 'array,integer,integer': + list($RL, $j0, $jF) = $args; + if (count($RL) > 0) { + $m = count($RL); + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + if (($jF >= $j0) && ($this->n >= $jF) && ($j0 >= 0)) { + $n = $jF - $j0; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_BOUNDS_EXCEPTION); + } + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n+1); + for ($i = 0; $i < $m; ++$i) { + for ($j = $j0; $j <= $jF; ++$j) { + $R->set($i, $j - $j0, $this->A[$RL[$i]][$j]); + } + } + return $R; + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * checkMatrixDimensions + * + * Is matrix B the same size? + * @param Matrix $B Matrix B + * @return boolean + */ + public function checkMatrixDimensions($B = null) + { + if ($B instanceof PHPExcel_Shared_JAMA_Matrix) { + if (($this->m == $B->getRowDimension()) && ($this->n == $B->getColumnDimension())) { + return true; + } else { + throw new PHPExcel_Calculation_Exception(self::MATRIX_DIMENSION_EXCEPTION); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + } // function checkMatrixDimensions() + + /** + * set + * + * Set the i,j-th element of the matrix. + * @param int $i Row position + * @param int $j Column position + * @param mixed $c Int/float/double value + * @return mixed Element (int/float/double) + */ + public function set($i = null, $j = null, $c = null) + { + // Optimized set version just has this + $this->A[$i][$j] = $c; + } // function set() + + /** + * identity + * + * Generate an identity matrix. + * @param int $m Row dimension + * @param int $n Column dimension + * @return Matrix Identity matrix + */ + public function identity($m = null, $n = null) + { + return $this->diagonal($m, $n, 1); + } + + /** + * diagonal + * + * Generate a diagonal matrix + * @param int $m Row dimension + * @param int $n Column dimension + * @param mixed $c Diagonal value + * @return Matrix Diagonal matrix + */ + public function diagonal($m = null, $n = null, $c = 1) + { + $R = new PHPExcel_Shared_JAMA_Matrix($m, $n); + for ($i = 0; $i < $m; ++$i) { + $R->set($i, $i, $c); + } + return $R; + } + + /** + * getMatrixByRow + * + * Get a submatrix by row index/range + * @param int $i0 Initial row index + * @param int $iF Final row index + * @return Matrix Submatrix + */ + public function getMatrixByRow($i0 = null, $iF = null) + { + if (is_int($i0)) { + if (is_int($iF)) { + return $this->getMatrix($i0, 0, $iF + 1, $this->n); + } else { + return $this->getMatrix($i0, 0, $i0 + 1, $this->n); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + } + + /** + * getMatrixByCol + * + * Get a submatrix by column index/range + * @param int $i0 Initial column index + * @param int $iF Final column index + * @return Matrix Submatrix + */ + public function getMatrixByCol($j0 = null, $jF = null) + { + if (is_int($j0)) { + if (is_int($jF)) { + return $this->getMatrix(0, $j0, $this->m, $jF + 1); + } else { + return $this->getMatrix(0, $j0, $this->m, $j0 + 1); + } + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + } + + /** + * transpose + * + * Tranpose matrix + * @return Matrix Transposed matrix + */ + public function transpose() + { + $R = new PHPExcel_Shared_JAMA_Matrix($this->n, $this->m); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $R->set($j, $i, $this->A[$i][$j]); + } + } + return $R; + } // function transpose() + + /** + * trace + * + * Sum of diagonal elements + * @return float Sum of diagonal elements + */ + public function trace() + { + $s = 0; + $n = min($this->m, $this->n); + for ($i = 0; $i < $n; ++$i) { + $s += $this->A[$i][$i]; + } + return $s; + } + + /** + * uminus + * + * Unary minus matrix -A + * @return Matrix Unary minus matrix + */ + public function uminus() + { + } + + /** + * plus + * + * A + B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function plus() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) + $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * plusEquals + * + * A = A + B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function plusEquals() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $validValues = true; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value, '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] += $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * minus + * + * A - B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function minus() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) - $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * minusEquals + * + * A = A - B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function minusEquals() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $validValues = true; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value, '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] -= $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * arrayTimes + * + * Element-by-element multiplication + * Cij = Aij * Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Cij + */ + public function arrayTimes() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) * $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * arrayTimesEquals + * + * Element-by-element multiplication + * Aij = Aij * Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayTimesEquals() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $validValues = true; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value, '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] *= $value; + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * arrayRightDivide + * + * Element-by-element right division + * A / B + * @param Matrix $B Matrix B + * @return Matrix Division result + */ + public function arrayRightDivide() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $validValues = true; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value, '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + if ($value == 0) { + // Trap for Divide by Zero error + $M->set($i, $j, '#DIV/0!'); + } else { + $M->set($i, $j, $this->A[$i][$j] / $value); + } + } else { + $M->set($i, $j, PHPExcel_Calculation_Functions::NaN()); + } + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + + /** + * arrayRightDivideEquals + * + * Element-by-element right division + * Aij = Aij / Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayRightDivideEquals() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $this->A[$i][$j] / $M->get($i, $j); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + + /** + * arrayLeftDivide + * + * Element-by-element Left division + * A / B + * @param Matrix $B Matrix B + * @return Matrix Division result + */ + public function arrayLeftDivide() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $M->set($i, $j, $M->get($i, $j) / $this->A[$i][$j]); + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + + /** + * arrayLeftDivideEquals + * + * Element-by-element Left division + * Aij = Aij / Bij + * @param mixed $B Matrix/Array + * @return Matrix Matrix Aij + */ + public function arrayLeftDivideEquals() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = $M->get($i, $j) / $this->A[$i][$j]; + } + } + return $M; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + + /** + * times + * + * Matrix multiplication + * @param mixed $n Matrix/Array/Scalar + * @return Matrix Product + */ + public function times() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $B = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + if ($this->n == $B->m) { + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $B->n); + for ($j = 0; $j < $B->n; ++$j) { + for ($k = 0; $k < $this->n; ++$k) { + $Bcolj[$k] = $B->A[$k][$j]; + } + for ($i = 0; $i < $this->m; ++$i) { + $Arowi = $this->A[$i]; + $s = 0; + for ($k = 0; $k < $this->n; ++$k) { + $s += $Arowi[$k] * $Bcolj[$k]; + } + $C->A[$i][$j] = $s; + } + } + return $C; + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixDimensionMismatch)); + } + break; + case 'array': + $B = new PHPExcel_Shared_JAMA_Matrix($args[0]); + if ($this->n == $B->m) { + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $B->n); + for ($i = 0; $i < $C->m; ++$i) { + for ($j = 0; $j < $C->n; ++$j) { + $s = "0"; + for ($k = 0; $k < $C->n; ++$k) { + $s += $this->A[$i][$k] * $B->A[$k][$j]; + } + $C->A[$i][$j] = $s; + } + } + return $C; + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(MatrixDimensionMismatch)); + } + return $M; + break; + case 'integer': + $C = new PHPExcel_Shared_JAMA_Matrix($this->A); + for ($i = 0; $i < $C->m; ++$i) { + for ($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] *= $args[0]; + } + } + return $C; + break; + case 'double': + $C = new PHPExcel_Shared_JAMA_Matrix($this->m, $this->n); + for ($i = 0; $i < $C->m; ++$i) { + for ($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] = $args[0] * $this->A[$i][$j]; + } + } + return $C; + break; + case 'float': + $C = new PHPExcel_Shared_JAMA_Matrix($this->A); + for ($i = 0; $i < $C->m; ++$i) { + for ($j = 0; $j < $C->n; ++$j) { + $C->A[$i][$j] *= $args[0]; + } + } + return $C; + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * power + * + * A = A ^ B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function power() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + break; + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $validValues = true; + $value = $M->get($i, $j); + if ((is_string($this->A[$i][$j])) && (strlen($this->A[$i][$j]) > 0) && (!is_numeric($this->A[$i][$j]))) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($this->A[$i][$j]); + } + if ((is_string($value)) && (strlen($value) > 0) && (!is_numeric($value))) { + $value = trim($value, '"'); + $validValues &= PHPExcel_Shared_String::convertToNumberIfFraction($value); + } + if ($validValues) { + $this->A[$i][$j] = pow($this->A[$i][$j], $value); + } else { + $this->A[$i][$j] = PHPExcel_Calculation_Functions::NaN(); + } + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * concat + * + * A = A & B + * @param mixed $B Matrix/Array + * @return Matrix Sum + */ + public function concat() + { + if (func_num_args() > 0) { + $args = func_get_args(); + $match = implode(",", array_map('gettype', $args)); + + switch ($match) { + case 'object': + if ($args[0] instanceof PHPExcel_Shared_JAMA_Matrix) { + $M = $args[0]; + } else { + throw new PHPExcel_Calculation_Exception(self::ARGUMENT_TYPE_EXCEPTION); + } + case 'array': + $M = new PHPExcel_Shared_JAMA_Matrix($args[0]); + break; + default: + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + break; + } + $this->checkMatrixDimensions($M); + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $this->A[$i][$j] = trim($this->A[$i][$j], '"').trim($M->get($i, $j), '"'); + } + } + return $this; + } else { + throw new PHPExcel_Calculation_Exception(self::POLYMORPHIC_ARGUMENT_EXCEPTION); + } + } + + /** + * Solve A*X = B. + * + * @param Matrix $B Right hand side + * @return Matrix ... Solution if A is square, least squares solution otherwise + */ + public function solve($B) + { + if ($this->m == $this->n) { + $LU = new PHPExcel_Shared_JAMA_LUDecomposition($this); + return $LU->solve($B); + } else { + $QR = new PHPExcel_Shared_JAMA_QRDecomposition($this); + return $QR->solve($B); + } + } + + /** + * Matrix inverse or pseudoinverse. + * + * @return Matrix ... Inverse(A) if A is square, pseudoinverse otherwise. + */ + public function inverse() + { + return $this->solve($this->identity($this->m, $this->m)); + } + + /** + * det + * + * Calculate determinant + * @return float Determinant + */ + public function det() + { + $L = new PHPExcel_Shared_JAMA_LUDecomposition($this); + return $L->det(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/QRDecomposition.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/QRDecomposition.php new file mode 100644 index 00000000..1e43c7c4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/QRDecomposition.php @@ -0,0 +1,235 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the QR decomposition is an m-by-n + * orthogonal matrix Q and an n-by-n upper triangular matrix R so that + * A = Q*R. + * + * The QR decompostion always exists, even if the matrix does not have + * full rank, so the constructor will never fail. The primary use of the + * QR decomposition is in the least squares solution of nonsquare systems + * of simultaneous linear equations. This will fail if isFullRank() + * returns false. + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class PHPExcel_Shared_JAMA_QRDecomposition +{ + const MATRIX_RANK_EXCEPTION = "Can only perform operation on full-rank matrix."; + + /** + * Array for internal storage of decomposition. + * @var array + */ + private $QR = array(); + + /** + * Row dimension. + * @var integer + */ + private $m; + + /** + * Column dimension. + * @var integer + */ + private $n; + + /** + * Array for internal storage of diagonal of R. + * @var array + */ + private $Rdiag = array(); + + + /** + * QR Decomposition computed by Householder reflections. + * + * @param matrix $A Rectangular matrix + * @return Structure to access R and the Householder vectors and compute Q. + */ + public function __construct($A) + { + if ($A instanceof PHPExcel_Shared_JAMA_Matrix) { + // Initialize. + $this->QR = $A->getArrayCopy(); + $this->m = $A->getRowDimension(); + $this->n = $A->getColumnDimension(); + // Main loop. + for ($k = 0; $k < $this->n; ++$k) { + // Compute 2-norm of k-th column without under/overflow. + $nrm = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $nrm = hypo($nrm, $this->QR[$i][$k]); + } + if ($nrm != 0.0) { + // Form k-th Householder vector. + if ($this->QR[$k][$k] < 0) { + $nrm = -$nrm; + } + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$k] /= $nrm; + } + $this->QR[$k][$k] += 1.0; + // Apply transformation to remaining columns. + for ($j = $k+1; $j < $this->n; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $this->QR[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->QR[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + $this->Rdiag[$k] = -$nrm; + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::ARGUMENT_TYPE_EXCEPTION); + } + } // function __construct() + + + /** + * Is the matrix full rank? + * + * @return boolean true if R, and hence A, has full rank, else false. + */ + public function isFullRank() + { + for ($j = 0; $j < $this->n; ++$j) { + if ($this->Rdiag[$j] == 0) { + return false; + } + } + return true; + } // function isFullRank() + + /** + * Return the Householder vectors + * + * @return Matrix Lower trapezoidal matrix whose columns define the reflections + */ + public function getH() + { + for ($i = 0; $i < $this->m; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i >= $j) { + $H[$i][$j] = $this->QR[$i][$j]; + } else { + $H[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($H); + } // function getH() + + /** + * Return the upper triangular factor + * + * @return Matrix upper triangular factor + */ + public function getR() + { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + if ($i < $j) { + $R[$i][$j] = $this->QR[$i][$j]; + } elseif ($i == $j) { + $R[$i][$j] = $this->Rdiag[$i]; + } else { + $R[$i][$j] = 0.0; + } + } + } + return new PHPExcel_Shared_JAMA_Matrix($R); + } // function getR() + + /** + * Generate and return the (economy-sized) orthogonal factor + * + * @return Matrix orthogonal factor + */ + public function getQ() + { + for ($k = $this->n-1; $k >= 0; --$k) { + for ($i = 0; $i < $this->m; ++$i) { + $Q[$i][$k] = 0.0; + } + $Q[$k][$k] = 1.0; + for ($j = $k; $j < $this->n; ++$j) { + if ($this->QR[$k][$k] != 0) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $Q[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $Q[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + } + /* + for($i = 0; $i < count($Q); ++$i) { + for($j = 0; $j < count($Q); ++$j) { + if (! isset($Q[$i][$j]) ) { + $Q[$i][$j] = 0; + } + } + } + */ + return new PHPExcel_Shared_JAMA_Matrix($Q); + } // function getQ() + + /** + * Least squares solution of A*X = B + * + * @param Matrix $B A Matrix with as many rows as A and any number of columns. + * @return Matrix Matrix that minimizes the two norm of Q*R*X-B. + */ + public function solve($B) + { + if ($B->getRowDimension() == $this->m) { + if ($this->isFullRank()) { + // Copy right hand side + $nx = $B->getColumnDimension(); + $X = $B->getArrayCopy(); + // Compute Y = transpose(Q)*B + for ($k = 0; $k < $this->n; ++$k) { + for ($j = 0; $j < $nx; ++$j) { + $s = 0.0; + for ($i = $k; $i < $this->m; ++$i) { + $s += $this->QR[$i][$k] * $X[$i][$j]; + } + $s = -$s/$this->QR[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $X[$i][$j] += $s * $this->QR[$i][$k]; + } + } + } + // Solve R*X = Y; + for ($k = $this->n-1; $k >= 0; --$k) { + for ($j = 0; $j < $nx; ++$j) { + $X[$k][$j] /= $this->Rdiag[$k]; + } + for ($i = 0; $i < $k; ++$i) { + for ($j = 0; $j < $nx; ++$j) { + $X[$i][$j] -= $X[$k][$j]* $this->QR[$i][$k]; + } + } + } + $X = new PHPExcel_Shared_JAMA_Matrix($X); + return ($X->getMatrix(0, $this->n-1, 0, $nx)); + } else { + throw new PHPExcel_Calculation_Exception(self::MATRIX_RANK_EXCEPTION); + } + } else { + throw new PHPExcel_Calculation_Exception(PHPExcel_Shared_JAMA_Matrix::MATRIX_DIMENSION_EXCEPTION); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/SingularValueDecomposition.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/SingularValueDecomposition.php new file mode 100644 index 00000000..f57d122c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/SingularValueDecomposition.php @@ -0,0 +1,528 @@ +<?php +/** + * @package JAMA + * + * For an m-by-n matrix A with m >= n, the singular value decomposition is + * an m-by-n orthogonal matrix U, an n-by-n diagonal matrix S, and + * an n-by-n orthogonal matrix V so that A = U*S*V'. + * + * The singular values, sigma[$k] = S[$k][$k], are ordered so that + * sigma[0] >= sigma[1] >= ... >= sigma[n-1]. + * + * The singular value decompostion always exists, so the constructor will + * never fail. The matrix condition number and the effective numerical + * rank can be computed from this decomposition. + * + * @author Paul Meagher + * @license PHP v3.0 + * @version 1.1 + */ +class SingularValueDecomposition +{ + /** + * Internal storage of U. + * @var array + */ + private $U = array(); + + /** + * Internal storage of V. + * @var array + */ + private $V = array(); + + /** + * Internal storage of singular values. + * @var array + */ + private $s = array(); + + /** + * Row dimension. + * @var int + */ + private $m; + + /** + * Column dimension. + * @var int + */ + private $n; + + /** + * Construct the singular value decomposition + * + * Derived from LINPACK code. + * + * @param $A Rectangular matrix + * @return Structure to access U, S and V. + */ + public function __construct($Arg) + { + // Initialize. + $A = $Arg->getArrayCopy(); + $this->m = $Arg->getRowDimension(); + $this->n = $Arg->getColumnDimension(); + $nu = min($this->m, $this->n); + $e = array(); + $work = array(); + $wantu = true; + $wantv = true; + $nct = min($this->m - 1, $this->n); + $nrt = max(0, min($this->n - 2, $this->m)); + + // Reduce A to bidiagonal form, storing the diagonal elements + // in s and the super-diagonal elements in e. + for ($k = 0; $k < max($nct, $nrt); ++$k) { + if ($k < $nct) { + // Compute the transformation for the k-th column and + // place the k-th diagonal in s[$k]. + // Compute 2-norm of k-th column without under/overflow. + $this->s[$k] = 0; + for ($i = $k; $i < $this->m; ++$i) { + $this->s[$k] = hypo($this->s[$k], $A[$i][$k]); + } + if ($this->s[$k] != 0.0) { + if ($A[$k][$k] < 0.0) { + $this->s[$k] = -$this->s[$k]; + } + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$k] /= $this->s[$k]; + } + $A[$k][$k] += 1.0; + } + $this->s[$k] = -$this->s[$k]; + } + + for ($j = $k + 1; $j < $this->n; ++$j) { + if (($k < $nct) & ($this->s[$k] != 0.0)) { + // Apply the transformation. + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $A[$i][$k] * $A[$i][$j]; + } + $t = -$t / $A[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $A[$i][$k]; + } + // Place the k-th row of A into e for the + // subsequent calculation of the row transformation. + $e[$j] = $A[$k][$j]; + } + } + + if ($wantu and ($k < $nct)) { + // Place the transformation in U for subsequent back + // multiplication. + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$k] = $A[$i][$k]; + } + } + + if ($k < $nrt) { + // Compute the k-th row transformation and place the + // k-th super-diagonal in e[$k]. + // Compute 2-norm without under/overflow. + $e[$k] = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$k] = hypo($e[$k], $e[$i]); + } + if ($e[$k] != 0.0) { + if ($e[$k+1] < 0.0) { + $e[$k] = -$e[$k]; + } + for ($i = $k + 1; $i < $this->n; ++$i) { + $e[$i] /= $e[$k]; + } + $e[$k+1] += 1.0; + } + $e[$k] = -$e[$k]; + if (($k+1 < $this->m) and ($e[$k] != 0.0)) { + // Apply the transformation. + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] = 0.0; + } + for ($j = $k+1; $j < $this->n; ++$j) { + for ($i = $k+1; $i < $this->m; ++$i) { + $work[$i] += $e[$j] * $A[$i][$j]; + } + } + for ($j = $k + 1; $j < $this->n; ++$j) { + $t = -$e[$j] / $e[$k+1]; + for ($i = $k + 1; $i < $this->m; ++$i) { + $A[$i][$j] += $t * $work[$i]; + } + } + } + if ($wantv) { + // Place the transformation in V for subsequent + // back multiplication. + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$k] = $e[$i]; + } + } + } + } + + // Set up the final bidiagonal matrix or order p. + $p = min($this->n, $this->m + 1); + if ($nct < $this->n) { + $this->s[$nct] = $A[$nct][$nct]; + } + if ($this->m < $p) { + $this->s[$p-1] = 0.0; + } + if ($nrt + 1 < $p) { + $e[$nrt] = $A[$nrt][$p-1]; + } + $e[$p-1] = 0.0; + // If required, generate U. + if ($wantu) { + for ($j = $nct; $j < $nu; ++$j) { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$j] = 0.0; + } + $this->U[$j][$j] = 1.0; + } + for ($k = $nct - 1; $k >= 0; --$k) { + if ($this->s[$k] != 0.0) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k; $i < $this->m; ++$i) { + $t += $this->U[$i][$k] * $this->U[$i][$j]; + } + $t = -$t / $this->U[$k][$k]; + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$j] += $t * $this->U[$i][$k]; + } + } + for ($i = $k; $i < $this->m; ++$i) { + $this->U[$i][$k] = -$this->U[$i][$k]; + } + $this->U[$k][$k] = 1.0 + $this->U[$k][$k]; + for ($i = 0; $i < $k - 1; ++$i) { + $this->U[$i][$k] = 0.0; + } + } else { + for ($i = 0; $i < $this->m; ++$i) { + $this->U[$i][$k] = 0.0; + } + $this->U[$k][$k] = 1.0; + } + } + } + + // If required, generate V. + if ($wantv) { + for ($k = $this->n - 1; $k >= 0; --$k) { + if (($k < $nrt) and ($e[$k] != 0.0)) { + for ($j = $k + 1; $j < $nu; ++$j) { + $t = 0; + for ($i = $k + 1; $i < $this->n; ++$i) { + $t += $this->V[$i][$k]* $this->V[$i][$j]; + } + $t = -$t / $this->V[$k+1][$k]; + for ($i = $k + 1; $i < $this->n; ++$i) { + $this->V[$i][$j] += $t * $this->V[$i][$k]; + } + } + } + for ($i = 0; $i < $this->n; ++$i) { + $this->V[$i][$k] = 0.0; + } + $this->V[$k][$k] = 1.0; + } + } + + // Main iteration loop for the singular values. + $pp = $p - 1; + $iter = 0; + $eps = pow(2.0, -52.0); + + while ($p > 0) { + // Here is where a test for too many iterations would go. + // This section of the program inspects for negligible + // elements in the s and e arrays. On completion the + // variables kase and k are set as follows: + // kase = 1 if s(p) and e[k-1] are negligible and k<p + // kase = 2 if s(k) is negligible and k<p + // kase = 3 if e[k-1] is negligible, k<p, and + // s(k), ..., s(p) are not negligible (qr step). + // kase = 4 if e(p-1) is negligible (convergence). + for ($k = $p - 2; $k >= -1; --$k) { + if ($k == -1) { + break; + } + if (abs($e[$k]) <= $eps * (abs($this->s[$k]) + abs($this->s[$k+1]))) { + $e[$k] = 0.0; + break; + } + } + if ($k == $p - 2) { + $kase = 4; + } else { + for ($ks = $p - 1; $ks >= $k; --$ks) { + if ($ks == $k) { + break; + } + $t = ($ks != $p ? abs($e[$ks]) : 0.) + ($ks != $k + 1 ? abs($e[$ks-1]) : 0.); + if (abs($this->s[$ks]) <= $eps * $t) { + $this->s[$ks] = 0.0; + break; + } + } + if ($ks == $k) { + $kase = 3; + } elseif ($ks == $p-1) { + $kase = 1; + } else { + $kase = 2; + $k = $ks; + } + } + ++$k; + + // Perform the task indicated by kase. + switch ($kase) { + // Deflate negligible s(p). + case 1: + $f = $e[$p-2]; + $e[$p-2] = 0.0; + for ($j = $p - 2; $j >= $k; --$j) { + $t = hypo($this->s[$j], $f); + $cs = $this->s[$j] / $t; + $sn = $f / $t; + $this->s[$j] = $t; + if ($j != $k) { + $f = -$sn * $e[$j-1]; + $e[$j-1] = $cs * $e[$j-1]; + } + if ($wantv) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$p-1]; + $this->V[$i][$p-1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$p-1]; + $this->V[$i][$j] = $t; + } + } + } + break; + // Split at negligible s(k). + case 2: + $f = $e[$k-1]; + $e[$k-1] = 0.0; + for ($j = $k; $j < $p; ++$j) { + $t = hypo($this->s[$j], $f); + $cs = $this->s[$j] / $t; + $sn = $f / $t; + $this->s[$j] = $t; + $f = -$sn * $e[$j]; + $e[$j] = $cs * $e[$j]; + if ($wantu) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$k-1]; + $this->U[$i][$k-1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$k-1]; + $this->U[$i][$j] = $t; + } + } + } + break; + // Perform one qr step. + case 3: + // Calculate the shift. + $scale = max(max(max(max(abs($this->s[$p-1]), abs($this->s[$p-2])), abs($e[$p-2])), abs($this->s[$k])), abs($e[$k])); + $sp = $this->s[$p-1] / $scale; + $spm1 = $this->s[$p-2] / $scale; + $epm1 = $e[$p-2] / $scale; + $sk = $this->s[$k] / $scale; + $ek = $e[$k] / $scale; + $b = (($spm1 + $sp) * ($spm1 - $sp) + $epm1 * $epm1) / 2.0; + $c = ($sp * $epm1) * ($sp * $epm1); + $shift = 0.0; + if (($b != 0.0) || ($c != 0.0)) { + $shift = sqrt($b * $b + $c); + if ($b < 0.0) { + $shift = -$shift; + } + $shift = $c / ($b + $shift); + } + $f = ($sk + $sp) * ($sk - $sp) + $shift; + $g = $sk * $ek; + // Chase zeros. + for ($j = $k; $j < $p-1; ++$j) { + $t = hypo($f, $g); + $cs = $f/$t; + $sn = $g/$t; + if ($j != $k) { + $e[$j-1] = $t; + } + $f = $cs * $this->s[$j] + $sn * $e[$j]; + $e[$j] = $cs * $e[$j] - $sn * $this->s[$j]; + $g = $sn * $this->s[$j+1]; + $this->s[$j+1] = $cs * $this->s[$j+1]; + if ($wantv) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $cs * $this->V[$i][$j] + $sn * $this->V[$i][$j+1]; + $this->V[$i][$j+1] = -$sn * $this->V[$i][$j] + $cs * $this->V[$i][$j+1]; + $this->V[$i][$j] = $t; + } + } + $t = hypo($f, $g); + $cs = $f/$t; + $sn = $g/$t; + $this->s[$j] = $t; + $f = $cs * $e[$j] + $sn * $this->s[$j+1]; + $this->s[$j+1] = -$sn * $e[$j] + $cs * $this->s[$j+1]; + $g = $sn * $e[$j+1]; + $e[$j+1] = $cs * $e[$j+1]; + if ($wantu && ($j < $this->m - 1)) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $cs * $this->U[$i][$j] + $sn * $this->U[$i][$j+1]; + $this->U[$i][$j+1] = -$sn * $this->U[$i][$j] + $cs * $this->U[$i][$j+1]; + $this->U[$i][$j] = $t; + } + } + } + $e[$p-2] = $f; + $iter = $iter + 1; + break; + // Convergence. + case 4: + // Make the singular values positive. + if ($this->s[$k] <= 0.0) { + $this->s[$k] = ($this->s[$k] < 0.0 ? -$this->s[$k] : 0.0); + if ($wantv) { + for ($i = 0; $i <= $pp; ++$i) { + $this->V[$i][$k] = -$this->V[$i][$k]; + } + } + } + // Order the singular values. + while ($k < $pp) { + if ($this->s[$k] >= $this->s[$k+1]) { + break; + } + $t = $this->s[$k]; + $this->s[$k] = $this->s[$k+1]; + $this->s[$k+1] = $t; + if ($wantv and ($k < $this->n - 1)) { + for ($i = 0; $i < $this->n; ++$i) { + $t = $this->V[$i][$k+1]; + $this->V[$i][$k+1] = $this->V[$i][$k]; + $this->V[$i][$k] = $t; + } + } + if ($wantu and ($k < $this->m-1)) { + for ($i = 0; $i < $this->m; ++$i) { + $t = $this->U[$i][$k+1]; + $this->U[$i][$k+1] = $this->U[$i][$k]; + $this->U[$i][$k] = $t; + } + } + ++$k; + } + $iter = 0; + --$p; + break; + } // end switch + } // end while + + } // end constructor + + + /** + * Return the left singular vectors + * + * @access public + * @return U + */ + public function getU() + { + return new Matrix($this->U, $this->m, min($this->m + 1, $this->n)); + } + + + /** + * Return the right singular vectors + * + * @access public + * @return V + */ + public function getV() + { + return new Matrix($this->V); + } + + + /** + * Return the one-dimensional array of singular values + * + * @access public + * @return diagonal of S. + */ + public function getSingularValues() + { + return $this->s; + } + + + /** + * Return the diagonal matrix of singular values + * + * @access public + * @return S + */ + public function getS() + { + for ($i = 0; $i < $this->n; ++$i) { + for ($j = 0; $j < $this->n; ++$j) { + $S[$i][$j] = 0.0; + } + $S[$i][$i] = $this->s[$i]; + } + return new Matrix($S); + } + + + /** + * Two norm + * + * @access public + * @return max(S) + */ + public function norm2() + { + return $this->s[0]; + } + + + /** + * Two norm condition number + * + * @access public + * @return max(S)/min(S) + */ + public function cond() + { + return $this->s[0] / $this->s[min($this->m, $this->n) - 1]; + } + + + /** + * Effective numerical matrix rank + * + * @access public + * @return Number of nonnegligible singular values. + */ + public function rank() + { + $eps = pow(2.0, -52.0); + $tol = max($this->m, $this->n) * $this->s[0] * $eps; + $r = 0; + for ($i = 0; $i < count($this->s); ++$i) { + if ($this->s[$i] > $tol) { + ++$r; + } + } + return $r; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Error.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Error.php new file mode 100644 index 00000000..71b8c994 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Error.php @@ -0,0 +1,83 @@ +<?php +/** + * @package JAMA + * + * Error handling + * @author Michael Bommarito + * @version 01292005 + */ + +//Language constant +define('JAMALANG', 'EN'); + + +//All errors may be defined by the following format: +//define('ExceptionName', N); +//$error['lang'][ExceptionName] = 'Error message'; +$error = array(); + +/* +I've used Babelfish and a little poor knowledge of Romance/Germanic languages for the translations here. +Feel free to correct anything that looks amiss to you. +*/ + +define('POLYMORPHIC_ARGUMENT_EXCEPTION', -1); +$error['EN'][POLYMORPHIC_ARGUMENT_EXCEPTION] = "Invalid argument pattern for polymorphic function."; +$error['FR'][POLYMORPHIC_ARGUMENT_EXCEPTION] = "Modèle inadmissible d'argument pour la fonction polymorphe.". +$error['DE'][POLYMORPHIC_ARGUMENT_EXCEPTION] = "Unzulässiges Argumentmuster für polymorphe Funktion."; + +define('ARGUMENT_TYPE_EXCEPTION', -2); +$error['EN'][ARGUMENT_TYPE_EXCEPTION] = "Invalid argument type."; +$error['FR'][ARGUMENT_TYPE_EXCEPTION] = "Type inadmissible d'argument."; +$error['DE'][ARGUMENT_TYPE_EXCEPTION] = "Unzulässige Argumentart."; + +define('ARGUMENT_BOUNDS_EXCEPTION', -3); +$error['EN'][ARGUMENT_BOUNDS_EXCEPTION] = "Invalid argument range."; +$error['FR'][ARGUMENT_BOUNDS_EXCEPTION] = "Gamme inadmissible d'argument."; +$error['DE'][ARGUMENT_BOUNDS_EXCEPTION] = "Unzulässige Argumentstrecke."; + +define('MATRIX_DIMENSION_EXCEPTION', -4); +$error['EN'][MATRIX_DIMENSION_EXCEPTION] = "Matrix dimensions are not equal."; +$error['FR'][MATRIX_DIMENSION_EXCEPTION] = "Les dimensions de Matrix ne sont pas égales."; +$error['DE'][MATRIX_DIMENSION_EXCEPTION] = "Matrixmaße sind nicht gleich."; + +define('PRECISION_LOSS_EXCEPTION', -5); +$error['EN'][PRECISION_LOSS_EXCEPTION] = "Significant precision loss detected."; +$error['FR'][PRECISION_LOSS_EXCEPTION] = "Perte significative de précision détectée."; +$error['DE'][PRECISION_LOSS_EXCEPTION] = "Bedeutender Präzision Verlust ermittelte."; + +define('MATRIX_SPD_EXCEPTION', -6); +$error['EN'][MATRIX_SPD_EXCEPTION] = "Can only perform operation on symmetric positive definite matrix."; +$error['FR'][MATRIX_SPD_EXCEPTION] = "Perte significative de précision détectée."; +$error['DE'][MATRIX_SPD_EXCEPTION] = "Bedeutender Präzision Verlust ermittelte."; + +define('MATRIX_SINGULAR_EXCEPTION', -7); +$error['EN'][MATRIX_SINGULAR_EXCEPTION] = "Can only perform operation on singular matrix."; + +define('MATRIX_RANK_EXCEPTION', -8); +$error['EN'][MATRIX_RANK_EXCEPTION] = "Can only perform operation on full-rank matrix."; + +define('ARRAY_LENGTH_EXCEPTION', -9); +$error['EN'][ARRAY_LENGTH_EXCEPTION] = "Array length must be a multiple of m."; + +define('ROW_LENGTH_EXCEPTION', -10); +$error['EN'][ROW_LENGTH_EXCEPTION] = "All rows must have the same length."; + +/** + * Custom error handler + * @param int $num Error number + */ +function JAMAError($errorNumber = null) +{ + global $error; + + if (isset($errorNumber)) { + if (isset($error[JAMALANG][$errorNumber])) { + return $error[JAMALANG][$errorNumber]; + } else { + return $error['EN'][$errorNumber]; + } + } else { + return ("Invalid argument to JAMAError()"); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Maths.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Maths.php new file mode 100644 index 00000000..386c1e67 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/JAMA/utils/Maths.php @@ -0,0 +1,44 @@ +<?php +/** + * @package JAMA + * + * Pythagorean Theorem: + * + * a = 3 + * b = 4 + * r = sqrt(square(a) + square(b)) + * r = 5 + * + * r = sqrt(a^2 + b^2) without under/overflow. + */ +function hypo($a, $b) +{ + if (abs($a) > abs($b)) { + $r = $b / $a; + $r = abs($a) * sqrt(1 + $r * $r); + } elseif ($b != 0) { + $r = $a / $b; + $r = abs($b) * sqrt(1 + $r * $r); + } else { + $r = 0.0; + } + return $r; +} // function hypo() + + +/** + * Mike Bommarito's version. + * Compute n-dimensional hyotheneuse. + * +function hypot() { + $s = 0; + foreach (func_get_args() as $d) { + if (is_numeric($d)) { + $s += pow($d, 2); + } else { + throw new PHPExcel_Calculation_Exception(JAMAError(ARGUMENT_TYPE_EXCEPTION)); + } + } + return sqrt($s); +} +*/ diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE.php new file mode 100644 index 00000000..42a3c529 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE.php @@ -0,0 +1,526 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: OLE.php,v 1.13 2007/03/07 14:38:25 schmidt Exp $ + + +/** +* Array for storing OLE instances that are accessed from +* OLE_ChainedBlockStream::stream_open(). +* @var array +*/ +$GLOBALS['_OLE_INSTANCES'] = array(); + +/** +* OLE package base class. +* +* @author Xavier Noguer <xnoguer@php.net> +* @author Christian Schmidt <schmidt@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE +{ + const OLE_PPS_TYPE_ROOT = 5; + const OLE_PPS_TYPE_DIR = 1; + const OLE_PPS_TYPE_FILE = 2; + const OLE_DATA_SIZE_SMALL = 0x1000; + const OLE_LONG_INT_SIZE = 4; + const OLE_PPS_SIZE = 0x80; + + /** + * The file handle for reading an OLE container + * @var resource + */ + public $_file_handle; + + /** + * Array of PPS's found on the OLE container + * @var array + */ + public $_list = array(); + + /** + * Root directory of OLE container + * @var OLE_PPS_Root + */ + public $root; + + /** + * Big Block Allocation Table + * @var array (blockId => nextBlockId) + */ + public $bbat; + + /** + * Short Block Allocation Table + * @var array (blockId => nextBlockId) + */ + public $sbat; + + /** + * Size of big blocks. This is usually 512. + * @var int number of octets per block. + */ + public $bigBlockSize; + + /** + * Size of small blocks. This is usually 64. + * @var int number of octets per block + */ + public $smallBlockSize; + + /** + * Reads an OLE container from the contents of the file given. + * + * @acces public + * @param string $file + * @return mixed true on success, PEAR_Error on failure + */ + public function read($file) + { + $fh = fopen($file, "r"); + if (!$fh) { + throw new PHPExcel_Reader_Exception("Can't open file $file"); + } + $this->_file_handle = $fh; + + $signature = fread($fh, 8); + if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) { + throw new PHPExcel_Reader_Exception("File doesn't seem to be an OLE container."); + } + fseek($fh, 28); + if (fread($fh, 2) != "\xFE\xFF") { + // This shouldn't be a problem in practice + throw new PHPExcel_Reader_Exception("Only Little-Endian encoding is supported."); + } + // Size of blocks and short blocks in bytes + $this->bigBlockSize = pow(2, self::_readInt2($fh)); + $this->smallBlockSize = pow(2, self::_readInt2($fh)); + + // Skip UID, revision number and version number + fseek($fh, 44); + // Number of blocks in Big Block Allocation Table + $bbatBlockCount = self::_readInt4($fh); + + // Root chain 1st block + $directoryFirstBlockId = self::_readInt4($fh); + + // Skip unused bytes + fseek($fh, 56); + // Streams shorter than this are stored using small blocks + $this->bigBlockThreshold = self::_readInt4($fh); + // Block id of first sector in Short Block Allocation Table + $sbatFirstBlockId = self::_readInt4($fh); + // Number of blocks in Short Block Allocation Table + $sbbatBlockCount = self::_readInt4($fh); + // Block id of first sector in Master Block Allocation Table + $mbatFirstBlockId = self::_readInt4($fh); + // Number of blocks in Master Block Allocation Table + $mbbatBlockCount = self::_readInt4($fh); + $this->bbat = array(); + + // Remaining 4 * 109 bytes of current block is beginning of Master + // Block Allocation Table + $mbatBlocks = array(); + for ($i = 0; $i < 109; ++$i) { + $mbatBlocks[] = self::_readInt4($fh); + } + + // Read rest of Master Block Allocation Table (if any is left) + $pos = $this->_getBlockOffset($mbatFirstBlockId); + for ($i = 0; $i < $mbbatBlockCount; ++$i) { + fseek($fh, $pos); + for ($j = 0; $j < $this->bigBlockSize / 4 - 1; ++$j) { + $mbatBlocks[] = self::_readInt4($fh); + } + // Last block id in each block points to next block + $pos = $this->_getBlockOffset(self::_readInt4($fh)); + } + + // Read Big Block Allocation Table according to chain specified by + // $mbatBlocks + for ($i = 0; $i < $bbatBlockCount; ++$i) { + $pos = $this->_getBlockOffset($mbatBlocks[$i]); + fseek($fh, $pos); + for ($j = 0; $j < $this->bigBlockSize / 4; ++$j) { + $this->bbat[] = self::_readInt4($fh); + } + } + + // Read short block allocation table (SBAT) + $this->sbat = array(); + $shortBlockCount = $sbbatBlockCount * $this->bigBlockSize / 4; + $sbatFh = $this->getStream($sbatFirstBlockId); + for ($blockId = 0; $blockId < $shortBlockCount; ++$blockId) { + $this->sbat[$blockId] = self::_readInt4($sbatFh); + } + fclose($sbatFh); + + $this->_readPpsWks($directoryFirstBlockId); + + return true; + } + + /** + * @param int block id + * @param int byte offset from beginning of file + * @access public + */ + public function _getBlockOffset($blockId) + { + return 512 + $blockId * $this->bigBlockSize; + } + + /** + * Returns a stream for use with fread() etc. External callers should + * use PHPExcel_Shared_OLE_PPS_File::getStream(). + * @param int|PPS block id or PPS + * @return resource read-only stream + */ + public function getStream($blockIdOrPps) + { + static $isRegistered = false; + if (!$isRegistered) { + stream_wrapper_register('ole-chainedblockstream', 'PHPExcel_Shared_OLE_ChainedBlockStream'); + $isRegistered = true; + } + + // Store current instance in global array, so that it can be accessed + // in OLE_ChainedBlockStream::stream_open(). + // Object is removed from self::$instances in OLE_Stream::close(). + $GLOBALS['_OLE_INSTANCES'][] = $this; + $instanceId = end(array_keys($GLOBALS['_OLE_INSTANCES'])); + + $path = 'ole-chainedblockstream://oleInstanceId=' . $instanceId; + if ($blockIdOrPps instanceof PHPExcel_Shared_OLE_PPS) { + $path .= '&blockId=' . $blockIdOrPps->_StartBlock; + $path .= '&size=' . $blockIdOrPps->Size; + } else { + $path .= '&blockId=' . $blockIdOrPps; + } + return fopen($path, 'r'); + } + + /** + * Reads a signed char. + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt1($fh) + { + list(, $tmp) = unpack("c", fread($fh, 1)); + return $tmp; + } + + /** + * Reads an unsigned short (2 octets). + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt2($fh) + { + list(, $tmp) = unpack("v", fread($fh, 2)); + return $tmp; + } + + /** + * Reads an unsigned long (4 octets). + * @param resource file handle + * @return int + * @access public + */ + private static function _readInt4($fh) + { + list(, $tmp) = unpack("V", fread($fh, 4)); + return $tmp; + } + + /** + * Gets information about all PPS's on the OLE container from the PPS WK's + * creates an OLE_PPS object for each one. + * + * @access public + * @param integer the block id of the first block + * @return mixed true on success, PEAR_Error on failure + */ + public function _readPpsWks($blockId) + { + $fh = $this->getStream($blockId); + for ($pos = 0;; $pos += 128) { + fseek($fh, $pos, SEEK_SET); + $nameUtf16 = fread($fh, 64); + $nameLength = self::_readInt2($fh); + $nameUtf16 = substr($nameUtf16, 0, $nameLength - 2); + // Simple conversion from UTF-16LE to ISO-8859-1 + $name = str_replace("\x00", "", $nameUtf16); + $type = self::_readInt1($fh); + switch ($type) { + case self::OLE_PPS_TYPE_ROOT: + $pps = new PHPExcel_Shared_OLE_PPS_Root(null, null, array()); + $this->root = $pps; + break; + case self::OLE_PPS_TYPE_DIR: + $pps = new PHPExcel_Shared_OLE_PPS(null, null, null, null, null, null, null, null, null, array()); + break; + case self::OLE_PPS_TYPE_FILE: + $pps = new PHPExcel_Shared_OLE_PPS_File($name); + break; + default: + continue; + } + fseek($fh, 1, SEEK_CUR); + $pps->Type = $type; + $pps->Name = $name; + $pps->PrevPps = self::_readInt4($fh); + $pps->NextPps = self::_readInt4($fh); + $pps->DirPps = self::_readInt4($fh); + fseek($fh, 20, SEEK_CUR); + $pps->Time1st = self::OLE2LocalDate(fread($fh, 8)); + $pps->Time2nd = self::OLE2LocalDate(fread($fh, 8)); + $pps->_StartBlock = self::_readInt4($fh); + $pps->Size = self::_readInt4($fh); + $pps->No = count($this->_list); + $this->_list[] = $pps; + + // check if the PPS tree (starting from root) is complete + if (isset($this->root) && $this->_ppsTreeComplete($this->root->No)) { + break; + } + } + fclose($fh); + + // Initialize $pps->children on directories + foreach ($this->_list as $pps) { + if ($pps->Type == self::OLE_PPS_TYPE_DIR || $pps->Type == self::OLE_PPS_TYPE_ROOT) { + $nos = array($pps->DirPps); + $pps->children = array(); + while ($nos) { + $no = array_pop($nos); + if ($no != -1) { + $childPps = $this->_list[$no]; + $nos[] = $childPps->PrevPps; + $nos[] = $childPps->NextPps; + $pps->children[] = $childPps; + } + } + } + } + + return true; + } + + /** + * It checks whether the PPS tree is complete (all PPS's read) + * starting with the given PPS (not necessarily root) + * + * @access public + * @param integer $index The index of the PPS from which we are checking + * @return boolean Whether the PPS tree for the given PPS is complete + */ + public function _ppsTreeComplete($index) + { + return isset($this->_list[$index]) && + ($pps = $this->_list[$index]) && + ($pps->PrevPps == -1 || + $this->_ppsTreeComplete($pps->PrevPps)) && + ($pps->NextPps == -1 || + $this->_ppsTreeComplete($pps->NextPps)) && + ($pps->DirPps == -1 || + $this->_ppsTreeComplete($pps->DirPps)); + } + + /** + * Checks whether a PPS is a File PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @access public + * @param integer $index The index for the PPS + * @return bool true if it's a File PPS, false otherwise + */ + public function isFile($index) + { + if (isset($this->_list[$index])) { + return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_FILE); + } + return false; + } + + /** + * Checks whether a PPS is a Root PPS or not. + * If there is no PPS for the index given, it will return false. + * + * @access public + * @param integer $index The index for the PPS. + * @return bool true if it's a Root PPS, false otherwise + */ + public function isRoot($index) + { + if (isset($this->_list[$index])) { + return ($this->_list[$index]->Type == self::OLE_PPS_TYPE_ROOT); + } + return false; + } + + /** + * Gives the total number of PPS's found in the OLE container. + * + * @access public + * @return integer The total number of PPS's found in the OLE container + */ + public function ppsTotal() + { + return count($this->_list); + } + + /** + * Gets data from a PPS + * If there is no PPS for the index given, it will return an empty string. + * + * @access public + * @param integer $index The index for the PPS + * @param integer $position The position from which to start reading + * (relative to the PPS) + * @param integer $length The amount of bytes to read (at most) + * @return string The binary string containing the data requested + * @see OLE_PPS_File::getStream() + */ + public function getData($index, $position, $length) + { + // if position is not valid return empty string + if (!isset($this->_list[$index]) || ($position >= $this->_list[$index]->Size) || ($position < 0)) { + return ''; + } + $fh = $this->getStream($this->_list[$index]); + $data = stream_get_contents($fh, $length, $position); + fclose($fh); + return $data; + } + + /** + * Gets the data length from a PPS + * If there is no PPS for the index given, it will return 0. + * + * @access public + * @param integer $index The index for the PPS + * @return integer The amount of bytes in data the PPS has + */ + public function getDataLength($index) + { + if (isset($this->_list[$index])) { + return $this->_list[$index]->Size; + } + return 0; + } + + /** + * Utility function to transform ASCII text to Unicode + * + * @access public + * @static + * @param string $ascii The ASCII string to transform + * @return string The string in Unicode + */ + public static function Asc2Ucs($ascii) + { + $rawname = ''; + for ($i = 0; $i < strlen($ascii); ++$i) { + $rawname .= $ascii{$i} . "\x00"; + } + return $rawname; + } + + /** + * Utility function + * Returns a string for the OLE container with the date given + * + * @access public + * @static + * @param integer $date A timestamp + * @return string The string for the OLE container + */ + public static function LocalDate2OLE($date = null) + { + if (!isset($date)) { + return "\x00\x00\x00\x00\x00\x00\x00\x00"; + } + + // factor used for separating numbers into 4 bytes parts + $factor = pow(2, 32); + + // days from 1-1-1601 until the beggining of UNIX era + $days = 134774; + // calculate seconds + $big_date = $days*24*3600 + gmmktime(date("H", $date), date("i", $date), date("s", $date), date("m", $date), date("d", $date), date("Y", $date)); + // multiply just to make MS happy + $big_date *= 10000000; + + $high_part = floor($big_date / $factor); + // lower 4 bytes + $low_part = floor((($big_date / $factor) - $high_part) * $factor); + + // Make HEX string + $res = ''; + + for ($i = 0; $i < 4; ++$i) { + $hex = $low_part % 0x100; + $res .= pack('c', $hex); + $low_part /= 0x100; + } + for ($i = 0; $i < 4; ++$i) { + $hex = $high_part % 0x100; + $res .= pack('c', $hex); + $high_part /= 0x100; + } + return $res; + } + + /** + * Returns a timestamp from an OLE container's date + * + * @access public + * @static + * @param integer $string A binary string with the encoded date + * @return string The timestamp corresponding to the string + */ + public static function OLE2LocalDate($string) + { + if (strlen($string) != 8) { + return new PEAR_Error("Expecting 8 byte string"); + } + + // factor used for separating numbers into 4 bytes parts + $factor = pow(2, 32); + list(, $high_part) = unpack('V', substr($string, 4, 4)); + list(, $low_part) = unpack('V', substr($string, 0, 4)); + + $big_date = ($high_part * $factor) + $low_part; + // translate to seconds + $big_date /= 10000000; + + // days from 1-1-1601 until the beggining of UNIX era + $days = 134774; + + // translate to seconds from beggining of UNIX era + $big_date -= $days * 24 * 3600; + return floor($big_date); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/ChainedBlockStream.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/ChainedBlockStream.php new file mode 100644 index 00000000..84d2cc50 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/ChainedBlockStream.php @@ -0,0 +1,206 @@ +<?php + +/** + * PHPExcel_Shared_OLE_ChainedBlockStream + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_OLE + * @copyright Copyright (c) 2006 - 2007 Christian Schmidt + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_OLE_ChainedBlockStream +{ + /** + * The OLE container of the file that is being read. + * @var OLE + */ + public $ole; + + /** + * Parameters specified by fopen(). + * @var array + */ + public $params; + + /** + * The binary data of the file. + * @var string + */ + public $data; + + /** + * The file pointer. + * @var int byte offset + */ + public $pos; + + /** + * Implements support for fopen(). + * For creating streams using this wrapper, use OLE_PPS_File::getStream(). + * + * @param string $path resource name including scheme, e.g. + * ole-chainedblockstream://oleInstanceId=1 + * @param string $mode only "r" is supported + * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH + * @param string &$openedPath absolute path of the opened stream (out parameter) + * @return bool true on success + */ + public function stream_open($path, $mode, $options, &$openedPath) + { + if ($mode != 'r') { + if ($options & STREAM_REPORT_ERRORS) { + trigger_error('Only reading is supported', E_USER_WARNING); + } + return false; + } + + // 25 is length of "ole-chainedblockstream://" + parse_str(substr($path, 25), $this->params); + if (!isset($this->params['oleInstanceId'], $this->params['blockId'], $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']])) { + if ($options & STREAM_REPORT_ERRORS) { + trigger_error('OLE stream not found', E_USER_WARNING); + } + return false; + } + $this->ole = $GLOBALS['_OLE_INSTANCES'][$this->params['oleInstanceId']]; + + $blockId = $this->params['blockId']; + $this->data = ''; + if (isset($this->params['size']) && $this->params['size'] < $this->ole->bigBlockThreshold && $blockId != $this->ole->root->_StartBlock) { + // Block id refers to small blocks + $rootPos = $this->ole->_getBlockOffset($this->ole->root->_StartBlock); + while ($blockId != -2) { + $pos = $rootPos + $blockId * $this->ole->bigBlockSize; + $blockId = $this->ole->sbat[$blockId]; + fseek($this->ole->_file_handle, $pos); + $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); + } + } else { + // Block id refers to big blocks + while ($blockId != -2) { + $pos = $this->ole->_getBlockOffset($blockId); + fseek($this->ole->_file_handle, $pos); + $this->data .= fread($this->ole->_file_handle, $this->ole->bigBlockSize); + $blockId = $this->ole->bbat[$blockId]; + } + } + if (isset($this->params['size'])) { + $this->data = substr($this->data, 0, $this->params['size']); + } + + if ($options & STREAM_USE_PATH) { + $openedPath = $path; + } + + return true; + } + + /** + * Implements support for fclose(). + * + */ + public function stream_close() + { + $this->ole = null; + unset($GLOBALS['_OLE_INSTANCES']); + } + + /** + * Implements support for fread(), fgets() etc. + * + * @param int $count maximum number of bytes to read + * @return string + */ + public function stream_read($count) + { + if ($this->stream_eof()) { + return false; + } + $s = substr($this->data, $this->pos, $count); + $this->pos += $count; + return $s; + } + + /** + * Implements support for feof(). + * + * @return bool TRUE if the file pointer is at EOF; otherwise FALSE + */ + public function stream_eof() + { + return $this->pos >= strlen($this->data); + } + + /** + * Returns the position of the file pointer, i.e. its offset into the file + * stream. Implements support for ftell(). + * + * @return int + */ + public function stream_tell() + { + return $this->pos; + } + + /** + * Implements support for fseek(). + * + * @param int $offset byte offset + * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END + * @return bool + */ + public function stream_seek($offset, $whence) + { + if ($whence == SEEK_SET && $offset >= 0) { + $this->pos = $offset; + } elseif ($whence == SEEK_CUR && -$offset <= $this->pos) { + $this->pos += $offset; + } elseif ($whence == SEEK_END && -$offset <= sizeof($this->data)) { + $this->pos = strlen($this->data) + $offset; + } else { + return false; + } + return true; + } + + /** + * Implements support for fstat(). Currently the only supported field is + * "size". + * @return array + */ + public function stream_stat() + { + return array( + 'size' => strlen($this->data), + ); + } + + // Methods used by stream_wrapper_register() that are not implemented: + // bool stream_flush ( void ) + // int stream_write ( string data ) + // bool rename ( string path_from, string path_to ) + // bool mkdir ( string path, int mode, int options ) + // bool rmdir ( string path, int options ) + // bool dir_opendir ( string path, int options ) + // array url_stat ( string path, int flags ) + // string dir_readdir ( void ) + // bool dir_rewinddir ( void ) + // bool dir_closedir ( void ) +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS.php new file mode 100644 index 00000000..608a892a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS.php @@ -0,0 +1,230 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: PPS.php,v 1.7 2007/02/13 21:00:42 schmidt Exp $ + + +/** +* Class for creating PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS +{ + /** + * The PPS index + * @var integer + */ + public $No; + + /** + * The PPS name (in Unicode) + * @var string + */ + public $Name; + + /** + * The PPS type. Dir, Root or File + * @var integer + */ + public $Type; + + /** + * The index of the previous PPS + * @var integer + */ + public $PrevPps; + + /** + * The index of the next PPS + * @var integer + */ + public $NextPps; + + /** + * The index of it's first child if this is a Dir or Root PPS + * @var integer + */ + public $DirPps; + + /** + * A timestamp + * @var integer + */ + public $Time1st; + + /** + * A timestamp + * @var integer + */ + public $Time2nd; + + /** + * Starting block (small or big) for this PPS's data inside the container + * @var integer + */ + public $_StartBlock; + + /** + * The size of the PPS's data (in bytes) + * @var integer + */ + public $Size; + + /** + * The PPS's data (only used if it's not using a temporary file) + * @var string + */ + public $_data; + + /** + * Array of child PPS's (only used by Root and Dir PPS's) + * @var array + */ + public $children = array(); + + /** + * Pointer to OLE container + * @var OLE + */ + public $ole; + + /** + * The constructor + * + * @access public + * @param integer $No The PPS index + * @param string $name The PPS name + * @param integer $type The PPS type. Dir, Root or File + * @param integer $prev The index of the previous PPS + * @param integer $next The index of the next PPS + * @param integer $dir The index of it's first child if this is a Dir or Root PPS + * @param integer $time_1st A timestamp + * @param integer $time_2nd A timestamp + * @param string $data The (usually binary) source data of the PPS + * @param array $children Array containing children PPS for this PPS + */ + public function __construct($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children) + { + $this->No = $No; + $this->Name = $name; + $this->Type = $type; + $this->PrevPps = $prev; + $this->NextPps = $next; + $this->DirPps = $dir; + $this->Time1st = $time_1st; + $this->Time2nd = $time_2nd; + $this->_data = $data; + $this->children = $children; + if ($data != '') { + $this->Size = strlen($data); + } else { + $this->Size = 0; + } + } + + /** + * Returns the amount of data saved for this PPS + * + * @access public + * @return integer The amount of data (in bytes) + */ + public function _DataLen() + { + if (!isset($this->_data)) { + return 0; + } + //if (isset($this->_PPS_FILE)) { + // fseek($this->_PPS_FILE, 0); + // $stats = fstat($this->_PPS_FILE); + // return $stats[7]; + //} else { + return strlen($this->_data); + //} + } + + /** + * Returns a string with the PPS's WK (What is a WK?) + * + * @access public + * @return string The binary string + */ + public function _getPpsWk() + { + $ret = str_pad($this->Name, 64, "\x00"); + + $ret .= pack("v", strlen($this->Name) + 2) // 66 + . pack("c", $this->Type) // 67 + . pack("c", 0x00) //UK // 68 + . pack("V", $this->PrevPps) //Prev // 72 + . pack("V", $this->NextPps) //Next // 76 + . pack("V", $this->DirPps) //Dir // 80 + . "\x00\x09\x02\x00" // 84 + . "\x00\x00\x00\x00" // 88 + . "\xc0\x00\x00\x00" // 92 + . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root + . "\x00\x00\x00\x00" // 100 + . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time1st) // 108 + . PHPExcel_Shared_OLE::LocalDate2OLE($this->Time2nd) // 116 + . pack("V", isset($this->_StartBlock)? + $this->_StartBlock:0) // 120 + . pack("V", $this->Size) // 124 + . pack("V", 0); // 128 + return $ret; + } + + /** + * Updates index and pointers to previous, next and children PPS's for this + * PPS. I don't think it'll work with Dir PPS's. + * + * @access public + * @param array &$raList Reference to the array of PPS's for the whole OLE + * container + * @return integer The index for this PPS + */ + public static function _savePpsSetPnt(&$raList, $to_save, $depth = 0) + { + if (!is_array($to_save) || (empty($to_save))) { + return 0xFFFFFFFF; + } elseif (count($to_save) == 1) { + $cnt = count($raList); + // If the first entry, it's the root... Don't clone it! + $raList[$cnt] = ( $depth == 0 ) ? $to_save[0] : clone $to_save[0]; + $raList[$cnt]->No = $cnt; + $raList[$cnt]->PrevPps = 0xFFFFFFFF; + $raList[$cnt]->NextPps = 0xFFFFFFFF; + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + } else { + $iPos = floor(count($to_save) / 2); + $aPrev = array_slice($to_save, 0, $iPos); + $aNext = array_slice($to_save, $iPos + 1); + $cnt = count($raList); + // If the first entry, it's the root... Don't clone it! + $raList[$cnt] = ( $depth == 0 ) ? $to_save[$iPos] : clone $to_save[$iPos]; + $raList[$cnt]->No = $cnt; + $raList[$cnt]->PrevPps = self::_savePpsSetPnt($raList, $aPrev, $depth++); + $raList[$cnt]->NextPps = self::_savePpsSetPnt($raList, $aNext, $depth++); + $raList[$cnt]->DirPps = self::_savePpsSetPnt($raList, @$raList[$cnt]->children, $depth++); + + } + return $cnt; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/File.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/File.php new file mode 100644 index 00000000..1ca337cb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/File.php @@ -0,0 +1,74 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: File.php,v 1.11 2007/02/13 21:00:42 schmidt Exp $ + + +/** +* Class for creating File PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS_File extends PHPExcel_Shared_OLE_PPS +{ + /** + * The constructor + * + * @access public + * @param string $name The name of the file (in Unicode) + * @see OLE::Asc2Ucs() + */ + public function __construct($name) + { + parent::__construct(null, $name, PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE, null, null, null, null, null, '', array()); + } + + /** + * Initialization method. Has to be called right after OLE_PPS_File(). + * + * @access public + * @return mixed true on success + */ + public function init() + { + return true; + } + + /** + * Append data to PPS + * + * @access public + * @param string $data The data to append + */ + public function append($data) + { + $this->_data .= $data; + } + + /** + * Returns a stream for reading this file using fread() etc. + * @return resource a read-only stream + */ + public function getStream() + { + $this->ole->getStream($this); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/Root.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/Root.php new file mode 100644 index 00000000..5d4052f0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLE/PPS/Root.php @@ -0,0 +1,462 @@ +<?php +/* vim: set expandtab tabstop=4 shiftwidth=4: */ +// +----------------------------------------------------------------------+ +// | PHP Version 4 | +// +----------------------------------------------------------------------+ +// | Copyright (c) 1997-2002 The PHP Group | +// +----------------------------------------------------------------------+ +// | This source file is subject to version 2.02 of the PHP license, | +// | that is bundled with this package in the file LICENSE, and is | +// | available at through the world-wide-web at | +// | http://www.php.net/license/2_02.txt. | +// | If you did not receive a copy of the PHP license and are unable to | +// | obtain it through the world-wide-web, please send a note to | +// | license@php.net so we can mail you a copy immediately. | +// +----------------------------------------------------------------------+ +// | Author: Xavier Noguer <xnoguer@php.net> | +// | Based on OLE::Storage_Lite by Kawai, Takanori | +// +----------------------------------------------------------------------+ +// +// $Id: Root.php,v 1.9 2005/04/23 21:53:49 dufuz Exp $ + + +/** +* Class for creating Root PPS's for OLE containers +* +* @author Xavier Noguer <xnoguer@php.net> +* @category PHPExcel +* @package PHPExcel_Shared_OLE +*/ +class PHPExcel_Shared_OLE_PPS_Root extends PHPExcel_Shared_OLE_PPS +{ + + /** + * Directory for temporary files + * @var string + */ + protected $tempDirectory = null; + + /** + * @param integer $time_1st A timestamp + * @param integer $time_2nd A timestamp + */ + public function __construct($time_1st, $time_2nd, $raChild) + { + $this->_tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + + parent::__construct(null, PHPExcel_Shared_OLE::Asc2Ucs('Root Entry'), PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT, null, null, null, $time_1st, $time_2nd, null, $raChild); + } + + /** + * Method for saving the whole OLE container (including files). + * In fact, if called with an empty argument (or '-'), it saves to a + * temporary file and then outputs it's contents to stdout. + * If a resource pointer to a stream created by fopen() is passed + * it will be used, but you have to close such stream by yourself. + * + * @param string|resource $filename The name of the file or stream where to save the OLE container. + * @access public + * @return mixed true on success + */ + public function save($filename) + { + // Initial Setting for saving + $this->_BIG_BLOCK_SIZE = pow( + 2, + (isset($this->_BIG_BLOCK_SIZE))? self::adjust2($this->_BIG_BLOCK_SIZE) : 9 + ); + $this->_SMALL_BLOCK_SIZE= pow( + 2, + (isset($this->_SMALL_BLOCK_SIZE))? self::adjust2($this->_SMALL_BLOCK_SIZE) : 6 + ); + + if (is_resource($filename)) { + $this->_FILEH_ = $filename; + } elseif ($filename == '-' || $filename == '') { + if ($this->tempDirectory === null) { + $this->tempDirectory = PHPExcel_Shared_File::sys_get_temp_dir(); + } + $this->_tmp_filename = tempnam($this->tempDirectory, "OLE_PPS_Root"); + $this->_FILEH_ = fopen($this->_tmp_filename, "w+b"); + if ($this->_FILEH_ == false) { + throw new PHPExcel_Writer_Exception("Can't create temporary file."); + } + } else { + $this->_FILEH_ = fopen($filename, "wb"); + } + if ($this->_FILEH_ == false) { + throw new PHPExcel_Writer_Exception("Can't open $filename. It may be in use or protected."); + } + // Make an array of PPS's (for Save) + $aList = array(); + PHPExcel_Shared_OLE_PPS::_savePpsSetPnt($aList, array($this)); + // calculate values for header + list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo); + // Save Header + $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt); + + // Make Small Data string (write SBD) + $this->_data = $this->_makeSmallData($aList); + + // Write BB + $this->_saveBigData($iSBDcnt, $aList); + // Write PPS + $this->_savePps($aList); + // Write Big Block Depot and BDList and Adding Header informations + $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt); + + if (!is_resource($filename)) { + fclose($this->_FILEH_); + } + + return true; + } + + /** + * Calculate some numbers + * + * @access public + * @param array $raList Reference to an array of PPS's + * @return array The array of numbers + */ + public function _calcSize(&$raList) + { + // Calculate Basic Setting + list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0); + $iSmallLen = 0; + $iSBcnt = 0; + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) { + $raList[$i]->Size = $raList[$i]->_DataLen(); + if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) { + $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); + } else { + $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); + } + } + } + $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE; + $iSlCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE); + $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0); + $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) + + (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0)); + $iCnt = count($raList); + $iBdCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE; + $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); + + return array($iSBDcnt, $iBBcnt, $iPPScnt); + } + + /** + * Helper function for caculating a magic value for block sizes + * + * @access public + * @param integer $i2 The argument + * @see save() + * @return integer + */ + private static function adjust2($i2) + { + $iWk = log($i2)/log(2); + return ($iWk > floor($iWk))? floor($iWk)+1:$iWk; + } + + /** + * Save OLE header + * + * @access public + * @param integer $iSBDcnt + * @param integer $iBBcnt + * @param integer $iPPScnt + */ + public function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) + { + $FILE = $this->_FILEH_; + + // Calculate Basic Setting + $iBlCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + + $iBdExL = 0; + $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; + $iAllW = $iAll; + $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); + + // Calculate BD count + if ($iBdCnt > $i1stBdL) { + while (1) { + ++$iBdExL; + ++$iAllW; + $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) { + break; + } + } + } + + // Save Header + fwrite( + $FILE, + "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . pack("v", 0x3b) + . pack("v", 0x03) + . pack("v", -2) + . pack("v", 9) + . pack("v", 6) + . pack("v", 0) + . "\x00\x00\x00\x00" + . "\x00\x00\x00\x00" + . pack("V", $iBdCnt) + . pack("V", $iBBcnt+$iSBDcnt) //ROOT START + . pack("V", 0) + . pack("V", 0x1000) + . pack("V", $iSBDcnt ? 0 : -2) //Small Block Depot + . pack("V", $iSBDcnt) + ); + // Extra BDList Start, Count + if ($iBdCnt < $i1stBdL) { + fwrite( + $FILE, + pack("V", -2) // Extra BDList Start + . pack("V", 0)// Extra BDList Count + ); + } else { + fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL)); + } + + // BDList + for ($i = 0; $i < $i1stBdL && $i < $iBdCnt; ++$i) { + fwrite($FILE, pack("V", $iAll+$i)); + } + if ($i < $i1stBdL) { + $jB = $i1stBdL - $i; + for ($j = 0; $j < $jB; ++$j) { + fwrite($FILE, (pack("V", -1))); + } + } + } + + /** + * Saving big data (PPS's with data bigger than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) + * + * @access public + * @param integer $iStBlk + * @param array &$raList Reference to array of PPS's + */ + public function _saveBigData($iStBlk, &$raList) + { + $FILE = $this->_FILEH_; + + // cycle through PPS's + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + if ($raList[$i]->Type != PHPExcel_Shared_OLE::OLE_PPS_TYPE_DIR) { + $raList[$i]->Size = $raList[$i]->_DataLen(); + if (($raList[$i]->Size >= PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) || (($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_ROOT) && isset($raList[$i]->_data))) { + // Write Data + //if (isset($raList[$i]->_PPS_FILE)) { + // $iLen = 0; + // fseek($raList[$i]->_PPS_FILE, 0); // To The Top + // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) { + // $iLen += strlen($sBuff); + // fwrite($FILE, $sBuff); + // } + //} else { + fwrite($FILE, $raList[$i]->_data); + //} + + if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) { + fwrite($FILE, str_repeat("\x00", $this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE))); + } + // Set For PPS + $raList[$i]->_StartBlock = $iStBlk; + $iStBlk += + (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); + } + // Close file for each PPS, and unlink it + //if (isset($raList[$i]->_PPS_FILE)) { + // fclose($raList[$i]->_PPS_FILE); + // $raList[$i]->_PPS_FILE = null; + // unlink($raList[$i]->_tmp_filename); + //} + } + } + } + + /** + * get small data (PPS's with data smaller than PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) + * + * @access public + * @param array &$raList Reference to array of PPS's + */ + public function _makeSmallData(&$raList) + { + $sRes = ''; + $FILE = $this->_FILEH_; + $iSmBlk = 0; + + $iCount = count($raList); + for ($i = 0; $i < $iCount; ++$i) { + // Make SBD, small data string + if ($raList[$i]->Type == PHPExcel_Shared_OLE::OLE_PPS_TYPE_FILE) { + if ($raList[$i]->Size <= 0) { + continue; + } + if ($raList[$i]->Size < PHPExcel_Shared_OLE::OLE_DATA_SIZE_SMALL) { + $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) + + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); + // Add to SBD + $jB = $iSmbCnt - 1; + for ($j = 0; $j < $jB; ++$j) { + fwrite($FILE, pack("V", $j+$iSmBlk+1)); + } + fwrite($FILE, pack("V", -2)); + + //// Add to Data String(this will be written for RootEntry) + //if ($raList[$i]->_PPS_FILE) { + // fseek($raList[$i]->_PPS_FILE, 0); // To The Top + // while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) { + // $sRes .= $sBuff; + // } + //} else { + $sRes .= $raList[$i]->_data; + //} + if ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) { + $sRes .= str_repeat("\x00", $this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)); + } + // Set for PPS + $raList[$i]->_StartBlock = $iSmBlk; + $iSmBlk += $iSmbCnt; + } + } + } + $iSbCnt = floor($this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE); + if ($iSmBlk % $iSbCnt) { + $iB = $iSbCnt - ($iSmBlk % $iSbCnt); + for ($i = 0; $i < $iB; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + return $sRes; + } + + /** + * Saves all the PPS's WKs + * + * @access public + * @param array $raList Reference to an array with all PPS's + */ + public function _savePps(&$raList) + { + // Save each PPS WK + $iC = count($raList); + for ($i = 0; $i < $iC; ++$i) { + fwrite($this->_FILEH_, $raList[$i]->_getPpsWk()); + } + // Adjust for Block + $iCnt = count($raList); + $iBCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_PPS_SIZE; + if ($iCnt % $iBCnt) { + fwrite($this->_FILEH_, str_repeat("\x00", ($iBCnt - ($iCnt % $iBCnt)) * PHPExcel_Shared_OLE::OLE_PPS_SIZE)); + } + } + + /** + * Saving Big Block Depot + * + * @access public + * @param integer $iSbdSize + * @param integer $iBsize + * @param integer $iPpsCnt + */ + public function _saveBbd($iSbdSize, $iBsize, $iPpsCnt) + { + $FILE = $this->_FILEH_; + // Calculate Basic Setting + $iBbCnt = $this->_BIG_BLOCK_SIZE / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / PHPExcel_Shared_OLE::OLE_LONG_INT_SIZE; + + $iBdExL = 0; + $iAll = $iBsize + $iPpsCnt + $iSbdSize; + $iAllW = $iAll; + $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); + $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); + // Calculate BD count + if ($iBdCnt >$i1stBdL) { + while (1) { + ++$iBdExL; + ++$iAllW; + $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); + $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); + if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) { + break; + } + } + } + + // Making BD + // Set for SBD + if ($iSbdSize > 0) { + for ($i = 0; $i < ($iSbdSize - 1); ++$i) { + fwrite($FILE, pack("V", $i+1)); + } + fwrite($FILE, pack("V", -2)); + } + // Set for B + for ($i = 0; $i < ($iBsize - 1); ++$i) { + fwrite($FILE, pack("V", $i+$iSbdSize+1)); + } + fwrite($FILE, pack("V", -2)); + + // Set for PPS + for ($i = 0; $i < ($iPpsCnt - 1); ++$i) { + fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1)); + } + fwrite($FILE, pack("V", -2)); + // Set for BBD itself ( 0xFFFFFFFD : BBD) + for ($i = 0; $i < $iBdCnt; ++$i) { + fwrite($FILE, pack("V", 0xFFFFFFFD)); + } + // Set for ExtraBDList + for ($i = 0; $i < $iBdExL; ++$i) { + fwrite($FILE, pack("V", 0xFFFFFFFC)); + } + // Adjust for Block + if (($iAllW + $iBdCnt) % $iBbCnt) { + $iBlock = ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); + for ($i = 0; $i < $iBlock; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + // Extra BDList + if ($iBdCnt > $i1stBdL) { + $iN=0; + $iNb=0; + for ($i = $i1stBdL; $i < $iBdCnt; $i++, ++$iN) { + if ($iN >= ($iBbCnt - 1)) { + $iN = 0; + ++$iNb; + fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb)); + } + fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i)); + } + if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) { + $iB = ($iBbCnt - 1) - (($iBdCnt - $i1stBdL) % ($iBbCnt - 1)); + for ($i = 0; $i < $iB; ++$i) { + fwrite($FILE, pack("V", -1)); + } + } + fwrite($FILE, pack("V", -2)); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLERead.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLERead.php new file mode 100644 index 00000000..6b15d970 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/OLERead.php @@ -0,0 +1,318 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +defined('IDENTIFIER_OLE') || + define('IDENTIFIER_OLE', pack('CCCCCCCC', 0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1)); + +class PHPExcel_Shared_OLERead +{ + private $data = ''; + + // OLE identifier + const IDENTIFIER_OLE = IDENTIFIER_OLE; + + // Size of a sector = 512 bytes + const BIG_BLOCK_SIZE = 0x200; + + // Size of a short sector = 64 bytes + const SMALL_BLOCK_SIZE = 0x40; + + // Size of a directory entry always = 128 bytes + const PROPERTY_STORAGE_BLOCK_SIZE = 0x80; + + // Minimum size of a standard stream = 4096 bytes, streams smaller than this are stored as short streams + const SMALL_BLOCK_THRESHOLD = 0x1000; + + // header offsets + const NUM_BIG_BLOCK_DEPOT_BLOCKS_POS = 0x2c; + const ROOT_START_BLOCK_POS = 0x30; + const SMALL_BLOCK_DEPOT_BLOCK_POS = 0x3c; + const EXTENSION_BLOCK_POS = 0x44; + const NUM_EXTENSION_BLOCK_POS = 0x48; + const BIG_BLOCK_DEPOT_BLOCKS_POS = 0x4c; + + // property storage offsets (directory offsets) + const SIZE_OF_NAME_POS = 0x40; + const TYPE_POS = 0x42; + const START_BLOCK_POS = 0x74; + const SIZE_POS = 0x78; + + + + public $wrkbook = null; + public $summaryInformation = null; + public $documentSummaryInformation = null; + + + /** + * Read the file + * + * @param $sFileName string Filename + * @throws PHPExcel_Reader_Exception + */ + public function read($sFileName) + { + // Check if file exists and is readable + if (!is_readable($sFileName)) { + throw new PHPExcel_Reader_Exception("Could not open " . $sFileName . " for reading! File does not exist, or it is not readable."); + } + + // Get the file identifier + // Don't bother reading the whole file until we know it's a valid OLE file + $this->data = file_get_contents($sFileName, false, null, 0, 8); + + // Check OLE identifier + if ($this->data != self::IDENTIFIER_OLE) { + throw new PHPExcel_Reader_Exception('The filename ' . $sFileName . ' is not recognised as an OLE file'); + } + + // Get the file data + $this->data = file_get_contents($sFileName); + + // Total number of sectors used for the SAT + $this->numBigBlockDepotBlocks = self::getInt4d($this->data, self::NUM_BIG_BLOCK_DEPOT_BLOCKS_POS); + + // SecID of the first sector of the directory stream + $this->rootStartBlock = self::getInt4d($this->data, self::ROOT_START_BLOCK_POS); + + // SecID of the first sector of the SSAT (or -2 if not extant) + $this->sbdStartBlock = self::getInt4d($this->data, self::SMALL_BLOCK_DEPOT_BLOCK_POS); + + // SecID of the first sector of the MSAT (or -2 if no additional sectors are used) + $this->extensionBlock = self::getInt4d($this->data, self::EXTENSION_BLOCK_POS); + + // Total number of sectors used by MSAT + $this->numExtensionBlocks = self::getInt4d($this->data, self::NUM_EXTENSION_BLOCK_POS); + + $bigBlockDepotBlocks = array(); + $pos = self::BIG_BLOCK_DEPOT_BLOCKS_POS; + + $bbdBlocks = $this->numBigBlockDepotBlocks; + + if ($this->numExtensionBlocks != 0) { + $bbdBlocks = (self::BIG_BLOCK_SIZE - self::BIG_BLOCK_DEPOT_BLOCKS_POS)/4; + } + + for ($i = 0; $i < $bbdBlocks; ++$i) { + $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); + $pos += 4; + } + + for ($j = 0; $j < $this->numExtensionBlocks; ++$j) { + $pos = ($this->extensionBlock + 1) * self::BIG_BLOCK_SIZE; + $blocksToRead = min($this->numBigBlockDepotBlocks - $bbdBlocks, self::BIG_BLOCK_SIZE / 4 - 1); + + for ($i = $bbdBlocks; $i < $bbdBlocks + $blocksToRead; ++$i) { + $bigBlockDepotBlocks[$i] = self::getInt4d($this->data, $pos); + $pos += 4; + } + + $bbdBlocks += $blocksToRead; + if ($bbdBlocks < $this->numBigBlockDepotBlocks) { + $this->extensionBlock = self::getInt4d($this->data, $pos); + } + } + + $pos = 0; + $this->bigBlockChain = ''; + $bbs = self::BIG_BLOCK_SIZE / 4; + for ($i = 0; $i < $this->numBigBlockDepotBlocks; ++$i) { + $pos = ($bigBlockDepotBlocks[$i] + 1) * self::BIG_BLOCK_SIZE; + + $this->bigBlockChain .= substr($this->data, $pos, 4*$bbs); + $pos += 4*$bbs; + } + + $pos = 0; + $sbdBlock = $this->sbdStartBlock; + $this->smallBlockChain = ''; + while ($sbdBlock != -2) { + $pos = ($sbdBlock + 1) * self::BIG_BLOCK_SIZE; + + $this->smallBlockChain .= substr($this->data, $pos, 4*$bbs); + $pos += 4*$bbs; + + $sbdBlock = self::getInt4d($this->bigBlockChain, $sbdBlock*4); + } + + // read the directory stream + $block = $this->rootStartBlock; + $this->entry = $this->_readData($block); + + $this->readPropertySets(); + } + + /** + * Extract binary stream data + * + * @return string + */ + public function getStream($stream) + { + if ($stream === null) { + return null; + } + + $streamData = ''; + + if ($this->props[$stream]['size'] < self::SMALL_BLOCK_THRESHOLD) { + $rootdata = $this->_readData($this->props[$this->rootentry]['startBlock']); + + $block = $this->props[$stream]['startBlock']; + + while ($block != -2) { + $pos = $block * self::SMALL_BLOCK_SIZE; + $streamData .= substr($rootdata, $pos, self::SMALL_BLOCK_SIZE); + + $block = self::getInt4d($this->smallBlockChain, $block*4); + } + + return $streamData; + } else { + $numBlocks = $this->props[$stream]['size'] / self::BIG_BLOCK_SIZE; + if ($this->props[$stream]['size'] % self::BIG_BLOCK_SIZE != 0) { + ++$numBlocks; + } + + if ($numBlocks == 0) { + return ''; + } + + $block = $this->props[$stream]['startBlock']; + + while ($block != -2) { + $pos = ($block + 1) * self::BIG_BLOCK_SIZE; + $streamData .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + $block = self::getInt4d($this->bigBlockChain, $block*4); + } + + return $streamData; + } + } + + /** + * Read a standard stream (by joining sectors using information from SAT) + * + * @param int $bl Sector ID where the stream starts + * @return string Data for standard stream + */ + private function _readData($bl) + { + $block = $bl; + $data = ''; + + while ($block != -2) { + $pos = ($block + 1) * self::BIG_BLOCK_SIZE; + $data .= substr($this->data, $pos, self::BIG_BLOCK_SIZE); + $block = self::getInt4d($this->bigBlockChain, $block*4); + } + return $data; + } + + /** + * Read entries in the directory stream. + */ + private function readPropertySets() + { + $offset = 0; + + // loop through entires, each entry is 128 bytes + $entryLen = strlen($this->entry); + while ($offset < $entryLen) { + // entry data (128 bytes) + $d = substr($this->entry, $offset, self::PROPERTY_STORAGE_BLOCK_SIZE); + + // size in bytes of name + $nameSize = ord($d[self::SIZE_OF_NAME_POS]) | (ord($d[self::SIZE_OF_NAME_POS+1]) << 8); + + // type of entry + $type = ord($d[self::TYPE_POS]); + + // sectorID of first sector or short sector, if this entry refers to a stream (the case with workbook) + // sectorID of first sector of the short-stream container stream, if this entry is root entry + $startBlock = self::getInt4d($d, self::START_BLOCK_POS); + + $size = self::getInt4d($d, self::SIZE_POS); + + $name = str_replace("\x00", "", substr($d, 0, $nameSize)); + + $this->props[] = array( + 'name' => $name, + 'type' => $type, + 'startBlock' => $startBlock, + 'size' => $size + ); + + // tmp helper to simplify checks + $upName = strtoupper($name); + + // Workbook directory entry (BIFF5 uses Book, BIFF8 uses Workbook) + if (($upName === 'WORKBOOK') || ($upName === 'BOOK')) { + $this->wrkbook = count($this->props) - 1; + } elseif ($upName === 'ROOT ENTRY' || $upName === 'R') { + // Root entry + $this->rootentry = count($this->props) - 1; + } + + // Summary information + if ($name == chr(5) . 'SummaryInformation') { +// echo 'Summary Information<br />'; + $this->summaryInformation = count($this->props) - 1; + } + + // Additional Document Summary information + if ($name == chr(5) . 'DocumentSummaryInformation') { +// echo 'Document Summary Information<br />'; + $this->documentSummaryInformation = count($this->props) - 1; + } + + $offset += self::PROPERTY_STORAGE_BLOCK_SIZE; + } + } + + /** + * Read 4 bytes of data at specified position + * + * @param string $data + * @param int $pos + * @return int + */ + private static function getInt4d($data, $pos) + { + // FIX: represent numbers correctly on 64-bit system + // http://sourceforge.net/tracker/index.php?func=detail&aid=1487372&group_id=99160&atid=623334 + // Hacked by Andreas Rehm 2006 to ensure correct result of the <<24 block on 32 and 64bit systems + $_or_24 = ord($data[$pos + 3]); + if ($_or_24 >= 128) { + // negative number + $_ord_24 = -abs((256 - $_or_24) << 24); + } else { + $_ord_24 = ($_or_24 & 127) << 24; + } + return ord($data[$pos]) | (ord($data[$pos + 1]) << 8) | (ord($data[$pos + 2]) << 16) | $_ord_24; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/gnu-lgpl.txt b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/gnu-lgpl.txt new file mode 100644 index 00000000..b1e3f5a2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/gnu-lgpl.txt @@ -0,0 +1,504 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/pclzip.lib.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/pclzip.lib.php new file mode 100644 index 00000000..a5a9b0a8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/pclzip.lib.php @@ -0,0 +1,5173 @@ +<?php +// -------------------------------------------------------------------------------- +// PhpConcept Library - Zip Module 2.8.2 +// -------------------------------------------------------------------------------- +// License GNU/LGPL - Vincent Blavet - August 2009 +// http://www.phpconcept.net +// -------------------------------------------------------------------------------- +// +// Presentation : +// PclZip is a PHP library that manage ZIP archives. +// So far tests show that archives generated by PclZip are readable by +// WinZip application and other tools. +// +// Description : +// See readme.txt and http://www.phpconcept.net +// +// Warning : +// This library and the associated files are non commercial, non professional +// work. +// It should not have unexpected results. However if any damage is caused by +// this software the author can not be responsible. +// The use of this software is at the risk of the user. +// +// -------------------------------------------------------------------------------- +// $Id: pclzip.lib.php,v 1.60 2009/09/30 21:01:04 vblavet Exp $ +// -------------------------------------------------------------------------------- + +// ----- Constants +if (!defined('PCLZIP_READ_BLOCK_SIZE')) { + define('PCLZIP_READ_BLOCK_SIZE', 2048); +} + +// ----- File list separator +// In version 1.x of PclZip, the separator for file list is a space +// (which is not a very smart choice, specifically for windows paths !). +// A better separator should be a comma (,). This constant gives you the +// abilty to change that. +// However notice that changing this value, may have impact on existing +// scripts, using space separated filenames. +// Recommanded values for compatibility with older versions : +//define('PCLZIP_SEPARATOR', ' '); +// Recommanded values for smart separation of filenames. +if (!defined('PCLZIP_SEPARATOR')) { + define('PCLZIP_SEPARATOR', ','); +} + +// ----- Error configuration +// 0 : PclZip Class integrated error handling +// 1 : PclError external library error handling. By enabling this +// you must ensure that you have included PclError library. +// [2,...] : reserved for futur use +if (!defined('PCLZIP_ERROR_EXTERNAL')) { + define('PCLZIP_ERROR_EXTERNAL', 0); +} + +// ----- Optional static temporary directory +// By default temporary files are generated in the script current +// path. +// If defined : +// - MUST BE terminated by a '/'. +// - MUST be a valid, already created directory +// Samples : +// define('PCLZIP_TEMPORARY_DIR', '/temp/'); +// define('PCLZIP_TEMPORARY_DIR', 'C:/Temp/'); +if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', ''); +} + +// ----- Optional threshold ratio for use of temporary files +// Pclzip sense the size of the file to add/extract and decide to +// use or not temporary file. The algorythm is looking for +// memory_limit of PHP and apply a ratio. +// threshold = memory_limit * ratio. +// Recommended values are under 0.5. Default 0.47. +// Samples : +// define('PCLZIP_TEMPORARY_FILE_RATIO', 0.5); +if (!defined('PCLZIP_TEMPORARY_FILE_RATIO')) { + define('PCLZIP_TEMPORARY_FILE_RATIO', 0.47); +} + +// -------------------------------------------------------------------------------- +// ***** UNDER THIS LINE NOTHING NEEDS TO BE MODIFIED ***** +// -------------------------------------------------------------------------------- + +// ----- Global variables +$g_pclzip_version = "2.8.2"; + +// ----- Error codes +// -1 : Unable to open file in binary write mode +// -2 : Unable to open file in binary read mode +// -3 : Invalid parameters +// -4 : File does not exist +// -5 : Filename is too long (max. 255) +// -6 : Not a valid zip file +// -7 : Invalid extracted file size +// -8 : Unable to create directory +// -9 : Invalid archive extension +// -10 : Invalid archive format +// -11 : Unable to delete file (unlink) +// -12 : Unable to rename file (rename) +// -13 : Invalid header checksum +// -14 : Invalid archive size +define('PCLZIP_ERR_USER_ABORTED', 2); +define('PCLZIP_ERR_NO_ERROR', 0); +define('PCLZIP_ERR_WRITE_OPEN_FAIL', -1); +define('PCLZIP_ERR_READ_OPEN_FAIL', -2); +define('PCLZIP_ERR_INVALID_PARAMETER', -3); +define('PCLZIP_ERR_MISSING_FILE', -4); +define('PCLZIP_ERR_FILENAME_TOO_LONG', -5); +define('PCLZIP_ERR_INVALID_ZIP', -6); +define('PCLZIP_ERR_BAD_EXTRACTED_FILE', -7); +define('PCLZIP_ERR_DIR_CREATE_FAIL', -8); +define('PCLZIP_ERR_BAD_EXTENSION', -9); +define('PCLZIP_ERR_BAD_FORMAT', -10); +define('PCLZIP_ERR_DELETE_FILE_FAIL', -11); +define('PCLZIP_ERR_RENAME_FILE_FAIL', -12); +define('PCLZIP_ERR_BAD_CHECKSUM', -13); +define('PCLZIP_ERR_INVALID_ARCHIVE_ZIP', -14); +define('PCLZIP_ERR_MISSING_OPTION_VALUE', -15); +define('PCLZIP_ERR_INVALID_OPTION_VALUE', -16); +define('PCLZIP_ERR_ALREADY_A_DIRECTORY', -17); +define('PCLZIP_ERR_UNSUPPORTED_COMPRESSION', -18); +define('PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', -19); +define('PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', -20); +define('PCLZIP_ERR_DIRECTORY_RESTRICTION', -21); + +// ----- Options values +define('PCLZIP_OPT_PATH', 77001); +define('PCLZIP_OPT_ADD_PATH', 77002); +define('PCLZIP_OPT_REMOVE_PATH', 77003); +define('PCLZIP_OPT_REMOVE_ALL_PATH', 77004); +define('PCLZIP_OPT_SET_CHMOD', 77005); +define('PCLZIP_OPT_EXTRACT_AS_STRING', 77006); +define('PCLZIP_OPT_NO_COMPRESSION', 77007); +define('PCLZIP_OPT_BY_NAME', 77008); +define('PCLZIP_OPT_BY_INDEX', 77009); +define('PCLZIP_OPT_BY_EREG', 77010); +define('PCLZIP_OPT_BY_PREG', 77011); +define('PCLZIP_OPT_COMMENT', 77012); +define('PCLZIP_OPT_ADD_COMMENT', 77013); +define('PCLZIP_OPT_PREPEND_COMMENT', 77014); +define('PCLZIP_OPT_EXTRACT_IN_OUTPUT', 77015); +define('PCLZIP_OPT_REPLACE_NEWER', 77016); +define('PCLZIP_OPT_STOP_ON_ERROR', 77017); +// Having big trouble with crypt. Need to multiply 2 long int +// which is not correctly supported by PHP ... +//define('PCLZIP_OPT_CRYPT', 77018); +define('PCLZIP_OPT_EXTRACT_DIR_RESTRICTION', 77019); +define('PCLZIP_OPT_TEMP_FILE_THRESHOLD', 77020); +define('PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD', 77020); // alias +define('PCLZIP_OPT_TEMP_FILE_ON', 77021); +define('PCLZIP_OPT_ADD_TEMP_FILE_ON', 77021); // alias +define('PCLZIP_OPT_TEMP_FILE_OFF', 77022); +define('PCLZIP_OPT_ADD_TEMP_FILE_OFF', 77022); // alias + +// ----- File description attributes +define('PCLZIP_ATT_FILE_NAME', 79001); +define('PCLZIP_ATT_FILE_NEW_SHORT_NAME', 79002); +define('PCLZIP_ATT_FILE_NEW_FULL_NAME', 79003); +define('PCLZIP_ATT_FILE_MTIME', 79004); +define('PCLZIP_ATT_FILE_CONTENT', 79005); +define('PCLZIP_ATT_FILE_COMMENT', 79006); + +// ----- Call backs values +define('PCLZIP_CB_PRE_EXTRACT', 78001); +define('PCLZIP_CB_POST_EXTRACT', 78002); +define('PCLZIP_CB_PRE_ADD', 78003); +define('PCLZIP_CB_POST_ADD', 78004); +/* For futur use +define('PCLZIP_CB_PRE_LIST', 78005); +define('PCLZIP_CB_POST_LIST', 78006); +define('PCLZIP_CB_PRE_DELETE', 78007); +define('PCLZIP_CB_POST_DELETE', 78008); +*/ + +// -------------------------------------------------------------------------------- +// Class : PclZip +// Description : +// PclZip is the class that represent a Zip archive. +// The public methods allow the manipulation of the archive. +// Attributes : +// Attributes must not be accessed directly. +// Methods : +// PclZip() : Object creator +// create() : Creates the Zip archive +// listContent() : List the content of the Zip archive +// extract() : Extract the content of the archive +// properties() : List the properties of the archive +// -------------------------------------------------------------------------------- +class PclZip +{ + // ----- Filename of the zip file + public $zipname = ''; + + // ----- File descriptor of the zip file + public $zip_fd = 0; + + // ----- Internal error handling + public $error_code = 1; + public $error_string = ''; + + // ----- Current status of the magic_quotes_runtime + // This value store the php configuration for magic_quotes + // The class can then disable the magic_quotes and reset it after + public $magic_quotes_status; + + // -------------------------------------------------------------------------------- + // Function : PclZip() + // Description : + // Creates a PclZip object and set the name of the associated Zip archive + // filename. + // Note that no real action is taken, if the archive does not exist it is not + // created. Use create() for that. + // -------------------------------------------------------------------------------- + public function __construct($p_zipname) + { + + // ----- Tests the zlib + if (!function_exists('gzopen')) { + die('Abort '.basename(__FILE__).' : Missing zlib extensions'); + } + + // ----- Set the attributes + $this->zipname = $p_zipname; + $this->zip_fd = 0; + $this->magic_quotes_status = -1; + + // ----- Return + return; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // create($p_filelist, $p_add_dir="", $p_remove_dir="") + // create($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two different synopsis. The first one is historical. + // This method creates a Zip Archive. The Zip file is created in the + // filesystem. The files and directories indicated in $p_filelist + // are added in the archive. See the parameters description for the + // supported format of $p_filelist. + // When a directory is in the list, the directory and its content is added + // in the archive. + // In this synopsis, the function takes an optional variable list of + // options. See bellow the supported options. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function create($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove from the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } elseif ($v_size > 2) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } else { + // ----- The list is a list of string names + $v_string_list = $p_filelist; + } + } elseif (is_string($p_filelist)) { + // ----- Look if the $p_filelist is a string + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } else { + // ----- Invalid variable type for $p_filelist + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + if ($v_string != '') { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } else { + } + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional' + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privCreate($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // add($p_filelist, $p_add_dir="", $p_remove_dir="") + // add($p_filelist, $p_option, $p_option_value, ...) + // Description : + // This method supports two synopsis. The first one is historical. + // This methods add the list of files in an existing archive. + // If a file with the same name already exists, it is added at the end of the + // archive, the first one is still present. + // If the archive does not exist, it is created. + // Parameters : + // $p_filelist : An array containing file or directory names, or + // a string containing one filename or one directory name, or + // a string containing a list of filenames and/or directory + // names separated by spaces. + // $p_add_dir : A path to add before the real path of the archived file, + // in order to have it memorized in the archive. + // $p_remove_dir : A path to remove from the real path of the file to archive, + // in order to have a shorter path memorized in the archive. + // When $p_add_dir and $p_remove_dir are set, $p_remove_dir + // is removed first, before $p_add_dir is added. + // Options : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_COMMENT : + // PCLZIP_OPT_ADD_COMMENT : + // PCLZIP_OPT_PREPEND_COMMENT : + // PCLZIP_CB_PRE_ADD : + // PCLZIP_CB_POST_ADD : + // Return Values : + // 0 on failure, + // The list of the added files, with a status of the add action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function add($p_filelist) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Set default values + $v_options = array(); + $v_options[PCLZIP_OPT_NO_COMPRESSION] = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_ADD => 'optional', + PCLZIP_CB_POST_ADD => 'optional', + PCLZIP_OPT_NO_COMPRESSION => 'optional', + PCLZIP_OPT_COMMENT => 'optional', + PCLZIP_OPT_ADD_COMMENT => 'optional', + PCLZIP_OPT_PREPEND_COMMENT => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + //, PCLZIP_OPT_CRYPT => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + // ----- Get the first argument + $v_options[PCLZIP_OPT_ADD_PATH] = $v_add_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_options[PCLZIP_OPT_REMOVE_PATH] = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Init + $v_string_list = array(); + $v_att_list = array(); + $v_filedescr_list = array(); + $p_result_list = array(); + + // ----- Look if the $p_filelist is really an array + if (is_array($p_filelist)) { + // ----- Look if the first element is also an array + // This will mean that this is a file description entry + if (isset($p_filelist[0]) && is_array($p_filelist[0])) { + $v_att_list = $p_filelist; + } else { + // ----- The list is a list of string names + $v_string_list = $p_filelist; + } + } elseif (is_string($p_filelist)) { + // ----- Look if the $p_filelist is a string + // ----- Create a list from the string + $v_string_list = explode(PCLZIP_SEPARATOR, $p_filelist); + } else { + // ----- Invalid variable type for $p_filelist + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type '".gettype($p_filelist)."' for p_filelist"); + return 0; + } + + // ----- Reformat the string list + if (sizeof($v_string_list) != 0) { + foreach ($v_string_list as $v_string) { + $v_att_list[][PCLZIP_ATT_FILE_NAME] = $v_string; + } + } + + // ----- For each file in the list check the attributes + $v_supported_attributes = array( + PCLZIP_ATT_FILE_NAME => 'mandatory', + PCLZIP_ATT_FILE_NEW_SHORT_NAME => 'optional', + PCLZIP_ATT_FILE_NEW_FULL_NAME => 'optional', + PCLZIP_ATT_FILE_MTIME => 'optional', + PCLZIP_ATT_FILE_CONTENT => 'optional', + PCLZIP_ATT_FILE_COMMENT => 'optional', + ); + foreach ($v_att_list as $v_entry) { + $v_result = $this->privFileDescrParseAtt($v_entry, $v_filedescr_list[], $v_options, $v_supported_attributes); + if ($v_result != 1) { + return 0; + } + } + + // ----- Expand the filelist (expand directories) + $v_result = $this->privFileDescrExpand($v_filedescr_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Call the create fct + $v_result = $this->privAdd($v_filedescr_list, $p_result_list, $v_options); + if ($v_result != 1) { + return 0; + } + + // ----- Return + return $p_result_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : listContent() + // Description : + // This public method, gives the list of the files and directories, with their + // properties. + // The properties of each entries in the list are (used also in other functions) : + // filename : Name of the file. For a create or add action it is the filename + // given by the user. For an extract function it is the filename + // of the extracted file. + // stored_filename : Name of the file / directory stored in the archive. + // size : Size of the stored file. + // compressed_size : Size of the file's data compressed in the archive + // (without the headers overhead) + // mtime : Last known modification date of the file (UNIX timestamp) + // comment : Comment associated with the file + // folder : true | false + // index : index of the file in the archive + // status : status of the action (depending of the action) : + // Values are : + // ok : OK ! + // filtered : the file / dir is not extracted (filtered by user) + // already_a_directory : the file can not be extracted because a + // directory with the same name already exists + // write_protected : the file can not be extracted because a file + // with the same name already exists and is + // write protected + // newer_exist : the file was not extracted because a newer file exists + // path_creation_fail : the file is not extracted because the folder + // does not exist and can not be created + // write_error : the file was not extracted because there was a + // error while writing the file + // read_error : the file was not extracted because there was a error + // while reading the file + // invalid_header : the file was not extracted because of an archive + // format error (bad file header) + // Note that each time a method can continue operating when there + // is an action error on a file, the error is only logged in the file status. + // Return Values : + // 0 on an unrecoverable failure, + // The list of the files in the archive. + // -------------------------------------------------------------------------------- + public function listContent() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Call the extracting fct + $p_list = array(); + if (($v_result = $this->privList($p_list)) != 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // extract($p_path="./", $p_remove_path="") + // extract([$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method extract all the files / directories from the archive to the + // folder indicated in $p_path. + // If you want to ignore the 'root' part of path of the memorized files + // you can indicate this in the optional $p_remove_path parameter. + // By default, if a newer file with the same name already exists, the + // file is not extracted. + // + // If both PCLZIP_OPT_PATH and PCLZIP_OPT_ADD_PATH aoptions + // are used, the path indicated in PCLZIP_OPT_ADD_PATH is append + // at the end of the path value of PCLZIP_OPT_PATH. + // Parameters : + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 or a negative value on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function extract() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_EXTRACT_IN_OUTPUT => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Trace + + // ----- Call the extracting fct + $p_list = array(); + $v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options); + if ($v_result < 1) { + unset($p_list); + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // Function : + // extractByIndex($p_index, $p_path="./", $p_remove_path="") + // extractByIndex($p_index, [$p_option, $p_option_value, ...]) + // Description : + // This method supports two synopsis. The first one is historical. + // This method is doing a partial extract of the archive. + // The extracted files or folders are identified by their index in the + // archive (from 0 to n). + // Note that if the index identify a folder, only the folder entry is + // extracted, not all the files included in the archive. + // Parameters : + // $p_index : A single index (integer) or a string of indexes of files to + // extract. The form of the string is "0,4-6,8-12" with only numbers + // and '-' for range or ',' to separate ranges. No spaces or ';' + // are allowed. + // $p_path : Path where the files and directories are to be extracted + // $p_remove_path : First part ('root' part) of the memorized path + // (if any similar) to remove while extracting. + // Options : + // PCLZIP_OPT_PATH : + // PCLZIP_OPT_ADD_PATH : + // PCLZIP_OPT_REMOVE_PATH : + // PCLZIP_OPT_REMOVE_ALL_PATH : + // PCLZIP_OPT_EXTRACT_AS_STRING : The files are extracted as strings and + // not as files. + // The resulting content is in a new field 'content' in the file + // structure. + // This option must be used alone (any other options are ignored). + // PCLZIP_CB_PRE_EXTRACT : + // PCLZIP_CB_POST_EXTRACT : + // Return Values : + // 0 on failure, + // The list of the extracted files, with a status of the action. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + //function extractByIndex($p_index, options...) + public function extractByIndex($p_index) + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + // $v_path = "./"; + $v_path = ''; + $v_remove_path = ""; + $v_remove_all_path = false; + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Default values for option + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + + // ----- Look for arguments + if ($v_size > 1) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Remove form the options list the first argument + array_shift($v_arg_list); + $v_size--; + + // ----- Look for first arg + if ((is_integer($v_arg_list[0])) && ($v_arg_list[0] > 77000)) { + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array( + PCLZIP_OPT_PATH => 'optional', + PCLZIP_OPT_REMOVE_PATH => 'optional', + PCLZIP_OPT_REMOVE_ALL_PATH => 'optional', + PCLZIP_OPT_EXTRACT_AS_STRING => 'optional', + PCLZIP_OPT_ADD_PATH => 'optional', + PCLZIP_CB_PRE_EXTRACT => 'optional', + PCLZIP_CB_POST_EXTRACT => 'optional', + PCLZIP_OPT_SET_CHMOD => 'optional', + PCLZIP_OPT_REPLACE_NEWER => 'optional', + PCLZIP_OPT_STOP_ON_ERROR => 'optional', + PCLZIP_OPT_EXTRACT_DIR_RESTRICTION => 'optional', + PCLZIP_OPT_TEMP_FILE_THRESHOLD => 'optional', + PCLZIP_OPT_TEMP_FILE_ON => 'optional', + PCLZIP_OPT_TEMP_FILE_OFF => 'optional' + )); + if ($v_result != 1) { + return 0; + } + + // ----- Set the arguments + if (isset($v_options[PCLZIP_OPT_PATH])) { + $v_path = $v_options[PCLZIP_OPT_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_PATH])) { + $v_remove_path = $v_options[PCLZIP_OPT_REMOVE_PATH]; + } + if (isset($v_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $v_remove_all_path = $v_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } + if (isset($v_options[PCLZIP_OPT_ADD_PATH])) { + // ----- Check for '/' in last path char + if ((strlen($v_path) > 0) && (substr($v_path, -1) != '/')) { + $v_path .= '/'; + } + $v_path .= $v_options[PCLZIP_OPT_ADD_PATH]; + } + if (!isset($v_options[PCLZIP_OPT_EXTRACT_AS_STRING])) { + $v_options[PCLZIP_OPT_EXTRACT_AS_STRING] = false; + } else { + } + } else { + // ----- Look for 2 args + // Here we need to support the first historic synopsis of the + // method. + + // ----- Get the first argument + $v_path = $v_arg_list[0]; + + // ----- Look for the optional second argument + if ($v_size == 2) { + $v_remove_path = $v_arg_list[1]; + } elseif ($v_size > 2) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid number / type of arguments"); + + // ----- Return + return 0; + } + } + } + + // ----- Trace + + // ----- Trick + // Here I want to reuse extractByRule(), so I need to parse the $p_index + // with privParseOptions() + $v_arg_trick = array (PCLZIP_OPT_BY_INDEX, $p_index); + $v_options_trick = array(); + $v_result = $this->privParseOptions($v_arg_trick, sizeof($v_arg_trick), $v_options_trick, array (PCLZIP_OPT_BY_INDEX => 'optional')); + if ($v_result != 1) { + return 0; + } + $v_options[PCLZIP_OPT_BY_INDEX] = $v_options_trick[PCLZIP_OPT_BY_INDEX]; + + // ----- Look for default option values + $this->privOptionDefaultThreshold($v_options); + + // ----- Call the extracting fct + if (($v_result = $this->privExtractByRule($p_list, $v_path, $v_remove_path, $v_remove_all_path, $v_options)) < 1) { + return(0); + } + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : + // delete([$p_option, $p_option_value, ...]) + // Description : + // This method removes files from the archive. + // If no parameters are given, then all the archive is emptied. + // Parameters : + // None or optional arguments. + // Options : + // PCLZIP_OPT_BY_INDEX : + // PCLZIP_OPT_BY_NAME : + // PCLZIP_OPT_BY_EREG : + // PCLZIP_OPT_BY_PREG : + // Return Values : + // 0 on failure, + // The list of the files which are still present in the archive. + // (see PclZip::listContent() for list entry format) + // -------------------------------------------------------------------------------- + public function delete() + { + $v_result=1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Set default values + $v_options = array(); + + // ----- Look for variable options arguments + $v_size = func_num_args(); + + // ----- Look for arguments + if ($v_size > 0) { + // ----- Get the arguments + $v_arg_list = func_get_args(); + + // ----- Parse the options + $v_result = $this->privParseOptions($v_arg_list, $v_size, $v_options, array ( + PCLZIP_OPT_BY_NAME => 'optional', + PCLZIP_OPT_BY_EREG => 'optional', + PCLZIP_OPT_BY_PREG => 'optional', + PCLZIP_OPT_BY_INDEX => 'optional' + )); + if ($v_result != 1) { + return 0; + } + } + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Call the delete fct + $v_list = array(); + if (($v_result = $this->privDeleteByRule($v_list, $v_options)) != 1) { + $this->privSwapBackMagicQuotes(); + unset($v_list); + return(0); + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : deleteByIndex() + // Description : + // ***** Deprecated ***** + // delete(PCLZIP_OPT_BY_INDEX, $p_index) should be prefered. + // -------------------------------------------------------------------------------- + public function deleteByIndex($p_index) + { + + $p_list = $this->delete(PCLZIP_OPT_BY_INDEX, $p_index); + + // ----- Return + return $p_list; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : properties() + // Description : + // This method gives the properties of the archive. + // The properties are : + // nb : Number of files in the archive + // comment : Comment associated with the archive file + // status : not_exist, ok + // Parameters : + // None + // Return Values : + // 0 on failure, + // An array with the archive properties. + // -------------------------------------------------------------------------------- + public function properties() + { + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + $this->privSwapBackMagicQuotes(); + return(0); + } + + // ----- Default properties + $v_prop = array(); + $v_prop['comment'] = ''; + $v_prop['nb'] = 0; + $v_prop['status'] = 'not_exist'; + + // ----- Look if file exists + if (@is_file($this->zipname)) { + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return 0; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privSwapBackMagicQuotes(); + return 0; + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Set the user attributes + $v_prop['comment'] = $v_central_dir['comment']; + $v_prop['nb'] = $v_central_dir['entries']; + $v_prop['status'] = 'ok'; + } + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_prop; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : duplicate() + // Description : + // This method creates an archive by copying the content of an other one. If + // the archive already exist, it is replaced by the new one without any warning. + // Parameters : + // $p_archive : The filename of a valid archive, or + // a valid PclZip object. + // Return Values : + // 1 on success. + // 0 or a negative value on error (error code). + // -------------------------------------------------------------------------------- + public function duplicate($p_archive) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the $p_archive is a PclZip object + if ((is_object($p_archive)) && (get_class($p_archive) == 'pclzip')) { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive->zipname); + } elseif (is_string($p_archive)) { + // ----- Look if the $p_archive is a string (so a filename) + // ----- Check that $p_archive is a valid zip file + // TBC : Should also check the archive format + if (!is_file($p_archive)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "No file with filename '".$p_archive."'"); + $v_result = PCLZIP_ERR_MISSING_FILE; + } else { + // ----- Duplicate the archive + $v_result = $this->privDuplicate($p_archive); + } + } else { + // ----- Invalid variable + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : merge() + // Description : + // This method merge the $p_archive_to_add archive at the end of the current + // one ($this). + // If the archive ($this) does not exist, the merge becomes a duplicate. + // If the $p_archive_to_add archive does not exist, the merge is a success. + // Parameters : + // $p_archive_to_add : It can be directly the filename of a valid zip archive, + // or a PclZip object archive. + // Return Values : + // 1 on success, + // 0 or negative values on error (see below). + // -------------------------------------------------------------------------------- + public function merge($p_archive_to_add) + { + $v_result = 1; + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Check archive + if (!$this->privCheckFormat()) { + return(0); + } + + // ----- Look if the $p_archive_to_add is a PclZip object + if ((is_object($p_archive_to_add)) && (get_class($p_archive_to_add) == 'pclzip')) { + // ----- Merge the archive + $v_result = $this->privMerge($p_archive_to_add); + } elseif (is_string($p_archive_to_add)) { + // ----- Look if the $p_archive_to_add is a string (so a filename) + // ----- Create a temporary archive + $v_object_archive = new PclZip($p_archive_to_add); + + // ----- Merge the archive + $v_result = $this->privMerge($v_object_archive); + } else { + // ----- Invalid variable + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid variable type p_archive_to_add"); + $v_result = PCLZIP_ERR_INVALID_PARAMETER; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : errorCode() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorCode() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorCode()); + } else { + return($this->error_code); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorName() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorName($p_with_code = false) + { + $v_name = array( + PCLZIP_ERR_NO_ERROR => 'PCLZIP_ERR_NO_ERROR', + PCLZIP_ERR_WRITE_OPEN_FAIL => 'PCLZIP_ERR_WRITE_OPEN_FAIL', + PCLZIP_ERR_READ_OPEN_FAIL => 'PCLZIP_ERR_READ_OPEN_FAIL', + PCLZIP_ERR_INVALID_PARAMETER => 'PCLZIP_ERR_INVALID_PARAMETER', + PCLZIP_ERR_MISSING_FILE => 'PCLZIP_ERR_MISSING_FILE', + PCLZIP_ERR_FILENAME_TOO_LONG => 'PCLZIP_ERR_FILENAME_TOO_LONG', + PCLZIP_ERR_INVALID_ZIP => 'PCLZIP_ERR_INVALID_ZIP', + PCLZIP_ERR_BAD_EXTRACTED_FILE => 'PCLZIP_ERR_BAD_EXTRACTED_FILE', + PCLZIP_ERR_DIR_CREATE_FAIL => 'PCLZIP_ERR_DIR_CREATE_FAIL', + PCLZIP_ERR_BAD_EXTENSION => 'PCLZIP_ERR_BAD_EXTENSION', + PCLZIP_ERR_BAD_FORMAT => 'PCLZIP_ERR_BAD_FORMAT', + PCLZIP_ERR_DELETE_FILE_FAIL => 'PCLZIP_ERR_DELETE_FILE_FAIL', + PCLZIP_ERR_RENAME_FILE_FAIL => 'PCLZIP_ERR_RENAME_FILE_FAIL', + PCLZIP_ERR_BAD_CHECKSUM => 'PCLZIP_ERR_BAD_CHECKSUM', + PCLZIP_ERR_INVALID_ARCHIVE_ZIP => 'PCLZIP_ERR_INVALID_ARCHIVE_ZIP', + PCLZIP_ERR_MISSING_OPTION_VALUE => 'PCLZIP_ERR_MISSING_OPTION_VALUE', + PCLZIP_ERR_INVALID_OPTION_VALUE => 'PCLZIP_ERR_INVALID_OPTION_VALUE', + PCLZIP_ERR_UNSUPPORTED_COMPRESSION => 'PCLZIP_ERR_UNSUPPORTED_COMPRESSION', + PCLZIP_ERR_UNSUPPORTED_ENCRYPTION => 'PCLZIP_ERR_UNSUPPORTED_ENCRYPTION', + PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE => 'PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE', + PCLZIP_ERR_DIRECTORY_RESTRICTION => 'PCLZIP_ERR_DIRECTORY_RESTRICTION', + ); + + if (isset($v_name[$this->error_code])) { + $v_value = $v_name[$this->error_code]; + } else { + $v_value = 'NoName'; + } + + if ($p_with_code) { + return($v_value.' ('.$this->error_code.')'); + } else { + return($v_value); + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : errorInfo() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function errorInfo($p_full = false) + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + return(PclErrorString()); + } else { + if ($p_full) { + return($this->errorName(true)." : ".$this->error_string); + } else { + return($this->error_string." [code ".$this->error_code."]"); + } + } + } + // -------------------------------------------------------------------------------- + + + // -------------------------------------------------------------------------------- + // ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** + // ***** ***** + // ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** + // -------------------------------------------------------------------------------- + + + + // -------------------------------------------------------------------------------- + // Function : privCheckFormat() + // Description : + // This method check that the archive exists and is a valid zip archive. + // Several level of check exists. (futur) + // Parameters : + // $p_level : Level of check. Default 0. + // 0 : Check the first bytes (magic codes) (default value)) + // 1 : 0 + Check the central directory (futur) + // 2 : 1 + Check each file header (futur) + // Return Values : + // true on success, + // false on error, the error code is set. + // -------------------------------------------------------------------------------- + public function privCheckFormat($p_level = 0) + { + $v_result = true; + + // ----- Reset the file system cache + clearstatcache(); + + // ----- Reset the error handler + $this->privErrorReset(); + + // ----- Look if the file exits + if (!is_file($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "Missing archive file '".$this->zipname."'"); + return(false); + } + + // ----- Check that the file is readeable + if (!is_readable($this->zipname)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to read archive '".$this->zipname."'"); + return(false); + } + + // ----- Check the magic code + // TBC + + // ----- Check the central header + // TBC + + // ----- Check each file header + // TBC + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privParseOptions() + // Description : + // This internal methods reads the variable list of arguments ($p_options_list, + // $p_size) and generate an array with the options and values ($v_result_list). + // $v_requested_options contains the options that can be present and those that + // must be present. + // $v_requested_options is an array, with the option value as key, and 'optional', + // or 'mandatory' as value. + // Parameters : + // See above. + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privParseOptions(&$p_options_list, $p_size, &$v_result_list, $v_requested_options = false) + { + $v_result=1; + + // ----- Read the options + $i=0; + while ($i<$p_size) { + // ----- Check if the option is supported + if (!isset($v_requested_options[$p_options_list[$i]])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid optional parameter '".$p_options_list[$i]."' for this method"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for next option + switch ($p_options_list[$i]) { + // ----- Look for options that request a path value + case PCLZIP_OPT_PATH: + case PCLZIP_OPT_REMOVE_PATH: + case PCLZIP_OPT_ADD_PATH: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_THRESHOLD: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + // ----- Check the value + $v_value = $p_options_list[$i+1]; + if ((!is_integer($v_value)) || ($v_value<0)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Integer expected for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + return PclZip::errorCode(); + } + + // ----- Get the value (and convert it in bytes) + $v_result_list[$p_options_list[$i]] = $v_value*1048576; + $i++; + break; + + case PCLZIP_OPT_TEMP_FILE_ON: + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_OFF])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_OFF'"); + return PclZip::errorCode(); + } + + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_TEMP_FILE_OFF: + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_ON])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_ON'"); + return PclZip::errorCode(); + } + // ----- Check for incompatible options + if (isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Option '".PclZipUtilOptionText($p_options_list[$i])."' can not be used with option 'PCLZIP_OPT_TEMP_FILE_THRESHOLD'"); + return PclZip::errorCode(); + } + $v_result_list[$p_options_list[$i]] = true; + break; + + case PCLZIP_OPT_EXTRACT_DIR_RESTRICTION: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1]) && ($p_options_list[$i+1] != '')) { + $v_result_list[$p_options_list[$i]] = PclZipUtilTranslateWinPath($p_options_list[$i+1], false); + $i++; + } else { + } + break; + // ----- Look for options that request an array of string for value + case PCLZIP_OPT_BY_NAME: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]][0] = $p_options_list[$i+1]; + } elseif (is_array($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + // ----- Look for options that request an EREG or PREG expression + case PCLZIP_OPT_BY_EREG: + // ereg() is deprecated starting with PHP 5.3. Move PCLZIP_OPT_BY_EREG + // to PCLZIP_OPT_BY_PREG + $p_options_list[$i] = PCLZIP_OPT_BY_PREG; + case PCLZIP_OPT_BY_PREG: + //case PCLZIP_OPT_CRYPT : + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that takes a string + case PCLZIP_OPT_COMMENT: + case PCLZIP_OPT_ADD_COMMENT: + case PCLZIP_OPT_PREPEND_COMMENT: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + if (is_string($p_options_list[$i+1])) { + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Wrong parameter value for option '" .PclZipUtilOptionText($p_options_list[$i]) ."'"); + + // ----- Return + return PclZip::errorCode(); + } + $i++; + break; + + // ----- Look for options that request an array of index + case PCLZIP_OPT_BY_INDEX: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_work_list = array(); + if (is_string($p_options_list[$i+1])) { + // ----- Remove spaces + $p_options_list[$i+1] = strtr($p_options_list[$i+1], ' ', ''); + + // ----- Parse items + $v_work_list = explode(",", $p_options_list[$i+1]); + } elseif (is_integer($p_options_list[$i+1])) { + $v_work_list[0] = $p_options_list[$i+1].'-'.$p_options_list[$i+1]; + } elseif (is_array($p_options_list[$i+1])) { + $v_work_list = $p_options_list[$i+1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Value must be integer, string or array for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Reduce the index list + // each index item in the list must be a couple with a start and + // an end value : [0,3], [5-5], [8-10], ... + // ----- Check the format of each item + $v_sort_flag=false; + $v_sort_value=0; + for ($j=0; $j<sizeof($v_work_list); $j++) { + // ----- Explode the item + $v_item_list = explode("-", $v_work_list[$j]); + $v_size_item_list = sizeof($v_item_list); + + // ----- TBC : Here we might check that each item is a + // real integer ... + + // ----- Look for single value + if ($v_size_item_list == 1) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[0]; + } elseif ($v_size_item_list == 2) { + // ----- Set the option value + $v_result_list[$p_options_list[$i]][$j]['start'] = $v_item_list[0]; + $v_result_list[$p_options_list[$i]][$j]['end'] = $v_item_list[1]; + } else { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Too many values in index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + + + // ----- Look for list sort + if ($v_result_list[$p_options_list[$i]][$j]['start'] < $v_sort_value) { + $v_sort_flag=true; + + // ----- TBC : An automatic sort should be writen ... + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Invalid order of index range for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + + // ----- Return + return PclZip::errorCode(); + } + $v_sort_value = $v_result_list[$p_options_list[$i]][$j]['start']; + } + + // ----- Sort the items + if ($v_sort_flag) { + // TBC : To Be Completed + } + // ----- Next option + $i++; + break; + // ----- Look for options that request no value + case PCLZIP_OPT_REMOVE_ALL_PATH: + case PCLZIP_OPT_EXTRACT_AS_STRING: + case PCLZIP_OPT_NO_COMPRESSION: + case PCLZIP_OPT_EXTRACT_IN_OUTPUT: + case PCLZIP_OPT_REPLACE_NEWER: + case PCLZIP_OPT_STOP_ON_ERROR: + $v_result_list[$p_options_list[$i]] = true; + break; + // ----- Look for options that request an octal value + case PCLZIP_OPT_SET_CHMOD: + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + // ----- Get the value + $v_result_list[$p_options_list[$i]] = $p_options_list[$i+1]; + $i++; + break; + + // ----- Look for options that request a call-back + case PCLZIP_CB_PRE_EXTRACT: + case PCLZIP_CB_POST_EXTRACT: + case PCLZIP_CB_PRE_ADD: + case PCLZIP_CB_POST_ADD: + /* for futur use + case PCLZIP_CB_PRE_DELETE : + case PCLZIP_CB_POST_DELETE : + case PCLZIP_CB_PRE_LIST : + case PCLZIP_CB_POST_LIST : + */ + // ----- Check the number of parameters + if (($i+1) >= $p_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_OPTION_VALUE, "Missing parameter value for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Get the value + $v_function_name = $p_options_list[$i+1]; + + // ----- Check that the value is a valid existing function + if (!function_exists($v_function_name)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_OPTION_VALUE, "Function '".$v_function_name."()' is not an existing function for option '".PclZipUtilOptionText($p_options_list[$i])."'"); + // ----- Return + return PclZip::errorCode(); + } + + // ----- Set the attribute + $v_result_list[$p_options_list[$i]] = $v_function_name; + $i++; + break; + default: + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '" .$p_options_list[$i]."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Next options + $i++; + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key=reset($v_requested_options); $key=key($v_requested_options); $key=next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($v_result_list[$key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + + // ----- Return + return PclZip::errorCode(); + } + } + } + } + + // ----- Look for default values + if (!isset($v_result_list[PCLZIP_OPT_TEMP_FILE_THRESHOLD])) { + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOptionDefaultThreshold() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privOptionDefaultThreshold(&$p_options) + { + $v_result=1; + + if (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) || isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) { + return $v_result; + } + + // ----- Get 'memory_limit' configuration value + $v_memory_limit = ini_get('memory_limit'); + $v_memory_limit = trim($v_memory_limit); + $last = strtolower(substr($v_memory_limit, -1)); + + if ($last == 'g') { + //$v_memory_limit = $v_memory_limit*1024*1024*1024; + $v_memory_limit = $v_memory_limit*1073741824; + } + if ($last == 'm') { + //$v_memory_limit = $v_memory_limit*1024*1024; + $v_memory_limit = $v_memory_limit*1048576; + } + if ($last == 'k') { + $v_memory_limit = $v_memory_limit*1024; + } + + $p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] = floor($v_memory_limit*PCLZIP_TEMPORARY_FILE_RATIO); + + // ----- Sanity check : No threshold if value lower than 1M + if ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] < 1048576) { + unset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrParseAtt() + // Description : + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privFileDescrParseAtt(&$p_file_list, &$p_filedescr, $v_options, $v_requested_options = false) + { + $v_result=1; + + // ----- For each file in the list check the attributes + foreach ($p_file_list as $v_key => $v_value) { + // ----- Check if the option is supported + if (!isset($v_requested_options[$v_key])) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file attribute '".$v_key."' for this file"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for attribute + switch ($v_key) { + case PCLZIP_ATT_FILE_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['filename'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['filename'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + case PCLZIP_ATT_FILE_NEW_SHORT_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_short_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_short_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty short filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + case PCLZIP_ATT_FILE_NEW_FULL_NAME: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + + $p_filedescr['new_full_name'] = PclZipUtilPathReduction($v_value); + + if ($p_filedescr['new_full_name'] == '') { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid empty full filename for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + break; + // ----- Look for options that takes a string + case PCLZIP_ATT_FILE_COMMENT: + if (!is_string($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". String expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + $p_filedescr['comment'] = $v_value; + break; + case PCLZIP_ATT_FILE_MTIME: + if (!is_integer($v_value)) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE, "Invalid type ".gettype($v_value).". Integer expected for attribute '".PclZipUtilOptionText($v_key)."'"); + return PclZip::errorCode(); + } + $p_filedescr['mtime'] = $v_value; + break; + case PCLZIP_ATT_FILE_CONTENT: + $p_filedescr['content'] = $v_value; + break; + default: + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Unknown parameter '".$v_key."'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for mandatory options + if ($v_requested_options !== false) { + for ($key = reset($v_requested_options); $key = key($v_requested_options); $key = next($v_requested_options)) { + // ----- Look for mandatory option + if ($v_requested_options[$key] == 'mandatory') { + // ----- Look if present + if (!isset($p_file_list[$key])) { + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Missing mandatory parameter ".PclZipUtilOptionText($key)."(".$key.")"); + return PclZip::errorCode(); + } + } + } + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privFileDescrExpand() + // Description : + // This method look for each item of the list to see if its a file, a folder + // or a string to be added as file. For any other type of files (link, other) + // just ignore the item. + // Then prepare the information that will be stored for that file. + // When its a folder, expand the folder with all the files that are in that + // folder (recursively). + // Parameters : + // Return Values : + // 1 on success. + // 0 on failure. + // -------------------------------------------------------------------------------- + public function privFileDescrExpand(&$p_filedescr_list, &$p_options) + { + $v_result=1; + + // ----- Create a result list + $v_result_list = array(); + + // ----- Look each entry + for ($i=0; $i<sizeof($p_filedescr_list); $i++) { + // ----- Get filedescr + $v_descr = $p_filedescr_list[$i]; + + // ----- Reduce the filename + $v_descr['filename'] = PclZipUtilTranslateWinPath($v_descr['filename'], false); + $v_descr['filename'] = PclZipUtilPathReduction($v_descr['filename']); + + // ----- Look for real file or folder + if (file_exists($v_descr['filename'])) { + if (@is_file($v_descr['filename'])) { + $v_descr['type'] = 'file'; + } elseif (@is_dir($v_descr['filename'])) { + $v_descr['type'] = 'folder'; + } elseif (@is_link($v_descr['filename'])) { + // skip + continue; + } else { + // skip + continue; + } + } elseif (isset($v_descr['content'])) { + // ----- Look for string added as file + $v_descr['type'] = 'virtual_file'; + } else { + // ----- Missing file + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$v_descr['filename']."' does not exist"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Calculate the stored filename + $this->privCalculateStoredFilename($v_descr, $p_options); + + // ----- Add the descriptor in result list + $v_result_list[sizeof($v_result_list)] = $v_descr; + + // ----- Look for folder + if ($v_descr['type'] == 'folder') { + // ----- List of items in folder + $v_dirlist_descr = array(); + $v_dirlist_nb = 0; + if ($v_folder_handler = @opendir($v_descr['filename'])) { + while (($v_item_handler = @readdir($v_folder_handler)) !== false) { + // ----- Skip '.' and '..' + if (($v_item_handler == '.') || ($v_item_handler == '..')) { + continue; + } + + // ----- Compose the full filename + $v_dirlist_descr[$v_dirlist_nb]['filename'] = $v_descr['filename'].'/'.$v_item_handler; + + // ----- Look for different stored filename + // Because the name of the folder was changed, the name of the + // files/sub-folders also change + if (($v_descr['stored_filename'] != $v_descr['filename']) + && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + if ($v_descr['stored_filename'] != '') { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_descr['stored_filename'].'/'.$v_item_handler; + } else { + $v_dirlist_descr[$v_dirlist_nb]['new_full_name'] = $v_item_handler; + } + } + $v_dirlist_nb++; + } + + @closedir($v_folder_handler); + } else { + // TBC : unable to open folder in read mode + } + + // ----- Expand each element of the list + if ($v_dirlist_nb != 0) { + // ----- Expand + if (($v_result = $this->privFileDescrExpand($v_dirlist_descr, $p_options)) != 1) { + return $v_result; + } + + // ----- Concat the resulting list + $v_result_list = array_merge($v_result_list, $v_dirlist_descr); + } + + // ----- Free local array + unset($v_dirlist_descr); + } + } + + // ----- Get the result list + $p_filedescr_list = $v_result_list; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCreate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privCreate($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the file in write mode + if (($v_result = $this->privOpenFd('wb')) != 1) { + // ----- Return + return $v_result; + } + + // ----- Add the list of files + $v_result = $this->privAddList($p_filedescr_list, $p_result_list, $p_options); + + // ----- Close + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAdd() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAdd($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Look if the archive exists or is empty + if ((!is_file($this->zipname)) || (filesize($this->zipname) == 0)) { + // ----- Do a create + $v_result = $this->privCreate($p_filedescr_list, $p_result_list, $p_options); + + // ----- Return + return $v_result; + } + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + fclose($v_zip_temp_fd); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = $v_central_dir['comment']; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_ADD_COMMENT])) { + $v_comment = $v_comment.$p_options[PCLZIP_OPT_ADD_COMMENT]; + } + if (isset($p_options[PCLZIP_OPT_PREPEND_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_PREPEND_COMMENT].$v_comment; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count+$v_central_dir['entries'], $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privOpenFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privOpenFd($p_mode) + { + $v_result=1; + + // ----- Look if already open + if ($this->zip_fd != 0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Zip file \''.$this->zipname.'\' already open'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, $p_mode)) == 0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in '.$p_mode.' mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCloseFd() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privCloseFd() + { + $v_result=1; + + if ($this->zip_fd != 0) { + @fclose($this->zip_fd); + } + $this->zip_fd = 0; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddList() + // Description : + // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is + // different from the real path of the file. This is usefull if you want to have PclTar + // running in any directory, and memorize relative path from an other directory. + // Parameters : + // $p_list : An array containing the file or directory names to add in the tar + // $p_result_list : list of added files with their properties (specially the status field) + // $p_add_dir : Path to add in the filename path archived + // $p_remove_dir : Path to remove in the filename path archived + // Return Values : + // -------------------------------------------------------------------------------- + // public function privAddList($p_list, &$p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_options) + public function privAddList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + + // ----- Add the files + $v_header_list = array(); + if (($v_result = $this->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) { + // ----- Return + return $v_result; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($this->zip_fd); + + // ----- Create the Central Dir files header + for ($i=0, $v_count=0; $i<sizeof($v_header_list); $i++) { + // ----- Create the file header + if ($v_header_list[$i]['status'] == 'ok') { + if (($v_result = $this->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + // ----- Return + return $v_result; + } + $v_count++; + } + + // ----- Transform the header to a 'usable' info + $this->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($this->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_count, $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileList() + // Description : + // Parameters : + // $p_filedescr_list : An array containing the file description + // or directory names to add in the zip + // $p_result_list : list of added files with their properties (specially the status field) + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFileList($p_filedescr_list, &$p_result_list, &$p_options) + { + $v_result=1; + $v_header = array(); + + // ----- Recuperate the current number of elt in list + $v_nb = sizeof($p_result_list); + + // ----- Loop on the files + for ($j=0; ($j<sizeof($p_filedescr_list)) && ($v_result==1); $j++) { + // ----- Format the filename + $p_filedescr_list[$j]['filename'] = PclZipUtilTranslateWinPath($p_filedescr_list[$j]['filename'], false); + + // ----- Skip empty file names + // TBC : Can this be possible ? not checked in DescrParseAtt ? + if ($p_filedescr_list[$j]['filename'] == "") { + continue; + } + + // ----- Check the filename + if (($p_filedescr_list[$j]['type'] != 'virtual_file') && (!file_exists($p_filedescr_list[$j]['filename']))) { + PclZip::privErrorLog(PCLZIP_ERR_MISSING_FILE, "File '".$p_filedescr_list[$j]['filename']."' does not exist"); + return PclZip::errorCode(); + } + + // ----- Look if it is a file or a dir with no all path remove option + // or a dir with all its path removed + // if ( (is_file($p_filedescr_list[$j]['filename'])) + // || ( is_dir($p_filedescr_list[$j]['filename']) + if (($p_filedescr_list[$j]['type'] == 'file') || ($p_filedescr_list[$j]['type'] == 'virtual_file') || (($p_filedescr_list[$j]['type'] == 'folder') && (!isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH]) || !$p_options[PCLZIP_OPT_REMOVE_ALL_PATH]))) { + // ----- Add the file + $v_result = $this->privAddFile($p_filedescr_list[$j], $v_header, $p_options); + if ($v_result != 1) { + return $v_result; + } + + // ----- Store the file infos + $p_result_list[$v_nb++] = $v_header; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=1; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + // TBC : Already done in the fileAtt check ... ? + if ($p_filename == "") { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for a stored different filename + /* TBC : Removed + if (isset($p_filedescr['stored_filename'])) { + $v_stored_filename = $p_filedescr['stored_filename']; + } + else { + $v_stored_filename = $p_filedescr['stored_filename']; + } + */ + + // ----- Set the file properties + clearstatcache(); + $p_header['version'] = 20; + $p_header['version_extracted'] = 10; + $p_header['flag'] = 0; + $p_header['compression'] = 0; + $p_header['crc'] = 0; + $p_header['compressed_size'] = 0; + $p_header['filename_len'] = strlen($p_filename); + $p_header['extra_len'] = 0; + $p_header['disk'] = 0; + $p_header['internal'] = 0; + $p_header['offset'] = 0; + $p_header['filename'] = $p_filename; + // TBC : Removed $p_header['stored_filename'] = $v_stored_filename; + $p_header['stored_filename'] = $p_filedescr['stored_filename']; + $p_header['extra'] = ''; + $p_header['status'] = 'ok'; + $p_header['index'] = -1; + + // ----- Look for regular file + if ($p_filedescr['type']=='file') { + $p_header['external'] = 0x00000000; + $p_header['size'] = filesize($p_filename); + } elseif ($p_filedescr['type']=='folder') { + // ----- Look for regular folder + $p_header['external'] = 0x00000010; + $p_header['mtime'] = filemtime($p_filename); + $p_header['size'] = filesize($p_filename); + } elseif ($p_filedescr['type'] == 'virtual_file') { + // ----- Look for virtual file + $p_header['external'] = 0x00000000; + $p_header['size'] = strlen($p_filedescr['content']); + } + + // ----- Look for filetime + if (isset($p_filedescr['mtime'])) { + $p_header['mtime'] = $p_filedescr['mtime']; + } elseif ($p_filedescr['type'] == 'virtual_file') { + $p_header['mtime'] = time(); + } else { + $p_header['mtime'] = filemtime($p_filename); + } + + // ------ Look for file comment + if (isset($p_filedescr['comment'])) { + $p_header['comment_len'] = strlen($p_filedescr['comment']); + $p_header['comment'] = $p_filedescr['comment']; + } else { + $p_header['comment_len'] = 0; + $p_header['comment'] = ''; + } + + // ----- Look for pre-add callback + if (isset($p_options[PCLZIP_CB_PRE_ADD])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_ADD].'(PCLZIP_CB_PRE_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_ADD](PCLZIP_CB_PRE_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_header['status'] = "skipped"; + $v_result = 1; + } + + // ----- Update the informations + // Only some fields can be modified + if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { + $p_header['stored_filename'] = PclZipUtilPathReduction($v_local_header['stored_filename']); + } + } + + // ----- Look for empty stored filename + if ($p_header['stored_filename'] == "") { + $p_header['status'] = "filtered"; + } + + // ----- Check the path length + if (strlen($p_header['stored_filename']) > 0xFF) { + $p_header['status'] = 'filename_too_long'; + } + + // ----- Look if no error, or file not skipped + if ($p_header['status'] == 'ok') { + // ----- Look for a file + if ($p_filedescr['type'] == 'file') { + // ----- Look for using temporary file to zip + if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_header['size'])))) { + $v_result = $this->privAddFileUsingTempFile($p_filedescr, $p_header, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } else { + // ----- Use "in memory" zip algo + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Read the file content + $v_content = @fread($v_file, $p_header['size']); + + // ----- Close the file + @fclose($v_file); + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } else { + // ----- Look for normal compression + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } + } elseif ($p_filedescr['type'] == 'virtual_file') { + // ----- Look for a virtual file (a file from string) + $v_content = $p_filedescr['content']; + + // ----- Calculate the CRC + $p_header['crc'] = @crc32($v_content); + + // ----- Look for no compression + if ($p_options[PCLZIP_OPT_NO_COMPRESSION]) { + // ----- Set header parameters + $p_header['compressed_size'] = $p_header['size']; + $p_header['compression'] = 0; + } else { + // ----- Look for normal compression + // ----- Compress the content + $v_content = @gzdeflate($v_content); + + // ----- Set header parameters + $p_header['compressed_size'] = strlen($v_content); + $p_header['compression'] = 8; + } + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + @fclose($v_file); + return $v_result; + } + + // ----- Write the compressed (or not) content + @fwrite($this->zip_fd, $v_content, $p_header['compressed_size']); + } elseif ($p_filedescr['type'] == 'folder') { + // ----- Look for a directory + // ----- Look for directory last '/' + if (@substr($p_header['stored_filename'], -1) != '/') { + $p_header['stored_filename'] .= '/'; + } + + // ----- Set the file properties + $p_header['size'] = 0; + //$p_header['external'] = 0x41FF0010; // Value for a folder : to be checked + $p_header['external'] = 0x00000010; // Value for a folder : to be checked + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } + } + } + + // ----- Look for post-add callback + if (isset($p_options[PCLZIP_CB_POST_ADD])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_header, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_ADD].'(PCLZIP_CB_POST_ADD, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_ADD](PCLZIP_CB_POST_ADD, $v_local_header); + if ($v_result == 0) { + // ----- Ignored + $v_result = 1; + } + + // ----- Update the informations + // Nothing can be modified + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privAddFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privAddFileUsingTempFile($p_filedescr, &$p_header, &$p_options) + { + $v_result=PCLZIP_ERR_NO_ERROR; + + // ----- Working variable + $p_filename = $p_filedescr['filename']; + + + // ----- Open the source file + if (($v_file = @fopen($p_filename, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); + return PclZip::errorCode(); + } + + // ----- Creates a compressed temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_file_compressed = @gzopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = filesize($p_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @gzputs($v_file_compressed, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file); + @gzclose($v_file_compressed); + + // ----- Check the minimum file size + if (filesize($v_gzip_temp_name) < 18) { + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'gzip temporary file \''.$v_gzip_temp_name.'\' has invalid filesize - should be minimum 18 bytes'); + return PclZip::errorCode(); + } + + // ----- Extract the compressed attributes + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the gzip file header + $v_binary_data = @fread($v_file_compressed, 10); + $v_data_header = unpack('a1id1/a1id2/a1cm/a1flag/Vmtime/a1xfl/a1os', $v_binary_data); + + // ----- Check some parameters + $v_data_header['os'] = bin2hex($v_data_header['os']); + + // ----- Read the gzip file footer + @fseek($v_file_compressed, filesize($v_gzip_temp_name)-8); + $v_binary_data = @fread($v_file_compressed, 8); + $v_data_footer = unpack('Vcrc/Vcompressed_size', $v_binary_data); + + // ----- Set the attributes + $p_header['compression'] = ord($v_data_header['cm']); + //$p_header['mtime'] = $v_data_header['mtime']; + $p_header['crc'] = $v_data_footer['crc']; + $p_header['compressed_size'] = filesize($v_gzip_temp_name)-18; + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Call the header generation + if (($v_result = $this->privWriteFileHeader($p_header)) != 1) { + return $v_result; + } + + // ----- Add the compressed data + if (($v_file_compressed = @fopen($v_gzip_temp_name, "rb")) == 0) { + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + fseek($v_file_compressed, 10); + $v_size = $p_header['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($v_file_compressed, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close the file + @fclose($v_file_compressed); + + // ----- Unlink the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCalculateStoredFilename() + // Description : + // Based on file descriptor properties and global options, this method + // calculate the filename that will be stored in the archive. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privCalculateStoredFilename(&$p_filedescr, &$p_options) + { + $v_result=1; + + // ----- Working variables + $p_filename = $p_filedescr['filename']; + if (isset($p_options[PCLZIP_OPT_ADD_PATH])) { + $p_add_dir = $p_options[PCLZIP_OPT_ADD_PATH]; + } else { + $p_add_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_PATH])) { + $p_remove_dir = $p_options[PCLZIP_OPT_REMOVE_PATH]; + } else { + $p_remove_dir = ''; + } + if (isset($p_options[PCLZIP_OPT_REMOVE_ALL_PATH])) { + $p_remove_all_dir = $p_options[PCLZIP_OPT_REMOVE_ALL_PATH]; + } else { + $p_remove_all_dir = 0; + } + + // ----- Look for full name change + if (isset($p_filedescr['new_full_name'])) { + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($p_filedescr['new_full_name']); + } else { + // ----- Look for path and/or short name change + // ----- Look for short name change + // Its when we cahnge just the filename but not the path + if (isset($p_filedescr['new_short_name'])) { + $v_path_info = pathinfo($p_filename); + $v_dir = ''; + if ($v_path_info['dirname'] != '') { + $v_dir = $v_path_info['dirname'].'/'; + } + $v_stored_filename = $v_dir.$p_filedescr['new_short_name']; + } else { + // ----- Calculate the stored filename + $v_stored_filename = $p_filename; + } + + // ----- Look for all path to remove + if ($p_remove_all_dir) { + $v_stored_filename = basename($p_filename); + } elseif ($p_remove_dir != "") { + // ----- Look for partial path remove + if (substr($p_remove_dir, -1) != '/') { + $p_remove_dir .= "/"; + } + + if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) { + if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) { + $p_remove_dir = "./".$p_remove_dir; + } + if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) { + $p_remove_dir = substr($p_remove_dir, 2); + } + } + + $v_compare = PclZipUtilPathInclusion($p_remove_dir, $v_stored_filename); + if ($v_compare > 0) { + if ($v_compare == 2) { + $v_stored_filename = ""; + } else { + $v_stored_filename = substr($v_stored_filename, strlen($p_remove_dir)); + } + } + } + + // ----- Remove drive letter if any + $v_stored_filename = PclZipUtilTranslateWinPath($v_stored_filename); + + // ----- Look for path to add + if ($p_add_dir != "") { + if (substr($p_add_dir, -1) == "/") { + $v_stored_filename = $p_add_dir.$v_stored_filename; + } else { + $v_stored_filename = $p_add_dir."/".$v_stored_filename; + } + } + } + + // ----- Filename (reduce the path of stored name) + $v_stored_filename = PclZipUtilPathReduction($v_stored_filename); + $p_filedescr['stored_filename'] = $v_stored_filename; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privWriteFileHeader(&$p_header) + { + $v_result=1; + + // ----- Store the offset position of the file + $p_header['offset'] = ftell($this->zip_fd); + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + // ----- Packed data + $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len']); + + // ----- Write the first 148 bytes of the header in the archive + fputs($this->zip_fd, $v_binary_data, 30); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privWriteCentralFileHeader(&$p_header) + { + $v_result=1; + + // TBC + //for(reset($p_header); $key = key($p_header); next($p_header)) { + //} + + // ----- Transform UNIX mtime to DOS format mdate/mtime + $v_date = getdate($p_header['mtime']); + $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; + $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; + + + // ----- Packed data + $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], $p_header['compressed_size'], $p_header['size'], strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); + + // ----- Write the 42 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 46); + + // ----- Write the variable fields + if (strlen($p_header['stored_filename']) != 0) { + fputs($this->zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); + } + if ($p_header['extra_len'] != 0) { + fputs($this->zip_fd, $p_header['extra'], $p_header['extra_len']); + } + if ($p_header['comment_len'] != 0) { + fputs($this->zip_fd, $p_header['comment'], $p_header['comment_len']); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privWriteCentralHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privWriteCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) + { + $v_result = 1; + + // ----- Packed data + $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); + + // ----- Write the 22 bytes of the header in the zip file + fputs($this->zip_fd, $v_binary_data, 22); + + // ----- Write the variable fields + if (strlen($p_comment) != 0) { + fputs($this->zip_fd, $p_comment, strlen($p_comment)); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privList() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privList(&$p_list) + { + $v_result = 1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Open the zip file + if (($this->zip_fd = @fopen($this->zipname, 'rb')) == 0) { + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->zipname.'\' in binary read mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Go to beginning of Central Dir + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_central_dir['offset'])) { + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + for ($i=0; $i<$v_central_dir['entries']; $i++) { + // ----- Read the file header + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + $v_header['index'] = $i; + + // ----- Get the only interesting attributes + $this->privConvertHeader2FileInfo($v_header, $p_list[$i]); + unset($v_header); + } + + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Magic quotes trick + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privConvertHeader2FileInfo() + // Description : + // This function takes the file informations from the central directory + // entries and extract the interesting parameters that will be given back. + // The resulting file infos are set in the array $p_info + // $p_info['filename'] : Filename with full path. Given by user (add), + // extracted in the filesystem (extract). + // $p_info['stored_filename'] : Stored filename in the archive. + // $p_info['size'] = Size of the file. + // $p_info['compressed_size'] = Compressed size of the file. + // $p_info['mtime'] = Last modification date of the file. + // $p_info['comment'] = Comment associated with the file. + // $p_info['folder'] = true/false : indicates if the entry is a folder or not. + // $p_info['status'] = status of the action on the file. + // $p_info['crc'] = CRC of the file content. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privConvertHeader2FileInfo($p_header, &$p_info) + { + $v_result=1; + + // ----- Get the interesting attributes + $v_temp_path = PclZipUtilPathReduction($p_header['filename']); + $p_info['filename'] = $v_temp_path; + $v_temp_path = PclZipUtilPathReduction($p_header['stored_filename']); + $p_info['stored_filename'] = $v_temp_path; + $p_info['size'] = $p_header['size']; + $p_info['compressed_size'] = $p_header['compressed_size']; + $p_info['mtime'] = $p_header['mtime']; + $p_info['comment'] = $p_header['comment']; + $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); + $p_info['index'] = $p_header['index']; + $p_info['status'] = $p_header['status']; + $p_info['crc'] = $p_header['crc']; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractByRule() + // Description : + // Extract a file or directory depending of rules (by index, by name, ...) + // Parameters : + // $p_file_list : An array where will be placed the properties of each + // extracted file + // $p_path : Path to add while writing the extracted files + // $p_remove_path : Path to remove (from the file memorized path) while writing the + // extracted files. If the path does not match the file path, + // the file is extracted with its memorized path. + // $p_remove_path does not apply to 'list' mode. + // $p_path and $p_remove_path are commulative. + // Return Values : + // 1 on success,0 or less on error (see error code list) + // -------------------------------------------------------------------------------- + public function privExtractByRule(&$p_file_list, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Magic quotes trick + $this->privDisableMagicQuotes(); + + // ----- Check the path + if (($p_path == "") || ((substr($p_path, 0, 1) != "/") && (substr($p_path, 0, 3) != "../") && (substr($p_path, 1, 2)!=":/"))) { + $p_path = "./".$p_path; + } + + // ----- Reduce the path last (and duplicated) '/' + if (($p_path != "./") && ($p_path != "/")) { + // ----- Look for the path end '/' + while (substr($p_path, -1) == "/") { + $p_path = substr($p_path, 0, strlen($p_path)-1); + } + } + + // ----- Look for path to remove format (should end by /) + if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { + $p_remove_path .= '/'; + } + $p_remove_path_size = strlen($p_remove_path); + + // ----- Open the zip file + if (($v_result = $this->privOpenFd('rb')) != 1) { + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + + // ----- Read each entry + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { + // ----- Read next Central dir entry + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Store the index + $v_header['index'] = $i; + + // ----- Store the file position + $v_pos_entry = ftell($this->zip_fd); + + // ----- Look for the specific extract rules + $v_extract = false; + + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + // ----- Look if the filename is in the list + for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_extract); $j++) { + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { + // ----- Look if the directory is in the filename path + if ((strlen($v_header['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_extract = true; + } + } elseif ($v_header['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + // ----- Look for a filename + $v_extract = true; + } + } + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + // ----- Look for extract by preg rule + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header['stored_filename'])) { + $v_extract = true; + } + } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + // ----- Look for extract by index rule + // ----- Look if the index is in the list + for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_extract); $j++) { + if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_extract = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } else { + // ----- Look for no rule, which means extract all the archive + $v_extract = true; + } + + // ----- Check compression method + if (($v_extract) && (($v_header['compression'] != 8) && ($v_header['compression'] != 0))) { + $v_header['status'] = 'unsupported_compression'; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_COMPRESSION, "Filename '".$v_header['stored_filename']."' is compressed by an unsupported compression method (".$v_header['compression'].") "); + + return PclZip::errorCode(); + } + } + + // ----- Check encrypted files + if (($v_extract) && (($v_header['flag'] & 1) == 1)) { + $v_header['status'] = 'unsupported_encryption'; + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { + $this->privSwapBackMagicQuotes(); + + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, "Unsupported encryption for filename '".$v_header['stored_filename']."'"); + + return PclZip::errorCode(); + } + } + + // ----- Look for real extraction + if (($v_extract) && ($v_header['status'] != 'ok')) { + $v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++]); + if ($v_result != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + $v_extract = false; + } + + // ----- Look for real extraction + if ($v_extract) { + // ----- Go to the file position + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + + $this->privSwapBackMagicQuotes(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Look for extraction as string + if ($p_options[PCLZIP_OPT_EXTRACT_AS_STRING]) { + $v_string = ''; + + // ----- Extracting the file + $v_result1 = $this->privExtractFileAsString($v_header, $v_string, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Set the file content + $p_file_list[$v_nb_extracted]['content'] = $v_string; + + // ----- Next extracted file + $v_nb_extracted++; + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } elseif ((isset($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) && ($p_options[PCLZIP_OPT_EXTRACT_IN_OUTPUT])) { + // ----- Look for extraction in standard output + // ----- Extracting the file in standard output + $v_result1 = $this->privExtractFileInOutput($v_header, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } else { + // ----- Look for normal extraction + // ----- Extracting the file + $v_result1 = $this->privExtractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_options); + if ($v_result1 < 1) { + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + return $v_result1; + } + + // ----- Get the only interesting attributes + if (($v_result = $this->privConvertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + return $v_result; + } + + // ----- Look for user callback abort + if ($v_result1 == 2) { + break; + } + } + } + } + + // ----- Close the zip file + $this->privCloseFd(); + $this->privSwapBackMagicQuotes(); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFile() + // Description : + // Parameters : + // Return Values : + // + // 1 : ... ? + // PCLZIP_ERR_USER_ABORTED(2) : User ask for extraction stop in callback + // -------------------------------------------------------------------------------- + public function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + // ----- Return + return $v_result; + } + + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for all path to remove + if ($p_remove_all_path == true) { + // ----- Look for folder entry that not need to be extracted + if (($p_entry['external']&0x00000010)==0x00000010) { + $p_entry['status'] = "filtered"; + + return $v_result; + } + + // ----- Get the basename of the path + $p_entry['filename'] = basename($p_entry['filename']); + } elseif ($p_remove_path != "") { + // ----- Look for path to remove + if (PclZipUtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) { + // ----- Change the file status + $p_entry['status'] = "filtered"; + + // ----- Return + return $v_result; + } + + $p_remove_path_size = strlen($p_remove_path); + if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) { + // ----- Remove the path + $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); + } + } + + // ----- Add the path + if ($p_path != '') { + $p_entry['filename'] = $p_path."/".$p_entry['filename']; + } + + // ----- Check a base_dir_restriction + if (isset($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION])) { + $v_inclusion = PclZipUtilPathInclusion($p_options[PCLZIP_OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']); + if ($v_inclusion == 0) { + PclZip::privErrorLog(PCLZIP_ERR_DIRECTORY_RESTRICTION, "Filename '".$p_entry['filename']."' is outside PCLZIP_OPT_EXTRACT_DIR_RESTRICTION"); + + return PclZip::errorCode(); + } + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + // ----- Look for specific actions while the file exist + if (file_exists($p_entry['filename'])) { + // ----- Look if file is a directory + if (is_dir($p_entry['filename'])) { + // ----- Change the file status + $p_entry['status'] = "already_a_directory"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR]===true)) { + PclZip::privErrorLog(PCLZIP_ERR_ALREADY_A_DIRECTORY, "Filename '".$p_entry['filename']."' is already used by an existing directory"); + return PclZip::errorCode(); + } + } elseif (!is_writeable($p_entry['filename'])) { + // ----- Look if file is write protected + // ----- Change the file status + $p_entry['status'] = "write_protected"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Filename '".$p_entry['filename']."' exists and is write protected"); + return PclZip::errorCode(); + } + } elseif (filemtime($p_entry['filename']) > $p_entry['mtime']) { + // ----- Look if the extracted file is older + // ----- Change the file status + if ((isset($p_options[PCLZIP_OPT_REPLACE_NEWER])) && ($p_options[PCLZIP_OPT_REPLACE_NEWER] === true)) { + } else { + $p_entry['status'] = "newer_exist"; + + // ----- Look for PCLZIP_OPT_STOP_ON_ERROR + // For historical reason first PclZip implementation does not stop + // when this kind of error occurs. + if ((isset($p_options[PCLZIP_OPT_STOP_ON_ERROR])) && ($p_options[PCLZIP_OPT_STOP_ON_ERROR] === true)) { + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, "Newer version of '".$p_entry['filename']."' exists and option PCLZIP_OPT_REPLACE_NEWER is not selected"); + return PclZip::errorCode(); + } + } + } else { + } + } else { + // ----- Check the directory availability and create it if necessary + if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) { + $v_dir_to_check = $p_entry['filename']; + } elseif (!strstr($p_entry['filename'], "/")) { + $v_dir_to_check = ""; + } else { + $v_dir_to_check = dirname($p_entry['filename']); + } + + if (($v_result = $this->privDirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { + // ----- Change the file status + $p_entry['status'] = "path_creation_fail"; + + // ----- Return + //return $v_result; + $v_result = 1; + } + } + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010) == 0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compression'] == 0) { + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + // ----- Change the file status + $p_entry['status'] = "write_error"; + + // ----- Return + return $v_result; + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + /* Try to speed up the code + $v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_binary_data, $v_read_size); + */ + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Closing the destination file + fclose($v_dest_file); + + // ----- Change the file mtime + touch($p_entry['filename'], $p_entry['mtime']); + } else { + // ----- TBC + // Need to be finished + if (($p_entry['flag'] & 1) == 1) { + PclZip::privErrorLog(PCLZIP_ERR_UNSUPPORTED_ENCRYPTION, 'File \''.$p_entry['filename'].'\' is encrypted. Encrypted files are not supported.'); + return PclZip::errorCode(); + } + + // ----- Look for using temporary file to unzip + if ((!isset($p_options[PCLZIP_OPT_TEMP_FILE_OFF])) && (isset($p_options[PCLZIP_OPT_TEMP_FILE_ON]) || (isset($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD]) && ($p_options[PCLZIP_OPT_TEMP_FILE_THRESHOLD] <= $p_entry['size'])))) { + $v_result = $this->privExtractFileUsingTempFile($p_entry, $p_options); + if ($v_result < PCLZIP_ERR_NO_ERROR) { + return $v_result; + } + } else { + // ----- Look for extract in memory + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = @gzinflate($v_buffer); + unset($v_buffer); + if ($v_file_content === false) { + // ----- Change the file status + // TBC + $p_entry['status'] = "error"; + + return $v_result; + } + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + // ----- Change the file status + $p_entry['status'] = "write_error"; + + return $v_result; + } + + // ----- Write the uncompressed data + @fwrite($v_dest_file, $v_file_content, $p_entry['size']); + unset($v_file_content); + + // ----- Closing the destination file + @fclose($v_dest_file); + } + + // ----- Change the file mtime + @touch($p_entry['filename'], $p_entry['mtime']); + } + + // ----- Look for chmod option + if (isset($p_options[PCLZIP_OPT_SET_CHMOD])) { + // ----- Change the mode of the file + @chmod($p_entry['filename'], $p_options[PCLZIP_OPT_SET_CHMOD]); + } + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Look for post-extract callback + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileUsingTempFile() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileUsingTempFile(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Creates a temporary file + $v_gzip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.gz'; + if (($v_dest_file = @fopen($v_gzip_temp_name, "wb")) == 0) { + fclose($v_file); + PclZip::privErrorLog(PCLZIP_ERR_WRITE_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary write mode'); + return PclZip::errorCode(); + } + + // ----- Write gz file format header + $v_binary_data = pack('va1a1Va1a1', 0x8b1f, Chr($p_entry['compression']), Chr(0x00), time(), Chr(0x00), Chr(3)); + @fwrite($v_dest_file, $v_binary_data, 10); + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['compressed_size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Write gz file format footer + $v_binary_data = pack('VV', $p_entry['crc'], $p_entry['size']); + @fwrite($v_dest_file, $v_binary_data, 8); + + // ----- Close the temporary file + @fclose($v_dest_file); + + // ----- Opening destination file + if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { + $p_entry['status'] = "write_error"; + return $v_result; + } + + // ----- Open the temporary gz file + if (($v_src_file = @gzopen($v_gzip_temp_name, 'rb')) == 0) { + @fclose($v_dest_file); + $p_entry['status'] = "read_error"; + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_gzip_temp_name.'\' in binary read mode'); + return PclZip::errorCode(); + } + + // ----- Read the file by PCLZIP_READ_BLOCK_SIZE octets blocks + $v_size = $p_entry['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($v_src_file, $v_read_size); + //$v_binary_data = pack('a'.$v_read_size, $v_buffer); + @fwrite($v_dest_file, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + @fclose($v_dest_file); + @gzclose($v_src_file); + + // ----- Delete the temporary file + @unlink($v_gzip_temp_name); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileInOutput() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileInOutput(&$p_entry, &$p_options) + { + $v_result=1; + + // ----- Read the file header + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + return $v_result; + } + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Trace + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + if ($p_entry['compressed_size'] == $p_entry['size']) { + // ----- Read the file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Send the file to the output + echo $v_buffer; + unset($v_buffer); + } else { + // ----- Read the compressed file in a buffer (one shot) + $v_buffer = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + $v_file_content = gzinflate($v_buffer); + unset($v_buffer); + + // ----- Send the file to the output + echo $v_file_content; + unset($v_file_content); + } + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Look for post-extract callback + + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privExtractFileAsString() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privExtractFileAsString(&$p_entry, &$p_string, &$p_options) + { + $v_result=1; + + // ----- Read the file header + $v_header = array(); + if (($v_result = $this->privReadFileHeader($v_header)) != 1) { + // ----- Return + return $v_result; + } + + // ----- Check that the file header is coherent with $p_entry info + if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) { + // TBC + } + + // ----- Look for pre-extract callback + if (isset($p_options[PCLZIP_CB_PRE_EXTRACT])) { + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_PRE_EXTRACT].'(PCLZIP_CB_PRE_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_PRE_EXTRACT](PCLZIP_CB_PRE_EXTRACT, $v_local_header); + if ($v_result == 0) { + // ----- Change the file status + $p_entry['status'] = "skipped"; + $v_result = 1; + } + + // ----- Look for abort result + if ($v_result == 2) { + // ----- This status is internal and will be changed in 'skipped' + $p_entry['status'] = "aborted"; + $v_result = PCLZIP_ERR_USER_ABORTED; + } + + // ----- Update the informations + // Only some fields can be modified + $p_entry['filename'] = $v_local_header['filename']; + } + + // ----- Look if extraction should be done + if ($p_entry['status'] == 'ok') { + // ----- Do the extraction (if not a folder) + if (!(($p_entry['external']&0x00000010)==0x00000010)) { + // ----- Look for not compressed file + // if ($p_entry['compressed_size'] == $p_entry['size']) + if ($p_entry['compression'] == 0) { + // ----- Reading the file + $p_string = @fread($this->zip_fd, $p_entry['compressed_size']); + } else { + // ----- Reading the file + $v_data = @fread($this->zip_fd, $p_entry['compressed_size']); + + // ----- Decompress the file + if (($p_string = @gzinflate($v_data)) === false) { + // TBC + } + } + // ----- Trace + } else { + // TBC : error : can not extract a folder in a string + } + } + + // ----- Change abort status + if ($p_entry['status'] == "aborted") { + $p_entry['status'] = "skipped"; + } elseif (isset($p_options[PCLZIP_CB_POST_EXTRACT])) { + // ----- Look for post-extract callback + // ----- Generate a local information + $v_local_header = array(); + $this->privConvertHeader2FileInfo($p_entry, $v_local_header); + + // ----- Swap the content to header + $v_local_header['content'] = $p_string; + $p_string = ''; + + // ----- Call the callback + // Here I do not use call_user_func() because I need to send a reference to the + // header. + // eval('$v_result = '.$p_options[PCLZIP_CB_POST_EXTRACT].'(PCLZIP_CB_POST_EXTRACT, $v_local_header);'); + $v_result = $p_options[PCLZIP_CB_POST_EXTRACT](PCLZIP_CB_POST_EXTRACT, $v_local_header); + + // ----- Swap back the content to header + $p_string = $v_local_header['content']; + unset($v_local_header['content']); + + // ----- Look for abort result + if ($v_result == 2) { + $v_result = PCLZIP_ERR_USER_ABORTED; + } + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadFileHeader(&$p_header) + { + $v_result=1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x04034b50) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 26); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 26) { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); + + // ----- Get filename + $p_header['filename'] = fread($this->zip_fd, $v_data['filename_len']); + + // ----- Get extra_fields + if ($v_data['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $v_data['extra_len']); + } else { + $p_header['extra'] = ''; + } + + // ----- Extract properties + $p_header['version_extracted'] = $v_data['version']; + $p_header['compression'] = $v_data['compression']; + $p_header['size'] = $v_data['size']; + $p_header['compressed_size'] = $v_data['compressed_size']; + $p_header['crc'] = $v_data['crc']; + $p_header['flag'] = $v_data['flag']; + $p_header['filename_len'] = $v_data['filename_len']; + + // ----- Recuperate date in UNIX format + $p_header['mdate'] = $v_data['mdate']; + $p_header['mtime'] = $v_data['mtime']; + if ($p_header['mdate'] && $p_header['mtime']) { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } else { + $p_header['mtime'] = time(); + } + + // TBC + //for(reset($v_data); $key = key($v_data); next($v_data)) { + //} + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set the status field + $p_header['status'] = "ok"; + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadCentralFileHeader() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadCentralFileHeader(&$p_header) + { + $v_result = 1; + + // ----- Read the 4 bytes signature + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] != 0x02014b50) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the first 42 bytes of the header + $v_binary_data = fread($this->zip_fd, 42); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 42) { + $p_header['filename'] = ""; + $p_header['status'] = "invalid_header"; + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); + + // ----- Get filename + if ($p_header['filename_len'] != 0) { + $p_header['filename'] = fread($this->zip_fd, $p_header['filename_len']); + } else { + $p_header['filename'] = ''; + } + + // ----- Get extra + if ($p_header['extra_len'] != 0) { + $p_header['extra'] = fread($this->zip_fd, $p_header['extra_len']); + } else { + $p_header['extra'] = ''; + } + + // ----- Get comment + if ($p_header['comment_len'] != 0) { + $p_header['comment'] = fread($this->zip_fd, $p_header['comment_len']); + } else { + $p_header['comment'] = ''; + } + + // ----- Extract properties + + // ----- Recuperate date in UNIX format + //if ($p_header['mdate'] && $p_header['mtime']) + // TBC : bug : this was ignoring time with 0/0/0 + if (1) { + // ----- Extract time + $v_hour = ($p_header['mtime'] & 0xF800) >> 11; + $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; + $v_seconde = ($p_header['mtime'] & 0x001F)*2; + + // ----- Extract date + $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; + $v_month = ($p_header['mdate'] & 0x01E0) >> 5; + $v_day = $p_header['mdate'] & 0x001F; + + // ----- Get UNIX date format + $p_header['mtime'] = @mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); + + } else { + $p_header['mtime'] = time(); + } + + // ----- Set the stored filename + $p_header['stored_filename'] = $p_header['filename']; + + // ----- Set default status to ok + $p_header['status'] = 'ok'; + + // ----- Look if it is a directory + if (substr($p_header['filename'], -1) == '/') { + //$p_header['external'] = 0x41FF0010; + $p_header['external'] = 0x00000010; + } + + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privCheckFileHeaders() + // Description : + // Parameters : + // Return Values : + // 1 on success, + // 0 on error; + // -------------------------------------------------------------------------------- + public function privCheckFileHeaders(&$p_local_header, &$p_central_header) + { + $v_result=1; + + // ----- Check the static values + // TBC + if ($p_local_header['filename'] != $p_central_header['filename']) { + } + if ($p_local_header['version_extracted'] != $p_central_header['version_extracted']) { + } + if ($p_local_header['flag'] != $p_central_header['flag']) { + } + if ($p_local_header['compression'] != $p_central_header['compression']) { + } + if ($p_local_header['mtime'] != $p_central_header['mtime']) { + } + if ($p_local_header['filename_len'] != $p_central_header['filename_len']) { + } + + // ----- Look for flag bit 3 + if (($p_local_header['flag'] & 8) == 8) { + $p_local_header['size'] = $p_central_header['size']; + $p_local_header['compressed_size'] = $p_central_header['compressed_size']; + $p_local_header['crc'] = $p_central_header['crc']; + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privReadEndCentralDir() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privReadEndCentralDir(&$p_central_dir) + { + $v_result=1; + + // ----- Go to the end of the zip file + $v_size = filesize($this->zipname); + @fseek($this->zip_fd, $v_size); + if (@ftell($this->zip_fd) != $v_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to go to the end of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- First try : look if this is an archive with no commentaries (most of the time) + // in this case the end of central dir is at 22 bytes of the file end + $v_found = 0; + if ($v_size > 26) { + @fseek($this->zip_fd, $v_size-22); + if (($v_pos = @ftell($this->zip_fd)) != ($v_size-22)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read for bytes + $v_binary_data = @fread($this->zip_fd, 4); + $v_data = @unpack('Vid', $v_binary_data); + + // ----- Check signature + if ($v_data['id'] == 0x06054b50) { + $v_found = 1; + } + + $v_pos = ftell($this->zip_fd); + } + + // ----- Go back to the maximum possible size of the Central Dir End Record + if (!$v_found) { + $v_maximum_size = 65557; // 0xFFFF + 22; + if ($v_maximum_size > $v_size) { + $v_maximum_size = $v_size; + } + @fseek($this->zip_fd, $v_size-$v_maximum_size); + if (@ftell($this->zip_fd) != ($v_size-$v_maximum_size)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'Unable to seek back to the middle of the archive \''.$this->zipname.'\''); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read byte per byte in order to find the signature + $v_pos = ftell($this->zip_fd); + $v_bytes = 0x00000000; + while ($v_pos < $v_size) { + // ----- Read a byte + $v_byte = @fread($this->zip_fd, 1); + + // ----- Add the byte + //$v_bytes = ($v_bytes << 8) | Ord($v_byte); + // Note we mask the old value down such that once shifted we can never end up with more than a 32bit number + // Otherwise on systems where we have 64bit integers the check below for the magic number will fail. + $v_bytes = (($v_bytes & 0xFFFFFF) << 8) | Ord($v_byte); + + // ----- Compare the bytes + if ($v_bytes == 0x504b0506) { + $v_pos++; + break; + } + + $v_pos++; + } + + // ----- Look if not found end of central dir + if ($v_pos == $v_size) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Unable to find End of Central Dir Record signature"); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Read the first 18 bytes of the header + $v_binary_data = fread($this->zip_fd, 18); + + // ----- Look for invalid block size + if (strlen($v_binary_data) != 18) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, "Invalid End of Central Dir Record size : ".strlen($v_binary_data)); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Extract the values + $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); + + // ----- Check the global size + if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { + // ----- Removed in release 2.2 see readme file + // The check of the file size is a little too strict. + // Some bugs where found when a zip is encrypted/decrypted with 'crypt'. + // While decrypted, zip has training 0 bytes + if (0) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_BAD_FORMAT, 'The central dir is not at the end of the archive. Some trailing bytes exists after the archive.'); + + // ----- Return + return PclZip::errorCode(); + } + } + + // ----- Get comment + if ($v_data['comment_size'] != 0) { + $p_central_dir['comment'] = fread($this->zip_fd, $v_data['comment_size']); + } else { + $p_central_dir['comment'] = ''; + } + + $p_central_dir['entries'] = $v_data['entries']; + $p_central_dir['disk_entries'] = $v_data['disk_entries']; + $p_central_dir['offset'] = $v_data['offset']; + $p_central_dir['size'] = $v_data['size']; + $p_central_dir['disk'] = $v_data['disk']; + $p_central_dir['disk_start'] = $v_data['disk_start']; + + // TBC + //for(reset($p_central_dir); $key = key($p_central_dir); next($p_central_dir)) { + //} + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDeleteByRule() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDeleteByRule(&$p_result_list, &$p_options) + { + $v_result=1; + $v_list_detail = array(); + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Scan all the files + // ----- Start at beginning of Central Dir + $v_pos_entry = $v_central_dir['offset']; + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_pos_entry)) { + // ----- Close the zip file + $this->privCloseFd(); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read each entry + $v_header_list = array(); + $j_start = 0; + for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { + // ----- Read the file header + $v_header_list[$v_nb_extracted] = array(); + if (($v_result = $this->privReadCentralFileHeader($v_header_list[$v_nb_extracted])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + + return $v_result; + } + + + // ----- Store the index + $v_header_list[$v_nb_extracted]['index'] = $i; + + // ----- Look for the specific extract rules + $v_found = false; + + // ----- Look for extract by name rule + if ((isset($p_options[PCLZIP_OPT_BY_NAME])) && ($p_options[PCLZIP_OPT_BY_NAME] != 0)) { + // ----- Look if the filename is in the list + for ($j=0; ($j<sizeof($p_options[PCLZIP_OPT_BY_NAME])) && (!$v_found); $j++) { + // ----- Look for a directory + if (substr($p_options[PCLZIP_OPT_BY_NAME][$j], -1) == "/") { + // ----- Look if the directory is in the filename path + if ((strlen($v_header_list[$v_nb_extracted]['stored_filename']) > strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_options[PCLZIP_OPT_BY_NAME][$j])) == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } elseif ((($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_options[PCLZIP_OPT_BY_NAME][$j])) { + $v_found = true; + } + } elseif ($v_header_list[$v_nb_extracted]['stored_filename'] == $p_options[PCLZIP_OPT_BY_NAME][$j]) { + // ----- Look for a filename + $v_found = true; + } + } + } elseif ((isset($p_options[PCLZIP_OPT_BY_PREG])) && ($p_options[PCLZIP_OPT_BY_PREG] != "")) { + // ----- Look for extract by preg rule + if (preg_match($p_options[PCLZIP_OPT_BY_PREG], $v_header_list[$v_nb_extracted]['stored_filename'])) { + $v_found = true; + } + } elseif ((isset($p_options[PCLZIP_OPT_BY_INDEX])) && ($p_options[PCLZIP_OPT_BY_INDEX] != 0)) { + // ----- Look for extract by index rule + // ----- Look if the index is in the list + for ($j=$j_start; ($j<sizeof($p_options[PCLZIP_OPT_BY_INDEX])) && (!$v_found); $j++) { + if (($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['start']) && ($i<=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end'])) { + $v_found = true; + } + if ($i>=$p_options[PCLZIP_OPT_BY_INDEX][$j]['end']) { + $j_start = $j+1; + } + if ($p_options[PCLZIP_OPT_BY_INDEX][$j]['start']>$i) { + break; + } + } + } else { + $v_found = true; + } + + // ----- Look for deletion + if ($v_found) { + unset($v_header_list[$v_nb_extracted]); + } else { + $v_nb_extracted++; + } + } + + // ----- Look if something need to be deleted + if ($v_nb_extracted > 0) { + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Creates a temporary zip archive + $v_temp_zip = new PclZip($v_zip_temp_name); + + // ----- Open the temporary zip file in write mode + if (($v_result = $v_temp_zip->privOpenFd('wb')) != 1) { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Look which file need to be kept + for ($i=0; $i<sizeof($v_header_list); $i++) { + // ----- Calculate the position of the header + @rewind($this->zip_fd); + if (@fseek($this->zip_fd, $v_header_list[$i]['offset'])) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Read the file header + $v_local_header = array(); + if (($v_result = $this->privReadFileHeader($v_local_header)) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Check that local file header is same as central file header + if ($this->privCheckFileHeaders($v_local_header, $v_header_list[$i]) != 1) { + // TBC + } + unset($v_local_header); + + // ----- Write the file header + if (($v_result = $v_temp_zip->privWriteFileHeader($v_header_list[$i])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Read/write the data block + if (($v_result = PclZipUtilCopyBlock($this->zip_fd, $v_temp_zip->zip_fd, $v_header_list[$i]['compressed_size'])) != 1) { + // ----- Close the zip file + $this->privCloseFd(); + $v_temp_zip->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_temp_zip->zip_fd); + + // ----- Re-Create the Central Dir files header + for ($i=0; $i<sizeof($v_header_list); $i++) { + // ----- Create the file header + if (($v_result = $v_temp_zip->privWriteCentralFileHeader($v_header_list[$i])) != 1) { + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Transform the header to a 'usable' info + $v_temp_zip->privConvertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); + } + + + // ----- Zip file comment + $v_comment = ''; + if (isset($p_options[PCLZIP_OPT_COMMENT])) { + $v_comment = $p_options[PCLZIP_OPT_COMMENT]; + } + + // ----- Calculate the size of the central header + $v_size = @ftell($v_temp_zip->zip_fd)-$v_offset; + + // ----- Create the central dir footer + if (($v_result = $v_temp_zip->privWriteCentralHeader(sizeof($v_header_list), $v_size, $v_offset, $v_comment)) != 1) { + // ----- Reset the file list + unset($v_header_list); + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + @unlink($v_zip_temp_name); + + // ----- Return + return $v_result; + } + + // ----- Close + $v_temp_zip->privCloseFd(); + $this->privCloseFd(); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Destroy the temporary archive + unset($v_temp_zip); + } elseif ($v_central_dir['entries'] != 0) { + // ----- Remove every files : reset the file + $this->privCloseFd(); + + if (($v_result = $this->privOpenFd('wb')) != 1) { + return $v_result; + } + + if (($v_result = $this->privWriteCentralHeader(0, 0, 0, '')) != 1) { + return $v_result; + } + + $this->privCloseFd(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDirCheck() + // Description : + // Check if a directory exists, if not it creates it and all the parents directory + // which may be useful. + // Parameters : + // $p_dir : Directory path to check. + // Return Values : + // 1 : OK + // -1 : Unable to create directory + // -------------------------------------------------------------------------------- + public function privDirCheck($p_dir, $p_is_dir = false) + { + $v_result = 1; + + // ----- Remove the final '/' + if (($p_is_dir) && (substr($p_dir, -1)=='/')) { + $p_dir = substr($p_dir, 0, strlen($p_dir)-1); + } + + // ----- Check the directory availability + if ((is_dir($p_dir)) || ($p_dir == "")) { + return 1; + } + + // ----- Extract parent directory + $p_parent_dir = dirname($p_dir); + + // ----- Just a check + if ($p_parent_dir != $p_dir) { + // ----- Look for parent directory + if ($p_parent_dir != "") { + if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) { + return $v_result; + } + } + } + + // ----- Create the directory + if (!@mkdir($p_dir, 0777)) { + // ----- Error log + PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '$p_dir'"); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privMerge() + // Description : + // If $p_archive_to_add does not exist, the function exit with a success result. + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privMerge(&$p_archive_to_add) + { + $v_result=1; + + // ----- Look if the archive_to_add exists + if (!is_file($p_archive_to_add->zipname)) { + // ----- Nothing to merge, so merge is a success + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Look if the archive exists + if (!is_file($this->zipname)) { + // ----- Do a duplicate + $v_result = $this->privDuplicate($p_archive_to_add->zipname); + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('rb')) != 1) { + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir = array(); + if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) { + $this->privCloseFd(); + return $v_result; + } + + // ----- Go to beginning of File + @rewind($this->zip_fd); + + // ----- Open the archive_to_add file + if (($v_result=$p_archive_to_add->privOpenFd('rb')) != 1) { + $this->privCloseFd(); + + // ----- Return + return $v_result; + } + + // ----- Read the central directory informations + $v_central_dir_to_add = array(); + if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + return $v_result; + } + + // ----- Go to beginning of File + @rewind($p_archive_to_add->zip_fd); + + // ----- Creates a temporay file + $v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp'; + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = $v_central_dir['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the files from the archive_to_add into the temporary file + $v_size = $v_central_dir_to_add['offset']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Store the offset of the central dir + $v_offset = @ftell($v_zip_temp_fd); + + // ----- Copy the block of file headers from the old archive + $v_size = $v_central_dir['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($this->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Copy the block of file headers from the archive_to_add + $v_size = $v_central_dir_to_add['size']; + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size); + @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Merge the file comments + $v_comment = $v_central_dir['comment'].' '.$v_central_dir_to_add['comment']; + + // ----- Calculate the size of the (new) central header + $v_size = @ftell($v_zip_temp_fd)-$v_offset; + + // ----- Swap the file descriptor + // Here is a trick : I swap the temporary fd with the zip fd, in order to use + // the following methods on the temporary fil and not the real archive fd + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Create the central dir footer + if (($v_result = $this->privWriteCentralHeader($v_central_dir['entries']+$v_central_dir_to_add['entries'], $v_size, $v_offset, $v_comment)) != 1) { + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + @fclose($v_zip_temp_fd); + $this->zip_fd = null; + + // ----- Reset the file list + unset($v_header_list); + + // ----- Return + return $v_result; + } + + // ----- Swap back the file descriptor + $v_swap = $this->zip_fd; + $this->zip_fd = $v_zip_temp_fd; + $v_zip_temp_fd = $v_swap; + + // ----- Close + $this->privCloseFd(); + $p_archive_to_add->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Delete the zip file + // TBC : I should test the result ... + @unlink($this->zipname); + + // ----- Rename the temporary file + // TBC : I should test the result ... + //@rename($v_zip_temp_name, $this->zipname); + PclZipUtilRename($v_zip_temp_name, $this->zipname); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDuplicate() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDuplicate($p_archive_filename) + { + $v_result=1; + + // ----- Look if the $p_archive_filename exists + if (!is_file($p_archive_filename)) { + // ----- Nothing to duplicate, so duplicate is a success. + $v_result = 1; + + // ----- Return + return $v_result; + } + + // ----- Open the zip file + if (($v_result=$this->privOpenFd('wb')) != 1) { + // ----- Return + return $v_result; + } + + // ----- Open the temporary file in write mode + if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { + $this->privCloseFd(); + + PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \''.$p_archive_filename.'\' in binary write mode'); + + // ----- Return + return PclZip::errorCode(); + } + + // ----- Copy the files from the archive to the temporary file + // TBC : Here I should better append the file and go back to erase the central dir + $v_size = filesize($p_archive_filename); + while ($v_size != 0) { + $v_read_size = ($v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = fread($v_zip_temp_fd, $v_read_size); + @fwrite($this->zip_fd, $v_buffer, $v_read_size); + $v_size -= $v_read_size; + } + + // ----- Close + $this->privCloseFd(); + + // ----- Close the temporary file + @fclose($v_zip_temp_fd); + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorLog() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privErrorLog($p_error_code = 0, $p_error_string = '') + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclError($p_error_code, $p_error_string); + } else { + $this->error_code = $p_error_code; + $this->error_string = $p_error_string; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privErrorReset() + // Description : + // Parameters : + // -------------------------------------------------------------------------------- + public function privErrorReset() + { + if (PCLZIP_ERROR_EXTERNAL == 1) { + PclErrorReset(); + } else { + $this->error_code = 0; + $this->error_string = ''; + } + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privDisableMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privDisableMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if already done + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Get and memorize the magic_quote value + $this->magic_quotes_status = @get_magic_quotes_runtime(); + + // ----- Disable magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime(0); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- + + // -------------------------------------------------------------------------------- + // Function : privSwapBackMagicQuotes() + // Description : + // Parameters : + // Return Values : + // -------------------------------------------------------------------------------- + public function privSwapBackMagicQuotes() + { + $v_result=1; + + // ----- Look if function exists + if ((!function_exists("get_magic_quotes_runtime")) || (!function_exists("set_magic_quotes_runtime"))) { + return $v_result; + } + + // ----- Look if something to do + if ($this->magic_quotes_status != -1) { + return $v_result; + } + + // ----- Swap back magic_quotes + if ($this->magic_quotes_status == 1) { + @set_magic_quotes_runtime($this->magic_quotes_status); + } + + // ----- Return + return $v_result; + } + // -------------------------------------------------------------------------------- +} +// End of class +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathReduction() +// Description : +// Parameters : +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilPathReduction($p_dir) +{ + $v_result = ""; + + // ----- Look for not empty path + if ($p_dir != "") { + // ----- Explode path by directory names + $v_list = explode("/", $p_dir); + + // ----- Study directories from last to first + $v_skip = 0; + for ($i=sizeof($v_list)-1; $i>=0; $i--) { + // ----- Look for current path + if ($v_list[$i] == ".") { + // ----- Ignore this directory + // Should be the first $i=0, but no check is done + } elseif ($v_list[$i] == "..") { + $v_skip++; + } elseif ($v_list[$i] == "") { + // ----- First '/' i.e. root slash + if ($i == 0) { + $v_result = "/".$v_result; + if ($v_skip > 0) { + // ----- It is an invalid path, so the path is not modified + // TBC + $v_result = $p_dir; + $v_skip = 0; + } + } elseif ($i == (sizeof($v_list)-1)) { + // ----- Last '/' i.e. indicates a directory + $v_result = $v_list[$i]; + } else { + // ----- Double '/' inside the path + // ----- Ignore only the double '//' in path, + // but not the first and last '/' + } + } else { + // ----- Look for item to skip + if ($v_skip > 0) { + $v_skip--; + } else { + $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); + } + } + } + + // ----- Look for skip + if ($v_skip > 0) { + while ($v_skip > 0) { + $v_result = '../'.$v_result; + $v_skip--; + } + } + } + + // ----- Return + return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilPathInclusion() +// Description : +// This function indicates if the path $p_path is under the $p_dir tree. Or, +// said in an other way, if the file or sub-dir $p_path is inside the dir +// $p_dir. +// The function indicates also if the path is exactly the same as the dir. +// This function supports path with duplicated '/' like '//', but does not +// support '.' or '..' statements. +// Parameters : +// Return Values : +// 0 if $p_path is not inside directory $p_dir +// 1 if $p_path is inside directory $p_dir +// 2 if $p_path is exactly the same as $p_dir +// -------------------------------------------------------------------------------- +function PclZipUtilPathInclusion($p_dir, $p_path) +{ + $v_result = 1; + + // ----- Look for path beginning by ./ + if (($p_dir == '.') || ((strlen($p_dir) >=2) && (substr($p_dir, 0, 2) == './'))) { + $p_dir = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_dir, 1); + } + if (($p_path == '.') || ((strlen($p_path) >=2) && (substr($p_path, 0, 2) == './'))) { + $p_path = PclZipUtilTranslateWinPath(getcwd(), false).'/'.substr($p_path, 1); + } + + // ----- Explode dir and path by directory separator + $v_list_dir = explode("/", $p_dir); + $v_list_dir_size = sizeof($v_list_dir); + $v_list_path = explode("/", $p_path); + $v_list_path_size = sizeof($v_list_path); + + // ----- Study directories paths + $i = 0; + $j = 0; + while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { + // ----- Look for empty dir (path reduction) + if ($v_list_dir[$i] == '') { + $i++; + continue; + } + if ($v_list_path[$j] == '') { + $j++; + continue; + } + + // ----- Compare the items + if (($v_list_dir[$i] != $v_list_path[$j]) && ($v_list_dir[$i] != '') && ($v_list_path[$j] != '')) { + $v_result = 0; + } + + // ----- Next items + $i++; + $j++; + } + + // ----- Look if everything seems to be the same + if ($v_result) { + // ----- Skip all the empty items + while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) { + $j++; + } + while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) { + $i++; + } + + if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { + // ----- There are exactly the same + $v_result = 2; + } elseif ($i < $v_list_dir_size) { + // ----- The path is shorter than the dir + $v_result = 0; + } + } + + // ----- Return + return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilCopyBlock() +// Description : +// Parameters : +// $p_mode : read/write compression mode +// 0 : src & dest normal +// 1 : src gzip, dest normal +// 2 : src normal, dest gzip +// 3 : src & dest gzip +// Return Values : +// -------------------------------------------------------------------------------- +function PclZipUtilCopyBlock($p_src, $p_dest, $p_size, $p_mode = 0) +{ + $v_result = 1; + + if ($p_mode==0) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode==1) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @fwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode==2) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @fread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } elseif ($p_mode==3) { + while ($p_size != 0) { + $v_read_size = ($p_size < PCLZIP_READ_BLOCK_SIZE ? $p_size : PCLZIP_READ_BLOCK_SIZE); + $v_buffer = @gzread($p_src, $v_read_size); + @gzwrite($p_dest, $v_buffer, $v_read_size); + $p_size -= $v_read_size; + } + } + + // ----- Return + return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilRename() +// Description : +// This function tries to do a simple rename() function. If it fails, it +// tries to copy the $p_src file in a new $p_dest file and then unlink the +// first one. +// Parameters : +// $p_src : Old filename +// $p_dest : New filename +// Return Values : +// 1 on success, 0 on failure. +// -------------------------------------------------------------------------------- +function PclZipUtilRename($p_src, $p_dest) +{ + $v_result = 1; + + // ----- Try to rename the files + if (!@rename($p_src, $p_dest)) { + // ----- Try to copy & unlink the src + if (!@copy($p_src, $p_dest)) { + $v_result = 0; + } elseif (!@unlink($p_src)) { + $v_result = 0; + } + } + + // ----- Return + return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilOptionText() +// Description : +// Translate option value in text. Mainly for debug purpose. +// Parameters : +// $p_option : the option value. +// Return Values : +// The option text value. +// -------------------------------------------------------------------------------- +function PclZipUtilOptionText($p_option) +{ + $v_list = get_defined_constants(); + for (reset($v_list); $v_key = key($v_list); next($v_list)) { + $v_prefix = substr($v_key, 0, 10); + if ((($v_prefix == 'PCLZIP_OPT') || ($v_prefix == 'PCLZIP_CB_') || ($v_prefix == 'PCLZIP_ATT')) && ($v_list[$v_key] == $p_option)) { + return $v_key; + } + } + + $v_result = 'Unknown'; + + return $v_result; +} +// -------------------------------------------------------------------------------- + +// -------------------------------------------------------------------------------- +// Function : PclZipUtilTranslateWinPath() +// Description : +// Translate windows path by replacing '\' by '/' and optionally removing +// drive letter. +// Parameters : +// $p_path : path to translate. +// $p_remove_disk_letter : true | false +// Return Values : +// The path translated. +// -------------------------------------------------------------------------------- +function PclZipUtilTranslateWinPath($p_path, $p_remove_disk_letter = true) +{ + if (stristr(php_uname(), 'windows')) { + // ----- Look for potential disk letter + if (($p_remove_disk_letter) && (($v_position = strpos($p_path, ':')) != false)) { + $p_path = substr($p_path, $v_position+1); + } + // ----- Change potential windows directory separator + if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) { + $p_path = strtr($p_path, '\\', '/'); + } + } + return $p_path; +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/readme.txt b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/readme.txt new file mode 100644 index 00000000..d1b11e25 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PCLZip/readme.txt @@ -0,0 +1,421 @@ +// -------------------------------------------------------------------------------- +// PclZip 2.8.2 - readme.txt +// -------------------------------------------------------------------------------- +// License GNU/LGPL - August 2009 +// Vincent Blavet - vincent@phpconcept.net +// http://www.phpconcept.net +// -------------------------------------------------------------------------------- +// $Id: readme.txt,v 1.60 2009/09/30 20:35:21 vblavet Exp $ +// -------------------------------------------------------------------------------- + + + +0 - Sommaire +============ + 1 - Introduction + 2 - What's new + 3 - Corrected bugs + 4 - Known bugs or limitations + 5 - License + 6 - Warning + 7 - Documentation + 8 - Author + 9 - Contribute + +1 - Introduction +================ + + PclZip is a library that allow you to manage a Zip archive. + + Full documentation about PclZip can be found here : http://www.phpconcept.net/pclzip + +2 - What's new +============== + + Version 2.8.2 : + - PCLZIP_CB_PRE_EXTRACT and PCLZIP_CB_POST_EXTRACT are now supported with + extraction as a string (PCLZIP_OPT_EXTRACT_AS_STRING). The string + can also be modified in the post-extract call back. + **Bugs correction : + - PCLZIP_OPT_REMOVE_ALL_PATH was not working correctly + - Remove use of eval() and do direct call to callback functions + - Correct support of 64bits systems (Thanks to WordPress team) + + Version 2.8.1 : + - Move option PCLZIP_OPT_BY_EREG to PCLZIP_OPT_BY_PREG because ereg() is + deprecated in PHP 5.3. When using option PCLZIP_OPT_BY_EREG, PclZip will + automatically replace it by PCLZIP_OPT_BY_PREG. + + Version 2.8 : + - Improve extraction of zip archive for large files by using temporary files + This feature is working like the one defined in r2.7. + Options are renamed : PCLZIP_OPT_TEMP_FILE_ON, PCLZIP_OPT_TEMP_FILE_OFF, + PCLZIP_OPT_TEMP_FILE_THRESHOLD + - Add a ratio constant PCLZIP_TEMPORARY_FILE_RATIO to configure the auto + sense of temporary file use. + - Bug correction : Reduce filepath in returned file list to remove ennoying + './/' preambule in file path. + + Version 2.7 : + - Improve creation of zip archive for large files : + PclZip will now autosense the configured memory and use temporary files + when large file is suspected. + This feature can also ne triggered by manual options in create() and add() + methods. 'PCLZIP_OPT_ADD_TEMP_FILE_ON' force the use of temporary files, + 'PCLZIP_OPT_ADD_TEMP_FILE_OFF' disable the autosense technic, + 'PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD' allow for configuration of a size + threshold to use temporary files. + Using "temporary files" rather than "memory" might take more time, but + might give the ability to zip very large files : + Tested on my win laptop with a 88Mo file : + Zip "in-memory" : 18sec (max_execution_time=30, memory_limit=180Mo) + Zip "tmporary-files" : 23sec (max_execution_time=30, memory_limit=30Mo) + - Replace use of mktime() by time() to limit the E_STRICT error messages. + - Bug correction : When adding files with full windows path (drive letter) + PclZip is now working. Before, if the drive letter is not the default + path, PclZip was not able to add the file. + + Version 2.6 : + - Code optimisation + - New attributes PCLZIP_ATT_FILE_COMMENT gives the ability to + add a comment for a specific file. (Don't really know if this is usefull) + - New attribute PCLZIP_ATT_FILE_CONTENT gives the ability to add a string + as a file. + - New attribute PCLZIP_ATT_FILE_MTIME modify the timestamp associated with + a file. + - Correct a bug. Files archived with a timestamp with 0h0m0s were extracted + with current time + - Add CRC value in the informations returned back for each file after an + action. + - Add missing closedir() statement. + - When adding a folder, and removing the path of this folder, files were + incorrectly added with a '/' at the beginning. Which means files are + related to root in unix systems. Corrected. + - Add conditional if before constant definition. This will allow users + to redefine constants without changing the file, and then improve + upgrade of pclzip code for new versions. + + Version 2.5 : + - Introduce the ability to add file/folder with individual properties (file descriptor). + This gives for example the ability to change the filename of a zipped file. + . Able to add files individually + . Able to change full name + . Able to change short name + . Compatible with global options + - New attributes : PCLZIP_ATT_FILE_NAME, PCLZIP_ATT_FILE_NEW_SHORT_NAME, PCLZIP_ATT_FILE_NEW_FULL_NAME + - New error code : PCLZIP_ERR_INVALID_ATTRIBUTE_VALUE + - Add a security control feature. PclZip can extract any file in any folder + of a system. People may use this to upload a zip file and try to override + a system file. The PCLZIP_OPT_EXTRACT_DIR_RESTRICTION will give the + ability to forgive any directory transversal behavior. + - New PCLZIP_OPT_EXTRACT_DIR_RESTRICTION : check extraction path + - New error code : PCLZIP_ERR_DIRECTORY_RESTRICTION + - Modification in PclZipUtilPathInclusion() : dir and path beginning with ./ will be prepend + by current path (getcwd()) + + Version 2.4 : + - Code improvment : try to speed up the code by removing unusefull call to pack() + - Correct bug in delete() : delete() should be called with no argument. This was not + the case in 2.3. This is corrected in 2.4. + - Correct a bug in path_inclusion function. When the path has several '../../', the + result was bad. + - Add a check for magic_quotes_runtime configuration. If enabled, PclZip will + disable it while working and det it back to its original value. + This resolve a lots of bad formated archive errors. + - Bug correction : PclZip now correctly unzip file in some specific situation, + when compressed content has same size as uncompressed content. + - Bug correction : When selecting option 'PCLZIP_OPT_REMOVE_ALL_PATH', + directories are not any more created. + - Code improvment : correct unclosed opendir(), better handling of . and .. in + loops. + + + Version 2.3 : + - Correct a bug with PHP5 : affecting the value 0xFE49FFE0 to a variable does not + give the same result in PHP4 and PHP5 .... + + Version 2.2 : + - Try development of PCLZIP_OPT_CRYPT ..... + However this becomes to a stop. To crypt/decrypt I need to multiply 2 long integers, + the result (greater than a long) is not supported by PHP. Even the use of bcmath + functions does not help. I did not find yet a solution ...; + - Add missing '/' at end of directory entries + - Check is a file is encrypted or not. Returns status 'unsupported_encryption' and/or + error code PCLZIP_ERR_UNSUPPORTED_ENCRYPTION. + - Corrected : Bad "version need to extract" field in local file header + - Add private method privCheckFileHeaders() in order to check local and central + file headers. PclZip is now supporting purpose bit flag bit 3. Purpose bit flag bit 3 gives + the ability to have a local file header without size, compressed size and crc filled. + - Add a generic status 'error' for file status + - Add control of compression type. PclZip only support deflate compression method. + Before v2.2, PclZip does not check the compression method used in an archive while + extracting. With v2.2 PclZip returns a new error status for a file using an unsupported + compression method. New status is "unsupported_compression". New error code is + PCLZIP_ERR_UNSUPPORTED_COMPRESSION. + - Add optional attribute PCLZIP_OPT_STOP_ON_ERROR. This will stop the extract of files + when errors like 'a folder with same name exists' or 'a newer file exists' or + 'a write protected file' exists, rather than set a status for the concerning file + and resume the extract of the zip. + - Add optional attribute PCLZIP_OPT_REPLACE_NEWER. This will force, during an extract' the + replacement of the file, even if a newer version of the file exists. + Note that today if a file with the same name already exists but is older it will be + replaced by the extracted one. + - Improve PclZipUtilOption() + - Support of zip archive with trailing bytes. Before 2.2, PclZip checks that the central + directory structure is the last data in the archive. Crypt encryption/decryption of + zip archive put trailing 0 bytes after decryption. PclZip is now supporting this. + + Version 2.1 : + - Add the ability to abort the extraction by using a user callback function. + The user can now return the value '2' in its callback which indicates to stop the + extraction. For a pre call-back extract is stopped before the extration of the current + file. For a post call back, the extraction is stopped after. + - Add the ability to extract a file (or several files) directly in the standard output. + This is done by the new parameter PCLZIP_OPT_EXTRACT_IN_OUTPUT with method extract(). + - Add support for parameters PCLZIP_OPT_COMMENT, PCLZIP_OPT_ADD_COMMENT, + PCLZIP_OPT_PREPEND_COMMENT. This will create, replace, add, or prepend comments + in the zip archive. + - When merging two archives, the comments are not any more lost, but merged, with a + blank space separator. + - Corrected bug : Files are not deleted when all files are asked to be deleted. + - Corrected bug : Folders with name '0' made PclZip to abort the create or add feature. + + + Version 2.0 : + ***** Warning : Some new features may break the backward compatibility for your scripts. + Please carefully read the readme file. + - Add the ability to delete by Index, name and regular expression. This feature is + performed by the method delete(), which uses the optional parameters + PCLZIP_OPT_BY_INDEX, PCLZIP_OPT_BY_NAME, PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG. + - Add the ability to extract by regular expression. To extract by regexp you must use the method + extract(), with the option PCLZIP_OPT_BY_EREG or PCLZIP_OPT_BY_PREG + (depending if you want to use ereg() or preg_match() syntax) followed by the + regular expression pattern. + - Add the ability to extract by index, directly with the extract() method. This is a + code improvment of the extractByIndex() method. + - Add the ability to extract by name. To extract by name you must use the method + extract(), with the option PCLZIP_OPT_BY_NAME followed by the filename to + extract or an array of filenames to extract. To extract all a folder, use the folder + name rather than the filename with a '/' at the end. + - Add the ability to add files without compression. This is done with a new attribute + which is PCLZIP_OPT_NO_COMPRESSION. + - Add the attribute PCLZIP_OPT_EXTRACT_AS_STRING, which allow to extract a file directly + in a string without using any file (or temporary file). + - Add constant PCLZIP_SEPARATOR for static configuration of filename separators in a single string. + The default separator is now a comma (,) and not any more a blank space. + THIS BREAK THE BACKWARD COMPATIBILITY : Please check if this may have an impact with + your script. + - Improve algorythm performance by removing the use of temporary files when adding or + extracting files in an archive. + - Add (correct) detection of empty filename zipping. This can occurs when the removed + path is the same + as a zipped dir. The dir is not zipped (['status'] = filtered), only its content. + - Add better support for windows paths (thanks for help from manus@manusfreedom.com). + - Corrected bug : When the archive file already exists with size=0, the add() method + fails. Corrected in 2.0. + - Remove the use of OS_WINDOWS constant. Use php_uname() function rather. + - Control the order of index ranges in extract by index feature. + - Change the internal management of folders (better handling of internal flag). + + + Version 1.3 : + - Removing the double include check. This is now done by include_once() and require_once() + PHP directives. + - Changing the error handling mecanism : Remove the use of an external error library. + The former PclError...() functions are replaced by internal equivalent methods. + By changing the environment variable PCLZIP_ERROR_EXTERNAL you can still use the former library. + Introducing the use of constants for error codes rather than integer values. This will help + in futur improvment. + Introduction of error handling functions like errorCode(), errorName() and errorInfo(). + - Remove the deprecated use of calling function with arguments passed by reference. + - Add the calling of extract(), extractByIndex(), create() and add() functions + with variable options rather than fixed arguments. + - Add the ability to remove all the file path while extracting or adding, + without any need to specify the path to remove. + This is available for extract(), extractByIndex(), create() and add() functionS by using + the new variable options parameters : + - PCLZIP_OPT_REMOVE_ALL_PATH : by indicating this option while calling the fct. + - Ability to change the mode of a file after the extraction (chmod()). + This is available for extract() and extractByIndex() functionS by using + the new variable options parameters. + - PCLZIP_OPT_SET_CHMOD : by setting the value of this option. + - Ability to definition call-back options. These call-back will be called during the adding, + or the extracting of file (extract(), extractByIndex(), create() and add() functions) : + - PCLZIP_CB_PRE_EXTRACT : will be called before each extraction of a file. The user + can trigerred the change the filename of the extracted file. The user can triggered the + skip of the extraction. This is adding a 'skipped' status in the file list result value. + - PCLZIP_CB_POST_EXTRACT : will be called after each extraction of a file. + Nothing can be triggered from that point. + - PCLZIP_CB_PRE_ADD : will be called before each add of a file. The user + can trigerred the change the stored filename of the added file. The user can triggered the + skip of the add. This is adding a 'skipped' status in the file list result value. + - PCLZIP_CB_POST_ADD : will be called after each add of a file. + Nothing can be triggered from that point. + - Two status are added in the file list returned as function result : skipped & filename_too_long + 'skipped' is used when a call-back function ask for skipping the file. + 'filename_too_long' is used while adding a file with a too long filename to archive (the file is + not added) + - Adding the function PclZipUtilPathInclusion(), that check the inclusion of a path into + a directory. + - Add a check of the presence of the archive file before some actions (like list, ...) + - Add the initialisation of field "index" in header array. This means that by + default index will be -1 when not explicitly set by the methods. + + Version 1.2 : + - Adding a duplicate function. + - Adding a merge function. The merge function is a "quick merge" function, + it just append the content of an archive at the end of the first one. There + is no check for duplicate files or more recent files. + - Improve the search of the central directory end. + + Version 1.1.2 : + + - Changing the license of PclZip. PclZip is now released under the GNU / LGPL license + (see License section). + - Adding the optional support of a static temporary directory. You will need to configure + the constant PCLZIP_TEMPORARY_DIR if you want to use this feature. + - Improving the rename() function. In some cases rename() does not work (different + Filesystems), so it will be replaced by a copy() + unlink() functions. + + Version 1.1.1 : + + - Maintenance release, no new feature. + + Version 1.1 : + + - New method Add() : adding files in the archive + - New method ExtractByIndex() : partial extract of the archive, files are identified by + their index in the archive + - New method DeleteByIndex() : delete some files/folder entries from the archive, + files are identified by their index in the archive. + - Adding a test of the zlib extension presence. If not present abort the script. + + Version 1.0.1 : + + - No new feature + + +3 - Corrected bugs +================== + + Corrected in Version 2.0 : + - Corrected : During an extraction, if a call-back fucntion is used and try to skip + a file, all the extraction process is stopped. + + Corrected in Version 1.3 : + - Corrected : Support of static synopsis for method extract() is broken. + - Corrected : invalid size of archive content field (0xFF) should be (0xFFFF). + - Corrected : When an extract is done with a remove_path parameter, the entry for + the directory with exactly the same path is not skipped/filtered. + - Corrected : extractByIndex() and deleteByIndex() were not managing index in the + right way. For example indexes '1,3-5,11' will only extract files 1 and 11. This + is due to a sort of the index resulting table that puts 11 before 3-5 (sort on + string and not interger). The sort is temporarilly removed, this means that + you must provide a sorted list of index ranges. + + Corrected in Version 1.2 : + + - Nothing. + + Corrected in Version 1.1.2 : + + - Corrected : Winzip is unable to delete or add new files in a PclZip created archives. + + Corrected in Version 1.1.1 : + + - Corrected : When archived file is not compressed (0% compression), the + extract method fails. + + Corrected in Version 1.1 : + + - Corrected : Adding a complete tree of folder may result in a bad archive + creation. + + Corrected in Version 1.0.1 : + + - Corrected : Error while compressing files greater than PCLZIP_READ_BLOCK_SIZE (default=1024). + + +4 - Known bugs or limitations +============================= + + Please publish bugs reports in SourceForge : + http://sourceforge.net/tracker/?group_id=40254&atid=427564 + + In Version 2.x : + - PclZip does only support file uncompressed or compressed with deflate (compression method 8) + - PclZip does not support password protected zip archive + - Some concern were seen when changing mtime of a file while archiving. + Seems to be linked to Daylight Saving Time (PclTest_changing_mtime). + + In Version 1.2 : + + - merge() methods does not check for duplicate files or last date of modifications. + + In Version 1.1 : + + - Limitation : Using 'extract' fields in the file header in the zip archive is not supported. + - WinZip is unable to delete a single file in a PclZip created archive. It is also unable to + add a file in a PclZip created archive. (Corrected in v.1.2) + + In Version 1.0.1 : + + - Adding a complete tree of folder may result in a bad archive + creation. (Corrected in V.1.1). + - Path given to methods must be in the unix format (/) and not the Windows format (\). + Workaround : Use only / directory separators. + - PclZip is using temporary files that are sometime the name of the file with a .tmp or .gz + added suffix. Files with these names may already exist and may be overwritten. + Workaround : none. + - PclZip does not check if the zlib extension is present. If it is absent, the zip + file is not created and the lib abort without warning. + Workaround : enable the zlib extension on the php install + + In Version 1.0 : + + - Error while compressing files greater than PCLZIP_READ_BLOCK_SIZE (default=1024). + (Corrected in v.1.0.1) + - Limitation : Multi-disk zip archive are not supported. + + +5 - License +=========== + + Since version 1.1.2, PclZip Library is released under GNU/LGPL license. + This library is free, so you can use it at no cost. + + HOWEVER, if you release a script, an application, a library or any kind of + code using PclZip library (or a part of it), YOU MUST : + - Indicate in the documentation (or a readme file), that your work + uses PclZip Library, and make a reference to the author and the web site + http://www.phpconcept.net + - Gives the ability to the final user to update the PclZip libary. + + I will also appreciate that you send me a mail (vincent@phpconcept.net), just to + be aware that someone is using PclZip. + + For more information about GNU/LGPL license : http://www.gnu.org + +6 - Warning +================= + + This library and the associated files are non commercial, non professional work. + It should not have unexpected results. However if any damage is caused by this software + the author can not be responsible. + The use of this software is at the risk of the user. + +7 - Documentation +================= + PclZip User Manuel is available in English on PhpConcept : http://www.phpconcept.net/pclzip/man/en/index.php + A Russian translation was done by Feskov Kuzma : http://php.russofile.ru/ru/authors/unsort/zip/ + +8 - Author +========== + + This software was written by Vincent Blavet (vincent@phpconcept.net) on its leasure time. + +9 - Contribute +============== + If you want to contribute to the development of PclZip, please contact vincent@phpconcept.net. + If you can help in financing PhpConcept hosting service, please go to + http://www.phpconcept.net/soutien.php diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PasswordHasher.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PasswordHasher.php new file mode 100644 index 00000000..946742bf --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/PasswordHasher.php @@ -0,0 +1,67 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Shared_PasswordHasher + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_PasswordHasher +{ + /** + * Create a password hash from a given string. + * + * This method is based on the algorithm provided by + * Daniel Rentz of OpenOffice and the PEAR package + * Spreadsheet_Excel_Writer by Xavier Noguer <xnoguer@rezebra.com>. + * + * @param string $pPassword Password to hash + * @return string Hashed password + */ + public static function hashPassword($pPassword = '') + { + $password = 0x0000; + $charPos = 1; // char position + + // split the plain text password in its component characters + $chars = preg_split('//', $pPassword, -1, PREG_SPLIT_NO_EMPTY); + foreach ($chars as $char) { + $value = ord($char) << $charPos++; // shifted ASCII value + $rotated_bits = $value >> 15; // rotated bits beyond bit 15 + $value &= 0x7fff; // first 15 bits + $password ^= ($value | $rotated_bits); + } + + $password ^= strlen($pPassword); + $password ^= 0xCE4B; + + return(strtoupper(dechex($password))); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/String.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/String.php new file mode 100644 index 00000000..fa1a64e0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/String.php @@ -0,0 +1,819 @@ +<?php + +/** + * PHPExcel_Shared_String + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_String +{ + /** Constants */ + /** Regular Expressions */ + // Fraction + const STRING_REGEXP_FRACTION = '(-?)(\d+)\s+(\d+\/\d+)'; + + + /** + * Control characters array + * + * @var string[] + */ + private static $controlCharacters = array(); + + /** + * SYLK Characters array + * + * $var array + */ + private static $SYLKCharacters = array(); + + /** + * Decimal separator + * + * @var string + */ + private static $decimalSeparator; + + /** + * Thousands separator + * + * @var string + */ + private static $thousandsSeparator; + + /** + * Currency code + * + * @var string + */ + private static $currencyCode; + + /** + * Is mbstring extension avalable? + * + * @var boolean + */ + private static $isMbstringEnabled; + + /** + * Is iconv extension avalable? + * + * @var boolean + */ + private static $isIconvEnabled; + + /** + * Build control characters array + */ + private static function buildControlCharacters() + { + for ($i = 0; $i <= 31; ++$i) { + if ($i != 9 && $i != 10 && $i != 13) { + $find = '_x' . sprintf('%04s', strtoupper(dechex($i))) . '_'; + $replace = chr($i); + self::$controlCharacters[$find] = $replace; + } + } + } + + /** + * Build SYLK characters array + */ + private static function buildSYLKCharacters() + { + self::$SYLKCharacters = array( + "\x1B 0" => chr(0), + "\x1B 1" => chr(1), + "\x1B 2" => chr(2), + "\x1B 3" => chr(3), + "\x1B 4" => chr(4), + "\x1B 5" => chr(5), + "\x1B 6" => chr(6), + "\x1B 7" => chr(7), + "\x1B 8" => chr(8), + "\x1B 9" => chr(9), + "\x1B :" => chr(10), + "\x1B ;" => chr(11), + "\x1B <" => chr(12), + "\x1B :" => chr(13), + "\x1B >" => chr(14), + "\x1B ?" => chr(15), + "\x1B!0" => chr(16), + "\x1B!1" => chr(17), + "\x1B!2" => chr(18), + "\x1B!3" => chr(19), + "\x1B!4" => chr(20), + "\x1B!5" => chr(21), + "\x1B!6" => chr(22), + "\x1B!7" => chr(23), + "\x1B!8" => chr(24), + "\x1B!9" => chr(25), + "\x1B!:" => chr(26), + "\x1B!;" => chr(27), + "\x1B!<" => chr(28), + "\x1B!=" => chr(29), + "\x1B!>" => chr(30), + "\x1B!?" => chr(31), + "\x1B'?" => chr(127), + "\x1B(0" => '€', // 128 in CP1252 + "\x1B(2" => '‚', // 130 in CP1252 + "\x1B(3" => 'ƒ', // 131 in CP1252 + "\x1B(4" => '„', // 132 in CP1252 + "\x1B(5" => '…', // 133 in CP1252 + "\x1B(6" => '†', // 134 in CP1252 + "\x1B(7" => '‡', // 135 in CP1252 + "\x1B(8" => 'ˆ', // 136 in CP1252 + "\x1B(9" => '‰', // 137 in CP1252 + "\x1B(:" => 'Š', // 138 in CP1252 + "\x1B(;" => '‹', // 139 in CP1252 + "\x1BNj" => 'Œ', // 140 in CP1252 + "\x1B(>" => 'Ž', // 142 in CP1252 + "\x1B)1" => '‘', // 145 in CP1252 + "\x1B)2" => '’', // 146 in CP1252 + "\x1B)3" => '“', // 147 in CP1252 + "\x1B)4" => '”', // 148 in CP1252 + "\x1B)5" => '•', // 149 in CP1252 + "\x1B)6" => '–', // 150 in CP1252 + "\x1B)7" => '—', // 151 in CP1252 + "\x1B)8" => '˜', // 152 in CP1252 + "\x1B)9" => '™', // 153 in CP1252 + "\x1B):" => 'š', // 154 in CP1252 + "\x1B);" => '›', // 155 in CP1252 + "\x1BNz" => 'œ', // 156 in CP1252 + "\x1B)>" => 'ž', // 158 in CP1252 + "\x1B)?" => 'Ÿ', // 159 in CP1252 + "\x1B*0" => ' ', // 160 in CP1252 + "\x1BN!" => '¡', // 161 in CP1252 + "\x1BN\"" => '¢', // 162 in CP1252 + "\x1BN#" => '£', // 163 in CP1252 + "\x1BN(" => '¤', // 164 in CP1252 + "\x1BN%" => '¥', // 165 in CP1252 + "\x1B*6" => '¦', // 166 in CP1252 + "\x1BN'" => '§', // 167 in CP1252 + "\x1BNH " => '¨', // 168 in CP1252 + "\x1BNS" => '©', // 169 in CP1252 + "\x1BNc" => 'ª', // 170 in CP1252 + "\x1BN+" => '«', // 171 in CP1252 + "\x1B*<" => '¬', // 172 in CP1252 + "\x1B*=" => '­', // 173 in CP1252 + "\x1BNR" => '®', // 174 in CP1252 + "\x1B*?" => '¯', // 175 in CP1252 + "\x1BN0" => '°', // 176 in CP1252 + "\x1BN1" => '±', // 177 in CP1252 + "\x1BN2" => '²', // 178 in CP1252 + "\x1BN3" => '³', // 179 in CP1252 + "\x1BNB " => '´', // 180 in CP1252 + "\x1BN5" => 'µ', // 181 in CP1252 + "\x1BN6" => '¶', // 182 in CP1252 + "\x1BN7" => '·', // 183 in CP1252 + "\x1B+8" => '¸', // 184 in CP1252 + "\x1BNQ" => '¹', // 185 in CP1252 + "\x1BNk" => 'º', // 186 in CP1252 + "\x1BN;" => '»', // 187 in CP1252 + "\x1BN<" => '¼', // 188 in CP1252 + "\x1BN=" => '½', // 189 in CP1252 + "\x1BN>" => '¾', // 190 in CP1252 + "\x1BN?" => '¿', // 191 in CP1252 + "\x1BNAA" => 'À', // 192 in CP1252 + "\x1BNBA" => 'Á', // 193 in CP1252 + "\x1BNCA" => 'Â', // 194 in CP1252 + "\x1BNDA" => 'Ã', // 195 in CP1252 + "\x1BNHA" => 'Ä', // 196 in CP1252 + "\x1BNJA" => 'Å', // 197 in CP1252 + "\x1BNa" => 'Æ', // 198 in CP1252 + "\x1BNKC" => 'Ç', // 199 in CP1252 + "\x1BNAE" => 'È', // 200 in CP1252 + "\x1BNBE" => 'É', // 201 in CP1252 + "\x1BNCE" => 'Ê', // 202 in CP1252 + "\x1BNHE" => 'Ë', // 203 in CP1252 + "\x1BNAI" => 'Ì', // 204 in CP1252 + "\x1BNBI" => 'Í', // 205 in CP1252 + "\x1BNCI" => 'Î', // 206 in CP1252 + "\x1BNHI" => 'Ï', // 207 in CP1252 + "\x1BNb" => 'Ð', // 208 in CP1252 + "\x1BNDN" => 'Ñ', // 209 in CP1252 + "\x1BNAO" => 'Ò', // 210 in CP1252 + "\x1BNBO" => 'Ó', // 211 in CP1252 + "\x1BNCO" => 'Ô', // 212 in CP1252 + "\x1BNDO" => 'Õ', // 213 in CP1252 + "\x1BNHO" => 'Ö', // 214 in CP1252 + "\x1B-7" => '×', // 215 in CP1252 + "\x1BNi" => 'Ø', // 216 in CP1252 + "\x1BNAU" => 'Ù', // 217 in CP1252 + "\x1BNBU" => 'Ú', // 218 in CP1252 + "\x1BNCU" => 'Û', // 219 in CP1252 + "\x1BNHU" => 'Ü', // 220 in CP1252 + "\x1B-=" => 'Ý', // 221 in CP1252 + "\x1BNl" => 'Þ', // 222 in CP1252 + "\x1BN{" => 'ß', // 223 in CP1252 + "\x1BNAa" => 'à', // 224 in CP1252 + "\x1BNBa" => 'á', // 225 in CP1252 + "\x1BNCa" => 'â', // 226 in CP1252 + "\x1BNDa" => 'ã', // 227 in CP1252 + "\x1BNHa" => 'ä', // 228 in CP1252 + "\x1BNJa" => 'å', // 229 in CP1252 + "\x1BNq" => 'æ', // 230 in CP1252 + "\x1BNKc" => 'ç', // 231 in CP1252 + "\x1BNAe" => 'è', // 232 in CP1252 + "\x1BNBe" => 'é', // 233 in CP1252 + "\x1BNCe" => 'ê', // 234 in CP1252 + "\x1BNHe" => 'ë', // 235 in CP1252 + "\x1BNAi" => 'ì', // 236 in CP1252 + "\x1BNBi" => 'í', // 237 in CP1252 + "\x1BNCi" => 'î', // 238 in CP1252 + "\x1BNHi" => 'ï', // 239 in CP1252 + "\x1BNs" => 'ð', // 240 in CP1252 + "\x1BNDn" => 'ñ', // 241 in CP1252 + "\x1BNAo" => 'ò', // 242 in CP1252 + "\x1BNBo" => 'ó', // 243 in CP1252 + "\x1BNCo" => 'ô', // 244 in CP1252 + "\x1BNDo" => 'õ', // 245 in CP1252 + "\x1BNHo" => 'ö', // 246 in CP1252 + "\x1B/7" => '÷', // 247 in CP1252 + "\x1BNy" => 'ø', // 248 in CP1252 + "\x1BNAu" => 'ù', // 249 in CP1252 + "\x1BNBu" => 'ú', // 250 in CP1252 + "\x1BNCu" => 'û', // 251 in CP1252 + "\x1BNHu" => 'ü', // 252 in CP1252 + "\x1B/=" => 'ý', // 253 in CP1252 + "\x1BN|" => 'þ', // 254 in CP1252 + "\x1BNHy" => 'ÿ', // 255 in CP1252 + ); + } + + /** + * Get whether mbstring extension is available + * + * @return boolean + */ + public static function getIsMbstringEnabled() + { + if (isset(self::$isMbstringEnabled)) { + return self::$isMbstringEnabled; + } + + self::$isMbstringEnabled = function_exists('mb_convert_encoding') ? + true : false; + + return self::$isMbstringEnabled; + } + + /** + * Get whether iconv extension is available + * + * @return boolean + */ + public static function getIsIconvEnabled() + { + if (isset(self::$isIconvEnabled)) { + return self::$isIconvEnabled; + } + + // Fail if iconv doesn't exist + if (!function_exists('iconv')) { + self::$isIconvEnabled = false; + return false; + } + + // Sometimes iconv is not working, and e.g. iconv('UTF-8', 'UTF-16LE', 'x') just returns false, + if (!@iconv('UTF-8', 'UTF-16LE', 'x')) { + self::$isIconvEnabled = false; + return false; + } + + // Sometimes iconv_substr('A', 0, 1, 'UTF-8') just returns false in PHP 5.2.0 + // we cannot use iconv in that case either (http://bugs.php.net/bug.php?id=37773) + if (!@iconv_substr('A', 0, 1, 'UTF-8')) { + self::$isIconvEnabled = false; + return false; + } + + // CUSTOM: IBM AIX iconv() does not work + if (defined('PHP_OS') && @stristr(PHP_OS, 'AIX') && defined('ICONV_IMPL') && (@strcasecmp(ICONV_IMPL, 'unknown') == 0) && defined('ICONV_VERSION') && (@strcasecmp(ICONV_VERSION, 'unknown') == 0)) { + self::$isIconvEnabled = false; + return false; + } + + // If we reach here no problems were detected with iconv + self::$isIconvEnabled = true; + return true; + } + + public static function buildCharacterSets() + { + if (empty(self::$controlCharacters)) { + self::buildControlCharacters(); + } + if (empty(self::$SYLKCharacters)) { + self::buildSYLKCharacters(); + } + } + + /** + * Convert from OpenXML escaped control character to PHP control character + * + * Excel 2007 team: + * ---------------- + * That's correct, control characters are stored directly in the shared-strings table. + * We do encode characters that cannot be represented in XML using the following escape sequence: + * _xHHHH_ where H represents a hexadecimal character in the character's value... + * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) + * element or in the shared string <t> element. + * + * @param string $value Value to unescape + * @return string + */ + public static function ControlCharacterOOXML2PHP($value = '') + { + return str_replace(array_keys(self::$controlCharacters), array_values(self::$controlCharacters), $value); + } + + /** + * Convert from PHP control character to OpenXML escaped control character + * + * Excel 2007 team: + * ---------------- + * That's correct, control characters are stored directly in the shared-strings table. + * We do encode characters that cannot be represented in XML using the following escape sequence: + * _xHHHH_ where H represents a hexadecimal character in the character's value... + * So you could end up with something like _x0008_ in a string (either in a cell value (<v>) + * element or in the shared string <t> element. + * + * @param string $value Value to escape + * @return string + */ + public static function ControlCharacterPHP2OOXML($value = '') + { + return str_replace(array_values(self::$controlCharacters), array_keys(self::$controlCharacters), $value); + } + + /** + * Try to sanitize UTF8, stripping invalid byte sequences. Not perfect. Does not surrogate characters. + * + * @param string $value + * @return string + */ + public static function SanitizeUTF8($value) + { + if (self::getIsIconvEnabled()) { + $value = @iconv('UTF-8', 'UTF-8', $value); + return $value; + } + + if (self::getIsMbstringEnabled()) { + $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8'); + return $value; + } + + // else, no conversion + return $value; + } + + /** + * Check if a string contains UTF8 data + * + * @param string $value + * @return boolean + */ + public static function IsUTF8($value = '') + { + return $value === '' || preg_match('/^./su', $value) === 1; + } + + /** + * Formats a numeric value as a string for output in various output writers forcing + * point as decimal separator in case locale is other than English. + * + * @param mixed $value + * @return string + */ + public static function FormatNumber($value) + { + if (is_float($value)) { + return str_replace(',', '.', $value); + } + return (string) $value; + } + + /** + * Converts a UTF-8 string into BIFF8 Unicode string data (8-bit string length) + * Writes the string using uncompressed notation, no rich text, no Asian phonetics + * If mbstring extension is not available, ASCII is assumed, and compressed notation is used + * although this will give wrong results for non-ASCII strings + * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3 + * + * @param string $value UTF-8 encoded string + * @param mixed[] $arrcRuns Details of rich text runs in $value + * @return string + */ + public static function UTF8toBIFF8UnicodeShort($value, $arrcRuns = array()) + { + // character count + $ln = self::CountCharacters($value, 'UTF-8'); + // option flags + if (empty($arrcRuns)) { + $opt = (self::getIsIconvEnabled() || self::getIsMbstringEnabled()) ? + 0x0001 : 0x0000; + $data = pack('CC', $ln, $opt); + // characters + $data .= self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + } else { + $data = pack('vC', $ln, 0x09); + $data .= pack('v', count($arrcRuns)); + // characters + $data .= self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + foreach ($arrcRuns as $cRun) { + $data .= pack('v', $cRun['strlen']); + $data .= pack('v', $cRun['fontidx']); + } + } + return $data; + } + + /** + * Converts a UTF-8 string into BIFF8 Unicode string data (16-bit string length) + * Writes the string using uncompressed notation, no rich text, no Asian phonetics + * If mbstring extension is not available, ASCII is assumed, and compressed notation is used + * although this will give wrong results for non-ASCII strings + * see OpenOffice.org's Documentation of the Microsoft Excel File Format, sect. 2.5.3 + * + * @param string $value UTF-8 encoded string + * @return string + */ + public static function UTF8toBIFF8UnicodeLong($value) + { + // character count + $ln = self::CountCharacters($value, 'UTF-8'); + + // option flags + $opt = (self::getIsIconvEnabled() || self::getIsMbstringEnabled()) ? + 0x0001 : 0x0000; + + // characters + $chars = self::ConvertEncoding($value, 'UTF-16LE', 'UTF-8'); + + $data = pack('vC', $ln, $opt) . $chars; + return $data; + } + + /** + * Convert string from one encoding to another. First try mbstring, then iconv, finally strlen + * + * @param string $value + * @param string $to Encoding to convert to, e.g. 'UTF-8' + * @param string $from Encoding to convert from, e.g. 'UTF-16LE' + * @return string + */ + public static function ConvertEncoding($value, $to, $from) + { + if (self::getIsIconvEnabled()) { + return iconv($from, $to, $value); + } + + if (self::getIsMbstringEnabled()) { + return mb_convert_encoding($value, $to, $from); + } + + if ($from == 'UTF-16LE') { + return self::utf16_decode($value, false); + } elseif ($from == 'UTF-16BE') { + return self::utf16_decode($value); + } + // else, no conversion + return $value; + } + + /** + * Decode UTF-16 encoded strings. + * + * Can handle both BOM'ed data and un-BOM'ed data. + * Assumes Big-Endian byte order if no BOM is available. + * This function was taken from http://php.net/manual/en/function.utf8-decode.php + * and $bom_be parameter added. + * + * @param string $str UTF-16 encoded data to decode. + * @return string UTF-8 / ISO encoded data. + * @access public + * @version 0.2 / 2010-05-13 + * @author Rasmus Andersson {@link http://rasmusandersson.se/} + * @author vadik56 + */ + public static function utf16_decode($str, $bom_be = true) + { + if (strlen($str) < 2) { + return $str; + } + $c0 = ord($str{0}); + $c1 = ord($str{1}); + if ($c0 == 0xfe && $c1 == 0xff) { + $str = substr($str, 2); + } elseif ($c0 == 0xff && $c1 == 0xfe) { + $str = substr($str, 2); + $bom_be = false; + } + $len = strlen($str); + $newstr = ''; + for ($i=0; $i<$len; $i+=2) { + if ($bom_be) { + $val = ord($str{$i}) << 4; + $val += ord($str{$i+1}); + } else { + $val = ord($str{$i+1}) << 4; + $val += ord($str{$i}); + } + $newstr .= ($val == 0x228) ? "\n" : chr($val); + } + return $newstr; + } + + /** + * Get character count. First try mbstring, then iconv, finally strlen + * + * @param string $value + * @param string $enc Encoding + * @return int Character count + */ + public static function CountCharacters($value, $enc = 'UTF-8') + { + if (self::getIsMbstringEnabled()) { + return mb_strlen($value, $enc); + } + + if (self::getIsIconvEnabled()) { + return iconv_strlen($value, $enc); + } + + // else strlen + return strlen($value); + } + + /** + * Get a substring of a UTF-8 encoded string. First try mbstring, then iconv, finally strlen + * + * @param string $pValue UTF-8 encoded string + * @param int $pStart Start offset + * @param int $pLength Maximum number of characters in substring + * @return string + */ + public static function Substring($pValue = '', $pStart = 0, $pLength = 0) + { + if (self::getIsMbstringEnabled()) { + return mb_substr($pValue, $pStart, $pLength, 'UTF-8'); + } + + if (self::getIsIconvEnabled()) { + return iconv_substr($pValue, $pStart, $pLength, 'UTF-8'); + } + + // else substr + return substr($pValue, $pStart, $pLength); + } + + /** + * Convert a UTF-8 encoded string to upper case + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToUpper($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_UPPER, "UTF-8"); + } + return strtoupper($pValue); + } + + /** + * Convert a UTF-8 encoded string to lower case + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToLower($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_LOWER, "UTF-8"); + } + return strtolower($pValue); + } + + /** + * Convert a UTF-8 encoded string to title/proper case + * (uppercase every first character in each word, lower case all other characters) + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrToTitle($pValue = '') + { + if (function_exists('mb_convert_case')) { + return mb_convert_case($pValue, MB_CASE_TITLE, "UTF-8"); + } + return ucwords($pValue); + } + + public static function mb_is_upper($char) + { + return mb_strtolower($char, "UTF-8") != $char; + } + + public static function mb_str_split($string) + { + # Split at all position not after the start: ^ + # and not before the end: $ + return preg_split('/(?<!^)(?!$)/u', $string); + } + + /** + * Reverse the case of a string, so that all uppercase characters become lowercase + * and all lowercase characters become uppercase + * + * @param string $pValue UTF-8 encoded string + * @return string + */ + public static function StrCaseReverse($pValue = '') + { + if (self::getIsMbstringEnabled()) { + $characters = self::mb_str_split($pValue); + foreach ($characters as &$character) { + if (self::mb_is_upper($character)) { + $character = mb_strtolower($character, 'UTF-8'); + } else { + $character = mb_strtoupper($character, 'UTF-8'); + } + } + return implode('', $characters); + } + return strtolower($pValue) ^ strtoupper($pValue) ^ $pValue; + } + + /** + * Identify whether a string contains a fractional numeric value, + * and convert it to a numeric if it is + * + * @param string &$operand string value to test + * @return boolean + */ + public static function convertToNumberIfFraction(&$operand) + { + if (preg_match('/^'.self::STRING_REGEXP_FRACTION.'$/i', $operand, $match)) { + $sign = ($match[1] == '-') ? '-' : '+'; + $fractionFormula = '='.$sign.$match[2].$sign.$match[3]; + $operand = PHPExcel_Calculation::getInstance()->_calculateFormulaValue($fractionFormula); + return true; + } + return false; + } // function convertToNumberIfFraction() + + /** + * Get the decimal separator. If it has not yet been set explicitly, try to obtain number + * formatting information from locale. + * + * @return string + */ + public static function getDecimalSeparator() + { + if (!isset(self::$decimalSeparator)) { + $localeconv = localeconv(); + self::$decimalSeparator = ($localeconv['decimal_point'] != '') + ? $localeconv['decimal_point'] : $localeconv['mon_decimal_point']; + + if (self::$decimalSeparator == '') { + // Default to . + self::$decimalSeparator = '.'; + } + } + return self::$decimalSeparator; + } + + /** + * Set the decimal separator. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for decimal separator + */ + public static function setDecimalSeparator($pValue = '.') + { + self::$decimalSeparator = $pValue; + } + + /** + * Get the thousands separator. If it has not yet been set explicitly, try to obtain number + * formatting information from locale. + * + * @return string + */ + public static function getThousandsSeparator() + { + if (!isset(self::$thousandsSeparator)) { + $localeconv = localeconv(); + self::$thousandsSeparator = ($localeconv['thousands_sep'] != '') + ? $localeconv['thousands_sep'] : $localeconv['mon_thousands_sep']; + + if (self::$thousandsSeparator == '') { + // Default to . + self::$thousandsSeparator = ','; + } + } + return self::$thousandsSeparator; + } + + /** + * Set the thousands separator. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for thousands separator + */ + public static function setThousandsSeparator($pValue = ',') + { + self::$thousandsSeparator = $pValue; + } + + /** + * Get the currency code. If it has not yet been set explicitly, try to obtain the + * symbol information from locale. + * + * @return string + */ + public static function getCurrencyCode() + { + if (!isset(self::$currencyCode)) { + $localeconv = localeconv(); + self::$currencyCode = ($localeconv['currency_symbol'] != '') + ? $localeconv['currency_symbol'] : $localeconv['int_curr_symbol']; + + if (self::$currencyCode == '') { + // Default to $ + self::$currencyCode = '$'; + } + } + return self::$currencyCode; + } + + /** + * Set the currency code. Only used by PHPExcel_Style_NumberFormat::toFormattedString() + * to format output by PHPExcel_Writer_HTML and PHPExcel_Writer_PDF + * + * @param string $pValue Character for currency code + */ + public static function setCurrencyCode($pValue = '$') + { + self::$currencyCode = $pValue; + } + + /** + * Convert SYLK encoded string to UTF-8 + * + * @param string $pValue + * @return string UTF-8 encoded string + */ + public static function SYLKtoUTF8($pValue = '') + { + // If there is no escape character in the string there is nothing to do + if (strpos($pValue, '') === false) { + return $pValue; + } + + foreach (self::$SYLKCharacters as $k => $v) { + $pValue = str_replace($k, $v, $pValue); + } + + return $pValue; + } + + /** + * Retrieve any leading numeric part of a string, or return the full string if no leading numeric + * (handles basic integer or float, but not exponent or non decimal) + * + * @param string $value + * @return mixed string or only the leading numeric part of the string + */ + public static function testStringAsNumeric($value) + { + if (is_numeric($value)) { + return $value; + } + $v = floatval($value); + return (is_numeric(substr($value, 0, strlen($v)))) ? $v : $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/TimeZone.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/TimeZone.php new file mode 100644 index 00000000..73373e04 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/TimeZone.php @@ -0,0 +1,144 @@ +<?php + +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Shared_TimeZone + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Shared_TimeZone +{ + /* + * Default Timezone used for date/time conversions + * + * @private + * @var string + */ + protected static $timezone = 'UTC'; + + /** + * Validate a Timezone name + * + * @param string $timezone Time zone (e.g. 'Europe/London') + * @return boolean Success or failure + */ + public static function _validateTimeZone($timezone) + { + if (in_array($timezone, DateTimeZone::listIdentifiers())) { + return true; + } + return false; + } + + /** + * Set the Default Timezone used for date/time conversions + * + * @param string $timezone Time zone (e.g. 'Europe/London') + * @return boolean Success or failure + */ + public static function setTimeZone($timezone) + { + if (self::_validateTimezone($timezone)) { + self::$timezone = $timezone; + return true; + } + return false; + } + + + /** + * Return the Default Timezone used for date/time conversions + * + * @return string Timezone (e.g. 'Europe/London') + */ + public static function getTimeZone() + { + return self::$timezone; + } + + + /** + * Return the Timezone transition for the specified timezone and timestamp + * + * @param DateTimeZone $objTimezone The timezone for finding the transitions + * @param integer $timestamp PHP date/time value for finding the current transition + * @return array The current transition details + */ + private static function getTimezoneTransitions($objTimezone, $timestamp) + { + $allTransitions = $objTimezone->getTransitions(); + $transitions = array(); + foreach ($allTransitions as $key => $transition) { + if ($transition['ts'] > $timestamp) { + $transitions[] = ($key > 0) ? $allTransitions[$key - 1] : $transition; + break; + } + if (empty($transitions)) { + $transitions[] = end($allTransitions); + } + } + + return $transitions; + } + + /** + * Return the Timezone offset used for date/time conversions to/from UST + * This requires both the timezone and the calculated date/time to allow for local DST + * + * @param string $timezone The timezone for finding the adjustment to UST + * @param integer $timestamp PHP date/time value + * @return integer Number of seconds for timezone adjustment + * @throws PHPExcel_Exception + */ + public static function getTimeZoneAdjustment($timezone, $timestamp) + { + if ($timezone !== null) { + if (!self::_validateTimezone($timezone)) { + throw new PHPExcel_Exception("Invalid timezone " . $timezone); + } + } else { + $timezone = self::$timezone; + } + + if ($timezone == 'UST') { + return 0; + } + + $objTimezone = new DateTimeZone($timezone); + if (version_compare(PHP_VERSION, '5.3.0') >= 0) { + $transitions = $objTimezone->getTransitions($timestamp, $timestamp); + } else { + $transitions = self::getTimezoneTransitions($objTimezone, $timestamp); + } + + return (count($transitions) > 0) ? $transitions[0]['offset'] : 0; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/XMLWriter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/XMLWriter.php new file mode 100644 index 00000000..1dc119b5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/XMLWriter.php @@ -0,0 +1,124 @@ +<?php + +if (!defined('DATE_W3C')) { + define('DATE_W3C', 'Y-m-d\TH:i:sP'); +} + +if (!defined('DEBUGMODE_ENABLED')) { + define('DEBUGMODE_ENABLED', false); +} + +/** + * PHPExcel_Shared_XMLWriter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_XMLWriter extends XMLWriter +{ + /** Temporary storage method */ + const STORAGE_MEMORY = 1; + const STORAGE_DISK = 2; + + /** + * Temporary filename + * + * @var string + */ + private $tempFileName = ''; + + /** + * Create a new PHPExcel_Shared_XMLWriter instance + * + * @param int $pTemporaryStorage Temporary storage location + * @param string $pTemporaryStorageFolder Temporary storage folder + */ + public function __construct($pTemporaryStorage = self::STORAGE_MEMORY, $pTemporaryStorageFolder = null) + { + // Open temporary storage + if ($pTemporaryStorage == self::STORAGE_MEMORY) { + $this->openMemory(); + } else { + // Create temporary filename + if ($pTemporaryStorageFolder === null) { + $pTemporaryStorageFolder = PHPExcel_Shared_File::sys_get_temp_dir(); + } + $this->tempFileName = @tempnam($pTemporaryStorageFolder, 'xml'); + + // Open storage + if ($this->openUri($this->tempFileName) === false) { + // Fallback to memory... + $this->openMemory(); + } + } + + // Set default values + if (DEBUGMODE_ENABLED) { + $this->setIndent(true); + } + } + + /** + * Destructor + */ + public function __destruct() + { + // Unlink temporary files + if ($this->tempFileName != '') { + @unlink($this->tempFileName); + } + } + + /** + * Get written data + * + * @return $data + */ + public function getData() + { + if ($this->tempFileName == '') { + return $this->outputMemory(true); + } else { + $this->flush(); + return file_get_contents($this->tempFileName); + } + } + + /** + * Fallback method for writeRaw, introduced in PHP 5.2 + * + * @param string $text + * @return string + */ + public function writeRawData($text) + { + if (is_array($text)) { + $text = implode("\n", $text); + } + + if (method_exists($this, 'writeRaw')) { + return $this->writeRaw(htmlspecialchars($text)); + } + + return $this->text($text); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipArchive.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipArchive.php new file mode 100644 index 00000000..9eac8cae --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipArchive.php @@ -0,0 +1,163 @@ +<?php + +if (!defined('PCLZIP_TEMPORARY_DIR')) { + define('PCLZIP_TEMPORARY_DIR', PHPExcel_Shared_File::sys_get_temp_dir() . DIRECTORY_SEPARATOR); +} +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/PCLZip/pclzip.lib.php'; + +/** + * PHPExcel_Shared_ZipArchive + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_ZipArchive + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_ZipArchive +{ + + /** constants */ + const OVERWRITE = 'OVERWRITE'; + const CREATE = 'CREATE'; + + + /** + * Temporary storage directory + * + * @var string + */ + private $tempDir; + + /** + * Zip Archive Stream Handle + * + * @var string + */ + private $zip; + + + /** + * Open a new zip archive + * + * @param string $fileName Filename for the zip archive + * @return boolean + */ + public function open($fileName) + { + $this->tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + $this->zip = new PclZip($fileName); + + return true; + } + + + /** + * Close this zip archive + * + */ + public function close() + { + } + + + /** + * Add a new file to the zip archive from a string of raw data. + * + * @param string $localname Directory/Name of the file to add to the zip archive + * @param string $contents String of data to add to the zip archive + */ + public function addFromString($localname, $contents) + { + $filenameParts = pathinfo($localname); + + $handle = fopen($this->tempDir.'/'.$filenameParts["basename"], "wb"); + fwrite($handle, $contents); + fclose($handle); + + $res = $this->zip->add($this->tempDir.'/'.$filenameParts["basename"], PCLZIP_OPT_REMOVE_PATH, $this->tempDir, PCLZIP_OPT_ADD_PATH, $filenameParts["dirname"]); + if ($res == 0) { + throw new PHPExcel_Writer_Exception("Error zipping files : " . $this->zip->errorInfo(true)); + } + + unlink($this->tempDir.'/'.$filenameParts["basename"]); + } + + /** + * Find if given fileName exist in archive (Emulate ZipArchive locateName()) + * + * @param string $fileName Filename for the file in zip archive + * @return boolean + */ + public function locateName($fileName) + { + $fileName = strtolower($fileName); + + $list = $this->zip->listContent(); + $listCount = count($list); + $index = -1; + for ($i = 0; $i < $listCount; ++$i) { + if (strtolower($list[$i]["filename"]) == $fileName || + strtolower($list[$i]["stored_filename"]) == $fileName) { + $index = $i; + break; + } + } + return ($index > -1) ? $index : false; + } + + /** + * Extract file from archive by given fileName (Emulate ZipArchive getFromName()) + * + * @param string $fileName Filename for the file in zip archive + * @return string $contents File string contents + */ + public function getFromName($fileName) + { + $index = $this->locateName($fileName); + + if ($index !== false) { + $extracted = $this->getFromIndex($index); + } else { + $fileName = substr($fileName, 1); + $index = $this->locateName($fileName); + if ($index === false) { + return false; + } + $extracted = $this->zip->getFromIndex($index); + } + + $contents = $extracted; + if ((is_array($extracted)) && ($extracted != 0)) { + $contents = $extracted[0]["content"]; + } + + return $contents; + } + + public function getFromIndex($index) { + $extracted = $this->zip->extractByIndex($index, PCLZIP_OPT_EXTRACT_AS_STRING); + $contents = ''; + if ((is_array($extracted)) && ($extracted != 0)) { + $contents = $extracted[0]["content"]; + } + + return $contents; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipStreamWrapper.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipStreamWrapper.php new file mode 100644 index 00000000..2e0324ce --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/ZipStreamWrapper.php @@ -0,0 +1,200 @@ +<?php + +/** + * PHPExcel_Shared_ZipStreamWrapper + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Shared_ZipStreamWrapper +{ + /** + * Internal ZipAcrhive + * + * @var ZipArchive + */ + private $archive; + + /** + * Filename in ZipAcrhive + * + * @var string + */ + private $fileNameInArchive = ''; + + /** + * Position in file + * + * @var int + */ + private $position = 0; + + /** + * Data + * + * @var mixed + */ + private $data = ''; + + /** + * Register wrapper + */ + public static function register() + { + @stream_wrapper_unregister('zip'); + @stream_wrapper_register('zip', __CLASS__); + } + + /** + * Implements support for fopen(). + * + * @param string $path resource name including scheme, e.g. + * @param string $mode only "r" is supported + * @param int $options mask of STREAM_REPORT_ERRORS and STREAM_USE_PATH + * @param string &$openedPath absolute path of the opened stream (out parameter) + * @return bool true on success + */ + public function stream_open($path, $mode, $options, &$opened_path) + { + // Check for mode + if ($mode{0} != 'r') { + throw new PHPExcel_Reader_Exception('Mode ' . $mode . ' is not supported. Only read mode is supported.'); + } + + $pos = strrpos($path, '#'); + $url['host'] = substr($path, 6, $pos - 6); // 6: strlen('zip://') + $url['fragment'] = substr($path, $pos + 1); + + // Open archive + $this->archive = new ZipArchive(); + $this->archive->open($url['host']); + + $this->fileNameInArchive = $url['fragment']; + $this->position = 0; + $this->data = $this->archive->getFromName($this->fileNameInArchive); + + return true; + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function statName() + { + return $this->fileNameInArchive; + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function url_stat() + { + return $this->statName($this->fileNameInArchive); + } + + /** + * Implements support for fstat(). + * + * @return boolean + */ + public function stream_stat() + { + return $this->archive->statName($this->fileNameInArchive); + } + + /** + * Implements support for fread(), fgets() etc. + * + * @param int $count maximum number of bytes to read + * @return string + */ + public function stream_read($count) + { + $ret = substr($this->data, $this->position, $count); + $this->position += strlen($ret); + return $ret; + } + + /** + * Returns the position of the file pointer, i.e. its offset into the file + * stream. Implements support for ftell(). + * + * @return int + */ + public function stream_tell() + { + return $this->position; + } + + /** + * EOF stream + * + * @return bool + */ + public function stream_eof() + { + return $this->position >= strlen($this->data); + } + + /** + * Seek stream + * + * @param int $offset byte offset + * @param int $whence SEEK_SET, SEEK_CUR or SEEK_END + * @return bool + */ + public function stream_seek($offset, $whence) + { + switch ($whence) { + case SEEK_SET: + if ($offset < strlen($this->data) && $offset >= 0) { + $this->position = $offset; + return true; + } else { + return false; + } + break; + case SEEK_CUR: + if ($offset >= 0) { + $this->position += $offset; + return true; + } else { + return false; + } + break; + case SEEK_END: + if (strlen($this->data) + $offset >= 0) { + $this->position = strlen($this->data) + $offset; + return true; + } else { + return false; + } + break; + default: + return false; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/bestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/bestFitClass.php new file mode 100644 index 00000000..2de029f9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/bestFitClass.php @@ -0,0 +1,425 @@ +<?php + +/** + * PHPExcel_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Best_Fit +{ + /** + * Indicator flag for a calculation error + * + * @var boolean + **/ + protected $error = false; + + /** + * Algorithm type to use for best-fit + * + * @var string + **/ + protected $bestFitType = 'undetermined'; + + /** + * Number of entries in the sets of x- and y-value arrays + * + * @var int + **/ + protected $valueCount = 0; + + /** + * X-value dataseries of values + * + * @var float[] + **/ + protected $xValues = array(); + + /** + * Y-value dataseries of values + * + * @var float[] + **/ + protected $yValues = array(); + + /** + * Flag indicating whether values should be adjusted to Y=0 + * + * @var boolean + **/ + protected $adjustToZero = false; + + /** + * Y-value series of best-fit values + * + * @var float[] + **/ + protected $yBestFitValues = array(); + + protected $goodnessOfFit = 1; + + protected $stdevOfResiduals = 0; + + protected $covariance = 0; + + protected $correlation = 0; + + protected $SSRegression = 0; + + protected $SSResiduals = 0; + + protected $DFResiduals = 0; + + protected $f = 0; + + protected $slope = 0; + + protected $slopeSE = 0; + + protected $intersect = 0; + + protected $intersectSE = 0; + + protected $xOffset = 0; + + protected $yOffset = 0; + + + public function getError() + { + return $this->error; + } + + + public function getBestFitType() + { + return $this->bestFitType; + } + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + */ + public function getValueOfYForX($xValue) + { + return false; + } + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + */ + public function getValueOfXForY($yValue) + { + return false; + } + + /** + * Return the original set of X-Values + * + * @return float[] X-Values + */ + public function getXValues() + { + return $this->xValues; + } + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getEquation($dp = 0) + { + return false; + } + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getSlope($dp = 0) + { + if ($dp != 0) { + return round($this->slope, $dp); + } + return $this->slope; + } + + /** + * Return the standard error of the Slope + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getSlopeSE($dp = 0) + { + if ($dp != 0) { + return round($this->slopeSE, $dp); + } + return $this->slopeSE; + } + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getIntersect($dp = 0) + { + if ($dp != 0) { + return round($this->intersect, $dp); + } + return $this->intersect; + } + + /** + * Return the standard error of the Intersect + * + * @param int $dp Number of places of decimal precision to display + * @return string + */ + public function getIntersectSE($dp = 0) + { + if ($dp != 0) { + return round($this->intersectSE, $dp); + } + return $this->intersectSE; + } + + /** + * Return the goodness of fit for this regression + * + * @param int $dp Number of places of decimal precision to return + * @return float + */ + public function getGoodnessOfFit($dp = 0) + { + if ($dp != 0) { + return round($this->goodnessOfFit, $dp); + } + return $this->goodnessOfFit; + } + + public function getGoodnessOfFitPercent($dp = 0) + { + if ($dp != 0) { + return round($this->goodnessOfFit * 100, $dp); + } + return $this->goodnessOfFit * 100; + } + + /** + * Return the standard deviation of the residuals for this regression + * + * @param int $dp Number of places of decimal precision to return + * @return float + */ + public function getStdevOfResiduals($dp = 0) + { + if ($dp != 0) { + return round($this->stdevOfResiduals, $dp); + } + return $this->stdevOfResiduals; + } + + public function getSSRegression($dp = 0) + { + if ($dp != 0) { + return round($this->SSRegression, $dp); + } + return $this->SSRegression; + } + + public function getSSResiduals($dp = 0) + { + if ($dp != 0) { + return round($this->SSResiduals, $dp); + } + return $this->SSResiduals; + } + + public function getDFResiduals($dp = 0) + { + if ($dp != 0) { + return round($this->DFResiduals, $dp); + } + return $this->DFResiduals; + } + + public function getF($dp = 0) + { + if ($dp != 0) { + return round($this->f, $dp); + } + return $this->f; + } + + public function getCovariance($dp = 0) + { + if ($dp != 0) { + return round($this->covariance, $dp); + } + return $this->covariance; + } + + public function getCorrelation($dp = 0) + { + if ($dp != 0) { + return round($this->correlation, $dp); + } + return $this->correlation; + } + + public function getYBestFitValues() + { + return $this->yBestFitValues; + } + + protected function calculateGoodnessOfFit($sumX, $sumY, $sumX2, $sumY2, $sumXY, $meanX, $meanY, $const) + { + $SSres = $SScov = $SScor = $SStot = $SSsex = 0.0; + foreach ($this->xValues as $xKey => $xValue) { + $bestFitY = $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); + + $SSres += ($this->yValues[$xKey] - $bestFitY) * ($this->yValues[$xKey] - $bestFitY); + if ($const) { + $SStot += ($this->yValues[$xKey] - $meanY) * ($this->yValues[$xKey] - $meanY); + } else { + $SStot += $this->yValues[$xKey] * $this->yValues[$xKey]; + } + $SScov += ($this->xValues[$xKey] - $meanX) * ($this->yValues[$xKey] - $meanY); + if ($const) { + $SSsex += ($this->xValues[$xKey] - $meanX) * ($this->xValues[$xKey] - $meanX); + } else { + $SSsex += $this->xValues[$xKey] * $this->xValues[$xKey]; + } + } + + $this->SSResiduals = $SSres; + $this->DFResiduals = $this->valueCount - 1 - $const; + + if ($this->DFResiduals == 0.0) { + $this->stdevOfResiduals = 0.0; + } else { + $this->stdevOfResiduals = sqrt($SSres / $this->DFResiduals); + } + if (($SStot == 0.0) || ($SSres == $SStot)) { + $this->goodnessOfFit = 1; + } else { + $this->goodnessOfFit = 1 - ($SSres / $SStot); + } + + $this->SSRegression = $this->goodnessOfFit * $SStot; + $this->covariance = $SScov / $this->valueCount; + $this->correlation = ($this->valueCount * $sumXY - $sumX * $sumY) / sqrt(($this->valueCount * $sumX2 - pow($sumX, 2)) * ($this->valueCount * $sumY2 - pow($sumY, 2))); + $this->slopeSE = $this->stdevOfResiduals / sqrt($SSsex); + $this->intersectSE = $this->stdevOfResiduals * sqrt(1 / ($this->valueCount - ($sumX * $sumX) / $sumX2)); + if ($this->SSResiduals != 0.0) { + if ($this->DFResiduals == 0.0) { + $this->f = 0.0; + } else { + $this->f = $this->SSRegression / ($this->SSResiduals / $this->DFResiduals); + } + } else { + if ($this->DFResiduals == 0.0) { + $this->f = 0.0; + } else { + $this->f = $this->SSRegression / $this->DFResiduals; + } + } + } + + protected function leastSquareFit($yValues, $xValues, $const) + { + // calculate sums + $x_sum = array_sum($xValues); + $y_sum = array_sum($yValues); + $meanX = $x_sum / $this->valueCount; + $meanY = $y_sum / $this->valueCount; + $mBase = $mDivisor = $xx_sum = $xy_sum = $yy_sum = 0.0; + for ($i = 0; $i < $this->valueCount; ++$i) { + $xy_sum += $xValues[$i] * $yValues[$i]; + $xx_sum += $xValues[$i] * $xValues[$i]; + $yy_sum += $yValues[$i] * $yValues[$i]; + + if ($const) { + $mBase += ($xValues[$i] - $meanX) * ($yValues[$i] - $meanY); + $mDivisor += ($xValues[$i] - $meanX) * ($xValues[$i] - $meanX); + } else { + $mBase += $xValues[$i] * $yValues[$i]; + $mDivisor += $xValues[$i] * $xValues[$i]; + } + } + + // calculate slope +// $this->slope = (($this->valueCount * $xy_sum) - ($x_sum * $y_sum)) / (($this->valueCount * $xx_sum) - ($x_sum * $x_sum)); + $this->slope = $mBase / $mDivisor; + + // calculate intersect +// $this->intersect = ($y_sum - ($this->slope * $x_sum)) / $this->valueCount; + if ($const) { + $this->intersect = $meanY - ($this->slope * $meanX); + } else { + $this->intersect = 0; + } + + $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum, $meanX, $meanY, $const); + } + + /** + * Define the regression + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($yValues, $xValues = array(), $const = true) + { + // Calculate number of points + $nY = count($yValues); + $nX = count($xValues); + + // Define X Values if necessary + if ($nX == 0) { + $xValues = range(1, $nY); + $nX = $nY; + } elseif ($nY != $nX) { + // Ensure both arrays of points are the same size + $this->error = true; + return false; + } + + $this->valueCount = $nY; + $this->xValues = $xValues; + $this->yValues = $yValues; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/exponentialBestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/exponentialBestFitClass.php new file mode 100644 index 00000000..44487352 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/exponentialBestFitClass.php @@ -0,0 +1,138 @@ +<?php + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + +/** + * PHPExcel_Exponential_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Exponential_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $bestFitType = 'exponential'; + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) + { + return $this->getIntersect() * pow($this->getSlope(), ($xValue - $this->xOffset)); + } + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) + { + return log(($yValue + $this->yOffset) / $this->getIntersect()) / log($this->getSlope()); + } + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp = 0) + { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = ' . $intersect . ' * ' . $slope . '^X'; + } + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getSlope($dp = 0) + { + if ($dp != 0) { + return round(exp($this->_slope), $dp); + } + return exp($this->_slope); + } + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getIntersect($dp = 0) + { + if ($dp != 0) { + return round(exp($this->intersect), $dp); + } + return exp($this->intersect); + } + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function exponentialRegression($yValues, $xValues, $const) + { + foreach ($yValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->leastSquareFit($yValues, $xValues, $const); + } + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($yValues, $xValues = array(), $const = true) + { + if (parent::__construct($yValues, $xValues) !== false) { + $this->exponentialRegression($yValues, $xValues, $const); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/linearBestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/linearBestFitClass.php new file mode 100644 index 00000000..76b55b3e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/linearBestFitClass.php @@ -0,0 +1,102 @@ +<?php + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + +/** + * PHPExcel_Linear_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Linear_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $bestFitType = 'linear'; + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) + { + return $this->getIntersect() + $this->getSlope() * $xValue; + } + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) + { + return ($yValue - $this->getIntersect()) / $this->getSlope(); + } + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp = 0) + { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = ' . $intersect . ' + ' . $slope . ' * X'; + } + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function linearRegression($yValues, $xValues, $const) + { + $this->leastSquareFit($yValues, $xValues, $const); + } + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($yValues, $xValues = array(), $const = true) + { + if (parent::__construct($yValues, $xValues) !== false) { + $this->linearRegression($yValues, $xValues, $const); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/logarithmicBestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/logarithmicBestFitClass.php new file mode 100644 index 00000000..221c5386 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/logarithmicBestFitClass.php @@ -0,0 +1,110 @@ +<?php + +require_once(PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'); + +/** + * PHPExcel_Logarithmic_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Logarithmic_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $bestFitType = 'logarithmic'; + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) + { + return $this->getIntersect() + $this->getSlope() * log($xValue - $this->xOffset); + } + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) + { + return exp(($yValue - $this->getIntersect()) / $this->getSlope()); + } + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp = 0) + { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = '.$intersect.' + '.$slope.' * log(X)'; + } + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function logarithmicRegression($yValues, $xValues, $const) + { + foreach ($xValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->leastSquareFit($yValues, $xValues, $const); + } + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($yValues, $xValues = array(), $const = true) + { + if (parent::__construct($yValues, $xValues) !== false) { + $this->logarithmicRegression($yValues, $xValues, $const); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/polynomialBestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/polynomialBestFitClass.php new file mode 100644 index 00000000..8a882b74 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/polynomialBestFitClass.php @@ -0,0 +1,222 @@ +<?php + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/JAMA/Matrix.php'; + +/** + * PHPExcel_Polynomial_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Polynomial_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $bestFitType = 'polynomial'; + + /** + * Polynomial order + * + * @protected + * @var int + **/ + protected $order = 0; + + + /** + * Return the order of this polynomial + * + * @return int + **/ + public function getOrder() + { + return $this->order; + } + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) + { + $retVal = $this->getIntersect(); + $slope = $this->getSlope(); + foreach ($slope as $key => $value) { + if ($value != 0.0) { + $retVal += $value * pow($xValue, $key + 1); + } + } + return $retVal; + } + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) + { + return ($yValue - $this->getIntersect()) / $this->getSlope(); + } + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp = 0) + { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + $equation = 'Y = ' . $intersect; + foreach ($slope as $key => $value) { + if ($value != 0.0) { + $equation .= ' + ' . $value . ' * X'; + if ($key > 0) { + $equation .= '^' . ($key + 1); + } + } + } + return $equation; + } + + + /** + * Return the Slope of the line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getSlope($dp = 0) + { + if ($dp != 0) { + $coefficients = array(); + foreach ($this->_slope as $coefficient) { + $coefficients[] = round($coefficient, $dp); + } + return $coefficients; + } + return $this->_slope; + } + + + public function getCoefficients($dp = 0) + { + return array_merge(array($this->getIntersect($dp)), $this->getSlope($dp)); + } + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param int $order Order of Polynomial for this regression + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function polynomialRegression($order, $yValues, $xValues, $const) + { + // calculate sums + $x_sum = array_sum($xValues); + $y_sum = array_sum($yValues); + $xx_sum = $xy_sum = 0; + for ($i = 0; $i < $this->valueCount; ++$i) { + $xy_sum += $xValues[$i] * $yValues[$i]; + $xx_sum += $xValues[$i] * $xValues[$i]; + $yy_sum += $yValues[$i] * $yValues[$i]; + } + /* + * This routine uses logic from the PHP port of polyfit version 0.1 + * written by Michael Bommarito and Paul Meagher + * + * The function fits a polynomial function of order $order through + * a series of x-y data points using least squares. + * + */ + for ($i = 0; $i < $this->valueCount; ++$i) { + for ($j = 0; $j <= $order; ++$j) { + $A[$i][$j] = pow($xValues[$i], $j); + } + } + for ($i=0; $i < $this->valueCount; ++$i) { + $B[$i] = array($yValues[$i]); + } + $matrixA = new Matrix($A); + $matrixB = new Matrix($B); + $C = $matrixA->solve($matrixB); + + $coefficients = array(); + for ($i = 0; $i < $C->m; ++$i) { + $r = $C->get($i, 0); + if (abs($r) <= pow(10, -9)) { + $r = 0; + } + $coefficients[] = $r; + } + + $this->intersect = array_shift($coefficients); + $this->_slope = $coefficients; + + $this->calculateGoodnessOfFit($x_sum, $y_sum, $xx_sum, $yy_sum, $xy_sum); + foreach ($this->xValues as $xKey => $xValue) { + $this->yBestFitValues[$xKey] = $this->getValueOfYForX($xValue); + } + } + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param int $order Order of Polynomial for this regression + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($order, $yValues, $xValues = array(), $const = true) + { + if (parent::__construct($yValues, $xValues) !== false) { + if ($order < $this->valueCount) { + $this->bestFitType .= '_'.$order; + $this->order = $order; + $this->polynomialRegression($order, $yValues, $xValues, $const); + if (($this->getGoodnessOfFit() < 0.0) || ($this->getGoodnessOfFit() > 1.0)) { + $this->_error = true; + } + } else { + $this->_error = true; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/powerBestFitClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/powerBestFitClass.php new file mode 100644 index 00000000..77c47342 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/powerBestFitClass.php @@ -0,0 +1,138 @@ +<?php + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/bestFitClass.php'; + +/** + * PHPExcel_Power_Best_Fit + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Power_Best_Fit extends PHPExcel_Best_Fit +{ + /** + * Algorithm type to use for best-fit + * (Name of this trend class) + * + * @var string + **/ + protected $bestFitType = 'power'; + + + /** + * Return the Y-Value for a specified value of X + * + * @param float $xValue X-Value + * @return float Y-Value + **/ + public function getValueOfYForX($xValue) + { + return $this->getIntersect() * pow(($xValue - $this->xOffset), $this->getSlope()); + } + + + /** + * Return the X-Value for a specified value of Y + * + * @param float $yValue Y-Value + * @return float X-Value + **/ + public function getValueOfXForY($yValue) + { + return pow((($yValue + $this->yOffset) / $this->getIntersect()), (1 / $this->getSlope())); + } + + + /** + * Return the Equation of the best-fit line + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getEquation($dp = 0) + { + $slope = $this->getSlope($dp); + $intersect = $this->getIntersect($dp); + + return 'Y = ' . $intersect . ' * X^' . $slope; + } + + + /** + * Return the Value of X where it intersects Y = 0 + * + * @param int $dp Number of places of decimal precision to display + * @return string + **/ + public function getIntersect($dp = 0) + { + if ($dp != 0) { + return round(exp($this->intersect), $dp); + } + return exp($this->intersect); + } + + + /** + * Execute the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + private function powerRegression($yValues, $xValues, $const) + { + foreach ($xValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + foreach ($yValues as &$value) { + if ($value < 0.0) { + $value = 0 - log(abs($value)); + } elseif ($value > 0.0) { + $value = log($value); + } + } + unset($value); + + $this->leastSquareFit($yValues, $xValues, $const); + } + + + /** + * Define the regression and calculate the goodness of fit for a set of X and Y data values + * + * @param float[] $yValues The set of Y-values for this regression + * @param float[] $xValues The set of X-values for this regression + * @param boolean $const + */ + public function __construct($yValues, $xValues = array(), $const = true) + { + if (parent::__construct($yValues, $xValues) !== false) { + $this->powerRegression($yValues, $xValues, $const); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/trendClass.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/trendClass.php new file mode 100644 index 00000000..715cd412 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Shared/trend/trendClass.php @@ -0,0 +1,147 @@ +<?php + +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/linearBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/logarithmicBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/exponentialBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/powerBestFitClass.php'; +require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/polynomialBestFitClass.php'; + +/** + * PHPExcel_trendClass + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Shared_Trend + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class trendClass +{ + const TREND_LINEAR = 'Linear'; + const TREND_LOGARITHMIC = 'Logarithmic'; + const TREND_EXPONENTIAL = 'Exponential'; + const TREND_POWER = 'Power'; + const TREND_POLYNOMIAL_2 = 'Polynomial_2'; + const TREND_POLYNOMIAL_3 = 'Polynomial_3'; + const TREND_POLYNOMIAL_4 = 'Polynomial_4'; + const TREND_POLYNOMIAL_5 = 'Polynomial_5'; + const TREND_POLYNOMIAL_6 = 'Polynomial_6'; + const TREND_BEST_FIT = 'Bestfit'; + const TREND_BEST_FIT_NO_POLY = 'Bestfit_no_Polynomials'; + + /** + * Names of the best-fit trend analysis methods + * + * @var string[] + **/ + private static $trendTypes = array( + self::TREND_LINEAR, + self::TREND_LOGARITHMIC, + self::TREND_EXPONENTIAL, + self::TREND_POWER + ); + + /** + * Names of the best-fit trend polynomial orders + * + * @var string[] + **/ + private static $trendTypePolynomialOrders = array( + self::TREND_POLYNOMIAL_2, + self::TREND_POLYNOMIAL_3, + self::TREND_POLYNOMIAL_4, + self::TREND_POLYNOMIAL_5, + self::TREND_POLYNOMIAL_6 + ); + + /** + * Cached results for each method when trying to identify which provides the best fit + * + * @var PHPExcel_Best_Fit[] + **/ + private static $trendCache = array(); + + + public static function calculate($trendType = self::TREND_BEST_FIT, $yValues, $xValues = array(), $const = true) + { + // Calculate number of points in each dataset + $nY = count($yValues); + $nX = count($xValues); + + // Define X Values if necessary + if ($nX == 0) { + $xValues = range(1, $nY); + $nX = $nY; + } elseif ($nY != $nX) { + // Ensure both arrays of points are the same size + trigger_error("trend(): Number of elements in coordinate arrays do not match.", E_USER_ERROR); + } + + $key = md5($trendType.$const.serialize($yValues).serialize($xValues)); + // Determine which trend method has been requested + switch ($trendType) { + // Instantiate and return the class for the requested trend method + case self::TREND_LINEAR: + case self::TREND_LOGARITHMIC: + case self::TREND_EXPONENTIAL: + case self::TREND_POWER: + if (!isset(self::$trendCache[$key])) { + $className = 'PHPExcel_'.$trendType.'_Best_Fit'; + self::$trendCache[$key] = new $className($yValues, $xValues, $const); + } + return self::$trendCache[$key]; + case self::TREND_POLYNOMIAL_2: + case self::TREND_POLYNOMIAL_3: + case self::TREND_POLYNOMIAL_4: + case self::TREND_POLYNOMIAL_5: + case self::TREND_POLYNOMIAL_6: + if (!isset(self::$trendCache[$key])) { + $order = substr($trendType, -1); + self::$trendCache[$key] = new PHPExcel_Polynomial_Best_Fit($order, $yValues, $xValues, $const); + } + return self::$trendCache[$key]; + case self::TREND_BEST_FIT: + case self::TREND_BEST_FIT_NO_POLY: + // If the request is to determine the best fit regression, then we test each trend line in turn + // Start by generating an instance of each available trend method + foreach (self::$trendTypes as $trendMethod) { + $className = 'PHPExcel_'.$trendMethod.'BestFit'; + $bestFit[$trendMethod] = new $className($yValues, $xValues, $const); + $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); + } + if ($trendType != self::TREND_BEST_FIT_NO_POLY) { + foreach (self::$trendTypePolynomialOrders as $trendMethod) { + $order = substr($trendMethod, -1); + $bestFit[$trendMethod] = new PHPExcel_Polynomial_Best_Fit($order, $yValues, $xValues, $const); + if ($bestFit[$trendMethod]->getError()) { + unset($bestFit[$trendMethod]); + } else { + $bestFitValue[$trendMethod] = $bestFit[$trendMethod]->getGoodnessOfFit(); + } + } + } + // Determine which of our trend lines is the best fit, and then we return the instance of that trend class + arsort($bestFitValue); + $bestFitType = key($bestFitValue); + return $bestFit[$bestFitType]; + default: + return false; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style.php new file mode 100644 index 00000000..6b952ef9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style.php @@ -0,0 +1,644 @@ +<?php + +/** + * PHPExcel_Style + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /** + * Font + * + * @var PHPExcel_Style_Font + */ + protected $font; + + /** + * Fill + * + * @var PHPExcel_Style_Fill + */ + protected $fill; + + /** + * Borders + * + * @var PHPExcel_Style_Borders + */ + protected $borders; + + /** + * Alignment + * + * @var PHPExcel_Style_Alignment + */ + protected $alignment; + + /** + * Number Format + * + * @var PHPExcel_Style_NumberFormat + */ + protected $numberFormat; + + /** + * Conditional styles + * + * @var PHPExcel_Style_Conditional[] + */ + protected $conditionalStyles; + + /** + * Protection + * + * @var PHPExcel_Style_Protection + */ + protected $protection; + + /** + * Index of style in collection. Only used for real style. + * + * @var int + */ + protected $index; + + /** + * Use Quote Prefix when displaying in cell editor. Only used for real style. + * + * @var boolean + */ + protected $quotePrefix = false; + + /** + * Create a new PHPExcel_Style + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + $this->isSupervisor = $isSupervisor; + + // Initialise values + $this->conditionalStyles = array(); + $this->font = new PHPExcel_Style_Font($isSupervisor, $isConditional); + $this->fill = new PHPExcel_Style_Fill($isSupervisor, $isConditional); + $this->borders = new PHPExcel_Style_Borders($isSupervisor, $isConditional); + $this->alignment = new PHPExcel_Style_Alignment($isSupervisor, $isConditional); + $this->numberFormat = new PHPExcel_Style_NumberFormat($isSupervisor, $isConditional); + $this->protection = new PHPExcel_Style_Protection($isSupervisor, $isConditional); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->font->bindParent($this); + $this->fill->bindParent($this); + $this->borders->bindParent($this); + $this->alignment->bindParent($this); + $this->numberFormat->bindParent($this); + $this->protection->bindParent($this); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style + */ + public function getSharedComponent() + { + $activeSheet = $this->getActiveSheet(); + $selectedCell = $this->getActiveCell(); // e.g. 'A1' + + if ($activeSheet->cellExists($selectedCell)) { + $xfIndex = $activeSheet->getCell($selectedCell)->getXfIndex(); + } else { + $xfIndex = 0; + } + + return $this->parent->getCellXfByIndex($xfIndex); + } + + /** + * Get parent. Only used for style supervisor + * + * @return PHPExcel + */ + public function getParent() + { + return $this->parent; + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('quotePrefix' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->applyFromArray( + * array( + * 'font' => array( + * 'name' => 'Arial', + * 'bold' => true, + * 'italic' => false, + * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE, + * 'strike' => false, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'borders' => array( + * 'bottom' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'top' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ), + * 'quotePrefix' => true + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @param boolean $pAdvanced Advanced mode for setting borders. + * @throws PHPExcel_Exception + * @return PHPExcel_Style + */ + public function applyFromArray($pStyles = null, $pAdvanced = true) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $pRange = $this->getSelectedCells(); + + // Uppercase coordinate + $pRange = strtoupper($pRange); + + // Is it a cell range or a single cell? + if (strpos($pRange, ':') === false) { + $rangeA = $pRange; + $rangeB = $pRange; + } else { + list($rangeA, $rangeB) = explode(':', $pRange); + } + + // Calculate range outer borders + $rangeStart = PHPExcel_Cell::coordinateFromString($rangeA); + $rangeEnd = PHPExcel_Cell::coordinateFromString($rangeB); + + // Translate column into index + $rangeStart[0] = PHPExcel_Cell::columnIndexFromString($rangeStart[0]) - 1; + $rangeEnd[0] = PHPExcel_Cell::columnIndexFromString($rangeEnd[0]) - 1; + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // ADVANCED MODE: + if ($pAdvanced && isset($pStyles['borders'])) { + // 'allborders' is a shorthand property for 'outline' and 'inside' and + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['allborders'])) { + foreach (array('outline', 'inside') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['allborders']; + } + } + unset($pStyles['borders']['allborders']); // not needed any more + } + // 'outline' is a shorthand property for 'top', 'right', 'bottom', 'left' + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['outline'])) { + foreach (array('top', 'right', 'bottom', 'left') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['outline']; + } + } + unset($pStyles['borders']['outline']); // not needed any more + } + // 'inside' is a shorthand property for 'vertical' and 'horizontal' + // it applies to components that have not been set explicitly + if (isset($pStyles['borders']['inside'])) { + foreach (array('vertical', 'horizontal') as $component) { + if (!isset($pStyles['borders'][$component])) { + $pStyles['borders'][$component] = $pStyles['borders']['inside']; + } + } + unset($pStyles['borders']['inside']); // not needed any more + } + // width and height characteristics of selection, 1, 2, or 3 (for 3 or more) + $xMax = min($rangeEnd[0] - $rangeStart[0] + 1, 3); + $yMax = min($rangeEnd[1] - $rangeStart[1] + 1, 3); + + // loop through up to 3 x 3 = 9 regions + for ($x = 1; $x <= $xMax; ++$x) { + // start column index for region + $colStart = ($x == 3) ? + PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0]) + : PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $x - 1); + // end column index for region + $colEnd = ($x == 1) ? + PHPExcel_Cell::stringFromColumnIndex($rangeStart[0]) + : PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] - $xMax + $x); + + for ($y = 1; $y <= $yMax; ++$y) { + // which edges are touching the region + $edges = array(); + if ($x == 1) { + // are we at left edge + $edges[] = 'left'; + } + if ($x == $xMax) { + // are we at right edge + $edges[] = 'right'; + } + if ($y == 1) { + // are we at top edge? + $edges[] = 'top'; + } + if ($y == $yMax) { + // are we at bottom edge? + $edges[] = 'bottom'; + } + + // start row index for region + $rowStart = ($y == 3) ? + $rangeEnd[1] : $rangeStart[1] + $y - 1; + + // end row index for region + $rowEnd = ($y == 1) ? + $rangeStart[1] : $rangeEnd[1] - $yMax + $y; + + // build range for region + $range = $colStart . $rowStart . ':' . $colEnd . $rowEnd; + + // retrieve relevant style array for region + $regionStyles = $pStyles; + unset($regionStyles['borders']['inside']); + + // what are the inner edges of the region when looking at the selection + $innerEdges = array_diff(array('top', 'right', 'bottom', 'left'), $edges); + + // inner edges that are not touching the region should take the 'inside' border properties if they have been set + foreach ($innerEdges as $innerEdge) { + switch ($innerEdge) { + case 'top': + case 'bottom': + // should pick up 'horizontal' border property if set + if (isset($pStyles['borders']['horizontal'])) { + $regionStyles['borders'][$innerEdge] = $pStyles['borders']['horizontal']; + } else { + unset($regionStyles['borders'][$innerEdge]); + } + break; + case 'left': + case 'right': + // should pick up 'vertical' border property if set + if (isset($pStyles['borders']['vertical'])) { + $regionStyles['borders'][$innerEdge] = $pStyles['borders']['vertical']; + } else { + unset($regionStyles['borders'][$innerEdge]); + } + break; + } + } + + // apply region style to region by calling applyFromArray() in simple mode + $this->getActiveSheet()->getStyle($range)->applyFromArray($regionStyles, false); + } + } + return $this; + } + + // SIMPLE MODE: + // Selection type, inspect + if (preg_match('/^[A-Z]+1:[A-Z]+1048576$/', $pRange)) { + $selectionType = 'COLUMN'; + } elseif (preg_match('/^A[0-9]+:XFD[0-9]+$/', $pRange)) { + $selectionType = 'ROW'; + } else { + $selectionType = 'CELL'; + } + + // First loop through columns, rows, or cells to find out which styles are affected by this operation + switch ($selectionType) { + case 'COLUMN': + $oldXfIndexes = array(); + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $oldXfIndexes[$this->getActiveSheet()->getColumnDimensionByColumn($col)->getXfIndex()] = true; + } + break; + case 'ROW': + $oldXfIndexes = array(); + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + if ($this->getActiveSheet()->getRowDimension($row)->getXfIndex() == null) { + $oldXfIndexes[0] = true; // row without explicit style should be formatted based on default style + } else { + $oldXfIndexes[$this->getActiveSheet()->getRowDimension($row)->getXfIndex()] = true; + } + } + break; + case 'CELL': + $oldXfIndexes = array(); + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $oldXfIndexes[$this->getActiveSheet()->getCellByColumnAndRow($col, $row)->getXfIndex()] = true; + } + } + break; + } + + // clone each of the affected styles, apply the style array, and add the new styles to the workbook + $workbook = $this->getActiveSheet()->getParent(); + foreach ($oldXfIndexes as $oldXfIndex => $dummy) { + $style = $workbook->getCellXfByIndex($oldXfIndex); + $newStyle = clone $style; + $newStyle->applyFromArray($pStyles); + + if ($existingStyle = $workbook->getCellXfByHashCode($newStyle->getHashCode())) { + // there is already such cell Xf in our collection + $newXfIndexes[$oldXfIndex] = $existingStyle->getIndex(); + } else { + // we don't have such a cell Xf, need to add + $workbook->addCellXf($newStyle); + $newXfIndexes[$oldXfIndex] = $newStyle->getIndex(); + } + } + + // Loop through columns, rows, or cells again and update the XF index + switch ($selectionType) { + case 'COLUMN': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + $columnDimension = $this->getActiveSheet()->getColumnDimensionByColumn($col); + $oldXfIndex = $columnDimension->getXfIndex(); + $columnDimension->setXfIndex($newXfIndexes[$oldXfIndex]); + } + break; + + case 'ROW': + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $rowDimension = $this->getActiveSheet()->getRowDimension($row); + $oldXfIndex = $rowDimension->getXfIndex() === null ? + 0 : $rowDimension->getXfIndex(); // row without explicit style should be formatted based on default style + $rowDimension->setXfIndex($newXfIndexes[$oldXfIndex]); + } + break; + + case 'CELL': + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $cell = $this->getActiveSheet()->getCellByColumnAndRow($col, $row); + $oldXfIndex = $cell->getXfIndex(); + $cell->setXfIndex($newXfIndexes[$oldXfIndex]); + } + } + break; + } + + } else { + // not a supervisor, just apply the style array directly on style object + if (array_key_exists('fill', $pStyles)) { + $this->getFill()->applyFromArray($pStyles['fill']); + } + if (array_key_exists('font', $pStyles)) { + $this->getFont()->applyFromArray($pStyles['font']); + } + if (array_key_exists('borders', $pStyles)) { + $this->getBorders()->applyFromArray($pStyles['borders']); + } + if (array_key_exists('alignment', $pStyles)) { + $this->getAlignment()->applyFromArray($pStyles['alignment']); + } + if (array_key_exists('numberformat', $pStyles)) { + $this->getNumberFormat()->applyFromArray($pStyles['numberformat']); + } + if (array_key_exists('protection', $pStyles)) { + $this->getProtection()->applyFromArray($pStyles['protection']); + } + if (array_key_exists('quotePrefix', $pStyles)) { + $this->quotePrefix = $pStyles['quotePrefix']; + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Fill + * + * @return PHPExcel_Style_Fill + */ + public function getFill() + { + return $this->fill; + } + + /** + * Get Font + * + * @return PHPExcel_Style_Font + */ + public function getFont() + { + return $this->font; + } + + /** + * Set font + * + * @param PHPExcel_Style_Font $font + * @return PHPExcel_Style + */ + public function setFont(PHPExcel_Style_Font $font) + { + $this->font = $font; + return $this; + } + + /** + * Get Borders + * + * @return PHPExcel_Style_Borders + */ + public function getBorders() + { + return $this->borders; + } + + /** + * Get Alignment + * + * @return PHPExcel_Style_Alignment + */ + public function getAlignment() + { + return $this->alignment; + } + + /** + * Get Number Format + * + * @return PHPExcel_Style_NumberFormat + */ + public function getNumberFormat() + { + return $this->numberFormat; + } + + /** + * Get Conditional Styles. Only used on supervisor. + * + * @return PHPExcel_Style_Conditional[] + */ + public function getConditionalStyles() + { + return $this->getActiveSheet()->getConditionalStyles($this->getActiveCell()); + } + + /** + * Set Conditional Styles. Only used on supervisor. + * + * @param PHPExcel_Style_Conditional[] $pValue Array of condtional styles + * @return PHPExcel_Style + */ + public function setConditionalStyles($pValue = null) + { + if (is_array($pValue)) { + $this->getActiveSheet()->setConditionalStyles($this->getSelectedCells(), $pValue); + } + return $this; + } + + /** + * Get Protection + * + * @return PHPExcel_Style_Protection + */ + public function getProtection() + { + return $this->protection; + } + + /** + * Get quote prefix + * + * @return boolean + */ + public function getQuotePrefix() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getQuotePrefix(); + } + return $this->quotePrefix; + } + + /** + * Set quote prefix + * + * @param boolean $pValue + */ + public function setQuotePrefix($pValue) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = array('quotePrefix' => $pValue); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->quotePrefix = (boolean) $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + $hashConditionals = ''; + foreach ($this->conditionalStyles as $conditional) { + $hashConditionals .= $conditional->getHashCode(); + } + + return md5( + $this->fill->getHashCode() . + $this->font->getHashCode() . + $this->borders->getHashCode() . + $this->alignment->getHashCode() . + $this->numberFormat->getHashCode() . + $hashConditionals . + $this->protection->getHashCode() . + ($this->quotePrefix ? 't' : 'f') . + __CLASS__ + ); + } + + /** + * Get own index in style collection + * + * @return int + */ + public function getIndex() + { + return $this->index; + } + + /** + * Set own index in style collection + * + * @param int $pValue + */ + public function setIndex($pValue) + { + $this->index = $pValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Alignment.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Alignment.php new file mode 100644 index 00000000..bfc49477 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Alignment.php @@ -0,0 +1,464 @@ +<?php +/** + * PHPExcel_Style_Alignment + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Alignment extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Horizontal alignment styles */ + const HORIZONTAL_GENERAL = 'general'; + const HORIZONTAL_LEFT = 'left'; + const HORIZONTAL_RIGHT = 'right'; + const HORIZONTAL_CENTER = 'center'; + const HORIZONTAL_CENTER_CONTINUOUS = 'centerContinuous'; + const HORIZONTAL_JUSTIFY = 'justify'; + const HORIZONTAL_FILL = 'fill'; + const HORIZONTAL_DISTRIBUTED = 'distributed'; // Excel2007 only + + /* Vertical alignment styles */ + const VERTICAL_BOTTOM = 'bottom'; + const VERTICAL_TOP = 'top'; + const VERTICAL_CENTER = 'center'; + const VERTICAL_JUSTIFY = 'justify'; + const VERTICAL_DISTRIBUTED = 'distributed'; // Excel2007 only + + /* Read order */ + const READORDER_CONTEXT = 0; + const READORDER_LTR = 1; + const READORDER_RTL = 2; + + /** + * Horizontal alignment + * + * @var string + */ + protected $horizontal = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + + /** + * Vertical alignment + * + * @var string + */ + protected $vertical = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + + /** + * Text rotation + * + * @var integer + */ + protected $textRotation = 0; + + /** + * Wrap text + * + * @var boolean + */ + protected $wrapText = false; + + /** + * Shrink to fit + * + * @var boolean + */ + protected $shrinkToFit = false; + + /** + * Indent - only possible with horizontal alignment left and right + * + * @var integer + */ + protected $indent = 0; + + /** + * Read order + * + * @var integer + */ + protected $readorder = 0; + + /** + * Create a new PHPExcel_Style_Alignment + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + if ($isConditional) { + $this->horizontal = null; + $this->vertical = null; + $this->textRotation = null; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Alignment + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getAlignment(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('alignment' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getAlignment()->applyFromArray( + * array( + * 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER, + * 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER, + * 'rotation' => 0, + * 'wrap' => TRUE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Alignment + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells()) + ->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['horizontal'])) { + $this->setHorizontal($pStyles['horizontal']); + } + if (isset($pStyles['vertical'])) { + $this->setVertical($pStyles['vertical']); + } + if (isset($pStyles['rotation'])) { + $this->setTextRotation($pStyles['rotation']); + } + if (isset($pStyles['wrap'])) { + $this->setWrapText($pStyles['wrap']); + } + if (isset($pStyles['shrinkToFit'])) { + $this->setShrinkToFit($pStyles['shrinkToFit']); + } + if (isset($pStyles['indent'])) { + $this->setIndent($pStyles['indent']); + } + if (isset($pStyles['readorder'])) { + $this->setReadorder($pStyles['readorder']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Horizontal + * + * @return string + */ + public function getHorizontal() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHorizontal(); + } + return $this->horizontal; + } + + /** + * Set Horizontal + * + * @param string $pValue + * @return PHPExcel_Style_Alignment + */ + public function setHorizontal($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL; + } + + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('horizontal' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->horizontal = $pValue; + } + return $this; + } + + /** + * Get Vertical + * + * @return string + */ + public function getVertical() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getVertical(); + } + return $this->vertical; + } + + /** + * Set Vertical + * + * @param string $pValue + * @return PHPExcel_Style_Alignment + */ + public function setVertical($pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM; + } + + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('vertical' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->vertical = $pValue; + } + return $this; + } + + /** + * Get TextRotation + * + * @return int + */ + public function getTextRotation() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getTextRotation(); + } + return $this->textRotation; + } + + /** + * Set TextRotation + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Alignment + */ + public function setTextRotation($pValue = 0) + { + // Excel2007 value 255 => PHPExcel value -165 + if ($pValue == 255) { + $pValue = -165; + } + + // Set rotation + if (($pValue >= -90 && $pValue <= 90) || $pValue == -165) { + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->textRotation = $pValue; + } + } else { + throw new PHPExcel_Exception("Text rotation should be a value between -90 and 90."); + } + + return $this; + } + + /** + * Get Wrap Text + * + * @return boolean + */ + public function getWrapText() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getWrapText(); + } + return $this->wrapText; + } + + /** + * Set Wrap Text + * + * @param boolean $pValue + * @return PHPExcel_Style_Alignment + */ + public function setWrapText($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('wrap' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->wrapText = $pValue; + } + return $this; + } + + /** + * Get Shrink to fit + * + * @return boolean + */ + public function getShrinkToFit() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getShrinkToFit(); + } + return $this->shrinkToFit; + } + + /** + * Set Shrink to fit + * + * @param boolean $pValue + * @return PHPExcel_Style_Alignment + */ + public function setShrinkToFit($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('shrinkToFit' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->shrinkToFit = $pValue; + } + return $this; + } + + /** + * Get indent + * + * @return int + */ + public function getIndent() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getIndent(); + } + return $this->indent; + } + + /** + * Set indent + * + * @param int $pValue + * @return PHPExcel_Style_Alignment + */ + public function setIndent($pValue = 0) + { + if ($pValue > 0) { + if ($this->getHorizontal() != self::HORIZONTAL_GENERAL && + $this->getHorizontal() != self::HORIZONTAL_LEFT && + $this->getHorizontal() != self::HORIZONTAL_RIGHT) { + $pValue = 0; // indent not supported + } + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('indent' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->indent = $pValue; + } + return $this; + } + + /** + * Get read order + * + * @return integer + */ + public function getReadorder() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getReadorder(); + } + return $this->readorder; + } + + /** + * Set read order + * + * @param int $pValue + * @return PHPExcel_Style_Alignment + */ + public function setReadorder($pValue = 0) + { + if ($pValue < 0 || $pValue > 2) { + $pValue = 0; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('readorder' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->readorder = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->horizontal . + $this->vertical . + $this->textRotation . + ($this->wrapText ? 't' : 'f') . + ($this->shrinkToFit ? 't' : 'f') . + $this->indent . + $this->readorder . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Border.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Border.php new file mode 100644 index 00000000..55efc501 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Border.php @@ -0,0 +1,282 @@ +<?php + +/** + * PHPExcel_Style_Border + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Border extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Border style */ + const BORDER_NONE = 'none'; + const BORDER_DASHDOT = 'dashDot'; + const BORDER_DASHDOTDOT = 'dashDotDot'; + const BORDER_DASHED = 'dashed'; + const BORDER_DOTTED = 'dotted'; + const BORDER_DOUBLE = 'double'; + const BORDER_HAIR = 'hair'; + const BORDER_MEDIUM = 'medium'; + const BORDER_MEDIUMDASHDOT = 'mediumDashDot'; + const BORDER_MEDIUMDASHDOTDOT = 'mediumDashDotDot'; + const BORDER_MEDIUMDASHED = 'mediumDashed'; + const BORDER_SLANTDASHDOT = 'slantDashDot'; + const BORDER_THICK = 'thick'; + const BORDER_THIN = 'thin'; + + /** + * Border style + * + * @var string + */ + protected $borderStyle = PHPExcel_Style_Border::BORDER_NONE; + + /** + * Border color + * + * @var PHPExcel_Style_Color + */ + protected $color; + + /** + * Parent property name + * + * @var string + */ + protected $parentPropertyName; + + /** + * Create a new PHPExcel_Style_Border + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->color->bindParent($this, 'color'); + } + } + + /** + * Bind parent. Only used for supervisor + * + * @param PHPExcel_Style_Borders $parent + * @param string $parentPropertyName + * @return PHPExcel_Style_Border + */ + public function bindParent($parent, $parentPropertyName = null) + { + $this->parent = $parent; + $this->parentPropertyName = $parentPropertyName; + return $this; + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getSharedComponent() + { + switch ($this->parentPropertyName) { + case 'allBorders': + case 'horizontal': + case 'inside': + case 'outline': + case 'vertical': + throw new PHPExcel_Exception('Cannot get shared component for a pseudo-border.'); + break; + case 'bottom': + return $this->parent->getSharedComponent()->getBottom(); + case 'diagonal': + return $this->parent->getSharedComponent()->getDiagonal(); + case 'left': + return $this->parent->getSharedComponent()->getLeft(); + case 'right': + return $this->parent->getSharedComponent()->getRight(); + case 'top': + return $this->parent->getSharedComponent()->getTop(); + } + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + switch ($this->parentPropertyName) { + case 'allBorders': + case 'bottom': + case 'diagonal': + case 'horizontal': + case 'inside': + case 'left': + case 'outline': + case 'right': + case 'top': + case 'vertical': + $key = strtolower('vertical'); + break; + } + return $this->parent->getStyleArray(array($key => $array)); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->getTop()->applyFromArray( + * array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Border + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['style'])) { + $this->setBorderStyle($pStyles['style']); + } + if (isset($pStyles['color'])) { + $this->getColor()->applyFromArray($pStyles['color']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Border style + * + * @return string + */ + public function getBorderStyle() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getBorderStyle(); + } + return $this->borderStyle; + } + + /** + * Set Border style + * + * @param string|boolean $pValue + * When passing a boolean, FALSE equates PHPExcel_Style_Border::BORDER_NONE + * and TRUE to PHPExcel_Style_Border::BORDER_MEDIUM + * @return PHPExcel_Style_Border + */ + public function setBorderStyle($pValue = PHPExcel_Style_Border::BORDER_NONE) + { + + if (empty($pValue)) { + $pValue = PHPExcel_Style_Border::BORDER_NONE; + } elseif (is_bool($pValue) && $pValue) { + $pValue = PHPExcel_Style_Border::BORDER_MEDIUM; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('style' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->borderStyle = $pValue; + } + return $this; + } + + /** + * Get Border Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() + { + return $this->color; + } + + /** + * Set Border Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Border + */ + public function setColor(PHPExcel_Style_Color $pValue = null) + { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->isSupervisor) { + $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->color = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->borderStyle . + $this->color->getHashCode() . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Borders.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Borders.php new file mode 100644 index 00000000..27c40a48 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Borders.php @@ -0,0 +1,429 @@ +<?php + +/** + * PHPExcel_Style_Borders + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Borders extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Diagonal directions */ + const DIAGONAL_NONE = 0; + const DIAGONAL_UP = 1; + const DIAGONAL_DOWN = 2; + const DIAGONAL_BOTH = 3; + + /** + * Left + * + * @var PHPExcel_Style_Border + */ + protected $left; + + /** + * Right + * + * @var PHPExcel_Style_Border + */ + protected $right; + + /** + * Top + * + * @var PHPExcel_Style_Border + */ + protected $top; + + /** + * Bottom + * + * @var PHPExcel_Style_Border + */ + protected $bottom; + + /** + * Diagonal + * + * @var PHPExcel_Style_Border + */ + protected $diagonal; + + /** + * DiagonalDirection + * + * @var int + */ + protected $diagonalDirection; + + /** + * All borders psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $allBorders; + + /** + * Outline psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $outline; + + /** + * Inside psedo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $inside; + + /** + * Vertical pseudo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $vertical; + + /** + * Horizontal pseudo-border. Only applies to supervisor. + * + * @var PHPExcel_Style_Border + */ + protected $horizontal; + + /** + * Create a new PHPExcel_Style_Borders + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + $this->left = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->right = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->top = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->bottom = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->diagonal = new PHPExcel_Style_Border($isSupervisor, $isConditional); + $this->diagonalDirection = PHPExcel_Style_Borders::DIAGONAL_NONE; + + // Specially for supervisor + if ($isSupervisor) { + // Initialize pseudo-borders + $this->allBorders = new PHPExcel_Style_Border(true); + $this->outline = new PHPExcel_Style_Border(true); + $this->inside = new PHPExcel_Style_Border(true); + $this->vertical = new PHPExcel_Style_Border(true); + $this->horizontal = new PHPExcel_Style_Border(true); + + // bind parent if we are a supervisor + $this->left->bindParent($this, 'left'); + $this->right->bindParent($this, 'right'); + $this->top->bindParent($this, 'top'); + $this->bottom->bindParent($this, 'bottom'); + $this->diagonal->bindParent($this, 'diagonal'); + $this->allBorders->bindParent($this, 'allBorders'); + $this->outline->bindParent($this, 'outline'); + $this->inside->bindParent($this, 'inside'); + $this->vertical->bindParent($this, 'vertical'); + $this->horizontal->bindParent($this, 'horizontal'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Borders + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getBorders(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('borders' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( + * array( + * 'bottom' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ), + * 'top' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ) + * ); + * </code> + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getBorders()->applyFromArray( + * array( + * 'allborders' => array( + * 'style' => PHPExcel_Style_Border::BORDER_DASHDOT, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Borders + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('left', $pStyles)) { + $this->getLeft()->applyFromArray($pStyles['left']); + } + if (array_key_exists('right', $pStyles)) { + $this->getRight()->applyFromArray($pStyles['right']); + } + if (array_key_exists('top', $pStyles)) { + $this->getTop()->applyFromArray($pStyles['top']); + } + if (array_key_exists('bottom', $pStyles)) { + $this->getBottom()->applyFromArray($pStyles['bottom']); + } + if (array_key_exists('diagonal', $pStyles)) { + $this->getDiagonal()->applyFromArray($pStyles['diagonal']); + } + if (array_key_exists('diagonaldirection', $pStyles)) { + $this->setDiagonalDirection($pStyles['diagonaldirection']); + } + if (array_key_exists('allborders', $pStyles)) { + $this->getLeft()->applyFromArray($pStyles['allborders']); + $this->getRight()->applyFromArray($pStyles['allborders']); + $this->getTop()->applyFromArray($pStyles['allborders']); + $this->getBottom()->applyFromArray($pStyles['allborders']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Left + * + * @return PHPExcel_Style_Border + */ + public function getLeft() + { + return $this->left; + } + + /** + * Get Right + * + * @return PHPExcel_Style_Border + */ + public function getRight() + { + return $this->right; + } + + /** + * Get Top + * + * @return PHPExcel_Style_Border + */ + public function getTop() + { + return $this->top; + } + + /** + * Get Bottom + * + * @return PHPExcel_Style_Border + */ + public function getBottom() + { + return $this->bottom; + } + + /** + * Get Diagonal + * + * @return PHPExcel_Style_Border + */ + public function getDiagonal() + { + return $this->diagonal; + } + + /** + * Get AllBorders (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getAllBorders() + { + if (!$this->isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->allBorders; + } + + /** + * Get Outline (pseudo-border). Only applies to supervisor. + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function getOutline() + { + if (!$this->isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->outline; + } + + /** + * Get Inside (pseudo-border). Only applies to supervisor. + * + * @return boolean + * @throws PHPExcel_Exception + */ + public function getInside() + { + if (!$this->isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->inside; + } + + /** + * Get Vertical (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getVertical() + { + if (!$this->isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->vertical; + } + + /** + * Get Horizontal (pseudo-border). Only applies to supervisor. + * + * @return PHPExcel_Style_Border + * @throws PHPExcel_Exception + */ + public function getHorizontal() + { + if (!$this->isSupervisor) { + throw new PHPExcel_Exception('Can only get pseudo-border for supervisor.'); + } + return $this->horizontal; + } + + /** + * Get DiagonalDirection + * + * @return int + */ + public function getDiagonalDirection() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getDiagonalDirection(); + } + return $this->diagonalDirection; + } + + /** + * Set DiagonalDirection + * + * @param int $pValue + * @return PHPExcel_Style_Borders + */ + public function setDiagonalDirection($pValue = PHPExcel_Style_Borders::DIAGONAL_NONE) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_Borders::DIAGONAL_NONE; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('diagonaldirection' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->diagonalDirection = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashcode(); + } + return md5( + $this->getLeft()->getHashCode() . + $this->getRight()->getHashCode() . + $this->getTop()->getHashCode() . + $this->getBottom()->getHashCode() . + $this->getDiagonal()->getHashCode() . + $this->getDiagonalDirection() . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Color.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Color.php new file mode 100644 index 00000000..9c7790f0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Color.php @@ -0,0 +1,443 @@ +<?php + +/** + * PHPExcel_Style_Color + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Color extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Colors */ + const COLOR_BLACK = 'FF000000'; + const COLOR_WHITE = 'FFFFFFFF'; + const COLOR_RED = 'FFFF0000'; + const COLOR_DARKRED = 'FF800000'; + const COLOR_BLUE = 'FF0000FF'; + const COLOR_DARKBLUE = 'FF000080'; + const COLOR_GREEN = 'FF00FF00'; + const COLOR_DARKGREEN = 'FF008000'; + const COLOR_YELLOW = 'FFFFFF00'; + const COLOR_DARKYELLOW = 'FF808000'; + + /** + * Indexed colors array + * + * @var array + */ + protected static $indexedColors; + + /** + * ARGB - Alpha RGB + * + * @var string + */ + protected $argb = null; + + /** + * Parent property name + * + * @var string + */ + protected $parentPropertyName; + + + /** + * Create a new PHPExcel_Style_Color + * + * @param string $pARGB ARGB value for the colour + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($pARGB = PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if (!$isConditional) { + $this->argb = $pARGB; + } + } + + /** + * Bind parent. Only used for supervisor + * + * @param mixed $parent + * @param string $parentPropertyName + * @return PHPExcel_Style_Color + */ + public function bindParent($parent, $parentPropertyName = null) + { + $this->parent = $parent; + $this->parentPropertyName = $parentPropertyName; + return $this; + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Color + */ + public function getSharedComponent() + { + switch ($this->parentPropertyName) { + case 'endColor': + return $this->parent->getSharedComponent()->getEndColor(); + case 'color': + return $this->parent->getSharedComponent()->getColor(); + case 'startColor': + return $this->parent->getSharedComponent()->getStartColor(); + } + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + switch ($this->parentPropertyName) { + case 'endColor': + $key = 'endcolor'; + break; + case 'color': + $key = 'color'; + break; + case 'startColor': + $key = 'startcolor'; + break; + + } + return $this->parent->getStyleArray(array($key => $array)); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->getColor()->applyFromArray( array('rgb' => '808080') ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Color + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('rgb', $pStyles)) { + $this->setRGB($pStyles['rgb']); + } + if (array_key_exists('argb', $pStyles)) { + $this->setARGB($pStyles['argb']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get ARGB + * + * @return string + */ + public function getARGB() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getARGB(); + } + return $this->argb; + } + + /** + * Set ARGB + * + * @param string $pValue + * @return PHPExcel_Style_Color + */ + public function setARGB($pValue = PHPExcel_Style_Color::COLOR_BLACK) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_Color::COLOR_BLACK; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('argb' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->argb = $pValue; + } + return $this; + } + + /** + * Get RGB + * + * @return string + */ + public function getRGB() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getRGB(); + } + return substr($this->argb, 2); + } + + /** + * Set RGB + * + * @param string $pValue RGB value + * @return PHPExcel_Style_Color + */ + public function setRGB($pValue = '000000') + { + if ($pValue == '') { + $pValue = '000000'; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('argb' => 'FF' . $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->argb = 'FF' . $pValue; + } + return $this; + } + + /** + * Get a specified colour component of an RGB value + * + * @private + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param int $offset Position within the RGB value to extract + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The extracted colour component + */ + private static function getColourComponent($RGB, $offset, $hex = true) + { + $colour = substr($RGB, $offset, 2); + if (!$hex) { + $colour = hexdec($colour); + } + return $colour; + } + + /** + * Get the red colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The red colour component + */ + public static function getRed($RGB, $hex = true) + { + return self::getColourComponent($RGB, strlen($RGB) - 6, $hex); + } + + /** + * Get the green colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The green colour component + */ + public static function getGreen($RGB, $hex = true) + { + return self::getColourComponent($RGB, strlen($RGB) - 4, $hex); + } + + /** + * Get the blue colour component of an RGB value + * + * @param string $RGB The colour as an RGB value (e.g. FF00CCCC or CCDDEE + * @param boolean $hex Flag indicating whether the component should be returned as a hex or a + * decimal value + * @return string The blue colour component + */ + public static function getBlue($RGB, $hex = true) + { + return self::getColourComponent($RGB, strlen($RGB) - 2, $hex); + } + + /** + * Adjust the brightness of a color + * + * @param string $hex The colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) + * @param float $adjustPercentage The percentage by which to adjust the colour as a float from -1 to 1 + * @return string The adjusted colour as an RGBA or RGB value (e.g. FF00CCCC or CCDDEE) + */ + public static function changeBrightness($hex, $adjustPercentage) + { + $rgba = (strlen($hex) == 8); + + $red = self::getRed($hex, false); + $green = self::getGreen($hex, false); + $blue = self::getBlue($hex, false); + if ($adjustPercentage > 0) { + $red += (255 - $red) * $adjustPercentage; + $green += (255 - $green) * $adjustPercentage; + $blue += (255 - $blue) * $adjustPercentage; + } else { + $red += $red * $adjustPercentage; + $green += $green * $adjustPercentage; + $blue += $blue * $adjustPercentage; + } + + if ($red < 0) { + $red = 0; + } elseif ($red > 255) { + $red = 255; + } + if ($green < 0) { + $green = 0; + } elseif ($green > 255) { + $green = 255; + } + if ($blue < 0) { + $blue = 0; + } elseif ($blue > 255) { + $blue = 255; + } + + $rgb = strtoupper( + str_pad(dechex($red), 2, '0', 0) . + str_pad(dechex($green), 2, '0', 0) . + str_pad(dechex($blue), 2, '0', 0) + ); + return (($rgba) ? 'FF' : '') . $rgb; + } + + /** + * Get indexed color + * + * @param int $pIndex Index entry point into the colour array + * @param boolean $background Flag to indicate whether default background or foreground colour + * should be returned if the indexed colour doesn't exist + * @return PHPExcel_Style_Color + */ + public static function indexedColor($pIndex, $background = false) + { + // Clean parameter + $pIndex = intval($pIndex); + + // Indexed colors + if (is_null(self::$indexedColors)) { + self::$indexedColors = array( + 1 => 'FF000000', // System Colour #1 - Black + 2 => 'FFFFFFFF', // System Colour #2 - White + 3 => 'FFFF0000', // System Colour #3 - Red + 4 => 'FF00FF00', // System Colour #4 - Green + 5 => 'FF0000FF', // System Colour #5 - Blue + 6 => 'FFFFFF00', // System Colour #6 - Yellow + 7 => 'FFFF00FF', // System Colour #7- Magenta + 8 => 'FF00FFFF', // System Colour #8- Cyan + 9 => 'FF800000', // Standard Colour #9 + 10 => 'FF008000', // Standard Colour #10 + 11 => 'FF000080', // Standard Colour #11 + 12 => 'FF808000', // Standard Colour #12 + 13 => 'FF800080', // Standard Colour #13 + 14 => 'FF008080', // Standard Colour #14 + 15 => 'FFC0C0C0', // Standard Colour #15 + 16 => 'FF808080', // Standard Colour #16 + 17 => 'FF9999FF', // Chart Fill Colour #17 + 18 => 'FF993366', // Chart Fill Colour #18 + 19 => 'FFFFFFCC', // Chart Fill Colour #19 + 20 => 'FFCCFFFF', // Chart Fill Colour #20 + 21 => 'FF660066', // Chart Fill Colour #21 + 22 => 'FFFF8080', // Chart Fill Colour #22 + 23 => 'FF0066CC', // Chart Fill Colour #23 + 24 => 'FFCCCCFF', // Chart Fill Colour #24 + 25 => 'FF000080', // Chart Line Colour #25 + 26 => 'FFFF00FF', // Chart Line Colour #26 + 27 => 'FFFFFF00', // Chart Line Colour #27 + 28 => 'FF00FFFF', // Chart Line Colour #28 + 29 => 'FF800080', // Chart Line Colour #29 + 30 => 'FF800000', // Chart Line Colour #30 + 31 => 'FF008080', // Chart Line Colour #31 + 32 => 'FF0000FF', // Chart Line Colour #32 + 33 => 'FF00CCFF', // Standard Colour #33 + 34 => 'FFCCFFFF', // Standard Colour #34 + 35 => 'FFCCFFCC', // Standard Colour #35 + 36 => 'FFFFFF99', // Standard Colour #36 + 37 => 'FF99CCFF', // Standard Colour #37 + 38 => 'FFFF99CC', // Standard Colour #38 + 39 => 'FFCC99FF', // Standard Colour #39 + 40 => 'FFFFCC99', // Standard Colour #40 + 41 => 'FF3366FF', // Standard Colour #41 + 42 => 'FF33CCCC', // Standard Colour #42 + 43 => 'FF99CC00', // Standard Colour #43 + 44 => 'FFFFCC00', // Standard Colour #44 + 45 => 'FFFF9900', // Standard Colour #45 + 46 => 'FFFF6600', // Standard Colour #46 + 47 => 'FF666699', // Standard Colour #47 + 48 => 'FF969696', // Standard Colour #48 + 49 => 'FF003366', // Standard Colour #49 + 50 => 'FF339966', // Standard Colour #50 + 51 => 'FF003300', // Standard Colour #51 + 52 => 'FF333300', // Standard Colour #52 + 53 => 'FF993300', // Standard Colour #53 + 54 => 'FF993366', // Standard Colour #54 + 55 => 'FF333399', // Standard Colour #55 + 56 => 'FF333333' // Standard Colour #56 + ); + } + + if (array_key_exists($pIndex, self::$indexedColors)) { + return new PHPExcel_Style_Color(self::$indexedColors[$pIndex]); + } + + if ($background) { + return new PHPExcel_Style_Color(self::COLOR_WHITE); + } + return new PHPExcel_Style_Color(self::COLOR_BLACK); + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->argb . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Conditional.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Conditional.php new file mode 100644 index 00000000..331362b4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Conditional.php @@ -0,0 +1,293 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Style_Conditional + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Style_Conditional implements PHPExcel_IComparable +{ + /* Condition types */ + const CONDITION_NONE = 'none'; + const CONDITION_CELLIS = 'cellIs'; + const CONDITION_CONTAINSTEXT = 'containsText'; + const CONDITION_EXPRESSION = 'expression'; + + /* Operator types */ + const OPERATOR_NONE = ''; + const OPERATOR_BEGINSWITH = 'beginsWith'; + const OPERATOR_ENDSWITH = 'endsWith'; + const OPERATOR_EQUAL = 'equal'; + const OPERATOR_GREATERTHAN = 'greaterThan'; + const OPERATOR_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const OPERATOR_LESSTHAN = 'lessThan'; + const OPERATOR_LESSTHANOREQUAL = 'lessThanOrEqual'; + const OPERATOR_NOTEQUAL = 'notEqual'; + const OPERATOR_CONTAINSTEXT = 'containsText'; + const OPERATOR_NOTCONTAINS = 'notContains'; + const OPERATOR_BETWEEN = 'between'; + + /** + * Condition type + * + * @var int + */ + private $conditionType; + + /** + * Operator type + * + * @var int + */ + private $operatorType; + + /** + * Text + * + * @var string + */ + private $text; + + /** + * Condition + * + * @var string[] + */ + private $condition = array(); + + /** + * Style + * + * @var PHPExcel_Style + */ + private $style; + + /** + * Create a new PHPExcel_Style_Conditional + */ + public function __construct() + { + // Initialise values + $this->conditionType = PHPExcel_Style_Conditional::CONDITION_NONE; + $this->operatorType = PHPExcel_Style_Conditional::OPERATOR_NONE; + $this->text = null; + $this->condition = array(); + $this->style = new PHPExcel_Style(false, true); + } + + /** + * Get Condition type + * + * @return string + */ + public function getConditionType() + { + return $this->conditionType; + } + + /** + * Set Condition type + * + * @param string $pValue PHPExcel_Style_Conditional condition type + * @return PHPExcel_Style_Conditional + */ + public function setConditionType($pValue = PHPExcel_Style_Conditional::CONDITION_NONE) + { + $this->conditionType = $pValue; + return $this; + } + + /** + * Get Operator type + * + * @return string + */ + public function getOperatorType() + { + return $this->operatorType; + } + + /** + * Set Operator type + * + * @param string $pValue PHPExcel_Style_Conditional operator type + * @return PHPExcel_Style_Conditional + */ + public function setOperatorType($pValue = PHPExcel_Style_Conditional::OPERATOR_NONE) + { + $this->operatorType = $pValue; + return $this; + } + + /** + * Get text + * + * @return string + */ + public function getText() + { + return $this->text; + } + + /** + * Set text + * + * @param string $value + * @return PHPExcel_Style_Conditional + */ + public function setText($value = null) + { + $this->text = $value; + return $this; + } + + /** + * Get Condition + * + * @deprecated Deprecated, use getConditions instead + * @return string + */ + public function getCondition() + { + if (isset($this->condition[0])) { + return $this->condition[0]; + } + + return ''; + } + + /** + * Set Condition + * + * @deprecated Deprecated, use setConditions instead + * @param string $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function setCondition($pValue = '') + { + if (!is_array($pValue)) { + $pValue = array($pValue); + } + + return $this->setConditions($pValue); + } + + /** + * Get Conditions + * + * @return string[] + */ + public function getConditions() + { + return $this->condition; + } + + /** + * Set Conditions + * + * @param string[] $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function setConditions($pValue) + { + if (!is_array($pValue)) { + $pValue = array($pValue); + } + $this->condition = $pValue; + return $this; + } + + /** + * Add Condition + * + * @param string $pValue Condition + * @return PHPExcel_Style_Conditional + */ + public function addCondition($pValue = '') + { + $this->condition[] = $pValue; + return $this; + } + + /** + * Get Style + * + * @return PHPExcel_Style + */ + public function getStyle() + { + return $this->style; + } + + /** + * Set Style + * + * @param PHPExcel_Style $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Conditional + */ + public function setStyle(PHPExcel_Style $pValue = null) + { + $this->style = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->conditionType . + $this->operatorType . + implode(';', $this->condition) . + $this->style->getHashCode() . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Fill.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Fill.php new file mode 100644 index 00000000..26343ff5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Fill.php @@ -0,0 +1,322 @@ +<?php + +/** + * PHPExcel_Style_Fill + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Fill extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Fill types */ + const FILL_NONE = 'none'; + const FILL_SOLID = 'solid'; + const FILL_GRADIENT_LINEAR = 'linear'; + const FILL_GRADIENT_PATH = 'path'; + const FILL_PATTERN_DARKDOWN = 'darkDown'; + const FILL_PATTERN_DARKGRAY = 'darkGray'; + const FILL_PATTERN_DARKGRID = 'darkGrid'; + const FILL_PATTERN_DARKHORIZONTAL = 'darkHorizontal'; + const FILL_PATTERN_DARKTRELLIS = 'darkTrellis'; + const FILL_PATTERN_DARKUP = 'darkUp'; + const FILL_PATTERN_DARKVERTICAL = 'darkVertical'; + const FILL_PATTERN_GRAY0625 = 'gray0625'; + const FILL_PATTERN_GRAY125 = 'gray125'; + const FILL_PATTERN_LIGHTDOWN = 'lightDown'; + const FILL_PATTERN_LIGHTGRAY = 'lightGray'; + const FILL_PATTERN_LIGHTGRID = 'lightGrid'; + const FILL_PATTERN_LIGHTHORIZONTAL = 'lightHorizontal'; + const FILL_PATTERN_LIGHTTRELLIS = 'lightTrellis'; + const FILL_PATTERN_LIGHTUP = 'lightUp'; + const FILL_PATTERN_LIGHTVERTICAL = 'lightVertical'; + const FILL_PATTERN_MEDIUMGRAY = 'mediumGray'; + + /** + * Fill type + * + * @var string + */ + protected $fillType = PHPExcel_Style_Fill::FILL_NONE; + + /** + * Rotation + * + * @var double + */ + protected $rotation = 0; + + /** + * Start color + * + * @var PHPExcel_Style_Color + */ + protected $startColor; + + /** + * End color + * + * @var PHPExcel_Style_Color + */ + protected $endColor; + + /** + * Create a new PHPExcel_Style_Fill + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if ($isConditional) { + $this->fillType = null; + } + $this->startColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_WHITE, $isSupervisor, $isConditional); + $this->endColor = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional); + + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->startColor->bindParent($this, 'startColor'); + $this->endColor->bindParent($this, 'endColor'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Fill + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getFill(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('fill' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFill()->applyFromArray( + * array( + * 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR, + * 'rotation' => 0, + * 'startcolor' => array( + * 'rgb' => '000000' + * ), + * 'endcolor' => array( + * 'argb' => 'FFFFFFFF' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('type', $pStyles)) { + $this->setFillType($pStyles['type']); + } + if (array_key_exists('rotation', $pStyles)) { + $this->setRotation($pStyles['rotation']); + } + if (array_key_exists('startcolor', $pStyles)) { + $this->getStartColor()->applyFromArray($pStyles['startcolor']); + } + if (array_key_exists('endcolor', $pStyles)) { + $this->getEndColor()->applyFromArray($pStyles['endcolor']); + } + if (array_key_exists('color', $pStyles)) { + $this->getStartColor()->applyFromArray($pStyles['color']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Fill Type + * + * @return string + */ + public function getFillType() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getFillType(); + } + return $this->fillType; + } + + /** + * Set Fill Type + * + * @param string $pValue PHPExcel_Style_Fill fill type + * @return PHPExcel_Style_Fill + */ + public function setFillType($pValue = PHPExcel_Style_Fill::FILL_NONE) + { + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('type' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->fillType = $pValue; + } + return $this; + } + + /** + * Get Rotation + * + * @return double + */ + public function getRotation() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getRotation(); + } + return $this->rotation; + } + + /** + * Set Rotation + * + * @param double $pValue + * @return PHPExcel_Style_Fill + */ + public function setRotation($pValue = 0) + { + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('rotation' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->rotation = $pValue; + } + return $this; + } + + /** + * Get Start Color + * + * @return PHPExcel_Style_Color + */ + public function getStartColor() + { + return $this->startColor; + } + + /** + * Set Start Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function setStartColor(PHPExcel_Style_Color $pValue = null) + { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->isSupervisor) { + $styleArray = $this->getStartColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->startColor = $color; + } + return $this; + } + + /** + * Get End Color + * + * @return PHPExcel_Style_Color + */ + public function getEndColor() + { + return $this->endColor; + } + + /** + * Set End Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Fill + */ + public function setEndColor(PHPExcel_Style_Color $pValue = null) + { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->isSupervisor) { + $styleArray = $this->getEndColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->endColor = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->getFillType() . + $this->getRotation() . + $this->getStartColor()->getHashCode() . + $this->getEndColor()->getHashCode() . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Font.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Font.php new file mode 100644 index 00000000..9566e1df --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Font.php @@ -0,0 +1,543 @@ +<?php + +/** + * PHPExcel_Style_Font + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Font extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Underline types */ + const UNDERLINE_NONE = 'none'; + const UNDERLINE_DOUBLE = 'double'; + const UNDERLINE_DOUBLEACCOUNTING = 'doubleAccounting'; + const UNDERLINE_SINGLE = 'single'; + const UNDERLINE_SINGLEACCOUNTING = 'singleAccounting'; + + /** + * Font Name + * + * @var string + */ + protected $name = 'Calibri'; + + /** + * Font Size + * + * @var float + */ + protected $size = 11; + + /** + * Bold + * + * @var boolean + */ + protected $bold = false; + + /** + * Italic + * + * @var boolean + */ + protected $italic = false; + + /** + * Superscript + * + * @var boolean + */ + protected $superScript = false; + + /** + * Subscript + * + * @var boolean + */ + protected $subScript = false; + + /** + * Underline + * + * @var string + */ + protected $underline = self::UNDERLINE_NONE; + + /** + * Strikethrough + * + * @var boolean + */ + protected $strikethrough = false; + + /** + * Foreground color + * + * @var PHPExcel_Style_Color + */ + protected $color; + + /** + * Create a new PHPExcel_Style_Font + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if ($isConditional) { + $this->name = null; + $this->size = null; + $this->bold = null; + $this->italic = null; + $this->superScript = null; + $this->subScript = null; + $this->underline = null; + $this->strikethrough = null; + $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor, $isConditional); + } else { + $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK, $isSupervisor); + } + // bind parent if we are a supervisor + if ($isSupervisor) { + $this->color->bindParent($this, 'color'); + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Font + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getFont(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('font' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getFont()->applyFromArray( + * array( + * 'name' => 'Arial', + * 'bold' => TRUE, + * 'italic' => FALSE, + * 'underline' => PHPExcel_Style_Font::UNDERLINE_DOUBLE, + * 'strike' => FALSE, + * 'color' => array( + * 'rgb' => '808080' + * ) + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Font + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('name', $pStyles)) { + $this->setName($pStyles['name']); + } + if (array_key_exists('bold', $pStyles)) { + $this->setBold($pStyles['bold']); + } + if (array_key_exists('italic', $pStyles)) { + $this->setItalic($pStyles['italic']); + } + if (array_key_exists('superScript', $pStyles)) { + $this->setSuperScript($pStyles['superScript']); + } + if (array_key_exists('subScript', $pStyles)) { + $this->setSubScript($pStyles['subScript']); + } + if (array_key_exists('underline', $pStyles)) { + $this->setUnderline($pStyles['underline']); + } + if (array_key_exists('strike', $pStyles)) { + $this->setStrikethrough($pStyles['strike']); + } + if (array_key_exists('color', $pStyles)) { + $this->getColor()->applyFromArray($pStyles['color']); + } + if (array_key_exists('size', $pStyles)) { + $this->setSize($pStyles['size']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Name + * + * @return string + */ + public function getName() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getName(); + } + return $this->name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Style_Font + */ + public function setName($pValue = 'Calibri') + { + if ($pValue == '') { + $pValue = 'Calibri'; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('name' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->name = $pValue; + } + return $this; + } + + /** + * Get Size + * + * @return double + */ + public function getSize() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getSize(); + } + return $this->size; + } + + /** + * Set Size + * + * @param double $pValue + * @return PHPExcel_Style_Font + */ + public function setSize($pValue = 10) + { + if ($pValue == '') { + $pValue = 10; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('size' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->size = $pValue; + } + return $this; + } + + /** + * Get Bold + * + * @return boolean + */ + public function getBold() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getBold(); + } + return $this->bold; + } + + /** + * Set Bold + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setBold($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('bold' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->bold = $pValue; + } + return $this; + } + + /** + * Get Italic + * + * @return boolean + */ + public function getItalic() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getItalic(); + } + return $this->italic; + } + + /** + * Set Italic + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setItalic($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('italic' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->italic = $pValue; + } + return $this; + } + + /** + * Get SuperScript + * + * @return boolean + */ + public function getSuperScript() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getSuperScript(); + } + return $this->superScript; + } + + /** + * Set SuperScript + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setSuperScript($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('superScript' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->superScript = $pValue; + $this->subScript = !$pValue; + } + return $this; + } + + /** + * Get SubScript + * + * @return boolean + */ + public function getSubScript() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getSubScript(); + } + return $this->subScript; + } + + /** + * Set SubScript + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setSubScript($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('subScript' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->subScript = $pValue; + $this->superScript = !$pValue; + } + return $this; + } + + /** + * Get Underline + * + * @return string + */ + public function getUnderline() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getUnderline(); + } + return $this->underline; + } + + /** + * Set Underline + * + * @param string|boolean $pValue PHPExcel_Style_Font underline type + * If a boolean is passed, then TRUE equates to UNDERLINE_SINGLE, + * false equates to UNDERLINE_NONE + * @return PHPExcel_Style_Font + */ + public function setUnderline($pValue = self::UNDERLINE_NONE) + { + if (is_bool($pValue)) { + $pValue = ($pValue) ? self::UNDERLINE_SINGLE : self::UNDERLINE_NONE; + } elseif ($pValue == '') { + $pValue = self::UNDERLINE_NONE; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('underline' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->underline = $pValue; + } + return $this; + } + + /** + * Get Strikethrough + * + * @return boolean + */ + public function getStrikethrough() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getStrikethrough(); + } + return $this->strikethrough; + } + + /** + * Set Strikethrough + * + * @param boolean $pValue + * @return PHPExcel_Style_Font + */ + public function setStrikethrough($pValue = false) + { + if ($pValue == '') { + $pValue = false; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('strike' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->strikethrough = $pValue; + } + return $this; + } + + /** + * Get Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() + { + return $this->color; + } + + /** + * Set Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Font + */ + public function setColor(PHPExcel_Style_Color $pValue = null) + { + // make sure parameter is a real color and not a supervisor + $color = $pValue->getIsSupervisor() ? $pValue->getSharedComponent() : $pValue; + + if ($this->isSupervisor) { + $styleArray = $this->getColor()->getStyleArray(array('argb' => $color->getARGB())); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->color = $color; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->name . + $this->size . + ($this->bold ? 't' : 'f') . + ($this->italic ? 't' : 'f') . + ($this->superScript ? 't' : 'f') . + ($this->subScript ? 't' : 'f') . + $this->underline . + ($this->strikethrough ? 't' : 'f') . + $this->color->getHashCode() . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/NumberFormat.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/NumberFormat.php new file mode 100644 index 00000000..1b72cda9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/NumberFormat.php @@ -0,0 +1,751 @@ +<?php + +/** + * PHPExcel_Style_NumberFormat + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_NumberFormat extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /* Pre-defined formats */ + const FORMAT_GENERAL = 'General'; + + const FORMAT_TEXT = '@'; + + const FORMAT_NUMBER = '0'; + const FORMAT_NUMBER_00 = '0.00'; + const FORMAT_NUMBER_COMMA_SEPARATED1 = '#,##0.00'; + const FORMAT_NUMBER_COMMA_SEPARATED2 = '#,##0.00_-'; + + const FORMAT_PERCENTAGE = '0%'; + const FORMAT_PERCENTAGE_00 = '0.00%'; + + const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd'; + const FORMAT_DATE_YYYYMMDD = 'yy-mm-dd'; + const FORMAT_DATE_DDMMYYYY = 'dd/mm/yy'; + const FORMAT_DATE_DMYSLASH = 'd/m/y'; + const FORMAT_DATE_DMYMINUS = 'd-m-y'; + const FORMAT_DATE_DMMINUS = 'd-m'; + const FORMAT_DATE_MYMINUS = 'm-y'; + const FORMAT_DATE_XLSX14 = 'mm-dd-yy'; + const FORMAT_DATE_XLSX15 = 'd-mmm-yy'; + const FORMAT_DATE_XLSX16 = 'd-mmm'; + const FORMAT_DATE_XLSX17 = 'mmm-yy'; + const FORMAT_DATE_XLSX22 = 'm/d/yy h:mm'; + const FORMAT_DATE_DATETIME = 'd/m/y h:mm'; + const FORMAT_DATE_TIME1 = 'h:mm AM/PM'; + const FORMAT_DATE_TIME2 = 'h:mm:ss AM/PM'; + const FORMAT_DATE_TIME3 = 'h:mm'; + const FORMAT_DATE_TIME4 = 'h:mm:ss'; + const FORMAT_DATE_TIME5 = 'mm:ss'; + const FORMAT_DATE_TIME6 = 'h:mm:ss'; + const FORMAT_DATE_TIME7 = 'i:s.S'; + const FORMAT_DATE_TIME8 = 'h:mm:ss;@'; + const FORMAT_DATE_YYYYMMDDSLASH = 'yy/mm/dd;@'; + + const FORMAT_CURRENCY_USD_SIMPLE = '"$"#,##0.00_-'; + const FORMAT_CURRENCY_USD = '$#,##0_-'; + const FORMAT_CURRENCY_EUR_SIMPLE = '[$EUR ]#,##0.00_-'; + + /** + * Excel built-in number formats + * + * @var array + */ + protected static $builtInFormats; + + /** + * Excel built-in number formats (flipped, for faster lookups) + * + * @var array + */ + protected static $flippedBuiltInFormats; + + /** + * Format Code + * + * @var string + */ + protected $formatCode = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + + /** + * Built-in format Code + * + * @var string + */ + protected $builtInFormatCode = 0; + + /** + * Create a new PHPExcel_Style_NumberFormat + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + if ($isConditional) { + $this->formatCode = null; + $this->builtInFormatCode = false; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_NumberFormat + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getNumberFormat(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('numberformat' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getNumberFormat()->applyFromArray( + * array( + * 'code' => PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_EUR_SIMPLE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_NumberFormat + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (array_key_exists('code', $pStyles)) { + $this->setFormatCode($pStyles['code']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get Format Code + * + * @return string + */ + public function getFormatCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getFormatCode(); + } + if ($this->builtInFormatCode !== false) { + return self::builtInFormatCode($this->builtInFormatCode); + } + return $this->formatCode; + } + + /** + * Set Format Code + * + * @param string $pValue + * @return PHPExcel_Style_NumberFormat + */ + public function setFormatCode($pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL) + { + if ($pValue == '') { + $pValue = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + } + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('code' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->formatCode = $pValue; + $this->builtInFormatCode = self::builtInFormatCodeIndex($pValue); + } + return $this; + } + + /** + * Get Built-In Format Code + * + * @return int + */ + public function getBuiltInFormatCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getBuiltInFormatCode(); + } + return $this->builtInFormatCode; + } + + /** + * Set Built-In Format Code + * + * @param int $pValue + * @return PHPExcel_Style_NumberFormat + */ + public function setBuiltInFormatCode($pValue = 0) + { + + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('code' => self::builtInFormatCode($pValue))); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->builtInFormatCode = $pValue; + $this->formatCode = self::builtInFormatCode($pValue); + } + return $this; + } + + /** + * Fill built-in format codes + */ + private static function fillBuiltInFormatCodes() + { + // [MS-OI29500: Microsoft Office Implementation Information for ISO/IEC-29500 Standard Compliance] + // 18.8.30. numFmt (Number Format) + // + // The ECMA standard defines built-in format IDs + // 14: "mm-dd-yy" + // 22: "m/d/yy h:mm" + // 37: "#,##0 ;(#,##0)" + // 38: "#,##0 ;[Red](#,##0)" + // 39: "#,##0.00;(#,##0.00)" + // 40: "#,##0.00;[Red](#,##0.00)" + // 47: "mmss.0" + // KOR fmt 55: "yyyy-mm-dd" + // Excel defines built-in format IDs + // 14: "m/d/yyyy" + // 22: "m/d/yyyy h:mm" + // 37: "#,##0_);(#,##0)" + // 38: "#,##0_);[Red](#,##0)" + // 39: "#,##0.00_);(#,##0.00)" + // 40: "#,##0.00_);[Red](#,##0.00)" + // 47: "mm:ss.0" + // KOR fmt 55: "yyyy/mm/dd" + + // Built-in format codes + if (is_null(self::$builtInFormats)) { + self::$builtInFormats = array(); + + // General + self::$builtInFormats[0] = PHPExcel_Style_NumberFormat::FORMAT_GENERAL; + self::$builtInFormats[1] = '0'; + self::$builtInFormats[2] = '0.00'; + self::$builtInFormats[3] = '#,##0'; + self::$builtInFormats[4] = '#,##0.00'; + + self::$builtInFormats[9] = '0%'; + self::$builtInFormats[10] = '0.00%'; + self::$builtInFormats[11] = '0.00E+00'; + self::$builtInFormats[12] = '# ?/?'; + self::$builtInFormats[13] = '# ??/??'; + self::$builtInFormats[14] = 'm/d/yyyy'; // Despite ECMA 'mm-dd-yy'; + self::$builtInFormats[15] = 'd-mmm-yy'; + self::$builtInFormats[16] = 'd-mmm'; + self::$builtInFormats[17] = 'mmm-yy'; + self::$builtInFormats[18] = 'h:mm AM/PM'; + self::$builtInFormats[19] = 'h:mm:ss AM/PM'; + self::$builtInFormats[20] = 'h:mm'; + self::$builtInFormats[21] = 'h:mm:ss'; + self::$builtInFormats[22] = 'm/d/yyyy h:mm'; // Despite ECMA 'm/d/yy h:mm'; + + self::$builtInFormats[37] = '#,##0_);(#,##0)'; // Despite ECMA '#,##0 ;(#,##0)'; + self::$builtInFormats[38] = '#,##0_);[Red](#,##0)'; // Despite ECMA '#,##0 ;[Red](#,##0)'; + self::$builtInFormats[39] = '#,##0.00_);(#,##0.00)'; // Despite ECMA '#,##0.00;(#,##0.00)'; + self::$builtInFormats[40] = '#,##0.00_);[Red](#,##0.00)'; // Despite ECMA '#,##0.00;[Red](#,##0.00)'; + + self::$builtInFormats[44] = '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)'; + self::$builtInFormats[45] = 'mm:ss'; + self::$builtInFormats[46] = '[h]:mm:ss'; + self::$builtInFormats[47] = 'mm:ss.0'; // Despite ECMA 'mmss.0'; + self::$builtInFormats[48] = '##0.0E+0'; + self::$builtInFormats[49] = '@'; + + // CHT + self::$builtInFormats[27] = '[$-404]e/m/d'; + self::$builtInFormats[30] = 'm/d/yy'; + self::$builtInFormats[36] = '[$-404]e/m/d'; + self::$builtInFormats[50] = '[$-404]e/m/d'; + self::$builtInFormats[57] = '[$-404]e/m/d'; + + // THA + self::$builtInFormats[59] = 't0'; + self::$builtInFormats[60] = 't0.00'; + self::$builtInFormats[61] = 't#,##0'; + self::$builtInFormats[62] = 't#,##0.00'; + self::$builtInFormats[67] = 't0%'; + self::$builtInFormats[68] = 't0.00%'; + self::$builtInFormats[69] = 't# ?/?'; + self::$builtInFormats[70] = 't# ??/??'; + + // Flip array (for faster lookups) + self::$flippedBuiltInFormats = array_flip(self::$builtInFormats); + } + } + + /** + * Get built-in format code + * + * @param int $pIndex + * @return string + */ + public static function builtInFormatCode($pIndex) + { + // Clean parameter + $pIndex = intval($pIndex); + + // Ensure built-in format codes are available + self::fillBuiltInFormatCodes(); + // Lookup format code + if (isset(self::$builtInFormats[$pIndex])) { + return self::$builtInFormats[$pIndex]; + } + + return ''; + } + + /** + * Get built-in format code index + * + * @param string $formatCode + * @return int|boolean + */ + public static function builtInFormatCodeIndex($formatCode) + { + // Ensure built-in format codes are available + self::fillBuiltInFormatCodes(); + + // Lookup format code + if (isset(self::$flippedBuiltInFormats[$formatCode])) { + return self::$flippedBuiltInFormats[$formatCode]; + } + + return false; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->formatCode . + $this->builtInFormatCode . + __CLASS__ + ); + } + + /** + * Search/replace values to convert Excel date/time format masks to PHP format masks + * + * @var array + */ + private static $dateFormatReplacements = array( + // first remove escapes related to non-format characters + '\\' => '', + // 12-hour suffix + 'am/pm' => 'A', + // 4-digit year + 'e' => 'Y', + 'yyyy' => 'Y', + // 2-digit year + 'yy' => 'y', + // first letter of month - no php equivalent + 'mmmmm' => 'M', + // full month name + 'mmmm' => 'F', + // short month name + 'mmm' => 'M', + // mm is minutes if time, but can also be month w/leading zero + // so we try to identify times be the inclusion of a : separator in the mask + // It isn't perfect, but the best way I know how + ':mm' => ':i', + 'mm:' => 'i:', + // month leading zero + 'mm' => 'm', + // month no leading zero + 'm' => 'n', + // full day of week name + 'dddd' => 'l', + // short day of week name + 'ddd' => 'D', + // days leading zero + 'dd' => 'd', + // days no leading zero + 'd' => 'j', + // seconds + 'ss' => 's', + // fractional seconds - no php equivalent + '.s' => '' + ); + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (24 hr clock) + * + * @var array + */ + private static $dateFormatReplacements24 = array( + 'hh' => 'H', + 'h' => 'G' + ); + /** + * Search/replace values to convert Excel date/time format masks hours to PHP format masks (12 hr clock) + * + * @var array + */ + private static $dateFormatReplacements12 = array( + 'hh' => 'h', + 'h' => 'g' + ); + + private static function setLowercaseCallback($matches) { + return mb_strtolower($matches[0]); + } + + private static function escapeQuotesCallback($matches) { + return '\\' . implode('\\', str_split($matches[1])); + } + + private static function formatAsDate(&$value, &$format) + { + // strip off first part containing e.g. [$-F800] or [$USD-409] + // general syntax: [$<Currency string>-<language info>] + // language info is in hexadecimal + $format = preg_replace('/^(\[\$[A-Z]*-[0-9A-F]*\])/i', '', $format); + + // OpenOffice.org uses upper-case number formats, e.g. 'YYYY', convert to lower-case; + // but we don't want to change any quoted strings + $format = preg_replace_callback('/(?:^|")([^"]*)(?:$|")/', array('self', 'setLowercaseCallback'), $format); + + // Only process the non-quoted blocks for date format characters + $blocks = explode('"', $format); + foreach($blocks as $key => &$block) { + if ($key % 2 == 0) { + $block = strtr($block, self::$dateFormatReplacements); + if (!strpos($block, 'A')) { + // 24-hour time format + $block = strtr($block, self::$dateFormatReplacements24); + } else { + // 12-hour time format + $block = strtr($block, self::$dateFormatReplacements12); + } + } + } + $format = implode('"', $blocks); + + // escape any quoted characters so that DateTime format() will render them correctly + $format = preg_replace_callback('/"(.*)"/U', array('self', 'escapeQuotesCallback'), $format); + + $dateObj = PHPExcel_Shared_Date::ExcelToPHPObject($value); + $value = $dateObj->format($format); + } + + private static function formatAsPercentage(&$value, &$format) + { + if ($format === self::FORMAT_PERCENTAGE) { + $value = round((100 * $value), 0) . '%'; + } else { + if (preg_match('/\.[#0]+/i', $format, $m)) { + $s = substr($m[0], 0, 1) . (strlen($m[0]) - 1); + $format = str_replace($m[0], $s, $format); + } + if (preg_match('/^[#0]+/', $format, $m)) { + $format = str_replace($m[0], strlen($m[0]), $format); + } + $format = '%' . str_replace('%', 'f%%', $format); + + $value = sprintf($format, 100 * $value); + } + } + + private static function formatAsFraction(&$value, &$format) + { + $sign = ($value < 0) ? '-' : ''; + + $integerPart = floor(abs($value)); + $decimalPart = trim(fmod(abs($value), 1), '0.'); + $decimalLength = strlen($decimalPart); + $decimalDivisor = pow(10, $decimalLength); + + $GCD = PHPExcel_Calculation_MathTrig::GCD($decimalPart, $decimalDivisor); + + $adjustedDecimalPart = $decimalPart/$GCD; + $adjustedDecimalDivisor = $decimalDivisor/$GCD; + + if ((strpos($format, '0') !== false) || (strpos($format, '#') !== false) || (substr($format, 0, 3) == '? ?')) { + if ($integerPart == 0) { + $integerPart = ''; + } + $value = "$sign$integerPart $adjustedDecimalPart/$adjustedDecimalDivisor"; + } else { + $adjustedDecimalPart += $integerPart * $adjustedDecimalDivisor; + $value = "$sign$adjustedDecimalPart/$adjustedDecimalDivisor"; + } + } + + private static function complexNumberFormatMask($number, $mask, $level = 0) + { + $sign = ($number < 0.0); + $number = abs($number); + if (strpos($mask, '.') !== false) { + $numbers = explode('.', $number . '.0'); + $masks = explode('.', $mask . '.0'); + $result1 = self::complexNumberFormatMask($numbers[0], $masks[0], 1); + $result2 = strrev(self::complexNumberFormatMask(strrev($numbers[1]), strrev($masks[1]), 1)); + return (($sign) ? '-' : '') . $result1 . '.' . $result2; + } + + $r = preg_match_all('/0+/', $mask, $result, PREG_OFFSET_CAPTURE); + if ($r > 1) { + $result = array_reverse($result[0]); + + foreach ($result as $block) { + $divisor = 1 . $block[0]; + $size = strlen($block[0]); + $offset = $block[1]; + + $blockValue = sprintf( + '%0' . $size . 'd', + fmod($number, $divisor) + ); + $number = floor($number / $divisor); + $mask = substr_replace($mask, $blockValue, $offset, $size); + } + if ($number > 0) { + $mask = substr_replace($mask, $number, $offset, 0); + } + $result = $mask; + } else { + $result = $number; + } + + return (($sign) ? '-' : '') . $result; + } + + /** + * Convert a value in a pre-defined format to a PHP string + * + * @param mixed $value Value to format + * @param string $format Format code + * @param array $callBack Callback function for additional formatting of string + * @return string Formatted string + */ + public static function toFormattedString($value = '0', $format = PHPExcel_Style_NumberFormat::FORMAT_GENERAL, $callBack = null) + { + // For now we do not treat strings although section 4 of a format code affects strings + if (!is_numeric($value)) { + return $value; + } + + // For 'General' format code, we just pass the value although this is not entirely the way Excel does it, + // it seems to round numbers to a total of 10 digits. + if (($format === PHPExcel_Style_NumberFormat::FORMAT_GENERAL) || ($format === PHPExcel_Style_NumberFormat::FORMAT_TEXT)) { + return $value; + } + + // Convert any other escaped characters to quoted strings, e.g. (\T to "T") + $format = preg_replace('/(\\\(.))(?=(?:[^"]|"[^"]*")*$)/u', '"${2}"', $format); + + // Get the sections, there can be up to four sections, separated with a semi-colon (but only if not a quoted literal) + $sections = preg_split('/(;)(?=(?:[^"]|"[^"]*")*$)/u', $format); + + // Extract the relevant section depending on whether number is positive, negative, or zero? + // Text not supported yet. + // Here is how the sections apply to various values in Excel: + // 1 section: [POSITIVE/NEGATIVE/ZERO/TEXT] + // 2 sections: [POSITIVE/ZERO/TEXT] [NEGATIVE] + // 3 sections: [POSITIVE/TEXT] [NEGATIVE] [ZERO] + // 4 sections: [POSITIVE] [NEGATIVE] [ZERO] [TEXT] + switch (count($sections)) { + case 1: + $format = $sections[0]; + break; + case 2: + $format = ($value >= 0) ? $sections[0] : $sections[1]; + $value = abs($value); // Use the absolute value + break; + case 3: + $format = ($value > 0) ? + $sections[0] : ( ($value < 0) ? + $sections[1] : $sections[2]); + $value = abs($value); // Use the absolute value + break; + case 4: + $format = ($value > 0) ? + $sections[0] : ( ($value < 0) ? + $sections[1] : $sections[2]); + $value = abs($value); // Use the absolute value + break; + default: + // something is wrong, just use first section + $format = $sections[0]; + break; + } + + // In Excel formats, "_" is used to add spacing, + // The following character indicates the size of the spacing, which we can't do in HTML, so we just use a standard space + $format = preg_replace('/_./', ' ', $format); + + // Save format with color information for later use below + $formatColor = $format; + + // Strip color information + $color_regex = '/^\\[[a-zA-Z]+\\]/'; + $format = preg_replace($color_regex, '', $format); + + // Let's begin inspecting the format and converting the value to a formatted string + + // Check for date/time characters (not inside quotes) + if (preg_match('/(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy](?=(?:[^"]|"[^"]*")*$)/miu', $format, $matches)) { + // datetime format + self::formatAsDate($value, $format); + } elseif (preg_match('/%$/', $format)) { + // % number format + self::formatAsPercentage($value, $format); + } else { + if ($format === self::FORMAT_CURRENCY_EUR_SIMPLE) { + $value = 'EUR ' . sprintf('%1.2f', $value); + } else { + // Some non-number strings are quoted, so we'll get rid of the quotes, likewise any positional * symbols + $format = str_replace(array('"', '*'), '', $format); + + // Find out if we need thousands separator + // This is indicated by a comma enclosed by a digit placeholder: + // #,# or 0,0 + $useThousands = preg_match('/(#,#|0,0)/', $format); + if ($useThousands) { + $format = preg_replace('/0,0/', '00', $format); + $format = preg_replace('/#,#/', '##', $format); + } + + // Scale thousands, millions,... + // This is indicated by a number of commas after a digit placeholder: + // #, or 0.0,, + $scale = 1; // same as no scale + $matches = array(); + if (preg_match('/(#|0)(,+)/', $format, $matches)) { + $scale = pow(1000, strlen($matches[2])); + + // strip the commas + $format = preg_replace('/0,+/', '0', $format); + $format = preg_replace('/#,+/', '#', $format); + } + + if (preg_match('/#?.*\?\/\?/', $format, $m)) { + //echo 'Format mask is fractional '.$format.' <br />'; + if ($value != (int)$value) { + self::formatAsFraction($value, $format); + } + + } else { + // Handle the number itself + + // scale number + $value = $value / $scale; + + // Strip # + $format = preg_replace('/\\#/', '0', $format); + + $n = "/\[[^\]]+\]/"; + $m = preg_replace($n, '', $format); + $number_regex = "/(0+)(\.?)(0*)/"; + if (preg_match($number_regex, $m, $matches)) { + $left = $matches[1]; + $dec = $matches[2]; + $right = $matches[3]; + + // minimun width of formatted number (including dot) + $minWidth = strlen($left) + strlen($dec) + strlen($right); + if ($useThousands) { + $value = number_format( + $value, + strlen($right), + PHPExcel_Shared_String::getDecimalSeparator(), + PHPExcel_Shared_String::getThousandsSeparator() + ); + $value = preg_replace($number_regex, $value, $format); + } else { + if (preg_match('/[0#]E[+-]0/i', $format)) { + // Scientific format + $value = sprintf('%5.2E', $value); + } elseif (preg_match('/0([^\d\.]+)0/', $format)) { + $value = self::complexNumberFormatMask($value, $format); + } else { + $sprintf_pattern = "%0$minWidth." . strlen($right) . "f"; + $value = sprintf($sprintf_pattern, $value); + $value = preg_replace($number_regex, $value, $format); + } + } + } + } + if (preg_match('/\[\$(.*)\]/u', $format, $m)) { + // Currency or Accounting + $currencyFormat = $m[0]; + $currencyCode = $m[1]; + list($currencyCode) = explode('-', $currencyCode); + if ($currencyCode == '') { + $currencyCode = PHPExcel_Shared_String::getCurrencyCode(); + } + $value = preg_replace('/\[\$([^\]]*)\]/u', $currencyCode, $value); + } + } + } + + // Escape any escaped slashes to a single slash + $format = preg_replace("/\\\\/u", '\\', $format); + + // Additional formatting provided by callback function + if ($callBack !== null) { + list($writerInstance, $function) = $callBack; + $value = $writerInstance->$function($value, $formatColor); + } + + return $value; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Protection.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Protection.php new file mode 100644 index 00000000..d5568f65 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Protection.php @@ -0,0 +1,204 @@ +<?php + +/** + * PHPExcel_Style_Protection + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Style_Protection extends PHPExcel_Style_Supervisor implements PHPExcel_IComparable +{ + /** Protection styles */ + const PROTECTION_INHERIT = 'inherit'; + const PROTECTION_PROTECTED = 'protected'; + const PROTECTION_UNPROTECTED = 'unprotected'; + + /** + * Locked + * + * @var string + */ + protected $locked; + + /** + * Hidden + * + * @var string + */ + protected $hidden; + + /** + * Create a new PHPExcel_Style_Protection + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + * @param boolean $isConditional Flag indicating if this is a conditional style or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false, $isConditional = false) + { + // Supervisor? + parent::__construct($isSupervisor); + + // Initialise values + if (!$isConditional) { + $this->locked = self::PROTECTION_INHERIT; + $this->hidden = self::PROTECTION_INHERIT; + } + } + + /** + * Get the shared style component for the currently active cell in currently active sheet. + * Only used for style supervisor + * + * @return PHPExcel_Style_Protection + */ + public function getSharedComponent() + { + return $this->parent->getSharedComponent()->getProtection(); + } + + /** + * Build style array from subcomponents + * + * @param array $array + * @return array + */ + public function getStyleArray($array) + { + return array('protection' => $array); + } + + /** + * Apply styles from array + * + * <code> + * $objPHPExcel->getActiveSheet()->getStyle('B2')->getLocked()->applyFromArray( + * array( + * 'locked' => TRUE, + * 'hidden' => FALSE + * ) + * ); + * </code> + * + * @param array $pStyles Array containing style information + * @throws PHPExcel_Exception + * @return PHPExcel_Style_Protection + */ + public function applyFromArray($pStyles = null) + { + if (is_array($pStyles)) { + if ($this->isSupervisor) { + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($this->getStyleArray($pStyles)); + } else { + if (isset($pStyles['locked'])) { + $this->setLocked($pStyles['locked']); + } + if (isset($pStyles['hidden'])) { + $this->setHidden($pStyles['hidden']); + } + } + } else { + throw new PHPExcel_Exception("Invalid style array passed."); + } + return $this; + } + + /** + * Get locked + * + * @return string + */ + public function getLocked() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getLocked(); + } + return $this->locked; + } + + /** + * Set locked + * + * @param string $pValue + * @return PHPExcel_Style_Protection + */ + public function setLocked($pValue = self::PROTECTION_INHERIT) + { + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('locked' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->locked = $pValue; + } + return $this; + } + + /** + * Get hidden + * + * @return string + */ + public function getHidden() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHidden(); + } + return $this->hidden; + } + + /** + * Set hidden + * + * @param string $pValue + * @return PHPExcel_Style_Protection + */ + public function setHidden($pValue = self::PROTECTION_INHERIT) + { + if ($this->isSupervisor) { + $styleArray = $this->getStyleArray(array('hidden' => $pValue)); + $this->getActiveSheet()->getStyle($this->getSelectedCells())->applyFromArray($styleArray); + } else { + $this->hidden = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->isSupervisor) { + return $this->getSharedComponent()->getHashCode(); + } + return md5( + $this->locked . + $this->hidden . + __CLASS__ + ); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Supervisor.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Supervisor.php new file mode 100644 index 00000000..a90e1c6a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Style/Supervisor.php @@ -0,0 +1,125 @@ +<?php + +/** + * PHPExcel_Style_Supervisor + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Style + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Style_Supervisor +{ + /** + * Supervisor? + * + * @var boolean + */ + protected $isSupervisor; + + /** + * Parent. Only used for supervisor + * + * @var PHPExcel_Style + */ + protected $parent; + + /** + * Create a new PHPExcel_Style_Alignment + * + * @param boolean $isSupervisor Flag indicating if this is a supervisor or not + * Leave this value at default unless you understand exactly what + * its ramifications are + */ + public function __construct($isSupervisor = false) + { + // Supervisor? + $this->isSupervisor = $isSupervisor; + } + + /** + * Bind parent. Only used for supervisor + * + * @param PHPExcel $parent + * @return PHPExcel_Style_Supervisor + */ + public function bindParent($parent, $parentPropertyName = null) + { + $this->parent = $parent; + return $this; + } + + /** + * Is this a supervisor or a cell style component? + * + * @return boolean + */ + public function getIsSupervisor() + { + return $this->isSupervisor; + } + + /** + * Get the currently active sheet. Only used for supervisor + * + * @return PHPExcel_Worksheet + */ + public function getActiveSheet() + { + return $this->parent->getActiveSheet(); + } + + /** + * Get the currently active cell coordinate in currently active sheet. + * Only used for supervisor + * + * @return string E.g. 'A1' + */ + public function getSelectedCells() + { + return $this->getActiveSheet()->getSelectedCells(); + } + + /** + * Get the currently active cell coordinate in currently active sheet. + * Only used for supervisor + * + * @return string E.g. 'A1' + */ + public function getActiveCell() + { + return $this->getActiveSheet()->getActiveCell(); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if ((is_object($value)) && ($key != 'parent')) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet.php new file mode 100644 index 00000000..483aa002 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet.php @@ -0,0 +1,2968 @@ +<?php + +/** + * PHPExcel_Worksheet + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet implements PHPExcel_IComparable +{ + /* Break types */ + const BREAK_NONE = 0; + const BREAK_ROW = 1; + const BREAK_COLUMN = 2; + + /* Sheet state */ + const SHEETSTATE_VISIBLE = 'visible'; + const SHEETSTATE_HIDDEN = 'hidden'; + const SHEETSTATE_VERYHIDDEN = 'veryHidden'; + + /** + * Invalid characters in sheet title + * + * @var array + */ + private static $invalidCharacters = array('*', ':', '/', '\\', '?', '[', ']'); + + /** + * Parent spreadsheet + * + * @var PHPExcel + */ + private $parent; + + /** + * Cacheable collection of cells + * + * @var PHPExcel_CachedObjectStorage_xxx + */ + private $cellCollection; + + /** + * Collection of row dimensions + * + * @var PHPExcel_Worksheet_RowDimension[] + */ + private $rowDimensions = array(); + + /** + * Default row dimension + * + * @var PHPExcel_Worksheet_RowDimension + */ + private $defaultRowDimension; + + /** + * Collection of column dimensions + * + * @var PHPExcel_Worksheet_ColumnDimension[] + */ + private $columnDimensions = array(); + + /** + * Default column dimension + * + * @var PHPExcel_Worksheet_ColumnDimension + */ + private $defaultColumnDimension = null; + + /** + * Collection of drawings + * + * @var PHPExcel_Worksheet_BaseDrawing[] + */ + private $drawingCollection = null; + + /** + * Collection of Chart objects + * + * @var PHPExcel_Chart[] + */ + private $chartCollection = array(); + + /** + * Worksheet title + * + * @var string + */ + private $title; + + /** + * Sheet state + * + * @var string + */ + private $sheetState; + + /** + * Page setup + * + * @var PHPExcel_Worksheet_PageSetup + */ + private $pageSetup; + + /** + * Page margins + * + * @var PHPExcel_Worksheet_PageMargins + */ + private $pageMargins; + + /** + * Page header/footer + * + * @var PHPExcel_Worksheet_HeaderFooter + */ + private $headerFooter; + + /** + * Sheet view + * + * @var PHPExcel_Worksheet_SheetView + */ + private $sheetView; + + /** + * Protection + * + * @var PHPExcel_Worksheet_Protection + */ + private $protection; + + /** + * Collection of styles + * + * @var PHPExcel_Style[] + */ + private $styles = array(); + + /** + * Conditional styles. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $conditionalStylesCollection = array(); + + /** + * Is the current cell collection sorted already? + * + * @var boolean + */ + private $cellCollectionIsSorted = false; + + /** + * Collection of breaks + * + * @var array + */ + private $breaks = array(); + + /** + * Collection of merged cell ranges + * + * @var array + */ + private $mergeCells = array(); + + /** + * Collection of protected cell ranges + * + * @var array + */ + private $protectedCells = array(); + + /** + * Autofilter Range and selection + * + * @var PHPExcel_Worksheet_AutoFilter + */ + private $autoFilter; + + /** + * Freeze pane + * + * @var string + */ + private $freezePane = ''; + + /** + * Show gridlines? + * + * @var boolean + */ + private $showGridlines = true; + + /** + * Print gridlines? + * + * @var boolean + */ + private $printGridlines = false; + + /** + * Show row and column headers? + * + * @var boolean + */ + private $showRowColHeaders = true; + + /** + * Show summary below? (Row/Column outline) + * + * @var boolean + */ + private $showSummaryBelow = true; + + /** + * Show summary right? (Row/Column outline) + * + * @var boolean + */ + private $showSummaryRight = true; + + /** + * Collection of comments + * + * @var PHPExcel_Comment[] + */ + private $comments = array(); + + /** + * Active cell. (Only one!) + * + * @var string + */ + private $activeCell = 'A1'; + + /** + * Selected cells + * + * @var string + */ + private $selectedCells = 'A1'; + + /** + * Cached highest column + * + * @var string + */ + private $cachedHighestColumn = 'A'; + + /** + * Cached highest row + * + * @var int + */ + private $cachedHighestRow = 1; + + /** + * Right-to-left? + * + * @var boolean + */ + private $rightToLeft = false; + + /** + * Hyperlinks. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $hyperlinkCollection = array(); + + /** + * Data validation objects. Indexed by cell coordinate, e.g. 'A1' + * + * @var array + */ + private $dataValidationCollection = array(); + + /** + * Tab color + * + * @var PHPExcel_Style_Color + */ + private $tabColor; + + /** + * Dirty flag + * + * @var boolean + */ + private $dirty = true; + + /** + * Hash + * + * @var string + */ + private $hash; + + /** + * CodeName + * + * @var string + */ + private $codeName = null; + + /** + * Create a new worksheet + * + * @param PHPExcel $pParent + * @param string $pTitle + */ + public function __construct(PHPExcel $pParent = null, $pTitle = 'Worksheet') + { + // Set parent and title + $this->parent = $pParent; + $this->setTitle($pTitle, false); + // setTitle can change $pTitle + $this->setCodeName($this->getTitle()); + $this->setSheetState(PHPExcel_Worksheet::SHEETSTATE_VISIBLE); + + $this->cellCollection = PHPExcel_CachedObjectStorageFactory::getInstance($this); + // Set page setup + $this->pageSetup = new PHPExcel_Worksheet_PageSetup(); + // Set page margins + $this->pageMargins = new PHPExcel_Worksheet_PageMargins(); + // Set page header/footer + $this->headerFooter = new PHPExcel_Worksheet_HeaderFooter(); + // Set sheet view + $this->sheetView = new PHPExcel_Worksheet_SheetView(); + // Drawing collection + $this->drawingCollection = new ArrayObject(); + // Chart collection + $this->chartCollection = new ArrayObject(); + // Protection + $this->protection = new PHPExcel_Worksheet_Protection(); + // Default row dimension + $this->defaultRowDimension = new PHPExcel_Worksheet_RowDimension(null); + // Default column dimension + $this->defaultColumnDimension = new PHPExcel_Worksheet_ColumnDimension(null); + $this->autoFilter = new PHPExcel_Worksheet_AutoFilter(null, $this); + } + + + /** + * Disconnect all cells from this PHPExcel_Worksheet object, + * typically so that the worksheet object can be unset + * + */ + public function disconnectCells() + { + if ($this->cellCollection !== null) { + $this->cellCollection->unsetWorksheetCells(); + $this->cellCollection = null; + } + // detach ourself from the workbook, so that it can then delete this worksheet successfully + $this->parent = null; + } + + /** + * Code to execute when this worksheet is unset() + * + */ + public function __destruct() + { + PHPExcel_Calculation::getInstance($this->parent)->clearCalculationCacheForWorksheet($this->title); + + $this->disconnectCells(); + } + + /** + * Return the cache controller for the cell collection + * + * @return PHPExcel_CachedObjectStorage_xxx + */ + public function getCellCacheController() + { + return $this->cellCollection; + } + + + /** + * Get array of invalid characters for sheet title + * + * @return array + */ + public static function getInvalidCharacters() + { + return self::$invalidCharacters; + } + + /** + * Check sheet code name for valid Excel syntax + * + * @param string $pValue The string to check + * @return string The valid string + * @throws Exception + */ + private static function checkSheetCodeName($pValue) + { + $CharCount = PHPExcel_Shared_String::CountCharacters($pValue); + if ($CharCount == 0) { + throw new PHPExcel_Exception('Sheet code name cannot be empty.'); + } + // Some of the printable ASCII characters are invalid: * : / \ ? [ ] and first and last characters cannot be a "'" + if ((str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) || + (PHPExcel_Shared_String::Substring($pValue, -1, 1)=='\'') || + (PHPExcel_Shared_String::Substring($pValue, 0, 1)=='\'')) { + throw new PHPExcel_Exception('Invalid character found in sheet code name'); + } + + // Maximum 31 characters allowed for sheet title + if ($CharCount > 31) { + throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet code name.'); + } + + return $pValue; + } + + /** + * Check sheet title for valid Excel syntax + * + * @param string $pValue The string to check + * @return string The valid string + * @throws PHPExcel_Exception + */ + private static function checkSheetTitle($pValue) + { + // Some of the printable ASCII characters are invalid: * : / \ ? [ ] + if (str_replace(self::$invalidCharacters, '', $pValue) !== $pValue) { + throw new PHPExcel_Exception('Invalid character found in sheet title'); + } + + // Maximum 31 characters allowed for sheet title + if (PHPExcel_Shared_String::CountCharacters($pValue) > 31) { + throw new PHPExcel_Exception('Maximum 31 characters allowed in sheet title.'); + } + + return $pValue; + } + + /** + * Get collection of cells + * + * @param boolean $pSorted Also sort the cell collection? + * @return PHPExcel_Cell[] + */ + public function getCellCollection($pSorted = true) + { + if ($pSorted) { + // Re-order cell collection + return $this->sortCellCollection(); + } + if ($this->cellCollection !== null) { + return $this->cellCollection->getCellList(); + } + return array(); + } + + /** + * Sort collection of cells + * + * @return PHPExcel_Worksheet + */ + public function sortCellCollection() + { + if ($this->cellCollection !== null) { + return $this->cellCollection->getSortedCellList(); + } + return array(); + } + + /** + * Get collection of row dimensions + * + * @return PHPExcel_Worksheet_RowDimension[] + */ + public function getRowDimensions() + { + return $this->rowDimensions; + } + + /** + * Get default row dimension + * + * @return PHPExcel_Worksheet_RowDimension + */ + public function getDefaultRowDimension() + { + return $this->defaultRowDimension; + } + + /** + * Get collection of column dimensions + * + * @return PHPExcel_Worksheet_ColumnDimension[] + */ + public function getColumnDimensions() + { + return $this->columnDimensions; + } + + /** + * Get default column dimension + * + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getDefaultColumnDimension() + { + return $this->defaultColumnDimension; + } + + /** + * Get collection of drawings + * + * @return PHPExcel_Worksheet_BaseDrawing[] + */ + public function getDrawingCollection() + { + return $this->drawingCollection; + } + + /** + * Get collection of charts + * + * @return PHPExcel_Chart[] + */ + public function getChartCollection() + { + return $this->chartCollection; + } + + /** + * Add chart + * + * @param PHPExcel_Chart $pChart + * @param int|null $iChartIndex Index where chart should go (0,1,..., or null for last) + * @return PHPExcel_Chart + */ + public function addChart(PHPExcel_Chart $pChart = null, $iChartIndex = null) + { + $pChart->setWorksheet($this); + if (is_null($iChartIndex)) { + $this->chartCollection[] = $pChart; + } else { + // Insert the chart at the requested index + array_splice($this->chartCollection, $iChartIndex, 0, array($pChart)); + } + + return $pChart; + } + + /** + * Return the count of charts on this worksheet + * + * @return int The number of charts + */ + public function getChartCount() + { + return count($this->chartCollection); + } + + /** + * Get a chart by its index position + * + * @param string $index Chart index position + * @return false|PHPExcel_Chart + * @throws PHPExcel_Exception + */ + public function getChartByIndex($index = null) + { + $chartCount = count($this->chartCollection); + if ($chartCount == 0) { + return false; + } + if (is_null($index)) { + $index = --$chartCount; + } + if (!isset($this->chartCollection[$index])) { + return false; + } + + return $this->chartCollection[$index]; + } + + /** + * Return an array of the names of charts on this worksheet + * + * @return string[] The names of charts + * @throws PHPExcel_Exception + */ + public function getChartNames() + { + $chartNames = array(); + foreach ($this->chartCollection as $chart) { + $chartNames[] = $chart->getName(); + } + return $chartNames; + } + + /** + * Get a chart by name + * + * @param string $chartName Chart name + * @return false|PHPExcel_Chart + * @throws PHPExcel_Exception + */ + public function getChartByName($chartName = '') + { + $chartCount = count($this->chartCollection); + if ($chartCount == 0) { + return false; + } + foreach ($this->chartCollection as $index => $chart) { + if ($chart->getName() == $chartName) { + return $this->chartCollection[$index]; + } + } + return false; + } + + /** + * Refresh column dimensions + * + * @return PHPExcel_Worksheet + */ + public function refreshColumnDimensions() + { + $currentColumnDimensions = $this->getColumnDimensions(); + $newColumnDimensions = array(); + + foreach ($currentColumnDimensions as $objColumnDimension) { + $newColumnDimensions[$objColumnDimension->getColumnIndex()] = $objColumnDimension; + } + + $this->columnDimensions = $newColumnDimensions; + + return $this; + } + + /** + * Refresh row dimensions + * + * @return PHPExcel_Worksheet + */ + public function refreshRowDimensions() + { + $currentRowDimensions = $this->getRowDimensions(); + $newRowDimensions = array(); + + foreach ($currentRowDimensions as $objRowDimension) { + $newRowDimensions[$objRowDimension->getRowIndex()] = $objRowDimension; + } + + $this->rowDimensions = $newRowDimensions; + + return $this; + } + + /** + * Calculate worksheet dimension + * + * @return string String containing the dimension of this worksheet + */ + public function calculateWorksheetDimension() + { + // Return + return 'A1' . ':' . $this->getHighestColumn() . $this->getHighestRow(); + } + + /** + * Calculate worksheet data dimension + * + * @return string String containing the dimension of this worksheet that actually contain data + */ + public function calculateWorksheetDataDimension() + { + // Return + return 'A1' . ':' . $this->getHighestDataColumn() . $this->getHighestDataRow(); + } + + /** + * Calculate widths for auto-size columns + * + * @param boolean $calculateMergeCells Calculate merge cell width + * @return PHPExcel_Worksheet; + */ + public function calculateColumnWidths($calculateMergeCells = false) + { + // initialize $autoSizes array + $autoSizes = array(); + foreach ($this->getColumnDimensions() as $colDimension) { + if ($colDimension->getAutoSize()) { + $autoSizes[$colDimension->getColumnIndex()] = -1; + } + } + + // There is only something to do if there are some auto-size columns + if (!empty($autoSizes)) { + // build list of cells references that participate in a merge + $isMergeCell = array(); + foreach ($this->getMergeCells() as $cells) { + foreach (PHPExcel_Cell::extractAllCellReferencesInRange($cells) as $cellReference) { + $isMergeCell[$cellReference] = true; + } + } + + // loop through all cells in the worksheet + foreach ($this->getCellCollection(false) as $cellID) { + $cell = $this->getCell($cellID, false); + if ($cell !== null && isset($autoSizes[$this->cellCollection->getCurrentColumn()])) { + // Determine width if cell does not participate in a merge + if (!isset($isMergeCell[$this->cellCollection->getCurrentAddress()])) { + // Calculated value + // To formatted string + $cellValue = PHPExcel_Style_NumberFormat::toFormattedString( + $cell->getCalculatedValue(), + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode() + ); + + $autoSizes[$this->cellCollection->getCurrentColumn()] = max( + (float) $autoSizes[$this->cellCollection->getCurrentColumn()], + (float)PHPExcel_Shared_Font::calculateColumnWidth( + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont(), + $cellValue, + $this->getParent()->getCellXfByIndex($cell->getXfIndex())->getAlignment()->getTextRotation(), + $this->getDefaultStyle()->getFont() + ) + ); + } + } + } + + // adjust column widths + foreach ($autoSizes as $columnIndex => $width) { + if ($width == -1) { + $width = $this->getDefaultColumnDimension()->getWidth(); + } + $this->getColumnDimension($columnIndex)->setWidth($width); + } + } + + return $this; + } + + /** + * Get parent + * + * @return PHPExcel + */ + public function getParent() + { + return $this->parent; + } + + /** + * Re-bind parent + * + * @param PHPExcel $parent + * @return PHPExcel_Worksheet + */ + public function rebindParent(PHPExcel $parent) + { + if ($this->parent !== null) { + $namedRanges = $this->parent->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + $parent->addNamedRange($namedRange); + } + + $this->parent->removeSheetByIndex( + $this->parent->getIndex($this) + ); + } + $this->parent = $parent; + + return $this; + } + + /** + * Get title + * + * @return string + */ + public function getTitle() + { + return $this->title; + } + + /** + * Set title + * + * @param string $pValue String containing the dimension of this worksheet + * @param string $updateFormulaCellReferences boolean Flag indicating whether cell references in formulae should + * be updated to reflect the new sheet name. + * This should be left as the default true, unless you are + * certain that no formula cells on any worksheet contain + * references to this worksheet + * @return PHPExcel_Worksheet + */ + public function setTitle($pValue = 'Worksheet', $updateFormulaCellReferences = true) + { + // Is this a 'rename' or not? + if ($this->getTitle() == $pValue) { + return $this; + } + + // Syntax check + self::checkSheetTitle($pValue); + + // Old title + $oldTitle = $this->getTitle(); + + if ($this->parent) { + // Is there already such sheet name? + if ($this->parent->sheetNameExists($pValue)) { + // Use name, but append with lowest possible integer + + if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 29); + } + $i = 1; + while ($this->parent->sheetNameExists($pValue . ' ' . $i)) { + ++$i; + if ($i == 10) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 28); + } + } elseif ($i == 100) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 27); + } + } + } + + $altTitle = $pValue . ' ' . $i; + return $this->setTitle($altTitle, $updateFormulaCellReferences); + } + } + + // Set title + $this->title = $pValue; + $this->dirty = true; + + if ($this->parent && $this->parent->getCalculationEngine()) { + // New title + $newTitle = $this->getTitle(); + $this->parent->getCalculationEngine() + ->renameCalculationCacheForWorksheet($oldTitle, $newTitle); + if ($updateFormulaCellReferences) { + PHPExcel_ReferenceHelper::getInstance()->updateNamedFormulas($this->parent, $oldTitle, $newTitle); + } + } + + return $this; + } + + /** + * Get sheet state + * + * @return string Sheet state (visible, hidden, veryHidden) + */ + public function getSheetState() + { + return $this->sheetState; + } + + /** + * Set sheet state + * + * @param string $value Sheet state (visible, hidden, veryHidden) + * @return PHPExcel_Worksheet + */ + public function setSheetState($value = PHPExcel_Worksheet::SHEETSTATE_VISIBLE) + { + $this->sheetState = $value; + return $this; + } + + /** + * Get page setup + * + * @return PHPExcel_Worksheet_PageSetup + */ + public function getPageSetup() + { + return $this->pageSetup; + } + + /** + * Set page setup + * + * @param PHPExcel_Worksheet_PageSetup $pValue + * @return PHPExcel_Worksheet + */ + public function setPageSetup(PHPExcel_Worksheet_PageSetup $pValue) + { + $this->pageSetup = $pValue; + return $this; + } + + /** + * Get page margins + * + * @return PHPExcel_Worksheet_PageMargins + */ + public function getPageMargins() + { + return $this->pageMargins; + } + + /** + * Set page margins + * + * @param PHPExcel_Worksheet_PageMargins $pValue + * @return PHPExcel_Worksheet + */ + public function setPageMargins(PHPExcel_Worksheet_PageMargins $pValue) + { + $this->pageMargins = $pValue; + return $this; + } + + /** + * Get page header/footer + * + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function getHeaderFooter() + { + return $this->headerFooter; + } + + /** + * Set page header/footer + * + * @param PHPExcel_Worksheet_HeaderFooter $pValue + * @return PHPExcel_Worksheet + */ + public function setHeaderFooter(PHPExcel_Worksheet_HeaderFooter $pValue) + { + $this->headerFooter = $pValue; + return $this; + } + + /** + * Get sheet view + * + * @return PHPExcel_Worksheet_SheetView + */ + public function getSheetView() + { + return $this->sheetView; + } + + /** + * Set sheet view + * + * @param PHPExcel_Worksheet_SheetView $pValue + * @return PHPExcel_Worksheet + */ + public function setSheetView(PHPExcel_Worksheet_SheetView $pValue) + { + $this->sheetView = $pValue; + return $this; + } + + /** + * Get Protection + * + * @return PHPExcel_Worksheet_Protection + */ + public function getProtection() + { + return $this->protection; + } + + /** + * Set Protection + * + * @param PHPExcel_Worksheet_Protection $pValue + * @return PHPExcel_Worksheet + */ + public function setProtection(PHPExcel_Worksheet_Protection $pValue) + { + $this->protection = $pValue; + $this->dirty = true; + + return $this; + } + + /** + * Get highest worksheet column + * + * @param string $row Return the data highest column for the specified row, + * or the highest column of any row if no row number is passed + * @return string Highest column name + */ + public function getHighestColumn($row = null) + { + if ($row == null) { + return $this->cachedHighestColumn; + } + return $this->getHighestDataColumn($row); + } + + /** + * Get highest worksheet column that contains data + * + * @param string $row Return the highest data column for the specified row, + * or the highest data column of any row if no row number is passed + * @return string Highest column name that contains data + */ + public function getHighestDataColumn($row = null) + { + return $this->cellCollection->getHighestColumn($row); + } + + /** + * Get highest worksheet row + * + * @param string $column Return the highest data row for the specified column, + * or the highest row of any column if no column letter is passed + * @return int Highest row number + */ + public function getHighestRow($column = null) + { + if ($column == null) { + return $this->cachedHighestRow; + } + return $this->getHighestDataRow($column); + } + + /** + * Get highest worksheet row that contains data + * + * @param string $column Return the highest data row for the specified column, + * or the highest data row of any column if no column letter is passed + * @return string Highest row number that contains data + */ + public function getHighestDataRow($column = null) + { + return $this->cellCollection->getHighestRow($column); + } + + /** + * Get highest worksheet column and highest row that have cell records + * + * @return array Highest column name and highest row number + */ + public function getHighestRowAndColumn() + { + return $this->cellCollection->getHighestRowAndColumn(); + } + + /** + * Set a cell value + * + * @param string $pCoordinate Coordinate of the cell + * @param mixed $pValue Value of the cell + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValue($pCoordinate = 'A1', $pValue = null, $returnCell = false) + { + $cell = $this->getCell(strtoupper($pCoordinate))->setValue($pValue); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell (A = 0) + * @param string $pRow Numeric row coordinate of the cell + * @param mixed $pValue Value of the cell + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $returnCell = false) + { + $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValue($pValue); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value + * + * @param string $pCoordinate Coordinate of the cell + * @param mixed $pValue Value of the cell + * @param string $pDataType Explicit data type + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueExplicit($pCoordinate = 'A1', $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false) + { + // Set value + $cell = $this->getCell(strtoupper($pCoordinate))->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; + } + + /** + * Set a cell value by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell + * @param string $pRow Numeric row coordinate of the cell + * @param mixed $pValue Value of the cell + * @param string $pDataType Explicit data type + * @param bool $returnCell Return the worksheet (false, default) or the cell (true) + * @return PHPExcel_Worksheet|PHPExcel_Cell Depending on the last parameter being specified + */ + public function setCellValueExplicitByColumnAndRow($pColumn = 0, $pRow = 1, $pValue = null, $pDataType = PHPExcel_Cell_DataType::TYPE_STRING, $returnCell = false) + { + $cell = $this->getCellByColumnAndRow($pColumn, $pRow)->setValueExplicit($pValue, $pDataType); + return ($returnCell) ? $cell : $this; + } + + /** + * Get cell at a specific coordinate + * + * @param string $pCoordinate Coordinate of the cell + * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't + * already exist, or a null should be returned instead + * @throws PHPExcel_Exception + * @return null|PHPExcel_Cell Cell that was found/created or null + */ + public function getCell($pCoordinate = 'A1', $createIfNotExists = true) + { + // Check cell collection + if ($this->cellCollection->isDataSet(strtoupper($pCoordinate))) { + return $this->cellCollection->getCacheData($pCoordinate); + } + + // Worksheet reference? + if (strpos($pCoordinate, '!') !== false) { + $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true); + return $this->parent->getSheetByName($worksheetReference[0])->getCell(strtoupper($worksheetReference[1]), $createIfNotExists); + } + + // Named range? + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && + (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this); + if ($namedRange !== null) { + $pCoordinate = $namedRange->getRange(); + return $namedRange->getWorksheet()->getCell($pCoordinate, $createIfNotExists); + } + } + + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) { + throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.'); + } elseif (strpos($pCoordinate, '$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } + + // Create new cell object, if required + return $createIfNotExists ? $this->createNewCell($pCoordinate) : null; + } + + /** + * Get cell at a specific coordinate by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell (starting from 0) + * @param string $pRow Numeric row coordinate of the cell + * @param boolean $createIfNotExists Flag indicating whether a new cell should be created if it doesn't + * already exist, or a null should be returned instead + * @return null|PHPExcel_Cell Cell that was found/created or null + */ + public function getCellByColumnAndRow($pColumn = 0, $pRow = 1, $createIfNotExists = true) + { + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($pColumn); + $coordinate = $columnLetter . $pRow; + + if ($this->cellCollection->isDataSet($coordinate)) { + return $this->cellCollection->getCacheData($coordinate); + } + + // Create new cell object, if required + return $createIfNotExists ? $this->createNewCell($coordinate) : null; + } + + /** + * Create a new cell at the specified coordinate + * + * @param string $pCoordinate Coordinate of the cell + * @return PHPExcel_Cell Cell that was created + */ + private function createNewCell($pCoordinate) + { + $cell = $this->cellCollection->addCacheData( + $pCoordinate, + new PHPExcel_Cell(null, PHPExcel_Cell_DataType::TYPE_NULL, $this) + ); + $this->cellCollectionIsSorted = false; + + // Coordinates + $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); + if (PHPExcel_Cell::columnIndexFromString($this->cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($aCoordinates[0])) { + $this->cachedHighestColumn = $aCoordinates[0]; + } + $this->cachedHighestRow = max($this->cachedHighestRow, $aCoordinates[1]); + + // Cell needs appropriate xfIndex from dimensions records + // but don't create dimension records if they don't already exist + $rowDimension = $this->getRowDimension($aCoordinates[1], false); + $columnDimension = $this->getColumnDimension($aCoordinates[0], false); + + if ($rowDimension !== null && $rowDimension->getXfIndex() > 0) { + // then there is a row dimension with explicit style, assign it to the cell + $cell->setXfIndex($rowDimension->getXfIndex()); + } elseif ($columnDimension !== null && $columnDimension->getXfIndex() > 0) { + // then there is a column dimension, assign it to the cell + $cell->setXfIndex($columnDimension->getXfIndex()); + } + + return $cell; + } + + /** + * Does the cell at a specific coordinate exist? + * + * @param string $pCoordinate Coordinate of the cell + * @throws PHPExcel_Exception + * @return boolean + */ + public function cellExists($pCoordinate = 'A1') + { + // Worksheet reference? + if (strpos($pCoordinate, '!') !== false) { + $worksheetReference = PHPExcel_Worksheet::extractSheetTitle($pCoordinate, true); + return $this->parent->getSheetByName($worksheetReference[0])->cellExists(strtoupper($worksheetReference[1])); + } + + // Named range? + if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $pCoordinate, $matches)) && + (preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $pCoordinate, $matches))) { + $namedRange = PHPExcel_NamedRange::resolveRange($pCoordinate, $this); + if ($namedRange !== null) { + $pCoordinate = $namedRange->getRange(); + if ($this->getHashCode() != $namedRange->getWorksheet()->getHashCode()) { + if (!$namedRange->getLocalOnly()) { + return $namedRange->getWorksheet()->cellExists($pCoordinate); + } else { + throw new PHPExcel_Exception('Named range ' . $namedRange->getName() . ' is not accessible from within sheet ' . $this->getTitle()); + } + } + } else { + return false; + } + } + + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) { + throw new PHPExcel_Exception('Cell coordinate can not be a range of cells.'); + } elseif (strpos($pCoordinate, '$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } else { + // Coordinates + $aCoordinates = PHPExcel_Cell::coordinateFromString($pCoordinate); + + // Cell exists? + return $this->cellCollection->isDataSet($pCoordinate); + } + } + + /** + * Cell at a specific coordinate by using numeric cell coordinates exists? + * + * @param string $pColumn Numeric column coordinate of the cell + * @param string $pRow Numeric row coordinate of the cell + * @return boolean + */ + public function cellExistsByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->cellExists(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get row dimension at a specific row + * + * @param int $pRow Numeric index of the row + * @return PHPExcel_Worksheet_RowDimension + */ + public function getRowDimension($pRow = 1, $create = true) + { + // Found + $found = null; + + // Get row dimension + if (!isset($this->rowDimensions[$pRow])) { + if (!$create) { + return null; + } + $this->rowDimensions[$pRow] = new PHPExcel_Worksheet_RowDimension($pRow); + + $this->cachedHighestRow = max($this->cachedHighestRow, $pRow); + } + return $this->rowDimensions[$pRow]; + } + + /** + * Get column dimension at a specific column + * + * @param string $pColumn String index of the column + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getColumnDimension($pColumn = 'A', $create = true) + { + // Uppercase coordinate + $pColumn = strtoupper($pColumn); + + // Fetch dimensions + if (!isset($this->columnDimensions[$pColumn])) { + if (!$create) { + return null; + } + $this->columnDimensions[$pColumn] = new PHPExcel_Worksheet_ColumnDimension($pColumn); + + if (PHPExcel_Cell::columnIndexFromString($this->cachedHighestColumn) < PHPExcel_Cell::columnIndexFromString($pColumn)) { + $this->cachedHighestColumn = $pColumn; + } + } + return $this->columnDimensions[$pColumn]; + } + + /** + * Get column dimension at a specific column by using numeric cell coordinates + * + * @param string $pColumn Numeric column coordinate of the cell + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function getColumnDimensionByColumn($pColumn = 0) + { + return $this->getColumnDimension(PHPExcel_Cell::stringFromColumnIndex($pColumn)); + } + + /** + * Get styles + * + * @return PHPExcel_Style[] + */ + public function getStyles() + { + return $this->styles; + } + + /** + * Get default style of workbook. + * + * @deprecated + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getDefaultStyle() + { + return $this->parent->getDefaultStyle(); + } + + /** + * Set default style - should only be used by PHPExcel_IReader implementations! + * + * @deprecated + * @param PHPExcel_Style $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setDefaultStyle(PHPExcel_Style $pValue) + { + $this->parent->getDefaultStyle()->applyFromArray(array( + 'font' => array( + 'name' => $pValue->getFont()->getName(), + 'size' => $pValue->getFont()->getSize(), + ), + )); + return $this; + } + + /** + * Get style for cell + * + * @param string $pCellCoordinate Cell coordinate (or range) to get style for + * @return PHPExcel_Style + * @throws PHPExcel_Exception + */ + public function getStyle($pCellCoordinate = 'A1') + { + // set this sheet as active + $this->parent->setActiveSheetIndex($this->parent->getIndex($this)); + + // set cell coordinate as active + $this->setSelectedCells(strtoupper($pCellCoordinate)); + + return $this->parent->getCellXfSupervisor(); + } + + /** + * Get conditional styles for a cell + * + * @param string $pCoordinate + * @return PHPExcel_Style_Conditional[] + */ + public function getConditionalStyles($pCoordinate = 'A1') + { + $pCoordinate = strtoupper($pCoordinate); + if (!isset($this->conditionalStylesCollection[$pCoordinate])) { + $this->conditionalStylesCollection[$pCoordinate] = array(); + } + return $this->conditionalStylesCollection[$pCoordinate]; + } + + /** + * Do conditional styles exist for this cell? + * + * @param string $pCoordinate + * @return boolean + */ + public function conditionalStylesExists($pCoordinate = 'A1') + { + if (isset($this->conditionalStylesCollection[strtoupper($pCoordinate)])) { + return true; + } + return false; + } + + /** + * Removes conditional styles for a cell + * + * @param string $pCoordinate + * @return PHPExcel_Worksheet + */ + public function removeConditionalStyles($pCoordinate = 'A1') + { + unset($this->conditionalStylesCollection[strtoupper($pCoordinate)]); + return $this; + } + + /** + * Get collection of conditional styles + * + * @return array + */ + public function getConditionalStylesCollection() + { + return $this->conditionalStylesCollection; + } + + /** + * Set conditional styles + * + * @param $pCoordinate string E.g. 'A1' + * @param $pValue PHPExcel_Style_Conditional[] + * @return PHPExcel_Worksheet + */ + public function setConditionalStyles($pCoordinate = 'A1', $pValue) + { + $this->conditionalStylesCollection[strtoupper($pCoordinate)] = $pValue; + return $this; + } + + /** + * Get style for cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @param int pColumn2 Numeric column coordinate of the range cell + * @param int pRow2 Numeric row coordinate of the range cell + * @return PHPExcel_Style + */ + public function getStyleByColumnAndRow($pColumn = 0, $pRow = 1, $pColumn2 = null, $pRow2 = null) + { + if (!is_null($pColumn2) && !is_null($pRow2)) { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->getStyle($cellRange); + } + + return $this->getStyle(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Set shared cell style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @deprecated + * @param PHPExcel_Style $pSharedCellStyle Cell style to share + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSharedStyle(PHPExcel_Style $pSharedCellStyle = null, $pRange = '') + { + $this->duplicateStyle($pSharedCellStyle, $pRange); + return $this; + } + + /** + * Duplicate cell style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @param PHPExcel_Style $pCellStyle Cell style to duplicate + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateStyle(PHPExcel_Style $pCellStyle = null, $pRange = '') + { + // make sure we have a real style and not supervisor + $style = $pCellStyle->getIsSupervisor() ? $pCellStyle->getSharedComponent() : $pCellStyle; + + // Add the style to the workbook if necessary + $workbook = $this->parent; + if ($existingStyle = $this->parent->getCellXfByHashCode($pCellStyle->getHashCode())) { + // there is already such cell Xf in our collection + $xfIndex = $existingStyle->getIndex(); + } else { + // we don't have such a cell Xf, need to add + $workbook->addCellXf($pCellStyle); + $xfIndex = $pCellStyle->getIndex(); + } + + // Calculate range outer borders + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange); + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // Loop through cells and apply styles + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $this->getCell(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row)->setXfIndex($xfIndex); + } + } + + return $this; + } + + /** + * Duplicate conditional style to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range! + * + * @param array of PHPExcel_Style_Conditional $pCellStyle Cell style to duplicate + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateConditionalStyle(array $pCellStyle = null, $pRange = '') + { + foreach ($pCellStyle as $cellStyle) { + if (!($cellStyle instanceof PHPExcel_Style_Conditional)) { + throw new PHPExcel_Exception('Style is not a conditional style'); + } + } + + // Calculate range outer borders + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange . ':' . $pRange); + + // Make sure we can loop upwards on rows and columns + if ($rangeStart[0] > $rangeEnd[0] && $rangeStart[1] > $rangeEnd[1]) { + $tmp = $rangeStart; + $rangeStart = $rangeEnd; + $rangeEnd = $tmp; + } + + // Loop through cells and apply styles + for ($col = $rangeStart[0]; $col <= $rangeEnd[0]; ++$col) { + for ($row = $rangeStart[1]; $row <= $rangeEnd[1]; ++$row) { + $this->setConditionalStyles(PHPExcel_Cell::stringFromColumnIndex($col - 1) . $row, $pCellStyle); + } + } + + return $this; + } + + /** + * Duplicate cell style array to a range of cells + * + * Please note that this will overwrite existing cell styles for cells in range, + * if they are in the styles array. For example, if you decide to set a range of + * cells to font bold, only include font bold in the styles array. + * + * @deprecated + * @param array $pStyles Array containing style information + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @param boolean $pAdvanced Advanced mode for setting borders. + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function duplicateStyleArray($pStyles = null, $pRange = '', $pAdvanced = true) + { + $this->getStyle($pRange)->applyFromArray($pStyles, $pAdvanced); + return $this; + } + + /** + * Set break on a cell + * + * @param string $pCell Cell coordinate (e.g. A1) + * @param int $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setBreak($pCell = 'A1', $pBreak = PHPExcel_Worksheet::BREAK_NONE) + { + // Uppercase coordinate + $pCell = strtoupper($pCell); + + if ($pCell != '') { + if ($pBreak == PHPExcel_Worksheet::BREAK_NONE) { + if (isset($this->breaks[$pCell])) { + unset($this->breaks[$pCell]); + } + } else { + $this->breaks[$pCell] = $pBreak; + } + } else { + throw new PHPExcel_Exception('No cell coordinate specified.'); + } + + return $this; + } + + /** + * Set break on a cell by using numeric cell coordinates + * + * @param integer $pColumn Numeric column coordinate of the cell + * @param integer $pRow Numeric row coordinate of the cell + * @param integer $pBreak Break type (type of PHPExcel_Worksheet::BREAK_*) + * @return PHPExcel_Worksheet + */ + public function setBreakByColumnAndRow($pColumn = 0, $pRow = 1, $pBreak = PHPExcel_Worksheet::BREAK_NONE) + { + return $this->setBreak(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow, $pBreak); + } + + /** + * Get breaks + * + * @return array[] + */ + public function getBreaks() + { + return $this->breaks; + } + + /** + * Set merge on a cell range + * + * @param string $pRange Cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function mergeCells($pRange = 'A1:A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (strpos($pRange, ':') !== false) { + $this->mergeCells[$pRange] = $pRange; + + // make sure cells are created + + // get the cells in the range + $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange); + + // create upper left cell if it does not already exist + $upperLeft = $aReferences[0]; + if (!$this->cellExists($upperLeft)) { + $this->getCell($upperLeft)->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL); + } + + // Blank out the rest of the cells in the range (if they exist) + $count = count($aReferences); + for ($i = 1; $i < $count; $i++) { + if ($this->cellExists($aReferences[$i])) { + $this->getCell($aReferences[$i])->setValueExplicit(null, PHPExcel_Cell_DataType::TYPE_NULL); + } + } + } else { + throw new PHPExcel_Exception('Merge must be set on a range of cells.'); + } + + return $this; + } + + /** + * Set merge on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function mergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->mergeCells($cellRange); + } + + /** + * Remove merge on a cell range + * + * @param string $pRange Cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unmergeCells($pRange = 'A1:A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (strpos($pRange, ':') !== false) { + if (isset($this->mergeCells[$pRange])) { + unset($this->mergeCells[$pRange]); + } else { + throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as merged.'); + } + } else { + throw new PHPExcel_Exception('Merge can only be removed from a range of cells.'); + } + + return $this; + } + + /** + * Remove merge on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unmergeCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unmergeCells($cellRange); + } + + /** + * Get merge cells array. + * + * @return array[] + */ + public function getMergeCells() + { + return $this->mergeCells; + } + + /** + * Set merge cells array for the entire sheet. Use instead mergeCells() to merge + * a single cell range. + * + * @param array + */ + public function setMergeCells($pValue = array()) + { + $this->mergeCells = $pValue; + return $this; + } + + /** + * Set protection on a cell range + * + * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function protectCells($pRange = 'A1', $pPassword = '', $pAlreadyHashed = false) + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (!$pAlreadyHashed) { + $pPassword = PHPExcel_Shared_PasswordHasher::hashPassword($pPassword); + } + $this->protectedCells[$pRange] = $pPassword; + + return $this; + } + + /** + * Set protection on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function protectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->protectCells($cellRange, $pPassword, $pAlreadyHashed); + } + + /** + * Remove protection on a cell range + * + * @param string $pRange Cell (e.g. A1) or cell range (e.g. A1:E1) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unprotectCells($pRange = 'A1') + { + // Uppercase coordinate + $pRange = strtoupper($pRange); + + if (isset($this->protectedCells[$pRange])) { + unset($this->protectedCells[$pRange]); + } else { + throw new PHPExcel_Exception('Cell range ' . $pRange . ' not known as protected.'); + } + return $this; + } + + /** + * Remove protection on a cell range by using numeric cell coordinates + * + * @param int $pColumn1 Numeric column coordinate of the first cell + * @param int $pRow1 Numeric row coordinate of the first cell + * @param int $pColumn2 Numeric column coordinate of the last cell + * @param int $pRow2 Numeric row coordinate of the last cell + * @param string $pPassword Password to unlock the protection + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function unprotectCellsByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1, $pPassword = '', $pAlreadyHashed = false) + { + $cellRange = PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 . ':' . PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2; + return $this->unprotectCells($cellRange, $pPassword, $pAlreadyHashed); + } + + /** + * Get protected cells + * + * @return array[] + */ + public function getProtectedCells() + { + return $this->protectedCells; + } + + /** + * Get Autofilter + * + * @return PHPExcel_Worksheet_AutoFilter + */ + public function getAutoFilter() + { + return $this->autoFilter; + } + + /** + * Set AutoFilter + * + * @param PHPExcel_Worksheet_AutoFilter|string $pValue + * A simple string containing a Cell range like 'A1:E10' is permitted for backward compatibility + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setAutoFilter($pValue) + { + $pRange = strtoupper($pValue); + if (is_string($pValue)) { + $this->autoFilter->setRange($pValue); + } elseif (is_object($pValue) && ($pValue instanceof PHPExcel_Worksheet_AutoFilter)) { + $this->autoFilter = $pValue; + } + return $this; + } + + /** + * Set Autofilter Range by using numeric cell coordinates + * + * @param integer $pColumn1 Numeric column coordinate of the first cell + * @param integer $pRow1 Numeric row coordinate of the first cell + * @param integer $pColumn2 Numeric column coordinate of the second cell + * @param integer $pRow2 Numeric row coordinate of the second cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setAutoFilterByColumnAndRow($pColumn1 = 0, $pRow1 = 1, $pColumn2 = 0, $pRow2 = 1) + { + return $this->setAutoFilter( + PHPExcel_Cell::stringFromColumnIndex($pColumn1) . $pRow1 + . ':' . + PHPExcel_Cell::stringFromColumnIndex($pColumn2) . $pRow2 + ); + } + + /** + * Remove autofilter + * + * @return PHPExcel_Worksheet + */ + public function removeAutoFilter() + { + $this->autoFilter->setRange(null); + return $this; + } + + /** + * Get Freeze Pane + * + * @return string + */ + public function getFreezePane() + { + return $this->freezePane; + } + + /** + * Freeze Pane + * + * @param string $pCell Cell (i.e. A2) + * Examples: + * A2 will freeze the rows above cell A2 (i.e row 1) + * B1 will freeze the columns to the left of cell B1 (i.e column A) + * B2 will freeze the rows above and to the left of cell A2 + * (i.e row 1 and column A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function freezePane($pCell = '') + { + // Uppercase coordinate + $pCell = strtoupper($pCell); + if (strpos($pCell, ':') === false && strpos($pCell, ',') === false) { + $this->freezePane = $pCell; + } else { + throw new PHPExcel_Exception('Freeze pane can not be set on a range of cells.'); + } + return $this; + } + + /** + * Freeze Pane by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function freezePaneByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->freezePane(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Unfreeze Pane + * + * @return PHPExcel_Worksheet + */ + public function unfreezePane() + { + return $this->freezePane(''); + } + + /** + * Insert a new row, updating all possible related data + * + * @param int $pBefore Insert before this one + * @param int $pNumRows Number of rows to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewRowBefore($pBefore = 1, $pNumRows = 1) + { + if ($pBefore >= 1) { + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore('A' . $pBefore, 0, $pNumRows, $this); + } else { + throw new PHPExcel_Exception("Rows can only be inserted before at least row 1."); + } + return $this; + } + + /** + * Insert a new column, updating all possible related data + * + * @param int $pBefore Insert before this one + * @param int $pNumCols Number of columns to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewColumnBefore($pBefore = 'A', $pNumCols = 1) + { + if (!is_numeric($pBefore)) { + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore($pBefore . '1', $pNumCols, 0, $this); + } else { + throw new PHPExcel_Exception("Column references should not be numeric."); + } + return $this; + } + + /** + * Insert a new column, updating all possible related data + * + * @param int $pBefore Insert before this one (numeric column coordinate of the cell) + * @param int $pNumCols Number of columns to insert + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function insertNewColumnBeforeByIndex($pBefore = 0, $pNumCols = 1) + { + if ($pBefore >= 0) { + return $this->insertNewColumnBefore(PHPExcel_Cell::stringFromColumnIndex($pBefore), $pNumCols); + } else { + throw new PHPExcel_Exception("Columns can only be inserted before at least column A (0)."); + } + } + + /** + * Delete a row, updating all possible related data + * + * @param int $pRow Remove starting with this one + * @param int $pNumRows Number of rows to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeRow($pRow = 1, $pNumRows = 1) + { + if ($pRow >= 1) { + $highestRow = $this->getHighestDataRow(); + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore('A' . ($pRow + $pNumRows), 0, -$pNumRows, $this); + for ($r = 0; $r < $pNumRows; ++$r) { + $this->getCellCacheController()->removeRow($highestRow); + --$highestRow; + } + } else { + throw new PHPExcel_Exception("Rows to be deleted should at least start from row 1."); + } + return $this; + } + + /** + * Remove a column, updating all possible related data + * + * @param string $pColumn Remove starting with this one + * @param int $pNumCols Number of columns to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeColumn($pColumn = 'A', $pNumCols = 1) + { + if (!is_numeric($pColumn)) { + $highestColumn = $this->getHighestDataColumn(); + $pColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($pColumn) - 1 + $pNumCols); + $objReferenceHelper = PHPExcel_ReferenceHelper::getInstance(); + $objReferenceHelper->insertNewBefore($pColumn . '1', -$pNumCols, 0, $this); + for ($c = 0; $c < $pNumCols; ++$c) { + $this->getCellCacheController()->removeColumn($highestColumn); + $highestColumn = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($highestColumn) - 2); + } + } else { + throw new PHPExcel_Exception("Column references should not be numeric."); + } + return $this; + } + + /** + * Remove a column, updating all possible related data + * + * @param int $pColumn Remove starting with this one (numeric column coordinate of the cell) + * @param int $pNumCols Number of columns to remove + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function removeColumnByIndex($pColumn = 0, $pNumCols = 1) + { + if ($pColumn >= 0) { + return $this->removeColumn(PHPExcel_Cell::stringFromColumnIndex($pColumn), $pNumCols); + } else { + throw new PHPExcel_Exception("Columns to be deleted should at least start from column 0"); + } + } + + /** + * Show gridlines? + * + * @return boolean + */ + public function getShowGridlines() + { + return $this->showGridlines; + } + + /** + * Set show gridlines + * + * @param boolean $pValue Show gridlines (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowGridlines($pValue = false) + { + $this->showGridlines = $pValue; + return $this; + } + + /** + * Print gridlines? + * + * @return boolean + */ + public function getPrintGridlines() + { + return $this->printGridlines; + } + + /** + * Set print gridlines + * + * @param boolean $pValue Print gridlines (true/false) + * @return PHPExcel_Worksheet + */ + public function setPrintGridlines($pValue = false) + { + $this->printGridlines = $pValue; + return $this; + } + + /** + * Show row and column headers? + * + * @return boolean + */ + public function getShowRowColHeaders() + { + return $this->showRowColHeaders; + } + + /** + * Set show row and column headers + * + * @param boolean $pValue Show row and column headers (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowRowColHeaders($pValue = false) + { + $this->showRowColHeaders = $pValue; + return $this; + } + + /** + * Show summary below? (Row/Column outlining) + * + * @return boolean + */ + public function getShowSummaryBelow() + { + return $this->showSummaryBelow; + } + + /** + * Set show summary below + * + * @param boolean $pValue Show summary below (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowSummaryBelow($pValue = true) + { + $this->showSummaryBelow = $pValue; + return $this; + } + + /** + * Show summary right? (Row/Column outlining) + * + * @return boolean + */ + public function getShowSummaryRight() + { + return $this->showSummaryRight; + } + + /** + * Set show summary right + * + * @param boolean $pValue Show summary right (true/false) + * @return PHPExcel_Worksheet + */ + public function setShowSummaryRight($pValue = true) + { + $this->showSummaryRight = $pValue; + return $this; + } + + /** + * Get comments + * + * @return PHPExcel_Comment[] + */ + public function getComments() + { + return $this->comments; + } + + /** + * Set comments array for the entire sheet. + * + * @param array of PHPExcel_Comment + * @return PHPExcel_Worksheet + */ + public function setComments($pValue = array()) + { + $this->comments = $pValue; + + return $this; + } + + /** + * Get comment for cell + * + * @param string $pCellCoordinate Cell coordinate to get comment for + * @return PHPExcel_Comment + * @throws PHPExcel_Exception + */ + public function getComment($pCellCoordinate = 'A1') + { + // Uppercase coordinate + $pCellCoordinate = strtoupper($pCellCoordinate); + + if (strpos($pCellCoordinate, ':') !== false || strpos($pCellCoordinate, ',') !== false) { + throw new PHPExcel_Exception('Cell coordinate string can not be a range of cells.'); + } elseif (strpos($pCellCoordinate, '$') !== false) { + throw new PHPExcel_Exception('Cell coordinate string must not be absolute.'); + } elseif ($pCellCoordinate == '') { + throw new PHPExcel_Exception('Cell coordinate can not be zero-length string.'); + } else { + // Check if we already have a comment for this cell. + // If not, create a new comment. + if (isset($this->comments[$pCellCoordinate])) { + return $this->comments[$pCellCoordinate]; + } else { + $newComment = new PHPExcel_Comment(); + $this->comments[$pCellCoordinate] = $newComment; + return $newComment; + } + } + } + + /** + * Get comment for cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @return PHPExcel_Comment + */ + public function getCommentByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->getComment(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get selected cell + * + * @deprecated + * @return string + */ + public function getSelectedCell() + { + return $this->getSelectedCells(); + } + + /** + * Get active cell + * + * @return string Example: 'A1' + */ + public function getActiveCell() + { + return $this->activeCell; + } + + /** + * Get selected cells + * + * @return string + */ + public function getSelectedCells() + { + return $this->selectedCells; + } + + /** + * Selected cell + * + * @param string $pCoordinate Cell (i.e. A1) + * @return PHPExcel_Worksheet + */ + public function setSelectedCell($pCoordinate = 'A1') + { + return $this->setSelectedCells($pCoordinate); + } + + /** + * Select a range of cells. + * + * @param string $pCoordinate Cell range, examples: 'A1', 'B2:G5', 'A:C', '3:6' + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSelectedCells($pCoordinate = 'A1') + { + // Uppercase coordinate + $pCoordinate = strtoupper($pCoordinate); + + // Convert 'A' to 'A:A' + $pCoordinate = preg_replace('/^([A-Z]+)$/', '${1}:${1}', $pCoordinate); + + // Convert '1' to '1:1' + $pCoordinate = preg_replace('/^([0-9]+)$/', '${1}:${1}', $pCoordinate); + + // Convert 'A:C' to 'A1:C1048576' + $pCoordinate = preg_replace('/^([A-Z]+):([A-Z]+)$/', '${1}1:${2}1048576', $pCoordinate); + + // Convert '1:3' to 'A1:XFD3' + $pCoordinate = preg_replace('/^([0-9]+):([0-9]+)$/', 'A${1}:XFD${2}', $pCoordinate); + + if (strpos($pCoordinate, ':') !== false || strpos($pCoordinate, ',') !== false) { + list($first, ) = PHPExcel_Cell::splitRange($pCoordinate); + $this->activeCell = $first[0]; + } else { + $this->activeCell = $pCoordinate; + } + $this->selectedCells = $pCoordinate; + return $this; + } + + /** + * Selected cell by using numeric cell coordinates + * + * @param int $pColumn Numeric column coordinate of the cell + * @param int $pRow Numeric row coordinate of the cell + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function setSelectedCellByColumnAndRow($pColumn = 0, $pRow = 1) + { + return $this->setSelectedCells(PHPExcel_Cell::stringFromColumnIndex($pColumn) . $pRow); + } + + /** + * Get right-to-left + * + * @return boolean + */ + public function getRightToLeft() + { + return $this->rightToLeft; + } + + /** + * Set right-to-left + * + * @param boolean $value Right-to-left true/false + * @return PHPExcel_Worksheet + */ + public function setRightToLeft($value = false) + { + $this->rightToLeft = $value; + return $this; + } + + /** + * Fill worksheet from values in array + * + * @param array $source Source array + * @param mixed $nullValue Value in source array that stands for blank cell + * @param string $startCell Insert array starting from this cell address as the top left coordinate + * @param boolean $strictNullComparison Apply strict comparison when testing for null values in the array + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet + */ + public function fromArray($source = null, $nullValue = null, $startCell = 'A1', $strictNullComparison = false) + { + if (is_array($source)) { + // Convert a 1-D array to 2-D (for ease of looping) + if (!is_array(end($source))) { + $source = array($source); + } + + // start coordinate + list ($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($startCell); + + // Loop through $source + foreach ($source as $rowData) { + $currentColumn = $startColumn; + foreach ($rowData as $cellValue) { + if ($strictNullComparison) { + if ($cellValue !== $nullValue) { + // Set cell value + $this->getCell($currentColumn . $startRow)->setValue($cellValue); + } + } else { + if ($cellValue != $nullValue) { + // Set cell value + $this->getCell($currentColumn . $startRow)->setValue($cellValue); + } + } + ++$currentColumn; + } + ++$startRow; + } + } else { + throw new PHPExcel_Exception("Parameter \$source should be an array."); + } + return $this; + } + + /** + * Create array from a range of cells + * + * @param string $pRange Range of cells (i.e. "A1:B10"), or just one cell (i.e. "A1") + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + */ + public function rangeToArray($pRange = 'A1', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + { + // Returnvalue + $returnValue = array(); + // Identify the range that we need to extract from the worksheet + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($pRange); + $minCol = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] -1); + $minRow = $rangeStart[1]; + $maxCol = PHPExcel_Cell::stringFromColumnIndex($rangeEnd[0] -1); + $maxRow = $rangeEnd[1]; + + $maxCol++; + // Loop through rows + $r = -1; + for ($row = $minRow; $row <= $maxRow; ++$row) { + $rRef = ($returnCellRef) ? $row : ++$r; + $c = -1; + // Loop through columns in the current row + for ($col = $minCol; $col != $maxCol; ++$col) { + $cRef = ($returnCellRef) ? $col : ++$c; + // Using getCell() will create a new cell if it doesn't already exist. We don't want that to happen + // so we test and retrieve directly against cellCollection + if ($this->cellCollection->isDataSet($col.$row)) { + // Cell exists + $cell = $this->cellCollection->getCacheData($col.$row); + if ($cell->getValue() !== null) { + if ($cell->getValue() instanceof PHPExcel_RichText) { + $returnValue[$rRef][$cRef] = $cell->getValue()->getPlainText(); + } else { + if ($calculateFormulas) { + $returnValue[$rRef][$cRef] = $cell->getCalculatedValue(); + } else { + $returnValue[$rRef][$cRef] = $cell->getValue(); + } + } + + if ($formatData) { + $style = $this->parent->getCellXfByIndex($cell->getXfIndex()); + $returnValue[$rRef][$cRef] = PHPExcel_Style_NumberFormat::toFormattedString( + $returnValue[$rRef][$cRef], + ($style && $style->getNumberFormat()) ? $style->getNumberFormat()->getFormatCode() : PHPExcel_Style_NumberFormat::FORMAT_GENERAL + ); + } + } else { + // Cell holds a NULL + $returnValue[$rRef][$cRef] = $nullValue; + } + } else { + // Cell doesn't exist + $returnValue[$rRef][$cRef] = $nullValue; + } + } + } + + // Return + return $returnValue; + } + + + /** + * Create array from a range of cells + * + * @param string $pNamedRange Name of the Named Range + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + * @throws PHPExcel_Exception + */ + public function namedRangeToArray($pNamedRange = '', $nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + { + $namedRange = PHPExcel_NamedRange::resolveRange($pNamedRange, $this); + if ($namedRange !== null) { + $pWorkSheet = $namedRange->getWorksheet(); + $pCellRange = $namedRange->getRange(); + + return $pWorkSheet->rangeToArray($pCellRange, $nullValue, $calculateFormulas, $formatData, $returnCellRef); + } + + throw new PHPExcel_Exception('Named Range '.$pNamedRange.' does not exist.'); + } + + + /** + * Create array from worksheet + * + * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist + * @param boolean $calculateFormulas Should formulas be calculated? + * @param boolean $formatData Should formatting be applied to cell values? + * @param boolean $returnCellRef False - Return a simple array of rows and columns indexed by number counting from zero + * True - Return rows and columns indexed by their actual row and column IDs + * @return array + */ + public function toArray($nullValue = null, $calculateFormulas = true, $formatData = true, $returnCellRef = false) + { + // Garbage collect... + $this->garbageCollect(); + + // Identify the range that we need to extract from the worksheet + $maxCol = $this->getHighestColumn(); + $maxRow = $this->getHighestRow(); + // Return + return $this->rangeToArray('A1:'.$maxCol.$maxRow, $nullValue, $calculateFormulas, $formatData, $returnCellRef); + } + + /** + * Get row iterator + * + * @param integer $startRow The row number at which to start iterating + * @param integer $endRow The row number at which to stop iterating + * + * @return PHPExcel_Worksheet_RowIterator + */ + public function getRowIterator($startRow = 1, $endRow = null) + { + return new PHPExcel_Worksheet_RowIterator($this, $startRow, $endRow); + } + + /** + * Get column iterator + * + * @param string $startColumn The column address at which to start iterating + * @param string $endColumn The column address at which to stop iterating + * + * @return PHPExcel_Worksheet_ColumnIterator + */ + public function getColumnIterator($startColumn = 'A', $endColumn = null) + { + return new PHPExcel_Worksheet_ColumnIterator($this, $startColumn, $endColumn); + } + + /** + * Run PHPExcel garabage collector. + * + * @return PHPExcel_Worksheet + */ + public function garbageCollect() + { + // Flush cache + $this->cellCollection->getCacheData('A1'); + // Build a reference table from images +// $imageCoordinates = array(); +// $iterator = $this->getDrawingCollection()->getIterator(); +// while ($iterator->valid()) { +// $imageCoordinates[$iterator->current()->getCoordinates()] = true; +// +// $iterator->next(); +// } +// + // Lookup highest column and highest row if cells are cleaned + $colRow = $this->cellCollection->getHighestRowAndColumn(); + $highestRow = $colRow['row']; + $highestColumn = PHPExcel_Cell::columnIndexFromString($colRow['column']); + + // Loop through column dimensions + foreach ($this->columnDimensions as $dimension) { + $highestColumn = max($highestColumn, PHPExcel_Cell::columnIndexFromString($dimension->getColumnIndex())); + } + + // Loop through row dimensions + foreach ($this->rowDimensions as $dimension) { + $highestRow = max($highestRow, $dimension->getRowIndex()); + } + + // Cache values + if ($highestColumn < 0) { + $this->cachedHighestColumn = 'A'; + } else { + $this->cachedHighestColumn = PHPExcel_Cell::stringFromColumnIndex(--$highestColumn); + } + $this->cachedHighestRow = $highestRow; + + // Return + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + if ($this->dirty) { + $this->hash = md5($this->title . $this->autoFilter . ($this->protection->isProtectionEnabled() ? 't' : 'f') . __CLASS__); + $this->dirty = false; + } + return $this->hash; + } + + /** + * Extract worksheet title from range. + * + * Example: extractSheetTitle("testSheet!A1") ==> 'A1' + * Example: extractSheetTitle("'testSheet 1'!A1", true) ==> array('testSheet 1', 'A1'); + * + * @param string $pRange Range to extract title from + * @param bool $returnRange Return range? (see example) + * @return mixed + */ + public static function extractSheetTitle($pRange, $returnRange = false) + { + // Sheet title included? + if (($sep = strpos($pRange, '!')) === false) { + return ''; + } + + if ($returnRange) { + return array(trim(substr($pRange, 0, $sep), "'"), substr($pRange, $sep + 1)); + } + + return substr($pRange, $sep + 1); + } + + /** + * Get hyperlink + * + * @param string $pCellCoordinate Cell coordinate to get hyperlink for + */ + public function getHyperlink($pCellCoordinate = 'A1') + { + // return hyperlink if we already have one + if (isset($this->hyperlinkCollection[$pCellCoordinate])) { + return $this->hyperlinkCollection[$pCellCoordinate]; + } + + // else create hyperlink + $this->hyperlinkCollection[$pCellCoordinate] = new PHPExcel_Cell_Hyperlink(); + return $this->hyperlinkCollection[$pCellCoordinate]; + } + + /** + * Set hyperlnk + * + * @param string $pCellCoordinate Cell coordinate to insert hyperlink + * @param PHPExcel_Cell_Hyperlink $pHyperlink + * @return PHPExcel_Worksheet + */ + public function setHyperlink($pCellCoordinate = 'A1', PHPExcel_Cell_Hyperlink $pHyperlink = null) + { + if ($pHyperlink === null) { + unset($this->hyperlinkCollection[$pCellCoordinate]); + } else { + $this->hyperlinkCollection[$pCellCoordinate] = $pHyperlink; + } + return $this; + } + + /** + * Hyperlink at a specific coordinate exists? + * + * @param string $pCoordinate + * @return boolean + */ + public function hyperlinkExists($pCoordinate = 'A1') + { + return isset($this->hyperlinkCollection[$pCoordinate]); + } + + /** + * Get collection of hyperlinks + * + * @return PHPExcel_Cell_Hyperlink[] + */ + public function getHyperlinkCollection() + { + return $this->hyperlinkCollection; + } + + /** + * Get data validation + * + * @param string $pCellCoordinate Cell coordinate to get data validation for + */ + public function getDataValidation($pCellCoordinate = 'A1') + { + // return data validation if we already have one + if (isset($this->dataValidationCollection[$pCellCoordinate])) { + return $this->dataValidationCollection[$pCellCoordinate]; + } + + // else create data validation + $this->dataValidationCollection[$pCellCoordinate] = new PHPExcel_Cell_DataValidation(); + return $this->dataValidationCollection[$pCellCoordinate]; + } + + /** + * Set data validation + * + * @param string $pCellCoordinate Cell coordinate to insert data validation + * @param PHPExcel_Cell_DataValidation $pDataValidation + * @return PHPExcel_Worksheet + */ + public function setDataValidation($pCellCoordinate = 'A1', PHPExcel_Cell_DataValidation $pDataValidation = null) + { + if ($pDataValidation === null) { + unset($this->dataValidationCollection[$pCellCoordinate]); + } else { + $this->dataValidationCollection[$pCellCoordinate] = $pDataValidation; + } + return $this; + } + + /** + * Data validation at a specific coordinate exists? + * + * @param string $pCoordinate + * @return boolean + */ + public function dataValidationExists($pCoordinate = 'A1') + { + return isset($this->dataValidationCollection[$pCoordinate]); + } + + /** + * Get collection of data validations + * + * @return PHPExcel_Cell_DataValidation[] + */ + public function getDataValidationCollection() + { + return $this->dataValidationCollection; + } + + /** + * Accepts a range, returning it as a range that falls within the current highest row and column of the worksheet + * + * @param string $range + * @return string Adjusted range value + */ + public function shrinkRangeToFit($range) + { + $maxCol = $this->getHighestColumn(); + $maxRow = $this->getHighestRow(); + $maxCol = PHPExcel_Cell::columnIndexFromString($maxCol); + + $rangeBlocks = explode(' ', $range); + foreach ($rangeBlocks as &$rangeSet) { + $rangeBoundaries = PHPExcel_Cell::getRangeBoundaries($rangeSet); + + if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[0][0]) > $maxCol) { + $rangeBoundaries[0][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); + } + if ($rangeBoundaries[0][1] > $maxRow) { + $rangeBoundaries[0][1] = $maxRow; + } + if (PHPExcel_Cell::columnIndexFromString($rangeBoundaries[1][0]) > $maxCol) { + $rangeBoundaries[1][0] = PHPExcel_Cell::stringFromColumnIndex($maxCol); + } + if ($rangeBoundaries[1][1] > $maxRow) { + $rangeBoundaries[1][1] = $maxRow; + } + $rangeSet = $rangeBoundaries[0][0].$rangeBoundaries[0][1].':'.$rangeBoundaries[1][0].$rangeBoundaries[1][1]; + } + unset($rangeSet); + $stRange = implode(' ', $rangeBlocks); + + return $stRange; + } + + /** + * Get tab color + * + * @return PHPExcel_Style_Color + */ + public function getTabColor() + { + if ($this->tabColor === null) { + $this->tabColor = new PHPExcel_Style_Color(); + } + return $this->tabColor; + } + + /** + * Reset tab color + * + * @return PHPExcel_Worksheet + */ + public function resetTabColor() + { + $this->tabColor = null; + unset($this->tabColor); + + return $this; + } + + /** + * Tab color set? + * + * @return boolean + */ + public function isTabColorSet() + { + return ($this->tabColor !== null); + } + + /** + * Copy worksheet (!= clone!) + * + * @return PHPExcel_Worksheet + */ + public function copy() + { + $copied = clone $this; + + return $copied; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + foreach ($this as $key => $val) { + if ($key == 'parent') { + continue; + } + + if (is_object($val) || (is_array($val))) { + if ($key == 'cellCollection') { + $newCollection = clone $this->cellCollection; + $newCollection->copyCellCollection($this); + $this->cellCollection = $newCollection; + } elseif ($key == 'drawingCollection') { + $newCollection = clone $this->drawingCollection; + $this->drawingCollection = $newCollection; + } elseif (($key == 'autoFilter') && ($this->autoFilter instanceof PHPExcel_Worksheet_AutoFilter)) { + $newAutoFilter = clone $this->autoFilter; + $this->autoFilter = $newAutoFilter; + $this->autoFilter->setParent($this); + } else { + $this->{$key} = unserialize(serialize($val)); + } + } + } + } +/** + * Define the code name of the sheet + * + * @param null|string Same rule as Title minus space not allowed (but, like Excel, change silently space to underscore) + * @return objWorksheet + * @throws PHPExcel_Exception + */ + public function setCodeName($pValue = null) + { + // Is this a 'rename' or not? + if ($this->getCodeName() == $pValue) { + return $this; + } + $pValue = str_replace(' ', '_', $pValue);//Excel does this automatically without flinching, we are doing the same + // Syntax check + // throw an exception if not valid + self::checkSheetCodeName($pValue); + + // We use the same code that setTitle to find a valid codeName else not using a space (Excel don't like) but a '_' + + if ($this->getParent()) { + // Is there already such sheet name? + if ($this->getParent()->sheetCodeNameExists($pValue)) { + // Use name, but append with lowest possible integer + + if (PHPExcel_Shared_String::CountCharacters($pValue) > 29) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 29); + } + $i = 1; + while ($this->getParent()->sheetCodeNameExists($pValue . '_' . $i)) { + ++$i; + if ($i == 10) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 28) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 28); + } + } elseif ($i == 100) { + if (PHPExcel_Shared_String::CountCharacters($pValue) > 27) { + $pValue = PHPExcel_Shared_String::Substring($pValue, 0, 27); + } + } + } + + $pValue = $pValue . '_' . $i;// ok, we have a valid name + //codeName is'nt used in formula : no need to call for an update + //return $this->setTitle($altTitle, $updateFormulaCellReferences); + } + } + + $this->codeName=$pValue; + return $this; + } + /** + * Return the code name of the sheet + * + * @return null|string + */ + public function getCodeName() + { + return $this->codeName; + } + /** + * Sheet has a code name ? + * @return boolean + */ + public function hasCodeName() + { + return !(is_null($this->codeName)); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter.php new file mode 100644 index 00000000..6ec8a446 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter.php @@ -0,0 +1,846 @@ +<?php + +/** + * PHPExcel_Worksheet_AutoFilter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_AutoFilter +{ + /** + * Autofilter Worksheet + * + * @var PHPExcel_Worksheet + */ + private $workSheet; + + + /** + * Autofilter Range + * + * @var string + */ + private $range = ''; + + + /** + * Autofilter Column Ruleset + * + * @var array of PHPExcel_Worksheet_AutoFilter_Column + */ + private $columns = array(); + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter + * + * @param string $pRange Cell range (i.e. A1:E10) + * @param PHPExcel_Worksheet $pSheet + */ + public function __construct($pRange = '', PHPExcel_Worksheet $pSheet = null) + { + $this->range = $pRange; + $this->workSheet = $pSheet; + } + + /** + * Get AutoFilter Parent Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getParent() + { + return $this->workSheet; + } + + /** + * Set AutoFilter Parent Worksheet + * + * @param PHPExcel_Worksheet $pSheet + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setParent(PHPExcel_Worksheet $pSheet = null) + { + $this->workSheet = $pSheet; + + return $this; + } + + /** + * Get AutoFilter Range + * + * @return string + */ + public function getRange() + { + return $this->range; + } + + /** + * Set AutoFilter Range + * + * @param string $pRange Cell range (i.e. A1:E10) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setRange($pRange = '') + { + // Uppercase coordinate + $cellAddress = explode('!', strtoupper($pRange)); + if (count($cellAddress) > 1) { + list($worksheet, $pRange) = $cellAddress; + } + + if (strpos($pRange, ':') !== false) { + $this->range = $pRange; + } elseif (empty($pRange)) { + $this->range = ''; + } else { + throw new PHPExcel_Exception('Autofilter must be set on a range of cells.'); + } + + if (empty($pRange)) { + // Discard all column rules + $this->columns = array(); + } else { + // Discard any column rules that are no longer valid within this range + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range); + foreach ($this->columns as $key => $value) { + $colIndex = PHPExcel_Cell::columnIndexFromString($key); + if (($rangeStart[0] > $colIndex) || ($rangeEnd[0] < $colIndex)) { + unset($this->columns[$key]); + } + } + } + + return $this; + } + + /** + * Get all AutoFilter Columns + * + * @throws PHPExcel_Exception + * @return array of PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumns() + { + return $this->columns; + } + + /** + * Validate that the specified column is in the AutoFilter range + * + * @param string $column Column name (e.g. A) + * @throws PHPExcel_Exception + * @return integer The column offset within the autofilter range + */ + public function testColumnInRange($column) + { + if (empty($this->range)) { + throw new PHPExcel_Exception("No autofilter range is defined."); + } + + $columnIndex = PHPExcel_Cell::columnIndexFromString($column); + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range); + if (($rangeStart[0] > $columnIndex) || ($rangeEnd[0] < $columnIndex)) { + throw new PHPExcel_Exception("Column is outside of current autofilter range."); + } + + return $columnIndex - $rangeStart[0]; + } + + /** + * Get a specified AutoFilter Column Offset within the defined AutoFilter range + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return integer The offset of the specified column within the autofilter range + */ + public function getColumnOffset($pColumn) + { + return $this->testColumnInRange($pColumn); + } + + /** + * Get a specified AutoFilter Column + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumn($pColumn) + { + $this->testColumnInRange($pColumn); + + if (!isset($this->columns[$pColumn])) { + $this->columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this); + } + + return $this->columns[$pColumn]; + } + + /** + * Get a specified AutoFilter Column by it's offset + * + * @param integer $pColumnOffset Column offset within range (starting from 0) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getColumnByOffset($pColumnOffset = 0) + { + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range); + $pColumn = PHPExcel_Cell::stringFromColumnIndex($rangeStart[0] + $pColumnOffset - 1); + + return $this->getColumn($pColumn); + } + + /** + * Set AutoFilter + * + * @param PHPExcel_Worksheet_AutoFilter_Column|string $pColumn + * A simple string containing a Column ID like 'A' is permitted + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function setColumn($pColumn) + { + if ((is_string($pColumn)) && (!empty($pColumn))) { + $column = $pColumn; + } elseif (is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) { + $column = $pColumn->getColumnIndex(); + } else { + throw new PHPExcel_Exception("Column is not within the autofilter range."); + } + $this->testColumnInRange($column); + + if (is_string($pColumn)) { + $this->columns[$pColumn] = new PHPExcel_Worksheet_AutoFilter_Column($pColumn, $this); + } elseif (is_object($pColumn) && ($pColumn instanceof PHPExcel_Worksheet_AutoFilter_Column)) { + $pColumn->setParent($this); + $this->columns[$column] = $pColumn; + } + ksort($this->columns); + + return $this; + } + + /** + * Clear a specified AutoFilter Column + * + * @param string $pColumn Column name (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function clearColumn($pColumn) + { + $this->testColumnInRange($pColumn); + + if (isset($this->columns[$pColumn])) { + unset($this->columns[$pColumn]); + } + + return $this; + } + + /** + * Shift an AutoFilter Column Rule to a different column + * + * Note: This method bypasses validation of the destination column to ensure it is within this AutoFilter range. + * Nor does it verify whether any column rule already exists at $toColumn, but will simply overrideany existing value. + * Use with caution. + * + * @param string $fromColumn Column name (e.g. A) + * @param string $toColumn Column name (e.g. B) + * @return PHPExcel_Worksheet_AutoFilter + */ + public function shiftColumn($fromColumn = null, $toColumn = null) + { + $fromColumn = strtoupper($fromColumn); + $toColumn = strtoupper($toColumn); + + if (($fromColumn !== null) && (isset($this->columns[$fromColumn])) && ($toColumn !== null)) { + $this->columns[$fromColumn]->setParent(); + $this->columns[$fromColumn]->setColumnIndex($toColumn); + $this->columns[$toColumn] = $this->columns[$fromColumn]; + $this->columns[$toColumn]->setParent($this); + unset($this->columns[$fromColumn]); + + ksort($this->columns); + } + + return $this; + } + + + /** + * Test if cell value is in the defined set of values + * + * @param mixed $cellValue + * @param mixed[] $dataSet + * @return boolean + */ + private static function filterTestInSimpleDataSet($cellValue, $dataSet) + { + $dataSetValues = $dataSet['filterValues']; + $blanks = $dataSet['blanks']; + if (($cellValue == '') || ($cellValue === null)) { + return $blanks; + } + return in_array($cellValue, $dataSetValues); + } + + /** + * Test if cell value is in the defined set of Excel date values + * + * @param mixed $cellValue + * @param mixed[] $dataSet + * @return boolean + */ + private static function filterTestInDateGroupSet($cellValue, $dataSet) + { + $dateSet = $dataSet['filterValues']; + $blanks = $dataSet['blanks']; + if (($cellValue == '') || ($cellValue === null)) { + return $blanks; + } + + if (is_numeric($cellValue)) { + $dateValue = PHPExcel_Shared_Date::ExcelToPHP($cellValue); + if ($cellValue < 1) { + // Just the time part + $dtVal = date('His', $dateValue); + $dateSet = $dateSet['time']; + } elseif ($cellValue == floor($cellValue)) { + // Just the date part + $dtVal = date('Ymd', $dateValue); + $dateSet = $dateSet['date']; + } else { + // date and time parts + $dtVal = date('YmdHis', $dateValue); + $dateSet = $dateSet['dateTime']; + } + foreach ($dateSet as $dateValue) { + // Use of substr to extract value at the appropriate group level + if (substr($dtVal, 0, strlen($dateValue)) == $dateValue) { + return true; + } + } + } + return false; + } + + /** + * Test if cell value is within a set of values defined by a ruleset + * + * @param mixed $cellValue + * @param mixed[] $ruleSet + * @return boolean + */ + private static function filterTestInCustomDataSet($cellValue, $ruleSet) + { + $dataSet = $ruleSet['filterRules']; + $join = $ruleSet['join']; + $customRuleForBlanks = isset($ruleSet['customRuleForBlanks']) ? $ruleSet['customRuleForBlanks'] : false; + + if (!$customRuleForBlanks) { + // Blank cells are always ignored, so return a FALSE + if (($cellValue == '') || ($cellValue === null)) { + return false; + } + } + $returnVal = ($join == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND); + foreach ($dataSet as $rule) { + if (is_numeric($rule['value'])) { + // Numeric values are tested using the appropriate operator + switch ($rule['operator']) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + $retVal = ($cellValue == $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + $retVal = ($cellValue != $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN: + $retVal = ($cellValue > $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL: + $retVal = ($cellValue >= $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN: + $retVal = ($cellValue < $rule['value']); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL: + $retVal = ($cellValue <= $rule['value']); + break; + } + } elseif ($rule['value'] == '') { + switch ($rule['operator']) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL: + $retVal = (($cellValue == '') || ($cellValue === null)); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_NOTEQUAL: + $retVal = (($cellValue != '') && ($cellValue !== null)); + break; + default: + $retVal = true; + break; + } + } else { + // String values are always tested for equality, factoring in for wildcards (hence a regexp test) + $retVal = preg_match('/^'.$rule['value'].'$/i', $cellValue); + } + // If there are multiple conditions, then we need to test both using the appropriate join operator + switch ($join) { + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR: + $returnVal = $returnVal || $retVal; + // Break as soon as we have a TRUE match for OR joins, + // to avoid unnecessary additional code execution + if ($returnVal) { + return $returnVal; + } + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND: + $returnVal = $returnVal && $retVal; + break; + } + } + + return $returnVal; + } + + /** + * Test if cell date value is matches a set of values defined by a set of months + * + * @param mixed $cellValue + * @param mixed[] $monthSet + * @return boolean + */ + private static function filterTestInPeriodDateSet($cellValue, $monthSet) + { + // Blank cells are always ignored, so return a FALSE + if (($cellValue == '') || ($cellValue === null)) { + return false; + } + + if (is_numeric($cellValue)) { + $dateValue = date('m', PHPExcel_Shared_Date::ExcelToPHP($cellValue)); + if (in_array($dateValue, $monthSet)) { + return true; + } + } + + return false; + } + + /** + * Search/Replace arrays to convert Excel wildcard syntax to a regexp syntax for preg_matching + * + * @var array + */ + private static $fromReplace = array('\*', '\?', '~~', '~.*', '~.?'); + private static $toReplace = array('.*', '.', '~', '\*', '\?'); + + + /** + * Convert a dynamic rule daterange to a custom filter range expression for ease of calculation + * + * @param string $dynamicRuleType + * @param PHPExcel_Worksheet_AutoFilter_Column &$filterColumn + * @return mixed[] + */ + private function dynamicFilterDateRange($dynamicRuleType, &$filterColumn) + { + $rDateType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC); + $val = $maxVal = null; + + $ruleValues = array(); + $baseDate = PHPExcel_Calculation_DateTime::DATENOW(); + // Calculate start/end dates for the required date range based on current date + switch ($dynamicRuleType) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: + $baseDate = strtotime('-7 days', $baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: + $baseDate = strtotime('-7 days', $baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: + $baseDate = strtotime('-1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: + $baseDate = strtotime('+1 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: + $baseDate = strtotime('-3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: + $baseDate = strtotime('+3 month', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: + $baseDate = strtotime('-1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: + $baseDate = strtotime('+1 year', gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + } + + switch ($dynamicRuleType) { + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TODAY: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day', $baseDate)); + $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE: + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(strtotime('+1 day', $baseDate)); + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR: + $maxVal = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 31, 12, date('Y', $baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1, date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER: + $thisMonth = date('m', $baseDate); + $thisQuarter = floor(--$thisMonth / 3); + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), (1+$thisQuarter)*3, date('Y', $baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, 1+$thisQuarter*3, date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH: + $maxVal = (int) PHPExcel_Shared_Date::PHPtoExcel(gmmktime(0, 0, 0, date('t', $baseDate), date('m', $baseDate), date('Y', $baseDate))); + ++$maxVal; + $val = (int) PHPExcel_Shared_Date::PHPToExcel(gmmktime(0, 0, 0, 1, date('m', $baseDate), date('Y', $baseDate))); + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK: + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK: + $dayOfWeek = date('w', $baseDate); + $val = (int) PHPExcel_Shared_Date::PHPToExcel($baseDate) - $dayOfWeek; + $maxVal = $val + 7; + break; + } + + switch ($dynamicRuleType) { + // Adjust Today dates for Yesterday and Tomorrow + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY: + --$maxVal; + --$val; + break; + case PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW: + ++$maxVal; + ++$val; + break; + } + + // Set the filter column rule attributes ready for writing + $filterColumn->setAttributes(array('val' => $val, 'maxVal' => $maxVal)); + + // Set the rules for identifying rows for hide/show + $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, 'value' => $val); + $ruleValues[] = array('operator' => PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN, 'value' => $maxVal); + PHPExcel_Calculation_Functions::setReturnDateType($rDateType); + + return array('method' => 'filterTestInCustomDataSet', 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND)); + } + + private function calculateTopTenValue($columnID, $startRow, $endRow, $ruleType, $ruleValue) + { + $range = $columnID.$startRow.':'.$columnID.$endRow; + $dataValues = PHPExcel_Calculation_Functions::flattenArray($this->workSheet->rangeToArray($range, null, true, false)); + + $dataValues = array_filter($dataValues); + if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) { + rsort($dataValues); + } else { + sort($dataValues); + } + + return array_pop(array_slice($dataValues, 0, $ruleValue)); + } + + /** + * Apply the AutoFilter rules to the AutoFilter Range + * + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter + */ + public function showHideRows() + { + list($rangeStart, $rangeEnd) = PHPExcel_Cell::rangeBoundaries($this->range); + + // The heading row should always be visible +// echo 'AutoFilter Heading Row ', $rangeStart[1],' is always SHOWN',PHP_EOL; + $this->workSheet->getRowDimension($rangeStart[1])->setVisible(true); + + $columnFilterTests = array(); + foreach ($this->columns as $columnID => $filterColumn) { + $rules = $filterColumn->getRules(); + switch ($filterColumn->getFilterType()) { + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER: + $ruleValues = array(); + // Build a list of the filter value selections + foreach ($rules as $rule) { + $ruleType = $rule->getRuleType(); + $ruleValues[] = $rule->getValue(); + } + // Test if we want to include blanks in our filter criteria + $blanks = false; + $ruleDataSet = array_filter($ruleValues); + if (count($ruleValues) != count($ruleDataSet)) { + $blanks = true; + } + if ($ruleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_FILTER) { + // Filter on absolute values + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInSimpleDataSet', + 'arguments' => array('filterValues' => $ruleDataSet, 'blanks' => $blanks) + ); + } else { + // Filter on date group values + $arguments = array( + 'date' => array(), + 'time' => array(), + 'dateTime' => array(), + ); + foreach ($ruleDataSet as $ruleValue) { + $date = $time = ''; + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR] !== '')) { + $date .= sprintf('%04d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_YEAR]); + } + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH] != '')) { + $date .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MONTH]); + } + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY] !== '')) { + $date .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_DAY]); + } + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR] !== '')) { + $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_HOUR]); + } + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE] !== '')) { + $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE]); + } + if ((isset($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND])) && + ($ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND] !== '')) { + $time .= sprintf('%02d', $ruleValue[PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP_SECOND]); + } + $dateTime = $date . $time; + $arguments['date'][] = $date; + $arguments['time'][] = $time; + $arguments['dateTime'][] = $dateTime; + } + // Remove empty elements + $arguments['date'] = array_filter($arguments['date']); + $arguments['time'] = array_filter($arguments['time']); + $arguments['dateTime'] = array_filter($arguments['dateTime']); + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInDateGroupSet', + 'arguments' => array('filterValues' => $arguments, 'blanks' => $blanks) + ); + } + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_CUSTOMFILTER: + $customRuleForBlanks = false; + $ruleValues = array(); + // Build a list of the filter value selections + foreach ($rules as $rule) { + $ruleType = $rule->getRuleType(); + $ruleValue = $rule->getValue(); + if (!is_numeric($ruleValue)) { + // Convert to a regexp allowing for regexp reserved characters, wildcards and escaped wildcards + $ruleValue = preg_quote($ruleValue); + $ruleValue = str_replace(self::$fromReplace, self::$toReplace, $ruleValue); + if (trim($ruleValue) == '') { + $customRuleForBlanks = true; + $ruleValue = trim($ruleValue); + } + } + $ruleValues[] = array('operator' => $rule->getOperator(), 'value' => $ruleValue); + } + $join = $filterColumn->getJoin(); + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInCustomDataSet', + 'arguments' => array('filterRules' => $ruleValues, 'join' => $join, 'customRuleForBlanks' => $customRuleForBlanks) + ); + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_DYNAMICFILTER: + $ruleValues = array(); + foreach ($rules as $rule) { + // We should only ever have one Dynamic Filter Rule anyway + $dynamicRuleType = $rule->getGrouping(); + if (($dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) || + ($dynamicRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE)) { + // Number (Average) based + // Calculate the average + $averageFormula = '=AVERAGE('.$columnID.($rangeStart[1]+1).':'.$columnID.$rangeEnd[1].')'; + $average = PHPExcel_Calculation::getInstance()->calculateFormula($averageFormula, null, $this->workSheet->getCell('A1')); + // Set above/below rule based on greaterThan or LessTan + $operator = ($dynamicRuleType === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHAN + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHAN; + $ruleValues[] = array('operator' => $operator, + 'value' => $average + ); + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInCustomDataSet', + 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR) + ); + } else { + // Date based + if ($dynamicRuleType{0} == 'M' || $dynamicRuleType{0} == 'Q') { + // Month or Quarter + sscanf($dynamicRuleType, '%[A-Z]%d', $periodType, $period); + if ($periodType == 'M') { + $ruleValues = array($period); + } else { + --$period; + $periodEnd = (1+$period)*3; + $periodStart = 1+$period*3; + $ruleValues = range($periodStart, $periodEnd); + } + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInPeriodDateSet', + 'arguments' => $ruleValues + ); + $filterColumn->setAttributes(array()); + } else { + // Date Range + $columnFilterTests[$columnID] = $this->dynamicFilterDateRange($dynamicRuleType, $filterColumn); + break; + } + } + } + break; + case PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_TOPTENFILTER: + $ruleValues = array(); + $dataRowCount = $rangeEnd[1] - $rangeStart[1]; + foreach ($rules as $rule) { + // We should only ever have one Dynamic Filter Rule anyway + $toptenRuleType = $rule->getGrouping(); + $ruleValue = $rule->getValue(); + $ruleOperator = $rule->getOperator(); + } + if ($ruleOperator === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) { + $ruleValue = floor($ruleValue * ($dataRowCount / 100)); + } + if ($ruleValue < 1) { + $ruleValue = 1; + } + if ($ruleValue > 500) { + $ruleValue = 500; + } + + $maxVal = $this->calculateTopTenValue($columnID, $rangeStart[1]+1, $rangeEnd[1], $toptenRuleType, $ruleValue); + + $operator = ($toptenRuleType == PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) + ? PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL + : PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL; + $ruleValues[] = array('operator' => $operator, 'value' => $maxVal); + $columnFilterTests[$columnID] = array( + 'method' => 'filterTestInCustomDataSet', + 'arguments' => array('filterRules' => $ruleValues, 'join' => PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_OR) + ); + $filterColumn->setAttributes(array('maxVal' => $maxVal)); + break; + } + } + +// echo 'Column Filter Test CRITERIA',PHP_EOL; +// var_dump($columnFilterTests); +// + // Execute the column tests for each row in the autoFilter range to determine show/hide, + for ($row = $rangeStart[1]+1; $row <= $rangeEnd[1]; ++$row) { +// echo 'Testing Row = ', $row,PHP_EOL; + $result = true; + foreach ($columnFilterTests as $columnID => $columnFilterTest) { +// echo 'Testing cell ', $columnID.$row,PHP_EOL; + $cellValue = $this->workSheet->getCell($columnID.$row)->getCalculatedValue(); +// echo 'Value is ', $cellValue,PHP_EOL; + // Execute the filter test + $result = $result && + call_user_func_array( + array('PHPExcel_Worksheet_AutoFilter', $columnFilterTest['method']), + array($cellValue, $columnFilterTest['arguments']) + ); +// echo (($result) ? 'VALID' : 'INVALID'),PHP_EOL; + // If filter test has resulted in FALSE, exit the loop straightaway rather than running any more tests + if (!$result) { + break; + } + } + // Set show/hide for the row based on the result of the autoFilter result +// echo (($result) ? 'SHOW' : 'HIDE'),PHP_EOL; + $this->workSheet->getRowDimension($row)->setVisible($result); + } + + return $this; + } + + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == 'workSheet') { + // Detach from worksheet + $this->{$key} = null; + } else { + $this->{$key} = clone $value; + } + } elseif ((is_array($value)) && ($key == 'columns')) { + // The columns array of PHPExcel_Worksheet_AutoFilter objects + $this->{$key} = array(); + foreach ($value as $k => $v) { + $this->{$key}[$k] = clone $v; + // attach the new cloned Column to this new cloned Autofilter object + $this->{$key}[$k]->setParent($this); + } + } else { + $this->{$key} = $value; + } + } + } + + /** + * toString method replicates previous behavior by returning the range if object is + * referenced as a property of its parent. + */ + public function __toString() + { + return (string) $this->range; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column.php new file mode 100644 index 00000000..d64fd816 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column.php @@ -0,0 +1,405 @@ +<?php + +/** + * PHPExcel_Worksheet_AutoFilter_Column + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_AutoFilter_Column +{ + const AUTOFILTER_FILTERTYPE_FILTER = 'filters'; + const AUTOFILTER_FILTERTYPE_CUSTOMFILTER = 'customFilters'; + // Supports no more than 2 rules, with an And/Or join criteria + // if more than 1 rule is defined + const AUTOFILTER_FILTERTYPE_DYNAMICFILTER = 'dynamicFilter'; + // Even though the filter rule is constant, the filtered data can vary + // e.g. filtered by date = TODAY + const AUTOFILTER_FILTERTYPE_TOPTENFILTER = 'top10'; + + /** + * Types of autofilter rules + * + * @var string[] + */ + private static $filterTypes = array( + // Currently we're not handling + // colorFilter + // extLst + // iconFilter + self::AUTOFILTER_FILTERTYPE_FILTER, + self::AUTOFILTER_FILTERTYPE_CUSTOMFILTER, + self::AUTOFILTER_FILTERTYPE_DYNAMICFILTER, + self::AUTOFILTER_FILTERTYPE_TOPTENFILTER, + ); + + /* Multiple Rule Connections */ + const AUTOFILTER_COLUMN_JOIN_AND = 'and'; + const AUTOFILTER_COLUMN_JOIN_OR = 'or'; + + /** + * Join options for autofilter rules + * + * @var string[] + */ + private static $ruleJoins = array( + self::AUTOFILTER_COLUMN_JOIN_AND, + self::AUTOFILTER_COLUMN_JOIN_OR, + ); + + /** + * Autofilter + * + * @var PHPExcel_Worksheet_AutoFilter + */ + private $parent; + + + /** + * Autofilter Column Index + * + * @var string + */ + private $columnIndex = ''; + + + /** + * Autofilter Column Filter Type + * + * @var string + */ + private $filterType = self::AUTOFILTER_FILTERTYPE_FILTER; + + + /** + * Autofilter Multiple Rules And/Or + * + * @var string + */ + private $join = self::AUTOFILTER_COLUMN_JOIN_OR; + + + /** + * Autofilter Column Rules + * + * @var array of PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + private $ruleset = array(); + + + /** + * Autofilter Column Dynamic Attributes + * + * @var array of mixed + */ + private $attributes = array(); + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter_Column + * + * @param string $pColumn Column (e.g. A) + * @param PHPExcel_Worksheet_AutoFilter $pParent Autofilter for this column + */ + public function __construct($pColumn, PHPExcel_Worksheet_AutoFilter $pParent = null) + { + $this->columnIndex = $pColumn; + $this->parent = $pParent; + } + + /** + * Get AutoFilter Column Index + * + * @return string + */ + public function getColumnIndex() + { + return $this->columnIndex; + } + + /** + * Set AutoFilter Column Index + * + * @param string $pColumn Column (e.g. A) + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setColumnIndex($pColumn) + { + // Uppercase coordinate + $pColumn = strtoupper($pColumn); + if ($this->parent !== null) { + $this->parent->testColumnInRange($pColumn); + } + + $this->columnIndex = $pColumn; + + return $this; + } + + /** + * Get this Column's AutoFilter Parent + * + * @return PHPExcel_Worksheet_AutoFilter + */ + public function getParent() + { + return $this->parent; + } + + /** + * Set this Column's AutoFilter Parent + * + * @param PHPExcel_Worksheet_AutoFilter + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setParent(PHPExcel_Worksheet_AutoFilter $pParent = null) + { + $this->parent = $pParent; + + return $this; + } + + /** + * Get AutoFilter Type + * + * @return string + */ + public function getFilterType() + { + return $this->filterType; + } + + /** + * Set AutoFilter Type + * + * @param string $pFilterType + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setFilterType($pFilterType = self::AUTOFILTER_FILTERTYPE_FILTER) + { + if (!in_array($pFilterType, self::$filterTypes)) { + throw new PHPExcel_Exception('Invalid filter type for column AutoFilter.'); + } + + $this->filterType = $pFilterType; + + return $this; + } + + /** + * Get AutoFilter Multiple Rules And/Or Join + * + * @return string + */ + public function getJoin() + { + return $this->join; + } + + /** + * Set AutoFilter Multiple Rules And/Or + * + * @param string $pJoin And/Or + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setJoin($pJoin = self::AUTOFILTER_COLUMN_JOIN_OR) + { + // Lowercase And/Or + $pJoin = strtolower($pJoin); + if (!in_array($pJoin, self::$ruleJoins)) { + throw new PHPExcel_Exception('Invalid rule connection for column AutoFilter.'); + } + + $this->join = $pJoin; + + return $this; + } + + /** + * Set AutoFilter Attributes + * + * @param string[] $pAttributes + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setAttributes($pAttributes = array()) + { + $this->attributes = $pAttributes; + + return $this; + } + + /** + * Set An AutoFilter Attribute + * + * @param string $pName Attribute Name + * @param string $pValue Attribute Value + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setAttribute($pName, $pValue) + { + $this->attributes[$pName] = $pValue; + + return $this; + } + + /** + * Get AutoFilter Column Attributes + * + * @return string + */ + public function getAttributes() + { + return $this->attributes; + } + + /** + * Get specific AutoFilter Column Attribute + * + * @param string $pName Attribute Name + * @return string + */ + public function getAttribute($pName) + { + if (isset($this->attributes[$pName])) { + return $this->attributes[$pName]; + } + return null; + } + + /** + * Get all AutoFilter Column Rules + * + * @throws PHPExcel_Exception + * @return array of PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function getRules() + { + return $this->ruleset; + } + + /** + * Get a specified AutoFilter Column Rule + * + * @param integer $pIndex Rule index in the ruleset array + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function getRule($pIndex) + { + if (!isset($this->ruleset[$pIndex])) { + $this->ruleset[$pIndex] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this); + } + return $this->ruleset[$pIndex]; + } + + /** + * Create a new AutoFilter Column Rule in the ruleset + * + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function createRule() + { + $this->ruleset[] = new PHPExcel_Worksheet_AutoFilter_Column_Rule($this); + + return end($this->ruleset); + } + + /** + * Add a new AutoFilter Column Rule to the ruleset + * + * @param PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule + * @param boolean $returnRule Flag indicating whether the rule object or the column object should be returned + * @return PHPExcel_Worksheet_AutoFilter_Column|PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function addRule(PHPExcel_Worksheet_AutoFilter_Column_Rule $pRule, $returnRule = true) + { + $pRule->setParent($this); + $this->ruleset[] = $pRule; + + return ($returnRule) ? $pRule : $this; + } + + /** + * Delete a specified AutoFilter Column Rule + * If the number of rules is reduced to 1, then we reset And/Or logic to Or + * + * @param integer $pIndex Rule index in the ruleset array + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function deleteRule($pIndex) + { + if (isset($this->ruleset[$pIndex])) { + unset($this->ruleset[$pIndex]); + // If we've just deleted down to a single rule, then reset And/Or joining to Or + if (count($this->ruleset) <= 1) { + $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); + } + } + + return $this; + } + + /** + * Delete all AutoFilter Column Rules + * + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function clearRules() + { + $this->ruleset = array(); + $this->setJoin(self::AUTOFILTER_COLUMN_JOIN_OR); + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == 'parent') { + // Detach from autofilter parent + $this->$key = null; + } else { + $this->$key = clone $value; + } + } elseif ((is_array($value)) && ($key == 'ruleset')) { + // The columns array of PHPExcel_Worksheet_AutoFilter objects + $this->$key = array(); + foreach ($value as $k => $v) { + $this->$key[$k] = clone $v; + // attach the new cloned Rule to this new cloned Autofilter Cloned object + $this->$key[$k]->setParent($this); + } + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column/Rule.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column/Rule.php new file mode 100644 index 00000000..39ad18bf --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/AutoFilter/Column/Rule.php @@ -0,0 +1,468 @@ +<?php + +/** + * PHPExcel_Worksheet_AutoFilter_Column_Rule + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_AutoFilter_Column_Rule +{ + const AUTOFILTER_RULETYPE_FILTER = 'filter'; + const AUTOFILTER_RULETYPE_DATEGROUP = 'dateGroupItem'; + const AUTOFILTER_RULETYPE_CUSTOMFILTER = 'customFilter'; + const AUTOFILTER_RULETYPE_DYNAMICFILTER = 'dynamicFilter'; + const AUTOFILTER_RULETYPE_TOPTENFILTER = 'top10Filter'; + + private static $ruleTypes = array( + // Currently we're not handling + // colorFilter + // extLst + // iconFilter + self::AUTOFILTER_RULETYPE_FILTER, + self::AUTOFILTER_RULETYPE_DATEGROUP, + self::AUTOFILTER_RULETYPE_CUSTOMFILTER, + self::AUTOFILTER_RULETYPE_DYNAMICFILTER, + self::AUTOFILTER_RULETYPE_TOPTENFILTER, + ); + + const AUTOFILTER_RULETYPE_DATEGROUP_YEAR = 'year'; + const AUTOFILTER_RULETYPE_DATEGROUP_MONTH = 'month'; + const AUTOFILTER_RULETYPE_DATEGROUP_DAY = 'day'; + const AUTOFILTER_RULETYPE_DATEGROUP_HOUR = 'hour'; + const AUTOFILTER_RULETYPE_DATEGROUP_MINUTE = 'minute'; + const AUTOFILTER_RULETYPE_DATEGROUP_SECOND = 'second'; + + private static $dateTimeGroups = array( + self::AUTOFILTER_RULETYPE_DATEGROUP_YEAR, + self::AUTOFILTER_RULETYPE_DATEGROUP_MONTH, + self::AUTOFILTER_RULETYPE_DATEGROUP_DAY, + self::AUTOFILTER_RULETYPE_DATEGROUP_HOUR, + self::AUTOFILTER_RULETYPE_DATEGROUP_MINUTE, + self::AUTOFILTER_RULETYPE_DATEGROUP_SECOND, + ); + + const AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY = 'yesterday'; + const AUTOFILTER_RULETYPE_DYNAMIC_TODAY = 'today'; + const AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW = 'tomorrow'; + const AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE = 'yearToDate'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR = 'thisYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER = 'thisQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH = 'thisMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK = 'thisWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR = 'lastYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER = 'lastQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH = 'lastMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK = 'lastWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR = 'nextYear'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER = 'nextQuarter'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH = 'nextMonth'; + const AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK = 'nextWeek'; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1 = 'M1'; + const AUTOFILTER_RULETYPE_DYNAMIC_JANUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2 = 'M2'; + const AUTOFILTER_RULETYPE_DYNAMIC_FEBRUARY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3 = 'M3'; + const AUTOFILTER_RULETYPE_DYNAMIC_MARCH = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4 = 'M4'; + const AUTOFILTER_RULETYPE_DYNAMIC_APRIL = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5 = 'M5'; + const AUTOFILTER_RULETYPE_DYNAMIC_MAY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6 = 'M6'; + const AUTOFILTER_RULETYPE_DYNAMIC_JUNE = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7 = 'M7'; + const AUTOFILTER_RULETYPE_DYNAMIC_JULY = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8 = 'M8'; + const AUTOFILTER_RULETYPE_DYNAMIC_AUGUST = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9 = 'M9'; + const AUTOFILTER_RULETYPE_DYNAMIC_SEPTEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10 = 'M10'; + const AUTOFILTER_RULETYPE_DYNAMIC_OCTOBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11 = 'M11'; + const AUTOFILTER_RULETYPE_DYNAMIC_NOVEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11; + const AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12 = 'M12'; + const AUTOFILTER_RULETYPE_DYNAMIC_DECEMBER = self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1 = 'Q1'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2 = 'Q2'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3 = 'Q3'; + const AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4 = 'Q4'; + const AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE = 'aboveAverage'; + const AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE = 'belowAverage'; + + private static $dynamicTypes = array( + self::AUTOFILTER_RULETYPE_DYNAMIC_YESTERDAY, + self::AUTOFILTER_RULETYPE_DYNAMIC_TODAY, + self::AUTOFILTER_RULETYPE_DYNAMIC_TOMORROW, + self::AUTOFILTER_RULETYPE_DYNAMIC_YEARTODATE, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_THISWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_LASTWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTYEAR, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTQUARTER, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTMONTH, + self::AUTOFILTER_RULETYPE_DYNAMIC_NEXTWEEK, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_1, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_2, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_3, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_4, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_5, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_6, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_7, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_8, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_9, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_10, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_11, + self::AUTOFILTER_RULETYPE_DYNAMIC_MONTH_12, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_1, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_2, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_3, + self::AUTOFILTER_RULETYPE_DYNAMIC_QUARTER_4, + self::AUTOFILTER_RULETYPE_DYNAMIC_ABOVEAVERAGE, + self::AUTOFILTER_RULETYPE_DYNAMIC_BELOWAVERAGE, + ); + + /* + * The only valid filter rule operators for filter and customFilter types are: + * <xsd:enumeration value="equal"/> + * <xsd:enumeration value="lessThan"/> + * <xsd:enumeration value="lessThanOrEqual"/> + * <xsd:enumeration value="notEqual"/> + * <xsd:enumeration value="greaterThanOrEqual"/> + * <xsd:enumeration value="greaterThan"/> + */ + const AUTOFILTER_COLUMN_RULE_EQUAL = 'equal'; + const AUTOFILTER_COLUMN_RULE_NOTEQUAL = 'notEqual'; + const AUTOFILTER_COLUMN_RULE_GREATERTHAN = 'greaterThan'; + const AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL = 'greaterThanOrEqual'; + const AUTOFILTER_COLUMN_RULE_LESSTHAN = 'lessThan'; + const AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL = 'lessThanOrEqual'; + + private static $operators = array( + self::AUTOFILTER_COLUMN_RULE_EQUAL, + self::AUTOFILTER_COLUMN_RULE_NOTEQUAL, + self::AUTOFILTER_COLUMN_RULE_GREATERTHAN, + self::AUTOFILTER_COLUMN_RULE_GREATERTHANOREQUAL, + self::AUTOFILTER_COLUMN_RULE_LESSTHAN, + self::AUTOFILTER_COLUMN_RULE_LESSTHANOREQUAL, + ); + + const AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE = 'byValue'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT = 'byPercent'; + + private static $topTenValue = array( + self::AUTOFILTER_COLUMN_RULE_TOPTEN_BY_VALUE, + self::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT, + ); + + const AUTOFILTER_COLUMN_RULE_TOPTEN_TOP = 'top'; + const AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM = 'bottom'; + + private static $topTenType = array( + self::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP, + self::AUTOFILTER_COLUMN_RULE_TOPTEN_BOTTOM, + ); + + + /* Rule Operators (Numeric, Boolean etc) */ +// const AUTOFILTER_COLUMN_RULE_BETWEEN = 'between'; // greaterThanOrEqual 1 && lessThanOrEqual 2 + /* Rule Operators (Numeric Special) which are translated to standard numeric operators with calculated values */ +// const AUTOFILTER_COLUMN_RULE_TOPTEN = 'topTen'; // greaterThan calculated value +// const AUTOFILTER_COLUMN_RULE_TOPTENPERCENT = 'topTenPercent'; // greaterThan calculated value +// const AUTOFILTER_COLUMN_RULE_ABOVEAVERAGE = 'aboveAverage'; // Value is calculated as the average +// const AUTOFILTER_COLUMN_RULE_BELOWAVERAGE = 'belowAverage'; // Value is calculated as the average + /* Rule Operators (String) which are set as wild-carded values */ +// const AUTOFILTER_COLUMN_RULE_BEGINSWITH = 'beginsWith'; // A* +// const AUTOFILTER_COLUMN_RULE_ENDSWITH = 'endsWith'; // *Z +// const AUTOFILTER_COLUMN_RULE_CONTAINS = 'contains'; // *B* +// const AUTOFILTER_COLUMN_RULE_DOESNTCONTAIN = 'notEqual'; // notEqual *B* + /* Rule Operators (Date Special) which are translated to standard numeric operators with calculated values */ +// const AUTOFILTER_COLUMN_RULE_BEFORE = 'lessThan'; +// const AUTOFILTER_COLUMN_RULE_AFTER = 'greaterThan'; +// const AUTOFILTER_COLUMN_RULE_YESTERDAY = 'yesterday'; +// const AUTOFILTER_COLUMN_RULE_TODAY = 'today'; +// const AUTOFILTER_COLUMN_RULE_TOMORROW = 'tomorrow'; +// const AUTOFILTER_COLUMN_RULE_LASTWEEK = 'lastWeek'; +// const AUTOFILTER_COLUMN_RULE_THISWEEK = 'thisWeek'; +// const AUTOFILTER_COLUMN_RULE_NEXTWEEK = 'nextWeek'; +// const AUTOFILTER_COLUMN_RULE_LASTMONTH = 'lastMonth'; +// const AUTOFILTER_COLUMN_RULE_THISMONTH = 'thisMonth'; +// const AUTOFILTER_COLUMN_RULE_NEXTMONTH = 'nextMonth'; +// const AUTOFILTER_COLUMN_RULE_LASTQUARTER = 'lastQuarter'; +// const AUTOFILTER_COLUMN_RULE_THISQUARTER = 'thisQuarter'; +// const AUTOFILTER_COLUMN_RULE_NEXTQUARTER = 'nextQuarter'; +// const AUTOFILTER_COLUMN_RULE_LASTYEAR = 'lastYear'; +// const AUTOFILTER_COLUMN_RULE_THISYEAR = 'thisYear'; +// const AUTOFILTER_COLUMN_RULE_NEXTYEAR = 'nextYear'; +// const AUTOFILTER_COLUMN_RULE_YEARTODATE = 'yearToDate'; // <dynamicFilter val="40909" type="yearToDate" maxVal="41113"/> +// const AUTOFILTER_COLUMN_RULE_ALLDATESINMONTH = 'allDatesInMonth'; // <dynamicFilter type="M2"/> for Month/February +// const AUTOFILTER_COLUMN_RULE_ALLDATESINQUARTER = 'allDatesInQuarter'; // <dynamicFilter type="Q2"/> for Quarter 2 + + /** + * Autofilter Column + * + * @var PHPExcel_Worksheet_AutoFilter_Column + */ + private $parent = null; + + + /** + * Autofilter Rule Type + * + * @var string + */ + private $ruleType = self::AUTOFILTER_RULETYPE_FILTER; + + + /** + * Autofilter Rule Value + * + * @var string + */ + private $value = ''; + + /** + * Autofilter Rule Operator + * + * @var string + */ + private $operator = self::AUTOFILTER_COLUMN_RULE_EQUAL; + + /** + * DateTimeGrouping Group Value + * + * @var string + */ + private $grouping = ''; + + + /** + * Create a new PHPExcel_Worksheet_AutoFilter_Column_Rule + * + * @param PHPExcel_Worksheet_AutoFilter_Column $pParent + */ + public function __construct(PHPExcel_Worksheet_AutoFilter_Column $pParent = null) + { + $this->parent = $pParent; + } + + /** + * Get AutoFilter Rule Type + * + * @return string + */ + public function getRuleType() + { + return $this->ruleType; + } + + /** + * Set AutoFilter Rule Type + * + * @param string $pRuleType + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function setRuleType($pRuleType = self::AUTOFILTER_RULETYPE_FILTER) + { + if (!in_array($pRuleType, self::$ruleTypes)) { + throw new PHPExcel_Exception('Invalid rule type for column AutoFilter Rule.'); + } + + $this->ruleType = $pRuleType; + + return $this; + } + + /** + * Get AutoFilter Rule Value + * + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Set AutoFilter Rule Value + * + * @param string|string[] $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setValue($pValue = '') + { + if (is_array($pValue)) { + $grouping = -1; + foreach ($pValue as $key => $value) { + // Validate array entries + if (!in_array($key, self::$dateTimeGroups)) { + // Remove any invalid entries from the value array + unset($pValue[$key]); + } else { + // Work out what the dateTime grouping will be + $grouping = max($grouping, array_search($key, self::$dateTimeGroups)); + } + } + if (count($pValue) == 0) { + throw new PHPExcel_Exception('Invalid rule value for column AutoFilter Rule.'); + } + // Set the dateTime grouping that we've anticipated + $this->setGrouping(self::$dateTimeGroups[$grouping]); + } + $this->value = $pValue; + + return $this; + } + + /** + * Get AutoFilter Rule Operator + * + * @return string + */ + public function getOperator() + { + return $this->operator; + } + + /** + * Set AutoFilter Rule Operator + * + * @param string $pOperator + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setOperator($pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL) + { + if (empty($pOperator)) { + $pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL; + } + if ((!in_array($pOperator, self::$operators)) && + (!in_array($pOperator, self::$topTenValue))) { + throw new PHPExcel_Exception('Invalid operator for column AutoFilter Rule.'); + } + $this->operator = $pOperator; + + return $this; + } + + /** + * Get AutoFilter Rule Grouping + * + * @return string + */ + public function getGrouping() + { + return $this->grouping; + } + + /** + * Set AutoFilter Rule Grouping + * + * @param string $pGrouping + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setGrouping($pGrouping = null) + { + if (($pGrouping !== null) && + (!in_array($pGrouping, self::$dateTimeGroups)) && + (!in_array($pGrouping, self::$dynamicTypes)) && + (!in_array($pGrouping, self::$topTenType))) { + throw new PHPExcel_Exception('Invalid rule type for column AutoFilter Rule.'); + } + $this->grouping = $pGrouping; + + return $this; + } + + /** + * Set AutoFilter Rule + * + * @param string $pOperator + * @param string|string[] $pValue + * @param string $pGrouping + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setRule($pOperator = self::AUTOFILTER_COLUMN_RULE_EQUAL, $pValue = '', $pGrouping = null) + { + $this->setOperator($pOperator); + $this->setValue($pValue); + // Only set grouping if it's been passed in as a user-supplied argument, + // otherwise we're calculating it when we setValue() and don't want to overwrite that + // If the user supplies an argumnet for grouping, then on their own head be it + if ($pGrouping !== null) { + $this->setGrouping($pGrouping); + } + + return $this; + } + + /** + * Get this Rule's AutoFilter Column Parent + * + * @return PHPExcel_Worksheet_AutoFilter_Column + */ + public function getParent() + { + return $this->parent; + } + + /** + * Set this Rule's AutoFilter Column Parent + * + * @param PHPExcel_Worksheet_AutoFilter_Column + * @return PHPExcel_Worksheet_AutoFilter_Column_Rule + */ + public function setParent(PHPExcel_Worksheet_AutoFilter_Column $pParent = null) + { + $this->parent = $pParent; + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + if ($key == 'parent') { + // Detach from autofilter column parent + $this->$key = null; + } else { + $this->$key = clone $value; + } + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/BaseDrawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/BaseDrawing.php new file mode 100644 index 00000000..9ad15c70 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/BaseDrawing.php @@ -0,0 +1,507 @@ +<?php + +/** + * PHPExcel_Worksheet_BaseDrawing + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /** + * Image counter + * + * @var int + */ + private static $imageCounter = 0; + + /** + * Image index + * + * @var int + */ + private $imageIndex = 0; + + /** + * Name + * + * @var string + */ + protected $name; + + /** + * Description + * + * @var string + */ + protected $description; + + /** + * Worksheet + * + * @var PHPExcel_Worksheet + */ + protected $worksheet; + + /** + * Coordinates + * + * @var string + */ + protected $coordinates; + + /** + * Offset X + * + * @var int + */ + protected $offsetX; + + /** + * Offset Y + * + * @var int + */ + protected $offsetY; + + /** + * Width + * + * @var int + */ + protected $width; + + /** + * Height + * + * @var int + */ + protected $height; + + /** + * Proportional resize + * + * @var boolean + */ + protected $resizeProportional; + + /** + * Rotation + * + * @var int + */ + protected $rotation; + + /** + * Shadow + * + * @var PHPExcel_Worksheet_Drawing_Shadow + */ + protected $shadow; + + /** + * Create a new PHPExcel_Worksheet_BaseDrawing + */ + public function __construct() + { + // Initialise values + $this->name = ''; + $this->description = ''; + $this->worksheet = null; + $this->coordinates = 'A1'; + $this->offsetX = 0; + $this->offsetY = 0; + $this->width = 0; + $this->height = 0; + $this->resizeProportional = true; + $this->rotation = 0; + $this->shadow = new PHPExcel_Worksheet_Drawing_Shadow(); + + // Set image index + self::$imageCounter++; + $this->imageIndex = self::$imageCounter; + } + + /** + * Get image index + * + * @return int + */ + public function getImageIndex() + { + return $this->imageIndex; + } + + /** + * Get Name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setName($pValue = '') + { + $this->name = $pValue; + return $this; + } + + /** + * Get Description + * + * @return string + */ + public function getDescription() + { + return $this->description; + } + + /** + * Set Description + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setDescription($pValue = '') + { + $this->description = $pValue; + return $this; + } + + /** + * Get Worksheet + * + * @return PHPExcel_Worksheet + */ + public function getWorksheet() + { + return $this->worksheet; + } + + /** + * Set Worksheet + * + * @param PHPExcel_Worksheet $pValue + * @param bool $pOverrideOld If a Worksheet has already been assigned, overwrite it and remove image from old Worksheet? + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWorksheet(PHPExcel_Worksheet $pValue = null, $pOverrideOld = false) + { + if (is_null($this->worksheet)) { + // Add drawing to PHPExcel_Worksheet + $this->worksheet = $pValue; + $this->worksheet->getCell($this->coordinates); + $this->worksheet->getDrawingCollection()->append($this); + } else { + if ($pOverrideOld) { + // Remove drawing from old PHPExcel_Worksheet + $iterator = $this->worksheet->getDrawingCollection()->getIterator(); + + while ($iterator->valid()) { + if ($iterator->current()->getHashCode() == $this->getHashCode()) { + $this->worksheet->getDrawingCollection()->offsetUnset($iterator->key()); + $this->worksheet = null; + break; + } + } + + // Set new PHPExcel_Worksheet + $this->setWorksheet($pValue); + } else { + throw new PHPExcel_Exception("A PHPExcel_Worksheet has already been assigned. Drawings can only exist on one PHPExcel_Worksheet."); + } + } + return $this; + } + + /** + * Get Coordinates + * + * @return string + */ + public function getCoordinates() + { + return $this->coordinates; + } + + /** + * Set Coordinates + * + * @param string $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setCoordinates($pValue = 'A1') + { + $this->coordinates = $pValue; + return $this; + } + + /** + * Get OffsetX + * + * @return int + */ + public function getOffsetX() + { + return $this->offsetX; + } + + /** + * Set OffsetX + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setOffsetX($pValue = 0) + { + $this->offsetX = $pValue; + return $this; + } + + /** + * Get OffsetY + * + * @return int + */ + public function getOffsetY() + { + return $this->offsetY; + } + + /** + * Set OffsetY + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setOffsetY($pValue = 0) + { + $this->offsetY = $pValue; + return $this; + } + + /** + * Get Width + * + * @return int + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set Width + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWidth($pValue = 0) + { + // Resize proportional? + if ($this->resizeProportional && $pValue != 0) { + $ratio = $this->height / ($this->width != 0 ? $this->width : 1); + $this->height = round($ratio * $pValue); + } + + // Set width + $this->width = $pValue; + + return $this; + } + + /** + * Get Height + * + * @return int + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set Height + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setHeight($pValue = 0) + { + // Resize proportional? + if ($this->resizeProportional && $pValue != 0) { + $ratio = $this->width / ($this->height != 0 ? $this->height : 1); + $this->width = round($ratio * $pValue); + } + + // Set height + $this->height = $pValue; + + return $this; + } + + /** + * Set width and height with proportional resize + * Example: + * <code> + * $objDrawing->setResizeProportional(true); + * $objDrawing->setWidthAndHeight(160,120); + * </code> + * + * @author Vincent@luo MSN:kele_100@hotmail.com + * @param int $width + * @param int $height + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setWidthAndHeight($width = 0, $height = 0) + { + $xratio = $width / ($this->width != 0 ? $this->width : 1); + $yratio = $height / ($this->height != 0 ? $this->height : 1); + if ($this->resizeProportional && !($width == 0 || $height == 0)) { + if (($xratio * $this->height) < $height) { + $this->height = ceil($xratio * $this->height); + $this->width = $width; + } else { + $this->width = ceil($yratio * $this->width); + $this->height = $height; + } + } else { + $this->width = $width; + $this->height = $height; + } + + return $this; + } + + /** + * Get ResizeProportional + * + * @return boolean + */ + public function getResizeProportional() + { + return $this->resizeProportional; + } + + /** + * Set ResizeProportional + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setResizeProportional($pValue = true) + { + $this->resizeProportional = $pValue; + return $this; + } + + /** + * Get Rotation + * + * @return int + */ + public function getRotation() + { + return $this->rotation; + } + + /** + * Set Rotation + * + * @param int $pValue + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setRotation($pValue = 0) + { + $this->rotation = $pValue; + return $this; + } + + /** + * Get Shadow + * + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function getShadow() + { + return $this->shadow; + } + + /** + * Set Shadow + * + * @param PHPExcel_Worksheet_Drawing_Shadow $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_BaseDrawing + */ + public function setShadow(PHPExcel_Worksheet_Drawing_Shadow $pValue = null) + { + $this->shadow = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->name . + $this->description . + $this->worksheet->getHashCode() . + $this->coordinates . + $this->offsetX . + $this->offsetY . + $this->width . + $this->height . + $this->rotation . + $this->shadow->getHashCode() . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/CellIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/CellIterator.php new file mode 100644 index 00000000..151c17f5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/CellIterator.php @@ -0,0 +1,88 @@ +<?php + +/** + * PHPExcel_Worksheet_CellIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Worksheet_CellIterator +{ + /** + * PHPExcel_Worksheet to iterate + * + * @var PHPExcel_Worksheet + */ + protected $subject; + + /** + * Current iterator position + * + * @var mixed + */ + protected $position = null; + + /** + * Iterate only existing cells + * + * @var boolean + */ + protected $onlyExistingCells = false; + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * Get loop only existing cells + * + * @return boolean + */ + public function getIterateOnlyExistingCells() + { + return $this->onlyExistingCells; + } + + /** + * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary + * + * @throws PHPExcel_Exception + */ + abstract protected function adjustForExistingOnlyRange(); + + /** + * Set the iterator to loop only existing cells + * + * @param boolean $value + * @throws PHPExcel_Exception + */ + public function setIterateOnlyExistingCells($value = true) + { + $this->onlyExistingCells = (boolean) $value; + + $this->adjustForExistingOnlyRange(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Column.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Column.php new file mode 100644 index 00000000..6d3f36d1 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Column.php @@ -0,0 +1,86 @@ +<?php + +/** + * PHPExcel_Worksheet_Column + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_Column +{ + /** + * PHPExcel_Worksheet + * + * @var PHPExcel_Worksheet + */ + private $parent; + + /** + * Column index + * + * @var string + */ + private $columnIndex; + + /** + * Create a new column + * + * @param PHPExcel_Worksheet $parent + * @param string $columnIndex + */ + public function __construct(PHPExcel_Worksheet $parent = null, $columnIndex = 'A') + { + // Set parent and column index + $this->parent = $parent; + $this->columnIndex = $columnIndex; + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->parent); + } + + /** + * Get column index + * + * @return string + */ + public function getColumnIndex() + { + return $this->columnIndex; + } + + /** + * Get cell iterator + * + * @param integer $startRow The row number at which to start iterating + * @param integer $endRow Optionally, the row number at which to stop iterating + * @return PHPExcel_Worksheet_CellIterator + */ + public function getCellIterator($startRow = 1, $endRow = null) + { + return new PHPExcel_Worksheet_ColumnCellIterator($this->parent, $this->columnIndex, $startRow, $endRow); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnCellIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnCellIterator.php new file mode 100644 index 00000000..7b8c2190 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnCellIterator.php @@ -0,0 +1,216 @@ +<?php + +/** + * PHPExcel_Worksheet_ColumnCellIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_ColumnCellIterator extends PHPExcel_Worksheet_CellIterator implements Iterator +{ + /** + * Column index + * + * @var string + */ + protected $columnIndex; + + /** + * Start position + * + * @var int + */ + protected $startRow = 1; + + /** + * End position + * + * @var int + */ + protected $endRow = 1; + + /** + * Create a new row iterator + * + * @param PHPExcel_Worksheet $subject The worksheet to iterate over + * @param string $columnIndex The column that we want to iterate + * @param integer $startRow The row number at which to start iterating + * @param integer $endRow Optionally, the row number at which to stop iterating + */ + public function __construct(PHPExcel_Worksheet $subject = null, $columnIndex = 'A', $startRow = 1, $endRow = null) + { + // Set subject + $this->subject = $subject; + $this->columnIndex = PHPExcel_Cell::columnIndexFromString($columnIndex) - 1; + $this->resetEnd($endRow); + $this->resetStart($startRow); + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * (Re)Set the start row and the current row pointer + * + * @param integer $startRow The row number at which to start iterating + * @return PHPExcel_Worksheet_ColumnCellIterator + * @throws PHPExcel_Exception + */ + public function resetStart($startRow = 1) + { + $this->startRow = $startRow; + $this->adjustForExistingOnlyRange(); + $this->seek($startRow); + + return $this; + } + + /** + * (Re)Set the end row + * + * @param integer $endRow The row number at which to stop iterating + * @return PHPExcel_Worksheet_ColumnCellIterator + * @throws PHPExcel_Exception + */ + public function resetEnd($endRow = null) + { + $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow(); + $this->adjustForExistingOnlyRange(); + + return $this; + } + + /** + * Set the row pointer to the selected row + * + * @param integer $row The row number to set the current pointer at + * @return PHPExcel_Worksheet_ColumnCellIterator + * @throws PHPExcel_Exception + */ + public function seek($row = 1) + { + if (($row < $this->startRow) || ($row > $this->endRow)) { + throw new PHPExcel_Exception("Row $row is out of range ({$this->startRow} - {$this->endRow})"); + } elseif ($this->onlyExistingCells && !($this->subject->cellExistsByColumnAndRow($this->columnIndex, $row))) { + throw new PHPExcel_Exception('In "IterateOnlyExistingCells" mode and Cell does not exist'); + } + $this->position = $row; + + return $this; + } + + /** + * Rewind the iterator to the starting row + */ + public function rewind() + { + $this->position = $this->startRow; + } + + /** + * Return the current cell in this worksheet column + * + * @return PHPExcel_Worksheet_Row + */ + public function current() + { + return $this->subject->getCellByColumnAndRow($this->columnIndex, $this->position); + } + + /** + * Return the current iterator key + * + * @return int + */ + public function key() + { + return $this->position; + } + + /** + * Set the iterator to its next value + */ + public function next() + { + do { + ++$this->position; + } while (($this->onlyExistingCells) && + (!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->position)) && + ($this->position <= $this->endRow)); + } + + /** + * Set the iterator to its previous value + */ + public function prev() + { + if ($this->position <= $this->startRow) { + throw new PHPExcel_Exception("Row is already at the beginning of range ({$this->startRow} - {$this->endRow})"); + } + + do { + --$this->position; + } while (($this->onlyExistingCells) && + (!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->position)) && + ($this->position >= $this->startRow)); + } + + /** + * Indicate if more rows exist in the worksheet range of rows that we're iterating + * + * @return boolean + */ + public function valid() + { + return $this->position <= $this->endRow; + } + + /** + * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary + * + * @throws PHPExcel_Exception + */ + protected function adjustForExistingOnlyRange() + { + if ($this->onlyExistingCells) { + while ((!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->startRow)) && + ($this->startRow <= $this->endRow)) { + ++$this->startRow; + } + if ($this->startRow > $this->endRow) { + throw new PHPExcel_Exception('No cells exist within the specified range'); + } + while ((!$this->subject->cellExistsByColumnAndRow($this->columnIndex, $this->endRow)) && + ($this->endRow >= $this->startRow)) { + --$this->endRow; + } + if ($this->endRow < $this->startRow) { + throw new PHPExcel_Exception('No cells exist within the specified range'); + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnDimension.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnDimension.php new file mode 100644 index 00000000..405b8258 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnDimension.php @@ -0,0 +1,132 @@ +<?php + +/** + * PHPExcel_Worksheet_ColumnDimension + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_ColumnDimension extends PHPExcel_Worksheet_Dimension +{ + /** + * Column index + * + * @var int + */ + private $columnIndex; + + /** + * Column width + * + * When this is set to a negative value, the column width should be ignored by IWriter + * + * @var double + */ + private $width = -1; + + /** + * Auto size? + * + * @var bool + */ + private $autoSize = false; + + /** + * Create a new PHPExcel_Worksheet_ColumnDimension + * + * @param string $pIndex Character column index + */ + public function __construct($pIndex = 'A') + { + // Initialise values + $this->columnIndex = $pIndex; + + // set dimension as unformatted by default + parent::__construct(0); + } + + /** + * Get ColumnIndex + * + * @return string + */ + public function getColumnIndex() + { + return $this->columnIndex; + } + + /** + * Set ColumnIndex + * + * @param string $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setColumnIndex($pValue) + { + $this->columnIndex = $pValue; + return $this; + } + + /** + * Get Width + * + * @return double + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set Width + * + * @param double $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setWidth($pValue = -1) + { + $this->width = $pValue; + return $this; + } + + /** + * Get Auto Size + * + * @return bool + */ + public function getAutoSize() + { + return $this->autoSize; + } + + /** + * Set Auto Size + * + * @param bool $pValue + * @return PHPExcel_Worksheet_ColumnDimension + */ + public function setAutoSize($pValue = false) + { + $this->autoSize = $pValue; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnIterator.php new file mode 100644 index 00000000..0db3e534 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/ColumnIterator.php @@ -0,0 +1,201 @@ +<?php + +/** + * PHPExcel_Worksheet_ColumnIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_ColumnIterator implements Iterator +{ + /** + * PHPExcel_Worksheet to iterate + * + * @var PHPExcel_Worksheet + */ + private $subject; + + /** + * Current iterator position + * + * @var int + */ + private $position = 0; + + /** + * Start position + * + * @var int + */ + private $startColumn = 0; + + + /** + * End position + * + * @var int + */ + private $endColumn = 0; + + + /** + * Create a new column iterator + * + * @param PHPExcel_Worksheet $subject The worksheet to iterate over + * @param string $startColumn The column address at which to start iterating + * @param string $endColumn Optionally, the column address at which to stop iterating + */ + public function __construct(PHPExcel_Worksheet $subject = null, $startColumn = 'A', $endColumn = null) + { + // Set subject + $this->subject = $subject; + $this->resetEnd($endColumn); + $this->resetStart($startColumn); + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * (Re)Set the start column and the current column pointer + * + * @param integer $startColumn The column address at which to start iterating + * @return PHPExcel_Worksheet_ColumnIterator + * @throws PHPExcel_Exception + */ + public function resetStart($startColumn = 'A') + { + $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1; + if ($startColumnIndex > PHPExcel_Cell::columnIndexFromString($this->subject->getHighestColumn()) - 1) { + throw new PHPExcel_Exception("Start column ({$startColumn}) is beyond highest column ({$this->subject->getHighestColumn()})"); + } + + $this->startColumn = $startColumnIndex; + if ($this->endColumn < $this->startColumn) { + $this->endColumn = $this->startColumn; + } + $this->seek($startColumn); + + return $this; + } + + /** + * (Re)Set the end column + * + * @param string $endColumn The column address at which to stop iterating + * @return PHPExcel_Worksheet_ColumnIterator + */ + public function resetEnd($endColumn = null) + { + $endColumn = ($endColumn) ? $endColumn : $this->subject->getHighestColumn(); + $this->endColumn = PHPExcel_Cell::columnIndexFromString($endColumn) - 1; + + return $this; + } + + /** + * Set the column pointer to the selected column + * + * @param string $column The column address to set the current pointer at + * @return PHPExcel_Worksheet_ColumnIterator + * @throws PHPExcel_Exception + */ + public function seek($column = 'A') + { + $column = PHPExcel_Cell::columnIndexFromString($column) - 1; + if (($column < $this->startColumn) || ($column > $this->endColumn)) { + throw new PHPExcel_Exception("Column $column is out of range ({$this->startColumn} - {$this->endColumn})"); + } + $this->position = $column; + + return $this; + } + + /** + * Rewind the iterator to the starting column + */ + public function rewind() + { + $this->position = $this->startColumn; + } + + /** + * Return the current column in this worksheet + * + * @return PHPExcel_Worksheet_Column + */ + public function current() + { + return new PHPExcel_Worksheet_Column($this->subject, PHPExcel_Cell::stringFromColumnIndex($this->position)); + } + + /** + * Return the current iterator key + * + * @return string + */ + public function key() + { + return PHPExcel_Cell::stringFromColumnIndex($this->position); + } + + /** + * Set the iterator to its next value + */ + public function next() + { + ++$this->position; + } + + /** + * Set the iterator to its previous value + * + * @throws PHPExcel_Exception + */ + public function prev() + { + if ($this->position <= $this->startColumn) { + throw new PHPExcel_Exception( + "Column is already at the beginning of range (" . + PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . " - " . + PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . ")" + ); + } + + --$this->position; + } + + /** + * Indicate if more columns exist in the worksheet range of columns that we're iterating + * + * @return boolean + */ + public function valid() + { + return $this->position <= $this->endColumn; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Dimension.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Dimension.php new file mode 100644 index 00000000..84f692cb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Dimension.php @@ -0,0 +1,178 @@ +<?php + +/** + * PHPExcel_Worksheet_Dimension + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Worksheet_Dimension +{ + /** + * Visible? + * + * @var bool + */ + private $visible = true; + + /** + * Outline level + * + * @var int + */ + private $outlineLevel = 0; + + /** + * Collapsed + * + * @var bool + */ + private $collapsed = false; + + /** + * Index to cellXf. Null value means row has no explicit cellXf format. + * + * @var int|null + */ + private $xfIndex; + + /** + * Create a new PHPExcel_Worksheet_Dimension + * + * @param int $pIndex Numeric row index + */ + public function __construct($initialValue = null) + { + // set dimension as unformatted by default + $this->xfIndex = $initialValue; + } + + /** + * Get Visible + * + * @return bool + */ + public function getVisible() + { + return $this->visible; + } + + /** + * Set Visible + * + * @param bool $pValue + * @return PHPExcel_Worksheet_Dimension + */ + public function setVisible($pValue = true) + { + $this->visible = $pValue; + return $this; + } + + /** + * Get Outline Level + * + * @return int + */ + public function getOutlineLevel() + { + return $this->outlineLevel; + } + + /** + * Set Outline Level + * + * Value must be between 0 and 7 + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_Dimension + */ + public function setOutlineLevel($pValue) + { + if ($pValue < 0 || $pValue > 7) { + throw new PHPExcel_Exception("Outline level must range between 0 and 7."); + } + + $this->outlineLevel = $pValue; + return $this; + } + + /** + * Get Collapsed + * + * @return bool + */ + public function getCollapsed() + { + return $this->collapsed; + } + + /** + * Set Collapsed + * + * @param bool $pValue + * @return PHPExcel_Worksheet_Dimension + */ + public function setCollapsed($pValue = true) + { + $this->collapsed = $pValue; + return $this; + } + + /** + * Get index to cellXf + * + * @return int + */ + public function getXfIndex() + { + return $this->xfIndex; + } + + /** + * Set index to cellXf + * + * @param int $pValue + * @return PHPExcel_Worksheet_Dimension + */ + public function setXfIndex($pValue = 0) + { + $this->xfIndex = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing.php new file mode 100644 index 00000000..e39d3eb9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing.php @@ -0,0 +1,147 @@ +<?php + +/** + * PHPExcel_Worksheet_Drawing + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_Drawing extends PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /** + * Path + * + * @var string + */ + private $path; + + /** + * Create a new PHPExcel_Worksheet_Drawing + */ + public function __construct() + { + // Initialise values + $this->path = ''; + + // Initialize parent + parent::__construct(); + } + + /** + * Get Filename + * + * @return string + */ + public function getFilename() + { + return basename($this->path); + } + + /** + * Get indexed filename (using image index) + * + * @return string + */ + public function getIndexedFilename() + { + $fileName = $this->getFilename(); + $fileName = str_replace(' ', '_', $fileName); + return str_replace('.' . $this->getExtension(), '', $fileName) . $this->getImageIndex() . '.' . $this->getExtension(); + } + + /** + * Get Extension + * + * @return string + */ + public function getExtension() + { + $exploded = explode(".", basename($this->path)); + return $exploded[count($exploded) - 1]; + } + + /** + * Get Path + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set Path + * + * @param string $pValue File path + * @param boolean $pVerifyFile Verify file + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_Drawing + */ + public function setPath($pValue = '', $pVerifyFile = true) + { + if ($pVerifyFile) { + if (file_exists($pValue)) { + $this->path = $pValue; + + if ($this->width == 0 && $this->height == 0) { + // Get width/height + list($this->width, $this->height) = getimagesize($pValue); + } + } else { + throw new PHPExcel_Exception("File $pValue not found!"); + } + } else { + $this->path = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->path . + parent::getHashCode() . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing/Shadow.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing/Shadow.php new file mode 100644 index 00000000..84db91d5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Drawing/Shadow.php @@ -0,0 +1,296 @@ +<?php + +/** + * PHPExcel_Worksheet_Drawing_Shadow + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet_Drawing + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_Drawing_Shadow implements PHPExcel_IComparable +{ + /* Shadow alignment */ + const SHADOW_BOTTOM = 'b'; + const SHADOW_BOTTOM_LEFT = 'bl'; + const SHADOW_BOTTOM_RIGHT = 'br'; + const SHADOW_CENTER = 'ctr'; + const SHADOW_LEFT = 'l'; + const SHADOW_TOP = 't'; + const SHADOW_TOP_LEFT = 'tl'; + const SHADOW_TOP_RIGHT = 'tr'; + + /** + * Visible + * + * @var boolean + */ + private $visible; + + /** + * Blur radius + * + * Defaults to 6 + * + * @var int + */ + private $blurRadius; + + /** + * Shadow distance + * + * Defaults to 2 + * + * @var int + */ + private $distance; + + /** + * Shadow direction (in degrees) + * + * @var int + */ + private $direction; + + /** + * Shadow alignment + * + * @var int + */ + private $alignment; + + /** + * Color + * + * @var PHPExcel_Style_Color + */ + private $color; + + /** + * Alpha + * + * @var int + */ + private $alpha; + + /** + * Create a new PHPExcel_Worksheet_Drawing_Shadow + */ + public function __construct() + { + // Initialise values + $this->visible = false; + $this->blurRadius = 6; + $this->distance = 2; + $this->direction = 0; + $this->alignment = PHPExcel_Worksheet_Drawing_Shadow::SHADOW_BOTTOM_RIGHT; + $this->color = new PHPExcel_Style_Color(PHPExcel_Style_Color::COLOR_BLACK); + $this->alpha = 50; + } + + /** + * Get Visible + * + * @return boolean + */ + public function getVisible() + { + return $this->visible; + } + + /** + * Set Visible + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setVisible($pValue = false) + { + $this->visible = $pValue; + return $this; + } + + /** + * Get Blur radius + * + * @return int + */ + public function getBlurRadius() + { + return $this->blurRadius; + } + + /** + * Set Blur radius + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setBlurRadius($pValue = 6) + { + $this->blurRadius = $pValue; + return $this; + } + + /** + * Get Shadow distance + * + * @return int + */ + public function getDistance() + { + return $this->distance; + } + + /** + * Set Shadow distance + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setDistance($pValue = 2) + { + $this->distance = $pValue; + return $this; + } + + /** + * Get Shadow direction (in degrees) + * + * @return int + */ + public function getDirection() + { + return $this->direction; + } + + /** + * Set Shadow direction (in degrees) + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setDirection($pValue = 0) + { + $this->direction = $pValue; + return $this; + } + + /** + * Get Shadow alignment + * + * @return int + */ + public function getAlignment() + { + return $this->alignment; + } + + /** + * Set Shadow alignment + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setAlignment($pValue = 0) + { + $this->alignment = $pValue; + return $this; + } + + /** + * Get Color + * + * @return PHPExcel_Style_Color + */ + public function getColor() + { + return $this->color; + } + + /** + * Set Color + * + * @param PHPExcel_Style_Color $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setColor(PHPExcel_Style_Color $pValue = null) + { + $this->color = $pValue; + return $this; + } + + /** + * Get Alpha + * + * @return int + */ + public function getAlpha() + { + return $this->alpha; + } + + /** + * Set Alpha + * + * @param int $pValue + * @return PHPExcel_Worksheet_Drawing_Shadow + */ + public function setAlpha($pValue = 0) + { + $this->alpha = $pValue; + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + ($this->visible ? 't' : 'f') . + $this->blurRadius . + $this->distance . + $this->direction . + $this->alignment . + $this->color->getHashCode() . + $this->alpha . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooter.php new file mode 100644 index 00000000..3a88923f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooter.php @@ -0,0 +1,494 @@ +<?php +/** + * PHPExcel_Worksheet_HeaderFooter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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,241 write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + * + * <code> + * Header/Footer Formatting Syntax taken from Office Open XML Part 4 - Markup Language Reference, page 1970: + * + * There are a number of formatting codes that can be written inline with the actual header / footer text, which + * affect the formatting in the header or footer. + * + * Example: This example shows the text "Center Bold Header" on the first line (center section), and the date on + * the second line (center section). + * &CCenter &"-,Bold"Bold&"-,Regular"Header_x000A_&D + * + * General Rules: + * There is no required order in which these codes must appear. + * + * The first occurrence of the following codes turns the formatting ON, the second occurrence turns it OFF again: + * - strikethrough + * - superscript + * - subscript + * Superscript and subscript cannot both be ON at same time. Whichever comes first wins and the other is ignored, + * while the first is ON. + * &L - code for "left section" (there are three header / footer locations, "left", "center", and "right"). When + * two or more occurrences of this section marker exist, the contents from all markers are concatenated, in the + * order of appearance, and placed into the left section. + * &P - code for "current page #" + * &N - code for "total pages" + * &font size - code for "text font size", where font size is a font size in points. + * &K - code for "text font color" + * RGB Color is specified as RRGGBB + * Theme Color is specifed as TTSNN where TT is the theme color Id, S is either "+" or "-" of the tint/shade + * value, NN is the tint/shade value. + * &S - code for "text strikethrough" on / off + * &X - code for "text super script" on / off + * &Y - code for "text subscript" on / off + * &C - code for "center section". When two or more occurrences of this section marker exist, the contents + * from all markers are concatenated, in the order of appearance, and placed into the center section. + * + * &D - code for "date" + * &T - code for "time" + * &G - code for "picture as background" + * &U - code for "text single underline" + * &E - code for "double underline" + * &R - code for "right section". When two or more occurrences of this section marker exist, the contents + * from all markers are concatenated, in the order of appearance, and placed into the right section. + * &Z - code for "this workbook's file path" + * &F - code for "this workbook's file name" + * &A - code for "sheet tab name" + * &+ - code for add to page #. + * &- - code for subtract from page #. + * &"font name,font type" - code for "text font name" and "text font type", where font name and font type + * are strings specifying the name and type of the font, separated by a comma. When a hyphen appears in font + * name, it means "none specified". Both of font name and font type can be localized values. + * &"-,Bold" - code for "bold font style" + * &B - also means "bold font style". + * &"-,Regular" - code for "regular font style" + * &"-,Italic" - code for "italic font style" + * &I - also means "italic font style" + * &"-,Bold Italic" code for "bold italic font style" + * &O - code for "outline style" + * &H - code for "shadow style" + * </code> + * + */ +class PHPExcel_Worksheet_HeaderFooter +{ + /* Header/footer image location */ + const IMAGE_HEADER_LEFT = 'LH'; + const IMAGE_HEADER_CENTER = 'CH'; + const IMAGE_HEADER_RIGHT = 'RH'; + const IMAGE_FOOTER_LEFT = 'LF'; + const IMAGE_FOOTER_CENTER = 'CF'; + const IMAGE_FOOTER_RIGHT = 'RF'; + + /** + * OddHeader + * + * @var string + */ + private $oddHeader = ''; + + /** + * OddFooter + * + * @var string + */ + private $oddFooter = ''; + + /** + * EvenHeader + * + * @var string + */ + private $evenHeader = ''; + + /** + * EvenFooter + * + * @var string + */ + private $evenFooter = ''; + + /** + * FirstHeader + * + * @var string + */ + private $firstHeader = ''; + + /** + * FirstFooter + * + * @var string + */ + private $firstFooter = ''; + + /** + * Different header for Odd/Even, defaults to false + * + * @var boolean + */ + private $differentOddEven = false; + + /** + * Different header for first page, defaults to false + * + * @var boolean + */ + private $differentFirst = false; + + /** + * Scale with document, defaults to true + * + * @var boolean + */ + private $scaleWithDocument = true; + + /** + * Align with margins, defaults to true + * + * @var boolean + */ + private $alignWithMargins = true; + + /** + * Header/footer images + * + * @var PHPExcel_Worksheet_HeaderFooterDrawing[] + */ + private $headerFooterImages = array(); + + /** + * Create a new PHPExcel_Worksheet_HeaderFooter + */ + public function __construct() + { + } + + /** + * Get OddHeader + * + * @return string + */ + public function getOddHeader() + { + return $this->oddHeader; + } + + /** + * Set OddHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setOddHeader($pValue) + { + $this->oddHeader = $pValue; + return $this; + } + + /** + * Get OddFooter + * + * @return string + */ + public function getOddFooter() + { + return $this->oddFooter; + } + + /** + * Set OddFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setOddFooter($pValue) + { + $this->oddFooter = $pValue; + return $this; + } + + /** + * Get EvenHeader + * + * @return string + */ + public function getEvenHeader() + { + return $this->evenHeader; + } + + /** + * Set EvenHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setEvenHeader($pValue) + { + $this->evenHeader = $pValue; + return $this; + } + + /** + * Get EvenFooter + * + * @return string + */ + public function getEvenFooter() + { + return $this->evenFooter; + } + + /** + * Set EvenFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setEvenFooter($pValue) + { + $this->evenFooter = $pValue; + return $this; + } + + /** + * Get FirstHeader + * + * @return string + */ + public function getFirstHeader() + { + return $this->firstHeader; + } + + /** + * Set FirstHeader + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstHeader($pValue) + { + $this->firstHeader = $pValue; + return $this; + } + + /** + * Get FirstFooter + * + * @return string + */ + public function getFirstFooter() + { + return $this->firstFooter; + } + + /** + * Set FirstFooter + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstFooter($pValue) + { + $this->firstFooter = $pValue; + return $this; + } + + /** + * Get DifferentOddEven + * + * @return boolean + */ + public function getDifferentOddEven() + { + return $this->differentOddEven; + } + + /** + * Set DifferentOddEven + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setDifferentOddEven($pValue = false) + { + $this->differentOddEven = $pValue; + return $this; + } + + /** + * Get DifferentFirst + * + * @return boolean + */ + public function getDifferentFirst() + { + return $this->differentFirst; + } + + /** + * Set DifferentFirst + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setDifferentFirst($pValue = false) + { + $this->differentFirst = $pValue; + return $this; + } + + /** + * Get ScaleWithDocument + * + * @return boolean + */ + public function getScaleWithDocument() + { + return $this->scaleWithDocument; + } + + /** + * Set ScaleWithDocument + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setScaleWithDocument($pValue = true) + { + $this->scaleWithDocument = $pValue; + return $this; + } + + /** + * Get AlignWithMargins + * + * @return boolean + */ + public function getAlignWithMargins() + { + return $this->alignWithMargins; + } + + /** + * Set AlignWithMargins + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setAlignWithMargins($pValue = true) + { + $this->alignWithMargins = $pValue; + return $this; + } + + /** + * Add header/footer image + * + * @param PHPExcel_Worksheet_HeaderFooterDrawing $image + * @param string $location + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function addImage(PHPExcel_Worksheet_HeaderFooterDrawing $image = null, $location = self::IMAGE_HEADER_LEFT) + { + $this->headerFooterImages[$location] = $image; + return $this; + } + + /** + * Remove header/footer image + * + * @param string $location + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function removeImage($location = self::IMAGE_HEADER_LEFT) + { + if (isset($this->headerFooterImages[$location])) { + unset($this->headerFooterImages[$location]); + } + return $this; + } + + /** + * Set header/footer images + * + * @param PHPExcel_Worksheet_HeaderFooterDrawing[] $images + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setImages($images) + { + if (!is_array($images)) { + throw new PHPExcel_Exception('Invalid parameter!'); + } + + $this->headerFooterImages = $images; + return $this; + } + + /** + * Get header/footer images + * + * @return PHPExcel_Worksheet_HeaderFooterDrawing[] + */ + public function getImages() + { + // Sort array + $images = array(); + if (isset($this->headerFooterImages[self::IMAGE_HEADER_LEFT])) { + $images[self::IMAGE_HEADER_LEFT] = $this->headerFooterImages[self::IMAGE_HEADER_LEFT]; + } + if (isset($this->headerFooterImages[self::IMAGE_HEADER_CENTER])) { + $images[self::IMAGE_HEADER_CENTER] = $this->headerFooterImages[self::IMAGE_HEADER_CENTER]; + } + if (isset($this->headerFooterImages[self::IMAGE_HEADER_RIGHT])) { + $images[self::IMAGE_HEADER_RIGHT] = $this->headerFooterImages[self::IMAGE_HEADER_RIGHT]; + } + if (isset($this->headerFooterImages[self::IMAGE_FOOTER_LEFT])) { + $images[self::IMAGE_FOOTER_LEFT] = $this->headerFooterImages[self::IMAGE_FOOTER_LEFT]; + } + if (isset($this->headerFooterImages[self::IMAGE_FOOTER_CENTER])) { + $images[self::IMAGE_FOOTER_CENTER] = $this->headerFooterImages[self::IMAGE_FOOTER_CENTER]; + } + if (isset($this->headerFooterImages[self::IMAGE_FOOTER_RIGHT])) { + $images[self::IMAGE_FOOTER_RIGHT] = $this->headerFooterImages[self::IMAGE_FOOTER_RIGHT]; + } + $this->headerFooterImages = $images; + + return $this->headerFooterImages; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooterDrawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooterDrawing.php new file mode 100644 index 00000000..a491f4ba --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/HeaderFooterDrawing.php @@ -0,0 +1,361 @@ +<?php + +/** + * PHPExcel_Worksheet_HeaderFooterDrawing + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_HeaderFooterDrawing extends PHPExcel_Worksheet_Drawing implements PHPExcel_IComparable +{ + /** + * Path + * + * @var string + */ + private $path; + + /** + * Name + * + * @var string + */ + protected $name; + + /** + * Offset X + * + * @var int + */ + protected $offsetX; + + /** + * Offset Y + * + * @var int + */ + protected $offsetY; + + /** + * Width + * + * @var int + */ + protected $width; + + /** + * Height + * + * @var int + */ + protected $height; + + /** + * Proportional resize + * + * @var boolean + */ + protected $resizeProportional; + + /** + * Create a new PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function __construct() + { + // Initialise values + $this->path = ''; + $this->name = ''; + $this->offsetX = 0; + $this->offsetY = 0; + $this->width = 0; + $this->height = 0; + $this->resizeProportional = true; + } + + /** + * Get Name + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Set Name + * + * @param string $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setName($pValue = '') + { + $this->name = $pValue; + return $this; + } + + /** + * Get OffsetX + * + * @return int + */ + public function getOffsetX() + { + return $this->offsetX; + } + + /** + * Set OffsetX + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setOffsetX($pValue = 0) + { + $this->offsetX = $pValue; + return $this; + } + + /** + * Get OffsetY + * + * @return int + */ + public function getOffsetY() + { + return $this->offsetY; + } + + /** + * Set OffsetY + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setOffsetY($pValue = 0) + { + $this->offsetY = $pValue; + return $this; + } + + /** + * Get Width + * + * @return int + */ + public function getWidth() + { + return $this->width; + } + + /** + * Set Width + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setWidth($pValue = 0) + { + // Resize proportional? + if ($this->resizeProportional && $pValue != 0) { + $ratio = $this->width / $this->height; + $this->height = round($ratio * $pValue); + } + + // Set width + $this->width = $pValue; + + return $this; + } + + /** + * Get Height + * + * @return int + */ + public function getHeight() + { + return $this->height; + } + + /** + * Set Height + * + * @param int $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setHeight($pValue = 0) + { + // Resize proportional? + if ($this->resizeProportional && $pValue != 0) { + $ratio = $this->width / $this->height; + $this->width = round($ratio * $pValue); + } + + // Set height + $this->height = $pValue; + + return $this; + } + + /** + * Set width and height with proportional resize + * Example: + * <code> + * $objDrawing->setResizeProportional(true); + * $objDrawing->setWidthAndHeight(160,120); + * </code> + * + * @author Vincent@luo MSN:kele_100@hotmail.com + * @param int $width + * @param int $height + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setWidthAndHeight($width = 0, $height = 0) + { + $xratio = $width / $this->width; + $yratio = $height / $this->height; + if ($this->resizeProportional && !($width == 0 || $height == 0)) { + if (($xratio * $this->height) < $height) { + $this->height = ceil($xratio * $this->height); + $this->width = $width; + } else { + $this->width = ceil($yratio * $this->width); + $this->height = $height; + } + } + return $this; + } + + /** + * Get ResizeProportional + * + * @return boolean + */ + public function getResizeProportional() + { + return $this->resizeProportional; + } + + /** + * Set ResizeProportional + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setResizeProportional($pValue = true) + { + $this->resizeProportional = $pValue; + return $this; + } + + /** + * Get Filename + * + * @return string + */ + public function getFilename() + { + return basename($this->path); + } + + /** + * Get Extension + * + * @return string + */ + public function getExtension() + { + $parts = explode(".", basename($this->path)); + return end($parts); + } + + /** + * Get Path + * + * @return string + */ + public function getPath() + { + return $this->path; + } + + /** + * Set Path + * + * @param string $pValue File path + * @param boolean $pVerifyFile Verify file + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_HeaderFooterDrawing + */ + public function setPath($pValue = '', $pVerifyFile = true) + { + if ($pVerifyFile) { + if (file_exists($pValue)) { + $this->path = $pValue; + + if ($this->width == 0 && $this->height == 0) { + // Get width/height + list($this->width, $this->height) = getimagesize($pValue); + } + } else { + throw new PHPExcel_Exception("File $pValue not found!"); + } + } else { + $this->path = $pValue; + } + return $this; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->path . + $this->name . + $this->offsetX . + $this->offsetY . + $this->width . + $this->height . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/MemoryDrawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/MemoryDrawing.php new file mode 100644 index 00000000..438ed2c5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/MemoryDrawing.php @@ -0,0 +1,201 @@ +<?php + +/** + * PHPExcel_Worksheet_MemoryDrawing + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_MemoryDrawing extends PHPExcel_Worksheet_BaseDrawing implements PHPExcel_IComparable +{ + /* Rendering functions */ + const RENDERING_DEFAULT = 'imagepng'; + const RENDERING_PNG = 'imagepng'; + const RENDERING_GIF = 'imagegif'; + const RENDERING_JPEG = 'imagejpeg'; + + /* MIME types */ + const MIMETYPE_DEFAULT = 'image/png'; + const MIMETYPE_PNG = 'image/png'; + const MIMETYPE_GIF = 'image/gif'; + const MIMETYPE_JPEG = 'image/jpeg'; + + /** + * Image resource + * + * @var resource + */ + private $imageResource; + + /** + * Rendering function + * + * @var string + */ + private $renderingFunction; + + /** + * Mime type + * + * @var string + */ + private $mimeType; + + /** + * Unique name + * + * @var string + */ + private $uniqueName; + + /** + * Create a new PHPExcel_Worksheet_MemoryDrawing + */ + public function __construct() + { + // Initialise values + $this->imageResource = null; + $this->renderingFunction = self::RENDERING_DEFAULT; + $this->mimeType = self::MIMETYPE_DEFAULT; + $this->uniqueName = md5(rand(0, 9999). time() . rand(0, 9999)); + + // Initialize parent + parent::__construct(); + } + + /** + * Get image resource + * + * @return resource + */ + public function getImageResource() + { + return $this->imageResource; + } + + /** + * Set image resource + * + * @param $value resource + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setImageResource($value = null) + { + $this->imageResource = $value; + + if (!is_null($this->imageResource)) { + // Get width/height + $this->width = imagesx($this->imageResource); + $this->height = imagesy($this->imageResource); + } + return $this; + } + + /** + * Get rendering function + * + * @return string + */ + public function getRenderingFunction() + { + return $this->renderingFunction; + } + + /** + * Set rendering function + * + * @param string $value + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setRenderingFunction($value = PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT) + { + $this->renderingFunction = $value; + return $this; + } + + /** + * Get mime type + * + * @return string + */ + public function getMimeType() + { + return $this->mimeType; + } + + /** + * Set mime type + * + * @param string $value + * @return PHPExcel_Worksheet_MemoryDrawing + */ + public function setMimeType($value = PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT) + { + $this->mimeType = $value; + return $this; + } + + /** + * Get indexed filename (using image index) + * + * @return string + */ + public function getIndexedFilename() + { + $extension = strtolower($this->getMimeType()); + $extension = explode('/', $extension); + $extension = $extension[1]; + + return $this->uniqueName . $this->getImageIndex() . '.' . $extension; + } + + /** + * Get hash code + * + * @return string Hash code + */ + public function getHashCode() + { + return md5( + $this->renderingFunction . + $this->mimeType . + $this->uniqueName . + parent::getHashCode() . + __CLASS__ + ); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageMargins.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageMargins.php new file mode 100644 index 00000000..70f5ee0f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageMargins.php @@ -0,0 +1,233 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Worksheet_PageMargins + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_PageMargins +{ + /** + * Left + * + * @var double + */ + private $left = 0.7; + + /** + * Right + * + * @var double + */ + private $right = 0.7; + + /** + * Top + * + * @var double + */ + private $top = 0.75; + + /** + * Bottom + * + * @var double + */ + private $bottom = 0.75; + + /** + * Header + * + * @var double + */ + private $header = 0.3; + + /** + * Footer + * + * @var double + */ + private $footer = 0.3; + + /** + * Create a new PHPExcel_Worksheet_PageMargins + */ + public function __construct() + { + } + + /** + * Get Left + * + * @return double + */ + public function getLeft() + { + return $this->left; + } + + /** + * Set Left + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setLeft($pValue) + { + $this->left = $pValue; + return $this; + } + + /** + * Get Right + * + * @return double + */ + public function getRight() + { + return $this->right; + } + + /** + * Set Right + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setRight($pValue) + { + $this->right = $pValue; + return $this; + } + + /** + * Get Top + * + * @return double + */ + public function getTop() + { + return $this->top; + } + + /** + * Set Top + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setTop($pValue) + { + $this->top = $pValue; + return $this; + } + + /** + * Get Bottom + * + * @return double + */ + public function getBottom() + { + return $this->bottom; + } + + /** + * Set Bottom + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setBottom($pValue) + { + $this->bottom = $pValue; + return $this; + } + + /** + * Get Header + * + * @return double + */ + public function getHeader() + { + return $this->header; + } + + /** + * Set Header + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setHeader($pValue) + { + $this->header = $pValue; + return $this; + } + + /** + * Get Footer + * + * @return double + */ + public function getFooter() + { + return $this->footer; + } + + /** + * Set Footer + * + * @param double $pValue + * @return PHPExcel_Worksheet_PageMargins + */ + public function setFooter($pValue) + { + $this->footer = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageSetup.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageSetup.php new file mode 100644 index 00000000..c67053e6 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/PageSetup.php @@ -0,0 +1,839 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Worksheet_PageSetup + * + * <code> + * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988: + * + * 1 = Letter paper (8.5 in. by 11 in.) + * 2 = Letter small paper (8.5 in. by 11 in.) + * 3 = Tabloid paper (11 in. by 17 in.) + * 4 = Ledger paper (17 in. by 11 in.) + * 5 = Legal paper (8.5 in. by 14 in.) + * 6 = Statement paper (5.5 in. by 8.5 in.) + * 7 = Executive paper (7.25 in. by 10.5 in.) + * 8 = A3 paper (297 mm by 420 mm) + * 9 = A4 paper (210 mm by 297 mm) + * 10 = A4 small paper (210 mm by 297 mm) + * 11 = A5 paper (148 mm by 210 mm) + * 12 = B4 paper (250 mm by 353 mm) + * 13 = B5 paper (176 mm by 250 mm) + * 14 = Folio paper (8.5 in. by 13 in.) + * 15 = Quarto paper (215 mm by 275 mm) + * 16 = Standard paper (10 in. by 14 in.) + * 17 = Standard paper (11 in. by 17 in.) + * 18 = Note paper (8.5 in. by 11 in.) + * 19 = #9 envelope (3.875 in. by 8.875 in.) + * 20 = #10 envelope (4.125 in. by 9.5 in.) + * 21 = #11 envelope (4.5 in. by 10.375 in.) + * 22 = #12 envelope (4.75 in. by 11 in.) + * 23 = #14 envelope (5 in. by 11.5 in.) + * 24 = C paper (17 in. by 22 in.) + * 25 = D paper (22 in. by 34 in.) + * 26 = E paper (34 in. by 44 in.) + * 27 = DL envelope (110 mm by 220 mm) + * 28 = C5 envelope (162 mm by 229 mm) + * 29 = C3 envelope (324 mm by 458 mm) + * 30 = C4 envelope (229 mm by 324 mm) + * 31 = C6 envelope (114 mm by 162 mm) + * 32 = C65 envelope (114 mm by 229 mm) + * 33 = B4 envelope (250 mm by 353 mm) + * 34 = B5 envelope (176 mm by 250 mm) + * 35 = B6 envelope (176 mm by 125 mm) + * 36 = Italy envelope (110 mm by 230 mm) + * 37 = Monarch envelope (3.875 in. by 7.5 in.). + * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) + * 39 = US standard fanfold (14.875 in. by 11 in.) + * 40 = German standard fanfold (8.5 in. by 12 in.) + * 41 = German legal fanfold (8.5 in. by 13 in.) + * 42 = ISO B4 (250 mm by 353 mm) + * 43 = Japanese double postcard (200 mm by 148 mm) + * 44 = Standard paper (9 in. by 11 in.) + * 45 = Standard paper (10 in. by 11 in.) + * 46 = Standard paper (15 in. by 11 in.) + * 47 = Invite envelope (220 mm by 220 mm) + * 50 = Letter extra paper (9.275 in. by 12 in.) + * 51 = Legal extra paper (9.275 in. by 15 in.) + * 52 = Tabloid extra paper (11.69 in. by 18 in.) + * 53 = A4 extra paper (236 mm by 322 mm) + * 54 = Letter transverse paper (8.275 in. by 11 in.) + * 55 = A4 transverse paper (210 mm by 297 mm) + * 56 = Letter extra transverse paper (9.275 in. by 12 in.) + * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) + * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) + * 59 = Letter plus paper (8.5 in. by 12.69 in.) + * 60 = A4 plus paper (210 mm by 330 mm) + * 61 = A5 transverse paper (148 mm by 210 mm) + * 62 = JIS B5 transverse paper (182 mm by 257 mm) + * 63 = A3 extra paper (322 mm by 445 mm) + * 64 = A5 extra paper (174 mm by 235 mm) + * 65 = ISO B5 extra paper (201 mm by 276 mm) + * 66 = A2 paper (420 mm by 594 mm) + * 67 = A3 transverse paper (297 mm by 420 mm) + * 68 = A3 extra transverse paper (322 mm by 445 mm) + * </code> + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_PageSetup +{ + /* Paper size */ + const PAPERSIZE_LETTER = 1; + const PAPERSIZE_LETTER_SMALL = 2; + const PAPERSIZE_TABLOID = 3; + const PAPERSIZE_LEDGER = 4; + const PAPERSIZE_LEGAL = 5; + const PAPERSIZE_STATEMENT = 6; + const PAPERSIZE_EXECUTIVE = 7; + const PAPERSIZE_A3 = 8; + const PAPERSIZE_A4 = 9; + const PAPERSIZE_A4_SMALL = 10; + const PAPERSIZE_A5 = 11; + const PAPERSIZE_B4 = 12; + const PAPERSIZE_B5 = 13; + const PAPERSIZE_FOLIO = 14; + const PAPERSIZE_QUARTO = 15; + const PAPERSIZE_STANDARD_1 = 16; + const PAPERSIZE_STANDARD_2 = 17; + const PAPERSIZE_NOTE = 18; + const PAPERSIZE_NO9_ENVELOPE = 19; + const PAPERSIZE_NO10_ENVELOPE = 20; + const PAPERSIZE_NO11_ENVELOPE = 21; + const PAPERSIZE_NO12_ENVELOPE = 22; + const PAPERSIZE_NO14_ENVELOPE = 23; + const PAPERSIZE_C = 24; + const PAPERSIZE_D = 25; + const PAPERSIZE_E = 26; + const PAPERSIZE_DL_ENVELOPE = 27; + const PAPERSIZE_C5_ENVELOPE = 28; + const PAPERSIZE_C3_ENVELOPE = 29; + const PAPERSIZE_C4_ENVELOPE = 30; + const PAPERSIZE_C6_ENVELOPE = 31; + const PAPERSIZE_C65_ENVELOPE = 32; + const PAPERSIZE_B4_ENVELOPE = 33; + const PAPERSIZE_B5_ENVELOPE = 34; + const PAPERSIZE_B6_ENVELOPE = 35; + const PAPERSIZE_ITALY_ENVELOPE = 36; + const PAPERSIZE_MONARCH_ENVELOPE = 37; + const PAPERSIZE_6_3_4_ENVELOPE = 38; + const PAPERSIZE_US_STANDARD_FANFOLD = 39; + const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; + const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; + const PAPERSIZE_ISO_B4 = 42; + const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; + const PAPERSIZE_STANDARD_PAPER_1 = 44; + const PAPERSIZE_STANDARD_PAPER_2 = 45; + const PAPERSIZE_STANDARD_PAPER_3 = 46; + const PAPERSIZE_INVITE_ENVELOPE = 47; + const PAPERSIZE_LETTER_EXTRA_PAPER = 48; + const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; + const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; + const PAPERSIZE_A4_EXTRA_PAPER = 51; + const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; + const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; + const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; + const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; + const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; + const PAPERSIZE_LETTER_PLUS_PAPER = 57; + const PAPERSIZE_A4_PLUS_PAPER = 58; + const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; + const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; + const PAPERSIZE_A3_EXTRA_PAPER = 61; + const PAPERSIZE_A5_EXTRA_PAPER = 62; + const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; + const PAPERSIZE_A2_PAPER = 64; + const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; + const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; + + /* Page orientation */ + const ORIENTATION_DEFAULT = 'default'; + const ORIENTATION_LANDSCAPE = 'landscape'; + const ORIENTATION_PORTRAIT = 'portrait'; + + /* Print Range Set Method */ + const SETPRINTRANGE_OVERWRITE = 'O'; + const SETPRINTRANGE_INSERT = 'I'; + + + /** + * Paper size + * + * @var int + */ + private $paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER; + + /** + * Orientation + * + * @var string + */ + private $orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT; + + /** + * Scale (Print Scale) + * + * Print scaling. Valid values range from 10 to 400 + * This setting is overridden when fitToWidth and/or fitToHeight are in use + * + * @var int? + */ + private $scale = 100; + + /** + * Fit To Page + * Whether scale or fitToWith / fitToHeight applies + * + * @var boolean + */ + private $fitToPage = false; + + /** + * Fit To Height + * Number of vertical pages to fit on + * + * @var int? + */ + private $fitToHeight = 1; + + /** + * Fit To Width + * Number of horizontal pages to fit on + * + * @var int? + */ + private $fitToWidth = 1; + + /** + * Columns to repeat at left + * + * @var array Containing start column and end column, empty array if option unset + */ + private $columnsToRepeatAtLeft = array('', ''); + + /** + * Rows to repeat at top + * + * @var array Containing start row number and end row number, empty array if option unset + */ + private $rowsToRepeatAtTop = array(0, 0); + + /** + * Center page horizontally + * + * @var boolean + */ + private $horizontalCentered = false; + + /** + * Center page vertically + * + * @var boolean + */ + private $verticalCentered = false; + + /** + * Print area + * + * @var string + */ + private $printArea = null; + + /** + * First page number + * + * @var int + */ + private $firstPageNumber = null; + + /** + * Create a new PHPExcel_Worksheet_PageSetup + */ + public function __construct() + { + } + + /** + * Get Paper Size + * + * @return int + */ + public function getPaperSize() + { + return $this->paperSize; + } + + /** + * Set Paper Size + * + * @param int $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) + { + $this->paperSize = $pValue; + return $this; + } + + /** + * Get Orientation + * + * @return string + */ + public function getOrientation() + { + return $this->orientation; + } + + /** + * Set Orientation + * + * @param string $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + { + $this->orientation = $pValue; + return $this; + } + + /** + * Get Scale + * + * @return int? + */ + public function getScale() + { + return $this->scale; + } + + /** + * Set Scale + * + * Print scaling. Valid values range from 10 to 400 + * This setting is overridden when fitToWidth and/or fitToHeight are in use + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setScale($pValue = 100, $pUpdate = true) + { + // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, + // but it is apparently still able to handle any scale >= 0, where 0 results in 100 + if (($pValue >= 0) || is_null($pValue)) { + $this->scale = $pValue; + if ($pUpdate) { + $this->fitToPage = false; + } + } else { + throw new PHPExcel_Exception("Scale must not be negative"); + } + return $this; + } + + /** + * Get Fit To Page + * + * @return boolean + */ + public function getFitToPage() + { + return $this->fitToPage; + } + + /** + * Set Fit To Page + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToPage($pValue = true) + { + $this->fitToPage = $pValue; + return $this; + } + + /** + * Get Fit To Height + * + * @return int? + */ + public function getFitToHeight() + { + return $this->fitToHeight; + } + + /** + * Set Fit To Height + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToHeight($pValue = 1, $pUpdate = true) + { + $this->fitToHeight = $pValue; + if ($pUpdate) { + $this->fitToPage = true; + } + return $this; + } + + /** + * Get Fit To Width + * + * @return int? + */ + public function getFitToWidth() + { + return $this->fitToWidth; + } + + /** + * Set Fit To Width + * + * @param int? $pValue + * @param boolean $pUpdate Update fitToPage so it applies rather than scaling + * @return PHPExcel_Worksheet_PageSetup + */ + public function setFitToWidth($pValue = 1, $pUpdate = true) + { + $this->fitToWidth = $pValue; + if ($pUpdate) { + $this->fitToPage = true; + } + return $this; + } + + /** + * Is Columns to repeat at left set? + * + * @return boolean + */ + public function isColumnsToRepeatAtLeftSet() + { + if (is_array($this->columnsToRepeatAtLeft)) { + if ($this->columnsToRepeatAtLeft[0] != '' && $this->columnsToRepeatAtLeft[1] != '') { + return true; + } + } + + return false; + } + + /** + * Get Columns to repeat at left + * + * @return array Containing start column and end column, empty array if option unset + */ + public function getColumnsToRepeatAtLeft() + { + return $this->columnsToRepeatAtLeft; + } + + /** + * Set Columns to repeat at left + * + * @param array $pValue Containing start column and end column, empty array if option unset + * @return PHPExcel_Worksheet_PageSetup + */ + public function setColumnsToRepeatAtLeft($pValue = null) + { + if (is_array($pValue)) { + $this->columnsToRepeatAtLeft = $pValue; + } + return $this; + } + + /** + * Set Columns to repeat at left by start and end + * + * @param string $pStart + * @param string $pEnd + * @return PHPExcel_Worksheet_PageSetup + */ + public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') + { + $this->columnsToRepeatAtLeft = array($pStart, $pEnd); + return $this; + } + + /** + * Is Rows to repeat at top set? + * + * @return boolean + */ + public function isRowsToRepeatAtTopSet() + { + if (is_array($this->rowsToRepeatAtTop)) { + if ($this->rowsToRepeatAtTop[0] != 0 && $this->rowsToRepeatAtTop[1] != 0) { + return true; + } + } + + return false; + } + + /** + * Get Rows to repeat at top + * + * @return array Containing start column and end column, empty array if option unset + */ + public function getRowsToRepeatAtTop() + { + return $this->rowsToRepeatAtTop; + } + + /** + * Set Rows to repeat at top + * + * @param array $pValue Containing start column and end column, empty array if option unset + * @return PHPExcel_Worksheet_PageSetup + */ + public function setRowsToRepeatAtTop($pValue = null) + { + if (is_array($pValue)) { + $this->rowsToRepeatAtTop = $pValue; + } + return $this; + } + + /** + * Set Rows to repeat at top by start and end + * + * @param int $pStart + * @param int $pEnd + * @return PHPExcel_Worksheet_PageSetup + */ + public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) + { + $this->rowsToRepeatAtTop = array($pStart, $pEnd); + return $this; + } + + /** + * Get center page horizontally + * + * @return bool + */ + public function getHorizontalCentered() + { + return $this->horizontalCentered; + } + + /** + * Set center page horizontally + * + * @param bool $value + * @return PHPExcel_Worksheet_PageSetup + */ + public function setHorizontalCentered($value = false) + { + $this->horizontalCentered = $value; + return $this; + } + + /** + * Get center page vertically + * + * @return bool + */ + public function getVerticalCentered() + { + return $this->verticalCentered; + } + + /** + * Set center page vertically + * + * @param bool $value + * @return PHPExcel_Worksheet_PageSetup + */ + public function setVerticalCentered($value = false) + { + $this->verticalCentered = $value; + return $this; + } + + /** + * Get print area + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string + * Otherwise, the specific range identified by the value of $index will be returned + * Print areas are numbered from 1 + * @throws PHPExcel_Exception + * @return string + */ + public function getPrintArea($index = 0) + { + if ($index == 0) { + return $this->printArea; + } + $printAreas = explode(',', $this->printArea); + if (isset($printAreas[$index-1])) { + return $printAreas[$index-1]; + } + throw new PHPExcel_Exception("Requested Print Area does not exist"); + } + + /** + * Is print area set? + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or an index value of 0, will identify whether any print range is set + * Otherwise, existence of the range identified by the value of $index will be returned + * Print areas are numbered from 1 + * @return boolean + */ + public function isPrintAreaSet($index = 0) + { + if ($index == 0) { + return !is_null($this->printArea); + } + $printAreas = explode(',', $this->printArea); + return isset($printAreas[$index-1]); + } + + /** + * Clear a print area + * + * @param int $index Identifier for a specific print area range if several ranges have been set + * Default behaviour, or an index value of 0, will clear all print ranges that are set + * Otherwise, the range identified by the value of $index will be removed from the series + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + */ + public function clearPrintArea($index = 0) + { + if ($index == 0) { + $this->printArea = null; + } else { + $printAreas = explode(',', $this->printArea); + if (isset($printAreas[$index-1])) { + unset($printAreas[$index-1]); + $this->printArea = implode(',', $printAreas); + } + } + + return $this; + } + + /** + * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20' + * + * @param string $value + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * When the method is "O"verwrite, then a positive integer index will overwrite that indexed + * entry in the print areas list; a negative index value will identify which entry to + * overwrite working bacward through the print area to the list, with the last entry as -1. + * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. + * When the method is "I"nsert, then a positive index will insert after that indexed entry in + * the print areas list, while a negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @param string $method Determines the method used when setting multiple print areas + * Default behaviour, or the "O" method, overwrites existing print area + * The "I" method, inserts the new print area before any specified index, or at the end of the list + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) + { + if (strpos($value, '!') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not specify a worksheet.'); + } elseif (strpos($value, ':') === false) { + throw new PHPExcel_Exception('Cell coordinate must be a range of cells.'); + } elseif (strpos($value, '$') !== false) { + throw new PHPExcel_Exception('Cell coordinate must not be absolute.'); + } + $value = strtoupper($value); + + if ($method == self::SETPRINTRANGE_OVERWRITE) { + if ($index == 0) { + $this->printArea = $value; + } else { + $printAreas = explode(',', $this->printArea); + if ($index < 0) { + $index = count($printAreas) - abs($index) + 1; + } + if (($index <= 0) || ($index > count($printAreas))) { + throw new PHPExcel_Exception('Invalid index for setting print range.'); + } + $printAreas[$index-1] = $value; + $this->printArea = implode(',', $printAreas); + } + } elseif ($method == self::SETPRINTRANGE_INSERT) { + if ($index == 0) { + $this->printArea .= ($this->printArea == '') ? $value : ','.$value; + } else { + $printAreas = explode(',', $this->printArea); + if ($index < 0) { + $index = abs($index) - 1; + } + if ($index > count($printAreas)) { + throw new PHPExcel_Exception('Invalid index for setting print range.'); + } + $printAreas = array_merge(array_slice($printAreas, 0, $index), array($value), array_slice($printAreas, $index)); + $this->printArea = implode(',', $printAreas); + } + } else { + throw new PHPExcel_Exception('Invalid method for setting print range.'); + } + + return $this; + } + + /** + * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas + * + * @param string $value + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * A positive index will insert after that indexed entry in the print areas list, while a + * negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function addPrintArea($value, $index = -1) + { + return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); + } + + /** + * Set print area + * + * @param int $column1 Column 1 + * @param int $row1 Row 1 + * @param int $column2 Column 2 + * @param int $row2 Row 2 + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * When the method is "O"verwrite, then a positive integer index will overwrite that indexed + * entry in the print areas list; a negative index value will identify which entry to + * overwrite working bacward through the print area to the list, with the last entry as -1. + * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. + * When the method is "I"nsert, then a positive index will insert after that indexed entry in + * the print areas list, while a negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @param string $method Determines the method used when setting multiple print areas + * Default behaviour, or the "O" method, overwrites existing print area + * The "I" method, inserts the new print area before any specified index, or at the end of the list + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) + { + return $this->setPrintArea( + PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, + $index, + $method + ); + } + + /** + * Add a new print area to the list of print areas + * + * @param int $column1 Start Column for the print area + * @param int $row1 Start Row for the print area + * @param int $column2 End Column for the print area + * @param int $row2 End Row for the print area + * @param int $index Identifier for a specific print area range allowing several ranges to be set + * A positive index will insert after that indexed entry in the print areas list, while a + * negative index will insert before the indexed entry. + * Specifying an index value of 0, will always append the new print range at the end of the + * list. + * Print areas are numbered from 1 + * @return PHPExcel_Worksheet_PageSetup + * @throws PHPExcel_Exception + */ + public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) + { + return $this->setPrintArea( + PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, + $index, + self::SETPRINTRANGE_INSERT + ); + } + + /** + * Get first page number + * + * @return int + */ + public function getFirstPageNumber() + { + return $this->firstPageNumber; + } + + /** + * Set first page number + * + * @param int $value + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function setFirstPageNumber($value = null) + { + $this->firstPageNumber = $value; + return $this; + } + + /** + * Reset first page number + * + * @return PHPExcel_Worksheet_HeaderFooter + */ + public function resetFirstPageNumber() + { + return $this->setFirstPageNumber(null); + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Protection.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Protection.php new file mode 100644 index 00000000..00633eeb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Protection.php @@ -0,0 +1,581 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Worksheet_Protection + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Worksheet_Protection +{ + /** + * Sheet + * + * @var boolean + */ + private $sheet = false; + + /** + * Objects + * + * @var boolean + */ + private $objects = false; + + /** + * Scenarios + * + * @var boolean + */ + private $scenarios = false; + + /** + * Format cells + * + * @var boolean + */ + private $formatCells = false; + + /** + * Format columns + * + * @var boolean + */ + private $formatColumns = false; + + /** + * Format rows + * + * @var boolean + */ + private $formatRows = false; + + /** + * Insert columns + * + * @var boolean + */ + private $insertColumns = false; + + /** + * Insert rows + * + * @var boolean + */ + private $insertRows = false; + + /** + * Insert hyperlinks + * + * @var boolean + */ + private $insertHyperlinks = false; + + /** + * Delete columns + * + * @var boolean + */ + private $deleteColumns = false; + + /** + * Delete rows + * + * @var boolean + */ + private $deleteRows = false; + + /** + * Select locked cells + * + * @var boolean + */ + private $selectLockedCells = false; + + /** + * Sort + * + * @var boolean + */ + private $sort = false; + + /** + * AutoFilter + * + * @var boolean + */ + private $autoFilter = false; + + /** + * Pivot tables + * + * @var boolean + */ + private $pivotTables = false; + + /** + * Select unlocked cells + * + * @var boolean + */ + private $selectUnlockedCells = false; + + /** + * Password + * + * @var string + */ + private $password = ''; + + /** + * Create a new PHPExcel_Worksheet_Protection + */ + public function __construct() + { + } + + /** + * Is some sort of protection enabled? + * + * @return boolean + */ + public function isProtectionEnabled() + { + return $this->sheet || + $this->objects || + $this->scenarios || + $this->formatCells || + $this->formatColumns || + $this->formatRows || + $this->insertColumns || + $this->insertRows || + $this->insertHyperlinks || + $this->deleteColumns || + $this->deleteRows || + $this->selectLockedCells || + $this->sort || + $this->autoFilter || + $this->pivotTables || + $this->selectUnlockedCells; + } + + /** + * Get Sheet + * + * @return boolean + */ + public function getSheet() + { + return $this->sheet; + } + + /** + * Set Sheet + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setSheet($pValue = false) + { + $this->sheet = $pValue; + return $this; + } + + /** + * Get Objects + * + * @return boolean + */ + public function getObjects() + { + return $this->objects; + } + + /** + * Set Objects + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setObjects($pValue = false) + { + $this->objects = $pValue; + return $this; + } + + /** + * Get Scenarios + * + * @return boolean + */ + public function getScenarios() + { + return $this->scenarios; + } + + /** + * Set Scenarios + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setScenarios($pValue = false) + { + $this->scenarios = $pValue; + return $this; + } + + /** + * Get FormatCells + * + * @return boolean + */ + public function getFormatCells() + { + return $this->formatCells; + } + + /** + * Set FormatCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setFormatCells($pValue = false) + { + $this->formatCells = $pValue; + return $this; + } + + /** + * Get FormatColumns + * + * @return boolean + */ + public function getFormatColumns() + { + return $this->formatColumns; + } + + /** + * Set FormatColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setFormatColumns($pValue = false) + { + $this->formatColumns = $pValue; + return $this; + } + + /** + * Get FormatRows + * + * @return boolean + */ + public function getFormatRows() + { + return $this->formatRows; + } + + /** + * Set FormatRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setFormatRows($pValue = false) + { + $this->formatRows = $pValue; + return $this; + } + + /** + * Get InsertColumns + * + * @return boolean + */ + public function getInsertColumns() + { + return $this->insertColumns; + } + + /** + * Set InsertColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setInsertColumns($pValue = false) + { + $this->insertColumns = $pValue; + return $this; + } + + /** + * Get InsertRows + * + * @return boolean + */ + public function getInsertRows() + { + return $this->insertRows; + } + + /** + * Set InsertRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setInsertRows($pValue = false) + { + $this->insertRows = $pValue; + return $this; + } + + /** + * Get InsertHyperlinks + * + * @return boolean + */ + public function getInsertHyperlinks() + { + return $this->insertHyperlinks; + } + + /** + * Set InsertHyperlinks + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setInsertHyperlinks($pValue = false) + { + $this->insertHyperlinks = $pValue; + return $this; + } + + /** + * Get DeleteColumns + * + * @return boolean + */ + public function getDeleteColumns() + { + return $this->deleteColumns; + } + + /** + * Set DeleteColumns + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setDeleteColumns($pValue = false) + { + $this->deleteColumns = $pValue; + return $this; + } + + /** + * Get DeleteRows + * + * @return boolean + */ + public function getDeleteRows() + { + return $this->deleteRows; + } + + /** + * Set DeleteRows + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setDeleteRows($pValue = false) + { + $this->deleteRows = $pValue; + return $this; + } + + /** + * Get SelectLockedCells + * + * @return boolean + */ + public function getSelectLockedCells() + { + return $this->selectLockedCells; + } + + /** + * Set SelectLockedCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setSelectLockedCells($pValue = false) + { + $this->selectLockedCells = $pValue; + return $this; + } + + /** + * Get Sort + * + * @return boolean + */ + public function getSort() + { + return $this->sort; + } + + /** + * Set Sort + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setSort($pValue = false) + { + $this->sort = $pValue; + return $this; + } + + /** + * Get AutoFilter + * + * @return boolean + */ + public function getAutoFilter() + { + return $this->autoFilter; + } + + /** + * Set AutoFilter + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setAutoFilter($pValue = false) + { + $this->autoFilter = $pValue; + return $this; + } + + /** + * Get PivotTables + * + * @return boolean + */ + public function getPivotTables() + { + return $this->pivotTables; + } + + /** + * Set PivotTables + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setPivotTables($pValue = false) + { + $this->pivotTables = $pValue; + return $this; + } + + /** + * Get SelectUnlockedCells + * + * @return boolean + */ + public function getSelectUnlockedCells() + { + return $this->selectUnlockedCells; + } + + /** + * Set SelectUnlockedCells + * + * @param boolean $pValue + * @return PHPExcel_Worksheet_Protection + */ + public function setSelectUnlockedCells($pValue = false) + { + $this->selectUnlockedCells = $pValue; + return $this; + } + + /** + * Get Password (hashed) + * + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * Set Password + * + * @param string $pValue + * @param boolean $pAlreadyHashed If the password has already been hashed, set this to true + * @return PHPExcel_Worksheet_Protection + */ + public function setPassword($pValue = '', $pAlreadyHashed = false) + { + if (!$pAlreadyHashed) { + $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue); + } + $this->password = $pValue; + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Row.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Row.php new file mode 100644 index 00000000..4f6034f5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/Row.php @@ -0,0 +1,86 @@ +<?php + +/** + * PHPExcel_Worksheet_Row + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_Row +{ + /** + * PHPExcel_Worksheet + * + * @var PHPExcel_Worksheet + */ + private $parent; + + /** + * Row index + * + * @var int + */ + private $rowIndex = 0; + + /** + * Create a new row + * + * @param PHPExcel_Worksheet $parent + * @param int $rowIndex + */ + public function __construct(PHPExcel_Worksheet $parent = null, $rowIndex = 1) + { + // Set parent and row index + $this->parent = $parent; + $this->rowIndex = $rowIndex; + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->parent); + } + + /** + * Get row index + * + * @return int + */ + public function getRowIndex() + { + return $this->rowIndex; + } + + /** + * Get cell iterator + * + * @param string $startColumn The column address at which to start iterating + * @param string $endColumn Optionally, the column address at which to stop iterating + * @return PHPExcel_Worksheet_CellIterator + */ + public function getCellIterator($startColumn = 'A', $endColumn = null) + { + return new PHPExcel_Worksheet_RowCellIterator($this->parent, $this->rowIndex, $startColumn, $endColumn); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowCellIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowCellIterator.php new file mode 100644 index 00000000..90eb9c9f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowCellIterator.php @@ -0,0 +1,225 @@ +<?php + +/** + * PHPExcel_Worksheet_RowCellIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_RowCellIterator extends PHPExcel_Worksheet_CellIterator implements Iterator +{ + /** + * Row index + * + * @var int + */ + protected $rowIndex; + + /** + * Start position + * + * @var int + */ + protected $startColumn = 0; + + /** + * End position + * + * @var int + */ + protected $endColumn = 0; + + /** + * Create a new column iterator + * + * @param PHPExcel_Worksheet $subject The worksheet to iterate over + * @param integer $rowIndex The row that we want to iterate + * @param string $startColumn The column address at which to start iterating + * @param string $endColumn Optionally, the column address at which to stop iterating + */ + public function __construct(PHPExcel_Worksheet $subject = null, $rowIndex = 1, $startColumn = 'A', $endColumn = null) + { + // Set subject and row index + $this->subject = $subject; + $this->rowIndex = $rowIndex; + $this->resetEnd($endColumn); + $this->resetStart($startColumn); + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * (Re)Set the start column and the current column pointer + * + * @param integer $startColumn The column address at which to start iterating + * @return PHPExcel_Worksheet_RowCellIterator + * @throws PHPExcel_Exception + */ + public function resetStart($startColumn = 'A') + { + $startColumnIndex = PHPExcel_Cell::columnIndexFromString($startColumn) - 1; + $this->startColumn = $startColumnIndex; + $this->adjustForExistingOnlyRange(); + $this->seek(PHPExcel_Cell::stringFromColumnIndex($this->startColumn)); + + return $this; + } + + /** + * (Re)Set the end column + * + * @param string $endColumn The column address at which to stop iterating + * @return PHPExcel_Worksheet_RowCellIterator + * @throws PHPExcel_Exception + */ + public function resetEnd($endColumn = null) + { + $endColumn = ($endColumn) ? $endColumn : $this->subject->getHighestColumn(); + $this->endColumn = PHPExcel_Cell::columnIndexFromString($endColumn) - 1; + $this->adjustForExistingOnlyRange(); + + return $this; + } + + /** + * Set the column pointer to the selected column + * + * @param string $column The column address to set the current pointer at + * @return PHPExcel_Worksheet_RowCellIterator + * @throws PHPExcel_Exception + */ + public function seek($column = 'A') + { + $column = PHPExcel_Cell::columnIndexFromString($column) - 1; + if (($column < $this->startColumn) || ($column > $this->endColumn)) { + throw new PHPExcel_Exception("Column $column is out of range ({$this->startColumn} - {$this->endColumn})"); + } elseif ($this->onlyExistingCells && !($this->subject->cellExistsByColumnAndRow($column, $this->rowIndex))) { + throw new PHPExcel_Exception('In "IterateOnlyExistingCells" mode and Cell does not exist'); + } + $this->position = $column; + + return $this; + } + + /** + * Rewind the iterator to the starting column + */ + public function rewind() + { + $this->position = $this->startColumn; + } + + /** + * Return the current cell in this worksheet row + * + * @return PHPExcel_Cell + */ + public function current() + { + return $this->subject->getCellByColumnAndRow($this->position, $this->rowIndex); + } + + /** + * Return the current iterator key + * + * @return string + */ + public function key() + { + return PHPExcel_Cell::stringFromColumnIndex($this->position); + } + + /** + * Set the iterator to its next value + */ + public function next() + { + do { + ++$this->position; + } while (($this->onlyExistingCells) && + (!$this->subject->cellExistsByColumnAndRow($this->position, $this->rowIndex)) && + ($this->position <= $this->endColumn)); + } + + /** + * Set the iterator to its previous value + * + * @throws PHPExcel_Exception + */ + public function prev() + { + if ($this->position <= $this->startColumn) { + throw new PHPExcel_Exception( + "Column is already at the beginning of range (" . + PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . " - " . + PHPExcel_Cell::stringFromColumnIndex($this->endColumn) . ")" + ); + } + + do { + --$this->position; + } while (($this->onlyExistingCells) && + (!$this->subject->cellExistsByColumnAndRow($this->position, $this->rowIndex)) && + ($this->position >= $this->startColumn)); + } + + /** + * Indicate if more columns exist in the worksheet range of columns that we're iterating + * + * @return boolean + */ + public function valid() + { + return $this->position <= $this->endColumn; + } + + /** + * Validate start/end values for "IterateOnlyExistingCells" mode, and adjust if necessary + * + * @throws PHPExcel_Exception + */ + protected function adjustForExistingOnlyRange() + { + if ($this->onlyExistingCells) { + while ((!$this->subject->cellExistsByColumnAndRow($this->startColumn, $this->rowIndex)) && + ($this->startColumn <= $this->endColumn)) { + ++$this->startColumn; + } + if ($this->startColumn > $this->endColumn) { + throw new PHPExcel_Exception('No cells exist within the specified range'); + } + while ((!$this->subject->cellExistsByColumnAndRow($this->endColumn, $this->rowIndex)) && + ($this->endColumn >= $this->startColumn)) { + --$this->endColumn; + } + if ($this->endColumn < $this->startColumn) { + throw new PHPExcel_Exception('No cells exist within the specified range'); + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowDimension.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowDimension.php new file mode 100644 index 00000000..c1474862 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowDimension.php @@ -0,0 +1,132 @@ +<?php + +/** + * PHPExcel_Worksheet_RowDimension + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_RowDimension extends PHPExcel_Worksheet_Dimension +{ + /** + * Row index + * + * @var int + */ + private $rowIndex; + + /** + * Row height (in pt) + * + * When this is set to a negative value, the row height should be ignored by IWriter + * + * @var double + */ + private $height = -1; + + /** + * ZeroHeight for Row? + * + * @var bool + */ + private $zeroHeight = false; + + /** + * Create a new PHPExcel_Worksheet_RowDimension + * + * @param int $pIndex Numeric row index + */ + public function __construct($pIndex = 0) + { + // Initialise values + $this->rowIndex = $pIndex; + + // set dimension as unformatted by default + parent::__construct(null); + } + + /** + * Get Row Index + * + * @return int + */ + public function getRowIndex() + { + return $this->rowIndex; + } + + /** + * Set Row Index + * + * @param int $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setRowIndex($pValue) + { + $this->rowIndex = $pValue; + return $this; + } + + /** + * Get Row Height + * + * @return double + */ + public function getRowHeight() + { + return $this->height; + } + + /** + * Set Row Height + * + * @param double $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setRowHeight($pValue = -1) + { + $this->height = $pValue; + return $this; + } + + /** + * Get ZeroHeight + * + * @return bool + */ + public function getZeroHeight() + { + return $this->zeroHeight; + } + + /** + * Set ZeroHeight + * + * @param bool $pValue + * @return PHPExcel_Worksheet_RowDimension + */ + public function setZeroHeight($pValue = false) + { + $this->zeroHeight = $pValue; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowIterator.php new file mode 100644 index 00000000..9ddb3e03 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/RowIterator.php @@ -0,0 +1,192 @@ +<?php + +/** + * PHPExcel_Worksheet_RowIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_RowIterator implements Iterator +{ + /** + * PHPExcel_Worksheet to iterate + * + * @var PHPExcel_Worksheet + */ + private $subject; + + /** + * Current iterator position + * + * @var int + */ + private $position = 1; + + /** + * Start position + * + * @var int + */ + private $startRow = 1; + + + /** + * End position + * + * @var int + */ + private $endRow = 1; + + + /** + * Create a new row iterator + * + * @param PHPExcel_Worksheet $subject The worksheet to iterate over + * @param integer $startRow The row number at which to start iterating + * @param integer $endRow Optionally, the row number at which to stop iterating + */ + public function __construct(PHPExcel_Worksheet $subject, $startRow = 1, $endRow = null) + { + // Set subject + $this->subject = $subject; + $this->resetEnd($endRow); + $this->resetStart($startRow); + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * (Re)Set the start row and the current row pointer + * + * @param integer $startRow The row number at which to start iterating + * @return PHPExcel_Worksheet_RowIterator + * @throws PHPExcel_Exception + */ + public function resetStart($startRow = 1) + { + if ($startRow > $this->subject->getHighestRow()) { + throw new PHPExcel_Exception("Start row ({$startRow}) is beyond highest row ({$this->subject->getHighestRow()})"); + } + + $this->startRow = $startRow; + if ($this->endRow < $this->startRow) { + $this->endRow = $this->startRow; + } + $this->seek($startRow); + + return $this; + } + + /** + * (Re)Set the end row + * + * @param integer $endRow The row number at which to stop iterating + * @return PHPExcel_Worksheet_RowIterator + */ + public function resetEnd($endRow = null) + { + $this->endRow = ($endRow) ? $endRow : $this->subject->getHighestRow(); + + return $this; + } + + /** + * Set the row pointer to the selected row + * + * @param integer $row The row number to set the current pointer at + * @return PHPExcel_Worksheet_RowIterator + * @throws PHPExcel_Exception + */ + public function seek($row = 1) + { + if (($row < $this->startRow) || ($row > $this->endRow)) { + throw new PHPExcel_Exception("Row $row is out of range ({$this->startRow} - {$this->endRow})"); + } + $this->position = $row; + + return $this; + } + + /** + * Rewind the iterator to the starting row + */ + public function rewind() + { + $this->position = $this->startRow; + } + + /** + * Return the current row in this worksheet + * + * @return PHPExcel_Worksheet_Row + */ + public function current() + { + return new PHPExcel_Worksheet_Row($this->subject, $this->position); + } + + /** + * Return the current iterator key + * + * @return int + */ + public function key() + { + return $this->position; + } + + /** + * Set the iterator to its next value + */ + public function next() + { + ++$this->position; + } + + /** + * Set the iterator to its previous value + */ + public function prev() + { + if ($this->position <= $this->startRow) { + throw new PHPExcel_Exception("Row is already at the beginning of range ({$this->startRow} - {$this->endRow})"); + } + + --$this->position; + } + + /** + * Indicate if more rows exist in the worksheet range of rows that we're iterating + * + * @return boolean + */ + public function valid() + { + return $this->position <= $this->endRow; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/SheetView.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/SheetView.php new file mode 100644 index 00000000..5aaef3ba --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Worksheet/SheetView.php @@ -0,0 +1,187 @@ +<?php + +/** + * PHPExcel_Worksheet_SheetView + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Worksheet + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Worksheet_SheetView +{ + + /* Sheet View types */ + const SHEETVIEW_NORMAL = 'normal'; + const SHEETVIEW_PAGE_LAYOUT = 'pageLayout'; + const SHEETVIEW_PAGE_BREAK_PREVIEW = 'pageBreakPreview'; + + private static $sheetViewTypes = array( + self::SHEETVIEW_NORMAL, + self::SHEETVIEW_PAGE_LAYOUT, + self::SHEETVIEW_PAGE_BREAK_PREVIEW, + ); + + /** + * ZoomScale + * + * Valid values range from 10 to 400. + * + * @var int + */ + private $zoomScale = 100; + + /** + * ZoomScaleNormal + * + * Valid values range from 10 to 400. + * + * @var int + */ + private $zoomScaleNormal = 100; + + /** + * View + * + * Valid values range from 10 to 400. + * + * @var string + */ + private $sheetviewType = self::SHEETVIEW_NORMAL; + + /** + * Create a new PHPExcel_Worksheet_SheetView + */ + public function __construct() + { + } + + /** + * Get ZoomScale + * + * @return int + */ + public function getZoomScale() + { + return $this->zoomScale; + } + + /** + * Set ZoomScale + * + * Valid values range from 10 to 400. + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setZoomScale($pValue = 100) + { + // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, + // but it is apparently still able to handle any scale >= 1 + if (($pValue >= 1) || is_null($pValue)) { + $this->zoomScale = $pValue; + } else { + throw new PHPExcel_Exception("Scale must be greater than or equal to 1."); + } + return $this; + } + + /** + * Get ZoomScaleNormal + * + * @return int + */ + public function getZoomScaleNormal() + { + return $this->zoomScaleNormal; + } + + /** + * Set ZoomScale + * + * Valid values range from 10 to 400. + * + * @param int $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setZoomScaleNormal($pValue = 100) + { + if (($pValue >= 1) || is_null($pValue)) { + $this->zoomScaleNormal = $pValue; + } else { + throw new PHPExcel_Exception("Scale must be greater than or equal to 1."); + } + return $this; + } + + /** + * Get View + * + * @return string + */ + public function getView() + { + return $this->sheetviewType; + } + + /** + * Set View + * + * Valid values are + * 'normal' self::SHEETVIEW_NORMAL + * 'pageLayout' self::SHEETVIEW_PAGE_LAYOUT + * 'pageBreakPreview' self::SHEETVIEW_PAGE_BREAK_PREVIEW + * + * @param string $pValue + * @throws PHPExcel_Exception + * @return PHPExcel_Worksheet_SheetView + */ + public function setView($pValue = null) + { + // MS Excel 2007 allows setting the view to 'normal', 'pageLayout' or 'pageBreakPreview' via the user interface + if ($pValue === null) { + $pValue = self::SHEETVIEW_NORMAL; + } + if (in_array($pValue, self::$sheetViewTypes)) { + $this->sheetviewType = $pValue; + } else { + throw new PHPExcel_Exception("Invalid sheetview layout type."); + } + + return $this; + } + + /** + * Implement PHP __clone to create a deep clone, not just a shallow copy. + */ + public function __clone() + { + $vars = get_object_vars($this); + foreach ($vars as $key => $value) { + if (is_object($value)) { + $this->$key = clone $value; + } else { + $this->$key = $value; + } + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/WorksheetIterator.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/WorksheetIterator.php new file mode 100644 index 00000000..cb1b2811 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/WorksheetIterator.php @@ -0,0 +1,108 @@ +<?php + +/** + * PHPExcel_WorksheetIterator + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_WorksheetIterator implements Iterator +{ + /** + * Spreadsheet to iterate + * + * @var PHPExcel + */ + private $subject; + + /** + * Current iterator position + * + * @var int + */ + private $position = 0; + + /** + * Create a new worksheet iterator + * + * @param PHPExcel $subject + */ + public function __construct(PHPExcel $subject = null) + { + // Set subject + $this->subject = $subject; + } + + /** + * Destructor + */ + public function __destruct() + { + unset($this->subject); + } + + /** + * Rewind iterator + */ + public function rewind() + { + $this->position = 0; + } + + /** + * Current PHPExcel_Worksheet + * + * @return PHPExcel_Worksheet + */ + public function current() + { + return $this->subject->getSheet($this->position); + } + + /** + * Current key + * + * @return int + */ + public function key() + { + return $this->position; + } + + /** + * Next value + */ + public function next() + { + ++$this->position; + } + + /** + * More PHPExcel_Worksheet instances available? + * + * @return boolean + */ + public function valid() + { + return $this->position < $this->subject->getSheetCount(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Abstract.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Abstract.php new file mode 100644 index 00000000..2a797a94 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Abstract.php @@ -0,0 +1,157 @@ +<?php + +/** + * PHPExcel_Writer_Abstract + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * Write charts that are defined in the workbook? + * Identifies whether the Writer should write definitions for any charts that exist in the PHPExcel object; + * + * @var boolean + */ + protected $includeCharts = false; + + /** + * Pre-calculate formulas + * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are + * immediately available to MS Excel or other office spreadsheet viewer when opening the file + * + * @var boolean + */ + protected $preCalculateFormulas = true; + + /** + * Use disk caching where possible? + * + * @var boolean + */ + protected $_useDiskCaching = false; + + /** + * Disk caching directory + * + * @var string + */ + protected $_diskCachingDirectory = './'; + + /** + * Write charts in workbook? + * If this is true, then the Writer will write definitions for any charts that exist in the PHPExcel object. + * If false (the default) it will ignore any charts defined in the PHPExcel object. + * + * @return boolean + */ + public function getIncludeCharts() + { + return $this->includeCharts; + } + + /** + * Set write charts in workbook + * Set to true, to advise the Writer to include any charts that exist in the PHPExcel object. + * Set to false (the default) to ignore charts. + * + * @param boolean $pValue + * @return PHPExcel_Writer_IWriter + */ + public function setIncludeCharts($pValue = false) + { + $this->includeCharts = (boolean) $pValue; + return $this; + } + + /** + * Get Pre-Calculate Formulas flag + * If this is true (the default), then the writer will recalculate all formulae in a workbook when saving, + * so that the pre-calculated values are immediately available to MS Excel or other office spreadsheet + * viewer when opening the file + * If false, then formulae are not calculated on save. This is faster for saving in PHPExcel, but slower + * when opening the resulting file in MS Excel, because Excel has to recalculate the formulae itself + * + * @return boolean + */ + public function getPreCalculateFormulas() + { + return $this->preCalculateFormulas; + } + + /** + * Set Pre-Calculate Formulas + * Set to true (the default) to advise the Writer to calculate all formulae on save + * Set to false to prevent precalculation of formulae on save. + * + * @param boolean $pValue Pre-Calculate Formulas? + * @return PHPExcel_Writer_IWriter + */ + public function setPreCalculateFormulas($pValue = true) + { + $this->preCalculateFormulas = (boolean) $pValue; + return $this; + } + + /** + * Get use disk caching where possible? + * + * @return boolean + */ + public function getUseDiskCaching() + { + return $this->_useDiskCaching; + } + + /** + * Set use disk caching where possible? + * + * @param boolean $pValue + * @param string $pDirectory Disk caching directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_Excel2007 + */ + public function setUseDiskCaching($pValue = false, $pDirectory = null) + { + $this->_useDiskCaching = $pValue; + + if ($pDirectory !== null) { + if (is_dir($pDirectory)) { + $this->_diskCachingDirectory = $pDirectory; + } else { + throw new PHPExcel_Writer_Exception("Directory does not exist: $pDirectory"); + } + } + return $this; + } + + /** + * Get disk caching directory + * + * @return string + */ + public function getDiskCachingDirectory() + { + return $this->_diskCachingDirectory; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/CSV.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/CSV.php new file mode 100644 index 00000000..e59c3013 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/CSV.php @@ -0,0 +1,352 @@ +<?php + +/** + * PHPExcel_Writer_CSV + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_CSV + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_CSV extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * PHPExcel object + * + * @var PHPExcel + */ + private $phpExcel; + + /** + * Delimiter + * + * @var string + */ + private $delimiter = ','; + + /** + * Enclosure + * + * @var string + */ + private $enclosure = '"'; + + /** + * Line ending + * + * @var string + */ + private $lineEnding = PHP_EOL; + + /** + * Sheet index to write + * + * @var int + */ + private $sheetIndex = 0; + + /** + * Whether to write a BOM (for UTF8). + * + * @var boolean + */ + private $useBOM = false; + + /** + * Whether to write a Separator line as the first line of the file + * sep=x + * + * @var boolean + */ + private $includeSeparatorLine = false; + + /** + * Whether to write a fully Excel compatible CSV file. + * + * @var boolean + */ + private $excelCompatibility = false; + + /** + * Create a new PHPExcel_Writer_CSV + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + $this->phpExcel = $phpExcel; + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + // Fetch sheet + $sheet = $this->phpExcel->getSheet($this->sheetIndex); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog(false); + $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Open file + $fileHandle = fopen($pFilename, 'wb+'); + if ($fileHandle === false) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + if ($this->excelCompatibility) { + $this->setUseBOM(true); // Enforce UTF-8 BOM Header + $this->setIncludeSeparatorLine(true); // Set separator line + $this->setEnclosure('"'); // Set enclosure to " + $this->setDelimiter(";"); // Set delimiter to a semi-colon + $this->setLineEnding("\r\n"); + } + if ($this->useBOM) { + // Write the UTF-8 BOM code if required + fwrite($fileHandle, "\xEF\xBB\xBF"); + } + if ($this->includeSeparatorLine) { + // Write the separator line if required + fwrite($fileHandle, 'sep=' . $this->getDelimiter() . $this->lineEnding); + } + + // Identify the range that we need to extract from the worksheet + $maxCol = $sheet->getHighestDataColumn(); + $maxRow = $sheet->getHighestDataRow(); + + // Write rows to file + for ($row = 1; $row <= $maxRow; ++$row) { + // Convert the row to an array... + $cellsArray = $sheet->rangeToArray('A'.$row.':'.$maxCol.$row, '', $this->preCalculateFormulas); + // ... and write to the file + $this->writeLine($fileHandle, $cellsArray[0]); + } + + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Get delimiter + * + * @return string + */ + public function getDelimiter() + { + return $this->delimiter; + } + + /** + * Set delimiter + * + * @param string $pValue Delimiter, defaults to , + * @return PHPExcel_Writer_CSV + */ + public function setDelimiter($pValue = ',') + { + $this->delimiter = $pValue; + return $this; + } + + /** + * Get enclosure + * + * @return string + */ + public function getEnclosure() + { + return $this->enclosure; + } + + /** + * Set enclosure + * + * @param string $pValue Enclosure, defaults to " + * @return PHPExcel_Writer_CSV + */ + public function setEnclosure($pValue = '"') + { + if ($pValue == '') { + $pValue = null; + } + $this->enclosure = $pValue; + return $this; + } + + /** + * Get line ending + * + * @return string + */ + public function getLineEnding() + { + return $this->lineEnding; + } + + /** + * Set line ending + * + * @param string $pValue Line ending, defaults to OS line ending (PHP_EOL) + * @return PHPExcel_Writer_CSV + */ + public function setLineEnding($pValue = PHP_EOL) + { + $this->lineEnding = $pValue; + return $this; + } + + /** + * Get whether BOM should be used + * + * @return boolean + */ + public function getUseBOM() + { + return $this->useBOM; + } + + /** + * Set whether BOM should be used + * + * @param boolean $pValue Use UTF-8 byte-order mark? Defaults to false + * @return PHPExcel_Writer_CSV + */ + public function setUseBOM($pValue = false) + { + $this->useBOM = $pValue; + return $this; + } + + /** + * Get whether a separator line should be included + * + * @return boolean + */ + public function getIncludeSeparatorLine() + { + return $this->includeSeparatorLine; + } + + /** + * Set whether a separator line should be included as the first line of the file + * + * @param boolean $pValue Use separator line? Defaults to false + * @return PHPExcel_Writer_CSV + */ + public function setIncludeSeparatorLine($pValue = false) + { + $this->includeSeparatorLine = $pValue; + return $this; + } + + /** + * Get whether the file should be saved with full Excel Compatibility + * + * @return boolean + */ + public function getExcelCompatibility() + { + return $this->excelCompatibility; + } + + /** + * Set whether the file should be saved with full Excel Compatibility + * + * @param boolean $pValue Set the file to be written as a fully Excel compatible csv file + * Note that this overrides other settings such as useBOM, enclosure and delimiter + * @return PHPExcel_Writer_CSV + */ + public function setExcelCompatibility($pValue = false) + { + $this->excelCompatibility = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() + { + return $this->sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Writer_CSV + */ + public function setSheetIndex($pValue = 0) + { + $this->sheetIndex = $pValue; + return $this; + } + + /** + * Write line to CSV file + * + * @param mixed $pFileHandle PHP filehandle + * @param array $pValues Array containing values in a row + * @throws PHPExcel_Writer_Exception + */ + private function writeLine($pFileHandle = null, $pValues = null) + { + if (is_array($pValues)) { + // No leading delimiter + $writeDelimiter = false; + + // Build the line + $line = ''; + + foreach ($pValues as $element) { + // Escape enclosures + $element = str_replace($this->enclosure, $this->enclosure . $this->enclosure, $element); + + // Add delimiter + if ($writeDelimiter) { + $line .= $this->delimiter; + } else { + $writeDelimiter = true; + } + + // Add enclosed string + $line .= $this->enclosure . $element . $this->enclosure; + } + + // Add line ending + $line .= $this->lineEnding; + + // Write to file + fwrite($pFileHandle, $line); + } else { + throw new PHPExcel_Writer_Exception("Invalid data row passed to CSV writer."); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007.php new file mode 100644 index 00000000..11d354b4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007.php @@ -0,0 +1,533 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007 extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * Pre-calculate formulas + * Forces PHPExcel to recalculate all formulae in a workbook when saving, so that the pre-calculated values are + * immediately available to MS Excel or other office spreadsheet viewer when opening the file + * + * Overrides the default TRUE for this specific writer for performance reasons + * + * @var boolean + */ + protected $preCalculateFormulas = false; + + /** + * Office2003 compatibility + * + * @var boolean + */ + private $office2003compatibility = false; + + /** + * Private writer parts + * + * @var PHPExcel_Writer_Excel2007_WriterPart[] + */ + private $writerParts = array(); + + /** + * Private PHPExcel + * + * @var PHPExcel + */ + private $spreadSheet; + + /** + * Private string table + * + * @var string[] + */ + private $stringTable = array(); + + /** + * Private unique PHPExcel_Style_Conditional HashTable + * + * @var PHPExcel_HashTable + */ + private $stylesConditionalHashTable; + + /** + * Private unique PHPExcel_Style HashTable + * + * @var PHPExcel_HashTable + */ + private $styleHashTable; + + /** + * Private unique PHPExcel_Style_Fill HashTable + * + * @var PHPExcel_HashTable + */ + private $fillHashTable; + + /** + * Private unique PHPExcel_Style_Font HashTable + * + * @var PHPExcel_HashTable + */ + private $fontHashTable; + + /** + * Private unique PHPExcel_Style_Borders HashTable + * + * @var PHPExcel_HashTable + */ + private $bordersHashTable ; + + /** + * Private unique PHPExcel_Style_NumberFormat HashTable + * + * @var PHPExcel_HashTable + */ + private $numFmtHashTable; + + /** + * Private unique PHPExcel_Worksheet_BaseDrawing HashTable + * + * @var PHPExcel_HashTable + */ + private $drawingHashTable; + + /** + * Create a new PHPExcel_Writer_Excel2007 + * + * @param PHPExcel $pPHPExcel + */ + public function __construct(PHPExcel $pPHPExcel = null) + { + // Assign PHPExcel + $this->setPHPExcel($pPHPExcel); + + $writerPartsArray = array( 'stringtable' => 'PHPExcel_Writer_Excel2007_StringTable', + 'contenttypes' => 'PHPExcel_Writer_Excel2007_ContentTypes', + 'docprops' => 'PHPExcel_Writer_Excel2007_DocProps', + 'rels' => 'PHPExcel_Writer_Excel2007_Rels', + 'theme' => 'PHPExcel_Writer_Excel2007_Theme', + 'style' => 'PHPExcel_Writer_Excel2007_Style', + 'workbook' => 'PHPExcel_Writer_Excel2007_Workbook', + 'worksheet' => 'PHPExcel_Writer_Excel2007_Worksheet', + 'drawing' => 'PHPExcel_Writer_Excel2007_Drawing', + 'comments' => 'PHPExcel_Writer_Excel2007_Comments', + 'chart' => 'PHPExcel_Writer_Excel2007_Chart', + 'relsvba' => 'PHPExcel_Writer_Excel2007_RelsVBA', + 'relsribbonobjects' => 'PHPExcel_Writer_Excel2007_RelsRibbon' + ); + + // Initialise writer parts + // and Assign their parent IWriters + foreach ($writerPartsArray as $writer => $class) { + $this->writerParts[$writer] = new $class($this); + } + + $hashTablesArray = array( 'stylesConditionalHashTable', 'fillHashTable', 'fontHashTable', + 'bordersHashTable', 'numFmtHashTable', 'drawingHashTable', + 'styleHashTable' + ); + + // Set HashTable variables + foreach ($hashTablesArray as $tableName) { + $this->$tableName = new PHPExcel_HashTable(); + } + } + + /** + * Get writer part + * + * @param string $pPartName Writer part name + * @return PHPExcel_Writer_Excel2007_WriterPart + */ + public function getWriterPart($pPartName = '') + { + if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { + return $this->writerParts[strtolower($pPartName)]; + } else { + return null; + } + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + if ($this->spreadSheet !== null) { + // garbage collect + $this->spreadSheet->garbageCollect(); + + // If $pFilename is php://output or php://stdout, make it a temporary file... + $originalFilename = $pFilename; + if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp'); + if ($pFilename == '') { + $pFilename = $originalFilename; + } + } + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->spreadSheet)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog(false); + $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + + // Create string lookup table + $this->stringTable = array(); + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + $this->stringTable = $this->getWriterPart('StringTable')->createStringTable($this->spreadSheet->getSheet($i), $this->stringTable); + } + + // Create styles dictionaries + $this->styleHashTable->addFromSource($this->getWriterPart('Style')->allStyles($this->spreadSheet)); + $this->stylesConditionalHashTable->addFromSource($this->getWriterPart('Style')->allConditionalStyles($this->spreadSheet)); + $this->fillHashTable->addFromSource($this->getWriterPart('Style')->allFills($this->spreadSheet)); + $this->fontHashTable->addFromSource($this->getWriterPart('Style')->allFonts($this->spreadSheet)); + $this->bordersHashTable->addFromSource($this->getWriterPart('Style')->allBorders($this->spreadSheet)); + $this->numFmtHashTable->addFromSource($this->getWriterPart('Style')->allNumberFormats($this->spreadSheet)); + + // Create drawing dictionary + $this->drawingHashTable->addFromSource($this->getWriterPart('Drawing')->allDrawings($this->spreadSheet)); + + // Create new ZIP file and open it for writing + $zipClass = PHPExcel_Settings::getZipClass(); + $objZip = new $zipClass(); + + // Retrieve OVERWRITE and CREATE constants from the instantiated zip class + // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP + $ro = new ReflectionObject($objZip); + $zipOverWrite = $ro->getConstant('OVERWRITE'); + $zipCreate = $ro->getConstant('CREATE'); + + if (file_exists($pFilename)) { + unlink($pFilename); + } + // Try opening the ZIP file + if ($objZip->open($pFilename, $zipOverWrite) !== true) { + if ($objZip->open($pFilename, $zipCreate) !== true) { + throw new PHPExcel_Writer_Exception("Could not open " . $pFilename . " for writing."); + } + } + + // Add [Content_Types].xml to ZIP file + $objZip->addFromString('[Content_Types].xml', $this->getWriterPart('ContentTypes')->writeContentTypes($this->spreadSheet, $this->includeCharts)); + + //if hasMacros, add the vbaProject.bin file, Certificate file(if exists) + if ($this->spreadSheet->hasMacros()) { + $macrosCode=$this->spreadSheet->getMacrosCode(); + if (!is_null($macrosCode)) {// we have the code ? + $objZip->addFromString('xl/vbaProject.bin', $macrosCode);//allways in 'xl', allways named vbaProject.bin + if ($this->spreadSheet->hasMacrosCertificate()) {//signed macros ? + // Yes : add the certificate file and the related rels file + $objZip->addFromString('xl/vbaProjectSignature.bin', $this->spreadSheet->getMacrosCertificate()); + $objZip->addFromString('xl/_rels/vbaProject.bin.rels', $this->getWriterPart('RelsVBA')->writeVBARelationships($this->spreadSheet)); + } + } + } + //a custom UI in this workbook ? add it ("base" xml and additional objects (pictures) and rels) + if ($this->spreadSheet->hasRibbon()) { + $tmpRibbonTarget=$this->spreadSheet->getRibbonXMLData('target'); + $objZip->addFromString($tmpRibbonTarget, $this->spreadSheet->getRibbonXMLData('data')); + if ($this->spreadSheet->hasRibbonBinObjects()) { + $tmpRootPath=dirname($tmpRibbonTarget).'/'; + $ribbonBinObjects=$this->spreadSheet->getRibbonBinObjects('data');//the files to write + foreach ($ribbonBinObjects as $aPath => $aContent) { + $objZip->addFromString($tmpRootPath.$aPath, $aContent); + } + //the rels for files + $objZip->addFromString($tmpRootPath.'_rels/'.basename($tmpRibbonTarget).'.rels', $this->getWriterPart('RelsRibbonObjects')->writeRibbonRelationships($this->spreadSheet)); + } + } + + // Add relationships to ZIP file + $objZip->addFromString('_rels/.rels', $this->getWriterPart('Rels')->writeRelationships($this->spreadSheet)); + $objZip->addFromString('xl/_rels/workbook.xml.rels', $this->getWriterPart('Rels')->writeWorkbookRelationships($this->spreadSheet)); + + // Add document properties to ZIP file + $objZip->addFromString('docProps/app.xml', $this->getWriterPart('DocProps')->writeDocPropsApp($this->spreadSheet)); + $objZip->addFromString('docProps/core.xml', $this->getWriterPart('DocProps')->writeDocPropsCore($this->spreadSheet)); + $customPropertiesPart = $this->getWriterPart('DocProps')->writeDocPropsCustom($this->spreadSheet); + if ($customPropertiesPart !== null) { + $objZip->addFromString('docProps/custom.xml', $customPropertiesPart); + } + + // Add theme to ZIP file + $objZip->addFromString('xl/theme/theme1.xml', $this->getWriterPart('Theme')->writeTheme($this->spreadSheet)); + + // Add string table to ZIP file + $objZip->addFromString('xl/sharedStrings.xml', $this->getWriterPart('StringTable')->writeStringTable($this->stringTable)); + + // Add styles to ZIP file + $objZip->addFromString('xl/styles.xml', $this->getWriterPart('Style')->writeStyles($this->spreadSheet)); + + // Add workbook to ZIP file + $objZip->addFromString('xl/workbook.xml', $this->getWriterPart('Workbook')->writeWorkbook($this->spreadSheet, $this->preCalculateFormulas)); + + $chartCount = 0; + // Add worksheets + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + $objZip->addFromString('xl/worksheets/sheet' . ($i + 1) . '.xml', $this->getWriterPart('Worksheet')->writeWorksheet($this->spreadSheet->getSheet($i), $this->stringTable, $this->includeCharts)); + if ($this->includeCharts) { + $charts = $this->spreadSheet->getSheet($i)->getChartCollection(); + if (count($charts) > 0) { + foreach ($charts as $chart) { + $objZip->addFromString('xl/charts/chart' . ($chartCount + 1) . '.xml', $this->getWriterPart('Chart')->writeChart($chart, $this->preCalculateFormulas)); + $chartCount++; + } + } + } + } + + $chartRef1 = $chartRef2 = 0; + // Add worksheet relationships (drawings, ...) + for ($i = 0; $i < $this->spreadSheet->getSheetCount(); ++$i) { + // Add relationships + $objZip->addFromString('xl/worksheets/_rels/sheet' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeWorksheetRelationships($this->spreadSheet->getSheet($i), ($i + 1), $this->includeCharts)); + + $drawings = $this->spreadSheet->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + if ($this->includeCharts) { + $chartCount = $this->spreadSheet->getSheet($i)->getChartCount(); + } + + // Add drawing and image relationship parts + if (($drawingCount > 0) || ($chartCount > 0)) { + // Drawing relationships + $objZip->addFromString('xl/drawings/_rels/drawing' . ($i + 1) . '.xml.rels', $this->getWriterPart('Rels')->writeDrawingRelationships($this->spreadSheet->getSheet($i), $chartRef1, $this->includeCharts)); + + // Drawings + $objZip->addFromString('xl/drawings/drawing' . ($i + 1) . '.xml', $this->getWriterPart('Drawing')->writeDrawings($this->spreadSheet->getSheet($i), $chartRef2, $this->includeCharts)); + } + + // Add comment relationship parts + if (count($this->spreadSheet->getSheet($i)->getComments()) > 0) { + // VML Comments + $objZip->addFromString('xl/drawings/vmlDrawing' . ($i + 1) . '.vml', $this->getWriterPart('Comments')->writeVMLComments($this->spreadSheet->getSheet($i))); + + // Comments + $objZip->addFromString('xl/comments' . ($i + 1) . '.xml', $this->getWriterPart('Comments')->writeComments($this->spreadSheet->getSheet($i))); + } + + // Add header/footer relationship parts + if (count($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages()) > 0) { + // VML Drawings + $objZip->addFromString('xl/drawings/vmlDrawingHF' . ($i + 1) . '.vml', $this->getWriterPart('Drawing')->writeVMLHeaderFooterImages($this->spreadSheet->getSheet($i))); + + // VML Drawing relationships + $objZip->addFromString('xl/drawings/_rels/vmlDrawingHF' . ($i + 1) . '.vml.rels', $this->getWriterPart('Rels')->writeHeaderFooterDrawingRelationships($this->spreadSheet->getSheet($i))); + + // Media + foreach ($this->spreadSheet->getSheet($i)->getHeaderFooter()->getImages() as $image) { + $objZip->addFromString('xl/media/' . $image->getIndexedFilename(), file_get_contents($image->getPath())); + } + } + } + + // Add media + for ($i = 0; $i < $this->getDrawingHashTable()->count(); ++$i) { + if ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { + $imageContents = null; + $imagePath = $this->getDrawingHashTable()->getByIndex($i)->getPath(); + if (strpos($imagePath, 'zip://') !== false) { + $imagePath = substr($imagePath, 6); + $imagePathSplitted = explode('#', $imagePath); + + $imageZip = new ZipArchive(); + $imageZip->open($imagePathSplitted[0]); + $imageContents = $imageZip->getFromName($imagePathSplitted[1]); + $imageZip->close(); + unset($imageZip); + } else { + $imageContents = file_get_contents($imagePath); + } + + $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + } elseif ($this->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { + ob_start(); + call_user_func( + $this->getDrawingHashTable()->getByIndex($i)->getRenderingFunction(), + $this->getDrawingHashTable()->getByIndex($i)->getImageResource() + ); + $imageContents = ob_get_contents(); + ob_end_clean(); + + $objZip->addFromString('xl/media/' . str_replace(' ', '_', $this->getDrawingHashTable()->getByIndex($i)->getIndexedFilename()), $imageContents); + } + } + + PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); + PHPExcel_Calculation::getInstance($this->spreadSheet)->getDebugLog()->setWriteDebugLog($saveDebugLog); + + // Close file + if ($objZip->close() === false) { + throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename."); + } + + // If a temporary file was used, copy it to the correct file stream + if ($originalFilename != $pFilename) { + if (copy($pFilename, $originalFilename) === false) { + throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename."); + } + @unlink($pFilename); + } + } else { + throw new PHPExcel_Writer_Exception("PHPExcel object unassigned."); + } + } + + /** + * Get PHPExcel object + * + * @return PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function getPHPExcel() + { + if ($this->spreadSheet !== null) { + return $this->spreadSheet; + } else { + throw new PHPExcel_Writer_Exception("No PHPExcel object assigned."); + } + } + + /** + * Set PHPExcel object + * + * @param PHPExcel $pPHPExcel PHPExcel object + * @throws PHPExcel_Writer_Exception + * @return PHPExcel_Writer_Excel2007 + */ + public function setPHPExcel(PHPExcel $pPHPExcel = null) + { + $this->spreadSheet = $pPHPExcel; + return $this; + } + + /** + * Get string table + * + * @return string[] + */ + public function getStringTable() + { + return $this->stringTable; + } + + /** + * Get PHPExcel_Style HashTable + * + * @return PHPExcel_HashTable + */ + public function getStyleHashTable() + { + return $this->styleHashTable; + } + + /** + * Get PHPExcel_Style_Conditional HashTable + * + * @return PHPExcel_HashTable + */ + public function getStylesConditionalHashTable() + { + return $this->stylesConditionalHashTable; + } + + /** + * Get PHPExcel_Style_Fill HashTable + * + * @return PHPExcel_HashTable + */ + public function getFillHashTable() + { + return $this->fillHashTable; + } + + /** + * Get PHPExcel_Style_Font HashTable + * + * @return PHPExcel_HashTable + */ + public function getFontHashTable() + { + return $this->fontHashTable; + } + + /** + * Get PHPExcel_Style_Borders HashTable + * + * @return PHPExcel_HashTable + */ + public function getBordersHashTable() + { + return $this->bordersHashTable; + } + + /** + * Get PHPExcel_Style_NumberFormat HashTable + * + * @return PHPExcel_HashTable + */ + public function getNumFmtHashTable() + { + return $this->numFmtHashTable; + } + + /** + * Get PHPExcel_Worksheet_BaseDrawing HashTable + * + * @return PHPExcel_HashTable + */ + public function getDrawingHashTable() + { + return $this->drawingHashTable; + } + + /** + * Get Office2003 compatibility + * + * @return boolean + */ + public function getOffice2003Compatibility() + { + return $this->office2003compatibility; + } + + /** + * Set Office2003 compatibility + * + * @param boolean $pValue Office2003 compatibility? + * @return PHPExcel_Writer_Excel2007 + */ + public function setOffice2003Compatibility($pValue = false) + { + $this->office2003compatibility = $pValue; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Chart.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Chart.php new file mode 100644 index 00000000..92fa2150 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Chart.php @@ -0,0 +1,1520 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Chart + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Chart extends PHPExcel_Writer_Excel2007_WriterPart +{ + protected $calculateCellValues; + + /** + * Write charts to XML format + * + * @param PHPExcel_Chart $pChart + * + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeChart(PHPExcel_Chart $pChart = null, $calculateCellValues = true) + { + $this->calculateCellValues = $calculateCellValues; + + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + // Ensure that data series values are up-to-date before we save + if ($this->calculateCellValues) { + $pChart->refresh(); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // c:chartSpace + $objWriter->startElement('c:chartSpace'); + $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + $objWriter->startElement('c:date1904'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + $objWriter->startElement('c:lang'); + $objWriter->writeAttribute('val', "en-GB"); + $objWriter->endElement(); + $objWriter->startElement('c:roundedCorners'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $this->writeAlternateContent($objWriter); + + $objWriter->startElement('c:chart'); + + $this->writeTitle($pChart->getTitle(), $objWriter); + + $objWriter->startElement('c:autoTitleDeleted'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $this->writePlotArea($pChart->getPlotArea(), $pChart->getXAxisLabel(), $pChart->getYAxisLabel(), $objWriter, $pChart->getWorksheet(), $pChart->getChartAxisX(), $pChart->getChartAxisY(), $pChart->getMajorGridlines(), $pChart->getMinorGridlines()); + + $this->writeLegend($pChart->getLegend(), $objWriter); + + $objWriter->startElement('c:plotVisOnly'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:dispBlanksAs'); + $objWriter->writeAttribute('val', "gap"); + $objWriter->endElement(); + + $objWriter->startElement('c:showDLblsOverMax'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + $this->writePrintSettings($objWriter); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write Chart Title + * + * @param PHPExcel_Chart_Title $title + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writeTitle(PHPExcel_Chart_Title $title = null, $objWriter) + { + if (is_null($title)) { + return; + } + + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + + $caption = $title->getCaption(); + if ((is_array($caption)) && (count($caption) > 0)) { + $caption = $caption[0]; + } + $this->getParentWriter()->getWriterPart('stringtable')->writeRichTextForCharts($objWriter, $caption, 'a'); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $this->writeLayout($title->getLayout(), $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Chart Legend + * + * @param PHPExcel_Chart_Legend $legend + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writeLegend(PHPExcel_Chart_Legend $legend = null, $objWriter) + { + if (is_null($legend)) { + return; + } + + $objWriter->startElement('c:legend'); + + $objWriter->startElement('c:legendPos'); + $objWriter->writeAttribute('val', $legend->getPosition()); + $objWriter->endElement(); + + $this->writeLayout($legend->getLayout(), $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', ($legend->getOverlay()) ? '1' : '0'); + $objWriter->endElement(); + + $objWriter->startElement('c:txPr'); + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:pPr'); + $objWriter->writeAttribute('rtl', 0); + + $objWriter->startElement('a:defRPr'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('a:endParaRPr'); + $objWriter->writeAttribute('lang', "en-US"); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Chart Plot Area + * + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $xAxisLabel + * @param PHPExcel_Chart_Title $yAxisLabel + * @param PHPExcel_Chart_Axis $xAxis + * @param PHPExcel_Chart_Axis $yAxis + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writePlotArea(PHPExcel_Chart_PlotArea $plotArea, PHPExcel_Chart_Title $xAxisLabel = null, PHPExcel_Chart_Title $yAxisLabel = null, $objWriter, PHPExcel_Worksheet $pSheet, PHPExcel_Chart_Axis $xAxis, PHPExcel_Chart_Axis $yAxis, PHPExcel_Chart_GridLines $majorGridlines, PHPExcel_Chart_GridLines $minorGridlines) + { + if (is_null($plotArea)) { + return; + } + + $id1 = $id2 = 0; + $this->_seriesIndex = 0; + $objWriter->startElement('c:plotArea'); + + $layout = $plotArea->getLayout(); + + $this->writeLayout($layout, $objWriter); + + $chartTypes = self::getChartType($plotArea); + $catIsMultiLevelSeries = $valIsMultiLevelSeries = false; + $plotGroupingType = ''; + foreach ($chartTypes as $chartType) { + $objWriter->startElement('c:' . $chartType); + + $groupCount = $plotArea->getPlotGroupCount(); + for ($i = 0; $i < $groupCount; ++$i) { + $plotGroup = $plotArea->getPlotGroupByIndex($i); + $groupType = $plotGroup->getPlotType(); + if ($groupType == $chartType) { + $plotStyle = $plotGroup->getPlotStyle(); + if ($groupType === PHPExcel_Chart_DataSeries::TYPE_RADARCHART) { + $objWriter->startElement('c:radarStyle'); + $objWriter->writeAttribute('val', $plotStyle); + $objWriter->endElement(); + } elseif ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART) { + $objWriter->startElement('c:scatterStyle'); + $objWriter->writeAttribute('val', $plotStyle); + $objWriter->endElement(); + } + + $this->writePlotGroup($plotGroup, $chartType, $objWriter, $catIsMultiLevelSeries, $valIsMultiLevelSeries, $plotGroupingType, $pSheet); + } + } + + $this->writeDataLabels($objWriter, $layout); + + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_LINECHART) { + // Line only, Line3D can't be smoothed + + $objWriter->startElement('c:smooth'); + $objWriter->writeAttribute('val', (integer) $plotGroup->getSmoothLine()); + $objWriter->endElement(); + } elseif (($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) ||($chartType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) { + $objWriter->startElement('c:gapWidth'); + $objWriter->writeAttribute('val', 150); + $objWriter->endElement(); + + if ($plotGroupingType == 'percentStacked' || $plotGroupingType == 'stacked') { + $objWriter->startElement('c:overlap'); + $objWriter->writeAttribute('val', 100); + $objWriter->endElement(); + } + } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $objWriter->startElement('c:bubbleScale'); + $objWriter->writeAttribute('val', 25); + $objWriter->endElement(); + + $objWriter->startElement('c:showNegBubbles'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } elseif ($chartType === PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) { + $objWriter->startElement('c:hiLowLines'); + $objWriter->endElement(); + + $objWriter->startElement('c:upDownBars'); + + $objWriter->startElement('c:gapWidth'); + $objWriter->writeAttribute('val', 300); + $objWriter->endElement(); + + $objWriter->startElement('c:upBars'); + $objWriter->endElement(); + + $objWriter->startElement('c:downBars'); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + // Generate 2 unique numbers to use for axId values + // $id1 = $id2 = rand(10000000,99999999); + // do { + // $id2 = rand(10000000,99999999); + // } while ($id1 == $id2); + $id1 = '75091328'; + $id2 = '75089408'; + + if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id1); + $objWriter->endElement(); + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + } else { + $objWriter->startElement('c:firstSliceAng'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) { + $objWriter->startElement('c:holeSize'); + $objWriter->writeAttribute('val', 50); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + if (($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($chartType !== PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + if ($chartType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $this->writeValueAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines); + } else { + $this->writeCategoryAxis($objWriter, $plotArea, $xAxisLabel, $chartType, $id1, $id2, $catIsMultiLevelSeries, $xAxis, $yAxis); + } + + $this->writeValueAxis($objWriter, $plotArea, $yAxisLabel, $chartType, $id1, $id2, $valIsMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines); + } + + $objWriter->endElement(); + } + + /** + * Write Data Labels + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_Layout $chartLayout Chart layout + * + * @throws PHPExcel_Writer_Exception + */ + private function writeDataLabels($objWriter, $chartLayout) + { + $objWriter->startElement('c:dLbls'); + + $objWriter->startElement('c:showLegendKey'); + $showLegendKey = (empty($chartLayout)) ? 0 : $chartLayout->getShowLegendKey(); + $objWriter->writeAttribute('val', ((empty($showLegendKey)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showVal'); + $showVal = (empty($chartLayout)) ? 0 : $chartLayout->getShowVal(); + $objWriter->writeAttribute('val', ((empty($showVal)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showCatName'); + $showCatName = (empty($chartLayout)) ? 0 : $chartLayout->getShowCatName(); + $objWriter->writeAttribute('val', ((empty($showCatName)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showSerName'); + $showSerName = (empty($chartLayout)) ? 0 : $chartLayout->getShowSerName(); + $objWriter->writeAttribute('val', ((empty($showSerName)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showPercent'); + $showPercent = (empty($chartLayout)) ? 0 : $chartLayout->getShowPercent(); + $objWriter->writeAttribute('val', ((empty($showPercent)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showBubbleSize'); + $showBubbleSize = (empty($chartLayout)) ? 0 : $chartLayout->getShowBubbleSize(); + $objWriter->writeAttribute('val', ((empty($showBubbleSize)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->startElement('c:showLeaderLines'); + $showLeaderLines = (empty($chartLayout)) ? 1 : $chartLayout->getShowLeaderLines(); + $objWriter->writeAttribute('val', ((empty($showLeaderLines)) ? 0 : 1)); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Category Axis + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $xAxisLabel + * @param string $groupType Chart type + * @param string $id1 + * @param string $id2 + * @param boolean $isMultiLevelSeries + * + * @throws PHPExcel_Writer_Exception + */ + private function writeCategoryAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $xAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis) + { + $objWriter->startElement('c:catAx'); + + if ($id1 > 0) { + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id1); + $objWriter->endElement(); + } + + $objWriter->startElement('c:scaling'); + $objWriter->startElement('c:orientation'); + $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('orientation')); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:delete'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:axPos'); + $objWriter->writeAttribute('val', "b"); + $objWriter->endElement(); + + if (!is_null($xAxisLabel)) { + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:r'); + + $caption = $xAxisLabel->getCaption(); + if (is_array($caption)) { + $caption = $caption[0]; + } + $objWriter->startElement('a:t'); + // $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption)); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $layout = $xAxisLabel->getLayout(); + $this->writeLayout($layout, $objWriter); + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + $objWriter->startElement('c:numFmt'); + $objWriter->writeAttribute('formatCode', $yAxis->getAxisNumberFormat()); + $objWriter->writeAttribute('sourceLinked', $yAxis->getAxisNumberSourceLinked()); + $objWriter->endElement(); + + $objWriter->startElement('c:majorTickMark'); + $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('major_tick_mark')); + $objWriter->endElement(); + + $objWriter->startElement('c:minorTickMark'); + $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('minor_tick_mark')); + $objWriter->endElement(); + + $objWriter->startElement('c:tickLblPos'); + $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('axis_labels')); + $objWriter->endElement(); + + if ($id2 > 0) { + $objWriter->startElement('c:crossAx'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + + $objWriter->startElement('c:crosses'); + $objWriter->writeAttribute('val', $yAxis->getAxisOptionsProperty('horizontal_crosses')); + $objWriter->endElement(); + } + + $objWriter->startElement('c:auto'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + + $objWriter->startElement('c:lblAlgn'); + $objWriter->writeAttribute('val', "ctr"); + $objWriter->endElement(); + + $objWriter->startElement('c:lblOffset'); + $objWriter->writeAttribute('val', 100); + $objWriter->endElement(); + + if ($isMultiLevelSeries) { + $objWriter->startElement('c:noMultiLvlLbl'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + $objWriter->endElement(); + } + + /** + * Write Value Axis + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart_PlotArea $plotArea + * @param PHPExcel_Chart_Title $yAxisLabel + * @param string $groupType Chart type + * @param string $id1 + * @param string $id2 + * @param boolean $isMultiLevelSeries + * + * @throws PHPExcel_Writer_Exception + */ + private function writeValueAxis($objWriter, PHPExcel_Chart_PlotArea $plotArea, $yAxisLabel, $groupType, $id1, $id2, $isMultiLevelSeries, $xAxis, $yAxis, $majorGridlines, $minorGridlines) + { + $objWriter->startElement('c:valAx'); + + if ($id2 > 0) { + $objWriter->startElement('c:axId'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + } + + $objWriter->startElement('c:scaling'); + + if (!is_null($xAxis->getAxisOptionsProperty('maximum'))) { + $objWriter->startElement('c:max'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('maximum')); + $objWriter->endElement(); + } + + if (!is_null($xAxis->getAxisOptionsProperty('minimum'))) { + $objWriter->startElement('c:min'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minimum')); + $objWriter->endElement(); + } + + $objWriter->startElement('c:orientation'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('orientation')); + + + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:delete'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:axPos'); + $objWriter->writeAttribute('val', "l"); + $objWriter->endElement(); + + $objWriter->startElement('c:majorGridlines'); + $objWriter->startElement('c:spPr'); + + if (!is_null($majorGridlines->getLineColorProperty('value'))) { + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', $majorGridlines->getLineStyleProperty('width')); + $objWriter->startElement('a:solidFill'); + $objWriter->startElement("a:{$majorGridlines->getLineColorProperty('type')}"); + $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $majorGridlines->getLineColorProperty('alpha')); + $objWriter->endElement(); //end alpha + $objWriter->endElement(); //end srgbClr + $objWriter->endElement(); //end solidFill + + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', $majorGridlines->getLineStyleProperty('dash')); + $objWriter->endElement(); + + if ($majorGridlines->getLineStyleProperty('join') == 'miter') { + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + } else { + $objWriter->startElement('a:bevel'); + $objWriter->endElement(); + } + + if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) { + $objWriter->startElement('a:headEnd'); + $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('head', 'w')); + $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('head', 'len')); + $objWriter->endElement(); + } + + if (!is_null($majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) { + $objWriter->startElement('a:tailEnd'); + $objWriter->writeAttribute('type', $majorGridlines->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('w', $majorGridlines->getLineStyleArrowParameters('end', 'w')); + $objWriter->writeAttribute('len', $majorGridlines->getLineStyleArrowParameters('end', 'len')); + $objWriter->endElement(); + } + $objWriter->endElement(); //end ln + } + $objWriter->startElement('a:effectLst'); + + if (!is_null($majorGridlines->getGlowSize())) { + $objWriter->startElement('a:glow'); + $objWriter->writeAttribute('rad', $majorGridlines->getGlowSize()); + $objWriter->startElement("a:{$majorGridlines->getGlowColor('type')}"); + $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $majorGridlines->getGlowColor('alpha')); + $objWriter->endElement(); //end alpha + $objWriter->endElement(); //end schemeClr + $objWriter->endElement(); //end glow + } + + if (!is_null($majorGridlines->getShadowProperty('presets'))) { + $objWriter->startElement("a:{$majorGridlines->getShadowProperty('effect')}"); + if (!is_null($majorGridlines->getShadowProperty('blur'))) { + $objWriter->writeAttribute('blurRad', $majorGridlines->getShadowProperty('blur')); + } + if (!is_null($majorGridlines->getShadowProperty('distance'))) { + $objWriter->writeAttribute('dist', $majorGridlines->getShadowProperty('distance')); + } + if (!is_null($majorGridlines->getShadowProperty('direction'))) { + $objWriter->writeAttribute('dir', $majorGridlines->getShadowProperty('direction')); + } + if (!is_null($majorGridlines->getShadowProperty('algn'))) { + $objWriter->writeAttribute('algn', $majorGridlines->getShadowProperty('algn')); + } + if (!is_null($majorGridlines->getShadowProperty(array('size', 'sx')))) { + $objWriter->writeAttribute('sx', $majorGridlines->getShadowProperty(array('size', 'sx'))); + } + if (!is_null($majorGridlines->getShadowProperty(array('size', 'sy')))) { + $objWriter->writeAttribute('sy', $majorGridlines->getShadowProperty(array('size', 'sy'))); + } + if (!is_null($majorGridlines->getShadowProperty(array('size', 'kx')))) { + $objWriter->writeAttribute('kx', $majorGridlines->getShadowProperty(array('size', 'kx'))); + } + if (!is_null($majorGridlines->getShadowProperty('rotWithShape'))) { + $objWriter->writeAttribute('rotWithShape', $majorGridlines->getShadowProperty('rotWithShape')); + } + $objWriter->startElement("a:{$majorGridlines->getShadowProperty(array('color', 'type'))}"); + $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'value'))); + + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $majorGridlines->getShadowProperty(array('color', 'alpha'))); + $objWriter->endElement(); //end alpha + + $objWriter->endElement(); //end color:type + $objWriter->endElement(); //end shadow + } + + if (!is_null($majorGridlines->getSoftEdgesSize())) { + $objWriter->startElement('a:softEdge'); + $objWriter->writeAttribute('rad', $majorGridlines->getSoftEdgesSize()); + $objWriter->endElement(); //end softEdge + } + + $objWriter->endElement(); //end effectLst + $objWriter->endElement(); //end spPr + $objWriter->endElement(); //end majorGridLines + + if ($minorGridlines->getObjectState()) { + $objWriter->startElement('c:minorGridlines'); + $objWriter->startElement('c:spPr'); + + if (!is_null($minorGridlines->getLineColorProperty('value'))) { + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', $minorGridlines->getLineStyleProperty('width')); + $objWriter->startElement('a:solidFill'); + $objWriter->startElement("a:{$minorGridlines->getLineColorProperty('type')}"); + $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $minorGridlines->getLineColorProperty('alpha')); + $objWriter->endElement(); //end alpha + $objWriter->endElement(); //end srgbClr + $objWriter->endElement(); //end solidFill + + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', $minorGridlines->getLineStyleProperty('dash')); + $objWriter->endElement(); + + if ($minorGridlines->getLineStyleProperty('join') == 'miter') { + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + } else { + $objWriter->startElement('a:bevel'); + $objWriter->endElement(); + } + + if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type')))) { + $objWriter->startElement('a:headEnd'); + $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('head', 'w')); + $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('head', 'len')); + $objWriter->endElement(); + } + + if (!is_null($minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type')))) { + $objWriter->startElement('a:tailEnd'); + $objWriter->writeAttribute('type', $minorGridlines->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('w', $minorGridlines->getLineStyleArrowParameters('end', 'w')); + $objWriter->writeAttribute('len', $minorGridlines->getLineStyleArrowParameters('end', 'len')); + $objWriter->endElement(); + } + $objWriter->endElement(); //end ln + } + + $objWriter->startElement('a:effectLst'); + + if (!is_null($minorGridlines->getGlowSize())) { + $objWriter->startElement('a:glow'); + $objWriter->writeAttribute('rad', $minorGridlines->getGlowSize()); + $objWriter->startElement("a:{$minorGridlines->getGlowColor('type')}"); + $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $minorGridlines->getGlowColor('alpha')); + $objWriter->endElement(); //end alpha + $objWriter->endElement(); //end schemeClr + $objWriter->endElement(); //end glow + } + + if (!is_null($minorGridlines->getShadowProperty('presets'))) { + $objWriter->startElement("a:{$minorGridlines->getShadowProperty('effect')}"); + if (!is_null($minorGridlines->getShadowProperty('blur'))) { + $objWriter->writeAttribute('blurRad', $minorGridlines->getShadowProperty('blur')); + } + if (!is_null($minorGridlines->getShadowProperty('distance'))) { + $objWriter->writeAttribute('dist', $minorGridlines->getShadowProperty('distance')); + } + if (!is_null($minorGridlines->getShadowProperty('direction'))) { + $objWriter->writeAttribute('dir', $minorGridlines->getShadowProperty('direction')); + } + if (!is_null($minorGridlines->getShadowProperty('algn'))) { + $objWriter->writeAttribute('algn', $minorGridlines->getShadowProperty('algn')); + } + if (!is_null($minorGridlines->getShadowProperty(array('size', 'sx')))) { + $objWriter->writeAttribute('sx', $minorGridlines->getShadowProperty(array('size', 'sx'))); + } + if (!is_null($minorGridlines->getShadowProperty(array('size', 'sy')))) { + $objWriter->writeAttribute('sy', $minorGridlines->getShadowProperty(array('size', 'sy'))); + } + if (!is_null($minorGridlines->getShadowProperty(array('size', 'kx')))) { + $objWriter->writeAttribute('kx', $minorGridlines->getShadowProperty(array('size', 'kx'))); + } + if (!is_null($minorGridlines->getShadowProperty('rotWithShape'))) { + $objWriter->writeAttribute('rotWithShape', $minorGridlines->getShadowProperty('rotWithShape')); + } + $objWriter->startElement("a:{$minorGridlines->getShadowProperty(array('color', 'type'))}"); + $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'value'))); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $minorGridlines->getShadowProperty(array('color', 'alpha'))); + $objWriter->endElement(); //end alpha + $objWriter->endElement(); //end color:type + $objWriter->endElement(); //end shadow + } + + if (!is_null($minorGridlines->getSoftEdgesSize())) { + $objWriter->startElement('a:softEdge'); + $objWriter->writeAttribute('rad', $minorGridlines->getSoftEdgesSize()); + $objWriter->endElement(); //end softEdge + } + + $objWriter->endElement(); //end effectLst + $objWriter->endElement(); //end spPr + $objWriter->endElement(); //end minorGridLines + } + + if (!is_null($yAxisLabel)) { + $objWriter->startElement('c:title'); + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:rich'); + + $objWriter->startElement('a:bodyPr'); + $objWriter->endElement(); + + $objWriter->startElement('a:lstStyle'); + $objWriter->endElement(); + + $objWriter->startElement('a:p'); + $objWriter->startElement('a:r'); + + $caption = $yAxisLabel->getCaption(); + if (is_array($caption)) { + $caption = $caption[0]; + } + + $objWriter->startElement('a:t'); + // $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($caption)); + $objWriter->endElement(); + + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $layout = $yAxisLabel->getLayout(); + $this->writeLayout($layout, $objWriter); + } + + $objWriter->startElement('c:overlay'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + $objWriter->startElement('c:numFmt'); + $objWriter->writeAttribute('formatCode', $xAxis->getAxisNumberFormat()); + $objWriter->writeAttribute('sourceLinked', $xAxis->getAxisNumberSourceLinked()); + $objWriter->endElement(); + + $objWriter->startElement('c:majorTickMark'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_tick_mark')); + $objWriter->endElement(); + + $objWriter->startElement('c:minorTickMark'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_tick_mark')); + $objWriter->endElement(); + + $objWriter->startElement('c:tickLblPos'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('axis_labels')); + $objWriter->endElement(); + + $objWriter->startElement('c:spPr'); + + if (!is_null($xAxis->getFillProperty('value'))) { + $objWriter->startElement('a:solidFill'); + $objWriter->startElement("a:" . $xAxis->getFillProperty('type')); + $objWriter->writeAttribute('val', $xAxis->getFillProperty('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $xAxis->getFillProperty('alpha')); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + } + + $objWriter->startElement('a:ln'); + + $objWriter->writeAttribute('w', $xAxis->getLineStyleProperty('width')); + $objWriter->writeAttribute('cap', $xAxis->getLineStyleProperty('cap')); + $objWriter->writeAttribute('cmpd', $xAxis->getLineStyleProperty('compound')); + + if (!is_null($xAxis->getLineProperty('value'))) { + $objWriter->startElement('a:solidFill'); + $objWriter->startElement("a:" . $xAxis->getLineProperty('type')); + $objWriter->writeAttribute('val', $xAxis->getLineProperty('value')); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $xAxis->getLineProperty('alpha')); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + } + + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', $xAxis->getLineStyleProperty('dash')); + $objWriter->endElement(); + + if ($xAxis->getLineStyleProperty('join') == 'miter') { + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + } else { + $objWriter->startElement('a:bevel'); + $objWriter->endElement(); + } + + if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'head', 'type')))) { + $objWriter->startElement('a:headEnd'); + $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'head', 'type'))); + $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('head')); + $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('head')); + $objWriter->endElement(); + } + + if (!is_null($xAxis->getLineStyleProperty(array('arrow', 'end', 'type')))) { + $objWriter->startElement('a:tailEnd'); + $objWriter->writeAttribute('type', $xAxis->getLineStyleProperty(array('arrow', 'end', 'type'))); + $objWriter->writeAttribute('w', $xAxis->getLineStyleArrowWidth('end')); + $objWriter->writeAttribute('len', $xAxis->getLineStyleArrowLength('end')); + $objWriter->endElement(); + } + + $objWriter->endElement(); + + $objWriter->startElement('a:effectLst'); + + if (!is_null($xAxis->getGlowProperty('size'))) { + $objWriter->startElement('a:glow'); + $objWriter->writeAttribute('rad', $xAxis->getGlowProperty('size')); + $objWriter->startElement("a:{$xAxis->getGlowProperty(array('color','type'))}"); + $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','value'))); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $xAxis->getGlowProperty(array('color','alpha'))); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + } + + if (!is_null($xAxis->getShadowProperty('presets'))) { + $objWriter->startElement("a:{$xAxis->getShadowProperty('effect')}"); + + if (!is_null($xAxis->getShadowProperty('blur'))) { + $objWriter->writeAttribute('blurRad', $xAxis->getShadowProperty('blur')); + } + if (!is_null($xAxis->getShadowProperty('distance'))) { + $objWriter->writeAttribute('dist', $xAxis->getShadowProperty('distance')); + } + if (!is_null($xAxis->getShadowProperty('direction'))) { + $objWriter->writeAttribute('dir', $xAxis->getShadowProperty('direction')); + } + if (!is_null($xAxis->getShadowProperty('algn'))) { + $objWriter->writeAttribute('algn', $xAxis->getShadowProperty('algn')); + } + if (!is_null($xAxis->getShadowProperty(array('size','sx')))) { + $objWriter->writeAttribute('sx', $xAxis->getShadowProperty(array('size','sx'))); + } + if (!is_null($xAxis->getShadowProperty(array('size','sy')))) { + $objWriter->writeAttribute('sy', $xAxis->getShadowProperty(array('size','sy'))); + } + if (!is_null($xAxis->getShadowProperty(array('size','kx')))) { + $objWriter->writeAttribute('kx', $xAxis->getShadowProperty(array('size','kx'))); + } + if (!is_null($xAxis->getShadowProperty('rotWithShape'))) { + $objWriter->writeAttribute('rotWithShape', $xAxis->getShadowProperty('rotWithShape')); + } + + $objWriter->startElement("a:{$xAxis->getShadowProperty(array('color','type'))}"); + $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','value'))); + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $xAxis->getShadowProperty(array('color','alpha'))); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + if (!is_null($xAxis->getSoftEdgesSize())) { + $objWriter->startElement('a:softEdge'); + $objWriter->writeAttribute('rad', $xAxis->getSoftEdgesSize()); + $objWriter->endElement(); + } + + $objWriter->endElement(); //effectList + $objWriter->endElement(); //end spPr + + if ($id1 > 0) { + $objWriter->startElement('c:crossAx'); + $objWriter->writeAttribute('val', $id2); + $objWriter->endElement(); + + if (!is_null($xAxis->getAxisOptionsProperty('horizontal_crosses_value'))) { + $objWriter->startElement('c:crossesAt'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses_value')); + $objWriter->endElement(); + } else { + $objWriter->startElement('c:crosses'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('horizontal_crosses')); + $objWriter->endElement(); + } + + $objWriter->startElement('c:crossBetween'); + $objWriter->writeAttribute('val', "midCat"); + $objWriter->endElement(); + + if (!is_null($xAxis->getAxisOptionsProperty('major_unit'))) { + $objWriter->startElement('c:majorUnit'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('major_unit')); + $objWriter->endElement(); + } + + if (!is_null($xAxis->getAxisOptionsProperty('minor_unit'))) { + $objWriter->startElement('c:minorUnit'); + $objWriter->writeAttribute('val', $xAxis->getAxisOptionsProperty('minor_unit')); + $objWriter->endElement(); + } + } + + if ($isMultiLevelSeries) { + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $objWriter->startElement('c:noMultiLvlLbl'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + /** + * Get the data series type(s) for a chart plot series + * + * @param PHPExcel_Chart_PlotArea $plotArea + * + * @return string|array + * @throws PHPExcel_Writer_Exception + */ + private static function getChartType($plotArea) + { + $groupCount = $plotArea->getPlotGroupCount(); + + if ($groupCount == 1) { + $chartType = array($plotArea->getPlotGroupByIndex(0)->getPlotType()); + } else { + $chartTypes = array(); + for ($i = 0; $i < $groupCount; ++$i) { + $chartTypes[] = $plotArea->getPlotGroupByIndex($i)->getPlotType(); + } + $chartType = array_unique($chartTypes); + if (count($chartTypes) == 0) { + throw new PHPExcel_Writer_Exception('Chart is not yet implemented'); + } + } + + return $chartType; + } + + /** + * Write Plot Group (series of related plots) + * + * @param PHPExcel_Chart_DataSeries $plotGroup + * @param string $groupType Type of plot for dataseries + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param boolean &$catIsMultiLevelSeries Is category a multi-series category + * @param boolean &$valIsMultiLevelSeries Is value set a multi-series set + * @param string &$plotGroupingType Type of grouping for multi-series values + * @param PHPExcel_Worksheet $pSheet + * + * @throws PHPExcel_Writer_Exception + */ + private function writePlotGroup($plotGroup, $groupType, $objWriter, &$catIsMultiLevelSeries, &$valIsMultiLevelSeries, &$plotGroupingType, PHPExcel_Worksheet $pSheet) + { + if (is_null($plotGroup)) { + return; + } + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D)) { + $objWriter->startElement('c:barDir'); + $objWriter->writeAttribute('val', $plotGroup->getPlotDirection()); + $objWriter->endElement(); + } + + if (!is_null($plotGroup->getPlotGrouping())) { + $plotGroupingType = $plotGroup->getPlotGrouping(); + $objWriter->startElement('c:grouping'); + $objWriter->writeAttribute('val', $plotGroupingType); + $objWriter->endElement(); + } + + // Get these details before the loop, because we can use the count to check for varyColors + $plotSeriesOrder = $plotGroup->getPlotOrder(); + $plotSeriesCount = count($plotSeriesOrder); + + if (($groupType !== PHPExcel_Chart_DataSeries::TYPE_RADARCHART) && ($groupType !== PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) { + if ($groupType !== PHPExcel_Chart_DataSeries::TYPE_LINECHART) { + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART) || ($plotSeriesCount > 1)) { + $objWriter->startElement('c:varyColors'); + $objWriter->writeAttribute('val', 1); + $objWriter->endElement(); + } else { + $objWriter->startElement('c:varyColors'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + } + } + + foreach ($plotSeriesOrder as $plotSeriesIdx => $plotSeriesRef) { + $objWriter->startElement('c:ser'); + + $objWriter->startElement('c:idx'); + $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesIdx); + $objWriter->endElement(); + + $objWriter->startElement('c:order'); + $objWriter->writeAttribute('val', $this->_seriesIndex + $plotSeriesRef); + $objWriter->endElement(); + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + $objWriter->startElement('c:dPt'); + $objWriter->startElement('c:idx'); + $objWriter->writeAttribute('val', 3); + $objWriter->endElement(); + + $objWriter->startElement('c:bubble3D'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + + $objWriter->startElement('c:spPr'); + $objWriter->startElement('a:solidFill'); + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FF9900'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + } + + // Labels + $plotSeriesLabel = $plotGroup->getPlotLabelByIndex($plotSeriesRef); + if ($plotSeriesLabel && ($plotSeriesLabel->getPointCount() > 0)) { + $objWriter->startElement('c:tx'); + $objWriter->startElement('c:strRef'); + $this->writePlotSeriesLabel($plotSeriesLabel, $objWriter); + $objWriter->endElement(); + $objWriter->endElement(); + } + + // Formatting for the points + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_LINECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART)) { + $objWriter->startElement('c:spPr'); + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', 12700); + if ($groupType == PHPExcel_Chart_DataSeries::TYPE_STOCKCHART) { + $objWriter->startElement('a:noFill'); + $objWriter->endElement(); + } + $objWriter->endElement(); + $objWriter->endElement(); + } + + $plotSeriesValues = $plotGroup->getPlotValuesByIndex($plotSeriesRef); + if ($plotSeriesValues) { + $plotSeriesMarker = $plotSeriesValues->getPointMarker(); + if ($plotSeriesMarker) { + $objWriter->startElement('c:marker'); + $objWriter->startElement('c:symbol'); + $objWriter->writeAttribute('val', $plotSeriesMarker); + $objWriter->endElement(); + + if ($plotSeriesMarker !== 'none') { + $objWriter->startElement('c:size'); + $objWriter->writeAttribute('val', 3); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_BARCHART_3D) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART)) { + $objWriter->startElement('c:invertIfNegative'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + + // Category Labels + $plotSeriesCategory = $plotGroup->getPlotCategoryByIndex($plotSeriesRef); + if ($plotSeriesCategory && ($plotSeriesCategory->getPointCount() > 0)) { + $catIsMultiLevelSeries = $catIsMultiLevelSeries || $plotSeriesCategory->isMultiLevelSeries(); + + if (($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) || ($groupType == PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + if (!is_null($plotGroup->getPlotStyle())) { + $plotStyle = $plotGroup->getPlotStyle(); + if ($plotStyle) { + $objWriter->startElement('c:explosion'); + $objWriter->writeAttribute('val', 25); + $objWriter->endElement(); + } + } + } + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) { + $objWriter->startElement('c:xVal'); + } else { + $objWriter->startElement('c:cat'); + } + + $this->writePlotSeriesValues($plotSeriesCategory, $objWriter, $groupType, 'str', $pSheet); + $objWriter->endElement(); + } + + // Values + if ($plotSeriesValues) { + $valIsMultiLevelSeries = $valIsMultiLevelSeries || $plotSeriesValues->isMultiLevelSeries(); + + if (($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) || ($groupType === PHPExcel_Chart_DataSeries::TYPE_SCATTERCHART)) { + $objWriter->startElement('c:yVal'); + } else { + $objWriter->startElement('c:val'); + } + + $this->writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, 'num', $pSheet); + $objWriter->endElement(); + } + + if ($groupType === PHPExcel_Chart_DataSeries::TYPE_BUBBLECHART) { + $this->writeBubbles($plotSeriesValues, $objWriter, $pSheet); + } + + $objWriter->endElement(); + } + + $this->_seriesIndex += $plotSeriesIdx + 1; + } + + /** + * Write Plot Series Label + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesLabel + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writePlotSeriesLabel($plotSeriesLabel, $objWriter) + { + if (is_null($plotSeriesLabel)) { + return; + } + + $objWriter->startElement('c:f'); + $objWriter->writeRawData($plotSeriesLabel->getDataSource()); + $objWriter->endElement(); + + $objWriter->startElement('c:strCache'); + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesLabel->getPointCount()); + $objWriter->endElement(); + + foreach ($plotSeriesLabel->getDataValues() as $plotLabelKey => $plotLabelValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotLabelKey); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData($plotLabelValue); + $objWriter->endElement(); + $objWriter->endElement(); + } + $objWriter->endElement(); + } + + /** + * Write Plot Series Values + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $groupType Type of plot for dataseries + * @param string $dataType Datatype of series values + * @param PHPExcel_Worksheet $pSheet + * + * @throws PHPExcel_Writer_Exception + */ + private function writePlotSeriesValues($plotSeriesValues, $objWriter, $groupType, $dataType = 'str', PHPExcel_Worksheet $pSheet) + { + if (is_null($plotSeriesValues)) { + return; + } + + if ($plotSeriesValues->isMultiLevelSeries()) { + $levelCount = $plotSeriesValues->multiLevelCount(); + + $objWriter->startElement('c:multiLvlStrRef'); + + $objWriter->startElement('c:f'); + $objWriter->writeRawData($plotSeriesValues->getDataSource()); + $objWriter->endElement(); + + $objWriter->startElement('c:multiLvlStrCache'); + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount()); + $objWriter->endElement(); + + for ($level = 0; $level < $levelCount; ++$level) { + $objWriter->startElement('c:lvl'); + + foreach ($plotSeriesValues->getDataValues() as $plotSeriesKey => $plotSeriesValue) { + if (isset($plotSeriesValue[$level])) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData($plotSeriesValue[$level]); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } else { + $objWriter->startElement('c:' . $dataType . 'Ref'); + + $objWriter->startElement('c:f'); + $objWriter->writeRawData($plotSeriesValues->getDataSource()); + $objWriter->endElement(); + + $objWriter->startElement('c:' . $dataType . 'Cache'); + + if (($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_PIECHART_3D) && ($groupType != PHPExcel_Chart_DataSeries::TYPE_DONUTCHART)) { + if (($plotSeriesValues->getFormatCode() !== null) && ($plotSeriesValues->getFormatCode() !== '')) { + $objWriter->startElement('c:formatCode'); + $objWriter->writeRawData($plotSeriesValues->getFormatCode()); + $objWriter->endElement(); + } + } + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount()); + $objWriter->endElement(); + + $dataValues = $plotSeriesValues->getDataValues(); + if (!empty($dataValues)) { + if (is_array($dataValues)) { + foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey); + + $objWriter->startElement('c:v'); + $objWriter->writeRawData($plotSeriesValue); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write Bubble Chart Details + * + * @param PHPExcel_Chart_DataSeriesValues $plotSeriesValues + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writeBubbles($plotSeriesValues, $objWriter, PHPExcel_Worksheet $pSheet) + { + if (is_null($plotSeriesValues)) { + return; + } + + $objWriter->startElement('c:bubbleSize'); + $objWriter->startElement('c:numLit'); + + $objWriter->startElement('c:formatCode'); + $objWriter->writeRawData('General'); + $objWriter->endElement(); + + $objWriter->startElement('c:ptCount'); + $objWriter->writeAttribute('val', $plotSeriesValues->getPointCount()); + $objWriter->endElement(); + + $dataValues = $plotSeriesValues->getDataValues(); + if (!empty($dataValues)) { + if (is_array($dataValues)) { + foreach ($dataValues as $plotSeriesKey => $plotSeriesValue) { + $objWriter->startElement('c:pt'); + $objWriter->writeAttribute('idx', $plotSeriesKey); + $objWriter->startElement('c:v'); + $objWriter->writeRawData(1); + $objWriter->endElement(); + $objWriter->endElement(); + } + } + } + + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('c:bubble3D'); + $objWriter->writeAttribute('val', 0); + $objWriter->endElement(); + } + + /** + * Write Layout + * + * @param PHPExcel_Chart_Layout $layout + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writeLayout(PHPExcel_Chart_Layout $layout = null, $objWriter) + { + $objWriter->startElement('c:layout'); + + if (!is_null($layout)) { + $objWriter->startElement('c:manualLayout'); + + $layoutTarget = $layout->getLayoutTarget(); + if (!is_null($layoutTarget)) { + $objWriter->startElement('c:layoutTarget'); + $objWriter->writeAttribute('val', $layoutTarget); + $objWriter->endElement(); + } + + $xMode = $layout->getXMode(); + if (!is_null($xMode)) { + $objWriter->startElement('c:xMode'); + $objWriter->writeAttribute('val', $xMode); + $objWriter->endElement(); + } + + $yMode = $layout->getYMode(); + if (!is_null($yMode)) { + $objWriter->startElement('c:yMode'); + $objWriter->writeAttribute('val', $yMode); + $objWriter->endElement(); + } + + $x = $layout->getXPosition(); + if (!is_null($x)) { + $objWriter->startElement('c:x'); + $objWriter->writeAttribute('val', $x); + $objWriter->endElement(); + } + + $y = $layout->getYPosition(); + if (!is_null($y)) { + $objWriter->startElement('c:y'); + $objWriter->writeAttribute('val', $y); + $objWriter->endElement(); + } + + $w = $layout->getWidth(); + if (!is_null($w)) { + $objWriter->startElement('c:w'); + $objWriter->writeAttribute('val', $w); + $objWriter->endElement(); + } + + $h = $layout->getHeight(); + if (!is_null($h)) { + $objWriter->startElement('c:h'); + $objWriter->writeAttribute('val', $h); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Alternate Content block + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writeAlternateContent($objWriter) + { + $objWriter->startElement('mc:AlternateContent'); + $objWriter->writeAttribute('xmlns:mc', 'http://schemas.openxmlformats.org/markup-compatibility/2006'); + + $objWriter->startElement('mc:Choice'); + $objWriter->writeAttribute('xmlns:c14', 'http://schemas.microsoft.com/office/drawing/2007/8/2/chart'); + $objWriter->writeAttribute('Requires', 'c14'); + + $objWriter->startElement('c14:style'); + $objWriter->writeAttribute('val', '102'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('mc:Fallback'); + $objWriter->startElement('c:style'); + $objWriter->writeAttribute('val', '2'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Printer Settings + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * + * @throws PHPExcel_Writer_Exception + */ + private function writePrintSettings($objWriter) + { + $objWriter->startElement('c:printSettings'); + + $objWriter->startElement('c:headerFooter'); + $objWriter->endElement(); + + $objWriter->startElement('c:pageMargins'); + $objWriter->writeAttribute('footer', 0.3); + $objWriter->writeAttribute('header', 0.3); + $objWriter->writeAttribute('r', 0.7); + $objWriter->writeAttribute('l', 0.7); + $objWriter->writeAttribute('t', 0.75); + $objWriter->writeAttribute('b', 0.75); + $objWriter->endElement(); + + $objWriter->startElement('c:pageSetup'); + $objWriter->writeAttribute('orientation', "portrait"); + $objWriter->endElement(); + + $objWriter->endElement(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Comments.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Comments.php new file mode 100644 index 00000000..7139f6c4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Comments.php @@ -0,0 +1,260 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Comments + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Comments extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write comments to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeComments(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Comments cache + $comments = $pWorksheet->getComments(); + + // Authors cache + $authors = array(); + $authorId = 0; + foreach ($comments as $comment) { + if (!isset($authors[$comment->getAuthor()])) { + $authors[$comment->getAuthor()] = $authorId++; + } + } + + // comments + $objWriter->startElement('comments'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + + // Loop through authors + $objWriter->startElement('authors'); + foreach ($authors as $author => $index) { + $objWriter->writeElement('author', $author); + } + $objWriter->endElement(); + + // Loop through comments + $objWriter->startElement('commentList'); + foreach ($comments as $key => $value) { + $this->writeComment($objWriter, $key, $value, $authors); + } + $objWriter->endElement(); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pCellReference Cell reference + * @param PHPExcel_Comment $pComment Comment + * @param array $pAuthors Array of authors + * @throws PHPExcel_Writer_Exception + */ + private function writeComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null, $pAuthors = null) + { + // comment + $objWriter->startElement('comment'); + $objWriter->writeAttribute('ref', $pCellReference); + $objWriter->writeAttribute('authorId', $pAuthors[$pComment->getAuthor()]); + + // text + $objWriter->startElement('text'); + $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $pComment->getText()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write VML comments to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVMLComments(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Comments cache + $comments = $pWorksheet->getComments(); + + // xml + $objWriter->startElement('xml'); + $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); + + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); + + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t202'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '202'); + $objWriter->writeAttribute('path', 'm,l,21600r21600,l21600,xe'); + + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Loop through comments + foreach ($comments as $key => $value) { + $this->writeVMLComment($objWriter, $key, $value); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write VML comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pCellReference Cell reference + * @param PHPExcel_Comment $pComment Comment + * @throws PHPExcel_Writer_Exception + */ + private function writeVMLComment(PHPExcel_Shared_XMLWriter $objWriter = null, $pCellReference = 'A1', PHPExcel_Comment $pComment = null) + { + // Metadata + list($column, $row) = PHPExcel_Cell::coordinateFromString($pCellReference); + $column = PHPExcel_Cell::columnIndexFromString($column); + $id = 1024 + $column + $row; + $id = substr($id, 0, 4); + + // v:shape + $objWriter->startElement('v:shape'); + $objWriter->writeAttribute('id', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t202'); + $objWriter->writeAttribute('style', 'position:absolute;margin-left:' . $pComment->getMarginLeft() . ';margin-top:' . $pComment->getMarginTop() . ';width:' . $pComment->getWidth() . ';height:' . $pComment->getHeight() . ';z-index:1;visibility:' . ($pComment->getVisible() ? 'visible' : 'hidden')); + $objWriter->writeAttribute('fillcolor', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->writeAttribute('o:insetmode', 'auto'); + + // v:fill + $objWriter->startElement('v:fill'); + $objWriter->writeAttribute('color2', '#' . $pComment->getFillColor()->getRGB()); + $objWriter->endElement(); + + // v:shadow + $objWriter->startElement('v:shadow'); + $objWriter->writeAttribute('on', 't'); + $objWriter->writeAttribute('color', 'black'); + $objWriter->writeAttribute('obscured', 't'); + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('o:connecttype', 'none'); + $objWriter->endElement(); + + // v:textbox + $objWriter->startElement('v:textbox'); + $objWriter->writeAttribute('style', 'mso-direction-alt:auto'); + + // div + $objWriter->startElement('div'); + $objWriter->writeAttribute('style', 'text-align:left'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // x:ClientData + $objWriter->startElement('x:ClientData'); + $objWriter->writeAttribute('ObjectType', 'Note'); + + // x:MoveWithCells + $objWriter->writeElement('x:MoveWithCells', ''); + + // x:SizeWithCells + $objWriter->writeElement('x:SizeWithCells', ''); + + // x:Anchor + //$objWriter->writeElement('x:Anchor', $column . ', 15, ' . ($row - 2) . ', 10, ' . ($column + 4) . ', 15, ' . ($row + 5) . ', 18'); + + // x:AutoFill + $objWriter->writeElement('x:AutoFill', 'False'); + + // x:Row + $objWriter->writeElement('x:Row', ($row - 1)); + + // x:Column + $objWriter->writeElement('x:Column', ($column - 1)); + + $objWriter->endElement(); + + $objWriter->endElement(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/ContentTypes.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/ContentTypes.php new file mode 100644 index 00000000..0d911899 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/ContentTypes.php @@ -0,0 +1,240 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_ContentTypes + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_ContentTypes extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write content types to XML format + * + * @param PHPExcel $pPHPExcel + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeContentTypes(PHPExcel $pPHPExcel = null, $includeCharts = false) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Types + $objWriter->startElement('Types'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/content-types'); + + // Theme + $this->writeOverrideContentType($objWriter, '/xl/theme/theme1.xml', 'application/vnd.openxmlformats-officedocument.theme+xml'); + + // Styles + $this->writeOverrideContentType($objWriter, '/xl/styles.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml'); + + // Rels + $this->writeDefaultContentType($objWriter, 'rels', 'application/vnd.openxmlformats-package.relationships+xml'); + + // XML + $this->writeDefaultContentType($objWriter, 'xml', 'application/xml'); + + // VML + $this->writeDefaultContentType($objWriter, 'vml', 'application/vnd.openxmlformats-officedocument.vmlDrawing'); + + // Workbook + if ($pPHPExcel->hasMacros()) { //Macros in workbook ? + // Yes : not standard content but "macroEnabled" + $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.ms-excel.sheet.macroEnabled.main+xml'); + //... and define a new type for the VBA project + $this->writeDefaultContentType($objWriter, 'bin', 'application/vnd.ms-office.vbaProject'); + if ($pPHPExcel->hasMacrosCertificate()) {// signed macros ? + // Yes : add needed information + $this->writeOverrideContentType($objWriter, '/xl/vbaProjectSignature.bin', 'application/vnd.ms-office.vbaProjectSignature'); + } + } else {// no macros in workbook, so standard type + $this->writeOverrideContentType($objWriter, '/xl/workbook.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml'); + } + + // DocProps + $this->writeOverrideContentType($objWriter, '/docProps/app.xml', 'application/vnd.openxmlformats-officedocument.extended-properties+xml'); + + $this->writeOverrideContentType($objWriter, '/docProps/core.xml', 'application/vnd.openxmlformats-package.core-properties+xml'); + + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (!empty($customPropertyList)) { + $this->writeOverrideContentType($objWriter, '/docProps/custom.xml', 'application/vnd.openxmlformats-officedocument.custom-properties+xml'); + } + + // Worksheets + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $this->writeOverrideContentType($objWriter, '/xl/worksheets/sheet' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml'); + } + + // Shared strings + $this->writeOverrideContentType($objWriter, '/xl/sharedStrings.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml'); + + // Add worksheet relationship content types + $chart = 1; + for ($i = 0; $i < $sheetCount; ++$i) { + $drawings = $pPHPExcel->getSheet($i)->getDrawingCollection(); + $drawingCount = count($drawings); + $chartCount = ($includeCharts) ? $pPHPExcel->getSheet($i)->getChartCount() : 0; + + // We need a drawing relationship for the worksheet if we have either drawings or charts + if (($drawingCount > 0) || ($chartCount > 0)) { + $this->writeOverrideContentType($objWriter, '/xl/drawings/drawing' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.drawing+xml'); + } + + // If we have charts, then we need a chart relationship for every individual chart + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->writeOverrideContentType($objWriter, '/xl/charts/chart' . $chart++ . '.xml', 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'); + } + } + } + + // Comments + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet($i)->getComments()) > 0) { + $this->writeOverrideContentType($objWriter, '/xl/comments' . ($i + 1) . '.xml', 'application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml'); + } + } + + // Add media content-types + $aMediaContentTypes = array(); + $mediaCount = $this->getParentWriter()->getDrawingHashTable()->count(); + for ($i = 0; $i < $mediaCount; ++$i) { + $extension = ''; + $mimeType = ''; + + if ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_Drawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getExtension()); + $mimeType = $this->getImageMimeType($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getPath()); + } elseif ($this->getParentWriter()->getDrawingHashTable()->getByIndex($i) instanceof PHPExcel_Worksheet_MemoryDrawing) { + $extension = strtolower($this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType()); + $extension = explode('/', $extension); + $extension = $extension[1]; + + $mimeType = $this->getParentWriter()->getDrawingHashTable()->getByIndex($i)->getMimeType(); + } + + if (!isset( $aMediaContentTypes[$extension])) { + $aMediaContentTypes[$extension] = $mimeType; + + $this->writeDefaultContentType($objWriter, $extension, $mimeType); + } + } + if ($pPHPExcel->hasRibbonBinObjects()) { + // Some additional objects in the ribbon ? + // we need to write "Extension" but not already write for media content + $tabRibbonTypes=array_diff($pPHPExcel->getRibbonBinObjects('types'), array_keys($aMediaContentTypes)); + foreach ($tabRibbonTypes as $aRibbonType) { + $mimeType='image/.'.$aRibbonType;//we wrote $mimeType like customUI Editor + $this->writeDefaultContentType($objWriter, $aRibbonType, $mimeType); + } + } + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + if (count($pPHPExcel->getSheet()->getHeaderFooter()->getImages()) > 0) { + foreach ($pPHPExcel->getSheet()->getHeaderFooter()->getImages() as $image) { + if (!isset( $aMediaContentTypes[strtolower($image->getExtension())])) { + $aMediaContentTypes[strtolower($image->getExtension())] = $this->getImageMimeType($image->getPath()); + + $this->writeDefaultContentType($objWriter, strtolower($image->getExtension()), $aMediaContentTypes[strtolower($image->getExtension())]); + } + } + } + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Get image mime type + * + * @param string $pFile Filename + * @return string Mime Type + * @throws PHPExcel_Writer_Exception + */ + private function getImageMimeType($pFile = '') + { + if (PHPExcel_Shared_File::file_exists($pFile)) { + $image = getimagesize($pFile); + return image_type_to_mime_type($image[2]); + } else { + throw new PHPExcel_Writer_Exception("File $pFile does not exist"); + } + } + + /** + * Write Default content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pPartname Part name + * @param string $pContentType Content type + * @throws PHPExcel_Writer_Exception + */ + private function writeDefaultContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') + { + if ($pPartname != '' && $pContentType != '') { + // Write content type + $objWriter->startElement('Default'); + $objWriter->writeAttribute('Extension', $pPartname); + $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Override content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pPartname Part name + * @param string $pContentType Content type + * @throws PHPExcel_Writer_Exception + */ + private function writeOverrideContentType(PHPExcel_Shared_XMLWriter $objWriter = null, $pPartname = '', $pContentType = '') + { + if ($pPartname != '' && $pContentType != '') { + // Write content type + $objWriter->startElement('Override'); + $objWriter->writeAttribute('PartName', $pPartname); + $objWriter->writeAttribute('ContentType', $pContentType); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/DocProps.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/DocProps.php new file mode 100644 index 00000000..fef3d937 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/DocProps.php @@ -0,0 +1,262 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_DocProps + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_DocProps extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write docProps/app.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsApp(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Properties + $objWriter->startElement('Properties'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'); + $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + // Application + $objWriter->writeElement('Application', 'Microsoft Excel'); + + // DocSecurity + $objWriter->writeElement('DocSecurity', '0'); + + // ScaleCrop + $objWriter->writeElement('ScaleCrop', 'false'); + + // HeadingPairs + $objWriter->startElement('HeadingPairs'); + + // Vector + $objWriter->startElement('vt:vector'); + $objWriter->writeAttribute('size', '2'); + $objWriter->writeAttribute('baseType', 'variant'); + + // Variant + $objWriter->startElement('vt:variant'); + $objWriter->writeElement('vt:lpstr', 'Worksheets'); + $objWriter->endElement(); + + // Variant + $objWriter->startElement('vt:variant'); + $objWriter->writeElement('vt:i4', $pPHPExcel->getSheetCount()); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // TitlesOfParts + $objWriter->startElement('TitlesOfParts'); + + // Vector + $objWriter->startElement('vt:vector'); + $objWriter->writeAttribute('size', $pPHPExcel->getSheetCount()); + $objWriter->writeAttribute('baseType', 'lpstr'); + + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $objWriter->writeElement('vt:lpstr', $pPHPExcel->getSheet($i)->getTitle()); + } + + $objWriter->endElement(); + + $objWriter->endElement(); + + // Company + $objWriter->writeElement('Company', $pPHPExcel->getProperties()->getCompany()); + + // Company + $objWriter->writeElement('Manager', $pPHPExcel->getProperties()->getManager()); + + // LinksUpToDate + $objWriter->writeElement('LinksUpToDate', 'false'); + + // SharedDoc + $objWriter->writeElement('SharedDoc', 'false'); + + // HyperlinksChanged + $objWriter->writeElement('HyperlinksChanged', 'false'); + + // AppVersion + $objWriter->writeElement('AppVersion', '12.0000'); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write docProps/core.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsCore(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // cp:coreProperties + $objWriter->startElement('cp:coreProperties'); + $objWriter->writeAttribute('xmlns:cp', 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:dcterms', 'http://purl.org/dc/terms/'); + $objWriter->writeAttribute('xmlns:dcmitype', 'http://purl.org/dc/dcmitype/'); + $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + + // dc:creator + $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator()); + + // cp:lastModifiedBy + $objWriter->writeElement('cp:lastModifiedBy', $pPHPExcel->getProperties()->getLastModifiedBy()); + + // dcterms:created + $objWriter->startElement('dcterms:created'); + $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getCreated())); + $objWriter->endElement(); + + // dcterms:modified + $objWriter->startElement('dcterms:modified'); + $objWriter->writeAttribute('xsi:type', 'dcterms:W3CDTF'); + $objWriter->writeRawData(date(DATE_W3C, $pPHPExcel->getProperties()->getModified())); + $objWriter->endElement(); + + // dc:title + $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle()); + + // dc:description + $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription()); + + // dc:subject + $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject()); + + // cp:keywords + $objWriter->writeElement('cp:keywords', $pPHPExcel->getProperties()->getKeywords()); + + // cp:category + $objWriter->writeElement('cp:category', $pPHPExcel->getProperties()->getCategory()); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write docProps/custom.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDocPropsCustom(PHPExcel $pPHPExcel = null) + { + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (empty($customPropertyList)) { + return; + } + + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // cp:coreProperties + $objWriter->startElement('Properties'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/officeDocument/2006/custom-properties'); + $objWriter->writeAttribute('xmlns:vt', 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes'); + + + foreach ($customPropertyList as $key => $customProperty) { + $propertyValue = $pPHPExcel->getProperties()->getCustomPropertyValue($customProperty); + $propertyType = $pPHPExcel->getProperties()->getCustomPropertyType($customProperty); + + $objWriter->startElement('property'); + $objWriter->writeAttribute('fmtid', '{D5CDD505-2E9C-101B-9397-08002B2CF9AE}'); + $objWriter->writeAttribute('pid', $key+2); + $objWriter->writeAttribute('name', $customProperty); + + switch ($propertyType) { + case 'i': + $objWriter->writeElement('vt:i4', $propertyValue); + break; + case 'f': + $objWriter->writeElement('vt:r8', $propertyValue); + break; + case 'b': + $objWriter->writeElement('vt:bool', ($propertyValue) ? 'true' : 'false'); + break; + case 'd': + $objWriter->startElement('vt:filetime'); + $objWriter->writeRawData(date(DATE_W3C, $propertyValue)); + $objWriter->endElement(); + break; + default: + $objWriter->writeElement('vt:lpwstr', $propertyValue); + break; + } + + $objWriter->endElement(); + } + + + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Drawing.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Drawing.php new file mode 100644 index 00000000..28143888 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Drawing.php @@ -0,0 +1,589 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Drawing + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write drawings to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int &$chartRef Chart ID + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // xdr:wsDr + $objWriter->startElement('xdr:wsDr'); + $objWriter->writeAttribute('xmlns:xdr', 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + + // Loop through images and write drawings + $i = 1; + $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + $this->writeDrawing($objWriter, $iterator->current(), $i); + + $iterator->next(); + ++$i; + } + + if ($includeCharts) { + $chartCount = $pWorksheet->getChartCount(); + // Loop through charts and write the chart position + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c+$i); + } + } + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write drawings to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Chart $pChart + * @param int $pRelationId + * @throws PHPExcel_Writer_Exception + */ + public function writeChart(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Chart $pChart = null, $pRelationId = -1) + { + $tl = $pChart->getTopLeftPosition(); + $tl['colRow'] = PHPExcel_Cell::coordinateFromString($tl['cell']); + $br = $pChart->getBottomRightPosition(); + $br['colRow'] = PHPExcel_Cell::coordinateFromString($br['cell']); + + $objWriter->startElement('xdr:twoCellAnchor'); + + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($tl['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['xOffset'])); + $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['yOffset'])); + $objWriter->endElement(); + $objWriter->startElement('xdr:to'); + $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($br['colRow'][0]) - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['xOffset'])); + $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['yOffset'])); + $objWriter->endElement(); + + $objWriter->startElement('xdr:graphicFrame'); + $objWriter->writeAttribute('macro', ''); + $objWriter->startElement('xdr:nvGraphicFramePr'); + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('name', 'Chart '.$pRelationId); + $objWriter->writeAttribute('id', 1025 * $pRelationId); + $objWriter->endElement(); + $objWriter->startElement('xdr:cNvGraphicFramePr'); + $objWriter->startElement('a:graphicFrameLocks'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('xdr:xfrm'); + $objWriter->startElement('a:off'); + $objWriter->writeAttribute('x', '0'); + $objWriter->writeAttribute('y', '0'); + $objWriter->endElement(); + $objWriter->startElement('a:ext'); + $objWriter->writeAttribute('cx', '0'); + $objWriter->writeAttribute('cy', '0'); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('a:graphic'); + $objWriter->startElement('a:graphicData'); + $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->startElement('c:chart'); + $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:id', 'rId'.$pRelationId); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + $objWriter->startElement('xdr:clientData'); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write drawings to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet_BaseDrawing $pDrawing + * @param int $pRelationId + * @throws PHPExcel_Writer_Exception + */ + public function writeDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet_BaseDrawing $pDrawing = null, $pRelationId = -1) + { + if ($pRelationId >= 0) { + // xdr:oneCellAnchor + $objWriter->startElement('xdr:oneCellAnchor'); + // Image location + $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates()); + $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]); + + // xdr:from + $objWriter->startElement('xdr:from'); + $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1); + $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX())); + $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1); + $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY())); + $objWriter->endElement(); + + // xdr:ext + $objWriter->startElement('xdr:ext'); + $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth())); + $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight())); + $objWriter->endElement(); + + // xdr:pic + $objWriter->startElement('xdr:pic'); + + // xdr:nvPicPr + $objWriter->startElement('xdr:nvPicPr'); + + // xdr:cNvPr + $objWriter->startElement('xdr:cNvPr'); + $objWriter->writeAttribute('id', $pRelationId); + $objWriter->writeAttribute('name', $pDrawing->getName()); + $objWriter->writeAttribute('descr', $pDrawing->getDescription()); + $objWriter->endElement(); + + // xdr:cNvPicPr + $objWriter->startElement('xdr:cNvPicPr'); + + // a:picLocks + $objWriter->startElement('a:picLocks'); + $objWriter->writeAttribute('noChangeAspect', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:blipFill + $objWriter->startElement('xdr:blipFill'); + + // a:blip + $objWriter->startElement('a:blip'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + $objWriter->writeAttribute('r:embed', 'rId' . $pRelationId); + $objWriter->endElement(); + + // a:stretch + $objWriter->startElement('a:stretch'); + $objWriter->writeElement('a:fillRect', null); + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:spPr + $objWriter->startElement('xdr:spPr'); + + // a:xfrm + $objWriter->startElement('a:xfrm'); + $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation())); + $objWriter->endElement(); + + // a:prstGeom + $objWriter->startElement('a:prstGeom'); + $objWriter->writeAttribute('prst', 'rect'); + + // a:avLst + $objWriter->writeElement('a:avLst', null); + + $objWriter->endElement(); + +// // a:solidFill +// $objWriter->startElement('a:solidFill'); + +// // a:srgbClr +// $objWriter->startElement('a:srgbClr'); +// $objWriter->writeAttribute('val', 'FFFFFF'); + +///* SHADE +// // a:shade +// $objWriter->startElement('a:shade'); +// $objWriter->writeAttribute('val', '85000'); +// $objWriter->endElement(); +//*/ + +// $objWriter->endElement(); + +// $objWriter->endElement(); +/* + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '88900'); + $objWriter->writeAttribute('cap', 'sq'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:miter + $objWriter->startElement('a:miter'); + $objWriter->writeAttribute('lim', '800000'); + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + + if ($pDrawing->getShadow()->getVisible()) { + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius())); + $objWriter->writeAttribute('dist', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance())); + $objWriter->writeAttribute('dir', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection())); + $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment()); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB()); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + } +/* + + // a:scene3d + $objWriter->startElement('a:scene3d'); + + // a:camera + $objWriter->startElement('a:camera'); + $objWriter->writeAttribute('prst', 'orthographicFront'); + $objWriter->endElement(); + + // a:lightRig + $objWriter->startElement('a:lightRig'); + $objWriter->writeAttribute('rig', 'twoPt'); + $objWriter->writeAttribute('dir', 't'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ +/* + // a:sp3d + $objWriter->startElement('a:sp3d'); + + // a:bevelT + $objWriter->startElement('a:bevelT'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('h', '19050'); + $objWriter->endElement(); + + // a:contourClr + $objWriter->startElement('a:contourClr'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); +*/ + $objWriter->endElement(); + + $objWriter->endElement(); + + // xdr:clientData + $objWriter->writeElement('xdr:clientData', null); + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write VML header/footer images to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVMLHeaderFooterImages(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Header/footer images + $images = $pWorksheet->getHeaderFooter()->getImages(); + + // xml + $objWriter->startElement('xml'); + $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml'); + $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office'); + $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel'); + + // o:shapelayout + $objWriter->startElement('o:shapelayout'); + $objWriter->writeAttribute('v:ext', 'edit'); + + // o:idmap + $objWriter->startElement('o:idmap'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('data', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:shapetype + $objWriter->startElement('v:shapetype'); + $objWriter->writeAttribute('id', '_x0000_t75'); + $objWriter->writeAttribute('coordsize', '21600,21600'); + $objWriter->writeAttribute('o:spt', '75'); + $objWriter->writeAttribute('o:preferrelative', 't'); + $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe'); + $objWriter->writeAttribute('filled', 'f'); + $objWriter->writeAttribute('stroked', 'f'); + + // v:stroke + $objWriter->startElement('v:stroke'); + $objWriter->writeAttribute('joinstyle', 'miter'); + $objWriter->endElement(); + + // v:formulas + $objWriter->startElement('v:formulas'); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 1 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum 0 0 @1'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @2 1 2'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @0 0 1'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @6 1 2'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @8 21600 0'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight'); + $objWriter->endElement(); + + // v:f + $objWriter->startElement('v:f'); + $objWriter->writeAttribute('eqn', 'sum @10 21600 0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // v:path + $objWriter->startElement('v:path'); + $objWriter->writeAttribute('o:extrusionok', 'f'); + $objWriter->writeAttribute('gradientshapeok', 't'); + $objWriter->writeAttribute('o:connecttype', 'rect'); + $objWriter->endElement(); + + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('aspectratio', 't'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Loop through images + foreach ($images as $key => $value) { + $this->writeVMLHeaderFooterImage($objWriter, $key, $value); + } + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write VML comment to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pReference Reference + * @param PHPExcel_Worksheet_HeaderFooterDrawing $pImage Image + * @throws PHPExcel_Writer_Exception + */ + private function writeVMLHeaderFooterImage(PHPExcel_Shared_XMLWriter $objWriter = null, $pReference = '', PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null) + { + // Calculate object id + preg_match('{(\d+)}', md5($pReference), $m); + $id = 1500 + (substr($m[1], 0, 2) * 1); + + // Calculate offset + $width = $pImage->getWidth(); + $height = $pImage->getHeight(); + $marginLeft = $pImage->getOffsetX(); + $marginTop = $pImage->getOffsetY(); + + // v:shape + $objWriter->startElement('v:shape'); + $objWriter->writeAttribute('id', $pReference); + $objWriter->writeAttribute('o:spid', '_x0000_s' . $id); + $objWriter->writeAttribute('type', '#_x0000_t75'); + $objWriter->writeAttribute('style', "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1"); + + // v:imagedata + $objWriter->startElement('v:imagedata'); + $objWriter->writeAttribute('o:relid', 'rId' . $pReference); + $objWriter->writeAttribute('o:title', $pImage->getName()); + $objWriter->endElement(); + + // o:lock + $objWriter->startElement('o:lock'); + $objWriter->writeAttribute('v:ext', 'edit'); + $objWriter->writeAttribute('rotation', 't'); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + + /** + * Get an array of all drawings + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Worksheet_Drawing[] All drawings in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allDrawings(PHPExcel $pPHPExcel = null) + { + // Get an array of all drawings + $aDrawings = array(); + + // Loop through PHPExcel + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // Loop through images and add to array + $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + $aDrawings[] = $iterator->current(); + + $iterator->next(); + } + } + + return $aDrawings; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Rels.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Rels.php new file mode 100644 index 00000000..14ff3371 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Rels.php @@ -0,0 +1,424 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Rels + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Rels extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeRelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + $customPropertyList = $pPHPExcel->getProperties()->getCustomProperties(); + if (!empty($customPropertyList)) { + // Relationship docProps/app.xml + $this->writeRelationship( + $objWriter, + 4, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties', + 'docProps/custom.xml' + ); + + } + + // Relationship docProps/app.xml + $this->writeRelationship( + $objWriter, + 3, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties', + 'docProps/app.xml' + ); + + // Relationship docProps/core.xml + $this->writeRelationship( + $objWriter, + 2, + 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties', + 'docProps/core.xml' + ); + + // Relationship xl/workbook.xml + $this->writeRelationship( + $objWriter, + 1, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument', + 'xl/workbook.xml' + ); + // a custom UI in workbook ? + if ($pPHPExcel->hasRibbon()) { + $this->writeRelationShip( + $objWriter, + 5, + 'http://schemas.microsoft.com/office/2006/relationships/ui/extensibility', + $pPHPExcel->getRibbonXMLData('target') + ); + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write workbook relationships to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorkbookRelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Relationship styles.xml + $this->writeRelationship( + $objWriter, + 1, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles', + 'styles.xml' + ); + + // Relationship theme/theme1.xml + $this->writeRelationship( + $objWriter, + 2, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme', + 'theme/theme1.xml' + ); + + // Relationship sharedStrings.xml + $this->writeRelationship( + $objWriter, + 3, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings', + 'sharedStrings.xml' + ); + + // Relationships with sheets + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + $this->writeRelationship( + $objWriter, + ($i + 1 + 3), + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet', + 'worksheets/sheet' . ($i + 1) . '.xml' + ); + } + // Relationships for vbaProject if needed + // id : just after the last sheet + if ($pPHPExcel->hasMacros()) { + $this->writeRelationShip( + $objWriter, + ($i + 1 + 3), + 'http://schemas.microsoft.com/office/2006/relationships/vbaProject', + 'vbaProject.bin' + ); + ++$i;//increment i if needed for an another relation + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write worksheet relationships to XML format + * + * Numbering is as follows: + * rId1 - Drawings + * rId_hyperlink_x - Hyperlinks + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int $pWorksheetId + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorksheetRelationships(PHPExcel_Worksheet $pWorksheet = null, $pWorksheetId = 1, $includeCharts = false) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Write drawing relationships? + $d = 0; + if ($includeCharts) { + $charts = $pWorksheet->getChartCollection(); + } else { + $charts = array(); + } + if (($pWorksheet->getDrawingCollection()->count() > 0) || + (count($charts) > 0)) { + $this->writeRelationship( + $objWriter, + ++$d, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing', + '../drawings/drawing' . $pWorksheetId . '.xml' + ); + } + + // Write chart relationships? +// $chartCount = 0; +// $charts = $pWorksheet->getChartCollection(); +// echo 'Chart Rels: ' , count($charts) , '<br />'; +// if (count($charts) > 0) { +// foreach ($charts as $chart) { +// $this->writeRelationship( +// $objWriter, +// ++$d, +// 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', +// '../charts/chart' . ++$chartCount . '.xml' +// ); +// } +// } +// + // Write hyperlink relationships? + $i = 1; + foreach ($pWorksheet->getHyperlinkCollection() as $hyperlink) { + if (!$hyperlink->isInternal()) { + $this->writeRelationship( + $objWriter, + '_hyperlink_' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink', + $hyperlink->getUrl(), + 'External' + ); + + ++$i; + } + } + + // Write comments relationship? + $i = 1; + if (count($pWorksheet->getComments()) > 0) { + $this->writeRelationship( + $objWriter, + '_comments_vml' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', + '../drawings/vmlDrawing' . $pWorksheetId . '.vml' + ); + + $this->writeRelationship( + $objWriter, + '_comments' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments', + '../comments' . $pWorksheetId . '.xml' + ); + } + + // Write header/footer relationship? + $i = 1; + if (count($pWorksheet->getHeaderFooter()->getImages()) > 0) { + $this->writeRelationship( + $objWriter, + '_headerfooter_vml' . $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing', + '../drawings/vmlDrawingHF' . $pWorksheetId . '.vml' + ); + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write drawing relationships to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @param int &$chartRef Chart ID + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Loop through images and write relationships + $i = 1; + $iterator = $pWorksheet->getDrawingCollection()->getIterator(); + while ($iterator->valid()) { + if ($iterator->current() instanceof PHPExcel_Worksheet_Drawing + || $iterator->current() instanceof PHPExcel_Worksheet_MemoryDrawing) { + // Write relationship for image drawing + $this->writeRelationship( + $objWriter, + $i, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + '../media/' . str_replace(' ', '', $iterator->current()->getIndexedFilename()) + ); + } + + $iterator->next(); + ++$i; + } + + if ($includeCharts) { + // Loop through charts and write relationships + $chartCount = $pWorksheet->getChartCount(); + if ($chartCount > 0) { + for ($c = 0; $c < $chartCount; ++$c) { + $this->writeRelationship( + $objWriter, + $i++, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart', + '../charts/chart' . ++$chartRef . '.xml' + ); + } + } + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write header/footer drawing relationships to XML format + * + * @param PHPExcel_Worksheet $pWorksheet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeHeaderFooterDrawingRelationships(PHPExcel_Worksheet $pWorksheet = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + + // Loop through images and write relationships + foreach ($pWorksheet->getHeaderFooter()->getImages() as $key => $value) { + // Write relationship for image drawing + $this->writeRelationship( + $objWriter, + $key, + 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image', + '../media/' . $value->getIndexedFilename() + ); + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write Override content type + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param int $pId Relationship ID. rId will be prepended! + * @param string $pType Relationship type + * @param string $pTarget Relationship target + * @param string $pTargetMode Relationship target mode + * @throws PHPExcel_Writer_Exception + */ + private function writeRelationship(PHPExcel_Shared_XMLWriter $objWriter = null, $pId = 1, $pType = '', $pTarget = '', $pTargetMode = '') + { + if ($pType != '' && $pTarget != '') { + // Write relationship + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', 'rId' . $pId); + $objWriter->writeAttribute('Type', $pType); + $objWriter->writeAttribute('Target', $pTarget); + + if ($pTargetMode != '') { + $objWriter->writeAttribute('TargetMode', $pTargetMode); + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsRibbon.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsRibbon.php new file mode 100644 index 00000000..5a4a9fc0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsRibbon.php @@ -0,0 +1,67 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_RelsRibbon + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_RelsRibbon extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships for additional objects of custom UI (ribbon) + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeRibbonRelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $localRels = $pPHPExcel->getRibbonBinObjects('names'); + if (is_array($localRels)) { + foreach ($localRels as $aId => $aTarget) { + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', $aId); + $objWriter->writeAttribute('Type', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image'); + $objWriter->writeAttribute('Target', $aTarget); + $objWriter->endElement(); + } + } + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsVBA.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsVBA.php new file mode 100644 index 00000000..bee0e643 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/RelsVBA.php @@ -0,0 +1,63 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_RelsVBA + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_RelsVBA extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write relationships for a signed VBA Project + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeVBARelationships(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Relationships + $objWriter->startElement('Relationships'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/package/2006/relationships'); + $objWriter->startElement('Relationship'); + $objWriter->writeAttribute('Id', 'rId1'); + $objWriter->writeAttribute('Type', 'http://schemas.microsoft.com/office/2006/relationships/vbaProjectSignature'); + $objWriter->writeAttribute('Target', 'vbaProjectSignature.bin'); + $objWriter->endElement(); + $objWriter->endElement(); + + return $objWriter->getData(); + + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/StringTable.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/StringTable.php new file mode 100644 index 00000000..fccec669 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/StringTable.php @@ -0,0 +1,313 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_StringTable + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_StringTable extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Create worksheet stringtable + * + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param string[] $pExistingTable Existing table to eventually merge with + * @return string[] String table for worksheet + * @throws PHPExcel_Writer_Exception + */ + public function createStringTable($pSheet = null, $pExistingTable = null) + { + if ($pSheet !== null) { + // Create string lookup table + $aStringTable = array(); + $cellCollection = null; + $aFlippedStringTable = null; // For faster lookup + + // Is an existing table given? + if (($pExistingTable !== null) && is_array($pExistingTable)) { + $aStringTable = $pExistingTable; + } + + // Fill index array + $aFlippedStringTable = $this->flipStringTable($aStringTable); + + // Loop through cells + foreach ($pSheet->getCellCollection() as $cellID) { + $cell = $pSheet->getCell($cellID); + $cellValue = $cell->getValue(); + if (!is_object($cellValue) && + ($cellValue !== null) && + $cellValue !== '' && + !isset($aFlippedStringTable[$cellValue]) && + ($cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_STRING2 || $cell->getDataType() == PHPExcel_Cell_DataType::TYPE_NULL)) { + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue] = true; + } elseif ($cellValue instanceof PHPExcel_RichText && + ($cellValue !== null) && + !isset($aFlippedStringTable[$cellValue->getHashCode()])) { + $aStringTable[] = $cellValue; + $aFlippedStringTable[$cellValue->getHashCode()] = true; + } + } + + return $aStringTable; + } else { + throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed."); + } + } + + /** + * Write string table to XML format + * + * @param string[] $pStringTable + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeStringTable($pStringTable = null) + { + if ($pStringTable !== null) { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // String table + $objWriter->startElement('sst'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('uniqueCount', count($pStringTable)); + + // Loop through string table + foreach ($pStringTable as $textElement) { + $objWriter->startElement('si'); + + if (! $textElement instanceof PHPExcel_RichText) { + $textToWrite = PHPExcel_Shared_String::ControlCharacterPHP2OOXML($textElement); + $objWriter->startElement('t'); + if ($textToWrite !== trim($textToWrite)) { + $objWriter->writeAttribute('xml:space', 'preserve'); + } + $objWriter->writeRawData($textToWrite); + $objWriter->endElement(); + } elseif ($textElement instanceof PHPExcel_RichText) { + $this->writeRichText($objWriter, $textElement); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + + return $objWriter->getData(); + } else { + throw new PHPExcel_Writer_Exception("Invalid string table array passed."); + } + } + + /** + * Write Rich Text + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_RichText $pRichText Rich text + * @param string $prefix Optional Namespace prefix + * @throws PHPExcel_Writer_Exception + */ + public function writeRichText(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_RichText $pRichText = null, $prefix = null) + { + if ($prefix !== null) { + $prefix .= ':'; + } + + // Loop through rich text elements + $elements = $pRichText->getRichTextElements(); + foreach ($elements as $element) { + // r + $objWriter->startElement($prefix.'r'); + + // rPr + if ($element instanceof PHPExcel_RichText_Run) { + // rPr + $objWriter->startElement($prefix.'rPr'); + + // rFont + $objWriter->startElement($prefix.'rFont'); + $objWriter->writeAttribute('val', $element->getFont()->getName()); + $objWriter->endElement(); + + // Bold + $objWriter->startElement($prefix.'b'); + $objWriter->writeAttribute('val', ($element->getFont()->getBold() ? 'true' : 'false')); + $objWriter->endElement(); + + // Italic + $objWriter->startElement($prefix.'i'); + $objWriter->writeAttribute('val', ($element->getFont()->getItalic() ? 'true' : 'false')); + $objWriter->endElement(); + + // Superscript / subscript + if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) { + $objWriter->startElement($prefix.'vertAlign'); + if ($element->getFont()->getSuperScript()) { + $objWriter->writeAttribute('val', 'superscript'); + } elseif ($element->getFont()->getSubScript()) { + $objWriter->writeAttribute('val', 'subscript'); + } + $objWriter->endElement(); + } + + // Strikethrough + $objWriter->startElement($prefix.'strike'); + $objWriter->writeAttribute('val', ($element->getFont()->getStrikethrough() ? 'true' : 'false')); + $objWriter->endElement(); + + // Color + $objWriter->startElement($prefix.'color'); + $objWriter->writeAttribute('rgb', $element->getFont()->getColor()->getARGB()); + $objWriter->endElement(); + + // Size + $objWriter->startElement($prefix.'sz'); + $objWriter->writeAttribute('val', $element->getFont()->getSize()); + $objWriter->endElement(); + + // Underline + $objWriter->startElement($prefix.'u'); + $objWriter->writeAttribute('val', $element->getFont()->getUnderline()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + + // t + $objWriter->startElement($prefix.'t'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($element->getText())); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write Rich Text + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string|PHPExcel_RichText $pRichText text string or Rich text + * @param string $prefix Optional Namespace prefix + * @throws PHPExcel_Writer_Exception + */ + public function writeRichTextForCharts(PHPExcel_Shared_XMLWriter $objWriter = null, $pRichText = null, $prefix = null) + { + if (!$pRichText instanceof PHPExcel_RichText) { + $textRun = $pRichText; + $pRichText = new PHPExcel_RichText(); + $pRichText->createTextRun($textRun); + } + + if ($prefix !== null) { + $prefix .= ':'; + } + + // Loop through rich text elements + $elements = $pRichText->getRichTextElements(); + foreach ($elements as $element) { + // r + $objWriter->startElement($prefix.'r'); + + // rPr + $objWriter->startElement($prefix.'rPr'); + + // Bold + $objWriter->writeAttribute('b', ($element->getFont()->getBold() ? 1 : 0)); + // Italic + $objWriter->writeAttribute('i', ($element->getFont()->getItalic() ? 1 : 0)); + // Underline + $underlineType = $element->getFont()->getUnderline(); + switch ($underlineType) { + case 'single': + $underlineType = 'sng'; + break; + case 'double': + $underlineType = 'dbl'; + break; + } + $objWriter->writeAttribute('u', $underlineType); + // Strikethrough + $objWriter->writeAttribute('strike', ($element->getFont()->getStrikethrough() ? 'sngStrike' : 'noStrike')); + + // rFont + $objWriter->startElement($prefix.'latin'); + $objWriter->writeAttribute('typeface', $element->getFont()->getName()); + $objWriter->endElement(); + + // Superscript / subscript +// if ($element->getFont()->getSuperScript() || $element->getFont()->getSubScript()) { +// $objWriter->startElement($prefix.'vertAlign'); +// if ($element->getFont()->getSuperScript()) { +// $objWriter->writeAttribute('val', 'superscript'); +// } elseif ($element->getFont()->getSubScript()) { +// $objWriter->writeAttribute('val', 'subscript'); +// } +// $objWriter->endElement(); +// } +// + $objWriter->endElement(); + + // t + $objWriter->startElement($prefix.'t'); +// $objWriter->writeAttribute('xml:space', 'preserve'); // Excel2010 accepts, Excel2007 complains + $objWriter->writeRawData(PHPExcel_Shared_String::ControlCharacterPHP2OOXML($element->getText())); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Flip string table (for index searching) + * + * @param array $stringTable Stringtable + * @return array + */ + public function flipStringTable($stringTable = array()) + { + // Return value + $returnValue = array(); + + // Loop through stringtable and add flipped items to $returnValue + foreach ($stringTable as $key => $value) { + if (! $value instanceof PHPExcel_RichText) { + $returnValue[$value] = $key; + } elseif ($value instanceof PHPExcel_RichText) { + $returnValue[$value->getHashCode()] = $key; + } + } + + return $returnValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Style.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Style.php new file mode 100644 index 00000000..d3f0af7b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Style.php @@ -0,0 +1,696 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Style + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Style extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write styles to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeStyles(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // styleSheet + $objWriter->startElement('styleSheet'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + + // numFmts + $objWriter->startElement('numFmts'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getNumFmtHashTable()->count()); + + // numFmt + for ($i = 0; $i < $this->getParentWriter()->getNumFmtHashTable()->count(); ++$i) { + $this->writeNumFmt($objWriter, $this->getParentWriter()->getNumFmtHashTable()->getByIndex($i), $i); + } + + $objWriter->endElement(); + + // fonts + $objWriter->startElement('fonts'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getFontHashTable()->count()); + + // font + for ($i = 0; $i < $this->getParentWriter()->getFontHashTable()->count(); ++$i) { + $this->writeFont($objWriter, $this->getParentWriter()->getFontHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // fills + $objWriter->startElement('fills'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getFillHashTable()->count()); + + // fill + for ($i = 0; $i < $this->getParentWriter()->getFillHashTable()->count(); ++$i) { + $this->writeFill($objWriter, $this->getParentWriter()->getFillHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // borders + $objWriter->startElement('borders'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getBordersHashTable()->count()); + + // border + for ($i = 0; $i < $this->getParentWriter()->getBordersHashTable()->count(); ++$i) { + $this->writeBorder($objWriter, $this->getParentWriter()->getBordersHashTable()->getByIndex($i)); + } + + $objWriter->endElement(); + + // cellStyleXfs + $objWriter->startElement('cellStyleXfs'); + $objWriter->writeAttribute('count', 1); + + // xf + $objWriter->startElement('xf'); + $objWriter->writeAttribute('numFmtId', 0); + $objWriter->writeAttribute('fontId', 0); + $objWriter->writeAttribute('fillId', 0); + $objWriter->writeAttribute('borderId', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + // cellXfs + $objWriter->startElement('cellXfs'); + $objWriter->writeAttribute('count', count($pPHPExcel->getCellXfCollection())); + + // xf + foreach ($pPHPExcel->getCellXfCollection() as $cellXf) { + $this->writeCellStyleXf($objWriter, $cellXf, $pPHPExcel); + } + + $objWriter->endElement(); + + // cellStyles + $objWriter->startElement('cellStyles'); + $objWriter->writeAttribute('count', 1); + + // cellStyle + $objWriter->startElement('cellStyle'); + $objWriter->writeAttribute('name', 'Normal'); + $objWriter->writeAttribute('xfId', 0); + $objWriter->writeAttribute('builtinId', 0); + $objWriter->endElement(); + + $objWriter->endElement(); + + // dxfs + $objWriter->startElement('dxfs'); + $objWriter->writeAttribute('count', $this->getParentWriter()->getStylesConditionalHashTable()->count()); + + // dxf + for ($i = 0; $i < $this->getParentWriter()->getStylesConditionalHashTable()->count(); ++$i) { + $this->writeCellStyleDxf($objWriter, $this->getParentWriter()->getStylesConditionalHashTable()->getByIndex($i)->getStyle()); + } + + $objWriter->endElement(); + + // tableStyles + $objWriter->startElement('tableStyles'); + $objWriter->writeAttribute('defaultTableStyle', 'TableStyleMedium9'); + $objWriter->writeAttribute('defaultPivotStyle', 'PivotTableStyle1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function writeFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // Check if this is a pattern type or gradient type + if ($pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR || + $pFill->getFillType() === PHPExcel_Style_Fill::FILL_GRADIENT_PATH) { + // Gradient fill + $this->writeGradientFill($objWriter, $pFill); + } elseif ($pFill->getFillType() !== null) { + // Pattern fill + $this->writePatternFill($objWriter, $pFill); + } + } + + /** + * Write Gradient Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function writeGradientFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // fill + $objWriter->startElement('fill'); + + // gradientFill + $objWriter->startElement('gradientFill'); + $objWriter->writeAttribute('type', $pFill->getFillType()); + $objWriter->writeAttribute('degree', $pFill->getRotation()); + + // stop + $objWriter->startElement('stop'); + $objWriter->writeAttribute('position', '0'); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + + // stop + $objWriter->startElement('stop'); + $objWriter->writeAttribute('position', '1'); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Pattern Fill + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Fill $pFill Fill style + * @throws PHPExcel_Writer_Exception + */ + private function writePatternFill(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Fill $pFill = null) + { + // fill + $objWriter->startElement('fill'); + + // patternFill + $objWriter->startElement('patternFill'); + $objWriter->writeAttribute('patternType', $pFill->getFillType()); + + if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) { + // fgColor + if ($pFill->getStartColor()->getARGB()) { + $objWriter->startElement('fgColor'); + $objWriter->writeAttribute('rgb', $pFill->getStartColor()->getARGB()); + $objWriter->endElement(); + } + } + if ($pFill->getFillType() !== PHPExcel_Style_Fill::FILL_NONE) { + // bgColor + if ($pFill->getEndColor()->getARGB()) { + $objWriter->startElement('bgColor'); + $objWriter->writeAttribute('rgb', $pFill->getEndColor()->getARGB()); + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write Font + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Font $pFont Font style + * @throws PHPExcel_Writer_Exception + */ + private function writeFont(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Font $pFont = null) + { + // font + $objWriter->startElement('font'); + // Weird! The order of these elements actually makes a difference when opening Excel2007 + // files in Excel2003 with the compatibility pack. It's not documented behaviour, + // and makes for a real WTF! + + // Bold. We explicitly write this element also when false (like MS Office Excel 2007 does + // for conditional formatting). Otherwise it will apparently not be picked up in conditional + // formatting style dialog + if ($pFont->getBold() !== null) { + $objWriter->startElement('b'); + $objWriter->writeAttribute('val', $pFont->getBold() ? '1' : '0'); + $objWriter->endElement(); + } + + // Italic + if ($pFont->getItalic() !== null) { + $objWriter->startElement('i'); + $objWriter->writeAttribute('val', $pFont->getItalic() ? '1' : '0'); + $objWriter->endElement(); + } + + // Strikethrough + if ($pFont->getStrikethrough() !== null) { + $objWriter->startElement('strike'); + $objWriter->writeAttribute('val', $pFont->getStrikethrough() ? '1' : '0'); + $objWriter->endElement(); + } + + // Underline + if ($pFont->getUnderline() !== null) { + $objWriter->startElement('u'); + $objWriter->writeAttribute('val', $pFont->getUnderline()); + $objWriter->endElement(); + } + + // Superscript / subscript + if ($pFont->getSuperScript() === true || $pFont->getSubScript() === true) { + $objWriter->startElement('vertAlign'); + if ($pFont->getSuperScript() === true) { + $objWriter->writeAttribute('val', 'superscript'); + } elseif ($pFont->getSubScript() === true) { + $objWriter->writeAttribute('val', 'subscript'); + } + $objWriter->endElement(); + } + + // Size + if ($pFont->getSize() !== null) { + $objWriter->startElement('sz'); + $objWriter->writeAttribute('val', $pFont->getSize()); + $objWriter->endElement(); + } + + // Foreground color + if ($pFont->getColor()->getARGB() !== null) { + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pFont->getColor()->getARGB()); + $objWriter->endElement(); + } + + // Name + if ($pFont->getName() !== null) { + $objWriter->startElement('name'); + $objWriter->writeAttribute('val', $pFont->getName()); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Border + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_Borders $pBorders Borders style + * @throws PHPExcel_Writer_Exception + */ + private function writeBorder(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_Borders $pBorders = null) + { + // Write border + $objWriter->startElement('border'); + // Diagonal? + switch ($pBorders->getDiagonalDirection()) { + case PHPExcel_Style_Borders::DIAGONAL_UP: + $objWriter->writeAttribute('diagonalUp', 'true'); + $objWriter->writeAttribute('diagonalDown', 'false'); + break; + case PHPExcel_Style_Borders::DIAGONAL_DOWN: + $objWriter->writeAttribute('diagonalUp', 'false'); + $objWriter->writeAttribute('diagonalDown', 'true'); + break; + case PHPExcel_Style_Borders::DIAGONAL_BOTH: + $objWriter->writeAttribute('diagonalUp', 'true'); + $objWriter->writeAttribute('diagonalDown', 'true'); + break; + } + + // BorderPr + $this->writeBorderPr($objWriter, 'left', $pBorders->getLeft()); + $this->writeBorderPr($objWriter, 'right', $pBorders->getRight()); + $this->writeBorderPr($objWriter, 'top', $pBorders->getTop()); + $this->writeBorderPr($objWriter, 'bottom', $pBorders->getBottom()); + $this->writeBorderPr($objWriter, 'diagonal', $pBorders->getDiagonal()); + $objWriter->endElement(); + } + + /** + * Write Cell Style Xf + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style $pStyle Style + * @param PHPExcel $pPHPExcel Workbook + * @throws PHPExcel_Writer_Exception + */ + private function writeCellStyleXf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null, PHPExcel $pPHPExcel = null) + { + // xf + $objWriter->startElement('xf'); + $objWriter->writeAttribute('xfId', 0); + $objWriter->writeAttribute('fontId', (int)$this->getParentWriter()->getFontHashTable()->getIndexForHashCode($pStyle->getFont()->getHashCode())); + if ($pStyle->getQuotePrefix()) { + $objWriter->writeAttribute('quotePrefix', 1); + } + + if ($pStyle->getNumberFormat()->getBuiltInFormatCode() === false) { + $objWriter->writeAttribute('numFmtId', (int)($this->getParentWriter()->getNumFmtHashTable()->getIndexForHashCode($pStyle->getNumberFormat()->getHashCode()) + 164)); + } else { + $objWriter->writeAttribute('numFmtId', (int)$pStyle->getNumberFormat()->getBuiltInFormatCode()); + } + + $objWriter->writeAttribute('fillId', (int)$this->getParentWriter()->getFillHashTable()->getIndexForHashCode($pStyle->getFill()->getHashCode())); + $objWriter->writeAttribute('borderId', (int)$this->getParentWriter()->getBordersHashTable()->getIndexForHashCode($pStyle->getBorders()->getHashCode())); + + // Apply styles? + $objWriter->writeAttribute('applyFont', ($pPHPExcel->getDefaultStyle()->getFont()->getHashCode() != $pStyle->getFont()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyNumberFormat', ($pPHPExcel->getDefaultStyle()->getNumberFormat()->getHashCode() != $pStyle->getNumberFormat()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyFill', ($pPHPExcel->getDefaultStyle()->getFill()->getHashCode() != $pStyle->getFill()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyBorder', ($pPHPExcel->getDefaultStyle()->getBorders()->getHashCode() != $pStyle->getBorders()->getHashCode()) ? '1' : '0'); + $objWriter->writeAttribute('applyAlignment', ($pPHPExcel->getDefaultStyle()->getAlignment()->getHashCode() != $pStyle->getAlignment()->getHashCode()) ? '1' : '0'); + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('applyProtection', 'true'); + } + + // alignment + $objWriter->startElement('alignment'); + $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); + $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + + $textRotation = 0; + if ($pStyle->getAlignment()->getTextRotation() >= 0) { + $textRotation = $pStyle->getAlignment()->getTextRotation(); + } elseif ($pStyle->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + } + $objWriter->writeAttribute('textRotation', $textRotation); + + $objWriter->writeAttribute('wrapText', ($pStyle->getAlignment()->getWrapText() ? 'true' : 'false')); + $objWriter->writeAttribute('shrinkToFit', ($pStyle->getAlignment()->getShrinkToFit() ? 'true' : 'false')); + + if ($pStyle->getAlignment()->getIndent() > 0) { + $objWriter->writeAttribute('indent', $pStyle->getAlignment()->getIndent()); + } + if ($pStyle->getAlignment()->getReadorder() > 0) { + $objWriter->writeAttribute('readingOrder', $pStyle->getAlignment()->getReadorder()); + } + $objWriter->endElement(); + + // protection + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT || $pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->startElement('protection'); + if ($pStyle->getProtection()->getLocked() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + if ($pStyle->getProtection()->getHidden() != PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Cell Style Dxf + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style $pStyle Style + * @throws PHPExcel_Writer_Exception + */ + private function writeCellStyleDxf(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style $pStyle = null) + { + // dxf + $objWriter->startElement('dxf'); + + // font + $this->writeFont($objWriter, $pStyle->getFont()); + + // numFmt + $this->writeNumFmt($objWriter, $pStyle->getNumberFormat()); + + // fill + $this->writeFill($objWriter, $pStyle->getFill()); + + // alignment + $objWriter->startElement('alignment'); + if ($pStyle->getAlignment()->getHorizontal() !== null) { + $objWriter->writeAttribute('horizontal', $pStyle->getAlignment()->getHorizontal()); + } + if ($pStyle->getAlignment()->getVertical() !== null) { + $objWriter->writeAttribute('vertical', $pStyle->getAlignment()->getVertical()); + } + + if ($pStyle->getAlignment()->getTextRotation() !== null) { + $textRotation = 0; + if ($pStyle->getAlignment()->getTextRotation() >= 0) { + $textRotation = $pStyle->getAlignment()->getTextRotation(); + } elseif ($pStyle->getAlignment()->getTextRotation() < 0) { + $textRotation = 90 - $pStyle->getAlignment()->getTextRotation(); + } + $objWriter->writeAttribute('textRotation', $textRotation); + } + $objWriter->endElement(); + + // border + $this->writeBorder($objWriter, $pStyle->getBorders()); + + // protection + if (($pStyle->getProtection()->getLocked() !== null) || ($pStyle->getProtection()->getHidden() !== null)) { + if ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT || + $pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT) { + $objWriter->startElement('protection'); + if (($pStyle->getProtection()->getLocked() !== null) && + ($pStyle->getProtection()->getLocked() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) { + $objWriter->writeAttribute('locked', ($pStyle->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + if (($pStyle->getProtection()->getHidden() !== null) && + ($pStyle->getProtection()->getHidden() !== PHPExcel_Style_Protection::PROTECTION_INHERIT)) { + $objWriter->writeAttribute('hidden', ($pStyle->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED ? 'true' : 'false')); + } + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } + + /** + * Write BorderPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pName Element name + * @param PHPExcel_Style_Border $pBorder Border style + * @throws PHPExcel_Writer_Exception + */ + private function writeBorderPr(PHPExcel_Shared_XMLWriter $objWriter = null, $pName = 'left', PHPExcel_Style_Border $pBorder = null) + { + // Write BorderPr + if ($pBorder->getBorderStyle() != PHPExcel_Style_Border::BORDER_NONE) { + $objWriter->startElement($pName); + $objWriter->writeAttribute('style', $pBorder->getBorderStyle()); + + // color + $objWriter->startElement('color'); + $objWriter->writeAttribute('rgb', $pBorder->getColor()->getARGB()); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + + /** + * Write NumberFormat + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Style_NumberFormat $pNumberFormat Number Format + * @param int $pId Number Format identifier + * @throws PHPExcel_Writer_Exception + */ + private function writeNumFmt(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Style_NumberFormat $pNumberFormat = null, $pId = 0) + { + // Translate formatcode + $formatCode = $pNumberFormat->getFormatCode(); + + // numFmt + if ($formatCode !== null) { + $objWriter->startElement('numFmt'); + $objWriter->writeAttribute('numFmtId', ($pId + 164)); + $objWriter->writeAttribute('formatCode', $formatCode); + $objWriter->endElement(); + } + } + + /** + * Get an array of all styles + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style[] All styles in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allStyles(PHPExcel $pPHPExcel = null) + { + return $pPHPExcel->getCellXfCollection(); + } + + /** + * Get an array of all conditional styles + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Conditional[] All conditional styles in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allConditionalStyles(PHPExcel $pPHPExcel = null) + { + // Get an array of all styles + $aStyles = array(); + + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + foreach ($pPHPExcel->getSheet($i)->getConditionalStylesCollection() as $conditionalStyles) { + foreach ($conditionalStyles as $conditionalStyle) { + $aStyles[] = $conditionalStyle; + } + } + } + + return $aStyles; + } + + /** + * Get an array of all fills + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Fill[] All fills in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allFills(PHPExcel $pPHPExcel = null) + { + // Get an array of unique fills + $aFills = array(); + + // Two first fills are predefined + $fill0 = new PHPExcel_Style_Fill(); + $fill0->setFillType(PHPExcel_Style_Fill::FILL_NONE); + $aFills[] = $fill0; + + $fill1 = new PHPExcel_Style_Fill(); + $fill1->setFillType(PHPExcel_Style_Fill::FILL_PATTERN_GRAY125); + $aFills[] = $fill1; + // The remaining fills + $aStyles = $this->allStyles($pPHPExcel); + foreach ($aStyles as $style) { + if (!array_key_exists($style->getFill()->getHashCode(), $aFills)) { + $aFills[ $style->getFill()->getHashCode() ] = $style->getFill(); + } + } + + return $aFills; + } + + /** + * Get an array of all fonts + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Font[] All fonts in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allFonts(PHPExcel $pPHPExcel = null) + { + // Get an array of unique fonts + $aFonts = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if (!array_key_exists($style->getFont()->getHashCode(), $aFonts)) { + $aFonts[ $style->getFont()->getHashCode() ] = $style->getFont(); + } + } + + return $aFonts; + } + + /** + * Get an array of all borders + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_Borders[] All borders in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allBorders(PHPExcel $pPHPExcel = null) + { + // Get an array of unique borders + $aBorders = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if (!array_key_exists($style->getBorders()->getHashCode(), $aBorders)) { + $aBorders[ $style->getBorders()->getHashCode() ] = $style->getBorders(); + } + } + + return $aBorders; + } + + /** + * Get an array of all number formats + * + * @param PHPExcel $pPHPExcel + * @return PHPExcel_Style_NumberFormat[] All number formats in PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function allNumberFormats(PHPExcel $pPHPExcel = null) + { + // Get an array of unique number formats + $aNumFmts = array(); + $aStyles = $this->allStyles($pPHPExcel); + + foreach ($aStyles as $style) { + if ($style->getNumberFormat()->getBuiltInFormatCode() === false && !array_key_exists($style->getNumberFormat()->getHashCode(), $aNumFmts)) { + $aNumFmts[ $style->getNumberFormat()->getHashCode() ] = $style->getNumberFormat(); + } + } + + return $aNumFmts; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Theme.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Theme.php new file mode 100644 index 00000000..223e4024 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Theme.php @@ -0,0 +1,869 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Writer_Excel2007_Theme + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Theme extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Map of Major fonts to write + * @static array of string + * + */ + private static $majorFonts = array( + 'Jpan' => 'MS Pゴシック', + 'Hang' => '맑은 고딕', + 'Hans' => '宋体', + 'Hant' => '新細明體', + 'Arab' => 'Times New Roman', + 'Hebr' => 'Times New Roman', + 'Thai' => 'Tahoma', + 'Ethi' => 'Nyala', + 'Beng' => 'Vrinda', + 'Gujr' => 'Shruti', + 'Khmr' => 'MoolBoran', + 'Knda' => 'Tunga', + 'Guru' => 'Raavi', + 'Cans' => 'Euphemia', + 'Cher' => 'Plantagenet Cherokee', + 'Yiii' => 'Microsoft Yi Baiti', + 'Tibt' => 'Microsoft Himalaya', + 'Thaa' => 'MV Boli', + 'Deva' => 'Mangal', + 'Telu' => 'Gautami', + 'Taml' => 'Latha', + 'Syrc' => 'Estrangelo Edessa', + 'Orya' => 'Kalinga', + 'Mlym' => 'Kartika', + 'Laoo' => 'DokChampa', + 'Sinh' => 'Iskoola Pota', + 'Mong' => 'Mongolian Baiti', + 'Viet' => 'Times New Roman', + 'Uigh' => 'Microsoft Uighur', + 'Geor' => 'Sylfaen', + ); + + /** + * Map of Minor fonts to write + * @static array of string + * + */ + private static $minorFonts = array( + 'Jpan' => 'MS Pゴシック', + 'Hang' => '맑은 고딕', + 'Hans' => '宋体', + 'Hant' => '新細明體', + 'Arab' => 'Arial', + 'Hebr' => 'Arial', + 'Thai' => 'Tahoma', + 'Ethi' => 'Nyala', + 'Beng' => 'Vrinda', + 'Gujr' => 'Shruti', + 'Khmr' => 'DaunPenh', + 'Knda' => 'Tunga', + 'Guru' => 'Raavi', + 'Cans' => 'Euphemia', + 'Cher' => 'Plantagenet Cherokee', + 'Yiii' => 'Microsoft Yi Baiti', + 'Tibt' => 'Microsoft Himalaya', + 'Thaa' => 'MV Boli', + 'Deva' => 'Mangal', + 'Telu' => 'Gautami', + 'Taml' => 'Latha', + 'Syrc' => 'Estrangelo Edessa', + 'Orya' => 'Kalinga', + 'Mlym' => 'Kartika', + 'Laoo' => 'DokChampa', + 'Sinh' => 'Iskoola Pota', + 'Mong' => 'Mongolian Baiti', + 'Viet' => 'Arial', + 'Uigh' => 'Microsoft Uighur', + 'Geor' => 'Sylfaen', + ); + + /** + * Map of core colours + * @static array of string + * + */ + private static $colourScheme = array( + 'dk2' => '1F497D', + 'lt2' => 'EEECE1', + 'accent1' => '4F81BD', + 'accent2' => 'C0504D', + 'accent3' => '9BBB59', + 'accent4' => '8064A2', + 'accent5' => '4BACC6', + 'accent6' => 'F79646', + 'hlink' => '0000FF', + 'folHlink' => '800080', + ); + + /** + * Write theme to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeTheme(PHPExcel $pPHPExcel = null) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // a:theme + $objWriter->startElement('a:theme'); + $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main'); + $objWriter->writeAttribute('name', 'Office Theme'); + + // a:themeElements + $objWriter->startElement('a:themeElements'); + + // a:clrScheme + $objWriter->startElement('a:clrScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:dk1 + $objWriter->startElement('a:dk1'); + + // a:sysClr + $objWriter->startElement('a:sysClr'); + $objWriter->writeAttribute('val', 'windowText'); + $objWriter->writeAttribute('lastClr', '000000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lt1 + $objWriter->startElement('a:lt1'); + + // a:sysClr + $objWriter->startElement('a:sysClr'); + $objWriter->writeAttribute('val', 'window'); + $objWriter->writeAttribute('lastClr', 'FFFFFF'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:dk2 + $this->writeColourScheme($objWriter); + + $objWriter->endElement(); + + // a:fontScheme + $objWriter->startElement('a:fontScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:majorFont + $objWriter->startElement('a:majorFont'); + $this->writeFonts($objWriter, 'Cambria', self::$majorFonts); + $objWriter->endElement(); + + // a:minorFont + $objWriter->startElement('a:minorFont'); + $this->writeFonts($objWriter, 'Calibri', self::$minorFonts); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:fmtScheme + $objWriter->startElement('a:fmtScheme'); + $objWriter->writeAttribute('name', 'Office'); + + // a:fillStyleLst + $objWriter->startElement('a:fillStyleLst'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '50000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '35000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '37000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '15000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lin + $objWriter->startElement('a:lin'); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '1'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '51000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '80000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '93000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '130000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '94000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '135000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lin + $objWriter->startElement('a:lin'); + $objWriter->writeAttribute('ang', '16200000'); + $objWriter->writeAttribute('scaled', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lnStyleLst + $objWriter->startElement('a:lnStyleLst'); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '9525'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '95000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '105000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '25400'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:ln + $objWriter->startElement('a:ln'); + $objWriter->writeAttribute('w', '38100'); + $objWriter->writeAttribute('cap', 'flat'); + $objWriter->writeAttribute('cmpd', 'sng'); + $objWriter->writeAttribute('algn', 'ctr'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:prstDash + $objWriter->startElement('a:prstDash'); + $objWriter->writeAttribute('val', 'solid'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + + + // a:effectStyleLst + $objWriter->startElement('a:effectStyleLst'); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '20000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '38000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:effectStyle + $objWriter->startElement('a:effectStyle'); + + // a:effectLst + $objWriter->startElement('a:effectLst'); + + // a:outerShdw + $objWriter->startElement('a:outerShdw'); + $objWriter->writeAttribute('blurRad', '40000'); + $objWriter->writeAttribute('dist', '23000'); + $objWriter->writeAttribute('dir', '5400000'); + $objWriter->writeAttribute('rotWithShape', '0'); + + // a:srgbClr + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', '000000'); + + // a:alpha + $objWriter->startElement('a:alpha'); + $objWriter->writeAttribute('val', '35000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:scene3d + $objWriter->startElement('a:scene3d'); + + // a:camera + $objWriter->startElement('a:camera'); + $objWriter->writeAttribute('prst', 'orthographicFront'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '0'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:lightRig + $objWriter->startElement('a:lightRig'); + $objWriter->writeAttribute('rig', 'threePt'); + $objWriter->writeAttribute('dir', 't'); + + // a:rot + $objWriter->startElement('a:rot'); + $objWriter->writeAttribute('lat', '0'); + $objWriter->writeAttribute('lon', '0'); + $objWriter->writeAttribute('rev', '1200000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:sp3d + $objWriter->startElement('a:sp3d'); + + // a:bevelT + $objWriter->startElement('a:bevelT'); + $objWriter->writeAttribute('w', '63500'); + $objWriter->writeAttribute('h', '25400'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:bgFillStyleLst + $objWriter->startElement('a:bgFillStyleLst'); + + // a:solidFill + $objWriter->startElement('a:solidFill'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '40000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '40000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '45000'); + $objWriter->endElement(); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '99000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '350000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '20000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '255000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:path + $objWriter->startElement('a:path'); + $objWriter->writeAttribute('path', 'circle'); + + // a:fillToRect + $objWriter->startElement('a:fillToRect'); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '-80000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '180000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gradFill + $objWriter->startElement('a:gradFill'); + $objWriter->writeAttribute('rotWithShape', '1'); + + // a:gsLst + $objWriter->startElement('a:gsLst'); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '0'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:tint + $objWriter->startElement('a:tint'); + $objWriter->writeAttribute('val', '80000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '300000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:gs + $objWriter->startElement('a:gs'); + $objWriter->writeAttribute('pos', '100000'); + + // a:schemeClr + $objWriter->startElement('a:schemeClr'); + $objWriter->writeAttribute('val', 'phClr'); + + // a:shade + $objWriter->startElement('a:shade'); + $objWriter->writeAttribute('val', '30000'); + $objWriter->endElement(); + + // a:satMod + $objWriter->startElement('a:satMod'); + $objWriter->writeAttribute('val', '200000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:path + $objWriter->startElement('a:path'); + $objWriter->writeAttribute('path', 'circle'); + + // a:fillToRect + $objWriter->startElement('a:fillToRect'); + $objWriter->writeAttribute('l', '50000'); + $objWriter->writeAttribute('t', '50000'); + $objWriter->writeAttribute('r', '50000'); + $objWriter->writeAttribute('b', '50000'); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + // a:objectDefaults + $objWriter->writeElement('a:objectDefaults', null); + + // a:extraClrSchemeLst + $objWriter->writeElement('a:extraClrSchemeLst', null); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write fonts to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @param string $latinFont + * @param array of string $fontSet + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + private function writeFonts($objWriter, $latinFont, $fontSet) + { + // a:latin + $objWriter->startElement('a:latin'); + $objWriter->writeAttribute('typeface', $latinFont); + $objWriter->endElement(); + + // a:ea + $objWriter->startElement('a:ea'); + $objWriter->writeAttribute('typeface', ''); + $objWriter->endElement(); + + // a:cs + $objWriter->startElement('a:cs'); + $objWriter->writeAttribute('typeface', ''); + $objWriter->endElement(); + + foreach ($fontSet as $fontScript => $typeface) { + $objWriter->startElement('a:font'); + $objWriter->writeAttribute('script', $fontScript); + $objWriter->writeAttribute('typeface', $typeface); + $objWriter->endElement(); + } + } + + /** + * Write colour scheme to XML format + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + private function writeColourScheme($objWriter) + { + foreach (self::$colourScheme as $colourName => $colourValue) { + $objWriter->startElement('a:'.$colourName); + + $objWriter->startElement('a:srgbClr'); + $objWriter->writeAttribute('val', $colourValue); + $objWriter->endElement(); + + $objWriter->endElement(); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Workbook.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Workbook.php new file mode 100644 index 00000000..87c877ea --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Workbook.php @@ -0,0 +1,448 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_Workbook + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel2007_Workbook extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write workbook to XML format + * + * @param PHPExcel $pPHPExcel + * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorkbook(PHPExcel $pPHPExcel = null, $recalcRequired = false) + { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // workbook + $objWriter->startElement('workbook'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + // fileVersion + $this->writeFileVersion($objWriter); + + // workbookPr + $this->writeWorkbookPr($objWriter); + + // workbookProtection + $this->writeWorkbookProtection($objWriter, $pPHPExcel); + + // bookViews + if ($this->getParentWriter()->getOffice2003Compatibility() === false) { + $this->writeBookViews($objWriter, $pPHPExcel); + } + + // sheets + $this->writeSheets($objWriter, $pPHPExcel); + + // definedNames + $this->writeDefinedNames($objWriter, $pPHPExcel); + + // calcPr + $this->writeCalcPr($objWriter, $recalcRequired); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } + + /** + * Write file version + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function writeFileVersion(PHPExcel_Shared_XMLWriter $objWriter = null) + { + $objWriter->startElement('fileVersion'); + $objWriter->writeAttribute('appName', 'xl'); + $objWriter->writeAttribute('lastEdited', '4'); + $objWriter->writeAttribute('lowestEdited', '4'); + $objWriter->writeAttribute('rupBuild', '4505'); + $objWriter->endElement(); + } + + /** + * Write WorkbookPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @throws PHPExcel_Writer_Exception + */ + private function writeWorkbookPr(PHPExcel_Shared_XMLWriter $objWriter = null) + { + $objWriter->startElement('workbookPr'); + + if (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) { + $objWriter->writeAttribute('date1904', '1'); + } + + $objWriter->writeAttribute('codeName', 'ThisWorkbook'); + + $objWriter->endElement(); + } + + /** + * Write BookViews + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function writeBookViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // bookViews + $objWriter->startElement('bookViews'); + + // workbookView + $objWriter->startElement('workbookView'); + + $objWriter->writeAttribute('activeTab', $pPHPExcel->getActiveSheetIndex()); + $objWriter->writeAttribute('autoFilterDateGrouping', '1'); + $objWriter->writeAttribute('firstSheet', '0'); + $objWriter->writeAttribute('minimized', '0'); + $objWriter->writeAttribute('showHorizontalScroll', '1'); + $objWriter->writeAttribute('showSheetTabs', '1'); + $objWriter->writeAttribute('showVerticalScroll', '1'); + $objWriter->writeAttribute('tabRatio', '600'); + $objWriter->writeAttribute('visibility', 'visible'); + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write WorkbookProtection + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function writeWorkbookProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + if ($pPHPExcel->getSecurity()->isSecurityEnabled()) { + $objWriter->startElement('workbookProtection'); + $objWriter->writeAttribute('lockRevision', ($pPHPExcel->getSecurity()->getLockRevision() ? 'true' : 'false')); + $objWriter->writeAttribute('lockStructure', ($pPHPExcel->getSecurity()->getLockStructure() ? 'true' : 'false')); + $objWriter->writeAttribute('lockWindows', ($pPHPExcel->getSecurity()->getLockWindows() ? 'true' : 'false')); + + if ($pPHPExcel->getSecurity()->getRevisionsPassword() != '') { + $objWriter->writeAttribute('revisionsPassword', $pPHPExcel->getSecurity()->getRevisionsPassword()); + } + + if ($pPHPExcel->getSecurity()->getWorkbookPassword() != '') { + $objWriter->writeAttribute('workbookPassword', $pPHPExcel->getSecurity()->getWorkbookPassword()); + } + + $objWriter->endElement(); + } + } + + /** + * Write calcPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param boolean $recalcRequired Indicate whether formulas should be recalculated before writing + * @throws PHPExcel_Writer_Exception + */ + private function writeCalcPr(PHPExcel_Shared_XMLWriter $objWriter = null, $recalcRequired = true) + { + $objWriter->startElement('calcPr'); + + // Set the calcid to a higher value than Excel itself will use, otherwise Excel will always recalc + // If MS Excel does do a recalc, then users opening a file in MS Excel will be prompted to save on exit + // because the file has changed + $objWriter->writeAttribute('calcId', '999999'); + $objWriter->writeAttribute('calcMode', 'auto'); + // fullCalcOnLoad isn't needed if we've recalculating for the save + $objWriter->writeAttribute('calcCompleted', ($recalcRequired) ? 1 : 0); + $objWriter->writeAttribute('fullCalcOnLoad', ($recalcRequired) ? 0 : 1); + + $objWriter->endElement(); + } + + /** + * Write sheets + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function writeSheets(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // Write sheets + $objWriter->startElement('sheets'); + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // sheet + $this->writeSheet( + $objWriter, + $pPHPExcel->getSheet($i)->getTitle(), + ($i + 1), + ($i + 1 + 3), + $pPHPExcel->getSheet($i)->getSheetState() + ); + } + + $objWriter->endElement(); + } + + /** + * Write sheet + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param string $pSheetname Sheet name + * @param int $pSheetId Sheet id + * @param int $pRelId Relationship ID + * @param string $sheetState Sheet state (visible, hidden, veryHidden) + * @throws PHPExcel_Writer_Exception + */ + private function writeSheet(PHPExcel_Shared_XMLWriter $objWriter = null, $pSheetname = '', $pSheetId = 1, $pRelId = 1, $sheetState = 'visible') + { + if ($pSheetname != '') { + // Write sheet + $objWriter->startElement('sheet'); + $objWriter->writeAttribute('name', $pSheetname); + $objWriter->writeAttribute('sheetId', $pSheetId); + if ($sheetState != 'visible' && $sheetState != '') { + $objWriter->writeAttribute('state', $sheetState); + } + $objWriter->writeAttribute('r:id', 'rId' . $pRelId); + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Defined Names + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function writeDefinedNames(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel = null) + { + // Write defined names + $objWriter->startElement('definedNames'); + + // Named ranges + if (count($pPHPExcel->getNamedRanges()) > 0) { + // Named ranges + $this->writeNamedRanges($objWriter, $pPHPExcel); + } + + // Other defined names + $sheetCount = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheetCount; ++$i) { + // definedName for autoFilter + $this->writeDefinedNameForAutofilter($objWriter, $pPHPExcel->getSheet($i), $i); + + // definedName for Print_Titles + $this->writeDefinedNameForPrintTitles($objWriter, $pPHPExcel->getSheet($i), $i); + + // definedName for Print_Area + $this->writeDefinedNameForPrintArea($objWriter, $pPHPExcel->getSheet($i), $i); + } + + $objWriter->endElement(); + } + + /** + * Write named ranges + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel $pPHPExcel + * @throws PHPExcel_Writer_Exception + */ + private function writeNamedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel $pPHPExcel) + { + // Loop named ranges + $namedRanges = $pPHPExcel->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + $this->writeDefinedNameForNamedRange($objWriter, $namedRange); + } + } + + /** + * Write Defined Name for named range + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_NamedRange $pNamedRange + * @throws PHPExcel_Writer_Exception + */ + private function writeDefinedNameForNamedRange(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_NamedRange $pNamedRange) + { + // definedName for named range + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', $pNamedRange->getName()); + if ($pNamedRange->getLocalOnly()) { + $objWriter->writeAttribute('localSheetId', $pNamedRange->getScope()->getParent()->getIndex($pNamedRange->getScope())); + } + + // Create absolute coordinate and write as raw text + $range = PHPExcel_Cell::splitRange($pNamedRange->getRange()); + for ($i = 0; $i < count($range); $i++) { + $range[$i][0] = '\'' . str_replace("'", "''", $pNamedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteReference($range[$i][0]); + if (isset($range[$i][1])) { + $range[$i][1] = PHPExcel_Cell::absoluteReference($range[$i][1]); + } + } + $range = PHPExcel_Cell::buildRange($range); + + $objWriter->writeRawData($range); + + $objWriter->endElement(); + } + + /** + * Write Defined Name for autoFilter + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function writeDefinedNameForAutofilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for autoFilter + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm._FilterDatabase'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + $objWriter->writeAttribute('hidden', '1'); + + // Create absolute coordinate and write as raw text + $range = PHPExcel_Cell::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref so we can make the cell ref absolute + if (strpos($range[0], '!') !== false) { + list($ws, $range[0]) = explode('!', $range[0]); + } + + $range[0] = PHPExcel_Cell::absoluteCoordinate($range[0]); + $range[1] = PHPExcel_Cell::absoluteCoordinate($range[1]); + $range = implode(':', $range); + + $objWriter->writeRawData('\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . $range); + + $objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function writeDefinedNameForPrintTitles(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for PrintTitles + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet() || $pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm.Print_Titles'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + + // Setting string + $settingString = ''; + + // Columns to repeat + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $repeat = $pSheet->getPageSetup()->getColumnsToRepeatAtLeft(); + + $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + // Rows to repeat + if ($pSheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + if ($pSheet->getPageSetup()->isColumnsToRepeatAtLeftSet()) { + $settingString .= ','; + } + + $repeat = $pSheet->getPageSetup()->getRowsToRepeatAtTop(); + + $settingString .= '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!$' . $repeat[0] . ':$' . $repeat[1]; + } + + $objWriter->writeRawData($settingString); + + $objWriter->endElement(); + } + } + + /** + * Write Defined Name for PrintTitles + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet + * @param int $pSheetId + * @throws PHPExcel_Writer_Exception + */ + private function writeDefinedNameForPrintArea(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pSheetId = 0) + { + // definedName for PrintArea + if ($pSheet->getPageSetup()->isPrintAreaSet()) { + $objWriter->startElement('definedName'); + $objWriter->writeAttribute('name', '_xlnm.Print_Area'); + $objWriter->writeAttribute('localSheetId', $pSheetId); + + // Setting string + $settingString = ''; + + // Print area + $printArea = PHPExcel_Cell::splitRange($pSheet->getPageSetup()->getPrintArea()); + + $chunks = array(); + foreach ($printArea as $printAreaRect) { + $printAreaRect[0] = PHPExcel_Cell::absoluteReference($printAreaRect[0]); + $printAreaRect[1] = PHPExcel_Cell::absoluteReference($printAreaRect[1]); + $chunks[] = '\'' . str_replace("'", "''", $pSheet->getTitle()) . '\'!' . implode(':', $printAreaRect); + } + + $objWriter->writeRawData(implode(',', $chunks)); + + $objWriter->endElement(); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Worksheet.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Worksheet.php new file mode 100644 index 00000000..c211403e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/Worksheet.php @@ -0,0 +1,1219 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Writer_Excel2007_Worksheet + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel2007_Worksheet extends PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Write worksheet to XML format + * + * @param PHPExcel_Worksheet $pSheet + * @param string[] $pStringTable + * @param boolean $includeCharts Flag indicating if we should write charts + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeWorksheet($pSheet = null, $pStringTable = null, $includeCharts = false) + { + if (!is_null($pSheet)) { + // Create XML writer + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8', 'yes'); + + // Worksheet + $objWriter->startElement('worksheet'); + $objWriter->writeAttribute('xml:space', 'preserve'); + $objWriter->writeAttribute('xmlns', 'http://schemas.openxmlformats.org/spreadsheetml/2006/main'); + $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'); + + // sheetPr + $this->writeSheetPr($objWriter, $pSheet); + + // Dimension + $this->writeDimension($objWriter, $pSheet); + + // sheetViews + $this->writeSheetViews($objWriter, $pSheet); + + // sheetFormatPr + $this->writeSheetFormatPr($objWriter, $pSheet); + + // cols + $this->writeCols($objWriter, $pSheet); + + // sheetData + $this->writeSheetData($objWriter, $pSheet, $pStringTable); + + // sheetProtection + $this->writeSheetProtection($objWriter, $pSheet); + + // protectedRanges + $this->writeProtectedRanges($objWriter, $pSheet); + + // autoFilter + $this->writeAutoFilter($objWriter, $pSheet); + + // mergeCells + $this->writeMergeCells($objWriter, $pSheet); + + // conditionalFormatting + $this->writeConditionalFormatting($objWriter, $pSheet); + + // dataValidations + $this->writeDataValidations($objWriter, $pSheet); + + // hyperlinks + $this->writeHyperlinks($objWriter, $pSheet); + + // Print options + $this->writePrintOptions($objWriter, $pSheet); + + // Page margins + $this->writePageMargins($objWriter, $pSheet); + + // Page setup + $this->writePageSetup($objWriter, $pSheet); + + // Header / footer + $this->writeHeaderFooter($objWriter, $pSheet); + + // Breaks + $this->writeBreaks($objWriter, $pSheet); + + // Drawings and/or Charts + $this->writeDrawings($objWriter, $pSheet, $includeCharts); + + // LegacyDrawing + $this->writeLegacyDrawing($objWriter, $pSheet); + + // LegacyDrawingHF + $this->writeLegacyDrawingHF($objWriter, $pSheet); + + $objWriter->endElement(); + + // Return + return $objWriter->getData(); + } else { + throw new PHPExcel_Writer_Exception("Invalid PHPExcel_Worksheet object passed."); + } + } + + /** + * Write SheetPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeSheetPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetPr + $objWriter->startElement('sheetPr'); + //$objWriter->writeAttribute('codeName', $pSheet->getTitle()); + if ($pSheet->getParent()->hasMacros()) {//if the workbook have macros, we need to have codeName for the sheet + if ($pSheet->hasCodeName()==false) { + $pSheet->setCodeName($pSheet->getTitle()); + } + $objWriter->writeAttribute('codeName', $pSheet->getCodeName()); + } + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + $objWriter->writeAttribute('filterMode', 1); + $pSheet->getAutoFilter()->showHideRows(); + } + + // tabColor + if ($pSheet->isTabColorSet()) { + $objWriter->startElement('tabColor'); + $objWriter->writeAttribute('rgb', $pSheet->getTabColor()->getARGB()); + $objWriter->endElement(); + } + + // outlinePr + $objWriter->startElement('outlinePr'); + $objWriter->writeAttribute('summaryBelow', ($pSheet->getShowSummaryBelow() ? '1' : '0')); + $objWriter->writeAttribute('summaryRight', ($pSheet->getShowSummaryRight() ? '1' : '0')); + $objWriter->endElement(); + + // pageSetUpPr + if ($pSheet->getPageSetup()->getFitToPage()) { + $objWriter->startElement('pageSetUpPr'); + $objWriter->writeAttribute('fitToPage', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + /** + * Write Dimension + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeDimension(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // dimension + $objWriter->startElement('dimension'); + $objWriter->writeAttribute('ref', $pSheet->calculateWorksheetDimension()); + $objWriter->endElement(); + } + + /** + * Write SheetViews + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeSheetViews(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetViews + $objWriter->startElement('sheetViews'); + + // Sheet selected? + $sheetSelected = false; + if ($this->getParentWriter()->getPHPExcel()->getIndex($pSheet) == $this->getParentWriter()->getPHPExcel()->getActiveSheetIndex()) { + $sheetSelected = true; + } + + // sheetView + $objWriter->startElement('sheetView'); + $objWriter->writeAttribute('tabSelected', $sheetSelected ? '1' : '0'); + $objWriter->writeAttribute('workbookViewId', '0'); + + // Zoom scales + if ($pSheet->getSheetView()->getZoomScale() != 100) { + $objWriter->writeAttribute('zoomScale', $pSheet->getSheetView()->getZoomScale()); + } + if ($pSheet->getSheetView()->getZoomScaleNormal() != 100) { + $objWriter->writeAttribute('zoomScaleNormal', $pSheet->getSheetView()->getZoomScaleNormal()); + } + + // View Layout Type + if ($pSheet->getSheetView()->getView() !== PHPExcel_Worksheet_SheetView::SHEETVIEW_NORMAL) { + $objWriter->writeAttribute('view', $pSheet->getSheetView()->getView()); + } + + // Gridlines + if ($pSheet->getShowGridlines()) { + $objWriter->writeAttribute('showGridLines', 'true'); + } else { + $objWriter->writeAttribute('showGridLines', 'false'); + } + + // Row and column headers + if ($pSheet->getShowRowColHeaders()) { + $objWriter->writeAttribute('showRowColHeaders', '1'); + } else { + $objWriter->writeAttribute('showRowColHeaders', '0'); + } + + // Right-to-left + if ($pSheet->getRightToLeft()) { + $objWriter->writeAttribute('rightToLeft', 'true'); + } + + $activeCell = $pSheet->getActiveCell(); + + // Pane + $pane = ''; + $topLeftCell = $pSheet->getFreezePane(); + if (($topLeftCell != '') && ($topLeftCell != 'A1')) { + $activeCell = empty($activeCell) ? $topLeftCell : $activeCell; + // Calculate freeze coordinates + $xSplit = $ySplit = 0; + + list($xSplit, $ySplit) = PHPExcel_Cell::coordinateFromString($topLeftCell); + $xSplit = PHPExcel_Cell::columnIndexFromString($xSplit); + + // pane + $pane = 'topRight'; + $objWriter->startElement('pane'); + if ($xSplit > 1) { + $objWriter->writeAttribute('xSplit', $xSplit - 1); + } + if ($ySplit > 1) { + $objWriter->writeAttribute('ySplit', $ySplit - 1); + $pane = ($xSplit > 1) ? 'bottomRight' : 'bottomLeft'; + } + $objWriter->writeAttribute('topLeftCell', $topLeftCell); + $objWriter->writeAttribute('activePane', $pane); + $objWriter->writeAttribute('state', 'frozen'); + $objWriter->endElement(); + + if (($xSplit > 1) && ($ySplit > 1)) { + // Write additional selections if more than two panes (ie both an X and a Y split) + $objWriter->startElement('selection'); + $objWriter->writeAttribute('pane', 'topRight'); + $objWriter->endElement(); + $objWriter->startElement('selection'); + $objWriter->writeAttribute('pane', 'bottomLeft'); + $objWriter->endElement(); + } + } + + // Selection +// if ($pane != '') { + // Only need to write selection element if we have a split pane + // We cheat a little by over-riding the active cell selection, setting it to the split cell + $objWriter->startElement('selection'); + if ($pane != '') { + $objWriter->writeAttribute('pane', $pane); + } + $objWriter->writeAttribute('activeCell', $activeCell); + $objWriter->writeAttribute('sqref', $activeCell); + $objWriter->endElement(); +// } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + + /** + * Write SheetFormatPr + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeSheetFormatPr(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetFormatPr + $objWriter->startElement('sheetFormatPr'); + + // Default row height + if ($pSheet->getDefaultRowDimension()->getRowHeight() >= 0) { + $objWriter->writeAttribute('customHeight', 'true'); + $objWriter->writeAttribute('defaultRowHeight', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultRowDimension()->getRowHeight())); + } else { + $objWriter->writeAttribute('defaultRowHeight', '14.4'); + } + + // Set Zero Height row + if ((string)$pSheet->getDefaultRowDimension()->getZeroHeight() == '1' || + strtolower((string)$pSheet->getDefaultRowDimension()->getZeroHeight()) == 'true') { + $objWriter->writeAttribute('zeroHeight', '1'); + } + + // Default column width + if ($pSheet->getDefaultColumnDimension()->getWidth() >= 0) { + $objWriter->writeAttribute('defaultColWidth', PHPExcel_Shared_String::FormatNumber($pSheet->getDefaultColumnDimension()->getWidth())); + } + + // Outline level - row + $outlineLevelRow = 0; + foreach ($pSheet->getRowDimensions() as $dimension) { + if ($dimension->getOutlineLevel() > $outlineLevelRow) { + $outlineLevelRow = $dimension->getOutlineLevel(); + } + } + $objWriter->writeAttribute('outlineLevelRow', (int)$outlineLevelRow); + + // Outline level - column + $outlineLevelCol = 0; + foreach ($pSheet->getColumnDimensions() as $dimension) { + if ($dimension->getOutlineLevel() > $outlineLevelCol) { + $outlineLevelCol = $dimension->getOutlineLevel(); + } + } + $objWriter->writeAttribute('outlineLevelCol', (int)$outlineLevelCol); + + $objWriter->endElement(); + } + + /** + * Write Cols + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeCols(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // cols + if (count($pSheet->getColumnDimensions()) > 0) { + $objWriter->startElement('cols'); + + $pSheet->calculateColumnWidths(); + + // Loop through column dimensions + foreach ($pSheet->getColumnDimensions() as $colDimension) { + // col + $objWriter->startElement('col'); + $objWriter->writeAttribute('min', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex())); + $objWriter->writeAttribute('max', PHPExcel_Cell::columnIndexFromString($colDimension->getColumnIndex())); + + if ($colDimension->getWidth() < 0) { + // No width set, apply default of 10 + $objWriter->writeAttribute('width', '9.10'); + } else { + // Width set + $objWriter->writeAttribute('width', PHPExcel_Shared_String::FormatNumber($colDimension->getWidth())); + } + + // Column visibility + if ($colDimension->getVisible() == false) { + $objWriter->writeAttribute('hidden', 'true'); + } + + // Auto size? + if ($colDimension->getAutoSize()) { + $objWriter->writeAttribute('bestFit', 'true'); + } + + // Custom width? + if ($colDimension->getWidth() != $pSheet->getDefaultColumnDimension()->getWidth()) { + $objWriter->writeAttribute('customWidth', 'true'); + } + + // Collapsed + if ($colDimension->getCollapsed() == true) { + $objWriter->writeAttribute('collapsed', 'true'); + } + + // Outline level + if ($colDimension->getOutlineLevel() > 0) { + $objWriter->writeAttribute('outlineLevel', $colDimension->getOutlineLevel()); + } + + // Style + $objWriter->writeAttribute('style', $colDimension->getXfIndex()); + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write SheetProtection + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeSheetProtection(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // sheetProtection + $objWriter->startElement('sheetProtection'); + + if ($pSheet->getProtection()->getPassword() != '') { + $objWriter->writeAttribute('password', $pSheet->getProtection()->getPassword()); + } + + $objWriter->writeAttribute('sheet', ($pSheet->getProtection()->getSheet() ? 'true' : 'false')); + $objWriter->writeAttribute('objects', ($pSheet->getProtection()->getObjects() ? 'true' : 'false')); + $objWriter->writeAttribute('scenarios', ($pSheet->getProtection()->getScenarios() ? 'true' : 'false')); + $objWriter->writeAttribute('formatCells', ($pSheet->getProtection()->getFormatCells() ? 'true' : 'false')); + $objWriter->writeAttribute('formatColumns', ($pSheet->getProtection()->getFormatColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('formatRows', ($pSheet->getProtection()->getFormatRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertColumns', ($pSheet->getProtection()->getInsertColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('insertRows', ($pSheet->getProtection()->getInsertRows() ? 'true' : 'false')); + $objWriter->writeAttribute('insertHyperlinks', ($pSheet->getProtection()->getInsertHyperlinks() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteColumns', ($pSheet->getProtection()->getDeleteColumns() ? 'true' : 'false')); + $objWriter->writeAttribute('deleteRows', ($pSheet->getProtection()->getDeleteRows() ? 'true' : 'false')); + $objWriter->writeAttribute('selectLockedCells', ($pSheet->getProtection()->getSelectLockedCells() ? 'true' : 'false')); + $objWriter->writeAttribute('sort', ($pSheet->getProtection()->getSort() ? 'true' : 'false')); + $objWriter->writeAttribute('autoFilter', ($pSheet->getProtection()->getAutoFilter() ? 'true' : 'false')); + $objWriter->writeAttribute('pivotTables', ($pSheet->getProtection()->getPivotTables() ? 'true' : 'false')); + $objWriter->writeAttribute('selectUnlockedCells', ($pSheet->getProtection()->getSelectUnlockedCells() ? 'true' : 'false')); + $objWriter->endElement(); + } + + /** + * Write ConditionalFormatting + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeConditionalFormatting(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Conditional id + $id = 1; + + // Loop through styles in the current worksheet + foreach ($pSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + // WHY was this again? + // if ($this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode()) == '') { + // continue; + // } + if ($conditional->getConditionType() != PHPExcel_Style_Conditional::CONDITION_NONE) { + // conditionalFormatting + $objWriter->startElement('conditionalFormatting'); + $objWriter->writeAttribute('sqref', $cellCoordinate); + + // cfRule + $objWriter->startElement('cfRule'); + $objWriter->writeAttribute('type', $conditional->getConditionType()); + $objWriter->writeAttribute('dxfId', $this->getParentWriter()->getStylesConditionalHashTable()->getIndexForHashCode($conditional->getHashCode())); + $objWriter->writeAttribute('priority', $id++); + + if (($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT) + && $conditional->getOperatorType() != PHPExcel_Style_Conditional::OPERATOR_NONE) { + $objWriter->writeAttribute('operator', $conditional->getOperatorType()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeAttribute('text', $conditional->getText()); + } + + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_CONTAINSTEXT + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'NOT(ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . ')))'); + } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BEGINSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'LEFT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_ENDSWITH + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'RIGHT(' . $cellCoordinate . ',' . strlen($conditional->getText()) . ')="' . $conditional->getText() . '"'); + } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + && $conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_NOTCONTAINS + && !is_null($conditional->getText())) { + $objWriter->writeElement('formula', 'ISERROR(SEARCH("' . $conditional->getText() . '",' . $cellCoordinate . '))'); + } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CONTAINSTEXT + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) { + foreach ($conditional->getConditions() as $formula) { + // Formula + $objWriter->writeElement('formula', $formula); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + } + } + + /** + * Write DataValidations + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeDataValidations(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Datavalidation collection + $dataValidationCollection = $pSheet->getDataValidationCollection(); + + // Write data validations? + if (!empty($dataValidationCollection)) { + $objWriter->startElement('dataValidations'); + $objWriter->writeAttribute('count', count($dataValidationCollection)); + + foreach ($dataValidationCollection as $coordinate => $dv) { + $objWriter->startElement('dataValidation'); + + if ($dv->getType() != '') { + $objWriter->writeAttribute('type', $dv->getType()); + } + + if ($dv->getErrorStyle() != '') { + $objWriter->writeAttribute('errorStyle', $dv->getErrorStyle()); + } + + if ($dv->getOperator() != '') { + $objWriter->writeAttribute('operator', $dv->getOperator()); + } + + $objWriter->writeAttribute('allowBlank', ($dv->getAllowBlank() ? '1' : '0')); + $objWriter->writeAttribute('showDropDown', (!$dv->getShowDropDown() ? '1' : '0')); + $objWriter->writeAttribute('showInputMessage', ($dv->getShowInputMessage() ? '1' : '0')); + $objWriter->writeAttribute('showErrorMessage', ($dv->getShowErrorMessage() ? '1' : '0')); + + if ($dv->getErrorTitle() !== '') { + $objWriter->writeAttribute('errorTitle', $dv->getErrorTitle()); + } + if ($dv->getError() !== '') { + $objWriter->writeAttribute('error', $dv->getError()); + } + if ($dv->getPromptTitle() !== '') { + $objWriter->writeAttribute('promptTitle', $dv->getPromptTitle()); + } + if ($dv->getPrompt() !== '') { + $objWriter->writeAttribute('prompt', $dv->getPrompt()); + } + + $objWriter->writeAttribute('sqref', $coordinate); + + if ($dv->getFormula1() !== '') { + $objWriter->writeElement('formula1', $dv->getFormula1()); + } + if ($dv->getFormula2() !== '') { + $objWriter->writeElement('formula2', $dv->getFormula2()); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write Hyperlinks + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeHyperlinks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Hyperlink collection + $hyperlinkCollection = $pSheet->getHyperlinkCollection(); + + // Relation ID + $relationId = 1; + + // Write hyperlinks? + if (!empty($hyperlinkCollection)) { + $objWriter->startElement('hyperlinks'); + + foreach ($hyperlinkCollection as $coordinate => $hyperlink) { + $objWriter->startElement('hyperlink'); + + $objWriter->writeAttribute('ref', $coordinate); + if (!$hyperlink->isInternal()) { + $objWriter->writeAttribute('r:id', 'rId_hyperlink_' . $relationId); + ++$relationId; + } else { + $objWriter->writeAttribute('location', str_replace('sheet://', '', $hyperlink->getUrl())); + } + + if ($hyperlink->getTooltip() != '') { + $objWriter->writeAttribute('tooltip', $hyperlink->getTooltip()); + } + + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write ProtectedRanges + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeProtectedRanges(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + if (count($pSheet->getProtectedCells()) > 0) { + // protectedRanges + $objWriter->startElement('protectedRanges'); + + // Loop protectedRanges + foreach ($pSheet->getProtectedCells() as $protectedCell => $passwordHash) { + // protectedRange + $objWriter->startElement('protectedRange'); + $objWriter->writeAttribute('name', 'p' . md5($protectedCell)); + $objWriter->writeAttribute('sqref', $protectedCell); + if (!empty($passwordHash)) { + $objWriter->writeAttribute('password', $passwordHash); + } + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write MergeCells + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeMergeCells(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + if (count($pSheet->getMergeCells()) > 0) { + // mergeCells + $objWriter->startElement('mergeCells'); + + // Loop mergeCells + foreach ($pSheet->getMergeCells() as $mergeCell) { + // mergeCell + $objWriter->startElement('mergeCell'); + $objWriter->writeAttribute('ref', $mergeCell); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write PrintOptions + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writePrintOptions(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // printOptions + $objWriter->startElement('printOptions'); + + $objWriter->writeAttribute('gridLines', ($pSheet->getPrintGridlines() ? 'true': 'false')); + $objWriter->writeAttribute('gridLinesSet', 'true'); + + if ($pSheet->getPageSetup()->getHorizontalCentered()) { + $objWriter->writeAttribute('horizontalCentered', 'true'); + } + + if ($pSheet->getPageSetup()->getVerticalCentered()) { + $objWriter->writeAttribute('verticalCentered', 'true'); + } + + $objWriter->endElement(); + } + + /** + * Write PageMargins + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writePageMargins(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // pageMargins + $objWriter->startElement('pageMargins'); + $objWriter->writeAttribute('left', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft())); + $objWriter->writeAttribute('right', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight())); + $objWriter->writeAttribute('top', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop())); + $objWriter->writeAttribute('bottom', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom())); + $objWriter->writeAttribute('header', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getHeader())); + $objWriter->writeAttribute('footer', PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getFooter())); + $objWriter->endElement(); + } + + /** + * Write AutoFilter + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeAutoFilter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + $autoFilterRange = $pSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + // autoFilter + $objWriter->startElement('autoFilter'); + + // Strip any worksheet reference from the filter coordinates + $range = PHPExcel_Cell::splitRange($autoFilterRange); + $range = $range[0]; + // Strip any worksheet ref + if (strpos($range[0], '!') !== false) { + list($ws, $range[0]) = explode('!', $range[0]); + } + $range = implode(':', $range); + + $objWriter->writeAttribute('ref', str_replace('$', '', $range)); + + $columns = $pSheet->getAutoFilter()->getColumns(); + if (count($columns > 0)) { + foreach ($columns as $columnID => $column) { + $rules = $column->getRules(); + if (count($rules) > 0) { + $objWriter->startElement('filterColumn'); + $objWriter->writeAttribute('colId', $pSheet->getAutoFilter()->getColumnOffset($columnID)); + + $objWriter->startElement($column->getFilterType()); + if ($column->getJoin() == PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_COLUMN_JOIN_AND) { + $objWriter->writeAttribute('and', 1); + } + + foreach ($rules as $rule) { + if (($column->getFilterType() === PHPExcel_Worksheet_AutoFilter_Column::AUTOFILTER_FILTERTYPE_FILTER) && + ($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) && + ($rule->getValue() === '')) { + // Filter rule for Blanks + $objWriter->writeAttribute('blank', 1); + } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DYNAMICFILTER) { + // Dynamic Filter Rule + $objWriter->writeAttribute('type', $rule->getGrouping()); + $val = $column->getAttribute('val'); + if ($val !== null) { + $objWriter->writeAttribute('val', $val); + } + $maxVal = $column->getAttribute('maxVal'); + if ($maxVal !== null) { + $objWriter->writeAttribute('maxVal', $maxVal); + } + } elseif ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_TOPTENFILTER) { + // Top 10 Filter Rule + $objWriter->writeAttribute('val', $rule->getValue()); + $objWriter->writeAttribute('percent', (($rule->getOperator() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_PERCENT) ? '1' : '0')); + $objWriter->writeAttribute('top', (($rule->getGrouping() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_TOPTEN_TOP) ? '1': '0')); + } else { + // Filter, DateGroupItem or CustomFilter + $objWriter->startElement($rule->getRuleType()); + + if ($rule->getOperator() !== PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_COLUMN_RULE_EQUAL) { + $objWriter->writeAttribute('operator', $rule->getOperator()); + } + if ($rule->getRuleType() === PHPExcel_Worksheet_AutoFilter_Column_Rule::AUTOFILTER_RULETYPE_DATEGROUP) { + // Date Group filters + foreach ($rule->getValue() as $key => $value) { + if ($value > '') { + $objWriter->writeAttribute($key, $value); + } + } + $objWriter->writeAttribute('dateTimeGrouping', $rule->getGrouping()); + } else { + $objWriter->writeAttribute('val', $rule->getValue()); + } + + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + + $objWriter->endElement(); + } + } + } + $objWriter->endElement(); + } + } + + /** + * Write PageSetup + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writePageSetup(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // pageSetup + $objWriter->startElement('pageSetup'); + $objWriter->writeAttribute('paperSize', $pSheet->getPageSetup()->getPaperSize()); + $objWriter->writeAttribute('orientation', $pSheet->getPageSetup()->getOrientation()); + + if (!is_null($pSheet->getPageSetup()->getScale())) { + $objWriter->writeAttribute('scale', $pSheet->getPageSetup()->getScale()); + } + if (!is_null($pSheet->getPageSetup()->getFitToHeight())) { + $objWriter->writeAttribute('fitToHeight', $pSheet->getPageSetup()->getFitToHeight()); + } else { + $objWriter->writeAttribute('fitToHeight', '0'); + } + if (!is_null($pSheet->getPageSetup()->getFitToWidth())) { + $objWriter->writeAttribute('fitToWidth', $pSheet->getPageSetup()->getFitToWidth()); + } else { + $objWriter->writeAttribute('fitToWidth', '0'); + } + if (!is_null($pSheet->getPageSetup()->getFirstPageNumber())) { + $objWriter->writeAttribute('firstPageNumber', $pSheet->getPageSetup()->getFirstPageNumber()); + $objWriter->writeAttribute('useFirstPageNumber', '1'); + } + + $objWriter->endElement(); + } + + /** + * Write Header / Footer + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeHeaderFooter(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // headerFooter + $objWriter->startElement('headerFooter'); + $objWriter->writeAttribute('differentOddEven', ($pSheet->getHeaderFooter()->getDifferentOddEven() ? 'true' : 'false')); + $objWriter->writeAttribute('differentFirst', ($pSheet->getHeaderFooter()->getDifferentFirst() ? 'true' : 'false')); + $objWriter->writeAttribute('scaleWithDoc', ($pSheet->getHeaderFooter()->getScaleWithDocument() ? 'true' : 'false')); + $objWriter->writeAttribute('alignWithMargins', ($pSheet->getHeaderFooter()->getAlignWithMargins() ? 'true' : 'false')); + + $objWriter->writeElement('oddHeader', $pSheet->getHeaderFooter()->getOddHeader()); + $objWriter->writeElement('oddFooter', $pSheet->getHeaderFooter()->getOddFooter()); + $objWriter->writeElement('evenHeader', $pSheet->getHeaderFooter()->getEvenHeader()); + $objWriter->writeElement('evenFooter', $pSheet->getHeaderFooter()->getEvenFooter()); + $objWriter->writeElement('firstHeader', $pSheet->getHeaderFooter()->getFirstHeader()); + $objWriter->writeElement('firstFooter', $pSheet->getHeaderFooter()->getFirstFooter()); + $objWriter->endElement(); + } + + /** + * Write Breaks + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeBreaks(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // Get row and column breaks + $aRowBreaks = array(); + $aColumnBreaks = array(); + foreach ($pSheet->getBreaks() as $cell => $breakType) { + if ($breakType == PHPExcel_Worksheet::BREAK_ROW) { + $aRowBreaks[] = $cell; + } elseif ($breakType == PHPExcel_Worksheet::BREAK_COLUMN) { + $aColumnBreaks[] = $cell; + } + } + + // rowBreaks + if (!empty($aRowBreaks)) { + $objWriter->startElement('rowBreaks'); + $objWriter->writeAttribute('count', count($aRowBreaks)); + $objWriter->writeAttribute('manualBreakCount', count($aRowBreaks)); + + foreach ($aRowBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); + + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', $coords[1]); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + + // Second, write column breaks + if (!empty($aColumnBreaks)) { + $objWriter->startElement('colBreaks'); + $objWriter->writeAttribute('count', count($aColumnBreaks)); + $objWriter->writeAttribute('manualBreakCount', count($aColumnBreaks)); + + foreach ($aColumnBreaks as $cell) { + $coords = PHPExcel_Cell::coordinateFromString($cell); + + $objWriter->startElement('brk'); + $objWriter->writeAttribute('id', PHPExcel_Cell::columnIndexFromString($coords[0]) - 1); + $objWriter->writeAttribute('man', '1'); + $objWriter->endElement(); + } + + $objWriter->endElement(); + } + } + + /** + * Write SheetData + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param string[] $pStringTable String table + * @throws PHPExcel_Writer_Exception + */ + private function writeSheetData(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pStringTable = null) + { + if (is_array($pStringTable)) { + // Flipped stringtable, for faster index searching + $aFlippedStringTable = $this->getParentWriter()->getWriterPart('stringtable')->flipStringTable($pStringTable); + + // sheetData + $objWriter->startElement('sheetData'); + + // Get column count + $colCount = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()); + + // Highest row number + $highestRow = $pSheet->getHighestRow(); + + // Loop through cells + $cellsByRow = array(); + foreach ($pSheet->getCellCollection() as $cellID) { + $cellAddress = PHPExcel_Cell::coordinateFromString($cellID); + $cellsByRow[$cellAddress[1]][] = $cellID; + } + + $currentRow = 0; + while ($currentRow++ < $highestRow) { + // Get row dimension + $rowDimension = $pSheet->getRowDimension($currentRow); + + // Write current row? + $writeCurrentRow = isset($cellsByRow[$currentRow]) || $rowDimension->getRowHeight() >= 0 || $rowDimension->getVisible() == false || $rowDimension->getCollapsed() == true || $rowDimension->getOutlineLevel() > 0 || $rowDimension->getXfIndex() !== null; + + if ($writeCurrentRow) { + // Start a new row + $objWriter->startElement('row'); + $objWriter->writeAttribute('r', $currentRow); + $objWriter->writeAttribute('spans', '1:' . $colCount); + + // Row dimensions + if ($rowDimension->getRowHeight() >= 0) { + $objWriter->writeAttribute('customHeight', '1'); + $objWriter->writeAttribute('ht', PHPExcel_Shared_String::FormatNumber($rowDimension->getRowHeight())); + } + + // Row visibility + if ($rowDimension->getVisible() == false) { + $objWriter->writeAttribute('hidden', 'true'); + } + + // Collapsed + if ($rowDimension->getCollapsed() == true) { + $objWriter->writeAttribute('collapsed', 'true'); + } + + // Outline level + if ($rowDimension->getOutlineLevel() > 0) { + $objWriter->writeAttribute('outlineLevel', $rowDimension->getOutlineLevel()); + } + + // Style + if ($rowDimension->getXfIndex() !== null) { + $objWriter->writeAttribute('s', $rowDimension->getXfIndex()); + $objWriter->writeAttribute('customFormat', '1'); + } + + // Write cells + if (isset($cellsByRow[$currentRow])) { + foreach ($cellsByRow[$currentRow] as $cellAddress) { + // Write cell + $this->writeCell($objWriter, $pSheet, $cellAddress, $pStringTable, $aFlippedStringTable); + } + } + + // End row + $objWriter->endElement(); + } + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Cell + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param PHPExcel_Cell $pCellAddress Cell Address + * @param string[] $pStringTable String table + * @param string[] $pFlippedStringTable String table (flipped), for faster index searching + * @throws PHPExcel_Writer_Exception + */ + private function writeCell(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $pCellAddress = null, $pStringTable = null, $pFlippedStringTable = null) + { + if (is_array($pStringTable) && is_array($pFlippedStringTable)) { + // Cell + $pCell = $pSheet->getCell($pCellAddress); + $objWriter->startElement('c'); + $objWriter->writeAttribute('r', $pCellAddress); + + // Sheet styles + if ($pCell->getXfIndex() != '') { + $objWriter->writeAttribute('s', $pCell->getXfIndex()); + } + + // If cell value is supplied, write cell value + $cellValue = $pCell->getValue(); + if (is_object($cellValue) || $cellValue !== '') { + // Map type + $mappedType = $pCell->getDataType(); + + // Write data type depending on its type + switch (strtolower($mappedType)) { + case 'inlinestr': // Inline string + case 's': // String + case 'b': // Boolean + $objWriter->writeAttribute('t', $mappedType); + break; + case 'f': // Formula + $calculatedValue = ($this->getParentWriter()->getPreCalculateFormulas()) ? + $pCell->getCalculatedValue() : + $cellValue; + if (is_string($calculatedValue)) { + $objWriter->writeAttribute('t', 'str'); + } + break; + case 'e': // Error + $objWriter->writeAttribute('t', $mappedType); + } + + // Write data depending on its type + switch (strtolower($mappedType)) { + case 'inlinestr': // Inline string + if (! $cellValue instanceof PHPExcel_RichText) { + $objWriter->writeElement('t', PHPExcel_Shared_String::ControlCharacterPHP2OOXML(htmlspecialchars($cellValue))); + } elseif ($cellValue instanceof PHPExcel_RichText) { + $objWriter->startElement('is'); + $this->getParentWriter()->getWriterPart('stringtable')->writeRichText($objWriter, $cellValue); + $objWriter->endElement(); + } + + break; + case 's': // String + if (! $cellValue instanceof PHPExcel_RichText) { + if (isset($pFlippedStringTable[$cellValue])) { + $objWriter->writeElement('v', $pFlippedStringTable[$cellValue]); + } + } elseif ($cellValue instanceof PHPExcel_RichText) { + $objWriter->writeElement('v', $pFlippedStringTable[$cellValue->getHashCode()]); + } + + break; + case 'f': // Formula + $attributes = $pCell->getFormulaAttributes(); + if ($attributes['t'] == 'array') { + $objWriter->startElement('f'); + $objWriter->writeAttribute('t', 'array'); + $objWriter->writeAttribute('ref', $pCellAddress); + $objWriter->writeAttribute('aca', '1'); + $objWriter->writeAttribute('ca', '1'); + $objWriter->text(substr($cellValue, 1)); + $objWriter->endElement(); + } else { + $objWriter->writeElement('f', substr($cellValue, 1)); + } + if ($this->getParentWriter()->getOffice2003Compatibility() === false) { + if ($this->getParentWriter()->getPreCalculateFormulas()) { +// $calculatedValue = $pCell->getCalculatedValue(); + if (!is_array($calculatedValue) && substr($calculatedValue, 0, 1) != '#') { + $objWriter->writeElement('v', PHPExcel_Shared_String::FormatNumber($calculatedValue)); + } else { + $objWriter->writeElement('v', '0'); + } + } else { + $objWriter->writeElement('v', '0'); + } + } + break; + case 'n': // Numeric + // force point as decimal separator in case current locale uses comma + $objWriter->writeElement('v', str_replace(',', '.', $cellValue)); + break; + case 'b': // Boolean + $objWriter->writeElement('v', ($cellValue ? '1' : '0')); + break; + case 'e': // Error + if (substr($cellValue, 0, 1) == '=') { + $objWriter->writeElement('f', substr($cellValue, 1)); + $objWriter->writeElement('v', substr($cellValue, 1)); + } else { + $objWriter->writeElement('v', $cellValue); + } + + break; + } + } + + $objWriter->endElement(); + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Write Drawings + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @param boolean $includeCharts Flag indicating if we should include drawing details for charts + * @throws PHPExcel_Writer_Exception + */ + private function writeDrawings(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null, $includeCharts = false) + { + $chartCount = ($includeCharts) ? $pSheet->getChartCollection()->count() : 0; + // If sheet contains drawings, add the relationships + if (($pSheet->getDrawingCollection()->count() > 0) || + ($chartCount > 0)) { + $objWriter->startElement('drawing'); + $objWriter->writeAttribute('r:id', 'rId1'); + $objWriter->endElement(); + } + } + + /** + * Write LegacyDrawing + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeLegacyDrawing(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // If sheet contains comments, add the relationships + if (count($pSheet->getComments()) > 0) { + $objWriter->startElement('legacyDrawing'); + $objWriter->writeAttribute('r:id', 'rId_comments_vml1'); + $objWriter->endElement(); + } + } + + /** + * Write LegacyDrawingHF + * + * @param PHPExcel_Shared_XMLWriter $objWriter XML Writer + * @param PHPExcel_Worksheet $pSheet Worksheet + * @throws PHPExcel_Writer_Exception + */ + private function writeLegacyDrawingHF(PHPExcel_Shared_XMLWriter $objWriter = null, PHPExcel_Worksheet $pSheet = null) + { + // If sheet contains images, add the relationships + if (count($pSheet->getHeaderFooter()->getImages()) > 0) { + $objWriter->startElement('legacyDrawingHF'); + $objWriter->writeAttribute('r:id', 'rId_headerfooter_vml1'); + $objWriter->endElement(); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/WriterPart.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/WriterPart.php new file mode 100644 index 00000000..806ebe51 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel2007/WriterPart.php @@ -0,0 +1,75 @@ +<?php + +/** + * PHPExcel_Writer_Excel2007_WriterPart + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel2007 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Writer_Excel2007_WriterPart +{ + /** + * Parent IWriter object + * + * @var PHPExcel_Writer_IWriter + */ + private $parentWriter; + + /** + * Set parent IWriter object + * + * @param PHPExcel_Writer_IWriter $pWriter + * @throws PHPExcel_Writer_Exception + */ + public function setParentWriter(PHPExcel_Writer_IWriter $pWriter = null) + { + $this->parentWriter = $pWriter; + } + + /** + * Get parent IWriter object + * + * @return PHPExcel_Writer_IWriter + * @throws PHPExcel_Writer_Exception + */ + public function getParentWriter() + { + if (!is_null($this->parentWriter)) { + return $this->parentWriter; + } else { + throw new PHPExcel_Writer_Exception("No parent PHPExcel_Writer_IWriter assigned."); + } + } + + /** + * Set parent IWriter object + * + * @param PHPExcel_Writer_IWriter $pWriter + * @throws PHPExcel_Writer_Exception + */ + public function __construct(PHPExcel_Writer_IWriter $pWriter = null) + { + if (!is_null($pWriter)) { + $this->parentWriter = $pWriter; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5.php new file mode 100644 index 00000000..2dede819 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5.php @@ -0,0 +1,904 @@ +<?php + +/** + * PHPExcel_Writer_Excel5 + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel5 extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * PHPExcel object + * + * @var PHPExcel + */ + private $phpExcel; + + /** + * Total number of shared strings in workbook + * + * @var int + */ + private $strTotal = 0; + + /** + * Number of unique shared strings in workbook + * + * @var int + */ + private $strUnique = 0; + + /** + * Array of unique shared strings in workbook + * + * @var array + */ + private $strTable = array(); + + /** + * Color cache. Mapping between RGB value and color index. + * + * @var array + */ + private $colors; + + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $parser; + + /** + * Identifier clusters for drawings. Used in MSODRAWINGGROUP record. + * + * @var array + */ + private $IDCLs; + + /** + * Basic OLE object summary information + * + * @var array + */ + private $summaryInformation; + + /** + * Extended OLE object document summary information + * + * @var array + */ + private $documentSummaryInformation; + + /** + * Create a new PHPExcel_Writer_Excel5 + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + $this->phpExcel = $phpExcel; + + $this->parser = new PHPExcel_Writer_Excel5_Parser(); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + + // garbage collect + $this->phpExcel->garbageCollect(); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog(false); + $saveDateReturnType = PHPExcel_Calculation_Functions::getReturnDateType(); + PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL); + + // initialize colors array + $this->colors = array(); + + // Initialise workbook writer + $this->writerWorkbook = new PHPExcel_Writer_Excel5_Workbook($this->phpExcel, $this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser); + + // Initialise worksheet writers + $countSheets = $this->phpExcel->getSheetCount(); + for ($i = 0; $i < $countSheets; ++$i) { + $this->writerWorksheets[$i] = new PHPExcel_Writer_Excel5_Worksheet($this->strTotal, $this->strUnique, $this->strTable, $this->colors, $this->parser, $this->preCalculateFormulas, $this->phpExcel->getSheet($i)); + } + + // build Escher objects. Escher objects for workbooks needs to be build before Escher object for workbook. + $this->buildWorksheetEschers(); + $this->buildWorkbookEscher(); + + // add 15 identical cell style Xfs + // for now, we use the first cellXf instead of cellStyleXf + $cellXfCollection = $this->phpExcel->getCellXfCollection(); + for ($i = 0; $i < 15; ++$i) { + $this->writerWorkbook->addXfWriter($cellXfCollection[0], true); + } + + // add all the cell Xfs + foreach ($this->phpExcel->getCellXfCollection() as $style) { + $this->writerWorkbook->addXfWriter($style, false); + } + + // add fonts from rich text eleemnts + for ($i = 0; $i < $countSheets; ++$i) { + foreach ($this->writerWorksheets[$i]->phpSheet->getCellCollection() as $cellID) { + $cell = $this->writerWorksheets[$i]->phpSheet->getCell($cellID); + $cVal = $cell->getValue(); + if ($cVal instanceof PHPExcel_RichText) { + $elements = $cVal->getRichTextElements(); + foreach ($elements as $element) { + if ($element instanceof PHPExcel_RichText_Run) { + $font = $element->getFont(); + $this->writerWorksheets[$i]->fontHashIndex[$font->getHashCode()] = $this->writerWorkbook->addFont($font); + } + } + } + } + } + + // initialize OLE file + $workbookStreamName = 'Workbook'; + $OLE = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs($workbookStreamName)); + + // Write the worksheet streams before the global workbook stream, + // because the byte sizes of these are needed in the global workbook stream + $worksheetSizes = array(); + for ($i = 0; $i < $countSheets; ++$i) { + $this->writerWorksheets[$i]->close(); + $worksheetSizes[] = $this->writerWorksheets[$i]->_datasize; + } + + // add binary data for global workbook stream + $OLE->append($this->writerWorkbook->writeWorkbook($worksheetSizes)); + + // add binary data for sheet streams + for ($i = 0; $i < $countSheets; ++$i) { + $OLE->append($this->writerWorksheets[$i]->getData()); + } + + $this->documentSummaryInformation = $this->writeDocumentSummaryInformation(); + // initialize OLE Document Summary Information + if (isset($this->documentSummaryInformation) && !empty($this->documentSummaryInformation)) { + $OLE_DocumentSummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'DocumentSummaryInformation')); + $OLE_DocumentSummaryInformation->append($this->documentSummaryInformation); + } + + $this->summaryInformation = $this->writeSummaryInformation(); + // initialize OLE Summary Information + if (isset($this->summaryInformation) && !empty($this->summaryInformation)) { + $OLE_SummaryInformation = new PHPExcel_Shared_OLE_PPS_File(PHPExcel_Shared_OLE::Asc2Ucs(chr(5) . 'SummaryInformation')); + $OLE_SummaryInformation->append($this->summaryInformation); + } + + // define OLE Parts + $arrRootData = array($OLE); + // initialize OLE Properties file + if (isset($OLE_SummaryInformation)) { + $arrRootData[] = $OLE_SummaryInformation; + } + // initialize OLE Extended Properties file + if (isset($OLE_DocumentSummaryInformation)) { + $arrRootData[] = $OLE_DocumentSummaryInformation; + } + + $root = new PHPExcel_Shared_OLE_PPS_Root(time(), time(), $arrRootData); + // save the OLE file + $res = $root->save($pFilename); + + PHPExcel_Calculation_Functions::setReturnDateType($saveDateReturnType); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Set temporary storage directory + * + * @deprecated + * @param string $pValue Temporary storage directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_Excel5 + */ + public function setTempDir($pValue = '') + { + return $this; + } + + /** + * Build the Worksheet Escher objects + * + */ + private function buildWorksheetEschers() + { + // 1-based index to BstoreContainer + $blipIndex = 0; + $lastReducedSpId = 0; + $lastSpId = 0; + + foreach ($this->phpExcel->getAllsheets() as $sheet) { + // sheet index + $sheetIndex = $sheet->getParent()->getIndex($sheet); + + $escher = null; + + // check if there are any shapes for this sheet + $filterRange = $sheet->getAutoFilter()->getRange(); + if (count($sheet->getDrawingCollection()) == 0 && empty($filterRange)) { + continue; + } + + // create intermediate Escher object + $escher = new PHPExcel_Shared_Escher(); + + // dgContainer + $dgContainer = new PHPExcel_Shared_Escher_DgContainer(); + + // set the drawing index (we use sheet index + 1) + $dgId = $sheet->getParent()->getIndex($sheet) + 1; + $dgContainer->setDgId($dgId); + $escher->setDgContainer($dgContainer); + + // spgrContainer + $spgrContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer(); + $dgContainer->setSpgrContainer($spgrContainer); + + // add one shape which is the group shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + $spContainer->setSpgr(true); + $spContainer->setSpType(0); + $spContainer->setSpId(($sheet->getParent()->getIndex($sheet) + 1) << 10); + $spgrContainer->addChild($spContainer); + + // add the shapes + + $countShapes[$sheetIndex] = 0; // count number of shapes (minus group shape), in sheet + + foreach ($sheet->getDrawingCollection() as $drawing) { + ++$blipIndex; + + ++$countShapes[$sheetIndex]; + + // add the shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + + // set the shape type + $spContainer->setSpType(0x004B); + // set the shape flag + $spContainer->setSpFlag(0x02); + + // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) + $reducedSpId = $countShapes[$sheetIndex]; + $spId = $reducedSpId + | ($sheet->getParent()->getIndex($sheet) + 1) << 10; + $spContainer->setSpId($spId); + + // keep track of last reducedSpId + $lastReducedSpId = $reducedSpId; + + // keep track of last spId + $lastSpId = $spId; + + // set the BLIP index + $spContainer->setOPT(0x4104, $blipIndex); + + // set coordinates and offsets, client anchor + $coordinates = $drawing->getCoordinates(); + $offsetX = $drawing->getOffsetX(); + $offsetY = $drawing->getOffsetY(); + $width = $drawing->getWidth(); + $height = $drawing->getHeight(); + + $twoAnchor = PHPExcel_Shared_Excel5::oneAnchor2twoAnchor($sheet, $coordinates, $offsetX, $offsetY, $width, $height); + + $spContainer->setStartCoordinates($twoAnchor['startCoordinates']); + $spContainer->setStartOffsetX($twoAnchor['startOffsetX']); + $spContainer->setStartOffsetY($twoAnchor['startOffsetY']); + $spContainer->setEndCoordinates($twoAnchor['endCoordinates']); + $spContainer->setEndOffsetX($twoAnchor['endOffsetX']); + $spContainer->setEndOffsetY($twoAnchor['endOffsetY']); + + $spgrContainer->addChild($spContainer); + } + + // AutoFilters + if (!empty($filterRange)) { + $rangeBounds = PHPExcel_Cell::rangeBoundaries($filterRange); + $iNumColStart = $rangeBounds[0][0]; + $iNumColEnd = $rangeBounds[1][0]; + + $iInc = $iNumColStart; + while ($iInc <= $iNumColEnd) { + ++$countShapes[$sheetIndex]; + + // create an Drawing Object for the dropdown + $oDrawing = new PHPExcel_Worksheet_BaseDrawing(); + // get the coordinates of drawing + $cDrawing = PHPExcel_Cell::stringFromColumnIndex($iInc - 1) . $rangeBounds[0][1]; + $oDrawing->setCoordinates($cDrawing); + $oDrawing->setWorksheet($sheet); + + // add the shape + $spContainer = new PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer(); + // set the shape type + $spContainer->setSpType(0x00C9); + // set the shape flag + $spContainer->setSpFlag(0x01); + + // set the shape index (we combine 1-based sheet index and $countShapes to create unique shape index) + $reducedSpId = $countShapes[$sheetIndex]; + $spId = $reducedSpId + | ($sheet->getParent()->getIndex($sheet) + 1) << 10; + $spContainer->setSpId($spId); + + // keep track of last reducedSpId + $lastReducedSpId = $reducedSpId; + + // keep track of last spId + $lastSpId = $spId; + + $spContainer->setOPT(0x007F, 0x01040104); // Protection -> fLockAgainstGrouping + $spContainer->setOPT(0x00BF, 0x00080008); // Text -> fFitTextToShape + $spContainer->setOPT(0x01BF, 0x00010000); // Fill Style -> fNoFillHitTest + $spContainer->setOPT(0x01FF, 0x00080000); // Line Style -> fNoLineDrawDash + $spContainer->setOPT(0x03BF, 0x000A0000); // Group Shape -> fPrint + + // set coordinates and offsets, client anchor + $endCoordinates = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::stringFromColumnIndex($iInc - 1)); + $endCoordinates .= $rangeBounds[0][1] + 1; + + $spContainer->setStartCoordinates($cDrawing); + $spContainer->setStartOffsetX(0); + $spContainer->setStartOffsetY(0); + $spContainer->setEndCoordinates($endCoordinates); + $spContainer->setEndOffsetX(0); + $spContainer->setEndOffsetY(0); + + $spgrContainer->addChild($spContainer); + $iInc++; + } + } + + // identifier clusters, used for workbook Escher object + $this->IDCLs[$dgId] = $lastReducedSpId; + + // set last shape index + $dgContainer->setLastSpId($lastSpId); + + // set the Escher object + $this->writerWorksheets[$sheetIndex]->setEscher($escher); + } + } + + /** + * Build the Escher object corresponding to the MSODRAWINGGROUP record + */ + private function buildWorkbookEscher() + { + $escher = null; + + // any drawings in this workbook? + $found = false; + foreach ($this->phpExcel->getAllSheets() as $sheet) { + if (count($sheet->getDrawingCollection()) > 0) { + $found = true; + break; + } + } + + // nothing to do if there are no drawings + if (!$found) { + return; + } + + // if we reach here, then there are drawings in the workbook + $escher = new PHPExcel_Shared_Escher(); + + // dggContainer + $dggContainer = new PHPExcel_Shared_Escher_DggContainer(); + $escher->setDggContainer($dggContainer); + + // set IDCLs (identifier clusters) + $dggContainer->setIDCLs($this->IDCLs); + + // this loop is for determining maximum shape identifier of all drawing + $spIdMax = 0; + $totalCountShapes = 0; + $countDrawings = 0; + + foreach ($this->phpExcel->getAllsheets() as $sheet) { + $sheetCountShapes = 0; // count number of shapes (minus group shape), in sheet + + if (count($sheet->getDrawingCollection()) > 0) { + ++$countDrawings; + + foreach ($sheet->getDrawingCollection() as $drawing) { + ++$sheetCountShapes; + ++$totalCountShapes; + + $spId = $sheetCountShapes | ($this->phpExcel->getIndex($sheet) + 1) << 10; + $spIdMax = max($spId, $spIdMax); + } + } + } + + $dggContainer->setSpIdMax($spIdMax + 1); + $dggContainer->setCDgSaved($countDrawings); + $dggContainer->setCSpSaved($totalCountShapes + $countDrawings); // total number of shapes incl. one group shapes per drawing + + // bstoreContainer + $bstoreContainer = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer(); + $dggContainer->setBstoreContainer($bstoreContainer); + + // the BSE's (all the images) + foreach ($this->phpExcel->getAllsheets() as $sheet) { + foreach ($sheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + $filename = $drawing->getPath(); + + list($imagesx, $imagesy, $imageFormat) = getimagesize($filename); + + switch ($imageFormat) { + case 1: // GIF, not supported by BIFF8, we convert to PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + ob_start(); + imagepng(imagecreatefromgif($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + break; + case 2: // JPEG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG; + $blipData = file_get_contents($filename); + break; + case 3: // PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + $blipData = file_get_contents($filename); + break; + case 6: // Windows DIB (BMP), we convert to PNG + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + ob_start(); + imagepng(PHPExcel_Shared_Drawing::imagecreatefrombmp($filename)); + $blipData = ob_get_contents(); + ob_end_clean(); + break; + default: + continue 2; + } + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($blipData); + + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + } elseif ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) { + switch ($drawing->getRenderingFunction()) { + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_JPEG: + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG; + $renderingFunction = 'imagejpeg'; + break; + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_GIF: + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_PNG: + case PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT: + $blipType = PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG; + $renderingFunction = 'imagepng'; + break; + } + + ob_start(); + call_user_func($renderingFunction, $drawing->getImageResource()); + $blipData = ob_get_contents(); + ob_end_clean(); + + $blip = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip(); + $blip->setData($blipData); + + $BSE = new PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE(); + $BSE->setBlipType($blipType); + $BSE->setBlip($blip); + + $bstoreContainer->addBSE($BSE); + } + } + } + + // Set the Escher object + $this->writerWorkbook->setEscher($escher); + } + + /** + * Build the OLE Part for DocumentSummary Information + * @return string + */ + private function writeDocumentSummaryInformation() + { + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + $data = pack('v', 0xFFFE); + // offset: 2; size: 2; + $data .= pack('v', 0x0000); + // offset: 4; size: 2; OS version + $data .= pack('v', 0x0106); + // offset: 6; size: 2; OS indicator + $data .= pack('v', 0x0002); + // offset: 8; size: 16 + $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); + // offset: 24; size: 4; section count + $data .= pack('V', 0x0001); + + // offset: 28; size: 16; first section's class id: 02 d5 cd d5 9c 2e 1b 10 93 97 08 00 2b 2c f9 ae + $data .= pack('vvvvvvvv', 0xD502, 0xD5CD, 0x2E9C, 0x101B, 0x9793, 0x0008, 0x2C2B, 0xAEF9); + // offset: 44; size: 4; offset of the start + $data .= pack('V', 0x30); + + // SECTION + $dataSection = array(); + $dataSection_NumProps = 0; + $dataSection_Summary = ''; + $dataSection_Content = ''; + + // GKPIDDSI_CODEPAGE: CodePage + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer + 'data' => array('data' => 1252)); + $dataSection_NumProps++; + + // GKPIDDSI_CATEGORY : Category + if ($this->phpExcel->getProperties()->getCategory()) { + $dataProp = $this->phpExcel->getProperties()->getCategory(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // GKPIDDSI_VERSION :Version of the application that wrote the property storage + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x17), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x03), + 'data' => array('pack' => 'V', 'data' => 0x000C0000)); + $dataSection_NumProps++; + // GKPIDDSI_SCALE : FALSE + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0B), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_LINKSDIRTY : True if any of the values for the linked properties have changed outside of the application + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x10), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_SHAREDOC : FALSE + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + // GKPIDDSI_HYPERLINKSCHANGED : True if any of the values for the _PID_LINKS (hyperlink text) have changed outside of the application + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x16), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x0B), + 'data' => array('data' => false)); + $dataSection_NumProps++; + + // GKPIDDSI_DOCSPARTS + // MS-OSHARED p75 (2.3.3.2.2.1) + // Structure is VtVecUnalignedLpstrValue (2.3.3.1.9) + // cElements + $dataProp = pack('v', 0x0001); + $dataProp .= pack('v', 0x0000); + // array of UnalignedLpstr + // cch + $dataProp .= pack('v', 0x000A); + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= 'Worksheet'.chr(0); + + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x101E), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + + // GKPIDDSI_HEADINGPAIR + // VtVecHeadingPairValue + // cElements + $dataProp = pack('v', 0x0002); + $dataProp .= pack('v', 0x0000); + // Array of vtHeadingPair + // vtUnalignedString - headingString + // stringType + $dataProp .= pack('v', 0x001E); + // padding + $dataProp .= pack('v', 0x0000); + // UnalignedLpstr + // cch + $dataProp .= pack('v', 0x0013); + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= 'Feuilles de calcul'; + // vtUnalignedString - headingParts + // wType : 0x0003 = 32 bit signed integer + $dataProp .= pack('v', 0x0300); + // padding + $dataProp .= pack('v', 0x0000); + // value + $dataProp .= pack('v', 0x0100); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + $dataProp .= pack('v', 0x0000); + + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x100C), + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + + // 4 Section Length + // 4 Property count + // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) + $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; + foreach ($dataSection as $dataProp) { + // Summary + $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); + // Offset + $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); + // DataType + $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); + // Data + if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } elseif ($dataProp['type']['data'] == 0x0B) { // Boolean + if ($dataProp['data']['data'] == false) { + $dataSection_Content .= pack('V', 0x0000); + } else { + $dataSection_Content .= pack('V', 0x0001); + } + $dataSection_Content_Offset += 4 + 4; + } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length + // Null-terminated string + $dataProp['data']['data'] .= chr(0); + $dataProp['data']['length'] += 1; + // Complete the string with null string for being a %4 + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); + + $dataSection_Content .= pack('V', $dataProp['data']['length']); + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); + } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 8; + } else { + // Data Type Not Used at the moment + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + $dataProp['data']['length']; + } + } + // Now $dataSection_Content_Offset contains the size of the content + + // section header + // offset: $secOffset; size: 4; section length + // + x Size of the content (summary + content) + $data .= pack('V', $dataSection_Content_Offset); + // offset: $secOffset+4; size: 4; property count + $data .= pack('V', $dataSection_NumProps); + // Section Summary + $data .= $dataSection_Summary; + // Section Content + $data .= $dataSection_Content; + + return $data; + } + + /** + * Build the OLE Part for Summary Information + * @return string + */ + private function writeSummaryInformation() + { + // offset: 0; size: 2; must be 0xFE 0xFF (UTF-16 LE byte order mark) + $data = pack('v', 0xFFFE); + // offset: 2; size: 2; + $data .= pack('v', 0x0000); + // offset: 4; size: 2; OS version + $data .= pack('v', 0x0106); + // offset: 6; size: 2; OS indicator + $data .= pack('v', 0x0002); + // offset: 8; size: 16 + $data .= pack('VVVV', 0x00, 0x00, 0x00, 0x00); + // offset: 24; size: 4; section count + $data .= pack('V', 0x0001); + + // offset: 28; size: 16; first section's class id: e0 85 9f f2 f9 4f 68 10 ab 91 08 00 2b 27 b3 d9 + $data .= pack('vvvvvvvv', 0x85E0, 0xF29F, 0x4FF9, 0x1068, 0x91AB, 0x0008, 0x272B, 0xD9B3); + // offset: 44; size: 4; offset of the start + $data .= pack('V', 0x30); + + // SECTION + $dataSection = array(); + $dataSection_NumProps = 0; + $dataSection_Summary = ''; + $dataSection_Content = ''; + + // CodePage : CP-1252 + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x01), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x02), // 2 byte signed integer + 'data' => array('data' => 1252)); + $dataSection_NumProps++; + + // Title + if ($this->phpExcel->getProperties()->getTitle()) { + $dataProp = $this->phpExcel->getProperties()->getTitle(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x02), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Subject + if ($this->phpExcel->getProperties()->getSubject()) { + $dataProp = $this->phpExcel->getProperties()->getSubject(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x03), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Author (Creator) + if ($this->phpExcel->getProperties()->getCreator()) { + $dataProp = $this->phpExcel->getProperties()->getCreator(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x04), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Keywords + if ($this->phpExcel->getProperties()->getKeywords()) { + $dataProp = $this->phpExcel->getProperties()->getKeywords(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x05), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Comments (Description) + if ($this->phpExcel->getProperties()->getDescription()) { + $dataProp = $this->phpExcel->getProperties()->getDescription(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x06), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Last Saved By (LastModifiedBy) + if ($this->phpExcel->getProperties()->getLastModifiedBy()) { + $dataProp = $this->phpExcel->getProperties()->getLastModifiedBy(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x08), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x1E), // null-terminated string prepended by dword string length + 'data' => array('data' => $dataProp, 'length' => strlen($dataProp))); + $dataSection_NumProps++; + } + // Created Date/Time + if ($this->phpExcel->getProperties()->getCreated()) { + $dataProp = $this->phpExcel->getProperties()->getCreated(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0C), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp))); + $dataSection_NumProps++; + } + // Modified Date/Time + if ($this->phpExcel->getProperties()->getModified()) { + $dataProp = $this->phpExcel->getProperties()->getModified(); + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x0D), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x40), // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + 'data' => array('data' => PHPExcel_Shared_OLE::LocalDate2OLE($dataProp))); + $dataSection_NumProps++; + } + // Security + $dataSection[] = array('summary'=> array('pack' => 'V', 'data' => 0x13), + 'offset' => array('pack' => 'V'), + 'type' => array('pack' => 'V', 'data' => 0x03), // 4 byte signed integer + 'data' => array('data' => 0x00)); + $dataSection_NumProps++; + + + // 4 Section Length + // 4 Property count + // 8 * $dataSection_NumProps (8 = ID (4) + OffSet(4)) + $dataSection_Content_Offset = 8 + $dataSection_NumProps * 8; + foreach ($dataSection as $dataProp) { + // Summary + $dataSection_Summary .= pack($dataProp['summary']['pack'], $dataProp['summary']['data']); + // Offset + $dataSection_Summary .= pack($dataProp['offset']['pack'], $dataSection_Content_Offset); + // DataType + $dataSection_Content .= pack($dataProp['type']['pack'], $dataProp['type']['data']); + // Data + if ($dataProp['type']['data'] == 0x02) { // 2 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } elseif ($dataProp['type']['data'] == 0x03) { // 4 byte signed integer + $dataSection_Content .= pack('V', $dataProp['data']['data']); + + $dataSection_Content_Offset += 4 + 4; + } elseif ($dataProp['type']['data'] == 0x1E) { // null-terminated string prepended by dword string length + // Null-terminated string + $dataProp['data']['data'] .= chr(0); + $dataProp['data']['length'] += 1; + // Complete the string with null string for being a %4 + $dataProp['data']['length'] = $dataProp['data']['length'] + ((4 - $dataProp['data']['length'] % 4)==4 ? 0 : (4 - $dataProp['data']['length'] % 4)); + $dataProp['data']['data'] = str_pad($dataProp['data']['data'], $dataProp['data']['length'], chr(0), STR_PAD_RIGHT); + + $dataSection_Content .= pack('V', $dataProp['data']['length']); + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 4 + strlen($dataProp['data']['data']); + } elseif ($dataProp['type']['data'] == 0x40) { // Filetime (64-bit value representing the number of 100-nanosecond intervals since January 1, 1601) + $dataSection_Content .= $dataProp['data']['data']; + + $dataSection_Content_Offset += 4 + 8; + } else { + // Data Type Not Used at the moment + } + } + // Now $dataSection_Content_Offset contains the size of the content + + // section header + // offset: $secOffset; size: 4; section length + // + x Size of the content (summary + content) + $data .= pack('V', $dataSection_Content_Offset); + // offset: $secOffset+4; size: 4; property count + $data .= pack('V', $dataSection_NumProps); + // Section Summary + $data .= $dataSection_Summary; + // Section Content + $data .= $dataSection_Content; + + return $data; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/BIFFwriter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/BIFFwriter.php new file mode 100644 index 00000000..a7957523 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/BIFFwriter.php @@ -0,0 +1,246 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_BIFFwriter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_BIFFwriter (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ +class PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * The byte order of this architecture. 0 => little endian, 1 => big endian + * @var integer + */ + private static $byteOrder; + + /** + * The string containing the data of the BIFF stream + * @var string + */ + public $_data; + + /** + * The size of the data in bytes. Should be the same as strlen($this->_data) + * @var integer + */ + public $_datasize; + + /** + * The maximum length for a BIFF record (excluding record header and length field). See addContinue() + * @var integer + * @see addContinue() + */ + private $limit = 8224; + + /** + * Constructor + */ + public function __construct() + { + $this->_data = ''; + $this->_datasize = 0; +// $this->limit = 8224; + } + + /** + * Determine the byte order and store it as class data to avoid + * recalculating it for each call to new(). + * + * @return int + */ + public static function getByteOrder() + { + if (!isset(self::$byteOrder)) { + // Check if "pack" gives the required IEEE 64bit float + $teststr = pack("d", 1.2345); + $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); + if ($number == $teststr) { + $byte_order = 0; // Little Endian + } elseif ($number == strrev($teststr)) { + $byte_order = 1; // Big Endian + } else { + // Give up. I'll fix this in a later version. + throw new PHPExcel_Writer_Exception("Required floating point format not supported on this platform."); + } + self::$byteOrder = $byte_order; + } + + return self::$byteOrder; + } + + /** + * General storage function + * + * @param string $data binary data to append + * @access private + */ + protected function append($data) + { + if (strlen($data) - 4 > $this->limit) { + $data = $this->addContinue($data); + } + $this->_data .= $data; + $this->_datasize += strlen($data); + } + + /** + * General storage function like append, but returns string instead of modifying $this->_data + * + * @param string $data binary data to write + * @return string + */ + public function writeData($data) + { + if (strlen($data) - 4 > $this->limit) { + $data = $this->addContinue($data); + } + $this->_datasize += strlen($data); + + return $data; + } + + /** + * Writes Excel BOF record to indicate the beginning of a stream or + * sub-stream in the BIFF file. + * + * @param integer $type Type of BIFF file to write: 0x0005 Workbook, + * 0x0010 Worksheet. + * @access private + */ + protected function storeBof($type) + { + $record = 0x0809; // Record identifier (BIFF5-BIFF8) + $length = 0x0010; + + // by inspection of real files, MS Office Excel 2007 writes the following + $unknown = pack("VV", 0x000100D1, 0x00000406); + + $build = 0x0DBB; // Excel 97 + $year = 0x07CC; // Excel 97 + + $version = 0x0600; // BIFF8 + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $version, $type, $build, $year); + $this->append($header . $data . $unknown); + } + + /** + * Writes Excel EOF record to indicate the end of a BIFF stream. + * + * @access private + */ + protected function storeEof() + { + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $this->append($header); + } + + /** + * Writes Excel EOF record to indicate the end of a BIFF stream. + * + * @access private + */ + public function writeEof() + { + $record = 0x000A; // Record identifier + $length = 0x0000; // Number of bytes to follow + $header = pack("vv", $record, $length); + return $this->writeData($header); + } + + /** + * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In + * Excel 97 the limit is 8228 bytes. Records that are longer than these limits + * must be split up into CONTINUE blocks. + * + * This function takes a long BIFF record and inserts CONTINUE records as + * necessary. + * + * @param string $data The original binary data to be written + * @return string A very convenient string of continue blocks + * @access private + */ + private function addContinue($data) + { + $limit = $this->limit; + $record = 0x003C; // Record identifier + + // The first 2080/8224 bytes remain intact. However, we have to change + // the length field of the record. + $tmp = substr($data, 0, 2) . pack("v", $limit) . substr($data, 4, $limit); + + $header = pack("vv", $record, $limit); // Headers for continue records + + // Retrieve chunks of 2080/8224 bytes +4 for the header. + $data_length = strlen($data); + for ($i = $limit + 4; $i < ($data_length - $limit); $i += $limit) { + $tmp .= $header; + $tmp .= substr($data, $i, $limit); + } + + // Retrieve the last chunk of data + $header = pack("vv", $record, strlen($data) - $i); + $tmp .= $header; + $tmp .= substr($data, $i, strlen($data) - $i); + + return $tmp; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Escher.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Escher.php new file mode 100644 index 00000000..c37fda9b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Escher.php @@ -0,0 +1,523 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Shared_Escher_DggContainer_BstoreContainer + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + */ +class PHPExcel_Writer_Excel5_Escher +{ + /** + * The object we are writing + */ + private $object; + + /** + * The written binary data + */ + private $data; + + /** + * Shape offsets. Positions in binary stream where a new shape record begins + * + * @var array + */ + private $spOffsets; + + /** + * Shape types. + * + * @var array + */ + private $spTypes; + + /** + * Constructor + * + * @param mixed + */ + public function __construct($object) + { + $this->object = $object; + } + + /** + * Process the object to be written + */ + public function close() + { + // initialize + $this->data = ''; + + switch (get_class($this->object)) { + case 'PHPExcel_Shared_Escher': + if ($dggContainer = $this->object->getDggContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($dggContainer); + $this->data = $writer->close(); + } elseif ($dgContainer = $this->object->getDgContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($dgContainer); + $this->data = $writer->close(); + $this->spOffsets = $writer->getSpOffsets(); + $this->spTypes = $writer->getSpTypes(); + } + break; + case 'PHPExcel_Shared_Escher_DggContainer': + // this is a container record + + // initialize + $innerData = ''; + + // write the dgg + $recVer = 0x0; + $recInstance = 0x0000; + $recType = 0xF006; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + // dgg data + $dggData = + pack( + 'VVVV', + $this->object->getSpIdMax(), // maximum shape identifier increased by one + $this->object->getCDgSaved() + 1, // number of file identifier clusters increased by one + $this->object->getCSpSaved(), + $this->object->getCDgSaved() // count total number of drawings saved + ); + + // add file identifier clusters (one per drawing) + $IDCLs = $this->object->getIDCLs(); + + foreach ($IDCLs as $dgId => $maxReducedSpId) { + $dggData .= pack('VV', $dgId, $maxReducedSpId + 1); + } + + $header = pack('vvV', $recVerInstance, $recType, strlen($dggData)); + $innerData .= $header . $dggData; + + // write the bstoreContainer + if ($bstoreContainer = $this->object->getBstoreContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($bstoreContainer); + $innerData .= $writer->close(); + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF000; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header . $innerData; + break; + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer': + // this is a container record + + // initialize + $innerData = ''; + + // treat the inner data + if ($BSECollection = $this->object->getBSECollection()) { + foreach ($BSECollection as $BSE) { + $writer = new PHPExcel_Writer_Excel5_Escher($BSE); + $innerData .= $writer->close(); + } + } + + // write the record + $recVer = 0xF; + $recInstance = count($this->object->getBSECollection()); + $recType = 0xF001; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header . $innerData; + break; + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE': + // this is a semi-container record + + // initialize + $innerData = ''; + + // here we treat the inner data + if ($blip = $this->object->getBlip()) { + $writer = new PHPExcel_Writer_Excel5_Escher($blip); + $innerData .= $writer->close(); + } + + // initialize + $data = ''; + + $btWin32 = $this->object->getBlipType(); + $btMacOS = $this->object->getBlipType(); + $data .= pack('CC', $btWin32, $btMacOS); + + $rgbUid = pack('VVVV', 0, 0, 0, 0); // todo + $data .= $rgbUid; + + $tag = 0; + $size = strlen($innerData); + $cRef = 1; + $foDelay = 0; //todo + $unused1 = 0x0; + $cbName = 0x0; + $unused2 = 0x0; + $unused3 = 0x0; + $data .= pack('vVVVCCCC', $tag, $size, $cRef, $foDelay, $unused1, $cbName, $unused2, $unused3); + + $data .= $innerData; + + // write the record + $recVer = 0x2; + $recInstance = $this->object->getBlipType(); + $recType = 0xF007; + $length = strlen($data); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header; + + $this->data .= $data; + break; + case 'PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE_Blip': + // this is an atom record + + // write the record + switch ($this->object->getParent()->getBlipType()) { + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_JPEG: + // initialize + $innerData = ''; + + $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo + $innerData .= $rgbUid1; + + $tag = 0xFF; // todo + $innerData .= pack('C', $tag); + + $innerData .= $this->object->getData(); + + $recVer = 0x0; + $recInstance = 0x46A; + $recType = 0xF01D; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header; + + $this->data .= $innerData; + break; + + case PHPExcel_Shared_Escher_DggContainer_BstoreContainer_BSE::BLIPTYPE_PNG: + // initialize + $innerData = ''; + + $rgbUid1 = pack('VVVV', 0, 0, 0, 0); // todo + $innerData .= $rgbUid1; + + $tag = 0xFF; // todo + $innerData .= pack('C', $tag); + + $innerData .= $this->object->getData(); + + $recVer = 0x0; + $recInstance = 0x6E0; + $recType = 0xF01E; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header; + + $this->data .= $innerData; + break; + } + break; + case 'PHPExcel_Shared_Escher_DgContainer': + // this is a container record + + // initialize + $innerData = ''; + + // write the dg + $recVer = 0x0; + $recInstance = $this->object->getDgId(); + $recType = 0xF008; + $length = 8; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + // number of shapes in this drawing (including group shape) + $countShapes = count($this->object->getSpgrContainer()->getChildren()); + $innerData .= $header . pack('VV', $countShapes, $this->object->getLastSpId()); + //$innerData .= $header . pack('VV', 0, 0); + + // write the spgrContainer + if ($spgrContainer = $this->object->getSpgrContainer()) { + $writer = new PHPExcel_Writer_Excel5_Escher($spgrContainer); + $innerData .= $writer->close(); + + // get the shape offsets relative to the spgrContainer record + $spOffsets = $writer->getSpOffsets(); + $spTypes = $writer->getSpTypes(); + + // save the shape offsets relative to dgContainer + foreach ($spOffsets as & $spOffset) { + $spOffset += 24; // add length of dgContainer header data (8 bytes) plus dg data (16 bytes) + } + + $this->spOffsets = $spOffsets; + $this->spTypes = $spTypes; + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF002; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header . $innerData; + break; + case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer': + // this is a container record + + // initialize + $innerData = ''; + + // initialize spape offsets + $totalSize = 8; + $spOffsets = array(); + $spTypes = array(); + + // treat the inner data + foreach ($this->object->getChildren() as $spContainer) { + $writer = new PHPExcel_Writer_Excel5_Escher($spContainer); + $spData = $writer->close(); + $innerData .= $spData; + + // save the shape offsets (where new shape records begin) + $totalSize += strlen($spData); + $spOffsets[] = $totalSize; + + $spTypes = array_merge($spTypes, $writer->getSpTypes()); + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF003; + $length = strlen($innerData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header . $innerData; + $this->spOffsets = $spOffsets; + $this->spTypes = $spTypes; + break; + case 'PHPExcel_Shared_Escher_DgContainer_SpgrContainer_SpContainer': + // initialize + $data = ''; + + // build the data + + // write group shape record, if necessary? + if ($this->object->getSpgr()) { + $recVer = 0x1; + $recInstance = 0x0000; + $recType = 0xF009; + $length = 0x00000010; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $data .= $header . pack('VVVV', 0, 0, 0, 0); + } + $this->spTypes[] = ($this->object->getSpType()); + + // write the shape record + $recVer = 0x2; + $recInstance = $this->object->getSpType(); // shape type + $recType = 0xF00A; + $length = 0x00000008; + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $data .= $header . pack('VV', $this->object->getSpId(), $this->object->getSpgr() ? 0x0005 : 0x0A00); + + + // the options + if ($this->object->getOPTCollection()) { + $optData = ''; + + $recVer = 0x3; + $recInstance = count($this->object->getOPTCollection()); + $recType = 0xF00B; + foreach ($this->object->getOPTCollection() as $property => $value) { + $optData .= pack('vV', $property, $value); + } + $length = strlen($optData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $optData; + } + + // the client anchor + if ($this->object->getStartCoordinates()) { + $clientAnchorData = ''; + + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF010; + + // start coordinates + list($column, $row) = PHPExcel_Cell::coordinateFromString($this->object->getStartCoordinates()); + $c1 = PHPExcel_Cell::columnIndexFromString($column) - 1; + $r1 = $row - 1; + + // start offsetX + $startOffsetX = $this->object->getStartOffsetX(); + + // start offsetY + $startOffsetY = $this->object->getStartOffsetY(); + + // end coordinates + list($column, $row) = PHPExcel_Cell::coordinateFromString($this->object->getEndCoordinates()); + $c2 = PHPExcel_Cell::columnIndexFromString($column) - 1; + $r2 = $row - 1; + + // end offsetX + $endOffsetX = $this->object->getEndOffsetX(); + + // end offsetY + $endOffsetY = $this->object->getEndOffsetY(); + + $clientAnchorData = pack('vvvvvvvvv', $this->object->getSpFlag(), $c1, $startOffsetX, $r1, $startOffsetY, $c2, $endOffsetX, $r2, $endOffsetY); + + $length = strlen($clientAnchorData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $clientAnchorData; + } + + // the client data, just empty for now + if (!$this->object->getSpgr()) { + $clientDataData = ''; + + $recVer = 0x0; + $recInstance = 0x0; + $recType = 0xF011; + + $length = strlen($clientDataData); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + $data .= $header . $clientDataData; + } + + // write the record + $recVer = 0xF; + $recInstance = 0x0000; + $recType = 0xF004; + $length = strlen($data); + + $recVerInstance = $recVer; + $recVerInstance |= $recInstance << 4; + + $header = pack('vvV', $recVerInstance, $recType, $length); + + $this->data = $header . $data; + break; + } + + return $this->data; + } + + /** + * Gets the shape offsets + * + * @return array + */ + public function getSpOffsets() + { + return $this->spOffsets; + } + + /** + * Gets the shape types + * + * @return array + */ + public function getSpTypes() + { + return $this->spTypes; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Font.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Font.php new file mode 100644 index 00000000..ed85ff45 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Font.php @@ -0,0 +1,166 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_Font + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Excel5_Font +{ + /** + * Color index + * + * @var int + */ + private $colorIndex; + + /** + * Font + * + * @var PHPExcel_Style_Font + */ + private $font; + + /** + * Constructor + * + * @param PHPExcel_Style_Font $font + */ + public function __construct(PHPExcel_Style_Font $font = null) + { + $this->colorIndex = 0x7FFF; + $this->font = $font; + } + + /** + * Set the color index + * + * @param int $colorIndex + */ + public function setColorIndex($colorIndex) + { + $this->colorIndex = $colorIndex; + } + + /** + * Get font record data + * + * @return string + */ + public function writeFont() + { + $font_outline = 0; + $font_shadow = 0; + + $icv = $this->colorIndex; // Index to color palette + if ($this->font->getSuperScript()) { + $sss = 1; + } elseif ($this->font->getSubScript()) { + $sss = 2; + } else { + $sss = 0; + } + $bFamily = 0; // Font family + $bCharSet = PHPExcel_Shared_Font::getCharsetFromFontName($this->font->getName()); // Character set + + $record = 0x31; // Record identifier + $reserved = 0x00; // Reserved + $grbit = 0x00; // Font attributes + if ($this->font->getItalic()) { + $grbit |= 0x02; + } + if ($this->font->getStrikethrough()) { + $grbit |= 0x08; + } + if ($font_outline) { + $grbit |= 0x10; + } + if ($font_shadow) { + $grbit |= 0x20; + } + + $data = pack( + "vvvvvCCCC", + // Fontsize (in twips) + $this->font->getSize() * 20, + $grbit, + // Colour + $icv, + // Font weight + self::mapBold($this->font->getBold()), + // Superscript/Subscript + $sss, + self::mapUnderline($this->font->getUnderline()), + $bFamily, + $bCharSet, + $reserved + ); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($this->font->getName()); + + $length = strlen($data); + $header = pack("vv", $record, $length); + + return($header . $data); + } + + /** + * Map to BIFF5-BIFF8 codes for bold + * + * @param boolean $bold + * @return int + */ + private static function mapBold($bold) + { + if ($bold) { + return 0x2BC; // 700 = Bold font weight + } + return 0x190; // 400 = Normal font weight + } + + /** + * Map of BIFF2-BIFF8 codes for underline styles + * @static array of int + * + */ + private static $mapUnderline = array( + PHPExcel_Style_Font::UNDERLINE_NONE => 0x00, + PHPExcel_Style_Font::UNDERLINE_SINGLE => 0x01, + PHPExcel_Style_Font::UNDERLINE_DOUBLE => 0x02, + PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING => 0x21, + PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING => 0x22, + ); + + /** + * Map underline + * + * @param string + * @return int + */ + private static function mapUnderline($underline) + { + if (isset(self::$mapUnderline[$underline])) { + return self::$mapUnderline[$underline]; + } + return 0x00; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Parser.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Parser.php new file mode 100644 index 00000000..0cf1c1d6 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Parser.php @@ -0,0 +1,1531 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_Parser + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// * Class for parsing Excel formulas +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ +class PHPExcel_Writer_Excel5_Parser +{ + /** Constants */ + // Sheet title in unquoted form + // Invalid sheet title characters cannot occur in the sheet title: + // *:/\?[] + // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?) + // +-% '^&<>=,;#()"{} + const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+'; + + // Sheet title in quoted form (without surrounding quotes) + // Invalid sheet title characters cannot occur in the sheet title: + // *:/\?[] (usual invalid sheet title characters) + // Single quote is represented as a pair '' + const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+'; + + /** + * The index of the character we are currently looking at + * @var integer + */ + public $currentCharacter; + + /** + * The token we are working on. + * @var string + */ + public $currentToken; + + /** + * The formula to parse + * @var string + */ + private $formula; + + /** + * The character ahead of the current char + * @var string + */ + public $lookAhead; + + /** + * The parse tree to be generated + * @var string + */ + private $parseTree; + + /** + * Array of external sheets + * @var array + */ + private $externalSheets; + + /** + * Array of sheet references in the form of REF structures + * @var array + */ + public $references; + + /** + * The class constructor + * + */ + public function __construct() + { + $this->currentCharacter = 0; + $this->currentToken = ''; // The token we are working on. + $this->formula = ''; // The formula to parse. + $this->lookAhead = ''; // The character ahead of the current char. + $this->parseTree = ''; // The parse tree to be generated. + $this->initializeHashes(); // Initialize the hashes: ptg's and function's ptg's + $this->externalSheets = array(); + $this->references = array(); + } + + /** + * Initialize the ptg and function hashes. + * + * @access private + */ + private function initializeHashes() + { + // The Excel ptg indices + $this->ptg = array( + 'ptgExp' => 0x01, + 'ptgTbl' => 0x02, + 'ptgAdd' => 0x03, + 'ptgSub' => 0x04, + 'ptgMul' => 0x05, + 'ptgDiv' => 0x06, + 'ptgPower' => 0x07, + 'ptgConcat' => 0x08, + 'ptgLT' => 0x09, + 'ptgLE' => 0x0A, + 'ptgEQ' => 0x0B, + 'ptgGE' => 0x0C, + 'ptgGT' => 0x0D, + 'ptgNE' => 0x0E, + 'ptgIsect' => 0x0F, + 'ptgUnion' => 0x10, + 'ptgRange' => 0x11, + 'ptgUplus' => 0x12, + 'ptgUminus' => 0x13, + 'ptgPercent' => 0x14, + 'ptgParen' => 0x15, + 'ptgMissArg' => 0x16, + 'ptgStr' => 0x17, + 'ptgAttr' => 0x19, + 'ptgSheet' => 0x1A, + 'ptgEndSheet' => 0x1B, + 'ptgErr' => 0x1C, + 'ptgBool' => 0x1D, + 'ptgInt' => 0x1E, + 'ptgNum' => 0x1F, + 'ptgArray' => 0x20, + 'ptgFunc' => 0x21, + 'ptgFuncVar' => 0x22, + 'ptgName' => 0x23, + 'ptgRef' => 0x24, + 'ptgArea' => 0x25, + 'ptgMemArea' => 0x26, + 'ptgMemErr' => 0x27, + 'ptgMemNoMem' => 0x28, + 'ptgMemFunc' => 0x29, + 'ptgRefErr' => 0x2A, + 'ptgAreaErr' => 0x2B, + 'ptgRefN' => 0x2C, + 'ptgAreaN' => 0x2D, + 'ptgMemAreaN' => 0x2E, + 'ptgMemNoMemN' => 0x2F, + 'ptgNameX' => 0x39, + 'ptgRef3d' => 0x3A, + 'ptgArea3d' => 0x3B, + 'ptgRefErr3d' => 0x3C, + 'ptgAreaErr3d' => 0x3D, + 'ptgArrayV' => 0x40, + 'ptgFuncV' => 0x41, + 'ptgFuncVarV' => 0x42, + 'ptgNameV' => 0x43, + 'ptgRefV' => 0x44, + 'ptgAreaV' => 0x45, + 'ptgMemAreaV' => 0x46, + 'ptgMemErrV' => 0x47, + 'ptgMemNoMemV' => 0x48, + 'ptgMemFuncV' => 0x49, + 'ptgRefErrV' => 0x4A, + 'ptgAreaErrV' => 0x4B, + 'ptgRefNV' => 0x4C, + 'ptgAreaNV' => 0x4D, + 'ptgMemAreaNV' => 0x4E, + 'ptgMemNoMemN' => 0x4F, + 'ptgFuncCEV' => 0x58, + 'ptgNameXV' => 0x59, + 'ptgRef3dV' => 0x5A, + 'ptgArea3dV' => 0x5B, + 'ptgRefErr3dV' => 0x5C, + 'ptgAreaErr3d' => 0x5D, + 'ptgArrayA' => 0x60, + 'ptgFuncA' => 0x61, + 'ptgFuncVarA' => 0x62, + 'ptgNameA' => 0x63, + 'ptgRefA' => 0x64, + 'ptgAreaA' => 0x65, + 'ptgMemAreaA' => 0x66, + 'ptgMemErrA' => 0x67, + 'ptgMemNoMemA' => 0x68, + 'ptgMemFuncA' => 0x69, + 'ptgRefErrA' => 0x6A, + 'ptgAreaErrA' => 0x6B, + 'ptgRefNA' => 0x6C, + 'ptgAreaNA' => 0x6D, + 'ptgMemAreaNA' => 0x6E, + 'ptgMemNoMemN' => 0x6F, + 'ptgFuncCEA' => 0x78, + 'ptgNameXA' => 0x79, + 'ptgRef3dA' => 0x7A, + 'ptgArea3dA' => 0x7B, + 'ptgRefErr3dA' => 0x7C, + 'ptgAreaErr3d' => 0x7D + ); + + // Thanks to Michael Meeks and Gnumeric for the initial arg values. + // + // The following hash was generated by "function_locale.pl" in the distro. + // Refer to function_locale.pl for non-English function names. + // + // The array elements are as follow: + // ptg: The Excel function ptg code. + // args: The number of arguments that the function takes: + // >=0 is a fixed number of arguments. + // -1 is a variable number of arguments. + // class: The reference, value or array class of the function args. + // vol: The function is volatile. + // + $this->functions = array( + // function ptg args class vol + 'COUNT' => array( 0, -1, 0, 0 ), + 'IF' => array( 1, -1, 1, 0 ), + 'ISNA' => array( 2, 1, 1, 0 ), + 'ISERROR' => array( 3, 1, 1, 0 ), + 'SUM' => array( 4, -1, 0, 0 ), + 'AVERAGE' => array( 5, -1, 0, 0 ), + 'MIN' => array( 6, -1, 0, 0 ), + 'MAX' => array( 7, -1, 0, 0 ), + 'ROW' => array( 8, -1, 0, 0 ), + 'COLUMN' => array( 9, -1, 0, 0 ), + 'NA' => array( 10, 0, 0, 0 ), + 'NPV' => array( 11, -1, 1, 0 ), + 'STDEV' => array( 12, -1, 0, 0 ), + 'DOLLAR' => array( 13, -1, 1, 0 ), + 'FIXED' => array( 14, -1, 1, 0 ), + 'SIN' => array( 15, 1, 1, 0 ), + 'COS' => array( 16, 1, 1, 0 ), + 'TAN' => array( 17, 1, 1, 0 ), + 'ATAN' => array( 18, 1, 1, 0 ), + 'PI' => array( 19, 0, 1, 0 ), + 'SQRT' => array( 20, 1, 1, 0 ), + 'EXP' => array( 21, 1, 1, 0 ), + 'LN' => array( 22, 1, 1, 0 ), + 'LOG10' => array( 23, 1, 1, 0 ), + 'ABS' => array( 24, 1, 1, 0 ), + 'INT' => array( 25, 1, 1, 0 ), + 'SIGN' => array( 26, 1, 1, 0 ), + 'ROUND' => array( 27, 2, 1, 0 ), + 'LOOKUP' => array( 28, -1, 0, 0 ), + 'INDEX' => array( 29, -1, 0, 1 ), + 'REPT' => array( 30, 2, 1, 0 ), + 'MID' => array( 31, 3, 1, 0 ), + 'LEN' => array( 32, 1, 1, 0 ), + 'VALUE' => array( 33, 1, 1, 0 ), + 'TRUE' => array( 34, 0, 1, 0 ), + 'FALSE' => array( 35, 0, 1, 0 ), + 'AND' => array( 36, -1, 0, 0 ), + 'OR' => array( 37, -1, 0, 0 ), + 'NOT' => array( 38, 1, 1, 0 ), + 'MOD' => array( 39, 2, 1, 0 ), + 'DCOUNT' => array( 40, 3, 0, 0 ), + 'DSUM' => array( 41, 3, 0, 0 ), + 'DAVERAGE' => array( 42, 3, 0, 0 ), + 'DMIN' => array( 43, 3, 0, 0 ), + 'DMAX' => array( 44, 3, 0, 0 ), + 'DSTDEV' => array( 45, 3, 0, 0 ), + 'VAR' => array( 46, -1, 0, 0 ), + 'DVAR' => array( 47, 3, 0, 0 ), + 'TEXT' => array( 48, 2, 1, 0 ), + 'LINEST' => array( 49, -1, 0, 0 ), + 'TREND' => array( 50, -1, 0, 0 ), + 'LOGEST' => array( 51, -1, 0, 0 ), + 'GROWTH' => array( 52, -1, 0, 0 ), + 'PV' => array( 56, -1, 1, 0 ), + 'FV' => array( 57, -1, 1, 0 ), + 'NPER' => array( 58, -1, 1, 0 ), + 'PMT' => array( 59, -1, 1, 0 ), + 'RATE' => array( 60, -1, 1, 0 ), + 'MIRR' => array( 61, 3, 0, 0 ), + 'IRR' => array( 62, -1, 0, 0 ), + 'RAND' => array( 63, 0, 1, 1 ), + 'MATCH' => array( 64, -1, 0, 0 ), + 'DATE' => array( 65, 3, 1, 0 ), + 'TIME' => array( 66, 3, 1, 0 ), + 'DAY' => array( 67, 1, 1, 0 ), + 'MONTH' => array( 68, 1, 1, 0 ), + 'YEAR' => array( 69, 1, 1, 0 ), + 'WEEKDAY' => array( 70, -1, 1, 0 ), + 'HOUR' => array( 71, 1, 1, 0 ), + 'MINUTE' => array( 72, 1, 1, 0 ), + 'SECOND' => array( 73, 1, 1, 0 ), + 'NOW' => array( 74, 0, 1, 1 ), + 'AREAS' => array( 75, 1, 0, 1 ), + 'ROWS' => array( 76, 1, 0, 1 ), + 'COLUMNS' => array( 77, 1, 0, 1 ), + 'OFFSET' => array( 78, -1, 0, 1 ), + 'SEARCH' => array( 82, -1, 1, 0 ), + 'TRANSPOSE' => array( 83, 1, 1, 0 ), + 'TYPE' => array( 86, 1, 1, 0 ), + 'ATAN2' => array( 97, 2, 1, 0 ), + 'ASIN' => array( 98, 1, 1, 0 ), + 'ACOS' => array( 99, 1, 1, 0 ), + 'CHOOSE' => array( 100, -1, 1, 0 ), + 'HLOOKUP' => array( 101, -1, 0, 0 ), + 'VLOOKUP' => array( 102, -1, 0, 0 ), + 'ISREF' => array( 105, 1, 0, 0 ), + 'LOG' => array( 109, -1, 1, 0 ), + 'CHAR' => array( 111, 1, 1, 0 ), + 'LOWER' => array( 112, 1, 1, 0 ), + 'UPPER' => array( 113, 1, 1, 0 ), + 'PROPER' => array( 114, 1, 1, 0 ), + 'LEFT' => array( 115, -1, 1, 0 ), + 'RIGHT' => array( 116, -1, 1, 0 ), + 'EXACT' => array( 117, 2, 1, 0 ), + 'TRIM' => array( 118, 1, 1, 0 ), + 'REPLACE' => array( 119, 4, 1, 0 ), + 'SUBSTITUTE' => array( 120, -1, 1, 0 ), + 'CODE' => array( 121, 1, 1, 0 ), + 'FIND' => array( 124, -1, 1, 0 ), + 'CELL' => array( 125, -1, 0, 1 ), + 'ISERR' => array( 126, 1, 1, 0 ), + 'ISTEXT' => array( 127, 1, 1, 0 ), + 'ISNUMBER' => array( 128, 1, 1, 0 ), + 'ISBLANK' => array( 129, 1, 1, 0 ), + 'T' => array( 130, 1, 0, 0 ), + 'N' => array( 131, 1, 0, 0 ), + 'DATEVALUE' => array( 140, 1, 1, 0 ), + 'TIMEVALUE' => array( 141, 1, 1, 0 ), + 'SLN' => array( 142, 3, 1, 0 ), + 'SYD' => array( 143, 4, 1, 0 ), + 'DDB' => array( 144, -1, 1, 0 ), + 'INDIRECT' => array( 148, -1, 1, 1 ), + 'CALL' => array( 150, -1, 1, 0 ), + 'CLEAN' => array( 162, 1, 1, 0 ), + 'MDETERM' => array( 163, 1, 2, 0 ), + 'MINVERSE' => array( 164, 1, 2, 0 ), + 'MMULT' => array( 165, 2, 2, 0 ), + 'IPMT' => array( 167, -1, 1, 0 ), + 'PPMT' => array( 168, -1, 1, 0 ), + 'COUNTA' => array( 169, -1, 0, 0 ), + 'PRODUCT' => array( 183, -1, 0, 0 ), + 'FACT' => array( 184, 1, 1, 0 ), + 'DPRODUCT' => array( 189, 3, 0, 0 ), + 'ISNONTEXT' => array( 190, 1, 1, 0 ), + 'STDEVP' => array( 193, -1, 0, 0 ), + 'VARP' => array( 194, -1, 0, 0 ), + 'DSTDEVP' => array( 195, 3, 0, 0 ), + 'DVARP' => array( 196, 3, 0, 0 ), + 'TRUNC' => array( 197, -1, 1, 0 ), + 'ISLOGICAL' => array( 198, 1, 1, 0 ), + 'DCOUNTA' => array( 199, 3, 0, 0 ), + 'USDOLLAR' => array( 204, -1, 1, 0 ), + 'FINDB' => array( 205, -1, 1, 0 ), + 'SEARCHB' => array( 206, -1, 1, 0 ), + 'REPLACEB' => array( 207, 4, 1, 0 ), + 'LEFTB' => array( 208, -1, 1, 0 ), + 'RIGHTB' => array( 209, -1, 1, 0 ), + 'MIDB' => array( 210, 3, 1, 0 ), + 'LENB' => array( 211, 1, 1, 0 ), + 'ROUNDUP' => array( 212, 2, 1, 0 ), + 'ROUNDDOWN' => array( 213, 2, 1, 0 ), + 'ASC' => array( 214, 1, 1, 0 ), + 'DBCS' => array( 215, 1, 1, 0 ), + 'RANK' => array( 216, -1, 0, 0 ), + 'ADDRESS' => array( 219, -1, 1, 0 ), + 'DAYS360' => array( 220, -1, 1, 0 ), + 'TODAY' => array( 221, 0, 1, 1 ), + 'VDB' => array( 222, -1, 1, 0 ), + 'MEDIAN' => array( 227, -1, 0, 0 ), + 'SUMPRODUCT' => array( 228, -1, 2, 0 ), + 'SINH' => array( 229, 1, 1, 0 ), + 'COSH' => array( 230, 1, 1, 0 ), + 'TANH' => array( 231, 1, 1, 0 ), + 'ASINH' => array( 232, 1, 1, 0 ), + 'ACOSH' => array( 233, 1, 1, 0 ), + 'ATANH' => array( 234, 1, 1, 0 ), + 'DGET' => array( 235, 3, 0, 0 ), + 'INFO' => array( 244, 1, 1, 1 ), + 'DB' => array( 247, -1, 1, 0 ), + 'FREQUENCY' => array( 252, 2, 0, 0 ), + 'ERROR.TYPE' => array( 261, 1, 1, 0 ), + 'REGISTER.ID' => array( 267, -1, 1, 0 ), + 'AVEDEV' => array( 269, -1, 0, 0 ), + 'BETADIST' => array( 270, -1, 1, 0 ), + 'GAMMALN' => array( 271, 1, 1, 0 ), + 'BETAINV' => array( 272, -1, 1, 0 ), + 'BINOMDIST' => array( 273, 4, 1, 0 ), + 'CHIDIST' => array( 274, 2, 1, 0 ), + 'CHIINV' => array( 275, 2, 1, 0 ), + 'COMBIN' => array( 276, 2, 1, 0 ), + 'CONFIDENCE' => array( 277, 3, 1, 0 ), + 'CRITBINOM' => array( 278, 3, 1, 0 ), + 'EVEN' => array( 279, 1, 1, 0 ), + 'EXPONDIST' => array( 280, 3, 1, 0 ), + 'FDIST' => array( 281, 3, 1, 0 ), + 'FINV' => array( 282, 3, 1, 0 ), + 'FISHER' => array( 283, 1, 1, 0 ), + 'FISHERINV' => array( 284, 1, 1, 0 ), + 'FLOOR' => array( 285, 2, 1, 0 ), + 'GAMMADIST' => array( 286, 4, 1, 0 ), + 'GAMMAINV' => array( 287, 3, 1, 0 ), + 'CEILING' => array( 288, 2, 1, 0 ), + 'HYPGEOMDIST' => array( 289, 4, 1, 0 ), + 'LOGNORMDIST' => array( 290, 3, 1, 0 ), + 'LOGINV' => array( 291, 3, 1, 0 ), + 'NEGBINOMDIST' => array( 292, 3, 1, 0 ), + 'NORMDIST' => array( 293, 4, 1, 0 ), + 'NORMSDIST' => array( 294, 1, 1, 0 ), + 'NORMINV' => array( 295, 3, 1, 0 ), + 'NORMSINV' => array( 296, 1, 1, 0 ), + 'STANDARDIZE' => array( 297, 3, 1, 0 ), + 'ODD' => array( 298, 1, 1, 0 ), + 'PERMUT' => array( 299, 2, 1, 0 ), + 'POISSON' => array( 300, 3, 1, 0 ), + 'TDIST' => array( 301, 3, 1, 0 ), + 'WEIBULL' => array( 302, 4, 1, 0 ), + 'SUMXMY2' => array( 303, 2, 2, 0 ), + 'SUMX2MY2' => array( 304, 2, 2, 0 ), + 'SUMX2PY2' => array( 305, 2, 2, 0 ), + 'CHITEST' => array( 306, 2, 2, 0 ), + 'CORREL' => array( 307, 2, 2, 0 ), + 'COVAR' => array( 308, 2, 2, 0 ), + 'FORECAST' => array( 309, 3, 2, 0 ), + 'FTEST' => array( 310, 2, 2, 0 ), + 'INTERCEPT' => array( 311, 2, 2, 0 ), + 'PEARSON' => array( 312, 2, 2, 0 ), + 'RSQ' => array( 313, 2, 2, 0 ), + 'STEYX' => array( 314, 2, 2, 0 ), + 'SLOPE' => array( 315, 2, 2, 0 ), + 'TTEST' => array( 316, 4, 2, 0 ), + 'PROB' => array( 317, -1, 2, 0 ), + 'DEVSQ' => array( 318, -1, 0, 0 ), + 'GEOMEAN' => array( 319, -1, 0, 0 ), + 'HARMEAN' => array( 320, -1, 0, 0 ), + 'SUMSQ' => array( 321, -1, 0, 0 ), + 'KURT' => array( 322, -1, 0, 0 ), + 'SKEW' => array( 323, -1, 0, 0 ), + 'ZTEST' => array( 324, -1, 0, 0 ), + 'LARGE' => array( 325, 2, 0, 0 ), + 'SMALL' => array( 326, 2, 0, 0 ), + 'QUARTILE' => array( 327, 2, 0, 0 ), + 'PERCENTILE' => array( 328, 2, 0, 0 ), + 'PERCENTRANK' => array( 329, -1, 0, 0 ), + 'MODE' => array( 330, -1, 2, 0 ), + 'TRIMMEAN' => array( 331, 2, 0, 0 ), + 'TINV' => array( 332, 2, 1, 0 ), + 'CONCATENATE' => array( 336, -1, 1, 0 ), + 'POWER' => array( 337, 2, 1, 0 ), + 'RADIANS' => array( 342, 1, 1, 0 ), + 'DEGREES' => array( 343, 1, 1, 0 ), + 'SUBTOTAL' => array( 344, -1, 0, 0 ), + 'SUMIF' => array( 345, -1, 0, 0 ), + 'COUNTIF' => array( 346, 2, 0, 0 ), + 'COUNTBLANK' => array( 347, 1, 0, 0 ), + 'ISPMT' => array( 350, 4, 1, 0 ), + 'DATEDIF' => array( 351, 3, 1, 0 ), + 'DATESTRING' => array( 352, 1, 1, 0 ), + 'NUMBERSTRING' => array( 353, 2, 1, 0 ), + 'ROMAN' => array( 354, -1, 1, 0 ), + 'GETPIVOTDATA' => array( 358, -1, 0, 0 ), + 'HYPERLINK' => array( 359, -1, 1, 0 ), + 'PHONETIC' => array( 360, 1, 0, 0 ), + 'AVERAGEA' => array( 361, -1, 0, 0 ), + 'MAXA' => array( 362, -1, 0, 0 ), + 'MINA' => array( 363, -1, 0, 0 ), + 'STDEVPA' => array( 364, -1, 0, 0 ), + 'VARPA' => array( 365, -1, 0, 0 ), + 'STDEVA' => array( 366, -1, 0, 0 ), + 'VARA' => array( 367, -1, 0, 0 ), + 'BAHTTEXT' => array( 368, 1, 0, 0 ), + ); + } + + /** + * Convert a token to the proper ptg value. + * + * @access private + * @param mixed $token The token to convert. + * @return mixed the converted token on success + */ + private function convert($token) + { + if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token)) { + return $this->convertString($token); + + } elseif (is_numeric($token)) { + return $this->convertNumber($token); + + // match references like A1 or $A$1 + } elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) { + return $this->convertRef2d($token); + + // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1 + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) { + return $this->convertRef3d($token); + + // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1 + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\d+)$/u", $token)) { + return $this->convertRef3d($token); + + // match ranges like A1:B2 or $A$1:$B$2 + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) { + return $this->convertRange2d($token); + + // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) { + return $this->convertRange3d($token); + + // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\d+)$/u", $token)) { + return $this->convertRange3d($token); + + // operators (including parentheses) + } elseif (isset($this->ptg[$token])) { + return pack("C", $this->ptg[$token]); + + // match error codes + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') { + return $this->convertError($token); + + // commented so argument number can be processed correctly. See toReversePolish(). + /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token)) + { + return($this->convertFunction($token, $this->_func_args)); + }*/ + + // if it's an argument, ignore the token (the argument remains) + } elseif ($token == 'arg') { + return ''; + } + + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown token $token"); + } + + /** + * Convert a number token to ptgInt or ptgNum + * + * @access private + * @param mixed $num an integer or double for conversion to its ptg value + */ + private function convertNumber($num) + { + // Integer in the range 0..2**16-1 + if ((preg_match("/^\d+$/", $num)) and ($num <= 65535)) { + return pack("Cv", $this->ptg['ptgInt'], $num); + } else { // A float + if (PHPExcel_Writer_Excel5_BIFFwriter::getByteOrder()) { // if it's Big Endian + $num = strrev($num); + } + return pack("Cd", $this->ptg['ptgNum'], $num); + } + } + + /** + * Convert a string token to ptgStr + * + * @access private + * @param string $string A string for conversion to its ptg value. + * @return mixed the converted token on success + */ + private function convertString($string) + { + // chop away beggining and ending quotes + $string = substr($string, 1, strlen($string) - 2); + if (strlen($string) > 255) { + throw new PHPExcel_Writer_Exception("String is too long"); + } + + return pack('C', $this->ptg['ptgStr']) . PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($string); + } + + /** + * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of + * args that it takes. + * + * @access private + * @param string $token The name of the function for convertion to ptg value. + * @param integer $num_args The number of arguments the function receives. + * @return string The packed ptg for the function + */ + private function convertFunction($token, $num_args) + { + $args = $this->functions[$token][1]; +// $volatile = $this->functions[$token][3]; + + // Fixed number of args eg. TIME($i, $j, $k). + if ($args >= 0) { + return pack("Cv", $this->ptg['ptgFuncV'], $this->functions[$token][0]); + } + // Variable number of args eg. SUM($i, $j, $k, ..). + if ($args == -1) { + return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]); + } + } + + /** + * Convert an Excel range such as A1:D4 to a ptgRefV. + * + * @access private + * @param string $range An Excel range in the A1:A2 + * @param int $class + */ + private function convertRange2d($range, $class = 0) + { + + // TODO: possible class value 0,1,2 check Formula.pm + // Split the range into 2 cell refs + if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) { + list($cell1, $cell2) = explode(':', $range); + } else { + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown range separator"); + } + + // Convert the cell references + list($row1, $col1) = $this->cellToPackedRowcol($cell1); + list($row2, $col2) = $this->cellToPackedRowcol($cell2); + + // The ptg value depends on the class of the ptg. + if ($class == 0) { + $ptgArea = pack("C", $this->ptg['ptgArea']); + } elseif ($class == 1) { + $ptgArea = pack("C", $this->ptg['ptgAreaV']); + } elseif ($class == 2) { + $ptgArea = pack("C", $this->ptg['ptgAreaA']); + } else { + // TODO: use real error codes + throw new PHPExcel_Writer_Exception("Unknown class $class"); + } + return $ptgArea . $row1 . $row2 . $col1. $col2; + } + + /** + * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to + * a ptgArea3d. + * + * @access private + * @param string $token An Excel range in the Sheet1!A1:A2 format. + * @return mixed The packed ptgArea3d token on success. + */ + private function convertRange3d($token) + { +// $class = 0; // formulas like Sheet1!$A$1:$A$2 in list type data validation need this class (0x3B) + + // Split the ref at the ! symbol + list($ext_ref, $range) = explode('!', $token); + + // Convert the external reference part (different for BIFF8) + $ext_ref = $this->getRefIndex($ext_ref); + + // Split the range into 2 cell refs + list($cell1, $cell2) = explode(':', $range); + + // Convert the cell references + if (preg_match("/^(\\$)?[A-Ia-i]?[A-Za-z](\\$)?(\d+)$/", $cell1)) { + list($row1, $col1) = $this->cellToPackedRowcol($cell1); + list($row2, $col2) = $this->cellToPackedRowcol($cell2); + } else { // It's a rows range (like 26:27) + list($row1, $col1, $row2, $col2) = $this->rangeToPackedRange($cell1.':'.$cell2); + } + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { + $ptgArea = pack("C", $this->ptg['ptgArea3d']); +// } elseif ($class == 1) { +// $ptgArea = pack("C", $this->ptg['ptgArea3dV']); +// } elseif ($class == 2) { +// $ptgArea = pack("C", $this->ptg['ptgArea3dA']); +// } else { +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + + return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2; + } + + /** + * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. + * + * @access private + * @param string $cell An Excel cell reference + * @return string The cell in packed() format with the corresponding ptg + */ + private function convertRef2d($cell) + { +// $class = 2; // as far as I know, this is magick. + + // Convert the cell reference + $cell_array = $this->cellToPackedRowcol($cell); + list($row, $col) = $cell_array; + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { +// $ptgRef = pack("C", $this->ptg['ptgRef']); +// } elseif ($class == 1) { +// $ptgRef = pack("C", $this->ptg['ptgRefV']); +// } elseif ($class == 2) { + $ptgRef = pack("C", $this->ptg['ptgRefA']); +// } else { +// // TODO: use real error codes +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + return $ptgRef.$row.$col; + } + + /** + * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a + * ptgRef3d. + * + * @access private + * @param string $cell An Excel cell reference + * @return mixed The packed ptgRef3d token on success. + */ + private function convertRef3d($cell) + { +// $class = 2; // as far as I know, this is magick. + + // Split the ref at the ! symbol + list($ext_ref, $cell) = explode('!', $cell); + + // Convert the external reference part (different for BIFF8) + $ext_ref = $this->getRefIndex($ext_ref); + + // Convert the cell reference part + list($row, $col) = $this->cellToPackedRowcol($cell); + + // The ptg value depends on the class of the ptg. +// if ($class == 0) { +// $ptgRef = pack("C", $this->ptg['ptgRef3d']); +// } elseif ($class == 1) { +// $ptgRef = pack("C", $this->ptg['ptgRef3dV']); +// } elseif ($class == 2) { + $ptgRef = pack("C", $this->ptg['ptgRef3dA']); +// } else { +// throw new PHPExcel_Writer_Exception("Unknown class $class"); +// } + + return $ptgRef . $ext_ref. $row . $col; + } + + /** + * Convert an error code to a ptgErr + * + * @access private + * @param string $errorCode The error code for conversion to its ptg value + * @return string The error code ptgErr + */ + private function convertError($errorCode) + { + switch ($errorCode) { + case '#NULL!': + return pack("C", 0x00); + case '#DIV/0!': + return pack("C", 0x07); + case '#VALUE!': + return pack("C", 0x0F); + case '#REF!': + return pack("C", 0x17); + case '#NAME?': + return pack("C", 0x1D); + case '#NUM!': + return pack("C", 0x24); + case '#N/A': + return pack("C", 0x2A); + } + return pack("C", 0xFF); + } + + /** + * Convert the sheet name part of an external reference, for example "Sheet1" or + * "Sheet1:Sheet2", to a packed structure. + * + * @access private + * @param string $ext_ref The name of the external reference + * @return string The reference index in packed() format + */ + private function packExtRef($ext_ref) + { + $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. + $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + + // Check if there is a sheet range eg., Sheet1:Sheet2. + if (preg_match("/:/", $ext_ref)) { + list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); + + $sheet1 = $this->getSheetIndex($sheet_name1); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula"); + } + $sheet2 = $this->getSheetIndex($sheet_name2); + if ($sheet2 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula"); + } + + // Reverse max and min sheet numbers if necessary + if ($sheet1 > $sheet2) { + list($sheet1, $sheet2) = array($sheet2, $sheet1); + } + } else { // Single sheet name only. + $sheet1 = $this->getSheetIndex($ext_ref); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula"); + } + $sheet2 = $sheet1; + } + + // References are stored relative to 0xFFFF. + $offset = -1 - $sheet1; + + return pack('vdvv', $offset, 0x00, $sheet1, $sheet2); + } + + /** + * Look up the REF index that corresponds to an external sheet name + * (or range). If it doesn't exist yet add it to the workbook's references + * array. It assumes all sheet names given must exist. + * + * @access private + * @param string $ext_ref The name of the external reference + * @return mixed The reference index in packed() format on success + */ + private function getRefIndex($ext_ref) + { + $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. + $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. + $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with ' + + // Check if there is a sheet range eg., Sheet1:Sheet2. + if (preg_match("/:/", $ext_ref)) { + list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); + + $sheet1 = $this->getSheetIndex($sheet_name1); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name1 in formula"); + } + $sheet2 = $this->getSheetIndex($sheet_name2); + if ($sheet2 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $sheet_name2 in formula"); + } + + // Reverse max and min sheet numbers if necessary + if ($sheet1 > $sheet2) { + list($sheet1, $sheet2) = array($sheet2, $sheet1); + } + } else { // Single sheet name only. + $sheet1 = $this->getSheetIndex($ext_ref); + if ($sheet1 == -1) { + throw new PHPExcel_Writer_Exception("Unknown sheet name $ext_ref in formula"); + } + $sheet2 = $sheet1; + } + + // assume all references belong to this document + $supbook_index = 0x00; + $ref = pack('vvv', $supbook_index, $sheet1, $sheet2); + $totalreferences = count($this->references); + $index = -1; + for ($i = 0; $i < $totalreferences; ++$i) { + if ($ref == $this->references[$i]) { + $index = $i; + break; + } + } + // if REF was not found add it to references array + if ($index == -1) { + $this->references[$totalreferences] = $ref; + $index = $totalreferences; + } + + return pack('v', $index); + } + + /** + * Look up the index that corresponds to an external sheet name. The hash of + * sheet names is updated by the addworksheet() method of the + * PHPExcel_Writer_Excel5_Workbook class. + * + * @access private + * @param string $sheet_name Sheet name + * @return integer The sheet index, -1 if the sheet was not found + */ + private function getSheetIndex($sheet_name) + { + if (!isset($this->externalSheets[$sheet_name])) { + return -1; + } else { + return $this->externalSheets[$sheet_name]; + } + } + + /** + * This method is used to update the array of sheet names. It is + * called by the addWorksheet() method of the + * PHPExcel_Writer_Excel5_Workbook class. + * + * @access public + * @see PHPExcel_Writer_Excel5_Workbook::addWorksheet() + * @param string $name The name of the worksheet being added + * @param integer $index The index of the worksheet being added + */ + public function setExtSheet($name, $index) + { + $this->externalSheets[$name] = $index; + } + + /** + * pack() row and column into the required 3 or 4 byte format. + * + * @access private + * @param string $cell The Excel cell reference to be packed + * @return array Array containing the row and column in packed() format + */ + private function cellToPackedRowcol($cell) + { + $cell = strtoupper($cell); + list($row, $col, $row_rel, $col_rel) = $this->cellToRowcol($cell); + if ($col >= 256) { + throw new PHPExcel_Writer_Exception("Column in: $cell greater than 255"); + } + if ($row >= 65536) { + throw new PHPExcel_Writer_Exception("Row in: $cell greater than 65536 "); + } + + // Set the high bits to indicate if row or col are relative. + $col |= $col_rel << 14; + $col |= $row_rel << 15; + $col = pack('v', $col); + + $row = pack('v', $row); + + return array($row, $col); + } + + /** + * pack() row range into the required 3 or 4 byte format. + * Just using maximum col/rows, which is probably not the correct solution + * + * @access private + * @param string $range The Excel range to be packed + * @return array Array containing (row1,col1,row2,col2) in packed() format + */ + private function rangeToPackedRange($range) + { + preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); + // return absolute rows if there is a $ in the ref + $row1_rel = empty($match[1]) ? 1 : 0; + $row1 = $match[2]; + $row2_rel = empty($match[3]) ? 1 : 0; + $row2 = $match[4]; + // Convert 1-index to zero-index + --$row1; + --$row2; + // Trick poor inocent Excel + $col1 = 0; + $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!) + + // FIXME: this changes for BIFF8 + if (($row1 >= 65536) or ($row2 >= 65536)) { + throw new PHPExcel_Writer_Exception("Row in: $range greater than 65536 "); + } + + // Set the high bits to indicate if rows are relative. + $col1 |= $row1_rel << 15; + $col2 |= $row2_rel << 15; + $col1 = pack('v', $col1); + $col2 = pack('v', $col2); + + $row1 = pack('v', $row1); + $row2 = pack('v', $row2); + + return array($row1, $col1, $row2, $col2); + } + + /** + * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero + * indexed row and column number. Also returns two (0,1) values to indicate + * whether the row or column are relative references. + * + * @access private + * @param string $cell The Excel cell reference in A1 format. + * @return array + */ + private function cellToRowcol($cell) + { + preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match); + // return absolute column if there is a $ in the ref + $col_rel = empty($match[1]) ? 1 : 0; + $col_ref = $match[2]; + $row_rel = empty($match[3]) ? 1 : 0; + $row = $match[4]; + + // Convert base26 column string to a number. + $expn = strlen($col_ref) - 1; + $col = 0; + $col_ref_length = strlen($col_ref); + for ($i = 0; $i < $col_ref_length; ++$i) { + $col += (ord($col_ref{$i}) - 64) * pow(26, $expn); + --$expn; + } + + // Convert 1-index to zero-index + --$row; + --$col; + + return array($row, $col, $row_rel, $col_rel); + } + + /** + * Advance to the next valid token. + * + * @access private + */ + private function advance() + { + $i = $this->currentCharacter; + $formula_length = strlen($this->formula); + // eat up white spaces + if ($i < $formula_length) { + while ($this->formula{$i} == " ") { + ++$i; + } + + if ($i < ($formula_length - 1)) { + $this->lookAhead = $this->formula{$i+1}; + } + $token = ''; + } + + while ($i < $formula_length) { + $token .= $this->formula{$i}; + + if ($i < ($formula_length - 1)) { + $this->lookAhead = $this->formula{$i+1}; + } else { + $this->lookAhead = ''; + } + + if ($this->match($token) != '') { + //if ($i < strlen($this->formula) - 1) { + // $this->lookAhead = $this->formula{$i+1}; + //} + $this->currentCharacter = $i + 1; + $this->currentToken = $token; + return 1; + } + + if ($i < ($formula_length - 2)) { + $this->lookAhead = $this->formula{$i+2}; + } else { // if we run out of characters lookAhead becomes empty + $this->lookAhead = ''; + } + ++$i; + } + //die("Lexical error ".$this->currentCharacter); + } + + /** + * Checks if it's a valid token. + * + * @access private + * @param mixed $token The token to check. + * @return mixed The checked token or false on failure + */ + private function match($token) + { + switch ($token) { + case "+": + case "-": + case "*": + case "/": + case "(": + case ")": + case ",": + case ";": + case ">=": + case "<=": + case "=": + case "<>": + case "^": + case "&": + case "%": + return $token; + break; + case ">": + if ($this->lookAhead == '=') { // it's a GE token + break; + } + return $token; + break; + case "<": + // it's a LE or a NE token + if (($this->lookAhead == '=') or ($this->lookAhead == '>')) { + break; + } + return $token; + break; + default: + // if it's a reference A1 or $A$1 or $A1 or A$1 + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.') and ($this->lookAhead != '!')) { + return $token; + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { + // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) + return $token; + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead) and ($this->lookAhead != ':') and ($this->lookAhead != '.')) { + // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) + return $token; + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $token) && !preg_match("/[0-9]/", $this->lookAhead)) { + // if it's a range A1:A2 or $A$1:$A$2 + return $token; + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) { + // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2 + return $token; + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $token) and !preg_match("/[0-9]/", $this->lookAhead)) { + // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2 + return $token; + } elseif (is_numeric($token) and (!is_numeric($token.$this->lookAhead) or ($this->lookAhead == '')) and ($this->lookAhead != '!') and ($this->lookAhead != ':')) { + // If it's a number (check that it's not a sheet name or range) + return $token; + } elseif (preg_match("/\"([^\"]|\"\"){0,255}\"/", $token) and $this->lookAhead != '"' and (substr_count($token, '"')%2 == 0)) { + // If it's a string (of maximum 255 characters) + return $token; + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $token) or $token == '#N/A') { + // If it's an error code + return $token; + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $token) and ($this->lookAhead == "(")) { + // if it's a function call + return $token; + } elseif (substr($token, -1) == ')') { + // It's an argument of some description (e.g. a named range), + // precise nature yet to be determined + return $token; + } + return ''; + } + } + + /** + * The parsing method. It parses a formula. + * + * @access public + * @param string $formula The formula to parse, without the initial equal + * sign (=). + * @return mixed true on success + */ + public function parse($formula) + { + $this->currentCharacter = 0; + $this->formula = $formula; + $this->lookAhead = isset($formula{1}) ? $formula{1} : ''; + $this->advance(); + $this->parseTree = $this->condition(); + return true; + } + + /** + * It parses a condition. It assumes the following rule: + * Cond -> Expr [(">" | "<") Expr] + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + private function condition() + { + $result = $this->expression(); + if ($this->currentToken == "<") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgLT', $result, $result2); + } elseif ($this->currentToken == ">") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgGT', $result, $result2); + } elseif ($this->currentToken == "<=") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgLE', $result, $result2); + } elseif ($this->currentToken == ">=") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgGE', $result, $result2); + } elseif ($this->currentToken == "=") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgEQ', $result, $result2); + } elseif ($this->currentToken == "<>") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgNE', $result, $result2); + } elseif ($this->currentToken == "&") { + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgConcat', $result, $result2); + } + return $result; + } + + /** + * It parses a expression. It assumes the following rule: + * Expr -> Term [("+" | "-") Term] + * -> "string" + * -> "-" Term : Negative value + * -> "+" Term : Positive value + * -> Error code + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + private function expression() + { + // If it's a string return a string node + if (preg_match("/\"([^\"]|\"\"){0,255}\"/", $this->currentToken)) { + $tmp = str_replace('""', '"', $this->currentToken); + if (($tmp == '"') || ($tmp == '')) { + // Trap for "" that has been used for an empty string + $tmp = '""'; + } + $result = $this->createTree($tmp, '', ''); + $this->advance(); + return $result; + // If it's an error code + } elseif (preg_match("/^#[A-Z0\/]{3,5}[!?]{1}$/", $this->currentToken) or $this->currentToken == '#N/A') { + $result = $this->createTree($this->currentToken, 'ptgErr', ''); + $this->advance(); + return $result; + // If it's a negative value + } elseif ($this->currentToken == "-") { + // catch "-" Term + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgUminus', $result2, ''); + return $result; + // If it's a positive value + } elseif ($this->currentToken == "+") { + // catch "+" Term + $this->advance(); + $result2 = $this->expression(); + $result = $this->createTree('ptgUplus', $result2, ''); + return $result; + } + $result = $this->term(); + while (($this->currentToken == "+") or + ($this->currentToken == "-") or + ($this->currentToken == "^")) { + /**/ + if ($this->currentToken == "+") { + $this->advance(); + $result2 = $this->term(); + $result = $this->createTree('ptgAdd', $result, $result2); + } elseif ($this->currentToken == "-") { + $this->advance(); + $result2 = $this->term(); + $result = $this->createTree('ptgSub', $result, $result2); + } else { + $this->advance(); + $result2 = $this->term(); + $result = $this->createTree('ptgPower', $result, $result2); + } + } + return $result; + } + + /** + * This function just introduces a ptgParen element in the tree, so that Excel + * doesn't get confused when working with a parenthesized formula afterwards. + * + * @access private + * @see fact() + * @return array The parsed ptg'd tree + */ + private function parenthesizedExpression() + { + $result = $this->createTree('ptgParen', $this->expression(), ''); + return $result; + } + + /** + * It parses a term. It assumes the following rule: + * Term -> Fact [("*" | "/") Fact] + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + private function term() + { + $result = $this->fact(); + while (($this->currentToken == "*") or + ($this->currentToken == "/")) { + /**/ + if ($this->currentToken == "*") { + $this->advance(); + $result2 = $this->fact(); + $result = $this->createTree('ptgMul', $result, $result2); + } else { + $this->advance(); + $result2 = $this->fact(); + $result = $this->createTree('ptgDiv', $result, $result2); + } + } + return $result; + } + + /** + * It parses a factor. It assumes the following rule: + * Fact -> ( Expr ) + * | CellRef + * | CellRange + * | Number + * | Function + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + private function fact() + { + if ($this->currentToken == "(") { + $this->advance(); // eat the "(" + $result = $this->parenthesizedExpression(); + if ($this->currentToken != ")") { + throw new PHPExcel_Writer_Exception("')' token expected."); + } + $this->advance(); // eat the ")" + return $result; + } + // if it's a reference + if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/', $this->currentToken)) { + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) { + // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1) + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?[A-Ia-i]?[A-Za-z]\\$?[0-9]+$/u", $this->currentToken)) { + // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1) + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken) or + preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/', $this->currentToken)) { + // if it's a range A1:B2 or $A$1:$B$2 + // must be an error? + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (preg_match("/^" . self::REGEX_SHEET_TITLE_UNQUOTED . "(\:" . self::REGEX_SHEET_TITLE_UNQUOTED . ")?\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) { + // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2) + // must be an error? + //$result = $this->currentToken; + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . "(\:" . self::REGEX_SHEET_TITLE_QUOTED . ")?'\!\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+:\\$?([A-Ia-i]?[A-Za-z])?\\$?[0-9]+$/u", $this->currentToken)) { + // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2) + // must be an error? + //$result = $this->currentToken; + $result = $this->createTree($this->currentToken, '', ''); + $this->advance(); + return $result; + } elseif (is_numeric($this->currentToken)) { + // If it's a number or a percent + if ($this->lookAhead == '%') { + $result = $this->createTree('ptgPercent', $this->currentToken, ''); + $this->advance(); // Skip the percentage operator once we've pre-built that tree + } else { + $result = $this->createTree($this->currentToken, '', ''); + } + $this->advance(); + return $result; + } elseif (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/i", $this->currentToken)) { + // if it's a function call + $result = $this->func(); + return $result; + } + throw new PHPExcel_Writer_Exception("Syntax error: ".$this->currentToken.", lookahead: ".$this->lookAhead.", current char: ".$this->currentCharacter); + } + + /** + * It parses a function call. It assumes the following rule: + * Func -> ( Expr [,Expr]* ) + * + * @access private + * @return mixed The parsed ptg'd tree on success + */ + private function func() + { + $num_args = 0; // number of arguments received + $function = strtoupper($this->currentToken); + $result = ''; // initialize result + $this->advance(); + $this->advance(); // eat the "(" + while ($this->currentToken != ')') { + /**/ + if ($num_args > 0) { + if ($this->currentToken == "," || $this->currentToken == ";") { + $this->advance(); // eat the "," or ";" + } else { + throw new PHPExcel_Writer_Exception("Syntax error: comma expected in function $function, arg #{$num_args}"); + } + $result2 = $this->condition(); + $result = $this->createTree('arg', $result, $result2); + } else { // first argument + $result2 = $this->condition(); + $result = $this->createTree('arg', '', $result2); + } + ++$num_args; + } + if (!isset($this->functions[$function])) { + throw new PHPExcel_Writer_Exception("Function $function() doesn't exist"); + } + $args = $this->functions[$function][1]; + // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid. + if (($args >= 0) and ($args != $num_args)) { + throw new PHPExcel_Writer_Exception("Incorrect number of arguments in function $function() "); + } + + $result = $this->createTree($function, $result, $num_args); + $this->advance(); // eat the ")" + return $result; + } + + /** + * Creates a tree. In fact an array which may have one or two arrays (sub-trees) + * as elements. + * + * @access private + * @param mixed $value The value of this node. + * @param mixed $left The left array (sub-tree) or a final node. + * @param mixed $right The right array (sub-tree) or a final node. + * @return array A tree + */ + private function createTree($value, $left, $right) + { + return array('value' => $value, 'left' => $left, 'right' => $right); + } + + /** + * Builds a string containing the tree in reverse polish notation (What you + * would use in a HP calculator stack). + * The following tree: + * + * + + * / \ + * 2 3 + * + * produces: "23+" + * + * The following tree: + * + * + + * / \ + * 3 * + * / \ + * 6 A1 + * + * produces: "36A1*+" + * + * In fact all operands, functions, references, etc... are written as ptg's + * + * @access public + * @param array $tree The optional tree to convert. + * @return string The tree in reverse polish notation + */ + public function toReversePolish($tree = array()) + { + $polish = ""; // the string we are going to return + if (empty($tree)) { // If it's the first call use parseTree + $tree = $this->parseTree; + } + + if (is_array($tree['left'])) { + $converted_tree = $this->toReversePolish($tree['left']); + $polish .= $converted_tree; + } elseif ($tree['left'] != '') { // It's a final node + $converted_tree = $this->convert($tree['left']); + $polish .= $converted_tree; + } + if (is_array($tree['right'])) { + $converted_tree = $this->toReversePolish($tree['right']); + $polish .= $converted_tree; + } elseif ($tree['right'] != '') { // It's a final node + $converted_tree = $this->convert($tree['right']); + $polish .= $converted_tree; + } + // if it's a function convert it here (so we can set it's arguments) + if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/", $tree['value']) and + !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) and + !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/", $tree['value']) and + !is_numeric($tree['value']) and + !isset($this->ptg[$tree['value']])) { + // left subtree for a function is always an array. + if ($tree['left'] != '') { + $left_tree = $this->toReversePolish($tree['left']); + } else { + $left_tree = ''; + } + // add it's left subtree and return. + return $left_tree.$this->convertFunction($tree['value'], $tree['right']); + } else { + $converted_tree = $this->convert($tree['value']); + } + $polish .= $converted_tree; + return $polish; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Workbook.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Workbook.php new file mode 100644 index 00000000..8b068437 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Workbook.php @@ -0,0 +1,1444 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_Workbook + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Workbook (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ +class PHPExcel_Writer_Excel5_Workbook extends PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $parser; + + /** + * The BIFF file size for the workbook. + * @var integer + * @see calcSheetOffsets() + */ + private $biffSize; + + /** + * XF Writers + * @var PHPExcel_Writer_Excel5_Xf[] + */ + private $xfWriters = array(); + + /** + * Array containing the colour palette + * @var array + */ + private $palette; + + /** + * The codepage indicates the text encoding used for strings + * @var integer + */ + private $codepage; + + /** + * The country code used for localization + * @var integer + */ + private $countryCode; + + /** + * Workbook + * @var PHPExcel + */ + private $phpExcel; + + /** + * Fonts writers + * + * @var PHPExcel_Writer_Excel5_Font[] + */ + private $fontWriters = array(); + + /** + * Added fonts. Maps from font's hash => index in workbook + * + * @var array + */ + private $addedFonts = array(); + + /** + * Shared number formats + * + * @var array + */ + private $numberFormats = array(); + + /** + * Added number formats. Maps from numberFormat's hash => index in workbook + * + * @var array + */ + private $addedNumberFormats = array(); + + /** + * Sizes of the binary worksheet streams + * + * @var array + */ + private $worksheetSizes = array(); + + /** + * Offsets of the binary worksheet streams relative to the start of the global workbook stream + * + * @var array + */ + private $worksheetOffsets = array(); + + /** + * Total number of shared strings in workbook + * + * @var int + */ + private $stringTotal; + + /** + * Number of unique shared strings in workbook + * + * @var int + */ + private $stringUnique; + + /** + * Array of unique shared strings in workbook + * + * @var array + */ + private $stringTable; + + /** + * Color cache + */ + private $colors; + + /** + * Escher object corresponding to MSODRAWINGGROUP + * + * @var PHPExcel_Shared_Escher + */ + private $escher; + + + /** + * Class constructor + * + * @param PHPExcel $phpExcel The Workbook + * @param int &$str_total Total number of strings + * @param int &$str_unique Total number of unique strings + * @param array &$str_table String Table + * @param array &$colors Colour Table + * @param mixed $parser The formula parser created for the Workbook + */ + public function __construct(PHPExcel $phpExcel = null, &$str_total, &$str_unique, &$str_table, &$colors, $parser) + { + // It needs to call its parent's constructor explicitly + parent::__construct(); + + $this->parser = $parser; + $this->biffSize = 0; + $this->palette = array(); + $this->countryCode = -1; + + $this->stringTotal = &$str_total; + $this->stringUnique = &$str_unique; + $this->stringTable = &$str_table; + $this->colors = &$colors; + $this->setPaletteXl97(); + + $this->phpExcel = $phpExcel; + + // set BIFFwriter limit for CONTINUE records + // $this->_limit = 8224; + $this->codepage = 0x04B0; + + // Add empty sheets and Build color cache + $countSheets = $phpExcel->getSheetCount(); + for ($i = 0; $i < $countSheets; ++$i) { + $phpSheet = $phpExcel->getSheet($i); + + $this->parser->setExtSheet($phpSheet->getTitle(), $i); // Register worksheet name with parser + + $supbook_index = 0x00; + $ref = pack('vvv', $supbook_index, $i, $i); + $this->parser->references[] = $ref; // Register reference with parser + + // Sheet tab colors? + if ($phpSheet->isTabColorSet()) { + $this->addColor($phpSheet->getTabColor()->getRGB()); + } + } + + } + + /** + * Add a new XF writer + * + * @param PHPExcel_Style + * @param boolean Is it a style XF? + * @return int Index to XF record + */ + public function addXfWriter($style, $isStyleXf = false) + { + $xfWriter = new PHPExcel_Writer_Excel5_Xf($style); + $xfWriter->setIsStyleXf($isStyleXf); + + // Add the font if not already added + $fontIndex = $this->addFont($style->getFont()); + + // Assign the font index to the xf record + $xfWriter->setFontIndex($fontIndex); + + // Background colors, best to treat these after the font so black will come after white in custom palette + $xfWriter->setFgColor($this->addColor($style->getFill()->getStartColor()->getRGB())); + $xfWriter->setBgColor($this->addColor($style->getFill()->getEndColor()->getRGB())); + $xfWriter->setBottomColor($this->addColor($style->getBorders()->getBottom()->getColor()->getRGB())); + $xfWriter->setTopColor($this->addColor($style->getBorders()->getTop()->getColor()->getRGB())); + $xfWriter->setRightColor($this->addColor($style->getBorders()->getRight()->getColor()->getRGB())); + $xfWriter->setLeftColor($this->addColor($style->getBorders()->getLeft()->getColor()->getRGB())); + $xfWriter->setDiagColor($this->addColor($style->getBorders()->getDiagonal()->getColor()->getRGB())); + + // Add the number format if it is not a built-in one and not already added + if ($style->getNumberFormat()->getBuiltInFormatCode() === false) { + $numberFormatHashCode = $style->getNumberFormat()->getHashCode(); + + if (isset($this->addedNumberFormats[$numberFormatHashCode])) { + $numberFormatIndex = $this->addedNumberFormats[$numberFormatHashCode]; + } else { + $numberFormatIndex = 164 + count($this->numberFormats); + $this->numberFormats[$numberFormatIndex] = $style->getNumberFormat(); + $this->addedNumberFormats[$numberFormatHashCode] = $numberFormatIndex; + } + } else { + $numberFormatIndex = (int) $style->getNumberFormat()->getBuiltInFormatCode(); + } + + // Assign the number format index to xf record + $xfWriter->setNumberFormatIndex($numberFormatIndex); + + $this->xfWriters[] = $xfWriter; + + $xfIndex = count($this->xfWriters) - 1; + return $xfIndex; + } + + /** + * Add a font to added fonts + * + * @param PHPExcel_Style_Font $font + * @return int Index to FONT record + */ + public function addFont(PHPExcel_Style_Font $font) + { + $fontHashCode = $font->getHashCode(); + if (isset($this->addedFonts[$fontHashCode])) { + $fontIndex = $this->addedFonts[$fontHashCode]; + } else { + $countFonts = count($this->fontWriters); + $fontIndex = ($countFonts < 4) ? $countFonts : $countFonts + 1; + + $fontWriter = new PHPExcel_Writer_Excel5_Font($font); + $fontWriter->setColorIndex($this->addColor($font->getColor()->getRGB())); + $this->fontWriters[] = $fontWriter; + + $this->addedFonts[$fontHashCode] = $fontIndex; + } + return $fontIndex; + } + + /** + * Alter color palette adding a custom color + * + * @param string $rgb E.g. 'FF00AA' + * @return int Color index + */ + private function addColor($rgb) + { + if (!isset($this->colors[$rgb])) { + if (count($this->colors) < 57) { + // then we add a custom color altering the palette + $colorIndex = 8 + count($this->colors); + $this->palette[$colorIndex] = + array( + hexdec(substr($rgb, 0, 2)), + hexdec(substr($rgb, 2, 2)), + hexdec(substr($rgb, 4)), + 0 + ); + $this->colors[$rgb] = $colorIndex; + } else { + // no room for more custom colors, just map to black + $colorIndex = 0; + } + } else { + // fetch already added custom color + $colorIndex = $this->colors[$rgb]; + } + + return $colorIndex; + } + + /** + * Sets the colour palette to the Excel 97+ default. + * + * @access private + */ + private function setPaletteXl97() + { + $this->palette = array( + 0x08 => array(0x00, 0x00, 0x00, 0x00), + 0x09 => array(0xff, 0xff, 0xff, 0x00), + 0x0A => array(0xff, 0x00, 0x00, 0x00), + 0x0B => array(0x00, 0xff, 0x00, 0x00), + 0x0C => array(0x00, 0x00, 0xff, 0x00), + 0x0D => array(0xff, 0xff, 0x00, 0x00), + 0x0E => array(0xff, 0x00, 0xff, 0x00), + 0x0F => array(0x00, 0xff, 0xff, 0x00), + 0x10 => array(0x80, 0x00, 0x00, 0x00), + 0x11 => array(0x00, 0x80, 0x00, 0x00), + 0x12 => array(0x00, 0x00, 0x80, 0x00), + 0x13 => array(0x80, 0x80, 0x00, 0x00), + 0x14 => array(0x80, 0x00, 0x80, 0x00), + 0x15 => array(0x00, 0x80, 0x80, 0x00), + 0x16 => array(0xc0, 0xc0, 0xc0, 0x00), + 0x17 => array(0x80, 0x80, 0x80, 0x00), + 0x18 => array(0x99, 0x99, 0xff, 0x00), + 0x19 => array(0x99, 0x33, 0x66, 0x00), + 0x1A => array(0xff, 0xff, 0xcc, 0x00), + 0x1B => array(0xcc, 0xff, 0xff, 0x00), + 0x1C => array(0x66, 0x00, 0x66, 0x00), + 0x1D => array(0xff, 0x80, 0x80, 0x00), + 0x1E => array(0x00, 0x66, 0xcc, 0x00), + 0x1F => array(0xcc, 0xcc, 0xff, 0x00), + 0x20 => array(0x00, 0x00, 0x80, 0x00), + 0x21 => array(0xff, 0x00, 0xff, 0x00), + 0x22 => array(0xff, 0xff, 0x00, 0x00), + 0x23 => array(0x00, 0xff, 0xff, 0x00), + 0x24 => array(0x80, 0x00, 0x80, 0x00), + 0x25 => array(0x80, 0x00, 0x00, 0x00), + 0x26 => array(0x00, 0x80, 0x80, 0x00), + 0x27 => array(0x00, 0x00, 0xff, 0x00), + 0x28 => array(0x00, 0xcc, 0xff, 0x00), + 0x29 => array(0xcc, 0xff, 0xff, 0x00), + 0x2A => array(0xcc, 0xff, 0xcc, 0x00), + 0x2B => array(0xff, 0xff, 0x99, 0x00), + 0x2C => array(0x99, 0xcc, 0xff, 0x00), + 0x2D => array(0xff, 0x99, 0xcc, 0x00), + 0x2E => array(0xcc, 0x99, 0xff, 0x00), + 0x2F => array(0xff, 0xcc, 0x99, 0x00), + 0x30 => array(0x33, 0x66, 0xff, 0x00), + 0x31 => array(0x33, 0xcc, 0xcc, 0x00), + 0x32 => array(0x99, 0xcc, 0x00, 0x00), + 0x33 => array(0xff, 0xcc, 0x00, 0x00), + 0x34 => array(0xff, 0x99, 0x00, 0x00), + 0x35 => array(0xff, 0x66, 0x00, 0x00), + 0x36 => array(0x66, 0x66, 0x99, 0x00), + 0x37 => array(0x96, 0x96, 0x96, 0x00), + 0x38 => array(0x00, 0x33, 0x66, 0x00), + 0x39 => array(0x33, 0x99, 0x66, 0x00), + 0x3A => array(0x00, 0x33, 0x00, 0x00), + 0x3B => array(0x33, 0x33, 0x00, 0x00), + 0x3C => array(0x99, 0x33, 0x00, 0x00), + 0x3D => array(0x99, 0x33, 0x66, 0x00), + 0x3E => array(0x33, 0x33, 0x99, 0x00), + 0x3F => array(0x33, 0x33, 0x33, 0x00), + ); + } + + /** + * Assemble worksheets into a workbook and send the BIFF data to an OLE + * storage. + * + * @param array $pWorksheetSizes The sizes in bytes of the binary worksheet streams + * @return string Binary data for workbook stream + */ + public function writeWorkbook($pWorksheetSizes = null) + { + $this->worksheetSizes = $pWorksheetSizes; + + // Calculate the number of selected worksheet tabs and call the finalization + // methods for each worksheet + $total_worksheets = $this->phpExcel->getSheetCount(); + + // Add part 1 of the Workbook globals, what goes before the SHEET records + $this->storeBof(0x0005); + $this->writeCodepage(); + $this->writeWindow1(); + + $this->writeDateMode(); + $this->writeAllFonts(); + $this->writeAllNumberFormats(); + $this->writeAllXfs(); + $this->writeAllStyles(); + $this->writePalette(); + + // Prepare part 3 of the workbook global stream, what goes after the SHEET records + $part3 = ''; + if ($this->countryCode != -1) { + $part3 .= $this->writeCountry(); + } + $part3 .= $this->writeRecalcId(); + + $part3 .= $this->writeSupbookInternal(); + /* TODO: store external SUPBOOK records and XCT and CRN records + in case of external references for BIFF8 */ + $part3 .= $this->writeExternalsheetBiff8(); + $part3 .= $this->writeAllDefinedNamesBiff8(); + $part3 .= $this->writeMsoDrawingGroup(); + $part3 .= $this->writeSharedStringsTable(); + + $part3 .= $this->writeEof(); + + // Add part 2 of the Workbook globals, the SHEET records + $this->calcSheetOffsets(); + for ($i = 0; $i < $total_worksheets; ++$i) { + $this->writeBoundSheet($this->phpExcel->getSheet($i), $this->worksheetOffsets[$i]); + } + + // Add part 3 of the Workbook globals + $this->_data .= $part3; + + return $this->_data; + } + + /** + * Calculate offsets for Worksheet BOF records. + * + * @access private + */ + private function calcSheetOffsets() + { + $boundsheet_length = 10; // fixed length for a BOUNDSHEET record + + // size of Workbook globals part 1 + 3 + $offset = $this->_datasize; + + // add size of Workbook globals part 2, the length of the SHEET records + $total_worksheets = count($this->phpExcel->getAllSheets()); + foreach ($this->phpExcel->getWorksheetIterator() as $sheet) { + $offset += $boundsheet_length + strlen(PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheet->getTitle())); + } + + // add the sizes of each of the Sheet substreams, respectively + for ($i = 0; $i < $total_worksheets; ++$i) { + $this->worksheetOffsets[$i] = $offset; + $offset += $this->worksheetSizes[$i]; + } + $this->biffSize = $offset; + } + + /** + * Store the Excel FONT records. + */ + private function writeAllFonts() + { + foreach ($this->fontWriters as $fontWriter) { + $this->append($fontWriter->writeFont()); + } + } + + /** + * Store user defined numerical formats i.e. FORMAT records + */ + private function writeAllNumberFormats() + { + foreach ($this->numberFormats as $numberFormatIndex => $numberFormat) { + $this->writeNumberFormat($numberFormat->getFormatCode(), $numberFormatIndex); + } + } + + /** + * Write all XF records. + */ + private function writeAllXfs() + { + foreach ($this->xfWriters as $xfWriter) { + $this->append($xfWriter->writeXf()); + } + } + + /** + * Write all STYLE records. + */ + private function writeAllStyles() + { + $this->writeStyle(); + } + + /** + * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for + * the NAME records. + */ + private function writeExternals() + { + $countSheets = $this->phpExcel->getSheetCount(); + // Create EXTERNCOUNT with number of worksheets + $this->writeExternalCount($countSheets); + + // Create EXTERNSHEET for each worksheet + for ($i = 0; $i < $countSheets; ++$i) { + $this->writeExternalSheet($this->phpExcel->getSheet($i)->getTitle()); + } + } + + /** + * Write the NAME record to define the print area and the repeat rows and cols. + */ + private function writeNames() + { + // total number of sheets + $total_worksheets = $this->phpExcel->getSheetCount(); + + // Create the print area NAME records + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup(); + // Write a Name record if the print area has been defined + if ($sheetSetup->isPrintAreaSet()) { + // Print area + $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea()); + $printArea = $printArea[0]; + $printArea[0] = PHPExcel_Cell::coordinateFromString($printArea[0]); + $printArea[1] = PHPExcel_Cell::coordinateFromString($printArea[1]); + + $print_rowmin = $printArea[0][1] - 1; + $print_rowmax = $printArea[1][1] - 1; + $print_colmin = PHPExcel_Cell::columnIndexFromString($printArea[0][0]) - 1; + $print_colmax = PHPExcel_Cell::columnIndexFromString($printArea[1][0]) - 1; + + $this->writeNameShort( + $i, // sheet index + 0x06, // NAME type + $print_rowmin, + $print_rowmax, + $print_colmin, + $print_colmax + ); + } + } + + // Create the print title NAME records + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup(); + + // simultaneous repeatColumns repeatRows + if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + + $this->writeNameLong( + $i, // sheet index + 0x07, // NAME type + $rowmin, + $rowmax, + $colmin, + $colmax + ); + + // (exclusive) either repeatColumns or repeatRows + } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { + // Columns to repeat + if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + } else { + $colmin = 0; + $colmax = 255; + } + + // Rows to repeat + if ($sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + } else { + $rowmin = 0; + $rowmax = 65535; + } + + $this->writeNameShort( + $i, // sheet index + 0x07, // NAME type + $rowmin, + $rowmax, + $colmin, + $colmax + ); + } + } + } + + /** + * Writes all the DEFINEDNAME records (BIFF8). + * So far this is only used for repeating rows/columns (print titles) and print areas + */ + private function writeAllDefinedNamesBiff8() + { + $chunk = ''; + + // Named ranges + if (count($this->phpExcel->getNamedRanges()) > 0) { + // Loop named ranges + $namedRanges = $this->phpExcel->getNamedRanges(); + foreach ($namedRanges as $namedRange) { + // Create absolute coordinate + $range = PHPExcel_Cell::splitRange($namedRange->getRange()); + for ($i = 0; $i < count($range); $i++) { + $range[$i][0] = '\'' . str_replace("'", "''", $namedRange->getWorksheet()->getTitle()) . '\'!' . PHPExcel_Cell::absoluteCoordinate($range[$i][0]); + if (isset($range[$i][1])) { + $range[$i][1] = PHPExcel_Cell::absoluteCoordinate($range[$i][1]); + } + } + $range = PHPExcel_Cell::buildRange($range); // e.g. Sheet1!$A$1:$B$2 + + // parse formula + try { + $error = $this->parser->parse($range); + $formulaData = $this->parser->toReversePolish(); + + // make sure tRef3d is of type tRef3dR (0x3A) + if (isset($formulaData{0}) and ($formulaData{0} == "\x7A" or $formulaData{0} == "\x5A")) { + $formulaData = "\x3A" . substr($formulaData, 1); + } + + if ($namedRange->getLocalOnly()) { + // local scope + $scope = $this->phpExcel->getIndex($namedRange->getScope()) + 1; + } else { + // global scope + $scope = 0; + } + $chunk .= $this->writeData($this->writeDefinedNameBiff8($namedRange->getName(), $formulaData, $scope, false)); + + } catch (PHPExcel_Exception $e) { + // do nothing + } + } + } + + // total number of sheets + $total_worksheets = $this->phpExcel->getSheetCount(); + + // write the print titles (repeating rows, columns), if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup(); + // simultaneous repeatColumns repeatRows + if ($sheetSetup->isColumnsToRepeatAtLeftSet() && $sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + + // construct formula data manually + $formulaData = pack('Cv', 0x29, 0x17); // tMemFunc + $formulaData .= pack('Cvvvvv', 0x3B, $i, 0, 65535, $colmin, $colmax); // tArea3d + $formulaData .= pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, 0, 255); // tArea3d + $formulaData .= pack('C', 0x10); // tList + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); + + // (exclusive) either repeatColumns or repeatRows + } elseif ($sheetSetup->isColumnsToRepeatAtLeftSet() || $sheetSetup->isRowsToRepeatAtTopSet()) { + // Columns to repeat + if ($sheetSetup->isColumnsToRepeatAtLeftSet()) { + $repeat = $sheetSetup->getColumnsToRepeatAtLeft(); + $colmin = PHPExcel_Cell::columnIndexFromString($repeat[0]) - 1; + $colmax = PHPExcel_Cell::columnIndexFromString($repeat[1]) - 1; + } else { + $colmin = 0; + $colmax = 255; + } + // Rows to repeat + if ($sheetSetup->isRowsToRepeatAtTopSet()) { + $repeat = $sheetSetup->getRowsToRepeatAtTop(); + $rowmin = $repeat[0] - 1; + $rowmax = $repeat[1] - 1; + } else { + $rowmin = 0; + $rowmax = 65535; + } + + // construct formula data manually because parser does not recognize absolute 3d cell references + $formulaData = pack('Cvvvvv', 0x3B, $i, $rowmin, $rowmax, $colmin, $colmax); + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x07), $formulaData, $i + 1, true)); + } + } + + // write the print areas, if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetSetup = $this->phpExcel->getSheet($i)->getPageSetup(); + if ($sheetSetup->isPrintAreaSet()) { + // Print area, e.g. A3:J6,H1:X20 + $printArea = PHPExcel_Cell::splitRange($sheetSetup->getPrintArea()); + $countPrintArea = count($printArea); + + $formulaData = ''; + for ($j = 0; $j < $countPrintArea; ++$j) { + $printAreaRect = $printArea[$j]; // e.g. A3:J6 + $printAreaRect[0] = PHPExcel_Cell::coordinateFromString($printAreaRect[0]); + $printAreaRect[1] = PHPExcel_Cell::coordinateFromString($printAreaRect[1]); + + $print_rowmin = $printAreaRect[0][1] - 1; + $print_rowmax = $printAreaRect[1][1] - 1; + $print_colmin = PHPExcel_Cell::columnIndexFromString($printAreaRect[0][0]) - 1; + $print_colmax = PHPExcel_Cell::columnIndexFromString($printAreaRect[1][0]) - 1; + + // construct formula data manually because parser does not recognize absolute 3d cell references + $formulaData .= pack('Cvvvvv', 0x3B, $i, $print_rowmin, $print_rowmax, $print_colmin, $print_colmax); + + if ($j > 0) { + $formulaData .= pack('C', 0x10); // list operator token ',' + } + } + + // store the DEFINEDNAME record + $chunk .= $this->writeData($this->writeDefinedNameBiff8(pack('C', 0x06), $formulaData, $i + 1, true)); + } + } + + // write autofilters, if any + for ($i = 0; $i < $total_worksheets; ++$i) { + $sheetAutoFilter = $this->phpExcel->getSheet($i)->getAutoFilter(); + $autoFilterRange = $sheetAutoFilter->getRange(); + if (!empty($autoFilterRange)) { + $rangeBounds = PHPExcel_Cell::rangeBoundaries($autoFilterRange); + + //Autofilter built in name + $name = pack('C', 0x0D); + + $chunk .= $this->writeData($this->writeShortNameBiff8($name, $i + 1, $rangeBounds, true)); + } + } + + return $chunk; + } + + /** + * Write a DEFINEDNAME record for BIFF8 using explicit binary formula data + * + * @param string $name The name in UTF-8 + * @param string $formulaData The binary formula data + * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param boolean $isBuiltIn Built-in name? + * @return string Complete binary record data + */ + private function writeDefinedNameBiff8($name, $formulaData, $sheetIndex = 0, $isBuiltIn = false) + { + $record = 0x0018; + + // option flags + $options = $isBuiltIn ? 0x20 : 0x00; + + // length of the name, character count + $nlen = PHPExcel_Shared_String::CountCharacters($name); + + // name with stripped length field + $name = substr(PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($name), 2); + + // size of the formula (in bytes) + $sz = strlen($formulaData); + + // combine the parts + $data = pack('vCCvvvCCCC', $options, 0, $nlen, $sz, 0, $sheetIndex, 0, 0, 0, 0) + . $name . $formulaData; + $length = strlen($data); + + $header = pack('vv', $record, $length); + + return $header . $data; + } + + /** + * Write a short NAME record + * + * @param string $name + * @param string $sheetIndex 1-based sheet index the defined name applies to. 0 = global + * @param integer[][] $rangeBounds range boundaries + * @param boolean $isHidden + * @return string Complete binary record data + * */ + private function writeShortNameBiff8($name, $sheetIndex = 0, $rangeBounds, $isHidden = false) + { + $record = 0x0018; + + // option flags + $options = ($isHidden ? 0x21 : 0x00); + + $extra = pack( + 'Cvvvvv', + 0x3B, + $sheetIndex - 1, + $rangeBounds[0][1] - 1, + $rangeBounds[1][1] - 1, + $rangeBounds[0][0] - 1, + $rangeBounds[1][0] - 1 + ); + + // size of the formula (in bytes) + $sz = strlen($extra); + + // combine the parts + $data = pack('vCCvvvCCCCC', $options, 0, 1, $sz, 0, $sheetIndex, 0, 0, 0, 0, 0) + . $name . $extra; + $length = strlen($data); + + $header = pack('vv', $record, $length); + + return $header . $data; + } + + /** + * Stores the CODEPAGE biff record. + */ + private function writeCodepage() + { + $record = 0x0042; // Record identifier + $length = 0x0002; // Number of bytes to follow + $cv = $this->codepage; // The code page + + $header = pack('vv', $record, $length); + $data = pack('v', $cv); + + $this->append($header . $data); + } + + /** + * Write Excel BIFF WINDOW1 record. + */ + private function writeWindow1() + { + $record = 0x003D; // Record identifier + $length = 0x0012; // Number of bytes to follow + + $xWn = 0x0000; // Horizontal position of window + $yWn = 0x0000; // Vertical position of window + $dxWn = 0x25BC; // Width of window + $dyWn = 0x1572; // Height of window + + $grbit = 0x0038; // Option flags + + // not supported by PHPExcel, so there is only one selected sheet, the active + $ctabsel = 1; // Number of workbook tabs selected + + $wTabRatio = 0x0258; // Tab to scrollbar ratio + + // not supported by PHPExcel, set to 0 + $itabFirst = 0; // 1st displayed worksheet + $itabCur = $this->phpExcel->getActiveSheetIndex(); // Active worksheet + + $header = pack("vv", $record, $length); + $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn, $grbit, $itabCur, $itabFirst, $ctabsel, $wTabRatio); + $this->append($header . $data); + } + + /** + * Writes Excel BIFF BOUNDSHEET record. + * + * @param PHPExcel_Worksheet $sheet Worksheet name + * @param integer $offset Location of worksheet BOF + */ + private function writeBoundSheet($sheet, $offset) + { + $sheetname = $sheet->getTitle(); + $record = 0x0085; // Record identifier + + // sheet state + switch ($sheet->getSheetState()) { + case PHPExcel_Worksheet::SHEETSTATE_VISIBLE: + $ss = 0x00; + break; + case PHPExcel_Worksheet::SHEETSTATE_HIDDEN: + $ss = 0x01; + break; + case PHPExcel_Worksheet::SHEETSTATE_VERYHIDDEN: + $ss = 0x02; + break; + default: + $ss = 0x00; + break; + } + + // sheet type + $st = 0x00; + + $grbit = 0x0000; // Visibility and sheet type + + $data = pack("VCC", $offset, $ss, $st); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($sheetname); + + $length = strlen($data); + $header = pack("vv", $record, $length); + $this->append($header . $data); + } + + /** + * Write Internal SUPBOOK record + */ + private function writeSupbookInternal() + { + $record = 0x01AE; // Record identifier + $length = 0x0004; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", $this->phpExcel->getSheetCount(), 0x0401); + return $this->writeData($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. + * + */ + private function writeExternalsheetBiff8() + { + $totalReferences = count($this->parser->references); + $record = 0x0017; // Record identifier + $length = 2 + 6 * $totalReferences; // Number of bytes to follow + + $supbook_index = 0; // FIXME: only using internal SUPBOOK record + $header = pack("vv", $record, $length); + $data = pack('v', $totalReferences); + for ($i = 0; $i < $totalReferences; ++$i) { + $data .= $this->parser->references[$i]; + } + return $this->writeData($header . $data); + } + + /** + * Write Excel BIFF STYLE records. + */ + private function writeStyle() + { + $record = 0x0293; // Record identifier + $length = 0x0004; // Bytes to follow + + $ixfe = 0x8000; // Index to cell style XF + $BuiltIn = 0x00; // Built-in style + $iLevel = 0xff; // Outline style level + + $header = pack("vv", $record, $length); + $data = pack("vCC", $ixfe, $BuiltIn, $iLevel); + $this->append($header . $data); + } + + /** + * Writes Excel FORMAT record for non "built-in" numerical formats. + * + * @param string $format Custom format string + * @param integer $ifmt Format index code + */ + private function writeNumberFormat($format, $ifmt) + { + $record = 0x041E; // Record identifier + + $numberFormatString = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($format); + $length = 2 + strlen($numberFormatString); // Number of bytes to follow + + + $header = pack("vv", $record, $length); + $data = pack("v", $ifmt) . $numberFormatString; + $this->append($header . $data); + } + + /** + * Write DATEMODE record to indicate the date system in use (1904 or 1900). + */ + private function writeDateMode() + { + $record = 0x0022; // Record identifier + $length = 0x0002; // Bytes to follow + + $f1904 = (PHPExcel_Shared_Date::getExcelCalendar() == PHPExcel_Shared_Date::CALENDAR_MAC_1904) + ? 1 + : 0; // Flag for 1904 date system + + $header = pack("vv", $record, $length); + $data = pack("v", $f1904); + $this->append($header . $data); + } + + /** + * Write BIFF record EXTERNCOUNT to indicate the number of external sheet + * references in the workbook. + * + * Excel only stores references to external sheets that are used in NAME. + * The workbook NAME record is required to define the print area and the repeat + * rows and columns. + * + * A similar method is used in Worksheet.php for a slightly different purpose. + * + * @param integer $cxals Number of external references + */ + private function writeExternalCount($cxals) + { + $record = 0x0016; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cxals); + $this->append($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. NAME record is required to define the print area and the repeat + * rows and columns. + * + * A similar method is used in Worksheet.php for a slightly different purpose. + * + * @param string $sheetname Worksheet name + */ + private function writeExternalSheet($sheetname) + { + $record = 0x0017; // Record identifier + $length = 0x02 + strlen($sheetname); // Number of bytes to follow + + $cch = strlen($sheetname); // Length of sheet name + $rgch = 0x03; // Filename encoding + + $header = pack("vv", $record, $length); + $data = pack("CC", $cch, $rgch); + $this->append($header . $data . $sheetname); + } + + /** + * Store the NAME record in the short format that is used for storing the print + * area, repeat rows only and repeat columns only. + * + * @param integer $index Sheet index + * @param integer $type Built-in name type + * @param integer $rowmin Start row + * @param integer $rowmax End row + * @param integer $colmin Start colum + * @param integer $colmax End column + */ + private function writeNameShort($index, $type, $rowmin, $rowmax, $colmin, $colmax) + { + $record = 0x0018; // Record identifier + $length = 0x0024; // Number of bytes to follow + + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x0015; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text + $cchDescription = 0x00; // Length of description text + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type + + $unknown03 = 0x3b; + $unknown04 = 0xffff - $index; + $unknown05 = 0x0000; + $unknown06 = 0x0000; + $unknown07 = 0x1087; + $unknown08 = 0x8005; + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $data .= pack("C", $chKey); + $data .= pack("C", $cch); + $data .= pack("v", $cce); + $data .= pack("v", $ixals); + $data .= pack("v", $itab); + $data .= pack("C", $cchCustMenu); + $data .= pack("C", $cchDescription); + $data .= pack("C", $cchHelptopic); + $data .= pack("C", $cchStatustext); + $data .= pack("C", $rgch); + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", $rowmin); + $data .= pack("v", $rowmax); + $data .= pack("C", $colmin); + $data .= pack("C", $colmax); + $this->append($header . $data); + } + + /** + * Store the NAME record in the long format that is used for storing the repeat + * rows and columns when both are specified. This shares a lot of code with + * writeNameShort() but we use a separate method to keep the code clean. + * Code abstraction for reuse can be carried too far, and I should know. ;-) + * + * @param integer $index Sheet index + * @param integer $type Built-in name type + * @param integer $rowmin Start row + * @param integer $rowmax End row + * @param integer $colmin Start colum + * @param integer $colmax End column + */ + private function writeNameLong($index, $type, $rowmin, $rowmax, $colmin, $colmax) + { + $record = 0x0018; // Record identifier + $length = 0x003d; // Number of bytes to follow + $grbit = 0x0020; // Option flags + $chKey = 0x00; // Keyboard shortcut + $cch = 0x01; // Length of text name + $cce = 0x002e; // Length of text definition + $ixals = $index + 1; // Sheet index + $itab = $ixals; // Equal to ixals + $cchCustMenu = 0x00; // Length of cust menu text + $cchDescription = 0x00; // Length of description text + $cchHelptopic = 0x00; // Length of help topic text + $cchStatustext = 0x00; // Length of status bar text + $rgch = $type; // Built-in name type + + $unknown01 = 0x29; + $unknown02 = 0x002b; + $unknown03 = 0x3b; + $unknown04 = 0xffff-$index; + $unknown05 = 0x0000; + $unknown06 = 0x0000; + $unknown07 = 0x1087; + $unknown08 = 0x8008; + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $data .= pack("C", $chKey); + $data .= pack("C", $cch); + $data .= pack("v", $cce); + $data .= pack("v", $ixals); + $data .= pack("v", $itab); + $data .= pack("C", $cchCustMenu); + $data .= pack("C", $cchDescription); + $data .= pack("C", $cchHelptopic); + $data .= pack("C", $cchStatustext); + $data .= pack("C", $rgch); + $data .= pack("C", $unknown01); + $data .= pack("v", $unknown02); + // Column definition + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", 0x0000); + $data .= pack("v", 0x3fff); + $data .= pack("C", $colmin); + $data .= pack("C", $colmax); + // Row definition + $data .= pack("C", $unknown03); + $data .= pack("v", $unknown04); + $data .= pack("v", $unknown05); + $data .= pack("v", $unknown06); + $data .= pack("v", $unknown07); + $data .= pack("v", $unknown08); + $data .= pack("v", $index); + $data .= pack("v", $index); + $data .= pack("v", $rowmin); + $data .= pack("v", $rowmax); + $data .= pack("C", 0x00); + $data .= pack("C", 0xff); + // End of data + $data .= pack("C", 0x10); + $this->append($header . $data); + } + + /** + * Stores the COUNTRY record for localization + * + * @return string + */ + private function writeCountry() + { + $record = 0x008C; // Record identifier + $length = 4; // Number of bytes to follow + + $header = pack('vv', $record, $length); + /* using the same country code always for simplicity */ + $data = pack('vv', $this->countryCode, $this->countryCode); + //$this->append($header . $data); + return $this->writeData($header . $data); + } + + /** + * Write the RECALCID record + * + * @return string + */ + private function writeRecalcId() + { + $record = 0x01C1; // Record identifier + $length = 8; // Number of bytes to follow + + $header = pack('vv', $record, $length); + + // by inspection of real Excel files, MS Office Excel 2007 writes this + $data = pack('VV', 0x000001C1, 0x00001E667); + + return $this->writeData($header . $data); + } + + /** + * Stores the PALETTE biff record. + */ + private function writePalette() + { + $aref = $this->palette; + + $record = 0x0092; // Record identifier + $length = 2 + 4 * count($aref); // Number of bytes to follow + $ccv = count($aref); // Number of RGB values to follow + $data = ''; // The RGB data + + // Pack the RGB data + foreach ($aref as $color) { + foreach ($color as $byte) { + $data .= pack("C", $byte); + } + } + + $header = pack("vvv", $record, $length, $ccv); + $this->append($header . $data); + } + + /** + * Handling of the SST continue blocks is complicated by the need to include an + * additional continuation byte depending on whether the string is split between + * blocks or whether it starts at the beginning of the block. (There are also + * additional complications that will arise later when/if Rich Strings are + * supported). + * + * The Excel documentation says that the SST record should be followed by an + * EXTSST record. The EXTSST record is a hash table that is used to optimise + * access to SST. However, despite the documentation it doesn't seem to be + * required so we will ignore it. + * + * @return string Binary data + */ + private function writeSharedStringsTable() + { + // maximum size of record data (excluding record header) + $continue_limit = 8224; + + // initialize array of record data blocks + $recordDatas = array(); + + // start SST record data block with total number of strings, total number of unique strings + $recordData = pack("VV", $this->stringTotal, $this->stringUnique); + + // loop through all (unique) strings in shared strings table + foreach (array_keys($this->stringTable) as $string) { + // here $string is a BIFF8 encoded string + + // length = character count + $headerinfo = unpack("vlength/Cencoding", $string); + + // currently, this is always 1 = uncompressed + $encoding = $headerinfo["encoding"]; + + // initialize finished writing current $string + $finished = false; + + while ($finished === false) { + // normally, there will be only one cycle, but if string cannot immediately be written as is + // there will be need for more than one cylcle, if string longer than one record data block, there + // may be need for even more cycles + + if (strlen($recordData) + strlen($string) <= $continue_limit) { + // then we can write the string (or remainder of string) without any problems + $recordData .= $string; + + if (strlen($recordData) + strlen($string) == $continue_limit) { + // we close the record data block, and initialize a new one + $recordDatas[] = $recordData; + $recordData = ''; + } + + // we are finished writing this string + $finished = true; + } else { + // special treatment writing the string (or remainder of the string) + // If the string is very long it may need to be written in more than one CONTINUE record. + + // check how many bytes more there is room for in the current record + $space_remaining = $continue_limit - strlen($recordData); + + // minimum space needed + // uncompressed: 2 byte string length length field + 1 byte option flags + 2 byte character + // compressed: 2 byte string length length field + 1 byte option flags + 1 byte character + $min_space_needed = ($encoding == 1) ? 5 : 4; + + // We have two cases + // 1. space remaining is less than minimum space needed + // here we must waste the space remaining and move to next record data block + // 2. space remaining is greater than or equal to minimum space needed + // here we write as much as we can in the current block, then move to next record data block + + // 1. space remaining is less than minimum space needed + if ($space_remaining < $min_space_needed) { + // we close the block, store the block data + $recordDatas[] = $recordData; + + // and start new record data block where we start writing the string + $recordData = ''; + + // 2. space remaining is greater than or equal to minimum space needed + } else { + // initialize effective remaining space, for Unicode strings this may need to be reduced by 1, see below + $effective_space_remaining = $space_remaining; + + // for uncompressed strings, sometimes effective space remaining is reduced by 1 + if ($encoding == 1 && (strlen($string) - $space_remaining) % 2 == 1) { + --$effective_space_remaining; + } + + // one block fininshed, store the block data + $recordData .= substr($string, 0, $effective_space_remaining); + + $string = substr($string, $effective_space_remaining); // for next cycle in while loop + $recordDatas[] = $recordData; + + // start new record data block with the repeated option flags + $recordData = pack('C', $encoding); + } + } + } + } + + // Store the last record data block unless it is empty + // if there was no need for any continue records, this will be the for SST record data block itself + if (strlen($recordData) > 0) { + $recordDatas[] = $recordData; + } + + // combine into one chunk with all the blocks SST, CONTINUE,... + $chunk = ''; + foreach ($recordDatas as $i => $recordData) { + // first block should have the SST record header, remaing should have CONTINUE header + $record = ($i == 0) ? 0x00FC : 0x003C; + + $header = pack("vv", $record, strlen($recordData)); + $data = $header . $recordData; + + $chunk .= $this->writeData($data); + } + + return $chunk; + } + + /** + * Writes the MSODRAWINGGROUP record if needed. Possibly split using CONTINUE records. + */ + private function writeMsoDrawingGroup() + { + // write the Escher stream if necessary + if (isset($this->escher)) { + $writer = new PHPExcel_Writer_Excel5_Escher($this->escher); + $data = $writer->close(); + + $record = 0x00EB; + $length = strlen($data); + $header = pack("vv", $record, $length); + + return $this->writeData($header . $data); + } else { + return ''; + } + } + + /** + * Get Escher object + * + * @return PHPExcel_Shared_Escher + */ + public function getEscher() + { + return $this->escher; + } + + /** + * Set Escher object + * + * @param PHPExcel_Shared_Escher $pValue + */ + public function setEscher(PHPExcel_Shared_Escher $pValue = null) + { + $this->escher = $pValue; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Worksheet.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Worksheet.php new file mode 100644 index 00000000..be965e23 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Worksheet.php @@ -0,0 +1,4240 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_Worksheet + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Worksheet (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ +class PHPExcel_Writer_Excel5_Worksheet extends PHPExcel_Writer_Excel5_BIFFwriter +{ + /** + * Formula parser + * + * @var PHPExcel_Writer_Excel5_Parser + */ + private $parser; + + /** + * Maximum number of characters for a string (LABEL record in BIFF5) + * @var integer + */ + private $xlsStringMaxLength; + + /** + * Array containing format information for columns + * @var array + */ + private $columnInfo; + + /** + * Array containing the selected area for the worksheet + * @var array + */ + private $selection; + + /** + * The active pane for the worksheet + * @var integer + */ + private $activePane; + + /** + * Whether to use outline. + * @var integer + */ + private $outlineOn; + + /** + * Auto outline styles. + * @var bool + */ + private $outlineStyle; + + /** + * Whether to have outline summary below. + * @var bool + */ + private $outlineBelow; + + /** + * Whether to have outline summary at the right. + * @var bool + */ + private $outlineRight; + + /** + * Reference to the total number of strings in the workbook + * @var integer + */ + private $stringTotal; + + /** + * Reference to the number of unique strings in the workbook + * @var integer + */ + private $stringUnique; + + /** + * Reference to the array containing all the unique strings in the workbook + * @var array + */ + private $stringTable; + + /** + * Color cache + */ + private $colors; + + /** + * Index of first used row (at least 0) + * @var int + */ + private $firstRowIndex; + + /** + * Index of last used row. (no used rows means -1) + * @var int + */ + private $lastRowIndex; + + /** + * Index of first used column (at least 0) + * @var int + */ + private $firstColumnIndex; + + /** + * Index of last used column (no used columns means -1) + * @var int + */ + private $lastColumnIndex; + + /** + * Sheet object + * @var PHPExcel_Worksheet + */ + public $phpSheet; + + /** + * Count cell style Xfs + * + * @var int + */ + private $countCellStyleXfs; + + /** + * Escher object corresponding to MSODRAWING + * + * @var PHPExcel_Shared_Escher + */ + private $escher; + + /** + * Array of font hashes associated to FONT records index + * + * @var array + */ + public $fontHashIndex; + + /** + * Constructor + * + * @param int &$str_total Total number of strings + * @param int &$str_unique Total number of unique strings + * @param array &$str_table String Table + * @param array &$colors Colour Table + * @param mixed $parser The formula parser created for the Workbook + * @param boolean $preCalculateFormulas Flag indicating whether formulas should be calculated or just written + * @param string $phpSheet The worksheet to write + * @param PHPExcel_Worksheet $phpSheet + */ + public function __construct(&$str_total, &$str_unique, &$str_table, &$colors, $parser, $preCalculateFormulas, $phpSheet) + { + // It needs to call its parent's constructor explicitly + parent::__construct(); + + // change BIFFwriter limit for CONTINUE records +// $this->_limit = 8224; + + + $this->_preCalculateFormulas = $preCalculateFormulas; + $this->stringTotal = &$str_total; + $this->stringUnique = &$str_unique; + $this->stringTable = &$str_table; + $this->colors = &$colors; + $this->parser = $parser; + + $this->phpSheet = $phpSheet; + + //$this->ext_sheets = array(); + //$this->offset = 0; + $this->xlsStringMaxLength = 255; + $this->columnInfo = array(); + $this->selection = array(0,0,0,0); + $this->activePane = 3; + + $this->_print_headers = 0; + + $this->outlineStyle = 0; + $this->outlineBelow = 1; + $this->outlineRight = 1; + $this->outlineOn = 1; + + $this->fontHashIndex = array(); + + // calculate values for DIMENSIONS record + $minR = 1; + $minC = 'A'; + + $maxR = $this->phpSheet->getHighestRow(); + $maxC = $this->phpSheet->getHighestColumn(); + + // Determine lowest and highest column and row +// $this->firstRowIndex = ($minR > 65535) ? 65535 : $minR; + $this->lastRowIndex = ($maxR > 65535) ? 65535 : $maxR ; + + $this->firstColumnIndex = PHPExcel_Cell::columnIndexFromString($minC); + $this->lastColumnIndex = PHPExcel_Cell::columnIndexFromString($maxC); + +// if ($this->firstColumnIndex > 255) $this->firstColumnIndex = 255; + if ($this->lastColumnIndex > 255) { + $this->lastColumnIndex = 255; + } + + $this->countCellStyleXfs = count($phpSheet->getParent()->getCellStyleXfCollection()); + } + + /** + * Add data to the beginning of the workbook (note the reverse order) + * and to the end of the workbook. + * + * @access public + * @see PHPExcel_Writer_Excel5_Workbook::storeWorkbook() + */ + public function close() + { + $phpSheet = $this->phpSheet; + + $num_sheets = $phpSheet->getParent()->getSheetCount(); + + // Write BOF record + $this->storeBof(0x0010); + + // Write PRINTHEADERS + $this->writePrintHeaders(); + + // Write PRINTGRIDLINES + $this->writePrintGridlines(); + + // Write GRIDSET + $this->writeGridset(); + + // Calculate column widths + $phpSheet->calculateColumnWidths(); + + // Column dimensions + if (($defaultWidth = $phpSheet->getDefaultColumnDimension()->getWidth()) < 0) { + $defaultWidth = PHPExcel_Shared_Font::getDefaultColumnWidthByFont($phpSheet->getParent()->getDefaultStyle()->getFont()); + } + + $columnDimensions = $phpSheet->getColumnDimensions(); + $maxCol = $this->lastColumnIndex -1; + for ($i = 0; $i <= $maxCol; ++$i) { + $hidden = 0; + $level = 0; + $xfIndex = 15; // there are 15 cell style Xfs + + $width = $defaultWidth; + + $columnLetter = PHPExcel_Cell::stringFromColumnIndex($i); + if (isset($columnDimensions[$columnLetter])) { + $columnDimension = $columnDimensions[$columnLetter]; + if ($columnDimension->getWidth() >= 0) { + $width = $columnDimension->getWidth(); + } + $hidden = $columnDimension->getVisible() ? 0 : 1; + $level = $columnDimension->getOutlineLevel(); + $xfIndex = $columnDimension->getXfIndex() + 15; // there are 15 cell style Xfs + } + + // Components of columnInfo: + // $firstcol first column on the range + // $lastcol last column on the range + // $width width to set + // $xfIndex The optional cell style Xf index to apply to the columns + // $hidden The optional hidden atribute + // $level The optional outline level + $this->columnInfo[] = array($i, $i, $width, $xfIndex, $hidden, $level); + } + + // Write GUTS + $this->writeGuts(); + + // Write DEFAULTROWHEIGHT + $this->writeDefaultRowHeight(); + // Write WSBOOL + $this->writeWsbool(); + // Write horizontal and vertical page breaks + $this->writeBreaks(); + // Write page header + $this->writeHeader(); + // Write page footer + $this->writeFooter(); + // Write page horizontal centering + $this->writeHcenter(); + // Write page vertical centering + $this->writeVcenter(); + // Write left margin + $this->writeMarginLeft(); + // Write right margin + $this->writeMarginRight(); + // Write top margin + $this->writeMarginTop(); + // Write bottom margin + $this->writeMarginBottom(); + // Write page setup + $this->writeSetup(); + // Write sheet protection + $this->writeProtect(); + // Write SCENPROTECT + $this->writeScenProtect(); + // Write OBJECTPROTECT + $this->writeObjectProtect(); + // Write sheet password + $this->writePassword(); + // Write DEFCOLWIDTH record + $this->writeDefcol(); + + // Write the COLINFO records if they exist + if (!empty($this->columnInfo)) { + $colcount = count($this->columnInfo); + for ($i = 0; $i < $colcount; ++$i) { + $this->writeColinfo($this->columnInfo[$i]); + } + } + $autoFilterRange = $phpSheet->getAutoFilter()->getRange(); + if (!empty($autoFilterRange)) { + // Write AUTOFILTERINFO + $this->writeAutoFilterInfo(); + } + + // Write sheet dimensions + $this->writeDimensions(); + + // Row dimensions + foreach ($phpSheet->getRowDimensions() as $rowDimension) { + $xfIndex = $rowDimension->getXfIndex() + 15; // there are 15 cellXfs + $this->writeRow($rowDimension->getRowIndex() - 1, $rowDimension->getRowHeight(), $xfIndex, ($rowDimension->getVisible() ? '0' : '1'), $rowDimension->getOutlineLevel()); + } + + // Write Cells + foreach ($phpSheet->getCellCollection() as $cellID) { + $cell = $phpSheet->getCell($cellID); + $row = $cell->getRow() - 1; + $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1; + + // Don't break Excel! +// if ($row + 1 > 65536 or $column + 1 > 256) { + if ($row > 65535 || $column > 255) { + break; + } + + // Write cell value + $xfIndex = $cell->getXfIndex() + 15; // there are 15 cell style Xfs + + $cVal = $cell->getValue(); + if ($cVal instanceof PHPExcel_RichText) { + // $this->writeString($row, $column, $cVal->getPlainText(), $xfIndex); + $arrcRun = array(); + $str_len = PHPExcel_Shared_String::CountCharacters($cVal->getPlainText(), 'UTF-8'); + $str_pos = 0; + $elements = $cVal->getRichTextElements(); + foreach ($elements as $element) { + // FONT Index + if ($element instanceof PHPExcel_RichText_Run) { + $str_fontidx = $this->fontHashIndex[$element->getFont()->getHashCode()]; + } else { + $str_fontidx = 0; + } + $arrcRun[] = array('strlen' => $str_pos, 'fontidx' => $str_fontidx); + // Position FROM + $str_pos += PHPExcel_Shared_String::CountCharacters($element->getText(), 'UTF-8'); + } + $this->writeRichTextString($row, $column, $cVal->getPlainText(), $xfIndex, $arrcRun); + } else { + switch ($cell->getDatatype()) { + case PHPExcel_Cell_DataType::TYPE_STRING: + case PHPExcel_Cell_DataType::TYPE_NULL: + if ($cVal === '' || $cVal === null) { + $this->writeBlank($row, $column, $xfIndex); + } else { + $this->writeString($row, $column, $cVal, $xfIndex); + } + break; + + case PHPExcel_Cell_DataType::TYPE_NUMERIC: + $this->writeNumber($row, $column, $cVal, $xfIndex); + break; + + case PHPExcel_Cell_DataType::TYPE_FORMULA: + $calculatedValue = $this->_preCalculateFormulas ? + $cell->getCalculatedValue() : null; + $this->writeFormula($row, $column, $cVal, $xfIndex, $calculatedValue); + break; + + case PHPExcel_Cell_DataType::TYPE_BOOL: + $this->writeBoolErr($row, $column, $cVal, 0, $xfIndex); + break; + + case PHPExcel_Cell_DataType::TYPE_ERROR: + $this->writeBoolErr($row, $column, self::mapErrorCode($cVal), 1, $xfIndex); + break; + + } + } + } + + // Append + $this->writeMsoDrawing(); + + // Write WINDOW2 record + $this->writeWindow2(); + + // Write PLV record + $this->writePageLayoutView(); + + // Write ZOOM record + $this->writeZoom(); + if ($phpSheet->getFreezePane()) { + $this->writePanes(); + } + + // Write SELECTION record + $this->writeSelection(); + + // Write MergedCellsTable Record + $this->writeMergedCells(); + + // Hyperlinks + foreach ($phpSheet->getHyperLinkCollection() as $coordinate => $hyperlink) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($coordinate); + + $url = $hyperlink->getUrl(); + + if (strpos($url, 'sheet://') !== false) { + // internal to current workbook + $url = str_replace('sheet://', 'internal:', $url); + + } elseif (preg_match('/^(http:|https:|ftp:|mailto:)/', $url)) { + // URL + // $url = $url; + + } else { + // external (local file) + $url = 'external:' . $url; + } + + $this->writeUrl($row - 1, PHPExcel_Cell::columnIndexFromString($column) - 1, $url); + } + + $this->writeDataValidity(); + $this->writeSheetLayout(); + + // Write SHEETPROTECTION record + $this->writeSheetProtection(); + $this->writeRangeProtection(); + + $arrConditionalStyles = $phpSheet->getConditionalStylesCollection(); + if (!empty($arrConditionalStyles)) { + $arrConditional = array(); + // @todo CFRule & CFHeader + // Write CFHEADER record + $this->writeCFHeader(); + // Write ConditionalFormattingTable records + foreach ($arrConditionalStyles as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) { + if (!in_array($conditional->getHashCode(), $arrConditional)) { + $arrConditional[] = $conditional->getHashCode(); + // Write CFRULE record + $this->writeCFRule($conditional); + } + } + } + } + } + + $this->storeEof(); + } + + /** + * Write a cell range address in BIFF8 + * always fixed range + * See section 2.5.14 in OpenOffice.org's Documentation of the Microsoft Excel File Format + * + * @param string $range E.g. 'A1' or 'A1:B6' + * @return string Binary data + */ + private function writeBIFF8CellRangeAddressFixed($range = 'A1') + { + $explodes = explode(':', $range); + + // extract first cell, e.g. 'A1' + $firstCell = $explodes[0]; + + // extract last cell, e.g. 'B6' + if (count($explodes) == 1) { + $lastCell = $firstCell; + } else { + $lastCell = $explodes[1]; + } + + $firstCellCoordinates = PHPExcel_Cell::coordinateFromString($firstCell); // e.g. array(0, 1) + $lastCellCoordinates = PHPExcel_Cell::coordinateFromString($lastCell); // e.g. array(1, 6) + + return pack('vvvv', $firstCellCoordinates[1] - 1, $lastCellCoordinates[1] - 1, PHPExcel_Cell::columnIndexFromString($firstCellCoordinates[0]) - 1, PHPExcel_Cell::columnIndexFromString($lastCellCoordinates[0]) - 1); + } + + /** + * Retrieves data from memory in one chunk, or from disk in $buffer + * sized chunks. + * + * @return string The data + */ + public function getData() + { + $buffer = 4096; + + // Return data stored in memory + if (isset($this->_data)) { + $tmp = $this->_data; + unset($this->_data); + return $tmp; + } + // No data to return + return false; + } + + /** + * Set the option to print the row and column headers on the printed page. + * + * @access public + * @param integer $print Whether to print the headers or not. Defaults to 1 (print). + */ + public function printRowColHeaders($print = 1) + { + $this->_print_headers = $print; + } + + /** + * This method sets the properties for outlining and grouping. The defaults + * correspond to Excel's defaults. + * + * @param bool $visible + * @param bool $symbols_below + * @param bool $symbols_right + * @param bool $auto_style + */ + public function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false) + { + $this->outlineOn = $visible; + $this->outlineBelow = $symbols_below; + $this->outlineRight = $symbols_right; + $this->outlineStyle = $auto_style; + + // Ensure this is a boolean vale for Window2 + if ($this->outlineOn) { + $this->outlineOn = 1; + } + } + + /** + * Write a double to the specified row and column (zero indexed). + * An integer can be written as a double. Excel will display an + * integer. $format is optional. + * + * Returns 0 : normal termination + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param float $num The number to write + * @param mixed $xfIndex The optional XF format + * @return integer + */ + private function writeNumber($row, $col, $num, $xfIndex) + { + $record = 0x0203; // Record identifier + $length = 0x000E; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $xfIndex); + $xl_double = pack("d", $num); + if (self::getByteOrder()) { // if it's Big Endian + $xl_double = strrev($xl_double); + } + + $this->append($header.$data.$xl_double); + return(0); + } + + /** + * Write a LABELSST record or a LABEL record. Which one depends on BIFF version + * + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param string $str The string + * @param int $xfIndex Index to XF record + */ + private function writeString($row, $col, $str, $xfIndex) + { + $this->writeLabelSst($row, $col, $str, $xfIndex); + } + + /** + * Write a LABELSST record or a LABEL record. Which one depends on BIFF version + * It differs from writeString by the writing of rich text strings. + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param string $str The string + * @param mixed $xfIndex The XF format index for the cell + * @param array $arrcRun Index to Font record and characters beginning + */ + private function writeRichTextString($row, $col, $str, $xfIndex, $arrcRun) + { + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow + $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeShort($str, $arrcRun); + + /* check if string is already present */ + if (!isset($this->stringTable[$str])) { + $this->stringTable[$str] = $this->stringUnique++; + } + $this->stringTotal++; + + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); + $this->append($header.$data); + } + + /** + * Write a string to the specified row and column (zero indexed). + * NOTE: there is an Excel 5 defined limit of 255 characters. + * $format is optional. + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @access public + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $str The string to write + * @param mixed $xfIndex The XF format index for the cell + * @return integer + */ + private function writeLabel($row, $col, $str, $xfIndex) + { + $strlen = strlen($str); + $record = 0x0204; // Record identifier + $length = 0x0008 + $strlen; // Bytes to follow + + $str_error = 0; + + if ($strlen > $this->xlsStringMaxLength) { // LABEL must be < 255 chars + $str = substr($str, 0, $this->xlsStringMaxLength); + $length = 0x0008 + $this->xlsStringMaxLength; + $strlen = $this->xlsStringMaxLength; + $str_error = -3; + } + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row, $col, $xfIndex, $strlen); + $this->append($header . $data . $str); + return($str_error); + } + + /** + * Write a string to the specified row and column (zero indexed). + * This is the BIFF8 version (no 255 chars limit). + * $format is optional. + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @access public + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $str The string to write + * @param mixed $xfIndex The XF format index for the cell + * @return integer + */ + private function writeLabelSst($row, $col, $str, $xfIndex) + { + $record = 0x00FD; // Record identifier + $length = 0x000A; // Bytes to follow + + $str = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($str); + + /* check if string is already present */ + if (!isset($this->stringTable[$str])) { + $this->stringTable[$str] = $this->stringUnique++; + } + $this->stringTotal++; + + $header = pack('vv', $record, $length); + $data = pack('vvvV', $row, $col, $xfIndex, $this->stringTable[$str]); + $this->append($header.$data); + } + + /** + * Writes a note associated with the cell given by the row and column. + * NOTE records don't have a length limit. + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $note The note to write + */ + private function writeNote($row, $col, $note) + { + $note_length = strlen($note); + $record = 0x001C; // Record identifier + $max_length = 2048; // Maximun length for a NOTE record + + // Length for this record is no more than 2048 + 6 + $length = 0x0006 + min($note_length, 2048); + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $note_length); + $this->append($header . $data . substr($note, 0, 2048)); + + for ($i = $max_length; $i < $note_length; $i += $max_length) { + $chunk = substr($note, $i, $max_length); + $length = 0x0006 + strlen($chunk); + $header = pack("vv", $record, $length); + $data = pack("vvv", -1, 0, strlen($chunk)); + $this->append($header.$data.$chunk); + } + return(0); + } + + /** + * Write a blank cell to the specified row and column (zero indexed). + * A blank cell is used to specify formatting without adding a string + * or a number. + * + * A blank cell without a format serves no purpose. Therefore, we don't write + * a BLANK record unless a format is specified. + * + * Returns 0 : normal termination (including no format) + * -1 : insufficient number of arguments + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param mixed $xfIndex The XF format index + */ + public function writeBlank($row, $col, $xfIndex) + { + $record = 0x0201; // Record identifier + $length = 0x0006; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vvv", $row, $col, $xfIndex); + $this->append($header . $data); + return 0; + } + + /** + * Write a boolean or an error type to the specified row and column (zero indexed) + * + * @param int $row Row index (0-based) + * @param int $col Column index (0-based) + * @param int $value + * @param boolean $isError Error or Boolean? + * @param int $xfIndex + */ + private function writeBoolErr($row, $col, $value, $isError, $xfIndex) + { + $record = 0x0205; + $length = 8; + + $header = pack("vv", $record, $length); + $data = pack("vvvCC", $row, $col, $xfIndex, $value, $isError); + $this->append($header . $data); + return 0; + } + + /** + * Write a formula to the specified row and column (zero indexed). + * The textual representation of the formula is passed to the parser in + * Parser.php which returns a packed binary string. + * + * Returns 0 : normal termination + * -1 : formula errors (bad formula) + * -2 : row or column out of range + * + * @param integer $row Zero indexed row + * @param integer $col Zero indexed column + * @param string $formula The formula text string + * @param mixed $xfIndex The XF format index + * @param mixed $calculatedValue Calculated value + * @return integer + */ + private function writeFormula($row, $col, $formula, $xfIndex, $calculatedValue) + { + $record = 0x0006; // Record identifier + + // Initialize possible additional value for STRING record that should be written after the FORMULA record? + $stringValue = null; + + // calculated value + if (isset($calculatedValue)) { + // Since we can't yet get the data type of the calculated value, + // we use best effort to determine data type + if (is_bool($calculatedValue)) { + // Boolean value + $num = pack('CCCvCv', 0x01, 0x00, (int)$calculatedValue, 0x00, 0x00, 0xFFFF); + } elseif (is_int($calculatedValue) || is_float($calculatedValue)) { + // Numeric value + $num = pack('d', $calculatedValue); + } elseif (is_string($calculatedValue)) { + if (array_key_exists($calculatedValue, PHPExcel_Cell_DataType::getErrorCodes())) { + // Error value + $num = pack('CCCvCv', 0x02, 0x00, self::mapErrorCode($calculatedValue), 0x00, 0x00, 0xFFFF); + } elseif ($calculatedValue === '') { + // Empty string (and BIFF8) + $num = pack('CCCvCv', 0x03, 0x00, 0x00, 0x00, 0x00, 0xFFFF); + } else { + // Non-empty string value (or empty string BIFF5) + $stringValue = $calculatedValue; + $num = pack('CCCvCv', 0x00, 0x00, 0x00, 0x00, 0x00, 0xFFFF); + } + } else { + // We are really not supposed to reach here + $num = pack('d', 0x00); + } + } else { + $num = pack('d', 0x00); + } + + $grbit = 0x03; // Option flags + $unknown = 0x0000; // Must be zero + + // Strip the '=' or '@' sign at the beginning of the formula string + if ($formula{0} == '=') { + $formula = substr($formula, 1); + } else { + // Error handling + $this->writeString($row, $col, 'Unrecognised character for formula'); + return -1; + } + + // Parse the formula using the parser in Parser.php + try { + $error = $this->parser->parse($formula); + $formula = $this->parser->toReversePolish(); + + $formlen = strlen($formula); // Length of the binary string + $length = 0x16 + $formlen; // Length of the record data + + $header = pack("vv", $record, $length); + + $data = pack("vvv", $row, $col, $xfIndex) + . $num + . pack("vVv", $grbit, $unknown, $formlen); + $this->append($header . $data . $formula); + + // Append also a STRING record if necessary + if ($stringValue !== null) { + $this->writeStringRecord($stringValue); + } + + return 0; + + } catch (PHPExcel_Exception $e) { + // do nothing + } + + } + + /** + * Write a STRING record. This + * + * @param string $stringValue + */ + private function writeStringRecord($stringValue) + { + $record = 0x0207; // Record identifier + $data = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($stringValue); + + $length = strlen($data); + $header = pack('vv', $record, $length); + + $this->append($header . $data); + } + + /** + * Write a hyperlink. + * This is comprised of two elements: the visible label and + * the invisible link. The visible label is the same as the link unless an + * alternative string is specified. The label is written using the + * writeString() method. Therefore the 255 characters string limit applies. + * $string and $format are optional. + * + * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external + * directory url. + * + * Returns 0 : normal termination + * -2 : row or column out of range + * -3 : long string truncated to 255 chars + * + * @param integer $row Row + * @param integer $col Column + * @param string $url URL string + * @return integer + */ + private function writeUrl($row, $col, $url) + { + // Add start row and col to arg list + return($this->writeUrlRange($row, $col, $row, $col, $url)); + } + + /** + * This is the more general form of writeUrl(). It allows a hyperlink to be + * written to a range of cells. This function also decides the type of hyperlink + * to be written. These are either, Web (http, ftp, mailto), Internal + * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). + * + * @access private + * @see writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + public function writeUrlRange($row1, $col1, $row2, $col2, $url) + { + // Check for internal/external sheet links or default to web link + if (preg_match('[^internal:]', $url)) { + return($this->writeUrlInternal($row1, $col1, $row2, $col2, $url)); + } + if (preg_match('[^external:]', $url)) { + return($this->writeUrlExternal($row1, $col1, $row2, $col2, $url)); + } + return($this->writeUrlWeb($row1, $col1, $row2, $col2, $url)); + } + + /** + * Used to write http, ftp and mailto hyperlinks. + * The link type ($options) is 0x03 is the same as absolute dir ref without + * sheet. However it is differentiated by the $unknown2 data stream. + * + * @access private + * @see writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + public function writeUrlWeb($row1, $col1, $row2, $col2, $url) + { + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); + $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B"); + + // Pack the option flags + $options = pack("V", 0x03); + + // Convert URL to a null terminated wchar string + $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); + $url = $url . "\0\0\0"; + + // Pack the length of the URL + $url_len = pack("V", strlen($url)); + + // Calculate the data length + $length = 0x34 + strlen($url); + + // Pack the header data + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row1, $row2, $col1, $col2); + + // Write the packed data + $this->append($header . $data . + $unknown1 . $options . + $unknown2 . $url_len . $url); + return 0; + } + + /** + * Used to write internal reference hyperlinks such as "Sheet1!A1". + * + * @access private + * @see writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + public function writeUrlInternal($row1, $col1, $row2, $col2, $url) + { + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Strip URL type + $url = preg_replace('/^internal:/', '', $url); + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); + + // Pack the option flags + $options = pack("V", 0x08); + + // Convert the URL type and to a null terminated wchar string + $url .= "\0"; + + // character count + $url_len = PHPExcel_Shared_String::CountCharacters($url); + $url_len = pack('V', $url_len); + + $url = PHPExcel_Shared_String::ConvertEncoding($url, 'UTF-16LE', 'UTF-8'); + + // Calculate the data length + $length = 0x24 + strlen($url); + + // Pack the header data + $header = pack("vv", $record, $length); + $data = pack("vvvv", $row1, $row2, $col1, $col2); + + // Write the packed data + $this->append($header . $data . + $unknown1 . $options . + $url_len . $url); + return 0; + } + + /** + * Write links to external directory names such as 'c:\foo.xls', + * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'. + * + * Note: Excel writes some relative links with the $dir_long string. We ignore + * these cases for the sake of simpler code. + * + * @access private + * @see writeUrl() + * @param integer $row1 Start row + * @param integer $col1 Start column + * @param integer $row2 End row + * @param integer $col2 End column + * @param string $url URL string + * @return integer + */ + public function writeUrlExternal($row1, $col1, $row2, $col2, $url) + { + // Network drives are different. We will handle them separately + // MS/Novell network drives and shares start with \\ + if (preg_match('[^external:\\\\]', $url)) { + return; //($this->writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); + } + + $record = 0x01B8; // Record identifier + $length = 0x00000; // Bytes to follow + + // Strip URL type and change Unix dir separator to Dos style (if needed) + // + $url = preg_replace('/^external:/', '', $url); + $url = preg_replace('/\//', "\\", $url); + + // Determine if the link is relative or absolute: + // relative if link contains no dir separator, "somefile.xls" + // relative if link starts with up-dir, "..\..\somefile.xls" + // otherwise, absolute + + $absolute = 0x00; // relative path + if (preg_match('/^[A-Z]:/', $url)) { + $absolute = 0x02; // absolute path on Windows, e.g. C:\... + } + $link_type = 0x01 | $absolute; + + // Determine if the link contains a sheet reference and change some of the + // parameters accordingly. + // Split the dir name and sheet name (if it exists) + $dir_long = $url; + if (preg_match("/\#/", $url)) { + $link_type |= 0x08; + } + + + // Pack the link type + $link_type = pack("V", $link_type); + + // Calculate the up-level dir count e.g.. (..\..\..\ == 3) + $up_count = preg_match_all("/\.\.\\\/", $dir_long, $useless); + $up_count = pack("v", $up_count); + + // Store the short dos dir name (null terminated) + $dir_short = preg_replace("/\.\.\\\/", '', $dir_long) . "\0"; + + // Store the long dir name as a wchar string (non-null terminated) + $dir_long = $dir_long . "\0"; + + // Pack the lengths of the dir strings + $dir_short_len = pack("V", strlen($dir_short)); + $dir_long_len = pack("V", strlen($dir_long)); + $stream_len = pack("V", 0); //strlen($dir_long) + 0x06); + + // Pack the undocumented parts of the hyperlink stream + $unknown1 = pack("H*", 'D0C9EA79F9BACE118C8200AA004BA90B02000000'); + $unknown2 = pack("H*", '0303000000000000C000000000000046'); + $unknown3 = pack("H*", 'FFFFADDE000000000000000000000000000000000000000'); + $unknown4 = pack("v", 0x03); + + // Pack the main data stream + $data = pack("vvvv", $row1, $row2, $col1, $col2) . + $unknown1 . + $link_type . + $unknown2 . + $up_count . + $dir_short_len. + $dir_short . + $unknown3 . + $stream_len ;/*. + $dir_long_len . + $unknown4 . + $dir_long . + $sheet_len . + $sheet ;*/ + + // Pack the header data + $length = strlen($data); + $header = pack("vv", $record, $length); + + // Write the packed data + $this->append($header. $data); + return 0; + } + + /** + * This method is used to set the height and format for a row. + * + * @param integer $row The row to set + * @param integer $height Height we are giving to the row. + * Use null to set XF without setting height + * @param integer $xfIndex The optional cell style Xf index to apply to the columns + * @param bool $hidden The optional hidden attribute + * @param integer $level The optional outline level for row, in range [0,7] + */ + private function writeRow($row, $height, $xfIndex, $hidden = false, $level = 0) + { + $record = 0x0208; // Record identifier + $length = 0x0010; // Number of bytes to follow + + $colMic = 0x0000; // First defined column + $colMac = 0x0000; // Last defined column + $irwMac = 0x0000; // Used by Excel to optimise loading + $reserved = 0x0000; // Reserved + $grbit = 0x0000; // Option flags + $ixfe = $xfIndex; + + if ($height < 0) { + $height = null; + } + + // Use writeRow($row, null, $XF) to set XF format without setting height + if ($height != null) { + $miyRw = $height * 20; // row height + } else { + $miyRw = 0xff; // default row height is 256 + } + + // Set the options flags. fUnsynced is used to show that the font and row + // heights are not compatible. This is usually the case for WriteExcel. + // The collapsed flag 0x10 doesn't seem to be used to indicate that a row + // is collapsed. Instead it is used to indicate that the previous row is + // collapsed. The zero height flag, 0x20, is used to collapse a row. + + $grbit |= $level; + if ($hidden) { + $grbit |= 0x0030; + } + if ($height !== null) { + $grbit |= 0x0040; // fUnsynced + } + if ($xfIndex !== 0xF) { + $grbit |= 0x0080; + } + $grbit |= 0x0100; + + $header = pack("vv", $record, $length); + $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw, $irwMac, $reserved, $grbit, $ixfe); + $this->append($header.$data); + } + + /** + * Writes Excel DIMENSIONS to define the area in which there is data. + */ + private function writeDimensions() + { + $record = 0x0200; // Record identifier + + $length = 0x000E; + $data = pack('VVvvv', $this->firstRowIndex, $this->lastRowIndex + 1, $this->firstColumnIndex, $this->lastColumnIndex + 1, 0x0000); // reserved + + $header = pack("vv", $record, $length); + $this->append($header.$data); + } + + /** + * Write BIFF record Window2. + */ + private function writeWindow2() + { + $record = 0x023E; // Record identifier + $length = 0x0012; + + $grbit = 0x00B6; // Option flags + $rwTop = 0x0000; // Top row visible in window + $colLeft = 0x0000; // Leftmost column visible in window + + + // The options flags that comprise $grbit + $fDspFmla = 0; // 0 - bit + $fDspGrid = $this->phpSheet->getShowGridlines() ? 1 : 0; // 1 + $fDspRwCol = $this->phpSheet->getShowRowColHeaders() ? 1 : 0; // 2 + $fFrozen = $this->phpSheet->getFreezePane() ? 1 : 0; // 3 + $fDspZeros = 1; // 4 + $fDefaultHdr = 1; // 5 + $fArabic = $this->phpSheet->getRightToLeft() ? 1 : 0; // 6 + $fDspGuts = $this->outlineOn; // 7 + $fFrozenNoSplit = 0; // 0 - bit + // no support in PHPExcel for selected sheet, therefore sheet is only selected if it is the active sheet + $fSelected = ($this->phpSheet === $this->phpSheet->getParent()->getActiveSheet()) ? 1 : 0; + $fPaged = 1; // 2 + $fPageBreakPreview = $this->phpSheet->getSheetView()->getView() === PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_BREAK_PREVIEW; + + $grbit = $fDspFmla; + $grbit |= $fDspGrid << 1; + $grbit |= $fDspRwCol << 2; + $grbit |= $fFrozen << 3; + $grbit |= $fDspZeros << 4; + $grbit |= $fDefaultHdr << 5; + $grbit |= $fArabic << 6; + $grbit |= $fDspGuts << 7; + $grbit |= $fFrozenNoSplit << 8; + $grbit |= $fSelected << 9; + $grbit |= $fPaged << 10; + $grbit |= $fPageBreakPreview << 11; + + $header = pack("vv", $record, $length); + $data = pack("vvv", $grbit, $rwTop, $colLeft); + + // FIXME !!! + $rgbHdr = 0x0040; // Row/column heading and gridline color index + $zoom_factor_page_break = ($fPageBreakPreview ? $this->phpSheet->getSheetView()->getZoomScale() : 0x0000); + $zoom_factor_normal = $this->phpSheet->getSheetView()->getZoomScaleNormal(); + + $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); + + $this->append($header.$data); + } + + /** + * Write BIFF record DEFAULTROWHEIGHT. + */ + private function writeDefaultRowHeight() + { + $defaultRowHeight = $this->phpSheet->getDefaultRowDimension()->getRowHeight(); + + if ($defaultRowHeight < 0) { + return; + } + + // convert to twips + $defaultRowHeight = (int) 20 * $defaultRowHeight; + + $record = 0x0225; // Record identifier + $length = 0x0004; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", 1, $defaultRowHeight); + $this->append($header . $data); + } + + /** + * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. + */ + private function writeDefcol() + { + $defaultColWidth = 8; + + $record = 0x0055; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $defaultColWidth); + $this->append($header . $data); + } + + /** + * Write BIFF record COLINFO to define column widths + * + * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C + * length record. + * + * @param array $col_array This is the only parameter received and is composed of the following: + * 0 => First formatted column, + * 1 => Last formatted column, + * 2 => Col width (8.43 is Excel default), + * 3 => The optional XF format of the column, + * 4 => Option flags. + * 5 => Optional outline level + */ + private function writeColinfo($col_array) + { + if (isset($col_array[0])) { + $colFirst = $col_array[0]; + } + if (isset($col_array[1])) { + $colLast = $col_array[1]; + } + if (isset($col_array[2])) { + $coldx = $col_array[2]; + } else { + $coldx = 8.43; + } + if (isset($col_array[3])) { + $xfIndex = $col_array[3]; + } else { + $xfIndex = 15; + } + if (isset($col_array[4])) { + $grbit = $col_array[4]; + } else { + $grbit = 0; + } + if (isset($col_array[5])) { + $level = $col_array[5]; + } else { + $level = 0; + } + $record = 0x007D; // Record identifier + $length = 0x000C; // Number of bytes to follow + + $coldx *= 256; // Convert to units of 1/256 of a char + + $ixfe = $xfIndex; + $reserved = 0x0000; // Reserved + + $level = max(0, min($level, 7)); + $grbit |= $level << 8; + + $header = pack("vv", $record, $length); + $data = pack("vvvvvv", $colFirst, $colLast, $coldx, $ixfe, $grbit, $reserved); + $this->append($header.$data); + } + + /** + * Write BIFF record SELECTION. + */ + private function writeSelection() + { + // look up the selected cell range + $selectedCells = $this->phpSheet->getSelectedCells(); + $selectedCells = PHPExcel_Cell::splitRange($this->phpSheet->getSelectedCells()); + $selectedCells = $selectedCells[0]; + if (count($selectedCells) == 2) { + list($first, $last) = $selectedCells; + } else { + $first = $selectedCells[0]; + $last = $selectedCells[0]; + } + + list($colFirst, $rwFirst) = PHPExcel_Cell::coordinateFromString($first); + $colFirst = PHPExcel_Cell::columnIndexFromString($colFirst) - 1; // base 0 column index + --$rwFirst; // base 0 row index + + list($colLast, $rwLast) = PHPExcel_Cell::coordinateFromString($last); + $colLast = PHPExcel_Cell::columnIndexFromString($colLast) - 1; // base 0 column index + --$rwLast; // base 0 row index + + // make sure we are not out of bounds + $colFirst = min($colFirst, 255); + $colLast = min($colLast, 255); + + $rwFirst = min($rwFirst, 65535); + $rwLast = min($rwLast, 65535); + + $record = 0x001D; // Record identifier + $length = 0x000F; // Number of bytes to follow + + $pnn = $this->activePane; // Pane position + $rwAct = $rwFirst; // Active row + $colAct = $colFirst; // Active column + $irefAct = 0; // Active cell ref + $cref = 1; // Number of refs + + if (!isset($rwLast)) { + $rwLast = $rwFirst; // Last row in reference + } + if (!isset($colLast)) { + $colLast = $colFirst; // Last col in reference + } + + // Swap last row/col for first row/col as necessary + if ($rwFirst > $rwLast) { + list($rwFirst, $rwLast) = array($rwLast, $rwFirst); + } + + if ($colFirst > $colLast) { + list($colFirst, $colLast) = array($colLast, $colFirst); + } + + $header = pack("vv", $record, $length); + $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct, $irefAct, $cref, $rwFirst, $rwLast, $colFirst, $colLast); + $this->append($header . $data); + } + + /** + * Store the MERGEDCELLS records for all ranges of merged cells + */ + private function writeMergedCells() + { + $mergeCells = $this->phpSheet->getMergeCells(); + $countMergeCells = count($mergeCells); + + if ($countMergeCells == 0) { + return; + } + + // maximum allowed number of merged cells per record + $maxCountMergeCellsPerRecord = 1027; + + // record identifier + $record = 0x00E5; + + // counter for total number of merged cells treated so far by the writer + $i = 0; + + // counter for number of merged cells written in record currently being written + $j = 0; + + // initialize record data + $recordData = ''; + + // loop through the merged cells + foreach ($mergeCells as $mergeCell) { + ++$i; + ++$j; + + // extract the row and column indexes + $range = PHPExcel_Cell::splitRange($mergeCell); + list($first, $last) = $range[0]; + list($firstColumn, $firstRow) = PHPExcel_Cell::coordinateFromString($first); + list($lastColumn, $lastRow) = PHPExcel_Cell::coordinateFromString($last); + + $recordData .= pack('vvvv', $firstRow - 1, $lastRow - 1, PHPExcel_Cell::columnIndexFromString($firstColumn) - 1, PHPExcel_Cell::columnIndexFromString($lastColumn) - 1); + + // flush record if we have reached limit for number of merged cells, or reached final merged cell + if ($j == $maxCountMergeCellsPerRecord or $i == $countMergeCells) { + $recordData = pack('v', $j) . $recordData; + $length = strlen($recordData); + $header = pack('vv', $record, $length); + $this->append($header . $recordData); + + // initialize for next record, if any + $recordData = ''; + $j = 0; + } + } + } + + /** + * Write SHEETLAYOUT record + */ + private function writeSheetLayout() + { + if (!$this->phpSheet->isTabColorSet()) { + return; + } + + $recordData = pack( + 'vvVVVvv', + 0x0862, + 0x0000, // unused + 0x00000000, // unused + 0x00000000, // unused + 0x00000014, // size of record data + $this->colors[$this->phpSheet->getTabColor()->getRGB()], // color index + 0x0000 // unused + ); + + $length = strlen($recordData); + + $record = 0x0862; // Record identifier + $header = pack('vv', $record, $length); + $this->append($header . $recordData); + } + + /** + * Write SHEETPROTECTION + */ + private function writeSheetProtection() + { + // record identifier + $record = 0x0867; + + // prepare options + $options = (int) !$this->phpSheet->getProtection()->getObjects() + | (int) !$this->phpSheet->getProtection()->getScenarios() << 1 + | (int) !$this->phpSheet->getProtection()->getFormatCells() << 2 + | (int) !$this->phpSheet->getProtection()->getFormatColumns() << 3 + | (int) !$this->phpSheet->getProtection()->getFormatRows() << 4 + | (int) !$this->phpSheet->getProtection()->getInsertColumns() << 5 + | (int) !$this->phpSheet->getProtection()->getInsertRows() << 6 + | (int) !$this->phpSheet->getProtection()->getInsertHyperlinks() << 7 + | (int) !$this->phpSheet->getProtection()->getDeleteColumns() << 8 + | (int) !$this->phpSheet->getProtection()->getDeleteRows() << 9 + | (int) !$this->phpSheet->getProtection()->getSelectLockedCells() << 10 + | (int) !$this->phpSheet->getProtection()->getSort() << 11 + | (int) !$this->phpSheet->getProtection()->getAutoFilter() << 12 + | (int) !$this->phpSheet->getProtection()->getPivotTables() << 13 + | (int) !$this->phpSheet->getProtection()->getSelectUnlockedCells() << 14 ; + + // record data + $recordData = pack( + 'vVVCVVvv', + 0x0867, // repeated record identifier + 0x0000, // not used + 0x0000, // not used + 0x00, // not used + 0x01000200, // unknown data + 0xFFFFFFFF, // unknown data + $options, // options + 0x0000 // not used + ); + + $length = strlen($recordData); + $header = pack('vv', $record, $length); + + $this->append($header . $recordData); + } + + /** + * Write BIFF record RANGEPROTECTION + * + * Openoffice.org's Documentaion of the Microsoft Excel File Format uses term RANGEPROTECTION for these records + * Microsoft Office Excel 97-2007 Binary File Format Specification uses term FEAT for these records + */ + private function writeRangeProtection() + { + foreach ($this->phpSheet->getProtectedCells() as $range => $password) { + // number of ranges, e.g. 'A1:B3 C20:D25' + $cellRanges = explode(' ', $range); + $cref = count($cellRanges); + + $recordData = pack( + 'vvVVvCVvVv', + 0x0868, + 0x00, + 0x0000, + 0x0000, + 0x02, + 0x0, + 0x0000, + $cref, + 0x0000, + 0x00 + ); + + foreach ($cellRanges as $cellRange) { + $recordData .= $this->writeBIFF8CellRangeAddressFixed($cellRange); + } + + // the rgbFeat structure + $recordData .= pack( + 'VV', + 0x0000, + hexdec($password) + ); + + $recordData .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong('p' . md5($recordData)); + + $length = strlen($recordData); + + $record = 0x0868; // Record identifier + $header = pack("vv", $record, $length); + $this->append($header . $recordData); + } + } + + /** + * Write BIFF record EXTERNCOUNT to indicate the number of external sheet + * references in a worksheet. + * + * Excel only stores references to external sheets that are used in formulas. + * For simplicity we store references to all the sheets in the workbook + * regardless of whether they are used or not. This reduces the overall + * complexity and eliminates the need for a two way dialogue between the formula + * parser the worksheet objects. + * + * @param integer $count The number of external sheet references in this worksheet + */ + private function writeExterncount($count) + { + $record = 0x0016; // Record identifier + $length = 0x0002; // Number of bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $count); + $this->append($header . $data); + } + + /** + * Writes the Excel BIFF EXTERNSHEET record. These references are used by + * formulas. A formula references a sheet name via an index. Since we store a + * reference to all of the external worksheets the EXTERNSHEET index is the same + * as the worksheet index. + * + * @param string $sheetname The name of a external worksheet + */ + private function writeExternsheet($sheetname) + { + $record = 0x0017; // Record identifier + + // References to the current sheet are encoded differently to references to + // external sheets. + // + if ($this->phpSheet->getTitle() == $sheetname) { + $sheetname = ''; + $length = 0x02; // The following 2 bytes + $cch = 1; // The following byte + $rgch = 0x02; // Self reference + } else { + $length = 0x02 + strlen($sheetname); + $cch = strlen($sheetname); + $rgch = 0x03; // Reference to a sheet in the current workbook + } + + $header = pack("vv", $record, $length); + $data = pack("CC", $cch, $rgch); + $this->append($header . $data . $sheetname); + } + + /** + * Writes the Excel BIFF PANE record. + * The panes can either be frozen or thawed (unfrozen). + * Frozen panes are specified in terms of an integer number of rows and columns. + * Thawed panes are specified in terms of Excel's units for rows and columns. + */ + private function writePanes() + { + $panes = array(); + if ($freezePane = $this->phpSheet->getFreezePane()) { + list($column, $row) = PHPExcel_Cell::coordinateFromString($freezePane); + $panes[0] = $row - 1; + $panes[1] = PHPExcel_Cell::columnIndexFromString($column) - 1; + } else { + // thaw panes + return; + } + + $y = isset($panes[0]) ? $panes[0] : null; + $x = isset($panes[1]) ? $panes[1] : null; + $rwTop = isset($panes[2]) ? $panes[2] : null; + $colLeft = isset($panes[3]) ? $panes[3] : null; + if (count($panes) > 4) { // if Active pane was received + $pnnAct = $panes[4]; + } else { + $pnnAct = null; + } + $record = 0x0041; // Record identifier + $length = 0x000A; // Number of bytes to follow + + // Code specific to frozen or thawed panes. + if ($this->phpSheet->getFreezePane()) { + // Set default values for $rwTop and $colLeft + if (!isset($rwTop)) { + $rwTop = $y; + } + if (!isset($colLeft)) { + $colLeft = $x; + } + } else { + // Set default values for $rwTop and $colLeft + if (!isset($rwTop)) { + $rwTop = 0; + } + if (!isset($colLeft)) { + $colLeft = 0; + } + + // Convert Excel's row and column units to the internal units. + // The default row height is 12.75 + // The default column width is 8.43 + // The following slope and intersection values were interpolated. + // + $y = 20*$y + 255; + $x = 113.879*$x + 390; + } + + + // Determine which pane should be active. There is also the undocumented + // option to override this should it be necessary: may be removed later. + // + if (!isset($pnnAct)) { + if ($x != 0 && $y != 0) { + $pnnAct = 0; // Bottom right + } + if ($x != 0 && $y == 0) { + $pnnAct = 1; // Top right + } + if ($x == 0 && $y != 0) { + $pnnAct = 2; // Bottom left + } + if ($x == 0 && $y == 0) { + $pnnAct = 3; // Top left + } + } + + $this->activePane = $pnnAct; // Used in writeSelection + + $header = pack("vv", $record, $length); + $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct); + $this->append($header . $data); + } + + /** + * Store the page setup SETUP BIFF record. + */ + private function writeSetup() + { + $record = 0x00A1; // Record identifier + $length = 0x0022; // Number of bytes to follow + + $iPaperSize = $this->phpSheet->getPageSetup()->getPaperSize(); // Paper size + + $iScale = $this->phpSheet->getPageSetup()->getScale() ? + $this->phpSheet->getPageSetup()->getScale() : 100; // Print scaling factor + + $iPageStart = 0x01; // Starting page number + $iFitWidth = (int) $this->phpSheet->getPageSetup()->getFitToWidth(); // Fit to number of pages wide + $iFitHeight = (int) $this->phpSheet->getPageSetup()->getFitToHeight(); // Fit to number of pages high + $grbit = 0x00; // Option flags + $iRes = 0x0258; // Print resolution + $iVRes = 0x0258; // Vertical print resolution + + $numHdr = $this->phpSheet->getPageMargins()->getHeader(); // Header Margin + + $numFtr = $this->phpSheet->getPageMargins()->getFooter(); // Footer Margin + $iCopies = 0x01; // Number of copies + + $fLeftToRight = 0x0; // Print over then down + + // Page orientation + $fLandscape = ($this->phpSheet->getPageSetup()->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? + 0x0 : 0x1; + + $fNoPls = 0x0; // Setup not read from printer + $fNoColor = 0x0; // Print black and white + $fDraft = 0x0; // Print draft quality + $fNotes = 0x0; // Print notes + $fNoOrient = 0x0; // Orientation not set + $fUsePage = 0x0; // Use custom starting page + + $grbit = $fLeftToRight; + $grbit |= $fLandscape << 1; + $grbit |= $fNoPls << 2; + $grbit |= $fNoColor << 3; + $grbit |= $fDraft << 4; + $grbit |= $fNotes << 5; + $grbit |= $fNoOrient << 6; + $grbit |= $fUsePage << 7; + + $numHdr = pack("d", $numHdr); + $numFtr = pack("d", $numFtr); + if (self::getByteOrder()) { // if it's Big Endian + $numHdr = strrev($numHdr); + $numFtr = strrev($numFtr); + } + + $header = pack("vv", $record, $length); + $data1 = pack("vvvvvvvv", $iPaperSize, $iScale, $iPageStart, $iFitWidth, $iFitHeight, $grbit, $iRes, $iVRes); + $data2 = $numHdr.$numFtr; + $data3 = pack("v", $iCopies); + $this->append($header . $data1 . $data2 . $data3); + } + + /** + * Store the header caption BIFF record. + */ + private function writeHeader() + { + $record = 0x0014; // Record identifier + + /* removing for now + // need to fix character count (multibyte!) + if (strlen($this->phpSheet->getHeaderFooter()->getOddHeader()) <= 255) { + $str = $this->phpSheet->getHeaderFooter()->getOddHeader(); // header string + } else { + $str = ''; + } + */ + + $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddHeader()); + $length = strlen($recordData); + + $header = pack("vv", $record, $length); + + $this->append($header . $recordData); + } + + /** + * Store the footer caption BIFF record. + */ + private function writeFooter() + { + $record = 0x0015; // Record identifier + + /* removing for now + // need to fix character count (multibyte!) + if (strlen($this->phpSheet->getHeaderFooter()->getOddFooter()) <= 255) { + $str = $this->phpSheet->getHeaderFooter()->getOddFooter(); + } else { + $str = ''; + } + */ + + $recordData = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($this->phpSheet->getHeaderFooter()->getOddFooter()); + $length = strlen($recordData); + + $header = pack("vv", $record, $length); + + $this->append($header . $recordData); + } + + /** + * Store the horizontal centering HCENTER BIFF record. + * + * @access private + */ + private function writeHcenter() + { + $record = 0x0083; // Record identifier + $length = 0x0002; // Bytes to follow + + $fHCenter = $this->phpSheet->getPageSetup()->getHorizontalCentered() ? 1 : 0; // Horizontal centering + + $header = pack("vv", $record, $length); + $data = pack("v", $fHCenter); + + $this->append($header.$data); + } + + /** + * Store the vertical centering VCENTER BIFF record. + */ + private function writeVcenter() + { + $record = 0x0084; // Record identifier + $length = 0x0002; // Bytes to follow + + $fVCenter = $this->phpSheet->getPageSetup()->getVerticalCentered() ? 1 : 0; // Horizontal centering + + $header = pack("vv", $record, $length); + $data = pack("v", $fVCenter); + $this->append($header . $data); + } + + /** + * Store the LEFTMARGIN BIFF record. + */ + private function writeMarginLeft() + { + $record = 0x0026; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->phpSheet->getPageMargins()->getLeft(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->append($header . $data); + } + + /** + * Store the RIGHTMARGIN BIFF record. + */ + private function writeMarginRight() + { + $record = 0x0027; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->phpSheet->getPageMargins()->getRight(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->append($header . $data); + } + + /** + * Store the TOPMARGIN BIFF record. + */ + private function writeMarginTop() + { + $record = 0x0028; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->phpSheet->getPageMargins()->getTop(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->append($header . $data); + } + + /** + * Store the BOTTOMMARGIN BIFF record. + */ + private function writeMarginBottom() + { + $record = 0x0029; // Record identifier + $length = 0x0008; // Bytes to follow + + $margin = $this->phpSheet->getPageMargins()->getBottom(); // Margin in inches + + $header = pack("vv", $record, $length); + $data = pack("d", $margin); + if (self::getByteOrder()) { // if it's Big Endian + $data = strrev($data); + } + + $this->append($header . $data); + } + + /** + * Write the PRINTHEADERS BIFF record. + */ + private function writePrintHeaders() + { + $record = 0x002a; // Record identifier + $length = 0x0002; // Bytes to follow + + $fPrintRwCol = $this->_print_headers; // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fPrintRwCol); + $this->append($header . $data); + } + + /** + * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the + * GRIDSET record. + */ + private function writePrintGridlines() + { + $record = 0x002b; // Record identifier + $length = 0x0002; // Bytes to follow + + $fPrintGrid = $this->phpSheet->getPrintGridlines() ? 1 : 0; // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fPrintGrid); + $this->append($header . $data); + } + + /** + * Write the GRIDSET BIFF record. Must be used in conjunction with the + * PRINTGRIDLINES record. + */ + private function writeGridset() + { + $record = 0x0082; // Record identifier + $length = 0x0002; // Bytes to follow + + $fGridSet = !$this->phpSheet->getPrintGridlines(); // Boolean flag + + $header = pack("vv", $record, $length); + $data = pack("v", $fGridSet); + $this->append($header . $data); + } + + /** + * Write the AUTOFILTERINFO BIFF record. This is used to configure the number of autofilter select used in the sheet. + */ + private function writeAutoFilterInfo() + { + $record = 0x009D; // Record identifier + $length = 0x0002; // Bytes to follow + + $rangeBounds = PHPExcel_Cell::rangeBoundaries($this->phpSheet->getAutoFilter()->getRange()); + $iNumFilters = 1 + $rangeBounds[1][0] - $rangeBounds[0][0]; + + $header = pack("vv", $record, $length); + $data = pack("v", $iNumFilters); + $this->append($header . $data); + } + + /** + * Write the GUTS BIFF record. This is used to configure the gutter margins + * where Excel outline symbols are displayed. The visibility of the gutters is + * controlled by a flag in WSBOOL. + * + * @see writeWsbool() + */ + private function writeGuts() + { + $record = 0x0080; // Record identifier + $length = 0x0008; // Bytes to follow + + $dxRwGut = 0x0000; // Size of row gutter + $dxColGut = 0x0000; // Size of col gutter + + // determine maximum row outline level + $maxRowOutlineLevel = 0; + foreach ($this->phpSheet->getRowDimensions() as $rowDimension) { + $maxRowOutlineLevel = max($maxRowOutlineLevel, $rowDimension->getOutlineLevel()); + } + + $col_level = 0; + + // Calculate the maximum column outline level. The equivalent calculation + // for the row outline level is carried out in writeRow(). + $colcount = count($this->columnInfo); + for ($i = 0; $i < $colcount; ++$i) { + $col_level = max($this->columnInfo[$i][5], $col_level); + } + + // Set the limits for the outline levels (0 <= x <= 7). + $col_level = max(0, min($col_level, 7)); + + // The displayed level is one greater than the max outline levels + if ($maxRowOutlineLevel) { + ++$maxRowOutlineLevel; + } + if ($col_level) { + ++$col_level; + } + + $header = pack("vv", $record, $length); + $data = pack("vvvv", $dxRwGut, $dxColGut, $maxRowOutlineLevel, $col_level); + + $this->append($header.$data); + } + + /** + * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction + * with the SETUP record. + */ + private function writeWsbool() + { + $record = 0x0081; // Record identifier + $length = 0x0002; // Bytes to follow + $grbit = 0x0000; + + // The only option that is of interest is the flag for fit to page. So we + // set all the options in one go. + // + // Set the option flags + $grbit |= 0x0001; // Auto page breaks visible + if ($this->outlineStyle) { + $grbit |= 0x0020; // Auto outline styles + } + if ($this->phpSheet->getShowSummaryBelow()) { + $grbit |= 0x0040; // Outline summary below + } + if ($this->phpSheet->getShowSummaryRight()) { + $grbit |= 0x0080; // Outline summary right + } + if ($this->phpSheet->getPageSetup()->getFitToPage()) { + $grbit |= 0x0100; // Page setup fit to page + } + if ($this->outlineOn) { + $grbit |= 0x0400; // Outline symbols displayed + } + + $header = pack("vv", $record, $length); + $data = pack("v", $grbit); + $this->append($header . $data); + } + + /** + * Write the HORIZONTALPAGEBREAKS and VERTICALPAGEBREAKS BIFF records. + */ + private function writeBreaks() + { + // initialize + $vbreaks = array(); + $hbreaks = array(); + + foreach ($this->phpSheet->getBreaks() as $cell => $breakType) { + // Fetch coordinates + $coordinates = PHPExcel_Cell::coordinateFromString($cell); + + // Decide what to do by the type of break + switch ($breakType) { + case PHPExcel_Worksheet::BREAK_COLUMN: + // Add to list of vertical breaks + $vbreaks[] = PHPExcel_Cell::columnIndexFromString($coordinates[0]) - 1; + break; + case PHPExcel_Worksheet::BREAK_ROW: + // Add to list of horizontal breaks + $hbreaks[] = $coordinates[1]; + break; + case PHPExcel_Worksheet::BREAK_NONE: + default: + // Nothing to do + break; + } + } + + //horizontal page breaks + if (!empty($hbreaks)) { + // Sort and filter array of page breaks + sort($hbreaks, SORT_NUMERIC); + if ($hbreaks[0] == 0) { // don't use first break if it's 0 + array_shift($hbreaks); + } + + $record = 0x001b; // Record identifier + $cbrk = count($hbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cbrk); + + // Append each page break + foreach ($hbreaks as $hbreak) { + $data .= pack("vvv", $hbreak, 0x0000, 0x00ff); + } + + $this->append($header . $data); + } + + // vertical page breaks + if (!empty($vbreaks)) { + // 1000 vertical pagebreaks appears to be an internal Excel 5 limit. + // It is slightly higher in Excel 97/200, approx. 1026 + $vbreaks = array_slice($vbreaks, 0, 1000); + + // Sort and filter array of page breaks + sort($vbreaks, SORT_NUMERIC); + if ($vbreaks[0] == 0) { // don't use first break if it's 0 + array_shift($vbreaks); + } + + $record = 0x001a; // Record identifier + $cbrk = count($vbreaks); // Number of page breaks + $length = 2 + 6 * $cbrk; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("v", $cbrk); + + // Append each page break + foreach ($vbreaks as $vbreak) { + $data .= pack("vvv", $vbreak, 0x0000, 0xffff); + } + + $this->append($header . $data); + } + } + + /** + * Set the Biff PROTECT record to indicate that the worksheet is protected. + */ + private function writeProtect() + { + // Exit unless sheet protection has been specified + if (!$this->phpSheet->getProtection()->getSheet()) { + return; + } + + $record = 0x0012; // Record identifier + $length = 0x0002; // Bytes to follow + + $fLock = 1; // Worksheet is protected + + $header = pack("vv", $record, $length); + $data = pack("v", $fLock); + + $this->append($header.$data); + } + + /** + * Write SCENPROTECT + */ + private function writeScenProtect() + { + // Exit if sheet protection is not active + if (!$this->phpSheet->getProtection()->getSheet()) { + return; + } + + // Exit if scenarios are not protected + if (!$this->phpSheet->getProtection()->getScenarios()) { + return; + } + + $record = 0x00DD; // Record identifier + $length = 0x0002; // Bytes to follow + + $header = pack('vv', $record, $length); + $data = pack('v', 1); + + $this->append($header . $data); + } + + /** + * Write OBJECTPROTECT + */ + private function writeObjectProtect() + { + // Exit if sheet protection is not active + if (!$this->phpSheet->getProtection()->getSheet()) { + return; + } + + // Exit if objects are not protected + if (!$this->phpSheet->getProtection()->getObjects()) { + return; + } + + $record = 0x0063; // Record identifier + $length = 0x0002; // Bytes to follow + + $header = pack('vv', $record, $length); + $data = pack('v', 1); + + $this->append($header . $data); + } + + /** + * Write the worksheet PASSWORD record. + */ + private function writePassword() + { + // Exit unless sheet protection and password have been specified + if (!$this->phpSheet->getProtection()->getSheet() || !$this->phpSheet->getProtection()->getPassword()) { + return; + } + + $record = 0x0013; // Record identifier + $length = 0x0002; // Bytes to follow + + $wPassword = hexdec($this->phpSheet->getProtection()->getPassword()); // Encoded password + + $header = pack("vv", $record, $length); + $data = pack("v", $wPassword); + + $this->append($header . $data); + } + + /** + * Insert a 24bit bitmap image in a worksheet. + * + * @access public + * @param integer $row The row we are going to insert the bitmap into + * @param integer $col The column we are going to insert the bitmap into + * @param mixed $bitmap The bitmap filename or GD-image resource + * @param integer $x The horizontal position (offset) of the image inside the cell. + * @param integer $y The vertical position (offset) of the image inside the cell. + * @param float $scale_x The horizontal scale + * @param float $scale_y The vertical scale + */ + public function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1) + { + $bitmap_array = (is_resource($bitmap) ? $this->processBitmapGd($bitmap) : $this->processBitmap($bitmap)); + list($width, $height, $size, $data) = $bitmap_array; //$this->processBitmap($bitmap); + + // Scale the frame of the image. + $width *= $scale_x; + $height *= $scale_y; + + // Calculate the vertices of the image and write the OBJ record + $this->positionImage($col, $row, $x, $y, $width, $height); + + // Write the IMDATA record to store the bitmap data + $record = 0x007f; + $length = 8 + $size; + $cf = 0x09; + $env = 0x01; + $lcb = $size; + + $header = pack("vvvvV", $record, $length, $cf, $env, $lcb); + $this->append($header.$data); + } + + /** + * Calculate the vertices that define the position of the image as required by + * the OBJ record. + * + * +------------+------------+ + * | A | B | + * +-----+------------+------------+ + * | |(x1,y1) | | + * | 1 |(A1)._______|______ | + * | | | | | + * | | | | | + * +-----+----| BITMAP |-----+ + * | | | | | + * | 2 | |______________. | + * | | | (B2)| + * | | | (x2,y2)| + * +---- +------------+------------+ + * + * Example of a bitmap that covers some of the area from cell A1 to cell B2. + * + * Based on the width and height of the bitmap we need to calculate 8 vars: + * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. + * The width and height of the cells are also variable and have to be taken into + * account. + * The values of $col_start and $row_start are passed in from the calling + * function. The values of $col_end and $row_end are calculated by subtracting + * the width and height of the bitmap from the width and height of the + * underlying cells. + * The vertices are expressed as a percentage of the underlying cell width as + * follows (rhs values are in pixels): + * + * x1 = X / W *1024 + * y1 = Y / H *256 + * x2 = (X-1) / W *1024 + * y2 = (Y-1) / H *256 + * + * Where: X is distance from the left side of the underlying cell + * Y is distance from the top of the underlying cell + * W is the width of the cell + * H is the height of the cell + * The SDK incorrectly states that the height should be expressed as a + * percentage of 1024. + * + * @access private + * @param integer $col_start Col containing upper left corner of object + * @param integer $row_start Row containing top left corner of object + * @param integer $x1 Distance to left side of object + * @param integer $y1 Distance to top of object + * @param integer $width Width of image frame + * @param integer $height Height of image frame + */ + public function positionImage($col_start, $row_start, $x1, $y1, $width, $height) + { + // Initialise end cell to the same as the start cell + $col_end = $col_start; // Col containing lower right corner of object + $row_end = $row_start; // Row containing bottom right corner of object + + // Zero the specified offset if greater than the cell dimensions + if ($x1 >= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start))) { + $x1 = 0; + } + if ($y1 >= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1)) { + $y1 = 0; + } + + $width = $width + $x1 -1; + $height = $height + $y1 -1; + + // Subtract the underlying cell widths to find the end cell of the image + while ($width >= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end))) { + $width -= PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)); + ++$col_end; + } + + // Subtract the underlying cell heights to find the end cell of the image + while ($height >= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1)) { + $height -= PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1); + ++$row_end; + } + + // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell + // with zero eight or width. + // + if (PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1) == 0) { + return; + } + if (PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1) == 0) { + return; + } + + // Convert the pixel values to the percentage value expected by Excel + $x1 = $x1 / PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_start)) * 1024; + $y1 = $y1 / PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_start + 1) * 256; + $x2 = $width / PHPExcel_Shared_Excel5::sizeCol($this->phpSheet, PHPExcel_Cell::stringFromColumnIndex($col_end)) * 1024; // Distance to right side of object + $y2 = $height / PHPExcel_Shared_Excel5::sizeRow($this->phpSheet, $row_end + 1) * 256; // Distance to bottom of object + + $this->writeObjPicture($col_start, $x1, $row_start, $y1, $col_end, $x2, $row_end, $y2); + } + + /** + * Store the OBJ record that precedes an IMDATA record. This could be generalise + * to support other Excel objects. + * + * @param integer $colL Column containing upper left corner of object + * @param integer $dxL Distance from left side of cell + * @param integer $rwT Row containing top left corner of object + * @param integer $dyT Distance from top of cell + * @param integer $colR Column containing lower right corner of object + * @param integer $dxR Distance from right of cell + * @param integer $rwB Row containing bottom right corner of object + * @param integer $dyB Distance from bottom of cell + */ + private function writeObjPicture($colL, $dxL, $rwT, $dyT, $colR, $dxR, $rwB, $dyB) + { + $record = 0x005d; // Record identifier + $length = 0x003c; // Bytes to follow + + $cObj = 0x0001; // Count of objects in file (set to 1) + $OT = 0x0008; // Object type. 8 = Picture + $id = 0x0001; // Object ID + $grbit = 0x0614; // Option flags + + $cbMacro = 0x0000; // Length of FMLA structure + $Reserved1 = 0x0000; // Reserved + $Reserved2 = 0x0000; // Reserved + + $icvBack = 0x09; // Background colour + $icvFore = 0x09; // Foreground colour + $fls = 0x00; // Fill pattern + $fAuto = 0x00; // Automatic fill + $icv = 0x08; // Line colour + $lns = 0xff; // Line style + $lnw = 0x01; // Line weight + $fAutoB = 0x00; // Automatic border + $frs = 0x0000; // Frame style + $cf = 0x0009; // Image format, 9 = bitmap + $Reserved3 = 0x0000; // Reserved + $cbPictFmla = 0x0000; // Length of FMLA structure + $Reserved4 = 0x0000; // Reserved + $grbit2 = 0x0001; // Option flags + $Reserved5 = 0x0000; // Reserved + + + $header = pack("vv", $record, $length); + $data = pack("V", $cObj); + $data .= pack("v", $OT); + $data .= pack("v", $id); + $data .= pack("v", $grbit); + $data .= pack("v", $colL); + $data .= pack("v", $dxL); + $data .= pack("v", $rwT); + $data .= pack("v", $dyT); + $data .= pack("v", $colR); + $data .= pack("v", $dxR); + $data .= pack("v", $rwB); + $data .= pack("v", $dyB); + $data .= pack("v", $cbMacro); + $data .= pack("V", $Reserved1); + $data .= pack("v", $Reserved2); + $data .= pack("C", $icvBack); + $data .= pack("C", $icvFore); + $data .= pack("C", $fls); + $data .= pack("C", $fAuto); + $data .= pack("C", $icv); + $data .= pack("C", $lns); + $data .= pack("C", $lnw); + $data .= pack("C", $fAutoB); + $data .= pack("v", $frs); + $data .= pack("V", $cf); + $data .= pack("v", $Reserved3); + $data .= pack("v", $cbPictFmla); + $data .= pack("v", $Reserved4); + $data .= pack("v", $grbit2); + $data .= pack("V", $Reserved5); + + $this->append($header . $data); + } + + /** + * Convert a GD-image into the internal format. + * + * @access private + * @param resource $image The image to process + * @return array Array with data and properties of the bitmap + */ + public function processBitmapGd($image) + { + $width = imagesx($image); + $height = imagesy($image); + + $data = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); + for ($j=$height; $j--;) { + for ($i=0; $i < $width; ++$i) { + $color = imagecolorsforindex($image, imagecolorat($image, $i, $j)); + foreach (array("red", "green", "blue") as $key) { + $color[$key] = $color[$key] + round((255 - $color[$key]) * $color["alpha"] / 127); + } + $data .= chr($color["blue"]) . chr($color["green"]) . chr($color["red"]); + } + if (3*$width % 4) { + $data .= str_repeat("\x00", 4 - 3*$width % 4); + } + } + + return array($width, $height, strlen($data), $data); + } + + /** + * Convert a 24 bit bitmap into the modified internal format used by Windows. + * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the + * MSDN library. + * + * @access private + * @param string $bitmap The bitmap to process + * @return array Array with data and properties of the bitmap + */ + public function processBitmap($bitmap) + { + // Open file. + $bmp_fd = @fopen($bitmap, "rb"); + if (!$bmp_fd) { + throw new PHPExcel_Writer_Exception("Couldn't import $bitmap"); + } + + // Slurp the file into a string. + $data = fread($bmp_fd, filesize($bitmap)); + + // Check that the file is big enough to be a bitmap. + if (strlen($data) <= 0x36) { + throw new PHPExcel_Writer_Exception("$bitmap doesn't contain enough data.\n"); + } + + // The first 2 bytes are used to identify the bitmap. + $identity = unpack("A2ident", $data); + if ($identity['ident'] != "BM") { + throw new PHPExcel_Writer_Exception("$bitmap doesn't appear to be a valid bitmap image.\n"); + } + + // Remove bitmap data: ID. + $data = substr($data, 2); + + // Read and remove the bitmap size. This is more reliable than reading + // the data size at offset 0x22. + // + $size_array = unpack("Vsa", substr($data, 0, 4)); + $size = $size_array['sa']; + $data = substr($data, 4); + $size -= 0x36; // Subtract size of bitmap header. + $size += 0x0C; // Add size of BIFF header. + + // Remove bitmap data: reserved, offset, header length. + $data = substr($data, 12); + + // Read and remove the bitmap width and height. Verify the sizes. + $width_and_height = unpack("V2", substr($data, 0, 8)); + $width = $width_and_height[1]; + $height = $width_and_height[2]; + $data = substr($data, 8); + if ($width > 0xFFFF) { + throw new PHPExcel_Writer_Exception("$bitmap: largest image width supported is 65k.\n"); + } + if ($height > 0xFFFF) { + throw new PHPExcel_Writer_Exception("$bitmap: largest image height supported is 65k.\n"); + } + + // Read and remove the bitmap planes and bpp data. Verify them. + $planes_and_bitcount = unpack("v2", substr($data, 0, 4)); + $data = substr($data, 4); + if ($planes_and_bitcount[2] != 24) { // Bitcount + throw new PHPExcel_Writer_Exception("$bitmap isn't a 24bit true color bitmap.\n"); + } + if ($planes_and_bitcount[1] != 1) { + throw new PHPExcel_Writer_Exception("$bitmap: only 1 plane supported in bitmap image.\n"); + } + + // Read and remove the bitmap compression. Verify compression. + $compression = unpack("Vcomp", substr($data, 0, 4)); + $data = substr($data, 4); + + //$compression = 0; + if ($compression['comp'] != 0) { + throw new PHPExcel_Writer_Exception("$bitmap: compression not supported in bitmap image.\n"); + } + + // Remove bitmap data: data size, hres, vres, colours, imp. colours. + $data = substr($data, 20); + + // Add the BITMAPCOREHEADER data + $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); + $data = $header . $data; + + return (array($width, $height, $size, $data)); + } + + /** + * Store the window zoom factor. This should be a reduced fraction but for + * simplicity we will store all fractions with a numerator of 100. + */ + private function writeZoom() + { + // If scale is 100 we don't need to write a record + if ($this->phpSheet->getSheetView()->getZoomScale() == 100) { + return; + } + + $record = 0x00A0; // Record identifier + $length = 0x0004; // Bytes to follow + + $header = pack("vv", $record, $length); + $data = pack("vv", $this->phpSheet->getSheetView()->getZoomScale(), 100); + $this->append($header . $data); + } + + /** + * Get Escher object + * + * @return PHPExcel_Shared_Escher + */ + public function getEscher() + { + return $this->escher; + } + + /** + * Set Escher object + * + * @param PHPExcel_Shared_Escher $pValue + */ + public function setEscher(PHPExcel_Shared_Escher $pValue = null) + { + $this->escher = $pValue; + } + + /** + * Write MSODRAWING record + */ + private function writeMsoDrawing() + { + // write the Escher stream if necessary + if (isset($this->escher)) { + $writer = new PHPExcel_Writer_Excel5_Escher($this->escher); + $data = $writer->close(); + $spOffsets = $writer->getSpOffsets(); + $spTypes = $writer->getSpTypes(); + // write the neccesary MSODRAWING, OBJ records + + // split the Escher stream + $spOffsets[0] = 0; + $nm = count($spOffsets) - 1; // number of shapes excluding first shape + for ($i = 1; $i <= $nm; ++$i) { + // MSODRAWING record + $record = 0x00EC; // Record identifier + + // chunk of Escher stream for one shape + $dataChunk = substr($data, $spOffsets[$i -1], $spOffsets[$i] - $spOffsets[$i - 1]); + + $length = strlen($dataChunk); + $header = pack("vv", $record, $length); + + $this->append($header . $dataChunk); + + // OBJ record + $record = 0x005D; // record identifier + $objData = ''; + + // ftCmo + if ($spTypes[$i] == 0x00C9) { + // Add ftCmo (common object data) subobject + $objData .= + pack( + 'vvvvvVVV', + 0x0015, // 0x0015 = ftCmo + 0x0012, // length of ftCmo data + 0x0014, // object type, 0x0014 = filter + $i, // object id number, Excel seems to use 1-based index, local for the sheet + 0x2101, // option flags, 0x2001 is what OpenOffice.org uses + 0, // reserved + 0, // reserved + 0 // reserved + ); + + // Add ftSbs Scroll bar subobject + $objData .= pack('vv', 0x00C, 0x0014); + $objData .= pack('H*', '0000000000000000640001000A00000010000100'); + // Add ftLbsData (List box data) subobject + $objData .= pack('vv', 0x0013, 0x1FEE); + $objData .= pack('H*', '00000000010001030000020008005700'); + } else { + // Add ftCmo (common object data) subobject + $objData .= + pack( + 'vvvvvVVV', + 0x0015, // 0x0015 = ftCmo + 0x0012, // length of ftCmo data + 0x0008, // object type, 0x0008 = picture + $i, // object id number, Excel seems to use 1-based index, local for the sheet + 0x6011, // option flags, 0x6011 is what OpenOffice.org uses + 0, // reserved + 0, // reserved + 0 // reserved + ); + } + + // ftEnd + $objData .= + pack( + 'vv', + 0x0000, // 0x0000 = ftEnd + 0x0000 // length of ftEnd data + ); + + $length = strlen($objData); + $header = pack('vv', $record, $length); + $this->append($header . $objData); + } + } + } + + /** + * Store the DATAVALIDATIONS and DATAVALIDATION records. + */ + private function writeDataValidity() + { + // Datavalidation collection + $dataValidationCollection = $this->phpSheet->getDataValidationCollection(); + + // Write data validations? + if (!empty($dataValidationCollection)) { + // DATAVALIDATIONS record + $record = 0x01B2; // Record identifier + $length = 0x0012; // Bytes to follow + + $grbit = 0x0000; // Prompt box at cell, no cached validity data at DV records + $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position + $verPos = 0x00000000; // Vertical position of prompt box, if fixed position + $objId = 0xFFFFFFFF; // Object identifier of drop down arrow object, or -1 if not visible + + $header = pack('vv', $record, $length); + $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, count($dataValidationCollection)); + $this->append($header.$data); + + // DATAVALIDATION records + $record = 0x01BE; // Record identifier + + foreach ($dataValidationCollection as $cellCoordinate => $dataValidation) { + // initialize record data + $data = ''; + + // options + $options = 0x00000000; + + // data type + $type = $dataValidation->getType(); + switch ($type) { + case PHPExcel_Cell_DataValidation::TYPE_NONE: + $type = 0x00; + break; + case PHPExcel_Cell_DataValidation::TYPE_WHOLE: + $type = 0x01; + break; + case PHPExcel_Cell_DataValidation::TYPE_DECIMAL: + $type = 0x02; + break; + case PHPExcel_Cell_DataValidation::TYPE_LIST: + $type = 0x03; + break; + case PHPExcel_Cell_DataValidation::TYPE_DATE: + $type = 0x04; + break; + case PHPExcel_Cell_DataValidation::TYPE_TIME: + $type = 0x05; + break; + case PHPExcel_Cell_DataValidation::TYPE_TEXTLENGTH: + $type = 0x06; + break; + case PHPExcel_Cell_DataValidation::TYPE_CUSTOM: + $type = 0x07; + break; + } + $options |= $type << 0; + + // error style + $errorStyle = $dataValidation->getType(); + switch ($errorStyle) { + case PHPExcel_Cell_DataValidation::STYLE_STOP: + $errorStyle = 0x00; + break; + case PHPExcel_Cell_DataValidation::STYLE_WARNING: + $errorStyle = 0x01; + break; + case PHPExcel_Cell_DataValidation::STYLE_INFORMATION: + $errorStyle = 0x02; + break; + } + $options |= $errorStyle << 4; + + // explicit formula? + if ($type == 0x03 && preg_match('/^\".*\"$/', $dataValidation->getFormula1())) { + $options |= 0x01 << 7; + } + + // empty cells allowed + $options |= $dataValidation->getAllowBlank() << 8; + + // show drop down + $options |= (!$dataValidation->getShowDropDown()) << 9; + + // show input message + $options |= $dataValidation->getShowInputMessage() << 18; + + // show error message + $options |= $dataValidation->getShowErrorMessage() << 19; + + // condition operator + $operator = $dataValidation->getOperator(); + switch ($operator) { + case PHPExcel_Cell_DataValidation::OPERATOR_BETWEEN: + $operator = 0x00; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_NOTBETWEEN: + $operator = 0x01; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_EQUAL: + $operator = 0x02; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_NOTEQUAL: + $operator = 0x03; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHAN: + $operator = 0x04; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHAN: + $operator = 0x05; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_GREATERTHANOREQUAL: + $operator = 0x06; + break; + case PHPExcel_Cell_DataValidation::OPERATOR_LESSTHANOREQUAL: + $operator = 0x07; + break; + } + $options |= $operator << 20; + + $data = pack('V', $options); + + // prompt title + $promptTitle = $dataValidation->getPromptTitle() !== '' ? + $dataValidation->getPromptTitle() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($promptTitle); + + // error title + $errorTitle = $dataValidation->getErrorTitle() !== '' ? + $dataValidation->getErrorTitle() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($errorTitle); + + // prompt text + $prompt = $dataValidation->getPrompt() !== '' ? + $dataValidation->getPrompt() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($prompt); + + // error text + $error = $dataValidation->getError() !== '' ? + $dataValidation->getError() : chr(0); + $data .= PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($error); + + // formula 1 + try { + $formula1 = $dataValidation->getFormula1(); + if ($type == 0x03) { // list type + $formula1 = str_replace(',', chr(0), $formula1); + } + $this->parser->parse($formula1); + $formula1 = $this->parser->toReversePolish(); + $sz1 = strlen($formula1); + } catch (PHPExcel_Exception $e) { + $sz1 = 0; + $formula1 = ''; + } + $data .= pack('vv', $sz1, 0x0000); + $data .= $formula1; + + // formula 2 + try { + $formula2 = $dataValidation->getFormula2(); + if ($formula2 === '') { + throw new PHPExcel_Writer_Exception('No formula2'); + } + $this->parser->parse($formula2); + $formula2 = $this->parser->toReversePolish(); + $sz2 = strlen($formula2); + } catch (PHPExcel_Exception $e) { + $sz2 = 0; + $formula2 = ''; + } + $data .= pack('vv', $sz2, 0x0000); + $data .= $formula2; + + // cell range address list + $data .= pack('v', 0x0001); + $data .= $this->writeBIFF8CellRangeAddressFixed($cellCoordinate); + + $length = strlen($data); + $header = pack("vv", $record, $length); + + $this->append($header . $data); + } + } + } + + /** + * Map Error code + * + * @param string $errorCode + * @return int + */ + private static function mapErrorCode($errorCode) + { + switch ($errorCode) { + case '#NULL!': + return 0x00; + case '#DIV/0!': + return 0x07; + case '#VALUE!': + return 0x0F; + case '#REF!': + return 0x17; + case '#NAME?': + return 0x1D; + case '#NUM!': + return 0x24; + case '#N/A': + return 0x2A; + } + + return 0; + } + + /** + * Write PLV Record + */ + private function writePageLayoutView() + { + $record = 0x088B; // Record identifier + $length = 0x0010; // Bytes to follow + + $rt = 0x088B; // 2 + $grbitFrt = 0x0000; // 2 + $reserved = 0x0000000000000000; // 8 + $wScalvePLV = $this->phpSheet->getSheetView()->getZoomScale(); // 2 + + // The options flags that comprise $grbit + if ($this->phpSheet->getSheetView()->getView() == PHPExcel_Worksheet_SheetView::SHEETVIEW_PAGE_LAYOUT) { + $fPageLayoutView = 1; + } else { + $fPageLayoutView = 0; + } + $fRulerVisible = 0; + $fWhitespaceHidden = 0; + + $grbit = $fPageLayoutView; // 2 + $grbit |= $fRulerVisible << 1; + $grbit |= $fWhitespaceHidden << 3; + + $header = pack("vv", $record, $length); + $data = pack("vvVVvv", $rt, $grbitFrt, 0x00000000, 0x00000000, $wScalvePLV, $grbit); + $this->append($header . $data); + } + + /** + * Write CFRule Record + * @param PHPExcel_Style_Conditional $conditional + */ + private function writeCFRule(PHPExcel_Style_Conditional $conditional) + { + $record = 0x01B1; // Record identifier + + // $type : Type of the CF + // $operatorType : Comparison operator + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION) { + $type = 0x02; + $operatorType = 0x00; + } elseif ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) { + $type = 0x01; + + switch ($conditional->getOperatorType()) { + case PHPExcel_Style_Conditional::OPERATOR_NONE: + $operatorType = 0x00; + break; + case PHPExcel_Style_Conditional::OPERATOR_EQUAL: + $operatorType = 0x03; + break; + case PHPExcel_Style_Conditional::OPERATOR_GREATERTHAN: + $operatorType = 0x05; + break; + case PHPExcel_Style_Conditional::OPERATOR_GREATERTHANOREQUAL: + $operatorType = 0x07; + break; + case PHPExcel_Style_Conditional::OPERATOR_LESSTHAN: + $operatorType = 0x06; + break; + case PHPExcel_Style_Conditional::OPERATOR_LESSTHANOREQUAL: + $operatorType = 0x08; + break; + case PHPExcel_Style_Conditional::OPERATOR_NOTEQUAL: + $operatorType = 0x04; + break; + case PHPExcel_Style_Conditional::OPERATOR_BETWEEN: + $operatorType = 0x01; + break; + // not OPERATOR_NOTBETWEEN 0x02 + } + } + + // $szValue1 : size of the formula data for first value or formula + // $szValue2 : size of the formula data for second value or formula + $arrConditions = $conditional->getConditions(); + $numConditions = sizeof($arrConditions); + if ($numConditions == 1) { + $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); + $szValue2 = 0x0000; + $operand1 = pack('Cv', 0x1E, $arrConditions[0]); + $operand2 = null; + } elseif ($numConditions == 2 && ($conditional->getOperatorType() == PHPExcel_Style_Conditional::OPERATOR_BETWEEN)) { + $szValue1 = ($arrConditions[0] <= 65535 ? 3 : 0x0000); + $szValue2 = ($arrConditions[1] <= 65535 ? 3 : 0x0000); + $operand1 = pack('Cv', 0x1E, $arrConditions[0]); + $operand2 = pack('Cv', 0x1E, $arrConditions[1]); + } else { + $szValue1 = 0x0000; + $szValue2 = 0x0000; + $operand1 = null; + $operand2 = null; + } + + // $flags : Option flags + // Alignment + $bAlignHz = ($conditional->getStyle()->getAlignment()->getHorizontal() == null ? 1 : 0); + $bAlignVt = ($conditional->getStyle()->getAlignment()->getVertical() == null ? 1 : 0); + $bAlignWrapTx = ($conditional->getStyle()->getAlignment()->getWrapText() == false ? 1 : 0); + $bTxRotation = ($conditional->getStyle()->getAlignment()->getTextRotation() == null ? 1 : 0); + $bIndent = ($conditional->getStyle()->getAlignment()->getIndent() == 0 ? 1 : 0); + $bShrinkToFit = ($conditional->getStyle()->getAlignment()->getShrinkToFit() == false ? 1 : 0); + if ($bAlignHz == 0 || $bAlignVt == 0 || $bAlignWrapTx == 0 || $bTxRotation == 0 || $bIndent == 0 || $bShrinkToFit == 0) { + $bFormatAlign = 1; + } else { + $bFormatAlign = 0; + } + // Protection + $bProtLocked = ($conditional->getStyle()->getProtection()->getLocked() == null ? 1 : 0); + $bProtHidden = ($conditional->getStyle()->getProtection()->getHidden() == null ? 1 : 0); + if ($bProtLocked == 0 || $bProtHidden == 0) { + $bFormatProt = 1; + } else { + $bFormatProt = 0; + } + // Border + $bBorderLeft = ($conditional->getStyle()->getBorders()->getLeft()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getLeft()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderRight = ($conditional->getStyle()->getBorders()->getRight()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getRight()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderTop = ($conditional->getStyle()->getBorders()->getTop()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getTop()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + $bBorderBottom = ($conditional->getStyle()->getBorders()->getBottom()->getColor()->getARGB() == PHPExcel_Style_Color::COLOR_BLACK + && $conditional->getStyle()->getBorders()->getBottom()->getBorderStyle() == PHPExcel_Style_Border::BORDER_NONE ? 1 : 0); + if ($bBorderLeft == 0 || $bBorderRight == 0 || $bBorderTop == 0 || $bBorderBottom == 0) { + $bFormatBorder = 1; + } else { + $bFormatBorder = 0; + } + // Pattern + $bFillStyle = ($conditional->getStyle()->getFill()->getFillType() == null ? 0 : 1); + $bFillColor = ($conditional->getStyle()->getFill()->getStartColor()->getARGB() == null ? 0 : 1); + $bFillColorBg = ($conditional->getStyle()->getFill()->getEndColor()->getARGB() == null ? 0 : 1); + if ($bFillStyle == 0 || $bFillColor == 0 || $bFillColorBg == 0) { + $bFormatFill = 1; + } else { + $bFormatFill = 0; + } + // Font + if ($conditional->getStyle()->getFont()->getName() != null + || $conditional->getStyle()->getFont()->getSize() != null + || $conditional->getStyle()->getFont()->getBold() != null + || $conditional->getStyle()->getFont()->getItalic() != null + || $conditional->getStyle()->getFont()->getSuperScript() != null + || $conditional->getStyle()->getFont()->getSubScript() != null + || $conditional->getStyle()->getFont()->getUnderline() != null + || $conditional->getStyle()->getFont()->getStrikethrough() != null + || $conditional->getStyle()->getFont()->getColor()->getARGB() != null) { + $bFormatFont = 1; + } else { + $bFormatFont = 0; + } + // Alignment + $flags = 0; + $flags |= (1 == $bAlignHz ? 0x00000001 : 0); + $flags |= (1 == $bAlignVt ? 0x00000002 : 0); + $flags |= (1 == $bAlignWrapTx ? 0x00000004 : 0); + $flags |= (1 == $bTxRotation ? 0x00000008 : 0); + // Justify last line flag + $flags |= (1 == 1 ? 0x00000010 : 0); + $flags |= (1 == $bIndent ? 0x00000020 : 0); + $flags |= (1 == $bShrinkToFit ? 0x00000040 : 0); + // Default + $flags |= (1 == 1 ? 0x00000080 : 0); + // Protection + $flags |= (1 == $bProtLocked ? 0x00000100 : 0); + $flags |= (1 == $bProtHidden ? 0x00000200 : 0); + // Border + $flags |= (1 == $bBorderLeft ? 0x00000400 : 0); + $flags |= (1 == $bBorderRight ? 0x00000800 : 0); + $flags |= (1 == $bBorderTop ? 0x00001000 : 0); + $flags |= (1 == $bBorderBottom ? 0x00002000 : 0); + $flags |= (1 == 1 ? 0x00004000 : 0); // Top left to Bottom right border + $flags |= (1 == 1 ? 0x00008000 : 0); // Bottom left to Top right border + // Pattern + $flags |= (1 == $bFillStyle ? 0x00010000 : 0); + $flags |= (1 == $bFillColor ? 0x00020000 : 0); + $flags |= (1 == $bFillColorBg ? 0x00040000 : 0); + $flags |= (1 == 1 ? 0x00380000 : 0); + // Font + $flags |= (1 == $bFormatFont ? 0x04000000 : 0); + // Alignment: + $flags |= (1 == $bFormatAlign ? 0x08000000 : 0); + // Border + $flags |= (1 == $bFormatBorder ? 0x10000000 : 0); + // Pattern + $flags |= (1 == $bFormatFill ? 0x20000000 : 0); + // Protection + $flags |= (1 == $bFormatProt ? 0x40000000 : 0); + // Text direction + $flags |= (1 == 0 ? 0x80000000 : 0); + + // Data Blocks + if ($bFormatFont == 1) { + // Font Name + if ($conditional->getStyle()->getFont()->getName() == null) { + $dataBlockFont = pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); + $dataBlockFont .= pack('VVVVVVVV', 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000); + } else { + $dataBlockFont = PHPExcel_Shared_String::UTF8toBIFF8UnicodeLong($conditional->getStyle()->getFont()->getName()); + } + // Font Size + if ($conditional->getStyle()->getFont()->getSize() == null) { + $dataBlockFont .= pack('V', 20 * 11); + } else { + $dataBlockFont .= pack('V', 20 * $conditional->getStyle()->getFont()->getSize()); + } + // Font Options + $dataBlockFont .= pack('V', 0); + // Font weight + if ($conditional->getStyle()->getFont()->getBold() == true) { + $dataBlockFont .= pack('v', 0x02BC); + } else { + $dataBlockFont .= pack('v', 0x0190); + } + // Escapement type + if ($conditional->getStyle()->getFont()->getSubScript() == true) { + $dataBlockFont .= pack('v', 0x02); + $fontEscapement = 0; + } elseif ($conditional->getStyle()->getFont()->getSuperScript() == true) { + $dataBlockFont .= pack('v', 0x01); + $fontEscapement = 0; + } else { + $dataBlockFont .= pack('v', 0x00); + $fontEscapement = 1; + } + // Underline type + switch ($conditional->getStyle()->getFont()->getUnderline()) { + case PHPExcel_Style_Font::UNDERLINE_NONE: + $dataBlockFont .= pack('C', 0x00); + $fontUnderline = 0; + break; + case PHPExcel_Style_Font::UNDERLINE_DOUBLE: + $dataBlockFont .= pack('C', 0x02); + $fontUnderline = 0; + break; + case PHPExcel_Style_Font::UNDERLINE_DOUBLEACCOUNTING: + $dataBlockFont .= pack('C', 0x22); + $fontUnderline = 0; + break; + case PHPExcel_Style_Font::UNDERLINE_SINGLE: + $dataBlockFont .= pack('C', 0x01); + $fontUnderline = 0; + break; + case PHPExcel_Style_Font::UNDERLINE_SINGLEACCOUNTING: + $dataBlockFont .= pack('C', 0x21); + $fontUnderline = 0; + break; + default: $dataBlockFont .= pack('C', 0x00); + $fontUnderline = 1; + break; + } + // Not used (3) + $dataBlockFont .= pack('vC', 0x0000, 0x00); + // Font color index + switch ($conditional->getStyle()->getFont()->getColor()->getRGB()) { + case '000000': + $colorIdx = 0x08; + break; + case 'FFFFFF': + $colorIdx = 0x09; + break; + case 'FF0000': + $colorIdx = 0x0A; + break; + case '00FF00': + $colorIdx = 0x0B; + break; + case '0000FF': + $colorIdx = 0x0C; + break; + case 'FFFF00': + $colorIdx = 0x0D; + break; + case 'FF00FF': + $colorIdx = 0x0E; + break; + case '00FFFF': + $colorIdx = 0x0F; + break; + case '800000': + $colorIdx = 0x10; + break; + case '008000': + $colorIdx = 0x11; + break; + case '000080': + $colorIdx = 0x12; + break; + case '808000': + $colorIdx = 0x13; + break; + case '800080': + $colorIdx = 0x14; + break; + case '008080': + $colorIdx = 0x15; + break; + case 'C0C0C0': + $colorIdx = 0x16; + break; + case '808080': + $colorIdx = 0x17; + break; + case '9999FF': + $colorIdx = 0x18; + break; + case '993366': + $colorIdx = 0x19; + break; + case 'FFFFCC': + $colorIdx = 0x1A; + break; + case 'CCFFFF': + $colorIdx = 0x1B; + break; + case '660066': + $colorIdx = 0x1C; + break; + case 'FF8080': + $colorIdx = 0x1D; + break; + case '0066CC': + $colorIdx = 0x1E; + break; + case 'CCCCFF': + $colorIdx = 0x1F; + break; + case '000080': + $colorIdx = 0x20; + break; + case 'FF00FF': + $colorIdx = 0x21; + break; + case 'FFFF00': + $colorIdx = 0x22; + break; + case '00FFFF': + $colorIdx = 0x23; + break; + case '800080': + $colorIdx = 0x24; + break; + case '800000': + $colorIdx = 0x25; + break; + case '008080': + $colorIdx = 0x26; + break; + case '0000FF': + $colorIdx = 0x27; + break; + case '00CCFF': + $colorIdx = 0x28; + break; + case 'CCFFFF': + $colorIdx = 0x29; + break; + case 'CCFFCC': + $colorIdx = 0x2A; + break; + case 'FFFF99': + $colorIdx = 0x2B; + break; + case '99CCFF': + $colorIdx = 0x2C; + break; + case 'FF99CC': + $colorIdx = 0x2D; + break; + case 'CC99FF': + $colorIdx = 0x2E; + break; + case 'FFCC99': + $colorIdx = 0x2F; + break; + case '3366FF': + $colorIdx = 0x30; + break; + case '33CCCC': + $colorIdx = 0x31; + break; + case '99CC00': + $colorIdx = 0x32; + break; + case 'FFCC00': + $colorIdx = 0x33; + break; + case 'FF9900': + $colorIdx = 0x34; + break; + case 'FF6600': + $colorIdx = 0x35; + break; + case '666699': + $colorIdx = 0x36; + break; + case '969696': + $colorIdx = 0x37; + break; + case '003366': + $colorIdx = 0x38; + break; + case '339966': + $colorIdx = 0x39; + break; + case '003300': + $colorIdx = 0x3A; + break; + case '333300': + $colorIdx = 0x3B; + break; + case '993300': + $colorIdx = 0x3C; + break; + case '993366': + $colorIdx = 0x3D; + break; + case '333399': + $colorIdx = 0x3E; + break; + case '333333': + $colorIdx = 0x3F; + break; + default: + $colorIdx = 0x00; + break; + } + $dataBlockFont .= pack('V', $colorIdx); + // Not used (4) + $dataBlockFont .= pack('V', 0x00000000); + // Options flags for modified font attributes + $optionsFlags = 0; + $optionsFlagsBold = ($conditional->getStyle()->getFont()->getBold() == null ? 1 : 0); + $optionsFlags |= (1 == $optionsFlagsBold ? 0x00000002 : 0); + $optionsFlags |= (1 == 1 ? 0x00000008 : 0); + $optionsFlags |= (1 == 1 ? 0x00000010 : 0); + $optionsFlags |= (1 == 0 ? 0x00000020 : 0); + $optionsFlags |= (1 == 1 ? 0x00000080 : 0); + $dataBlockFont .= pack('V', $optionsFlags); + // Escapement type + $dataBlockFont .= pack('V', $fontEscapement); + // Underline type + $dataBlockFont .= pack('V', $fontUnderline); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Always + $dataBlockFont .= pack('V', 0x00000000); + // Not used (8) + $dataBlockFont .= pack('VV', 0x00000000, 0x00000000); + // Always + $dataBlockFont .= pack('v', 0x0001); + } + if ($bFormatAlign == 1) { + $blockAlign = 0; + // Alignment and text break + switch ($conditional->getStyle()->getAlignment()->getHorizontal()) { + case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL: + $blockAlign = 0; + break; + case PHPExcel_Style_Alignment::HORIZONTAL_LEFT: + $blockAlign = 1; + break; + case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT: + $blockAlign = 3; + break; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER: + $blockAlign = 2; + break; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: + $blockAlign = 6; + break; + case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY: + $blockAlign = 5; + break; + } + if ($conditional->getStyle()->getAlignment()->getWrapText() == true) { + $blockAlign |= 1 << 3; + } else { + $blockAlign |= 0 << 3; + } + switch ($conditional->getStyle()->getAlignment()->getVertical()) { + case PHPExcel_Style_Alignment::VERTICAL_BOTTOM: + $blockAlign = 2 << 4; + break; + case PHPExcel_Style_Alignment::VERTICAL_TOP: + $blockAlign = 0 << 4; + break; + case PHPExcel_Style_Alignment::VERTICAL_CENTER: + $blockAlign = 1 << 4; + break; + case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY: + $blockAlign = 3 << 4; + break; + } + $blockAlign |= 0 << 7; + + // Text rotation angle + $blockRotation = $conditional->getStyle()->getAlignment()->getTextRotation(); + + // Indentation + $blockIndent = $conditional->getStyle()->getAlignment()->getIndent(); + if ($conditional->getStyle()->getAlignment()->getShrinkToFit() == true) { + $blockIndent |= 1 << 4; + } else { + $blockIndent |= 0 << 4; + } + $blockIndent |= 0 << 6; + + // Relative indentation + $blockIndentRelative = 255; + + $dataBlockAlign = pack('CCvvv', $blockAlign, $blockRotation, $blockIndent, $blockIndentRelative, 0x0000); + } + if ($bFormatBorder == 1) { + $blockLineStyle = 0; + switch ($conditional->getStyle()->getBorders()->getLeft()->getBorderStyle()) { + case PHPExcel_Style_Border::BORDER_NONE: + $blockLineStyle |= 0x00; + break; + case PHPExcel_Style_Border::BORDER_THIN: + $blockLineStyle |= 0x01; + break; + case PHPExcel_Style_Border::BORDER_MEDIUM: + $blockLineStyle |= 0x02; + break; + case PHPExcel_Style_Border::BORDER_DASHED: + $blockLineStyle |= 0x03; + break; + case PHPExcel_Style_Border::BORDER_DOTTED: + $blockLineStyle |= 0x04; + break; + case PHPExcel_Style_Border::BORDER_THICK: + $blockLineStyle |= 0x05; + break; + case PHPExcel_Style_Border::BORDER_DOUBLE: + $blockLineStyle |= 0x06; + break; + case PHPExcel_Style_Border::BORDER_HAIR: + $blockLineStyle |= 0x07; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + $blockLineStyle |= 0x08; + break; + case PHPExcel_Style_Border::BORDER_DASHDOT: + $blockLineStyle |= 0x09; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + $blockLineStyle |= 0x0A; + break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + $blockLineStyle |= 0x0B; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + $blockLineStyle |= 0x0C; + break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + $blockLineStyle |= 0x0D; + break; + } + switch ($conditional->getStyle()->getBorders()->getRight()->getBorderStyle()) { + case PHPExcel_Style_Border::BORDER_NONE: + $blockLineStyle |= 0x00 << 4; + break; + case PHPExcel_Style_Border::BORDER_THIN: + $blockLineStyle |= 0x01 << 4; + break; + case PHPExcel_Style_Border::BORDER_MEDIUM: + $blockLineStyle |= 0x02 << 4; + break; + case PHPExcel_Style_Border::BORDER_DASHED: + $blockLineStyle |= 0x03 << 4; + break; + case PHPExcel_Style_Border::BORDER_DOTTED: + $blockLineStyle |= 0x04 << 4; + break; + case PHPExcel_Style_Border::BORDER_THICK: + $blockLineStyle |= 0x05 << 4; + break; + case PHPExcel_Style_Border::BORDER_DOUBLE: + $blockLineStyle |= 0x06 << 4; + break; + case PHPExcel_Style_Border::BORDER_HAIR: + $blockLineStyle |= 0x07 << 4; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + $blockLineStyle |= 0x08 << 4; + break; + case PHPExcel_Style_Border::BORDER_DASHDOT: + $blockLineStyle |= 0x09 << 4; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + $blockLineStyle |= 0x0A << 4; + break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + $blockLineStyle |= 0x0B << 4; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + $blockLineStyle |= 0x0C << 4; + break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + $blockLineStyle |= 0x0D << 4; + break; + } + switch ($conditional->getStyle()->getBorders()->getTop()->getBorderStyle()) { + case PHPExcel_Style_Border::BORDER_NONE: + $blockLineStyle |= 0x00 << 8; + break; + case PHPExcel_Style_Border::BORDER_THIN: + $blockLineStyle |= 0x01 << 8; + break; + case PHPExcel_Style_Border::BORDER_MEDIUM: + $blockLineStyle |= 0x02 << 8; + break; + case PHPExcel_Style_Border::BORDER_DASHED: + $blockLineStyle |= 0x03 << 8; + break; + case PHPExcel_Style_Border::BORDER_DOTTED: + $blockLineStyle |= 0x04 << 8; + break; + case PHPExcel_Style_Border::BORDER_THICK: + $blockLineStyle |= 0x05 << 8; + break; + case PHPExcel_Style_Border::BORDER_DOUBLE: + $blockLineStyle |= 0x06 << 8; + break; + case PHPExcel_Style_Border::BORDER_HAIR: + $blockLineStyle |= 0x07 << 8; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + $blockLineStyle |= 0x08 << 8; + break; + case PHPExcel_Style_Border::BORDER_DASHDOT: + $blockLineStyle |= 0x09 << 8; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + $blockLineStyle |= 0x0A << 8; + break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + $blockLineStyle |= 0x0B << 8; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + $blockLineStyle |= 0x0C << 8; + break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + $blockLineStyle |= 0x0D << 8; + break; + } + switch ($conditional->getStyle()->getBorders()->getBottom()->getBorderStyle()) { + case PHPExcel_Style_Border::BORDER_NONE: + $blockLineStyle |= 0x00 << 12; + break; + case PHPExcel_Style_Border::BORDER_THIN: + $blockLineStyle |= 0x01 << 12; + break; + case PHPExcel_Style_Border::BORDER_MEDIUM: + $blockLineStyle |= 0x02 << 12; + break; + case PHPExcel_Style_Border::BORDER_DASHED: + $blockLineStyle |= 0x03 << 12; + break; + case PHPExcel_Style_Border::BORDER_DOTTED: + $blockLineStyle |= 0x04 << 12; + break; + case PHPExcel_Style_Border::BORDER_THICK: + $blockLineStyle |= 0x05 << 12; + break; + case PHPExcel_Style_Border::BORDER_DOUBLE: + $blockLineStyle |= 0x06 << 12; + break; + case PHPExcel_Style_Border::BORDER_HAIR: + $blockLineStyle |= 0x07 << 12; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + $blockLineStyle |= 0x08 << 12; + break; + case PHPExcel_Style_Border::BORDER_DASHDOT: + $blockLineStyle |= 0x09 << 12; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + $blockLineStyle |= 0x0A << 12; + break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + $blockLineStyle |= 0x0B << 12; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + $blockLineStyle |= 0x0C << 12; + break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + $blockLineStyle |= 0x0D << 12; + break; + } + //@todo writeCFRule() => $blockLineStyle => Index Color for left line + //@todo writeCFRule() => $blockLineStyle => Index Color for right line + //@todo writeCFRule() => $blockLineStyle => Top-left to bottom-right on/off + //@todo writeCFRule() => $blockLineStyle => Bottom-left to top-right on/off + $blockColor = 0; + //@todo writeCFRule() => $blockColor => Index Color for top line + //@todo writeCFRule() => $blockColor => Index Color for bottom line + //@todo writeCFRule() => $blockColor => Index Color for diagonal line + switch ($conditional->getStyle()->getBorders()->getDiagonal()->getBorderStyle()) { + case PHPExcel_Style_Border::BORDER_NONE: + $blockColor |= 0x00 << 21; + break; + case PHPExcel_Style_Border::BORDER_THIN: + $blockColor |= 0x01 << 21; + break; + case PHPExcel_Style_Border::BORDER_MEDIUM: + $blockColor |= 0x02 << 21; + break; + case PHPExcel_Style_Border::BORDER_DASHED: + $blockColor |= 0x03 << 21; + break; + case PHPExcel_Style_Border::BORDER_DOTTED: + $blockColor |= 0x04 << 21; + break; + case PHPExcel_Style_Border::BORDER_THICK: + $blockColor |= 0x05 << 21; + break; + case PHPExcel_Style_Border::BORDER_DOUBLE: + $blockColor |= 0x06 << 21; + break; + case PHPExcel_Style_Border::BORDER_HAIR: + $blockColor |= 0x07 << 21; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + $blockColor |= 0x08 << 21; + break; + case PHPExcel_Style_Border::BORDER_DASHDOT: + $blockColor |= 0x09 << 21; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + $blockColor |= 0x0A << 21; + break; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + $blockColor |= 0x0B << 21; + break; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + $blockColor |= 0x0C << 21; + break; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + $blockColor |= 0x0D << 21; + break; + } + $dataBlockBorder = pack('vv', $blockLineStyle, $blockColor); + } + if ($bFormatFill == 1) { + // Fill Patern Style + $blockFillPatternStyle = 0; + switch ($conditional->getStyle()->getFill()->getFillType()) { + case PHPExcel_Style_Fill::FILL_NONE: + $blockFillPatternStyle = 0x00; + break; + case PHPExcel_Style_Fill::FILL_SOLID: + $blockFillPatternStyle = 0x01; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY: + $blockFillPatternStyle = 0x02; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY: + $blockFillPatternStyle = 0x03; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY: + $blockFillPatternStyle = 0x04; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL: + $blockFillPatternStyle = 0x05; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL: + $blockFillPatternStyle = 0x06; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN: + $blockFillPatternStyle = 0x07; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKUP: + $blockFillPatternStyle = 0x08; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID: + $blockFillPatternStyle = 0x09; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS: + $blockFillPatternStyle = 0x0A; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL: + $blockFillPatternStyle = 0x0B; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL: + $blockFillPatternStyle = 0x0C; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN: + $blockFillPatternStyle = 0x0D; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP: + $blockFillPatternStyle = 0x0E; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID: + $blockFillPatternStyle = 0x0F; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS: + $blockFillPatternStyle = 0x10; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_GRAY125: + $blockFillPatternStyle = 0x11; + break; + case PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625: + $blockFillPatternStyle = 0x12; + break; + case PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR: + $blockFillPatternStyle = 0x00; + break; // does not exist in BIFF8 + case PHPExcel_Style_Fill::FILL_GRADIENT_PATH: + $blockFillPatternStyle = 0x00; + break; // does not exist in BIFF8 + default: + $blockFillPatternStyle = 0x00; + break; + } + // Color + switch ($conditional->getStyle()->getFill()->getStartColor()->getRGB()) { + case '000000': + $colorIdxBg = 0x08; + break; + case 'FFFFFF': + $colorIdxBg = 0x09; + break; + case 'FF0000': + $colorIdxBg = 0x0A; + break; + case '00FF00': + $colorIdxBg = 0x0B; + break; + case '0000FF': + $colorIdxBg = 0x0C; + break; + case 'FFFF00': + $colorIdxBg = 0x0D; + break; + case 'FF00FF': + $colorIdxBg = 0x0E; + break; + case '00FFFF': + $colorIdxBg = 0x0F; + break; + case '800000': + $colorIdxBg = 0x10; + break; + case '008000': + $colorIdxBg = 0x11; + break; + case '000080': + $colorIdxBg = 0x12; + break; + case '808000': + $colorIdxBg = 0x13; + break; + case '800080': + $colorIdxBg = 0x14; + break; + case '008080': + $colorIdxBg = 0x15; + break; + case 'C0C0C0': + $colorIdxBg = 0x16; + break; + case '808080': + $colorIdxBg = 0x17; + break; + case '9999FF': + $colorIdxBg = 0x18; + break; + case '993366': + $colorIdxBg = 0x19; + break; + case 'FFFFCC': + $colorIdxBg = 0x1A; + break; + case 'CCFFFF': + $colorIdxBg = 0x1B; + break; + case '660066': + $colorIdxBg = 0x1C; + break; + case 'FF8080': + $colorIdxBg = 0x1D; + break; + case '0066CC': + $colorIdxBg = 0x1E; + break; + case 'CCCCFF': + $colorIdxBg = 0x1F; + break; + case '000080': + $colorIdxBg = 0x20; + break; + case 'FF00FF': + $colorIdxBg = 0x21; + break; + case 'FFFF00': + $colorIdxBg = 0x22; + break; + case '00FFFF': + $colorIdxBg = 0x23; + break; + case '800080': + $colorIdxBg = 0x24; + break; + case '800000': + $colorIdxBg = 0x25; + break; + case '008080': + $colorIdxBg = 0x26; + break; + case '0000FF': + $colorIdxBg = 0x27; + break; + case '00CCFF': + $colorIdxBg = 0x28; + break; + case 'CCFFFF': + $colorIdxBg = 0x29; + break; + case 'CCFFCC': + $colorIdxBg = 0x2A; + break; + case 'FFFF99': + $colorIdxBg = 0x2B; + break; + case '99CCFF': + $colorIdxBg = 0x2C; + break; + case 'FF99CC': + $colorIdxBg = 0x2D; + break; + case 'CC99FF': + $colorIdxBg = 0x2E; + break; + case 'FFCC99': + $colorIdxBg = 0x2F; + break; + case '3366FF': + $colorIdxBg = 0x30; + break; + case '33CCCC': + $colorIdxBg = 0x31; + break; + case '99CC00': + $colorIdxBg = 0x32; + break; + case 'FFCC00': + $colorIdxBg = 0x33; + break; + case 'FF9900': + $colorIdxBg = 0x34; + break; + case 'FF6600': + $colorIdxBg = 0x35; + break; + case '666699': + $colorIdxBg = 0x36; + break; + case '969696': + $colorIdxBg = 0x37; + break; + case '003366': + $colorIdxBg = 0x38; + break; + case '339966': + $colorIdxBg = 0x39; + break; + case '003300': + $colorIdxBg = 0x3A; + break; + case '333300': + $colorIdxBg = 0x3B; + break; + case '993300': + $colorIdxBg = 0x3C; + break; + case '993366': + $colorIdxBg = 0x3D; + break; + case '333399': + $colorIdxBg = 0x3E; + break; + case '333333': + $colorIdxBg = 0x3F; + break; + default: + $colorIdxBg = 0x41; + break; + } + // Fg Color + switch ($conditional->getStyle()->getFill()->getEndColor()->getRGB()) { + case '000000': + $colorIdxFg = 0x08; + break; + case 'FFFFFF': + $colorIdxFg = 0x09; + break; + case 'FF0000': + $colorIdxFg = 0x0A; + break; + case '00FF00': + $colorIdxFg = 0x0B; + break; + case '0000FF': + $colorIdxFg = 0x0C; + break; + case 'FFFF00': + $colorIdxFg = 0x0D; + break; + case 'FF00FF': + $colorIdxFg = 0x0E; + break; + case '00FFFF': + $colorIdxFg = 0x0F; + break; + case '800000': + $colorIdxFg = 0x10; + break; + case '008000': + $colorIdxFg = 0x11; + break; + case '000080': + $colorIdxFg = 0x12; + break; + case '808000': + $colorIdxFg = 0x13; + break; + case '800080': + $colorIdxFg = 0x14; + break; + case '008080': + $colorIdxFg = 0x15; + break; + case 'C0C0C0': + $colorIdxFg = 0x16; + break; + case '808080': + $colorIdxFg = 0x17; + break; + case '9999FF': + $colorIdxFg = 0x18; + break; + case '993366': + $colorIdxFg = 0x19; + break; + case 'FFFFCC': + $colorIdxFg = 0x1A; + break; + case 'CCFFFF': + $colorIdxFg = 0x1B; + break; + case '660066': + $colorIdxFg = 0x1C; + break; + case 'FF8080': + $colorIdxFg = 0x1D; + break; + case '0066CC': + $colorIdxFg = 0x1E; + break; + case 'CCCCFF': + $colorIdxFg = 0x1F; + break; + case '000080': + $colorIdxFg = 0x20; + break; + case 'FF00FF': + $colorIdxFg = 0x21; + break; + case 'FFFF00': + $colorIdxFg = 0x22; + break; + case '00FFFF': + $colorIdxFg = 0x23; + break; + case '800080': + $colorIdxFg = 0x24; + break; + case '800000': + $colorIdxFg = 0x25; + break; + case '008080': + $colorIdxFg = 0x26; + break; + case '0000FF': + $colorIdxFg = 0x27; + break; + case '00CCFF': + $colorIdxFg = 0x28; + break; + case 'CCFFFF': + $colorIdxFg = 0x29; + break; + case 'CCFFCC': + $colorIdxFg = 0x2A; + break; + case 'FFFF99': + $colorIdxFg = 0x2B; + break; + case '99CCFF': + $colorIdxFg = 0x2C; + break; + case 'FF99CC': + $colorIdxFg = 0x2D; + break; + case 'CC99FF': + $colorIdxFg = 0x2E; + break; + case 'FFCC99': + $colorIdxFg = 0x2F; + break; + case '3366FF': + $colorIdxFg = 0x30; + break; + case '33CCCC': + $colorIdxFg = 0x31; + break; + case '99CC00': + $colorIdxFg = 0x32; + break; + case 'FFCC00': + $colorIdxFg = 0x33; + break; + case 'FF9900': + $colorIdxFg = 0x34; + break; + case 'FF6600': + $colorIdxFg = 0x35; + break; + case '666699': + $colorIdxFg = 0x36; + break; + case '969696': + $colorIdxFg = 0x37; + break; + case '003366': + $colorIdxFg = 0x38; + break; + case '339966': + $colorIdxFg = 0x39; + break; + case '003300': + $colorIdxFg = 0x3A; + break; + case '333300': + $colorIdxFg = 0x3B; + break; + case '993300': + $colorIdxFg = 0x3C; + break; + case '993366': + $colorIdxFg = 0x3D; + break; + case '333399': + $colorIdxFg = 0x3E; + break; + case '333333': + $colorIdxFg = 0x3F; + break; + default: + $colorIdxFg = 0x40; + break; + } + $dataBlockFill = pack('v', $blockFillPatternStyle); + $dataBlockFill .= pack('v', $colorIdxFg | ($colorIdxBg << 7)); + } + if ($bFormatProt == 1) { + $dataBlockProtection = 0; + if ($conditional->getStyle()->getProtection()->getLocked() == PHPExcel_Style_Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1; + } + if ($conditional->getStyle()->getProtection()->getHidden() == PHPExcel_Style_Protection::PROTECTION_PROTECTED) { + $dataBlockProtection = 1 << 1; + } + } + + $data = pack('CCvvVv', $type, $operatorType, $szValue1, $szValue2, $flags, 0x0000); + if ($bFormatFont == 1) { // Block Formatting : OK + $data .= $dataBlockFont; + } + if ($bFormatAlign == 1) { + $data .= $dataBlockAlign; + } + if ($bFormatBorder == 1) { + $data .= $dataBlockBorder; + } + if ($bFormatFill == 1) { // Block Formatting : OK + $data .= $dataBlockFill; + } + if ($bFormatProt == 1) { + $data .= $dataBlockProtection; + } + if (!is_null($operand1)) { + $data .= $operand1; + } + if (!is_null($operand2)) { + $data .= $operand2; + } + $header = pack('vv', $record, strlen($data)); + $this->append($header . $data); + } + + /** + * Write CFHeader record + */ + private function writeCFHeader() + { + $record = 0x01B0; // Record identifier + $length = 0x0016; // Bytes to follow + + $numColumnMin = null; + $numColumnMax = null; + $numRowMin = null; + $numRowMax = null; + $arrConditional = array(); + foreach ($this->phpSheet->getConditionalStylesCollection() as $cellCoordinate => $conditionalStyles) { + foreach ($conditionalStyles as $conditional) { + if ($conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_EXPRESSION + || $conditional->getConditionType() == PHPExcel_Style_Conditional::CONDITION_CELLIS) { + if (!in_array($conditional->getHashCode(), $arrConditional)) { + $arrConditional[] = $conditional->getHashCode(); + } + // Cells + $arrCoord = PHPExcel_Cell::coordinateFromString($cellCoordinate); + if (!is_numeric($arrCoord[0])) { + $arrCoord[0] = PHPExcel_Cell::columnIndexFromString($arrCoord[0]); + } + if (is_null($numColumnMin) || ($numColumnMin > $arrCoord[0])) { + $numColumnMin = $arrCoord[0]; + } + if (is_null($numColumnMax) || ($numColumnMax < $arrCoord[0])) { + $numColumnMax = $arrCoord[0]; + } + if (is_null($numRowMin) || ($numRowMin > $arrCoord[1])) { + $numRowMin = $arrCoord[1]; + } + if (is_null($numRowMax) || ($numRowMax < $arrCoord[1])) { + $numRowMax = $arrCoord[1]; + } + } + } + } + $needRedraw = 1; + $cellRange = pack('vvvv', $numRowMin-1, $numRowMax-1, $numColumnMin-1, $numColumnMax-1); + + $header = pack('vv', $record, $length); + $data = pack('vv', count($arrConditional), $needRedraw); + $data .= $cellRange; + $data .= pack('v', 0x0001); + $data .= $cellRange; + $this->append($header . $data); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Xf.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Xf.php new file mode 100644 index 00000000..e41589a8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Excel5/Xf.php @@ -0,0 +1,557 @@ +<?php + +/** + * PHPExcel_Writer_Excel5_Xf + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_Excel5 + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + +// Original file header of PEAR::Spreadsheet_Excel_Writer_Format (used as the base for this class): +// ----------------------------------------------------------------------------------------- +// /* +// * Module written/ported by Xavier Noguer <xnoguer@rezebra.com> +// * +// * The majority of this is _NOT_ my code. I simply ported it from the +// * PERL Spreadsheet::WriteExcel module. +// * +// * The author of the Spreadsheet::WriteExcel module is John McNamara +// * <jmcnamara@cpan.org> +// * +// * I _DO_ maintain this code, and John McNamara has nothing to do with the +// * porting of this code to PHP. Any questions directly related to this +// * class library should be directed to me. +// * +// * License Information: +// * +// * Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets +// * Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com +// * +// * 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 +// */ +class PHPExcel_Writer_Excel5_Xf +{ + /** + * Style XF or a cell XF ? + * + * @var boolean + */ + private $isStyleXf; + + /** + * Index to the FONT record. Index 4 does not exist + * @var integer + */ + private $fontIndex; + + /** + * An index (2 bytes) to a FORMAT record (number format). + * @var integer + */ + private $numberFormatIndex; + + /** + * 1 bit, apparently not used. + * @var integer + */ + private $textJustLast; + + /** + * The cell's foreground color. + * @var integer + */ + private $foregroundColor; + + /** + * The cell's background color. + * @var integer + */ + private $backgroundColor; + + /** + * Color of the bottom border of the cell. + * @var integer + */ + private $bottomBorderColor; + + /** + * Color of the top border of the cell. + * @var integer + */ + private $topBorderColor; + + /** + * Color of the left border of the cell. + * @var integer + */ + private $leftBorderColor; + + /** + * Color of the right border of the cell. + * @var integer + */ + private $rightBorderColor; + + /** + * Constructor + * + * @access public + * @param PHPExcel_Style The XF format + */ + public function __construct(PHPExcel_Style $style = null) + { + $this->isStyleXf = false; + $this->fontIndex = 0; + + $this->numberFormatIndex = 0; + + $this->textJustLast = 0; + + $this->foregroundColor = 0x40; + $this->backgroundColor = 0x41; + + $this->_diag = 0; + + $this->bottomBorderColor = 0x40; + $this->topBorderColor = 0x40; + $this->leftBorderColor = 0x40; + $this->rightBorderColor = 0x40; + $this->_diag_color = 0x40; + $this->_style = $style; + + } + + + /** + * Generate an Excel BIFF XF record (style or cell). + * + * @return string The XF record + */ + public function writeXf() + { + // Set the type of the XF record and some of the attributes. + if ($this->isStyleXf) { + $style = 0xFFF5; + } else { + $style = self::mapLocked($this->_style->getProtection()->getLocked()); + $style |= self::mapHidden($this->_style->getProtection()->getHidden()) << 1; + } + + // Flags to indicate if attributes have been set. + $atr_num = ($this->numberFormatIndex != 0)?1:0; + $atr_fnt = ($this->fontIndex != 0)?1:0; + $atr_alc = ((int) $this->_style->getAlignment()->getWrapText()) ? 1 : 0; + $atr_bdr = (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) || + self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) || + self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) || + self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()))?1:0; + $atr_pat = (($this->foregroundColor != 0x40) || + ($this->backgroundColor != 0x41) || + self::mapFillType($this->_style->getFill()->getFillType()))?1:0; + $atr_prot = self::mapLocked($this->_style->getProtection()->getLocked()) + | self::mapHidden($this->_style->getProtection()->getHidden()); + + // Zero the default border colour if the border has not been set. + if (self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) == 0) { + $this->bottomBorderColor = 0; + } + if (self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) == 0) { + $this->topBorderColor = 0; + } + if (self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) == 0) { + $this->rightBorderColor = 0; + } + if (self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()) == 0) { + $this->leftBorderColor = 0; + } + if (self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) == 0) { + $this->_diag_color = 0; + } + + $record = 0x00E0; // Record identifier + $length = 0x0014; // Number of bytes to follow + + $ifnt = $this->fontIndex; // Index to FONT record + $ifmt = $this->numberFormatIndex; // Index to FORMAT record + + $align = $this->mapHAlign($this->_style->getAlignment()->getHorizontal()); // Alignment + $align |= (int) $this->_style->getAlignment()->getWrapText() << 3; + $align |= self::mapVAlign($this->_style->getAlignment()->getVertical()) << 4; + $align |= $this->textJustLast << 7; + + $used_attrib = $atr_num << 2; + $used_attrib |= $atr_fnt << 3; + $used_attrib |= $atr_alc << 4; + $used_attrib |= $atr_bdr << 5; + $used_attrib |= $atr_pat << 6; + $used_attrib |= $atr_prot << 7; + + $icv = $this->foregroundColor; // fg and bg pattern colors + $icv |= $this->backgroundColor << 7; + + $border1 = self::mapBorderStyle($this->_style->getBorders()->getLeft()->getBorderStyle()); // Border line style and color + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getRight()->getBorderStyle()) << 4; + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getTop()->getBorderStyle()) << 8; + $border1 |= self::mapBorderStyle($this->_style->getBorders()->getBottom()->getBorderStyle()) << 12; + $border1 |= $this->leftBorderColor << 16; + $border1 |= $this->rightBorderColor << 23; + + $diagonalDirection = $this->_style->getBorders()->getDiagonalDirection(); + $diag_tl_to_rb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH + || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_DOWN; + $diag_tr_to_lb = $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_BOTH + || $diagonalDirection == PHPExcel_Style_Borders::DIAGONAL_UP; + $border1 |= $diag_tl_to_rb << 30; + $border1 |= $diag_tr_to_lb << 31; + + $border2 = $this->topBorderColor; // Border color + $border2 |= $this->bottomBorderColor << 7; + $border2 |= $this->_diag_color << 14; + $border2 |= self::mapBorderStyle($this->_style->getBorders()->getDiagonal()->getBorderStyle()) << 21; + $border2 |= self::mapFillType($this->_style->getFill()->getFillType()) << 26; + + $header = pack("vv", $record, $length); + + //BIFF8 options: identation, shrinkToFit and text direction + $biff8_options = $this->_style->getAlignment()->getIndent(); + $biff8_options |= (int) $this->_style->getAlignment()->getShrinkToFit() << 4; + + $data = pack("vvvC", $ifnt, $ifmt, $style, $align); + $data .= pack("CCC", self::mapTextRotation($this->_style->getAlignment()->getTextRotation()), $biff8_options, $used_attrib); + $data .= pack("VVv", $border1, $border2, $icv); + + return($header . $data); + } + + /** + * Is this a style XF ? + * + * @param boolean $value + */ + public function setIsStyleXf($value) + { + $this->isStyleXf = $value; + } + + /** + * Sets the cell's bottom border color + * + * @access public + * @param int $colorIndex Color index + */ + public function setBottomColor($colorIndex) + { + $this->bottomBorderColor = $colorIndex; + } + + /** + * Sets the cell's top border color + * + * @access public + * @param int $colorIndex Color index + */ + public function setTopColor($colorIndex) + { + $this->topBorderColor = $colorIndex; + } + + /** + * Sets the cell's left border color + * + * @access public + * @param int $colorIndex Color index + */ + public function setLeftColor($colorIndex) + { + $this->leftBorderColor = $colorIndex; + } + + /** + * Sets the cell's right border color + * + * @access public + * @param int $colorIndex Color index + */ + public function setRightColor($colorIndex) + { + $this->rightBorderColor = $colorIndex; + } + + /** + * Sets the cell's diagonal border color + * + * @access public + * @param int $colorIndex Color index + */ + public function setDiagColor($colorIndex) + { + $this->_diag_color = $colorIndex; + } + + + /** + * Sets the cell's foreground color + * + * @access public + * @param int $colorIndex Color index + */ + public function setFgColor($colorIndex) + { + $this->foregroundColor = $colorIndex; + } + + /** + * Sets the cell's background color + * + * @access public + * @param int $colorIndex Color index + */ + public function setBgColor($colorIndex) + { + $this->backgroundColor = $colorIndex; + } + + /** + * Sets the index to the number format record + * It can be date, time, currency, etc... + * + * @access public + * @param integer $numberFormatIndex Index to format record + */ + public function setNumberFormatIndex($numberFormatIndex) + { + $this->numberFormatIndex = $numberFormatIndex; + } + + /** + * Set the font index. + * + * @param int $value Font index, note that value 4 does not exist + */ + public function setFontIndex($value) + { + $this->fontIndex = $value; + } + + /** + * Map of BIFF2-BIFF8 codes for border styles + * @static array of int + * + */ + private static $mapBorderStyles = array( + PHPExcel_Style_Border::BORDER_NONE => 0x00, + PHPExcel_Style_Border::BORDER_THIN => 0x01, + PHPExcel_Style_Border::BORDER_MEDIUM => 0x02, + PHPExcel_Style_Border::BORDER_DASHED => 0x03, + PHPExcel_Style_Border::BORDER_DOTTED => 0x04, + PHPExcel_Style_Border::BORDER_THICK => 0x05, + PHPExcel_Style_Border::BORDER_DOUBLE => 0x06, + PHPExcel_Style_Border::BORDER_HAIR => 0x07, + PHPExcel_Style_Border::BORDER_MEDIUMDASHED => 0x08, + PHPExcel_Style_Border::BORDER_DASHDOT => 0x09, + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT => 0x0A, + PHPExcel_Style_Border::BORDER_DASHDOTDOT => 0x0B, + PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT => 0x0C, + PHPExcel_Style_Border::BORDER_SLANTDASHDOT => 0x0D, + ); + + /** + * Map border style + * + * @param string $borderStyle + * @return int + */ + private static function mapBorderStyle($borderStyle) + { + if (isset(self::$mapBorderStyles[$borderStyle])) { + return self::$mapBorderStyles[$borderStyle]; + } + return 0x00; + } + + /** + * Map of BIFF2-BIFF8 codes for fill types + * @static array of int + * + */ + private static $mapFillTypes = array( + PHPExcel_Style_Fill::FILL_NONE => 0x00, + PHPExcel_Style_Fill::FILL_SOLID => 0x01, + PHPExcel_Style_Fill::FILL_PATTERN_MEDIUMGRAY => 0x02, + PHPExcel_Style_Fill::FILL_PATTERN_DARKGRAY => 0x03, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRAY => 0x04, + PHPExcel_Style_Fill::FILL_PATTERN_DARKHORIZONTAL => 0x05, + PHPExcel_Style_Fill::FILL_PATTERN_DARKVERTICAL => 0x06, + PHPExcel_Style_Fill::FILL_PATTERN_DARKDOWN => 0x07, + PHPExcel_Style_Fill::FILL_PATTERN_DARKUP => 0x08, + PHPExcel_Style_Fill::FILL_PATTERN_DARKGRID => 0x09, + PHPExcel_Style_Fill::FILL_PATTERN_DARKTRELLIS => 0x0A, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTHORIZONTAL => 0x0B, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTVERTICAL => 0x0C, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTDOWN => 0x0D, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTUP => 0x0E, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTGRID => 0x0F, + PHPExcel_Style_Fill::FILL_PATTERN_LIGHTTRELLIS => 0x10, + PHPExcel_Style_Fill::FILL_PATTERN_GRAY125 => 0x11, + PHPExcel_Style_Fill::FILL_PATTERN_GRAY0625 => 0x12, + PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR => 0x00, // does not exist in BIFF8 + PHPExcel_Style_Fill::FILL_GRADIENT_PATH => 0x00, // does not exist in BIFF8 + ); + + /** + * Map fill type + * + * @param string $fillType + * @return int + */ + private static function mapFillType($fillType) + { + if (isset(self::$mapFillTypes[$fillType])) { + return self::$mapFillTypes[$fillType]; + } + return 0x00; + } + + /** + * Map of BIFF2-BIFF8 codes for horizontal alignment + * @static array of int + * + */ + private static $mapHAlignments = array( + PHPExcel_Style_Alignment::HORIZONTAL_GENERAL => 0, + PHPExcel_Style_Alignment::HORIZONTAL_LEFT => 1, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER => 2, + PHPExcel_Style_Alignment::HORIZONTAL_RIGHT => 3, + PHPExcel_Style_Alignment::HORIZONTAL_FILL => 4, + PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY => 5, + PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS => 6, + ); + + /** + * Map to BIFF2-BIFF8 codes for horizontal alignment + * + * @param string $hAlign + * @return int + */ + private function mapHAlign($hAlign) + { + if (isset(self::$mapHAlignments[$hAlign])) { + return self::$mapHAlignments[$hAlign]; + } + return 0; + } + + /** + * Map of BIFF2-BIFF8 codes for vertical alignment + * @static array of int + * + */ + private static $mapVAlignments = array( + PHPExcel_Style_Alignment::VERTICAL_TOP => 0, + PHPExcel_Style_Alignment::VERTICAL_CENTER => 1, + PHPExcel_Style_Alignment::VERTICAL_BOTTOM => 2, + PHPExcel_Style_Alignment::VERTICAL_JUSTIFY => 3, + ); + + /** + * Map to BIFF2-BIFF8 codes for vertical alignment + * + * @param string $vAlign + * @return int + */ + private static function mapVAlign($vAlign) + { + if (isset(self::$mapVAlignments[$vAlign])) { + return self::$mapVAlignments[$vAlign]; + } + return 2; + } + + /** + * Map to BIFF8 codes for text rotation angle + * + * @param int $textRotation + * @return int + */ + private static function mapTextRotation($textRotation) + { + if ($textRotation >= 0) { + return $textRotation; + } elseif ($textRotation == -165) { + return 255; + } elseif ($textRotation < 0) { + return 90 - $textRotation; + } + } + + /** + * Map locked + * + * @param string + * @return int + */ + private static function mapLocked($locked) + { + switch ($locked) { + case PHPExcel_Style_Protection::PROTECTION_INHERIT: + return 1; + case PHPExcel_Style_Protection::PROTECTION_PROTECTED: + return 1; + case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: + return 0; + default: + return 1; + } + } + + /** + * Map hidden + * + * @param string + * @return int + */ + private static function mapHidden($hidden) + { + switch ($hidden) { + case PHPExcel_Style_Protection::PROTECTION_INHERIT: + return 0; + case PHPExcel_Style_Protection::PROTECTION_PROTECTED: + return 1; + case PHPExcel_Style_Protection::PROTECTION_UNPROTECTED: + return 0; + default: + return 0; + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Exception.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Exception.php new file mode 100644 index 00000000..bfa00568 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/Exception.php @@ -0,0 +1,46 @@ +<?php + +/** + * PHPExcel_Writer_Exception + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_Exception extends PHPExcel_Exception +{ + /** + * Error handler callback + * + * @param mixed $code + * @param mixed $string + * @param mixed $file + * @param mixed $line + * @param mixed $context + */ + public static function errorHandlerCallback($code, $string, $file, $line, $context) + { + $e = new self($string, $code); + $e->line = $line; + $e->file = $file; + throw $e; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/HTML.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/HTML.php new file mode 100644 index 00000000..31d7c63a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/HTML.php @@ -0,0 +1,1612 @@ +<?php + +/** + * PHPExcel_Writer_HTML + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_HTML + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_HTML extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * PHPExcel object + * + * @var PHPExcel + */ + protected $phpExcel; + + /** + * Sheet index to write + * + * @var int + */ + private $sheetIndex = 0; + + /** + * Images root + * + * @var string + */ + private $imagesRoot = '.'; + + /** + * embed images, or link to images + * + * @var boolean + */ + private $embedImages = false; + + /** + * Use inline CSS? + * + * @var boolean + */ + private $useInlineCss = false; + + /** + * Array of CSS styles + * + * @var array + */ + private $cssStyles; + + /** + * Array of column widths in points + * + * @var array + */ + private $columnWidths; + + /** + * Default font + * + * @var PHPExcel_Style_Font + */ + private $defaultFont; + + /** + * Flag whether spans have been calculated + * + * @var boolean + */ + private $spansAreCalculated = false; + + /** + * Excel cells that should not be written as HTML cells + * + * @var array + */ + private $isSpannedCell = array(); + + /** + * Excel cells that are upper-left corner in a cell merge + * + * @var array + */ + private $isBaseCell = array(); + + /** + * Excel rows that should not be written as HTML rows + * + * @var array + */ + private $isSpannedRow = array(); + + /** + * Is the current writer creating PDF? + * + * @var boolean + */ + protected $isPdf = false; + + /** + * Generate the Navigation block + * + * @var boolean + */ + private $generateSheetNavigationBlock = true; + + /** + * Create a new PHPExcel_Writer_HTML + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + $this->phpExcel = $phpExcel; + $this->defaultFont = $this->phpExcel->getDefaultStyle()->getFont(); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + // garbage collect + $this->phpExcel->garbageCollect(); + + $saveDebugLog = PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->getWriteDebugLog(); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog(false); + $saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Build CSS + $this->buildCSS(!$this->useInlineCss); + + // Open file + $fileHandle = fopen($pFilename, 'wb+'); + if ($fileHandle === false) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + // Write headers + fwrite($fileHandle, $this->generateHTMLHeader(!$this->useInlineCss)); + + // Write navigation (tabs) + if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) { + fwrite($fileHandle, $this->generateNavigation()); + } + + // Write data + fwrite($fileHandle, $this->generateSheetData()); + + // Write footer + fwrite($fileHandle, $this->generateHTMLFooter()); + + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($saveArrayReturnType); + PHPExcel_Calculation::getInstance($this->phpExcel)->getDebugLog()->setWriteDebugLog($saveDebugLog); + } + + /** + * Map VAlign + * + * @param string $vAlign Vertical alignment + * @return string + */ + private function mapVAlign($vAlign) + { + switch ($vAlign) { + case PHPExcel_Style_Alignment::VERTICAL_BOTTOM: + return 'bottom'; + case PHPExcel_Style_Alignment::VERTICAL_TOP: + return 'top'; + case PHPExcel_Style_Alignment::VERTICAL_CENTER: + case PHPExcel_Style_Alignment::VERTICAL_JUSTIFY: + return 'middle'; + default: + return 'baseline'; + } + } + + /** + * Map HAlign + * + * @param string $hAlign Horizontal alignment + * @return string|false + */ + private function mapHAlign($hAlign) + { + switch ($hAlign) { + case PHPExcel_Style_Alignment::HORIZONTAL_GENERAL: + return false; + case PHPExcel_Style_Alignment::HORIZONTAL_LEFT: + return 'left'; + case PHPExcel_Style_Alignment::HORIZONTAL_RIGHT: + return 'right'; + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER: + case PHPExcel_Style_Alignment::HORIZONTAL_CENTER_CONTINUOUS: + return 'center'; + case PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY: + return 'justify'; + default: + return false; + } + } + + /** + * Map border style + * + * @param int $borderStyle Sheet index + * @return string + */ + private function mapBorderStyle($borderStyle) + { + switch ($borderStyle) { + case PHPExcel_Style_Border::BORDER_NONE: + return 'none'; + case PHPExcel_Style_Border::BORDER_DASHDOT: + return '1px dashed'; + case PHPExcel_Style_Border::BORDER_DASHDOTDOT: + return '1px dotted'; + case PHPExcel_Style_Border::BORDER_DASHED: + return '1px dashed'; + case PHPExcel_Style_Border::BORDER_DOTTED: + return '1px dotted'; + case PHPExcel_Style_Border::BORDER_DOUBLE: + return '3px double'; + case PHPExcel_Style_Border::BORDER_HAIR: + return '1px solid'; + case PHPExcel_Style_Border::BORDER_MEDIUM: + return '2px solid'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOT: + return '2px dashed'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHDOTDOT: + return '2px dotted'; + case PHPExcel_Style_Border::BORDER_MEDIUMDASHED: + return '2px dashed'; + case PHPExcel_Style_Border::BORDER_SLANTDASHDOT: + return '2px dashed'; + case PHPExcel_Style_Border::BORDER_THICK: + return '3px solid'; + case PHPExcel_Style_Border::BORDER_THIN: + return '1px solid'; + default: + // map others to thin + return '1px solid'; + } + } + + /** + * Get sheet index + * + * @return int + */ + public function getSheetIndex() + { + return $this->sheetIndex; + } + + /** + * Set sheet index + * + * @param int $pValue Sheet index + * @return PHPExcel_Writer_HTML + */ + public function setSheetIndex($pValue = 0) + { + $this->sheetIndex = $pValue; + return $this; + } + + /** + * Get sheet index + * + * @return boolean + */ + public function getGenerateSheetNavigationBlock() + { + return $this->generateSheetNavigationBlock; + } + + /** + * Set sheet index + * + * @param boolean $pValue Flag indicating whether the sheet navigation block should be generated or not + * @return PHPExcel_Writer_HTML + */ + public function setGenerateSheetNavigationBlock($pValue = true) + { + $this->generateSheetNavigationBlock = (bool) $pValue; + return $this; + } + + /** + * Write all sheets (resets sheetIndex to NULL) + */ + public function writeAllSheets() + { + $this->sheetIndex = null; + return $this; + } + + /** + * Generate HTML header + * + * @param boolean $pIncludeStyles Include styles? + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateHTMLHeader($pIncludeStyles = false) + { + // PHPExcel object known? + if (is_null($this->phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Construct HTML + $properties = $this->phpExcel->getProperties(); + $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . PHP_EOL; + $html .= '<!-- Generated by PHPExcel - http://www.phpexcel.net -->' . PHP_EOL; + $html .= '<html>' . PHP_EOL; + $html .= ' <head>' . PHP_EOL; + $html .= ' <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . PHP_EOL; + if ($properties->getTitle() > '') { + $html .= ' <title>' . htmlspecialchars($properties->getTitle()) . '</title>' . PHP_EOL; + } + if ($properties->getCreator() > '') { + $html .= ' <meta name="author" content="' . htmlspecialchars($properties->getCreator()) . '" />' . PHP_EOL; + } + if ($properties->getTitle() > '') { + $html .= ' <meta name="title" content="' . htmlspecialchars($properties->getTitle()) . '" />' . PHP_EOL; + } + if ($properties->getDescription() > '') { + $html .= ' <meta name="description" content="' . htmlspecialchars($properties->getDescription()) . '" />' . PHP_EOL; + } + if ($properties->getSubject() > '') { + $html .= ' <meta name="subject" content="' . htmlspecialchars($properties->getSubject()) . '" />' . PHP_EOL; + } + if ($properties->getKeywords() > '') { + $html .= ' <meta name="keywords" content="' . htmlspecialchars($properties->getKeywords()) . '" />' . PHP_EOL; + } + if ($properties->getCategory() > '') { + $html .= ' <meta name="category" content="' . htmlspecialchars($properties->getCategory()) . '" />' . PHP_EOL; + } + if ($properties->getCompany() > '') { + $html .= ' <meta name="company" content="' . htmlspecialchars($properties->getCompany()) . '" />' . PHP_EOL; + } + if ($properties->getManager() > '') { + $html .= ' <meta name="manager" content="' . htmlspecialchars($properties->getManager()) . '" />' . PHP_EOL; + } + + if ($pIncludeStyles) { + $html .= $this->generateStyles(true); + } + + $html .= ' </head>' . PHP_EOL; + $html .= '' . PHP_EOL; + $html .= ' <body>' . PHP_EOL; + + return $html; + } + + /** + * Generate sheet data + * + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateSheetData() + { + // PHPExcel object known? + if (is_null($this->phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Ensure that Spans have been calculated? + if ($this->sheetIndex !== null || !$this->spansAreCalculated) { + $this->calculateSpans(); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->sheetIndex)) { + $sheets = $this->phpExcel->getAllSheets(); + } else { + $sheets[] = $this->phpExcel->getSheet($this->sheetIndex); + } + + // Construct HTML + $html = ''; + + // Loop all sheets + $sheetId = 0; + foreach ($sheets as $sheet) { + // Write table header + $html .= $this->generateTableHeader($sheet); + + // Get worksheet dimension + $dimension = explode(':', $sheet->calculateWorksheetDimension()); + $dimension[0] = PHPExcel_Cell::coordinateFromString($dimension[0]); + $dimension[0][0] = PHPExcel_Cell::columnIndexFromString($dimension[0][0]) - 1; + $dimension[1] = PHPExcel_Cell::coordinateFromString($dimension[1]); + $dimension[1][0] = PHPExcel_Cell::columnIndexFromString($dimension[1][0]) - 1; + + // row min,max + $rowMin = $dimension[0][1]; + $rowMax = $dimension[1][1]; + + // calculate start of <tbody>, <thead> + $tbodyStart = $rowMin; + $theadStart = $theadEnd = 0; // default: no <thead> no </thead> + if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) { + $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop(); + + // we can only support repeating rows that start at top row + if ($rowsToRepeatAtTop[0] == 1) { + $theadStart = $rowsToRepeatAtTop[0]; + $theadEnd = $rowsToRepeatAtTop[1]; + $tbodyStart = $rowsToRepeatAtTop[1] + 1; + } + } + + // Loop through cells + $row = $rowMin-1; + while ($row++ < $rowMax) { + // <thead> ? + if ($row == $theadStart) { + $html .= ' <thead>' . PHP_EOL; + $cellType = 'th'; + } + + // <tbody> ? + if ($row == $tbodyStart) { + $html .= ' <tbody>' . PHP_EOL; + $cellType = 'td'; + } + + // Write row if there are HTML table cells in it + if (!isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) { + // Start a new rowData + $rowData = array(); + // Loop through columns + $column = $dimension[0][0] - 1; + while ($column++ < $dimension[1][0]) { + // Cell exists? + if ($sheet->cellExistsByColumnAndRow($column, $row)) { + $rowData[$column] = PHPExcel_Cell::stringFromColumnIndex($column) . $row; + } else { + $rowData[$column] = ''; + } + } + $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType); + } + + // </thead> ? + if ($row == $theadEnd) { + $html .= ' </thead>' . PHP_EOL; + } + } + $html .= $this->extendRowsForChartsAndImages($sheet, $row); + + // Close table body. + $html .= ' </tbody>' . PHP_EOL; + + // Write table footer + $html .= $this->generateTableFooter(); + + // Writing PDF? + if ($this->isPdf) { + if (is_null($this->sheetIndex) && $sheetId + 1 < $this->phpExcel->getSheetCount()) { + $html .= '<div style="page-break-before:always" />'; + } + } + + // Next sheet + ++$sheetId; + } + + return $html; + } + + /** + * Generate sheet tabs + * + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateNavigation() + { + // PHPExcel object known? + if (is_null($this->phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->sheetIndex)) { + $sheets = $this->phpExcel->getAllSheets(); + } else { + $sheets[] = $this->phpExcel->getSheet($this->sheetIndex); + } + + // Construct HTML + $html = ''; + + // Only if there are more than 1 sheets + if (count($sheets) > 1) { + // Loop all sheets + $sheetId = 0; + + $html .= '<ul class="navigation">' . PHP_EOL; + + foreach ($sheets as $sheet) { + $html .= ' <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL; + ++$sheetId; + } + + $html .= '</ul>' . PHP_EOL; + } + + return $html; + } + + private function extendRowsForChartsAndImages(PHPExcel_Worksheet $pSheet, $row) + { + $rowMax = $row; + $colMax = 'A'; + if ($this->includeCharts) { + foreach ($pSheet->getChartCollection() as $chart) { + if ($chart instanceof PHPExcel_Chart) { + $chartCoordinates = $chart->getTopLeftPosition(); + $chartTL = PHPExcel_Cell::coordinateFromString($chartCoordinates['cell']); + $chartCol = PHPExcel_Cell::columnIndexFromString($chartTL[0]); + if ($chartTL[1] > $rowMax) { + $rowMax = $chartTL[1]; + if ($chartCol > PHPExcel_Cell::columnIndexFromString($colMax)) { + $colMax = $chartTL[0]; + } + } + } + } + } + + foreach ($pSheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + $imageTL = PHPExcel_Cell::coordinateFromString($drawing->getCoordinates()); + $imageCol = PHPExcel_Cell::columnIndexFromString($imageTL[0]); + if ($imageTL[1] > $rowMax) { + $rowMax = $imageTL[1]; + if ($imageCol > PHPExcel_Cell::columnIndexFromString($colMax)) { + $colMax = $imageTL[0]; + } + } + } + } + + $html = ''; + $colMax++; + while ($row <= $rowMax) { + $html .= '<tr>'; + for ($col = 'A'; $col != $colMax; ++$col) { + $html .= '<td>'; + $html .= $this->writeImageInCell($pSheet, $col.$row); + if ($this->includeCharts) { + $html .= $this->writeChartInCell($pSheet, $col.$row); + } + $html .= '</td>'; + } + ++$row; + $html .= '</tr>'; + } + return $html; + } + + + /** + * Generate image tag in cell + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param string $coordinates Cell coordinates + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function writeImageInCell(PHPExcel_Worksheet $pSheet, $coordinates) + { + // Construct HTML + $html = ''; + + // Write images + foreach ($pSheet->getDrawingCollection() as $drawing) { + if ($drawing instanceof PHPExcel_Worksheet_Drawing) { + if ($drawing->getCoordinates() == $coordinates) { + $filename = $drawing->getPath(); + + // Strip off eventual '.' + if (substr($filename, 0, 1) == '.') { + $filename = substr($filename, 1); + } + + // Prepend images root + $filename = $this->getImagesRoot() . $filename; + + // Strip off eventual '.' + if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') { + $filename = substr($filename, 1); + } + + // Convert UTF8 data to PCDATA + $filename = htmlspecialchars($filename); + + $html .= PHP_EOL; + if ((!$this->embedImages) || ($this->isPdf)) { + $imageData = $filename; + } else { + $imageDetails = getimagesize($filename); + if ($fp = fopen($filename, "rb", 0)) { + $picture = fread($fp, filesize($filename)); + fclose($fp); + // base64 encode the binary data, then break it + // into chunks according to RFC 2045 semantics + $base64 = chunk_split(base64_encode($picture)); + $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + } else { + $imageData = $filename; + } + } + + $html .= '<div style="position: relative;">'; + $html .= '<img style="position: absolute; z-index: 1; left: ' . + $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' . + $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' . + $imageData . '" border="0" />'; + $html .= '</div>'; + } + } elseif ($drawing instanceof PHPExcel_Worksheet_MemoryDrawing) { + if ($drawing->getCoordinates() != $coordinates) { + continue; + } + ob_start(); // Let's start output buffering. + imagepng($drawing->getImageResource()); // This will normally output the image, but because of ob_start(), it won't. + $contents = ob_get_contents(); // Instead, output above is saved to $contents + ob_end_clean(); // End the output buffer. + + $dataUri = "data:image/jpeg;base64," . base64_encode($contents); + + // Because of the nature of tables, width is more important than height. + // max-width: 100% ensures that image doesnt overflow containing cell + // width: X sets width of supplied image. + // As a result, images bigger than cell will be contained and images smaller will not get stretched + $html .= '<img src="'.$dataUri.'" style="max-width:100%;width:'.$drawing->getWidth().'px;" />'; + } + } + + return $html; + } + + /** + * Generate chart tag in cell + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param string $coordinates Cell coordinates + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function writeChartInCell(PHPExcel_Worksheet $pSheet, $coordinates) + { + // Construct HTML + $html = ''; + + // Write charts + foreach ($pSheet->getChartCollection() as $chart) { + if ($chart instanceof PHPExcel_Chart) { + $chartCoordinates = $chart->getTopLeftPosition(); + if ($chartCoordinates['cell'] == $coordinates) { + $chartFileName = PHPExcel_Shared_File::sys_get_temp_dir().'/'.uniqid().'.png'; + if (!$chart->render($chartFileName)) { + return; + } + + $html .= PHP_EOL; + $imageDetails = getimagesize($chartFileName); + if ($fp = fopen($chartFileName, "rb", 0)) { + $picture = fread($fp, filesize($chartFileName)); + fclose($fp); + // base64 encode the binary data, then break it + // into chunks according to RFC 2045 semantics + $base64 = chunk_split(base64_encode($picture)); + $imageData = 'data:'.$imageDetails['mime'].';base64,' . $base64; + + $html .= '<div style="position: relative;">'; + $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" border="0" />' . PHP_EOL; + $html .= '</div>'; + + unlink($chartFileName); + } + } + } + } + + // Return + return $html; + } + + /** + * Generate CSS styles + * + * @param boolean $generateSurroundingHTML Generate surrounding HTML tags? (&lt;style&gt; and &lt;/style&gt;) + * @return string + * @throws PHPExcel_Writer_Exception + */ + public function generateStyles($generateSurroundingHTML = true) + { + // PHPExcel object known? + if (is_null($this->phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Build CSS + $css = $this->buildCSS($generateSurroundingHTML); + + // Construct HTML + $html = ''; + + // Start styles + if ($generateSurroundingHTML) { + $html .= ' <style type="text/css">' . PHP_EOL; + $html .= ' html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL; + } + + // Write all other styles + foreach ($css as $styleName => $styleDefinition) { + if ($styleName != 'html') { + $html .= ' ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL; + } + } + + // End styles + if ($generateSurroundingHTML) { + $html .= ' </style>' . PHP_EOL; + } + + // Return + return $html; + } + + /** + * Build CSS styles + * + * @param boolean $generateSurroundingHTML Generate surrounding HTML style? (html { }) + * @return array + * @throws PHPExcel_Writer_Exception + */ + public function buildCSS($generateSurroundingHTML = true) + { + // PHPExcel object known? + if (is_null($this->phpExcel)) { + throw new PHPExcel_Writer_Exception('Internal PHPExcel object not set to an instance of an object.'); + } + + // Cached? + if (!is_null($this->cssStyles)) { + return $this->cssStyles; + } + + // Ensure that spans have been calculated + if (!$this->spansAreCalculated) { + $this->calculateSpans(); + } + + // Construct CSS + $css = array(); + + // Start styles + if ($generateSurroundingHTML) { + // html { } + $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif'; + $css['html']['font-size'] = '11pt'; + $css['html']['background-color'] = 'white'; + } + + + // table { } + $css['table']['border-collapse'] = 'collapse'; + if (!$this->isPdf) { + $css['table']['page-break-after'] = 'always'; + } + + // .gridlines td { } + $css['.gridlines td']['border'] = '1px dotted black'; + $css['.gridlines th']['border'] = '1px dotted black'; + + // .b {} + $css['.b']['text-align'] = 'center'; // BOOL + + // .e {} + $css['.e']['text-align'] = 'center'; // ERROR + + // .f {} + $css['.f']['text-align'] = 'right'; // FORMULA + + // .inlineStr {} + $css['.inlineStr']['text-align'] = 'left'; // INLINE + + // .n {} + $css['.n']['text-align'] = 'right'; // NUMERIC + + // .s {} + $css['.s']['text-align'] = 'left'; // STRING + + // Calculate cell style hashes + foreach ($this->phpExcel->getCellXfCollection() as $index => $style) { + $css['td.style' . $index] = $this->createCSSStyle($style); + $css['th.style' . $index] = $this->createCSSStyle($style); + } + + // Fetch sheets + $sheets = array(); + if (is_null($this->sheetIndex)) { + $sheets = $this->phpExcel->getAllSheets(); + } else { + $sheets[] = $this->phpExcel->getSheet($this->sheetIndex); + } + + // Build styles per sheet + foreach ($sheets as $sheet) { + // Calculate hash code + $sheetIndex = $sheet->getParent()->getIndex($sheet); + + // Build styles + // Calculate column widths + $sheet->calculateColumnWidths(); + + // col elements, initialize + $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()) - 1; + $column = -1; + while ($column++ < $highestColumnIndex) { + $this->columnWidths[$sheetIndex][$column] = 42; // approximation + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt'; + } + + // col elements, loop through columnDimensions and set width + foreach ($sheet->getColumnDimensions() as $columnDimension) { + if (($width = PHPExcel_Shared_Drawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont)) >= 0) { + $width = PHPExcel_Shared_Drawing::pixelsToPoints($width); + $column = PHPExcel_Cell::columnIndexFromString($columnDimension->getColumnIndex()) - 1; + $this->columnWidths[$sheetIndex][$column] = $width; + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt'; + + if ($columnDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse'; + $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7 + } + } + } + + // Default row height + $rowDimension = $sheet->getDefaultRowDimension(); + + // table.sheetN tr { } + $css['table.sheet' . $sheetIndex . ' tr'] = array(); + + if ($rowDimension->getRowHeight() == -1) { + $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->phpExcel->getDefaultStyle()->getFont()); + } else { + $pt_height = $rowDimension->getRowHeight(); + } + $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt'; + if ($rowDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none'; + $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden'; + } + + // Calculate row heights + foreach ($sheet->getRowDimensions() as $rowDimension) { + $row = $rowDimension->getRowIndex() - 1; + + // table.sheetN tr.rowYYYYYY { } + $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = array(); + + if ($rowDimension->getRowHeight() == -1) { + $pt_height = PHPExcel_Shared_Font::getDefaultRowHeightByFont($this->phpExcel->getDefaultStyle()->getFont()); + } else { + $pt_height = $rowDimension->getRowHeight(); + } + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt'; + if ($rowDimension->getVisible() === false) { + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none'; + $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden'; + } + } + } + + // Cache + if (is_null($this->cssStyles)) { + $this->cssStyles = $css; + } + + // Return + return $css; + } + + /** + * Create CSS style + * + * @param PHPExcel_Style $pStyle PHPExcel_Style + * @return array + */ + private function createCSSStyle(PHPExcel_Style $pStyle) + { + // Construct CSS + $css = ''; + + // Create CSS + $css = array_merge( + $this->createCSSStyleAlignment($pStyle->getAlignment()), + $this->createCSSStyleBorders($pStyle->getBorders()), + $this->createCSSStyleFont($pStyle->getFont()), + $this->createCSSStyleFill($pStyle->getFill()) + ); + + // Return + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Alignment) + * + * @param PHPExcel_Style_Alignment $pStyle PHPExcel_Style_Alignment + * @return array + */ + private function createCSSStyleAlignment(PHPExcel_Style_Alignment $pStyle) + { + // Construct CSS + $css = array(); + + // Create CSS + $css['vertical-align'] = $this->mapVAlign($pStyle->getVertical()); + if ($textAlign = $this->mapHAlign($pStyle->getHorizontal())) { + $css['text-align'] = $textAlign; + if (in_array($textAlign, array('left', 'right'))) { + $css['padding-'.$textAlign] = (string)((int)$pStyle->getIndent() * 9).'px'; + } + } + + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Font) + * + * @param PHPExcel_Style_Font $pStyle PHPExcel_Style_Font + * @return array + */ + private function createCSSStyleFont(PHPExcel_Style_Font $pStyle) + { + // Construct CSS + $css = array(); + + // Create CSS + if ($pStyle->getBold()) { + $css['font-weight'] = 'bold'; + } + if ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) { + $css['text-decoration'] = 'underline line-through'; + } elseif ($pStyle->getUnderline() != PHPExcel_Style_Font::UNDERLINE_NONE) { + $css['text-decoration'] = 'underline'; + } elseif ($pStyle->getStrikethrough()) { + $css['text-decoration'] = 'line-through'; + } + if ($pStyle->getItalic()) { + $css['font-style'] = 'italic'; + } + + $css['color'] = '#' . $pStyle->getColor()->getRGB(); + $css['font-family'] = '\'' . $pStyle->getName() . '\''; + $css['font-size'] = $pStyle->getSize() . 'pt'; + + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Borders) + * + * @param PHPExcel_Style_Borders $pStyle PHPExcel_Style_Borders + * @return array + */ + private function createCSSStyleBorders(PHPExcel_Style_Borders $pStyle) + { + // Construct CSS + $css = array(); + + // Create CSS + $css['border-bottom'] = $this->createCSSStyleBorder($pStyle->getBottom()); + $css['border-top'] = $this->createCSSStyleBorder($pStyle->getTop()); + $css['border-left'] = $this->createCSSStyleBorder($pStyle->getLeft()); + $css['border-right'] = $this->createCSSStyleBorder($pStyle->getRight()); + + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Border) + * + * @param PHPExcel_Style_Border $pStyle PHPExcel_Style_Border + * @return string + */ + private function createCSSStyleBorder(PHPExcel_Style_Border $pStyle) + { + // Create CSS +// $css = $this->mapBorderStyle($pStyle->getBorderStyle()) . ' #' . $pStyle->getColor()->getRGB(); + // Create CSS - add !important to non-none border styles for merged cells + $borderStyle = $this->mapBorderStyle($pStyle->getBorderStyle()); + $css = $borderStyle . ' #' . $pStyle->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important'); + + return $css; + } + + /** + * Create CSS style (PHPExcel_Style_Fill) + * + * @param PHPExcel_Style_Fill $pStyle PHPExcel_Style_Fill + * @return array + */ + private function createCSSStyleFill(PHPExcel_Style_Fill $pStyle) + { + // Construct HTML + $css = array(); + + // Create CSS + $value = $pStyle->getFillType() == PHPExcel_Style_Fill::FILL_NONE ? + 'white' : '#' . $pStyle->getStartColor()->getRGB(); + $css['background-color'] = $value; + + return $css; + } + + /** + * Generate HTML footer + */ + public function generateHTMLFooter() + { + // Construct HTML + $html = ''; + $html .= ' </body>' . PHP_EOL; + $html .= '</html>' . PHP_EOL; + + return $html; + } + + /** + * Generate table header + * + * @param PHPExcel_Worksheet $pSheet The worksheet for the table we are writing + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function generateTableHeader($pSheet) + { + $sheetIndex = $pSheet->getParent()->getIndex($pSheet); + + // Construct HTML + $html = ''; + $html .= $this->setMargins($pSheet); + + if (!$this->useInlineCss) { + $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : ''; + $html .= ' <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL; + } else { + $style = isset($this->cssStyles['table']) ? + $this->assembleCSS($this->cssStyles['table']) : ''; + + if ($this->isPdf && $pSheet->getShowGridlines()) { + $html .= ' <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="1" style="' . $style . '">' . PHP_EOL; + } else { + $html .= ' <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="0" style="' . $style . '">' . PHP_EOL; + } + } + + // Write <col> elements + $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($pSheet->getHighestColumn()) - 1; + $i = -1; + while ($i++ < $highestColumnIndex) { + if (!$this->isPdf) { + if (!$this->useInlineCss) { + $html .= ' <col class="col' . $i . '">' . PHP_EOL; + } else { + $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ? + $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : ''; + $html .= ' <col style="' . $style . '">' . PHP_EOL; + } + } + } + + return $html; + } + + /** + * Generate table footer + * + * @throws PHPExcel_Writer_Exception + */ + private function generateTableFooter() + { + $html = ' </table>' . PHP_EOL; + + return $html; + } + + /** + * Generate row + * + * @param PHPExcel_Worksheet $pSheet PHPExcel_Worksheet + * @param array $pValues Array containing cells in a row + * @param int $pRow Row number (0-based) + * @return string + * @throws PHPExcel_Writer_Exception + */ + private function generateRow(PHPExcel_Worksheet $pSheet, $pValues = null, $pRow = 0, $cellType = 'td') + { + if (is_array($pValues)) { + // Construct HTML + $html = ''; + + // Sheet index + $sheetIndex = $pSheet->getParent()->getIndex($pSheet); + + // DomPDF and breaks + if ($this->isPdf && count($pSheet->getBreaks()) > 0) { + $breaks = $pSheet->getBreaks(); + + // check if a break is needed before this row + if (isset($breaks['A' . $pRow])) { + // close table: </table> + $html .= $this->generateTableFooter(); + + // insert page break + $html .= '<div style="page-break-before:always" />'; + + // open table again: <table> + <col> etc. + $html .= $this->generateTableHeader($pSheet); + } + } + + // Write row start + if (!$this->useInlineCss) { + $html .= ' <tr class="row' . $pRow . '">' . PHP_EOL; + } else { + $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) + ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : ''; + + $html .= ' <tr style="' . $style . '">' . PHP_EOL; + } + + // Write cells + $colNum = 0; + foreach ($pValues as $cellAddress) { + $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : ''; + $coordinate = PHPExcel_Cell::stringFromColumnIndex($colNum) . ($pRow + 1); + if (!$this->useInlineCss) { + $cssClass = ''; + $cssClass = 'column' . $colNum; + } else { + $cssClass = array(); + if ($cellType == 'th') { + if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) { + $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum]; + } + } else { + if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) { + $this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum]; + } + } + } + $colSpan = 1; + $rowSpan = 1; + + // initialize + $cellData = '&nbsp;'; + + // PHPExcel_Cell + if ($cell instanceof PHPExcel_Cell) { + $cellData = ''; + if (is_null($cell->getParent())) { + $cell->attach($pSheet); + } + // Value + if ($cell->getValue() instanceof PHPExcel_RichText) { + // Loop through rich text elements + $elements = $cell->getValue()->getRichTextElements(); + foreach ($elements as $element) { + // Rich text start? + if ($element instanceof PHPExcel_RichText_Run) { + $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">'; + + if ($element->getFont()->getSuperScript()) { + $cellData .= '<sup>'; + } elseif ($element->getFont()->getSubScript()) { + $cellData .= '<sub>'; + } + } + + // Convert UTF8 data to PCDATA + $cellText = $element->getText(); + $cellData .= htmlspecialchars($cellText); + + if ($element instanceof PHPExcel_RichText_Run) { + if ($element->getFont()->getSuperScript()) { + $cellData .= '</sup>'; + } elseif ($element->getFont()->getSubScript()) { + $cellData .= '</sub>'; + } + + $cellData .= '</span>'; + } + } + } else { + if ($this->preCalculateFormulas) { + $cellData = PHPExcel_Style_NumberFormat::toFormattedString( + $cell->getCalculatedValue(), + $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), + array($this, 'formatColor') + ); + } else { + $cellData = PHPExcel_Style_NumberFormat::toFormattedString( + $cell->getValue(), + $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(), + array($this, 'formatColor') + ); + } + $cellData = htmlspecialchars($cellData); + if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperScript()) { + $cellData = '<sup>'.$cellData.'</sup>'; + } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubScript()) { + $cellData = '<sub>'.$cellData.'</sub>'; + } + } + + // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp; + // Example: " Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world" + $cellData = preg_replace("/(?m)(?:^|\\G) /", '&nbsp;', $cellData); + + // convert newline "\n" to '<br>' + $cellData = nl2br($cellData); + + // Extend CSS class? + if (!$this->useInlineCss) { + $cssClass .= ' style' . $cell->getXfIndex(); + $cssClass .= ' ' . $cell->getDataType(); + } else { + if ($cellType == 'th') { + if (isset($this->cssStyles['th.style' . $cell->getXfIndex()])) { + $cssClass = array_merge($cssClass, $this->cssStyles['th.style' . $cell->getXfIndex()]); + } + } else { + if (isset($this->cssStyles['td.style' . $cell->getXfIndex()])) { + $cssClass = array_merge($cssClass, $this->cssStyles['td.style' . $cell->getXfIndex()]); + } + } + + // General horizontal alignment: Actual horizontal alignment depends on dataType + $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex()); + if ($sharedStyle->getAlignment()->getHorizontal() == PHPExcel_Style_Alignment::HORIZONTAL_GENERAL + && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])) { + $cssClass['text-align'] = $this->cssStyles['.' . $cell->getDataType()]['text-align']; + } + } + } + + // Hyperlink? + if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) { + $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>'; + } + + // Should the cell be written or is it swallowed by a rowspan or colspan? + $writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]) + && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]); + + // Colspan and Rowspan + $colspan = 1; + $rowspan = 1; + if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) { + $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]; + $rowSpan = $spans['rowspan']; + $colSpan = $spans['colspan']; + + // Also apply style from last cell in merge to fix borders - + // relies on !important for non-none border declarations in createCSSStyleBorder + $endCellCoord = PHPExcel_Cell::stringFromColumnIndex($colNum + $colSpan - 1) . ($pRow + $rowSpan); + if (!$this->useInlineCss) { + $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex(); + } + } + + // Write + if ($writeCell) { + // Column start + $html .= ' <' . $cellType; + if (!$this->useInlineCss) { + $html .= ' class="' . $cssClass . '"'; + } else { + //** Necessary redundant code for the sake of PHPExcel_Writer_PDF ** + // We must explicitly write the width of the <td> element because TCPDF + // does not recognize e.g. <col style="width:42pt"> + $width = 0; + $i = $colNum - 1; + $e = $colNum + $colSpan - 1; + while ($i++ < $e) { + if (isset($this->columnWidths[$sheetIndex][$i])) { + $width += $this->columnWidths[$sheetIndex][$i]; + } + } + $cssClass['width'] = $width . 'pt'; + + // We must also explicitly write the height of the <td> element because TCPDF + // does not recognize e.g. <tr style="height:50pt"> + if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) { + $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height']; + $cssClass['height'] = $height; + } + //** end of redundant code ** + + $html .= ' style="' . $this->assembleCSS($cssClass) . '"'; + } + if ($colSpan > 1) { + $html .= ' colspan="' . $colSpan . '"'; + } + if ($rowSpan > 1) { + $html .= ' rowspan="' . $rowSpan . '"'; + } + $html .= '>'; + + // Image? + $html .= $this->writeImageInCell($pSheet, $coordinate); + + // Chart? + if ($this->includeCharts) { + $html .= $this->writeChartInCell($pSheet, $coordinate); + } + + // Cell data + $html .= $cellData; + + // Column end + $html .= '</'.$cellType.'>' . PHP_EOL; + } + + // Next column + ++$colNum; + } + + // Write row end + $html .= ' </tr>' . PHP_EOL; + + // Return + return $html; + } else { + throw new PHPExcel_Writer_Exception("Invalid parameters passed."); + } + } + + /** + * Takes array where of CSS properties / values and converts to CSS string + * + * @param array + * @return string + */ + private function assembleCSS($pValue = array()) + { + $pairs = array(); + foreach ($pValue as $property => $value) { + $pairs[] = $property . ':' . $value; + } + $string = implode('; ', $pairs); + + return $string; + } + + /** + * Get images root + * + * @return string + */ + public function getImagesRoot() + { + return $this->imagesRoot; + } + + /** + * Set images root + * + * @param string $pValue + * @return PHPExcel_Writer_HTML + */ + public function setImagesRoot($pValue = '.') + { + $this->imagesRoot = $pValue; + return $this; + } + + /** + * Get embed images + * + * @return boolean + */ + public function getEmbedImages() + { + return $this->embedImages; + } + + /** + * Set embed images + * + * @param boolean $pValue + * @return PHPExcel_Writer_HTML + */ + public function setEmbedImages($pValue = '.') + { + $this->embedImages = $pValue; + return $this; + } + + /** + * Get use inline CSS? + * + * @return boolean + */ + public function getUseInlineCss() + { + return $this->useInlineCss; + } + + /** + * Set use inline CSS? + * + * @param boolean $pValue + * @return PHPExcel_Writer_HTML + */ + public function setUseInlineCss($pValue = false) + { + $this->useInlineCss = $pValue; + return $this; + } + + /** + * Add color to formatted string as inline style + * + * @param string $pValue Plain formatted value without color + * @param string $pFormat Format code + * @return string + */ + public function formatColor($pValue, $pFormat) + { + // Color information, e.g. [Red] is always at the beginning + $color = null; // initialize + $matches = array(); + + $color_regex = '/^\\[[a-zA-Z]+\\]/'; + if (preg_match($color_regex, $pFormat, $matches)) { + $color = str_replace('[', '', $matches[0]); + $color = str_replace(']', '', $color); + $color = strtolower($color); + } + + // convert to PCDATA + $value = htmlspecialchars($pValue); + + // color span tag + if ($color !== null) { + $value = '<span style="color:' . $color . '">' . $value . '</span>'; + } + + return $value; + } + + /** + * Calculate information about HTML colspan and rowspan which is not always the same as Excel's + */ + private function calculateSpans() + { + // Identify all cells that should be omitted in HTML due to cell merge. + // In HTML only the upper-left cell should be written and it should have + // appropriate rowspan / colspan attribute + $sheetIndexes = $this->sheetIndex !== null ? + array($this->sheetIndex) : range(0, $this->phpExcel->getSheetCount() - 1); + + foreach ($sheetIndexes as $sheetIndex) { + $sheet = $this->phpExcel->getSheet($sheetIndex); + + $candidateSpannedRow = array(); + + // loop through all Excel merged cells + foreach ($sheet->getMergeCells() as $cells) { + list($cells,) = PHPExcel_Cell::splitRange($cells); + $first = $cells[0]; + $last = $cells[1]; + + list($fc, $fr) = PHPExcel_Cell::coordinateFromString($first); + $fc = PHPExcel_Cell::columnIndexFromString($fc) - 1; + + list($lc, $lr) = PHPExcel_Cell::coordinateFromString($last); + $lc = PHPExcel_Cell::columnIndexFromString($lc) - 1; + + // loop through the individual cells in the individual merge + $r = $fr - 1; + while ($r++ < $lr) { + // also, flag this row as a HTML row that is candidate to be omitted + $candidateSpannedRow[$r] = $r; + + $c = $fc - 1; + while ($c++ < $lc) { + if (!($c == $fc && $r == $fr)) { + // not the upper-left cell (should not be written in HTML) + $this->isSpannedCell[$sheetIndex][$r][$c] = array( + 'baseCell' => array($fr, $fc), + ); + } else { + // upper-left is the base cell that should hold the colspan/rowspan attribute + $this->isBaseCell[$sheetIndex][$r][$c] = array( + 'xlrowspan' => $lr - $fr + 1, // Excel rowspan + 'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change + 'xlcolspan' => $lc - $fc + 1, // Excel colspan + 'colspan' => $lc - $fc + 1, // HTML colspan, value may change + ); + } + } + } + } + + // Identify which rows should be omitted in HTML. These are the rows where all the cells + // participate in a merge and the where base cells are somewhere above. + $countColumns = PHPExcel_Cell::columnIndexFromString($sheet->getHighestColumn()); + foreach ($candidateSpannedRow as $rowIndex) { + if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) { + if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) { + $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex; + }; + } + } + + // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1 + if (isset($this->isSpannedRow[$sheetIndex])) { + foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) { + $adjustedBaseCells = array(); + $c = -1; + $e = $countColumns - 1; + while ($c++ < $e) { + $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell']; + + if (!in_array($baseCell, $adjustedBaseCells)) { + // subtract rowspan by 1 + --$this->isBaseCell[$sheetIndex][ $baseCell[0] ][ $baseCell[1] ]['rowspan']; + $adjustedBaseCells[] = $baseCell; + } + } + } + } + + // TODO: Same for columns + } + + // We have calculated the spans + $this->spansAreCalculated = true; + } + + private function setMargins(PHPExcel_Worksheet $pSheet) + { + $htmlPage = '@page { '; + $htmlBody = 'body { '; + + $left = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getLeft()) . 'in; '; + $htmlPage .= 'margin-left: ' . $left; + $htmlBody .= 'margin-left: ' . $left; + $right = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getRight()) . 'in; '; + $htmlPage .= 'margin-right: ' . $right; + $htmlBody .= 'margin-right: ' . $right; + $top = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getTop()) . 'in; '; + $htmlPage .= 'margin-top: ' . $top; + $htmlBody .= 'margin-top: ' . $top; + $bottom = PHPExcel_Shared_String::FormatNumber($pSheet->getPageMargins()->getBottom()) . 'in; '; + $htmlPage .= 'margin-bottom: ' . $bottom; + $htmlBody .= 'margin-bottom: ' . $bottom; + + $htmlPage .= "}\n"; + $htmlBody .= "}\n"; + + return "<style>\n" . $htmlPage . $htmlBody . "</style>\n"; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/IWriter.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/IWriter.php new file mode 100644 index 00000000..c7cfe740 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/IWriter.php @@ -0,0 +1,37 @@ +<?php + +/** + * PHPExcel_Writer_IWriter + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +interface PHPExcel_Writer_IWriter +{ + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null); +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument.php new file mode 100644 index 00000000..912ba9df --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument.php @@ -0,0 +1,190 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument extends PHPExcel_Writer_Abstract implements PHPExcel_Writer_IWriter +{ + /** + * Private writer parts + * + * @var PHPExcel_Writer_OpenDocument_WriterPart[] + */ + private $writerParts = array(); + + /** + * Private PHPExcel + * + * @var PHPExcel + */ + private $spreadSheet; + + /** + * Create a new PHPExcel_Writer_OpenDocument + * + * @param PHPExcel $pPHPExcel + */ + public function __construct(PHPExcel $pPHPExcel = null) + { + $this->setPHPExcel($pPHPExcel); + + $writerPartsArray = array( + 'content' => 'PHPExcel_Writer_OpenDocument_Content', + 'meta' => 'PHPExcel_Writer_OpenDocument_Meta', + 'meta_inf' => 'PHPExcel_Writer_OpenDocument_MetaInf', + 'mimetype' => 'PHPExcel_Writer_OpenDocument_Mimetype', + 'settings' => 'PHPExcel_Writer_OpenDocument_Settings', + 'styles' => 'PHPExcel_Writer_OpenDocument_Styles', + 'thumbnails' => 'PHPExcel_Writer_OpenDocument_Thumbnails' + ); + + foreach ($writerPartsArray as $writer => $class) { + $this->writerParts[$writer] = new $class($this); + } + } + + /** + * Get writer part + * + * @param string $pPartName Writer part name + * @return PHPExcel_Writer_Excel2007_WriterPart + */ + public function getWriterPart($pPartName = '') + { + if ($pPartName != '' && isset($this->writerParts[strtolower($pPartName)])) { + return $this->writerParts[strtolower($pPartName)]; + } else { + return null; + } + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + if (!$this->spreadSheet) { + throw new PHPExcel_Writer_Exception('PHPExcel object unassigned.'); + } + + // garbage collect + $this->spreadSheet->garbageCollect(); + + // If $pFilename is php://output or php://stdout, make it a temporary file... + $originalFilename = $pFilename; + if (strtolower($pFilename) == 'php://output' || strtolower($pFilename) == 'php://stdout') { + $pFilename = @tempnam(PHPExcel_Shared_File::sys_get_temp_dir(), 'phpxltmp'); + if ($pFilename == '') { + $pFilename = $originalFilename; + } + } + + $objZip = $this->createZip($pFilename); + + $objZip->addFromString('META-INF/manifest.xml', $this->getWriterPart('meta_inf')->writeManifest()); + $objZip->addFromString('Thumbnails/thumbnail.png', $this->getWriterPart('thumbnails')->writeThumbnail()); + $objZip->addFromString('content.xml', $this->getWriterPart('content')->write()); + $objZip->addFromString('meta.xml', $this->getWriterPart('meta')->write()); + $objZip->addFromString('mimetype', $this->getWriterPart('mimetype')->write()); + $objZip->addFromString('settings.xml', $this->getWriterPart('settings')->write()); + $objZip->addFromString('styles.xml', $this->getWriterPart('styles')->write()); + + // Close file + if ($objZip->close() === false) { + throw new PHPExcel_Writer_Exception("Could not close zip file $pFilename."); + } + + // If a temporary file was used, copy it to the correct file stream + if ($originalFilename != $pFilename) { + if (copy($pFilename, $originalFilename) === false) { + throw new PHPExcel_Writer_Exception("Could not copy temporary zip file $pFilename to $originalFilename."); + } + @unlink($pFilename); + } + } + + /** + * Create zip object + * + * @param string $pFilename + * @throws PHPExcel_Writer_Exception + * @return ZipArchive + */ + private function createZip($pFilename) + { + // Create new ZIP file and open it for writing + $zipClass = PHPExcel_Settings::getZipClass(); + $objZip = new $zipClass(); + + // Retrieve OVERWRITE and CREATE constants from the instantiated zip class + // This method of accessing constant values from a dynamic class should work with all appropriate versions of PHP + $ro = new ReflectionObject($objZip); + $zipOverWrite = $ro->getConstant('OVERWRITE'); + $zipCreate = $ro->getConstant('CREATE'); + + if (file_exists($pFilename)) { + unlink($pFilename); + } + // Try opening the ZIP file + if ($objZip->open($pFilename, $zipOverWrite) !== true) { + if ($objZip->open($pFilename, $zipCreate) !== true) { + throw new PHPExcel_Writer_Exception("Could not open $pFilename for writing."); + } + } + + return $objZip; + } + + /** + * Get PHPExcel object + * + * @return PHPExcel + * @throws PHPExcel_Writer_Exception + */ + public function getPHPExcel() + { + if ($this->spreadSheet !== null) { + return $this->spreadSheet; + } else { + throw new PHPExcel_Writer_Exception('No PHPExcel assigned.'); + } + } + + /** + * Set PHPExcel object + * + * @param PHPExcel $pPHPExcel PHPExcel object + * @throws PHPExcel_Writer_Exception + * @return PHPExcel_Writer_Excel2007 + */ + public function setPHPExcel(PHPExcel $pPHPExcel = null) + { + $this->spreadSheet = $pPHPExcel; + return $this; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Cell/Comment.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Cell/Comment.php new file mode 100644 index 00000000..f1e98a16 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Cell/Comment.php @@ -0,0 +1,63 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Writer_OpenDocument_Cell_Comment + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @author Alexander Pervakov <frost-nzcr4@jagmort.com> + */ +class PHPExcel_Writer_OpenDocument_Cell_Comment +{ + public static function write(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Cell $cell) + { + $comments = $cell->getWorksheet()->getComments(); + if (!isset($comments[$cell->getCoordinate()])) { + return; + } + $comment = $comments[$cell->getCoordinate()]; + + $objWriter->startElement('office:annotation'); + //$objWriter->writeAttribute('draw:style-name', 'gr1'); + //$objWriter->writeAttribute('draw:text-style-name', 'P1'); + $objWriter->writeAttribute('svg:width', $comment->getWidth()); + $objWriter->writeAttribute('svg:height', $comment->getHeight()); + $objWriter->writeAttribute('svg:x', $comment->getMarginLeft()); + $objWriter->writeAttribute('svg:y', $comment->getMarginTop()); + //$objWriter->writeAttribute('draw:caption-point-x', $comment->getMarginLeft()); + //$objWriter->writeAttribute('draw:caption-point-y', $comment->getMarginTop()); + $objWriter->writeElement('dc:creator', $comment->getAuthor()); + // TODO: Not realized in PHPExcel_Comment yet. + //$objWriter->writeElement('dc:date', $comment->getDate()); + $objWriter->writeElement('text:p', $comment->getText()->getPlainText()); + //$objWriter->writeAttribute('draw:text-style-name', 'P1'); + $objWriter->endElement(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Content.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Content.php new file mode 100644 index 00000000..a34b1670 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Content.php @@ -0,0 +1,272 @@ +<?php +/** + * PHPExcel + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ + + +/** + * PHPExcel_Writer_OpenDocument_Content + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @author Alexander Pervakov <frost-nzcr4@jagmort.com> + */ +class PHPExcel_Writer_OpenDocument_Content extends PHPExcel_Writer_OpenDocument_WriterPart +{ + const NUMBER_COLS_REPEATED_MAX = 1024; + const NUMBER_ROWS_REPEATED_MAX = 1048576; + + /** + * Write content.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function write(PHPExcel $pPHPExcel = null) + { + if (!$pPHPExcel) { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); /* @var $pPHPExcel PHPExcel */ + } + + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8'); + + // Content + $objWriter->startElement('office:document-content'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); + $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); + $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); + $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); + $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); + $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); + $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); + $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); + $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); + $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); + $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); + $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); + $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); + $objWriter->writeAttribute('xmlns:xforms', 'http://www.w3.org/2002/xforms'); + $objWriter->writeAttribute('xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); + $objWriter->writeAttribute('xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); + $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); + $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); + $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); + $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); + $objWriter->writeAttribute('xmlns:field', 'urn:openoffice:names:experimental:ooo-ms-interop:xmlns:field:1.0'); + $objWriter->writeAttribute('xmlns:formx', 'urn:openoffice:names:experimental:ooxml-odf-interop:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); + $objWriter->writeAttribute('office:version', '1.2'); + + $objWriter->writeElement('office:scripts'); + $objWriter->writeElement('office:font-face-decls'); + $objWriter->writeElement('office:automatic-styles'); + + $objWriter->startElement('office:body'); + $objWriter->startElement('office:spreadsheet'); + $objWriter->writeElement('table:calculation-settings'); + $this->writeSheets($objWriter); + $objWriter->writeElement('table:named-expressions'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + return $objWriter->getData(); + } + + /** + * Write sheets + * + * @param PHPExcel_Shared_XMLWriter $objWriter + */ + private function writeSheets(PHPExcel_Shared_XMLWriter $objWriter) + { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); /* @var $pPHPExcel PHPExcel */ + + $sheet_count = $pPHPExcel->getSheetCount(); + for ($i = 0; $i < $sheet_count; $i++) { + //$this->getWriterPart('Worksheet')->writeWorksheet()); + $objWriter->startElement('table:table'); + $objWriter->writeAttribute('table:name', $pPHPExcel->getSheet($i)->getTitle()); + $objWriter->writeElement('office:forms'); + $objWriter->startElement('table:table-column'); + $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->endElement(); + $this->writeRows($objWriter, $pPHPExcel->getSheet($i)); + $objWriter->endElement(); + } + } + + /** + * Write rows of the specified sheet + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @param PHPExcel_Worksheet $sheet + */ + private function writeRows(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Worksheet $sheet) + { + $number_rows_repeated = self::NUMBER_ROWS_REPEATED_MAX; + $span_row = 0; + $rows = $sheet->getRowIterator(); + while ($rows->valid()) { + $number_rows_repeated--; + $row = $rows->current(); + if ($row->getCellIterator()->valid()) { + if ($span_row) { + $objWriter->startElement('table:table-row'); + if ($span_row > 1) { + $objWriter->writeAttribute('table:number-rows-repeated', $span_row); + } + $objWriter->startElement('table:table-cell'); + $objWriter->writeAttribute('table:number-columns-repeated', self::NUMBER_COLS_REPEATED_MAX); + $objWriter->endElement(); + $objWriter->endElement(); + $span_row = 0; + } + $objWriter->startElement('table:table-row'); + $this->writeCells($objWriter, $row); + $objWriter->endElement(); + } else { + $span_row++; + } + $rows->next(); + } + } + + /** + * Write cells of the specified row + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @param PHPExcel_Worksheet_Row $row + * @throws PHPExcel_Writer_Exception + */ + private function writeCells(PHPExcel_Shared_XMLWriter $objWriter, PHPExcel_Worksheet_Row $row) + { + $number_cols_repeated = self::NUMBER_COLS_REPEATED_MAX; + $prev_column = -1; + $cells = $row->getCellIterator(); + while ($cells->valid()) { + $cell = $cells->current(); + $column = PHPExcel_Cell::columnIndexFromString($cell->getColumn()) - 1; + + $this->writeCellSpan($objWriter, $column, $prev_column); + $objWriter->startElement('table:table-cell'); + + switch ($cell->getDataType()) { + case PHPExcel_Cell_DataType::TYPE_BOOL: + $objWriter->writeAttribute('office:value-type', 'boolean'); + $objWriter->writeAttribute('office:value', $cell->getValue()); + $objWriter->writeElement('text:p', $cell->getValue()); + break; + + case PHPExcel_Cell_DataType::TYPE_ERROR: + throw new PHPExcel_Writer_Exception('Writing of error not implemented yet.'); + break; + + case PHPExcel_Cell_DataType::TYPE_FORMULA: + try { + $formula_value = $cell->getCalculatedValue(); + } catch (Exception $e) { + $formula_value = $cell->getValue(); + } + $objWriter->writeAttribute('table:formula', 'of:' . $cell->getValue()); + if (is_numeric($formula_value)) { + $objWriter->writeAttribute('office:value-type', 'float'); + } else { + $objWriter->writeAttribute('office:value-type', 'string'); + } + $objWriter->writeAttribute('office:value', $formula_value); + $objWriter->writeElement('text:p', $formula_value); + break; + + case PHPExcel_Cell_DataType::TYPE_INLINE: + throw new PHPExcel_Writer_Exception('Writing of inline not implemented yet.'); + break; + + case PHPExcel_Cell_DataType::TYPE_NUMERIC: + $objWriter->writeAttribute('office:value-type', 'float'); + $objWriter->writeAttribute('office:value', $cell->getValue()); + $objWriter->writeElement('text:p', $cell->getValue()); + break; + + case PHPExcel_Cell_DataType::TYPE_STRING: + $objWriter->writeAttribute('office:value-type', 'string'); + $objWriter->writeElement('text:p', $cell->getValue()); + break; + } + PHPExcel_Writer_OpenDocument_Cell_Comment::write($objWriter, $cell); + $objWriter->endElement(); + $prev_column = $column; + $cells->next(); + } + $number_cols_repeated = $number_cols_repeated - $prev_column - 1; + if ($number_cols_repeated > 0) { + if ($number_cols_repeated > 1) { + $objWriter->startElement('table:table-cell'); + $objWriter->writeAttribute('table:number-columns-repeated', $number_cols_repeated); + $objWriter->endElement(); + } else { + $objWriter->writeElement('table:table-cell'); + } + } + } + + /** + * Write span + * + * @param PHPExcel_Shared_XMLWriter $objWriter + * @param integer $curColumn + * @param integer $prevColumn + */ + private function writeCellSpan(PHPExcel_Shared_XMLWriter $objWriter, $curColumn, $prevColumn) + { + $diff = $curColumn - $prevColumn - 1; + if (1 === $diff) { + $objWriter->writeElement('table:table-cell'); + } elseif ($diff > 1) { + $objWriter->startElement('table:table-cell'); + $objWriter->writeAttribute('table:number-columns-repeated', $diff); + $objWriter->endElement(); + } + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Meta.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Meta.php new file mode 100644 index 00000000..1a5c5fd0 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Meta.php @@ -0,0 +1,95 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_Meta + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_Meta extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write meta.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function write(PHPExcel $pPHPExcel = null) + { + if (!$pPHPExcel) { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); + } + + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8'); + + // Meta + $objWriter->startElement('office:document-meta'); + + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $objWriter->writeAttribute('office:version', '1.2'); + + $objWriter->startElement('office:meta'); + + $objWriter->writeElement('meta:initial-creator', $pPHPExcel->getProperties()->getCreator()); + $objWriter->writeElement('dc:creator', $pPHPExcel->getProperties()->getCreator()); + $objWriter->writeElement('meta:creation-date', date(DATE_W3C, $pPHPExcel->getProperties()->getCreated())); + $objWriter->writeElement('dc:date', date(DATE_W3C, $pPHPExcel->getProperties()->getCreated())); + $objWriter->writeElement('dc:title', $pPHPExcel->getProperties()->getTitle()); + $objWriter->writeElement('dc:description', $pPHPExcel->getProperties()->getDescription()); + $objWriter->writeElement('dc:subject', $pPHPExcel->getProperties()->getSubject()); + $keywords = explode(' ', $pPHPExcel->getProperties()->getKeywords()); + foreach ($keywords as $keyword) { + $objWriter->writeElement('meta:keyword', $keyword); + } + + //<meta:document-statistic meta:table-count="XXX" meta:cell-count="XXX" meta:object-count="XXX"/> + $objWriter->startElement('meta:user-defined'); + $objWriter->writeAttribute('meta:name', 'Company'); + $objWriter->writeRaw($pPHPExcel->getProperties()->getCompany()); + $objWriter->endElement(); + + $objWriter->startElement('meta:user-defined'); + $objWriter->writeAttribute('meta:name', 'category'); + $objWriter->writeRaw($pPHPExcel->getProperties()->getCategory()); + $objWriter->endElement(); + + $objWriter->endElement(); + + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/MetaInf.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/MetaInf.php new file mode 100644 index 00000000..c43b7233 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/MetaInf.php @@ -0,0 +1,87 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_MetaInf + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_MetaInf extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write META-INF/manifest.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeManifest(PHPExcel $pPHPExcel = null) + { + if (!$pPHPExcel) { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); + } + + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8'); + + // Manifest + $objWriter->startElement('manifest:manifest'); + $objWriter->writeAttribute('xmlns:manifest', 'urn:oasis:names:tc:opendocument:xmlns:manifest:1.0'); + $objWriter->writeAttribute('manifest:version', '1.2'); + + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', '/'); + $objWriter->writeAttribute('manifest:version', '1.2'); + $objWriter->writeAttribute('manifest:media-type', 'application/vnd.oasis.opendocument.spreadsheet'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'meta.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'settings.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'content.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'Thumbnails/thumbnail.png'); + $objWriter->writeAttribute('manifest:media-type', 'image/png'); + $objWriter->endElement(); + $objWriter->startElement('manifest:file-entry'); + $objWriter->writeAttribute('manifest:full-path', 'styles.xml'); + $objWriter->writeAttribute('manifest:media-type', 'text/xml'); + $objWriter->endElement(); + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Mimetype.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Mimetype.php new file mode 100644 index 00000000..d51a8b97 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Mimetype.php @@ -0,0 +1,41 @@ +<?php + +/** + * PHPExcel + * + * PHPExcel_Writer_OpenDocument_Mimetype + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_Mimetype extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write mimetype to plain text format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function write(PHPExcel $pPHPExcel = null) + { + return 'application/vnd.oasis.opendocument.spreadsheet'; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Settings.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Settings.php new file mode 100644 index 00000000..84161b6d --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Settings.php @@ -0,0 +1,76 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_Settings + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_Settings extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write settings.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function write(PHPExcel $pPHPExcel = null) + { + if (!$pPHPExcel) { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); + } + + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8'); + + // Settings + $objWriter->startElement('office:document-settings'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:config', 'urn:oasis:names:tc:opendocument:xmlns:config:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('office:version', '1.2'); + + $objWriter->startElement('office:settings'); + $objWriter->startElement('config:config-item-set'); + $objWriter->writeAttribute('config:name', 'ooo:view-settings'); + $objWriter->startElement('config:config-item-map-indexed'); + $objWriter->writeAttribute('config:name', 'Views'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->startElement('config:config-item-set'); + $objWriter->writeAttribute('config:name', 'ooo:configuration-settings'); + $objWriter->endElement(); + $objWriter->endElement(); + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Styles.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Styles.php new file mode 100644 index 00000000..cc6e25b4 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Styles.php @@ -0,0 +1,92 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_Styles + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_Styles extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write styles.xml to XML format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function write(PHPExcel $pPHPExcel = null) + { + if (!$pPHPExcel) { + $pPHPExcel = $this->getParentWriter()->getPHPExcel(); + } + + $objWriter = null; + if ($this->getParentWriter()->getUseDiskCaching()) { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK, $this->getParentWriter()->getDiskCachingDirectory()); + } else { + $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY); + } + + // XML header + $objWriter->startDocument('1.0', 'UTF-8'); + + // Content + $objWriter->startElement('office:document-styles'); + $objWriter->writeAttribute('xmlns:office', 'urn:oasis:names:tc:opendocument:xmlns:office:1.0'); + $objWriter->writeAttribute('xmlns:style', 'urn:oasis:names:tc:opendocument:xmlns:style:1.0'); + $objWriter->writeAttribute('xmlns:text', 'urn:oasis:names:tc:opendocument:xmlns:text:1.0'); + $objWriter->writeAttribute('xmlns:table', 'urn:oasis:names:tc:opendocument:xmlns:table:1.0'); + $objWriter->writeAttribute('xmlns:draw', 'urn:oasis:names:tc:opendocument:xmlns:drawing:1.0'); + $objWriter->writeAttribute('xmlns:fo', 'urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0'); + $objWriter->writeAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); + $objWriter->writeAttribute('xmlns:dc', 'http://purl.org/dc/elements/1.1/'); + $objWriter->writeAttribute('xmlns:meta', 'urn:oasis:names:tc:opendocument:xmlns:meta:1.0'); + $objWriter->writeAttribute('xmlns:number', 'urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0'); + $objWriter->writeAttribute('xmlns:presentation', 'urn:oasis:names:tc:opendocument:xmlns:presentation:1.0'); + $objWriter->writeAttribute('xmlns:svg', 'urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0'); + $objWriter->writeAttribute('xmlns:chart', 'urn:oasis:names:tc:opendocument:xmlns:chart:1.0'); + $objWriter->writeAttribute('xmlns:dr3d', 'urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0'); + $objWriter->writeAttribute('xmlns:math', 'http://www.w3.org/1998/Math/MathML'); + $objWriter->writeAttribute('xmlns:form', 'urn:oasis:names:tc:opendocument:xmlns:form:1.0'); + $objWriter->writeAttribute('xmlns:script', 'urn:oasis:names:tc:opendocument:xmlns:script:1.0'); + $objWriter->writeAttribute('xmlns:ooo', 'http://openoffice.org/2004/office'); + $objWriter->writeAttribute('xmlns:ooow', 'http://openoffice.org/2004/writer'); + $objWriter->writeAttribute('xmlns:oooc', 'http://openoffice.org/2004/calc'); + $objWriter->writeAttribute('xmlns:dom', 'http://www.w3.org/2001/xml-events'); + $objWriter->writeAttribute('xmlns:rpt', 'http://openoffice.org/2005/report'); + $objWriter->writeAttribute('xmlns:of', 'urn:oasis:names:tc:opendocument:xmlns:of:1.2'); + $objWriter->writeAttribute('xmlns:xhtml', 'http://www.w3.org/1999/xhtml'); + $objWriter->writeAttribute('xmlns:grddl', 'http://www.w3.org/2003/g/data-view#'); + $objWriter->writeAttribute('xmlns:tableooo', 'http://openoffice.org/2009/table'); + $objWriter->writeAttribute('xmlns:css3t', 'http://www.w3.org/TR/css3-text/'); + $objWriter->writeAttribute('office:version', '1.2'); + + $objWriter->writeElement('office:font-face-decls'); + $objWriter->writeElement('office:styles'); + $objWriter->writeElement('office:automatic-styles'); + $objWriter->writeElement('office:master-styles'); + $objWriter->endElement(); + + return $objWriter->getData(); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Thumbnails.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Thumbnails.php new file mode 100644 index 00000000..54247ae2 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/Thumbnails.php @@ -0,0 +1,41 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_Thumbnails + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_OpenDocument_Thumbnails extends PHPExcel_Writer_OpenDocument_WriterPart +{ + /** + * Write Thumbnails/thumbnail.png to PNG format + * + * @param PHPExcel $pPHPExcel + * @return string XML Output + * @throws PHPExcel_Writer_Exception + */ + public function writeThumbnail(PHPExcel $pPHPExcel = null) + { + return ''; + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/WriterPart.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/WriterPart.php new file mode 100644 index 00000000..562787a3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/OpenDocument/WriterPart.php @@ -0,0 +1,30 @@ +<?php + +/** + * PHPExcel_Writer_OpenDocument_WriterPart + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_OpenDocument + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Writer_OpenDocument_WriterPart extends PHPExcel_Writer_Excel2007_WriterPart +{ +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF.php new file mode 100644 index 00000000..579edfa5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF.php @@ -0,0 +1,89 @@ +<?php + +/** + * PHPExcel_Writer_PDF + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_PDF implements PHPExcel_Writer_IWriter +{ + + /** + * The wrapper for the requested PDF rendering engine + * + * @var PHPExcel_Writer_PDF_Core + */ + private $renderer = null; + + /** + * Instantiate a new renderer of the configured type within this container class + * + * @param PHPExcel $phpExcel PHPExcel object + * @throws PHPExcel_Writer_Exception when PDF library is not configured + */ + public function __construct(PHPExcel $phpExcel) + { + $pdfLibraryName = PHPExcel_Settings::getPdfRendererName(); + if (is_null($pdfLibraryName)) { + throw new PHPExcel_Writer_Exception("PDF Rendering library has not been defined."); + } + + $pdfLibraryPath = PHPExcel_Settings::getPdfRendererPath(); + if (is_null($pdfLibraryName)) { + throw new PHPExcel_Writer_Exception("PDF Rendering library path has not been defined."); + } + $includePath = str_replace('\\', '/', get_include_path()); + $rendererPath = str_replace('\\', '/', $pdfLibraryPath); + if (strpos($rendererPath, $includePath) === false) { + set_include_path(get_include_path() . PATH_SEPARATOR . $pdfLibraryPath); + } + + $rendererName = 'PHPExcel_Writer_PDF_' . $pdfLibraryName; + $this->renderer = new $rendererName($phpExcel); + } + + + /** + * Magic method to handle direct calls to the configured PDF renderer wrapper class. + * + * @param string $name Renderer library method name + * @param mixed[] $arguments Array of arguments to pass to the renderer method + * @return mixed Returned data from the PDF renderer wrapper method + */ + public function __call($name, $arguments) + { + if ($this->renderer === null) { + throw new PHPExcel_Writer_Exception("PDF Rendering library has not been defined."); + } + + return call_user_func_array(array($this->renderer, $name), $arguments); + } + + /** + * {@inheritdoc} + */ + public function save($pFilename = null) + { + $this->renderer->save($pFilename); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/Core.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/Core.php new file mode 100644 index 00000000..4fed84a7 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/Core.php @@ -0,0 +1,355 @@ +<?php + +/** + * PHPExcel_Writer_PDF_Core + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +abstract class PHPExcel_Writer_PDF_Core extends PHPExcel_Writer_HTML +{ + /** + * Temporary storage directory + * + * @var string + */ + protected $tempDir = ''; + + /** + * Font + * + * @var string + */ + protected $font = 'freesans'; + + /** + * Orientation (Over-ride) + * + * @var string + */ + protected $orientation; + + /** + * Paper size (Over-ride) + * + * @var int + */ + protected $paperSize; + + + /** + * Temporary storage for Save Array Return type + * + * @var string + */ + private $saveArrayReturnType; + + /** + * Paper Sizes xRef List + * + * @var array + */ + protected static $paperSizes = array( + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_SMALL + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID + => array(792.00, 1224.00), // (11 in. by 17 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEDGER + => array(1224.00, 792.00), // (17 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL + => 'LEGAL', // (8.5 in. by 14 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STATEMENT + => array(396.00, 612.00), // (5.5 in. by 8.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_EXECUTIVE + => 'EXECUTIVE', // (7.25 in. by 10.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3 + => 'A3', // (297 mm by 420 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4 + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_SMALL + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5 + => 'A5', // (148 mm by 210 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4 + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5 + => 'B5', // (176 mm by 250 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_FOLIO + => 'FOLIO', // (8.5 in. by 13 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_QUARTO + => array(609.45, 779.53), // (215 mm by 275 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_1 + => array(720.00, 1008.00), // (10 in. by 14 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_2 + => array(792.00, 1224.00), // (11 in. by 17 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NOTE + => 'LETTER', // (8.5 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO9_ENVELOPE + => array(279.00, 639.00), // (3.875 in. by 8.875 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO10_ENVELOPE + => array(297.00, 684.00), // (4.125 in. by 9.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO11_ENVELOPE + => array(324.00, 747.00), // (4.5 in. by 10.375 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO12_ENVELOPE + => array(342.00, 792.00), // (4.75 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_NO14_ENVELOPE + => array(360.00, 828.00), // (5 in. by 11.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C + => array(1224.00, 1584.00), // (17 in. by 22 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_D + => array(1584.00, 2448.00), // (22 in. by 34 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_E + => array(2448.00, 3168.00), // (34 in. by 44 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_DL_ENVELOPE + => array(311.81, 623.62), // (110 mm by 220 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C5_ENVELOPE + => 'C5', // (162 mm by 229 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C3_ENVELOPE + => 'C3', // (324 mm by 458 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C4_ENVELOPE + => 'C4', // (229 mm by 324 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C6_ENVELOPE + => 'C6', // (114 mm by 162 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_C65_ENVELOPE + => array(323.15, 649.13), // (114 mm by 229 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B4_ENVELOPE + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B5_ENVELOPE + => 'B5', // (176 mm by 250 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_B6_ENVELOPE + => array(498.90, 354.33), // (176 mm by 125 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ITALY_ENVELOPE + => array(311.81, 651.97), // (110 mm by 230 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_MONARCH_ENVELOPE + => array(279.00, 540.00), // (3.875 in. by 7.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_6_3_4_ENVELOPE + => array(261.00, 468.00), // (3.625 in. by 6.5 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_US_STANDARD_FANFOLD + => array(1071.00, 792.00), // (14.875 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_STANDARD_FANFOLD + => array(612.00, 864.00), // (8.5 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_GERMAN_LEGAL_FANFOLD + => 'FOLIO', // (8.5 in. by 13 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B4 + => 'B4', // (250 mm by 353 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_JAPANESE_DOUBLE_POSTCARD + => array(566.93, 419.53), // (200 mm by 148 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_1 + => array(648.00, 792.00), // (9 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_2 + => array(720.00, 792.00), // (10 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_STANDARD_PAPER_3 + => array(1080.00, 792.00), // (15 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_INVITE_ENVELOPE + => array(623.62, 623.62), // (220 mm by 220 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_PAPER + => array(667.80, 864.00), // (9.275 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL_EXTRA_PAPER + => array(667.80, 1080.00), // (9.275 in. by 15 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_TABLOID_EXTRA_PAPER + => array(841.68, 1296.00), // (11.69 in. by 18 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_EXTRA_PAPER + => array(668.98, 912.76), // (236 mm by 322 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_TRANSVERSE_PAPER + => array(595.80, 792.00), // (8.275 in. by 11 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_TRANSVERSE_PAPER + => 'A4', // (210 mm by 297 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER + => array(667.80, 864.00), // (9.275 in. by 12 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERA_SUPERA_A4_PAPER + => array(643.46, 1009.13), // (227 mm by 356 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_SUPERB_SUPERB_A3_PAPER + => array(864.57, 1380.47), // (305 mm by 487 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER_PLUS_PAPER + => array(612.00, 913.68), // (8.5 in. by 12.69 in.) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4_PLUS_PAPER + => array(595.28, 935.43), // (210 mm by 330 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_TRANSVERSE_PAPER + => 'A5', // (148 mm by 210 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_JIS_B5_TRANSVERSE_PAPER + => array(515.91, 728.50), // (182 mm by 257 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_PAPER + => array(912.76, 1261.42), // (322 mm by 445 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A5_EXTRA_PAPER + => array(493.23, 666.14), // (174 mm by 235 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_ISO_B5_EXTRA_PAPER + => array(569.76, 782.36), // (201 mm by 276 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A2_PAPER + => 'A2', // (420 mm by 594 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_TRANSVERSE_PAPER + => 'A3', // (297 mm by 420 mm) + PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER + => array(912.76, 1261.42) // (322 mm by 445 mm) + ); + + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + $this->setUseInlineCss(true); + $this->tempDir = PHPExcel_Shared_File::sys_get_temp_dir(); + } + + /** + * Get Font + * + * @return string + */ + public function getFont() + { + return $this->font; + } + + /** + * Set font. Examples: + * 'arialunicid0-chinese-simplified' + * 'arialunicid0-chinese-traditional' + * 'arialunicid0-korean' + * 'arialunicid0-japanese' + * + * @param string $fontName + */ + public function setFont($fontName) + { + $this->font = $fontName; + return $this; + } + + /** + * Get Paper Size + * + * @return int + */ + public function getPaperSize() + { + return $this->paperSize; + } + + /** + * Set Paper Size + * + * @param string $pValue Paper size + * @return PHPExcel_Writer_PDF + */ + public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) + { + $this->paperSize = $pValue; + return $this; + } + + /** + * Get Orientation + * + * @return string + */ + public function getOrientation() + { + return $this->orientation; + } + + /** + * Set Orientation + * + * @param string $pValue Page orientation + * @return PHPExcel_Writer_PDF + */ + public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + { + $this->orientation = $pValue; + return $this; + } + + /** + * Get temporary storage directory + * + * @return string + */ + public function getTempDir() + { + return $this->tempDir; + } + + /** + * Set temporary storage directory + * + * @param string $pValue Temporary storage directory + * @throws PHPExcel_Writer_Exception when directory does not exist + * @return PHPExcel_Writer_PDF + */ + public function setTempDir($pValue = '') + { + if (is_dir($pValue)) { + $this->tempDir = $pValue; + } else { + throw new PHPExcel_Writer_Exception("Directory does not exist: $pValue"); + } + return $this; + } + + /** + * Save PHPExcel to PDF file, pre-save + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + protected function prepareForSave($pFilename = null) + { + // garbage collect + $this->phpExcel->garbageCollect(); + + $this->saveArrayReturnType = PHPExcel_Calculation::getArrayReturnType(); + PHPExcel_Calculation::setArrayReturnType(PHPExcel_Calculation::RETURN_ARRAY_AS_VALUE); + + // Open file + $fileHandle = fopen($pFilename, 'w'); + if ($fileHandle === false) { + throw new PHPExcel_Writer_Exception("Could not open file $pFilename for writing."); + } + + // Set PDF + $this->isPdf = true; + // Build CSS + $this->buildCSS(true); + + return $fileHandle; + } + + /** + * Save PHPExcel to PDF file, post-save + * + * @param resource $fileHandle + * @throws PHPExcel_Writer_Exception + */ + protected function restoreStateAfterSave($fileHandle) + { + // Close file + fclose($fileHandle); + + PHPExcel_Calculation::setArrayReturnType($this->saveArrayReturnType); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/DomPDF.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/DomPDF.php new file mode 100644 index 00000000..83761acb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/DomPDF.php @@ -0,0 +1,108 @@ +<?php + +/** Require DomPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/dompdf_config.inc.php'; +if (file_exists($pdfRendererClassFile)) { + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_DomPDF + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_PDF_DomPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + + $orientation = ($orientation == 'L') ? 'landscape' : 'portrait'; + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT + : $this->getOrientation(); + } + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$paperSizes[$printPaperSize])) { + $paperSize = self::$paperSizes[$printPaperSize]; + } + + + // Create PDF + $pdf = new DOMPDF(); + $pdf->set_paper(strtolower($paperSize), $orientation); + + $pdf->load_html( + $this->generateHTMLHeader(false) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + $pdf->render(); + + // Write to file + fwrite($fileHandle, $pdf->output()); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/mPDF.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/mPDF.php new file mode 100644 index 00000000..e4e6057d --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/mPDF.php @@ -0,0 +1,118 @@ +<?php + +/** Require mPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/mpdf.php'; +if (file_exists($pdfRendererClassFile)) { + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_mPDF + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_PDF_mPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + $this->setOrientation($orientation); + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) + ? PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT + : $this->getOrientation(); + } + $orientation = strtoupper($orientation); + + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$paperSizes[$printPaperSize])) { + $paperSize = self::$paperSizes[$printPaperSize]; + } + + + // Create PDF + $pdf = new mpdf(); + $ortmp = $orientation; + $pdf->_setPageSize(strtoupper($paperSize), $ortmp); + $pdf->DefOrientation = $orientation; + $pdf->AddPage($orientation); + + // Document info + $pdf->SetTitle($this->phpExcel->getProperties()->getTitle()); + $pdf->SetAuthor($this->phpExcel->getProperties()->getCreator()); + $pdf->SetSubject($this->phpExcel->getProperties()->getSubject()); + $pdf->SetKeywords($this->phpExcel->getProperties()->getKeywords()); + $pdf->SetCreator($this->phpExcel->getProperties()->getCreator()); + + $pdf->WriteHTML( + $this->generateHTMLHeader(false) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + + // Write to file + fwrite($fileHandle, $pdf->Output('', 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/tcPDF.php b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/tcPDF.php new file mode 100644 index 00000000..dea33a35 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/Writer/PDF/tcPDF.php @@ -0,0 +1,123 @@ +<?php + +/** Require tcPDF library */ +$pdfRendererClassFile = PHPExcel_Settings::getPdfRendererPath() . '/tcpdf.php'; +if (file_exists($pdfRendererClassFile)) { + $k_path_url = PHPExcel_Settings::getPdfRendererPath(); + require_once $pdfRendererClassFile; +} else { + throw new PHPExcel_Writer_Exception('Unable to load PDF Rendering library'); +} + +/** + * PHPExcel_Writer_PDF_tcPDF + * + * Copyright (c) 2006 - 2015 PHPExcel + * + * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * @category PHPExcel + * @package PHPExcel_Writer_PDF + * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) + * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL + * @version ##VERSION##, ##DATE## + */ +class PHPExcel_Writer_PDF_tcPDF extends PHPExcel_Writer_PDF_Core implements PHPExcel_Writer_IWriter +{ + /** + * Create a new PHPExcel_Writer_PDF + * + * @param PHPExcel $phpExcel PHPExcel object + */ + public function __construct(PHPExcel $phpExcel) + { + parent::__construct($phpExcel); + } + + /** + * Save PHPExcel to file + * + * @param string $pFilename Name of the file to save as + * @throws PHPExcel_Writer_Exception + */ + public function save($pFilename = null) + { + $fileHandle = parent::prepareForSave($pFilename); + + // Default PDF paper size + $paperSize = 'LETTER'; // Letter (8.5 in. by 11 in.) + + // Check for paper size and page orientation + if (is_null($this->getSheetIndex())) { + $orientation = ($this->phpExcel->getSheet(0)->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet(0)->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet(0)->getPageMargins(); + } else { + $orientation = ($this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation() + == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P'; + $printPaperSize = $this->phpExcel->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize(); + $printMargins = $this->phpExcel->getSheet($this->getSheetIndex())->getPageMargins(); + } + + // Override Page Orientation + if (!is_null($this->getOrientation())) { + $orientation = ($this->getOrientation() == PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE) + ? 'L' + : 'P'; + } + // Override Paper Size + if (!is_null($this->getPaperSize())) { + $printPaperSize = $this->getPaperSize(); + } + + if (isset(self::$paperSizes[$printPaperSize])) { + $paperSize = self::$paperSizes[$printPaperSize]; + } + + + // Create PDF + $pdf = new TCPDF($orientation, 'pt', $paperSize); + $pdf->setFontSubsetting(false); + // Set margins, converting inches to points (using 72 dpi) + $pdf->SetMargins($printMargins->getLeft() * 72, $printMargins->getTop() * 72, $printMargins->getRight() * 72); + $pdf->SetAutoPageBreak(true, $printMargins->getBottom() * 72); + + $pdf->setPrintHeader(false); + $pdf->setPrintFooter(false); + + $pdf->AddPage(); + + // Set the appropriate font + $pdf->SetFont($this->getFont()); + $pdf->writeHTML( + $this->generateHTMLHeader(false) . + $this->generateSheetData() . + $this->generateHTMLFooter() + ); + + // Document info + $pdf->SetTitle($this->phpExcel->getProperties()->getTitle()); + $pdf->SetAuthor($this->phpExcel->getProperties()->getCreator()); + $pdf->SetSubject($this->phpExcel->getProperties()->getSubject()); + $pdf->SetKeywords($this->phpExcel->getProperties()->getKeywords()); + $pdf->SetCreator($this->phpExcel->getProperties()->getCreator()); + + // Write to file + fwrite($fileHandle, $pdf->output($pFilename, 'S')); + + parent::restoreStateAfterSave($fileHandle); + } +} diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/bg/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/bg/config new file mode 100644 index 00000000..4cecddb3 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/bg/config @@ -0,0 +1,49 @@ +## +## PHPExcel +## + +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = лв + + +## +## Excel Error Codes (For future use) + +## +NULL = #ПРАЗНО! +DIV0 = #ДЕЛ/0! +VALUE = #СТОЙНОСТ! +REF = #РЕФ! +NAME = #ИМЕ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/config new file mode 100644 index 00000000..42cdf326 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = Kč + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #HODNOTA! +REF = #REF! +NAME = #NÁZEV? +NUM = #NUM! +NA = #N/A diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/functions new file mode 100644 index 00000000..c0a3cbbf --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/cs/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funkce doplňků a automatizace +## +GETPIVOTDATA = ZÍSKATKONTDATA ## Vrátí data uložená v kontingenční tabulce. Pomocí funkce ZÍSKATKONTDATA můžete načíst souhrnná data z kontingenční tabulky, pokud jsou tato data v kontingenční sestavě zobrazena. + + +## +## Cube functions Funkce pro práci s krychlemi +## +CUBEKPIMEMBER = CUBEKPIMEMBER ## Vrátí název, vlastnost a velikost klíčového ukazatele výkonu (KUV) a zobrazí v buňce název a vlastnost. Klíčový ukazatel výkonu je kvantifikovatelná veličina, například hrubý měsíční zisk nebo čtvrtletní obrat na zaměstnance, která se používá pro sledování výkonnosti organizace. +CUBEMEMBER = CUBEMEMBER ## Vrátí člen nebo n-tici v hierarchii krychle. Slouží k ověření, zda v krychli existuje člen nebo n-tice. +CUBEMEMBERPROPERTY = CUBEMEMBERPROPERTY ## Vrátí hodnotu vlastnosti člena v krychli. Slouží k ověření, zda v krychli existuje člen s daným názvem, a k vrácení konkrétní vlastnosti tohoto člena. +CUBERANKEDMEMBER = CUBERANKEDMEMBER ## Vrátí n-tý nebo pořadový člen sady. Použijte ji pro vrácení jednoho nebo více prvků sady, například obchodníka s nejvyšším obratem nebo deseti nejlepších studentů. +CUBESET = CUBESET ## Definuje vypočtenou sadu členů nebo n-tic odesláním výrazu sady do krychle na serveru, který vytvoří sadu a potom ji vrátí do aplikace Microsoft Office Excel. +CUBESETCOUNT = CUBESETCOUNT ## Vrátí počet položek v množině +CUBEVALUE = CUBEVALUE ## Vrátí úhrnnou hodnotu z krychle. + + +## +## Database functions Funkce databáze +## +DAVERAGE = DPRŮMĚR ## Vrátí průměr vybraných položek databáze. +DCOUNT = DPOČET ## Spočítá buňky databáze obsahující čísla. +DCOUNTA = DPOČET2 ## Spočítá buňky databáze, které nejsou prázdné. +DGET = DZÍSKAT ## Extrahuje z databáze jeden záznam splňující zadaná kritéria. +DMAX = DMAX ## Vrátí maximální hodnotu z vybraných položek databáze. +DMIN = DMIN ## Vrátí minimální hodnotu z vybraných položek databáze. +DPRODUCT = DSOUČIN ## Vynásobí hodnoty určitého pole záznamů v databázi, které splňují daná kritéria. +DSTDEV = DSMODCH.VÝBĚR ## Odhadne směrodatnou odchylku výběru vybraných položek databáze. +DSTDEVP = DSMODCH ## Vypočte směrodatnou odchylku základního souboru vybraných položek databáze. +DSUM = DSUMA ## Sečte čísla ve sloupcovém poli záznamů databáze, která splňují daná kritéria. +DVAR = DVAR.VÝBĚR ## Odhadne rozptyl výběru vybraných položek databáze. +DVARP = DVAR ## Vypočte rozptyl základního souboru vybraných položek databáze. + + +## +## Date and time functions Funkce data a času +## +DATE = DATUM ## Vrátí pořadové číslo určitého data. +DATEVALUE = DATUMHODN ## Převede datum ve formě textu na pořadové číslo. +DAY = DEN ## Převede pořadové číslo na den v měsíci. +DAYS360 = ROK360 ## Vrátí počet dní mezi dvěma daty na základě roku s 360 dny. +EDATE = EDATE ## Vrátí pořadové číslo data, které označuje určený počet měsíců před nebo po počátečním datu. +EOMONTH = EOMONTH ## Vrátí pořadové číslo posledního dne měsíce před nebo po zadaném počtu měsíců. +HOUR = HODINA ## Převede pořadové číslo na hodinu. +MINUTE = MINUTA ## Převede pořadové číslo na minutu. +MONTH = MĚSÍC ## Převede pořadové číslo na měsíc. +NETWORKDAYS = NETWORKDAYS ## Vrátí počet celých pracovních dní mezi dvěma daty. +NOW = NYNÍ ## Vrátí pořadové číslo aktuálního data a času. +SECOND = SEKUNDA ## Převede pořadové číslo na sekundu. +TIME = ČAS ## Vrátí pořadové číslo určitého času. +TIMEVALUE = ČASHODN ## Převede čas ve formě textu na pořadové číslo. +TODAY = DNES ## Vrátí pořadové číslo dnešního data. +WEEKDAY = DENTÝDNE ## Převede pořadové číslo na den v týdnu. +WEEKNUM = WEEKNUM ## Převede pořadové číslo na číslo představující číselnou pozici týdne v roce. +WORKDAY = WORKDAY ## Vrátí pořadové číslo data před nebo po zadaném počtu pracovních dní. +YEAR = ROK ## Převede pořadové číslo na rok. +YEARFRAC = YEARFRAC ## Vrátí část roku vyjádřenou zlomkem a představující počet celých dní mezi počátečním a koncovým datem. + + +## +## Engineering functions Inženýrské funkce (Technické funkce) +## +BESSELI = BESSELI ## Vrátí modifikovanou Besselovu funkci In(x). +BESSELJ = BESSELJ ## Vrátí modifikovanou Besselovu funkci Jn(x). +BESSELK = BESSELK ## Vrátí modifikovanou Besselovu funkci Kn(x). +BESSELY = BESSELY ## Vrátí Besselovu funkci Yn(x). +BIN2DEC = BIN2DEC ## Převede binární číslo na desítkové. +BIN2HEX = BIN2HEX ## Převede binární číslo na šestnáctkové. +BIN2OCT = BIN2OCT ## Převede binární číslo na osmičkové. +COMPLEX = COMPLEX ## Převede reálnou a imaginární část na komplexní číslo. +CONVERT = CONVERT ## Převede číslo do jiného jednotkového měrného systému. +DEC2BIN = DEC2BIN ## Převede desítkového čísla na dvojkové +DEC2HEX = DEC2HEX ## Převede desítkové číslo na šestnáctkové. +DEC2OCT = DEC2OCT ## Převede desítkové číslo na osmičkové. +DELTA = DELTA ## Testuje rovnost dvou hodnot. +ERF = ERF ## Vrátí chybovou funkci. +ERFC = ERFC ## Vrátí doplňkovou chybovou funkci. +GESTEP = GESTEP ## Testuje, zda je číslo větší než mezní hodnota. +HEX2BIN = HEX2BIN ## Převede šestnáctkové číslo na binární. +HEX2DEC = HEX2DEC ## Převede šestnáctkové číslo na desítkové. +HEX2OCT = HEX2OCT ## Převede šestnáctkové číslo na osmičkové. +IMABS = IMABS ## Vrátí absolutní hodnotu (modul) komplexního čísla. +IMAGINARY = IMAGINARY ## Vrátí imaginární část komplexního čísla. +IMARGUMENT = IMARGUMENT ## Vrátí argument théta, úhel vyjádřený v radiánech. +IMCONJUGATE = IMCONJUGATE ## Vrátí komplexně sdružené číslo ke komplexnímu číslu. +IMCOS = IMCOS ## Vrátí kosinus komplexního čísla. +IMDIV = IMDIV ## Vrátí podíl dvou komplexních čísel. +IMEXP = IMEXP ## Vrátí exponenciální tvar komplexního čísla. +IMLN = IMLN ## Vrátí přirozený logaritmus komplexního čísla. +IMLOG10 = IMLOG10 ## Vrátí dekadický logaritmus komplexního čísla. +IMLOG2 = IMLOG2 ## Vrátí logaritmus komplexního čísla při základu 2. +IMPOWER = IMPOWER ## Vrátí komplexní číslo umocněné na celé číslo. +IMPRODUCT = IMPRODUCT ## Vrátí součin komplexních čísel. +IMREAL = IMREAL ## Vrátí reálnou část komplexního čísla. +IMSIN = IMSIN ## Vrátí sinus komplexního čísla. +IMSQRT = IMSQRT ## Vrátí druhou odmocninu komplexního čísla. +IMSUB = IMSUB ## Vrátí rozdíl mezi dvěma komplexními čísly. +IMSUM = IMSUM ## Vrátí součet dvou komplexních čísel. +OCT2BIN = OCT2BIN ## Převede osmičkové číslo na binární. +OCT2DEC = OCT2DEC ## Převede osmičkové číslo na desítkové. +OCT2HEX = OCT2HEX ## Převede osmičkové číslo na šestnáctkové. + + +## +## Financial functions Finanční funkce +## +ACCRINT = ACCRINT ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen v pravidelných termínech. +ACCRINTM = ACCRINTM ## Vrátí nahromaděný úrok z cenného papíru, ze kterého je úrok placen k datu splatnosti. +AMORDEGRC = AMORDEGRC ## Vrátí lineární amortizaci v každém účetním období pomocí koeficientu amortizace. +AMORLINC = AMORLINC ## Vrátí lineární amortizaci v každém účetním období. +COUPDAYBS = COUPDAYBS ## Vrátí počet dnů od začátku období placení kupónů do data splatnosti. +COUPDAYS = COUPDAYS ## Vrátí počet dnů v období placení kupónů, které obsahuje den zúčtování. +COUPDAYSNC = COUPDAYSNC ## Vrátí počet dnů od data zúčtování do následujícího data placení kupónu. +COUPNCD = COUPNCD ## Vrátí následující datum placení kupónu po datu zúčtování. +COUPNUM = COUPNUM ## Vrátí počet kupónů splatných mezi datem zúčtování a datem splatnosti. +COUPPCD = COUPPCD ## Vrátí předchozí datum placení kupónu před datem zúčtování. +CUMIPMT = CUMIPMT ## Vrátí kumulativní úrok splacený mezi dvěma obdobími. +CUMPRINC = CUMPRINC ## Vrátí kumulativní jistinu splacenou mezi dvěma obdobími půjčky. +DB = ODPIS.ZRYCH ## Vrátí odpis aktiva za určité období pomocí degresivní metody odpisu s pevným zůstatkem. +DDB = ODPIS.ZRYCH2 ## Vrátí odpis aktiva za určité období pomocí dvojité degresivní metody odpisu nebo jiné metody, kterou zadáte. +DISC = DISC ## Vrátí diskontní sazbu cenného papíru. +DOLLARDE = DOLLARDE ## Převede částku v korunách vyjádřenou zlomkem na částku v korunách vyjádřenou desetinným číslem. +DOLLARFR = DOLLARFR ## Převede částku v korunách vyjádřenou desetinným číslem na částku v korunách vyjádřenou zlomkem. +DURATION = DURATION ## Vrátí roční dobu cenného papíru s pravidelnými úrokovými sazbami. +EFFECT = EFFECT ## Vrátí efektivní roční úrokovou sazbu. +FV = BUDHODNOTA ## Vrátí budoucí hodnotu investice. +FVSCHEDULE = FVSCHEDULE ## Vrátí budoucí hodnotu počáteční jistiny po použití série sazeb složitého úroku. +INTRATE = INTRATE ## Vrátí úrokovou sazbu plně investovaného cenného papíru. +IPMT = PLATBA.ÚROK ## Vrátí výšku úroku investice za dané období. +IRR = MÍRA.VÝNOSNOSTI ## Vrátí vnitřní výnosové procento série peněžních toků. +ISPMT = ISPMT ## Vypočte výši úroku z investice zaplaceného během určitého období. +MDURATION = MDURATION ## Vrátí Macauleyho modifikovanou dobu cenného papíru o nominální hodnotě 100 Kč. +MIRR = MOD.MÍRA.VÝNOSNOSTI ## Vrátí vnitřní sazbu výnosu, přičemž kladné a záporné hodnoty peněžních prostředků jsou financovány podle různých sazeb. +NOMINAL = NOMINAL ## Vrátí nominální roční úrokovou sazbu. +NPER = POČET.OBDOBÍ ## Vrátí počet období pro investici. +NPV = ČISTÁ.SOUČHODNOTA ## Vrátí čistou současnou hodnotu investice vypočítanou na základě série pravidelných peněžních toků a diskontní sazby. +ODDFPRICE = ODDFPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným prvním obdobím. +ODDFYIELD = ODDFYIELD ## Vrátí výnos cenného papíru s odlišným prvním obdobím. +ODDLPRICE = ODDLPRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč s odlišným posledním obdobím. +ODDLYIELD = ODDLYIELD ## Vrátí výnos cenného papíru s odlišným posledním obdobím. +PMT = PLATBA ## Vrátí hodnotu pravidelné splátky anuity. +PPMT = PLATBA.ZÁKLAD ## Vrátí hodnotu splátky jistiny pro zadanou investici za dané období. +PRICE = PRICE ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen v pravidelných termínech. +PRICEDISC = PRICEDISC ## Vrátí cenu diskontního cenného papíru o nominální hodnotě 100 Kč. +PRICEMAT = PRICEMAT ## Vrátí cenu cenného papíru o nominální hodnotě 100 Kč, ze kterého je úrok placen k datu splatnosti. +PV = SOUČHODNOTA ## Vrátí současnou hodnotu investice. +RATE = ÚROKOVÁ.MÍRA ## Vrátí úrokovou sazbu vztaženou na období anuity. +RECEIVED = RECEIVED ## Vrátí částku obdrženou k datu splatnosti plně investovaného cenného papíru. +SLN = ODPIS.LIN ## Vrátí přímé odpisy aktiva pro jedno období. +SYD = ODPIS.NELIN ## Vrátí směrné číslo ročních odpisů aktiva pro zadané období. +TBILLEQ = TBILLEQ ## Vrátí výnos směnky státní pokladny ekvivalentní výnosu obligace. +TBILLPRICE = TBILLPRICE ## Vrátí cenu směnky státní pokladny o nominální hodnotě 100 Kč. +TBILLYIELD = TBILLYIELD ## Vrátí výnos směnky státní pokladny. +VDB = ODPIS.ZA.INT ## Vrátí odpis aktiva pro určité období nebo část období pomocí degresivní metody odpisu. +XIRR = XIRR ## Vrátí vnitřní výnosnost pro harmonogram peněžních toků, který nemusí být nutně periodický. +XNPV = XNPV ## Vrátí čistou současnou hodnotu pro harmonogram peněžních toků, který nemusí být nutně periodický. +YIELD = YIELD ## Vrátí výnos cenného papíru, ze kterého je úrok placen v pravidelných termínech. +YIELDDISC = YIELDDISC ## Vrátí roční výnos diskontního cenného papíru, například směnky státní pokladny. +YIELDMAT = YIELDMAT ## Vrátí roční výnos cenného papíru, ze kterého je úrok placen k datu splatnosti. + + +## +## Information functions Informační funkce +## +CELL = POLÍČKO ## Vrátí informace o formátování, umístění nebo obsahu buňky. +ERROR.TYPE = CHYBA.TYP ## Vrátí číslo odpovídající typu chyby. +INFO = O.PROSTŘEDÍ ## Vrátí informace o aktuálním pracovním prostředí. +ISBLANK = JE.PRÁZDNÉ ## Vrátí hodnotu PRAVDA, pokud se argument hodnota odkazuje na prázdnou buňku. +ISERR = JE.CHYBA ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota (kromě #N/A). +ISERROR = JE.CHYBHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota libovolná chybová hodnota. +ISEVEN = ISEVEN ## Vrátí hodnotu PRAVDA, pokud je číslo sudé. +ISLOGICAL = JE.LOGHODN ## Vrátí hodnotu PRAVDA, pokud je argument hodnota logická hodnota. +ISNA = JE.NEDEF ## Vrátí hodnotu PRAVDA, pokud je argument hodnota chybová hodnota #N/A. +ISNONTEXT = JE.NETEXT ## Vrátí hodnotu PRAVDA, pokud argument hodnota není text. +ISNUMBER = JE.ČÍSLO ## Vrátí hodnotu PRAVDA, pokud je argument hodnota číslo. +ISODD = ISODD ## Vrátí hodnotu PRAVDA, pokud je číslo liché. +ISREF = JE.ODKAZ ## Vrátí hodnotu PRAVDA, pokud je argument hodnota odkaz. +ISTEXT = JE.TEXT ## Vrátí hodnotu PRAVDA, pokud je argument hodnota text. +N = N ## Vrátí hodnotu převedenou na číslo. +NA = NEDEF ## Vrátí chybovou hodnotu #N/A. +TYPE = TYP ## Vrátí číslo označující datový typ hodnoty. + + +## +## Logical functions Logické funkce +## +AND = A ## Vrátí hodnotu PRAVDA, mají-li všechny argumenty hodnotu PRAVDA. +FALSE = NEPRAVDA ## Vrátí logickou hodnotu NEPRAVDA. +IF = KDYŽ ## Určí, který logický test má proběhnout. +IFERROR = IFERROR ## Pokud je vzorec vyhodnocen jako chyba, vrátí zadanou hodnotu. V opačném případě vrátí výsledek vzorce. +NOT = NE ## Provede logickou negaci argumentu funkce. +OR = NEBO ## Vrátí hodnotu PRAVDA, je-li alespoň jeden argument roven hodnotě PRAVDA. +TRUE = PRAVDA ## Vrátí logickou hodnotu PRAVDA. + + +## +## Lookup and reference functions Vyhledávací funkce +## +ADDRESS = ODKAZ ## Vrátí textový odkaz na jednu buňku listu. +AREAS = POČET.BLOKŮ ## Vrátí počet oblastí v odkazu. +CHOOSE = ZVOLIT ## Zvolí hodnotu ze seznamu hodnot. +COLUMN = SLOUPEC ## Vrátí číslo sloupce odkazu. +COLUMNS = SLOUPCE ## Vrátí počet sloupců v odkazu. +HLOOKUP = VVYHLEDAT ## Prohledá horní řádek matice a vrátí hodnotu určené buňky. +HYPERLINK = HYPERTEXTOVÝ.ODKAZ ## Vytvoří zástupce nebo odkaz, který otevře dokument uložený na síťovém serveru, v síti intranet nebo Internet. +INDEX = INDEX ## Pomocí rejstříku zvolí hodnotu z odkazu nebo matice. +INDIRECT = NEPŘÍMÝ.ODKAZ ## Vrátí odkaz určený textovou hodnotou. +LOOKUP = VYHLEDAT ## Vyhledá hodnoty ve vektoru nebo matici. +MATCH = POZVYHLEDAT ## Vyhledá hodnoty v odkazu nebo matici. +OFFSET = POSUN ## Vrátí posun odkazu od zadaného odkazu. +ROW = ŘÁDEK ## Vrátí číslo řádku odkazu. +ROWS = ŘÁDKY ## Vrátí počet řádků v odkazu. +RTD = RTD ## Načte data reálného času z programu, který podporuje automatizaci modelu COM (Automatizace: Způsob práce s objekty určité aplikace z jiné aplikace nebo nástroje pro vývoj. Automatizace (dříve nazývaná automatizace OLE) je počítačovým standardem a je funkcí modelu COM (Component Object Model).). +TRANSPOSE = TRANSPOZICE ## Vrátí transponovanou matici. +VLOOKUP = SVYHLEDAT ## Prohledá první sloupec matice, přesune kurzor v řádku a vrátí hodnotu buňky. + + +## +## Math and trigonometry functions Matematické a trigonometrické funkce +## +ABS = ABS ## Vrátí absolutní hodnotu čísla. +ACOS = ARCCOS ## Vrátí arkuskosinus čísla. +ACOSH = ARCCOSH ## Vrátí hyperbolický arkuskosinus čísla. +ASIN = ARCSIN ## Vrátí arkussinus čísla. +ASINH = ARCSINH ## Vrátí hyperbolický arkussinus čísla. +ATAN = ARCTG ## Vrátí arkustangens čísla. +ATAN2 = ARCTG2 ## Vrátí arkustangens x-ové a y-ové souřadnice. +ATANH = ARCTGH ## Vrátí hyperbolický arkustangens čísla. +CEILING = ZAOKR.NAHORU ## Zaokrouhlí číslo na nejbližší celé číslo nebo na nejbližší násobek zadané hodnoty. +COMBIN = KOMBINACE ## Vrátí počet kombinací pro daný počet položek. +COS = COS ## Vrátí kosinus čísla. +COSH = COSH ## Vrátí hyperbolický kosinus čísla. +DEGREES = DEGREES ## Převede radiány na stupně. +EVEN = ZAOKROUHLIT.NA.SUDÉ ## Zaokrouhlí číslo nahoru na nejbližší celé sudé číslo. +EXP = EXP ## Vrátí základ přirozeného logaritmu e umocněný na zadané číslo. +FACT = FAKTORIÁL ## Vrátí faktoriál čísla. +FACTDOUBLE = FACTDOUBLE ## Vrátí dvojitý faktoriál čísla. +FLOOR = ZAOKR.DOLŮ ## Zaokrouhlí číslo dolů, směrem k nule. +GCD = GCD ## Vrátí největší společný dělitel. +INT = CELÁ.ČÁST ## Zaokrouhlí číslo dolů na nejbližší celé číslo. +LCM = LCM ## Vrátí nejmenší společný násobek. +LN = LN ## Vrátí přirozený logaritmus čísla. +LOG = LOGZ ## Vrátí logaritmus čísla při zadaném základu. +LOG10 = LOG ## Vrátí dekadický logaritmus čísla. +MDETERM = DETERMINANT ## Vrátí determinant matice. +MINVERSE = INVERZE ## Vrátí inverzní matici. +MMULT = SOUČIN.MATIC ## Vrátí součin dvou matic. +MOD = MOD ## Vrátí zbytek po dělení. +MROUND = MROUND ## Vrátí číslo zaokrouhlené na požadovaný násobek. +MULTINOMIAL = MULTINOMIAL ## Vrátí mnohočlen z množiny čísel. +ODD = ZAOKROUHLIT.NA.LICHÉ ## Zaokrouhlí číslo nahoru na nejbližší celé liché číslo. +PI = PI ## Vrátí hodnotu čísla pí. +POWER = POWER ## Umocní číslo na zadanou mocninu. +PRODUCT = SOUČIN ## Vynásobí argumenty funkce. +QUOTIENT = QUOTIENT ## Vrátí celou část dělení. +RADIANS = RADIANS ## Převede stupně na radiány. +RAND = NÁHČÍSLO ## Vrátí náhodné číslo mezi 0 a 1. +RANDBETWEEN = RANDBETWEEN ## Vrátí náhodné číslo mezi zadanými čísly. +ROMAN = ROMAN ## Převede arabskou číslici na římskou ve formátu textu. +ROUND = ZAOKROUHLIT ## Zaokrouhlí číslo na zadaný počet číslic. +ROUNDDOWN = ROUNDDOWN ## Zaokrouhlí číslo dolů, směrem k nule. +ROUNDUP = ROUNDUP ## Zaokrouhlí číslo nahoru, směrem od nuly. +SERIESSUM = SERIESSUM ## Vrátí součet mocninné řady určené podle vzorce. +SIGN = SIGN ## Vrátí znaménko čísla. +SIN = SIN ## Vrátí sinus daného úhlu. +SINH = SINH ## Vrátí hyperbolický sinus čísla. +SQRT = ODMOCNINA ## Vrátí kladnou druhou odmocninu. +SQRTPI = SQRTPI ## Vrátí druhou odmocninu výrazu (číslo * pí). +SUBTOTAL = SUBTOTAL ## Vrátí souhrn v seznamu nebo databázi. +SUM = SUMA ## Sečte argumenty funkce. +SUMIF = SUMIF ## Sečte buňky vybrané podle zadaných kritérií. +SUMIFS = SUMIFS ## Sečte buňky určené více zadanými podmínkami. +SUMPRODUCT = SOUČIN.SKALÁRNÍ ## Vrátí součet součinů odpovídajících prvků matic. +SUMSQ = SUMA.ČTVERCŮ ## Vrátí součet čtverců argumentů. +SUMX2MY2 = SUMX2MY2 ## Vrátí součet rozdílu čtverců odpovídajících hodnot ve dvou maticích. +SUMX2PY2 = SUMX2PY2 ## Vrátí součet součtu čtverců odpovídajících hodnot ve dvou maticích. +SUMXMY2 = SUMXMY2 ## Vrátí součet čtverců rozdílů odpovídajících hodnot ve dvou maticích. +TAN = TGTG ## Vrátí tangens čísla. +TANH = TGH ## Vrátí hyperbolický tangens čísla. +TRUNC = USEKNOUT ## Zkrátí číslo na celé číslo. + + +## +## Statistical functions Statistické funkce +## +AVEDEV = PRŮMODCHYLKA ## Vrátí průměrnou hodnotu absolutních odchylek datových bodů od jejich střední hodnoty. +AVERAGE = PRŮMĚR ## Vrátí průměrnou hodnotu argumentů. +AVERAGEA = AVERAGEA ## Vrátí průměrnou hodnotu argumentů včetně čísel, textu a logických hodnot. +AVERAGEIF = AVERAGEIF ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk v oblasti, které vyhovují příslušné podmínce. +AVERAGEIFS = AVERAGEIFS ## Vrátí průměrnou hodnotu (aritmetický průměr) všech buněk vyhovujících několika podmínkám. +BETADIST = BETADIST ## Vrátí hodnotu součtového rozdělení beta. +BETAINV = BETAINV ## Vrátí inverzní hodnotu součtového rozdělení pro zadané rozdělení beta. +BINOMDIST = BINOMDIST ## Vrátí hodnotu binomického rozdělení pravděpodobnosti jednotlivých veličin. +CHIDIST = CHIDIST ## Vrátí jednostrannou pravděpodobnost rozdělení chí-kvadrát. +CHIINV = CHIINV ## Vrátí hodnotu funkce inverzní k distribuční funkci jednostranné pravděpodobnosti rozdělení chí-kvadrát. +CHITEST = CHITEST ## Vrátí test nezávislosti. +CONFIDENCE = CONFIDENCE ## Vrátí interval spolehlivosti pro střední hodnotu základního souboru. +CORREL = CORREL ## Vrátí korelační koeficient mezi dvěma množinami dat. +COUNT = POČET ## Vrátí počet čísel v seznamu argumentů. +COUNTA = POČET2 ## Vrátí počet hodnot v seznamu argumentů. +COUNTBLANK = COUNTBLANK ## Spočítá počet prázdných buněk v oblasti. +COUNTIF = COUNTIF ## Spočítá buňky v oblasti, které odpovídají zadaným kritériím. +COUNTIFS = COUNTIFS ## Spočítá buňky v oblasti, které odpovídají více kritériím. +COVAR = COVAR ## Vrátí hodnotu kovariance, průměrnou hodnotu součinů párových odchylek +CRITBINOM = CRITBINOM ## Vrátí nejmenší hodnotu, pro kterou má součtové binomické rozdělení hodnotu větší nebo rovnu hodnotě kritéria. +DEVSQ = DEVSQ ## Vrátí součet čtverců odchylek. +EXPONDIST = EXPONDIST ## Vrátí hodnotu exponenciálního rozdělení. +FDIST = FDIST ## Vrátí hodnotu rozdělení pravděpodobnosti F. +FINV = FINV ## Vrátí hodnotu inverzní funkce k distribuční funkci rozdělení F. +FISHER = FISHER ## Vrátí hodnotu Fisherovy transformace. +FISHERINV = FISHERINV ## Vrátí hodnotu inverzní funkce k Fisherově transformaci. +FORECAST = FORECAST ## Vrátí hodnotu lineárního trendu. +FREQUENCY = ČETNOSTI ## Vrátí četnost rozdělení jako svislou matici. +FTEST = FTEST ## Vrátí výsledek F-testu. +GAMMADIST = GAMMADIST ## Vrátí hodnotu rozdělení gama. +GAMMAINV = GAMMAINV ## Vrátí hodnotu inverzní funkce k distribuční funkci součtového rozdělení gama. +GAMMALN = GAMMALN ## Vrátí přirozený logaritmus funkce gama, Γ(x). +GEOMEAN = GEOMEAN ## Vrátí geometrický průměr. +GROWTH = LOGLINTREND ## Vrátí hodnoty exponenciálního trendu. +HARMEAN = HARMEAN ## Vrátí harmonický průměr. +HYPGEOMDIST = HYPGEOMDIST ## Vrátí hodnotu hypergeometrického rozdělení. +INTERCEPT = INTERCEPT ## Vrátí úsek lineární regresní čáry. +KURT = KURT ## Vrátí hodnotu excesu množiny dat. +LARGE = LARGE ## Vrátí k-tou největší hodnotu množiny dat. +LINEST = LINREGRESE ## Vrátí parametry lineárního trendu. +LOGEST = LOGLINREGRESE ## Vrátí parametry exponenciálního trendu. +LOGINV = LOGINV ## Vrátí inverzní funkci k distribuční funkci logaritmicko-normálního rozdělení. +LOGNORMDIST = LOGNORMDIST ## Vrátí hodnotu součtového logaritmicko-normálního rozdělení. +MAX = MAX ## Vrátí maximální hodnotu seznamu argumentů. +MAXA = MAXA ## Vrátí maximální hodnotu seznamu argumentů včetně čísel, textu a logických hodnot. +MEDIAN = MEDIAN ## Vrátí střední hodnotu zadaných čísel. +MIN = MIN ## Vrátí minimální hodnotu seznamu argumentů. +MINA = MINA ## Vrátí nejmenší hodnotu v seznamu argumentů včetně čísel, textu a logických hodnot. +MODE = MODE ## Vrátí hodnotu, která se v množině dat vyskytuje nejčastěji. +NEGBINOMDIST = NEGBINOMDIST ## Vrátí hodnotu negativního binomického rozdělení. +NORMDIST = NORMDIST ## Vrátí hodnotu normálního součtového rozdělení. +NORMINV = NORMINV ## Vrátí inverzní funkci k funkci normálního součtového rozdělení. +NORMSDIST = NORMSDIST ## Vrátí hodnotu standardního normálního součtového rozdělení. +NORMSINV = NORMSINV ## Vrátí inverzní funkci k funkci standardního normálního součtového rozdělení. +PEARSON = PEARSON ## Vrátí Pearsonův výsledný momentový korelační koeficient. +PERCENTILE = PERCENTIL ## Vrátí hodnotu k-tého percentilu hodnot v oblasti. +PERCENTRANK = PERCENTRANK ## Vrátí pořadí hodnoty v množině dat vyjádřené procentuální částí množiny dat. +PERMUT = PERMUTACE ## Vrátí počet permutací pro zadaný počet objektů. +POISSON = POISSON ## Vrátí hodnotu distribuční funkce Poissonova rozdělení. +PROB = PROB ## Vrátí pravděpodobnost výskytu hodnot v oblasti mezi dvěma mezními hodnotami. +QUARTILE = QUARTIL ## Vrátí hodnotu kvartilu množiny dat. +RANK = RANK ## Vrátí pořadí čísla v seznamu čísel. +RSQ = RKQ ## Vrátí druhou mocninu Pearsonova výsledného momentového korelačního koeficientu. +SKEW = SKEW ## Vrátí zešikmení rozdělení. +SLOPE = SLOPE ## Vrátí směrnici lineární regresní čáry. +SMALL = SMALL ## Vrátí k-tou nejmenší hodnotu množiny dat. +STANDARDIZE = STANDARDIZE ## Vrátí normalizovanou hodnotu. +STDEV = SMODCH.VÝBĚR ## Vypočte směrodatnou odchylku výběru. +STDEVA = STDEVA ## Vypočte směrodatnou odchylku výběru včetně čísel, textu a logických hodnot. +STDEVP = SMODCH ## Vypočte směrodatnou odchylku základního souboru. +STDEVPA = STDEVPA ## Vypočte směrodatnou odchylku základního souboru včetně čísel, textu a logických hodnot. +STEYX = STEYX ## Vrátí standardní chybu předpovězené hodnoty y pro každou hodnotu x v regresi. +TDIST = TDIST ## Vrátí hodnotu Studentova t-rozdělení. +TINV = TINV ## Vrátí inverzní funkci k distribuční funkci Studentova t-rozdělení. +TREND = LINTREND ## Vrátí hodnoty lineárního trendu. +TRIMMEAN = TRIMMEAN ## Vrátí střední hodnotu vnitřní části množiny dat. +TTEST = TTEST ## Vrátí pravděpodobnost spojenou se Studentovým t-testem. +VAR = VAR.VÝBĚR ## Vypočte rozptyl výběru. +VARA = VARA ## Vypočte rozptyl výběru včetně čísel, textu a logických hodnot. +VARP = VAR ## Vypočte rozptyl základního souboru. +VARPA = VARPA ## Vypočte rozptyl základního souboru včetně čísel, textu a logických hodnot. +WEIBULL = WEIBULL ## Vrátí hodnotu Weibullova rozdělení. +ZTEST = ZTEST ## Vrátí jednostrannou P-hodnotu z-testu. + + +## +## Text functions Textové funkce +## +ASC = ASC ## Změní znaky s plnou šířkou (dvoubajtové)v řetězci znaků na znaky s poloviční šířkou (jednobajtové). +BAHTTEXT = BAHTTEXT ## Převede číslo na text ve formátu, měny ß (baht). +CHAR = ZNAK ## Vrátí znak určený číslem kódu. +CLEAN = VYČISTIT ## Odebere z textu všechny netisknutelné znaky. +CODE = KÓD ## Vrátí číselný kód prvního znaku zadaného textového řetězce. +CONCATENATE = CONCATENATE ## Spojí několik textových položek do jedné. +DOLLAR = KČ ## Převede číslo na text ve formátu měny Kč (česká koruna). +EXACT = STEJNÉ ## Zkontroluje, zda jsou dvě textové hodnoty shodné. +FIND = NAJÍT ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). +FINDB = FINDB ## Nalezne textovou hodnotu uvnitř jiné (rozlišuje malá a velká písmena). +FIXED = ZAOKROUHLIT.NA.TEXT ## Zformátuje číslo jako text s pevným počtem desetinných míst. +JIS = JIS ## Změní znaky s poloviční šířkou (jednobajtové) v řetězci znaků na znaky s plnou šířkou (dvoubajtové). +LEFT = ZLEVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. +LEFTB = LEFTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vlevo. +LEN = DÉLKA ## Vrátí počet znaků textového řetězce. +LENB = LENB ## Vrátí počet znaků textového řetězce. +LOWER = MALÁ ## Převede text na malá písmena. +MID = ČÁST ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. +MIDB = MIDB ## Vrátí určitý počet znaků textového řetězce počínaje zadaným místem. +PHONETIC = ZVUKOVÉ ## Extrahuje fonetické znaky (furigana) z textového řetězce. +PROPER = VELKÁ2 ## Převede první písmeno každého slova textové hodnoty na velké. +REPLACE = NAHRADIT ## Nahradí znaky uvnitř textu. +REPLACEB = NAHRADITB ## Nahradí znaky uvnitř textu. +REPT = OPAKOVAT ## Zopakuje text podle zadaného počtu opakování. +RIGHT = ZPRAVA ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. +RIGHTB = RIGHTB ## Vrátí první znaky textové hodnoty umístěné nejvíce vpravo. +SEARCH = HLEDAT ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). +SEARCHB = SEARCHB ## Nalezne textovou hodnotu uvnitř jiné (malá a velká písmena nejsou rozlišována). +SUBSTITUTE = DOSADIT ## V textovém řetězci nahradí starý text novým. +T = T ## Převede argumenty na text. +TEXT = HODNOTA.NA.TEXT ## Zformátuje číslo a převede ho na text. +TRIM = PROČISTIT ## Odstraní z textu mezery. +UPPER = VELKÁ ## Převede text na velká písmena. +VALUE = HODNOTA ## Převede textový argument na číslo. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/config new file mode 100644 index 00000000..ae590031 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/config @@ -0,0 +1,48 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + + +## +## Excel Error Codes (For future use) +## +NULL = #NUL! +DIV0 = #DIVISION/0! +VALUE = #VÆRDI! +REF = #REFERENCE! +NAME = #NAVN? +NUM = #NUM! +NA = #I/T diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/functions new file mode 100644 index 00000000..26e0310c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/da/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Tilføjelsesprogram- og automatiseringsfunktioner +## +GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data, der er lagret i en pivottabelrapport + + +## +## Cube functions Kubefunktioner +## +CUBEKPIMEMBER = KUBE.KPI.MEDLEM ## Returnerer navn, egenskab og mål for en KPI-indikator og viser navnet og egenskaben i cellen. En KPI-indikator er en målbar størrelse, f.eks. bruttooverskud pr. måned eller personaleudskiftning pr. kvartal, der bruges til at overvåge en organisations præstationer. +CUBEMEMBER = KUBE.MEDLEM ## Returnerer et medlem eller en tupel fra kubehierarkiet. Bruges til at validere, om et medlem eller en tupel findes i kuben. +CUBEMEMBERPROPERTY = KUBEMEDLEM.EGENSKAB ## Returnerer værdien af en egenskab for et medlem i kuben. Bruges til at validere, om et medlemsnavn findes i kuben, og returnere den angivne egenskab for medlemmet. +CUBERANKEDMEMBER = KUBEMEDLEM.RANG ## Returnerer det n'te eller rangordnede medlem i et sæt. Bruges til at returnere et eller flere elementer i et sæt, f.eks. topsælgere eller de 10 bedste elever. +CUBESET = KUBESÆT ## Definerer et beregnet sæt medlemmer eller tupler ved at sende et sætudtryk til kuben på serveren, som opretter sættet og returnerer det til Microsoft Office Excel. +CUBESETCOUNT = KUBESÆT.TÆL ## Returnerer antallet af elementer i et sæt. +CUBEVALUE = KUBEVÆRDI ## Returnerer en sammenlagt (aggregeret) værdi fra en kube. + + +## +## Database functions Databasefunktioner +## +DAVERAGE = DMIDDEL ## Returnerer gennemsnittet af markerede databaseposter +DCOUNT = DTÆL ## Tæller de celler, der indeholder tal, i en database +DCOUNTA = DTÆLV ## Tæller udfyldte celler i en database +DGET = DHENT ## Uddrager en enkelt post, der opfylder de angivne kriterier, fra en database +DMAX = DMAKS ## Returnerer den største værdi blandt markerede databaseposter +DMIN = DMIN ## Returnerer den mindste værdi blandt markerede databaseposter +DPRODUCT = DPRODUKT ## Ganger værdierne i et bestemt felt med poster, der opfylder kriterierne i en database +DSTDEV = DSTDAFV ## Beregner et skøn over standardafvigelsen baseret på en stikprøve af markerede databaseposter +DSTDEVP = DSTDAFVP ## Beregner standardafvigelsen baseret på hele populationen af markerede databaseposter +DSUM = DSUM ## Sammenlægger de tal i feltkolonnen i databasen, der opfylder kriterierne +DVAR = DVARIANS ## Beregner varians baseret på en stikprøve af markerede databaseposter +DVARP = DVARIANSP ## Beregner varians baseret på hele populationen af markerede databaseposter + + +## +## Date and time functions Dato- og klokkeslætsfunktioner +## +DATE = DATO ## Returnerer serienummeret for en bestemt dato +DATEVALUE = DATOVÆRDI ## Konverterer en dato i form af tekst til et serienummer +DAY = DAG ## Konverterer et serienummer til en dag i måneden +DAYS360 = DAGE360 ## Beregner antallet af dage mellem to datoer på grundlag af et år med 360 dage +EDATE = EDATO ## Returnerer serienummeret for den dato, der ligger det angivne antal måneder før eller efter startdatoen +EOMONTH = SLUT.PÅ.MÅNED ## Returnerer serienummeret på den sidste dag i måneden før eller efter et angivet antal måneder +HOUR = TIME ## Konverterer et serienummer til en time +MINUTE = MINUT ## Konverterer et serienummer til et minut +MONTH = MÅNED ## Konverterer et serienummer til en måned +NETWORKDAYS = ANTAL.ARBEJDSDAGE ## Returnerer antallet af hele arbejdsdage mellem to datoer +NOW = NU ## Returnerer serienummeret for den aktuelle dato eller det aktuelle klokkeslæt +SECOND = SEKUND ## Konverterer et serienummer til et sekund +TIME = KLOKKESLÆT ## Returnerer serienummeret for et bestemt klokkeslæt +TIMEVALUE = TIDSVÆRDI ## Konverterer et klokkeslæt i form af tekst til et serienummer +TODAY = IDAG ## Returnerer serienummeret for dags dato +WEEKDAY = UGEDAG ## Konverterer et serienummer til en ugedag +WEEKNUM = UGE.NR ## Konverterer et serienummer til et tal, der angiver ugenummeret i året +WORKDAY = ARBEJDSDAG ## Returnerer serienummeret for dagen før eller efter det angivne antal arbejdsdage +YEAR = ÅR ## Konverterer et serienummer til et år +YEARFRAC = ÅR.BRØK ## Returnerer årsbrøken, der repræsenterer antallet af hele dage mellem startdato og slutdato + + +## +## Engineering functions Tekniske funktioner +## +BESSELI = BESSELI ## Returnerer den modificerede Bessel-funktion In(x) +BESSELJ = BESSELJ ## Returnerer Bessel-funktionen Jn(x) +BESSELK = BESSELK ## Returnerer den modificerede Bessel-funktion Kn(x) +BESSELY = BESSELY ## Returnerer Bessel-funktionen Yn(x) +BIN2DEC = BIN.TIL.DEC ## Konverterer et binært tal til et decimaltal +BIN2HEX = BIN.TIL.HEX ## Konverterer et binært tal til et heksadecimalt tal +BIN2OCT = BIN.TIL.OKT ## Konverterer et binært tal til et oktaltal. +COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koefficienter til et komplekst tal +CONVERT = KONVERTER ## Konverterer et tal fra én måleenhed til en anden +DEC2BIN = DEC.TIL.BIN ## Konverterer et decimaltal til et binært tal +DEC2HEX = DEC.TIL.HEX ## Konverterer et decimaltal til et heksadecimalt tal +DEC2OCT = DEC.TIL.OKT ## Konverterer et decimaltal til et oktaltal +DELTA = DELTA ## Tester, om to værdier er ens +ERF = FEJLFUNK ## Returner fejlfunktionen +ERFC = FEJLFUNK.KOMP ## Returnerer den komplementære fejlfunktion +GESTEP = GETRIN ## Tester, om et tal er større end en grænseværdi +HEX2BIN = HEX.TIL.BIN ## Konverterer et heksadecimalt tal til et binært tal +HEX2DEC = HEX.TIL.DEC ## Konverterer et decimaltal til et heksadecimalt tal +HEX2OCT = HEX.TIL.OKT ## Konverterer et heksadecimalt tal til et oktaltal +IMABS = IMAGABS ## Returnerer den absolutte værdi (modulus) for et komplekst tal +IMAGINARY = IMAGINÆR ## Returnerer den imaginære koefficient for et komplekst tal +IMARGUMENT = IMAGARGUMENT ## Returnerer argumentet theta, en vinkel udtrykt i radianer +IMCONJUGATE = IMAGKONJUGERE ## Returnerer den komplekse konjugation af et komplekst tal +IMCOS = IMAGCOS ## Returnerer et komplekst tals cosinus +IMDIV = IMAGDIV ## Returnerer kvotienten for to komplekse tal +IMEXP = IMAGEKSP ## Returnerer et komplekst tals eksponentialfunktion +IMLN = IMAGLN ## Returnerer et komplekst tals naturlige logaritme +IMLOG10 = IMAGLOG10 ## Returnerer et komplekst tals sædvanlige logaritme (titalslogaritme) +IMLOG2 = IMAGLOG2 ## Returnerer et komplekst tals sædvanlige logaritme (totalslogaritme) +IMPOWER = IMAGPOTENS ## Returnerer et komplekst tal opløftet i en heltalspotens +IMPRODUCT = IMAGPRODUKT ## Returnerer produktet af komplekse tal +IMREAL = IMAGREELT ## Returnerer den reelle koefficient for et komplekst tal +IMSIN = IMAGSIN ## Returnerer et komplekst tals sinus +IMSQRT = IMAGKVROD ## Returnerer et komplekst tals kvadratrod +IMSUB = IMAGSUB ## Returnerer forskellen mellem to komplekse tal +IMSUM = IMAGSUM ## Returnerer summen af komplekse tal +OCT2BIN = OKT.TIL.BIN ## Konverterer et oktaltal til et binært tal +OCT2DEC = OKT.TIL.DEC ## Konverterer et oktaltal til et decimaltal +OCT2HEX = OKT.TIL.HEX ## Konverterer et oktaltal til et heksadecimalt tal + + +## +## Financial functions Finansielle funktioner +## +ACCRINT = PÅLØBRENTE ## Returnerer den påløbne rente for et værdipapir med periodiske renteudbetalinger +ACCRINTM = PÅLØBRENTE.UDLØB ## Returnerer den påløbne rente for et værdipapir, hvor renteudbetalingen finder sted ved papirets udløb +AMORDEGRC = AMORDEGRC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode ved hjælp af en afskrivningskoefficient +AMORLINC = AMORLINC ## Returnerer afskrivningsbeløbet for hver regnskabsperiode +COUPDAYBS = KUPONDAGE.SA ## Returnerer antallet af dage fra starten af kuponperioden til afregningsdatoen +COUPDAYS = KUPONDAGE.A ## Returnerer antallet af dage fra begyndelsen af kuponperioden til afregningsdatoen +COUPDAYSNC = KUPONDAGE.ANK ## Returnerer antallet af dage i den kuponperiode, der indeholder afregningsdatoen +COUPNCD = KUPONDAG.NÆSTE ## Returnerer den næste kupondato efter afregningsdatoen +COUPNUM = KUPONBETALINGER ## Returnerer antallet af kuponudbetalinger mellem afregnings- og udløbsdatoen +COUPPCD = KUPONDAG.FORRIGE ## Returnerer den forrige kupondato før afregningsdatoen +CUMIPMT = AKKUM.RENTE ## Returnerer den akkumulerede rente, der betales på et lån mellem to perioder +CUMPRINC = AKKUM.HOVEDSTOL ## Returnerer den akkumulerede nedbringelse af hovedstol mellem to perioder +DB = DB ## Returnerer afskrivningen på et aktiv i en angivet periode ved anvendelse af saldometoden +DDB = DSA ## Returnerer afskrivningsbeløbet for et aktiv over en bestemt periode ved anvendelse af dobbeltsaldometoden eller en anden afskrivningsmetode, som du angiver +DISC = DISKONTO ## Returnerer et værdipapirs diskonto +DOLLARDE = KR.DECIMAL ## Konverterer en kronepris udtrykt som brøk til en kronepris udtrykt som decimaltal +DOLLARFR = KR.BRØK ## Konverterer en kronepris udtrykt som decimaltal til en kronepris udtrykt som brøk +DURATION = VARIGHED ## Returnerer den årlige løbetid for et værdipapir med periodiske renteudbetalinger +EFFECT = EFFEKTIV.RENTE ## Returnerer den årlige effektive rente +FV = FV ## Returnerer fremtidsværdien af en investering +FVSCHEDULE = FVTABEL ## Returnerer den fremtidige værdi af en hovedstol, når der er tilskrevet rente og rentes rente efter forskellige rentesatser +INTRATE = RENTEFOD ## Returnerer renten på et fuldt ud investeret værdipapir +IPMT = R.YDELSE ## Returnerer renten fra en investering for en given periode +IRR = IA ## Returnerer den interne rente for en række pengestrømme +ISPMT = ISPMT ## Beregner den betalte rente i løbet af en bestemt investeringsperiode +MDURATION = MVARIGHED ## Returnerer Macauleys modificerede løbetid for et værdipapir med en formodet pari på kr. 100 +MIRR = MIA ## Returnerer den interne forrentning, hvor positive og negative pengestrømme finansieres til forskellig rente +NOMINAL = NOMINEL ## Returnerer den årlige nominelle rente +NPER = NPER ## Returnerer antallet af perioder for en investering +NPV = NUTIDSVÆRDI ## Returnerer nettonutidsværdien for en investering baseret på en række periodiske pengestrømme og en diskonteringssats +ODDFPRICE = ULIGE.KURS.PÅLYDENDE ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med en ulige (kort eller lang) første periode +ODDFYIELD = ULIGE.FØRSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige første periode +ODDLPRICE = ULIGE.SIDSTE.KURS ## Returnerer kursen pr. kr. 100 nominel værdi for et værdipapir med ulige sidste periode +ODDLYIELD = ULIGE.SIDSTE.AFKAST ## Returnerer afkastet for et værdipapir med ulige sidste periode +PMT = YDELSE ## Returnerer renten fra en investering for en given periode +PPMT = H.YDELSE ## Returnerer ydelsen på hovedstolen for en investering i en given periode +PRICE = KURS ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir med periodiske renteudbetalinger +PRICEDISC = KURS.DISKONTO ## Returnerer kursen pr. kr 100 nominel værdi for et diskonteret værdipapir +PRICEMAT = KURS.UDLØB ## Returnerer kursen pr. kr 100 nominel værdi for et værdipapir, hvor renten udbetales ved papirets udløb +PV = NV ## Returnerer den nuværende værdi af en investering +RATE = RENTE ## Returnerer renten i hver periode for en annuitet +RECEIVED = MODTAGET.VED.UDLØB ## Returnerer det beløb, der modtages ved udløbet af et fuldt ud investeret værdipapir +SLN = LA ## Returnerer den lineære afskrivning for et aktiv i en enkelt periode +SYD = ÅRSAFSKRIVNING ## Returnerer den årlige afskrivning på et aktiv i en bestemt periode +TBILLEQ = STATSOBLIGATION ## Returnerer det obligationsækvivalente afkast for en statsobligation +TBILLPRICE = STATSOBLIGATION.KURS ## Returnerer kursen pr. kr 100 nominel værdi for en statsobligation +TBILLYIELD = STATSOBLIGATION.AFKAST ## Returnerer en afkastet på en statsobligation +VDB = VSA ## Returnerer afskrivningen på et aktiv i en angivet periode, herunder delperioder, ved brug af dobbeltsaldometoden +XIRR = INTERN.RENTE ## Returnerer den interne rente for en plan over pengestrømme, der ikke behøver at være periodiske +XNPV = NETTO.NUTIDSVÆRDI ## Returnerer nutidsværdien for en plan over pengestrømme, der ikke behøver at være periodiske +YIELD = AFKAST ## Returnerer afkastet for et værdipapir med periodiske renteudbetalinger +YIELDDISC = AFKAST.DISKONTO ## Returnerer det årlige afkast for et diskonteret værdipapir, f.eks. en statsobligation +YIELDMAT = AFKAST.UDLØBSDATO ## Returnerer det årlige afkast for et værdipapir, hvor renten udbetales ved papirets udløb + + +## +## Information functions Informationsfunktioner +## +CELL = CELLE ## Returnerer oplysninger om formatering, placering eller indhold af en celle +ERROR.TYPE = FEJLTYPE ## Returnerer et tal, der svarer til en fejltype +INFO = INFO ## Returnerer oplysninger om det aktuelle operativmiljø +ISBLANK = ER.TOM ## Returnerer SAND, hvis værdien er tom +ISERR = ER.FJL ## Returnerer SAND, hvis værdien er en fejlværdi undtagen #I/T +ISERROR = ER.FEJL ## Returnerer SAND, hvis værdien er en fejlværdi +ISEVEN = ER.LIGE ## Returnerer SAND, hvis tallet er lige +ISLOGICAL = ER.LOGISK ## Returnerer SAND, hvis værdien er en logisk værdi +ISNA = ER.IKKE.TILGÆNGELIG ## Returnerer SAND, hvis værdien er fejlværdien #I/T +ISNONTEXT = ER.IKKE.TEKST ## Returnerer SAND, hvis værdien ikke er tekst +ISNUMBER = ER.TAL ## Returnerer SAND, hvis værdien er et tal +ISODD = ER.ULIGE ## Returnerer SAND, hvis tallet er ulige +ISREF = ER.REFERENCE ## Returnerer SAND, hvis værdien er en reference +ISTEXT = ER.TEKST ## Returnerer SAND, hvis værdien er tekst +N = TAL ## Returnerer en værdi konverteret til et tal +NA = IKKE.TILGÆNGELIG ## Returnerer fejlværdien #I/T +TYPE = VÆRDITYPE ## Returnerer et tal, der angiver datatypen for en værdi + + +## +## Logical functions Logiske funktioner +## +AND = OG ## Returnerer SAND, hvis alle argumenterne er sande +FALSE = FALSK ## Returnerer den logiske værdi FALSK +IF = HVIS ## Angiver en logisk test, der skal udføres +IFERROR = HVIS.FEJL ## Returnerer en værdi, du angiver, hvis en formel evauleres som en fejl. Returnerer i modsat fald resultatet af formlen +NOT = IKKE ## Vender argumentets logik om +OR = ELLER ## Returneret værdien SAND, hvis mindst ét argument er sandt +TRUE = SAND ## Returnerer den logiske værdi SAND + + +## +## Lookup and reference functions Opslags- og referencefunktioner +## +ADDRESS = ADRESSE ## Returnerer en reference som tekst til en enkelt celle i et regneark +AREAS = OMRÅDER ## Returnerer antallet af områder i en reference +CHOOSE = VÆLG ## Vælger en værdi på en liste med værdier +COLUMN = KOLONNE ## Returnerer kolonnenummeret i en reference +COLUMNS = KOLONNER ## Returnerer antallet af kolonner i en reference +HLOOKUP = VOPSLAG ## Søger i den øverste række af en matrix og returnerer værdien af den angivne celle +HYPERLINK = HYPERLINK ## Opretter en genvej kaldet et hyperlink, der åbner et dokument, som er lagret på en netværksserver, på et intranet eller på internettet +INDEX = INDEKS ## Anvender et indeks til at vælge en værdi fra en reference eller en matrix +INDIRECT = INDIREKTE ## Returnerer en reference, der er angivet af en tekstværdi +LOOKUP = SLÅ.OP ## Søger værdier i en vektor eller en matrix +MATCH = SAMMENLIGN ## Søger værdier i en reference eller en matrix +OFFSET = FORSKYDNING ## Returnerer en reference forskudt i forhold til en given reference +ROW = RÆKKE ## Returnerer rækkenummeret for en reference +ROWS = RÆKKER ## Returnerer antallet af rækker i en reference +RTD = RTD ## Henter realtidsdata fra et program, der understøtter COM-automatisering (Automation: En metode til at arbejde med objekter fra et andet program eller udviklingsværktøj. Automation, som tidligere blev kaldt OLE Automation, er en industristandard og en funktion i COM (Component Object Model).) +TRANSPOSE = TRANSPONER ## Returnerer en transponeret matrix +VLOOKUP = LOPSLAG ## Søger i øverste række af en matrix og flytter på tværs af rækken for at returnere en celleværdi + + +## +## Math and trigonometry functions Matematiske og trigonometriske funktioner +## +ABS = ABS ## Returnerer den absolutte værdi af et tal +ACOS = ARCCOS ## Returnerer et tals arcus cosinus +ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus af tal +ASIN = ARCSIN ## Returnerer et tals arcus sinus +ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus for tal +ATAN = ARCTAN ## Returnerer et tals arcus tangens +ATAN2 = ARCTAN2 ## Returnerer de angivne x- og y-koordinaters arcus tangens +ATANH = ARCTANH ## Returnerer et tals inverse hyperbolske tangens +CEILING = AFRUND.LOFT ## Afrunder et tal til nærmeste heltal eller til nærmeste multiplum af betydning +COMBIN = KOMBIN ## Returnerer antallet af kombinationer for et givet antal objekter +COS = COS ## Returnerer et tals cosinus +COSH = COSH ## Returnerer den inverse hyperbolske cosinus af et tal +DEGREES = GRADER ## Konverterer radianer til grader +EVEN = LIGE ## Runder et tal op til nærmeste lige heltal +EXP = EKSP ## Returnerer e opløftet til en potens af et angivet tal +FACT = FAKULTET ## Returnerer et tals fakultet +FACTDOUBLE = DOBBELT.FAKULTET ## Returnerer et tals dobbelte fakultet +FLOOR = AFRUND.GULV ## Runder et tal ned mod nul +GCD = STØRSTE.FÆLLES.DIVISOR ## Returnerer den største fælles divisor +INT = HELTAL ## Nedrunder et tal til det nærmeste heltal +LCM = MINDSTE.FÆLLES.MULTIPLUM ## Returnerer det mindste fælles multiplum +LN = LN ## Returnerer et tals naturlige logaritme +LOG = LOG ## Returnerer logaritmen for et tal på grundlag af et angivet grundtal +LOG10 = LOG10 ## Returnerer titalslogaritmen af et tal +MDETERM = MDETERM ## Returnerer determinanten for en matrix +MINVERSE = MINVERT ## Returnerer den inverse matrix for en matrix +MMULT = MPRODUKT ## Returnerer matrixproduktet af to matrixer +MOD = REST ## Returnerer restværdien fra division +MROUND = MAFRUND ## Returnerer et tal afrundet til det ønskede multiplum +MULTINOMIAL = MULTINOMIAL ## Returnerer et multinomialt talsæt +ODD = ULIGE ## Runder et tal op til nærmeste ulige heltal +PI = PI ## Returnerer værdien af pi +POWER = POTENS ## Returnerer resultatet af et tal opløftet til en potens +PRODUCT = PRODUKT ## Multiplicerer argumenterne +QUOTIENT = KVOTIENT ## Returnerer heltalsdelen ved division +RADIANS = RADIANER ## Konverterer grader til radianer +RAND = SLUMP ## Returnerer et tilfældigt tal mellem 0 og 1 +RANDBETWEEN = SLUMP.MELLEM ## Returnerer et tilfældigt tal mellem de tal, der angives +ROMAN = ROMERTAL ## Konverterer et arabertal til romertal som tekst +ROUND = AFRUND ## Afrunder et tal til et angivet antal decimaler +ROUNDDOWN = RUND.NED ## Runder et tal ned mod nul +ROUNDUP = RUND.OP ## Runder et tal op, væk fra 0 (nul) +SERIESSUM = SERIESUM ## Returnerer summen af en potensserie baseret på en formel +SIGN = FORTEGN ## Returnerer et tals fortegn +SIN = SIN ## Returnerer en given vinkels sinusværdi +SINH = SINH ## Returnerer den hyperbolske sinus af et tal +SQRT = KVROD ## Returnerer en positiv kvadratrod +SQRTPI = KVRODPI ## Returnerer kvadratroden af (tal * pi;) +SUBTOTAL = SUBTOTAL ## Returnerer en subtotal på en liste eller i en database +SUM = SUM ## Lægger argumenterne sammen +SUMIF = SUM.HVIS ## Lægger de celler sammen, der er specificeret af et givet kriterium. +SUMIFS = SUM.HVISER ## Lægger de celler i et område sammen, der opfylder flere kriterier. +SUMPRODUCT = SUMPRODUKT ## Returnerer summen af produkter af ens matrixkomponenter +SUMSQ = SUMKV ## Returnerer summen af argumenternes kvadrater +SUMX2MY2 = SUMX2MY2 ## Returnerer summen af differensen mellem kvadrater af ens værdier i to matrixer +SUMX2PY2 = SUMX2PY2 ## Returnerer summen af summen af kvadrater af tilsvarende værdier i to matrixer +SUMXMY2 = SUMXMY2 ## Returnerer summen af kvadrater af differenser mellem ens værdier i to matrixer +TAN = TAN ## Returnerer et tals tangens +TANH = TANH ## Returnerer et tals hyperbolske tangens +TRUNC = AFKORT ## Afkorter et tal til et heltal + + +## +## Statistical functions Statistiske funktioner +## +AVEDEV = MAD ## Returnerer den gennemsnitlige numeriske afvigelse fra stikprøvens middelværdi +AVERAGE = MIDDEL ## Returnerer middelværdien af argumenterne +AVERAGEA = MIDDELV ## Returnerer middelværdien af argumenterne og medtager tal, tekst og logiske værdier +AVERAGEIF = MIDDEL.HVIS ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder et givet kriterium, i et område +AVERAGEIFS = MIDDEL.HVISER ## Returnerer gennemsnittet (den aritmetiske middelværdi) af alle de celler, der opfylder flere kriterier. +BETADIST = BETAFORDELING ## Returnerer den kumulative betafordelingsfunktion +BETAINV = BETAINV ## Returnerer den inverse kumulative fordelingsfunktion for en angivet betafordeling +BINOMDIST = BINOMIALFORDELING ## Returnerer punktsandsynligheden for binomialfordelingen +CHIDIST = CHIFORDELING ## Returnerer fraktilsandsynligheden for en chi2-fordeling +CHIINV = CHIINV ## Returnerer den inverse fraktilsandsynlighed for en chi2-fordeling +CHITEST = CHITEST ## Foretager en test for uafhængighed +CONFIDENCE = KONFIDENSINTERVAL ## Returnerer et konfidensinterval for en population +CORREL = KORRELATION ## Returnerer korrelationskoefficienten mellem to datasæt +COUNT = TÆL ## Tæller antallet af tal på en liste med argumenter +COUNTA = TÆLV ## Tæller antallet af værdier på en liste med argumenter +COUNTBLANK = ANTAL.BLANKE ## Tæller antallet af tomme celler i et område +COUNTIF = TÆLHVIS ## Tæller antallet af celler, som opfylder de givne kriterier, i et område +COUNTIFS = TÆL.HVISER ## Tæller antallet af de celler, som opfylder flere kriterier, i et område +COVAR = KOVARIANS ## Beregner kovariansen mellem to stokastiske variabler +CRITBINOM = KRITBINOM ## Returnerer den mindste værdi for x, for hvilken det gælder, at fordelingsfunktionen er mindre end eller lig med kriterieværdien. +DEVSQ = SAK ## Returnerer summen af de kvadrerede afvigelser fra middelværdien +EXPONDIST = EKSPFORDELING ## Returnerer eksponentialfordelingen +FDIST = FFORDELING ## Returnerer fraktilsandsynligheden for F-fordelingen +FINV = FINV ## Returnerer den inverse fraktilsandsynlighed for F-fordelingen +FISHER = FISHER ## Returnerer Fisher-transformationen +FISHERINV = FISHERINV ## Returnerer den inverse Fisher-transformation +FORECAST = PROGNOSE ## Returnerer en prognoseværdi baseret på lineær tendens +FREQUENCY = FREKVENS ## Returnerer en frekvensfordeling i en søjlevektor +FTEST = FTEST ## Returnerer resultatet af en F-test til sammenligning af varians +GAMMADIST = GAMMAFORDELING ## Returnerer fordelingsfunktionen for gammafordelingen +GAMMAINV = GAMMAINV ## Returnerer den inverse fordelingsfunktion for gammafordelingen +GAMMALN = GAMMALN ## Returnerer den naturlige logaritme til gammafordelingen, G(x) +GEOMEAN = GEOMIDDELVÆRDI ## Returnerer det geometriske gennemsnit +GROWTH = FORØGELSE ## Returnerer værdier langs en eksponentiel tendens +HARMEAN = HARMIDDELVÆRDI ## Returnerer det harmoniske gennemsnit +HYPGEOMDIST = HYPGEOFORDELING ## Returnerer punktsandsynligheden i en hypergeometrisk fordeling +INTERCEPT = SKÆRING ## Returnerer afskæringsværdien på y-aksen i en lineær regression +KURT = TOPSTEJL ## Returnerer kurtosisværdien for en stokastisk variabel +LARGE = STOR ## Returnerer den k'te største værdi i et datasæt +LINEST = LINREGR ## Returnerer parameterestimaterne for en lineær tendens +LOGEST = LOGREGR ## Returnerer parameterestimaterne for en eksponentiel tendens +LOGINV = LOGINV ## Returnerer den inverse fordelingsfunktion for lognormalfordelingen +LOGNORMDIST = LOGNORMFORDELING ## Returnerer fordelingsfunktionen for lognormalfordelingen +MAX = MAKS ## Returnerer den maksimale værdi på en liste med argumenter. +MAXA = MAKSV ## Returnerer den maksimale værdi på en liste med argumenter og medtager tal, tekst og logiske værdier +MEDIAN = MEDIAN ## Returnerer medianen for de angivne tal +MIN = MIN ## Returnerer den mindste værdi på en liste med argumenter. +MINA = MINV ## Returnerer den mindste værdi på en liste med argumenter og medtager tal, tekst og logiske værdier +MODE = HYPPIGST ## Returnerer den hyppigste værdi i et datasæt +NEGBINOMDIST = NEGBINOMFORDELING ## Returnerer den negative binomialfordeling +NORMDIST = NORMFORDELING ## Returnerer fordelingsfunktionen for normalfordelingen +NORMINV = NORMINV ## Returnerer den inverse fordelingsfunktion for normalfordelingen +NORMSDIST = STANDARDNORMFORDELING ## Returnerer fordelingsfunktionen for standardnormalfordelingen +NORMSINV = STANDARDNORMINV ## Returnerer den inverse fordelingsfunktion for standardnormalfordelingen +PEARSON = PEARSON ## Returnerer Pearsons korrelationskoefficient +PERCENTILE = FRAKTIL ## Returnerer den k'te fraktil for datasættet +PERCENTRANK = PROCENTPLADS ## Returnerer den procentuelle rang for en given værdi i et datasæt +PERMUT = PERMUT ## Returnerer antallet af permutationer for et givet sæt objekter +POISSON = POISSON ## Returnerer fordelingsfunktionen for en Poisson-fordeling +PROB = SANDSYNLIGHED ## Returnerer intervalsandsynligheden +QUARTILE = KVARTIL ## Returnerer kvartilen i et givet datasæt +RANK = PLADS ## Returnerer rangen for et tal på en liste med tal +RSQ = FORKLARINGSGRAD ## Returnerer R2-værdien fra en simpel lineær regression +SKEW = SKÆVHED ## Returnerer skævheden for en stokastisk variabel +SLOPE = HÆLDNING ## Returnerer estimatet på hældningen fra en simpel lineær regression +SMALL = MINDSTE ## Returnerer den k'te mindste værdi i datasættet +STANDARDIZE = STANDARDISER ## Returnerer en standardiseret værdi +STDEV = STDAFV ## Estimerer standardafvigelsen på basis af en stikprøve +STDEVA = STDAFVV ## Beregner standardafvigelsen på basis af en prøve og medtager tal, tekst og logiske værdier +STDEVP = STDAFVP ## Beregner standardafvigelsen på basis af en hel population +STDEVPA = STDAFVPV ## Beregner standardafvigelsen på basis af en hel population og medtager tal, tekst og logiske værdier +STEYX = STFYX ## Returnerer standardafvigelsen for de estimerede y-værdier i den simple lineære regression +TDIST = TFORDELING ## Returnerer fordelingsfunktionen for Student's t-fordeling +TINV = TINV ## Returnerer den inverse fordelingsfunktion for Student's t-fordeling +TREND = TENDENS ## Returnerer værdi under antagelse af en lineær tendens +TRIMMEAN = TRIMMIDDELVÆRDI ## Returnerer den trimmede middelværdi for datasættet +TTEST = TTEST ## Returnerer den sandsynlighed, der er forbundet med Student's t-test +VAR = VARIANS ## Beregner variansen på basis af en prøve +VARA = VARIANSV ## Beregner variansen på basis af en prøve og medtager tal, tekst og logiske værdier +VARP = VARIANSP ## Beregner variansen på basis af hele populationen +VARPA = VARIANSPV ## Beregner variansen på basis af hele populationen og medtager tal, tekst og logiske værdier +WEIBULL = WEIBULL ## Returnerer fordelingsfunktionen for Weibull-fordelingen +ZTEST = ZTEST ## Returnerer sandsynlighedsværdien ved en en-sidet z-test + + +## +## Text functions Tekstfunktioner +## +ASC = ASC ## Ændrer engelske tegn i fuld bredde (dobbelt-byte) eller katakana i en tegnstreng til tegn i halv bredde (enkelt-byte) +BAHTTEXT = BAHTTEKST ## Konverterer et tal til tekst ved hjælp af valutaformatet ß (baht) +CHAR = TEGN ## Returnerer det tegn, der svarer til kodenummeret +CLEAN = RENS ## Fjerner alle tegn, der ikke kan udskrives, fra tekst +CODE = KODE ## Returnerer en numerisk kode for det første tegn i en tekststreng +CONCATENATE = SAMMENKÆDNING ## Sammenkæder adskillige tekstelementer til ét tekstelement +DOLLAR = KR ## Konverterer et tal til tekst ved hjælp af valutaformatet kr. (kroner) +EXACT = EKSAKT ## Kontrollerer, om to tekstværdier er identiske +FIND = FIND ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) +FINDB = FINDB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes mellem store og små bogstaver) +FIXED = FAST ## Formaterer et tal som tekst med et fast antal decimaler +JIS = JIS ## Ændrer engelske tegn i halv bredde (enkelt-byte) eller katakana i en tegnstreng til tegn i fuld bredde (dobbelt-byte) +LEFT = VENSTRE ## Returnerer tegnet længst til venstre i en tekstværdi +LEFTB = VENSTREB ## Returnerer tegnet længst til venstre i en tekstværdi +LEN = LÆNGDE ## Returnerer antallet af tegn i en tekststreng +LENB = LÆNGDEB ## Returnerer antallet af tegn i en tekststreng +LOWER = SMÅ.BOGSTAVER ## Konverterer tekst til små bogstaver +MID = MIDT ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition +MIDB = MIDTB ## Returnerer et bestemt antal tegn fra en tekststreng fra og med den angivne startposition +PHONETIC = FONETISK ## Uddrager de fonetiske (furigana) tegn fra en tekststreng +PROPER = STORT.FORBOGSTAV ## Konverterer første bogstav i hvert ord i teksten til stort bogstav +REPLACE = ERSTAT ## Erstatter tegn i tekst +REPLACEB = ERSTATB ## Erstatter tegn i tekst +REPT = GENTAG ## Gentager tekst et givet antal gange +RIGHT = HØJRE ## Returnerer tegnet længste til højre i en tekstværdi +RIGHTB = HØJREB ## Returnerer tegnet længste til højre i en tekstværdi +SEARCH = SØG ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) +SEARCHB = SØGB ## Søger efter en tekstværdi i en anden tekstværdi (der skelnes ikke mellem store og små bogstaver) +SUBSTITUTE = UDSKIFT ## Udskifter gammel tekst med ny tekst i en tekststreng +T = T ## Konverterer argumenterne til tekst +TEXT = TEKST ## Formaterer et tal og konverterer det til tekst +TRIM = FJERN.OVERFLØDIGE.BLANKE ## Fjerner mellemrum fra tekst +UPPER = STORE.BOGSTAVER ## Konverterer tekst til store bogstaver +VALUE = VÆRDI ## Konverterer et tekstargument til et tal diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/config new file mode 100644 index 00000000..aa0228e7 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #WERT! +REF = #BEZUG! +NAME = #NAME? +NUM = #ZAHL! +NA = #NV diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/functions new file mode 100644 index 00000000..3147f9c8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/de/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Add-In- und Automatisierungsfunktionen +## +GETPIVOTDATA = PIVOTDATENZUORDNEN ## In einem PivotTable-Bericht gespeicherte Daten werden zurückgegeben. + + +## +## Cube functions Cubefunktionen +## +CUBEKPIMEMBER = CUBEKPIELEMENT ## Gibt Name, Eigenschaft und Measure eines Key Performance Indicators (KPI) zurück und zeigt den Namen und die Eigenschaft in der Zelle an. Ein KPI ist ein quantifizierbares Maß, wie z. B. der monatliche Bruttogewinn oder die vierteljährliche Mitarbeiterfluktuation, mit dessen Hilfe das Leistungsverhalten eines Unternehmens überwacht werden kann. +CUBEMEMBER = CUBEELEMENT ## Gibt ein Element oder ein Tuple in einer Cubehierarchie zurück. Wird verwendet, um zu überprüfen, ob das Element oder Tuple im Cube vorhanden ist. +CUBEMEMBERPROPERTY = CUBEELEMENTEIGENSCHAFT ## Gibt den Wert einer Elementeigenschaft im Cube zurück. Wird verwendet, um zu überprüfen, ob ein Elementname im Cube vorhanden ist, und um die für dieses Element angegebene Eigenschaft zurückzugeben. +CUBERANKEDMEMBER = CUBERANGELEMENT ## Gibt das n-te oder n-rangige Element in einer Menge zurück. Wird verwendet, um mindestens ein Element in einer Menge zurückzugeben, wie z. B. bester Vertriebsmitarbeiter oder 10 beste Kursteilnehmer. +CUBESET = CUBEMENGE ## Definiert eine berechnete Menge Elemente oder Tuples durch Senden eines Mengenausdrucks an den Cube auf dem Server, der die Menge erstellt und an Microsoft Office Excel zurückgibt. +CUBESETCOUNT = CUBEMENGENANZAHL ## Gibt die Anzahl der Elemente in einer Menge zurück. +CUBEVALUE = CUBEWERT ## Gibt einen Aggregatwert aus einem Cube zurück. + + +## +## Database functions Datenbankfunktionen +## +DAVERAGE = DBMITTELWERT ## Gibt den Mittelwert der ausgewählten Datenbankeinträge zurück +DCOUNT = DBANZAHL ## Zählt die Zellen mit Zahlen in einer Datenbank +DCOUNTA = DBANZAHL2 ## Zählt nicht leere Zellen in einer Datenbank +DGET = DBAUSZUG ## Extrahiert aus einer Datenbank einen einzelnen Datensatz, der den angegebenen Kriterien entspricht +DMAX = DBMAX ## Gibt den größten Wert aus ausgewählten Datenbankeinträgen zurück +DMIN = DBMIN ## Gibt den kleinsten Wert aus ausgewählten Datenbankeinträgen zurück +DPRODUCT = DBPRODUKT ## Multipliziert die Werte in einem bestimmten Feld mit Datensätzen, die den Kriterien in einer Datenbank entsprechen +DSTDEV = DBSTDABW ## Schätzt die Standardabweichung auf der Grundlage einer Stichprobe aus ausgewählten Datenbankeinträgen +DSTDEVP = DBSTDABWN ## Berechnet die Standardabweichung auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge +DSUM = DBSUMME ## Addiert die Zahlen in der Feldspalte mit Datensätzen in der Datenbank, die den Kriterien entsprechen +DVAR = DBVARIANZ ## Schätzt die Varianz auf der Grundlage ausgewählter Datenbankeinträge +DVARP = DBVARIANZEN ## Berechnet die Varianz auf der Grundlage der Grundgesamtheit ausgewählter Datenbankeinträge + + +## +## Date and time functions Datums- und Zeitfunktionen +## +DATE = DATUM ## Gibt die fortlaufende Zahl eines bestimmten Datums zurück +DATEVALUE = DATWERT ## Wandelt ein Datum in Form von Text in eine fortlaufende Zahl um +DAY = TAG ## Wandelt eine fortlaufende Zahl in den Tag des Monats um +DAYS360 = TAGE360 ## Berechnet die Anzahl der Tage zwischen zwei Datumsangaben ausgehend von einem Jahr, das 360 Tage hat +EDATE = EDATUM ## Gibt die fortlaufende Zahl des Datums zurück, bei dem es sich um die angegebene Anzahl von Monaten vor oder nach dem Anfangstermin handelt +EOMONTH = MONATSENDE ## Gibt die fortlaufende Zahl des letzten Tags des Monats vor oder nach einer festgelegten Anzahl von Monaten zurück +HOUR = STUNDE ## Wandelt eine fortlaufende Zahl in eine Stunde um +MINUTE = MINUTE ## Wandelt eine fortlaufende Zahl in eine Minute um +MONTH = MONAT ## Wandelt eine fortlaufende Zahl in einen Monat um +NETWORKDAYS = NETTOARBEITSTAGE ## Gibt die Anzahl von ganzen Arbeitstagen zwischen zwei Datumswerten zurück +NOW = JETZT ## Gibt die fortlaufende Zahl des aktuellen Datums und der aktuellen Uhrzeit zurück +SECOND = SEKUNDE ## Wandelt eine fortlaufende Zahl in eine Sekunde um +TIME = ZEIT ## Gibt die fortlaufende Zahl einer bestimmten Uhrzeit zurück +TIMEVALUE = ZEITWERT ## Wandelt eine Uhrzeit in Form von Text in eine fortlaufende Zahl um +TODAY = HEUTE ## Gibt die fortlaufende Zahl des heutigen Datums zurück +WEEKDAY = WOCHENTAG ## Wandelt eine fortlaufende Zahl in den Wochentag um +WEEKNUM = KALENDERWOCHE ## Wandelt eine fortlaufende Zahl in eine Zahl um, die angibt, in welche Woche eines Jahres das angegebene Datum fällt +WORKDAY = ARBEITSTAG ## Gibt die fortlaufende Zahl des Datums vor oder nach einer bestimmten Anzahl von Arbeitstagen zurück +YEAR = JAHR ## Wandelt eine fortlaufende Zahl in ein Jahr um +YEARFRAC = BRTEILJAHRE ## Gibt die Anzahl der ganzen Tage zwischen Ausgangsdatum und Enddatum in Bruchteilen von Jahren zurück + + +## +## Engineering functions Konstruktionsfunktionen +## +BESSELI = BESSELI ## Gibt die geänderte Besselfunktion In(x) zurück +BESSELJ = BESSELJ ## Gibt die Besselfunktion Jn(x) zurück +BESSELK = BESSELK ## Gibt die geänderte Besselfunktion Kn(x) zurück +BESSELY = BESSELY ## Gibt die Besselfunktion Yn(x) zurück +BIN2DEC = BININDEZ ## Wandelt eine binäre Zahl (Dualzahl) in eine dezimale Zahl um +BIN2HEX = BININHEX ## Wandelt eine binäre Zahl (Dualzahl) in eine hexadezimale Zahl um +BIN2OCT = BININOKT ## Wandelt eine binäre Zahl (Dualzahl) in eine oktale Zahl um +COMPLEX = KOMPLEXE ## Wandelt den Real- und Imaginärteil in eine komplexe Zahl um +CONVERT = UMWANDELN ## Wandelt eine Zahl von einem Maßsystem in ein anderes um +DEC2BIN = DEZINBIN ## Wandelt eine dezimale Zahl in eine binäre Zahl (Dualzahl) um +DEC2HEX = DEZINHEX ## Wandelt eine dezimale Zahl in eine hexadezimale Zahl um +DEC2OCT = DEZINOKT ## Wandelt eine dezimale Zahl in eine oktale Zahl um +DELTA = DELTA ## Überprüft, ob zwei Werte gleich sind +ERF = GAUSSFEHLER ## Gibt die Gauss'sche Fehlerfunktion zurück +ERFC = GAUSSFKOMPL ## Gibt das Komplement zur Gauss'schen Fehlerfunktion zurück +GESTEP = GGANZZAHL ## Überprüft, ob eine Zahl größer als ein gegebener Schwellenwert ist +HEX2BIN = HEXINBIN ## Wandelt eine hexadezimale Zahl in eine Binärzahl um +HEX2DEC = HEXINDEZ ## Wandelt eine hexadezimale Zahl in eine dezimale Zahl um +HEX2OCT = HEXINOKT ## Wandelt eine hexadezimale Zahl in eine Oktalzahl um +IMABS = IMABS ## Gibt den Absolutbetrag (Modulo) einer komplexen Zahl zurück +IMAGINARY = IMAGINÄRTEIL ## Gibt den Imaginärteil einer komplexen Zahl zurück +IMARGUMENT = IMARGUMENT ## Gibt das Argument Theta zurück, einen Winkel, der als Bogenmaß ausgedrückt wird +IMCONJUGATE = IMKONJUGIERTE ## Gibt die konjugierte komplexe Zahl zu einer komplexen Zahl zurück +IMCOS = IMCOS ## Gibt den Kosinus einer komplexen Zahl zurück +IMDIV = IMDIV ## Gibt den Quotienten zweier komplexer Zahlen zurück +IMEXP = IMEXP ## Gibt die algebraische Form einer in exponentieller Schreibweise vorliegenden komplexen Zahl zurück +IMLN = IMLN ## Gibt den natürlichen Logarithmus einer komplexen Zahl zurück +IMLOG10 = IMLOG10 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 10 zurück +IMLOG2 = IMLOG2 ## Gibt den Logarithmus einer komplexen Zahl zur Basis 2 zurück +IMPOWER = IMAPOTENZ ## Potenziert eine komplexe Zahl mit einer ganzen Zahl +IMPRODUCT = IMPRODUKT ## Gibt das Produkt von komplexen Zahlen zurück +IMREAL = IMREALTEIL ## Gibt den Realteil einer komplexen Zahl zurück +IMSIN = IMSIN ## Gibt den Sinus einer komplexen Zahl zurück +IMSQRT = IMWURZEL ## Gibt die Quadratwurzel einer komplexen Zahl zurück +IMSUB = IMSUB ## Gibt die Differenz zwischen zwei komplexen Zahlen zurück +IMSUM = IMSUMME ## Gibt die Summe von komplexen Zahlen zurück +OCT2BIN = OKTINBIN ## Wandelt eine oktale Zahl in eine binäre Zahl (Dualzahl) um +OCT2DEC = OKTINDEZ ## Wandelt eine oktale Zahl in eine dezimale Zahl um +OCT2HEX = OKTINHEX ## Wandelt eine oktale Zahl in eine hexadezimale Zahl um + + +## +## Financial functions Finanzmathematische Funktionen +## +ACCRINT = AUFGELZINS ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers mit periodischen Zinszahlungen zurück +ACCRINTM = AUFGELZINSF ## Gibt die aufgelaufenen Zinsen (Stückzinsen) eines Wertpapiers zurück, die bei Fälligkeit ausgezahlt werden +AMORDEGRC = AMORDEGRK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume mithilfe eines Abschreibungskoeffizienten zurück +AMORLINC = AMORLINEARK ## Gibt die Abschreibung für die einzelnen Abschreibungszeiträume zurück +COUPDAYBS = ZINSTERMTAGVA ## Gibt die Anzahl der Tage vom Anfang des Zinstermins bis zum Abrechnungstermin zurück +COUPDAYS = ZINSTERMTAGE ## Gibt die Anzahl der Tage der Zinsperiode zurück, die den Abrechnungstermin einschließt +COUPDAYSNC = ZINSTERMTAGNZ ## Gibt die Anzahl der Tage vom Abrechnungstermin bis zum nächsten Zinstermin zurück +COUPNCD = ZINSTERMNZ ## Gibt das Datum des ersten Zinstermins nach dem Abrechnungstermin zurück +COUPNUM = ZINSTERMZAHL ## Gibt die Anzahl der Zinstermine zwischen Abrechnungs- und Fälligkeitsdatum zurück +COUPPCD = ZINSTERMVZ ## Gibt das Datum des letzten Zinstermins vor dem Abrechnungstermin zurück +CUMIPMT = KUMZINSZ ## Berechnet die kumulierten Zinsen, die zwischen zwei Perioden zu zahlen sind +CUMPRINC = KUMKAPITAL ## Berechnet die aufgelaufene Tilgung eines Darlehens, die zwischen zwei Perioden zu zahlen ist +DB = GDA2 ## Gibt die geometrisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück +DDB = GDA ## Gibt die Abschreibung eines Anlageguts für einen angegebenen Zeitraum unter Verwendung der degressiven Doppelraten-Abschreibung oder eines anderen von Ihnen angegebenen Abschreibungsverfahrens zurück +DISC = DISAGIO ## Gibt den in Prozent ausgedrückten Abzinsungssatz eines Wertpapiers zurück +DOLLARDE = NOTIERUNGDEZ ## Wandelt eine Notierung, die als Dezimalbruch ausgedrückt wurde, in eine Dezimalzahl um +DOLLARFR = NOTIERUNGBRU ## Wandelt eine Notierung, die als Dezimalzahl ausgedrückt wurde, in einen Dezimalbruch um +DURATION = DURATION ## Gibt die jährliche Duration eines Wertpapiers mit periodischen Zinszahlungen zurück +EFFECT = EFFEKTIV ## Gibt die jährliche Effektivverzinsung zurück +FV = ZW ## Gibt den zukünftigen Wert (Endwert) einer Investition zurück +FVSCHEDULE = ZW2 ## Gibt den aufgezinsten Wert des Anfangskapitals für eine Reihe periodisch unterschiedlicher Zinssätze zurück +INTRATE = ZINSSATZ ## Gibt den Zinssatz eines voll investierten Wertpapiers zurück +IPMT = ZINSZ ## Gibt die Zinszahlung einer Investition für die angegebene Periode zurück +IRR = IKV ## Gibt den internen Zinsfuß einer Investition ohne Finanzierungskosten oder Reinvestitionsgewinne zurück +ISPMT = ISPMT ## Berechnet die während eines bestimmten Zeitraums für eine Investition gezahlten Zinsen +MDURATION = MDURATION ## Gibt die geänderte Dauer für ein Wertpapier mit einem angenommenen Nennwert von 100 € zurück +MIRR = QIKV ## Gibt den internen Zinsfuß zurück, wobei positive und negative Zahlungen zu unterschiedlichen Sätzen finanziert werden +NOMINAL = NOMINAL ## Gibt die jährliche Nominalverzinsung zurück +NPER = ZZR ## Gibt die Anzahl der Zahlungsperioden einer Investition zurück +NPV = NBW ## Gibt den Nettobarwert einer Investition auf Basis periodisch anfallender Zahlungen und eines Abzinsungsfaktors zurück +ODDFPRICE = UNREGER.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück +ODDFYIELD = UNREGER.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen ersten Zinstermin zurück +ODDLPRICE = UNREGLE.KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück +ODDLYIELD = UNREGLE.REND ## Gibt die Rendite eines Wertpapiers mit einem unregelmäßigen letzten Zinstermin zurück +PMT = RMZ ## Gibt die periodische Zahlung für eine Annuität zurück +PPMT = KAPZ ## Gibt die Kapitalrückzahlung einer Investition für eine angegebene Periode zurück +PRICE = KURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das periodisch Zinsen auszahlt +PRICEDISC = KURSDISAGIO ## Gibt den Kurs pro 100 € Nennwert eines unverzinslichen Wertpapiers zurück +PRICEMAT = KURSFÄLLIG ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt +PV = BW ## Gibt den Barwert einer Investition zurück +RATE = ZINS ## Gibt den Zinssatz pro Zeitraum einer Annuität zurück +RECEIVED = AUSZAHLUNG ## Gibt den Auszahlungsbetrag eines voll investierten Wertpapiers am Fälligkeitstermin zurück +SLN = LIA ## Gibt die lineare Abschreibung eines Wirtschaftsguts pro Periode zurück +SYD = DIA ## Gibt die arithmetisch-degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode zurück +TBILLEQ = TBILLÄQUIV ## Gibt die Rendite für ein Wertpapier zurück +TBILLPRICE = TBILLKURS ## Gibt den Kurs pro 100 € Nennwert eines Wertpapiers zurück +TBILLYIELD = TBILLRENDITE ## Gibt die Rendite für ein Wertpapier zurück +VDB = VDB ## Gibt die degressive Abschreibung eines Wirtschaftsguts für eine bestimmte Periode oder Teilperiode zurück +XIRR = XINTZINSFUSS ## Gibt den internen Zinsfuß einer Reihe nicht periodisch anfallender Zahlungen zurück +XNPV = XKAPITALWERT ## Gibt den Nettobarwert (Kapitalwert) einer Reihe nicht periodisch anfallender Zahlungen zurück +YIELD = RENDITE ## Gibt die Rendite eines Wertpapiers zurück, das periodisch Zinsen auszahlt +YIELDDISC = RENDITEDIS ## Gibt die jährliche Rendite eines unverzinslichen Wertpapiers zurück +YIELDMAT = RENDITEFÄLL ## Gibt die jährliche Rendite eines Wertpapiers zurück, das Zinsen am Fälligkeitsdatum auszahlt + + +## +## Information functions Informationsfunktionen +## +CELL = ZELLE ## Gibt Informationen zu Formatierung, Position oder Inhalt einer Zelle zurück +ERROR.TYPE = FEHLER.TYP ## Gibt eine Zahl zurück, die einem Fehlertyp entspricht +INFO = INFO ## Gibt Informationen zur aktuellen Betriebssystemumgebung zurück +ISBLANK = ISTLEER ## Gibt WAHR zurück, wenn der Wert leer ist +ISERR = ISTFEHL ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert außer #N/V ist +ISERROR = ISTFEHLER ## Gibt WAHR zurück, wenn der Wert ein beliebiger Fehlerwert ist +ISEVEN = ISTGERADE ## Gibt WAHR zurück, wenn es sich um eine gerade Zahl handelt +ISLOGICAL = ISTLOG ## Gibt WAHR zurück, wenn der Wert ein Wahrheitswert ist +ISNA = ISTNV ## Gibt WAHR zurück, wenn der Wert der Fehlerwert #N/V ist +ISNONTEXT = ISTKTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das keinen Text enthält +ISNUMBER = ISTZAHL ## Gibt WAHR zurück, wenn der Wert eine Zahl ist +ISODD = ISTUNGERADE ## Gibt WAHR zurück, wenn es sich um eine ungerade Zahl handelt +ISREF = ISTBEZUG ## Gibt WAHR zurück, wenn der Wert ein Bezug ist +ISTEXT = ISTTEXT ## Gibt WAHR zurück, wenn der Wert ein Element ist, das Text enthält +N = N ## Gibt den in eine Zahl umgewandelten Wert zurück +NA = NV ## Gibt den Fehlerwert #NV zurück +TYPE = TYP ## Gibt eine Zahl zurück, die den Datentyp des angegebenen Werts anzeigt + + +## +## Logical functions Logische Funktionen +## +AND = UND ## Gibt WAHR zurück, wenn alle zugehörigen Argumente WAHR sind +FALSE = FALSCH ## Gibt den Wahrheitswert FALSCH zurück +IF = WENN ## Gibt einen logischen Test zum Ausführen an +IFERROR = WENNFEHLER ## Gibt einen von Ihnen festgelegten Wert zurück, wenn die Auswertung der Formel zu einem Fehler führt; andernfalls wird das Ergebnis der Formel zurückgegeben +NOT = NICHT ## Kehrt den Wahrheitswert der zugehörigen Argumente um +OR = ODER ## Gibt WAHR zurück, wenn ein Argument WAHR ist +TRUE = WAHR ## Gibt den Wahrheitswert WAHR zurück + + +## +## Lookup and reference functions Nachschlage- und Verweisfunktionen +## +ADDRESS = ADRESSE ## Gibt einen Bezug auf eine einzelne Zelle in einem Tabellenblatt als Text zurück +AREAS = BEREICHE ## Gibt die Anzahl der innerhalb eines Bezugs aufgeführten Bereiche zurück +CHOOSE = WAHL ## Wählt einen Wert aus eine Liste mit Werten aus +COLUMN = SPALTE ## Gibt die Spaltennummer eines Bezugs zurück +COLUMNS = SPALTEN ## Gibt die Anzahl der Spalten in einem Bezug zurück +HLOOKUP = HVERWEIS ## Sucht in der obersten Zeile einer Matrix und gibt den Wert der angegebenen Zelle zurück +HYPERLINK = HYPERLINK ## Erstellt eine Verknüpfung, über die ein auf einem Netzwerkserver, in einem Intranet oder im Internet gespeichertes Dokument geöffnet wird +INDEX = INDEX ## Verwendet einen Index, um einen Wert aus einem Bezug oder einer Matrix auszuwählen +INDIRECT = INDIREKT ## Gibt einen Bezug zurück, der von einem Textwert angegeben wird +LOOKUP = LOOKUP ## Sucht Werte in einem Vektor oder einer Matrix +MATCH = VERGLEICH ## Sucht Werte in einem Bezug oder einer Matrix +OFFSET = BEREICH.VERSCHIEBEN ## Gibt einen Bezugoffset aus einem gegebenen Bezug zurück +ROW = ZEILE ## Gibt die Zeilennummer eines Bezugs zurück +ROWS = ZEILEN ## Gibt die Anzahl der Zeilen in einem Bezug zurück +RTD = RTD ## Ruft Echtzeitdaten von einem Programm ab, das die COM-Automatisierung (Automatisierung: Ein Verfahren, bei dem aus einer Anwendung oder einem Entwicklungstool heraus mit den Objekten einer anderen Anwendung gearbeitet wird. Die früher als OLE-Automatisierung bezeichnete Automatisierung ist ein Industriestandard und eine Funktion von COM (Component Object Model).) unterstützt +TRANSPOSE = MTRANS ## Gibt die transponierte Matrix einer Matrix zurück +VLOOKUP = SVERWEIS ## Sucht in der ersten Spalte einer Matrix und arbeitet sich durch die Zeile, um den Wert einer Zelle zurückzugeben + + +## +## Math and trigonometry functions Mathematische und trigonometrische Funktionen +## +ABS = ABS ## Gibt den Absolutwert einer Zahl zurück +ACOS = ARCCOS ## Gibt den Arkuskosinus einer Zahl zurück +ACOSH = ARCCOSHYP ## Gibt den umgekehrten hyperbolischen Kosinus einer Zahl zurück +ASIN = ARCSIN ## Gibt den Arkussinus einer Zahl zurück +ASINH = ARCSINHYP ## Gibt den umgekehrten hyperbolischen Sinus einer Zahl zurück +ATAN = ARCTAN ## Gibt den Arkustangens einer Zahl zurück +ATAN2 = ARCTAN2 ## Gibt den Arkustangens einer x- und einer y-Koordinate zurück +ATANH = ARCTANHYP ## Gibt den umgekehrten hyperbolischen Tangens einer Zahl zurück +CEILING = OBERGRENZE ## Rundet eine Zahl auf die nächste ganze Zahl oder das nächste Vielfache von Schritt +COMBIN = KOMBINATIONEN ## Gibt die Anzahl der Kombinationen für eine bestimmte Anzahl von Objekten zurück +COS = COS ## Gibt den Kosinus einer Zahl zurück +COSH = COSHYP ## Gibt den hyperbolischen Kosinus einer Zahl zurück +DEGREES = GRAD ## Wandelt Bogenmaß (Radiant) in Grad um +EVEN = GERADE ## Rundet eine Zahl auf die nächste gerade ganze Zahl auf +EXP = EXP ## Potenziert die Basis e mit der als Argument angegebenen Zahl +FACT = FAKULTÄT ## Gibt die Fakultät einer Zahl zurück +FACTDOUBLE = ZWEIFAKULTÄT ## Gibt die Fakultät zu Zahl mit Schrittlänge 2 zurück +FLOOR = UNTERGRENZE ## Rundet die Zahl auf Anzahl_Stellen ab +GCD = GGT ## Gibt den größten gemeinsamen Teiler zurück +INT = GANZZAHL ## Rundet eine Zahl auf die nächstkleinere ganze Zahl ab +LCM = KGV ## Gibt das kleinste gemeinsame Vielfache zurück +LN = LN ## Gibt den natürlichen Logarithmus einer Zahl zurück +LOG = LOG ## Gibt den Logarithmus einer Zahl zu der angegebenen Basis zurück +LOG10 = LOG10 ## Gibt den Logarithmus einer Zahl zur Basis 10 zurück +MDETERM = MDET ## Gibt die Determinante einer Matrix zurück +MINVERSE = MINV ## Gibt die inverse Matrix einer Matrix zurück +MMULT = MMULT ## Gibt das Produkt zweier Matrizen zurück +MOD = REST ## Gibt den Rest einer Division zurück +MROUND = VRUNDEN ## Gibt eine auf das gewünschte Vielfache gerundete Zahl zurück +MULTINOMIAL = POLYNOMIAL ## Gibt den Polynomialkoeffizienten einer Gruppe von Zahlen zurück +ODD = UNGERADE ## Rundet eine Zahl auf die nächste ungerade ganze Zahl auf +PI = PI ## Gibt den Wert Pi zurück +POWER = POTENZ ## Gibt als Ergebnis eine potenzierte Zahl zurück +PRODUCT = PRODUKT ## Multipliziert die zugehörigen Argumente +QUOTIENT = QUOTIENT ## Gibt den ganzzahligen Anteil einer Division zurück +RADIANS = BOGENMASS ## Wandelt Grad in Bogenmaß (Radiant) um +RAND = ZUFALLSZAHL ## Gibt eine Zufallszahl zwischen 0 und 1 zurück +RANDBETWEEN = ZUFALLSBEREICH ## Gibt eine Zufallszahl aus dem festgelegten Bereich zurück +ROMAN = RÖMISCH ## Wandelt eine arabische Zahl in eine römische Zahl als Text um +ROUND = RUNDEN ## Rundet eine Zahl auf eine bestimmte Anzahl von Dezimalstellen +ROUNDDOWN = ABRUNDEN ## Rundet die Zahl auf Anzahl_Stellen ab +ROUNDUP = AUFRUNDEN ## Rundet die Zahl auf Anzahl_Stellen auf +SERIESSUM = POTENZREIHE ## Gibt die Summe von Potenzen (zur Berechnung von Potenzreihen und dichotomen Wahrscheinlichkeiten) zurück +SIGN = VORZEICHEN ## Gibt das Vorzeichen einer Zahl zurück +SIN = SIN ## Gibt den Sinus einer Zahl zurück +SINH = SINHYP ## Gibt den hyperbolischen Sinus einer Zahl zurück +SQRT = WURZEL ## Gibt die Quadratwurzel einer Zahl zurück +SQRTPI = WURZELPI ## Gibt die Wurzel aus der mit Pi (pi) multiplizierten Zahl zurück +SUBTOTAL = TEILERGEBNIS ## Gibt ein Teilergebnis in einer Liste oder Datenbank zurück +SUM = SUMME ## Addiert die zugehörigen Argumente +SUMIF = SUMMEWENN ## Addiert Zahlen, die mit den Suchkriterien übereinstimmen +SUMIFS = SUMMEWENNS ## Die Zellen, die mehrere Kriterien erfüllen, werden in einem Bereich hinzugefügt +SUMPRODUCT = SUMMENPRODUKT ## Gibt die Summe der Produkte zusammengehöriger Matrixkomponenten zurück +SUMSQ = QUADRATESUMME ## Gibt die Summe der quadrierten Argumente zurück +SUMX2MY2 = SUMMEX2MY2 ## Gibt die Summe der Differenzen der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück +SUMX2PY2 = SUMMEX2PY2 ## Gibt die Summe der Quadrate für zusammengehörige Komponenten zweier Matrizen zurück +SUMXMY2 = SUMMEXMY2 ## Gibt die Summe der quadrierten Differenzen für zusammengehörige Komponenten zweier Matrizen zurück +TAN = TAN ## Gibt den Tangens einer Zahl zurück +TANH = TANHYP ## Gibt den hyperbolischen Tangens einer Zahl zurück +TRUNC = KÜRZEN ## Schneidet die Kommastellen einer Zahl ab und gibt als Ergebnis eine ganze Zahl zurück + + +## +## Statistical functions Statistische Funktionen +## +AVEDEV = MITTELABW ## Gibt die durchschnittliche absolute Abweichung einer Reihe von Merkmalsausprägungen und ihrem Mittelwert zurück +AVERAGE = MITTELWERT ## Gibt den Mittelwert der zugehörigen Argumente zurück +AVERAGEA = MITTELWERTA ## Gibt den Mittelwert der zugehörigen Argumente, die Zahlen, Text und Wahrheitswerte enthalten, zurück +AVERAGEIF = MITTELWERTWENN ## Der Durchschnittswert (arithmetisches Mittel) für alle Zellen in einem Bereich, die einem angegebenen Kriterium entsprechen, wird zurückgegeben +AVERAGEIFS = MITTELWERTWENNS ## Gibt den Durchschnittswert (arithmetisches Mittel) aller Zellen zurück, die mehreren Kriterien entsprechen +BETADIST = BETAVERT ## Gibt die Werte der kumulierten Betaverteilungsfunktion zurück +BETAINV = BETAINV ## Gibt das Quantil der angegebenen Betaverteilung zurück +BINOMDIST = BINOMVERT ## Gibt Wahrscheinlichkeiten einer binomialverteilten Zufallsvariablen zurück +CHIDIST = CHIVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer Chi-Quadrat-verteilten Zufallsgröße zurück +CHIINV = CHIINV ## Gibt Quantile der Verteilungsfunktion (1-Alpha) der Chi-Quadrat-Verteilung zurück +CHITEST = CHITEST ## Gibt die Teststatistik eines Unabhängigkeitstests zurück +CONFIDENCE = KONFIDENZ ## Ermöglicht die Berechnung des 1-Alpha Konfidenzintervalls für den Erwartungswert einer Zufallsvariablen +CORREL = KORREL ## Gibt den Korrelationskoeffizienten zweier Reihen von Merkmalsausprägungen zurück +COUNT = ANZAHL ## Gibt die Anzahl der Zahlen in der Liste mit Argumenten an +COUNTA = ANZAHL2 ## Gibt die Anzahl der Werte in der Liste mit Argumenten an +COUNTBLANK = ANZAHLLEEREZELLEN ## Gibt die Anzahl der leeren Zellen in einem Bereich an +COUNTIF = ZÄHLENWENN ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit den Suchkriterien übereinstimmen +COUNTIFS = ZÄHLENWENNS ## Gibt die Anzahl der Zellen in einem Bereich an, deren Inhalte mit mehreren Suchkriterien übereinstimmen +COVAR = KOVAR ## Gibt die Kovarianz zurück, den Mittelwert der für alle Datenpunktpaare gebildeten Produkte der Abweichungen +CRITBINOM = KRITBINOM ## Gibt den kleinsten Wert zurück, für den die kumulierten Wahrscheinlichkeiten der Binomialverteilung kleiner oder gleich einer Grenzwahrscheinlichkeit sind +DEVSQ = SUMQUADABW ## Gibt die Summe der quadrierten Abweichungen der Datenpunkte von ihrem Stichprobenmittelwert zurück +EXPONDIST = EXPONVERT ## Gibt Wahrscheinlichkeiten einer exponential verteilten Zufallsvariablen zurück +FDIST = FVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer F-verteilten Zufallsvariablen zurück +FINV = FINV ## Gibt Quantile der F-Verteilung zurück +FISHER = FISHER ## Gibt die Fisher-Transformation zurück +FISHERINV = FISHERINV ## Gibt die Umkehrung der Fisher-Transformation zurück +FORECAST = PROGNOSE ## Gibt einen Wert zurück, der sich aus einem linearen Trend ergibt +FREQUENCY = HÄUFIGKEIT ## Gibt eine Häufigkeitsverteilung als vertikale Matrix zurück +FTEST = FTEST ## Gibt die Teststatistik eines F-Tests zurück +GAMMADIST = GAMMAVERT ## Gibt Wahrscheinlichkeiten einer gammaverteilten Zufallsvariablen zurück +GAMMAINV = GAMMAINV ## Gibt Quantile der Gammaverteilung zurück +GAMMALN = GAMMALN ## Gibt den natürlichen Logarithmus der Gammafunktion zurück, Γ(x) +GEOMEAN = GEOMITTEL ## Gibt das geometrische Mittel zurück +GROWTH = VARIATION ## Gibt Werte zurück, die sich aus einem exponentiellen Trend ergeben +HARMEAN = HARMITTEL ## Gibt das harmonische Mittel zurück +HYPGEOMDIST = HYPGEOMVERT ## Gibt Wahrscheinlichkeiten einer hypergeometrisch-verteilten Zufallsvariablen zurück +INTERCEPT = ACHSENABSCHNITT ## Gibt den Schnittpunkt der Regressionsgeraden zurück +KURT = KURT ## Gibt die Kurtosis (Exzess) einer Datengruppe zurück +LARGE = KGRÖSSTE ## Gibt den k-größten Wert einer Datengruppe zurück +LINEST = RGP ## Gibt die Parameter eines linearen Trends zurück +LOGEST = RKP ## Gibt die Parameter eines exponentiellen Trends zurück +LOGINV = LOGINV ## Gibt Quantile der Lognormalverteilung zurück +LOGNORMDIST = LOGNORMVERT ## Gibt Werte der Verteilungsfunktion einer lognormalverteilten Zufallsvariablen zurück +MAX = MAX ## Gibt den Maximalwert einer Liste mit Argumenten zurück +MAXA = MAXA ## Gibt den Maximalwert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten +MEDIAN = MEDIAN ## Gibt den Median der angegebenen Zahlen zurück +MIN = MIN ## Gibt den Minimalwert einer Liste mit Argumenten zurück +MINA = MINA ## Gibt den kleinsten Wert einer Liste mit Argumenten zurück, die Zahlen, Text und Wahrheitswerte enthalten +MODE = MODALWERT ## Gibt den am häufigsten vorkommenden Wert in einer Datengruppe zurück +NEGBINOMDIST = NEGBINOMVERT ## Gibt Wahrscheinlichkeiten einer negativen, binominal verteilten Zufallsvariablen zurück +NORMDIST = NORMVERT ## Gibt Wahrscheinlichkeiten einer normal verteilten Zufallsvariablen zurück +NORMINV = NORMINV ## Gibt Quantile der Normalverteilung zurück +NORMSDIST = STANDNORMVERT ## Gibt Werte der Verteilungsfunktion einer standardnormalverteilten Zufallsvariablen zurück +NORMSINV = STANDNORMINV ## Gibt Quantile der Standardnormalverteilung zurück +PEARSON = PEARSON ## Gibt den Pearsonschen Korrelationskoeffizienten zurück +PERCENTILE = QUANTIL ## Gibt das Alpha-Quantil einer Gruppe von Daten zurück +PERCENTRANK = QUANTILSRANG ## Gibt den prozentualen Rang (Alpha) eines Werts in einer Datengruppe zurück +PERMUT = VARIATIONEN ## Gibt die Anzahl der Möglichkeiten zurück, um k Elemente aus einer Menge von n Elementen ohne Zurücklegen zu ziehen +POISSON = POISSON ## Gibt Wahrscheinlichkeiten einer poissonverteilten Zufallsvariablen zurück +PROB = WAHRSCHBEREICH ## Gibt die Wahrscheinlichkeit für ein von zwei Werten eingeschlossenes Intervall zurück +QUARTILE = QUARTILE ## Gibt die Quartile der Datengruppe zurück +RANK = RANG ## Gibt den Rang zurück, den eine Zahl innerhalb einer Liste von Zahlen einnimmt +RSQ = BESTIMMTHEITSMASS ## Gibt das Quadrat des Pearsonschen Korrelationskoeffizienten zurück +SKEW = SCHIEFE ## Gibt die Schiefe einer Verteilung zurück +SLOPE = STEIGUNG ## Gibt die Steigung der Regressionsgeraden zurück +SMALL = KKLEINSTE ## Gibt den k-kleinsten Wert einer Datengruppe zurück +STANDARDIZE = STANDARDISIERUNG ## Gibt den standardisierten Wert zurück +STDEV = STABW ## Schätzt die Standardabweichung ausgehend von einer Stichprobe +STDEVA = STABWA ## Schätzt die Standardabweichung ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält +STDEVP = STABWN ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit +STDEVPA = STABWNA ## Berechnet die Standardabweichung ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält +STEYX = STFEHLERYX ## Gibt den Standardfehler der geschätzten y-Werte für alle x-Werte der Regression zurück +TDIST = TVERT ## Gibt Werte der Verteilungsfunktion (1-Alpha) einer (Student) t-verteilten Zufallsvariablen zurück +TINV = TINV ## Gibt Quantile der t-Verteilung zurück +TREND = TREND ## Gibt Werte zurück, die sich aus einem linearen Trend ergeben +TRIMMEAN = GESTUTZTMITTEL ## Gibt den Mittelwert einer Datengruppe zurück, ohne die Randwerte zu berücksichtigen +TTEST = TTEST ## Gibt die Teststatistik eines Student'schen t-Tests zurück +VAR = VARIANZ ## Schätzt die Varianz ausgehend von einer Stichprobe +VARA = VARIANZA ## Schätzt die Varianz ausgehend von einer Stichprobe, die Zahlen, Text und Wahrheitswerte enthält +VARP = VARIANZEN ## Berechnet die Varianz ausgehend von der Grundgesamtheit +VARPA = VARIANZENA ## Berechnet die Varianz ausgehend von der Grundgesamtheit, die Zahlen, Text und Wahrheitswerte enthält +WEIBULL = WEIBULL ## Gibt Wahrscheinlichkeiten einer weibullverteilten Zufallsvariablen zurück +ZTEST = GTEST ## Gibt den einseitigen Wahrscheinlichkeitswert für einen Gausstest (Normalverteilung) zurück + + +## +## Text functions Textfunktionen +## +ASC = ASC ## Konvertiert DB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in SB-Text +BAHTTEXT = BAHTTEXT ## Wandelt eine Zahl in Text im Währungsformat ß (Baht) um +CHAR = ZEICHEN ## Gibt das der Codezahl entsprechende Zeichen zurück +CLEAN = SÄUBERN ## Löscht alle nicht druckbaren Zeichen aus einem Text +CODE = CODE ## Gibt die Codezahl des ersten Zeichens in einem Text zurück +CONCATENATE = VERKETTEN ## Verknüpft mehrere Textelemente zu einem Textelement +DOLLAR = DM ## Wandelt eine Zahl in Text im Währungsformat € (Euro) um +EXACT = IDENTISCH ## Prüft, ob zwei Textwerte identisch sind +FIND = FINDEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) +FINDB = FINDENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird unterschieden) +FIXED = FEST ## Formatiert eine Zahl als Text mit einer festen Anzahl von Dezimalstellen +JIS = JIS ## Konvertiert SB-Text in einer Zeichenfolge (lateinische Buchstaben oder Katakana) in DB-Text +LEFT = LINKS ## Gibt die Zeichen ganz links in einem Textwert zurück +LEFTB = LINKSB ## Gibt die Zeichen ganz links in einem Textwert zurück +LEN = LÄNGE ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück +LENB = LÄNGEB ## Gibt die Anzahl der Zeichen in einer Zeichenfolge zurück +LOWER = KLEIN ## Wandelt Text in Kleinbuchstaben um +MID = TEIL ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück +MIDB = TEILB ## Gibt eine bestimmte Anzahl Zeichen aus einer Zeichenfolge ab der von Ihnen angegebenen Stelle zurück +PHONETIC = PHONETIC ## Extrahiert die phonetischen (Furigana-)Zeichen aus einer Textzeichenfolge +PROPER = GROSS2 ## Wandelt den ersten Buchstaben aller Wörter eines Textwerts in Großbuchstaben um +REPLACE = ERSETZEN ## Ersetzt Zeichen in Text +REPLACEB = ERSETZENB ## Ersetzt Zeichen in Text +REPT = WIEDERHOLEN ## Wiederholt einen Text so oft wie angegeben +RIGHT = RECHTS ## Gibt die Zeichen ganz rechts in einem Textwert zurück +RIGHTB = RECHTSB ## Gibt die Zeichen ganz rechts in einem Textwert zurück +SEARCH = SUCHEN ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) +SEARCHB = SUCHENB ## Sucht nach einem Textwert, der in einem anderen Textwert enthalten ist (Groß-/Kleinschreibung wird nicht unterschieden) +SUBSTITUTE = WECHSELN ## Ersetzt in einer Zeichenfolge neuen Text gegen alten +T = T ## Wandelt die zugehörigen Argumente in Text um +TEXT = TEXT ## Formatiert eine Zahl und wandelt sie in Text um +TRIM = GLÄTTEN ## Entfernt Leerzeichen aus Text +UPPER = GROSS ## Wandelt Text in Großbuchstaben um +VALUE = WERT ## Wandelt ein Textargument in eine Zahl um diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/en/uk/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/en/uk/config new file mode 100644 index 00000000..532080b5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/en/uk/config @@ -0,0 +1,32 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +## +## (For future use) +## +currencySymbol = £ diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/config new file mode 100644 index 00000000..96cfa69d --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = $ ## I'm surprised that the Excel Documentation suggests $ rather than € + + +## +## Excel Error Codes (For future use) +## +NULL = #¡NULO! +DIV0 = #¡DIV/0! +VALUE = #¡VALOR! +REF = #¡REF! +NAME = #¿NOMBRE? +NUM = #¡NÚM! +NA = #N/A diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/functions new file mode 100644 index 00000000..48762695 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/es/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funciones de complementos y automatización +## +GETPIVOTDATA = IMPORTARDATOSDINAMICOS ## Devuelve los datos almacenados en un informe de tabla dinámica. + + +## +## Cube functions Funciones de cubo +## +CUBEKPIMEMBER = MIEMBROKPICUBO ## Devuelve un nombre, propiedad y medida de indicador de rendimiento clave (KPI) y muestra el nombre y la propiedad en la celda. Un KPI es una medida cuantificable, como los beneficios brutos mensuales o la facturación trimestral por empleado, que se usa para supervisar el rendimiento de una organización. +CUBEMEMBER = MIEMBROCUBO ## Devuelve un miembro o tupla en una jerarquía de cubo. Se usa para validar la existencia del miembro o la tupla en el cubo. +CUBEMEMBERPROPERTY = PROPIEDADMIEMBROCUBO ## Devuelve el valor de una propiedad de miembro del cubo Se usa para validar la existencia de un nombre de miembro en el cubo y para devolver la propiedad especificada para este miembro. +CUBERANKEDMEMBER = MIEMBRORANGOCUBO ## Devuelve el miembro n, o clasificado, de un conjunto. Se usa para devolver uno o más elementos de un conjunto, por ejemplo, el representante con mejores ventas o los diez mejores alumnos. +CUBESET = CONJUNTOCUBO ## Define un conjunto calculado de miembros o tuplas mediante el envío de una expresión de conjunto al cubo en el servidor, lo que crea el conjunto y, después, devuelve dicho conjunto a Microsoft Office Excel. +CUBESETCOUNT = RECUENTOCONJUNTOCUBO ## Devuelve el número de elementos de un conjunto. +CUBEVALUE = VALORCUBO ## Devuelve un valor agregado de un cubo. + + +## +## Database functions Funciones de base de datos +## +DAVERAGE = BDPROMEDIO ## Devuelve el promedio de las entradas seleccionadas en la base de datos. +DCOUNT = BDCONTAR ## Cuenta el número de celdas que contienen números en una base de datos. +DCOUNTA = BDCONTARA ## Cuenta el número de celdas no vacías en una base de datos. +DGET = BDEXTRAER ## Extrae de una base de datos un único registro que cumple los criterios especificados. +DMAX = BDMAX ## Devuelve el valor máximo de las entradas seleccionadas de la base de datos. +DMIN = BDMIN ## Devuelve el valor mínimo de las entradas seleccionadas de la base de datos. +DPRODUCT = BDPRODUCTO ## Multiplica los valores de un campo concreto de registros de una base de datos que cumplen los criterios especificados. +DSTDEV = BDDESVEST ## Calcula la desviación estándar a partir de una muestra de entradas seleccionadas en la base de datos. +DSTDEVP = BDDESVESTP ## Calcula la desviación estándar en función de la población total de las entradas seleccionadas de la base de datos. +DSUM = BDSUMA ## Suma los números de la columna de campo de los registros de la base de datos que cumplen los criterios. +DVAR = BDVAR ## Calcula la varianza a partir de una muestra de entradas seleccionadas de la base de datos. +DVARP = BDVARP ## Calcula la varianza a partir de la población total de entradas seleccionadas de la base de datos. + + +## +## Date and time functions Funciones de fecha y hora +## +DATE = FECHA ## Devuelve el número de serie correspondiente a una fecha determinada. +DATEVALUE = FECHANUMERO ## Convierte una fecha con formato de texto en un valor de número de serie. +DAY = DIA ## Convierte un número de serie en un valor de día del mes. +DAYS360 = DIAS360 ## Calcula el número de días entre dos fechas a partir de un año de 360 días. +EDATE = FECHA.MES ## Devuelve el número de serie de la fecha equivalente al número indicado de meses anteriores o posteriores a la fecha inicial. +EOMONTH = FIN.MES ## Devuelve el número de serie correspondiente al último día del mes anterior o posterior a un número de meses especificado. +HOUR = HORA ## Convierte un número de serie en un valor de hora. +MINUTE = MINUTO ## Convierte un número de serie en un valor de minuto. +MONTH = MES ## Convierte un número de serie en un valor de mes. +NETWORKDAYS = DIAS.LAB ## Devuelve el número de todos los días laborables existentes entre dos fechas. +NOW = AHORA ## Devuelve el número de serie correspondiente a la fecha y hora actuales. +SECOND = SEGUNDO ## Convierte un número de serie en un valor de segundo. +TIME = HORA ## Devuelve el número de serie correspondiente a una hora determinada. +TIMEVALUE = HORANUMERO ## Convierte una hora con formato de texto en un valor de número de serie. +TODAY = HOY ## Devuelve el número de serie correspondiente al día actual. +WEEKDAY = DIASEM ## Convierte un número de serie en un valor de día de la semana. +WEEKNUM = NUM.DE.SEMANA ## Convierte un número de serie en un número que representa el lugar numérico correspondiente a una semana de un año. +WORKDAY = DIA.LAB ## Devuelve el número de serie de la fecha que tiene lugar antes o después de un número determinado de días laborables. +YEAR = AÑO ## Convierte un número de serie en un valor de año. +YEARFRAC = FRAC.AÑO ## Devuelve la fracción de año que representa el número total de días existentes entre el valor de fecha_inicial y el de fecha_final. + + +## +## Engineering functions Funciones de ingeniería +## +BESSELI = BESSELI ## Devuelve la función Bessel In(x) modificada. +BESSELJ = BESSELJ ## Devuelve la función Bessel Jn(x). +BESSELK = BESSELK ## Devuelve la función Bessel Kn(x) modificada. +BESSELY = BESSELY ## Devuelve la función Bessel Yn(x). +BIN2DEC = BIN.A.DEC ## Convierte un número binario en decimal. +BIN2HEX = BIN.A.HEX ## Convierte un número binario en hexadecimal. +BIN2OCT = BIN.A.OCT ## Convierte un número binario en octal. +COMPLEX = COMPLEJO ## Convierte coeficientes reales e imaginarios en un número complejo. +CONVERT = CONVERTIR ## Convierte un número de un sistema de medida a otro. +DEC2BIN = DEC.A.BIN ## Convierte un número decimal en binario. +DEC2HEX = DEC.A.HEX ## Convierte un número decimal en hexadecimal. +DEC2OCT = DEC.A.OCT ## Convierte un número decimal en octal. +DELTA = DELTA ## Comprueba si dos valores son iguales. +ERF = FUN.ERROR ## Devuelve la función de error. +ERFC = FUN.ERROR.COMPL ## Devuelve la función de error complementario. +GESTEP = MAYOR.O.IGUAL ## Comprueba si un número es mayor que un valor de umbral. +HEX2BIN = HEX.A.BIN ## Convierte un número hexadecimal en binario. +HEX2DEC = HEX.A.DEC ## Convierte un número hexadecimal en decimal. +HEX2OCT = HEX.A.OCT ## Convierte un número hexadecimal en octal. +IMABS = IM.ABS ## Devuelve el valor absoluto (módulo) de un número complejo. +IMAGINARY = IMAGINARIO ## Devuelve el coeficiente imaginario de un número complejo. +IMARGUMENT = IM.ANGULO ## Devuelve el argumento theta, un ángulo expresado en radianes. +IMCONJUGATE = IM.CONJUGADA ## Devuelve la conjugada compleja de un número complejo. +IMCOS = IM.COS ## Devuelve el coseno de un número complejo. +IMDIV = IM.DIV ## Devuelve el cociente de dos números complejos. +IMEXP = IM.EXP ## Devuelve el valor exponencial de un número complejo. +IMLN = IM.LN ## Devuelve el logaritmo natural (neperiano) de un número complejo. +IMLOG10 = IM.LOG10 ## Devuelve el logaritmo en base 10 de un número complejo. +IMLOG2 = IM.LOG2 ## Devuelve el logaritmo en base 2 de un número complejo. +IMPOWER = IM.POT ## Devuelve un número complejo elevado a una potencia entera. +IMPRODUCT = IM.PRODUCT ## Devuelve el producto de números complejos. +IMREAL = IM.REAL ## Devuelve el coeficiente real de un número complejo. +IMSIN = IM.SENO ## Devuelve el seno de un número complejo. +IMSQRT = IM.RAIZ2 ## Devuelve la raíz cuadrada de un número complejo. +IMSUB = IM.SUSTR ## Devuelve la diferencia entre dos números complejos. +IMSUM = IM.SUM ## Devuelve la suma de números complejos. +OCT2BIN = OCT.A.BIN ## Convierte un número octal en binario. +OCT2DEC = OCT.A.DEC ## Convierte un número octal en decimal. +OCT2HEX = OCT.A.HEX ## Convierte un número octal en hexadecimal. + + +## +## Financial functions Funciones financieras +## +ACCRINT = INT.ACUM ## Devuelve el interés acumulado de un valor bursátil con pagos de interés periódicos. +ACCRINTM = INT.ACUM.V ## Devuelve el interés acumulado de un valor bursátil con pagos de interés al vencimiento. +AMORDEGRC = AMORTIZ.PROGRE ## Devuelve la amortización de cada período contable mediante el uso de un coeficiente de amortización. +AMORLINC = AMORTIZ.LIN ## Devuelve la amortización de cada uno de los períodos contables. +COUPDAYBS = CUPON.DIAS.L1 ## Devuelve el número de días desde el principio del período de un cupón hasta la fecha de liquidación. +COUPDAYS = CUPON.DIAS ## Devuelve el número de días del período (entre dos cupones) donde se encuentra la fecha de liquidación. +COUPDAYSNC = CUPON.DIAS.L2 ## Devuelve el número de días desde la fecha de liquidación hasta la fecha del próximo cupón. +COUPNCD = CUPON.FECHA.L2 ## Devuelve la fecha del próximo cupón después de la fecha de liquidación. +COUPNUM = CUPON.NUM ## Devuelve el número de pagos de cupón entre la fecha de liquidación y la fecha de vencimiento. +COUPPCD = CUPON.FECHA.L1 ## Devuelve la fecha de cupón anterior a la fecha de liquidación. +CUMIPMT = PAGO.INT.ENTRE ## Devuelve el interés acumulado pagado entre dos períodos. +CUMPRINC = PAGO.PRINC.ENTRE ## Devuelve el capital acumulado pagado de un préstamo entre dos períodos. +DB = DB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización de saldo fijo. +DDB = DDB ## Devuelve la amortización de un bien durante un período específico a través del método de amortización por doble disminución de saldo u otro método que se especifique. +DISC = TASA.DESC ## Devuelve la tasa de descuento de un valor bursátil. +DOLLARDE = MONEDA.DEC ## Convierte una cotización de un valor bursátil expresada en forma fraccionaria en una cotización de un valor bursátil expresada en forma decimal. +DOLLARFR = MONEDA.FRAC ## Convierte una cotización de un valor bursátil expresada en forma decimal en una cotización de un valor bursátil expresada en forma fraccionaria. +DURATION = DURACION ## Devuelve la duración anual de un valor bursátil con pagos de interés periódico. +EFFECT = INT.EFECTIVO ## Devuelve la tasa de interés anual efectiva. +FV = VF ## Devuelve el valor futuro de una inversión. +FVSCHEDULE = VF.PLAN ## Devuelve el valor futuro de un capital inicial después de aplicar una serie de tasas de interés compuesto. +INTRATE = TASA.INT ## Devuelve la tasa de interés para la inversión total de un valor bursátil. +IPMT = PAGOINT ## Devuelve el pago de intereses de una inversión durante un período determinado. +IRR = TIR ## Devuelve la tasa interna de retorno para una serie de flujos de efectivo periódicos. +ISPMT = INT.PAGO.DIR ## Calcula el interés pagado durante un período específico de una inversión. +MDURATION = DURACION.MODIF ## Devuelve la duración de Macauley modificada de un valor bursátil con un valor nominal supuesto de 100 $. +MIRR = TIRM ## Devuelve la tasa interna de retorno donde se financian flujos de efectivo positivos y negativos a tasas diferentes. +NOMINAL = TASA.NOMINAL ## Devuelve la tasa nominal de interés anual. +NPER = NPER ## Devuelve el número de períodos de una inversión. +NPV = VNA ## Devuelve el valor neto actual de una inversión en función de una serie de flujos periódicos de efectivo y una tasa de descuento. +ODDFPRICE = PRECIO.PER.IRREGULAR.1 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un primer período impar. +ODDFYIELD = RENDTO.PER.IRREGULAR.1 ## Devuelve el rendimiento de un valor bursátil con un primer período impar. +ODDLPRICE = PRECIO.PER.IRREGULAR.2 ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con un último período impar. +ODDLYIELD = RENDTO.PER.IRREGULAR.2 ## Devuelve el rendimiento de un valor bursátil con un último período impar. +PMT = PAGO ## Devuelve el pago periódico de una anualidad. +PPMT = PAGOPRIN ## Devuelve el pago de capital de una inversión durante un período determinado. +PRICE = PRECIO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga una tasa de interés periódico. +PRICEDISC = PRECIO.DESCUENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil con descuento. +PRICEMAT = PRECIO.VENCIMIENTO ## Devuelve el precio por un valor nominal de 100 $ de un valor bursátil que paga interés a su vencimiento. +PV = VALACT ## Devuelve el valor actual de una inversión. +RATE = TASA ## Devuelve la tasa de interés por período de una anualidad. +RECEIVED = CANTIDAD.RECIBIDA ## Devuelve la cantidad recibida al vencimiento de un valor bursátil completamente invertido. +SLN = SLN ## Devuelve la amortización por método directo de un bien en un período dado. +SYD = SYD ## Devuelve la amortización por suma de dígitos de los años de un bien durante un período especificado. +TBILLEQ = LETRA.DE.TES.EQV.A.BONO ## Devuelve el rendimiento de un bono equivalente a una letra del Tesoro (de EE.UU.) +TBILLPRICE = LETRA.DE.TES.PRECIO ## Devuelve el precio por un valor nominal de 100 $ de una letra del Tesoro (de EE.UU.) +TBILLYIELD = LETRA.DE.TES.RENDTO ## Devuelve el rendimiento de una letra del Tesoro (de EE.UU.) +VDB = DVS ## Devuelve la amortización de un bien durante un período específico o parcial a través del método de cálculo del saldo en disminución. +XIRR = TIR.NO.PER ## Devuelve la tasa interna de retorno para un flujo de efectivo que no es necesariamente periódico. +XNPV = VNA.NO.PER ## Devuelve el valor neto actual para un flujo de efectivo que no es necesariamente periódico. +YIELD = RENDTO ## Devuelve el rendimiento de un valor bursátil que paga intereses periódicos. +YIELDDISC = RENDTO.DESC ## Devuelve el rendimiento anual de un valor bursátil con descuento; por ejemplo, una letra del Tesoro (de EE.UU.) +YIELDMAT = RENDTO.VENCTO ## Devuelve el rendimiento anual de un valor bursátil que paga intereses al vencimiento. + + +## +## Information functions Funciones de información +## +CELL = CELDA ## Devuelve información acerca del formato, la ubicación o el contenido de una celda. +ERROR.TYPE = TIPO.DE.ERROR ## Devuelve un número que corresponde a un tipo de error. +INFO = INFO ## Devuelve información acerca del entorno operativo en uso. +ISBLANK = ESBLANCO ## Devuelve VERDADERO si el valor está en blanco. +ISERR = ESERR ## Devuelve VERDADERO si el valor es cualquier valor de error excepto #N/A. +ISERROR = ESERROR ## Devuelve VERDADERO si el valor es cualquier valor de error. +ISEVEN = ES.PAR ## Devuelve VERDADERO si el número es par. +ISLOGICAL = ESLOGICO ## Devuelve VERDADERO si el valor es un valor lógico. +ISNA = ESNOD ## Devuelve VERDADERO si el valor es el valor de error #N/A. +ISNONTEXT = ESNOTEXTO ## Devuelve VERDADERO si el valor no es texto. +ISNUMBER = ESNUMERO ## Devuelve VERDADERO si el valor es un número. +ISODD = ES.IMPAR ## Devuelve VERDADERO si el número es impar. +ISREF = ESREF ## Devuelve VERDADERO si el valor es una referencia. +ISTEXT = ESTEXTO ## Devuelve VERDADERO si el valor es texto. +N = N ## Devuelve un valor convertido en un número. +NA = ND ## Devuelve el valor de error #N/A. +TYPE = TIPO ## Devuelve un número que indica el tipo de datos de un valor. + + +## +## Logical functions Funciones lógicas +## +AND = Y ## Devuelve VERDADERO si todos sus argumentos son VERDADERO. +FALSE = FALSO ## Devuelve el valor lógico FALSO. +IF = SI ## Especifica una prueba lógica que realizar. +IFERROR = SI.ERROR ## Devuelve un valor que se especifica si una fórmula lo evalúa como un error; de lo contrario, devuelve el resultado de la fórmula. +NOT = NO ## Invierte el valor lógico del argumento. +OR = O ## Devuelve VERDADERO si cualquier argumento es VERDADERO. +TRUE = VERDADERO ## Devuelve el valor lógico VERDADERO. + + +## +## Lookup and reference functions Funciones de búsqueda y referencia +## +ADDRESS = DIRECCION ## Devuelve una referencia como texto a una sola celda de una hoja de cálculo. +AREAS = AREAS ## Devuelve el número de áreas de una referencia. +CHOOSE = ELEGIR ## Elige un valor de una lista de valores. +COLUMN = COLUMNA ## Devuelve el número de columna de una referencia. +COLUMNS = COLUMNAS ## Devuelve el número de columnas de una referencia. +HLOOKUP = BUSCARH ## Busca en la fila superior de una matriz y devuelve el valor de la celda indicada. +HYPERLINK = HIPERVINCULO ## Crea un acceso directo o un salto que abre un documento almacenado en un servidor de red, en una intranet o en Internet. +INDEX = INDICE ## Usa un índice para elegir un valor de una referencia o matriz. +INDIRECT = INDIRECTO ## Devuelve una referencia indicada por un valor de texto. +LOOKUP = BUSCAR ## Busca valores de un vector o una matriz. +MATCH = COINCIDIR ## Busca valores de una referencia o matriz. +OFFSET = DESREF ## Devuelve un desplazamiento de referencia respecto a una referencia dada. +ROW = FILA ## Devuelve el número de fila de una referencia. +ROWS = FILAS ## Devuelve el número de filas de una referencia. +RTD = RDTR ## Recupera datos en tiempo real desde un programa compatible con la automatización COM (automatización: modo de trabajar con los objetos de una aplicación desde otra aplicación o herramienta de entorno. La automatización, antes denominada automatización OLE, es un estándar de la industria y una función del Modelo de objetos componentes (COM).). +TRANSPOSE = TRANSPONER ## Devuelve la transposición de una matriz. +VLOOKUP = BUSCARV ## Busca en la primera columna de una matriz y se mueve en horizontal por la fila para devolver el valor de una celda. + + +## +## Math and trigonometry functions Funciones matemáticas y trigonométricas +## +ABS = ABS ## Devuelve el valor absoluto de un número. +ACOS = ACOS ## Devuelve el arcocoseno de un número. +ACOSH = ACOSH ## Devuelve el coseno hiperbólico inverso de un número. +ASIN = ASENO ## Devuelve el arcoseno de un número. +ASINH = ASENOH ## Devuelve el seno hiperbólico inverso de un número. +ATAN = ATAN ## Devuelve la arcotangente de un número. +ATAN2 = ATAN2 ## Devuelve la arcotangente de las coordenadas "x" e "y". +ATANH = ATANH ## Devuelve la tangente hiperbólica inversa de un número. +CEILING = MULTIPLO.SUPERIOR ## Redondea un número al entero más próximo o al múltiplo significativo más cercano. +COMBIN = COMBINAT ## Devuelve el número de combinaciones para un número determinado de objetos. +COS = COS ## Devuelve el coseno de un número. +COSH = COSH ## Devuelve el coseno hiperbólico de un número. +DEGREES = GRADOS ## Convierte radianes en grados. +EVEN = REDONDEA.PAR ## Redondea un número hasta el entero par más próximo. +EXP = EXP ## Devuelve e elevado a la potencia de un número dado. +FACT = FACT ## Devuelve el factorial de un número. +FACTDOUBLE = FACT.DOBLE ## Devuelve el factorial doble de un número. +FLOOR = MULTIPLO.INFERIOR ## Redondea un número hacia abajo, en dirección hacia cero. +GCD = M.C.D ## Devuelve el máximo común divisor. +INT = ENTERO ## Redondea un número hacia abajo hasta el entero más próximo. +LCM = M.C.M ## Devuelve el mínimo común múltiplo. +LN = LN ## Devuelve el logaritmo natural (neperiano) de un número. +LOG = LOG ## Devuelve el logaritmo de un número en una base especificada. +LOG10 = LOG10 ## Devuelve el logaritmo en base 10 de un número. +MDETERM = MDETERM ## Devuelve la determinante matricial de una matriz. +MINVERSE = MINVERSA ## Devuelve la matriz inversa de una matriz. +MMULT = MMULT ## Devuelve el producto de matriz de dos matrices. +MOD = RESIDUO ## Devuelve el resto de la división. +MROUND = REDOND.MULT ## Devuelve un número redondeado al múltiplo deseado. +MULTINOMIAL = MULTINOMIAL ## Devuelve el polinomio de un conjunto de números. +ODD = REDONDEA.IMPAR ## Redondea un número hacia arriba hasta el entero impar más próximo. +PI = PI ## Devuelve el valor de pi. +POWER = POTENCIA ## Devuelve el resultado de elevar un número a una potencia. +PRODUCT = PRODUCTO ## Multiplica sus argumentos. +QUOTIENT = COCIENTE ## Devuelve la parte entera de una división. +RADIANS = RADIANES ## Convierte grados en radianes. +RAND = ALEATORIO ## Devuelve un número aleatorio entre 0 y 1. +RANDBETWEEN = ALEATORIO.ENTRE ## Devuelve un número aleatorio entre los números que especifique. +ROMAN = NUMERO.ROMANO ## Convierte un número arábigo en número romano, con formato de texto. +ROUND = REDONDEAR ## Redondea un número al número de decimales especificado. +ROUNDDOWN = REDONDEAR.MENOS ## Redondea un número hacia abajo, en dirección hacia cero. +ROUNDUP = REDONDEAR.MAS ## Redondea un número hacia arriba, en dirección contraria a cero. +SERIESSUM = SUMA.SERIES ## Devuelve la suma de una serie de potencias en función de la fórmula. +SIGN = SIGNO ## Devuelve el signo de un número. +SIN = SENO ## Devuelve el seno de un ángulo determinado. +SINH = SENOH ## Devuelve el seno hiperbólico de un número. +SQRT = RAIZ ## Devuelve la raíz cuadrada positiva de un número. +SQRTPI = RAIZ2PI ## Devuelve la raíz cuadrada de un número multiplicado por PI (número * pi). +SUBTOTAL = SUBTOTALES ## Devuelve un subtotal en una lista o base de datos. +SUM = SUMA ## Suma sus argumentos. +SUMIF = SUMAR.SI ## Suma las celdas especificadas que cumplen unos criterios determinados. +SUMIFS = SUMAR.SI.CONJUNTO ## Suma las celdas de un rango que cumplen varios criterios. +SUMPRODUCT = SUMAPRODUCTO ## Devuelve la suma de los productos de los correspondientes componentes de matriz. +SUMSQ = SUMA.CUADRADOS ## Devuelve la suma de los cuadrados de los argumentos. +SUMX2MY2 = SUMAX2MENOSY2 ## Devuelve la suma de la diferencia de los cuadrados de los valores correspondientes de dos matrices. +SUMX2PY2 = SUMAX2MASY2 ## Devuelve la suma de la suma de los cuadrados de los valores correspondientes de dos matrices. +SUMXMY2 = SUMAXMENOSY2 ## Devuelve la suma de los cuadrados de las diferencias de los valores correspondientes de dos matrices. +TAN = TAN ## Devuelve la tangente de un número. +TANH = TANH ## Devuelve la tangente hiperbólica de un número. +TRUNC = TRUNCAR ## Trunca un número a un entero. + + +## +## Statistical functions Funciones estadísticas +## +AVEDEV = DESVPROM ## Devuelve el promedio de las desviaciones absolutas de la media de los puntos de datos. +AVERAGE = PROMEDIO ## Devuelve el promedio de sus argumentos. +AVERAGEA = PROMEDIOA ## Devuelve el promedio de sus argumentos, incluidos números, texto y valores lógicos. +AVERAGEIF = PROMEDIO.SI ## Devuelve el promedio (media aritmética) de todas las celdas de un rango que cumplen unos criterios determinados. +AVERAGEIFS = PROMEDIO.SI.CONJUNTO ## Devuelve el promedio (media aritmética) de todas las celdas que cumplen múltiples criterios. +BETADIST = DISTR.BETA ## Devuelve la función de distribución beta acumulativa. +BETAINV = DISTR.BETA.INV ## Devuelve la función inversa de la función de distribución acumulativa de una distribución beta especificada. +BINOMDIST = DISTR.BINOM ## Devuelve la probabilidad de una variable aleatoria discreta siguiendo una distribución binomial. +CHIDIST = DISTR.CHI ## Devuelve la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. +CHIINV = PRUEBA.CHI.INV ## Devuelve la función inversa de la probabilidad de una variable aleatoria continua siguiendo una distribución chi cuadrado de una sola cola. +CHITEST = PRUEBA.CHI ## Devuelve la prueba de independencia. +CONFIDENCE = INTERVALO.CONFIANZA ## Devuelve el intervalo de confianza de la media de una población. +CORREL = COEF.DE.CORREL ## Devuelve el coeficiente de correlación entre dos conjuntos de datos. +COUNT = CONTAR ## Cuenta cuántos números hay en la lista de argumentos. +COUNTA = CONTARA ## Cuenta cuántos valores hay en la lista de argumentos. +COUNTBLANK = CONTAR.BLANCO ## Cuenta el número de celdas en blanco de un rango. +COUNTIF = CONTAR.SI ## Cuenta el número de celdas, dentro del rango, que cumplen el criterio especificado. +COUNTIFS = CONTAR.SI.CONJUNTO ## Cuenta el número de celdas, dentro del rango, que cumplen varios criterios. +COVAR = COVAR ## Devuelve la covarianza, que es el promedio de los productos de las desviaciones para cada pareja de puntos de datos. +CRITBINOM = BINOM.CRIT ## Devuelve el menor valor cuya distribución binomial acumulativa es menor o igual a un valor de criterio. +DEVSQ = DESVIA2 ## Devuelve la suma de los cuadrados de las desviaciones. +EXPONDIST = DISTR.EXP ## Devuelve la distribución exponencial. +FDIST = DISTR.F ## Devuelve la distribución de probabilidad F. +FINV = DISTR.F.INV ## Devuelve la función inversa de la distribución de probabilidad F. +FISHER = FISHER ## Devuelve la transformación Fisher. +FISHERINV = PRUEBA.FISHER.INV ## Devuelve la función inversa de la transformación Fisher. +FORECAST = PRONOSTICO ## Devuelve un valor en una tendencia lineal. +FREQUENCY = FRECUENCIA ## Devuelve una distribución de frecuencia como una matriz vertical. +FTEST = PRUEBA.F ## Devuelve el resultado de una prueba F. +GAMMADIST = DISTR.GAMMA ## Devuelve la distribución gamma. +GAMMAINV = DISTR.GAMMA.INV ## Devuelve la función inversa de la distribución gamma acumulativa. +GAMMALN = GAMMA.LN ## Devuelve el logaritmo natural de la función gamma, G(x). +GEOMEAN = MEDIA.GEOM ## Devuelve la media geométrica. +GROWTH = CRECIMIENTO ## Devuelve valores en una tendencia exponencial. +HARMEAN = MEDIA.ARMO ## Devuelve la media armónica. +HYPGEOMDIST = DISTR.HIPERGEOM ## Devuelve la distribución hipergeométrica. +INTERCEPT = INTERSECCION.EJE ## Devuelve la intersección de la línea de regresión lineal. +KURT = CURTOSIS ## Devuelve la curtosis de un conjunto de datos. +LARGE = K.ESIMO.MAYOR ## Devuelve el k-ésimo mayor valor de un conjunto de datos. +LINEST = ESTIMACION.LINEAL ## Devuelve los parámetros de una tendencia lineal. +LOGEST = ESTIMACION.LOGARITMICA ## Devuelve los parámetros de una tendencia exponencial. +LOGINV = DISTR.LOG.INV ## Devuelve la función inversa de la distribución logarítmico-normal. +LOGNORMDIST = DISTR.LOG.NORM ## Devuelve la distribución logarítmico-normal acumulativa. +MAX = MAX ## Devuelve el valor máximo de una lista de argumentos. +MAXA = MAXA ## Devuelve el valor máximo de una lista de argumentos, incluidos números, texto y valores lógicos. +MEDIAN = MEDIANA ## Devuelve la mediana de los números dados. +MIN = MIN ## Devuelve el valor mínimo de una lista de argumentos. +MINA = MINA ## Devuelve el valor mínimo de una lista de argumentos, incluidos números, texto y valores lógicos. +MODE = MODA ## Devuelve el valor más común de un conjunto de datos. +NEGBINOMDIST = NEGBINOMDIST ## Devuelve la distribución binomial negativa. +NORMDIST = DISTR.NORM ## Devuelve la distribución normal acumulativa. +NORMINV = DISTR.NORM.INV ## Devuelve la función inversa de la distribución normal acumulativa. +NORMSDIST = DISTR.NORM.ESTAND ## Devuelve la distribución normal estándar acumulativa. +NORMSINV = DISTR.NORM.ESTAND.INV ## Devuelve la función inversa de la distribución normal estándar acumulativa. +PEARSON = PEARSON ## Devuelve el coeficiente de momento de correlación de producto Pearson. +PERCENTILE = PERCENTIL ## Devuelve el k-ésimo percentil de los valores de un rango. +PERCENTRANK = RANGO.PERCENTIL ## Devuelve el rango porcentual de un valor de un conjunto de datos. +PERMUT = PERMUTACIONES ## Devuelve el número de permutaciones de un número determinado de objetos. +POISSON = POISSON ## Devuelve la distribución de Poisson. +PROB = PROBABILIDAD ## Devuelve la probabilidad de que los valores de un rango se encuentren entre dos límites. +QUARTILE = CUARTIL ## Devuelve el cuartil de un conjunto de datos. +RANK = JERARQUIA ## Devuelve la jerarquía de un número en una lista de números. +RSQ = COEFICIENTE.R2 ## Devuelve el cuadrado del coeficiente de momento de correlación de producto Pearson. +SKEW = COEFICIENTE.ASIMETRIA ## Devuelve la asimetría de una distribución. +SLOPE = PENDIENTE ## Devuelve la pendiente de la línea de regresión lineal. +SMALL = K.ESIMO.MENOR ## Devuelve el k-ésimo menor valor de un conjunto de datos. +STANDARDIZE = NORMALIZACION ## Devuelve un valor normalizado. +STDEV = DESVEST ## Calcula la desviación estándar a partir de una muestra. +STDEVA = DESVESTA ## Calcula la desviación estándar a partir de una muestra, incluidos números, texto y valores lógicos. +STDEVP = DESVESTP ## Calcula la desviación estándar en función de toda la población. +STDEVPA = DESVESTPA ## Calcula la desviación estándar en función de toda la población, incluidos números, texto y valores lógicos. +STEYX = ERROR.TIPICO.XY ## Devuelve el error estándar del valor de "y" previsto para cada "x" de la regresión. +TDIST = DISTR.T ## Devuelve la distribución de t de Student. +TINV = DISTR.T.INV ## Devuelve la función inversa de la distribución de t de Student. +TREND = TENDENCIA ## Devuelve valores en una tendencia lineal. +TRIMMEAN = MEDIA.ACOTADA ## Devuelve la media del interior de un conjunto de datos. +TTEST = PRUEBA.T ## Devuelve la probabilidad asociada a una prueba t de Student. +VAR = VAR ## Calcula la varianza en función de una muestra. +VARA = VARA ## Calcula la varianza en función de una muestra, incluidos números, texto y valores lógicos. +VARP = VARP ## Calcula la varianza en función de toda la población. +VARPA = VARPA ## Calcula la varianza en función de toda la población, incluidos números, texto y valores lógicos. +WEIBULL = DIST.WEIBULL ## Devuelve la distribución de Weibull. +ZTEST = PRUEBA.Z ## Devuelve el valor de una probabilidad de una cola de una prueba z. + + +## +## Text functions Funciones de texto +## +ASC = ASC ## Convierte las letras inglesas o katakana de ancho completo (de dos bytes) dentro de una cadena de caracteres en caracteres de ancho medio (de un byte). +BAHTTEXT = TEXTOBAHT ## Convierte un número en texto, con el formato de moneda ß (Baht). +CHAR = CARACTER ## Devuelve el carácter especificado por el número de código. +CLEAN = LIMPIAR ## Quita del texto todos los caracteres no imprimibles. +CODE = CODIGO ## Devuelve un código numérico del primer carácter de una cadena de texto. +CONCATENATE = CONCATENAR ## Concatena varios elementos de texto en uno solo. +DOLLAR = MONEDA ## Convierte un número en texto, con el formato de moneda $ (dólar). +EXACT = IGUAL ## Comprueba si dos valores de texto son idénticos. +FIND = ENCONTRAR ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). +FINDB = ENCONTRARB ## Busca un valor de texto dentro de otro (distingue mayúsculas de minúsculas). +FIXED = DECIMAL ## Da formato a un número como texto con un número fijo de decimales. +JIS = JIS ## Convierte las letras inglesas o katakana de ancho medio (de un byte) dentro de una cadena de caracteres en caracteres de ancho completo (de dos bytes). +LEFT = IZQUIERDA ## Devuelve los caracteres del lado izquierdo de un valor de texto. +LEFTB = IZQUIERDAB ## Devuelve los caracteres del lado izquierdo de un valor de texto. +LEN = LARGO ## Devuelve el número de caracteres de una cadena de texto. +LENB = LARGOB ## Devuelve el número de caracteres de una cadena de texto. +LOWER = MINUSC ## Pone el texto en minúsculas. +MID = EXTRAE ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. +MIDB = EXTRAEB ## Devuelve un número específico de caracteres de una cadena de texto que comienza en la posición que se especifique. +PHONETIC = FONETICO ## Extrae los caracteres fonéticos (furigana) de una cadena de texto. +PROPER = NOMPROPIO ## Pone en mayúscula la primera letra de cada palabra de un valor de texto. +REPLACE = REEMPLAZAR ## Reemplaza caracteres de texto. +REPLACEB = REEMPLAZARB ## Reemplaza caracteres de texto. +REPT = REPETIR ## Repite el texto un número determinado de veces. +RIGHT = DERECHA ## Devuelve los caracteres del lado derecho de un valor de texto. +RIGHTB = DERECHAB ## Devuelve los caracteres del lado derecho de un valor de texto. +SEARCH = HALLAR ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). +SEARCHB = HALLARB ## Busca un valor de texto dentro de otro (no distingue mayúsculas de minúsculas). +SUBSTITUTE = SUSTITUIR ## Sustituye texto nuevo por texto antiguo en una cadena de texto. +T = T ## Convierte sus argumentos a texto. +TEXT = TEXTO ## Da formato a un número y lo convierte en texto. +TRIM = ESPACIOS ## Quita los espacios del texto. +UPPER = MAYUSC ## Pone el texto en mayúsculas. +VALUE = VALOR ## Convierte un argumento de texto en un número. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/config new file mode 100644 index 00000000..498cf4ce --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = $ # Symbol not known, should it be a € (Euro)? + + +## +## Excel Error Codes (For future use) +## +NULL = #TYHJÄ! +DIV0 = #JAKO/0! +VALUE = #ARVO! +REF = #VIITTAUS! +NAME = #NIMI? +NUM = #LUKU! +NA = #PUUTTUU diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/functions new file mode 100644 index 00000000..6a7c2b36 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fi/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Apuohjelma- ja automaatiofunktiot +## +GETPIVOTDATA = NOUDA.PIVOT.TIEDOT ## Palauttaa pivot-taulukkoraporttiin tallennettuja tietoja. + + +## +## Cube functions Kuutiofunktiot +## +CUBEKPIMEMBER = KUUTIOKPIJÄSEN ## Palauttaa suorituskykyilmaisimen (KPI) nimen, ominaisuuden sekä mitan ja näyttää nimen sekä ominaisuuden solussa. KPI on mitattavissa oleva suure, kuten kuukauden bruttotuotto tai vuosineljänneksen työntekijäkohtainen liikevaihto, joiden avulla tarkkaillaan organisaation suorituskykyä. +CUBEMEMBER = KUUTIONJÄSEN ## Palauttaa kuutiohierarkian jäsenen tai monikon. Tällä funktiolla voit tarkistaa, että jäsen tai monikko on olemassa kuutiossa. +CUBEMEMBERPROPERTY = KUUTIONJÄSENENOMINAISUUS ## Palauttaa kuution jäsenominaisuuden arvon. Tällä funktiolla voit tarkistaa, että nimi on olemassa kuutiossa, ja palauttaa tämän jäsenen määritetyn ominaisuuden. +CUBERANKEDMEMBER = KUUTIONLUOKITELTUJÄSEN ## Palauttaa joukon n:nnen jäsenen. Tällä funktiolla voit palauttaa joukosta elementtejä, kuten parhaan myyjän tai 10 parasta opiskelijaa. +CUBESET = KUUTIOJOUKKO ## Määrittää lasketun jäsen- tai monikkojoukon lähettämällä joukon lausekkeita palvelimessa olevalle kuutiolle. Palvelin luo joukon ja palauttaa sen Microsoft Office Excelille. +CUBESETCOUNT = KUUTIOJOUKKOJENMÄÄRÄ ## Palauttaa joukon kohteiden määrän. +CUBEVALUE = KUUTIONARVO ## Palauttaa koostetun arvon kuutiosta. + + +## +## Database functions Tietokantafunktiot +## +DAVERAGE = TKESKIARVO ## Palauttaa valittujen tietokantamerkintöjen keskiarvon. +DCOUNT = TLASKE ## Laskee tietokannan lukuja sisältävien solujen määrän. +DCOUNTA = TLASKEA ## Laskee tietokannan tietoja sisältävien solujen määrän. +DGET = TNOUDA ## Hakee määritettyjä ehtoja vastaavan tietueen tietokannasta. +DMAX = TMAKS ## Palauttaa suurimman arvon tietokannasta valittujen arvojen joukosta. +DMIN = TMIN ## Palauttaa pienimmän arvon tietokannasta valittujen arvojen joukosta. +DPRODUCT = TTULO ## Kertoo määritetyn ehdon täyttävien tietokannan tietueiden tietyssä kentässä olevat arvot. +DSTDEV = TKESKIHAJONTA ## Laskee keskihajonnan tietokannasta valituista arvoista muodostuvan otoksen perusteella. +DSTDEVP = TKESKIHAJONTAP ## Laskee keskihajonnan tietokannasta valittujen arvojen koko populaation perusteella. +DSUM = TSUMMA ## Lisää luvut määritetyn ehdon täyttävien tietokannan tietueiden kenttäsarakkeeseen. +DVAR = TVARIANSSI ## Laskee varianssin tietokannasta valittujen arvojen otoksen perusteella. +DVARP = TVARIANSSIP ## Laskee varianssin tietokannasta valittujen arvojen koko populaation perusteella. + + +## +## Date and time functions Päivämäärä- ja aikafunktiot +## +DATE = PÄIVÄYS ## Palauttaa annetun päivämäärän järjestysluvun. +DATEVALUE = PÄIVÄYSARVO ## Muuntaa tekstimuodossa olevan päivämäärän järjestysluvuksi. +DAY = PÄIVÄ ## Muuntaa järjestysluvun kuukauden päiväksi. +DAYS360 = PÄIVÄT360 ## Laskee kahden päivämäärän välisten päivien määrän käyttäen perustana 360-päiväistä vuotta. +EDATE = PÄIVÄ.KUUKAUSI ## Palauttaa järjestyslukuna päivämäärän, joka poikkeaa aloituspäivän päivämäärästä annetun kuukausimäärän verran joko eteen- tai taaksepäin. +EOMONTH = KUUKAUSI.LOPPU ## Palauttaa järjestyslukuna sen kuukauden viimeisen päivämäärän, joka poikkeaa annetun kuukausimäärän verran eteen- tai taaksepäin. +HOUR = TUNNIT ## Muuntaa järjestysluvun tunneiksi. +MINUTE = MINUUTIT ## Muuntaa järjestysluvun minuuteiksi. +MONTH = KUUKAUSI ## Muuntaa järjestysluvun kuukausiksi. +NETWORKDAYS = TYÖPÄIVÄT ## Palauttaa kahden päivämäärän välissä olevien täysien työpäivien määrän. +NOW = NYT ## Palauttaa kuluvan päivämäärän ja ajan järjestysnumeron. +SECOND = SEKUNNIT ## Muuntaa järjestysluvun sekunneiksi. +TIME = AIKA ## Palauttaa annetun kellonajan järjestysluvun. +TIMEVALUE = AIKA_ARVO ## Muuntaa tekstimuodossa olevan kellonajan järjestysluvuksi. +TODAY = TÄMÄ.PÄIVÄ ## Palauttaa kuluvan päivän päivämäärän järjestysluvun. +WEEKDAY = VIIKONPÄIVÄ ## Muuntaa järjestysluvun viikonpäiväksi. +WEEKNUM = VIIKKO.NRO ## Muuntaa järjestysluvun luvuksi, joka ilmaisee viikon järjestysluvun vuoden alusta laskettuna. +WORKDAY = TYÖPÄIVÄ ## Palauttaa järjestysluvun päivämäärälle, joka sijaitsee annettujen työpäivien verran eteen tai taaksepäin. +YEAR = VUOSI ## Muuntaa järjestysluvun vuosiksi. +YEARFRAC = VUOSI.OSA ## Palauttaa määritettyjen päivämäärien (aloituspäivä ja lopetuspäivä) välisen osan vuodesta. + + +## +## Engineering functions Tekniset funktiot +## +BESSELI = BESSELI ## Palauttaa muunnetun Bessel-funktion In(x). +BESSELJ = BESSELJ ## Palauttaa Bessel-funktion Jn(x). +BESSELK = BESSELK ## Palauttaa muunnetun Bessel-funktion Kn(x). +BESSELY = BESSELY ## Palauttaa Bessel-funktion Yn(x). +BIN2DEC = BINDES ## Muuntaa binaariluvun desimaaliluvuksi. +BIN2HEX = BINHEKSA ## Muuntaa binaariluvun heksadesimaaliluvuksi. +BIN2OCT = BINOKT ## Muuntaa binaariluvun oktaaliluvuksi. +COMPLEX = KOMPLEKSI ## Muuntaa reaali- ja imaginaariosien kertoimet kompleksiluvuksi. +CONVERT = MUUNNA ## Muuntaa luvun toisen mittajärjestelmän mukaiseksi. +DEC2BIN = DESBIN ## Muuntaa desimaaliluvun binaariluvuksi. +DEC2HEX = DESHEKSA ## Muuntaa kymmenjärjestelmän luvun heksadesimaaliluvuksi. +DEC2OCT = DESOKT ## Muuntaa kymmenjärjestelmän luvun oktaaliluvuksi. +DELTA = SAMA.ARVO ## Tarkistaa, ovatko kaksi arvoa yhtä suuria. +ERF = VIRHEFUNKTIO ## Palauttaa virhefunktion. +ERFC = VIRHEFUNKTIO.KOMPLEMENTTI ## Palauttaa komplementtivirhefunktion. +GESTEP = RAJA ## Testaa, onko luku suurempi kuin kynnysarvo. +HEX2BIN = HEKSABIN ## Muuntaa heksadesimaaliluvun binaariluvuksi. +HEX2DEC = HEKSADES ## Muuntaa heksadesimaaliluvun desimaaliluvuksi. +HEX2OCT = HEKSAOKT ## Muuntaa heksadesimaaliluvun oktaaliluvuksi. +IMABS = KOMPLEKSI.ITSEISARVO ## Palauttaa kompleksiluvun itseisarvon (moduluksen). +IMAGINARY = KOMPLEKSI.IMAG ## Palauttaa kompleksiluvun imaginaariosan kertoimen. +IMARGUMENT = KOMPLEKSI.ARG ## Palauttaa theeta-argumentin, joka on radiaaneina annettu kulma. +IMCONJUGATE = KOMPLEKSI.KONJ ## Palauttaa kompleksiluvun konjugaattiluvun. +IMCOS = KOMPLEKSI.COS ## Palauttaa kompleksiluvun kosinin. +IMDIV = KOMPLEKSI.OSAM ## Palauttaa kahden kompleksiluvun osamäärän. +IMEXP = KOMPLEKSI.EKSP ## Palauttaa kompleksiluvun eksponentin. +IMLN = KOMPLEKSI.LN ## Palauttaa kompleksiluvun luonnollisen logaritmin. +IMLOG10 = KOMPLEKSI.LOG10 ## Palauttaa kompleksiluvun kymmenkantaisen logaritmin. +IMLOG2 = KOMPLEKSI.LOG2 ## Palauttaa kompleksiluvun kaksikantaisen logaritmin. +IMPOWER = KOMPLEKSI.POT ## Palauttaa kokonaislukupotenssiin korotetun kompleksiluvun. +IMPRODUCT = KOMPLEKSI.TULO ## Palauttaa kompleksilukujen tulon. +IMREAL = KOMPLEKSI.REAALI ## Palauttaa kompleksiluvun reaaliosan kertoimen. +IMSIN = KOMPLEKSI.SIN ## Palauttaa kompleksiluvun sinin. +IMSQRT = KOMPLEKSI.NELIÖJ ## Palauttaa kompleksiluvun neliöjuuren. +IMSUB = KOMPLEKSI.EROTUS ## Palauttaa kahden kompleksiluvun erotuksen. +IMSUM = KOMPLEKSI.SUM ## Palauttaa kompleksilukujen summan. +OCT2BIN = OKTBIN ## Muuntaa oktaaliluvun binaariluvuksi. +OCT2DEC = OKTDES ## Muuntaa oktaaliluvun desimaaliluvuksi. +OCT2HEX = OKTHEKSA ## Muuntaa oktaaliluvun heksadesimaaliluvuksi. + + +## +## Financial functions Rahoitusfunktiot +## +ACCRINT = KERTYNYT.KORKO ## Laskee arvopaperille kertyneen koron, kun korko kertyy säännöllisin väliajoin. +ACCRINTM = KERTYNYT.KORKO.LOPUSSA ## Laskee arvopaperille kertyneen koron, kun korko maksetaan eräpäivänä. +AMORDEGRC = AMORDEGRC ## Laskee kunkin laskentakauden poiston poistokerrointa käyttämällä. +AMORLINC = AMORLINC ## Palauttaa kunkin laskentakauden poiston. +COUPDAYBS = KORKOPÄIVÄT.ALUSTA ## Palauttaa koronmaksukauden aloituspäivän ja tilityspäivän välisen ajanjakson päivien määrän. +COUPDAYS = KORKOPÄIVÄT ## Palauttaa päivien määrän koronmaksukaudelta, johon tilityspäivä kuuluu. +COUPDAYSNC = KORKOPÄIVÄT.SEURAAVA ## Palauttaa tilityspäivän ja seuraavan koronmaksupäivän välisen ajanjakson päivien määrän. +COUPNCD = KORKOMAKSU.SEURAAVA ## Palauttaa tilityspäivän jälkeisen seuraavan koronmaksupäivän. +COUPNUM = KORKOPÄIVÄJAKSOT ## Palauttaa arvopaperin ostopäivän ja erääntymispäivän välisten koronmaksupäivien määrän. +COUPPCD = KORKOPÄIVÄ.EDELLINEN ## Palauttaa tilityspäivää edeltävän koronmaksupäivän. +CUMIPMT = MAKSETTU.KORKO ## Palauttaa kahden jakson välisenä aikana kertyneen koron. +CUMPRINC = MAKSETTU.LYHENNYS ## Palauttaa lainalle kahden jakson välisenä aikana kertyneen lyhennyksen. +DB = DB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. +DDB = DDB ## Palauttaa kauden kirjanpidollisen poiston amerikkalaisen DDB-menetelmän (Double-Declining Balance) tai jonkin muun määrittämäsi menetelmän mukaan. +DISC = DISKONTTOKORKO ## Palauttaa arvopaperin diskonttokoron. +DOLLARDE = VALUUTTA.DES ## Muuntaa murtolukuna ilmoitetun valuuttamäärän desimaaliluvuksi. +DOLLARFR = VALUUTTA.MURTO ## Muuntaa desimaalilukuna ilmaistun valuuttamäärän murtoluvuksi. +DURATION = KESTO ## Palauttaa keston arvopaperille, jonka koronmaksu tapahtuu säännöllisesti. +EFFECT = KORKO.EFEKT ## Palauttaa todellisen vuosikoron. +FV = TULEVA.ARVO ## Palauttaa sijoituksen tulevan arvon. +FVSCHEDULE = TULEVA.ARVO.ERIKORKO ## Palauttaa pääoman tulevan arvon, kun pääomalle on kertynyt korkoa vaihtelevasti. +INTRATE = KORKO.ARVOPAPERI ## Palauttaa arvopaperin korkokannan täysin sijoitetulle arvopaperille. +IPMT = IPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona kertyvän koron. +IRR = SISÄINEN.KORKO ## Laskee sisäisen korkokannan kassavirrasta muodostuvalle sarjalle. +ISPMT = ONMAKSU ## Laskee sijoituksen maksetun koron tietyllä jaksolla. +MDURATION = KESTO.MUUNN ## Palauttaa muunnetun Macauley-keston arvopaperille, jonka oletettu nimellisarvo on 100 euroa. +MIRR = MSISÄINEN ## Palauttaa sisäisen korkokannan, kun positiivisten ja negatiivisten kassavirtojen rahoituskorko on erilainen. +NOMINAL = KORKO.VUOSI ## Palauttaa vuosittaisen nimelliskoron. +NPER = NJAKSO ## Palauttaa sijoituksen jaksojen määrän. +NPV = NNA ## Palauttaa sijoituksen nykyarvon toistuvista kassavirroista muodostuvan sarjan ja diskonttokoron perusteella. +ODDFPRICE = PARITON.ENS.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa ensimmäinen jakso on pariton. +ODDFYIELD = PARITON.ENS.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa ensimmäinen jakso on pariton. +ODDLPRICE = PARITON.VIIM.NIMELLISARVO ## Palauttaa arvopaperin hinnan tilanteessa, jossa viimeinen jakso on pariton. +ODDLYIELD = PARITON.VIIM.TUOTTO ## Palauttaa arvopaperin tuoton tilanteessa, jossa viimeinen jakso on pariton. +PMT = MAKSU ## Palauttaa annuiteetin kausittaisen maksuerän. +PPMT = PPMT ## Laskee sijoitukselle tai lainalle tiettynä ajanjaksona maksettavan lyhennyksen. +PRICE = HINTA ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan säännöllisin väliajoin. +PRICEDISC = HINTA.DISK ## Palauttaa diskontatun arvopaperin hinnan 100 euron nimellisarvoa kohden. +PRICEMAT = HINTA.LUNASTUS ## Palauttaa hinnan 100 euron nimellisarvoa kohden arvopaperille, jonka korko maksetaan erääntymispäivänä. +PV = NA ## Palauttaa sijoituksen nykyarvon. +RATE = KORKO ## Palauttaa annuiteetin kausittaisen korkokannan. +RECEIVED = SAATU.HINTA ## Palauttaa arvopaperin tuoton erääntymispäivänä kokonaan maksetulle sijoitukselle. +SLN = STP ## Palauttaa sijoituksen tasapoiston yhdeltä jaksolta. +SYD = VUOSIPOISTO ## Palauttaa sijoituksen vuosipoiston annettuna kautena amerikkalaisen SYD-menetelmän (Sum-of-Year's Digits) avulla. +TBILLEQ = OBLIG.TUOTTOPROS ## Palauttaa valtion obligaation tuoton vastaavana joukkovelkakirjan tuottona. +TBILLPRICE = OBLIG.HINTA ## Palauttaa obligaation hinnan 100 euron nimellisarvoa kohden. +TBILLYIELD = OBLIG.TUOTTO ## Palauttaa obligaation tuoton. +VDB = VDB ## Palauttaa annetun kauden tai kauden osan kirjanpidollisen poiston amerikkalaisen DB-menetelmän (Fixed-declining balance) mukaan. +XIRR = SISÄINEN.KORKO.JAKSOTON ## Palauttaa sisäisen korkokannan kassavirtojen sarjoille, jotka eivät välttämättä ole säännöllisiä. +XNPV = NNA.JAKSOTON ## Palauttaa nettonykyarvon kassavirtasarjalle, joka ei välttämättä ole kausittainen. +YIELD = TUOTTO ## Palauttaa tuoton arvopaperille, jonka korko maksetaan säännöllisin väliajoin. +YIELDDISC = TUOTTO.DISK ## Palauttaa diskontatun arvopaperin, kuten obligaation, vuosittaisen tuoton. +YIELDMAT = TUOTTO.ERÄP ## Palauttaa erääntymispäivänään korkoa tuottavan arvopaperin vuosittaisen tuoton. + + +## +## Information functions Erikoisfunktiot +## +CELL = SOLU ## Palauttaa tietoja solun muotoilusta, sijainnista ja sisällöstä. +ERROR.TYPE = VIRHEEN.LAJI ## Palauttaa virhetyyppiä vastaavan luvun. +INFO = KUVAUS ## Palauttaa tietoja nykyisestä käyttöympäristöstä. +ISBLANK = ONTYHJÄ ## Palauttaa arvon TOSI, jos arvo on tyhjä. +ISERR = ONVIRH ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo paitsi arvo #PUUTTUU!. +ISERROR = ONVIRHE ## Palauttaa arvon TOSI, jos arvo on mikä tahansa virhearvo. +ISEVEN = ONPARILLINEN ## Palauttaa arvon TOSI, jos arvo on parillinen. +ISLOGICAL = ONTOTUUS ## Palauttaa arvon TOSI, jos arvo on mikä tahansa looginen arvo. +ISNA = ONPUUTTUU ## Palauttaa arvon TOSI, jos virhearvo on #PUUTTUU!. +ISNONTEXT = ONEI_TEKSTI ## Palauttaa arvon TOSI, jos arvo ei ole teksti. +ISNUMBER = ONLUKU ## Palauttaa arvon TOSI, jos arvo on luku. +ISODD = ONPARITON ## Palauttaa arvon TOSI, jos arvo on pariton. +ISREF = ONVIITT ## Palauttaa arvon TOSI, jos arvo on viittaus. +ISTEXT = ONTEKSTI ## Palauttaa arvon TOSI, jos arvo on teksti. +N = N ## Palauttaa arvon luvuksi muunnettuna. +NA = PUUTTUU ## Palauttaa virhearvon #PUUTTUU!. +TYPE = TYYPPI ## Palauttaa luvun, joka ilmaisee arvon tietotyypin. + + +## +## Logical functions Loogiset funktiot +## +AND = JA ## Palauttaa arvon TOSI, jos kaikkien argumenttien arvo on TOSI. +FALSE = EPÄTOSI ## Palauttaa totuusarvon EPÄTOSI. +IF = JOS ## Määrittää suoritettavan loogisen testin. +IFERROR = JOSVIRHE ## Palauttaa määrittämäsi arvon, jos kaavan tulos on virhe; muussa tapauksessa palauttaa kaavan tuloksen. +NOT = EI ## Kääntää argumentin loogisen arvon. +OR = TAI ## Palauttaa arvon TOSI, jos minkä tahansa argumentin arvo on TOSI. +TRUE = TOSI ## Palauttaa totuusarvon TOSI. + + +## +## Lookup and reference functions Haku- ja viitefunktiot +## +ADDRESS = OSOITE ## Palauttaa laskentataulukon soluun osoittavan viittauksen tekstinä. +AREAS = ALUEET ## Palauttaa viittauksessa olevien alueiden määrän. +CHOOSE = VALITSE.INDEKSI ## Valitsee arvon arvoluettelosta. +COLUMN = SARAKE ## Palauttaa viittauksen sarakenumeron. +COLUMNS = SARAKKEET ## Palauttaa viittauksessa olevien sarakkeiden määrän. +HLOOKUP = VHAKU ## Suorittaa haun matriisin ylimmältä riviltä ja palauttaa määritetyn solun arvon. +HYPERLINK = HYPERLINKKI ## Luo pikakuvakkeen tai tekstin, joka avaa verkkopalvelimeen, intranetiin tai Internetiin tallennetun tiedoston. +INDEX = INDEKSI ## Valitsee arvon viittauksesta tai matriisista indeksin mukaan. +INDIRECT = EPÄSUORA ## Palauttaa tekstiarvona ilmaistun viittauksen. +LOOKUP = HAKU ## Etsii arvoja vektorista tai matriisista. +MATCH = VASTINE ## Etsii arvoja viittauksesta tai matriisista. +OFFSET = SIIRTYMÄ ## Palauttaa annetun viittauksen siirtymän. +ROW = RIVI ## Palauttaa viittauksen rivinumeron. +ROWS = RIVIT ## Palauttaa viittauksessa olevien rivien määrän. +RTD = RTD ## Noutaa COM-automaatiota (automaatio: Tapa käsitellä sovelluksen objekteja toisesta sovelluksesta tai kehitystyökalusta. Automaatio, jota aiemmin kutsuttiin OLE-automaatioksi, on teollisuusstandardi ja COM-mallin (Component Object Model) ominaisuus.) tukevasta ohjelmasta reaaliaikaisia tietoja. +TRANSPOSE = TRANSPONOI ## Palauttaa matriisin käänteismatriisin. +VLOOKUP = PHAKU ## Suorittaa haun matriisin ensimmäisestä sarakkeesta ja palauttaa rivillä olevan solun arvon. + + +## +## Math and trigonometry functions Matemaattiset ja trigonometriset funktiot +## +ABS = ITSEISARVO ## Palauttaa luvun itseisarvon. +ACOS = ACOS ## Palauttaa luvun arkuskosinin. +ACOSH = ACOSH ## Palauttaa luvun käänteisen hyperbolisen kosinin. +ASIN = ASIN ## Palauttaa luvun arkussinin. +ASINH = ASINH ## Palauttaa luvun käänteisen hyperbolisen sinin. +ATAN = ATAN ## Palauttaa luvun arkustangentin. +ATAN2 = ATAN2 ## Palauttaa arkustangentin x- ja y-koordinaatin perusteella. +ATANH = ATANH ## Palauttaa luvun käänteisen hyperbolisen tangentin. +CEILING = PYÖRISTÄ.KERR.YLÖS ## Pyöristää luvun lähimpään kokonaislukuun tai tarkkuusargumentin lähimpään kerrannaiseen. +COMBIN = KOMBINAATIO ## Palauttaa mahdollisten kombinaatioiden määrän annetulle objektien määrälle. +COS = COS ## Palauttaa luvun kosinin. +COSH = COSH ## Palauttaa luvun hyperbolisen kosinin. +DEGREES = ASTEET ## Muuntaa radiaanit asteiksi. +EVEN = PARILLINEN ## Pyöristää luvun ylöspäin lähimpään parilliseen kokonaislukuun. +EXP = EKSPONENTTI ## Palauttaa e:n korotettuna annetun luvun osoittamaan potenssiin. +FACT = KERTOMA ## Palauttaa luvun kertoman. +FACTDOUBLE = KERTOMA.OSA ## Palauttaa luvun osakertoman. +FLOOR = PYÖRISTÄ.KERR.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). +GCD = SUURIN.YHT.TEKIJÄ ## Palauttaa suurimman yhteisen tekijän. +INT = KOKONAISLUKU ## Pyöristää luvun alaspäin lähimpään kokonaislukuun. +LCM = PIENIN.YHT.JAETTAVA ## Palauttaa pienimmän yhteisen tekijän. +LN = LUONNLOG ## Palauttaa luvun luonnollisen logaritmin. +LOG = LOG ## Laskee luvun logaritmin käyttämällä annettua kantalukua. +LOG10 = LOG10 ## Palauttaa luvun kymmenkantaisen logaritmin. +MDETERM = MDETERM ## Palauttaa matriisin matriisideterminantin. +MINVERSE = MKÄÄNTEINEN ## Palauttaa matriisin käänteismatriisin. +MMULT = MKERRO ## Palauttaa kahden matriisin tulon. +MOD = JAKOJ ## Palauttaa jakolaskun jäännöksen. +MROUND = PYÖRISTÄ.KERR ## Palauttaa luvun pyöristettynä annetun luvun kerrannaiseen. +MULTINOMIAL = MULTINOMI ## Palauttaa lukujoukon multinomin. +ODD = PARITON ## Pyöristää luvun ylöspäin lähimpään parittomaan kokonaislukuun. +PI = PII ## Palauttaa piin arvon. +POWER = POTENSSI ## Palauttaa luvun korotettuna haluttuun potenssiin. +PRODUCT = TULO ## Kertoo annetut argumentit. +QUOTIENT = OSAMÄÄRÄ ## Palauttaa osamäärän kokonaislukuosan. +RADIANS = RADIAANIT ## Muuntaa asteet radiaaneiksi. +RAND = SATUNNAISLUKU ## Palauttaa satunnaisluvun väliltä 0–1. +RANDBETWEEN = SATUNNAISLUKU.VÄLILTÄ ## Palauttaa satunnaisluvun määritettyjen lukujen väliltä. +ROMAN = ROMAN ## Muuntaa arabialaisen numeron tekstimuotoiseksi roomalaiseksi numeroksi. +ROUND = PYÖRISTÄ ## Pyöristää luvun annettuun määrään desimaaleja. +ROUNDDOWN = PYÖRISTÄ.DES.ALAS ## Pyöristää luvun alaspäin (nollaa kohti). +ROUNDUP = PYÖRISTÄ.DES.YLÖS ## Pyöristää luvun ylöspäin (poispäin nollasta). +SERIESSUM = SARJA.SUMMA ## Palauttaa kaavaan perustuvan potenssisarjan arvon. +SIGN = ETUMERKKI ## Palauttaa luvun etumerkin. +SIN = SIN ## Palauttaa annetun kulman sinin. +SINH = SINH ## Palauttaa luvun hyperbolisen sinin. +SQRT = NELIÖJUURI ## Palauttaa positiivisen neliöjuuren. +SQRTPI = NELIÖJUURI.PII ## Palauttaa tulon (luku * pii) neliöjuuren. +SUBTOTAL = VÄLISUMMA ## Palauttaa luettelon tai tietokannan välisumman. +SUM = SUMMA ## Laskee yhteen annetut argumentit. +SUMIF = SUMMA.JOS ## Laskee ehdot täyttävien solujen summan. +SUMIFS = SUMMA.JOS.JOUKKO ## Laskee yhteen solualueen useita ehtoja vastaavat solut. +SUMPRODUCT = TULOJEN.SUMMA ## Palauttaa matriisin toisiaan vastaavien osien tulojen summan. +SUMSQ = NELIÖSUMMA ## Palauttaa argumenttien neliöiden summan. +SUMX2MY2 = NELIÖSUMMIEN.EROTUS ## Palauttaa kahden matriisin toisiaan vastaavien arvojen laskettujen neliösummien erotuksen. +SUMX2PY2 = NELIÖSUMMIEN.SUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen neliösummien summan. +SUMXMY2 = EROTUSTEN.NELIÖSUMMA ## Palauttaa kahden matriisin toisiaan vastaavien arvojen erotusten neliösumman. +TAN = TAN ## Palauttaa luvun tangentin. +TANH = TANH ## Palauttaa luvun hyperbolisen tangentin. +TRUNC = KATKAISE ## Katkaisee luvun kokonaisluvuksi. + + +## +## Statistical functions Tilastolliset funktiot +## +AVEDEV = KESKIPOIKKEAMA ## Palauttaa hajontojen itseisarvojen keskiarvon. +AVERAGE = KESKIARVO ## Palauttaa argumenttien keskiarvon. +AVERAGEA = KESKIARVOA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, keskiarvon. +AVERAGEIF = KESKIARVO.JOS ## Palauttaa alueen niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka täyttävät annetut ehdot. +AVERAGEIFS = KESKIARVO.JOS.JOUKKO ## Palauttaa niiden solujen keskiarvon (aritmeettisen keskiarvon), jotka vastaavat useita ehtoja. +BETADIST = BEETAJAKAUMA ## Palauttaa kumulatiivisen beetajakaumafunktion arvon. +BETAINV = BEETAJAKAUMA.KÄÄNT ## Palauttaa määritetyn beetajakauman käänteisen kumulatiivisen jakaumafunktion arvon. +BINOMDIST = BINOMIJAKAUMA ## Palauttaa yksittäisen termin binomijakaumatodennäköisyyden. +CHIDIST = CHIJAKAUMA ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden. +CHIINV = CHIJAKAUMA.KÄÄNT ## Palauttaa yksisuuntaisen chi-neliön jakauman todennäköisyyden käänteisarvon. +CHITEST = CHITESTI ## Palauttaa riippumattomuustestin tuloksen. +CONFIDENCE = LUOTTAMUSVÄLI ## Palauttaa luottamusvälin populaation keskiarvolle. +CORREL = KORRELAATIO ## Palauttaa kahden arvojoukon korrelaatiokertoimen. +COUNT = LASKE ## Laskee argumenttiluettelossa olevien lukujen määrän. +COUNTA = LASKE.A ## Laskee argumenttiluettelossa olevien arvojen määrän. +COUNTBLANK = LASKE.TYHJÄT ## Laskee alueella olevien tyhjien solujen määrän. +COUNTIF = LASKE.JOS ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa annettuja ehtoja. +COUNTIFS = LASKE.JOS.JOUKKO ## Laskee alueella olevien sellaisten solujen määrän, joiden sisältö vastaa useita ehtoja. +COVAR = KOVARIANSSI ## Palauttaa kovarianssin, joka on keskiarvo havaintoaineiston kunkin pisteparin poikkeamien tuloista. +CRITBINOM = BINOMIJAKAUMA.KRIT ## Palauttaa pienimmän arvon, jossa binomijakauman kertymäfunktion arvo on pienempi tai yhtä suuri kuin vertailuarvo. +DEVSQ = OIKAISTU.NELIÖSUMMA ## Palauttaa keskipoikkeamien neliösumman. +EXPONDIST = EKSPONENTIAALIJAKAUMA ## Palauttaa eksponentiaalijakauman. +FDIST = FJAKAUMA ## Palauttaa F-todennäköisyysjakauman. +FINV = FJAKAUMA.KÄÄNT ## Palauttaa F-todennäköisyysjakauman käänteisfunktion. +FISHER = FISHER ## Palauttaa Fisher-muunnoksen. +FISHERINV = FISHER.KÄÄNT ## Palauttaa käänteisen Fisher-muunnoksen. +FORECAST = ENNUSTE ## Palauttaa lineaarisen trendin arvon. +FREQUENCY = TAAJUUS ## Palauttaa frekvenssijakautuman pystysuuntaisena matriisina. +FTEST = FTESTI ## Palauttaa F-testin tuloksen. +GAMMADIST = GAMMAJAKAUMA ## Palauttaa gammajakauman. +GAMMAINV = GAMMAJAKAUMA.KÄÄNT ## Palauttaa käänteisen gammajakauman kertymäfunktion. +GAMMALN = GAMMALN ## Palauttaa gammafunktion luonnollisen logaritmin G(x). +GEOMEAN = KESKIARVO.GEOM ## Palauttaa geometrisen keskiarvon. +GROWTH = KASVU ## Palauttaa eksponentiaalisen trendin arvon. +HARMEAN = KESKIARVO.HARM ## Palauttaa harmonisen keskiarvon. +HYPGEOMDIST = HYPERGEOM.JAKAUMA ## Palauttaa hypergeometrisen jakauman. +INTERCEPT = LEIKKAUSPISTE ## Palauttaa lineaarisen regressiosuoran leikkauspisteen. +KURT = KURT ## Palauttaa tietoalueen vinous-arvon eli huipukkuuden. +LARGE = SUURI ## Palauttaa tietojoukon k:nneksi suurimman arvon. +LINEST = LINREGR ## Palauttaa lineaarisen trendin parametrit. +LOGEST = LOGREGR ## Palauttaa eksponentiaalisen trendin parametrit. +LOGINV = LOGNORM.JAKAUMA.KÄÄNT ## Palauttaa lognormeeratun jakauman käänteisfunktion. +LOGNORMDIST = LOGNORM.JAKAUMA ## Palauttaa lognormaalisen jakauman kertymäfunktion. +MAX = MAKS ## Palauttaa suurimman arvon argumenttiluettelosta. +MAXA = MAKSA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, suurimman arvon. +MEDIAN = MEDIAANI ## Palauttaa annettujen lukujen mediaanin. +MIN = MIN ## Palauttaa pienimmän arvon argumenttiluettelosta. +MINA = MINA ## Palauttaa argumenttien, mukaan lukien lukujen, tekstin ja loogisten arvojen, pienimmän arvon. +MODE = MOODI ## Palauttaa tietojoukossa useimmin esiintyvän arvon. +NEGBINOMDIST = BINOMIJAKAUMA.NEG ## Palauttaa negatiivisen binomijakauman. +NORMDIST = NORM.JAKAUMA ## Palauttaa normaalijakauman kertymäfunktion. +NORMINV = NORM.JAKAUMA.KÄÄNT ## Palauttaa käänteisen normaalijakauman kertymäfunktion. +NORMSDIST = NORM.JAKAUMA.NORMIT ## Palauttaa normitetun normaalijakauman kertymäfunktion. +NORMSINV = NORM.JAKAUMA.NORMIT.KÄÄNT ## Palauttaa normitetun normaalijakauman kertymäfunktion käänteisarvon. +PEARSON = PEARSON ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen. +PERCENTILE = PROSENTTIPISTE ## Palauttaa alueen arvojen k:nnen prosenttipisteen. +PERCENTRANK = PROSENTTIJÄRJESTYS ## Palauttaa tietojoukon arvon prosentuaalisen järjestysluvun. +PERMUT = PERMUTAATIO ## Palauttaa mahdollisten permutaatioiden määrän annetulle objektien määrälle. +POISSON = POISSON ## Palauttaa Poissonin todennäköisyysjakauman. +PROB = TODENNÄKÖISYYS ## Palauttaa todennäköisyyden sille, että arvot ovat tietyltä väliltä. +QUARTILE = NELJÄNNES ## Palauttaa tietoalueen neljänneksen. +RANK = ARVON.MUKAAN ## Palauttaa luvun paikan lukuarvoluettelossa. +RSQ = PEARSON.NELIÖ ## Palauttaa Pearsonin tulomomenttikorrelaatiokertoimen neliön. +SKEW = JAKAUMAN.VINOUS ## Palauttaa jakauman vinouden. +SLOPE = KULMAKERROIN ## Palauttaa lineaarisen regressiosuoran kulmakertoimen. +SMALL = PIENI ## Palauttaa tietojoukon k:nneksi pienimmän arvon. +STANDARDIZE = NORMITA ## Palauttaa normitetun arvon. +STDEV = KESKIHAJONTA ## Laskee populaation keskihajonnan otoksen perusteella. +STDEVA = KESKIHAJONTAA ## Laskee populaation keskihajonnan otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. +STDEVP = KESKIHAJONTAP ## Laskee normaalijakautuman koko populaation perusteella. +STDEVPA = KESKIHAJONTAPA ## Laskee populaation keskihajonnan koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. +STEYX = KESKIVIRHE ## Palauttaa regression kutakin x-arvoa vastaavan ennustetun y-arvon keskivirheen. +TDIST = TJAKAUMA ## Palauttaa t-jakautuman. +TINV = TJAKAUMA.KÄÄNT ## Palauttaa käänteisen t-jakauman. +TREND = SUUNTAUS ## Palauttaa lineaarisen trendin arvoja. +TRIMMEAN = KESKIARVO.TASATTU ## Palauttaa tietojoukon tasatun keskiarvon. +TTEST = TTESTI ## Palauttaa t-testiin liittyvän todennäköisyyden. +VAR = VAR ## Arvioi populaation varianssia otoksen perusteella. +VARA = VARA ## Laskee populaation varianssin otoksen perusteella, mukaan lukien luvut, tekstin ja loogiset arvot. +VARP = VARP ## Laskee varianssin koko populaation perusteella. +VARPA = VARPA ## Laskee populaation varianssin koko populaation perusteella, mukaan lukien luvut, tekstin ja totuusarvot. +WEIBULL = WEIBULL ## Palauttaa Weibullin jakauman. +ZTEST = ZTESTI ## Palauttaa z-testin yksisuuntaisen todennäköisyysarvon. + + +## +## Text functions Tekstifunktiot +## +ASC = ASC ## Muuntaa merkkijonossa olevat englanninkieliset DBCS- tai katakana-merkit SBCS-merkeiksi. +BAHTTEXT = BAHTTEKSTI ## Muuntaa luvun tekstiksi ß (baht) -valuuttamuotoa käyttämällä. +CHAR = MERKKI ## Palauttaa koodin lukua vastaavan merkin. +CLEAN = SIIVOA ## Poistaa tekstistä kaikki tulostumattomat merkit. +CODE = KOODI ## Palauttaa tekstimerkkijonon ensimmäisen merkin numerokoodin. +CONCATENATE = KETJUTA ## Yhdistää useat merkkijonot yhdeksi merkkijonoksi. +DOLLAR = VALUUTTA ## Muuntaa luvun tekstiksi $ (dollari) -valuuttamuotoa käyttämällä. +EXACT = VERTAA ## Tarkistaa, ovatko kaksi tekstiarvoa samanlaiset. +FIND = ETSI ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). +FINDB = ETSIB ## Etsii tekstiarvon toisen tekstin sisältä (tunnistaa isot ja pienet kirjaimet). +FIXED = KIINTEÄ ## Muotoilee luvun tekstiksi, jossa on kiinteä määrä desimaaleja. +JIS = JIS ## Muuntaa merkkijonossa olevat englanninkieliset SBCS- tai katakana-merkit DBCS-merkeiksi. +LEFT = VASEN ## Palauttaa tekstiarvon vasemmanpuoliset merkit. +LEFTB = VASENB ## Palauttaa tekstiarvon vasemmanpuoliset merkit. +LEN = PITUUS ## Palauttaa tekstimerkkijonon merkkien määrän. +LENB = PITUUSB ## Palauttaa tekstimerkkijonon merkkien määrän. +LOWER = PIENET ## Muuntaa tekstin pieniksi kirjaimiksi. +MID = POIMI.TEKSTI ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. +MIDB = POIMI.TEKSTIB ## Palauttaa määritetyn määrän merkkejä merkkijonosta alkaen annetusta kohdasta. +PHONETIC = FONEETTINEN ## Hakee foneettiset (furigana) merkit merkkijonosta. +PROPER = ERISNIMI ## Muuttaa merkkijonon kunkin sanan ensimmäisen kirjaimen isoksi. +REPLACE = KORVAA ## Korvaa tekstissä olevat merkit. +REPLACEB = KORVAAB ## Korvaa tekstissä olevat merkit. +REPT = TOISTA ## Toistaa tekstin annetun määrän kertoja. +RIGHT = OIKEA ## Palauttaa tekstiarvon oikeanpuoliset merkit. +RIGHTB = OIKEAB ## Palauttaa tekstiarvon oikeanpuoliset merkit. +SEARCH = KÄY.LÄPI ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). +SEARCHB = KÄY.LÄPIB ## Etsii tekstiarvon toisen tekstin sisältä (isot ja pienet kirjaimet tulkitaan samoiksi merkeiksi). +SUBSTITUTE = VAIHDA ## Korvaa merkkijonossa olevan tekstin toisella. +T = T ## Muuntaa argumentit tekstiksi. +TEXT = TEKSTI ## Muotoilee luvun ja muuntaa sen tekstiksi. +TRIM = POISTA.VÄLIT ## Poistaa välilyönnit tekstistä. +UPPER = ISOT ## Muuntaa tekstin isoiksi kirjaimiksi. +VALUE = ARVO ## Muuntaa tekstiargumentin luvuksi. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/config new file mode 100644 index 00000000..1f5db88c --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NUL! +DIV0 = #DIV/0! +VALUE = #VALEUR! +REF = #REF! +NAME = #NOM? +NUM = #NOMBRE! +NA = #N/A diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/functions new file mode 100644 index 00000000..03b80e5a --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/fr/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Fonctions de complément et d’automatisation +## +GETPIVOTDATA = LIREDONNEESTABCROISDYNAMIQUE ## Renvoie les données stockées dans un rapport de tableau croisé dynamique. + + +## +## Cube functions Fonctions Cube +## +CUBEKPIMEMBER = MEMBREKPICUBE ## Renvoie un nom, une propriété et une mesure d’indicateur de performance clé et affiche le nom et la propriété dans la cellule. Un indicateur de performance clé est une mesure quantifiable, telle que la marge bénéficiaire brute mensuelle ou la rotation trimestrielle du personnel, utilisée pour évaluer les performances d’une entreprise. +CUBEMEMBER = MEMBRECUBE ## Renvoie un membre ou un uplet dans une hiérarchie de cubes. Utilisez cette fonction pour valider l’existence du membre ou de l’uplet dans le cube. +CUBEMEMBERPROPERTY = PROPRIETEMEMBRECUBE ## Renvoie la valeur d’une propriété de membre du cube. Utilisez cette fonction pour valider l’existence d’un nom de membre dans le cube et pour renvoyer la propriété spécifiée pour ce membre. +CUBERANKEDMEMBER = RANGMEMBRECUBE ## Renvoie le nième membre ou le membre placé à un certain rang dans un ensemble. Utilisez cette fonction pour renvoyer un ou plusieurs éléments d’un ensemble, tels que les meilleurs vendeurs ou les 10 meilleurs étudiants. +CUBESET = JEUCUBE ## Définit un ensemble calculé de membres ou d’uplets en envoyant une expression définie au cube sur le serveur qui crée l’ensemble et le renvoie à Microsoft Office Excel. +CUBESETCOUNT = NBJEUCUBE ## Renvoie le nombre d’éléments dans un jeu. +CUBEVALUE = VALEURCUBE ## Renvoie une valeur d’agrégation issue d’un cube. + + +## +## Database functions Fonctions de base de données +## +DAVERAGE = BDMOYENNE ## Renvoie la moyenne des entrées de base de données sélectionnées. +DCOUNT = BCOMPTE ## Compte le nombre de cellules d’une base de données qui contiennent des nombres. +DCOUNTA = BDNBVAL ## Compte les cellules non vides d’une base de données. +DGET = BDLIRE ## Extrait d’une base de données un enregistrement unique répondant aux critères spécifiés. +DMAX = BDMAX ## Renvoie la valeur maximale des entrées de base de données sélectionnées. +DMIN = BDMIN ## Renvoie la valeur minimale des entrées de base de données sélectionnées. +DPRODUCT = BDPRODUIT ## Multiplie les valeurs d’un champ particulier des enregistrements d’une base de données, qui répondent aux critères spécifiés. +DSTDEV = BDECARTYPE ## Calcule l’écart type pour un échantillon d’entrées de base de données sélectionnées. +DSTDEVP = BDECARTYPEP ## Calcule l’écart type pour l’ensemble d’une population d’entrées de base de données sélectionnées. +DSUM = BDSOMME ## Ajoute les nombres dans la colonne de champ des enregistrements de la base de données, qui répondent aux critères. +DVAR = BDVAR ## Calcule la variance pour un échantillon d’entrées de base de données sélectionnées. +DVARP = BDVARP ## Calcule la variance pour l’ensemble d’une population d’entrées de base de données sélectionnées. + + +## +## Date and time functions Fonctions de date et d’heure +## +DATE = DATE ## Renvoie le numéro de série d’une date précise. +DATEVALUE = DATEVAL ## Convertit une date représentée sous forme de texte en numéro de série. +DAY = JOUR ## Convertit un numéro de série en jour du mois. +DAYS360 = JOURS360 ## Calcule le nombre de jours qui séparent deux dates sur la base d’une année de 360 jours. +EDATE = MOIS.DECALER ## Renvoie le numéro séquentiel de la date qui représente une date spécifiée (l’argument date_départ), corrigée en plus ou en moins du nombre de mois indiqué. +EOMONTH = FIN.MOIS ## Renvoie le numéro séquentiel de la date du dernier jour du mois précédant ou suivant la date_départ du nombre de mois indiqué. +HOUR = HEURE ## Convertit un numéro de série en heure. +MINUTE = MINUTE ## Convertit un numéro de série en minute. +MONTH = MOIS ## Convertit un numéro de série en mois. +NETWORKDAYS = NB.JOURS.OUVRES ## Renvoie le nombre de jours ouvrés entiers compris entre deux dates. +NOW = MAINTENANT ## Renvoie le numéro de série de la date et de l’heure du jour. +SECOND = SECONDE ## Convertit un numéro de série en seconde. +TIME = TEMPS ## Renvoie le numéro de série d’une heure précise. +TIMEVALUE = TEMPSVAL ## Convertit une date représentée sous forme de texte en numéro de série. +TODAY = AUJOURDHUI ## Renvoie le numéro de série de la date du jour. +WEEKDAY = JOURSEM ## Convertit un numéro de série en jour de la semaine. +WEEKNUM = NO.SEMAINE ## Convertit un numéro de série en un numéro représentant l’ordre de la semaine dans l’année. +WORKDAY = SERIE.JOUR.OUVRE ## Renvoie le numéro de série de la date avant ou après le nombre de jours ouvrés spécifiés. +YEAR = ANNEE ## Convertit un numéro de série en année. +YEARFRAC = FRACTION.ANNEE ## Renvoie la fraction de l’année représentant le nombre de jours entre la date de début et la date de fin. + + +## +## Engineering functions Fonctions d’ingénierie +## +BESSELI = BESSELI ## Renvoie la fonction Bessel modifiée In(x). +BESSELJ = BESSELJ ## Renvoie la fonction Bessel Jn(x). +BESSELK = BESSELK ## Renvoie la fonction Bessel modifiée Kn(x). +BESSELY = BESSELY ## Renvoie la fonction Bessel Yn(x). +BIN2DEC = BINDEC ## Convertit un nombre binaire en nombre décimal. +BIN2HEX = BINHEX ## Convertit un nombre binaire en nombre hexadécimal. +BIN2OCT = BINOCT ## Convertit un nombre binaire en nombre octal. +COMPLEX = COMPLEXE ## Convertit des coefficients réel et imaginaire en un nombre complexe. +CONVERT = CONVERT ## Convertit un nombre d’une unité de mesure à une autre. +DEC2BIN = DECBIN ## Convertit un nombre décimal en nombre binaire. +DEC2HEX = DECHEX ## Convertit un nombre décimal en nombre hexadécimal. +DEC2OCT = DECOCT ## Convertit un nombre décimal en nombre octal. +DELTA = DELTA ## Teste l’égalité de deux nombres. +ERF = ERF ## Renvoie la valeur de la fonction d’erreur. +ERFC = ERFC ## Renvoie la valeur de la fonction d’erreur complémentaire. +GESTEP = SUP.SEUIL ## Teste si un nombre est supérieur à une valeur de seuil. +HEX2BIN = HEXBIN ## Convertit un nombre hexadécimal en nombre binaire. +HEX2DEC = HEXDEC ## Convertit un nombre hexadécimal en nombre décimal. +HEX2OCT = HEXOCT ## Convertit un nombre hexadécimal en nombre octal. +IMABS = COMPLEXE.MODULE ## Renvoie la valeur absolue (module) d’un nombre complexe. +IMAGINARY = COMPLEXE.IMAGINAIRE ## Renvoie le coefficient imaginaire d’un nombre complexe. +IMARGUMENT = COMPLEXE.ARGUMENT ## Renvoie l’argument thêta, un angle exprimé en radians. +IMCONJUGATE = COMPLEXE.CONJUGUE ## Renvoie le nombre complexe conjugué d’un nombre complexe. +IMCOS = IMCOS ## Renvoie le cosinus d’un nombre complexe. +IMDIV = COMPLEXE.DIV ## Renvoie le quotient de deux nombres complexes. +IMEXP = COMPLEXE.EXP ## Renvoie la fonction exponentielle d’un nombre complexe. +IMLN = COMPLEXE.LN ## Renvoie le logarithme népérien d’un nombre complexe. +IMLOG10 = COMPLEXE.LOG10 ## Calcule le logarithme en base 10 d’un nombre complexe. +IMLOG2 = COMPLEXE.LOG2 ## Calcule le logarithme en base 2 d’un nombre complexe. +IMPOWER = COMPLEXE.PUISSANCE ## Renvoie un nombre complexe élevé à une puissance entière. +IMPRODUCT = COMPLEXE.PRODUIT ## Renvoie le produit de plusieurs nombres complexes. +IMREAL = COMPLEXE.REEL ## Renvoie le coefficient réel d’un nombre complexe. +IMSIN = COMPLEXE.SIN ## Renvoie le sinus d’un nombre complexe. +IMSQRT = COMPLEXE.RACINE ## Renvoie la racine carrée d’un nombre complexe. +IMSUB = COMPLEXE.DIFFERENCE ## Renvoie la différence entre deux nombres complexes. +IMSUM = COMPLEXE.SOMME ## Renvoie la somme de plusieurs nombres complexes. +OCT2BIN = OCTBIN ## Convertit un nombre octal en nombre binaire. +OCT2DEC = OCTDEC ## Convertit un nombre octal en nombre décimal. +OCT2HEX = OCTHEX ## Convertit un nombre octal en nombre hexadécimal. + + +## +## Financial functions Fonctions financières +## +ACCRINT = INTERET.ACC ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu périodiquement. +ACCRINTM = INTERET.ACC.MAT ## Renvoie l’intérêt couru non échu d’un titre dont l’intérêt est perçu à l’échéance. +AMORDEGRC = AMORDEGRC ## Renvoie l’amortissement correspondant à chaque période comptable en utilisant un coefficient d’amortissement. +AMORLINC = AMORLINC ## Renvoie l’amortissement d’un bien à la fin d’une période fiscale donnée. +COUPDAYBS = NB.JOURS.COUPON.PREC ## Renvoie le nombre de jours entre le début de la période de coupon et la date de liquidation. +COUPDAYS = NB.JOURS.COUPONS ## Renvoie le nombre de jours pour la période du coupon contenant la date de liquidation. +COUPDAYSNC = NB.JOURS.COUPON.SUIV ## Renvoie le nombre de jours entre la date de liquidation et la date du coupon suivant la date de liquidation. +COUPNCD = DATE.COUPON.SUIV ## Renvoie la première date de coupon ultérieure à la date de règlement. +COUPNUM = NB.COUPONS ## Renvoie le nombre de coupons dus entre la date de règlement et la date d’échéance. +COUPPCD = DATE.COUPON.PREC ## Renvoie la date de coupon précédant la date de règlement. +CUMIPMT = CUMUL.INTER ## Renvoie l’intérêt cumulé payé sur un emprunt entre deux périodes. +CUMPRINC = CUMUL.PRINCPER ## Renvoie le montant cumulé des remboursements du capital d’un emprunt effectués entre deux périodes. +DB = DB ## Renvoie l’amortissement d’un bien pour une période spécifiée en utilisant la méthode de l’amortissement dégressif à taux fixe. +DDB = DDB ## Renvoie l’amortissement d’un bien pour toute période spécifiée, en utilisant la méthode de l’amortissement dégressif à taux double ou selon un coefficient à spécifier. +DISC = TAUX.ESCOMPTE ## Calcule le taux d’escompte d’une transaction. +DOLLARDE = PRIX.DEC ## Convertit un prix en euros, exprimé sous forme de fraction, en un prix en euros exprimé sous forme de nombre décimal. +DOLLARFR = PRIX.FRAC ## Convertit un prix en euros, exprimé sous forme de nombre décimal, en un prix en euros exprimé sous forme de fraction. +DURATION = DUREE ## Renvoie la durée, en années, d’un titre dont l’intérêt est perçu périodiquement. +EFFECT = TAUX.EFFECTIF ## Renvoie le taux d’intérêt annuel effectif. +FV = VC ## Renvoie la valeur future d’un investissement. +FVSCHEDULE = VC.PAIEMENTS ## Calcule la valeur future d’un investissement en appliquant une série de taux d’intérêt composites. +INTRATE = TAUX.INTERET ## Affiche le taux d’intérêt d’un titre totalement investi. +IPMT = INTPER ## Calcule le montant des intérêts d’un investissement pour une période donnée. +IRR = TRI ## Calcule le taux de rentabilité interne d’un investissement pour une succession de trésoreries. +ISPMT = ISPMT ## Calcule le montant des intérêts d’un investissement pour une période donnée. +MDURATION = DUREE.MODIFIEE ## Renvoie la durée de Macauley modifiée pour un titre ayant une valeur nominale hypothétique de 100_euros. +MIRR = TRIM ## Calcule le taux de rentabilité interne lorsque les paiements positifs et négatifs sont financés à des taux différents. +NOMINAL = TAUX.NOMINAL ## Calcule le taux d’intérêt nominal annuel. +NPER = NPM ## Renvoie le nombre de versements nécessaires pour rembourser un emprunt. +NPV = VAN ## Calcule la valeur actuelle nette d’un investissement basé sur une série de décaissements et un taux d’escompte. +ODDFPRICE = PRIX.PCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. +ODDFYIELD = REND.PCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la première période de coupon est irrégulière. +ODDLPRICE = PRIX.DCOUPON.IRREG ## Renvoie le prix par tranche de valeur nominale de 100 euros d’un titre dont la première période de coupon est irrégulière. +ODDLYIELD = REND.DCOUPON.IRREG ## Renvoie le taux de rendement d’un titre dont la dernière période de coupon est irrégulière. +PMT = VPM ## Calcule le paiement périodique d’un investissement donné. +PPMT = PRINCPER ## Calcule, pour une période donnée, la part de remboursement du principal d’un investissement. +PRICE = PRIX.TITRE ## Renvoie le prix d’un titre rapportant des intérêts périodiques, pour une valeur nominale de 100 euros. +PRICEDISC = VALEUR.ENCAISSEMENT ## Renvoie la valeur d’encaissement d’un escompte commercial, pour une valeur nominale de 100 euros. +PRICEMAT = PRIX.TITRE.ECHEANCE ## Renvoie le prix d’un titre dont la valeur nominale est 100 euros et qui rapporte des intérêts à l’échéance. +PV = PV ## Calcule la valeur actuelle d’un investissement. +RATE = TAUX ## Calcule le taux d’intérêt par période pour une annuité. +RECEIVED = VALEUR.NOMINALE ## Renvoie la valeur nominale à échéance d’un effet de commerce. +SLN = AMORLIN ## Calcule l’amortissement linéaire d’un bien pour une période donnée. +SYD = SYD ## Calcule l’amortissement d’un bien pour une période donnée sur la base de la méthode américaine Sum-of-Years Digits (amortissement dégressif à taux décroissant appliqué à une valeur constante). +TBILLEQ = TAUX.ESCOMPTE.R ## Renvoie le taux d’escompte rationnel d’un bon du Trésor. +TBILLPRICE = PRIX.BON.TRESOR ## Renvoie le prix d’un bon du Trésor d’une valeur nominale de 100 euros. +TBILLYIELD = RENDEMENT.BON.TRESOR ## Calcule le taux de rendement d’un bon du Trésor. +VDB = VDB ## Renvoie l’amortissement d’un bien pour une période spécifiée ou partielle en utilisant une méthode de l’amortissement dégressif à taux fixe. +XIRR = TRI.PAIEMENTS ## Calcule le taux de rentabilité interne d’un ensemble de paiements non périodiques. +XNPV = VAN.PAIEMENTS ## Renvoie la valeur actuelle nette d’un ensemble de paiements non périodiques. +YIELD = RENDEMENT.TITRE ## Calcule le rendement d’un titre rapportant des intérêts périodiquement. +YIELDDISC = RENDEMENT.SIMPLE ## Calcule le taux de rendement d’un emprunt à intérêt simple (par exemple, un bon du Trésor). +YIELDMAT = RENDEMENT.TITRE.ECHEANCE ## Renvoie le rendement annuel d’un titre qui rapporte des intérêts à l’échéance. + + +## +## Information functions Fonctions d’information +## +CELL = CELLULE ## Renvoie des informations sur la mise en forme, l’emplacement et le contenu d’une cellule. +ERROR.TYPE = TYPE.ERREUR ## Renvoie un nombre correspondant à un type d’erreur. +INFO = INFORMATIONS ## Renvoie des informations sur l’environnement d’exploitation actuel. +ISBLANK = ESTVIDE ## Renvoie VRAI si l’argument valeur est vide. +ISERR = ESTERR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur, sauf #N/A. +ISERROR = ESTERREUR ## Renvoie VRAI si l’argument valeur fait référence à une valeur d’erreur. +ISEVEN = EST.PAIR ## Renvoie VRAI si le chiffre est pair. +ISLOGICAL = ESTLOGIQUE ## Renvoie VRAI si l’argument valeur fait référence à une valeur logique. +ISNA = ESTNA ## Renvoie VRAI si l’argument valeur fait référence à la valeur d’erreur #N/A. +ISNONTEXT = ESTNONTEXTE ## Renvoie VRAI si l’argument valeur ne se présente pas sous forme de texte. +ISNUMBER = ESTNUM ## Renvoie VRAI si l’argument valeur représente un nombre. +ISODD = EST.IMPAIR ## Renvoie VRAI si le chiffre est impair. +ISREF = ESTREF ## Renvoie VRAI si l’argument valeur est une référence. +ISTEXT = ESTTEXTE ## Renvoie VRAI si l’argument valeur se présente sous forme de texte. +N = N ## Renvoie une valeur convertie en nombre. +NA = NA ## Renvoie la valeur d’erreur #N/A. +TYPE = TYPE ## Renvoie un nombre indiquant le type de données d’une valeur. + + +## +## Logical functions Fonctions logiques +## +AND = ET ## Renvoie VRAI si tous ses arguments sont VRAI. +FALSE = FAUX ## Renvoie la valeur logique FAUX. +IF = SI ## Spécifie un test logique à effectuer. +IFERROR = SIERREUR ## Renvoie une valeur que vous spécifiez si une formule génère une erreur ; sinon, elle renvoie le résultat de la formule. +NOT = NON ## Inverse la logique de cet argument. +OR = OU ## Renvoie VRAI si un des arguments est VRAI. +TRUE = VRAI ## Renvoie la valeur logique VRAI. + + +## +## Lookup and reference functions Fonctions de recherche et de référence +## +ADDRESS = ADRESSE ## Renvoie une référence sous forme de texte à une seule cellule d’une feuille de calcul. +AREAS = ZONES ## Renvoie le nombre de zones dans une référence. +CHOOSE = CHOISIR ## Choisit une valeur dans une liste. +COLUMN = COLONNE ## Renvoie le numéro de colonne d’une référence. +COLUMNS = COLONNES ## Renvoie le nombre de colonnes dans une référence. +HLOOKUP = RECHERCHEH ## Effectue une recherche dans la première ligne d’une matrice et renvoie la valeur de la cellule indiquée. +HYPERLINK = LIEN_HYPERTEXTE ## Crée un raccourci ou un renvoi qui ouvre un document stocké sur un serveur réseau, sur un réseau Intranet ou sur Internet. +INDEX = INDEX ## Utilise un index pour choisir une valeur provenant d’une référence ou d’une matrice. +INDIRECT = INDIRECT ## Renvoie une référence indiquée par une valeur de texte. +LOOKUP = RECHERCHE ## Recherche des valeurs dans un vecteur ou une matrice. +MATCH = EQUIV ## Recherche des valeurs dans une référence ou une matrice. +OFFSET = DECALER ## Renvoie une référence décalée par rapport à une référence donnée. +ROW = LIGNE ## Renvoie le numéro de ligne d’une référence. +ROWS = LIGNES ## Renvoie le nombre de lignes dans une référence. +RTD = RTD ## Extrait les données en temps réel à partir d’un programme prenant en charge l’automation COM (Automation : utilisation des objets d'une application à partir d'une autre application ou d'un autre outil de développement. Autrefois appelée OLE Automation, Automation est une norme industrielle et une fonctionnalité du modèle d'objet COM (Component Object Model).). +TRANSPOSE = TRANSPOSE ## Renvoie la transposition d’une matrice. +VLOOKUP = RECHERCHEV ## Effectue une recherche dans la première colonne d’une matrice et se déplace sur la ligne pour renvoyer la valeur d’une cellule. + + +## +## Math and trigonometry functions Fonctions mathématiques et trigonométriques +## +ABS = ABS ## Renvoie la valeur absolue d’un nombre. +ACOS = ACOS ## Renvoie l’arccosinus d’un nombre. +ACOSH = ACOSH ## Renvoie le cosinus hyperbolique inverse d’un nombre. +ASIN = ASIN ## Renvoie l’arcsinus d’un nombre. +ASINH = ASINH ## Renvoie le sinus hyperbolique inverse d’un nombre. +ATAN = ATAN ## Renvoie l’arctangente d’un nombre. +ATAN2 = ATAN2 ## Renvoie l’arctangente des coordonnées x et y. +ATANH = ATANH ## Renvoie la tangente hyperbolique inverse d’un nombre. +CEILING = PLAFOND ## Arrondit un nombre au nombre entier le plus proche ou au multiple le plus proche de l’argument précision en s’éloignant de zéro. +COMBIN = COMBIN ## Renvoie le nombre de combinaisons que l’on peut former avec un nombre donné d’objets. +COS = COS ## Renvoie le cosinus d’un nombre. +COSH = COSH ## Renvoie le cosinus hyperbolique d’un nombre. +DEGREES = DEGRES ## Convertit des radians en degrés. +EVEN = PAIR ## Arrondit un nombre au nombre entier pair le plus proche en s’éloignant de zéro. +EXP = EXP ## Renvoie e élevé à la puissance d’un nombre donné. +FACT = FACT ## Renvoie la factorielle d’un nombre. +FACTDOUBLE = FACTDOUBLE ## Renvoie la factorielle double d’un nombre. +FLOOR = PLANCHER ## Arrondit un nombre en tendant vers 0 (zéro). +GCD = PGCD ## Renvoie le plus grand commun diviseur. +INT = ENT ## Arrondit un nombre à l’entier immédiatement inférieur. +LCM = PPCM ## Renvoie le plus petit commun multiple. +LN = LN ## Renvoie le logarithme népérien d’un nombre. +LOG = LOG ## Renvoie le logarithme d’un nombre dans la base spécifiée. +LOG10 = LOG10 ## Calcule le logarithme en base 10 d’un nombre. +MDETERM = DETERMAT ## Renvoie le déterminant d’une matrice. +MINVERSE = INVERSEMAT ## Renvoie la matrice inverse d’une matrice. +MMULT = PRODUITMAT ## Renvoie le produit de deux matrices. +MOD = MOD ## Renvoie le reste d’une division. +MROUND = ARRONDI.AU.MULTIPLE ## Donne l’arrondi d’un nombre au multiple spécifié. +MULTINOMIAL = MULTINOMIALE ## Calcule la multinomiale d’un ensemble de nombres. +ODD = IMPAIR ## Renvoie le nombre, arrondi à la valeur du nombre entier impair le plus proche en s’éloignant de zéro. +PI = PI ## Renvoie la valeur de pi. +POWER = PUISSANCE ## Renvoie la valeur du nombre élevé à une puissance. +PRODUCT = PRODUIT ## Multiplie ses arguments. +QUOTIENT = QUOTIENT ## Renvoie la partie entière du résultat d’une division. +RADIANS = RADIANS ## Convertit des degrés en radians. +RAND = ALEA ## Renvoie un nombre aléatoire compris entre 0 et 1. +RANDBETWEEN = ALEA.ENTRE.BORNES ## Renvoie un nombre aléatoire entre les nombres que vous spécifiez. +ROMAN = ROMAIN ## Convertit des chiffres arabes en chiffres romains, sous forme de texte. +ROUND = ARRONDI ## Arrondit un nombre au nombre de chiffres indiqué. +ROUNDDOWN = ARRONDI.INF ## Arrondit un nombre en tendant vers 0 (zéro). +ROUNDUP = ARRONDI.SUP ## Arrondit un nombre à l’entier supérieur, en s’éloignant de zéro. +SERIESSUM = SOMME.SERIES ## Renvoie la somme d’une série géométrique en s’appuyant sur la formule suivante : +SIGN = SIGNE ## Renvoie le signe d’un nombre. +SIN = SIN ## Renvoie le sinus d’un angle donné. +SINH = SINH ## Renvoie le sinus hyperbolique d’un nombre. +SQRT = RACINE ## Renvoie la racine carrée d’un nombre. +SQRTPI = RACINE.PI ## Renvoie la racine carrée de (nombre * pi). +SUBTOTAL = SOUS.TOTAL ## Renvoie un sous-total dans une liste ou une base de données. +SUM = SOMME ## Calcule la somme de ses arguments. +SUMIF = SOMME.SI ## Additionne les cellules spécifiées si elles répondent à un critère donné. +SUMIFS = SOMME.SI.ENS ## Ajoute les cellules d’une plage qui répondent à plusieurs critères. +SUMPRODUCT = SOMMEPROD ## Multiplie les valeurs correspondantes des matrices spécifiées et calcule la somme de ces produits. +SUMSQ = SOMME.CARRES ## Renvoie la somme des carrés des arguments. +SUMX2MY2 = SOMME.X2MY2 ## Renvoie la somme de la différence des carrés des valeurs correspondantes de deux matrices. +SUMX2PY2 = SOMME.X2PY2 ## Renvoie la somme de la somme des carrés des valeurs correspondantes de deux matrices. +SUMXMY2 = SOMME.XMY2 ## Renvoie la somme des carrés des différences entre les valeurs correspondantes de deux matrices. +TAN = TAN ## Renvoie la tangente d’un nombre. +TANH = TANH ## Renvoie la tangente hyperbolique d’un nombre. +TRUNC = TRONQUE ## Renvoie la partie entière d’un nombre. + + +## +## Statistical functions Fonctions statistiques +## +AVEDEV = ECART.MOYEN ## Renvoie la moyenne des écarts absolus observés dans la moyenne des points de données. +AVERAGE = MOYENNE ## Renvoie la moyenne de ses arguments. +AVERAGEA = AVERAGEA ## Renvoie la moyenne de ses arguments, nombres, texte et valeurs logiques inclus. +AVERAGEIF = MOYENNE.SI ## Renvoie la moyenne (arithmétique) de toutes les cellules d’une plage qui répondent à des critères donnés. +AVERAGEIFS = MOYENNE.SI.ENS ## Renvoie la moyenne (arithmétique) de toutes les cellules qui répondent à plusieurs critères. +BETADIST = LOI.BETA ## Renvoie la fonction de distribution cumulée. +BETAINV = BETA.INVERSE ## Renvoie l’inverse de la fonction de distribution cumulée pour une distribution bêta spécifiée. +BINOMDIST = LOI.BINOMIALE ## Renvoie la probabilité d’une variable aléatoire discrète suivant la loi binomiale. +CHIDIST = LOI.KHIDEUX ## Renvoie la probabilité unilatérale de la distribution khi-deux. +CHIINV = KHIDEUX.INVERSE ## Renvoie l’inverse de la probabilité unilatérale de la distribution khi-deux. +CHITEST = TEST.KHIDEUX ## Renvoie le test d’indépendance. +CONFIDENCE = INTERVALLE.CONFIANCE ## Renvoie l’intervalle de confiance pour une moyenne de population. +CORREL = COEFFICIENT.CORRELATION ## Renvoie le coefficient de corrélation entre deux séries de données. +COUNT = NB ## Détermine les nombres compris dans la liste des arguments. +COUNTA = NBVAL ## Détermine le nombre de valeurs comprises dans la liste des arguments. +COUNTBLANK = NB.VIDE ## Compte le nombre de cellules vides dans une plage. +COUNTIF = NB.SI ## Compte le nombre de cellules qui répondent à un critère donné dans une plage. +COUNTIFS = NB.SI.ENS ## Compte le nombre de cellules à l’intérieur d’une plage qui répondent à plusieurs critères. +COVAR = COVARIANCE ## Renvoie la covariance, moyenne des produits des écarts pour chaque série d’observations. +CRITBINOM = CRITERE.LOI.BINOMIALE ## Renvoie la plus petite valeur pour laquelle la distribution binomiale cumulée est inférieure ou égale à une valeur de critère. +DEVSQ = SOMME.CARRES.ECARTS ## Renvoie la somme des carrés des écarts. +EXPONDIST = LOI.EXPONENTIELLE ## Renvoie la distribution exponentielle. +FDIST = LOI.F ## Renvoie la distribution de probabilité F. +FINV = INVERSE.LOI.F ## Renvoie l’inverse de la distribution de probabilité F. +FISHER = FISHER ## Renvoie la transformation de Fisher. +FISHERINV = FISHER.INVERSE ## Renvoie l’inverse de la transformation de Fisher. +FORECAST = PREVISION ## Calcule une valeur par rapport à une tendance linéaire. +FREQUENCY = FREQUENCE ## Calcule la fréquence d’apparition des valeurs dans une plage de valeurs, puis renvoie des nombres sous forme de matrice verticale. +FTEST = TEST.F ## Renvoie le résultat d’un test F. +GAMMADIST = LOI.GAMMA ## Renvoie la probabilité d’une variable aléatoire suivant une loi Gamma. +GAMMAINV = LOI.GAMMA.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi Gamma. +GAMMALN = LNGAMMA ## Renvoie le logarithme népérien de la fonction Gamma, G(x) +GEOMEAN = MOYENNE.GEOMETRIQUE ## Renvoie la moyenne géométrique. +GROWTH = CROISSANCE ## Calcule des valeurs par rapport à une tendance exponentielle. +HARMEAN = MOYENNE.HARMONIQUE ## Renvoie la moyenne harmonique. +HYPGEOMDIST = LOI.HYPERGEOMETRIQUE ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi hypergéométrique. +INTERCEPT = ORDONNEE.ORIGINE ## Renvoie l’ordonnée à l’origine d’une droite de régression linéaire. +KURT = KURTOSIS ## Renvoie le kurtosis d’une série de données. +LARGE = GRANDE.VALEUR ## Renvoie la k-ième plus grande valeur d’une série de données. +LINEST = DROITEREG ## Renvoie les paramètres d’une tendance linéaire. +LOGEST = LOGREG ## Renvoie les paramètres d’une tendance exponentielle. +LOGINV = LOI.LOGNORMALE.INVERSE ## Renvoie l’inverse de la probabilité pour une variable aléatoire suivant la loi lognormale. +LOGNORMDIST = LOI.LOGNORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi lognormale. +MAX = MAX ## Renvoie la valeur maximale contenue dans une liste d’arguments. +MAXA = MAXA ## Renvoie la valeur maximale d’une liste d’arguments, nombres, texte et valeurs logiques inclus. +MEDIAN = MEDIANE ## Renvoie la valeur médiane des nombres donnés. +MIN = MIN ## Renvoie la valeur minimale contenue dans une liste d’arguments. +MINA = MINA ## Renvoie la plus petite valeur d’une liste d’arguments, nombres, texte et valeurs logiques inclus. +MODE = MODE ## Renvoie la valeur la plus courante d’une série de données. +NEGBINOMDIST = LOI.BINOMIALE.NEG ## Renvoie la probabilité d’une variable aléatoire discrète suivant une loi binomiale négative. +NORMDIST = LOI.NORMALE ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale. +NORMINV = LOI.NORMALE.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi normale standard. +NORMSDIST = LOI.NORMALE.STANDARD ## Renvoie la probabilité d’une variable aléatoire continue suivant une loi normale standard. +NORMSINV = LOI.NORMALE.STANDARD.INVERSE ## Renvoie l’inverse de la distribution cumulée normale standard. +PEARSON = PEARSON ## Renvoie le coefficient de corrélation d’échantillonnage de Pearson. +PERCENTILE = CENTILE ## Renvoie le k-ième centile des valeurs d’une plage. +PERCENTRANK = RANG.POURCENTAGE ## Renvoie le rang en pourcentage d’une valeur d’une série de données. +PERMUT = PERMUTATION ## Renvoie le nombre de permutations pour un nombre donné d’objets. +POISSON = LOI.POISSON ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Poisson. +PROB = PROBABILITE ## Renvoie la probabilité que des valeurs d’une plage soient comprises entre deux limites. +QUARTILE = QUARTILE ## Renvoie le quartile d’une série de données. +RANK = RANG ## Renvoie le rang d’un nombre contenu dans une liste. +RSQ = COEFFICIENT.DETERMINATION ## Renvoie la valeur du coefficient de détermination R^2 d’une régression linéaire. +SKEW = COEFFICIENT.ASYMETRIE ## Renvoie l’asymétrie d’une distribution. +SLOPE = PENTE ## Renvoie la pente d’une droite de régression linéaire. +SMALL = PETITE.VALEUR ## Renvoie la k-ième plus petite valeur d’une série de données. +STANDARDIZE = CENTREE.REDUITE ## Renvoie une valeur centrée réduite. +STDEV = ECARTYPE ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population. +STDEVA = STDEVA ## Évalue l’écart type d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques inclus. +STDEVP = ECARTYPEP ## Calcule l’écart type d’une population à partir de la population entière. +STDEVPA = STDEVPA ## Calcule l’écart type d’une population à partir de l’ensemble de la population, nombres, texte et valeurs logiques inclus. +STEYX = ERREUR.TYPE.XY ## Renvoie l’erreur type de la valeur y prévue pour chaque x de la régression. +TDIST = LOI.STUDENT ## Renvoie la probabilité d’une variable aléatoire suivant une loi T de Student. +TINV = LOI.STUDENT.INVERSE ## Renvoie, pour une probabilité donnée, la valeur d’une variable aléatoire suivant une loi T de Student. +TREND = TENDANCE ## Renvoie des valeurs par rapport à une tendance linéaire. +TRIMMEAN = MOYENNE.REDUITE ## Renvoie la moyenne de l’intérieur d’une série de données. +TTEST = TEST.STUDENT ## Renvoie la probabilité associée à un test T de Student. +VAR = VAR ## Calcule la variance sur la base d’un échantillon. +VARA = VARA ## Estime la variance d’une population en se basant sur un échantillon de cette population, nombres, texte et valeurs logiques incluses. +VARP = VAR.P ## Calcule la variance sur la base de l’ensemble de la population. +VARPA = VARPA ## Calcule la variance d’une population en se basant sur la population entière, nombres, texte et valeurs logiques inclus. +WEIBULL = LOI.WEIBULL ## Renvoie la probabilité d’une variable aléatoire suivant une loi de Weibull. +ZTEST = TEST.Z ## Renvoie la valeur de probabilité unilatérale d’un test z. + + +## +## Text functions Fonctions de texte +## +ASC = ASC ## Change les caractères anglais ou katakana à pleine chasse (codés sur deux octets) à l’intérieur d’une chaîne de caractères en caractères à demi-chasse (codés sur un octet). +BAHTTEXT = BAHTTEXT ## Convertit un nombre en texte en utilisant le format monétaire ß (baht). +CHAR = CAR ## Renvoie le caractère spécifié par le code numérique. +CLEAN = EPURAGE ## Supprime tous les caractères de contrôle du texte. +CODE = CODE ## Renvoie le numéro de code du premier caractère du texte. +CONCATENATE = CONCATENER ## Assemble plusieurs éléments textuels de façon à n’en former qu’un seul. +DOLLAR = EURO ## Convertit un nombre en texte en utilisant le format monétaire € (euro). +EXACT = EXACT ## Vérifie si deux valeurs de texte sont identiques. +FIND = TROUVE ## Trouve un valeur textuelle dans une autre, en respectant la casse. +FINDB = TROUVERB ## Trouve un valeur textuelle dans une autre, en respectant la casse. +FIXED = CTXT ## Convertit un nombre au format texte avec un nombre de décimales spécifié. +JIS = JIS ## Change les caractères anglais ou katakana à demi-chasse (codés sur un octet) à l’intérieur d’une chaîne de caractères en caractères à à pleine chasse (codés sur deux octets). +LEFT = GAUCHE ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. +LEFTB = GAUCHEB ## Renvoie des caractères situés à l’extrême gauche d’une chaîne de caractères. +LEN = NBCAR ## Renvoie le nombre de caractères contenus dans une chaîne de texte. +LENB = LENB ## Renvoie le nombre de caractères contenus dans une chaîne de texte. +LOWER = MINUSCULE ## Convertit le texte en minuscules. +MID = STXT ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. +MIDB = STXTB ## Renvoie un nombre déterminé de caractères d’une chaîne de texte à partir de la position que vous indiquez. +PHONETIC = PHONETIQUE ## Extrait les caractères phonétiques (furigana) d’une chaîne de texte. +PROPER = NOMPROPRE ## Met en majuscules la première lettre de chaque mot dans une chaîne textuelle. +REPLACE = REMPLACER ## Remplace des caractères dans un texte. +REPLACEB = REMPLACERB ## Remplace des caractères dans un texte. +REPT = REPT ## Répète un texte un certain nombre de fois. +RIGHT = DROITE ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. +RIGHTB = DROITEB ## Renvoie des caractères situés à l’extrême droite d’une chaîne de caractères. +SEARCH = CHERCHE ## Trouve un texte dans un autre texte (sans respecter la casse). +SEARCHB = CHERCHERB ## Trouve un texte dans un autre texte (sans respecter la casse). +SUBSTITUTE = SUBSTITUE ## Remplace l’ancien texte d’une chaîne de caractères par un nouveau. +T = T ## Convertit ses arguments en texte. +TEXT = TEXTE ## Convertit un nombre au format texte. +TRIM = SUPPRESPACE ## Supprime les espaces du texte. +UPPER = MAJUSCULE ## Convertit le texte en majuscules. +VALUE = CNUM ## Convertit un argument textuel en nombre diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/config new file mode 100644 index 00000000..080b2018 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = Ft + + +## +## Excel Error Codes (For future use) +## +NULL = #NULLA! +DIV0 = #ZÉRÓOSZTÓ! +VALUE = #ÉRTÉK! +REF = #HIV! +NAME = #NÉV? +NUM = #SZÁM! +NA = #HIÁNYZIK diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/functions new file mode 100644 index 00000000..200d3f71 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/hu/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Bővítmények és automatizálási függvények +## +GETPIVOTDATA = KIMUTATÁSADATOT.VESZ ## A kimutatásokban tárolt adatok visszaadására használható. + + +## +## Cube functions Kockafüggvények +## +CUBEKPIMEMBER = KOCKA.FŐTELJMUT ## Egy fő teljesítménymutató (KPI) nevét, tulajdonságát és mértékegységét adja eredményül, a nevet és a tulajdonságot megjeleníti a cellában. A KPI-k számszerűsíthető mérési lehetőséget jelentenek – ilyen mutató például a havi bruttó nyereség vagy az egy alkalmazottra jutó negyedéves forgalom –, egy szervezet teljesítményének nyomonkövetésére használhatók. +CUBEMEMBER = KOCKA.TAG ## Kockahierachia tagját vagy rekordját adja eredményül. Ellenőrizhető vele, hogy szerepel-e a kockában az adott tag vagy rekord. +CUBEMEMBERPROPERTY = KOCKA.TAG.TUL ## A kocka egyik tagtulajdonságának értékét adja eredményül. Használatával ellenőrizhető, hogy szerepel-e egy tagnév a kockában, eredménye pedig az erre a tagra vonatkozó, megadott tulajdonság. +CUBERANKEDMEMBER = KOCKA.HALM.ELEM ## Egy halmaz rangsor szerinti n-edik tagját adja eredményül. Használatával egy halmaz egy vagy több elemét kaphatja meg, például a legnagyobb teljesítményű üzletkötőt vagy a 10 legjobb tanulót. +CUBESET = KOCKA.HALM ## Számított tagok vagy rekordok halmazát adja eredményül, ehhez egy beállított kifejezést elküld a kiszolgálón található kockának, majd ezt a halmazt adja vissza a Microsoft Office Excel alkalmazásnak. +CUBESETCOUNT = KOCKA.HALM.DB ## Egy halmaz elemszámát adja eredményül. +CUBEVALUE = KOCKA.ÉRTÉK ## Kockából összesített értéket ad eredményül. + + +## +## Database functions Adatbázis-kezelő függvények +## +DAVERAGE = AB.ÁTLAG ## A kijelölt adatbáziselemek átlagát számítja ki. +DCOUNT = AB.DARAB ## Megszámolja, hogy az adatbázisban hány cella tartalmaz számokat. +DCOUNTA = AB.DARAB2 ## Megszámolja az adatbázisban lévő nem üres cellákat. +DGET = AB.MEZŐ ## Egy adatbázisból egyetlen olyan rekordot ad vissza, amely megfelel a megadott feltételeknek. +DMAX = AB.MAX ## A kiválasztott adatbáziselemek közül a legnagyobb értéket adja eredményül. +DMIN = AB.MIN ## A kijelölt adatbáziselemek közül a legkisebb értéket adja eredményül. +DPRODUCT = AB.SZORZAT ## Az adatbázis megadott feltételeknek eleget tevő rekordjaira összeszorozza a megadott mezőben található számértékeket, és eredményül ezt a szorzatot adja. +DSTDEV = AB.SZÓRÁS ## A kijelölt adatbáziselemek egy mintája alapján megbecsüli a szórást. +DSTDEVP = AB.SZÓRÁS2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórást. +DSUM = AB.SZUM ## Összeadja a feltételnek megfelelő adatbázisrekordok mezőoszlopában a számokat. +DVAR = AB.VAR ## A kijelölt adatbáziselemek mintája alapján becslést ad a szórásnégyzetre. +DVARP = AB.VAR2 ## A kijelölt adatbáziselemek teljes sokasága alapján kiszámítja a szórásnégyzetet. + + +## +## Date and time functions Dátumfüggvények +## +DATE = DÁTUM ## Adott dátum dátumértékét adja eredményül. +DATEVALUE = DÁTUMÉRTÉK ## Szövegként megadott dátumot dátumértékké alakít át. +DAY = NAP ## Dátumértéket a hónap egy napjává (0-31) alakít. +DAYS360 = NAP360 ## Két dátum közé eső napok számát számítja ki a 360 napos év alapján. +EDATE = EDATE ## Adott dátumnál adott számú hónappal korábbi vagy későbbi dátum dátumértékét adja eredményül. +EOMONTH = EOMONTH ## Adott dátumnál adott számú hónappal korábbi vagy későbbi hónap utolsó napjának dátumértékét adja eredményül. +HOUR = ÓRA ## Időértéket órákká alakít. +MINUTE = PERC ## Időértéket percekké alakít. +MONTH = HÓNAP ## Időértéket hónapokká alakít. +NETWORKDAYS = NETWORKDAYS ## Két dátum között a teljes munkanapok számát adja meg. +NOW = MOST ## A napi dátum dátumértékét és a pontos idő időértékét adja eredményül. +SECOND = MPERC ## Időértéket másodpercekké alakít át. +TIME = IDŐ ## Adott időpont időértékét adja meg. +TIMEVALUE = IDŐÉRTÉK ## Szövegként megadott időpontot időértékké alakít át. +TODAY = MA ## A napi dátum dátumértékét adja eredményül. +WEEKDAY = HÉT.NAPJA ## Dátumértéket a hét napjává alakítja át. +WEEKNUM = WEEKNUM ## Visszatérési értéke egy szám, amely azt mutatja meg, hogy a megadott dátum az év hányadik hetére esik. +WORKDAY = WORKDAY ## Adott dátumnál adott munkanappal korábbi vagy későbbi dátum dátumértékét adja eredményül. +YEAR = ÉV ## Sorszámot évvé alakít át. +YEARFRAC = YEARFRAC ## Az adott dátumok közötti teljes napok számát törtévként adja meg. + + +## +## Engineering functions Mérnöki függvények +## +BESSELI = BESSELI ## Az In(x) módosított Bessel-függvény értékét adja eredményül. +BESSELJ = BESSELJ ## A Jn(x) Bessel-függvény értékét adja eredményül. +BESSELK = BESSELK ## A Kn(x) módosított Bessel-függvény értékét adja eredményül. +BESSELY = BESSELY ## Az Yn(x) módosított Bessel-függvény értékét adja eredményül. +BIN2DEC = BIN2DEC ## Bináris számot decimálissá alakít át. +BIN2HEX = BIN2HEX ## Bináris számot hexadecimálissá alakít át. +BIN2OCT = BIN2OCT ## Bináris számot oktálissá alakít át. +COMPLEX = COMPLEX ## Valós és képzetes részből komplex számot képez. +CONVERT = CONVERT ## Mértékegységeket vált át. +DEC2BIN = DEC2BIN ## Decimális számot binárissá alakít át. +DEC2HEX = DEC2HEX ## Decimális számot hexadecimálissá alakít át. +DEC2OCT = DEC2OCT ## Decimális számot oktálissá alakít át. +DELTA = DELTA ## Azt vizsgálja, hogy két érték egyenlő-e. +ERF = ERF ## A hibafüggvény értékét adja eredményül. +ERFC = ERFC ## A kiegészített hibafüggvény értékét adja eredményül. +GESTEP = GESTEP ## Azt vizsgálja, hogy egy szám nagyobb-e adott küszöbértéknél. +HEX2BIN = HEX2BIN ## Hexadecimális számot binárissá alakít át. +HEX2DEC = HEX2DEC ## Hexadecimális számot decimálissá alakít át. +HEX2OCT = HEX2OCT ## Hexadecimális számot oktálissá alakít át. +IMABS = IMABS ## Komplex szám abszolút értékét (modulusát) adja eredményül. +IMAGINARY = IMAGINARY ## Komplex szám képzetes részét adja eredményül. +IMARGUMENT = IMARGUMENT ## A komplex szám radiánban kifejezett théta argumentumát adja eredményül. +IMCONJUGATE = IMCONJUGATE ## Komplex szám komplex konjugáltját adja eredményül. +IMCOS = IMCOS ## Komplex szám koszinuszát adja eredményül. +IMDIV = IMDIV ## Két komplex szám hányadosát adja eredményül. +IMEXP = IMEXP ## Az e szám komplex kitevőjű hatványát adja eredményül. +IMLN = IMLN ## Komplex szám természetes logaritmusát adja eredményül. +IMLOG10 = IMLOG10 ## Komplex szám tízes alapú logaritmusát adja eredményül. +IMLOG2 = IMLOG2 ## Komplex szám kettes alapú logaritmusát adja eredményül. +IMPOWER = IMPOWER ## Komplex szám hatványát adja eredményül. +IMPRODUCT = IMPRODUCT ## Komplex számok szorzatát adja eredményül. +IMREAL = IMREAL ## Komplex szám valós részét adja eredményül. +IMSIN = IMSIN ## Komplex szám szinuszát adja eredményül. +IMSQRT = IMSQRT ## Komplex szám négyzetgyökét adja eredményül. +IMSUB = IMSUB ## Két komplex szám különbségét adja eredményül. +IMSUM = IMSUM ## Komplex számok összegét adja eredményül. +OCT2BIN = OCT2BIN ## Oktális számot binárissá alakít át. +OCT2DEC = OCT2DEC ## Oktális számot decimálissá alakít át. +OCT2HEX = OCT2HEX ## Oktális számot hexadecimálissá alakít át. + + +## +## Financial functions Pénzügyi függvények +## +ACCRINT = ACCRINT ## Periodikusan kamatozó értékpapír felszaporodott kamatát adja eredményül. +ACCRINTM = ACCRINTM ## Lejáratkor kamatozó értékpapír felszaporodott kamatát adja eredményül. +AMORDEGRC = AMORDEGRC ## Állóeszköz lineáris értékcsökkenését adja meg az egyes könyvelési időszakokra vonatkozóan. +AMORLINC = AMORLINC ## Az egyes könyvelési időszakokban az értékcsökkenést adja meg. +COUPDAYBS = COUPDAYBS ## A szelvényidőszak kezdetétől a kifizetés időpontjáig eltelt napokat adja vissza. +COUPDAYS = COUPDAYS ## A kifizetés időpontját magában foglaló szelvényperiódus hosszát adja meg napokban. +COUPDAYSNC = COUPDAYSNC ## A kifizetés időpontja és a legközelebbi szelvénydátum közötti napok számát adja meg. +COUPNCD = COUPNCD ## A kifizetést követő legelső szelvénydátumot adja eredményül. +COUPNUM = COUPNUM ## A kifizetés és a lejárat időpontja között kifizetendő szelvények számát adja eredményül. +COUPPCD = COUPPCD ## A kifizetés előtti utolsó szelvénydátumot adja eredményül. +CUMIPMT = CUMIPMT ## Két fizetési időszak között kifizetett kamat halmozott értékét adja eredményül. +CUMPRINC = CUMPRINC ## Két fizetési időszak között kifizetett részletek halmozott (kamatot nem tartalmazó) értékét adja eredményül. +DB = KCS2 ## Eszköz adott időszak alatti értékcsökkenését számítja ki a lineáris leírási modell alkalmazásával. +DDB = KCSA ## Eszköz értékcsökkenését számítja ki adott időszakra vonatkozóan a progresszív vagy egyéb megadott leírási modell alkalmazásával. +DISC = DISC ## Értékpapír leszámítolási kamatlábát adja eredményül. +DOLLARDE = DOLLARDE ## Egy közönséges törtként megadott számot tizedes törtté alakít át. +DOLLARFR = DOLLARFR ## Tizedes törtként megadott számot közönséges törtté alakít át. +DURATION = DURATION ## Periodikus kamatfizetésű értékpapír éves kamatérzékenységét adja eredményül. +EFFECT = EFFECT ## Az éves tényleges kamatláb értékét adja eredményül. +FV = JBÉ ## Befektetés jövőbeli értékét számítja ki. +FVSCHEDULE = FVSCHEDULE ## A kezdőtőke adott kamatlábak szerint megnövelt jövőbeli értékét adja eredményül. +INTRATE = INTRATE ## A lejáratig teljesen lekötött értékpapír kamatrátáját adja eredményül. +IPMT = RRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. +IRR = BMR ## A befektetés belső megtérülési rátáját számítja ki pénzáramláshoz. +ISPMT = LRÉSZLETKAMAT ## A befektetés adott időszakára fizetett kamatot számítja ki. +MDURATION = MDURATION ## Egy 100 Ft névértékű értékpapír Macauley-féle módosított kamatérzékenységét adja eredményül. +MIRR = MEGTÉRÜLÉS ## A befektetés belső megtérülési rátáját számítja ki a költségek és a bevételek különböző kamatlába mellett. +NOMINAL = NOMINAL ## Az éves névleges kamatláb értékét adja eredményül. +NPER = PER.SZÁM ## A törlesztési időszakok számát adja meg. +NPV = NMÉ ## Befektetéshez kapcsolódó pénzáramlás nettó jelenértékét számítja ki ismert pénzáramlás és kamatláb mellett. +ODDFPRICE = ODDFPRICE ## Egy 100 Ft névértékű, a futamidő elején töredék-időszakos értékpapír árát adja eredményül. +ODDFYIELD = ODDFYIELD ## A futamidő elején töredék-időszakos értékpapír hozamát adja eredményül. +ODDLPRICE = ODDLPRICE ## Egy 100 Ft névértékű, a futamidő végén töredék-időszakos értékpapír árát adja eredményül. +ODDLYIELD = ODDLYIELD ## A futamidő végén töredék-időszakos értékpapír hozamát adja eredményül. +PMT = RÉSZLET ## A törlesztési időszakra vonatkozó törlesztési összeget számítja ki. +PPMT = PRÉSZLET ## Hiteltörlesztésen belül a tőketörlesztés nagyságát számítja ki adott időszakra. +PRICE = PRICE ## Egy 100 Ft névértékű, periodikusan kamatozó értékpapír árát adja eredményül. +PRICEDISC = PRICEDISC ## Egy 100 Ft névértékű leszámítolt értékpapír árát adja eredményül. +PRICEMAT = PRICEMAT ## Egy 100 Ft névértékű, a lejáratkor kamatozó értékpapír árát adja eredményül. +PV = MÉ ## Befektetés jelenlegi értékét számítja ki. +RATE = RÁTA ## Egy törlesztési időszakban az egy időszakra eső kamatláb nagyságát számítja ki. +RECEIVED = RECEIVED ## A lejáratig teljesen lekötött értékpapír lejáratakor kapott összegét adja eredményül. +SLN = LCSA ## Tárgyi eszköz egy időszakra eső amortizációját adja meg bruttó érték szerinti lineáris leírási kulcsot alkalmazva. +SYD = SYD ## Tárgyi eszköz értékcsökkenését számítja ki adott időszakra az évek számjegyösszegével dolgozó módszer alapján. +TBILLEQ = TBILLEQ ## Kincstárjegy kötvény-egyenértékű hozamát adja eredményül. +TBILLPRICE = TBILLPRICE ## Egy 100 Ft névértékű kincstárjegy árát adja eredményül. +TBILLYIELD = TBILLYIELD ## Kincstárjegy hozamát adja eredményül. +VDB = ÉCSRI ## Tárgyi eszköz amortizációját számítja ki megadott vagy részidőszakra a csökkenő egyenleg módszerének alkalmazásával. +XIRR = XIRR ## Ütemezett készpénzforgalom (cash flow) belső megtérülési kamatrátáját adja eredményül. +XNPV = XNPV ## Ütemezett készpénzforgalom (cash flow) nettó jelenlegi értékét adja eredményül. +YIELD = YIELD ## Periodikusan kamatozó értékpapír hozamát adja eredményül. +YIELDDISC = YIELDDISC ## Leszámítolt értékpapír (például kincstárjegy) éves hozamát adja eredményül. +YIELDMAT = YIELDMAT ## Lejáratkor kamatozó értékpapír éves hozamát adja eredményül. + + +## +## Information functions Információs függvények +## +CELL = CELLA ## Egy cella formátumára, elhelyezkedésére vagy tartalmára vonatkozó adatokat ad eredményül. +ERROR.TYPE = HIBA.TÍPUS ## Egy hibatípushoz tartozó számot ad eredményül. +INFO = INFÓ ## A rendszer- és munkakörnyezet pillanatnyi állapotáról ad felvilágosítást. +ISBLANK = ÜRES ## Eredménye IGAZ, ha az érték üres. +ISERR = HIBA ## Eredménye IGAZ, ha az érték valamelyik hibaérték a #HIÁNYZIK kivételével. +ISERROR = HIBÁS ## Eredménye IGAZ, ha az érték valamelyik hibaérték. +ISEVEN = ISEVEN ## Eredménye IGAZ, ha argumentuma páros szám. +ISLOGICAL = LOGIKAI ## Eredménye IGAZ, ha az érték logikai érték. +ISNA = NINCS ## Eredménye IGAZ, ha az érték a #HIÁNYZIK hibaérték. +ISNONTEXT = NEM.SZÖVEG ## Eredménye IGAZ, ha az érték nem szöveg. +ISNUMBER = SZÁM ## Eredménye IGAZ, ha az érték szám. +ISODD = ISODD ## Eredménye IGAZ, ha argumentuma páratlan szám. +ISREF = HIVATKOZÁS ## Eredménye IGAZ, ha az érték hivatkozás. +ISTEXT = SZÖVEG.E ## Eredménye IGAZ, ha az érték szöveg. +N = N ## Argumentumának értékét számmá alakítja. +NA = HIÁNYZIK ## Eredménye a #HIÁNYZIK hibaérték. +TYPE = TÍPUS ## Érték adattípusának azonosítószámát adja eredményül. + + +## +## Logical functions Logikai függvények +## +AND = ÉS ## Eredménye IGAZ, ha minden argumentuma IGAZ. +FALSE = HAMIS ## A HAMIS logikai értéket adja eredményül. +IF = HA ## Logikai vizsgálatot hajt végre. +IFERROR = HAHIBA ## A megadott értéket adja vissza, ha egy képlet hibához vezet; más esetben a képlet értékét adja eredményül. +NOT = NEM ## Argumentuma értékének ellentettjét adja eredményül. +OR = VAGY ## Eredménye IGAZ, ha bármely argumentuma IGAZ. +TRUE = IGAZ ## Az IGAZ logikai értéket adja eredményül. + + +## +## Lookup and reference functions Keresési és hivatkozási függvények +## +ADDRESS = CÍM ## A munkalap egy cellájára való hivatkozást adja szövegként eredményül. +AREAS = TERÜLET ## Hivatkozásban a területek számát adja eredményül. +CHOOSE = VÁLASZT ## Értékek listájából választ ki egy elemet. +COLUMN = OSZLOP ## Egy hivatkozás oszlopszámát adja eredményül. +COLUMNS = OSZLOPOK ## A hivatkozásban található oszlopok számát adja eredményül. +HLOOKUP = VKERES ## A megadott tömb felső sorában adott értékű elemet keres, és a megtalált elem oszlopából adott sorban elhelyezkedő értékkel tér vissza. +HYPERLINK = HIPERHIVATKOZÁS ## Hálózati kiszolgálón, intraneten vagy az interneten tárolt dokumentumot megnyitó parancsikont vagy hivatkozást hoz létre. +INDEX = INDEX ## Tömb- vagy hivatkozás indexszel megadott értékét adja vissza. +INDIRECT = INDIREKT ## Szöveg megadott hivatkozást ad eredményül. +LOOKUP = KERES ## Vektorban vagy tömbben keres meg értékeket. +MATCH = HOL.VAN ## Hivatkozásban vagy tömbben értékeket keres. +OFFSET = OFSZET ## Hivatkozás egy másik hivatkozástól számított távolságát adja meg. +ROW = SOR ## Egy hivatkozás sorának számát adja meg. +ROWS = SOROK ## Egy hivatkozás sorainak számát adja meg. +RTD = RTD ## Valós idejű adatokat keres vissza a COM automatizmust (automatizálás: Egy alkalmazás objektumaival való munka másik alkalmazásból vagy fejlesztőeszközből. A korábban OLE automatizmusnak nevezett automatizálás iparági szabvány, a Component Object Model (COM) szolgáltatása.) támogató programból. +TRANSPOSE = TRANSZPONÁLÁS ## Egy tömb transzponáltját adja eredményül. +VLOOKUP = FKERES ## A megadott tömb bal szélső oszlopában megkeres egy értéket, majd annak sora és a megadott oszlop metszéspontjában levő értéked adja eredményül. + + +## +## Math and trigonometry functions Matematikai és trigonometrikus függvények +## +ABS = ABS ## Egy szám abszolút értékét adja eredményül. +ACOS = ARCCOS ## Egy szám arkusz koszinuszát számítja ki. +ACOSH = ACOSH ## Egy szám inverz koszinusz hiperbolikuszát számítja ki. +ASIN = ARCSIN ## Egy szám arkusz szinuszát számítja ki. +ASINH = ASINH ## Egy szám inverz szinusz hiperbolikuszát számítja ki. +ATAN = ARCTAN ## Egy szám arkusz tangensét számítja ki. +ATAN2 = ARCTAN2 ## X és y koordináták alapján számítja ki az arkusz tangens értéket. +ATANH = ATANH ## A szám inverz tangens hiperbolikuszát számítja ki. +CEILING = PLAFON ## Egy számot a legközelebbi egészre vagy a pontosságként megadott érték legközelebb eső többszörösére kerekít. +COMBIN = KOMBINÁCIÓK ## Adott számú objektum összes lehetséges kombinációinak számát számítja ki. +COS = COS ## Egy szám koszinuszát számítja ki. +COSH = COSH ## Egy szám koszinusz hiperbolikuszát számítja ki. +DEGREES = FOK ## Radiánt fokká alakít át. +EVEN = PÁROS ## Egy számot a legközelebbi páros egész számra kerekít. +EXP = KITEVŐ ## Az e adott kitevőjű hatványát adja eredményül. +FACT = FAKT ## Egy szám faktoriálisát számítja ki. +FACTDOUBLE = FACTDOUBLE ## Egy szám dupla faktoriálisát adja eredményül. +FLOOR = PADLÓ ## Egy számot lefelé, a nulla felé kerekít. +GCD = GCD ## A legnagyobb közös osztót adja eredményül. +INT = INT ## Egy számot lefelé kerekít a legközelebbi egészre. +LCM = LCM ## A legkisebb közös többszöröst adja eredményül. +LN = LN ## Egy szám természetes logaritmusát számítja ki. +LOG = LOG ## Egy szám adott alapú logaritmusát számítja ki. +LOG10 = LOG10 ## Egy szám 10-es alapú logaritmusát számítja ki. +MDETERM = MDETERM ## Egy tömb mátrix-determinánsát számítja ki. +MINVERSE = INVERZ.MÁTRIX ## Egy tömb mátrix inverzét adja eredményül. +MMULT = MSZORZAT ## Két tömb mátrix-szorzatát adja meg. +MOD = MARADÉK ## Egy szám osztási maradékát adja eredményül. +MROUND = MROUND ## A kívánt többszörösére kerekített értéket ad eredményül. +MULTINOMIAL = MULTINOMIAL ## Számhalmaz multinomiálisát adja eredményül. +ODD = PÁRATLAN ## Egy számot a legközelebbi páratlan számra kerekít. +PI = PI ## A pi matematikai állandót adja vissza. +POWER = HATVÁNY ## Egy szám adott kitevőjű hatványát számítja ki. +PRODUCT = SZORZAT ## Argumentumai szorzatát számítja ki. +QUOTIENT = QUOTIENT ## Egy hányados egész részét adja eredményül. +RADIANS = RADIÁN ## Fokot radiánná alakít át. +RAND = VÉL ## Egy 0 és 1 közötti véletlen számot ad eredményül. +RANDBETWEEN = RANDBETWEEN ## Megadott számok közé eső véletlen számot állít elő. +ROMAN = RÓMAI ## Egy számot római számokkal kifejezve szövegként ad eredményül. +ROUND = KEREKÍTÉS ## Egy számot adott számú számjegyre kerekít. +ROUNDDOWN = KEREKÍTÉS.LE ## Egy számot lefelé, a nulla felé kerekít. +ROUNDUP = KEREKÍTÉS.FEL ## Egy számot felfelé, a nullától távolabbra kerekít. +SERIESSUM = SERIESSUM ## Hatványsor összegét adja eredményül. +SIGN = ELŐJEL ## Egy szám előjelét adja meg. +SIN = SIN ## Egy szög szinuszát számítja ki. +SINH = SINH ## Egy szám szinusz hiperbolikuszát számítja ki. +SQRT = GYÖK ## Egy szám pozitív négyzetgyökét számítja ki. +SQRTPI = SQRTPI ## A (szám*pi) négyzetgyökét adja eredményül. +SUBTOTAL = RÉSZÖSSZEG ## Lista vagy adatbázis részösszegét adja eredményül. +SUM = SZUM ## Összeadja az argumentumlistájában lévő számokat. +SUMIF = SZUMHA ## A megadott feltételeknek eleget tevő cellákban található értékeket adja össze. +SUMIFS = SZUMHATÖBB ## Több megadott feltételnek eleget tévő tartománycellák összegét adja eredményül. +SUMPRODUCT = SZORZATÖSSZEG ## A megfelelő tömbelemek szorzatának összegét számítja ki. +SUMSQ = NÉGYZETÖSSZEG ## Argumentumai négyzetének összegét számítja ki. +SUMX2MY2 = SZUMX2BŐLY2 ## Két tömb megfelelő elemei négyzetének különbségét összegzi. +SUMX2PY2 = SZUMX2MEGY2 ## Két tömb megfelelő elemei négyzetének összegét összegzi. +SUMXMY2 = SZUMXBŐLY2 ## Két tömb megfelelő elemei különbségének négyzetösszegét számítja ki. +TAN = TAN ## Egy szám tangensét számítja ki. +TANH = TANH ## Egy szám tangens hiperbolikuszát számítja ki. +TRUNC = CSONK ## Egy számot egésszé csonkít. + + +## +## Statistical functions Statisztikai függvények +## +AVEDEV = ÁTL.ELTÉRÉS ## Az adatpontoknak átlaguktól való átlagos abszolút eltérését számítja ki. +AVERAGE = ÁTLAG ## Argumentumai átlagát számítja ki. +AVERAGEA = ÁTLAGA ## Argumentumai átlagát számítja ki (beleértve a számokat, szöveget és logikai értékeket). +AVERAGEIF = ÁTLAGHA ## A megadott feltételnek eleget tévő tartomány celláinak átlagát (számtani közepét) adja eredményül. +AVERAGEIFS = ÁTLAGHATÖBB ## A megadott feltételeknek eleget tévő cellák átlagát (számtani közepét) adja eredményül. +BETADIST = BÉTA.ELOSZLÁS ## A béta-eloszlás függvényt számítja ki. +BETAINV = INVERZ.BÉTA ## Adott béta-eloszláshoz kiszámítja a béta eloszlásfüggvény inverzét. +BINOMDIST = BINOM.ELOSZLÁS ## A diszkrét binomiális eloszlás valószínűségértékét számítja ki. +CHIDIST = KHI.ELOSZLÁS ## A khi-négyzet-eloszlás egyszélű valószínűségértékét számítja ki. +CHIINV = INVERZ.KHI ## A khi-négyzet-eloszlás egyszélű valószínűségértékének inverzét számítja ki. +CHITEST = KHI.PRÓBA ## Függetlenségvizsgálatot hajt végre. +CONFIDENCE = MEGBÍZHATÓSÁG ## Egy statisztikai sokaság várható értékének megbízhatósági intervallumát adja eredményül. +CORREL = KORREL ## Két adathalmaz korrelációs együtthatóját számítja ki. +COUNT = DARAB ## Megszámolja, hogy argumentumlistájában hány szám található. +COUNTA = DARAB2 ## Megszámolja, hogy argumentumlistájában hány érték található. +COUNTBLANK = DARABÜRES ## Egy tartományban összeszámolja az üres cellákat. +COUNTIF = DARABTELI ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek a megadott feltételnek. +COUNTIFS = DARABHATÖBB ## Egy tartományban összeszámolja azokat a cellákat, amelyek eleget tesznek több feltételnek. +COVAR = KOVAR ## A kovarianciát, azaz a páronkénti eltérések szorzatának átlagát számítja ki. +CRITBINOM = KRITBINOM ## Azt a legkisebb számot adja eredményül, amelyre a binomiális eloszlásfüggvény értéke nem kisebb egy adott határértéknél. +DEVSQ = SQ ## Az átlagtól való eltérések négyzetének összegét számítja ki. +EXPONDIST = EXP.ELOSZLÁS ## Az exponenciális eloszlás értékét számítja ki. +FDIST = F.ELOSZLÁS ## Az F-eloszlás értékét számítja ki. +FINV = INVERZ.F ## Az F-eloszlás inverzének értékét számítja ki. +FISHER = FISHER ## Fisher-transzformációt hajt végre. +FISHERINV = INVERZ.FISHER ## A Fisher-transzformáció inverzét hajtja végre. +FORECAST = ELŐREJELZÉS ## Az ismert értékek alapján lineáris regresszióval becsült értéket ad eredményül. +FREQUENCY = GYAKORISÁG ## A gyakorisági vagy empirikus eloszlás értékét függőleges tömbként adja eredményül. +FTEST = F.PRÓBA ## Az F-próba értékét adja eredményül. +GAMMADIST = GAMMA.ELOSZLÁS ## A gamma-eloszlás értékét számítja ki. +GAMMAINV = INVERZ.GAMMA ## A gamma-eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +GAMMALN = GAMMALN ## A gamma-függvény természetes logaritmusát számítja ki. +GEOMEAN = MÉRTANI.KÖZÉP ## Argumentumai mértani középértékét számítja ki. +GROWTH = NÖV ## Exponenciális regresszió alapján ad becslést. +HARMEAN = HARM.KÖZÉP ## Argumentumai harmonikus átlagát számítja ki. +HYPGEOMDIST = HIPERGEOM.ELOSZLÁS ## A hipergeometriai eloszlás értékét számítja ki. +INTERCEPT = METSZ ## A regressziós egyenes y tengellyel való metszéspontját határozza meg. +KURT = CSÚCSOSSÁG ## Egy adathalmaz csúcsosságát számítja ki. +LARGE = NAGY ## Egy adathalmaz k-adik legnagyobb elemét adja eredményül. +LINEST = LIN.ILL ## A legkisebb négyzetek módszerével az adatokra illesztett egyenes paramétereit határozza meg. +LOGEST = LOG.ILL ## Az adatokra illesztett exponenciális görbe paramétereit határozza meg. +LOGINV = INVERZ.LOG.ELOSZLÁS ## A lognormális eloszlás inverzét számítja ki. +LOGNORMDIST = LOG.ELOSZLÁS ## A lognormális eloszlásfüggvény értékét számítja ki. +MAX = MAX ## Az argumentumai között szereplő legnagyobb számot adja meg. +MAXA = MAX2 ## Az argumentumai között szereplő legnagyobb számot adja meg (beleértve a számokat, szöveget és logikai értékeket). +MEDIAN = MEDIÁN ## Adott számhalmaz mediánját számítja ki. +MIN = MIN ## Az argumentumai között szereplő legkisebb számot adja meg. +MINA = MIN2 ## Az argumentumai között szereplő legkisebb számot adja meg, beleértve a számokat, szöveget és logikai értékeket. +MODE = MÓDUSZ ## Egy adathalmazból kiválasztja a leggyakrabban előforduló számot. +NEGBINOMDIST = NEGBINOM.ELOSZL ## A negatív binomiális eloszlás értékét számítja ki. +NORMDIST = NORM.ELOSZL ## A normális eloszlás értékét számítja ki. +NORMINV = INVERZ.NORM ## A normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +NORMSDIST = STNORMELOSZL ## A standard normális eloszlás eloszlásfüggvényének értékét számítja ki. +NORMSINV = INVERZ.STNORM ## A standard normális eloszlás eloszlásfüggvénye inverzének értékét számítja ki. +PEARSON = PEARSON ## A Pearson-féle korrelációs együtthatót számítja ki. +PERCENTILE = PERCENTILIS ## Egy tartományban található értékek k-adik percentilisét, azaz százalékosztályát adja eredményül. +PERCENTRANK = SZÁZALÉKRANG ## Egy értéknek egy adathalmazon belül vett százalékos rangját (elhelyezkedését) számítja ki. +PERMUT = VARIÁCIÓK ## Adott számú objektum k-ad osztályú ismétlés nélküli variációinak számát számítja ki. +POISSON = POISSON ## A Poisson-eloszlás értékét számítja ki. +PROB = VALÓSZÍNŰSÉG ## Annak valószínűségét számítja ki, hogy adott értékek két határérték közé esnek. +QUARTILE = KVARTILIS ## Egy adathalmaz kvartilisét (negyedszintjét) számítja ki. +RANK = SORSZÁM ## Kiszámítja, hogy egy szám hányadik egy számsorozatban. +RSQ = RNÉGYZET ## Kiszámítja a Pearson-féle szorzatmomentum korrelációs együtthatójának négyzetét. +SKEW = FERDESÉG ## Egy eloszlás ferdeségét határozza meg. +SLOPE = MEREDEKSÉG ## Egy lineáris regressziós egyenes meredekségét számítja ki. +SMALL = KICSI ## Egy adathalmaz k-adik legkisebb elemét adja meg. +STANDARDIZE = NORMALIZÁLÁS ## Normalizált értéket ad eredményül. +STDEV = SZÓRÁS ## Egy statisztikai sokaság mintájából kiszámítja annak szórását. +STDEVA = SZÓRÁSA ## Egy statisztikai sokaság mintájából kiszámítja annak szórását (beleértve a számokat, szöveget és logikai értékeket). +STDEVP = SZÓRÁSP ## Egy statisztikai sokaság egészéből kiszámítja annak szórását. +STDEVPA = SZÓRÁSPA ## Egy statisztikai sokaság egészéből kiszámítja annak szórását (beleértve számokat, szöveget és logikai értékeket). +STEYX = STHIBAYX ## Egy regresszió esetén az egyes x-értékek alapján meghatározott y-értékek standard hibáját számítja ki. +TDIST = T.ELOSZLÁS ## A Student-féle t-eloszlás értékét számítja ki. +TINV = INVERZ.T ## A Student-féle t-eloszlás inverzét számítja ki. +TREND = TREND ## Lineáris trend értékeit számítja ki. +TRIMMEAN = RÉSZÁTLAG ## Egy adathalmaz középső részének átlagát számítja ki. +TTEST = T.PRÓBA ## A Student-féle t-próbához tartozó valószínűséget számítja ki. +VAR = VAR ## Minta alapján becslést ad a varianciára. +VARA = VARA ## Minta alapján becslést ad a varianciára (beleértve számokat, szöveget és logikai értékeket). +VARP = VARP ## Egy statisztikai sokaság varianciáját számítja ki. +VARPA = VARPA ## Egy statisztikai sokaság varianciáját számítja ki (beleértve számokat, szöveget és logikai értékeket). +WEIBULL = WEIBULL ## A Weibull-féle eloszlás értékét számítja ki. +ZTEST = Z.PRÓBA ## Az egyszélű z-próbával kapott valószínűségértéket számítja ki. + + +## +## Text functions Szövegműveletekhez használható függvények +## +ASC = ASC ## Szöveg teljes szélességű (kétbájtos) latin és katakana karaktereit félszélességű (egybájtos) karakterekké alakítja. +BAHTTEXT = BAHTSZÖVEG ## Számot szöveggé alakít a ß (baht) pénznemformátum használatával. +CHAR = KARAKTER ## A kódszámmal meghatározott karaktert adja eredményül. +CLEAN = TISZTÍT ## A szövegből eltávolítja az összes nem nyomtatható karaktert. +CODE = KÓD ## Karaktersorozat első karakterének numerikus kódját adja eredményül. +CONCATENATE = ÖSSZEFŰZ ## Több szövegelemet egyetlen szöveges elemmé fűz össze. +DOLLAR = FORINT ## Számot pénznem formátumú szöveggé alakít át. +EXACT = AZONOS ## Megvizsgálja, hogy két érték azonos-e. +FIND = SZÖVEG.TALÁL ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). +FINDB = SZÖVEG.TALÁL2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk megkülönböztetésével). +FIXED = FIX ## Számot szöveges formátumúra alakít adott számú tizedesjegyre kerekítve. +JIS = JIS ## A félszélességű (egybájtos) latin és a katakana karaktereket teljes szélességű (kétbájtos) karakterekké alakítja. +LEFT = BAL ## Szöveg bal szélső karaktereit adja eredményül. +LEFTB = BAL2 ## Szöveg bal szélső karaktereit adja eredményül. +LEN = HOSSZ ## Szöveg karakterekben mért hosszát adja eredményül. +LENB = HOSSZ2 ## Szöveg karakterekben mért hosszát adja eredményül. +LOWER = KISBETŰ ## Szöveget kisbetűssé alakít át. +MID = KÖZÉP ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. +MIDB = KÖZÉP2 ## A szöveg adott pozíciójától kezdve megadott számú karaktert ad vissza eredményként. +PHONETIC = PHONETIC ## Szöveg furigana (fonetikus) karaktereit adja vissza. +PROPER = TNÉV ## Szöveg minden szavának kezdőbetűjét nagybetűsre cseréli. +REPLACE = CSERE ## A szövegen belül karaktereket cserél. +REPLACEB = CSERE2 ## A szövegen belül karaktereket cserél. +REPT = SOKSZOR ## Megadott számú alkalommal megismétel egy szövegrészt. +RIGHT = JOBB ## Szövegrész jobb szélső karaktereit adja eredményül. +RIGHTB = JOBB2 ## Szövegrész jobb szélső karaktereit adja eredményül. +SEARCH = SZÖVEG.KERES ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). +SEARCHB = SZÖVEG.KERES2 ## Karaktersorozatot keres egy másikban (a kis- és nagybetűk között nem tesz különbséget). +SUBSTITUTE = HELYETTE ## Szövegben adott karaktereket másikra cserél. +T = T ## Argumentumát szöveggé alakítja át. +TEXT = SZÖVEG ## Számértéket alakít át adott számformátumú szöveggé. +TRIM = TRIM ## A szövegből eltávolítja a szóközöket. +UPPER = NAGYBETŰS ## Szöveget nagybetűssé alakít át. +VALUE = ÉRTÉK ## Szöveget számmá alakít át. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/config new file mode 100644 index 00000000..c3afa754 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULLO! +DIV0 = #DIV/0! +VALUE = #VALORE! +REF = #RIF! +NAME = #NOME? +NUM = #NUM! +NA = #N/D diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/functions new file mode 100644 index 00000000..d371f3d7 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/it/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funzioni di automazione e dei componenti aggiuntivi +## +GETPIVOTDATA = INFO.DATI.TAB.PIVOT ## Restituisce i dati memorizzati in un rapporto di tabella pivot + + +## +## Cube functions Funzioni cubo +## +CUBEKPIMEMBER = MEMBRO.KPI.CUBO ## Restituisce il nome, la proprietà e la misura di un indicatore di prestazioni chiave (KPI) e visualizza il nome e la proprietà nella cella. Un KPI è una misura quantificabile, ad esempio l'utile lordo mensile o il fatturato trimestrale dei dipendenti, utilizzata per il monitoraggio delle prestazioni di un'organizzazione. +CUBEMEMBER = MEMBRO.CUBO ## Restituisce un membro o una tupla in una gerarchia di cubi. Consente di verificare l'esistenza del membro o della tupla nel cubo. +CUBEMEMBERPROPERTY = PROPRIETÀ.MEMBRO.CUBO ## Restituisce il valore di una proprietà di un membro del cubo. Consente di verificare l'esistenza di un nome di membro all'interno del cubo e di restituire la proprietà specificata per tale membro. +CUBERANKEDMEMBER = MEMBRO.CUBO.CON.RANGO ## Restituisce l'n-esimo membro o il membro ordinato di un insieme. Consente di restituire uno o più elementi in un insieme, ad esempio l'agente di vendita migliore o i primi 10 studenti. +CUBESET = SET.CUBO ## Definisce un insieme di tuple o membri calcolati mediante l'invio di un'espressione di insieme al cubo sul server. In questo modo l'insieme viene creato e restituito a Microsoft Office Excel. +CUBESETCOUNT = CONTA.SET.CUBO ## Restituisce il numero di elementi di un insieme. +CUBEVALUE = VALORE.CUBO ## Restituisce un valore aggregato da un cubo. + + +## +## Database functions Funzioni di database +## +DAVERAGE = DB.MEDIA ## Restituisce la media di voci del database selezionate +DCOUNT = DB.CONTA.NUMERI ## Conta le celle di un database contenenti numeri +DCOUNTA = DB.CONTA.VALORI ## Conta le celle non vuote in un database +DGET = DB.VALORI ## Estrae da un database un singolo record che soddisfa i criteri specificati +DMAX = DB.MAX ## Restituisce il valore massimo dalle voci selezionate in un database +DMIN = DB.MIN ## Restituisce il valore minimo dalle voci di un database selezionate +DPRODUCT = DB.PRODOTTO ## Moltiplica i valori in un determinato campo di record che soddisfano i criteri del database +DSTDEV = DB.DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione di voci di un database selezionate +DSTDEVP = DB.DEV.ST.POP ## Calcola la deviazione standard sulla base di tutte le voci di un database selezionate +DSUM = DB.SOMMA ## Aggiunge i numeri nel campo colonna di record del database che soddisfa determinati criteri +DVAR = DB.VAR ## Restituisce una stima della varianza sulla base di un campione da voci di un database selezionate +DVARP = DB.VAR.POP ## Calcola la varianza sulla base di tutte le voci di un database selezionate + + +## +## Date and time functions Funzioni data e ora +## +DATE = DATA ## Restituisce il numero seriale di una determinata data +DATEVALUE = DATA.VALORE ## Converte una data sotto forma di testo in un numero seriale +DAY = GIORNO ## Converte un numero seriale in un giorno del mese +DAYS360 = GIORNO360 ## Calcola il numero di giorni compreso tra due date basandosi su un anno di 360 giorni +EDATE = DATA.MESE ## Restituisce il numero seriale della data che rappresenta il numero di mesi prima o dopo la data di inizio +EOMONTH = FINE.MESE ## Restituisce il numero seriale dell'ultimo giorno del mese, prima o dopo un determinato numero di mesi +HOUR = ORA ## Converte un numero seriale in un'ora +MINUTE = MINUTO ## Converte un numero seriale in un minuto +MONTH = MESE ## Converte un numero seriale in un mese +NETWORKDAYS = GIORNI.LAVORATIVI.TOT ## Restituisce il numero di tutti i giorni lavorativi compresi fra due date +NOW = ADESSO ## Restituisce il numero seriale della data e dell'ora corrente +SECOND = SECONDO ## Converte un numero seriale in un secondo +TIME = ORARIO ## Restituisce il numero seriale di una determinata ora +TIMEVALUE = ORARIO.VALORE ## Converte un orario in forma di testo in un numero seriale +TODAY = OGGI ## Restituisce il numero seriale relativo alla data odierna +WEEKDAY = GIORNO.SETTIMANA ## Converte un numero seriale in un giorno della settimana +WEEKNUM = NUM.SETTIMANA ## Converte un numero seriale in un numero che rappresenta la posizione numerica di una settimana nell'anno +WORKDAY = GIORNO.LAVORATIVO ## Restituisce il numero della data prima o dopo un determinato numero di giorni lavorativi +YEAR = ANNO ## Converte un numero seriale in un anno +YEARFRAC = FRAZIONE.ANNO ## Restituisce la frazione dell'anno che rappresenta il numero dei giorni compresi tra una data_ iniziale e una data_finale + + +## +## Engineering functions Funzioni ingegneristiche +## +BESSELI = BESSEL.I ## Restituisce la funzione di Bessel modificata In(x) +BESSELJ = BESSEL.J ## Restituisce la funzione di Bessel Jn(x) +BESSELK = BESSEL.K ## Restituisce la funzione di Bessel modificata Kn(x) +BESSELY = BESSEL.Y ## Restituisce la funzione di Bessel Yn(x) +BIN2DEC = BINARIO.DECIMALE ## Converte un numero binario in decimale +BIN2HEX = BINARIO.HEX ## Converte un numero binario in esadecimale +BIN2OCT = BINARIO.OCT ## Converte un numero binario in ottale +COMPLEX = COMPLESSO ## Converte i coefficienti reali e immaginari in numeri complessi +CONVERT = CONVERTI ## Converte un numero da un sistema di misura in un altro +DEC2BIN = DECIMALE.BINARIO ## Converte un numero decimale in binario +DEC2HEX = DECIMALE.HEX ## Converte un numero decimale in esadecimale +DEC2OCT = DECIMALE.OCT ## Converte un numero decimale in ottale +DELTA = DELTA ## Verifica se due valori sono uguali +ERF = FUNZ.ERRORE ## Restituisce la funzione di errore +ERFC = FUNZ.ERRORE.COMP ## Restituisce la funzione di errore complementare +GESTEP = SOGLIA ## Verifica se un numero è maggiore del valore di soglia +HEX2BIN = HEX.BINARIO ## Converte un numero esadecimale in binario +HEX2DEC = HEX.DECIMALE ## Converte un numero esadecimale in decimale +HEX2OCT = HEX.OCT ## Converte un numero esadecimale in ottale +IMABS = COMP.MODULO ## Restituisce il valore assoluto (modulo) di un numero complesso +IMAGINARY = COMP.IMMAGINARIO ## Restituisce il coefficiente immaginario di un numero complesso +IMARGUMENT = COMP.ARGOMENTO ## Restituisce l'argomento theta, un angolo espresso in radianti +IMCONJUGATE = COMP.CONIUGATO ## Restituisce il complesso coniugato del numero complesso +IMCOS = COMP.COS ## Restituisce il coseno di un numero complesso +IMDIV = COMP.DIV ## Restituisce il quoziente di due numeri complessi +IMEXP = COMP.EXP ## Restituisce il valore esponenziale di un numero complesso +IMLN = COMP.LN ## Restituisce il logaritmo naturale di un numero complesso +IMLOG10 = COMP.LOG10 ## Restituisce il logaritmo in base 10 di un numero complesso +IMLOG2 = COMP.LOG2 ## Restituisce un logaritmo in base 2 di un numero complesso +IMPOWER = COMP.POTENZA ## Restituisce il numero complesso elevato a una potenza intera +IMPRODUCT = COMP.PRODOTTO ## Restituisce il prodotto di numeri complessi compresi tra 2 e 29 +IMREAL = COMP.PARTE.REALE ## Restituisce il coefficiente reale di un numero complesso +IMSIN = COMP.SEN ## Restituisce il seno di un numero complesso +IMSQRT = COMP.RADQ ## Restituisce la radice quadrata di un numero complesso +IMSUB = COMP.DIFF ## Restituisce la differenza fra due numeri complessi +IMSUM = COMP.SOMMA ## Restituisce la somma di numeri complessi +OCT2BIN = OCT.BINARIO ## Converte un numero ottale in binario +OCT2DEC = OCT.DECIMALE ## Converte un numero ottale in decimale +OCT2HEX = OCT.HEX ## Converte un numero ottale in esadecimale + + +## +## Financial functions Funzioni finanziarie +## +ACCRINT = INT.MATURATO.PER ## Restituisce l'interesse maturato di un titolo che paga interessi periodici +ACCRINTM = INT.MATURATO.SCAD ## Restituisce l'interesse maturato di un titolo che paga interessi alla scadenza +AMORDEGRC = AMMORT.DEGR ## Restituisce l'ammortamento per ogni periodo contabile utilizzando un coefficiente di ammortamento +AMORLINC = AMMORT.PER ## Restituisce l'ammortamento per ogni periodo contabile +COUPDAYBS = GIORNI.CED.INIZ.LIQ ## Restituisce il numero dei giorni che vanno dall'inizio del periodo di durata della cedola alla data di liquidazione +COUPDAYS = GIORNI.CED ## Restituisce il numero dei giorni relativi al periodo della cedola che contiene la data di liquidazione +COUPDAYSNC = GIORNI.CED.NUOVA ## Restituisce il numero di giorni che vanno dalla data di liquidazione alla data della cedola successiva +COUPNCD = DATA.CED.SUCC ## Restituisce un numero che rappresenta la data della cedola successiva alla data di liquidazione +COUPNUM = NUM.CED ## Restituisce il numero di cedole pagabili fra la data di liquidazione e la data di scadenza +COUPPCD = DATA.CED.PREC ## Restituisce un numero che rappresenta la data della cedola precedente alla data di liquidazione +CUMIPMT = INT.CUMUL ## Restituisce l'interesse cumulativo pagato fra due periodi +CUMPRINC = CAP.CUM ## Restituisce il capitale cumulativo pagato per estinguere un debito fra due periodi +DB = DB ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a quote fisse decrescenti +DDB = AMMORT ## Restituisce l'ammortamento di un bene per un periodo specificato utilizzando il metodo di ammortamento a doppie quote decrescenti o altri metodi specificati +DISC = TASSO.SCONTO ## Restituisce il tasso di sconto per un titolo +DOLLARDE = VALUTA.DEC ## Converte un prezzo valuta, espresso come frazione, in prezzo valuta, espresso come numero decimale +DOLLARFR = VALUTA.FRAZ ## Converte un prezzo valuta, espresso come numero decimale, in prezzo valuta, espresso come frazione +DURATION = DURATA ## Restituisce la durata annuale di un titolo con i pagamenti di interesse periodico +EFFECT = EFFETTIVO ## Restituisce l'effettivo tasso di interesse annuo +FV = VAL.FUT ## Restituisce il valore futuro di un investimento +FVSCHEDULE = VAL.FUT.CAPITALE ## Restituisce il valore futuro di un capitale iniziale dopo aver applicato una serie di tassi di interesse composti +INTRATE = TASSO.INT ## Restituisce il tasso di interesse per un titolo interamente investito +IPMT = INTERESSI ## Restituisce il valore degli interessi per un investimento relativo a un periodo specifico +IRR = TIR.COST ## Restituisce il tasso di rendimento interno per una serie di flussi di cassa +ISPMT = INTERESSE.RATA ## Calcola l'interesse di un investimento pagato durante un periodo specifico +MDURATION = DURATA.M ## Restituisce la durata Macauley modificata per un titolo con un valore presunto di € 100 +MIRR = TIR.VAR ## Restituisce il tasso di rendimento interno in cui i flussi di cassa positivi e negativi sono finanziati a tassi differenti +NOMINAL = NOMINALE ## Restituisce il tasso di interesse nominale annuale +NPER = NUM.RATE ## Restituisce un numero di periodi relativi a un investimento +NPV = VAN ## Restituisce il valore attuale netto di un investimento basato su una serie di flussi di cassa periodici e sul tasso di sconto +ODDFPRICE = PREZZO.PRIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente il primo periodo di durata irregolare +ODDFYIELD = REND.PRIMO.IRR ## Restituisce il rendimento di un titolo avente il primo periodo di durata irregolare +ODDLPRICE = PREZZO.ULTIMO.IRR ## Restituisce il prezzo di un titolo dal valore nominale di € 100 avente l'ultimo periodo di durata irregolare +ODDLYIELD = REND.ULTIMO.IRR ## Restituisce il rendimento di un titolo avente l'ultimo periodo di durata irregolare +PMT = RATA ## Restituisce il pagamento periodico di una rendita annua +PPMT = P.RATA ## Restituisce il pagamento sul capitale di un investimento per un dato periodo +PRICE = PREZZO ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga interessi periodici +PRICEDISC = PREZZO.SCONT ## Restituisce il prezzo di un titolo scontato dal valore nominale di € 100 +PRICEMAT = PREZZO.SCAD ## Restituisce il prezzo di un titolo dal valore nominale di € 100 che paga gli interessi alla scadenza +PV = VA ## Restituisce il valore attuale di un investimento +RATE = TASSO ## Restituisce il tasso di interesse per un periodo di un'annualità +RECEIVED = RICEV.SCAD ## Restituisce l'ammontare ricevuto alla scadenza di un titolo interamente investito +SLN = AMMORT.COST ## Restituisce l'ammortamento a quote costanti di un bene per un singolo periodo +SYD = AMMORT.ANNUO ## Restituisce l'ammortamento a somma degli anni di un bene per un periodo specificato +TBILLEQ = BOT.EQUIV ## Restituisce il rendimento equivalente ad un'obbligazione per un Buono ordinario del Tesoro +TBILLPRICE = BOT.PREZZO ## Restituisce il prezzo di un Buono del Tesoro dal valore nominale di € 100 +TBILLYIELD = BOT.REND ## Restituisce il rendimento di un Buono del Tesoro +VDB = AMMORT.VAR ## Restituisce l'ammortamento di un bene per un periodo specificato o parziale utilizzando il metodo a doppie quote proporzionali ai valori residui +XIRR = TIR.X ## Restituisce il tasso di rendimento interno di un impiego di flussi di cassa +XNPV = VAN.X ## Restituisce il valore attuale netto di un impiego di flussi di cassa non necessariamente periodici +YIELD = REND ## Restituisce il rendimento di un titolo che frutta interessi periodici +YIELDDISC = REND.TITOLI.SCONT ## Restituisce il rendimento annuale di un titolo scontato, ad esempio un Buono del Tesoro +YIELDMAT = REND.SCAD ## Restituisce il rendimento annuo di un titolo che paga interessi alla scadenza + + +## +## Information functions Funzioni relative alle informazioni +## +CELL = CELLA ## Restituisce le informazioni sulla formattazione, la posizione o i contenuti di una cella +ERROR.TYPE = ERRORE.TIPO ## Restituisce un numero che corrisponde a un tipo di errore +INFO = INFO ## Restituisce le informazioni sull'ambiente operativo corrente +ISBLANK = VAL.VUOTO ## Restituisce VERO se il valore è vuoto +ISERR = VAL.ERR ## Restituisce VERO se il valore è un valore di errore qualsiasi tranne #N/D +ISERROR = VAL.ERRORE ## Restituisce VERO se il valore è un valore di errore qualsiasi +ISEVEN = VAL.PARI ## Restituisce VERO se il numero è pari +ISLOGICAL = VAL.LOGICO ## Restituisce VERO se il valore è un valore logico +ISNA = VAL.NON.DISP ## Restituisce VERO se il valore è un valore di errore #N/D +ISNONTEXT = VAL.NON.TESTO ## Restituisce VERO se il valore non è in formato testo +ISNUMBER = VAL.NUMERO ## Restituisce VERO se il valore è un numero +ISODD = VAL.DISPARI ## Restituisce VERO se il numero è dispari +ISREF = VAL.RIF ## Restituisce VERO se il valore è un riferimento +ISTEXT = VAL.TESTO ## Restituisce VERO se il valore è in formato testo +N = NUM ## Restituisce un valore convertito in numero +NA = NON.DISP ## Restituisce il valore di errore #N/D +TYPE = TIPO ## Restituisce un numero che indica il tipo di dati relativi a un valore + + +## +## Logical functions Funzioni logiche +## +AND = E ## Restituisce VERO se tutti gli argomenti sono VERO +FALSE = FALSO ## Restituisce il valore logico FALSO +IF = SE ## Specifica un test logico da eseguire +IFERROR = SE.ERRORE ## Restituisce un valore specificato se una formula fornisce un errore come risultato; in caso contrario, restituisce il risultato della formula +NOT = NON ## Inverte la logica degli argomenti +OR = O ## Restituisce VERO se un argomento qualsiasi è VERO +TRUE = VERO ## Restituisce il valore logico VERO + + +## +## Lookup and reference functions Funzioni di ricerca e di riferimento +## +ADDRESS = INDIRIZZO ## Restituisce un riferimento come testo in una singola cella di un foglio di lavoro +AREAS = AREE ## Restituisce il numero di aree in un riferimento +CHOOSE = SCEGLI ## Sceglie un valore da un elenco di valori +COLUMN = RIF.COLONNA ## Restituisce il numero di colonna di un riferimento +COLUMNS = COLONNE ## Restituisce il numero di colonne in un riferimento +HLOOKUP = CERCA.ORIZZ ## Effettua una ricerca nella riga superiore di una matrice e restituisce il valore della cella specificata +HYPERLINK = COLLEG.IPERTESTUALE ## Crea un collegamento che apre un documento memorizzato in un server di rete, una rete Intranet o Internet +INDEX = INDICE ## Utilizza un indice per scegliere un valore da un riferimento o da una matrice +INDIRECT = INDIRETTO ## Restituisce un riferimento specificato da un valore testo +LOOKUP = CERCA ## Ricerca i valori in un vettore o in una matrice +MATCH = CONFRONTA ## Ricerca i valori in un riferimento o in una matrice +OFFSET = SCARTO ## Restituisce uno scarto di riferimento da un riferimento dato +ROW = RIF.RIGA ## Restituisce il numero di riga di un riferimento +ROWS = RIGHE ## Restituisce il numero delle righe in un riferimento +RTD = DATITEMPOREALE ## Recupera dati in tempo reale da un programma che supporta l'automazione COM (automazione: Metodo per utilizzare gli oggetti di un'applicazione da un'altra applicazione o da un altro strumento di sviluppo. Precedentemente nota come automazione OLE, l'automazione è uno standard del settore e una caratteristica del modello COM (Component Object Model).) +TRANSPOSE = MATR.TRASPOSTA ## Restituisce la trasposizione di una matrice +VLOOKUP = CERCA.VERT ## Effettua una ricerca nella prima colonna di una matrice e si sposta attraverso la riga per restituire il valore di una cella + + +## +## Math and trigonometry functions Funzioni matematiche e trigonometriche +## +ABS = ASS ## Restituisce il valore assoluto di un numero. +ACOS = ARCCOS ## Restituisce l'arcocoseno di un numero +ACOSH = ARCCOSH ## Restituisce l'inverso del coseno iperbolico di un numero +ASIN = ARCSEN ## Restituisce l'arcoseno di un numero +ASINH = ARCSENH ## Restituisce l'inverso del seno iperbolico di un numero +ATAN = ARCTAN ## Restituisce l'arcotangente di un numero +ATAN2 = ARCTAN.2 ## Restituisce l'arcotangente delle coordinate x e y specificate +ATANH = ARCTANH ## Restituisce l'inverso della tangente iperbolica di un numero +CEILING = ARROTONDA.ECCESSO ## Arrotonda un numero per eccesso all'intero più vicino o al multiplo più vicino a peso +COMBIN = COMBINAZIONE ## Restituisce il numero di combinazioni possibili per un numero assegnato di elementi +COS = COS ## Restituisce il coseno dell'angolo specificato +COSH = COSH ## Restituisce il coseno iperbolico di un numero +DEGREES = GRADI ## Converte i radianti in gradi +EVEN = PARI ## Arrotonda il valore assoluto di un numero per eccesso al più vicino intero pari +EXP = ESP ## Restituisce il numero e elevato alla potenza di num +FACT = FATTORIALE ## Restituisce il fattoriale di un numero +FACTDOUBLE = FATT.DOPPIO ## Restituisce il fattoriale doppio di un numero +FLOOR = ARROTONDA.DIFETTO ## Arrotonda un numero per difetto al multiplo più vicino a zero +GCD = MCD ## Restituisce il massimo comune divisore +INT = INT ## Arrotonda un numero per difetto al numero intero più vicino +LCM = MCM ## Restituisce il minimo comune multiplo +LN = LN ## Restituisce il logaritmo naturale di un numero +LOG = LOG ## Restituisce il logaritmo di un numero in una specificata base +LOG10 = LOG10 ## Restituisce il logaritmo in base 10 di un numero +MDETERM = MATR.DETERM ## Restituisce il determinante di una matrice +MINVERSE = MATR.INVERSA ## Restituisce l'inverso di una matrice +MMULT = MATR.PRODOTTO ## Restituisce il prodotto di due matrici +MOD = RESTO ## Restituisce il resto della divisione +MROUND = ARROTONDA.MULTIPLO ## Restituisce un numero arrotondato al multiplo desiderato +MULTINOMIAL = MULTINOMIALE ## Restituisce il multinomiale di un insieme di numeri +ODD = DISPARI ## Arrotonda un numero per eccesso al più vicino intero dispari +PI = PI.GRECO ## Restituisce il valore di pi greco +POWER = POTENZA ## Restituisce il risultato di un numero elevato a potenza +PRODUCT = PRODOTTO ## Moltiplica i suoi argomenti +QUOTIENT = QUOZIENTE ## Restituisce la parte intera di una divisione +RADIANS = RADIANTI ## Converte i gradi in radianti +RAND = CASUALE ## Restituisce un numero casuale compreso tra 0 e 1 +RANDBETWEEN = CASUALE.TRA ## Restituisce un numero casuale compreso tra i numeri specificati +ROMAN = ROMANO ## Restituisce il numero come numero romano sotto forma di testo +ROUND = ARROTONDA ## Arrotonda il numero al numero di cifre specificato +ROUNDDOWN = ARROTONDA.PER.DIF ## Arrotonda il valore assoluto di un numero per difetto +ROUNDUP = ARROTONDA.PER.ECC ## Arrotonda il valore assoluto di un numero per eccesso +SERIESSUM = SOMMA.SERIE ## Restituisce la somma di una serie di potenze in base alla formula +SIGN = SEGNO ## Restituisce il segno di un numero +SIN = SEN ## Restituisce il seno di un dato angolo +SINH = SENH ## Restituisce il seno iperbolico di un numero +SQRT = RADQ ## Restituisce una radice quadrata +SQRTPI = RADQ.PI.GRECO ## Restituisce la radice quadrata di un numero (numero * pi greco) +SUBTOTAL = SUBTOTALE ## Restituisce un subtotale in un elenco o in un database +SUM = SOMMA ## Somma i suoi argomenti +SUMIF = SOMMA.SE ## Somma le celle specificate da un dato criterio +SUMIFS = SOMMA.PIÙ.SE ## Somma le celle in un intervallo che soddisfano più criteri +SUMPRODUCT = MATR.SOMMA.PRODOTTO ## Restituisce la somma dei prodotti dei componenti corrispondenti della matrice +SUMSQ = SOMMA.Q ## Restituisce la somma dei quadrati degli argomenti +SUMX2MY2 = SOMMA.DIFF.Q ## Restituisce la somma della differenza dei quadrati dei corrispondenti elementi in due matrici +SUMX2PY2 = SOMMA.SOMMA.Q ## Restituisce la somma della somma dei quadrati dei corrispondenti elementi in due matrici +SUMXMY2 = SOMMA.Q.DIFF ## Restituisce la somma dei quadrati delle differenze dei corrispondenti elementi in due matrici +TAN = TAN ## Restituisce la tangente di un numero +TANH = TANH ## Restituisce la tangente iperbolica di un numero +TRUNC = TRONCA ## Tronca la parte decimale di un numero + + +## +## Statistical functions Funzioni statistiche +## +AVEDEV = MEDIA.DEV ## Restituisce la media delle deviazioni assolute delle coordinate rispetto alla loro media +AVERAGE = MEDIA ## Restituisce la media degli argomenti +AVERAGEA = MEDIA.VALORI ## Restituisce la media degli argomenti, inclusi i numeri, il testo e i valori logici +AVERAGEIF = MEDIA.SE ## Restituisce la media aritmetica di tutte le celle in un intervallo che soddisfano un determinato criterio +AVERAGEIFS = MEDIA.PIÙ.SE ## Restituisce la media aritmetica di tutte le celle che soddisfano più criteri +BETADIST = DISTRIB.BETA ## Restituisce la funzione di distribuzione cumulativa beta +BETAINV = INV.BETA ## Restituisce l'inverso della funzione di distribuzione cumulativa per una distribuzione beta specificata +BINOMDIST = DISTRIB.BINOM ## Restituisce la distribuzione binomiale per il termine individuale +CHIDIST = DISTRIB.CHI ## Restituisce la probabilità a una coda per la distribuzione del chi quadrato +CHIINV = INV.CHI ## Restituisce l'inverso della probabilità ad una coda per la distribuzione del chi quadrato +CHITEST = TEST.CHI ## Restituisce il test per l'indipendenza +CONFIDENCE = CONFIDENZA ## Restituisce l'intervallo di confidenza per una popolazione +CORREL = CORRELAZIONE ## Restituisce il coefficiente di correlazione tra due insiemi di dati +COUNT = CONTA.NUMERI ## Conta la quantità di numeri nell'elenco di argomenti +COUNTA = CONTA.VALORI ## Conta il numero di valori nell'elenco di argomenti +COUNTBLANK = CONTA.VUOTE ## Conta il numero di celle vuote all'interno di un intervallo +COUNTIF = CONTA.SE ## Conta il numero di celle all'interno di un intervallo che soddisfa i criteri specificati +COUNTIFS = CONTA.PIÙ.SE ## Conta il numero di celle in un intervallo che soddisfano più criteri. +COVAR = COVARIANZA ## Calcola la covarianza, la media dei prodotti delle deviazioni accoppiate +CRITBINOM = CRIT.BINOM ## Restituisce il più piccolo valore per il quale la distribuzione cumulativa binomiale risulta maggiore o uguale ad un valore di criterio +DEVSQ = DEV.Q ## Restituisce la somma dei quadrati delle deviazioni +EXPONDIST = DISTRIB.EXP ## Restituisce la distribuzione esponenziale +FDIST = DISTRIB.F ## Restituisce la distribuzione di probabilità F +FINV = INV.F ## Restituisce l'inverso della distribuzione della probabilità F +FISHER = FISHER ## Restituisce la trasformazione di Fisher +FISHERINV = INV.FISHER ## Restituisce l'inverso della trasformazione di Fisher +FORECAST = PREVISIONE ## Restituisce i valori lungo una tendenza lineare +FREQUENCY = FREQUENZA ## Restituisce la distribuzione di frequenza come matrice verticale +FTEST = TEST.F ## Restituisce il risultato di un test F +GAMMADIST = DISTRIB.GAMMA ## Restituisce la distribuzione gamma +GAMMAINV = INV.GAMMA ## Restituisce l'inverso della distribuzione cumulativa gamma +GAMMALN = LN.GAMMA ## Restituisce il logaritmo naturale della funzione gamma, G(x) +GEOMEAN = MEDIA.GEOMETRICA ## Restituisce la media geometrica +GROWTH = CRESCITA ## Restituisce i valori lungo una linea di tendenza esponenziale +HARMEAN = MEDIA.ARMONICA ## Restituisce la media armonica +HYPGEOMDIST = DISTRIB.IPERGEOM ## Restituisce la distribuzione ipergeometrica +INTERCEPT = INTERCETTA ## Restituisce l'intercetta della retta di regressione lineare +KURT = CURTOSI ## Restituisce la curtosi di un insieme di dati +LARGE = GRANDE ## Restituisce il k-esimo valore più grande in un insieme di dati +LINEST = REGR.LIN ## Restituisce i parametri di una tendenza lineare +LOGEST = REGR.LOG ## Restituisce i parametri di una linea di tendenza esponenziale +LOGINV = INV.LOGNORM ## Restituisce l'inverso di una distribuzione lognormale +LOGNORMDIST = DISTRIB.LOGNORM ## Restituisce la distribuzione lognormale cumulativa +MAX = MAX ## Restituisce il valore massimo in un elenco di argomenti +MAXA = MAX.VALORI ## Restituisce il valore massimo in un elenco di argomenti, inclusi i numeri, il testo e i valori logici +MEDIAN = MEDIANA ## Restituisce la mediana dei numeri specificati +MIN = MIN ## Restituisce il valore minimo in un elenco di argomenti +MINA = MIN.VALORI ## Restituisce il più piccolo valore in un elenco di argomenti, inclusi i numeri, il testo e i valori logici +MODE = MODA ## Restituisce il valore più comune in un insieme di dati +NEGBINOMDIST = DISTRIB.BINOM.NEG ## Restituisce la distribuzione binomiale negativa +NORMDIST = DISTRIB.NORM ## Restituisce la distribuzione cumulativa normale +NORMINV = INV.NORM ## Restituisce l'inverso della distribuzione cumulativa normale standard +NORMSDIST = DISTRIB.NORM.ST ## Restituisce la distribuzione cumulativa normale standard +NORMSINV = INV.NORM.ST ## Restituisce l'inverso della distribuzione cumulativa normale +PEARSON = PEARSON ## Restituisce il coefficiente del momento di correlazione di Pearson +PERCENTILE = PERCENTILE ## Restituisce il k-esimo dato percentile di valori in un intervallo +PERCENTRANK = PERCENT.RANGO ## Restituisce il rango di un valore in un insieme di dati come percentuale +PERMUT = PERMUTAZIONE ## Restituisce il numero delle permutazioni per un determinato numero di oggetti +POISSON = POISSON ## Restituisce la distribuzione di Poisson +PROB = PROBABILITÀ ## Calcola la probabilità che dei valori in un intervallo siano compresi tra due limiti +QUARTILE = QUARTILE ## Restituisce il quartile di un insieme di dati +RANK = RANGO ## Restituisce il rango di un numero in un elenco di numeri +RSQ = RQ ## Restituisce la radice quadrata del coefficiente di momento di correlazione di Pearson +SKEW = ASIMMETRIA ## Restituisce il grado di asimmetria di una distribuzione +SLOPE = PENDENZA ## Restituisce la pendenza di una retta di regressione lineare +SMALL = PICCOLO ## Restituisce il k-esimo valore più piccolo in un insieme di dati +STANDARDIZE = NORMALIZZA ## Restituisce un valore normalizzato +STDEV = DEV.ST ## Restituisce una stima della deviazione standard sulla base di un campione +STDEVA = DEV.ST.VALORI ## Restituisce una stima della deviazione standard sulla base di un campione, inclusi i numeri, il testo e i valori logici +STDEVP = DEV.ST.POP ## Calcola la deviazione standard sulla base di un'intera popolazione +STDEVPA = DEV.ST.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici +STEYX = ERR.STD.YX ## Restituisce l'errore standard del valore previsto per y per ogni valore x nella regressione +TDIST = DISTRIB.T ## Restituisce la distribuzione t di Student +TINV = INV.T ## Restituisce l'inversa della distribuzione t di Student +TREND = TENDENZA ## Restituisce i valori lungo una linea di tendenza lineare +TRIMMEAN = MEDIA.TRONCATA ## Restituisce la media della parte interna di un insieme di dati +TTEST = TEST.T ## Restituisce la probabilità associata ad un test t di Student +VAR = VAR ## Stima la varianza sulla base di un campione +VARA = VAR.VALORI ## Stima la varianza sulla base di un campione, inclusi i numeri, il testo e i valori logici +VARP = VAR.POP ## Calcola la varianza sulla base dell'intera popolazione +VARPA = VAR.POP.VALORI ## Calcola la deviazione standard sulla base sull'intera popolazione, inclusi i numeri, il testo e i valori logici +WEIBULL = WEIBULL ## Restituisce la distribuzione di Weibull +ZTEST = TEST.Z ## Restituisce il valore di probabilità a una coda per un test z + + +## +## Text functions Funzioni di testo +## +ASC = ASC ## Modifica le lettere inglesi o il katakana a doppio byte all'interno di una stringa di caratteri in caratteri a singolo byte +BAHTTEXT = BAHTTESTO ## Converte un numero in testo, utilizzando il formato valuta ß (baht) +CHAR = CODICE.CARATT ## Restituisce il carattere specificato dal numero di codice +CLEAN = LIBERA ## Elimina dal testo tutti i caratteri che non è possibile stampare +CODE = CODICE ## Restituisce il codice numerico del primo carattere di una stringa di testo +CONCATENATE = CONCATENA ## Unisce diversi elementi di testo in un unico elemento di testo +DOLLAR = VALUTA ## Converte un numero in testo, utilizzando il formato valuta € (euro) +EXACT = IDENTICO ## Verifica se due valori di testo sono uguali +FIND = TROVA ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) +FINDB = TROVA.B ## Rileva un valore di testo all'interno di un altro (distinzione tra maiuscole e minuscole) +FIXED = FISSO ## Formatta un numero come testo con un numero fisso di decimali +JIS = ORDINAMENTO.JIS ## Modifica le lettere inglesi o i caratteri katakana a byte singolo all'interno di una stringa di caratteri in caratteri a byte doppio. +LEFT = SINISTRA ## Restituisce il carattere più a sinistra di un valore di testo +LEFTB = SINISTRA.B ## Restituisce il carattere più a sinistra di un valore di testo +LEN = LUNGHEZZA ## Restituisce il numero di caratteri di una stringa di testo +LENB = LUNB ## Restituisce il numero di caratteri di una stringa di testo +LOWER = MINUSC ## Converte il testo in lettere minuscole +MID = MEDIA ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata +MIDB = MEDIA.B ## Restituisce un numero specifico di caratteri di una stringa di testo a partire dalla posizione specificata +PHONETIC = FURIGANA ## Estrae i caratteri fonetici (furigana) da una stringa di testo. +PROPER = MAIUSC.INIZ ## Converte in maiuscolo la prima lettera di ogni parola di un valore di testo +REPLACE = RIMPIAZZA ## Sostituisce i caratteri all'interno di un testo +REPLACEB = SOSTITUISCI.B ## Sostituisce i caratteri all'interno di un testo +REPT = RIPETI ## Ripete un testo per un dato numero di volte +RIGHT = DESTRA ## Restituisce il carattere più a destra di un valore di testo +RIGHTB = DESTRA.B ## Restituisce il carattere più a destra di un valore di testo +SEARCH = RICERCA ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) +SEARCHB = CERCA.B ## Rileva un valore di testo all'interno di un altro (non è sensibile alle maiuscole e minuscole) +SUBSTITUTE = SOSTITUISCI ## Sostituisce il nuovo testo al testo contenuto in una stringa +T = T ## Converte gli argomenti in testo +TEXT = TESTO ## Formatta un numero e lo converte in testo +TRIM = ANNULLA.SPAZI ## Elimina gli spazi dal testo +UPPER = MAIUSC ## Converte il testo in lettere maiuscole +VALUE = VALORE ## Converte un argomento di testo in numero diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/config new file mode 100644 index 00000000..48dcc15b --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #LEEG! +DIV0 = #DEEL/0! +VALUE = #WAARDE! +REF = #VERW! +NAME = #NAAM? +NUM = #GETAL! +NA = #N/B diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/functions new file mode 100644 index 00000000..573600ac --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/nl/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Automatiseringsfuncties en functies in invoegtoepassingen +## +GETPIVOTDATA = DRAAITABEL.OPHALEN ## Geeft gegevens uit een draaitabelrapport als resultaat + + +## +## Cube functions Kubusfuncties +## +CUBEKPIMEMBER = KUBUSKPILID ## Retourneert de naam, eigenschap en waarde van een KPI (prestatie-indicator) en geeft de naam en de eigenschap in de cel weer. Een KPI is een meetbare waarde, zoals de maandelijkse brutowinst of de omzet per kwartaal per werknemer, die wordt gebruikt om de prestaties van een organisatie te bewaken +CUBEMEMBER = KUBUSLID ## Retourneert een lid of tupel in een kubushiërarchie. Wordt gebruikt om te controleren of het lid of de tupel in de kubus aanwezig is +CUBEMEMBERPROPERTY = KUBUSLIDEIGENSCHAP ## Retourneert de waarde van een lideigenschap in de kubus. Wordt gebruikt om te controleren of de lidnaam in de kubus bestaat en retourneert de opgegeven eigenschap voor dit lid +CUBERANKEDMEMBER = KUBUSGERANGCHIKTLID ## Retourneert het zoveelste, gerangschikte lid in een set. Wordt gebruikt om een of meer elementen in een set te retourneren, zoals de tien beste verkopers of de tien beste studenten +CUBESET = KUBUSSET ## Definieert een berekende set leden of tupels door een ingestelde expressie naar de kubus op de server te sturen, alwaar de set wordt gemaakt en vervolgens wordt geretourneerd naar Microsoft Office Excel +CUBESETCOUNT = KUBUSSETAANTAL ## Retourneert het aantal onderdelen in een set +CUBEVALUE = KUBUSWAARDE ## Retourneert een samengestelde waarde van een kubus + + +## +## Database functions Databasefuncties +## +DAVERAGE = DBGEMIDDELDE ## Berekent de gemiddelde waarde in geselecteerde databasegegevens +DCOUNT = DBAANTAL ## Telt de cellen met getallen in een database +DCOUNTA = DBAANTALC ## Telt de niet-lege cellen in een database +DGET = DBLEZEN ## Retourneert één record dat voldoet aan de opgegeven criteria uit een database +DMAX = DBMAX ## Retourneert de maximumwaarde in de geselecteerde databasegegevens +DMIN = DBMIN ## Retourneert de minimumwaarde in de geselecteerde databasegegevens +DPRODUCT = DBPRODUCT ## Vermenigvuldigt de waarden in een bepaald veld van de records die voldoen aan de criteria in een database +DSTDEV = DBSTDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef uit geselecteerde databasegegevens +DSTDEVP = DBSTDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie van geselecteerde databasegegevens +DSUM = DBSOM ## Telt de getallen uit een kolom records in de database op die voldoen aan de criteria +DVAR = DBVAR ## Maakt een schatting van de variantie op basis van een steekproef uit geselecteerde databasegegevens +DVARP = DBVARP ## Berekent de variantie op basis van de volledige populatie van geselecteerde databasegegevens + + +## +## Date and time functions Datum- en tijdfuncties +## +DATE = DATUM ## Geeft als resultaat het seriële getal van een opgegeven datum +DATEVALUE = DATUMWAARDE ## Converteert een datum in de vorm van tekst naar een serieel getal +DAY = DAG ## Converteert een serieel getal naar een dag van de maand +DAYS360 = DAGEN360 ## Berekent het aantal dagen tussen twee datums op basis van een jaar met 360 dagen +EDATE = ZELFDE.DAG ## Geeft als resultaat het seriële getal van een datum die het opgegeven aantal maanden voor of na de begindatum ligt +EOMONTH = LAATSTE.DAG ## Geeft als resultaat het seriële getal van de laatste dag van de maand voor of na het opgegeven aantal maanden +HOUR = UUR ## Converteert een serieel getal naar uren +MINUTE = MINUUT ## Converteert een serieel naar getal minuten +MONTH = MAAND ## Converteert een serieel getal naar een maand +NETWORKDAYS = NETTO.WERKDAGEN ## Geeft als resultaat het aantal hele werkdagen tussen twee datums +NOW = NU ## Geeft als resultaat het seriële getal van de huidige datum en tijd +SECOND = SECONDE ## Converteert een serieel getal naar seconden +TIME = TIJD ## Geeft als resultaat het seriële getal van een bepaald tijdstip +TIMEVALUE = TIJDWAARDE ## Converteert de tijd in de vorm van tekst naar een serieel getal +TODAY = VANDAAG ## Geeft als resultaat het seriële getal van de huidige datum +WEEKDAY = WEEKDAG ## Converteert een serieel getal naar een weekdag +WEEKNUM = WEEKNUMMER ## Converteert een serieel getal naar een weeknummer +WORKDAY = WERKDAG ## Geeft als resultaat het seriële getal van de datum voor of na een bepaald aantal werkdagen +YEAR = JAAR ## Converteert een serieel getal naar een jaar +YEARFRAC = JAAR.DEEL ## Geeft als resultaat het gedeelte van het jaar, uitgedrukt in het aantal hele dagen tussen begindatum en einddatum + + +## +## Engineering functions Technische functies +## +BESSELI = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie In(x) +BESSELJ = BESSEL.J ## Geeft als resultaat de Bessel-functie Jn(x) +BESSELK = BESSEL.K ## Geeft als resultaat de gewijzigde Bessel-functie Kn(x) +BESSELY = BESSEL.Y ## Geeft als resultaat de gewijzigde Bessel-functie Yn(x) +BIN2DEC = BIN.N.DEC ## Converteert een binair getal naar een decimaal getal +BIN2HEX = BIN.N.HEX ## Converteert een binair getal naar een hexadecimaal getal +BIN2OCT = BIN.N.OCT ## Converteert een binair getal naar een octaal getal +COMPLEX = COMPLEX ## Converteert reële en imaginaire coëfficiënten naar een complex getal +CONVERT = CONVERTEREN ## Converteert een getal in de ene maateenheid naar een getal in een andere maateenheid +DEC2BIN = DEC.N.BIN ## Converteert een decimaal getal naar een binair getal +DEC2HEX = DEC.N.HEX ## Converteert een decimaal getal naar een hexadecimaal getal +DEC2OCT = DEC.N.OCT ## Converteert een decimaal getal naar een octaal getal +DELTA = DELTA ## Test of twee waarden gelijk zijn +ERF = FOUTFUNCTIE ## Geeft als resultaat de foutfunctie +ERFC = FOUT.COMPLEMENT ## Geeft als resultaat de complementaire foutfunctie +GESTEP = GROTER.DAN ## Test of een getal groter is dan de drempelwaarde +HEX2BIN = HEX.N.BIN ## Converteert een hexadecimaal getal naar een binair getal +HEX2DEC = HEX.N.DEC ## Converteert een hexadecimaal getal naar een decimaal getal +HEX2OCT = HEX.N.OCT ## Converteert een hexadecimaal getal naar een octaal getal +IMABS = C.ABS ## Geeft als resultaat de absolute waarde (modulus) van een complex getal +IMAGINARY = C.IM.DEEL ## Geeft als resultaat de imaginaire coëfficiënt van een complex getal +IMARGUMENT = C.ARGUMENT ## Geeft als resultaat het argument thèta, een hoek uitgedrukt in radialen +IMCONJUGATE = C.TOEGEVOEGD ## Geeft als resultaat het complexe toegevoegde getal van een complex getal +IMCOS = C.COS ## Geeft als resultaat de cosinus van een complex getal +IMDIV = C.QUOTIENT ## Geeft als resultaat het quotiënt van twee complexe getallen +IMEXP = C.EXP ## Geeft als resultaat de exponent van een complex getal +IMLN = C.LN ## Geeft als resultaat de natuurlijke logaritme van een complex getal +IMLOG10 = C.LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een complex getal +IMLOG2 = C.LOG2 ## Geeft als resultaat de logaritme met grondtal 2 van een complex getal +IMPOWER = C.MACHT ## Geeft als resultaat een complex getal dat is verheven tot de macht van een geheel getal +IMPRODUCT = C.PRODUCT ## Geeft als resultaat het product van complexe getallen +IMREAL = C.REEEL.DEEL ## Geeft als resultaat de reële coëfficiënt van een complex getal +IMSIN = C.SIN ## Geeft als resultaat de sinus van een complex getal +IMSQRT = C.WORTEL ## Geeft als resultaat de vierkantswortel van een complex getal +IMSUB = C.VERSCHIL ## Geeft als resultaat het verschil tussen twee complexe getallen +IMSUM = C.SOM ## Geeft als resultaat de som van complexe getallen +OCT2BIN = OCT.N.BIN ## Converteert een octaal getal naar een binair getal +OCT2DEC = OCT.N.DEC ## Converteert een octaal getal naar een decimaal getal +OCT2HEX = OCT.N.HEX ## Converteert een octaal getal naar een hexadecimaal getal + + +## +## Financial functions Financiële functies +## +ACCRINT = SAMENG.RENTE ## Berekent de opgelopen rente voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +ACCRINTM = SAMENG.RENTE.V ## Berekent de opgelopen rente voor een waardepapier waarvan de rente op de vervaldatum wordt uitgekeerd +AMORDEGRC = AMORDEGRC ## Geeft als resultaat de afschrijving voor elke boekingsperiode door een afschrijvingscoëfficiënt toe te passen +AMORLINC = AMORLINC ## Berekent de afschrijving voor elke boekingsperiode +COUPDAYBS = COUP.DAGEN.BB ## Berekent het aantal dagen vanaf het begin van de coupontermijn tot de stortingsdatum +COUPDAYS = COUP.DAGEN ## Geeft als resultaat het aantal dagen in de coupontermijn waarin de stortingsdatum valt +COUPDAYSNC = COUP.DAGEN.VV ## Geeft als resultaat het aantal dagen vanaf de stortingsdatum tot de volgende couponvervaldatum +COUPNCD = COUP.DATUM.NB ## Geeft als resultaat de volgende coupondatum na de stortingsdatum +COUPNUM = COUP.AANTAL ## Geeft als resultaat het aantal coupons dat nog moet worden uitbetaald tussen de stortingsdatum en de vervaldatum +COUPPCD = COUP.DATUM.VB ## Geeft als resultaat de vorige couponvervaldatum vóór de stortingsdatum +CUMIPMT = CUM.RENTE ## Geeft als resultaat de cumulatieve rente die tussen twee termijnen is uitgekeerd +CUMPRINC = CUM.HOOFDSOM ## Geeft als resultaat de cumulatieve hoofdsom van een lening die tussen twee termijnen is terugbetaald +DB = DB ## Geeft als resultaat de afschrijving van activa voor een bepaalde periode met behulp van de 'fixed declining balance'-methode +DDB = DDB ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'double declining balance'-methode of een andere methode die u opgeeft +DISC = DISCONTO ## Geeft als resultaat het discontopercentage voor een waardepapier +DOLLARDE = EURO.DE ## Converteert een prijs in euro's, uitgedrukt in een breuk, naar een prijs in euro's, uitgedrukt in een decimaal getal +DOLLARFR = EURO.BR ## Converteert een prijs in euro's, uitgedrukt in een decimaal getal, naar een prijs in euro's, uitgedrukt in een breuk +DURATION = DUUR ## Geeft als resultaat de gewogen gemiddelde looptijd voor een waardepapier met periodieke rentebetalingen +EFFECT = EFFECT.RENTE ## Geeft als resultaat het effectieve jaarlijkse rentepercentage +FV = TW ## Geeft als resultaat de toekomstige waarde van een investering +FVSCHEDULE = TOEK.WAARDE2 ## Geeft als resultaat de toekomstige waarde van een bepaalde hoofdsom na het toepassen van een reeks samengestelde rentepercentages +INTRATE = RENTEPERCENTAGE ## Geeft als resultaat het rentepercentage voor een volgestort waardepapier +IPMT = IBET ## Geeft als resultaat de te betalen rente voor een investering over een bepaalde termijn +IRR = IR ## Geeft als resultaat de interne rentabiliteit voor een reeks cashflows +ISPMT = ISBET ## Geeft als resultaat de rente die is betaald tijdens een bepaalde termijn van een investering +MDURATION = AANG.DUUR ## Geeft als resultaat de aangepaste Macauley-looptijd voor een waardepapier, aangenomen dat de nominale waarde € 100 bedraagt +MIRR = GIR ## Geeft als resultaat de interne rentabiliteit voor een serie cashflows, waarbij voor betalingen een ander rentepercentage geldt dan voor inkomsten +NOMINAL = NOMINALE.RENTE ## Geeft als resultaat het nominale jaarlijkse rentepercentage +NPER = NPER ## Geeft als resultaat het aantal termijnen van een investering +NPV = NHW ## Geeft als resultaat de netto huidige waarde van een investering op basis van een reeks periodieke cashflows en een discontopercentage +ODDFPRICE = AFW.ET.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende eerste termijn +ODDFYIELD = AFW.ET.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende eerste termijn +ODDLPRICE = AFW.LT.PRIJS ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier met een afwijkende laatste termijn +ODDLYIELD = AFW.LT.REND ## Geeft als resultaat het rendement voor een waardepapier met een afwijkende laatste termijn +PMT = BET ## Geeft als resultaat de periodieke betaling voor een annuïteit +PPMT = PBET ## Geeft als resultaat de afbetaling op de hoofdsom voor een bepaalde termijn +PRICE = PRIJS.NOM ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +PRICEDISC = PRIJS.DISCONTO ## Geeft als resultaat de prijs per € 100 nominale waarde voor een verdisconteerd waardepapier +PRICEMAT = PRIJS.VERVALDAG ## Geeft als resultaat de prijs per € 100 nominale waarde voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum +PV = HW ## Geeft als resultaat de huidige waarde van een investering +RATE = RENTE ## Geeft als resultaat het periodieke rentepercentage voor een annuïteit +RECEIVED = OPBRENGST ## Geeft als resultaat het bedrag dat op de vervaldatum wordt uitgekeerd voor een volgestort waardepapier +SLN = LIN.AFSCHR ## Geeft als resultaat de lineaire afschrijving van activa over één termijn +SYD = SYD ## Geeft als resultaat de afschrijving van activa over een bepaalde termijn met behulp van de 'Sum-Of-Years-Digits'-methode +TBILLEQ = SCHATK.OBL ## Geeft als resultaat het rendement op schatkistpapier, dat op dezelfde manier wordt berekend als het rendement op obligaties +TBILLPRICE = SCHATK.PRIJS ## Bepaalt de prijs per € 100 nominale waarde voor schatkistpapier +TBILLYIELD = SCHATK.REND ## Berekent het rendement voor schatkistpapier +VDB = VDB ## Geeft als resultaat de afschrijving van activa over een gehele of gedeeltelijke termijn met behulp van de 'declining balance'-methode +XIRR = IR.SCHEMA ## Berekent de interne rentabiliteit voor een betalingsschema van cashflows +XNPV = NHW2 ## Berekent de huidige nettowaarde voor een betalingsschema van cashflows +YIELD = RENDEMENT ## Geeft als resultaat het rendement voor een waardepapier waarvan de rente periodiek wordt uitgekeerd +YIELDDISC = REND.DISCONTO ## Geeft als resultaat het jaarlijkse rendement voor een verdisconteerd waardepapier, bijvoorbeeld schatkistpapier +YIELDMAT = REND.VERVAL ## Geeft als resultaat het jaarlijkse rendement voor een waardepapier waarvan de rente wordt uitgekeerd op de vervaldatum + + +## +## Information functions Informatiefuncties +## +CELL = CEL ## Geeft als resultaat informatie over de opmaak, locatie of inhoud van een cel +ERROR.TYPE = TYPE.FOUT ## Geeft als resultaat een getal dat overeenkomt met een van de foutwaarden van Microsoft Excel +INFO = INFO ## Geeft als resultaat informatie over de huidige besturingsomgeving +ISBLANK = ISLEEG ## Geeft als resultaat WAAR als de waarde leeg is +ISERR = ISFOUT2 ## Geeft als resultaat WAAR als de waarde een foutwaarde is, met uitzondering van #N/B +ISERROR = ISFOUT ## Geeft als resultaat WAAR als de waarde een foutwaarde is +ISEVEN = IS.EVEN ## Geeft als resultaat WAAR als het getal even is +ISLOGICAL = ISLOGISCH ## Geeft als resultaat WAAR als de waarde een logische waarde is +ISNA = ISNB ## Geeft als resultaat WAAR als de waarde de foutwaarde #N/B is +ISNONTEXT = ISGEENTEKST ## Geeft als resultaat WAAR als de waarde geen tekst is +ISNUMBER = ISGETAL ## Geeft als resultaat WAAR als de waarde een getal is +ISODD = IS.ONEVEN ## Geeft als resultaat WAAR als het getal oneven is +ISREF = ISVERWIJZING ## Geeft als resultaat WAAR als de waarde een verwijzing is +ISTEXT = ISTEKST ## Geeft als resultaat WAAR als de waarde tekst is +N = N ## Geeft als resultaat een waarde die is geconverteerd naar een getal +NA = NB ## Geeft als resultaat de foutwaarde #N/B +TYPE = TYPE ## Geeft als resultaat een getal dat het gegevenstype van een waarde aangeeft + + +## +## Logical functions Logische functies +## +AND = EN ## Geeft als resultaat WAAR als alle argumenten WAAR zijn +FALSE = ONWAAR ## Geeft als resultaat de logische waarde ONWAAR +IF = ALS ## Geeft een logische test aan +IFERROR = ALS.FOUT ## Retourneert een waarde die u opgeeft als een formule een fout oplevert, anders wordt het resultaat van de formule geretourneerd +NOT = NIET ## Keert de logische waarde van het argument om +OR = OF ## Geeft als resultaat WAAR als minimaal een van de argumenten WAAR is +TRUE = WAAR ## Geeft als resultaat de logische waarde WAAR + + +## +## Lookup and reference functions Zoek- en verwijzingsfuncties +## +ADDRESS = ADRES ## Geeft als resultaat een verwijzing, in de vorm van tekst, naar één bepaalde cel in een werkblad +AREAS = BEREIKEN ## Geeft als resultaat het aantal bereiken in een verwijzing +CHOOSE = KIEZEN ## Kiest een waarde uit een lijst met waarden +COLUMN = KOLOM ## Geeft als resultaat het kolomnummer van een verwijzing +COLUMNS = KOLOMMEN ## Geeft als resultaat het aantal kolommen in een verwijzing +HLOOKUP = HORIZ.ZOEKEN ## Zoekt in de bovenste rij van een matrix naar een bepaalde waarde en geeft als resultaat de gevonden waarde in de opgegeven cel +HYPERLINK = HYPERLINK ## Maakt een snelkoppeling of een sprong waarmee een document wordt geopend dat is opgeslagen op een netwerkserver, een intranet of op internet +INDEX = INDEX ## Kiest met een index een waarde uit een verwijzing of een matrix +INDIRECT = INDIRECT ## Geeft als resultaat een verwijzing die wordt aangegeven met een tekstwaarde +LOOKUP = ZOEKEN ## Zoekt naar bepaalde waarden in een vector of een matrix +MATCH = VERGELIJKEN ## Zoekt naar bepaalde waarden in een verwijzing of een matrix +OFFSET = VERSCHUIVING ## Geeft als resultaat een nieuwe verwijzing die is verschoven ten opzichte van een bepaalde verwijzing +ROW = RIJ ## Geeft als resultaat het rijnummer van een verwijzing +ROWS = RIJEN ## Geeft als resultaat het aantal rijen in een verwijzing +RTD = RTG ## Haalt realtimegegevens op uit een programma dat COM-automatisering (automatisering: een methode waarmee de ene toepassing objecten van een andere toepassing of ontwikkelprogramma kan besturen. Automatisering werd vroeger OLE-automatisering genoemd. Automatisering is een industrienorm die deel uitmaakt van het Component Object Model (COM).) ondersteunt +TRANSPOSE = TRANSPONEREN ## Geeft als resultaat de getransponeerde van een matrix +VLOOKUP = VERT.ZOEKEN ## Zoekt in de meest linkse kolom van een matrix naar een bepaalde waarde en geeft als resultaat de waarde in de opgegeven cel + + +## +## Math and trigonometry functions Wiskundige en trigonometrische functies +## +ABS = ABS ## Geeft als resultaat de absolute waarde van een getal +ACOS = BOOGCOS ## Geeft als resultaat de boogcosinus van een getal +ACOSH = BOOGCOSH ## Geeft als resultaat de inverse cosinus hyperbolicus van een getal +ASIN = BOOGSIN ## Geeft als resultaat de boogsinus van een getal +ASINH = BOOGSINH ## Geeft als resultaat de inverse sinus hyperbolicus van een getal +ATAN = BOOGTAN ## Geeft als resultaat de boogtangens van een getal +ATAN2 = BOOGTAN2 ## Geeft als resultaat de boogtangens van de x- en y-coördinaten +ATANH = BOOGTANH ## Geeft als resultaat de inverse tangens hyperbolicus van een getal +CEILING = AFRONDEN.BOVEN ## Rondt de absolute waarde van een getal naar boven af op het dichtstbijzijnde gehele getal of het dichtstbijzijnde significante veelvoud +COMBIN = COMBINATIES ## Geeft als resultaat het aantal combinaties voor een bepaald aantal objecten +COS = COS ## Geeft als resultaat de cosinus van een getal +COSH = COSH ## Geeft als resultaat de cosinus hyperbolicus van een getal +DEGREES = GRADEN ## Converteert radialen naar graden +EVEN = EVEN ## Rondt het getal af op het dichtstbijzijnde gehele even getal +EXP = EXP ## Verheft e tot de macht van een bepaald getal +FACT = FACULTEIT ## Geeft als resultaat de faculteit van een getal +FACTDOUBLE = DUBBELE.FACULTEIT ## Geeft als resultaat de dubbele faculteit van een getal +FLOOR = AFRONDEN.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af +GCD = GGD ## Geeft als resultaat de grootste gemene deler +INT = INTEGER ## Rondt een getal naar beneden af op het dichtstbijzijnde gehele getal +LCM = KGV ## Geeft als resultaat het kleinste gemene veelvoud +LN = LN ## Geeft als resultaat de natuurlijke logaritme van een getal +LOG = LOG ## Geeft als resultaat de logaritme met het opgegeven grondtal van een getal +LOG10 = LOG10 ## Geeft als resultaat de logaritme met grondtal 10 van een getal +MDETERM = DETERMINANTMAT ## Geeft als resultaat de determinant van een matrix +MINVERSE = INVERSEMAT ## Geeft als resultaat de inverse van een matrix +MMULT = PRODUCTMAT ## Geeft als resultaat het product van twee matrices +MOD = REST ## Geeft als resultaat het restgetal van een deling +MROUND = AFRONDEN.N.VEELVOUD ## Geeft als resultaat een getal afgerond op het gewenste veelvoud +MULTINOMIAL = MULTINOMIAAL ## Geeft als resultaat de multinomiaalcoëfficiënt van een reeks getallen +ODD = ONEVEN ## Rondt de absolute waarde van het getal naar boven af op het dichtstbijzijnde gehele oneven getal +PI = PI ## Geeft als resultaat de waarde van pi +POWER = MACHT ## Verheft een getal tot een macht +PRODUCT = PRODUCT ## Vermenigvuldigt de argumenten met elkaar +QUOTIENT = QUOTIENT ## Geeft als resultaat de uitkomst van een deling als geheel getal +RADIANS = RADIALEN ## Converteert graden naar radialen +RAND = ASELECT ## Geeft als resultaat een willekeurig getal tussen 0 en 1 +RANDBETWEEN = ASELECTTUSSEN ## Geeft een willekeurig getal tussen de getallen die u hebt opgegeven +ROMAN = ROMEINS ## Converteert een Arabisch getal naar een Romeins getal en geeft het resultaat weer in de vorm van tekst +ROUND = AFRONDEN ## Rondt een getal af op het opgegeven aantal decimalen +ROUNDDOWN = AFRONDEN.NAAR.BENEDEN ## Rondt de absolute waarde van een getal naar beneden af +ROUNDUP = AFRONDEN.NAAR.BOVEN ## Rondt de absolute waarde van een getal naar boven af +SERIESSUM = SOM.MACHTREEKS ## Geeft als resultaat de som van een machtreeks die is gebaseerd op de formule +SIGN = POS.NEG ## Geeft als resultaat het teken van een getal +SIN = SIN ## Geeft als resultaat de sinus van de opgegeven hoek +SINH = SINH ## Geeft als resultaat de sinus hyperbolicus van een getal +SQRT = WORTEL ## Geeft als resultaat de positieve vierkantswortel van een getal +SQRTPI = WORTEL.PI ## Geeft als resultaat de vierkantswortel van (getal * pi) +SUBTOTAL = SUBTOTAAL ## Geeft als resultaat een subtotaal voor een bereik +SUM = SOM ## Telt de argumenten op +SUMIF = SOM.ALS ## Telt de getallen bij elkaar op die voldoen aan een bepaald criterium +SUMIFS = SOMMEN.ALS ## Telt de cellen in een bereik op die aan meerdere criteria voldoen +SUMPRODUCT = SOMPRODUCT ## Geeft als resultaat de som van de producten van de corresponderende matrixelementen +SUMSQ = KWADRATENSOM ## Geeft als resultaat de som van de kwadraten van de argumenten +SUMX2MY2 = SOM.X2MINY2 ## Geeft als resultaat de som van het verschil tussen de kwadraten van corresponderende waarden in twee matrices +SUMX2PY2 = SOM.X2PLUSY2 ## Geeft als resultaat de som van de kwadratensom van corresponderende waarden in twee matrices +SUMXMY2 = SOM.XMINY.2 ## Geeft als resultaat de som van de kwadraten van de verschillen tussen de corresponderende waarden in twee matrices +TAN = TAN ## Geeft als resultaat de tangens van een getal +TANH = TANH ## Geeft als resultaat de tangens hyperbolicus van een getal +TRUNC = GEHEEL ## Kapt een getal af tot een geheel getal + + +## +## Statistical functions Statistische functies +## +AVEDEV = GEM.DEVIATIE ## Geeft als resultaat het gemiddelde van de absolute deviaties van gegevenspunten ten opzichte van hun gemiddelde waarde +AVERAGE = GEMIDDELDE ## Geeft als resultaat het gemiddelde van de argumenten +AVERAGEA = GEMIDDELDEA ## Geeft als resultaat het gemiddelde van de argumenten, inclusief getallen, tekst en logische waarden +AVERAGEIF = GEMIDDELDE.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen in een bereik die voldoen aan de opgegeven criteria +AVERAGEIFS = GEMIDDELDEN.ALS ## Geeft het gemiddelde (rekenkundig gemiddelde) als resultaat van alle cellen die aan meerdere criteria voldoen +BETADIST = BETA.VERD ## Geeft als resultaat de cumulatieve bèta-verdelingsfunctie +BETAINV = BETA.INV ## Geeft als resultaat de inverse van de cumulatieve verdelingsfunctie voor een gegeven bèta-verdeling +BINOMDIST = BINOMIALE.VERD ## Geeft als resultaat de binomiale verdeling +CHIDIST = CHI.KWADRAAT ## Geeft als resultaat de eenzijdige kans van de chi-kwadraatverdeling +CHIINV = CHI.KWADRAAT.INV ## Geeft als resultaat de inverse van een eenzijdige kans van de chi-kwadraatverdeling +CHITEST = CHI.TOETS ## Geeft als resultaat de onafhankelijkheidstoets +CONFIDENCE = BETROUWBAARHEID ## Geeft als resultaat het betrouwbaarheidsinterval van een gemiddelde waarde voor de elementen van een populatie +CORREL = CORRELATIE ## Geeft als resultaat de correlatiecoëfficiënt van twee gegevensverzamelingen +COUNT = AANTAL ## Telt het aantal getallen in de argumentenlijst +COUNTA = AANTALARG ## Telt het aantal waarden in de argumentenlijst +COUNTBLANK = AANTAL.LEGE.CELLEN ## Telt het aantal lege cellen in een bereik +COUNTIF = AANTAL.ALS ## Telt in een bereik het aantal cellen die voldoen aan een bepaald criterium +COUNTIFS = AANTALLEN.ALS ## Telt in een bereik het aantal cellen die voldoen aan meerdere criteria +COVAR = COVARIANTIE ## Geeft als resultaat de covariantie, het gemiddelde van de producten van de gepaarde deviaties +CRITBINOM = CRIT.BINOM ## Geeft als resultaat de kleinste waarde waarvoor de binomiale verdeling kleiner is dan of gelijk is aan het criterium +DEVSQ = DEV.KWAD ## Geeft als resultaat de som van de deviaties in het kwadraat +EXPONDIST = EXPON.VERD ## Geeft als resultaat de exponentiële verdeling +FDIST = F.VERDELING ## Geeft als resultaat de F-verdeling +FINV = F.INVERSE ## Geeft als resultaat de inverse van de F-verdeling +FISHER = FISHER ## Geeft als resultaat de Fisher-transformatie +FISHERINV = FISHER.INV ## Geeft als resultaat de inverse van de Fisher-transformatie +FORECAST = VOORSPELLEN ## Geeft als resultaat een waarde op basis van een lineaire trend +FREQUENCY = FREQUENTIE ## Geeft als resultaat een frequentieverdeling in de vorm van een verticale matrix +FTEST = F.TOETS ## Geeft als resultaat een F-toets +GAMMADIST = GAMMA.VERD ## Geeft als resultaat de gamma-verdeling +GAMMAINV = GAMMA.INV ## Geeft als resultaat de inverse van de cumulatieve gamma-verdeling +GAMMALN = GAMMA.LN ## Geeft als resultaat de natuurlijke logaritme van de gamma-functie, G(x) +GEOMEAN = MEETK.GEM ## Geeft als resultaat het meetkundige gemiddelde +GROWTH = GROEI ## Geeft als resultaat de waarden voor een exponentiële trend +HARMEAN = HARM.GEM ## Geeft als resultaat het harmonische gemiddelde +HYPGEOMDIST = HYPERGEO.VERD ## Geeft als resultaat de hypergeometrische verdeling +INTERCEPT = SNIJPUNT ## Geeft als resultaat het snijpunt van de lineaire regressielijn met de y-as +KURT = KURTOSIS ## Geeft als resultaat de kurtosis van een gegevensverzameling +LARGE = GROOTSTE ## Geeft als resultaat de op k-1 na grootste waarde in een gegevensverzameling +LINEST = LIJNSCH ## Geeft als resultaat de parameters van een lineaire trend +LOGEST = LOGSCH ## Geeft als resultaat de parameters van een exponentiële trend +LOGINV = LOG.NORM.INV ## Geeft als resultaat de inverse van de logaritmische normale verdeling +LOGNORMDIST = LOG.NORM.VERD ## Geeft als resultaat de cumulatieve logaritmische normale verdeling +MAX = MAX ## Geeft als resultaat de maximumwaarde in een lijst met argumenten +MAXA = MAXA ## Geeft als resultaat de maximumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden +MEDIAN = MEDIAAN ## Geeft als resultaat de mediaan van de opgegeven getallen +MIN = MIN ## Geeft als resultaat de minimumwaarde in een lijst met argumenten +MINA = MINA ## Geeft als resultaat de minimumwaarde in een lijst met argumenten, inclusief getallen, tekst en logische waarden +MODE = MODUS ## Geeft als resultaat de meest voorkomende waarde in een gegevensverzameling +NEGBINOMDIST = NEG.BINOM.VERD ## Geeft als resultaat de negatieve binomiaalverdeling +NORMDIST = NORM.VERD ## Geeft als resultaat de cumulatieve normale verdeling +NORMINV = NORM.INV ## Geeft als resultaat de inverse van de cumulatieve standaardnormale verdeling +NORMSDIST = STAND.NORM.VERD ## Geeft als resultaat de cumulatieve standaardnormale verdeling +NORMSINV = STAND.NORM.INV ## Geeft als resultaat de inverse van de cumulatieve normale verdeling +PEARSON = PEARSON ## Geeft als resultaat de correlatiecoëfficiënt van Pearson +PERCENTILE = PERCENTIEL ## Geeft als resultaat het k-de percentiel van waarden in een bereik +PERCENTRANK = PERCENT.RANG ## Geeft als resultaat de positie, in procenten uitgedrukt, van een waarde in de rangorde van een gegevensverzameling +PERMUT = PERMUTATIES ## Geeft als resultaat het aantal permutaties voor een gegeven aantal objecten +POISSON = POISSON ## Geeft als resultaat de Poisson-verdeling +PROB = KANS ## Geeft als resultaat de kans dat waarden zich tussen twee grenzen bevinden +QUARTILE = KWARTIEL ## Geeft als resultaat het kwartiel van een gegevensverzameling +RANK = RANG ## Geeft als resultaat het rangnummer van een getal in een lijst getallen +RSQ = R.KWADRAAT ## Geeft als resultaat het kwadraat van de Pearson-correlatiecoëfficiënt +SKEW = SCHEEFHEID ## Geeft als resultaat de mate van asymmetrie van een verdeling +SLOPE = RICHTING ## Geeft als resultaat de richtingscoëfficiënt van een lineaire regressielijn +SMALL = KLEINSTE ## Geeft als resultaat de op k-1 na kleinste waarde in een gegevensverzameling +STANDARDIZE = NORMALISEREN ## Geeft als resultaat een genormaliseerde waarde +STDEV = STDEV ## Maakt een schatting van de standaarddeviatie op basis van een steekproef +STDEVA = STDEVA ## Maakt een schatting van de standaarddeviatie op basis van een steekproef, inclusief getallen, tekst en logische waarden +STDEVP = STDEVP ## Berekent de standaarddeviatie op basis van de volledige populatie +STDEVPA = STDEVPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden +STEYX = STAND.FOUT.YX ## Geeft als resultaat de standaardfout in de voorspelde y-waarde voor elke x in een regressie +TDIST = T.VERD ## Geeft als resultaat de Student T-verdeling +TINV = T.INV ## Geeft als resultaat de inverse van de Student T-verdeling +TREND = TREND ## Geeft als resultaat de waarden voor een lineaire trend +TRIMMEAN = GETRIMD.GEM ## Geeft als resultaat het gemiddelde van waarden in een gegevensverzameling +TTEST = T.TOETS ## Geeft als resultaat de kans met behulp van de Student T-toets +VAR = VAR ## Maakt een schatting van de variantie op basis van een steekproef +VARA = VARA ## Maakt een schatting van de variantie op basis van een steekproef, inclusief getallen, tekst en logische waarden +VARP = VARP ## Berekent de variantie op basis van de volledige populatie +VARPA = VARPA ## Berekent de standaarddeviatie op basis van de volledige populatie, inclusief getallen, tekst en logische waarden +WEIBULL = WEIBULL ## Geeft als resultaat de Weibull-verdeling +ZTEST = Z.TOETS ## Geeft als resultaat de eenzijdige kanswaarde van een Z-toets + + +## +## Text functions Tekstfuncties +## +ASC = ASC ## Wijzigt Nederlandse letters of katakanatekens over de volle breedte (dubbel-bytetekens) binnen een tekenreeks in tekens over de halve breedte (enkel-bytetekens) +BAHTTEXT = BAHT.TEKST ## Converteert een getal naar tekst met de valutanotatie ß (baht) +CHAR = TEKEN ## Geeft als resultaat het teken dat hoort bij de opgegeven code +CLEAN = WISSEN.CONTROL ## Verwijdert alle niet-afdrukbare tekens uit een tekst +CODE = CODE ## Geeft als resultaat de numerieke code voor het eerste teken in een tekenreeks +CONCATENATE = TEKST.SAMENVOEGEN ## Voegt verschillende tekstfragmenten samen tot één tekstfragment +DOLLAR = EURO ## Converteert een getal naar tekst met de valutanotatie € (euro) +EXACT = GELIJK ## Controleert of twee tekenreeksen identiek zijn +FIND = VIND.ALLES ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +FINDB = VIND.ALLES.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +FIXED = VAST ## Maakt een getal als tekst met een vast aantal decimalen op +JIS = JIS ## Wijzigt Nederlandse letters of katakanatekens over de halve breedte (enkel-bytetekens) binnen een tekenreeks in tekens over de volle breedte (dubbel-bytetekens) +LEFT = LINKS ## Geeft als resultaat de meest linkse tekens in een tekenreeks +LEFTB = LINKSB ## Geeft als resultaat de meest linkse tekens in een tekenreeks +LEN = LENGTE ## Geeft als resultaat het aantal tekens in een tekenreeks +LENB = LENGTEB ## Geeft als resultaat het aantal tekens in een tekenreeks +LOWER = KLEINE.LETTERS ## Zet tekst om in kleine letters +MID = MIDDEN ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft +MIDB = DEELB ## Geeft als resultaat een bepaald aantal tekens van een tekenreeks vanaf de positie die u opgeeft +PHONETIC = FONETISCH ## Haalt de fonetische tekens (furigana) uit een tekenreeks op +PROPER = BEGINLETTERS ## Zet de eerste letter van elk woord in een tekst om in een hoofdletter +REPLACE = VERVANG ## Vervangt tekens binnen een tekst +REPLACEB = VERVANGENB ## Vervangt tekens binnen een tekst +REPT = HERHALING ## Herhaalt een tekst een aantal malen +RIGHT = RECHTS ## Geeft als resultaat de meest rechtse tekens in een tekenreeks +RIGHTB = RECHTSB ## Geeft als resultaat de meest rechtse tekens in een tekenreeks +SEARCH = VIND.SPEC ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +SEARCHB = VIND.SPEC.B ## Zoekt een bepaalde tekenreeks in een tekst (waarbij geen onderscheid wordt gemaakt tussen hoofdletters en kleine letters) +SUBSTITUTE = SUBSTITUEREN ## Vervangt oude tekst door nieuwe tekst in een tekenreeks +T = T ## Converteert de argumenten naar tekst +TEXT = TEKST ## Maakt een getal op en converteert het getal naar tekst +TRIM = SPATIES.WISSEN ## Verwijdert de spaties uit een tekst +UPPER = HOOFDLETTERS ## Zet tekst om in hoofdletters +VALUE = WAARDE ## Converteert tekst naar een getal diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/config new file mode 100644 index 00000000..bf2d34a7 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + +## +## Excel Error Codes (For future use) +## +NULL = #NULL! +DIV0 = #DIV/0! +VALUE = #VERDI! +REF = #REF! +NAME = #NAVN? +NUM = #NUM! +NA = #I/T diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/functions new file mode 100644 index 00000000..10d0a207 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/no/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funksjonene Tillegg og Automatisering +## +GETPIVOTDATA = HENTPIVOTDATA ## Returnerer data som er lagret i en pivottabellrapport + + +## +## Cube functions Kubefunksjoner +## +CUBEKPIMEMBER = KUBEKPIMEDLEM ## Returnerer navnet, egenskapen og målet for en viktig ytelsesindikator (KPI), og viser navnet og egenskapen i cellen. En KPI er en målbar enhet, for eksempel månedlig bruttoinntjening eller kvartalsvis inntjening per ansatt, og brukes til å overvåke ytelsen i en organisasjon. +CUBEMEMBER = KUBEMEDLEM ## Returnerer et medlem eller en tuppel i et kubehierarki. Brukes til å validere at medlemmet eller tuppelen finnes i kuben. +CUBEMEMBERPROPERTY = KUBEMEDLEMEGENSKAP ## Returnerer verdien til en medlemsegenskap i kuben. Brukes til å validere at et medlemsnavn finnes i kuben, og til å returnere den angitte egenskapen for dette medlemmet. +CUBERANKEDMEMBER = KUBERANGERTMEDLEM ## Returnerer det n-te, eller rangerte, medlemmet i et sett. Brukes til å returnere ett eller flere elementer i et sett, for eksempel de 10 beste studentene. +CUBESET = KUBESETT ## Definerer et beregnet sett av medlemmer eller tuppeler ved å sende et settuttrykk til kuben på serveren, noe som oppretter settet og deretter returnerer dette settet til Microsoft Office Excel. +CUBESETCOUNT = KUBESETTANTALL ## Returnerer antallet elementer i et sett. +CUBEVALUE = KUBEVERDI ## Returnerer en aggregert verdi fra en kube. + + +## +## Database functions Databasefunksjoner +## +DAVERAGE = DGJENNOMSNITT ## Returnerer gjennomsnittet av merkede databaseposter +DCOUNT = DANTALL ## Teller celler som inneholder tall i en database +DCOUNTA = DANTALLA ## Teller celler som ikke er tomme i en database +DGET = DHENT ## Trekker ut fra en database en post som oppfyller angitte vilkår +DMAX = DMAKS ## Returnerer maksimumsverdien fra merkede databaseposter +DMIN = DMIN ## Returnerer minimumsverdien fra merkede databaseposter +DPRODUCT = DPRODUKT ## Multipliserer verdiene i et bestemt felt med poster som oppfyller vilkårene i en database +DSTDEV = DSTDAV ## Estimerer standardavviket basert på et utvalg av merkede databaseposter +DSTDEVP = DSTAVP ## Beregner standardavviket basert på at merkede databaseposter utgjør hele populasjonen +DSUM = DSUMMER ## Legger til tallene i feltkolonnen med poster, i databasen som oppfyller vilkårene +DVAR = DVARIANS ## Estimerer variansen basert på et utvalg av merkede databaseposter +DVARP = DVARIANSP ## Beregner variansen basert på at merkede databaseposter utgjør hele populasjonen + + +## +## Date and time functions Dato- og tidsfunksjoner +## +DATE = DATO ## Returnerer serienummeret som svarer til en bestemt dato +DATEVALUE = DATOVERDI ## Konverterer en dato med tekstformat til et serienummer +DAY = DAG ## Konverterer et serienummer til en dag i måneden +DAYS360 = DAGER360 ## Beregner antall dager mellom to datoer basert på et år med 360 dager +EDATE = DAG.ETTER ## Returnerer serienummeret som svarer til datoen som er det indikerte antall måneder før eller etter startdatoen +EOMONTH = MÅNEDSSLUTT ## Returnerer serienummeret som svarer til siste dag i måneden, før eller etter et angitt antall måneder +HOUR = TIME ## Konverterer et serienummer til en time +MINUTE = MINUTT ## Konverterer et serienummer til et minutt +MONTH = MÅNED ## Konverterer et serienummer til en måned +NETWORKDAYS = NETT.ARBEIDSDAGER ## Returnerer antall hele arbeidsdager mellom to datoer +NOW = NÅ ## Returnerer serienummeret som svarer til gjeldende dato og klokkeslett +SECOND = SEKUND ## Konverterer et serienummer til et sekund +TIME = TID ## Returnerer serienummeret som svarer til et bestemt klokkeslett +TIMEVALUE = TIDSVERDI ## Konverterer et klokkeslett i tekstformat til et serienummer +TODAY = IDAG ## Returnerer serienummeret som svarer til dagens dato +WEEKDAY = UKEDAG ## Konverterer et serienummer til en ukedag +WEEKNUM = UKENR ## Konverterer et serienummer til et tall som representerer hvilket nummer uken har i et år +WORKDAY = ARBEIDSDAG ## Returnerer serienummeret som svarer til datoen før eller etter et angitt antall arbeidsdager +YEAR = ÅR ## Konverterer et serienummer til et år +YEARFRAC = ÅRDEL ## Returnerer brøkdelen for året, som svarer til antall hele dager mellom startdato og sluttdato + + +## +## Engineering functions Tekniske funksjoner +## +BESSELI = BESSELI ## Returnerer den endrede Bessel-funksjonen In(x) +BESSELJ = BESSELJ ## Returnerer Bessel-funksjonen Jn(x) +BESSELK = BESSELK ## Returnerer den endrede Bessel-funksjonen Kn(x) +BESSELY = BESSELY ## Returnerer Bessel-funksjonen Yn(x) +BIN2DEC = BINTILDES ## Konverterer et binært tall til et desimaltall +BIN2HEX = BINTILHEKS ## Konverterer et binært tall til et heksadesimaltall +BIN2OCT = BINTILOKT ## Konverterer et binært tall til et oktaltall +COMPLEX = KOMPLEKS ## Konverterer reelle og imaginære koeffisienter til et komplekst tall +CONVERT = KONVERTER ## Konverterer et tall fra ett målsystem til et annet +DEC2BIN = DESTILBIN ## Konverterer et desimaltall til et binærtall +DEC2HEX = DESTILHEKS ## Konverterer et heltall i 10-tallsystemet til et heksadesimalt tall +DEC2OCT = DESTILOKT ## Konverterer et heltall i 10-tallsystemet til et oktaltall +DELTA = DELTA ## Undersøker om to verdier er like +ERF = FEILF ## Returnerer feilfunksjonen +ERFC = FEILFK ## Returnerer den komplementære feilfunksjonen +GESTEP = GRENSEVERDI ## Tester om et tall er større enn en terskelverdi +HEX2BIN = HEKSTILBIN ## Konverterer et heksadesimaltall til et binært tall +HEX2DEC = HEKSTILDES ## Konverterer et heksadesimalt tall til et heltall i 10-tallsystemet +HEX2OCT = HEKSTILOKT ## Konverterer et heksadesimalt tall til et oktaltall +IMABS = IMABS ## Returnerer absoluttverdien (koeffisienten) til et komplekst tall +IMAGINARY = IMAGINÆR ## Returnerer den imaginære koeffisienten til et komplekst tall +IMARGUMENT = IMARGUMENT ## Returnerer argumentet theta, som er en vinkel uttrykt i radianer +IMCONJUGATE = IMKONJUGERT ## Returnerer den komplekse konjugaten til et komplekst tall +IMCOS = IMCOS ## Returnerer cosinus til et komplekst tall +IMDIV = IMDIV ## Returnerer kvotienten til to komplekse tall +IMEXP = IMEKSP ## Returnerer eksponenten til et komplekst tall +IMLN = IMLN ## Returnerer den naturlige logaritmen for et komplekst tall +IMLOG10 = IMLOG10 ## Returnerer logaritmen med grunntall 10 for et komplekst tall +IMLOG2 = IMLOG2 ## Returnerer logaritmen med grunntall 2 for et komplekst tall +IMPOWER = IMOPPHØY ## Returnerer et komplekst tall opphøyd til en heltallspotens +IMPRODUCT = IMPRODUKT ## Returnerer produktet av komplekse tall +IMREAL = IMREELL ## Returnerer den reelle koeffisienten til et komplekst tall +IMSIN = IMSIN ## Returnerer sinus til et komplekst tall +IMSQRT = IMROT ## Returnerer kvadratroten av et komplekst tall +IMSUB = IMSUB ## Returnerer differansen mellom to komplekse tall +IMSUM = IMSUMMER ## Returnerer summen av komplekse tall +OCT2BIN = OKTTILBIN ## Konverterer et oktaltall til et binært tall +OCT2DEC = OKTTILDES ## Konverterer et oktaltall til et desimaltall +OCT2HEX = OKTTILHEKS ## Konverterer et oktaltall til et heksadesimaltall + + +## +## Financial functions Økonomiske funksjoner +## +ACCRINT = PÅLØPT.PERIODISK.RENTE ## Returnerer påløpte renter for et verdipapir som betaler periodisk rente +ACCRINTM = PÅLØPT.FORFALLSRENTE ## Returnerer den påløpte renten for et verdipapir som betaler rente ved forfall +AMORDEGRC = AMORDEGRC ## Returnerer avskrivningen for hver regnskapsperiode ved hjelp av en avskrivingskoeffisient +AMORLINC = AMORLINC ## Returnerer avskrivingen for hver regnskapsperiode +COUPDAYBS = OBLIG.DAGER.FF ## Returnerer antall dager fra begynnelsen av den rentebærende perioden til innløsningsdatoen +COUPDAYS = OBLIG.DAGER ## Returnerer antall dager i den rentebærende perioden som inneholder innløsningsdatoen +COUPDAYSNC = OBLIG.DAGER.NF ## Returnerer antall dager fra betalingsdato til neste renteinnbetalingsdato +COUPNCD = OBLIG.DAGER.EF ## Returnerer obligasjonsdatoen som kommer etter oppgjørsdatoen +COUPNUM = OBLIG.ANTALL ## Returnerer antall obligasjoner som skal betales mellom oppgjørsdatoen og forfallsdatoen +COUPPCD = OBLIG.DAG.FORRIGE ## Returnerer obligasjonsdatoen som kommer før oppgjørsdatoen +CUMIPMT = SAMLET.RENTE ## Returnerer den kumulative renten som er betalt mellom to perioder +CUMPRINC = SAMLET.HOVEDSTOL ## Returnerer den kumulative hovedstolen som er betalt for et lån mellom to perioder +DB = DAVSKR ## Returnerer avskrivningen for et aktivum i en angitt periode, foretatt med fast degressiv avskrivning +DDB = DEGRAVS ## Returnerer avskrivningen for et aktivum for en gitt periode, ved hjelp av dobbel degressiv avskrivning eller en metode som du selv angir +DISC = DISKONTERT ## Returnerer diskonteringsraten for et verdipapir +DOLLARDE = DOLLARDE ## Konverterer en valutapris uttrykt som en brøk, til en valutapris uttrykt som et desimaltall +DOLLARFR = DOLLARBR ## Konverterer en valutapris uttrykt som et desimaltall, til en valutapris uttrykt som en brøk +DURATION = VARIGHET ## Returnerer årlig varighet for et verdipapir med renter som betales periodisk +EFFECT = EFFEKTIV.RENTE ## Returnerer den effektive årlige rentesatsen +FV = SLUTTVERDI ## Returnerer fremtidig verdi for en investering +FVSCHEDULE = SVPLAN ## Returnerer den fremtidige verdien av en inngående hovedstol etter å ha anvendt en serie med sammensatte rentesatser +INTRATE = RENTESATS ## Returnerer rentefoten av et fullfinansiert verdipapir +IPMT = RAVDRAG ## Returnerer betalte renter på en investering for en gitt periode +IRR = IR ## Returnerer internrenten for en serie kontantstrømmer +ISPMT = ER.AVDRAG ## Beregner renten som er betalt for en investering i løpet av en bestemt periode +MDURATION = MVARIGHET ## Returnerer Macauleys modifiserte varighet for et verdipapir med en antatt pålydende verdi på kr 100,00 +MIRR = MODIR ## Returnerer internrenten der positive og negative kontantstrømmer finansieres med forskjellige satser +NOMINAL = NOMINELL ## Returnerer årlig nominell rentesats +NPER = PERIODER ## Returnerer antall perioder for en investering +NPV = NNV ## Returnerer netto nåverdi for en investering, basert på en serie periodiske kontantstrømmer og en rentesats +ODDFPRICE = AVVIKFP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde første periode +ODDFYIELD = AVVIKFP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde første periode +ODDLPRICE = AVVIKSP.PRIS ## Returnerer pris pålydende kr 100 for et verdipapir med en odde siste periode +ODDLYIELD = AVVIKSP.AVKASTNING ## Returnerer avkastingen for et verdipapir med en odde siste periode +PMT = AVDRAG ## Returnerer periodisk betaling for en annuitet +PPMT = AMORT ## Returnerer betalingen på hovedstolen for en investering i en gitt periode +PRICE = PRIS ## Returnerer prisen per pålydende kr 100 for et verdipapir som gir periodisk avkastning +PRICEDISC = PRIS.DISKONTERT ## Returnerer prisen per pålydende kr 100 for et diskontert verdipapir +PRICEMAT = PRIS.FORFALL ## Returnerer prisen per pålydende kr 100 av et verdipapir som betaler rente ved forfall +PV = NÅVERDI ## Returnerer nåverdien av en investering +RATE = RENTE ## Returnerer rentesatsen per periode for en annuitet +RECEIVED = MOTTATT.AVKAST ## Returnerer summen som mottas ved forfallsdato for et fullinvestert verdipapir +SLN = LINAVS ## Returnerer den lineære avskrivningen for et aktivum i én periode +SYD = ÅRSAVS ## Returnerer årsavskrivningen for et aktivum i en angitt periode +TBILLEQ = TBILLEKV ## Returnerer den obligasjonsekvivalente avkastningen for en statsobligasjon +TBILLPRICE = TBILLPRIS ## Returnerer prisen per pålydende kr 100 for en statsobligasjon +TBILLYIELD = TBILLAVKASTNING ## Returnerer avkastningen til en statsobligasjon +VDB = VERDIAVS ## Returnerer avskrivningen for et aktivum i en angitt periode eller delperiode, ved hjelp av degressiv avskrivning +XIRR = XIR ## Returnerer internrenten for en serie kontantstrømmer som ikke nødvendigvis er periodiske +XNPV = XNNV ## Returnerer netto nåverdi for en serie kontantstrømmer som ikke nødvendigvis er periodiske +YIELD = AVKAST ## Returnerer avkastningen på et verdipapir som betaler periodisk rente +YIELDDISC = AVKAST.DISKONTERT ## Returnerer årlig avkastning for et diskontert verdipapir, for eksempel en statskasseveksel +YIELDMAT = AVKAST.FORFALL ## Returnerer den årlige avkastningen for et verdipapir som betaler rente ved forfallsdato + + +## +## Information functions Informasjonsfunksjoner +## +CELL = CELLE ## Returnerer informasjon om formatering, plassering eller innholdet til en celle +ERROR.TYPE = FEIL.TYPE ## Returnerer et tall som svarer til en feiltype +INFO = INFO ## Returnerer informasjon om gjeldende operativmiljø +ISBLANK = ERTOM ## Returnerer SANN hvis verdien er tom +ISERR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst annen feilverdi enn #I/T +ISERROR = ERFEIL ## Returnerer SANN hvis verdien er en hvilken som helst feilverdi +ISEVEN = ERPARTALL ## Returnerer SANN hvis tallet er et partall +ISLOGICAL = ERLOGISK ## Returnerer SANN hvis verdien er en logisk verdi +ISNA = ERIT ## Returnerer SANN hvis verdien er feilverdien #I/T +ISNONTEXT = ERIKKETEKST ## Returnerer SANN hvis verdien ikke er tekst +ISNUMBER = ERTALL ## Returnerer SANN hvis verdien er et tall +ISODD = ERODDETALL ## Returnerer SANN hvis tallet er et oddetall +ISREF = ERREF ## Returnerer SANN hvis verdien er en referanse +ISTEXT = ERTEKST ## Returnerer SANN hvis verdien er tekst +N = N ## Returnerer en verdi som er konvertert til et tall +NA = IT ## Returnerer feilverdien #I/T +TYPE = VERDITYPE ## Returnerer et tall som indikerer datatypen til en verdi + + +## +## Logical functions Logiske funksjoner +## +AND = OG ## Returnerer SANN hvis alle argumentene er lik SANN +FALSE = USANN ## Returnerer den logiske verdien USANN +IF = HVIS ## Angir en logisk test som skal utføres +IFERROR = HVISFEIL ## Returnerer en verdi du angir hvis en formel evaluerer til en feil. Ellers returnerer den resultatet av formelen. +NOT = IKKE ## Reverserer logikken til argumentet +OR = ELLER ## Returnerer SANN hvis ett eller flere argumenter er lik SANN +TRUE = SANN ## Returnerer den logiske verdien SANN + + +## +## Lookup and reference functions Oppslag- og referansefunksjoner +## +ADDRESS = ADRESSE ## Returnerer en referanse som tekst til en enkelt celle i et regneark +AREAS = OMRÅDER ## Returnerer antall områder i en referanse +CHOOSE = VELG ## Velger en verdi fra en liste med verdier +COLUMN = KOLONNE ## Returnerer kolonnenummeret for en referanse +COLUMNS = KOLONNER ## Returnerer antall kolonner i en referanse +HLOOKUP = FINN.KOLONNE ## Leter i den øverste raden i en matrise og returnerer verdien for den angitte cellen +HYPERLINK = HYPERKOBLING ## Oppretter en snarvei eller et hopp som åpner et dokument som er lagret på en nettverksserver, et intranett eller Internett +INDEX = INDEKS ## Bruker en indeks til å velge en verdi fra en referanse eller matrise +INDIRECT = INDIREKTE ## Returnerer en referanse angitt av en tekstverdi +LOOKUP = SLÅ.OPP ## Slår opp verdier i en vektor eller matrise +MATCH = SAMMENLIGNE ## Slår opp verdier i en referanse eller matrise +OFFSET = FORSKYVNING ## Returnerer en referanseforskyvning fra en gitt referanse +ROW = RAD ## Returnerer radnummeret for en referanse +ROWS = RADER ## Returnerer antall rader i en referanse +RTD = RTD ## Henter sanntidsdata fra et program som støtter COM-automatisering (automatisering: En måte å arbeide på med programobjekter fra et annet program- eller utviklingsverktøy. Tidligere kalt OLE-automatisering. Automatisering er en bransjestandard og en funksjon i Component Object Model (COM).) +TRANSPOSE = TRANSPONER ## Returnerer transponeringen av en matrise +VLOOKUP = FINN.RAD ## Leter i den første kolonnen i en matrise og flytter bortover raden for å returnere verdien til en celle + + +## +## Math and trigonometry functions Matematikk- og trigonometrifunksjoner +## +ABS = ABS ## Returnerer absoluttverdien til et tall +ACOS = ARCCOS ## Returnerer arcus cosinus til et tall +ACOSH = ARCCOSH ## Returnerer den inverse hyperbolske cosinus til et tall +ASIN = ARCSIN ## Returnerer arcus sinus til et tall +ASINH = ARCSINH ## Returnerer den inverse hyperbolske sinus til et tall +ATAN = ARCTAN ## Returnerer arcus tangens til et tall +ATAN2 = ARCTAN2 ## Returnerer arcus tangens fra x- og y-koordinater +ATANH = ARCTANH ## Returnerer den inverse hyperbolske tangens til et tall +CEILING = AVRUND.GJELDENDE.MULTIPLUM ## Runder av et tall til nærmeste heltall eller til nærmeste signifikante multiplum +COMBIN = KOMBINASJON ## Returnerer antall kombinasjoner for ett gitt antall objekter +COS = COS ## Returnerer cosinus til et tall +COSH = COSH ## Returnerer den hyperbolske cosinus til et tall +DEGREES = GRADER ## Konverterer radianer til grader +EVEN = AVRUND.TIL.PARTALL ## Runder av et tall oppover til nærmeste heltall som er et partall +EXP = EKSP ## Returnerer e opphøyd i en angitt potens +FACT = FAKULTET ## Returnerer fakultet til et tall +FACTDOUBLE = DOBBELFAKT ## Returnerer et talls doble fakultet +FLOOR = AVRUND.GJELDENDE.MULTIPLUM.NED ## Avrunder et tall nedover, mot null +GCD = SFF ## Returnerer høyeste felles divisor +INT = HELTALL ## Avrunder et tall nedover til nærmeste heltall +LCM = MFM ## Returnerer minste felles multiplum +LN = LN ## Returnerer den naturlige logaritmen til et tall +LOG = LOG ## Returnerer logaritmen for et tall til et angitt grunntall +LOG10 = LOG10 ## Returnerer logaritmen med grunntall 10 for et tall +MDETERM = MDETERM ## Returnerer matrisedeterminanten til en matrise +MINVERSE = MINVERS ## Returnerer den inverse matrisen til en matrise +MMULT = MMULT ## Returnerer matriseproduktet av to matriser +MOD = REST ## Returnerer resten fra en divisjon +MROUND = MRUND ## Returnerer et tall avrundet til det ønskede multiplum +MULTINOMIAL = MULTINOMINELL ## Returnerer det multinominelle for et sett med tall +ODD = AVRUND.TIL.ODDETALL ## Runder av et tall oppover til nærmeste heltall som er et oddetall +PI = PI ## Returnerer verdien av pi +POWER = OPPHØYD.I ## Returnerer resultatet av et tall opphøyd i en potens +PRODUCT = PRODUKT ## Multipliserer argumentene +QUOTIENT = KVOTIENT ## Returnerer heltallsdelen av en divisjon +RADIANS = RADIANER ## Konverterer grader til radianer +RAND = TILFELDIG ## Returnerer et tilfeldig tall mellom 0 og 1 +RANDBETWEEN = TILFELDIGMELLOM ## Returnerer et tilfeldig tall innenfor et angitt område +ROMAN = ROMERTALL ## Konverterer vanlige tall til romertall, som tekst +ROUND = AVRUND ## Avrunder et tall til et angitt antall sifre +ROUNDDOWN = AVRUND.NED ## Avrunder et tall nedover, mot null +ROUNDUP = AVRUND.OPP ## Runder av et tall oppover, bort fra null +SERIESSUM = SUMMER.REKKE ## Returnerer summen av en geometrisk rekke, basert på formelen +SIGN = FORTEGN ## Returnerer fortegnet for et tall +SIN = SIN ## Returnerer sinus til en gitt vinkel +SINH = SINH ## Returnerer den hyperbolske sinus til et tall +SQRT = ROT ## Returnerer en positiv kvadratrot +SQRTPI = ROTPI ## Returnerer kvadratroten av (tall * pi) +SUBTOTAL = DELSUM ## Returnerer en delsum i en liste eller database +SUM = SUMMER ## Legger sammen argumentene +SUMIF = SUMMERHVIS ## Legger sammen cellene angitt ved et gitt vilkår +SUMIFS = SUMMER.HVIS.SETT ## Legger sammen cellene i et område som oppfyller flere vilkår +SUMPRODUCT = SUMMERPRODUKT ## Returnerer summen av produktene av tilsvarende matrisekomponenter +SUMSQ = SUMMERKVADRAT ## Returnerer kvadratsummen av argumentene +SUMX2MY2 = SUMMERX2MY2 ## Returnerer summen av differansen av kvadratene for tilsvarende verdier i to matriser +SUMX2PY2 = SUMMERX2PY2 ## Returnerer summen av kvadratsummene for tilsvarende verdier i to matriser +SUMXMY2 = SUMMERXMY2 ## Returnerer summen av kvadratene av differansen for tilsvarende verdier i to matriser +TAN = TAN ## Returnerer tangens for et tall +TANH = TANH ## Returnerer den hyperbolske tangens for et tall +TRUNC = AVKORT ## Korter av et tall til et heltall + + +## +## Statistical functions Statistiske funksjoner +## +AVEDEV = GJENNOMSNITTSAVVIK ## Returnerer datapunktenes gjennomsnittlige absoluttavvik fra middelverdien +AVERAGE = GJENNOMSNITT ## Returnerer gjennomsnittet for argumentene +AVERAGEA = GJENNOMSNITTA ## Returnerer gjennomsnittet for argumentene, inkludert tall, tekst og logiske verdier +AVERAGEIF = GJENNOMSNITTHVIS ## Returnerer gjennomsnittet (aritmetisk gjennomsnitt) av alle cellene i et område som oppfyller et bestemt vilkår +AVERAGEIFS = GJENNOMSNITT.HVIS.SETT ## Returnerer gjennomsnittet (aritmetisk middelverdi) av alle celler som oppfyller flere vilkår. +BETADIST = BETA.FORDELING ## Returnerer den kumulative betafordelingsfunksjonen +BETAINV = INVERS.BETA.FORDELING ## Returnerer den inverse verdien til fordelingsfunksjonen for en angitt betafordeling +BINOMDIST = BINOM.FORDELING ## Returnerer den individuelle binomiske sannsynlighetsfordelingen +CHIDIST = KJI.FORDELING ## Returnerer den ensidige sannsynligheten for en kjikvadrert fordeling +CHIINV = INVERS.KJI.FORDELING ## Returnerer den inverse av den ensidige sannsynligheten for den kjikvadrerte fordelingen +CHITEST = KJI.TEST ## Utfører testen for uavhengighet +CONFIDENCE = KONFIDENS ## Returnerer konfidensintervallet til gjennomsnittet for en populasjon +CORREL = KORRELASJON ## Returnerer korrelasjonskoeffisienten mellom to datasett +COUNT = ANTALL ## Teller hvor mange tall som er i argumentlisten +COUNTA = ANTALLA ## Teller hvor mange verdier som er i argumentlisten +COUNTBLANK = TELLBLANKE ## Teller antall tomme celler i et område. +COUNTIF = ANTALL.HVIS ## Teller antall celler i et område som oppfyller gitte vilkår +COUNTIFS = ANTALL.HVIS.SETT ## Teller antallet ikke-tomme celler i et område som oppfyller flere vilkår +COVAR = KOVARIANS ## Returnerer kovariansen, gjennomsnittet av produktene av parvise avvik +CRITBINOM = GRENSE.BINOM ## Returnerer den minste verdien der den kumulative binomiske fordelingen er mindre enn eller lik en vilkårsverdi +DEVSQ = AVVIK.KVADRERT ## Returnerer summen av kvadrerte avvik +EXPONDIST = EKSP.FORDELING ## Returnerer eksponentialfordelingen +FDIST = FFORDELING ## Returnerer F-sannsynlighetsfordelingen +FINV = FFORDELING.INVERS ## Returnerer den inverse av den sannsynlige F-fordelingen +FISHER = FISHER ## Returnerer Fisher-transformasjonen +FISHERINV = FISHERINV ## Returnerer den inverse av Fisher-transformasjonen +FORECAST = PROGNOSE ## Returnerer en verdi langs en lineær trend +FREQUENCY = FREKVENS ## Returnerer en frekvensdistribusjon som en loddrett matrise +FTEST = FTEST ## Returnerer resultatet av en F-test +GAMMADIST = GAMMAFORDELING ## Returnerer gammafordelingen +GAMMAINV = GAMMAINV ## Returnerer den inverse av den gammakumulative fordelingen +GAMMALN = GAMMALN ## Returnerer den naturlige logaritmen til gammafunksjonen G(x) +GEOMEAN = GJENNOMSNITT.GEOMETRISK ## Returnerer den geometriske middelverdien +GROWTH = VEKST ## Returnerer verdier langs en eksponentiell trend +HARMEAN = GJENNOMSNITT.HARMONISK ## Returnerer den harmoniske middelverdien +HYPGEOMDIST = HYPGEOM.FORDELING ## Returnerer den hypergeometriske fordelingen +INTERCEPT = SKJÆRINGSPUNKT ## Returnerer skjæringspunktet til den lineære regresjonslinjen +KURT = KURT ## Returnerer kurtosen til et datasett +LARGE = N.STØRST ## Returnerer den n-te største verdien i et datasett +LINEST = RETTLINJE ## Returnerer parameterne til en lineær trend +LOGEST = KURVE ## Returnerer parameterne til en eksponentiell trend +LOGINV = LOGINV ## Returnerer den inverse lognormale fordelingen +LOGNORMDIST = LOGNORMFORD ## Returnerer den kumulative lognormale fordelingen +MAX = STØRST ## Returnerer maksimumsverdien i en argumentliste +MAXA = MAKSA ## Returnerer maksimumsverdien i en argumentliste, inkludert tall, tekst og logiske verdier +MEDIAN = MEDIAN ## Returnerer medianen til tallene som er gitt +MIN = MIN ## Returnerer minimumsverdien i en argumentliste +MINA = MINA ## Returnerer den minste verdien i en argumentliste, inkludert tall, tekst og logiske verdier +MODE = MODUS ## Returnerer den vanligste verdien i et datasett +NEGBINOMDIST = NEGBINOM.FORDELING ## Returnerer den negative binomiske fordelingen +NORMDIST = NORMALFORDELING ## Returnerer den kumulative normalfordelingen +NORMINV = NORMINV ## Returnerer den inverse kumulative normalfordelingen +NORMSDIST = NORMSFORDELING ## Returnerer standard kumulativ normalfordeling +NORMSINV = NORMSINV ## Returnerer den inverse av den den kumulative standard normalfordelingen +PEARSON = PEARSON ## Returnerer produktmomentkorrelasjonskoeffisienten, Pearson +PERCENTILE = PERSENTIL ## Returnerer den n-te persentil av verdiene i et område +PERCENTRANK = PROSENTDEL ## Returnerer prosentrangeringen av en verdi i et datasett +PERMUT = PERMUTER ## Returnerer antall permutasjoner for et gitt antall objekter +POISSON = POISSON ## Returnerer Poissons sannsynlighetsfordeling +PROB = SANNSYNLIG ## Returnerer sannsynligheten for at verdier i et område ligger mellom to grenser +QUARTILE = KVARTIL ## Returnerer kvartilen til et datasett +RANK = RANG ## Returnerer rangeringen av et tall, eller plassen tallet har i en rekke +RSQ = RKVADRAT ## Returnerer kvadratet av produktmomentkorrelasjonskoeffisienten (Pearsons r) +SKEW = SKJEVFORDELING ## Returnerer skjevheten i en fordeling +SLOPE = STIGNINGSTALL ## Returnerer stigningtallet for den lineære regresjonslinjen +SMALL = N.MINST ## Returnerer den n-te minste verdien i et datasett +STANDARDIZE = NORMALISER ## Returnerer en normalisert verdi +STDEV = STDAV ## Estimere standardavvik på grunnlag av et utvalg +STDEVA = STDAVVIKA ## Estimerer standardavvik basert på et utvalg, inkludert tall, tekst og logiske verdier +STDEVP = STDAVP ## Beregner standardavvik basert på hele populasjonen +STDEVPA = STDAVVIKPA ## Beregner standardavvik basert på hele populasjonen, inkludert tall, tekst og logiske verdier +STEYX = STANDARDFEIL ## Returnerer standardfeilen for den predikerte y-verdien for hver x i regresjonen +TDIST = TFORDELING ## Returnerer en Student t-fordeling +TINV = TINV ## Returnerer den inverse Student t-fordelingen +TREND = TREND ## Returnerer verdier langs en lineær trend +TRIMMEAN = TRIMMET.GJENNOMSNITT ## Returnerer den interne middelverdien til et datasett +TTEST = TTEST ## Returnerer sannsynligheten assosiert med en Student t-test +VAR = VARIANS ## Estimerer varians basert på et utvalg +VARA = VARIANSA ## Estimerer varians basert på et utvalg, inkludert tall, tekst og logiske verdier +VARP = VARIANSP ## Beregner varians basert på hele populasjonen +VARPA = VARIANSPA ## Beregner varians basert på hele populasjonen, inkludert tall, tekst og logiske verdier +WEIBULL = WEIBULL.FORDELING ## Returnerer Weibull-fordelingen +ZTEST = ZTEST ## Returnerer den ensidige sannsynlighetsverdien for en z-test + + +## +## Text functions Tekstfunksjoner +## +ASC = STIGENDE ## Endrer fullbreddes (dobbeltbyte) engelske bokstaver eller katakana i en tegnstreng, til halvbreddes (enkeltbyte) tegn +BAHTTEXT = BAHTTEKST ## Konverterer et tall til tekst, og bruker valutaformatet ß (baht) +CHAR = TEGNKODE ## Returnerer tegnet som svarer til kodenummeret +CLEAN = RENSK ## Fjerner alle tegn som ikke kan skrives ut, fra teksten +CODE = KODE ## Returnerer en numerisk kode for det første tegnet i en tekststreng +CONCATENATE = KJEDE.SAMMEN ## Slår sammen flere tekstelementer til ett tekstelement +DOLLAR = VALUTA ## Konverterer et tall til tekst, og bruker valutaformatet $ (dollar) +EXACT = EKSAKT ## Kontrollerer om to tekstverdier er like +FIND = FINN ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) +FINDB = FINNB ## Finner en tekstverdi inne i en annen (skiller mellom store og små bokstaver) +FIXED = FASTSATT ## Formaterer et tall som tekst med et bestemt antall desimaler +JIS = JIS ## Endrer halvbreddes (enkeltbyte) engelske bokstaver eller katakana i en tegnstreng, til fullbreddes (dobbeltbyte) tegn +LEFT = VENSTRE ## Returnerer tegnene lengst til venstre i en tekstverdi +LEFTB = VENSTREB ## Returnerer tegnene lengst til venstre i en tekstverdi +LEN = LENGDE ## Returnerer antall tegn i en tekststreng +LENB = LENGDEB ## Returnerer antall tegn i en tekststreng +LOWER = SMÅ ## Konverterer tekst til små bokstaver +MID = DELTEKST ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir +MIDB = DELTEKSTB ## Returnerer et angitt antall tegn fra en tekststreng, og begynner fra posisjonen du angir +PHONETIC = FURIGANA ## Trekker ut fonetiske tegn (furigana) fra en tekststreng +PROPER = STOR.FORBOKSTAV ## Gir den første bokstaven i hvert ord i en tekstverdi stor forbokstav +REPLACE = ERSTATT ## Erstatter tegn i en tekst +REPLACEB = ERSTATTB ## Erstatter tegn i en tekst +REPT = GJENTA ## Gjentar tekst et gitt antall ganger +RIGHT = HØYRE ## Returnerer tegnene lengst til høyre i en tekstverdi +RIGHTB = HØYREB ## Returnerer tegnene lengst til høyre i en tekstverdi +SEARCH = SØK ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) +SEARCHB = SØKB ## Finner en tekstverdi inne i en annen (skiller ikke mellom store og små bokstaver) +SUBSTITUTE = BYTT.UT ## Bytter ut gammel tekst med ny tekst i en tekststreng +T = T ## Konverterer argumentene til tekst +TEXT = TEKST ## Formaterer et tall og konverterer det til tekst +TRIM = TRIMME ## Fjerner mellomrom fra tekst +UPPER = STORE ## Konverterer tekst til store bokstaver +VALUE = VERDI ## Konverterer et tekstargument til et tall diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/config new file mode 100644 index 00000000..4dd75bee --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = zł + + +## +## Excel Error Codes (For future use) +## +NULL = #ZERO! +DIV0 = #DZIEL/0! +VALUE = #ARG! +REF = #ADR! +NAME = #NAZWA? +NUM = #LICZBA! +NA = #N/D! diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/functions new file mode 100644 index 00000000..1881a71e --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pl/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Funkcje dodatków i automatyzacji +## +GETPIVOTDATA = WEŹDANETABELI ## Zwraca dane przechowywane w raporcie tabeli przestawnej. + + +## +## Cube functions Funkcje modułów +## +CUBEKPIMEMBER = ELEMENT.KPI.MODUŁU ## Zwraca nazwę, właściwość i miarę kluczowego wskaźnika wydajności (KPI) oraz wyświetla nazwę i właściwość w komórce. Wskaźnik KPI jest miarą ilościową, taką jak miesięczny zysk brutto lub kwartalna fluktuacja pracowników, używaną do monitorowania wydajności organizacji. +CUBEMEMBER = ELEMENT.MODUŁU ## Zwraca element lub krotkę z hierarchii modułu. Służy do sprawdzania, czy element lub krotka istnieje w module. +CUBEMEMBERPROPERTY = WŁAŚCIWOŚĆ.ELEMENTU.MODUŁU ## Zwraca wartość właściwości elementu w module. Służy do sprawdzania, czy nazwa elementu istnieje w module, i zwracania określonej właściwości dla tego elementu. +CUBERANKEDMEMBER = USZEREGOWANY.ELEMENT.MODUŁU ## Zwraca n-ty (albo uszeregowany) element zestawu. Służy do zwracania elementu lub elementów zestawu, na przykład najlepszego sprzedawcy lub 10 najlepszych studentów. +CUBESET = ZESTAW.MODUŁÓW ## Definiuje obliczony zestaw elementów lub krotek, wysyłając wyrażenie zestawu do serwera modułu, który tworzy zestaw i zwraca go do programu Microsoft Office Excel. +CUBESETCOUNT = LICZNIK.MODUŁÓW.ZESTAWU ## Zwraca liczbę elementów zestawu. +CUBEVALUE = WARTOŚĆ.MODUŁU ## Zwraca zagregowaną wartość z modułu. + + +## +## Database functions Funkcje baz danych +## +DAVERAGE = BD.ŚREDNIA ## Zwraca wartość średniej wybranych wpisów bazy danych. +DCOUNT = BD.ILE.REKORDÓW ## Zlicza komórki zawierające liczby w bazie danych. +DCOUNTA = BD.ILE.REKORDÓW.A ## Zlicza niepuste komórki w bazie danych. +DGET = BD.POLE ## Wyodrębnia z bazy danych jeden rekord spełniający określone kryteria. +DMAX = BD.MAX ## Zwraca wartość maksymalną z wybranych wpisów bazy danych. +DMIN = BD.MIN ## Zwraca wartość minimalną z wybranych wpisów bazy danych. +DPRODUCT = BD.ILOCZYN ## Mnoży wartości w konkretnym, spełniającym kryteria polu rekordów bazy danych. +DSTDEV = BD.ODCH.STANDARD ## Szacuje odchylenie standardowe na podstawie próbki z wybranych wpisów bazy danych. +DSTDEVP = BD.ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji wybranych wpisów bazy danych. +DSUM = BD.SUMA ## Dodaje liczby w kolumnie pól rekordów bazy danych, które spełniają kryteria. +DVAR = BD.WARIANCJA ## Szacuje wariancję na podstawie próbki z wybranych wpisów bazy danych. +DVARP = BD.WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji wybranych wpisów bazy danych. + + +## +## Date and time functions Funkcje dat, godzin i czasu +## +DATE = DATA ## Zwraca liczbę seryjną dla wybranej daty. +DATEVALUE = DATA.WARTOŚĆ ## Konwertuje datę w formie tekstu na liczbę seryjną. +DAY = DZIEŃ ## Konwertuje liczbę seryjną na dzień miesiąca. +DAYS360 = DNI.360 ## Oblicza liczbę dni między dwiema datami na podstawie roku 360-dniowego. +EDATE = UPŁDNI ## Zwraca liczbę seryjną daty jako wskazaną liczbę miesięcy przed określoną datą początkową lub po niej. +EOMONTH = EOMONTH ## Zwraca liczbę seryjną ostatniego dnia miesiąca przed określoną liczbą miesięcy lub po niej. +HOUR = GODZINA ## Konwertuje liczbę seryjną na godzinę. +MINUTE = MINUTA ## Konwertuje liczbę seryjną na minutę. +MONTH = MIESIĄC ## Konwertuje liczbę seryjną na miesiąc. +NETWORKDAYS = NETWORKDAYS ## Zwraca liczbę pełnych dni roboczych między dwiema datami. +NOW = TERAZ ## Zwraca liczbę seryjną bieżącej daty i godziny. +SECOND = SEKUNDA ## Konwertuje liczbę seryjną na sekundę. +TIME = CZAS ## Zwraca liczbę seryjną określonego czasu. +TIMEVALUE = CZAS.WARTOŚĆ ## Konwertuje czas w formie tekstu na liczbę seryjną. +TODAY = DZIŚ ## Zwraca liczbę seryjną dla daty bieżącej. +WEEKDAY = DZIEŃ.TYG ## Konwertuje liczbę seryjną na dzień tygodnia. +WEEKNUM = WEEKNUM ## Konwertuje liczbę seryjną na liczbę reprezentującą numer tygodnia w roku. +WORKDAY = WORKDAY ## Zwraca liczbę seryjną dla daty przed określoną liczbą dni roboczych lub po niej. +YEAR = ROK ## Konwertuje liczbę seryjną na rok. +YEARFRAC = YEARFRAC ## Zwraca część roku reprezentowaną przez pełną liczbę dni między datą początkową a datą końcową. + + +## +## Engineering functions Funkcje inżynierskie +## +BESSELI = BESSELI ## Zwraca wartość zmodyfikowanej funkcji Bessela In(x). +BESSELJ = BESSELJ ## Zwraca wartość funkcji Bessela Jn(x). +BESSELK = BESSELK ## Zwraca wartość zmodyfikowanej funkcji Bessela Kn(x). +BESSELY = BESSELY ## Zwraca wartość funkcji Bessela Yn(x). +BIN2DEC = BIN2DEC ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci dziesiętnej. +BIN2HEX = BIN2HEX ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci szesnastkowej. +BIN2OCT = BIN2OCT ## Konwertuje liczbę w postaci dwójkowej na liczbę w postaci ósemkowej. +COMPLEX = COMPLEX ## Konwertuje część rzeczywistą i urojoną na liczbę zespoloną. +CONVERT = CONVERT ## Konwertuje liczbę z jednego systemu miar na inny. +DEC2BIN = DEC2BIN ## Konwertuje liczbę w postaci dziesiętnej na postać dwójkową. +DEC2HEX = DEC2HEX ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci szesnastkowej. +DEC2OCT = DEC2OCT ## Konwertuje liczbę w postaci dziesiętnej na liczbę w postaci ósemkowej. +DELTA = DELTA ## Sprawdza, czy dwie wartości są równe. +ERF = ERF ## Zwraca wartość funkcji błędu. +ERFC = ERFC ## Zwraca wartość komplementarnej funkcji błędu. +GESTEP = GESTEP ## Sprawdza, czy liczba jest większa niż wartość progowa. +HEX2BIN = HEX2BIN ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dwójkowej. +HEX2DEC = HEX2DEC ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci dziesiętnej. +HEX2OCT = HEX2OCT ## Konwertuje liczbę w postaci szesnastkowej na liczbę w postaci ósemkowej. +IMABS = IMABS ## Zwraca wartość bezwzględną (moduł) liczby zespolonej. +IMAGINARY = IMAGINARY ## Zwraca wartość części urojonej liczby zespolonej. +IMARGUMENT = IMARGUMENT ## Zwraca wartość argumentu liczby zespolonej, przy czym kąt wyrażony jest w radianach. +IMCONJUGATE = IMCONJUGATE ## Zwraca wartość liczby sprzężonej danej liczby zespolonej. +IMCOS = IMCOS ## Zwraca wartość cosinusa liczby zespolonej. +IMDIV = IMDIV ## Zwraca wartość ilorazu dwóch liczb zespolonych. +IMEXP = IMEXP ## Zwraca postać wykładniczą liczby zespolonej. +IMLN = IMLN ## Zwraca wartość logarytmu naturalnego liczby zespolonej. +IMLOG10 = IMLOG10 ## Zwraca wartość logarytmu dziesiętnego liczby zespolonej. +IMLOG2 = IMLOG2 ## Zwraca wartość logarytmu liczby zespolonej przy podstawie 2. +IMPOWER = IMPOWER ## Zwraca wartość liczby zespolonej podniesionej do potęgi całkowitej. +IMPRODUCT = IMPRODUCT ## Zwraca wartość iloczynu liczb zespolonych. +IMREAL = IMREAL ## Zwraca wartość części rzeczywistej liczby zespolonej. +IMSIN = IMSIN ## Zwraca wartość sinusa liczby zespolonej. +IMSQRT = IMSQRT ## Zwraca wartość pierwiastka kwadratowego z liczby zespolonej. +IMSUB = IMSUB ## Zwraca wartość różnicy dwóch liczb zespolonych. +IMSUM = IMSUM ## Zwraca wartość sumy liczb zespolonych. +OCT2BIN = OCT2BIN ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dwójkowej. +OCT2DEC = OCT2DEC ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci dziesiętnej. +OCT2HEX = OCT2HEX ## Konwertuje liczbę w postaci ósemkowej na liczbę w postaci szesnastkowej. + + +## +## Financial functions Funkcje finansowe +## +ACCRINT = ACCRINT ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem okresowym. +ACCRINTM = ACCRINTM ## Zwraca narosłe odsetki dla papieru wartościowego z oprocentowaniem w terminie wykupu. +AMORDEGRC = AMORDEGRC ## Zwraca amortyzację dla każdego okresu rozliczeniowego z wykorzystaniem współczynnika amortyzacji. +AMORLINC = AMORLINC ## Zwraca amortyzację dla każdego okresu rozliczeniowego. +COUPDAYBS = COUPDAYBS ## Zwraca liczbę dni od początku okresu dywidendy do dnia rozliczeniowego. +COUPDAYS = COUPDAYS ## Zwraca liczbę dni w okresie dywidendy, z uwzględnieniem dnia rozliczeniowego. +COUPDAYSNC = COUPDAYSNC ## Zwraca liczbę dni od dnia rozliczeniowego do daty następnego dnia dywidendy. +COUPNCD = COUPNCD ## Zwraca dzień następnej dywidendy po dniu rozliczeniowym. +COUPNUM = COUPNUM ## Zwraca liczbę dywidend płatnych między dniem rozliczeniowym a dniem wykupu. +COUPPCD = COUPPCD ## Zwraca dzień poprzedniej dywidendy przed dniem rozliczeniowym. +CUMIPMT = CUMIPMT ## Zwraca wartość procentu składanego płatnego między dwoma okresami. +CUMPRINC = CUMPRINC ## Zwraca wartość kapitału skumulowanego spłaty pożyczki między dwoma okresami. +DB = DB ## Zwraca amortyzację środka trwałego w danym okresie metodą degresywną z zastosowaniem stałej bazowej. +DDB = DDB ## Zwraca amortyzację środka trwałego za podany okres metodą degresywną z zastosowaniem podwójnej bazowej lub metodą określoną przez użytkownika. +DISC = DISC ## Zwraca wartość stopy dyskontowej papieru wartościowego. +DOLLARDE = DOLLARDE ## Konwertuje cenę w postaci ułamkowej na cenę wyrażoną w postaci dziesiętnej. +DOLLARFR = DOLLARFR ## Konwertuje cenę wyrażoną w postaci dziesiętnej na cenę wyrażoną w postaci ułamkowej. +DURATION = DURATION ## Zwraca wartość rocznego przychodu z papieru wartościowego o okresowych wypłatach oprocentowania. +EFFECT = EFFECT ## Zwraca wartość efektywnej rocznej stopy procentowej. +FV = FV ## Zwraca przyszłą wartość lokaty. +FVSCHEDULE = FVSCHEDULE ## Zwraca przyszłą wartość kapitału początkowego wraz z szeregiem procentów składanych. +INTRATE = INTRATE ## Zwraca wartość stopy procentowej papieru wartościowego całkowicie ulokowanego. +IPMT = IPMT ## Zwraca wysokość spłaty oprocentowania lokaty za dany okres. +IRR = IRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii przepływów gotówkowych. +ISPMT = ISPMT ## Oblicza wysokość spłaty oprocentowania za dany okres lokaty. +MDURATION = MDURATION ## Zwraca wartość zmodyfikowanego okresu Macauleya dla papieru wartościowego o założonej wartości nominalnej 100 zł. +MIRR = MIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla przypadku, gdy dodatnie i ujemne przepływy gotówkowe mają różne stopy. +NOMINAL = NOMINAL ## Zwraca wysokość nominalnej rocznej stopy procentowej. +NPER = NPER ## Zwraca liczbę okresów dla lokaty. +NPV = NPV ## Zwraca wartość bieżącą netto lokaty na podstawie szeregu okresowych przepływów gotówkowych i stopy dyskontowej. +ODDFPRICE = ODDFPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym pierwszym okresem. +ODDFYIELD = ODDFYIELD ## Zwraca rentowność papieru wartościowego z nietypowym pierwszym okresem. +ODDLPRICE = ODDLPRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z nietypowym ostatnim okresem. +ODDLYIELD = ODDLYIELD ## Zwraca rentowność papieru wartościowego z nietypowym ostatnim okresem. +PMT = PMT ## Zwraca wartość okresowej płatności raty rocznej. +PPMT = PPMT ## Zwraca wysokość spłaty kapitału w przypadku lokaty dla danego okresu. +PRICE = PRICE ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem okresowym. +PRICEDISC = PRICEDISC ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego zdyskontowanego. +PRICEMAT = PRICEMAT ## Zwraca cenę za 100 zł wartości nominalnej papieru wartościowego z oprocentowaniem w terminie wykupu. +PV = PV ## Zwraca wartość bieżącą lokaty. +RATE = RATE ## Zwraca wysokość stopy procentowej w okresie raty rocznej. +RECEIVED = RECEIVED ## Zwraca wartość kapitału otrzymanego przy wykupie papieru wartościowego całkowicie ulokowanego. +SLN = SLN ## Zwraca amortyzację środka trwałego za jeden okres metodą liniową. +SYD = SYD ## Zwraca amortyzację środka trwałego za dany okres metodą sumy cyfr lat amortyzacji. +TBILLEQ = TBILLEQ ## Zwraca rentowność ekwiwalentu obligacji dla bonu skarbowego. +TBILLPRICE = TBILLPRICE ## Zwraca cenę za 100 zł wartości nominalnej bonu skarbowego. +TBILLYIELD = TBILLYIELD ## Zwraca rentowność bonu skarbowego. +VDB = VDB ## Oblicza amortyzację środka trwałego w danym okresie lub jego części metodą degresywną. +XIRR = XIRR ## Zwraca wartość wewnętrznej stopy zwrotu dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. +XNPV = XNPV ## Zwraca wartość bieżącą netto dla serii rozłożonych w czasie przepływów gotówkowych, niekoniecznie okresowych. +YIELD = YIELD ## Zwraca rentowność papieru wartościowego z oprocentowaniem okresowym. +YIELDDISC = YIELDDISC ## Zwraca roczną rentowność zdyskontowanego papieru wartościowego, na przykład bonu skarbowego. +YIELDMAT = YIELDMAT ## Zwraca roczną rentowność papieru wartościowego oprocentowanego przy wykupie. + + +## +## Information functions Funkcje informacyjne +## +CELL = KOMÓRKA ## Zwraca informacje o formacie, położeniu lub zawartości komórki. +ERROR.TYPE = NR.BŁĘDU ## Zwraca liczbę odpowiadającą typowi błędu. +INFO = INFO ## Zwraca informację o aktualnym środowisku pracy. +ISBLANK = CZY.PUSTA ## Zwraca wartość PRAWDA, jeśli wartość jest pusta. +ISERR = CZY.BŁ ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu, z wyjątkiem #N/D!. +ISERROR = CZY.BŁĄD ## Zwraca wartość PRAWDA, jeśli wartość jest dowolną wartością błędu. +ISEVEN = ISEVEN ## Zwraca wartość PRAWDA, jeśli liczba jest parzysta. +ISLOGICAL = CZY.LOGICZNA ## Zwraca wartość PRAWDA, jeśli wartość jest wartością logiczną. +ISNA = CZY.BRAK ## Zwraca wartość PRAWDA, jeśli wartość jest wartością błędu #N/D!. +ISNONTEXT = CZY.NIE.TEKST ## Zwraca wartość PRAWDA, jeśli wartość nie jest tekstem. +ISNUMBER = CZY.LICZBA ## Zwraca wartość PRAWDA, jeśli wartość jest liczbą. +ISODD = ISODD ## Zwraca wartość PRAWDA, jeśli liczba jest nieparzysta. +ISREF = CZY.ADR ## Zwraca wartość PRAWDA, jeśli wartość jest odwołaniem. +ISTEXT = CZY.TEKST ## Zwraca wartość PRAWDA, jeśli wartość jest tekstem. +N = L ## Zwraca wartość przekonwertowaną na postać liczbową. +NA = BRAK ## Zwraca wartość błędu #N/D!. +TYPE = TYP ## Zwraca liczbę wskazującą typ danych wartości. + + +## +## Logical functions Funkcje logiczne +## +AND = ORAZ ## Zwraca wartość PRAWDA, jeśli wszystkie argumenty mają wartość PRAWDA. +FALSE = FAŁSZ ## Zwraca wartość logiczną FAŁSZ. +IF = JEŻELI ## Określa warunek logiczny do sprawdzenia. +IFERROR = JEŻELI.BŁĄD ## Zwraca określoną wartość, jeśli wynikiem obliczenia formuły jest błąd; w przeciwnym przypadku zwraca wynik formuły. +NOT = NIE ## Odwraca wartość logiczną argumentu. +OR = LUB ## Zwraca wartość PRAWDA, jeśli co najmniej jeden z argumentów ma wartość PRAWDA. +TRUE = PRAWDA ## Zwraca wartość logiczną PRAWDA. + + +## +## Lookup and reference functions Funkcje wyszukiwania i odwołań +## +ADDRESS = ADRES ## Zwraca odwołanie do jednej komórki w arkuszu jako wartość tekstową. +AREAS = OBSZARY ## Zwraca liczbę obszarów występujących w odwołaniu. +CHOOSE = WYBIERZ ## Wybiera wartość z listy wartości. +COLUMN = NR.KOLUMNY ## Zwraca numer kolumny z odwołania. +COLUMNS = LICZBA.KOLUMN ## Zwraca liczbę kolumn dla danego odwołania. +HLOOKUP = WYSZUKAJ.POZIOMO ## Przegląda górny wiersz tablicy i zwraca wartość wskazanej komórki. +HYPERLINK = HIPERŁĄCZE ## Tworzy skrót lub skok, który pozwala otwierać dokument przechowywany na serwerze sieciowym, w sieci intranet lub w Internecie. +INDEX = INDEKS ## Używa indeksu do wybierania wartości z odwołania lub tablicy. +INDIRECT = ADR.POŚR ## Zwraca odwołanie określone przez wartość tekstową. +LOOKUP = WYSZUKAJ ## Wyszukuje wartości w wektorze lub tablicy. +MATCH = PODAJ.POZYCJĘ ## Wyszukuje wartości w odwołaniu lub w tablicy. +OFFSET = PRZESUNIĘCIE ## Zwraca adres przesunięty od danego odwołania. +ROW = WIERSZ ## Zwraca numer wiersza odwołania. +ROWS = ILE.WIERSZY ## Zwraca liczbę wierszy dla danego odwołania. +RTD = RTD ## Pobiera dane w czasie rzeczywistym z programu obsługującego automatyzację COM (Automatyzacja: Sposób pracy z obiektami aplikacji pochodzącymi z innej aplikacji lub narzędzia projektowania. Nazywana wcześniej Automatyzacją OLE, Automatyzacja jest standardem przemysłowym i funkcją obiektowego modelu składników (COM, Component Object Model).). +TRANSPOSE = TRANSPONUJ ## Zwraca transponowaną tablicę. +VLOOKUP = WYSZUKAJ.PIONOWO ## Przeszukuje pierwszą kolumnę tablicy i przechodzi wzdłuż wiersza, aby zwrócić wartość komórki. + + +## +## Math and trigonometry functions Funkcje matematyczne i trygonometryczne +## +ABS = MODUŁ.LICZBY ## Zwraca wartość absolutną liczby. +ACOS = ACOS ## Zwraca arcus cosinus liczby. +ACOSH = ACOSH ## Zwraca arcus cosinus hiperboliczny liczby. +ASIN = ASIN ## Zwraca arcus sinus liczby. +ASINH = ASINH ## Zwraca arcus sinus hiperboliczny liczby. +ATAN = ATAN ## Zwraca arcus tangens liczby. +ATAN2 = ATAN2 ## Zwraca arcus tangens liczby na podstawie współrzędnych x i y. +ATANH = ATANH ## Zwraca arcus tangens hiperboliczny liczby. +CEILING = ZAOKR.W.GÓRĘ ## Zaokrągla liczbę do najbliższej liczby całkowitej lub do najbliższej wielokrotności dokładności. +COMBIN = KOMBINACJE ## Zwraca liczbę kombinacji dla danej liczby obiektów. +COS = COS ## Zwraca cosinus liczby. +COSH = COSH ## Zwraca cosinus hiperboliczny liczby. +DEGREES = STOPNIE ## Konwertuje radiany na stopnie. +EVEN = ZAOKR.DO.PARZ ## Zaokrągla liczbę w górę do najbliższej liczby parzystej. +EXP = EXP ## Zwraca wartość liczby e podniesionej do potęgi określonej przez podaną liczbę. +FACT = SILNIA ## Zwraca silnię liczby. +FACTDOUBLE = FACTDOUBLE ## Zwraca podwójną silnię liczby. +FLOOR = ZAOKR.W.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. +GCD = GCD ## Zwraca największy wspólny dzielnik. +INT = ZAOKR.DO.CAŁK ## Zaokrągla liczbę w dół do najbliższej liczby całkowitej. +LCM = LCM ## Zwraca najmniejszą wspólną wielokrotność. +LN = LN ## Zwraca logarytm naturalny podanej liczby. +LOG = LOG ## Zwraca logarytm danej liczby przy zadanej podstawie. +LOG10 = LOG10 ## Zwraca logarytm dziesiętny liczby. +MDETERM = WYZNACZNIK.MACIERZY ## Zwraca wyznacznik macierzy tablicy. +MINVERSE = MACIERZ.ODW ## Zwraca odwrotność macierzy tablicy. +MMULT = MACIERZ.ILOCZYN ## Zwraca iloczyn macierzy dwóch tablic. +MOD = MOD ## Zwraca resztę z dzielenia. +MROUND = MROUND ## Zwraca liczbę zaokrągloną do żądanej wielokrotności. +MULTINOMIAL = MULTINOMIAL ## Zwraca wielomian dla zbioru liczb. +ODD = ZAOKR.DO.NPARZ ## Zaokrągla liczbę w górę do najbliższej liczby nieparzystej. +PI = PI ## Zwraca wartość liczby Pi. +POWER = POTĘGA ## Zwraca liczbę podniesioną do potęgi. +PRODUCT = ILOCZYN ## Mnoży argumenty. +QUOTIENT = QUOTIENT ## Zwraca iloraz (całkowity). +RADIANS = RADIANY ## Konwertuje stopnie na radiany. +RAND = LOS ## Zwraca liczbę pseudolosową z zakresu od 0 do 1. +RANDBETWEEN = RANDBETWEEN ## Zwraca liczbę pseudolosową z zakresu określonego przez podane argumenty. +ROMAN = RZYMSKIE ## Konwertuje liczbę arabską na rzymską jako tekst. +ROUND = ZAOKR ## Zaokrągla liczbę do określonej liczby cyfr. +ROUNDDOWN = ZAOKR.DÓŁ ## Zaokrągla liczbę w dół, w kierunku zera. +ROUNDUP = ZAOKR.GÓRA ## Zaokrągla liczbę w górę, w kierunku od zera. +SERIESSUM = SERIESSUM ## Zwraca sumę szeregu potęgowego na podstawie wzoru. +SIGN = ZNAK.LICZBY ## Zwraca znak liczby. +SIN = SIN ## Zwraca sinus danego kąta. +SINH = SINH ## Zwraca sinus hiperboliczny liczby. +SQRT = PIERWIASTEK ## Zwraca dodatni pierwiastek kwadratowy. +SQRTPI = SQRTPI ## Zwraca pierwiastek kwadratowy iloczynu (liczba * Pi). +SUBTOTAL = SUMY.POŚREDNIE ## Zwraca sumę częściową listy lub bazy danych. +SUM = SUMA ## Dodaje argumenty. +SUMIF = SUMA.JEŻELI ## Dodaje komórki określone przez podane kryterium. +SUMIFS = SUMA.WARUNKÓW ## Dodaje komórki w zakresie, które spełniają wiele kryteriów. +SUMPRODUCT = SUMA.ILOCZYNÓW ## Zwraca sumę iloczynów odpowiednich elementów tablicy. +SUMSQ = SUMA.KWADRATÓW ## Zwraca sumę kwadratów argumentów. +SUMX2MY2 = SUMA.X2.M.Y2 ## Zwraca sumę różnic kwadratów odpowiednich wartości w dwóch tablicach. +SUMX2PY2 = SUMA.X2.P.Y2 ## Zwraca sumę sum kwadratów odpowiednich wartości w dwóch tablicach. +SUMXMY2 = SUMA.XMY.2 ## Zwraca sumę kwadratów różnic odpowiednich wartości w dwóch tablicach. +TAN = TAN ## Zwraca tangens liczby. +TANH = TANH ## Zwraca tangens hiperboliczny liczby. +TRUNC = LICZBA.CAŁK ## Przycina liczbę do wartości całkowitej. + + +## +## Statistical functions Funkcje statystyczne +## +AVEDEV = ODCH.ŚREDNIE ## Zwraca średnią wartość odchyleń absolutnych punktów danych od ich wartości średniej. +AVERAGE = ŚREDNIA ## Zwraca wartość średnią argumentów. +AVERAGEA = ŚREDNIA.A ## Zwraca wartość średnią argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +AVERAGEIF = ŚREDNIA.JEŻELI ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek w zakresie, które spełniają podane kryteria. +AVERAGEIFS = ŚREDNIA.WARUNKÓW ## Zwraca średnią (średnią arytmetyczną) wszystkich komórek, które spełniają jedno lub więcej kryteriów. +BETADIST = ROZKŁAD.BETA ## Zwraca skumulowaną funkcję gęstości prawdopodobieństwa beta. +BETAINV = ROZKŁAD.BETA.ODW ## Zwraca odwrotność skumulowanej funkcji gęstości prawdopodobieństwa beta. +BINOMDIST = ROZKŁAD.DWUM ## Zwraca pojedynczy składnik dwumianowego rozkładu prawdopodobieństwa. +CHIDIST = ROZKŁAD.CHI ## Zwraca wartość jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. +CHIINV = ROZKŁAD.CHI.ODW ## Zwraca odwrotność wartości jednostronnego prawdopodobieństwa rozkładu chi-kwadrat. +CHITEST = TEST.CHI ## Zwraca test niezależności. +CONFIDENCE = UFNOŚĆ ## Zwraca interwał ufności dla średniej populacji. +CORREL = WSP.KORELACJI ## Zwraca współczynnik korelacji dwóch zbiorów danych. +COUNT = ILE.LICZB ## Zlicza liczby znajdujące się na liście argumentów. +COUNTA = ILE.NIEPUSTYCH ## Zlicza wartości znajdujące się na liście argumentów. +COUNTBLANK = LICZ.PUSTE ## Zwraca liczbę pustych komórek w pewnym zakresie. +COUNTIF = LICZ.JEŻELI ## Zlicza komórki wewnątrz zakresu, które spełniają podane kryteria. +COUNTIFS = LICZ.WARUNKI ## Zlicza komórki wewnątrz zakresu, które spełniają wiele kryteriów. +COVAR = KOWARIANCJA ## Zwraca kowariancję, czyli średnią wartość iloczynów odpowiednich odchyleń. +CRITBINOM = PRÓG.ROZKŁAD.DWUM ## Zwraca najmniejszą wartość, dla której skumulowany rozkład dwumianowy jest mniejszy niż wartość kryterium lub równy jej. +DEVSQ = ODCH.KWADRATOWE ## Zwraca sumę kwadratów odchyleń. +EXPONDIST = ROZKŁAD.EXP ## Zwraca rozkład wykładniczy. +FDIST = ROZKŁAD.F ## Zwraca rozkład prawdopodobieństwa F. +FINV = ROZKŁAD.F.ODW ## Zwraca odwrotność rozkładu prawdopodobieństwa F. +FISHER = ROZKŁAD.FISHER ## Zwraca transformację Fishera. +FISHERINV = ROZKŁAD.FISHER.ODW ## Zwraca odwrotność transformacji Fishera. +FORECAST = REGLINX ## Zwraca wartość trendu liniowego. +FREQUENCY = CZĘSTOŚĆ ## Zwraca rozkład częstotliwości jako tablicę pionową. +FTEST = TEST.F ## Zwraca wynik testu F. +GAMMADIST = ROZKŁAD.GAMMA ## Zwraca rozkład gamma. +GAMMAINV = ROZKŁAD.GAMMA.ODW ## Zwraca odwrotność skumulowanego rozkładu gamma. +GAMMALN = ROZKŁAD.LIN.GAMMA ## Zwraca logarytm naturalny funkcji gamma, Γ(x). +GEOMEAN = ŚREDNIA.GEOMETRYCZNA ## Zwraca średnią geometryczną. +GROWTH = REGEXPW ## Zwraca wartości trendu wykładniczego. +HARMEAN = ŚREDNIA.HARMONICZNA ## Zwraca średnią harmoniczną. +HYPGEOMDIST = ROZKŁAD.HIPERGEOM ## Zwraca rozkład hipergeometryczny. +INTERCEPT = ODCIĘTA ## Zwraca punkt przecięcia osi pionowej z linią regresji liniowej. +KURT = KURTOZA ## Zwraca kurtozę zbioru danych. +LARGE = MAX.K ## Zwraca k-tą największą wartość ze zbioru danych. +LINEST = REGLINP ## Zwraca parametry trendu liniowego. +LOGEST = REGEXPP ## Zwraca parametry trendu wykładniczego. +LOGINV = ROZKŁAD.LOG.ODW ## Zwraca odwrotność rozkładu logarytmu naturalnego. +LOGNORMDIST = ROZKŁAD.LOG ## Zwraca skumulowany rozkład logarytmu naturalnego. +MAX = MAX ## Zwraca maksymalną wartość listy argumentów. +MAXA = MAX.A ## Zwraca maksymalną wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +MEDIAN = MEDIANA ## Zwraca medianę podanych liczb. +MIN = MIN ## Zwraca minimalną wartość listy argumentów. +MINA = MIN.A ## Zwraca najmniejszą wartość listy argumentów, z uwzględnieniem liczb, tekstów i wartości logicznych. +MODE = WYST.NAJCZĘŚCIEJ ## Zwraca wartość najczęściej występującą w zbiorze danych. +NEGBINOMDIST = ROZKŁAD.DWUM.PRZEC ## Zwraca ujemny rozkład dwumianowy. +NORMDIST = ROZKŁAD.NORMALNY ## Zwraca rozkład normalny skumulowany. +NORMINV = ROZKŁAD.NORMALNY.ODW ## Zwraca odwrotność rozkładu normalnego skumulowanego. +NORMSDIST = ROZKŁAD.NORMALNY.S ## Zwraca standardowy rozkład normalny skumulowany. +NORMSINV = ROZKŁAD.NORMALNY.S.ODW ## Zwraca odwrotność standardowego rozkładu normalnego skumulowanego. +PEARSON = PEARSON ## Zwraca współczynnik korelacji momentu iloczynu Pearsona. +PERCENTILE = PERCENTYL ## Wyznacza k-ty percentyl wartości w zakresie. +PERCENTRANK = PROCENT.POZYCJA ## Zwraca procentową pozycję wartości w zbiorze danych. +PERMUT = PERMUTACJE ## Zwraca liczbę permutacji dla danej liczby obiektów. +POISSON = ROZKŁAD.POISSON ## Zwraca rozkład Poissona. +PROB = PRAWDPD ## Zwraca prawdopodobieństwo, że wartości w zakresie leżą pomiędzy dwiema granicami. +QUARTILE = KWARTYL ## Wyznacza kwartyl zbioru danych. +RANK = POZYCJA ## Zwraca pozycję liczby na liście liczb. +RSQ = R.KWADRAT ## Zwraca kwadrat współczynnika korelacji momentu iloczynu Pearsona. +SKEW = SKOŚNOŚĆ ## Zwraca skośność rozkładu. +SLOPE = NACHYLENIE ## Zwraca nachylenie linii regresji liniowej. +SMALL = MIN.K ## Zwraca k-tą najmniejszą wartość ze zbioru danych. +STANDARDIZE = NORMALIZUJ ## Zwraca wartość znormalizowaną. +STDEV = ODCH.STANDARDOWE ## Szacuje odchylenie standardowe na podstawie próbki. +STDEVA = ODCH.STANDARDOWE.A ## Szacuje odchylenie standardowe na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. +STDEVP = ODCH.STANDARD.POPUL ## Oblicza odchylenie standardowe na podstawie całej populacji. +STDEVPA = ODCH.STANDARD.POPUL.A ## Oblicza odchylenie standardowe na podstawie całej populacji, z uwzględnieniem liczb, teksów i wartości logicznych. +STEYX = REGBŁSTD ## Zwraca błąd standardowy przewidzianej wartości y dla każdej wartości x w regresji. +TDIST = ROZKŁAD.T ## Zwraca rozkład t-Studenta. +TINV = ROZKŁAD.T.ODW ## Zwraca odwrotność rozkładu t-Studenta. +TREND = REGLINW ## Zwraca wartości trendu liniowego. +TRIMMEAN = ŚREDNIA.WEWN ## Zwraca średnią wartość dla wnętrza zbioru danych. +TTEST = TEST.T ## Zwraca prawdopodobieństwo związane z testem t-Studenta. +VAR = WARIANCJA ## Szacuje wariancję na podstawie próbki. +VARA = WARIANCJA.A ## Szacuje wariancję na podstawie próbki, z uwzględnieniem liczb, tekstów i wartości logicznych. +VARP = WARIANCJA.POPUL ## Oblicza wariancję na podstawie całej populacji. +VARPA = WARIANCJA.POPUL.A ## Oblicza wariancję na podstawie całej populacji, z uwzględnieniem liczb, tekstów i wartości logicznych. +WEIBULL = ROZKŁAD.WEIBULL ## Zwraca rozkład Weibulla. +ZTEST = TEST.Z ## Zwraca wartość jednostronnego prawdopodobieństwa testu z. + + +## +## Text functions Funkcje tekstowe +## +ASC = ASC ## Zamienia litery angielskie lub katakana o pełnej szerokości (dwubajtowe) w ciągu znaków na znaki o szerokości połówkowej (jednobajtowe). +BAHTTEXT = BAHTTEXT ## Konwertuje liczbę na tekst, stosując format walutowy ß (baht). +CHAR = ZNAK ## Zwraca znak o podanym numerze kodu. +CLEAN = OCZYŚĆ ## Usuwa z tekstu wszystkie znaki, które nie mogą być drukowane. +CODE = KOD ## Zwraca kod numeryczny pierwszego znaku w ciągu tekstowym. +CONCATENATE = ZŁĄCZ.TEKSTY ## Łączy kilka oddzielnych tekstów w jeden tekst. +DOLLAR = KWOTA ## Konwertuje liczbę na tekst, stosując format walutowy $ (dolar). +EXACT = PORÓWNAJ ## Sprawdza identyczność dwóch wartości tekstowych. +FIND = ZNAJDŹ ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). +FINDB = ZNAJDŹB ## Znajduje jedną wartość tekstową wewnątrz innej (z uwzględnieniem wielkich i małych liter). +FIXED = ZAOKR.DO.TEKST ## Formatuje liczbę jako tekst przy stałej liczbie miejsc dziesiętnych. +JIS = JIS ## Zmienia litery angielskie lub katakana o szerokości połówkowej (jednobajtowe) w ciągu znaków na znaki o pełnej szerokości (dwubajtowe). +LEFT = LEWY ## Zwraca skrajne lewe znaki z wartości tekstowej. +LEFTB = LEWYB ## Zwraca skrajne lewe znaki z wartości tekstowej. +LEN = DŁ ## Zwraca liczbę znaków ciągu tekstowego. +LENB = DŁ.B ## Zwraca liczbę znaków ciągu tekstowego. +LOWER = LITERY.MAŁE ## Konwertuje wielkie litery tekstu na małe litery. +MID = FRAGMENT.TEKSTU ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. +MIDB = FRAGMENT.TEKSTU.B ## Zwraca określoną liczbę znaków z ciągu tekstowego, zaczynając od zadanej pozycji. +PHONETIC = PHONETIC ## Wybiera znaki fonetyczne (furigana) z ciągu tekstowego. +PROPER = Z.WIELKIEJ.LITERY ## Zastępuje pierwszą literę każdego wyrazu tekstu wielką literą. +REPLACE = ZASTĄP ## Zastępuje znaki w tekście. +REPLACEB = ZASTĄP.B ## Zastępuje znaki w tekście. +REPT = POWT ## Powiela tekst daną liczbę razy. +RIGHT = PRAWY ## Zwraca skrajne prawe znaki z wartości tekstowej. +RIGHTB = PRAWYB ## Zwraca skrajne prawe znaki z wartości tekstowej. +SEARCH = SZUKAJ.TEKST ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). +SEARCHB = SZUKAJ.TEKST.B ## Wyszukuje jedną wartość tekstową wewnątrz innej (bez uwzględniania wielkości liter). +SUBSTITUTE = PODSTAW ## Podstawia nowy tekst w miejsce poprzedniego tekstu w ciągu tekstowym. +T = T ## Konwertuje argumenty na tekst. +TEXT = TEKST ## Formatuje liczbę i konwertuje ją na tekst. +TRIM = USUŃ.ZBĘDNE.ODSTĘPY ## Usuwa spacje z tekstu. +UPPER = LITERY.WIELKIE ## Konwertuje znaki tekstu na wielkie litery. +VALUE = WARTOŚĆ ## Konwertuje argument tekstowy na liczbę. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/config new file mode 100644 index 00000000..45b6fbd9 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = R$ + + +## +## Excel Error Codes (For future use) +## +NULL = #NULO! +DIV0 = #DIV/0! +VALUE = #VALOR! +REF = #REF! +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/functions new file mode 100644 index 00000000..a062a7fa --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/br/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Funções Suplemento e Automação +## +GETPIVOTDATA = INFODADOSTABELADINÂMICA ## Retorna os dados armazenados em um relatório de tabela dinâmica + + +## +## Cube functions Funções de Cubo +## +CUBEKPIMEMBER = MEMBROKPICUBO ## Retorna o nome de um KPI (indicador de desempenho-chave), uma propriedade e uma medida e exibe o nome e a propriedade na célula. Um KPI é uma medida quantificável, como o lucro bruto mensal ou a rotatividade trimestral dos funcionários, usada para monitorar o desempenho de uma organização. +CUBEMEMBER = MEMBROCUBO ## Retorna um membro ou tupla em uma hierarquia de cubo. Use para validar se o membro ou tupla existe no cubo. +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Retorna o valor da propriedade de um membro no cubo. Usada para validar a existência do nome do membro no cubo e para retornar a propriedade especificada para esse membro. +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Retorna o enésimo membro, ou o membro ordenado, em um conjunto. Use para retornar um ou mais elementos em um conjunto, assim como o melhor vendedor ou os dez melhores alunos. +CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou tuplas enviando uma expressão do conjunto para o cubo no servidor, que cria o conjunto e o retorna para o Microsoft Office Excel. +CUBESETCOUNT = CONTAGEMCONJUNTOCUBO ## Retorna o número de itens em um conjunto. +CUBEVALUE = VALORCUBO ## Retorna um valor agregado de um cubo. + + +## +## Database functions Funções de banco de dados +## +DAVERAGE = BDMÉDIA ## Retorna a média das entradas selecionadas de um banco de dados +DCOUNT = BDCONTAR ## Conta as células que contêm números em um banco de dados +DCOUNTA = BDCONTARA ## Conta células não vazias em um banco de dados +DGET = BDEXTRAIR ## Extrai de um banco de dados um único registro que corresponde a um critério específico +DMAX = BDMÁX ## Retorna o valor máximo de entradas selecionadas de um banco de dados +DMIN = BDMÍN ## Retorna o valor mínimo de entradas selecionadas de um banco de dados +DPRODUCT = BDMULTIPL ## Multiplica os valores em um campo específico de registros que correspondem ao critério em um banco de dados +DSTDEV = BDEST ## Estima o desvio padrão com base em uma amostra de entradas selecionadas de um banco de dados +DSTDEVP = BDDESVPA ## Calcula o desvio padrão com base na população inteira de entradas selecionadas de um banco de dados +DSUM = BDSOMA ## Adiciona os números à coluna de campos de registros do banco de dados que correspondem ao critério +DVAR = BDVAREST ## Estima a variância com base em uma amostra de entradas selecionadas de um banco de dados +DVARP = BDVARP ## Calcula a variância com base na população inteira de entradas selecionadas de um banco de dados + + +## +## Date and time functions Funções de data e hora +## +DATE = DATA ## Retorna o número de série de uma data específica +DATEVALUE = DATA.VALOR ## Converte uma data na forma de texto para um número de série +DAY = DIA ## Converte um número de série em um dia do mês +DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base em um ano de 360 dias +EDATE = DATAM ## Retorna o número de série da data que é o número indicado de meses antes ou depois da data inicial +EOMONTH = FIMMÊS ## Retorna o número de série do último dia do mês antes ou depois de um número especificado de meses +HOUR = HORA ## Converte um número de série em uma hora +MINUTE = MINUTO ## Converte um número de série em um minuto +MONTH = MÊS ## Converte um número de série em um mês +NETWORKDAYS = DIATRABALHOTOTAL ## Retorna o número de dias úteis inteiros entre duas datas +NOW = AGORA ## Retorna o número de série seqüencial da data e hora atuais +SECOND = SEGUNDO ## Converte um número de série em um segundo +TIME = HORA ## Retorna o número de série de uma hora específica +TIMEVALUE = VALOR.TEMPO ## Converte um horário na forma de texto para um número de série +TODAY = HOJE ## Retorna o número de série da data de hoje +WEEKDAY = DIA.DA.SEMANA ## Converte um número de série em um dia da semana +WEEKNUM = NÚMSEMANA ## Converte um número de série em um número que representa onde a semana cai numericamente em um ano +WORKDAY = DIATRABALHO ## Retorna o número de série da data antes ou depois de um número específico de dias úteis +YEAR = ANO ## Converte um número de série em um ano +YEARFRAC = FRAÇÃOANO ## Retorna a fração do ano que representa o número de dias entre data_inicial e data_final + + +## +## Engineering functions Funções de engenharia +## +BESSELI = BESSELI ## Retorna a função de Bessel In(x) modificada +BESSELJ = BESSELJ ## Retorna a função de Bessel Jn(x) +BESSELK = BESSELK ## Retorna a função de Bessel Kn(x) modificada +BESSELY = BESSELY ## Retorna a função de Bessel Yn(x) +BIN2DEC = BIN2DEC ## Converte um número binário em decimal +BIN2HEX = BIN2HEX ## Converte um número binário em hexadecimal +BIN2OCT = BIN2OCT ## Converte um número binário em octal +COMPLEX = COMPLEX ## Converte coeficientes reais e imaginários e um número complexo +CONVERT = CONVERTER ## Converte um número de um sistema de medida para outro +DEC2BIN = DECABIN ## Converte um número decimal em binário +DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal +DEC2OCT = DECAOCT ## Converte um número decimal em octal +DELTA = DELTA ## Testa se dois valores são iguais +ERF = FUNERRO ## Retorna a função de erro +ERFC = FUNERROCOMPL ## Retorna a função de erro complementar +GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite +HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário +HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal +HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal +IMABS = IMABS ## Retorna o valor absoluto (módulo) de um número complexo +IMAGINARY = IMAGINÁRIO ## Retorna o coeficiente imaginário de um número complexo +IMARGUMENT = IMARG ## Retorna o argumento teta, um ângulo expresso em radianos +IMCONJUGATE = IMCONJ ## Retorna o conjugado complexo de um número complexo +IMCOS = IMCOS ## Retorna o cosseno de um número complexo +IMDIV = IMDIV ## Retorna o quociente de dois números complexos +IMEXP = IMEXP ## Retorna o exponencial de um número complexo +IMLN = IMLN ## Retorna o logaritmo natural de um número complexo +IMLOG10 = IMLOG10 ## Retorna o logaritmo de base 10 de um número complexo +IMLOG2 = IMLOG2 ## Retorna o logaritmo de base 2 de um número complexo +IMPOWER = IMPOT ## Retorna um número complexo elevado a uma potência inteira +IMPRODUCT = IMPROD ## Retorna o produto de números complexos +IMREAL = IMREAL ## Retorna o coeficiente real de um número complexo +IMSIN = IMSENO ## Retorna o seno de um número complexo +IMSQRT = IMRAIZ ## Retorna a raiz quadrada de um número complexo +IMSUB = IMSUBTR ## Retorna a diferença entre dois números complexos +IMSUM = IMSOMA ## Retorna a soma de números complexos +OCT2BIN = OCTABIN ## Converte um número octal em binário +OCT2DEC = OCTADEC ## Converte um número octal em decimal +OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal + + +## +## Financial functions Funções financeiras +## +ACCRINT = JUROSACUM ## Retorna a taxa de juros acumulados de um título que paga uma taxa periódica de juros +ACCRINTM = JUROSACUMV ## Retorna os juros acumulados de um título que paga juros no vencimento +AMORDEGRC = AMORDEGRC ## Retorna a depreciação para cada período contábil usando o coeficiente de depreciação +AMORLINC = AMORLINC ## Retorna a depreciação para cada período contábil +COUPDAYBS = CUPDIASINLIQ ## Retorna o número de dias do início do período de cupom até a data de liquidação +COUPDAYS = CUPDIAS ## Retorna o número de dias no período de cupom que contém a data de quitação +COUPDAYSNC = CUPDIASPRÓX ## Retorna o número de dias da data de liquidação até a data do próximo cupom +COUPNCD = CUPDATAPRÓX ## Retorna a próxima data de cupom após a data de quitação +COUPNUM = CUPNÚM ## Retorna o número de cupons pagáveis entre as datas de quitação e vencimento +COUPPCD = CUPDATAANT ## Retorna a data de cupom anterior à data de quitação +CUMIPMT = PGTOJURACUM ## Retorna os juros acumulados pagos entre dois períodos +CUMPRINC = PGTOCAPACUM ## Retorna o capital acumulado pago sobre um empréstimo entre dois períodos +DB = BD ## Retorna a depreciação de um ativo para um período especificado, usando o método de balanço de declínio fixo +DDB = BDD ## Retorna a depreciação de um ativo com relação a um período especificado usando o método de saldos decrescentes duplos ou qualquer outro método especificado por você +DISC = DESC ## Retorna a taxa de desconto de um título +DOLLARDE = MOEDADEC ## Converte um preço em formato de moeda, na forma fracionária, em um preço na forma decimal +DOLLARFR = MOEDAFRA ## Converte um preço, apresentado na forma decimal, em um preço apresentado na forma fracionária +DURATION = DURAÇÃO ## Retorna a duração anual de um título com pagamentos de juros periódicos +EFFECT = EFETIVA ## Retorna a taxa de juros anual efetiva +FV = VF ## Retorna o valor futuro de um investimento +FVSCHEDULE = VFPLANO ## Retorna o valor futuro de um capital inicial após a aplicação de uma série de taxas de juros compostas +INTRATE = TAXAJUROS ## Retorna a taxa de juros de um título totalmente investido +IPMT = IPGTO ## Retorna o pagamento de juros para um investimento em um determinado período +IRR = TIR ## Retorna a taxa interna de retorno de uma série de fluxos de caixa +ISPMT = ÉPGTO ## Calcula os juros pagos durante um período específico de um investimento +MDURATION = MDURAÇÃO ## Retorna a duração de Macauley modificada para um título com um valor de paridade equivalente a R$ 100 +MIRR = MTIR ## Calcula a taxa interna de retorno em que fluxos de caixa positivos e negativos são financiados com diferentes taxas +NOMINAL = NOMINAL ## Retorna a taxa de juros nominal anual +NPER = NPER ## Retorna o número de períodos de um investimento +NPV = VPL ## Retorna o valor líquido atual de um investimento com base em uma série de fluxos de caixa periódicos e em uma taxa de desconto +ODDFPRICE = PREÇOPRIMINC ## Retorna o preço por R$ 100 de valor nominal de um título com um primeiro período indefinido +ODDFYIELD = LUCROPRIMINC ## Retorna o rendimento de um título com um primeiro período indefinido +ODDLPRICE = PREÇOÚLTINC ## Retorna o preço por R$ 100 de valor nominal de um título com um último período de cupom indefinido +ODDLYIELD = LUCROÚLTINC ## Retorna o rendimento de um título com um último período indefinido +PMT = PGTO ## Retorna o pagamento periódico de uma anuidade +PPMT = PPGTO ## Retorna o pagamento de capital para determinado período de investimento +PRICE = PREÇO ## Retorna a preço por R$ 100,00 de valor nominal de um título que paga juros periódicos +PRICEDISC = PREÇODESC ## Retorna o preço por R$ 100,00 de valor nominal de um título descontado +PRICEMAT = PREÇOVENC ## Retorna o preço por R$ 100,00 de valor nominal de um título que paga juros no vencimento +PV = VP ## Retorna o valor presente de um investimento +RATE = TAXA ## Retorna a taxa de juros por período de uma anuidade +RECEIVED = RECEBER ## Retorna a quantia recebida no vencimento de um título totalmente investido +SLN = DPD ## Retorna a depreciação em linha reta de um ativo durante um período +SYD = SDA ## Retorna a depreciação dos dígitos da soma dos anos de um ativo para um período especificado +TBILLEQ = OTN ## Retorna o rendimento de um título equivalente a uma obrigação do Tesouro +TBILLPRICE = OTNVALOR ## Retorna o preço por R$ 100,00 de valor nominal de uma obrigação do Tesouro +TBILLYIELD = OTNLUCRO ## Retorna o rendimento de uma obrigação do Tesouro +VDB = BDV ## Retorna a depreciação de um ativo para um período especificado ou parcial usando um método de balanço declinante +XIRR = XTIR ## Fornece a taxa interna de retorno para um programa de fluxos de caixa que não é necessariamente periódico +XNPV = XVPL ## Retorna o valor presente líquido de um programa de fluxos de caixa que não é necessariamente periódico +YIELD = LUCRO ## Retorna o lucro de um título que paga juros periódicos +YIELDDISC = LUCRODESC ## Retorna o rendimento anual de um título descontado. Por exemplo, uma obrigação do Tesouro +YIELDMAT = LUCROVENC ## Retorna o lucro anual de um título que paga juros no vencimento + + +## +## Information functions Funções de informação +## +CELL = CÉL ## Retorna informações sobre formatação, localização ou conteúdo de uma célula +ERROR.TYPE = TIPO.ERRO ## Retorna um número correspondente a um tipo de erro +INFO = INFORMAÇÃO ## Retorna informações sobre o ambiente operacional atual +ISBLANK = ÉCÉL.VAZIA ## Retorna VERDADEIRO se o valor for vazio +ISERR = ÉERRO ## Retorna VERDADEIRO se o valor for um valor de erro diferente de #N/D +ISERROR = ÉERROS ## Retorna VERDADEIRO se o valor for um valor de erro +ISEVEN = ÉPAR ## Retorna VERDADEIRO se o número for par +ISLOGICAL = ÉLÓGICO ## Retorna VERDADEIRO se o valor for um valor lógico +ISNA = É.NÃO.DISP ## Retorna VERDADEIRO se o valor for o valor de erro #N/D +ISNONTEXT = É.NÃO.TEXTO ## Retorna VERDADEIRO se o valor for diferente de texto +ISNUMBER = ÉNÚM ## Retorna VERDADEIRO se o valor for um número +ISODD = ÉIMPAR ## Retorna VERDADEIRO se o número for ímpar +ISREF = ÉREF ## Retorna VERDADEIRO se o valor for uma referência +ISTEXT = ÉTEXTO ## Retorna VERDADEIRO se o valor for texto +N = N ## Retorna um valor convertido em um número +NA = NÃO.DISP ## Retorna o valor de erro #N/D +TYPE = TIPO ## Retorna um número indicando o tipo de dados de um valor + + +## +## Logical functions Funções lógicas +## +AND = E ## Retorna VERDADEIRO se todos os seus argumentos forem VERDADEIROS +FALSE = FALSO ## Retorna o valor lógico FALSO +IF = SE ## Especifica um teste lógico a ser executado +IFERROR = SEERRO ## Retornará um valor que você especifica se uma fórmula for avaliada para um erro; do contrário, retornará o resultado da fórmula +NOT = NÃO ## Inverte o valor lógico do argumento +OR = OU ## Retorna VERDADEIRO se um dos argumentos for VERDADEIRO +TRUE = VERDADEIRO ## Retorna o valor lógico VERDADEIRO + + +## +## Lookup and reference functions Funções de pesquisa e referência +## +ADDRESS = ENDEREÇO ## Retorna uma referência como texto para uma única célula em uma planilha +AREAS = ÁREAS ## Retorna o número de áreas em uma referência +CHOOSE = ESCOLHER ## Escolhe um valor a partir de uma lista de valores +COLUMN = COL ## Retorna o número da coluna de uma referência +COLUMNS = COLS ## Retorna o número de colunas em uma referência +HLOOKUP = PROCH ## Procura na linha superior de uma matriz e retorna o valor da célula especificada +HYPERLINK = HYPERLINK ## Cria um atalho ou salto que abre um documento armazenado em um servidor de rede, uma intranet ou na Internet +INDEX = ÍNDICE ## Usa um índice para escolher um valor de uma referência ou matriz +INDIRECT = INDIRETO ## Retorna uma referência indicada por um valor de texto +LOOKUP = PROC ## Procura valores em um vetor ou em uma matriz +MATCH = CORRESP ## Procura valores em uma referência ou em uma matriz +OFFSET = DESLOC ## Retorna um deslocamento de referência com base em uma determinada referência +ROW = LIN ## Retorna o número da linha de uma referência +ROWS = LINS ## Retorna o número de linhas em uma referência +RTD = RTD ## Recupera dados em tempo real de um programa que ofereça suporte a automação COM (automação: uma forma de trabalhar com objetos de um aplicativo a partir de outro aplicativo ou ferramenta de desenvolvimento. Chamada inicialmente de automação OLE, a automação é um padrão industrial e um recurso do modelo de objeto componente (COM).) +TRANSPOSE = TRANSPOR ## Retorna a transposição de uma matriz +VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e move ao longo da linha para retornar o valor de uma célula + + +## +## Math and trigonometry functions Funções matemáticas e trigonométricas +## +ABS = ABS ## Retorna o valor absoluto de um número +ACOS = ACOS ## Retorna o arco cosseno de um número +ACOSH = ACOSH ## Retorna o cosseno hiperbólico inverso de um número +ASIN = ASEN ## Retorna o arco seno de um número +ASINH = ASENH ## Retorna o seno hiperbólico inverso de um número +ATAN = ATAN ## Retorna o arco tangente de um número +ATAN2 = ATAN2 ## Retorna o arco tangente das coordenadas x e y especificadas +ATANH = ATANH ## Retorna a tangente hiperbólica inversa de um número +CEILING = TETO ## Arredonda um número para o inteiro mais próximo ou para o múltiplo mais próximo de significância +COMBIN = COMBIN ## Retorna o número de combinações de um determinado número de objetos +COS = COS ## Retorna o cosseno de um número +COSH = COSH ## Retorna o cosseno hiperbólico de um número +DEGREES = GRAUS ## Converte radianos em graus +EVEN = PAR ## Arredonda um número para cima até o inteiro par mais próximo +EXP = EXP ## Retorna e elevado à potência de um número especificado +FACT = FATORIAL ## Retorna o fatorial de um número +FACTDOUBLE = FATDUPLO ## Retorna o fatorial duplo de um número +FLOOR = ARREDMULTB ## Arredonda um número para baixo até zero +GCD = MDC ## Retorna o máximo divisor comum +INT = INT ## Arredonda um número para baixo até o número inteiro mais próximo +LCM = MMC ## Retorna o mínimo múltiplo comum +LN = LN ## Retorna o logaritmo natural de um número +LOG = LOG ## Retorna o logaritmo de um número de uma base especificada +LOG10 = LOG10 ## Retorna o logaritmo de base 10 de um número +MDETERM = MATRIZ.DETERM ## Retorna o determinante de uma matriz de uma variável do tipo matriz +MINVERSE = MATRIZ.INVERSO ## Retorna a matriz inversa de uma matriz +MMULT = MATRIZ.MULT ## Retorna o produto de duas matrizes +MOD = RESTO ## Retorna o resto da divisão +MROUND = MARRED ## Retorna um número arredondado ao múltiplo desejado +MULTINOMIAL = MULTINOMIAL ## Retorna o multinomial de um conjunto de números +ODD = ÍMPAR ## Arredonda um número para cima até o inteiro ímpar mais próximo +PI = PI ## Retorna o valor de Pi +POWER = POTÊNCIA ## Fornece o resultado de um número elevado a uma potência +PRODUCT = MULT ## Multiplica seus argumentos +QUOTIENT = QUOCIENTE ## Retorna a parte inteira de uma divisão +RADIANS = RADIANOS ## Converte graus em radianos +RAND = ALEATÓRIO ## Retorna um número aleatório entre 0 e 1 +RANDBETWEEN = ALEATÓRIOENTRE ## Retorna um número aleatório entre os números especificados +ROMAN = ROMANO ## Converte um algarismo arábico em romano, como texto +ROUND = ARRED ## Arredonda um número até uma quantidade especificada de dígitos +ROUNDDOWN = ARREDONDAR.PARA.BAIXO ## Arredonda um número para baixo até zero +ROUNDUP = ARREDONDAR.PARA.CIMA ## Arredonda um número para cima, afastando-o de zero +SERIESSUM = SOMASEQÜÊNCIA ## Retorna a soma de uma série polinomial baseada na fórmula +SIGN = SINAL ## Retorna o sinal de um número +SIN = SEN ## Retorna o seno de um ângulo dado +SINH = SENH ## Retorna o seno hiperbólico de um número +SQRT = RAIZ ## Retorna uma raiz quadrada positiva +SQRTPI = RAIZPI ## Retorna a raiz quadrada de (núm* pi) +SUBTOTAL = SUBTOTAL ## Retorna um subtotal em uma lista ou em um banco de dados +SUM = SOMA ## Soma seus argumentos +SUMIF = SOMASE ## Adiciona as células especificadas por um determinado critério +SUMIFS = SOMASE ## Adiciona as células em um intervalo que atende a vários critérios +SUMPRODUCT = SOMARPRODUTO ## Retorna a soma dos produtos de componentes correspondentes de matrizes +SUMSQ = SOMAQUAD ## Retorna a soma dos quadrados dos argumentos +SUMX2MY2 = SOMAX2DY2 ## Retorna a soma da diferença dos quadrados dos valores correspondentes em duas matrizes +SUMX2PY2 = SOMAX2SY2 ## Retorna a soma da soma dos quadrados dos valores correspondentes em duas matrizes +SUMXMY2 = SOMAXMY2 ## Retorna a soma dos quadrados das diferenças dos valores correspondentes em duas matrizes +TAN = TAN ## Retorna a tangente de um número +TANH = TANH ## Retorna a tangente hiperbólica de um número +TRUNC = TRUNCAR ## Trunca um número para um inteiro + + +## +## Statistical functions Funções estatísticas +## +AVEDEV = DESV.MÉDIO ## Retorna a média aritmética dos desvios médios dos pontos de dados a partir de sua média +AVERAGE = MÉDIA ## Retorna a média dos argumentos +AVERAGEA = MÉDIAA ## Retorna a média dos argumentos, inclusive números, texto e valores lógicos +AVERAGEIF = MÉDIASE ## Retorna a média (média aritmética) de todas as células em um intervalo que atendem a um determinado critério +AVERAGEIFS = MÉDIASES ## Retorna a média (média aritmética) de todas as células que atendem a múltiplos critérios. +BETADIST = DISTBETA ## Retorna a função de distribuição cumulativa beta +BETAINV = BETA.ACUM.INV ## Retorna o inverso da função de distribuição cumulativa para uma distribuição beta especificada +BINOMDIST = DISTRBINOM ## Retorna a probabilidade de distribuição binomial do termo individual +CHIDIST = DIST.QUI ## Retorna a probabilidade unicaudal da distribuição qui-quadrada +CHIINV = INV.QUI ## Retorna o inverso da probabilidade uni-caudal da distribuição qui-quadrada +CHITEST = TESTE.QUI ## Retorna o teste para independência +CONFIDENCE = INT.CONFIANÇA ## Retorna o intervalo de confiança para uma média da população +CORREL = CORREL ## Retorna o coeficiente de correlação entre dois conjuntos de dados +COUNT = CONT.NÚM ## Calcula quantos números há na lista de argumentos +COUNTA = CONT.VALORES ## Calcula quantos valores há na lista de argumentos +COUNTBLANK = CONTAR.VAZIO ## Conta o número de células vazias no intervalo especificado +COUNTIF = CONT.SE ## Calcula o número de células não vazias em um intervalo que corresponde a determinados critérios +COUNTIFS = CONT.SES ## Conta o número de células dentro de um intervalo que atende a múltiplos critérios +COVAR = COVAR ## Retorna a covariância, a média dos produtos dos desvios pares +CRITBINOM = CRIT.BINOM ## Retorna o menor valor para o qual a distribuição binomial cumulativa é menor ou igual ao valor padrão +DEVSQ = DESVQ ## Retorna a soma dos quadrados dos desvios +EXPONDIST = DISTEXPON ## Retorna a distribuição exponencial +FDIST = DISTF ## Retorna a distribuição de probabilidade F +FINV = INVF ## Retorna o inverso da distribuição de probabilidades F +FISHER = FISHER ## Retorna a transformação Fisher +FISHERINV = FISHERINV ## Retorna o inverso da transformação Fisher +FORECAST = PREVISÃO ## Retorna um valor ao longo de uma linha reta +FREQUENCY = FREQÜÊNCIA ## Retorna uma distribuição de freqüência como uma matriz vertical +FTEST = TESTEF ## Retorna o resultado de um teste F +GAMMADIST = DISTGAMA ## Retorna a distribuição gama +GAMMAINV = INVGAMA ## Retorna o inverso da distribuição cumulativa gama +GAMMALN = LNGAMA ## Retorna o logaritmo natural da função gama, G(x) +GEOMEAN = MÉDIA.GEOMÉTRICA ## Retorna a média geométrica +GROWTH = CRESCIMENTO ## Retorna valores ao longo de uma tendência exponencial +HARMEAN = MÉDIA.HARMÔNICA ## Retorna a média harmônica +HYPGEOMDIST = DIST.HIPERGEOM ## Retorna a distribuição hipergeométrica +INTERCEPT = INTERCEPÇÃO ## Retorna a intercepção da linha de regressão linear +KURT = CURT ## Retorna a curtose de um conjunto de dados +LARGE = MAIOR ## Retorna o maior valor k-ésimo de um conjunto de dados +LINEST = PROJ.LIN ## Retorna os parâmetros de uma tendência linear +LOGEST = PROJ.LOG ## Retorna os parâmetros de uma tendência exponencial +LOGINV = INVLOG ## Retorna o inverso da distribuição lognormal +LOGNORMDIST = DIST.LOGNORMAL ## Retorna a distribuição lognormal cumulativa +MAX = MÁXIMO ## Retorna o valor máximo em uma lista de argumentos +MAXA = MÁXIMOA ## Retorna o maior valor em uma lista de argumentos, inclusive números, texto e valores lógicos +MEDIAN = MED ## Retorna a mediana dos números indicados +MIN = MÍNIMO ## Retorna o valor mínimo em uma lista de argumentos +MINA = MÍNIMOA ## Retorna o menor valor em uma lista de argumentos, inclusive números, texto e valores lógicos +MODE = MODO ## Retorna o valor mais comum em um conjunto de dados +NEGBINOMDIST = DIST.BIN.NEG ## Retorna a distribuição binomial negativa +NORMDIST = DIST.NORM ## Retorna a distribuição cumulativa normal +NORMINV = INV.NORM ## Retorna o inverso da distribuição cumulativa normal +NORMSDIST = DIST.NORMP ## Retorna a distribuição cumulativa normal padrão +NORMSINV = INV.NORMP ## Retorna o inverso da distribuição cumulativa normal padrão +PEARSON = PEARSON ## Retorna o coeficiente de correlação do momento do produto Pearson +PERCENTILE = PERCENTIL ## Retorna o k-ésimo percentil de valores em um intervalo +PERCENTRANK = ORDEM.PORCENTUAL ## Retorna a ordem percentual de um valor em um conjunto de dados +PERMUT = PERMUT ## Retorna o número de permutações de um determinado número de objetos +POISSON = POISSON ## Retorna a distribuição Poisson +PROB = PROB ## Retorna a probabilidade de valores em um intervalo estarem entre dois limites +QUARTILE = QUARTIL ## Retorna o quartil do conjunto de dados +RANK = ORDEM ## Retorna a posição de um número em uma lista de números +RSQ = RQUAD ## Retorna o quadrado do coeficiente de correlação do momento do produto de Pearson +SKEW = DISTORÇÃO ## Retorna a distorção de uma distribuição +SLOPE = INCLINAÇÃO ## Retorna a inclinação da linha de regressão linear +SMALL = MENOR ## Retorna o menor valor k-ésimo do conjunto de dados +STANDARDIZE = PADRONIZAR ## Retorna um valor normalizado +STDEV = DESVPAD ## Estima o desvio padrão com base em uma amostra +STDEVA = DESVPADA ## Estima o desvio padrão com base em uma amostra, inclusive números, texto e valores lógicos +STDEVP = DESVPADP ## Calcula o desvio padrão com base na população total +STDEVPA = DESVPADPA ## Calcula o desvio padrão com base na população total, inclusive números, texto e valores lógicos +STEYX = EPADYX ## Retorna o erro padrão do valor-y previsto para cada x da regressão +TDIST = DISTT ## Retorna a distribuição t de Student +TINV = INVT ## Retorna o inverso da distribuição t de Student +TREND = TENDÊNCIA ## Retorna valores ao longo de uma tendência linear +TRIMMEAN = MÉDIA.INTERNA ## Retorna a média do interior de um conjunto de dados +TTEST = TESTET ## Retorna a probabilidade associada ao teste t de Student +VAR = VAR ## Estima a variância com base em uma amostra +VARA = VARA ## Estima a variância com base em uma amostra, inclusive números, texto e valores lógicos +VARP = VARP ## Calcula a variância com base na população inteira +VARPA = VARPA ## Calcula a variância com base na população total, inclusive números, texto e valores lógicos +WEIBULL = WEIBULL ## Retorna a distribuição Weibull +ZTEST = TESTEZ ## Retorna o valor de probabilidade uni-caudal de um teste-z + + +## +## Text functions Funções de texto +## +ASC = ASC ## Altera letras do inglês ou katakana de largura total (bytes duplos) dentro de uma seqüência de caracteres para caracteres de meia largura (byte único) +BAHTTEXT = BAHTTEXT ## Converte um número em um texto, usando o formato de moeda ß (baht) +CHAR = CARACT ## Retorna o caractere especificado pelo número de código +CLEAN = TIRAR ## Remove todos os caracteres do texto que não podem ser impressos +CODE = CÓDIGO ## Retorna um código numérico para o primeiro caractere de uma seqüência de caracteres de texto +CONCATENATE = CONCATENAR ## Agrupa vários itens de texto em um único item de texto +DOLLAR = MOEDA ## Converte um número em texto, usando o formato de moeda $ (dólar) +EXACT = EXATO ## Verifica se dois valores de texto são idênticos +FIND = PROCURAR ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) +FINDB = PROCURARB ## Procura um valor de texto dentro de outro (diferencia maiúsculas de minúsculas) +FIXED = DEF.NÚM.DEC ## Formata um número como texto com um número fixo de decimais +JIS = JIS ## Altera letras do inglês ou katakana de meia largura (byte único) dentro de uma seqüência de caracteres para caracteres de largura total (bytes duplos) +LEFT = ESQUERDA ## Retorna os caracteres mais à esquerda de um valor de texto +LEFTB = ESQUERDAB ## Retorna os caracteres mais à esquerda de um valor de texto +LEN = NÚM.CARACT ## Retorna o número de caracteres em uma seqüência de texto +LENB = NÚM.CARACTB ## Retorna o número de caracteres em uma seqüência de texto +LOWER = MINÚSCULA ## Converte texto para minúsculas +MID = EXT.TEXTO ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada +MIDB = EXT.TEXTOB ## Retorna um número específico de caracteres de uma seqüência de texto começando na posição especificada +PHONETIC = FONÉTICA ## Extrai os caracteres fonéticos (furigana) de uma seqüência de caracteres de texto +PROPER = PRI.MAIÚSCULA ## Coloca a primeira letra de cada palavra em maiúscula em um valor de texto +REPLACE = MUDAR ## Muda os caracteres dentro do texto +REPLACEB = MUDARB ## Muda os caracteres dentro do texto +REPT = REPT ## Repete o texto um determinado número de vezes +RIGHT = DIREITA ## Retorna os caracteres mais à direita de um valor de texto +RIGHTB = DIREITAB ## Retorna os caracteres mais à direita de um valor de texto +SEARCH = LOCALIZAR ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) +SEARCHB = LOCALIZARB ## Localiza um valor de texto dentro de outro (não diferencia maiúsculas de minúsculas) +SUBSTITUTE = SUBSTITUIR ## Substitui um novo texto por um texto antigo em uma seqüência de texto +T = T ## Converte os argumentos em texto +TEXT = TEXTO ## Formata um número e o converte em texto +TRIM = ARRUMAR ## Remove espaços do texto +UPPER = MAIÚSCULA ## Converte o texto em maiúsculas +VALUE = VALOR ## Converte um argumento de texto em um número diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/config new file mode 100644 index 00000000..8bb8d8b8 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = € + + +## +## Excel Error Codes (For future use) +## +NULL = #NULO! +DIV0 = #DIV/0! +VALUE = #VALOR! +REF = #REF! +NAME = #NOME? +NUM = #NÚM! +NA = #N/D diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/functions new file mode 100644 index 00000000..ba4eb471 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/pt/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Funções de Suplemento e Automatização +## +GETPIVOTDATA = OBTERDADOSDIN ## Devolve dados armazenados num relatório de Tabela Dinâmica + + +## +## Cube functions Funções de cubo +## +CUBEKPIMEMBER = MEMBROKPICUBO ## Devolve o nome, propriedade e medição de um KPI (key performance indicator) e apresenta o nome e a propriedade na célula. Um KPI é uma medida quantificável, como, por exemplo, o lucro mensal bruto ou a rotatividade trimestral de pessoal, utilizada para monitorizar o desempenho de uma organização. +CUBEMEMBER = MEMBROCUBO ## Devolve um membro ou cadeia de identificação numa hierarquia de cubo. Utilizada para validar a existência do membro ou cadeia de identificação no cubo. +CUBEMEMBERPROPERTY = PROPRIEDADEMEMBROCUBO ## Devolve o valor de uma propriedade de membro no cubo. Utilizada para validar a existência de um nome de membro no cubo e para devolver a propriedade especificada para esse membro. +CUBERANKEDMEMBER = MEMBROCLASSIFICADOCUBO ## Devolve o enésimo ou a classificação mais alta num conjunto. Utilizada para devolver um ou mais elementos num conjunto, tal como o melhor vendedor ou os 10 melhores alunos. +CUBESET = CONJUNTOCUBO ## Define um conjunto calculado de membros ou cadeias de identificação enviando uma expressão de conjunto para o cubo no servidor, que cria o conjunto e, em seguida, devolve o conjunto ao Microsoft Office Excel. +CUBESETCOUNT = CONTARCONJUNTOCUBO ## Devolve o número de itens num conjunto. +CUBEVALUE = VALORCUBO ## Devolve um valor agregado do cubo. + + +## +## Database functions Funções de base de dados +## +DAVERAGE = BDMÉDIA ## Devolve a média das entradas da base de dados seleccionadas +DCOUNT = BDCONTAR ## Conta as células que contêm números numa base de dados +DCOUNTA = BDCONTAR.VAL ## Conta as células que não estejam em branco numa base de dados +DGET = BDOBTER ## Extrai de uma base de dados um único registo que corresponde aos critérios especificados +DMAX = BDMÁX ## Devolve o valor máximo das entradas da base de dados seleccionadas +DMIN = BDMÍN ## Devolve o valor mínimo das entradas da base de dados seleccionadas +DPRODUCT = BDMULTIPL ## Multiplica os valores de um determinado campo de registos que correspondem aos critérios numa base de dados +DSTDEV = BDDESVPAD ## Calcula o desvio-padrão com base numa amostra de entradas da base de dados seleccionadas +DSTDEVP = BDDESVPADP ## Calcula o desvio-padrão com base na população total das entradas da base de dados seleccionadas +DSUM = BDSOMA ## Adiciona os números na coluna de campo dos registos de base de dados que correspondem aos critérios +DVAR = BDVAR ## Calcula a variância com base numa amostra das entradas de base de dados seleccionadas +DVARP = BDVARP ## Calcula a variância com base na população total das entradas de base de dados seleccionadas + + +## +## Date and time functions Funções de data e hora +## +DATE = DATA ## Devolve o número de série de uma determinada data +DATEVALUE = DATA.VALOR ## Converte uma data em forma de texto num número de série +DAY = DIA ## Converte um número de série num dia do mês +DAYS360 = DIAS360 ## Calcula o número de dias entre duas datas com base num ano com 360 dias +EDATE = DATAM ## Devolve um número de série de data que corresponde ao número de meses indicado antes ou depois da data de início +EOMONTH = FIMMÊS ## Devolve o número de série do último dia do mês antes ou depois de um número de meses especificado +HOUR = HORA ## Converte um número de série numa hora +MINUTE = MINUTO ## Converte um número de série num minuto +MONTH = MÊS ## Converte um número de série num mês +NETWORKDAYS = DIATRABALHOTOTAL ## Devolve o número total de dias úteis entre duas datas +NOW = AGORA ## Devolve o número de série da data e hora actuais +SECOND = SEGUNDO ## Converte um número de série num segundo +TIME = TEMPO ## Devolve o número de série de um determinado tempo +TIMEVALUE = VALOR.TEMPO ## Converte um tempo em forma de texto num número de série +TODAY = HOJE ## Devolve o número de série da data actual +WEEKDAY = DIA.SEMANA ## Converte um número de série num dia da semana +WEEKNUM = NÚMSEMANA ## Converte um número de série num número que representa o número da semana num determinado ano +WORKDAY = DIA.TRABALHO ## Devolve o número de série da data antes ou depois de um número de dias úteis especificado +YEAR = ANO ## Converte um número de série num ano +YEARFRAC = FRACÇÃOANO ## Devolve a fracção de ano que representa o número de dias inteiros entre a data_de_início e a data_de_fim + + +## +## Engineering functions Funções de engenharia +## +BESSELI = BESSELI ## Devolve a função de Bessel modificada In(x) +BESSELJ = BESSELJ ## Devolve a função de Bessel Jn(x) +BESSELK = BESSELK ## Devolve a função de Bessel modificada Kn(x) +BESSELY = BESSELY ## Devolve a função de Bessel Yn(x) +BIN2DEC = BINADEC ## Converte um número binário em decimal +BIN2HEX = BINAHEX ## Converte um número binário em hexadecimal +BIN2OCT = BINAOCT ## Converte um número binário em octal +COMPLEX = COMPLEXO ## Converte coeficientes reais e imaginários num número complexo +CONVERT = CONVERTER ## Converte um número de um sistema de medida noutro +DEC2BIN = DECABIN ## Converte um número decimal em binário +DEC2HEX = DECAHEX ## Converte um número decimal em hexadecimal +DEC2OCT = DECAOCT ## Converte um número decimal em octal +DELTA = DELTA ## Testa se dois valores são iguais +ERF = FUNCERRO ## Devolve a função de erro +ERFC = FUNCERROCOMPL ## Devolve a função de erro complementar +GESTEP = DEGRAU ## Testa se um número é maior do que um valor limite +HEX2BIN = HEXABIN ## Converte um número hexadecimal em binário +HEX2DEC = HEXADEC ## Converte um número hexadecimal em decimal +HEX2OCT = HEXAOCT ## Converte um número hexadecimal em octal +IMABS = IMABS ## Devolve o valor absoluto (módulo) de um número complexo +IMAGINARY = IMAGINÁRIO ## Devolve o coeficiente imaginário de um número complexo +IMARGUMENT = IMARG ## Devolve o argumento Teta, um ângulo expresso em radianos +IMCONJUGATE = IMCONJ ## Devolve o conjugado complexo de um número complexo +IMCOS = IMCOS ## Devolve o co-seno de um número complexo +IMDIV = IMDIV ## Devolve o quociente de dois números complexos +IMEXP = IMEXP ## Devolve o exponencial de um número complexo +IMLN = IMLN ## Devolve o logaritmo natural de um número complexo +IMLOG10 = IMLOG10 ## Devolve o logaritmo de base 10 de um número complexo +IMLOG2 = IMLOG2 ## Devolve o logaritmo de base 2 de um número complexo +IMPOWER = IMPOT ## Devolve um número complexo elevado a uma potência inteira +IMPRODUCT = IMPROD ## Devolve o produto de números complexos +IMREAL = IMREAL ## Devolve o coeficiente real de um número complexo +IMSIN = IMSENO ## Devolve o seno de um número complexo +IMSQRT = IMRAIZ ## Devolve a raiz quadrada de um número complexo +IMSUB = IMSUBTR ## Devolve a diferença entre dois números complexos +IMSUM = IMSOMA ## Devolve a soma de números complexos +OCT2BIN = OCTABIN ## Converte um número octal em binário +OCT2DEC = OCTADEC ## Converte um número octal em decimal +OCT2HEX = OCTAHEX ## Converte um número octal em hexadecimal + + +## +## Financial functions Funções financeiras +## +ACCRINT = JUROSACUM ## Devolve os juros acumulados de um título que paga juros periódicos +ACCRINTM = JUROSACUMV ## Devolve os juros acumulados de um título que paga juros no vencimento +AMORDEGRC = AMORDEGRC ## Devolve a depreciação correspondente a cada período contabilístico utilizando um coeficiente de depreciação +AMORLINC = AMORLINC ## Devolve a depreciação correspondente a cada período contabilístico +COUPDAYBS = CUPDIASINLIQ ## Devolve o número de dias entre o início do período do cupão e a data de regularização +COUPDAYS = CUPDIAS ## Devolve o número de dias no período do cupão que contém a data de regularização +COUPDAYSNC = CUPDIASPRÓX ## Devolve o número de dias entre a data de regularização e a data do cupão seguinte +COUPNCD = CUPDATAPRÓX ## Devolve a data do cupão seguinte após a data de regularização +COUPNUM = CUPNÚM ## Devolve o número de cupões a serem pagos entre a data de regularização e a data de vencimento +COUPPCD = CUPDATAANT ## Devolve a data do cupão anterior antes da data de regularização +CUMIPMT = PGTOJURACUM ## Devolve os juros cumulativos pagos entre dois períodos +CUMPRINC = PGTOCAPACUM ## Devolve o capital cumulativo pago a título de empréstimo entre dois períodos +DB = BD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas fixas +DDB = BDD ## Devolve a depreciação de um activo relativo a um período especificado utilizando o método das quotas degressivas duplas ou qualquer outro método especificado +DISC = DESC ## Devolve a taxa de desconto de um título +DOLLARDE = MOEDADEC ## Converte um preço em unidade monetária, expresso como uma fracção, num preço em unidade monetária, expresso como um número decimal +DOLLARFR = MOEDAFRA ## Converte um preço em unidade monetária, expresso como um número decimal, num preço em unidade monetária, expresso como uma fracção +DURATION = DURAÇÃO ## Devolve a duração anual de um título com pagamentos de juros periódicos +EFFECT = EFECTIVA ## Devolve a taxa de juros anual efectiva +FV = VF ## Devolve o valor futuro de um investimento +FVSCHEDULE = VFPLANO ## Devolve o valor futuro de um capital inicial após a aplicação de uma série de taxas de juro compostas +INTRATE = TAXAJUROS ## Devolve a taxa de juros de um título investido na totalidade +IPMT = IPGTO ## Devolve o pagamento dos juros de um investimento durante um determinado período +IRR = TIR ## Devolve a taxa de rentabilidade interna para uma série de fluxos monetários +ISPMT = É.PGTO ## Calcula os juros pagos durante um período específico de um investimento +MDURATION = MDURAÇÃO ## Devolve a duração modificada de Macauley de um título com um valor de paridade equivalente a € 100 +MIRR = MTIR ## Devolve a taxa interna de rentabilidade em que os fluxos monetários positivos e negativos são financiados com taxas diferentes +NOMINAL = NOMINAL ## Devolve a taxa de juros nominal anual +NPER = NPER ## Devolve o número de períodos de um investimento +NPV = VAL ## Devolve o valor actual líquido de um investimento com base numa série de fluxos monetários periódicos e numa taxa de desconto +ODDFPRICE = PREÇOPRIMINC ## Devolve o preço por € 100 do valor nominal de um título com um período inicial incompleto +ODDFYIELD = LUCROPRIMINC ## Devolve o lucro de um título com um período inicial incompleto +ODDLPRICE = PREÇOÚLTINC ## Devolve o preço por € 100 do valor nominal de um título com um período final incompleto +ODDLYIELD = LUCROÚLTINC ## Devolve o lucro de um título com um período final incompleto +PMT = PGTO ## Devolve o pagamento periódico de uma anuidade +PPMT = PPGTO ## Devolve o pagamento sobre o capital de um investimento num determinado período +PRICE = PREÇO ## Devolve o preço por € 100 do valor nominal de um título que paga juros periódicos +PRICEDISC = PREÇODESC ## Devolve o preço por € 100 do valor nominal de um título descontado +PRICEMAT = PREÇOVENC ## Devolve o preço por € 100 do valor nominal de um título que paga juros no vencimento +PV = VA ## Devolve o valor actual de um investimento +RATE = TAXA ## Devolve a taxa de juros por período de uma anuidade +RECEIVED = RECEBER ## Devolve o montante recebido no vencimento de um título investido na totalidade +SLN = AMORT ## Devolve uma depreciação linear de um activo durante um período +SYD = AMORTD ## Devolve a depreciação por algarismos da soma dos anos de um activo durante um período especificado +TBILLEQ = OTN ## Devolve o lucro de um título equivalente a uma Obrigação do Tesouro +TBILLPRICE = OTNVALOR ## Devolve o preço por € 100 de valor nominal de uma Obrigação do Tesouro +TBILLYIELD = OTNLUCRO ## Devolve o lucro de uma Obrigação do Tesouro +VDB = BDV ## Devolve a depreciação de um activo relativo a um período específico ou parcial utilizando um método de quotas degressivas +XIRR = XTIR ## Devolve a taxa interna de rentabilidade de um plano de fluxos monetários que não seja necessariamente periódica +XNPV = XVAL ## Devolve o valor actual líquido de um plano de fluxos monetários que não seja necessariamente periódico +YIELD = LUCRO ## Devolve o lucro de um título que paga juros periódicos +YIELDDISC = LUCRODESC ## Devolve o lucro anual de um título emitido abaixo do valor nominal, por exemplo, uma Obrigação do Tesouro +YIELDMAT = LUCROVENC ## Devolve o lucro anual de um título que paga juros na data de vencimento + + +## +## Information functions Funções de informação +## +CELL = CÉL ## Devolve informações sobre a formatação, localização ou conteúdo de uma célula +ERROR.TYPE = TIPO.ERRO ## Devolve um número correspondente a um tipo de erro +INFO = INFORMAÇÃO ## Devolve informações sobre o ambiente de funcionamento actual +ISBLANK = É.CÉL.VAZIA ## Devolve VERDADEIRO se o valor estiver em branco +ISERR = É.ERROS ## Devolve VERDADEIRO se o valor for um valor de erro diferente de #N/D +ISERROR = É.ERRO ## Devolve VERDADEIRO se o valor for um valor de erro +ISEVEN = ÉPAR ## Devolve VERDADEIRO se o número for par +ISLOGICAL = É.LÓGICO ## Devolve VERDADEIRO se o valor for lógico +ISNA = É.NÃO.DISP ## Devolve VERDADEIRO se o valor for o valor de erro #N/D +ISNONTEXT = É.NÃO.TEXTO ## Devolve VERDADEIRO se o valor não for texto +ISNUMBER = É.NÚM ## Devolve VERDADEIRO se o valor for um número +ISODD = ÉÍMPAR ## Devolve VERDADEIRO se o número for ímpar +ISREF = É.REF ## Devolve VERDADEIRO se o valor for uma referência +ISTEXT = É.TEXTO ## Devolve VERDADEIRO se o valor for texto +N = N ## Devolve um valor convertido num número +NA = NÃO.DISP ## Devolve o valor de erro #N/D +TYPE = TIPO ## Devolve um número que indica o tipo de dados de um valor + + +## +## Logical functions Funções lógicas +## +AND = E ## Devolve VERDADEIRO se todos os respectivos argumentos corresponderem a VERDADEIRO +FALSE = FALSO ## Devolve o valor lógico FALSO +IF = SE ## Especifica um teste lógico a ser executado +IFERROR = SE.ERRO ## Devolve um valor definido pelo utilizador se ocorrer um erro na fórmula, e devolve o resultado da fórmula se não ocorrer nenhum erro +NOT = NÃO ## Inverte a lógica do respectivo argumento +OR = OU ## Devolve VERDADEIRO se qualquer argumento for VERDADEIRO +TRUE = VERDADEIRO ## Devolve o valor lógico VERDADEIRO + + +## +## Lookup and reference functions Funções de pesquisa e referência +## +ADDRESS = ENDEREÇO ## Devolve uma referência a uma única célula numa folha de cálculo como texto +AREAS = ÁREAS ## Devolve o número de áreas numa referência +CHOOSE = SELECCIONAR ## Selecciona um valor a partir de uma lista de valores +COLUMN = COL ## Devolve o número da coluna de uma referência +COLUMNS = COLS ## Devolve o número de colunas numa referência +HLOOKUP = PROCH ## Procura na linha superior de uma matriz e devolve o valor da célula indicada +HYPERLINK = HIPERLIGAÇÃO ## Cria um atalho ou hiperligação que abre um documento armazenado num servidor de rede, numa intranet ou na Internet +INDEX = ÍNDICE ## Utiliza um índice para escolher um valor de uma referência ou de uma matriz +INDIRECT = INDIRECTO ## Devolve uma referência indicada por um valor de texto +LOOKUP = PROC ## Procura valores num vector ou numa matriz +MATCH = CORRESP ## Procura valores numa referência ou numa matriz +OFFSET = DESLOCAMENTO ## Devolve o deslocamento de referência de uma determinada referência +ROW = LIN ## Devolve o número da linha de uma referência +ROWS = LINS ## Devolve o número de linhas numa referência +RTD = RTD ## Obtém dados em tempo real a partir de um programa que suporte automatização COM (automatização: modo de trabalhar com objectos de uma aplicação a partir de outra aplicação ou ferramenta de desenvolvimento. Anteriormente conhecida como automatização OLE, a automatização é uma norma da indústria de software e uma funcionalidade COM (Component Object Model).) +TRANSPOSE = TRANSPOR ## Devolve a transposição de uma matriz +VLOOKUP = PROCV ## Procura na primeira coluna de uma matriz e percorre a linha para devolver o valor de uma célula + + +## +## Math and trigonometry functions Funções matemáticas e trigonométricas +## +ABS = ABS ## Devolve o valor absoluto de um número +ACOS = ACOS ## Devolve o arco de co-seno de um número +ACOSH = ACOSH ## Devolve o co-seno hiperbólico inverso de um número +ASIN = ASEN ## Devolve o arco de seno de um número +ASINH = ASENH ## Devolve o seno hiperbólico inverso de um número +ATAN = ATAN ## Devolve o arco de tangente de um número +ATAN2 = ATAN2 ## Devolve o arco de tangente das coordenadas x e y +ATANH = ATANH ## Devolve a tangente hiperbólica inversa de um número +CEILING = ARRED.EXCESSO ## Arredonda um número para o número inteiro mais próximo ou para o múltiplo de significância mais próximo +COMBIN = COMBIN ## Devolve o número de combinações de um determinado número de objectos +COS = COS ## Devolve o co-seno de um número +COSH = COSH ## Devolve o co-seno hiperbólico de um número +DEGREES = GRAUS ## Converte radianos em graus +EVEN = PAR ## Arredonda um número por excesso para o número inteiro mais próximo +EXP = EXP ## Devolve e elevado à potência de um determinado número +FACT = FACTORIAL ## Devolve o factorial de um número +FACTDOUBLE = FACTDUPLO ## Devolve o factorial duplo de um número +FLOOR = ARRED.DEFEITO ## Arredonda um número por defeito até zero +GCD = MDC ## Devolve o maior divisor comum +INT = INT ## Arredonda um número por defeito para o número inteiro mais próximo +LCM = MMC ## Devolve o mínimo múltiplo comum +LN = LN ## Devolve o logaritmo natural de um número +LOG = LOG ## Devolve o logaritmo de um número com uma base especificada +LOG10 = LOG10 ## Devolve o logaritmo de base 10 de um número +MDETERM = MATRIZ.DETERM ## Devolve o determinante matricial de uma matriz +MINVERSE = MATRIZ.INVERSA ## Devolve o inverso matricial de uma matriz +MMULT = MATRIZ.MULT ## Devolve o produto matricial de duas matrizes +MOD = RESTO ## Devolve o resto da divisão +MROUND = MARRED ## Devolve um número arredondado para o múltiplo pretendido +MULTINOMIAL = POLINOMIAL ## Devolve o polinomial de um conjunto de números +ODD = ÍMPAR ## Arredonda por excesso um número para o número inteiro ímpar mais próximo +PI = PI ## Devolve o valor de pi +POWER = POTÊNCIA ## Devolve o resultado de um número elevado a uma potência +PRODUCT = PRODUTO ## Multiplica os respectivos argumentos +QUOTIENT = QUOCIENTE ## Devolve a parte inteira de uma divisão +RADIANS = RADIANOS ## Converte graus em radianos +RAND = ALEATÓRIO ## Devolve um número aleatório entre 0 e 1 +RANDBETWEEN = ALEATÓRIOENTRE ## Devolve um número aleatório entre os números especificados +ROMAN = ROMANO ## Converte um número árabe em romano, como texto +ROUND = ARRED ## Arredonda um número para um número de dígitos especificado +ROUNDDOWN = ARRED.PARA.BAIXO ## Arredonda um número por defeito até zero +ROUNDUP = ARRED.PARA.CIMA ## Arredonda um número por excesso, afastando-o de zero +SERIESSUM = SOMASÉRIE ## Devolve a soma de uma série de potências baseada na fórmula +SIGN = SINAL ## Devolve o sinal de um número +SIN = SEN ## Devolve o seno de um determinado ângulo +SINH = SENH ## Devolve o seno hiperbólico de um número +SQRT = RAIZQ ## Devolve uma raiz quadrada positiva +SQRTPI = RAIZPI ## Devolve a raiz quadrada de (núm * pi) +SUBTOTAL = SUBTOTAL ## Devolve um subtotal numa lista ou base de dados +SUM = SOMA ## Adiciona os respectivos argumentos +SUMIF = SOMA.SE ## Adiciona as células especificadas por um determinado critério +SUMIFS = SOMA.SE.S ## Adiciona as células num intervalo que cumpre vários critérios +SUMPRODUCT = SOMARPRODUTO ## Devolve a soma dos produtos de componentes de matrizes correspondentes +SUMSQ = SOMARQUAD ## Devolve a soma dos quadrados dos argumentos +SUMX2MY2 = SOMAX2DY2 ## Devolve a soma da diferença dos quadrados dos valores correspondentes em duas matrizes +SUMX2PY2 = SOMAX2SY2 ## Devolve a soma da soma dos quadrados dos valores correspondentes em duas matrizes +SUMXMY2 = SOMAXMY2 ## Devolve a soma dos quadrados da diferença dos valores correspondentes em duas matrizes +TAN = TAN ## Devolve a tangente de um número +TANH = TANH ## Devolve a tangente hiperbólica de um número +TRUNC = TRUNCAR ## Trunca um número para um número inteiro + + +## +## Statistical functions Funções estatísticas +## +AVEDEV = DESV.MÉDIO ## Devolve a média aritmética dos desvios absolutos à média dos pontos de dados +AVERAGE = MÉDIA ## Devolve a média dos respectivos argumentos +AVERAGEA = MÉDIAA ## Devolve uma média dos respectivos argumentos, incluindo números, texto e valores lógicos +AVERAGEIF = MÉDIA.SE ## Devolve a média aritmética de todas as células num intervalo que cumprem determinado critério +AVERAGEIFS = MÉDIA.SE.S ## Devolve a média aritmética de todas as células que cumprem múltiplos critérios +BETADIST = DISTBETA ## Devolve a função de distribuição cumulativa beta +BETAINV = BETA.ACUM.INV ## Devolve o inverso da função de distribuição cumulativa relativamente a uma distribuição beta específica +BINOMDIST = DISTRBINOM ## Devolve a probabilidade de distribuição binomial de termo individual +CHIDIST = DIST.CHI ## Devolve a probabilidade unicaudal da distribuição qui-quadrada +CHIINV = INV.CHI ## Devolve o inverso da probabilidade unicaudal da distribuição qui-quadrada +CHITEST = TESTE.CHI ## Devolve o teste para independência +CONFIDENCE = INT.CONFIANÇA ## Devolve o intervalo de confiança correspondente a uma média de população +CORREL = CORREL ## Devolve o coeficiente de correlação entre dois conjuntos de dados +COUNT = CONTAR ## Conta os números que existem na lista de argumentos +COUNTA = CONTAR.VAL ## Conta os valores que existem na lista de argumentos +COUNTBLANK = CONTAR.VAZIO ## Conta o número de células em branco num intervalo +COUNTIF = CONTAR.SE ## Calcula o número de células num intervalo que corresponde aos critérios determinados +COUNTIFS = CONTAR.SE.S ## Conta o número de células num intervalo que cumprem múltiplos critérios +COVAR = COVAR ## Devolve a covariância, que é a média dos produtos de desvios de pares +CRITBINOM = CRIT.BINOM ## Devolve o menor valor em que a distribuição binomial cumulativa é inferior ou igual a um valor de critério +DEVSQ = DESVQ ## Devolve a soma dos quadrados dos desvios +EXPONDIST = DISTEXPON ## Devolve a distribuição exponencial +FDIST = DISTF ## Devolve a distribuição da probabilidade F +FINV = INVF ## Devolve o inverso da distribuição da probabilidade F +FISHER = FISHER ## Devolve a transformação Fisher +FISHERINV = FISHERINV ## Devolve o inverso da transformação Fisher +FORECAST = PREVISÃO ## Devolve um valor ao longo de uma tendência linear +FREQUENCY = FREQUÊNCIA ## Devolve uma distribuição de frequência como uma matriz vertical +FTEST = TESTEF ## Devolve o resultado de um teste F +GAMMADIST = DISTGAMA ## Devolve a distribuição gama +GAMMAINV = INVGAMA ## Devolve o inverso da distribuição gama cumulativa +GAMMALN = LNGAMA ## Devolve o logaritmo natural da função gama, Γ(x) +GEOMEAN = MÉDIA.GEOMÉTRICA ## Devolve a média geométrica +GROWTH = CRESCIMENTO ## Devolve valores ao longo de uma tendência exponencial +HARMEAN = MÉDIA.HARMÓNICA ## Devolve a média harmónica +HYPGEOMDIST = DIST.HIPERGEOM ## Devolve a distribuição hipergeométrica +INTERCEPT = INTERCEPTAR ## Devolve a intercepção da linha de regressão linear +KURT = CURT ## Devolve a curtose de um conjunto de dados +LARGE = MAIOR ## Devolve o maior valor k-ésimo de um conjunto de dados +LINEST = PROJ.LIN ## Devolve os parâmetros de uma tendência linear +LOGEST = PROJ.LOG ## Devolve os parâmetros de uma tendência exponencial +LOGINV = INVLOG ## Devolve o inverso da distribuição normal logarítmica +LOGNORMDIST = DIST.NORMALLOG ## Devolve a distribuição normal logarítmica cumulativa +MAX = MÁXIMO ## Devolve o valor máximo numa lista de argumentos +MAXA = MÁXIMOA ## Devolve o valor máximo numa lista de argumentos, incluindo números, texto e valores lógicos +MEDIAN = MED ## Devolve a mediana dos números indicados +MIN = MÍNIMO ## Devolve o valor mínimo numa lista de argumentos +MINA = MÍNIMOA ## Devolve o valor mínimo numa lista de argumentos, incluindo números, texto e valores lógicos +MODE = MODA ## Devolve o valor mais comum num conjunto de dados +NEGBINOMDIST = DIST.BIN.NEG ## Devolve a distribuição binominal negativa +NORMDIST = DIST.NORM ## Devolve a distribuição cumulativa normal +NORMINV = INV.NORM ## Devolve o inverso da distribuição cumulativa normal +NORMSDIST = DIST.NORMP ## Devolve a distribuição cumulativa normal padrão +NORMSINV = INV.NORMP ## Devolve o inverso da distribuição cumulativa normal padrão +PEARSON = PEARSON ## Devolve o coeficiente de correlação momento/produto de Pearson +PERCENTILE = PERCENTIL ## Devolve o k-ésimo percentil de valores num intervalo +PERCENTRANK = ORDEM.PERCENTUAL ## Devolve a ordem percentual de um valor num conjunto de dados +PERMUT = PERMUTAR ## Devolve o número de permutações de um determinado número de objectos +POISSON = POISSON ## Devolve a distribuição de Poisson +PROB = PROB ## Devolve a probabilidade dos valores num intervalo se encontrarem entre dois limites +QUARTILE = QUARTIL ## Devolve o quartil de um conjunto de dados +RANK = ORDEM ## Devolve a ordem de um número numa lista numérica +RSQ = RQUAD ## Devolve o quadrado do coeficiente de correlação momento/produto de Pearson +SKEW = DISTORÇÃO ## Devolve a distorção de uma distribuição +SLOPE = DECLIVE ## Devolve o declive da linha de regressão linear +SMALL = MENOR ## Devolve o menor valor de k-ésimo de um conjunto de dados +STANDARDIZE = NORMALIZAR ## Devolve um valor normalizado +STDEV = DESVPAD ## Calcula o desvio-padrão com base numa amostra +STDEVA = DESVPADA ## Calcula o desvio-padrão com base numa amostra, incluindo números, texto e valores lógicos +STDEVP = DESVPADP ## Calcula o desvio-padrão com base na população total +STDEVPA = DESVPADPA ## Calcula o desvio-padrão com base na população total, incluindo números, texto e valores lógicos +STEYX = EPADYX ## Devolve o erro-padrão do valor de y previsto para cada x na regressão +TDIST = DISTT ## Devolve a distribuição t de Student +TINV = INVT ## Devolve o inverso da distribuição t de Student +TREND = TENDÊNCIA ## Devolve valores ao longo de uma tendência linear +TRIMMEAN = MÉDIA.INTERNA ## Devolve a média do interior de um conjunto de dados +TTEST = TESTET ## Devolve a probabilidade associada ao teste t de Student +VAR = VAR ## Calcula a variância com base numa amostra +VARA = VARA ## Calcula a variância com base numa amostra, incluindo números, texto e valores lógicos +VARP = VARP ## Calcula a variância com base na população total +VARPA = VARPA ## Calcula a variância com base na população total, incluindo números, texto e valores lógicos +WEIBULL = WEIBULL ## Devolve a distribuição Weibull +ZTEST = TESTEZ ## Devolve o valor de probabilidade unicaudal de um teste-z + + +## +## Text functions Funções de texto +## +ASC = ASC ## Altera letras ou katakana de largura total (byte duplo) numa cadeia de caracteres para caracteres de largura média (byte único) +BAHTTEXT = TEXTO.BAHT ## Converte um número em texto, utilizando o formato monetário ß (baht) +CHAR = CARÁCT ## Devolve o carácter especificado pelo número de código +CLEAN = LIMPAR ## Remove do texto todos os caracteres não imprimíveis +CODE = CÓDIGO ## Devolve um código numérico correspondente ao primeiro carácter numa cadeia de texto +CONCATENATE = CONCATENAR ## Agrupa vários itens de texto num único item de texto +DOLLAR = MOEDA ## Converte um número em texto, utilizando o formato monetário € (Euro) +EXACT = EXACTO ## Verifica se dois valores de texto são idênticos +FIND = LOCALIZAR ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) +FINDB = LOCALIZARB ## Localiza um valor de texto dentro de outro (sensível às maiúsculas e minúsculas) +FIXED = FIXA ## Formata um número como texto com um número fixo de decimais +JIS = JIS ## Altera letras ou katakana de largura média (byte único) numa cadeia de caracteres para caracteres de largura total (byte duplo) +LEFT = ESQUERDA ## Devolve os caracteres mais à esquerda de um valor de texto +LEFTB = ESQUERDAB ## Devolve os caracteres mais à esquerda de um valor de texto +LEN = NÚM.CARACT ## Devolve o número de caracteres de uma cadeia de texto +LENB = NÚM.CARACTB ## Devolve o número de caracteres de uma cadeia de texto +LOWER = MINÚSCULAS ## Converte o texto em minúsculas +MID = SEG.TEXTO ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada +MIDB = SEG.TEXTOB ## Devolve um número específico de caracteres de uma cadeia de texto, a partir da posição especificada +PHONETIC = FONÉTICA ## Retira os caracteres fonéticos (furigana) de uma cadeia de texto +PROPER = INICIAL.MAIÚSCULA ## Coloca em maiúsculas a primeira letra de cada palavra de um valor de texto +REPLACE = SUBSTITUIR ## Substitui caracteres no texto +REPLACEB = SUBSTITUIRB ## Substitui caracteres no texto +REPT = REPETIR ## Repete texto um determinado número de vezes +RIGHT = DIREITA ## Devolve os caracteres mais à direita de um valor de texto +RIGHTB = DIREITAB ## Devolve os caracteres mais à direita de um valor de texto +SEARCH = PROCURAR ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) +SEARCHB = PROCURARB ## Localiza um valor de texto dentro de outro (não sensível a maiúsculas e minúsculas) +SUBSTITUTE = SUBST ## Substitui texto novo por texto antigo numa cadeia de texto +T = T ## Converte os respectivos argumentos em texto +TEXT = TEXTO ## Formata um número e converte-o em texto +TRIM = COMPACTAR ## Remove espaços do texto +UPPER = MAIÚSCULAS ## Converte texto em maiúsculas +VALUE = VALOR ## Converte um argumento de texto num número diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/config new file mode 100644 index 00000000..56e45bfd --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = р + + +## +## Excel Error Codes (For future use) +## +NULL = #ПУСТО! +DIV0 = #ДЕЛ/0! +VALUE = #ЗНАЧ! +REF = #ССЫЛ! +NAME = #ИМЯ? +NUM = #ЧИСЛО! +NA = #Н/Д diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/functions new file mode 100644 index 00000000..5ff6d4fb --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/ru/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from information provided by web-junior (http://www.web-junior.net/) +## +## + + +## +## Add-in and Automation functions Функции надстроек и автоматизации +## +GETPIVOTDATA = ПОЛУЧИТЬ.ДАННЫЕ.СВОДНОЙ.ТАБЛИЦЫ ## Возвращает данные, хранящиеся в отчете сводной таблицы. + + +## +## Cube functions Функции Куб +## +CUBEKPIMEMBER = КУБЭЛЕМЕНТКИП ## Возвращает свойство ключевого индикатора производительности «(КИП)» и отображает имя «КИП» в ячейке. «КИП» представляет собой количественную величину, такую как ежемесячная валовая прибыль или ежеквартальная текучесть кадров, используемой для контроля эффективности работы организации. +CUBEMEMBER = КУБЭЛЕМЕНТ ## Возвращает элемент или кортеж из куба. Используется для проверки существования элемента или кортежа в кубе. +CUBEMEMBERPROPERTY = КУБСВОЙСТВОЭЛЕМЕНТА ## Возвращает значение свойства элемента из куба. Используется для проверки существования имени элемента в кубе и возвращает указанное свойство для этого элемента. +CUBERANKEDMEMBER = КУБПОРЭЛЕМЕНТ ## Возвращает n-ый или ранжированный элемент в множество. Используется для возвращения одного или нескольких элементов в множество, например, лучшего продавца или 10 лучших студентов. +CUBESET = КУБМНОЖ ## Определяет вычислительное множество элементов или кортежей, отправляя на сервер выражение, которое создает множество, а затем возвращает его в Microsoft Office Excel. +CUBESETCOUNT = КУБЧИСЛОЭЛМНОЖ ## Возвращает число элементов множества. +CUBEVALUE = КУБЗНАЧЕНИЕ ## Возвращает обобщенное значение из куба. + + +## +## Database functions Функции для работы с базами данных +## +DAVERAGE = ДСРЗНАЧ ## Возвращает среднее значение выбранных записей базы данных. +DCOUNT = БСЧЁТ ## Подсчитывает количество числовых ячеек в базе данных. +DCOUNTA = БСЧЁТА ## Подсчитывает количество непустых ячеек в базе данных. +DGET = БИЗВЛЕЧЬ ## Извлекает из базы данных одну запись, удовлетворяющую заданному условию. +DMAX = ДМАКС ## Возвращает максимальное значение среди выделенных записей базы данных. +DMIN = ДМИН ## Возвращает минимальное значение среди выделенных записей базы данных. +DPRODUCT = БДПРОИЗВЕД ## Перемножает значения определенного поля в записях базы данных, удовлетворяющих условию. +DSTDEV = ДСТАНДОТКЛ ## Оценивает стандартное отклонение по выборке для выделенных записей базы данных. +DSTDEVP = ДСТАНДОТКЛП ## Вычисляет стандартное отклонение по генеральной совокупности для выделенных записей базы данных +DSUM = БДСУММ ## Суммирует числа в поле для записей базы данных, удовлетворяющих условию. +DVAR = БДДИСП ## Оценивает дисперсию по выборке из выделенных записей базы данных +DVARP = БДДИСПП ## Вычисляет дисперсию по генеральной совокупности для выделенных записей базы данных + + +## +## Date and time functions Функции даты и времени +## +DATE = ДАТА ## Возвращает заданную дату в числовом формате. +DATEVALUE = ДАТАЗНАЧ ## Преобразует дату из текстового формата в числовой формат. +DAY = ДЕНЬ ## Преобразует дату в числовом формате в день месяца. +DAYS360 = ДНЕЙ360 ## Вычисляет количество дней между двумя датами на основе 360-дневного года. +EDATE = ДАТАМЕС ## Возвращает дату в числовом формате, отстоящую на заданное число месяцев вперед или назад от начальной даты. +EOMONTH = КОНМЕСЯЦА ## Возвращает дату в числовом формате для последнего дня месяца, отстоящего вперед или назад на заданное число месяцев. +HOUR = ЧАС ## Преобразует дату в числовом формате в часы. +MINUTE = МИНУТЫ ## Преобразует дату в числовом формате в минуты. +MONTH = МЕСЯЦ ## Преобразует дату в числовом формате в месяцы. +NETWORKDAYS = ЧИСТРАБДНИ ## Возвращает количество рабочих дней между двумя датами. +NOW = ТДАТА ## Возвращает текущую дату и время в числовом формате. +SECOND = СЕКУНДЫ ## Преобразует дату в числовом формате в секунды. +TIME = ВРЕМЯ ## Возвращает заданное время в числовом формате. +TIMEVALUE = ВРЕМЗНАЧ ## Преобразует время из текстового формата в числовой формат. +TODAY = СЕГОДНЯ ## Возвращает текущую дату в числовом формате. +WEEKDAY = ДЕНЬНЕД ## Преобразует дату в числовом формате в день недели. +WEEKNUM = НОМНЕДЕЛИ ## Преобразует числовое представление в число, которое указывает, на какую неделю года приходится указанная дата. +WORKDAY = РАБДЕНЬ ## Возвращает дату в числовом формате, отстоящую вперед или назад на заданное количество рабочих дней. +YEAR = ГОД ## Преобразует дату в числовом формате в год. +YEARFRAC = ДОЛЯГОДА ## Возвращает долю года, которую составляет количество дней между начальной и конечной датами. + + +## +## Engineering functions Инженерные функции +## +BESSELI = БЕССЕЛЬ.I ## Возвращает модифицированную функцию Бесселя In(x). +BESSELJ = БЕССЕЛЬ.J ## Возвращает функцию Бесселя Jn(x). +BESSELK = БЕССЕЛЬ.K ## Возвращает модифицированную функцию Бесселя Kn(x). +BESSELY = БЕССЕЛЬ.Y ## Возвращает функцию Бесселя Yn(x). +BIN2DEC = ДВ.В.ДЕС ## Преобразует двоичное число в десятичное. +BIN2HEX = ДВ.В.ШЕСТН ## Преобразует двоичное число в шестнадцатеричное. +BIN2OCT = ДВ.В.ВОСЬМ ## Преобразует двоичное число в восьмеричное. +COMPLEX = КОМПЛЕКСН ## Преобразует коэффициенты при вещественной и мнимой частях комплексного числа в комплексное число. +CONVERT = ПРЕОБР ## Преобразует число из одной системы единиц измерения в другую. +DEC2BIN = ДЕС.В.ДВ ## Преобразует десятичное число в двоичное. +DEC2HEX = ДЕС.В.ШЕСТН ## Преобразует десятичное число в шестнадцатеричное. +DEC2OCT = ДЕС.В.ВОСЬМ ## Преобразует десятичное число в восьмеричное. +DELTA = ДЕЛЬТА ## Проверяет равенство двух значений. +ERF = ФОШ ## Возвращает функцию ошибки. +ERFC = ДФОШ ## Возвращает дополнительную функцию ошибки. +GESTEP = ПОРОГ ## Проверяет, не превышает ли данное число порогового значения. +HEX2BIN = ШЕСТН.В.ДВ ## Преобразует шестнадцатеричное число в двоичное. +HEX2DEC = ШЕСТН.В.ДЕС ## Преобразует шестнадцатеричное число в десятичное. +HEX2OCT = ШЕСТН.В.ВОСЬМ ## Преобразует шестнадцатеричное число в восьмеричное. +IMABS = МНИМ.ABS ## Возвращает абсолютную величину (модуль) комплексного числа. +IMAGINARY = МНИМ.ЧАСТЬ ## Возвращает коэффициент при мнимой части комплексного числа. +IMARGUMENT = МНИМ.АРГУМЕНТ ## Возвращает значение аргумента комплексного числа (тета) — угол, выраженный в радианах. +IMCONJUGATE = МНИМ.СОПРЯЖ ## Возвращает комплексно-сопряженное комплексное число. +IMCOS = МНИМ.COS ## Возвращает косинус комплексного числа. +IMDIV = МНИМ.ДЕЛ ## Возвращает частное от деления двух комплексных чисел. +IMEXP = МНИМ.EXP ## Возвращает экспоненту комплексного числа. +IMLN = МНИМ.LN ## Возвращает натуральный логарифм комплексного числа. +IMLOG10 = МНИМ.LOG10 ## Возвращает обычный (десятичный) логарифм комплексного числа. +IMLOG2 = МНИМ.LOG2 ## Возвращает двоичный логарифм комплексного числа. +IMPOWER = МНИМ.СТЕПЕНЬ ## Возвращает комплексное число, возведенное в целую степень. +IMPRODUCT = МНИМ.ПРОИЗВЕД ## Возвращает произведение от 2 до 29 комплексных чисел. +IMREAL = МНИМ.ВЕЩ ## Возвращает коэффициент при вещественной части комплексного числа. +IMSIN = МНИМ.SIN ## Возвращает синус комплексного числа. +IMSQRT = МНИМ.КОРЕНЬ ## Возвращает значение квадратного корня из комплексного числа. +IMSUB = МНИМ.РАЗН ## Возвращает разность двух комплексных чисел. +IMSUM = МНИМ.СУММ ## Возвращает сумму комплексных чисел. +OCT2BIN = ВОСЬМ.В.ДВ ## Преобразует восьмеричное число в двоичное. +OCT2DEC = ВОСЬМ.В.ДЕС ## Преобразует восьмеричное число в десятичное. +OCT2HEX = ВОСЬМ.В.ШЕСТН ## Преобразует восьмеричное число в шестнадцатеричное. + + +## +## Financial functions Финансовые функции +## +ACCRINT = НАКОПДОХОД ## Возвращает накопленный процент по ценным бумагам с периодической выплатой процентов. +ACCRINTM = НАКОПДОХОДПОГАШ ## Возвращает накопленный процент по ценным бумагам, проценты по которым выплачиваются в срок погашения. +AMORDEGRC = АМОРУМ ## Возвращает величину амортизации для каждого периода, используя коэффициент амортизации. +AMORLINC = АМОРУВ ## Возвращает величину амортизации для каждого периода. +COUPDAYBS = ДНЕЙКУПОНДО ## Возвращает количество дней от начала действия купона до даты соглашения. +COUPDAYS = ДНЕЙКУПОН ## Возвращает число дней в периоде купона, содержащем дату соглашения. +COUPDAYSNC = ДНЕЙКУПОНПОСЛЕ ## Возвращает число дней от даты соглашения до срока следующего купона. +COUPNCD = ДАТАКУПОНПОСЛЕ ## Возвращает следующую дату купона после даты соглашения. +COUPNUM = ЧИСЛКУПОН ## Возвращает количество купонов, которые могут быть оплачены между датой соглашения и сроком вступления в силу. +COUPPCD = ДАТАКУПОНДО ## Возвращает предыдущую дату купона перед датой соглашения. +CUMIPMT = ОБЩПЛАТ ## Возвращает общую выплату, произведенную между двумя периодическими выплатами. +CUMPRINC = ОБЩДОХОД ## Возвращает общую выплату по займу между двумя периодами. +DB = ФУО ## Возвращает величину амортизации актива для заданного периода, рассчитанную методом фиксированного уменьшения остатка. +DDB = ДДОБ ## Возвращает величину амортизации актива за данный период, используя метод двойного уменьшения остатка или иной явно указанный метод. +DISC = СКИДКА ## Возвращает норму скидки для ценных бумаг. +DOLLARDE = РУБЛЬ.ДЕС ## Преобразует цену в рублях, выраженную в виде дроби, в цену в рублях, выраженную десятичным числом. +DOLLARFR = РУБЛЬ.ДРОБЬ ## Преобразует цену в рублях, выраженную десятичным числом, в цену в рублях, выраженную в виде дроби. +DURATION = ДЛИТ ## Возвращает ежегодную продолжительность действия ценных бумаг с периодическими выплатами по процентам. +EFFECT = ЭФФЕКТ ## Возвращает действующие ежегодные процентные ставки. +FV = БС ## Возвращает будущую стоимость инвестиции. +FVSCHEDULE = БЗРАСПИС ## Возвращает будущую стоимость первоначальной основной суммы после начисления ряда сложных процентов. +INTRATE = ИНОРМА ## Возвращает процентную ставку для полностью инвестированных ценных бумаг. +IPMT = ПРПЛТ ## Возвращает величину выплаты прибыли на вложения за данный период. +IRR = ВСД ## Возвращает внутреннюю ставку доходности для ряда потоков денежных средств. +ISPMT = ПРОЦПЛАТ ## Вычисляет выплаты за указанный период инвестиции. +MDURATION = МДЛИТ ## Возвращает модифицированную длительность Маколея для ценных бумаг с предполагаемой номинальной стоимостью 100 рублей. +MIRR = МВСД ## Возвращает внутреннюю ставку доходности, при которой положительные и отрицательные денежные потоки имеют разные значения ставки. +NOMINAL = НОМИНАЛ ## Возвращает номинальную годовую процентную ставку. +NPER = КПЕР ## Возвращает общее количество периодов выплаты для данного вклада. +NPV = ЧПС ## Возвращает чистую приведенную стоимость инвестиции, основанной на серии периодических денежных потоков и ставке дисконтирования. +ODDFPRICE = ЦЕНАПЕРВНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным первым периодом. +ODDFYIELD = ДОХОДПЕРВНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным первым периодом. +ODDLPRICE = ЦЕНАПОСЛНЕРЕГ ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг с нерегулярным последним периодом. +ODDLYIELD = ДОХОДПОСЛНЕРЕГ ## Возвращает доход по ценным бумагам с нерегулярным последним периодом. +PMT = ПЛТ ## Возвращает величину выплаты за один период аннуитета. +PPMT = ОСПЛТ ## Возвращает величину выплат в погашение основной суммы по инвестиции за заданный период. +PRICE = ЦЕНА ## Возвращает цену за 100 рублей нарицательной стоимости ценных бумаг, по которым производится периодическая выплата процентов. +PRICEDISC = ЦЕНАСКИДКА ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, на которые сделана скидка. +PRICEMAT = ЦЕНАПОГАШ ## Возвращает цену за 100 рублей номинальной стоимости ценных бумаг, проценты по которым выплачиваются в срок погашения. +PV = ПС ## Возвращает приведенную (к текущему моменту) стоимость инвестиции. +RATE = СТАВКА ## Возвращает процентную ставку по аннуитету за один период. +RECEIVED = ПОЛУЧЕНО ## Возвращает сумму, полученную к сроку погашения полностью обеспеченных ценных бумаг. +SLN = АПЛ ## Возвращает величину линейной амортизации актива за один период. +SYD = АСЧ ## Возвращает величину амортизации актива за данный период, рассчитанную методом суммы годовых чисел. +TBILLEQ = РАВНОКЧЕК ## Возвращает эквивалентный облигации доход по казначейскому чеку. +TBILLPRICE = ЦЕНАКЧЕК ## Возвращает цену за 100 рублей нарицательной стоимости для казначейского чека. +TBILLYIELD = ДОХОДКЧЕК ## Возвращает доход по казначейскому чеку. +VDB = ПУО ## Возвращает величину амортизации актива для указанного или частичного периода при использовании метода сокращающегося баланса. +XIRR = ЧИСТВНДОХ ## Возвращает внутреннюю ставку доходности для графика денежных потоков, которые не обязательно носят периодический характер. +XNPV = ЧИСТНЗ ## Возвращает чистую приведенную стоимость для денежных потоков, которые не обязательно являются периодическими. +YIELD = ДОХОД ## Возвращает доход от ценных бумаг, по которым производятся периодические выплаты процентов. +YIELDDISC = ДОХОДСКИДКА ## Возвращает годовой доход по ценным бумагам, на которые сделана скидка (пример — казначейские чеки). +YIELDMAT = ДОХОДПОГАШ ## Возвращает годовой доход от ценных бумаг, проценты по которым выплачиваются в срок погашения. + + +## +## Information functions Информационные функции +## +CELL = ЯЧЕЙКА ## Возвращает информацию о формате, расположении или содержимом ячейки. +ERROR.TYPE = ТИП.ОШИБКИ ## Возвращает числовой код, соответствующий типу ошибки. +INFO = ИНФОРМ ## Возвращает информацию о текущей операционной среде. +ISBLANK = ЕПУСТО ## Возвращает значение ИСТИНА, если аргумент является ссылкой на пустую ячейку. +ISERR = ЕОШ ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки, кроме #Н/Д. +ISERROR = ЕОШИБКА ## Возвращает значение ИСТИНА, если аргумент ссылается на любое значение ошибки. +ISEVEN = ЕЧЁТН ## Возвращает значение ИСТИНА, если значение аргумента является четным числом. +ISLOGICAL = ЕЛОГИЧ ## Возвращает значение ИСТИНА, если аргумент ссылается на логическое значение. +ISNA = ЕНД ## Возвращает значение ИСТИНА, если аргумент ссылается на значение ошибки #Н/Д. +ISNONTEXT = ЕНЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента не является текстом. +ISNUMBER = ЕЧИСЛО ## Возвращает значение ИСТИНА, если аргумент ссылается на число. +ISODD = ЕНЕЧЁТ ## Возвращает значение ИСТИНА, если значение аргумента является нечетным числом. +ISREF = ЕССЫЛКА ## Возвращает значение ИСТИНА, если значение аргумента является ссылкой. +ISTEXT = ЕТЕКСТ ## Возвращает значение ИСТИНА, если значение аргумента является текстом. +N = Ч ## Возвращает значение, преобразованное в число. +NA = НД ## Возвращает значение ошибки #Н/Д. +TYPE = ТИП ## Возвращает число, обозначающее тип данных значения. + + +## +## Logical functions Логические функции +## +AND = И ## Renvoie VRAI si tous ses arguments sont VRAI. +FALSE = ЛОЖЬ ## Возвращает логическое значение ЛОЖЬ. +IF = ЕСЛИ ## Выполняет проверку условия. +IFERROR = ЕСЛИОШИБКА ## Возвращает введённое значение, если вычисление по формуле вызывает ошибку; в противном случае функция возвращает результат вычисления. +NOT = НЕ ## Меняет логическое значение своего аргумента на противоположное. +OR = ИЛИ ## Возвращает значение ИСТИНА, если хотя бы один аргумент имеет значение ИСТИНА. +TRUE = ИСТИНА ## Возвращает логическое значение ИСТИНА. + + +## +## Lookup and reference functions Функции ссылки и поиска +## +ADDRESS = АДРЕС ## Возвращает ссылку на отдельную ячейку листа в виде текста. +AREAS = ОБЛАСТИ ## Возвращает количество областей в ссылке. +CHOOSE = ВЫБОР ## Выбирает значение из списка значений по индексу. +COLUMN = СТОЛБЕЦ ## Возвращает номер столбца, на который указывает ссылка. +COLUMNS = ЧИСЛСТОЛБ ## Возвращает количество столбцов в ссылке. +HLOOKUP = ГПР ## Ищет в первой строке массива и возвращает значение отмеченной ячейки +HYPERLINK = ГИПЕРССЫЛКА ## Создает ссылку, открывающую документ, который находится на сервере сети, в интрасети или в Интернете. +INDEX = ИНДЕКС ## Использует индекс для выбора значения из ссылки или массива. +INDIRECT = ДВССЫЛ ## Возвращает ссылку, заданную текстовым значением. +LOOKUP = ПРОСМОТР ## Ищет значения в векторе или массиве. +MATCH = ПОИСКПОЗ ## Ищет значения в ссылке или массиве. +OFFSET = СМЕЩ ## Возвращает смещение ссылки относительно заданной ссылки. +ROW = СТРОКА ## Возвращает номер строки, определяемой ссылкой. +ROWS = ЧСТРОК ## Возвращает количество строк в ссылке. +RTD = ДРВ ## Извлекает данные реального времени из программ, поддерживающих автоматизацию COM (Программирование объектов. Стандартное средство для работы с объектами некоторого приложения из другого приложения или средства разработки. Программирование объектов (ранее называемое программированием OLE) является функцией модели COM (Component Object Model, модель компонентных объектов).). +TRANSPOSE = ТРАНСП ## Возвращает транспонированный массив. +VLOOKUP = ВПР ## Ищет значение в первом столбце массива и возвращает значение из ячейки в найденной строке и указанном столбце. + + +## +## Math and trigonometry functions Математические и тригонометрические функции +## +ABS = ABS ## Возвращает модуль (абсолютную величину) числа. +ACOS = ACOS ## Возвращает арккосинус числа. +ACOSH = ACOSH ## Возвращает гиперболический арккосинус числа. +ASIN = ASIN ## Возвращает арксинус числа. +ASINH = ASINH ## Возвращает гиперболический арксинус числа. +ATAN = ATAN ## Возвращает арктангенс числа. +ATAN2 = ATAN2 ## Возвращает арктангенс для заданных координат x и y. +ATANH = ATANH ## Возвращает гиперболический арктангенс числа. +CEILING = ОКРВВЕРХ ## Округляет число до ближайшего целого или до ближайшего кратного указанному значению. +COMBIN = ЧИСЛКОМБ ## Возвращает количество комбинаций для заданного числа объектов. +COS = COS ## Возвращает косинус числа. +COSH = COSH ## Возвращает гиперболический косинус числа. +DEGREES = ГРАДУСЫ ## Преобразует радианы в градусы. +EVEN = ЧЁТН ## Округляет число до ближайшего четного целого. +EXP = EXP ## Возвращает число e, возведенное в указанную степень. +FACT = ФАКТР ## Возвращает факториал числа. +FACTDOUBLE = ДВФАКТР ## Возвращает двойной факториал числа. +FLOOR = ОКРВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. +GCD = НОД ## Возвращает наибольший общий делитель. +INT = ЦЕЛОЕ ## Округляет число до ближайшего меньшего целого. +LCM = НОК ## Возвращает наименьшее общее кратное. +LN = LN ## Возвращает натуральный логарифм числа. +LOG = LOG ## Возвращает логарифм числа по заданному основанию. +LOG10 = LOG10 ## Возвращает десятичный логарифм числа. +MDETERM = МОПРЕД ## Возвращает определитель матрицы массива. +MINVERSE = МОБР ## Возвращает обратную матрицу массива. +MMULT = МУМНОЖ ## Возвращает произведение матриц двух массивов. +MOD = ОСТАТ ## Возвращает остаток от деления. +MROUND = ОКРУГЛТ ## Возвращает число, округленное с требуемой точностью. +MULTINOMIAL = МУЛЬТИНОМ ## Возвращает мультиномиальный коэффициент множества чисел. +ODD = НЕЧЁТ ## Округляет число до ближайшего нечетного целого. +PI = ПИ ## Возвращает число пи. +POWER = СТЕПЕНЬ ## Возвращает результат возведения числа в степень. +PRODUCT = ПРОИЗВЕД ## Возвращает произведение аргументов. +QUOTIENT = ЧАСТНОЕ ## Возвращает целую часть частного при делении. +RADIANS = РАДИАНЫ ## Преобразует градусы в радианы. +RAND = СЛЧИС ## Возвращает случайное число в интервале от 0 до 1. +RANDBETWEEN = СЛУЧМЕЖДУ ## Возвращает случайное число в интервале между двумя заданными числами. +ROMAN = РИМСКОЕ ## Преобразует арабские цифры в римские в виде текста. +ROUND = ОКРУГЛ ## Округляет число до указанного количества десятичных разрядов. +ROUNDDOWN = ОКРУГЛВНИЗ ## Округляет число до ближайшего меньшего по модулю значения. +ROUNDUP = ОКРУГЛВВЕРХ ## Округляет число до ближайшего большего по модулю значения. +SERIESSUM = РЯД.СУММ ## Возвращает сумму степенного ряда, вычисленную по формуле. +SIGN = ЗНАК ## Возвращает знак числа. +SIN = SIN ## Возвращает синус заданного угла. +SINH = SINH ## Возвращает гиперболический синус числа. +SQRT = КОРЕНЬ ## Возвращает положительное значение квадратного корня. +SQRTPI = КОРЕНЬПИ ## Возвращает квадратный корень из значения выражения (число * ПИ). +SUBTOTAL = ПРОМЕЖУТОЧНЫЕ.ИТОГИ ## Возвращает промежуточный итог в списке или базе данных. +SUM = СУММ ## Суммирует аргументы. +SUMIF = СУММЕСЛИ ## Суммирует ячейки, удовлетворяющие заданному условию. +SUMIFS = СУММЕСЛИМН ## Суммирует диапазон ячеек, удовлетворяющих нескольким условиям. +SUMPRODUCT = СУММПРОИЗВ ## Возвращает сумму произведений соответствующих элементов массивов. +SUMSQ = СУММКВ ## Возвращает сумму квадратов аргументов. +SUMX2MY2 = СУММРАЗНКВ ## Возвращает сумму разностей квадратов соответствующих значений в двух массивах. +SUMX2PY2 = СУММСУММКВ ## Возвращает сумму сумм квадратов соответствующих элементов двух массивов. +SUMXMY2 = СУММКВРАЗН ## Возвращает сумму квадратов разностей соответствующих значений в двух массивах. +TAN = TAN ## Возвращает тангенс числа. +TANH = TANH ## Возвращает гиперболический тангенс числа. +TRUNC = ОТБР ## Отбрасывает дробную часть числа. + + +## +## Statistical functions Статистические функции +## +AVEDEV = СРОТКЛ ## Возвращает среднее арифметическое абсолютных значений отклонений точек данных от среднего. +AVERAGE = СРЗНАЧ ## Возвращает среднее арифметическое аргументов. +AVERAGEA = СРЗНАЧА ## Возвращает среднее арифметическое аргументов, включая числа, текст и логические значения. +AVERAGEIF = СРЗНАЧЕСЛИ ## Возвращает среднее значение (среднее арифметическое) всех ячеек в диапазоне, которые удовлетворяют данному условию. +AVERAGEIFS = СРЗНАЧЕСЛИМН ## Возвращает среднее значение (среднее арифметическое) всех ячеек, которые удовлетворяют нескольким условиям. +BETADIST = БЕТАРАСП ## Возвращает интегральную функцию бета-распределения. +BETAINV = БЕТАОБР ## Возвращает обратную интегральную функцию указанного бета-распределения. +BINOMDIST = БИНОМРАСП ## Возвращает отдельное значение биномиального распределения. +CHIDIST = ХИ2РАСП ## Возвращает одностороннюю вероятность распределения хи-квадрат. +CHIINV = ХИ2ОБР ## Возвращает обратное значение односторонней вероятности распределения хи-квадрат. +CHITEST = ХИ2ТЕСТ ## Возвращает тест на независимость. +CONFIDENCE = ДОВЕРИТ ## Возвращает доверительный интервал для среднего значения по генеральной совокупности. +CORREL = КОРРЕЛ ## Возвращает коэффициент корреляции между двумя множествами данных. +COUNT = СЧЁТ ## Подсчитывает количество чисел в списке аргументов. +COUNTA = СЧЁТЗ ## Подсчитывает количество значений в списке аргументов. +COUNTBLANK = СЧИТАТЬПУСТОТЫ ## Подсчитывает количество пустых ячеек в диапазоне +COUNTIF = СЧЁТЕСЛИ ## Подсчитывает количество ячеек в диапазоне, удовлетворяющих заданному условию +COUNTIFS = СЧЁТЕСЛИМН ## Подсчитывает количество ячеек внутри диапазона, удовлетворяющих нескольким условиям. +COVAR = КОВАР ## Возвращает ковариацию, среднее произведений парных отклонений +CRITBINOM = КРИТБИНОМ ## Возвращает наименьшее значение, для которого интегральное биномиальное распределение меньше или равно заданному критерию. +DEVSQ = КВАДРОТКЛ ## Возвращает сумму квадратов отклонений. +EXPONDIST = ЭКСПРАСП ## Возвращает экспоненциальное распределение. +FDIST = FРАСП ## Возвращает F-распределение вероятности. +FINV = FРАСПОБР ## Возвращает обратное значение для F-распределения вероятности. +FISHER = ФИШЕР ## Возвращает преобразование Фишера. +FISHERINV = ФИШЕРОБР ## Возвращает обратное преобразование Фишера. +FORECAST = ПРЕДСКАЗ ## Возвращает значение линейного тренда. +FREQUENCY = ЧАСТОТА ## Возвращает распределение частот в виде вертикального массива. +FTEST = ФТЕСТ ## Возвращает результат F-теста. +GAMMADIST = ГАММАРАСП ## Возвращает гамма-распределение. +GAMMAINV = ГАММАОБР ## Возвращает обратное гамма-распределение. +GAMMALN = ГАММАНЛОГ ## Возвращает натуральный логарифм гамма функции, Γ(x). +GEOMEAN = СРГЕОМ ## Возвращает среднее геометрическое. +GROWTH = РОСТ ## Возвращает значения в соответствии с экспоненциальным трендом. +HARMEAN = СРГАРМ ## Возвращает среднее гармоническое. +HYPGEOMDIST = ГИПЕРГЕОМЕТ ## Возвращает гипергеометрическое распределение. +INTERCEPT = ОТРЕЗОК ## Возвращает отрезок, отсекаемый на оси линией линейной регрессии. +KURT = ЭКСЦЕСС ## Возвращает эксцесс множества данных. +LARGE = НАИБОЛЬШИЙ ## Возвращает k-ое наибольшее значение в множестве данных. +LINEST = ЛИНЕЙН ## Возвращает параметры линейного тренда. +LOGEST = ЛГРФПРИБЛ ## Возвращает параметры экспоненциального тренда. +LOGINV = ЛОГНОРМОБР ## Возвращает обратное логарифмическое нормальное распределение. +LOGNORMDIST = ЛОГНОРМРАСП ## Возвращает интегральное логарифмическое нормальное распределение. +MAX = МАКС ## Возвращает наибольшее значение в списке аргументов. +MAXA = МАКСА ## Возвращает наибольшее значение в списке аргументов, включая числа, текст и логические значения. +MEDIAN = МЕДИАНА ## Возвращает медиану заданных чисел. +MIN = МИН ## Возвращает наименьшее значение в списке аргументов. +MINA = МИНА ## Возвращает наименьшее значение в списке аргументов, включая числа, текст и логические значения. +MODE = МОДА ## Возвращает значение моды множества данных. +NEGBINOMDIST = ОТРБИНОМРАСП ## Возвращает отрицательное биномиальное распределение. +NORMDIST = НОРМРАСП ## Возвращает нормальную функцию распределения. +NORMINV = НОРМОБР ## Возвращает обратное нормальное распределение. +NORMSDIST = НОРМСТРАСП ## Возвращает стандартное нормальное интегральное распределение. +NORMSINV = НОРМСТОБР ## Возвращает обратное значение стандартного нормального распределения. +PEARSON = ПИРСОН ## Возвращает коэффициент корреляции Пирсона. +PERCENTILE = ПЕРСЕНТИЛЬ ## Возвращает k-ую персентиль для значений диапазона. +PERCENTRANK = ПРОЦЕНТРАНГ ## Возвращает процентную норму значения в множестве данных. +PERMUT = ПЕРЕСТ ## Возвращает количество перестановок для заданного числа объектов. +POISSON = ПУАССОН ## Возвращает распределение Пуассона. +PROB = ВЕРОЯТНОСТЬ ## Возвращает вероятность того, что значение из диапазона находится внутри заданных пределов. +QUARTILE = КВАРТИЛЬ ## Возвращает квартиль множества данных. +RANK = РАНГ ## Возвращает ранг числа в списке чисел. +RSQ = КВПИРСОН ## Возвращает квадрат коэффициента корреляции Пирсона. +SKEW = СКОС ## Возвращает асимметрию распределения. +SLOPE = НАКЛОН ## Возвращает наклон линии линейной регрессии. +SMALL = НАИМЕНЬШИЙ ## Возвращает k-ое наименьшее значение в множестве данных. +STANDARDIZE = НОРМАЛИЗАЦИЯ ## Возвращает нормализованное значение. +STDEV = СТАНДОТКЛОН ## Оценивает стандартное отклонение по выборке. +STDEVA = СТАНДОТКЛОНА ## Оценивает стандартное отклонение по выборке, включая числа, текст и логические значения. +STDEVP = СТАНДОТКЛОНП ## Вычисляет стандартное отклонение по генеральной совокупности. +STDEVPA = СТАНДОТКЛОНПА ## Вычисляет стандартное отклонение по генеральной совокупности, включая числа, текст и логические значения. +STEYX = СТОШYX ## Возвращает стандартную ошибку предсказанных значений y для каждого значения x в регрессии. +TDIST = СТЬЮДРАСП ## Возвращает t-распределение Стьюдента. +TINV = СТЬЮДРАСПОБР ## Возвращает обратное t-распределение Стьюдента. +TREND = ТЕНДЕНЦИЯ ## Возвращает значения в соответствии с линейным трендом. +TRIMMEAN = УРЕЗСРЕДНЕЕ ## Возвращает среднее внутренности множества данных. +TTEST = ТТЕСТ ## Возвращает вероятность, соответствующую критерию Стьюдента. +VAR = ДИСП ## Оценивает дисперсию по выборке. +VARA = ДИСПА ## Оценивает дисперсию по выборке, включая числа, текст и логические значения. +VARP = ДИСПР ## Вычисляет дисперсию для генеральной совокупности. +VARPA = ДИСПРА ## Вычисляет дисперсию для генеральной совокупности, включая числа, текст и логические значения. +WEIBULL = ВЕЙБУЛЛ ## Возвращает распределение Вейбулла. +ZTEST = ZТЕСТ ## Возвращает двустороннее P-значение z-теста. + + +## +## Text functions Текстовые функции +## +ASC = ASC ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полноширинные (двухбайтовые) знаки в полуширинные (однобайтовые). +BAHTTEXT = БАТТЕКСТ ## Преобразует число в текст, используя денежный формат ß (БАТ). +CHAR = СИМВОЛ ## Возвращает знак с заданным кодом. +CLEAN = ПЕЧСИМВ ## Удаляет все непечатаемые знаки из текста. +CODE = КОДСИМВ ## Возвращает числовой код первого знака в текстовой строке. +CONCATENATE = СЦЕПИТЬ ## Объединяет несколько текстовых элементов в один. +DOLLAR = РУБЛЬ ## Преобразует число в текст, используя денежный формат. +EXACT = СОВПАД ## Проверяет идентичность двух текстовых значений. +FIND = НАЙТИ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). +FINDB = НАЙТИБ ## Ищет вхождения одного текстового значения в другом (с учетом регистра). +FIXED = ФИКСИРОВАННЫЙ ## Форматирует число и преобразует его в текст с заданным числом десятичных знаков. +JIS = JIS ## Для языков с двухбайтовыми наборами знаков (например, катакана) преобразует полуширинные (однобайтовые) знаки в текстовой строке в полноширинные (двухбайтовые). +LEFT = ЛЕВСИМВ ## Возвращает крайние слева знаки текстового значения. +LEFTB = ЛЕВБ ## Возвращает крайние слева знаки текстового значения. +LEN = ДЛСТР ## Возвращает количество знаков в текстовой строке. +LENB = ДЛИНБ ## Возвращает количество знаков в текстовой строке. +LOWER = СТРОЧН ## Преобразует все буквы текста в строчные. +MID = ПСТР ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. +MIDB = ПСТРБ ## Возвращает заданное число знаков из строки текста, начиная с указанной позиции. +PHONETIC = PHONETIC ## Извлекает фонетические (фуригана) знаки из текстовой строки. +PROPER = ПРОПНАЧ ## Преобразует первую букву в каждом слове текста в прописную. +REPLACE = ЗАМЕНИТЬ ## Заменяет знаки в тексте. +REPLACEB = ЗАМЕНИТЬБ ## Заменяет знаки в тексте. +REPT = ПОВТОР ## Повторяет текст заданное число раз. +RIGHT = ПРАВСИМВ ## Возвращает крайние справа знаки текстовой строки. +RIGHTB = ПРАВБ ## Возвращает крайние справа знаки текстовой строки. +SEARCH = ПОИСК ## Ищет вхождения одного текстового значения в другом (без учета регистра). +SEARCHB = ПОИСКБ ## Ищет вхождения одного текстового значения в другом (без учета регистра). +SUBSTITUTE = ПОДСТАВИТЬ ## Заменяет в текстовой строке старый текст новым. +T = Т ## Преобразует аргументы в текст. +TEXT = ТЕКСТ ## Форматирует число и преобразует его в текст. +TRIM = СЖПРОБЕЛЫ ## Удаляет из текста пробелы. +UPPER = ПРОПИСН ## Преобразует все буквы текста в прописные. +VALUE = ЗНАЧЕН ## Преобразует текстовый аргумент в число. diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/config new file mode 100644 index 00000000..726f7716 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = kr + + +## +## Excel Error Codes (For future use) +## +NULL = #Skärning! +DIV0 = #Division/0! +VALUE = #Värdefel! +REF = #Referens! +NAME = #Namn? +NUM = #Ogiltigt! +NA = #Saknas! diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/functions new file mode 100644 index 00000000..73b2deb5 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/sv/functions @@ -0,0 +1,408 @@ +## +## Add-in and Automation functions Tilläggs- och automatiseringsfunktioner +## +GETPIVOTDATA = HÄMTA.PIVOTDATA ## Returnerar data som lagrats i en pivottabellrapport + + +## +## Cube functions Kubfunktioner +## +CUBEKPIMEMBER = KUBKPIMEDLEM ## Returnerar namn, egenskap och mått för en KPI och visar namnet och egenskapen i cellen. En KPI, eller prestandaindikator, är ett kvantifierbart mått, t.ex. månatlig bruttovinst eller personalomsättning per kvartal, som används för att analysera ett företags resultat. +CUBEMEMBER = KUBMEDLEM ## Returnerar en medlem eller ett par i en kubhierarki. Används för att verifiera att medlemmen eller paret finns i kuben. +CUBEMEMBERPROPERTY = KUBMEDLEMSEGENSKAP ## Returnerar värdet för en medlemsegenskap i kuben. Används för att verifiera att ett medlemsnamn finns i kuben, samt för att returnera den angivna egenskapen för medlemmen. +CUBERANKEDMEMBER = KUBRANGORDNADMEDLEM ## Returnerar den n:te, eller rangordnade, medlemmen i en uppsättning. Används för att returnera ett eller flera element i en uppsättning, till exempelvis den bästa försäljaren eller de tio bästa eleverna. +CUBESET = KUBINSTÄLLNING ## Definierar en beräknad uppsättning medlemmar eller par genom att skicka ett bestämt uttryck till kuben på servern, som skapar uppsättningen och sedan returnerar den till Microsoft Office Excel. +CUBESETCOUNT = KUBINSTÄLLNINGANTAL ## Returnerar antalet objekt i en uppsättning. +CUBEVALUE = KUBVÄRDE ## Returnerar ett mängdvärde från en kub. + + +## +## Database functions Databasfunktioner +## +DAVERAGE = DMEDEL ## Returnerar medelvärdet av databasposterna +DCOUNT = DANTAL ## Räknar antalet celler som innehåller tal i en databas +DCOUNTA = DANTALV ## Räknar ifyllda celler i en databas +DGET = DHÄMTA ## Hämtar en enstaka post från en databas som uppfyller de angivna villkoren +DMAX = DMAX ## Returnerar det största värdet från databasposterna +DMIN = DMIN ## Returnerar det minsta värdet från databasposterna +DPRODUCT = DPRODUKT ## Multiplicerar värdena i ett visst fält i poster som uppfyller villkoret +DSTDEV = DSTDAV ## Uppskattar standardavvikelsen baserat på ett urval av databasposterna +DSTDEVP = DSTDAVP ## Beräknar standardavvikelsen utifrån hela populationen av valda databasposter +DSUM = DSUMMA ## Summerar talen i kolumnfält i databasposter som uppfyller villkoret +DVAR = DVARIANS ## Uppskattar variansen baserat på ett urval av databasposterna +DVARP = DVARIANSP ## Beräknar variansen utifrån hela populationen av valda databasposter + + +## +## Date and time functions Tid- och datumfunktioner +## +DATE = DATUM ## Returnerar ett serienummer för ett visst datum +DATEVALUE = DATUMVÄRDE ## Konverterar ett datum i textformat till ett serienummer +DAY = DAG ## Konverterar ett serienummer till dag i månaden +DAYS360 = DAGAR360 ## Beräknar antalet dagar mellan två datum baserat på ett 360-dagarsår +EDATE = EDATUM ## Returnerar serienumret för ett datum som infaller ett visst antal månader före eller efter startdatumet +EOMONTH = SLUTMÅNAD ## Returnerar serienumret för sista dagen i månaden ett visst antal månader tidigare eller senare +HOUR = TIMME ## Konverterar ett serienummer till en timme +MINUTE = MINUT ## Konverterar ett serienummer till en minut +MONTH = MÅNAD ## Konverterar ett serienummer till en månad +NETWORKDAYS = NETTOARBETSDAGAR ## Returnerar antalet hela arbetsdagar mellan två datum +NOW = NU ## Returnerar serienumret för dagens datum och aktuell tid +SECOND = SEKUND ## Konverterar ett serienummer till en sekund +TIME = KLOCKSLAG ## Returnerar serienumret för en viss tid +TIMEVALUE = TIDVÄRDE ## Konverterar en tid i textformat till ett serienummer +TODAY = IDAG ## Returnerar serienumret för dagens datum +WEEKDAY = VECKODAG ## Konverterar ett serienummer till en dag i veckan +WEEKNUM = VECKONR ## Konverterar ett serienummer till ett veckonummer +WORKDAY = ARBETSDAGAR ## Returnerar serienumret för ett datum ett visst antal arbetsdagar tidigare eller senare +YEAR = ÅR ## Konverterar ett serienummer till ett år +YEARFRAC = ÅRDEL ## Returnerar en del av ett år som representerar antalet hela dagar mellan start- och slutdatum + + +## +## Engineering functions Tekniska funktioner +## +BESSELI = BESSELI ## Returnerar den modifierade Bessel-funktionen In(x) +BESSELJ = BESSELJ ## Returnerar Bessel-funktionen Jn(x) +BESSELK = BESSELK ## Returnerar den modifierade Bessel-funktionen Kn(x) +BESSELY = BESSELY ## Returnerar Bessel-funktionen Yn(x) +BIN2DEC = BIN.TILL.DEC ## Omvandlar ett binärt tal till decimalt +BIN2HEX = BIN.TILL.HEX ## Omvandlar ett binärt tal till hexadecimalt +BIN2OCT = BIN.TILL.OKT ## Omvandlar ett binärt tal till oktalt +COMPLEX = KOMPLEX ## Omvandlar reella och imaginära koefficienter till ett komplext tal +CONVERT = KONVERTERA ## Omvandlar ett tal från ett måttsystem till ett annat +DEC2BIN = DEC.TILL.BIN ## Omvandlar ett decimalt tal till binärt +DEC2HEX = DEC.TILL.HEX ## Omvandlar ett decimalt tal till hexadecimalt +DEC2OCT = DEC.TILL.OKT ## Omvandlar ett decimalt tal till oktalt +DELTA = DELTA ## Testar om två värden är lika +ERF = FELF ## Returnerar felfunktionen +ERFC = FELFK ## Returnerar den komplementära felfunktionen +GESTEP = SLSTEG ## Testar om ett tal är större än ett tröskelvärde +HEX2BIN = HEX.TILL.BIN ## Omvandlar ett hexadecimalt tal till binärt +HEX2DEC = HEX.TILL.DEC ## Omvandlar ett hexadecimalt tal till decimalt +HEX2OCT = HEX.TILL.OKT ## Omvandlar ett hexadecimalt tal till oktalt +IMABS = IMABS ## Returnerar absolutvärdet (modulus) för ett komplext tal +IMAGINARY = IMAGINÄR ## Returnerar den imaginära koefficienten för ett komplext tal +IMARGUMENT = IMARGUMENT ## Returnerar det komplexa talets argument, en vinkel uttryckt i radianer +IMCONJUGATE = IMKONJUGAT ## Returnerar det komplexa talets konjugat +IMCOS = IMCOS ## Returnerar cosinus för ett komplext tal +IMDIV = IMDIV ## Returnerar kvoten för två komplexa tal +IMEXP = IMEUPPHÖJT ## Returnerar exponenten för ett komplext tal +IMLN = IMLN ## Returnerar den naturliga logaritmen för ett komplext tal +IMLOG10 = IMLOG10 ## Returnerar 10-logaritmen för ett komplext tal +IMLOG2 = IMLOG2 ## Returnerar 2-logaritmen för ett komplext tal +IMPOWER = IMUPPHÖJT ## Returnerar ett komplext tal upphöjt till en exponent +IMPRODUCT = IMPRODUKT ## Returnerar produkten av komplexa tal +IMREAL = IMREAL ## Returnerar den reella koefficienten för ett komplext tal +IMSIN = IMSIN ## Returnerar sinus för ett komplext tal +IMSQRT = IMROT ## Returnerar kvadratroten av ett komplext tal +IMSUB = IMDIFF ## Returnerar differensen mellan två komplexa tal +IMSUM = IMSUM ## Returnerar summan av komplexa tal +OCT2BIN = OKT.TILL.BIN ## Omvandlar ett oktalt tal till binärt +OCT2DEC = OKT.TILL.DEC ## Omvandlar ett oktalt tal till decimalt +OCT2HEX = OKT.TILL.HEX ## Omvandlar ett oktalt tal till hexadecimalt + + +## +## Financial functions Finansiella funktioner +## +ACCRINT = UPPLRÄNTA ## Returnerar den upplupna räntan för värdepapper med periodisk ränta +ACCRINTM = UPPLOBLRÄNTA ## Returnerar den upplupna räntan för ett värdepapper som ger avkastning på förfallodagen +AMORDEGRC = AMORDEGRC ## Returnerar avskrivningen för varje redovisningsperiod med hjälp av en avskrivningskoefficient +AMORLINC = AMORLINC ## Returnerar avskrivningen för varje redovisningsperiod +COUPDAYBS = KUPDAGBB ## Returnerar antal dagar från början av kupongperioden till likviddagen +COUPDAYS = KUPDAGARS ## Returnerar antalet dagar i kupongperioden som innehåller betalningsdatumet +COUPDAYSNC = KUPDAGNK ## Returnerar antalet dagar från betalningsdatumet till nästa kupongdatum +COUPNCD = KUPNKD ## Returnerar nästa kupongdatum efter likviddagen +COUPNUM = KUPANT ## Returnerar kuponger som förfaller till betalning mellan likviddagen och förfallodagen +COUPPCD = KUPFKD ## Returnerar föregående kupongdatum före likviddagen +CUMIPMT = KUMRÄNTA ## Returnerar den ackumulerade räntan som betalats mellan två perioder +CUMPRINC = KUMPRIS ## Returnerar det ackumulerade kapitalbeloppet som betalats på ett lån mellan två perioder +DB = DB ## Returnerar avskrivningen för en tillgång under en angiven tid enligt metoden för fast degressiv avskrivning +DDB = DEGAVSKR ## Returnerar en tillgångs värdeminskning under en viss period med hjälp av dubbel degressiv avskrivning eller någon annan metod som du anger +DISC = DISK ## Returnerar diskonteringsräntan för ett värdepapper +DOLLARDE = DECTAL ## Omvandlar ett pris uttryckt som ett bråk till ett decimaltal +DOLLARFR = BRÅK ## Omvandlar ett pris i kronor uttryckt som ett decimaltal till ett bråk +DURATION = LÖPTID ## Returnerar den årliga löptiden för en säkerhet med periodiska räntebetalningar +EFFECT = EFFRÄNTA ## Returnerar den årliga effektiva räntesatsen +FV = SLUTVÄRDE ## Returnerar det framtida värdet på en investering +FVSCHEDULE = FÖRRÄNTNING ## Returnerar det framtida värdet av ett begynnelsekapital beräknat på olika räntenivåer +INTRATE = ÅRSRÄNTA ## Returnerar räntesatsen för ett betalt värdepapper +IPMT = RBETALNING ## Returnerar räntedelen av en betalning för en given period +IRR = IR ## Returnerar internräntan för en serie betalningar +ISPMT = RALÅN ## Beräknar räntan som har betalats under en specifik betalningsperiod +MDURATION = MLÖPTID ## Returnerar den modifierade Macauley-löptiden för ett värdepapper med det antagna nominella värdet 100 kr +MIRR = MODIR ## Returnerar internräntan där positiva och negativa betalningar finansieras med olika räntor +NOMINAL = NOMRÄNTA ## Returnerar den årliga nominella räntesatsen +NPER = PERIODER ## Returnerar antalet perioder för en investering +NPV = NETNUVÄRDE ## Returnerar nuvärdet av en serie periodiska betalningar vid en given diskonteringsränta +ODDFPRICE = UDDAFPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda första period +ODDFYIELD = UDDAFAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda första period +ODDLPRICE = UDDASPRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper med en udda sista period +ODDLYIELD = UDDASAVKASTNING ## Returnerar avkastningen för en säkerhet med en udda sista period +PMT = BETALNING ## Returnerar den periodiska betalningen för en annuitet +PPMT = AMORT ## Returnerar amorteringsdelen av en annuitetsbetalning för en given period +PRICE = PRIS ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger periodisk ränta +PRICEDISC = PRISDISK ## Returnerar priset per 100 kr nominellt värde för ett diskonterat värdepapper +PRICEMAT = PRISFÖRF ## Returnerar priset per 100 kr nominellt värde för ett värdepapper som ger ränta på förfallodagen +PV = PV ## Returnerar nuvärdet av en serie lika stora periodiska betalningar +RATE = RÄNTA ## Returnerar räntesatsen per period i en annuitet +RECEIVED = BELOPP ## Returnerar beloppet som utdelas på förfallodagen för ett betalat värdepapper +SLN = LINAVSKR ## Returnerar den linjära avskrivningen för en tillgång under en period +SYD = ÅRSAVSKR ## Returnerar den årliga avskrivningssumman för en tillgång under en angiven period +TBILLEQ = SSVXEKV ## Returnerar avkastningen motsvarande en obligation för en statsskuldväxel +TBILLPRICE = SSVXPRIS ## Returnerar priset per 100 kr nominellt värde för en statsskuldväxel +TBILLYIELD = SSVXRÄNTA ## Returnerar avkastningen för en statsskuldväxel +VDB = VDEGRAVSKR ## Returnerar avskrivningen för en tillgång under en angiven period (med degressiv avskrivning) +XIRR = XIRR ## Returnerar internräntan för en serie betalningar som inte nödvändigtvis är periodiska +XNPV = XNUVÄRDE ## Returnerar det nuvarande nettovärdet för en serie betalningar som inte nödvändigtvis är periodiska +YIELD = NOMAVK ## Returnerar avkastningen för ett värdepapper som ger periodisk ränta +YIELDDISC = NOMAVKDISK ## Returnerar den årliga avkastningen för diskonterade värdepapper, exempelvis en statsskuldväxel +YIELDMAT = NOMAVKFÖRF ## Returnerar den årliga avkastningen för ett värdepapper som ger ränta på förfallodagen + + +## +## Information functions Informationsfunktioner +## +CELL = CELL ## Returnerar information om formatering, plats och innehåll i en cell +ERROR.TYPE = FEL.TYP ## Returnerar ett tal som motsvarar ett felvärde +INFO = INFO ## Returnerar information om operativsystemet +ISBLANK = ÄRREF ## Returnerar SANT om värdet är tomt +ISERR = Ä ## Returnerar SANT om värdet är ett felvärde annat än #SAKNAS! +ISERROR = ÄRFEL ## Returnerar SANT om värdet är ett felvärde +ISEVEN = ÄRJÄMN ## Returnerar SANT om talet är jämnt +ISLOGICAL = ÄREJTEXT ## Returnerar SANT om värdet är ett logiskt värde +ISNA = ÄRLOGISK ## Returnerar SANT om värdet är felvärdet #SAKNAS! +ISNONTEXT = ÄRSAKNAD ## Returnerar SANT om värdet inte är text +ISNUMBER = ÄRTAL ## Returnerar SANT om värdet är ett tal +ISODD = ÄRUDDA ## Returnerar SANT om talet är udda +ISREF = ÄRTOM ## Returnerar SANT om värdet är en referens +ISTEXT = ÄRTEXT ## Returnerar SANT om värdet är text +N = N ## Returnerar ett värde omvandlat till ett tal +NA = SAKNAS ## Returnerar felvärdet #SAKNAS! +TYPE = VÄRDETYP ## Returnerar ett tal som anger värdets datatyp + + +## +## Logical functions Logiska funktioner +## +AND = OCH ## Returnerar SANT om alla argument är sanna +FALSE = FALSKT ## Returnerar det logiska värdet FALSKT +IF = OM ## Anger vilket logiskt test som ska utföras +IFERROR = OMFEL ## Returnerar ett värde som du anger om en formel utvärderar till ett fel; annars returneras resultatet av formeln +NOT = ICKE ## Inverterar logiken för argumenten +OR = ELLER ## Returnerar SANT om något argument är SANT +TRUE = SANT ## Returnerar det logiska värdet SANT + + +## +## Lookup and reference functions Sök- och referensfunktioner +## +ADDRESS = ADRESS ## Returnerar en referens som text till en enstaka cell i ett kalkylblad +AREAS = OMRÅDEN ## Returnerar antalet områden i en referens +CHOOSE = VÄLJ ## Väljer ett värde i en lista över värden +COLUMN = KOLUMN ## Returnerar kolumnnumret för en referens +COLUMNS = KOLUMNER ## Returnerar antalet kolumner i en referens +HLOOKUP = LETAKOLUMN ## Söker i den översta raden i en matris och returnerar värdet för angiven cell +HYPERLINK = HYPERLÄNK ## Skapar en genväg eller ett hopp till ett dokument i nätverket, i ett intranät eller på Internet +INDEX = INDEX ## Använder ett index för ett välja ett värde i en referens eller matris +INDIRECT = INDIREKT ## Returnerar en referens som anges av ett textvärde +LOOKUP = LETAUPP ## Letar upp värden i en vektor eller matris +MATCH = PASSA ## Letar upp värden i en referens eller matris +OFFSET = FÖRSKJUTNING ## Returnerar en referens förskjuten i förhållande till en given referens +ROW = RAD ## Returnerar radnumret för en referens +ROWS = RADER ## Returnerar antalet rader i en referens +RTD = RTD ## Hämtar realtidsdata från ett program som stöder COM-automation (Automation: Ett sätt att arbeta med ett programs objekt från ett annat program eller utvecklingsverktyg. Detta kallades tidigare för OLE Automation, och är en branschstandard och ingår i Component Object Model (COM).) +TRANSPOSE = TRANSPONERA ## Transponerar en matris +VLOOKUP = LETARAD ## Letar i den första kolumnen i en matris och flyttar över raden för att returnera värdet för en cell + + +## +## Math and trigonometry functions Matematiska och trigonometriska funktioner +## +ABS = ABS ## Returnerar absolutvärdet av ett tal +ACOS = ARCCOS ## Returnerar arcus cosinus för ett tal +ACOSH = ARCCOSH ## Returnerar inverterad hyperbolisk cosinus för ett tal +ASIN = ARCSIN ## Returnerar arcus cosinus för ett tal +ASINH = ARCSINH ## Returnerar hyperbolisk arcus sinus för ett tal +ATAN = ARCTAN ## Returnerar arcus tangens för ett tal +ATAN2 = ARCTAN2 ## Returnerar arcus tangens för en x- och en y- koordinat +ATANH = ARCTANH ## Returnerar hyperbolisk arcus tangens för ett tal +CEILING = RUNDA.UPP ## Avrundar ett tal till närmaste heltal eller närmaste signifikanta multipel +COMBIN = KOMBIN ## Returnerar antalet kombinationer för ett givet antal objekt +COS = COS ## Returnerar cosinus för ett tal +COSH = COSH ## Returnerar hyperboliskt cosinus för ett tal +DEGREES = GRADER ## Omvandlar radianer till grader +EVEN = JÄMN ## Avrundar ett tal uppåt till närmaste heltal +EXP = EXP ## Returnerar e upphöjt till ett givet tal +FACT = FAKULTET ## Returnerar fakulteten för ett tal +FACTDOUBLE = DUBBELFAKULTET ## Returnerar dubbelfakulteten för ett tal +FLOOR = RUNDA.NED ## Avrundar ett tal nedåt mot noll +GCD = SGD ## Returnerar den största gemensamma nämnaren +INT = HELTAL ## Avrundar ett tal nedåt till närmaste heltal +LCM = MGM ## Returnerar den minsta gemensamma multipeln +LN = LN ## Returnerar den naturliga logaritmen för ett tal +LOG = LOG ## Returnerar logaritmen för ett tal för en given bas +LOG10 = LOG10 ## Returnerar 10-logaritmen för ett tal +MDETERM = MDETERM ## Returnerar matrisen som är avgörandet av en matris +MINVERSE = MINVERT ## Returnerar matrisinversen av en matris +MMULT = MMULT ## Returnerar matrisprodukten av två matriser +MOD = REST ## Returnerar resten vid en division +MROUND = MAVRUNDA ## Returnerar ett tal avrundat till en given multipel +MULTINOMIAL = MULTINOMIAL ## Returnerar multinomialen för en uppsättning tal +ODD = UDDA ## Avrundar ett tal uppåt till närmaste udda heltal +PI = PI ## Returnerar värdet pi +POWER = UPPHÖJT.TILL ## Returnerar resultatet av ett tal upphöjt till en exponent +PRODUCT = PRODUKT ## Multiplicerar argumenten +QUOTIENT = KVOT ## Returnerar heltalsdelen av en division +RADIANS = RADIANER ## Omvandlar grader till radianer +RAND = SLUMP ## Returnerar ett slumptal mellan 0 och 1 +RANDBETWEEN = SLUMP.MELLAN ## Returnerar ett slumptal mellan de tal som du anger +ROMAN = ROMERSK ## Omvandlar vanliga (arabiska) siffror till romerska som text +ROUND = AVRUNDA ## Avrundar ett tal till ett angivet antal siffror +ROUNDDOWN = AVRUNDA.NEDÅT ## Avrundar ett tal nedåt mot noll +ROUNDUP = AVRUNDA.UPPÅT ## Avrundar ett tal uppåt, från noll +SERIESSUM = SERIESUMMA ## Returnerar summan av en potensserie baserat på formeln +SIGN = TECKEN ## Returnerar tecknet för ett tal +SIN = SIN ## Returnerar sinus för en given vinkel +SINH = SINH ## Returnerar hyperbolisk sinus för ett tal +SQRT = ROT ## Returnerar den positiva kvadratroten +SQRTPI = ROTPI ## Returnerar kvadratroten för (tal * pi) +SUBTOTAL = DELSUMMA ## Returnerar en delsumma i en lista eller databas +SUM = SUMMA ## Summerar argumenten +SUMIF = SUMMA.OM ## Summerar celler enligt ett angivet villkor +SUMIFS = SUMMA.OMF ## Lägger till cellerna i ett område som uppfyller flera kriterier +SUMPRODUCT = PRODUKTSUMMA ## Returnerar summan av produkterna i motsvarande matriskomponenter +SUMSQ = KVADRATSUMMA ## Returnerar summan av argumentens kvadrater +SUMX2MY2 = SUMMAX2MY2 ## Returnerar summan av differensen mellan kvadraterna för motsvarande värden i två matriser +SUMX2PY2 = SUMMAX2PY2 ## Returnerar summan av summan av kvadraterna av motsvarande värden i två matriser +SUMXMY2 = SUMMAXMY2 ## Returnerar summan av kvadraten av skillnaden mellan motsvarande värden i två matriser +TAN = TAN ## Returnerar tangens för ett tal +TANH = TANH ## Returnerar hyperbolisk tangens för ett tal +TRUNC = AVKORTA ## Avkortar ett tal till ett heltal + + +## +## Statistical functions Statistiska funktioner +## +AVEDEV = MEDELAVV ## Returnerar medelvärdet för datapunkters absoluta avvikelse från deras medelvärde +AVERAGE = MEDEL ## Returnerar medelvärdet av argumenten +AVERAGEA = AVERAGEA ## Returnerar medelvärdet av argumenten, inklusive tal, text och logiska värden +AVERAGEIF = MEDELOM ## Returnerar medelvärdet (aritmetiskt medelvärde) för alla celler i ett område som uppfyller ett givet kriterium +AVERAGEIFS = MEDELOMF ## Returnerar medelvärdet (det aritmetiska medelvärdet) för alla celler som uppfyller flera villkor. +BETADIST = BETAFÖRD ## Returnerar den kumulativa betafördelningsfunktionen +BETAINV = BETAINV ## Returnerar inversen till den kumulativa fördelningsfunktionen för en viss betafördelning +BINOMDIST = BINOMFÖRD ## Returnerar den individuella binomialfördelningen +CHIDIST = CHI2FÖRD ## Returnerar den ensidiga sannolikheten av c2-fördelningen +CHIINV = CHI2INV ## Returnerar inversen av chi2-fördelningen +CHITEST = CHI2TEST ## Returnerar oberoendetesten +CONFIDENCE = KONFIDENS ## Returnerar konfidensintervallet för en populations medelvärde +CORREL = KORREL ## Returnerar korrelationskoefficienten mellan två datamängder +COUNT = ANTAL ## Räknar hur många tal som finns bland argumenten +COUNTA = ANTALV ## Räknar hur många värden som finns bland argumenten +COUNTBLANK = ANTAL.TOMMA ## Räknar antalet tomma celler i ett område +COUNTIF = ANTAL.OM ## Räknar antalet celler i ett område som uppfyller angivna villkor. +COUNTIFS = ANTAL.OMF ## Räknar antalet celler i ett område som uppfyller flera villkor. +COVAR = KOVAR ## Returnerar kovariansen, d.v.s. medelvärdet av produkterna för parade avvikelser +CRITBINOM = KRITBINOM ## Returnerar det minsta värdet för vilket den kumulativa binomialfördelningen är mindre än eller lika med ett villkorsvärde +DEVSQ = KVADAVV ## Returnerar summan av kvadrater på avvikelser +EXPONDIST = EXPONFÖRD ## Returnerar exponentialfördelningen +FDIST = FFÖRD ## Returnerar F-sannolikhetsfördelningen +FINV = FINV ## Returnerar inversen till F-sannolikhetsfördelningen +FISHER = FISHER ## Returnerar Fisher-transformationen +FISHERINV = FISHERINV ## Returnerar inversen till Fisher-transformationen +FORECAST = PREDIKTION ## Returnerar ett värde längs en linjär trendlinje +FREQUENCY = FREKVENS ## Returnerar en frekvensfördelning som en lodrät matris +FTEST = FTEST ## Returnerar resultatet av en F-test +GAMMADIST = GAMMAFÖRD ## Returnerar gammafördelningen +GAMMAINV = GAMMAINV ## Returnerar inversen till den kumulativa gammafördelningen +GAMMALN = GAMMALN ## Returnerar den naturliga logaritmen för gammafunktionen, G(x) +GEOMEAN = GEOMEDEL ## Returnerar det geometriska medelvärdet +GROWTH = EXPTREND ## Returnerar värden längs en exponentiell trend +HARMEAN = HARMMEDEL ## Returnerar det harmoniska medelvärdet +HYPGEOMDIST = HYPGEOMFÖRD ## Returnerar den hypergeometriska fördelningen +INTERCEPT = SKÄRNINGSPUNKT ## Returnerar skärningspunkten för en linjär regressionslinje +KURT = TOPPIGHET ## Returnerar toppigheten av en mängd data +LARGE = STÖRSTA ## Returnerar det n:te största värdet i en mängd data +LINEST = REGR ## Returnerar parametrar till en linjär trendlinje +LOGEST = EXPREGR ## Returnerar parametrarna i en exponentiell trend +LOGINV = LOGINV ## Returnerar inversen till den lognormala fördelningen +LOGNORMDIST = LOGNORMFÖRD ## Returnerar den kumulativa lognormala fördelningen +MAX = MAX ## Returnerar det största värdet i en lista av argument +MAXA = MAXA ## Returnerar det största värdet i en lista av argument, inklusive tal, text och logiska värden +MEDIAN = MEDIAN ## Returnerar medianen för angivna tal +MIN = MIN ## Returnerar det minsta värdet i en lista med argument +MINA = MINA ## Returnerar det minsta värdet i en lista över argument, inklusive tal, text och logiska värden +MODE = TYPVÄRDE ## Returnerar det vanligaste värdet i en datamängd +NEGBINOMDIST = NEGBINOMFÖRD ## Returnerar den negativa binomialfördelningen +NORMDIST = NORMFÖRD ## Returnerar den kumulativa normalfördelningen +NORMINV = NORMINV ## Returnerar inversen till den kumulativa normalfördelningen +NORMSDIST = NORMSFÖRD ## Returnerar den kumulativa standardnormalfördelningen +NORMSINV = NORMSINV ## Returnerar inversen till den kumulativa standardnormalfördelningen +PEARSON = PEARSON ## Returnerar korrelationskoefficienten till Pearsons momentprodukt +PERCENTILE = PERCENTIL ## Returnerar den n:te percentilen av värden i ett område +PERCENTRANK = PROCENTRANG ## Returnerar procentrangen för ett värde i en datamängd +PERMUT = PERMUT ## Returnerar antal permutationer för ett givet antal objekt +POISSON = POISSON ## Returnerar Poisson-fördelningen +PROB = SANNOLIKHET ## Returnerar sannolikheten att värden i ett område ligger mellan två gränser +QUARTILE = KVARTIL ## Returnerar kvartilen av en mängd data +RANK = RANG ## Returnerar rangordningen för ett tal i en lista med tal +RSQ = RKV ## Returnerar kvadraten av Pearsons produktmomentkorrelationskoefficient +SKEW = SNEDHET ## Returnerar snedheten för en fördelning +SLOPE = LUTNING ## Returnerar lutningen på en linjär regressionslinje +SMALL = MINSTA ## Returnerar det n:te minsta värdet i en mängd data +STANDARDIZE = STANDARDISERA ## Returnerar ett normaliserat värde +STDEV = STDAV ## Uppskattar standardavvikelsen baserat på ett urval +STDEVA = STDEVA ## Uppskattar standardavvikelsen baserat på ett urval, inklusive tal, text och logiska värden +STDEVP = STDAVP ## Beräknar standardavvikelsen baserat på hela populationen +STDEVPA = STDEVPA ## Beräknar standardavvikelsen baserat på hela populationen, inklusive tal, text och logiska värden +STEYX = STDFELYX ## Returnerar standardfelet för ett förutspått y-värde för varje x-värde i regressionen +TDIST = TFÖRD ## Returnerar Students t-fördelning +TINV = TINV ## Returnerar inversen till Students t-fördelning +TREND = TREND ## Returnerar värden längs en linjär trend +TRIMMEAN = TRIMMEDEL ## Returnerar medelvärdet av mittpunkterna i en datamängd +TTEST = TTEST ## Returnerar sannolikheten beräknad ur Students t-test +VAR = VARIANS ## Uppskattar variansen baserat på ett urval +VARA = VARA ## Uppskattar variansen baserat på ett urval, inklusive tal, text och logiska värden +VARP = VARIANSP ## Beräknar variansen baserat på hela populationen +VARPA = VARPA ## Beräknar variansen baserat på hela populationen, inklusive tal, text och logiska värden +WEIBULL = WEIBULL ## Returnerar Weibull-fördelningen +ZTEST = ZTEST ## Returnerar det ensidiga sannolikhetsvärdet av ett z-test + + +## +## Text functions Textfunktioner +## +ASC = ASC ## Ändrar helbredds (dubbel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med halvt breddsteg (enkel byte) +BAHTTEXT = BAHTTEXT ## Omvandlar ett tal till text med valutaformatet ß (baht) +CHAR = TECKENKOD ## Returnerar tecknet som anges av kod +CLEAN = STÄDA ## Tar bort alla icke utskrivbara tecken i en text +CODE = KOD ## Returnerar en numerisk kod för det första tecknet i en textsträng +CONCATENATE = SAMMANFOGA ## Sammanfogar flera textdelar till en textsträng +DOLLAR = VALUTA ## Omvandlar ett tal till text med valutaformat +EXACT = EXAKT ## Kontrollerar om två textvärden är identiska +FIND = HITTA ## Hittar en text i en annan (skiljer på gemener och versaler) +FINDB = HITTAB ## Hittar en text i en annan (skiljer på gemener och versaler) +FIXED = FASTTAL ## Formaterar ett tal som text med ett fast antal decimaler +JIS = JIS ## Ändrar halvbredds (enkel byte) engelska bokstäver eller katakana inom en teckensträng till tecken med helt breddsteg (dubbel byte) +LEFT = VÄNSTER ## Returnerar tecken längst till vänster i en sträng +LEFTB = VÄNSTERB ## Returnerar tecken längst till vänster i en sträng +LEN = LÄNGD ## Returnerar antalet tecken i en textsträng +LENB = LÄNGDB ## Returnerar antalet tecken i en textsträng +LOWER = GEMENER ## Omvandlar text till gemener +MID = EXTEXT ## Returnerar angivet antal tecken från en text med början vid den position som du anger +MIDB = EXTEXTB ## Returnerar angivet antal tecken från en text med början vid den position som du anger +PHONETIC = PHONETIC ## Returnerar de fonetiska (furigana) tecknen i en textsträng +PROPER = INITIAL ## Ändrar första bokstaven i varje ord i ett textvärde till versal +REPLACE = ERSÄTT ## Ersätter tecken i text +REPLACEB = ERSÄTTB ## Ersätter tecken i text +REPT = REP ## Upprepar en text ett bestämt antal gånger +RIGHT = HÖGER ## Returnerar tecken längst till höger i en sträng +RIGHTB = HÖGERB ## Returnerar tecken längst till höger i en sträng +SEARCH = SÖK ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) +SEARCHB = SÖKB ## Hittar ett textvärde i ett annat (skiljer inte på gemener och versaler) +SUBSTITUTE = BYT.UT ## Ersätter gammal text med ny text i en textsträng +T = T ## Omvandlar argumenten till text +TEXT = TEXT ## Formaterar ett tal och omvandlar det till text +TRIM = RENSA ## Tar bort blanksteg från text +UPPER = VERSALER ## Omvandlar text till versaler +VALUE = TEXTNUM ## Omvandlar ett textargument till ett tal diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/config b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/config new file mode 100644 index 00000000..b69d4257 --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/config @@ -0,0 +1,47 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Settings +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## + + +ArgumentSeparator = ; + + +## +## (For future use) +## +currencySymbol = YTL + + +## +## Excel Error Codes (For future use) +## +NULL = #BOŞ! +DIV0 = #SAYI/0! +VALUE = #DEĞER! +REF = #BAŞV! +NAME = #AD? +NUM = #SAYI! +NA = #YOK diff --git a/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/functions b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/functions new file mode 100644 index 00000000..45d7df1f --- /dev/null +++ b/application/third_party/tripadvisor_spider/controllers/PHPExcel/locale/tr/functions @@ -0,0 +1,438 @@ +## +## PHPExcel +## +## Copyright (c) 2006 - 2013 PHPExcel +## +## 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA +## +## @category PHPExcel +## @package PHPExcel_Calculation +## @copyright Copyright (c) 2006 - 2013 PHPExcel (http://www.codeplex.com/PHPExcel) +## @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL +## @version ##VERSION##, ##DATE## +## +## Data in this file derived from http://www.piuha.fi/excel-function-name-translation/ +## +## + + +## +## Add-in and Automation functions Eklenti ve Otomasyon fonksiyonları +## +GETPIVOTDATA = ÖZETVERİAL ## Bir Özet Tablo raporunda saklanan verileri verir. + + +## +## Cube functions Küp işlevleri +## +CUBEKPIMEMBER = KÜPKPIÜYE ## Kilit performans göstergesi (KPI-Key Performance Indicator) adını, özelliğini ve ölçüsünü verir ve hücredeki ad ve özelliği gösterir. KPI, bir kurumun performansını izlemek için kullanılan aylık brüt kâr ya da üç aylık çalışan giriş çıkışları gibi ölçülebilen bir birimdir. +CUBEMEMBER = KÜPÜYE ## Bir küp hiyerarşisinde bir üyeyi veya kaydı verir. Üye veya kaydın küpte varolduğunu doğrulamak için kullanılır. +CUBEMEMBERPROPERTY = KÜPÜYEÖZELLİĞİ ## Bir küpte bir üyenin özelliğinin değerini verir. Küp içinde üye adının varlığını doğrulamak ve bu üyenin belli özelliklerini getirmek için kullanılır. +CUBERANKEDMEMBER = KÜPÜYESIRASI ## Bir küme içindeki üyenin derecesini veya kaçıncı olduğunu verir. En iyi satış elemanı, veya en iyi on öğrenci gibi bir kümedeki bir veya daha fazla öğeyi getirmek için kullanılır. +CUBESET = KÜPKÜME ## Kümeyi oluşturan ve ardından bu kümeyi Microsoft Office Excel'e getiren sunucudaki küpe küme ifadelerini göndererek hesaplanan üye veya kayıt kümesini tanımlar. +CUBESETCOUNT = KÜPKÜMESAY ## Bir kümedeki öğelerin sayısını getirir. +CUBEVALUE = KÜPDEĞER ## Bir küpten toplam değeri getirir. + + +## +## Database functions Veritabanı işlevleri +## +DAVERAGE = VSEÇORT ## Seçili veritabanı girdilerinin ortalamasını verir. +DCOUNT = VSEÇSAY ## Veritabanında sayı içeren hücre sayısını hesaplar. +DCOUNTA = VSEÇSAYDOLU ## Veritabanındaki boş olmayan hücreleri sayar. +DGET = VAL ## Veritabanından, belirtilen ölçütlerle eşleşen tek bir rapor çıkarır. +DMAX = VSEÇMAK ## Seçili veritabanı girişlerinin en yüksek değerini verir. +DMIN = VSEÇMİN ## Seçili veritabanı girişlerinin en düşük değerini verir. +DPRODUCT = VSEÇÇARP ## Kayıtların belli bir alanında bulunan, bir veritabanındaki ölçütlerle eşleşen değerleri çarpar. +DSTDEV = VSEÇSTDSAPMA ## Seçili veritabanı girişlerinden oluşan bir örneğe dayanarak, standart sapmayı tahmin eder. +DSTDEVP = VSEÇSTDSAPMAS ## Standart sapmayı, seçili veritabanı girişlerinin tüm popülasyonunu esas alarak hesaplar. +DSUM = VSEÇTOPLA ## Kayıtların alan sütununda bulunan, ölçütle eşleşen sayıları toplar. +DVAR = VSEÇVAR ## Seçili veritabanı girişlerinden oluşan bir örneği esas alarak farkı tahmin eder. +DVARP = VSEÇVARS ## Seçili veritabanı girişlerinin tüm popülasyonunu esas alarak farkı hesaplar. + + +## +## Date and time functions Tarih ve saat işlevleri +## +DATE = TARİH ## Belirli bir tarihin seri numarasını verir. +DATEVALUE = TARİHSAYISI ## Metin biçimindeki bir tarihi seri numarasına dönüştürür. +DAY = GÜN ## Seri numarasını, ayın bir gününe dönüştürür. +DAYS360 = GÜN360 ## İki tarih arasındaki gün sayısını, 360 günlük yılı esas alarak hesaplar. +EDATE = SERİTARİH ## Başlangıç tarihinden itibaren, belirtilen ay sayısından önce veya sonraki tarihin seri numarasını verir. +EOMONTH = SERİAY ## Belirtilen sayıda ay önce veya sonraki ayın son gününün seri numarasını verir. +HOUR = SAAT ## Bir seri numarasını saate dönüştürür. +MINUTE = DAKİKA ## Bir seri numarasını dakikaya dönüştürür. +MONTH = AY ## Bir seri numarasını aya dönüştürür. +NETWORKDAYS = TAMİŞGÜNÜ ## İki tarih arasındaki tam çalışma günlerinin sayısını verir. +NOW = ŞİMDİ ## Geçerli tarihin ve saatin seri numarasını verir. +SECOND = SANİYE ## Bir seri numarasını saniyeye dönüştürür. +TIME = ZAMAN ## Belirli bir zamanın seri numarasını verir. +TIMEVALUE = ZAMANSAYISI ## Metin biçimindeki zamanı seri numarasına dönüştürür. +TODAY = BUGÜN ## Bugünün tarihini seri numarasına dönüştürür. +WEEKDAY = HAFTANINGÜNÜ ## Bir seri numarasını, haftanın gününe dönüştürür. +WEEKNUM = HAFTASAY ## Dizisel değerini, haftanın yıl içinde bulunduğu konumu sayısal olarak gösteren sayıya dönüştürür. +WORKDAY = İŞGÜNÜ ## Belirtilen sayıda çalışma günü öncesinin ya da sonrasının tarihinin seri numarasını verir. +YEAR = YIL ## Bir seri numarasını yıla dönüştürür. +YEARFRAC = YILORAN ## Başlangıç_tarihi ve bitiş_tarihi arasındaki tam günleri gösteren yıl kesrini verir. + + +## +## Engineering functions Mühendislik işlevleri +## +BESSELI = BESSELI ## Değiştirilmiş Bessel fonksiyonu In(x)'i verir. +BESSELJ = BESSELJ ## Bessel fonksiyonu Jn(x)'i verir. +BESSELK = BESSELK ## Değiştirilmiş Bessel fonksiyonu Kn(x)'i verir. +BESSELY = BESSELY ## Bessel fonksiyonu Yn(x)'i verir. +BIN2DEC = BIN2DEC ## İkili bir sayıyı, ondalık sayıya dönüştürür. +BIN2HEX = BIN2HEX ## İkili bir sayıyı, onaltılıya dönüştürür. +BIN2OCT = BIN2OCT ## İkili bir sayıyı, sekizliye dönüştürür. +COMPLEX = KARMAŞIK ## Gerçek ve sanal katsayıları, karmaşık sayıya dönüştürür. +CONVERT = ÇEVİR ## Bir sayıyı, bir ölçüm sisteminden bir başka ölçüm sistemine dönüştürür. +DEC2BIN = DEC2BIN ## Ondalık bir sayıyı, ikiliye dönüştürür. +DEC2HEX = DEC2HEX ## Ondalık bir sayıyı, onaltılıya dönüştürür. +DEC2OCT = DEC2OCT ## Ondalık bir sayıyı sekizliğe dönüştürür. +DELTA = DELTA ## İki değerin eşit olup olmadığını sınar. +ERF = HATAİŞLEV ## Hata işlevini verir. +ERFC = TÜMHATAİŞLEV ## Tümleyici hata işlevini verir. +GESTEP = BESINIR ## Bir sayının eşik değerinden büyük olup olmadığını sınar. +HEX2BIN = HEX2BIN ## Onaltılı bir sayıyı ikiliye dönüştürür. +HEX2DEC = HEX2DEC ## Onaltılı bir sayıyı ondalığa dönüştürür. +HEX2OCT = HEX2OCT ## Onaltılı bir sayıyı sekizliğe dönüştürür. +IMABS = SANMUTLAK ## Karmaşık bir sayının mutlak değerini (modül) verir. +IMAGINARY = SANAL ## Karmaşık bir sayının sanal katsayısını verir. +IMARGUMENT = SANBAĞ_DEĞİŞKEN ## Radyanlarla belirtilen bir açı olan teta bağımsız değişkenini verir. +IMCONJUGATE = SANEŞLENEK ## Karmaşık bir sayının karmaşık eşleniğini verir. +IMCOS = SANCOS ## Karmaşık bir sayının kosinüsünü verir. +IMDIV = SANBÖL ## İki karmaşık sayının bölümünü verir. +IMEXP = SANÜS ## Karmaşık bir sayının üssünü verir. +IMLN = SANLN ## Karmaşık bir sayının doğal logaritmasını verir. +IMLOG10 = SANLOG10 ## Karmaşık bir sayının, 10 tabanında logaritmasını verir. +IMLOG2 = SANLOG2 ## Karmaşık bir sayının 2 tabanında logaritmasını verir. +IMPOWER = SANÜSSÜ ## Karmaşık bir sayıyı, bir tamsayı üssüne yükseltilmiş olarak verir. +IMPRODUCT = SANÇARP ## Karmaşık sayıların çarpımını verir. +IMREAL = SANGERÇEK ## Karmaşık bir sayının, gerçek katsayısını verir. +IMSIN = SANSIN ## Karmaşık bir sayının sinüsünü verir. +IMSQRT = SANKAREKÖK ## Karmaşık bir sayının karekökünü verir. +IMSUB = SANÇIKAR ## İki karmaşık sayının farkını verir. +IMSUM = SANTOPLA ## Karmaşık sayıların toplamını verir. +OCT2BIN = OCT2BIN ## Sekizli bir sayıyı ikiliye dönüştürür. +OCT2DEC = OCT2DEC ## Sekizli bir sayıyı ondalığa dönüştürür. +OCT2HEX = OCT2HEX ## Sekizli bir sayıyı onaltılıya dönüştürür. + + +## +## Financial functions Finansal fonksiyonlar +## +ACCRINT = GERÇEKFAİZ ## Dönemsel faiz ödeyen hisse senedine ilişkin tahakkuk eden faizi getirir. +ACCRINTM = GERÇEKFAİZV ## Vadesinde ödeme yapan bir tahvilin tahakkuk etmiş faizini verir. +AMORDEGRC = AMORDEGRC ## Yıpranma katsayısı kullanarak her hesap döneminin değer kaybını verir. +AMORLINC = AMORLINC ## Her hesap dönemi içindeki yıpranmayı verir. +COUPDAYBS = KUPONGÜNBD ## Kupon süresinin başlangıcından alış tarihine kadar olan süredeki gün sayısını verir. +COUPDAYS = KUPONGÜN ## Kupon süresindeki, gün sayısını, alış tarihini de içermek üzere, verir. +COUPDAYSNC = KUPONGÜNDSK ## Alış tarihinden bir sonraki kupon tarihine kadar olan gün sayısını verir. +COUPNCD = KUPONGÜNSKT ## Alış tarihinden bir sonraki kupon tarihini verir. +COUPNUM = KUPONSAYI ## Alış tarihiyle vade tarihi arasında ödenecek kuponların sayısını verir. +COUPPCD = KUPONGÜNÖKT ## Alış tarihinden bir önceki kupon tarihini verir. +CUMIPMT = AİÇVERİMORANI ## İki dönem arasında ödenen kümülatif faizi verir. +CUMPRINC = ANA_PARA_ÖDEMESİ ## İki dönem arasında bir borç üzerine ödenen birikimli temeli verir. +DB = AZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, sabit azalan bakiye yöntemini kullanarak verir. +DDB = ÇİFTAZALANBAKİYE ## Bir malın belirtilen bir süre içindeki yıpranmasını, çift azalan bakiye yöntemi ya da sizin belirttiğiniz başka bir yöntemi kullanarak verir. +DISC = İNDİRİM ## Bir tahvilin indirim oranını verir. +DOLLARDE = LİRAON ## Kesir olarak tanımlanmış lira fiyatını, ondalık sayı olarak tanımlanmış lira fiyatına dönüştürür. +DOLLARFR = LİRAKES ## Ondalık sayı olarak tanımlanmış lira fiyatını, kesir olarak tanımlanmış lira fiyatına dönüştürür. +DURATION = SÜRE ## Belli aralıklarla faiz ödemesi yapan bir tahvilin yıllık süresini verir. +EFFECT = ETKİN ## Efektif yıllık faiz oranını verir. +FV = ANBD ## Bir yatırımın gelecekteki değerini verir. +FVSCHEDULE = GDPROGRAM ## Bir seri birleşik faiz oranı uyguladıktan sonra, bir başlangıçtaki anaparanın gelecekteki değerini verir. +INTRATE = FAİZORANI ## Tam olarak yatırım yapılmış bir tahvilin faiz oranını verir. +IPMT = FAİZTUTARI ## Bir yatırımın verilen bir süre için faiz ödemesini verir. +IRR = İÇ_VERİM_ORANI ## Bir para akışı serisi için, iç verim oranını verir. +ISPMT = ISPMT ## Yatırımın belirli bir dönemi boyunca ödenen faizi hesaplar. +MDURATION = MSÜRE ## Varsayılan par değeri 10.000.000 lira olan bir tahvil için Macauley değiştirilmiş süreyi verir. +MIRR = D_İÇ_VERİM_ORANI ## Pozitif ve negatif para akışlarının farklı oranlarda finanse edildiği durumlarda, iç verim oranını verir. +NOMINAL = NOMİNAL ## Yıllık nominal faiz oranını verir. +NPER = DÖNEM_SAYISI ## Bir yatırımın dönem sayısını verir. +NPV = NBD ## Bir yatırımın bugünkü net değerini, bir dönemsel para akışları serisine ve bir indirim oranına bağlı olarak verir. +ODDFPRICE = TEKYDEĞER ## Tek bir ilk dönemi olan bir tahvilin değerini, her 100.000.000 lirada bir verir. +ODDFYIELD = TEKYÖDEME ## Tek bir ilk dönemi olan bir tahvilin ödemesini verir. +ODDLPRICE = TEKSDEĞER ## Tek bir son dönemi olan bir tahvilin fiyatını her 10.000.000 lirada bir verir. +ODDLYIELD = TEKSÖDEME ## Tek bir son dönemi olan bir tahvilin ödemesini verir. +PMT = DEVRESEL_ÖDEME ## Bir yıllık dönemsel ödemeyi verir. +PPMT = ANA_PARA_ÖDEMESİ ## Verilen bir süre için, bir yatırımın anaparasına dayanan ödemeyi verir. +PRICE = DEĞER ## Dönemsel faiz ödeyen bir tahvilin fiyatını 10.000.00 liralık değer başına verir. +PRICEDISC = DEĞERİND ## İndirimli bir tahvilin fiyatını 10.000.000 liralık nominal değer başına verir. +PRICEMAT = DEĞERVADE ## Faizini vade sonunda ödeyen bir tahvilin fiyatını 10.000.000 nominal değer başına verir. +PV = BD ## Bir yatırımın bugünkü değerini verir. +RATE = FAİZ_ORANI ## Bir yıllık dönem başına düşen faiz oranını verir. +RECEIVED = GETİRİ ## Tam olarak yatırılmış bir tahvilin vadesinin bitiminde alınan miktarı verir. +SLN = DA ## Bir malın bir dönem içindeki doğrusal yıpranmasını verir. +SYD = YAT ## Bir malın belirli bir dönem için olan amortismanını verir. +TBILLEQ = HTAHEŞ ## Bir Hazine bonosunun bono eşdeğeri ödemesini verir. +TBILLPRICE = HTAHDEĞER ## Bir Hazine bonosunun değerini, 10.000.000 liralık nominal değer başına verir. +TBILLYIELD = HTAHÖDEME ## Bir Hazine bonosunun ödemesini verir. +VDB = DAB ## Bir malın amortismanını, belirlenmiş ya da kısmi bir dönem için, bir azalan bakiye yöntemi kullanarak verir. +XIRR = AİÇVERİMORANI ## Dönemsel olması gerekmeyen bir para akışları programı için, iç verim oranını verir. +XNPV = ANBD ## Dönemsel olması gerekmeyen bir para akışları programı için, bugünkü net değeri verir. +YIELD = ÖDEME ## Belirli aralıklarla faiz ödeyen bir tahvilin ödemesini verir. +YIELDDISC = ÖDEMEİND ## İndirimli bir tahvilin yıllık ödemesini verir; örneğin, bir Hazine bonosunun. +YIELDMAT = ÖDEMEVADE ## Vadesinin bitiminde faiz ödeyen bir tahvilin yıllık ödemesini verir. + + +## +## Information functions Bilgi fonksiyonları +## +CELL = HÜCRE ## Bir hücrenin biçimlendirmesi, konumu ya da içeriği hakkında bilgi verir. +ERROR.TYPE = HATA.TİPİ ## Bir hata türüne ilişkin sayıları verir. +INFO = BİLGİ ## Geçerli işletim ortamı hakkında bilgi verir. +ISBLANK = EBOŞSA ## Değer boşsa, DOĞRU verir. +ISERR = EHATA ## Değer, #YOK dışındaki bir hata değeriyse, DOĞRU verir. +ISERROR = EHATALIYSA ## Değer, herhangi bir hata değeriyse, DOĞRU verir. +ISEVEN = ÇİFTTİR ## Sayı çiftse, DOĞRU verir. +ISLOGICAL = EMANTIKSALSA ## Değer, mantıksal bir değerse, DOĞRU verir. +ISNA = EYOKSA ## Değer, #YOK hata değeriyse, DOĞRU verir. +ISNONTEXT = EMETİNDEĞİLSE ## Değer, metin değilse, DOĞRU verir. +ISNUMBER = ESAYIYSA ## Değer, bir sayıysa, DOĞRU verir. +ISODD = TEKTİR ## Sayı tekse, DOĞRU verir. +ISREF = EREFSE ## Değer bir başvuruysa, DOĞRU verir. +ISTEXT = EMETİNSE ## Değer bir metinse DOĞRU verir. +N = N ## Sayıya dönüştürülmüş bir değer verir. +NA = YOKSAY ## #YOK hata değerini verir. +TYPE = TİP ## Bir değerin veri türünü belirten bir sayı verir. + + +## +## Logical functions Mantıksal fonksiyonlar +## +AND = VE ## Bütün bağımsız değişkenleri DOĞRU ise, DOĞRU verir. +FALSE = YANLIŞ ## YANLIŞ mantıksal değerini verir. +IF = EĞER ## Gerçekleştirilecek bir mantıksal sınama belirtir. +IFERROR = EĞERHATA ## Formül hatalıysa belirttiğiniz değeri verir; bunun dışındaki durumlarda formülün sonucunu verir. +NOT = DEĞİL ## Bağımsız değişkeninin mantığını tersine çevirir. +OR = YADA ## Bağımsız değişkenlerden herhangi birisi DOĞRU ise, DOĞRU verir. +TRUE = DOĞRU ## DOĞRU mantıksal değerini verir. + + +## +## Lookup and reference functions Arama ve Başvuru fonksiyonları +## +ADDRESS = ADRES ## Bir başvuruyu, çalışma sayfasındaki tek bir hücreye metin olarak verir. +AREAS = ALANSAY ## Renvoie le nombre de zones dans une référence. +CHOOSE = ELEMAN ## Değerler listesinden bir değer seçer. +COLUMN = SÜTUN ## Bir başvurunun sütun sayısını verir. +COLUMNS = SÜTUNSAY ## Bir başvurudaki sütunların sayısını verir. +HLOOKUP = YATAYARA ## Bir dizinin en üst satırına bakar ve belirtilen hücrenin değerini verir. +HYPERLINK = KÖPRÜ ## Bir ağ sunucusunda, bir intranette ya da Internet'te depolanan bir belgeyi açan bir kısayol ya da atlama oluşturur. +INDEX = İNDİS ## Başvurudan veya diziden bir değer seçmek için, bir dizin kullanır. +INDIRECT = DOLAYLI ## Metin değeriyle belirtilen bir başvuru verir. +LOOKUP = ARA ## Bir vektördeki veya dizideki değerleri arar. +MATCH = KAÇINCI ## Bir başvurudaki veya dizideki değerleri arar. +OFFSET = KAYDIR ## Verilen bir başvurudan, bir başvuru kaydırmayı verir. +ROW = SATIR ## Bir başvurunun satır sayısını verir. +ROWS = SATIRSAY ## Bir başvurudaki satırların sayısını verir. +RTD = RTD ## COM otomasyonunu destekleyen programdan gerçek zaman verileri alır. +TRANSPOSE = DEVRİK_DÖNÜŞÜM ## Bir dizinin devrik dönüşümünü verir. +VLOOKUP = DÜŞEYARA ## Bir dizinin ilk sütununa bakar ve bir hücrenin değerini vermek için satır boyunca hareket eder. + + +## +## Math and trigonometry functions Matematik ve trigonometri fonksiyonları +## +ABS = MUTLAK ## Bir sayının mutlak değerini verir. +ACOS = ACOS ## Bir sayının ark kosinüsünü verir. +ACOSH = ACOSH ## Bir sayının ters hiperbolik kosinüsünü verir. +ASIN = ASİN ## Bir sayının ark sinüsünü verir. +ASINH = ASİNH ## Bir sayının ters hiperbolik sinüsünü verir. +ATAN = ATAN ## Bir sayının ark tanjantını verir. +ATAN2 = ATAN2 ## Ark tanjantı, x- ve y- koordinatlarından verir. +ATANH = ATANH ## Bir sayının ters hiperbolik tanjantını verir. +CEILING = TAVANAYUVARLA ## Bir sayıyı, en yakın tamsayıya ya da en yakın katına yuvarlar. +COMBIN = KOMBİNASYON ## Verilen sayıda öğenin kombinasyon sayısını verir. +COS = COS ## Bir sayının kosinüsünü verir. +COSH = COSH ## Bir sayının hiperbolik kosinüsünü verir. +DEGREES = DERECE ## Radyanları dereceye dönüştürür. +EVEN = ÇİFT ## Bir sayıyı, en yakın daha büyük çift tamsayıya yuvarlar. +EXP = ÜS ## e'yi, verilen bir sayının üssüne yükseltilmiş olarak verir. +FACT = ÇARPINIM ## Bir sayının faktörünü verir. +FACTDOUBLE = ÇİFTFAKTÖR ## Bir sayının çift çarpınımını verir. +FLOOR = TABANAYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. +GCD = OBEB ## En büyük ortak böleni verir. +INT = TAMSAYI ## Bir sayıyı aşağıya doğru en yakın tamsayıya yuvarlar. +LCM = OKEK ## En küçük ortak katı verir. +LN = LN ## Bir sayının doğal logaritmasını verir. +LOG = LOG ## Bir sayının, belirtilen bir tabandaki logaritmasını verir. +LOG10 = LOG10 ## Bir sayının 10 tabanında logaritmasını verir. +MDETERM = DETERMİNANT ## Bir dizinin dizey determinantını verir. +MINVERSE = DİZEY_TERS ## Bir dizinin dizey tersini verir. +MMULT = DÇARP ## İki dizinin dizey çarpımını verir. +MOD = MODÜLO ## Bölmeden kalanı verir. +MROUND = KYUVARLA ## İstenen kata yuvarlanmış bir sayı verir. +MULTINOMIAL = ÇOKTERİMLİ ## Bir sayılar kümesinin çok terimlisini verir. +ODD = TEK ## Bir sayıyı en yakın daha büyük tek sayıya yuvarlar. +PI = Pİ ## Pi değerini verir. +POWER = KUVVET ## Bir üsse yükseltilmiş sayının sonucunu verir. +PRODUCT = ÇARPIM ## Bağımsız değişkenlerini çarpar. +QUOTIENT = BÖLÜM ## Bir bölme işleminin tamsayı kısmını verir. +RADIANS = RADYAN ## Dereceleri radyanlara dönüştürür. +RAND = S_SAYI_ÜRET ## 0 ile 1 arasında rastgele bir sayı verir. +RANDBETWEEN = RASTGELEARALIK ## Belirttiğiniz sayılar arasında rastgele bir sayı verir. +ROMAN = ROMEN ## Bir normal rakamı, metin olarak, romen rakamına çevirir. +ROUND = YUVARLA ## Bir sayıyı, belirtilen basamak sayısına yuvarlar. +ROUNDDOWN = AŞAĞIYUVARLA ## Bir sayıyı, daha küçük sayıya, sıfıra yakınsayarak yuvarlar. +ROUNDUP = YUKARIYUVARLA ## Bir sayıyı daha büyük sayıya, sıfırdan ıraksayarak yuvarlar. +SERIESSUM = SERİTOPLA ## Bir üs serisinin toplamını, formüle bağlı olarak verir. +SIGN = İŞARET ## Bir sayının işaretini verir. +SIN = SİN ## Verilen bir açının sinüsünü verir. +SINH = SİNH ## Bir sayının hiperbolik sinüsünü verir. +SQRT = KAREKÖK ## Pozitif bir karekök verir. +SQRTPI = KAREKÖKPİ ## (* Pi sayısının) kare kökünü verir. +SUBTOTAL = ALTTOPLAM ## Bir listedeki ya da veritabanındaki bir alt toplamı verir. +SUM = TOPLA ## Bağımsız değişkenlerini toplar. +SUMIF = ETOPLA ## Verilen ölçütle belirlenen hücreleri toplar. +SUMIFS = SUMIFS ## Bir aralıktaki, birden fazla ölçüte uyan hücreleri ekler. +SUMPRODUCT = TOPLA.ÇARPIM ## İlişkili dizi bileşenlerinin çarpımlarının toplamını verir. +SUMSQ = TOPKARE ## Bağımsız değişkenlerin karelerinin toplamını verir. +SUMX2MY2 = TOPX2EY2 ## İki dizideki ilişkili değerlerin farkının toplamını verir. +SUMX2PY2 = TOPX2AY2 ## İki dizideki ilişkili değerlerin karelerinin toplamının toplamını verir. +SUMXMY2 = TOPXEY2 ## İki dizideki ilişkili değerlerin farklarının karelerinin toplamını verir. +TAN = TAN ## Bir sayının tanjantını verir. +TANH = TANH ## Bir sayının hiperbolik tanjantını verir. +TRUNC = NSAT ## Bir sayının, tamsayı durumuna gelecek şekilde, fazlalıklarını atar. + + +## +## Statistical functions İstatistiksel fonksiyonlar +## +AVEDEV = ORTSAP ## Veri noktalarının ortalamalarından mutlak sapmalarının ortalamasını verir. +AVERAGE = ORTALAMA ## Bağımsız değişkenlerinin ortalamasını verir. +AVERAGEA = ORTALAMAA ## Bağımsız değişkenlerinin, sayılar, metin ve mantıksal değerleri içermek üzere ortalamasını verir. +AVERAGEIF = EĞERORTALAMA ## Verili ölçütü karşılayan bir aralıktaki bütün hücrelerin ortalamasını (aritmetik ortalama) hesaplar. +AVERAGEIFS = EĞERLERORTALAMA ## Birden çok ölçüte uyan tüm hücrelerin ortalamasını (aritmetik ortalama) hesaplar. +BETADIST = BETADAĞ ## Beta birikimli dağılım fonksiyonunu verir. +BETAINV = BETATERS ## Belirli bir beta dağılımı için birikimli dağılım fonksiyonunun tersini verir. +BINOMDIST = BİNOMDAĞ ## Tek terimli binom dağılımı olasılığını verir. +CHIDIST = KİKAREDAĞ ## Kikare dağılımın tek kuyruklu olasılığını verir. +CHIINV = KİKARETERS ## Kikare dağılımın kuyruklu olasılığının tersini verir. +CHITEST = KİKARETEST ## Bağımsızlık sınamalarını verir. +CONFIDENCE = GÜVENİRLİK ## Bir popülasyon ortalaması için güvenirlik aralığını verir. +CORREL = KORELASYON ## İki veri kümesi arasındaki bağlantı katsayısını verir. +COUNT = BAĞ_DEĞ_SAY ## Bağımsız değişkenler listesinde kaç tane sayı bulunduğunu sayar. +COUNTA = BAĞ_DEĞ_DOLU_SAY ## Bağımsız değişkenler listesinde kaç tane değer bulunduğunu sayar. +COUNTBLANK = BOŞLUKSAY ## Aralıktaki boş hücre sayısını hesaplar. +COUNTIF = EĞERSAY ## Verilen ölçütlere uyan bir aralık içindeki hücreleri sayar. +COUNTIFS = ÇOKEĞERSAY ## Birden çok ölçüte uyan bir aralık içindeki hücreleri sayar. +COVAR = KOVARYANS ## Eşleştirilmiş sapmaların ortalaması olan kovaryansı verir. +CRITBINOM = KRİTİKBİNOM ## Birikimli binom dağılımının bir ölçüt değerinden küçük veya ölçüt değerine eşit olduğu en küçük değeri verir. +DEVSQ = SAPKARE ## Sapmaların karelerinin toplamını verir. +EXPONDIST = ÜSTELDAĞ ## Üstel dağılımı verir. +FDIST = FDAĞ ## F olasılık dağılımını verir. +FINV = FTERS ## F olasılık dağılımının tersini verir. +FISHER = FISHER ## Fisher dönüşümünü verir. +FISHERINV = FISHERTERS ## Fisher dönüşümünün tersini verir. +FORECAST = TAHMİN ## Bir doğrusal eğilim boyunca bir değer verir. +FREQUENCY = SIKLIK ## Bir sıklık dağılımını, dikey bir dizi olarak verir. +FTEST = FTEST ## Bir F-test'in sonucunu verir. +GAMMADIST = GAMADAĞ ## Gama dağılımını verir. +GAMMAINV = GAMATERS ## Gama kümülatif dağılımının tersini verir. +GAMMALN = GAMALN ## Gama fonksiyonunun (?(x)) doğal logaritmasını verir. +GEOMEAN = GEOORT ## Geometrik ortayı verir. +GROWTH = BÜYÜME ## Üstel bir eğilim boyunca değerler verir. +HARMEAN = HARORT ## Harmonik ortayı verir. +HYPGEOMDIST = HİPERGEOMDAĞ ## Hipergeometrik dağılımı verir. +INTERCEPT = KESMENOKTASI ## Doğrusal çakıştırma çizgisinin kesişme noktasını verir. +KURT = BASIKLIK ## Bir veri kümesinin basıklığını verir. +LARGE = BÜYÜK ## Bir veri kümesinde k. en büyük değeri verir. +LINEST = DOT ## Doğrusal bir eğilimin parametrelerini verir. +LOGEST = LOT ## Üstel bir eğilimin parametrelerini verir. +LOGINV = LOGTERS ## Bir lognormal dağılımının tersini verir. +LOGNORMDIST = LOGNORMDAĞ ## Birikimli lognormal dağılımını verir. +MAX = MAK ## Bir bağımsız değişkenler listesindeki en büyük değeri verir. +MAXA = MAKA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri içermek üzere, en büyük değeri verir. +MEDIAN = ORTANCA ## Belirtilen sayıların orta değerini verir. +MIN = MİN ## Bir bağımsız değişkenler listesindeki en küçük değeri verir. +MINA = MİNA ## Bir bağımsız değişkenler listesindeki, sayılar, metin ve mantıksal değerleri de içermek üzere, en küçük değeri verir. +MODE = ENÇOK_OLAN ## Bir veri kümesindeki en sık rastlanan değeri verir. +NEGBINOMDIST = NEGBİNOMDAĞ ## Negatif binom dağılımını verir. +NORMDIST = NORMDAĞ ## Normal birikimli dağılımı verir. +NORMINV = NORMTERS ## Normal kümülatif dağılımın tersini verir. +NORMSDIST = NORMSDAĞ ## Standart normal birikimli dağılımı verir. +NORMSINV = NORMSTERS ## Standart normal birikimli dağılımın tersini verir. +PEARSON = PEARSON ## Pearson çarpım moment korelasyon katsayısını verir. +PERCENTILE = YÜZDEBİRLİK ## Bir aralık içerisinde bulunan değerlerin k. frekans toplamını verir. +PERCENTRANK = YÜZDERANK ## Bir veri kümesindeki bir değerin yüzde mertebesini verir. +PERMUT = PERMÜTASYON ## Verilen sayıda nesne için permütasyon sayısını verir. +POISSON = POISSON ## Poisson dağılımını verir. +PROB = OLASILIK ## Bir aralıktaki değerlerin iki sınır arasında olması olasılığını verir. +QUARTILE = DÖRTTEBİRLİK ## Bir veri kümesinin dörtte birliğini verir. +RANK = RANK ## Bir sayılar listesinde bir sayının mertebesini verir. +RSQ = RKARE ## Pearson çarpım moment korelasyon katsayısının karesini verir. +SKEW = ÇARPIKLIK ## Bir dağılımın çarpıklığını verir. +SLOPE = EĞİM ## Doğrusal çakışma çizgisinin eğimini verir. +SMALL = KÜÇÜK ## Bir veri kümesinde k. en küçük değeri verir. +STANDARDIZE = STANDARTLAŞTIRMA ## Normalleştirilmiş bir değer verir. +STDEV = STDSAPMA ## Bir örneğe dayanarak standart sapmayı tahmin eder. +STDEVA = STDSAPMAA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. +STDEVP = STDSAPMAS ## Standart sapmayı, tüm popülasyona bağlı olarak hesaplar. +STDEVPA = STDSAPMASA ## Standart sapmayı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. +STEYX = STHYX ## Regresyondaki her x için tahmini y değerinin standart hatasını verir. +TDIST = TDAĞ ## T-dağılımını verir. +TINV = TTERS ## T-dağılımının tersini verir. +TREND = EĞİLİM ## Doğrusal bir eğilim boyunca değerler verir. +TRIMMEAN = KIRPORTALAMA ## Bir veri kümesinin içinin ortalamasını verir. +TTEST = TTEST ## T-test'le ilişkilendirilmiş olasılığı verir. +VAR = VAR ## Varyansı, bir örneğe bağlı olarak tahmin eder. +VARA = VARA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, bir örneğe bağlı olarak tahmin eder. +VARP = VARS ## Varyansı, tüm popülasyona dayanarak hesaplar. +VARPA = VARSA ## Varyansı, sayılar, metin ve mantıksal değerleri içermek üzere, tüm popülasyona bağlı olarak hesaplar. +WEIBULL = WEIBULL ## Weibull dağılımını hesaplar. +ZTEST = ZTEST ## Z-testinin tek kuyruklu olasılık değerini hesaplar. + + +## +## Text functions Metin fonksiyonları +## +ASC = ASC ## Bir karakter dizesindeki çift enli (iki bayt) İngilizce harfleri veya katakanayı yarım enli (tek bayt) karakterlerle değiştirir. +BAHTTEXT = BAHTTEXT ## Sayıyı, ß (baht) para birimi biçimini kullanarak metne dönüştürür. +CHAR = DAMGA ## Kod sayısıyla belirtilen karakteri verir. +CLEAN = TEMİZ ## Metindeki bütün yazdırılamaz karakterleri kaldırır. +CODE = KOD ## Bir metin dizesindeki ilk karakter için sayısal bir kod verir. +CONCATENATE = BİRLEŞTİR ## Pek çok metin öğesini bir metin öğesi olarak birleştirir. +DOLLAR = LİRA ## Bir sayıyı YTL (yeni Türk lirası) para birimi biçimini kullanarak metne dönüştürür. +EXACT = ÖZDEŞ ## İki metin değerinin özdeş olup olmadığını anlamak için, değerleri denetler. +FIND = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). +FINDB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlıdır). +FIXED = SAYIDÜZENLE ## Bir sayıyı, sabit sayıda ondalıkla, metin olarak biçimlendirir. +JIS = JIS ## Bir karakter dizesindeki tek enli (tek bayt) İngilizce harfleri veya katakanayı çift enli (iki bayt) karakterlerle değiştirir. +LEFT = SOL ## Bir metin değerinden en soldaki karakterleri verir. +LEFTB = SOLB ## Bir metin değerinden en soldaki karakterleri verir. +LEN = UZUNLUK ## Bir metin dizesindeki karakter sayısını verir. +LENB = UZUNLUKB ## Bir metin dizesindeki karakter sayısını verir. +LOWER = KÜÇÜKHARF ## Metni küçük harfe çevirir. +MID = ORTA ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. +MIDB = ORTAB ## Bir metin dizesinden belirli sayıda karakteri, belirttiğiniz konumdan başlamak üzere verir. +PHONETIC = SES ## Metin dizesinden ses (furigana) karakterlerini ayıklar. +PROPER = YAZIM.DÜZENİ ## Bir metin değerinin her bir sözcüğünün ilk harfini büyük harfe çevirir. +REPLACE = DEĞİŞTİR ## Metnin içindeki karakterleri değiştirir. +REPLACEB = DEĞİŞTİRB ## Metnin içindeki karakterleri değiştirir. +REPT = YİNELE ## Metni belirtilen sayıda yineler. +RIGHT = SAĞ ## Bir metin değerinden en sağdaki karakterleri verir. +RIGHTB = SAĞB ## Bir metin değerinden en sağdaki karakterleri verir. +SEARCH = BUL ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). +SEARCHB = BULB ## Bir metin değerini, bir başkasının içinde bulur (büyük küçük harf duyarlı değildir). +SUBSTITUTE = YERİNEKOY ## Bir metin dizesinde, eski metnin yerine yeni metin koyar. +T = M ## Bağımsız değerlerini metne dönüştürür. +TEXT = METNEÇEVİR ## Bir sayıyı biçimlendirir ve metne dönüştürür. +TRIM = KIRP ## Metindeki boşlukları kaldırır. +UPPER = BÜYÜKHARF ## Metni büyük harfe çevirir. +VALUE = SAYIYAÇEVİR ## Bir metin bağımsız değişkenini sayıya dönüştürür. diff --git a/application/third_party/tripadvisor_spider/views/third_party_input.php b/application/third_party/tripadvisor_spider/views/third_party_input.php new file mode 100644 index 00000000..0643046e --- /dev/null +++ b/application/third_party/tripadvisor_spider/views/third_party_input.php @@ -0,0 +1,157 @@ +<div class="container"> + <div class="row"> + <div class="panel panel-default"> + <div class="panel-heading"> + <h2 class="text-center">TA数据录入</h2> + </div> + <div class="panel-body"> + <div class="method_select"> + <ul class="nav nav-tabs" role="tablist"> + <li role="presentation" class="active"> + <a href="#handinput" aria-controls="handinput" role="tab" data-toggle="tab">手动录入</a> + </li> + <li role="presentation"> + <a href="#excelinput" aria-controls="excelinput" role="tab" data-toggle="tab">excel导入</a> + </li> + </ul> + <div class="tab-content"> + <div role="tabpanel" class="tab-pane active" id="handinput"> + <div class="row" style="margin-top:10px;"> + <div class="col-md-18"> + <input class="form-control" id="ta_url" type="text" autocomplete="off" /> + </div> + <div class="col-md-6"> + <a href="#" id="contentbyurl" class="btn btn-info">抓取页面</a> + </div> + </div> + <div class="result_view"> + <div class="row"> + <h3 class="text-center">评论抓取预览</h3> + <div class="review_content"> + <div class="col-md-4"> + <p class="review_name"></p> + <p class="review_stars"></p> + </div> + <div class="col-md-20"> + <p class="ta_title"></p> + <p class="ta_content"></p> + <p class="review_date"></p> + </div> + </div> + </div> + </div> + </div> + <div role="tabpanel" class="tab-pane" id="excelinput"> + <div class="row" style="margin-top:10px;"> + <div class="col-md-18"> + <input class="form-control" id="file_excel" type="file" /> + </div> + <div class="col-md-6"> + <a href="#" id="contentbyexcel" class="btn btn-info">导出信息</a> + </div> + </div> + <div class="excel_view"> + <h3 class="text-center">excel数据导出预览</h3> + <div class="excel_content"> + + </div> + </div> + </div> + </div> + </div> + </div> + </div> + </div> +</div> +<script> +$(function(){ + //手动提交获取TA评论 + $('#contentbyurl').click(function(){ + //获取填写的url + var ta_url = $('#ta_url').val(); + var stars = ''; + if(ta_url == ''){ + alert('请填写需要采集的TA地址'); + }else{ + $.ajax({ + url:'/info.php/apps/tripadvisor_spider/index/get_reviews_detail', + data:{url:ta_url}, + success:function(json,status){ + var data = $.parseJSON(json); + console.log(data); + $('.ta_content').html(data.content); + $('.review_date').html('Date of experience: '+data.review_date); + $('.review_name').html(data.review_name); + $('.ta_title').html('<strong>'+data.title+'</strong>'); + if(data.star_nums){ + for(var i=0;i<data.star_nums;i++){ + stars += '<span class="glyphicon glyphicon-star"></span>'; + } + $('.review_stars').html(stars); + } + } + }); + } + }); + + //上传文件 + $('#contentbyexcel').click(function(){ + var fileArray = document.getElementById("file_excel").files; + var formData = new FormData(); + for(var i=0; i<fileArray.length; i++){ + formData.append("fileArray", fileArray[i]); + } + + $.ajax({ + url:'/info.php/apps/tripadvisor_spider/index/analysis_excel', + data: formData, + type: 'post', + cache: false, + contentType: false, + processData: false, + success:function(json,status){ + var jsondata = $.parseJSON(json); + var html = ''; + var j,ta_url; + var num = 0; + for (var i=0;i<jsondata.length;i++){ + for (j in jsondata[i].list_data){ + html += '<div class="row"><div class="col-md-4">'; + html += '<p>'+jsondata[i].destination+'</p>'; + html += '<p>团名:'+jsondata[i].list_data[j][0]+'</p>'; + html += '<p>导游:'+jsondata[i].list_data[j][1]+'</p>'; + html += '<p>发帖账户:'+jsondata[i].list_data[j][3]+'</p>'; + html += '<p>星级:'+jsondata[i].list_data[j][4]+'</p>'; + html += '</div>'; + html += '<div class="col-md-20">'; + html += '<p id="excel_title_'+num+'"></p>'; + html += '<p id="excel_content_'+num+'"></p>'; + ta_url = jsondata[i].list_data[j][2]; + //console.log(ta_url); + if(ta_url.indexOf('ShowUserReviews') != -1){ + $.ajax({ + url:'/info.php/apps/tripadvisor_spider/index/get_reviews_detail', + data:{url:ta_url,html_num:num}, + success:function(json_detail,status){ + var data = $.parseJSON(json_detail); + $('#excel_title_'+data.html_id).html(data.title); + $('#excel_content_'+data.html_id).html(data.content); + console.log(html); + } + }); + + }else{ + html += '<p>'+ta_url+'</p>'; + } + html += '</div></div><hr>'; + num++; + } + + } + //console.log(html); + $('.excel_content').html(html); + } + }); + }); +}); +</script> \ No newline at end of file diff --git a/webht/third_party/messagecenter/controllers/index.php b/webht/third_party/messagecenter/controllers/index.php index 2ac45867..1f8a711f 100644 --- a/webht/third_party/messagecenter/controllers/index.php +++ b/webht/third_party/messagecenter/controllers/index.php @@ -9,15 +9,7 @@ class Index extends CI_Controller { $this->load->helper('message'); $this->key = '3d15821171548bf7d0a93afab66e797b'; $this->sendsms = 'https://yun.tim.qq.com/v5/tlssmssvr/sendsms'; - } - - public function test(){ - echo phpinfo(); - /*try { - echo '1'; - } finally { - echo '2'; - }*/ + $this->db_train_zw = $this->config->item('db_train_zw'); } public function index(){ @@ -176,7 +168,50 @@ class Index extends CI_Controller { $back_data = json_decode($back_json); print_r($back_json); } + + //计算各个事业部使用短信的价格 + public function count_price(){ + $this->load->model('messagecenter_model'); + $from_time = $this->input->get_post('from_time'); + $to_time = $this->input->get_post('to_time'); + + $sms_price_list = array("376"=>"0.0651","971"=>"0.0415","93"=>"0.0731","1268"=>"0.0781","1264"=>"0.0454","355"=>"0.0949","374"=>"0.0813","244"=>"0.0633","54"=>"0.0301","1684"=>"0.1100","43"=>"0.1287","61"=>"0.0804","297"=>"0.0553","994"=>"0.1462","387"=>"0.0772","1246"=>"0.0521","880"=>"0.0846","32"=>"0.0825","226"=>"0.0776","359"=>"0.0737","973"=>"0.0229","257"=>"0.0383","229"=>"0.0498","1441"=>"0.0548","673"=>"0.0173","591"=>"0.0649","599"=>"0.0443","55"=>"0.0167","1242"=>"0.0390","975"=>"0.0396","267"=>"0.0427","375"=>"0.0638","501"=>"0.0330","1"=>"0.0080","243"=>"0.0513","236"=>"0.0633","242"=>"0.0664","41"=>"0.0712","225"=>"0.0819","682"=>"0.0403","56"=>"0.0680","237"=>"0.0548","57"=>"0.0414","506"=>"0.0694","238"=>"0.0869","599"=>"0.0489","357"=>"0.0335","420"=>"0.0801","49"=>"0.1000","253"=>"0.1106","45"=>"0.0532","1767"=>".0550","1809"=>"0.0519","213"=>"0.1656","593"=>"0.1068","372"=>"0.1141","20"=>"0.0492","291"=>"0.0915","34"=>"0.0988","251"=>"0.0336","358"=>"0.1390","679"=>"0.0367","691"=>"0.1491","298"=>"0.0158","33"=>"0.0778","241"=>"0.0357","44"=>"0.0464","1473"=>"0.0489","995"=>"0.0218","594"=>"0.1515","233"=>"0.0244","350"=>"0.0201","299"=>"0.0128","220"=>"0.0454","224"=>"0.0884","590"=>"0.2772","240"=>"0.0863","30"=>"0.1013","502"=>"0.0555","1671"=>"0.0564","245"=>"0.0978","592"=>"0.0726","852"=>"0.0448","504"=>"0.0645","385"=>"0.0801","509"=>"0.0848","36"=>"0.1197","62"=>"0.0334","353"=>"0.0824","972"=>"0.0173","91"=>"0.0085","964"=>"0.0611","354"=>"0.0333","39"=>"0.0823","1876"=>"0.0374","962"=>"0.0700","81"=>"0.0750","254"=>"0.0299","996"=>"0.0564","855"=>"0.0561","686"=>"0.0510","269"=>"0.0459","1869"=>"0.0947","82"=>"0.0357","965"=>"0.0518","1345"=>"0.0463","7"=>"0.0783","856"=>"0.0456","961"=>"0.0464","1758"=>"0.0414","423"=>"0.0297","94"=>"0.0690","231"=>"0.0709","266"=>"0.0589","370"=>"0.0419","352"=>"0.0157","371"=>"0.0696","218"=>"0.0569","212"=>"0.0832","377"=>"0.0638","373"=>"0.0954","382"=>"0.0358","261"=>"0.0564","692"=>"0.1323","389"=>"0.0303","223"=>"0.1927","95"=>"0.0940","976"=>"0.0645","853"=>"0.0267","222"=>"0.0800","1664"=>"0.0685","356"=>"0.0316","230"=>"0.0509","960"=>"0.0340","265"=>"0.0486","52"=>"0.0332","60"=>"0.0362","258"=>"0.0315","264"=>"0.0429","687"=>"0.2356","227"=>"0.0769","234"=>"0.0314","505"=>"0.0726","31"=>"0.1564","47"=>"0.0942","977"=>"0.1029","674"=>"0.0842","64"=>"0.1162","968"=>"0.0750","507"=>"0.0723","51"=>"0.0440","689"=>"0.1246","675"=>"0.0692","63"=>"0.0355","92"=>"0.0226","48"=>"0.0411","508"=>"0.0580","1787"=>"0.0564","351"=>"0.0522","680"=>"0.0855","595"=>"0.0306","974"=>"0.0526","262"=>"0.2108","40"=>"0.0744","381"=>"0.0472","7"=>"0.0321","250"=>"0.0366","966"=>"0.0357","677"=>"0.0303","248"=>"0.0644","249"=>"0.0510","46"=>"0.1066","65"=>"0.0380","386"=>"0.0383","421"=>"0.0999","232"=>"0.0305","378"=>"0.0587","221"=>"0.0719","252"=>"0.0873","597"=>"0.0495","239"=>"0.1149","503"=>"0.0574","268"=>"0.0748","1649"=>"0.0411","235"=>"0.0378","228"=>"0.0348","66"=>"0.0192","992"=>"0.0607","670"=>"0.0656","993"=>"0.0580","216"=>"0.1255","676"=>"0.0371","90"=>"0.0090","1868"=>"0.0384","886"=>"0.0540","255"=>"0.0422","380"=>"0.0533","256"=>"0.0776","1"=>"0.0063","598"=>"0.1093","998"=>"0.1411","1784"=>"0.0619","58"=>"0.0203","1284"=>"0.0480","84"=>"0.0399","678"=>"0.0611","685"=>"0.0774","967"=>"0.0284","269"=>"0.1589","27"=>"0.0319","260"=>"0.0422","263"=>"0.0253"); + + $tp_list = $this->messagecenter_model->get_tp_list($from_time,$to_time); + $tp_total_price = 0; + $cht_total_price = 0; + //TP的短信费用 + foreach($tp_list as $tp_item){ + if($tp_item->TPSL_nationCode == '86'){ + $tp_total_price += 2 * 0.1; + }else{ + //echo $sms_price_list[$tp_item->TPSL_nationCode]; + $tp_total_price += (2 * $sms_price_list[$tp_item->TPSL_nationCode]) * 6.7335; + } + } + + //商旅短信费用 + $cht_list = $this->messagecenter_model->get_cht_list($from_time,$to_time); + + foreach($cht_list as $cht_item){ + if($cht_item->nation_code == '86'){ + $cht_total_price += 2 * 0.1; + }else{ + //echo $sms_price_list[$tp_item->TPSL_nationCode]; + $cht_total_price += $sms_price_list[$cht_item->nation_code] * 6.7335; + } + } + + $all_total = $cht_total_price + $tp_total_price; + + /*echo 'tp:'.$tp_total_price.'<br>'; + echo 'cht:'.$cht_total_price.'<br>'; + echo 'total:'.$all_total.'<br>';*/ + + echo '{"tp":"'.$tp_total_price.'","cht":"'.$cht_total_price.'","all_total":"'.$all_total.'"}'; + } + } diff --git a/webht/third_party/messagecenter/models/messagecenter_model.php b/webht/third_party/messagecenter/models/messagecenter_model.php new file mode 100644 index 00000000..dd2060ba --- /dev/null +++ b/webht/third_party/messagecenter/models/messagecenter_model.php @@ -0,0 +1,20 @@ +<?php + +class messagecenter_model extends CI_Model { + function __construct() { + parent::__construct(); + $this->INFO = $this->load->database('INFO', TRUE); + } + + public function get_tp_list($from_time,$to_time){ + $sql = 'select * from trippest_sms_log where TPSL_callbackTime > ? and TPSL_callbackTime < ? and TPSL_sendState = 1'; + $query = $this->INFO->query($sql,array($from_time,$to_time)); + return $query->result(); + } + + public function get_cht_list($from_time,$to_time){ + $sql = 'select * from [syn123].InfoManager.dbo.train_sms_verification where created_on > ? and created_on < ?'; + $query = $this->INFO->query($sql,array($from_time,$to_time)); + return $query->result(); + } +} \ No newline at end of file diff --git a/webht/third_party/messagecenter/views/message_index.php b/webht/third_party/messagecenter/views/message_index.php index 4e70dfd4..e7008d61 100644 --- a/webht/third_party/messagecenter/views/message_index.php +++ b/webht/third_party/messagecenter/views/message_index.php @@ -1,9 +1,12 @@ +<link href="/css/webht/flatpicker.min.css" rel="stylesheet"> +<script src="/js/flatpickr-4.4.4.min.js"></script> <div style="width:90%;margin:30px auto;"> <div class="panel-heading"> <ul class="nav nav-tabs"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Home</a></li> <li role="presentation"><a href="#manager" aria-controls="manager" role="tab" data-toggle="tab">管理页面</a></li> <li role="presentation"><a href="#sendsms" aria-controls="sendsms" role="tab" data-toggle="tab">发送短信页面</a></li> + <li role="presentation"><a href="#count_price" aria-controls="count_price" role="tab" data-toggle="tab">计算费用</a></li> </ul> </div> @@ -48,5 +51,54 @@ <button type="submit" class="btn btn-default">发送短信</button> </form> </div> + + <div role="tabpanel" class="tab-pane" id="count_price"> + <div class="row"> + <div class="col-md-10"> + 起始时间:<input id="from_time" class="form-control"/> + </div> + <div class="col-md-10"> + 截止时间:<input id="to_time" class="form-control"/> + </div> + <div class="col-md-4"> + <a href="#" class="btn btn-default" id="get_price">查询</a> + </div> + </div> + <div class="row" style="margin-top:20px;"> + <div class="col-md-8"> + <p id="tp_price"></p> + </div> + <div class="col-md-8"> + <p id="cht_price"></p> + </div> + <div class="col-md-8"> + <p id="total_price"></p> + </div> + </div> + </div> </div> -</div> \ No newline at end of file +</div> + +<script> +$(function(){ + $('#from_time').flatpickr(); + $('#to_time').flatpickr(); + + $('#get_price').click(function(){ + var from_time = $('#from_time').val(); + var to_time = $('#to_time').val(); + + if(from_time != '' && to_time != ''){ + $.ajax({ + url:'/webht.php/apps/messagecenter/index/count_price?from_time='+from_time+'&to_time='+to_time, + success:function(json,status){ + var data = JSON.parse(json); + $('#tp_price').html('tp费用:'+data.tp); + $('#cht_price').html('cht费用:'+data.cht); + $('#total_price').html('总费用费用:'+data.all_total); + } + }); + } + }); +}); +</script> \ No newline at end of file From 31bc3002b6ea3a538b36f68028f1d58b3bd7541c Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 8 May 2019 14:33:10 +0800 Subject: [PATCH 317/382] =?UTF-8?q?=E6=B3=A8=E9=87=8A=E6=8E=89=E6=96=B0?= =?UTF-8?q?=E5=A2=9E=E5=BA=A7=E4=BD=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/ctrip/controllers/ctrip_train.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/application/third_party/ctrip/controllers/ctrip_train.php b/application/third_party/ctrip/controllers/ctrip_train.php index 1836268e..bdd6c8f9 100644 --- a/application/third_party/ctrip/controllers/ctrip_train.php +++ b/application/third_party/ctrip/controllers/ctrip_train.php @@ -123,11 +123,11 @@ class ctrip_train extends CI_Controller{ $rwNum = $Seats->TicketLeft; } - if($Seats->SeatName == '一等双软下'){ + /*if($Seats->SeatName == '一等双软下'){ $ydrwPrice = $Seats->Price * 10; $SeaType .= '"I":"'.$ydrwPrice.'","AI":"¥'.$Seats->Price.'",'; $ydrwNum = $Seats->TicketLeft; - } + }*/ if($Seats->SeatName == '软座'){ $rzPrice = $Seats->Price * 10; @@ -173,11 +173,11 @@ class ctrip_train extends CI_Controller{ $ywNum = $Seats->TicketLeft; } - if($Seats->SeatName == '二等双软下'){ + /*if($Seats->SeatName == '二等双软下'){ $errwPrice = $Seats->Price * 10; $SeaType .= '"J":"'.$errwPrice.'","AJ":"¥'.$Seats->Price.'",'; $errwNum = $Seats->TicketLeft; - } + }*/ if($Seats->SeatName == '动卧下'){ $SeaType .= '"F":"¥'.$Seats->Price.'",'; @@ -200,7 +200,7 @@ class ctrip_train extends CI_Controller{ $ydzNum = isset($ydzNum) ? ticket_exchange($ydzNum,$iseven) : ''; $swzNum = isset($swzNum) ? ticket_exchange($swzNum,$iseven) : ''; $dwNum = isset($dwNum) ? ticket_exchange($dwNum,$iseven) : ''; - $ydrwNum = isset($ydrwNum) ? ticket_exchange($ydrwNum,$iseven) : ''; + /*$ydrwNum = isset($ydrwNum) ? ticket_exchange($ydrwNum,$iseven) : ''; $errwNum = isset($errwNum) ? ticket_exchange($errwNum,$iseven) : ''; if($rwNum == '' && $ydrwNum != ''){ @@ -209,7 +209,7 @@ class ctrip_train extends CI_Controller{ if($ywNum == '' && $errwNum != ''){ $ywNum = $errwNum; - } + }*/ $runMin = $TrainInfo->DurationMinutes % 60; $runHour = ($TrainInfo->DurationMinutes - $runMin) / 60; From f17460389c91d1b51648aef0907175058e9a7d87 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 May 2019 16:45:34 +0800 Subject: [PATCH 318/382] =?UTF-8?q?paypal=20=E9=80=80=E6=AC=BE:=E5=8C=BA?= =?UTF-8?q?=E5=88=86=E5=95=86=E6=97=85=E7=9A=84APP=E5=92=8CAPP=E7=BB=84?= =?UTF-8?q?=E7=9A=84APP;=E9=80=80=E6=AC=BE=E9=82=AE=E4=BB=B6=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E6=A8=A1=E6=9D=BF=E5=8E=8B=E7=BC=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 2 +- .../third_party/paypal/views/refund_buyer.php | 40 +------------------ 2 files changed, 3 insertions(+), 39 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 08bd185b..c5b2a1fd 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -940,7 +940,7 @@ class Index extends CI_Controller { $ht_memo .= '原收款号:' . $parent_txn_id; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 - if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") != '-biz') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 $this->Paypal_model->add_account_info_forAPP($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } else { diff --git a/webht/third_party/paypal/views/refund_buyer.php b/webht/third_party/paypal/views/refund_buyer.php index a4b05563..002285d0 100644 --- a/webht/third_party/paypal/views/refund_buyer.php +++ b/webht/third_party/paypal/views/refund_buyer.php @@ -1,37 +1,5 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns=http://www.w3.org/1999/xhtml> -<head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title>Your Submission Was Successful! - China Highlights</title><style type=text/css>* { margin:0; font-family: Verdana, Arial, Helvetica, sans-serif; }body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size:13px; color:#545454; right: auto; }img, ul, ul li { padding:0; margin:0; border:0; }#warp { border-top:8px solid #a31022!important; }#logo { border: none!important}#logo, #surveyContent { width:210mm; margin:5px auto; padding:5px; }h1 { margin:15px 0 10px 0; font-size:24px; border-bottom:1px solid #d9d9d9; color:#545454; }h2 { margin:15px 0 10px 0; font-size:20px; color:#545454; }.tableSurvey table td { padding:5px; }.tableSurvey table td strong { margin-top:8px; }.tableSurvey1 { border:1px solid #e1e1e1; }.tableSurvey1 th { border:1px solid #fff; height:30px; padding-right:10px; text-align:right; background:#f1f1f1; }.tableSurvey1 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.tableSurvey2 { border:1px solid #e1e1e1; }.tableSurvey2 th { border:1px solid #fff; padding:5px 10px; text-align:right; background:#f1f1f1; font-weight:normal; }.tableSurvey2 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.blue{ color:#0070C0} -.text-bold {font-weight: bold;} -.text-right{text-align: right;} -.title-bold{font-weight: bold;background-color: #ddd;padding: 3px 0;} -</style></head> -<body> - <div id=warp> - <div id=surveyContent> - <?php $raw = json_decode($pn_memo); $c_gross = str_replace("-", "", $pn_mc_gross); ?> - <p>Dear <?php echo $pn_payer ?>,</p> - <br> - <p>China Highlights has refunded to your account today - <?php echo $c_gross ?><?php echo $pn_mc_currency ?>. The transaction to appear on your account may take up to 2-weeks.</p> - <br> - <p>Please find below details of your refund transaction:</p> - <br> - <p class="title-bold">Transaction details</p> - <p ><?php echo $raw->payment_date ?></p> - <p >Payment status: <?php echo $pn_payment_status ?></p> - <br> - <p class="title-bold">Payment details</p> - <p>Gross amount</p> - <p class="text-right"><?php echo $pn_mc_gross ?> <?php echo $pn_mc_currency ?></p> - <br> - <p class="title-bold">Invoice ID</p> - <p><?php echo $pn_invoice ?></p> - <br> - <p class="title-bold">Contact information</p> - <p ><?php echo $pn_payer ?></p> - <p ><?php echo $pn_payer_email ?></p> - <br> - <br> - <pre style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:13px;"> +<html xmlns=http://www.w3.org/1999/xhtml> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title>Your Submission Was Successful! - China Highlights</title><style type=text/css>* { margin:0; font-family: Verdana, Arial, Helvetica, sans-serif; }body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size:13px; color:#545454; right: auto; }img, ul, ul li { padding:0; margin:0; border:0; }#warp { border-top:8px solid #a31022!important; }#logo { border: none!important}#logo, #surveyContent { width:210mm; margin:5px auto; padding:5px; }h1 { margin:15px 0 10px 0; font-size:24px; border-bottom:1px solid #d9d9d9; color:#545454; }h2 { margin:15px 0 10px 0; font-size:20px; color:#545454; }.tableSurvey table td { padding:5px; }.tableSurvey table td strong { margin-top:8px; }.tableSurvey1 { border:1px solid #e1e1e1; }.tableSurvey1 th { border:1px solid #fff; height:30px; padding-right:10px; text-align:right; background:#f1f1f1; }.tableSurvey1 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.tableSurvey2 { border:1px solid #e1e1e1; }.tableSurvey2 th { border:1px solid #fff; padding:5px 10px; text-align:right; background:#f1f1f1; font-weight:normal; }.tableSurvey2 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.blue{ color:#0070C0}.text-bold {font-weight: bold;}.text-right{text-align: right;}.title-bold{font-weight: bold;background-color: #ddd;padding: 3px 0;}</style></head> <body> <div id=warp> <div id=surveyContent> <?php $raw = json_decode($pn_memo); $c_gross = str_replace("-", "", $pn_mc_gross); ?> <p>Dear <?php echo $pn_payer ?>,</p> <br> <p>China Highlights has refunded to your account today - <?php echo $c_gross ?><?php echo $pn_mc_currency ?>. The transaction to appear on your account may take up to 2-weeks.</p> <br> <p>Please find below details of your refund transaction:</p> <br> <p class=title-bold>Transaction details</p> <p><?php echo $raw->payment_date ?></p> <p>Payment status: <?php echo $pn_payment_status ?></p> <br> <p class=title-bold>Payment details</p> <p>Gross amount</p> <p class=text-right><?php echo $pn_mc_gross ?> <?php echo $pn_mc_currency ?></p> <br> <p class=title-bold>Invoice ID</p> <p><?php echo $pn_invoice ?></p> <br> <p class=title-bold>Contact information</p> <p><?php echo $pn_payer ?></p> <p><?php echo $pn_payer_email ?></p> <br> <br> <pre style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:13px;"> Best Regards! <?php echo $advisor_detail->fullname ?>, Travel Advisor<br> @@ -39,8 +7,4 @@ Tel: <?php echo $advisor_detail->tel ?> Mobile: <?php echo $advisor_detail->mob E-mail: <?php echo $advisor_detail->email ?><br> <?php if(isset($site)) { echo $site . '<br>'; } ?> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China - </pre> - </div> - </div> -</body> -</html> + </pre> </div> </div> </body> </html> From b2be7d0214b2e4bf7e011571c533600291e04d40 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 May 2019 16:46:11 +0800 Subject: [PATCH 319/382] =?UTF-8?q?iPaylinks=20=E9=80=80=E6=AC=BE=E5=A4=84?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 216 +++++++++++++++++- .../pay/models/IPayLinks_model.php | 68 +++++- .../third_party/pay/views/iPayLinks_list2.php | 18 +- webht/third_party/pay/views/note_setting.php | 2 +- webht/third_party/pay/views/refund_buyer.php | 10 + 5 files changed, 289 insertions(+), 25 deletions(-) create mode 100644 webht/third_party/pay/views/refund_buyer.php diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index c953e061..f5a83729 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -276,7 +276,7 @@ class IPayLinksService extends CI_Controller return; } - public function query_pay($orderid=NULL) + public function query_pay($orderid=NULL, $output=true) { $this->query_info_arr["queryOrderId"] = $this->create_guid(); $this->query_info_arr["orderId"] = $orderid; @@ -286,8 +286,10 @@ class IPayLinksService extends CI_Controller $this->query_info_arr["signMsg"] = $this->generate_sign($this->query_info_arr); $resp = $this->curl($this->queryUrl,$this->query_info_arr); $resp_obj = simplexml_load_string($resp); - $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); - return; + if ($output !== true) { + return $resp_obj->details; + } + return $this->output->set_content_type('application/json')->set_output(json_encode(simplexml_load_string($resp))); } public function query_refund($refund_order_id) { @@ -364,14 +366,14 @@ class IPayLinksService extends CI_Controller * @date 2017-08-29 * @param string $orderid 订单号 */ - public function batch_send_note($pn_txn_id = false, $old_ssje=NULL) + public function batch_send_note($pn_txn_id = false, $old_ssje=NULL, $pn_id=NULL) { $data = array(); $int = 0; //优先处理指定的交易号,用于修正交易号直接发送通知 if ( ! empty($pn_txn_id)) { - $data['unsend_list'] = array($this->Note_model->note($pn_txn_id)); + $data['unsend_list'] = array($this->Note_model->note($pn_txn_id, $pn_id)); } // 待处理的 if (empty($data['unsend_list'])) { @@ -392,6 +394,7 @@ class IPayLinksService extends CI_Controller //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->IPL_payType == 'refund') { + $this->send_refund($item, $old_ssje); // $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } @@ -446,14 +449,14 @@ class IPayLinksService extends CI_Controller $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 - if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") != '-biz') { //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 $this->IPayLinks_model->add_account_info_forAPP( $GAI_COLI_SN, $advisor_info->COLI_ID, $item->IPL_orderAmount, $item->IPL_completeTime, - mb_strtoupper($item->currencyCode), + $currencyCode, $ssje, $item->IPL_completeTime, $item->IPL_completeTime, @@ -573,6 +576,197 @@ class IPayLinksService extends CI_Controller return; } + /*! + * 退款处理 + * @date 2019-05-08 + * * TODO APP组的退款没有原始订单 + */ + public function send_refund($item, $old_ssje=NULL) + { + if ($item->IPL_stateCode != 2) { + return false; + } + // 原始收款订单 + $raw_memo = json_decode($item->IPL_memo); + $parent_order = $raw_memo->orderId; + // 查询原始收款的交易号 + $parent_payment = $this->query_pay($parent_order, false); + if (empty($parent_payment)) { + $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); + return false; + } + $parent_payment = $parent_payment->detail; + $parent_dealId = $parent_payment->dealId; + $parent_note = $this->Note_model->note($parent_dealId); + // APP 组的退款查不到原始收款记录 + if (empty($parent_note) && true === $this->IPayLinks_model->if_APP_order($parent_order) ) { + $parent_note = $parent_payment; + // 补充字段 + $parent_note->IPL_orderId = $parent_order . '_B'; + $parent_note->IPL_currencyCode = $parent_payment->currencyCode; + $parent_note->IPL_payerName = strval("''"); + $parent_note->IPL_payerEmail = strval("''"); + } + //订单号 + $orderid_info = $this->analysis_orderid($parent_note->IPL_orderId); + $orderid_info = json_decode($orderid_info); + //根据订单号查找外联信息 + $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + //查不到订单信息 + if (empty($advisor_info)) { + $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); + return false; + } + //更新正确的订单信息到记录中,以这个为主 + $this->Note_model->set_invoice($item->IPL_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype); + + //添加支付信息入库 + //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 + if (!empty($orderid_info)) { + $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($parent_note->IPL_currencyCode))); + $currencyCode = mb_strtoupper(trim($currencyCode)); + $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode, '15018'); + $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + //更新还没有填的客邮和交易号de收款记录(商务订单) + if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { + $ht_memo = '(自动录入)退款号:' . $item->IPL_dealId . "\n. "; + $ht_memo .= '原收款号:' . $parent_dealId; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") != '-biz') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + $this->IPayLinks_model->add_account_info_forAPP( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->IPL_orderAmount, + $item->IPL_completeTime, + $currencyCode, + $ssje, + $item->IPL_completeTime, + $item->IPL_completeTime, + $item->IPL_acquiringTime, + $parent_note->IPL_payerName, + $parent_note->IPL_payerEmail, + $item->IPL_dealId, + $ht_memo); + $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } else { + if (false == $this->IPayLinks_model->if_biz_gai_exists($item->IPL_dealId) ) { + $this->IPayLinks_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } + $this->IPayLinks_model->add_account_info( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->IPL_orderAmount, + $item->IPL_completeTime, + $currencyCode, + $ssje, + $item->IPL_completeTime, + $item->IPL_completeTime, + $item->IPL_acquiringTime, + $parent_note->IPL_payerName, + $parent_note->IPL_payerEmail, + $item->IPL_dealId, + $ht_memo); + } + } + //更新还没有填的客邮和交易号的收款记录(传统订单) + elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { + $ht_memo = '(自动)退款号:' . $item->IPL_dealId . "\n. "; + $ht_memo .= '原交易号:' . $parent_dealId; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + $gai_sn = $this->IPayLinks_model->add_tour_account_info( + $GAI_COLI_SN, + $item->IPL_orderAmount, + $item->IPL_completeTime, + $currencyCode, + $ssje, + $item->IPL_completeTime, + $item->IPL_completeTime, + $item->IPL_acquiringTime, + $parent_note->IPL_payerName, + $parent_note->IPL_payerEmail, + $item->IPL_dealId, + $ht_memo); + //添加汉特的订单提醒 + $this->IPayLinks_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . mb_strtoupper($currencyCode) . $item->IPL_orderAmount); + } + } + + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->Note_model->update_send($item->IPL_dealId, 'sendfail'); + return false; + } + + //添加邮件发送记录 + // if (true) { // test + if ($item->IPL_sent !== 'send' && substr($item->IPL_sent, 0, 5) !== 'send-') { + // 客人邮件中的外联落款 + // $web_code = 'cht'; // 默认cht + $web_lgc = 1; + $web_code = strtolower($advisor_info->COLI_WebCode); + $site_info = $this->config->item('site'); + if (isset($site_info[$web_code])) { + $site_info = $site_info[$web_code]; + $item->site = $site_info['site_url']; + $web_lgc = $site_info['site_lgc']; + } + $advisor_detail = $this->IPayLinks_model->get_advisor_detail($advisor_info->COLI_SN, $advisor_info->OPI_SN, $web_lgc); + $item->advisor_detail = $advisor_detail; + + //给外联发送通知邮件 + $fromName = !empty($parent_note->IPL_payerName) ? $parent_note->IPL_payerName : ''; + $fromEmail = !empty($parent_note->IPL_payerEmail) ? $parent_note->IPL_payerEmail : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->IPL_orderAmount . $currencyCode . ' / ' . $fromName; + $body = $this->load->view('receipt_mail', $item, true); + $M_RelatedInfo = $item->IPL_sn; + $M_AddTime = $item->IPL_completeTime; + $M_State = 0; + $this->IPayLinks_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'iPayLinks note'); + // 通知客人, 客人邮箱 + $customer_detail = $this->IPayLinks_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype); + $c_fromName = $advisor_detail->fullname; + $opi_email_list = explode(";", $advisor_detail->email); // 解析外联的邮件 + $c_fromEmail = trim($opi_email_list[0]); + $c_toName = $customer_detail->fullname; + $c_toEmail = $customer_detail->email; + $c_subject = $currencyCode . " " . str_replace('-', '', $item->IPL_orderAmount) . " Refunded to your account, booking number " . $item->IPL_orderId; + // 修改一些字段名, 为了和Alipay等用同一个邮件模板 + $item->payer = $customer_detail->fullname; + $item->payer_email = $customer_detail->email; + $item->total_amount = $item->IPL_orderAmount; + $item->payment_date = $item->IPL_completeTime; + $item->payment_status = "Refunfed"; + $item->currency = $currencyCode; + $item->invoice = $item->IPL_orderId; + $c_body = $this->load->view('refund_buyer', $item, true); + $c_M_RelatedInfo = $item->IPL_sn; + $c_M_AddTime = $item->IPL_completeTime; + $c_M_State = 0; + $this->IPayLinks_model->save_automail( + $c_fromName, + $c_fromEmail, + $c_toName, + $c_toEmail, + $c_subject, + $c_body, + $c_M_RelatedInfo, + $c_M_State, + $c_M_AddTime, + 'iPayLinks refund receipt'); + $this->Note_model->update_send($item->IPL_dealId, 'send-customer'); + } + //添加邮件发送记录 end + // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 + + return ; + } + //解析出订单号 public function analysis_orderid($note_invoice_string) { $data = array(); @@ -990,6 +1184,12 @@ class IPayLinksService extends CI_Controller $data['note'] = $this->Note_model->note($pn_txn_id, $pn_id); $orderid_info = $this->analysis_orderid($data['note']->IPL_orderId); + if (empty($orderid_info) && $data['note']->IPL_payType == 'refund' + && true === $this->IPayLinks_model->if_APP_order($data['note']->IPL_orderId) + ) { + // APP 组的退款订单是没有后缀的 + $orderid_info = $this->analysis_orderid($data['note']->IPL_orderId . '_B'); + } if (!empty($orderid_info)) { $orderid_info = json_decode($orderid_info); if ($orderid_info->ordertype === 'T') { @@ -1014,7 +1214,7 @@ class IPayLinksService extends CI_Controller $advisor_info = $this->IPayLinks_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); if (!empty($advisor_info)) { $this->Note_model->set_invoice($pn_txn_id, $neworder); - $this->batch_send_note($pn_txn_id, $old_ssje); + $this->batch_send_note($pn_txn_id, $old_ssje, $pn_id); echo json_encode('修改成功!'); return true; } diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 1ba2db80..80a6af77 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -18,7 +18,7 @@ class IPayLinks_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class IPayLinks_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class IPayLinks_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class IPayLinks_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class IPayLinks_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -174,7 +174,7 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,?,15018,?,?,?,?,?,?,?,N?,N?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; @@ -207,7 +207,7 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + ) VALUES (?,?,15018,?,?,?,?,?,?,?,N?,N?,?,?,0,0)"; $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; @@ -405,4 +405,58 @@ class IPayLinks_model extends CI_Model { ); return $this->HT->insert("BIZ_OrderOperationLog", $db_column); } + + public function get_advisor_detail($COLI_SN, $OPI_SN, $lgc=1) + { + $advisor_signature = $this->get_advisor_signature($COLI_SN); + if (empty($advisor_signature)) { + $sql = "SELECT OPI_SN, '+86-'+OPI_MoveTelephone mobile,'+86-773-'+OPI_Telephone tel,OPI_Email email,OPI2_Name fullname,OPI2_FirstName,OPI2_LastName + FROM [Tourmanager].[dbo].[V_Operator_Info] + where OPI_SN=? and LGC_LGC=? "; + $advisor_signature = $this->HT->query($sql, array($OPI_SN, $lgc))->row(); + } + return $advisor_signature; + } + public function get_advisor_signature($COLI_SN) + { + $sql = "SELECT top 1 dbo.agenter_user.Name fullname, dbo.agenter_user.tel, + dbo.agenter_user.Email email, dbo.agenter_user.mobile, OPI_DEI_SN, COLI_OPI_ID + FROM dbo.BIZ_ConfirmLineInfo + INNER JOIN dbo.agenter_user ON dbo.BIZ_ConfirmLineInfo.COLI_OPI_ID = dbo.agenter_user.AU_OPI_SN + AND + (dbo.BIZ_ConfirmLineInfo.COLI_WebCode = dbo.agenter_user.agenter + OR (COLI_WebCode in ('EXPCH','MESENLLA','traba','wayaway','guias') and agenter='VAC') + ) + LEFT JOIN OperatorInfo on COLI_OPI_ID = OPI_SN + WHERE (dbo.BIZ_ConfirmLineInfo.COLI_SN = ?)"; + return $this->HT->query($sql, array($COLI_SN))->row(); + } + + public function get_customer_detail($COLI_SN, $ordertype) + { + if ($ordertype === 'T') { + $sql = "SELECT mei.MEI_FirstName+' '+isnull(mei.MEI_MiddleName,'')+' '+isnull(mei.MEI_LastName,'') fullname, + mei.MEI_MailList email + FROM MEmberInfo mei + INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN and cul.CUL_IsLinkMan=1 + WHERE CUL_COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } else { + $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname,GUT_Email email from BIZ_GUEST g + INNER JOIN BIZ_ConfirmLineInfo coli on coli.COLI_GUT_SN=g.GUT_SN + WHERE COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } + } + + public function if_APP_order($order_id) + { + $sql = "SELECT top 1 1 + from BIZ_ConfirmLineInfo coli + where COLI_ID=? + and exists ( + select 1 from OperatorInfo where OPI_SN=COLI_OPI_ID and OPI_DEI_SN=16 + )"; + return $this->HT->query($sql, array($order_id))->num_rows() > 0; + } } diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index 0a981772..c382a143 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -75,7 +75,7 @@ <body> <div id="wrapper" class="chkVisible print-none"> <div class="navbar-header" style="float:none;border-bottom: 1px solid #ccc;"> - <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="http://www.mycht.cn/webht.php/index/index"> + <a class="navbar-brand text-muted" style="height: 52px;padding-top: 7px;padding-left: 30px;" href="/webht.php/index/index"> <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>iPayLinks Notes</h1> @@ -122,7 +122,7 @@ <!-- left --> <div class="col-md-4 col-xs-24 print-none"> <div class="row"> - <form method="post" id="search_list" action="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list/"> + <form method="post" id="search_list" action="/webht.php/apps/pay/ipaylinksservice/note_list/"> <div class="input-group"> <input type="text" name="keywords" value="<?php echo isset($search_key) ? $search_key : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> <span class="input-group-addon search-btn" onclick="$('#search_list').submit();"></span> @@ -132,11 +132,11 @@ </div> <p class="btn-lg"></p> <ul class="list-unstyled hidden-xs links"> - <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list">&gt;全部收款邮件</a></li> + <li><a class="text-primary" href="/webht.php/apps/pay/ipaylinksservice/note_list">&gt;全部收款邮件</a></li> <li class="btn-sm"></li> - <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_faillist" >&gt;错误通知列表</a></li> + <li><a class="text-primary" href="/webht.php/apps/pay/ipaylinksservice/note_faillist" >&gt;错误通知列表</a></li> <li class="btn-sm"></li> - <li><a class="text-primary" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/batch_send_note" target="_blank">&gt;手动处理通知</a></li> + <li><a class="text-primary" href="/webht.php/apps/pay/ipaylinksservice/batch_send_note" target="_blank">&gt;手动处理通知</a></li> <li class="btn-sm"></li> <li><a class="text-primary" href="http://share.chtcdn.com/info.php/sendmail/send_mail" target="_blank">&gt;发送邮件</a></li> <li class="btn-lg"></li> @@ -171,7 +171,7 @@ <li class="col-sm-1 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"><?php echo ($key + 1); ?></li> <li class="col-sm-5 nopadding-L" style="overflow:hidden;word-break: break-all;height: 25px;"> <?php if ($item->IPL_dealId) { ?> - <a class="seen" target="_blank" href="http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/receipt/<?php echo $item->IPL_dealId; ?>"> + <a class="seen" target="_blank" href="/webht.php/apps/pay/ipaylinksservice/receipt/<?php echo $item->IPL_dealId; ?>"> <?php } else {?> <a class="seen" target="_blank" href="#"> <?php } ?> @@ -297,7 +297,7 @@ defaultDate: '<?php echo $date; ?>', dateFormat: 'yy-mm-dd', onSelect: function(dateText) { - window.location.href = 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/note_list?date=' + dateText; + window.location.href = '/webht.php/apps/pay/ipaylinksservice/note_list?date=' + dateText; } }); $(".ui-datepicker").css('width', '15.7em'); @@ -356,7 +356,7 @@ $.ajax({ type: "get", dataType: "json", - url: 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/closeGai/' + pn_txn_id, + url: '/webht.php/apps/pay/ipaylinksservice/closeGai/' + pn_txn_id, success: function(data, textStatus) { alert(data); }, @@ -415,7 +415,7 @@ $.ajax({ type: "get", dataType: "json", - url: 'http://www.mycht.cn/webht.php/apps/pay/ipaylinksservice/close_note/' + pn_txn_id, + url: '/webht.php/apps/pay/ipaylinksservice/close_note/' + pn_txn_id, success: function(data, textStatus) { alert(data); }, diff --git a/webht/third_party/pay/views/note_setting.php b/webht/third_party/pay/views/note_setting.php index 973aef58..02adb51b 100644 --- a/webht/third_party/pay/views/note_setting.php +++ b/webht/third_party/pay/views/note_setting.php @@ -1,4 +1,4 @@ -<form action="http://www.mycht.cn/webht.php/apps/pay/iPayLinksService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> +<form action="/webht.php/apps/pay/iPayLinksService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> <dl class="dl-horizontal"> <dt>交易号</dt> diff --git a/webht/third_party/pay/views/refund_buyer.php b/webht/third_party/pay/views/refund_buyer.php new file mode 100644 index 00000000..fdbc74fe --- /dev/null +++ b/webht/third_party/pay/views/refund_buyer.php @@ -0,0 +1,10 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns=http://www.w3.org/1999/xhtml> <head><meta http-equiv=Content-Type content="text/html; charset=utf-8"><title>Your Submission Was Successful! - China Highlights</title><style type=text/css>* { margin:0; font-family: Verdana, Arial, Helvetica, sans-serif; }body { font-family: Verdana, Arial, Helvetica, sans-serif; font-size:13px; color:#545454; right: auto; }img, ul, ul li { padding:0; margin:0; border:0; }#warp { border-top:8px solid #a31022!important; }#logo { border: none!important}#logo, #surveyContent { width:210mm; margin:5px auto; padding:5px; }h1 { margin:15px 0 10px 0; font-size:24px; border-bottom:1px solid #d9d9d9; color:#545454; }h2 { margin:15px 0 10px 0; font-size:20px; color:#545454; }.tableSurvey table td { padding:5px; }.tableSurvey table td strong { margin-top:8px; }.tableSurvey1 { border:1px solid #e1e1e1; }.tableSurvey1 th { border:1px solid #fff; height:30px; padding-right:10px; text-align:right; background:#f1f1f1; }.tableSurvey1 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.tableSurvey2 { border:1px solid #e1e1e1; }.tableSurvey2 th { border:1px solid #fff; padding:5px 10px; text-align:right; background:#f1f1f1; font-weight:normal; }.tableSurvey2 td { border:1px solid #f9f9f9; padding:5px; text-align:center; width:80px; }.blue{ color:#0070C0}.text-bold {font-weight: bold;}.text-right{text-align: right;}.title-bold{font-weight: bold;background-color: #ddd;padding: 3px 0;}</style></head> <body> <div id=warp> <div id=surveyContent> <?php $c_gross = str_replace("-", "", $total_amount); ?> <p>Dear <?php echo $payer ?>,</p> <br> <p>China Highlights has refunded to your account today - <?php echo $c_gross ?><?php echo $currency ?>. The transaction to appear on your account may take up to 2-weeks.</p> <br> <p>Please find below details of your refund transaction:</p> <br> <p class=title-bold>Transaction details</p> <p><?php echo $payment_date ?></p> <p>Payment status: <?php echo $payment_status ?></p> <br> <p class=title-bold>Payment details</p> <p>Gross amount</p> <p class=text-right><?php echo $total_amount ?> <?php echo $currency ?></p> <br> <p class=title-bold>Invoice ID</p> <p><?php echo $invoice ?></p> <br> <p class=title-bold>Contact information</p> <p><?php echo $payer ?></p> <p><?php echo $payer_email ?></p> <br> <br> <pre style="font-family: Verdana, Arial, Helvetica, sans-serif;font-size:13px;"> +Best Regards! + +<?php echo $advisor_detail->fullname ?>, Travel Advisor<br> +Tel: <?php echo $advisor_detail->tel ?> Mobile: <?php echo $advisor_detail->mobile ?><br> +E-mail: <?php echo $advisor_detail->email ?><br> +<?php if(isset($site)) { echo $site . '<br>'; } ?> +Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China + </pre> </div> </div> </body> </html> From b4d5773dabb3f74516aeead6ce60dd7945c4114f Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 May 2019 17:16:50 +0800 Subject: [PATCH 320/382] =?UTF-8?q?paypal,iPaylinks=20=E6=8E=A8=E9=80=81?= =?UTF-8?q?=E5=88=97=E8=A1=A8=E7=9A=84=E5=8F=91=E9=80=81=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E6=98=BE=E7=A4=BA;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 8 ++++---- webht/third_party/pay/views/iPayLinks_list2.php | 4 ++-- webht/third_party/paypal/views/note_list.php | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index ba7942ca..37c43624 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -196,9 +196,9 @@ class Note_model extends CI_Model { $sql = "SELECT -- gai.GAI_SN, -- gaib.GAI_SN, - -- COLI.COLI_ID, + -- COLI.COLI_ID,IPL_payType='pay' and case - when IPL_payType='pay' and (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 + when (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 when IPL_payType='pay' and coli.COLI_ID is not null then 99999 when IPL_payType<>'pay' then 10000 when IPL_sent='closeRecord' then 10000 @@ -207,8 +207,8 @@ class Note_model extends CI_Model { ipl.* from InfoManager.dbo.IPayLinksLog ipl left join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on coli.COLI_ID=ipl.IPL_orderId and coli.COLI_Department=16 - left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 and ipl.IPL_payType='pay' - left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' + left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 --and ipl.IPL_payType='pay' + left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 --and ipl.IPL_payType='pay' where 1=1 and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') ) $this->send diff --git a/webht/third_party/pay/views/iPayLinks_list2.php b/webht/third_party/pay/views/iPayLinks_list2.php index c382a143..97134d4d 100644 --- a/webht/third_party/pay/views/iPayLinks_list2.php +++ b/webht/third_party/pay/views/iPayLinks_list2.php @@ -194,8 +194,8 @@ <?php $show_send = ''; $class_css = ''; - if ($item->IPL_sent == 'send') { - $show_send = $item->IPL_sent; + if ($item->IPL_sent == 'send' || substr($item->IPL_sent, 0, 5) == 'send-') { + $show_send = 'send'; } else if ($item->IPL_sent == 'closeRecord') { $show_send = "已忽略"; } else if (strcmp(trim($item->IPL_stateCode), "2") && $item->IPL_stateCode != NULL) { diff --git a/webht/third_party/paypal/views/note_list.php b/webht/third_party/paypal/views/note_list.php index 612750ed..4dcfcb2d 100644 --- a/webht/third_party/paypal/views/note_list.php +++ b/webht/third_party/paypal/views/note_list.php @@ -210,7 +210,7 @@ echo "<option value=\"$vf->TEL_SN@" . strstr($vf->TEL_transactionDate, " ", true $class_css = ''; $show_record = '查看录入状态'; if ($item->pn_send == 'send' || substr($item->pn_send, 0, 5) == "send-") { - $show_send = $item->pn_send; + $show_send = 'send'; } elseif ($item->pn_send == 'closeRecord') { $show_send = $show_record = '已忽略'; } else if ($item->pn_payment_status == 'Completed') { From 3714c7b22506dc85ffaf1fee08260a1066b3ab97 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 8 May 2019 17:34:36 +0800 Subject: [PATCH 321/382] =?UTF-8?q?=E4=B8=8A=E7=BA=BF144=E5=89=8D,=20?= =?UTF-8?q?=E6=97=A0=E9=80=80=E6=AC=BE=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 1 - webht/third_party/pay/models/note_model.php | 8 ++++---- webht/third_party/paypal/controllers/index.php | 8 +++----- 3 files changed, 7 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index f5a83729..65fb8869 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -394,7 +394,6 @@ class IPayLinksService extends CI_Controller //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->IPL_payType == 'refund') { - $this->send_refund($item, $old_ssje); // $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 37c43624..ba7942ca 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -196,9 +196,9 @@ class Note_model extends CI_Model { $sql = "SELECT -- gai.GAI_SN, -- gaib.GAI_SN, - -- COLI.COLI_ID,IPL_payType='pay' and + -- COLI.COLI_ID, case - when (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 + when IPL_payType='pay' and (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 when IPL_payType='pay' and coli.COLI_ID is not null then 99999 when IPL_payType<>'pay' then 10000 when IPL_sent='closeRecord' then 10000 @@ -207,8 +207,8 @@ class Note_model extends CI_Model { ipl.* from InfoManager.dbo.IPayLinksLog ipl left join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on coli.COLI_ID=ipl.IPL_orderId and coli.COLI_Department=16 - left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 --and ipl.IPL_payType='pay' - left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 --and ipl.IPL_payType='pay' + left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 and ipl.IPL_payType='pay' + left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' where 1=1 and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') ) $this->send diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index c5b2a1fd..ce530df9 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -653,8 +653,6 @@ class Index extends CI_Controller { $ordertype = 'T'; } elseif (substr($ordertype_temp, 0, 1) == 'B') { $ordertype = 'B'; - } elseif (substr($ordertype_temp, 0, 1) == 'A') { - $ordertype = 'A'; } } // 2018.05.28 for Trippest, tourMaster的订单号是01开头 @@ -749,10 +747,8 @@ class Index extends CI_Controller { } //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->pn_payment_status == 'Refunded') { - $this->send_refund($item, $handpick, $old_ssje); + $this->Note_model->update_send($item->pn_txn_id, 'send'); continue; - // $this->Note_model->update_send($item->pn_txn_id, 'send'); - // continue; } //只处理完成状态,其他状态由陆燕处理 @@ -882,6 +878,7 @@ class Index extends CI_Controller { $M_State = 0; $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); //添加邮件发送记录 end + $this->Note_model->update_send($item->pn_txn_id, 'send'); } } @@ -961,6 +958,7 @@ class Index extends CI_Controller { } } + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie From 62c25429292d04e1d0202b72b989a92f03e61346 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 11:23:51 +0800 Subject: [PATCH 322/382] =?UTF-8?q?=E4=BF=9D=E5=AD=98=E8=80=81=E7=89=88?= =?UTF-8?q?=E6=9C=AC=E7=9A=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/train/config/config.php | 17 +- .../third_party/train/config/constants.php | 4 + .../third_party/train/controllers/auto.php | 574 +++++++++---- .../train/controllers/citycode.php | 526 ++++++++++++ .../train/controllers/ctrip_train.php | 585 +++++++++++++ .../third_party/train/controllers/index.php | 626 +++++++++++--- .../third_party/train/controllers/junjun.php | 366 ++++++++ .../train/controllers/tuniu_callback.php | 251 ++++++ .../train/controllers/tuniu_train.php | 778 ++++++++++++++++++ .../train/helpers/train_helper.php | 40 + .../third_party/train/libraries/Des.php | 59 ++ .../train/models/BIZ_train_model.php | 557 ++++++++++--- .../train/models/ctrip_train_model.php | 301 +++++++ .../train/models/order_people_model.php | 72 +- .../train/models/sendmail_model.php | 79 +- .../third_party/train/models/test_model.php | 0 .../third_party/train/models/tuniu_model.php | 461 +++++++++++ .../train/models/tuniuprice_model.php | 16 + application/third_party/train/views/email.php | 101 +-- .../third_party/train/views/email_before.php | 48 ++ .../third_party/train/views/email_fault.php | 26 + .../third_party/train/views/email_test.php | 33 + .../train/views/export20161229.php | 23 + .../train/views/ht_order_list.html | 44 +- .../train/views/ht_train_order_info.php | 305 ++++++- .../train/views/ht_train_order_info_test.php | 509 ++++++++++++ application/third_party/train/views/order.php | 28 +- .../third_party/train/views/train_help.php | 2 + .../train/views/train_transaction_excel.php | 178 ++++ .../train/views/tuniu/grabTicketBook.php | 137 +++ .../train/views/tuniu/ht_order_list.html | 82 ++ .../train/views/tuniu/ht_train_order_info.php | 392 +++++++++ .../third_party/train/views/tuniu/order.php | 113 +++ .../views/tuniu/train_transaction_excel.php | 176 ++++ application/third_party/train/随笔.txt | 53 ++ 35 files changed, 7093 insertions(+), 469 deletions(-) create mode 100644 application/third_party/train/config/constants.php create mode 100644 application/third_party/train/controllers/citycode.php create mode 100644 application/third_party/train/controllers/ctrip_train.php create mode 100644 application/third_party/train/controllers/junjun.php create mode 100644 application/third_party/train/controllers/tuniu_callback.php create mode 100644 application/third_party/train/controllers/tuniu_train.php create mode 100644 application/third_party/train/helpers/train_helper.php create mode 100644 application/third_party/train/libraries/Des.php create mode 100644 application/third_party/train/models/ctrip_train_model.php create mode 100644 application/third_party/train/models/test_model.php create mode 100644 application/third_party/train/models/tuniu_model.php create mode 100644 application/third_party/train/models/tuniuprice_model.php create mode 100644 application/third_party/train/views/email_before.php create mode 100644 application/third_party/train/views/email_fault.php create mode 100644 application/third_party/train/views/email_test.php create mode 100644 application/third_party/train/views/export20161229.php create mode 100644 application/third_party/train/views/ht_train_order_info_test.php create mode 100644 application/third_party/train/views/train_help.php create mode 100644 application/third_party/train/views/train_transaction_excel.php create mode 100644 application/third_party/train/views/tuniu/grabTicketBook.php create mode 100644 application/third_party/train/views/tuniu/ht_order_list.html create mode 100644 application/third_party/train/views/tuniu/ht_train_order_info.php create mode 100644 application/third_party/train/views/tuniu/order.php create mode 100644 application/third_party/train/views/tuniu/train_transaction_excel.php create mode 100644 application/third_party/train/随笔.txt diff --git a/application/third_party/train/config/config.php b/application/third_party/train/config/config.php index 573d5514..99cbb15f 100644 --- a/application/third_party/train/config/config.php +++ b/application/third_party/train/config/config.php @@ -1,5 +1,13 @@ <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); +//途牛apiurl (测试) +//define("TUNIU_URL","218.94.82.118:13532"); +//define("TUNIU_KEY","Te56CBQmorzJGeYIIK"); + +//途牛apiurl (正式) +define("TUNIU_URL","https://open.tuniu.cn"); +define("TUNIU_KEY","AILvoDj8El7KCSMe25"); + //聚合火车订票API key define("JUHE_TRAIN_API_KEY","79f03107b921ef31310bd40a1415c1cb"); @@ -52,6 +60,7 @@ $config["train_zw"]=array( "2"=>"软座", "3"=>"硬卧", "1"=>"硬座", + "F"=>"动卧", ); //数据库座次配对,包厢硬卧(5),无座(WZ),聚合没有 $config["db_train_zw"]=array( @@ -65,7 +74,7 @@ $config["db_train_zw"]=array( "A"=>"6", "S"=>"4", "4"=>"4", - "F"=>"4", + "F"=>"F", "3"=>"3", "2"=>"2", "1"=>"1", @@ -85,4 +94,8 @@ $config["train_passportty"]=array( "2"=>"一代身份证", "C"=>"港澳通行证", "G"=>"台湾通行证" - ); \ No newline at end of file + ); + +//黑名单用户 +$config['black_list'] = array('209582910','539152642','506157109','E66735489','E66735492','E80377215','G23001338','E95287649','345276546','PA4286015','G09382769','G26113116','G25996274','572309763','506620366','505897939','E71156367','E21961674','v716898','561669436','EL657289','533300106','482225223','514815909','592108236'); + \ No newline at end of file diff --git a/application/third_party/train/config/constants.php b/application/third_party/train/config/constants.php new file mode 100644 index 00000000..9d315fd5 --- /dev/null +++ b/application/third_party/train/config/constants.php @@ -0,0 +1,4 @@ +<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); + + +define("JUHE_API_KEY","123"); \ No newline at end of file diff --git a/application/third_party/train/controllers/auto.php b/application/third_party/train/controllers/auto.php index a6d1dff4..7ac5a656 100644 --- a/application/third_party/train/controllers/auto.php +++ b/application/third_party/train/controllers/auto.php @@ -1,5 +1,4 @@ -<?php - +<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); @@ -35,70 +34,152 @@ class Auto extends CI_Controller{ $this->code_zw=$this->config->item('train_zw'); $this->piaotype=$this->config->item('train_piaotype'); $this->passportty=$this->config->item('train_passportty'); - - $this->load->model("BIZ_train_model");//加载模型 + $this->balance_api = "http://op.juhe.cn/trainTickets/balance.php";//余额 + $this->load->model("BIZ_train_model");//加载模型 } + + //index + public function index(){ + echo 'index'; + //print_r($black_list); + } - - //用于自动出票,接收COLI_SN + //用于自动发送确认信 + public function send_confirmmail(){ + //header('Location: http://www.mycht.cn/info.php/apps/trainsystem/api/send_confirmmail'); + die(); + $mailarr = $this->BIZ_train_model->auto_sendmail(); + foreach($mailarr as $obj){ + $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($obj->JOL_COLD_SN); + $coli_id = $coli_id[0]->COLI_ID; + $juhe_order = $obj->JOL_JuheOrder; + $this->send_mail_to_guest($coli_id,$juhe_order); + } + } + + //用于自动出票 public function auto_pay_ticket(){ + //header('Location: http://www.mycht.cn/info.php/apps/trainsystem/addorders/auto_pay_ticket'); + die(); date_default_timezone_set('Asia/Shanghai'); - // $coli_sn="473013018"; - $coli_sn = $this->input->post("coli_sn"); - $list=new StdClass; - $back_data = 1; - - if(!empty($coli_sn)){ - $cold_sn=$this->BIZ_train_model->get_cold_sn($coli_sn); - $coli_id = $this->BIZ_train_model->coli_sn_get_coli_id($coli_sn); - $i = 0; - $list->info=array(); - foreach ($cold_sn as $v) { - if($v->COLD_SPFS > 1){ - //寄送票 - $back_data = 0; - break; - } - $list->info[$i]=new StdClass; - $list->info[$i]->people=$this->BIZ_train_model->biz_people($v->COLD_SN); - $list->info[$i]->train=$this->BIZ_train_model->get_biz_foi($v->COLD_SN); - $list->info[$i]->status=$this->BIZ_train_model->get_biz_jol($v->COLD_SN); - - if(count($list->info[$i]->people) > 5){ - $back_data = 0; - break; - }; - if((strtotime($list->info[$i]->train[0]->DepartureTime) - time())/3600 < 3 or (strtotime($list->info[$i]->train[0]->DepartureTime) - time())/24/3600 >29){ - $back_data = 0; - break; - } - if($list->info[$i]->train[0]->adultcost > 1000){ - $back_data = 0; - break; - } - $i++; - } - if($back_data == 0){ - echo 0; - return false; - }else{ - foreach ($cold_sn as $v) { - $reback = $this->submit_juhe_order($v->COLD_SN,$coli_id[0]->COLI_ID); - if($reback["status"] && !empty($reback["order"])){ - $back_data .= ",".$reback["order"]; - } - } - } - $back_data = substr($back_data, 2); - if($back_data){ //这里 $back_data 还有可能没数据,所以判断一下 - echo $back_data; - }else{ - echo 0; - } - return false; - } - + //$this->BIZ_train_model->auto_add(); + //判断账户余额,如果小于1000自动退出。 + $post_data=array("key"=>$this->key); + $back_data=$this->post_data($this->balance_api,$post_data); + $price = json_decode($back_data)->result; + print_r('账户余额:'.$price); + if($price < 1000){ + exit('账户余额不足'); + } + //筛选出能自动出票的订单 + $auto_pool = $this->BIZ_train_model->auto_check_ticket(); + + //创建一个不允许自动出票的国际火车票数组 + $nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795'); + + //创建黑名单 + $black_list = $this->config->item('black_list'); + $string = ''; + foreach($auto_pool as $item){ + $this->ticketype = 1; + $back_message = ''; + $cold_sn = $item->COLD_SN; + $coli_id = $item->coli_id; + $back_data = 1; + + $people_arr = $this->BIZ_train_model->biz_people($cold_sn); + $train_info = $this->BIZ_train_model->get_biz_foi($cold_sn); + //print_r($train_info); + if($item->COLD_SPFS > 1){ + //寄送票 + $back_data = 0; + $back_message .= '-邮寄不自动出票'; + } + + //乘客人数大于5人不出票 + if(count($people_arr) > 5){ + $back_data = 0; + $back_message .= '-乘客人数大于5不自动出票'; + } + + //护照号如果在黑名单的就不自动出票 + foreach($people_arr as $people_info){ + if(in_array($people_info->BPE_Passport,$black_list)){ + $back_data = 0; + $back_message .= '-此用户为黑名单用户,不自动出票'; + } + + if(strlen($people_info->BPE_Passport) >= 18){ + $back_data = 0; + $back_message .= '-护照位数大于18不自动出票'; + } + } + + //单张票价不能大于1000人民币 + if($train_info[0]->adultcost > 1000){ + $back_data = 0; + $back_message .= '-单价大于1000不自动出票'; + } + + //如果为国际火车票就不出票 + if(in_array($train_info[0]->FlightsNo, $nation_train)){ + $back_data = 0; + $back_message .= '-国际火车票不自动出票'; + } + + //无座的订单不做出票 + if($train_info[0]->Aircraft == 'WZ'){ + $back_data = 0; + $back_message .= '-无座不自动出票'; + } + + //香港火车不自动出票 + if($train_info[0]->DepartAirport == 'XJA'){ + $back_data = 0; + $back_message .= '-香港火车不自动出票'; + } + + $DepartureDate = strtotime($train_info[0]->DepartureDate); + $time = time(); + $depart_diff = ($DepartureDate - $time) / 86400; + + if($train_info[0]->ArrivalAirport == 'XJA' && $train_info[0]->adultcost > 500 && $depart_diff > 5){ + $back_data = 0; + $back_message .= '-内地香港火车金额大于500超过五天不自动出票'; + } + //print_r($train_info); + + //如果刚好是第三十天的订单 + if(($item->COLI_State == '8' || $item->COLI_State == '63')){ + $this->ticketype = 3; + $time_obj = $this->BIZ_train_model->get_saletime($train_info['0']->DepartAirport_cn); + //print_r($time_obj); + if(!empty($time_obj)){ + $saletime = strtotime($time_obj->TST_saletime); + //echo $saletime; + $sale_diff = (time() - $saletime) / 3600; + if($sale_diff > 1){ + $back_data = 0; + $back_message .= '-超过抢票时间'; + }else if($sale_diff <0){ + $back_data = 0; + $back_message .= '-未到抢票时间'; + } + } + } + + if($back_data == 0){ + $string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')'.$back_message.'</td></tr>'; + }else{ + //单个订单提交 + $this->submit_juhe_order($cold_sn,$coli_id); + //$string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>'; + } + } + print_r('<table border="1">'.$string.'</table>'); } + + //根据汉特订单明细表SN来获取车次,乘客信息,拼接成聚合提交订单的url public function submit_juhe_order($cold_sn,$coli_id) { // $cold_sn=$this->input->get("order"); @@ -122,7 +203,15 @@ class Auto extends CI_Controller{ return false; } - + + //选座功能 + $selectseat = ''; + $train_select = $data['train']->FOI_SelectedSeat; + $obj = explode(',',$train_select); + foreach($obj as $value){ + $selectseat .= $value; + } + $data['people_list'] = $this->BIZ_train_model->biz_people($cold_sn); if (empty($data['people_list'])) { //显示错误,找不到用户信息 @@ -130,6 +219,7 @@ class Auto extends CI_Controller{ echo json_encode($reback); return false; } + //前面做过判断,为什么还要再判断一次 if (count($data['people_list']) > 5) { //显示错误,用户超过五个 $reback["mes"]="乘客不能超过五个"; @@ -144,9 +234,13 @@ class Auto extends CI_Controller{ foreach ($data['people_list'] as $key => $item) { $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 - //乘客姓名 - $passengersename = trim($item->BPE_FirstName) . trim($item->BPE_MiddleName) . trim($item->BPE_LastName); - //乘客类型 + //乘客姓名(聚合要求名字中不能出现空格字符) + $passengersename = str_replace(' ','',$item->BPE_FirstName) . str_replace(' ','',$item->BPE_MiddleName) . str_replace(' ','',$item->BPE_LastName); + //将/替换掉 + $passengersename = str_replace('/','',$passengersename); + $passengersename = $this->chk_sp_name($passengersename); + + //乘客类型 switch ($item->BPE_GuestType) { case 1: $piaotype = 1; @@ -161,9 +255,24 @@ class Auto extends CI_Controller{ $piaotypename = "成人票"; break; } - $passporttypeseid = "B"; //护照 - $passporttypeseidname = "护照"; - $passportseno = $item->BPE_Passport; + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + $passportseno = str_replace(' ','',$item->BPE_Passport); $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; } $passengers.="]"; @@ -174,6 +283,8 @@ class Auto extends CI_Controller{ "key"=>$this->key, "user_orderid"=>$cold_sn,//自定义订单号 "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, "from_station_name"=>$data["train"]->DepartAirport_cn, "from_station_code"=>$data["train"]->DepartAirport, "to_station_code"=>$data["train"]->ArrivalAirport, @@ -181,9 +292,22 @@ class Auto extends CI_Controller{ "passengers"=>$passengers, "checi"=>$data["train"]->FlightsNo ); - // $bakc_json=$this->post_data($url,$post_data); + $arr = ''; + foreach($post_data as $key=>$value){ + $arr .= $key.'='.$value.';'; + } + + //return '汉特订单号:'.$coli_id.'-可以自动出票---'.$arr; + //echo '<br>'; + //print_r($url); + //print_r($post_data); + //echo '<br>'; + + //print_r($post_data); + //die(); + $bakc_json=$this->post_data($url,$post_data); $bakc=json_decode($bakc_json);//json=>obj - + $add_data=new StdClass(); $add_data->JOL_COLD_SN=(int)$cold_sn; @@ -201,17 +325,18 @@ class Auto extends CI_Controller{ $reback["status"]=1; $reback["order"]=$bakc->result->orderid; $reback["mes"]="订单提交成功,等待回调"; - $this->send_mail_to_wl("订单:{$coli_id} 提交成功","翰特订单号:{$coli_id} ;聚合订单号:{$bakc->result->orderid}"); - }else{ + //$this->send_mail_to_wl("订单:{$coli_id} 提交成功","翰特订单号:{$coli_id} ;聚合订单号:{$bakc->result->orderid}",$coli_id); + }else{ $add_data->JOL_JuheOrder=null; $reback["mes"]= $bakc_json; $add_data->JOL_Status="e"; - $this->send_mail_to_wl("订单:{$coli_id} 提交失败","翰特订单号:{$coli_id}"); + // $this->send_mail_to_wl("订单:{$coli_id} 提交失败","翰特订单号:{$coli_id}",$coli_id); } - $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data); - + //聚合返回数据之后记录到聚合订单表 + $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data,$this->ticketype); return $reback; } + public function ticket_status($coli_sn="",$jh_id=""){ if(empty($coli_sn)){ $coli_sn = $this->input->get("sn"); @@ -246,99 +371,207 @@ class Auto extends CI_Controller{ $list->cols_id = $cols_id[0]->COLI_ID; $this->load->view("ticket_status",$list); } - //发邮件给外联 - public function send_mail_to_wl($subject,$body){ - $this->load->model("Sendmail_model"); - $fromName = "csk"; - $fromEmail = "csk@hainatravel.com"; - $toName = "ethel"; - $toEmail = "ethel@chinahighlights.com"; - $this->Sendmail_model->SendGuest($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + + //发邮件给外联 + public function send_mail_to_wl($subject,$body,$coli_id){ + //$subject = 'autopay ticket'; + //$body = 'this is autopay ticket'; + $this->load->model("Sendmail_model"); + $fromName = "cyc"; + $fromEmail = "cyc@hainatravel.com"; + //获取该订单的操作员的邮箱以及姓名 + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); } - //发邮件给客人 - public function send_mail_to_guest($coli_id,$jh_order){ - $this->load->model("Sendmail_model"); + + //发邮件给客人(测试) + public function send_mail_to_guest_old($coli_id,$jh_order){ + $this->load->model("Sendmail_model"); + $info = $this->BIZ_train_model->get_user_info($jh_order); $guest = $this->BIZ_train_model->get_guest_info($coli_id); - $fromName = "sharon"; - $fromEmail = "sharon@chinahighlights.com"; - $toName = $guest[0]->GUT_LastName; - $toEmail = $guest[0]->GUT_Email; - $subject = "auto pay test $jh_order"; - $body = "csk test train ticket $jh_order"; - $this->Sendmail_model->SendGuest($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + //print_r($guest); + $operator_info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $fromName = $operator_info[0]->Name; + $fromEmail = $operator_info[0]->OPI_Email; + $toName = $guest[0]->GUT_LastName.$guest[0]->GUT_FirstName; + $toEmail = $guest[0]->GUT_Email;// + $data['coli_id'] = $coli_id; + $data['toname'] = $toName; + $data['adult'] = $info->COLD_PersonNum; + $data['chlid'] = $info->COLD_ChildNum; + $data['baby'] = $info->COLD_BabyNum; + $data['price'] = $this->BIZ_train_model->get_paypal($coli_id); + $data['allpeople'] = $this->BIZ_train_model->biz_people($info->COLD_SN); + $data['train_info'] = $this->BIZ_train_model->get_biz_foi($info->COLD_SN); + $differtime = (strtotime($data['train_info'][0]->DepartureTime) - time()) / 3600; + $obj = $this->BIZ_train_model->get_biz_jol_info($info->COLD_SN,$jh_order); + $data['juhe_info'] = json_decode($obj->JOL_BackTxt); + $status = $obj->JOL_Status; + $data['operator'] = $operator_info; + $data['emailarr'] = explode(';',$operator_info[0]->Email); + + $coach = array(); + $seats = array(); + $string = ''; + foreach($data['juhe_info']->passengers as $item){ + foreach(explode(',',$item->cxin) as $item){ + if(strpos($item,'车厢')){ + $item = str_replace('车厢','',$item); + array_push($coach,$item); + }else{ + $find = array('座上铺','座中铺','座下铺','座'); + $replace = array(' upper',' middle',' lower',''); + $item = str_replace($find,$replace,$item); + array_push($seats,$item); + } + } + } + + //判断车厢是否唯一,如果不唯一的话,分成两个车厢 + if(count(array_unique($coach)) == 1){ + $onlycoach = array_unique($coach); + $string .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach) as $item_coach){ + $string .= 'Coach '.$item_coach.','; + } + } + + $string .= 'Seat '; + foreach($seats as $item_seat){ + $string .= $item_seat.','; + } + + $data['seatinfo'] = substr($string,0,strlen($string)-1); + + if($status == '4' && $differtime > 0){ + $subject = "Got payment and issued train ticket(s), Order No $coli_id"; + $body = $this->load->view('email',$data,true); + print_r($body); + //$this->send_mail_to_wl("订单:{$coli_id} 出票成功","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //发送邮件给客人 + //$flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + }else if($status == '1' && $differtime < 18 && $differtime > 0){ + $subject = "The train ticket(s) will be issued manually, Order No $coli_id"; + $body = $this->load->view('email_fault',$data,true); + print_r($body); + //$this->send_mail_to_wl("订单:{$coli_id} 出票失败","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //测试阶段,将失败邮件发送一份给操作外联。 + //$flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$fromName,$fromEmail,$subject,$body); + //测试阶段,将失败邮件发送一份给操作外联。 + //$this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + }else{ + echo $jh_order.'不需要发邮件<br>'; + //$this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$jh_order),array("JOL_SendMail"=>2)); + $flag = false; + } + + if($flag){ + //$this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$jh_order),array("JOL_SendMail"=>1,"JOL_M_SN"=>$flag)); + } } - // - public function sub_callback(){ - $data_post=$this->input->post(); - // $data_post["data"]='{"from_station_name":"桂林北","from_station_code":"GBZ","to_station_name":"柳州","to_station_code":"LZZ","train_date":"2017-01-05","orderid":"111111H","user_orderid":"488015272","orderamount":null,"ordernumber":null,"checi":"K457","msg":"没有余票","status":"4","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E132124","price":"1","zwcode":"1","zwname":"硬座"},{"passengerid":2,"passengersename":"TW","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E02030609","price":"1","zwcode":"1","zwname":"硬座"}],"refund_money":null,"sign":"a5bc2ac8ef2b3a4c1bca323c3898e748"}'; - $data=json_decode($data_post["data"]); - - $this->load->model("order_people_model","op"); - $update_data=new StdClass(); - $update_data->JOL_BackTxt=$data_post["data"]; - $update_data->JOL_RebackMsg=$data->msg; - $update_data->JOL_Status=$data->status; - $update_data->JOL_JuheOrder=$data->orderid; - $update_data->JOL_Price=$data->passengers[0]->price; - - $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($data->user_orderid); - - $add_train_order_data = new StdClass; - if($data->status=="2"){ - $post_data=array( - "key"=>$this->key, - "orderid"=>$data->orderid - ); - $back_json=$this->my_post($this->pay_api,$post_data); - $back=json_decode($back_json); - $update_data->JOL_BackTxt=$back_json; - $update_data->JOL_RebackMsg=$back->reason; - }elseif($data->status=="4"){ - //付款成功 写入TOC表 - $add_train_order_data->TOC_Memo=$data->orderid; - $add_train_order_data->TOC_COLD_SN=$data->user_orderid; - $add_train_order_data->TOC_TrainNumber=$data->checi; - $add_train_order_data->TOC_DepartureDate=$data->train_date; - $add_train_order_data->TOC_TicketCost=$data->orderamount; - $add_train_order_data->poundage=(count($data->passengers)*2)."";//手续费,每人两块,转换成字符串 - $add_train_order_data->FOI_TrainNetOrderNo=$data->ordernumber; - $this->op->add_train_order($add_train_order_data); - $this->send_mail_to_wl("订单:{$coli_id[0]->COLI_ID} 出票成功","翰特订单号:{$coli_id[0]->COLI_ID};聚合订单号:{$data->orderid}"); - $this->send_mail_to_guest($coli_id[0]->COLI_ID,$data->orderid); - }elseif($data->status=="7"){ - //退票成功 写入TOC表 - $newtime="";//记录最新操作时间 - $refund_passportseno="";//退票人护照号 - $refund_money="";//退票金额 - foreach ($data->passengers as $p) { - //找出退票人,规则:操作时间最新的 - if($p->refundTimeline){//是否有退票操作 - //$p->refundTimeline[count($p->refundTimeline)-1] 最新操作 - if($p->refundTimeline[count($p->refundTimeline)-1]->time > $newtime){ - $newtime=$p->refundTimeline[count($p->refundTimeline)-1]->time; - $refund_passportseno=$p->refundTimeline[count($p->refundTimeline)-1]->detail->passportseno; - $refund_money=$p->refundTimeline[count($p->refundTimeline)-1]->detail->returnmoney; - } - } - } - $add_train_order_data->TOC_Memo=$data->orderid." ".$refund_passportseno; - $add_train_order_data->TOC_COLD_SN=$data->user_orderid; - $add_train_order_data->TOC_TrainNumber=$data->checi; - $add_train_order_data->TOC_DepartureDate=$data->train_date; - $add_train_order_data->TOC_TicketCost=-$refund_money; - $add_train_order_data->FOI_TrainNetOrderNo=null;//退票不用更新取票号,以此在模型里面判断是否为退票消息 - $this->op->add_train_order($add_train_order_data); - }else{ - $this->send_mail_to_wl("订单:{$coli_id[0]->COLI_ID} 出票失败","翰特订单号:{$coli_id[0]->COLI_ID};聚合订单号:{$data->orderid};返回信息:{$data->msg}"); - } - - - $this->op->update_jh_order($update_data); - echo "success"; + + //发邮件给客人 + public function send_mail_to_guest($coli_id,$jh_order){ + $this->load->model("Sendmail_model"); + $info = $this->BIZ_train_model->get_user_info($jh_order); + $guest = $this->BIZ_train_model->get_guest_info($coli_id); + //print_r($guest); + $operator_info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $fromName = $operator_info[0]->Name; + $fromEmail = $operator_info[0]->OPI_Email; + $toName = $guest[0]->GUT_LastName.$guest[0]->GUT_FirstName; + $toEmail = $guest[0]->GUT_Email;// + $data['coli_id'] = $coli_id; + $data['toname'] = $toName; + $data['adult'] = $info->COLD_PersonNum; + $data['chlid'] = $info->COLD_ChildNum; + $data['baby'] = $info->COLD_BabyNum; + $data['price'] = $this->BIZ_train_model->get_paypal($coli_id); + $data['allpeople'] = $this->BIZ_train_model->biz_people($info->COLD_SN); + $data['train_info'] = $this->BIZ_train_model->get_biz_foi($info->COLD_SN); + $differtime = (strtotime($data['train_info'][0]->DepartureTime) - time()) / 3600; + $obj = $this->BIZ_train_model->get_biz_jol_info($info->COLD_SN,$jh_order); + $data['juhe_info'] = json_decode($obj->JOL_BackTxt); + $status = $obj->JOL_Status; + $data['operator'] = $operator_info; + $data['emailarr'] = explode(';',$operator_info[0]->Email); + + $coach = array(); + $seats = array(); + $string = ''; + foreach($data['juhe_info']->passengers as $item){ + foreach(explode(',',$item->cxin) as $item){ + if(strpos($item,'车厢')){ + $item = str_replace('车厢','',$item); + array_push($coach,$item); + }else{ + $find = array('座上铺','座中铺','座下铺','座'); + $replace = array(' upper',' middle',' lower',''); + $item = str_replace($find,$replace,$item); + array_push($seats,$item); + } + } + } + + //判断车厢是否唯一,如果不唯一的话,分成两个车厢 + if(count(array_unique($coach)) == 1){ + $onlycoach = array_unique($coach); + $string .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach) as $item_coach){ + $string .= 'Coach '.$item_coach.','; + } + } + + $string .= 'Seat '; + foreach($seats as $item_seat){ + $string .= $item_seat.','; + } + + $data['seatinfo'] = substr($string,0,strlen($string)-1); + + if($status == '4' && $differtime > 0){ + $subject = "Got payment and issued train ticket(s), Order No $coli_id"; + $body = $this->load->view('email',$data,true); + $this->send_mail_to_wl("订单:{$coli_id} 出票成功","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //发送邮件给客人 + $flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + $this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$jh_order),array("JOL_SendMail"=>1,"JOL_M_SN"=>$flag)); + }else if($status == '1' && $differtime < 18 && $differtime > 0){ + $subject = "The train ticket(s) will be issued manually, Order No $coli_id"; + $body = $this->load->view('email_fault',$data,true); + $this->send_mail_to_wl("订单:{$coli_id} 出票失败","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); + //测试阶段,将失败邮件发送一份给操作外联。 + $flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$fromName,$fromEmail,$subject,$body); + //测试阶段,将失败邮件发送一份给操作外联。 + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + $this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$jh_order),array("JOL_SendMail"=>1,"JOL_M_SN"=>$flag)); + }else{ + echo $jh_order.'不需要发邮件<br>'; + $this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$jh_order),array("JOL_SendMail"=>2)); + $flag = false; + } + } - - - + + //存储火车票开售时间 + public function add_sale_time(){ + $time = '18:00'; + $str = ''; + $station_arr = explode('、',$str); + foreach($station_arr as $station){ + $this->BIZ_train_model->sale_time_station($station,$time); + } + } + + public function update_sale_time(){ + + $this->BIZ_train_model->test(); + } + function my_post($url,$post_data){ // $url = "http://op.juhe.cn/trainTickets/cityCode"; // $post_from = array("stationName" => $from,"key"=>"79f03107b921ef31310bd40a1415c1cb"); @@ -380,6 +613,15 @@ class Auto extends CI_Controller{ // $output=json_decode($output,TRUE);//json => array return $output; - } + } + + function chk_sp_name($name){ + $name = str_replace( + array('á', 'é', 'è', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ',' ','/',' ',','), + array('a', 'e', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N','','','',''), + $name + ); + return substr(strtoupper($name),0,30); + } -} \ No newline at end of file +} diff --git a/application/third_party/train/controllers/citycode.php b/application/third_party/train/controllers/citycode.php new file mode 100644 index 00000000..8d95217f --- /dev/null +++ b/application/third_party/train/controllers/citycode.php @@ -0,0 +1,526 @@ +<?php + +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +//[{"ticket_no":"E855807446107001B","passengername":"陈斯坤","passporttypeseid":"1","passportseno":"450521199406098313"}] +class Citycode extends CI_Controller +{ + public function index(){ + header("Content-Type: text/html;charset=utf-8"); + $this->load->model("BIZ_train_model"); + // $data='{"reason":"查询全部站点简码成功", "result":[{"name":"北京北", "code":"VAP"}, {"name":"北京东", "code":"BOP"}, {"name":"北京", "code":"BJP"}, {"name":"北京南", "code":"VNP"}, {"name":"北京西", "code":"BXP"}, {"name":"广州南", "code":"IZQ"}, {"name":"重庆北", "code":"CUW"}, {"name":"重庆", "code":"CQW"}, {"name":"重庆南", "code":"CRW"}, {"name":"广州东", "code":"GGQ"}, {"name":"上海", "code":"SHH"}, {"name":"上海南", "code":"SNH"}, {"name":"上海虹桥", "code":"AOH"}, {"name":"上海西", "code":"SXH"}, {"name":"天津北", "code":"TBP"}, {"name":"天津", "code":"TJP"}, {"name":"天津南", "code":"TIP"}, {"name":"天津西", "code":"TXP"}, {"name":"长春", "code":"CCT"}, {"name":"长春南", "code":"CET"}, {"name":"长春西", "code":"CRT"}, {"name":"成都东", "code":"ICW"}, {"name":"成都南", "code":"CNW"}, {"name":"成都", "code":"CDW"}, {"name":"长沙", "code":"CSQ"}, {"name":"长沙南", "code":"CWQ"}, {"name":"福州", "code":"FZS"}, {"name":"福州南", "code":"FYS"}, {"name":"贵阳", "code":"GIW"}, {"name":"广州", "code":"GZQ"}, {"name":"广州西", "code":"GXQ"}, {"name":"哈尔滨", "code":"HBB"}, {"name":"哈尔滨东", "code":"VBB"}, {"name":"哈尔滨西", "code":"VAB"}, {"name":"合肥", "code":"HFH"}, {"name":"合肥西", "code":"HTH"}, {"name":"呼和浩特东", "code":"NDC"}, {"name":"呼和浩特", "code":"HHC"}, {"name":"海口东", "code":"HMQ"}, {"name":"海口", "code":"VUQ"}, {"name":"杭州东", "code":"HGH"}, {"name":"杭州", "code":"HZH"}, {"name":"杭州南", "code":"XHH"}, {"name":"济南", "code":"JNK"}, {"name":"济南东", "code":"JAK"}, {"name":"济南西", "code":"JGK"}, {"name":"昆明", "code":"KMM"}, {"name":"昆明西", "code":"KXM"}, {"name":"拉萨", "code":"LSO"}, {"name":"兰州东", "code":"LVJ"}, {"name":"兰州", "code":"LZJ"}, {"name":"兰州西", "code":"LAJ"}, {"name":"南昌", "code":"NCG"}, {"name":"南京", "code":"NJH"}, {"name":"南京南", "code":"NKH"}, {"name":"南宁", "code":"NNZ"}, {"name":"石家庄北", "code":"VVP"}, {"name":"石家庄", "code":"SJP"}, {"name":"沈阳", "code":"SYT"}, {"name":"沈阳北", "code":"SBT"}, {"name":"沈阳东", "code":"SDT"}, {"name":"太原北", "code":"TBV"}, {"name":"太原东", "code":"TDV"}, {"name":"太原", "code":"TYV"}, {"name":"武汉", "code":"WHN"}, {"name":"王家营西", "code":"KNM"}, {"name":"乌鲁木齐南", "code":"WMR"}, {"name":"西安北", "code":"EAY"}, {"name":"西安", "code":"XAY"}, {"name":"西安南", "code":"CAY"}, {"name":"西宁", "code":"XNO"}, {"name":"银川", "code":"YIJ"}, {"name":"郑州", "code":"ZZF"}, {"name":"阿尔山", "code":"ART"}, {"name":"安康", "code":"AKY"}, {"name":"阿克苏", "code":"ASR"}, {"name":"阿里河", "code":"AHX"}, {"name":"阿拉山口", "code":"AKR"}, {"name":"安平", "code":"APT"}, {"name":"安庆", "code":"AQH"}, {"name":"安顺", "code":"ASW"}, {"name":"鞍山", "code":"AST"}, {"name":"安阳", "code":"AYF"}, {"name":"北安", "code":"BAB"}, {"name":"蚌埠", "code":"BBH"}, {"name":"白城", "code":"BCT"}, {"name":"北海", "code":"BHZ"}, {"name":"白河", "code":"BEL"}, {"name":"白涧", "code":"BAP"}, {"name":"宝鸡", "code":"BJY"}, {"name":"滨江", "code":"BJB"}, {"name":"博克图", "code":"BKX"}, {"name":"百色", "code":"BIZ"}, {"name":"白山市", "code":"HJL"}, {"name":"北台", "code":"BTT"}, {"name":"包头东", "code":"BDC"}, {"name":"包头", "code":"BTC"}, {"name":"北屯市", "code":"BXR"}, {"name":"本溪", "code":"BXT"}, {"name":"白云鄂博", "code":"BEC"}, {"name":"白银西", "code":"BXJ"}, {"name":"亳州", "code":"BZH"}, {"name":"赤壁", "code":"CBN"}, {"name":"常德", "code":"VGQ"}, {"name":"承德", "code":"CDP"}, {"name":"长甸", "code":"CDT"}, {"name":"赤峰", "code":"CFD"}, {"name":"茶陵", "code":"CDG"}, {"name":"苍南", "code":"CEH"}, {"name":"昌平", "code":"CPP"}, {"name":"崇仁", "code":"CRG"}, {"name":"昌图", "code":"CTT"}, {"name":"长汀镇", "code":"CDB"}, {"name":"曹县", "code":"CXK"}, {"name":"楚雄", "code":"COM"}, {"name":"陈相屯", "code":"CXT"}, {"name":"长治北", "code":"CBF"}, {"name":"长征", "code":"CZJ"}, {"name":"池州", "code":"IYH"}, {"name":"常州", "code":"CZH"}, {"name":"郴州", "code":"CZQ"}, {"name":"长治", "code":"CZF"}, {"name":"沧州", "code":"COP"}, {"name":"崇左", "code":"CZZ"}, {"name":"大安北", "code":"RNT"}, {"name":"大成", "code":"DCT"}, {"name":"丹东", "code":"DUT"}, {"name":"东方红", "code":"DFB"}, {"name":"东莞东", "code":"DMQ"}, {"name":"大虎山", "code":"DHD"}, {"name":"敦煌", "code":"DHJ"}, {"name":"敦化", "code":"DHL"}, {"name":"德惠", "code":"DHT"}, {"name":"东京城", "code":"DJB"}, {"name":"大涧", "code":"DFP"}, {"name":"都江堰", "code":"DDW"}, {"name":"大连北", "code":"DFT"}, {"name":"大理", "code":"DKM"}, {"name":"大连", "code":"DLT"}, {"name":"定南", "code":"DNG"}, {"name":"大庆", "code":"DZX"}, {"name":"东胜", "code":"DOC"}, {"name":"大石桥", "code":"DQT"}, {"name":"大同", "code":"DTV"}, {"name":"东营", "code":"DPK"}, {"name":"大杨树", "code":"DUX"}, {"name":"都匀", "code":"RYW"}, {"name":"邓州", "code":"DOF"}, {"name":"达州", "code":"RXW"}, {"name":"德州", "code":"DZP"}, {"name":"额济纳", "code":"EJC"}, {"name":"二连", "code":"RLC"}, {"name":"恩施", "code":"ESN"}, {"name":"福鼎", "code":"FES"}, {"name":"风陵渡", "code":"FLV"}, {"name":"涪陵", "code":"FLW"}, {"name":"富拉尔基", "code":"FRX"}, {"name":"抚顺北", "code":"FET"}, {"name":"佛山", "code":"FSQ"}, {"name":"阜新", "code":"FXD"}, {"name":"阜阳", "code":"FYH"}, {"name":"格尔木", "code":"GRO"}, {"name":"广汉", "code":"GHW"}, {"name":"古交", "code":"GJV"}, {"name":"桂林北", "code":"GBZ"}, {"name":"古莲", "code":"GRX"}, {"name":"桂林", "code":"GLZ"}, {"name":"固始", "code":"GXN"}, {"name":"广水", "code":"GSN"}, {"name":"干塘", "code":"GNJ"}, {"name":"广元", "code":"GYW"}, {"name":"广州北", "code":"GBQ"}, {"name":"赣州", "code":"GZG"}, {"name":"公主岭", "code":"GLT"}, {"name":"公主岭南", "code":"GBT"}, {"name":"淮安", "code":"AUH"}, {"name":"鹤北", "code":"HMB"}, {"name":"淮北", "code":"HRH"}, {"name":"淮滨", "code":"HVN"}, {"name":"河边", "code":"HBV"}, {"name":"潢川", "code":"KCN"}, {"name":"韩城", "code":"HCY"}, {"name":"邯郸", "code":"HDP"}, {"name":"横道河子", "code":"HDB"}, {"name":"鹤岗", "code":"HGB"}, {"name":"皇姑屯", "code":"HTT"}, {"name":"红果", "code":"HEM"}, {"name":"黑河", "code":"HJB"}, {"name":"怀化", "code":"HHQ"}, {"name":"汉口", "code":"HKN"}, {"name":"葫芦岛", "code":"HLD"}, {"name":"海拉尔", "code":"HRX"}, {"name":"霍林郭勒", "code":"HWD"}, {"name":"海伦", "code":"HLB"}, {"name":"侯马", "code":"HMV"}, {"name":"哈密", "code":"HMR"}, {"name":"淮南", "code":"HAH"}, {"name":"桦南", "code":"HNB"}, {"name":"海宁西", "code":"EUH"}, {"name":"鹤庆", "code":"HQM"}, {"name":"怀柔北", "code":"HBP"}, {"name":"怀柔", "code":"HRP"}, {"name":"黄石东", "code":"OSN"}, {"name":"华山", "code":"HSY"}, {"name":"黄石", "code":"HSN"}, {"name":"黄山", "code":"HKH"}, {"name":"衡水", "code":"HSP"}, {"name":"衡阳", "code":"HYQ"}, {"name":"菏泽", "code":"HIK"}, {"name":"贺州", "code":"HXZ"}, {"name":"汉中", "code":"HOY"}, {"name":"惠州", "code":"HCQ"}, {"name":"吉安", "code":"VAG"}, {"name":"集安", "code":"JAL"}, {"name":"江边村", "code":"JBG"}, {"name":"晋城", "code":"JCF"}, {"name":"金城江", "code":"JJZ"}, {"name":"景德镇", "code":"JCG"}, {"name":"嘉峰", "code":"JFF"}, {"name":"加格达奇", "code":"JGX"}, {"name":"井冈山", "code":"JGG"}, {"name":"蛟河", "code":"JHL"}, {"name":"金华南", "code":"RNH"}, {"name":"金华", "code":"JBH"}, {"name":"九江", "code":"JJG"}, {"name":"吉林", "code":"JLL"}, {"name":"荆门", "code":"JMN"}, {"name":"佳木斯", "code":"JMB"}, {"name":"济宁", "code":"JIK"}, {"name":"集宁南", "code":"JAC"}, {"name":"酒泉", "code":"JQJ"}, {"name":"江山", "code":"JUH"}, {"name":"吉首", "code":"JIQ"}, {"name":"九台", "code":"JTL"}, {"name":"镜铁山", "code":"JVJ"}, {"name":"鸡西", "code":"JXB"}, {"name":"蓟县", "code":"JKP"}, {"name":"绩溪县", "code":"JRH"}, {"name":"嘉峪关", "code":"JGJ"}, {"name":"江油", "code":"JFW"}, {"name":"锦州", "code":"JZD"}, {"name":"金州", "code":"JZT"}, {"name":"库尔勒", "code":"KLR"}, {"name":"开封", "code":"KFF"}, {"name":"岢岚", "code":"KLV"}, {"name":"凯里", "code":"KLW"}, {"name":"喀什", "code":"KSR"}, {"name":"昆山南", "code":"KNH"}, {"name":"奎屯", "code":"KTR"}, {"name":"开原", "code":"KYT"}, {"name":"六安", "code":"UAH"}, {"name":"灵宝", "code":"LBF"}, {"name":"芦潮港", "code":"UCH"}, {"name":"隆昌", "code":"LCW"}, {"name":"陆川", "code":"LKZ"}, {"name":"利川", "code":"LCN"}, {"name":"临川", "code":"LCG"}, {"name":"潞城", "code":"UTP"}, {"name":"鹿道", "code":"LDL"}, {"name":"娄底", "code":"LDQ"}, {"name":"临汾", "code":"LFV"}, {"name":"良各庄", "code":"LGP"}, {"name":"临河", "code":"LHC"}, {"name":"漯河", "code":"LON"}, {"name":"绿化", "code":"LWJ"}, {"name":"隆化", "code":"UHP"}, {"name":"丽江", "code":"LHM"}, {"name":"临江", "code":"LQL"}, {"name":"龙井", "code":"LJL"}, {"name":"吕梁", "code":"LHV"}, {"name":"醴陵", "code":"LLG"}, {"name":"柳林南", "code":"LKV"}, {"name":"滦平", "code":"UPP"}, {"name":"六盘水", "code":"UMW"}, {"name":"灵丘", "code":"LVV"}, {"name":"旅顺", "code":"LST"}, {"name":"陇西", "code":"LXJ"}, {"name":"澧县", "code":"LEQ"}, {"name":"兰溪", "code":"LWH"}, {"name":"临西", "code":"UEP"}, {"name":"龙岩", "code":"LYS"}, {"name":"耒阳", "code":"LYQ"}, {"name":"洛阳", "code":"LYF"}, {"name":"洛阳东", "code":"LDF"}, {"name":"连云港东", "code":"UKH"}, {"name":"临沂", "code":"LVK"}, {"name":"洛阳龙门", "code":"LLF"}, {"name":"柳园", "code":"DHR"}, {"name":"凌源", "code":"LYD"}, {"name":"辽源", "code":"LYL"}, {"name":"立志", "code":"LZX"}, {"name":"柳州", "code":"LZZ"}, {"name":"辽中", "code":"LZD"}, {"name":"麻城", "code":"MCN"}, {"name":"免渡河", "code":"MDX"}, {"name":"牡丹江", "code":"MDB"}, {"name":"莫尔道嘎", "code":"MRX"}, {"name":"满归", "code":"MHX"}, {"name":"明光", "code":"MGH"}, {"name":"漠河", "code":"MVX"}, {"name":"茂名东", "code":"MDQ"}, {"name":"茂名", "code":"MMZ"}, {"name":"密山", "code":"MSB"}, {"name":"马三家", "code":"MJT"}, {"name":"麻尾", "code":"VAW"}, {"name":"绵阳", "code":"MYW"}, {"name":"梅州", "code":"MOQ"}, {"name":"满洲里", "code":"MLX"}, {"name":"宁波东", "code":"NVH"}, {"name":"宁波", "code":"NGH"}, {"name":"南岔", "code":"NCB"}, {"name":"南充", "code":"NCW"}, {"name":"南丹", "code":"NDZ"}, {"name":"南大庙", "code":"NMP"}, {"name":"南芬", "code":"NFT"}, {"name":"讷河", "code":"NHX"}, {"name":"嫩江", "code":"NGX"}, {"name":"内江", "code":"NJW"}, {"name":"南平", "code":"NPS"}, {"name":"南通", "code":"NUH"}, {"name":"南阳", "code":"NFF"}, {"name":"碾子山", "code":"NZX"}, {"name":"平顶山", "code":"PEN"}, {"name":"盘锦", "code":"PVD"}, {"name":"平凉", "code":"PIJ"}, {"name":"平凉南", "code":"POJ"}, {"name":"平泉", "code":"PQP"}, {"name":"坪石", "code":"PSQ"}, {"name":"萍乡", "code":"PXG"}, {"name":"凭祥", "code":"PXZ"}, {"name":"郫县西", "code":"PCW"}, {"name":"攀枝花", "code":"PRW"}, {"name":"蕲春", "code":"QRN"}, {"name":"青城山", "code":"QSW"}, {"name":"青岛", "code":"QDK"}, {"name":"清河城", "code":"QYP"}, {"name":"黔江", "code":"QNW"}, {"name":"曲靖", "code":"QJM"}, {"name":"前进镇", "code":"QEB"}, {"name":"齐齐哈尔", "code":"QHX"}, {"name":"七台河", "code":"QTB"}, {"name":"沁县", "code":"QVV"}, {"name":"泉州东", "code":"QRS"}, {"name":"泉州", "code":"QYS"}, {"name":"衢州", "code":"QEH"}, {"name":"融安", "code":"RAZ"}, {"name":"汝箕沟", "code":"RQJ"}, {"name":"瑞金", "code":"RJG"}, {"name":"日照", "code":"RZK"}, {"name":"双城堡", "code":"SCB"}, {"name":"绥芬河", "code":"SFB"}, {"name":"韶关东", "code":"SGQ"}, {"name":"山海关", "code":"SHD"}, {"name":"绥化", "code":"SHB"}, {"name":"三间房", "code":"SFX"}, {"name":"苏家屯", "code":"SXT"}, {"name":"舒兰", "code":"SLL"}, {"name":"三明", "code":"SMS"}, {"name":"神木", "code":"OMY"}, {"name":"三门峡", "code":"SMF"}, {"name":"商南", "code":"ONY"}, {"name":"遂宁", "code":"NIW"}, {"name":"四平", "code":"SPT"}, {"name":"商丘", "code":"SQF"}, {"name":"上饶", "code":"SRG"}, {"name":"韶山", "code":"SSQ"}, {"name":"宿松", "code":"OAH"}, {"name":"汕头", "code":"OTQ"}, {"name":"邵武", "code":"SWS"}, {"name":"涉县", "code":"OEP"}, {"name":"三亚", "code":"SEQ"}, {"name":"邵阳", "code":"SYQ"}, {"name":"十堰", "code":"SNN"}, {"name":"双鸭山", "code":"SSB"}, {"name":"松原", "code":"VYT"}, {"name":"深圳", "code":"SZQ"}, {"name":"苏州", "code":"SZH"}, {"name":"随州", "code":"SZN"}, {"name":"宿州", "code":"OXH"}, {"name":"朔州", "code":"SUV"}, {"name":"深圳西", "code":"OSQ"}, {"name":"塘豹", "code":"TBQ"}, {"name":"塔尔气", "code":"TVX"}, {"name":"潼关", "code":"TGY"}, {"name":"塘沽", "code":"TGP"}, {"name":"塔河", "code":"TXX"}, {"name":"通化", "code":"THL"}, {"name":"泰来", "code":"TLX"}, {"name":"吐鲁番", "code":"TFR"}, {"name":"通辽", "code":"TLD"}, {"name":"铁岭", "code":"TLT"}, {"name":"陶赖昭", "code":"TPT"}, {"name":"图们", "code":"TML"}, {"name":"铜仁", "code":"RDQ"}, {"name":"唐山北", "code":"FUP"}, {"name":"田师府", "code":"TFT"}, {"name":"泰山", "code":"TAK"}, {"name":"唐山", "code":"TSP"}, {"name":"天水", "code":"TSJ"}, {"name":"通远堡", "code":"TYT"}, {"name":"太阳升", "code":"TQT"}, {"name":"泰州", "code":"UTH"}, {"name":"桐梓", "code":"TZW"}, {"name":"通州西", "code":"TAP"}, {"name":"五常", "code":"WCB"}, {"name":"武昌", "code":"WCN"}, {"name":"瓦房店", "code":"WDT"}, {"name":"威海", "code":"WKK"}, {"name":"芜湖", "code":"WHH"}, {"name":"乌海西", "code":"WXC"}, {"name":"吴家屯", "code":"WJT"}, {"name":"武隆", "code":"WLW"}, {"name":"乌兰浩特", "code":"WWT"}, {"name":"渭南", "code":"WNY"}, {"name":"威舍", "code":"WSM"}, {"name":"歪头山", "code":"WIT"}, {"name":"武威", "code":"WUJ"}, {"name":"武威南", "code":"WWJ"}, {"name":"无锡", "code":"WXH"}, {"name":"乌西", "code":"WXR"}, {"name":"乌伊岭", "code":"WPB"}, {"name":"武夷山", "code":"WAS"}, {"name":"万源", "code":"WYY"}, {"name":"万州", "code":"WYW"}, {"name":"梧州", "code":"WZZ"}, {"name":"温州", "code":"RZH"}, {"name":"温州南", "code":"VRH"}, {"name":"西昌", "code":"ECW"}, {"name":"许昌", "code":"XCF"}, {"name":"西昌南", "code":"ENW"}, {"name":"香坊", "code":"XFB"}, {"name":"轩岗", "code":"XGV"}, {"name":"兴国", "code":"EUG"}, {"name":"宣汉", "code":"XHY"}, {"name":"新会", "code":"EFQ"}, {"name":"新晃", "code":"XLQ"}, {"name":"锡林浩特", "code":"XTC"}, {"name":"兴隆县", "code":"EXP"}, {"name":"厦门北", "code":"XKS"}, {"name":"厦门", "code":"XMS"}, {"name":"厦门高崎", "code":"XBS"}, {"name":"秀山", "code":"ETW"}, {"name":"小市", "code":"XST"}, {"name":"向塘", "code":"XTG"}, {"name":"宣威", "code":"XWM"}, {"name":"新乡", "code":"XXF"}, {"name":"信阳", "code":"XUN"}, {"name":"咸阳", "code":"XYY"}, {"name":"襄阳", "code":"XFN"}, {"name":"熊岳城", "code":"XYT"}, {"name":"兴义", "code":"XRZ"}, {"name":"新沂", "code":"VIH"}, {"name":"新余", "code":"XUG"}, {"name":"徐州", "code":"XCH"}, {"name":"延安", "code":"YWY"}, {"name":"宜宾", "code":"YBW"}, {"name":"亚布力南", "code":"YWB"}, {"name":"叶柏寿", "code":"YBD"}, {"name":"宜昌东", "code":"HAN"}, {"name":"永川", "code":"YCW"}, {"name":"宜昌", "code":"YCN"}, {"name":"盐城", "code":"AFH"}, {"name":"运城", "code":"YNV"}, {"name":"伊春", "code":"YCB"}, {"name":"榆次", "code":"YCV"}, {"name":"杨村", "code":"YBP"}, {"name":"宜春西", "code":"YCG"}, {"name":"伊尔施", "code":"YET"}, {"name":"燕岗", "code":"YGW"}, {"name":"永济", "code":"YIV"}, {"name":"延吉", "code":"YJL"}, {"name":"营口", "code":"YKT"}, {"name":"牙克石", "code":"YKX"}, {"name":"阎良", "code":"YNY"}, {"name":"玉林", "code":"YLZ"}, {"name":"榆林", "code":"ALY"}, {"name":"一面坡", "code":"YPB"}, {"name":"伊宁", "code":"YMR"}, {"name":"阳平关", "code":"YAY"}, {"name":"玉屏", "code":"YZW"}, {"name":"原平", "code":"YPV"}, {"name":"延庆", "code":"YNP"}, {"name":"阳泉曲", "code":"YYV"}, {"name":"玉泉", "code":"YQB"}, {"name":"阳泉", "code":"AQP"}, {"name":"玉山", "code":"YNG"}, {"name":"营山", "code":"NUW"}, {"name":"燕山", "code":"AOP"}, {"name":"榆树", "code":"YRT"}, {"name":"鹰潭", "code":"YTG"}, {"name":"烟台", "code":"YAK"}, {"name":"伊图里河", "code":"YEX"}, {"name":"玉田县", "code":"ATP"}, {"name":"义乌", "code":"YWH"}, {"name":"阳新", "code":"YON"}, {"name":"义县", "code":"YXD"}, {"name":"益阳", "code":"AEQ"}, {"name":"岳阳", "code":"YYQ"}, {"name":"永州", "code":"AOQ"}, {"name":"扬州", "code":"YLH"}, {"name":"淄博", "code":"ZBK"}, {"name":"镇城底", "code":"ZDV"}, {"name":"自贡", "code":"ZGW"}, {"name":"珠海", "code":"ZHQ"}, {"name":"珠海北", "code":"ZIQ"}, {"name":"湛江", "code":"ZJZ"}, {"name":"镇江", "code":"ZJH"}, {"name":"张家界", "code":"DIQ"}, {"name":"张家口", "code":"ZKP"}, {"name":"张家口南", "code":"ZMP"}, {"name":"周口", "code":"ZKN"}, {"name":"哲里木", "code":"ZLC"}, {"name":"扎兰屯", "code":"ZTX"}, {"name":"驻马店", "code":"ZDN"}, {"name":"肇庆", "code":"ZVQ"}, {"name":"周水子", "code":"ZIT"}, {"name":"昭通", "code":"ZDW"}, {"name":"中卫", "code":"ZWJ"}, {"name":"资阳", "code":"ZYW"}, {"name":"遵义", "code":"ZIW"}, {"name":"枣庄", "code":"ZEK"}, {"name":"资中", "code":"ZZW"}, {"name":"株洲", "code":"ZZQ"}, {"name":"枣庄西", "code":"ZFK"}, {"name":"昂昂溪", "code":"AAX"}, {"name":"阿城", "code":"ACB"}, {"name":"安达", "code":"ADX"}, {"name":"安德", "code":"ARW"}, {"name":"安定", "code":"ADP"}, {"name":"安广", "code":"AGT"}, {"name":"艾河", "code":"AHP"}, {"name":"安化", "code":"PKQ"}, {"name":"艾家村", "code":"AJJ"}, {"name":"鳌江", "code":"ARH"}, {"name":"安家", "code":"AJB"}, {"name":"阿金", "code":"AJD"}, {"name":"阿克陶", "code":"AER"}, {"name":"安口窑", "code":"AYY"}, {"name":"敖力布告", "code":"ALD"}, {"name":"安龙", "code":"AUZ"}, {"name":"阿龙山", "code":"ASX"}, {"name":"安陆", "code":"ALN"}, {"name":"阿木尔", "code":"JTX"}, {"name":"阿南庄", "code":"AZM"}, {"name":"安庆西", "code":"APH"}, {"name":"鞍山西", "code":"AXT"}, {"name":"安塘", "code":"ATV"}, {"name":"安亭北", "code":"ASH"}, {"name":"阿图什", "code":"ATR"}, {"name":"安图", "code":"ATL"}, {"name":"安溪", "code":"AXS"}, {"name":"博鳌", "code":"BWQ"}, {"name":"北碚", "code":"BPW"}, {"name":"白壁关", "code":"BGV"}, {"name":"蚌埠南", "code":"BMH"}, {"name":"巴楚", "code":"BCR"}, {"name":"板城", "code":"BUP"}, {"name":"北戴河", "code":"BEP"}, {"name":"保定", "code":"BDP"}, {"name":"宝坻", "code":"BPP"}, {"name":"八达岭", "code":"ILP"}, {"name":"巴东", "code":"BNN"}, {"name":"柏果", "code":"BGM"}, {"name":"布海", "code":"BUT"}, {"name":"白河东", "code":"BIY"}, {"name":"贲红", "code":"BVC"}, {"name":"宝华山", "code":"BWH"}, {"name":"白河县", "code":"BEY"}, {"name":"白芨沟", "code":"BJJ"}, {"name":"碧鸡关", "code":"BJM"}, {"name":"北滘", "code":"IBQ"}, {"name":"碧江", "code":"BLQ"}, {"name":"白鸡坡", "code":"BBM"}, {"name":"笔架山", "code":"BSB"}, {"name":"八角台", "code":"BTD"}, {"name":"保康", "code":"BKD"}, {"name":"白奎堡", "code":"BKB"}, {"name":"白狼", "code":"BAT"}, {"name":"百浪", "code":"BRZ"}, {"name":"博乐", "code":"BOR"}, {"name":"宝拉格", "code":"BQC"}, {"name":"巴林", "code":"BLX"}, {"name":"宝林", "code":"BNB"}, {"name":"北流", "code":"BOZ"}, {"name":"勃利", "code":"BLB"}, {"name":"布列开", "code":"BLR"}, {"name":"宝龙山", "code":"BND"}, {"name":"百里峡", "code":"AAP"}, {"name":"八面城", "code":"BMD"}, {"name":"班猫箐", "code":"BNM"}, {"name":"八面通", "code":"BMB"}, {"name":"北马圈子", "code":"BRP"}, {"name":"北票南", "code":"RPD"}, {"name":"白旗", "code":"BQP"}, {"name":"宝泉岭", "code":"BQB"}, {"name":"白泉", "code":"BQL"}, {"name":"白沙", "code":"BSW"}, {"name":"巴山", "code":"BAY"}, {"name":"白水江", "code":"BSY"}, {"name":"白沙坡", "code":"BPM"}, {"name":"白石山", "code":"BAL"}, {"name":"白水镇", "code":"BUM"}, {"name":"坂田", "code":"BTQ"}, {"name":"泊头", "code":"BZP"}, {"name":"北屯", "code":"BYP"}, {"name":"本溪湖", "code":"BHT"}, {"name":"博兴", "code":"BXK"}, {"name":"八仙筒", "code":"VXD"}, {"name":"白音察干", "code":"BYC"}, {"name":"背荫河", "code":"BYB"}, {"name":"北营", "code":"BIV"}, {"name":"巴彦高勒", "code":"BAC"}, {"name":"白音他拉", "code":"BID"}, {"name":"鲅鱼圈", "code":"BYT"}, {"name":"白银市", "code":"BNJ"}, {"name":"白音胡硕", "code":"BCD"}, {"name":"巴中", "code":"IEW"}, {"name":"霸州", "code":"RMP"}, {"name":"北宅", "code":"BVP"}, {"name":"赤壁北", "code":"CIN"}, {"name":"查布嘎", "code":"CBC"}, {"name":"长城", "code":"CEJ"}, {"name":"长冲", "code":"CCM"}, {"name":"承德东", "code":"CCP"}, {"name":"赤峰西", "code":"CID"}, {"name":"嵯岗", "code":"CAX"}, {"name":"柴岗", "code":"CGT"}, {"name":"长葛", "code":"CEF"}, {"name":"柴沟堡", "code":"CGV"}, {"name":"城固", "code":"CGY"}, {"name":"陈官营", "code":"CAJ"}, {"name":"成高子", "code":"CZB"}, {"name":"草海", "code":"WBW"}, {"name":"柴河", "code":"CHB"}, {"name":"册亨", "code":"CHZ"}, {"name":"草河口", "code":"CKT"}, {"name":"崔黄口", "code":"CHP"}, {"name":"巢湖", "code":"CIH"}, {"name":"蔡家沟", "code":"CJT"}, {"name":"成吉思汗", "code":"CJX"}, {"name":"岔江", "code":"CAM"}, {"name":"蔡家坡", "code":"CJY"}, {"name":"昌乐", "code":"CLK"}, {"name":"超梁沟", "code":"CYP"}, {"name":"慈利", "code":"CUQ"}, {"name":"昌黎", "code":"CLP"}, {"name":"长岭子", "code":"CLT"}, {"name":"晨明", "code":"CMB"}, {"name":"长农", "code":"CNJ"}, {"name":"昌平北", "code":"VBP"}, {"name":"常平", "code":"DAQ"}, {"name":"长坡岭", "code":"CPM"}, {"name":"辰清", "code":"CQB"}, {"name":"蔡山", "code":"CON"}, {"name":"楚山", "code":"CSB"}, {"name":"长寿", "code":"EFW"}, {"name":"磁山", "code":"CSP"}, {"name":"苍石", "code":"CST"}, {"name":"草市", "code":"CSL"}, {"name":"察素齐", "code":"CSC"}, {"name":"长山屯", "code":"CVT"}, {"name":"长汀", "code":"CES"}, {"name":"昌图西", "code":"CPT"}, {"name":"春湾", "code":"CQQ"}, {"name":"磁县", "code":"CIP"}, {"name":"岑溪", "code":"CNZ"}, {"name":"辰溪", "code":"CXQ"}, {"name":"磁西", "code":"CRP"}, {"name":"长兴南", "code":"CFH"}, {"name":"磁窑", "code":"CYK"}, {"name":"朝阳", "code":"CYD"}, {"name":"春阳", "code":"CAL"}, {"name":"城阳", "code":"CEK"}, {"name":"创业村", "code":"CEX"}, {"name":"朝阳川", "code":"CYL"}, {"name":"朝阳地", "code":"CDD"}, {"name":"长垣", "code":"CYF"}, {"name":"朝阳镇", "code":"CZL"}, {"name":"滁州北", "code":"CUH"}, {"name":"常州北", "code":"ESH"}, {"name":"滁州", "code":"CXH"}, {"name":"潮州", "code":"CKQ"}, {"name":"常庄", "code":"CVK"}, {"name":"曹子里", "code":"CFP"}, {"name":"车转湾", "code":"CWM"}, {"name":"郴州西", "code":"ICQ"}, {"name":"沧州西", "code":"CBP"}, {"name":"德安", "code":"DAG"}, {"name":"大安", "code":"RAT"}, {"name":"大坝", "code":"DBJ"}, {"name":"大板", "code":"DBC"}, {"name":"大巴", "code":"DBD"}, {"name":"到保", "code":"RBT"}, {"name":"定边", "code":"DYJ"}, {"name":"东边井", "code":"DBB"}, {"name":"德伯斯", "code":"RDT"}, {"name":"打柴沟", "code":"DGJ"}, {"name":"德昌", "code":"DVW"}, {"name":"滴道", "code":"DDB"}, {"name":"大磴沟", "code":"DKJ"}, {"name":"刀尔登", "code":"DRD"}, {"name":"得耳布尔", "code":"DRX"}, {"name":"东方", "code":"UFQ"}, {"name":"丹凤", "code":"DGY"}, {"name":"东丰", "code":"DIL"}, {"name":"都格", "code":"DMM"}, {"name":"大官屯", "code":"DTT"}, {"name":"大关", "code":"RGW"}, {"name":"东光", "code":"DGP"}, {"name":"东海", "code":"DHB"}, {"name":"大灰厂", "code":"DHP"}, {"name":"大红旗", "code":"DQD"}, {"name":"大禾塘", "code":"SOQ"}, {"name":"东海县", "code":"DQH"}, {"name":"德惠西", "code":"DXT"}, {"name":"达家沟", "code":"DJT"}, {"name":"东津", "code":"DKB"}, {"name":"杜家", "code":"DJL"}, {"name":"大口屯", "code":"DKP"}, {"name":"东来", "code":"RVD"}, {"name":"德令哈", "code":"DHO"}, {"name":"大陆号", "code":"DLC"}, {"name":"带岭", "code":"DLB"}, {"name":"大林", "code":"DLD"}, {"name":"达拉特旗", "code":"DIC"}, {"name":"独立屯", "code":"DTX"}, {"name":"豆罗", "code":"DLV"}, {"name":"达拉特西", "code":"DNC"}, {"name":"东明村", "code":"DMD"}, {"name":"洞庙河", "code":"DEP"}, {"name":"东明县", "code":"DNF"}, {"name":"大拟", "code":"DNZ"}, {"name":"大平房", "code":"DPD"}, {"name":"大盘石", "code":"RPP"}, {"name":"大埔", "code":"DPI"}, {"name":"大堡", "code":"DVT"}, {"name":"大庆东", "code":"LFX"}, {"name":"大其拉哈", "code":"DQX"}, {"name":"道清", "code":"DML"}, {"name":"对青山", "code":"DQB"}, {"name":"德清西", "code":"MOH"}, {"name":"大庆西", "code":"RHX"}, {"name":"东升", "code":"DRQ"}, {"name":"独山", "code":"RWW"}, {"name":"砀山", "code":"DKH"}, {"name":"登沙河", "code":"DWT"}, {"name":"读书铺", "code":"DPM"}, {"name":"大石头", "code":"DSL"}, {"name":"东胜西", "code":"DYC"}, {"name":"大石寨", "code":"RZT"}, {"name":"东台", "code":"DBH"}, {"name":"定陶", "code":"DQK"}, {"name":"灯塔", "code":"DGT"}, {"name":"大田边", "code":"DBM"}, {"name":"东通化", "code":"DTL"}, {"name":"丹徒", "code":"RUH"}, {"name":"大屯", "code":"DNT"}, {"name":"东湾", "code":"DRJ"}, {"name":"大武口", "code":"DFJ"}, {"name":"低窝铺", "code":"DWJ"}, {"name":"大王滩", "code":"DZZ"}, {"name":"大湾子", "code":"DFM"}, {"name":"大兴沟", "code":"DXL"}, {"name":"大兴", "code":"DXX"}, {"name":"定西", "code":"DSJ"}, {"name":"甸心", "code":"DXM"}, {"name":"东乡", "code":"DXG"}, {"name":"代县", "code":"DKV"}, {"name":"定襄", "code":"DXV"}, {"name":"东戌", "code":"RXP"}, {"name":"东辛庄", "code":"DXD"}, {"name":"德阳", "code":"DYW"}, {"name":"丹阳", "code":"DYH"}, {"name":"大雁", "code":"DYX"}, {"name":"当阳", "code":"DYN"}, {"name":"丹阳北", "code":"EXH"}, {"name":"大英东", "code":"IAW"}, {"name":"东淤地", "code":"DBV"}, {"name":"大营", "code":"DYV"}, {"name":"定远", "code":"EWH"}, {"name":"岱岳", "code":"RYV"}, {"name":"大元", "code":"DYZ"}, {"name":"大营镇", "code":"DJP"}, {"name":"大营子", "code":"DZD"}, {"name":"大战场", "code":"DTJ"}, {"name":"德州东", "code":"DIP"}, {"name":"低庄", "code":"DVQ"}, {"name":"东镇", "code":"DNV"}, {"name":"道州", "code":"DFZ"}, {"name":"东至", "code":"DCH"}, {"name":"东庄", "code":"DZV"}, {"name":"兑镇", "code":"DWV"}, {"name":"豆庄", "code":"ROP"}, {"name":"定州", "code":"DXP"}, {"name":"大竹园", "code":"DZY"}, {"name":"大杖子", "code":"DAP"}, {"name":"豆张庄", "code":"RZP"}, {"name":"峨边", "code":"EBW"}, {"name":"二道沟门", "code":"RDP"}, {"name":"二道湾", "code":"RDX"}, {"name":"鄂尔多斯", "code":"EEC"}, {"name":"二龙", "code":"RLD"}, {"name":"二龙山屯", "code":"ELA"}, {"name":"峨眉", "code":"EMW"}, {"name":"二密河", "code":"RML"}, {"name":"二营", "code":"RYJ"}, {"name":"鄂州", "code":"ECN"}, {"name":"福安", "code":"FAS"}, {"name":"丰城", "code":"FCG"}, {"name":"丰城南", "code":"FNG"}, {"name":"肥东", "code":"FIH"}, {"name":"发耳", "code":"FEM"}, {"name":"富海", "code":"FHX"}, {"name":"福海", "code":"FHR"}, {"name":"凤凰城", "code":"FHT"}, {"name":"奉化", "code":"FHH"}, {"name":"富锦", "code":"FIB"}, {"name":"范家屯", "code":"FTT"}, {"name":"福利区", "code":"FLJ"}, {"name":"福利屯", "code":"FTB"}, {"name":"丰乐镇", "code":"FZB"}, {"name":"阜南", "code":"FNH"}, {"name":"阜宁", "code":"AKH"}, {"name":"抚宁", "code":"FNP"}, {"name":"福清", "code":"FQS"}, {"name":"福泉", "code":"VMW"}, {"name":"丰水村", "code":"FSJ"}, {"name":"丰顺", "code":"FUQ"}, {"name":"繁峙", "code":"FSV"}, {"name":"抚顺", "code":"FST"}, {"name":"福山口", "code":"FKP"}, {"name":"扶绥", "code":"FSZ"}, {"name":"冯屯", "code":"FTX"}, {"name":"浮图峪", "code":"FYP"}, {"name":"富县东", "code":"FDY"}, {"name":"凤县", "code":"FXY"}, {"name":"富县", "code":"FEY"}, {"name":"费县", "code":"FXK"}, {"name":"凤阳", "code":"FUH"}, {"name":"汾阳", "code":"FAV"}, {"name":"扶余北", "code":"FBT"}, {"name":"分宜", "code":"FYG"}, {"name":"富源", "code":"FYM"}, {"name":"扶余", "code":"FYT"}, {"name":"富裕", "code":"FYX"}, {"name":"抚州北", "code":"FBG"}, {"name":"凤州", "code":"FZY"}, {"name":"丰镇", "code":"FZC"}, {"name":"范镇", "code":"VZK"}, {"name":"固安", "code":"GFP"}, {"name":"广安", "code":"VJW"}, {"name":"高碑店", "code":"GBP"}, {"name":"沟帮子", "code":"GBD"}, {"name":"甘草店", "code":"GDJ"}, {"name":"谷城", "code":"GCN"}, {"name":"藁城", "code":"GEP"}, {"name":"高村", "code":"GCV"}, {"name":"古城镇", "code":"GZB"}, {"name":"广德", "code":"GRH"}, {"name":"贵定", "code":"GTW"}, {"name":"贵定南", "code":"IDW"}, {"name":"古东", "code":"GDV"}, {"name":"贵港", "code":"GGZ"}, {"name":"官高", "code":"GVP"}, {"name":"葛根庙", "code":"GGT"}, {"name":"干沟", "code":"GGL"}, {"name":"甘谷", "code":"GGJ"}, {"name":"高各庄", "code":"GGP"}, {"name":"甘河", "code":"GAX"}, {"name":"根河", "code":"GEX"}, {"name":"郭家店", "code":"GDT"}, {"name":"孤家子", "code":"GKT"}, {"name":"古浪", "code":"GLJ"}, {"name":"皋兰", "code":"GEJ"}, {"name":"高楼房", "code":"GFM"}, {"name":"归流河", "code":"GHT"}, {"name":"关林", "code":"GLF"}, {"name":"甘洛", "code":"VOW"}, {"name":"郭磊庄", "code":"GLP"}, {"name":"高密", "code":"GMK"}, {"name":"公庙子", "code":"GMC"}, {"name":"工农湖", "code":"GRT"}, {"name":"广宁寺", "code":"GNT"}, {"name":"广南卫", "code":"GNM"}, {"name":"高平", "code":"GPF"}, {"name":"甘泉北", "code":"GEY"}, {"name":"共青城", "code":"GAG"}, {"name":"甘旗卡", "code":"GQD"}, {"name":"甘泉", "code":"GQY"}, {"name":"高桥镇", "code":"GZD"}, {"name":"赶水", "code":"GSW"}, {"name":"灌水", "code":"GST"}, {"name":"孤山口", "code":"GSP"}, {"name":"果松", "code":"GSL"}, {"name":"高山子", "code":"GSD"}, {"name":"嘎什甸子", "code":"GXD"}, {"name":"高台", "code":"GTJ"}, {"name":"高滩", "code":"GAY"}, {"name":"古田", "code":"GTS"}, {"name":"官厅", "code":"GTP"}, {"name":"官厅西", "code":"KEP"}, {"name":"贵溪", "code":"GXG"}, {"name":"涡阳", "code":"GYH"}, {"name":"巩义", "code":"GXF"}, {"name":"高邑", "code":"GIP"}, {"name":"巩义南", "code":"GYF"}, {"name":"广元南", "code":"GAW"}, {"name":"固原", "code":"GUJ"}, {"name":"菇园", "code":"GYL"}, {"name":"公营子", "code":"GYD"}, {"name":"光泽", "code":"GZS"}, {"name":"古镇", "code":"GNQ"}, {"name":"瓜州", "code":"GZJ"}, {"name":"高州", "code":"GSQ"}, {"name":"固镇", "code":"GEH"}, {"name":"盖州", "code":"GXT"}, {"name":"官字井", "code":"GOT"}, {"name":"革镇堡", "code":"GZT"}, {"name":"冠豸山", "code":"GSS"}, {"name":"盖州西", "code":"GAT"}, {"name":"红安", "code":"HWN"}, {"name":"淮安南", "code":"AMH"}, {"name":"红安西", "code":"VXN"}, {"name":"海安县", "code":"HIH"}, {"name":"黄柏", "code":"HBL"}, {"name":"海北", "code":"HEB"}, {"name":"鹤壁", "code":"HAF"}, {"name":"华城", "code":"VCQ"}, {"name":"合川", "code":"WKW"}, {"name":"河唇", "code":"HCZ"}, {"name":"汉川", "code":"HCN"}, {"name":"海城", "code":"HCT"}, {"name":"黑冲滩", "code":"HCJ"}, {"name":"黄村", "code":"HCP"}, {"name":"海城西", "code":"HXT"}, {"name":"化德", "code":"HGC"}, {"name":"洪洞", "code":"HDV"}, {"name":"霍尔果斯", "code":"HFR"}, {"name":"横峰", "code":"HFG"}, {"name":"韩府湾", "code":"HXJ"}, {"name":"汉沽", "code":"HGP"}, {"name":"红光镇", "code":"IGW"}, {"name":"浑河", "code":"HHT"}, {"name":"红花沟", "code":"VHD"}, {"name":"黄花筒", "code":"HUD"}, {"name":"贺家店", "code":"HJJ"}, {"name":"和静", "code":"HJR"}, {"name":"红江", "code":"HFM"}, {"name":"黑井", "code":"HIM"}, {"name":"获嘉", "code":"HJF"}, {"name":"河津", "code":"HJV"}, {"name":"涵江", "code":"HJS"}, {"name":"华家", "code":"HJT"}, {"name":"杭锦后旗", "code":"HDC"}, {"name":"河间西", "code":"HXP"}, {"name":"花家庄", "code":"HJM"}, {"name":"河口南", "code":"HKJ"}, {"name":"黄口", "code":"KOH"}, {"name":"湖口", "code":"HKG"}, {"name":"呼兰", "code":"HUB"}, {"name":"葫芦岛北", "code":"HPD"}, {"name":"浩良河", "code":"HHB"}, {"name":"哈拉海", "code":"HIT"}, {"name":"鹤立", "code":"HOB"}, {"name":"桦林", "code":"HIB"}, {"name":"黄陵", "code":"ULY"}, {"name":"海林", "code":"HRB"}, {"name":"虎林", "code":"VLB"}, {"name":"寒岭", "code":"HAT"}, {"name":"和龙", "code":"HLL"}, {"name":"海龙", "code":"HIL"}, {"name":"哈拉苏", "code":"HAX"}, {"name":"呼鲁斯太", "code":"VTJ"}, {"name":"火连寨", "code":"HLT"}, {"name":"黄梅", "code":"VEH"}, {"name":"韩麻营", "code":"HYP"}, {"name":"黄泥河", "code":"HHL"}, {"name":"海宁", "code":"HNH"}, {"name":"惠农", "code":"HMJ"}, {"name":"和平", "code":"VAQ"}, {"name":"花棚子", "code":"HZM"}, {"name":"花桥", "code":"VQH"}, {"name":"宏庆", "code":"HEY"}, {"name":"怀仁", "code":"HRV"}, {"name":"华容", "code":"HRN"}, {"name":"华山北", "code":"HDY"}, {"name":"黄松甸", "code":"HDL"}, {"name":"和什托洛盖", "code":"VSR"}, {"name":"红山", "code":"VSB"}, {"name":"汉寿", "code":"VSQ"}, {"name":"衡山", "code":"HSQ"}, {"name":"黑水", "code":"HOT"}, {"name":"惠山", "code":"VCH"}, {"name":"虎什哈", "code":"HHP"}, {"name":"红寺堡", "code":"HSJ"}, {"name":"虎石台", "code":"HUT"}, {"name":"海石湾", "code":"HSO"}, {"name":"衡山西", "code":"HEQ"}, {"name":"红砂岘", "code":"VSJ"}, {"name":"黑台", "code":"HQB"}, {"name":"桓台", "code":"VTK"}, {"name":"和田", "code":"VTR"}, {"name":"会同", "code":"VTQ"}, {"name":"海坨子", "code":"HZT"}, {"name":"黑旺", "code":"HWK"}, {"name":"海湾", "code":"RWH"}, {"name":"红星", "code":"VXB"}, {"name":"徽县", "code":"HYY"}, {"name":"红兴隆", "code":"VHB"}, {"name":"换新天", "code":"VTB"}, {"name":"红岘台", "code":"HTJ"}, {"name":"红彦", "code":"VIX"}, {"name":"合阳", "code":"HAY"}, {"name":"海阳", "code":"HYK"}, {"name":"衡阳东", "code":"HVQ"}, {"name":"华蓥", "code":"HUW"}, {"name":"汉阴", "code":"HQY"}, {"name":"黄羊滩", "code":"HGJ"}, {"name":"汉源", "code":"WHW"}, {"name":"湟源", "code":"HNO"}, {"name":"河源", "code":"VIQ"}, {"name":"花园", "code":"HUN"}, {"name":"黄羊镇", "code":"HYJ"}, {"name":"湖州", "code":"VZH"}, {"name":"化州", "code":"HZZ"}, {"name":"黄州", "code":"VON"}, {"name":"霍州", "code":"HZV"}, {"name":"惠州西", "code":"VXQ"}, {"name":"巨宝", "code":"JRT"}, {"name":"靖边", "code":"JIY"}, {"name":"金宝屯", "code":"JBD"}, {"name":"晋城北", "code":"JEF"}, {"name":"金昌", "code":"JCJ"}, {"name":"鄄城", "code":"JCK"}, {"name":"交城", "code":"JNV"}, {"name":"建昌", "code":"JFD"}, {"name":"峻德", "code":"JDB"}, {"name":"井店", "code":"JFP"}, {"name":"鸡东", "code":"JOB"}, {"name":"江都", "code":"UDH"}, {"name":"鸡冠山", "code":"JST"}, {"name":"金沟屯", "code":"VGP"}, {"name":"静海", "code":"JHP"}, {"name":"金河", "code":"JHX"}, {"name":"锦河", "code":"JHB"}, {"name":"精河", "code":"JHR"}, {"name":"精河南", "code":"JIR"}, {"name":"江华", "code":"JHZ"}, {"name":"建湖", "code":"AJH"}, {"name":"纪家沟", "code":"VJD"}, {"name":"晋江", "code":"JJS"}, {"name":"江津", "code":"JJW"}, {"name":"姜家", "code":"JJB"}, {"name":"金坑", "code":"JKT"}, {"name":"芨岭", "code":"JLJ"}, {"name":"金马村", "code":"JMM"}, {"name":"江门", "code":"JWQ"}, {"name":"角美", "code":"JES"}, {"name":"莒南", "code":"JOK"}, {"name":"井南", "code":"JNP"}, {"name":"建瓯", "code":"JVS"}, {"name":"经棚", "code":"JPC"}, {"name":"江桥", "code":"JQX"}, {"name":"九三", "code":"SSX"}, {"name":"金山北", "code":"EGH"}, {"name":"京山", "code":"JCN"}, {"name":"建始", "code":"JRN"}, {"name":"嘉善", "code":"JSH"}, {"name":"稷山", "code":"JVV"}, {"name":"吉舒", "code":"JSL"}, {"name":"建设", "code":"JET"}, {"name":"甲山", "code":"JOP"}, {"name":"建三江", "code":"JIB"}, {"name":"嘉善南", "code":"EAH"}, {"name":"金山屯", "code":"JTB"}, {"name":"江所田", "code":"JOM"}, {"name":"景泰", "code":"JTJ"}, {"name":"九台南", "code":"JNL"}, {"name":"吉文", "code":"JWX"}, {"name":"进贤", "code":"JUG"}, {"name":"莒县", "code":"JKK"}, {"name":"嘉祥", "code":"JUK"}, {"name":"介休", "code":"JXV"}, {"name":"井陉", "code":"JJP"}, {"name":"嘉兴", "code":"JXH"}, {"name":"嘉兴南", "code":"EPH"}, {"name":"夹心子", "code":"JXT"}, {"name":"简阳", "code":"JYW"}, {"name":"揭阳", "code":"JRQ"}, {"name":"建阳", "code":"JYS"}, {"name":"姜堰", "code":"UEH"}, {"name":"巨野", "code":"JYK"}, {"name":"江永", "code":"JYZ"}, {"name":"靖远", "code":"JYJ"}, {"name":"缙云", "code":"JYH"}, {"name":"江源", "code":"SZL"}, {"name":"济源", "code":"JYF"}, {"name":"靖远西", "code":"JXJ"}, {"name":"胶州北", "code":"JZK"}, {"name":"焦作东", "code":"WEF"}, {"name":"靖州", "code":"JEQ"}, {"name":"荆州", "code":"JBN"}, {"name":"金寨", "code":"JZH"}, {"name":"晋州", "code":"JXP"}, {"name":"胶州", "code":"JXK"}, {"name":"锦州南", "code":"JOD"}, {"name":"焦作", "code":"JOF"}, {"name":"旧庄窝", "code":"JVP"}, {"name":"金杖子", "code":"JYD"}, {"name":"开安", "code":"KAT"}, {"name":"库车", "code":"KCR"}, {"name":"康城", "code":"KCP"}, {"name":"库都尔", "code":"KDX"}, {"name":"宽甸", "code":"KDT"}, {"name":"克东", "code":"KOB"}, {"name":"开江", "code":"KAW"}, {"name":"康金井", "code":"KJB"}, {"name":"喀喇其", "code":"KQX"}, {"name":"开鲁", "code":"KLC"}, {"name":"克拉玛依", "code":"KHR"}, {"name":"口前", "code":"KQL"}, {"name":"奎山", "code":"KAB"}, {"name":"昆山", "code":"KSH"}, {"name":"克山", "code":"KSB"}, {"name":"开通", "code":"KTT"}, {"name":"康熙岭", "code":"KXZ"}, {"name":"昆阳", "code":"KAM"}, {"name":"克一河", "code":"KHX"}, {"name":"开原西", "code":"KXT"}, {"name":"康庄", "code":"KZP"}, {"name":"来宾", "code":"UBZ"}, {"name":"老边", "code":"LLT"}, {"name":"灵宝西", "code":"LPF"}, {"name":"龙川", "code":"LUQ"}, {"name":"乐昌", "code":"LCQ"}, {"name":"黎城", "code":"UCP"}, {"name":"聊城", "code":"UCK"}, {"name":"蓝村", "code":"LCK"}, {"name":"两当", "code":"LDY"}, {"name":"林东", "code":"LRC"}, {"name":"乐都", "code":"LDO"}, {"name":"梁底下", "code":"LDP"}, {"name":"六道河子", "code":"LVP"}, {"name":"鲁番", "code":"LVM"}, {"name":"廊坊", "code":"LJP"}, {"name":"落垡", "code":"LOP"}, {"name":"廊坊北", "code":"LFP"}, {"name":"老府", "code":"UFD"}, {"name":"兰岗", "code":"LNB"}, {"name":"龙骨甸", "code":"LGM"}, {"name":"芦沟", "code":"LOM"}, {"name":"龙沟", "code":"LGJ"}, {"name":"拉古", "code":"LGB"}, {"name":"临海", "code":"UFH"}, {"name":"林海", "code":"LXX"}, {"name":"拉哈", "code":"LHX"}, {"name":"凌海", "code":"JID"}, {"name":"柳河", "code":"LNL"}, {"name":"六合", "code":"KLH"}, {"name":"龙华", "code":"LHP"}, {"name":"滦河沿", "code":"UNP"}, {"name":"六合镇", "code":"LEX"}, {"name":"亮甲店", "code":"LRT"}, {"name":"刘家店", "code":"UDT"}, {"name":"刘家河", "code":"LVT"}, {"name":"连江", "code":"LKS"}, {"name":"李家", "code":"LJB"}, {"name":"罗江", "code":"LJW"}, {"name":"廉江", "code":"LJZ"}, {"name":"庐江", "code":"UJH"}, {"name":"两家", "code":"UJT"}, {"name":"龙江", "code":"LJX"}, {"name":"龙嘉", "code":"UJL"}, {"name":"莲江口", "code":"LHB"}, {"name":"蔺家楼", "code":"ULK"}, {"name":"李家坪", "code":"LIJ"}, {"name":"兰考", "code":"LKF"}, {"name":"林口", "code":"LKB"}, {"name":"路口铺", "code":"LKQ"}, {"name":"老莱", "code":"LAX"}, {"name":"拉林", "code":"LAB"}, {"name":"陆良", "code":"LRM"}, {"name":"龙里", "code":"LLW"}, {"name":"零陵", "code":"UWZ"}, {"name":"临澧", "code":"LWQ"}, {"name":"兰棱", "code":"LLB"}, {"name":"卢龙", "code":"UAP"}, {"name":"喇嘛甸", "code":"LMX"}, {"name":"里木店", "code":"LMB"}, {"name":"洛门", "code":"LMJ"}, {"name":"龙南", "code":"UNG"}, {"name":"梁平", "code":"UQW"}, {"name":"罗平", "code":"LPM"}, {"name":"落坡岭", "code":"LPP"}, {"name":"六盘山", "code":"UPJ"}, {"name":"乐平市", "code":"LPG"}, {"name":"临清", "code":"UQK"}, {"name":"龙泉寺", "code":"UQJ"}, {"name":"乐山北", "code":"UTW"}, {"name":"乐善村", "code":"LUM"}, {"name":"冷水江东", "code":"UDQ"}, {"name":"连山关", "code":"LGT"}, {"name":"流水沟", "code":"USP"}, {"name":"陵水", "code":"LIQ"}, {"name":"罗山", "code":"LRN"}, {"name":"鲁山", "code":"LAF"}, {"name":"丽水", "code":"USH"}, {"name":"梁山", "code":"LMK"}, {"name":"灵石", "code":"LSV"}, {"name":"露水河", "code":"LUL"}, {"name":"庐山", "code":"LSG"}, {"name":"林盛堡", "code":"LBT"}, {"name":"柳树屯", "code":"LSD"}, {"name":"龙山镇", "code":"LAS"}, {"name":"梨树镇", "code":"LSB"}, {"name":"李石寨", "code":"LET"}, {"name":"黎塘", "code":"LTZ"}, {"name":"轮台", "code":"LAR"}, {"name":"芦台", "code":"LTP"}, {"name":"龙塘坝", "code":"LBM"}, {"name":"濑湍", "code":"LVZ"}, {"name":"骆驼巷", "code":"LTJ"}, {"name":"李旺", "code":"VLJ"}, {"name":"莱芜东", "code":"LWK"}, {"name":"狼尾山", "code":"LRJ"}, {"name":"灵武", "code":"LNJ"}, {"name":"莱芜西", "code":"UXK"}, {"name":"朗乡", "code":"LXB"}, {"name":"陇县", "code":"LXY"}, {"name":"临湘", "code":"LXQ"}, {"name":"芦溪", "code":"LUG"}, {"name":"莱西", "code":"LXK"}, {"name":"林西", "code":"LXC"}, {"name":"滦县", "code":"UXP"}, {"name":"略阳", "code":"LYY"}, {"name":"莱阳", "code":"LYK"}, {"name":"辽阳", "code":"LYT"}, {"name":"临沂北", "code":"UYK"}, {"name":"凌源东", "code":"LDD"}, {"name":"连云港", "code":"UIH"}, {"name":"临颍", "code":"LNF"}, {"name":"老营", "code":"LXL"}, {"name":"龙游", "code":"LMH"}, {"name":"罗源", "code":"LVS"}, {"name":"林源", "code":"LYX"}, {"name":"涟源", "code":"LAQ"}, {"name":"涞源", "code":"LYP"}, {"name":"耒阳西", "code":"LPQ"}, {"name":"临泽", "code":"LEJ"}, {"name":"龙爪沟", "code":"LZT"}, {"name":"雷州", "code":"UAQ"}, {"name":"六枝", "code":"LIW"}, {"name":"鹿寨", "code":"LIZ"}, {"name":"来舟", "code":"LZS"}, {"name":"龙镇", "code":"LZA"}, {"name":"拉鲊", "code":"LEM"}, {"name":"兰州新区", "code":"LQJ"}, {"name":"马鞍山", "code":"MAH"}, {"name":"毛坝", "code":"MBY"}, {"name":"毛坝关", "code":"MGY"}, {"name":"麻城北", "code":"MBN"}, {"name":"渑池", "code":"MCF"}, {"name":"明城", "code":"MCL"}, {"name":"庙城", "code":"MAP"}, {"name":"渑池南", "code":"MNF"}, {"name":"茅草坪", "code":"KPM"}, {"name":"猛洞河", "code":"MUQ"}, {"name":"磨刀石", "code":"MOB"}, {"name":"弥渡", "code":"MDF"}, {"name":"帽儿山", "code":"MRB"}, {"name":"明港", "code":"MGN"}, {"name":"梅河口", "code":"MHL"}, {"name":"马皇", "code":"MHZ"}, {"name":"孟家岗", "code":"MGB"}, {"name":"美兰", "code":"MHQ"}, {"name":"汨罗东", "code":"MQQ"}, {"name":"马莲河", "code":"MHB"}, {"name":"茅岭", "code":"MLZ"}, {"name":"庙岭", "code":"MLL"}, {"name":"茂林", "code":"MLD"}, {"name":"穆棱", "code":"MLB"}, {"name":"马林", "code":"MID"}, {"name":"马龙", "code":"MGM"}, {"name":"木里图", "code":"MUD"}, {"name":"汨罗", "code":"MLQ"}, {"name":"玛纳斯湖", "code":"MNR"}, {"name":"冕宁", "code":"UGW"}, {"name":"沐滂", "code":"MPQ"}, {"name":"马桥河", "code":"MQB"}, {"name":"闽清", "code":"MQS"}, {"name":"民权", "code":"MQF"}, {"name":"明水河", "code":"MUT"}, {"name":"麻山", "code":"MAB"}, {"name":"眉山", "code":"MSW"}, {"name":"漫水湾", "code":"MKW"}, {"name":"茂舍祖", "code":"MOM"}, {"name":"米沙子", "code":"MST"}, {"name":"美溪", "code":"MEB"}, {"name":"勉县", "code":"MVY"}, {"name":"麻阳", "code":"MVQ"}, {"name":"密云北", "code":"MUP"}, {"name":"米易", "code":"MMW"}, {"name":"麦园", "code":"MYS"}, {"name":"墨玉", "code":"MUR"}, {"name":"庙庄", "code":"MZJ"}, {"name":"米脂", "code":"MEY"}, {"name":"明珠", "code":"MFQ"}, {"name":"宁安", "code":"NAB"}, {"name":"农安", "code":"NAT"}, {"name":"南博山", "code":"NBK"}, {"name":"南仇", "code":"NCK"}, {"name":"南城司", "code":"NSP"}, {"name":"宁村", "code":"NCZ"}, {"name":"宁德", "code":"NES"}, {"name":"南观村", "code":"NGP"}, {"name":"南宫东", "code":"NFP"}, {"name":"南关岭", "code":"NLT"}, {"name":"宁国", "code":"NNH"}, {"name":"宁海", "code":"NHH"}, {"name":"南河川", "code":"NHJ"}, {"name":"南华", "code":"NHS"}, {"name":"泥河子", "code":"NHD"}, {"name":"宁家", "code":"NVT"}, {"name":"南靖", "code":"NJS"}, {"name":"牛家", "code":"NJB"}, {"name":"能家", "code":"NJD"}, {"name":"南口", "code":"NKP"}, {"name":"南口前", "code":"NKT"}, {"name":"南朗", "code":"NNQ"}, {"name":"乃林", "code":"NLD"}, {"name":"尼勒克", "code":"NIR"}, {"name":"那罗", "code":"ULZ"}, {"name":"宁陵县", "code":"NLF"}, {"name":"奈曼", "code":"NMD"}, {"name":"宁明", "code":"NMZ"}, {"name":"南木", "code":"NMX"}, {"name":"南平南", "code":"NNS"}, {"name":"那铺", "code":"NPZ"}, {"name":"南桥", "code":"NQD"}, {"name":"那曲", "code":"NQO"}, {"name":"暖泉", "code":"NQJ"}, {"name":"南台", "code":"NTT"}, {"name":"南头", "code":"NOQ"}, {"name":"宁武", "code":"NWV"}, {"name":"南湾子", "code":"NWP"}, {"name":"南翔北", "code":"NEH"}, {"name":"宁乡", "code":"NXQ"}, {"name":"内乡", "code":"NXF"}, {"name":"牛心台", "code":"NXT"}, {"name":"南峪", "code":"NUP"}, {"name":"娘子关", "code":"NIP"}, {"name":"南召", "code":"NAF"}, {"name":"南杂木", "code":"NZT"}, {"name":"平安", "code":"PAL"}, {"name":"蓬安", "code":"PAW"}, {"name":"平安驿", "code":"PNO"}, {"name":"磐安镇", "code":"PAJ"}, {"name":"平安镇", "code":"PZT"}, {"name":"蒲城东", "code":"PEY"}, {"name":"蒲城", "code":"PCY"}, {"name":"裴德", "code":"PDB"}, {"name":"偏店", "code":"PRP"}, {"name":"平顶山西", "code":"BFF"}, {"name":"坡底下", "code":"PXJ"}, {"name":"瓢儿屯", "code":"PRT"}, {"name":"平房", "code":"PFB"}, {"name":"平岗", "code":"PGL"}, {"name":"平关", "code":"PGM"}, {"name":"盘关", "code":"PAM"}, {"name":"平果", "code":"PGZ"}, {"name":"徘徊北", "code":"PHP"}, {"name":"平河口", "code":"PHM"}, {"name":"盘锦北", "code":"PBD"}, {"name":"潘家店", "code":"PDP"}, {"name":"皮口", "code":"PKT"}, {"name":"普兰店", "code":"PLT"}, {"name":"偏岭", "code":"PNT"}, {"name":"平山", "code":"PSB"}, {"name":"彭山", "code":"PSW"}, {"name":"皮山", "code":"PSR"}, {"name":"彭水", "code":"PHW"}, {"name":"磐石", "code":"PSL"}, {"name":"平社", "code":"PSV"}, {"name":"平台", "code":"PVT"}, {"name":"平田", "code":"PTM"}, {"name":"莆田", "code":"PTS"}, {"name":"葡萄菁", "code":"PTW"}, {"name":"普湾", "code":"PWT"}, {"name":"平旺", "code":"PWV"}, {"name":"平型关", "code":"PGV"}, {"name":"普雄", "code":"POW"}, {"name":"郫县", "code":"PWW"}, {"name":"平洋", "code":"PYX"}, {"name":"彭阳", "code":"PYJ"}, {"name":"平遥", "code":"PYV"}, {"name":"平邑", "code":"PIK"}, {"name":"平原堡", "code":"PPJ"}, {"name":"平原", "code":"PYK"}, {"name":"平峪", "code":"PYP"}, {"name":"彭泽", "code":"PZG"}, {"name":"邳州", "code":"PJH"}, {"name":"平庄", "code":"PZD"}, {"name":"泡子", "code":"POD"}, {"name":"平庄南", "code":"PND"}, {"name":"乾安", "code":"QOT"}, {"name":"庆安", "code":"QAB"}, {"name":"迁安", "code":"QQP"}, {"name":"祁东北", "code":"QRQ"}, {"name":"七甸", "code":"QDM"}, {"name":"曲阜东", "code":"QAK"}, {"name":"庆丰", "code":"QFT"}, {"name":"奇峰塔", "code":"QVP"}, {"name":"曲阜", "code":"QFK"}, {"name":"琼海", "code":"QYQ"}, {"name":"秦皇岛", "code":"QTP"}, {"name":"千河", "code":"QUY"}, {"name":"清河", "code":"QIP"}, {"name":"清河门", "code":"QHD"}, {"name":"清华园", "code":"QHP"}, {"name":"渠旧", "code":"QJZ"}, {"name":"綦江", "code":"QJW"}, {"name":"潜江", "code":"QJN"}, {"name":"全椒", "code":"INH"}, {"name":"秦家", "code":"QJB"}, {"name":"祁家堡", "code":"QBT"}, {"name":"清涧县", "code":"QNY"}, {"name":"秦家庄", "code":"QZV"}, {"name":"七里河", "code":"QLD"}, {"name":"渠黎", "code":"QLZ"}, {"name":"秦岭", "code":"QLY"}, {"name":"青龙山", "code":"QGH"}, {"name":"祁门", "code":"QIH"}, {"name":"前磨头", "code":"QMP"}, {"name":"青山", "code":"QSB"}, {"name":"确山", "code":"QSN"}, {"name":"清水", "code":"QUJ"}, {"name":"前山", "code":"QXQ"}, {"name":"戚墅堰", "code":"QYH"}, {"name":"青田", "code":"QVH"}, {"name":"桥头", "code":"QAT"}, {"name":"青铜峡", "code":"QTJ"}, {"name":"前卫", "code":"QWD"}, {"name":"前苇塘", "code":"QWP"}, {"name":"渠县", "code":"QRW"}, {"name":"祁县", "code":"QXV"}, {"name":"青县", "code":"QXP"}, {"name":"桥西", "code":"QXJ"}, {"name":"清徐", "code":"QUV"}, {"name":"旗下营", "code":"QXC"}, {"name":"千阳", "code":"QOY"}, {"name":"沁阳", "code":"QYF"}, {"name":"泉阳", "code":"QYL"}, {"name":"祁阳北", "code":"QVQ"}, {"name":"七营", "code":"QYJ"}, {"name":"庆阳山", "code":"QSJ"}, {"name":"清远", "code":"QBQ"}, {"name":"清原", "code":"QYT"}, {"name":"钦州东", "code":"QDZ"}, {"name":"钦州", "code":"QRZ"}, {"name":"青州市", "code":"QZK"}, {"name":"瑞安", "code":"RAH"}, {"name":"荣昌", "code":"RCW"}, {"name":"瑞昌", "code":"RCG"}, {"name":"如皋", "code":"RBH"}, {"name":"容桂", "code":"RUQ"}, {"name":"任丘", "code":"RQP"}, {"name":"乳山", "code":"ROK"}, {"name":"融水", "code":"RSZ"}, {"name":"热水", "code":"RSD"}, {"name":"容县", "code":"RXZ"}, {"name":"饶阳", "code":"RVP"}, {"name":"汝阳", "code":"RYF"}, {"name":"绕阳河", "code":"RHD"}, {"name":"汝州", "code":"ROF"}, {"name":"石坝", "code":"OBJ"}, {"name":"上板城", "code":"SBP"}, {"name":"施秉", "code":"AQW"}, {"name":"上板城南", "code":"OBP"}, {"name":"世博园", "code":"ZWT"}, {"name":"双城北", "code":"SBB"}, {"name":"商城", "code":"SWN"}, {"name":"莎车", "code":"SCR"}, {"name":"顺昌", "code":"SCS"}, {"name":"舒城", "code":"OCH"}, {"name":"神池", "code":"SMV"}, {"name":"沙城", "code":"SCP"}, {"name":"石城", "code":"SCT"}, {"name":"山城镇", "code":"SCL"}, {"name":"山丹", "code":"SDJ"}, {"name":"顺德", "code":"ORQ"}, {"name":"绥德", "code":"ODY"}, {"name":"水洞", "code":"SIL"}, {"name":"商都", "code":"SXC"}, {"name":"十渡", "code":"SEP"}, {"name":"四道湾", "code":"OUD"}, {"name":"顺德学院", "code":"OJQ"}, {"name":"绅坊", "code":"OLH"}, {"name":"双丰", "code":"OFB"}, {"name":"四方台", "code":"STB"}, {"name":"水富", "code":"OTW"}, {"name":"三关口", "code":"OKJ"}, {"name":"桑根达来", "code":"OGC"}, {"name":"韶关", "code":"SNQ"}, {"name":"上高镇", "code":"SVK"}, {"name":"上杭", "code":"JBS"}, {"name":"沙海", "code":"SED"}, {"name":"松河", "code":"SBM"}, {"name":"沙河", "code":"SHP"}, {"name":"沙河口", "code":"SKT"}, {"name":"赛汗塔拉", "code":"SHC"}, {"name":"沙河市", "code":"VOP"}, {"name":"沙后所", "code":"SSD"}, {"name":"山河屯", "code":"SHL"}, {"name":"三河县", "code":"OXP"}, {"name":"四合永", "code":"OHD"}, {"name":"三汇镇", "code":"OZW"}, {"name":"双河镇", "code":"SEL"}, {"name":"石河子", "code":"SZR"}, {"name":"三合庄", "code":"SVP"}, {"name":"三家店", "code":"ODP"}, {"name":"水家湖", "code":"SQH"}, {"name":"沈家河", "code":"OJJ"}, {"name":"松江河", "code":"SJL"}, {"name":"尚家", "code":"SJB"}, {"name":"孙家", "code":"SUB"}, {"name":"沈家", "code":"OJB"}, {"name":"松江", "code":"SAH"}, {"name":"三江口", "code":"SKD"}, {"name":"司家岭", "code":"OLK"}, {"name":"松江南", "code":"IMH"}, {"name":"石景山南", "code":"SRP"}, {"name":"邵家堂", "code":"SJJ"}, {"name":"三江县", "code":"SOZ"}, {"name":"三家寨", "code":"SMM"}, {"name":"十家子", "code":"SJD"}, {"name":"松江镇", "code":"OZL"}, {"name":"施家嘴", "code":"SHM"}, {"name":"深井子", "code":"SWT"}, {"name":"什里店", "code":"OMP"}, {"name":"疏勒", "code":"SUR"}, {"name":"疏勒河", "code":"SHJ"}, {"name":"舍力虎", "code":"VLD"}, {"name":"石磷", "code":"SPB"}, {"name":"双辽", "code":"ZJD"}, {"name":"绥棱", "code":"SIB"}, {"name":"石岭", "code":"SOL"}, {"name":"石林", "code":"SLM"}, {"name":"石林南", "code":"LNM"}, {"name":"石龙", "code":"SLQ"}, {"name":"萨拉齐", "code":"SLC"}, {"name":"索伦", "code":"SNT"}, {"name":"商洛", "code":"OLY"}, {"name":"沙岭子", "code":"SLP"}, {"name":"石门县北", "code":"VFQ"}, {"name":"三门峡南", "code":"SCF"}, {"name":"三门县", "code":"OQH"}, {"name":"石门县", "code":"OMQ"}, {"name":"三门峡西", "code":"SXF"}, {"name":"肃宁", "code":"SYP"}, {"name":"宋", "code":"SOB"}, {"name":"双牌", "code":"SBZ"}, {"name":"四平东", "code":"PPT"}, {"name":"遂平", "code":"SON"}, {"name":"沙坡头", "code":"SFJ"}, {"name":"商丘南", "code":"SPF"}, {"name":"水泉", "code":"SID"}, {"name":"石泉县", "code":"SXY"}, {"name":"石桥子", "code":"SQT"}, {"name":"石人城", "code":"SRB"}, {"name":"石人", "code":"SRL"}, {"name":"山市", "code":"SQB"}, {"name":"神树", "code":"SWB"}, {"name":"鄯善", "code":"SSR"}, {"name":"三水", "code":"SJQ"}, {"name":"泗水", "code":"OSK"}, {"name":"石山", "code":"SAD"}, {"name":"松树", "code":"SFT"}, {"name":"首山", "code":"SAT"}, {"name":"三十家", "code":"SRD"}, {"name":"三十里堡", "code":"SST"}, {"name":"松树镇", "code":"SSL"}, {"name":"松桃", "code":"MZQ"}, {"name":"索图罕", "code":"SHX"}, {"name":"三堂集", "code":"SDH"}, {"name":"石头", "code":"OTB"}, {"name":"神头", "code":"SEV"}, {"name":"沙沱", "code":"SFM"}, {"name":"上万", "code":"SWP"}, {"name":"孙吴", "code":"SKB"}, {"name":"沙湾县", "code":"SXR"}, {"name":"遂溪", "code":"SXZ"}, {"name":"沙县", "code":"SAS"}, {"name":"歙县", "code":"OVH"}, {"name":"绍兴", "code":"SOH"}, {"name":"石岘", "code":"SXL"}, {"name":"上西铺", "code":"SXM"}, {"name":"石峡子", "code":"SXJ"}, {"name":"绥阳", "code":"SYB"}, {"name":"沭阳", "code":"FMH"}, {"name":"寿阳", "code":"SYV"}, {"name":"水洋", "code":"OYP"}, {"name":"三阳川", "code":"SYJ"}, {"name":"上腰墩", "code":"SPJ"}, {"name":"三营", "code":"OEJ"}, {"name":"顺义", "code":"SOP"}, {"name":"三义井", "code":"OYD"}, {"name":"三源浦", "code":"SYL"}, {"name":"三原", "code":"SAY"}, {"name":"上虞", "code":"BDH"}, {"name":"上园", "code":"SUD"}, {"name":"水源", "code":"OYJ"}, {"name":"桑园子", "code":"SAJ"}, {"name":"绥中北", "code":"SND"}, {"name":"苏州北", "code":"OHH"}, {"name":"宿州东", "code":"SRH"}, {"name":"深圳东", "code":"BJQ"}, {"name":"深州", "code":"OZP"}, {"name":"孙镇", "code":"OZY"}, {"name":"绥中", "code":"SZD"}, {"name":"尚志", "code":"SZB"}, {"name":"师庄", "code":"SNM"}, {"name":"松滋", "code":"SIN"}, {"name":"师宗", "code":"SEM"}, {"name":"苏州园区", "code":"KAH"}, {"name":"苏州新区", "code":"ITH"}, {"name":"泰安", "code":"TMK"}, {"name":"台安", "code":"TID"}, {"name":"通安驿", "code":"TAJ"}, {"name":"桐柏", "code":"TBF"}, {"name":"通北", "code":"TBB"}, {"name":"汤池", "code":"TCX"}, {"name":"桐城", "code":"TTH"}, {"name":"郯城", "code":"TZK"}, {"name":"铁厂", "code":"TCL"}, {"name":"桃村", "code":"TCK"}, {"name":"通道", "code":"TRQ"}, {"name":"田东", "code":"TDZ"}, {"name":"天岗", "code":"TGL"}, {"name":"土贵乌拉", "code":"TGC"}, {"name":"通沟", "code":"TOL"}, {"name":"太谷", "code":"TGV"}, {"name":"塔哈", "code":"THX"}, {"name":"棠海", "code":"THM"}, {"name":"唐河", "code":"THF"}, {"name":"泰和", "code":"THG"}, {"name":"太湖", "code":"TKH"}, {"name":"团结", "code":"TIX"}, {"name":"谭家井", "code":"TNJ"}, {"name":"陶家屯", "code":"TOT"}, {"name":"唐家湾", "code":"PDQ"}, {"name":"统军庄", "code":"TZP"}, {"name":"泰康", "code":"TKX"}, {"name":"吐列毛杜", "code":"TMD"}, {"name":"图里河", "code":"TEX"}, {"name":"亭亮", "code":"TIZ"}, {"name":"田林", "code":"TFZ"}, {"name":"铜陵", "code":"TJH"}, {"name":"铁力", "code":"TLB"}, {"name":"铁岭西", "code":"PXT"}, {"name":"图们北", "code":"QSL"}, {"name":"天门", "code":"TMN"}, {"name":"天门南", "code":"TNN"}, {"name":"太姥山", "code":"TLS"}, {"name":"土牧尔台", "code":"TRC"}, {"name":"土门子", "code":"TCJ"}, {"name":"潼南", "code":"TVW"}, {"name":"洮南", "code":"TVT"}, {"name":"太平川", "code":"TIT"}, {"name":"太平镇", "code":"TEB"}, {"name":"图强", "code":"TQX"}, {"name":"台前", "code":"TTK"}, {"name":"天桥岭", "code":"TQL"}, {"name":"土桥子", "code":"TQJ"}, {"name":"汤山城", "code":"TCT"}, {"name":"桃山", "code":"TAB"}, {"name":"塔石嘴", "code":"TIM"}, {"name":"通途", "code":"TUT"}, {"name":"汤旺河", "code":"THB"}, {"name":"同心", "code":"TXJ"}, {"name":"土溪", "code":"TSW"}, {"name":"桐乡", "code":"TCH"}, {"name":"田阳", "code":"TRZ"}, {"name":"天义", "code":"TND"}, {"name":"汤阴", "code":"TYF"}, {"name":"驼腰岭", "code":"TIL"}, {"name":"太阳山", "code":"TYJ"}, {"name":"汤原", "code":"TYB"}, {"name":"塔崖驿", "code":"TYP"}, {"name":"滕州东", "code":"TEK"}, {"name":"台州", "code":"TZH"}, {"name":"天祝", "code":"TZJ"}, {"name":"滕州", "code":"TXK"}, {"name":"天镇", "code":"TZV"}, {"name":"桐子林", "code":"TEW"}, {"name":"天柱山", "code":"QWH"}, {"name":"文安", "code":"WBP"}, {"name":"武安", "code":"WAP"}, {"name":"王安镇", "code":"WVP"}, {"name":"旺苍", "code":"WEW"}, {"name":"五叉沟", "code":"WCT"}, {"name":"文昌", "code":"WEQ"}, {"name":"温春", "code":"WDB"}, {"name":"五大连池", "code":"WRB"}, {"name":"文登", "code":"WBK"}, {"name":"五道沟", "code":"WDL"}, {"name":"五道河", "code":"WHP"}, {"name":"文地", "code":"WNZ"}, {"name":"卫东", "code":"WVT"}, {"name":"武当山", "code":"WRN"}, {"name":"望都", "code":"WDP"}, {"name":"乌尔旗汗", "code":"WHX"}, {"name":"潍坊", "code":"WFK"}, {"name":"万发屯", "code":"WFB"}, {"name":"王府", "code":"WUT"}, {"name":"瓦房店西", "code":"WXT"}, {"name":"王岗", "code":"WGB"}, {"name":"武功", "code":"WGY"}, {"name":"湾沟", "code":"WGL"}, {"name":"吴官田", "code":"WGM"}, {"name":"乌海", "code":"WVC"}, {"name":"苇河", "code":"WHB"}, {"name":"卫辉", "code":"WHF"}, {"name":"吴家川", "code":"WCJ"}, {"name":"五家", "code":"WUB"}, {"name":"威箐", "code":"WAM"}, {"name":"午汲", "code":"WJP"}, {"name":"渭津", "code":"WJL"}, {"name":"王家湾", "code":"WJJ"}, {"name":"倭肯", "code":"WQB"}, {"name":"五棵树", "code":"WKT"}, {"name":"五龙背", "code":"WBT"}, {"name":"乌兰哈达", "code":"WLC"}, {"name":"万乐", "code":"WEB"}, {"name":"瓦拉干", "code":"WVX"}, {"name":"温岭", "code":"VHH"}, {"name":"五莲", "code":"WLK"}, {"name":"乌拉特前旗", "code":"WQC"}, {"name":"乌拉山", "code":"WSC"}, {"name":"卧里屯", "code":"WLX"}, {"name":"渭南北", "code":"WBY"}, {"name":"乌奴耳", "code":"WRX"}, {"name":"万宁", "code":"WNQ"}, {"name":"万年", "code":"WWG"}, {"name":"渭南南", "code":"WVY"}, {"name":"渭南镇", "code":"WNJ"}, {"name":"沃皮", "code":"WPT"}, {"name":"吴堡", "code":"WUY"}, {"name":"吴桥", "code":"WUP"}, {"name":"汪清", "code":"WQL"}, {"name":"武清", "code":"WWP"}, {"name":"武山", "code":"WSJ"}, {"name":"文水", "code":"WEV"}, {"name":"魏善庄", "code":"WSP"}, {"name":"王瞳", "code":"WTP"}, {"name":"五台山", "code":"WSV"}, {"name":"王团庄", "code":"WZJ"}, {"name":"五五", "code":"WVR"}, {"name":"无锡东", "code":"WGH"}, {"name":"卫星", "code":"WVB"}, {"name":"闻喜", "code":"WXV"}, {"name":"武乡", "code":"WVV"}, {"name":"无锡新区", "code":"IFH"}, {"name":"武穴", "code":"WXN"}, {"name":"吴圩", "code":"WYZ"}, {"name":"王杨", "code":"WYB"}, {"name":"五营", "code":"WWB"}, {"name":"武义", "code":"RYH"}, {"name":"瓦窑田", "code":"WIM"}, {"name":"五原", "code":"WYC"}, {"name":"苇子沟", "code":"WZL"}, {"name":"韦庄", "code":"WZY"}, {"name":"五寨", "code":"WZV"}, {"name":"王兆屯", "code":"WZB"}, {"name":"微子镇", "code":"WQP"}, {"name":"魏杖子", "code":"WKD"}, {"name":"新安", "code":"EAM"}, {"name":"兴安", "code":"XAZ"}, {"name":"新安县", "code":"XAF"}, {"name":"新保安", "code":"XAP"}, {"name":"下板城", "code":"EBP"}, {"name":"西八里", "code":"XLP"}, {"name":"宣城", "code":"ECH"}, {"name":"兴城", "code":"XCD"}, {"name":"小村", "code":"XEM"}, {"name":"新绰源", "code":"XRX"}, {"name":"下城子", "code":"XCB"}, {"name":"新城子", "code":"XCT"}, {"name":"喜德", "code":"EDW"}, {"name":"小得江", "code":"EJM"}, {"name":"西大庙", "code":"XMP"}, {"name":"小董", "code":"XEZ"}, {"name":"小东", "code":"XOD"}, {"name":"息烽", "code":"XFW"}, {"name":"信丰", "code":"EFG"}, {"name":"襄汾", "code":"XFV"}, {"name":"新干", "code":"EGG"}, {"name":"孝感", "code":"XGN"}, {"name":"西固城", "code":"XUJ"}, {"name":"西固", "code":"XIJ"}, {"name":"夏官营", "code":"XGJ"}, {"name":"西岗子", "code":"NBB"}, {"name":"襄河", "code":"XXB"}, {"name":"新和", "code":"XIR"}, {"name":"宣和", "code":"XWJ"}, {"name":"斜河涧", "code":"EEP"}, {"name":"新华屯", "code":"XAX"}, {"name":"新华", "code":"XHB"}, {"name":"新化", "code":"EHQ"}, {"name":"宣化", "code":"XHP"}, {"name":"兴和西", "code":"XEC"}, {"name":"小河沿", "code":"XYD"}, {"name":"下花园", "code":"XYP"}, {"name":"小河镇", "code":"EKY"}, {"name":"徐家", "code":"XJB"}, {"name":"峡江", "code":"EJG"}, {"name":"新绛", "code":"XJV"}, {"name":"辛集", "code":"ENP"}, {"name":"新江", "code":"XJM"}, {"name":"西街口", "code":"EKM"}, {"name":"许家屯", "code":"XJT"}, {"name":"许家台", "code":"XTJ"}, {"name":"谢家镇", "code":"XMT"}, {"name":"兴凯", "code":"EKB"}, {"name":"小榄", "code":"EAQ"}, {"name":"香兰", "code":"XNB"}, {"name":"兴隆店", "code":"XDD"}, {"name":"新乐", "code":"ELP"}, {"name":"新林", "code":"XPX"}, {"name":"小岭", "code":"XLB"}, {"name":"新李", "code":"XLJ"}, {"name":"西林", "code":"XYB"}, {"name":"西柳", "code":"GCT"}, {"name":"仙林", "code":"XPH"}, {"name":"新立屯", "code":"XLD"}, {"name":"兴隆镇", "code":"XZB"}, {"name":"新立镇", "code":"XGT"}, {"name":"新民", "code":"XMD"}, {"name":"西麻山", "code":"XMB"}, {"name":"下马塘", "code":"XAT"}, {"name":"孝南", "code":"XNV"}, {"name":"咸宁北", "code":"XRN"}, {"name":"兴宁", "code":"ENQ"}, {"name":"咸宁", "code":"XNN"}, {"name":"犀浦东", "code":"XAW"}, {"name":"西平", "code":"XPN"}, {"name":"兴平", "code":"XPY"}, {"name":"新坪田", "code":"XPM"}, {"name":"霞浦", "code":"XOS"}, {"name":"溆浦", "code":"EPQ"}, {"name":"犀浦", "code":"XIW"}, {"name":"新青", "code":"XQB"}, {"name":"新邱", "code":"XQD"}, {"name":"兴泉堡", "code":"XQJ"}, {"name":"仙人桥", "code":"XRL"}, {"name":"小寺沟", "code":"ESP"}, {"name":"杏树", "code":"XSB"}, {"name":"夏石", "code":"XIZ"}, {"name":"浠水", "code":"XZN"}, {"name":"下社", "code":"XSV"}, {"name":"徐水", "code":"XSP"}, {"name":"小哨", "code":"XAM"}, {"name":"新松浦", "code":"XOB"}, {"name":"杏树屯", "code":"XDT"}, {"name":"许三湾", "code":"XSJ"}, {"name":"湘潭", "code":"XTQ"}, {"name":"邢台", "code":"XTP"}, {"name":"仙桃西", "code":"XAN"}, {"name":"下台子", "code":"EIP"}, {"name":"徐闻", "code":"XJQ"}, {"name":"新窝铺", "code":"EPD"}, {"name":"修武", "code":"XWF"}, {"name":"新县", "code":"XSN"}, {"name":"息县", "code":"ENN"}, {"name":"西乡", "code":"XQY"}, {"name":"湘乡", "code":"XXQ"}, {"name":"西峡", "code":"XIF"}, {"name":"孝西", "code":"XOV"}, {"name":"小新街", "code":"XXM"}, {"name":"新兴县", "code":"XGQ"}, {"name":"西小召", "code":"XZC"}, {"name":"小西庄", "code":"XXP"}, {"name":"向阳", "code":"XDB"}, {"name":"旬阳", "code":"XUY"}, {"name":"旬阳北", "code":"XBY"}, {"name":"襄阳东", "code":"XWN"}, {"name":"兴业", "code":"SNZ"}, {"name":"小雨谷", "code":"XHM"}, {"name":"信宜", "code":"EEQ"}, {"name":"小月旧", "code":"XFM"}, {"name":"小扬气", "code":"XYX"}, {"name":"祥云", "code":"EXM"}, {"name":"襄垣", "code":"EIF"}, {"name":"夏邑县", "code":"EJH"}, {"name":"新友谊", "code":"EYB"}, {"name":"新阳镇", "code":"XZJ"}, {"name":"徐州东", "code":"UUH"}, {"name":"新帐房", "code":"XZX"}, {"name":"悬钟", "code":"XRP"}, {"name":"新肇", "code":"XZT"}, {"name":"忻州", "code":"XXV"}, {"name":"汐子", "code":"XZD"}, {"name":"西哲里木", "code":"XRD"}, {"name":"新杖子", "code":"ERP"}, {"name":"姚安", "code":"YAC"}, {"name":"依安", "code":"YAX"}, {"name":"永安", "code":"YAS"}, {"name":"永安乡", "code":"YNB"}, {"name":"亚布力", "code":"YBB"}, {"name":"元宝山", "code":"YUD"}, {"name":"羊草", "code":"YAB"}, {"name":"秧草地", "code":"YKM"}, {"name":"阳澄湖", "code":"AIH"}, {"name":"迎春", "code":"YYB"}, {"name":"叶城", "code":"YER"}, {"name":"盐池", "code":"YKJ"}, {"name":"砚川", "code":"YYY"}, {"name":"阳春", "code":"YQQ"}, {"name":"宜城", "code":"YIN"}, {"name":"应城", "code":"YHN"}, {"name":"禹城", "code":"YCK"}, {"name":"晏城", "code":"YEK"}, {"name":"羊场", "code":"YED"}, {"name":"阳城", "code":"YNF"}, {"name":"阳岔", "code":"YAL"}, {"name":"郓城", "code":"YPK"}, {"name":"雁翅", "code":"YAP"}, {"name":"云彩岭", "code":"ACP"}, {"name":"虞城县", "code":"IXH"}, {"name":"营城子", "code":"YCT"}, {"name":"永登", "code":"YDJ"}, {"name":"英德", "code":"YDQ"}, {"name":"尹地", "code":"YDM"}, {"name":"永定", "code":"YGS"}, {"name":"雁荡山", "code":"YGH"}, {"name":"于都", "code":"YDG"}, {"name":"园墩", "code":"YAJ"}, {"name":"英德西", "code":"IIQ"}, {"name":"永丰营", "code":"YYM"}, {"name":"杨岗", "code":"YRB"}, {"name":"阳高", "code":"YOV"}, {"name":"阳谷", "code":"YIK"}, {"name":"友好", "code":"YOB"}, {"name":"余杭", "code":"EVH"}, {"name":"沿河城", "code":"YHP"}, {"name":"岩会", "code":"AEP"}, {"name":"羊臼河", "code":"YHM"}, {"name":"永嘉", "code":"URH"}, {"name":"营街", "code":"YAM"}, {"name":"盐津", "code":"AEW"}, {"name":"余江", "code":"YHG"}, {"name":"燕郊", "code":"AJP"}, {"name":"姚家", "code":"YAT"}, {"name":"岳家井", "code":"YGJ"}, {"name":"一间堡", "code":"YJT"}, {"name":"英吉沙", "code":"YIR"}, {"name":"云居寺", "code":"AFP"}, {"name":"燕家庄", "code":"AZK"}, {"name":"永康", "code":"RFH"}, {"name":"营口东", "code":"YGT"}, {"name":"银浪", "code":"YJX"}, {"name":"永郎", "code":"YLW"}, {"name":"宜良北", "code":"YSM"}, {"name":"永乐店", "code":"YDY"}, {"name":"伊拉哈", "code":"YLX"}, {"name":"伊林", "code":"YLB"}, {"name":"杨陵", "code":"YSY"}, {"name":"彝良", "code":"ALW"}, {"name":"杨林", "code":"YLM"}, {"name":"余粮堡", "code":"YLD"}, {"name":"杨柳青", "code":"YQP"}, {"name":"月亮田", "code":"YUM"}, {"name":"亚龙湾", "code":"TWQ"}, {"name":"义马", "code":"YMF"}, {"name":"玉门", "code":"YXJ"}, {"name":"云梦", "code":"YMN"}, {"name":"元谋", "code":"YMM"}, {"name":"阳明堡", "code":"YVV"}, {"name":"一面山", "code":"YST"}, {"name":"沂南", "code":"YNK"}, {"name":"宜耐", "code":"YVM"}, {"name":"伊宁东", "code":"YNR"}, {"name":"营盘水", "code":"YZJ"}, {"name":"羊堡", "code":"ABM"}, {"name":"阳泉北", "code":"YPP"}, {"name":"乐清", "code":"UPH"}, {"name":"焉耆", "code":"YSR"}, {"name":"源迁", "code":"AQK"}, {"name":"姚千户屯", "code":"YQT"}, {"name":"阳曲", "code":"YQV"}, {"name":"榆树沟", "code":"YGP"}, {"name":"月山", "code":"YBF"}, {"name":"玉石", "code":"YSJ"}, {"name":"偃师", "code":"YSF"}, {"name":"沂水", "code":"YUK"}, {"name":"榆社", "code":"YSV"}, {"name":"窑上", "code":"ASP"}, {"name":"元氏", "code":"YSP"}, {"name":"杨树岭", "code":"YAD"}, {"name":"野三坡", "code":"AIP"}, {"name":"榆树屯", "code":"YSX"}, {"name":"榆树台", "code":"YUT"}, {"name":"鹰手营子", "code":"YIP"}, {"name":"源潭", "code":"YTQ"}, {"name":"牙屯堡", "code":"YTZ"}, {"name":"烟筒山", "code":"YSL"}, {"name":"烟筒屯", "code":"YUX"}, {"name":"羊尾哨", "code":"YWM"}, {"name":"越西", "code":"YHW"}, {"name":"攸县", "code":"YOG"}, {"name":"玉溪", "code":"YXM"}, {"name":"永修", "code":"ACG"}, {"name":"弋阳", "code":"YIG"}, {"name":"酉阳", "code":"AFW"}, {"name":"余姚", "code":"YYH"}, {"name":"岳阳东", "code":"YIQ"}, {"name":"阳邑", "code":"ARP"}, {"name":"鸭园", "code":"YYL"}, {"name":"鸳鸯镇", "code":"YYJ"}, {"name":"燕子砭", "code":"YZY"}, {"name":"宜州", "code":"YSZ"}, {"name":"仪征", "code":"UZH"}, {"name":"兖州", "code":"YZK"}, {"name":"迤资", "code":"YQM"}, {"name":"羊者窝", "code":"AEM"}, {"name":"杨杖子", "code":"YZD"}, {"name":"镇安", "code":"ZEY"}, {"name":"治安", "code":"ZAD"}, {"name":"招柏", "code":"ZBP"}, {"name":"张百湾", "code":"ZUP"}, {"name":"中川机场", "code":"ZJJ"}, {"name":"枝城", "code":"ZCN"}, {"name":"子长", "code":"ZHY"}, {"name":"诸城", "code":"ZQK"}, {"name":"邹城", "code":"ZIK"}, {"name":"赵城", "code":"ZCV"}, {"name":"章党", "code":"ZHT"}, {"name":"正定", "code":"ZDP"}, {"name":"肇东", "code":"ZDB"}, {"name":"照福铺", "code":"ZFM"}, {"name":"章古台", "code":"ZGD"}, {"name":"赵光", "code":"ZGB"}, {"name":"中和", "code":"ZHX"}, {"name":"中华门", "code":"VNH"}, {"name":"枝江北", "code":"ZIN"}, {"name":"钟家村", "code":"ZJY"}, {"name":"朱家沟", "code":"ZUB"}, {"name":"紫荆关", "code":"ZYP"}, {"name":"周家", "code":"ZOB"}, {"name":"诸暨", "code":"ZDH"}, {"name":"镇江南", "code":"ZEH"}, {"name":"周家屯", "code":"ZOD"}, {"name":"褚家湾", "code":"CWJ"}, {"name":"湛江西", "code":"ZWQ"}, {"name":"朱家窑", "code":"ZUJ"}, {"name":"曾家坪子", "code":"ZBW"}, {"name":"张兰", "code":"ZLV"}, {"name":"镇赉", "code":"ZLT"}, {"name":"枣林", "code":"ZIV"}, {"name":"扎鲁特", "code":"ZLD"}, {"name":"扎赉诺尔西", "code":"ZXX"}, {"name":"樟木头", "code":"ZOQ"}, {"name":"中牟", "code":"ZGF"}, {"name":"中宁东", "code":"ZDJ"}, {"name":"中宁", "code":"VNJ"}, {"name":"中宁南", "code":"ZNJ"}, {"name":"镇平", "code":"ZPF"}, {"name":"漳平", "code":"ZPS"}, {"name":"泽普", "code":"ZPR"}, {"name":"枣强", "code":"ZVP"}, {"name":"张桥", "code":"ZQY"}, {"name":"章丘", "code":"ZTK"}, {"name":"朱日和", "code":"ZRC"}, {"name":"泽润里", "code":"ZLM"}, {"name":"中山北", "code":"ZGQ"}, {"name":"樟树东", "code":"ZOG"}, {"name":"中山", "code":"ZSQ"}, {"name":"柞水", "code":"ZSY"}, {"name":"钟山", "code":"ZSZ"}, {"name":"樟树", "code":"ZSG"}, {"name":"珠窝", "code":"ZOP"}, {"name":"张维屯", "code":"ZWB"}, {"name":"彰武", "code":"ZWD"}, {"name":"棕溪", "code":"ZOY"}, {"name":"钟祥", "code":"ZTN"}, {"name":"资溪", "code":"ZXS"}, {"name":"镇西", "code":"ZVT"}, {"name":"张辛", "code":"ZIP"}, {"name":"正镶白旗", "code":"ZXC"}, {"name":"紫阳", "code":"ZVY"}, {"name":"枣阳", "code":"ZYN"}, {"name":"竹园坝", "code":"ZAW"}, {"name":"张掖", "code":"ZYJ"}, {"name":"镇远", "code":"ZUW"}, {"name":"朱杨溪", "code":"ZXW"}, {"name":"漳州东", "code":"GOS"}, {"name":"漳州", "code":"ZUS"}, {"name":"壮志", "code":"ZUX"}, {"name":"子洲", "code":"ZZY"}, {"name":"中寨", "code":"ZZM"}, {"name":"涿州", "code":"ZXP"}, {"name":"咋子", "code":"ZAL"}, {"name":"卓资山", "code":"ZZC"}, {"name":"株洲西", "code":"ZAQ"}, {"name":"安仁", "code":"ARG"}, {"name":"安图西", "code":"AXL"}, {"name":"安阳东", "code":"ADF"}, {"name":"栟茶", "code":"FWH"}, {"name":"保定东", "code":"BMP"}, {"name":"滨海", "code":"FHP"}, {"name":"滨海北", "code":"FCP"}, {"name":"宝鸡南", "code":"BBY"}, {"name":"宝清", "code":"BUB"}, {"name":"本溪新城", "code":"BVT"}, {"name":"彬县", "code":"BXY"}, {"name":"宾阳", "code":"UKZ"}, {"name":"滨州", "code":"BIK"}, {"name":"巢湖东", "code":"GUH"}, {"name":"从江", "code":"KNW"}, {"name":"长临河", "code":"FVH"}, {"name":"茶陵南", "code":"CNG"}, {"name":"长庆桥", "code":"CQJ"}, {"name":"长寿北", "code":"COW"}, {"name":"潮汕", "code":"CBQ"}, {"name":"长武", "code":"CWY"}, {"name":"长兴", "code":"CBH"}, {"name":"长阳", "code":"CYN"}, {"name":"潮阳", "code":"CNQ"}, {"name":"东安东", "code":"DCZ"}, {"name":"东戴河", "code":"RDD"}, {"name":"东二道河", "code":"DRB"}, {"name":"东莞", "code":"RTQ"}, {"name":"大苴", "code":"DIM"}, {"name":"大荔", "code":"DNY"}, {"name":"大青沟", "code":"DSD"}, {"name":"德清", "code":"DRH"}, {"name":"大石头南", "code":"DAL"}, {"name":"大通西", "code":"DTO"}, {"name":"德兴", "code":"DWG"}, {"name":"丹霞山", "code":"IRQ"}, {"name":"大冶北", "code":"DBN"}, {"name":"都匀东", "code":"KJW"}, {"name":"东营南", "code":"DOK"}, {"name":"大余", "code":"DYG"}, {"name":"定州东", "code":"DOP"}, {"name":"峨眉山", "code":"IXW"}, {"name":"鄂州东", "code":"EFN"}, {"name":"防城港北", "code":"FBZ"}, {"name":"凤城东", "code":"FDT"}, {"name":"富川", "code":"FDZ"}, {"name":"丰都", "code":"FUW"}, {"name":"涪陵北", "code":"FEW"}, {"name":"抚远", "code":"FYB"}, {"name":"抚州东", "code":"FDG"}, {"name":"抚州", "code":"FZG"}, {"name":"高安", "code":"GCG"}, {"name":"广安南", "code":"VUW"}, {"name":"高碑店东", "code":"GMP"}, {"name":"恭城", "code":"GCZ"}, {"name":"贵定北", "code":"FMW"}, {"name":"葛店南", "code":"GNN"}, {"name":"贵定县", "code":"KIW"}, {"name":"广汉北", "code":"GVW"}, {"name":"革居", "code":"GEM"}, {"name":"光明城", "code":"IMQ"}, {"name":"广宁", "code":"FBQ"}, {"name":"桂平", "code":"GAZ"}, {"name":"弓棚子", "code":"GPT"}, {"name":"古田北", "code":"GBS"}, {"name":"广通北", "code":"GPM"}, {"name":"高台南", "code":"GAJ"}, {"name":"贵阳北", "code":"KQW"}, {"name":"高邑西", "code":"GNP"}, {"name":"惠安", "code":"HNS"}, {"name":"鹤壁东", "code":"HFF"}, {"name":"寒葱沟", "code":"HKB"}, {"name":"珲春", "code":"HUL"}, {"name":"邯郸东", "code":"HPP"}, {"name":"惠东", "code":"KDQ"}, {"name":"海东西", "code":"HDO"}, {"name":"洪洞西", "code":"HTV"}, {"name":"哈尔滨北", "code":"HTB"}, {"name":"合肥北城", "code":"COH"}, {"name":"合肥南", "code":"ENH"}, {"name":"黄冈", "code":"KGN"}, {"name":"黄冈东", "code":"KAN"}, {"name":"横沟桥东", "code":"HNN"}, {"name":"黄冈西", "code":"KXN"}, {"name":"洪河", "code":"HPB"}, {"name":"怀化南", "code":"KAQ"}, {"name":"黄河景区", "code":"HCF"}, {"name":"花湖", "code":"KHN"}, {"name":"怀集", "code":"FAQ"}, {"name":"河口北", "code":"HBM"}, {"name":"鲘门", "code":"KMQ"}, {"name":"虎门", "code":"IUQ"}, {"name":"侯马西", "code":"HPV"}, {"name":"衡南", "code":"HNG"}, {"name":"淮南东", "code":"HOH"}, {"name":"合浦", "code":"HVZ"}, {"name":"霍邱", "code":"FBH"}, {"name":"怀仁东", "code":"HFV"}, {"name":"华容东", "code":"HPN"}, {"name":"华容南", "code":"KRN"}, {"name":"黄石北", "code":"KSN"}, {"name":"黄山北", "code":"NYH"}, {"name":"贺胜桥东", "code":"HLN"}, {"name":"和硕", "code":"VUR"}, {"name":"花山南", "code":"KNN"}, {"name":"海阳北", "code":"HEK"}, {"name":"霍州东", "code":"HWV"}, {"name":"惠州南", "code":"KNQ"}, {"name":"泾川", "code":"JAJ"}, {"name":"旌德", "code":"NSH"}, {"name":"蛟河西", "code":"JOL"}, {"name":"军粮城北", "code":"JMP"}, {"name":"将乐", "code":"JLS"}, {"name":"贾鲁河", "code":"JLF"}, {"name":"即墨北", "code":"JVK"}, {"name":"建宁县北", "code":"JCS"}, {"name":"江宁", "code":"JJH"}, {"name":"建瓯西", "code":"JUS"}, {"name":"酒泉南", "code":"JNJ"}, {"name":"句容西", "code":"JWH"}, {"name":"建水", "code":"JSM"}, {"name":"界首市", "code":"JUN"}, {"name":"绩溪北", "code":"NRH"}, {"name":"介休东", "code":"JDV"}, {"name":"泾县", "code":"LOH"}, {"name":"进贤南", "code":"JXG"}, {"name":"嘉峪关南", "code":"JBJ"}, {"name":"晋中", "code":"JZV"}, {"name":"凯里南", "code":"QKW"}, {"name":"库伦", "code":"KLD"}, {"name":"葵潭", "code":"KTQ"}, {"name":"开阳", "code":"KVW"}, {"name":"来宾北", "code":"UCZ"}, {"name":"灵璧", "code":"GMH"}, {"name":"绿博园", "code":"LCF"}, {"name":"罗城", "code":"VCZ"}, {"name":"陵城", "code":"LGK"}, {"name":"龙洞堡", "code":"FVW"}, {"name":"乐都南", "code":"LVO"}, {"name":"娄底南", "code":"UOQ"}, {"name":"离堆公园", "code":"INW"}, {"name":"陆丰", "code":"LLQ"}, {"name":"禄丰南", "code":"LQM"}, {"name":"临汾西", "code":"LXV"}, {"name":"滦河", "code":"UDP"}, {"name":"漯河西", "code":"LBN"}, {"name":"罗江东", "code":"IKW"}, {"name":"利津南", "code":"LNK"}, {"name":"龙里北", "code":"KFW"}, {"name":"醴陵东", "code":"UKQ"}, {"name":"礼泉", "code":"LGY"}, {"name":"灵石东", "code":"UDV"}, {"name":"乐山", "code":"IVW"}, {"name":"龙市", "code":"LAG"}, {"name":"溧水", "code":"LDH"}, {"name":"莱西北", "code":"LBK"}, {"name":"溧阳", "code":"LEH"}, {"name":"临邑", "code":"LUK"}, {"name":"柳园南", "code":"LNR"}, {"name":"鹿寨北", "code":"LSZ"}, {"name":"临泽南", "code":"LDJ"}, {"name":"明港东", "code":"MDN"}, {"name":"民和南", "code":"MNO"}, {"name":"马兰", "code":"MLR"}, {"name":"民乐", "code":"MBJ"}, {"name":"玛纳斯", "code":"MSR"}, {"name":"牟平", "code":"MBK"}, {"name":"闽清北", "code":"MBS"}, {"name":"眉山东", "code":"IUW"}, {"name":"庙山", "code":"MSN"}, {"name":"门源", "code":"MYO"}, {"name":"蒙自北", "code":"MBM"}, {"name":"蒙自", "code":"MZM"}, {"name":"南城", "code":"NDG"}, {"name":"南昌西", "code":"NXG"}, {"name":"南芬北", "code":"NUT"}, {"name":"南丰", "code":"NFG"}, {"name":"南湖东", "code":"NDN"}, {"name":"南江", "code":"FIW"}, {"name":"南江口", "code":"NDQ"}, {"name":"南陵", "code":"LLH"}, {"name":"尼木", "code":"NMO"}, {"name":"南宁东", "code":"NFZ"}, {"name":"南平北", "code":"NBS"}, {"name":"南雄", "code":"NCQ"}, {"name":"南阳寨", "code":"NYF"}, {"name":"普安", "code":"PAN"}, {"name":"屏边", "code":"PBM"}, {"name":"普定", "code":"PGW"}, {"name":"平度", "code":"PAK"}, {"name":"普宁", "code":"PEQ"}, {"name":"平南南", "code":"PAZ"}, {"name":"彭山北", "code":"PPW"}, {"name":"坪上", "code":"PSK"}, {"name":"萍乡北", "code":"PBG"}, {"name":"平遥古城", "code":"PDV"}, {"name":"彭州", "code":"PMW"}, {"name":"青白江东", "code":"QFW"}, {"name":"青岛北", "code":"QHK"}, {"name":"祁东", "code":"QMQ"}, {"name":"前锋", "code":"QFB"}, {"name":"青莲", "code":"QEW"}, {"name":"齐齐哈尔南", "code":"QNB"}, {"name":"清水北", "code":"QEJ"}, {"name":"青神", "code":"QVW"}, {"name":"岐山", "code":"QAY"}, {"name":"庆盛", "code":"QSQ"}, {"name":"曲水县", "code":"QSO"}, {"name":"祁县东", "code":"QGV"}, {"name":"乾县", "code":"QBY"}, {"name":"祁阳", "code":"QWQ"}, {"name":"全州南", "code":"QNZ"}, {"name":"仁布", "code":"RUO"}, {"name":"荣成", "code":"RCK"}, {"name":"如东", "code":"RIH"}, {"name":"榕江", "code":"RVW"}, {"name":"日喀则", "code":"RKO"}, {"name":"饶平", "code":"RVQ"}, {"name":"宋城路", "code":"SFF"}, {"name":"三都县", "code":"KKW"}, {"name":"商河", "code":"SOK"}, {"name":"泗洪", "code":"GQH"}, {"name":"三江南", "code":"SWZ"}, {"name":"三井子", "code":"OJT"}, {"name":"双流机场", "code":"IPW"}, {"name":"双流西", "code":"IQW"}, {"name":"三明北", "code":"SHS"}, {"name":"山坡东", "code":"SBN"}, {"name":"沈丘", "code":"SQN"}, {"name":"鄯善北", "code":"SMR"}, {"name":"三水南", "code":"RNQ"}, {"name":"韶山南", "code":"INQ"}, {"name":"三穗", "code":"QHW"}, {"name":"汕尾", "code":"OGQ"}, {"name":"歙县北", "code":"NPH"}, {"name":"绍兴北", "code":"SLH"}, {"name":"始兴", "code":"IPQ"}, {"name":"泗县", "code":"GPH"}, {"name":"泗阳", "code":"MPH"}, {"name":"邵阳北", "code":"OVQ"}, {"name":"上虞北", "code":"SSH"}, {"name":"松原北", "code":"OCT"}, {"name":"山阴", "code":"SNV"}, {"name":"沈阳南", "code":"SOT"}, {"name":"深圳北", "code":"IOQ"}, {"name":"神州", "code":"SRQ"}, {"name":"深圳坪山", "code":"IFQ"}, {"name":"石嘴山", "code":"QQJ"}, {"name":"石柱县", "code":"OSW"}, {"name":"桃村北", "code":"TOK"}, {"name":"土地堂东", "code":"TTN"}, {"name":"太谷西", "code":"TIV"}, {"name":"吐哈", "code":"THR"}, {"name":"通海", "code":"TAM"}, {"name":"通化县", "code":"TXL"}, {"name":"吐鲁番北", "code":"TAR"}, {"name":"铜陵北", "code":"KXH"}, {"name":"泰宁", "code":"TNS"}, {"name":"铜仁南", "code":"TNW"}, {"name":"汤逊湖", "code":"THN"}, {"name":"藤县", "code":"TAZ"}, {"name":"太原南", "code":"TNV"}, {"name":"通远堡西", "code":"TST"}, {"name":"文登东", "code":"WGK"}, {"name":"五府山", "code":"WFG"}, {"name":"威虎岭北", "code":"WBL"}, {"name":"威海北", "code":"WHK"}, {"name":"五龙背东", "code":"WMT"}, {"name":"乌龙泉南", "code":"WFN"}, {"name":"五女山", "code":"WET"}, {"name":"无为", "code":"IIH"}, {"name":"瓦屋山", "code":"WAH"}, {"name":"闻喜西", "code":"WOV"}, {"name":"武夷山北", "code":"WBS"}, {"name":"武夷山东", "code":"WCS"}, {"name":"婺源", "code":"WYG"}, {"name":"武陟", "code":"WIF"}, {"name":"梧州南", "code":"WBZ"}, {"name":"兴安北", "code":"XDZ"}, {"name":"许昌东", "code":"XVF"}, {"name":"项城", "code":"ERN"}, {"name":"新都东", "code":"EWW"}, {"name":"西丰", "code":"XFT"}, {"name":"襄汾西", "code":"XTV"}, {"name":"孝感北", "code":"XJN"}, {"name":"新化南", "code":"EJQ"}, {"name":"新晃西", "code":"EWQ"}, {"name":"新津", "code":"IRW"}, {"name":"新津南", "code":"ITW"}, {"name":"咸宁东", "code":"XKN"}, {"name":"咸宁南", "code":"UNN"}, {"name":"溆浦南", "code":"EMQ"}, {"name":"协荣", "code":"ROO"}, {"name":"湘潭北", "code":"EDQ"}, {"name":"邢台东", "code":"EDP"}, {"name":"修武西", "code":"EXF"}, {"name":"新乡东", "code":"EGF"}, {"name":"新余北", "code":"XBG"}, {"name":"西阳村", "code":"XQF"}, {"name":"信阳东", "code":"OYN"}, {"name":"咸阳秦都", "code":"XOY"}, {"name":"仙游", "code":"XWS"}, {"name":"迎宾路", "code":"YFW"}, {"name":"运城北", "code":"ABV"}, {"name":"宜春", "code":"YEG"}, {"name":"岳池", "code":"AWW"}, {"name":"云浮东", "code":"IXQ"}, {"name":"永福南", "code":"YBZ"}, {"name":"雨格", "code":"VTM"}, {"name":"洋河", "code":"GTH"}, {"name":"永济北", "code":"AJV"}, {"name":"于家堡", "code":"YKP"}, {"name":"延吉西", "code":"YXL"}, {"name":"运粮河", "code":"YEF"}, {"name":"炎陵", "code":"YAG"}, {"name":"杨陵南", "code":"YEY"}, {"name":"郁南", "code":"YKQ"}, {"name":"永寿", "code":"ASY"}, {"name":"玉山南", "code":"YGG"}, {"name":"永泰", "code":"YTS"}, {"name":"鹰潭北", "code":"YKG"}, {"name":"烟台南", "code":"YLK"}, {"name":"尤溪", "code":"YXS"}, {"name":"云霄", "code":"YBS"}, {"name":"宜兴", "code":"YUH"}, {"name":"阳信", "code":"YVK"}, {"name":"应县", "code":"YZV"}, {"name":"攸县南", "code":"YXG"}, {"name":"余姚北", "code":"CTH"}, {"name":"诏安", "code":"ZDS"}, {"name":"正定机场", "code":"ZHP"}, {"name":"纸坊东", "code":"ZMN"}, {"name":"昭化", "code":"ZHW"}, {"name":"芷江", "code":"ZPQ"}, {"name":"织金", "code":"IZW"}, {"name":"左岭", "code":"ZSN"}, {"name":"驻马店西", "code":"ZLN"}, {"name":"漳浦", "code":"ZCS"}, {"name":"肇庆东", "code":"FCQ"}, {"name":"庄桥", "code":"ZQH"}, {"name":"钟山西", "code":"ZAZ"}, {"name":"张掖西", "code":"ZEJ"}, {"name":"涿州东", "code":"ZAP"}, {"name":"卓资东", "code":"ZDC"}, {"name":"郑州东", "code":"ZAF"}, {"name":"胜芳", "code":"SUP"}, {"name":"隆安东", "code":"IDZ"}, {"name":"缙云西", "code":"PYH"}, {"name":"邵东", "code":"FIQ"} ], "error_code":0 }'; +// $data='{"result":[{"name":"北京北", "code":"VAP"}, {"name":"北京东", "code":"BOP"}, {"name":"北京", "code":"BJP"}, {"name":"北京南", "code":"VNP"}, {"name":"北京西", "code":"BXP"}, {"name":"广州南", "code":"IZQ"}, {"name":"重庆北", "code":"CUW"}, {"name":"重庆", "code":"CQW"}, {"name":"重庆南", "code":"CRW"}, {"name":"广州东", "code":"GGQ"}, {"name":"上海", "code":"SHH"}, {"name":"上海南", "code":"SNH"}, {"name":"上海虹桥", "code":"AOH"}, {"name":"上海西", "code":"SXH"}, {"name":"天津北", "code":"TBP"}, {"name":"天津", "code":"TJP"}, {"name":"天津南", "code":"TIP"}, {"name":"天津西", "code":"TXP"}, {"name":"长春", "code":"CCT"}, {"name":"长春南", "code":"CET"}, {"name":"长春西", "code":"CRT"}, {"name":"成都东", "code":"ICW"}, {"name":"成都南", "code":"CNW"}, {"name":"成都", "code":"CDW"}, {"name":"长沙", "code":"CSQ"}, {"name":"长沙南", "code":"CWQ"}, {"name":"福州", "code":"FZS"}, {"name":"福州南", "code":"FYS"}, {"name":"贵阳", "code":"GIW"}, {"name":"广州", "code":"GZQ"}, {"name":"广州西", "code":"GXQ"}, {"name":"哈尔滨", "code":"HBB"}, {"name":"哈尔滨东", "code":"VBB"}, {"name":"哈尔滨西", "code":"VAB"}, {"name":"合肥", "code":"HFH"}, {"name":"合肥西", "code":"HTH"}, {"name":"呼和浩特东", "code":"NDC"}, {"name":"呼和浩特", "code":"HHC"}, {"name":"海口东", "code":"HMQ"}, {"name":"海口", "code":"VUQ"}, {"name":"杭州东", "code":"HGH"}, {"name":"杭州", "code":"HZH"}, {"name":"杭州南", "code":"XHH"}, {"name":"济南", "code":"JNK"}, {"name":"济南东", "code":"JAK"}, {"name":"济南西", "code":"JGK"}, {"name":"昆明", "code":"KMM"}, {"name":"昆明西", "code":"KXM"}, {"name":"拉萨", "code":"LSO"}, {"name":"兰州东", "code":"LVJ"}, {"name":"兰州", "code":"LZJ"}, {"name":"兰州西", "code":"LAJ"}, {"name":"南昌", "code":"NCG"}, {"name":"南京", "code":"NJH"}, {"name":"南京南", "code":"NKH"}, {"name":"南宁", "code":"NNZ"}, {"name":"石家庄北", "code":"VVP"}, {"name":"石家庄", "code":"SJP"}, {"name":"沈阳", "code":"SYT"}, {"name":"沈阳北", "code":"SBT"}, {"name":"沈阳东", "code":"SDT"}, {"name":"太原北", "code":"TBV"}, {"name":"太原东", "code":"TDV"}, {"name":"太原", "code":"TYV"}, {"name":"武汉", "code":"WHN"}, {"name":"王家营西", "code":"KNM"}, {"name":"乌鲁木齐南", "code":"WMR"}, {"name":"西安北", "code":"EAY"}, {"name":"西安", "code":"XAY"}, {"name":"西安南", "code":"CAY"}, {"name":"西宁", "code":"XNO"}, {"name":"银川", "code":"YIJ"}, {"name":"郑州", "code":"ZZF"}, {"name":"阿尔山", "code":"ART"}, {"name":"安康", "code":"AKY"}, {"name":"阿克苏", "code":"ASR"}, {"name":"阿里河", "code":"AHX"}, {"name":"阿拉山口", "code":"AKR"}, {"name":"安平", "code":"APT"}, {"name":"安庆", "code":"AQH"}, {"name":"安顺", "code":"ASW"}, {"name":"鞍山", "code":"AST"}, {"name":"安阳", "code":"AYF"}, {"name":"北安", "code":"BAB"}, {"name":"蚌埠", "code":"BBH"}, {"name":"白城", "code":"BCT"}, {"name":"北海", "code":"BHZ"}, {"name":"白河", "code":"BEL"}, {"name":"白涧", "code":"BAP"}, {"name":"宝鸡", "code":"BJY"}, {"name":"滨江", "code":"BJB"}, {"name":"博克图", "code":"BKX"}, {"name":"百色", "code":"BIZ"}, {"name":"白山市", "code":"HJL"}, {"name":"北台", "code":"BTT"}, {"name":"包头东", "code":"BDC"}, {"name":"包头", "code":"BTC"}, {"name":"北屯市", "code":"BXR"}, {"name":"本溪", "code":"BXT"}, {"name":"白云鄂博", "code":"BEC"}, {"name":"白银西", "code":"BXJ"}, {"name":"亳州", "code":"BZH"}, {"name":"赤壁", "code":"CBN"}, {"name":"常德", "code":"VGQ"}, {"name":"承德", "code":"CDP"}, {"name":"长甸", "code":"CDT"}, {"name":"赤峰", "code":"CFD"}, {"name":"茶陵", "code":"CDG"}, {"name":"苍南", "code":"CEH"}, {"name":"昌平", "code":"CPP"}, {"name":"崇仁", "code":"CRG"}, {"name":"昌图", "code":"CTT"}, {"name":"长汀镇", "code":"CDB"}, {"name":"曹县", "code":"CXK"}, {"name":"楚雄", "code":"COM"}, {"name":"陈相屯", "code":"CXT"}, {"name":"长治北", "code":"CBF"}, {"name":"长征", "code":"CZJ"}, {"name":"池州", "code":"IYH"}, {"name":"常州", "code":"CZH"}, {"name":"郴州", "code":"CZQ"}, {"name":"长治", "code":"CZF"}, {"name":"沧州", "code":"COP"}, {"name":"崇左", "code":"CZZ"}, {"name":"大安北", "code":"RNT"}, {"name":"大成", "code":"DCT"}, {"name":"丹东", "code":"DUT"}, {"name":"东方红", "code":"DFB"}, {"name":"东莞东", "code":"DMQ"}, {"name":"大虎山", "code":"DHD"}, {"name":"敦煌", "code":"DHJ"}, {"name":"敦化", "code":"DHL"}, {"name":"德惠", "code":"DHT"}, {"name":"东京城", "code":"DJB"}, {"name":"大涧", "code":"DFP"}, {"name":"都江堰", "code":"DDW"}, {"name":"大连北", "code":"DFT"}, {"name":"大理", "code":"DKM"}, {"name":"大连", "code":"DLT"}, {"name":"定南", "code":"DNG"}, {"name":"大庆", "code":"DZX"}, {"name":"东胜", "code":"DOC"}, {"name":"大石桥", "code":"DQT"}, {"name":"大同", "code":"DTV"}, {"name":"东营", "code":"DPK"}, {"name":"大杨树", "code":"DUX"}, {"name":"都匀", "code":"RYW"}, {"name":"邓州", "code":"DOF"}, {"name":"达州", "code":"RXW"}, {"name":"德州", "code":"DZP"}, {"name":"额济纳", "code":"EJC"}, {"name":"二连", "code":"RLC"}, {"name":"恩施", "code":"ESN"}, {"name":"福鼎", "code":"FES"}, {"name":"风陵渡", "code":"FLV"}, {"name":"涪陵", "code":"FLW"}, {"name":"富拉尔基", "code":"FRX"}, {"name":"抚顺北", "code":"FET"}, {"name":"佛山", "code":"FSQ"}, {"name":"阜新", "code":"FXD"}, {"name":"阜阳", "code":"FYH"}, {"name":"格尔木", "code":"GRO"}, {"name":"广汉", "code":"GHW"}, {"name":"古交", "code":"GJV"}, {"name":"桂林北", "code":"GBZ"}, {"name":"古莲", "code":"GRX"}, {"name":"桂林", "code":"GLZ"}, {"name":"固始", "code":"GXN"}, {"name":"广水", "code":"GSN"}, {"name":"干塘", "code":"GNJ"}, {"name":"广元", "code":"GYW"}, {"name":"广州北", "code":"GBQ"}, {"name":"赣州", "code":"GZG"}, {"name":"公主岭", "code":"GLT"}, {"name":"公主岭南", "code":"GBT"}, {"name":"淮安", "code":"AUH"}, {"name":"鹤北", "code":"HMB"}, {"name":"淮北", "code":"HRH"}, {"name":"淮滨", "code":"HVN"}, {"name":"河边", "code":"HBV"}, {"name":"潢川", "code":"KCN"}, {"name":"韩城", "code":"HCY"}, {"name":"邯郸", "code":"HDP"}, {"name":"横道河子", "code":"HDB"}, {"name":"鹤岗", "code":"HGB"}, {"name":"皇姑屯", "code":"HTT"}, {"name":"红果", "code":"HEM"}, {"name":"黑河", "code":"HJB"}, {"name":"怀化", "code":"HHQ"}, {"name":"汉口", "code":"HKN"}, {"name":"葫芦岛", "code":"HLD"}, {"name":"海拉尔", "code":"HRX"}, {"name":"霍林郭勒", "code":"HWD"}, {"name":"海伦", "code":"HLB"}, {"name":"侯马", "code":"HMV"}, {"name":"哈密", "code":"HMR"}, {"name":"淮南", "code":"HAH"}, {"name":"桦南", "code":"HNB"}, {"name":"海宁西", "code":"EUH"}, {"name":"鹤庆", "code":"HQM"}, {"name":"怀柔北", "code":"HBP"}, {"name":"怀柔", "code":"HRP"}, {"name":"黄石东", "code":"OSN"}, {"name":"华山", "code":"HSY"}, {"name":"黄石", "code":"HSN"}, {"name":"黄山", "code":"HKH"}, {"name":"衡水", "code":"HSP"}, {"name":"衡阳", "code":"HYQ"}, {"name":"菏泽", "code":"HIK"}, {"name":"贺州", "code":"HXZ"}, {"name":"汉中", "code":"HOY"}, {"name":"惠州", "code":"HCQ"}, {"name":"吉安", "code":"VAG"}, {"name":"集安", "code":"JAL"}, {"name":"江边村", "code":"JBG"}, {"name":"晋城", "code":"JCF"}, {"name":"金城江", "code":"JJZ"}, {"name":"景德镇", "code":"JCG"}, {"name":"嘉峰", "code":"JFF"}, {"name":"加格达奇", "code":"JGX"}, {"name":"井冈山", "code":"JGG"}, {"name":"蛟河", "code":"JHL"}, {"name":"金华南", "code":"RNH"}, {"name":"金华", "code":"JBH"}, {"name":"九江", "code":"JJG"}, {"name":"吉林", "code":"JLL"}, {"name":"荆门", "code":"JMN"}, {"name":"佳木斯", "code":"JMB"}, {"name":"济宁", "code":"JIK"}, {"name":"集宁南", "code":"JAC"}, {"name":"酒泉", "code":"JQJ"}, {"name":"江山", "code":"JUH"}, {"name":"吉首", "code":"JIQ"}, {"name":"九台", "code":"JTL"}, {"name":"镜铁山", "code":"JVJ"}, {"name":"鸡西", "code":"JXB"}, {"name":"蓟县", "code":"JKP"}, {"name":"绩溪县", "code":"JRH"}, {"name":"嘉峪关", "code":"JGJ"}, {"name":"江油", "code":"JFW"}, {"name":"锦州", "code":"JZD"}, {"name":"金州", "code":"JZT"}, {"name":"库尔勒", "code":"KLR"}, {"name":"开封", "code":"KFF"}, {"name":"岢岚", "code":"KLV"}, {"name":"凯里", "code":"KLW"}, {"name":"喀什", "code":"KSR"}, {"name":"昆山南", "code":"KNH"}, {"name":"奎屯", "code":"KTR"}, {"name":"开原", "code":"KYT"}, {"name":"六安", "code":"UAH"}, {"name":"灵宝", "code":"LBF"}, {"name":"芦潮港", "code":"UCH"}, {"name":"隆昌", "code":"LCW"}, {"name":"陆川", "code":"LKZ"}, {"name":"利川", "code":"LCN"}, {"name":"临川", "code":"LCG"}, {"name":"潞城", "code":"UTP"}, {"name":"鹿道", "code":"LDL"}, {"name":"娄底", "code":"LDQ"}, {"name":"临汾", "code":"LFV"}, {"name":"良各庄", "code":"LGP"}, {"name":"临河", "code":"LHC"}, {"name":"漯河", "code":"LON"}, {"name":"绿化", "code":"LWJ"}, {"name":"隆化", "code":"UHP"}, {"name":"丽江", "code":"LHM"}, {"name":"临江", "code":"LQL"}, {"name":"龙井", "code":"LJL"}, {"name":"吕梁", "code":"LHV"}, {"name":"醴陵", "code":"LLG"}, {"name":"柳林南", "code":"LKV"}, {"name":"滦平", "code":"UPP"}, {"name":"六盘水", "code":"UMW"}, {"name":"灵丘", "code":"LVV"}, {"name":"旅顺", "code":"LST"}, {"name":"陇西", "code":"LXJ"}, {"name":"澧县", "code":"LEQ"}, {"name":"兰溪", "code":"LWH"}, {"name":"临西", "code":"UEP"}, {"name":"龙岩", "code":"LYS"}, {"name":"耒阳", "code":"LYQ"}, {"name":"洛阳", "code":"LYF"}, {"name":"洛阳东", "code":"LDF"}, {"name":"连云港东", "code":"UKH"}, {"name":"临沂", "code":"LVK"}, {"name":"洛阳龙门", "code":"LLF"}, {"name":"柳园", "code":"DHR"}, {"name":"凌源", "code":"LYD"}, {"name":"辽源", "code":"LYL"}, {"name":"立志", "code":"LZX"}, {"name":"柳州", "code":"LZZ"}, {"name":"辽中", "code":"LZD"}, {"name":"麻城", "code":"MCN"}, {"name":"免渡河", "code":"MDX"}, {"name":"牡丹江", "code":"MDB"}, {"name":"莫尔道嘎", "code":"MRX"}, {"name":"满归", "code":"MHX"}, {"name":"明光", "code":"MGH"}, {"name":"漠河", "code":"MVX"}, {"name":"茂名东", "code":"MDQ"}, {"name":"茂名", "code":"MMZ"}, {"name":"密山", "code":"MSB"}, {"name":"马三家", "code":"MJT"}, {"name":"麻尾", "code":"VAW"}, {"name":"绵阳", "code":"MYW"}, {"name":"梅州", "code":"MOQ"}, {"name":"满洲里", "code":"MLX"}, {"name":"宁波东", "code":"NVH"}, {"name":"宁波", "code":"NGH"}, {"name":"南岔", "code":"NCB"}, {"name":"南充", "code":"NCW"}, {"name":"南丹", "code":"NDZ"}, {"name":"南大庙", "code":"NMP"}, {"name":"南芬", "code":"NFT"}, {"name":"讷河", "code":"NHX"}, {"name":"嫩江", "code":"NGX"}, {"name":"内江", "code":"NJW"}, {"name":"南平", "code":"NPS"}, {"name":"南通", "code":"NUH"}, {"name":"南阳", "code":"NFF"}, {"name":"碾子山", "code":"NZX"}, {"name":"平顶山", "code":"PEN"}, {"name":"盘锦", "code":"PVD"}, {"name":"平凉", "code":"PIJ"}, {"name":"平凉南", "code":"POJ"}, {"name":"平泉", "code":"PQP"}, {"name":"坪石", "code":"PSQ"}, {"name":"萍乡", "code":"PXG"}, {"name":"凭祥", "code":"PXZ"}, {"name":"郫县西", "code":"PCW"}, {"name":"攀枝花", "code":"PRW"}, {"name":"蕲春", "code":"QRN"}, {"name":"青城山", "code":"QSW"}, {"name":"青岛", "code":"QDK"}, {"name":"清河城", "code":"QYP"}, {"name":"黔江", "code":"QNW"}, {"name":"曲靖", "code":"QJM"}, {"name":"前进镇", "code":"QEB"}, {"name":"齐齐哈尔", "code":"QHX"}, {"name":"七台河", "code":"QTB"}, {"name":"沁县", "code":"QVV"}, {"name":"泉州东", "code":"QRS"}, {"name":"泉州", "code":"QYS"}, {"name":"衢州", "code":"QEH"}, {"name":"融安", "code":"RAZ"}, {"name":"汝箕沟", "code":"RQJ"}, {"name":"瑞金", "code":"RJG"}, {"name":"日照", "code":"RZK"}, {"name":"双城堡", "code":"SCB"}, {"name":"绥芬河", "code":"SFB"}, {"name":"韶关东", "code":"SGQ"}, {"name":"山海关", "code":"SHD"}, {"name":"绥化", "code":"SHB"}, {"name":"三间房", "code":"SFX"}, {"name":"苏家屯", "code":"SXT"}, {"name":"舒兰", "code":"SLL"}, {"name":"三明", "code":"SMS"}, {"name":"神木", "code":"OMY"}, {"name":"三门峡", "code":"SMF"}, {"name":"商南", "code":"ONY"}, {"name":"遂宁", "code":"NIW"}, {"name":"四平", "code":"SPT"}, {"name":"商丘", "code":"SQF"}, {"name":"上饶", "code":"SRG"}, {"name":"韶山", "code":"SSQ"}, {"name":"宿松", "code":"OAH"}, {"name":"汕头", "code":"OTQ"}, {"name":"邵武", "code":"SWS"}, {"name":"涉县", "code":"OEP"}, {"name":"三亚", "code":"SEQ"}, {"name":"邵阳", "code":"SYQ"}, {"name":"十堰", "code":"SNN"}, {"name":"双鸭山", "code":"SSB"}, {"name":"松原", "code":"VYT"}, {"name":"深圳", "code":"SZQ"}, {"name":"苏州", "code":"SZH"}, {"name":"随州", "code":"SZN"}, {"name":"宿州", "code":"OXH"}, {"name":"朔州", "code":"SUV"}, {"name":"深圳西", "code":"OSQ"}, {"name":"塘豹", "code":"TBQ"}, {"name":"塔尔气", "code":"TVX"}, {"name":"潼关", "code":"TGY"}, {"name":"塘沽", "code":"TGP"}, {"name":"塔河", "code":"TXX"}, {"name":"通化", "code":"THL"}, {"name":"泰来", "code":"TLX"}, {"name":"吐鲁番", "code":"TFR"}, {"name":"通辽", "code":"TLD"}, {"name":"铁岭", "code":"TLT"}, {"name":"陶赖昭", "code":"TPT"}, {"name":"图们", "code":"TML"}, {"name":"铜仁", "code":"RDQ"}, {"name":"唐山北", "code":"FUP"}, {"name":"田师府", "code":"TFT"}, {"name":"泰山", "code":"TAK"}, {"name":"唐山", "code":"TSP"}, {"name":"天水", "code":"TSJ"}, {"name":"通远堡", "code":"TYT"}, {"name":"太阳升", "code":"TQT"}, {"name":"泰州", "code":"UTH"}, {"name":"桐梓", "code":"TZW"}, {"name":"通州西", "code":"TAP"}, {"name":"五常", "code":"WCB"}, {"name":"武昌", "code":"WCN"}, {"name":"瓦房店", "code":"WDT"}, {"name":"威海", "code":"WKK"}, {"name":"芜湖", "code":"WHH"}, {"name":"乌海西", "code":"WXC"}, {"name":"吴家屯", "code":"WJT"}, {"name":"武隆", "code":"WLW"}, {"name":"乌兰浩特", "code":"WWT"}, {"name":"渭南", "code":"WNY"}, {"name":"威舍", "code":"WSM"}, {"name":"歪头山", "code":"WIT"}, {"name":"武威", "code":"WUJ"}, {"name":"武威南", "code":"WWJ"}, {"name":"无锡", "code":"WXH"}, {"name":"乌西", "code":"WXR"}, {"name":"乌伊岭", "code":"WPB"}, {"name":"武夷山", "code":"WAS"}, {"name":"万源", "code":"WYY"}, {"name":"万州", "code":"WYW"}, {"name":"梧州", "code":"WZZ"}, {"name":"温州", "code":"RZH"}, {"name":"温州南", "code":"VRH"}, {"name":"西昌", "code":"ECW"}, {"name":"许昌", "code":"XCF"}, {"name":"西昌南", "code":"ENW"}, {"name":"香坊", "code":"XFB"}, {"name":"轩岗", "code":"XGV"}, {"name":"兴国", "code":"EUG"}, {"name":"宣汉", "code":"XHY"}, {"name":"新会", "code":"EFQ"}, {"name":"新晃", "code":"XLQ"}, {"name":"锡林浩特", "code":"XTC"}, {"name":"兴隆县", "code":"EXP"}, {"name":"厦门北", "code":"XKS"}, {"name":"厦门", "code":"XMS"}, {"name":"厦门高崎", "code":"XBS"}, {"name":"秀山", "code":"ETW"}, {"name":"小市", "code":"XST"}, {"name":"向塘", "code":"XTG"}, {"name":"宣威", "code":"XWM"}, {"name":"新乡", "code":"XXF"}, {"name":"信阳", "code":"XUN"}, {"name":"咸阳", "code":"XYY"}, {"name":"襄阳", "code":"XFN"}, {"name":"熊岳城", "code":"XYT"}, {"name":"兴义", "code":"XRZ"}, {"name":"新沂", "code":"VIH"}, {"name":"新余", "code":"XUG"}, {"name":"徐州", "code":"XCH"}, {"name":"延安", "code":"YWY"}, {"name":"宜宾", "code":"YBW"}, {"name":"亚布力南", "code":"YWB"}, {"name":"叶柏寿", "code":"YBD"}, {"name":"宜昌东", "code":"HAN"}, {"name":"永川", "code":"YCW"}, {"name":"宜昌", "code":"YCN"}, {"name":"盐城", "code":"AFH"}, {"name":"运城", "code":"YNV"}, {"name":"伊春", "code":"YCB"}, {"name":"榆次", "code":"YCV"}, {"name":"杨村", "code":"YBP"}, {"name":"宜春西", "code":"YCG"}, {"name":"伊尔施", "code":"YET"}, {"name":"燕岗", "code":"YGW"}, {"name":"永济", "code":"YIV"}, {"name":"延吉", "code":"YJL"}, {"name":"营口", "code":"YKT"}, {"name":"牙克石", "code":"YKX"}, {"name":"阎良", "code":"YNY"}, {"name":"玉林", "code":"YLZ"}, {"name":"榆林", "code":"ALY"}, {"name":"一面坡", "code":"YPB"}, {"name":"伊宁", "code":"YMR"}, {"name":"阳平关", "code":"YAY"}, {"name":"玉屏", "code":"YZW"}, {"name":"原平", "code":"YPV"}, {"name":"延庆", "code":"YNP"}, {"name":"阳泉曲", "code":"YYV"}, {"name":"玉泉", "code":"YQB"}, {"name":"阳泉", "code":"AQP"}, {"name":"玉山", "code":"YNG"}, {"name":"营山", "code":"NUW"}, {"name":"燕山", "code":"AOP"}, {"name":"榆树", "code":"YRT"}, {"name":"鹰潭", "code":"YTG"}, {"name":"烟台", "code":"YAK"}, {"name":"伊图里河", "code":"YEX"}, {"name":"玉田县", "code":"ATP"}, {"name":"义乌", "code":"YWH"}, {"name":"阳新", "code":"YON"}, {"name":"义县", "code":"YXD"}, {"name":"益阳", "code":"AEQ"}, {"name":"岳阳", "code":"YYQ"}, {"name":"永州", "code":"AOQ"}, {"name":"扬州", "code":"YLH"}, {"name":"淄博", "code":"ZBK"}, {"name":"镇城底", "code":"ZDV"}, {"name":"自贡", "code":"ZGW"}, {"name":"珠海", "code":"ZHQ"}, {"name":"珠海北", "code":"ZIQ"}, {"name":"湛江", "code":"ZJZ"}, {"name":"镇江", "code":"ZJH"}, {"name":"张家界", "code":"DIQ"}, {"name":"张家口", "code":"ZKP"}, {"name":"张家口南", "code":"ZMP"}, {"name":"周口", "code":"ZKN"}, {"name":"哲里木", "code":"ZLC"}, {"name":"扎兰屯", "code":"ZTX"}, {"name":"驻马店", "code":"ZDN"}, {"name":"肇庆", "code":"ZVQ"}, {"name":"周水子", "code":"ZIT"}, {"name":"昭通", "code":"ZDW"}, {"name":"中卫", "code":"ZWJ"}, {"name":"资阳", "code":"ZYW"}, {"name":"遵义", "code":"ZIW"}, {"name":"枣庄", "code":"ZEK"}, {"name":"资中", "code":"ZZW"}, {"name":"株洲", "code":"ZZQ"}, {"name":"枣庄西", "code":"ZFK"}, {"name":"昂昂溪", "code":"AAX"}, {"name":"阿城", "code":"ACB"}, {"name":"安达", "code":"ADX"}, {"name":"安德", "code":"ARW"}, {"name":"安定", "code":"ADP"}, {"name":"安广", "code":"AGT"}, {"name":"艾河", "code":"AHP"}, {"name":"安化", "code":"PKQ"}, {"name":"艾家村", "code":"AJJ"}, {"name":"鳌江", "code":"ARH"}, {"name":"安家", "code":"AJB"}, {"name":"阿金", "code":"AJD"}, {"name":"阿克陶", "code":"AER"}, {"name":"安口窑", "code":"AYY"}, {"name":"敖力布告", "code":"ALD"}, {"name":"安龙", "code":"AUZ"}, {"name":"阿龙山", "code":"ASX"}, {"name":"安陆", "code":"ALN"}, {"name":"阿木尔", "code":"JTX"}, {"name":"阿南庄", "code":"AZM"}, {"name":"安庆西", "code":"APH"}, {"name":"鞍山西", "code":"AXT"}, {"name":"安塘", "code":"ATV"}, {"name":"安亭北", "code":"ASH"}, {"name":"阿图什", "code":"ATR"}, {"name":"安图", "code":"ATL"}, {"name":"安溪", "code":"AXS"}, {"name":"博鳌", "code":"BWQ"}, {"name":"北碚", "code":"BPW"}, {"name":"白壁关", "code":"BGV"}, {"name":"蚌埠南", "code":"BMH"}, {"name":"巴楚", "code":"BCR"}, {"name":"板城", "code":"BUP"}, {"name":"北戴河", "code":"BEP"}, {"name":"保定", "code":"BDP"}, {"name":"宝坻", "code":"BPP"}, {"name":"八达岭", "code":"ILP"}, {"name":"巴东", "code":"BNN"}, {"name":"柏果", "code":"BGM"}, {"name":"布海", "code":"BUT"}, {"name":"白河东", "code":"BIY"}, {"name":"贲红", "code":"BVC"}, {"name":"宝华山", "code":"BWH"}, {"name":"白河县", "code":"BEY"}, {"name":"白芨沟", "code":"BJJ"}, {"name":"碧鸡关", "code":"BJM"}, {"name":"北滘", "code":"IBQ"}, {"name":"碧江", "code":"BLQ"}, {"name":"白鸡坡", "code":"BBM"}, {"name":"笔架山", "code":"BSB"}, {"name":"八角台", "code":"BTD"}, {"name":"保康", "code":"BKD"}, {"name":"白奎堡", "code":"BKB"}, {"name":"白狼", "code":"BAT"}, {"name":"百浪", "code":"BRZ"}, {"name":"博乐", "code":"BOR"}, {"name":"宝拉格", "code":"BQC"}, {"name":"巴林", "code":"BLX"}, {"name":"宝林", "code":"BNB"}, {"name":"北流", "code":"BOZ"}, {"name":"勃利", "code":"BLB"}, {"name":"布列开", "code":"BLR"}, {"name":"宝龙山", "code":"BND"}, {"name":"百里峡", "code":"AAP"}, {"name":"八面城", "code":"BMD"}, {"name":"班猫箐", "code":"BNM"}, {"name":"八面通", "code":"BMB"}, {"name":"北马圈子", "code":"BRP"}, {"name":"北票南", "code":"RPD"}, {"name":"白旗", "code":"BQP"}, {"name":"宝泉岭", "code":"BQB"}, {"name":"白泉", "code":"BQL"}, {"name":"白沙", "code":"BSW"}, {"name":"巴山", "code":"BAY"}, {"name":"白水江", "code":"BSY"}, {"name":"白沙坡", "code":"BPM"}, {"name":"白石山", "code":"BAL"}, {"name":"白水镇", "code":"BUM"}, {"name":"坂田", "code":"BTQ"}, {"name":"泊头", "code":"BZP"}, {"name":"北屯", "code":"BYP"}, {"name":"本溪湖", "code":"BHT"}, {"name":"博兴", "code":"BXK"}, {"name":"八仙筒", "code":"VXD"}, {"name":"白音察干", "code":"BYC"}, {"name":"背荫河", "code":"BYB"}, {"name":"北营", "code":"BIV"}, {"name":"巴彦高勒", "code":"BAC"}, {"name":"白音他拉", "code":"BID"}, {"name":"鲅鱼圈", "code":"BYT"}, {"name":"白银市", "code":"BNJ"}, {"name":"白音胡硕", "code":"BCD"}, {"name":"巴中", "code":"IEW"}, {"name":"霸州", "code":"RMP"}, {"name":"北宅", "code":"BVP"}, {"name":"赤壁北", "code":"CIN"}, {"name":"查布嘎", "code":"CBC"}, {"name":"长城", "code":"CEJ"}, {"name":"长冲", "code":"CCM"}, {"name":"承德东", "code":"CCP"}, {"name":"赤峰西", "code":"CID"}, {"name":"嵯岗", "code":"CAX"}, {"name":"柴岗", "code":"CGT"}, {"name":"长葛", "code":"CEF"}, {"name":"柴沟堡", "code":"CGV"}, {"name":"城固", "code":"CGY"}, {"name":"陈官营", "code":"CAJ"}, {"name":"成高子", "code":"CZB"}, {"name":"草海", "code":"WBW"}, {"name":"柴河", "code":"CHB"}, {"name":"册亨", "code":"CHZ"}, {"name":"草河口", "code":"CKT"}, {"name":"崔黄口", "code":"CHP"}, {"name":"巢湖", "code":"CIH"}, {"name":"蔡家沟", "code":"CJT"}, {"name":"成吉思汗", "code":"CJX"}, {"name":"岔江", "code":"CAM"}, {"name":"蔡家坡", "code":"CJY"}, {"name":"昌乐", "code":"CLK"}, {"name":"超梁沟", "code":"CYP"}, {"name":"慈利", "code":"CUQ"}, {"name":"昌黎", "code":"CLP"}, {"name":"长岭子", "code":"CLT"}, {"name":"晨明", "code":"CMB"}, {"name":"长农", "code":"CNJ"}, {"name":"昌平北", "code":"VBP"}, {"name":"常平", "code":"DAQ"}, {"name":"长坡岭", "code":"CPM"}, {"name":"辰清", "code":"CQB"}, {"name":"蔡山", "code":"CON"}, {"name":"楚山", "code":"CSB"}, {"name":"长寿", "code":"EFW"}, {"name":"磁山", "code":"CSP"}, {"name":"苍石", "code":"CST"}, {"name":"草市", "code":"CSL"}, {"name":"察素齐", "code":"CSC"}, {"name":"长山屯", "code":"CVT"}, {"name":"长汀", "code":"CES"}, {"name":"昌图西", "code":"CPT"}, {"name":"春湾", "code":"CQQ"}, {"name":"磁县", "code":"CIP"}, {"name":"岑溪", "code":"CNZ"}, {"name":"辰溪", "code":"CXQ"}, {"name":"磁西", "code":"CRP"}, {"name":"长兴南", "code":"CFH"}, {"name":"磁窑", "code":"CYK"}, {"name":"朝阳", "code":"CYD"}, {"name":"春阳", "code":"CAL"}, {"name":"城阳", "code":"CEK"}, {"name":"创业村", "code":"CEX"}, {"name":"朝阳川", "code":"CYL"}, {"name":"朝阳地", "code":"CDD"}, {"name":"长垣", "code":"CYF"}, {"name":"朝阳镇", "code":"CZL"}, {"name":"滁州北", "code":"CUH"}, {"name":"常州北", "code":"ESH"}, {"name":"滁州", "code":"CXH"}, {"name":"潮州", "code":"CKQ"}, {"name":"常庄", "code":"CVK"}, {"name":"曹子里", "code":"CFP"}, {"name":"车转湾", "code":"CWM"}, {"name":"郴州西", "code":"ICQ"}, {"name":"沧州西", "code":"CBP"}, {"name":"德安", "code":"DAG"}, {"name":"大安", "code":"RAT"}, {"name":"大坝", "code":"DBJ"}, {"name":"大板", "code":"DBC"}, {"name":"大巴", "code":"DBD"}, {"name":"到保", "code":"RBT"}, {"name":"定边", "code":"DYJ"}, {"name":"东边井", "code":"DBB"}, {"name":"德伯斯", "code":"RDT"}, {"name":"打柴沟", "code":"DGJ"}, {"name":"德昌", "code":"DVW"}, {"name":"滴道", "code":"DDB"}, {"name":"大磴沟", "code":"DKJ"}, {"name":"刀尔登", "code":"DRD"}, {"name":"得耳布尔", "code":"DRX"}, {"name":"东方", "code":"UFQ"}, {"name":"丹凤", "code":"DGY"}, {"name":"东丰", "code":"DIL"}, {"name":"都格", "code":"DMM"}, {"name":"大官屯", "code":"DTT"}, {"name":"大关", "code":"RGW"}, {"name":"东光", "code":"DGP"}, {"name":"东海", "code":"DHB"}, {"name":"大灰厂", "code":"DHP"}, {"name":"大红旗", "code":"DQD"}, {"name":"大禾塘", "code":"SOQ"}, {"name":"东海县", "code":"DQH"}, {"name":"德惠西", "code":"DXT"}, {"name":"达家沟", "code":"DJT"}, {"name":"东津", "code":"DKB"}, {"name":"杜家", "code":"DJL"}, {"name":"大口屯", "code":"DKP"}, {"name":"东来", "code":"RVD"}, {"name":"德令哈", "code":"DHO"}, {"name":"大陆号", "code":"DLC"}, {"name":"带岭", "code":"DLB"}, {"name":"大林", "code":"DLD"}, {"name":"达拉特旗", "code":"DIC"}, {"name":"独立屯", "code":"DTX"}, {"name":"豆罗", "code":"DLV"}, {"name":"达拉特西", "code":"DNC"}, {"name":"东明村", "code":"DMD"}, {"name":"洞庙河", "code":"DEP"}, {"name":"东明县", "code":"DNF"}, {"name":"大拟", "code":"DNZ"}, {"name":"大平房", "code":"DPD"}, {"name":"大盘石", "code":"RPP"}, {"name":"大埔", "code":"DPI"}, {"name":"大堡", "code":"DVT"}, {"name":"大庆东", "code":"LFX"}, {"name":"大其拉哈", "code":"DQX"}, {"name":"道清", "code":"DML"}, {"name":"对青山", "code":"DQB"}, {"name":"德清西", "code":"MOH"}, {"name":"大庆西", "code":"RHX"}, {"name":"东升", "code":"DRQ"}, {"name":"独山", "code":"RWW"}, {"name":"砀山", "code":"DKH"}, {"name":"登沙河", "code":"DWT"}, {"name":"读书铺", "code":"DPM"}, {"name":"大石头", "code":"DSL"}, {"name":"东胜西", "code":"DYC"}, {"name":"大石寨", "code":"RZT"}, {"name":"东台", "code":"DBH"}, {"name":"定陶", "code":"DQK"}, {"name":"灯塔", "code":"DGT"}, {"name":"大田边", "code":"DBM"}, {"name":"东通化", "code":"DTL"}, {"name":"丹徒", "code":"RUH"}, {"name":"大屯", "code":"DNT"}, {"name":"东湾", "code":"DRJ"}, {"name":"大武口", "code":"DFJ"}, {"name":"低窝铺", "code":"DWJ"}, {"name":"大王滩", "code":"DZZ"}, {"name":"大湾子", "code":"DFM"}, {"name":"大兴沟", "code":"DXL"}, {"name":"大兴", "code":"DXX"}, {"name":"定西", "code":"DSJ"}, {"name":"甸心", "code":"DXM"}, {"name":"东乡", "code":"DXG"}, {"name":"代县", "code":"DKV"}, {"name":"定襄", "code":"DXV"}, {"name":"东戌", "code":"RXP"}, {"name":"东辛庄", "code":"DXD"}, {"name":"德阳", "code":"DYW"}, {"name":"丹阳", "code":"DYH"}, {"name":"大雁", "code":"DYX"}, {"name":"当阳", "code":"DYN"}, {"name":"丹阳北", "code":"EXH"}, {"name":"大英东", "code":"IAW"}, {"name":"东淤地", "code":"DBV"}, {"name":"大营", "code":"DYV"}, {"name":"定远", "code":"EWH"}, {"name":"岱岳", "code":"RYV"}, {"name":"大元", "code":"DYZ"}, {"name":"大营镇", "code":"DJP"}, {"name":"大营子", "code":"DZD"}, {"name":"大战场", "code":"DTJ"}, {"name":"德州东", "code":"DIP"}, {"name":"低庄", "code":"DVQ"}, {"name":"东镇", "code":"DNV"}, {"name":"道州", "code":"DFZ"}, {"name":"东至", "code":"DCH"}, {"name":"东庄", "code":"DZV"}, {"name":"兑镇", "code":"DWV"}, {"name":"豆庄", "code":"ROP"}, {"name":"定州", "code":"DXP"}, {"name":"大竹园", "code":"DZY"}, {"name":"大杖子", "code":"DAP"}, {"name":"豆张庄", "code":"RZP"}, {"name":"峨边", "code":"EBW"}, {"name":"二道沟门", "code":"RDP"}, {"name":"二道湾", "code":"RDX"}, {"name":"鄂尔多斯", "code":"EEC"}, {"name":"二龙", "code":"RLD"}, {"name":"二龙山屯", "code":"ELA"}, {"name":"峨眉", "code":"EMW"}, {"name":"二密河", "code":"RML"}, {"name":"二营", "code":"RYJ"}, {"name":"鄂州", "code":"ECN"}, {"name":"福安", "code":"FAS"}, {"name":"丰城", "code":"FCG"}, {"name":"丰城南", "code":"FNG"}, {"name":"肥东", "code":"FIH"}, {"name":"发耳", "code":"FEM"}, {"name":"富海", "code":"FHX"}, {"name":"福海", "code":"FHR"}, {"name":"凤凰城", "code":"FHT"}, {"name":"奉化", "code":"FHH"}, {"name":"富锦", "code":"FIB"}, {"name":"范家屯", "code":"FTT"}, {"name":"福利区", "code":"FLJ"}, {"name":"福利屯", "code":"FTB"}, {"name":"丰乐镇", "code":"FZB"}, {"name":"阜南", "code":"FNH"}, {"name":"阜宁", "code":"AKH"}, {"name":"抚宁", "code":"FNP"}, {"name":"福清", "code":"FQS"}, {"name":"福泉", "code":"VMW"}, {"name":"丰水村", "code":"FSJ"}, {"name":"丰顺", "code":"FUQ"}, {"name":"繁峙", "code":"FSV"}, {"name":"抚顺", "code":"FST"}, {"name":"福山口", "code":"FKP"}, {"name":"扶绥", "code":"FSZ"}, {"name":"冯屯", "code":"FTX"}, {"name":"浮图峪", "code":"FYP"}, {"name":"富县东", "code":"FDY"}, {"name":"凤县", "code":"FXY"}, {"name":"富县", "code":"FEY"}, {"name":"费县", "code":"FXK"}, {"name":"凤阳", "code":"FUH"}, {"name":"汾阳", "code":"FAV"}, {"name":"扶余北", "code":"FBT"}, {"name":"分宜", "code":"FYG"}, {"name":"富源", "code":"FYM"}, {"name":"扶余", "code":"FYT"}, {"name":"富裕", "code":"FYX"}, {"name":"抚州北", "code":"FBG"}, {"name":"凤州", "code":"FZY"}, {"name":"丰镇", "code":"FZC"}, {"name":"范镇", "code":"VZK"}, {"name":"固安", "code":"GFP"}, {"name":"广安", "code":"VJW"}, {"name":"高碑店", "code":"GBP"}, {"name":"沟帮子", "code":"GBD"}, {"name":"甘草店", "code":"GDJ"}, {"name":"谷城", "code":"GCN"}, {"name":"藁城", "code":"GEP"}, {"name":"高村", "code":"GCV"}, {"name":"古城镇", "code":"GZB"}, {"name":"广德", "code":"GRH"}, {"name":"贵定", "code":"GTW"}, {"name":"贵定南", "code":"IDW"}, {"name":"古东", "code":"GDV"}, {"name":"贵港", "code":"GGZ"}, {"name":"官高", "code":"GVP"}, {"name":"葛根庙", "code":"GGT"}, {"name":"干沟", "code":"GGL"}, {"name":"甘谷", "code":"GGJ"}, {"name":"高各庄", "code":"GGP"}, {"name":"甘河", "code":"GAX"}, {"name":"根河", "code":"GEX"}, {"name":"郭家店", "code":"GDT"}, {"name":"孤家子", "code":"GKT"}, {"name":"古浪", "code":"GLJ"}, {"name":"皋兰", "code":"GEJ"}, {"name":"高楼房", "code":"GFM"}, {"name":"归流河", "code":"GHT"}, {"name":"关林", "code":"GLF"}, {"name":"甘洛", "code":"VOW"}, {"name":"郭磊庄", "code":"GLP"}, {"name":"高密", "code":"GMK"}, {"name":"公庙子", "code":"GMC"}, {"name":"工农湖", "code":"GRT"}, {"name":"广宁寺", "code":"GNT"}, {"name":"广南卫", "code":"GNM"}, {"name":"高平", "code":"GPF"}, {"name":"甘泉北", "code":"GEY"}, {"name":"共青城", "code":"GAG"}, {"name":"甘旗卡", "code":"GQD"}, {"name":"甘泉", "code":"GQY"}, {"name":"高桥镇", "code":"GZD"}, {"name":"赶水", "code":"GSW"}, {"name":"灌水", "code":"GST"}, {"name":"孤山口", "code":"GSP"}, {"name":"果松", "code":"GSL"}, {"name":"高山子", "code":"GSD"}, {"name":"嘎什甸子", "code":"GXD"}, {"name":"高台", "code":"GTJ"}, {"name":"高滩", "code":"GAY"}, {"name":"古田", "code":"GTS"}, {"name":"官厅", "code":"GTP"}, {"name":"官厅西", "code":"KEP"}, {"name":"贵溪", "code":"GXG"}, {"name":"涡阳", "code":"GYH"}, {"name":"巩义", "code":"GXF"}, {"name":"高邑", "code":"GIP"}, {"name":"巩义南", "code":"GYF"}, {"name":"广元南", "code":"GAW"}, {"name":"固原", "code":"GUJ"}, {"name":"菇园", "code":"GYL"}, {"name":"公营子", "code":"GYD"}, {"name":"光泽", "code":"GZS"}, {"name":"古镇", "code":"GNQ"}, {"name":"瓜州", "code":"GZJ"}, {"name":"高州", "code":"GSQ"}, {"name":"固镇", "code":"GEH"}, {"name":"盖州", "code":"GXT"}, {"name":"官字井", "code":"GOT"}, {"name":"革镇堡", "code":"GZT"}, {"name":"冠豸山", "code":"GSS"}, {"name":"盖州西", "code":"GAT"}, {"name":"红安", "code":"HWN"}, {"name":"淮安南", "code":"AMH"}, {"name":"红安西", "code":"VXN"}, {"name":"海安县", "code":"HIH"}, {"name":"黄柏", "code":"HBL"}, {"name":"海北", "code":"HEB"}, {"name":"鹤壁", "code":"HAF"}, {"name":"华城", "code":"VCQ"}, {"name":"合川", "code":"WKW"}, {"name":"河唇", "code":"HCZ"}, {"name":"汉川", "code":"HCN"}, {"name":"海城", "code":"HCT"}, {"name":"黑冲滩", "code":"HCJ"}, {"name":"黄村", "code":"HCP"}, {"name":"海城西", "code":"HXT"}, {"name":"化德", "code":"HGC"}, {"name":"洪洞", "code":"HDV"}, {"name":"霍尔果斯", "code":"HFR"}, {"name":"横峰", "code":"HFG"}, {"name":"韩府湾", "code":"HXJ"}, {"name":"汉沽", "code":"HGP"}, {"name":"红光镇", "code":"IGW"}, {"name":"浑河", "code":"HHT"}, {"name":"红花沟", "code":"VHD"}, {"name":"黄花筒", "code":"HUD"}, {"name":"贺家店", "code":"HJJ"}, {"name":"和静", "code":"HJR"}, {"name":"红江", "code":"HFM"}, {"name":"黑井", "code":"HIM"}, {"name":"获嘉", "code":"HJF"}, {"name":"河津", "code":"HJV"}, {"name":"涵江", "code":"HJS"}, {"name":"华家", "code":"HJT"}, {"name":"杭锦后旗", "code":"HDC"}, {"name":"河间西", "code":"HXP"}, {"name":"花家庄", "code":"HJM"}, {"name":"河口南", "code":"HKJ"}, {"name":"黄口", "code":"KOH"}, {"name":"湖口", "code":"HKG"}, {"name":"呼兰", "code":"HUB"}, {"name":"葫芦岛北", "code":"HPD"}, {"name":"浩良河", "code":"HHB"}, {"name":"哈拉海", "code":"HIT"}, {"name":"鹤立", "code":"HOB"}, {"name":"桦林", "code":"HIB"}, {"name":"黄陵", "code":"ULY"}, {"name":"海林", "code":"HRB"}, {"name":"虎林", "code":"VLB"}, {"name":"寒岭", "code":"HAT"}, {"name":"和龙", "code":"HLL"}, {"name":"海龙", "code":"HIL"}, {"name":"哈拉苏", "code":"HAX"}, {"name":"呼鲁斯太", "code":"VTJ"}, {"name":"火连寨", "code":"HLT"}, {"name":"黄梅", "code":"VEH"}, {"name":"韩麻营", "code":"HYP"}, {"name":"黄泥河", "code":"HHL"}, {"name":"海宁", "code":"HNH"}, {"name":"惠农", "code":"HMJ"}, {"name":"和平", "code":"VAQ"}, {"name":"花棚子", "code":"HZM"}, {"name":"花桥", "code":"VQH"}, {"name":"宏庆", "code":"HEY"}, {"name":"怀仁", "code":"HRV"}, {"name":"华容", "code":"HRN"}, {"name":"华山北", "code":"HDY"}, {"name":"黄松甸", "code":"HDL"}, {"name":"和什托洛盖", "code":"VSR"}, {"name":"红山", "code":"VSB"}, {"name":"汉寿", "code":"VSQ"}, {"name":"衡山", "code":"HSQ"}, {"name":"黑水", "code":"HOT"}, {"name":"惠山", "code":"VCH"}, {"name":"虎什哈", "code":"HHP"}, {"name":"红寺堡", "code":"HSJ"}, {"name":"虎石台", "code":"HUT"}, {"name":"海石湾", "code":"HSO"}, {"name":"衡山西", "code":"HEQ"}, {"name":"红砂岘", "code":"VSJ"}, {"name":"黑台", "code":"HQB"}, {"name":"桓台", "code":"VTK"}, {"name":"和田", "code":"VTR"}, {"name":"会同", "code":"VTQ"}, {"name":"海坨子", "code":"HZT"}, {"name":"黑旺", "code":"HWK"}, {"name":"海湾", "code":"RWH"}, {"name":"红星", "code":"VXB"}, {"name":"徽县", "code":"HYY"}, {"name":"红兴隆", "code":"VHB"}, {"name":"换新天", "code":"VTB"}, {"name":"红岘台", "code":"HTJ"}, {"name":"红彦", "code":"VIX"}, {"name":"合阳", "code":"HAY"}, {"name":"海阳", "code":"HYK"}, {"name":"衡阳东", "code":"HVQ"}, {"name":"华蓥", "code":"HUW"}, {"name":"汉阴", "code":"HQY"}, {"name":"黄羊滩", "code":"HGJ"}, {"name":"汉源", "code":"WHW"}, {"name":"湟源", "code":"HNO"}, {"name":"河源", "code":"VIQ"}, {"name":"花园", "code":"HUN"}, {"name":"黄羊镇", "code":"HYJ"}, {"name":"湖州", "code":"VZH"}, {"name":"化州", "code":"HZZ"}, {"name":"黄州", "code":"VON"}, {"name":"霍州", "code":"HZV"}, {"name":"惠州西", "code":"VXQ"}, {"name":"巨宝", "code":"JRT"}, {"name":"靖边", "code":"JIY"}, {"name":"金宝屯", "code":"JBD"}, {"name":"晋城北", "code":"JEF"}, {"name":"金昌", "code":"JCJ"}, {"name":"鄄城", "code":"JCK"}, {"name":"交城", "code":"JNV"}, {"name":"建昌", "code":"JFD"}, {"name":"峻德", "code":"JDB"}, {"name":"井店", "code":"JFP"}, {"name":"鸡东", "code":"JOB"}, {"name":"江都", "code":"UDH"}, {"name":"鸡冠山", "code":"JST"}, {"name":"金沟屯", "code":"VGP"}, {"name":"静海", "code":"JHP"}, {"name":"金河", "code":"JHX"}, {"name":"锦河", "code":"JHB"}, {"name":"精河", "code":"JHR"}, {"name":"精河南", "code":"JIR"}, {"name":"江华", "code":"JHZ"}, {"name":"建湖", "code":"AJH"}, {"name":"纪家沟", "code":"VJD"}, {"name":"晋江", "code":"JJS"}, {"name":"江津", "code":"JJW"}, {"name":"姜家", "code":"JJB"}, {"name":"金坑", "code":"JKT"}, {"name":"芨岭", "code":"JLJ"}, {"name":"金马村", "code":"JMM"}, {"name":"江门", "code":"JWQ"}, {"name":"角美", "code":"JES"}, {"name":"莒南", "code":"JOK"}, {"name":"井南", "code":"JNP"}, {"name":"建瓯", "code":"JVS"}, {"name":"经棚", "code":"JPC"}, {"name":"江桥", "code":"JQX"}, {"name":"九三", "code":"SSX"}, {"name":"金山北", "code":"EGH"}, {"name":"京山", "code":"JCN"}, {"name":"建始", "code":"JRN"}, {"name":"嘉善", "code":"JSH"}, {"name":"稷山", "code":"JVV"}, {"name":"吉舒", "code":"JSL"}, {"name":"建设", "code":"JET"}, {"name":"甲山", "code":"JOP"}, {"name":"建三江", "code":"JIB"}, {"name":"嘉善南", "code":"EAH"}, {"name":"金山屯", "code":"JTB"}, {"name":"江所田", "code":"JOM"}, {"name":"景泰", "code":"JTJ"}, {"name":"九台南", "code":"JNL"}, {"name":"吉文", "code":"JWX"}, {"name":"进贤", "code":"JUG"}, {"name":"莒县", "code":"JKK"}, {"name":"嘉祥", "code":"JUK"}, {"name":"介休", "code":"JXV"}, {"name":"井陉", "code":"JJP"}, {"name":"嘉兴", "code":"JXH"}, {"name":"嘉兴南", "code":"EPH"}, {"name":"夹心子", "code":"JXT"}, {"name":"简阳", "code":"JYW"}, {"name":"揭阳", "code":"JRQ"}, {"name":"建阳", "code":"JYS"}, {"name":"姜堰", "code":"UEH"}, {"name":"巨野", "code":"JYK"}, {"name":"江永", "code":"JYZ"}, {"name":"靖远", "code":"JYJ"}, {"name":"缙云", "code":"JYH"}, {"name":"江源", "code":"SZL"}, {"name":"济源", "code":"JYF"}, {"name":"靖远西", "code":"JXJ"}, {"name":"胶州北", "code":"JZK"}, {"name":"焦作东", "code":"WEF"}, {"name":"靖州", "code":"JEQ"}, {"name":"荆州", "code":"JBN"}, {"name":"金寨", "code":"JZH"}, {"name":"晋州", "code":"JXP"}, {"name":"胶州", "code":"JXK"}, {"name":"锦州南", "code":"JOD"}, {"name":"焦作", "code":"JOF"}, {"name":"旧庄窝", "code":"JVP"}, {"name":"金杖子", "code":"JYD"}, {"name":"开安", "code":"KAT"}, {"name":"库车", "code":"KCR"}, {"name":"康城", "code":"KCP"}, {"name":"库都尔", "code":"KDX"}, {"name":"宽甸", "code":"KDT"}, {"name":"克东", "code":"KOB"}, {"name":"开江", "code":"KAW"}, {"name":"康金井", "code":"KJB"}, {"name":"喀喇其", "code":"KQX"}, {"name":"开鲁", "code":"KLC"}, {"name":"克拉玛依", "code":"KHR"}, {"name":"口前", "code":"KQL"}, {"name":"奎山", "code":"KAB"}, {"name":"昆山", "code":"KSH"}, {"name":"克山", "code":"KSB"}, {"name":"开通", "code":"KTT"}, {"name":"康熙岭", "code":"KXZ"}, {"name":"昆阳", "code":"KAM"}, {"name":"克一河", "code":"KHX"}, {"name":"开原西", "code":"KXT"}, {"name":"康庄", "code":"KZP"}, {"name":"来宾", "code":"UBZ"}, {"name":"老边", "code":"LLT"}, {"name":"灵宝西", "code":"LPF"}, {"name":"龙川", "code":"LUQ"}, {"name":"乐昌", "code":"LCQ"}, {"name":"黎城", "code":"UCP"}, {"name":"聊城", "code":"UCK"}, {"name":"蓝村", "code":"LCK"}, {"name":"两当", "code":"LDY"}, {"name":"林东", "code":"LRC"}, {"name":"乐都", "code":"LDO"}, {"name":"梁底下", "code":"LDP"}, {"name":"六道河子", "code":"LVP"}, {"name":"鲁番", "code":"LVM"}, {"name":"廊坊", "code":"LJP"}, {"name":"落垡", "code":"LOP"}, {"name":"廊坊北", "code":"LFP"}, {"name":"老府", "code":"UFD"}, {"name":"兰岗", "code":"LNB"}, {"name":"龙骨甸", "code":"LGM"}, {"name":"芦沟", "code":"LOM"}, {"name":"龙沟", "code":"LGJ"}, {"name":"拉古", "code":"LGB"}, {"name":"临海", "code":"UFH"}, {"name":"林海", "code":"LXX"}, {"name":"拉哈", "code":"LHX"}, {"name":"凌海", "code":"JID"}, {"name":"柳河", "code":"LNL"}, {"name":"六合", "code":"KLH"}, {"name":"龙华", "code":"LHP"}, {"name":"滦河沿", "code":"UNP"}, {"name":"六合镇", "code":"LEX"}, {"name":"亮甲店", "code":"LRT"}, {"name":"刘家店", "code":"UDT"}, {"name":"刘家河", "code":"LVT"}, {"name":"连江", "code":"LKS"}, {"name":"李家", "code":"LJB"}, {"name":"罗江", "code":"LJW"}, {"name":"廉江", "code":"LJZ"}, {"name":"庐江", "code":"UJH"}, {"name":"两家", "code":"UJT"}, {"name":"龙江", "code":"LJX"}, {"name":"龙嘉", "code":"UJL"}, {"name":"莲江口", "code":"LHB"}, {"name":"蔺家楼", "code":"ULK"}, {"name":"李家坪", "code":"LIJ"}, {"name":"兰考", "code":"LKF"}, {"name":"林口", "code":"LKB"}, {"name":"路口铺", "code":"LKQ"}, {"name":"老莱", "code":"LAX"}, {"name":"拉林", "code":"LAB"}, {"name":"陆良", "code":"LRM"}, {"name":"龙里", "code":"LLW"}, {"name":"零陵", "code":"UWZ"}, {"name":"临澧", "code":"LWQ"}, {"name":"兰棱", "code":"LLB"}, {"name":"卢龙", "code":"UAP"}, {"name":"喇嘛甸", "code":"LMX"}, {"name":"里木店", "code":"LMB"}, {"name":"洛门", "code":"LMJ"}, {"name":"龙南", "code":"UNG"}, {"name":"梁平", "code":"UQW"}, {"name":"罗平", "code":"LPM"}, {"name":"落坡岭", "code":"LPP"}, {"name":"六盘山", "code":"UPJ"}, {"name":"乐平市", "code":"LPG"}, {"name":"临清", "code":"UQK"}, {"name":"龙泉寺", "code":"UQJ"}, {"name":"乐山北", "code":"UTW"}, {"name":"乐善村", "code":"LUM"}, {"name":"冷水江东", "code":"UDQ"}, {"name":"连山关", "code":"LGT"}, {"name":"流水沟", "code":"USP"}, {"name":"陵水", "code":"LIQ"}, {"name":"罗山", "code":"LRN"}, {"name":"鲁山", "code":"LAF"}, {"name":"丽水", "code":"USH"}, {"name":"梁山", "code":"LMK"}, {"name":"灵石", "code":"LSV"}, {"name":"露水河", "code":"LUL"}, {"name":"庐山", "code":"LSG"}, {"name":"林盛堡", "code":"LBT"}, {"name":"柳树屯", "code":"LSD"}, {"name":"龙山镇", "code":"LAS"}, {"name":"梨树镇", "code":"LSB"}, {"name":"李石寨", "code":"LET"}, {"name":"黎塘", "code":"LTZ"}, {"name":"轮台", "code":"LAR"}, {"name":"芦台", "code":"LTP"}, {"name":"龙塘坝", "code":"LBM"}, {"name":"濑湍", "code":"LVZ"}, {"name":"骆驼巷", "code":"LTJ"}, {"name":"李旺", "code":"VLJ"}, {"name":"莱芜东", "code":"LWK"}, {"name":"狼尾山", "code":"LRJ"}, {"name":"灵武", "code":"LNJ"}, {"name":"莱芜西", "code":"UXK"}, {"name":"朗乡", "code":"LXB"}, {"name":"陇县", "code":"LXY"}, {"name":"临湘", "code":"LXQ"}, {"name":"芦溪", "code":"LUG"}, {"name":"莱西", "code":"LXK"}, {"name":"林西", "code":"LXC"}, {"name":"滦县", "code":"UXP"}, {"name":"略阳", "code":"LYY"}, {"name":"莱阳", "code":"LYK"}, {"name":"辽阳", "code":"LYT"}, {"name":"临沂北", "code":"UYK"}, {"name":"凌源东", "code":"LDD"}, {"name":"连云港", "code":"UIH"}, {"name":"临颍", "code":"LNF"}, {"name":"老营", "code":"LXL"}, {"name":"龙游", "code":"LMH"}, {"name":"罗源", "code":"LVS"}, {"name":"林源", "code":"LYX"}, {"name":"涟源", "code":"LAQ"}, {"name":"涞源", "code":"LYP"}, {"name":"耒阳西", "code":"LPQ"}, {"name":"临泽", "code":"LEJ"}, {"name":"龙爪沟", "code":"LZT"}, {"name":"雷州", "code":"UAQ"}, {"name":"六枝", "code":"LIW"}, {"name":"鹿寨", "code":"LIZ"}, {"name":"来舟", "code":"LZS"}, {"name":"龙镇", "code":"LZA"}, {"name":"拉鲊", "code":"LEM"}, {"name":"兰州新区", "code":"LQJ"}, {"name":"马鞍山", "code":"MAH"}, {"name":"毛坝", "code":"MBY"}, {"name":"毛坝关", "code":"MGY"}, {"name":"麻城北", "code":"MBN"}, {"name":"渑池", "code":"MCF"}, {"name":"明城", "code":"MCL"}, {"name":"庙城", "code":"MAP"}, {"name":"渑池南", "code":"MNF"}, {"name":"茅草坪", "code":"KPM"}, {"name":"猛洞河", "code":"MUQ"}, {"name":"磨刀石", "code":"MOB"}, {"name":"弥渡", "code":"MDF"}, {"name":"帽儿山", "code":"MRB"}, {"name":"明港", "code":"MGN"}, {"name":"梅河口", "code":"MHL"}, {"name":"马皇", "code":"MHZ"}, {"name":"孟家岗", "code":"MGB"}, {"name":"美兰", "code":"MHQ"}, {"name":"汨罗东", "code":"MQQ"}, {"name":"马莲河", "code":"MHB"}, {"name":"茅岭", "code":"MLZ"}, {"name":"庙岭", "code":"MLL"}, {"name":"茂林", "code":"MLD"}, {"name":"穆棱", "code":"MLB"}, {"name":"马林", "code":"MID"}, {"name":"马龙", "code":"MGM"}, {"name":"木里图", "code":"MUD"}, {"name":"汨罗", "code":"MLQ"}, {"name":"玛纳斯湖", "code":"MNR"}, {"name":"冕宁", "code":"UGW"}, {"name":"沐滂", "code":"MPQ"}, {"name":"马桥河", "code":"MQB"}, {"name":"闽清", "code":"MQS"}, {"name":"民权", "code":"MQF"}, {"name":"明水河", "code":"MUT"}, {"name":"麻山", "code":"MAB"}, {"name":"眉山", "code":"MSW"}, {"name":"漫水湾", "code":"MKW"}, {"name":"茂舍祖", "code":"MOM"}, {"name":"米沙子", "code":"MST"}, {"name":"美溪", "code":"MEB"}, {"name":"勉县", "code":"MVY"}, {"name":"麻阳", "code":"MVQ"}, {"name":"密云北", "code":"MUP"}, {"name":"米易", "code":"MMW"}, {"name":"麦园", "code":"MYS"}, {"name":"墨玉", "code":"MUR"}, {"name":"庙庄", "code":"MZJ"}, {"name":"米脂", "code":"MEY"}, {"name":"明珠", "code":"MFQ"}, {"name":"宁安", "code":"NAB"}, {"name":"农安", "code":"NAT"}, {"name":"南博山", "code":"NBK"}, {"name":"南仇", "code":"NCK"}, {"name":"南城司", "code":"NSP"}, {"name":"宁村", "code":"NCZ"}, {"name":"宁德", "code":"NES"}, {"name":"南观村", "code":"NGP"}, {"name":"南宫东", "code":"NFP"}, {"name":"南关岭", "code":"NLT"}, {"name":"宁国", "code":"NNH"}, {"name":"宁海", "code":"NHH"}, {"name":"南河川", "code":"NHJ"}, {"name":"南华", "code":"NHS"}, {"name":"泥河子", "code":"NHD"}, {"name":"宁家", "code":"NVT"}, {"name":"南靖", "code":"NJS"}, {"name":"牛家", "code":"NJB"}, {"name":"能家", "code":"NJD"}, {"name":"南口", "code":"NKP"}, {"name":"南口前", "code":"NKT"}, {"name":"南朗", "code":"NNQ"}, {"name":"乃林", "code":"NLD"}, {"name":"尼勒克", "code":"NIR"}, {"name":"那罗", "code":"ULZ"}, {"name":"宁陵县", "code":"NLF"}, {"name":"奈曼", "code":"NMD"}, {"name":"宁明", "code":"NMZ"}, {"name":"南木", "code":"NMX"}, {"name":"南平南", "code":"NNS"}, {"name":"那铺", "code":"NPZ"}, {"name":"南桥", "code":"NQD"}, {"name":"那曲", "code":"NQO"}, {"name":"暖泉", "code":"NQJ"}, {"name":"南台", "code":"NTT"}, {"name":"南头", "code":"NOQ"}, {"name":"宁武", "code":"NWV"}, {"name":"南湾子", "code":"NWP"}, {"name":"南翔北", "code":"NEH"}, {"name":"宁乡", "code":"NXQ"}, {"name":"内乡", "code":"NXF"}, {"name":"牛心台", "code":"NXT"}, {"name":"南峪", "code":"NUP"}, {"name":"娘子关", "code":"NIP"}, {"name":"南召", "code":"NAF"}, {"name":"南杂木", "code":"NZT"}, {"name":"平安", "code":"PAL"}, {"name":"蓬安", "code":"PAW"}, {"name":"平安驿", "code":"PNO"}, {"name":"磐安镇", "code":"PAJ"}, {"name":"平安镇", "code":"PZT"}, {"name":"蒲城东", "code":"PEY"}, {"name":"蒲城", "code":"PCY"}, {"name":"裴德", "code":"PDB"}, {"name":"偏店", "code":"PRP"}, {"name":"平顶山西", "code":"BFF"}, {"name":"坡底下", "code":"PXJ"}, {"name":"瓢儿屯", "code":"PRT"}, {"name":"平房", "code":"PFB"}, {"name":"平岗", "code":"PGL"}, {"name":"平关", "code":"PGM"}, {"name":"盘关", "code":"PAM"}, {"name":"平果", "code":"PGZ"}, {"name":"徘徊北", "code":"PHP"}, {"name":"平河口", "code":"PHM"}, {"name":"盘锦北", "code":"PBD"}, {"name":"潘家店", "code":"PDP"}, {"name":"皮口", "code":"PKT"}, {"name":"普兰店", "code":"PLT"}, {"name":"偏岭", "code":"PNT"}, {"name":"平山", "code":"PSB"}, {"name":"彭山", "code":"PSW"}, {"name":"皮山", "code":"PSR"}, {"name":"彭水", "code":"PHW"}, {"name":"磐石", "code":"PSL"}, {"name":"平社", "code":"PSV"}, {"name":"平台", "code":"PVT"}, {"name":"平田", "code":"PTM"}, {"name":"莆田", "code":"PTS"}, {"name":"葡萄菁", "code":"PTW"}, {"name":"普湾", "code":"PWT"}, {"name":"平旺", "code":"PWV"}, {"name":"平型关", "code":"PGV"}, {"name":"普雄", "code":"POW"}, {"name":"郫县", "code":"PWW"}, {"name":"平洋", "code":"PYX"}, {"name":"彭阳", "code":"PYJ"}, {"name":"平遥", "code":"PYV"}, {"name":"平邑", "code":"PIK"}, {"name":"平原堡", "code":"PPJ"}, {"name":"平原", "code":"PYK"}, {"name":"平峪", "code":"PYP"}, {"name":"彭泽", "code":"PZG"}, {"name":"邳州", "code":"PJH"}, {"name":"平庄", "code":"PZD"}, {"name":"泡子", "code":"POD"}, {"name":"平庄南", "code":"PND"}, {"name":"乾安", "code":"QOT"}, {"name":"庆安", "code":"QAB"}, {"name":"迁安", "code":"QQP"}, {"name":"祁东北", "code":"QRQ"}, {"name":"七甸", "code":"QDM"}, {"name":"曲阜东", "code":"QAK"}, {"name":"庆丰", "code":"QFT"}, {"name":"奇峰塔", "code":"QVP"}, {"name":"曲阜", "code":"QFK"}, {"name":"琼海", "code":"QYQ"}, {"name":"秦皇岛", "code":"QTP"}, {"name":"千河", "code":"QUY"}, {"name":"清河", "code":"QIP"}, {"name":"清河门", "code":"QHD"}, {"name":"清华园", "code":"QHP"}, {"name":"渠旧", "code":"QJZ"}, {"name":"綦江", "code":"QJW"}, {"name":"潜江", "code":"QJN"}, {"name":"全椒", "code":"INH"}, {"name":"秦家", "code":"QJB"}, {"name":"祁家堡", "code":"QBT"}, {"name":"清涧县", "code":"QNY"}, {"name":"秦家庄", "code":"QZV"}, {"name":"七里河", "code":"QLD"}, {"name":"渠黎", "code":"QLZ"}, {"name":"秦岭", "code":"QLY"}, {"name":"青龙山", "code":"QGH"}, {"name":"祁门", "code":"QIH"}, {"name":"前磨头", "code":"QMP"}, {"name":"青山", "code":"QSB"}, {"name":"确山", "code":"QSN"}, {"name":"清水", "code":"QUJ"}, {"name":"前山", "code":"QXQ"}, {"name":"戚墅堰", "code":"QYH"}, {"name":"青田", "code":"QVH"}, {"name":"桥头", "code":"QAT"}, {"name":"青铜峡", "code":"QTJ"}, {"name":"前卫", "code":"QWD"}, {"name":"前苇塘", "code":"QWP"}, {"name":"渠县", "code":"QRW"}, {"name":"祁县", "code":"QXV"}, {"name":"青县", "code":"QXP"}, {"name":"桥西", "code":"QXJ"}, {"name":"清徐", "code":"QUV"}, {"name":"旗下营", "code":"QXC"}, {"name":"千阳", "code":"QOY"}, {"name":"沁阳", "code":"QYF"}, {"name":"泉阳", "code":"QYL"}, {"name":"祁阳北", "code":"QVQ"}, {"name":"七营", "code":"QYJ"}, {"name":"庆阳山", "code":"QSJ"}, {"name":"清远", "code":"QBQ"}, {"name":"清原", "code":"QYT"}, {"name":"钦州东", "code":"QDZ"}, {"name":"钦州", "code":"QRZ"}, {"name":"青州市", "code":"QZK"}, {"name":"瑞安", "code":"RAH"}, {"name":"荣昌", "code":"RCW"}, {"name":"瑞昌", "code":"RCG"}, {"name":"如皋", "code":"RBH"}, {"name":"容桂", "code":"RUQ"}, {"name":"任丘", "code":"RQP"}, {"name":"乳山", "code":"ROK"}, {"name":"融水", "code":"RSZ"}, {"name":"热水", "code":"RSD"}, {"name":"容县", "code":"RXZ"}, {"name":"饶阳", "code":"RVP"}, {"name":"汝阳", "code":"RYF"}, {"name":"绕阳河", "code":"RHD"}, {"name":"汝州", "code":"ROF"}, {"name":"石坝", "code":"OBJ"}, {"name":"上板城", "code":"SBP"}, {"name":"施秉", "code":"AQW"}, {"name":"上板城南", "code":"OBP"}, {"name":"世博园", "code":"ZWT"}, {"name":"双城北", "code":"SBB"}, {"name":"商城", "code":"SWN"}, {"name":"莎车", "code":"SCR"}, {"name":"顺昌", "code":"SCS"}, {"name":"舒城", "code":"OCH"}, {"name":"神池", "code":"SMV"}, {"name":"沙城", "code":"SCP"}, {"name":"石城", "code":"SCT"}, {"name":"山城镇", "code":"SCL"}, {"name":"山丹", "code":"SDJ"}, {"name":"顺德", "code":"ORQ"}, {"name":"绥德", "code":"ODY"}, {"name":"水洞", "code":"SIL"}, {"name":"商都", "code":"SXC"}, {"name":"十渡", "code":"SEP"}, {"name":"四道湾", "code":"OUD"}, {"name":"顺德学院", "code":"OJQ"}, {"name":"绅坊", "code":"OLH"}, {"name":"双丰", "code":"OFB"}, {"name":"四方台", "code":"STB"}, {"name":"水富", "code":"OTW"}, {"name":"三关口", "code":"OKJ"}, {"name":"桑根达来", "code":"OGC"}, {"name":"韶关", "code":"SNQ"}, {"name":"上高镇", "code":"SVK"}, {"name":"上杭", "code":"JBS"}, {"name":"沙海", "code":"SED"}, {"name":"松河", "code":"SBM"}, {"name":"沙河", "code":"SHP"}, {"name":"沙河口", "code":"SKT"}, {"name":"赛汗塔拉", "code":"SHC"}, {"name":"沙河市", "code":"VOP"}, {"name":"沙后所", "code":"SSD"}, {"name":"山河屯", "code":"SHL"}, {"name":"三河县", "code":"OXP"}, {"name":"四合永", "code":"OHD"}, {"name":"三汇镇", "code":"OZW"}, {"name":"双河镇", "code":"SEL"}, {"name":"石河子", "code":"SZR"}, {"name":"三合庄", "code":"SVP"}, {"name":"三家店", "code":"ODP"}, {"name":"水家湖", "code":"SQH"}, {"name":"沈家河", "code":"OJJ"}, {"name":"松江河", "code":"SJL"}, {"name":"尚家", "code":"SJB"}, {"name":"孙家", "code":"SUB"}, {"name":"沈家", "code":"OJB"}, {"name":"松江", "code":"SAH"}, {"name":"三江口", "code":"SKD"}, {"name":"司家岭", "code":"OLK"}, {"name":"松江南", "code":"IMH"}, {"name":"石景山南", "code":"SRP"}, {"name":"邵家堂", "code":"SJJ"}, {"name":"三江县", "code":"SOZ"}, {"name":"三家寨", "code":"SMM"}, {"name":"十家子", "code":"SJD"}, {"name":"松江镇", "code":"OZL"}, {"name":"施家嘴", "code":"SHM"}, {"name":"深井子", "code":"SWT"}, {"name":"什里店", "code":"OMP"}, {"name":"疏勒", "code":"SUR"}, {"name":"疏勒河", "code":"SHJ"}, {"name":"舍力虎", "code":"VLD"}, {"name":"石磷", "code":"SPB"}, {"name":"双辽", "code":"ZJD"}, {"name":"绥棱", "code":"SIB"}, {"name":"石岭", "code":"SOL"}, {"name":"石林", "code":"SLM"}, {"name":"石林南", "code":"LNM"}, {"name":"石龙", "code":"SLQ"}, {"name":"萨拉齐", "code":"SLC"}, {"name":"索伦", "code":"SNT"}, {"name":"商洛", "code":"OLY"}, {"name":"沙岭子", "code":"SLP"}, {"name":"石门县北", "code":"VFQ"}, {"name":"三门峡南", "code":"SCF"}, {"name":"三门县", "code":"OQH"}, {"name":"石门县", "code":"OMQ"}, {"name":"三门峡西", "code":"SXF"}, {"name":"肃宁", "code":"SYP"}, {"name":"宋", "code":"SOB"}, {"name":"双牌", "code":"SBZ"}, {"name":"四平东", "code":"PPT"}, {"name":"遂平", "code":"SON"}, {"name":"沙坡头", "code":"SFJ"}, {"name":"商丘南", "code":"SPF"}, {"name":"水泉", "code":"SID"}, {"name":"石泉县", "code":"SXY"}, {"name":"石桥子", "code":"SQT"}, {"name":"石人城", "code":"SRB"}, {"name":"石人", "code":"SRL"}, {"name":"山市", "code":"SQB"}, {"name":"神树", "code":"SWB"}, {"name":"鄯善", "code":"SSR"}, {"name":"三水", "code":"SJQ"}, {"name":"泗水", "code":"OSK"}, {"name":"石山", "code":"SAD"}, {"name":"松树", "code":"SFT"}, {"name":"首山", "code":"SAT"}, {"name":"三十家", "code":"SRD"}, {"name":"三十里堡", "code":"SST"}, {"name":"松树镇", "code":"SSL"}, {"name":"松桃", "code":"MZQ"}, {"name":"索图罕", "code":"SHX"}, {"name":"三堂集", "code":"SDH"}, {"name":"石头", "code":"OTB"}, {"name":"神头", "code":"SEV"}, {"name":"沙沱", "code":"SFM"}, {"name":"上万", "code":"SWP"}, {"name":"孙吴", "code":"SKB"}, {"name":"沙湾县", "code":"SXR"}, {"name":"遂溪", "code":"SXZ"}, {"name":"沙县", "code":"SAS"}, {"name":"歙县", "code":"OVH"}, {"name":"绍兴", "code":"SOH"}, {"name":"石岘", "code":"SXL"}, {"name":"上西铺", "code":"SXM"}, {"name":"石峡子", "code":"SXJ"}, {"name":"绥阳", "code":"SYB"}, {"name":"沭阳", "code":"FMH"}, {"name":"寿阳", "code":"SYV"}, {"name":"水洋", "code":"OYP"}, {"name":"三阳川", "code":"SYJ"}, {"name":"上腰墩", "code":"SPJ"}, {"name":"三营", "code":"OEJ"}, {"name":"顺义", "code":"SOP"}, {"name":"三义井", "code":"OYD"}, {"name":"三源浦", "code":"SYL"}, {"name":"三原", "code":"SAY"}, {"name":"上虞", "code":"BDH"}, {"name":"上园", "code":"SUD"}, {"name":"水源", "code":"OYJ"}, {"name":"桑园子", "code":"SAJ"}, {"name":"绥中北", "code":"SND"}, {"name":"苏州北", "code":"OHH"}, {"name":"宿州东", "code":"SRH"}, {"name":"深圳东", "code":"BJQ"}, {"name":"深州", "code":"OZP"}, {"name":"孙镇", "code":"OZY"}, {"name":"绥中", "code":"SZD"}, {"name":"尚志", "code":"SZB"}, {"name":"师庄", "code":"SNM"}, {"name":"松滋", "code":"SIN"}, {"name":"师宗", "code":"SEM"}, {"name":"苏州园区", "code":"KAH"}, {"name":"苏州新区", "code":"ITH"}, {"name":"泰安", "code":"TMK"}, {"name":"台安", "code":"TID"}, {"name":"通安驿", "code":"TAJ"}, {"name":"桐柏", "code":"TBF"}, {"name":"通北", "code":"TBB"}, {"name":"汤池", "code":"TCX"}, {"name":"桐城", "code":"TTH"}, {"name":"郯城", "code":"TZK"}, {"name":"铁厂", "code":"TCL"}, {"name":"桃村", "code":"TCK"}, {"name":"通道", "code":"TRQ"}, {"name":"田东", "code":"TDZ"}, {"name":"天岗", "code":"TGL"}, {"name":"土贵乌拉", "code":"TGC"}, {"name":"通沟", "code":"TOL"}, {"name":"太谷", "code":"TGV"}, {"name":"塔哈", "code":"THX"}, {"name":"棠海", "code":"THM"}, {"name":"唐河", "code":"THF"}, {"name":"泰和", "code":"THG"}, {"name":"太湖", "code":"TKH"}, {"name":"团结", "code":"TIX"}, {"name":"谭家井", "code":"TNJ"}, {"name":"陶家屯", "code":"TOT"}, {"name":"唐家湾", "code":"PDQ"}, {"name":"统军庄", "code":"TZP"}, {"name":"泰康", "code":"TKX"}, {"name":"吐列毛杜", "code":"TMD"}, {"name":"图里河", "code":"TEX"}, {"name":"亭亮", "code":"TIZ"}, {"name":"田林", "code":"TFZ"}, {"name":"铜陵", "code":"TJH"}, {"name":"铁力", "code":"TLB"}, {"name":"铁岭西", "code":"PXT"}, {"name":"图们北", "code":"QSL"}, {"name":"天门", "code":"TMN"}, {"name":"天门南", "code":"TNN"}, {"name":"太姥山", "code":"TLS"}, {"name":"土牧尔台", "code":"TRC"}, {"name":"土门子", "code":"TCJ"}, {"name":"潼南", "code":"TVW"}, {"name":"洮南", "code":"TVT"}, {"name":"太平川", "code":"TIT"}, {"name":"太平镇", "code":"TEB"}, {"name":"图强", "code":"TQX"}, {"name":"台前", "code":"TTK"}, {"name":"天桥岭", "code":"TQL"}, {"name":"土桥子", "code":"TQJ"}, {"name":"汤山城", "code":"TCT"}, {"name":"桃山", "code":"TAB"}, {"name":"塔石嘴", "code":"TIM"}, {"name":"通途", "code":"TUT"}, {"name":"汤旺河", "code":"THB"}, {"name":"同心", "code":"TXJ"}, {"name":"土溪", "code":"TSW"}, {"name":"桐乡", "code":"TCH"}, {"name":"田阳", "code":"TRZ"}, {"name":"天义", "code":"TND"}, {"name":"汤阴", "code":"TYF"}, {"name":"驼腰岭", "code":"TIL"}, {"name":"太阳山", "code":"TYJ"}, {"name":"汤原", "code":"TYB"}, {"name":"塔崖驿", "code":"TYP"}, {"name":"滕州东", "code":"TEK"}, {"name":"台州", "code":"TZH"}, {"name":"天祝", "code":"TZJ"}, {"name":"滕州", "code":"TXK"}, {"name":"天镇", "code":"TZV"}, {"name":"桐子林", "code":"TEW"}, {"name":"天柱山", "code":"QWH"}, {"name":"文安", "code":"WBP"}, {"name":"武安", "code":"WAP"}, {"name":"王安镇", "code":"WVP"}, {"name":"旺苍", "code":"WEW"}, {"name":"五叉沟", "code":"WCT"}, {"name":"文昌", "code":"WEQ"}, {"name":"温春", "code":"WDB"}, {"name":"五大连池", "code":"WRB"}, {"name":"文登", "code":"WBK"}, {"name":"五道沟", "code":"WDL"}, {"name":"五道河", "code":"WHP"}, {"name":"文地", "code":"WNZ"}, {"name":"卫东", "code":"WVT"}, {"name":"武当山", "code":"WRN"}, {"name":"望都", "code":"WDP"}, {"name":"乌尔旗汗", "code":"WHX"}, {"name":"潍坊", "code":"WFK"}, {"name":"万发屯", "code":"WFB"}, {"name":"王府", "code":"WUT"}, {"name":"瓦房店西", "code":"WXT"}, {"name":"王岗", "code":"WGB"}, {"name":"武功", "code":"WGY"}, {"name":"湾沟", "code":"WGL"}, {"name":"吴官田", "code":"WGM"}, {"name":"乌海", "code":"WVC"}, {"name":"苇河", "code":"WHB"}, {"name":"卫辉", "code":"WHF"}, {"name":"吴家川", "code":"WCJ"}, {"name":"五家", "code":"WUB"}, {"name":"威箐", "code":"WAM"}, {"name":"午汲", "code":"WJP"}, {"name":"渭津", "code":"WJL"}, {"name":"王家湾", "code":"WJJ"}, {"name":"倭肯", "code":"WQB"}, {"name":"五棵树", "code":"WKT"}, {"name":"五龙背", "code":"WBT"}, {"name":"乌兰哈达", "code":"WLC"}, {"name":"万乐", "code":"WEB"}, {"name":"瓦拉干", "code":"WVX"}, {"name":"温岭", "code":"VHH"}, {"name":"五莲", "code":"WLK"}, {"name":"乌拉特前旗", "code":"WQC"}, {"name":"乌拉山", "code":"WSC"}, {"name":"卧里屯", "code":"WLX"}, {"name":"渭南北", "code":"WBY"}, {"name":"乌奴耳", "code":"WRX"}, {"name":"万宁", "code":"WNQ"}, {"name":"万年", "code":"WWG"}, {"name":"渭南南", "code":"WVY"}, {"name":"渭南镇", "code":"WNJ"}, {"name":"沃皮", "code":"WPT"}, {"name":"吴堡", "code":"WUY"}, {"name":"吴桥", "code":"WUP"}, {"name":"汪清", "code":"WQL"}, {"name":"武清", "code":"WWP"}, {"name":"武山", "code":"WSJ"}, {"name":"文水", "code":"WEV"}, {"name":"魏善庄", "code":"WSP"}, {"name":"王瞳", "code":"WTP"}, {"name":"五台山", "code":"WSV"}, {"name":"王团庄", "code":"WZJ"}, {"name":"五五", "code":"WVR"}, {"name":"无锡东", "code":"WGH"}, {"name":"卫星", "code":"WVB"}, {"name":"闻喜", "code":"WXV"}, {"name":"武乡", "code":"WVV"}, {"name":"无锡新区", "code":"IFH"}, {"name":"武穴", "code":"WXN"}, {"name":"吴圩", "code":"WYZ"}, {"name":"王杨", "code":"WYB"}, {"name":"五营", "code":"WWB"}, {"name":"武义", "code":"RYH"}, {"name":"瓦窑田", "code":"WIM"}, {"name":"五原", "code":"WYC"}, {"name":"苇子沟", "code":"WZL"}, {"name":"韦庄", "code":"WZY"}, {"name":"五寨", "code":"WZV"}, {"name":"王兆屯", "code":"WZB"}, {"name":"微子镇", "code":"WQP"}, {"name":"魏杖子", "code":"WKD"}, {"name":"新安", "code":"EAM"}, {"name":"兴安", "code":"XAZ"}, {"name":"新安县", "code":"XAF"}, {"name":"新保安", "code":"XAP"}, {"name":"下板城", "code":"EBP"}, {"name":"西八里", "code":"XLP"}, {"name":"宣城", "code":"ECH"}, {"name":"兴城", "code":"XCD"}, {"name":"小村", "code":"XEM"}, {"name":"新绰源", "code":"XRX"}, {"name":"下城子", "code":"XCB"}, {"name":"新城子", "code":"XCT"}, {"name":"喜德", "code":"EDW"}, {"name":"小得江", "code":"EJM"}, {"name":"西大庙", "code":"XMP"}, {"name":"小董", "code":"XEZ"}, {"name":"小东", "code":"XOD"}, {"name":"息烽", "code":"XFW"}, {"name":"信丰", "code":"EFG"}, {"name":"襄汾", "code":"XFV"}, {"name":"新干", "code":"EGG"}, {"name":"孝感", "code":"XGN"}, {"name":"西固城", "code":"XUJ"}, {"name":"西固", "code":"XIJ"}, {"name":"夏官营", "code":"XGJ"}, {"name":"西岗子", "code":"NBB"}, {"name":"襄河", "code":"XXB"}, {"name":"新和", "code":"XIR"}, {"name":"宣和", "code":"XWJ"}, {"name":"斜河涧", "code":"EEP"}, {"name":"新华屯", "code":"XAX"}, {"name":"新华", "code":"XHB"}, {"name":"新化", "code":"EHQ"}, {"name":"宣化", "code":"XHP"}, {"name":"兴和西", "code":"XEC"}, {"name":"小河沿", "code":"XYD"}, {"name":"下花园", "code":"XYP"}, {"name":"小河镇", "code":"EKY"}, {"name":"徐家", "code":"XJB"}, {"name":"峡江", "code":"EJG"}, {"name":"新绛", "code":"XJV"}, {"name":"辛集", "code":"ENP"}, {"name":"新江", "code":"XJM"}, {"name":"西街口", "code":"EKM"}, {"name":"许家屯", "code":"XJT"}, {"name":"许家台", "code":"XTJ"}, {"name":"谢家镇", "code":"XMT"}, {"name":"兴凯", "code":"EKB"}, {"name":"小榄", "code":"EAQ"}, {"name":"香兰", "code":"XNB"}, {"name":"兴隆店", "code":"XDD"}, {"name":"新乐", "code":"ELP"}, {"name":"新林", "code":"XPX"}, {"name":"小岭", "code":"XLB"}, {"name":"新李", "code":"XLJ"}, {"name":"西林", "code":"XYB"}, {"name":"西柳", "code":"GCT"}, {"name":"仙林", "code":"XPH"}, {"name":"新立屯", "code":"XLD"}, {"name":"兴隆镇", "code":"XZB"}, {"name":"新立镇", "code":"XGT"}, {"name":"新民", "code":"XMD"}, {"name":"西麻山", "code":"XMB"}, {"name":"下马塘", "code":"XAT"}, {"name":"孝南", "code":"XNV"}, {"name":"咸宁北", "code":"XRN"}, {"name":"兴宁", "code":"ENQ"}, {"name":"咸宁", "code":"XNN"}, {"name":"犀浦东", "code":"XAW"}, {"name":"西平", "code":"XPN"}, {"name":"兴平", "code":"XPY"}, {"name":"新坪田", "code":"XPM"}, {"name":"霞浦", "code":"XOS"}, {"name":"溆浦", "code":"EPQ"}, {"name":"犀浦", "code":"XIW"}, {"name":"新青", "code":"XQB"}, {"name":"新邱", "code":"XQD"}, {"name":"兴泉堡", "code":"XQJ"}, {"name":"仙人桥", "code":"XRL"}, {"name":"小寺沟", "code":"ESP"}, {"name":"杏树", "code":"XSB"}, {"name":"夏石", "code":"XIZ"}, {"name":"浠水", "code":"XZN"}, {"name":"下社", "code":"XSV"}, {"name":"徐水", "code":"XSP"}, {"name":"小哨", "code":"XAM"}, {"name":"新松浦", "code":"XOB"}, {"name":"杏树屯", "code":"XDT"}, {"name":"许三湾", "code":"XSJ"}, {"name":"湘潭", "code":"XTQ"}, {"name":"邢台", "code":"XTP"}, {"name":"仙桃西", "code":"XAN"}, {"name":"下台子", "code":"EIP"}, {"name":"徐闻", "code":"XJQ"}, {"name":"新窝铺", "code":"EPD"}, {"name":"修武", "code":"XWF"}, {"name":"新县", "code":"XSN"}, {"name":"息县", "code":"ENN"}, {"name":"西乡", "code":"XQY"}, {"name":"湘乡", "code":"XXQ"}, {"name":"西峡", "code":"XIF"}, {"name":"孝西", "code":"XOV"}, {"name":"小新街", "code":"XXM"}, {"name":"新兴县", "code":"XGQ"}, {"name":"西小召", "code":"XZC"}, {"name":"小西庄", "code":"XXP"}, {"name":"向阳", "code":"XDB"}, {"name":"旬阳", "code":"XUY"}, {"name":"旬阳北", "code":"XBY"}, {"name":"襄阳东", "code":"XWN"}, {"name":"兴业", "code":"SNZ"}, {"name":"小雨谷", "code":"XHM"}, {"name":"信宜", "code":"EEQ"}, {"name":"小月旧", "code":"XFM"}, {"name":"小扬气", "code":"XYX"}, {"name":"祥云", "code":"EXM"}, {"name":"襄垣", "code":"EIF"}, {"name":"夏邑县", "code":"EJH"}, {"name":"新友谊", "code":"EYB"}, {"name":"新阳镇", "code":"XZJ"}, {"name":"徐州东", "code":"UUH"}, {"name":"新帐房", "code":"XZX"}, {"name":"悬钟", "code":"XRP"}, {"name":"新肇", "code":"XZT"}, {"name":"忻州", "code":"XXV"}, {"name":"汐子", "code":"XZD"}, {"name":"西哲里木", "code":"XRD"}, {"name":"新杖子", "code":"ERP"}, {"name":"姚安", "code":"YAC"}, {"name":"依安", "code":"YAX"}, {"name":"永安", "code":"YAS"}, {"name":"永安乡", "code":"YNB"}, {"name":"亚布力", "code":"YBB"}, {"name":"元宝山", "code":"YUD"}, {"name":"羊草", "code":"YAB"}, {"name":"秧草地", "code":"YKM"}, {"name":"阳澄湖", "code":"AIH"}, {"name":"迎春", "code":"YYB"}, {"name":"叶城", "code":"YER"}, {"name":"盐池", "code":"YKJ"}, {"name":"砚川", "code":"YYY"}, {"name":"阳春", "code":"YQQ"}, {"name":"宜城", "code":"YIN"}, {"name":"应城", "code":"YHN"}, {"name":"禹城", "code":"YCK"}, {"name":"晏城", "code":"YEK"}, {"name":"羊场", "code":"YED"}, {"name":"阳城", "code":"YNF"}, {"name":"阳岔", "code":"YAL"}, {"name":"郓城", "code":"YPK"}, {"name":"雁翅", "code":"YAP"}, {"name":"云彩岭", "code":"ACP"}, {"name":"虞城县", "code":"IXH"}, {"name":"营城子", "code":"YCT"}, {"name":"永登", "code":"YDJ"}, {"name":"英德", "code":"YDQ"}, {"name":"尹地", "code":"YDM"}, {"name":"永定", "code":"YGS"}, {"name":"雁荡山", "code":"YGH"}, {"name":"于都", "code":"YDG"}, {"name":"园墩", "code":"YAJ"}, {"name":"英德西", "code":"IIQ"}, {"name":"永丰营", "code":"YYM"}, {"name":"杨岗", "code":"YRB"}, {"name":"阳高", "code":"YOV"}, {"name":"阳谷", "code":"YIK"}, {"name":"友好", "code":"YOB"}, {"name":"余杭", "code":"EVH"}, {"name":"沿河城", "code":"YHP"}, {"name":"岩会", "code":"AEP"}, {"name":"羊臼河", "code":"YHM"}, {"name":"永嘉", "code":"URH"}, {"name":"营街", "code":"YAM"}, {"name":"盐津", "code":"AEW"}, {"name":"余江", "code":"YHG"}, {"name":"燕郊", "code":"AJP"}, {"name":"姚家", "code":"YAT"}, {"name":"岳家井", "code":"YGJ"}, {"name":"一间堡", "code":"YJT"}, {"name":"英吉沙", "code":"YIR"}, {"name":"云居寺", "code":"AFP"}, {"name":"燕家庄", "code":"AZK"}, {"name":"永康", "code":"RFH"}, {"name":"营口东", "code":"YGT"}, {"name":"银浪", "code":"YJX"}, {"name":"永郎", "code":"YLW"}, {"name":"宜良北", "code":"YSM"}, {"name":"永乐店", "code":"YDY"}, {"name":"伊拉哈", "code":"YLX"}, {"name":"伊林", "code":"YLB"}, {"name":"杨陵", "code":"YSY"}, {"name":"彝良", "code":"ALW"}, {"name":"杨林", "code":"YLM"}, {"name":"余粮堡", "code":"YLD"}, {"name":"杨柳青", "code":"YQP"}, {"name":"月亮田", "code":"YUM"}, {"name":"亚龙湾", "code":"TWQ"}, {"name":"义马", "code":"YMF"}, {"name":"玉门", "code":"YXJ"}, {"name":"云梦", "code":"YMN"}, {"name":"元谋", "code":"YMM"}, {"name":"阳明堡", "code":"YVV"}, {"name":"一面山", "code":"YST"}, {"name":"沂南", "code":"YNK"}, {"name":"宜耐", "code":"YVM"}, {"name":"伊宁东", "code":"YNR"}, {"name":"营盘水", "code":"YZJ"}, {"name":"羊堡", "code":"ABM"}, {"name":"阳泉北", "code":"YPP"}, {"name":"乐清", "code":"UPH"}, {"name":"焉耆", "code":"YSR"}, {"name":"源迁", "code":"AQK"}, {"name":"姚千户屯", "code":"YQT"}, {"name":"阳曲", "code":"YQV"}, {"name":"榆树沟", "code":"YGP"}, {"name":"月山", "code":"YBF"}, {"name":"玉石", "code":"YSJ"}, {"name":"偃师", "code":"YSF"}, {"name":"沂水", "code":"YUK"}, {"name":"榆社", "code":"YSV"}, {"name":"窑上", "code":"ASP"}, {"name":"元氏", "code":"YSP"}, {"name":"杨树岭", "code":"YAD"}, {"name":"野三坡", "code":"AIP"}, {"name":"榆树屯", "code":"YSX"}, {"name":"榆树台", "code":"YUT"}, {"name":"鹰手营子", "code":"YIP"}, {"name":"源潭", "code":"YTQ"}, {"name":"牙屯堡", "code":"YTZ"}, {"name":"烟筒山", "code":"YSL"}, {"name":"烟筒屯", "code":"YUX"}, {"name":"羊尾哨", "code":"YWM"}, {"name":"越西", "code":"YHW"}, {"name":"攸县", "code":"YOG"}, {"name":"玉溪", "code":"YXM"}, {"name":"永修", "code":"ACG"}, {"name":"弋阳", "code":"YIG"}, {"name":"酉阳", "code":"AFW"}, {"name":"余姚", "code":"YYH"}, {"name":"岳阳东", "code":"YIQ"}, {"name":"阳邑", "code":"ARP"}, {"name":"鸭园", "code":"YYL"}, {"name":"鸳鸯镇", "code":"YYJ"}, {"name":"燕子砭", "code":"YZY"}, {"name":"宜州", "code":"YSZ"}, {"name":"仪征", "code":"UZH"}, {"name":"兖州", "code":"YZK"}, {"name":"迤资", "code":"YQM"}, {"name":"羊者窝", "code":"AEM"}, {"name":"杨杖子", "code":"YZD"}, {"name":"镇安", "code":"ZEY"}, {"name":"治安", "code":"ZAD"}, {"name":"招柏", "code":"ZBP"}, {"name":"张百湾", "code":"ZUP"}, {"name":"中川机场", "code":"ZJJ"}, {"name":"枝城", "code":"ZCN"}, {"name":"子长", "code":"ZHY"}, {"name":"诸城", "code":"ZQK"}, {"name":"邹城", "code":"ZIK"}, {"name":"赵城", "code":"ZCV"}, {"name":"章党", "code":"ZHT"}, {"name":"正定", "code":"ZDP"}, {"name":"肇东", "code":"ZDB"}, {"name":"照福铺", "code":"ZFM"}, {"name":"章古台", "code":"ZGD"}, {"name":"赵光", "code":"ZGB"}, {"name":"中和", "code":"ZHX"}, {"name":"中华门", "code":"VNH"}, {"name":"枝江北", "code":"ZIN"}, {"name":"钟家村", "code":"ZJY"}, {"name":"朱家沟", "code":"ZUB"}, {"name":"紫荆关", "code":"ZYP"}, {"name":"周家", "code":"ZOB"}, {"name":"诸暨", "code":"ZDH"}, {"name":"镇江南", "code":"ZEH"}, {"name":"周家屯", "code":"ZOD"}, {"name":"褚家湾", "code":"CWJ"}, {"name":"湛江西", "code":"ZWQ"}, {"name":"朱家窑", "code":"ZUJ"}, {"name":"曾家坪子", "code":"ZBW"}, {"name":"张兰", "code":"ZLV"}, {"name":"镇赉", "code":"ZLT"}, {"name":"枣林", "code":"ZIV"}, {"name":"扎鲁特", "code":"ZLD"}, {"name":"扎赉诺尔西", "code":"ZXX"}, {"name":"樟木头", "code":"ZOQ"}, {"name":"中牟", "code":"ZGF"}, {"name":"中宁东", "code":"ZDJ"}, {"name":"中宁", "code":"VNJ"}, {"name":"中宁南", "code":"ZNJ"}, {"name":"镇平", "code":"ZPF"}, {"name":"漳平", "code":"ZPS"}, {"name":"泽普", "code":"ZPR"}, {"name":"枣强", "code":"ZVP"}, {"name":"张桥", "code":"ZQY"}, {"name":"章丘", "code":"ZTK"}, {"name":"朱日和", "code":"ZRC"}, {"name":"泽润里", "code":"ZLM"}, {"name":"中山北", "code":"ZGQ"}, {"name":"樟树东", "code":"ZOG"}, {"name":"中山", "code":"ZSQ"}, {"name":"柞水", "code":"ZSY"}, {"name":"钟山", "code":"ZSZ"}, {"name":"樟树", "code":"ZSG"}, {"name":"珠窝", "code":"ZOP"}, {"name":"张维屯", "code":"ZWB"}, {"name":"彰武", "code":"ZWD"}, {"name":"棕溪", "code":"ZOY"}, {"name":"钟祥", "code":"ZTN"}, {"name":"资溪", "code":"ZXS"}, {"name":"镇西", "code":"ZVT"}, {"name":"张辛", "code":"ZIP"}, {"name":"正镶白旗", "code":"ZXC"}, {"name":"紫阳", "code":"ZVY"}, {"name":"枣阳", "code":"ZYN"}, {"name":"竹园坝", "code":"ZAW"}, {"name":"张掖", "code":"ZYJ"}, {"name":"镇远", "code":"ZUW"}, {"name":"朱杨溪", "code":"ZXW"}, {"name":"漳州东", "code":"GOS"}, {"name":"漳州", "code":"ZUS"}, {"name":"壮志", "code":"ZUX"}, {"name":"子洲", "code":"ZZY"}, {"name":"中寨", "code":"ZZM"}, {"name":"涿州", "code":"ZXP"}, {"name":"咋子", "code":"ZAL"}, {"name":"卓资山", "code":"ZZC"}, {"name":"株洲西", "code":"ZAQ"}, {"name":"安仁", "code":"ARG"}, {"name":"安图西", "code":"AXL"}, {"name":"安阳东", "code":"ADF"}, {"name":"栟茶", "code":"FWH"}, {"name":"保定东", "code":"BMP"}, {"name":"滨海", "code":"FHP"}, {"name":"滨海北", "code":"FCP"}, {"name":"宝鸡南", "code":"BBY"}, {"name":"宝清", "code":"BUB"}, {"name":"本溪新城", "code":"BVT"}, {"name":"彬县", "code":"BXY"}, {"name":"宾阳", "code":"UKZ"}, {"name":"滨州", "code":"BIK"}, {"name":"巢湖东", "code":"GUH"}, {"name":"从江", "code":"KNW"}, {"name":"长临河", "code":"FVH"}, {"name":"茶陵南", "code":"CNG"}, {"name":"长庆桥", "code":"CQJ"}, {"name":"长寿北", "code":"COW"}, {"name":"潮汕", "code":"CBQ"}, {"name":"长武", "code":"CWY"}, {"name":"长兴", "code":"CBH"}, {"name":"长阳", "code":"CYN"}, {"name":"潮阳", "code":"CNQ"}, {"name":"东安东", "code":"DCZ"}, {"name":"东戴河", "code":"RDD"}, {"name":"东二道河", "code":"DRB"}, {"name":"东莞", "code":"RTQ"}, {"name":"大苴", "code":"DIM"}, {"name":"大荔", "code":"DNY"}, {"name":"大青沟", "code":"DSD"}, {"name":"德清", "code":"DRH"}, {"name":"大石头南", "code":"DAL"}, {"name":"大通西", "code":"DTO"}, {"name":"德兴", "code":"DWG"}, {"name":"丹霞山", "code":"IRQ"}, {"name":"大冶北", "code":"DBN"}, {"name":"都匀东", "code":"KJW"}, {"name":"东营南", "code":"DOK"}, {"name":"大余", "code":"DYG"}, {"name":"定州东", "code":"DOP"}, {"name":"峨眉山", "code":"IXW"}, {"name":"鄂州东", "code":"EFN"}, {"name":"防城港北", "code":"FBZ"}, {"name":"凤城东", "code":"FDT"}, {"name":"富川", "code":"FDZ"}, {"name":"丰都", "code":"FUW"}, {"name":"涪陵北", "code":"FEW"}, {"name":"抚远", "code":"FYB"}, {"name":"抚州东", "code":"FDG"}, {"name":"抚州", "code":"FZG"}, {"name":"高安", "code":"GCG"}, {"name":"广安南", "code":"VUW"}, {"name":"高碑店东", "code":"GMP"}, {"name":"恭城", "code":"GCZ"}, {"name":"贵定北", "code":"FMW"}, {"name":"葛店南", "code":"GNN"}, {"name":"贵定县", "code":"KIW"}, {"name":"广汉北", "code":"GVW"}, {"name":"革居", "code":"GEM"}, {"name":"光明城", "code":"IMQ"}, {"name":"广宁", "code":"FBQ"}, {"name":"桂平", "code":"GAZ"}, {"name":"弓棚子", "code":"GPT"}, {"name":"古田北", "code":"GBS"}, {"name":"广通北", "code":"GPM"}, {"name":"高台南", "code":"GAJ"}, {"name":"贵阳北", "code":"KQW"}, {"name":"高邑西", "code":"GNP"}, {"name":"惠安", "code":"HNS"}, {"name":"鹤壁东", "code":"HFF"}, {"name":"寒葱沟", "code":"HKB"}, {"name":"珲春", "code":"HUL"}, {"name":"邯郸东", "code":"HPP"}, {"name":"惠东", "code":"KDQ"}, {"name":"海东西", "code":"HDO"}, {"name":"洪洞西", "code":"HTV"}, {"name":"哈尔滨北", "code":"HTB"}, {"name":"合肥北城", "code":"COH"}, {"name":"合肥南", "code":"ENH"}, {"name":"黄冈", "code":"KGN"}, {"name":"黄冈东", "code":"KAN"}, {"name":"横沟桥东", "code":"HNN"}, {"name":"黄冈西", "code":"KXN"}, {"name":"洪河", "code":"HPB"}, {"name":"怀化南", "code":"KAQ"}, {"name":"黄河景区", "code":"HCF"}, {"name":"花湖", "code":"KHN"}, {"name":"怀集", "code":"FAQ"}, {"name":"河口北", "code":"HBM"}, {"name":"鲘门", "code":"KMQ"}, {"name":"虎门", "code":"IUQ"}, {"name":"侯马西", "code":"HPV"}, {"name":"衡南", "code":"HNG"}, {"name":"淮南东", "code":"HOH"}, {"name":"合浦", "code":"HVZ"}, {"name":"霍邱", "code":"FBH"}, {"name":"怀仁东", "code":"HFV"}, {"name":"华容东", "code":"HPN"}, {"name":"华容南", "code":"KRN"}, {"name":"黄石北", "code":"KSN"}, {"name":"黄山北", "code":"NYH"}, {"name":"贺胜桥东", "code":"HLN"}, {"name":"和硕", "code":"VUR"}, {"name":"花山南", "code":"KNN"}, {"name":"海阳北", "code":"HEK"}, {"name":"霍州东", "code":"HWV"}, {"name":"惠州南", "code":"KNQ"}, {"name":"泾川", "code":"JAJ"}, {"name":"旌德", "code":"NSH"}, {"name":"蛟河西", "code":"JOL"}, {"name":"军粮城北", "code":"JMP"}, {"name":"将乐", "code":"JLS"}, {"name":"贾鲁河", "code":"JLF"}, {"name":"即墨北", "code":"JVK"}, {"name":"建宁县北", "code":"JCS"}, {"name":"江宁", "code":"JJH"}, {"name":"建瓯西", "code":"JUS"}, {"name":"酒泉南", "code":"JNJ"}, {"name":"句容西", "code":"JWH"}, {"name":"建水", "code":"JSM"}, {"name":"界首市", "code":"JUN"}, {"name":"绩溪北", "code":"NRH"}, {"name":"介休东", "code":"JDV"}, {"name":"泾县", "code":"LOH"}, {"name":"进贤南", "code":"JXG"}, {"name":"嘉峪关南", "code":"JBJ"}, {"name":"晋中", "code":"JZV"}, {"name":"凯里南", "code":"QKW"}, {"name":"库伦", "code":"KLD"}, {"name":"葵潭", "code":"KTQ"}, {"name":"开阳", "code":"KVW"}, {"name":"来宾北", "code":"UCZ"}, {"name":"灵璧", "code":"GMH"}, {"name":"绿博园", "code":"LCF"}, {"name":"罗城", "code":"VCZ"}, {"name":"陵城", "code":"LGK"}, {"name":"龙洞堡", "code":"FVW"}, {"name":"乐都南", "code":"LVO"}, {"name":"娄底南", "code":"UOQ"}, {"name":"离堆公园", "code":"INW"}, {"name":"陆丰", "code":"LLQ"}, {"name":"禄丰南", "code":"LQM"}, {"name":"临汾西", "code":"LXV"}, {"name":"滦河", "code":"UDP"}, {"name":"漯河西", "code":"LBN"}, {"name":"罗江东", "code":"IKW"}, {"name":"利津南", "code":"LNK"}, {"name":"龙里北", "code":"KFW"}, {"name":"醴陵东", "code":"UKQ"}, {"name":"礼泉", "code":"LGY"}, {"name":"灵石东", "code":"UDV"}, {"name":"乐山", "code":"IVW"}, {"name":"龙市", "code":"LAG"}, {"name":"溧水", "code":"LDH"}, {"name":"莱西北", "code":"LBK"}, {"name":"溧阳", "code":"LEH"}, {"name":"临邑", "code":"LUK"}, {"name":"柳园南", "code":"LNR"}, {"name":"鹿寨北", "code":"LSZ"}, {"name":"临泽南", "code":"LDJ"}, {"name":"明港东", "code":"MDN"}, {"name":"民和南", "code":"MNO"}, {"name":"马兰", "code":"MLR"}, {"name":"民乐", "code":"MBJ"}, {"name":"玛纳斯", "code":"MSR"}, {"name":"牟平", "code":"MBK"}, {"name":"闽清北", "code":"MBS"}, {"name":"眉山东", "code":"IUW"}, {"name":"庙山", "code":"MSN"}, {"name":"门源", "code":"MYO"}, {"name":"蒙自北", "code":"MBM"}, {"name":"蒙自", "code":"MZM"}, {"name":"南城", "code":"NDG"}, {"name":"南昌西", "code":"NXG"}, {"name":"南芬北", "code":"NUT"}, {"name":"南丰", "code":"NFG"}, {"name":"南湖东", "code":"NDN"}, {"name":"南江", "code":"FIW"}, {"name":"南江口", "code":"NDQ"}, {"name":"南陵", "code":"LLH"}, {"name":"尼木", "code":"NMO"}, {"name":"南宁东", "code":"NFZ"}, {"name":"南平北", "code":"NBS"}, {"name":"南雄", "code":"NCQ"}, {"name":"南阳寨", "code":"NYF"}, {"name":"普安", "code":"PAN"}, {"name":"屏边", "code":"PBM"}, {"name":"普定", "code":"PGW"}, {"name":"平度", "code":"PAK"}, {"name":"普宁", "code":"PEQ"}, {"name":"平南南", "code":"PAZ"}, {"name":"彭山北", "code":"PPW"}, {"name":"坪上", "code":"PSK"}, {"name":"萍乡北", "code":"PBG"}, {"name":"平遥古城", "code":"PDV"}, {"name":"彭州", "code":"PMW"}, {"name":"青白江东", "code":"QFW"}, {"name":"青岛北", "code":"QHK"}, {"name":"祁东", "code":"QMQ"}, {"name":"前锋", "code":"QFB"}, {"name":"青莲", "code":"QEW"}, {"name":"齐齐哈尔南", "code":"QNB"}, {"name":"清水北", "code":"QEJ"}, {"name":"青神", "code":"QVW"}, {"name":"岐山", "code":"QAY"}, {"name":"庆盛", "code":"QSQ"}, {"name":"曲水县", "code":"QSO"}, {"name":"祁县东", "code":"QGV"}, {"name":"乾县", "code":"QBY"}, {"name":"祁阳", "code":"QWQ"}, {"name":"全州南", "code":"QNZ"}, {"name":"仁布", "code":"RUO"}, {"name":"荣成", "code":"RCK"}, {"name":"如东", "code":"RIH"}, {"name":"榕江", "code":"RVW"}, {"name":"日喀则", "code":"RKO"}, {"name":"饶平", "code":"RVQ"}, {"name":"宋城路", "code":"SFF"}, {"name":"三都县", "code":"KKW"}, {"name":"商河", "code":"SOK"}, {"name":"泗洪", "code":"GQH"}, {"name":"三江南", "code":"SWZ"}, {"name":"三井子", "code":"OJT"}, {"name":"双流机场", "code":"IPW"}, {"name":"双流西", "code":"IQW"}, {"name":"三明北", "code":"SHS"}, {"name":"山坡东", "code":"SBN"}, {"name":"沈丘", "code":"SQN"}, {"name":"鄯善北", "code":"SMR"}, {"name":"三水南", "code":"RNQ"}, {"name":"韶山南", "code":"INQ"}, {"name":"三穗", "code":"QHW"}, {"name":"汕尾", "code":"OGQ"}, {"name":"歙县北", "code":"NPH"}, {"name":"绍兴北", "code":"SLH"}, {"name":"始兴", "code":"IPQ"}, {"name":"泗县", "code":"GPH"}, {"name":"泗阳", "code":"MPH"}, {"name":"邵阳北", "code":"OVQ"}, {"name":"上虞北", "code":"SSH"}, {"name":"松原北", "code":"OCT"}, {"name":"山阴", "code":"SNV"}, {"name":"沈阳南", "code":"SOT"}, {"name":"深圳北", "code":"IOQ"}, {"name":"神州", "code":"SRQ"}, {"name":"深圳坪山", "code":"IFQ"}, {"name":"石嘴山", "code":"QQJ"}, {"name":"石柱县", "code":"OSW"}, {"name":"桃村北", "code":"TOK"}, {"name":"土地堂东", "code":"TTN"}, {"name":"太谷西", "code":"TIV"}, {"name":"吐哈", "code":"THR"}, {"name":"通海", "code":"TAM"}, {"name":"通化县", "code":"TXL"}, {"name":"吐鲁番北", "code":"TAR"}, {"name":"铜陵北", "code":"KXH"}, {"name":"泰宁", "code":"TNS"}, {"name":"铜仁南", "code":"TNW"}, {"name":"汤逊湖", "code":"THN"}, {"name":"藤县", "code":"TAZ"}, {"name":"太原南", "code":"TNV"}, {"name":"通远堡西", "code":"TST"}, {"name":"文登东", "code":"WGK"}, {"name":"五府山", "code":"WFG"}, {"name":"威虎岭北", "code":"WBL"}, {"name":"威海北", "code":"WHK"}, {"name":"五龙背东", "code":"WMT"}, {"name":"乌龙泉南", "code":"WFN"}, {"name":"五女山", "code":"WET"}, {"name":"无为", "code":"IIH"}, {"name":"瓦屋山", "code":"WAH"}, {"name":"闻喜西", "code":"WOV"}, {"name":"武夷山北", "code":"WBS"}, {"name":"武夷山东", "code":"WCS"}, {"name":"婺源", "code":"WYG"}, {"name":"武陟", "code":"WIF"}, {"name":"梧州南", "code":"WBZ"}, {"name":"兴安北", "code":"XDZ"}, {"name":"许昌东", "code":"XVF"}, {"name":"项城", "code":"ERN"}, {"name":"新都东", "code":"EWW"}, {"name":"西丰", "code":"XFT"}, {"name":"襄汾西", "code":"XTV"}, {"name":"孝感北", "code":"XJN"}, {"name":"新化南", "code":"EJQ"}, {"name":"新晃西", "code":"EWQ"}, {"name":"新津", "code":"IRW"}, {"name":"新津南", "code":"ITW"}, {"name":"咸宁东", "code":"XKN"}, {"name":"咸宁南", "code":"UNN"}, {"name":"溆浦南", "code":"EMQ"}, {"name":"协荣", "code":"ROO"}, {"name":"湘潭北", "code":"EDQ"}, {"name":"邢台东", "code":"EDP"}, {"name":"修武西", "code":"EXF"}, {"name":"新乡东", "code":"EGF"}, {"name":"新余北", "code":"XBG"}, {"name":"西阳村", "code":"XQF"}, {"name":"信阳东", "code":"OYN"}, {"name":"咸阳秦都", "code":"XOY"}, {"name":"仙游", "code":"XWS"}, {"name":"迎宾路", "code":"YFW"}, {"name":"运城北", "code":"ABV"}, {"name":"宜春", "code":"YEG"}, {"name":"岳池", "code":"AWW"}, {"name":"云浮东", "code":"IXQ"}, {"name":"永福南", "code":"YBZ"}, {"name":"雨格", "code":"VTM"}, {"name":"洋河", "code":"GTH"}, {"name":"永济北", "code":"AJV"}, {"name":"于家堡", "code":"YKP"}, {"name":"延吉西", "code":"YXL"}, {"name":"运粮河", "code":"YEF"}, {"name":"炎陵", "code":"YAG"}, {"name":"杨陵南", "code":"YEY"}, {"name":"郁南", "code":"YKQ"}, {"name":"永寿", "code":"ASY"}, {"name":"玉山南", "code":"YGG"}, {"name":"永泰", "code":"YTS"}, {"name":"鹰潭北", "code":"YKG"}, {"name":"烟台南", "code":"YLK"}, {"name":"尤溪", "code":"YXS"}, {"name":"云霄", "code":"YBS"}, {"name":"宜兴", "code":"YUH"}, {"name":"阳信", "code":"YVK"}, {"name":"应县", "code":"YZV"}, {"name":"攸县南", "code":"YXG"}, {"name":"余姚北", "code":"CTH"}, {"name":"诏安", "code":"ZDS"}, {"name":"正定机场", "code":"ZHP"}, {"name":"纸坊东", "code":"ZMN"}, {"name":"昭化", "code":"ZHW"}, {"name":"芷江", "code":"ZPQ"}, {"name":"织金", "code":"IZW"}, {"name":"左岭", "code":"ZSN"}, {"name":"驻马店西", "code":"ZLN"}, {"name":"漳浦", "code":"ZCS"}, {"name":"肇庆东", "code":"FCQ"}, {"name":"庄桥", "code":"ZQH"}, {"name":"钟山西", "code":"ZAZ"}, {"name":"张掖西", "code":"ZEJ"}, {"name":"涿州东", "code":"ZAP"}, {"name":"卓资东", "code":"ZDC"}, {"name":"郑州东", "code":"ZAF"}, {"name":"胜芳", "code":"SUP"}, {"name":"隆安东", "code":"IDZ"}, {"name":"缙云西", "code":"PYH"}, {"name":"邵东", "code":"FIQ"} ], "error_code":0 }'; +$data='@bjb|北京北|VAP|beijingbei|bjb|0@bjd|北京东|BOP|beijingdong|bjd|1@bji|北京|BJP|beijing|bj|2@bjn|北京南|VNP|beijingnan|bjn|3@bjx|北京西|BXP|beijingxi|bjx|4@gzn|广州南|IZQ|guangzhounan|gzn|5@cqb|重庆北|CUW|chongqingbei|cqb|6@cqi|重庆|CQW|chongqing|cq|7@cqn|重庆南|CRW|chongqingnan|cqn|8@gzd|广州东|GGQ|guangzhoudong|gzd|9@sha|上海|SHH|shanghai|sh|10@shn|上海南|SNH|shanghainan|shn|11@shq|上海虹桥|AOH|shanghaihongqiao|shhq|12@shx|上海西|SXH|shanghaixi|shx|13@tjb|天津北|TBP|tianjinbei|tjb|14@tji|天津|TJP|tianjin|tj|15@tjn|天津南|TIP|tianjinnan|tjn|16@tjx|天津西|TXP|tianjinxi|tjx|17@cch|长春|CCT|changchun|cc|18@ccn|长春南|CET|changchunnan|ccn|19@ccx|长春西|CRT|changchunxi|ccx|20@cdd|成都东|ICW|chengdudong|cdd|21@cdn|成都南|CNW|chengdunan|cdn|22@cdu|成都|CDW|chengdu|cd|23@csh|长沙|CSQ|changsha|cs|24@csn|长沙南|CWQ|changshanan|csn|25@fzh|福州|FZS|fuzhou|fz|26@fzn|福州南|FYS|fuzhounan|fzn|27@gya|贵阳|GIW|guiyang|gy|28@gzh|广州|GZQ|guangzhou|gz|29@gzx|广州西|GXQ|guangzhouxi|gzx|30@heb|哈尔滨|HBB|haerbin|heb|31@hed|哈尔滨东|VBB|haerbindong|hebd|32@hex|哈尔滨西|VAB|haerbinxi|hebx|33@hfe|合肥|HFH|hefei|hf|34@hfx|合肥西|HTH|hefeixi|hfx|35@hhd|呼和浩特东|NDC|huhehaotedong|hhhtd|36@hht|呼和浩特|HHC|huhehaote|hhht|37@hkd|海 口东|KEQ|haikoudong|hkd|38@hkd|海口东|HMQ|haikoudong|hkd|39@hko|海口|VUQ|haikou|hk|40@hzd|杭州东|HGH|hangzhoudong|hzd|41@hzh|杭州|HZH|hangzhou|hz|42@hzn|杭州南|XHH|hangzhounan|hzn|43@jna|济南|JNK|jinan|jn|44@jnd|济南东|JAK|jinandong|jnd|45@jnx|济南西|JGK|jinanxi|jnx|46@kmi|昆明|KMM|kunming|km|47@kmx|昆明西|KXM|kunmingxi|kmx|48@lsa|拉萨|LSO|lasa|ls|49@lzd|兰州东|LVJ|lanzhoudong|lzd|50@lzh|兰州|LZJ|lanzhou|lz|51@lzx|兰州西|LAJ|lanzhouxi|lzx|52@nch|南昌|NCG|nanchang|nc|53@nji|南京|NJH|nanjing|nj|54@njn|南京南|NKH|nanjingnan|njn|55@nni|南宁|NNZ|nanning|nn|56@sjb|石家庄北|VVP|shijiazhuangbei|sjzb|57@sjz|石家庄|SJP|shijiazhuang|sjz|58@sya|沈阳|SYT|shenyang|sy|59@syb|沈阳北|SBT|shenyangbei|syb|60@syd|沈阳东|SDT|shenyangdong|syd|61@tyb|太原北|TBV|taiyuanbei|tyb|62@tyd|太原东|TDV|taiyuandong|tyd|63@tyu|太原|TYV|taiyuan|ty|64@wha|武汉|WHN|wuhan|wh|65@wjx|王家营西|KNM|wangjiayingxi|wjyx|66@wln|乌鲁木齐南|WMR|wulumuqinan|wlmqn|67@xab|西安北|EAY|xianbei|xab|68@xan|西安|XAY|xian|xa|69@xan|西安南|CAY|xiannan|xan|70@xni|西宁|XNO|xining|xn|71@ych|银川|YIJ|yinchuan|yc|72@zzh|郑州|ZZF|zhengzhou|zz|73@aes|阿尔山|ART|aershan|aes|74@aka|安康|AKY|ankang|ak|75@aks|阿克苏|ASR|akesu|aks|76@alh|阿里河|AHX|alihe|alh|77@alk|阿拉山口|AKR|alashankou|alsk|78@api|安平|APT|anping|ap|79@aqi|安庆|AQH|anqing|aq|80@ash|安顺|ASW|anshun|as|81@ash|鞍山|AST|anshan|as|82@aya|安阳|AYF|anyang|ay|83@ban|北安|BAB|beian|ba|84@bbu|蚌埠|BBH|bengbu|bb|85@bch|白城|BCT|baicheng|bc|86@bha|北海|BHZ|beihai|bh|87@bhe|白河|BEL|baihe|bh|88@bji|白涧|BAP|baijian|bj|89@bji|宝鸡|BJY|baoji|bj|90@bji|滨江|BJB|binjiang|bj|91@bkt|博克图|BKX|boketu|bkt|92@bse|百色|BIZ|baise|bs|93@bss|白山市|HJL|baishanshi|bss|94@bta|北台|BTT|beitai|bt|95@btd|包头东|BDC|baotoudong|btd|96@bto|包头|BTC|baotou|bt|97@bts|北屯市|BXR|beitunshi|bts|98@bxi|本溪|BXT|benxi|bx|99@byb|白云鄂博|BEC|baiyunebo|byeb|100@byx|白银西|BXJ|baiyinxi|byx|101@bzh|亳州|BZH|bozhou|bz|102@cbi|赤壁|CBN|chibi|cb|103@cde|常德|VGQ|changde|cd|104@cde|承德|CDP|chengde|cd|105@cdi|长甸|CDT|changdian|cd|106@cfe|赤峰|CFD|chifeng|cf|107@cli|茶陵|CDG|chaling|cl|108@cna|苍南|CEH|cangnan|cn|109@cpi|昌平|CPP|changping|cp|110@cre|崇仁|CRG|chongren|cr|111@ctu|昌图|CTT|changtu|ct|112@ctz|长汀镇|CDB|changtingzhen|ctz|113@cxi|曹县|CXK|caoxian|cx|114@cxi|楚雄|COM|chuxiong|cx|115@cxt|陈相屯|CXT|chenxiangtun|cxt|116@czb|长治北|CBF|changzhibei|czb|117@czh|池州|IYH|chizhou|cz|118@czh|长征|CZJ|changzheng|cz|119@czh|常州|CZH|changzhou|cz|120@czh|郴州|CZQ|chenzhou|cz|121@czh|长治|CZF|changzhi|cz|122@czh|沧州|COP|cangzhou|cz|123@czu|崇左|CZZ|chongzuo|cz|124@dab|大安北|RNT|daanbei|dab|125@dch|大成|DCT|dacheng|dc|126@ddo|丹东|DUT|dandong|dd|127@dfh|东方红|DFB|dongfanghong|dfh|128@dgd|东莞东|DMQ|dongguandong|dgd|129@dhs|大虎山|DHD|dahushan|dhs|130@dhu|敦煌|DHJ|dunhuang|dh|131@dhu|敦化|DHL|dunhua|dh|132@dhu|德惠|DHT|dehui|dh|133@djc|东京城|DJB|dongjingcheng|djc|134@dji|大涧|DFP|dajian|dj|135@djy|都江堰|DDW|dujiangyan|djy|136@dlb|大连北|DFT|dalianbei|dlb|137@dli|大理|DKM|dali|dl|138@dli|大连|DLT|dalian|dl|139@dna|定南|DNG|dingnan|dn|140@dqi|大庆|DZX|daqing|dq|141@dsh|东胜|DOC|dongsheng|ds|142@dsq|大石桥|DQT|dashiqiao|dsq|143@dto|大同|DTV|datong|dt|144@dyi|东营|DPK|dongying|dy|145@dys|大杨树|DUX|dayangshu|dys|146@dyu|都匀|RYW|duyun|dy|147@dzh|邓州|DOF|dengzhou|dz|148@dzh|达州|RXW|dazhou|dz|149@dzh|德州|DZP|dezhou|dz|150@ejn|额济纳|EJC|ejina|ejn|151@eli|二连|RLC|erlian|el|152@esh|恩施|ESN|enshi|es|153@fdi|福鼎|FES|fuding|fd|154@fhc|凤凰机场|FJQ|fenghuangjichang|fhjc|155@fld|风陵渡|FLV|fenglingdu|fld|156@fli|涪陵|FLW|fuling|fl|157@flj|富拉尔基|FRX|fulaerji|flej|158@fsb|抚顺北|FET|fushunbei|fsb|159@fsh|佛山|FSQ|foshan|fs|160@fxn|阜新南|FXD|fuxinnan|fxn|161@fya|阜阳|FYH|fuyang|fy|162@gem|格尔木|GRO|geermu|gem|163@gha|广汉|GHW|guanghan|gh|164@gji|古交|GJV|gujiao|gj|165@glb|桂林北|GBZ|guilinbei|glb|166@gli|古莲|GRX|gulian|gl|167@gli|桂林|GLZ|guilin|gl|168@gsh|固始|GXN|gushi|gs|169@gsh|广水|GSN|guangshui|gs|170@gta|干塘|GNJ|gantang|gt|171@gyu|广元|GYW|guangyuan|gy|172@gzb|广州北|GBQ|guangzhoubei|gzb|173@gzh|赣州|GZG|ganzhou|gz|174@gzl|公主岭|GLT|gongzhuling|gzl|175@gzn|公主岭南|GBT|gongzhulingnan|gzln|176@han|淮安|AUH|huaian|ha|177@hbe|淮北|HRH|huaibei|hb|178@hbe|鹤北|HMB|hebei|hb|179@hbi|淮滨|HVN|huaibin|hb|180@hbi|河边|HBV|hebian|hb|181@hch|潢川|KCN|huangchuan|hc|182@hch|韩城|HCY|hancheng|hc|183@hda|邯郸|HDP|handan|hd|184@hdz|横道河子|HDB|hengdaohezi|hdhz|185@hga|鹤岗|HGB|hegang|hg|186@hgt|皇姑屯|HTT|huanggutun|hgt|187@hgu|红果|HEM|hongguo|hg|188@hhe|黑河|HJB|heihe|hh|189@hhu|怀化|HHQ|huaihua|hh|190@hko|汉口|HKN|hankou|hk|191@hld|葫芦岛|HLD|huludao|hld|192@hle|海拉尔|HRX|hailaer|hle|193@hll|霍林郭勒|HWD|huolinguole|hlgl|194@hlu|海伦|HLB|hailun|hl|195@hma|侯马|HMV|houma|hm|196@hmi|哈密|HMR|hami|hm|197@hna|淮南|HAH|huainan|hn|198@hna|桦南|HNB|huanan|hn|199@hnx|海宁西|EUH|hainingxi|hnx|200@hqi|鹤庆|HQM|heqing|hq|201@hrb|怀柔北|HBP|huairoubei|hrb|202@hro|怀柔|HRP|huairou|hr|203@hsd|黄石东|OSN|huangshidong|hsd|204@hsh|华山|HSY|huashan|hs|205@hsh|黄山|HKH|huangshan|hs|206@hsh|黄石|HSN|huangshi|hs|207@hsh|衡水|HSP|hengshui|hs|208@hya|衡阳|HYQ|hengyang|hy|209@hze|菏泽|HIK|heze|hz|210@hzh|贺州|HXZ|hezhou|hz|211@hzh|汉中|HOY|hanzhong|hz|212@hzh|惠州|HCQ|huizhou|hz|213@jan|吉安|VAG|jian|ja|214@jan|集安|JAL|jian|ja|215@jbc|江边村|JBG|jiangbiancun|jbc|216@jch|晋城|JCF|jincheng|jc|217@jcj|金城江|JJZ|jinchengjiang|jcj|218@jdz|景德镇|JCG|jingdezhen|jdz|219@jfe|嘉峰|JFF|jiafeng|jf|220@jgq|加格达奇|JGX|jiagedaqi|jgdq|221@jgs|井冈山|JGG|jinggangshan|jgs|222@jhe|蛟河|JHL|jiaohe|jh|223@jhn|金华南|RNH|jinhuanan|jhn|224@jhu|金华|JBH|jinhua|jh|225@jji|九江|JJG|jiujiang|jj|226@jli|吉林|JLL|jilin|jl|227@jme|荆门|JMN|jingmen|jm|228@jms|佳木斯|JMB|jiamusi|jms|229@jni|济宁|JIK|jining|jn|230@jnn|集宁南|JAC|jiningnan|jnn|231@jqu|酒泉|JQJ|jiuquan|jq|232@jsh|江山|JUH|jiangshan|js|233@jsh|吉首|JIQ|jishou|js|234@jta|九台|JTL|jiutai|jt|235@jts|镜铁山|JVJ|jingtieshan|jts|236@jxi|鸡西|JXB|jixi|jx|237@jxi|蓟县|JKP|jixian|jx|238@jxx|绩溪县|JRH|jixixian|jxx|239@jyg|嘉峪关|JGJ|jiayuguan|jyg|240@jyo|江油|JFW|jiangyou|jy|241@jzh|锦州|JZD|jinzhou|jz|242@jzh|金州|JZT|jinzhou|jz|243@kel|库尔勒|KLR|kuerle|kel|244@kfe|开封|KFF|kaifeng|kf|245@kla|岢岚|KLV|kelan|kl|246@kli|凯里|KLW|kaili|kl|247@ksh|喀什|KSR|kashi|ks|248@ksn|昆山南|KNH|kunshannan|ksn|249@ktu|奎屯|KTR|kuitun|kt|250@kyu|开原|KYT|kaiyuan|ky|251@lan|六安|UAH|luan|la|252@lba|灵宝|LBF|lingbao|lb|253@lcg|芦潮港|UCH|luchaogang|lcg|254@lch|隆昌|LCW|longchang|lc|255@lch|陆川|LKZ|luchuan|lc|256@lch|利川|LCN|lichuan|lc|257@lch|临川|LCG|linchuan|lc|258@lch|潞城|UTP|lucheng|lc|259@lda|鹿道|LDL|ludao|ld|260@ldi|娄底|LDQ|loudi|ld|261@lfe|临汾|LFV|linfen|lf|262@lgz|良各庄|LGP|lianggezhuang|lgz|263@lhe|临河|LHC|linhe|lh|264@lhe|漯河|LON|luohe|lh|265@lhu|绿化|LWJ|lvhua|lh|266@lhu|隆化|UHP|longhua|lh|267@lji|丽江|LHM|lijiang|lj|268@lji|临江|LQL|linjiang|lj|269@lji|龙井|LJL|longjing|lj|270@lli|吕梁|LHV|lvliang|ll|271@lli|醴陵|LLG|liling|ll|272@lln|柳林南|LKV|liulinnan|lln|273@lpi|滦平|UPP|luanping|lp|274@lps|六盘水|UMW|liupanshui|lps|275@lqi|灵丘|LVV|lingqiu|lq|276@lsh|旅顺|LST|lvshun|ls|277@lxi|兰溪|LWH|lanxi|lx|278@lxi|陇西|LXJ|longxi|lx|279@lxi|澧县|LEQ|lixian|lx|280@lxi|临西|UEP|linxi|lx|281@lya|龙岩|LYS|longyan|ly|282@lya|耒阳|LYQ|leiyang|ly|283@lya|洛阳|LYF|luoyang|ly|284@lyd|连云港东|UKH|lianyungangdong|lygd|285@lyd|洛阳东|LDF|luoyangdong|lyd|286@lyi|临沂|LVK|linyi|ly|287@lym|洛阳龙门|LLF|luoyanglongmen|lylm|288@lyu|柳园|DHR|liuyuan|ly|289@lyu|凌源|LYD|lingyuan|ly|290@lyu|辽源|LYL|liaoyuan|ly|291@lzh|立志|LZX|lizhi|lz|292@lzh|柳州|LZZ|liuzhou|lz|293@lzh|辽中|LZD|liaozhong|lz|294@mch|麻城|MCN|macheng|mc|295@mdh|免渡河|MDX|mianduhe|mdh|296@mdj|牡丹江|MDB|mudanjiang|mdj|297@meg|莫尔道嘎|MRX|moerdaoga|medg|298@mgu|明光|MGH|mingguang|mg|299@mgu|满归|MHX|mangui|mg|300@mhe|漠河|MVX|mohe|mh|301@mmi|茂名|MDQ|maoming|mm|302@mmx|茂名西|MMZ|maomingxi|mmx|303@msh|密山|MSB|mishan|ms|304@msj|马三家|MJT|masanjia|msj|305@mwe|麻尾|VAW|mawei|mw|306@mya|绵阳|MYW|mianyang|my|307@mzh|梅州|MOQ|meizhou|mz|308@mzl|满洲里|MLX|manzhouli|mzl|309@nbd|宁波东|NVH|ningbodong|nbd|310@nbo|宁波|NGH|ningbo|nb|311@nch|南岔|NCB|nancha|nc|312@nch|南充|NCW|nanchong|nc|313@nda|南丹|NDZ|nandan|nd|314@ndm|南大庙|NMP|nandamiao|ndm|315@nfe|南芬|NFT|nanfen|nf|316@nhe|讷河|NHX|nehe|nh|317@nji|嫩江|NGX|nenjiang|nj|318@nji|内江|NJW|neijiang|nj|319@npi|南平|NPS|nanping|np|320@nto|南通|NUH|nantong|nt|321@nya|南阳|NFF|nanyang|ny|322@nzs|碾子山|NZX|nianzishan|nzs|323@pds|平顶山|PEN|pingdingshan|pds|324@pji|盘锦|PVD|panjin|pj|325@pli|平凉|PIJ|pingliang|pl|326@pln|平凉南|POJ|pingliangnan|pln|327@pqu|平泉|PQP|pingquan|pq|328@psh|坪石|PSQ|pingshi|ps|329@pxi|萍乡|PXG|pingxiang|px|330@pxi|凭祥|PXZ|pingxiang|px|331@pxx|郫县西|PCW|pixianxi|pxx|332@pzh|攀枝花|PRW|panzhihua|pzh|333@qch|蕲春|QRN|qichun|qc|334@qcs|青城山|QSW|qingchengshan|qcs|335@qda|青岛|QDK|qingdao|qd|336@qhc|清河城|QYP|qinghecheng|qhc|337@qji|曲靖|QJM|qujing|qj|338@qji|黔江|QNW|qianjiang|qj|339@qjz|前进镇|QEB|qianjinzhen|qjz|340@qqe|齐齐哈尔|QHX|qiqihaer|qqhe|341@qth|七台河|QTB|qitaihe|qth|342@qxi|沁县|QVV|qinxian|qx|343@qzd|泉州东|QRS|quanzhoudong|qzd|344@qzh|衢州|QEH|quzhou|qz|345@qzh|泉州|QYS|quanzhou|qz|346@ran|融安|RAZ|rongan|ra|347@rjg|汝箕沟|RQJ|rujigou|rqg|348@rji|瑞金|RJG|ruijin|rj|349@rzh|日照|RZK|rizhao|rz|350@scp|双城堡|SCB|shuangchengpu|scb|351@sfh|绥芬河|SFB|suifenhe|sfh|352@sgd|韶关东|SGQ|shaoguandong|sgd|353@shg|山海关|SHD|shanhaiguan|shg|354@shu|绥化|SHB|suihua|sh|355@sjf|三间房|SFX|sanjianfang|sjf|356@sjt|苏家屯|SXT|sujiatun|sjt|357@sla|舒兰|SLL|shulan|sl|358@smi|三明|SMS|sanming|sm|359@smu|神木|OMY|shenmu|sm|360@smx|三门峡|SMF|sanmenxia|smx|361@sna|商南|ONY|shangnan|sn|362@sni|遂宁|NIW|suining|sn|363@spi|四平|SPT|siping|sp|364@sqi|商丘|SQF|shangqiu|sq|365@sra|上饶|SRG|shangrao|sr|366@ssh|韶山|SSQ|shaoshan|ss|367@sso|宿松|OAH|susong|ss|368@sto|汕头|OTQ|shantou|st|369@swu|邵武|SWS|shaowu|sw|370@sxi|涉县|OEP|shexian|sx|371@sya|三亚|SEQ|sanya|sy|372@sya|三 亚|JUQ|sanya|sy|373@sya|邵阳|SYQ|shaoyang|sy|374@sya|十堰|SNN|shiyan|sy|375@sys|双鸭山|SSB|shuangyashan|sys|376@syu|松原|VYT|songyuan|sy|377@szh|苏州|SZH|suzhou|sz|378@szh|深圳|SZQ|shenzhen|sz|379@szh|宿州|OXH|suzhou|sz|380@szh|随州|SZN|suizhou|sz|381@szh|朔州|SUV|shuozhou|sz|382@szx|深圳西|OSQ|shenzhenxi|szx|383@tba|塘豹|TBQ|tangbao|tb|384@teq|塔尔气|TVX|taerqi|teq|385@tgu|潼关|TGY|tongguan|tg|386@tgu|塘沽|TGP|tanggu|tg|387@the|塔河|TXX|tahe|th|388@thu|通化|THL|tonghua|th|389@tla|泰来|TLX|tailai|tl|390@tlf|吐鲁番|TFR|tulufan|tlf|391@tli|通辽|TLD|tongliao|tl|392@tli|铁岭|TLT|tieling|tl|393@tlz|陶赖昭|TPT|taolaizhao|tlz|394@tme|图们|TML|tumen|tm|395@tre|铜仁|RDQ|tongren|tr|396@tsb|唐山北|FUP|tangshanbei|tsb|397@tsf|田师府|TFT|tianshifu|tsf|398@tsh|泰山|TAK|taishan|ts|399@tsh|唐山|TSP|tangshan|ts|400@tsh|天水|TSJ|tianshui|ts|401@typ|通远堡|TYT|tongyuanpu|tyb|402@tys|太阳升|TQT|taiyangsheng|tys|403@tzh|泰州|UTH|taizhou|tz|404@tzi|桐梓|TZW|tongzi|tz|405@tzx|通州西|TAP|tongzhouxi|tzx|406@wch|五常|WCB|wuchang|wc|407@wch|武昌|WCN|wuchang|wc|408@wfd|瓦房店|WDT|wafangdian|wfd|409@wha|威海|WKK|weihai|wh|410@whu|芜湖|WHH|wuhu|wh|411@whx|乌海西|WXC|wuhaixi|whx|412@wjt|吴家屯|WJT|wujiatun|wjt|413@wlo|武隆|WLW|wulong|wl|414@wlt|乌兰浩特|WWT|wulanhaote|wlht|415@wna|渭南|WNY|weinan|wn|416@wsh|威舍|WSM|weishe|ws|417@wts|歪头山|WIT|waitoushan|wts|418@wwe|武威|WUJ|wuwei|ww|419@wwn|武威南|WWJ|wuweinan|wwn|420@wxi|无锡|WXH|wuxi|wx|421@wxi|乌西|WXR|wuxi|wx|422@wyl|乌伊岭|WPB|wuyiling|wyl|423@wys|武夷山|WAS|wuyishan|wys|424@wyu|万源|WYY|wanyuan|wy|425@wzh|万州|WYW|wanzhou|wz|426@wzh|梧州|WZZ|wuzhou|wz|427@wzh|温州|RZH|wenzhou|wz|428@wzn|温州南|VRH|wenzhounan|wzn|429@xch|西昌|ECW|xichang|xc|430@xch|许昌|XCF|xuchang|xc|431@xcn|西昌南|ENW|xichangnan|xcn|432@xfa|香坊|XFB|xiangfang|xf|433@xga|轩岗|XGV|xuangang|xg|434@xgu|兴国|EUG|xingguo|xg|435@xha|宣汉|XHY|xuanhan|xh|436@xhu|新会|EFQ|xinhui|xh|437@xhu|新晃|XLQ|xinhuang|xh|438@xlt|锡林浩特|XTC|xilinhaote|xlht|439@xlx|兴隆县|EXP|xinglongxian|xlx|440@xmb|厦门北|XKS|xiamenbei|xmb|441@xme|厦门|XMS|xiamen|xm|442@xmq|厦门高崎|XBS|xiamengaoqi|xmgq|443@xsh|小市|XST|xiaoshi|xs|444@xsh|秀山|ETW|xiushan|xs|445@xta|向塘|XTG|xiangtang|xt|446@xwe|宣威|XWM|xuanwei|xw|447@xxi|新乡|XXF|xinxiang|xx|448@xya|信阳|XUN|xinyang|xy|449@xya|咸阳|XYY|xianyang|xy|450@xya|襄阳|XFN|xiangyang|xy|451@xyc|熊岳城|XYT|xiongyuecheng|xyc|452@xyi|新沂|VIH|xinyi|xy|453@xyi|兴义|XRZ|xingyi|xy|454@xyu|新余|XUG|xinyu|xy|455@xzh|徐州|XCH|xuzhou|xz|456@yan|延安|YWY|yanan|ya|457@ybi|宜宾|YBW|yibin|yb|458@ybn|亚布力南|YWB|yabulinan|ybln|459@ybs|叶柏寿|YBD|yebaishou|ybs|460@ycd|宜昌东|HAN|yichangdong|ycd|461@ych|永川|YCW|yongchuan|yc|462@ych|盐城|AFH|yancheng|yc|463@ych|宜昌|YCN|yichang|yc|464@ych|运城|YNV|yuncheng|yc|465@ych|伊春|YCB|yichun|yc|466@yci|榆次|YCV|yuci|yc|467@ycu|杨村|YBP|yangcun|yc|468@ycx|宜春西|YCG|yichunxi|ycx|469@yes|伊尔施|YET|yiershi|yes|470@yga|燕岗|YGW|yangang|yg|471@yji|永济|YIV|yongji|yj|472@yji|延吉|YJL|yanji|yj|473@yko|营口|YKT|yingkou|yk|474@yks|牙克石|YKX|yakeshi|yks|475@yli|阎良|YNY|yanliang|yl|476@yli|玉林|YLZ|yulin|yl|477@yli|榆林|ALY|yulin|yl|478@ylw|亚龙湾|TWQ|yalongwan|ylw|479@ymp|一面坡|YPB|yimianpo|ymp|480@yni|伊宁|YMR|yining|yn|481@ypg|阳平关|YAY|yangpingguan|ypg|482@ypi|玉屏|YZW|yuping|yp|483@ypi|原平|YPV|yuanping|yp|484@yqi|延庆|YNP|yanqing|yq|485@yqq|阳泉曲|YYV|yangquanqu|yqq|486@yqu|玉泉|YQB|yuquan|yq|487@yqu|阳泉|AQP|yangquan|yq|488@ysh|营山|NUW|yingshan|ys|489@ysh|玉山|YNG|yushan|ys|490@ysh|燕山|AOP|yanshan|ys|491@ysh|榆树|YRT|yushu|ys|492@yta|鹰潭|YTG|yingtan|yt|493@yta|烟台|YAK|yantai|yt|494@yth|伊图里河|YEX|yitulihe|ytlh|495@ytx|玉田县|ATP|yutianxian|ytx|496@ywu|义乌|YWH|yiwu|yw|497@yxi|阳新|YON|yangxin|yx|498@yxi|义县|YXD|yixian|yx|499@yya|益阳|AEQ|yiyang|yy|500@yya|岳阳|YYQ|yueyang|yy|501@yzh|崖州|YUQ|yazhou|yz|502@yzh|永州|AOQ|yongzhou|yz|503@yzh|扬州|YLH|yangzhou|yz|504@zbo|淄博|ZBK|zibo|zb|505@zcd|镇城底|ZDV|zhenchengdi|zcd|506@zgo|自贡|ZGW|zigong|zg|507@zha|珠海|ZHQ|zhuhai|zh|508@zhb|珠海北|ZIQ|zhuhaibei|zhb|509@zji|湛江|ZJZ|zhanjiang|zj|510@zji|镇江|ZJH|zhenjiang|zj|511@zjj|张家界|DIQ|zhangjiajie|zjj|512@zjk|张家口|ZKP|zhangjiakou|zjk|513@zjn|张家口南|ZMP|zhangjiakounan|zjkn|514@zko|周口|ZKN|zhoukou|zk|515@zlm|哲里木|ZLC|zhelimu|zlm|516@zlt|扎兰屯|ZTX|zhalantun|zlt|517@zmd|驻马店|ZDN|zhumadian|zmd|518@zqi|肇庆|ZVQ|zhaoqing|zq|519@zsz|周水子|ZIT|zhoushuizi|zsz|520@zto|昭通|ZDW|zhaotong|zt|521@zwe|中卫|ZWJ|zhongwei|zw|522@zya|资阳|ZYW|ziyang|zy|523@zyi|遵义|ZIW|zunyi|zy|524@zzh|枣庄|ZEK|zaozhuang|zz|525@zzh|资中|ZZW|zizhong|zz|526@zzh|株洲|ZZQ|zhuzhou|zz|527@zzx|枣庄西|ZFK|zaozhuangxi|zzx|528@aax|昂昂溪|AAX|angangxi|aax|529@ach|阿城|ACB|acheng|ac|530@ada|安达|ADX|anda|ad|531@ade|安德|ARW|ande|ad|532@adi|安定|ADP|anding|ad|533@agu|安广|AGT|anguang|ag|534@ahe|艾河|AHP|aihe|ah|535@ahu|安化|PKQ|anhua|ah|536@ajc|艾家村|AJJ|aijiacun|ajc|537@aji|鳌江|ARH|aojiang|aj|538@aji|安家|AJB|anjia|aj|539@aji|阿金|AJD|ajin|aj|540@akt|阿克陶|AER|aketao|akt|541@aky|安口窑|AYY|ankouyao|aky|542@alg|敖力布告|ALD|aolibugao|albg|543@alo|安龙|AUZ|anlong|al|544@als|阿龙山|ASX|alongshan|als|545@alu|安陆|ALN|anlu|al|546@ame|阿木尔|JTX|amuer|ame|547@anz|阿南庄|AZM|ananzhuang|anz|548@aqx|安庆西|APH|anqingxi|aqx|549@asx|鞍山西|AXT|anshanxi|asx|550@ata|安塘|ATV|antang|at|551@atb|安亭北|ASH|antingbei|atb|552@ats|阿图什|ATR|atushi|ats|553@atu|安图|ATL|antu|at|554@axi|安溪|AXS|anxi|ax|555@bao|博鳌|BWQ|boao|ba|556@bbe|北碚|BPW|beibei|bb|557@bbg|白壁关|BGV|baibiguan|bbg|558@bbn|蚌埠南|BMH|bengbunan|bbn|559@bch|巴楚|BCR|bachu|bc|560@bch|板城|BUP|bancheng|bc|561@bdh|北戴河|BEP|beidaihe|bdh|562@bdi|保定|BDP|baoding|bd|563@bdi|宝坻|BPP|baodi|bd|564@bdl|八达岭|ILP|badaling|bdl|565@bdo|巴东|BNN|badong|bd|566@bgu|柏果|BGM|baiguo|bg|567@bha|布海|BUT|buhai|bh|568@bhd|白河东|BIY|baihedong|bhd|569@bho|贲红|BVC|benhong|bh|570@bhs|宝华山|BWH|baohuashan|bhs|571@bhx|白河县|BEY|baihexian|bhx|572@bjg|白芨沟|BJJ|baijigou|bjg|573@bjg|碧鸡关|BJM|bijiguan|bjg|574@bji|北滘|IBQ|beijiao|b|575@bji|碧江|BLQ|bijiang|bj|576@bjp|白鸡坡|BBM|baijipo|bjp|577@bjs|笔架山|BSB|bijiashan|bjs|578@bjt|八角台|BTD|bajiaotai|bjt|579@bka|保康|BKD|baokang|bk|580@bkp|白奎堡|BKB|baikuipu|bkb|581@bla|白狼|BAT|bailang|bl|582@bla|百浪|BRZ|bailang|bl|583@ble|博乐|BOR|bole|bl|584@blg|宝拉格|BQC|baolage|blg|585@bli|巴林|BLX|balin|bl|586@bli|宝林|BNB|baolin|bl|587@bli|北流|BOZ|beiliu|bl|588@bli|勃利|BLB|boli|bl|589@blk|布列开|BLR|buliekai|blk|590@bls|宝龙山|BND|baolongshan|bls|591@blx|百里峡|AAP|bailixia|blx|592@bmc|八面城|BMD|bamiancheng|bmc|593@bmq|班猫箐|BNM|banmaoqing|bmj|594@bmt|八面通|BMB|bamiantong|bmt|595@bmz|北马圈子|BRP|beimaquanzi|bmqz|596@bpn|北票南|RPD|beipiaonan|bpn|597@bqi|白旗|BQP|baiqi|bq|598@bql|宝泉岭|BQB|baoquanling|bql|599@bqu|白泉|BQL|baiquan|bq|600@bsh|巴山|BAY|bashan|bs|601@bsh|白沙|BSW|baisha|bs|602@bsj|白水江|BSY|baishuijiang|bsj|603@bsp|白沙坡|BPM|baishapo|bsp|604@bss|白石山|BAL|baishishan|bss|605@bsz|白水镇|BUM|baishuizhen|bsz|606@btd|包头 东|FDC|baotoudong|btd|607@bti|坂田|BTQ|bantian|bt|608@bto|泊头|BZP|botou|bt|609@btu|北屯|BYP|beitun|bt|610@bxh|本溪湖|BHT|benxihu|bxh|611@bxi|博兴|BXK|boxing|bx|612@bxt|八仙筒|VXD|baxiantong|bxt|613@byg|白音察干|BYC|baiyinchagan|bycg|614@byh|背荫河|BYB|beiyinhe|byh|615@byi|北营|BIV|beiying|by|616@byl|巴彦高勒|BAC|bayangaole|bygl|617@byl|白音他拉|BID|baiyintala|bytl|618@byq|鲅鱼圈|BYT|bayuquan|byq|619@bys|白银市|BNJ|baiyinshi|bys|620@bys|白音胡硕|BCD|baiyinhushuo|byhs|621@bzh|巴中|IEW|bazhong|bz|622@bzh|霸州|RMP|bazhou|bz|623@bzh|北宅|BVP|beizhai|bz|624@cbb|赤壁北|CIN|chibibei|cbb|625@cbg|查布嘎|CBC|chabuga|cbg|626@cch|长城|CEJ|changcheng|cc|627@cch|长冲|CCM|changchong|cc|628@cdd|承德东|CCP|chengdedong|cdd|629@cfx|赤峰西|CID|chifengxi|cfx|630@cga|嵯岗|CAX|cuogang|cg|631@cga|柴岗|CGT|chaigang|cg|632@cge|长葛|CEF|changge|cg|633@cgp|柴沟堡|CGV|chaigoupu|cgb|634@cgu|城固|CGY|chenggu|cg|635@cgy|陈官营|CAJ|chenguanying|cgy|636@cgz|成高子|CZB|chenggaozi|cgz|637@cha|草海|WBW|caohai|ch|638@che|柴河|CHB|chaihe|ch|639@che|册亨|CHZ|ceheng|ch|640@chk|草河口|CKT|caohekou|chk|641@chk|崔黄口|CHP|cuihuangkou|chk|642@chu|巢湖|CIH|chaohu|ch|643@cjg|蔡家沟|CJT|caijiagou|cjg|644@cjh|成吉思汗|CJX|chengjisihan|cjsh|645@cji|岔江|CAM|chajiang|cj|646@cjp|蔡家坡|CJY|caijiapo|cjp|647@cle|昌乐|CLK|changle|cl|648@clg|超梁沟|CYP|chaolianggou|clg|649@cli|慈利|CUQ|cili|cl|650@cli|昌黎|CLP|changli|cl|651@clz|长岭子|CLT|changlingzi|clz|652@cmi|晨明|CMB|chenming|cm|653@cno|长农|CNJ|changnong|cn|654@cpb|昌平北|VBP|changpingbei|cpb|655@cpi|常平|DAQ|changping|cp|656@cpl|长坡岭|CPM|changpoling|cpl|657@cqi|辰清|CQB|chenqing|cq|658@csh|蔡山|CON|caishan|cs|659@csh|楚山|CSB|chushan|cs|660@csh|长寿|EFW|changshou|cs|661@csh|磁山|CSP|cishan|cs|662@csh|苍石|CST|cangshi|cs|663@csh|草市|CSL|caoshi|cs|664@csq|察素齐|CSC|chasuqi|csq|665@cst|长山屯|CVT|changshantun|cst|666@cti|长汀|CES|changting|ct|667@ctx|昌图西|CPT|changtuxi|ctx|668@cwa|春湾|CQQ|chunwan|cw|669@cxi|磁县|CIP|cixian|cx|670@cxi|岑溪|CNZ|cenxi|cx|671@cxi|辰溪|CXQ|chenxi|cx|672@cxi|磁西|CRP|cixi|cx|673@cxn|长兴南|CFH|changxingnan|cxn|674@cya|磁窑|CYK|ciyao|cy|675@cya|朝阳|CYD|chaoyang|cy|676@cya|春阳|CAL|chunyang|cy|677@cya|城阳|CEK|chengyang|cy|678@cyc|创业村|CEX|chuangyecun|cyc|679@cyc|朝阳川|CYL|chaoyangchuan|cyc|680@cyd|朝阳地|CDD|chaoyangdi|cyd|681@cyu|长垣|CYF|changyuan|cy|682@cyz|朝阳镇|CZL|chaoyangzhen|cyz|683@czb|滁州北|CUH|chuzhoubei|czb|684@czb|常州北|ESH|changzhoubei|czb|685@czh|滁州|CXH|chuzhou|cz|686@czh|潮州|CKQ|chaozhou|cz|687@czh|常庄|CVK|changzhuang|cz|688@czl|曹子里|CFP|caozili|czl|689@czw|车转湾|CWM|chezhuanwan|czw|690@czx|郴州西|ICQ|chenzhouxi|czx|691@czx|沧州西|CBP|cangzhouxi|czx|692@dan|德安|DAG|dean|da|693@dan|大安|RAT|daan|da|694@dba|大坝|DBJ|daba|db|695@dba|大板|DBC|daban|db|696@dba|大巴|DBD|daba|db|697@dba|到保|RBT|daobao|db|698@dbi|定边|DYJ|dingbian|db|699@dbj|东边井|DBB|dongbianjing|dbj|700@dbs|德伯斯|RDT|debosi|dbs|701@dcg|打柴沟|DGJ|dachaigou|dcg|702@dch|德昌|DVW|dechang|dc|703@dda|滴道|DDB|didao|dd|704@ddg|大磴沟|DKJ|dadenggou|ddg|705@ded|刀尔登|DRD|daoerdeng|ded|706@dee|得耳布尔|DRX|deerbuer|debe|707@dfa|东方|UFQ|dongfang|df|708@dfe|丹凤|DGY|danfeng|df|709@dfe|东丰|DIL|dongfeng|df|710@dge|都格|DMM|duge|dg|711@dgt|大官屯|DTT|daguantun|dgt|712@dgu|大关|RGW|daguan|dg|713@dgu|东光|DGP|dongguang|dg|714@dha|东海|DHB|donghai|dh|715@dhc|大灰厂|DHP|dahuichang|dhc|716@dhq|大红旗|DQD|dahongqi|dhq|717@dht|大禾塘|SOQ|shaodong|sd|718@dhx|东海县|DQH|donghaixian|dhx|719@dhx|德惠西|DXT|dehuixi|dhx|720@djg|达家沟|DJT|dajiagou|djg|721@dji|东津|DKB|dongjin|dj|722@dji|杜家|DJL|dujia|dj|723@dkt|大口屯|DKP|dakoutun|dkt|724@dla|东来|RVD|donglai|dl|725@dlh|德令哈|DHO|delingha|dlh|726@dlh|大陆号|DLC|daluhao|dlh|727@dli|带岭|DLB|dailing|dl|728@dli|大林|DLD|dalin|dl|729@dlq|达拉特旗|DIC|dalateqi|dltq|730@dlt|独立屯|DTX|dulitun|dlt|731@dlu|豆罗|DLV|douluo|dl|732@dlx|达拉特西|DNC|dalatexi|dltx|733@dmc|东明村|DMD|dongmingcun|dmc|734@dmh|洞庙河|DEP|dongmiaohe|dmh|735@dmx|东明县|DNF|dongmingxian|dmx|736@dni|大拟|DNZ|dani|dn|737@dpf|大平房|DPD|dapingfang|dpf|738@dps|大盘石|RPP|dapanshi|dps|739@dpu|大埔|DPI|dapu|dp|740@dpu|大堡|DVT|dapu|db|741@dqd|大庆东|LFX|daqingdong|dqd|742@dqh|大其拉哈|DQX|daqilaha|dqlh|743@dqi|道清|DML|daoqing|dq|744@dqs|对青山|DQB|duiqingshan|dqs|745@dqx|德清西|MOH|deqingxi|dqx|746@dqx|大庆西|RHX|daqingxi|dqx|747@dsh|东升|DRQ|dongsheng|ds|748@dsh|砀山|DKH|dangshan|ds|749@dsh|独山|RWW|dushan|ds|750@dsh|登沙河|DWT|dengshahe|dsh|751@dsp|读书铺|DPM|dushupu|dsp|752@dst|大石头|DSL|dashitou|dst|753@dsx|东胜西|DYC|dongshengxi|dsx|754@dsz|大石寨|RZT|dashizhai|dsz|755@dta|东台|DBH|dongtai|dt|756@dta|定陶|DQK|dingtao|dt|757@dta|灯塔|DGT|dengta|dt|758@dtb|大田边|DBM|datianbian|dtb|759@dth|东通化|DTL|dongtonghua|dth|760@dtu|丹徒|RUH|dantu|dt|761@dtu|大屯|DNT|datun|dt|762@dwa|东湾|DRJ|dongwan|dw|763@dwk|大武口|DFJ|dawukou|dwk|764@dwp|低窝铺|DWJ|diwopu|dwp|765@dwt|大王滩|DZZ|dawangtan|dwt|766@dwz|大湾子|DFM|dawanzi|dwz|767@dxg|大兴沟|DXL|daxinggou|dxg|768@dxi|大兴|DXX|daxing|dx|769@dxi|定西|DSJ|dingxi|dx|770@dxi|甸心|DXM|dianxin|dx|771@dxi|东乡|DXG|dongxiang|dx|772@dxi|代县|DKV|daixian|dx|773@dxi|定襄|DXV|dingxiang|dx|774@dxu|东戌|RXP|dongxu|dx|775@dxz|东辛庄|DXD|dongxinzhuang|dxz|776@dya|丹阳|DYH|danyang|dy|777@dya|德阳|DYW|deyang|dy|778@dya|大雁|DYX|dayan|dy|779@dya|当阳|DYN|dangyang|dy|780@dyb|丹阳北|EXH|danyangbei|dyb|781@dyd|大英东|IAW|dayingdong|dyd|782@dyd|东淤地|DBV|dongyudi|dyd|783@dyi|大营|DYV|daying|dy|784@dyu|定远|EWH|dingyuan|dy|785@dyu|岱岳|RYV|daiyue|dy|786@dyu|大元|DYZ|dayuan|dy|787@dyz|大营镇|DJP|dayingzhen|dyz|788@dyz|大营子|DZD|dayingzi|dyz|789@dzc|大战场|DTJ|dazhanchang|dzc|790@dzd|德州东|DIP|dezhoudong|dzd|791@dzh|东至|DCH|dongzhi|dz|792@dzh|低庄|DVQ|dizhuang|dz|793@dzh|东镇|DNV|dongzhen|dz|794@dzh|道州|DFZ|daozhou|dz|795@dzh|东庄|DZV|dongzhuang|dz|796@dzh|兑镇|DWV|duizhen|dz|797@dzh|豆庄|ROP|douzhuang|dz|798@dzh|定州|DXP|dingzhou|dz|799@dzy|大竹园|DZY|dazhuyuan|dzy|800@dzz|大杖子|DAP|dazhangzi|dzz|801@dzz|豆张庄|RZP|douzhangzhuang|dzz|802@ebi|峨边|EBW|ebian|eb|803@edm|二道沟门|RDP|erdaogoumen|edgm|804@edw|二道湾|RDX|erdaowan|edw|805@ees|鄂尔多斯|EEC|eerduosi|eeds|806@elo|二龙|RLD|erlong|el|807@elt|二龙山屯|ELA|erlongshantun|elst|808@eme|峨眉|EMW|emei|em|809@emh|二密河|RML|ermihe|emh|810@eyi|二营|RYJ|erying|ey|811@ezh|鄂州|ECN|ezhou|ez|812@fan|福安|FAS|fuan|fa|813@fch|丰城|FCG|fengcheng|fc|814@fcn|丰城南|FNG|fengchengnan|fcn|815@fdo|肥东|FIH|feidong|fd|816@fer|发耳|FEM|faer|fe|817@fha|富海|FHX|fuhai|fh|818@fha|福海|FHR|fuhai|fh|819@fhc|凤凰城|FHT|fenghuangcheng|fhc|820@fhe|汾河|FEV|fenhe|fh|821@fhu|奉化|FHH|fenghua|fh|822@fji|富锦|FIB|fujin|fj|823@fjt|范家屯|FTT|fanjiatun|fjt|824@flq|福利区|FLJ|fuliqu|flq|825@flt|福利屯|FTB|fulitun|flt|826@flz|丰乐镇|FZB|fenglezhen|flz|827@fna|阜南|FNH|funan|fn|828@fni|阜宁|AKH|funing|fn|829@fni|抚宁|FNP|funing|fn|830@fqi|福清|FQS|fuqing|fq|831@fqu|福泉|VMW|fuquan|fq|832@fsc|丰水村|FSJ|fengshuicun|fsc|833@fsh|丰顺|FUQ|fengshun|fs|834@fsh|繁峙|FSV|fanshi|fs|835@fsh|抚顺|FST|fushun|fs|836@fsk|福山口|FKP|fushankou|fsk|837@fsu|扶绥|FSZ|fusui|fs|838@ftu|冯屯|FTX|fengtun|ft|839@fty|浮图峪|FYP|futuyu|fty|840@fxd|富县东|FDY|fuxiandong|fxd|841@fxi|凤县|FXY|fengxian|fx|842@fxi|富县|FEY|fuxian|fx|843@fxi|费县|FXK|feixian|fx|844@fya|凤阳|FUH|fengyang|fy|845@fya|汾阳|FAV|fenyang|fy|846@fyb|扶余北|FBT|fuyubei|fyb|847@fyi|分宜|FYG|fenyi|fy|848@fyu|富源|FYM|fuyuan|fy|849@fyu|扶余|FYT|fuyu|fy|850@fyu|富裕|FYX|fuyu|fy|851@fzb|抚州北|FBG|fuzhoubei|fzb|852@fzh|凤州|FZY|fengzhou|fz|853@fzh|丰镇|FZC|fengzhen|fz|854@fzh|范镇|VZK|fanzhen|fz|855@gan|固安|GFP|guan|ga|856@gan|广安|VJW|guangan|ga|857@gbd|高碑店|GBP|gaobeidian|gbd|858@gbz|沟帮子|GBD|goubangzi|gbz|859@gcd|甘草店|GDJ|gancaodian|gcd|860@gch|谷城|GCN|gucheng|gc|861@gch|藁城|GEP|gaocheng|gc|862@gcu|高村|GCV|gaocun|gc|863@gcz|古城镇|GZB|guchengzhen|gcz|864@gde|广德|GRH|guangde|gd|865@gdi|贵定|GTW|guiding|gd|866@gdn|贵定南|IDW|guidingnan|gdn|867@gdo|古东|GDV|gudong|gd|868@gga|贵港|GGZ|guigang|gg|869@gga|官高|GVP|guangao|gg|870@ggm|葛根庙|GGT|gegenmiao|ggm|871@ggo|干沟|GGL|gangou|gg|872@ggu|甘谷|GGJ|gangu|gg|873@ggz|高各庄|GGP|gaogezhuang|ggz|874@ghe|甘河|GAX|ganhe|gh|875@ghe|根河|GEX|genhe|gh|876@gjd|郭家店|GDT|guojiadian|gjd|877@gjz|孤家子|GKT|gujiazi|gjz|878@gla|古浪|GLJ|gulang|gl|879@gla|皋兰|GEJ|gaolan|gl|880@glf|高楼房|GFM|gaoloufang|glf|881@glh|归流河|GHT|guiliuhe|glh|882@gli|关林|GLF|guanlin|gl|883@glu|甘洛|VOW|ganluo|gl|884@glz|郭磊庄|GLP|guoleizhuang|glz|885@gmi|高密|GMK|gaomi|gm|886@gmz|公庙子|GMC|gongmiaozi|gmz|887@gnh|工农湖|GRT|gongnonghu|gnh|888@gnn|广宁寺南|GNT|guangningsinan|gns|889@gnw|广南卫|GNM|guangnanwei|gnw|890@gpi|高平|GPF|gaoping|gp|891@gqb|甘泉北|GEY|ganquanbei|gqb|892@gqc|共青城|GAG|gongqingcheng|gqc|893@gqk|甘旗卡|GQD|ganqika|gqk|894@gqu|甘泉|GQY|ganquan|gq|895@gqz|高桥镇|GZD|gaoqiaozhen|gqz|896@gsh|灌水|GST|guanshui|gs|897@gsh|赶水|GSW|ganshui|gs|898@gsk|孤山口|GSP|gushankou|gsk|899@gso|果松|GSL|guosong|gs|900@gsz|高山子|GSD|gaoshanzi|gsz|901@gsz|嘎什甸子|GXD|gashidianzi|gsdz|902@gta|高台|GTJ|gaotai|gt|903@gta|高滩|GAY|gaotan|gt|904@gti|古田|GTS|gutian|gt|905@gti|官厅|GTP|guanting|gt|906@gtx|官厅西|KEP|guantingxi|gtx|907@gxi|贵溪|GXG|guixi|gx|908@gya|涡阳|GYH|guoyang|gy|909@gyi|巩义|GXF|gongyi|gy|910@gyi|高邑|GIP|gaoyi|gy|911@gyn|巩义南|GYF|gongyinan|gyn|912@gyn|广元南|GAW|guangyuannan|gyn|913@gyu|固原|GUJ|guyuan|gy|914@gyu|菇园|GYL|guyuan|gy|915@gyz|公营子|GYD|gongyingzi|gyz|916@gze|光泽|GZS|guangze|gz|917@gzh|古镇|GNQ|guzhen|gz|918@gzh|固镇|GEH|guzhen|gz|919@gzh|虢镇|GZY|guozhen|gz|920@gzh|瓜州|GZJ|guazhou|gz|921@gzh|高州|GSQ|gaozhou|gz|922@gzh|盖州|GXT|gaizhou|gz|923@gzj|官字井|GOT|guanzijing|gzj|924@gzp|革镇堡|GZT|gezhenpu|gzb|925@gzs|冠豸山|GSS|guanzhaishan|gzs|926@gzx|盖州西|GAT|gaizhouxi|gzx|927@han|淮安南|AMH|huaiannan|han|928@han|红安|HWN|hongan|ha|929@hax|海安县|HIH|haianxian|hax|930@hax|红安西|VXN|honganxi|hax|931@hba|黄柏|HBL|huangbai|hb|932@hbe|海北|HEB|haibei|hb|933@hbi|鹤壁|HAF|hebi|hb|934@hcb|会昌北|XEG|huichangbei|hcb|935@hch|华城|VCQ|huacheng|hc|936@hch|河唇|HCZ|hechun|hc|937@hch|汉川|HCN|hanchuan|hc|938@hch|海城|HCT|haicheng|hc|939@hch|合川|WKW|hechuan|hc|940@hct|黑冲滩|HCJ|heichongtan|hct|941@hcu|黄村|HCP|huangcun|hc|942@hcx|海城西|HXT|haichengxi|hcx|943@hde|化德|HGC|huade|hd|944@hdo|洪洞|HDV|hongtong|hd|945@hes|霍尔果斯|HFR|huoerguosi|hegs|946@hfe|横峰|HFG|hengfeng|hf|947@hfw|韩府湾|HXJ|hanfuwan|hfw|948@hgu|汉沽|HGP|hangu|hg|949@hgy|黄瓜园|HYM|huangguayuan|hgy|950@hgz|红光镇|IGW|hongguangzhen|hgz|951@hhe|浑河|HHT|hunhe|hh|952@hhg|红花沟|VHD|honghuagou|hhg|953@hht|黄花筒|HUD|huanghuatong|hht|954@hjd|贺家店|HJJ|hejiadian|hjd|955@hji|和静|HJR|hejing|hj|956@hji|红江|HFM|hongjiang|hj|957@hji|黑井|HIM|heijing|hj|958@hji|获嘉|HJF|huojia|hj|959@hji|河津|HJV|hejin|hj|960@hji|涵江|HJS|hanjiang|hj|961@hji|华家|HJT|huajia|hj|962@hjq|杭锦后旗|HDC|hangjinhouqi|hjhq|963@hjx|河间西|HXP|hejianxi|hjx|964@hjz|花家庄|HJM|huajiazhuang|hjz|965@hkn|河口南|HKJ|hekounan|hkn|966@hko|黄口|KOH|huangkou|hk|967@hko|湖口|HKG|hukou|hk|968@hla|呼兰|HUB|hulan|hl|969@hlb|葫芦岛北|HPD|huludaobei|hldb|970@hlh|浩良河|HHB|haolianghe|hlh|971@hlh|哈拉海|HIT|halahai|hlh|972@hli|鹤立|HOB|heli|hl|973@hli|桦林|HIB|hualin|hl|974@hli|黄陵|ULY|huangling|hl|975@hli|海林|HRB|hailin|hl|976@hli|虎林|VLB|hulin|hl|977@hli|寒岭|HAT|hanling|hl|978@hlo|和龙|HLL|helong|hl|979@hlo|海龙|HIL|hailong|hl|980@hls|哈拉苏|HAX|halasu|hls|981@hlt|呼鲁斯太|VTJ|hulusitai|hlst|982@hlz|火连寨|HLT|huolianzhai|hlz|983@hme|黄梅|VEH|huangmei|hm|984@hmy|韩麻营|HYP|hanmaying|hmy|985@hnh|黄泥河|HHL|huangnihe|hnh|986@hni|海宁|HNH|haining|hn|987@hno|惠农|HMJ|huinong|hn|988@hpi|和平|VAQ|heping|hp|989@hpz|花棚子|HZM|huapengzi|hpz|990@hqi|花桥|VQH|huaqiao|hq|991@hqi|宏庆|HEY|hongqing|hq|992@hre|怀仁|HRV|huairen|hr|993@hro|华容|HRN|huarong|hr|994@hsb|华山北|HDY|huashanbei|hsb|995@hsd|黄松甸|HDL|huangsongdian|hsd|996@hsg|和什托洛盖|VSR|heshituoluogai|hstlg|997@hsh|红山|VSB|hongshan|hs|998@hsh|汉寿|VSQ|hanshou|hs|999@hsh|衡山|HSQ|hengshan|hs|1000@hsh|黑水|HOT|heishui|hs|1001@hsh|惠山|VCH|huishan|hs|1002@hsh|虎什哈|HHP|hushiha|hsh|1003@hsp|红寺堡|HSJ|hongsipu|hsb|1004@hst|虎石台|HUT|hushitai|hst|1005@hsw|海石湾|HSO|haishiwan|hsw|1006@hsx|衡山西|HEQ|hengshanxi|hsx|1007@hsx|红砂岘|VSJ|hongshaxian|hsj|1008@hta|黑台|HQB|heitai|ht|1009@hta|桓台|VTK|huantai|ht|1010@hti|和田|VTR|hetian|ht|1011@hto|会同|VTQ|huitong|ht|1012@htz|海坨子|HZT|haituozi|htz|1013@hwa|黑旺|HWK|heiwang|hw|1014@hwa|海湾|RWH|haiwan|hw|1015@hxi|红星|VXB|hongxing|hx|1016@hxi|徽县|HYY|huixian|hx|1017@hxl|红兴隆|VHB|hongxinglong|hxl|1018@hxt|换新天|VTB|huanxintian|hxt|1019@hxt|红岘台|HTJ|hongxiantai|hxt|1020@hya|红彦|VIX|hongyan|hy|1021@hya|合阳|HAY|heyang|hy|1022@hya|海阳|HYK|haiyang|hy|1023@hyd|衡阳东|HVQ|hengyangdong|hyd|1024@hyi|华蓥|HUW|huaying|hy|1025@hyi|汉阴|HQY|hanyin|hy|1026@hyt|黄羊滩|HGJ|huangyangtan|hyt|1027@hyu|汉源|WHW|hanyuan|hy|1028@hyu|河源|VIQ|heyuan|hy|1029@hyu|花园|HUN|huayuan|hy|1030@hyu|湟源|HNO|huangyuan|hy|1031@hyz|黄羊镇|HYJ|huangyangzhen|hyz|1032@hzh|湖州|VZH|huzhou|hz|1033@hzh|化州|HZZ|huazhou|hz|1034@hzh|黄州|VON|huangzhou|hz|1035@hzh|霍州|HZV|huozhou|hz|1036@hzx|惠州西|VXQ|huizhouxi|hzx|1037@jba|巨宝|JRT|jubao|jb|1038@jbi|靖边|JIY|jingbian|jb|1039@jbt|金宝屯|JBD|jinbaotun|jbt|1040@jcb|晋城北|JEF|jinchengbei|jcb|1041@jch|金昌|JCJ|jinchang|jc|1042@jch|鄄城|JCK|juancheng|jc|1043@jch|交城|JNV|jiaocheng|jc|1044@jch|建昌|JFD|jianchang|jc|1045@jde|峻德|JDB|junde|jd|1046@jdi|井店|JFP|jingdian|jd|1047@jdo|鸡东|JOB|jidong|jd|1048@jdu|江都|UDH|jiangdu|jd|1049@jgs|鸡冠山|JST|jiguanshan|jgs|1050@jgt|金沟屯|VGP|jingoutun|jgt|1051@jha|静海|JHP|jinghai|jh|1052@jhe|金河|JHX|jinhe|jh|1053@jhe|锦河|JHB|jinhe|jh|1054@jhe|精河|JHR|jinghe|jh|1055@jhn|精河南|JIR|jinghenan|jhn|1056@jhu|江华|JHZ|jianghua|jh|1057@jhu|建湖|AJH|jianhu|jh|1058@jjg|纪家沟|VJD|jijiagou|jjg|1059@jji|晋江|JJS|jinjiang|jj|1060@jji|姜家|JJB|jiangjia|jj|1061@jji|江津|JJW|jiangjin|jj|1062@jke|金坑|JKT|jinkeng|jk|1063@jli|芨岭|JLJ|jiling|jl|1064@jmc|金马村|JMM|jinmacun|jmc|1065@jme|江门|JWQ|jiangmen|jm|1066@jme|角美|JES|jiaomei|jm|1067@jna|莒南|JOK|junan|jn|1068@jna|井南|JNP|jingnan|jn|1069@jou|建瓯|JVS|jianou|jo|1070@jpe|经棚|JPC|jingpeng|jp|1071@jqi|江桥|JQX|jiangqiao|jq|1072@jsa|九三|SSX|jiusan|js|1073@jsb|金山北|EGH|jinshanbei|jsb|1074@jsh|嘉善|JSH|jiashan|js|1075@jsh|京山|JCN|jingshan|js|1076@jsh|建始|JRN|jianshi|js|1077@jsh|稷山|JVV|jishan|js|1078@jsh|吉舒|JSL|jishu|js|1079@jsh|建设|JET|jianshe|js|1080@jsh|甲山|JOP|jiashan|js|1081@jsj|建三江|JIB|jiansanjiang|jsj|1082@jsn|嘉善南|EAH|jiashannan|jsn|1083@jst|金山屯|JTB|jinshantun|jst|1084@jst|江所田|JOM|jiangsuotian|jst|1085@jta|景泰|JTJ|jingtai|jt|1086@jtn|九台南|JNL|jiutainan|jtn|1087@jwe|吉文|JWX|jiwen|jw|1088@jxi|进贤|JUG|jinxian|jx|1089@jxi|莒县|JKK|juxian|jx|1090@jxi|嘉祥|JUK|jiaxiang|jx|1091@jxi|介休|JXV|jiexiu|jx|1092@jxi|嘉兴|JXH|jiaxing|jx|1093@jxi|井陉|JJP|jingxing|jx|1094@jxn|嘉兴南|EPH|jiaxingnan|jxn|1095@jxz|夹心子|JXT|jiaxinzi|jxz|1096@jya|姜堰|UEH|jiangyan|jy|1097@jya|揭阳|JRQ|jieyang|jy|1098@jya|建阳|JYS|jianyang|jy|1099@jya|简阳|JYW|jianyang|jy|1100@jye|巨野|JYK|juye|jy|1101@jyo|江永|JYZ|jiangyong|jy|1102@jyu|缙云|JYH|jinyun|jy|1103@jyu|靖远|JYJ|jingyuan|jy|1104@jyu|江源|SZL|jiangyuan|jy|1105@jyu|济源|JYF|jiyuan|jy|1106@jyx|靖远西|JXJ|jingyuanxi|jyx|1107@jzb|胶州北|JZK|jiaozhoubei|jzb|1108@jzd|焦作东|WEF|jiaozuodong|jzd|1109@jzh|金寨|JZH|jinzhai|jz|1110@jzh|靖州|JEQ|jingzhou|jz|1111@jzh|荆州|JBN|jingzhou|jz|1112@jzh|胶州|JXK|jiaozhou|jz|1113@jzh|晋州|JXP|jinzhou|jz|1114@jzn|锦州南|JOD|jinzhounan|jzn|1115@jzu|焦作|JOF|jiaozuo|jz|1116@jzw|旧庄窝|JVP|jiuzhuangwo|jzw|1117@jzz|金杖子|JYD|jinzhangzi|jzz|1118@kan|开安|KAT|kaian|ka|1119@kch|库车|KCR|kuche|kc|1120@kch|康城|KCP|kangcheng|kc|1121@kde|库都尔|KDX|kuduer|kde|1122@kdi|宽甸|KDT|kuandian|kd|1123@kdo|克东|KOB|kedong|kd|1124@kdz|昆独仑召|KDC|kundulunzhao|kdlz|1125@kji|开江|KAW|kaijiang|kj|1126@kjj|康金井|KJB|kangjinjing|kjj|1127@klq|喀喇其|KQX|kalaqi|klq|1128@klu|开鲁|KLC|kailu|kl|1129@kly|克拉玛依|KHR|kelamayi|klmy|1130@kqi|口前|KQL|kouqian|kq|1131@ksh|昆山|KSH|kunshan|ks|1132@ksh|奎山|KAB|kuishan|ks|1133@ksh|克山|KSB|keshan|ks|1134@kto|开通|KTT|kaitong|kt|1135@kxl|康熙岭|KXZ|kangxiling|kxl|1136@kya|昆阳|KAM|kunyang|ky|1137@kyh|克一河|KHX|keyihe|kyh|1138@kyx|开原西|KXT|kaiyuanxi|kyx|1139@kzh|康庄|KZP|kangzhuang|kz|1140@lbi|来宾|UBZ|laibin|lb|1141@lbi|老边|LLT|laobian|lb|1142@lbx|灵宝西|LPF|lingbaoxi|lbx|1143@lch|龙川|LUQ|longchuan|lc|1144@lch|乐昌|LCQ|lechang|lc|1145@lch|黎城|UCP|licheng|lc|1146@lch|聊城|UCK|liaocheng|lc|1147@lcu|蓝村|LCK|lancun|lc|1148@lda|两当|LDY|liangdang|ld|1149@ldo|林东|LRC|lindong|ld|1150@ldu|乐都|LDO|ledu|ld|1151@ldx|梁底下|LDP|liangdixia|ldx|1152@ldz|六道河子|LVP|liudaohezi|ldhz|1153@lfa|鲁番|LVM|lufan|lf|1154@lfa|廊坊|LJP|langfang|lf|1155@lfa|落垡|LOP|luofa|lf|1156@lfb|廊坊北|LFP|langfangbei|lfb|1157@lfu|老府|UFD|laofu|lf|1158@lga|兰岗|LNB|langang|lg|1159@lgd|龙骨甸|LGM|longgudian|lgd|1160@lgo|芦沟|LOM|lugou|lg|1161@lgo|龙沟|LGJ|longgou|lg|1162@lgu|拉古|LGB|lagu|lg|1163@lha|临海|UFH|linhai|lh|1164@lha|林海|LXX|linhai|lh|1165@lha|拉哈|LHX|laha|lh|1166@lha|凌海|JID|linghai|lh|1167@lhe|柳河|LNL|liuhe|lh|1168@lhe|六合|KLH|liuhe|lh|1169@lhu|龙华|LHP|longhua|lh|1170@lhy|滦河沿|UNP|luanheyan|lhy|1171@lhz|六合镇|LEX|liuhezhen|lhz|1172@ljd|亮甲店|LRT|liangjiadian|ljd|1173@ljd|刘家店|UDT|liujiadian|ljd|1174@ljh|刘家河|LVT|liujiahe|ljh|1175@lji|连江|LKS|lianjiang|lj|1176@lji|庐江|UJH|lujiang|lj|1177@lji|李家|LJB|lijia|lj|1178@lji|罗江|LJW|luojiang|lj|1179@lji|廉江|LJZ|lianjiang|lj|1180@lji|两家|UJT|liangjia|lj|1181@lji|龙江|LJX|longjiang|lj|1182@lji|龙嘉|UJL|longjia|lj|1183@ljk|莲江口|LHB|lianjiangkou|ljk|1184@ljl|蔺家楼|ULK|linjialou|ljl|1185@ljp|李家坪|LIJ|lijiaping|ljp|1186@lka|兰考|LKF|lankao|lk|1187@lko|林口|LKB|linkou|lk|1188@lkp|路口铺|LKQ|lukoupu|lkp|1189@lla|老莱|LAX|laolai|ll|1190@lli|拉林|LAB|lalin|ll|1191@lli|陆良|LRM|luliang|ll|1192@lli|龙里|LLW|longli|ll|1193@lli|临澧|LWQ|linli|ll|1194@lli|兰棱|LLB|lanling|ll|1195@lli|零陵|UWZ|lingling|ll|1196@llo|卢龙|UAP|lulong|ll|1197@lmd|喇嘛甸|LMX|lamadian|lmd|1198@lmd|里木店|LMB|limudian|lmd|1199@lme|洛门|LMJ|luomen|lm|1200@lna|龙南|UNG|longnan|ln|1201@lpi|梁平|UQW|liangping|lp|1202@lpi|罗平|LPM|luoping|lp|1203@lpl|落坡岭|LPP|luopoling|lpl|1204@lps|六盘山|UPJ|liupanshan|lps|1205@lps|乐平市|LPG|lepingshi|lps|1206@lqi|临清|UQK|linqing|lq|1207@lqs|龙泉寺|UQJ|longquansi|lqs|1208@lsb|乐山北|UTW|leshanbei|ls|1209@lsc|乐善村|LUM|leshancun|lsc|1210@lsd|冷水江东|UDQ|lengshuijiangdong|lsjd|1211@lsg|连山关|LGT|lianshanguan|lsg|1212@lsg|流水沟|USP|liushuigou|lsg|1213@lsh|陵水|LIQ|lingshui|ls|1214@lsh|丽水|USH|lishui|ls|1215@lsh|罗山|LRN|luoshan|ls|1216@lsh|鲁山|LAF|lushan|ls|1217@lsh|梁山|LMK|liangshan|ls|1218@lsh|灵石|LSV|lingshi|ls|1219@lsh|露水河|LUL|lushuihe|lsh|1220@lsh|庐山|LSG|lushan|ls|1221@lsp|林盛堡|LBT|linshengpu|lsp|1222@lst|柳树屯|LSD|liushutun|lst|1223@lsz|龙山镇|LAS|longshanzhen|lsz|1224@lsz|梨树镇|LSB|lishuzhen|lsz|1225@lsz|李石寨|LET|lishizhai|lsz|1226@lta|黎塘|LTZ|litang|lt|1227@lta|轮台|LAR|luntai|lt|1228@lta|芦台|LTP|lutai|lt|1229@ltb|龙塘坝|LBM|longtangba|ltb|1230@ltu|濑湍|LVZ|laituan|lt|1231@ltx|骆驼巷|LTJ|luotuoxiang|ltx|1232@lwa|李旺|VLJ|liwang|lw|1233@lwd|莱芜东|LWK|laiwudong|lwd|1234@lws|狼尾山|LRJ|langweishan|lws|1235@lwu|灵武|LNJ|lingwu|lw|1236@lwx|莱芜西|UXK|laiwuxi|lwx|1237@lxi|朗乡|LXB|langxiang|lx|1238@lxi|陇县|LXY|longxian|lx|1239@lxi|临湘|LXQ|linxiang|lx|1240@lxi|芦溪|LUG|luxi|lx|1241@lxi|莱西|LXK|laixi|lx|1242@lxi|林西|LXC|linxi|lx|1243@lxi|滦县|UXP|luanxian|lx|1244@lya|略阳|LYY|lueyang|ly|1245@lya|莱阳|LYK|laiyang|ly|1246@lya|辽阳|LYT|liaoyang|ly|1247@lyb|临沂北|UYK|linyibei|lyb|1248@lyd|凌源东|LDD|lingyuandong|lyd|1249@lyg|连云港|UIH|lianyungang|lyg|1250@lyi|临颍|LNF|linying|ly|1251@lyi|老营|LXL|laoying|ly|1252@lyo|龙游|LMH|longyou|ly|1253@lyu|罗源|LVS|luoyuan|ly|1254@lyu|林源|LYX|linyuan|ly|1255@lyu|涟源|LAQ|lianyuan|ly|1256@lyu|涞源|LYP|laiyuan|ly|1257@lyx|耒阳西|LPQ|leiyangxi|lyx|1258@lze|临泽|LEJ|linze|lz|1259@lzg|龙爪沟|LZT|longzhuagou|lzg|1260@lzh|雷州|UAQ|leizhou|lz|1261@lzh|六枝|LIW|liuzhi|lz|1262@lzh|鹿寨|LIZ|luzhai|lz|1263@lzh|来舟|LZS|laizhou|lz|1264@lzh|龙镇|LZA|longzhen|lz|1265@lzh|拉鲊|LEM|lazha|lz|1266@lzq|兰州新区|LQJ|lanzhouxinqu|lzxq|1267@mas|马鞍山|MAH|maanshan|mas|1268@mba|毛坝|MBY|maoba|mb|1269@mbg|毛坝关|MGY|maobaguan|mbg|1270@mcb|麻城北|MBN|machengbei|mcb|1271@mch|渑池|MCF|mianchi|mc|1272@mch|明城|MCL|mingcheng|mc|1273@mch|庙城|MAP|miaocheng|mc|1274@mcn|渑池南|MNF|mianchinan|mcn|1275@mcp|茅草坪|KPM|maocaoping|mcp|1276@mdh|猛洞河|MUQ|mengdonghe|mdh|1277@mds|磨刀石|MOB|modaoshi|mds|1278@mdu|弥渡|MDF|midu|md|1279@mes|帽儿山|MRB|maoershan|mes|1280@mga|明港|MGN|minggang|mg|1281@mhk|梅河口|MHL|meihekou|mhk|1282@mhu|马皇|MHZ|mahuang|mh|1283@mjg|孟家岗|MGB|mengjiagang|mjg|1284@mla|美兰|MHQ|meilan|ml|1285@mld|汨罗东|MQQ|miluodong|mld|1286@mlh|马莲河|MHB|malianhe|mlh|1287@mli|茅岭|MLZ|maoling|ml|1288@mli|庙岭|MLL|miaoling|ml|1289@mli|茂林|MLD|maolin|ml|1290@mli|穆棱|MLB|muling|ml|1291@mli|马林|MID|malin|ml|1292@mlo|马龙|MGM|malong|ml|1293@mlt|木里图|MUD|mulitu|mlt|1294@mlu|汨罗|MLQ|miluo|ml|1295@mnh|玛纳斯湖|MNR|manasihu|mnsh|1296@mni|冕宁|UGW|mianning|mn|1297@mpa|沐滂|MPQ|mupang|mp|1298@mqh|马桥河|MQB|maqiaohe|mqh|1299@mqi|闽清|MQS|minqing|mq|1300@mqu|民权|MQF|minquan|mq|1301@msh|明水河|MUT|mingshuihe|msh|1302@msh|麻山|MAB|mashan|ms|1303@msh|眉山|MSW|meishan|ms|1304@msw|漫水湾|MKW|manshuiwan|msw|1305@msz|茂舍祖|MOM|maoshezu|msz|1306@msz|米沙子|MST|mishazi|msz|1307@mxi|美溪|MEB|meixi|mx|1308@mxi|勉县|MVY|mianxian|mx|1309@mya|麻阳|MVQ|mayang|my|1310@myb|密云北|MUP|miyunbei|myb|1311@myi|米易|MMW|miyi|my|1312@myu|麦园|MYS|maiyuan|my|1313@myu|墨玉|MUR|moyu|my|1314@mzh|庙庄|MZJ|miaozhuang|mz|1315@mzh|米脂|MEY|mizhi|mz|1316@mzh|明珠|MFQ|mingzhu|mz|1317@nan|宁安|NAB|ningan|na|1318@nan|农安|NAT|nongan|na|1319@nbs|南博山|NBK|nanboshan|nbs|1320@nch|南仇|NCK|nanqiu|nc|1321@ncs|南城司|NSP|nanchengsi|ncs|1322@ncu|宁村|NCZ|ningcun|nc|1323@nde|宁德|NES|ningde|nd|1324@ngc|南观村|NGP|nanguancun|ngc|1325@ngd|南宫东|NFP|nangongdong|ngd|1326@ngl|南关岭|NLT|nanguanling|ngl|1327@ngu|宁国|NNH|ningguo|ng|1328@nha|宁海|NHH|ninghai|nh|1329@nhc|南河川|NHJ|nanhechuan|nhc|1330@nhu|南华|NHS|nanhua|nh|1331@nhz|泥河子|NHD|nihezi|nhz|1332@nji|宁家|NVT|ningjia|nj|1333@nji|南靖|NJS|nanjing|nj|1334@nji|牛家|NJB|niujia|nj|1335@nji|能家|NJD|nengjia|nj|1336@nko|南口|NKP|nankou|nk|1337@nkq|南口前|NKT|nankouqian|nkq|1338@nla|南朗|NNQ|nanlang|nl|1339@nli|乃林|NLD|nailin|nl|1340@nlk|尼勒克|NIR|nileke|nlk|1341@nlu|那罗|ULZ|naluo|nl|1342@nlx|宁陵县|NLF|ninglingxian|nlx|1343@nma|奈曼|NMD|naiman|nm|1344@nmi|宁明|NMZ|ningming|nm|1345@nmu|南木|NMX|nanmu|nm|1346@npn|南平南|NNS|nanpingnan|npn|1347@npu|那铺|NPZ|napu|np|1348@nqi|南桥|NQD|nanqiao|nq|1349@nqu|那曲|NQO|naqu|nq|1350@nqu|暖泉|NQJ|nuanquan|nq|1351@nta|南台|NTT|nantai|nt|1352@nto|南头|NOQ|nantou|nt|1353@nwu|宁武|NWV|ningwu|nw|1354@nwz|南湾子|NWP|nanwanzi|nwz|1355@nxb|南翔北|NEH|nanxiangbei|nxb|1356@nxi|宁乡|NXQ|ningxiang|nx|1357@nxi|内乡|NXF|neixiang|nx|1358@nxt|牛心台|NXT|niuxintai|nxt|1359@nyu|南峪|NUP|nanyu|ny|1360@nzg|娘子关|NIP|niangziguan|nzg|1361@nzh|南召|NAF|nanzhao|nz|1362@nzm|南杂木|NZT|nanzamu|nzm|1363@pan|蓬安|PAW|pengan|pa|1364@pan|平安|PAL|pingan|pa|1365@pay|平安驿|PNO|pinganyi|pay|1366@paz|磐安镇|PAJ|pananzhen|paz|1367@paz|平安镇|PZT|pinganzhen|paz|1368@pcd|蒲城东|PEY|puchengdong|pcd|1369@pch|蒲城|PCY|pucheng|pc|1370@pde|裴德|PDB|peide|pd|1371@pdi|偏店|PRP|piandian|pd|1372@pdx|平顶山西|BFF|pingdingshanxi|pdsx|1373@pdx|坡底下|PXJ|podixia|pdx|1374@pet|瓢儿屯|PRT|piaoertun|pet|1375@pfa|平房|PFB|pingfang|pf|1376@pga|平岗|PGL|pinggang|pg|1377@pgu|平关|PGM|pingguan|pg|1378@pgu|盘关|PAM|panguan|pg|1379@pgu|平果|PGZ|pingguo|pg|1380@phb|徘徊北|PHP|paihuaibei|phb|1381@phk|平河口|PHM|pinghekou|phk|1382@phu|平湖|PHQ|pinghu|ph|1383@pjb|盘锦北|PBD|panjinbei|pjb|1384@pjd|潘家店|PDP|panjiadian|pjd|1385@pkn|皮口南|PKT|pikounan|pk|1386@pld|普兰店|PLT|pulandian|pld|1387@pli|偏岭|PNT|pianling|pl|1388@psh|平山|PSB|pingshan|ps|1389@psh|彭山|PSW|pengshan|ps|1390@psh|皮山|PSR|pishan|ps|1391@psh|磐石|PSL|panshi|ps|1392@psh|平社|PSV|pingshe|ps|1393@psh|彭水|PHW|pengshui|ps|1394@pta|平台|PVT|pingtai|pt|1395@pti|平田|PTM|pingtian|pt|1396@pti|莆田|PTS|putian|pt|1397@ptq|葡萄菁|PTW|putaojing|ptj|1398@pwa|普湾|PWT|puwan|pw|1399@pwa|平旺|PWV|pingwang|pw|1400@pxg|平型关|PGV|pingxingguan|pxg|1401@pxi|普雄|POW|puxiong|px|1402@pxi|郫县|PWW|pixian|px|1403@pya|平洋|PYX|pingyang|py|1404@pya|彭阳|PYJ|pengyang|py|1405@pya|平遥|PYV|pingyao|py|1406@pyi|平邑|PIK|pingyi|py|1407@pyp|平原堡|PPJ|pingyuanpu|pyp|1408@pyu|平原|PYK|pingyuan|py|1409@pyu|平峪|PYP|pingyu|py|1410@pze|彭泽|PZG|pengze|pz|1411@pzh|邳州|PJH|pizhou|pz|1412@pzh|平庄|PZD|pingzhuang|pz|1413@pzi|泡子|POD|paozi|pz|1414@pzn|平庄南|PND|pingzhuangnan|pzn|1415@qan|乾安|QOT|qianan|qa|1416@qan|庆安|QAB|qingan|qa|1417@qan|迁安|QQP|qianan|qa|1418@qdb|祁东北|QRQ|qidongbei|qd|1419@qdi|七甸|QDM|qidian|qd|1420@qfd|曲阜东|QAK|qufudong|qfd|1421@qfe|庆丰|QFT|qingfeng|qf|1422@qft|奇峰塔|QVP|qifengta|qft|1423@qfu|曲阜|QFK|qufu|qf|1424@qha|琼海|QYQ|qionghai|qh|1425@qhd|秦皇岛|QTP|qinhuangdao|qhd|1426@qhe|千河|QUY|qianhe|qh|1427@qhe|清河|QIP|qinghe|qh|1428@qhm|清河门|QHD|qinghemen|qhm|1429@qhy|清华园|QHP|qinghuayuan|qhy|1430@qji|全椒|INH|quanjiao|qj|1431@qji|渠旧|QJZ|qujiu|qj|1432@qji|潜江|QJN|qianjiang|qj|1433@qji|秦家|QJB|qinjia|qj|1434@qji|綦江|QJW|qijiang|qj|1435@qjp|祁家堡|QBT|qijiapu|qjb|1436@qjx|清涧县|QNY|qingjianxian|qjx|1437@qjz|秦家庄|QZV|qinjiazhuang|qjz|1438@qlh|七里河|QLD|qilihe|qlh|1439@qli|秦岭|QLY|qinling|ql|1440@qli|渠黎|QLZ|quli|ql|1441@qlo|青龙|QIB|qinglong|ql|1442@qls|青龙山|QGH|qinglongshan|qls|1443@qme|祁门|QIH|qimen|qm|1444@qmt|前磨头|QMP|qianmotou|qmt|1445@qsh|青山|QSB|qingshan|qs|1446@qsh|确山|QSN|queshan|qs|1447@qsh|前山|QXQ|qianshan|qs|1448@qsh|清水|QUJ|qingshui|qs|1449@qsy|戚墅堰|QYH|qishuyan|qsy|1450@qti|青田|QVH|qingtian|qt|1451@qto|桥头|QAT|qiaotou|qt|1452@qtx|青铜峡|QTJ|qingtongxia|qtx|1453@qwe|前卫|QWD|qianwei|qw|1454@qwt|前苇塘|QWP|qianweitang|qwt|1455@qxi|渠县|QRW|quxian|qx|1456@qxi|祁县|QXV|qixian|qx|1457@qxi|青县|QXP|qingxian|qx|1458@qxi|桥西|QXJ|qiaoxi|qx|1459@qxu|清徐|QUV|qingxu|qx|1460@qxy|旗下营|QXC|qixiaying|qxy|1461@qya|千阳|QOY|qianyang|qy|1462@qya|沁阳|QYF|qinyang|qy|1463@qya|泉阳|QYL|quanyang|qy|1464@qyb|祁阳北|QVQ|qiyangbei|qy|1465@qyi|七营|QYJ|qiying|qy|1466@qys|庆阳山|QSJ|qingyangshan|qys|1467@qyu|清远|QBQ|qingyuan|qy|1468@qyu|清原|QYT|qingyuan|qy|1469@qzd|钦州东|QDZ|qinzhoudong|qzd|1470@qzh|钦州|QRZ|qinzhou|qz|1471@qzs|青州市|QZK|qingzhoushi|qzs|1472@ran|瑞安|RAH|ruian|ra|1473@rch|荣昌|RCW|rongchang|rc|1474@rch|瑞昌|RCG|ruichang|rc|1475@rga|如皋|RBH|rugao|rg|1476@rgu|容桂|RUQ|ronggui|rg|1477@rqi|任丘|RQP|renqiu|rq|1478@rsh|乳山|ROK|rushan|rs|1479@rsh|融水|RSZ|rongshui|rs|1480@rsh|热水|RSD|reshui|rs|1481@rxi|容县|RXZ|rongxian|rx|1482@rya|饶阳|RVP|raoyang|ry|1483@rya|汝阳|RYF|ruyang|ry|1484@ryh|绕阳河|RHD|raoyanghe|ryh|1485@rzh|汝州|ROF|ruzhou|rz|1486@sba|石坝|OBJ|shiba|sb|1487@sbc|上板城|SBP|shangbancheng|sbc|1488@sbi|施秉|AQW|shibing|sb|1489@sbn|上板城南|OBP|shangbanchengnan|sbcn|1490@sby|世博园|ZWT|shiboyuan|sby|1491@scb|双城北|SBB|shuangchengbei|scb|1492@sch|舒城|OCH|shucheng|sc|1493@sch|商城|SWN|shangcheng|sc|1494@sch|莎车|SCR|shache|sc|1495@sch|顺昌|SCS|shunchang|sc|1496@sch|神池|SMV|shenchi|sc|1497@sch|沙城|SCP|shacheng|sc|1498@sch|石城|SCT|shicheng|sc|1499@scz|山城镇|SCL|shanchengzhen|scz|1500@sda|山丹|SDJ|shandan|sd|1501@sde|顺德|ORQ|shunde|sd|1502@sde|绥德|ODY|suide|sd|1503@sdo|水洞|SIL|shuidong|sd|1504@sdu|商都|SXC|shangdu|sd|1505@sdu|十渡|SEP|shidu|sd|1506@sdw|四道湾|OUD|sidaowan|sdw|1507@sdy|顺德学院|OJQ|shundexueyuan|sdxy|1508@sfa|绅坊|OLH|shenfang|sf|1509@sfe|双丰|OFB|shuangfeng|sf|1510@sft|四方台|STB|sifangtai|sft|1511@sfu|水富|OTW|shuifu|sf|1512@sgk|三关口|OKJ|sanguankou|sgk|1513@sgl|桑根达来|OGC|sanggendalai|sgdl|1514@sgu|韶关|SNQ|shaoguan|sg|1515@sgz|上高镇|SVK|shanggaozhen|sgz|1516@sha|上杭|JBS|shanghang|sh|1517@sha|沙海|SED|shahai|sh|1518@she|松河|SBM|songhe|sh|1519@she|沙河|SHP|shahe|sh|1520@shk|沙河口|SKT|shahekou|shk|1521@shl|赛汗塔拉|SHC|saihantala|shtl|1522@shs|沙河市|VOP|shaheshi|shs|1523@shs|沙后所|SSD|shahousuo|shs|1524@sht|山河屯|SHL|shanhetun|sht|1525@shx|三河县|OXP|sanhexian|shx|1526@shy|四合永|OHD|siheyong|shy|1527@shz|三汇镇|OZW|sanhuizhen|shz|1528@shz|双河镇|SEL|shuanghezhen|shz|1529@shz|石河子|SZR|shihezi|shz|1530@shz|三合庄|SVP|sanhezhuang|shz|1531@sjd|三家店|ODP|sanjiadian|sjd|1532@sjh|水家湖|SQH|shuijiahu|sjh|1533@sjh|沈家河|OJJ|shenjiahe|sjh|1534@sjh|松江河|SJL|songjianghe|sjh|1535@sji|尚家|SJB|shangjia|sj|1536@sji|孙家|SUB|sunjia|sj|1537@sji|沈家|OJB|shenjia|sj|1538@sji|双吉|SML|shuangji|sj|1539@sji|松江|SAH|songjiang|sj|1540@sjk|三江口|SKD|sanjiangkou|sjk|1541@sjl|司家岭|OLK|sijialing|sjl|1542@sjn|松江南|IMH|songjiangnan|sjn|1543@sjn|石景山南|SRP|shijingshannan|sjsn|1544@sjt|邵家堂|SJJ|shaojiatang|sjt|1545@sjx|三江县|SOZ|sanjiangxian|sjx|1546@sjz|三家寨|SMM|sanjiazhai|sjz|1547@sjz|十家子|SJD|shijiazi|sjz|1548@sjz|松江镇|OZL|songjiangzhen|sjz|1549@sjz|施家嘴|SHM|shijiazui|sjz|1550@sjz|深井子|SWT|shenjingzi|sjz|1551@sld|什里店|OMP|shilidian|sld|1552@sle|疏勒|SUR|shule|sl|1553@slh|疏勒河|SHJ|shulehe|slh|1554@slh|舍力虎|VLD|shelihu|slh|1555@sli|石磷|SPB|shilin|sl|1556@sli|双辽|ZJD|shuangliao|sl|1557@sli|绥棱|SIB|suiling|sl|1558@sli|石岭|SOL|shiling|sl|1559@sli|石林|SLM|shilin|sl|1560@sln|石林南|LNM|shilinnan|sln|1561@slo|石龙|SLQ|shilong|sl|1562@slq|萨拉齐|SLC|salaqi|slq|1563@slu|索伦|SNT|suolun|sl|1564@slu|商洛|OLY|shangluo|sl|1565@slz|沙岭子|SLP|shalingzi|slz|1566@smb|石门县北|VFQ|shimenxianbei|smxb|1567@smn|三门峡南|SCF|sanmenxianan|smxn|1568@smx|三门县|OQH|sanmenxian|smx|1569@smx|石门县|OMQ|shimenxian|smx|1570@smx|三门峡西|SXF|sanmenxiaxi|smxx|1571@sni|肃宁|SYP|suning|sn|1572@son|宋|SOB|song|s|1573@spa|双牌|SBZ|shuangpai|sp|1574@spd|四平东|PPT|sipingdong|spd|1575@spi|遂平|SON|suiping|sp|1576@spt|沙坡头|SFJ|shapotou|spt|1577@sqi|沙桥|SQM|shaqiao|sq|1578@sqn|商丘南|SPF|shangqiunan|sqn|1579@squ|水泉|SID|shuiquan|sq|1580@sqx|石泉县|SXY|shiquanxian|sqx|1581@sqz|石桥子|SQT|shiqiaozi|sqz|1582@src|石人城|SRB|shirencheng|src|1583@sre|石人|SRL|shiren|sr|1584@ssh|山市|SQB|shanshi|ss|1585@ssh|神树|SWB|shenshu|ss|1586@ssh|鄯善|SSR|shanshan|ss|1587@ssh|三水|SJQ|sanshui|ss|1588@ssh|泗水|OSK|sishui|ss|1589@ssh|石山|SAD|shishan|ss|1590@ssh|松树|SFT|songshu|ss|1591@ssh|首山|SAT|shoushan|ss|1592@ssj|三十家|SRD|sanshijia|ssj|1593@ssp|三十里堡|SST|sanshilipu|sslb|1594@ssz|松树镇|SSL|songshuzhen|ssz|1595@sta|松桃|MZQ|songtao|st|1596@sth|索图罕|SHX|suotuhan|sth|1597@stj|三堂集|SDH|santangji|stj|1598@sto|石头|OTB|shitou|st|1599@sto|神头|SEV|shentou|st|1600@stu|沙沱|SFM|shatuo|st|1601@swa|上万|SWP|shangwan|sw|1602@swu|孙吴|SKB|sunwu|sw|1603@swx|沙湾县|SXR|shawanxian|swx|1604@sxi|歙县|OVH|shexian|sx|1605@sxi|遂溪|SXZ|suixi|sx|1606@sxi|沙县|SAS|shaxian|sx|1607@sxi|绍兴|SOH|shaoxing|sx|1608@sxi|石岘|SXL|shixian|sj|1609@sxp|上西铺|SXM|shangxipu|sxp|1610@sxz|石峡子|SXJ|shixiazi|sxz|1611@sya|沭阳|FMH|shuyang|sy|1612@sya|绥阳|SYB|suiyang|sy|1613@sya|寿阳|SYV|shouyang|sy|1614@sya|水洋|OYP|shuiyang|sy|1615@syc|三阳川|SYJ|sanyangchuan|syc|1616@syd|上腰墩|SPJ|shangyaodun|syd|1617@syi|三营|OEJ|sanying|sy|1618@syi|顺义|SOP|shunyi|sy|1619@syj|三义井|OYD|sanyijing|syj|1620@syp|三源浦|SYL|sanyuanpu|syp|1621@syu|上虞|BDH|shangyu|sy|1622@syu|三原|SAY|sanyuan|sy|1623@syu|上园|SUD|shangyuan|sy|1624@syu|水源|OYJ|shuiyuan|sy|1625@syz|桑园子|SAJ|sangyuanzi|syz|1626@szb|绥中北|SND|suizhongbei|szb|1627@szb|苏州北|OHH|suzhoubei|szb|1628@szd|宿州东|SRH|suzhoudong|szd|1629@szd|深圳东|BJQ|shenzhendong|szd|1630@szh|深州|OZP|shenzhou|sz|1631@szh|孙镇|OZY|sunzhen|sz|1632@szh|绥中|SZD|suizhong|sz|1633@szh|尚志|SZB|shangzhi|sz|1634@szh|师庄|SNM|shizhuang|sz|1635@szi|松滋|SIN|songzi|sz|1636@szo|师宗|SEM|shizong|sz|1637@szq|苏州园区|KAH|suzhouyuanqu|szyq|1638@szq|苏州新区|ITH|suzhouxinqu|szxq|1639@tan|泰安|TMK|taian|ta|1640@tan|台安|TID|taian|ta|1641@tay|通安驿|TAJ|tonganyi|tay|1642@tba|桐柏|TBF|tongbai|tb|1643@tbe|通北|TBB|tongbei|tb|1644@tch|桐城|TTH|tongcheng|tc|1645@tch|汤池|TCX|tangchi|tc|1646@tch|郯城|TZK|tancheng|tc|1647@tch|铁厂|TCL|tiechang|tc|1648@tcu|桃村|TCK|taocun|tc|1649@tda|通道|TRQ|tongdao|td|1650@tdo|田东|TDZ|tiandong|td|1651@tga|天岗|TGL|tiangang|tg|1652@tgl|土贵乌拉|TGC|tuguiwula|tgwl|1653@tgo|通沟|TOL|tonggou|tg|1654@tgu|太谷|TGV|taigu|tg|1655@tha|塔哈|THX|taha|th|1656@tha|棠海|THM|tanghai|th|1657@the|唐河|THF|tanghe|th|1658@the|泰和|THG|taihe|th|1659@thu|太湖|TKH|taihu|th|1660@tji|团结|TIX|tuanjie|tj|1661@tjj|谭家井|TNJ|tanjiajing|tjj|1662@tjt|陶家屯|TOT|taojiatun|tjt|1663@tjw|唐家湾|PDQ|tangjiawan|tjw|1664@tjz|统军庄|TZP|tongjunzhuang|tjz|1665@tka|泰康|TKX|taikang|tk|1666@tld|吐列毛杜|TMD|tuliemaodu|tlmd|1667@tlh|图里河|TEX|tulihe|tlh|1668@tli|铜陵|TJH|tongling|tl|1669@tli|田林|TFZ|tianlin|tl|1670@tli|亭亮|TIZ|tingliang|tl|1671@tli|铁力|TLB|tieli|tl|1672@tlx|铁岭西|PXT|tielingxi|tlx|1673@tmb|图们北|QSL|tumenbei|tmb|1674@tme|天门|TMN|tianmen|tm|1675@tmn|天门南|TNN|tianmennan|tmn|1676@tms|太姥山|TLS|taimushan|tms|1677@tmt|土牧尔台|TRC|tumuertai|tmet|1678@tmz|土门子|TCJ|tumenzi|tmz|1679@tna|洮南|TVT|taonan|tn|1680@tna|潼南|TVW|tongnan|tn|1681@tpc|太平川|TIT|taipingchuan|tpc|1682@tpz|太平镇|TEB|taipingzhen|tpz|1683@tqi|图强|TQX|tuqiang|tq|1684@tqi|台前|TTK|taiqian|tq|1685@tql|天桥岭|TQL|tianqiaoling|tql|1686@tqz|土桥子|TQJ|tuqiaozi|tqz|1687@tsc|汤山城|TCT|tangshancheng|tsc|1688@tsh|桃山|TAB|taoshan|ts|1689@tsz|塔石嘴|TIM|tashizui|tsz|1690@ttu|通途|TUT|tongtu|tt|1691@twh|汤旺河|THB|tangwanghe|twh|1692@txi|同心|TXJ|tongxin|tx|1693@txi|土溪|TSW|tuxi|tx|1694@txi|桐乡|TCH|tongxiang|tx|1695@tya|田阳|TRZ|tianyang|ty|1696@tyi|天义|TND|tianyi|ty|1697@tyi|汤阴|TYF|tangyin|ty|1698@tyl|驼腰岭|TIL|tuoyaoling|tyl|1699@tys|太阳山|TYJ|taiyangshan|tys|1700@tyu|汤原|TYB|tangyuan|ty|1701@tyy|塔崖驿|TYP|tayayi|tyy|1702@tzd|滕州东|TEK|tengzhoudong|tzd|1703@tzh|台州|TZH|taizhou|tz|1704@tzh|天祝|TZJ|tianzhu|tz|1705@tzh|滕州|TXK|tengzhou|tz|1706@tzh|天镇|TZV|tianzhen|tz|1707@tzl|桐子林|TEW|tongzilin|tzl|1708@tzs|天柱山|QWH|tianzhushan|tzs|1709@wan|文安|WBP|wenan|wa|1710@wan|武安|WAP|wuan|wa|1711@waz|王安镇|WVP|wanganzhen|waz|1712@wca|旺苍|WEW|wangcang|wc|1713@wcg|五叉沟|WCT|wuchagou|wcg|1714@wch|文昌|WEQ|wenchang|wc|1715@wch|温春|WDB|wenchun|wc|1716@wdc|五大连池|WRB|wudalianchi|wdlc|1717@wde|文登|WBK|wendeng|wd|1718@wdg|五道沟|WDL|wudaogou|wdg|1719@wdh|五道河|WHP|wudaohe|wdh|1720@wdi|文地|WNZ|wendi|wd|1721@wdo|卫东|WVT|weidong|wd|1722@wds|武当山|WRN|wudangshan|wds|1723@wdu|望都|WDP|wangdu|wd|1724@weh|乌尔旗汗|WHX|wuerqihan|weqh|1725@wfa|潍坊|WFK|weifang|wf|1726@wft|万发屯|WFB|wanfatun|wft|1727@wfu|王府|WUT|wangfu|wf|1728@wfx|瓦房店西|WXT|wafangdianxi|wfdx|1729@wga|王岗|WGB|wanggang|wg|1730@wgo|武功|WGY|wugong|wg|1731@wgo|湾沟|WGL|wangou|wg|1732@wgt|吴官田|WGM|wuguantian|wgt|1733@wha|乌海|WVC|wuhai|wh|1734@whe|苇河|WHB|weihe|wh|1735@whu|卫辉|WHF|weihui|wh|1736@wjc|吴家川|WCJ|wujiachuan|wjc|1737@wji|五家|WUB|wujia|wj|1738@wji|威箐|WAM|weiqing|wq|1739@wji|午汲|WJP|wuji|wj|1740@wji|渭津|WJL|weijin|wj|1741@wjw|王家湾|WJJ|wangjiawan|wjw|1742@wke|倭肯|WQB|woken|wk|1743@wks|五棵树|WKT|wukeshu|wks|1744@wlb|五龙背|WBT|wulongbei|wlb|1745@wld|乌兰哈达|WLC|wulanhada|wlhd|1746@wle|万乐|WEB|wanle|wl|1747@wlg|瓦拉干|WVX|walagan|wlg|1748@wli|温岭|VHH|wenling|wl|1749@wli|五莲|WLK|wulian|wl|1750@wlq|乌拉特前旗|WQC|wulateqianqi|wltqq|1751@wls|乌拉山|WSC|wulashan|wls|1752@wlt|卧里屯|WLX|wolitun|wlt|1753@wnb|渭南北|WBY|weinanbei|wnb|1754@wne|乌奴耳|WRX|wunuer|wne|1755@wni|万宁|WNQ|wanning|wn|1756@wni|万年|WWG|wannian|wn|1757@wnn|渭南南|WVY|weinannan|wnn|1758@wnz|渭南镇|WNJ|weinanzhen|wnz|1759@wpi|沃皮|WPT|wopi|wp|1760@wpu|吴堡|WUY|wupu|wb|1761@wqi|吴桥|WUP|wuqiao|wq|1762@wqi|汪清|WQL|wangqing|wq|1763@wqi|武清|WWP|wuqing|wq|1764@wsh|武山|WSJ|wushan|ws|1765@wsh|文水|WEV|wenshui|ws|1766@wsz|魏善庄|WSP|weishanzhuang|wsz|1767@wto|王瞳|WTP|wangtong|wt|1768@wts|五台山|WSV|wutaishan|wts|1769@wtz|王团庄|WZJ|wangtuanzhuang|wtz|1770@wwu|五五|WVR|wuwu|ww|1771@wxd|无锡东|WGH|wuxidong|wxd|1772@wxi|卫星|WVB|weixing|wx|1773@wxi|闻喜|WXV|wenxi|wx|1774@wxi|武乡|WVV|wuxiang|wx|1775@wxq|无锡新区|IFH|wuxixinqu|wxxq|1776@wxu|武穴|WXN|wuxue|wx|1777@wxu|吴圩|WYZ|wuxu|wy|1778@wya|王杨|WYB|wangyang|wy|1779@wyi|武义|RYH|wuyi|wy|1780@wyi|五营|WWB|wuying|wy|1781@wyt|瓦窑田|WIM|wayaotian|wjt|1782@wyu|五原|WYC|wuyuan|wy|1783@wzg|苇子沟|WZL|weizigou|wzg|1784@wzh|韦庄|WZY|weizhuang|wz|1785@wzh|五寨|WZV|wuzhai|wz|1786@wzt|王兆屯|WZB|wangzhaotun|wzt|1787@wzz|微子镇|WQP|weizizhen|wzz|1788@wzz|魏杖子|WKD|weizhangzi|wzz|1789@xan|新安|EAM|xinan|xa|1790@xan|兴安|XAZ|xingan|xa|1791@xax|新安县|XAF|xinanxian|xax|1792@xba|新保安|XAP|xinbaoan|xba|1793@xbc|下板城|EBP|xiabancheng|xbc|1794@xbl|西八里|XLP|xibali|xbl|1795@xch|宣城|ECH|xuancheng|xc|1796@xch|兴城|XCD|xingcheng|xc|1797@xcu|小村|XEM|xiaocun|xc|1798@xcy|新绰源|XRX|xinchuoyuan|xcy|1799@xcz|下城子|XCB|xiachengzi|xcz|1800@xcz|新城子|XCT|xinchengzi|xcz|1801@xde|喜德|EDW|xide|xd|1802@xdj|小得江|EJM|xiaodejiang|xdj|1803@xdm|西大庙|XMP|xidamiao|xdm|1804@xdo|小董|XEZ|xiaodong|xd|1805@xdo|小东|XOD|xiaodong|xdo|1806@xfe|信丰|EFG|xinfeng|xf|1807@xfe|襄汾|XFV|xiangfen|xf|1808@xfe|息烽|XFW|xifeng|xf|1809@xga|新干|EGG|xingan|xg|1810@xga|孝感|XGN|xiaogan|xg|1811@xgc|西固城|XUJ|xigucheng|xgc|1812@xgu|西固|XIJ|xigu|xg|1813@xgy|夏官营|XGJ|xiaguanying|xgy|1814@xgz|西岗子|NBB|xigangzi|xgz|1815@xhe|襄河|XXB|xianghe|xh|1816@xhe|新和|XIR|xinhe|xh|1817@xhe|宣和|XWJ|xuanhe|xh|1818@xhj|斜河涧|EEP|xiehejian|xhj|1819@xht|新华屯|XAX|xinhuatun|xht|1820@xhu|新华|XHB|xinhua|xh|1821@xhu|新化|EHQ|xinhua|xh|1822@xhu|宣化|XHP|xuanhua|xh|1823@xhx|兴和西|XEC|xinghexi|xhx|1824@xhy|小河沿|XYD|xiaoheyan|xhy|1825@xhy|下花园|XYP|xiahuayuan|xhy|1826@xhz|小河镇|EKY|xiaohezhen|xhz|1827@xji|徐家|XJB|xujia|xj|1828@xji|峡江|EJG|xiajiang|xj|1829@xji|新绛|XJV|xinjiang|xj|1830@xji|辛集|ENP|xinji|xj|1831@xji|新江|XJM|xinjiang|xj|1832@xjk|西街口|EKM|xijiekou|xjk|1833@xjt|许家屯|XJT|xujiatun|xjt|1834@xjt|许家台|XTJ|xujiatai|xjt|1835@xjz|谢家镇|XMT|xiejiazhen|xjz|1836@xka|兴凯|EKB|xingkai|xk|1837@xla|小榄|EAQ|xiaolan|xl|1838@xla|香兰|XNB|xianglan|xl|1839@xld|兴隆店|XDD|xinglongdian|xld|1840@xle|新乐|ELP|xinle|xl|1841@xli|新林|XPX|xinlin|xl|1842@xli|小岭|XLB|xiaoling|xl|1843@xli|新李|XLJ|xinli|xl|1844@xli|西林|XYB|xilin|xl|1845@xli|西柳|GCT|xiliu|xl|1846@xli|仙林|XPH|xianlin|xl|1847@xlt|新立屯|XLD|xinlitun|xlt|1848@xlz|兴隆镇|XZB|xinglongzhen|xlz|1849@xlz|新立镇|XGT|xinlizhen|xlz|1850@xmi|新民|XMD|xinmin|xm|1851@xms|西麻山|XMB|ximashan|xms|1852@xmt|下马塘|XAT|xiamatang|xmt|1853@xna|孝南|XNV|xiaonan|xn|1854@xnb|咸宁北|XRN|xianningbei|xnb|1855@xni|兴宁|ENQ|xingning|xn|1856@xni|咸宁|XNN|xianning|xn|1857@xpd|犀浦东|XAW|xipudong|xpd|1858@xpi|西平|XPN|xiping|xp|1859@xpi|兴平|XPY|xingping|xp|1860@xpt|新坪田|XPM|xinpingtian|xpt|1861@xpu|霞浦|XOS|xiapu|xp|1862@xpu|溆浦|EPQ|xupu|xp|1863@xpu|犀浦|XIW|xipu|xp|1864@xqi|新青|XQB|xinqing|xq|1865@xqi|新邱|XQD|xinqiu|xq|1866@xqp|兴泉堡|XQJ|xingquanbu|xqp|1867@xrq|仙人桥|XRL|xianrenqiao|xrq|1868@xsg|小寺沟|ESP|xiaosigou|xsg|1869@xsh|杏树|XSB|xingshu|xs|1870@xsh|浠水|XZN|xishui|xs|1871@xsh|下社|XSV|xiashe|xs|1872@xsh|徐水|XSP|xushui|xs|1873@xsh|夏石|XIZ|xiashi|xs|1874@xsh|小哨|XAM|xiaoshao|xs|1875@xsp|新松浦|XOB|xinsongpu|xsp|1876@xst|杏树屯|XDT|xingshutun|xst|1877@xsw|许三湾|XSJ|xusanwan|xsw|1878@xta|湘潭|XTQ|xiangtan|xt|1879@xta|邢台|XTP|xingtai|xt|1880@xtx|仙桃西|XAN|xiantaoxi|xtx|1881@xtz|下台子|EIP|xiataizi|xtz|1882@xwe|徐闻|XJQ|xuwen|xw|1883@xwp|新窝铺|EPD|xinwopu|xwp|1884@xwu|修武|XWF|xiuwu|xw|1885@xxi|新县|XSN|xinxian|xx|1886@xxi|息县|ENN|xixian|xx|1887@xxi|西乡|XQY|xixiang|xx|1888@xxi|湘乡|XXQ|xiangxiang|xx|1889@xxi|西峡|XIF|xixia|xx|1890@xxi|孝西|XOV|xiaoxi|xx|1891@xxj|小新街|XXM|xiaoxinjie|xxj|1892@xxx|新兴县|XGQ|xinxingxian|xxx|1893@xxz|西小召|XZC|xixiaozhao|xxz|1894@xxz|小西庄|XXP|xiaoxizhuang|xxz|1895@xya|向阳|XDB|xiangyang|xy|1896@xya|旬阳|XUY|xunyang|xy|1897@xyb|旬阳北|XBY|xunyangbei|xyb|1898@xyd|襄阳东|XWN|xiangyangdong|xyd|1899@xye|兴业|SNZ|xingye|xy|1900@xyg|小雨谷|XHM|xiaoyugu|xyg|1901@xyi|信宜|EEQ|xinyi|xy|1902@xyj|小月旧|XFM|xiaoyuejiu|xyj|1903@xyq|小扬气|XYX|xiaoyangqi|xyq|1904@xyu|祥云|EXM|xiangyun|xy|1905@xyu|襄垣|EIF|xiangyuan|xy|1906@xyx|夏邑县|EJH|xiayixian|xyx|1907@xyy|新友谊|EYB|xinyouyi|xyy|1908@xyz|新阳镇|XZJ|xinyangzhen|xyz|1909@xzd|徐州东|UUH|xuzhoudong|xzd|1910@xzf|新帐房|XZX|xinzhangfang|xzf|1911@xzh|悬钟|XRP|xuanzhong|xz|1912@xzh|新肇|XZT|xinzhao|xz|1913@xzh|忻州|XXV|xinzhou|xz|1914@xzi|汐子|XZD|xizi|xz|1915@xzm|西哲里木|XRD|xizhelimu|xzlm|1916@xzz|新杖子|ERP|xinzhangzi|xzz|1917@yan|姚安|YAC|yaoan|ya|1918@yan|依安|YAX|yian|ya|1919@yan|永安|YAS|yongan|ya|1920@yax|永安乡|YNB|yonganxiang|yax|1921@ybl|亚布力|YBB|yabuli|ybl|1922@ybs|元宝山|YUD|yuanbaoshan|ybs|1923@yca|羊草|YAB|yangcao|yc|1924@ycd|秧草地|YKM|yangcaodi|ycd|1925@ych|阳澄湖|AIH|yangchenghu|ych|1926@ych|迎春|YYB|yingchun|yc|1927@ych|叶城|YER|yecheng|yc|1928@ych|盐池|YKJ|yanchi|yc|1929@ych|砚川|YYY|yanchuan|yc|1930@ych|阳春|YQQ|yangchun|yc|1931@ych|宜城|YIN|yicheng|yc|1932@ych|应城|YHN|yingcheng|yc|1933@ych|禹城|YCK|yucheng|yc|1934@ych|晏城|YEK|yancheng|yc|1935@ych|羊场|YED|yangchang|yc|1936@ych|阳城|YNF|yangcheng|yc|1937@ych|阳岔|YAL|yangcha|yc|1938@ych|郓城|YPK|yuncheng|yc|1939@ych|雁翅|YAP|yanchi|yc|1940@ycl|云彩岭|ACP|yuncailing|ycl|1941@ycx|虞城县|IXH|yuchengxian|ycx|1942@ycz|营城子|YCT|yingchengzi|ycz|1943@yde|英德|YDQ|yingde|yd|1944@yde|永登|YDJ|yongdeng|yd|1945@ydi|尹地|YDM|yindi|yd|1946@ydi|永定|YGS|yongding|yd|1947@yds|雁荡山|YGH|yandangshan|yds|1948@ydu|于都|YDG|yudu|yd|1949@ydu|园墩|YAJ|yuandun|yd|1950@ydx|英德西|IIQ|yingdexi|ydx|1951@yfy|永丰营|YYM|yongfengying|yfy|1952@yga|杨岗|YRB|yanggang|yg|1953@yga|阳高|YOV|yanggao|yg|1954@ygu|阳谷|YIK|yanggu|yg|1955@yha|友好|YOB|youhao|yh|1956@yha|余杭|EVH|yuhang|yh|1957@yhc|沿河城|YHP|yanhecheng|yhc|1958@yhu|岩会|AEP|yanhui|yh|1959@yjh|羊臼河|YHM|yangjiuhe|yjh|1960@yji|永嘉|URH|yongjia|yj|1961@yji|营街|YAM|yingjie|yj|1962@yji|盐津|AEW|yanjin|yj|1963@yji|余江|YHG|yujiang|yj|1964@yji|燕郊|AJP|yanjiao|yj|1965@yji|姚家|YAT|yaojia|yj|1966@yjj|岳家井|YGJ|yuejiajing|yjj|1967@yjp|一间堡|YJT|yijianpu|yjb|1968@yjs|英吉沙|YIR|yingjisha|yjs|1969@yjs|云居寺|AFP|yunjusi|yjs|1970@yjz|燕家庄|AZK|yanjiazhuang|yjz|1971@yka|永康|RFH|yongkang|yk|1972@ykd|营口东|YGT|yingkoudong|ykd|1973@yla|银浪|YJX|yinlang|yl|1974@yla|永郎|YLW|yonglang|yl|1975@ylb|宜良北|YSM|yiliangbei|ylb|1976@yld|永乐店|YDY|yongledian|yld|1977@ylh|伊拉哈|YLX|yilaha|ylh|1978@yli|伊林|YLB|yilin|yl|1979@yli|杨陵|YSY|yangling|yl|1980@yli|彝良|ALW|yiliang|yl|1981@yli|杨林|YLM|yanglin|yl|1982@ylp|余粮堡|YLD|yuliangpu|ylb|1983@ylq|杨柳青|YQP|yangliuqing|ylq|1984@ylt|月亮田|YUM|yueliangtian|ylt|1985@yma|义马|YMF|yima|ym|1986@yme|玉门|YXJ|yumen|ym|1987@yme|云梦|YMN|yunmeng|ym|1988@ymo|元谋|YMM|yuanmou|ym|1989@ymp|阳明堡|YVV|yangmingbu|ymp|1990@yms|一面山|YST|yimianshan|yms|1991@yna|沂南|YNK|yinan|yn|1992@yna|宜耐|YVM|yinai|yn|1993@ynd|伊宁东|YNR|yiningdong|ynd|1994@yps|营盘水|YZJ|yingpanshui|yps|1995@ypu|羊堡|ABM|yangpu|yp|1996@yqb|阳泉北|YPP|yangquanbei|yqb|1997@yqi|乐清|UPH|yueqing|yq|1998@yqi|焉耆|YSR|yanqi|yq|1999@yqi|源迁|AQK|yuanqian|yq|2000@yqt|姚千户屯|YQT|yaoqianhutun|yqht|2001@yqu|阳曲|YQV|yangqu|yq|2002@ysg|榆树沟|YGP|yushugou|ysg|2003@ysh|月山|YBF|yueshan|ys|2004@ysh|玉石|YSJ|yushi|ys|2005@ysh|玉舍|AUM|yushe|ys|2006@ysh|偃师|YSF|yanshi|ys|2007@ysh|沂水|YUK|yishui|ys|2008@ysh|榆社|YSV|yushe|ys|2009@ysh|窑上|ASP|yaoshang|ys|2010@ysh|元氏|YSP|yuanshi|ys|2011@ysl|杨树岭|YAD|yangshuling|ysl|2012@ysp|野三坡|AIP|yesanpo|ysp|2013@yst|榆树屯|YSX|yushutun|yst|2014@yst|榆树台|YUT|yushutai|yst|2015@ysz|鹰手营子|YIP|yingshouyingzi|ysyz|2016@yta|源潭|YTQ|yuantan|yt|2017@ytp|牙屯堡|YTZ|yatunpu|ytb|2018@yts|烟筒山|YSL|yantongshan|yts|2019@ytt|烟筒屯|YUX|yantongtun|ytt|2020@yws|羊尾哨|YWM|yangweishao|yws|2021@yxi|越西|YHW|yuexi|yx|2022@yxi|攸县|YOG|youxian|yx|2023@yxi|永修|ACG|yongxiu|yx|2024@yxx|玉溪西|YXM|yuxixi|yxx|2025@yya|弋阳|YIG|yiyang|yy|2026@yya|余姚|YYH|yuyao|yy|2027@yya|酉阳|AFW|youyang|yy|2028@yyd|岳阳东|YIQ|yueyangdong|yyd|2029@yyi|阳邑|ARP|yangyi|yy|2030@yyu|鸭园|YYL|yayuan|yy|2031@yyz|鸳鸯镇|YYJ|yuanyangzhen|yyz|2032@yzb|燕子砭|YZY|yanzibian|yzb|2033@yzh|仪征|UZH|yizheng|yz|2034@yzh|宜州|YSZ|yizhou|yz|2035@yzh|兖州|YZK|yanzhou|yz|2036@yzi|迤资|YQM|yizi|yz|2037@yzw|羊者窝|AEM|yangzhewo|wzw|2038@yzz|杨杖子|YZD|yangzhangzi|yzz|2039@zan|镇安|ZEY|zhenan|za|2040@zan|治安|ZAD|zhian|za|2041@zba|招柏|ZBP|zhaobai|zb|2042@zbw|张百湾|ZUP|zhangbaiwan|zbw|2043@zcc|中川机场|ZJJ|zhongchuanjichang|zcjc|2044@zch|枝城|ZCN|zhicheng|zc|2045@zch|子长|ZHY|zichang|zc|2046@zch|诸城|ZQK|zhucheng|zc|2047@zch|邹城|ZIK|zoucheng|zc|2048@zch|赵城|ZCV|zhaocheng|zc|2049@zda|章党|ZHT|zhangdang|zd|2050@zdi|正定|ZDP|zhengding|zd|2051@zdo|肇东|ZDB|zhaodong|zd|2052@zfp|照福铺|ZFM|zhaofupu|zfp|2053@zgt|章古台|ZGD|zhanggutai|zgt|2054@zgu|赵光|ZGB|zhaoguang|zg|2055@zhe|中和|ZHX|zhonghe|zh|2056@zhm|中华门|VNH|zhonghuamen|zhm|2057@zjb|枝江北|ZIN|zhijiangbei|zjb|2058@zjc|钟家村|ZJY|zhongjiacun|zjc|2059@zjg|朱家沟|ZUB|zhujiagou|zjg|2060@zjg|紫荆关|ZYP|zijingguan|zjg|2061@zji|周家|ZOB|zhoujia|zj|2062@zji|诸暨|ZDH|zhuji|zj|2063@zjn|镇江南|ZEH|zhenjiangnan|zjn|2064@zjt|周家屯|ZOD|zhoujiatun|zjt|2065@zjw|褚家湾|CWJ|zhujiawan|cjw|2066@zjx|湛江西|ZWQ|zhanjiangxi|zjx|2067@zjy|朱家窑|ZUJ|zhujiayao|zjy|2068@zjz|曾家坪子|ZBW|zengjiapingzi|zjpz|2069@zla|张兰|ZLV|zhanglan|zla|2070@zla|镇赉|ZLT|zhenlai|zl|2071@zli|枣林|ZIV|zaolin|zl|2072@zlt|扎鲁特|ZLD|zhalute|zlt|2073@zlx|扎赉诺尔西|ZXX|zhalainuoerxi|zlnex|2074@zmt|樟木头|ZOQ|zhangmutou|zmt|2075@zmu|中牟|ZGF|zhongmu|zm|2076@znd|中宁东|ZDJ|zhongningdong|znd|2077@zni|中宁|VNJ|zhongning|zn|2078@znn|中宁南|ZNJ|zhongningnan|znn|2079@zpi|镇平|ZPF|zhenping|zp|2080@zpi|漳平|ZPS|zhangping|zp|2081@zpu|泽普|ZPR|zepu|zp|2082@zqi|枣强|ZVP|zaoqiang|zq|2083@zqi|张桥|ZQY|zhangqiao|zq|2084@zqi|章丘|ZTK|zhangqiu|zq|2085@zrh|朱日和|ZRC|zhurihe|zrh|2086@zrl|泽润里|ZLM|zerunli|zrl|2087@zsb|中山北|ZGQ|zhongshanbei|zsb|2088@zsd|樟树东|ZOG|zhangshudong|zsd|2089@zsh|中山|ZSQ|zhongshan|zs|2090@zsh|柞水|ZSY|zhashui|zs|2091@zsh|钟山|ZSZ|zhongshan|zs|2092@zsh|樟树|ZSG|zhangshu|zs|2093@zwo|珠窝|ZOP|zhuwo|zw|2094@zwt|张维屯|ZWB|zhangweitun|zwt|2095@zwu|彰武|ZWD|zhangwu|zw|2096@zxi|棕溪|ZOY|zongxi|zx|2097@zxi|钟祥|ZTN|zhongxiang|zx|2098@zxi|资溪|ZXS|zixi|zx|2099@zxi|镇西|ZVT|zhenxi|zx|2100@zxi|张辛|ZIP|zhangxin|zx|2101@zxq|正镶白旗|ZXC|zhengxiangbaiqi|zxbq|2102@zya|紫阳|ZVY|ziyang|zy|2103@zya|枣阳|ZYN|zaoyang|zy|2104@zyb|竹园坝|ZAW|zhuyuanba|zyb|2105@zye|张掖|ZYJ|zhangye|zy|2106@zyu|镇远|ZUW|zhenyuan|zy|2107@zyx|朱杨溪|ZXW|zhuyangxi|zyx|2108@zzd|漳州东|GOS|zhangzhoudong|zzd|2109@zzh|漳州|ZUS|zhangzhou|zz|2110@zzh|壮志|ZUX|zhuangzhi|zz|2111@zzh|子洲|ZZY|zizhou|zz|2112@zzh|中寨|ZZM|zhongzhai|zz|2113@zzh|涿州|ZXP|zhuozhou|zz|2114@zzi|咋子|ZAL|zhazi|zz|2115@zzs|卓资山|ZZC|zhuozishan|zzs|2116@zzx|株洲西|ZAQ|zhuzhouxi|zzx|2117@zzx|郑州西|XPF|zhengzhouxi|zzx|2118@abq|阿巴嘎旗|AQC|abagaqi|abgq|2119@aeb|阿尔山北|ARX|aershanbei|aesb|2120@are|安仁|ARG|anren|ar|2121@asx|安顺西|ASE|anshunxi|asx|2122@atx|安图西|AXL|antuxi|atx|2123@ayd|安阳东|ADF|anyangdong|ayd|2124@bba|博白|BBZ|bobai|bb|2125@bbu|八步|BBE|babu|bb|2126@bch|栟茶|FWH|bencha|bc|2127@bdd|保定东|BMP|baodingdong|bdd|2128@bgo|白沟|FEP|baigou|bg|2129@bha|滨海|FHP|binhai|bh|2130@bhb|滨海北|FCP|binhaibei|bhb|2131@bjn|宝鸡南|BBY|baojinan|bjn|2132@bjz|北井子|BRT|beijingzi|bjz|2133@bmj|白马井|BFQ|baimajing|bmj|2134@bqi|宝清|BUB|baoqing|bq|2135@bsh|璧山|FZW|bishan|bs|2136@bsx|白水县|BGY|baishuixian|bsx|2137@bta|板塘|NGQ|bantang|bt|2138@bxc|本溪新城|BVT|benxixincheng|bxxc|2139@bxi|彬县|BXY|binxian|bx|2140@bya|宾阳|UKZ|binyang|by|2141@byd|白洋淀|FWP|baiyangdian|byd|2142@byi|百宜|FHW|baiyi|by|2143@byn|白音华南|FNC|baiyinhuanan|byhn|2144@bzd|巴中东|BDE|bazhongdong|bzd|2145@bzh|滨州|BIK|binzhou|bz|2146@bzx|霸州西|FOP|bazhouxi|bzx|2147@cch|澄城|CUY|chengcheng|cc|2148@chd|巢湖东|GUH|chaohudong|chd|2149@cji|从江|KNW|congjiang|cj|2150@cka|茶卡|CVO|chaka|ck|2151@clh|长临河|FVH|changlinhe|clh|2152@cln|茶陵南|CNG|chalingnan|cln|2153@cpd|常平东|FQQ|changpingdong|cpd|2154@cqq|长庆桥|CQJ|changqingqiao|cqq|2155@csb|长寿北|COW|changshoubei|csb|2156@csh|长寿湖|CSE|changshouhu|csh|2157@csh|潮汕|CBQ|chaoshan|cs|2158@ctn|长汀南|CNS|changtingnan|ctn|2159@cwu|长武|CWY|changwu|cw|2160@cxi|长兴|CBH|changxing|cx|2161@cxi|苍溪|CXE|cangxi|cx|2162@cya|长阳|CYN|changyang|cy|2163@cya|潮阳|CNQ|chaoyang|cy|2164@czt|城子坦|CWT|chengzitan|czt|2165@dad|东安东|DCZ|dongandong|dad|2166@dba|德保|RBZ|debao|db|2167@ddh|东戴河|RDD|dongdaihe|ddh|2168@ddx|丹东西|RWT|dandongxi|ddx|2169@deh|东二道河|DRB|dongerdaohe|dedh|2170@dfe|大丰|KRQ|dafeng|df|2171@dfn|大方南|DNE|dafangnan|dfn|2172@dgb|东港北|RGT|donggangbei|dgb|2173@dgs|大孤山|RMT|dagushan|dgs|2174@dgu|东莞|RTQ|dongguan|dg|2175@dhd|鼎湖东|UWQ|dinghudong|dhd|2176@dhs|鼎湖山|NVQ|dinghushan|dhs|2177@dji|垫江|DJE|dianjiang|dj|2178@dji|洞井|FWQ|dongjing|dj|2179@dju|大苴|DIM|daju|dj|2180@dli|大荔|DNY|dali|dl|2181@dqg|大青沟|DSD|daqinggou|dqg|2182@dqi|德清|DRH|deqing|dq|2183@dsn|砀山南|PRH|dangshannan|dsn|2184@dsn|大石头南|DAL|dashitounan|dstn|2185@dtd|当涂东|OWH|dangtudong|dtd|2186@dtx|大通西|DTO|datongxi|dtx|2187@dwa|大旺|WWQ|dawang|dw|2188@dxi|德兴|DWG|dexing|dx|2189@dxs|丹霞山|IRQ|danxiashan|dxs|2190@dyb|大冶北|DBN|dayebei|dyb|2191@dyd|都匀东|KJW|duyundong|dyd|2192@dyn|东营南|DOK|dongyingnan|dyn|2193@dyu|大余|DYG|dayu|dy|2194@dzd|定州东|DOP|dingzhoudong|dzd|2195@dzh|端州|WZQ|duanzhou|dz|2196@dzn|大足南|FQW|dazunan|dzn|2197@ems|峨眉山|IXW|emeishan|ems|2198@ezd|鄂州东|EFN|ezhoudong|ezd|2199@fcb|防城港北|FBZ|fangchenggangbei|fcgb|2200@fcd|凤城东|FDT|fengchengdong|fcd|2201@fch|富川|FDZ|fuchuan|fc|2202@fcx|繁昌西|PUH|fanchangxi|fcx|2203@fdu|丰都|FUW|fengdu|fd|2204@flb|涪陵北|FEW|fulingbei|flb|2205@fni|富宁|FNM|funing|fn|2206@fqi|法启|FQE|faqi|fq|2207@frn|芙蓉南|KCQ|furongnan|frn|2208@fsh|复盛|FAW|fusheng|fs|2209@fso|抚松|FSL|fusong|fs|2210@fsz|福山镇|FZQ|fushanzhen|fsz|2211@fti|福田|NZQ|futian|ft|2212@fyb|富源北|FBM|fuyuanbei|fyb|2213@fyu|抚远|FYB|fuyuan|fy|2214@fzd|抚州东|FDG|fuzhoudong|fzd|2215@fzh|抚州|FZG|fuzhou|fz|2216@gan|高安|GCG|gaoan|ga|2217@gan|广安南|VUW|guangannan|gan|2218@gan|贵安|GAE|guian|ga|2219@gbd|高碑店东|GMP|gaobeidiandong|gbdd|2220@gch|恭城|GCZ|gongcheng|gc|2221@gdb|贵定北|FMW|guidingbei|gdb|2222@gdn|葛店南|GNN|gediannan|gdn|2223@gdx|贵定县|KIW|guidingxian|gdx|2224@ghb|广汉北|GVW|guanghanbei|ghb|2225@gju|革居|GEM|geju|gj|2226@gli|关岭|GLE|guanling|gl|2227@glx|桂林西|GEZ|guilinxi|glx|2228@gmc|光明城|IMQ|guangmingcheng|gmc|2229@gni|广宁|FBQ|guangning|gn|2230@gns|广宁寺|GQT|guangningsi|gns|2231@gnx|广南县|GXM|guangnanxian|gnx|2232@gpi|桂平|GAZ|guiping|gp|2233@gpz|弓棚子|GPT|gongpengzi|gpz|2234@gsh|光山|GUN|guangshan|gs|2235@gtb|古田北|GBS|gutianbei|gtb|2236@gtb|广通北|GPM|guangtongbei|gtb|2237@gtn|高台南|GAJ|gaotainan|gtn|2238@gtz|古田会址|STS|gutianhuizhi|gthz|2239@gyb|贵阳北|KQW|guiyangbei|gyb|2240@gyx|高邑西|GNP|gaoyixi|gyx|2241@han|惠安|HNS|huian|ha|2242@hbd|鹤壁东|HFF|hebidong|hbd|2243@hcg|寒葱沟|HKB|hanconggou|hcg|2244@hch|珲春|HUL|hunchun|hch|2245@hdd|邯郸东|HPP|handandong|hdd|2246@hdo|惠东|KDQ|huidong|hd|2247@hdp|哈达铺|HDJ|hadapu|hdp|2248@hdx|海东西|HDO|haidongxi|hdx|2249@hdx|洪洞西|HTV|hongtongxi|hdx|2250@heb|哈尔滨北|HTB|haerbinbei|hebb|2251@hfc|合肥北城|COH|hefeibeicheng|hfbc|2252@hfn|合肥南|ENH|hefeinan|hfn|2253@hga|黄冈|KGN|huanggang|hg|2254@hgd|黄冈东|KAN|huanggangdong|hgd|2255@hgd|横沟桥东|HNN|henggouqiaodong|hgqd|2256@hgx|黄冈西|KXN|huanggangxi|hgx|2257@hhe|洪河|HPB|honghe|hh|2258@hhn|怀化南|KAQ|huaihuanan|hhn|2259@hhq|黄河景区|HCF|huanghejingqu|hhjq|2260@hhu|花湖|KHN|huahu|hh|2261@hhu|惠环|KHQ|huihuan|hh|2262@hhu|后湖|IHN|houhu|hh|2263@hji|怀集|FAQ|huaiji|hj|2264@hkb|河口北|HBM|hekoubei|hkb|2265@hli|黄流|KLQ|huangliu|hl|2266@hln|黄陵南|VLY|huanglingnan|hln|2267@hme|鲘门|KMQ|houmen|hm|2268@hme|虎门|IUQ|humen|hm|2269@hmx|侯马西|HPV|houmaxi|hmx|2270@hna|衡南|HNG|hengnan|hn|2271@hnd|淮南东|HOH|huainandong|hnd|2272@hpu|合浦|HVZ|hepu|hp|2273@hqi|霍邱|FBH|huoqiu|hq|2274@hrd|怀仁东|HFV|huairendong|hrd|2275@hrd|华容东|HPN|huarongdong|hrd|2276@hrn|华容南|KRN|huarongnan|hrn|2277@hsb|黄石北|KSN|huangshibei|hsb|2278@hsb|黄山北|NYH|huangshanbei|hsb|2279@hsd|贺胜桥东|HLN|heshengqiaodong|hsqd|2280@hsh|和硕|VUR|heshuo|hs|2281@hsn|花山南|KNN|huashannan|hsn|2282@hta|荷塘|KXQ|hetang|ht|2283@hyb|合阳北|HTY|heyangbei|hyb|2284@hyb|海阳北|HEK|haiyangbei|hyb|2285@hyi|槐荫|IYN|huaiyin|hy|2286@hyk|花园口|HYT|huayuankou|hyk|2287@hzd|霍州东|HWV|huozhoudong|hzd|2288@hzn|惠州南|KNQ|huizhounan|hzn|2289@jch|泾川|JAJ|jingchuan|jc|2290@jde|旌德|NSH|jingde|jd|2291@jfe|尖峰|PFQ|jianfeng|jf|2292@jhx|蛟河西|JOL|jiaohexi|jhx|2293@jlb|军粮城北|JMP|junliangchengbei|jlcb|2294@jle|将乐|JLS|jiangle|jl|2295@jlh|贾鲁河|JLF|jialuhe|jlh|2296@jls|九郎山|KJQ|jiulangshan|jls|2297@jmb|即墨北|JVK|jimobei|jmb|2298@jnb|建宁县北|JCS|jianningxianbei|jnxb|2299@jni|江宁|JJH|jiangning|jn|2300@jnx|江宁西|OKH|jiangningxi|jnx|2301@jox|建瓯西|JUS|jianouxi|jox|2302@jqn|酒泉南|JNJ|jiuquannan|jqn|2303@jrx|句容西|JWH|jurongxi|jrx|2304@jsh|建水|JSM|jianshui|js|2305@jss|界首市|JUN|jieshoushi|jss|2306@jxb|绩溪北|NRH|jixibei|jxb|2307@jxd|介休东|JDV|jiexiudong|jxd|2308@jxi|泾县|LOH|jingxian|jx|2309@jxi|靖西|JMZ|jingxi|jx|2310@jxn|进贤南|JXG|jinxiannan|jxn|2311@jyn|嘉峪关南|JBJ|jiayuguannan|jygn|2312@jyn|简阳南|JOW|jianyangnan|jyn|2313@jyt|金银潭|JTN|jinyintan|jyt|2314@jyu|靖宇|JYL|jingyu|jy|2315@jyw|金月湾|PYQ|jinyuewan|jyw|2316@jyx|缙云西|PYH|jinyunxi|jyx|2317@jzh|晋中|JZV|jinzhong|jz|2318@kfb|开封北|KBF|kaifengbei|kfb|2319@kln|凯里南|QKW|kailinan|kln|2320@klu|库伦|KLD|kulun|kl|2321@kmn|昆明南|KOM|kunmingnan|kmn|2322@kta|葵潭|KTQ|kuitan|kt|2323@kya|开阳|KVW|kaiyang|ky|2324@lad|隆安东|IDZ|longandong|lad|2325@lbb|来宾北|UCZ|laibinbei|lbb|2326@lbi|灵璧|GMH|lingbi|lb|2327@lby|绿博园|LCF|lvboyuan|lby|2328@lcb|隆昌北|NWW|longchangbei|lcb|2329@lch|临城|UUP|lincheng|lc|2330@lch|罗城|VCZ|luocheng|lc|2331@lch|陵城|LGK|lingcheng|lc|2332@lcz|老城镇|ACQ|laochengzhen|lcz|2333@ldb|龙洞堡|FVW|longdongbao|ldb|2334@ldn|乐都南|LVO|ledunan|ldn|2335@ldn|娄底南|UOQ|loudinan|ldn|2336@ldo|乐东|UQQ|ledong|ld|2337@ldy|离堆公园|INW|liduigongyuan|ldgy|2338@lfe|陆丰|LLQ|lufeng|lf|2339@lfe|龙丰|KFQ|longfeng|lf|2340@lfn|禄丰南|LQM|lufengnan|lfn|2341@lfx|临汾西|LXV|linfenxi|lfx|2342@lgn|临高南|KGQ|lingaonan|lgn|2343@lhe|滦河|UDP|luanhe|lh|2344@lhx|漯河西|LBN|luohexi|lhx|2345@ljd|罗江东|IKW|luojiangdong|ljd|2346@lji|柳江|UQZ|liujiang|lj|2347@ljn|利津南|LNK|lijinnan|ljn|2348@lkn|兰考南|LUF|lankaonan|lkn|2349@llb|兰陵北|COK|lanlingbei|llb|2350@llb|龙里北|KFW|longlibei|llb|2351@llb|沥林北|KBQ|lilinbei|llb|2352@lld|醴陵东|UKQ|lilingdong|lld|2353@lna|陇南|INJ|longnan|ln|2354@lpn|梁平南|LPE|liangpingnan|lpn|2355@lqu|礼泉|LGY|liquan|lq|2356@lsd|灵石东|UDV|lingshidong|lsd|2357@lsh|乐山|IVW|leshan|ls|2358@lsh|龙市|LAG|longshi|sh|2359@lsh|溧水|LDH|lishui|ls|2360@lwj|洛湾三江|KRW|luowansanjiang|lwsj|2361@lxb|莱西北|LBK|laixibei|lxb|2362@lya|溧阳|LEH|liyang|ly|2363@lyi|临邑|LUK|linyi|ly|2364@lyn|柳园南|LNR|liuyuannan|lyn|2365@lzb|鹿寨北|LSZ|luzhaibei|lzb|2366@lzh|阆中|LZE|langzhong|lz|2367@lzn|临泽南|LDJ|linzenan|lzn|2368@mad|马鞍山东|OMH|maanshandong|masd|2369@mch|毛陈|MHN|maochen|mc|2370@mgd|明港东|MDN|minggangdong|mgd|2371@mhn|民和南|MNO|minhenan|mhn|2372@mji|闵集|MJN|minji|mj|2373@mla|马兰|MLR|malan|ml|2374@mle|民乐|MBJ|minle|ml|2375@mle|弥勒|MLM|mile|ml|2376@mns|玛纳斯|MSR|manasi|mns|2377@mpi|牟平|MBK|muping|mp|2378@mqb|闽清北|MBS|minqingbei|mqb|2379@mqb|民权北|MIF|minquanbei|mqb|2380@msd|眉山东|IUW|meishandong|msd|2381@msh|庙山|MSN|miaoshan|ms|2382@mxi|岷县|MXJ|minxian|mx|2383@myu|门源|MYO|menyuan|my|2384@myu|暮云|KIQ|muyun|my|2385@mzb|蒙自北|MBM|mengzibei|mzb|2386@mzh|孟庄|MZF|mengzhuang|mz|2387@mzi|蒙自|MZM|mengzi|mz|2388@nbu|南部|NBE|nanbu|nb|2389@nca|南曹|NEF|nancao|nc|2390@ncb|南充北|NCE|nanchongbei|ncb|2391@nch|南城|NDG|nancheng|nc|2392@ncx|南昌西|NXG|nanchangxi|ncx|2393@ndn|宁东南|NDJ|ningdongnan|ndn|2394@ndo|宁东|NOJ|ningdong|nd|2395@nfb|南芬北|NUT|nanfenbei|nfb|2396@nfe|南丰|NFG|nanfeng|nf|2397@nhd|南湖东|NDN|nanhudong|nhd|2398@njb|内江北|NKW|neijiangbei|njb|2399@nji|南江|FIW|nanjiang|nj|2400@njk|南江口|NDQ|nanjiangkou|nj|2401@nli|南陵|LLH|nanling|nl|2402@nmu|尼木|NMO|nimu|nm|2403@nnd|南宁东|NFZ|nanningdong|nnd|2404@nnx|南宁西|NXZ|nanningxi|nnx|2405@npb|南平北|NBS|nanpingbei|npb|2406@nxi|南雄|NCQ|nanxiong|nx|2407@nyo|纳雍|NYE|nayong|ny|2408@nyz|南阳寨|NYF|nanyangzhai|nyz|2409@pan|普安|PAN|puan|pa|2410@pax|普安县|PUE|puanxian|pax|2411@pbi|屏边|PBM|pingbian|pb|2412@pbn|平坝南|PBE|pingbanan|pbn|2413@pch|平昌|PCE|pingchang|pc|2414@pdi|普定|PGW|puding|pd|2415@pdu|平度|PAK|pingdu|pd|2416@pko|皮口|PUT|pikou|pk|2417@plc|盘龙城|PNN|panlongcheng|plc|2418@pni|普宁|PEQ|puning|pn|2419@pnn|平南南|PAZ|pingnannan|pn|2420@psb|彭山北|PPW|pengshanbei|psb|2421@psh|坪上|PSK|pingshang|ps|2422@pxb|萍乡北|PBG|pingxiangbei|pxb|2423@pya|濮阳|PYF|puyang|py|2424@pyc|平遥古城|PDV|pingyaogucheng|pygc|2425@pzh|普者黑|PZM|puzhehei|pzh|2426@pzh|盘州|PAE|panzhou|pz|2427@pzh|彭州|PMW|pengzhou|pz|2428@qbd|青白江东|QFW|qingbaijiangdong|qbjd|2429@qdb|青岛北|QHK|qingdaobei|qdb|2430@qdo|祁东|QMQ|qidong|qd|2431@qdu|青堆|QET|qingdui|qd|2432@qfe|前锋|QFB|qianfeng|qf|2433@qjb|曲靖北|QBM|qujingbei|qjb|2434@qji|曲江|QIM|qujiang|qj|2435@qli|青莲|QEW|qinglian|ql|2436@qqn|齐齐哈尔南|QNB|qiqihaernan|qqhen|2437@qsb|清水北|QEJ|qingshuibei|qsb|2438@qsh|青神|QVW|qingshen|qs|2439@qsh|岐山|QAY|qishan|qs|2440@qsh|庆盛|QSQ|qingsheng|qs|2441@qsx|曲水县|QSO|qushuixian|qsx|2442@qxd|祁县东|QGV|qixiandong|qxd|2443@qxi|乾县|QBY|qianxian|qx|2444@qya|祁阳|QWQ|qiyang|qy|2445@qzn|全州南|QNZ|quanzhounan|qzn|2446@qzw|棋子湾|QZQ|qiziwan|qzw|2447@rbu|仁布|RUO|renbu|rb|2448@rcb|荣昌北|RQW|rongchangbei|rcb|2449@rch|荣成|RCK|rongcheng|rc|2450@rdo|如东|RIH|rudong|rd|2451@rji|榕江|RVW|rongjiang|rj|2452@rkz|日喀则|RKO|rikaze|rkz|2453@rpi|饶平|RVQ|raoping|rp|2454@scl|宋城路|SFF|songchenglu|scl|2455@sdh|三道湖|SDL|sandaohu|sdh|2456@sdo|邵东|FIQ|shaodong|sd|2457@sdx|三都县|KKW|sanduxian|sdx|2458@sfa|胜芳|SUP|shengfang|sf|2459@sfb|双峰北|NFQ|shuangfengbei|sfb|2460@she|商河|SOK|shanghe|sh|2461@sho|泗洪|GQH|sihong|sh|2462@shu|四会|AHQ|sihui|sh|2463@sjn|三江南|SWZ|sanjiangnan|sjn|2464@sjz|三井子|OJT|sanjingzi|sjz|2465@slc|双流机场|IPW|shuangliujichang|sljc|2466@slx|双流西|IQW|shuangliuxi|slx|2467@slx|石林西|SYM|shilinxi|slx|2468@smb|三明北|SHS|sanmingbei|smb|2469@smi|嵩明|SVM|songming|sm|2470@sml|树木岭|FMQ|shumuling|sml|2471@snq|苏尼特左旗|ONC|sunitezuoqi|sntzq|2472@spd|山坡东|SBN|shanpodong|spd|2473@sqi|石桥|SQE|shiqiao|sq|2474@sqi|沈丘|SQN|shenqiu|sq|2475@ssb|鄯善北|SMR|shanshanbei|ssb|2476@ssb|狮山北|NSQ|shishanbei|ssb|2477@ssb|三水北|ARQ|sanshuibei|ssb|2478@ssh|狮山|KSQ|shishan|ss|2479@ssn|三水南|RNQ|sanshuinan|ssn|2480@ssn|韶山南|INQ|shaoshannan|ssn|2481@ssu|三穗|QHW|sansui|ss|2482@sti|石梯|STE|shiti|st|2483@swe|汕尾|OGQ|shanwei|sw|2484@sxb|歙县北|NPH|shexianbei|sxb|2485@sxb|绍兴北|SLH|shaoxingbei|sxb|2486@sxd|绍兴东|SSH|shaoxingdong|sxd|2487@sxi|泗县|GPH|sixian|sx|2488@sxi|始兴|IPQ|shixing|sx|2489@sya|泗阳|MPH|siyang|sy|2490@syb|邵阳北|OVQ|shaoyangbei|syb|2491@syb|松原北|OCT|songyuanbei|syb|2492@syi|山阴|SNV|shanyin|sy|2493@syn|沈阳南|SOT|shenyangnan|syn|2494@szb|深圳北|IOQ|shenzhenbei|szb|2495@szh|神州|SRQ|shenzhou|sz|2496@szs|深圳坪山|IFQ|shenzhenpingshan|szps|2497@szs|石嘴山|QQJ|shizuishan|szs|2498@szx|石柱县|OSW|shizhuxian|szx|2499@tcb|桃村北|TOK|taocunbei|tcb|2500@tdb|田东北|TBZ|tiandongbei|tdb|2501@tdd|土地堂东|TTN|tuditangdong|tdtd|2502@tgx|太谷西|TIV|taiguxi|tgx|2503@tha|吐哈|THR|tuha|th|2504@tha|通海|TAM|tonghai|th|2505@thc|天河机场|TJN|tianhejichang|thjc|2506@thj|天河街|TEN|tianhejie|thj|2507@thx|通化县|TXL|tonghuaxian|thx|2508@tji|同江|TJB|tongjiang|tj|2509@tlb|铜陵北|KXH|tonglingbei|tlb|2510@tlb|吐鲁番北|TAR|tulufanbei|tlfb|2511@tni|泰宁|TNS|taining|tn|2512@trn|铜仁南|TNW|tongrennan|trn|2513@txd|田心东|KQQ|tianxindong|txd|2514@txh|汤逊湖|THN|tangxunhu|txh|2515@txi|藤县|TAZ|tengxian|tx|2516@tyn|太原南|TNV|taiyuannan|tyn|2517@tyx|通远堡西|TST|tongyuanpuxi|typx|2518@wdd|文登东|WGK|wendengdong|wdd|2519@wfs|五府山|WFG|wufushan|wfs|2520@whb|威虎岭北|WBL|weihulingbei|whlb|2521@whb|威海北|WHK|weihaibei|whb|2522@wld|五龙背东|WMT|wulongbeidong|wlbd|2523@wln|乌龙泉南|WFN|wulongquannan|wlqn|2524@wlq|乌鲁木齐|WAR|wulumuqi|wlmq|2525@wns|五女山|WET|wunvshan|wns|2526@wsh|武胜|WSE|wusheng|ws|2527@wwe|无为|IIH|wuwei|ww|2528@wws|瓦屋山|WAH|wawushan|wws|2529@wxx|闻喜西|WOV|wenxixi|wxx|2530@wyb|武义北|WDH|wuyibei|wyb|2531@wyb|武夷山北|WBS|wuyishanbei|wysb|2532@wyd|武夷山东|WCS|wuyishandong|wysd|2533@wyu|婺源|WYG|wuyuan|wy|2534@wyu|渭源|WEJ|weiyuan|wy|2535@wzb|万州北|WZE|wanzhoubei|wzb|2536@wzh|武陟|WIF|wuzhi|wz|2537@wzn|梧州南|WBZ|wuzhounan|wzn|2538@xab|兴安北|XDZ|xinganbei|xab|2539@xcd|许昌东|XVF|xuchangdong|xcd|2540@xch|项城|ERN|xiangcheng|xc|2541@xdd|新都东|EWW|xindudong|xdd|2542@xfe|西丰|XFT|xifeng|xf|2543@xfe|先锋|NQQ|xianfeng|xf|2544@xfl|湘府路|FVQ|xiangfulu|xfl|2545@xfx|襄汾西|XTV|xiangfenxi|xfx|2546@xgb|孝感北|XJN|xiaoganbei|xgb|2547@xgd|孝感东|GDN|xiaogandong|xgd|2548@xhd|西湖东|WDQ|xihudong|xhd|2549@xhn|新化南|EJQ|xinhuanan|xhn|2550@xhx|新晃西|EWQ|xinhuangxi|xhx|2551@xji|新津|IRW|xinjin|xj|2552@xjk|小金口|NKQ|xiaojinkou|xjk|2553@xjn|新津南|ITW|xinjinnan|xjn|2554@xnd|咸宁东|XKN|xianningdong|xnd|2555@xnn|咸宁南|UNN|xianningnan|xnn|2556@xpn|溆浦南|EMQ|xupunan|xpn|2557@xtb|湘潭北|EDQ|xiangtanbei|xtb|2558@xtd|邢台东|EDP|xingtaidong|xtd|2559@xwq|西乌旗|XWC|xiwuqi|xwq|2560@xwx|修武西|EXF|xiuwuxi|xwx|2561@xxb|萧县北|QSH|xiaoxianbei|xxb|2562@xxd|新乡东|EGF|xinxiangdong|xxd|2563@xyb|新余北|XBG|xinyubei|xyb|2564@xyc|西阳村|XQF|xiyangcun|xyc|2565@xyd|信阳东|OYN|xinyangdong|xyd|2566@xyd|咸阳秦都|XOY|xianyangqindu|xyqd|2567@xyo|仙游|XWS|xianyou|xy|2568@xzc|新郑机场|EZF|xinzhengjichang|xzjc|2569@xzl|香樟路|FNQ|xiangzhanglu|xzl|2570@ybl|迎宾路|YFW|yingbinlu|ybl|2571@ycb|永城北|RGH|yongchengbei|ycb|2572@ycb|运城北|ABV|yunchengbei|ycb|2573@ycd|永川东|WMW|yongchuandong|ycd|2574@ych|宜春|YEG|yichun|yc|2575@ych|岳池|AWW|yuechi|yc|2576@ydh|云东海|NAQ|yundonghai|ydh|2577@ydu|姚渡|AOJ|yaodu|yd|2578@yfd|云浮东|IXQ|yunfudong|yfd|2579@yfn|永福南|YBZ|yongfunan|yfn|2580@yge|雨格|VTM|yuge|yg|2581@yhe|洋河|GTH|yanghe|yh|2582@yjb|永济北|AJV|yongjibei|yjb|2583@yji|弋江|RVH|yijiang|yj|2584@yjp|于家堡|YKP|yujiapu|yjp|2585@yjx|延吉西|YXL|yanjixi|yjx|2586@ykn|永康南|QUH|yongkangnan|ykn|2587@ylh|运粮河|YEF|yunlianghe|ylh|2588@yli|炎陵|YAG|yanling|yl|2589@yln|杨陵南|YEY|yanglingnan|yln|2590@ymi|伊敏|YMX|yimin|ym|2591@yna|郁南|YKQ|yunan|yn|2592@ypi|银瓶|KPQ|yinping|yp|2593@ysh|永寿|ASY|yongshou|ys|2594@ysh|阳朔|YCZ|yangshuo|ys|2595@ysh|云山|KZQ|yunshan|ys|2596@ysn|玉山南|YGG|yushannan|ysn|2597@yta|银滩|CTQ|yintan|yt|2598@yta|永泰|YTS|yongtai|yt|2599@ytb|鹰潭北|YKG|yingtanbei|ytb|2600@ytn|烟台南|YLK|yantainan|ytn|2601@yxi|尤溪|YXS|youxi|yx|2602@yxi|宜兴|YUH|yixing|yx|2603@yxi|云霄|YBS|yunxiao|yx|2604@yxi|玉溪|AXM|yuxi|yx|2605@yxi|阳信|YVK|yangxin|yx|2606@yxi|应县|YZV|yingxian|yx|2607@yxn|攸县南|YXG|youxiannan|yxn|2608@yyb|余姚北|CTH|yuyaobei|yyb|2609@zan|诏安|ZDS|zhaoan|za|2610@zdc|正定机场|ZHP|zhengdingjichang|zdjc|2611@zfd|纸坊东|ZMN|zhifangdong|zfd|2612@zhb|庄河北|ZUT|zhuanghebei|zhb|2613@zhu|昭化|ZHW|zhaohua|zhu|2614@zjb|织金北|ZJE|zhijinbei|zjb|2615@zji|芷江|ZPQ|zhijiang|zj|2616@zji|织金|IZW|zhijin|zj|2617@zka|仲恺|KKQ|zhongkai|zk|2618@zko|曾口|ZKE|zengkou|zk|2619@zli|左岭|ZSN|zuoling|zl|2620@zmd|樟木头东|ZRQ|zhangmutoudong|zmtd|2621@zmx|驻马店西|ZLN|zhumadianxi|zmdx|2622@zpu|漳浦|ZCS|zhangpu|zp|2623@zqd|肇庆东|FCQ|zhaoqingdong|zqd|2624@zqi|庄桥|ZQH|zhuangqiao|zq|2625@zsh|昭山|KWQ|zhaoshan|zs|2626@zsx|钟山西|ZAZ|zhongshanxi|zsx|2627@zxi|漳县|ZXJ|zhangxian|zx|2628@zyb|资阳北|FYW|ziyangbei|zyb|2629@zyx|张掖西|ZEJ|zhangyexi|zyx|2630@zzb|资中北|WZW|zizhongbei|zzb|2631@zzd|涿州东|ZAP|zhuozhoudong|zzd|2632@zzd|枣庄东|ZNK|zaozhuangdong|zzd|2633@zzd|卓资东|ZDC|zhuozidong|zzd|2634@zzd|郑州东|ZAF|zhengzhoudong|zzd|2635@zzn|株洲南|KVQ|zhuzhounan|zzn|2636'; +$data=explode("|", $data); +$num=count($data)-5; +$no_station=array(); +$s=""; +$j=0; +for($i=0;$i<$num;$i+=5){ + + $name=preg_replace('# #', '', $data[$i+1]);; + $r=$this->BIZ_train_model->get_train_station_code("TRS_StationCN='".$name."'"); + if(empty($r)){ + ++$j; + $no_station[$i]["name"]=$name; + $no_station[$i]["code"]=$data[$i+2]; + $no_station[$i]["py"]=ucfirst($data[$i+3]); + $s.="@".(46500+$j)."|".$no_station[$i]["code"]."|".$no_station[$i]["py"]."|".$no_station[$i]["name"]."|2|"."\n"; + } +} +var_dump($no_station); +// echo $s; +die; + $data=json_decode($data,true); + + + // // var_dump($data); + // $d=""; + // foreach ($data["result"] as $key => $v) { + // // foreach ($v as $v_code) { + // $d.="$key=>array('name'=>'{$v['name']}','code'=>'{$v['code']}'),"; + // // } + $no_station=array(); + foreach ($data["result"] as $key => $v) { + $r=$this->BIZ_train_model->get_train_station_code("TRS_StationCN='合浦'");var_dump($r);die; + if(empty($r)){ + $no_station[$key]["name"]=$v['name']; + $no_station[$key]["code"]=$v['code']; + } + } + var_dump($no_station); die; + // } + $d=array( + 0=>array('name'=>'北京北','code'=>'VAP'),1=>array('name'=>'北京东','code'=>'BOP'),2=>array('name'=>'北京','code'=>'BJP'),3=>array('name'=>'北京南','code'=>'VNP'),4=>array('name'=>'北京西','code'=>'BXP'),5=>array('name'=>'广州南','code'=>'IZQ'),6=>array('name'=>'重庆北','code'=>'CUW'),7=>array('name'=>'重庆','code'=>'CQW'),8=>array('name'=>'重庆南','code'=>'CRW'),9=>array('name'=>'广州东','code'=>'GGQ'),10=>array('name'=>'上海','code'=>'SHH'),11=>array('name'=>'上海南','code'=>'SNH'),12=>array('name'=>'上海虹桥','code'=>'AOH'),13=>array('name'=>'上海西','code'=>'SXH'),14=>array('name'=>'天津北','code'=>'TBP'),15=>array('name'=>'天津','code'=>'TJP'),16=>array('name'=>'天津南','code'=>'TIP'),17=>array('name'=>'天津西','code'=>'TXP'),18=>array('name'=>'长春','code'=>'CCT'),19=>array('name'=>'长春南','code'=>'CET'),20=>array('name'=>'长春西','code'=>'CRT'),21=>array('name'=>'成都东','code'=>'ICW'),22=>array('name'=>'成都南','code'=>'CNW'),23=>array('name'=>'成都','code'=>'CDW'),24=>array('name'=>'长沙','code'=>'CSQ'),25=>array('name'=>'长沙南','code'=>'CWQ'),26=>array('name'=>'福州','code'=>'FZS'),27=>array('name'=>'福州南','code'=>'FYS'),28=>array('name'=>'贵阳','code'=>'GIW'),29=>array('name'=>'广州','code'=>'GZQ'),30=>array('name'=>'广州西','code'=>'GXQ'),31=>array('name'=>'哈尔滨','code'=>'HBB'),32=>array('name'=>'哈尔滨东','code'=>'VBB'),33=>array('name'=>'哈尔滨西','code'=>'VAB'),34=>array('name'=>'合肥','code'=>'HFH'),35=>array('name'=>'合肥西','code'=>'HTH'),36=>array('name'=>'呼和浩特东','code'=>'NDC'),37=>array('name'=>'呼和浩特','code'=>'HHC'),38=>array('name'=>'海口东','code'=>'HMQ'),39=>array('name'=>'海口','code'=>'VUQ'),40=>array('name'=>'杭州东','code'=>'HGH'),41=>array('name'=>'杭州','code'=>'HZH'),42=>array('name'=>'杭州南','code'=>'XHH'),43=>array('name'=>'济南','code'=>'JNK'),44=>array('name'=>'济南东','code'=>'JAK'),45=>array('name'=>'济南西','code'=>'JGK'),46=>array('name'=>'昆明','code'=>'KMM'),47=>array('name'=>'昆明西','code'=>'KXM'),48=>array('name'=>'拉萨','code'=>'LSO'),49=>array('name'=>'兰州东','code'=>'LVJ'),50=>array('name'=>'兰州','code'=>'LZJ'),51=>array('name'=>'兰州西','code'=>'LAJ'),52=>array('name'=>'南昌','code'=>'NCG'),53=>array('name'=>'南京','code'=>'NJH'),54=>array('name'=>'南京南','code'=>'NKH'),55=>array('name'=>'南宁','code'=>'NNZ'),56=>array('name'=>'石家庄北','code'=>'VVP'),57=>array('name'=>'石家庄','code'=>'SJP'),58=>array('name'=>'沈阳','code'=>'SYT'),59=>array('name'=>'沈阳北','code'=>'SBT'),60=>array('name'=>'沈阳东','code'=>'SDT'),61=>array('name'=>'太原北','code'=>'TBV'),62=>array('name'=>'太原东','code'=>'TDV'),63=>array('name'=>'太原','code'=>'TYV'),64=>array('name'=>'武汉','code'=>'WHN'),65=>array('name'=>'王家营西','code'=>'KNM'),66=>array('name'=>'乌鲁木齐南','code'=>'WMR'),67=>array('name'=>'西安北','code'=>'EAY'),68=>array('name'=>'西安','code'=>'XAY'),69=>array('name'=>'西安南','code'=>'CAY'),70=>array('name'=>'西宁','code'=>'XNO'),71=>array('name'=>'银川','code'=>'YIJ'),72=>array('name'=>'郑州','code'=>'ZZF'),73=>array('name'=>'阿尔山','code'=>'ART'),74=>array('name'=>'安康','code'=>'AKY'),75=>array('name'=>'阿克苏','code'=>'ASR'),76=>array('name'=>'阿里河','code'=>'AHX'),77=>array('name'=>'阿拉山口','code'=>'AKR'),78=>array('name'=>'安平','code'=>'APT'),79=>array('name'=>'安庆','code'=>'AQH'),80=>array('name'=>'安顺','code'=>'ASW'),81=>array('name'=>'鞍山','code'=>'AST'),82=>array('name'=>'安阳','code'=>'AYF'),83=>array('name'=>'北安','code'=>'BAB'),84=>array('name'=>'蚌埠','code'=>'BBH'),85=>array('name'=>'白城','code'=>'BCT'),86=>array('name'=>'北海','code'=>'BHZ'),87=>array('name'=>'白河','code'=>'BEL'),88=>array('name'=>'白涧','code'=>'BAP'),89=>array('name'=>'宝鸡','code'=>'BJY'),90=>array('name'=>'滨江','code'=>'BJB'),91=>array('name'=>'博克图','code'=>'BKX'),92=>array('name'=>'百色','code'=>'BIZ'),93=>array('name'=>'白山市','code'=>'HJL'),94=>array('name'=>'北台','code'=>'BTT'),95=>array('name'=>'包头东','code'=>'BDC'),96=>array('name'=>'包头','code'=>'BTC'),97=>array('name'=>'北屯市','code'=>'BXR'),98=>array('name'=>'本溪','code'=>'BXT'),99=>array('name'=>'白云鄂博','code'=>'BEC'),100=>array('name'=>'白银西','code'=>'BXJ'),101=>array('name'=>'亳州','code'=>'BZH'),102=>array('name'=>'赤壁','code'=>'CBN'),103=>array('name'=>'常德','code'=>'VGQ'),104=>array('name'=>'承德','code'=>'CDP'),105=>array('name'=>'长甸','code'=>'CDT'),106=>array('name'=>'赤峰','code'=>'CFD'),107=>array('name'=>'茶陵','code'=>'CDG'),108=>array('name'=>'苍南','code'=>'CEH'),109=>array('name'=>'昌平','code'=>'CPP'),110=>array('name'=>'崇仁','code'=>'CRG'),111=>array('name'=>'昌图','code'=>'CTT'),112=>array('name'=>'长汀镇','code'=>'CDB'),113=>array('name'=>'曹县','code'=>'CXK'),114=>array('name'=>'楚雄','code'=>'COM'),115=>array('name'=>'陈相屯','code'=>'CXT'),116=>array('name'=>'长治北','code'=>'CBF'),117=>array('name'=>'长征','code'=>'CZJ'),118=>array('name'=>'池州','code'=>'IYH'),119=>array('name'=>'常州','code'=>'CZH'),120=>array('name'=>'郴州','code'=>'CZQ'),121=>array('name'=>'长治','code'=>'CZF'),122=>array('name'=>'沧州','code'=>'COP'),123=>array('name'=>'崇左','code'=>'CZZ'),124=>array('name'=>'大安北','code'=>'RNT'),125=>array('name'=>'大成','code'=>'DCT'),126=>array('name'=>'丹东','code'=>'DUT'),127=>array('name'=>'东方红','code'=>'DFB'),128=>array('name'=>'东莞东','code'=>'DMQ'),129=>array('name'=>'大虎山','code'=>'DHD'),130=>array('name'=>'敦煌','code'=>'DHJ'),131=>array('name'=>'敦化','code'=>'DHL'),132=>array('name'=>'德惠','code'=>'DHT'),133=>array('name'=>'东京城','code'=>'DJB'),134=>array('name'=>'大涧','code'=>'DFP'),135=>array('name'=>'都江堰','code'=>'DDW'),136=>array('name'=>'大连北','code'=>'DFT'),137=>array('name'=>'大理','code'=>'DKM'),138=>array('name'=>'大连','code'=>'DLT'),139=>array('name'=>'定南','code'=>'DNG'),140=>array('name'=>'大庆','code'=>'DZX'),141=>array('name'=>'东胜','code'=>'DOC'),142=>array('name'=>'大石桥','code'=>'DQT'),143=>array('name'=>'大同','code'=>'DTV'),144=>array('name'=>'东营','code'=>'DPK'),145=>array('name'=>'大杨树','code'=>'DUX'),146=>array('name'=>'都匀','code'=>'RYW'),147=>array('name'=>'邓州','code'=>'DOF'),148=>array('name'=>'达州','code'=>'RXW'),149=>array('name'=>'德州','code'=>'DZP'),150=>array('name'=>'额济纳','code'=>'EJC'),151=>array('name'=>'二连','code'=>'RLC'),152=>array('name'=>'恩施','code'=>'ESN'),153=>array('name'=>'福鼎','code'=>'FES'),154=>array('name'=>'风陵渡','code'=>'FLV'),155=>array('name'=>'涪陵','code'=>'FLW'),156=>array('name'=>'富拉尔基','code'=>'FRX'),157=>array('name'=>'抚顺北','code'=>'FET'),158=>array('name'=>'佛山','code'=>'FSQ'),159=>array('name'=>'阜新','code'=>'FXD'),160=>array('name'=>'阜阳','code'=>'FYH'),161=>array('name'=>'格尔木','code'=>'GRO'),162=>array('name'=>'广汉','code'=>'GHW'),163=>array('name'=>'古交','code'=>'GJV'),164=>array('name'=>'桂林北','code'=>'GBZ'),165=>array('name'=>'古莲','code'=>'GRX'),166=>array('name'=>'桂林','code'=>'GLZ'),167=>array('name'=>'固始','code'=>'GXN'),168=>array('name'=>'广水','code'=>'GSN'),169=>array('name'=>'干塘','code'=>'GNJ'),170=>array('name'=>'广元','code'=>'GYW'),171=>array('name'=>'广州北','code'=>'GBQ'),172=>array('name'=>'赣州','code'=>'GZG'),173=>array('name'=>'公主岭','code'=>'GLT'),174=>array('name'=>'公主岭南','code'=>'GBT'),175=>array('name'=>'淮安','code'=>'AUH'),176=>array('name'=>'鹤北','code'=>'HMB'),177=>array('name'=>'淮北','code'=>'HRH'),178=>array('name'=>'淮滨','code'=>'HVN'),179=>array('name'=>'河边','code'=>'HBV'),180=>array('name'=>'潢川','code'=>'KCN'),181=>array('name'=>'韩城','code'=>'HCY'),182=>array('name'=>'邯郸','code'=>'HDP'),183=>array('name'=>'横道河子','code'=>'HDB'),184=>array('name'=>'鹤岗','code'=>'HGB'),185=>array('name'=>'皇姑屯','code'=>'HTT'),186=>array('name'=>'红果','code'=>'HEM'),187=>array('name'=>'黑河','code'=>'HJB'),188=>array('name'=>'怀化','code'=>'HHQ'),189=>array('name'=>'汉口','code'=>'HKN'),190=>array('name'=>'葫芦岛','code'=>'HLD'),191=>array('name'=>'海拉尔','code'=>'HRX'),192=>array('name'=>'霍林郭勒','code'=>'HWD'),193=>array('name'=>'海伦','code'=>'HLB'),194=>array('name'=>'侯马','code'=>'HMV'),195=>array('name'=>'哈密','code'=>'HMR'),196=>array('name'=>'淮南','code'=>'HAH'),197=>array('name'=>'桦南','code'=>'HNB'),198=>array('name'=>'海宁西','code'=>'EUH'),199=>array('name'=>'鹤庆','code'=>'HQM'),200=>array('name'=>'怀柔北','code'=>'HBP'),201=>array('name'=>'怀柔','code'=>'HRP'),202=>array('name'=>'黄石东','code'=>'OSN'),203=>array('name'=>'华山','code'=>'HSY'),204=>array('name'=>'黄石','code'=>'HSN'),205=>array('name'=>'黄山','code'=>'HKH'),206=>array('name'=>'衡水','code'=>'HSP'),207=>array('name'=>'衡阳','code'=>'HYQ'),208=>array('name'=>'菏泽','code'=>'HIK'),209=>array('name'=>'贺州','code'=>'HXZ'),210=>array('name'=>'汉中','code'=>'HOY'),211=>array('name'=>'惠州','code'=>'HCQ'),212=>array('name'=>'吉安','code'=>'VAG'),213=>array('name'=>'集安','code'=>'JAL'),214=>array('name'=>'江边村','code'=>'JBG'),215=>array('name'=>'晋城','code'=>'JCF'),216=>array('name'=>'金城江','code'=>'JJZ'),217=>array('name'=>'景德镇','code'=>'JCG'),218=>array('name'=>'嘉峰','code'=>'JFF'),219=>array('name'=>'加格达奇','code'=>'JGX'),220=>array('name'=>'井冈山','code'=>'JGG'),221=>array('name'=>'蛟河','code'=>'JHL'),222=>array('name'=>'金华南','code'=>'RNH'),223=>array('name'=>'金华','code'=>'JBH'),224=>array('name'=>'九江','code'=>'JJG'),225=>array('name'=>'吉林','code'=>'JLL'),226=>array('name'=>'荆门','code'=>'JMN'),227=>array('name'=>'佳木斯','code'=>'JMB'),228=>array('name'=>'济宁','code'=>'JIK'),229=>array('name'=>'集宁南','code'=>'JAC'),230=>array('name'=>'酒泉','code'=>'JQJ'),231=>array('name'=>'江山','code'=>'JUH'),232=>array('name'=>'吉首','code'=>'JIQ'),233=>array('name'=>'九台','code'=>'JTL'),234=>array('name'=>'镜铁山','code'=>'JVJ'),235=>array('name'=>'鸡西','code'=>'JXB'),236=>array('name'=>'蓟县','code'=>'JKP'),237=>array('name'=>'绩溪县','code'=>'JRH'),238=>array('name'=>'嘉峪关','code'=>'JGJ'),239=>array('name'=>'江油','code'=>'JFW'),240=>array('name'=>'锦州','code'=>'JZD'),241=>array('name'=>'金州','code'=>'JZT'),242=>array('name'=>'库尔勒','code'=>'KLR'),243=>array('name'=>'开封','code'=>'KFF'),244=>array('name'=>'岢岚','code'=>'KLV'),245=>array('name'=>'凯里','code'=>'KLW'),246=>array('name'=>'喀什','code'=>'KSR'),247=>array('name'=>'昆山南','code'=>'KNH'),248=>array('name'=>'奎屯','code'=>'KTR'),249=>array('name'=>'开原','code'=>'KYT'),250=>array('name'=>'六安','code'=>'UAH'),251=>array('name'=>'灵宝','code'=>'LBF'),252=>array('name'=>'芦潮港','code'=>'UCH'),253=>array('name'=>'隆昌','code'=>'LCW'),254=>array('name'=>'陆川','code'=>'LKZ'),255=>array('name'=>'利川','code'=>'LCN'),256=>array('name'=>'临川','code'=>'LCG'),257=>array('name'=>'潞城','code'=>'UTP'),258=>array('name'=>'鹿道','code'=>'LDL'),259=>array('name'=>'娄底','code'=>'LDQ'),260=>array('name'=>'临汾','code'=>'LFV'),261=>array('name'=>'良各庄','code'=>'LGP'),262=>array('name'=>'临河','code'=>'LHC'),263=>array('name'=>'漯河','code'=>'LON'),264=>array('name'=>'绿化','code'=>'LWJ'),265=>array('name'=>'隆化','code'=>'UHP'),266=>array('name'=>'丽江','code'=>'LHM'),267=>array('name'=>'临江','code'=>'LQL'),268=>array('name'=>'龙井','code'=>'LJL'),269=>array('name'=>'吕梁','code'=>'LHV'),270=>array('name'=>'醴陵','code'=>'LLG'),271=>array('name'=>'柳林南','code'=>'LKV'),272=>array('name'=>'滦平','code'=>'UPP'),273=>array('name'=>'六盘水','code'=>'UMW'),274=>array('name'=>'灵丘','code'=>'LVV'),275=>array('name'=>'旅顺','code'=>'LST'),276=>array('name'=>'陇西','code'=>'LXJ'),277=>array('name'=>'澧县','code'=>'LEQ'),278=>array('name'=>'兰溪','code'=>'LWH'),279=>array('name'=>'临西','code'=>'UEP'),280=>array('name'=>'龙岩','code'=>'LYS'),281=>array('name'=>'耒阳','code'=>'LYQ'),282=>array('name'=>'洛阳','code'=>'LYF'),283=>array('name'=>'洛阳东','code'=>'LDF'),284=>array('name'=>'连云港东','code'=>'UKH'),285=>array('name'=>'临沂','code'=>'LVK'),286=>array('name'=>'洛阳龙门','code'=>'LLF'),287=>array('name'=>'柳园','code'=>'DHR'),288=>array('name'=>'凌源','code'=>'LYD'),289=>array('name'=>'辽源','code'=>'LYL'),290=>array('name'=>'立志','code'=>'LZX'),291=>array('name'=>'柳州','code'=>'LZZ'),292=>array('name'=>'辽中','code'=>'LZD'),293=>array('name'=>'麻城','code'=>'MCN'),294=>array('name'=>'免渡河','code'=>'MDX'),295=>array('name'=>'牡丹江','code'=>'MDB'),296=>array('name'=>'莫尔道嘎','code'=>'MRX'),297=>array('name'=>'满归','code'=>'MHX'),298=>array('name'=>'明光','code'=>'MGH'),299=>array('name'=>'漠河','code'=>'MVX'),300=>array('name'=>'茂名东','code'=>'MDQ'),301=>array('name'=>'茂名','code'=>'MMZ'),302=>array('name'=>'密山','code'=>'MSB'),303=>array('name'=>'马三家','code'=>'MJT'),304=>array('name'=>'麻尾','code'=>'VAW'),305=>array('name'=>'绵阳','code'=>'MYW'),306=>array('name'=>'梅州','code'=>'MOQ'),307=>array('name'=>'满洲里','code'=>'MLX'),308=>array('name'=>'宁波东','code'=>'NVH'),309=>array('name'=>'宁波','code'=>'NGH'),310=>array('name'=>'南岔','code'=>'NCB'),311=>array('name'=>'南充','code'=>'NCW'),312=>array('name'=>'南丹','code'=>'NDZ'),313=>array('name'=>'南大庙','code'=>'NMP'),314=>array('name'=>'南芬','code'=>'NFT'),315=>array('name'=>'讷河','code'=>'NHX'),316=>array('name'=>'嫩江','code'=>'NGX'),317=>array('name'=>'内江','code'=>'NJW'),318=>array('name'=>'南平','code'=>'NPS'),319=>array('name'=>'南通','code'=>'NUH'),320=>array('name'=>'南阳','code'=>'NFF'),321=>array('name'=>'碾子山','code'=>'NZX'),322=>array('name'=>'平顶山','code'=>'PEN'),323=>array('name'=>'盘锦','code'=>'PVD'),324=>array('name'=>'平凉','code'=>'PIJ'),325=>array('name'=>'平凉南','code'=>'POJ'),326=>array('name'=>'平泉','code'=>'PQP'),327=>array('name'=>'坪石','code'=>'PSQ'),328=>array('name'=>'萍乡','code'=>'PXG'),329=>array('name'=>'凭祥','code'=>'PXZ'),330=>array('name'=>'郫县西','code'=>'PCW'),331=>array('name'=>'攀枝花','code'=>'PRW'),332=>array('name'=>'蕲春','code'=>'QRN'),333=>array('name'=>'青城山','code'=>'QSW'),334=>array('name'=>'青岛','code'=>'QDK'),335=>array('name'=>'清河城','code'=>'QYP'),336=>array('name'=>'黔江','code'=>'QNW'),337=>array('name'=>'曲靖','code'=>'QJM'),338=>array('name'=>'前进镇','code'=>'QEB'),339=>array('name'=>'齐齐哈尔','code'=>'QHX'),340=>array('name'=>'七台河','code'=>'QTB'),341=>array('name'=>'沁县','code'=>'QVV'),342=>array('name'=>'泉州东','code'=>'QRS'),343=>array('name'=>'泉州','code'=>'QYS'),344=>array('name'=>'衢州','code'=>'QEH'),345=>array('name'=>'融安','code'=>'RAZ'),346=>array('name'=>'汝箕沟','code'=>'RQJ'),347=>array('name'=>'瑞金','code'=>'RJG'),348=>array('name'=>'日照','code'=>'RZK'),349=>array('name'=>'双城堡','code'=>'SCB'),350=>array('name'=>'绥芬河','code'=>'SFB'),351=>array('name'=>'韶关东','code'=>'SGQ'),352=>array('name'=>'山海关','code'=>'SHD'),353=>array('name'=>'绥化','code'=>'SHB'),354=>array('name'=>'三间房','code'=>'SFX'),355=>array('name'=>'苏家屯','code'=>'SXT'),356=>array('name'=>'舒兰','code'=>'SLL'),357=>array('name'=>'三明','code'=>'SMS'),358=>array('name'=>'神木','code'=>'OMY'),359=>array('name'=>'三门峡','code'=>'SMF'),360=>array('name'=>'商南','code'=>'ONY'),361=>array('name'=>'遂宁','code'=>'NIW'),362=>array('name'=>'四平','code'=>'SPT'),363=>array('name'=>'商丘','code'=>'SQF'),364=>array('name'=>'上饶','code'=>'SRG'),365=>array('name'=>'韶山','code'=>'SSQ'),366=>array('name'=>'宿松','code'=>'OAH'),367=>array('name'=>'汕头','code'=>'OTQ'),368=>array('name'=>'邵武','code'=>'SWS'),369=>array('name'=>'涉县','code'=>'OEP'),370=>array('name'=>'三亚','code'=>'SEQ'),371=>array('name'=>'邵阳','code'=>'SYQ'),372=>array('name'=>'十堰','code'=>'SNN'),373=>array('name'=>'双鸭山','code'=>'SSB'),374=>array('name'=>'松原','code'=>'VYT'),375=>array('name'=>'深圳','code'=>'SZQ'),376=>array('name'=>'苏州','code'=>'SZH'),377=>array('name'=>'随州','code'=>'SZN'),378=>array('name'=>'宿州','code'=>'OXH'),379=>array('name'=>'朔州','code'=>'SUV'),380=>array('name'=>'深圳西','code'=>'OSQ'),381=>array('name'=>'塘豹','code'=>'TBQ'),382=>array('name'=>'塔尔气','code'=>'TVX'),383=>array('name'=>'潼关','code'=>'TGY'),384=>array('name'=>'塘沽','code'=>'TGP'),385=>array('name'=>'塔河','code'=>'TXX'),386=>array('name'=>'通化','code'=>'THL'),387=>array('name'=>'泰来','code'=>'TLX'),388=>array('name'=>'吐鲁番','code'=>'TFR'),389=>array('name'=>'通辽','code'=>'TLD'),390=>array('name'=>'铁岭','code'=>'TLT'),391=>array('name'=>'陶赖昭','code'=>'TPT'),392=>array('name'=>'图们','code'=>'TML'),393=>array('name'=>'铜仁','code'=>'RDQ'),394=>array('name'=>'唐山北','code'=>'FUP'),395=>array('name'=>'田师府','code'=>'TFT'),396=>array('name'=>'泰山','code'=>'TAK'),397=>array('name'=>'唐山','code'=>'TSP'),398=>array('name'=>'天水','code'=>'TSJ'),399=>array('name'=>'通远堡','code'=>'TYT'),400=>array('name'=>'太阳升','code'=>'TQT'),401=>array('name'=>'泰州','code'=>'UTH'),402=>array('name'=>'桐梓','code'=>'TZW'),403=>array('name'=>'通州西','code'=>'TAP'),404=>array('name'=>'五常','code'=>'WCB'),405=>array('name'=>'武昌','code'=>'WCN'),406=>array('name'=>'瓦房店','code'=>'WDT'),407=>array('name'=>'威海','code'=>'WKK'),408=>array('name'=>'芜湖','code'=>'WHH'),409=>array('name'=>'乌海西','code'=>'WXC'),410=>array('name'=>'吴家屯','code'=>'WJT'),411=>array('name'=>'武隆','code'=>'WLW'),412=>array('name'=>'乌兰浩特','code'=>'WWT'),413=>array('name'=>'渭南','code'=>'WNY'),414=>array('name'=>'威舍','code'=>'WSM'),415=>array('name'=>'歪头山','code'=>'WIT'),416=>array('name'=>'武威','code'=>'WUJ'),417=>array('name'=>'武威南','code'=>'WWJ'),418=>array('name'=>'无锡','code'=>'WXH'),419=>array('name'=>'乌西','code'=>'WXR'),420=>array('name'=>'乌伊岭','code'=>'WPB'),421=>array('name'=>'武夷山','code'=>'WAS'),422=>array('name'=>'万源','code'=>'WYY'),423=>array('name'=>'万州','code'=>'WYW'),424=>array('name'=>'梧州','code'=>'WZZ'),425=>array('name'=>'温州','code'=>'RZH'),426=>array('name'=>'温州南','code'=>'VRH'),427=>array('name'=>'西昌','code'=>'ECW'),428=>array('name'=>'许昌','code'=>'XCF'),429=>array('name'=>'西昌南','code'=>'ENW'),430=>array('name'=>'香坊','code'=>'XFB'),431=>array('name'=>'轩岗','code'=>'XGV'),432=>array('name'=>'兴国','code'=>'EUG'),433=>array('name'=>'宣汉','code'=>'XHY'),434=>array('name'=>'新会','code'=>'EFQ'),435=>array('name'=>'新晃','code'=>'XLQ'),436=>array('name'=>'锡林浩特','code'=>'XTC'),437=>array('name'=>'兴隆县','code'=>'EXP'),438=>array('name'=>'厦门北','code'=>'XKS'),439=>array('name'=>'厦门','code'=>'XMS'),440=>array('name'=>'厦门高崎','code'=>'XBS'),441=>array('name'=>'秀山','code'=>'ETW'),442=>array('name'=>'小市','code'=>'XST'),443=>array('name'=>'向塘','code'=>'XTG'),444=>array('name'=>'宣威','code'=>'XWM'),445=>array('name'=>'新乡','code'=>'XXF'),446=>array('name'=>'信阳','code'=>'XUN'),447=>array('name'=>'咸阳','code'=>'XYY'),448=>array('name'=>'襄阳','code'=>'XFN'),449=>array('name'=>'熊岳城','code'=>'XYT'),450=>array('name'=>'兴义','code'=>'XRZ'),451=>array('name'=>'新沂','code'=>'VIH'),452=>array('name'=>'新余','code'=>'XUG'),453=>array('name'=>'徐州','code'=>'XCH'),454=>array('name'=>'延安','code'=>'YWY'),455=>array('name'=>'宜宾','code'=>'YBW'),456=>array('name'=>'亚布力南','code'=>'YWB'),457=>array('name'=>'叶柏寿','code'=>'YBD'),458=>array('name'=>'宜昌东','code'=>'HAN'),459=>array('name'=>'永川','code'=>'YCW'),460=>array('name'=>'宜昌','code'=>'YCN'),461=>array('name'=>'盐城','code'=>'AFH'),462=>array('name'=>'运城','code'=>'YNV'),463=>array('name'=>'伊春','code'=>'YCB'),464=>array('name'=>'榆次','code'=>'YCV'),465=>array('name'=>'杨村','code'=>'YBP'),466=>array('name'=>'宜春西','code'=>'YCG'),467=>array('name'=>'伊尔施','code'=>'YET'),468=>array('name'=>'燕岗','code'=>'YGW'),469=>array('name'=>'永济','code'=>'YIV'),470=>array('name'=>'延吉','code'=>'YJL'),471=>array('name'=>'营口','code'=>'YKT'),472=>array('name'=>'牙克石','code'=>'YKX'),473=>array('name'=>'阎良','code'=>'YNY'),474=>array('name'=>'玉林','code'=>'YLZ'),475=>array('name'=>'榆林','code'=>'ALY'),476=>array('name'=>'一面坡','code'=>'YPB'),477=>array('name'=>'伊宁','code'=>'YMR'),478=>array('name'=>'阳平关','code'=>'YAY'),479=>array('name'=>'玉屏','code'=>'YZW'),480=>array('name'=>'原平','code'=>'YPV'),481=>array('name'=>'延庆','code'=>'YNP'),482=>array('name'=>'阳泉曲','code'=>'YYV'),483=>array('name'=>'玉泉','code'=>'YQB'),484=>array('name'=>'阳泉','code'=>'AQP'),485=>array('name'=>'玉山','code'=>'YNG'),486=>array('name'=>'营山','code'=>'NUW'),487=>array('name'=>'燕山','code'=>'AOP'),488=>array('name'=>'榆树','code'=>'YRT'),489=>array('name'=>'鹰潭','code'=>'YTG'),490=>array('name'=>'烟台','code'=>'YAK'),491=>array('name'=>'伊图里河','code'=>'YEX'),492=>array('name'=>'玉田县','code'=>'ATP'),493=>array('name'=>'义乌','code'=>'YWH'),494=>array('name'=>'阳新','code'=>'YON'),495=>array('name'=>'义县','code'=>'YXD'),496=>array('name'=>'益阳','code'=>'AEQ'),497=>array('name'=>'岳阳','code'=>'YYQ'),498=>array('name'=>'永州','code'=>'AOQ'),499=>array('name'=>'扬州','code'=>'YLH'),500=>array('name'=>'淄博','code'=>'ZBK'),501=>array('name'=>'镇城底','code'=>'ZDV'),502=>array('name'=>'自贡','code'=>'ZGW'),503=>array('name'=>'珠海','code'=>'ZHQ'),504=>array('name'=>'珠海北','code'=>'ZIQ'),505=>array('name'=>'湛江','code'=>'ZJZ'),506=>array('name'=>'镇江','code'=>'ZJH'),507=>array('name'=>'张家界','code'=>'DIQ'),508=>array('name'=>'张家口','code'=>'ZKP'),509=>array('name'=>'张家口南','code'=>'ZMP'),510=>array('name'=>'周口','code'=>'ZKN'),511=>array('name'=>'哲里木','code'=>'ZLC'),512=>array('name'=>'扎兰屯','code'=>'ZTX'),513=>array('name'=>'驻马店','code'=>'ZDN'),514=>array('name'=>'肇庆','code'=>'ZVQ'),515=>array('name'=>'周水子','code'=>'ZIT'),516=>array('name'=>'昭通','code'=>'ZDW'),517=>array('name'=>'中卫','code'=>'ZWJ'),518=>array('name'=>'资阳','code'=>'ZYW'),519=>array('name'=>'遵义','code'=>'ZIW'),520=>array('name'=>'枣庄','code'=>'ZEK'),521=>array('name'=>'资中','code'=>'ZZW'),522=>array('name'=>'株洲','code'=>'ZZQ'),523=>array('name'=>'枣庄西','code'=>'ZFK'),524=>array('name'=>'昂昂溪','code'=>'AAX'),525=>array('name'=>'阿城','code'=>'ACB'),526=>array('name'=>'安达','code'=>'ADX'),527=>array('name'=>'安德','code'=>'ARW'),528=>array('name'=>'安定','code'=>'ADP'),529=>array('name'=>'安广','code'=>'AGT'),530=>array('name'=>'艾河','code'=>'AHP'),531=>array('name'=>'安化','code'=>'PKQ'),532=>array('name'=>'艾家村','code'=>'AJJ'),533=>array('name'=>'鳌江','code'=>'ARH'),534=>array('name'=>'安家','code'=>'AJB'),535=>array('name'=>'阿金','code'=>'AJD'),536=>array('name'=>'阿克陶','code'=>'AER'),537=>array('name'=>'安口窑','code'=>'AYY'),538=>array('name'=>'敖力布告','code'=>'ALD'),539=>array('name'=>'安龙','code'=>'AUZ'),540=>array('name'=>'阿龙山','code'=>'ASX'),541=>array('name'=>'安陆','code'=>'ALN'),542=>array('name'=>'阿木尔','code'=>'JTX'),543=>array('name'=>'阿南庄','code'=>'AZM'),544=>array('name'=>'安庆西','code'=>'APH'),545=>array('name'=>'鞍山西','code'=>'AXT'),546=>array('name'=>'安塘','code'=>'ATV'),547=>array('name'=>'安亭北','code'=>'ASH'),548=>array('name'=>'阿图什','code'=>'ATR'),549=>array('name'=>'安图','code'=>'ATL'),550=>array('name'=>'安溪','code'=>'AXS'),551=>array('name'=>'博鳌','code'=>'BWQ'),552=>array('name'=>'北碚','code'=>'BPW'),553=>array('name'=>'白壁关','code'=>'BGV'),554=>array('name'=>'蚌埠南','code'=>'BMH'),555=>array('name'=>'巴楚','code'=>'BCR'),556=>array('name'=>'板城','code'=>'BUP'),557=>array('name'=>'北戴河','code'=>'BEP'),558=>array('name'=>'保定','code'=>'BDP'),559=>array('name'=>'宝坻','code'=>'BPP'),560=>array('name'=>'八达岭','code'=>'ILP'),561=>array('name'=>'巴东','code'=>'BNN'),562=>array('name'=>'柏果','code'=>'BGM'),563=>array('name'=>'布海','code'=>'BUT'),564=>array('name'=>'白河东','code'=>'BIY'),565=>array('name'=>'贲红','code'=>'BVC'),566=>array('name'=>'宝华山','code'=>'BWH'),567=>array('name'=>'白河县','code'=>'BEY'),568=>array('name'=>'白芨沟','code'=>'BJJ'),569=>array('name'=>'碧鸡关','code'=>'BJM'),570=>array('name'=>'北滘','code'=>'IBQ'),571=>array('name'=>'碧江','code'=>'BLQ'),572=>array('name'=>'白鸡坡','code'=>'BBM'),573=>array('name'=>'笔架山','code'=>'BSB'),574=>array('name'=>'八角台','code'=>'BTD'),575=>array('name'=>'保康','code'=>'BKD'),576=>array('name'=>'白奎堡','code'=>'BKB'),577=>array('name'=>'白狼','code'=>'BAT'),578=>array('name'=>'百浪','code'=>'BRZ'),579=>array('name'=>'博乐','code'=>'BOR'),580=>array('name'=>'宝拉格','code'=>'BQC'),581=>array('name'=>'巴林','code'=>'BLX'),582=>array('name'=>'宝林','code'=>'BNB'),583=>array('name'=>'北流','code'=>'BOZ'),584=>array('name'=>'勃利','code'=>'BLB'),585=>array('name'=>'布列开','code'=>'BLR'),586=>array('name'=>'宝龙山','code'=>'BND'),587=>array('name'=>'百里峡','code'=>'AAP'),588=>array('name'=>'八面城','code'=>'BMD'),589=>array('name'=>'班猫箐','code'=>'BNM'),590=>array('name'=>'八面通','code'=>'BMB'),591=>array('name'=>'北马圈子','code'=>'BRP'),592=>array('name'=>'北票南','code'=>'RPD'),593=>array('name'=>'白旗','code'=>'BQP'),594=>array('name'=>'宝泉岭','code'=>'BQB'),595=>array('name'=>'白泉','code'=>'BQL'),596=>array('name'=>'白沙','code'=>'BSW'),597=>array('name'=>'巴山','code'=>'BAY'),598=>array('name'=>'白水江','code'=>'BSY'),599=>array('name'=>'白沙坡','code'=>'BPM'),600=>array('name'=>'白石山','code'=>'BAL'),601=>array('name'=>'白水镇','code'=>'BUM'),602=>array('name'=>'坂田','code'=>'BTQ'),603=>array('name'=>'泊头','code'=>'BZP'),604=>array('name'=>'北屯','code'=>'BYP'),605=>array('name'=>'本溪湖','code'=>'BHT'),606=>array('name'=>'博兴','code'=>'BXK'),607=>array('name'=>'八仙筒','code'=>'VXD'),608=>array('name'=>'白音察干','code'=>'BYC'),609=>array('name'=>'背荫河','code'=>'BYB'),610=>array('name'=>'北营','code'=>'BIV'),611=>array('name'=>'巴彦高勒','code'=>'BAC'),612=>array('name'=>'白音他拉','code'=>'BID'),613=>array('name'=>'鲅鱼圈','code'=>'BYT'),614=>array('name'=>'白银市','code'=>'BNJ'),615=>array('name'=>'白音胡硕','code'=>'BCD'),616=>array('name'=>'巴中','code'=>'IEW'),617=>array('name'=>'霸州','code'=>'RMP'),618=>array('name'=>'北宅','code'=>'BVP'),619=>array('name'=>'赤壁北','code'=>'CIN'),620=>array('name'=>'查布嘎','code'=>'CBC'),621=>array('name'=>'长城','code'=>'CEJ'),622=>array('name'=>'长冲','code'=>'CCM'),623=>array('name'=>'承德东','code'=>'CCP'),624=>array('name'=>'赤峰西','code'=>'CID'),625=>array('name'=>'嵯岗','code'=>'CAX'),626=>array('name'=>'柴岗','code'=>'CGT'),627=>array('name'=>'长葛','code'=>'CEF'),628=>array('name'=>'柴沟堡','code'=>'CGV'),629=>array('name'=>'城固','code'=>'CGY'),630=>array('name'=>'陈官营','code'=>'CAJ'),631=>array('name'=>'成高子','code'=>'CZB'),632=>array('name'=>'草海','code'=>'WBW'),633=>array('name'=>'柴河','code'=>'CHB'),634=>array('name'=>'册亨','code'=>'CHZ'),635=>array('name'=>'草河口','code'=>'CKT'),636=>array('name'=>'崔黄口','code'=>'CHP'),637=>array('name'=>'巢湖','code'=>'CIH'),638=>array('name'=>'蔡家沟','code'=>'CJT'),639=>array('name'=>'成吉思汗','code'=>'CJX'),640=>array('name'=>'岔江','code'=>'CAM'),641=>array('name'=>'蔡家坡','code'=>'CJY'),642=>array('name'=>'昌乐','code'=>'CLK'),643=>array('name'=>'超梁沟','code'=>'CYP'),644=>array('name'=>'慈利','code'=>'CUQ'),645=>array('name'=>'昌黎','code'=>'CLP'),646=>array('name'=>'长岭子','code'=>'CLT'),647=>array('name'=>'晨明','code'=>'CMB'),648=>array('name'=>'长农','code'=>'CNJ'),649=>array('name'=>'昌平北','code'=>'VBP'),650=>array('name'=>'常平','code'=>'DAQ'),651=>array('name'=>'长坡岭','code'=>'CPM'),652=>array('name'=>'辰清','code'=>'CQB'),653=>array('name'=>'蔡山','code'=>'CON'),654=>array('name'=>'楚山','code'=>'CSB'),655=>array('name'=>'长寿','code'=>'EFW'),656=>array('name'=>'磁山','code'=>'CSP'),657=>array('name'=>'苍石','code'=>'CST'),658=>array('name'=>'草市','code'=>'CSL'),659=>array('name'=>'察素齐','code'=>'CSC'),660=>array('name'=>'长山屯','code'=>'CVT'),661=>array('name'=>'长汀','code'=>'CES'),662=>array('name'=>'昌图西','code'=>'CPT'),663=>array('name'=>'春湾','code'=>'CQQ'),664=>array('name'=>'磁县','code'=>'CIP'),665=>array('name'=>'岑溪','code'=>'CNZ'),666=>array('name'=>'辰溪','code'=>'CXQ'),667=>array('name'=>'磁西','code'=>'CRP'),668=>array('name'=>'长兴南','code'=>'CFH'),669=>array('name'=>'磁窑','code'=>'CYK'),670=>array('name'=>'朝阳','code'=>'CYD'),671=>array('name'=>'春阳','code'=>'CAL'),672=>array('name'=>'城阳','code'=>'CEK'),673=>array('name'=>'创业村','code'=>'CEX'),674=>array('name'=>'朝阳川','code'=>'CYL'),675=>array('name'=>'朝阳地','code'=>'CDD'),676=>array('name'=>'长垣','code'=>'CYF'),677=>array('name'=>'朝阳镇','code'=>'CZL'),678=>array('name'=>'滁州北','code'=>'CUH'),679=>array('name'=>'常州北','code'=>'ESH'),680=>array('name'=>'滁州','code'=>'CXH'),681=>array('name'=>'潮州','code'=>'CKQ'),682=>array('name'=>'常庄','code'=>'CVK'),683=>array('name'=>'曹子里','code'=>'CFP'),684=>array('name'=>'车转湾','code'=>'CWM'),685=>array('name'=>'郴州西','code'=>'ICQ'),686=>array('name'=>'沧州西','code'=>'CBP'),687=>array('name'=>'德安','code'=>'DAG'),688=>array('name'=>'大安','code'=>'RAT'),689=>array('name'=>'大坝','code'=>'DBJ'),690=>array('name'=>'大板','code'=>'DBC'),691=>array('name'=>'大巴','code'=>'DBD'),692=>array('name'=>'到保','code'=>'RBT'),693=>array('name'=>'定边','code'=>'DYJ'),694=>array('name'=>'东边井','code'=>'DBB'),695=>array('name'=>'德伯斯','code'=>'RDT'),696=>array('name'=>'打柴沟','code'=>'DGJ'),697=>array('name'=>'德昌','code'=>'DVW'),698=>array('name'=>'滴道','code'=>'DDB'),699=>array('name'=>'大磴沟','code'=>'DKJ'),700=>array('name'=>'刀尔登','code'=>'DRD'),701=>array('name'=>'得耳布尔','code'=>'DRX'),702=>array('name'=>'东方','code'=>'UFQ'),703=>array('name'=>'丹凤','code'=>'DGY'),704=>array('name'=>'东丰','code'=>'DIL'),705=>array('name'=>'都格','code'=>'DMM'),706=>array('name'=>'大官屯','code'=>'DTT'),707=>array('name'=>'大关','code'=>'RGW'),708=>array('name'=>'东光','code'=>'DGP'),709=>array('name'=>'东海','code'=>'DHB'),710=>array('name'=>'大灰厂','code'=>'DHP'),711=>array('name'=>'大红旗','code'=>'DQD'),712=>array('name'=>'大禾塘','code'=>'SOQ'),713=>array('name'=>'东海县','code'=>'DQH'),714=>array('name'=>'德惠西','code'=>'DXT'),715=>array('name'=>'达家沟','code'=>'DJT'),716=>array('name'=>'东津','code'=>'DKB'),717=>array('name'=>'杜家','code'=>'DJL'),718=>array('name'=>'大口屯','code'=>'DKP'),719=>array('name'=>'东来','code'=>'RVD'),720=>array('name'=>'德令哈','code'=>'DHO'),721=>array('name'=>'大陆号','code'=>'DLC'),722=>array('name'=>'带岭','code'=>'DLB'),723=>array('name'=>'大林','code'=>'DLD'),724=>array('name'=>'达拉特旗','code'=>'DIC'),725=>array('name'=>'独立屯','code'=>'DTX'),726=>array('name'=>'豆罗','code'=>'DLV'),727=>array('name'=>'达拉特西','code'=>'DNC'),728=>array('name'=>'东明村','code'=>'DMD'),729=>array('name'=>'洞庙河','code'=>'DEP'),730=>array('name'=>'东明县','code'=>'DNF'),731=>array('name'=>'大拟','code'=>'DNZ'),732=>array('name'=>'大平房','code'=>'DPD'),733=>array('name'=>'大盘石','code'=>'RPP'),734=>array('name'=>'大埔','code'=>'DPI'),735=>array('name'=>'大堡','code'=>'DVT'),736=>array('name'=>'大庆东','code'=>'LFX'),737=>array('name'=>'大其拉哈','code'=>'DQX'),738=>array('name'=>'道清','code'=>'DML'),739=>array('name'=>'对青山','code'=>'DQB'),740=>array('name'=>'德清西','code'=>'MOH'),741=>array('name'=>'大庆西','code'=>'RHX'),742=>array('name'=>'东升','code'=>'DRQ'),743=>array('name'=>'独山','code'=>'RWW'),744=>array('name'=>'砀山','code'=>'DKH'),745=>array('name'=>'登沙河','code'=>'DWT'),746=>array('name'=>'读书铺','code'=>'DPM'),747=>array('name'=>'大石头','code'=>'DSL'),748=>array('name'=>'东胜西','code'=>'DYC'),749=>array('name'=>'大石寨','code'=>'RZT'),750=>array('name'=>'东台','code'=>'DBH'),751=>array('name'=>'定陶','code'=>'DQK'),752=>array('name'=>'灯塔','code'=>'DGT'),753=>array('name'=>'大田边','code'=>'DBM'),754=>array('name'=>'东通化','code'=>'DTL'),755=>array('name'=>'丹徒','code'=>'RUH'),756=>array('name'=>'大屯','code'=>'DNT'),757=>array('name'=>'东湾','code'=>'DRJ'),758=>array('name'=>'大武口','code'=>'DFJ'),759=>array('name'=>'低窝铺','code'=>'DWJ'),760=>array('name'=>'大王滩','code'=>'DZZ'),761=>array('name'=>'大湾子','code'=>'DFM'),762=>array('name'=>'大兴沟','code'=>'DXL'),763=>array('name'=>'大兴','code'=>'DXX'),764=>array('name'=>'定西','code'=>'DSJ'),765=>array('name'=>'甸心','code'=>'DXM'),766=>array('name'=>'东乡','code'=>'DXG'),767=>array('name'=>'代县','code'=>'DKV'),768=>array('name'=>'定襄','code'=>'DXV'),769=>array('name'=>'东戌','code'=>'RXP'),770=>array('name'=>'东辛庄','code'=>'DXD'),771=>array('name'=>'德阳','code'=>'DYW'),772=>array('name'=>'丹阳','code'=>'DYH'),773=>array('name'=>'大雁','code'=>'DYX'),774=>array('name'=>'当阳','code'=>'DYN'),775=>array('name'=>'丹阳北','code'=>'EXH'),776=>array('name'=>'大英东','code'=>'IAW'),777=>array('name'=>'东淤地','code'=>'DBV'),778=>array('name'=>'大营','code'=>'DYV'),779=>array('name'=>'定远','code'=>'EWH'),780=>array('name'=>'岱岳','code'=>'RYV'),781=>array('name'=>'大元','code'=>'DYZ'),782=>array('name'=>'大营镇','code'=>'DJP'),783=>array('name'=>'大营子','code'=>'DZD'),784=>array('name'=>'大战场','code'=>'DTJ'),785=>array('name'=>'德州东','code'=>'DIP'),786=>array('name'=>'低庄','code'=>'DVQ'),787=>array('name'=>'东镇','code'=>'DNV'),788=>array('name'=>'道州','code'=>'DFZ'),789=>array('name'=>'东至','code'=>'DCH'),790=>array('name'=>'东庄','code'=>'DZV'),791=>array('name'=>'兑镇','code'=>'DWV'),792=>array('name'=>'豆庄','code'=>'ROP'),793=>array('name'=>'定州','code'=>'DXP'),794=>array('name'=>'大竹园','code'=>'DZY'),795=>array('name'=>'大杖子','code'=>'DAP'),796=>array('name'=>'豆张庄','code'=>'RZP'),797=>array('name'=>'峨边','code'=>'EBW'),798=>array('name'=>'二道沟门','code'=>'RDP'),799=>array('name'=>'二道湾','code'=>'RDX'),800=>array('name'=>'鄂尔多斯','code'=>'EEC'),801=>array('name'=>'二龙','code'=>'RLD'),802=>array('name'=>'二龙山屯','code'=>'ELA'),803=>array('name'=>'峨眉','code'=>'EMW'),804=>array('name'=>'二密河','code'=>'RML'),805=>array('name'=>'二营','code'=>'RYJ'),806=>array('name'=>'鄂州','code'=>'ECN'),807=>array('name'=>'福安','code'=>'FAS'),808=>array('name'=>'丰城','code'=>'FCG'),809=>array('name'=>'丰城南','code'=>'FNG'),810=>array('name'=>'肥东','code'=>'FIH'),811=>array('name'=>'发耳','code'=>'FEM'),812=>array('name'=>'富海','code'=>'FHX'),813=>array('name'=>'福海','code'=>'FHR'),814=>array('name'=>'凤凰城','code'=>'FHT'),815=>array('name'=>'奉化','code'=>'FHH'),816=>array('name'=>'富锦','code'=>'FIB'),817=>array('name'=>'范家屯','code'=>'FTT'),818=>array('name'=>'福利区','code'=>'FLJ'),819=>array('name'=>'福利屯','code'=>'FTB'),820=>array('name'=>'丰乐镇','code'=>'FZB'),821=>array('name'=>'阜南','code'=>'FNH'),822=>array('name'=>'阜宁','code'=>'AKH'),823=>array('name'=>'抚宁','code'=>'FNP'),824=>array('name'=>'福清','code'=>'FQS'),825=>array('name'=>'福泉','code'=>'VMW'),826=>array('name'=>'丰水村','code'=>'FSJ'),827=>array('name'=>'丰顺','code'=>'FUQ'),828=>array('name'=>'繁峙','code'=>'FSV'),829=>array('name'=>'抚顺','code'=>'FST'),830=>array('name'=>'福山口','code'=>'FKP'),831=>array('name'=>'扶绥','code'=>'FSZ'),832=>array('name'=>'冯屯','code'=>'FTX'),833=>array('name'=>'浮图峪','code'=>'FYP'),834=>array('name'=>'富县东','code'=>'FDY'),835=>array('name'=>'凤县','code'=>'FXY'),836=>array('name'=>'富县','code'=>'FEY'),837=>array('name'=>'费县','code'=>'FXK'),838=>array('name'=>'凤阳','code'=>'FUH'),839=>array('name'=>'汾阳','code'=>'FAV'),840=>array('name'=>'扶余北','code'=>'FBT'),841=>array('name'=>'分宜','code'=>'FYG'),842=>array('name'=>'富源','code'=>'FYM'),843=>array('name'=>'扶余','code'=>'FYT'),844=>array('name'=>'富裕','code'=>'FYX'),845=>array('name'=>'抚州北','code'=>'FBG'),846=>array('name'=>'凤州','code'=>'FZY'),847=>array('name'=>'丰镇','code'=>'FZC'),848=>array('name'=>'范镇','code'=>'VZK'),849=>array('name'=>'固安','code'=>'GFP'),850=>array('name'=>'广安','code'=>'VJW'),851=>array('name'=>'高碑店','code'=>'GBP'),852=>array('name'=>'沟帮子','code'=>'GBD'),853=>array('name'=>'甘草店','code'=>'GDJ'),854=>array('name'=>'谷城','code'=>'GCN'),855=>array('name'=>'藁城','code'=>'GEP'),856=>array('name'=>'高村','code'=>'GCV'),857=>array('name'=>'古城镇','code'=>'GZB'),858=>array('name'=>'广德','code'=>'GRH'),859=>array('name'=>'贵定','code'=>'GTW'),860=>array('name'=>'贵定南','code'=>'IDW'),861=>array('name'=>'古东','code'=>'GDV'),862=>array('name'=>'贵港','code'=>'GGZ'),863=>array('name'=>'官高','code'=>'GVP'),864=>array('name'=>'葛根庙','code'=>'GGT'),865=>array('name'=>'干沟','code'=>'GGL'),866=>array('name'=>'甘谷','code'=>'GGJ'),867=>array('name'=>'高各庄','code'=>'GGP'),868=>array('name'=>'甘河','code'=>'GAX'),869=>array('name'=>'根河','code'=>'GEX'),870=>array('name'=>'郭家店','code'=>'GDT'),871=>array('name'=>'孤家子','code'=>'GKT'),872=>array('name'=>'古浪','code'=>'GLJ'),873=>array('name'=>'皋兰','code'=>'GEJ'),874=>array('name'=>'高楼房','code'=>'GFM'),875=>array('name'=>'归流河','code'=>'GHT'),876=>array('name'=>'关林','code'=>'GLF'),877=>array('name'=>'甘洛','code'=>'VOW'),878=>array('name'=>'郭磊庄','code'=>'GLP'),879=>array('name'=>'高密','code'=>'GMK'),880=>array('name'=>'公庙子','code'=>'GMC'),881=>array('name'=>'工农湖','code'=>'GRT'),882=>array('name'=>'广宁寺','code'=>'GNT'),883=>array('name'=>'广南卫','code'=>'GNM'),884=>array('name'=>'高平','code'=>'GPF'),885=>array('name'=>'甘泉北','code'=>'GEY'),886=>array('name'=>'共青城','code'=>'GAG'),887=>array('name'=>'甘旗卡','code'=>'GQD'),888=>array('name'=>'甘泉','code'=>'GQY'),889=>array('name'=>'高桥镇','code'=>'GZD'),890=>array('name'=>'赶水','code'=>'GSW'),891=>array('name'=>'灌水','code'=>'GST'),892=>array('name'=>'孤山口','code'=>'GSP'),893=>array('name'=>'果松','code'=>'GSL'),894=>array('name'=>'高山子','code'=>'GSD'),895=>array('name'=>'嘎什甸子','code'=>'GXD'),896=>array('name'=>'高台','code'=>'GTJ'),897=>array('name'=>'高滩','code'=>'GAY'),898=>array('name'=>'古田','code'=>'GTS'),899=>array('name'=>'官厅','code'=>'GTP'),900=>array('name'=>'官厅西','code'=>'KEP'),901=>array('name'=>'贵溪','code'=>'GXG'),902=>array('name'=>'涡阳','code'=>'GYH'),903=>array('name'=>'巩义','code'=>'GXF'),904=>array('name'=>'高邑','code'=>'GIP'),905=>array('name'=>'巩义南','code'=>'GYF'),906=>array('name'=>'广元南','code'=>'GAW'),907=>array('name'=>'固原','code'=>'GUJ'),908=>array('name'=>'菇园','code'=>'GYL'),909=>array('name'=>'公营子','code'=>'GYD'),910=>array('name'=>'光泽','code'=>'GZS'),911=>array('name'=>'古镇','code'=>'GNQ'),912=>array('name'=>'瓜州','code'=>'GZJ'),913=>array('name'=>'高州','code'=>'GSQ'),914=>array('name'=>'固镇','code'=>'GEH'),915=>array('name'=>'盖州','code'=>'GXT'),916=>array('name'=>'官字井','code'=>'GOT'),917=>array('name'=>'革镇堡','code'=>'GZT'),918=>array('name'=>'冠豸山','code'=>'GSS'),919=>array('name'=>'盖州西','code'=>'GAT'),920=>array('name'=>'红安','code'=>'HWN'),921=>array('name'=>'淮安南','code'=>'AMH'),922=>array('name'=>'红安西','code'=>'VXN'),923=>array('name'=>'海安县','code'=>'HIH'),924=>array('name'=>'黄柏','code'=>'HBL'),925=>array('name'=>'海北','code'=>'HEB'),926=>array('name'=>'鹤壁','code'=>'HAF'),927=>array('name'=>'华城','code'=>'VCQ'),928=>array('name'=>'合川','code'=>'WKW'),929=>array('name'=>'河唇','code'=>'HCZ'),930=>array('name'=>'汉川','code'=>'HCN'),931=>array('name'=>'海城','code'=>'HCT'),932=>array('name'=>'黑冲滩','code'=>'HCJ'),933=>array('name'=>'黄村','code'=>'HCP'),934=>array('name'=>'海城西','code'=>'HXT'),935=>array('name'=>'化德','code'=>'HGC'),936=>array('name'=>'洪洞','code'=>'HDV'),937=>array('name'=>'霍尔果斯','code'=>'HFR'),938=>array('name'=>'横峰','code'=>'HFG'),939=>array('name'=>'韩府湾','code'=>'HXJ'),940=>array('name'=>'汉沽','code'=>'HGP'),941=>array('name'=>'红光镇','code'=>'IGW'),942=>array('name'=>'浑河','code'=>'HHT'),943=>array('name'=>'红花沟','code'=>'VHD'),944=>array('name'=>'黄花筒','code'=>'HUD'),945=>array('name'=>'贺家店','code'=>'HJJ'),946=>array('name'=>'和静','code'=>'HJR'),947=>array('name'=>'红江','code'=>'HFM'),948=>array('name'=>'黑井','code'=>'HIM'),949=>array('name'=>'获嘉','code'=>'HJF'),950=>array('name'=>'河津','code'=>'HJV'),951=>array('name'=>'涵江','code'=>'HJS'),952=>array('name'=>'华家','code'=>'HJT'),953=>array('name'=>'杭锦后旗','code'=>'HDC'),954=>array('name'=>'河间西','code'=>'HXP'),955=>array('name'=>'花家庄','code'=>'HJM'),956=>array('name'=>'河口南','code'=>'HKJ'),957=>array('name'=>'黄口','code'=>'KOH'),958=>array('name'=>'湖口','code'=>'HKG'),959=>array('name'=>'呼兰','code'=>'HUB'),960=>array('name'=>'葫芦岛北','code'=>'HPD'),961=>array('name'=>'浩良河','code'=>'HHB'),962=>array('name'=>'哈拉海','code'=>'HIT'),963=>array('name'=>'鹤立','code'=>'HOB'),964=>array('name'=>'桦林','code'=>'HIB'),965=>array('name'=>'黄陵','code'=>'ULY'),966=>array('name'=>'海林','code'=>'HRB'),967=>array('name'=>'虎林','code'=>'VLB'),968=>array('name'=>'寒岭','code'=>'HAT'),969=>array('name'=>'和龙','code'=>'HLL'),970=>array('name'=>'海龙','code'=>'HIL'),971=>array('name'=>'哈拉苏','code'=>'HAX'),972=>array('name'=>'呼鲁斯太','code'=>'VTJ'),973=>array('name'=>'火连寨','code'=>'HLT'),974=>array('name'=>'黄梅','code'=>'VEH'),975=>array('name'=>'韩麻营','code'=>'HYP'),976=>array('name'=>'黄泥河','code'=>'HHL'),977=>array('name'=>'海宁','code'=>'HNH'),978=>array('name'=>'惠农','code'=>'HMJ'),979=>array('name'=>'和平','code'=>'VAQ'),980=>array('name'=>'花棚子','code'=>'HZM'),981=>array('name'=>'花桥','code'=>'VQH'),982=>array('name'=>'宏庆','code'=>'HEY'),983=>array('name'=>'怀仁','code'=>'HRV'),984=>array('name'=>'华容','code'=>'HRN'),985=>array('name'=>'华山北','code'=>'HDY'),986=>array('name'=>'黄松甸','code'=>'HDL'),987=>array('name'=>'和什托洛盖','code'=>'VSR'),988=>array('name'=>'红山','code'=>'VSB'),989=>array('name'=>'汉寿','code'=>'VSQ'),990=>array('name'=>'衡山','code'=>'HSQ'),991=>array('name'=>'黑水','code'=>'HOT'),992=>array('name'=>'惠山','code'=>'VCH'),993=>array('name'=>'虎什哈','code'=>'HHP'),994=>array('name'=>'红寺堡','code'=>'HSJ'),995=>array('name'=>'虎石台','code'=>'HUT'),996=>array('name'=>'海石湾','code'=>'HSO'),997=>array('name'=>'衡山西','code'=>'HEQ'),998=>array('name'=>'红砂岘','code'=>'VSJ'),999=>array('name'=>'黑台','code'=>'HQB'),1000=>array('name'=>'桓台','code'=>'VTK'),1001=>array('name'=>'和田','code'=>'VTR'),1002=>array('name'=>'会同','code'=>'VTQ'),1003=>array('name'=>'海坨子','code'=>'HZT'),1004=>array('name'=>'黑旺','code'=>'HWK'),1005=>array('name'=>'海湾','code'=>'RWH'),1006=>array('name'=>'红星','code'=>'VXB'),1007=>array('name'=>'徽县','code'=>'HYY'),1008=>array('name'=>'红兴隆','code'=>'VHB'),1009=>array('name'=>'换新天','code'=>'VTB'),1010=>array('name'=>'红岘台','code'=>'HTJ'),1011=>array('name'=>'红彦','code'=>'VIX'),1012=>array('name'=>'合阳','code'=>'HAY'),1013=>array('name'=>'海阳','code'=>'HYK'),1014=>array('name'=>'衡阳东','code'=>'HVQ'),1015=>array('name'=>'华蓥','code'=>'HUW'),1016=>array('name'=>'汉阴','code'=>'HQY'),1017=>array('name'=>'黄羊滩','code'=>'HGJ'),1018=>array('name'=>'汉源','code'=>'WHW'),1019=>array('name'=>'湟源','code'=>'HNO'),1020=>array('name'=>'河源','code'=>'VIQ'),1021=>array('name'=>'花园','code'=>'HUN'),1022=>array('name'=>'黄羊镇','code'=>'HYJ'),1023=>array('name'=>'湖州','code'=>'VZH'),1024=>array('name'=>'化州','code'=>'HZZ'),1025=>array('name'=>'黄州','code'=>'VON'),1026=>array('name'=>'霍州','code'=>'HZV'),1027=>array('name'=>'惠州西','code'=>'VXQ'),1028=>array('name'=>'巨宝','code'=>'JRT'),1029=>array('name'=>'靖边','code'=>'JIY'),1030=>array('name'=>'金宝屯','code'=>'JBD'),1031=>array('name'=>'晋城北','code'=>'JEF'),1032=>array('name'=>'金昌','code'=>'JCJ'),1033=>array('name'=>'鄄城','code'=>'JCK'),1034=>array('name'=>'交城','code'=>'JNV'),1035=>array('name'=>'建昌','code'=>'JFD'),1036=>array('name'=>'峻德','code'=>'JDB'),1037=>array('name'=>'井店','code'=>'JFP'),1038=>array('name'=>'鸡东','code'=>'JOB'),1039=>array('name'=>'江都','code'=>'UDH'),1040=>array('name'=>'鸡冠山','code'=>'JST'),1041=>array('name'=>'金沟屯','code'=>'VGP'),1042=>array('name'=>'静海','code'=>'JHP'),1043=>array('name'=>'金河','code'=>'JHX'),1044=>array('name'=>'锦河','code'=>'JHB'),1045=>array('name'=>'精河','code'=>'JHR'),1046=>array('name'=>'精河南','code'=>'JIR'),1047=>array('name'=>'江华','code'=>'JHZ'),1048=>array('name'=>'建湖','code'=>'AJH'),1049=>array('name'=>'纪家沟','code'=>'VJD'),1050=>array('name'=>'晋江','code'=>'JJS'),1051=>array('name'=>'江津','code'=>'JJW'),1052=>array('name'=>'姜家','code'=>'JJB'),1053=>array('name'=>'金坑','code'=>'JKT'),1054=>array('name'=>'芨岭','code'=>'JLJ'),1055=>array('name'=>'金马村','code'=>'JMM'),1056=>array('name'=>'江门','code'=>'JWQ'),1057=>array('name'=>'角美','code'=>'JES'),1058=>array('name'=>'莒南','code'=>'JOK'),1059=>array('name'=>'井南','code'=>'JNP'),1060=>array('name'=>'建瓯','code'=>'JVS'),1061=>array('name'=>'经棚','code'=>'JPC'),1062=>array('name'=>'江桥','code'=>'JQX'),1063=>array('name'=>'九三','code'=>'SSX'),1064=>array('name'=>'金山北','code'=>'EGH'),1065=>array('name'=>'京山','code'=>'JCN'),1066=>array('name'=>'建始','code'=>'JRN'),1067=>array('name'=>'嘉善','code'=>'JSH'),1068=>array('name'=>'稷山','code'=>'JVV'),1069=>array('name'=>'吉舒','code'=>'JSL'),1070=>array('name'=>'建设','code'=>'JET'),1071=>array('name'=>'甲山','code'=>'JOP'),1072=>array('name'=>'建三江','code'=>'JIB'),1073=>array('name'=>'嘉善南','code'=>'EAH'),1074=>array('name'=>'金山屯','code'=>'JTB'),1075=>array('name'=>'江所田','code'=>'JOM'),1076=>array('name'=>'景泰','code'=>'JTJ'),1077=>array('name'=>'九台南','code'=>'JNL'),1078=>array('name'=>'吉文','code'=>'JWX'),1079=>array('name'=>'进贤','code'=>'JUG'),1080=>array('name'=>'莒县','code'=>'JKK'),1081=>array('name'=>'嘉祥','code'=>'JUK'),1082=>array('name'=>'介休','code'=>'JXV'),1083=>array('name'=>'井陉','code'=>'JJP'),1084=>array('name'=>'嘉兴','code'=>'JXH'),1085=>array('name'=>'嘉兴南','code'=>'EPH'),1086=>array('name'=>'夹心子','code'=>'JXT'),1087=>array('name'=>'简阳','code'=>'JYW'),1088=>array('name'=>'揭阳','code'=>'JRQ'),1089=>array('name'=>'建阳','code'=>'JYS'),1090=>array('name'=>'姜堰','code'=>'UEH'),1091=>array('name'=>'巨野','code'=>'JYK'),1092=>array('name'=>'江永','code'=>'JYZ'),1093=>array('name'=>'靖远','code'=>'JYJ'),1094=>array('name'=>'缙云','code'=>'JYH'),1095=>array('name'=>'江源','code'=>'SZL'),1096=>array('name'=>'济源','code'=>'JYF'),1097=>array('name'=>'靖远西','code'=>'JXJ'),1098=>array('name'=>'胶州北','code'=>'JZK'),1099=>array('name'=>'焦作东','code'=>'WEF'),1100=>array('name'=>'靖州','code'=>'JEQ'),1101=>array('name'=>'荆州','code'=>'JBN'),1102=>array('name'=>'金寨','code'=>'JZH'),1103=>array('name'=>'晋州','code'=>'JXP'),1104=>array('name'=>'胶州','code'=>'JXK'),1105=>array('name'=>'锦州南','code'=>'JOD'),1106=>array('name'=>'焦作','code'=>'JOF'),1107=>array('name'=>'旧庄窝','code'=>'JVP'),1108=>array('name'=>'金杖子','code'=>'JYD'),1109=>array('name'=>'开安','code'=>'KAT'),1110=>array('name'=>'库车','code'=>'KCR'),1111=>array('name'=>'康城','code'=>'KCP'),1112=>array('name'=>'库都尔','code'=>'KDX'),1113=>array('name'=>'宽甸','code'=>'KDT'),1114=>array('name'=>'克东','code'=>'KOB'),1115=>array('name'=>'开江','code'=>'KAW'),1116=>array('name'=>'康金井','code'=>'KJB'),1117=>array('name'=>'喀喇其','code'=>'KQX'),1118=>array('name'=>'开鲁','code'=>'KLC'),1119=>array('name'=>'克拉玛依','code'=>'KHR'),1120=>array('name'=>'口前','code'=>'KQL'),1121=>array('name'=>'奎山','code'=>'KAB'),1122=>array('name'=>'昆山','code'=>'KSH'),1123=>array('name'=>'克山','code'=>'KSB'),1124=>array('name'=>'开通','code'=>'KTT'),1125=>array('name'=>'康熙岭','code'=>'KXZ'),1126=>array('name'=>'昆阳','code'=>'KAM'),1127=>array('name'=>'克一河','code'=>'KHX'),1128=>array('name'=>'开原西','code'=>'KXT'),1129=>array('name'=>'康庄','code'=>'KZP'),1130=>array('name'=>'来宾','code'=>'UBZ'),1131=>array('name'=>'老边','code'=>'LLT'),1132=>array('name'=>'灵宝西','code'=>'LPF'),1133=>array('name'=>'龙川','code'=>'LUQ'),1134=>array('name'=>'乐昌','code'=>'LCQ'),1135=>array('name'=>'黎城','code'=>'UCP'),1136=>array('name'=>'聊城','code'=>'UCK'),1137=>array('name'=>'蓝村','code'=>'LCK'),1138=>array('name'=>'两当','code'=>'LDY'),1139=>array('name'=>'林东','code'=>'LRC'),1140=>array('name'=>'乐都','code'=>'LDO'),1141=>array('name'=>'梁底下','code'=>'LDP'),1142=>array('name'=>'六道河子','code'=>'LVP'),1143=>array('name'=>'鲁番','code'=>'LVM'),1144=>array('name'=>'廊坊','code'=>'LJP'),1145=>array('name'=>'落垡','code'=>'LOP'),1146=>array('name'=>'廊坊北','code'=>'LFP'),1147=>array('name'=>'老府','code'=>'UFD'),1148=>array('name'=>'兰岗','code'=>'LNB'),1149=>array('name'=>'龙骨甸','code'=>'LGM'),1150=>array('name'=>'芦沟','code'=>'LOM'),1151=>array('name'=>'龙沟','code'=>'LGJ'),1152=>array('name'=>'拉古','code'=>'LGB'),1153=>array('name'=>'临海','code'=>'UFH'),1154=>array('name'=>'林海','code'=>'LXX'),1155=>array('name'=>'拉哈','code'=>'LHX'),1156=>array('name'=>'凌海','code'=>'JID'),1157=>array('name'=>'柳河','code'=>'LNL'),1158=>array('name'=>'六合','code'=>'KLH'),1159=>array('name'=>'龙华','code'=>'LHP'),1160=>array('name'=>'滦河沿','code'=>'UNP'),1161=>array('name'=>'六合镇','code'=>'LEX'),1162=>array('name'=>'亮甲店','code'=>'LRT'),1163=>array('name'=>'刘家店','code'=>'UDT'),1164=>array('name'=>'刘家河','code'=>'LVT'),1165=>array('name'=>'连江','code'=>'LKS'),1166=>array('name'=>'李家','code'=>'LJB'),1167=>array('name'=>'罗江','code'=>'LJW'),1168=>array('name'=>'廉江','code'=>'LJZ'),1169=>array('name'=>'庐江','code'=>'UJH'),1170=>array('name'=>'两家','code'=>'UJT'),1171=>array('name'=>'龙江','code'=>'LJX'),1172=>array('name'=>'龙嘉','code'=>'UJL'),1173=>array('name'=>'莲江口','code'=>'LHB'),1174=>array('name'=>'蔺家楼','code'=>'ULK'),1175=>array('name'=>'李家坪','code'=>'LIJ'),1176=>array('name'=>'兰考','code'=>'LKF'),1177=>array('name'=>'林口','code'=>'LKB'),1178=>array('name'=>'路口铺','code'=>'LKQ'),1179=>array('name'=>'老莱','code'=>'LAX'),1180=>array('name'=>'拉林','code'=>'LAB'),1181=>array('name'=>'陆良','code'=>'LRM'),1182=>array('name'=>'龙里','code'=>'LLW'),1183=>array('name'=>'零陵','code'=>'UWZ'),1184=>array('name'=>'临澧','code'=>'LWQ'),1185=>array('name'=>'兰棱','code'=>'LLB'),1186=>array('name'=>'卢龙','code'=>'UAP'),1187=>array('name'=>'喇嘛甸','code'=>'LMX'),1188=>array('name'=>'里木店','code'=>'LMB'),1189=>array('name'=>'洛门','code'=>'LMJ'),1190=>array('name'=>'龙南','code'=>'UNG'),1191=>array('name'=>'梁平','code'=>'UQW'),1192=>array('name'=>'罗平','code'=>'LPM'),1193=>array('name'=>'落坡岭','code'=>'LPP'),1194=>array('name'=>'六盘山','code'=>'UPJ'),1195=>array('name'=>'乐平市','code'=>'LPG'),1196=>array('name'=>'临清','code'=>'UQK'),1197=>array('name'=>'龙泉寺','code'=>'UQJ'),1198=>array('name'=>'乐山北','code'=>'UTW'),1199=>array('name'=>'乐善村','code'=>'LUM'),1200=>array('name'=>'冷水江东','code'=>'UDQ'),1201=>array('name'=>'连山关','code'=>'LGT'),1202=>array('name'=>'流水沟','code'=>'USP'),1203=>array('name'=>'陵水','code'=>'LIQ'),1204=>array('name'=>'罗山','code'=>'LRN'),1205=>array('name'=>'鲁山','code'=>'LAF'),1206=>array('name'=>'丽水','code'=>'USH'),1207=>array('name'=>'梁山','code'=>'LMK'),1208=>array('name'=>'灵石','code'=>'LSV'),1209=>array('name'=>'露水河','code'=>'LUL'),1210=>array('name'=>'庐山','code'=>'LSG'),1211=>array('name'=>'林盛堡','code'=>'LBT'),1212=>array('name'=>'柳树屯','code'=>'LSD'),1213=>array('name'=>'龙山镇','code'=>'LAS'),1214=>array('name'=>'梨树镇','code'=>'LSB'),1215=>array('name'=>'李石寨','code'=>'LET'),1216=>array('name'=>'黎塘','code'=>'LTZ'),1217=>array('name'=>'轮台','code'=>'LAR'),1218=>array('name'=>'芦台','code'=>'LTP'),1219=>array('name'=>'龙塘坝','code'=>'LBM'),1220=>array('name'=>'濑湍','code'=>'LVZ'),1221=>array('name'=>'骆驼巷','code'=>'LTJ'),1222=>array('name'=>'李旺','code'=>'VLJ'),1223=>array('name'=>'莱芜东','code'=>'LWK'),1224=>array('name'=>'狼尾山','code'=>'LRJ'),1225=>array('name'=>'灵武','code'=>'LNJ'),1226=>array('name'=>'莱芜西','code'=>'UXK'),1227=>array('name'=>'朗乡','code'=>'LXB'),1228=>array('name'=>'陇县','code'=>'LXY'),1229=>array('name'=>'临湘','code'=>'LXQ'),1230=>array('name'=>'芦溪','code'=>'LUG'),1231=>array('name'=>'莱西','code'=>'LXK'),1232=>array('name'=>'林西','code'=>'LXC'),1233=>array('name'=>'滦县','code'=>'UXP'),1234=>array('name'=>'略阳','code'=>'LYY'),1235=>array('name'=>'莱阳','code'=>'LYK'),1236=>array('name'=>'辽阳','code'=>'LYT'),1237=>array('name'=>'临沂北','code'=>'UYK'),1238=>array('name'=>'凌源东','code'=>'LDD'),1239=>array('name'=>'连云港','code'=>'UIH'),1240=>array('name'=>'临颍','code'=>'LNF'),1241=>array('name'=>'老营','code'=>'LXL'),1242=>array('name'=>'龙游','code'=>'LMH'),1243=>array('name'=>'罗源','code'=>'LVS'),1244=>array('name'=>'林源','code'=>'LYX'),1245=>array('name'=>'涟源','code'=>'LAQ'),1246=>array('name'=>'涞源','code'=>'LYP'),1247=>array('name'=>'耒阳西','code'=>'LPQ'),1248=>array('name'=>'临泽','code'=>'LEJ'),1249=>array('name'=>'龙爪沟','code'=>'LZT'),1250=>array('name'=>'雷州','code'=>'UAQ'),1251=>array('name'=>'六枝','code'=>'LIW'),1252=>array('name'=>'鹿寨','code'=>'LIZ'),1253=>array('name'=>'来舟','code'=>'LZS'),1254=>array('name'=>'龙镇','code'=>'LZA'),1255=>array('name'=>'拉鲊','code'=>'LEM'),1256=>array('name'=>'兰州新区','code'=>'LQJ'),1257=>array('name'=>'马鞍山','code'=>'MAH'),1258=>array('name'=>'毛坝','code'=>'MBY'),1259=>array('name'=>'毛坝关','code'=>'MGY'),1260=>array('name'=>'麻城北','code'=>'MBN'),1261=>array('name'=>'渑池','code'=>'MCF'),1262=>array('name'=>'明城','code'=>'MCL'),1263=>array('name'=>'庙城','code'=>'MAP'),1264=>array('name'=>'渑池南','code'=>'MNF'),1265=>array('name'=>'茅草坪','code'=>'KPM'),1266=>array('name'=>'猛洞河','code'=>'MUQ'),1267=>array('name'=>'磨刀石','code'=>'MOB'),1268=>array('name'=>'弥渡','code'=>'MDF'),1269=>array('name'=>'帽儿山','code'=>'MRB'),1270=>array('name'=>'明港','code'=>'MGN'),1271=>array('name'=>'梅河口','code'=>'MHL'),1272=>array('name'=>'马皇','code'=>'MHZ'),1273=>array('name'=>'孟家岗','code'=>'MGB'),1274=>array('name'=>'美兰','code'=>'MHQ'),1275=>array('name'=>'汨罗东','code'=>'MQQ'),1276=>array('name'=>'马莲河','code'=>'MHB'),1277=>array('name'=>'茅岭','code'=>'MLZ'),1278=>array('name'=>'庙岭','code'=>'MLL'),1279=>array('name'=>'茂林','code'=>'MLD'),1280=>array('name'=>'穆棱','code'=>'MLB'),1281=>array('name'=>'马林','code'=>'MID'),1282=>array('name'=>'马龙','code'=>'MGM'),1283=>array('name'=>'木里图','code'=>'MUD'),1284=>array('name'=>'汨罗','code'=>'MLQ'),1285=>array('name'=>'玛纳斯湖','code'=>'MNR'),1286=>array('name'=>'冕宁','code'=>'UGW'),1287=>array('name'=>'沐滂','code'=>'MPQ'),1288=>array('name'=>'马桥河','code'=>'MQB'),1289=>array('name'=>'闽清','code'=>'MQS'),1290=>array('name'=>'民权','code'=>'MQF'),1291=>array('name'=>'明水河','code'=>'MUT'),1292=>array('name'=>'麻山','code'=>'MAB'),1293=>array('name'=>'眉山','code'=>'MSW'),1294=>array('name'=>'漫水湾','code'=>'MKW'),1295=>array('name'=>'茂舍祖','code'=>'MOM'),1296=>array('name'=>'米沙子','code'=>'MST'),1297=>array('name'=>'美溪','code'=>'MEB'),1298=>array('name'=>'勉县','code'=>'MVY'),1299=>array('name'=>'麻阳','code'=>'MVQ'),1300=>array('name'=>'密云北','code'=>'MUP'),1301=>array('name'=>'米易','code'=>'MMW'),1302=>array('name'=>'麦园','code'=>'MYS'),1303=>array('name'=>'墨玉','code'=>'MUR'),1304=>array('name'=>'庙庄','code'=>'MZJ'),1305=>array('name'=>'米脂','code'=>'MEY'),1306=>array('name'=>'明珠','code'=>'MFQ'),1307=>array('name'=>'宁安','code'=>'NAB'),1308=>array('name'=>'农安','code'=>'NAT'),1309=>array('name'=>'南博山','code'=>'NBK'),1310=>array('name'=>'南仇','code'=>'NCK'),1311=>array('name'=>'南城司','code'=>'NSP'),1312=>array('name'=>'宁村','code'=>'NCZ'),1313=>array('name'=>'宁德','code'=>'NES'),1314=>array('name'=>'南观村','code'=>'NGP'),1315=>array('name'=>'南宫东','code'=>'NFP'),1316=>array('name'=>'南关岭','code'=>'NLT'),1317=>array('name'=>'宁国','code'=>'NNH'),1318=>array('name'=>'宁海','code'=>'NHH'),1319=>array('name'=>'南河川','code'=>'NHJ'),1320=>array('name'=>'南华','code'=>'NHS'),1321=>array('name'=>'泥河子','code'=>'NHD'),1322=>array('name'=>'宁家','code'=>'NVT'),1323=>array('name'=>'南靖','code'=>'NJS'),1324=>array('name'=>'牛家','code'=>'NJB'),1325=>array('name'=>'能家','code'=>'NJD'),1326=>array('name'=>'南口','code'=>'NKP'),1327=>array('name'=>'南口前','code'=>'NKT'),1328=>array('name'=>'南朗','code'=>'NNQ'),1329=>array('name'=>'乃林','code'=>'NLD'),1330=>array('name'=>'尼勒克','code'=>'NIR'),1331=>array('name'=>'那罗','code'=>'ULZ'),1332=>array('name'=>'宁陵县','code'=>'NLF'),1333=>array('name'=>'奈曼','code'=>'NMD'),1334=>array('name'=>'宁明','code'=>'NMZ'),1335=>array('name'=>'南木','code'=>'NMX'),1336=>array('name'=>'南平南','code'=>'NNS'),1337=>array('name'=>'那铺','code'=>'NPZ'),1338=>array('name'=>'南桥','code'=>'NQD'),1339=>array('name'=>'那曲','code'=>'NQO'),1340=>array('name'=>'暖泉','code'=>'NQJ'),1341=>array('name'=>'南台','code'=>'NTT'),1342=>array('name'=>'南头','code'=>'NOQ'),1343=>array('name'=>'宁武','code'=>'NWV'),1344=>array('name'=>'南湾子','code'=>'NWP'),1345=>array('name'=>'南翔北','code'=>'NEH'),1346=>array('name'=>'宁乡','code'=>'NXQ'),1347=>array('name'=>'内乡','code'=>'NXF'),1348=>array('name'=>'牛心台','code'=>'NXT'),1349=>array('name'=>'南峪','code'=>'NUP'),1350=>array('name'=>'娘子关','code'=>'NIP'),1351=>array('name'=>'南召','code'=>'NAF'),1352=>array('name'=>'南杂木','code'=>'NZT'),1353=>array('name'=>'平安','code'=>'PAL'),1354=>array('name'=>'蓬安','code'=>'PAW'),1355=>array('name'=>'平安驿','code'=>'PNO'),1356=>array('name'=>'磐安镇','code'=>'PAJ'),1357=>array('name'=>'平安镇','code'=>'PZT'),1358=>array('name'=>'蒲城东','code'=>'PEY'),1359=>array('name'=>'蒲城','code'=>'PCY'),1360=>array('name'=>'裴德','code'=>'PDB'),1361=>array('name'=>'偏店','code'=>'PRP'),1362=>array('name'=>'平顶山西','code'=>'BFF'),1363=>array('name'=>'坡底下','code'=>'PXJ'),1364=>array('name'=>'瓢儿屯','code'=>'PRT'),1365=>array('name'=>'平房','code'=>'PFB'),1366=>array('name'=>'平岗','code'=>'PGL'),1367=>array('name'=>'平关','code'=>'PGM'),1368=>array('name'=>'盘关','code'=>'PAM'),1369=>array('name'=>'平果','code'=>'PGZ'),1370=>array('name'=>'徘徊北','code'=>'PHP'),1371=>array('name'=>'平河口','code'=>'PHM'),1372=>array('name'=>'盘锦北','code'=>'PBD'),1373=>array('name'=>'潘家店','code'=>'PDP'),1374=>array('name'=>'皮口','code'=>'PKT'),1375=>array('name'=>'普兰店','code'=>'PLT'),1376=>array('name'=>'偏岭','code'=>'PNT'),1377=>array('name'=>'平山','code'=>'PSB'),1378=>array('name'=>'彭山','code'=>'PSW'),1379=>array('name'=>'皮山','code'=>'PSR'),1380=>array('name'=>'彭水','code'=>'PHW'),1381=>array('name'=>'磐石','code'=>'PSL'),1382=>array('name'=>'平社','code'=>'PSV'),1383=>array('name'=>'平台','code'=>'PVT'),1384=>array('name'=>'平田','code'=>'PTM'),1385=>array('name'=>'莆田','code'=>'PTS'),1386=>array('name'=>'葡萄菁','code'=>'PTW'),1387=>array('name'=>'普湾','code'=>'PWT'),1388=>array('name'=>'平旺','code'=>'PWV'),1389=>array('name'=>'平型关','code'=>'PGV'),1390=>array('name'=>'普雄','code'=>'POW'),1391=>array('name'=>'郫县','code'=>'PWW'),1392=>array('name'=>'平洋','code'=>'PYX'),1393=>array('name'=>'彭阳','code'=>'PYJ'),1394=>array('name'=>'平遥','code'=>'PYV'),1395=>array('name'=>'平邑','code'=>'PIK'),1396=>array('name'=>'平原堡','code'=>'PPJ'),1397=>array('name'=>'平原','code'=>'PYK'),1398=>array('name'=>'平峪','code'=>'PYP'),1399=>array('name'=>'彭泽','code'=>'PZG'),1400=>array('name'=>'邳州','code'=>'PJH'),1401=>array('name'=>'平庄','code'=>'PZD'),1402=>array('name'=>'泡子','code'=>'POD'),1403=>array('name'=>'平庄南','code'=>'PND'),1404=>array('name'=>'乾安','code'=>'QOT'),1405=>array('name'=>'庆安','code'=>'QAB'),1406=>array('name'=>'迁安','code'=>'QQP'),1407=>array('name'=>'祁东北','code'=>'QRQ'),1408=>array('name'=>'七甸','code'=>'QDM'),1409=>array('name'=>'曲阜东','code'=>'QAK'),1410=>array('name'=>'庆丰','code'=>'QFT'),1411=>array('name'=>'奇峰塔','code'=>'QVP'),1412=>array('name'=>'曲阜','code'=>'QFK'),1413=>array('name'=>'琼海','code'=>'QYQ'),1414=>array('name'=>'秦皇岛','code'=>'QTP'),1415=>array('name'=>'千河','code'=>'QUY'),1416=>array('name'=>'清河','code'=>'QIP'),1417=>array('name'=>'清河门','code'=>'QHD'),1418=>array('name'=>'清华园','code'=>'QHP'),1419=>array('name'=>'渠旧','code'=>'QJZ'),1420=>array('name'=>'綦江','code'=>'QJW'),1421=>array('name'=>'潜江','code'=>'QJN'),1422=>array('name'=>'全椒','code'=>'INH'),1423=>array('name'=>'秦家','code'=>'QJB'),1424=>array('name'=>'祁家堡','code'=>'QBT'),1425=>array('name'=>'清涧县','code'=>'QNY'),1426=>array('name'=>'秦家庄','code'=>'QZV'),1427=>array('name'=>'七里河','code'=>'QLD'),1428=>array('name'=>'渠黎','code'=>'QLZ'),1429=>array('name'=>'秦岭','code'=>'QLY'),1430=>array('name'=>'青龙山','code'=>'QGH'),1431=>array('name'=>'祁门','code'=>'QIH'),1432=>array('name'=>'前磨头','code'=>'QMP'),1433=>array('name'=>'青山','code'=>'QSB'),1434=>array('name'=>'确山','code'=>'QSN'),1435=>array('name'=>'清水','code'=>'QUJ'),1436=>array('name'=>'前山','code'=>'QXQ'),1437=>array('name'=>'戚墅堰','code'=>'QYH'),1438=>array('name'=>'青田','code'=>'QVH'),1439=>array('name'=>'桥头','code'=>'QAT'),1440=>array('name'=>'青铜峡','code'=>'QTJ'),1441=>array('name'=>'前卫','code'=>'QWD'),1442=>array('name'=>'前苇塘','code'=>'QWP'),1443=>array('name'=>'渠县','code'=>'QRW'),1444=>array('name'=>'祁县','code'=>'QXV'),1445=>array('name'=>'青县','code'=>'QXP'),1446=>array('name'=>'桥西','code'=>'QXJ'),1447=>array('name'=>'清徐','code'=>'QUV'),1448=>array('name'=>'旗下营','code'=>'QXC'),1449=>array('name'=>'千阳','code'=>'QOY'),1450=>array('name'=>'沁阳','code'=>'QYF'),1451=>array('name'=>'泉阳','code'=>'QYL'),1452=>array('name'=>'祁阳北','code'=>'QVQ'),1453=>array('name'=>'七营','code'=>'QYJ'),1454=>array('name'=>'庆阳山','code'=>'QSJ'),1455=>array('name'=>'清远','code'=>'QBQ'),1456=>array('name'=>'清原','code'=>'QYT'),1457=>array('name'=>'钦州东','code'=>'QDZ'),1458=>array('name'=>'钦州','code'=>'QRZ'),1459=>array('name'=>'青州市','code'=>'QZK'),1460=>array('name'=>'瑞安','code'=>'RAH'),1461=>array('name'=>'荣昌','code'=>'RCW'),1462=>array('name'=>'瑞昌','code'=>'RCG'),1463=>array('name'=>'如皋','code'=>'RBH'),1464=>array('name'=>'容桂','code'=>'RUQ'),1465=>array('name'=>'任丘','code'=>'RQP'),1466=>array('name'=>'乳山','code'=>'ROK'),1467=>array('name'=>'融水','code'=>'RSZ'),1468=>array('name'=>'热水','code'=>'RSD'),1469=>array('name'=>'容县','code'=>'RXZ'),1470=>array('name'=>'饶阳','code'=>'RVP'),1471=>array('name'=>'汝阳','code'=>'RYF'),1472=>array('name'=>'绕阳河','code'=>'RHD'),1473=>array('name'=>'汝州','code'=>'ROF'),1474=>array('name'=>'石坝','code'=>'OBJ'),1475=>array('name'=>'上板城','code'=>'SBP'),1476=>array('name'=>'施秉','code'=>'AQW'),1477=>array('name'=>'上板城南','code'=>'OBP'),1478=>array('name'=>'世博园','code'=>'ZWT'),1479=>array('name'=>'双城北','code'=>'SBB'),1480=>array('name'=>'商城','code'=>'SWN'),1481=>array('name'=>'莎车','code'=>'SCR'),1482=>array('name'=>'顺昌','code'=>'SCS'),1483=>array('name'=>'舒城','code'=>'OCH'),1484=>array('name'=>'神池','code'=>'SMV'),1485=>array('name'=>'沙城','code'=>'SCP'),1486=>array('name'=>'石城','code'=>'SCT'),1487=>array('name'=>'山城镇','code'=>'SCL'),1488=>array('name'=>'山丹','code'=>'SDJ'),1489=>array('name'=>'顺德','code'=>'ORQ'),1490=>array('name'=>'绥德','code'=>'ODY'),1491=>array('name'=>'水洞','code'=>'SIL'),1492=>array('name'=>'商都','code'=>'SXC'),1493=>array('name'=>'十渡','code'=>'SEP'),1494=>array('name'=>'四道湾','code'=>'OUD'),1495=>array('name'=>'顺德学院','code'=>'OJQ'),1496=>array('name'=>'绅坊','code'=>'OLH'),1497=>array('name'=>'双丰','code'=>'OFB'),1498=>array('name'=>'四方台','code'=>'STB'),1499=>array('name'=>'水富','code'=>'OTW'),1500=>array('name'=>'三关口','code'=>'OKJ'),1501=>array('name'=>'桑根达来','code'=>'OGC'),1502=>array('name'=>'韶关','code'=>'SNQ'),1503=>array('name'=>'上高镇','code'=>'SVK'),1504=>array('name'=>'上杭','code'=>'JBS'),1505=>array('name'=>'沙海','code'=>'SED'),1506=>array('name'=>'松河','code'=>'SBM'),1507=>array('name'=>'沙河','code'=>'SHP'),1508=>array('name'=>'沙河口','code'=>'SKT'),1509=>array('name'=>'赛汗塔拉','code'=>'SHC'),1510=>array('name'=>'沙河市','code'=>'VOP'),1511=>array('name'=>'沙后所','code'=>'SSD'),1512=>array('name'=>'山河屯','code'=>'SHL'),1513=>array('name'=>'三河县','code'=>'OXP'),1514=>array('name'=>'四合永','code'=>'OHD'),1515=>array('name'=>'三汇镇','code'=>'OZW'),1516=>array('name'=>'双河镇','code'=>'SEL'),1517=>array('name'=>'石河子','code'=>'SZR'),1518=>array('name'=>'三合庄','code'=>'SVP'),1519=>array('name'=>'三家店','code'=>'ODP'),1520=>array('name'=>'水家湖','code'=>'SQH'),1521=>array('name'=>'沈家河','code'=>'OJJ'),1522=>array('name'=>'松江河','code'=>'SJL'),1523=>array('name'=>'尚家','code'=>'SJB'),1524=>array('name'=>'孙家','code'=>'SUB'),1525=>array('name'=>'沈家','code'=>'OJB'),1526=>array('name'=>'松江','code'=>'SAH'),1527=>array('name'=>'三江口','code'=>'SKD'),1528=>array('name'=>'司家岭','code'=>'OLK'),1529=>array('name'=>'松江南','code'=>'IMH'),1530=>array('name'=>'石景山南','code'=>'SRP'),1531=>array('name'=>'邵家堂','code'=>'SJJ'),1532=>array('name'=>'三江县','code'=>'SOZ'),1533=>array('name'=>'三家寨','code'=>'SMM'),1534=>array('name'=>'十家子','code'=>'SJD'),1535=>array('name'=>'松江镇','code'=>'OZL'),1536=>array('name'=>'施家嘴','code'=>'SHM'),1537=>array('name'=>'深井子','code'=>'SWT'),1538=>array('name'=>'什里店','code'=>'OMP'),1539=>array('name'=>'疏勒','code'=>'SUR'),1540=>array('name'=>'疏勒河','code'=>'SHJ'),1541=>array('name'=>'舍力虎','code'=>'VLD'),1542=>array('name'=>'石磷','code'=>'SPB'),1543=>array('name'=>'双辽','code'=>'ZJD'),1544=>array('name'=>'绥棱','code'=>'SIB'),1545=>array('name'=>'石岭','code'=>'SOL'),1546=>array('name'=>'石林','code'=>'SLM'),1547=>array('name'=>'石林南','code'=>'LNM'),1548=>array('name'=>'石龙','code'=>'SLQ'),1549=>array('name'=>'萨拉齐','code'=>'SLC'),1550=>array('name'=>'索伦','code'=>'SNT'),1551=>array('name'=>'商洛','code'=>'OLY'),1552=>array('name'=>'沙岭子','code'=>'SLP'),1553=>array('name'=>'石门县北','code'=>'VFQ'),1554=>array('name'=>'三门峡南','code'=>'SCF'),1555=>array('name'=>'三门县','code'=>'OQH'),1556=>array('name'=>'石门县','code'=>'OMQ'),1557=>array('name'=>'三门峡西','code'=>'SXF'),1558=>array('name'=>'肃宁','code'=>'SYP'),1559=>array('name'=>'宋','code'=>'SOB'),1560=>array('name'=>'双牌','code'=>'SBZ'),1561=>array('name'=>'四平东','code'=>'PPT'),1562=>array('name'=>'遂平','code'=>'SON'),1563=>array('name'=>'沙坡头','code'=>'SFJ'),1564=>array('name'=>'商丘南','code'=>'SPF'),1565=>array('name'=>'水泉','code'=>'SID'),1566=>array('name'=>'石泉县','code'=>'SXY'),1567=>array('name'=>'石桥子','code'=>'SQT'),1568=>array('name'=>'石人城','code'=>'SRB'),1569=>array('name'=>'石人','code'=>'SRL'),1570=>array('name'=>'山市','code'=>'SQB'),1571=>array('name'=>'神树','code'=>'SWB'),1572=>array('name'=>'鄯善','code'=>'SSR'),1573=>array('name'=>'三水','code'=>'SJQ'),1574=>array('name'=>'泗水','code'=>'OSK'),1575=>array('name'=>'石山','code'=>'SAD'),1576=>array('name'=>'松树','code'=>'SFT'),1577=>array('name'=>'首山','code'=>'SAT'),1578=>array('name'=>'三十家','code'=>'SRD'),1579=>array('name'=>'三十里堡','code'=>'SST'),1580=>array('name'=>'松树镇','code'=>'SSL'),1581=>array('name'=>'松桃','code'=>'MZQ'),1582=>array('name'=>'索图罕','code'=>'SHX'),1583=>array('name'=>'三堂集','code'=>'SDH'),1584=>array('name'=>'石头','code'=>'OTB'),1585=>array('name'=>'神头','code'=>'SEV'),1586=>array('name'=>'沙沱','code'=>'SFM'),1587=>array('name'=>'上万','code'=>'SWP'),1588=>array('name'=>'孙吴','code'=>'SKB'),1589=>array('name'=>'沙湾县','code'=>'SXR'),1590=>array('name'=>'遂溪','code'=>'SXZ'),1591=>array('name'=>'沙县','code'=>'SAS'),1592=>array('name'=>'歙县','code'=>'OVH'),1593=>array('name'=>'绍兴','code'=>'SOH'),1594=>array('name'=>'石岘','code'=>'SXL'),1595=>array('name'=>'上西铺','code'=>'SXM'),1596=>array('name'=>'石峡子','code'=>'SXJ'),1597=>array('name'=>'绥阳','code'=>'SYB'),1598=>array('name'=>'沭阳','code'=>'FMH'),1599=>array('name'=>'寿阳','code'=>'SYV'),1600=>array('name'=>'水洋','code'=>'OYP'),1601=>array('name'=>'三阳川','code'=>'SYJ'),1602=>array('name'=>'上腰墩','code'=>'SPJ'),1603=>array('name'=>'三营','code'=>'OEJ'),1604=>array('name'=>'顺义','code'=>'SOP'),1605=>array('name'=>'三义井','code'=>'OYD'),1606=>array('name'=>'三源浦','code'=>'SYL'),1607=>array('name'=>'三原','code'=>'SAY'),1608=>array('name'=>'上虞','code'=>'BDH'),1609=>array('name'=>'上园','code'=>'SUD'),1610=>array('name'=>'水源','code'=>'OYJ'),1611=>array('name'=>'桑园子','code'=>'SAJ'),1612=>array('name'=>'绥中北','code'=>'SND'),1613=>array('name'=>'苏州北','code'=>'OHH'),1614=>array('name'=>'宿州东','code'=>'SRH'),1615=>array('name'=>'深圳东','code'=>'BJQ'),1616=>array('name'=>'深州','code'=>'OZP'),1617=>array('name'=>'孙镇','code'=>'OZY'),1618=>array('name'=>'绥中','code'=>'SZD'),1619=>array('name'=>'尚志','code'=>'SZB'),1620=>array('name'=>'师庄','code'=>'SNM'),1621=>array('name'=>'松滋','code'=>'SIN'),1622=>array('name'=>'师宗','code'=>'SEM'),1623=>array('name'=>'苏州园区','code'=>'KAH'),1624=>array('name'=>'苏州新区','code'=>'ITH'),1625=>array('name'=>'泰安','code'=>'TMK'),1626=>array('name'=>'台安','code'=>'TID'),1627=>array('name'=>'通安驿','code'=>'TAJ'),1628=>array('name'=>'桐柏','code'=>'TBF'),1629=>array('name'=>'通北','code'=>'TBB'),1630=>array('name'=>'汤池','code'=>'TCX'),1631=>array('name'=>'桐城','code'=>'TTH'),1632=>array('name'=>'郯城','code'=>'TZK'),1633=>array('name'=>'铁厂','code'=>'TCL'),1634=>array('name'=>'桃村','code'=>'TCK'),1635=>array('name'=>'通道','code'=>'TRQ'),1636=>array('name'=>'田东','code'=>'TDZ'),1637=>array('name'=>'天岗','code'=>'TGL'),1638=>array('name'=>'土贵乌拉','code'=>'TGC'),1639=>array('name'=>'通沟','code'=>'TOL'),1640=>array('name'=>'太谷','code'=>'TGV'),1641=>array('name'=>'塔哈','code'=>'THX'),1642=>array('name'=>'棠海','code'=>'THM'),1643=>array('name'=>'唐河','code'=>'THF'),1644=>array('name'=>'泰和','code'=>'THG'),1645=>array('name'=>'太湖','code'=>'TKH'),1646=>array('name'=>'团结','code'=>'TIX'),1647=>array('name'=>'谭家井','code'=>'TNJ'),1648=>array('name'=>'陶家屯','code'=>'TOT'),1649=>array('name'=>'唐家湾','code'=>'PDQ'),1650=>array('name'=>'统军庄','code'=>'TZP'),1651=>array('name'=>'泰康','code'=>'TKX'),1652=>array('name'=>'吐列毛杜','code'=>'TMD'),1653=>array('name'=>'图里河','code'=>'TEX'),1654=>array('name'=>'亭亮','code'=>'TIZ'),1655=>array('name'=>'田林','code'=>'TFZ'),1656=>array('name'=>'铜陵','code'=>'TJH'),1657=>array('name'=>'铁力','code'=>'TLB'),1658=>array('name'=>'铁岭西','code'=>'PXT'),1659=>array('name'=>'图们北','code'=>'QSL'),1660=>array('name'=>'天门','code'=>'TMN'),1661=>array('name'=>'天门南','code'=>'TNN'),1662=>array('name'=>'太姥山','code'=>'TLS'),1663=>array('name'=>'土牧尔台','code'=>'TRC'),1664=>array('name'=>'土门子','code'=>'TCJ'),1665=>array('name'=>'潼南','code'=>'TVW'),1666=>array('name'=>'洮南','code'=>'TVT'),1667=>array('name'=>'太平川','code'=>'TIT'),1668=>array('name'=>'太平镇','code'=>'TEB'),1669=>array('name'=>'图强','code'=>'TQX'),1670=>array('name'=>'台前','code'=>'TTK'),1671=>array('name'=>'天桥岭','code'=>'TQL'),1672=>array('name'=>'土桥子','code'=>'TQJ'),1673=>array('name'=>'汤山城','code'=>'TCT'),1674=>array('name'=>'桃山','code'=>'TAB'),1675=>array('name'=>'塔石嘴','code'=>'TIM'),1676=>array('name'=>'通途','code'=>'TUT'),1677=>array('name'=>'汤旺河','code'=>'THB'),1678=>array('name'=>'同心','code'=>'TXJ'),1679=>array('name'=>'土溪','code'=>'TSW'),1680=>array('name'=>'桐乡','code'=>'TCH'),1681=>array('name'=>'田阳','code'=>'TRZ'),1682=>array('name'=>'天义','code'=>'TND'),1683=>array('name'=>'汤阴','code'=>'TYF'),1684=>array('name'=>'驼腰岭','code'=>'TIL'),1685=>array('name'=>'太阳山','code'=>'TYJ'),1686=>array('name'=>'汤原','code'=>'TYB'),1687=>array('name'=>'塔崖驿','code'=>'TYP'),1688=>array('name'=>'滕州东','code'=>'TEK'),1689=>array('name'=>'台州','code'=>'TZH'),1690=>array('name'=>'天祝','code'=>'TZJ'),1691=>array('name'=>'滕州','code'=>'TXK'),1692=>array('name'=>'天镇','code'=>'TZV'),1693=>array('name'=>'桐子林','code'=>'TEW'),1694=>array('name'=>'天柱山','code'=>'QWH'),1695=>array('name'=>'文安','code'=>'WBP'),1696=>array('name'=>'武安','code'=>'WAP'),1697=>array('name'=>'王安镇','code'=>'WVP'),1698=>array('name'=>'旺苍','code'=>'WEW'),1699=>array('name'=>'五叉沟','code'=>'WCT'),1700=>array('name'=>'文昌','code'=>'WEQ'),1701=>array('name'=>'温春','code'=>'WDB'),1702=>array('name'=>'五大连池','code'=>'WRB'),1703=>array('name'=>'文登','code'=>'WBK'),1704=>array('name'=>'五道沟','code'=>'WDL'),1705=>array('name'=>'五道河','code'=>'WHP'),1706=>array('name'=>'文地','code'=>'WNZ'),1707=>array('name'=>'卫东','code'=>'WVT'),1708=>array('name'=>'武当山','code'=>'WRN'),1709=>array('name'=>'望都','code'=>'WDP'),1710=>array('name'=>'乌尔旗汗','code'=>'WHX'),1711=>array('name'=>'潍坊','code'=>'WFK'),1712=>array('name'=>'万发屯','code'=>'WFB'),1713=>array('name'=>'王府','code'=>'WUT'),1714=>array('name'=>'瓦房店西','code'=>'WXT'),1715=>array('name'=>'王岗','code'=>'WGB'),1716=>array('name'=>'武功','code'=>'WGY'),1717=>array('name'=>'湾沟','code'=>'WGL'),1718=>array('name'=>'吴官田','code'=>'WGM'),1719=>array('name'=>'乌海','code'=>'WVC'),1720=>array('name'=>'苇河','code'=>'WHB'),1721=>array('name'=>'卫辉','code'=>'WHF'),1722=>array('name'=>'吴家川','code'=>'WCJ'),1723=>array('name'=>'五家','code'=>'WUB'),1724=>array('name'=>'威箐','code'=>'WAM'),1725=>array('name'=>'午汲','code'=>'WJP'),1726=>array('name'=>'渭津','code'=>'WJL'),1727=>array('name'=>'王家湾','code'=>'WJJ'),1728=>array('name'=>'倭肯','code'=>'WQB'),1729=>array('name'=>'五棵树','code'=>'WKT'),1730=>array('name'=>'五龙背','code'=>'WBT'),1731=>array('name'=>'乌兰哈达','code'=>'WLC'),1732=>array('name'=>'万乐','code'=>'WEB'),1733=>array('name'=>'瓦拉干','code'=>'WVX'),1734=>array('name'=>'温岭','code'=>'VHH'),1735=>array('name'=>'五莲','code'=>'WLK'),1736=>array('name'=>'乌拉特前旗','code'=>'WQC'),1737=>array('name'=>'乌拉山','code'=>'WSC'),1738=>array('name'=>'卧里屯','code'=>'WLX'),1739=>array('name'=>'渭南北','code'=>'WBY'),1740=>array('name'=>'乌奴耳','code'=>'WRX'),1741=>array('name'=>'万宁','code'=>'WNQ'),1742=>array('name'=>'万年','code'=>'WWG'),1743=>array('name'=>'渭南南','code'=>'WVY'),1744=>array('name'=>'渭南镇','code'=>'WNJ'),1745=>array('name'=>'沃皮','code'=>'WPT'),1746=>array('name'=>'吴堡','code'=>'WUY'),1747=>array('name'=>'吴桥','code'=>'WUP'),1748=>array('name'=>'汪清','code'=>'WQL'),1749=>array('name'=>'武清','code'=>'WWP'),1750=>array('name'=>'武山','code'=>'WSJ'),1751=>array('name'=>'文水','code'=>'WEV'),1752=>array('name'=>'魏善庄','code'=>'WSP'),1753=>array('name'=>'王瞳','code'=>'WTP'),1754=>array('name'=>'五台山','code'=>'WSV'),1755=>array('name'=>'王团庄','code'=>'WZJ'),1756=>array('name'=>'五五','code'=>'WVR'),1757=>array('name'=>'无锡东','code'=>'WGH'),1758=>array('name'=>'卫星','code'=>'WVB'),1759=>array('name'=>'闻喜','code'=>'WXV'),1760=>array('name'=>'武乡','code'=>'WVV'),1761=>array('name'=>'无锡新区','code'=>'IFH'),1762=>array('name'=>'武穴','code'=>'WXN'),1763=>array('name'=>'吴圩','code'=>'WYZ'),1764=>array('name'=>'王杨','code'=>'WYB'),1765=>array('name'=>'五营','code'=>'WWB'),1766=>array('name'=>'武义','code'=>'RYH'),1767=>array('name'=>'瓦窑田','code'=>'WIM'),1768=>array('name'=>'五原','code'=>'WYC'),1769=>array('name'=>'苇子沟','code'=>'WZL'),1770=>array('name'=>'韦庄','code'=>'WZY'),1771=>array('name'=>'五寨','code'=>'WZV'),1772=>array('name'=>'王兆屯','code'=>'WZB'),1773=>array('name'=>'微子镇','code'=>'WQP'),1774=>array('name'=>'魏杖子','code'=>'WKD'),1775=>array('name'=>'新安','code'=>'EAM'),1776=>array('name'=>'兴安','code'=>'XAZ'),1777=>array('name'=>'新安县','code'=>'XAF'),1778=>array('name'=>'新保安','code'=>'XAP'),1779=>array('name'=>'下板城','code'=>'EBP'),1780=>array('name'=>'西八里','code'=>'XLP'),1781=>array('name'=>'宣城','code'=>'ECH'),1782=>array('name'=>'兴城','code'=>'XCD'),1783=>array('name'=>'小村','code'=>'XEM'),1784=>array('name'=>'新绰源','code'=>'XRX'),1785=>array('name'=>'下城子','code'=>'XCB'),1786=>array('name'=>'新城子','code'=>'XCT'),1787=>array('name'=>'喜德','code'=>'EDW'),1788=>array('name'=>'小得江','code'=>'EJM'),1789=>array('name'=>'西大庙','code'=>'XMP'),1790=>array('name'=>'小董','code'=>'XEZ'),1791=>array('name'=>'小东','code'=>'XOD'),1792=>array('name'=>'息烽','code'=>'XFW'),1793=>array('name'=>'信丰','code'=>'EFG'),1794=>array('name'=>'襄汾','code'=>'XFV'),1795=>array('name'=>'新干','code'=>'EGG'),1796=>array('name'=>'孝感','code'=>'XGN'),1797=>array('name'=>'西固城','code'=>'XUJ'),1798=>array('name'=>'西固','code'=>'XIJ'),1799=>array('name'=>'夏官营','code'=>'XGJ'),1800=>array('name'=>'西岗子','code'=>'NBB'),1801=>array('name'=>'襄河','code'=>'XXB'),1802=>array('name'=>'新和','code'=>'XIR'),1803=>array('name'=>'宣和','code'=>'XWJ'),1804=>array('name'=>'斜河涧','code'=>'EEP'),1805=>array('name'=>'新华屯','code'=>'XAX'),1806=>array('name'=>'新华','code'=>'XHB'),1807=>array('name'=>'新化','code'=>'EHQ'),1808=>array('name'=>'宣化','code'=>'XHP'),1809=>array('name'=>'兴和西','code'=>'XEC'),1810=>array('name'=>'小河沿','code'=>'XYD'),1811=>array('name'=>'下花园','code'=>'XYP'),1812=>array('name'=>'小河镇','code'=>'EKY'),1813=>array('name'=>'徐家','code'=>'XJB'),1814=>array('name'=>'峡江','code'=>'EJG'),1815=>array('name'=>'新绛','code'=>'XJV'),1816=>array('name'=>'辛集','code'=>'ENP'),1817=>array('name'=>'新江','code'=>'XJM'),1818=>array('name'=>'西街口','code'=>'EKM'),1819=>array('name'=>'许家屯','code'=>'XJT'),1820=>array('name'=>'许家台','code'=>'XTJ'),1821=>array('name'=>'谢家镇','code'=>'XMT'),1822=>array('name'=>'兴凯','code'=>'EKB'),1823=>array('name'=>'小榄','code'=>'EAQ'),1824=>array('name'=>'香兰','code'=>'XNB'),1825=>array('name'=>'兴隆店','code'=>'XDD'),1826=>array('name'=>'新乐','code'=>'ELP'),1827=>array('name'=>'新林','code'=>'XPX'),1828=>array('name'=>'小岭','code'=>'XLB'),1829=>array('name'=>'新李','code'=>'XLJ'),1830=>array('name'=>'西林','code'=>'XYB'),1831=>array('name'=>'西柳','code'=>'GCT'),1832=>array('name'=>'仙林','code'=>'XPH'),1833=>array('name'=>'新立屯','code'=>'XLD'),1834=>array('name'=>'兴隆镇','code'=>'XZB'),1835=>array('name'=>'新立镇','code'=>'XGT'),1836=>array('name'=>'新民','code'=>'XMD'),1837=>array('name'=>'西麻山','code'=>'XMB'),1838=>array('name'=>'下马塘','code'=>'XAT'),1839=>array('name'=>'孝南','code'=>'XNV'),1840=>array('name'=>'咸宁北','code'=>'XRN'),1841=>array('name'=>'兴宁','code'=>'ENQ'),1842=>array('name'=>'咸宁','code'=>'XNN'),1843=>array('name'=>'犀浦东','code'=>'XAW'),1844=>array('name'=>'西平','code'=>'XPN'),1845=>array('name'=>'兴平','code'=>'XPY'),1846=>array('name'=>'新坪田','code'=>'XPM'),1847=>array('name'=>'霞浦','code'=>'XOS'),1848=>array('name'=>'溆浦','code'=>'EPQ'),1849=>array('name'=>'犀浦','code'=>'XIW'),1850=>array('name'=>'新青','code'=>'XQB'),1851=>array('name'=>'新邱','code'=>'XQD'),1852=>array('name'=>'兴泉堡','code'=>'XQJ'),1853=>array('name'=>'仙人桥','code'=>'XRL'),1854=>array('name'=>'小寺沟','code'=>'ESP'),1855=>array('name'=>'杏树','code'=>'XSB'),1856=>array('name'=>'夏石','code'=>'XIZ'),1857=>array('name'=>'浠水','code'=>'XZN'),1858=>array('name'=>'下社','code'=>'XSV'),1859=>array('name'=>'徐水','code'=>'XSP'),1860=>array('name'=>'小哨','code'=>'XAM'),1861=>array('name'=>'新松浦','code'=>'XOB'),1862=>array('name'=>'杏树屯','code'=>'XDT'),1863=>array('name'=>'许三湾','code'=>'XSJ'),1864=>array('name'=>'湘潭','code'=>'XTQ'),1865=>array('name'=>'邢台','code'=>'XTP'),1866=>array('name'=>'仙桃西','code'=>'XAN'),1867=>array('name'=>'下台子','code'=>'EIP'),1868=>array('name'=>'徐闻','code'=>'XJQ'),1869=>array('name'=>'新窝铺','code'=>'EPD'),1870=>array('name'=>'修武','code'=>'XWF'),1871=>array('name'=>'新县','code'=>'XSN'),1872=>array('name'=>'息县','code'=>'ENN'),1873=>array('name'=>'西乡','code'=>'XQY'),1874=>array('name'=>'湘乡','code'=>'XXQ'),1875=>array('name'=>'西峡','code'=>'XIF'),1876=>array('name'=>'孝西','code'=>'XOV'),1877=>array('name'=>'小新街','code'=>'XXM'),1878=>array('name'=>'新兴县','code'=>'XGQ'),1879=>array('name'=>'西小召','code'=>'XZC'),1880=>array('name'=>'小西庄','code'=>'XXP'),1881=>array('name'=>'向阳','code'=>'XDB'),1882=>array('name'=>'旬阳','code'=>'XUY'),1883=>array('name'=>'旬阳北','code'=>'XBY'),1884=>array('name'=>'襄阳东','code'=>'XWN'),1885=>array('name'=>'兴业','code'=>'SNZ'),1886=>array('name'=>'小雨谷','code'=>'XHM'),1887=>array('name'=>'信宜','code'=>'EEQ'),1888=>array('name'=>'小月旧','code'=>'XFM'),1889=>array('name'=>'小扬气','code'=>'XYX'),1890=>array('name'=>'祥云','code'=>'EXM'),1891=>array('name'=>'襄垣','code'=>'EIF'),1892=>array('name'=>'夏邑县','code'=>'EJH'),1893=>array('name'=>'新友谊','code'=>'EYB'),1894=>array('name'=>'新阳镇','code'=>'XZJ'),1895=>array('name'=>'徐州东','code'=>'UUH'),1896=>array('name'=>'新帐房','code'=>'XZX'),1897=>array('name'=>'悬钟','code'=>'XRP'),1898=>array('name'=>'新肇','code'=>'XZT'),1899=>array('name'=>'忻州','code'=>'XXV'),1900=>array('name'=>'汐子','code'=>'XZD'),1901=>array('name'=>'西哲里木','code'=>'XRD'),1902=>array('name'=>'新杖子','code'=>'ERP'),1903=>array('name'=>'姚安','code'=>'YAC'),1904=>array('name'=>'依安','code'=>'YAX'),1905=>array('name'=>'永安','code'=>'YAS'),1906=>array('name'=>'永安乡','code'=>'YNB'),1907=>array('name'=>'亚布力','code'=>'YBB'),1908=>array('name'=>'元宝山','code'=>'YUD'),1909=>array('name'=>'羊草','code'=>'YAB'),1910=>array('name'=>'秧草地','code'=>'YKM'),1911=>array('name'=>'阳澄湖','code'=>'AIH'),1912=>array('name'=>'迎春','code'=>'YYB'),1913=>array('name'=>'叶城','code'=>'YER'),1914=>array('name'=>'盐池','code'=>'YKJ'),1915=>array('name'=>'砚川','code'=>'YYY'),1916=>array('name'=>'阳春','code'=>'YQQ'),1917=>array('name'=>'宜城','code'=>'YIN'),1918=>array('name'=>'应城','code'=>'YHN'),1919=>array('name'=>'禹城','code'=>'YCK'),1920=>array('name'=>'晏城','code'=>'YEK'),1921=>array('name'=>'羊场','code'=>'YED'),1922=>array('name'=>'阳城','code'=>'YNF'),1923=>array('name'=>'阳岔','code'=>'YAL'),1924=>array('name'=>'郓城','code'=>'YPK'),1925=>array('name'=>'雁翅','code'=>'YAP'),1926=>array('name'=>'云彩岭','code'=>'ACP'),1927=>array('name'=>'虞城县','code'=>'IXH'),1928=>array('name'=>'营城子','code'=>'YCT'),1929=>array('name'=>'永登','code'=>'YDJ'),1930=>array('name'=>'英德','code'=>'YDQ'),1931=>array('name'=>'尹地','code'=>'YDM'),1932=>array('name'=>'永定','code'=>'YGS'),1933=>array('name'=>'雁荡山','code'=>'YGH'),1934=>array('name'=>'于都','code'=>'YDG'),1935=>array('name'=>'园墩','code'=>'YAJ'),1936=>array('name'=>'英德西','code'=>'IIQ'),1937=>array('name'=>'永丰营','code'=>'YYM'),1938=>array('name'=>'杨岗','code'=>'YRB'),1939=>array('name'=>'阳高','code'=>'YOV'),1940=>array('name'=>'阳谷','code'=>'YIK'),1941=>array('name'=>'友好','code'=>'YOB'),1942=>array('name'=>'余杭','code'=>'EVH'),1943=>array('name'=>'沿河城','code'=>'YHP'),1944=>array('name'=>'岩会','code'=>'AEP'),1945=>array('name'=>'羊臼河','code'=>'YHM'),1946=>array('name'=>'永嘉','code'=>'URH'),1947=>array('name'=>'营街','code'=>'YAM'),1948=>array('name'=>'盐津','code'=>'AEW'),1949=>array('name'=>'余江','code'=>'YHG'),1950=>array('name'=>'燕郊','code'=>'AJP'),1951=>array('name'=>'姚家','code'=>'YAT'),1952=>array('name'=>'岳家井','code'=>'YGJ'),1953=>array('name'=>'一间堡','code'=>'YJT'),1954=>array('name'=>'英吉沙','code'=>'YIR'),1955=>array('name'=>'云居寺','code'=>'AFP'),1956=>array('name'=>'燕家庄','code'=>'AZK'),1957=>array('name'=>'永康','code'=>'RFH'),1958=>array('name'=>'营口东','code'=>'YGT'),1959=>array('name'=>'银浪','code'=>'YJX'),1960=>array('name'=>'永郎','code'=>'YLW'),1961=>array('name'=>'宜良北','code'=>'YSM'),1962=>array('name'=>'永乐店','code'=>'YDY'),1963=>array('name'=>'伊拉哈','code'=>'YLX'),1964=>array('name'=>'伊林','code'=>'YLB'),1965=>array('name'=>'杨陵','code'=>'YSY'),1966=>array('name'=>'彝良','code'=>'ALW'),1967=>array('name'=>'杨林','code'=>'YLM'),1968=>array('name'=>'余粮堡','code'=>'YLD'),1969=>array('name'=>'杨柳青','code'=>'YQP'),1970=>array('name'=>'月亮田','code'=>'YUM'),1971=>array('name'=>'亚龙湾','code'=>'TWQ'),1972=>array('name'=>'义马','code'=>'YMF'),1973=>array('name'=>'玉门','code'=>'YXJ'),1974=>array('name'=>'云梦','code'=>'YMN'),1975=>array('name'=>'元谋','code'=>'YMM'),1976=>array('name'=>'阳明堡','code'=>'YVV'),1977=>array('name'=>'一面山','code'=>'YST'),1978=>array('name'=>'沂南','code'=>'YNK'),1979=>array('name'=>'宜耐','code'=>'YVM'),1980=>array('name'=>'伊宁东','code'=>'YNR'),1981=>array('name'=>'营盘水','code'=>'YZJ'),1982=>array('name'=>'羊堡','code'=>'ABM'),1983=>array('name'=>'阳泉北','code'=>'YPP'),1984=>array('name'=>'乐清','code'=>'UPH'),1985=>array('name'=>'焉耆','code'=>'YSR'),1986=>array('name'=>'源迁','code'=>'AQK'),1987=>array('name'=>'姚千户屯','code'=>'YQT'),1988=>array('name'=>'阳曲','code'=>'YQV'),1989=>array('name'=>'榆树沟','code'=>'YGP'),1990=>array('name'=>'月山','code'=>'YBF'),1991=>array('name'=>'玉石','code'=>'YSJ'),1992=>array('name'=>'偃师','code'=>'YSF'),1993=>array('name'=>'沂水','code'=>'YUK'),1994=>array('name'=>'榆社','code'=>'YSV'),1995=>array('name'=>'窑上','code'=>'ASP'),1996=>array('name'=>'元氏','code'=>'YSP'),1997=>array('name'=>'杨树岭','code'=>'YAD'),1998=>array('name'=>'野三坡','code'=>'AIP'),1999=>array('name'=>'榆树屯','code'=>'YSX'),2000=>array('name'=>'榆树台','code'=>'YUT'),2001=>array('name'=>'鹰手营子','code'=>'YIP'),2002=>array('name'=>'源潭','code'=>'YTQ'),2003=>array('name'=>'牙屯堡','code'=>'YTZ'),2004=>array('name'=>'烟筒山','code'=>'YSL'),2005=>array('name'=>'烟筒屯','code'=>'YUX'),2006=>array('name'=>'羊尾哨','code'=>'YWM'),2007=>array('name'=>'越西','code'=>'YHW'),2008=>array('name'=>'攸县','code'=>'YOG'),2009=>array('name'=>'玉溪','code'=>'YXM'),2010=>array('name'=>'永修','code'=>'ACG'),2011=>array('name'=>'弋阳','code'=>'YIG'),2012=>array('name'=>'酉阳','code'=>'AFW'),2013=>array('name'=>'余姚','code'=>'YYH'),2014=>array('name'=>'岳阳东','code'=>'YIQ'),2015=>array('name'=>'阳邑','code'=>'ARP'),2016=>array('name'=>'鸭园','code'=>'YYL'),2017=>array('name'=>'鸳鸯镇','code'=>'YYJ'),2018=>array('name'=>'燕子砭','code'=>'YZY'),2019=>array('name'=>'宜州','code'=>'YSZ'),2020=>array('name'=>'仪征','code'=>'UZH'),2021=>array('name'=>'兖州','code'=>'YZK'),2022=>array('name'=>'迤资','code'=>'YQM'),2023=>array('name'=>'羊者窝','code'=>'AEM'),2024=>array('name'=>'杨杖子','code'=>'YZD'),2025=>array('name'=>'镇安','code'=>'ZEY'),2026=>array('name'=>'治安','code'=>'ZAD'),2027=>array('name'=>'招柏','code'=>'ZBP'),2028=>array('name'=>'张百湾','code'=>'ZUP'),2029=>array('name'=>'中川机场','code'=>'ZJJ'),2030=>array('name'=>'枝城','code'=>'ZCN'),2031=>array('name'=>'子长','code'=>'ZHY'),2032=>array('name'=>'诸城','code'=>'ZQK'),2033=>array('name'=>'邹城','code'=>'ZIK'),2034=>array('name'=>'赵城','code'=>'ZCV'),2035=>array('name'=>'章党','code'=>'ZHT'),2036=>array('name'=>'正定','code'=>'ZDP'),2037=>array('name'=>'肇东','code'=>'ZDB'),2038=>array('name'=>'照福铺','code'=>'ZFM'),2039=>array('name'=>'章古台','code'=>'ZGD'),2040=>array('name'=>'赵光','code'=>'ZGB'),2041=>array('name'=>'中和','code'=>'ZHX'),2042=>array('name'=>'中华门','code'=>'VNH'),2043=>array('name'=>'枝江北','code'=>'ZIN'),2044=>array('name'=>'钟家村','code'=>'ZJY'),2045=>array('name'=>'朱家沟','code'=>'ZUB'),2046=>array('name'=>'紫荆关','code'=>'ZYP'),2047=>array('name'=>'周家','code'=>'ZOB'),2048=>array('name'=>'诸暨','code'=>'ZDH'),2049=>array('name'=>'镇江南','code'=>'ZEH'),2050=>array('name'=>'周家屯','code'=>'ZOD'),2051=>array('name'=>'褚家湾','code'=>'CWJ'),2052=>array('name'=>'湛江西','code'=>'ZWQ'),2053=>array('name'=>'朱家窑','code'=>'ZUJ'),2054=>array('name'=>'曾家坪子','code'=>'ZBW'),2055=>array('name'=>'张兰','code'=>'ZLV'),2056=>array('name'=>'镇赉','code'=>'ZLT'),2057=>array('name'=>'枣林','code'=>'ZIV'),2058=>array('name'=>'扎鲁特','code'=>'ZLD'),2059=>array('name'=>'扎赉诺尔西','code'=>'ZXX'),2060=>array('name'=>'樟木头','code'=>'ZOQ'),2061=>array('name'=>'中牟','code'=>'ZGF'),2062=>array('name'=>'中宁东','code'=>'ZDJ'),2063=>array('name'=>'中宁','code'=>'VNJ'),2064=>array('name'=>'中宁南','code'=>'ZNJ'),2065=>array('name'=>'镇平','code'=>'ZPF'),2066=>array('name'=>'漳平','code'=>'ZPS'),2067=>array('name'=>'泽普','code'=>'ZPR'),2068=>array('name'=>'枣强','code'=>'ZVP'),2069=>array('name'=>'张桥','code'=>'ZQY'),2070=>array('name'=>'章丘','code'=>'ZTK'),2071=>array('name'=>'朱日和','code'=>'ZRC'),2072=>array('name'=>'泽润里','code'=>'ZLM'),2073=>array('name'=>'中山北','code'=>'ZGQ'),2074=>array('name'=>'樟树东','code'=>'ZOG'),2075=>array('name'=>'中山','code'=>'ZSQ'),2076=>array('name'=>'柞水','code'=>'ZSY'),2077=>array('name'=>'钟山','code'=>'ZSZ'),2078=>array('name'=>'樟树','code'=>'ZSG'),2079=>array('name'=>'珠窝','code'=>'ZOP'),2080=>array('name'=>'张维屯','code'=>'ZWB'),2081=>array('name'=>'彰武','code'=>'ZWD'),2082=>array('name'=>'棕溪','code'=>'ZOY'),2083=>array('name'=>'钟祥','code'=>'ZTN'),2084=>array('name'=>'资溪','code'=>'ZXS'),2085=>array('name'=>'镇西','code'=>'ZVT'),2086=>array('name'=>'张辛','code'=>'ZIP'),2087=>array('name'=>'正镶白旗','code'=>'ZXC'),2088=>array('name'=>'紫阳','code'=>'ZVY'),2089=>array('name'=>'枣阳','code'=>'ZYN'),2090=>array('name'=>'竹园坝','code'=>'ZAW'),2091=>array('name'=>'张掖','code'=>'ZYJ'),2092=>array('name'=>'镇远','code'=>'ZUW'),2093=>array('name'=>'朱杨溪','code'=>'ZXW'),2094=>array('name'=>'漳州东','code'=>'GOS'),2095=>array('name'=>'漳州','code'=>'ZUS'),2096=>array('name'=>'壮志','code'=>'ZUX'),2097=>array('name'=>'子洲','code'=>'ZZY'),2098=>array('name'=>'中寨','code'=>'ZZM'),2099=>array('name'=>'涿州','code'=>'ZXP'),2100=>array('name'=>'咋子','code'=>'ZAL'),2101=>array('name'=>'卓资山','code'=>'ZZC'),2102=>array('name'=>'株洲西','code'=>'ZAQ'),2103=>array('name'=>'安仁','code'=>'ARG'),2104=>array('name'=>'安图西','code'=>'AXL'),2105=>array('name'=>'安阳东','code'=>'ADF'),2106=>array('name'=>'栟茶','code'=>'FWH'),2107=>array('name'=>'保定东','code'=>'BMP'),2108=>array('name'=>'滨海','code'=>'FHP'),2109=>array('name'=>'滨海北','code'=>'FCP'),2110=>array('name'=>'宝鸡南','code'=>'BBY'),2111=>array('name'=>'宝清','code'=>'BUB'),2112=>array('name'=>'本溪新城','code'=>'BVT'),2113=>array('name'=>'彬县','code'=>'BXY'),2114=>array('name'=>'宾阳','code'=>'UKZ'),2115=>array('name'=>'滨州','code'=>'BIK'),2116=>array('name'=>'巢湖东','code'=>'GUH'),2117=>array('name'=>'从江','code'=>'KNW'),2118=>array('name'=>'长临河','code'=>'FVH'),2119=>array('name'=>'茶陵南','code'=>'CNG'),2120=>array('name'=>'长庆桥','code'=>'CQJ'),2121=>array('name'=>'长寿北','code'=>'COW'),2122=>array('name'=>'潮汕','code'=>'CBQ'),2123=>array('name'=>'长武','code'=>'CWY'),2124=>array('name'=>'长兴','code'=>'CBH'),2125=>array('name'=>'长阳','code'=>'CYN'),2126=>array('name'=>'潮阳','code'=>'CNQ'),2127=>array('name'=>'东安东','code'=>'DCZ'),2128=>array('name'=>'东戴河','code'=>'RDD'),2129=>array('name'=>'东二道河','code'=>'DRB'),2130=>array('name'=>'东莞','code'=>'RTQ'),2131=>array('name'=>'大苴','code'=>'DIM'),2132=>array('name'=>'大荔','code'=>'DNY'),2133=>array('name'=>'大青沟','code'=>'DSD'),2134=>array('name'=>'德清','code'=>'DRH'),2135=>array('name'=>'大石头南','code'=>'DAL'),2136=>array('name'=>'大通西','code'=>'DTO'),2137=>array('name'=>'德兴','code'=>'DWG'),2138=>array('name'=>'丹霞山','code'=>'IRQ'),2139=>array('name'=>'大冶北','code'=>'DBN'),2140=>array('name'=>'都匀东','code'=>'KJW'),2141=>array('name'=>'东营南','code'=>'DOK'),2142=>array('name'=>'大余','code'=>'DYG'),2143=>array('name'=>'定州东','code'=>'DOP'),2144=>array('name'=>'峨眉山','code'=>'IXW'),2145=>array('name'=>'鄂州东','code'=>'EFN'),2146=>array('name'=>'防城港北','code'=>'FBZ'),2147=>array('name'=>'凤城东','code'=>'FDT'),2148=>array('name'=>'富川','code'=>'FDZ'),2149=>array('name'=>'丰都','code'=>'FUW'),2150=>array('name'=>'涪陵北','code'=>'FEW'),2151=>array('name'=>'抚远','code'=>'FYB'),2152=>array('name'=>'抚州东','code'=>'FDG'),2153=>array('name'=>'抚州','code'=>'FZG'),2154=>array('name'=>'高安','code'=>'GCG'),2155=>array('name'=>'广安南','code'=>'VUW'),2156=>array('name'=>'高碑店东','code'=>'GMP'),2157=>array('name'=>'恭城','code'=>'GCZ'),2158=>array('name'=>'贵定北','code'=>'FMW'),2159=>array('name'=>'葛店南','code'=>'GNN'),2160=>array('name'=>'贵定县','code'=>'KIW'),2161=>array('name'=>'广汉北','code'=>'GVW'),2162=>array('name'=>'革居','code'=>'GEM'),2163=>array('name'=>'光明城','code'=>'IMQ'),2164=>array('name'=>'广宁','code'=>'FBQ'),2165=>array('name'=>'桂平','code'=>'GAZ'),2166=>array('name'=>'弓棚子','code'=>'GPT'),2167=>array('name'=>'古田北','code'=>'GBS'),2168=>array('name'=>'广通北','code'=>'GPM'),2169=>array('name'=>'高台南','code'=>'GAJ'),2170=>array('name'=>'贵阳北','code'=>'KQW'),2171=>array('name'=>'高邑西','code'=>'GNP'),2172=>array('name'=>'惠安','code'=>'HNS'),2173=>array('name'=>'鹤壁东','code'=>'HFF'),2174=>array('name'=>'寒葱沟','code'=>'HKB'),2175=>array('name'=>'珲春','code'=>'HUL'),2176=>array('name'=>'邯郸东','code'=>'HPP'),2177=>array('name'=>'惠东','code'=>'KDQ'),2178=>array('name'=>'海东西','code'=>'HDO'),2179=>array('name'=>'洪洞西','code'=>'HTV'),2180=>array('name'=>'哈尔滨北','code'=>'HTB'),2181=>array('name'=>'合肥北城','code'=>'COH'),2182=>array('name'=>'合肥南','code'=>'ENH'),2183=>array('name'=>'黄冈','code'=>'KGN'),2184=>array('name'=>'黄冈东','code'=>'KAN'),2185=>array('name'=>'横沟桥东','code'=>'HNN'),2186=>array('name'=>'黄冈西','code'=>'KXN'),2187=>array('name'=>'洪河','code'=>'HPB'),2188=>array('name'=>'怀化南','code'=>'KAQ'),2189=>array('name'=>'黄河景区','code'=>'HCF'),2190=>array('name'=>'花湖','code'=>'KHN'),2191=>array('name'=>'怀集','code'=>'FAQ'),2192=>array('name'=>'河口北','code'=>'HBM'),2193=>array('name'=>'鲘门','code'=>'KMQ'),2194=>array('name'=>'虎门','code'=>'IUQ'),2195=>array('name'=>'侯马西','code'=>'HPV'),2196=>array('name'=>'衡南','code'=>'HNG'),2197=>array('name'=>'淮南东','code'=>'HOH'),2198=>array('name'=>'合浦','code'=>'HVZ'),2199=>array('name'=>'霍邱','code'=>'FBH'),2200=>array('name'=>'怀仁东','code'=>'HFV'),2201=>array('name'=>'华容东','code'=>'HPN'),2202=>array('name'=>'华容南','code'=>'KRN'),2203=>array('name'=>'黄石北','code'=>'KSN'),2204=>array('name'=>'黄山北','code'=>'NYH'),2205=>array('name'=>'贺胜桥东','code'=>'HLN'),2206=>array('name'=>'和硕','code'=>'VUR'),2207=>array('name'=>'花山南','code'=>'KNN'),2208=>array('name'=>'海阳北','code'=>'HEK'),2209=>array('name'=>'霍州东','code'=>'HWV'),2210=>array('name'=>'惠州南','code'=>'KNQ'),2211=>array('name'=>'泾川','code'=>'JAJ'),2212=>array('name'=>'旌德','code'=>'NSH'),2213=>array('name'=>'蛟河西','code'=>'JOL'),2214=>array('name'=>'军粮城北','code'=>'JMP'),2215=>array('name'=>'将乐','code'=>'JLS'),2216=>array('name'=>'贾鲁河','code'=>'JLF'),2217=>array('name'=>'即墨北','code'=>'JVK'),2218=>array('name'=>'建宁县北','code'=>'JCS'),2219=>array('name'=>'江宁','code'=>'JJH'),2220=>array('name'=>'建瓯西','code'=>'JUS'),2221=>array('name'=>'酒泉南','code'=>'JNJ'),2222=>array('name'=>'句容西','code'=>'JWH'),2223=>array('name'=>'建水','code'=>'JSM'),2224=>array('name'=>'界首市','code'=>'JUN'),2225=>array('name'=>'绩溪北','code'=>'NRH'),2226=>array('name'=>'介休东','code'=>'JDV'),2227=>array('name'=>'泾县','code'=>'LOH'),2228=>array('name'=>'进贤南','code'=>'JXG'),2229=>array('name'=>'嘉峪关南','code'=>'JBJ'),2230=>array('name'=>'晋中','code'=>'JZV'),2231=>array('name'=>'凯里南','code'=>'QKW'),2232=>array('name'=>'库伦','code'=>'KLD'),2233=>array('name'=>'葵潭','code'=>'KTQ'),2234=>array('name'=>'开阳','code'=>'KVW'),2235=>array('name'=>'来宾北','code'=>'UCZ'),2236=>array('name'=>'灵璧','code'=>'GMH'),2237=>array('name'=>'绿博园','code'=>'LCF'),2238=>array('name'=>'罗城','code'=>'VCZ'),2239=>array('name'=>'陵城','code'=>'LGK'),2240=>array('name'=>'龙洞堡','code'=>'FVW'),2241=>array('name'=>'乐都南','code'=>'LVO'),2242=>array('name'=>'娄底南','code'=>'UOQ'),2243=>array('name'=>'离堆公园','code'=>'INW'),2244=>array('name'=>'陆丰','code'=>'LLQ'),2245=>array('name'=>'禄丰南','code'=>'LQM'),2246=>array('name'=>'临汾西','code'=>'LXV'),2247=>array('name'=>'滦河','code'=>'UDP'),2248=>array('name'=>'漯河西','code'=>'LBN'),2249=>array('name'=>'罗江东','code'=>'IKW'),2250=>array('name'=>'利津南','code'=>'LNK'),2251=>array('name'=>'龙里北','code'=>'KFW'),2252=>array('name'=>'醴陵东','code'=>'UKQ'),2253=>array('name'=>'礼泉','code'=>'LGY'),2254=>array('name'=>'灵石东','code'=>'UDV'),2255=>array('name'=>'乐山','code'=>'IVW'),2256=>array('name'=>'龙市','code'=>'LAG'),2257=>array('name'=>'溧水','code'=>'LDH'),2258=>array('name'=>'莱西北','code'=>'LBK'),2259=>array('name'=>'溧阳','code'=>'LEH'),2260=>array('name'=>'临邑','code'=>'LUK'),2261=>array('name'=>'柳园南','code'=>'LNR'),2262=>array('name'=>'鹿寨北','code'=>'LSZ'),2263=>array('name'=>'临泽南','code'=>'LDJ'),2264=>array('name'=>'明港东','code'=>'MDN'),2265=>array('name'=>'民和南','code'=>'MNO'),2266=>array('name'=>'马兰','code'=>'MLR'),2267=>array('name'=>'民乐','code'=>'MBJ'),2268=>array('name'=>'玛纳斯','code'=>'MSR'),2269=>array('name'=>'牟平','code'=>'MBK'),2270=>array('name'=>'闽清北','code'=>'MBS'),2271=>array('name'=>'眉山东','code'=>'IUW'),2272=>array('name'=>'庙山','code'=>'MSN'),2273=>array('name'=>'门源','code'=>'MYO'),2274=>array('name'=>'蒙自北','code'=>'MBM'),2275=>array('name'=>'蒙自','code'=>'MZM'),2276=>array('name'=>'南城','code'=>'NDG'),2277=>array('name'=>'南昌西','code'=>'NXG'),2278=>array('name'=>'南芬北','code'=>'NUT'),2279=>array('name'=>'南丰','code'=>'NFG'),2280=>array('name'=>'南湖东','code'=>'NDN'),2281=>array('name'=>'南江','code'=>'FIW'),2282=>array('name'=>'南江口','code'=>'NDQ'),2283=>array('name'=>'南陵','code'=>'LLH'),2284=>array('name'=>'尼木','code'=>'NMO'),2285=>array('name'=>'南宁东','code'=>'NFZ'),2286=>array('name'=>'南平北','code'=>'NBS'),2287=>array('name'=>'南雄','code'=>'NCQ'),2288=>array('name'=>'南阳寨','code'=>'NYF'),2289=>array('name'=>'普安','code'=>'PAN'),2290=>array('name'=>'屏边','code'=>'PBM'),2291=>array('name'=>'普定','code'=>'PGW'),2292=>array('name'=>'平度','code'=>'PAK'),2293=>array('name'=>'普宁','code'=>'PEQ'),2294=>array('name'=>'平南南','code'=>'PAZ'),2295=>array('name'=>'彭山北','code'=>'PPW'),2296=>array('name'=>'坪上','code'=>'PSK'),2297=>array('name'=>'萍乡北','code'=>'PBG'),2298=>array('name'=>'平遥古城','code'=>'PDV'),2299=>array('name'=>'彭州','code'=>'PMW'),2300=>array('name'=>'青白江东','code'=>'QFW'),2301=>array('name'=>'青岛北','code'=>'QHK'),2302=>array('name'=>'祁东','code'=>'QMQ'),2303=>array('name'=>'前锋','code'=>'QFB'),2304=>array('name'=>'青莲','code'=>'QEW'),2305=>array('name'=>'齐齐哈尔南','code'=>'QNB'),2306=>array('name'=>'清水北','code'=>'QEJ'),2307=>array('name'=>'青神','code'=>'QVW'),2308=>array('name'=>'岐山','code'=>'QAY'),2309=>array('name'=>'庆盛','code'=>'QSQ'),2310=>array('name'=>'曲水县','code'=>'QSO'),2311=>array('name'=>'祁县东','code'=>'QGV'),2312=>array('name'=>'乾县','code'=>'QBY'),2313=>array('name'=>'祁阳','code'=>'QWQ'),2314=>array('name'=>'全州南','code'=>'QNZ'),2315=>array('name'=>'仁布','code'=>'RUO'),2316=>array('name'=>'荣成','code'=>'RCK'),2317=>array('name'=>'如东','code'=>'RIH'),2318=>array('name'=>'榕江','code'=>'RVW'),2319=>array('name'=>'日喀则','code'=>'RKO'),2320=>array('name'=>'饶平','code'=>'RVQ'),2321=>array('name'=>'宋城路','code'=>'SFF'),2322=>array('name'=>'三都县','code'=>'KKW'),2323=>array('name'=>'商河','code'=>'SOK'),2324=>array('name'=>'泗洪','code'=>'GQH'),2325=>array('name'=>'三江南','code'=>'SWZ'),2326=>array('name'=>'三井子','code'=>'OJT'),2327=>array('name'=>'双流机场','code'=>'IPW'),2328=>array('name'=>'双流西','code'=>'IQW'),2329=>array('name'=>'三明北','code'=>'SHS'),2330=>array('name'=>'山坡东','code'=>'SBN'),2331=>array('name'=>'沈丘','code'=>'SQN'),2332=>array('name'=>'鄯善北','code'=>'SMR'),2333=>array('name'=>'三水南','code'=>'RNQ'),2334=>array('name'=>'韶山南','code'=>'INQ'),2335=>array('name'=>'三穗','code'=>'QHW'),2336=>array('name'=>'汕尾','code'=>'OGQ'),2337=>array('name'=>'歙县北','code'=>'NPH'),2338=>array('name'=>'绍兴北','code'=>'SLH'),2339=>array('name'=>'始兴','code'=>'IPQ'),2340=>array('name'=>'泗县','code'=>'GPH'),2341=>array('name'=>'泗阳','code'=>'MPH'),2342=>array('name'=>'邵阳北','code'=>'OVQ'),2343=>array('name'=>'上虞北','code'=>'SSH'),2344=>array('name'=>'松原北','code'=>'OCT'),2345=>array('name'=>'山阴','code'=>'SNV'),2346=>array('name'=>'沈阳南','code'=>'SOT'),2347=>array('name'=>'深圳北','code'=>'IOQ'),2348=>array('name'=>'神州','code'=>'SRQ'),2349=>array('name'=>'深圳坪山','code'=>'IFQ'),2350=>array('name'=>'石嘴山','code'=>'QQJ'),2351=>array('name'=>'石柱县','code'=>'OSW'),2352=>array('name'=>'桃村北','code'=>'TOK'),2353=>array('name'=>'土地堂东','code'=>'TTN'),2354=>array('name'=>'太谷西','code'=>'TIV'),2355=>array('name'=>'吐哈','code'=>'THR'),2356=>array('name'=>'通海','code'=>'TAM'),2357=>array('name'=>'通化县','code'=>'TXL'),2358=>array('name'=>'吐鲁番北','code'=>'TAR'),2359=>array('name'=>'铜陵北','code'=>'KXH'),2360=>array('name'=>'泰宁','code'=>'TNS'),2361=>array('name'=>'铜仁南','code'=>'TNW'),2362=>array('name'=>'汤逊湖','code'=>'THN'),2363=>array('name'=>'藤县','code'=>'TAZ'),2364=>array('name'=>'太原南','code'=>'TNV'),2365=>array('name'=>'通远堡西','code'=>'TST'),2366=>array('name'=>'文登东','code'=>'WGK'),2367=>array('name'=>'五府山','code'=>'WFG'),2368=>array('name'=>'威虎岭北','code'=>'WBL'),2369=>array('name'=>'威海北','code'=>'WHK'),2370=>array('name'=>'五龙背东','code'=>'WMT'),2371=>array('name'=>'乌龙泉南','code'=>'WFN'),2372=>array('name'=>'五女山','code'=>'WET'),2373=>array('name'=>'无为','code'=>'IIH'),2374=>array('name'=>'瓦屋山','code'=>'WAH'),2375=>array('name'=>'闻喜西','code'=>'WOV'),2376=>array('name'=>'武夷山北','code'=>'WBS'),2377=>array('name'=>'武夷山东','code'=>'WCS'),2378=>array('name'=>'婺源','code'=>'WYG'),2379=>array('name'=>'武陟','code'=>'WIF'),2380=>array('name'=>'梧州南','code'=>'WBZ'),2381=>array('name'=>'兴安北','code'=>'XDZ'),2382=>array('name'=>'许昌东','code'=>'XVF'),2383=>array('name'=>'项城','code'=>'ERN'),2384=>array('name'=>'新都东','code'=>'EWW'),2385=>array('name'=>'西丰','code'=>'XFT'),2386=>array('name'=>'襄汾西','code'=>'XTV'),2387=>array('name'=>'孝感北','code'=>'XJN'),2388=>array('name'=>'新化南','code'=>'EJQ'),2389=>array('name'=>'新晃西','code'=>'EWQ'),2390=>array('name'=>'新津','code'=>'IRW'),2391=>array('name'=>'新津南','code'=>'ITW'),2392=>array('name'=>'咸宁东','code'=>'XKN'),2393=>array('name'=>'咸宁南','code'=>'UNN'),2394=>array('name'=>'溆浦南','code'=>'EMQ'),2395=>array('name'=>'协荣','code'=>'ROO'),2396=>array('name'=>'湘潭北','code'=>'EDQ'),2397=>array('name'=>'邢台东','code'=>'EDP'),2398=>array('name'=>'修武西','code'=>'EXF'),2399=>array('name'=>'新乡东','code'=>'EGF'),2400=>array('name'=>'新余北','code'=>'XBG'),2401=>array('name'=>'西阳村','code'=>'XQF'),2402=>array('name'=>'信阳东','code'=>'OYN'),2403=>array('name'=>'咸阳秦都','code'=>'XOY'),2404=>array('name'=>'仙游','code'=>'XWS'),2405=>array('name'=>'迎宾路','code'=>'YFW'),2406=>array('name'=>'运城北','code'=>'ABV'),2407=>array('name'=>'宜春','code'=>'YEG'),2408=>array('name'=>'岳池','code'=>'AWW'),2409=>array('name'=>'云浮东','code'=>'IXQ'),2410=>array('name'=>'永福南','code'=>'YBZ'),2411=>array('name'=>'雨格','code'=>'VTM'),2412=>array('name'=>'洋河','code'=>'GTH'),2413=>array('name'=>'永济北','code'=>'AJV'),2414=>array('name'=>'于家堡','code'=>'YKP'),2415=>array('name'=>'延吉西','code'=>'YXL'),2416=>array('name'=>'运粮河','code'=>'YEF'),2417=>array('name'=>'炎陵','code'=>'YAG'),2418=>array('name'=>'杨陵南','code'=>'YEY'),2419=>array('name'=>'郁南','code'=>'YKQ'),2420=>array('name'=>'永寿','code'=>'ASY'),2421=>array('name'=>'玉山南','code'=>'YGG'),2422=>array('name'=>'永泰','code'=>'YTS'),2423=>array('name'=>'鹰潭北','code'=>'YKG'),2424=>array('name'=>'烟台南','code'=>'YLK'),2425=>array('name'=>'尤溪','code'=>'YXS'),2426=>array('name'=>'云霄','code'=>'YBS'),2427=>array('name'=>'宜兴','code'=>'YUH'),2428=>array('name'=>'阳信','code'=>'YVK'),2429=>array('name'=>'应县','code'=>'YZV'),2430=>array('name'=>'攸县南','code'=>'YXG'),2431=>array('name'=>'余姚北','code'=>'CTH'),2432=>array('name'=>'诏安','code'=>'ZDS'),2433=>array('name'=>'正定机场','code'=>'ZHP'),2434=>array('name'=>'纸坊东','code'=>'ZMN'),2435=>array('name'=>'昭化','code'=>'ZHW'),2436=>array('name'=>'芷江','code'=>'ZPQ'),2437=>array('name'=>'织金','code'=>'IZW'),2438=>array('name'=>'左岭','code'=>'ZSN'),2439=>array('name'=>'驻马店西','code'=>'ZLN'),2440=>array('name'=>'漳浦','code'=>'ZCS'),2441=>array('name'=>'肇庆东','code'=>'FCQ'),2442=>array('name'=>'庄桥','code'=>'ZQH'),2443=>array('name'=>'钟山西','code'=>'ZAZ'),2444=>array('name'=>'张掖西','code'=>'ZEJ'),2445=>array('name'=>'涿州东','code'=>'ZAP'),2446=>array('name'=>'卓资东','code'=>'ZDC'),2447=>array('name'=>'郑州东','code'=>'ZAF'),2448=>array('name'=>'胜芳','code'=>'SUP'),2449=>array('name'=>'隆安东','code'=>'IDZ'),2450=>array('name'=>'缙云西','code'=>'PYH'),2451=>array('name'=>'邵东','code'=>'FIQ') + ); + // foreach ($d as $key=>$v1) { + + // $d[$key]["keywords"]=$this->getAllPY($v1["name"])."|".$this->getFirstPY($v1["name"]); + + // } + var_dump($d); + } + + + + private $pylist = array( + 'a'=>-20319, + 'ai'=>-20317, + 'an'=>-20304, + 'ang'=>-20295, + 'ao'=>-20292, + 'ba'=>-20283, + 'bai'=>-20265, + 'ban'=>-20257, + 'bang'=>-20242, + 'bao'=>-20230, + 'bei'=>-20051, + 'ben'=>-20036, + 'beng'=>-20032, + 'bi'=>-20026, + 'bian'=>-20002, + 'biao'=>-19990, + 'bie'=>-19986, + 'bin'=>-19982, + 'bing'=>-19976, + 'bo'=>-19805, + 'bu'=>-19784, + 'ca'=>-19775, + 'cai'=>-19774, + 'can'=>-19763, + 'cang'=>-19756, + 'cao'=>-19751, + 'ce'=>-19746, + 'ceng'=>-19741, + 'cha'=>-19739, + 'chai'=>-19728, + 'chan'=>-19725, + 'chang'=>-19715, + 'chao'=>-19540, + 'che'=>-19531, + 'chen'=>-19525, + 'cheng'=>-19515, + 'chi'=>-19500, + 'chong'=>-19484, + 'chou'=>-19479, + 'chu'=>-19467, + 'chuai'=>-19289, + 'chuan'=>-19288, + 'chuang'=>-19281, + 'chui'=>-19275, + 'chun'=>-19270, + 'chuo'=>-19263, + 'ci'=>-19261, + 'cong'=>-19249, + 'cou'=>-19243, + 'cu'=>-19242, + 'cuan'=>-19238, + 'cui'=>-19235, + 'cun'=>-19227, + 'cuo'=>-19224, + 'da'=>-19218, + 'dai'=>-19212, + 'dan'=>-19038, + 'dang'=>-19023, + 'dao'=>-19018, + 'de'=>-19006, + 'deng'=>-19003, + 'di'=>-18996, + 'dian'=>-18977, + 'diao'=>-18961, + 'die'=>-18952, + 'ding'=>-18783, + 'diu'=>-18774, + 'dong'=>-18773, + 'dou'=>-18763, + 'du'=>-18756, + 'duan'=>-18741, + 'dui'=>-18735, + 'dun'=>-18731, + 'duo'=>-18722, + 'e'=>-18710, + 'en'=>-18697, + 'er'=>-18696, + 'fa'=>-18526, + 'fan'=>-18518, + 'fang'=>-18501, + 'fei'=>-18490, + 'fen'=>-18478, + 'feng'=>-18463, + 'fo'=>-18448, + 'fou'=>-18447, + 'fu'=>-18446, + 'ga'=>-18239, + 'gai'=>-18237, + 'gan'=>-18231, + 'gang'=>-18220, + 'gao'=>-18211, + 'ge'=>-18201, + 'gei'=>-18184, + 'gen'=>-18183, + 'geng'=>-18181, + 'gong'=>-18012, + 'gou'=>-17997, + 'gu'=>-17988, + 'gua'=>-17970, + 'guai'=>-17964, + 'guan'=>-17961, + 'guang'=>-17950, + 'gui'=>-17947, + 'gun'=>-17931, + 'guo'=>-17928, + 'ha'=>-17922, + 'hai'=>-17759, + 'han'=>-17752, + 'hang'=>-17733, + 'hao'=>-17730, + 'he'=>-17721, + 'hei'=>-17703, + 'hen'=>-17701, + 'heng'=>-17697, + 'hong'=>-17692, + 'hou'=>-17683, + 'hu'=>-17676, + 'hua'=>-17496, + 'huai'=>-17487, + 'huan'=>-17482, + 'huang'=>-17468, + 'hui'=>-17454, + 'hun'=>-17433, + 'huo'=>-17427, + 'ji'=>-17417, + 'jia'=>-17202, + 'jian'=>-17185, + 'jiang'=>-16983, + 'jiao'=>-16970, + 'jie'=>-16942, + 'jin'=>-16915, + 'jing'=>-16733, + 'jiong'=>-16708, + 'jiu'=>-16706, + 'ju'=>-16689, + 'juan'=>-16664, + 'jue'=>-16657, + 'jun'=>-16647, + 'ka'=>-16474, + 'kai'=>-16470, + 'kan'=>-16465, + 'kang'=>-16459, + 'kao'=>-16452, + 'ke'=>-16448, + 'ken'=>-16433, + 'keng'=>-16429, + 'kong'=>-16427, + 'kou'=>-16423, + 'ku'=>-16419, + 'kua'=>-16412, + 'kuai'=>-16407, + 'kuan'=>-16403, + 'kuang'=>-16401, + 'kui'=>-16393, + 'kun'=>-16220, + 'kuo'=>-16216, + 'la'=>-16212, + 'lai'=>-16205, + 'lan'=>-16202, + 'lang'=>-16187, + 'lao'=>-16180, + 'le'=>-16171, + 'lei'=>-16169, + 'leng'=>-16158, + 'li'=>-16155, + 'lia'=>-15959, + 'lian'=>-15958, + 'liang'=>-15944, + 'liao'=>-15933, + 'lie'=>-15920, + 'lin'=>-15915, + 'ling'=>-15903, + 'liu'=>-15889, + 'long'=>-15878, + 'lou'=>-15707, + 'lu'=>-15701, + 'lv'=>-15681, + 'luan'=>-15667, + 'lue'=>-15661, + 'lun'=>-15659, + 'luo'=>-15652, + 'ma'=>-15640, + 'mai'=>-15631, + 'man'=>-15625, + 'mang'=>-15454, + 'mao'=>-15448, + 'me'=>-15436, + 'mei'=>-15435, + 'men'=>-15419, + 'meng'=>-15416, + 'mi'=>-15408, + 'mian'=>-15394, + 'miao'=>-15385, + 'mie'=>-15377, + 'min'=>-15375, + 'ming'=>-15369, + 'miu'=>-15363, + 'mo'=>-15362, + 'mou'=>-15183, + 'mu'=>-15180, + 'na'=>-15165, + 'nai'=>-15158, + 'nan'=>-15153, + 'nang'=>-15150, + 'nao'=>-15149, + 'ne'=>-15144, + 'nei'=>-15143, + 'nen'=>-15141, + 'neng'=>-15140, + 'ni'=>-15139, + 'nian'=>-15128, + 'niang'=>-15121, + 'niao'=>-15119, + 'nie'=>-15117, + 'nin'=>-15110, + 'ning'=>-15109, + 'niu'=>-14941, + 'nong'=>-14937, + 'nu'=>-14933, + 'nv'=>-14930, + 'nuan'=>-14929, + 'nue'=>-14928, + 'nuo'=>-14926, + 'o'=>-14922, + 'ou'=>-14921, + 'pa'=>-14914, + 'pai'=>-14908, + 'pan'=>-14902, + 'pang'=>-14894, + 'pao'=>-14889, + 'pei'=>-14882, + 'pen'=>-14873, + 'peng'=>-14871, + 'pi'=>-14857, + 'pian'=>-14678, + 'piao'=>-14674, + 'pie'=>-14670, + 'pin'=>-14668, + 'ping'=>-14663, + 'po'=>-14654, + 'pu'=>-14645, + 'qi'=>-14630, + 'qia'=>-14594, + 'qian'=>-14429, + 'qiang'=>-14407, + 'qiao'=>-14399, + 'qie'=>-14384, + 'qin'=>-14379, + 'qing'=>-14368, + 'qiong'=>-14355, + 'qiu'=>-14353, + 'qu'=>-14345, + 'quan'=>-14170, + 'que'=>-14159, + 'qun'=>-14151, + 'ran'=>-14149, + 'rang'=>-14145, + 'rao'=>-14140, + 're'=>-14137, + 'ren'=>-14135, + 'reng'=>-14125, + 'ri'=>-14123, + 'rong'=>-14122, + 'rou'=>-14112, + 'ru'=>-14109, + 'ruan'=>-14099, + 'rui'=>-14097, + 'run'=>-14094, + 'ruo'=>-14092, + 'sa'=>-14090, + 'sai'=>-14087, + 'san'=>-14083, + 'sang'=>-13917, + 'sao'=>-13914, + 'se'=>-13910, + 'sen'=>-13907, + 'seng'=>-13906, + 'sha'=>-13905, + 'shai'=>-13896, + 'shan'=>-13894, + 'shang'=>-13878, + 'shao'=>-13870, + 'she'=>-13859, + 'shen'=>-13847, + 'sheng'=>-13831, + 'shi'=>-13658, + 'shou'=>-13611, + 'shu'=>-13601, + 'shua'=>-13406, + 'shuai'=>-13404, + 'shuan'=>-13400, + 'shuang'=>-13398, + 'shui'=>-13395, + 'shun'=>-13391, + 'shuo'=>-13387, + 'si'=>-13383, + 'song'=>-13367, + 'sou'=>-13359, + 'su'=>-13356, + 'suan'=>-13343, + 'sui'=>-13340, + 'sun'=>-13329, + 'suo'=>-13326, + 'ta'=>-13318, + 'tai'=>-13147, + 'tan'=>-13138, + 'tang'=>-13120, + 'tao'=>-13107, + 'te'=>-13096, + 'teng'=>-13095, + 'ti'=>-13091, + 'tian'=>-13076, + 'tiao'=>-13068, + 'tie'=>-13063, + 'ting'=>-13060, + 'tong'=>-12888, + 'tou'=>-12875, + 'tu'=>-12871, + 'tuan'=>-12860, + 'tui'=>-12858, + 'tun'=>-12852, + 'tuo'=>-12849, + 'wa'=>-12838, + 'wai'=>-12831, + 'wan'=>-12829, + 'wang'=>-12812, + 'wei'=>-12802, + 'wen'=>-12607, + 'weng'=>-12597, + 'wo'=>-12594, + 'wu'=>-12585, + 'xi'=>-12556, + 'xia'=>-12359, + 'xian'=>-12346, + 'xiang'=>-12320, + 'xiao'=>-12300, + 'xie'=>-12120, + 'xin'=>-12099, + 'xing'=>-12089, + 'xiong'=>-12074, + 'xiu'=>-12067, + 'xu'=>-12058, + 'xuan'=>-12039, + 'xue'=>-11867, + 'xun'=>-11861, + 'ya'=>-11847, + 'yan'=>-11831, + 'yang'=>-11798, + 'yao'=>-11781, + 'ye'=>-11604, + 'yi'=>-11589, + 'yin'=>-11536, + 'ying'=>-11358, + 'yo'=>-11340, + 'yong'=>-11339, + 'you'=>-11324, + 'yu'=>-11303, + 'yuan'=>-11097, + 'yue'=>-11077, + 'yun'=>-11067, + 'za'=>-11055, + 'zai'=>-11052, + 'zan'=>-11045, + 'zang'=>-11041, + 'zao'=>-11038, + 'ze'=>-11024, + 'zei'=>-11020, + 'zen'=>-11019, + 'zeng'=>-11018, + 'zha'=>-11014, + 'zhai'=>-10838, + 'zhan'=>-10832, + 'zhang'=>-10815, + 'zhao'=>-10800, + 'zhe'=>-10790, + 'zhen'=>-10780, + 'zheng'=>-10764, + 'zhi'=>-10587, + 'zhong'=>-10544, + 'zhou'=>-10533, + 'zhu'=>-10519, + 'zhua'=>-10331, + 'zhuai'=>-10329, + 'zhuan'=>-10328, + 'zhuang'=>-10322, + 'zhui'=>-10315, + 'zhun'=>-10309, + 'zhuo'=>-10307, + 'zi'=>-10296, + 'zong'=>-10281, + 'zou'=>-10274, + 'zu'=>-10270, + 'zuan'=>-10262, + 'zui'=>-10260, + 'zun'=>-10256, + 'zuo'=>-10254 + ); + + + + //全部拼音 + public function getAllPY($chinese="按是", $delimiter = '', $length = 0) { + $py = $this->zh_to_pys($chinese, $delimiter); + if($length) { + $py = substr($py, 0, $length); + } + return $py; + // var_dump($py); + } + //拼音首个字母 + public function getFirstPY($chinese="北京"){ + $result = '' ; + for ($i=0; $i<strlen($chinese); $i++) { + $p = ord(substr($chinese,$i,1)); + if ($p>160) { + $q = ord(substr($chinese,++$i,1)); + $p = $p*256 + $q - 65536; + } + $result .= substr($this->zh_to_py($p),0,1); + } + return $result ; + // var_dump($result); + } + + + //-------------------中文转拼音--------------------------------// + private function zh_to_py($num, $blank = '') { + if($num>0 && $num<160 ) { + return chr($num); + } elseif ($num<-20319||$num>-10247) { + return $blank; + } else { + foreach ($this->pylist as $py => $code) { + if($code > $num) break; + $result = $py; + } + return $result; + } + } + + + private function zh_to_pys($chinese, $delimiter = ' ', $first=0){ + $result = array(); + for($i=0; $i<strlen($chinese); $i++) { + $p = ord(substr($chinese,$i,1)); + if($p>160) { + $q = ord(substr($chinese,++$i,1)); + $p = $p*256 + $q - 65536; + } + $result[] = $this->zh_to_py($p); + if ($first) { + return $result[0]; + } + } + return implode($delimiter, $result); + } + + +} \ No newline at end of file diff --git a/application/third_party/train/controllers/ctrip_train.php b/application/third_party/train/controllers/ctrip_train.php new file mode 100644 index 00000000..8d062f9e --- /dev/null +++ b/application/third_party/train/controllers/ctrip_train.php @@ -0,0 +1,585 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +//帐号密钥 +define("ORDERUSER","guilintravel"); +define("ORDERKEY","07f811fe29f04008a8fcc86e81c012b9"); + +//数据返回格式地址 +define("JSONRETURN","http://m.ctrip.com/restapi/soa2/12976/json/"); +define("XMLRETURN","http://m.ctrip.com/restapi/soa2/12976/xml/"); + +class ctrip_train extends CI_Controller{ + + public function __construct(){ + parent::__construct(); + $this->load->helper("train");//加载模型 + $this->load->model("ctrip_train_model");//加载模型 + } + + public function addorders(){ + //接收参数 + $cold_sn = $this->input->get("order"); + $bpe_sn = $this->input->get("people"); + $SelectSeat = $this->input->get("selectseat"); + $data = array(); + $rebakc = array();//返回数据 + $rebakc["status"] = 0; + $rebakc["mes"] = ""; + + + if(!is_numeric($cold_sn)){ + $rebakc["mes"] = "订单号是数字"; + echo json_encode($rebakc); + return false; + } + if(empty($bpe_sn)){ + $rebakc["mes"] = "请选择乘客"; + echo json_encode($rebakc); + return false; + } + + $data['train'] = $this->ctrip_train_model->biz_order_detail($cold_sn); + $data['people_list'] = $this->ctrip_train_model->in_bpesn_people_info($bpe_sn); + + /*print_r($data['train']); + print_r($data['people_list']);*/ + + //生成订单号 + $OrderNumber = ORDERUSER.time(); + + if (empty($data['train'])) { + //显示错误,找不到车次 + $rebakc["mes"] = "找不到车次"; + echo json_encode($rebakc); + return false; + + } + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $rebakc["mes"] = "找不到乘客信息"; + echo json_encode($rebakc); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $rebakc["mes"] = "乘客不能超过五个"; + echo json_encode($rebakc); + return false; + } + + $db_train_zw = $this->config->item('db_train_zw'); + $train_zw = $this->config->item('train_zw'); + $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 + $black_list = $this->config->item('black_list'); + + //拼接发送的报文 + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.PartnerAddOrder'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.PartnerAddOrder'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->PartnerName = ORDERUSER; + $PostData['TrainOrderService']->Operation = ''; + $PostData['TrainOrderService']->OrderType = '电子'; + $PostData['TrainOrderService']->OrderTicketType = '0'; + $PostData['TrainOrderService']->OrderNumber = $OrderNumber; + $PostData['TrainOrderService']->ChannelName = ORDERUSER; + + $PostData['TrainOrderService']->Order->OrderTime = $time; + $PostData['TrainOrderService']->Order->OrderMedia = 'pc'; + $PostData['TrainOrderService']->Order->Insurance = 'N'; + $PostData['TrainOrderService']->Order->Invoice = 'N'; + $PostData['TrainOrderService']->Order->PrivateCustomization = '0'; + + $PostData['TrainOrderService']->Order->TicketItem->FromStationName = $data['train']->DepartAirport_cn; + $PostData['TrainOrderService']->Order->TicketItem->ToStationName = $data['train']->ArrivalAirport_cn; + $PostData['TrainOrderService']->Order->TicketItem->TicketTime = date('Y-m-d H:i:s',strtotime($data['train']->DepartureTime)); + $PostData['TrainOrderService']->Order->TicketItem->TrainNumber = $data['train']->FlightsNo; + $PostData['TrainOrderService']->Order->TicketItem->ArrivalDateTime = date('Y-m-d H:i:s',strtotime($data['train']->ArrivalTime)); + $PostData['TrainOrderService']->Order->TicketItem->TicketPrice = $data['train']->adultcost; + $PostData['TrainOrderService']->Order->TicketItem->TicketCount = count($data['people_list']); + + $AdultNum = 0; + $ChildNum = 0; + $Passport = ''; + foreach ($data['people_list'] as $PassagerInfo){ + //乘客类型 + switch ($PassagerInfo->BPE_GuestType) { + case 1: + $PiaoType = 1; + $PiaoTypeName = "成人票"; + $AdultNum++; + break; + case 2: + $PiaoType = 2; + $PiaoTypeName = "儿童票"; + $ChildNum++; + break; + default://外国人应该就两种票吧 + $PiaoType = 1; + $PiaoTypeName = "成人票"; + break; + } + + //证件类型 + switch ($PassagerInfo->BPE_PassportType){ + case 'Chinese ID': + $PassportTypeseId = "1"; + $PassportTypeseidName = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $PassportTypeseidName = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $PassportTypeseId = "G"; + $PassportTypeseidName = "台湾通行证"; + break; + default : + $PassportTypeseId = "B"; + $PassportTypeseidName = "护照"; + break; + } + //$Passport .= chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0|'; + + if($PiaoType == 1){ + $RelatioNme = chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName); + $Passport .= chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0|'; + }elseif($PiaoType == 2){ + $Passport .= $RelatioNme.','.$PassportTypeseidName.','.$PassagerInfo->BPE_Passport.','.$PiaoTypeName.','.''.',0,'.chk_sp_name($PassagerInfo->BPE_FirstName.$PassagerInfo->BPE_MiddleName.$PassagerInfo->BPE_LastName).'|'; + } + + } + + $PostData['TrainOrderService']->Order->TicketItem->AuditTicketCount = $AdultNum; + $PostData['TrainOrderService']->Order->TicketItem->ChildTicketCount = $ChildNum; + $PostData['TrainOrderService']->Order->TicketItem->SeatName = $train_zw[$db_train_zw[$data['train']->Aircraft]]; + $PostData['TrainOrderService']->Order->TicketItem->SelectedSeat = $SelectSeat; + $PostData['TrainOrderService']->Order->TicketItem->AcceptSeat = ''; + $PostData['TrainOrderService']->Order->TicketItem->passport = substr($Passport,0,strlen($Passport)-1); + $PostData['TrainOrderService']->Order->TicketItem->OrderPrice = $data['train']->adultcost * $AdultNum + $data['train']->childcost * $ChildNum; + + $PostData['TrainOrderService']->Order->FrontSeatFlag = '0'; + + $PostData['TrainOrderService']->Order->User->UserID = ''; + $PostData['TrainOrderService']->Order->User->UserName = 'guilintravel'; + $PostData['TrainOrderService']->Order->User->userLoginName = 'guilintravel'; + $PostData['TrainOrderService']->Order->User->UserMobile = '18877381547'; + //print_r($PostData);die(); + //本地添加记录 + $add_data = new stdClass(); + $add_data->cold_sn = $cold_sn; + $add_data->ordernumber = $OrderNumber; + $add_data->returncode = ''; + $add_data->status = '2'; + $add_data->errormsg = '预定中'; + $add_data->checi = $data['train']->FlightsNo; + $add_data->fromstationame = $data['train']->DepartAirport_cn; + $add_data->fromstationcode = $data['train']->DepartAirport; + $add_data->tostationame = $data['train']->ArrivalAirport_cn; + $add_data->tostationcode = $data['train']->ArrivalAirport; + $add_data->startdate = date('Y-m-d',strtotime($data['train']->DepartureDate)); + $add_data->startime = date('H:i',strtotime($data['train']->DepartureTime)); + $add_data->endtime = date('H:i',strtotime($data['train']->ArrivalTime)); + $add_data->runtime = (strtotime($data['train']->ArrivalTime) - strtotime($data['train']->DepartureTime)) / 60; + $add_data->channel = 'ctrip'; + $add_data->isauto = 0; + + + //存储到数据库 + $this->ctrip_train_model->add_orders($add_data); + + $Url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerAddOrder'; + $ResponseJson = GetPost_http($Url,json_encode($PostData),'POST'); + $ResponseData = json_decode($ResponseJson); + + //echo '预定'; + //print_r($ResponseData); + + //预定请求成功后执行支付 + if($ResponseData->Status == 'SUCCESS'){ + //计算订单总价,进行支付 + $total_price = $AdultNum * $data['train']->adultcost + $ChildNum * $data['train']->childcost; + $this->payorders($OrderNumber,$total_price); + $rebakc["status"] = 1; + $rebakc["order"] = $OrderNumber; + $rebakc["mes"] = "订单提交成功,等待回调"; + echo json_encode($rebakc); + } + } + + //取消订单 + public function cancelorders(){ + $CtripOrder = $this->input->post('CtripOrder'); + + $CtripOrder = '488110485_1543999756'; + + //生成报文 + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.PartnerPayOrder'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.PartnerPayOrder'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->PartnerName = ORDERUSER; + $PostData['TrainOrderService']->OrderNumber = $CtripOrder; + $PostData['TrainOrderService']->CancelTime = date('Y-m-d H:s:i',time()); + + $Url = 'http://ws-ordercenter-train.fat.ctripqa.com/orderCore/api/json/PartnerCancelOrder'; + + $ResponseData = GetPost_http($Url,json_encode($PostData),'POST'); + + print_r($ResponseData); + } + + //请求支付 + public function payorders($CtripOrder,$Price){ + if(empty($CtripOrder) && !is_numeric($Price)){ + exit('传参错误!'); + } + + //生成报文 + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.PartnerPayOrder'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.PartnerPayOrder'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->PartnerName = ORDERUSER; + $PostData['TrainOrderService']->OrderNumber = $CtripOrder; + $PostData['TrainOrderService']->PayedPrice = $Price; + //$PostData['TrainOrderService']->PayType = $time; + //$PostData['TrainOrderService']->TradeNumber = $time; + + $Url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerPayOrder'; + + $ResponseJson = GetPost_http($Url,json_encode($PostData),'POST'); + $ResponseData = json_decode($ResponseJson); + + //echo '支付'; + //print_r($ResponseData); + //支付同步回调信息 {"Status":"SUCCESS","PartnerName":"guilintravel","OrderNumber":"guilintravel1546071576","OperationDateTime":"2018-12-29 16:19:37","RetCode":0,"ResponseStatus":{"Timestamp":"\/Date(1546071577236+0800)\/","Ack":"Success","Errors":[],"Extension":[]}} + } + + //退票接口 + public function returnticket(){ + //接收数据 + $CtripOrder = $this->input->get_post('CtripOrder'); + $PassagerId = $this->input->get_post('PassagerId'); + + //根据获取到的订单号获取信息 + if(empty($CtripOrder)){ + exit('订单号为空'); + } + + $ReturnObj = $this->ctrip_train_model->get_passager_info($CtripOrder,$PassagerId); + if(empty($ReturnObj)){ + exit('订单详情为空'); + } + + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.ticketReturn'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.ticketReturn'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->contactName = '陈宇超'; + $PostData['TrainOrderService']->contactMobile = '18877381547'; + $PostData['TrainOrderService']->OrderNumber = $CtripOrder; + $PostData['TrainOrderService']->OperatorType = '0'; + $PostData['TrainOrderService']->TicketInfo = ''; + $PostData['TrainOrderService']->TicketInfo = array(); + + $i = 0; + foreach($ReturnObj as $items){ + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderNumber'] = $items->ts_elecnumber; + if($items->tst_ticketype == '儿童票'){ + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderType'] = '2'; + }else{ + $PostData['TrainOrderService']->TicketInfo[$i]['eOrderType'] = '1'; + } + $PostData['TrainOrderService']->TicketInfo[$i]['seatNumber'] = $items->tst_seatdetail; + $PostData['TrainOrderService']->TicketInfo[$i]['passportName'] = $items->tst_realname; + $PostData['TrainOrderService']->TicketInfo[$i]['passport'] = $items->tst_numberid; + $PostData['TrainOrderService']->TicketInfo[$i]['realName'] = $items->tst_realname; + $i++; + } + + + //发起退票请求 + $Url = 'http://m.ctrip.com/restapi/soa2/11009/json/PartnerReturnTicket'; + $ResponseJson = GetPost_http($Url,json_encode($PostData),'POST'); + $ResponseData = json_decode($ResponseJson); + + //请求结束后,将乘客状态更改为出票状态 + /*$ResponseData = new stdClass(); + $ResponseData->Status = ''; + $ResponseData->Status = 'SUCCESS';*/ + + if($ResponseData->Status == 'SUCCESS'){ + echo "<script>alert('请求成功,正在处理退票...');location.href='".site_url("/apps/trainsystem/pages/refund?order=$CtripOrder")."';</script>"; + } + //print_r($ResponseJson); + } + + //火车票改签 + public function rescheduleticket(){ + //订单号 + $CtripOrder = $this->input->get_post('CtripOrder'); + //改签车次 + $RescheduleTrainNumber = $this->input->get_post('RescheduleTrainNumber'); + //改签出发站 + $DepartStationName = $this->input->get_post('DepartStationName'); + //改签到达站 + $ArriveStationName = $this->input->get_post('ArriveStationName'); + //改签车次票价 + $RescheduleTicketPrice = $this->input->get_post('RescheduleTicketPrice'); + //改签坐席 + $RescheduleSeatName = $this->input->get_post('RescheduleSeatName'); + //改签出发时间 + $RescheduleDepartTime = $this->input->get_post('RescheduleDepartTime'); + //改签到达时间 + $RescheduleArriveTime = $this->input->get_post('RescheduleArriveTime'); + + //赋值测试 + $CtripOrder = '488111988_1544754322'; + $RescheduleTrainNumber = 'D8205'; + $DepartStationName = '桂林'; + $ArriveStationName = '南宁东'; + $RescheduleTicketPrice = '128.5'; + $RescheduleSeatName = '二等座'; + $RescheduleDepartTime = '2019/01/01 10:38'; + $RescheduleArriveTime = '2019/01/01 13:03'; + + $PostData = array(); + $TimeStamp = time(); + $time = date('Y-m-d H:i:s',$TimeStamp); + $PostData['Authentication']->TimeStamp = $time; + $PostData['Authentication']->ServiceName = 'order.partnerreschedule'; + $PostData['Authentication']->PartnerName = ORDERUSER; + $MessageIdentity = md5($time.'order.partnerreschedule'.ORDERKEY); + $PostData['Authentication']->MessageIdentity = $MessageIdentity; + + $PostData['TrainOrderService']->OrderNumber = $CtripOrder; + $PostData['TrainOrderService']->Operator = '陈宇超'; + $PostData['TrainOrderService']->RescheduleTrainNumber = $RescheduleTrainNumber; + $PostData['TrainOrderService']->DepartStationName = $DepartStationName; + $PostData['TrainOrderService']->ArriveStationName = $ArriveStationName; + $PostData['TrainOrderService']->RescheduleDepartTime = $ArriveStationName; + $PostData['TrainOrderService']->RescheduleArriveTime = $ArriveStationName; + $PostData['TrainOrderService']->RescheduleTicketPrice = $RescheduleTicketPrice; + $PostData['TrainOrderService']->RescheduleSeatName = $RescheduleSeatName; + + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos = array(); + + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['eOrderNumber'] = 'E1317265149'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['eOrderType'] = '1'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['realName'] = 'LISI'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['CarriageNo'] = '12'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['seatNumber'] = '877号'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['passportName'] = 'LISI'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['0']['passport'] = '123456789'; + + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['eOrderNumber'] = 'E1317265149'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['eOrderType'] = '1'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['realName'] = 'WANGWU'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['CarriageNo'] = '13'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['seatNumber'] = '878号'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['passportName'] = 'WANGWU'; + $PostData['TrainOrderService']->RescheduleTicketPassengerInfos['1']['passport'] = '123456789'; + + //print_r(json_encode($PostData));die(); + $Url = 'http://ws-ordercenter-train.fat.ctripqa.com/orderCore/api/json/PartnerReschedule'; + $ResponseData = GetPost_http($Url,json_encode($PostData),'POST'); + print_r($ResponseData); + } + + //回调函数 + public function ctrip_callback(){ + $back_json = file_get_contents('php://input'); + log_message('error','携程回调信息:'.$back_json); + /*$back_json = '{"Authentication":{"ServiceName":"web.order.returnTicketNotice","PartnerName":"tieyou","TimeStamp":"2019-1-18 11:35:22","MessageIdentity":"93F2BA3253829E8FAD29B5DEB7646A59"},"TrainOrderService":{"contactName":{},"contactMobile":{},"OrderNumber":"guilintravel1547778269","refundTicket":{"childBillId":{},"orderId":"8360041214","eOrderNumber":"EB59937931","eOrderType":"1","seatNumber":"01D\u53f7","passport":"544712454","passportName":"YANGFRANCISCHENG","realName":"YANGFRANCISCHENG","status":"1","reason":"\u9000\u7968\u6210\u529f\uff0c\u9000\u6b3e\u91d1\u989d:218.50\u5143"}}}';*/ + $ctrip_backdata = json_decode($back_json); + //print_r($ctrip_backdata); + if(!empty($ctrip_backdata)){ + $update_data = new stdClass(); + $update_data->ServiceName = $ctrip_backdata->Authentication->ServiceName; + $update_data->ordernumber = ''; + $update_data->seatsinfo = ''; + $update_data->TicketCheck = ''; + $update_data->bookcallback = ''; + $update_data->confirmcallback = ''; + $update_data->returncallback = ''; + $update_data->OrderTotleFee = 0; + $update_data->ElectronicOrderNumber = ''; + $update_data->reschedulecallback = ''; + + if($update_data->ServiceName == 'web.order.notifyTicket'){ + $update_data->OrderStatus = '4'; + $update_data->ErrorMsg = '出票成功'; + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $update_data->OrderTotleFee = $ctrip_backdata->TrainOrderService->OrderInfo->OrderTotleFee; + $update_data->ElectronicOrderNumber = $ctrip_backdata->TrainOrderService->OrderInfo->ElectronicOrderNumber; + + //新添加检票口信息 + if(isset($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck)){ + if(!is_object($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck)){ + $update_data->TicketCheck = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->TicketCheck; + } + } + + //获取总票数,由于携程接口单人和多人返回的数据结构不一致 + $person_num = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketCount; + + //存储座位信息 转换为英文 + $coach_arr = array(); + $seats_arr = array(); + $data_passager = new stdClass(); + $string = ''; + $i = 0; + if($person_num > 1){ + foreach ($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo as $items){ + if(strpos($items->SeatNo,'车厢')){ + $coach = mb_substr($items->SeatNo,0,strpos($items->SeatNo,'车厢')); + array_push($coach_arr,$coach); + $seat = mb_substr($items->SeatNo,strpos($items->SeatNo,'车厢')+2,mb_strlen($items->SeatNo,'UTF8')); + $find = array('号'); + $replace = array(''); + $seat = str_replace($find,$replace,$seat); + array_push($seats_arr,$seat); + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $data_passager->realname = $items->PassengerName; + $data_passager->identitytype = $items->IdentityType; + $data_passager->numberid = $items->NumberID; + $data_passager->ticketype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketType; + $data_passager->ticketprice = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketPrice; + $data_passager->seatype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketSeat; + $data_passager->seatdetail = $items->SeatNo; + $this->ctrip_train_model->add_passagers($data_passager); + $i++; + } + + }else{ + $seatinfo_html = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->SeatNo; + if(strpos($seatinfo_html,'车厢')){ + $coach = mb_substr($seatinfo_html,0,strpos($seatinfo_html,'车厢')); + array_push($coach_arr,$coach); + $seat = mb_substr($seatinfo_html,strpos($seatinfo_html,'车厢')+2,mb_strlen($seatinfo_html,'UTF8')); + $find = array('号'); + $replace = array(''); + $seat = str_replace($find,$replace,$seat); + array_push($seats_arr,$seat); + } + + //对订票乘客进行存储 + $data_passager->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $data_passager->realname = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->PassengerName; + $data_passager->identitytype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->IdentityType; + $data_passager->numberid = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->NumberID; + $data_passager->ticketype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->TicketType; + $data_passager->ticketprice = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketPrice; + $data_passager->seatype = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->OrderTicketSeat; + $data_passager->seatdetail = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfoFinal->Tickets->Ticket->DetailInfos->DetailInfo->SeatNo; + $this->ctrip_train_model->add_passagers($data_passager); + } + + if(count(array_unique($coach_arr)) == 1){ + $onlycoach = array_unique($coach_arr); + $update_data->seatsinfo .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach_arr) as $item_coach){ + $update_data->seatsinfo .= 'Coach '.$item_coach.','; + } + } + + $update_data->seatsinfo .= 'Seat '; + foreach($seats_arr as $item_seat){ + $update_data->seatsinfo .= $item_seat.','; + } + + $update_data->seatsinfo = substr($update_data->seatsinfo,0,strlen($update_data->seatsinfo)-1); + + $update_data->bookcallback = $back_json; + + //添加支付记录 + $add_train_payment_data->TOC_Memo = $update_data->ordernumber; + //根据订单号获取cold_sn + $order_info = $this->ctrip_train_model->get_order_info($update_data->ordernumber); + $cold_sn = $order_info->ts_cold_sn; + $add_train_payment_data->TOC_COLD_SN = $cold_sn; + $add_train_payment_data->TOC_TrainNumber = $ctrip_backdata->TrainOrderService->OrderInfo->TicketInfo->OrderTicketCheci; + $add_train_payment_data->TOC_DepartureDate = date('Y-m-d',strtotime($ctrip_backdata->TrainOrderService->OrderInfo->TicketInfo->OrderTicketYMD)); + $add_train_payment_data->TOC_TicketCost = $update_data->OrderTotleFee; + $add_train_payment_data->poundage = ($person_num*5)."";//手续费,每人五块,转换成字符串 + $add_train_payment_data->FOI_TrainNetOrderNo = $update_data->ElectronicOrderNumber; + //print_r($add_train_order_data);die(); + $this->ctrip_train_model->add_train_payment($add_train_payment_data); + //记录供应商(瀚特) + $this->ctrip_train_model->update_cold_planvei_sn($cold_sn); + }else if($update_data->ServiceName == 'web.order.notifyNoTicket'){ + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $update_data->OrderStatus = '1'; + $update_data->ErrorMsg = $ctrip_backdata->TrainOrderService->OrderInfo->NoTicketReasons; + $update_data->confirmcallback = $back_json; + }else if($update_data->ServiceName == 'web.order.returnTicketNotice'){ + $update_data->ordernumber = $ctrip_backdata->TrainOrderService->OrderNumber; + $update_data->OrderStatus = '7'; + $update_data->ErrorMsg = $ctrip_backdata->TrainOrderService->refundTicket->reason; + $update_data->returncallback = $back_json; + + //退票时还需要单独对对每个乘客存储回调信息 + $passpager_info = new stdClass(); + $passpager_info->returncallback = $back_json; + $passpager_info->status = '7'; + $passpager_info->ordernumber = $ctrip_backdata->TrainOrderService->OrderNumber; + $passpager_info->realname = $ctrip_backdata->TrainOrderService->refundTicket->realName; + $passpager_info->numberid = $ctrip_backdata->TrainOrderService->refundTicket->passport; + $this->ctrip_train_model->update_passpager_info($passpager_info); + }else if($update_data->ServiceName == 'web.order.requestRefund'){ + $return_order = $ctrip_backdata->TrainOrderService->OrderInfo->OrderNumber; + $return_money = $ctrip_backdata->TrainOrderService->TotalRefundAmount; + + //根据订单号获取cold_sn + $order_info = $this->ctrip_train_model->get_order_info($return_order); + $cold_sn = $order_info->ts_cold_sn; + //print_r($order_info); + + $add_train_payment_data->TOC_Memo = $return_order.'_'.$ctrip_backdata->TrainOrderService->OrderInfo->OrderTid; + $add_train_payment_data->TOC_COLD_SN = $cold_sn; + $add_train_payment_data->TOC_TrainNumber = $order_info->ts_checi; + $add_train_payment_data->TOC_DepartureDate = $order_info->ts_startdate; + $add_train_payment_data->TOC_TicketCost = -$ctrip_backdata->TrainOrderService->TotalRefundAmount; + $add_train_payment_data->FOI_TrainNetOrderNo=null; + //print_r($add_train_payment_data);die(); + $this->ctrip_train_model->add_train_payment($add_train_payment_data); + return false; + } + + //更新订单信息(出票系统) + $this->ctrip_train_model->update_orders($update_data); + } + //print_r($update_data); + //print_r(json_decode($back_xml)); + + } + +} \ No newline at end of file diff --git a/application/third_party/train/controllers/index.php b/application/third_party/train/controllers/index.php index 48d2673b..bedf3785 100644 --- a/application/third_party/train/controllers/index.php +++ b/application/third_party/train/controllers/index.php @@ -23,7 +23,6 @@ class Index extends CI_Controller{ { // header("Content-Type: text/html;charset=utf-8"); parent::__construct(); - $this->config->load('config'); $this->order_status_msg=$this->config->item('train_order_status_msg'); $this->key=JUHE_TRAIN_API_KEY; $this->cx_api=JUHE_TRAIN_CX_API; @@ -38,98 +37,46 @@ class Index extends CI_Controller{ $this->passportty=$this->config->item('train_passportty'); $this->load->model("BIZ_train_model");//加载模型 + $this->load->model("order_people_model","op"); } - public function index() + public function index($coli_id=null){ + header('Location: http://www.mycht.cn/info.php/apps/trainsystem/pages/'); + $this->ht_train_order_info_test($coli_id); + // $this->load->view('bootstrap3/header'); + // $this->load->view('welcome'); + // $this->load->view('bootstrap3/footer'); + } + + public function index_test($coli_id=null) { - $this->ht_train_order_info(); + $this->ht_train_order_info_test($coli_id); // $this->load->view('bootstrap3/header'); // $this->load->view('welcome'); // $this->load->view('bootstrap3/footer'); } + public function welcome(){ $this->load->view('bootstrap3/header'); $this->load->view('welcome'); $this->load->view('bootstrap3/footer'); } - public function export_bk(){ - $from_date=$this->input->post("from_date"); - $to_date=$this->input->post("to_date"); - if(!empty($from_date) && !empty($to_date)){ - $from_date=date("Y-m-d H:i",strtotime($from_date)); - $to_date=date("Y-m-d H:i",strtotime($to_date)); - $r="";//聚合返回的数据 - $string_r="";//写入excel表格数据 - $coli_id=""; - $wl_name=""; - $arr="";//整合完成的数组 - $url=JUHE_TRAIN_EXPORT_API;//请求的url - $url.="?key=".$this->key; - $url.="&since=".$from_date; - $url.="&before=".$to_date; - $r=$this->get_data($url); - // $r=mb_convert_encoding($r, "utf-8", "gb2312"); - $r=explode("\n",$r); - $excel_head='"记录编号","时间","火车票订单号","最新余额","信息","变化值","翰特订单号","外联"'; - $excel_head=mb_convert_encoding($excel_head,"gbk","utf-8"); - $string_r=$excel_head; - for($i=1;$i<count($r)-1;$i++){ - $r_info=explode(",",$r[$i]); - $juhe_order=substr($r_info[4], 1,14); - $coli_id=$this->BIZ_train_model->jh_order_get_coli_id($juhe_order); - if($coli_id){ - $r_info[6]=$coli_id[0]->COLI_ID; - $wl_name = $this->BIZ_train_model->get_operatorinfo($r_info[6]); - $r_info[7]=mb_convert_encoding($wl_name[0]->OPI_Name, "gbk", "utf-8"); - // $r_info[7]=$wl_name[0]->OPI_Name; - }else{ - $r_info[6]=""; - $r_info[7]=""; - } - $r_info[3]=mb_convert_encoding($r_info[3],"utf-8","gbk"); - if(is_numeric(mb_strpos($r_info[3],"扣款"))){ - $r_info[3]="票款"; - } - if(is_numeric(mb_strpos($r_info[3],"扣手续费"))){ - $r_info[3]="手续费"; - } - if(is_numeric(mb_strpos($r_info[3],"线上退票成功"))){ - $r_info[3]="退票费"; - } - $r_info[3]=mb_convert_encoding($r_info[3],"gbk","utf-8"); - $arr[]=$r_info; - } - $ht_order_sort = array(); - $wl_name_sort = array(); - foreach ($arr as $a) { - $wl_name_sort[] = $a[7]; - } - foreach ($arr as $a) { - $ht_order_sort[] = $a[6]; - } - array_multisort($wl_name_sort, $ht_order_sort,SORT_ASC, SORT_STRING, $arr); - foreach ($arr as $a) { - $ht_order_sort[] = $a[6]; - $string_r.="\n"."$a[0],$a[2],$a[4],$a[5],$a[3],$a[1]".',"'.$a[6].'"'.',"'.$a[7].'"'; - } - $string_r=mb_convert_encoding($string_r,"utf-8","gbk"); - header("Content-type:application/vnd.ms-excel"); - header("Content-Disposition:attachment;filename=juhe_train.csv"); - echo $string_r;die; - } - $this->load->view('bootstrap3/header'); - $this->load->view('export'); - $this->load->view('bootstrap3/footer'); - } public function export(){ + set_time_limit(0); + //创建跟踪号 + $trackcode = $this->BIZ_train_model->getTrackingCode(); $from_date=$this->input->post("from_date"); $to_date=$this->input->post("to_date"); $examine=$this->input->post("examine"); + //$operator=$this->input->post("operator"); + $reback=array();//返回的数据 - $reback["from_date"]=$from_date; + $reback["from_date"]=$from_date; $reback["to_date"]=$to_date; $reback["examine"]=$examine; + $group = array(); + if(!empty($from_date) && !empty($to_date)){ $from_date=date("Y-m-d H:i",strtotime($from_date)); $to_date=date("Y-m-d H:i",strtotime($to_date)); @@ -137,17 +84,44 @@ class Index extends CI_Controller{ $string_r="";//输出 $coli_id=""; $wl_name=""; - $arr="";//整合完成的数组,写进excel表的数据 + $arr = array();//整合完成的数组,写进excel表的数据 $url=JUHE_TRAIN_EXPORT_API;//请求的url $url.="?key=".$this->key; $url.="&since=".$from_date; $url.="&before=".$to_date; $r=$this->get_data($url); $r=explode("\n",$r); + //print_r($r); + //die(); + for($i=1;$i<count($r)-1;$i++){ $r_info=explode(",",$r[$i]); - $juhe_order=substr($r_info[4], 1,14); - $coli_id=$this->BIZ_train_model->jh_order_get_coli_id($juhe_order); + $juhe_order=substr($r_info[4], 1,strlen($r_info[4])-2); + $obj = $this->BIZ_train_model->jh_order_get_coli_id($juhe_order); + //print_r($obj); + if(!empty($obj)){ + $coli_id = $obj[0]->COLI_ID; + $coli_sn = $obj[0]->COLI_SN; + }else{ + echo $juhe_order; + } + + $this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode); + + /*if(empty($coli_sn) || empty($coli_sn)){ + print_r($juhe_order); + }*/ + + + /* + $flag = $this->BIZ_train_model->islink($coli_sn); + if($flag){ + $this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode); + }else{ + echo $coli_sn.'该订单还未关联财务表,不能导出账单。<br>'; + die(); + } + */ //去掉数据两边的双引号 $r_info[2]=substr($r_info[2], stripos($r_info[2],'"')+1,strrpos($r_info[2],'"')-1); $r_info[1]=substr($r_info[1], stripos($r_info[1],'"')+1,strrpos($r_info[1],'"')-1); @@ -156,10 +130,9 @@ class Index extends CI_Controller{ $r_info[7] = "";//储存外联名 $r_info[8] = "";//储存coli_id if($coli_id){ - $r_info[8] = $coli_id[0]->COLI_ID; + $r_info[8] = $coli_id; $gri_no=$this->BIZ_train_model->get_gri_no($r_info[8]);//团名 - $wl_name = $this->BIZ_train_model->get_operatorinfo($r_info[8]); - + $wl_name = $this->BIZ_train_model->get_operatorinfo($r_info[8]); if($gri_no){ $r_info[6] = $gri_no[0]->GRI_No; } @@ -167,8 +140,9 @@ class Index extends CI_Controller{ $r_info[7] = $wl_name[0]->OPI_Name; } } - $r_info[3]=mb_convert_encoding($r_info[3],"utf-8","gbk"); - + + //$r_info[3]=mb_convert_encoding($r_info[3],"utf-8","gbk"); + if(is_numeric(mb_strpos($r_info[3],"充值"))){ if(is_numeric(mb_strpos($r_info[3],"扣款"))){ $r_info[3]="票款(有充值)"; @@ -190,19 +164,39 @@ class Index extends CI_Controller{ $r_info[3]="退票费"; } // $r_info[3]=mb_convert_encoding($r_info[3],"gbk","utf-8"); + $r_info['trackcode'] = $trackcode; $arr[]=$r_info; + + /* + //根据外联的名字创建数组来存储对应外联的订单信息 + if(!empty($r_info[7])){ + if(!isset($group[$r_info[7]])){ + $group[$r_info[7]] = array(); + } + array_push($group[$r_info[7]],$r_info); + }*/ + } + /* + //将存储好的分组重新循环出来。 + foreach($group as $item){ + foreach ($item as $value){ + array_push($arr,$value); + } + } + */ + //die(); if(empty($examine)){ - header("Content-type:application/vnd.ms-excel"); - header("Content-Disposition:attachment;filename=juhe_train.xml"); + header("Content-type:application/vnd.ms-excel;charset=utf-8"); + header("Content-Disposition:attachment;filename=juhe_train.xls"); $string_r= $this->load->view("train_transaction_excel",array("arr"=>$arr),TRUE); echo $string_r;die; }else{ krsort($arr);//数组倒序 $reback["data"]=$arr; } - } + $this->load->view('bootstrap3/header'); $this->load->view('export',$reback); $this->load->view('bootstrap3/footer'); @@ -220,6 +214,7 @@ class Index extends CI_Controller{ echo json_encode($reback); return false; } + public function search(){ $from=$this->input->post("from"); $to=$this->input->post("to"); @@ -246,6 +241,7 @@ class Index extends CI_Controller{ die(json_encode(array("status"=>0,"mes"=>"站点名称错误"))); } } + public function ch_train_search(){ $from=$this->input->get("from"); $to=$this->input->get("to"); @@ -254,6 +250,7 @@ class Index extends CI_Controller{ $ticket=$this->post_data("http://op.juhe.cn/trainTickets/ticketsAvailable",$ticket_data); $ticket=json_decode($ticket); } + public function ch_train_search_t(){ // $seat_key = array( @@ -420,10 +417,12 @@ class Index extends CI_Controller{ $this->load->view('booking',$data); $this->load->view('bootstrap3/footer'); } + //接收订单COLD_SN和客户BPE_SN 获取车次,乘客信息,拼接成聚合提交订单的url public function get_sn_submit_juhe() { $cold_sn=$this->input->get("order"); $bpe_sn=$this->input->get("people"); + $selectseat=$this->input->get("selectseat"); $data = array(); $rebakc=array();//返回数据 $rebakc["status"]=0; @@ -465,12 +464,16 @@ class Index extends CI_Controller{ $train_zw = $this->config->item('train_zw'); $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 + $black_list = $this->config->item('black_list'); + $passengers=""; foreach ($data['people_list'] as $key => $item) { //乘客姓名 - $passengersename = trim($item->BPE_FirstName) . trim($item->BPE_MiddleName) . trim($item->BPE_LastName); - //乘客类型 + $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName; + //将特殊字符转换为正常字符以便于出票 + $passengersename = $this->chk_sp_name($passengersename); + //乘客类型 switch ($item->BPE_GuestType) { case 1: $piaotype = 1; @@ -485,29 +488,89 @@ class Index extends CI_Controller{ $piaotypename = "成人票"; break; } - $passporttypeseid = "B"; //护照 - $passporttypeseidname = "护照"; - $passportseno = $item->BPE_Passport; - $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + switch ($item->BPE_SEX){ + case '100003': + $sex = 'F'; + break; + case '100001': + $sex = 'M'; + break; + } + + $passportseno = str_replace(' ','',$item->BPE_Passport); + + //添加一个判断护照号是否在黑名单 + if(in_array($passportseno,$black_list)){ + $rebakc["mes"]="乘客为黑名单用户"; + echo json_encode($rebakc); + return false; + } + + if($passporttypeseid == 'G'){ + $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '","gatValidDateEnd":"'.$item->BPE_PassExpdate.'","gatBornDate":"'.$item->BPE_BirthDate.'","sexCode":"'.$sex.'"}'; + }else{ + $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; + } + } $passengers.="]"; $passengers = substr($passengers, 1); $passengers = "[" . $passengers; $url=$this->dp_api; - $post_data=array( + if(empty($selectseat)){ + $post_data=array( "key"=>$this->key, "user_orderid"=>$cold_sn,//自定义订单号 "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", "from_station_name"=>$data["train"]->DepartAirport_cn, "from_station_code"=>$data["train"]->DepartAirport, "to_station_code"=>$data["train"]->ArrivalAirport, "to_station_name"=>$data["train"]->ArrivalAirport_cn, "passengers"=>$passengers, "checi"=>$data["train"]->FlightsNo - ); + ); + }else{ + $post_data=array( + "key"=>$this->key, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + } + //print_r($post_data); + //die(); $bakc_json=$this->post_data($url,$post_data); $bakc=json_decode($bakc_json);//json=>obj - + $add_data=new StdClass(); $add_data->JOL_COLD_SN=(int)$cold_sn; @@ -530,15 +593,19 @@ class Index extends CI_Controller{ $rebakc["mes"]= $bakc_json; $add_data->JOL_Status="e"; } - $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data); + $isauto = false; + $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data,$isauto); echo json_encode($rebakc); return false; } + + //根据汉特订单明细表SN来获取车次,乘客信息,拼接成聚合提交订单的url public function submit_juhe_order() { $cold_sn=$this->input->get("order"); + $selectseat=$this->input->get("selectseat"); $data = array(); $rebakc=array();//返回数据 $rebakc["status"]=0; @@ -565,6 +632,7 @@ class Index extends CI_Controller{ echo json_encode($rebakc); return false; } + if (count($data['people_list']) > 5) { //显示错误,用户超过五个 $rebakc["mes"]="乘客不能超过五个"; @@ -574,14 +642,16 @@ class Index extends CI_Controller{ $db_train_zw = $this->config->item('db_train_zw'); $train_zw = $this->config->item('train_zw'); - + $black_list = $this->config->item('black_list'); + $passengers=''; foreach ($data['people_list'] as $key => $item) { $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 //乘客姓名 - $passengersename = trim($item->BPE_FirstName) . trim($item->BPE_MiddleName) . trim($item->BPE_LastName); - //乘客类型 + $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName; + $passengersename = $this->chk_sp_name($passengersename); + //乘客类型 switch ($item->BPE_GuestType) { case 1: $piaotype = 1; @@ -596,9 +666,38 @@ class Index extends CI_Controller{ $piaotypename = "成人票"; break; } - $passporttypeseid = "B"; //护照 - $passporttypeseidname = "护照"; - $passportseno = $item->BPE_Passport; + + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + /*$passporttypeseid = "B"; //护照 + $passporttypeseidname = "护照";*/ + + $passportseno = str_replace(' ','',$item->BPE_Passport); + + //添加一个判断护照号是否在黑名单 + if(in_array($passportseno,$black_list)){ + $rebakc["mes"]="乘客为黑名单用"; + echo json_encode($rebakc); + return false; + } + $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; } $passengers.="]"; @@ -609,13 +708,17 @@ class Index extends CI_Controller{ "key"=>$this->key, "user_orderid"=>$cold_sn,//自定义订单号 "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, "from_station_name"=>$data["train"]->DepartAirport_cn, "from_station_code"=>$data["train"]->DepartAirport, "to_station_code"=>$data["train"]->ArrivalAirport, "to_station_name"=>$data["train"]->ArrivalAirport_cn, "passengers"=>$passengers, "checi"=>$data["train"]->FlightsNo - ); + ); + //print_r($selectseat); + //die(); $bakc_json=$this->post_data($url,$post_data); $bakc=json_decode($bakc_json);//json=>obj @@ -641,7 +744,8 @@ class Index extends CI_Controller{ $rebakc["mes"]= $bakc_json; $add_data->JOL_Status="e"; } - $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data); + $isauto = false; + $add_back_data=$this->BIZ_train_model->add_biz_jol($add_data,$isauto); echo json_encode($rebakc); return false; @@ -709,6 +813,7 @@ class Index extends CI_Controller{ "key"=>$this->key, "user_orderid"=>$order,//自定义订单号 "train_date"=>substr($data->cold[0]->COLD_StartDate, 0, 10), + "is_accept_standing"=>"no", "from_station_name"=>$data->cold[0]->LeaveStation, "from_station_code"=>$data->cold[0]->DepartAirport, "to_station_code"=>$data->cold[0]->ArrivalAirport, @@ -763,8 +868,51 @@ class Index extends CI_Controller{ die(json_encode($rebakc)); } + //测试支付 + public function test_pay(){ + $url=$this->dp_api; + $post_data=array( + "key"=>$this->key, + "user_orderid"=>'123456',//自定义订单号 + "train_date"=>'2017-10-05', + "from_station_name"=>'桂林站', + "from_station_code"=>'GLZ', + "to_station_code"=>'GBZ', + "to_station_name"=>'桂林北', + "checi"=>"D8494", + "passengers"=>'[{ + "passengerid":1, + "passengersename":"陈宇超", + "piaotype":"1", + "piaotypename":"成人票", + "passporttypeseid":"1", + "passporttypeseidname":"二代身份证", + "passportseno":"450302199208131039", + "price":"5.5", + "zwcode":"O", + "zwname":"二等座" + }]' + ); + + $bakc_json=$this->post_data($url,$post_data); + $bakc=json_decode($bakc_json);//json=>obj + print_r($bakc); + } + + //测试 + public function testjson(){ + $post_data=array( + "key"=>$this->key, + "orderid"=>'JH150485160583226' + ); + $back_json=$this->my_post($this->pay_api,$post_data); + print_r($back_json); + } + + //回调控制 public function sub_callback(){ $data_post=$this->input->post(); + log_message('error','聚合回调:'.json_encode($data_post)); $data=json_decode($data_post["data"]); $this->load->model("order_people_model","op"); @@ -780,9 +928,8 @@ class Index extends CI_Controller{ "orderid"=>$data->orderid ); $back_json=$this->my_post($this->pay_api,$post_data); - $back=json_decode($back_json); - $update_data->JOL_BackTxt=$back_json; - $update_data->JOL_RebackMsg=$back->reason; + $update_data->JOL_BackTxt=json_encode($back_json); + $update_data->JOL_RebackMsg=$back_json['reason']; }elseif($data->status=="4"){ //付款成功 写入TOC表 $add_train_order_data->TOC_Memo=$data->orderid; @@ -792,7 +939,45 @@ class Index extends CI_Controller{ $add_train_order_data->TOC_TicketCost=$data->orderamount; $add_train_order_data->poundage=(count($data->passengers)*2)."";//手续费,每人两块,转换成字符串 $add_train_order_data->FOI_TrainNetOrderNo=$data->ordernumber; - $this->op->add_train_order($add_train_order_data); + $this->op->add_train_order($add_train_order_data); + + $coach = array(); + $seats = array(); + $string = ''; + $passagers = $data->passengers; + foreach($passagers as $item){ + foreach(explode(',',$item->cxin) as $item){ + if(strpos($item,'车厢')){ + $item = str_replace('车厢','',$item); + array_push($coach,$item); + }else{ + $find = array('座上铺','座中铺','座下铺','座'); + $replace = array(' upper',' middle',' lower',''); + $item = str_replace($find,$replace,$item); + array_push($seats,$item); + } + } + } + + //判断车厢是否唯一,如果不唯一的话,分成两个车厢 + if(count(array_unique($coach)) == 1){ + $onlycoach = array_unique($coach); + $string .= 'Coach '.$onlycoach[0].','; + }else{ + foreach (array_unique($coach) as $item_coach){ + $string .= 'Coach '.$item_coach.','; + } + } + + $string .= 'Seat '; + foreach($seats as $item_seat){ + $string .= $item_seat.','; + } + + $seatinfo = substr($string,0,strlen($string)-1); + $this->BIZ_train_model->addseatinfo($seatinfo,$add_train_order_data->TOC_COLD_SN); + //成功出票后对订单状态进行更新 + //$this->update_state($add_train_order_data->TOC_COLD_SN,'4'); }elseif($data->status=="7"){ //退票成功 写入TOC表 $newtime="";//记录最新操作时间 @@ -815,19 +1000,130 @@ class Index extends CI_Controller{ $add_train_order_data->TOC_DepartureDate=$data->train_date; $add_train_order_data->TOC_TicketCost=-$refund_money; $add_train_order_data->FOI_TrainNetOrderNo=null;//退票不用更新取票号,以此在模型里面判断是否为退票消息 + //成功出票后对订单状态进行更新 + //$this->update_state($add_train_order_data->TOC_COLD_SN,'7'); $this->op->add_train_order($add_train_order_data); } - + $this->op->update_cold_planvei_sn($data->user_orderid); $this->op->update_jh_order($update_data); echo "success"; } + + //更新订单状态 + public function update_state($cold_sn,$status){ + //验证传参 + if(empty($cold_sn) || empty($status)){ + exit('传参错误'); + } + + + $coli_sn = $this->BIZ_train_model->cold_sn_get_coli_sn($cold_sn); + $coli_sn = $coli_sn[0]->COLD_COLI_SN; + //获取订单站点 + $web_code = $this->BIZ_train_model->get_order_webcode($coli_sn)->COLI_WebCode; + + //判断CH的订单才做处理 + if(strtoupper($web_code) == 'CHT'){ + /*switch ($status){ + case '4': + $status = '61'; + break; + case '7': + $status = '64'; + break; + default: + $status = '63'; + break; + }*/ + + //先更新当前子订单 + $this->BIZ_train_model->update_cold_state($status,$cold_sn); + + //更新主订单状态 + $this->BIZ_train_model->update_coli_state('63',$coli_sn); + + /* + $all_train = $this->BIZ_train_model->get_alltrain($coli_sn); + $all_count = count($all_train); + + $status_count = 0; + + foreach($all_train as $value){ + if($value->COLD_State == $status){ + $status_count++; + } + } + + //更新主订单状态 + if($status_count >= $all_count){ + $this->BIZ_train_model->update_coli_state($status,$coli_sn); + }else{ + + }*/ + } + } + + //发邮件给外联 + public function send_mail_to_wl($subject,$body,$coli_id){ + //$subject = 'autopay ticket'; + //$body = 'this is autopay ticket'; + $this->load->model("Sendmail_model"); + $fromName = "cyc"; + $fromEmail = "cyc@hainatravel.com"; + //获取该订单的操作员的邮箱以及姓名 + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + } + + //发邮件给客人 + public function send_mail_to_guest($coli_id,$jh_order){ + $this->load->model("Sendmail_model"); + $info = $this->BIZ_train_model->get_user_info($jh_order); + $guest = $this->BIZ_train_model->get_guest_info($coli_id); + $operator_info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $fromName = $operator_info[0]->Name; + $fromEmail = $operator_info[0]->OPI_Email; + $toName = $guest[0]->GUT_LastName; + $toEmail = $guest[0]->GUT_Email;// + $data['coli_id'] = $coli_id; + $data['toname'] = $toName; + $data['adult'] = $info->COLD_PersonNum; + $data['chlid'] = $info->COLD_ChildNum; + $data['baby'] = $info->COLD_BabyNum; + $data['price'] = $this->BIZ_train_model->get_paypal($coli_id); + $data['allpeople'] = $this->BIZ_train_model->biz_people($info->COLD_SN); + $data['train_info'] = $this->BIZ_train_model->get_biz_foi($info->COLD_SN); + $data['juhe_info'] = json_decode($this->BIZ_train_model->get_biz_jol_info($info->COLD_SN,$jh_order)->JOL_BackTxt); + $data['operator'] = $operator_info; + $data['emailarr'] = explode(';',$operator_info[0]->Email); + /*$order = $jh_order; + $post_data=array( + "key"=>"79f03107b921ef31310bd40a1415c1cb", + "orderid"=>$order + ); + $back_data=$this->my_post("http://op.juhe.cn/trainTickets/orderStatus",$post_data); + $data['result'] = $back_data['result']; + print_r($data['result']);*/ + $subject = "Got payment and issued train ticket(s), Order No $coli_id"; + $body = $this->load->view('email',$data,true); + //print_r($data); + //print_r($body); + //die(); + //$this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + //测试阶段,将确认信发送一份给操作外联。 + $this->Sendmail_model->SendMailToTable('cyc','cyc@hainatravel.com','cyc','cyc@hainatravel.com','确认信副本',$body); + } + //汉特&聚合 订单列表 public function ht_order_list(){ $this->load->model("order_people_model","op"); $page_size=10; $page=$this->input->get("page"); $order=$this->input->get("order"); + $web_code=$this->input->get("web_code"); $where="1=1";//搜索条件 $page_parameter="";//返回的分页条件参数 if(empty($page) or !is_numeric($page)){ @@ -835,10 +1131,16 @@ class Index extends CI_Controller{ } if(!empty($order)){ $where="BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR JOL_JuheOrder='{$order}'"; + $where2="where BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR JOL_JuheOrder='{$order}'"; $list["order"]=$order; - $page_parameter="order=".$order."&"; + $page_parameter="order=".$order; } + if(!empty($web_code)){ + $where="BIZ_ConfirmLineInfo.COLI_WebCode='{$web_code}'"; + $page_parameter="web_code=".$web_code; + } $data=$this->op->get_order($page_size,$page,$where); + //print_r($data); $list["data"]=$data->list; $this->load->library('pagination'); @@ -860,8 +1162,7 @@ class Index extends CI_Controller{ foreach ($list["data"] as $key => $value) { $value->info=$this->order_status_msg[$value->JOL_Status];//自定义说明信息; } - - + $this->load->view('bootstrap3/header'); $this->load->view('ht_order_list.html',$list); @@ -889,9 +1190,13 @@ class Index extends CI_Controller{ $this->load->view('ht_train_order.html',$list); $this->load->view('bootstrap3/footer'); } - //输入翰特订单号cols_id,获取火车订票的相关信息,模拟翰特订单详情页面 - public function ht_train_order_info(){ - $cols_id=$this->input->post("ht_order"); + + public function ht_train_order_info($coli_id=null){ + if($coli_id == null){ + $cols_id=$this->input->post("ht_order"); + }else{ + $cols_id = $coli_id; + } $list=new StdClass; if(!empty($cols_id)){ $cold_sn=$this->BIZ_train_model->get_biz_cold($cols_id); @@ -921,6 +1226,45 @@ class Index extends CI_Controller{ $this->load->view('ht_train_order_info',$list); $this->load->view('bootstrap3/footer'); } + + //输入翰特订单号cols_id,获取火车订票的相关信息,模拟翰特订单详情页面 + public function ht_train_order_info_test($coli_id=null){ + if($coli_id == null){ + $cols_id=$this->input->post("ht_order"); + }else{ + $cols_id = $coli_id; + } + + $list=new StdClass; + if(!empty($cols_id)){ + $cold_sn=$this->BIZ_train_model->get_biz_cold($cols_id); + $list->wl=$this->BIZ_train_model->get_operatorinfo($cols_id); + $i=0; + $list->info=array(); + foreach ($cold_sn as $v) { + $list->info[$i]=new StdClass; + $list->info[$i]->people=$this->BIZ_train_model->biz_people($v->COLD_SN); + $list->info[$i]->train=$this->BIZ_train_model->get_biz_foi($v->COLD_SN); + $list->info[$i]->status=$this->BIZ_train_model->get_biz_jol($v->COLD_SN); + $i++; + } + $list->cols_id=$cols_id; + } + $post_data=array( + "key"=>$this->key + ); + $back_data=$this->post_data($this->balance_api,$post_data); + $back_data = json_decode($back_data); + if(!empty($back_data->result)){ + $list->balance = $back_data->result; + }else{ + $list->balance = "NULL"; + } + //print_r($list); + $this->load->view('bootstrap3/header'); + $this->load->view('ht_train_order_info_test',$list); + $this->load->view('bootstrap3/footer'); + } //订单信息填写 public function booking_write(){ $this->load->model("order_people_model","op"); @@ -1088,13 +1432,17 @@ class Index extends CI_Controller{ $post_data=array( "key"=>"79f03107b921ef31310bd40a1415c1cb", "orderid"=>$order - ); + ); $back_data=$this->my_post("http://op.juhe.cn/trainTickets/orderStatus",$post_data); $data=array( "JOL_Status"=>$back_data["result"]["status"], - "JOL_RebackMsg"=>$back_data["result"]["msg"] + "JOL_RebackMsg"=>$back_data["result"]["msg"], + "JOL_Price"=>$back_data["result"]["orderamount"] ); + //print_r($back_data); + //die(); $this->load->model("BIZ_train_model"); + //print_r($back_data); //查询到订单最新情况,更新本地数据库 $this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$order),$data); // var_dump($back_data); @@ -1103,6 +1451,8 @@ class Index extends CI_Controller{ $this->load->view('bootstrap3/footer'); } } + + //取消订单 public function cancel_order(){ if($order=$this->input->get("order")){ @@ -1140,6 +1490,7 @@ class Index extends CI_Controller{ "JOL_Status"=>$back_data["result"]["status"], "JOL_RebackMsg"=>$back_data["result"]["msg"] ); + //print_r($back_data); $this->load->model("BIZ_train_model"); //查询到订单最新情况,更新本地数据库 $this->BIZ_train_model->update_biz_jol(array("JOL_JuheOrder"=>$order),$data); @@ -1155,6 +1506,20 @@ class Index extends CI_Controller{ $passporttypeseid=$this->input->get("passporttypeseid"); $ticket_no=$this->input->get("ticket_no"); $passengername=$this->input->get("name"); + + if(empty($ticket_no)){ + $post_data=array( + "key"=>$this->key, + "orderid"=>$order + ); + $back_data=$this->my_post($this->status_api,$post_data); + foreach($back_data['result']['passengers'] as $items){ + if($items['passengersename'] == $passengername && $items['passportseno']){ + $ticket_no = $items['ticket_no']; + $passporttypeseid = $items['passporttypeseid']; + } + } + } if(!empty($order) && !empty($passportseno) && !empty($passporttypeseid) && !empty($ticket_no) && !empty($passengername)){ $post_data=array( @@ -1162,6 +1527,7 @@ class Index extends CI_Controller{ "orderid"=>$order, "tickets"=>'[{"ticket_no":"'.$ticket_no.'","passengername":"'.$passengername.'","passporttypeseid":"'.$passporttypeseid.'","passportseno":"'.$passportseno.'"}]', ); + //print_r($post_data);die(); $back_data=$this->my_post($this->refund_api,$post_data); if($back_data["error_code"]==0){ @@ -1170,6 +1536,22 @@ class Index extends CI_Controller{ } return; } + + public function get_mailinfo($m_sn=null){ + if(!$m_sn){ + exit('error!!请联系cyc'); + } + $obj = $this->BIZ_train_model->get_mail($m_sn); + if($obj->M_State){ + echo '<span style="color:green;">邮件发送成功</span><br>提交时间:'.$obj->M_AddTime.'<br>'; + }else{ + echo '<span style="color:red;">邮件已提交,但还未发送成功,10分钟后刷新查看最新状态</span><br>提交时间:'.$obj->M_AddTime.'<br>'; + } + echo '<span>发件邮箱:'.$obj->M_ReplyToEmail.'</span>'; + echo '<hr/>'; + print_r($obj->M_Body); + } + function my_post($url,$post_data){ // $url = "http://op.juhe.cn/trainTickets/cityCode"; // $post_from = array("stationName" => $from,"key"=>"79f03107b921ef31310bd40a1415c1cb"); @@ -1212,5 +1594,17 @@ class Index extends CI_Controller{ // $output=json_decode($output,TRUE);//json => array return $output; } - + + function chk_sp_name($name){ + $name = str_replace( + array('á', 'é', 'è', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ',' ','/',' ',','), + array('a', 'e', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N','','','',''), + $name + ); + return substr(strtoupper($name),0,30); + } + + public function test(){ + $this->BIZ_train_model->test(); + } } \ No newline at end of file diff --git a/application/third_party/train/controllers/junjun.php b/application/third_party/train/controllers/junjun.php new file mode 100644 index 00000000..2c38d755 --- /dev/null +++ b/application/third_party/train/controllers/junjun.php @@ -0,0 +1,366 @@ +<?php +/** +junjun.php +用于测试自动出票中出现的问题。 +查询coli_sn来测试。 +*/ +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + +class junjun extends CI_Controller{ + + public function __construct() { + header("Content-Type: text/html;charset=utf-8"); + parent::__construct(); + $this->config->load('config'); + $this->order_status_msg=$this->config->item('train_order_status_msg'); + $this->key=JUHE_TRAIN_API_KEY; + $this->cx_api=JUHE_TRAIN_CX_API; + $this->dp_api=JUHE_TRAIN_DP_API; + $this->qxdd_api=JUHE_TRAIN_CANCEL_API; + $this->pay_api=JUHE_TRAIN_PAY_API; + $this->refund_api=JUHE_TRAIN_REFUND_API; + $this->status_api=JUHE_TRAIN_STATUS_API; + $this->code_zw=$this->config->item('train_zw'); + $this->piaotype=$this->config->item('train_piaotype'); + $this->passportty=$this->config->item('train_passportty'); + $this->balance_api = "http://op.juhe.cn/trainTickets/balance.php";//余额 + $this->load->model("BIZ_train_model");//加载模型 + } + + public function test(){ + $arr = array('',''); + print_r($arr); + echo count($arr); + if(!empty($arr)){ + echo '123'; + } + } + + + public function index(){ + $this->ticketype = 1; + //筛选出能自动出票的订单 + $auto_pool = $this->BIZ_train_model->auto_check_ticket(); + //print_r($auto_pool); + $auto_pool = array('0'=>(object)array('COLD_SN'=>'488096935','coli_id'=>'180824444','COLI_State'=>'13')); + //print_r($auto_pool); + //创建一个不允许自动出票的国际火车票数组 + $nation_train = array('K19', 'K23', 'Z8701', 'Z8702', 'Z97', 'Z98', 'Z99', 'Z100', 'K9795'); + + //创建黑名单 + $black_list = $this->config->item('black_list'); + $string = ''; + foreach($auto_pool as $item){ + $this->ticketype = 1; + $back_message = ''; + $cold_sn = $item->COLD_SN; + $coli_id = $item->coli_id; + $back_data = 1; + + $people_arr = $this->BIZ_train_model->biz_people($cold_sn); + $train_info = $this->BIZ_train_model->get_biz_foi($cold_sn); + /* + if($item->COLD_SPFS > 1){ + //寄送票 + $back_data = 0; + $back_message .= '-邮寄不自动出票'; + } + */ + //乘客人数大于5人不出票 + if(count($people_arr) > 5){ + $back_data = 0; + $back_message .= '-乘客人数大于5不自动出票'; + } + + //护照号如果在黑名单的就不自动出票 + foreach($people_arr as $people_info){ + if(in_array($people_info->BPE_Passport,$black_list)){ + $back_data = 0; + $back_message .= '-此用户为黑名单用户,不自动出票'; + } + + if(strlen($people_info->BPE_Passport) >= 18){ + $back_data = 0; + $back_message .= '-护照位数大于18不自动出票'; + } + } + + //单张票价不能大于1000人民币 + if($train_info[0]->adultcost > 1000){ + $back_data = 0; + $back_message .= '-单价大于1000不自动出票'; + } + + //如果为国际火车票就不出票 + if(in_array($train_info[0]->FlightsNo, $nation_train)){ + $back_data = 0; + $back_message .= '-国际火车票不自动出票'; + } + + //无座的订单不做出票 + if($train_info[0]->Aircraft == 'WZ'){ + $back_data = 0; + $back_message .= '-无座不自动出票'; + } + + //香港火车不自动出票 + if($train_info[0]->ArrivalAirport == 'XJA' || $train_info[0]->DepartAirport == 'XJA'){ + $back_data = 0; + $back_message .= '-香港火车不自动出票'; + } + //print_r($train_info); + + //如果刚好是第三十天的订单 + if(($item->COLI_State == '8' || $item->COLI_State == '63')){ + $this->ticketype = 3; + $time_obj = $this->BIZ_train_model->get_saletime($train_info['0']->DepartAirport_cn); + if(!empty($time_obj)){ + $saletime = strtotime($time_obj->TST_saletime); + $now_time = time(); + $sale_diff = (time() - $saletime) / 3600; + if($sale_diff > 1){ + $back_data = 0; + $back_message .= '-超过抢票时间'; + }else if($sale_diff <0){ + $back_data = 0; + $back_message .= '-未到抢票时间'; + } + } + } + + if($back_data == 0){ + $string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')'.$back_message.'</td></tr>'; + }else{ + //单个订单提交 + //$this->submit_juhe_order($cold_sn,$coli_id); + $string .= '<tr><td>汉特订单号:'.$coli_id.'('.$cold_sn.')可以自动出票</td></tr>'; + } + } + print_r('<table border="1">'.$string.'</table>'); + } + + + public function submit_juhe_order($cold_sn,$coli_id) { + $this->load->model("BIZ_train_model"); + $cold_sn='488079918';//488084043 + //$cold_sn=$this->input->get("order"); + //$bpe_sn=$this->input->get("people"); + //$selectseat=$this->input->get("selectseat"); + //$bpe_sn = '(473118360); + $data = array(); + $rebakc=array();//返回数据 + $rebakc["status"]=0; + $rebakc["mes"]=""; + if(!is_numeric($cold_sn)){ + $rebakc["mes"]="订单号是数字"; + echo json_encode($rebakc); + return false; + } + if(empty($bpe_sn)){ + $rebakc["mes"]="请选择乘客"; + echo json_encode($rebakc); + return false; + } + + $data['train'] = $this->BIZ_train_model->biz_order_detail($cold_sn); + $data['people_list']=$this->BIZ_train_model->in_bpesn_people_info($bpe_sn); + if (empty($data['train'])) { + //显示错误,找不到车次 + $rebakc["mes"]="找不到车次"; + echo json_encode($rebakc); + return false; + + } + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $rebakc["mes"]="找不到乘客信息"; + echo json_encode($rebakc); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $rebakc["mes"]="乘客不能超过五个"; + echo json_encode($rebakc); + return false; + } + $db_train_zw = $this->config->item('db_train_zw'); + $train_zw = $this->config->item('train_zw'); + $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 + $black_list = $this->config->item('black_list'); + + $passengers=""; + foreach ($data['people_list'] as $key => $item) { + + //乘客姓名 + $passengersename = $item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName; + //将特殊字符转换为正常字符以便于出票 + $passengersename = $this->chk_sp_name($passengersename); + //乘客类型 + switch ($item->BPE_GuestType) { + case 1: + $piaotype = 1; + $piaotypename = "成人票"; + break; + case 2: + $piaotype = 2; + $piaotypename = "儿童票"; + break; + default://外国人应该就两种票吧 + $piaotype = 1; + $piaotypename = "成人票"; + break; + } + + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + + $passportseno = str_replace(' ','',$item->BPE_Passport); + + //添加一个判断护照号是否在黑名单 + if(in_array($passportseno,$black_list)){ + $rebakc["mes"]="乘客为黑名单用户"; + echo json_encode($rebakc); + return false; + } + + $passengers.=',{"passengerid":' . ( ++$key) . ',"passengersename":"' . $passengersename . '","piaotype":"' . $piaotype . '","piaotypename":"' . $piaotypename . '","passporttypeseid":"' . $passporttypeseid . '","passporttypeseidname":"' . $passporttypeseidname . '","passportseno":"' . $passportseno . '","price":"1","zwcode":"' . $zwcode . '","zwname":"' . $zwname . '"}'; + } + $passengers.="]"; + $passengers = substr($passengers, 1); + $passengers = "[" . $passengers; + $url=$this->dp_api; + if(empty($selectseat)){ + $post_data=array( + "key"=>$this->key, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + }else{ + $post_data=array( + "key"=>$this->key, + "user_orderid"=>$cold_sn,//自定义订单号 + "train_date"=>substr($data["train"]->DepartureDate, 0, 10), + "is_accept_standing"=>"no", + "choose_seats"=>$selectseat, + "from_station_name"=>$data["train"]->DepartAirport_cn, + "from_station_code"=>$data["train"]->DepartAirport, + "to_station_code"=>$data["train"]->ArrivalAirport, + "to_station_name"=>$data["train"]->ArrivalAirport_cn, + "passengers"=>$passengers, + "checi"=>$data["train"]->FlightsNo + ); + } + + return $coli_id.'('.$cold_sn.')可以自动出票'; + } + + // + public function count_select(){ + $obj = $this->BIZ_train_model->get_juhe_select(); + //print_r($obj); + $html = ''; + $html .= '<table border="1">'; + $html .= '<tr><th>序号</th><th>聚合订单号</th><th>出票后信息</th><th>订单原信息</th><th>是否自动出票</th></tr>'; + $i = 1; + foreach($obj as $item){ + $html .= '<tr><td>'.$i.'</td><td>'.$item->JOL_JuheOrder.'</td>'; + if(isset(json_decode($item->JOL_BackTxt)->passengers)){ + $passengers = json_decode($item->JOL_BackTxt)->passengers; + }else{ + $passengers = ''; + } + $ex_obj = ''; + if(!empty($passengers)){ + foreach($passengers as $pass_tiem){ + $ex_obj .= $pass_tiem->cxin; + } + } + if($item->JOL_IsAuto == '1'){ + $item->JOL_IsAuto ='是'; + }else{ + $item->JOL_IsAuto ='否'; + } + $html .= '<td>'.$ex_obj.'</td><td>'.$item->FOI_SelectedSeat.'</td><td>'.$item->JOL_IsAuto.'</td></tr>'; + $i++; + } + $html .= '</table>'; + echo $html; + } + + public function update_juheorder(){ + print_r($this->BIZ_train_model->test()); + } + + public function update_state($cold_sn){ + //先更新当前订单 + $flag = $this->BIZ_train_model->update_cold_state($cold_sn); + if(!$flag){ + log_message('error','状态更新失败:'.$cold_sn); + }else{ + $coli_sn = $this->BIZ_train_model->cold_sn_get_coli_sn($cold_sn); + $coli_sn = $coli_sn[0]->COLD_COLI_SN; + $all_train = $this->BIZ_train_model->get_alltrain($coli_sn); + $all_count = count($all_train); + $success_count = 0; + foreach($all_train as $value){ + if($value->COLD_State == '61'){ + $success_count++; + } + } + if($all_count == $success_count){ + $this->BIZ_train_model->update_coli_state('61',$coli_sn); + }else{ + $this->BIZ_train_model->update_coli_state('62',$coli_sn); + } + } + } + + //测试发送邮件 + public function test_send(){ + $phone = '18677367018'; + $name = 'sw'; + $coli_id = '780258'; + $email = 'sw@hainatravel.com'; + + $mail_data = array(); + $mail_data['name'] = $name; + $mail_data['phone'] = $phone; + $mailtitle = 'Signup successfully on China Highlights Customer Center'; + $mail_body = $this->load->view('train_help',$mail_data,true); + $fromName = 'China Highlights Customer Center'; + $fromEmail = 'sharon@chinahighlights.net'; + $toName = $name; + $toEmail = $email; + $this->load->model("Sendmail_model"); + $this->Sendmail_model->SendMailToTable($fromName, $fromEmail, $toName, $toEmail, $mailtitle, $mail_body); + } + +} +?> \ No newline at end of file diff --git a/application/third_party/train/controllers/tuniu_callback.php b/application/third_party/train/controllers/tuniu_callback.php new file mode 100644 index 00000000..57917914 --- /dev/null +++ b/application/third_party/train/controllers/tuniu_callback.php @@ -0,0 +1,251 @@ +<?php +if (!defined('BASEPATH')) + exit('No direct script access allowed'); + + +class Tuniu_callback extends CI_Controller{ + public function __construct(){ + // header("Content-Type: text/html;charset=utf-8"); + parent::__construct(); + $this->load->library('Des'); + $this->load->model("BIZ_train_model"); + $this->load->model("tuniu_model"); + } + /* + 接收占位回调 + */ + public function book(){ + $back_json = file_get_contents('php://input'); + log_message('error','预定占座回调:'.$back_json); + $back_data_one = json_decode(base64_decode($back_json)); + $back_data = array(); + $crypt = new DES(); + $mstr = $crypt->decrypt($back_data_one->data,TUNIU_KEY); + $back_data_two = json_decode($mstr); + + $back_data['errorMsg'] = $back_data_one->errorMsg; + $back_data['returnCode'] = $back_data_one->returnCode; + $back_data['retailOrderId'] = $back_data_two->retailOrderId; + $back_data['orderId'] = $back_data_two->orderId; + $back_data['orderAmount'] = $back_data_two->orderAmount; + $back_data['fromStationCode'] = $back_data_two->fromStationCode; + $back_data['fromStationName'] = $back_data_two->fromStationName; + $back_data['toStationCode'] = $back_data_two->toStationCode; + $back_data['toStationName'] = $back_data_two->toStationName; + $back_data['cheCi'] = $back_data_two->cheCi; + $back_data['backtxt'] = $mstr; + $back_data['status'] = '2'; + //更新预定异步回调信息 + $this->tuniu_model->book_tuniu_order($back_data); + if($back_data['returnCode'] == '231000'){ + $url = 'http://www.mycht.cn/info.php/apps/train/tuniu_train/confirm_ticket/'.$back_data['retailOrderId'].'/'.$back_data['orderId']; + echo $url; + $this->get_http($url,'GET'); + } + } + + public function test(){ + $back_json = "eyJlcnJvck1zZyI6IuihjOeoi+WGsueqgSIsInJldHVybkNvZGUiOjMwMywiZGF0YSI6IjBwZE4zaWlUWE1ISzFPRndGL2Evei9vZzc1dVZsSVpwVzBKTFdnS3dybUlaYWRUSnhEVmNZeW5ib1BZWFBNaWhJazVEVzBhYlBQbDhcbitXdWFCUUVsbmlzcWhBN1ZJSndEZEVvN0JCR0t4RXZ2K0wya090cEkvV01aK0JGTEFJc1hyYi9ZMWM5MTZnUjhIOUROYTdYdXpUV29cbkpzdmI0eTF6aUI5U3BIYWFPM2pQWXZyRHAvMUJCZndPanRuQVNVK2plcGNyMkZoekVJRDRMOHpRV0hMSFNRc2ZoVzVDeHpoQ1J0VUhcbmNFc0tpL212ZEVRcGFEb0diZE1JOWxlWUp4TFZWT0xrNUdCbEh0cGVSNTVBNTNtckVJbExiYU9TNGlRMURCQjUrUjAydzNDYldreHpcblcwWXFFT2U0Znc4R2U2QksyczFlVlYwc1VMSU90YzBZTU00TU4xeUpITHFMdGxieHFKclhjZTJjNi9WYTNjMnJDSk5DN1ltZ004NWVcbi9wYTk2VHNhaytoYUtSNUFncUQ4OXd4aUhETkNlQmEzRHpXMlh2NUZiYVRUc3RJcHRYbTZEaHo5U1Q3ZkJkcTlzYkhSMHdqMlY1Z25cbkV0VWVSR1F5a1hadTJqUDBaZjc5YTFHaCJ9"; + //print_r(base64_encode($back_json)); + $back_data = $this->tuniu_strdecrypt($back_json); + print_r($back_data); + //echo (count($back_data->data->passengers)*5); + } + + /* + 接收取消占位回调 + */ + public function cancelbook(){ + $back_json = file_get_contents('php://input'); + $sn = 5830; + log_message('error','取消站位'.$back_json); + } + + /* + 接收确认出票回调 + */ + public function confirm(){ + $back_json = file_get_contents('php://input'); + //$back_json = 'eyJlcnJvck1zZyI6IuWkhOeQhuaIluaTjeS9nOaIkOWKnyIsInJldHVybkNvZGUiOjIzMTAwMCwiZGF0YSI6eyJyZXRhaWxPcmRlcklkIjoiNDg4MDkzNDQ4XzE1MzM3OTQwMDIiLCJvcmRlcklkIjoiMTE4NDUxMjM5NyJ9fQ=='; + $back_data = json_decode(base64_decode($back_json)); + //print_r($back_data); + //die(); + log_message('error','确认出票回调:'.$back_json); + $data = array(); + $data['errorMsg'] = $back_data->errorMsg; + $data['returnCode'] = $back_data->returnCode; + $data['retailOrderId'] = $back_data->data->retailOrderId; + $data['orderId'] = $back_data->data->orderId; + $data['confirmtxt'] = $back_json; + + if($back_data->returnCode != '231000'){ + $data['status'] = '1'; + }else{ + $data['status'] = '4'; + //通过订单号去获取预定时返回的信息 + $bookobj = $this->tuniu_model->get_tuniuorder_info($data['retailOrderId'],$data['orderId']); + $bookinfo = json_decode($bookobj[0]->tol_booktxt); + $obj = explode('_',$back_data->data->retailOrderId); + $add_train_order_data->TOC_COLD_SN = $obj[0]; + $add_train_order_data->TOC_Memo = $back_data->data->orderId; + $add_train_order_data->TOC_TrainNumber = $bookinfo->cheCi; + $add_train_order_data->TOC_DepartureDate = $bookinfo->trainDate; + $add_train_order_data->TOC_TicketCost = $bookinfo->orderAmount; + $add_train_order_data->FOI_TrainNetOrderNo = $bookinfo->orderNumber; + $add_train_order_data->poundage = (count($bookinfo->passengers)*3).""; + $this->tuniu_model->add_grab_order($add_train_order_data); + } + $this->tuniu_model->confirm_tuniu_order($data); + } + + /* + 接收退票回调 + */ + public function return_ticket(){ + $back_json = file_get_contents('php://input'); + log_message('error','退票回调:'.$back_json); + $back_data = $this->tuniu_strdecrypt($back_json); + //更新途牛订单列表信息 + $updata_data = array(); + $updata_data['retailOrderId'] = $back_data->data->retailOrderId; + $updata_data['returnCode'] = $back_data->returnCode; + $updata_data['errorMsg'] = $back_data->errorMsg; + $updata_data['returntxt'] = json_encode($back_data); + $this->tuniu_model->return_tuniu_order($updata_data); + + //添加瀚特信息(有问题) + /*$add_train_order_data = new stdClass(); + $obj = explode('_',$back_data->data->retailOrderId); + $add_train_order_data->TOC_COLD_SN = $obj[0]; + $add_train_order_data->TOC_Memo = $back_data->data->orderId." ".$back_data->data->returnTickets->passportNo; + $add_train_order_data->TOC_TrainNumber = $back_data->data->cheCi; + $add_train_order_data->TOC_TicketCost = $back_data->data->returnMoney; + $add_train_order_data->FOI_TrainNetOrderNo = null; + $this->tuniu_model->add_return_order($add_train_order_data);*/ + } + + /* + 接收线下退款回调 + */ + public function return_cash(){ + echo '回调接收线下退款数据'; + } + + /* + 接收抢票预定(占位) + */ + public function grabTicketBook(){ + $back_json = file_get_contents('php://input'); + $back_data = $this->tuniu_strdecrypt($back_json); + log_message('error','抢票预定:'.$back_json); + $update_data = array(); + if($back_data->returnCode == '231000'){ + $update_data['errorMsg'] = $back_data->errorMsg; + $update_data['returnCode'] = $back_data->returnCode; + $update_data['retailOrderId'] = $back_data->data->retailOrderId; + $update_data['orderId'] = $back_data->data->orderId; + $update_data['fromStationCode'] = $back_data->data->fromStationCode; + $update_data['fromStationName'] = $back_data->data->fromStationName; + $update_data['toStationCode'] = $back_data->data->toStationCode; + $update_data['toStationName'] = $back_data->data->toStationName; + $update_data['cheCi'] = $back_data->data->cheCi; + $update_data['orderAmount'] = $back_data->data->orderAmount; + $update_data['booktxt'] = json_encode($back_data); + //更新数据库信息 + $this->tuniu_model->grab_tuniu_order($update_data); + + //添加瀚特信息 + $add_train_order_data = new stdClass(); + $obj = explode('_',$back_data->data->retailOrderId); + $add_train_order_data->TOC_COLD_SN = $obj[0]; + $add_train_order_data->TOC_Memo = $back_data->data->orderId; + $add_train_order_data->TOC_TrainNumber = $back_data->data->cheCi; + $add_train_order_data->TOC_DepartureDate = $back_data->data->trainDate; + $add_train_order_data->TOC_TicketCost = $back_data->data->orderAmount; + $add_train_order_data->FOI_TrainNetOrderNo = $back_data->data->orderNumber; + $add_train_order_data->poundage = (count($back_data->data->passengers)*5).""; + $this->tuniu_model->add_grab_order($add_train_order_data); + //print_r($update_data['booktxt']); + }else{ + $update_data['retailOrderId'] = $back_data->data->retailOrderId; + $update_data['errorMsg'] = $back_data->errorMsg; + $update_data['returnCode'] = $back_data->returnCode; + $this->tuniu_model->update_status($update_data); + } + } + + /* + 接收取消抢票 + */ + public function cancelTicketBook(){ + $back_json = file_get_contents('php://input'); + log_message('error','取消抢票:'.$back_json); + $back_data = json_decode(base64_decode($back_json)); + $update_data = array(); + $update_data['errorMsg'] = $back_data->errorMsg; + $update_data['returnCode'] = $back_data->returnCode; + $update_data['orderId'] = $back_data->data->orderId; + $update_data['retailOrderId'] = $back_data->data->retailOrderId; + $this->tuniu_model->cancelgragticket($update_data); + } + + /* + 接收改签预定 + */ + public function change_occupy(){ + echo '回调接收改签预定数据'; + } + + /* + 接收改签确认 + */ + public function change_confirm(){ + echo '回调接收改签确认数据'; + } + + /* + 接收改签预定 + */ + public function change_cancel(){ + echo '回调接收改签取消数据'; + } + + //解密方法 + public function tuniu_strdecrypt($str){ + $back_data_one = json_decode(base64_decode($str)); + $back_data = array(); + $crypt = new DES(); + $mstr = $crypt->decrypt($back_data_one->data,TUNIU_KEY); + $back_data_one->data = json_decode($mstr); + return $back_data_one; + } + + + + //发送请求函数 + public function get_http($url, $data = '', $method = 'GET') { + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + if ($method == 'POST' && !empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); + } + curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $tmpInfo = curl_exec($curl); // 执行操作 + $errno = curl_errno($curl); + if ($errno !== 0) { + return false; + echo $errno . curl_error($curl); //记录错误日志 + } + curl_close($curl); //关闭CURL会话 + return $tmpInfo; //返回数据 + } +} \ No newline at end of file diff --git a/application/third_party/train/controllers/tuniu_train.php b/application/third_party/train/controllers/tuniu_train.php new file mode 100644 index 00000000..981b1c35 --- /dev/null +++ b/application/third_party/train/controllers/tuniu_train.php @@ -0,0 +1,778 @@ +<?php + +if (!defined('BASEPATH')) +exit('No direct script access allowed'); + +class Tuniu_train extends CI_Controller{ + + private $order_status_msg;//订单状态说明 + + public function __construct(){ + parent::__construct(); + //header("Content-Type: text/html;charset=utf-8"); + $this->load->library('Des'); + $this->load->model("tuniu_model"); + $this->load->model("order_people_model","op"); + } + + + //途牛出票页面 + public function index(){ + $cols_id=$this->input->post("ht_order"); + $list=new StdClass; + if(!empty($cols_id)){ + $cold_sn=$this->tuniu_model->get_biz_cold($cols_id); + $list->wl=$this->tuniu_model->get_operatorinfo($cols_id); + $i=0; + $list->info=array(); + foreach ($cold_sn as $v) { + $list->info[$i]=new StdClass; + $list->info[$i]->people=$this->tuniu_model->biz_people($v->COLD_SN); + $list->info[$i]->train=$this->tuniu_model->get_biz_foi($v->COLD_SN); + $list->info[$i]->status=$this->tuniu_model->get_biz_jol($v->COLD_SN); + $i++; + } + $list->cols_id=$cols_id; + } + $this->load->view('bootstrap3/header'); + $this->load->view('tuniu/ht_train_order_info',$list); + $this->load->view('bootstrap3/footer'); + } + + //订单列表 + public function ht_order_list(){ + $page_size=10; + $page=$this->input->get("page"); + $order=$this->input->get("order"); + $where="1=1";//搜索条件 + $page_parameter="";//返回的分页条件参数 + if(empty($page) or !is_numeric($page)){ + $page=0; + } + if(!empty($order)){ + $where="Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_ID='{$order}' OR tol_orderId='{$order}'"; + $list["order"]=$order; + $page_parameter="order=".$order."&"; + } + $data=$this->tuniu_model->get_order($page_size,$page,$where); + + $list["data"]=$data->list; + + $this->load->library('pagination'); + + $config['base_url'] = site_url("/apps/train/tuniu_train/ht_order_list?{$page_parameter}"); + $config['total_rows'] = $data->count; + $config['per_page'] = $page_size; + $config['page_query_string']=TRUE; + $config['query_string_segment']="page"; + $config['cur_tag_open'] = '<li class="active"><a href="#">'; + $config['cur_tag_close'] = '</a></li>'; + $config['first_tag_open']=$config['last_tag_open']=$config['next_tag_open']=$config['prev_tag_open']=$config['num_tag_open']="<li>"; + $config['first_tag_close']=$config['last_tag_close']=$config['next_tag_close']=$config['prev_tag_close']=$config['num_tag_close']="</li>"; + + $this->pagination->initialize($config); + + $list["page_link"]=$this->pagination->create_links(); + + foreach ($list["data"] as $key => $value) { + if($value->tol_Status == '2'){ + $value->info='预定'.$value->tol_errorMsg;//普通出票 + }else if($value->tol_Status == '4'){ + $value->info='出票'.$value->tol_errorMsg;//普通出票 + }else if($value->tol_Status == '7'){ + $value->info='退票'.$value->tol_errorMsg;//普通出票和抢票通用 + }else if($value->tol_Status == '8'){ + $value->info='抢票'.$value->tol_errorMsg;//取消抢票 + }else if($value->tol_Status == '9'){ + if($value->tol_returnCode == 231000){ + $value->info='抢票成功';//抢票执行结果 + }else{ + $value->info=$value->tol_errorMsg;//抢票执行结果 + } + }elseif($value->tol_Status == '6'){ + $value->info='抢票中';//抢票 + }elseif($value->tol_Status == '0'){ + $value->info=$value->tol_errorMsg;//站位 + }else{ + $value->info = ''; + } + + } + + $this->load->view('bootstrap3/header'); + $this->load->view('/tuniu/ht_order_list.html',$list); + $this->load->view('bootstrap3/footer'); + } + + + //选择乘客出票(一个或多个,不超过5个) + public function get_sn_submit_tuniu() { + $cold_sn = $this->input->get("order"); + $bpe_sn = $this->input->get("people"); + $coli_id = $this->input->get('coli_id'); + $selectseat = $this->input->get("selectseat"); + + $data = array(); + $rebakc = array();//返回数据 + $rebakc["status"]=0; + $rebakc["mes"]=""; + if(!is_numeric($cold_sn)){ + $rebakc["mes"]="订单号是数字"; + echo json_encode($rebakc); + return false; + } + if(empty($bpe_sn)){ + $rebakc["mes"]="请选择乘客"; + echo json_encode($rebakc); + return false; + } + + $data['train'] = $this->tuniu_model->biz_order_detail($cold_sn); + $data['people_list'] = $this->tuniu_model->in_bpesn_people_info($bpe_sn); + //$data['operator'] = $this->BIZ_train_model->get_operatorinfo($coli_id); + + if (empty($data['train'])) { + //显示错误,找不到车次 + $rebakc["mes"]="找不到车次"; + echo json_encode($rebakc); + return false; + + } + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $rebakc["mes"]="找不到乘客信息"; + echo json_encode($rebakc); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $rebakc["mes"]="乘客不能超过五个"; + echo json_encode($rebakc); + return false; + } + + $db_train_zw = $this->config->item('db_train_zw'); + $train_zw = $this->config->item('train_zw'); + $ticketype = $this->config->item('train_piaotype'); + $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 + $passengers=""; + $cold_sn = $cold_sn.'_'.time(); + + //拼接车次信息 + $tuniu_data = '{'; + $tuniu_data .= '"retailOrderId":"'.$cold_sn.'",'; + $tuniu_data .= '"cheCi": "'.$data['train']->FlightsNo.'", '; + $tuniu_data .= '"fromStationCode": "'.$data['train']->DepartAirport.'", '; + $tuniu_data .= '"fromStationName": "'.$data['train']->DepartAirport_cn.'", '; + $tuniu_data .= '"toStationCode": "'.$data['train']->ArrivalAirport.'", '; + $tuniu_data .= '"toStationName": "'.$data['train']->ArrivalAirport_cn.'", '; + $tuniu_data .= '"trainDate": "'.substr($data["train"]->DepartureDate, 0, 10).'", '; + $tuniu_data .= '"callBackUrl": "http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",'; + $tuniu_data .= '"hasSeat": true,'; + $tuniu_data .= '"contact": "陈宇超",'; + $tuniu_data .= '"phone": "18877381547",'; + $tuniu_data .= '"isChooseSeats": true,'; + $tuniu_data .= '"chooseSeats":"'.$selectseat.'",'; + + //循环乘客 + $passengers = ''; + foreach ($data['people_list'] as $key => $item) { + $passengers .= '{'; + $passengers .= '"passengerId":'.$key.','; + $passengers .= '"ticketNo":"null",'; + //乘客姓名 + $passengersename = str_replace(' ','',$item->BPE_FirstName) . str_replace(' ','',$item->BPE_MiddleName) . str_replace(' ','',$item->BPE_LastName); + //将特殊字符转换为正常字符以便于出票 + $passengersename = $this->chk_sp_name($passengersename); + $passengers .= '"passengerName":"'.$passengersename.'",'; + $passportseno = str_replace(' ','',$item->BPE_Passport); + + $passengers .= '"passportNo":"'.$passportseno.'",'; + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + //乘客类型 + switch ($item->BPE_GuestType) { + case 1: + $piaotype = 1; + $piaotypename = "成人票"; + break; + case 2: + $piaotype = 2; + $piaotypename = "儿童票"; + break; + default://外国人应该就两种票吧 + $piaotype = 1; + $piaotypename = "成人票"; + break; + } + + $passengers .= '"passportTypeId":"'.$passporttypeseid.'",'; + $passengers .= '"passportTypeName":"'.$passporttypeseidname.'",'; + + //票类型 + $passengers .= '"piaoType":"'.$item->BPE_GuestType.'",'; + $passengers .= '"piaoTypeName":"'.$ticketype[$item->BPE_GuestType].'",'; + + //座位类型piaoTypeName + $passengers .= '"zwCode":"'.$zwcode.'",'; + $passengers .= '"zwName":"'.$zwname.'",'; + + $passengers .= '"cxin":"null",'; + $passengers .= '"price":"'.$data['train']->adultcost.'",'; + $passengers .= '"reason": 0'; + $passengers .= '},'; + } + $passengers = substr($passengers,0,strlen($passengers)-1); + $passengers = '['.$passengers.']'; + $tuniu_data .= '"passengers": '.$passengers.'}'; + + //print_r($tuniu_data); + //die(); + $crypt = new DES(); + $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$this->create_sign().'", + "timestamp": "'.date('Y-m-d H:i:s',time()).'", + "data": "'.$mstr.'" + }'; + + $url = TUNIU_URL.'/train/book'; + $back_json = $this->get_http($url,$post_data,'POST'); + $back = json_decode($back_json);//json=>obj + //print_r($back_json); + if($back->success == 1){ + $rebakc["mes"]="订单提交成功,等待回调"; + }else{ + $rebakc["mes"]= $bakc_json; + } + $add_data=new StdClass(); + $add_data->tol_retailOrderId = $cold_sn; + if(isset($back->data->orderId)){ + $add_data->tol_orderId = $back->data->orderId; + }else{ + $add_data->tol_orderId = ''; + } + $add_data->tol_status = '0'; + $add_data->tol_fromStationName = $data['train']->DepartAirport_cn; + $add_data->tol_fromStationCode = $data['train']->DepartAirport; + $add_data->tol_toStationName = $data['train']->ArrivalAirport_cn; + $add_data->tol_toStationCode = $data['train']->ArrivalAirport; + $add_data->tol_errorMsg = $back->errorMsg; + $add_data->tol_cheCi = $data['train']->FlightsNo; + $isauto = false; + + $add_back_data=$this->tuniu_model->tuniu_add_biz_jol($add_data,$isauto); + + echo json_encode($rebakc); + return false; + } + + //取消占座 + public function cancel_book($retailOrderId,$orderId){ + $url = TUNIU_URL.'/train/cancel'; + $sign = $this->create_sign(); + $time = date('Y-m-d H:i:s',time()); + $crypt = new DES(); + $tuniu_data = '{ + "retailOrderId":"'.$retailOrderId.'", + "orderId":"'.$orderId.'", + "callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/cancelbook" + }'; + $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": "'.$mstr.'" + }'; + + $back_data = $this->get_http($url,$post_data,'POST'); + print_r($back_data); + } + + //确认出票 + public function confirm_ticket($retailOrderId=null,$orderId=null){ + $url = TUNIU_URL.'/train/confirm'; + $sign = $this->create_sign(); + $time = date('Y-m-d H:i:s',time()); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": { + "retailOrderId":"'.$retailOrderId.'", + "orderId":"'.$orderId.'", + "callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/confirm" + } + }'; + $back_data = $this->get_http($url,$post_data,'POST'); + + print_r($back_data); + } + + //退票接口 + public function cancel_ticket($retailOrderId,$orderId,$ticketNo=null){ + $url = TUNIU_URL.'/train/return'; + $sign = $this->create_sign(); + $time = date('Y-m-d H:i:s',time()); + $obj = $this->tuniu_model->get_tuniuorder_info($retailOrderId,$orderId); + $info = json_decode($obj[0]->tol_booktxt); + $orderNumber = $info->orderNumber; + $str = '['; + foreach($info->passengers as $item){ + if(empty($ticketNo)){ + $str .='{'; + $str .= '"ticketNo":"'.$item->ticketNo.'",'; + $str .= '"passengerName":"'.$item->passengerName.'",'; + $str .= '"passportTypeId":"'.$item->passportTypeId.'",'; + $str .= '"passportNo":"'.$item->passportNo.'"'; + $str .= '},'; + }else{ + if($item->ticketNo == $ticketNo){ + $str .='{'; + $str .= '"ticketNo":"'.$item->ticketNo.'",'; + $str .= '"passengerName":"'.$item->passengerName.'",'; + $str .= '"passportTypeId":"'.$item->passportTypeId.'",'; + $str .= '"passportNo":"'.$item->passportNo.'"'; + $str .= '},'; + } + } + + } + $str = substr($str,0,strlen($str)-1); + $str .= ']'; + $data = '{ + "retailOrderId": "'.$retailOrderId.'", + "orderId": "'.$orderId.'", + "orderNumber": "'.$orderNumber.'", + "callBackUrl":"http://www.mycht.cn/info.php/apps/train/tuniu_callback/return_ticket", + "tickets":'.$str.' + }'; + $crypt = new DES(); + $mstr = $crypt->encrypt($data,TUNIU_KEY); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": "'.$mstr.'" + }'; + $back_data = $this->get_http($url,$post_data,'POST'); + + print_r($back_data); + } + + //获取途牛订单信息 + public function order(){ + $retailOrderId=$this->input->get("retailOrderId"); + $orderId=$this->input->get("orderId"); + if($retailOrderId && $orderId){ + $url = TUNIU_URL.'/train/orderStatusQuery'; + $sign = $this->create_sign(); + $time = date('Y-m-d H:i:s',time()); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": { + "retailOrderId":"'.$retailOrderId.'", + "orderId":"'.$orderId.'" + } + }'; + $back_json = $this->get_http($url,$post_data,'POST'); + //获取异步回调信息 + $grab_callback = $this->tuniu_model->get_tuniuorder_info($retailOrderId,$orderId); + $back_data = json_decode($back_json); + //print_r($back_data); + $back_data->grab_callback = $grab_callback[0]->tol_booktxt; + //print_r($back_data); + $this->load->view('bootstrap3/header'); + $this->load->view('tuniu/order',$back_data); + $this->load->view('bootstrap3/footer'); + }else{ + exit('订单信息不完整'); + } + } + + //抢票页面 + public function grab_index(){ + $cols_id=$this->input->post("ht_order"); + $list=new StdClass; + if(!empty($cols_id)){ + $cold_sn=$this->tuniu_model->get_biz_cold($cols_id); + $list->wl=$this->tuniu_model->get_operatorinfo($cols_id); + $i=0; + $list->info=array(); + foreach ($cold_sn as $v) { + $list->info[$i]=new StdClass; + $list->info[$i]->people=$this->tuniu_model->biz_people($v->COLD_SN); + $list->info[$i]->train=$this->tuniu_model->get_biz_foi($v->COLD_SN); + $list->info[$i]->status=$this->tuniu_model->get_biz_jol($v->COLD_SN); + $i++; + } + $list->cols_id=$cols_id; + } + $this->load->view('bootstrap3/header'); + $this->load->view('tuniu/grabTicketBook',$list); + $this->load->view('bootstrap3/footer'); + } + + //抢票接口 + public function grabTicketBook(){ + $cold_sn = $this->input->get("order"); + $bpe_sn = $this->input->get("people"); + //$coli_id = $this->input->get('coli_id'); + $deadline = $this->input->get('deadline'); + $alternate_train = $this->input->get('alternate_train'); + $alternate_seat = $this->input->get('alternate_seat'); + + $data = array(); + $rebakc = array();//返回数据 + $rebakc["status"]=0; + $rebakc["mes"]=""; + if(!is_numeric($cold_sn)){ + $rebakc["mes"]="订单号是数字"; + echo json_encode($rebakc); + return false; + } + if(empty($bpe_sn)){ + $rebakc["mes"]="请选择乘客"; + echo json_encode($rebakc); + return false; + } + if(empty($deadline)){ + $rebakc["mes"]="请填写截止日期"; + echo json_encode($rebakc); + return false; + } + + + $data['train'] = $this->tuniu_model->biz_order_detail($cold_sn); + $data['people_list'] = $this->tuniu_model->in_bpesn_people_info($bpe_sn); + //$data['operator'] = $this->BIZ_train_model->get_operatorinfo($coli_id); + + if (empty($data['train'])) { + //显示错误,找不到车次 + $rebakc["mes"]="找不到车次"; + echo json_encode($rebakc); + return false; + + } + if (empty($data['people_list'])) { + //显示错误,找不到用户信息 + $rebakc["mes"]="找不到乘客信息"; + echo json_encode($rebakc); + return false; + } + + if (count($data['people_list']) > 5) { + //显示错误,用户超过五个 + $rebakc["mes"]="乘客不能超过五个"; + echo json_encode($rebakc); + return false; + } + + $db_train_zw = $this->config->item('db_train_zw'); + $train_zw = $this->config->item('train_zw'); + $ticketype = $this->config->item('train_piaotype'); + $zwcode = $db_train_zw[$data['train']->Aircraft]; //座位简码 + $zwname = $train_zw[$db_train_zw[$data['train']->Aircraft]]; //座位名称 + $passengers=""; + $cold_sn = $cold_sn.'_'.time(); + + //拼接抢票车次信息 + $tuniu_data = '{'; + $tuniu_data .= '"retailOrderId":"'.$cold_sn.'",'; + $tuniu_data .= '"cheCi": "'.$data['train']->FlightsNo.'", '; + $tuniu_data .= '"fromStationCode": "'.$data['train']->DepartAirport.'", '; + $tuniu_data .= '"fromStationName": "'.$data['train']->DepartAirport_cn.'", '; + $tuniu_data .= '"toStationCode": "'.$data['train']->ArrivalAirport.'", '; + $tuniu_data .= '"toStationName": "'.$data['train']->ArrivalAirport_cn.'", '; + $tuniu_data .= '"trainDate": "'.substr($data["train"]->DepartureDate, 0, 10).'", '; + $tuniu_data .= '"deadLine": "'.$deadline.'", '; + $tuniu_data .= '"reserveCheCi": null, '; + $tuniu_data .= '"reserveZwCode": null, '; + $tuniu_data .= '"hasSeat": true,'; + //$tuniu_data .= '"callBackUrl": "http://www.mycht.cn/info.php/apps/train/tuniu_callback/book",'; + $tuniu_data .= '"contact": "陈宇超",'; + $tuniu_data .= '"phone": "18877381547",'; + $tuniu_data .= '"grabType": "1",'; + $tuniu_data .= '"grabFrequency": "common",'; + $tuniu_data .= '"grabQueue": "common",'; + $tuniu_data .= '"grabEntryway": "single",'; + + //循环乘客 + $passengers = ''; + foreach ($data['people_list'] as $key => $item) { + $passengers .= '{'; + $passengers .= '"passengerId":'.$key.','; + $passengers .= '"ticketNo":"null",'; + //乘客姓名 + $passengersename = str_replace(' ','',$item->BPE_FirstName) . str_replace(' ','',$item->BPE_MiddleName) . str_replace(' ','',$item->BPE_LastName); + //将特殊字符转换为正常字符以便于出票 + $passengersename = $this->chk_sp_name($passengersename); + $passengers .= '"passengerName":"'.$passengersename.'",'; + $passportseno = str_replace(' ','',$item->BPE_Passport); + + $passengers .= '"passportNo":"'.$passportseno.'",'; + + //证件类型 + switch ($item->BPE_PassportType){ + case 'Chinese ID': + $passporttypeseid = "1"; + $passporttypeseidname = "二代身份证"; + break; + case 'Travel Permit from Hong Kong / Macau': + $passporttypeseid = "C"; + $passporttypeseidname = "港澳通行证"; + break; + case 'Travel Permit from Taiwan': + $passporttypeseid = "G"; + $passporttypeseidname = "台湾通行证"; + break; + default : + $passporttypeseid = "B"; + $passporttypeseidname = "护照"; + break; + } + + + $passengers .= '"passportTypeId":"'.$passporttypeseid.'",'; + $passengers .= '"passportTypeName":"'.$passporttypeseidname.'",'; + + //票类型 + $passengers .= '"piaoType":"'.$item->BPE_GuestType.'",'; + $passengers .= '"piaoTypeName":"'.$ticketype[$item->BPE_GuestType].'",'; + + //座位类型piaoTypeName + $passengers .= '"zwCode":"'.$zwcode.'",'; + $passengers .= '"zwName":"'.$zwname.'",'; + + $passengers .= '"cxin":"null",'; + $passengers .= '"price":"'.$data['train']->adultcost.'",'; + $passengers .= '"reason": 0'; + $passengers .= '},'; + } + $passengers = substr($passengers,0,strlen($passengers)-1); + $passengers = '['.$passengers.']'; + $tuniu_data .= '"passengers": '.$passengers.'}'; + + $crypt = new DES(); + $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY); + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$this->create_sign().'", + "timestamp": "'.date('Y-m-d H:i:s',time()).'", + "data": "'.$mstr.'" + }'; + + $url = TUNIU_URL.'/train/grabTicketBook'; + + $back_json=$this->get_http($url,$post_data,'POST'); + $back=json_decode($back_json);//json=>obj + log_message('error','抢票预定同步:'.$back_json); + if($back->success == 1){ + $rebakc["mes"]="订单提交成功,等待回调"; + }else{ + $rebakc["mes"]= $bakc_json; + } + $add_data=new StdClass(); + $add_data->tol_retailOrderId = $back->data->retailOrderId; + if(isset($back->data->orderId)){ + $add_data->tol_orderId = $back->data->orderId; + }else{ + $add_data->tol_orderId = ''; + } + + $add_data->tol_fromStationName = $data['train']->DepartAirport_cn; + $add_data->tol_fromStationCode = $data['train']->DepartAirport; + $add_data->tol_toStationName = $data['train']->ArrivalAirport_cn; + $add_data->tol_toStationCode = $data['train']->ArrivalAirport; + $add_data->tol_cheCi = $data['train']->FlightsNo; + $add_data->tol_status = '6'; + $isauto = false; + $add_back_data=$this->tuniu_model->tuniu_add_biz_jol($add_data,$isauto); + print_r($back); + echo $cold_sn; + echo json_encode($rebakc); + return false; + + } + + //取消抢票 + public function cancelgrabTicket($retailOrderId,$orderId){ + $url = TUNIU_URL.'/train/cancelGrabTicket'; + $sign = $this->create_sign(); + $time = date('Y-m-d H:i:s',time()); + $tuniu_data = '{ + "orderId":"'.$orderId.'", + "retailOrderId":"'.$retailOrderId.'", + "userName":null, + "userPassword":null + }'; + + $crypt = new DES(); + $mstr = $crypt->encrypt($tuniu_data,TUNIU_KEY); + + $post_data = '{ + "apiKey": "'.TUNIU_KEY.'", + "sign": "'.$sign.'", + "timestamp": "'.$time.'", + "data": "'.$mstr.'" + }'; + $back_data = $this->get_http($url,$post_data,'POST'); + print_r($back_data); + } + + //导出途牛账单 + public function export(){ + $this->load->model("BIZ_train_model");//加载模型 + $trackcode = $this->BIZ_train_model->getTrackingCode(); + $record = $this->tuniu_model->get_transaction_record(); + /*print_r($record); + die();*/ + //创建一个数组进行数据格式化 + $r_info = array(); + + foreach ($record as $item){ + if(empty($item->tne_ordernumber)){ + continue; + } + //print_r($item); + //订单时间 + $r_info[0] = $item->tne_jydate; + //订单操作类型(分为付款和收款) + $r_info[1] = $item->tne_jytype; + //途牛订单号 + $r_info[2] = $item->tne_ordernumber; + //订单交易金额 + if($item->tne_jytype == '付款'){ + $r_info[3] = '-'.$item->tne_jyprice; + }else{ + $r_info[3] = $item->tne_jyprice; + } + //获取订单cold_sn + $order_info = $this->tuniu_model->get_order_info($item->tne_ordernumber); + //echo $item->tne_ordernumber.'////'; + //print_r($order_info); + $obj = explode('_',$order_info[0]->tol_retailOrderId); + $cold_sn = $obj[0]; + //获取订单coli_Id + $order_obj = $this->tuniu_model->get_coli_id($cold_sn); + //print_r($coli_id); + $coli_id = $order_obj[0]->COLI_ID; + $coli_sn = $order_obj[0]->COLI_SN; + //echo $coli_id[0]->coli_id; + //$coli_sn = $coli_id[0]->coli_sn; + //echo $coli_id[0]->coli_sn;; + $this->BIZ_train_model->linkTrackingCode($coli_sn,$trackcode); + //获取团号 + $gri_no = $this->tuniu_model->get_gri_no($coli_id);//团名 + if($gri_no){ + $r_info[4] = $gri_no[0]->GRI_No; + } + //获取外联名 + $wl_name = $this->tuniu_model->get_operatorinfo($coli_id); + if($wl_name){ + $r_info[5] = $wl_name[0]->OPI_Name; + } + $r_info['trackcode'] = $trackcode; + $arr[]=$r_info; + + } + + header("Content-type:application/vnd.ms-excel;charset=utf-8"); + header("Content-Disposition:attachment;filename=tuniu_train.xls"); + $string_r= $this->load->view("tuniu/train_transaction_excel",array("arr"=>$arr),TRUE); + echo $string_r;die; + } + + //发送请求函数 + public function get_http($url, $data = '', $method = 'GET') { + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在 + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + if ($method == 'POST' && !empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json;charset=UTF-8')); + } + curl_setopt($curl, CURLOPT_TIMEOUT, 45); // 设置超时限制防止死循环 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $tmpInfo = curl_exec($curl); // 执行操作 + $errno = curl_errno($curl); + if ($errno !== 0) { + return false; + echo $errno . curl_error($curl); //记录错误日志 + } + curl_close($curl); //关闭CURL会话 + return $tmpInfo; //返回数据 + } + + function vpost($url,$data){ // 模拟提交数据函数 + $curl = curl_init(); // 启动一个CURL会话 + curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址 + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查 + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在 + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器 + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转 + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer + curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求 + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包 + curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环 + curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容 + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回 + $tmpInfo = curl_exec($curl); // 执行操作 + if (curl_errno($curl)) { + $tmpInfo = 'Errno'.curl_error($curl);//捕抓异常 + } + curl_close($curl); // 关闭CURL会话 + return $tmpInfo; // 返回数据 + } + + //国际姓名特殊字符转换 + function chk_sp_name($name){ + $name = str_replace( + array('á', 'é', 'í', 'ó', 'ú', 'ñ', 'Á', 'É', 'Í', 'Ó', 'Ú', 'Ñ'), + array('a', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N'), + $name + ); + return substr(strtoupper($name),0,30); + } + + //途牛接口创建请求签名 + public function create_sign(){ + $time = date('Y-m-d H:i:s',time()); + $secretKey = 'qvHMJVywEQqsd4EneHQl'; + $id = 'retailId25'; + $timeStamp = 'timestamp'.$time; + $sign = $secretKey.$id.'apiKey'.TUNIU_KEY.$timeStamp.$secretKey; + return strtoupper(md5($sign)); + } +} \ No newline at end of file diff --git a/application/third_party/train/helpers/train_helper.php b/application/third_party/train/helpers/train_helper.php new file mode 100644 index 00000000..b9a0d51a --- /dev/null +++ b/application/third_party/train/helpers/train_helper.php @@ -0,0 +1,40 @@ +<?php + +//ַת +function chk_sp_name($name){ + $name = str_replace( + array('', '', '', '', '', '?', '', '', '', '', '', '?',' ','/',' ',','), + array('a', 'e', 'i', 'o', 'u', 'n', 'A', 'E', 'I', 'O', 'U', 'N','','','',''), + $name + ); + return substr(strtoupper($name),0,30); +} + +// +function GetPost_http($url, $data = '', $method = 'GET') { + $curl = curl_init(); // һCURLỰ + curl_setopt($curl, CURLOPT_URL, $url); // Ҫʵĵַ + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // ֤֤Դļ + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // ֤мSSL㷨Ƿ + curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // ģûʹõ + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // ʹԶת + curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // ԶReferer + if ($method == 'POST' && !empty($data)) { + curl_setopt($curl, CURLOPT_POST, 1); // һPost + curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Postύݰ + curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); + } + curl_setopt($curl, CURLOPT_TIMEOUT, 40); // óʱƷֹѭ + curl_setopt($curl, CURLOPT_TIMEOUT_MS, 40000); // óʱƷֹѭ + curl_setopt($curl, CURLOPT_HEADER, 0); // ʾصHeader + curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // ȡϢļʽ + $tmpInfo = curl_exec($curl); // ִв + $errno = curl_errno($curl); + if ($errno !== 0) { + log_message('error', 'ctripost'.$errno.curl_error($curl)); + } + curl_close($curl); //رCURLỰ + return $tmpInfo; // +} + +?> \ No newline at end of file diff --git a/application/third_party/train/libraries/Des.php b/application/third_party/train/libraries/Des.php new file mode 100644 index 00000000..b2ea6b5f --- /dev/null +++ b/application/third_party/train/libraries/Des.php @@ -0,0 +1,59 @@ +<?php +class Des +{ + + function encrypt($string,$key) + { + $size = mcrypt_get_block_size('des','ecb'); + //$string = mb_convert_encoding($string, 'GBK', 'UTF-8'); + $string = $this->pkcs5_pad($string, $size); + $td = mcrypt_module_open('des', '', 'ecb', ''); + $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); + @mcrypt_generic_init($td, $key, $iv); + $data = mcrypt_generic($td, $string); + mcrypt_generic_deinit($td); + mcrypt_module_close($td); + $data = base64_encode($data); + return $data; + } + + function decrypt($string,$key) + { + $string = base64_decode($string); + $td = mcrypt_module_open('des', '', 'ecb', ''); + //使用MCRYPT_DES算法,cbc模式 + $iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND); + $ks = mcrypt_enc_get_key_size($td); + @mcrypt_generic_init($td, $key, $iv); + //初始处理 + $decrypted = mdecrypt_generic($td, $string); + //解密 + mcrypt_generic_deinit($td); + //结束 + mcrypt_module_close($td); + + $result = $this->pkcs5_unpad($decrypted); + //$result = mb_convert_encoding($result, 'UTF-8', 'GBK'); + return $result; + } + + function pkcs5_pad($text, $blocksize) + { + $pad = $blocksize - (strlen($text) % $blocksize); + return $text . str_repeat(chr($pad), $pad); + } + + function pkcs5_unpad($text) + { + $pad = ord($text{strlen($text) - 1}); + if ($pad > strlen($text)) { + return false; + } + if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) { + return false; + } + return substr($text, 0, -1 * $pad); + } +} + +?> \ No newline at end of file diff --git a/application/third_party/train/models/BIZ_train_model.php b/application/third_party/train/models/BIZ_train_model.php index 3cebc984..6e809f90 100644 --- a/application/third_party/train/models/BIZ_train_model.php +++ b/application/third_party/train/models/BIZ_train_model.php @@ -5,72 +5,167 @@ class BIZ_train_model extends CI_Model { function __construct() { parent::__construct(); $this->HT = $this->load->database('HT', TRUE); - $this->INFO = $this->load->database('INFO', TRUE); + $this->INFO = $this->load->database('INFO', TRUE); } - //新增或更新缓存 - public function addOrUpdate($tpc_from_station,$tpc_to_station,$tpc_content){ - $sql = "IF NOT EXISTS( - SELECT 1 - FROM TrainPriceCache - WHERE - tpc_from_station = '$tpc_from_station' - AND tpc_to_station = '$tpc_to_station' - ) BEGIN - INSERT INTO TrainPriceCache - ( - tpc_from_station, - tpc_to_station, - tpc_content, - tpc_datetime, - tpc_source - ) - VALUES - ( - '$tpc_from_station','$tpc_to_station','$tpc_content',GETDATE(),'juhe' - ) - END - ELSE - BEGIN - UPDATE TrainPriceCache - SET tpc_from_station = '$tpc_from_station', - tpc_to_station = '$tpc_to_station', - tpc_content = '$tpc_content', - tpc_datetime = GETDATE(), - tpc_source = 'juhe' - WHERE - tpc_from_station = '$tpc_from_station' - AND tpc_to_station = '$tpc_to_station' - END - "; - $query = $this->INFO->query($sql); - return $query; + //测试 + function test_myslef(){ + $sql = "UPDATE BIZ_JuheOrderList SET JOL_SendMail = 1"; + $query = $this->HT->query($sql); + //eturn $query->result(); } - //获取缓存的火车信息 - //如果读取到缓存是7天以前的数据就不返回任何数据,并且将其删除。 - public function get_train_cache($tpc_from_station,$tpc_to_station){ - $sql = "SELECT - * - FROM - TrainPriceCache + //自动获取符合自动出票要求的订单的coli_sn + function auto_check_ticket(){ + $sql = "SELECT distinct COLD_SN ,coli_id,COLD_SPFS,COLI_State + FROM BIZ_ConfirmLineInfo bcli + inner join BIZ_ConfirmLineDetail bcld on COLD_COLI_SN=COLI_SN + LEFT JOIN BIZ_GroupAccountInfo bgai + ON bcli.COLI_SN = bgai.GAI_COLI_SN + WHERE bcli.COLI_ServiceType = '2' + AND bcli.COLI_State in ('11','13','8','63') + AND bcli.COLI_WebCode in ('cht', 'JP', 'train_it', 'VC', 'train_ru','GM-Train','SHT','CT') + AND (bcli.COLI_Price - bgai.GAI_SQJE) <= 20 + AND (bcli.COLI_Price - bgai.GAI_SQJE) >= 0 + AND bcli.DeleteFlag = 0 + AND bgai.DeleteFlag = 0 + AND bcld.DeleteFlag = 0 + --AND COLD_SPFS<=2 + AND NOT EXISTS ( + SELECT TOP 1 1 + FROM BIZ_JuheOrderList + WHERE JOL_COLD_SN = COLD_SN + ) + and (((COLI_State<>8 and COLI_State<>63) and COLD_StartDate < CONVERT(varchar(100),GETDATE()+29,23)) or ((COLI_State=8 or COLI_State=63) and COLD_StartDate between CONVERT(varchar(100),GETDATE()+29,23) and CONVERT(varchar(100),GETDATE()+29,23)+' 23:59')) + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + + //筛选符合发送邮件的订单 + public function auto_sendmail(){ + $sql = "SELECT + JOL_COLD_SN, + JOL_JuheOrder, + JOL_Status, + JOL_RebackMsg + FROM + BIZ_JuheOrderList bjo + left join + BIZ_ConfirmLineDetail bcld + on + bcld.COLD_SN = bjo.JOL_COLD_SN + left join + BIZ_ConfirmLineInfo bcli + on + bcld.COLD_COLI_SN = bcli.COLI_SN WHERE - tpc_from_station = '$tpc_from_station' - AND - tpc_to_station = '$tpc_to_station'"; - $query = $this->INFO->query($sql); - return $query->row(); + JOL_SendMail = 0 + AND + JOL_IsAuto = 1 + AND + JOL_Status != '0' + AND + JOL_Status != 'e' + AND + JOL_Status != '2' + AND + bcli.COLI_WebCode = 'cht'"; + $query = $this->HT->query($sql); + return $query->result(); } - //删除缓存操作 - function delete_traincache($tpc_from_station,$tpc_to_station){ - $sql = "DELETE FROM - TrainPriceCache + //筛选符合发送邮件的订单 + public function auto_sendmailtest(){ + $sql = "SELECT + JOL_COLD_SN, + JOL_JuheOrder, + JOL_Status, + JOL_RebackMsg + FROM + BIZ_JuheOrderList bjo + left join + BIZ_ConfirmLineDetail bcld + on + bcld.COLD_SN = bjo.JOL_COLD_SN + left join + BIZ_ConfirmLineInfo bcli + on + bcld.COLD_COLI_SN = bcli.COLI_SN WHERE - tpc_from_station = '$tpc_from_station' + JOL_SendMail = 0 + AND + JOL_IsAuto = 1 AND - tpc_to_station = '$tpc_to_station'"; - $query = $this->INFO->query($sql); + bcli.COLI_WebCode = 'cht'"; + $query = $this->HT->query($sql); + return $query->result(); + } + + //获取失败的订单请求了多少次接口 + /* + 状态4为成功出票 + 状态2为等待回调 + 状态7为线上退票 + */ + function get_count_jol($cold_sn){ + $sql = "select + count(JOL_JuheOrder) as count + from + BIZ_JuheOrderList + where + JOL_COLD_SN = ? + and + JOL_Status not in (4,2,7)"; + $query = $this->HT->query($sql,$cold_sn); + return $query->row(); + } + + //成功出票后,更新汉特订单中,special request的值 + function update_special_request($coli_id){ + $sql = "update + BIZ_ConfirmLineInfo + set + COLI_OrderDetailText = '已经自动出票---' + (select COLI_OrderDetailText from BIZ_ConfirmLineInfo where COLI_ID = '$coli_id') + where + COLI_ID = '$coli_id'"; + $query = $this->HT->query($sql); + return $query; + } + + //邮件使用 + function get_user_info($jh_order){ + $sql = "select + * + from + BIZ_ConfirmLineDetail + where + COLD_SN = ( + select + top 1 JOL_COLD_SN + from + BIZ_JuheOrderList + where + JOL_JuheOrder = ? + )"; + $query = $query = $this->HT->query($sql, $jh_order); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //获取paypal付款记录 + function get_paypal($coli_id){ + $sql = "select top 1 GAI_SQJE from BIZ_GroupAccountInfo where GAI_COLI_ID = ?"; + $query = $query = $this->HT->query($sql, $coli_id); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } } function biz_order_detail($cold_sn) { @@ -82,16 +177,24 @@ class BIZ_train_model extends CI_Model { ,bfoi.FlightsNo ,bfoi.Aircraft ,bfoi.DepartureDate + ,bfoi.FOI_SelectedSeat ,( SELECT TOP 1 TRS_StationCN FROM TrainStation WHERE TRS_Code = DepartAirport + and ISNULL(TRS_StationCN,'')<>'' ) AS DepartAirport_cn ,( SELECT TOP 1 TRS_StationCN FROM TrainStation WHERE TRS_Code = ArrivalAirport - ) AS ArrivalAirport_cn + and ISNULL(TRS_StationCN,'')<>'' + ) AS ArrivalAirport_cn, + FOI_TrainNetOrderNo, + bfoi.adultcost, + bfoi.childcost, + ArrivalTime, + DepartureTime FROM BIZ_FlightsOrderInfo bfoi WHERE bfoi.FOI_COLD_SN = ? "; @@ -111,6 +214,10 @@ class BIZ_train_model extends CI_Model { ,bbp.BPE_LastName ,bbp.BPE_GuestType ,bbp.BPE_Passport + ,bbp.BPE_PassportType + ,bbp.BPE_SEX + ,bbp.BPE_BirthDate + ,bbp.BPE_PassExpdate FROM BIZ_BookPeople bbp WHERE BPE_SN in(".$bpe_sn.") "; @@ -126,6 +233,7 @@ class BIZ_train_model extends CI_Model { ,bbp.BPE_LastName ,bbp.BPE_GuestType ,bbp.BPE_Passport + ,bbp.BPE_PassportType FROM BIZ_BookPeople bbp WHERE EXISTS( SELECT TOP 1 1 @@ -139,24 +247,25 @@ class BIZ_train_model extends CI_Model { } //添加聚合订单记录,BIZ_JuheOrderList - function add_biz_jol($data){ - $sql=" - INSERT INTO BIZ_JuheOrderList( - JOL_SubTime, - JOL_COLD_SN, - JOL_JuheOrder, - JOL_Status, - JOL_RebackMsg, - JOL_FromStation, - JOL_ToStation, - JOL_FromStationCode, - JOL_ToStationCode, - JOL_TrainCode, - JOL_BackTxt - ) - VALUES(getdate(),?,?,?,?,?,?,?,?,?,?) - "; - $query = $this->HT->query($sql, array($data->JOL_COLD_SN,$data->JOL_JuheOrder,$data->JOL_Status,$data->JOL_RebackMsg,$data->JOL_FromStation,$data->JOL_ToStation,$data->JOL_FromStationCode,$data->JOL_ToStationCode,$data->JOL_TrainCode,$data->JOL_BackTxt + function add_biz_jol($data,$isauto){ + $sql=" + INSERT INTO BIZ_JuheOrderList( + JOL_SubTime, + JOL_COLD_SN, + JOL_JuheOrder, + JOL_Status, + JOL_RebackMsg, + JOL_FromStation, + JOL_ToStation, + JOL_FromStationCode, + JOL_ToStationCode, + JOL_TrainCode, + JOL_BackTxt, + JOL_IsAuto + ) + VALUES(getdate(),?,?,?,?,?,?,?,?,?,?,?) + "; + $query = $this->HT->query($sql, array($data->JOL_COLD_SN,$data->JOL_JuheOrder,$data->JOL_Status,$data->JOL_RebackMsg,$data->JOL_FromStation,$data->JOL_ToStation,$data->JOL_FromStationCode,$data->JOL_ToStationCode,$data->JOL_TrainCode,$data->JOL_BackTxt,$isauto )); return $query; } @@ -179,12 +288,28 @@ class BIZ_train_model extends CI_Model { SELECT FOI_COLD_SN, FlightsNo, Cabin, + Aircraft, DepartureCity, + DepartAirport, + ArrivalAirport, ArrivalCity, DepartureDate, DepartureTime, ArrivalTime, - adultcost + adultcost, + FOI_SelectedSeat, + FOI_TrainNetOrderNo, + FOI_SaleDate, + ( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + ) AS ArrivalAirport_cn FROM BIZ_FlightsOrderInfo WHERE FOI_COLD_SN = ? "; @@ -196,24 +321,39 @@ class BIZ_train_model extends CI_Model { function get_biz_jol($cold_sn) { $sql = "SELECT top 1 JOL_SN FROM BIZ_JuheOrderList WHERE JOL_COLD_SN= ?"; $query = $this->HT->query($sql, $cold_sn); - return $query->result(); + if($query->num_rows() == 0){ + return true; + }else{ + return false; + } } //传入COLI_ID,获取外联名 - function get_operatorinfo($cols_id) { + function get_operatorInfo($cols_id) { $sql = " - SELECT OPI_Name - FROM OperatorInfo - WHERE OPI_SN = ( - SELECT COLI_OPI_ID - FROM BIZ_ConfirmLineInfo bcli - WHERE bcli.COLI_ID = ? - ) + SELECT + Name, + OPI_Name, + case when OPI_SN=375 then OPI_EmailBak else OPI_Email end as OPI_Email, + tel, + Mobile, + Email + FROM OperatorInfo + left join agenter_user + on AU_OPI_SN = OPI_SN + WHERE OPI_SN = ( + SELECT COLI_OPI_ID + FROM BIZ_ConfirmLineInfo bcli + WHERE bcli.COLI_ID = ? + ) + and agenter in ('cht', 'train_vac', 'jp', 'train_it', 'vc', 'ru') "; $query = $this->HT->query($sql, $cols_id); return $query->result(); } - + + + /* 以上为get_ht_order优化代码 */ //修改BIZ_JuheOrderList @@ -229,13 +369,19 @@ class BIZ_train_model extends CI_Model { //接收聚合订单号,获取翰特订单号,即BIZ_ConfirmLineInfo的COLI_ID function jh_order_get_coli_id($jh_order){ - $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_SN= - (SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail bcld WHERE bcld.COLD_SN= - (SELECT JOL_COLD_SN FROM BIZ_JuheOrderList bjol WHERE bjol.JOL_JuheOrder= ? )) - "; - $query = $this->HT->query($sql, $jh_order); - return $query->result(); + $sql="SELECT + COLI_ID,COLI_SN,COLI_OPI_ID + FROM + BIZ_ConfirmLineInfo bcli + WHERE + bcli.COLI_SN= + (SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail bcld WHERE bcld.COLD_SN= + (SELECT JOL_COLD_SN FROM BIZ_JuheOrderList bjol WHERE bjol.JOL_JuheOrder= ? )) + "; + $query = $this->HT->query($sql, $jh_order); + return $query->result(); } + //通过COLI_ID获取团名 即 GroupInfo的GRI_No function get_gri_no($coli_id){ $sql="SELECT GRI_No FROM GroupInfo @@ -246,6 +392,89 @@ class BIZ_train_model extends CI_Model { $query = $this->HT->query($sql, $coli_id); return $query->result(); } + + //获取跟踪号 + public function getTrackingCode(){ + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "exec dbo.SP_getTrackingCode;"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + }else{ + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + return($result_object[0]->TrackingCode); + } + } + + //根据coli_sn判断订单是否关联 + public function islink($coli_sn){ + $sql = "select * from CK_GroupInfo left join BIZ_ConfirmLineInfo on CGI_GRI_SN=COLI_GRI_SN where COLI_SN = '$coli_sn'"; + $query = $this->HT->query($sql); + if($query->num_rows() > 0){ + return true; + }else{ + return false; + } + } + + //跟踪号与订单关联 + public function linkTrackingCode($coli_sn,$TrackCode){ + include('c:/database_conn.php'); + $connection = array( + 'UID' => $db['HT']['username'], + 'PWD' => $db['HT']['password'], + 'Database' => 'tourmanager', + 'ConnectionPooling' => 1, + 'CharacterSet' => 'utf-8', + 'ReturnDatesAsStrings' => 1 + ); + $conn = sqlsrv_connect($db['HT']['hostname'], $connection); + $stmt = sqlsrv_query($conn, "exec dbo.SP_recordTrackingCode '$coli_sn', '$TrackCode'"); + if ($stmt === false) { + echo "Error in executing statement 3.\n"; + die(print_r(sqlsrv_errors(), true)); + }else{ + //存储过程中每一个select都会产生一个结果集,取某个结果集就需要从第一个移动到需要的那个结果集 + //如果结果集为空就移到下一个 + /* + while (sqlsrv_has_rows($stmt) !== TRUE) { + sqlsrv_next_result($stmt); + } + + $result_object = array(); + while ($row = sqlsrv_fetch_object($stmt)) { + $result_object[] = $row; + } + */ + sqlsrv_free_stmt($stmt); + sqlsrv_close($conn); + + + } + } + //通过COLI_ID获取我的支付 BIZ_TrainOrderCost function get_train_order_cost($coli_id){ $sql="SELECT TOC_Memo,TOC_TrainNumber,TOC_DepartureDate,TOC_TicketCost @@ -269,7 +498,7 @@ class BIZ_train_model extends CI_Model { } //用于自动出票,传入主订单翰特订单号 COLI_ID ,获取客人的姓名和邮箱 public function get_guest_info($COLI_ID){ - $sql = "SELECT GUT_LastName,GUT_Email FROM BIZ_GUEST bg WHERE bg.GUT_SN = + $sql = "SELECT GUT_FirstName,GUT_LastName,GUT_Email FROM BIZ_GUEST bg WHERE bg.GUT_SN = ( SELECT COLI_GUT_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID = ?) "; $query = $this->HT->query($sql,$COLI_ID); @@ -296,11 +525,11 @@ class BIZ_train_model extends CI_Model { WHERE JOL_COLD_SN = ? AND JOL_JuheOrder = ? "; $query = $this->HT->query($sql,array($cold_sn,$jol_jo)); - return $query->result(); + return $query->row(); } // 传入coli_sn获取订单号 public function coli_sn_get_coli_id($coli_sn){ - $sql="SELECT COLI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN = ? "; + $sql="SELECT COLI_ID,COLI_WebCode FROM BIZ_ConfirmLineInfo WHERE COLI_SN = ? "; $query = $this->HT->query($sql,array($coli_sn)); return $query->result(); } @@ -332,5 +561,141 @@ class BIZ_train_model extends CI_Model { echo $query; //return $query; + } + + public function get_mail($m_sn){ + $sql = "SELECT * FROM Email_AutomaticSend WHERE M_SN = ?"; + $query = $this->HT->query($sql,$m_sn); + return $query->row(); + } + + + + public function get_ht_order(){ + $sql = "select + COLI_ID, + COLD_SN, + FOI_SelectedSeat + from + BIZ_ConfirmLineInfo bcli + left join BIZ_ConfirmLineDetail bgai on COLI_SN = COLD_COLI_SN + left join BIZ_FlightsOrderInfo bfoi on FOI_COLD_SN = COLD_SN + where + COLI_ServiceType = '2' + AND + COLI_WebCode in ('cht') + and + COLI_ApplyDate > '2018-02-01' + AND bcli.DeleteFlag = 0 + AND bgai.DeleteFlag = 0 + and COLI_State != 30 + and COLI_State != 50 + and COLI_State != 40 + and COLI_State != 60 + and FOI_SelectedSeat != 'NULL' + and FOI_SelectedSeat != '' + order by COLI_ApplyDate asc "; + $query = $this->HT->query($sql); + return $query->result(); + } + + public function get_juhe_select(){ + $sql = "select + FOI_SelectedSeat, + JOL_BackTxt, + JOL_JuheOrder, + JOL_IsAuto + from + BIZ_JuheOrderList + left join BIZ_FlightsOrderInfo on FOI_COLD_SN = JOL_COLD_SN + where JOL_SubTime > '2018-02-01' + and JOL_Status = '4' + and FOI_SelectedSeat != 'NULL' + and FOI_SelectedSeat != '' + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + //更新当前订单 + public function update_cold_state($state,$cold_sn){ + $sql="update BIZ_ConfirmLineDetail set COLD_State = ? where COLD_SN = ?"; + $query = $this->HT->query($sql,array($state,$cold_sn)); + return $query; + } + + public function update_coli_state($state,$coli_sn){ + $sql="update BIZ_ConfirmLineInfo set COLI_State = ? where COLI_SN = ?"; + $query = $this->HT->query($sql,array($state,$coli_sn)); + } + + public function cold_sn_get_coli_sn($cold_sn){ + $sql = "select COLD_COLI_SN from BIZ_ConfirmLineDetail where COLD_SN = ?"; + $query = $this->HT->query($sql,$cold_sn); + return $query->result(); + } + + public function get_alltrain($coli_sn){ + $sql = "select * from BIZ_ConfirmLineDetail where COLD_COLI_SN = ?"; + $query = $this->HT->query($sql,$coli_sn); + return $query->result(); + } + + public function get_order_webcode($coli_sn){ + $sql = "select COLI_WebCode from BIZ_ConfirmLineInfo where COLI_SN = ?"; + $query = $this->HT->query($sql,$coli_sn); + return $query->row(); + } + + public function sale_time_station($station,$time){ + $sql = 'INSERT INTO TrainSaleTime (TST_station_cn,TST_saletime) VALUES (?,?) '; + $query = $this->HT->query($sql,array($station,$time)); + return $query; + } + + public function update_sale_time($time,$update_time){ + $sql = "update TrainSaleTime set TST_saletime = '{$time}' WHERE TST_saletime = '{$update_time}'"; + $query = $this->HT->query($sql); + return $query; + } + + public function get_saletime($station){ + $sql = 'select TST_saletime from TrainSaleTime where TST_station_cn = ?'; + $query = $this->HT->query($sql,$station); + return $query->row(); + } + + // + public function addseatinfo($seat_info,$cold_sn){ + $sql = "if EXISTS(select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}' and FOI_BookSeat = '{$seat_info}' or FOI_BookSeat = 'NULL') + update BIZ_FlightsOrderInfo set FOI_BookSeat = '{$seat_info}' where FOI_COLD_SN = '{$cold_sn}' + else + if(select CHARINDEX('{$seat_info}',FOI_BookSeat) from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}') = 0 + update BIZ_FlightsOrderInfo set FOI_BookSeat = (select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}') + ',{$seat_info}' where FOI_COLD_SN = '{$cold_sn}'"; + $query = $this->HT->query($sql,array($seat_info,$cold_sn)); + } + + public function test(){ + + $seat_info = 'Coach 09,Seat 05A,05C'; + $cold_sn = '488110751'; + + //$sql = "update BIZ_FlightsOrderInfo set FOI_BookSeat = '{$seat_info}' where FOI_COLD_SN = '{$cold_sn}'"; + + /*$sql = "IF (select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}' and FOI_BookSeat like '%{$seat_info}%') + update BIZ_FlightsOrderInfo set FOI_BookSeat = '{$seat_info}' where FOI_COLD_SN = '{$cold_sn}' + else + update BIZ_FlightsOrderInfo set FOI_BookSeat = (select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}') + ',{$seat_info}' where FOI_COLD_SN = '{$cold_sn}' + ";*/ + $sql = "if EXISTS(select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}' and FOI_BookSeat = '{$seat_info}' or FOI_BookSeat = 'NULL') + update BIZ_FlightsOrderInfo set FOI_BookSeat = '{$seat_info}' where FOI_COLD_SN = '{$cold_sn}' + else + if(select CHARINDEX('{$seat_info}',FOI_BookSeat) from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}') = 0 + update BIZ_FlightsOrderInfo set FOI_BookSeat = (select FOI_BookSeat from BIZ_FlightsOrderInfo where FOI_COLD_SN = '{$cold_sn}') + ',{$seat_info}' where FOI_COLD_SN = '{$cold_sn}' + "; + + + $query = $this->HT->query($sql); + } } diff --git a/application/third_party/train/models/ctrip_train_model.php b/application/third_party/train/models/ctrip_train_model.php new file mode 100644 index 00000000..88f4c614 --- /dev/null +++ b/application/third_party/train/models/ctrip_train_model.php @@ -0,0 +1,301 @@ +<?php +class ctrip_train_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + $this->INFO = $this->load->database('INFO', TRUE); + } + + //获取订单详情 + function biz_order_detail($cold_sn) { + $sql = " + SELECT TOP 1 bfoi.FOI_SN + ,bfoi.FOI_COLD_SN + ,bfoi.DepartAirport + ,bfoi.ArrivalAirport + ,bfoi.FlightsNo + ,bfoi.Aircraft + ,bfoi.DepartureDate + ,bfoi.FOI_SelectedSeat + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + and ISNULL(TRS_StationCN,'')<>'' + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + and ISNULL(TRS_StationCN,'')<>'' + ) AS ArrivalAirport_cn, + FOI_TrainNetOrderNo, + bfoi.adultcost, + bfoi.childcost, + ArrivalTime, + DepartureTime, + DepartureDate + FROM BIZ_FlightsOrderInfo bfoi + WHERE bfoi.FOI_COLD_SN = ? + "; + $query = $this->HT->query($sql, $cold_sn); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //传入一组BPE_SN获取乘客信息 + function in_bpesn_people_info($bpe_sn){ + $sql = " + SELECT bbp.BPE_SN + ,bbp.BPE_FirstName + ,bbp.BPE_MiddleName + ,bbp.BPE_LastName + ,bbp.BPE_GuestType + ,bbp.BPE_Passport + ,bbp.BPE_PassportType + FROM BIZ_BookPeople bbp + WHERE BPE_SN in(".$bpe_sn.") + order by BPE_GuestType asc + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + function add_passagers($data){ + $sql = "IF EXISTS (select * from trainsystem_tickets where tst_ordernumber = '{$data->ordernumber}' and tst_numberid = '{$data->numberid}') + update + trainsystem_tickets + set + tst_identitytype = '{$data->identitytype}', + tst_numberid = '{$data->numberid}', + tst_ticketype = '{$data->ticketype}', + tst_ticketprice = '{$data->ticketprice}', + tst_seatstype = '{$data->seatype}', + tst_seatdetail = '{$data->seatdetail}' + where + tst_ordernumber = '{$data->ordernumber}' + and + tst_numberid = '{$data->numberid}' + else + INSERT INTO trainsystem_tickets ( + tst_ordernumber, + tst_realname, + tst_identitytype, + tst_numberid, + tst_ticketype, + tst_ticketprice, + tst_seatstype, + tst_seatdetail + )VALUES( + '{$data->ordernumber}', + '{$data->realname}', + '{$data->identitytype}', + '{$data->numberid}', + '{$data->ticketype}', + '{$data->ticketprice}', + '{$data->seatype}', + '{$data->seatdetail}' + ) + "; + $query =$this->INFO->query($sql); + } + + function add_orders($data){ + $sql=" + INSERT INTO trainsystem( + ts_cold_sn, + ts_ordernumber, + ts_subtime, + ts_returncode, + ts_status, + ts_errormsg, + ts_fromstationame, + ts_fromstationcode, + ts_tostationame, + ts_tostationcode, + ts_startdate, + ts_startime, + ts_endtime, + ts_runtime, + ts_checi, + ts_channel, + ts_isauto + ) + VALUES( + '{$data->cold_sn}', + '{$data->ordernumber}', + getdate(), + '{$data->returncode}', + '{$data->status}', + '{$data->errormsg}', + '{$data->fromstationame}', + '{$data->fromstationcode}', + '{$data->tostationame}', + '{$data->tostationcode}', + '{$data->startdate}', + '{$data->startime}', + '{$data->endtime}', + '{$data->runtime}', + '{$data->checi}', + '{$data->channel}', + '{$data->isauto}' + ) + "; + //echo $sql; + $query = $this->INFO->query($sql); + } + + public function update_orders($data){ + $where = ''; + if(!empty($data->bookcallback)){ + $where .= " + ts_seatsinfo = '{$data->seatsinfo}', + ts_checkdoor = '{$data->TicketCheck}', + ts_elecnumber = '{$data->ElectronicOrderNumber}', + ts_orderamount = '{$data->OrderTotleFee}', + ts_bookcallback = '{$data->bookcallback}',"; + }else if(!empty($data->confirmcallback)){ + $where .= "ts_confirmcallback = '{$data->confirmcallback}',"; + }else if(!empty($data->returncallback)){ + $where .= "ts_returncallback = '{$data->returncallback}',"; + }else if(!empty($data->reschedulecallback)){ + $where .= "ts_reschedulecallback = '{$data->reschedulecallback}',"; + } + $sql =" + update trainsystem + set + ts_status = '{$data->OrderStatus}', + ts_errormsg = '{$data->ErrorMsg}', + ".substr($where,0,strlen($where)-1)." + where + ts_ordernumber = '{$data->ordernumber}' + "; + //echo $sql;die(); + $query = $this->INFO->query($sql); + } + + public function get_order_info($ordernumber){ + $sql = "select * from trainsystem where ts_ordernumber = '$ordernumber'"; + $query = $this->INFO->query($sql); + return $query->row(); + } + + public function get_passager_info($ctriporder,$PassagerId=null){ + if(empty($PassagerId)){ + $where = ""; + }else{ + $where = "and tst_id = $PassagerId"; + } + $sql = "select * from trainsystem_tickets left join trainsystem on tst_ordernumber = ts_ordernumber where tst_ordernumber = '{$ctriporder}' $where"; + $query = $this->INFO->query($sql); + return $query->result(); + } + + //更新供应商 + public function update_cold_planvei_sn($cold_sn){ + $sql = "update BIZ_ConfirmLineDetail set COLD_PlanVEI_SN=30427 where COLD_SN = ?"; + $query = $this->HT->query($sql,$cold_sn); + } + + //新增支付记录 + public function add_train_payment($data){ + //主表ID,下面两个地方用到,所以先筛选出来,不知道能不能通过合并提高效率 + $sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?"; + $query=$this->HT->query($sql,$data->TOC_COLD_SN); + $query=$query->result(); + $CCSN=$query[0]->COLD_COLI_SN; + //删除多余支付记录 + $sql = "delete from BIZ_TrainOrderCost where TOC_COLI_SN = '{$CCSN}' and TOC_TicketCost is null"; + $query=$this->HT->query($sql); + if(empty($data->FOI_TrainNetOrderNo)){ + //退票 + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_DepartureDate, + TOC_TicketCost, + TOC_WL + ) + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}))"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%","携程退票费 ".$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost)); + }else{ + //出票 + //BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号 + /* + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=? + WHERE + FOI_COLD_SN=? + */ + $sql="IF EXISTS( + select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo like '%$data->FOI_TrainNetOrderNo%')) + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN' + ELSE + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN'"; + + $this->HT->query($sql); + + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_DepartureDate, + TOC_TicketCost, + TOC_WL, + TOC_OtherCost + ) + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%",$data->TOC_Memo." 携程出票",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost,$data->TOC_Memo." 手续费",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->poundage)); + } + return $query; + + } + + //更新乘客表信息 + public function update_passpager_info($data){ + $sql = "update + trainsystem_tickets + set + tst_status = '{$data->status}', + tst_returncallback = '{$data->returncallback}', + tst_lasteditdate = getdate() + where + tst_ordernumber = '{$data->ordernumber}' + and + tst_realname = '{$data->realname}' + and + tst_numberid = '{$data->numberid}' + "; + $query = $this->INFO->query($sql); + } + + +} + +?> \ No newline at end of file diff --git a/application/third_party/train/models/order_people_model.php b/application/third_party/train/models/order_people_model.php index 495772f4..9a19e3c4 100644 --- a/application/third_party/train/models/order_people_model.php +++ b/application/third_party/train/models/order_people_model.php @@ -106,8 +106,12 @@ class Order_people_model extends CI_Model { $query = $this->HT->query($sql,array($data->JOL_RebackMsg,$data->JOL_BackTxt,$data->JOL_Status,$data->JOL_Price,$data->JOL_JuheOrder)); return $query; } - - + + public function update_cold_planvei_sn($cold_sn){ + $sql = "update BIZ_ConfirmLineDetail set COLD_PlanVEI_SN=30427 where COLD_SN = ?"; + $query = $this->HT->query($sql,$cold_sn); + } + //BIZ_TrainOrderCost,我的支付 //BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号 public function add_train_order($data){ @@ -116,6 +120,9 @@ class Order_people_model extends CI_Model { $query=$this->HT->query($sql,$data->TOC_COLD_SN); $query=$query->result(); $CCSN=$query[0]->COLD_COLI_SN; + //删除多余支付记录 + $sql = "delete from BIZ_TrainOrderCost where TOC_COLI_SN = '{$CCSN}' and TOC_TicketCost is null"; + $query=$this->HT->query($sql); if(empty($data->FOI_TrainNetOrderNo)){ //退票 $sql="IF NOT EXISTS( @@ -137,12 +144,29 @@ class Order_people_model extends CI_Model { }else{ //出票 //BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号 - $sql="UPDATE BIZ_FlightsOrderInfo + /* + UPDATE BIZ_FlightsOrderInfo SET FOI_TrainNetOrderNo=? WHERE - FOI_COLD_SN=?"; - $this->HT->query($sql,array($data->FOI_TrainNetOrderNo,$data->TOC_COLD_SN)); + FOI_COLD_SN=? + */ + $sql="IF EXISTS( + select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo like '%$data->FOI_TrainNetOrderNo%')) + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN' + ELSE + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN'"; + + $this->HT->query($sql); + $sql="IF NOT EXISTS( SELECT TOP 1 1 FROM BIZ_TrainOrderCost WHERE TOC_COLD_SN = ? AND TOC_Memo like ? @@ -188,7 +212,11 @@ class Order_people_model extends CI_Model { BIZ_JuheOrderList.JOL_ToStation, BIZ_JuheOrderList.JOL_TrainCode, BIZ_JuheOrderList.JOL_Price, - BIZ_ConfirmLineInfo.COLI_ID + BIZ_JuheOrderList.JOL_IsAuto, + BIZ_JuheOrderList.JOL_SendMail, + BIZ_JuheOrderList.JOL_M_SN, + BIZ_ConfirmLineInfo.COLI_ID, + BIZ_ConfirmLineInfo.COLI_WebCode FROM BIZ_JuheOrderList LEFT JOIN @@ -196,10 +224,21 @@ class Order_people_model extends CI_Model { ON BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=BIZ_JuheOrderList.JOL_COLD_SN) WHERE - BIZ_JuheOrderList.JOL_SN NOT IN(SELECT TOP {$page} BIZ_JuheOrderList.JOL_SN FROM BIZ_JuheOrderList ORDER BY BIZ_JuheOrderList.JOL_SubTime DESC) + BIZ_JuheOrderList.JOL_SN NOT IN( + SELECT + TOP {$page} JOL_SN + FROM + BIZ_JuheOrderList + LEFT JOIN + BIZ_ConfirmLineInfo + ON + BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=BIZ_JuheOrderList.JOL_COLD_SN) + where {$where} + ORDER BY JOL_SubTime DESC) AND {$where} ORDER BY BIZ_JuheOrderList.JOL_SubTime DESC"; + $query = $this->HT->query($sql); $data->list=$query->result(); return $data; @@ -323,5 +362,22 @@ class Order_people_model extends CI_Model { } /*以上为get_ht_order优化代码*/ - + public function test($data){ + + $sql="IF EXISTS( + select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo = '$data->FOI_TrainNetOrderNo')) + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN' + ELSE + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN'"; + print_r($sql); + $this->HT->query($sql); + } } \ No newline at end of file diff --git a/application/third_party/train/models/sendmail_model.php b/application/third_party/train/models/sendmail_model.php index 824f98ee..98ec89bc 100644 --- a/application/third_party/train/models/sendmail_model.php +++ b/application/third_party/train/models/sendmail_model.php @@ -10,6 +10,7 @@ class Sendmail_model extends CI_Model { function SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body) { + $time = date('Y-m-d H:i:s',time()); if($this->validEmail($toEmail)) { $data = array( @@ -22,9 +23,36 @@ class Sendmail_model extends CI_Model { "M_Web" => "CHT", //所属站点 "M_FromName" => "Chinahighlights.com", //站点名称 "M_State" => 0, + "M_AddTime" => $time ); $this->HT->insert('Email_AutomaticSend',$data); - return TRUE; + $m_sn = $this->HT->insert_id('Email_AutomaticSend'); + return $m_sn; + }else{ + return FALSE; + } + } + + function SendMailToTabletest($fromName,$fromEmail,$toName,$toEmail,$subject,$body) + { + $time = date('Y-m-d H:i:s',time()); + if($this->validEmail($toEmail)) + { + $data = array( + "M_ReplyToName" => $fromName, //回复人 + "M_ReplyToEmail" => $fromEmail, //回复地址 + "M_ToName" => $toName, //收件人名 + "M_ToEmail" => $toEmail, //收件邮件地址 + "M_Title" => $subject, //主题 + "M_Body" => $body, //邮件正文 + "M_Web" => "CHT", //所属站点 + "M_FromName" => "Chinahighlights.com", //站点名称 + "M_State" => 0, + "M_AddTime" => $time, + ); + $this->HT->insert('Email_AutomaticSend',$data); + $m_sn = $this->HT->insert_id('Email_AutomaticSend'); + return $m_sn; }else{ return FALSE; } @@ -41,6 +69,55 @@ class Sendmail_model extends CI_Model { $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); + $domain = str_replace(' ','',$domain); + if ($localLen < 1 || $localLen > 64){ + // local part length exceeded + $isValid = false; + }else if ($domainLen < 1 || $domainLen > 255){ + // domain part length exceeded + $isValid = false; + }else if ($local[0] == '.' || $local[$localLen-1] == '.'){ + // local part starts or ends with '.' + $isValid = false; + }else if (preg_match('/\\.\\./', $local)){ + // local part has two consecutive dots + $isValid = false; + }else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)){ + // character not valid in domain part + $isValid = false; + }else if (preg_match('/\\.\\./', $domain)){ + // domain part has two consecutive dots + $isValid = false; + }else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',str_replace("\\\\","",$local))){ + // character not valid in local part unless + // local part is quoted + if (!preg_match('/^"(\\\\"|[^"])+"$/',str_replace("\\\\","",$local))){ + $isValid = false; + } + } + /* + 不检查是否有DNS解析 + if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A"))){ + // domain not found in DNS + $isValid = false; + } + */ + } + return $isValid; + } + + public function validEmailtest($email){ + $isValid = true; + $atIndex = strrpos($email, "@"); + if (is_bool($atIndex) && !$atIndex){ + $isValid = false; + }else{ + $domain = substr($email, $atIndex+1); + $local = substr($email, 0, $atIndex); + $localLen = strlen($local); + $domainLen = strlen($domain); + $domain = str_replace(' ','',$domain); + print_r(preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)); if ($localLen < 1 || $localLen > 64){ // local part length exceeded $isValid = false; diff --git a/application/third_party/train/models/test_model.php b/application/third_party/train/models/test_model.php new file mode 100644 index 00000000..e69de29b diff --git a/application/third_party/train/models/tuniu_model.php b/application/third_party/train/models/tuniu_model.php new file mode 100644 index 00000000..93ce6058 --- /dev/null +++ b/application/third_party/train/models/tuniu_model.php @@ -0,0 +1,461 @@ +<?php + +class tuniu_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + $this->INFO = $this->load->database('INFO', TRUE); + } + + //传入主订单翰特订单号COLI_ID(161014006M),获取子订单中火车订单的COLD_SN + function get_biz_cold($cols_id) { + $sql = "SELECT COLD_SN + FROM BIZ_ConfirmLineDetail bcld + WHERE bcld.COLD_COLI_SN=( + SELECT COLI_SN FROM BIZ_ConfirmLineInfo bcli WHERE bcli.COLI_ID=?) + AND bcld.DeleteFlag=0 AND bcld.COLD_ServiceType='2'"; + $query = $this->HT->query($sql, $cols_id); + return $query->result(); + } + + //传入COLI_ID,获取外联名 + function get_operatorinfo($cols_id) { + $sql = " + SELECT + Name, + OPI_Name, + OPI_Email, + tel, + Mobile, + Email + FROM OperatorInfo + left join agenter_user + on AU_OPI_SN = OPI_SN + WHERE OPI_SN = ( + SELECT COLI_OPI_ID + FROM BIZ_ConfirmLineInfo bcli + WHERE bcli.COLI_ID = ? + ) + and agenter in ('cht', 'train_vac', 'jp', 'train_it', 'vc', 'ru') + "; + $query = $this->HT->query($sql, $cols_id); + return $query->result(); + } + + //传入子订单COLD_SN,获取子订单对应的乘客信息 + function biz_people($cold_sn) { + $sql = " + SELECT bbp.BPE_SN + ,bbp.BPE_FirstName + ,bbp.BPE_MiddleName + ,bbp.BPE_LastName + ,bbp.BPE_GuestType + ,bbp.BPE_Passport + FROM BIZ_BookPeople bbp + WHERE EXISTS( + SELECT TOP 1 1 + FROM BIZ_BookPeopleList bbpl + WHERE bbpl.BPL_BPE_SN = bbp.BPE_SN + AND bbpl.BPL_COLD_SN = ? + ) + "; + $query = $this->HT->query($sql, $cold_sn); + return $query->result(); + } + + //传入COLD_SN,获取火车车次等信息 + function get_biz_foi($cold_sn) { + $sql = " + SELECT FOI_COLD_SN, + FlightsNo, + Cabin, + Aircraft, + DepartureCity, + ArrivalCity, + DepartureDate, + DepartureTime, + ArrivalTime, + adultcost, + FOI_SelectedSeat, + FOI_TrainNetOrderNo, + FOI_SaleDate, + ( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + ) AS ArrivalAirport_cn + FROM BIZ_FlightsOrderInfo + WHERE FOI_COLD_SN = ? + "; + $query = $this->HT->query($sql, $cold_sn); + return $query->result(); + } + + //传入COLD_SN,获取BIZ_JuheOrderList是否存在此子订单,用来判断是否提交过给聚合 + function get_biz_jol($cold_sn) { + $sql = "SELECT top 1 JOL_SN FROM BIZ_JuheOrderList WHERE JOL_COLD_SN= ?"; + $query = $this->HT->query($sql, $cold_sn); + if($query->num_rows() == 0){ + return true; + }else{ + return false; + } + } + + public function get_order($pagesize=2,$page=0,$where="1=1"){ + $data=new StdClass(); + //获取总条数 + $sql="SELECT COUNT(*) AS count FROM TuniuOrderList + LEFT JOIN + Tourmanager.dbo.BIZ_ConfirmLineInfo + ON + Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM Tourmanager.dbo.BIZ_ConfirmLineDetail WHERE COLD_SN=substring(tol_retailOrderId,0,charindex('_',tol_retailOrderId))) + WHERE + {$where} + "; + $query = $this->INFO->query($sql); + $count=$query->result(); + $data->count=$count[0]->count; + + $sql="SELECT TOP {$pagesize} TuniuOrderList.tol_subtime, + TuniuOrderList.tol_orderId, + TuniuOrderList.tol_returnCode, + TuniuOrderList.tol_retailOrderId, + TuniuOrderList.tol_Status, + TuniuOrderList.tol_errorMsg, + TuniuOrderList.tol_fromStationName, + TuniuOrderList.tol_toStationName, + TuniuOrderList.tol_cheCi, + TuniuOrderList.tol_orderAmount, + TuniuOrderList.tol_isauto, + TuniuOrderList.tol_sendmail, + Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_ID, + Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_WebCode + FROM + TuniuOrderList + LEFT JOIN + Tourmanager.dbo.BIZ_ConfirmLineInfo + ON + Tourmanager.dbo.BIZ_ConfirmLineInfo.COLI_SN=(SELECT COLD_COLI_SN FROM Tourmanager.dbo.BIZ_ConfirmLineDetail WHERE COLD_SN=substring(tol_retailOrderId,0,charindex('_',tol_retailOrderId))) + WHERE + TuniuOrderList.tol_orderId NOT IN(SELECT TOP {$page} TuniuOrderList.tol_orderId FROM TuniuOrderList ORDER BY TuniuOrderList.tol_sn DESC) + AND + {$where} + ORDER BY TuniuOrderList.tol_sn DESC"; + $query = $this->INFO->query($sql); + $data->list=$query->result(); + return $data; + + } + + function biz_order_detail($cold_sn) { + $sql = " + SELECT TOP 1 bfoi.FOI_SN + ,bfoi.FOI_COLD_SN + ,bfoi.DepartAirport + ,bfoi.ArrivalAirport + ,bfoi.FlightsNo + ,bfoi.Aircraft + ,bfoi.DepartureDate + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = DepartAirport + ) AS DepartAirport_cn + ,( + SELECT TOP 1 TRS_StationCN + FROM TrainStation + WHERE TRS_Code = ArrivalAirport + ) AS ArrivalAirport_cn, + FOI_TrainNetOrderNo, + bfoi.adultcost + FROM BIZ_FlightsOrderInfo bfoi + WHERE bfoi.FOI_COLD_SN = ? + "; + $query = $this->HT->query($sql, $cold_sn); + if ($query->num_rows() > 0) { + return $query->row(); + } else { + return false; + } + } + + //传入一组BPE_SN获取乘客信息 + function in_bpesn_people_info($bpe_sn){ + $sql = " + SELECT bbp.BPE_SN + ,bbp.BPE_FirstName + ,bbp.BPE_MiddleName + ,bbp.BPE_LastName + ,bbp.BPE_GuestType + ,bbp.BPE_Passport + ,bbp.BPE_PassportType + FROM BIZ_BookPeople bbp + WHERE BPE_SN in(".$bpe_sn.") + "; + $query = $this->HT->query($sql); + return $query->result(); + } + + //添加途牛订单记录 + function tuniu_add_biz_jol($data,$isauto){ + if($isauto){ + $isauto = 1; + }else{ + $isauto = 0; + } + $sql=" + INSERT INTO TuniuOrderList( + tol_subTime, + tol_cheCi, + tol_fromStationName, + tol_fromStationCode, + tol_toStationName, + tol_toStationCode, + tol_retailOrderId, + tol_orderId, + tol_status, + tol_errorMsg, + tol_isauto + ) + VALUES(getdate(),?,?,?,?,?,?,?,?,?,?) + "; + $query = $this->INFO->query($sql,array($data->tol_cheCi,$data->tol_fromStationName,$data->tol_fromStationCode,$data->tol_toStationName,$data->tol_toStationCode,$data->tol_retailOrderId,$data->tol_orderId,$data->tol_status,$data->tol_errorMsg,$isauto)); + return $query; + } + + + //途牛预定处理 + function book_tuniu_order($data){ + $sql = " + UPDATE TuniuOrderList + set + tol_orderId = '{$data['orderId']}', + tol_returnCode = '{$data['returnCode']}', + tol_status = '2', + tol_errorMsg = '{$data['errorMsg']}', + --tol_fromStationCode = '{$data['fromStationCode']}', + --tol_fromStationName = '{$data['fromStationName']}', + --tol_toStationCode = '{$data['toStationCode']}', + --tol_toStationName = '{$data['toStationName']}', + --tol_cheCi = '{$data['cheCi']}', + tol_orderAmount = '{$data['orderAmount']}', + tol_booktxt = '{$data['backtxt']}' + WHERE + tol_retailOrderId = '{$data['retailOrderId']}' + "; + + $query = $this->INFO->query($sql); + return $query; + } + + //确认出票更新 + public function confirm_tuniu_order($data){ + $sql = " + UPDATE TuniuOrderList + set + tol_orderId = '{$data['orderId']}', + tol_returnCode = '{$data['returnCode']}', + tol_status = '4', + tol_errorMsg = '{$data['errorMsg']}', + tol_confirmtxt = '{$data['confirmtxt']}' + WHERE + tol_retailOrderId = '{$data['retailOrderId']}' + "; + + $query = $this->INFO->query($sql); + return $query; + } + + //退票更新 + public function return_tuniu_order($data){ + $sql = " + UPDATE TuniuOrderList + set + tol_returnCode = '{$data['returnCode']}', + tol_status = '7', + tol_errorMsg = '{$data['errorMsg']}', + tol_returntxt = '{$data['returntxt']}' + WHERE + tol_retailOrderId = '{$data['retailOrderId']}' + "; + + $query = $this->INFO->query($sql); + return $query; + } + + //抢票更新 + public function grab_tuniu_order($data){ + $sql = " + UPDATE TuniuOrderList + set + tol_returnCode = '{$data['returnCode']}', + tol_status = '9', + tol_errorMsg = '{$data['errorMsg']}', + tol_fromStationCode = '{$data['fromStationCode']}', + tol_fromStationName = '{$data['fromStationName']}', + tol_toStationCode = '{$data['toStationCode']}', + tol_toStationName = '{$data['toStationName']}', + tol_cheCi = '{$data['cheCi']}', + tol_orderAmount = '{$data['orderAmount']}', + tol_booktxt = '{$data['booktxt']}' + + WHERE + tol_retailOrderId = '{$data['retailOrderId']}' + "; + + $query = $this->INFO->query($sql); + return $query; + } + + //取消抢票更新 + public function cancelgragticket($data){ + $sql = " + UPDATE TuniuOrderList + set + tol_errorMsg = '{$data['errorMsg']}', + tol_returnCode = '{$data['returnCode']}', + tol_status = '8', + tol_orderId = '{$data['orderId']}' + WHERE + tol_retailOrderId = '{$data['retailOrderId']}' + "; + + $query = $this->INFO->query($sql); + return $query; + } + + //获取途牛订单信息 + public function get_tuniuorder_info($retailOrderId,$orderId){ + $sql = 'select tol_booktxt from TuniuOrderList where tol_retailOrderId = ? and tol_orderId =?'; + $query = $this->INFO->query($sql,array($retailOrderId,$orderId)); + return $query->result(); + } + + //BIZ_TrainOrderCost,我的支付 + //BIZ_FlightsOrderInfo.FOI_TrainNetOrderNo,更新取票号 + public function add_grab_order($data){ + $sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?"; + $query=$this->HT->query($sql,$data->TOC_COLD_SN); + $query=$query->result(); + $CCSN=$query[0]->COLD_COLI_SN; + //删除多余支付记录 + $sql = "delete from BIZ_TrainOrderCost where TOC_COLI_SN = '{$CCSN}' and TOC_TicketCost is null"; + $query=$this->HT->query($sql); + $sql="IF EXISTS( + select * from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN' and (FOI_TrainNetOrderNo is null or FOI_TrainNetOrderNo = '' or FOI_TrainNetOrderNo like '%$data->FOI_TrainNetOrderNo%')) + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo='$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN' + ELSE + UPDATE BIZ_FlightsOrderInfo + SET + FOI_TrainNetOrderNo=(select FOI_TrainNetOrderNo from BIZ_FlightsOrderInfo where FOI_COLD_SN = '$data->TOC_COLD_SN') + '&' + '$data->FOI_TrainNetOrderNo' + WHERE + FOI_COLD_SN='$data->TOC_COLD_SN'"; + + $this->HT->query($sql); + + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_DepartureDate, + TOC_TicketCost, + TOC_WL, + TOC_OtherCost + ) + VALUES(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),null),(?,getdate(),{$CCSN},?,?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}),1)"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%",$data->TOC_Memo." 途牛抢票出票",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->TOC_TicketCost,$data->TOC_Memo." 手续费",$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_DepartureDate,$data->poundage)); + return $query; + } + + public function add_return_order($data){ + $sql="SELECT COLD_COLI_SN FROM BIZ_ConfirmLineDetail WHERE COLD_SN=?"; + $query=$this->HT->query($sql,$data->TOC_COLD_SN); + $query=$query->result(); + $CCSN=$query[0]->COLD_COLI_SN; + + $sql="IF NOT EXISTS( + SELECT TOP 1 1 FROM BIZ_TrainOrderCost + WHERE TOC_COLD_SN = ? AND TOC_Memo like ? + ) + INSERT INTO BIZ_TrainOrderCost( + TOC_Memo, + TOC_CreateDate, + TOC_COLI_SN, + TOC_COLD_SN, + TOC_TrainNumber, + TOC_TicketCost, + TOC_WL + ) + VALUES(?,getdate(),{$CCSN},?,?,?,(SELECT COLI_OPI_ID FROM BIZ_ConfirmLineInfo WHERE COLI_SN={$CCSN}))"; + $query = $this->HT->query($sql,array($data->TOC_COLD_SN,"%".$data->TOC_Memo."%","途牛退票费 ".$data->TOC_Memo,$data->TOC_COLD_SN,$data->TOC_TrainNumber,$data->TOC_TicketCost)); + return $query; + } + + public function update_status($data){ + $sql = "update + TuniuOrderList + set + tol_status = '9', + tol_returnCode = '{$data['returnCode']}', + tol_errorMsg = '{$data['errorMsg']}' + where + tol_retailOrderId = '{$data['retailOrderId']}' + "; + $query = $this->INFO->query($sql); + return $query; + } + + public function get_transaction_record(){ + $sql = "select * from TuniuExcel"; + $query = $this->INFO->query($sql); + return $query->result(); + } + + public function get_order_info($order){ + $sql = "SELECT tol_retailOrderId,tol_orderId FROM TuniuOrderList WHERE tol_orderId = '{$order}'"; + $query = $this->INFO->query($sql); + return $query->result(); + } + + public function get_coli_id($cold_sn){ + $sql = "select * from BIZ_ConfirmLineInfo where coli_sn = (select cold_coli_sn from BIZ_ConfirmLineDetail where COLD_SN = '{$cold_sn}')"; + $query = $this->HT->query($sql); + return $query->result(); + } + + function get_gri_no($coli_id){ + $sql="SELECT GRI_No FROM GroupInfo + WHERE GRI_SN=( + SELECT COLI_GRI_SN FROM BIZ_ConfirmLineInfo WHERE COLI_ID=? + ) + "; + $query = $this->HT->query($sql, $coli_id); + return $query->result(); + } + + public function test(){ + $sql = "delete from TuniuOrderList where tol_sn in (18,20)"; + $query = $this->INFO->query($sql); + return $query; + } + +} + +?> \ No newline at end of file diff --git a/application/third_party/train/models/tuniuprice_model.php b/application/third_party/train/models/tuniuprice_model.php new file mode 100644 index 00000000..4482d2e6 --- /dev/null +++ b/application/third_party/train/models/tuniuprice_model.php @@ -0,0 +1,16 @@ +<?php +class tuniuprice_model extends CI_Model { + + function __construct() { + parent::__construct(); + $this->HT = $this->load->database('HT', TRUE); + } + + + +} + + + + +?> \ No newline at end of file diff --git a/application/third_party/train/views/email.php b/application/third_party/train/views/email.php index 66184036..9fc4c7a2 100644 --- a/application/third_party/train/views/email.php +++ b/application/third_party/train/views/email.php @@ -1,70 +1,33 @@ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> -<html xmlns="http://www.w3.org/1999/xhtml"> -<head> -<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> -<title>无标题文档</title> -<style> -*{ font-family:Verdana, Geneva, sans-serif;} -h1{ font-size:18px; text-align:center; color:#545454; margin:0 0 10px 0!important;} -p{ font-size:14px; color:#545454; line-height:22px; margin-bottom:12px!important;} -table.table{ width:90%; border-width:1px 1px 0 1px; border-color:#d1d1d1; border-style: solid; margin-bottom:15px;} -table.table th{ background:#f1f1f1; color:#666; border-bottom:1px solid #d1d1d1; width:180px; font-size:14px; text-align:left; padding:8px 10px 8px 10px;} -table.table td{ padding:8px 0 8px 10px; border-bottom:1px solid #d1d1d1; font-size:14px; color:#545454;} -</style> -</head> -<body> -<h1>China Highlights Booking Confirmation</h1> -<p>Dear <?php echo $user[0]->GUT_LastName?>,</p> -<p>Thanks for payment US$145 . The train tickets have already been issued. </p> -<p> You can collect the paper ticket(s) from now at any train station in mainland China. </p> -<p> Please present all passenger(s) original passport(s) and Ticket Pick Up No.E601014106 &nbsp;at any ticket collecting counters (in Chinese 取票窗口)of any railway stations in mainland China. They will then issue your paper train ticket(s). </p> -<table border="0" cellpadding="0" cellspacing="0" class="table"> - <tr> - <th>Passenger(s)</th> - <td><p>2 adult(s) - </p> - <p> 1. ALEXANDER JAMES JOHNSON , passport number 503406354<br /> -2. SIAN MARIE JOHNSON , passport number 528876517</p></td> - </tr> -</table> -<p>Train 1:</p> -<table border="0" cellpadding="0" cellspacing="0" class="table"> - <tr> - <th><strong>Ticket Pick Up No.</strong></th> - <td>E601014106&nbsp; </td> - </tr> - <tr> - <th><strong>Train No.</strong></th> - <td>Z19</td> - </tr> - <tr> - <th><strong>Departure</strong></th> - <td>20:40 Jun.06 Beijing Xi (West) Station(in Chinese 北京西火车站)</td> - </tr> - <tr> - <th><strong>Arrival</strong></th> - <td>08:31AM Jun.07 Xi'an Station(in Chinese 西安火车站) </td> - </tr> - <tr> - <th><strong>Class</strong></th> - <td>Soft Sleeper </td> - </tr> -</table> -<p>Kindly note below:</p> -<p> 1. The same passport that was used for booking should also be used for ticket collection. A renewed passport won't be acceptable even if the holder is the same person. The system does not allow us to change passport number or passenger name after issue ticket. Have to issue new ticket if wrong passport number or name.</p> -<p> 2. There is no further fee if collect train ticket(s) at the DEPARTURE station shown on your ticket(s). RMB 5 per ticket will be charged at a ticket counter at other stations. E.g. if you have booked Beijing-Shanghai and Shanghai-Beijing ticket(s), and you collect them all at Beijing, you will be charged RMB 5 per ticket for the Shanghai-Beijing ticket(s), but if you pick up the return leg ticket(s) separately in Shanghai you will avoid the charge.</p> -<p> 3. On departure day, please time your arrival wisely. If you are going to collect your tickets on departure day, we suggest you be at the station at least 1.5 hours ahead of the stated departure time to allow for waiting in queue at the ticket-counter, for security checks and for ticket checks.<br /> -If you&rsquo;ve already collected before the departure day, it is also wise to be at the station at least 40 minutes ahead. </p> -<p> 4. Download railway station instructions, maps and tips at <a href="http://www.chinahighlights.com/china-trains/station-map.htm">http://www.chinahighlights.com/china-trains/station-map.htm</a> <br /> - <br /> -5.Terms &amp; Conditions. <a href="http://www.chinahighlights.com/china-trains/booking-policy.htm">http://www.chinahighlights.com/china-trains/booking-policy.htm</a></p> -<p> Best Regards!<br /> - Iris Wang, Travel Advisor<br /> - Tel: +86-773-2801368 &nbsp;Mobile:+86-18775900313 <br /> - Fax: 86-773-2827424, 86-773-2885308 <br /> - E-mail: <a href="mailto:iris@chinahighlights.me">iris@chinahighlights.me</a><br /> - <a href="http://www.chinahighlights.com">www.chinahighlights.com</a> <br /> - Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China<br /> -If you wish to share anything with my supervisor (Ms. Alex Yang), please feel free to send your email to <a href="mailto:alex@chinahighlights.net">alex@chinahighlights.net</a>. </p> -</body> -</html> +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>China train ticket(s) confirmed, Booking Number <?php echo $coli_id;?></title><style>*{ font-family:Verdana, Geneva, sans-serif; color:#545454;}</style></head><body style="font-family:Verdana, Geneva, sans-serif; border-left:1px solid #d1d1d1; border-right:1px solid #d1d1d1;"><h1 style="font-size:20px; text-align:center;">China Highlights Booking Confirmation</h1><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Dear <?php echo $toname?>,</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Thank you for your payment of US$<?php echo $price->GAI_SQJE?> . The train tickets have already been issued. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> You can collect the paper ticket(s) from now on at any train station in mainland China.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><strong>Please note:</strong></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">1.Please present the <strong>original passport(s) of all the passenger(s)</strong> and the ticket pick-up number(s) <span style="color:#33F"><?php echo $juhe_info->ordernumber;?></span> at ticket collection counters. The counter will then issue your paper train ticket(s). </p> +<p>See the <a style="color:#33F" href="https://www.chinahighlights.com/travelguide/transportation/how-to-board-train.htm">video</a> about how to collect the ticket(s) in China. +</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please double check the train(s) information and passport information. Let us know AT ONCE if you see any mistakes below. We can try to cancel tickets to minimize your loss. A 20% cancellation fee is charged by China Railway.</p><table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;width: 293px;">Ticket collection sentences</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p>The bilingual note below might help you pick up tickets at the ticket collection counter more easily.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 1.Please show me which window for picking up the train ticket. 你好,请问哪个是取票窗?</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please issue the paper tickets for me. The following is the pick up number(s).请帮我出票,电子取票号如下.</p></td></tr></table> +<?php + $j = 0; + foreach($train_info as $item){ + echo '<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"> + <tr> + <th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Pick up number</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><span style="color:#33F">'.$item->FOI_TrainNetOrderNo.'</span></td>'; + echo '</tr><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Train No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->FlightsNo.'</td></tr><tr>'; + echo '<th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Departure</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->DepartureTime.' '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Arrival</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->ArrivalTime.' '.$item->ArrivalCity.' Station(in Chinese '.$item->ArrivalAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Class</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->Cabin.' ('.$seatinfo.')</td></tr></table>'; + } +?> +<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;">Passenger(s)</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p><?php + if($adult>0){echo $adult.' adult(s) ';} + if($chlid>0){echo $chlid.' chlid(s) ';} + if($baby>0){echo $baby.' baby(s) ';} + ?></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> <?php + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + ?></p></td></tr></table> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 3.On your departure day, please time your arrival at the station wisely. If you are going to collect your train ticket(s) on the departure day, allow enough time waiting in the queue of the ticket collection counter, for the security x-ray check of your luggage, and for the ticket check before entering the passenger lounge. Tickets will stop being issued 30 minutes prior to departure. We suggest you be at the station at least 1.5 hours ahead of the stated departure time. Please leave at least 2.5 hours during public holidays.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 4.If you’ve already collected your ticket before the departure day, we recommend that you be at the station at least 40 minutes ahead of time. Please be at the station at least 1.5 hours during a public holiday. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 5.Please don't throw your ticket(s) away because you'll need it to exit the station.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">6.If you cancel the ticket(s) at a train station yourself, the money will be refunded to our account. Please cancel the tickets before the train departure. And email us then we will refund you accordingly.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">7.<a style="color:#33F" href="https://www.chinahighlights.com/china-trains/booking-policy.htm">China Highlights train ticket booking policy </a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Should you have any questions about your train ticket bookings, please do not hesitate to contact me.</p> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Best Regards!</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><?php echo $operator[0]->Name?>, Travel Advisor</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Tel: <?php echo $operator[0]->tel;?> Mobile: <?php echo $operator[0]->Mobile;?> </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Fax: 86-773-2827424, 86-773-2885308 </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> E-mail: <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?>;</a><a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?>;</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">WeChat: CH_train<p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><a href="http://www.chinahighlights.com">www.chinahighlights.com</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> If you wish to share anything with my supervisor (Ms. ethel), please feel free to send your email to <a href="mailto:ethel@chinahighlights.net">ethel@chinahighlights.net</a>.</p></body></html> diff --git a/application/third_party/train/views/email_before.php b/application/third_party/train/views/email_before.php new file mode 100644 index 00000000..2a077a6c --- /dev/null +++ b/application/third_party/train/views/email_before.php @@ -0,0 +1,48 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>China Highlights Booking Confirmation</title><style>*{ font-family:Verdana, Geneva, sans-serif; color:#545454;}</style></head><body style="font-family:Verdana, Geneva, sans-serif; border-left:1px solid #d1d1d1; border-right:1px solid #d1d1d1;"><h1 style="font-size:20px; text-align:center;">China Highlights Booking Confirmation</h1><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Dear <?php echo $toname?>,</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Thanks for payment US$<?php echo $price->GAI_SQJE?> . The train tickets have already been issued. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> You can collect the paper ticket(s) from now at any train station in mainland China.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> The same passport that was used for booking should also be used for ticket collection. A renewed passport won't be acceptable even if the holder is the same person. The system does not allow us to change passport number or passenger name after issue ticket. Have to issue new ticket if wrong passport number or name.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Please collect your paper tickets from a ticket counter in the train station. Tickets will stop being printed 30 minutes prior to departure. On departure day, please time your arrival wisely. If you are going to collect your tickets on departure day, allow for time waiting in queue at the ticket-counter, for security checks and for ticket checks. We suggest you be at the station at least 1.5 hours ahead of the stated departure time.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">If you’ve already collected before the departure day, it is also wise to be at the station at least 40 minutes ahead. </p><table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;">Passenger(s)</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p><?php + if($adult>0){echo $adult.' adult(s) ';} + if($chlid>0){echo $chlid.' chlid(s) ';} + if($baby>0){echo $baby.' baby(s) ';} + ?></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> <?php + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + ?></p></td></tr></table> +<?php + $j = 0; + foreach($train_info as $item){ + echo '<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Train'.++$j.':</p>'; + echo '<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"> + <tr> + <th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Ticket Pick Up No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><span style="color:#33F">'.$item->FOI_TrainNetOrderNo.'</span></td>'; + echo '</tr><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Train No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->FlightsNo.'</td></tr><tr>'; + echo '<th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Departure</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->DepartureTime.' '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Arrival</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->ArrivalTime.' '.$item->ArrivalCity.' Station(in Chinese '.$item->ArrivalAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Class</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->Cabin.'</td></tr></table>'; + } +?> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Kindly note below:</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">1.Please present all passenger(s) original passport(s) and Ticket Pick Up No.<span style="color:#33F"><?php echo $item->FOI_TrainNetOrderNo?></span>at any ticket counters of any railway stations. They will then issue your paper train ticket(s). You can find more instruction of collecting tickets enclosure. +</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 2.You can show screenshot of the paper tickets to the railway station counter. It helps get paper tickets easily.</p> +<?php + foreach($train_info as $obj){ + echo '<table width="100%" border="0" cellspacing="0" cellpadding="0">'; + echo '<tr style="background:#f0f0f0; color:#545454; font-weight:100; font-size:20px; ">'; + echo ' <th style="font-weight:100; font-size:18px; text-align:left;padding:8px 10px; border-top:3px solid #ad1818;">'.substr($obj->DepartureDate,0,10).'&nbsp;&nbsp;&nbsp;'.$obj->FlightsNo.'&nbsp;&nbsp;&nbsp;'.$obj->FOI_TrainNetOrderNo.'</th></tr><tr>'; + echo '<td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;"><p>'.$obj->DepartAirport_cn.'('.$obj->DepartureCity.')<span style=" font-size:12px;">'.$obj->DepartureTime.'</span> To '.$obj->ArrivalAirport_cn.'('.$obj->ArrivalCity.')<span style=" font-size:12px;">'.$obj->ArrivalTime.'</span></p></td></tr>'; + foreach($juhe_info->passengers as $people){ + echo '<tr><td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;">'; + echo '<p>'.$people->passengersename.'('.$people->piaotypename.') '; + echo $people->cxin.' 票价:¥'.$people->price.'</p>'; + echo '</td></tr>'; + } + echo '<tr><td style=" padding:8px 10px; font-size:15px; color:#545454; border-bottom:1px solid #d1d1d1;"><p>出票成功</p></td></tr></table>'; + } +?> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 3. There is no further fee if collect train ticket(s) at the DEPARTURE station shown on your ticket(s). RMB 5 per ticket will be charged at the ticket counter at other stations. Return tickets are treated separately. E.g. if you have booked Beijing-Shanghai and Shanghai-Beijing ticket(s), and you collect them all at Beijing, you will be charged RMB 5 per ticket for the Shanghai-Beijing ticket(s), but if you pick up the return leg ticket(s) separately in Shanghai you will avoid the charge.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 4. Please keep your ticket(s) and don't throw your ticket(s) away once you've boarded your train, you'll need it to exit the station.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 5.Download railway station instructions, maps and tips at <a href="https://www.chinahighlights.com/china-trains/station-map.htm">https://www.chinahighlights.com/china-trains/station-map.htm</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">6.Terms & Conditions. <a href="https://www.chinahighlights.com/china-trains/booking-policy.htm">https://www.chinahighlights.com/china-trains/booking-policy.htm</a></p><p>&nbsp;</p> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Best Regards!</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><?php echo $operator[0]->Name?>, Travel Advisor</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Tel: <?php echo $operator[0]->tel;?> Mobile: <?php echo $operator[0]->Mobile;?> </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Fax: 86-773-2827424, 86-773-2885308 </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> E-mail: <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?>;</a><a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?>;</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><a href="http://www.chinahighlights.com">www.chinahighlights.com</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> If you wish to share anything with my supervisor (Ms. Alex Yang), please feel free to send your email to <a href="mailto:alex@chinahighlights.net">alex@chinahighlights.net</a>.</p></body></html> diff --git a/application/third_party/train/views/email_fault.php b/application/third_party/train/views/email_fault.php new file mode 100644 index 00000000..a059912b --- /dev/null +++ b/application/third_party/train/views/email_fault.php @@ -0,0 +1,26 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Dear <?php echo $toname?>,</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;"> Thank you for your booking (order number <?php echo $coli_id?>), we have received your payment of USD<?php echo $price->GAI_SQJE?>.&nbsp;</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;"> Due to the heavy traffic flow of data, the system failed to automatically issue your ticket(s).</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Your travel advisor will purchase your train ticket(s) manually. &nbsp;You will receive an email within half a working day (Our time now:&nbsp;<strong><?php echo date('H:i').' '.date('a');?></strong>, <?php echo date('D');?>,<?php echo date('F').' '.date('d').','.date('Y');?> GMT+8).Should you have any questions or concerns with regards to your train booking, please do not hesitate to contact me at <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?></a>;<a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?></a> or telephone <?php echo $operator[0]->tel;?>. </p> +<?php foreach($train_info as $item){ + echo '<table border="0" cellspacing="0" cellpadding="0" width="60%">'; + echo '<tr><th width="17%" style="font-family:Verdana, Geneva, sans-serif;font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Train No. </th>'; + echo '<td width="83%" style="font-family:Verdana, Geneva, sans-serif;font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->FlightsNo.'</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Departure </th>'; + echo '<td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->DepartureTime.', '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)&nbsp;</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Arrival </th><td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->ArrivalTime.', '.$item->ArrivalCity.'(in Chinese'. $item->ArrivalAirport_cn.'火车站)&nbsp; </td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Class </th><td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'.$item->Cabin.'</td></tr>'; + echo '<tr><th style="font-family:Verdana, Geneva, sans-serif; font-size:14px; color:#a31022; background:#e6e6e6; text-align:left; padding:10px;">Passenger(s) </th>'; + echo '<td style="font-family:Verdana, Geneva, sans-serif; font-size:14px; text-align:left; padding:10px; border-bottom:1px solid #d1d1d1;">'; + if($adult>0){echo $adult.' adult(s)<br/> ';} + if($chlid>0){echo $chlid.' chlid(s)<br/> ';} + if($baby>0){echo $baby.' baby(s)<br/> ';} + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + echo '</tr></table>'; + echo '<p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Regards <br />'; + echo $operator[0]->Name.'<br/>Travel Advisor<br/>'; + echo 'Telephone:&nbsp;(Office)'.$operator[0]->tel.', M: '.$operator[0]->Mobile.','; + echo 'Email: <a href="mailto:'.$emailarr[0].'">'.$emailarr[0].'</a>;<a href="mailto:'.$emailarr[1].'">'.$emailarr[1].'</a>;&nbsp</p>'; + }?> +</body> +</html> diff --git a/application/third_party/train/views/email_test.php b/application/third_party/train/views/email_test.php new file mode 100644 index 00000000..9fc4c7a2 --- /dev/null +++ b/application/third_party/train/views/email_test.php @@ -0,0 +1,33 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> +<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>China train ticket(s) confirmed, Booking Number <?php echo $coli_id;?></title><style>*{ font-family:Verdana, Geneva, sans-serif; color:#545454;}</style></head><body style="font-family:Verdana, Geneva, sans-serif; border-left:1px solid #d1d1d1; border-right:1px solid #d1d1d1;"><h1 style="font-size:20px; text-align:center;">China Highlights Booking Confirmation</h1><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Dear <?php echo $toname?>,</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Thank you for your payment of US$<?php echo $price->GAI_SQJE?> . The train tickets have already been issued. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> You can collect the paper ticket(s) from now on at any train station in mainland China.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><strong>Please note:</strong></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">1.Please present the <strong>original passport(s) of all the passenger(s)</strong> and the ticket pick-up number(s) <span style="color:#33F"><?php echo $juhe_info->ordernumber;?></span> at ticket collection counters. The counter will then issue your paper train ticket(s). </p> +<p>See the <a style="color:#33F" href="https://www.chinahighlights.com/travelguide/transportation/how-to-board-train.htm">video</a> about how to collect the ticket(s) in China. +</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please double check the train(s) information and passport information. Let us know AT ONCE if you see any mistakes below. We can try to cancel tickets to minimize your loss. A 20% cancellation fee is charged by China Railway.</p><table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;width: 293px;">Ticket collection sentences</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p>The bilingual note below might help you pick up tickets at the ticket collection counter more easily.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 1.Please show me which window for picking up the train ticket. 你好,请问哪个是取票窗?</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">2.Please issue the paper tickets for me. The following is the pick up number(s).请帮我出票,电子取票号如下.</p></td></tr></table> +<?php + $j = 0; + foreach($train_info as $item){ + echo '<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"> + <tr> + <th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Pick up number</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><span style="color:#33F">'.$item->FOI_TrainNetOrderNo.'</span></td>'; + echo '</tr><tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Train No.</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->FlightsNo.'</td></tr><tr>'; + echo '<th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Departure</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->DepartureTime.' '.$item->DepartureCity.' Station(in Chinese '.$item->DepartAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Arrival</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->ArrivalTime.' '.$item->ArrivalCity.' Station(in Chinese '.$item->ArrivalAirport_cn.'火车站)</td></tr>'; + echo '<tr><th style="text-align:left; padding:10px; font-size:14px; background:#f1f1f1;"><strong>Class</strong></th>'; + echo '<td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;">'.$item->Cabin.' ('.$seatinfo.')</td></tr></table>'; + } +?> +<table border="0" cellpadding="0" cellspacing="0" style="width:100%; border-top:3px solid #a31022; border-left:1px solid #d1d1d1; margin-bottom:15px;"><tr><th style="width: 293px;text-align:left; padding:10px; font-size:14px; background:#f1f1f1;">Passenger(s)</th><td style="border-bottom:1px solid #d1d1d1; border-right:1px solid #d1d1d1; font-size:14px; line-height:22px; padding:10px;"><p><?php + if($adult>0){echo $adult.' adult(s) ';} + if($chlid>0){echo $chlid.' chlid(s) ';} + if($baby>0){echo $baby.' baby(s) ';} + ?></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> <?php + $i=0; + foreach($allpeople as $item){ + echo ++$i.'.'.$item->BPE_FirstName.$item->BPE_MiddleName.$item->BPE_LastName.' , passport number '.$item->BPE_Passport.'<br>'; + } + ?></p></td></tr></table> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 3.On your departure day, please time your arrival at the station wisely. If you are going to collect your train ticket(s) on the departure day, allow enough time waiting in the queue of the ticket collection counter, for the security x-ray check of your luggage, and for the ticket check before entering the passenger lounge. Tickets will stop being issued 30 minutes prior to departure. We suggest you be at the station at least 1.5 hours ahead of the stated departure time. Please leave at least 2.5 hours during public holidays.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 4.If you’ve already collected your ticket before the departure day, we recommend that you be at the station at least 40 minutes ahead of time. Please be at the station at least 1.5 hours during a public holiday. </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> 5.Please don't throw your ticket(s) away because you'll need it to exit the station.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">6.If you cancel the ticket(s) at a train station yourself, the money will be refunded to our account. Please cancel the tickets before the train departure. And email us then we will refund you accordingly.</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">7.<a style="color:#33F" href="https://www.chinahighlights.com/china-trains/booking-policy.htm">China Highlights train ticket booking policy </a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">Should you have any questions about your train ticket bookings, please do not hesitate to contact me.</p> +<p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Best Regards!</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><?php echo $operator[0]->Name?>, Travel Advisor</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Tel: <?php echo $operator[0]->tel;?> Mobile: <?php echo $operator[0]->Mobile;?> </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Fax: 86-773-2827424, 86-773-2885308 </p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> E-mail: <a href="mailto:<?php echo $emailarr[0]?>"><?php echo $emailarr[0]?>;</a><a href="mailto:<?php echo $emailarr[1]?>"><?php echo $emailarr[1]?>;</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;">WeChat: CH_train<p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"><a href="http://www.chinahighlights.com">www.chinahighlights.com</a></p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> Address: Building 6, Chuangyi Business Park, 70 Qilidian Road, Guilin, Guangxi, 541004, China</p><p style="font-size:14px; margin:0 0 18px 0; line-height:22px;"> If you wish to share anything with my supervisor (Ms. ethel), please feel free to send your email to <a href="mailto:ethel@chinahighlights.net">ethel@chinahighlights.net</a>.</p></body></html> diff --git a/application/third_party/train/views/export20161229.php b/application/third_party/train/views/export20161229.php new file mode 100644 index 00000000..a2433f09 --- /dev/null +++ b/application/third_party/train/views/export20161229.php @@ -0,0 +1,23 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">交易记录导出&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/ht_order_list');?>">订单列表>></a> </h3> + </div> + <div class="panel-body"> + <form style="width: 500px;float: left;" action="" method="post"> + <input type="text" name="from_date" class="date" value="">至 + <input type="text" name="to_date" class="date" value=""> + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 导出</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;"> + </div> + </div> + +</div> + +<script> + $(".date").datepicker({ + 'format': 'yyyy-m-d', + 'autoclose': true + }); +</script> \ No newline at end of file diff --git a/application/third_party/train/views/ht_order_list.html b/application/third_party/train/views/ht_order_list.html index dc7256e7..4514d87a 100644 --- a/application/third_party/train/views/ht_order_list.html +++ b/application/third_party/train/views/ht_order_list.html @@ -9,6 +9,22 @@ <div class="col-md-6"> <input class="form-control" type="text" placeholder="汉特订单号或聚合订单号" name="order" value="<?php echo !empty($order)?"$order":"";?>"> </div> + <div class="col-md-4"> + <select class="form-control" name="web_code"> + <option value ="分站点查询,默认商旅" disabled="disabled" selected>分站点查询,默认全站</option> + <option value ="CHT">商旅</option> + <option value ="jp">日本</option> + <option value="train_vac">西班牙</option> + <option value="train_it">意大利</option> + <option value="train_ru">俄罗斯</option> + <option value="train_vc">法国</option> + </select> + </div> + <!--<div class="col-md-5"> + <input type="text" name="from_date" class="date" value="" class=""> + 至 + <input type="text" name="to_date" class="date" value=""> + </div>--> <div class="col-md-5"> <button type="submit" id="sub" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-search"></span> 搜索</button> </div> @@ -25,7 +41,7 @@ <thead> <tr> <th style="text-align:center;">序号</th> - <th style="text-align:center;">汉特订单号</th> + <th style="text-align:center;">汉特订单号(商家订单号)</th> <th style="text-align:center;">聚合订单号</th> <th style="text-align:center;">车次</th> <th style="text-align:center;">出发</th> @@ -33,6 +49,9 @@ <th style="text-align:center;">状态</th> <th style="text-align:center;">价格</th> <th style="text-align:center;">提交时间</th> + <th style="text-align:center;">所属部门</th> + <th style="text-align:center;">出票方式</th> + <th style="text-align:center;">是否发送邮件</th> <th style="text-align:center;">操作</th> </tr> </thead> @@ -40,7 +59,7 @@ <?php $num=0; foreach($data as $v):?> <tr> <td><?php echo ++$num;?></td> - <td><?php echo $v->COLI_ID;?></td> + <td><?php echo $v->COLI_ID.'('.$v->JOL_COLD_SN.')';?></td> <td><?php echo $v->JOL_JuheOrder;?></td> <td><?php echo $v->JOL_TrainCode;?></td> <td><?php echo $v->JOL_FromStation;?></td> @@ -48,6 +67,27 @@ <td><?php echo $v->info;?></td> <td><?php echo $v->JOL_Price;?></td> <td><?php echo $v->JOL_SubTime;?></td> + <td><?php echo $v->COLI_WebCode;?></td> + <?php + if($v->JOL_IsAuto == 1){ + echo '<td>自动</td>'; + }elseif($v->JOL_IsAuto == 0){ + echo '<td>手动</td>'; + }elseif($v->JOL_IsAuto == 3){ + echo '<td>抢票</td>'; + } + ?> + <?php + if($v->JOL_SendMail == 1){ + if($v->JOL_M_SN){ + echo '<td><a target="_blank" href="http://www.mycht.cn/info.php/apps/train/index/get_mailinfo/'.$v->JOL_M_SN.'">是</a></td>'; + }else{ + echo '<td>是</td>'; + } + }else{ + echo '<td>否</td>'; + } + ?> <td><a target="_blank" href="order?order=<?php echo $v->JOL_JuheOrder;?>">详情</a></td> </tr> <?php endforeach;?> diff --git a/application/third_party/train/views/ht_train_order_info.php b/application/third_party/train/views/ht_train_order_info.php index 6189118b..93aed6f3 100644 --- a/application/third_party/train/views/ht_train_order_info.php +++ b/application/third_party/train/views/ht_train_order_info.php @@ -1,7 +1,83 @@ +<style> +.clear {clear: both;} +.train-summary{ font-size:12px; margin-bottom:10px;} +.train-summary span{ color:#9a0918;} +a:link.seat-a{background-image:url(/css/images/train/a-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-a{background-image:url(/css/images/train/a-seath.jpg);} +.selected_seat-a{background-image:url(/css/images/train/a-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-b{background-image:url(/css/images/train/b-seat.jpg); background-repeat:no-repeat; text-decoration:none; width:55px; display:block; height:42px; float:left;} +a:hover.seat-b{background-image:url(/css/images/train/b-seath.jpg);} +.selected_seat-b{background-image:url(/css/images/train/b-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-c{background-image:url(/css/images/train/c-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-c{background-image:url(/css/images/train/c-seath.jpg);} +.selected_seat-c{background-image:url(/css/images/train/c-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-d{background-image:url(/css/images/train/d-seat.jpg); background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:hover.seat-d{background-image:url(/css/images/train/d-seath.jpg);} +.selected_seat-d{background-image:url(/css/images/train/d-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.seat-f{background-image:url(/css/images/train/f-seat.jpg); background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:hover.seat-f{background-image:url(/css/images/train/f-seath.jpg);} +.selected_seat-f{background-image:url(/css/images/train/f-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.sleep-a {background-image:url(/css/images/train/l-up.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-a { background-image:url(/css/images/train/l-upa.jpg); } +.selected_sleep-a { background-image:url(/css/images/train/l-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-b {background-image:url(/css/images/train/r-up.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-b { background-image:url(/css/images/train/r-upa.jpg); } +.selected_sleep-b { background-image:url(/css/images/train/r-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-c {background-image:url(/css/images/train/l-mid.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-c { background-image:url(/css/images/train/l-mida.jpg); } +.selected_sleep-c { background-image:url(/css/images/train/l-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-d {background-image:url(/css/images/train/r-mid.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-d { background-image:url(/css/images/train/r-mida.jpg); } +.selected_sleep-d { background-image:url(/css/images/train/r-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-e {background-image:url(/css/images/train/l-low.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-e { background-image:url(/css/images/train/l-lowa.jpg); } +.selected_sleep-e { background-image:url(/css/images/train/l-lowa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-f {background-image:url(/css/images/train/r-low.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-f { background-image:url(/css/images/train/r-lowa.jpg); } +.selected_sleep-f { background-image:url(/css/images/train/r-lowa.jpg)!important; width:104px; display:block; height:38px; float:left; } +</style> +<script> +$(function(){ + //var selected = $('.selectticket').find('.selected').length; + //$('.selected_People').html(selected); +}); + +function selseat(seat){ + var type = $(seat).attr('type'); + var total = $(seat).parent().parent().find('.train-summary .seat_TotalPeople').html(); + if(total>=5){ + total = 5; + $('.seat_TotalPeople').html(total); + } + var count = $(seat).parent().parent().find('.selected').length; + console.log('执行之前的数量'+count); + //处理选座事件 + + if($(seat).hasClass('selected_'+type)){ + $(seat).removeClass('selected'); + $(seat).removeClass('selected_'+type); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('减掉之后'+count); + }else{ + if(count >= total){ + alert('You already chose seats for all the passengers.'); + }else{ + $(seat).addClass('selected_'+type); + $(seat).addClass('selected'); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('增加之后'+count); + } + + } + +} +</script> <div style="width:90%;margin:30px auto;"> <div class="panel panel-primary"> <div class="panel-heading"> - <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/ht_order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/export');?>">导出交易记录>></a> <span style="margin-left:200px;">版本:V2.0</span><span class="pull-right">聚合余额(RMB):<?php echo $balance;?></span></h3> + <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/ht_order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/tuniu_train/ht_order_list');?>">抢票订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/export');?>">导出交易记录>></a> <span style="margin-left:200px;">版本:V2.0</span><span class="pull-right">聚合余额(RMB):<?php echo $balance;?></span></h3> </div> <div class="panel-body"> <form style="width: 300px;float: left;" action="" method="post"> @@ -46,7 +122,7 @@ <td><?php echo $v->train[0]->DepartureTime;?></td> <td><?php echo $v->train[0]->ArrivalTime;?></td> <td><?php echo $v->train[0]->adultcost;?></td> - <td><?php echo !empty($v->status)?"<span style='color:red;'>是</span>":"否";?></td> + <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> <td><button type="button" class="btn btn-success pay_api" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>" title="超过五个乘客不可用" >快捷订票</button></td> </tr> <tr> @@ -71,6 +147,145 @@ <td><?php echo $p->BPE_GuestType==1?"成人":($p->BPE_GuestType==2?"儿童":"婴儿");?></td> </tr> <?php endforeach;?> + <tr style="text-align:;"> + <td colspan="11" class="selectticket"> + <?php + $traintype = substr($v->train[0]->FlightsNo,0,1); + $arr = array('C','D','G'); + $sel_count = 0; + if(in_array($traintype,$arr)){ + $selectseat = ''; + $train_select = $v->train[0]->FOI_SelectedSeat; + $a1=$b1=$c1=$d1=$f1=$a2=$b2=$c2=$d2=$f2=false; + if($train_select){ + $obj = explode(',',$train_select); + foreach($obj as $value){ + switch($value){ + case '1A': + $a1 = true; + $sel_count++; + break; + case '1B': + $b1 = true; + $sel_count++; + break; + case '1C': + $c1 = true; + $sel_count++; + break; + case '1D': + $d1 = true; + $sel_count++; + break; + case '1F': + $f1 = true; + $sel_count++; + break; + case '2A': + $a2 = true; + $sel_count++; + break; + case '2B': + $b2 = true; + $sel_count++; + break; + case '2C': + $c2 = true; + $sel_count++; + break; + case '2D': + $d2 = true; + $sel_count++; + break; + case '2F': + $f2 = true; + $sel_count++; + break; + } + } + } + $html = ''; + $html .= '<div class="train-summary">'.$v->train[0]->Cabin.' for '.$v->train[0]->FlightsNo.' <span>(<span class="selected_People">'.$sel_count.'</span> of <span class="seat_TotalPeople">'.count($v->people).'</span> Seats)</span></div>'; + $html .= '<div class="seatPick">'; + if($a1){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b1){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + } + + } + if($c1){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d1){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + } + + } + if($f1){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + $html .= '<div class="seatPick">'; + if($a2){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b2){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + } + + } + if($c2){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d2){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + } + + } + if($f2){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + + if($v->train[0]->Aircraft != 'F'){ + echo $html; + } + } + ?> + </td> + </tr> <tr style="text-align:;"> <td> <button type="button" class="btn btn-success checked_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">订票</button> @@ -78,18 +293,35 @@ <td colspan="4" class="biaoqian"><span class="back_mes" style="color:red;line-height: 30px;"></span> </td> </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success grab_ticket" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">抢票</button> + </td> + <td colspan="4"> + <span class="grab_config"><a style="text-decoration:none;cursor:pointer;">点击打开配置清单</a></span> + <p class="grab_mes" style="color:red;line-height: 30px;"></p> + <table class="table table-condensed table-bordered grab_config_table hidden"> + <tbody> + <tr> + <td colspan="2"><span style="float:left">截止时间 : <input type="text" name="deadline" class="date"/> 示例:2018-03-22 17:00:00(必填)</span></td> + <td colspan="2"><span style="float:left">备选车次 : <input type="text" name="alternate_train"/> 示例:["k10","G10"]</span></td> + <td colspan="2"><span style="float:left">备选座位 : <input type="text" name="alternate_seat"/> 示例:["1","2"]</span></td> + </tr> + </tbody> + </table> + </td> + + </tr> <tr id="back_<?php echo $v->train[0]->FOI_COLD_SN;?>" style="display:none;"> <td colspan="5"> 快捷订票处理结果:<span style="color:red;"></span> </td> </tr> + </tbody> </table> - </td> </tr> - - </tbody> </table> <?php endforeach;endif;?> @@ -105,8 +337,14 @@ // alert(url+$(this).attr("data-order")); var THIS=$(this); var order=$(this).attr("data-order"); + var selectseat = ''; + $(this).parent().parent().next().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); $.ajax({ - url:url+$(this).attr("data-order"), + url:url+$(this).attr("data-order")+'&selectseat='+selectseat, beforeSend:function(data){ THIS.html("处理中..."); THIS.attr("disabled","disabled") @@ -142,8 +380,15 @@ checkbox.each(function(i){ people_sn+=","+$(this).val(); }); + var selectseat = ''; + $(this).parent().parent().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + people_sn=people_sn.substring(1); - url2+=$(this).attr("data-order")+"&people="+people_sn; + url2+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat; var THIS=$(this); THIS.parent().parent().find(".back_mes").html(" ");//清空提示 @@ -163,6 +408,52 @@ dataType: "json", }); + + return false; + }); + + //抢票清单 + $('.grab_config').click(function(){ + var table = $(this).next().next('.grab_config_table'); + if(table.hasClass('hidden')){ + table.removeClass('hidden'); + }else{ + table.addClass('hidden'); + } + }); + + //开始抢票 + $('.grab_ticket').click(function(){ + var url2="<?php echo site_url('apps/train/tuniu_train/grabTicketBook?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + people_sn=people_sn.substring(1); + // var coli_id = $('input[name="ht_order"]').val(); + var deadline = $(this).parent().next().find('.date').val(); + var alternate_train = $('input[name="alternate_train"]').val(); + var alternate_seat = $('input[name="alternate_seat"]').val(); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&deadline="+deadline+"&alternate_train="+alternate_train+"&alternate_seat="+alternate_seat; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("抢票"); + THIS.parent().next().find(".grab_mes").html(data.mes); + + }, + dataType: "json", + + }); return false; }); diff --git a/application/third_party/train/views/ht_train_order_info_test.php b/application/third_party/train/views/ht_train_order_info_test.php new file mode 100644 index 00000000..b210c868 --- /dev/null +++ b/application/third_party/train/views/ht_train_order_info_test.php @@ -0,0 +1,509 @@ +<style> +.clear {clear: both;} +.train-summary{ font-size:12px; margin-bottom:10px;} +.train-summary span{ color:#9a0918;} +a:link.seat-a{background-image:url(/css/images/train/a-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-a{background-image:url(/css/images/train/a-seath.jpg);} +.selected_seat-a{background-image:url(/css/images/train/a-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-b{background-image:url(/css/images/train/b-seat.jpg); background-repeat:no-repeat; text-decoration:none; width:55px; display:block; height:42px; float:left;} +a:hover.seat-b{background-image:url(/css/images/train/b-seath.jpg);} +.selected_seat-b{background-image:url(/css/images/train/b-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-c{background-image:url(/css/images/train/c-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-c{background-image:url(/css/images/train/c-seath.jpg);} +.selected_seat-c{background-image:url(/css/images/train/c-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-d{background-image:url(/css/images/train/d-seat.jpg); background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:hover.seat-d{background-image:url(/css/images/train/d-seath.jpg);} +.selected_seat-d{background-image:url(/css/images/train/d-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.seat-f{background-image:url(/css/images/train/f-seat.jpg); background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:hover.seat-f{background-image:url(/css/images/train/f-seath.jpg);} +.selected_seat-f{background-image:url(/css/images/train/f-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.sleep-a {background-image:url(/css/images/train/l-up.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-a { background-image:url(/css/images/train/l-upa.jpg); } +.selected_sleep-a { background-image:url(/css/images/train/l-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-b {background-image:url(/css/images/train/r-up.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-b { background-image:url(/css/images/train/r-upa.jpg); } +.selected_sleep-b { background-image:url(/css/images/train/r-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-c {background-image:url(/css/images/train/l-mid.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-c { background-image:url(/css/images/train/l-mida.jpg); } +.selected_sleep-c { background-image:url(/css/images/train/l-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-d {background-image:url(/css/images/train/r-mid.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-d { background-image:url(/css/images/train/r-mida.jpg); } +.selected_sleep-d { background-image:url(/css/images/train/r-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-e {background-image:url(/css/images/train/l-low.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-e { background-image:url(/css/images/train/l-lowa.jpg); } +.selected_sleep-e { background-image:url(/css/images/train/l-lowa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-f {background-image:url(/css/images/train/r-low.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-f { background-image:url(/css/images/train/r-lowa.jpg); } +.selected_sleep-f { background-image:url(/css/images/train/r-lowa.jpg)!important; width:104px; display:block; height:38px; float:left; } +</style> +<script> +$(function(){ + //var selected = $('.selectticket').find('.selected').length; + //$('.selected_People').html(selected); +}); + +function selseat(seat){ + var type = $(seat).attr('type'); + var total = $(seat).parent().parent().find('.train-summary .seat_TotalPeople').html(); + if(total>=5){ + total = 5; + $('.seat_TotalPeople').html(total); + } + var count = $(seat).parent().parent().find('.selected').length; + console.log('执行之前的数量'+count); + //处理选座事件 + + if($(seat).hasClass('selected_'+type)){ + $(seat).removeClass('selected'); + $(seat).removeClass('selected_'+type); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('减掉之后'+count); + }else{ + if(count >= total){ + alert('You already chose seats for all the passengers.'); + }else{ + $(seat).addClass('selected_'+type); + $(seat).addClass('selected'); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('增加之后'+count); + } + + } + +} +</script> +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/ht_order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('/apps/trainsystem/pages/order_list');?>">携程订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/trainsystem/pages/order_list');?>">抢票订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/export');?>">导出交易记录>></a> <span style="margin-left:200px;">版本:V2.0</span><span class="pull-right">聚合余额(RMB):<?php echo $balance;?></span></h3> + </div> + <div class="panel-body"> + <form style="width: 300px;float: left;" action="" method="post"> + <input type="text" name="ht_order" value="<?php echo isset($cols_id)?$cols_id:""; ?>"> + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 获取信息</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;">外联:<span><?php if(!empty($wl)){echo $wl[0]->OPI_Name;}?></span></p> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">火车订单信息</h3> + </div> + <div class="panel-body"> + <?php if(!empty($info)):?> + <?php $num=1; foreach($info as $v):?> + <table class="table table-bordered table-hover" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">座位</th> + <th style="text-align:center;">出发城市</th> + <th style="text-align:center;">抵达城市</th> + <th style="text-align:center;">发车日期</th> + <th style="text-align:center;">发车时间</th> + <th style="text-align:center;">抵达时间</th> + <th style="text-align:center;">票价</th> + <th style="text-align:center;">是否提交过</th> + <th style="text-align:center;">操作</th> + </tr> + </thead> + <tbody> + + <tr> + <td><?php echo $num++;?></td> + <td><?php echo $v->train[0]->FlightsNo;?></td> + <td><?php echo $v->train[0]->Cabin;?></td> + <td><?php echo $v->train[0]->DepartureCity;?></td> + <td><?php echo $v->train[0]->ArrivalCity;?></td> + <td><?php echo $v->train[0]->DepartureDate;?></td> + <td><?php echo $v->train[0]->DepartureTime;?></td> + <td><?php echo $v->train[0]->ArrivalTime;?></td> + <td><?php echo $v->train[0]->adultcost;?></td> + <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> + <td><button type="button" class="btn btn-success pay_api" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>" title="超过五个乘客不可用" >快捷订票</button></td> + </tr> + <tr> + <td colspan="11"> + <table class="table table-condensed table-bordered"> + <thead> + <tr> + <th style="text-align:center;"><input class="check_people" type="checkbox" /></th> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">姓名</th> + <th style="text-align:center;">护照</th> + <th style="text-align:center;">年龄类型</th> + </tr> + </thead> + <tbody> + <?php foreach($v->people as $key=>$p): ?> + <tr> + <td><input name="" type="checkbox" value="<?php echo $p->BPE_SN;?>" /></td> + <td><?php echo $key+1;?></td> + <td class="people_name"><?php echo $p->BPE_FirstName." ".$p->BPE_MiddleName." ".$p->BPE_LastName;?></td> + <td><?php echo $p->BPE_Passport;?></td> + <td><?php echo $p->BPE_GuestType==1?"成人":($p->BPE_GuestType==2?"儿童":"婴儿");?></td> + </tr> + <?php endforeach;?> + <tr style="text-align:;"> + <td colspan="11" class="selectticket"> + <?php + $traintype = substr($v->train[0]->FlightsNo,0,1); + $arr = array('C','D','G'); + $sel_count = 0; + if(in_array($traintype,$arr)){ + $selectseat = ''; + $train_select = $v->train[0]->FOI_SelectedSeat; + $a1=$b1=$c1=$d1=$f1=$a2=$b2=$c2=$d2=$f2=false; + if($train_select){ + $obj = explode(',',$train_select); + foreach($obj as $value){ + switch($value){ + case '1A': + $a1 = true; + $sel_count++; + break; + case '1B': + $b1 = true; + $sel_count++; + break; + case '1C': + $c1 = true; + $sel_count++; + break; + case '1D': + $d1 = true; + $sel_count++; + break; + case '1F': + $f1 = true; + $sel_count++; + break; + case '2A': + $a2 = true; + $sel_count++; + break; + case '2B': + $b2 = true; + $sel_count++; + break; + case '2C': + $c2 = true; + $sel_count++; + break; + case '2D': + $d2 = true; + $sel_count++; + break; + case '2F': + $f2 = true; + $sel_count++; + break; + } + } + } + $html = ''; + $html .= '<div class="train-summary">'.$v->train[0]->Cabin.' for '.$v->train[0]->FlightsNo.' <span>(<span class="selected_People">'.$sel_count.'</span> of <span class="seat_TotalPeople">'.count($v->people).'</span> Seats)</span></div>'; + $html .= '<div class="seatPick">'; + if($a1){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b1){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + } + + } + if($c1){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d1){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + } + + } + if($f1){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + $html .= '<div class="seatPick">'; + if($a2){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b2){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + } + + } + if($c2){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d2){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + } + + } + if($f2){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + + if($v->train[0]->Aircraft != 'F'){ + echo $html; + } + } + ?> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success checked_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">聚合订票</button> + </td> + <td colspan="4" class="biaoqian"><span class="back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success ctrip_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">携程订票</button> + </td> + <td colspan="4" class="biaoqian"><span class="ctrip_back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success grab_ticket" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">抢票</button> + </td> + <td colspan="4"> + <span class="grab_config"><a style="text-decoration:none;cursor:pointer;">点击打开配置清单</a></span> + <p class="grab_mes" style="color:red;line-height: 30px;"></p> + <table class="table table-condensed table-bordered grab_config_table hidden"> + <tbody> + <tr> + <td colspan="2"><span style="float:left">截止时间 : <input type="text" name="deadline" class="date"/> 示例:2018-03-22 17:00:00(必填)</span></td> + <td colspan="2"><span style="float:left">备选车次 : <input type="text" name="alternate_train"/> 示例:["k10","G10"]</span></td> + <td colspan="2"><span style="float:left">备选座位 : <input type="text" name="alternate_seat"/> 示例:["1","2"]</span></td> + </tr> + </tbody> + </table> + </td> + + </tr> + <tr id="back_<?php echo $v->train[0]->FOI_COLD_SN;?>" style="display:none;"> + <td colspan="5"> + 快捷订票处理结果:<span style="color:red;"></span> + </td> + </tr> + + </tbody> + </table> + </td> + </tr> + </tbody> + </table> + <?php endforeach;endif;?> + </div> + </div> +</div> + +<script> + var url="<?php echo site_url('apps/train/index/submit_juhe_order?').'order=';?>"; + var order_ul="<?php echo site_url('apps/train/index/order?').'order=';?>";//订单详情页面 + + $(".pay_api").click(function(){ + // alert(url+$(this).attr("data-order")); + var THIS=$(this); + var order=$(this).attr("data-order"); + var selectseat = ''; + $(this).parent().parent().next().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + $.ajax({ + url:url+$(this).attr("data-order")+'&selectseat='+selectseat, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("快捷订票"); + if(data.status==1){ + THIS.parent().html("<a href='"+order_ul+data.order+"' target='_blank'>订单详情</a>"); + } + + $("#back_"+order+" span").html(data.mes); + $("#back_"+order).show(); + + }, + dataType: "json", + + }); + return false; + }); + + $(".check_people").click(function(){ + if($(this).is(":checked")){ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").attr("checked","checked"); + }else{ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").removeAttr("checked"); + } + }); + + //聚合出票 + $(".checked_pay").click(function(){ + var url2="<?php echo site_url('apps/train/index/get_sn_submit_juhe?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + var selectseat = ''; + $(this).parent().parent().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + + people_sn=people_sn.substring(1); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("订票"); + + THIS.parent().parent().find(".back_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); + + //携程出票 + $(".ctrip_pay").click(function(){ + var ctrip_url="<?php echo site_url('apps/train/ctrip_train/addorders?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + var selectseat = ''; + $(this).parent().parent().prev().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data')+','; + } + }); + selectseat=selectseat.substr(0,selectseat.length-1); + people_sn=people_sn.substring(1); + ctrip_url+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat; + + var THIS=$(this); + THIS.parent().parent().find(".ctrip_back_mes").html(" ");//清空提示 + $.ajax({ + url:ctrip_url, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("携程订票"); + + THIS.parent().parent().find(".ctrip_back_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); + + //抢票清单 + $('.grab_config').click(function(){ + var table = $(this).next().next('.grab_config_table'); + if(table.hasClass('hidden')){ + table.removeClass('hidden'); + }else{ + table.addClass('hidden'); + } + }); + + //开始抢票 + $('.grab_ticket').click(function(){ + var url2="<?php echo site_url('apps/train/tuniu_train/grabTicketBook?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + people_sn=people_sn.substring(1); + // var coli_id = $('input[name="ht_order"]').val(); + var deadline = $(this).parent().next().find('.date').val(); + var alternate_train = $('input[name="alternate_train"]').val(); + var alternate_seat = $('input[name="alternate_seat"]').val(); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&deadline="+deadline+"&alternate_train="+alternate_train+"&alternate_seat="+alternate_seat; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("抢票"); + THIS.parent().next().find(".grab_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); +</script> \ No newline at end of file diff --git a/application/third_party/train/views/order.php b/application/third_party/train/views/order.php index f3bf123a..db5f008c 100644 --- a/application/third_party/train/views/order.php +++ b/application/third_party/train/views/order.php @@ -1,3 +1,4 @@ +<script type="text/javascript" src="https://data.chinahighlights.com/js/train/StationInfo.js"></script> <div style="width:90%;margin:30px auto;"> <div class="panel panel-primary" style="width:60%;margin:0 auto;"> <div class="panel-heading"> @@ -5,7 +6,7 @@ </div> <div class="panel-body"> <?php if((int)$result["status"]>1):?> - <p><?php echo $result["from_station_name"];?><span class="glyphicon glyphicon-arrow-right"></span><?php echo $result["to_station_name"];?></p> + <p style="display:inline-block"><?php echo $result["from_station_name"];?><span class="from_station_en"> </span><br><span class="start_time"></span></p><span class="glyphicon glyphicon-arrow-right"> </span><p style="display:inline-block"> <?php echo $result["to_station_name"];?><span class="to_station_en"> </span><br><span class="arrive_time"></span></p> <?php foreach ($result["passengers"] as $v):?> <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> <p><?php echo @$v["passengersename"]."({$v['piaotypename']})&nbsp;&nbsp;&nbsp;&nbsp;{$v['zwname']}&nbsp;&nbsp;{$v['cxin']}&nbsp;&nbsp;&nbsp;&nbsp;票价:¥{$v['price']}";?></p> @@ -46,6 +47,29 @@ <?php endif;?> </div> </div> -</div> +</div> +<script> +var StationInfoArr = StationInfo.split("@"); +var StationNameArr = new Array(); +var code_name = new Array(); +var station_cn_en = new Array(); +var form_data = {}; +for (var i = 0; i < StationInfoArr.length; ++i) { + StationNameArr.push(StationInfoArr[i].split("|")); + code_name[StationNameArr[i][1]] = [StationNameArr[i][2]]; + station_cn_en[StationNameArr[i][3]] = StationNameArr[i][2]; +} +$(function(){ + var from_station_en = code_name['<?php echo $result['from_station_code']?>']; + var to_station_en = code_name['<?php echo $result['to_station_code']?>']; + var start_time = '<?php echo $result['start_time']?>'; + var arrive_time = '<?php echo $result['arrive_time']?>'; + //console.log(code_name); + $('.from_station_en').html('('+from_station_en+') '); + $('.to_station_en').html('('+to_station_en+')'); + $('.start_time').html('('+start_time.substring(0,start_time.length-3)+')'); + $('.arrive_time').html('('+arrive_time.substring(0,arrive_time.length-3)+')'); +}); +</script> diff --git a/application/third_party/train/views/train_help.php b/application/third_party/train/views/train_help.php new file mode 100644 index 00000000..88ad5cf6 --- /dev/null +++ b/application/third_party/train/views/train_help.php @@ -0,0 +1,2 @@ +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title></head><body><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Dear <?php echo $name?>,</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Thank you for your interest in China Highlights.</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Your account has been created with your phone number : <?php echo $phone?></p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">If you have any questions, please don't hesitate to contact us : <a href="https://www.chinahighlights.com/contactus/">https://www.chinahighlights.com/contactus/</a></p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">Thanks,</p><p style="font-family:Verdana, Geneva, sans-serif; font-size:14px; line-height:24px; margin-bottom:12px;">The China Highlights Team</p> +</body></html> \ No newline at end of file diff --git a/application/third_party/train/views/train_transaction_excel.php b/application/third_party/train/views/train_transaction_excel.php new file mode 100644 index 00000000..fd45ab3b --- /dev/null +++ b/application/third_party/train/views/train_transaction_excel.php @@ -0,0 +1,178 @@ +<?xml version="1.0" encoding="utf-8"?> +<?mso-application progid="Excel.Sheet"?> +<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:o="urn:schemas-microsoft-com:office:office" + xmlns:x="urn:schemas-microsoft-com:office:excel" + xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:html="http://www.w3.org/TR/REC-html40"> + <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> + <Author>c21</Author> + <LastAuthor>c21</LastAuthor> + <Created>2016-12-23T01:21:46Z</Created> + <LastSaved>2016-12-23T01:38:10Z</LastSaved> + <Version>12.00</Version> + </DocumentProperties> + <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> + <WindowHeight>9630</WindowHeight> + <WindowWidth>21555</WindowWidth> + <WindowTopX>0</WindowTopX> + <WindowTopY>90</WindowTopY> + <ProtectStructure>False</ProtectStructure> + <ProtectWindows>False</ProtectWindows> + </ExcelWorkbook> + <Styles> + <Style ss:ID="Default" ss:Name="Normal"> + <Alignment ss:Vertical="Center"/> + <Borders/> + <Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/> + <Interior/> + <NumberFormat/> + <Protection/> + </Style> + <Style ss:ID="m58993952"> + <Alignment ss:Horizontal="Right" ss:Vertical="Center" ss:WrapText="1"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="m58993972"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="20" + ss:Color="#000000" ss:Bold="1"/> + </Style> + <Style ss:ID="m58993992"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="s78"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + </Style> + <Style ss:ID="s79"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + <NumberFormat ss:Format="General Date"/> + </Style> + </Styles> + <Worksheet ss:Name="Sheet1"> + <?php $num=count($arr);?> + <Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="<?php echo $num+6;?>" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Column ss:AutoFitWidth="0" ss:Width="115.5"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="100.5"/> + <Column ss:AutoFitWidth="0" ss:Width="62.25"/> + <Column ss:AutoFitWidth="0" ss:Width="203.25"/> + <Row ss:AutoFitHeight="0"> + <Cell ss:MergeAcross="5" ss:MergeDown="1" ss:StyleID="m58993952"><Data + ss:Type="String">苏州新科兰德科技有限公司&#10;地址:苏州市园区启月街288号紫金东方307室&#10;联系电话:051262391880&#10;开户银行:浙商银行苏州分行&#10;公司名称:苏州新科兰德科技有限公司&#10;银行账号:3050020010120100129207&#10;跟踪号:<?php echo $arr[0]['trackcode'];?></Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="99.75"/> + <Row ss:AutoFitHeight="0" ss:Height="42"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993972"><Data ss:Type="String">桂林海纳国际旅行社有限公司火车票对账文件</Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s78"><Data ss:Type="String">时间</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">信息</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">购票人</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">团名</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">变化值</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">最新余额</Data></Cell> + </Row> + <?php for($i=$num-1;$i>=0;$i--){?> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s79"><Data ss:Type="String"><?php echo $arr[$i][2];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][3];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][7];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][6];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="Number"><?php echo $arr[$i][1];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="Number"><?php echo $arr[$i][5];?></Data></Cell> + </Row> + <?php }?> + <Row ss:AutoFitHeight="0" ss:Height="36"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993992"><Data ss:Type="String">苏州新科兰德科技有限公司©版权所有 苏ICP备14006450号-3 增值电信业务经营许可证:苏B2-20140496</Data></Cell> + </Row> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <Selected/> + <Panes> + <Pane> + <Number>3</Number> + <ActiveRow>4</ActiveRow> + <ActiveCol>4</ActiveCol> + </Pane> + </Panes> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet2"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet3"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> +</Workbook> diff --git a/application/third_party/train/views/tuniu/grabTicketBook.php b/application/third_party/train/views/tuniu/grabTicketBook.php new file mode 100644 index 00000000..0d04332a --- /dev/null +++ b/application/third_party/train/views/tuniu/grabTicketBook.php @@ -0,0 +1,137 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/tuniu_train/ht_order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/export');?>">导出交易记录>></a> <span style="margin-left:200px;">途牛抢票测试版</span></h3> + </div> + <div class="panel-body"> + <form style="width: 300px;float: left;" action="" method="post"> + <input type="text" name="ht_order" value="<?php echo isset($cols_id)?$cols_id:""; ?>"> + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 获取信息</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;">外联:<span><?php if(!empty($wl)){echo $wl[0]->OPI_Name;}?></span></p> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">火车订单信息</h3> + </div> + <div class="panel-body"> + <?php if(!empty($info)):?> + <?php $num=1; foreach($info as $v):?> + <table class="table table-bordered table-hover" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">座位</th> + <th style="text-align:center;">出发城市</th> + <th style="text-align:center;">抵达城市</th> + <th style="text-align:center;">发车日期</th> + <th style="text-align:center;">发车时间</th> + <th style="text-align:center;">抵达时间</th> + <th style="text-align:center;">票价</th> + <th style="text-align:center;">是否提交过</th> + </tr> + </thead> + <tbody> + + <tr> + <td><?php echo $num++;?></td> + <td><?php echo $v->train[0]->FlightsNo;?></td> + <td><?php echo $v->train[0]->Cabin;?></td> + <td><?php echo $v->train[0]->DepartureCity;?></td> + <td><?php echo $v->train[0]->ArrivalCity;?></td> + <td><?php echo $v->train[0]->DepartureDate;?></td> + <td><?php echo $v->train[0]->DepartureTime;?></td> + <td><?php echo $v->train[0]->ArrivalTime;?></td> + <td><?php echo $v->train[0]->adultcost;?></td> + <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> + </tr> + <tr> + <td colspan="11"> + <table class="table table-condensed table-bordered"> + <thead> + <tr> + <th style="text-align:center;"><input class="check_people" type="checkbox" /></th> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">姓名</th> + <th style="text-align:center;">护照</th> + <th style="text-align:center;">年龄类型</th> + </tr> + </thead> + <tbody> + <?php foreach($v->people as $key=>$p): ?> + <tr> + <td><input name="" type="checkbox" value="<?php echo $p->BPE_SN;?>" /></td> + <td><?php echo $key+1;?></td> + <td class="people_name"><?php echo $p->BPE_FirstName." ".$p->BPE_MiddleName." ".$p->BPE_LastName;?></td> + <td><?php echo $p->BPE_Passport;?></td> + <td><?php echo $p->BPE_GuestType==1?"成人":($p->BPE_GuestType==2?"儿童":"婴儿");?></td> + </tr> + <?php endforeach;?> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success checked_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">抢票</button> + </td> + <td colspan="4" class="biaoqian"><span class="back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr id="back_<?php echo $v->train[0]->FOI_COLD_SN;?>" style="display:none;"> + <td colspan="5"> + 快捷订票处理结果:<span style="color:red;"></span> + </td> + </tr> + </tbody> + </table> + + </td> + </tr> + + + </tbody> + </table> + <?php endforeach;endif;?> + </div> + </div> +</div> + +<script> + $(".check_people").click(function(){ + if($(this).is(":checked")){ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").attr("checked","checked"); + }else{ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").removeAttr("checked"); + } + }); + $(".checked_pay").click(function(){ + var url2="<?php echo site_url('apps/train/tuniu_train/grabTicketBook?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + people_sn=people_sn.substring(1); + var coli_id = $('input[name="ht_order"]').val(); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&coli_id="+coli_id; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + //THIS.html("处理中..."); + //THIS.attr("disabled","disabled") + }, + success:function(data){ + //THIS.removeAttr("disabled"); + //THIS.html("订票"); + //THIS.parent().parent().find(".back_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); +</script> \ No newline at end of file diff --git a/application/third_party/train/views/tuniu/ht_order_list.html b/application/third_party/train/views/tuniu/ht_order_list.html new file mode 100644 index 00000000..2f1508f9 --- /dev/null +++ b/application/third_party/train/views/tuniu/ht_order_list.html @@ -0,0 +1,82 @@ +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">订单搜索</h3> + </div> + <div class="panel-body"> + <div class="row"> + <form style="" action="" method="get"> + <div class="col-md-6"> + <input class="form-control" type="text" placeholder="汉特订单号或聚合订单号" name="order" value="<?php echo !empty($order)?"$order":"";?>"> + </div> + <div class="col-md-5"> + <button type="submit" id="sub" class="btn btn-success btn-sm"><span class="glyphicon glyphicon-search"></span> 搜索</button> + </div> + </form> + </div> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">订单列表</h3> + </div> + <div class="panel-body"> + <table class="table table-striped" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">汉特订单号</th> + <th style="text-align:center;">途牛订单号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">出发</th> + <th style="text-align:center;">到达</th> + <th style="text-align:center;">状态</th> + <th style="text-align:center;">价格</th> + <th style="text-align:center;">提交时间</th> + <th style="text-align:center;">所属部门</th> + <!--<th style="text-align:center;">自动出票</th> + <th style="text-align:center;">是否发送邮件</th> + <th style="text-align:center;">操作</th>--> + </tr> + </thead> + <tbody> + <?php $num=0; foreach($data as $v):?> + <tr> + <td><?php echo ++$num;?></td> + <td><?php echo $v->COLI_ID;?></td> + <td><?php echo $v->tol_orderId;?></td> + <td><?php echo $v->tol_cheCi;?></td> + <td><?php echo $v->tol_fromStationName;?></td> + <td><?php echo $v->tol_toStationName;?></td> + <td><?php echo $v->info;?></td> + <td><?php echo $v->tol_orderAmount;?></td> + <td><?php echo $v->tol_subtime;?></td> + <td><?php echo $v->COLI_WebCode;?></td> + + <?php + if($v->tol_isauto){ + echo '<td>是</td>'; + }else{ + echo '<td>否</td>'; + } + ?> + <?php + if($v->tol_sendmail == 1){ + if($v->JOL_M_SN){ + echo '<td><a target="_blank" href="http://www.mycht.cn/info.php/apps/train/index/get_mailinfo/'.$v->JOL_M_SN.'">是</a></td>'; + }else{ + echo '<td>是</td>'; + } + }else{ + echo '<td>否</td>'; + } + ?> + <td><a target="_blank" href="order?retailOrderId=<?php echo $v->tol_retailOrderId;?>&orderId=<?php echo $v->tol_orderId;?>">详情</a></td> + </tr> + <?php endforeach;?> + </tbody> + </table> + <div style="text-align:right;"><ul class="pagination"><?php echo $page_link;?></ul></div> + </div> + </div> +</div> \ No newline at end of file diff --git a/application/third_party/train/views/tuniu/ht_train_order_info.php b/application/third_party/train/views/tuniu/ht_train_order_info.php new file mode 100644 index 00000000..961aa8bf --- /dev/null +++ b/application/third_party/train/views/tuniu/ht_train_order_info.php @@ -0,0 +1,392 @@ +<style> +.clear {clear: both;} +.train-summary{ font-size:12px; margin-bottom:10px;} +.train-summary span{ color:#9a0918;} +a:link.seat-a{background-image:url(/css/images/train/a-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-a{background-image:url(/css/images/train/a-seath.jpg);} +.selected_seat-a{background-image:url(/css/images/train/a-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-b{background-image:url(/css/images/train/b-seat.jpg); background-repeat:no-repeat; text-decoration:none; width:55px; display:block; height:42px; float:left;} +a:hover.seat-b{background-image:url(/css/images/train/b-seath.jpg);} +.selected_seat-b{background-image:url(/css/images/train/b-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-c{background-image:url(/css/images/train/c-seat.jpg); background-repeat:no-repeat; width:131px; display:block; height:42px; float:left;} +a:hover.seat-c{background-image:url(/css/images/train/c-seath.jpg);} +.selected_seat-c{background-image:url(/css/images/train/c-seata.jpg)!important; background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:link.seat-d{background-image:url(/css/images/train/d-seat.jpg); background-repeat:no-repeat; width:55px; display:block; height:42px; float:left;} +a:hover.seat-d{background-image:url(/css/images/train/d-seath.jpg);} +.selected_seat-d{background-image:url(/css/images/train/d-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.seat-f{background-image:url(/css/images/train/f-seat.jpg); background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:hover.seat-f{background-image:url(/css/images/train/f-seath.jpg);} +.selected_seat-f{background-image:url(/css/images/train/f-seata.jpg)!important; background-repeat:no-repeat; width:136px; display:block; height:42px; float:left;} +a:link.sleep-a {background-image:url(/css/images/train/l-up.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-a { background-image:url(/css/images/train/l-upa.jpg); } +.selected_sleep-a { background-image:url(/css/images/train/l-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-b {background-image:url(/css/images/train/r-up.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-b { background-image:url(/css/images/train/r-upa.jpg); } +.selected_sleep-b { background-image:url(/css/images/train/r-upa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-c {background-image:url(/css/images/train/l-mid.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-c { background-image:url(/css/images/train/l-mida.jpg); } +.selected_sleep-c { background-image:url(/css/images/train/l-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-d {background-image:url(/css/images/train/r-mid.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-d { background-image:url(/css/images/train/r-mida.jpg); } +.selected_sleep-d { background-image:url(/css/images/train/r-mida.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-e {background-image:url(/css/images/train/l-low.jpg); background-repeat:no-repeat; width:163px; display:block; height:38px; float:left; } +a:hover.sleep-e { background-image:url(/css/images/train/l-lowa.jpg); } +.selected_sleep-e { background-image:url(/css/images/train/l-lowa.jpg)!important; width:163px; display:block; height:38px; float:left; } +a:link.sleep-f {background-image:url(/css/images/train/r-low.jpg); background-repeat:no-repeat; width:104px; display:block; height:38px; float:left; } +a:hover.sleep-f { background-image:url(/css/images/train/r-lowa.jpg); } +.selected_sleep-f { background-image:url(/css/images/train/r-lowa.jpg)!important; width:104px; display:block; height:38px; float:left; } +</style> +<script> +$(function(){ + //var selected = $('.selectticket').find('.selected').length; + //$('.selected_People').html(selected); +}); + +function selseat(seat){ + var type = $(seat).attr('type'); + var total = $(seat).parent().parent().find('.train-summary .seat_TotalPeople').html(); + if(total>=5){ + total = 5; + $('.seat_TotalPeople').html(total); + } + var count = $(seat).parent().parent().find('.selected').length; + console.log('执行之前的数量'+count); + //处理选座事件 + + if($(seat).hasClass('selected_'+type)){ + $(seat).removeClass('selected'); + $(seat).removeClass('selected_'+type); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('减掉之后'+count); + }else{ + if(count >= total){ + alert('You already chose seats for all the passengers.'); + }else{ + $(seat).addClass('selected_'+type); + $(seat).addClass('selected'); + count = $(seat).parent().parent().find('.selected').length; + $('.selected_People').html(count); + console.log('增加之后'+count); + } + + } + +} +</script> +<div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/tuniu_train/ht_order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/train/index/export');?>">导出交易记录>></a> <span style="margin-left:200px;">途牛出票测试版</span></h3> + </div> + <div class="panel-body"> + <form style="width: 300px;float: left;" action="" method="post"> + <input type="text" name="ht_order" value="<?php echo isset($cols_id)?$cols_id:""; ?>"> + <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 获取信息</button> + </form> + <p style="margin: 0 0 10px; width: 200px; float: left; line-height: 30px;">外联:<span><?php if(!empty($wl)){echo $wl[0]->OPI_Name;}?></span></p> + </div> + </div> + <div class="panel panel-primary"> + <div class="panel-heading"> + <h3 class="panel-title">火车订单信息</h3> + </div> + <div class="panel-body"> + <?php if(!empty($info)):?> + <?php $num=1; foreach($info as $v):?> + <table class="table table-bordered table-hover" style="text-align:center;"> + <thead> + <tr> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">车次</th> + <th style="text-align:center;">座位</th> + <th style="text-align:center;">出发城市</th> + <th style="text-align:center;">抵达城市</th> + <th style="text-align:center;">发车日期</th> + <th style="text-align:center;">发车时间</th> + <th style="text-align:center;">抵达时间</th> + <th style="text-align:center;">票价</th> + <th style="text-align:center;">是否提交过</th> + <th style="text-align:center;">操作</th> + </tr> + </thead> + <tbody> + + <tr> + <td><?php echo $num++;?></td> + <td><?php echo $v->train[0]->FlightsNo;?></td> + <td><?php echo $v->train[0]->Cabin;?></td> + <td><?php echo $v->train[0]->DepartureCity;?></td> + <td><?php echo $v->train[0]->ArrivalCity;?></td> + <td><?php echo $v->train[0]->DepartureDate;?></td> + <td><?php echo $v->train[0]->DepartureTime;?></td> + <td><?php echo $v->train[0]->ArrivalTime;?></td> + <td><?php echo $v->train[0]->adultcost;?></td> + <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> + <td><button type="button" class="btn btn-success pay_api" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>" title="超过五个乘客不可用" >快捷订票</button></td> + </tr> + <tr> + <td colspan="11"> + <table class="table table-condensed table-bordered"> + <thead> + <tr> + <th style="text-align:center;"><input class="check_people" type="checkbox" /></th> + <th style="text-align:center;">序号</th> + <th style="text-align:center;">姓名</th> + <th style="text-align:center;">护照</th> + <th style="text-align:center;">年龄类型</th> + </tr> + </thead> + <tbody> + <?php foreach($v->people as $key=>$p): ?> + <tr> + <td><input name="" type="checkbox" value="<?php echo $p->BPE_SN;?>" /></td> + <td><?php echo $key+1;?></td> + <td class="people_name"><?php echo $p->BPE_FirstName." ".$p->BPE_MiddleName." ".$p->BPE_LastName;?></td> + <td><?php echo $p->BPE_Passport;?></td> + <td><?php echo $p->BPE_GuestType==1?"成人":($p->BPE_GuestType==2?"儿童":"婴儿");?></td> + </tr> + <?php endforeach;?> + <tr style="text-align:;"> + <td colspan="11" class="selectticket"> + <?php + $traintype = substr($v->train[0]->FlightsNo,0,1); + $arr = array('C','D','G'); + $sel_count = 0; + if(in_array($traintype,$arr)){ + $selectseat = ''; + $train_select = $v->train[0]->FOI_SelectedSeat; + $a1=$b1=$c1=$d1=$f1=$a2=$b2=$c2=$d2=$f2=false; + if($train_select){ + $obj = explode(',',$train_select); + foreach($obj as $value){ + switch($value){ + case '1A': + $a1 = true; + $sel_count++; + break; + case '1B': + $b1 = true; + $sel_count++; + break; + case '1C': + $c1 = true; + $sel_count++; + break; + case '1D': + $d1 = true; + $sel_count++; + break; + case '1F': + $f1 = true; + $sel_count++; + break; + case '2A': + $a2 = true; + $sel_count++; + break; + case '2B': + $b2 = true; + $sel_count++; + break; + case '2C': + $c2 = true; + $sel_count++; + break; + case '2D': + $d2 = true; + $sel_count++; + break; + case '2F': + $f2 = true; + $sel_count++; + break; + } + } + } + $html = ''; + $html .= '<div class="train-summary">'.$v->train[0]->Cabin.' for '.$v->train[0]->FlightsNo.' <span>(<span class="selected_People">'.$sel_count.'</span> of <span class="seat_TotalPeople">'.count($v->people).'</span> Seats)</span></div>'; + $html .= '<div class="seatPick">'; + if($a1){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="1A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b1){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="1B" onclick ="selseat(this);"></a>'; + } + + } + if($c1){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="1C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d1){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="1D" onclick ="selseat(this);"></a>'; + } + + } + if($f1){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="1F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + $html .= '<div class="seatPick">'; + if($a2){ + $html .= '<a class="seat-a selected_seat-a selected" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + }else{ + $html .= '<a class="seat-a" type="seat-a" href="javascript:void(0);" data="2A" onclick ="selseat(this)";></a>'; + } + + if($v->train[0]->Aircraft == 'O' || $v->train[0]->Aircraft == '8'){ + if($b2){ + $html .= '<a class="seat-b selected_seat-b selected" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-b" type="seat-b" href="javascript:void(0);" data="2B" onclick ="selseat(this);"></a>'; + } + + } + if($c2){ + $html .= '<a class="seat-c selected_seat-c selected" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-c" type="seat-c" href="javascript:void(0);" data="2C" onclick ="selseat(this);"></a>'; + } + + if($v->train[0]->Aircraft != '9'){ + if($d2){ + $html .= '<a class="seat-d selected_seat-d selected" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-d" type="seat-d" href="javascript:void(0);" data="2D" onclick ="selseat(this);"></a>'; + } + + } + if($f2){ + $html .= '<a class="seat-f selected_seat-f selected" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + }else{ + $html .= '<a class="seat-f" type="seat-f" href="javascript:void(0);" data="2F" onclick ="selseat(this);"></a>'; + } + + $html .= '<div class="clear"></div></div>'; + + if($v->train[0]->Aircraft != 'F'){ + echo $html; + } + } + ?> + </td> + </tr> + <tr style="text-align:;"> + <td> + <button type="button" class="btn btn-success checked_pay" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>">订票</button> + </td> + <td colspan="4" class="biaoqian"><span class="back_mes" style="color:red;line-height: 30px;"></span> + </td> + </tr> + <tr id="back_<?php echo $v->train[0]->FOI_COLD_SN;?>" style="display:none;"> + <td colspan="5"> + 快捷订票处理结果:<span style="color:red;"></span> + </td> + </tr> + </tbody> + </table> + + </td> + </tr> + + + </tbody> + </table> + <?php endforeach;endif;?> + </div> + </div> +</div> + +<script> + var url="<?php echo site_url('apps/train/index/submit_juhe_order?').'order=';?>"; + var order_ul="<?php echo site_url('apps/train/index/order?').'order=';?>";//订单详情页面 + + $(".pay_api").click(function(){ + // alert(url+$(this).attr("data-order")); + var THIS=$(this); + var order=$(this).attr("data-order"); + $.ajax({ + url:url+$(this).attr("data-order"), + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("快捷订票"); + if(data.status==1){ + THIS.parent().html("<a href='"+order_ul+data.order+"' target='_blank'>订单详情</a>"); + } + + $("#back_"+order+" span").html(data.mes); + $("#back_"+order).show(); + + }, + dataType: "json", + + }); + return false; + }); + + $(".check_people").click(function(){ + if($(this).is(":checked")){ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").attr("checked","checked"); + }else{ + $(this).parent().parent().parent().parent().find("input[type=checkbox]").removeAttr("checked"); + } + }); + $(".checked_pay").click(function(){ + var url2="<?php echo site_url('apps/train/tuniu_train/get_sn_submit_tuniu?').'order=';?>"; + var checkbox=$(this).parent().parent().parent().find(":checked"); + var people_sn=""; + checkbox.each(function(i){ + people_sn+=","+$(this).val(); + }); + + var selectseat = ''; + $(this).parent().parent().prev().find('.selected').each(function(){ + if($(this).hasClass('selected')){ + selectseat += $(this).attr('data'); + } + }); + + people_sn=people_sn.substring(1); + var coli_id = $('input[name="ht_order"]').val(); + url2+=$(this).attr("data-order")+"&people="+people_sn+"&coli_id="+coli_id+'&selectseat='+selectseat; + + var THIS=$(this); + THIS.parent().parent().find(".back_mes").html(" ");//清空提示 + $.ajax({ + url:url2, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled") + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("订票"); + THIS.parent().parent().find(".back_mes").html(data.mes); + + }, + dataType: "json", + + }); + + return false; + }); +</script> \ No newline at end of file diff --git a/application/third_party/train/views/tuniu/order.php b/application/third_party/train/views/tuniu/order.php new file mode 100644 index 00000000..bb7b6229 --- /dev/null +++ b/application/third_party/train/views/tuniu/order.php @@ -0,0 +1,113 @@ +<script type="text/javascript" src="/js/StationInfo.js"></script> +<!-- 调用接口查询订单信息 --> +<div style="width:90%;margin:30px auto;"> +<div class="panel panel-primary" style="width:60%;margin:0 auto;"> + <div class="panel-heading"> + <h3 class="panel-title">订单状态</h3> + </div> + <div class="panel-body"> + <p>途牛订单号:<?php echo $data->orderId?>&nbsp;&nbsp;&nbsp;&nbsp;途牛订单状态:<?php echo $data->orderStatus?></p> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + + </div> + </div> +</div> + +<?php + //调用订单异步返回的信息 + //途牛订单状态接口查询不返回订单详细信息,只能在异步返回中查看,非常蛋疼。 + $info = json_decode($grab_callback); + //print_r($info); + //print_r($data); + if($data->orderStatus == '抢票中'){ ?> + <div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary" style="width:60%;margin:0 auto;"> + <div class="panel-heading"> + <h3 class="panel-title">途牛操作</h3> + </div> + <div class="panel-body"> + <p style="text-align:center;"><a href="#" tuniu_url="/cancelgrabTicket/<?php echo $data->retailOrderId.'/'.$data->orderId?>" style="padding:5px 15px;" class="btn btn-warning btn-sm cancelgrab">取消抢票 <span class="glyphicon glyphicon-forward"></span></a></p> + </div> + </div> + </div> +<?php }else if($data->orderStatus == '出票成功'){ ?> + <div style="width:90%;margin:30px auto;"> + <div class="panel panel-primary" style="width:60%;margin:0 auto;"> + <div class="panel-heading"> + <h3 class="panel-title"><?php echo $info->trainDate;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo $info->cheCi;?>&nbsp;&nbsp;&nbsp;&nbsp;<?php echo isset($info->orderNumber)?$info->orderNumber:"";?></h3> + </div> + <div class="panel-body"> + <p style="display:inline-block"><?php echo $info->fromStationName;?><span class="from_station_en"> </span><br><span class="start_time"></span></p><span class="glyphicon glyphicon-arrow-right"> </span><p style="display:inline-block"> <?php echo $info->toStationName;?><span class="to_station_en"> </span><br><span class="arrive_time"></span></p> + <?php foreach ($info->passengers as $value){ + echo '<p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p>'; + echo '<p>'.$value->passengerName.'('.$value->piaoTypeName.')&nbsp;&nbsp;&nbsp;&nbsp;'.$value->zwName.'&nbsp;&nbsp;&nbsp;'.$value->cxin.'&nbsp;&nbsp;&nbsp;&nbsp;票价:¥'.$value->price.'<a href="#" tuniu_url="/cancel_ticket/'.$info->retailOrderId.'/'.$info->orderId.'/'.$value->ticketNo.'/" style="padding:5px 15px;" class="btn btn-warning btn-sm cancelticket pull-right">单人退票 <span class="glyphicon glyphicon-forward"></span></a></p>'; + }?> + <p style="border-top:1px dashed #000; height:1px;margin-top:10px;" ></p> + <p style="text-align:center;"><a href="#" tuniu_url="/cancel_ticket/<?php echo $info->retailOrderId.'/'.$info->orderId?>" style="padding:5px 15px;" class="btn btn-warning btn-sm cancelticket">一键全退 <span class="glyphicon glyphicon-forward"></span></a></p> + </div> + </div> + </div> +<script> +var StationInfoArr = StationInfo.split("@"); +var StationNameArr = new Array(); +var code_name = new Array(); +var station_cn_en = new Array(); +var form_data = {}; +for (var i = 0; i < StationInfoArr.length; ++i) { + StationNameArr.push(StationInfoArr[i].split("|")); + code_name[StationNameArr[i][1]] = [StationNameArr[i][2]]; + station_cn_en[StationNameArr[i][3]] = StationNameArr[i][2]; +} +$(function(){ + var from_station_en = code_name['<?php echo $info->data->fromStationCode;?>']; + var to_station_en = code_name['<?php echo $info->data->toStationCode;?>']; + var start_time = '<?php echo $info->data->trainDate.' '.$info->data->startTime;?>'; + var arrive_time = '<?php echo $info->data->trainDate.' '.$info->data->arriveTime;?>'; + $('.from_station_en').html('('+from_station_en+') '); + $('.to_station_en').html('('+to_station_en+')'); + $('.start_time').html('('+start_time.substring(0,start_time.length-3)+')'); + $('.arrive_time').html('('+arrive_time.substring(0,arrive_time.length-3)+')'); +}); +</script> +<?php }?> +<script> +$(function(){ + $('.cancelgrab').click(function(){ + var cancel_url = $(this).attr('tuniu_url'); + var url = "<?php echo site_url('apps/train/tuniu_train')?>"+cancel_url; + var THIS=$(this); + $.ajax({ + url:url, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("取消成功"); + }, + dataType: "json", + }); + }); + + $('.cancelticket').click(function(){ + var cancel_url = $(this).attr('tuniu_url'); + var url = "<?php echo site_url('apps/train/tuniu_train')?>"+cancel_url; + var THIS=$(this); + $.ajax({ + url:url, + beforeSend:function(data){ + THIS.html("处理中..."); + THIS.attr("disabled","disabled"); + }, + success:function(data){ + THIS.removeAttr("disabled"); + THIS.html("退票成功"); + }, + dataType: "json", + }); + }); +}); +</script> + + diff --git a/application/third_party/train/views/tuniu/train_transaction_excel.php b/application/third_party/train/views/tuniu/train_transaction_excel.php new file mode 100644 index 00000000..9a35bbca --- /dev/null +++ b/application/third_party/train/views/tuniu/train_transaction_excel.php @@ -0,0 +1,176 @@ +<?xml version="1.0" encoding="utf-8"?> +<?mso-application progid="Excel.Sheet"?> +<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:o="urn:schemas-microsoft-com:office:office" + xmlns:x="urn:schemas-microsoft-com:office:excel" + xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" + xmlns:html="http://www.w3.org/TR/REC-html40"> + <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office"> + <Author>c21</Author> + <LastAuthor>c21</LastAuthor> + <Created>2016-12-23T01:21:46Z</Created> + <LastSaved>2016-12-23T01:38:10Z</LastSaved> + <Version>12.00</Version> + </DocumentProperties> + <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel"> + <WindowHeight>9630</WindowHeight> + <WindowWidth>21555</WindowWidth> + <WindowTopX>0</WindowTopX> + <WindowTopY>90</WindowTopY> + <ProtectStructure>False</ProtectStructure> + <ProtectWindows>False</ProtectWindows> + </ExcelWorkbook> + <Styles> + <Style ss:ID="Default" ss:Name="Normal"> + <Alignment ss:Vertical="Center"/> + <Borders/> + <Font ss:FontName="宋体" x:CharSet="134" ss:Size="11" ss:Color="#000000"/> + <Interior/> + <NumberFormat/> + <Protection/> + </Style> + <Style ss:ID="m58993952"> + <Alignment ss:Horizontal="Right" ss:Vertical="Center" ss:WrapText="1"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="m58993972"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="20" + ss:Color="#000000" ss:Bold="1"/> + </Style> + <Style ss:ID="m58993992"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Size="11" + ss:Color="#000000"/> + </Style> + <Style ss:ID="s78"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + </Style> + <Style ss:ID="s79"> + <Alignment ss:Horizontal="Center" ss:Vertical="Center"/> + <Borders> + <Border ss:Position="Bottom" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Left" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Right" ss:LineStyle="Continuous" ss:Weight="1"/> + <Border ss:Position="Top" ss:LineStyle="Continuous" ss:Weight="1"/> + </Borders> + <Font ss:FontName="微软雅黑" x:CharSet="134" x:Family="Swiss" ss:Color="#000000"/> + <NumberFormat ss:Format="General Date"/> + </Style> + </Styles> + <Worksheet ss:Name="Sheet1"> + <?php $num=count($arr);?> + <Table ss:ExpandedColumnCount="6" ss:ExpandedRowCount="<?php echo $num+6;?>" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Column ss:AutoFitWidth="0" ss:Width="115.5"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="111"/> + <Column ss:AutoFitWidth="0" ss:Width="100.5"/> + <Column ss:AutoFitWidth="0" ss:Width="62.25"/> + <Column ss:AutoFitWidth="0" ss:Width="203.25"/> + <Row ss:AutoFitHeight="0"> + <Cell ss:MergeAcross="5" ss:MergeDown="1" ss:StyleID="m58993952"><Data + ss:Type="String">苏州新科兰德科技有限公司&#10;地址:苏州市园区启月街288号紫金东方307室&#10;联系电话:051262391880&#10;开户银行:浙商银行苏州分行&#10;公司名称:苏州新科兰德科技有限公司&#10;银行账号:3050020010120100129207&#10;跟踪号:<?php echo $arr[0]['trackcode'];?></Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="99.75"/> + <Row ss:AutoFitHeight="0" ss:Height="42"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993972"><Data ss:Type="String">桂林海纳国际旅行社有限公司火车票对账文件</Data></Cell> + </Row> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s78"><Data ss:Type="String">时间</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">信息</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">购票人</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">团名</Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String">变化值</Data></Cell> + </Row> + <?php for($i=$num-1;$i>=0;$i--){?> + <Row ss:AutoFitHeight="0" ss:Height="16.5"> + <Cell ss:StyleID="s79"><Data ss:Type="String"><?php echo $arr[$i][0];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][1];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][5];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="String"><?php echo $arr[$i][4];?></Data></Cell> + <Cell ss:StyleID="s78"><Data ss:Type="Number"><?php echo $arr[$i][3];?></Data></Cell> + </Row> + <?php }?> + <Row ss:AutoFitHeight="0" ss:Height="36"> + <Cell ss:MergeAcross="5" ss:StyleID="m58993992"><Data ss:Type="String">苏州新科兰德科技有限公司©版权所有 苏ICP备14006450号-3 增值电信业务经营许可证:苏B2-20140496</Data></Cell> + </Row> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <Selected/> + <Panes> + <Pane> + <Number>3</Number> + <ActiveRow>4</ActiveRow> + <ActiveCol>4</ActiveCol> + </Pane> + </Panes> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet2"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> + <Worksheet ss:Name="Sheet3"> + <Table ss:ExpandedColumnCount="1" ss:ExpandedRowCount="1" x:FullColumns="1" + x:FullRows="1" ss:DefaultColumnWidth="54" ss:DefaultRowHeight="13.5"> + <Row ss:AutoFitHeight="0"/> + </Table> + <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel"> + <PageSetup> + <Header x:Margin="0.3"/> + <Footer x:Margin="0.3"/> + <PageMargins x:Bottom="0.75" x:Left="0.7" x:Right="0.7" x:Top="0.75"/> + </PageSetup> + <Unsynced/> + <ProtectObjects>False</ProtectObjects> + <ProtectScenarios>False</ProtectScenarios> + </WorksheetOptions> + </Worksheet> +</Workbook> diff --git a/application/third_party/train/随笔.txt b/application/third_party/train/随笔.txt new file mode 100644 index 00000000..da9338f8 --- /dev/null +++ b/application/third_party/train/随笔.txt @@ -0,0 +1,53 @@ +TOC_ID 自增ID +TOC_COLI_SN 商务主表COLI_SN +TOC_GroupName 团名 +TOC_COLD_SN 商务明细表COLD_SN +TOC_TrainNumber 火车车次 +TOC_DepartureDate 出发日期 +TOC_TicketCost 价格 +TOC_OtherCost 其它成本标识 +TOC_NBBZ 是否内部报账标识 +TOC_BCM_Bill 交通银行账单标识 +TOC_WL 外联 +TOC_SFBZ 是否已报账标识 +TOC_Order 排序号 +TOC_Memo 备注 +TOC_PicName 上传图片名称(已不用) +TOC_Creator 创建者 +TOC_CreateDate 创建日期 +TOC_LastEditor 最后修改者 +TOC_LastEditDate 最后修改日期 +TOC_DeleteFlag 删除标识 +TOC_ListOrder 查询排序字段 +TOC_MoveFlag 是否移动标识 +TOC_GetTicket 是否已取票 +TOC_Billing 是否已做账标识 +TOC_BZDate 报账日期 +TOC_NeedTicketFee 是否寄送状态 + + + +https://open-sbox.sf-express.com/rest/v1.0/route/query/access_token/15D008266E5E90964EC3C2F7B98C0A9F/sf_appid/00000111/sf_appkey/B21FA8B875514EBCEFEC7285A33E3000 + + +//令牌 +https://open-sbox.sf-express.com/public/v1.0/security/access_token/sf_appid/00021240/sf_appkey/2458B56F2B5C3E24B9C1AF1823458DDC + + +//查询 +https://open-sbox.sf-express.com/public/v1.1.2/security/access_token/query/sf_appid/00021240/sf_appkey/2458B56F2B5C3E24B9C1AF1823458DDC +{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2016-11-30","orderid":"1476686669783H","user_orderid":"488015272","orderamount":"5.50","ordernumber":"E903359160","checi":"D8238","msg":"有乘客退票成功,相关款项已退还至您的账户","status":"7","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E127233","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E903359160107001A","cxin":"07车厢,01A座","reason":0,"returntickets":{"ticket_no":"E903359160107001A","passengername":"CSK","passporttypeseid":"B","passportseno":"E127233","refund_apply_time":"2016-10-17 14:49:17","returnsuccess":true,"returnmoney":"5.5","returntime":"2016-10-17 14:52:05","returnfailid":"","returnfailmsg":"","returntype":"1"},"refundTimeline":[{"time":"2016-10-17 14:49:17","msg":"线上申请退票"},{"time":"2016-10-17 14:52:05","msg":"线上退票成功","detail":{"returnsuccess":true,"returnmoney":"5.5","returntime":"2016-10-17 14:52:05","returnfailid":"","returnfailmsg":"","returntype":"1","ticket_no":"E903359160107001A","passengername":"CSK","passporttypeseid":"B","passportseno":"E127233"}}]}],"refund_money":"5.50","sign":"49121a3cada0af88b2ce64746dc7b13f"} + +{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2016-11-30","orderid":"1476935104693H","user_orderid":"488015272","orderamount":"8.50","ordernumber":"E974154132","checi":"D8238","msg":"有乘客退票成功,相关款项已退还至您的账户","status":"7","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E127233","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E974154132107001A","cxin":"07车厢,01A座","reason":0,"returntickets":{"ticket_no":"E974154132107001A","passengername":"CSK","passporttypeseid":"B","passportseno":"E127233","refund_apply_time":"2016-10-21 14:51:00","returnsuccess":true,"returnmoney":"5.5","returntime":"2016-10-21 14:52:06","returnfailid":"","returnfailmsg":"","returntype":"1"},"refundTimeline":[{"time":"2016-10-21 14:51:00","msg":"线上申请退票"},{"time":"2016-10-21 14:52:06","msg":"线上退票成功","detail":{"returnsuccess":true,"returnmoney":"5.5","returntime":"2016-10-21 14:52:06","returnfailid":"","returnfailmsg":"","returntype":"1","ticket_no":"E974154132107001A","passengername":"CSK","passporttypeseid":"B","passportseno":"E127233"}}]},{"passengerid":2,"passengersename":"test k","piaotype":"2","piaotypename":"儿童票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E127234","price":"3.0","zwcode":"O","zwname":"二等座","ticket_no":"E974154132107001D","cxin":"07车厢,01D座","reason":0,"returntickets":{"ticket_no":"E974154132107001D","passengername":"test k","passporttypeseid":"B","passportseno":"E127234","refund_apply_time":"2016-10-21 14:51:04"},"refundTimeline":[{"time":"2016-10-21 14:51:04","msg":"线上申请退票"}]}],"refund_money":"5.50","sign":"9671aa6b0bf8378403473d3a6452ac94"} + +$data_post["data"]='{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2016-11-30","orderid":"1476343928878H","user_orderid":"488015272","orderamount":"5.50","ordernumber":"E098614072","checi":"D8888","msg":"出票成功","status":"4","passengers":[{"passengerid":1,"passengersename":"csk","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E11021322","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E098614072107001C","cxin":"07车厢,01C座","reason":0}],"refund_money":null,"sign":"9cd116f3c333a43e396c0acb115adc3f"}' + +1、出票成功 +{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2017-01-22","orderid":"1482737845760H","user_orderid":"488020631","orderamount":"11.00","ordernumber":"E179703891","checi":"D8238","msg":"出票成功","status":"4","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E132124","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014C","cxin":"06车厢,14C座","reason":0},{"passengerid":2,"passengersename":"TW","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E02030609","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014D","cxin":"06车厢,14D座","reason":0}],"refund_money":null,"sign":"a38d8ac11d00f800ae5b5753a693becd"} + +2、CSK退票 +{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2017-01-22","orderid":"1482737845760H","user_orderid":"488020631","orderamount":"11.00","ordernumber":"E179703891","checi":"D8238","msg":"有乘客退票成功,相关款项已退还至您的账户","status":"7","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E132124","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014C","cxin":"06车厢,14C座","reason":0,"returntickets":{"ticket_no":"E179703891106014C","passengername":"CSK","passporttypeseid":"B","passportseno":"E132124","refund_apply_time":"2016-12-26 15:50:11","returnsuccess":true,"returnmoney":"5.5","returntime":"2016-12-26 15:52:06","returnfailid":"","returnfailmsg":"","returntype":"1"},"refundTimeline":[{"time":"2016-12-26 15:50:11","msg":"线上申请退票"},{"time":"2016-12-26 15:52:06","msg":"线上退票成功","detail":{"returnsuccess":true,"returnmoney":"5.5","returntime":"2016-12-26 15:52:06","returnfailid":"","returnfailmsg":"","returntype":"1","ticket_no":"E179703891106014C","passengername":"CSK","passporttypeseid":"B","passportseno":"E132124"}}]},{"passengerid":2,"passengersename":"TW","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E02030609","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014D","cxin":"06车厢,14D座","reason":0}],"refund_money":"5.50","sign":"a38d8ac11d00f800ae5b5753a693becd"} + + + +{"from_station_name":"桂林","from_station_code":"GLZ","to_station_name":"桂林北","to_station_code":"GBZ","train_date":"2017-01-22","orderid":"1482737845760H","user_orderid":"488020631","orderamount":"11.00","ordernumber":"E179703891","checi":"D8238","msg":"有乘客退票成功,相关款项已退还至您的账户","status":"7","passengers":[{"passengerid":1,"passengersename":"CSK","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E132124","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014C","cxin":"06车厢,14C座","reason":0,"returntickets":{"ticket_no":"E179703891106014C","passengername":"CSK","passporttypeseid":"B","passportseno":"E132124","refund_apply_time":"2016-12-26 15:50:11","returnsuccess":true,"returnmoney":"5.5","returntime":"2016-12-26 15:52:06","returnfailid":"","returnfailmsg":"","returntype":"1"},"refundTimeline":[{"time":"2016-12-26 15:50:11","msg":"线上申请退票"},{"time":"2016-12-26 15:52:06","msg":"线上退票成功","detail":{"returnsuccess":true,"returnmoney":"5.5","returntime":"2016-12-26 15:52:06","returnfailid":"","returnfailmsg":"","returntype":"1","ticket_no":"E179703891106014C","passengername":"CSK","passporttypeseid":"B","passportseno":"E132124"}}]},{"passengerid":2,"passengersename":"TW","piaotype":"1","piaotypename":"成人票","passporttypeseid":"B","passporttypeseidname":"护照","passportseno":"E02030609","price":"5.5","zwcode":"O","zwname":"二等座","ticket_no":"E179703891106014D","cxin":"06车厢,14D座","reason":0}],"refund_money":"5.50","sign":"a38d8ac11d00f800ae5b5753a693becd"} From 80dc193869a969145d6c1e863244e16c35cc71f0 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 13:55:11 +0800 Subject: [PATCH 323/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=9B=B4=E6=8D=A2?= =?UTF-8?q?=E5=9C=B0=E5=9D=80=E5=90=8E=E4=BA=A7=E7=94=9F=E7=9A=84=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/trainsystem/models/BIZ_train_model.php | 2 +- webht/third_party/dingmail/views/login.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/application/third_party/trainsystem/models/BIZ_train_model.php b/application/third_party/trainsystem/models/BIZ_train_model.php index 0c4b8fea..dcc64977 100644 --- a/application/third_party/trainsystem/models/BIZ_train_model.php +++ b/application/third_party/trainsystem/models/BIZ_train_model.php @@ -253,7 +253,7 @@ class BIZ_train_model extends CI_Model { //自动获取符合自动出票要求的订单的coli_sn function auto_check_ticket(){ - $sql = "SELECT distinct top 30 COLD_SN ,coli_id,COLD_SPFS,COLI_State + $sql = "SELECT distinct top 50 COLD_SN ,coli_id,COLD_SPFS,COLI_State FROM BIZ_ConfirmLineInfo bcli inner join BIZ_ConfirmLineDetail bcld on COLD_COLI_SN=COLI_SN LEFT JOIN BIZ_GroupAccountInfo bgai diff --git a/webht/third_party/dingmail/views/login.php b/webht/third_party/dingmail/views/login.php index 6c38f003..c3fe090e 100644 --- a/webht/third_party/dingmail/views/login.php +++ b/webht/third_party/dingmail/views/login.php @@ -3,7 +3,7 @@ <head> <meta charset="utf-8"> <title>value系统登录</title> - <link href="http://data.chtcdn.com/bootstrap/css/bootstrap.min.css" rel="stylesheet"> + <link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <link rel="stylesheet" href="/js/poshytip/tip-yellow/tip-yellow.css" type="text/css" /> <link rel="stylesheet" href="/js/modaldialog/css/jquery.modaldialog.css" type="text/css" /> <link rel="stylesheet" href="/js/kindeditor/themes/default/default.css" type="text/css" media="screen" /> From 5b82484514699af455e363de84b1cfd3faa18415 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 13:57:19 +0800 Subject: [PATCH 324/382] =?UTF-8?q?=E6=8F=90=E4=BA=A4=E7=A1=AE=E5=AE=9E?= =?UTF-8?q?=E7=9A=84=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- dinglogin/dingding - 副本.js | 41 ++++++++++++++++++++++++++++++++ dinglogin/dingding.css | 29 +++++++++++++++++++++++ dinglogin/dingding.js | 41 ++++++++++++++++++++++++++++++++ dinglogin/dingdingtest.css | 29 +++++++++++++++++++++++ dinglogin/dingmail.js | 43 ++++++++++++++++++++++++++++++++++ dinglogin/dingmailtest.js | 42 +++++++++++++++++++++++++++++++++ 6 files changed, 225 insertions(+) create mode 100644 dinglogin/dingding - 副本.js create mode 100644 dinglogin/dingding.css create mode 100644 dinglogin/dingding.js create mode 100644 dinglogin/dingdingtest.css create mode 100644 dinglogin/dingmail.js create mode 100644 dinglogin/dingmailtest.js diff --git a/dinglogin/dingding - 副本.js b/dinglogin/dingding - 副本.js new file mode 100644 index 00000000..4ccce825 --- /dev/null +++ b/dinglogin/dingding - 副本.js @@ -0,0 +1,41 @@ +$(function(){ + var url = encodeURIComponent("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoaeyo28cm9bj2cxoxs&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/info.php/apps/dingding/index/auth_login"); + var obj = DDLogin({ + id:"login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span> + goto: url, + style: "", + href: "", + width : "300px", + height: "300px" + }); + + var hanndleMessage = function (event) { + var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了 + var origin = event.origin; + login_url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoaeyo28cm9bj2cxoxs&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/info.php/apps/dingding/index/auth_login&loginTmpCode='+loginTmpCode; + window.location.href = login_url; + }; + if (typeof window.addEventListener != 'undefined') { + window.addEventListener('message', hanndleMessage, false); + } else if (typeof window.attachEvent != 'undefined') { + window.attachEvent('onmessage', hanndleMessage); + } + + $('.login_type').click(function(){ + if($(this).html() == '账号登录'){ + $('.pc_login').removeClass('hide'); + $('#login_container').addClass('hide'); + $('.ding_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).prev().removeClass('login_type_active'); + } + if($(this).html() == '钉钉扫码登录'){ + $('.ding_login').removeClass('hide'); + $('#login_container').removeClass('hide'); + $('.pc_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).next().removeClass('login_type_active'); + } + }); + +}); diff --git a/dinglogin/dingding.css b/dinglogin/dingding.css new file mode 100644 index 00000000..506093d9 --- /dev/null +++ b/dinglogin/dingding.css @@ -0,0 +1,29 @@ +.ding_login{ + width:365px; + height:400px; + margin:0 auto; +} +.login_header{ + width: 100%; + height: 64px; + font-size: 18px; + color: #898d90; + overflow: hidden; + border-bottom: 1px solid #e8e8e8; +} +.login_type{ + width: 50%; + line-height: 60px; + text-align: center; + border-bottom: 4px solid transparent; + float: left; + cursor: pointer; +} +.login_type_active{ + color: #38adff; + border-bottom: 4px solid #38adff; + cursor: default; +} +.hide{ + display: none; +} \ No newline at end of file diff --git a/dinglogin/dingding.js b/dinglogin/dingding.js new file mode 100644 index 00000000..4ccce825 --- /dev/null +++ b/dinglogin/dingding.js @@ -0,0 +1,41 @@ +$(function(){ + var url = encodeURIComponent("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoaeyo28cm9bj2cxoxs&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/info.php/apps/dingding/index/auth_login"); + var obj = DDLogin({ + id:"login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span> + goto: url, + style: "", + href: "", + width : "300px", + height: "300px" + }); + + var hanndleMessage = function (event) { + var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了 + var origin = event.origin; + login_url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoaeyo28cm9bj2cxoxs&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/info.php/apps/dingding/index/auth_login&loginTmpCode='+loginTmpCode; + window.location.href = login_url; + }; + if (typeof window.addEventListener != 'undefined') { + window.addEventListener('message', hanndleMessage, false); + } else if (typeof window.attachEvent != 'undefined') { + window.attachEvent('onmessage', hanndleMessage); + } + + $('.login_type').click(function(){ + if($(this).html() == '账号登录'){ + $('.pc_login').removeClass('hide'); + $('#login_container').addClass('hide'); + $('.ding_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).prev().removeClass('login_type_active'); + } + if($(this).html() == '钉钉扫码登录'){ + $('.ding_login').removeClass('hide'); + $('#login_container').removeClass('hide'); + $('.pc_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).next().removeClass('login_type_active'); + } + }); + +}); diff --git a/dinglogin/dingdingtest.css b/dinglogin/dingdingtest.css new file mode 100644 index 00000000..506093d9 --- /dev/null +++ b/dinglogin/dingdingtest.css @@ -0,0 +1,29 @@ +.ding_login{ + width:365px; + height:400px; + margin:0 auto; +} +.login_header{ + width: 100%; + height: 64px; + font-size: 18px; + color: #898d90; + overflow: hidden; + border-bottom: 1px solid #e8e8e8; +} +.login_type{ + width: 50%; + line-height: 60px; + text-align: center; + border-bottom: 4px solid transparent; + float: left; + cursor: pointer; +} +.login_type_active{ + color: #38adff; + border-bottom: 4px solid #38adff; + cursor: default; +} +.hide{ + display: none; +} \ No newline at end of file diff --git a/dinglogin/dingmail.js b/dinglogin/dingmail.js new file mode 100644 index 00000000..a7d1dc76 --- /dev/null +++ b/dinglogin/dingmail.js @@ -0,0 +1,43 @@ +$(function(){ + var url = encodeURIComponent("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoagxeeheunc0p95eu8&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/webht.php/apps/dingmail/index/auth_login"); + + var obj = DDLogin({ + id:"login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span> + goto: url, + style: "", + href: "", + width : "300px", + height: "300px" + }); + + var hanndleMessage = function (event) { + var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了 + var origin = event.origin; + login_url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoagxeeheunc0p95eu8&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://www.mycht.cn/webht.php/apps/dingmail/index/auth_login&loginTmpCode='+loginTmpCode; + window.location.href = login_url; + }; + if (typeof window.addEventListener != 'undefined') { + window.addEventListener('message', hanndleMessage, false); + } else if (typeof window.attachEvent != 'undefined') { + window.attachEvent('onmessage', hanndleMessage); + } + + $('.login_type').click(function(){ + console.log($(this).html()); + if($(this).html() == '钉钉帐号密码登录'){ + $('.pc_login').removeClass('hide'); + $('#login_container').addClass('hide'); + $('.ding_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).prev().removeClass('login_type_active'); + } + if($(this).html() == '钉钉扫码登录'){ + $('.ding_login').removeClass('hide'); + $('#login_container').removeClass('hide'); + $('.pc_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).next().removeClass('login_type_active'); + } + }); + +}); diff --git a/dinglogin/dingmailtest.js b/dinglogin/dingmailtest.js new file mode 100644 index 00000000..f52fb95f --- /dev/null +++ b/dinglogin/dingmailtest.js @@ -0,0 +1,42 @@ +$(function(){ + var url = encodeURIComponent("https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoar4ini4akuc7mifny&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://share.chtcdn.com/webht.php/apps/dingmailtest/index/auth_login"); + + var obj = DDLogin({ + id:"login_container",//这里需要你在自己的页面定义一个HTML标签并设置id,例如<div id="login_container"></div>或<span id="login_container"></span> + goto: url, + style: "", + href: "", + width : "300px", + height: "300px" + }); + + var hanndleMessage = function (event) { + var loginTmpCode = event.data; //拿到loginTmpCode后就可以在这里构造跳转链接进行跳转了 + var origin = event.origin; + login_url = 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dingoar4ini4akuc7mifny&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=http://share.chtcdn.com/webht.php/apps/dingmailtest/index/auth_login&loginTmpCode='+loginTmpCode; + window.location.href = login_url; + }; + if (typeof window.addEventListener != 'undefined') { + window.addEventListener('message', hanndleMessage, false); + } else if (typeof window.attachEvent != 'undefined') { + window.attachEvent('onmessage', hanndleMessage); + } + + $('.login_type').click(function(){ + if($(this).html() == '账号登录'){ + $('.pc_login').removeClass('hide'); + $('#login_container').addClass('hide'); + $('.ding_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).prev().removeClass('login_type_active'); + } + if($(this).html() == '钉钉扫码登录'){ + $('.ding_login').removeClass('hide'); + $('#login_container').removeClass('hide'); + $('.pc_login').addClass('hide'); + $(this).addClass('login_type_active'); + $(this).next().removeClass('login_type_active'); + } + }); + +}); From d11a12503288bdfe87cef16e717354306b5c216b Mon Sep 17 00:00:00 2001 From: LMR <59361885@qq.com> Date: Thu, 9 May 2019 13:58:54 +0800 Subject: [PATCH 325/382] =?UTF-8?q?=E5=9B=BD=E9=99=85=E7=AB=99=E7=A7=BB?= =?UTF-8?q?=E9=99=A4FAQ=E4=BF=A1=E6=81=AF=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/controllers/information.php | 135 ++++++++++++++---------- 1 file changed, 77 insertions(+), 58 deletions(-) diff --git a/application/controllers/information.php b/application/controllers/information.php index d3d18193..cac198b1 100644 --- a/application/controllers/information.php +++ b/application/controllers/information.php @@ -3,9 +3,11 @@ if (!defined('BASEPATH')) exit('No direct script access allowed'); -class Information extends CI_Controller { +class Information extends CI_Controller +{ - function __construct() { + function __construct() + { parent::__construct(); $this->permission->is_admin(); //$this->output->enable_profiler(TRUE); @@ -22,11 +24,13 @@ class Information extends CI_Controller { $this->load->library('Amplib'); //加载AMP处理类 } - public function index() { + public function index() + { echo '信息首页'; } - public function add($is_parent_id) { + public function add($is_parent_id) + { //添加空内容. $this->InfoContents_model->Add('', 'New Information', '', '', '', '', '', '', '', 0, 0, '', '', 0, 0, '', '', 0, '', 0, '', ''); $infocontent = $this->InfoContents_model->get_ic_contents($this->InfoContents_model->insert_id); @@ -44,7 +48,8 @@ class Information extends CI_Controller { } //移动结构顺序 - public function move() { + public function move() + { //网站会提交一个同级节点id列表字符串,按照这个去排序 $parent_id = $this->input->post('pid'); $idsStr = $this->input->post('ids'); @@ -65,7 +70,8 @@ class Information extends CI_Controller { //把文章移动到任意板块文章下 //is_id 信息结构ID,is_parent_id即将转移到的信息结构id - public function move_by_is_id() { + public function move_by_is_id() + { $data = array(); $is_id = $this->input->post('is_id'); $is_parent_id = $this->input->post('is_parent_id'); @@ -90,7 +96,8 @@ class Information extends CI_Controller { return TRUE; } - public function delete($is_id) { + public function delete($is_id) + { //查询结构信息 $Structure = $this->InfoStructures_model->Detail($is_id); if ($Structure == FALSE) { @@ -124,7 +131,8 @@ class Information extends CI_Controller { } } - public function edit($is_id) { + public function edit($is_id) + { set_time_limit(30); //$this->output->enable_profiler(true); //查询结构信息 @@ -188,37 +196,37 @@ class Information extends CI_Controller { - if ($Structure->is_sitecode=='ct'){ + if ($Structure->is_sitecode == 'ct') { $data['infoTypeList'] = $this->config->item('InfoType_ct'); - }else { - + } else { + switch ($data['rootInformation']->ic_ht_area_type) { case 'c': //城市 $data['infoTypeList'] = $this->config->item('InfoType_city'); $data['unlink_landscape_list'] = $this->Information_model->get_unlink_landscape_list($data['rootInformation']->ic_ht_area_id); break; - case 'p'://省份 + case 'p': //省份 $data['infoTypeList'] = $this->config->item('InfoType_province'); break; - case 'n'://国家 + case 'n': //国家 $data['infoTypeList'] = $this->config->item('InfoType_country'); break; - case 't'://特殊区域 + case 't': //特殊区域 $data['infoTypeList'] = $this->config->item('InfoType_special'); break; - case 'e'://大洲 + case 'e': //大洲 $data['infoTypeList'] = array(); break; - case 'z'://公民游 + case 'z': //公民游 $data['infoTypeList'] = $this->config->item('InfoType_citizen'); break; - case 'v'://视频 + case 'v': //视频 $data['infoTypeList'] = $this->config->item('InfoType_video'); break; - case 'f'://节庆 + case 'f': //节庆 $data['infoTypeList'] = $this->config->item('InfoType_festival'); break; - case 'pd'://产品管理 + case 'pd': //产品管理 $data['infoTypeList'] = $this->config->item('InfoType_product'); //LMR 2016-7-14 if (in_array($this->config->item('site_code'), array('vac', 'vc', 'jp', 'ru', 'it'))) { @@ -297,7 +305,8 @@ class Information extends CI_Controller { exit(); } */ - public function test_proxy($url = false) { + public function test_proxy($url = false) + { $curl = curl_init(); //curl_setopt($curl,CURLOPT_URL, "http://graph.facebook.com/?id=http://www.chinahighlights.com"); //curl_setopt($curl,CURLOPT_URL, 'http://graph.facebook.com/?id=http://www.mybeijingchina.com/beijing-attractions/beihai-park/'); @@ -313,7 +322,8 @@ class Information extends CI_Controller { } // 分享数 lzq - public function statistical_sharing() { + public function statistical_sharing() + { //$info_ic = $this->Information_model->get_ic_url_by_code('mbj'); $info_ic = $this->Information_model->get_ic_url(); @@ -355,7 +365,8 @@ class Information extends CI_Controller { $this->load->view('bootstrap3/statistical_sharing'); } - public function edit_save() { + public function edit_save() + { header('Cache-Control: no-cache'); $information = $this->Information_model->Detail($this->input->post('is_id')); if ($information === false) { @@ -387,18 +398,18 @@ class Information extends CI_Controller { //AMP更新和生成 beign $auto_update_amp = $this->input->get_post('auto_update_amp'); if (!empty($auto_update_amp) && $auto_update_amp == 'true' && $this->input->post('ic_status') == 1) { - $amp_result=$this->amplib->auto_create($information->ic_id); + $amp_result = $this->amplib->auto_create($information->ic_id); if (!empty($amp_result)) { $amp_result = json_decode($amp_result); - if($amp_result->result=='ok'){ - $amp_save_result= $this->amplib->edit_save($information->ic_id,$amp_result->data->amp,'1'); - if(!empty($amp_save_result)){ - $amp_save_result = json_decode($amp_save_result); - if($amp_save_result->name=='no'){ - echo json_encode(array('name' => 'no', 'value' => 'AMP转换语法错误,请重新进入AMP编辑器检查')); - return; - } - } + if ($amp_result->result == 'ok') { + $amp_save_result = $this->amplib->edit_save($information->ic_id, $amp_result->data->amp, '1'); + if (!empty($amp_save_result)) { + $amp_save_result = json_decode($amp_save_result); + if ($amp_save_result->name == 'no') { + echo json_encode(array('name' => 'no', 'value' => 'AMP转换语法错误,请重新进入AMP编辑器检查')); + return; + } + } } } } @@ -428,7 +439,7 @@ class Information extends CI_Controller { $update_info_log = $this->update_cache($ic_url, true); } else if (strcasecmp($site_code, "cht") == 0 && !empty($auto_update_cache)) { $update_info_log = $this->update_cache($ic_url); - } else if (strcasecmp($site_code, "cht") != 0 && strcasecmp($site_code, "gm") != 0) {//非cht站点并且非GM + } else if (strcasecmp($site_code, "cht") != 0 && strcasecmp($site_code, "gm") != 0) { //非cht站点并且非GM $update_info_log = $this->update_cache($ic_url); } @@ -470,7 +481,8 @@ class Information extends CI_Controller { } //URL不重复检查 - function ic_url_check() { + function ic_url_check() + { if ($this->input->post('ignore_url_check')) { return true; } @@ -484,7 +496,8 @@ class Information extends CI_Controller { } //URL格式检查,不能包含大小写、空格等特殊字符 - function ic_url_format($url) { + function ic_url_format($url) + { if ($url != mb_strtolower($url) || strpos($url, ' ') !== false || strpos($url, '--') !== false || strpos($url, ')') !== false || strpos($url, '(') !== false || strpos($url, '//') !== false || strpos($url, '\\') !== false) { return false; } @@ -493,7 +506,8 @@ class Information extends CI_Controller { //更新静态文件 //不用参数提交的原因是可能url带有特殊字符,CI会报错 - public function update_cache($static_html_url = false, $delete_only = false) { + public function update_cache($static_html_url = false, $delete_only = false) + { $url = !empty($static_html_url) ? $static_html_url : $this->input->post('cache_url'); $url = str_replace($this->config->item('site_url'), '', $url); $original_url = $url; //原始链接 @@ -518,7 +532,7 @@ class Information extends CI_Controller { case 'ah': if ($delete_only === true) { $url = 'https://www.asiahighlights.com/index.php/information/delete_cache_8X913mksJ/?static_html_url=' . $url; - } else {// static_html_optimize=comeon 启用静态化压缩和js、css延迟加载 + } else { // static_html_optimize=comeon 启用静态化压缩和js、css延迟加载 $url = 'https://www.asiahighlights.com/index.php/information/detail/?static_html_url=' . $url . '&static_html_optimize=comeon'; } break; @@ -534,16 +548,16 @@ class Information extends CI_Controller { } break; - case 'vac'://国际站 + case 'vac': //国际站 case 'vc': case 'it': case 'ru': case 'jp': - if ($delete_only) { + $information = $this->Information_model->Detail($url); + if ($delete_only || $information->ic_ht_area_type === 'q') { //只删除操作,在url修改和不发布信息的时候使用 $url = $this->config->item('site_url') . '/index.php/welcome/update_cache/delete_only?static_html_url=' . $url; } else { - $information = $this->Information_model->Detail($url); $tmp = $url; //判断是否是更新信息 // 产品页面不能生成静态页面,比如/beijing/hotel/只是为了在导航显示一个链接,如果生成了静态页面,网前只会显示一个空白页面了 @@ -558,9 +572,9 @@ class Information extends CI_Controller { if (isset($information->ic_type) && $information->ic_type == 'product') { $url = $this->config->item('site_url') . '/index.php/welcome/update_cache/?static_html_url=' . $tmp; } - //int return direct - $cache_url = $this->input->post('cache_url'); - if ($url && !$cache_url) { + //int return direct + $cache_url = $this->input->post('cache_url'); + if ($url && !$cache_url) { /* ignore_user_abort(true); $ch = curl_init(); @@ -577,24 +591,25 @@ class Information extends CI_Controller { curl_close($ch); */ $data['async_update'] = $url; - $data[] = array('name' => 'ok', 'value' => '信息保存成功,请在8秒后检查更新页面。', 'url' => $url); - //如果是外部调用就返回结果,内部就不返回了 - if ($cache_url) { - echo json_encode($data); - } - return $data; - } + $data[] = array('name' => 'ok', 'value' => '信息保存成功,请在8秒后检查更新页面。', 'url' => $url); + //如果是外部调用就返回结果,内部就不返回了 + if ($cache_url) { + echo json_encode($data); + } + return $data; + } } break; - case 'ct'://子站点使用 + case 'ct': //子站点使用 case 'sht': case 'gl': case 'mbj': case 'yz': $url = $this->config->item('site_url') . $url . '@cache@refresh'; break; - default:return false; + default: + return false; break; } @@ -623,7 +638,8 @@ class Information extends CI_Controller { } //更新CDN缓存 - public function update_cdn($static_html_url = false) { + public function update_cdn($static_html_url = false) + { $flag = false; //false:不更新,true:更新 $update_site = array('jp', 'ru'); //需要更新CDN的站点 //需要更新的url @@ -658,7 +674,8 @@ class Information extends CI_Controller { } //获取产品信息,提供给用户选择进行绑定 - function get_products() { + function get_products() + { $HT_productType = $this->input->post('product_type'); $HT_productName = $this->input->post('product_name'); //产品类型 @@ -679,7 +696,8 @@ class Information extends CI_Controller { } //显示备份的内容 - function backup_content($log_id) { + function backup_content($log_id) + { $data['log_info'] = $this->Logs_model->read($log_id); $data['log_list'] = $this->Logs_model->get_all_backup_list($data['log_info']->log_res_id); $this->load->view('bootstrap/header', $data); @@ -688,7 +706,8 @@ class Information extends CI_Controller { } //保存自定义配置 - function save_meta() { + function save_meta() + { $im_ic_id = $this->input->post('im_ic_id'); $im_key = $this->input->post('im_key'); $im_value = $this->input->post('im_value'); @@ -708,7 +727,8 @@ class Information extends CI_Controller { } //保存自定义配置 - function delete_meta() { + function delete_meta() + { $im_ic_id = $this->input->post('im_ic_id'); $im_key = $this->input->post('im_key'); if ($im_ic_id && $im_key) { @@ -721,5 +741,4 @@ class Information extends CI_Controller { echo json_encode($data); return true; } - } From 220b2d29e82b879669a836ee75f91d3402c1c8f4 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 13:59:34 +0800 Subject: [PATCH 326/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E7=A1=AE=E5=AE=9E?= =?UTF-8?q?=E7=9A=84=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/images/+_value.png | Bin 0 -> 3301 bytes css/images/+like.png | Bin 0 -> 6343 bytes css/images/+unlike.png | Bin 0 -> 7126 bytes 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 css/images/+_value.png create mode 100644 css/images/+like.png create mode 100644 css/images/+unlike.png diff --git a/css/images/+_value.png b/css/images/+_value.png new file mode 100644 index 0000000000000000000000000000000000000000..af3597da00200666d71961e83d8b56f156c0072f GIT binary patch literal 3301 zcmV<B3>x!^P)<h;3K|Lk000e1NJLTq003kF001lq1^@s6lj$8*0000PbVXQnQ*UN; zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU;he<?1RCwC#TU(42RT}=!>FVjrKzGj! z)6*~mBQvlMy3PnZNDM?JG1*Coi-`hJ#D{&@2Unj^5`-s&L^1oY>VqUEUN;Vsh#R60 z8;u5okSv;ES;ciC%mth)&}=t-tIPiXUv;XhdwMQ9BQuabr0BYws&meN`TooKM_85x z)wXb&tdgM0kZP+k<ko3gHm|!EWKV<;;Pd&QP$=*(chcxuhmq0I-)AzJRfT*$nog(h zD(HHY`b!~l_?y)YBRbV!VwUELUl%k_J!+rIEC`tcOUaeV&#9vjKD#sjZ`e=SUP|}A zC9Ht^UP+^CGicMq3<w^>40z-?=dOw7px&~~V4x=0pV#$xC>ZRmt*!krvUu^CNMvzu zO&|ao(o@$BFiZn!CYjbmb47RlUM5#45=;s(4U-=dL;QX}T)%!jdhOb^`z~L;{8Y>G zmcxF{{}~Ph!C(;lHGb|(?-+*RGVr%!h;Tk+IP4KNft^!9rzR~>@S(UPi6O#1Q_Lv& zp381^sL7U2Sa`49?+f>-&nF>sBLfAafL8*t*(}j-dp4U};n%d}(q+ru4uyg_P1C?M zO=g4-g`GaD>pDm&OBq6qxaX5TNTt&O)P~jLV`C4-VzIw1YhK2Sr9p`aLi}=qidm|& z>ktYr5rt>&d0r@(z9O;cC5M5gt4U(Y8CjnHD=|crugJ0)O*BDm!d|Ea7SU1ibv9do zR4N67gZ(eY<BiAa>gvvrFx#3eTutF~FGJK#)QI@N;NUa$_4Ruj>gynk8d1m>Axyc- z!o!uBxX-g=2u<42K%qPEWH=fk9St|^HDEuKS7$)Wg(M5grP?Z+T~Vv1)^t&(L4q}g znL!Z58fiK-lD1~zb3@NV-#{O0OjA7mQDeNZmxNq5bc8dF-_=N>G`|LV!B&~!k>Pbi zL&MuvuUhq7BocvKF2|6h)QtMjLFb5>%p`^h8rH!@(lQ!=rPYB#>Z2e_F_PaR0@6Rp zn8Nqyn!YWa1(H@0_6q4CqVTd<bLlGteN)=tW7#l@>%}?yxVM38@kv@dLbKFKZ}1t; zRVS#{Y=xrv;d}^2=zZbZAK}c+hAb%&c1)z35AX3!txW7p9>-Gi!$-ecz4`;vmhZkl zzZ}1Lcu7OUIifAEooJCoMli8(0)vB>HjR&uKX}hQoqK6A1|FeMm?!qDFltt~bgMSK z+;4JqQ6i1=DB!_h2-4{k^!E?^Igv<o2Lgd)C=_B%ku1?@kgs038Xp@Q`@_1mYxa_1 zB0ECN$QSZZjpk?H6ngsoHH;iY+qSm0H@-iA{tZHff^Itk3<3m8$c(P`_O|E9y$y%M z>>&_rkU9~=s%;LK;=no4lkEl47SU+?4?q0(WiksAp;;riBDWURW+WPkqAI1)h=(B* z4lz^_*J=Va4o1$T4MFH&OUa$g9{ty@;1(pie^MwmoRETSBZU=Vq;a8;w^~}7R}Tyf zY(tIdmc)Ro*RE}9ZfX96I7ix%%jRqYiT{X;`CNX6lQ{*ilre+alb;SPAc76Shp%fW zG%vyF`ACg8jtU8Ro;_C$>g(!%%;s_{(AWngK~*doJsGH};fS1FFk}L8kW`4^EF2Er z9+)xQ4Ns!L>`cy6o=O(IOZ(dPSV?Od8yjD~a^=b<IWjuBrM0#7vrHz-=@B+8*omTa z(ijS0GTGei!H}kH@a~>Lcqcl4Q{XTIwSvt7WkyWfcGSgUfF5p_j5jtO%jI)WgBs$E z8o48>7e(jNSGCA<;n5>4RSZWoWkXKaPMn8<_~#N0_$Qo?GR-Q*Zi??ac|-gCkqo0h zEMS3pGmQCUfQ!c~XT1)Dx~~khGT5Huy;CzZ@>6~Parkh!k^|!z=k;!w-gPmjV+d%< zsHpVD%)FFeW*Cot+k!{sXZttnu&ZM#%x{IxgBxHUY=w9J^mllyNj+Q-yY_qqaPUjm zxMw%q>(1){e8JZ^(@!6VmEUeaB2O^}B;c{9b=b&#k9h9W_woLF8a&WnK~Ubj2!Fxn z8M;3E5`>OF0V`hzxbXBg{Nm)<ZfgqJrxcdtJPJ&kPb+b2=h92rcU+sM2NGuU0sK7z z|M;d%2G4#8J!_s~;=3(+2ec|uH+S-H&!y>QSM@D#tqofz+&lfxC!lll?&7!|yWxu! z_?vtJ-a9*`pEczih!+|ebCsK4u&v{M*nb?E_tTef2#OMT`fLw8{7|Aq(jQZLJVD~; zs-1!ps4@HcH58_aPnr20m373L#xnRdzn$$}_-#GxShE%OeM=I!&4wR@jo08=c(<vn zE5pYN04u(N%;rw}d`|6JAM{Ls&$($7W=P6eaoShT#IPeA%##nF=z13R6U3dcjpxue zA46xy`cf!Cybm4kL1H1c?^ypE&gKa84bS~oDF|l`QQNTmOZx;MihCBG{oZm|sBB}% z0GGB$*9^kDU5Qz1$wtEI{*U3ra4Yov^hemyRcdHoBjdZ`**TZoQbz-w3`a0_bd(uz z)XrC6_v8+Q+V63~4Bks}_SDI_;_L{e*VRUh?JA23d9j6IU+#VAeRve5bLX2I05+Bp zWB4K*CFVEWF{?4k9e}>^BV`)lphS|qDzB@H!id`0+B99hR5+V%K2XY_;EDotnY@;K zghKa9L|2jf!byGH4-YeB9)OMIQrL6{GK*a7x1E@T2xQxjqvIEmVW;5q@HCDC^+m^F z$OD0|CAYfXpdD)<N<8{LkHt)JW04K$@%?pb?G&ZwisroYs`=o0^7?jp_3G98NGm8$ zU(_sXfieY&vGD*xV417y#4Lx_5b<7s2be$<pM1qchW-r@I@*WQ>vh}he#Jo0aj!i@ zKGC7Wp|&FIW>k#9@sacGUjWO(Dw+T`;8K>PRsNSstrO?IJO5NP7JX|;!;%t+a_fW~ z6`R@K#2nZVucqFT`yrFB%NrPynV^uvvJDH2jEvl!N~iCViA3Uq(b3W8)h?D|!a}nj zw?m_H2hNBnfp-dAi1x$7!&?%Grfx2B=)2h06$*t0>gwwL%~ckaJgoUBa=6VjL<u_w z;$XR(e`q%DzH#Hms+Dakk4Zx}VCmAtr<Z^Jc_-NsGB68j5x2|X3I5nFI~G2l&x=c! zF70e?Za&88dEye)EVZ|_?K}Vd`9su6)%MPZG512G^3ls-(|dn5$4!SU6!t)%h8-w1 zeos%&M|a+N=kvq|Mx<Q9U=<=GlS-xH7cN}b+tJzaOfV1t-LNYpD92*lq!f#+AOu#$ zvd+?eGfe@NGh%}CGD$zRv82w6V=7p;TxC#Ov$P#fQzs_yZY=i8W2_Mf1{tab1_riA zqLDLbDtbY^r-BpOvW-TgBW>+%FZT4DeRXtnjCTxGAvKLewW>@ok1E<lep~_1)!lY| ztLI>s&MfIy=}`SEyYJI8$?HN+7noIIP-#YDVn0>2>1Dostr%Hc16OrATeURx91`E} zx67$C6mCQxaq{c0KM#k)y$$sZz0{9V?>uhW*)LaRponQylNG&i@#3zgrlw<P`TwQ1 z9tp;{%G@bsnE)Y987P-;I&qCEHJypaX1T@8VoKsqwxKp1#H!L)vYRS1!Nui1pPM?G zj5%J$dB?KXZMx;JB-mtzNjqqpR%r_NLpq@Gj-5Mq?ya@!);<zhya=C}TsKYL7xRFM zt-TZAyb4C{=~SAm|0eX0x3sjh93~HpN>}Kk%1iJvQn_$m=6DHsv+U7i83)B$&LL5q zvf)TMu9br{LIY1dvC;<ndzS6&SfZ#Uob$8aca629C6WrKJw?=H4wA{_ir(Jd{js{( z$@cd4!%9d=7^L$T1uPWa>UZ_02r6iy$x{XredMmuv9T>pP4R9V;4?0y3x?dn2%0p# ztF%KU(1<5W)tN=6HDhU>Eki1PU)Xa{Rq7LLh@;`IC*-V6s_GEwD}yV`V@IU>cQrR| zWL(%nq25jrcq9@zvux?o?!}91fnK33JN=CfSD$z^u!JFmb1BpedMT61F>w`hh%w_= zuB^*tv&)h5Q5<v?!do0CA7BWRGUrHE4(~<OIUV$EoM;?9iFvAsQZ8p9S{trChwFH7 z(V|8FA>yae|F4V1PSUSK=v)EUg<6zUI}(TtBS_pJRd1qEUQTNZ)C5M5l1P^9a-wC8 z-_L6c1Ofx$+S*>C4}EKSOUtX#STsp=<a)P!fh*#v#@Ce-&-S^fM&b*rRsZO-%8+WS jGNj6oYWubA{{jpEVH<Rg7TGQj00000NkvXXu0mjf#${kI literal 0 HcmV?d00001 diff --git a/css/images/+like.png b/css/images/+like.png new file mode 100644 index 0000000000000000000000000000000000000000..f3c31d82b568a612206b1c571b9b4236b377524b GIT binary patch literal 6343 zcmV;&7&zyNP)<h;3K|Lk000e1NJLTq003A3001Kh1^@s65OB>l00009a7bBm000ie z000ie0hKEb8vp<bO=&|zP*7-ZbZ>KLZ*U+<Lqi~Na&Km7Y-Iodc-oy)cUY767Czti zWe-+D*zmEJY=HnGBdiF>5Lu!Sk^o_Z5E4Meg@_7P6crJiNL9pw)e1<Rh~l6qxMx9% zh+2zPTsZC@+^4mDdhhM+``7!t=bY#K&Uw!dfDsZVk>;Xm069{HJUZAPk55R%$-RIA z6-eL&AQ0xu!e<4=008g<d3b(wus{3(uWtYX0C3eVBofEr|AV?vCRYF;kpSQ#66Xs6 zkWv81E>y@A0LT~suv4>S3ILP<0Bm`DLLvaF4FK%)Nj?Pt*r}7;7Xa9z9H|HZjR63e zC`Tj$K)V27Re@400>HumpsYY5E(E}?0f1SyGDiY{y#)Yvj#!WnKwtoXnL;eg03bL5 z07D)V%>y7z1E4U{zu>7~aD})?0RX_umCct+(lZpemCzb@^6=o|A>zVpu|i=NDG+7} z<RYAxn<EoQ=L1a63;+Nc`O(4tI6si*=H%h#X6J10^u?n7Yw&L(J|Xen{=AF=1OO0D z&+pn_<>l4`aK{0#b-!z=TL9Wt0BGO&T{GJWpjryhdijfaIQ&2!o}p04JRKYg3k&Tf zVxhe-<BLB3GvROGi+=X}Kpy_vdhh^onn0PYz@vlxaba$Du2PQY%LGC(ZujRS{>O!X z{f;To;xw^bEES6JSc$k$B2CA6xl)ltA<32E66t?3@gJ7`36pmX0IY^jz)rRYwaaY4 ze(nJRiw;=Qb^t(r^DT@T3y}a2XEZW-_W%Hszxj_qD**t_m!#tW0KDiJT&R>6OvVTR z07RgHDzHHZ48atvzz&?j9lXF70$~P3Knx_nJP<+#<bWIsp%|7y8C1YJ*aWq(0~(+a zn&A+%!7(@u=im}tf$MM=24EPT!Wg`U2?RmN2oqr;I*1Wsj@Tm32p5@-1R`NbG?IX% zAnAw{Q6k02a-;&OLTZs+NF(wsauhj@TtNDe+sGg?iu{VaM=_LvvQY!n0(C&Ss2>`N z#-MZ2bTkiLfR>_b(HgWKJ%F~Nr_oF3b#wrIijHG|(J>BYjM-sajE6;FiC7vY#};Gd zST$CUHDeuEH+B^pz@B062qXfFfD`NpUW5?BY=V%GM_5c)L#QR}BeW8_2v-S%gfYS= zB9o|3v?Y2H`NVi)I<b&gMyw|8As!)~C0-{E6JL`^Bo4`v<W349C6F>n3rTB8+ej^> zQ=~r95NVuDChL%G$=>7$vVg20myx%S50Foi`^m%Pw-h?Xh~i8Mq9jtJloCocWk2Nv zrJpiFnV_ms&8eQ$2&#xWpIS+6pmtC%Q-`S&G<BLK&6^fO%cL!%)zF%0XKD9nFX?o; z3EhJpMVHW*(rf4k>F4Q#^mhymh7E(qNMa}%YZ-ePrx>>xFPTiH1=E+A$W$=bG8>s^ zm=Bn5Rah$aDtr}@$`X}2l~$F0mFKEdRdZE8)p@E5RI61Ft6o-prbbn>P~)iy)E2AN zsU20jsWz_8Qg>31P|s0cqrPALg8E|(vWA65poU1JRAaZs8I2(p#xiB`SVGovRs-uS zYnV-9TeA7=Om+qP8+I>yOjAR1s%ETak!GFdam@h^#<Ae=IoX^_&LPeX&U-BbEk7-> z)@rS0t$wXH+Irf)+G6c;?H29p+V6F6oj{!|o%K3xI`?%6x;DB|x`n#ib<gTP(_`y- z=?V49^$zLX(MR=d^rQ6`>hIR?(H}Q3Gzd138Ei2)WAMz7W9Vy`X}HnwgyE<W%V@fh z#Au_@NuwvYChmu4<285}K4z?M9Ad0A-euftJYiyKGTWrYq{ZaEDb18?nr6Duw9|CV z%*ZU<tk|r{?2b9roNJz8zS+Fn{EdaBMV!S-i#ChLmfDtl%LSHAmiMffRz6mFR`pib ztVz~f>n!VS)>mv$8&{hQn>w4zwy3R}t;BYlZQm5)6pty=DfLrs+A-|>><a9f>;~;Q z_F?uV_HFjh9n2gO9o9Q^JA86<b<B2baJ=iJ;WWdk#HqvSS7#e%p>v({H5aB!kjoO6 zc9$1ZZKsN-Zl8L~mE{`ly3)1N^`o1+o7}D0ZPeY&J;i;i`%NyJ8_8Y6J?}yE@b_5a zam?eLr<<q3^N{B+UUpttUi-ZsPqUmRp4KpJ$lJtQ;JwRxU^+fMW%|zP13tz+0-t)H zhrXu1BHul}BYxI?nSKZSp8Grc%l(h|zu|fE7V%C6U;)7a<pI5c8iBI|YXctynFOT= zH3f|Yy9O@|J{3X?2@P2va+7bs7xEkVV>8@mESk|3$_SkmS{wQ>%qC18))9_|&j{ZT zes8AvOzF(F2#DZEY>2oYX&IRp`F#{ADl)1r>QS^)ba8a|EY_^#S^H<bj`5GFjJZ48 zYPNEAXRK;$Qfy=Fo4A0us<?r8hxkSDmlAXnBnj<_<iyy-J&EIU0_SX+Go0j_RF-sO zuI1dKxfkZ?&dZ*6JXtkakbF3Wm=c$=KjniULQpRlPvxg>O&t^Rgqwv=MZThqqEWH8 zxJo>d=ABlR_Bh=;eM9<ahEGOy#xn^|QY(3p8Irjp^G#Mn*50ho*>Tw|Ih34~oTE|= zX_mAr*D$vzw@+p(E0Yc6dFE}(8<U61_v9n_bMxC3Y=unGqqI`4P!1MMFQ_YcTNqn- zxJbQ7TGTV&X8!8=BMX8Se7%scP`I$O*tmFE@!%rAMY|Rwi&GbOE-_tFx@351@X~$D zXv?ye{ZQgqQdRP5dED}jQiIZ^r9&%%S2UHWl*!9(uJl^DV-;bQWL58Km(^QVe<~N1 zU#xJfsIK_1M!4qUS59BmeD!&4+S=Yqx61A7Nb98QZmjoNzpqNYYC+Y|hVTuo8}W_h z8((co-gKdQYW0rIw9U%R12tha?OV*YtlRRTHly}>oqt`+R{gE3x4zjX+Sb3_cYE^= zgB=w+-tUy`ytONMS8KgRef4hA?t<Nq8e$u|zvh13xJP$S#h#CQrF#eVMeplsbZ>0j zufM;t32jm~jUGrkaOInTZ`zyfns>EuS}G30LFK_G-==(f<51|K&cocp&EJ`SxAh3? zNO>#LI=^+SEu(FqJ)ynt=!~PC9bO$rzPJB=?=j<Jb;mW2SDv7qC_VA{<bspqr(~y| zolZYJ)S29Q_e}hmYh6)Yy=Ozuo<A3K?o78|_sR3#=Z{_Rym0g)_hQ>6w@a-(u02P7 zaQ)#(uUl{HW%tYNS3ItC^iAtK(eKlL`f9+{bJzISE?u8_z3;~C8@FyI-5j_jy7l;W z_U#vU3hqqYU3!mrul&B+{ptt$59)uk{;_4iZQ%G|z+lhASr6|H35TBkl>gI*;nGLU zN7W-nBaM%pA0HbH8olyl&XeJ%vZoWz%6?Y=dFykl=imL}`%BMQ{Mhgd`HRoLu6e2R za__6DuR6yg#~-}Tc|Gx_{H@O0eebyMy5GmWADJlpK>kqk(fVV@r_fLLKIeS?{4e)} z^ZO;zpECde03c&XQcVB=dL;k=fP(-4`Tqa_faw4Lbua(`>R<o>I+y?e7jKeZ#YO-C z4fIJwK~#9!?3!zE9p!n)H(@3;C7EQ>;ZkNgQ<B!?19X~{IHY7sCNR^`Nt-lnGX!uT zF$TiLCNUUHa7Y7$fdDaJY-4JKZ7kWAEMFi7Y-|hJl8%nfo;_Ec`$anE=-lsndoO$b z{jfU6lB{D1No3NFKm2D`yE^ag{`PtQ@AE$I3IK%j`uKDn!g;{|j{qmr*_OtV6GA+Z z6f*gukV<ETOg1n0LlI%fYWqwyHvUgue_)l};d;_CBEC92B5oY9J6^O{ZJTD3bpf)> zq2UqnW0Pe>+-w!4jTWo;icNC<HWZ0{-yaNLBstxm%;t-NFBlel!H|%e!fUEN65wp1 zB&4%>VQf74S${CR#^v$7Jdw`6T_~3!s~T#Gj;gAmDx3SJG}KicvZ_PXDKzb)OVy`K zr>v!!=ayQUPN8Tz%GElG<tipJxo{vHdCcnzJRKiTe$gL_T(Bg7$C4=_mC62DFdV%t z6pnV~3MCL`fEot4(E#HH6pcdG2o#M#p0ckIwxr@lqa}Uv*fc1MXj>%=icY6VB@8;_ z&<F!z1_(1ytt$w}#*R7N-mm$C;Y%knxrGBBPfZBXvGGeiqy9(I*&I=I3c?KYrYJXW zV)DUS4@xK$ePMtZH(wfUUSlQ%-2|cPY{_4qsx#D8GEIs${iW%YgD?X+<;WFFcCRn6 zCmfCc^=y#m1f0s`gxGlUvQd9veWfZBjWE#3#-~EnW=7Hi029hlsjJxY2P>Z4`aVvN zgrE}!%K3~aTYRK02Jp0d<_7AD3V$g4Qfw^orSVj{#VwV|wFf+&N;mcA?os~}HCZLi zx7UQ*e9-2x#RF!DC-eB->+j=@{R8OOH-NEJ5zJ`(X#%DUvZjMD1G1*W=^4GlG9vzE zB9#`3m6}i}SK9*)N8>^yHg=)cAG{)+D@fX;4=EafHf3;WLT!RvIA9K)GK9x+*tX{s z+`%Na@9W3OAwMYREw458rvX@}9EwgLt2!t*8Z}vc#Oe0lm`J7nVot!JNK6>@2R|2z z#y0De=ch(%Gm13Apy=c**b4!yQwl;kBI7x1?K+KEvVh)WA`TptAZrAK@hK5Zpz8B& zmx1zGdJ8kpE!HBY^(sP<m`Lvk$HuNIRqH~rQfm)55Q==t>kC|;E0lV8117L3Q99Ko zn$Q<*5uC&39>W_wgGgq|IMU}p_q!shiUu<E8uN@`zyy}b(N+(joB`m-<|(RmHlt@O z46sf)G|E62N2RVH5RPsRhGQ3mBeC{?<KxK-y}rOpls6hpNIK<a<We?0V#(qyf-w$R zCD?t?ihePKWWkK!_xe4cjKe?!Y%(PzjL!*}Fb2DWz%xqlottWa*#fe8ifEMLfi*JT zeNP8qOv^?V0$9;VE6A7ugd(vIe1Xs<p>Xt~_8uG?yEZwIIW%<uYkPqy-SwP+shKH| z$u{-Leabi(=diirc&)1+(R2aPi8MO)58~|;E)>f$iWLRLavi0LjJm8rC-j`TEMVXp z|5(KhH&$`Q6&0*qD<cph7)wxm;R|Ja{p(eH_q#Pb^Na$<`JydCYxR%@viYJl5RU#w zARN7+Enu7E{7tc3ofB^J4bB@dGrLj~E}<Np8^{)F*mcl?W5YfaWCf9A25<Hb;JMe| z!>$8E*m-aWJN6Htqx%&4hW*GE>(hLBstki;+iNQR`!@<++*rr5WfgREsE9-<?!8yW z{{0%3FR$Qd_sZz$(ZD!cGQc|Js3{s8ZtrfJ<b0+rV9DiqyjoYx84Nu~qq-Tv%_wdM zm@)&ILJbxvf&qINLsAqLdju9KiUBc-od+z~ac~Hknv9B0kgn9>45e^%$cJ|ayg1VD z#-R^H>^?Mz7q%b8X<HZ#ppEx(JoU7KYrj#!-~4SEmtS7S^5qpc-2~TMQ^obyS8>TD zWn6h>1>gEs73+Vgz-aI#1FY&44!3vLIRRVkju%_rLg&}$xc~#eNlO4fxO*FZcwYx@ zS-k_dtbP+eysrcQx^gp~c=>I3<7vnSM^VvGR5erygUmT(&QZ}cWXolEqX}%=(~o1P zeQg1&x(T_jU&pGu>e#+r#kxlnSgi!r8pHh$$k^Sf;h(=#MI=T6aHvZZ!OiKk<nkP{ zjEI}t0v@v3w#)}?(<0`IU;sEd6vVBocjB%`dU4PCUi|E_UfllkJ-F-9PMoy*QKt+g zl^|bNQIs_kw4$LPYe*F<7|Z5ybkKv1Z+w8rc>b&j$Ql3TIQqVhn}1Y?PB=REXt?_C z%6Rfg1wUO`$My~tfPt@kwF;Y^V0Wk5^5LZb%niWd_8uIz+1mqly1nabvI>o|bNaBN zkrvRo01rt~tbC{wKl#Nz-1*QxtXkKD6{|aO|AuZ1IKw7jO>coMD*7Z~70E&wv2+G+ z_eps5t&_-?<XJt~FgQ;3>A3kvHDt0T>_m#9yIaG`m36$iLj}OW42HoWf@RApxZ%bs zfTgqu0{5uzHOb}P&=#;LIiD_9>t}(RT6<_&17)q^&$$4Lo-y3@XcumOa4%Lq)Pp-8 z?#7BWUAX`8y%><fs1b^iN~T1vekOwRC5%QB*l}<GZ=Y~MR`gk4yiOT%1&U0L0$})u zYbv<*+A40ip@u8JT)}nUtm13StN7xV%CL?QL?Y(@HYXhm0o-KJ+}0HpcBi|`DoW3_ z1?&$+{ym+^d8gGLX8No?JN$Nloq;6o+t7{MAKZ&o4|ikLx*puNrVID}YA;SZCIL^2 zU{kreigc+6M<9l+d-^aah0iJg&CG!*H@9E;`zlnOfpLa`K^>)v8PzL(Tu0X)4FI1u z(_837qX}219NBy^5eP?r9E`+nY72NQIdPFM5c)lx5}ArlFf%W12YV*q1^{0;jWxgS z#civ*uxecoe!8|Bx7^=p0+zz45{i<lqad5MP?R+k6b;#`j8vhBesL79>^crlFbT$u zc?>oTS1zkS(agN~s;er9j!^&x{`0?Tcx$)TvW7*cX_J!`YBUguj~|bZCqJJ`XFt^z zurCn$w8s~?rBto&pW6MW4sJ6cp9`?j03zc#Jo?*1xb1;1ta`W`_pI;19lzLv)lYO| z#5)Fp25N+&q7hUyg7T#DH5n860uCM*v9aSAQrYsn0P_aJh)AGn48MC`!L!dPxbems z)~%D_a1f-k6qGG~s;sDH0gP}1vZ{-LP~<jWAarpc6!~;}!2ZxDT%OU-$Ho$G5N6cp z@}Ri@^F{-SbO{@te+Rcd(1p9#?Z@-49>-G~-^Z#)yRi3N8zu@>lvKSnxD{0u1zAP5 zT1O<6#?Au+=s6;yT310CpR@Go4-)kC>sY?Lf+wFcXKe8}#m-$CuD`y5z56t1I-geb zS+EBa1_QuECfDb5dzblx;ZOPkp-;5;;9ywr1wx<k_yS+emnx3gD^K$;xO1a{Oum8* zFZ=;NxO)eF^7Fme@ca=x_Ut?O-m0xwwSE^i?L3LyhppIkco=UTvSQaED|Q?lMn~@e zwsfAv%WodXup>Ha6>PR_;+Kyr__y!XV1R)cla)2Y+y^+;J}e`Vq9APX7NJw#NT#!I z`hww`0-?yIflx#Ugd*oCxF;usL@F&r#}b!~20}Y(iUyr>$f|ypP0R-{<s9Xjifx^z zuyWll-1Ar$?tZKbcRsQkcdYHei~n;BhmJaM;C%@_M?_Qais(KfV&6M9?0?S=r!Rq; zqC;nF&SFn9AD-#4GtZL+ScJJ4N?MgfMI)fRfxgp&cUVQ~>Od$W_=91=9}Kq#oG+Gz ze6cK)$~7ULNM1JT4{ld90%kN?Bj(gv@O<jQDq+YK>xhi!5FXDV6we|M%OaY{qgvO@ zyjG`Bwb@sA3FB?+4<B2>T{#=Dxu~nP0IP%=iB$TnP&9sBY&<E9Cns8J3piIO3AsW^ z$QQ~&I+qvX<H?Ji9`Ei_rIsb!V1yfI)q>|!uB6<6(ZCtO+){3wsj#s#g&;EJ@A+86 zq5%^IStF)&3VCu>xn%{6LDkJ1oEZ&FWO5xRK0I}+%j>&&B9jwlYF>aRvN<7>D+uvK z@^XjE^UdT$=0LTsoMHy1t;H$&nWcI~Cy+HAvPxR3z}o)-sX8-1IZz2?m6+djXk>B~ z*_=>u1E?$da4M5K>GcKv<=Bb7>)fM$A(hUarH=|&aC?0h+U$<2M+3ochokYs*+S7# zs+luBof&6DP4Pwp0MGzHd1Fb$49qFYXF1;Hx0E+P+qA<CfN~C5Q&Fkakt>vokyzqD zFcM#36{RoR?2f-W-q$ZIC162vx&`;B?{mX8`z7H>{QJH@c!S&P+hTXRd+knlufyf( zl3bpBlFQTWaC^F)Zg02K?dg_We;nBz&R&<t(`mEYPl$H=al7O^EK1J9PS0qE=y3H) zE_aV**gEKRxw=Kke#|>My4~e=@3q<OC#<6FLx<aWz$S@(Ba+xZVi)@)r}L24?|;GJ za&PqqBM*8;gBM9o&&76!OAsZe@NogY&?-uw4M*eO9`y(Bl$`Eg4co*m!#4XCtIhs< ztIht(u+6^7DoUG1L}`;%lr|09>`Nl+92y?6Z4o8=i-VS-t|5!1bJ#lay2WaH-6lDo zv5bhDtv36n4^N#wFk%xo4Gmj%Ih@X?MbZA!pk=7*)X+e;)o$B5I6Sy_V0f^5z%sbk zY8%<+@_HW@CC9IQf$$1nAbf%3^j@?mz~^=T^VRc!&uhB=cL3n5jo<&vYFhvR002ov JPDHLkV1nxX8xsHk literal 0 HcmV?d00001 diff --git a/css/images/+unlike.png b/css/images/+unlike.png new file mode 100644 index 0000000000000000000000000000000000000000..569916c5359394965b12f844c1a0faae14c32a3e GIT binary patch literal 7126 zcmV;{8!6<8P)<h;3K|Lk000e1NJLTq003A3001Kh1^@s65OB>l00009a7bBm000ie z000ie0hKEb8vp<bO=&|zP*7-ZbZ>KLZ*U+<Lqi~Na&Km7Y-Iodc-oy)cUY767Czti zWe-+D*zmEJY=HnGBdiF>5Lu!Sk^o_Z5E4Meg@_7P6crJiNL9pw)e1<Rh~l6qxMx9% zh+2zPTsZC@+^4mDdhhM+``7!t=bY#K&Uw!dfDsZVk>;Xm069{HJUZAPk55R%$-RIA z6-eL&AQ0xu!e<4=008g<d3b(wus{3(uWtYX0C3eVBofEr|AV?vCRYF;kpSQ#66Xs6 zkWv81E>y@A0LT~suv4>S3ILP<0Bm`DLLvaF4FK%)Nj?Pt*r}7;7Xa9z9H|HZjR63e zC`Tj$K)V27Re@400>HumpsYY5E(E}?0f1SyGDiY{y#)Yvj#!WnKwtoXnL;eg03bL5 z07D)V%>y7z1E4U{zu>7~aD})?0RX_umCct+(lZpemCzb@^6=o|A>zVpu|i=NDG+7} z<RYAxn<EoQ=L1a63;+Nc`O(4tI6si*=H%h#X6J10^u?n7Yw&L(J|Xen{=AF=1OO0D z&+pn_<>l4`aK{0#b-!z=TL9Wt0BGO&T{GJWpjryhdijfaIQ&2!o}p04JRKYg3k&Tf zVxhe-<BLB3GvROGi+=X}Kpy_vdhh^onn0PYz@vlxaba$Du2PQY%LGC(ZujRS{>O!X z{f;To;xw^bEES6JSc$k$B2CA6xl)ltA<32E66t?3@gJ7`36pmX0IY^jz)rRYwaaY4 ze(nJRiw;=Qb^t(r^DT@T3y}a2XEZW-_W%Hszxj_qD**t_m!#tW0KDiJT&R>6OvVTR z07RgHDzHHZ48atvzz&?j9lXF70$~P3Knx_nJP<+#<bWIsp%|7y8C1YJ*aWq(0~(+a zn&A+%!7(@u=im}tf$MM=24EPT!Wg`U2?RmN2oqr;I*1Wsj@Tm32p5@-1R`NbG?IX% zAnAw{Q6k02a-;&OLTZs+NF(wsauhj@TtNDe+sGg?iu{VaM=_LvvQY!n0(C&Ss2>`N z#-MZ2bTkiLfR>_b(HgWKJ%F~Nr_oF3b#wrIijHG|(J>BYjM-sajE6;FiC7vY#};Gd zST$CUHDeuEH+B^pz@B062qXfFfD`NpUW5?BY=V%GM_5c)L#QR}BeW8_2v-S%gfYS= zB9o|3v?Y2H`NVi)I<b&gMyw|8As!)~C0-{E6JL`^Bo4`v<W349C6F>n3rTB8+ej^> zQ=~r95NVuDChL%G$=>7$vVg20myx%S50Foi`^m%Pw-h?Xh~i8Mq9jtJloCocWk2Nv zrJpiFnV_ms&8eQ$2&#xWpIS+6pmtC%Q-`S&G<BLK&6^fO%cL!%)zF%0XKD9nFX?o; z3EhJpMVHW*(rf4k>F4Q#^mhymh7E(qNMa}%YZ-ePrx>>xFPTiH1=E+A$W$=bG8>s^ zm=Bn5Rah$aDtr}@$`X}2l~$F0mFKEdRdZE8)p@E5RI61Ft6o-prbbn>P~)iy)E2AN zsU20jsWz_8Qg>31P|s0cqrPALg8E|(vWA65poU1JRAaZs8I2(p#xiB`SVGovRs-uS zYnV-9TeA7=Om+qP8+I>yOjAR1s%ETak!GFdam@h^#<Ae=IoX^_&LPeX&U-BbEk7-> z)@rS0t$wXH+Irf)+G6c;?H29p+V6F6oj{!|o%K3xI`?%6x;DB|x`n#ib<gTP(_`y- z=?V49^$zLX(MR=d^rQ6`>hIR?(H}Q3Gzd138Ei2)WAMz7W9Vy`X}HnwgyE<W%V@fh z#Au_@NuwvYChmu4<285}K4z?M9Ad0A-euftJYiyKGTWrYq{ZaEDb18?nr6Duw9|CV z%*ZU<tk|r{?2b9roNJz8zS+Fn{EdaBMV!S-i#ChLmfDtl%LSHAmiMffRz6mFR`pib ztVz~f>n!VS)>mv$8&{hQn>w4zwy3R}t;BYlZQm5)6pty=DfLrs+A-|>><a9f>;~;Q z_F?uV_HFjh9n2gO9o9Q^JA86<b<B2baJ=iJ;WWdk#HqvSS7#e%p>v({H5aB!kjoO6 zc9$1ZZKsN-Zl8L~mE{`ly3)1N^`o1+o7}D0ZPeY&J;i;i`%NyJ8_8Y6J?}yE@b_5a zam?eLr<<q3^N{B+UUpttUi-ZsPqUmRp4KpJ$lJtQ;JwRxU^+fMW%|zP13tz+0-t)H zhrXu1BHul}BYxI?nSKZSp8Grc%l(h|zu|fE7V%C6U;)7a<pI5c8iBI|YXctynFOT= zH3f|Yy9O@|J{3X?2@P2va+7bs7xEkVV>8@mESk|3$_SkmS{wQ>%qC18))9_|&j{ZT zes8AvOzF(F2#DZEY>2oYX&IRp`F#{ADl)1r>QS^)ba8a|EY_^#S^H<bj`5GFjJZ48 zYPNEAXRK;$Qfy=Fo4A0us<?r8hxkSDmlAXnBnj<_<iyy-J&EIU0_SX+Go0j_RF-sO zuI1dKxfkZ?&dZ*6JXtkakbF3Wm=c$=KjniULQpRlPvxg>O&t^Rgqwv=MZThqqEWH8 zxJo>d=ABlR_Bh=;eM9<ahEGOy#xn^|QY(3p8Irjp^G#Mn*50ho*>Tw|Ih34~oTE|= zX_mAr*D$vzw@+p(E0Yc6dFE}(8<U61_v9n_bMxC3Y=unGqqI`4P!1MMFQ_YcTNqn- zxJbQ7TGTV&X8!8=BMX8Se7%scP`I$O*tmFE@!%rAMY|Rwi&GbOE-_tFx@351@X~$D zXv?ye{ZQgqQdRP5dED}jQiIZ^r9&%%S2UHWl*!9(uJl^DV-;bQWL58Km(^QVe<~N1 zU#xJfsIK_1M!4qUS59BmeD!&4+S=Yqx61A7Nb98QZmjoNzpqNYYC+Y|hVTuo8}W_h z8((co-gKdQYW0rIw9U%R12tha?OV*YtlRRTHly}>oqt`+R{gE3x4zjX+Sb3_cYE^= zgB=w+-tUy`ytONMS8KgRef4hA?t<Nq8e$u|zvh13xJP$S#h#CQrF#eVMeplsbZ>0j zufM;t32jm~jUGrkaOInTZ`zyfns>EuS}G30LFK_G-==(f<51|K&cocp&EJ`SxAh3? zNO>#LI=^+SEu(FqJ)ynt=!~PC9bO$rzPJB=?=j<Jb;mW2SDv7qC_VA{<bspqr(~y| zolZYJ)S29Q_e}hmYh6)Yy=Ozuo<A3K?o78|_sR3#=Z{_Rym0g)_hQ>6w@a-(u02P7 zaQ)#(uUl{HW%tYNS3ItC^iAtK(eKlL`f9+{bJzISE?u8_z3;~C8@FyI-5j_jy7l;W z_U#vU3hqqYU3!mrul&B+{ptt$59)uk{;_4iZQ%G|z+lhASr6|H35TBkl>gI*;nGLU zN7W-nBaM%pA0HbH8olyl&XeJ%vZoWz%6?Y=dFykl=imL}`%BMQ{Mhgd`HRoLu6e2R za__6DuR6yg#~-}Tc|Gx_{H@O0eebyMy5GmWADJlpK>kqk(fVV@r_fLLKIeS?{4e)} z^ZO;zpECde03c&XQcVB=dL;k=fP(-4`Tqa_faw4Lbua(`>R<o>I+y?e7jKeZ#YO-C z5d%p?K~#9!?3#Iy9%Y@!Usu7SmJ*g)wcOoW4{AjOSH*AzOb8)iAqNNsO0tU}l2s73 zvLLR2qKgWPoIwbXYZ5|$gk)kSgm8oa0R(cBIWzN~^B(hFeLdaJ^YqjG*+1TSCo_S` z<yE!CRDG-8x8Jw>?f&%d`JIyh67T8Hr}rSd2l)RH;Lw;MX&olC4iiH7iF(~i*p8F1 zEIX0T<~|q%^0U=ieM*16aC2WW{YWyMzCV@8-qV{*&FxL59%`y@P{~73-(OL^eaZRB zbmrdPzU1#Rx&B*RPmFO~FHxyfKTs?UBy7h`*tV01qId+erVbjgW!VYaaS{XN>g0T} zG^cJmk5+26Nca*jP`H7_5fax|xW2;i8?U`U;Y&>r9K3w_SCG;KDkRV$LMrOEOQmL0 zsnvH{wsTdvT$zzCl#cq70uBQC{(PZ$V!2wstz4~d^>v6c1{1}ECTd*JKGeMMgVrAb z$(I^&2ntk))MkVl`yv8ms9DaNm1=!)t#19J<9dG^$NX`CrBsJkD%ESs)mp~!d{j6H zR2#(L4ebx`Us}Ej5rH0BO$Q^fkNX)8+!g+&e6iHx`@zxgX2tsjY@#Tkls>#xuV3zX zz7&B%n+U1R5Yz*QYev4-hCqjd+d++boY~LnXh;Ma?+~FLDB!*2c!El``m;c)BXt-i zhHF&7!@l%4rE=w3&zDLBYUt?=UxFi-kRebSB{foMgf<8rBD6wiNuWZM3XxI}N4)Ew z)&>=5{6OP}22Te=#~uja24r<;8V0y|&QX6?hj>z=!U!*r<oXLU`wN9nI<A|r9VcNs z&gg)BKS%_De81<35800QiswsIXb^!S(BY7uYg(`fR0E!g@IxPbfeHk5z#^m`3!K;` zh%}KlfK74BHePyQIj_xM${!Xl<Mnw9*tTgqCIlQwAVaEgOpOXwWFhxs#iK6igOD%7 z5ti)u3K8g0U4@Ve&zC42#hwVRtJkeB+m3U@egO;LPdKjok(y=SDnnBgQVm&a!@o6t zw7K7xnm`%?qX=RPtTG5mEWrh8kwxt0K)B#4%D?|T_s*EfHDe}l!ztsqe(VHhoiUML zOgWeI$|n#p2nov7c-RDy-#GtXH>u#AH*R8741V+B56TNhlfpM3lo_(%M&{F44g0j> zA%EXk(Vp<{sn@Mfc|s&SAw~!632~V1IL8HnT&PThul87J6Lix}$RXcp5JnKhB{tpu zOYXh+G9I3NJ6)v$Dhk-yayP%Z<YI2S<Xil1++^;*;1aslZ^Y{Cqu$<2Iagu*?C&t= zoKtygcbPDRSj70Ti>sV>Sg?*`o<9Eq+-iNue;XjVZaptu`vYP?$c8`mV~~uLrwp!8 z=s4!ZYp$jD+2`@&cm&`Bi7#?6mdMahcic*;T)9~I{^7#+-#02?snp*LRH}DK9mP$s zQk#b5>Tra6Xu|iEK}R0C{x<8U{u|52oXvw@oynHX+o={aJU!zq?!4q8?z`bep1S2W zyv`0l0cMW_?pn*D87I*4qx%U&h)@t)5k|!LdgP6T!1Ax0h*PfOYeUneZ@c?mc0Do= z2G1O*klf}i>}Xj+`(uyOy?PBhT9#1B_7e^sv;NYVBsXk?LHLf42Mo9wn*tRg!-#=O zb*<-mM+8Cefzf?%5d2fkavt3ixc2b_vhe@{84(zpK)g-cx#L+e_G}iPayf6jxs!4+ z$FlLq^YVjp8g~>ys1(W=eC?o2fQe%wlP9@$F8@1r5}TfQx`DnP5_<747qI7ftQvbd zdXQ}Q@~3$Aif{AqVTbYN%{R002R~%<9lu4zF<r}_;+d;v(KdA&3ywUB7iP^Ozhf7# z-E<?HX3yraV~=I+`4_NZ_H1@7SxOL^0|vaeHCvANg5$bh_JlZQRKWfD!VTqWeZO#< zPq6Vi!jEjca0gFMJ)M<jjOWRdzQvnwb&)UTSbgRRtbJe(7T^GO42}e0Y`n-u8iR}^ zs3N<5cp1N#@lD?9E<*$+i1Ag3iek!LJ*=8Ei8Yfav*4pgvSPvnx>^?V^!XR?@^#nK zvwS%_9(a%)b04DR6Q98KB@&2%fxZ-N)20I;LfE-r5$%f>vEt-Yc<Bc}V*A2{q+WcP zAdC(Pu+oOQ?UL=!w`6kt|1&D!Lb3FH+ZD)gFjpPzq_Sbb4J(e2k&P4XVAc6wW7(N! z@aU<RvTbW0`Amkjryt96a~D$8-~*n7&;bIASk(!l0M{5K5q9^h+;#Cqv|j&9OfAId zM$nSl;Mp$u&087Rv4ba0_#)X?Uqe|oPfwdhaohIh0wDrcoOCj-2pWM5Xq|8teJ^aJ z*u5Lu_OMC=Y`y1RUi{wGRJyyVq_Y&dcT+74AY^z*7VP<wT)wa<lk2~ARKTfh?ye!< zqW6E&MivpFjDwJGvwHeCo)~`yOHaLoZEx+S+@E3f*w3==!3C5xh!}hc#sw{HLT#gz z#5D>hl0<lPJ>J6Y<4>pU;g!ULfSc8$8U)z-wQ*SaBIPYxSa;!t4D4zjkyAGT`zj>8 z=`|J{c@%BuoWs12f1K_$ZM^XBGg<n%&#~xZA7jm=Nwl6hfhW(LK=<l3$S6Lf3RP-D zDwA8++n1U*D&XE^YRT|mHfr=7bP+-}f?Om8SY14O?s!_qp24!yE@Ip39n|_WtQh}k z+8$m+6>!6tP(v)BioiAjIN*mCc3j4f06Wj>S(A9+^8W@4{BUF$46tI%7}i~Q5xpx` z@Z5h~M%#rK@zVFd&&Kav&5KuG!_s4p!3z`s%Z~j#^N%<JfDKp8qT|UGM8K;*y^(TP z_s~O$0b#)N53L2DO-wr5zpgi#9vyJ0G;p=!`Rp&qiNP+JuNrx<Z+wKGWYzSEJU0Go zEIEA|-CMdTCwqBf;-^?OcOG>h6cVEqekiFC;>CauVWg4BhIxh+T7Ep0Td(*fvCD{+ zWJ1H{U;l==hab-F)oTD)J9Qeb-gFZkEiLStzmT^VE@Ihn$Dw1`diOoN{_|T{{?#!= zz;l;fPRHX<vU>7l<{xzwPfwrDsxv3B;_OMh`Rm(IQFO>b&hsUO(!iX2p?JfnfOGl6 zPivMlR8Z_)xs7lQI&3t5q``|Mw#>0?>Ub8PHI8{_Ok?XSn+fYBo|$<Hcl_wTC|VKd zh*)`8s!YC=rIIV+^_H=-IjnpdFEfD1wlnA2bNJQw?nHYKgdr-98EEfd$(S+hn!k`$ z<HivTTIkyI&ZD?>+faID23>^bOUmgiw&n8FX=57}{GF?4f9!Dz?d_yq-bAUhhk<00 zS8w_`&tHB8Vax#oZZc?Y>$ayex&8&|>^^+3?YJjZ>(*PtL5|3M-{pP7KgQUe&5M_w z&73bB#~o)~!L}XUL_p6|cXG>wsl0jDYGNRYZR({BJbTueEI;8y?*Gb}JaXI@X*vE2 zJb3&G+;{wmEST_h-deK-BS%_rpbZ9i>XcJ)%GCzoDO1S4vI*U+?!t)WUmb%h0)#fW zfo9pUpJ&&@53~HV)97hiN3Ac#x^K+D%H`-@y@n0ny&4GzU1&7n1}dalvsczF>+_cF zd}bfb9-SyxtG6_}SdEfXjcDxb4ck`+Z3IdckUQVtjd}CvZry<N15_M>ljYePZ|1JE zrjpv)MT|m`=lQFq^XU2K@bV+8*tvKKol75O`;tf5vY>^5=U)LIw2b!zITfM@edUUi zPTm9fyz?k--!YU$#Cv5CuCG}7*<*Nh_H0@{^=Ud+tRw;on>X{!H!tP2n}0S0_h0}w zv#I8TuUq!Ie4%)FzEB*!RCZkVL-o2fL8@@!aLDiGllNF~OsI+w^->)c$&HZ&%0opU zlbtM{K9Rew`7!DKegvA=Zoizlvo0i6dH3#G7=qG!3Jnv*w6`p#bLlcxpEYq0;Azu& z>`Pywb^Lf*$Bkp<xbZCh<R|e|h!-dvN3i0glZk;+XE)_^7FRa<8HMfJS^v$MSmo+a zyYql6IbRKx$|^LkJFYjmT&W&isn$NU55Ug*EZhE|Wjl9CZS;O86;dOWL4-CAC1e!g z=?Kq6_<)Wgi~v-b!iJ^XGxjt#KCq;5vkR|d&LxxCyv1rnab++XTq&`%hZQ!m4mmt~ zsnvLK)^|y+e-0Hz#Bt1qE3c$yRV$U<yBX-{VxX&=HRqm(+Z<>4ifX<z)SD1G8nV_9 zXgl{jD%m{VU`Oqse6R}9QH<q!ZMC}f51#Pf=ZSsvB0M1yLWmE$p7$A7`1c8^z0poQ zbP>`ZLLVm-sKDR{Aj23j*yfC7OsJ~FUYZTpe4F{#{sgxkQeAu#_kLp{Z@y6{j$>ja z2}FP&hKN|>ga#EwdzRr~&95Sm(VlLaib2JVeKLX|f&hkky{@ks4W7}O>;~Ln&H97P zBI255KjOIVzX~BfdLZ4jgzx)_V!8b3bgutGFOZ^{g6!=khF^qGF?Ikr8a#t`V*)oq z1qKrdqzQ;HRGweT&!<db>zW-nkKe&PGbZu+t7&3F0xbN<!U}9$9iWU)AO*fQ2R|~B zdIaEu(P)4hMU@)rB#J<x!ibLUo~v?&!U?|bCtM*C?!EvktrI#76M<3*;rmAql&iP+ zQs1Ra)EKAek-gwORvh7Js7Dd52?&)y1uj}EEG>~?qcc-?`dId>>$&gTDJ=c^In2Lk zCfUt7AjS@T>`3FO2pL4UxHzGE$PIVDDY<`%y&CSGuigP!1PU(*1_6h7fs7p2yVv!+ zF9uR3!Z1u|trJ@71DnZ3ah%8(iXTp<GuPUl_k;=~6%4j6-&ur2I2tNM*s(x|byR2} zLmx*Q0zV=Oz~EDS`#B!J@*);oGK0*LHt=F>KfsA1Y!eYkFdkTVI8lI<<}WfR9U31= zjVCo?glh`%<=`p~4V9WT@9mDx|E$*PQ{p&IL{XG5#ti9zrphLY68S<g(U(g9eciH- zbzHG1Q2M#X2s<1xLUL7ztqq>i1kyt(2cbP`kwEAO?Kk=lQ2;vf2&kX{3lJ!*SYzpk zP#KH}2!v)J20H>N{{oX}88)UIesez82#_jl40=^)kUB!D@TI!#wiOD+(|7J_pIEKc z-vRef04FTVP85ozf3a=n_)4|D(sJBCl<O8=pa_&1ma7_sG(@J6lu9DJ$RJEiU?P-` z&=QP>AdIQU3M-Nbqma^|O@uN&P9$+n)EEPW(LqU@7;R!ybGz4P!?(k~zqeGVaeP75 zvZz_kqqVxd%yGSQilu>nE)<GK@7&d%_>%%Il?D>Ey7iI%eBlVs6JM@WYu_o92JTK} zvTM_sTwAU`|70fH-<rwxw`Ozwt-1buYc7{>ZSHF-J*Z5!zcribZ_Q@%BR<Py^R3xz zzBRkoar;v$lWptI=a+Q%?C$94?cJJ8rJwCfr8ne@rFp4LZhbnN`+a*yXC{-$weIfg z-CQh{?#cD%miF}aZtd#n?oMYjE4zAoI=XiE^mOm;*^$nq*AA4+H}x0tza1!7CKgKr zAFNbse^(qRCkn+<;?D*6u>O4E1HK;|Q>)jf<O{_g_a;*ddXuU7=}dM`GL@N|Ol2NQ zr3aPDK9o#l-l4w1ZE8>>KhKV`f8Xj&Cg*3f+26KzbZqSC>U^fBw{LMzZ{M<Pf8o~N zWNL9=D*ecgojc!3CQ}b}c6Y7K=L<i{WYTwbbak$KyS@FDzEtwTU0v-PcXhUJYVYiL zwzscu!9cluWq&?@-9WiAu2>pKRI0TP|51S7(|iBE`X1o-G*bUJ07Onv#&GSn7XSbN M07*qoM6N<$g7O;D(EtDd literal 0 HcmV?d00001 From ce003ab2b8dadfd1f712aab1a028a193872e9fe0 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 14:59:29 +0800 Subject: [PATCH 327/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/images/{+_value.png => +value.png} | Bin 1 file changed, 0 insertions(+), 0 deletions(-) rename css/images/{+_value.png => +value.png} (100%) diff --git a/css/images/+_value.png b/css/images/+value.png similarity index 100% rename from css/images/+_value.png rename to css/images/+value.png From fb6d50b99c05101bcdcf22d0607a2e324962fa31 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Thu, 9 May 2019 15:04:43 +0800 Subject: [PATCH 328/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/images/+value.png | Bin 3301 -> 0 bytes css/images/+valuemail.png | Bin 0 -> 3961 bytes 2 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 css/images/+value.png create mode 100644 css/images/+valuemail.png diff --git a/css/images/+value.png b/css/images/+value.png deleted file mode 100644 index af3597da00200666d71961e83d8b56f156c0072f..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3301 zcmV<B3>x!^P)<h;3K|Lk000e1NJLTq003kF001lq1^@s6lj$8*0000PbVXQnQ*UN; zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU;he<?1RCwC#TU(42RT}=!>FVjrKzGj! z)6*~mBQvlMy3PnZNDM?JG1*Coi-`hJ#D{&@2Unj^5`-s&L^1oY>VqUEUN;Vsh#R60 z8;u5okSv;ES;ciC%mth)&}=t-tIPiXUv;XhdwMQ9BQuabr0BYws&meN`TooKM_85x z)wXb&tdgM0kZP+k<ko3gHm|!EWKV<;;Pd&QP$=*(chcxuhmq0I-)AzJRfT*$nog(h zD(HHY`b!~l_?y)YBRbV!VwUELUl%k_J!+rIEC`tcOUaeV&#9vjKD#sjZ`e=SUP|}A zC9Ht^UP+^CGicMq3<w^>40z-?=dOw7px&~~V4x=0pV#$xC>ZRmt*!krvUu^CNMvzu zO&|ao(o@$BFiZn!CYjbmb47RlUM5#45=;s(4U-=dL;QX}T)%!jdhOb^`z~L;{8Y>G zmcxF{{}~Ph!C(;lHGb|(?-+*RGVr%!h;Tk+IP4KNft^!9rzR~>@S(UPi6O#1Q_Lv& zp381^sL7U2Sa`49?+f>-&nF>sBLfAafL8*t*(}j-dp4U};n%d}(q+ru4uyg_P1C?M zO=g4-g`GaD>pDm&OBq6qxaX5TNTt&O)P~jLV`C4-VzIw1YhK2Sr9p`aLi}=qidm|& z>ktYr5rt>&d0r@(z9O;cC5M5gt4U(Y8CjnHD=|crugJ0)O*BDm!d|Ea7SU1ibv9do zR4N67gZ(eY<BiAa>gvvrFx#3eTutF~FGJK#)QI@N;NUa$_4Ruj>gynk8d1m>Axyc- z!o!uBxX-g=2u<42K%qPEWH=fk9St|^HDEuKS7$)Wg(M5grP?Z+T~Vv1)^t&(L4q}g znL!Z58fiK-lD1~zb3@NV-#{O0OjA7mQDeNZmxNq5bc8dF-_=N>G`|LV!B&~!k>Pbi zL&MuvuUhq7BocvKF2|6h)QtMjLFb5>%p`^h8rH!@(lQ!=rPYB#>Z2e_F_PaR0@6Rp zn8Nqyn!YWa1(H@0_6q4CqVTd<bLlGteN)=tW7#l@>%}?yxVM38@kv@dLbKFKZ}1t; zRVS#{Y=xrv;d}^2=zZbZAK}c+hAb%&c1)z35AX3!txW7p9>-Gi!$-ecz4`;vmhZkl zzZ}1Lcu7OUIifAEooJCoMli8(0)vB>HjR&uKX}hQoqK6A1|FeMm?!qDFltt~bgMSK z+;4JqQ6i1=DB!_h2-4{k^!E?^Igv<o2Lgd)C=_B%ku1?@kgs038Xp@Q`@_1mYxa_1 zB0ECN$QSZZjpk?H6ngsoHH;iY+qSm0H@-iA{tZHff^Itk3<3m8$c(P`_O|E9y$y%M z>>&_rkU9~=s%;LK;=no4lkEl47SU+?4?q0(WiksAp;;riBDWURW+WPkqAI1)h=(B* z4lz^_*J=Va4o1$T4MFH&OUa$g9{ty@;1(pie^MwmoRETSBZU=Vq;a8;w^~}7R}Tyf zY(tIdmc)Ro*RE}9ZfX96I7ix%%jRqYiT{X;`CNX6lQ{*ilre+alb;SPAc76Shp%fW zG%vyF`ACg8jtU8Ro;_C$>g(!%%;s_{(AWngK~*doJsGH};fS1FFk}L8kW`4^EF2Er z9+)xQ4Ns!L>`cy6o=O(IOZ(dPSV?Od8yjD~a^=b<IWjuBrM0#7vrHz-=@B+8*omTa z(ijS0GTGei!H}kH@a~>Lcqcl4Q{XTIwSvt7WkyWfcGSgUfF5p_j5jtO%jI)WgBs$E z8o48>7e(jNSGCA<;n5>4RSZWoWkXKaPMn8<_~#N0_$Qo?GR-Q*Zi??ac|-gCkqo0h zEMS3pGmQCUfQ!c~XT1)Dx~~khGT5Huy;CzZ@>6~Parkh!k^|!z=k;!w-gPmjV+d%< zsHpVD%)FFeW*Cot+k!{sXZttnu&ZM#%x{IxgBxHUY=w9J^mllyNj+Q-yY_qqaPUjm zxMw%q>(1){e8JZ^(@!6VmEUeaB2O^}B;c{9b=b&#k9h9W_woLF8a&WnK~Ubj2!Fxn z8M;3E5`>OF0V`hzxbXBg{Nm)<ZfgqJrxcdtJPJ&kPb+b2=h92rcU+sM2NGuU0sK7z z|M;d%2G4#8J!_s~;=3(+2ec|uH+S-H&!y>QSM@D#tqofz+&lfxC!lll?&7!|yWxu! z_?vtJ-a9*`pEczih!+|ebCsK4u&v{M*nb?E_tTef2#OMT`fLw8{7|Aq(jQZLJVD~; zs-1!ps4@HcH58_aPnr20m373L#xnRdzn$$}_-#GxShE%OeM=I!&4wR@jo08=c(<vn zE5pYN04u(N%;rw}d`|6JAM{Ls&$($7W=P6eaoShT#IPeA%##nF=z13R6U3dcjpxue zA46xy`cf!Cybm4kL1H1c?^ypE&gKa84bS~oDF|l`QQNTmOZx;MihCBG{oZm|sBB}% z0GGB$*9^kDU5Qz1$wtEI{*U3ra4Yov^hemyRcdHoBjdZ`**TZoQbz-w3`a0_bd(uz z)XrC6_v8+Q+V63~4Bks}_SDI_;_L{e*VRUh?JA23d9j6IU+#VAeRve5bLX2I05+Bp zWB4K*CFVEWF{?4k9e}>^BV`)lphS|qDzB@H!id`0+B99hR5+V%K2XY_;EDotnY@;K zghKa9L|2jf!byGH4-YeB9)OMIQrL6{GK*a7x1E@T2xQxjqvIEmVW;5q@HCDC^+m^F z$OD0|CAYfXpdD)<N<8{LkHt)JW04K$@%?pb?G&ZwisroYs`=o0^7?jp_3G98NGm8$ zU(_sXfieY&vGD*xV417y#4Lx_5b<7s2be$<pM1qchW-r@I@*WQ>vh}he#Jo0aj!i@ zKGC7Wp|&FIW>k#9@sacGUjWO(Dw+T`;8K>PRsNSstrO?IJO5NP7JX|;!;%t+a_fW~ z6`R@K#2nZVucqFT`yrFB%NrPynV^uvvJDH2jEvl!N~iCViA3Uq(b3W8)h?D|!a}nj zw?m_H2hNBnfp-dAi1x$7!&?%Grfx2B=)2h06$*t0>gwwL%~ckaJgoUBa=6VjL<u_w z;$XR(e`q%DzH#Hms+Dakk4Zx}VCmAtr<Z^Jc_-NsGB68j5x2|X3I5nFI~G2l&x=c! zF70e?Za&88dEye)EVZ|_?K}Vd`9su6)%MPZG512G^3ls-(|dn5$4!SU6!t)%h8-w1 zeos%&M|a+N=kvq|Mx<Q9U=<=GlS-xH7cN}b+tJzaOfV1t-LNYpD92*lq!f#+AOu#$ zvd+?eGfe@NGh%}CGD$zRv82w6V=7p;TxC#Ov$P#fQzs_yZY=i8W2_Mf1{tab1_riA zqLDLbDtbY^r-BpOvW-TgBW>+%FZT4DeRXtnjCTxGAvKLewW>@ok1E<lep~_1)!lY| ztLI>s&MfIy=}`SEyYJI8$?HN+7noIIP-#YDVn0>2>1Dostr%Hc16OrATeURx91`E} zx67$C6mCQxaq{c0KM#k)y$$sZz0{9V?>uhW*)LaRponQylNG&i@#3zgrlw<P`TwQ1 z9tp;{%G@bsnE)Y987P-;I&qCEHJypaX1T@8VoKsqwxKp1#H!L)vYRS1!Nui1pPM?G zj5%J$dB?KXZMx;JB-mtzNjqqpR%r_NLpq@Gj-5Mq?ya@!);<zhya=C}TsKYL7xRFM zt-TZAyb4C{=~SAm|0eX0x3sjh93~HpN>}Kk%1iJvQn_$m=6DHsv+U7i83)B$&LL5q zvf)TMu9br{LIY1dvC;<ndzS6&SfZ#Uob$8aca629C6WrKJw?=H4wA{_ir(Jd{js{( z$@cd4!%9d=7^L$T1uPWa>UZ_02r6iy$x{XredMmuv9T>pP4R9V;4?0y3x?dn2%0p# ztF%KU(1<5W)tN=6HDhU>Eki1PU)Xa{Rq7LLh@;`IC*-V6s_GEwD}yV`V@IU>cQrR| zWL(%nq25jrcq9@zvux?o?!}91fnK33JN=CfSD$z^u!JFmb1BpedMT61F>w`hh%w_= zuB^*tv&)h5Q5<v?!do0CA7BWRGUrHE4(~<OIUV$EoM;?9iFvAsQZ8p9S{trChwFH7 z(V|8FA>yae|F4V1PSUSK=v)EUg<6zUI}(TtBS_pJRd1qEUQTNZ)C5M5l1P^9a-wC8 z-_L6c1Ofx$+S*>C4}EKSOUtX#STsp=<a)P!fh*#v#@Ce-&-S^fM&b*rRsZO-%8+WS jGNj6oYWubA{{jpEVH<Rg7TGQj00000NkvXXu0mjf#${kI diff --git a/css/images/+valuemail.png b/css/images/+valuemail.png new file mode 100644 index 0000000000000000000000000000000000000000..98bb67b29174203606242c1ff6e678a44209990e GIT binary patch literal 3961 zcmV-<4~FoGP)<h;3K|Lk000e1NJLTq003A3001Kh1^@s65OB>l0000PbVXQnQ*UN; zcVTj606}DLVr3vnZDD6+Qe|Oed2z{QJOBU>8%ab#RCwC#S__mE)tUb4R#jK`%yduB z^gMe&0f{^kP@GkH_#(QxoERU+>?)h6fLV3pCabcL#UyKV_v|ja>K;SPS$72=OJZE( ziYL1p3@Skq5!5rsgCZaqL||a1hn`2zOh4*z_rJHQYr1=S9`Oig&7q*7yXw|`eE)a< z|NH+cg>#P6$H_a`X$VdO{Fy$q{Fmch-B1(-xts~p${`pGLe~TII|p6U0`2YXSE{-; zR9jQKjD9a<jK!F$2Ee)EIF3y>GX+q}4WfKPFT`bcT;YmEeKYEXIrLM~LZPdUljn%y zvBj2Oc>!-6nwU6~@6qj*i%Bu@ojjyiHZbfex!WJ(-gmAt=9p$KW!a8O-%nVU^<;m4 z|29?C*rZ7<I}(Wm&BZ~ax*BvHgiXQPy^hNP90(X}aB%R9fmG_|nwpw>E2}CQfg9F! zUC~rl9?es9*s#DIft~8XBCxPs_=FMs*(pUP^Z)g%u6Vy0cu6zn-!GUWjOlO-HYXd~ zPJbqA5;Q~T>+88c5YT^403R<0uvV6F1T=Se<XA_?UExUN+bu2ea41y4xMyzLcH{>h zWnCNbg6S4Ruaw~?CSV>e!4u;+5<Hil%mc>-n29AQ`EebucUI6pFY$;<(K+rLEYCQ_ z>pwppVWBX&MrjDKfdX1Y3mB2g$|_V<hVJj^JjR&9QUvmgnyRLYcW()UP0Lc!>GY&b zCi9J^rpA?#a6}jM7gou)72m}<E|wy`dtlQbWMzk}sLJcoP=Zs=u;Jvkr8bKA!`$7= z!Heu8&O5g72+TWSd*F%ox_?eihYRkB`MLL~-rN+)9U7ZiE?}aaU_4aUX-HN&vb|Ur zmoxG<f+UXZ-3NJ(YYflW5Np@ud}NQbn~xstIMSa=t!Zv*+UVmW2$=`1GjT$KH8?aB zC;zf?%9&^084Lw0EYpIfY4QdrC&?*%CZwWOvJ+gVB8^1^(*pr?b#=A%_4WP0FpQ@H z^jmy<XJMKq(nCXRXlUrx$&)92qasvMk;|I0kxenonE(h1Svsf}e}11;wvy+tbelFB z8XD#WL!rqX$2u-crBZUo`aYP{f<_?6BjNDu5K&ivN<orbhB>^Q$2@2oX&L<K3%9{^ z$lBzI?pU+}SDbYv(xx-9fcR<c5F&#X(B$GQ(=OuPCqL8?(28+f_rgKSLSAW!H@A|g zdWUxY9J;oz2w-B{J#}?;R|!`k7)@$HvR4K+&kv6#r#0;`e*EL5cy{-1+#Qq!erwLc z^RcTiHA3pdK2=<1G;iRYEnmf7x1WQ5TDB5%Sw8%I`YD6h*dq3D<^pY7&b7qk8HWyi z{4fE0KpSqz7e%AhrV-HUv*dRLV+HL6xI*UYx(3VUqcD*eu4K^F`5qL*Q%>|rW>gHC zZsa{R*s3s`ZoK%v-@>Y$&!U|*VTj|T%1Ieq9ZyjaR?L-YGsEHV-}LtOCVjJHvY93I z^$n}inVgVl(kiN|x+*|2+8Sq~<Zm>iIE!J*sRLKa6Pq?p4A+0@CwO9RE9#kf(qlkg zBq&mUyDVm;D#+Ew$Pdr<8BB?UD*UacYEnkY`8uwgg0~G$_CX>GA-yD_pk0)67zIql zH*k*pD%XguCB{qBd8LfxR*2cb0vDPQ?G(DdAPdNfK0RG5h!rSUu5H;c`KXij<)@ni z${a$tS2GriRro_xR#x7f*Qn#gPD3x3#nmHR;-ghog}MrHivXy&b&e)&7j9o_6R?lr zrQbY`U*&96kjvp}95>Iq8)sJ!;LTsJ!}F;G1+Q!HSC=nFeR3y$wBs4HQE*X>TFg9S z4ep*DCXkEg%4n|H6Fc$myEdX-uf_bSw_wS%X|M<1#xvWV!M?y`TzJ-3uw?2K1VnJ8 z_Ga&PJiKKiJ_rR63*UtME?$HxBAZ!GNhu?fCc$KK6V-(2N*~~W9>@|)jY8Uw#;~@n zcVR6hCN?Wrh%$f=Q@t|L$_L$!-VIp3=}lAzIQ$q#0L+_q7yf+SB?zk&;R}Xxlpvbw z476>$58K$e`1UpTBSN9qq2wZ3Z=n6<-I#vea`5i0`0jt)i(kjC#C0=T(AD-hR_$rW z!n)_sTE~m&MQc$*QB2_({QavBqHRGdu9$Kbj6f94Y7f?KUWd27I1iUkn~F;2AaP^| zp5Cz&;rQoqPTy{<dTj-EBp<`3Ypy^gw@0`fMYx4B>PN7e^l-lqu-F#k$rMBD!{-0~ zI=;E%XE<P&$##u`a|HB2dN($|x4Sr7r491J`&+S~>E~EH<pPpX-j1Q2W3d`s_=Ppt z_@yLfY<~^YBiErN>>%v~F{^qO=C)pr`&#EBbKnQqax{sHuJ}IgnG-@z&*0Jjc?erR zO5=itQ1NhNSuH#ROD<i5#UK3_5~>^d_0V)&ebE}cvZoEZRX2D$)&SbxxEE~dFL3Ai zQF;H&>>Mn4=TGqbtPXtra{-c|d_w9%YG6$p*1;m7a2#h$*T57L-JQE}NQ@Dhpb|IA z?1X^?ZROrFH47UVOGRVr_4wM>r|_?PwqnKX#RxJRZ@;|@GiIy+C%I{yaXYp=upEQD z7w>QXAy({qgo0bpP1#3F6zweSIK8++k)t5UB6QC2eC_*q^}u_0u5%Hd*lE#@QlXlC zh($CUIGzNX(JXvuao=MEaUpZH!eF9|EA(~f3OW32Ne!hOgY&D%m1&#B=$Rogndui` zS?eX(wEH`F@$ehCq2@KbkU1Z>H8zqmaYIpG$IDo~Z7te@ci}%5uEv62ts6T};k?X5 zxLaTFa-3Y^BXorR7*Bt711_z$ka0xFA~mHE8_7Lnt=~;ei{!%xIGfGN5~YlSWzlme z*{H@BW-rC975gx#ma?0C@cviPmdm&x(_E@5=HQ~UXBYcm58!w>PW|z+p57)UbI!us zaoOwF;_-ufaKW*om=m9iXq7>MlfXT&0oSa*2h*<Jhxad@ih*|@g5^w1kcr|>VPIv7 zP9N1R+E9RT(y!q4k8`-}+yE5E^@D2aAok=Y;d4=j2@WIUST36@V6bBw`EsPM?L11z z^ArF?Ha2tqgLrCwxi0(g#JZWdJ#pMkG-z(|=n6b}-Q8%aC}S=%K-RX)YHP8GQ1B0M z!+CSD`t3XMo%o+&&EgrT4UosnrLpU`oAFloT6}NHRM!h?m2$2Drj1e_^)xcEuzN`8 ze6J1ZRWrAr6ip7*!j;yXjd<=b)^1&c^XnhRk``4Oe8;AL!LC{Vh?zCUNPxL~B;d<6 zuhc8uZPv_&eGff2F!-3vMoKaR|0YjTnWPspBR&Gp1X3kF+;#?NLGHFMy(c#cxOwz> zD2B!7-GZtQx8rzS9A`9Cg4=E_(a=L+z3n(KD122KzkKW8Fhr^S2LoN;{Rt%LY(y8V zG*CqXSQnr~n(>FVb=dpiyXYd^RJ#waZ@m*ctT5U>xEGiHWIgs~reo=)HzM@$Be?Nr ze}ttk+=Q?EbP*ovJr7?#(?D4dp|~|<ftyS-q^c0g$LSv!7+B{6oJ=NrMVcplafzFd zAfM7Y6>TqCOssA`?pXW}xMA|esH91o1bj{lV&Uv>;f|&RzPD*E&Ux$sB+t7IH?s~r z`^IuSaG(?IZ?42&w7rXN>q#tIe>FBA5mCGj%P)Ko)AfzG>PP2d!P7UPt9m8oSErC= zt+?g$mmwakMC&E%@zRao#F-zzjGyj!4sRwFW965>hN+dTtm9O?dN$|0DCr;;t9^a_ zC;WQwp1u43vaY`Fp=fnf^NYn^W8ZCz8bydD`iFSr;a05fPPv6AVs*=;`|*pLzK=O| z#9)h$Uk_GFRRx#z4^BQ(XTv5JUNoEQK{7i?pjV)=CI&v(g<et-0ZKZmoIac|MKPU{ z13DM2Xhwyq$O>*>wj2G~G^qyz4RoHHoft$leGkf-i%<?4&!K0a7g?H)p~nz47_rwW zJ8ucFSG*TEshWJ)z&nq3UOzB2l<|FVZEfv_o@7r;Bpg{vKPMF`it*o_5EeAh)O0@1 z4fVJHlbo7V--4h_6h0}BMU~E7NU@aW1Z0dD7jvI8hyf}Z(X8alhxLeuhM#phGC`o= zNrs688&Mr{`*cL0P#YnXvuS$|ji{|jp(zq>@Sbou<-zrnBe!lNvp1E=@3~xde@{<O zW56&r_zdpqP8x|sVoIbsvbv$6VFmZ{*g__ct%Dd@d!#EFkrMw74E}$A<mc_V360pB zO!jOdaGxS~yPvKMmn-Q+mU8DK{eAt3P$*>9M5B5(lbb-HeVA8SbM$;;JW1n5U#H0L zPkaZBG2Tfw8uv<;B6jJjj)MmezMCFO_czCzKPY;lA&zJ?I!O8RcaI)9>X0>7g)6Hx zi+q?U012(gPg3zOU&!|Zg#QR~B-j%Hyy&`Tyh6!Y+NSWD`*7EF4Stb~56@GkCWMLm zoRWJEi&G9^Ad&3ZUQ<((h{a-C14dxvV|$T#P<m%ku=~41hYq8$p<xyIW=*;aRrnhB z`ID3PSITf1Qx@h+Dsl2YHhQTuZ!l#<$~-dJQ800k3$=Vv%~ny$wiyQ2)vtMjbKf}f z1r`6A*wq$c5YRQL=X-m5U)j5N-%HieC_z>)<u3OEk2X?*O6v?YH8%cjN5`>F>S&<0 zrsjv<fI$ha0>4fyK+PAL#a~f0%0FhxPuh0uvBKjB0LKHj9IK1m4I8dub1(3rAky;! zR+ln+_`7FhE;X&JD>z;PA=oR{l+EROZOiUTr3U_)KyD64BJ16p#u@v?6ET3MYH1q# z(Nur`CC85)yR{`ApHop)xq{9&(xg;Hbpcf6B8Joad^F8Zm>L$T0OeEkiKQ&|-@Bm2 zvw-HaNG1UeFM999-Hq_wfp{Az&s^6fisZq2U4a)HJ)KGSS*B%DB5}*%!-wYvL&1JB zz%R?KO&k9~ukt#5*zwNJ9Pd)LMZ#6fsIvtGbd)9(q(!QZtFk#`s{4kA|CWYJYOm<T zKlPwfR-03z&K*(a&<G-%<}RkEs!TO4$1>=D@`RSAFlG^m?wc)cQI}$@6L3qn%yQj@ zP5fat-DA_WF4MHKw4)<5?xU2Ly+tz2q5jv7iQnn>gHQG|?$gI<fIrK}{|PVv0R(V_ TlHlHj00000NkvXXu0mjfC1|6X literal 0 HcmV?d00001 From fa4f294cabd4234b22400b917b8f508f4712469c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 9 May 2019 17:01:08 +0800 Subject: [PATCH 329/382] =?UTF-8?q?Alipay=20=E9=80=80=E6=AC=BE=E5=A4=84?= =?UTF-8?q?=E7=90=86;Note:=20=E9=80=80=E6=AC=BE=E5=8F=B732=E4=BD=8D,=20?= =?UTF-8?q?=E8=B6=85=E8=BF=87GAI=5FAccreditNo=E7=9A=84=E9=95=BF=E5=BA=A6,?= =?UTF-8?q?=E5=BD=95=E5=85=A5=E5=92=8C=E5=88=A4=E6=96=AD=E6=97=B6=E6=88=AA?= =?UTF-8?q?=E5=8F=96,=20=E5=A4=87=E6=B3=A8=E5=AE=8C=E6=95=B4.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 209 +++++++++++++++++- webht/third_party/pay/models/Alipay_model.php | 63 +++++- webht/third_party/pay/views/alipay_list.php | 4 +- .../pay/views/alipay_note_setting.php | 2 +- 4 files changed, 256 insertions(+), 22 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index cf9dce05..07a44c19 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -358,7 +358,8 @@ class AlipayTradeService extends CI_Controller //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->ALI_payType == 'refund') { - $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); + $this->send_refund($item); + // $this->Alipay_note_model->update_send($item->ALI_dealId, 'send'); continue; } @@ -415,7 +416,7 @@ class AlipayTradeService extends CI_Controller $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 - if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") != '-biz') { //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 $this->Alipay_model->add_account_info_forAPP( $GAI_COLI_SN, @@ -521,6 +522,191 @@ class AlipayTradeService extends CI_Controller return; } + /*! + * 退款处理 + * @date 2019-05-09 + * * TODO 线下收款之后产生的退款没有通知 + */ + public function send_refund($item) + { + // raw + $raw = json_decode($item->ALI_memo); + $parent_order = $raw->out_trade_no; + $parent_trade_no = $raw->trade_no; + $parent_note = $this->Alipay_note_model->note($parent_trade_no); + // APP 组的退款查不到原始收款记录 todo + if (empty($parent_note) ) { # && true === $this->Alipay_note_model->if_APP_order($parent_order) ) { + // $parent_note = $parent_payment; + // 补充字段 + // $parent_note->IPL_orderId = $parent_order . '_B'; + // $parent_note->IPL_currencyCode = $parent_payment->currencyCode; + // $parent_note->IPL_payerName = strval("''"); + // $parent_note->IPL_payerEmail = strval("''"); + + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + return false; + } + //订单号 + $orderid_info = analysis_orderid($parent_note->ALI_orderId); + $orderid_info = json_decode($orderid_info); + //根据订单号查找外联信息 + $advisor_info = $this->Alipay_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + //查不到订单信息 + if (empty($advisor_info)) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + return false; + } + //更新正确的订单信息到记录中,以这个为主 + $this->Alipay_note_model->set_invoice($item->ALI_dealId, $orderid_info->orderid . '_' . $orderid_info->ordertype); + + //添加支付信息入库 + //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 + if ( ! empty($orderid_info)) { + $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->ALI_currencyCode))); + $currencyCode = mb_strtoupper(trim($currencyCode)); + $ssje = $this->Alipay_model->get_ssje($item->ALI_orderAmount, $currencyCode, '15015'); + $USD_amount = $this->Alipay_model->get_USD($item->ALI_orderAmount, $currencyCode); + //更新还没有填的客邮和交易号de收款记录(商务订单) + if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { + $ht_memo = '(自动)退款号:' . $item->ALI_dealId . "\n. "; + $ht_memo .= '原收款号:' . $parent_trade_no; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") != '-biz') {//只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 + $this->Alipay_model->add_account_info_forAPP( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->ALI_orderAmount, + $item->ALI_completeTime, + $currencyCode, + $ssje, + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_acquiringTime, + NULL, + NULL, + $item->ALI_dealId, + $ht_memo); + $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } else { + if (false == $this->Alipay_model->if_biz_gai_exists($item->ALI_dealId) ) { + $this->Alipay_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); + } + $this->Alipay_model->add_account_info( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->ALI_orderAmount, + $item->ALI_completeTime, + $currencyCode, + $USD_amount, + $ssje, + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_acquiringTime, + NULL, + NULL, + $item->ALI_dealId, + $ht_memo); + } + } + //更新还没有填的客邮和交易号的收款记录(传统订单) + elseif (isset($advisor_info->order_type) && $advisor_info->order_type == 1) { + $ht_memo = '(自动)退款号:' . $item->ALI_dealId . "\n. "; + $ht_memo .= '原交易号:' . $parent_trade_no; + $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; + $gai_sn = $this->Alipay_model->add_tour_account_info( + $GAI_COLI_SN, + $item->ALI_orderAmount, + $item->ALI_completeTime, + $currencyCode, + $ssje, + $item->ALI_completeTime, + $item->ALI_completeTime, + $item->ALI_acquiringTime, + NULL, + NULL, + $item->ALI_dealId, + $ht_memo); + //添加汉特的订单提醒 + $this->Alipay_model->update_coli_introduction($GAI_COLI_SN, '已退款 ' . ($currencyCode) . $item->ALI_orderAmount); + } + } + + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->Alipay_note_model->update_send($item->ALI_dealId, 'sendfail'); + return false; + } + + //添加邮件发送记录 + // if (true) { // test + if ($item->ALI_sent !== 'send' && substr($item->ALI_sent, 0, 5) !== 'send-') { + // 客人邮件中的外联落款 + // $web_code = 'cht'; // 默认cht + $web_lgc = 1; + $web_code = strtolower($advisor_info->COLI_WebCode); + $site_info = $this->config->item('site'); + if (isset($site_info[$web_code])) { + $site_info = $site_info[$web_code]; + $item->site = $site_info['site_url']; + $web_lgc = $site_info['site_lgc']; + } + $advisor_detail = $this->Alipay_model->get_advisor_detail($advisor_info->COLI_SN, $advisor_info->OPI_SN, $web_lgc); + $item->advisor_detail = $advisor_detail; + + //给外联发送通知邮件 + $fromName = !empty($parent_note->ALI_payerName) ? $parent_note->ALI_payerName : 'Alipay'; + $fromEmail = !empty($parent_note->ALI_payerEmail) ? $parent_note->ALI_payerEmail : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->ALI_orderAmount . $currencyCode . ' / ' . $fromName; + $body = $this->load->view('alipay_receipt_mail', $item, true); + $M_RelatedInfo = $item->ALI_sn; + $M_AddTime = $item->ALI_completeTime; + $M_State = 0; + $this->Alipay_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'Alipay note'); + // 通知客人, 客人邮箱 + $customer_detail = $this->Alipay_model->get_customer_detail($advisor_info->COLI_SN, $orderid_info->ordertype); + $c_fromName = $advisor_detail->fullname; + $opi_email_list = explode(";", $advisor_detail->email); // 解析外联的邮件 + $c_fromEmail = trim($opi_email_list[0]); + $c_toName = $customer_detail->fullname; + $c_toEmail = $customer_detail->email; + $c_subject = $currencyCode . " " . str_replace('-', '', $item->ALI_orderAmount) . " Refunded to your account, booking number " . $item->ALI_orderId; + // 修改一些字段名, 为了和iPaylinks等用同一个邮件模板 + $item->payer = $customer_detail->fullname; + $item->payer_email = $customer_detail->email; + $item->total_amount = $item->ALI_orderAmount; + $item->payment_date = $item->ALI_completeTime; + $item->payment_status = "Refunfed"; + $item->currency = $currencyCode; + $item->invoice = $item->ALI_orderId; + $c_body = $this->load->view('refund_buyer', $item, true); + $c_M_RelatedInfo = $item->ALI_sn; + $c_M_AddTime = $item->ALI_completeTime; + $c_M_State = 0; + $this->Alipay_model->save_automail( + $c_fromName, + $c_fromEmail, + $c_toName, + $c_toEmail, + $c_subject, + $c_body, + $c_M_RelatedInfo, + $c_M_State, + $c_M_AddTime, + 'Alipay refund receipt'); + $this->Alipay_note_model->update_send($item->ALI_dealId, 'send-customer'); + } + //添加邮件发送记录 end + // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 + + return ; + } + /** * alipay.trade.query (统一收单线下交易查询) * @param $builder 业务参数,使用buildmodel中的对象生成。 @@ -538,7 +724,7 @@ class AlipayTradeService extends CI_Controller return $response; } - public function query_pay($dealId=NULL,$orderId=NULL) + public function query_pay($dealId=NULL,$orderId=NULL, $debug=false) { if ($dealId === NULL) { $dealId = $this->input->get_post('dealid'); @@ -549,20 +735,24 @@ class AlipayTradeService extends CI_Controller $this->AlipayTradeQueryContentBuilder->setOutTradeNo($orderId); } $response = $this->Query($this->AlipayTradeQueryContentBuilder); - // return $this->output->set_content_type('application/json')->set_output(json_encode($response)); + if ($debug != false) { + return $this->output->set_content_type('application/json')->set_output(json_encode($response)); // test + } return $response; } /*! * 查询退款 * @date 2019-04-24 - * @param [type] $dealId 必须, 退款交易号.out_biz_no - * @param [type] $trade_no 必须, 原收款交易号 + * @param [type] $dealId 必须, 退款请求号.out_biz_no, 或原始交易订单号 + * @param [type] $trade_no 必须, 原收款交易号, 和order_id不能同时为空 + * @param [type] $order_id 必须, 原收款订单号, 和trade_no不能同时为空 */ - public function query_refund($dealId=NULL,$trade_no=NULL) + public function query_refund($dealId=NULL,$trade_no=NULL, $order_id=NULL) { - $this->AlipayTradeQueryContentBuilder->setTradeNo($trade_no); $this->AlipayTradeQueryContentBuilder->setOutRequestNo($dealId); + $this->AlipayTradeQueryContentBuilder->setTradeNo($trade_no); + $this->AlipayTradeQueryContentBuilder->setOutTradeNo($order_id); $biz_content=$this->AlipayTradeQueryContentBuilder->getBizContent(); $request = new AlipayTradeFastpayRefundQueryRequest(); @@ -589,7 +779,7 @@ class AlipayTradeService extends CI_Controller $request = new AlipayDataDataserviceBillDownloadurlQueryRequest(); $request->setBizContent("{" . "\"bill_type\":\"signcustomer\"," . - "\"bill_date\":\"2019-04-03\"" . + "\"bill_date\":\"2019-04-25\"" . "}"); $response = $this->aopclientRequestExecute ($request); // var_dump($response); @@ -779,6 +969,7 @@ var_dump($response->$responseNode); } //修改订单名 + // TODO 支持转移功能 public function note_modal_save() { $data = array(); diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 27be3647..150e3c4e 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -18,7 +18,7 @@ class Alipay_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class Alipay_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class Alipay_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class Alipay_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class Alipay_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -144,7 +144,7 @@ class Alipay_model extends CI_Model { $sql = " SELECT TOP 1 1 FROM BIZ_GroupAccountInfo WHERE (GAI_AccreditNo = ? OR GAI_Memo LIKE '%$GAI_AccreditNo%') AND DeleteFlag=0"; - $result = $this->HT->query($sql, array($GAI_AccreditNo)); + $result = $this->HT->query($sql, array(substr($GAI_AccreditNo,0,30))); return ($result->num_rows() > 0); } @@ -175,7 +175,7 @@ class Alipay_model extends CI_Model { ,GAI_State ,DeleteFlag ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $query = $this->HT->query($sql, array($GAI_COLI_SN, $GAI_SQJE, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, substr($GAI_AccreditNo,0, 30), $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -209,7 +209,7 @@ class Alipay_model extends CI_Model { ,GAI_State ,DeleteFlag ) VALUES (?,?,15015,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + $query = $this->HT->query($sql, array(substr($GAI_AccreditNo,0, 30), $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, substr($GAI_AccreditNo,0, 30), $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -242,8 +242,8 @@ class Alipay_model extends CI_Model { ,DeleteFlag ) VALUES (?,15015,?,?,?,?,?,?,?,?,?,?,?,0,0) ELSE - UPDATE GroupAccountInfo SET GAI_SSJE='$GAI_SSJE' WHERE GAI_AccreditNo='$GAI_AccreditNo' "; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + UPDATE GroupAccountInfo SET GAI_SSJE='$GAI_SSJE' WHERE GAI_AccreditNo='" . substr($GAI_AccreditNo,0, 30) ."' "; + $query = $this->HT->query($sql, array(substr($GAI_AccreditNo,0, 30), $GAI_COLI_SN, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, substr($GAI_AccreditNo,0, 30), $GAI_Memo)); $insertid = $this->HT->last_id('GroupAccountInfo'); return $insertid; } @@ -370,4 +370,47 @@ class Alipay_model extends CI_Model { } return 0; } + + public function get_advisor_detail($COLI_SN, $OPI_SN, $lgc=1) + { + $advisor_signature = $this->get_advisor_signature($COLI_SN); + if (empty($advisor_signature)) { + $sql = "SELECT OPI_SN, '+86-'+OPI_MoveTelephone mobile,'+86-773-'+OPI_Telephone tel,OPI_Email email,OPI2_Name fullname,OPI2_FirstName,OPI2_LastName + FROM [Tourmanager].[dbo].[V_Operator_Info] + where OPI_SN=? and LGC_LGC=? "; + $advisor_signature = $this->HT->query($sql, array($OPI_SN, $lgc))->row(); + } + return $advisor_signature; + } + public function get_advisor_signature($COLI_SN) + { + $sql = "SELECT top 1 dbo.agenter_user.Name fullname, dbo.agenter_user.tel, + dbo.agenter_user.Email email, dbo.agenter_user.mobile, OPI_DEI_SN, COLI_OPI_ID + FROM dbo.BIZ_ConfirmLineInfo + INNER JOIN dbo.agenter_user ON dbo.BIZ_ConfirmLineInfo.COLI_OPI_ID = dbo.agenter_user.AU_OPI_SN + AND + (dbo.BIZ_ConfirmLineInfo.COLI_WebCode = dbo.agenter_user.agenter + OR (COLI_WebCode in ('EXPCH','MESENLLA','traba','wayaway','guias') and agenter='VAC') + ) + LEFT JOIN OperatorInfo on COLI_OPI_ID = OPI_SN + WHERE (dbo.BIZ_ConfirmLineInfo.COLI_SN = ?)"; + return $this->HT->query($sql, array($COLI_SN))->row(); + } + + public function get_customer_detail($COLI_SN, $ordertype) + { + if ($ordertype === 'T') { + $sql = "SELECT mei.MEI_FirstName+' '+isnull(mei.MEI_MiddleName,'')+' '+isnull(mei.MEI_LastName,'') fullname, + mei.MEI_MailList email + FROM MEmberInfo mei + INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN and cul.CUL_IsLinkMan=1 + WHERE CUL_COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } else { + $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname,GUT_Email email from BIZ_GUEST g + INNER JOIN BIZ_ConfirmLineInfo coli on coli.COLI_GUT_SN=g.GUT_SN + WHERE COLI_SN=? "; + return $this->HT->query($sql, $COLI_SN)->row(); + } + } } diff --git a/webht/third_party/pay/views/alipay_list.php b/webht/third_party/pay/views/alipay_list.php index faceb099..ced5d78e 100644 --- a/webht/third_party/pay/views/alipay_list.php +++ b/webht/third_party/pay/views/alipay_list.php @@ -162,8 +162,8 @@ <?php $show_send = ''; $class_css = ''; - if ($item->ALI_sent == 'send') { - $show_send = $item->ALI_sent; + if ($item->ALI_sent == 'send' || substr($item->ALI_sent, 0, 5) == "send-") { + $show_send = 'send'; } else if (strcmp(trim($item->ALI_resultMsg), "TRADE_SUCCESS")) { $class_css = 'btn-danger'; // $show_send = $paytext[intval(trim($item->ALI_resultMsg))]; diff --git a/webht/third_party/pay/views/alipay_note_setting.php b/webht/third_party/pay/views/alipay_note_setting.php index e1bcc4bb..d5ab442f 100644 --- a/webht/third_party/pay/views/alipay_note_setting.php +++ b/webht/third_party/pay/views/alipay_note_setting.php @@ -1,4 +1,4 @@ -<form action="http://www.mycht.cn/webht.php/apps/pay/AlipayTradeService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> +<form action="/webht.php/apps/pay/AlipayTradeService/note_modal_save" method="post" id="form_modal_orderid" name="form_modal_orderid"> <dl class="dl-horizontal"> <dt>交易号</dt> From 48a24c26b9653ba293fffe901eba575dbc9847f2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 May 2019 09:28:22 +0800 Subject: [PATCH 330/382] =?UTF-8?q?paypal=20APP=E7=BB=84=E7=9A=84=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E6=8F=90=E9=86=92=E5=A4=96=E8=81=94=E6=A0=B8=E5=AF=B9?= =?UTF-8?q?=E6=94=B6=E6=AC=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 75 +++++++++++++++---- webht/views/n-header.php | 2 +- 2 files changed, 61 insertions(+), 16 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index ce530df9..168f2891 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -757,40 +757,50 @@ class Index extends CI_Controller { continue; } - //检测是否是APP订单,默认不处理 - // && $item->pn_payment_status !== 'Refunded' - if ( - ( (strpos($item->pn_memo, 'China Train Booking') !== false) - || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) - ) - && empty($pn_txn_id) - ) { //APP自动出票的订单不需要处理 - $this->Note_model->update_send($item->pn_txn_id, 'send'); - continue; - } - //根据note信息找到订单号 + $get_order_no = $item->pn_invoice; $orderid_info = $this->analysis_orderid($item->pn_invoice); if (empty($orderid_info)) { + $get_order_no = $item->pn_custom; $orderid_info = $this->analysis_orderid($item->pn_custom); } if (empty($orderid_info)) { + $get_order_no = $item->pn_item_name; $orderid_info = $this->analysis_orderid($item->pn_item_name); } if (empty($orderid_info)) { + $get_order_no = $item->pn_item_number; $orderid_info = $this->analysis_orderid($item->pn_item_number); } - //找不到订单号,设置为发送失败标示 if (empty($orderid_info)) { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); continue; } + $orderid_info = json_decode($orderid_info); + // 仅自动程序发送提醒 false == $handpick && + if ($item->pn_payment_status === 'Completed' + && $orderid_info->ordertype == 'A' && strpos($get_order_no, 'China Train Booking') !== false) { + // APP 组的China Train Booking-开头的订单号 + // 发送邮件提醒外联核对收款金额, 不写入收款记录 + $this->process_notify_APP($item, $orderid_info); + continue; + } + + //检测是否是APP订单,默认不处理 + // && $item->pn_payment_status !== 'Refunded' + if ( + ( (strpos($item->pn_memo, 'China Train Booking') !== false) + || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) + ) + && empty($pn_txn_id) + ) { //APP自动出票的订单不需要处理 + $this->Note_model->update_send($item->pn_txn_id, 'send'); + continue; + } //根据订单号查找外联信息 - $orderid_info = json_decode($orderid_info); - $handpick = empty($pn_txn_id) ? false : TRUE; $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); // for trippest tourMaster 2018.05.28 @@ -1457,4 +1467,39 @@ class Index extends CI_Controller { return; } + public function process_notify_APP($item, $orderid_info) + { + $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype); + //查不到订单信息 + if (empty($advisor_info)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); + return false; + } + $opi_email = !empty($advisor_info->OPI_Email) ? $advisor_info->OPI_Email : ''; //lussie@chinahighlights.net + $opi_firstname = !empty($advisor_info->OPI_FirstName) ? $advisor_info->OPI_FirstName : !empty($advisor_info->OPI_Name) ? $advisor_info->OPI_Name : ''; //lussie + //没有外联信息表示订单未分配 + if (empty($opi_email) || empty($opi_firstname)) { + $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); + return false; + } + //添加邮件发送记录 + if ($item->pn_send !== 'send') { + //给外联发送通知邮件 + $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; + $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; + $toName = !empty($opi_firstname) ? $opi_firstname : ''; + $toEmail = !empty($opi_email) ? $opi_email : ''; + // $subject = $orderid_info->orderid . '_' . $orderid_info->ordertype . ' / ' . $item->pn_mc_gross . $item->pn_mc_currency . ' / ' . $fromName; + $subject = "请核对收款_" . $orderid_info->orderid . "_" . $item->pn_mc_currency . "_" . $item->pn_mc_gross; + $body = $this->load->view('mail_templete', $item, true); //$item->pn_memo; + $M_RelatedInfo = $item->pn_sn; + $M_AddTime = $item->pn_payment_date; + $M_State = 0; + $this->Paypal_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, $M_RelatedInfo, $M_State, $M_AddTime, 'paypal note'); + //添加邮件发送记录 end + $this->Note_model->update_send($item->pn_txn_id, 'send'); + } + return false; + } + } diff --git a/webht/views/n-header.php b/webht/views/n-header.php index cb06b1ad..2881dc99 100644 --- a/webht/views/n-header.php +++ b/webht/views/n-header.php @@ -8,7 +8,7 @@ <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> <link href="/css/nav/nav.css?v=20150723" rel="stylesheet"> <link href="/css/webht/jquery-ui-1.10.0.custom.css" rel="stylesheet"> - <script src="http://www.mycht.cn/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> + <script src="http://www.mycht.cn/min?f=/js/jquery.js,/js/bootstrap.min.js,/js/navigation.js,/js/jquery.form.min.js"></script> <script src="http://www.mycht.cn/js/jquery-ui.min.js?v=1"></script> <!--[if lt IE 9]> <script src="/js/respond.min.js" type="text/javascript"></script> From 08a2e3934a4dca3be1643e9dfba8f756f268f65a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 10 May 2019 10:25:33 +0800 Subject: [PATCH 331/382] =?UTF-8?q?Alipay=20=E5=A2=9E=E5=8A=A0=E5=8C=BA?= =?UTF-8?q?=E5=88=86=E5=95=86=E6=97=85APP=E5=92=8CAPP=E7=BB=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index cf9dce05..67cda313 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -415,7 +415,7 @@ class AlipayTradeService extends CI_Controller $ht_memo = '交易号(自动录入):' . $item->ALI_dealId; $GAI_COLI_SN = isset($advisor_info->COLI_SN) ? $advisor_info->COLI_SN : 0; //CHTAPP订单添加记录前判断是否有记录,以前的APP版本没有交易号,只能拿金额来判断 - if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP') { + if (substr($advisor_info->COLI_WebCode, 0, 6) == 'CHTAPP' && strstr($advisor_info->COLI_WebCode, "-") !== '-biz') { //只判断前6位字符,CHTAPP-fr CHTAPP-jp等各语种都属于APP订单 $this->Alipay_model->add_account_info_forAPP( $GAI_COLI_SN, From ef804fb1d1170d4200f8da5a273e25f0d268aaa0 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Fri, 10 May 2019 10:40:23 +0800 Subject: [PATCH 332/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=9B=BE=E7=89=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- css/images/train/a-seat.jpg | Bin 0 -> 2406 bytes css/images/train/a-seata.jpg | Bin 0 -> 2968 bytes css/images/train/a-seath.jpg | Bin 0 -> 3233 bytes css/images/train/a-seath.png | Bin 0 -> 3233 bytes css/images/train/b-seat.jpg | Bin 0 -> 1652 bytes css/images/train/b-seata.jpg | Bin 0 -> 2229 bytes css/images/train/b-seath.jpg | Bin 0 -> 1826 bytes css/images/train/b-seath.png | Bin 0 -> 1826 bytes css/images/train/c-seat.jpg | Bin 0 -> 2285 bytes css/images/train/c-seata.jpg | Bin 0 -> 2882 bytes css/images/train/c-seath.jpg | Bin 0 -> 2969 bytes css/images/train/c-seath.png | Bin 0 -> 2969 bytes css/images/train/d-seat.jpg | Bin 0 -> 1660 bytes css/images/train/d-seata.jpg | Bin 0 -> 2253 bytes css/images/train/d-seath.jpg | Bin 0 -> 2531 bytes css/images/train/d-seath.png | Bin 0 -> 2531 bytes css/images/train/f-seat.jpg | Bin 0 -> 2468 bytes css/images/train/f-seata.jpg | Bin 0 -> 3078 bytes css/images/train/f-seath.jpg | Bin 0 -> 4652 bytes css/images/train/f-seath.png | Bin 0 -> 4652 bytes 20 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 css/images/train/a-seat.jpg create mode 100644 css/images/train/a-seata.jpg create mode 100644 css/images/train/a-seath.jpg create mode 100644 css/images/train/a-seath.png create mode 100644 css/images/train/b-seat.jpg create mode 100644 css/images/train/b-seata.jpg create mode 100644 css/images/train/b-seath.jpg create mode 100644 css/images/train/b-seath.png create mode 100644 css/images/train/c-seat.jpg create mode 100644 css/images/train/c-seata.jpg create mode 100644 css/images/train/c-seath.jpg create mode 100644 css/images/train/c-seath.png create mode 100644 css/images/train/d-seat.jpg create mode 100644 css/images/train/d-seata.jpg create mode 100644 css/images/train/d-seath.jpg create mode 100644 css/images/train/d-seath.png create mode 100644 css/images/train/f-seat.jpg create mode 100644 css/images/train/f-seata.jpg create mode 100644 css/images/train/f-seath.jpg create mode 100644 css/images/train/f-seath.png diff --git a/css/images/train/a-seat.jpg b/css/images/train/a-seat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..b39e19de259e5feb30eb6ddb09dd224798484856 GIT binary patch literal 2406 zcmbVM2~<;O7JgX>F$5(-00r9^79&gYUP4|-B&8t<149F{jSHJ0d6WoQOo9ZlDwQ+F zjDi)a2*o<o5eBgxkR{3#(rOEqkyAuj-S9XlD%6g+jFx5|2<n{U>6tVCdGDP6zsvXC zd;fcX`;dJM@RXWVSpX0n9RLu4*USC@ph)r*IRyX)z@y?Y0I-kYwAn_ZPQYSm3{1IF zn~5+LS~bfg*Rdcb$O6K`O**+E2Qktzkq=cGA^oTJPC8Ac6w=pmWuQzaMzU2=+w@4{ zw%8=awj2dtNe_RI7G@Hd)H*d{l+#S=T#Z3s64K|u1?YZO%%aogOpG}~x@eY_wqCZD zCf4c^8kfllR)7#hgJC8V!i8Zdh{gsXHVZ^QI2Z~MaA5(PN1I=ClufV95+q0>=ef|6 zkUpPOettePpTpGZKV(6CK7SU2%??H_f(->4qudm%G59PXNDzZUuhJP+S`BR$QJ$&I zGYaWwq%TuY>twQ5z;CUVT0NWBoVCH2fV>Xlt=5L50v*CiKn&VEy#hhaeHNV2+Wj`s ztRWhWAWpABFGZd!(JJ!Ph{hN#5z<i&Q>ju4Boa2C4U42~NXnP;Aczk}fFiC`90I~z zku(xoz<8T)gha$;OL(DD5flPJQl2P;7b@oSAr2TSmPGI+3%=1BgHf(gAPc-Ily}~j z_nW=~u^y2dwfZEjHg}-|)@EysT0^#0M-wN)G{!oWMybs=te(A|m)S}Xy=p6>jMQt@ zw7L2URBz!IiMb#YAq7ELDw@kX6a>Y59>n9YAvQZgOrQ5v{y#Nip~0|bo8ygUSrDNe zIJ<q-`sm@+@E{s=V)W=}*r$NSa}5tDZRiMM?4v+2K)~bi4tRot17Q&X{hf#e0?~;~ zA~}&rWEb+>av?8X;<98h+11s}&DGW0%gf9A-B%0a=;-K7cJ_2}@mx-&P?x__{I46k z4WJN#0AM!`LjkZ9432`ap9f~&2`mnS!MuJ#a1Ize0qaP7Q}$Bp0$}hMEFR;yh=`k$ zU@<tn13+225^^QDiTdd52&!Ye{FBCnk53oFHBI08aKwor2Ch5h4fvN(_7Q-LL#Zh^ z3J?y=B<`|p0zJtD9HuBfOHzIA_l$aT`l_UVG57mBbl?;GpcRyKVO^><U}n9`i;>P> zI-AmS9lt(l2YO!kjoS`|bzh>!mtFnhyF_W+DOYSRfv`6texG|T>3fFlz^2Oun;&KO zl!Sf+0*18Xk{uR0i#k@cqD%i{zvWc<z>x1mKudj9d&YJjIE@w|tbbJF)!aul-Q2J# zXDDuO8dg@^C5T_ytoLpIv-`jZl@nZJi8)s5E7SSOpBx8AC*8-ZDR7TeCMiow^C%5k zVnXx49_@cjT{Ygh2xNi*Yj(eQcjq%5zo#ndaWW_9HoXiS=IxWZnOjL;_DQ74^xNjo z265tMO;AJq;p>y!ckX%BF7I7KsvimyxYTJ9f=~1no#=?L-Dh-;hCds8T84d!DS8-P z-E>EHZNqjJ^&|7NLCxB5pxC_Ybmi}Il09M>OB>Q@arCB&W$AYtJ0}Z!XG(A7AVOB_ z#D<k@mCZfK$8EeTv&Itm=%}(kBW81LkkdP3+lEy;R^@wMUEdboQX91quB>>m<w(@y zMnuh+tZ05%Rl*!IMpJ}o+*I<@s*=>??XgF4)a;h)H%fAoyE0=QbP=ci06()nkcVW& znF|JS|K63_T4Jei|M`7Qy9G&WIsZeq+jR2jz~Mc?&!=P03I{8)F0>6qUOBd+_DtiG zJ(q0bsZ+gEpJI=mxgSj)-7Y%*Rn{3>;--p&{WEKp<@$I25bnsx7zxWGFRmS1w<Yzd z^ZAdf8CUH<?>b1PWJJ>bX?^eRMO|fbzn;9cJUTJW*_h^mn;0UK3ga#(eO~#Cugz*} zXo)Hf9gU5O+{Ybji5cjxtYxnEKD>2ncM6-DNF)(2sD}G4b{vaR{pFsIucglHn@!qS zQ)6LFbm3Ck+To^yBZ=h=jTu-I+hN_ZKMpIEaHQqg^pA;#U73F8hCf)``*mF-QrA$- z`&3W}*ZbGkb+obk9a?d?w6ph~+z|?`7x5E-bJQUk<Np5U`cp;Lz1Cvhq07l*^*6;+ zBo=<H@S2CM>bmbOW6DI}OnPT>%4kbmL$z!qr~T5MqQk3Kr<Mvh2YkE>**;CmBkG7~ zPbbM&mJ=nbVQgS~I&tp>kk&XEJ8-)4ANQA=I9Xi|ny|l8j^qt|6CW=jpEt+nr4y}A zu~#Plv}GUM{IG$ryyo1p_{xH1Nw-hs;al}jbnuOn4W9(~w%uY+TS*8(yuT>)TdSAz zMy~7|tH<Wa@y|fc($=%C2UGV@D|$c3Q^vq4?pN-VuTAc9i|19EYc%Nsf5P|w)&Kk+ z?F+{pKTVy$U%J#G*<JYE<h9x_`u%R3Kj&R28as4y)a3nh<pbYffwJ=M*_)AsRoVW5 zb!B&JI@w39EBtYo*Kb3d>ba%tQATlvhbNU&uk0?@6k!*sY68CeJH@rT!llrXF{+(l z!MLjlzmD#VF8G^oY0T=jQJpyiyEKiO*XNN@hQ0F|ZkKIv=S=sFz9%y~?>+Av`IS|L LQ_O3Z*oXfE+xBak literal 0 HcmV?d00001 diff --git a/css/images/train/a-seata.jpg b/css/images/train/a-seata.jpg new file mode 100644 index 0000000000000000000000000000000000000000..d68badf56cc3525f0e13b8d1d93784c7431e8652 GIT binary patch literal 2968 zcmbVM2~bn#7QQzL5doF3iy|>%$|4~NkPtN3kVOInWiwJxh)IwDSxCaJLaSCmT)?7M z1tfx6c!&x@4GJg-h+vC=sYta{k$uspAeH3>6nvd=I&a>YduRUtY~MNOKj+N+Hq!-| z(BlN50KjBg1De2Rni&KTv}kTbJOBbPHG2a9%ydD;VRE^|+0ITR!*F=woqP;eEVPT` zNbGPJtR1jnW1NJ;jo{0XJNdf=A~I^Eq6&o+@W?2(BMZxtQ2Aj3w*)EQH^Iw~n-IYz z@lYFGkQ?Hh<Af3+U(P|s2_r=^=QuKI&bhPtJj=F2A?H-&5o8o)78SXTwFOBPOZiAg zjJ+)vi^Cxa1Pso>kwCz$L*lVGyd75k5o~b|&W;3UJQ4YcP--+OFVxwG#`uJ#zL8O% zl8TLu#l+fU#L``MI1-68>jRIsRcqMF;ze>!oUKT<X5IshFXKuD61hMuLe6^R>=Z}K z$tZQCA5#!YSgZxdU#yl;IGfj;woLBB{~X2_wPk+s626@eUnY*0a`|fYHS@;m+Wj-o ztfD#^=gm@q`cXKMG%+_?$QQ|(G%`vp!SDn;XBrJp!V@TTJdRGH6LB~a))h-}q*EQR z1V;*;ft&a7MOy}uL2$sj(kVDc9F9&T5vdLoBAsGS#5!TA^aWd{NG9iqxcqrs!7T1a zTgpG$I#Z>5j$ADD6N@9~J77zgST2@@i6uy?F9B)E7KnJ_See!A^L)&f#+M3W_&kPG zEJV)L*IDodd{?X^7UxRGVhME0T;5JtER{sW5$*9fJl>Ux`ee)de`;o@4#sY_IsU6z z=2_|voINhIzWTB-JbaOQVx;QPm>C9^&NV#1t5%O7IP(<P55QqCm<9~4p#fhESO40Y zaJZ(nj+U0TmX?mL&K&9LEM2C%Y^jdEzJY<h{>l|AR;)B%AaK#5MN4#+nCR-7m>MDs zO&0|J>tUuEKxhKiz&<F503ZkuiU4P7fkO4305w4H^9BJlpfLC%O%S4HLP0fs7O4dg z4RDbz0Kz~h1On64UOXp+fKZqQfY5`l*2gVE;SKgvT-THs8WA+TIrb-7{qjoN{EhEY zEgWj28AKB`I0%7gz_qmJ9fJ@Almc6g^VZYge4Cz&HyDk&)8g|;-w<we4YgDHo#Ogk zd#b}s2cQE5)saIHz(%0|9GHxS1Jx!_AVdd(YDyt3u~ZbSPW1X|6mtX(+9kWb*(<1X zD$ybDapII){9w|yQj$VPcu>MTOIg1Dtxj1D^#QwVPgLx=A>5j6a(d*Qs<Emk>3Y-D z(oN4er8kFzRJkg1r)lK`dvatfASbsz{`;1XOcJqf!=0|l+@8~lYs-&qG9U&HDO->Q zeK!%mYWS%}cS$Oihx3CTy1v_=)zGrh_;`cV^?da@_rKCYN<y~c7_fct3lG?589`As zL&?xHL#Q=xy%7n;o{+5iwYirJ1Fed#GCTYu{E0D@?-`L5U++)!@1YR|3hQ^(7FV?s z7r(YS&%AoNC)|Q?ly*vv>UipUkzeY~lpBoFR6s$^kQ=AG!?xKOB|MpWCIx+2X&0;m z9Z?qvOs011QRIympYeonfnT2|1i!DZO1jiY>LfL9t_gnfJ}D~SvY!{&Ni968T#x&M z$4WS#i%E^>`qlSQ@Vy^im?}*@#{GXL-9oHx>K!N$ervr$%5tc4^^ZIyA6~KPa>lAQ zgH8;X+M5H9mRgZb4@qOYrRLjx1TDo&spJnOQx!SWk4HvycoQxvT=yh>QhTIWvB{%H z!G(jl=%`bqCGDp&|17??>ZmY(0I!>_Yb0|U3Rm>CL;MfdE*`b9N=~??sG9)}Ka>47 z-5O}sw_B8%p^rWX?!1fhij1+gR8)~(u^iu)6~u+;Z8$K%&;R%O^dt8U%ifpvX){`V z%|-TBtIF0D<(rilW$Q=X>%^p>zAC&}n4H+uDgCpssqbW2tIhToubWeU9%Sx0-DTET z_uSYl4V`v>>|mC}Ws7!ASnp5C9```yOJD1uE9k9XUs4qPxTA?ARw-gzh9_$Xtjafp zB4CKze5}sg1E>q?KBx54O6V!Fuou2svNqB2A>=Hq_GHe`Zx1+*6KlpuuG1|8mqV6s z&J0TJIo|1J_2|eig_%vh0a}PdB+)XZeGocR-nq{#U(ZiP-EK^;Cd2^MtA|`#d=gd7 zXb_hy_+>qJbT38B-YjTbk$<gtlks)$?HLD#_S`Ugr3E}b^sF-DJ?5q__5%8ZJoNBB z_o>V7QRP+3rTGQ7(OGd{O~gMChA1tE@)+BXEafta#=JZP*WKj)zdvzoaby|pPT;c$ zFCU{1h+YlWdC&q`MWr=)ig(@hnDFdW4vEl(w!y8-t7P!>8h`*<0wN59erfx=qhG6w znAAev<z9;)W*Z$6^)Vys&v#6-eIySNznFbLZWAsX7|ax?bl7LX-JOwRc?WzVGYxMm z<^5F$FMd;Ea@X(5iMxNYi$f!=Y=jhYe|z|ant<E*zEdU|718ZO4-*oj&MbZen5M7$ z+FP|k;2#K$(vQ*<+g>hg^{=*^0_lTvXm4-jU2!6_cCfsI{o(d>e|dR$PW<|_rK;Hc z7s(0TYi-hd7*ZJbSST&V^MvhX<{B_8^R-{gJ#;laHlhWwK_AHF-gCNf?(wc|t#{56 zoNS`H-O?UhDbq?#MTT0q9xixGuQoczP76%q+_-cg1lw+8(wNrT(0J*)8=ZPjx?W4P z%lii`+*54dr`^Utexw|K5#oit0<YP6#8)EH=&0E3dl4LT@96bnN>^^>l5p+m>z+gg zva`J@?3LcMXW^)nn+d(AHR}HU+|te2Rb%<jmD8^t#s_3SC3YH5UhSFk%<1urXE)yT z8yG2GRX>zfJo=p86e|`Sk5EmJqlX6iU!F2pYdsQei1%sUR$BDI^pP_5MOpqq^9ygT zDE=yYIxv#dJK@<lIHivzjs+PLhTF=9pI%gAWF~hU#+50>&zghEEfY<}=!&S?L&Z6I zH4hK9cICuaR5F&;%jjm!6(k*PSDHl|`;M=ZSGmpDt-Nt$S4LDqd%<4cV%g)38|OCk z!m>VC`hm_I33fOQs{=3Gy8niF^3C1|ZagFiuJ9NfyEDGZSiiJJh<OS3+!M0hx!dN6 zz@1fKy4Sp}D4@iI>0Y4x>BjAg_A|hb6VC_UC1s^gx@_v~ZU~x4t-Jr$Zd=l;y|I5y z1^4ihmL2WEQ2uRr<V5d|YhTs5j08O@%xLRyJNr%4AFN|mT|!k`+j6<*aqn#gDoS5L z&z8pfOfrm=O%9F8H^>j5{|mRnJ{Lcc@%P}%lO|t^8zz&2-&7Wl2X{<vn|-2BDoHa> F{sYkeoaF!j literal 0 HcmV?d00001 diff --git a/css/images/train/a-seath.jpg b/css/images/train/a-seath.jpg new file mode 100644 index 0000000000000000000000000000000000000000..40c5e70a1778f767984a7051bcab171cba5f81b1 GIT binary patch literal 3233 zcmaJ^c|4SB8y=B;=p;)D)0pgx8Dks!o-z{C7`rhuF)@pov5c%kWf!Sv(Nu&ISwdx} zqNA+ogk;H5h%BMf`9`NY-ydJ!`+MK_S$@}j-Pe6T*FR5^lcOC_SXLMS008X|SUYpa zc<!erxQ+W)n2V9-4!fB)Sf&g07&8n<Cju-8R6iofo{aM+IumgOR&WQ=7y#e}lh9Zu z7Uh7%Q^{JmEsRz;nZ}I<0F2GTX*hf!kqPo6`jaRo;Dv{cU=WF50(R9!X`^UX!~oKP z2s+Uv!V!&+2*eu_z-Fc(<8UOGfJ|iKK;h&d3IiE#0{+g6<j%LYp<vK=2s6+G{EsLs z$_Zper4vEAS~{9|Z5Rxsr>6x&=<4agG(d1|7#yn2ef2b92&Aqa60Q&W@qoG6=!9cP zXKULZxwtD6Z~&7@LqefpVPRTfI$Bh^KNMzYXt>1zhih^XnhX|&i3``HFcg0>SQ8m| zI*G<4Q7ND;Mw}ltglPiiD*dMfGVK>Fh4G_J+=fBJaWp7QOM9!NpFkAq|3k^-UuXu? znfR~X|4Gb1vuH%9Gm$|Jq2sv+cT90B6%A=cC*qh?I+{ui`q@RN04kHp2%yqHRxWxV z6;~34Kn-K4e#fIwNP7x{iKF0&_SPm~E`t_{L_q2pTIt#7>1f*;T5-E>qi+b)v#>ze z*xJDL^mS~kbbiKKQ}H2WB8B-gmhf*Z?6<L7Rv^>3nXQR*QYevNOQ(`S-%Cc4eyas; z^IN_jv4r1hf!qEz7RnU^-8$I+I_RHUT=#5Ef7zD1_+@+|h3j@Y*VfIpU9JFtkfgn} z1v-3i?vmR9G*#wti0reVa`wTYl+bpmijtz+nCtZcal&jVXg?c_NSwKuqQzEuP!tfC z3}Q<yUBA0s?Vy@FY*0sis1M;$^>-KRTm9afd#~)hOu8&?965byEpqzuG^=J|Grh+w z=3A=plgB4)?Ce}Im<OJvb#-;g$;tiwXyB<S-iJ3@9yIek$;#RpVtM}5qW|?HH*B$1 zEEelzVX$mP#(QB`v9}?xZ8bylOI15!M(^GeDpcGFl(B|5@}&tG@4T|`rg0XrQ<*&- z>7_LnOPiM#DD!D-i2CyBWtq<`eRh3)J&spE2?9Z^7~sxd1C6;><Xye$V<#IxBoaF( zPWP(Rw<e!k-dz9K+H&P0!@9*(HriYcHFFO2&D8s9WWRSqRTToXwz=}|tk2YJMNo!m zE`JxUS`?U?D0FdQ%_5cs;vJThe<v96(CG@z%P~T?vH$rbn&Gf>=8_)yxUiP2HeyGD z{42W<1SkXR;2>%TX^i?}`@}iCuu*KXeRta#%%l~MSi7t~MPufqL5}<4*!sq@|E9Z~ zM0t5RvmtWB`J7PgYfmwKhwaVd=KOIt`)4LC8`I>Bs_io5;|P`%fl<Q2m6VheV6fv6 z@<0(_u*6MALC`%FW-1dWdXw!Npq=ry?4?-qKtt4tbUC9?QHaE?OgD4>n^KzYu?;Nb znY5G?m#>R)oS{B~M}@9qIlu9x?y!+@AN|C(wzel33Vo!$o2aH7r;_T50<h_fx=7ZY zMG0iy#fuR$-TU5b@Gn*Dnd9W=6W;e1`*-C%y5ko62hemJHKQ+D@AWYB@Kw{OZ(mu? z&dyCaIYwb0KCjMh2S3^TvW92+KfgQ{ZLohAtMwFcdAf_*o8Q4r*Ie@;DRG%j>{dN{ ze5B4$PNwC~ZYvtcy}R*G>kC?5T<3K6Ux4~pCfW2ofWxA{h9l~G`wYxN=Va6(SKlAq zF79MR8*S>$)hSP9v)NqjJx4AQZu9w<o`Si}RFCfCxkk<Y3L87Cy=~n2zGqQEU9FN} zjzRGFOwSFL+@n;0cIM^Fk$->NY-zC^?msQAAf{kiN9f3^Ke6^S&3F+(n32%@H1{eV z>*)Brx8P6><@Ld<%|a4No{iC7M?TLF)l~X-O}Ur&Kf9<4@%k$nBY8N_IM*}^S^em! zh_u$*>_egRgWI3EcMsoZ2<VJUVI@634AqFosF3g0O0Eo45D$5et-R|q%;RV7kdRS& z5Hfpet(HD1Y%o%P;=(nq7tLAgi~CeOYiYQqSf2Wb)orSXs*u?Mm0}gv%FG{wpT{4G zguCB6E{Tml5gHmgR83AooOxPitlsC>_}A`({r3W0S;pSS9wkdUw0E}ec(MC5J-t&y zVjrZXT%$ErV<xR>@xyB)_5GuqrZ$Xkh#xx%4u>x-EtyY$-B`}e&5h>=wutmhM|b6! zSou#L2J9*nHwjSTlzHCIYEDStO9kocOSd&so}|k$raEzId>ny4V=YUOVITIImwD7U z4%V}lr*7C~jPnYJ%ZqluEcL<<D%z!McvR1gKT6T3j=a5f#VAZ{kDf!b8FN5^ugA5_ z+i*F1ZQ+dogyPDY&(6*+DJe<YqtBi=uj$ckH{9NFR@uKZC$6%kLj`tHW~Zk*HROH2 z(2kD~Sw6qLVnH~tu%C>8lOIo!=wUOzwnWSw_l_is7q!6?ca`~-59g((iSLFd#3qpZ zQZ_a=40zxYOiT6Uh>^h7$U9G)@WT(oy8K=gyA;+XKz$nKJe9*1M(V9ji`8)&J0f00 zO9k3^0?TDRW`}B^WkB=VCAZ3B*YdapAxM)qZsA7R=%u3vZwa5<>DO_<;kNKz4n}jw zV;6AO=OfZBYab_`^ys#Ly76qTt^MTlZZW2xcS^O%$)klAo-GHiI^lUu@;0Dkc4MB& ziBGdH#WUja==lA|xlVj+y4b(69htGewjdwF(tpVlx<Y;ZK=*jRilkxtsbGUz=>T6` zbJ@!7(;0j8DZWR|J3qE1NoZtZ%DjO*XDm42Kx|b&=0N<aJufU)z{P%V8jsrwFD<Zx zZ=mVpvrGE1qq_Fbf-Td-J9A*zSJ|pAv7!q+!zt2GB~J-$fF%ciD?G;kyuCtO!GtH< z$o;Nwb2WKLW_lM`vo}k9;@)|vPbq>lKX~u%BSkurIpZWB@#WKeE&RhsV@yn~a<HXY zn?=;I@_e;w9UigE?yv6Xp}e!(rq}F`d!+2AZz}~u+TjL~>og~T(xea{f3Z%yFmJo! zO*O&8O{z~&m-IRmGkwNpd;9wK@$!J%n&SoBLKue7Qv-7&^&Yu0g$eu9qdu?nlr2v^ z!yn6;$TouG>R%<ieBSnEUb?txVgb@)xq}E10LXgq|7m0u|L$H?fn{m2WIPaQ=9?)n z@ktQWG3nqaK$){BAPx^I)fC-$9FfN%XH}z?!qVpA!*UTM=d`T+{+QH}#*8n5t1nQ_ z@hHw{opz!X?*jF{uy&I8ZM;Y@q<I(L(M?RhuB=ASd8t_u>5z5%XxkA71yJr&^LU%+ z58Hu)R`FG1S4-2^k4P$)$BEO%Ht!IC0~qYNo*8t2nsJj<viN?{r;wxkHG{ROt<~xY z6$kv(j<ksSruC?-I@@xJN|~H}-HS0F^3_Tz9OkdN4^U@#frWGogj2FlRFOwbpAASf zs+5bx9KStp3}nNj&L(|CoXasl>X%fx7LnowUC6_SyvUZTw3B{u>PiU@pPHs7O6I1Y zr_0)1I9Y<-<vqo^9v!6`v}aE{L%Qs}&HcipodMnGYD~p@-1<;Ly>d66$9t^jlV*@| zE5D@98R-fsw8l^m8dICLjJRQUUs#<cGL^jinQ0N?_9bs0_RFDrsW0MQRaTx61j9v& z^S`F{dhSl!X4_wup#v#ys6<oV$R7ZGa;+qCgs=_+ht*&milm`)N2AcK>)V>Y%zC-R z9E!8fdMTgD*Os<Ad69{@T~Umve0^ve8+##Ks3;SK*rDWkBvT3p?gcwo=OiNDxCQ0E zm=@OZllWs{7YR6Q^h!%YQ&m-!+0a*9YIAzC5sodePWk(c7v!6A6Ci+gToCwJu5ato NU~l7SU25se{trX{h{ON@ literal 0 HcmV?d00001 diff --git a/css/images/train/a-seath.png b/css/images/train/a-seath.png new file mode 100644 index 0000000000000000000000000000000000000000..40c5e70a1778f767984a7051bcab171cba5f81b1 GIT binary patch literal 3233 zcmaJ^c|4SB8y=B;=p;)D)0pgx8Dks!o-z{C7`rhuF)@pov5c%kWf!Sv(Nu&ISwdx} zqNA+ogk;H5h%BMf`9`NY-ydJ!`+MK_S$@}j-Pe6T*FR5^lcOC_SXLMS008X|SUYpa zc<!erxQ+W)n2V9-4!fB)Sf&g07&8n<Cju-8R6iofo{aM+IumgOR&WQ=7y#e}lh9Zu z7Uh7%Q^{JmEsRz;nZ}I<0F2GTX*hf!kqPo6`jaRo;Dv{cU=WF50(R9!X`^UX!~oKP z2s+Uv!V!&+2*eu_z-Fc(<8UOGfJ|iKK;h&d3IiE#0{+g6<j%LYp<vK=2s6+G{EsLs z$_Zper4vEAS~{9|Z5Rxsr>6x&=<4agG(d1|7#yn2ef2b92&Aqa60Q&W@qoG6=!9cP zXKULZxwtD6Z~&7@LqefpVPRTfI$Bh^KNMzYXt>1zhih^XnhX|&i3``HFcg0>SQ8m| zI*G<4Q7ND;Mw}ltglPiiD*dMfGVK>Fh4G_J+=fBJaWp7QOM9!NpFkAq|3k^-UuXu? znfR~X|4Gb1vuH%9Gm$|Jq2sv+cT90B6%A=cC*qh?I+{ui`q@RN04kHp2%yqHRxWxV z6;~34Kn-K4e#fIwNP7x{iKF0&_SPm~E`t_{L_q2pTIt#7>1f*;T5-E>qi+b)v#>ze z*xJDL^mS~kbbiKKQ}H2WB8B-gmhf*Z?6<L7Rv^>3nXQR*QYevNOQ(`S-%Cc4eyas; z^IN_jv4r1hf!qEz7RnU^-8$I+I_RHUT=#5Ef7zD1_+@+|h3j@Y*VfIpU9JFtkfgn} z1v-3i?vmR9G*#wti0reVa`wTYl+bpmijtz+nCtZcal&jVXg?c_NSwKuqQzEuP!tfC z3}Q<yUBA0s?Vy@FY*0sis1M;$^>-KRTm9afd#~)hOu8&?965byEpqzuG^=J|Grh+w z=3A=plgB4)?Ce}Im<OJvb#-;g$;tiwXyB<S-iJ3@9yIek$;#RpVtM}5qW|?HH*B$1 zEEelzVX$mP#(QB`v9}?xZ8bylOI15!M(^GeDpcGFl(B|5@}&tG@4T|`rg0XrQ<*&- z>7_LnOPiM#DD!D-i2CyBWtq<`eRh3)J&spE2?9Z^7~sxd1C6;><Xye$V<#IxBoaF( zPWP(Rw<e!k-dz9K+H&P0!@9*(HriYcHFFO2&D8s9WWRSqRTToXwz=}|tk2YJMNo!m zE`JxUS`?U?D0FdQ%_5cs;vJThe<v96(CG@z%P~T?vH$rbn&Gf>=8_)yxUiP2HeyGD z{42W<1SkXR;2>%TX^i?}`@}iCuu*KXeRta#%%l~MSi7t~MPufqL5}<4*!sq@|E9Z~ zM0t5RvmtWB`J7PgYfmwKhwaVd=KOIt`)4LC8`I>Bs_io5;|P`%fl<Q2m6VheV6fv6 z@<0(_u*6MALC`%FW-1dWdXw!Npq=ry?4?-qKtt4tbUC9?QHaE?OgD4>n^KzYu?;Nb znY5G?m#>R)oS{B~M}@9qIlu9x?y!+@AN|C(wzel33Vo!$o2aH7r;_T50<h_fx=7ZY zMG0iy#fuR$-TU5b@Gn*Dnd9W=6W;e1`*-C%y5ko62hemJHKQ+D@AWYB@Kw{OZ(mu? z&dyCaIYwb0KCjMh2S3^TvW92+KfgQ{ZLohAtMwFcdAf_*o8Q4r*Ie@;DRG%j>{dN{ ze5B4$PNwC~ZYvtcy}R*G>kC?5T<3K6Ux4~pCfW2ofWxA{h9l~G`wYxN=Va6(SKlAq zF79MR8*S>$)hSP9v)NqjJx4AQZu9w<o`Si}RFCfCxkk<Y3L87Cy=~n2zGqQEU9FN} zjzRGFOwSFL+@n;0cIM^Fk$->NY-zC^?msQAAf{kiN9f3^Ke6^S&3F+(n32%@H1{eV z>*)Brx8P6><@Ld<%|a4No{iC7M?TLF)l~X-O}Ur&Kf9<4@%k$nBY8N_IM*}^S^em! zh_u$*>_egRgWI3EcMsoZ2<VJUVI@634AqFosF3g0O0Eo45D$5et-R|q%;RV7kdRS& z5Hfpet(HD1Y%o%P;=(nq7tLAgi~CeOYiYQqSf2Wb)orSXs*u?Mm0}gv%FG{wpT{4G zguCB6E{Tml5gHmgR83AooOxPitlsC>_}A`({r3W0S;pSS9wkdUw0E}ec(MC5J-t&y zVjrZXT%$ErV<xR>@xyB)_5GuqrZ$Xkh#xx%4u>x-EtyY$-B`}e&5h>=wutmhM|b6! zSou#L2J9*nHwjSTlzHCIYEDStO9kocOSd&so}|k$raEzId>ny4V=YUOVITIImwD7U z4%V}lr*7C~jPnYJ%ZqluEcL<<D%z!McvR1gKT6T3j=a5f#VAZ{kDf!b8FN5^ugA5_ z+i*F1ZQ+dogyPDY&(6*+DJe<YqtBi=uj$ckH{9NFR@uKZC$6%kLj`tHW~Zk*HROH2 z(2kD~Sw6qLVnH~tu%C>8lOIo!=wUOzwnWSw_l_is7q!6?ca`~-59g((iSLFd#3qpZ zQZ_a=40zxYOiT6Uh>^h7$U9G)@WT(oy8K=gyA;+XKz$nKJe9*1M(V9ji`8)&J0f00 zO9k3^0?TDRW`}B^WkB=VCAZ3B*YdapAxM)qZsA7R=%u3vZwa5<>DO_<;kNKz4n}jw zV;6AO=OfZBYab_`^ys#Ly76qTt^MTlZZW2xcS^O%$)klAo-GHiI^lUu@;0Dkc4MB& ziBGdH#WUja==lA|xlVj+y4b(69htGewjdwF(tpVlx<Y;ZK=*jRilkxtsbGUz=>T6` zbJ@!7(;0j8DZWR|J3qE1NoZtZ%DjO*XDm42Kx|b&=0N<aJufU)z{P%V8jsrwFD<Zx zZ=mVpvrGE1qq_Fbf-Td-J9A*zSJ|pAv7!q+!zt2GB~J-$fF%ciD?G;kyuCtO!GtH< z$o;Nwb2WKLW_lM`vo}k9;@)|vPbq>lKX~u%BSkurIpZWB@#WKeE&RhsV@yn~a<HXY zn?=;I@_e;w9UigE?yv6Xp}e!(rq}F`d!+2AZz}~u+TjL~>og~T(xea{f3Z%yFmJo! zO*O&8O{z~&m-IRmGkwNpd;9wK@$!J%n&SoBLKue7Qv-7&^&Yu0g$eu9qdu?nlr2v^ z!yn6;$TouG>R%<ieBSnEUb?txVgb@)xq}E10LXgq|7m0u|L$H?fn{m2WIPaQ=9?)n z@ktQWG3nqaK$){BAPx^I)fC-$9FfN%XH}z?!qVpA!*UTM=d`T+{+QH}#*8n5t1nQ_ z@hHw{opz!X?*jF{uy&I8ZM;Y@q<I(L(M?RhuB=ASd8t_u>5z5%XxkA71yJr&^LU%+ z58Hu)R`FG1S4-2^k4P$)$BEO%Ht!IC0~qYNo*8t2nsJj<viN?{r;wxkHG{ROt<~xY z6$kv(j<ksSruC?-I@@xJN|~H}-HS0F^3_Tz9OkdN4^U@#frWGogj2FlRFOwbpAASf zs+5bx9KStp3}nNj&L(|CoXasl>X%fx7LnowUC6_SyvUZTw3B{u>PiU@pPHs7O6I1Y zr_0)1I9Y<-<vqo^9v!6`v}aE{L%Qs}&HcipodMnGYD~p@-1<;Ly>d66$9t^jlV*@| zE5D@98R-fsw8l^m8dICLjJRQUUs#<cGL^jinQ0N?_9bs0_RFDrsW0MQRaTx61j9v& z^S`F{dhSl!X4_wup#v#ys6<oV$R7ZGa;+qCgs=_+ht*&milm`)N2AcK>)V>Y%zC-R z9E!8fdMTgD*Os<Ad69{@T~Umve0^ve8+##Ks3;SK*rDWkBvT3p?gcwo=OiNDxCQ0E zm=@OZllWs{7YR6Q^h!%YQ&m-!+0a*9YIAzC5sodePWk(c7v!6A6Ci+gToCwJu5ato NU~l7SU25se{trX{h{ON@ literal 0 HcmV?d00001 diff --git a/css/images/train/b-seat.jpg b/css/images/train/b-seat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..e216b4e38ffaf76128164fae4b4002c13ba84010 GIT binary patch literal 1652 zcmbVM4NMzl82*mC{&FzNPeRxdj$_MU8|~deTdvYU+bf7mwfrbEBPON2!2#{n_86tQ z$c9@?+)S8LmpC_u;@n_J+;njxahn(s#YvVK1QAhVG;^Cl-27oXuO01XLKfqjyX5=c z?|q*4=X>8zoD}Ckrai=M1)#EW9Z-V1BK`t2Oq;u<13&<g)Fl9jb1>f|2!4}J=L>3G z9=?Iqx_PfI<nrrCEujM?r6Iq|-NFi31KY^?%=q=QAK)10G2?Z52jTGB*e345aDc4| zKV0h$x43B!Ub+!037JA(zn2wUSjgMz3z|Y^JW6ho))BQ1$D$@eiy5~>ykeUjPRzy! zSWK@iEN~Mfi5U!9vPf?*kQ*?HASoRoeTD+E$fP%zC?mEcxa2M1*=nk0%9ngeJ2SqN zRC{~7w!Kix2O4!GP16w$iYkyS3W6Oz!4)d-1#@Ez3>$O@IKRO0J}koMYT(-hGcHAX zCk3zH;fND2TP?3Ql2_C^C{(j|!&ufjSli)eb=7Q;Zwt6t$vig(mTGr@M-f9Q8q*^I zPP!CVE5p0nysS^CWX!m9qV;ed6T?t6Ww6*O(oWlrBuNui!lJj^iU@<=VlO9S9Lr&? zj73i|Mw{J27LlagXelxl+i03BB#Lc}m1bhtN?%ZL`P^*GFDLn3!dmZ(HQ55JOW*^w zJl`7Y0A~{~@WCeDkJ)MrSY93H^YHD#{K)m($(CUQ+&0!z9^k!Lw7w>88UGfWo*=Du zf-u-E(Y%WZ!bTfOV<AOSl+}hWVLkt+W;!VtU8FhgX_lBu>cGe{-ulueK0K^XnwWqz z8sasO9Bp{uIVX)EBu;~8fgC{)86ua-<SM!JCo1J~Wg@CpC#uzG3L2FZG<ikJiexk` zEj>LgZPm(^D_3R51yU#!NoZ1LN=jx{h9)B`e(+xx;yIvEf_1<MLmH5vfnW_Jj(~Om z5?}~|?!F*Eic$e5DF3C49;W~ZPJm=dGS!kblmH_@rpd9Srpd|f399;?!mg9)MHz<k zcyCRx%GIzl_w`!6LUS*B6e>;u6o#ZIU=1h*e{J&Y?`vJK=e?9RFmmu{-=lC?x%&!_ z?7UX>NA33gidVPX<}VDY;qen9FwWJ<kRfX)_Fb~GNsauS^Yi3ujm^gu=^0t*=fB_X zZrgS0^ruhNtvA)bJNA5*{NnJ`;+VfX>w(!fzTJ0FRljRZafS1fSLmKgc?HB`ZnmRj z!t&*gjicdhYagFFzT@NzIj1rPemX)|_6(j?^;|gQ`gPt}ws|5ycU9N6F7vPm4u9iI zHFUrHwr29=RqGeWCO%v9e*Vybz06~8R&;FQ)@+ciKGxOiknc!MY~DNY<kgzI9Ei!- zSJpFR-SW_$NiICngK)0hwR?<7ispFqs?+?HnZ@C`vO}rg-|Rq#f9&6Kr1wPXVE$S? zG$SQFeyh(J-d<IO5SOMdw+I){)Vx@ME}$Ep&^+V(%?@Y9iR6U`>YwZ95ZQWE_4TM_ zyzJ;`-~9A!oecV+`cLom{+*rk`A@%h^YZz!v1!fdK>lgv>bLr5K1K<+IGaVzC~t^B cK5IMt;X=LpqZ_vtQuEXaojrN#72;R_0H!(!dH?_b literal 0 HcmV?d00001 diff --git a/css/images/train/b-seata.jpg b/css/images/train/b-seata.jpg new file mode 100644 index 0000000000000000000000000000000000000000..803f3b0773b9b8a702391fd0515422b2227eed25 GIT binary patch literal 2229 zcmbVM3s6&M7QT72fIxUu6dy6zT|r55L&!@4=5bLfAP_>j7SxbLa)CU^g9O?-C>ALz zK7gg5Oof0jilB=K6)V;T>K0T+P{$&;KrJqn#mZWsxHWqNg1a+LXJ^m+cjo`k|DE%l zbN+L#{egW1@P#b!UI2)U3<R8jH)5Xvh$53bJsUs)SVSEP0QM1#R%JBmxKygfK#?i5 zDN2f5tEO6HIx0w^QGw8Ki%up_R~ktv%2ZgxBR{)xjZA_SJhC(-nij1SDpl~d9KBMU z6O$m%NtbgJ<nS<3sD*1$>(ol4jAT(~XbfBnk38?3i|ie0Dw#A7F{bm#d<QG({peVd zP^(vxLMXvOavBJdm`n=D2w^h8O(Z%Eq*H0gVg`W>ZU~c0XOUhD8DY~a_HyGz5wE$B z6Oa5lDYMy3F$Yt$`cx{&;cy&2==2~25oE~L7-g0qjlqA>gGgzR>tUS{)@n!&kFpf4 z$;cxkkuId5)<s7zIeu%k)M`gw^Js%HUil`Bx1tRR**YaPUTM&p^l~Kv_g^$dYWLej z4j>W@cZVKE9z~WR(#lP0rN$U3;*pUXiUL+}MIt(f&g4UM5aK{A5aiGVG=2yqWYCx) zd?*53^zl~P2v!7>L5qO+U<e38EDlS^;IklpFpI{f385w1NR7cL)5w*Jys(3J!4~>W zTdq*Alo_@91g$n>u>)dNTBFvW(&|V;F_W}G3TqTvvmwCoJPX;1lzKQzsff^P)uj3Q za^bh|3uqxUPyo?rOo%_9H=9Nia#$cMm=4nE0wMXet>XWw85IeJ>S&JtXqH74(t(cc zQtKm!rQuO(kcrVFqhX%}+~yk|P<(}qAj<v_I0)deSS${U$Kmk5!y})I6CUs6;_B?| z;_U3|;W{rKu5Rug?ryGLUf$kbUaS24{8p`95)^?zSmwIS*Tchir4P|(<<iCfy0L!+ z5S@TPfQ3O30W=YXA)@S^Ks^#44uyL20|5Xm4o`4GqYxz;^Itbu914R+6FdL_hel)Z zZqAqmGZY$w#Q}ICVV$R!HyD?9(TB;GT_@9nOBe|)cTMm33iN%p{)4rW)5}>>Cxje@ zMq`!{aEqiUG!f&8T?fX=GLKi^A=Bggyu5Mm@b~{kpbz%3Hj5c}`vBmILE<4|h(I{d zmw5bedUo|;vTSu7nY;Cy6S?LpQqPktDXG2S3^Uof*V9jOrRFowBbfb#$4Z5*n4N1< z{I;`yVZvvJzdssqW2Q;+YGzJ)DsP9^vikF1kF{53{s8nwH4uUEjy23C+ax?HYq>FE zNRDAom6ScTj$j8#x;R{+#51<$(<m|iU7EW`?)?|t-$M0U&rRmzKNL1Ja$<~kF<q#< zw8L}9<qt2LiT*D5=e9^*rPb~J$Be>*_)Trf#C1@7#pRYXD>@@_!}y)9cp1#NG#+qq zjf@=wvkgh`+7puP(#>XBQbNk(figl|P_L=^XT9WBQ{kg9?dLCN!Y+Tb^~Y&w#XsDd zT7Ka4$GRv_*I50f#l=aD<*k(Vr+!3qJ_%I?h(sbC;M`eT+`!y<X=8C*;kk;Ev8idF zjk0?-^&s5KI4W8HSUi-VvTnJ2$%}b5pH_|?U<WoOmaVK8U%7bdWP9Ua+y0)!(x=hi z7i^!SaQr@oQa;=D-e6$Wt(4HfZL1{7kS*=Vq@e(4$juG(z3*=dRNdYCN+34W78i9( zPfDxbtsWhGke%`1X5F4ggZ(9{>q6^O)58q6;U~J30|x};@=_hToUm1Yto20a5V7)` zti-WKft%s9sXyW+V{-Sl>tD9`i$B@-M`q^V*LNnD=5LG2`qn$|T*b>#r+iHA^Lu}; ztCXyc*%+?Ly!r?Bh+f^ltF7gD;@7^tDwC-`;P#2!q9^BPo3v9MUlgfszF3j|_}ajs zYtzl2^o;vSM?Pr6=j^U-Ppz3r-Q0fr%X{*(`<|2Ls%x*?V%6*sxIOWZ_*9$uYMXvA zbGS>AaH;lc^-udGcHqLbL)p`3hHQ<Up}W#&!;_%p!B+yqgT$>>lWvt+@Udb}8#Its z7Zg>H@0?qzqY?Theo~#g)g^Q`^;vo%Ui_0cF|vP;t#8NJ`3o&}U~Hc?e8$?*^ysu= zE^O-Pugm|oTQK|A)*s`x1P`oEhPw@QRUTu}&99y`*Y0_+p*Ut}A}cj1D#4~`Pdjqq zSUu|i-v*^$C2VN<v}1Qg(aAfN4N&q2x4g|gyqWRm`y@9m-lY<PY;`~T6qO7oSN)RO z@oN~h`-|xu3rFJ~_x^WbxB>UF51;jq{;T0=YJFbW@B+~KsM}@b&YP{3UEQ08QeAkP ztrcgEq@=A_UjUHxzh{q@PX|i=q#@RD>;Ut&4K%$MP+Jqdd7|?E)P)^u$Kct|dr!`u Uclv0}Gfi&X7H`!2BG|wCHwP0j_W%F@ literal 0 HcmV?d00001 diff --git a/css/images/train/b-seath.jpg b/css/images/train/b-seath.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3685e6d6cbe33c1f837c702d5dc0adec087c5b0f GIT binary patch literal 1826 zcmaJ?X;2eq7)})xsV4}cL+P@J3PQ4*(~SlV*^Pp7g~-uXG$c#dO0pr@KtNDbq=3hG zgtmwWDo{~tMVVGbs`Z-DpcteGQmWEX+5%Eg6eQAaL~MUpcfQ^4*!Owfd%paLuq6|n zW;!t#jETWZQ5ii8=-1D26#f0WM=qzQ859;vMUjbAnnI5=#40iY2ZA*UH7>&ys`QlW z_(BF_bRr>-rD8*u3zejXsj$m1O&T4IW-t~mGU*h`H8=$%;A%oE0=ug(fB>Nqfib*L zC{!oGlZd4mdORv4Os>pWqeN8TqCjAwNk|iDa7qD~G|5_n&?Ew1^9t#;{g?#;uSKXe zB5>HK*w6?-Lh5mV$K(VkAs7bud?w80@%gYnz=mKp3!(=<0OksLd?8x^ym>%cn_iVD zl%di$y6Bw<Orj{Aki|+%OJk;Sn516Kf)NC<bFkR~v_ya*T}vrU0a}Ci2m^{6lzKu( z5u_HdGb$2DBP9Z9ONU+1=t4u^5^D`_0!4?6Wm4!^FcV^FG<LsUOB*N|{;wJDls3rI zbvR3g8%U#GN#`Tcdjw3!?){4Fg0wZla6LgMMUjk>N}~qXQo*PQr2jBggi45_Y=q4h zV{8~hFaZoBP!J^MVG=IH=ZP^XJi_rVEJwoOBhvY>6p_%GzyxA85+vcy$G8X^l8Rw$ z1RJb1PztRQAJI$Ddf#B7_hN+-J+7cgy__VIM=Bs9iKIwF5~%|uQG8%-453w#X$D_= zdWOA4aXpcWtE75T1H6u}ka&lFR4S12xe$hlVV>P~L?Gdc1(=v4faXIIjP`pNt9n<= zhOyHB#j<E)SoY%hPqB;~(G_T4zAb%v^R{_#E!{DCx;3hgnita@CksZ!a?`!exSPx7 z!BY-ob~e6rSlhd4V~J^MPP_QF^1Gp{@gkF1RuQtc7wq4BDDQjY(}$hq{)4}$G@ls< zFCO%7-cf5~bBb)IeD;N@A@|NFPex^%cfsXmFh4uAbW{nzpn5M)+TQ(%OVGE!8OuX! zkC)CfUtjP6w%8>v=R`^nRbS+?E-P!>Nh&!PKsygLXzLuKDt%{r`;Ix5a`9@?c&D|J zL5H>oly|Ri{!ZwY?`Y7cB&$Og=rL*P0WlJvRj%pri5VX&^@=|`szS`Ub=$YGC+NES z=ZAE*<vY;I1@7bAYJPNfL`Ih>U26;26C`_+ZE7%nt4y+R*DTMg#MTHe5Zi!&7e9LC zmz!fP-)r!h^=Rukw}OzW#%@WZdrF`uH+M^bTZ5y?GU0Z^e&Sl(mJJFweA=sT%s1LD zdxmeB8R&KIPt#yVdg_AW+~(!(jvYD0#l^dK@3tm6_^47-pLaJ#E7t`c7}t2EbYR+q zjTgsEExX%Mn3LDr+gsn==V5%}ZJxd4Y0;j-_I7o@Q+j4*RW>E(IJxG>Jdeq(U)F#3 zXiH1WvX=1h@H2Iuo}T5Cd~R5+)~>DqerjqeUm%z~d9tO$b}et!%9XAS1%&u)RTZ^< z{i1E@`KM}XM2}|#Rkd`HQiO5js~eWSzP{*VMxAa7X3a5-Tik8~<L7l`TP(|JEz-k1 zKc(+S(4qdvWpnpcS}c}++ezo5%XO=L>N#zZnJZS~z0NE@wOYOVi|XtqgP_tmdfl!@ z4R?J?inaU2X|I<1_tT<XLhd#;?zx#*6JHnQamU-^#KR{m{z$0b-ar_Qt^?MAfq_}t zdreKTadEz$oN0RIGw}?N7@FSJ+S=OFQ+ZJH`{b%~XU^p1&O!6zuguZ@t^HvzELfPh zee=5NIo+4<+___pOStv$*u&E<<$KSTB$PicRHbeDIAn|%K5g@uE*<)`1ifXetL>Wp zNM8BC|LLo~N9wW%r30;^=8&<y?bfXxcx(Qt6U}vpk0VQWy7>I;ihhawbtVp~V3a+> zDlp!C+~yY<f%PT+T6m=3yn~-8a;$5%hjTUAf9X<CMoMIeS4^So+N!XlO(M?rL0+(z mlULh?56yl<FIVNC9}h7cUXTpGR)079trd)gp(lb?Z~O;ERMw9G literal 0 HcmV?d00001 diff --git a/css/images/train/b-seath.png b/css/images/train/b-seath.png new file mode 100644 index 0000000000000000000000000000000000000000..3685e6d6cbe33c1f837c702d5dc0adec087c5b0f GIT binary patch literal 1826 zcmaJ?X;2eq7)})xsV4}cL+P@J3PQ4*(~SlV*^Pp7g~-uXG$c#dO0pr@KtNDbq=3hG zgtmwWDo{~tMVVGbs`Z-DpcteGQmWEX+5%Eg6eQAaL~MUpcfQ^4*!Owfd%paLuq6|n zW;!t#jETWZQ5ii8=-1D26#f0WM=qzQ859;vMUjbAnnI5=#40iY2ZA*UH7>&ys`QlW z_(BF_bRr>-rD8*u3zejXsj$m1O&T4IW-t~mGU*h`H8=$%;A%oE0=ug(fB>Nqfib*L zC{!oGlZd4mdORv4Os>pWqeN8TqCjAwNk|iDa7qD~G|5_n&?Ew1^9t#;{g?#;uSKXe zB5>HK*w6?-Lh5mV$K(VkAs7bud?w80@%gYnz=mKp3!(=<0OksLd?8x^ym>%cn_iVD zl%di$y6Bw<Orj{Aki|+%OJk;Sn516Kf)NC<bFkR~v_ya*T}vrU0a}Ci2m^{6lzKu( z5u_HdGb$2DBP9Z9ONU+1=t4u^5^D`_0!4?6Wm4!^FcV^FG<LsUOB*N|{;wJDls3rI zbvR3g8%U#GN#`Tcdjw3!?){4Fg0wZla6LgMMUjk>N}~qXQo*PQr2jBggi45_Y=q4h zV{8~hFaZoBP!J^MVG=IH=ZP^XJi_rVEJwoOBhvY>6p_%GzyxA85+vcy$G8X^l8Rw$ z1RJb1PztRQAJI$Ddf#B7_hN+-J+7cgy__VIM=Bs9iKIwF5~%|uQG8%-453w#X$D_= zdWOA4aXpcWtE75T1H6u}ka&lFR4S12xe$hlVV>P~L?Gdc1(=v4faXIIjP`pNt9n<= zhOyHB#j<E)SoY%hPqB;~(G_T4zAb%v^R{_#E!{DCx;3hgnita@CksZ!a?`!exSPx7 z!BY-ob~e6rSlhd4V~J^MPP_QF^1Gp{@gkF1RuQtc7wq4BDDQjY(}$hq{)4}$G@ls< zFCO%7-cf5~bBb)IeD;N@A@|NFPex^%cfsXmFh4uAbW{nzpn5M)+TQ(%OVGE!8OuX! zkC)CfUtjP6w%8>v=R`^nRbS+?E-P!>Nh&!PKsygLXzLuKDt%{r`;Ix5a`9@?c&D|J zL5H>oly|Ri{!ZwY?`Y7cB&$Og=rL*P0WlJvRj%pri5VX&^@=|`szS`Ub=$YGC+NES z=ZAE*<vY;I1@7bAYJPNfL`Ih>U26;26C`_+ZE7%nt4y+R*DTMg#MTHe5Zi!&7e9LC zmz!fP-)r!h^=Rukw}OzW#%@WZdrF`uH+M^bTZ5y?GU0Z^e&Sl(mJJFweA=sT%s1LD zdxmeB8R&KIPt#yVdg_AW+~(!(jvYD0#l^dK@3tm6_^47-pLaJ#E7t`c7}t2EbYR+q zjTgsEExX%Mn3LDr+gsn==V5%}ZJxd4Y0;j-_I7o@Q+j4*RW>E(IJxG>Jdeq(U)F#3 zXiH1WvX=1h@H2Iuo}T5Cd~R5+)~>DqerjqeUm%z~d9tO$b}et!%9XAS1%&u)RTZ^< z{i1E@`KM}XM2}|#Rkd`HQiO5js~eWSzP{*VMxAa7X3a5-Tik8~<L7l`TP(|JEz-k1 zKc(+S(4qdvWpnpcS}c}++ezo5%XO=L>N#zZnJZS~z0NE@wOYOVi|XtqgP_tmdfl!@ z4R?J?inaU2X|I<1_tT<XLhd#;?zx#*6JHnQamU-^#KR{m{z$0b-ar_Qt^?MAfq_}t zdreKTadEz$oN0RIGw}?N7@FSJ+S=OFQ+ZJH`{b%~XU^p1&O!6zuguZ@t^HvzELfPh zee=5NIo+4<+___pOStv$*u&E<<$KSTB$PicRHbeDIAn|%K5g@uE*<)`1ifXetL>Wp zNM8BC|LLo~N9wW%r30;^=8&<y?bfXxcx(Qt6U}vpk0VQWy7>I;ihhawbtVp~V3a+> zDlp!C+~yY<f%PT+T6m=3yn~-8a;$5%hjTUAf9X<CMoMIeS4^So+N!XlO(M?rL0+(z mlULh?56yl<FIVNC9}h7cUXTpGR)079trd)gp(lb?Z~O;ERMw9G literal 0 HcmV?d00001 diff --git a/css/images/train/c-seat.jpg b/css/images/train/c-seat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..43b900f1dedbe7714d0cfef2bc1b9dd7da67271e GIT binary patch literal 2285 zcmbVM3s6&68onVUgg_vXP!X_%04-2S?#+{=JiH{KfQ!q^g%zQO<Vvz3xgiM>SOw)# zMG<-Jx}}v;3af~$4+OEG;8M$2SG2TB<x%9J#X_mBU16#<dqKfY>vVSZpL=J{`Op78 z-*+ruS;heunOVIJ03sv(0TS>+EVBSjnx)X>064%JQwITnWgL&HOeVdU&DI%NawVFE zuoS44ZI<iV5DR1jL7`^7T%kcsj5H)&tqW#;-`UM%sFlIYM1C|Ft(PDwbwsWKiO=1b zpvcuIL`r682qVZWHf!}-#3W~!wHZ32*c{AU3NFUhi)uELv1DS>1T*2qtc;}S7={Ej zAPhc>8=wFoh#?TLARb>JfYvcMAjDyV*e3{pcw)Xl%n>r43lqy`P;L{)NyDG#!gj&T z=S^j2XS1@oEYy(BhD0LKVhj!^0J8`%=IBgvbAZn1wH!f;7!?M!-lRr#jKzrZG&IW; z%)}~v)`C_a9la9xrPI=C7yDYWHk#s)7iGNE+L(}|N7!+Q5zR6v5X{_b*%_PNZzozb z#Htbh-k`=VMV=u=6<JzDXNr^tGqDqvQmqtAr5q7Q0LwU#Oe7ORkO&L|VZKbl0|k6o z77i`Pc$sgQ6y|fJfuIbAcn~BL!aQN1L?nW^V4y@ACXz1uM(T_vxlVyB=T&2QpZN;I zf74eiF(7giYDhrQjAaDGs8ADXRH1r?BwoPqO;qcYXtvRB@p_(hD@6?I?T9kmfNB{_ z^A)RKk{_1vK`2ZHf&v-5)OR2VN<>0P$mKvBPMC!G+*kSk%#4i{!(If(&%m;*!VtK) zT!B8eSs@Ri!x&@0s9~7{9F_nND0?sp;w-~J5kR!IwkB8;2?U}o5&P{(L?X$~o=mnQ zlkKVYOG34GaHKjq*gHAV=}u1WZf<Vw9xH;gv9Y1pQ(UN27guMRv+K&i|GKdB05lTd z4;12YG{B06!_#n<Pk>zPoxtO;|HTu6w<Zv+a5f}N`wO80I6NMQCz5Rm&rWbwcx!-0 zSmg;3Va{nM6F>HICbzJa&T|%2Tnvj#E2xh*$_*bS*wB6z%Q6Jm<8fFacp4B2{N(e` zsJM<?W_47_3~S>T-)w?Uz%h3+Z<nVGg^~~6SijI7I-eiamEgEvVF9v#XubqzQ0quS z8x_x)>s>0HpzJNXXY+4YqD$4@g2;2wkoO0(^jD_oWP;W1^>s16(1PU7SG83)j}@jB zR@B`AZ{@wwf8lO8c|7bQADV9IEAPD)wX@?y)1DNE#=GVHje`224VsQqf(t$0PK*DR zH{JK(NWCxPYIe}m{_odc2hU%_x3*oUulA)=h2^`Z2Db`*8vDzN#80FxJ~xL=M+I%| z4h@Y6c_3m~0Xul{OaCR?(q$aov3)Ghf3Q*2`gv-+<7-!JLpB^}5{~2uVsbYozk2-i z1KjXba#@K+5!KF__;M)m*wFT-HoMdxmii!ul6G`D4dmX4(F9Jo!JGT5Usv<oXHM4G z``z_$^sy!!@bP|o>loZOX;$#})=ofw40rA6_Pbm*sg%ZF^E9lDA6WHC(S?DSJ?@*U zt!h#$quY~!naN&BY14cPh4&Zr`F$mC&XXw%8`QDyQP{_$fbizzKgrIzl8h<WLR&kp z^X%Eip4snA1j1*Itd8O6mO(mocx#j9O(0^m_w}8td(R#3(!Ji7`DBDX4KDoESaEty z;z-Ht5x1cB{#UP-*i}~+^FF=A*;P5S=a5R1=9QV3T^t+mZrtg0lKymBh?OBObHGEs z#%8$8wdS+Jl1KXeKJ{nn4ixPtlSQ@uSw}^wp5xy%2;L%H+@g+OeM}O;{XkOo@x4{7 z_Npe?_M}_+zNo{Mr}^(pjO1;OZ=K@bkBoKQVlL!z1INqhsHbD}!L{1<NhQTER(5HC zaJ9GV=ddW4OYR(fa^4d@Xq)*{t%NPQk@YdJIWmz~b$R`xjQq#l6Ps*~+;FB!D8V<I zTW;>CJY1u_0)JRAFS7ui)B9|HJtNZ8rw9DGrx4zr$&g~+V~2)-w)Rtv5t}#Z8;-hB zRbCZkeV5<adb#wA`_<*evP|1#nO}Q(OkKQOuB~2k&Vh8ht90AM6zFoRq9$u_C`}r^ zR?7~lKl^^v9}28SV!v!dW5?jSuitoO=s#yEMeL^Er9^6h$6{N*ZMSpId@I=a-5KYT zBkbNl&W|TM_9nG@7e|60wYhhE*m2@mRMy(AGp;5w;RU2r{c;1drGZLsPC7hH3aVZc zYISIS_{U8Xbvwv!kD>Px_wBy#m%p>SG1Z^4F5@lc$-j><D(g?Y_NZ;w9sEW3LCsvw z=;5z-*UA4}>zJ;o^JT^OE>kbD@9}$i>4!$23<f^T>z;wrmiXvZH8=NAwC~~jSI0E> d7gV(KqyI>ULeO_RXP<fytgDx4OZTwc`Y%L`I5_|S literal 0 HcmV?d00001 diff --git a/css/images/train/c-seata.jpg b/css/images/train/c-seata.jpg new file mode 100644 index 0000000000000000000000000000000000000000..76297a4463d3208dacaa00a6ac2af1b96b4765e7 GIT binary patch literal 2882 zcmbVM3pCXE9{<nNbIQcfBF3;*5A%MRJi?4ZO3a|!w3eB{Eb}lAGn6iBTdCAWFSRL) zLdGFkwdqCLL^kA^_ia^3D|*@G&M3O)p3a_o?(h8n=lp)(*XR45>zo?|mb28tC;;&F zT?Oa^pU&JEfMhCpv55c(fNIIE05CTQk;EtzQU(qumSZFMl1KrTClTS)5mFohi^l=3 z9%^X>FIJ#HM+%~aVmHjhFE=n~A>R!XN(sORNWBFy!VO6>L2%M0HZLib=fcN$xT9Uw z47Erq5-1|jYEhh6&QQBy=8ZG7cO4mrLC=dQV%;#FI#hI6Kp@&%A`_q~SdudjPavSF zR4jo^p;8HJ&_q0eh{J0?sxyJipimh^8v5hGXwhW+C`J&|=OdQ(<%anfluD(-sz_Lg zEE-2}adFYvAQGLm63+5Ou_8k4ESB3ZSYQg|Jeg3c5K6>ooyCYqiBjQ)(R%tJ1d%i# zVA1ervn3Mg;+mJ1D}n@{-1w}toSi5Y;DQ8liBiTBXvOUpl(o70dmx>l)*HrVnNVAl zh&ZN%rxXdq3SXuhM$5tSg?t8+NpvAnJy}Eo%Y{WF5M1zHcuxw;n~bMYJXt=31sk8$ z^`ZGt$pjM1lRzO5STq-!H`$ZM@+8slbi6lfQP)>2S44<;f(2Zm4)=pD@o#k*-ZDXi zLLy^JBykHJ5Evs-NaQgRDcU=jigpSWiun?ie5I~DAEIRnWWodi-$y19q383<5Pk;V z3s1olyjXZVmE}1fHyw}ncA*hyBqD)G^zz1h)aCy_Im2n4!ReagKbmEMr0qc6b+Pre zkHz5;h_w?V(~id63t-87!vp-A+7SfJ^#FSSI1~znLE$hM+yJiqjr8GgeIsK-LnA{& zV-w@~V`98ysmanM#-^rbW~QdrR#sNlwu=X(r>BQ7Ml3fmS#F6!qAV8~|LbM$CV<oj zRsp*qAS3`rf*?rHTpe&xyC=X95a`ne0iZAlTu&dYrTrHJ0t11ea6J<M1OY?9dIrWu zAJo7g2o!)Jm%;7y2*e6gGX=$S3x>4&5*bB}xaAco%VJlyDb1IswbZum$>$VU&_eaK z9)Q4Ls1aOm0T={ELY6`82wUPkBYrsdkQmfrY6eR!myuBB7_YpFU^0BJ8!(1wokBv8 zfCn&j><Gr$&14_@XksHLq3qx)a9_&9-2Q~o6Up`5nnUz1C-bn$1M#R^Qad3lxR-Uo zCeq5E{+=o<9vC^~`^T)ZH+=fWlc-(4pNX;xxV}GUOnx`t@h@6P@xIaPHh*pv&R8a% z5D})h9lSGcj;~g{=HnmlMOa4+T3AX$k#-Jsz82RmTxJOPd96RSufJAYkSEI<C|dD| z^%v}1Y7}Q16UDg`vevKohMkjv0-O?P2wLX^1J0Vk+z-D__$vEV!8&fB4WgLz+@~w) zl5nj)MSO--&~J#|kUhGT*qC5*xWV;4w~PF2ZQAk?2WfIc&XxlTMqAmXr0MPkI(s#X z-6LesN`v=%7PWnuIvxNTb38qxv3PV_BT|M8|Nd?wS3Z3FT18EQ>#SzNE>@nsb%%{! zXzbx^Xai{7H{wCiJ<UzA|9S=;QdVb*Qdac_`84*h8ZqC(j&i62m2fN8^DcFUY`j_i zM^EzG!o-dEq}6q`wW(*z(uVo;mpHiqG)0R|+@ASc=5V~2?oTBitLGBqHdDVy$l{;i z9Ry+LLk@nnG&(YIGlLE7x!m0wQ*}dj#hq}r-g@F%Sg~Pb`Y9xe!wH2lFZ%hes_+jf zkogffS+2P|ddH8J5>^L3tMTc5|7A`4sp_8}a?^)5yyM4JR5SB4w$WE<LXKIU5AN-1 zZt4wrvF+xQ5<g|((AAORH67}>A6wdnk5^&x+12GMEk%98O5yjm{FBO!JxFUd*Sb?w zDj-jnI<!|@s_HY?1t0Y(*<_wo+;QbdWno&XvUTz@>iO$OnN5~n-WK<=jtn2VVE4rQ z)E4YY%-EX}d}U6F!sq10sdMq$_7IwiM+*;*T%aY#mp8VUw~t+_A6e2@8yFInO3shZ zG2u4l?lCM%8>o3-QQ4aDQ_+z8^@vrAJk!FlmomD;KemI{{QSkFc|QHl@$vy>!WDyc z8_&9LkFPpK<2t~5SoW08bf*)=rJ&nW<Ig9of_pCi*<<z;KfPweo{KHJVwzW4l~mP~ z3vcmkK!Jq^_xy@3(cn}u=I!a-*Jld6wh;@sVc+k(4t)!eWr+{ZfTYRQPutpkt!*+> zQz{G5Mdcj49~d#hVYFFk&b2mg5Cw0zMQ<sz5hB13c3LYtI1Z7bC6U25Tcg~UNmH+g zXPZhyZ-kqg4|f!O$&4AU^KZOAyx-0s{_xU(L)JZ_`bVZtNA|8v&x@>1y{>Eb#oEJv zz7amXed2Anh7=f;bl~z-__%k^%+_0~<oK2w-zm56{Yy1X(<FyK%%4&fB(1K0_7?Hg zy@34Flv?3kqkxu5w@tfx`^|gr$KTzJ;smuH8MNK~CUg$)nr$Xc7Y){4ZglO7ee1#X zwaocC<L4KTYAC!mn`_5Hv#)%iSU)5XMP{u!!N^#hirI;sfHyQgX5-IqcRU%>cP9GI zY5bbyN%v;IeYs-u96*{e@R(S?tIXzVMRK@s{p|jcveX^_Qp|iT)71=+U`)MYyT&Wf z)X7-J^EvuOXGM<QusgJMjNv3Y6?JlhvA>y}0~ckUau?Gp$wGW{??CIz^gzSaDUL1a zgGbE_%%mGl5!o<NEi>kq15rbd*O+(xkfZGAj%50*i2HhHcAu1aYYXBwx1Q^8jSSnJ zP_ixh$LcuHD|-ukm41yiioNxY>77i$O*Qp5<i+mrjh&AsE4uCe(e8K7H*8CHre>LR z<ts0j<C27wOJ~i%Dd$^k9@I^qQC!epd#{x=?VeHHIY4g>dh*J(>w3QPdGd@{BLESH z(grJjs?l?*%<SLXSl{&Y0VhvW+GM?UvRN~m8~d)yHd=%G3Txk*e22$>XQAG;b-KTG z{GV&>$EGG_L$>i@UGA(t+hfV9shRKxzs|V1p057>aR_zu530<Xs|ZBG!<=seG*72g z`EKMV1}uB@uK{HJj6#HlURBfZyj*mf9GyEIH%78x=jHg3TWd~<M$1Q(szjsUqiOd$ zUnc#+-E-D)ad~R@C~|yuZ~wj*?>#bxaTfh=Vhpr_>iE2@r!W4Xe>Y4&ZEH02<|$ON aK6YQ7twr6yTMvtxb$neu7R-3eb^RNOtZn%K literal 0 HcmV?d00001 diff --git a/css/images/train/c-seath.jpg b/css/images/train/c-seath.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5ae70395dab9a96de6cb09fcdc8efa13d749dc38 GIT binary patch literal 2969 zcmaJ@c|4SB8@4Y;c4Jp#Y}seVGG>@8Gl)!O2}Lqy-ZGY%VP?z>;)F<+(k4o>RVbB2 z$Z`-uQI>>5PIOR+P+97Gb*l6I@%6pG_kEw|eSX(<-S>Sx_w)O`$$NJ@ivOnk8xIeU zxYJI&8#u;;kDdr0_}=y|RskH8nD*XGciLeln-~u8*pg`h0Msdzcm!|*h-7ZqW59}s zhaX1q@Md}wTrebBs1b1!W5fxigKQoiD{Bs&ND2m+&;Z~Fg^GpE*EYbQ6fzd(Wk!G# z=r|ydvNJLqaF5*WL5d6}p~*1o9Z)L{1{4Sdm_#TiG=$2)aImm%x)^Z2xoixBeuFTB zv9N!V@+Rzs;%MOj)Xd1lkOW5{pyuXA2vak2bA$mD2}dA};oxm<h%m*NnPZSB==Tc- zMhhn&#<<}fzQ+Q;u&_WTla4VqX0zEwY!f3|_z`0S8jar6Kq3u6gdu}VWfD1tREEY6 z1w6nYg;VHE3XKZgR3rw_SWGMo%=DiULg_zcsf_P7frc4#h;(Cw5qz_xA3y@(|3gDV zf1(*oH{joV|EDm+gG&dD-2euS6;1*-?y$yYC^`lg4iK5Na1R<S<cEuU18GbeBalXi z;@r)l+r21MGL6m9{e~wHFiunklSm~2PIxQ~R4}4Y$QU#Vjx)C~g*%{epzHQ1G!BQh zGlARVO&w4cNIUcoE}lkWg#uLO4=(v%F5;Km%~lAdgOTw-I3)rgJA~6hq2EfzP=1+< ziTyA2zH`aH%*Djvmt12o8RN~3{jZJwu>^L{=JaRVf*(H{AE1KW9uBs3c*$$<e2IuV z;cY!QL+>s<4wmzgYb~vnl_lh#;16pQJ%Wl8kru}HwBe-speMfY&e-7vZG8pGrG)9a zaYlGSX^5OzP1pgvpkt4P6y4^uMZW9Vi_E__Zq9Q@kLC<&dQR@EOJ}=|)Er$~x%DCE zLrxx5XKu7^xUbK{)peZfhsoJp<d)^4o#hglQ4!I-%Yr>So80noZD{B~Wg%hcDr>O- zVrps%jl@FWa5<$dBB*g7*;6H$LZN(p=Cb-(pqZ_ied!Wc^P{Ln-~H6Ti!S?w-n?}y zjZhL_Hlf5baOUW`w&m|R3Haz0o$6qcQ$tqGjY&xvwOk$N2<NIxS3{*NrG#L6)=bB% z)@}J%&3hgw?&K{P?;tl#YQ4ROs5MhuOwIYt_lcXZzsnk?^2O~#V-2y}6qF~t)|TI* zj;=28@(WEw$Wbqn=P=!N*J4BRU%Nx(<==d2DsVi-*JQJ{x~%_}xoC@dogKHT)W8Z7 zmd>Vi!}4^xXN4M~Kg)DT#;$+5D+^ua92O{RLz4Qh9y`|@5vzO!K;i>dWLvvdiZK)3 zWi~F_%H6A;7CZ4pe6GbNHu4GzrC(=<QB=`%*6`rq_N2a{p`j|;Sa+^9KiW>=Sf{Dd zd~q7L?)Lpv@o|~@SoV2A!RM*v<>eJ)<dmYKqQjY8D1J!Hc+@+3riyjU`ruvCa>$Lr z97}dnz`dR`Z7zwkyz$PKaENw3RPc?ip5Ak)SK+D7K7r4>RW;3dV^*or85fa2M|*}w zt`&E2{WBv^2BqkGTVqDST~rYvnV&gQ^vUJUgDlaKEypEr7vHtawWTVN;5{>M-@aDN z*F0;%vtQ_B+*uy}{t-F+)kUPpL3>{p&WAT?kHqe-$l?;Wj0eG6D%B(VRFBoieyuMo z#N$t9TXWv~FHJpTu~^XpVvnJFjT`+X>WLex%Sn>kw7<M5xFUjTst~p3AZUS@Gg#J) zT*-&`<G8dF+&iLfy9*6y$CeOk2uR}MUysCEv!vJ&ZW9XhjB9&I=t|84C`e@tfgrxo zdwox7OK1Cou-8&pfzEzTSAgc5scE^s8r|cHUG)&GOup+Dt9F=HUXapE2<0j;ttc?P zQGawzLJd<9`!xpNCGuReEB-!p<iW8P*RNW;F7yz;#0iRRwT|ghz2IgbW}AbJiWsV( zoc!bIWpw;&SDTPxrxx>tcQ5ZH%jzgAE~@^S64X?1sLIX%sZG_1sO6ddU71Gq8GEi+ z>2~>V?U@;CuztaMJMbjSBnf&_R0T!#IO^hEF5>D00Fzg+QK#3QTta!>I>4IjIDa$W zrX@?QVr^-<x7hvqm+2~}v)U}{#x1?t=L~E28H7DcSF@Bi_Dh{Y(MF@^M$qdfGG2%@ z35Jk_>Zh50eeSvAVhR^BGfBcrldkF8tm`Sg+O1jEq}Ei3zNc?POiq}mL>#{AgD5`4 z;r-&|E`t~S^^px52GI#Aj;V_3rSn#I7M=_GSv>6_D7UD<&VqI1AyVWG?QTLK5Inw? zJ-^j7P^xTj%{6JX9O&#gum7y@e(;O3{r3{>2Ti=D#8Ax|&AW%IXqncI5-R2){+E~I z`;yPvdS7HJE4)~KNNY+EwW6ojnO7ZGRjV<>Z_I%XO1*sbM|^b-indiF>f_wLiIVkn z>8{n4+2Qt@%F2kviN_DbcfgPyBD>!C?As?;(O!4=ZpPEHgSCyP=7oyg*!;=t`O$+9 zId@xWnZ}2xfr0+?z8kIw*D(Xow$U)@;G*Ik>Yir4*=I_jf1>HH8bOET+|^%_+S12s zGLU?R`ufca&LbycUX}xn>8e?l?73$Jj)EmOxr29ze|P6zk1z0i*!h>gO<Pb3HbtQN z6!Gam_3}D<$3e-7>N6OYZ_C1(x=;K&8!zMxnEsP&vlRNyFZ|QsvEGKMi(J;z{xaRG zvsHLJsLEz}yji$WWk>Xbj;)I@Xv;cyc1!S_w*!Vn%6@l(xTw?Zda#Xbt^6>wypuvw zV!|39&R8>WxH2@pS6rv?)KqC{DMGGz1@w2?;84A<u;Kgudq=ukkNnP?8>d=+1<lZo zi5rm$X;i$%*JOZ9t(RBH6>5z*ESSs?YdBOJ@r1B?+92Miin?z?qmrmykN;HcQfe=; z)#?N(Q)^=!bt^uq$8@zkb*f;{+YFMq6zO<D9UiEM<vpbmsaNEmUT%`w=-+7A%PaKg zk9_EYPu>_=JQ~|xocqw8Z{PWI5D9hdDSK0``7|4Z^77=)r5L^&20j;h7AEX=U0>3S zEK79uoKjV?+@C02<(%76c-nfo;H9k{q}6cvm1l-z;ht-0U!^SfpS-G|ID(`?%+(Wk zi_>KUlA~jyPWq<eMmmx#64HH-uMQ@i<`;U6a#-5Ye@j<XsICHj=Ml@cWb#-@++}Db z{KQ{c)Z&IHA;0W0uYrivj;D`Hx99Wat3{qg4Lp#}P%+Sbu{IgU9UV#-x&KtsIjBRZ zi#xc$(eKS3*!6NUm$lO9JQjB>jCghXh@O7+sgoPIrvn!bSl&{u7KYTuDEG>FMwYxk zRBwB^te$e$d2EKnyXyL(`^wk)?VTpI#9%4KfFyiI=KILt6a|@LKkgU3^qqyV8q&GZ zH($V>rEOoaZhz%=<>Rn+KzYs*O*7zGw(M-3d~#eKF6qEvS$UD)V~6rf0k_);3hmeB znldvphgDU&?lo|=%15gmKUaN<<<2!ol7g*Qw#g6s?YTUVUb&&w$b*<7*Z5E7jcxuc NJK68Xm)ZHp{Re+w6G{L8 literal 0 HcmV?d00001 diff --git a/css/images/train/c-seath.png b/css/images/train/c-seath.png new file mode 100644 index 0000000000000000000000000000000000000000..5ae70395dab9a96de6cb09fcdc8efa13d749dc38 GIT binary patch literal 2969 zcmaJ@c|4SB8@4Y;c4Jp#Y}seVGG>@8Gl)!O2}Lqy-ZGY%VP?z>;)F<+(k4o>RVbB2 z$Z`-uQI>>5PIOR+P+97Gb*l6I@%6pG_kEw|eSX(<-S>Sx_w)O`$$NJ@ivOnk8xIeU zxYJI&8#u;;kDdr0_}=y|RskH8nD*XGciLeln-~u8*pg`h0Msdzcm!|*h-7ZqW59}s zhaX1q@Md}wTrebBs1b1!W5fxigKQoiD{Bs&ND2m+&;Z~Fg^GpE*EYbQ6fzd(Wk!G# z=r|ydvNJLqaF5*WL5d6}p~*1o9Z)L{1{4Sdm_#TiG=$2)aImm%x)^Z2xoixBeuFTB zv9N!V@+Rzs;%MOj)Xd1lkOW5{pyuXA2vak2bA$mD2}dA};oxm<h%m*NnPZSB==Tc- zMhhn&#<<}fzQ+Q;u&_WTla4VqX0zEwY!f3|_z`0S8jar6Kq3u6gdu}VWfD1tREEY6 z1w6nYg;VHE3XKZgR3rw_SWGMo%=DiULg_zcsf_P7frc4#h;(Cw5qz_xA3y@(|3gDV zf1(*oH{joV|EDm+gG&dD-2euS6;1*-?y$yYC^`lg4iK5Na1R<S<cEuU18GbeBalXi z;@r)l+r21MGL6m9{e~wHFiunklSm~2PIxQ~R4}4Y$QU#Vjx)C~g*%{epzHQ1G!BQh zGlARVO&w4cNIUcoE}lkWg#uLO4=(v%F5;Km%~lAdgOTw-I3)rgJA~6hq2EfzP=1+< ziTyA2zH`aH%*Djvmt12o8RN~3{jZJwu>^L{=JaRVf*(H{AE1KW9uBs3c*$$<e2IuV z;cY!QL+>s<4wmzgYb~vnl_lh#;16pQJ%Wl8kru}HwBe-speMfY&e-7vZG8pGrG)9a zaYlGSX^5OzP1pgvpkt4P6y4^uMZW9Vi_E__Zq9Q@kLC<&dQR@EOJ}=|)Er$~x%DCE zLrxx5XKu7^xUbK{)peZfhsoJp<d)^4o#hglQ4!I-%Yr>So80noZD{B~Wg%hcDr>O- zVrps%jl@FWa5<$dBB*g7*;6H$LZN(p=Cb-(pqZ_ied!Wc^P{Ln-~H6Ti!S?w-n?}y zjZhL_Hlf5baOUW`w&m|R3Haz0o$6qcQ$tqGjY&xvwOk$N2<NIxS3{*NrG#L6)=bB% z)@}J%&3hgw?&K{P?;tl#YQ4ROs5MhuOwIYt_lcXZzsnk?^2O~#V-2y}6qF~t)|TI* zj;=28@(WEw$Wbqn=P=!N*J4BRU%Nx(<==d2DsVi-*JQJ{x~%_}xoC@dogKHT)W8Z7 zmd>Vi!}4^xXN4M~Kg)DT#;$+5D+^ua92O{RLz4Qh9y`|@5vzO!K;i>dWLvvdiZK)3 zWi~F_%H6A;7CZ4pe6GbNHu4GzrC(=<QB=`%*6`rq_N2a{p`j|;Sa+^9KiW>=Sf{Dd zd~q7L?)Lpv@o|~@SoV2A!RM*v<>eJ)<dmYKqQjY8D1J!Hc+@+3riyjU`ruvCa>$Lr z97}dnz`dR`Z7zwkyz$PKaENw3RPc?ip5Ak)SK+D7K7r4>RW;3dV^*or85fa2M|*}w zt`&E2{WBv^2BqkGTVqDST~rYvnV&gQ^vUJUgDlaKEypEr7vHtawWTVN;5{>M-@aDN z*F0;%vtQ_B+*uy}{t-F+)kUPpL3>{p&WAT?kHqe-$l?;Wj0eG6D%B(VRFBoieyuMo z#N$t9TXWv~FHJpTu~^XpVvnJFjT`+X>WLex%Sn>kw7<M5xFUjTst~p3AZUS@Gg#J) zT*-&`<G8dF+&iLfy9*6y$CeOk2uR}MUysCEv!vJ&ZW9XhjB9&I=t|84C`e@tfgrxo zdwox7OK1Cou-8&pfzEzTSAgc5scE^s8r|cHUG)&GOup+Dt9F=HUXapE2<0j;ttc?P zQGawzLJd<9`!xpNCGuReEB-!p<iW8P*RNW;F7yz;#0iRRwT|ghz2IgbW}AbJiWsV( zoc!bIWpw;&SDTPxrxx>tcQ5ZH%jzgAE~@^S64X?1sLIX%sZG_1sO6ddU71Gq8GEi+ z>2~>V?U@;CuztaMJMbjSBnf&_R0T!#IO^hEF5>D00Fzg+QK#3QTta!>I>4IjIDa$W zrX@?QVr^-<x7hvqm+2~}v)U}{#x1?t=L~E28H7DcSF@Bi_Dh{Y(MF@^M$qdfGG2%@ z35Jk_>Zh50eeSvAVhR^BGfBcrldkF8tm`Sg+O1jEq}Ei3zNc?POiq}mL>#{AgD5`4 z;r-&|E`t~S^^px52GI#Aj;V_3rSn#I7M=_GSv>6_D7UD<&VqI1AyVWG?QTLK5Inw? zJ-^j7P^xTj%{6JX9O&#gum7y@e(;O3{r3{>2Ti=D#8Ax|&AW%IXqncI5-R2){+E~I z`;yPvdS7HJE4)~KNNY+EwW6ojnO7ZGRjV<>Z_I%XO1*sbM|^b-indiF>f_wLiIVkn z>8{n4+2Qt@%F2kviN_DbcfgPyBD>!C?As?;(O!4=ZpPEHgSCyP=7oyg*!;=t`O$+9 zId@xWnZ}2xfr0+?z8kIw*D(Xow$U)@;G*Ik>Yir4*=I_jf1>HH8bOET+|^%_+S12s zGLU?R`ufca&LbycUX}xn>8e?l?73$Jj)EmOxr29ze|P6zk1z0i*!h>gO<Pb3HbtQN z6!Gam_3}D<$3e-7>N6OYZ_C1(x=;K&8!zMxnEsP&vlRNyFZ|QsvEGKMi(J;z{xaRG zvsHLJsLEz}yji$WWk>Xbj;)I@Xv;cyc1!S_w*!Vn%6@l(xTw?Zda#Xbt^6>wypuvw zV!|39&R8>WxH2@pS6rv?)KqC{DMGGz1@w2?;84A<u;Kgudq=ukkNnP?8>d=+1<lZo zi5rm$X;i$%*JOZ9t(RBH6>5z*ESSs?YdBOJ@r1B?+92Miin?z?qmrmykN;HcQfe=; z)#?N(Q)^=!bt^uq$8@zkb*f;{+YFMq6zO<D9UiEM<vpbmsaNEmUT%`w=-+7A%PaKg zk9_EYPu>_=JQ~|xocqw8Z{PWI5D9hdDSK0``7|4Z^77=)r5L^&20j;h7AEX=U0>3S zEK79uoKjV?+@C02<(%76c-nfo;H9k{q}6cvm1l-z;ht-0U!^SfpS-G|ID(`?%+(Wk zi_>KUlA~jyPWq<eMmmx#64HH-uMQ@i<`;U6a#-5Ye@j<XsICHj=Ml@cWb#-@++}Db z{KQ{c)Z&IHA;0W0uYrivj;D`Hx99Wat3{qg4Lp#}P%+Sbu{IgU9UV#-x&KtsIjBRZ zi#xc$(eKS3*!6NUm$lO9JQjB>jCghXh@O7+sgoPIrvn!bSl&{u7KYTuDEG>FMwYxk zRBwB^te$e$d2EKnyXyL(`^wk)?VTpI#9%4KfFyiI=KILt6a|@LKkgU3^qqyV8q&GZ zH($V>rEOoaZhz%=<>Rn+KzYs*O*7zGw(M-3d~#eKF6qEvS$UD)V~6rf0k_);3hmeB znldvphgDU&?lo|=%15gmKUaN<<<2!ol7g*Qw#g6s?YTUVUb&&w$b*<7*Z5E7jcxuc NJK68Xm)ZHp{Re+w6G{L8 literal 0 HcmV?d00001 diff --git a/css/images/train/d-seat.jpg b/css/images/train/d-seat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..7954baaf63f628236c7f916400409067468ba4de GIT binary patch literal 1660 zcmbVMeQXnD7=Lf=+Oc(AOFJ_50mmUak@Y^-UU%opxZd63B!jUPK_n)(_E;}ld-d+N zl?ll*7)BEQnAt=`U_lTAY81g}1O@aj4Cpd6j0IuLL@@|MA&Z1ruVvlPEX4TaF899A z`+I)R$NM~&xR@9L1$<oE06<O6Vvq%<C2<4Txz=FwMgRe$uC4?iF=CLzniiu`G^)CU zklZM`f^r0n3o#UTVJN7qipPXtv#7z1Vv`j0A-6vN5`m?V4_V`>#cE@$7?z&tP{f9g z6@g$!bC3!lRZHQ@I316~BBCb1@kmQlrQ<#%MNaGMq#8xw6hv$GAxzRMytcLuW@SZ$ zJ+AVyAco^GNxE>iha~YOFoEF&is=tohP!DGNfTapQV`vn652r5bJdf+^qmixOsc)T z-PK<1l9eVDrzk4PK@ep+qD<Ww)r5FiR9%>6;6yd3NHI;4qi~W@Xp~zuAEHP4AcaV* zwswkm#%e_($-Gi%RjU`L!<Z4R1~$e-v|d!@RwXFv@P%n(y>^dwlmzP0&?^;5zZ9W` zlY^}hF{;&YK14rpg`^P8aRfz>3{T)Z#d~p_!u%NH;aN9EdKkVMPjk#<>*pAX#l2ph z!QD8{dl|R4f~6?D9IIeCKgFeOYoe+qM1x}5ucZ5(v?U*DOS6h7XtENJ<(6~@)P-eD zR>N`(W*bPjbd3}Z$?fWs$?JKLEhj2cn;5EA<OrOqFD=dBpJ6>1?&mQ~k06zI1%|Pd z7x$JEI6?SXWYRYDe`<#6!Jx_Jc&J&@D!l`f%c<7aH&eqSM)iqN^wCJ%1lCl;gU~5` z1fj$**a}QWqcPKH%FHy)GU;zlmdTWrW693W$<DUeEGe;Bta-LPtHt4PIvtMUqN1YW z`BMU!&E{N7Zh_5KP?&GeFPu8~uZzSfV9x@Jf!6@pL53YN*rCMNpbdZw0|Y_Se-NNY zX*OhJ{X>^JwgJch8I3t6^CTR~Fc^V-!R$<Cz+u9Bi29@DTRwK@lc$mW4XSgM(Af2M zz+<*QOr9c2TmlvYqz7TJgDP-uxz>9ydWSFVa~wOi``dMgO?T|p=AB(k+wFUS&AsN` zVgh(ao;z$fcQgTZj~!WU{LtSCU&_7uopaVWJNVJlEA9rYrHkEjuU;v+-BfyReAiv^ z)=#^*`=?)>t1SHDLQfw0`e=?;gP!RAw5WMrNtb`e58HFIY|D@_+0^xY-WmMP;DECv z?6~>Lp~kj7zrI^kajl41ci#E<@8PFDI1|PWy|JmX*ER?1?TLJ~ZA<0K`{Nbsr9Zj% zuJ_&iF-Wf;s(W+m3$Kl;i(Jclb}mv%n3mtNo%Lq}4X1chcVS_%u#)~oJn$B{7^pcq zyu_I|Qg*Pq#eH&rT?YQVczsT+(0XAi4~HuMae3n8f@OPWk4~J}_M$2tKi$3d+0P!^ z<1`QJb-4W3qPmXFt5zAY!Qs`Bm-cDz+#scXp(oByumeuZbPfgQ1qFHkfX#Vi$rD}I ztlKk}^61_xg~#jW{p(A7(@5oalOx8y{Fgr&5<4ZsSpQCDJ~|e;OK+-LeYSF+{4;}e N_LpX7boM8P{szx%24(;N literal 0 HcmV?d00001 diff --git a/css/images/train/d-seata.jpg b/css/images/train/d-seata.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fb69c751654d0dcdde487ca4527dbf170eca7138 GIT binary patch literal 2253 zcmbVMdsGu=7N3v@h(QQ%1vErf9uksCNJ1h3LlOkK2n13@@a&1nSRy17@*sgKwnuSA zsjQ-FQCure5kW;fwDQsdqSECl)MBx+tQr)-mf{o5PC#(~@bv82d%l_T&HaA&{_efs zy<@s#8U<X12KhDsh>Y|Dtbh+<ng9p_oir^AKmiy;9Si`bQ8b*Y)v7oYic%9Gk-=M` z04c1X7$hnR7(k@}!J!6~M4AR^iCdx1<Vr4Ss<D+sl*_oJL`F0<TE&M_<q_FxC_Z~* zf;2l#%9fErLx{l!jzOVPKw1gWph#D0I0i0h&N&C!o7EH&aSozQ<C1u0R^q1USRx-* zLqtXZoh+q-Ad$%o00S9JCg@M3Q9&AoiYz7>4CFAF92$%GUPuU=TDFZN5`@3!LcX}9 z_etsX`T#vW09JoS0oiP}*$0hAMi698mQpJ*kd>O%3mycJMyi&pv~pNUG<%e6g>_mk z35j$*1%)a)deQMmtEEtw^O{3zv?Az37#~Gz60%efMFeSJomvVZ@YM^(NbUZZ$P7fH z;l!xr$fZcq1+Y}7fRx%u0hffF1jytvjzB<T)0jLV4HUA4ED&T<!>BxlkRM28GI+vp zaKXn%ZNq~CnF6{%$O9Q5C}go&{6HQ{$fL8UK~%nQ(Kb@4(Mpt3Xn|L5=AF0Y|Di31 zuZARASe*dF=?fhYn+j`TO)9J+^5dCApG3J*2J1Dx=IfcyRsgBxnUE}84J(Lq_2tMv z!XHLuP{A-EmC6+I=JF1rQu%Ba$fDCg8ZC@ZdT%THe`-cSf}xn3<G-3^L4|andAr#9 z$j9RFKuTm{)W~R<CV^#h4G+k!A|r@0-39glI1C1Z#o(}5+!7q}EVaVntd`=ft(RI` z<L&TsVuxR5YiGL*@8IC*=-}Y)=H}+UYEe*@mX<bn8&^9!*A-3#rxl9_|Lewd6(Cpv zegF%NA^;Wy6q<lCwFA{id{`6;_2CZ!V6Zq#D+?4FQCgT^9|VI%p>Y<Lb^r>EMxn8I zjP3jx0>%JX9KqAx5{z?jV)AJ8-G!GN0~6|RyGlqp=WD-)sr%ao_LPasU08`$2tCTe z0&Rm`vfvtJK|tGMJi$0g#+Qdq_t8ZC4vtu7-bFRt=^81lq;7S5AkH)l;L%7(1T+B% z1^PD~B1rqJjz%Vy4JK}XDf-64Xhok@j%sYb?K*aG-0e>mBLzO4aa&x%oR5e@j%@Co zwi{0Bym=`)(b7MwJG7-~?K}Off6twP_BQzw<9D@{{#n<8#=pOuu(9#MqXXp7_!tM9 zijV`xAFDfyi#vA~;aQ%$H@F&v*NdHQM?^C0g%1-p-z!S;sW;A??7iBvFEi6Sf4Y2q zaI7oyOiz_FIw+I$c4(krYGZ+}@$Tr&g5ZBZH^%)^GPKD)#;$GTD(A@;QD;vu$q}E9 zCDad=R3vrXvj6Tyip1A1ZYXbHi|&~n+TJ48t2bA?gniVHoqjU9@{3Fd_csA9jkzhq z#+tE*ucl6E#*Q`RoR`I&vYVKQS^g;Mi{#A4<QnH6ClkG|2fDVkyy-amO~skKiv+P) ztQADHmmRKVZoa(saNPcLMTJv4xOJEFqi$q0ebxB;C!g1_GT^?HePa=?l+5H>f-mXs z-BHy?%lB5@o}75}aI#uYzONoE=L{HrZ6OZdDa08&in?1H))(Ns8lcmi>0{J<{Fev) zQLu5{jXjS`DBN{}wZ}!ao@<KTO@LCQPFr>|puQ%j?ZN*0D&^3UERV^TBL{m{M)4yt zH*aQi-j3@aq&t4n?Ddz9O}S-*$tB!}m--trlJ|iBJo}{LtLd0$ug9cC`;wFEdfbZF zeQv``+KTBvbUl@)KM{J)x~jz3Gy};ioi@bh_1rCnBfEoAPH2CudFmy;u$TTXkCS<0 z!Q-)n7LEznKeg-1n=wWyy%#!v*aU2M4=q1Jv8@d{Kax`0meV-HN}1VJ8u`1vJiGe( z_}lQp>3F#}nO8rSTQR=bV`I+9z2_rc8J)YG#G;|Y&;R=KJ0}xxp|$jfw|;un6Sb|& z@pra8gz#vJb;Gm4rtO`7)BU@ysr*J)->SST!yRkHfjY;;Fu`o?)S6pA{G33o+~S>I z5695&b-Oy_xn3r~X=iSw37|i>-!**jO;h&KLgTX|yNoT_FI`%M4Wj+1#f#>*7jMgn z$xTUDxy!56uUF>(B61!m+1Zeowf@hIy<3={HukCyM4Wi=>g%7Hm*1)v4>t8}*m3Dm z&M#@d)rG7)ZD1=sSZB_qpR#{y*%hLH`n+}R>e2E055DCJrLvdDQbUraTj9&El2+Nq zSdy<jUhC%F-Y9JT9>3!0Ua3f--%#4@IbP`#<+~g=8rVzn`<i*>@$d^j@c|{Flx+f- s-EE*Q%D1dEdfi0v&~F!F;2Gwut$uLUWk>VW=<8IhBWnHp+GYCbKeE_FjsO4v literal 0 HcmV?d00001 diff --git a/css/images/train/d-seath.jpg b/css/images/train/d-seath.jpg new file mode 100644 index 0000000000000000000000000000000000000000..dd2098c754d88c0fd752e8e8cdad06830bd71509 GIT binary patch literal 2531 zcmaJ@c|25mA0B0?NS2!7&h1W9k}}H~3^NR7b8Umhgh^=3oMB=XGe?G`s5ITAB5T}M z+OD)9q$F!@(P}AcyNHw)E!TTgdfz{K@A;f_e#?2D=ezvA-_Pgl@bUV6_AJv`2n1rb zn=6w8kGAl$e8x2RojuCs!h;FK3V?iNA}EHh01-5yEEGh$N%&zP2jmN5qppDt2*h-e zm>U2EustaPnFPn5#NbpCIm|{N9Gp~gz90gG(4k<MSW3l=T&%{R#X>5^--b<K%Nby} z*fmZ8`o?*21#uAqvJm6sh;~p>U;zmT@zE+tq*O^!Q88b2De!!98;?PMg+LKh%r~b3 z*gj~6OaY>8a8_6W0RYe>5)QDoA&~$}G?4%h@dWrLVF7E34T(auMSs6Aur-BHMBy-9 zzT1LVR7^Mo$tiezOiT<e#tJ7>gy8`)nLMdMBw}F%Rv9aW_$sVaxp+!}2`U8&u^bZ1 zr07XSeyA)OqGDiAzl9)?v)Mm{rONM#f>VZ9@#S~`N5D%YlW~1TD<KZ}UpIb=R&rzI zAf5v%Wzh-&d>*33Q)D=I|88g!2zx{ER*2z4;YTuMf@ldSh1{4_4EzNr6bmU#CXq}e z(O5))MP}Io0GU81&}>)?YXZrJ#&Q9sG=9dVyATKrnl<1;rn>+D%a%?cx-eJ_8p(=D zu%nY`Q(QNx65>k*;FMi4Z1+2t@UL77Ljm$3nSv{mMNU<KPq++{DZ^!QG{cvKUgj^B z3S}`$i^=2p7A+H0h}VNc7lllM{+eHk_$T(6E_T)=rWJ!l18gRJC)+ZtX|^nyl`X-J zz+k~~f8z>&ma}hM=Ktm5VQ27@#qmGIGPMO);N<j2>BEa3%>zo|j#0p^kqN$HA`sff zZcG|ib$^K0E#tE0I=zV<>F$;ev>`PTkB2+c)!L;?s$OCCnm?)@NS{-uxnp#t+44E+ zgGP=kN}N3&d?|n5a^0l0EARz!7#qZ+yX8fa&Zp;)tH}qdbHFTIkg1-wQmI7r<r&k_ zm=&g6o9zgc<z~F2HG1H}`;^h<@r2{8&8zD7tgn}8H(jwJwEdn2gy=cmd3^Qiw3^p6 zy~S$ly4cdHb2If0Z?$US8M+;;Rq41Msf^P&)v4Z)HW<Fhn4{3RPDYPs+yQe7w-z%i z5<VVE*oHGhuGQKuS7<(~(Y0{3$asUTM3i>Ozg%<<O`>eo<iE~K%$#;}JC<qYUSxyC zz4c!mAF*%YRZqY0eVH>Gifo!_cLSW;QUsfsZBIGwC8-`YgZidp!6j@);Oh9kYgepw zZlXnGm65TQ{~`8rr`o2by3`cZm1Uei3Z7)v0cUZy>_awkSC?r-1RRN8w)e?}k=6?k zDg$@7QLpInxnUt`SxScAJC<d}M(MpVs8Q6=h_ZO?(7DAeSi&HqTEJs^ONq=UNr55x z``e95lIBOq>Wc=_%?mi0h_n-(aclf2OE<M?WpJVmvNAKD8ozyLa3ZLB!?T*tz1!lb z(q?5VgGYJpEB)xXJdKcwyad!A6Nb2hTc;iS)g-SXH?pBWI=ooNo!oHAas0!Ugk(o{ zwDD7!V?cTAZg$D$H~HIcW7br>GHxk5v8nEZAgpE0hj$M9vpaam`Qe)7=O!+OwqKqY zem=^uZ^2hQRV*v&9$fz@r`uj1)Zg1V=6h1=Sug~Ce6m?#y1;AcQBRLF!oK(p_oGQE z=MR-!C-w$xsSF*o$Wa=rHU6g6ceG;`B4oRgiAfGI9Np4|M-#mXcy|pSb}nXY!t~io z>V~X|?BZ^xp*`+Su4uOzgn`-zg>6T8U5cA$`?$$O`6=Xak{z(*;NhGrRFt9FnjrhN zo}cn#CaN}G@Y>sNe<L@s^pUA@&lw+`ZZ*=j|0MeAy+oC>Z@STrzwQ@ZGH><Hr|ueG zZhg1bes{vf4_2OKgY#yJ$lIuHt5L1M+;f?0o8!tNrrS2}L7yf!t?9Y#PH>3&Jj2|J z>2={u{FmlZsgXq0Qy)?+y&rn`%RX7jr%OSf){jumgfy~y0|!X<km5PryuaolAU@=C z;~mzk-Q@880;KPO(vp;*TzpShZn0u0>g=cI{k{hdWM1m=d+}>h_E_A=0f(ruI~D52 zo2}VCmA&^Y>Sl9<d$Oi^7yZJ{qHOgD@br_qXab)`yT;8-D-2P2Z?)f~=6`;DzIMC* zn&9}V{73~fT-(x<^V{WrMC74hc{Q!F3AbsizH^o6NE6RT0)&pujV~uq>C+<n8(x}W zHhG8Mv`q(ZApMc1I$^bst$SV8A$QLop(;eb9xmNer+XjYQweAl_A|NKeXf;EpG8-+ z*16-FgvYd^ss<KBEs>{POG<0_IKIlUFljjUwhF_`%v#Xvb!ExHNMX^=f(7;uoW*tz zN#+}xsA_+oMHcCpUa3aPfRA`$-a*g5UY`<O{KNZ%`b(qk9bH~t8o#Y4dg#)ZYjvKZ zw^y1ZL)|3NiT0hV{w^#=6u?<6H0{V4N^CD(>5B2Zn;IB?!~OldgP)%ipPJ}xDN7`- zuqyzPRr&!Zp%-S03@QQ->5_T#fKzURrAY7N2^+ZXiH}<tbFO>PuL;%m3y+g_t_!x0 zh&Gw!ty-vyx8pggga0HO9&zs4SW_~tw#;^2X=xILs7qF>QU%)YALr{}mvYJ1j%n`g zGh7+x(SGVxE-ILNtF!c<a_kKU!vKM=6@giGeEqE8n2hwd{@Ca9xgG0rmX8#MrG~k@ z<Q%@WP}eo<UAf;K>cp$Q%P3Xfy($$7g$+seAC4|$o6pN{+3%b0IM{I6W@%6^&O)AM zS#O~H?a!`wLuTmQeJ9KB=@V;yNiShFc|cw2-79L}ajo=c;*oY5_cyeMWmZ|8zWZco zXsBU}8LPzLDtUe|&%`sWy(|!vX6q#|AXPl?Ja1W%*2~u;ng+Y#f*VQb)e*J5TI#%! f@}#ldi0O!vTdIvha5=7%zg=!DFXn0b+NA#gUrZy5 literal 0 HcmV?d00001 diff --git a/css/images/train/d-seath.png b/css/images/train/d-seath.png new file mode 100644 index 0000000000000000000000000000000000000000..dd2098c754d88c0fd752e8e8cdad06830bd71509 GIT binary patch literal 2531 zcmaJ@c|25mA0B0?NS2!7&h1W9k}}H~3^NR7b8Umhgh^=3oMB=XGe?G`s5ITAB5T}M z+OD)9q$F!@(P}AcyNHw)E!TTgdfz{K@A;f_e#?2D=ezvA-_Pgl@bUV6_AJv`2n1rb zn=6w8kGAl$e8x2RojuCs!h;FK3V?iNA}EHh01-5yEEGh$N%&zP2jmN5qppDt2*h-e zm>U2EustaPnFPn5#NbpCIm|{N9Gp~gz90gG(4k<MSW3l=T&%{R#X>5^--b<K%Nby} z*fmZ8`o?*21#uAqvJm6sh;~p>U;zmT@zE+tq*O^!Q88b2De!!98;?PMg+LKh%r~b3 z*gj~6OaY>8a8_6W0RYe>5)QDoA&~$}G?4%h@dWrLVF7E34T(auMSs6Aur-BHMBy-9 zzT1LVR7^Mo$tiezOiT<e#tJ7>gy8`)nLMdMBw}F%Rv9aW_$sVaxp+!}2`U8&u^bZ1 zr07XSeyA)OqGDiAzl9)?v)Mm{rONM#f>VZ9@#S~`N5D%YlW~1TD<KZ}UpIb=R&rzI zAf5v%Wzh-&d>*33Q)D=I|88g!2zx{ER*2z4;YTuMf@ldSh1{4_4EzNr6bmU#CXq}e z(O5))MP}Io0GU81&}>)?YXZrJ#&Q9sG=9dVyATKrnl<1;rn>+D%a%?cx-eJ_8p(=D zu%nY`Q(QNx65>k*;FMi4Z1+2t@UL77Ljm$3nSv{mMNU<KPq++{DZ^!QG{cvKUgj^B z3S}`$i^=2p7A+H0h}VNc7lllM{+eHk_$T(6E_T)=rWJ!l18gRJC)+ZtX|^nyl`X-J zz+k~~f8z>&ma}hM=Ktm5VQ27@#qmGIGPMO);N<j2>BEa3%>zo|j#0p^kqN$HA`sff zZcG|ib$^K0E#tE0I=zV<>F$;ev>`PTkB2+c)!L;?s$OCCnm?)@NS{-uxnp#t+44E+ zgGP=kN}N3&d?|n5a^0l0EARz!7#qZ+yX8fa&Zp;)tH}qdbHFTIkg1-wQmI7r<r&k_ zm=&g6o9zgc<z~F2HG1H}`;^h<@r2{8&8zD7tgn}8H(jwJwEdn2gy=cmd3^Qiw3^p6 zy~S$ly4cdHb2If0Z?$US8M+;;Rq41Msf^P&)v4Z)HW<Fhn4{3RPDYPs+yQe7w-z%i z5<VVE*oHGhuGQKuS7<(~(Y0{3$asUTM3i>Ozg%<<O`>eo<iE~K%$#;}JC<qYUSxyC zz4c!mAF*%YRZqY0eVH>Gifo!_cLSW;QUsfsZBIGwC8-`YgZidp!6j@);Oh9kYgepw zZlXnGm65TQ{~`8rr`o2by3`cZm1Uei3Z7)v0cUZy>_awkSC?r-1RRN8w)e?}k=6?k zDg$@7QLpInxnUt`SxScAJC<d}M(MpVs8Q6=h_ZO?(7DAeSi&HqTEJs^ONq=UNr55x z``e95lIBOq>Wc=_%?mi0h_n-(aclf2OE<M?WpJVmvNAKD8ozyLa3ZLB!?T*tz1!lb z(q?5VgGYJpEB)xXJdKcwyad!A6Nb2hTc;iS)g-SXH?pBWI=ooNo!oHAas0!Ugk(o{ zwDD7!V?cTAZg$D$H~HIcW7br>GHxk5v8nEZAgpE0hj$M9vpaam`Qe)7=O!+OwqKqY zem=^uZ^2hQRV*v&9$fz@r`uj1)Zg1V=6h1=Sug~Ce6m?#y1;AcQBRLF!oK(p_oGQE z=MR-!C-w$xsSF*o$Wa=rHU6g6ceG;`B4oRgiAfGI9Np4|M-#mXcy|pSb}nXY!t~io z>V~X|?BZ^xp*`+Su4uOzgn`-zg>6T8U5cA$`?$$O`6=Xak{z(*;NhGrRFt9FnjrhN zo}cn#CaN}G@Y>sNe<L@s^pUA@&lw+`ZZ*=j|0MeAy+oC>Z@STrzwQ@ZGH><Hr|ueG zZhg1bes{vf4_2OKgY#yJ$lIuHt5L1M+;f?0o8!tNrrS2}L7yf!t?9Y#PH>3&Jj2|J z>2={u{FmlZsgXq0Qy)?+y&rn`%RX7jr%OSf){jumgfy~y0|!X<km5PryuaolAU@=C z;~mzk-Q@880;KPO(vp;*TzpShZn0u0>g=cI{k{hdWM1m=d+}>h_E_A=0f(ruI~D52 zo2}VCmA&^Y>Sl9<d$Oi^7yZJ{qHOgD@br_qXab)`yT;8-D-2P2Z?)f~=6`;DzIMC* zn&9}V{73~fT-(x<^V{WrMC74hc{Q!F3AbsizH^o6NE6RT0)&pujV~uq>C+<n8(x}W zHhG8Mv`q(ZApMc1I$^bst$SV8A$QLop(;eb9xmNer+XjYQweAl_A|NKeXf;EpG8-+ z*16-FgvYd^ss<KBEs>{POG<0_IKIlUFljjUwhF_`%v#Xvb!ExHNMX^=f(7;uoW*tz zN#+}xsA_+oMHcCpUa3aPfRA`$-a*g5UY`<O{KNZ%`b(qk9bH~t8o#Y4dg#)ZYjvKZ zw^y1ZL)|3NiT0hV{w^#=6u?<6H0{V4N^CD(>5B2Zn;IB?!~OldgP)%ipPJ}xDN7`- zuqyzPRr&!Zp%-S03@QQ->5_T#fKzURrAY7N2^+ZXiH}<tbFO>PuL;%m3y+g_t_!x0 zh&Gw!ty-vyx8pggga0HO9&zs4SW_~tw#;^2X=xILs7qF>QU%)YALr{}mvYJ1j%n`g zGh7+x(SGVxE-ILNtF!c<a_kKU!vKM=6@giGeEqE8n2hwd{@Ca9xgG0rmX8#MrG~k@ z<Q%@WP}eo<UAf;K>cp$Q%P3Xfy($$7g$+seAC4|$o6pN{+3%b0IM{I6W@%6^&O)AM zS#O~H?a!`wLuTmQeJ9KB=@V;yNiShFc|cw2-79L}ajo=c;*oY5_cyeMWmZ|8zWZco zXsBU}8LPzLDtUe|&%`sWy(|!vX6q#|AXPl?Ja1W%*2~u;ng+Y#f*VQb)e*J5TI#%! f@}#ldi0O!vTdIvha5=7%zg=!DFXn0b+NA#gUrZy5 literal 0 HcmV?d00001 diff --git a/css/images/train/f-seat.jpg b/css/images/train/f-seat.jpg new file mode 100644 index 0000000000000000000000000000000000000000..84a2dccb6a458300183924447c5f7fcac83c4ff9 GIT binary patch literal 2468 zcmbVMc~nzp7JnfN$Q}un5tnCJ8W2cc2qB39$)*isFhZ13sx~BnL`Ysp0t8%;ph%-t zWKlT^rijQW_9zOpMHH8rQkc38DvL}Nsj^61DLPd%4+QKVo}Qk$=e={j?|%3Ge)oRg zz1P-hyAOB?jH)C65DEhU2jGL)9s_uOx-2CNKmiy;%?1G5eKf2z7_=-hS)&h;%Hc#s zhzwSfjZ!Tc3Zakz_F|(}Doarqz(hr|N)thR(sY3cs^k&G_%IPgq~$4;s?V}@in#0; zi7Y!s#*`BmM}ll4%c$0>6$UA2RHth6EMo+50-S}c$JJyaIALN)i6C;uS;4=F#2^pW zDZsFh&|nz_f<QVw1fqq}=}-_zr9f0N1^MW~5RDZ^XHmn!Ng*O^I(ZT+mcL|@3)w{w zCzHy|%nZp44S{vZWQfURj$=@%!H7k$K1*Ye8iO@@pD6^sLNC*)v<4Nd0ml)giEz3h zf`~-=J_WT_B$@{P=xwRh<9SV3>kYAr4`F=NS})1cD#)=4J)EwSDG+m?DQD#F{+MXo z5Q&DhT&F@FMViWoW$9{##vtTJ5RsD*xk}FB^QlZKog<(^0;V7wf|wL8g%c*=(J1sV zj$jEih4C?8E}z5XLE&5h2ckicAe=)BXYiOzD3rqB@wrU?l&?^uH%K)y#T2g!;hps5 z{Gl(4r&CA`uucNQsZ$joR>B5YuY|QAFOCk9;#C?soT(2Of1dZ*@)bH&hC;qX2dlw} z`(>#<!q4G_Q6R2>LZJ&d6L~Wz6dp4i3J;}1R4SK8ob;9dKX*n(f+3F=$M1?|N`+M5 z_;R}Rk<E1TC^SgN=#bX1SpnCHf(PU+NDHEDJ-{{qhrwX57#tRhn}I`qCkGtP!O7Xt z(aF)#+1+_U+?`$B+}&KAJv;~m505$C-rjTOPYcT4-rmL8#mn8@YqlrebN2MXpIz8m z0K5Yb2o#`Ec)$*iLgP`kE5K#|g#yqhM5bp5293p`?Cl(Wr<y!-2T*7`w4K8YC+vF- z$_|YIu=ts{1s)KGNUb9n!dBei#)jsdp?OMk_g+jiRmSP*_Bz=SUkUyL!z7%o8*oOW zkXX=oU@`D+?@dhkBKPw1#ofpA(l`sg@3{yzo!wkI|9I}Rl$?j}JdHK;XEnZq@5h@> zr?^|eKG*9?-*ZL59t8~i+?#H9X-<&;4NUQuP`B^l0fOgs62TE`mm6gft6uIH>8v<2 zf!caqyXJ6$DEH(iiJuGyo2cq%)zn{lk1`%uTet9{c{x_D7f31JN_t+i=;Cf~qj7*$ zvt{6i!DE#q%DSeCoa9W4a@M*>xn11@j!q<kNA&|Zu5Qh;eLGK?mi_b6zsm}%9tjOH zGZb^<pgGSw^F(N2pGdPQ{Zd83vcCkRV~=$_IpPvD=fuM2y7F@pr?9@>?0UiXJ@ba$ z{poXe{kqbJ>e-^J_2WGv%n}RLO$k=@`TkEcYrb00x#!UFnD`^L4MR*0;}`K|{F#fK zwRU;Ss}^gnj8@!|cqh-{DHpD8+cx5#SDxX)+0MRvzu&U;bV=2&4A<GNn-9(!Ub*bT zlV`))#Fn8hO8c#Kh1N~4Mt-`jy&Uo{M#f{8H%4VzY2@(N)kU@6-jfLL-y?Xx`m1Wi zK^L;I1lZLnt@m+7bMi;;zW8lXGdiknjO}{$PLz0cl;ySkb4xLNiyW0d&oyU3kN0Um zH3`_!S+cL=p094z0sYVV`6J@Qo2SuhtUp`a+bePAvPf%N>A)3LFiI2kqG(S6yPNHO zxX2{38@&_TXbB!m_{Wbck_Lt0PWcZF2du4y9S783Yg!e`9Q=h<9km`UX<jD6V0(G@ zTe4`dr@3u|dgrQ2UeSS4Vo+I3w}$Jx<WT8cbwt5#Nj-3CRos_9s4?9carxNlww)b^ z^Lp#mL%uynVosLLocUwP1Lx5OGoiaYt;*Er5c{;hVkK5TN;^q;JZN3#x9I5Eipr#* z{p-`au;NEiJk8RqF~ZS^Th(n`)7=%Z+O`;?DZ*#t?Znr~H^xrn4L99QhW=jFH=LW= zGtb<=gNW@5ZRq%QjJfpF1v7jc-D*{CJ*Oj*>sMkMHBU0FFSp|=W<D6raz6KPcw=#3 zU8!EkmbjjTZ9wCjXv^Ekni`XrYGkPKyKBD3l0Ih)&}Wei>xbqQSlY9#S#Qh#lWSSM zvBEw%#X<_Qh?o2K!X<B1Gi9{jp6*+lKU@%fyWK40Bt(n-97!u;0{R%@?46r1F&WuD zw6bdr`Rn$T__7;%0!iFMXlhYWJ;9WbsHAXDuLcjaZHK?|6n9EK+rBR$^~~Jp=#uuV zsMfAHm7h-%Xe3cYH?vozf7|2VWoc{J9}iy24h@0Mr)@~nSUZY#4Xx>@tc84wIeUA< zkCittH)Pzww<lcLZwbgRohu*l6A}6sGb~S4<&2=}E5YJ-4snIu|7}_u@6W8WQms#a zYIHtJIH;(P$9!IjFHTb(U8<3)7xmZGV*}29m;Z&S$`rTT%j`g#YG)a9d#kyjFe>&` zONGm}d4Vp=TaLaSc^mjl9El}gg9qcyxlaSOY|M#1C-GjGx|DdT`Yu>h`ArN%x^>PM zMiRR@lWo2FB<gxl^ELZ3_1BT6o1PiM4P&@w`%-Jgjzd`&*0&?gHa<yY#a8PJrupTe jt8NP)zf$6xd%sDBBKMSC?0<V0i;I3gZV(JNTi5>p_V%9- literal 0 HcmV?d00001 diff --git a/css/images/train/f-seata.jpg b/css/images/train/f-seata.jpg new file mode 100644 index 0000000000000000000000000000000000000000..63fb12881aefa7196fe913a394f02a89702a985b GIT binary patch literal 3078 zcmbVNdo<MP8~@J5j9aclZmls`w`R<YnPCRG%nae@e%;FMj+w#GT+9q3mr{{ZDA5*@ zYtoiB_f1kK){-c+a!ZL?Td0sWwSGgf`$uQb@BE(g{l4dYpZD|JpXa<Q4_BT5TJ(5M zH~_f0nFF%G-?Z`)P^HB(qxS$H04inM0l>-=2tQIR7EmlLc_Ivh#Sdd+n0&5fJVRiK z!(c4|JBN4ygBi^hBg5Dc9G*RDuDKP3<gn~f!9-82r+~_i<ZMq6vi%dh0+<QWOfn1Q zunlP!Pl@LWxNI>48PDC#6H(&rQESR6()}vi5`|oYh@<UMPODatA)Y=+DqqM(5;0b2 zCKiW7l1LaFfk-0Zwj%LZ9NrQu{YYpWfkGrv@YcxBgpyhlvcf5TG?&k|q$hjS=b$7K z2}WXt;R_=yabz-iRR<oAmLkxiJv=cZ9?cUOu4|yNMNA<_Am;FS$W@JuFn+Aq9wqhk zQwUsvr{{*^FJ_C&U5#rEEfV{&|90bxXi>l(0o&4#E#k)tnQSTCa9voMyMH&d3Y2<7 z@fLEVMPclw@tLt)Hc#wEvqwp9Ff0y>LZjiyc#;zxkE4_6);Js)>x^|G(y0V2iReUk z!L94~qO6MzfkY$V=uS8y4o9~pTT=;6)^sN;Ype~HO5c!m<B7x!9+SOpm$Pd3lPvaM zWhqo4n<3^41Ni*i>mA?|$rtlQk$eG?>Q6$N26K2UzC>iUTAokQ(%3>y9Gm4L<a3d0 z`K55aVBZ-_#NwRkSS*R|v=+Aw7E2{t<E*XlI6U5&iux?e`hRj}DRstjwK@LLEbA<3 z2d-{6T3>qD7#=oHIx#}&XspZvN^1=dux?665VSG^qyjJ~6e<IS$;iOuVA5Yf76y}5 zP?VQfke63fQCuSxMI~hwWhF&*bp%3PT~Ak6S5JR~KyWyGlj0^V6%{QV4OI=Djf?+v zvvLzql?BX!!w`@v09FM-R6#3kKs^8g0bq!9*&rxH1_qY}fu%eM0QtuS0D;PYz%aN9 z0D^!aV7Q!uoZOle2n>M&GOB7Y19hB}FCL)*M>*G6)e^)+5@Y|ZFyX<I0d)gfF@6X7 zn78|5HH}is11mOL2g^$R0D-{}MffK*tGNQJLe!u*-xvcY#)*>qc)vb%gv|b{D4~^x z=Br!Ir8S2B1lY<jpeXfA3RMLhfQ78%M$->dXI>Wt2EZm#9{0W-8xkou-T9$zPS@AD zrX#m*;^h8YZjt5LVx9fZ3@-I&pA65hRtlLvm%TJt(>mY!s@CD4xB8|Ce$KONg;$?L z8ojzYA=U5pgx%5qx$?-N+U!q!a<^pY_-&z9NKAUp4>~a>h$?ff3dc7pQR41SdZlZ5 z(VOjcUdYEZ$##e0NWs>&0-BnaQAcFXUdLjKVgxwFM;_#8DgzV~-cyGjo+D2MI`T}F zVZUiF8s<-r>8r(^*j!!N{B4DK;=SMQUTrHullr$d<y~3cTAOjSJZ4iK0sR}XEU}gQ z)EZY1({d1j{Hbz=8-00;t3uGO4pRf0m(U5phh}s2?Qe@x-l}`;vq*a@4!T>N@i1xJ z{`G9)o5cc)!K&x)ZEt|8r+nFqcFL~NHxV+q;FPo0x(R1<`dD?LscPXQ&BE?96N*Qf zo^M9nvC#k+X)Y+jpe=v&-HSB4hSPYzKNP&H#x-?9$U(u6rflOc$mGA~wd^Pz<7SHw ztLrNLl4yS7jQnGAkXp%H2Dl6C!5tnKahD8iTWB1mwxlUPVapbFqwg5>X&zP4rN<q7 z4dlpKNUy!RP1JQUrC}znaR>U!Xtnowf>vkGa#vgGF-Kj%D8~zspYU@F%-K<Ik>i_j z>CEKvctk@`UE5{q`9)pH@28e_@FvFTLc>h>gA?`a7<Y4-oi-Mjpi?@P{$oSEcgKQe zcix;Ti>354I(FTN=<5!VXz@(!ZOflM8OQg3gJ-n=+@Uv`r16zycv?GiDYR=kBa=k> zYhF@8Kqyq7%e!zTxZzS<WFM4p<9x7jhrX#o*Qo-tV4~y8cNW*tUtb(k-AOFU#aIXq zk?TVVqr(XYYhPq$g&%KdWET|_+9qyt!uO>S0-Ej`!>yuck8i*Ecu%x@zn6Jd<&oZz zLcUv%&8`A*f5i*Z;1&Pg1xXUb57GX^z$^PLR{$SPA9=_H+W<B0`-<OHZr|#;H<S4= zry&=hzI6A95~$hco!46$?RXmiLtCg2t7qPW6t5v8t4_|otonAVOU^ybN#!1Q%B^Sj zJAYm>l_Mw&hPppWX&mEkHl`O;7>#0d&-5{yQB*%hLt3*zUdacSk30Q-@&>hq$s(rj zoE`pX={Y^p(iO!$8dOTnIh}{vdd6#*=WOIsn74&%e>f|k9{4H9|40WHL^_-MWIv~- zbkU@0cDP|tjeEZ`sQZW<t1ISE!cMw8*Q=?|DF$j5FEP1RY;mrtf|DNMEqrY@hAv-J z$FZ(0SO03BP66u*ZF`$4%w{u5ehAHpjFX4_Vi3>-m!(VXZ+gq-g5iUbrXHrhTl*k* zsKH*NQ;DX~7QwBWnH6R|H;^-whcpn@d+BNNwH2UU(mLC^JG{7iLHoza*5UNZh1!zD zZB5hPO@{_ET0`F#R425Sx&1!pJ|BGQkL5$@ow@-wQJIx`XlwU-i{xcV;)n#@@s(m= zpohCh(mvO>!7Bh`Us?CZD2d>OP<eCyU&_5|nVy#Poy$bNXUHP_TaUoWU8kxKfB4Vk z(-&FCw#b;sfW~89?XC`=C`qHtp2gp9vFlB=`91`@aPmXoBU|qkz-n2};m@+xi0q)6 zWPP{vzm7h=5|c0)m;7R2{^OQ$;6WMiO|m!S{_raq5F02qImv76+DkZs%TIpifw>*q zW*p6KH!8kdVXBsfFs($q)-zSU(0G&fJfhUft#CP#J<V~Z-r?4irkdTfGBdOA-EI>8 zb;>RIcGdx=xyB7bAeG^Z()@;7(;aJO?vI{=7_vRfb2Crx?{xgWpnT!di<kz_TBkfN zrrIfWA$%7zX<}evY^=&yd!W9G9unsEb;_@^1^qoEdiA!^ho>%2c-%wWcF(Gb%Q>GR z)KBu!hn?v^(6!t7fpV3+Q1?66=+em!Qs^(CkF*<}oJuJlL0@b_O<p)waMaV>R;0ig zH_p3Y=2_8g1=TQ8D-^W(sBn}c!jhin1%i}0l<>Wk_k(ry;5t#eT6$*qdB#_-B{zD7 zrC#1OphpUj6i;cMkldNa)h1ZwMgCaEbamaUy*NHNv(LkDcG2V3os@-f-;f8}jED6P zB}*2Uzw7&Txy4Se2|f@+^ga@o{^VTf$Gw9KHQVOA;TX`OMyCHnXjx-3^4=g<`+WKE zY_@9xwLjR*JfosY8_~ZV$SbMMLKm6WhmE90_BuQpdKiwWq7!mC&Gm&1i+}8Slr@(U zCBjN;2Vbw<#v1@K{;^x<^_Hdl_@bC+AGXbaLV>jhLTmER=IcFS*CVVB-gtMt4s2ae Y-~G&_ecr}){Ai~m>z|K^!^+Tq0dQf)mjD0& literal 0 HcmV?d00001 diff --git a/css/images/train/f-seath.jpg b/css/images/train/f-seath.jpg new file mode 100644 index 0000000000000000000000000000000000000000..fbf310f28d95aee2d5baeff3e289afa88ac005cb GIT binary patch literal 4652 zcmaJ_c|276-=DGXl$|j4CCrRv80!o(cCtq(gR#VzF*D4_QkKe|C`OA)5t2kI`w+6U z(5(n5`x4<IJI}cH_IsW`?(;jZbIx};pZDkU{%qerPO77WB`=o*7XSd@wYEYzGsYCg zqsGC+c+c=8e`gHhWV8p_1s_PJV2D@%G63&~1zF=TL0D%jCLlVZ8*2mrFb9UXdXPQr z?F{_!I8Dr<j3yOFV4wj2BU35?;~$D8gZ!{TA>qbyOARe@ppXD#xs$r~5PO0-HaNuU z91-hs&cW6HT&O=hK+e<zWJEP!D8OOK7!VZ~7EUst8q58q*MKoU+y={m{t_XF8q57n z%ER6fWR53dLAsjS8vYO{6a<55LUnXuFsM363j);wLl`$q1FB=73p3Et1O0Q!F{}{- z0u7u|7XR2{tc>M?$z*~77)+s1G%4Decw!J33WviFb!cg6FeEfc(cxqaRU@1v|62nJ zOY$d%5Xd3;aL}Pfj2}LdY%IrM`nL->g1!BJ6o-@k2^1q_U@C?HhH65<INYIMe@T<b z&e;E@@vqV(*JuJ3?2IMhBZ>Zud<4q>1~X#!-whoKGT0cLAcioKf(b+6{UdSMaI!VZ zSdQ^UGaw|u0EN<mYr&9cEhrj})`LRf5Hko;7j3Qsf$1XA7SP{1{tb(?fWROYW>5>b znFSPz*3*Z<;rdWL9etP%6t1NY`;D~@Cy_DX{@CAkLl}1d!9xBk*1(*I#gOqtS3ExK zcLg{G<H>kZFrEN1cY%RaPKJaB;3*{4!}R>^EecBviNXe05b-$BU-2~v`4{^r3w<3J zN(X{QLUj+h!}ZK{ka}pOwjM+uVvc6`{Wmt?-(vPR7W)5U!3;9s!{Ycq#qxWLQGtik z|CBys@t@|whBG>b$Y>2-nW9$!0H3!t3h7E6TJZ7;6Yh|_^X1D|(xNI3UB{&+q9U5k zn(ic&!8(Ohq^4VBruGLHK}~`)_-||mWTd9@Tgb#NOFIejiXDN-TKI2yp{!6kC`~h! zVvRMTW=vGne#@69Qh7uNFB@);FVB=~NP*J}Tk+pEb~Lpw<3}6e9El|*N}Xa7dDyY* zmqm|9c3*&|Z)KD%^Gm^gULPM(gP%qZ-3q+uQ^~Ug=hk<*B^)PQ13!s*Snw$S(}wBZ znxJ&p+=t?Rhd;#f^EHZH%TJtJGiFD!=5stFUsSi5OQ&V_+gT&Hobn4D!xe3j%nC|G z%y6Esw~bOeeN17`?B3mN@M_qEm@sd~(hl=8{4!X55!7z!VfTYVf8b{`$W(rY*eKJb zGAZl4UCR-yj?s2nGkWLkRfU*SL<zajvYn}Iu_h;YW!pD9Clnw7ny((RcIaSN`oi^5 zy&B)ZY$Ag0A!;?fYwQxNeKhQF)OXun5qH(Fxia6+?gv=)kl5kO$n62{MBi*qIO}v` zb<JHd7S=1ORxmd7=gRw&XM}hN`PZH`Ge_*uewu&wUQ72X2NL-+T?7=iUF4Sd9O@3v zrKje+nLGU=xrDUj`(x~y;FbP3_vi$$`mma1+&yuDxH5=PRo8TELrKXHSjcUJOF&=6 zL+XWwv?6ph4AFtWI*K2-Mp^tMAJp?+_HOmwP&cKXGV&qqtv{dGq_ccqX|9r+4=4iC zR(2;0#nRg?#&j=y?u}c`%E~f->V#k&7)@dy;*;Xbv|_#LYcy|EDwTZFx(Nu)^72h- zJrVS)I)5UohyAsZyO*28=jXSJ2sE-HEyFfnT(F-%==L}hr}Sd(HdOm`(55IRb+f@k zUBc^QzyEpiS&JJ$CvItC-22s8r?+dZalZuK9kh^;&U7V_ba)o?7odM4OY6O>h6$H} zLM4_-`La(Vd_-%i)Jt+7o9A*oSY@}PRaYHR?W!Y{cLkc8C!fug&0&d&iAjA`CNl`A zq8eqj3RyE9)pGZ@Qv?sn1v)v~T~!cix4gAN%F+anPYn${x}A1biD-wY^LzVt7_8z; ztn-$;3i_l(?YqF@QYK{mEtBe)`{8Jw&`;(eBnz)syLt_u_>`4U@S0n-8SYzsF|FI1 zCSqPHAk8N2qO8+h0eup@5U%B&p*l0_t3tm70><~R{V>`Q)ATE>&+cAOP;<m-F%^}W zq$bCrMcK#{iXbdFcL^$xS0i@AjQTy2g)h+Vf>XlGX*!)883_~?kocZ}6!5(IGBvTQ z)fd2$2JFoTA8bxs390JeLk@D*NXKuE@tf{uFYpX-9D73pklxfih{wA4n@`m8a#t1_ z?wBzv<#u1dNyjWaJ$WWh*b1OPU*4LzbN?xB7?z{YGoGn8N?q%>>^F(u)mKQTsNPCv zTPd#Ld>w+rDIQ!|2{<dCLhC(m;UFr3Nsbno^n||WD(pE9Bb$i^EgH5Ae;oPH*n}N8 z)3CvFnqOmnTyhEHAls!TJ^9Xhldrq-RPB5^xEUnMR2H{2l~2Wmga89|rgKl2cs8BW zl{mk@HDkOnV(#wOhCTX>^LFM)neuH1!8ptw(8EI8uZLQCRvMkf^P&;tM^i-ukX{i= z<5ud|Uw!I}SNCm`2^Y(G;l|he(wX&XQHQaq?ypjWj^liRcF@n!rkJJCCWVv}j1#2n zVPWF+>~H%MS4`s%_BJH(jYk#(v^Y<<(KNiC)8CCo&qy6Pt@kZf`_fgzx!GCj_XKto z9qQOcQ4p2~&>4Kph`N05vUHIug&~<Ls0`U}+8B*lZe_<@q)*cmm?7Y`YzKs_h^BW} zFV1lObuCR&R7B@4Js|&mc0n%&EgGT3Y@)85<akDYjP0v;HA@hoex|%li*Y!nrE$?X z6n2L3Ey%lvO!xP84)%BOzEwf*3%}F^owy0hT$9-5{%Sd~xABeLw~Eawc4fSSel*>8 z*B0EwQb&o3@>94a2tqN7`S;*ne1%2-IaydJt<o-h(mP_nhl1HnWaa+;0wO&a_O)IZ za>2G+cntHiVaX&G<>{N&eyX{WC;b|?iz-K)-m{m(2DxD#N-nc3K1zSy=u4ig|M0f6 zS)Y^B?5wV??iJJh%}SpJ&=>ogFyn*W)!N!x%D1?Ujc@1qdE&RGMEmkpZ#vK*z&Yjd zus3mwwF6xwM7!zkGIP#u+|Dm#52U20$0m61$CDO^C^pyT?fK)ryFJIBIA-ks+51;H zx9o5K7^x#ga4P};n`_F2RKJPNOokzTgMr6hFM|8!q=ND(0FcQU5hEp!7Xgco$80$( zD<3@x^{y5;zph>KFs6F`nFnE~P`*hqmj<$0U$eWDeKy#mYO?-P$7<+mZb=NH=(3xw z?c`%e-p-ML(lpkl=BYd{lbr?awZ@&F4Vjslv+R%`15eo52&Stu?;n0VI*1stGVQ+t zb)dGs1279DeongWD=^?q;&nSmV8p~}A^&Y4zG>Y(S@LCvoSU0lZ=MD-rIqt*%u<sf z<!5`MOx#+({1u~W;#AM{bl_%<yk!=>ip>@R=QiKD#_QF+b1{u3n7<{6d;F_CO>^<= zh-xHB$;Sk{ddYsjYzzbzlu{zqVIQ4bMqyt+ohVnSo9HBZ>YaI;Bf;Bx1nU7=eRjNa zXjQN-=`AP)-?H~>dF&Nw`VEk0eSLkI-4UbD5Ac`sSBpm82tWkCdZ$9}Je#e5w<u9k zk>(*2&Rps%26<IsS6Y?~wNE}8%P45yI?tLw4bSSy{hcLtAk$Ep%frOks#Bi6-X1p8 zKvo%A+Ls8=!RPx8{z&>n#NNxVU(A7L>Z3l5cxp#UEgo}Ntg3ukSbS9D4Bn`mY5LN4 zEXi`~9XiyV5@9NmYeLd$GiHA$Q<Sg(5_0UhiEoa6Ekyx{HR}3z@@xvfr07S{Ep#=B zkP;4Dj&!z|BhV6g4bm!Q7)95IurkBK2A3yuPcTW2wDDaK;K}mSpz3Pr_Q^N)uFd_? z>hB?NXJ?`2y&phe{`l<m7h)D(%L4w1EBAN!pNqzsp(*YP!%|Td4I1!OXX8Pcw8S-x zL}bM}A@phAWv=ERt%&xkIQCy|PyL+Js<I+9V|fB>I%v9~pD&CIRQlLPKu}vFr1!0t zeDz9BC9Qy<jb<CFy{#IcgatzSuWPC<0)DMA@~~Gz$x(<$O-)k%Rr_uyeb&d*!G3WW z=cfyT1m?by|FEaM^y}bS9%giV+$&x^fby~$-JF2@X(=k&W7)*lmEoDdoqvq*uspFi z=OMvN3&SejdAv4z@!r<!6DMt7TvE<ezQ+}rgw3g-0rERy&vd>%CRQ%)Vgh^(i1vw| zx?U2-Bax7cu(C+yi1afm;Fh2j^0XwDIkc6Jp8KIOd5=S-O2V73jmt`WnkhM3_TJ?Y zVTqL9vS~Jlq|nyt$jC?`yIdH3Rd8+v-@L{4m_hUQI)3WIqbFBjW2Sw}DxadqyWX2F zi7hKW@fxBte`&<MCMY=bt4+Mix^tj+_x#F-OR00V1rwnI_zl@(UrjG<Bhvd3v*KU> zkX&KYPUcX$mm@l&Z<L^#KbB~EIUiOWEC$?)9eG|`Ykx~Wf^OhiS@NkgkyD$AdTq<{ zIIYSRkq&kJ3SGKU9~2t;1Do$tBJ~F33ai)^$S_{`DBsECG}|Olu9dA+z!$*fdUwcG zB#AJ_e<4lP&@3xk$}yoLg4<Qa_Vw`xsgYgkc1Ve&70s##VyzF>o?Wr_REB_D?PLMQ zvzC&jV);?-bcF|x>l?>J^tkgJ-$h$qwBjtfya|d>V*vo#*lyG5*Q8|6ATF|%az6Pk zmm_gn*1i!P-}N!1Yo(8jxCrfUli0S$=DxZ3Yf443c<}wPRl`SnVjUG`fo*L=y%Te` zJyVzJUxFI_f}Sf+yR$?G^SyXC6AxR|_z)%XsVC)iid$(tIs#{uK}Oi1kh3TRmPvae zELgDh*p7v12k}`1VsAP&9d2#I;k4ioU?o{LJ2%{5_^5A{N;%a{T~Ds)Eq2*{UxT~i z<)C!6l>#3n#XCW7grb<u6RLt+#F^y$WRJ?fWmWrVUciMWKf97jdHb1f>ajv_xr(G{ zO6w)bvY&|O*u*1u&3bd9*E?o|R(ZYlhu-dA6m2&3NLe$Uk1r#bU1MtP7g1Q@{{rmj z>kRp$5-5@K;A(tf4(l(MV<NH-%^nq0b=;DI^aC|)Pg~0P_#He=7rMj4gcGzWsA)(} zgCl|BK=hEaxiU`pK8_{R!DZ&5`iC$U#CG7LYiusJ---z?8VkC85aPOBi_UutnU`rM z?5z~OB3t7scAqcr3i8=%d$F7b7ATSIn2s1LO0JIvk<J$ACtD>AwYyr7%CyfZB!%^6 zzrO&>RH(bT4^$qvJKw!`{zJ~J#lygX>Ld9_t+v;LhjY@f1$q{Ag5{Eihofk>e@0FE zz;{F1sZ&};H+wu=dpkNc<F6xm0tJ$<mmZ7)+qKy`XY4v~nsLim=k^My;Z{*>fiKq) zML{cfFq5_rq-S8VqczgVH({+Ira%H4CQx0Pm=B&#doyr(_eg5SH}mnJ1@2z99iDjf zQr=eOZHntzcU;`PS$DX*AKBqg){7NW`fkR54o<lk2adtXN)q0v02N=_KKenC1Y}Ko z>-}VXwCAYc$vG$Dc84_0n(bH0+MvsJRSTCtAmYe%WI{w6Zqys;(QRX8KYtq#-eI9Z zT8eazkh=aF?bzyF9FVuOth16%6M&?QtJW0%Ip2-ASz|-JYj=Zb&}Na@!%wKDz%^JR zB=6ptedtvl!=jeS`_A$bxk~n0t9CP+`)_6Rf{<^(a68_gMkaZxF|=_I7T16Oo4jGg e9=>iLOb67C^$zIS91A=Ae`AeyKvkOgCjJkXIvkt; literal 0 HcmV?d00001 diff --git a/css/images/train/f-seath.png b/css/images/train/f-seath.png new file mode 100644 index 0000000000000000000000000000000000000000..fbf310f28d95aee2d5baeff3e289afa88ac005cb GIT binary patch literal 4652 zcmaJ_c|276-=DGXl$|j4CCrRv80!o(cCtq(gR#VzF*D4_QkKe|C`OA)5t2kI`w+6U z(5(n5`x4<IJI}cH_IsW`?(;jZbIx};pZDkU{%qerPO77WB`=o*7XSd@wYEYzGsYCg zqsGC+c+c=8e`gHhWV8p_1s_PJV2D@%G63&~1zF=TL0D%jCLlVZ8*2mrFb9UXdXPQr z?F{_!I8Dr<j3yOFV4wj2BU35?;~$D8gZ!{TA>qbyOARe@ppXD#xs$r~5PO0-HaNuU z91-hs&cW6HT&O=hK+e<zWJEP!D8OOK7!VZ~7EUst8q58q*MKoU+y={m{t_XF8q57n z%ER6fWR53dLAsjS8vYO{6a<55LUnXuFsM363j);wLl`$q1FB=73p3Et1O0Q!F{}{- z0u7u|7XR2{tc>M?$z*~77)+s1G%4Decw!J33WviFb!cg6FeEfc(cxqaRU@1v|62nJ zOY$d%5Xd3;aL}Pfj2}LdY%IrM`nL->g1!BJ6o-@k2^1q_U@C?HhH65<INYIMe@T<b z&e;E@@vqV(*JuJ3?2IMhBZ>Zud<4q>1~X#!-whoKGT0cLAcioKf(b+6{UdSMaI!VZ zSdQ^UGaw|u0EN<mYr&9cEhrj})`LRf5Hko;7j3Qsf$1XA7SP{1{tb(?fWROYW>5>b znFSPz*3*Z<;rdWL9etP%6t1NY`;D~@Cy_DX{@CAkLl}1d!9xBk*1(*I#gOqtS3ExK zcLg{G<H>kZFrEN1cY%RaPKJaB;3*{4!}R>^EecBviNXe05b-$BU-2~v`4{^r3w<3J zN(X{QLUj+h!}ZK{ka}pOwjM+uVvc6`{Wmt?-(vPR7W)5U!3;9s!{Ycq#qxWLQGtik z|CBys@t@|whBG>b$Y>2-nW9$!0H3!t3h7E6TJZ7;6Yh|_^X1D|(xNI3UB{&+q9U5k zn(ic&!8(Ohq^4VBruGLHK}~`)_-||mWTd9@Tgb#NOFIejiXDN-TKI2yp{!6kC`~h! zVvRMTW=vGne#@69Qh7uNFB@);FVB=~NP*J}Tk+pEb~Lpw<3}6e9El|*N}Xa7dDyY* zmqm|9c3*&|Z)KD%^Gm^gULPM(gP%qZ-3q+uQ^~Ug=hk<*B^)PQ13!s*Snw$S(}wBZ znxJ&p+=t?Rhd;#f^EHZH%TJtJGiFD!=5stFUsSi5OQ&V_+gT&Hobn4D!xe3j%nC|G z%y6Esw~bOeeN17`?B3mN@M_qEm@sd~(hl=8{4!X55!7z!VfTYVf8b{`$W(rY*eKJb zGAZl4UCR-yj?s2nGkWLkRfU*SL<zajvYn}Iu_h;YW!pD9Clnw7ny((RcIaSN`oi^5 zy&B)ZY$Ag0A!;?fYwQxNeKhQF)OXun5qH(Fxia6+?gv=)kl5kO$n62{MBi*qIO}v` zb<JHd7S=1ORxmd7=gRw&XM}hN`PZH`Ge_*uewu&wUQ72X2NL-+T?7=iUF4Sd9O@3v zrKje+nLGU=xrDUj`(x~y;FbP3_vi$$`mma1+&yuDxH5=PRo8TELrKXHSjcUJOF&=6 zL+XWwv?6ph4AFtWI*K2-Mp^tMAJp?+_HOmwP&cKXGV&qqtv{dGq_ccqX|9r+4=4iC zR(2;0#nRg?#&j=y?u}c`%E~f->V#k&7)@dy;*;Xbv|_#LYcy|EDwTZFx(Nu)^72h- zJrVS)I)5UohyAsZyO*28=jXSJ2sE-HEyFfnT(F-%==L}hr}Sd(HdOm`(55IRb+f@k zUBc^QzyEpiS&JJ$CvItC-22s8r?+dZalZuK9kh^;&U7V_ba)o?7odM4OY6O>h6$H} zLM4_-`La(Vd_-%i)Jt+7o9A*oSY@}PRaYHR?W!Y{cLkc8C!fug&0&d&iAjA`CNl`A zq8eqj3RyE9)pGZ@Qv?sn1v)v~T~!cix4gAN%F+anPYn${x}A1biD-wY^LzVt7_8z; ztn-$;3i_l(?YqF@QYK{mEtBe)`{8Jw&`;(eBnz)syLt_u_>`4U@S0n-8SYzsF|FI1 zCSqPHAk8N2qO8+h0eup@5U%B&p*l0_t3tm70><~R{V>`Q)ATE>&+cAOP;<m-F%^}W zq$bCrMcK#{iXbdFcL^$xS0i@AjQTy2g)h+Vf>XlGX*!)883_~?kocZ}6!5(IGBvTQ z)fd2$2JFoTA8bxs390JeLk@D*NXKuE@tf{uFYpX-9D73pklxfih{wA4n@`m8a#t1_ z?wBzv<#u1dNyjWaJ$WWh*b1OPU*4LzbN?xB7?z{YGoGn8N?q%>>^F(u)mKQTsNPCv zTPd#Ld>w+rDIQ!|2{<dCLhC(m;UFr3Nsbno^n||WD(pE9Bb$i^EgH5Ae;oPH*n}N8 z)3CvFnqOmnTyhEHAls!TJ^9Xhldrq-RPB5^xEUnMR2H{2l~2Wmga89|rgKl2cs8BW zl{mk@HDkOnV(#wOhCTX>^LFM)neuH1!8ptw(8EI8uZLQCRvMkf^P&;tM^i-ukX{i= z<5ud|Uw!I}SNCm`2^Y(G;l|he(wX&XQHQaq?ypjWj^liRcF@n!rkJJCCWVv}j1#2n zVPWF+>~H%MS4`s%_BJH(jYk#(v^Y<<(KNiC)8CCo&qy6Pt@kZf`_fgzx!GCj_XKto z9qQOcQ4p2~&>4Kph`N05vUHIug&~<Ls0`U}+8B*lZe_<@q)*cmm?7Y`YzKs_h^BW} zFV1lObuCR&R7B@4Js|&mc0n%&EgGT3Y@)85<akDYjP0v;HA@hoex|%li*Y!nrE$?X z6n2L3Ey%lvO!xP84)%BOzEwf*3%}F^owy0hT$9-5{%Sd~xABeLw~Eawc4fSSel*>8 z*B0EwQb&o3@>94a2tqN7`S;*ne1%2-IaydJt<o-h(mP_nhl1HnWaa+;0wO&a_O)IZ za>2G+cntHiVaX&G<>{N&eyX{WC;b|?iz-K)-m{m(2DxD#N-nc3K1zSy=u4ig|M0f6 zS)Y^B?5wV??iJJh%}SpJ&=>ogFyn*W)!N!x%D1?Ujc@1qdE&RGMEmkpZ#vK*z&Yjd zus3mwwF6xwM7!zkGIP#u+|Dm#52U20$0m61$CDO^C^pyT?fK)ryFJIBIA-ks+51;H zx9o5K7^x#ga4P};n`_F2RKJPNOokzTgMr6hFM|8!q=ND(0FcQU5hEp!7Xgco$80$( zD<3@x^{y5;zph>KFs6F`nFnE~P`*hqmj<$0U$eWDeKy#mYO?-P$7<+mZb=NH=(3xw z?c`%e-p-ML(lpkl=BYd{lbr?awZ@&F4Vjslv+R%`15eo52&Stu?;n0VI*1stGVQ+t zb)dGs1279DeongWD=^?q;&nSmV8p~}A^&Y4zG>Y(S@LCvoSU0lZ=MD-rIqt*%u<sf z<!5`MOx#+({1u~W;#AM{bl_%<yk!=>ip>@R=QiKD#_QF+b1{u3n7<{6d;F_CO>^<= zh-xHB$;Sk{ddYsjYzzbzlu{zqVIQ4bMqyt+ohVnSo9HBZ>YaI;Bf;Bx1nU7=eRjNa zXjQN-=`AP)-?H~>dF&Nw`VEk0eSLkI-4UbD5Ac`sSBpm82tWkCdZ$9}Je#e5w<u9k zk>(*2&Rps%26<IsS6Y?~wNE}8%P45yI?tLw4bSSy{hcLtAk$Ep%frOks#Bi6-X1p8 zKvo%A+Ls8=!RPx8{z&>n#NNxVU(A7L>Z3l5cxp#UEgo}Ntg3ukSbS9D4Bn`mY5LN4 zEXi`~9XiyV5@9NmYeLd$GiHA$Q<Sg(5_0UhiEoa6Ekyx{HR}3z@@xvfr07S{Ep#=B zkP;4Dj&!z|BhV6g4bm!Q7)95IurkBK2A3yuPcTW2wDDaK;K}mSpz3Pr_Q^N)uFd_? z>hB?NXJ?`2y&phe{`l<m7h)D(%L4w1EBAN!pNqzsp(*YP!%|Td4I1!OXX8Pcw8S-x zL}bM}A@phAWv=ERt%&xkIQCy|PyL+Js<I+9V|fB>I%v9~pD&CIRQlLPKu}vFr1!0t zeDz9BC9Qy<jb<CFy{#IcgatzSuWPC<0)DMA@~~Gz$x(<$O-)k%Rr_uyeb&d*!G3WW z=cfyT1m?by|FEaM^y}bS9%giV+$&x^fby~$-JF2@X(=k&W7)*lmEoDdoqvq*uspFi z=OMvN3&SejdAv4z@!r<!6DMt7TvE<ezQ+}rgw3g-0rERy&vd>%CRQ%)Vgh^(i1vw| zx?U2-Bax7cu(C+yi1afm;Fh2j^0XwDIkc6Jp8KIOd5=S-O2V73jmt`WnkhM3_TJ?Y zVTqL9vS~Jlq|nyt$jC?`yIdH3Rd8+v-@L{4m_hUQI)3WIqbFBjW2Sw}DxadqyWX2F zi7hKW@fxBte`&<MCMY=bt4+Mix^tj+_x#F-OR00V1rwnI_zl@(UrjG<Bhvd3v*KU> zkX&KYPUcX$mm@l&Z<L^#KbB~EIUiOWEC$?)9eG|`Ykx~Wf^OhiS@NkgkyD$AdTq<{ zIIYSRkq&kJ3SGKU9~2t;1Do$tBJ~F33ai)^$S_{`DBsECG}|Olu9dA+z!$*fdUwcG zB#AJ_e<4lP&@3xk$}yoLg4<Qa_Vw`xsgYgkc1Ve&70s##VyzF>o?Wr_REB_D?PLMQ zvzC&jV);?-bcF|x>l?>J^tkgJ-$h$qwBjtfya|d>V*vo#*lyG5*Q8|6ATF|%az6Pk zmm_gn*1i!P-}N!1Yo(8jxCrfUli0S$=DxZ3Yf443c<}wPRl`SnVjUG`fo*L=y%Te` zJyVzJUxFI_f}Sf+yR$?G^SyXC6AxR|_z)%XsVC)iid$(tIs#{uK}Oi1kh3TRmPvae zELgDh*p7v12k}`1VsAP&9d2#I;k4ioU?o{LJ2%{5_^5A{N;%a{T~Ds)Eq2*{UxT~i z<)C!6l>#3n#XCW7grb<u6RLt+#F^y$WRJ?fWmWrVUciMWKf97jdHb1f>ajv_xr(G{ zO6w)bvY&|O*u*1u&3bd9*E?o|R(ZYlhu-dA6m2&3NLe$Uk1r#bU1MtP7g1Q@{{rmj z>kRp$5-5@K;A(tf4(l(MV<NH-%^nq0b=;DI^aC|)Pg~0P_#He=7rMj4gcGzWsA)(} zgCl|BK=hEaxiU`pK8_{R!DZ&5`iC$U#CG7LYiusJ---z?8VkC85aPOBi_UutnU`rM z?5z~OB3t7scAqcr3i8=%d$F7b7ATSIn2s1LO0JIvk<J$ACtD>AwYyr7%CyfZB!%^6 zzrO&>RH(bT4^$qvJKw!`{zJ~J#lygX>Ld9_t+v;LhjY@f1$q{Ag5{Eihofk>e@0FE zz;{F1sZ&};H+wu=dpkNc<F6xm0tJ$<mmZ7)+qKy`XY4v~nsLim=k^My;Z{*>fiKq) zML{cfFq5_rq-S8VqczgVH({+Ira%H4CQx0Pm=B&#doyr(_eg5SH}mnJ1@2z99iDjf zQr=eOZHntzcU;`PS$DX*AKBqg){7NW`fkR54o<lk2adtXN)q0v02N=_KKenC1Y}Ko z>-}VXwCAYc$vG$Dc84_0n(bH0+MvsJRSTCtAmYe%WI{w6Zqys;(QRX8KYtq#-eI9Z zT8eazkh=aF?bzyF9FVuOth16%6M&?QtJW0%Ip2-ASz|-JYj=Zb&}Na@!%wKDz%^JR zB=6ptedtvl!=jeS`_A$bxk~n0t9CP+`)_6Rf{<^(a68_gMkaZxF|=_I7T16Oo4jGg e9=>iLOb67C^$zIS91A=Ae`AeyKvkOgCjJkXIvkt; literal 0 HcmV?d00001 From b110df3fff426be4bc24a50b37deda327ce4357b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Sun, 12 May 2019 13:14:30 +0800 Subject: [PATCH 333/382] paypal Trippest --- webht/third_party/paypal/models/paypal_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 0f8697f5..0c53cc56 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -607,8 +607,8 @@ class Paypal_model extends CI_Model { { $sql = "SELECT top 1 * from BIZ_ConfirmLineInfo WHERE 1=1 "; - $tp_order ? $sql.=" and COLI_PriceMemo=$tp_order " : ""; - $real_orderid ? $sql.=" and COLI_ID=$real_orderid " : ""; + $tp_order ? $sql.=" and COLI_PriceMemo='$tp_order' " : ""; + $real_orderid ? $sql.=" and COLI_ID='$real_orderid' " : ""; return $this->HT->query($sql)->row(); } From 74fa02151b0b5044bafc13068e43302317764b2b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 13 May 2019 09:30:23 +0800 Subject: [PATCH 334/382] =?UTF-8?q?wxpay=20=E9=85=8D=E7=BD=AE=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/config/wxpay.php | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/webht/third_party/pay/config/wxpay.php b/webht/third_party/pay/config/wxpay.php index b4752bff..30f0a87c 100644 --- a/webht/third_party/pay/config/wxpay.php +++ b/webht/third_party/pay/config/wxpay.php @@ -1,7 +1,6 @@ <?php $config["sign_type"] = "HMAC-SHA256"; $config["trade_type"] = "NATIVE"; -$config["notify_url"] = ""; $config["currency"] = "CNY"; $config["currency_unit"] = 100; $config["method_code"] = 15016; @@ -9,17 +8,20 @@ $config["method_code"] = 15016; * 各账号的设置 */ // test -$config['test']["app_id"] = "wx426b3015555a46be"; -$config['test']["mch_id"] = "1900009851"; -$config['test']["key"] = "8934e7d15453e97507ef794cf7b0519d"; +$config['test']["notify_url"] = "https://www.mycht.cn/webht.php/apps/pay/wxpayservice/notify/test"; +$config['test']["app_id"] = "wx426b3015555a46be"; +$config['test']["mch_id"] = "1900009851"; +$config['test']["key"] = "8934e7d15453e97507ef794cf7b0519d"; $config['test']["app_secret"] = "7813490da6f1265e4901ffb80afaa36f"; // Trippest -$config['trippest']["app_id"] = ""; -$config['trippest']["mch_id"] = ""; -$config['trippest']["key"] = ""; +$config['trippest']["notify_url"] = "https://www.mycht.cn/webht.php/apps/pay/wxpayservice/notify/trippest"; +$config['trippest']["app_id"] = "wx7e605820faf98a05"; +$config['trippest']["mch_id"] = "1528541381"; +$config['trippest']["key"] = "b6f4db121410468e814d812c6c641efd"; $config['trippest']["app_secret"] = ""; // ChinaHighlights = China train booking -$config['cht']["app_id"] = ""; -$config['cht']["mch_id"] = ""; -$config['cht']["key"] = ""; +$config['cht']["notify_url"] = "https://www.mycht.cn/webht.php/apps/pay/wxpayservice/notify/cht"; +$config['cht']["app_id"] = "wxd6c8dd69af5128cd"; +$config['cht']["mch_id"] = "1353239702"; +$config['cht']["key"] = "aada7476b3fecc2c6e33a7c765298516"; $config['cht']["app_secret"] = ""; From 896cf8dc9740c49f1abc6d18733da18d2393f26c Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 13 May 2019 10:24:56 +0800 Subject: [PATCH 335/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=8F=91=E9=80=81?= =?UTF-8?q?=E9=82=AE=E4=BB=B6=E7=AB=99=E7=82=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/models/BIZ_train_model.php | 2 +- .../dingmail/controllers/index.php | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/application/third_party/trainsystem/models/BIZ_train_model.php b/application/third_party/trainsystem/models/BIZ_train_model.php index dcc64977..01c2ef1b 100644 --- a/application/third_party/trainsystem/models/BIZ_train_model.php +++ b/application/third_party/trainsystem/models/BIZ_train_model.php @@ -312,7 +312,7 @@ class BIZ_train_model extends CI_Model { AND ts_status != '2' AND - bcli.COLI_WebCode = 'cht' + bcli.COLI_WebCode in ('cht','WebMob-biz','WeChat-biz') "; $query = $this->INFO->query($sql); return $query->result(); diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index 7ee50452..e64b2b6b 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -192,6 +192,54 @@ class Index extends CI_Controller { return; } + //ajax发送邮件 + public function ajax_sendmail(){ + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); + + $data = array(); + $data['position'] = $this->input->get_post('position'); + $data['phone'] = $this->input->get_post('phone'); + $data['email'] = $this->input->get_post('email'); + $data['name'] = $this->input->get_post('name'); + $data['sex'] = $this->input->get_post('sex'); + $data['school'] = $this->input->get_post('school'); + $data['education'] = $this->input->get_post('education'); + $data['currentcompany'] = $this->input->get_post('currentcompany'); + $data['from_time'] = $this->input->get_post('from_time'); + $data['to_time'] = $this->input->get_post('to_time'); + + $mailnody = ''; + $mailnody .= '应聘职位:'.$data['position'].'<br>'; + $mailnody .= '手机号码:'.$data['phone'].'<br>'; + $mailnody .= '电子邮箱:'.$data['email'].'<br>'; + $mailnody .= '姓名:'.$data['name'].'<br>'; + if($data['sex'] == 0){ + $data['sex'] = '女'; + }else{ + $data['sex'] = '男'; + } + $mailnody .= '性别:'.$data['sex'].'<br>'; + $mailnody .= '毕业院校:'.$data['school'].'<br>'; + $mailnody .= '最高学历:'.$data['education'].'<br>'; + $mailnody .= '当前公司:'.$data['currentcompany'].'<br>'; + $mailnody .= '任职时间开始:'.$data['from_time'].'<br>'; + $mailnody .= '任职时间结束:'.$data['to_time'].'<br>'; + + $tolist_array = array(); + $tolist_array['0'] = new stdClass(); + $tolist_array['0']->ddu_Email = 'cyc@hainatravel.com'; + + if($this->do_sendmail('cyc',$tolist_array,'','应聘简历',$mailnody)){ + echo '{"status":1}'; + }else{ + echo '{"status":0}'; + } + } + //执行邮件发送功能 public function do_sendmail($fromuser, $tolist_array, $cclist_array, $subject, $mailbody) { $this->load->library('Phpmailer_lib'); From d05810b93f4468ed349083640a8aab33d19fd996 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 13 May 2019 15:51:30 +0800 Subject: [PATCH 336/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B7=A8=E5=9F=9F?= =?UTF-8?q?=E5=A4=B4=E9=83=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 078bf373..8f7e05a0 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -10,6 +10,7 @@ class returnorders extends CI_Controller{ $this->load->model("train_system_model"); $this->load->model("Sendmail_model"); $this->load->model('BIZ_train_model'); + } public function index(){ @@ -17,6 +18,11 @@ class returnorders extends CI_Controller{ } public function returntickets(){ + header('Access-Control-Allow-Origin:*'); + header('Access-Control-Allow-Methods:POST, GET'); + header('Access-Control-Max-Age:0'); + header('Access-Control-Allow-Headers:x-requested-with, Content-Type'); + header('Access-Control-Allow-Credentials:true'); //第三方订单号(为了避免一个子订单乘客分开出票而产生错误) $ordernumber = $this->input->get_post('ordernumber'); //护照姓名 From 22c6858d63110bb25b39504360cc3a59ad67c699 Mon Sep 17 00:00:00 2001 From: LMR <59361885@qq.com> Date: Mon, 13 May 2019 15:53:06 +0800 Subject: [PATCH 337/382] =?UTF-8?q?=E5=AE=B9=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/controllers/information.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/controllers/information.php b/application/controllers/information.php index cac198b1..9de4109c 100644 --- a/application/controllers/information.php +++ b/application/controllers/information.php @@ -554,7 +554,7 @@ class Information extends CI_Controller case 'ru': case 'jp': $information = $this->Information_model->Detail($url); - if ($delete_only || $information->ic_ht_area_type === 'q') { + if ($delete_only || !$information || $information->ic_ht_area_type === 'q') { //只删除操作,在url修改和不发布信息的时候使用 $url = $this->config->item('site_url') . '/index.php/welcome/update_cache/delete_only?static_html_url=' . $url; } else { From 075cd9635f26dce5723b1ae133de9681f67cdde9 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 13 May 2019 16:15:05 +0800 Subject: [PATCH 338/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=82=AE=E4=BB=B6?= =?UTF-8?q?=E5=8F=91=E9=80=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/dingmail/controllers/index.php | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index e64b2b6b..b11f4bda 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -254,7 +254,13 @@ class Index extends CI_Controller { $mail->CharSet = "utf-8"; $mail->Encoding = "base64"; $mail->IsHTML(true); - + $mail->SMTPOptions = array( + 'ssl' => array( + 'verify_peer' => false, + 'verify_peer_name' => false, + 'allow_self_signed' => true + ) + ); $mail->FromName = $fromuser; //收件人昵称 $mail->From = 'admin@hainatravel.com'; //发件人 From 62f13bca2a6e747c2b17c1a62f9231d9c9ba7710 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 13 May 2019 16:41:57 +0800 Subject: [PATCH 339/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=AB=AF=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/dingmail/controllers/index.php | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index b11f4bda..b09ddda8 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -246,21 +246,16 @@ class Index extends CI_Controller { $mail = new PHPMailer(); $mail->IsSMTP(); $mail->Host = 'smtp.mxhichina.com';//smtp.sendgrid.net - $mail->Port = 25; + $mail->Port = 465; $mail->SMTPAuth = true; + $mail->SMTPSecure = false; $mail->Username = 'admin@hainatravel.com'; $mail->Password = "Hainatravel123";//Hainatravel1234 - $mail->SMTPSecure = 'tls'; + $mail->SMTPSecure = 'ssl'; $mail->CharSet = "utf-8"; $mail->Encoding = "base64"; $mail->IsHTML(true); - $mail->SMTPOptions = array( - 'ssl' => array( - 'verify_peer' => false, - 'verify_peer_name' => false, - 'allow_self_signed' => true - ) - ); + //$mail->SMTPDebug = 2; $mail->FromName = $fromuser; //收件人昵称 $mail->From = 'admin@hainatravel.com'; //发件人 From 3506581a546a29ad1a994532eecdb6d2c3db3e7b Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 09:52:43 +0800 Subject: [PATCH 340/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9value=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dingmail/controllers/index.php | 29 +++++++++++++++++-- webht/third_party/dingmail/views/mail.php | 6 ++-- 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index b09ddda8..fa62d011 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -73,12 +73,13 @@ class Index extends CI_Controller { //value邮件页面 public function mail_index(){ - if($this->session->userdata('dingding_user_info') === false){ + /*if($this->session->userdata('dingding_user_info') === false){ $this->load->view('login'); }else{ //print_r($this->session->userdata('dingding_user_info')); $this->load->view('mail'); - } + }*/ + $this->load->view('mail'); } //发送邮件 @@ -231,7 +232,7 @@ class Index extends CI_Controller { $tolist_array = array(); $tolist_array['0'] = new stdClass(); - $tolist_array['0']->ddu_Email = 'cyc@hainatravel.com'; + $tolist_array['0']->ddu_Email = 'hr@chinahighlights.net'; if($this->do_sendmail('cyc',$tolist_array,'','应聘简历',$mailnody)){ echo '{"status":1}'; @@ -575,6 +576,28 @@ class Index extends CI_Controller { return; } + public function upload_photos() { + $save_path = date('Y-m-d'); + $jsfunction = 'get_photo_url'; + $upload_id = 'Profile_file'; + $config['upload_path'] = APPPATH . 'upload/' . $save_path; + if (!is_dir($config['upload_path'])) { + @mkdir($config['upload_path'], 0777, true); + } + $config['allowed_types'] = 'gif|jpg|png'; + $config['encrypt_name'] = true; + + $this->load->library('upload', $config); + if (!$this->upload->do_upload($upload_id)) { + $error = array('error' => $this->upload->display_errors()); + var_dump($error); + } else { + $data = array('upload_data' => $this->upload->data()); + $file_name = 'http://' . $_SERVER['HTTP_HOST'] . '/' . $config['upload_path'] . '/' . $data['upload_data']['file_name']; + echo "<script>parent.$jsfunction('$file_name');</script>"; + } + } + //退出 public function logout(){ $this->session->unset_userdata('dingding_user_info'); diff --git a/webht/third_party/dingmail/views/mail.php b/webht/third_party/dingmail/views/mail.php index cbcbdef3..de104df7 100644 --- a/webht/third_party/dingmail/views/mail.php +++ b/webht/third_party/dingmail/views/mail.php @@ -7,7 +7,7 @@ <title>HT在线平台</title> <!-- <link href="/css/webht/bootstrap.min.css" rel="stylesheet"> <link href="/css/webht/webht.css?v=1" rel="stylesheet">--> - <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js,/js/jquery.suggest.js"></script> + <script src="/min?f=/js/jquery.min.js,/js/bootstrap.min.js,/js/webht.js"></script> <link href="/min?f=/css/webht/bootstrap.min.css,/css/webht/webht.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="/css/webht/jquery.suggest.css" /> <script src="/js/TQEditor/TQEditor.js" type="text/javascript"></script> @@ -287,7 +287,7 @@ <h4 class="modal-title" id="myModalLabel">插入图片</h4> </div> <div class="modal-body"> - <form action="<?php echo site_url('apps/outlook/index/upload_photos');?>" + <form action="<?php echo site_url('apps/dingmail/index/upload_photos');?>" method="post" target="ifm1" class="form-inline form_upload_photos" @@ -322,6 +322,8 @@ </div> <script type="text/javascript" defer="true"> +jQuery.browser={};(function(){jQuery.browser.msie=false; jQuery.browser.version=0;if(navigator.userAgent.match(/MSIE ([0-9]+)./)){ jQuery.browser.msie=true;jQuery.browser.version=RegExp.$1;}})(); + var $img_modal=$('#myModal-img'); var doname="<?php echo $_SERVER['HTTP_HOST']; ?>"; var TQE=new tqEditor('emailcontent', From d7c18614e4387dce20668f4a9cb49cac3f05b153 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 09:53:30 +0800 Subject: [PATCH 341/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9value=E7=B3=BB?= =?UTF-8?q?=E7=BB=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/dingmail/controllers/index.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/webht/third_party/dingmail/controllers/index.php b/webht/third_party/dingmail/controllers/index.php index fa62d011..2a2549c0 100644 --- a/webht/third_party/dingmail/controllers/index.php +++ b/webht/third_party/dingmail/controllers/index.php @@ -73,13 +73,12 @@ class Index extends CI_Controller { //value邮件页面 public function mail_index(){ - /*if($this->session->userdata('dingding_user_info') === false){ + if($this->session->userdata('dingding_user_info') === false){ $this->load->view('login'); }else{ //print_r($this->session->userdata('dingding_user_info')); $this->load->view('mail'); - }*/ - $this->load->view('mail'); + } } //发送邮件 From d322fc2b2282f8ac40e6fa603c265e8e69bcbd10 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 May 2019 10:05:11 +0800 Subject: [PATCH 342/382] =?UTF-8?q?=E5=BC=82=E6=AD=A5=E9=80=9A=E7=9F=A5?= =?UTF-8?q?=E6=9C=AA=E5=90=88=E5=B9=B6.=E9=9A=90=E8=97=8F=E5=A4=9A?= =?UTF-8?q?=E9=80=89=E7=9A=84=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/views/payment_list.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/views/payment_list.php b/webht/third_party/pay/views/payment_list.php index 57310825..30580cde 100644 --- a/webht/third_party/pay/views/payment_list.php +++ b/webht/third_party/pay/views/payment_list.php @@ -115,9 +115,7 @@ <img width="150" style="height:40px;" src="/css/nav/img/6000.png"> </a> <h1>Payment List</h1> - <label> - <input type="checkbox" name="" value="15016" checked readonly class="input-check"><span>微信</span> - </label> + <ul class="nav navbar-nav navbar-right pull-right" style="margin:7.5px 0;"> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false"><?php $userdata=$this->session->userdata('admin_chtcdn'); echo $userdata['OPI_Name']; ?> <span class="caret"></span></a> @@ -135,6 +133,11 @@ <div class="col-md-4 col-xs-24 print-none"> <div class="row"> <form method="post" id="search_note_list" action="/webht.php/apps/pay/paymentservice/note_list/"> +<!-- <div class="input-group"> + <label> + <input type="checkbox" name="" value="15016" checked readonly class="input-check"><span>微信</span> + </label> + </div> --> <div class="input-group"> <input type="text" name="keywords" value="<?php echo isset($keywords) ? $keywords : ''; ?>" class="form-control" placeholder="订单号" style="height: 33px;-webkit-box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);box-shadow: inset 0 0px 0px rgba(0,0,0,0.075);border-bottom:1px solid #ddd;"> <span class="input-group-addon search-btn" onclick="$('#search_note_list').submit();"></span> From 6c725b32e2b2e31577eba1030b14eebf8acd83e3 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 10:17:09 +0800 Subject: [PATCH 343/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=80=80=E7=A5=A8?= =?UTF-8?q?=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 8f7e05a0..67110fe4 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -41,12 +41,14 @@ class returnorders extends CI_Controller{ $ticket_data = $this->train_system_model->ticketfrom($ordernumber); $passenger_data = $this->train_system_model->get_passenger_info($ordernumber,$passportname,$passportno); - $channel = $ticket_data->ts_channel; - if(empty($passenger_data)){ - exit('乘客信息为空无法退票'); + header("HTTP/1.1 404 Not Found"); + exit('{"reason":"乘客信息为空无法退票","status":"404"}'); + exit(''); } + $channel = $ticket_data->ts_channel; + switch ($channel){ case 'juhe': $this->juheModel($ticket_data,$passenger_data); From 5f4c41fe30f7cec94aba914c7ebcc0d079e0d531 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 May 2019 10:46:07 +0800 Subject: [PATCH 344/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 1 + webht/third_party/paypal/controllers/index.php | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 65fb8869..f5a83729 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -394,6 +394,7 @@ class IPayLinksService extends CI_Controller //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->IPL_payType == 'refund') { + $this->send_refund($item, $old_ssje); // $this->Note_model->update_send($item->IPL_dealId, 'send'); continue; } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 168f2891..8ff6abca 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -747,7 +747,8 @@ class Index extends CI_Controller { } //退款状态默认为已经处理,陆燕在退款前手动通知外联了,系统跳过处理 if ($item->pn_payment_status == 'Refunded') { - $this->Note_model->update_send($item->pn_txn_id, 'send'); + $this->send_refund($item, $handpick, $old_ssje); + // $this->Note_model->update_send($item->pn_txn_id, 'send'); continue; } From 91d3cb29343c06599f5cf9102dbff09e3806bcd7 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 May 2019 10:58:45 +0800 Subject: [PATCH 345/382] =?UTF-8?q?iPaylinks=20=E6=8E=A8=E9=80=81=E5=88=97?= =?UTF-8?q?=E8=A1=A8=E7=9A=84=E5=8F=91=E9=80=81=E7=8A=B6=E6=80=81=E6=98=BE?= =?UTF-8?q?=E7=A4=BA;?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index ba7942ca..37c43624 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -196,9 +196,9 @@ class Note_model extends CI_Model { $sql = "SELECT -- gai.GAI_SN, -- gaib.GAI_SN, - -- COLI.COLI_ID, + -- COLI.COLI_ID,IPL_payType='pay' and case - when IPL_payType='pay' and (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 + when (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 when IPL_payType='pay' and coli.COLI_ID is not null then 99999 when IPL_payType<>'pay' then 10000 when IPL_sent='closeRecord' then 10000 @@ -207,8 +207,8 @@ class Note_model extends CI_Model { ipl.* from InfoManager.dbo.IPayLinksLog ipl left join Tourmanager.dbo.BIZ_ConfirmLineInfo coli on coli.COLI_ID=ipl.IPL_orderId and coli.COLI_Department=16 - left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 and ipl.IPL_payType='pay' - left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 and ipl.IPL_payType='pay' + left join Tourmanager.dbo.BIZ_GroupAccountInfo gaib on ipl.IPL_dealId=gaib.GAI_AccreditNo and gaib.DeleteFlag=0 --and ipl.IPL_payType='pay' + left join Tourmanager.dbo.GroupAccountInfo gai on gai.GAI_AccreditNo=ipl.IPL_dealId and gai.DeleteFlag=0 --and ipl.IPL_payType='pay' where 1=1 and ( (ipl.IPL_stateCode=2 and ipl.IPL_payType<>'pay') or (ipl.IPL_resultCode='0000' and ipl.IPL_payType='pay') ) $this->send From a3c214f6f7d234991f0f61dd1038f8db027553bb Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 11:14:15 +0800 Subject: [PATCH 346/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9warning?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/trainsystem/controllers/api.php | 1 + 1 file changed, 1 insertion(+) diff --git a/application/third_party/trainsystem/controllers/api.php b/application/third_party/trainsystem/controllers/api.php index 7091dbfd..b4ef1121 100644 --- a/application/third_party/trainsystem/controllers/api.php +++ b/application/third_party/trainsystem/controllers/api.php @@ -26,6 +26,7 @@ class api extends CI_Controller{ $return_data = array(); $i = 0; foreach($tickets_info as $items){ + $return_data[$i] = new stdClass(); $return_data[$i]->cold_sn = (int) $items->ts_cold_sn; $return_data[$i]->ordernumber = $items->ts_ordernumber; $return_data[$i]->status = $items->tst_status; From 89e6840f1874cec3bfeef59f916a457c3af56af1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=B9=E8=AF=9A=E8=AF=9A?= <ycc@hainatravel.com> Date: Tue, 14 May 2019 11:28:10 +0800 Subject: [PATCH 347/382] =?UTF-8?q?CDN=E5=88=86=E5=8F=91=E4=B9=8B=E5=90=8E?= =?UTF-8?q?=E6=BA=90=E7=AB=99=E5=9F=9F=E5=90=8D=E4=BF=AE=E6=AD=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/config/config.php | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/application/config/config.php b/application/config/config.php index 684dda6a..f04b8859 100644 --- a/application/config/config.php +++ b/application/config/config.php @@ -18,7 +18,26 @@ if (!defined('BASEPATH')) | path to your installation. | */ -$config['base_url'] = ''; + +//CDN分发之后,源站和前端域名不一致在这里修正,否则程序生成的链接是源站的域名 +$base_url=''; +switch ($_SERVER['SERVER_NAME']){ + case 'origin-ct.mycht.cn': + $base_url='https://ct.mycht.cn'; + break; + case 'origin-gm.mycht.cn': + $base_url='https://gm.mycht.cn'; + break; + case 'origin-cht.mycht.cn': + $base_url='https://cht.mycht.cn'; + break; + case 'origin-int.mycht.cn': + $base_url='https://int.mycht.cn'; + break; + default:$base_url=''; +} + +$config['base_url'] = $base_url; /* |-------------------------------------------------------------------------- From 521a20e5367fd023151d3c19a6fdf29587ac6e06 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 14:58:41 +0800 Subject: [PATCH 348/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=80=80=E7=A5=A8?= =?UTF-8?q?=E5=90=8E=E5=8F=91=E9=80=81=E9=82=AE=E4=BB=B6=E7=BB=99=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/controllers/returnorders.php | 38 ++++++++++++++----- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 67110fe4..f0605b31 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -86,20 +86,38 @@ class returnorders extends CI_Controller{ log_message('error','聚合退票:'.$ticket_data->ts_ordernumber.'|'.$back_json); $back_data = json_decode($back_json); + $fromName = 'trainsystem'; + $fromEmail = 'cyc@hainatravel.com'; + $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn); + $coli_id = $coli_id['0']->COLI_ID; + $info = $this->BIZ_train_model->get_operatorInfo($coli_id); + $toName = $info[0]->OPI_Name; + $toEmail = $info[0]->OPI_Email; + $Mobile = $info[0]->Mobile; + $subject = '退票请求'; if($back_data->error_code == '0'){ - //退票成功后发送一封邮件 - $fromName = 'trainsystem'; - $fromEmail = 'cyc@hainatravel.com'; - $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn); - $coli_id = $coli_id['0']->COLI_ID; - $info = $this->BIZ_train_model->get_operatorInfo($coli_id); - $toName = $info[0]->OPI_Name; - $toEmail = $info[0]->OPI_Email; - $subject = '退票请求'; + //退票成功后发送邮件 $body = $back_detail_data->result->ordernumber.' 提出退票,乘客:'.$data->tst_realname.', '.$back_detail_data->result->start_time.' '.$back_detail_data->result->checi; + //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + //发送邮件给客人 + $customer_subject = 'returntickets'; + $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.')have been cancelled online successfully. Your travel advisor('.$toName.',email address:'.$toEmail',phone number (+86)'.$Mobile.')will contact you with the refund details via email within 24 hours.'; + $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); + $customer_email = $customer_email[0]->GUT_Email; + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); echo '{"reason":"退票成功","status":"200"}'; }else{ + //退票失败后发送邮件 + $body = $ticket_data->ts_ordernumber.'退票失败'; + //发送邮件给外联 + $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); + /发送邮件给客人 + $customer_subject = 'returntickets'; + $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.')has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number (+86)'.Mobile.'will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); + $customer_email = $customer_email[0]->GUT_Email; + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); header("HTTP/1.1 404 Not Found"); echo '{"reason":"退票失败","status":"404"}'; } @@ -147,8 +165,10 @@ class returnorders extends CI_Controller{ $info = $this->BIZ_train_model->get_operatorInfo($coli_id); $toName = $info[0]->OPI_Name; $toEmail = $info[0]->OPI_Email; + $Mobile = $info[0]->Mobile; $subject = '退票请求'; $body = '乘客:'.$data->tst_realname.' 对订单:'.$data->ts_ordernumber.'发起退票请求!!!'; + //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); echo '{"reason":"退票成功","status":"200"}'; }else{ From f0fd458f868ad1e1056b767a23d5db5a2e21e26a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 14 May 2019 15:19:50 +0800 Subject: [PATCH 349/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E5=87=AD=E8=AF=81:?= =?UTF-8?q?=E5=AE=A2=E4=BA=BA=E9=82=AE=E4=BB=B6=E7=9A=84=E5=8F=91=E9=80=81?= =?UTF-8?q?=E4=BA=BA=E5=90=8D=E7=A7=B0=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/AlipayTradeService.php | 2 +- webht/third_party/pay/controllers/iPayLinksService.php | 2 +- webht/third_party/paypal/controllers/index.php | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 07a44c19..56aafad6 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -698,7 +698,7 @@ class AlipayTradeService extends CI_Controller $c_M_RelatedInfo, $c_M_State, $c_M_AddTime, - 'Alipay refund receipt'); + 'ChinaHighlights refund receipt'); $this->Alipay_note_model->update_send($item->ALI_dealId, 'send-customer'); } //添加邮件发送记录 end diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index f5a83729..575af7ac 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -758,7 +758,7 @@ class IPayLinksService extends CI_Controller $c_M_RelatedInfo, $c_M_State, $c_M_AddTime, - 'iPayLinks refund receipt'); + 'ChinaHighlights refund receipt'); $this->Note_model->update_send($item->IPL_dealId, 'send-customer'); } //添加邮件发送记录 end diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 8ff6abca..30df9cbe 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1027,7 +1027,7 @@ class Index extends CI_Controller { $c_M_RelatedInfo, $c_M_State, $c_M_AddTime, - 'paypal refund receipt'); + 'ChinaHighlights refund receipt'); $this->Note_model->update_send($item->pn_txn_id, 'send-customer'); } //添加邮件发送记录 end From 014c8a77fcdbcb9a7d680c146728ef5e4fe762bd Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 16:05:43 +0800 Subject: [PATCH 350/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=80=80=E7=A5=A8?= =?UTF-8?q?=E7=A8=8B=E5=BA=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index f0605b31..c7c01ef9 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -102,7 +102,7 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'returntickets'; - $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.')have been cancelled online successfully. Your travel advisor('.$toName.',email address:'.$toEmail',phone number (+86)'.$Mobile.')will contact you with the refund details via email within 24 hours.'; + $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.')have been cancelled online successfully. Your travel advisor('.$toName.',email address:'.$toEmail.',phone number (+86)'.$Mobile.')will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); From 918e980cc0ac7e19974823f3f8bb62803d456b8e Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 16:14:03 +0800 Subject: [PATCH 351/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=82=AE=E4=BB=B6?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index c7c01ef9..a09cfa28 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -112,7 +112,7 @@ class returnorders extends CI_Controller{ $body = $ticket_data->ts_ordernumber.'退票失败'; //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); - /发送邮件给客人 + //发送邮件给客人 $customer_subject = 'returntickets'; $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.')has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number (+86)'.Mobile.'will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); From d81949e3d046fabed52df12ae813bc24d349a408 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Tue, 14 May 2019 16:48:07 +0800 Subject: [PATCH 352/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=87=BA=E7=AB=99?= =?UTF-8?q?=E7=A5=A8=E7=9A=84=E9=80=89=E6=8B=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/controllers/addorders.php | 13 +++++++++++-- .../trainsystem/controllers/returnorders.php | 4 ++-- .../third_party/trainsystem/views/homepage.php | 10 +++++++--- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/application/third_party/trainsystem/controllers/addorders.php b/application/third_party/trainsystem/controllers/addorders.php index f5ae9b28..13e874d5 100644 --- a/application/third_party/trainsystem/controllers/addorders.php +++ b/application/third_party/trainsystem/controllers/addorders.php @@ -156,7 +156,10 @@ class addorders extends CI_Controller{ $selectseat = $this->input->get_post("selectseat"); //接收出票接口 $type = $this->input->get_post("type"); + //接受是否有站票 + $this->istanding = $this->input->get_post("istanding"); } + //测试数据 /*$cold_sn = '488121613'; $bpe_sn = '473183645,473183646,473183647'; @@ -297,12 +300,18 @@ class addorders extends CI_Controller{ $passengers .= "]"; $passengers = substr($passengers, 1); $passengers = "[" . $passengers; + + $is_accept_standing = 'no'; + if($this->istanding == 'true'){ + $is_accept_standing = 'yes'; + } + if(empty($selectseat)){ $post_data=array( "key"=>JUHE_TRAIN_API_KEY, "user_orderid"=>$cold_sn,//自定义订单号 "train_date"=>substr($data["train"]->DepartureDate, 0, 10), - "is_accept_standing"=>"no", + "is_accept_standing"=>$is_accept_standing, "from_station_name"=>$data["train"]->DepartAirport_cn, "from_station_code"=>$data["train"]->DepartAirport, "to_station_code"=>$data["train"]->ArrivalAirport, @@ -315,7 +324,7 @@ class addorders extends CI_Controller{ "key"=>JUHE_TRAIN_API_KEY, "user_orderid"=>$cold_sn,//自定义订单号 "train_date"=>substr($data["train"]->DepartureDate, 0, 10), - "is_accept_standing"=>"no", + "is_accept_standing"=>$is_accept_standing, "choose_seats"=>$selectseat, "from_station_name"=>$data["train"]->DepartAirport_cn, "from_station_code"=>$data["train"]->DepartAirport, diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index a09cfa28..d2ca666f 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -102,7 +102,7 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'returntickets'; - $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.')have been cancelled online successfully. Your travel advisor('.$toName.',email address:'.$toEmail.',phone number (+86)'.$Mobile.')will contact you with the refund details via email within 24 hours.'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number (+86)'.$Mobile.') will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); @@ -114,7 +114,7 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'returntickets'; - $customer_body = '<p>Dear'.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.')has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number (+86)'.Mobile.'will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number (+86)'.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); diff --git a/application/third_party/trainsystem/views/homepage.php b/application/third_party/trainsystem/views/homepage.php index 832859b3..c19cd801 100644 --- a/application/third_party/trainsystem/views/homepage.php +++ b/application/third_party/trainsystem/views/homepage.php @@ -80,7 +80,7 @@ function selseat(seat){ <h3 class="panel-title">翰特订单号&nbsp;<a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/trainsystem/pages/order_list');?>">订单列表>></a><a style="margin-left:50px;" target='_blank' href="<?php echo site_url('apps/trainsystem/pages/export');?>">导出交易记录>></a> <span style="margin-left:200px;">版本:V2.0</span><span class="pull-right">聚合余额(RMB):<?php echo $balance;?></span></h3> </div> <div class="panel-body"> - <form style="width: 300px;float: left;" action="http://www.mycht.cn/info.php/apps/trainsystem/pages/index/" method="post"> + <form style="width: 300px;float: left;" action="/info.php/apps/trainsystem/pages/index/" method="post"> <input type="text" name="ht_order" value="<?php echo isset($cols_id)?$cols_id:""; ?>"> <button type="submit" id="sub" class="btn btn-warning btn-sm"><span class="glyphicon glyphicon-download-alt"></span> 获取信息</button> </form> @@ -107,6 +107,7 @@ function selseat(seat){ <th style="text-align:center;">抵达时间</th> <th style="text-align:center;">票价</th> <th style="text-align:center;">是否提交过</th> + <th style="text-align:center;">是否接受无座</th> </tr> </thead> <tbody> @@ -122,7 +123,7 @@ function selseat(seat){ <td><?php echo $v->train[0]->ArrivalTime;?></td> <td><?php echo $v->train[0]->adultcost;?></td> <td><?php echo !empty($v->status)?"否":"<span style='color:green;'>是</span>";?></td> - <!--<td><button type="button" class="btn btn-success pay_api" data-order="<?php echo $v->train[0]->FOI_COLD_SN;?>" title="超过五个乘客不可用" >快捷订票</button></td>--> + <td><input type="checkbox" name="istanding"/></td> </tr> <tr> <td colspan="11"> @@ -400,7 +401,10 @@ function selseat(seat){ }); people_sn=people_sn.substring(1); - url2+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat+"&type=juhe"; + var istanding = $('input[name="istanding"]').is(':checked'); + + url2+=$(this).attr("data-order")+"&people="+people_sn+"&selectseat="+selectseat+"&type=juhe&istanding="+istanding; + var THIS=$(this); THIS.parent().parent().find(".back_mes").html(" ");//清空提示 $.ajax({ From a0216c12c8721bb2bf55955459cb3877feaeb4ec Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 09:50:32 +0800 Subject: [PATCH 353/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E5=88=A4=E6=96=AD?= =?UTF-8?q?=E6=98=AF=E5=90=A6=E8=A6=81=E9=80=9A=E7=9F=A5=E8=B4=A2=E5=8A=A1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/AlipayTradeService.php | 5 +++- .../pay/controllers/iPayLinksService.php | 6 ++++- webht/third_party/pay/models/Alipay_model.php | 10 ++++---- .../pay/models/IPayLinks_model.php | 10 ++++---- .../models/Online_payment_account_model.php | 14 +++++++++++ .../third_party/paypal/controllers/index.php | 6 +++-- .../paypal/models/paypal_model.php | 25 +++++++++++++++---- 7 files changed, 57 insertions(+), 19 deletions(-) diff --git a/webht/third_party/pay/controllers/AlipayTradeService.php b/webht/third_party/pay/controllers/AlipayTradeService.php index 56aafad6..6bd08c44 100644 --- a/webht/third_party/pay/controllers/AlipayTradeService.php +++ b/webht/third_party/pay/controllers/AlipayTradeService.php @@ -50,6 +50,7 @@ class AlipayTradeService extends CI_Controller $this->load->model('Alipay_note_model'); $this->load->model('Alipay_model'); $this->load->helper('payment'); + $this->load->model('Online_payment_account_model', 'payment_model'); $this->gateway_url = $this->config->item('gatewayUrl'); $this->appid = $this->config->item('app_id'); @@ -703,7 +704,9 @@ class AlipayTradeService extends CI_Controller } //添加邮件发送记录 end // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 - + if ($this->payment_model->if_finance_exists($advisor_info->COLI_GRI_SN)===true) { + $this->Note_model->update_send($item->ALI_dealId, 'send-to-finance'); + } return ; } diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 575af7ac..1c0f04a2 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -21,6 +21,7 @@ class IPayLinksService extends CI_Controller // $this->config->load('dev_iPayLinks'); // test $this->load->model('IPayLinks_model'); $this->load->model('Note_model'); + $this->load->model('Online_payment_account_model', 'payment_model'); $this->gatewayUrl = $this->config->item('gatewayUrl'); @@ -762,7 +763,10 @@ class IPayLinksService extends CI_Controller $this->Note_model->update_send($item->IPL_dealId, 'send-customer'); } //添加邮件发送记录 end - // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 + // 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 + if ($this->payment_model->if_finance_exists($advisor_info->COLI_GRI_SN)===true) { + $this->Note_model->update_send($item->IPL_dealId, 'send-to-finance'); + } return ; } diff --git a/webht/third_party/pay/models/Alipay_model.php b/webht/third_party/pay/models/Alipay_model.php index 150e3c4e..a6d8322f 100644 --- a/webht/third_party/pay/models/Alipay_model.php +++ b/webht/third_party/pay/models/Alipay_model.php @@ -18,7 +18,7 @@ class Alipay_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class Alipay_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class Alipay_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class Alipay_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class Alipay_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 80a6af77..6b9f4a64 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -18,7 +18,7 @@ class IPayLinks_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode, COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -26,7 +26,7 @@ class IPayLinks_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID'"; $query = $this->HT->query($sql); @@ -36,7 +36,7 @@ class IPayLinks_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -44,7 +44,7 @@ class IPayLinks_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -60,7 +60,7 @@ class IPayLinks_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index 91fc6fa0..39e5c6a6 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -327,5 +327,19 @@ class Online_payment_account_model extends CI_Model { return $query; } + /*! + * 查询财务系统中是否已导入该团的账单数据 + * @date 2019-05-14 + */ + public function if_finance_exists($gri_sn) + { + $sql = "SELECT top 1 1 + from financedata.dbo.CW_GroupZD gz + inner join Tourmanager.dbo.CK_GroupInfo cgi on gz.GZD_CGI_SN=cgi.CGI_SN + where ISNULL(GZD_DeleteFlag,0)=0 and isnull(DelFlag,0)=0 + and cgi.CGI_GRI_SN=? "; + return $this->HT->query($sql, $gri_sn)->num_rows() > 0; + } + } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 30df9cbe..ac142a6b 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1031,8 +1031,10 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'send-customer'); } //添加邮件发送记录 end - // TODO 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 - + // 如果已做账, 标记需要通知财务send-to-finance, 通知时间用订单日志记录 + if ($this->Paypal_model->if_finance_exists($advisor_info->COLI_GRI_SN)===true) { + $this->Note_model->update_send($item->pn_txn_id, 'send-to-finance'); + } return ; } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 0c53cc56..a005ba0d 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -19,7 +19,7 @@ class Paypal_model extends CI_Model { $fieldsql = $orderinfo == false ? '' : " ,* "; //先查商务订单B,APP订单A、再查传统订单T if ($ordertype == 'B' || $ordertype == 'A') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_Email,OPI_FirstName,OPI_SN,OPI_Name,COLI_WebCode,COLI_Department,COLI_PayManner,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID =?"; $query = $this->HT->query($sql, array($COLI_ID)); @@ -27,7 +27,7 @@ class Paypal_model extends CI_Model { } //后查传统订单的原因是因为传统订单的订单号去掉外联名字首字母后可能会和商务订单的重合。 if (empty($result) && ($ordertype == 'T')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_State $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_ID like '%$COLI_ID' order by CHARINDEX('$COLI_ID', COLI_ID) "; @@ -41,7 +41,7 @@ class Paypal_model extends CI_Model { //查传统订单add_code,网前实时支付会先生成一个临时订单号存在add_code里,如订单45103248 if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_AddCode =? "; $query = $this->HT->query($sql, array($COLI_ID)); @@ -49,7 +49,7 @@ class Paypal_model extends CI_Model { } if (empty($result) && ($ordertype == 'M')) { - $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli + $sql = "SELECT TOP 2 1 as order_type, COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode $fieldsql from ConfirmLineInfo cli LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where EXISTS ( @@ -65,7 +65,7 @@ class Paypal_model extends CI_Model { //订单号查询不到尝试使用团号查询 if (empty($result) && $ordertype == 'B') { - $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo + $sql = "SELECT TOP 2 0 as order_type,COLI_SN,COLI_ID,COLI_GRI_SN,OPI_SN,OPI_Email,OPI_FirstName,OPI_Name,COLI_WebCode,COLI_Department,COLI_State $fieldsql from BIZ_ConfirmLineInfo LEFT JOIN OperatorInfo ON COLI_OPI_ID=OPI_SN where COLI_GroupCode like '%-$COLI_ID%'"; $query = $this->HT->query($sql); @@ -654,4 +654,19 @@ class Paypal_model extends CI_Model { return $this->HT->query($sql, $COLI_SN)->row(); } } + + + /*! + * 查询财务系统中是否已导入该团的账单数据 + * @date 2019-05-14 + */ + public function if_finance_exists($gri_sn) + { + $sql = "SELECT top 1 1 + from financedata.dbo.CW_GroupZD gz + inner join Tourmanager.dbo.CK_GroupInfo cgi on gz.GZD_CGI_SN=cgi.CGI_SN + where ISNULL(GZD_DeleteFlag,0)=0 and isnull(DelFlag,0)=0 + and cgi.CGI_GRI_SN=? "; + return $this->HT->query($sql, $gri_sn)->num_rows() > 0; + } } From 93372526825260be1ace17c6e36e6fc80e68ba45 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 15 May 2019 09:58:15 +0800 Subject: [PATCH 354/382] =?UTF-8?q?=E4=B8=8A=E7=BA=BF=E9=80=80=E7=A5=A8?= =?UTF-8?q?=E5=90=8E=E5=8F=91=E9=80=81=E9=82=AE=E4=BB=B6=E7=BB=99=E5=AE=A2?= =?UTF-8?q?=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/addorders.php | 8 +++++++- .../third_party/trainsystem/controllers/returnorders.php | 8 ++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/application/third_party/trainsystem/controllers/addorders.php b/application/third_party/trainsystem/controllers/addorders.php index 13e874d5..9de9a291 100644 --- a/application/third_party/trainsystem/controllers/addorders.php +++ b/application/third_party/trainsystem/controllers/addorders.php @@ -627,7 +627,13 @@ class addorders extends CI_Controller{ $PostData['TrainOrderService']->Order->TicketItem->ChildTicketCount = $ChildNum; $PostData['TrainOrderService']->Order->TicketItem->SeatName = $this->train_zw[$this->db_train_zw[$data['train']->Aircraft]]; $PostData['TrainOrderService']->Order->TicketItem->SelectedSeat = $selectseat; - $PostData['TrainOrderService']->Order->TicketItem->AcceptSeat = ''; + + $is_accept_standing = ''; + if($this->istanding == 'true'){ + $is_accept_standing = '无座'; + } + $PostData['TrainOrderService']->Order->TicketItem->AcceptSeat = $is_accept_standing; + $PostData['TrainOrderService']->Order->TicketItem->passport = substr($Passport,0,strlen($Passport)-1); $PostData['TrainOrderService']->Order->TicketItem->OrderPrice = $data['train']->adultcost * $AdultNum + $data['train']->childcost * $ChildNum; diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index d2ca666f..0742d87f 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -102,10 +102,10 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'returntickets'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number (+86)'.$Mobile.') will contact you with the refund details via email within 24 hours.'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); echo '{"reason":"退票成功","status":"200"}'; }else{ //退票失败后发送邮件 @@ -114,10 +114,10 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'returntickets'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number (+86)'.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'cyc@hainatravel.com',$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); header("HTTP/1.1 404 Not Found"); echo '{"reason":"退票失败","status":"404"}'; } From 690e2fd3433b75a6f45c7da07a85a69dcf05528c Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 15 May 2019 10:12:17 +0800 Subject: [PATCH 355/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=82=AE=E7=AE=B1?= =?UTF-8?q?=E8=BF=9B=E8=A1=8C=E6=B5=8B=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 0742d87f..2e6f9046 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -105,7 +105,7 @@ class returnorders extends CI_Controller{ $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); echo '{"reason":"退票成功","status":"200"}'; }else{ //退票失败后发送邮件 @@ -117,7 +117,7 @@ class returnorders extends CI_Controller{ $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); header("HTTP/1.1 404 Not Found"); echo '{"reason":"退票失败","status":"404"}'; } From 009653b1e1eba3ffc386d3b1673d8efdfe94db61 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 15 May 2019 10:45:53 +0800 Subject: [PATCH 356/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=82=AE=E4=BB=B6?= =?UTF-8?q?=E6=A8=A1=E6=9D=BF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/controllers/returnorders.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 2e6f9046..d2903963 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -91,7 +91,7 @@ class returnorders extends CI_Controller{ $coli_id = $this->BIZ_train_model->cold_sn_get_coli_id($ticket_data->ts_cold_sn); $coli_id = $coli_id['0']->COLI_ID; $info = $this->BIZ_train_model->get_operatorInfo($coli_id); - $toName = $info[0]->OPI_Name; + $toName = $info[0]->Name; $toEmail = $info[0]->OPI_Email; $Mobile = $info[0]->Mobile; $subject = '退票请求'; @@ -101,8 +101,8 @@ class returnorders extends CI_Controller{ //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 - $customer_subject = 'returntickets'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; + $customer_subject = 'China Train Ticket(s) Cancelation'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); @@ -113,8 +113,8 @@ class returnorders extends CI_Controller{ //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 - $customer_subject = 'returntickets'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_subject = 'China Train Ticket(s) Cancelation'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); From 6fe0fdbadfbcf84c5e3ec3bccf58c9d71bfaab42 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 11:58:16 +0800 Subject: [PATCH 357/382] =?UTF-8?q?ipaylinks=E9=80=80=E6=AC=BE=E9=80=9A?= =?UTF-8?q?=E7=9F=A5unsend?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/note_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/note_model.php b/webht/third_party/pay/models/note_model.php index 37c43624..8f5fc052 100644 --- a/webht/third_party/pay/models/note_model.php +++ b/webht/third_party/pay/models/note_model.php @@ -197,10 +197,10 @@ class Note_model extends CI_Model { -- gai.GAI_SN, -- gaib.GAI_SN, -- COLI.COLI_ID,IPL_payType='pay' and + -- when IPL_payType<>'pay' then 10000 case when (ISNULL(gaib.GAI_SN, 0)+ISNULL(gai.GAI_SN, 0))>0 then 9999 when IPL_payType='pay' and coli.COLI_ID is not null then 99999 - when IPL_payType<>'pay' then 10000 when IPL_sent='closeRecord' then 10000 else 1 end isRecord, @@ -287,7 +287,7 @@ class Note_model extends CI_Model { ) VALUES ( - ?,?,?,?,?,?,?,'send',?,?,? + ?,?,?,?,?,?,?,'unsend',?,?,? ) "; $query = $this->INFO->query($sql, From 5da96c4884ee3c0576790228abe16ce2990c9c03 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Wed, 15 May 2019 14:13:54 +0800 Subject: [PATCH 358/382] =?UTF-8?q?=E4=B8=8A=E7=BA=BF=E5=8F=91=E9=80=81?= =?UTF-8?q?=E9=80=80=E7=A5=A8=E9=82=AE=E4=BB=B6=E7=BB=99=E5=AE=A2=E4=BA=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trainsystem/controllers/returnorders.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index d2903963..749cbd67 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -102,10 +102,10 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'China Train Ticket(s) Cancelation'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.',train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.',email address:'.$toEmail.',phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); echo '{"reason":"退票成功","status":"200"}'; }else{ //退票失败后发送邮件 @@ -117,7 +117,7 @@ class returnorders extends CI_Controller{ $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,'Phoebe@chinahighlights.net',$customer_subject,$customer_body); + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); header("HTTP/1.1 404 Not Found"); echo '{"reason":"退票失败","status":"404"}'; } From dea7dd8f30b553e29c8a3211a78436eb422030cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B0=B9=E8=AF=9A=E8=AF=9A?= <ycc@hainatravel.com> Date: Wed, 15 May 2019 14:15:25 +0800 Subject: [PATCH 359/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=A4=9A=E5=AA=92?= =?UTF-8?q?=E4=BD=93=E4=B8=AD=E5=BF=83=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- media/popselectpicture.php | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/media/popselectpicture.php b/media/popselectpicture.php index 9f476067..a1a4ef5f 100644 --- a/media/popselectpicture.php +++ b/media/popselectpicture.php @@ -106,6 +106,24 @@ function is_remote_ip() return true; } +//CDN分发之后,源站和前端域名不一致在这里修正,否则程序生成的链接是源站的域名 +$base_url=''; +switch ($_SERVER['SERVER_NAME']){ + case 'origin-ct.mycht.cn': + $base_url='https://ct.mycht.cn'; + break; + case 'origin-gm.mycht.cn': + $base_url='https://gm.mycht.cn'; + break; + case 'origin-cht.mycht.cn': + $base_url='https://cht.mycht.cn'; + break; + case 'origin-int.mycht.cn': + $base_url='https://int.mycht.cn'; + break; + default:$base_url='https://'.$_SERVER['HTTP_HOST']; +} + ?> <?php if (isset($_GET['rwidth'])) { @@ -116,7 +134,7 @@ function is_remote_ip() <?php if (isset($_GET['remote']) || is_remote_ip()){ ?> <iframe id="test" frameborder="0" src="http://photo.chtcdn.com:3581/OutputApp/searchpicture.aspx?<?php echo($rwidth);?>webcode=<?php echo $media_site_code; ?>&lgc=<?php echo $_GET['site_lgc'];?>&apptype=translate&uname=ycc&upass=ycc&lmisn=1&WebUrl=<?php echo isset($_GET['WebUrl'])?$_GET['WebUrl']:false;?>&redirecturl=http://<?php echo $_SERVER['HTTP_HOST']; ?>/media/transitval.php" > </iframe> <?php }else{ ?> - <iframe id="test" frameborder="0" src="https://video.chtcdn.com/OutputApp/searchpicture.aspx?<?php echo($rwidth);?>webcode=<?php echo $media_site_code; ?>&lgc=<?php echo $_GET['site_lgc'];?>&apptype=infomation&WebUrl=<?php echo isset($_GET['WebUrl'])?$_GET['WebUrl']:false;?>&redirecturl=https://<?php echo $_SERVER['HTTP_HOST']; ?>/media/transitval.php" > </iframe> + <iframe id="test" frameborder="0" src="https://video.chtcdn.com/OutputApp/searchpicture.aspx?<?php echo($rwidth);?>webcode=<?php echo $media_site_code; ?>&lgc=<?php echo $_GET['site_lgc'];?>&apptype=infomation&WebUrl=<?php echo isset($_GET['WebUrl'])?$_GET['WebUrl']:false;?>&redirecturl=<?php echo $base_url; ?>/media/transitval.php" > </iframe> <?php } ?> </body> </html> From bad9e43339af5d90f24fe9514fcded2e32d95480 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 14:49:25 +0800 Subject: [PATCH 360/382] =?UTF-8?q?=E6=B5=8B=E8=AF=95=E9=80=80=E6=AC=BE?= =?UTF-8?q?=E7=9A=84=E8=B4=A2=E5=8A=A1=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/PaymentService.php | 79 +++++++++++++++++++ .../models/Online_payment_account_model.php | 65 +++++++++++++++ 2 files changed, 144 insertions(+) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index bf6180b6..10e9cea0 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -387,5 +387,84 @@ log_message('error','send_notify begin ----'); return; } + /*! + * 发送状态是send-to-finance的记录 + * refund-imported + * @date 2019-05-15 + */ + public function refund_finance_notify() + { + $all_list = $this->account_model->get_refund_imported(); + if (empty($all_list)) { + echo "No refund record."; + return false; + } + $this->load->library('PHPExcel'); + $objPHPExcel = new PHPExcel(); + $objPHPExcel->setActiveSheetIndex(0); + //set width + $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(5); + $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15); // 部门 + $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30); // 团号 + $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(15); // 金额 + $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(15); // 币种 + $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15); // 人民币 + $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20); // 付款人 + $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30); // 邮箱 + $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20); // 交易号 + $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(20); // 时间 + // 对齐 + $objPHPExcel->getActiveSheet()->getStyle('D')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + $objPHPExcel->getActiveSheet()->getStyle('F')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_RIGHT); + // 表标题行 + $objPHPExcel->getActiveSheet() + ->SetCellValue('A1', '#') + ->SetCellValue('B1', '部门') + ->SetCellValue('C1', '团号') + ->SetCellValue('D1', '金额') + ->SetCellValue('E1', '币种') + ->SetCellValue('F1', '人民币') + ->SetCellValue('G1', '付款人') + ->SetCellValue('H1', '邮箱') + ->SetCellValue('I1', '交易号') + ->SetCellValue('J1', '时间'); + $currency_sum = array(); + bcscale(2); + $rowCount = 2; + foreach ($all_list as $key => $row) { + $objPHPExcel->getActiveSheet() + ->SetCellValue('A'.$rowCount, ($rowCount-1)) + ->SetCellValue('B'.$rowCount, $row['department']) + ->setCellValueExplicit('C'.$rowCount, $row['gri_name'], PHPExcel_Cell_DataType::TYPE_STRING) + ->setCellValueExplicit('D'.$rowCount, number_format($row['amount'], 2, ".", ""),PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('E'.$rowCount, trim($row['currency'])) + ->setCellValueExplicit('F'.$rowCount, $row['amount_CNY'], PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('G'.$rowCount, $row['payer']) + ->SetCellValue('H'.$rowCount, $row['payer_email']) + ->setCellValueExplicit('I'.$rowCount, $row['transaction_id'], PHPExcel_Cell_DataType::TYPE_STRING) + ->SetCellValue('J'.$rowCount, $row['payment_date']); + $rowCount++; + } + $filename = "refund_imported_" . date('Y-m-d_H_i_s'); + $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); + $objWriter->save(FCPATH . "download_statement/refund/" . $filename . ".xls"); + if (file_exists(FCPATH . "download_statement/refund/" . $filename . ".xls")) { + // 保存成功:更新标记,邮件 + foreach ($all_list as $ka => $va) { + // $this->account_model->update_send_fiance($va['note_sn'], $va['payment_type']); + } + $fromName = 'refund imported'; + $fromEmail = ''; + $toName = 'lyt'; + $toEmail = 'lyt@hainatravel.com'; + $subject = $filename; + $body = "https://www.mycht.cn/download_statement/refund/" . $filename . ".xls"; + $M_AddTime = date('Y-m-d_H_i_s'); + $M_State = 0; + $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, 0, $M_State, $M_AddTime, 'refund imported', 'refund imported'); + } + return false; + } + } diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index 39e5c6a6..d3fb765c 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -341,5 +341,70 @@ class Online_payment_account_model extends CI_Model { return $this->HT->query($sql, $gri_sn)->num_rows() > 0; } + /*! + * 查询标记为需要发送财务的退款记录send-to-finance + * TODO 异步通知合并 + * @date 2019-05-15 + */ + public function get_refund_imported() + { + $ret = array(); + $paypal_sql = "SELECT 'paypal' as 'payment_type', pn_sn note_sn, pn_txn_id transaction_id, + (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN + where OPI_SN=ISNULL(coli.COLI_OPI_ID, bcoli.COLI_OPI_ID)) as department, + (select GRI_Name from GRoupInfo where gri_sn=ISNULL(coli.COLI_GRI_SN,bcoli.COLI_GRI_SN)) as gri_name, + pn.pn_payment_date payment_date, + pn.pn_mc_gross amount,pn_mc_currency currency, + isnull(gai.GAI_SSJE,bgai.GAI_SSJE) amount_CNY, + pn_payer payer,pn_payer_email payer_email + from paypal_note pn + left join GroupAccountInfo gai on gai.GAI_AccreditNo=pn.pn_txn_id + left join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN + left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=pn.pn_txn_id + left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN + where pn_send='send-to-finance' "; + $ret = $paypal_list = $this->HT->query($paypal_sql)->result_array(); + $ipaylinks_sql = "SELECT 'ipaylinks' as 'payment_type', IPL_sn note_sn,IPL_dealId transaction_id, + (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN + where OPI_SN=ISNULL(coli.COLI_OPI_ID, bcoli.COLI_OPI_ID)) as department, + (select GRI_Name from GRoupInfo where gri_sn=ISNULL(coli.COLI_GRI_SN,bcoli.COLI_GRI_SN)) as gri_name, + pn.IPL_completeTime payment_date, + pn.IPL_orderAmount amount, + isnull(IPL_currencyCode,isnull(gai.GAI_SQJECurrency,bgai.GAI_SQJECurrency)) currency, + isnull(gai.GAI_SSJE,bgai.GAI_SSJE) amount_CNY, + isnull(IPL_payerName,isnull(gai.GAI_CusName,bgai.GAI_CusName)) payer, + isnull(IPL_payerEmail,ISNULL(gai.gai_cusEmail,bgai.gai_cusemail)) payer_email + from InfoManager.dbo.IPayLinksLog pn + left join GroupAccountInfo gai on gai.GAI_AccreditNo=pn.IPL_dealId + left join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN + left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=pn.IPL_dealId + left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN + where IPL_sent='send-to-finance' "; + $ipaylinks_list = $this->HT->query($ipaylinks_sql)->result_array(); + if ( ! empty($ipaylinks_list)) { + $ret = array_merge($paypal_list, $ipaylinks_list); + } + return $ret; + } + + public function update_send_fiance($note_sn, $payment_type) + { + $sql = ""; + switch ($payment_type) { + case 'paypal': + $sql = " UPDATE Tourmanager.dbo.paypal_note SET pn_send = 'send-finance' WHERE pn_sn = ? "; + break; + case 'ipaylinks': + $sql = " UPDATE InfoManager.dbo.IPayLinksLog SET IPL_sent = 'send-finance' WHERE IPL_sn = ? "; + break; + + default: + # code... + break; + } + if ($sql==="") {return false;} + return $this->HT->query($sql, $note_sn); + } + } From 2512a1df76611ca9cd71470f9069b497aac06f6b Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 15:04:39 +0800 Subject: [PATCH 361/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E7=9A=84=E8=B4=A2?= =?UTF-8?q?=E5=8A=A1=E9=82=AE=E4=BB=B6=E9=80=9A=E7=9F=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/pay/controllers/PaymentService.php | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index 10e9cea0..76800b78 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -445,21 +445,22 @@ log_message('error','send_notify begin ----'); ->SetCellValue('J'.$rowCount, $row['payment_date']); $rowCount++; } - $filename = "refund_imported_" . date('Y-m-d_H_i_s'); + $time_set = date('Y-m-d_H_i_s') + $filename = "refund_imported_" . $time_set; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save(FCPATH . "download_statement/refund/" . $filename . ".xls"); if (file_exists(FCPATH . "download_statement/refund/" . $filename . ".xls")) { // 保存成功:更新标记,邮件 foreach ($all_list as $ka => $va) { - // $this->account_model->update_send_fiance($va['note_sn'], $va['payment_type']); + $this->account_model->update_send_fiance($va['note_sn'], $va['payment_type']); } $fromName = 'refund imported'; $fromEmail = ''; - $toName = 'lyt'; - $toEmail = 'lyt@hainatravel.com'; + $toName = 'fgy'; + $toEmail = 'fgy@hainatravel.com'; $subject = $filename; - $body = "https://www.mycht.cn/download_statement/refund/" . $filename . ".xls"; - $M_AddTime = date('Y-m-d_H_i_s'); + $body = "导入账单后有退款, 已汇总到文件. <br>文件生成日期:" date("Y-m-d H:i") ". <br>下载链接: https://www.mycht.cn/download_statement/refund/" . $filename . ".xls"; + $M_AddTime = $time_set; $M_State = 0; $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, 0, $M_State, $M_AddTime, 'refund imported', 'refund imported'); } From 17ee96e325dc19e0458f5d1d68cdfa8b8c132328 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 16:23:30 +0800 Subject: [PATCH 362/382] =?UTF-8?q?=E9=80=80=E6=AC=BE=E7=9A=84=E8=B4=A2?= =?UTF-8?q?=E5=8A=A1=E9=80=9A=E7=9F=A5=E5=A2=9E=E5=8A=A0alipay?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../models/Online_payment_account_model.php | 26 ++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index d3fb765c..b6f9b1c7 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -381,9 +381,26 @@ class Online_payment_account_model extends CI_Model { left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN where IPL_sent='send-to-finance' "; $ipaylinks_list = $this->HT->query($ipaylinks_sql)->result_array(); - if ( ! empty($ipaylinks_list)) { - $ret = array_merge($paypal_list, $ipaylinks_list); - } + empty($ipaylinks_list) ? $ipaylinks_list=array() : false; + $alipay_sql = "SELECT 'alipay' as 'payment_type', ALI_sn note_sn,ALI_dealId transaction_id, + (select DEI_DepartmentName from OperatorInfo inner join DepartmentInfo on OPI_DEI_SN=DEI_SN + where OPI_SN=ISNULL(coli.COLI_OPI_ID, bcoli.COLI_OPI_ID)) as department, + (select GRI_Name from GRoupInfo where gri_sn=ISNULL(coli.COLI_GRI_SN,bcoli.COLI_GRI_SN)) as gri_name, + pn.ALI_completeTime payment_date, + pn.ALI_orderAmount amount, + isnull(ALI_currencyCode,isnull(gai.GAI_SQJECurrency,bgai.GAI_SQJECurrency)) currency, + isnull(gai.GAI_SSJE,bgai.GAI_SSJE) amount_CNY, + isnull(ALI_payerName,isnull(gai.GAI_CusName,bgai.GAI_CusName)) payer, + isnull(ALI_payerEmail,ISNULL(gai.gai_cusEmail,bgai.gai_cusemail)) payer_email + from InfoManager.dbo.AlipayLog pn + left join GroupAccountInfo gai on gai.GAI_AccreditNo=pn.ALI_dealId + left join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN + left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=pn.ALI_dealId + left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN + where ALI_sent='send-to-finance' "; + $alipay_list = $this->HT->query($alipay_sql)->result_array(); + empty($alipay_list) ? $alipay_list=array() : false; + $ret = array_merge($paypal_list, $ipaylinks_list, $alipay_list); return $ret; } @@ -397,6 +414,9 @@ class Online_payment_account_model extends CI_Model { case 'ipaylinks': $sql = " UPDATE InfoManager.dbo.IPayLinksLog SET IPL_sent = 'send-finance' WHERE IPL_sn = ? "; break; + case 'alipay': + $sql = " UPDATE InfoManager.dbo.AlipayLog SET ALI_sent = 'send-finance' WHERE ALI_sn = ? "; + break; default: # code... From 8b80b8e3e946cc3aab9f3ee82f732c1adc1f8c97 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 16:45:17 +0800 Subject: [PATCH 363/382] =?UTF-8?q?APP=E7=BB=84=E7=9A=84=E6=94=B6=E6=AC=BE?= =?UTF-8?q?=E6=A0=B8=E5=AF=B9=E6=8F=90=E9=86=92,=20=E7=94=A8=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=8F=B7=E5=92=8C=E9=87=91=E9=A2=9D=E5=88=A4=E6=96=AD?= =?UTF-8?q?=20=E4=B8=8D=E8=80=83=E8=99=91=E8=AE=A2=E5=8D=95=E5=A4=9A?= =?UTF-8?q?=E4=B8=AA=E6=94=B6=E6=AC=BE=E7=9A=84=E6=83=85=E5=86=B5=20?= =?UTF-8?q?=E5=A6=82=E6=9E=9C=E6=94=B6=E6=AC=BE=E8=AE=B0=E5=BD=95=E6=98=AF?= =?UTF-8?q?0=E6=9D=A1,=E5=88=99=E9=9C=80=E8=A6=81=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/paypal/controllers/index.php | 36 ++++++++++--------- .../paypal/models/paypal_model.php | 6 ++-- 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index ac142a6b..1982d8d0 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -785,21 +785,21 @@ class Index extends CI_Controller { && $orderid_info->ordertype == 'A' && strpos($get_order_no, 'China Train Booking') !== false) { // APP 组的China Train Booking-开头的订单号 // 发送邮件提醒外联核对收款金额, 不写入收款记录 - $this->process_notify_APP($item, $orderid_info); - continue; + $if_empty_gai = $this->process_notify_APP($item, $orderid_info); + if($if_empty_gai !== true) { continue }; // 收款记录为空, 需要补录 } //检测是否是APP订单,默认不处理 // && $item->pn_payment_status !== 'Refunded' - if ( - ( (strpos($item->pn_memo, 'China Train Booking') !== false) - || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) - ) - && empty($pn_txn_id) - ) { //APP自动出票的订单不需要处理 - $this->Note_model->update_send($item->pn_txn_id, 'send'); - continue; - } + // if ( + // ( (strpos($item->pn_memo, 'China Train Booking') !== false) + // || (strpos($item->pn_memo, 'ChinaTrainBooking') !== false) + // ) + // && empty($pn_txn_id) + // ) { //APP自动出票的订单不需要处理 + // $this->Note_model->update_send($item->pn_txn_id, 'send'); + // continue; + // } //根据订单号查找外联信息 $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); @@ -820,10 +820,10 @@ class Index extends CI_Controller { $this->Note_model->set_invoice($item->pn_txn_id, $orderid_info->orderid . '_' . $orderid_info->ordertype); //检测是否是APP订单,默认不处理 - if ($orderid_info->ordertype == 'A' ) { //APP自动出票的订单不需要处理 - $this->Note_model->update_send($item->pn_txn_id, 'send'); - continue; - } + // if ($orderid_info->ordertype == 'A' ) { //APP自动出票的订单不需要处理 + // $this->Note_model->update_send($item->pn_txn_id, 'send'); + // continue; + // } //添加支付信息入库 //没有分配订单之前先添加付款记录,这个过程可能会执行多次,必须在添加记录前查找是否有数据 @@ -1485,8 +1485,9 @@ class Index extends CI_Controller { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); return false; } + $order_gai_list = $this->Paypal_model->get_money_list($orderid_info->orderid, $item->pn_mc_gross, $item->pn_mc_currency); //添加邮件发送记录 - if ($item->pn_send !== 'send') { + if ($item->pn_send !== 'send' && empty($order_gai_list)) { //给外联发送通知邮件 $fromName = !empty($item->pn_payer) ? $item->pn_payer : ''; $fromEmail = !empty($item->pn_payer_email) ? $item->pn_payer_email : ''; @@ -1502,7 +1503,8 @@ class Index extends CI_Controller { //添加邮件发送记录 end $this->Note_model->update_send($item->pn_txn_id, 'send'); } - return false; + $order_gai = $this->Paypal_model->get_money_list($orderid_info->orderid); + return empty($order_gai); } } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index a005ba0d..167e2c68 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -87,10 +87,12 @@ class Paypal_model extends CI_Model { } //获取收款记录(商务订单) - public function get_money_list($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency) { + public function get_money_list($GAI_COLI_ID, $GAI_SQJE=null, $GAI_SQJECurrency=null) { + $je_sql = $GAI_SQJE===null ? " " : " and GAI_SQJE=? "; + $currency_sql = $GAI_SQJECurrency===null ? " " : " and GAI_SQJECurrency=? "; $sql = "SELECT GAI_SN,GAI_CusEmail,GAI_Memo FROM BIZ_GroupAccountInfo bgai - WHERE bgai.GAI_COLI_ID = ? and GAI_SQJE=? and GAI_SQJECurrency=? + WHERE bgai.GAI_COLI_ID = ? $je_sql $currency_sql ORDER BY bgai.GAI_SN ASC"; $query = $this->HT->query($sql, array($GAI_COLI_ID, $GAI_SQJE, $GAI_SQJECurrency)); $result = $query->result(); From 686d94b2873f36b31d5068fc9c34f1dbe5d8ed34 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 16:46:16 +0800 Subject: [PATCH 364/382] =?UTF-8?q?=E4=BB=A3=E7=A0=81bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 1982d8d0..f4ad53f5 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -786,7 +786,7 @@ class Index extends CI_Controller { // APP 组的China Train Booking-开头的订单号 // 发送邮件提醒外联核对收款金额, 不写入收款记录 $if_empty_gai = $this->process_notify_APP($item, $orderid_info); - if($if_empty_gai !== true) { continue }; // 收款记录为空, 需要补录 + if($if_empty_gai !== true) { continue; } // 收款记录为空, 需要补录 } //检测是否是APP订单,默认不处理 From 409f889cbcfe05ed6a0b6fc67dfe2e1eee2c5dd2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Wed, 15 May 2019 17:24:15 +0800 Subject: [PATCH 365/382] =?UTF-8?q?=E4=BF=AE=E6=AD=A3APP=E7=9A=84=E8=AE=A2?= =?UTF-8?q?=E5=8D=95=E5=8F=B7=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 4 +++- webht/third_party/pay/helpers/payment_helper.php | 4 +++- webht/third_party/paypal/controllers/index.php | 5 +++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 1c0f04a2..b0da3978 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -783,8 +783,10 @@ class IPayLinksService extends CI_Controller //APP订单处理,如标题China Train Booking-160617462 if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) { $note_invoice_string = explode('-', $note_invoice_string); - if (isset($note_invoice_string[1])) { + if (isset($note_invoice_string[1]) && $note_invoice_string[1] !== "ChinaTrainBooking") { $note_invoice_string = trim($note_invoice_string[1]); + } elseif (isset($note_invoice_string[0]) && $note_invoice_string[0] !== "China Train Booking") { + $note_invoice_string = trim($note_invoice_string[0]); } return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单,不需要处理交易记录和通知 } diff --git a/webht/third_party/pay/helpers/payment_helper.php b/webht/third_party/pay/helpers/payment_helper.php index 80dc5010..15339534 100644 --- a/webht/third_party/pay/helpers/payment_helper.php +++ b/webht/third_party/pay/helpers/payment_helper.php @@ -106,8 +106,10 @@ function analysis_orderid($note_invoice_string) { //APP订单处理,如标题China Train Booking-160617462 if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) { $note_invoice_string = explode('-', $note_invoice_string); - if (isset($note_invoice_string[1])) { + if (isset($note_invoice_string[1]) && $note_invoice_string[1] !== "ChinaTrainBooking") { $note_invoice_string = trim($note_invoice_string[1]); + } elseif (isset($note_invoice_string[0]) && $note_invoice_string[0] !== "China Train Booking") { + $note_invoice_string = trim($note_invoice_string[0]); } return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单,不需要处理交易记录和通知 } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index f4ad53f5..d9601bc7 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -623,8 +623,10 @@ class Index extends CI_Controller { //APP订单处理,如标题China Train Booking-160617462 if ((strpos($note_invoice_string, 'China Train Booking') !== false) || (strpos($note_invoice_string, 'ChinaTrainBooking') !== false)) { $note_invoice_string = explode('-', $note_invoice_string); - if (isset($note_invoice_string[1])) { + if (isset($note_invoice_string[1]) && $note_invoice_string[1] !== "ChinaTrainBooking") { $note_invoice_string = trim($note_invoice_string[1]); + } elseif (isset($note_invoice_string[0]) && $note_invoice_string[0] !== "China Train Booking") { + $note_invoice_string = trim($note_invoice_string[0]); } return json_encode(array('orderid' => $note_invoice_string, 'ordertype' => 'A')); //APP订单,不需要处理交易记录和通知 } @@ -927,7 +929,6 @@ class Index extends CI_Controller { //根据订单号查找外联信息 $advisor_info = $this->Paypal_model->get_order($orderid_info->orderid, false, $orderid_info->ordertype, $handpick); - //查不到订单信息 if (empty($advisor_info)) { $this->Note_model->update_send($item->pn_txn_id, 'sendfail'); From 236c318a95b9fc81f756de21c1fe06b9c05915c4 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 09:22:59 +0800 Subject: [PATCH 366/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=9A=84=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95,=20=E7=BE=8E=E9=87=91=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E5=86=99=E5=85=A5GAI=5FMoney,=20=E6=89=80=E6=9C=89?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../pay/controllers/iPayLinksService.php | 2 ++ .../pay/models/IPayLinks_model.php | 21 ++++++++++++++++--- .../third_party/paypal/controllers/index.php | 17 ++++++++++++++- .../paypal/models/paypal_model.php | 20 +++++++++++++++--- 4 files changed, 53 insertions(+), 7 deletions(-) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index b0da3978..41add687 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -445,6 +445,7 @@ class IPayLinksService extends CI_Controller $currencyCode = str_replace("CNY", "RMB", trim(mb_strtoupper($item->IPL_currencyCode))); $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + $USD_amount = $this->IPayLinks_model->get_USD($item->IPL_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->IPL_dealId; @@ -483,6 +484,7 @@ class IPayLinksService extends CI_Controller $item->IPL_orderAmount, $item->IPL_completeTime, $currencyCode, + $USD_amount, $ssje, $item->IPL_completeTime, $item->IPL_completeTime, diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 6b9f4a64..0e1562b3 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -181,7 +181,7 @@ class IPayLinks_model extends CI_Model { } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -197,6 +197,7 @@ class IPayLinks_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_Money ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate @@ -207,8 +208,8 @@ class IPayLinks_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15018,?,?,?,?,?,?,?,N?,N?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15018,?,?,?,?,?,?,?,?,N?,N?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -459,4 +460,18 @@ class IPayLinks_model extends CI_Model { )"; return $this->HT->query($sql, array($order_id))->num_rows() > 0; } + + /*! + * 调用数据库函数,转换为美金 + */ + public function get_USD($amount, $currency='RMB') + { + $sql = "SELECT dbo.ConvertCurrencyToCurrency(?,?,?,?) as ssje"; + $query = $this->HT->query($sql, array(1, mb_strtolower($currency), 'usd', $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } } diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index d9601bc7..77ec94f2 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -832,6 +832,7 @@ class Index extends CI_Controller { if (!empty($orderid_info)) { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '交易号(自动录入):' . $item->pn_txn_id; @@ -849,7 +850,21 @@ class Index extends CI_Controller { $this->Paypal_model->update_biz_coli_state($GAI_COLI_SN, 13); $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'BS13'); } - $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, '', $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->add_account_info( + $GAI_COLI_SN, + $advisor_info->COLI_ID, + $item->pn_mc_gross, + $item->pn_payment_date, + mb_strtoupper($item->pn_mc_currency), + $USD_amount, + $ssje, + $item->pn_payment_date, + $item->pn_payment_date, + $item->pn_payment_date, + '', + $item->pn_payer_email, + $item->pn_txn_id, + $ht_memo); // 更新订单主表付款方式,防止没访问thankyou-train.asp $this->Paypal_model->update_paymanner($GAI_COLI_SN, '15010'); } diff --git a/webht/third_party/paypal/models/paypal_model.php b/webht/third_party/paypal/models/paypal_model.php index 167e2c68..ff8e6de2 100644 --- a/webht/third_party/paypal/models/paypal_model.php +++ b/webht/third_party/paypal/models/paypal_model.php @@ -188,7 +188,7 @@ class Paypal_model extends CI_Model { } //添加收款记录(商务订单) - public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { + public function add_account_info($GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo) { //先判断是否有这条数据 $sql = " @@ -204,6 +204,7 @@ class Paypal_model extends CI_Model { ,GAI_SQJE ,GAI_SQDate ,GAI_SQJECurrency + ,GAI_Money ,GAI_SSJE ,GAI_SSDate ,GAI_AccountDate @@ -214,8 +215,8 @@ class Paypal_model extends CI_Model { ,GAI_Memo ,GAI_State ,DeleteFlag - ) VALUES (?,?,15002,?,?,?,?,?,?,?,?,?,?,?,0,0)"; - $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); + ) VALUES (?,?,15002,?,?,?,?,?,?,?,?,?,?,?,?,0,0)"; + $query = $this->HT->query($sql, array($GAI_AccreditNo, $GAI_COLI_SN, $GAI_COLI_ID, $GAI_SQJE, $GAI_SQDate, $GAI_SQJECurrency, $GAI_Money, $GAI_SSJE, $GAI_SSDate, $GAI_AccountDate, $GAI_SubmitDate, $GAI_CusName, $GAI_CusEmail, $GAI_AccreditNo, $GAI_Memo)); $insertid = $this->HT->last_id('BIZ_GroupAccountInfo'); return $query; } @@ -657,6 +658,19 @@ class Paypal_model extends CI_Model { } } + /*! + * 调用数据库函数,转换为美金 + */ + public function get_USD($amount, $currency='RMB') + { + $sql = "SELECT dbo.ConvertCurrencyToCurrency(?,?,?,?) as ssje"; + $query = $this->HT->query($sql, array(1, mb_strtolower($currency), 'usd', $amount)); + $result = $query->result(); + if ( ! empty($result)) { + return $result[0]->ssje; + } + return 0; + } /*! * 查询财务系统中是否已导入该团的账单数据 From 9c292205223d9a7c143294868f565e05641a34d1 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 10:21:23 +0800 Subject: [PATCH 367/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=9A=84=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95,=20=E7=BE=8E=E9=87=91=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E5=86=99=E5=85=A5GAI=5FMoney,=20=E6=89=80=E6=9C=89?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/iPayLinksService.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/pay/controllers/iPayLinksService.php b/webht/third_party/pay/controllers/iPayLinksService.php index 41add687..1231650d 100644 --- a/webht/third_party/pay/controllers/iPayLinksService.php +++ b/webht/third_party/pay/controllers/iPayLinksService.php @@ -630,6 +630,7 @@ class IPayLinksService extends CI_Controller $currencyCode = mb_strtoupper(trim($currencyCode)); $ssje = $this->IPayLinks_model->get_ssje($item->IPL_orderAmount, $currencyCode, '15018'); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + $USD_amount = $this->IPayLinks_model->get_USD($item->IPL_orderAmount, $currencyCode); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '(自动录入)退款号:' . $item->IPL_dealId . "\n. "; @@ -662,6 +663,7 @@ class IPayLinksService extends CI_Controller $item->IPL_orderAmount, $item->IPL_completeTime, $currencyCode, + $USD_amount, $ssje, $item->IPL_completeTime, $item->IPL_completeTime, From 2b3eee966ff74ecfc0dd28cadb6ad5d7d2677bb3 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 10:24:52 +0800 Subject: [PATCH 368/382] =?UTF-8?q?=E5=95=86=E6=97=85=E7=9A=84=E6=94=B6?= =?UTF-8?q?=E6=AC=BE=E8=AE=B0=E5=BD=95,=20=E7=BE=8E=E9=87=91=E9=87=91?= =?UTF-8?q?=E9=A2=9D=E5=86=99=E5=85=A5GAI=5FMoney,=20=E6=89=80=E6=9C=89?= =?UTF-8?q?=E6=94=AF=E4=BB=98=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 77ec94f2..6bcc96a8 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -958,6 +958,7 @@ class Index extends CI_Controller { if (!empty($orderid_info)) { $ssje = $this->Paypal_model->get_ssje($item->pn_mc_gross, '15002', mb_strtoupper($item->pn_mc_currency)); $ssje = $old_ssje===NULL ? $ssje : $old_ssje; + $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency); //更新还没有填的客邮和交易号de收款记录(商务订单) if (isset($advisor_info->order_type) && $advisor_info->order_type == 0) { $ht_memo = '(自动录入)退款号:' . $item->pn_txn_id . "\n. "; @@ -971,7 +972,7 @@ class Index extends CI_Controller { if (false == $this->Paypal_model->if_biz_gai_exists($item->pn_txn_id) ) { $this->Paypal_model->insert_biz_order_log($GAI_COLI_SN, 'Refunded'); } - $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); + $this->Paypal_model->add_account_info($GAI_COLI_SN, $advisor_info->COLI_ID, $item->pn_mc_gross, $item->pn_payment_date, mb_strtoupper($item->pn_mc_currency), $USD_amount, $ssje, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payment_date, $item->pn_payer, $item->pn_payer_email, $item->pn_txn_id, $ht_memo); } } //更新还没有填的客邮和交易号的收款记录(传统订单) From 5c852e0ae2249988999966c626839691f8f99e68 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 11:38:44 +0800 Subject: [PATCH 369/382] =?UTF-8?q?alipay=20=E7=9A=84=E9=80=80=E6=AC=BE?= =?UTF-8?q?=E5=8F=B7=E8=B6=85=E9=95=BF,=E6=88=AA=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Online_payment_account_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index b6f9b1c7..ac51e93a 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -393,9 +393,9 @@ class Online_payment_account_model extends CI_Model { isnull(ALI_payerName,isnull(gai.GAI_CusName,bgai.GAI_CusName)) payer, isnull(ALI_payerEmail,ISNULL(gai.gai_cusEmail,bgai.gai_cusemail)) payer_email from InfoManager.dbo.AlipayLog pn - left join GroupAccountInfo gai on gai.GAI_AccreditNo=pn.ALI_dealId + left join GroupAccountInfo gai on gai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,30) left join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN - left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=pn.ALI_dealId + left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,30) left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN where ALI_sent='send-to-finance' "; $alipay_list = $this->HT->query($alipay_sql)->result_array(); From 59ec3abc0754ee6365963117e2340bf1229cbbb2 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 11:47:23 +0800 Subject: [PATCH 370/382] =?UTF-8?q?alipay=20=E7=9A=84=E9=80=80=E6=AC=BE?= =?UTF-8?q?=E5=8F=B7=E8=B6=85=E9=95=BF,=E6=88=AA=E6=96=AD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/Online_payment_account_model.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/Online_payment_account_model.php b/webht/third_party/pay/models/Online_payment_account_model.php index ac51e93a..6ff43412 100644 --- a/webht/third_party/pay/models/Online_payment_account_model.php +++ b/webht/third_party/pay/models/Online_payment_account_model.php @@ -393,9 +393,9 @@ class Online_payment_account_model extends CI_Model { isnull(ALI_payerName,isnull(gai.GAI_CusName,bgai.GAI_CusName)) payer, isnull(ALI_payerEmail,ISNULL(gai.gai_cusEmail,bgai.gai_cusemail)) payer_email from InfoManager.dbo.AlipayLog pn - left join GroupAccountInfo gai on gai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,30) + left join GroupAccountInfo gai on gai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,31) left join ConfirmLineInfo coli on coli.COLI_SN=gai.GAI_COLI_SN - left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,30) + left join BIZ_GroupAccountInfo bgai on bgai.GAI_AccreditNo=SUBSTRING(pn.ALI_dealId,0,31) left join BIZ_ConfirmLineInfo bcoli on bcoli.COLI_SN=bgai.GAI_COLI_SN where ALI_sent='send-to-finance' "; $alipay_list = $this->HT->query($alipay_sql)->result_array(); From 61bc4f25b7009af506f4031713f91fbc03a91b44 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 16:45:11 +0800 Subject: [PATCH 371/382] =?UTF-8?q?Trippest=E7=9A=84=E5=BD=95=E5=85=A5?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0money=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 6bcc96a8..1fd3f0f5 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1081,6 +1081,7 @@ class Index extends CI_Controller { } $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; + $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency); if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) { if ( ! empty($ht_tp_order)) { $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); @@ -1110,6 +1111,7 @@ class Index extends CI_Controller { $paypal_msg->pn_mc_gross, $paypal_msg->pn_payment_date, mb_strtoupper($paypal_msg->pn_mc_currency), + $USD_amount, $ssje, $paypal_msg->pn_payment_date, $paypal_msg->pn_payment_date, From 0f4ff86099a56cb9e0312ad0004cbf85c0a8fc3c Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 16:46:42 +0800 Subject: [PATCH 372/382] =?UTF-8?q?Trippest=E7=9A=84=E5=BD=95=E5=85=A5?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0money=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 1fd3f0f5..196519f2 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -1081,7 +1081,7 @@ class Index extends CI_Controller { } $ssje = $this->Paypal_model->get_ssje($paypal_msg->pn_mc_gross, '15002', mb_strtoupper($paypal_msg->pn_mc_currency)); $ht_memo = '交易号(自动录入):' . $paypal_msg->pn_txn_id; - $USD_amount = $this->Paypal_model->get_USD($item->pn_mc_gross, $item->pn_mc_currency); + $USD_amount = $this->Paypal_model->get_USD($paypal_msg->pn_mc_gross, $paypal_msg->pn_mc_currency); if (false == $this->Paypal_model->if_biz_gai_exists($paypal_msg->pn_txn_id) ) { if ( ! empty($ht_tp_order)) { $this->Paypal_model->update_biz_coli_state($ht_tp_order->COLI_SN, 13); From 396304d313b00c9b18a8b11bb284739463a7b58a Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 17:12:05 +0800 Subject: [PATCH 373/382] =?UTF-8?q?=E4=BB=A3=E7=A0=81bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/PaymentService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index 76800b78..c617d755 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -445,7 +445,7 @@ log_message('error','send_notify begin ----'); ->SetCellValue('J'.$rowCount, $row['payment_date']); $rowCount++; } - $time_set = date('Y-m-d_H_i_s') + $time_set = date('Y-m-d_H_i_s'); $filename = "refund_imported_" . $time_set; $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save(FCPATH . "download_statement/refund/" . $filename . ".xls"); From 0acf159b10d9315622d191ccea09f3aca3f61f94 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Thu, 16 May 2019 17:13:09 +0800 Subject: [PATCH 374/382] =?UTF-8?q?=E4=BB=A3=E7=A0=81bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/controllers/PaymentService.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/pay/controllers/PaymentService.php b/webht/third_party/pay/controllers/PaymentService.php index c617d755..aecb8887 100644 --- a/webht/third_party/pay/controllers/PaymentService.php +++ b/webht/third_party/pay/controllers/PaymentService.php @@ -459,7 +459,7 @@ log_message('error','send_notify begin ----'); $toName = 'fgy'; $toEmail = 'fgy@hainatravel.com'; $subject = $filename; - $body = "导入账单后有退款, 已汇总到文件. <br>文件生成日期:" date("Y-m-d H:i") ". <br>下载链接: https://www.mycht.cn/download_statement/refund/" . $filename . ".xls"; + $body = "导入账单后有退款, 已汇总到文件. <br>文件生成日期:". date("Y-m-d H:i"). ". <br>下载链接: https://www.mycht.cn/download_statement/refund/" . $filename . ".xls"; $M_AddTime = $time_set; $M_State = 0; $this->account_model->save_automail($fromName, $fromEmail, $toName, $toEmail, $subject, $body, 0, $M_State, $M_AddTime, 'refund imported', 'refund imported'); From 94e2942154036762f9a3fdef1f2acbd1bd215273 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 May 2019 10:28:08 +0800 Subject: [PATCH 375/382] =?UTF-8?q?=E4=BC=A0=E7=BB=9F=E5=9B=A2,=E6=B2=A1?= =?UTF-8?q?=E6=9C=89=E8=81=94=E7=B3=BB=E4=BA=BA'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/pay/models/IPayLinks_model.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webht/third_party/pay/models/IPayLinks_model.php b/webht/third_party/pay/models/IPayLinks_model.php index 0e1562b3..5d3025ce 100644 --- a/webht/third_party/pay/models/IPayLinks_model.php +++ b/webht/third_party/pay/models/IPayLinks_model.php @@ -439,8 +439,9 @@ class IPayLinks_model extends CI_Model { $sql = "SELECT mei.MEI_FirstName+' '+isnull(mei.MEI_MiddleName,'')+' '+isnull(mei.MEI_LastName,'') fullname, mei.MEI_MailList email FROM MEmberInfo mei - INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN and cul.CUL_IsLinkMan=1 - WHERE CUL_COLI_SN=? "; + INNER JOIN CUstomerList cul on mei.MEI_SN=cul.CUL_CUI_SN --and cul.CUL_IsLinkMan=1 + WHERE CUL_COLI_SN=? and isnull(mei.MEI_MailList,'')<>'' + order by cul.CUL_IsLinkMan desc"; return $this->HT->query($sql, $COLI_SN)->row(); } else { $sql = "SELECT GUT_FirstName+' '+GUT_LastName fullname,GUT_Email email from BIZ_GUEST g From 0f1deb1ef0a280cb1ed52f57a5b09f20d91b5899 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 May 2019 13:38:21 +0800 Subject: [PATCH 376/382] =?UTF-8?q?Trippest=E8=87=AA=E5=8A=A8=E7=94=9F?= =?UTF-8?q?=E6=88=90=E8=B4=A6=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trippestOrderSync/controllers/TulanduoApi.php | 5 +++++ .../trippestOrderSync/models/orders_model.php | 13 +++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php index 4c4384e0..ba83d1d4 100644 --- a/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php +++ b/webht/third_party/trippestOrderSync/controllers/TulanduoApi.php @@ -697,6 +697,11 @@ class TulanduoApi extends CI_Controller $output_text = "Got order operations from TuLanDuo:" . $detail_jsonResp->orderDetail->orderId . ". " . $coli_id; log_message('error', $output_text); echo $output_text; + if (strval($order->isHistory) === '1') { + require_once('order_finance.php'); + $vendor_class = new Order_finance(); + $vendor_class->single_order_report($coli_sn); + } return; } diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e241900c..e32fbaf3 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -176,7 +176,12 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo_finance() { // return array(); // 历史数据已获取完毕 - $to_update_cost_date = date("Y-m-d", strtotime("-45 days")); + // $to_update_cost_date = date("Y-m-d", strtotime("-45 days")); + $to_update_month_begin = date('Y-m-01', strtotime("-4 months", strtotime(date("Y-m-d")))); + $to_update_month_end = date('Y-m-01', strtotime("-3 months", strtotime(date("Y-m-d")))); + $end_d = strtotime($to_update_month_end)-1; + $to_update_month_end = date("Y-m-d 23:59:59", $end_d); + $set_time = date("Y-m-d 00:00:00", strtotime("+50 days",$end_d)); $last_update_time = date("Y-m-d 00:00:00"); $sql = " SELECT top 1 coli.COLI_ID, coli.COLI_SN, coli.COLI_GRI_SN, cold.COLD_SN, coli.COLI_OrderDetailText, coli.COLI_Memo,coli.COLI_State,coli.COLI_OPI_ID, cold.COLD_PlanVEI_SN, cold.COLD_MemoText, gci.*,'1' as 'isHistory' @@ -189,15 +194,15 @@ class Orders_model extends CI_Model { where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') -- 45天前的订单 - and gci.gci_leaveDate = '$to_update_cost_date' + --and gci.gci_leaveDate = '$to_update_cost_date' -- 今天更新一次 and gci.GCI_createTime < '$last_update_time' -- 已生成账单的不再自动同步 and NOT exists ( select 1 from report_order where ordernumber=COLI_ID and orderstats=1 ) --- and GCI_travelDate between '2018-08-01' and '2018-08-31 23:59:59' --- and gci.GCI_createTime < '2018-12-06 14:00:00' + and GCI_travelDate between '$to_update_month_begin' and '$to_update_month_end' + and gci.GCI_createTime < '$set_time' and GCI_combineNo not like '%取消%' "; $sql .= " ORDER BY isHistory ASC,GCI_createTime ASC "; From 8f517e548c8b47c2f4ae1f4f99188ae6ccc13f76 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Fri, 17 May 2019 14:49:57 +0800 Subject: [PATCH 377/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=81=AB=E8=BD=A6?= =?UTF-8?q?=E5=87=BA=E7=A5=A8=E4=BA=A7=E7=94=9F=E7=9A=84=E8=AD=A6=E5=91=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/trainsystem/controllers/addorders.php | 1 + .../third_party/trainsystem/controllers/returnorders.php | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/application/third_party/trainsystem/controllers/addorders.php b/application/third_party/trainsystem/controllers/addorders.php index 9de9a291..e4316a86 100644 --- a/application/third_party/trainsystem/controllers/addorders.php +++ b/application/third_party/trainsystem/controllers/addorders.php @@ -13,6 +13,7 @@ class addorders extends CI_Controller{ $this->train_zw = $this->config->item('train_zw'); $this->black_list = $this->config->item('black_list'); $this->isauto = 0; + $this->istanding = 'false'; } public function index(){ diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 749cbd67..82e7aa31 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -114,7 +114,7 @@ class returnorders extends CI_Controller{ $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); //发送邮件给客人 $customer_subject = 'China Train Ticket(s) Cancelation'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); $customer_email = $customer_email[0]->GUT_Email; $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); From 1f33f5ddefeca3de2c3776815bf6616e01eb15a9 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Fri, 17 May 2019 16:14:28 +0800 Subject: [PATCH 378/382] =?UTF-8?q?Trippest=E8=B4=A6=E5=8D=95:=E5=88=A0?= =?UTF-8?q?=E6=8E=8945=E5=A4=A9=E7=9A=84=E6=9F=A5=E8=AF=A2=E6=9D=A1?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/trippestOrderSync/models/orders_model.php | 3 --- 1 file changed, 3 deletions(-) diff --git a/webht/third_party/trippestOrderSync/models/orders_model.php b/webht/third_party/trippestOrderSync/models/orders_model.php index e32fbaf3..54a1c821 100644 --- a/webht/third_party/trippestOrderSync/models/orders_model.php +++ b/webht/third_party/trippestOrderSync/models/orders_model.php @@ -176,7 +176,6 @@ class Orders_model extends CI_Model { public function get_groupCombineInfo_finance() { // return array(); // 历史数据已获取完毕 - // $to_update_cost_date = date("Y-m-d", strtotime("-45 days")); $to_update_month_begin = date('Y-m-01', strtotime("-4 months", strtotime(date("Y-m-d")))); $to_update_month_end = date('Y-m-01', strtotime("-3 months", strtotime(date("Y-m-d")))); $end_d = strtotime($to_update_month_end)-1; @@ -193,8 +192,6 @@ class Orders_model extends CI_Model { LEFT JOIN BIZ_ConfirmLineDetail cold ON cold.COLD_COLI_SN=coli.COLI_SN where GCI_combineNo is not null and GCI_combineNo not in ('cancel','forbidden') - -- 45天前的订单 - --and gci.gci_leaveDate = '$to_update_cost_date' -- 今天更新一次 and gci.GCI_createTime < '$last_update_time' -- 已生成账单的不再自动同步 From 2bd7df0795296c84a75ca588fca0076e4334209b Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 20 May 2019 10:07:59 +0800 Subject: [PATCH 379/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E9=80=80=E7=A5=A8?= =?UTF-8?q?=E9=82=AE=E4=BB=B6=E5=8F=91=E9=80=81=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../trainsystem/controllers/returnorders.php | 33 +++++++++++-------- .../third_party/trainsystem/views/refund.php | 2 +- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/application/third_party/trainsystem/controllers/returnorders.php b/application/third_party/trainsystem/controllers/returnorders.php index 82e7aa31..a4a9b263 100644 --- a/application/third_party/trainsystem/controllers/returnorders.php +++ b/application/third_party/trainsystem/controllers/returnorders.php @@ -10,7 +10,7 @@ class returnorders extends CI_Controller{ $this->load->model("train_system_model"); $this->load->model("Sendmail_model"); $this->load->model('BIZ_train_model'); - + $this->usercenter = 'yes'; } public function index(){ @@ -29,6 +29,8 @@ class returnorders extends CI_Controller{ $passportname = $this->input->get_post('passportname'); //护照号 $passportno = $this->input->get_post('passportno'); + //判断是否为用户中心操作 + $this->usercenter = $this->input->get_post('usercenter'); if(!$ordernumber || !$passportname || !$passportno){ header("HTTP/1.1 404 Not Found"); @@ -72,7 +74,6 @@ class returnorders extends CI_Controller{ $ticket_no = $items->ticket_no; } } - //发起退票 $post_data1 = array( "key"=>JUHE_TRAIN_API_KEY, @@ -100,24 +101,28 @@ class returnorders extends CI_Controller{ $body = $back_detail_data->result->ordernumber.' 提出退票,乘客:'.$data->tst_realname.', '.$back_detail_data->result->start_time.' '.$back_detail_data->result->checi; //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); - //发送邮件给客人 - $customer_subject = 'China Train Ticket(s) Cancelation'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; - $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); - $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + if($this->usercenter == 'yes'){ + //发送邮件给客人 + $customer_subject = 'China Train Ticket(s) Cancelation'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your tickets (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No. '.$back_detail_data->result->checi.') have been cancelled online successfully. Your travel advisor ('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you with the refund details via email within 24 hours.'; + $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); + $customer_email = $customer_email[0]->GUT_Email; + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + } echo '{"reason":"退票成功","status":"200"}'; }else{ //退票失败后发送邮件 $body = $ticket_data->ts_ordernumber.'退票失败'; //发送邮件给外联 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); - //发送邮件给客人 - $customer_subject = 'China Train Ticket(s) Cancelation'; - $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; - $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); - $customer_email = $customer_email[0]->GUT_Email; - $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + if($this->usercenter == 'yes'){ + //发送邮件给客人 + $customer_subject = 'China Train Ticket(s) Cancelation'; + $customer_body = '<p>Dear '.$data->tst_realname.',</p><p>Your application for online ticket cancellation (ticket number '.$back_detail_data->result->ordernumber.', for name '.$data->tst_realname.', train No.'.$back_detail_data->result->checi.') has failed.Your travel advisor('.$toName.', email address: '.$toEmail.', phone number '.$Mobile.') will contact you via email within 24 hours. Please call us if you need to contact us urgently.</p>'; + $customer_email = $this->BIZ_train_model->get_guest_info($coli_id); + $customer_email = $customer_email[0]->GUT_Email; + $this->Sendmail_model->SendMailToTable($toName,$toEmail,$data->tst_realname,$customer_email,$customer_subject,$customer_body); + } header("HTTP/1.1 404 Not Found"); echo '{"reason":"退票失败","status":"404"}'; } diff --git a/application/third_party/trainsystem/views/refund.php b/application/third_party/trainsystem/views/refund.php index 6eeeac99..2737c70b 100644 --- a/application/third_party/trainsystem/views/refund.php +++ b/application/third_party/trainsystem/views/refund.php @@ -30,7 +30,7 @@ $(function(){ var return_ticket = $(this); name = $(this).attr('name'); passid = $(this).attr('passid'); - url += '&passportname='+name+'&passportno='+passid; + url += '&passportname='+name+'&passportno='+passid+'&usercenter=no'; //console.log(url);return false; $.ajax({ url:url, From 005e62c62b5b7cd4405daab83e8d098f180e33f3 Mon Sep 17 00:00:00 2001 From: cyc <cyc@hainatravel.com> Date: Mon, 20 May 2019 10:27:07 +0800 Subject: [PATCH 380/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=87=BA=E7=A5=A8?= =?UTF-8?q?=E9=82=AE=E4=BB=B6=E5=8F=91=E9=80=81=E8=A7=84=E5=88=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application/third_party/trainsystem/controllers/api.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/application/third_party/trainsystem/controllers/api.php b/application/third_party/trainsystem/controllers/api.php index b4ef1121..c62c3293 100644 --- a/application/third_party/trainsystem/controllers/api.php +++ b/application/third_party/trainsystem/controllers/api.php @@ -87,7 +87,7 @@ class api extends CI_Controller{ //发送邮件给客人 $flag = $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>1,"ts_m_sn"=>$flag)); - }else if($status == '1' && $differtime < 18 && $differtime > 0){ + }else if($status == '1'){ $subject = "The train ticket(s) will be issued manually, Order No $coli_id"; $body = $this->load->view('email_fault',$data,true); $this->send_mail_to_wl("订单:{$coli_id} 出票失败","翰特订单号:{$coli_id};聚合订单号:{$jh_order}",$coli_id); @@ -96,10 +96,6 @@ class api extends CI_Controller{ //测试阶段,将失败邮件发送一份给操作外联。 $this->Sendmail_model->SendMailToTable($fromName,$fromEmail,$toName,$toEmail,$subject,$body); $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>1,"ts_m_sn"=>$flag)); - }else{ - echo $jh_order.'不需要发邮件<br>'; - $this->BIZ_train_model->update_biz_jol(array("ts_ordernumber"=>$jh_order),array("ts_sendmail"=>2)); - $flag = false; } } From 4f2a0869a72abcda9c3f84159a1d19860dbf73bb Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Mon, 20 May 2019 15:35:17 +0800 Subject: [PATCH 381/382] =?UTF-8?q?fixed=20=E6=8B=BC=E5=9B=A2=E4=BA=A7?= =?UTF-8?q?=E5=93=81=E5=90=8D=E4=B8=AD=E6=96=87=E5=AD=97=E7=AC=A6bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../third_party/trippestOrderSync/controllers/order_finance.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webht/third_party/trippestOrderSync/controllers/order_finance.php b/webht/third_party/trippestOrderSync/controllers/order_finance.php index e4c06133..0b37e211 100644 --- a/webht/third_party/trippestOrderSync/controllers/order_finance.php +++ b/webht/third_party/trippestOrderSync/controllers/order_finance.php @@ -190,7 +190,7 @@ class Order_finance extends CI_Controller { $cost_c = array(); $cost_c['ordernumber'] = $cost->coli_id; $cost_c['tourCode'] = mb_substr(implode(',', array_unique(array_map(function($ele){ return $ele->real_code; }, $cost->order_cost))), 0, 50); - $cost_c['tourname'] = substr($cost->pag_name, 0, 200) ; + $cost_c['tourname'] = mb_substr($cost->pag_name, 0, 200) ; $cost_c['tourtime'] = $cost->startdate; $cost_c['tourRSd'] = $cost->order_cost[0]->adult_num; $cost_c['tourRSx'] = $cost->order_cost[0]->child_num; From a2d7979498cbd02dc76481dd2dc258778d492f80 Mon Sep 17 00:00:00 2001 From: lyt <lyt@hainatravel.com> Date: Tue, 21 May 2019 09:55:36 +0800 Subject: [PATCH 382/382] =?UTF-8?q?APP=E7=BB=84=E7=9A=84=E5=90=8E=E7=BC=80?= =?UTF-8?q?A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webht/third_party/paypal/controllers/index.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/webht/third_party/paypal/controllers/index.php b/webht/third_party/paypal/controllers/index.php index 196519f2..b4dfbc2c 100644 --- a/webht/third_party/paypal/controllers/index.php +++ b/webht/third_party/paypal/controllers/index.php @@ -655,6 +655,8 @@ class Index extends CI_Controller { $ordertype = 'T'; } elseif (substr($ordertype_temp, 0, 1) == 'B') { $ordertype = 'B'; + } elseif (substr($ordertype_temp, 0, 1) == 'A') { + $ordertype = 'B'; } } // 2018.05.28 for Trippest, tourMaster的订单号是01开头